Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(ar): extract the AR studio into packages/ar-studio and add a parity test so the package and the app stay in step

nirholas111fc15c75eb
diff --git a/docs/ar-studio.md b/docs/ar-studio.md
index 3fa6034d3..503e3caf6 100644
--- a/docs/ar-studio.md
+++ b/docs/ar-studio.md
@@ -13,7 +13,18 @@ This doc covers what is unique to AR Studio. For the underlying `POST /api/forge
## How it works
-The page ([`pages/ar-studio.html`](../pages/ar-studio.html)) only imports [`src/ar-studio.js`](../src/ar-studio.js) after a WebGL check. Scene math, serialization, and the share hash live in [`src/ar/studio-scene.js`](../src/ar/studio-scene.js); the Colyseus client is [`src/ar/studio-net.js`](../src/ar/studio-net.js); WebXR multi-placement is [`src/ar/multi-place.js`](../src/ar/multi-place.js).
+The page ([`pages/ar-studio.html`](../pages/ar-studio.html)) only imports [`src/ar-studio.js`](../src/ar-studio.js) after a WebGL check. The page code owns the three.ws specifics (the forge, gallery and Objects tray, the HUD, the sign-in-free flows). Everything reusable lives in one place, the [`3d-ar-studio`](https://www.npmjs.com/package/3d-ar-studio) package at [`packages/ar-studio`](../packages/ar-studio), and the page imports it directly from there, so the npm package and the hosted studio can no longer drift:
+
+| Concern | Module (all under `packages/ar-studio/src/studio/`) |
+|---|---|
+| Scene math, serialization, the `#s=` share hash, share URLs | `scene-math.js` |
+| Shared logical frame and room codes | `coords.js` |
+| WebXR multi-placement with one anchor per model | `multi-place.js` (with `anchor-lifecycle.js`, `depth-occlusion.js`, `estimated-lighting.js`, `pinch.js`) |
+| Colyseus room client, timeout and single-retry reconnect | `net.js` (wire schema in `schemas.js`) |
+
+[`src/ar/studio-net.js`](../src/ar/studio-net.js) is a thin subclass of the package's `StudioNet` that only resolves which Colyseus host the three.ws site dials. The package's share-URL helpers take the full URL of the page that hosts the studio (`https://three.ws/ar/studio`), which is what lets a third-party embed build links against its own page. The room server keeps its own copy of the wire schema ([`multiplayer/src/studio-schemas.js`](../multiplayer/src/studio-schemas.js)); [`tests/ar-studio-package-parity.test.js`](../tests/ar-studio-package-parity.test.js) fails if it and the package schema ever diverge. [`src/ar/webxr.js`](../src/ar/webxr.js) (the single-model lane) and [`src/irl.js`](../src/irl.js) consume the same anchor, depth and pinch modules.
+
+Edit the shared modules in `packages/ar-studio`, not in `src/`. The directory is exported to [nirholas/3D-AR-Studio](https://github.com/nirholas/3D-AR-Studio) through `data/standalone-mirrors.json`; publishing a new `3d-ar-studio` version is an owner action.
### Model sources
diff --git a/packages/ar-studio/.gitignore b/packages/ar-studio/.gitignore
new file mode 100644
index 000000000..4464afd7e
--- /dev/null
+++ b/packages/ar-studio/.gitignore
@@ -0,0 +1,7 @@
+node_modules/
+*.log
+.DS_Store
+.env
+.env.local
+smoke.png
+dist/
diff --git a/packages/ar-studio/CHANGELOG.md b/packages/ar-studio/CHANGELOG.md
new file mode 100644
index 000000000..ea2538be0
--- /dev/null
+++ b/packages/ar-studio/CHANGELOG.md
@@ -0,0 +1,120 @@
+# Changelog
+
+## 0.3.2
+
+- **A model placed through Quick Look now rests on your floor instead of hanging in the air.**
+ 0.3.1 got an iPhone into ARKit; once there, the model hung at roughly the height it had been
+ authored at and drifted with the phone rather than settling on a surface, which reads as
+ broken tracking and is not. AR Quick Look anchors the scene's ORIGIN to the plane it detects
+ and never looks at the geometry, so a GLB authored around its bounding-box centre arrives
+ half-buried and one authored around a distant scene origin arrives floating across the room.
+ No anchoring flag fixes that; the content has to be moved. Every export is now stood on y=0
+ with its footprint centred over the origin before it is written. On the Poly Haven wrench in
+ the demo catalogue that is a 14 cm correction.
+- **The pinch size reaches the AR viewer.** `USDZExporter` walks `scene.children` and writes
+ each node's LOCAL matrix, so the transform on the object handed to it is never written at
+ all: the scale the studio set on the exported root was silently dropped, and every model
+ arrived at its authored size no matter what anyone had resized it to. Placement now rides on
+ a `Model` stage node inside the root, which does get written.
+- **A model authored in centimetres is brought back to room scale** on the convert-from-URL
+ path. USDZ is metres, so a 75 cm prop authored as 75 units arrived 75 m tall, far too large
+ for any plane ARKit found indoors, and swam around the viewer: the same symptom as a broken
+ anchor from a completely different cause.
+- **The page hands the camera over before the AR viewer opens.** The camera is a single-client
+ resource on a phone. Leaving the studio's `getUserMedia` stream running while Quick Look
+ started ARKit against the same camera left world tracking and plane detection unable to
+ converge. The passthrough is now released on the way into native AR and restarted when you
+ come back, exactly as the immersive WebXR path has always done.
+- **The camera passthrough says what it is.** It is a gyroscope over a video feed: it turns with
+ you, but it has no plane detection and no positional tracking, so walking around was never
+ going to hold a model to a spot on the real floor. On a device with a real AR viewer the
+ status line now says so and offers the one-tap route to it.
+- **A model too big for any plane in the room is brought back to one that fits.** Quick Look
+ does not place a model until ARKit has found a horizontal plane large enough to hold it;
+ until then the model hangs aligned to the camera and travels with the phone, which reads as
+ broken tracking rather than as "still looking". Exports are now capped at a 2.5 m footprint
+ and a 2.5 m height. This is a ceiling, not a normalizer: furniture, people and props pass
+ through untouched. It matters because the pinch size is honoured again, and the studio lets
+ that reach 4x, which on a standing figure is seven metres of nothing a floor will ever fit.
+- The render loop stops while the native AR viewer has the screen, instead of drawing 60 frames
+ a second of a hidden page while ARKit is doing plane detection on the same GPU.
+- New API: `usdzExportRoot()`, `groundOnFloor()`, `fitToRoomScale()`, `clampToPlaceableSize()`,
+ `MAX_AR_FOOTPRINT_M`, `MAX_AR_HEIGHT_M`, and a `fit` option on `sceneToUsdzBlob()`.
+
+## 0.3.1
+
+- **Quick Look now opens in AR, not Object mode.** 0.3.0 got an iPhone all the way into Apple's
+ viewer and then landed on the turntable, with the AR tab inert: everything looked right and
+ the one thing anybody wanted did not happen. Safari decides whether a URL is an AR asset from
+ its file extension, and a `blob:` URL has no path and therefore no extension, so the generated
+ USDZ was opened as a generic 3D file. The anchor now carries
+ `download="<model-name>.usdz"`, which is the name Safari sniffs. Exported as
+ `usdzFilename()`, and pinned by a test, because nothing about the symptom points at the cause.
+- The Quick Look checkout banner is all-or-nothing now, matching how Quick Look renders it:
+ `withQuickLookBanner()` returns the URL untouched unless a `callToAction` is present, instead
+ of producing a banner with a title and a dead button.
+
+## 0.3.0
+
+- **"Place in your space" now actually opens the AR viewer on an iPhone.** 0.2.0 routed iOS to
+ AR Quick Look but converted the model to USDZ *inside* the tap handler, and iOS opens
+ `rel="ar"` only while the page still holds the user gesture that asked for it. The conversion
+ outlived the gesture, Safari silently declined, and the button did nothing. Preparing and
+ opening are now separate steps: the studio converts ahead of the tap, and the tap itself is
+ synchronous straight through to the anchor.
+- **A designed hand-off sheet** between the AR button and the device viewer: a preview of the
+ model that is going, a picker when the scene holds more than one, honest progress while the
+ USDZ is built, an error state with a retry, and one primary button. Full dialog semantics
+ (focus capture and return, Escape, backdrop dismiss) and a designed empty state.
+- **The USDZ is exported from the copy already standing in your scene**, not refetched. No
+ second download, no second CORS round trip, and the model reaches Quick Look at the size it
+ was pinched to and in the pose it was in.
+- **Conversions are cached** (four at a time, least-recently-used, object URLs revoked on
+ eviction) and warmed in the background for whichever model the button would send, so opening
+ AR a second time is instant.
+- Exports are tuned for their only reader: `quickLookCompatible` corrects Apple's inverted
+ texture repeat handling, and horizontal plane anchoring is declared in the file.
+- A meshopt-compressed GLB no longer fails a one-shot conversion that starts before the decoder
+ has finished loading.
+- New API: `prepareNativeAr()`, `objectToUsdzBlob()`, `cachedUsdzUrl()`, `isQuickLookReady()`,
+ `releaseQuickLook()`, `clearQuickLookCache()`, `studio.openArSheet()`,
+ `studio.closeArSheet()`, and the `ar-sheet` event.
+
+## 0.2.0
+
+- **Real ARKit and ARCore placement, not a camera-passthrough approximation.** An iPhone has no
+ WebXR, and until now it fell back to compositing the scene over the camera feed, which floats
+ rather than sticks. It now opens Apple's AR Quick Look: real plane detection, real scale, real
+ occlusion. The GLB is converted to USDZ on the device (a real conversion via three.js's
+ `USDZExporter`, about a second for a typical prop), so no server and no pre-baked USDZ is
+ needed. Android without WebXR opens Scene Viewer.
+- The **AR** button now resolves the device's best path at boot, labels itself for what it will
+ actually do, and acts on the selected model.
+- New API: `studio.enterAR()`, `studio.placeInYourSpace()`, `studio.arMode`, the `native-ar` and
+ `native-ar-error` events, and the exported `arCapability()`, `placeInYourSpace()`,
+ `glbUrlToUsdzBlob()` and `withQuickLookBanner()` helpers.
+
+## 0.1.0
+
+First release.
+
+- **The studio.** A live multi-model AR scene for any web page: place, drag, pinch-resize,
+ twist-rotate and duplicate any number of models through the device camera, with a designed
+ path on every device (WebXR on Android and headsets, camera passthrough with gyro world-lock
+ on iOS, grid preview with a QR hand-off on desktop).
+- **Text to 3D, in the camera.** A prompt box in the dock generates a model on a free, keyless
+ lane and drops the result into the room. Progress narration reports only what the pipeline
+ actually reported.
+- **Pluggable model sources.** Ships wired to a few hundred CC0 props. `assets` takes a
+ manifest URL, an inline list, a custom source object, or an ordered array of them; five
+ common catalogue shapes are read without reshaping.
+- **Scenes are links.** Models and transforms round-trip through the URL and a QR code, and
+ persist to localStorage between visits.
+- **Shared rooms.** A six-character code puts two or more people in one arrangement, with live
+ presence and per-owner edit gating.
+- **Universal idle animation.** Humanoid models with no baked clip get one retargeted onto
+ their own skeleton, with no rig allow-list.
+- **MCP server.** Six tools so an agent can generate, search, arrange, export and scaffold AR
+ experiences: `generate_3d_model`, `check_generation`, `search_models`, `compose_ar_scene`,
+ `export_ar`, `create_ar_page`.
+- **CLI.** `create`, `dev`, `deploy` and `page`, so adding AR to a project is two commands.
diff --git a/packages/ar-studio/CITATION.cff b/packages/ar-studio/CITATION.cff
new file mode 100644
index 000000000..bc67244f3
--- /dev/null
+++ b/packages/ar-studio/CITATION.cff
@@ -0,0 +1,10 @@
+cff-version: 1.2.0
+message: If you use this software, please cite it as below.
+title: "3D-AR-Studio"
+abstract: "Drop a full augmented-reality studio into any web page. Place any number of 3D models in your real room through the camera, generate new ones from a text prompt, arrange them, then share the scene as a link, a QR code, or a live room. WebXR + Quick Look + Scene Viewer, a free CC0 model library, and an MCP server for agents."
+license: Apache-2.0
+repository-code: "https://github.com/nirholas/3D-AR-Studio"
+url: "https://three.ws"
+authors:
+ - name: three.ws
+ website: "https://three.ws"
diff --git a/packages/ar-studio/CODE_OF_CONDUCT.md b/packages/ar-studio/CODE_OF_CONDUCT.md
new file mode 100644
index 000000000..4954bc6c1
--- /dev/null
+++ b/packages/ar-studio/CODE_OF_CONDUCT.md
@@ -0,0 +1,7 @@
+# Code of Conduct
+
+This project follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).
+
+In short: be respectful, assume good faith, keep feedback about the work, and do not harass anyone. Maintainers may remove comments, commits or contributions that break these rules and may block repeat offenders.
+
+Report conduct concerns privately to [email protected]. Reports are handled in confidence.
diff --git a/packages/ar-studio/CONTRIBUTING.md b/packages/ar-studio/CONTRIBUTING.md
new file mode 100644
index 000000000..a40f7ad1d
--- /dev/null
+++ b/packages/ar-studio/CONTRIBUTING.md
@@ -0,0 +1,28 @@
+# Contributing to 3D-AR-Studio
+
+Thanks for helping. Small, focused changes land fastest.
+
+## Ways to contribute
+
+- **Report a bug** with the [bug form](https://github.com/nirholas/3D-AR-Studio/issues/new?template=bug.yml). Include what you ran, what you expected and the smallest reproduction you can.
+- **Propose a feature** with the [feature form](https://github.com/nirholas/3D-AR-Studio/issues/new?template=feature.yml). Describe the problem first, then the change.
+- **Ask a question or share what you built** in [Discussions](https://github.com/nirholas/3D-AR-Studio/discussions).
+- **Fix something** with a pull request.
+
+## Local setup
+
+```bash
+git clone https://github.com/nirholas/3D-AR-Studio.git
+cd 3D-AR-Studio
+npm install
+npm test
+```
+
+## Pull requests
+
+- One change per pull request, with a test where the change is testable.
+- Describe what changed and why in plain language.
+- Do not add dependencies for something a few lines of code can do.
+- Security-sensitive reports go through [SECURITY.md](SECURITY.md), not a public issue.
+
+By contributing you agree that your work is licensed under Apache-2.0, the license of this project.
diff --git a/packages/ar-studio/LICENSE b/packages/ar-studio/LICENSE
new file mode 100644
index 000000000..261eeb9e9
--- /dev/null
+++ b/packages/ar-studio/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/packages/ar-studio/README.md b/packages/ar-studio/README.md
new file mode 100644
index 000000000..09f463db1
--- /dev/null
+++ b/packages/ar-studio/README.md
@@ -0,0 +1,511 @@
+# 3D AR Studio
+
+<!-- three.ws:badges -->
+[![GitHub stars](https://img.shields.io/github/stars/nirholas/3D-AR-Studio?style=flat&logo=github)](https://github.com/nirholas/3D-AR-Studio/stargazers) [![License](https://img.shields.io/github/license/nirholas/3D-AR-Studio?style=flat)](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/LICENSE) [![Last commit](https://img.shields.io/github/last-commit/nirholas/3D-AR-Studio?style=flat)](https://github.com/nirholas/3D-AR-Studio/commits) [![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen?style=flat)](https://github.com/nirholas/3D-AR-Studio/pulls)
+<!-- /three.ws:badges -->
+
+
+**Drop a full augmented-reality studio into any web page.**
+
+Place as many 3D models as you like in your real room through the camera, describe a new one
+and watch it appear, arrange everything by hand, then share the whole scene as a link, a QR
+code, or a live room someone else can build in with you.
+
+[**Live demo**](https://nirholas.github.io/3D-AR-Studio/) · [npm](https://www.npmjs.com/package/3d-ar-studio) · [MCP server](#mcp-server)
+
+```html
+<script type="module" src="https://unpkg.com/3d-ar-studio/dist/ar-studio.min.js"></script>
+<ar-studio></ar-studio>
+```
+
+That is a working AR studio. No build step, no API key, no account. It comes wired to a free
+library of a few hundred public-domain models and a free, keyless text-to-3D lane; point it at
+your own catalogue with one option when you are ready.
+
+---
+
+> **Source of truth.** This package lives in the three.ws monorepo at [`packages/ar-studio`](https://github.com/nirholas/three.ws/tree/main/packages/ar-studio) and is mirrored one-way to [nirholas/3D-AR-Studio](https://github.com/nirholas/3D-AR-Studio). The hosted studio at [three.ws/ar/studio](https://three.ws/ar/studio) imports these same modules, so a fix here is a fix there. Send pull requests against the monorepo.
+
+## Why this exists
+
+Every web-AR drop-in places exactly one model and then hands off to a native viewer, which
+ends the session. This one keeps the whole scene in your page:
+
+- **Many models, one room.** Place, drag, pinch-resize, twist-rotate and duplicate as many
+ models as you want in a single live camera view.
+- **Generate without leaving the camera.** Type "a brass desk lamp" into the dock. The
+ generation runs behind the live view and the finished model drops into the room.
+- **Real WebXR where it exists.** An always-armed hit-test reticle, one `XRAnchor` per placed
+ model, real-world light estimation, and depth occlusion so models hide behind your furniture.
+- **Real ARKit and ARCore everywhere else.** iPhones have no WebXR, so tapping **Place in your
+ space** opens Apple's AR Quick Look for real: true plane detection, true scale, true
+ occlusion, the system's own "View in AR" sheet. The model is converted to USDZ on the device
+ (a real conversion via three.js's `USDZExporter`, no server involved) and, because it is
+ exported from the copy already standing in your scene, it arrives at the size you pinched it
+ to and in the pose it was in, stood on the floor rather than hanging at the height it happened
+ to be modelled at. Android without WebXR gets Scene Viewer. Desktop gets a grid
+ preview and a QR hand-off to a phone.
+- **Scenes are links.** Models, positions, rotations and scales round-trip through the URL.
+ Compose on a laptop, scan the QR, it reopens exactly on your phone.
+- **Build together, live.** Open a room, share a six-character code, and every add and move
+ syncs to everyone in it.
+- **Characters actually move.** Any humanoid GLB with no baked animation gets an idle clip
+ retargeted onto its own skeleton. No rig allow-list, no T-poses.
+- **Agents can drive it.** A bundled MCP server lets Claude, ChatGPT or your own agent
+ generate a model, compose an arrangement, and hand a person one link that opens it in
+ their room.
+
+The rendering ladder, anchor lifecycle, retargeting pipeline, scene format and shared-room
+protocol are extracted from the AR surfaces running in production on
+[three.ws](https://three.ws), and generalized so they work on your site with your models.
+
+---
+
+## Install
+
+```bash
+npm i 3d-ar-studio three
+```
+
+`three` is a peer dependency, so you keep one copy of it and pick the version. The CDN bundle
+(`dist/ar-studio.min.js`) has three.js inside it and needs nothing else.
+
+```js
+import { createArStudio } from '3d-ar-studio'
+
+const studio = createArStudio('#stage', {
+ branding: { title: 'Acme AR', accent: '#00b894' },
+})
+
+studio.on('add', ({ placement }) => console.log('placed', placement.title))
+```
+
+The studio fills its host element absolutely, so give the host a height (any positioned box
+with a real height works; a `<div>` with no height gets a sensible `70vh` default rather than
+rendering invisibly).
+
+### Scaffold a deployable page
+
+```bash
+npx 3d-ar-studio create my-ar-site # a folder you can publish as-is
+cd my-ar-site
+npx 3d-ar-studio dev # look at it locally
+npx 3d-ar-studio deploy # push it and turn on GitHub Pages
+```
+
+`deploy` prints every `git` and `gh` command before it runs it. It needs
+[git](https://git-scm.com) and the [GitHub CLI](https://cli.github.com); without them it tells
+you the three manual steps instead of failing silently.
+
+Templates: `static` (one HTML file, no build), `vite`, `react`.
+
+Both `3d-ar-studio` and `ar-studio` run the CLI. The MCP server is a separate
+binary in its own package, so `npx 3d-ar-studio-mcp` resolves cleanly: see
+[MCP server](#mcp-server).
+
+---
+
+## Your own models
+
+The tray is filled from three.ws by default: a few hundred public-domain (CC0) props, free for
+commercial use, served with open CORS. Swap in your own with the `assets` option.
+
+**A JSON file anywhere.** Five common shapes are read without reshaping:
+
+```js
+createArStudio(el, { assets: 'https://cdn.acme.com/models.json' })
+```
+
+```jsonc
+// Any of these work:
+[ { "url": "https://cdn.acme.com/chair.glb", "name": "Aero chair" } ]
+{ "items": [ … ] }
+{ "objects": [ … ] } // three.ws object library
+{ "creations": [ … ] } // three.ws forge gallery
+{ "models": [ … ] }
+```
+
+Per entry, the model URL is read from the first present of `src`, `url`, `glb`, `glb_url`,
+`glbUrl`, `file` or `model`; the label from `title`, `label`, `name` or `prompt`; and the
+thumbnail from `poster`, `thumb`, `thumbnail`, `image` or `preview_image_url`. Anything that
+is not an https (or site-relative) URL is dropped rather than handed to the loader.
+
+**A list you hold in code:**
+
+```js
+import { staticSource } from '3d-ar-studio/sources'
+
+createArStudio(el, {
+ assets: staticSource({
+ label: 'Our furniture',
+ items: [{ src: 'https://cdn.acme.com/chair.glb', title: 'Aero chair', poster: '…' }],
+ }),
+})
+```
+
+**Several tabs at once, in the order you want them:**
+
+```js
+createArStudio(el, { assets: ['recent', myCatalogue, 'objects', 'link'] })
+```
+
+Built-in keys: `'three.ws'` (the default set), `'recent'`, `'objects'`, `'community'`, `'link'`.
+
+**Anything else.** A source is an object with a `list()`:
+
+```js
+createArStudio(el, {
+ assets: {
+ id: 'search',
+ label: 'Search',
+ searchable: true,
+ async list() {
+ const rows = await fetch('/api/models').then((r) => r.json())
+ return rows.map((m) => ({ src: m.glb, title: m.name, poster: m.thumb }))
+ },
+ },
+})
+```
+
+Throwing from `list()` is fine: the tray renders a designed error state with a Retry button.
+
+**Your users can retarget it too**, without touching your code: `?assets=https://…/manifest.json`
+on the page URL. Only https URLs are accepted, and every model source is re-validated before it
+reaches the loader, so a hostile link can add a catalogue but can never smuggle a
+`javascript:` or `data:` model into the scene. Set `allowUrlOverride: false` to switch that off.
+
+### CORS
+
+Models are loaded by the browser, so the host serving your `.glb` files has to allow
+cross-origin requests (`access-control-allow-origin`). If a model fails to load, that is
+almost always why, and the studio says so in the status line rather than failing silently.
+
+---
+
+## Options
+
+| Option | Default | What it does |
+| --- | --- | --- |
+| `assets` | `'three.ws'` | Where models come from: a preset key, a manifest URL, a source object, or an array of them. |
+| `generate` | enabled | `{ enabled, endpoint, kind, tier, timeoutMs, pollMs }`. `endpoint` is any MCP server exposing a compatible generate tool. |
+| `rooms` | enabled | `{ enabled, server }`. Point `server` at your own Colyseus deployment to host shared rooms yourself. |
+| `animations` | three.ws idle clip | `{ enabled, manifestUrl, clip }`. The clip retargeted onto humanoid models that ship no animation. |
+| `lighting` | `'studio'` HDRI | `{ preset, urls }`. `preset: null` uses procedural lighting only and downloads no HDRI. |
+| `branding` |: | `{ title, accent, backHref, backLabel }`. |
+| `shareBaseUrl` | this page | Where share links and QR codes point. |
+| `origin` | `https://three.ws` | Origin for the hosted "View in your space" launcher and viewer links. |
+| `persistKey` | `'ar-studio:scene:v1'` | localStorage key for the saved scene. Change it to run two studios on one origin. |
+| `persist` | `true` | Restore the last scene on load. |
+| `maxPlacements` | `20` | Cap on simultaneous models. Keeps low-end phones interactive. |
+| `fullscreen` | auto | Render as a fixed full-screen layer. Defaults to true only when mounted on `document.body`. |
+| `allowUrlOverride` | `true` | Honour `?assets=`, `?src=`, `?room=` and `?forge=` on the hosting page's URL. |
+| `onEvent` | `null` | Called with `(event, detail)` for every notable action. Wire it to your analytics. |
+
+### URL parameters
+
+| Parameter | Effect |
+| --- | --- |
+| `?assets=<https url>` | Swap the catalogue. |
+| `?src=<glb>&title=<name>` | Load models into the scene. Repeatable. |
+| `#s=<payload>` | Reopen a full arrangement, transforms included. Written by `shareUrl()`. |
+| `?room=<code>` | Join a shared room. |
+| `?forge=<prompt>` | Start a generation on load. |
+
+### Methods
+
+```js
+await studio.addModel({ src, title }) // place a model
+studio.clear() // remove everything; returns what was there
+studio.getScene() // [{ src, title, x, z, yaw, scale }]
+await studio.setScene(items) // replace the arrangement
+studio.shareUrl() // a link that reopens it exactly
+await studio.generate('a brass desk lamp') // text to 3D, into the room
+studio.viewInYourSpace(src, title) // open the hosted launch page for one model
+await studio.startCamera() // needs a user gesture on iOS
+await studio.enterAR() // best AR path for this device
+studio.openArSheet() // the "Place in your space" hand-off sheet
+studio.closeArSheet()
+await studio.placeInYourSpace() // straight to the native viewer, no sheet
+await studio.toggleImmersive() // enter or leave WebXR specifically
+await studio.openRoom() // returns the room code
+studio.destroy() // releases camera, socket and GPU context
+```
+
+### Events
+
+`studio.on(name, fn)` returns an unsubscribe function. The same events also fire as
+`ar-studio:<name>` DOM events on the mounted element.
+
+| Event | Detail |
+| --- | --- |
+| `add` | `{ placement, remote }` |
+| `remove` | `{ src, title }` |
+| `select` | `{ placement }` (null when deselected) |
+| `clear` | `{ items }` |
+| `generate` | `{ model }` |
+| `generate-error` | `{ error, prompt }` |
+| `camera` | `{ active }` |
+| `xr` | `{ active }` |
+| `native-ar` | `{ src, title, viewer }` where viewer is `quicklook`, `sceneviewer` or `none` |
+| `native-ar-error` | `{ error, src }` |
+| `ar-sheet` | `{ open }` when the hand-off sheet opens or closes |
+| `room` | `{ status, code }` |
+| `share` | `{ url }` |
+
+---
+
+## Web component
+
+```html
+<ar-studio
+ assets="https://cdn.acme.com/models.json"
+ title="Acme AR"
+ accent="#00b894"
+ generate="true"
+ rooms="true"
+></ar-studio>
+```
+
+`element.studio` is the live instance. Importing `3d-ar-studio/auto` (what the CDN bundle
+does) registers the element for you.
+
+---
+
+## Keyboard and accessibility
+
+Every control is a real button with an accessible name, the source tabs implement the full
+ARIA tablist contract, and each dialog takes and returns focus.
+
+| Key | Action |
+| --- | --- |
+| Arrows | Nudge the selected model, camera-relative. Hold Shift for fine steps. |
+| `R` | Rotate 45°. |
+| `D` | Duplicate. |
+| Delete / Backspace | Remove, with an undo in the status line. |
+| Escape | Close the open panel, or deselect. |
+
+`prefers-reduced-motion` removes the spawn-in animation and every transition.
+
+---
+
+## MCP server
+
+```bash
+npx 3d-ar-studio-mcp
+```
+
+```json
+{
+ "mcpServers": {
+ "3d-ar-studio": {
+ "command": "npx",
+ "args": ["-y", "3d-ar-studio-mcp"]
+ }
+ }
+}
+```
+
+No API key. Every tool is free and keyless.
+
+| Tool | What it does |
+| --- | --- |
+| `generate_3d_model` | Turn a text prompt into a textured GLB. Returns the model plus links that open it in AR. |
+| `check_generation` | Collect a generation that was still rendering when the first call returned. |
+| `search_models` | Search the free CC0 library (or any catalogue you configure) by name, category and tag. |
+| `compose_ar_scene` | Arrange several models into one scene and return a single link that reopens it exactly. |
+| `export_ar` | Turn any GLB URL into a device-aware "View in your space" link. |
+| `create_ar_page` | Emit a complete, self-contained HTML page embedding the studio, ready to commit. |
+
+| Environment variable | Default | What it changes |
+| --- | --- | --- |
+| `AR_STUDIO_PAGE_URL` | the hosted demo | The page `compose_ar_scene` links to. Set it to your own deployment. |
+| `AR_STUDIO_ASSETS` | the free CC0 library | Catalogue `search_models` searches. |
+| `AR_STUDIO_MCP_ENDPOINT` | three.ws 3D Studio | The MCP endpoint used for generation. |
+| `AR_STUDIO_ORIGIN` | `https://three.ws` | Origin for hosted AR launch and viewer links. |
+
+A session looks like this:
+
+```
+> Put a mid-century lamp and a potted fern in my living room.
+
+ generate_3d_model { prompt: "a brass mid-century desk lamp" } → lamp.glb
+ search_models { query: "potted plant" } → fern.glb
+ compose_ar_scene { models: [{ src: lamp.glb, x: 0, z: -1.4 },
+ { src: fern.glb, x: 0.9, z: -1.2 }] }
+
+ → one link; open it on a phone and both objects stand in the room.
+```
+
+---
+
+## Device support
+
+| Device | Path | What you get |
+| --- | --- | --- |
+| Android Chrome | WebXR `immersive-ar` | The whole scene in the room: hit-test placement, per-model anchors, light estimation, depth occlusion. |
+| iOS Safari | AR Quick Look | One model at a time in Apple's own viewer, with real ARKit tracking, scale and occlusion. The model is converted to USDZ on the device. Camera passthrough with gyro world-lock composes the multi-model scene in-page alongside it. |
+| Android without WebXR | Scene Viewer | One model at a time through ARCore, with a browser fallback if ARCore is missing. |
+| Desktop | Preview | Grid floor, drag-look, QR hand-off to a phone. |
+| Headsets | WebXR | Same as Android Chrome. |
+
+The **AR** button in the top bar always takes the best path the device has, labels itself so it
+never promises the wrong one, and acts on the selected model (or the last one placed).
+
+Camera and WebXR both need a secure context: `https://` or `localhost`.
+
+### Placing one model in someone's real room
+
+On a device with WebXR the AR button goes straight into an immersive session. Everywhere else
+it opens the **hand-off sheet**: which model is going, a picker when the scene holds more than
+one, and a single primary button that opens the device's own AR viewer.
+
+The sheet exists for one specific reason, and it is worth knowing about if you are building
+your own UI on top of this package:
+
+> **iOS opens AR Quick Look only while the page still holds the user gesture that asked for
+> it.** Converting a GLB to USDZ takes a second or two. Start the conversion inside the tap
+> handler and by the time the `<a rel="ar">` is clicked the gesture has expired, Safari
+> silently declines, and the button looks broken. That is the single most common reason a
+> "View in AR" button does nothing on an iPhone.
+
+There is a second trap right behind it, and it is worse because the failure looks like success:
+
+> **Safari decides whether a URL is an AR asset from its file extension.** A `blob:` URL has no
+> path, so it has no extension. Hand one to `<a rel="ar">` with no filename and Safari still
+> opens Quick Look, but as a generic 3D preview: the viewer comes up in **Object** mode with AR
+> unavailable. Setting `download="something.usdz"` on the anchor gives Safari the name it
+> sniffs, and Quick Look enters AR. `openQuickLook()` does this for you.
+
+So the package splits preparing from opening, and never does them in one tap:
+
+```js
+import { prepareNativeAr, isQuickLookReady } from '3d-ar-studio';
+
+// Ahead of the tap: convert, cache, and keep the result.
+const handoff = await prepareNativeAr({
+ src: 'https://example.com/chair.glb',
+ title: 'Chair',
+ key: '[email protected]', // cache identity; include the scale if you bake one in
+});
+
+// Inside the tap, synchronously. No await between the click and open().
+button.addEventListener('click', () => handoff?.open());
+```
+
+`prepareNativeAr` resolves to `null` on a device with no native AR viewer, `{ viewer:
+'quicklook' }` on iOS with a `blob:` USDZ ready to open, and `{ viewer: 'sceneviewer' }` on
+Android, where nothing needs converting at all. Conversions are cached (four at a time,
+least-recently-used, object URLs revoked on eviction); `isQuickLookReady(key)`,
+`releaseQuickLook(key)` and `clearQuickLookCache()` let you drive that cache yourself.
+
+The studio warms the cache in the background for whichever model the button would send, which
+is why the second tap of the day is instant. `placeInYourSpace()` still exists and still does
+both halves in one call: reach for it when the USDZ is already cached, or when you are calling
+it from your own already-prepared button.
+
+Exporting from the live scene rather than refetching the GLB is deliberate too: no second
+download, no second CORS round trip, and the person gets the pose and the size they are
+looking at. `objectToUsdzBlob(object3D)` is exported if you want that for your own three.js
+scene.
+
+### Why a model hangs in the air instead of resting on your floor
+
+The third trap, and the one that survives both of the others:
+
+> **AR Quick Look anchors the scene's ORIGIN to the plane it detects, and never looks at the
+> geometry.** A GLB authored around its bounding-box centre arrives half-buried; one authored
+> around a distant scene origin arrives floating across the room at whatever height it was
+> modelled at. Both read as broken tracking, and no anchoring property fixes either: the
+> content has to be moved.
+
+Every export from this package is therefore stood on `y = 0` with its footprint centred over
+the origin before it is written. `groundOnFloor()` is exported if you want to do that to your
+own scene.
+
+Two smaller ones ride along with it:
+
+> **`USDZExporter` walks `scene.children` and writes each node's LOCAL matrix**, so the
+> transform on the object you hand it is never written at all. Set a scale on the root and the
+> file comes out at the original size with no warning. `usdzExportRoot()` wraps content in an
+> identity root plus a `Model` stage node, and every placement this package applies rides on
+> the stage, which does get written.
+
+> **USDZ is metres** (`metersPerUnit = 1`). A 75 cm prop authored in centimetres arrives 75 m
+> tall, too large for any plane ARKit found indoors, and swims around the viewer. Pass
+> `{ fit: true }` to `sceneToUsdzBlob()` (`glbUrlToUsdzBlob()` already does) to normalize a
+> model straight off the network. Anything already within 2x of a believable real-world size
+> is left exactly as authored.
+
+And the one that looks most like broken tracking of all:
+
+> **Quick Look does not place a model until ARKit has found a plane big enough to hold it.**
+> Until then it hangs aligned to the camera and travels with the phone. Past a certain size
+> there is no such plane in an ordinary room, so it never lands at all. Every export is capped
+> at `MAX_AR_FOOTPRINT_M` (2.5 m) and `MAX_AR_HEIGHT_M` (2.5 m) by `clampToPlaceableSize()`.
+> A ceiling, not a normalizer: furniture, people and props go through untouched.
+
+### The camera is one client at a time
+
+The studio releases its `getUserMedia` passthrough on the way into the device's AR viewer and
+restarts it when you come back. Leave the page's stream running and ARKit starts against a
+camera another process is already holding: the model appears, and then world tracking and
+plane detection never converge, so it drifts with the phone instead of settling. If you drive
+the hand-off yourself from your own camera UI, stop your tracks before you call `open()`.
+
+Passthrough itself is a gyroscope over a video feed: it turns with you, and that is all. It has
+no plane detection and no positional tracking, so it will never hold a model to a spot on a
+real floor. On iOS that is what Quick Look is for, and the studio's status line says so.
+
+---
+
+## Development
+
+```bash
+npm install
+npm test # 75 unit tests, no browser needed
+npm run build # dist/ bundles
+npm run build:site # docs/ (the GitHub Pages site)
+npm run test:browser # 35 end-to-end checks in a real browser (needs Playwright)
+npm run inspect # MCP Inspector against the local server
+```
+
+The published site is committed under `docs/` and served by GitHub Pages from the `main`
+branch. There is no CI workflow: `npm run build && npm run build:site`, commit, push.
+
+---
+
+## Licence and credits
+
+Apache-2.0.
+
+The bundle includes [three.js](https://threejs.org) (MIT) and
+[colyseus.js](https://colyseus.io) (MIT). The default model library is CC0 content from
+[Poly Haven](https://polyhaven.com), and the default generation and animation lanes are hosted
+by [three.ws](https://three.ws). None of them is required: every one is a URL you can change.
+
+## Star History
+
+[![Star History Chart](https://api.star-history.com/svg?repos=nirholas/3D-AR-Studio&type=Date)](https://www.star-history.com/#nirholas/3D-AR-Studio&Date)
+
+<!-- three.ws:growth -->
+## Support the project
+
+If 3D-AR-Studio saves you time, **[star it on GitHub](https://github.com/nirholas/3D-AR-Studio)**. Stars are how other developers and AI agents find the repositories worth trusting, and they cost you one click.
+
+Know someone who would use it? [Post on X](https://twitter.com/intent/tweet?text=3D-AR-Studio%3A%20Drop%20a%20full%20augmented-reality%20studio%20into%20any%20web%20page&url=https%3A%2F%2Fgithub.com%2Fnirholas%2F3D-AR-Studio) · [Share on Bluesky](https://bsky.app/intent/compose?text=3D-AR-Studio%3A%20Drop%20a%20full%20augmented-reality%20studio%20into%20any%20web%20page%20https%3A%2F%2Fgithub.com%2Fnirholas%2F3D-AR-Studio) · [Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fgithub.com%2Fnirholas%2F3D-AR-Studio) · [Submit to Hacker News](https://news.ycombinator.com/submitlink?u=https%3A%2F%2Fgithub.com%2Fnirholas%2F3D-AR-Studio&t=3D-AR-Studio%3A%20Drop%20a%20full%20augmented-reality%20studio%20into%20any%20web%20page) · [Share on Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fgithub.com%2Fnirholas%2F3D-AR-Studio&title=3D-AR-Studio%3A%20Drop%20a%20full%20augmented-reality%20studio%20into%20any%20web%20page)
+
+## Built for AI agents too
+
+Coding agents and LLM tooling can read this repo directly: [llms.txt](./llms.txt), [llms-full.txt](./llms-full.txt). Point an agent at `https://github.com/nirholas/3D-AR-Studio` and it has the context it needs.
+
+## More from the same author
+
+- [All repositories by nirholas](https://github.com/nirholas/nirholas#readme): the full catalog, grouped by topic
+- [three.ws](https://three.ws): the platform for 3D AI agents with Solana wallets, a skill marketplace and x402 payments
+- Questions or ideas: [open an issue](https://github.com/nirholas/3D-AR-Studio/issues) or [start a discussion](https://github.com/nirholas/3D-AR-Studio/discussions)
+
+## Contributors
+
+[![Contributors](https://contrib.rocks/image?repo=nirholas/3D-AR-Studio)](https://github.com/nirholas/3D-AR-Studio/graphs/contributors)
+
+<!-- /three.ws:growth -->
diff --git a/packages/ar-studio/SECURITY.md b/packages/ar-studio/SECURITY.md
new file mode 100644
index 000000000..e92bd572c
--- /dev/null
+++ b/packages/ar-studio/SECURITY.md
@@ -0,0 +1,17 @@
+# Security Policy
+
+## Reporting a vulnerability
+
+Please do not open a public issue for a vulnerability.
+
+Use GitHub's private reporting: https://github.com/nirholas/3D-AR-Studio/security/advisories/new
+
+You will get an acknowledgement within 3 business days and a status update within 10. Fixes ship in the next release with credit to the reporter unless you prefer otherwise.
+
+## Scope
+
+In scope: this repository's code and its documented configuration. Out of scope: third-party services it talks to, and findings that need a compromised machine or a leaked key.
+
+## Supported versions
+
+The latest release (or the default branch when there are no releases) receives fixes.
diff --git a/packages/ar-studio/bin/cli.mjs b/packages/ar-studio/bin/cli.mjs
new file mode 100755
index 000000000..c5150a5ba
--- /dev/null
+++ b/packages/ar-studio/bin/cli.mjs
@@ -0,0 +1,294 @@
+#!/usr/bin/env node
+// 3D AR Studio command line.
+//
+// npx 3d-ar-studio create my-ar-site scaffold a publishable page
+// npx 3d-ar-studio dev serve it locally over http
+// npx 3d-ar-studio deploy push it and turn on GitHub Pages
+// npx 3d-ar-studio page > index.html print a single self-contained page
+//
+// The point of `create` + `deploy` is that adding AR to a project should be two
+// commands, not an afternoon. Neither command hides anything: `create` writes
+// plain files you can read, and `deploy` prints every git and gh command it runs
+// before running it.
+
+import { cp, mkdir, readFile, readdir, writeFile, stat } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import { createServer } from 'node:http';
+import { spawnSync } from 'node:child_process';
+import { basename, dirname, extname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { renderPage } from '../mcp/tools.js';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(HERE, '..');
+const pkg = JSON.parse(await readFile(resolve(ROOT, 'package.json'), 'utf8'));
+
+const TEMPLATES = ['static', 'vite', 'react'];
+
+const argv = process.argv.slice(2);
+const command = argv[0] || 'help';
+const flags = parseFlags(argv.slice(1));
+
+const COMMANDS = { create, dev, deploy, page, help, version };
+const run = COMMANDS[command] || (() => {
+ fail(`Unknown command "${command}". Run \`3d-ar-studio help\` to see what there is.`);
+});
+await run();
+
+// ── create ──────────────────────────────────────────────────────────────────
+
+async function create() {
+ const dir = resolve(process.cwd(), flags._[0] || 'ar-studio-site');
+ const template = String(flags.template || flags.t || 'static');
+ if (!TEMPLATES.includes(template)) {
+ fail(`Unknown template "${template}". Pick one of: ${TEMPLATES.join(', ')}.`);
+ }
+ if (existsSync(dir) && (await readdir(dir)).length) {
+ fail(`${dir} already has files in it. Pass an empty directory, or a new name.`);
+ }
+ const title = String(flags.title || titleFromDir(dir));
+ const accent = String(flags.accent || '#8b7cf8');
+
+ await mkdir(dir, { recursive: true });
+ await copyTemplate(resolve(ROOT, 'templates', template), dir, {
+ __TITLE__: title,
+ __ACCENT__: accent,
+ __SLUG__: slug(basename(dir)),
+ });
+
+ console.log(`\nCreated ${rel(dir)} from the "${template}" template.\n`);
+ if (template === 'static') {
+ console.log(' cd ' + rel(dir));
+ console.log(' npx 3d-ar-studio dev # look at it');
+ console.log(' npx 3d-ar-studio deploy # publish it on GitHub Pages\n');
+ } else if (template === 'vite') {
+ console.log(' cd ' + rel(dir));
+ console.log(' npm install');
+ console.log(' npm run dev\n');
+ } else {
+ console.log(' Copy src/ArStudio.jsx into your app, then `npm i 3d-ar-studio three`.\n');
+ }
+ console.log('Point it at your own models with the `assets` option. Docs: https://github.com/nirholas/3D-AR-Studio#your-own-models\n');
+}
+
+async function copyTemplate(from, to, replacements) {
+ for (const entry of await readdir(from, { withFileTypes: true })) {
+ const src = join(from, entry.name);
+ const dest = join(to, entry.name);
+ if (entry.isDirectory()) {
+ await mkdir(dest, { recursive: true });
+ await copyTemplate(src, dest, replacements);
+ continue;
+ }
+ if (['.html', '.js', '.jsx', '.json', '.md', '.css'].includes(extname(entry.name))) {
+ let text = await readFile(src, 'utf8');
+ for (const [token, value] of Object.entries(replacements)) text = text.split(token).join(value);
+ await writeFile(dest, text);
+ } else {
+ await cp(src, dest);
+ }
+ }
+}
+
+// ── dev ─────────────────────────────────────────────────────────────────────
+
+async function dev() {
+ const dir = resolve(process.cwd(), flags.dir || flags._[0] || '.');
+ const port = Number(flags.port || flags.p || 5175);
+ if (!existsSync(dir)) fail(`${dir} does not exist.`);
+
+ const TYPES = {
+ '.html': 'text/html; charset=utf-8',
+ '.js': 'text/javascript; charset=utf-8',
+ '.mjs': 'text/javascript; charset=utf-8',
+ '.css': 'text/css; charset=utf-8',
+ '.json': 'application/json; charset=utf-8',
+ '.map': 'application/json; charset=utf-8',
+ '.glb': 'model/gltf-binary',
+ '.gltf': 'model/gltf+json',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.svg': 'image/svg+xml',
+ '.wasm': 'application/wasm',
+ '.hdr': 'image/vnd.radiance',
+ };
+
+ const server = createServer(async (req, res) => {
+ const path = decodeURIComponent(String(req.url).split('?')[0]);
+ let file = resolve(dir, `.${path}`);
+ // Never serve outside the served directory, whatever the request says.
+ if (!file.startsWith(dir)) {
+ res.writeHead(403).end('Forbidden');
+ return;
+ }
+ try {
+ if ((await stat(file)).isDirectory()) file = join(file, 'index.html');
+ } catch {
+ res.writeHead(404, { 'content-type': 'text/plain' }).end('Not found');
+ return;
+ }
+ try {
+ const body = await readFile(file);
+ res.writeHead(200, {
+ 'content-type': TYPES[extname(file)] || 'application/octet-stream',
+ 'cache-control': 'no-store',
+ // The studio itself needs these to open a camera and an XR session.
+ 'permissions-policy': 'camera=(self), xr-spatial-tracking=(self), gyroscope=(self), accelerometer=(self)',
+ });
+ res.end(body);
+ } catch {
+ res.writeHead(404, { 'content-type': 'text/plain' }).end('Not found');
+ }
+ });
+
+ server.listen(port, () => {
+ console.log(`\nServing ${rel(dir)} on http://localhost:${port}\n`);
+ console.log('Camera and WebXR need a secure context. http://localhost counts as one;');
+ console.log('a LAN address over plain http does not, so use a tunnel to test on a phone.\n');
+ });
+}
+
+// ── deploy ──────────────────────────────────────────────────────────────────
+
+async function deploy() {
+ const dir = resolve(process.cwd(), flags.dir || '.');
+ const name = String(flags.repo || basename(dir));
+ const branch = String(flags.branch || 'main');
+ if (!existsSync(join(dir, 'index.html'))) {
+ fail(`${rel(dir)} has no index.html, so there is nothing for Pages to serve. Run \`3d-ar-studio create\` first.`);
+ }
+ if (!has('git')) fail('git is not installed, and deploy needs it.');
+ if (!has('gh')) {
+ fail(
+ 'This command drives the GitHub CLI (`gh`), which is not installed.\n'
+ + 'Install it from https://cli.github.com, or publish by hand: commit this folder,\n'
+ + 'push it, then enable Pages under Settings -> Pages, serving from the branch root.',
+ );
+ }
+
+ const git = (...args) => sh('git', args, dir);
+ if (!existsSync(join(dir, '.git'))) {
+ git('init', '-b', branch);
+ }
+ git('add', '.');
+ // A commit with nothing staged exits non-zero; that is fine when re-deploying.
+ sh('git', ['commit', '-m', 'Publish the AR studio page'], dir, { allowFailure: true });
+
+ const slugged = slug(name);
+ const exists = sh('gh', ['repo', 'view', slugged, '--json', 'name'], dir, { allowFailure: true, quiet: true }).status === 0;
+ if (!exists) {
+ console.log(`\nCreating the GitHub repository "${slugged}"…`);
+ sh('gh', ['repo', 'create', slugged, '--public', '--source', '.', '--remote', 'origin', '--push'], dir);
+ } else {
+ if (sh('git', ['remote', 'get-url', 'origin'], dir, { allowFailure: true, quiet: true }).status !== 0) {
+ const url = sh('gh', ['repo', 'view', slugged, '--json', 'url', '-q', '.url'], dir, { quiet: true }).stdout.trim();
+ git('remote', 'add', 'origin', url);
+ }
+ git('push', '-u', 'origin', branch);
+ }
+
+ const owner = sh('gh', ['api', 'user', '-q', '.login'], dir, { quiet: true }).stdout.trim();
+ console.log('\nTurning on GitHub Pages…');
+ const pages = sh('gh', [
+ 'api', '--method', 'POST', `repos/${owner}/${slugged}/pages`,
+ '-f', 'source[branch]=' + branch, '-f', 'source[path]=/',
+ ], dir, { allowFailure: true, quiet: true });
+ if (pages.status !== 0 && !/already exists/i.test(pages.stderr)) {
+ console.log('\nPages could not be enabled automatically. Turn it on under');
+ console.log(`https://github.com/${owner}/${slugged}/settings/pages (branch ${branch}, folder /).`);
+ }
+
+ console.log(`\nPublished. It goes live within a minute or two at:\n\n https://${owner}.github.io/${slugged}/\n`);
+ console.log('Open that on a phone and tap Camera.\n');
+}
+
+// ── page ────────────────────────────────────────────────────────────────────
+
+async function page() {
+ process.stdout.write(renderPage({
+ title: String(flags.title || 'AR Studio'),
+ accent: String(flags.accent || '#8b7cf8'),
+ ...(flags.assets ? { assets: String(flags.assets) } : {}),
+ ...(flags.generate === false ? { generate: false } : {}),
+ }));
+}
+
+// ── help ────────────────────────────────────────────────────────────────────
+
+async function version() {
+ console.log(pkg.version);
+}
+
+async function help() {
+ console.log(`
+3d-ar-studio ${pkg.version}
+${pkg.homepage}
+
+ create [dir] Scaffold a publishable AR page.
+ --template static|vite|react (default: static)
+ --title "Acme AR" --accent "#00b894"
+
+ dev [dir] Serve a folder locally over http.
+ --port 5175
+
+ deploy Commit, push, and enable GitHub Pages for the current folder.
+ --repo my-ar-site --branch main --dir .
+ Needs git and the GitHub CLI (gh).
+
+ page Print one self-contained AR page to stdout.
+ --title --accent --assets https://your.cdn/models.json
+
+ help, version
+
+The MCP server is a separate binary: \`npx 3d-ar-studio-mcp\`.
+`);
+}
+
+// ── plumbing ────────────────────────────────────────────────────────────────
+
+function parseFlags(args) {
+ const out = { _: [] };
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (!arg.startsWith('--')) { out._.push(arg); continue; }
+ const [key, inline] = arg.slice(2).split('=');
+ if (inline !== undefined) out[key] = inline;
+ else if (args[i + 1] && !args[i + 1].startsWith('--')) out[key] = args[++i];
+ else if (key.startsWith('no-')) out[key.slice(3)] = false;
+ else out[key] = true;
+ }
+ return out;
+}
+
+function sh(cmd, args, cwd, { allowFailure = false, quiet = false } = {}) {
+ if (!quiet) console.log(` $ ${cmd} ${args.join(' ')}`);
+ const res = spawnSync(cmd, args, { cwd, encoding: 'utf8', stdio: quiet ? 'pipe' : ['inherit', 'inherit', 'pipe'] });
+ if (res.status !== 0 && !allowFailure) {
+ fail(`\`${cmd} ${args.join(' ')}\` failed.\n${(res.stderr || '').trim()}`);
+ }
+ return { status: res.status, stdout: res.stdout || '', stderr: res.stderr || '' };
+}
+
+function has(cmd) {
+ return spawnSync(cmd, ['--version'], { stdio: 'ignore' }).status === 0;
+}
+
+function slug(s) {
+ return String(s).toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'ar-studio-site';
+}
+
+function titleFromDir(dir) {
+ const name = basename(dir).replace(/[_-]+/g, ' ').trim();
+ return name ? name.charAt(0).toUpperCase() + name.slice(1) : 'AR Studio';
+}
+
+function rel(p) {
+ const r = p.replace(`${process.cwd()}/`, '');
+ return r || '.';
+}
+
+function fail(message) {
+ console.error(`\n${message}\n`);
+ process.exit(1);
+}
diff --git a/packages/ar-studio/bin/mcp.mjs b/packages/ar-studio/bin/mcp.mjs
new file mode 100755
index 000000000..b7df507b9
--- /dev/null
+++ b/packages/ar-studio/bin/mcp.mjs
@@ -0,0 +1,15 @@
+#!/usr/bin/env node
+// The 3D AR Studio MCP server, over stdio.
+//
+// npx 3d-ar-studio-mcp
+//
+// Add it to a client's config as { "command": "npx", "args": ["-y", "3d-ar-studio-mcp"] }.
+
+import { main } from '../mcp/index.js';
+
+main().catch((err) => {
+ // stdout is the protocol channel: diagnostics must go to stderr or they
+ // corrupt the JSON-RPC stream.
+ console.error('[3d-ar-studio-mcp]', err?.stack || err?.message || err);
+ process.exit(1);
+});
diff --git a/packages/ar-studio/docs/.nojekyll b/packages/ar-studio/docs/.nojekyll
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/ar-studio/docs/ar-studio.min.js b/packages/ar-studio/docs/ar-studio.min.js
new file mode 100644
index 000000000..76b5802f5
--- /dev/null
+++ b/packages/ar-studio/docs/ar-studio.min.js
@@ -0,0 +1,4535 @@
+/*! 3d-ar-studio v0.3.2 · https://nirholas.github.io/3D-AR-Studio/
+ * Apache-2.0 licensed. Bundles three.js (MIT) and colyseus.js (MIT). */
+var xv=Object.create;var wc=Object.defineProperty;var _v=Object.getOwnPropertyDescriptor;var yv=Object.getOwnPropertyNames;var vv=Object.getPrototypeOf,Sv=Object.prototype.hasOwnProperty;var un=(i,e,t)=>()=>{if(t)throw t[0];try{return i&&(e=i(i=0)),e}catch(n){throw t=[n],n}};var dn=(i,e)=>()=>{try{return e||i((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ar=(i,e)=>{for(var t in e)wc(i,t,{get:e[t],enumerable:!0})},ag=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yv(e))!Sv.call(i,r)&&r!==t&&wc(i,r,{get:()=>e[r],enumerable:!(n=_v(e,r))||n.enumerable});return i};var og=(i,e,t)=>(t=i!=null?xv(vv(i)):{},ag(e||!i||!i.__esModule?wc(t,"default",{value:i,enumerable:!0}):t,i)),Gs=i=>ag(wc({},"__esModule",{value:!0}),i);function wv(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function M0(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function aa(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function A0(){let i=aa("canvas");return i.style.display="block",i}function eo(...i){let e="THREE."+i.shift();oa?oa("log",e,...i):console.log(e,...i)}function T0(i){let e=i[0];if(typeof e=="string"&&e.startsWith("TSL:")){let t=i[1];t&&t.isStackTrace?i[0]+=" "+t.getLocation():i[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return i}function Ke(...i){i=T0(i);let e="THREE."+i.shift();if(oa)oa("warn",e,...i);else{let t=i[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...i)}}function et(...i){i=T0(i);let e="THREE."+i.shift();if(oa)oa("error",e,...i);else{let t=i[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...i)}}function al(...i){let e=i.join(" ");e in cg||(cg[e]=!0,Ke(...i))}function E0(i,e,t){return new Promise(function(n,r){function s(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:r();break;case i.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:n()}}setTimeout(s,t)})}function Ii(){let i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(In[i&255]+In[i>>8&255]+In[i>>16&255]+In[i>>24&255]+"-"+In[e&255]+In[e>>8&255]+"-"+In[e>>16&15|64]+In[e>>24&255]+"-"+In[t&63|128]+In[t>>8&255]+"-"+In[t>>16&255]+In[t>>24&255]+In[n&255]+In[n>>8&255]+In[n>>16&255]+In[n>>24&255]).toLowerCase()}function bt(i,e,t){return Math.max(e,Math.min(t,i))}function zd(i,e){return(i%e+e)%e}function Mv(i,e,t,n,r){return n+(i-e)*(r-n)/(t-e)}function Av(i,e,t){return i!==e?(t-i)/(e-i):0}function Ja(i,e,t){return(1-t)*i+t*e}function Tv(i,e,t,n){return Ja(i,e,1-Math.exp(-t*n))}function Ev(i,e=1){return e-Math.abs(zd(i,e*2)-e)}function Rv(i,e,t){return i<=e?0:i>=t?1:(i=(i-e)/(t-e),i*i*(3-2*i))}function Cv(i,e,t){return i<=e?0:i>=t?1:(i=(i-e)/(t-e),i*i*i*(i*(i*6-15)+10))}function Iv(i,e){return i+Math.floor(Math.random()*(e-i+1))}function Pv(i,e){return i+Math.random()*(e-i)}function Lv(i){return i*(.5-Math.random())}function Dv(i){i!==void 0&&(lg=i);let e=lg+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function Nv(i){return i*Ya}function Ov(i){return i*bs}function Fv(i){return(i&i-1)===0&&i!==0}function Uv(i){return Math.pow(2,Math.ceil(Math.log(i)/Math.LN2))}function kv(i){return Math.pow(2,Math.floor(Math.log(i)/Math.LN2))}function Bv(i,e,t,n,r){let s=Math.cos,a=Math.sin,o=s(t/2),l=a(t/2),c=s((e+n)/2),h=a((e+n)/2),d=s((e-n)/2),f=a((e-n)/2),p=s((n-e)/2),x=a((n-e)/2);switch(r){case"XYX":i.set(o*h,l*d,l*f,o*c);break;case"YZY":i.set(l*f,o*h,l*d,o*c);break;case"ZXZ":i.set(l*d,l*f,o*h,o*c);break;case"XZX":i.set(o*h,l*x,l*p,o*c);break;case"YXY":i.set(l*p,o*h,l*x,o*c);break;case"ZYZ":i.set(l*x,l*p,o*h,o*c);break;default:Ke("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function Ri(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function Nt(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}function zv(){let i={enabled:!0,workingColorSpace:bn,spaces:{},convert:function(r,s,a){return this.enabled===!1||s===a||!s||!a||(this.spaces[s].transfer===Dt&&(r.r=fr(r.r),r.g=fr(r.g),r.b=fr(r.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Dt&&(r.r=ia(r.r),r.g=ia(r.g),r.b=ia(r.b))),r},workingToColorSpace:function(r,s){return this.convert(r,this.workingColorSpace,s)},colorSpaceToWorking:function(r,s){return this.convert(r,s,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===Fi?Qa:this.spaces[r].transfer},getToneMappingMode:function(r){return this.spaces[r].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(r,s=this.workingColorSpace){return r.fromArray(this.spaces[s].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,s,a){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(r,s){return al("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return al("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(r,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[bn]:{primaries:e,whitePoint:n,transfer:Qa,toXYZ:ug,fromXYZ:dg,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Xt},outputColorSpaceConfig:{drawingBufferColorSpace:Xt}},[Xt]:{primaries:e,whitePoint:n,transfer:Dt,toXYZ:ug,fromXYZ:dg,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Xt}}}),i}function fr(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function ia(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}function Bu(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?ol.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(Ke("Texture: Unable to serialize Texture."),{})}function Gu(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}function Yu(i,e,t,n,r){for(let s=0,a=i.length-3;s<=a;s+=3){as.fromArray(i,s);let o=r.x*Math.abs(as.x)+r.y*Math.abs(as.y)+r.z*Math.abs(as.z),l=e.dot(as),c=t.dot(as),h=n.dot(as);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}function Yv(){let i=new ArrayBuffer(4),e=new Float32Array(i),t=new Uint32Array(i),n=new Uint32Array(512),r=new Uint32Array(512);for(let l=0;l<256;++l){let c=l-127;c<-27?(n[l]=0,n[l|256]=32768,r[l]=24,r[l|256]=24):c<-14?(n[l]=1024>>-c-14,n[l|256]=1024>>-c-14|32768,r[l]=-c-1,r[l|256]=-c-1):c<=15?(n[l]=c+15<<10,n[l|256]=c+15<<10|32768,r[l]=13,r[l|256]=13):c<128?(n[l]=31744,n[l|256]=64512,r[l]=24,r[l|256]=24):(n[l]=31744,n[l|256]=64512,r[l]=13,r[l|256]=13)}let s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,h=0;for(;(c&8388608)===0;)c<<=1,h-=8388608;c&=-8388609,h+=947912704,s[l]=c|h}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:n,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function Jv(i){Math.abs(i)>65504&&Ke("DataUtils.toHalfFloat(): Value out of range."),i=bt(i,-65504,65504),dr.floatView[0]=i;let e=dr.uint32View[0],t=e>>23&511;return dr.baseTable[t]+((e&8388607)>>dr.shiftTable[t])}function Zv(i){let e=i>>10;return dr.uint32View[0]=dr.mantissaTable[dr.offsetTable[e]+(i&1023)]+dr.exponentTable[e],dr.floatView[0]}function iS(i,e,t,n,r,s,a,o){let l;if(e.side===An?l=n.intersectTriangle(a,s,r,!0,o):l=n.intersectTriangle(r,s,a,e.side===Pi,o),l===null)return null;kc.copy(o),kc.applyMatrix4(i.matrixWorld);let c=t.ray.origin.distanceTo(kc);return c<t.near||c>t.far?null:{distance:c,point:kc.clone(),object:i}}function Bc(i,e,t,n,r,s,a,o,l,c){i.getVertexPosition(o,Nc),i.getVertexPosition(l,Oc),i.getVertexPosition(c,Fc);let h=iS(i,e,t,n,Nc,Oc,Fc,wg);if(h){let d=new W;Lr.getBarycoord(wg,Nc,Oc,Fc,d),r&&(h.uv=Lr.getInterpolatedAttribute(r,o,l,c,d,new dt)),s&&(h.uv1=Lr.getInterpolatedAttribute(s,o,l,c,d,new dt)),a&&(h.normal=Lr.getInterpolatedAttribute(a,o,l,c,d,new W),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let f={a:o,b:l,c,normal:new W,materialIndex:0};Lr.getNormal(Nc,Oc,Fc,f.normal),h.face=f,h.barycoord=d}return h}function Wc(i,e,t,n,r,s,a){let o=i.geometry.attributes.position;if(hl.fromBufferAttribute(o,r),ul.fromBufferAttribute(o,s),t.distanceSqToSegment(hl,ul,ad,Lg)>n)return;ad.applyMatrix4(i.matrixWorld);let c=e.ray.origin.distanceTo(ad);if(!(c<e.near||c>e.far))return{distance:c,point:Lg.clone().applyMatrix4(i.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:i}}function Fg(i,e,t,n,r,s,a){let o=dd.distanceSqToPoint(i);if(o<t){let l=new W;dd.closestPointToPoint(i,l),l.applyMatrix4(n);let c=r.ray.origin.distanceTo(l);if(c<r.near||c>r.far)return;s.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}function Es(i){let e={};for(let t in i){e[t]={};for(let n in i[t]){let r=i[t][n];if(Ug(r))r.isRenderTargetTexture?(Ke("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=r.clone();else if(Array.isArray(r))if(Ug(r[0])){let s=[];for(let a=0,o=r.length;a<o;a++)s[a]=r[a].clone();e[t][n]=s}else e[t][n]=r.slice();else e[t][n]=r}}return e}function Nn(i){let e={};for(let t=0;t<i.length;t++){let n=Es(i[t]);for(let r in n)e[r]=n[r]}return e}function Ug(i){return i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)}function hS(i){let e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function Gd(i){let e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:ut.workingColorSpace}function ds(i,e){return!i||i.constructor===e?i:typeof e.BYTES_PER_ELEMENT=="number"?new e(i):Array.prototype.slice.call(i)}function P0(i){function e(r,s){return i[r]-i[s]}let t=i.length,n=new Array(t);for(let r=0;r!==t;++r)n[r]=r;return n.sort(e),n}function fd(i,e,t){let n=i.length,r=new i.constructor(n);for(let s=0,a=0;a!==n;++s){let o=t[s]*e;for(let l=0;l!==e;++l)r[a++]=i[o+l]}return r}function Vd(i,e,t,n){let r=1,s=i[0];for(;s!==void 0&&s[n]===void 0;)s=i[r++];if(s===void 0)return;let a=s[n];if(a!==void 0)if(Array.isArray(a))do a=s[n],a!==void 0&&(e.push(s.time),t.push(...a)),s=i[r++];while(s!==void 0);else if(a.toArray!==void 0)do a=s[n],a!==void 0&&(e.push(s.time),a.toArray(t,t.length)),s=i[r++];while(s!==void 0);else do a=s[n],a!==void 0&&(e.push(s.time),t.push(a)),s=i[r++];while(s!==void 0)}function fS(i,e,t,n,r=30){let s=i.clone();s.name=e;let a=[];for(let l=0;l<s.tracks.length;++l){let c=s.tracks[l],h=c.getValueSize(),d=[],f=[];for(let p=0;p<c.times.length;++p){let x=c.times[p]*r;if(!(x<t||x>=n)){d.push(c.times[p]);for(let y=0;y<h;++y)f.push(c.values[p*h+y])}}d.length!==0&&(c.times=ds(d,c.times.constructor),c.values=ds(f,c.values.constructor),a.push(c))}s.tracks=a;let o=1/0;for(let l=0;l<s.tracks.length;++l)o>s.tracks[l].times[0]&&(o=s.tracks[l].times[0]);for(let l=0;l<s.tracks.length;++l)s.tracks[l].shift(-1*o);return s.resetDuration(),s}function pS(i,e=0,t=i,n=30){n<=0&&(n=30);let r=t.tracks.length,s=e/n;for(let a=0;a<r;++a){let o=t.tracks[a],l=o.ValueTypeName;if(l==="bool"||l==="string")continue;let c=i.tracks.find(function(g){return g.name===o.name&&g.ValueTypeName===l});if(c===void 0)continue;let h=0,d=o.getValueSize();o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(h=d/3);let f=0,p=c.getValueSize();c.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(f=p/3);let x=o.times.length-1,y;if(s<=o.times[0]){let g=h,S=d-h;y=o.values.slice(g,S)}else if(s>=o.times[x]){let g=x*d+h,S=g+d-h;y=o.values.slice(g,S)}else{let g=o.createInterpolant(),S=h,A=d-h;g.evaluate(s),y=g.resultBuffer.slice(S,A)}l==="quaternion"&&new Pt().fromArray(y).normalize().conjugate().toArray(y);let b=c.times.length;for(let g=0;g<b;++g){let S=g*p+f;if(l==="quaternion")Pt.multiplyQuaternionsFlat(c.values,S,y,0,c.values,S);else{let A=p-f*2;for(let T=0;T<A;++T)c.values[S+T]-=y[T]}}}return i.blendMode=Uo,i}function mS(i){switch(i.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return ji;case"vector":case"vector2":case"vector3":case"vector4":return Ki;case"color":return bo;case"quaternion":return Xi;case"bool":case"boolean":return mr;case"string":return gr}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+i)}function gS(i){if(i.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");let e=mS(i.type);if(i.times===void 0){let t=[],n=[];Vd(i.keys,t,n,"value"),i.times=t,i.values=n}return e.parse!==void 0?e.parse(i):new e(i.name,i.times,i.values,i.interpolation)}function kg(i){try{let e=i.slice(i.indexOf(":")+1);return new URL(e).protocol==="blob:"}catch{return!1}}function Wg(i,e){return i.distance-e.distance}function _d(i,e,t,n){let r=!0;if(i.layers.test(e.layers)&&i.raycast(e,t)===!1&&(r=!1),r===!0&&n===!0){let s=i.children;for(let a=0,o=s.length;a<o;a++)_d(s[a],e,t,!0)}}function $d(i,e,t,n){let r=TS(n);switch(t){case Fd:return i*e;case Ol:return i*e/r.components*r.byteLength;case Fl:return i*e/r.components*r.byteLength;case Xr:return i*e*2/r.components*r.byteLength;case Ul:return i*e*2/r.components*r.byteLength;case Ud:return i*e*3/r.components*r.byteLength;case ci:return i*e*4/r.components*r.byteLength;case kl:return i*e*4/r.components*r.byteLength;case Io:case Po:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case Lo:case Do:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case zl:case Gl:return Math.max(i,16)*Math.max(e,8)/4;case Bl:case Hl:return Math.max(i,8)*Math.max(e,8)/2;case Vl:case Wl:case $l:case jl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case ql:case No:case Xl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Kl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Yl:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case Jl:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case Zl:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case Ql:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case eh:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case th:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case nh:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case ih:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case rh:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case sh:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case ah:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case oh:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case ch:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case lh:case hh:case uh:return Math.ceil(i/4)*Math.ceil(e/4)*16;case dh:case fh:return Math.ceil(i/4)*Math.ceil(e/4)*8;case Oo:case ph:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function TS(i){switch(i){case Qn:case Ld:return{byteLength:1,components:1};case ba:case Dd:case Gn:return{byteLength:2,components:1};case Dl:case Nl:return{byteLength:2,components:4};case Oi:case Ll:case Tn:return{byteLength:4,components:1};case Nd:case Od:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}var qg,vd,$g,Eo,jg,qr,Pi,An,Dn,Ji,fs,Sd,wd,Md,Xg,Dr,Kg,Yg,Jg,Zg,Qg,e0,t0,n0,Yc,Jc,i0,r0,s0,a0,o0,c0,l0,h0,u0,Zc,Qc,el,ps,tl,nl,il,rl,Rl,d0,f0,Ni,Ad,Td,Ed,Ro,Rd,Cd,Id,ld,p0,Pd,$r,As,Cl,Il,Co,Nr,Kn,ra,on,Pl,Ts,zt,ga,xi,Qn,Ld,Dd,ba,Ll,Oi,Tn,Gn,Dl,Nl,xa,Nd,Od,Fd,Ud,ci,Wi,jr,Ol,Fl,Xr,Ul,kl,Io,Po,Lo,Do,Bl,zl,Hl,Gl,Vl,Wl,ql,$l,jl,No,Xl,Kl,Yl,Jl,Zl,Ql,eh,th,nh,ih,rh,sh,ah,oh,ch,lh,hh,uh,dh,fh,Oo,ph,_a,Fo,m0,ms,gs,Kc,hd,hs,us,Za,mh,Uo,kd,ko,ya,g0,Bo,b0,Fi,Xt,bn,Qa,Dt,ls,ud,x0,_0,y0,gh,v0,S0,bh,w0,sl,Bd,Ci,sa,cg,oa,R0,Li,In,lg,Ya,bs,Hd,jd,dt,Pt,Xd,W,Uu,hg,Kd,ct,ku,ug,dg,ut,Vs,ol,Hv,ca,Gv,zu,xn,Yd,kt,cl,Hn,to,ll,El,ot,Ws,Ai,Vv,Wv,Tr,Mc,ri,fg,pg,qi,la,qv,mg,qs,ar,Ac,Ga,$v,jv,gg,bg,xg,_g,Xv,$s,Hu,qt,pn,Kv,ha,C0,Er,Tc,Ve,Pn,no,Or,Ti,or,Vu,cr,js,Xs,yg,Wu,qu,$u,ju,Xu,Ku,Lr,rn,lr,Ei,Ec,Ks,Ys,Js,Rr,Cr,ss,Va,Rc,Cc,as,dr,Fr,fn,Ic,Qv,Kt,io,ro,Qt,eS,Wa,Ju,Yn,tS,pi,Zu,Zs,si,qa,vn,mn,Ur,zn,kr,nS,Ln,hr,Qu,Pc,Ir,ed,Lc,td,Br,gn,vg,os,Dc,Sg,Nc,Oc,Fc,nd,Uc,wg,kc,xt,$a,Mg,Ag,rS,Tg,zc,id,Eg,rd,so,ua,xs,Rg,sS,ao,zr,Qs,Cg,Hc,Ig,aS,ja,Xa,_s,sd,oS,cS,Gi,cs,lS,Gc,da,ys,hl,ul,Pg,Ka,Vc,ad,Lg,vs,Dg,Ng,fa,oo,pa,Og,dd,qc,$c,co,lo,Ss,pr,dl,ho,Hr,uo,mi,Gr,fo,I0,uS,dS,ai,fl,gi,Jn,po,pl,ml,mo,$i,gl,go,bl,xl,Zn,mr,bo,ji,_l,Xi,gr,Ki,bi,Vi,yl,L0,oi,ur,pd,Yi,ea,vl,xo,_o,Vr,ma,od,Bg,zg,yo,jc,Xc,Hi,vo,Pr,Hg,Gg,an,md,So,gd,ws,Wr,bd,Di,Sl,wo,br,cd,Mo,ta,na,wl,Ml,Al,Wd,bS,qd,xS,_S,yS,vS,SS,wS,MS,xd,Ut,Tl,AS,Ms,Vg,Ao,Jd,yd,To,Zd=un(()=>{qg=0,vd=1,$g=2,Eo=1,jg=2,qr=3,Pi=0,An=1,Dn=2,Ji=0,fs=1,Sd=2,wd=3,Md=4,Xg=5,Dr=100,Kg=101,Yg=102,Jg=103,Zg=104,Qg=200,e0=201,t0=202,n0=203,Yc=204,Jc=205,i0=206,r0=207,s0=208,a0=209,o0=210,c0=211,l0=212,h0=213,u0=214,Zc=0,Qc=1,el=2,ps=3,tl=4,nl=5,il=6,rl=7,Rl=0,d0=1,f0=2,Ni=0,Ad=1,Td=2,Ed=3,Ro=4,Rd=5,Cd=6,Id=7,ld="attached",p0="detached",Pd=300,$r=301,As=302,Cl=303,Il=304,Co=306,Nr=1e3,Kn=1001,ra=1002,on=1003,Pl=1004,Ts=1005,zt=1006,ga=1007,xi=1008,Qn=1009,Ld=1010,Dd=1011,ba=1012,Ll=1013,Oi=1014,Tn=1015,Gn=1016,Dl=1017,Nl=1018,xa=1020,Nd=35902,Od=35899,Fd=1021,Ud=1022,ci=1023,Wi=1026,jr=1027,Ol=1028,Fl=1029,Xr=1030,Ul=1031,kl=1033,Io=33776,Po=33777,Lo=33778,Do=33779,Bl=35840,zl=35841,Hl=35842,Gl=35843,Vl=36196,Wl=37492,ql=37496,$l=37488,jl=37489,No=37490,Xl=37491,Kl=37808,Yl=37809,Jl=37810,Zl=37811,Ql=37812,eh=37813,th=37814,nh=37815,ih=37816,rh=37817,sh=37818,ah=37819,oh=37820,ch=37821,lh=36492,hh=36494,uh=36495,dh=36283,fh=36284,Oo=36285,ph=36286,_a=2200,Fo=2201,m0=2202,ms=2300,gs=2301,Kc=2302,hd=2303,hs=2400,us=2401,Za=2402,mh=2500,Uo=2501,kd=0,ko=1,ya=2,g0=3200,Bo=0,b0=1,Fi="",Xt="srgb",bn="srgb-linear",Qa="linear",Dt="srgb",ls=7680,ud=519,x0=512,_0=513,y0=514,gh=515,v0=516,S0=517,bh=518,w0=519,sl=35044,Bd="300 es",Ci=2e3,sa=2001;cg={},oa=null;R0={[Zc]:Qc,[el]:il,[tl]:rl,[ps]:nl,[Qc]:Zc,[il]:el,[rl]:tl,[nl]:ps},Li=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let r=n.slice(0);for(let s=0,a=r.length;s<a;s++)r[s].call(this,e);e.target=null}}},In=["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"],lg=1234567,Ya=Math.PI/180,bs=180/Math.PI;Hd={DEG2RAD:Ya,RAD2DEG:bs,generateUUID:Ii,clamp:bt,euclideanModulo:zd,mapLinear:Mv,inverseLerp:Av,lerp:Ja,damp:Tv,pingpong:Ev,smoothstep:Rv,smootherstep:Cv,randInt:Iv,randFloat:Pv,randFloatSpread:Lv,seededRandom:Dv,degToRad:Nv,radToDeg:Ov,isPowerOfTwo:Fv,ceilPowerOfTwo:Uv,floorPowerOfTwo:kv,setQuaternionFromProperEuler:Bv,normalize:Nt,denormalize:Ri},jd=class jd{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=bt(this.x,e.x,t.x),this.y=bt(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=bt(this.x,e,t),this.y=bt(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(bt(n,e,t))}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(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.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(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(bt(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),s=this.x-e.x,a=this.y-e.y;return this.x=s*n-a*r+e.x,this.y=s*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};jd.prototype.isVector2=!0;dt=jd,Pt=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,s,a,o){let l=n[r+0],c=n[r+1],h=n[r+2],d=n[r+3],f=s[a+0],p=s[a+1],x=s[a+2],y=s[a+3];if(d!==y||l!==f||c!==p||h!==x){let b=l*f+c*p+h*x+d*y;b<0&&(f=-f,p=-p,x=-x,y=-y,b=-b);let g=1-o;if(b<.9995){let S=Math.acos(b),A=Math.sin(S);g=Math.sin(g*S)/A,o=Math.sin(o*S)/A,l=l*g+f*o,c=c*g+p*o,h=h*g+x*o,d=d*g+y*o}else{l=l*g+f*o,c=c*g+p*o,h=h*g+x*o,d=d*g+y*o;let S=1/Math.sqrt(l*l+c*c+h*h+d*d);l*=S,c*=S,h*=S,d*=S}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=d}static multiplyQuaternionsFlat(e,t,n,r,s,a){let o=n[r],l=n[r+1],c=n[r+2],h=n[r+3],d=s[a],f=s[a+1],p=s[a+2],x=s[a+3];return e[t]=o*x+h*d+l*p-c*f,e[t+1]=l*x+h*f+c*d-o*p,e[t+2]=c*x+h*p+o*f-l*d,e[t+3]=h*x-o*d-l*f-c*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,s=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(n/2),h=o(r/2),d=o(s/2),f=l(n/2),p=l(r/2),x=l(s/2);switch(a){case"XYZ":this._x=f*h*d+c*p*x,this._y=c*p*d-f*h*x,this._z=c*h*x+f*p*d,this._w=c*h*d-f*p*x;break;case"YXZ":this._x=f*h*d+c*p*x,this._y=c*p*d-f*h*x,this._z=c*h*x-f*p*d,this._w=c*h*d+f*p*x;break;case"ZXY":this._x=f*h*d-c*p*x,this._y=c*p*d+f*h*x,this._z=c*h*x+f*p*d,this._w=c*h*d-f*p*x;break;case"ZYX":this._x=f*h*d-c*p*x,this._y=c*p*d+f*h*x,this._z=c*h*x-f*p*d,this._w=c*h*d+f*p*x;break;case"YZX":this._x=f*h*d+c*p*x,this._y=c*p*d+f*h*x,this._z=c*h*x-f*p*d,this._w=c*h*d-f*p*x;break;case"XZY":this._x=f*h*d-c*p*x,this._y=c*p*d-f*h*x,this._z=c*h*x+f*p*d,this._w=c*h*d+f*p*x;break;default:Ke("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],s=t[8],a=t[1],o=t[5],l=t[9],c=t[2],h=t[6],d=t[10],f=n+o+d;if(f>0){let p=.5/Math.sqrt(f+1);this._w=.25/p,this._x=(h-l)*p,this._y=(s-c)*p,this._z=(a-r)*p}else if(n>o&&n>d){let p=2*Math.sqrt(1+n-o-d);this._w=(h-l)/p,this._x=.25*p,this._y=(r+a)/p,this._z=(s+c)/p}else if(o>d){let p=2*Math.sqrt(1+o-n-d);this._w=(s-c)/p,this._x=(r+a)/p,this._y=.25*p,this._z=(l+h)/p}else{let p=2*Math.sqrt(1+d-n-o);this._w=(a-r)/p,this._x=(s+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(bt(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),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(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._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 e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,s=e._z,a=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=n*h+a*o+r*c-s*l,this._y=r*h+a*l+s*o-n*c,this._z=s*h+a*c+n*l-r*o,this._w=a*h-n*o-r*l-s*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,s=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,s=-s,a=-a,o=-o);let l=1-t;if(o<.9995){let c=Math.acos(o),h=Math.sin(c);l=Math.sin(l*c)/h,t=Math.sin(t*c)/h,this._x=this._x*l+n*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this._onChangeCallback()}else this._x=this._x*l+n*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},Xd=class Xd{constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(hg.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(hg.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*r,this.y=s[1]*t+s[4]*n+s[7]*r,this.z=s[2]*t+s[5]*n+s[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,s=e.elements,a=1/(s[3]*t+s[7]*n+s[11]*r+s[15]);return this.x=(s[0]*t+s[4]*n+s[8]*r+s[12])*a,this.y=(s[1]*t+s[5]*n+s[9]*r+s[13])*a,this.z=(s[2]*t+s[6]*n+s[10]*r+s[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,s=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*r-o*n),h=2*(o*t-s*r),d=2*(s*n-a*t);return this.x=t+l*c+a*d-o*h,this.y=n+l*h+o*c-s*d,this.z=r+l*d+s*h-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*r,this.y=s[1]*t+s[5]*n+s[9]*r,this.z=s[2]*t+s[6]*n+s[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=bt(this.x,e.x,t.x),this.y=bt(this.y,e.y,t.y),this.z=bt(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=bt(this.x,e,t),this.y=bt(this.y,e,t),this.z=bt(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(bt(n,e,t))}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(e){return this.x*e.x+this.y*e.y+this.z*e.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(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,s=e.z,a=t.x,o=t.y,l=t.z;return this.x=r*l-s*o,this.y=s*a-n*l,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Uu.copy(this).projectOnVector(e),this.sub(Uu)}reflect(e){return this.sub(Uu.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(bt(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};Xd.prototype.isVector3=!0;W=Xd,Uu=new W,hg=new Pt,Kd=class Kd{constructor(e,t,n,r,s,a,o,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,s,a,o,l,c)}set(e,t,n,r,s,a,o,l,c){let h=this.elements;return h[0]=e,h[1]=r,h[2]=o,h[3]=t,h[4]=s,h[5]=l,h[6]=n,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,s=this.elements,a=n[0],o=n[3],l=n[6],c=n[1],h=n[4],d=n[7],f=n[2],p=n[5],x=n[8],y=r[0],b=r[3],g=r[6],S=r[1],A=r[4],T=r[7],N=r[2],P=r[5],U=r[8];return s[0]=a*y+o*S+l*N,s[3]=a*b+o*A+l*P,s[6]=a*g+o*T+l*U,s[1]=c*y+h*S+d*N,s[4]=c*b+h*A+d*P,s[7]=c*g+h*T+d*U,s[2]=f*y+p*S+x*N,s[5]=f*b+p*A+x*P,s[8]=f*g+p*T+x*U,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*a*h-t*o*c-n*s*h+n*o*l+r*s*c-r*a*l}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],d=h*a-o*c,f=o*l-h*s,p=c*s-a*l,x=t*d+n*f+r*p;if(x===0)return this.set(0,0,0,0,0,0,0,0,0);let y=1/x;return e[0]=d*y,e[1]=(r*c-h*n)*y,e[2]=(o*n-r*a)*y,e[3]=f*y,e[4]=(h*t-r*l)*y,e[5]=(r*s-o*t)*y,e[6]=p*y,e[7]=(n*l-c*t)*y,e[8]=(a*t-n*s)*y,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,s,a,o){let l=Math.cos(s),c=Math.sin(s);return this.set(n*l,n*c,-n*(l*a+c*o)+a+e,-r*c,r*l,-r*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(ku.makeScale(e,t)),this}rotate(e){return this.premultiply(ku.makeRotation(-e)),this}translate(e,t){return this.premultiply(ku.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let r=0;r<9;r++)if(t[r]!==n[r])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}};Kd.prototype.isMatrix3=!0;ct=Kd,ku=new ct,ug=new ct().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),dg=new ct().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);ut=zv();ol=class{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Vs===void 0&&(Vs=aa("canvas")),Vs.width=e.width,Vs.height=e.height;let r=Vs.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),n=Vs}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){let t=aa("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),s=r.data;for(let a=0;a<s.length;a++)s[a]=fr(s[a]/255)*255;return n.putImageData(r,0,0),t}else if(e.data){let t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(fr(t[n]/255)*255):t[n]=fr(t[n]);return{data:t,width:e.width,height:e.height}}else return Ke("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}},Hv=0,ca=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Hv++}),this.uuid=Ii(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:""},r=this.data;if(r!==null){let s;if(Array.isArray(r)){s=[];for(let a=0,o=r.length;a<o;a++)r[a].isDataTexture?s.push(Bu(r[a].image)):s.push(Bu(r[a]))}else s=Bu(r);n.url=s}return t||(e.images[this.uuid]=n),n}};Gv=0,zu=new W,xn=class i extends Li{constructor(e=i.DEFAULT_IMAGE,t=i.DEFAULT_MAPPING,n=Kn,r=Kn,s=zt,a=xi,o=ci,l=Qn,c=i.DEFAULT_ANISOTROPY,h=Fi){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Gv++}),this.uuid=Ii(),this.name="",this.source=new ca(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=r,this.magFilter=s,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new dt(0,0),this.repeat=new dt(1,1),this.center=new dt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ct,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(zu).x}get height(){return this.source.getSize(zu).y}get depth(){return this.source.getSize(zu).z}get image(){return this.source.data}set image(e){this.source.data=e}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(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){Ke(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Ke(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).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),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Pd)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Nr:e.x=e.x-Math.floor(e.x);break;case Kn:e.x=e.x<0?0:1;break;case ra:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Nr:e.y=e.y-Math.floor(e.y);break;case Kn:e.y=e.y<0?0:1;break;case ra:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};xn.DEFAULT_IMAGE=null;xn.DEFAULT_MAPPING=Pd;xn.DEFAULT_ANISOTROPY=1;Yd=class Yd{constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*s,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*s,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*s,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,s,l=e.elements,c=l[0],h=l[4],d=l[8],f=l[1],p=l[5],x=l[9],y=l[2],b=l[6],g=l[10];if(Math.abs(h-f)<.01&&Math.abs(d-y)<.01&&Math.abs(x-b)<.01){if(Math.abs(h+f)<.1&&Math.abs(d+y)<.1&&Math.abs(x+b)<.1&&Math.abs(c+p+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let A=(c+1)/2,T=(p+1)/2,N=(g+1)/2,P=(h+f)/4,U=(d+y)/4,v=(x+b)/4;return A>T&&A>N?A<.01?(n=0,r=.707106781,s=.707106781):(n=Math.sqrt(A),r=P/n,s=U/n):T>N?T<.01?(n=.707106781,r=0,s=.707106781):(r=Math.sqrt(T),n=P/r,s=v/r):N<.01?(n=.707106781,r=.707106781,s=0):(s=Math.sqrt(N),n=U/s,r=v/s),this.set(n,r,s,t),this}let S=Math.sqrt((b-x)*(b-x)+(d-y)*(d-y)+(f-h)*(f-h));return Math.abs(S)<.001&&(S=1),this.x=(b-x)/S,this.y=(d-y)/S,this.z=(f-h)/S,this.w=Math.acos((c+p+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=bt(this.x,e.x,t.x),this.y=bt(this.y,e.y,t.y),this.z=bt(this.z,e.z,t.z),this.w=bt(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=bt(this.x,e,t),this.y=bt(this.y,e,t),this.z=bt(this.z,e,t),this.w=bt(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(bt(n,e,t))}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(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.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(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),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}};Yd.prototype.isVector4=!0;kt=Yd,cl=class extends Li{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:zt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new kt(0,0,e,t),this.scissorTest=!1,this.viewport=new kt(0,0,e,t),this.textures=[];let r={width:e,height:t,depth:n.depth},s=new xn(r),a=n.count;for(let o=0;o<a;o++)this.textures[o]=s.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){let t={minFilter:zt,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,s=this.textures.length;r<s;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let r=Object.assign({},e.textures[t].image);this.textures[t].source=new ca(r)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this.multiview=e.multiview,this}dispose(){this.dispatchEvent({type:"dispose"})}},Hn=class extends cl{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},to=class extends xn{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=on,this.minFilter=on,this.wrapR=Kn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},ll=class extends xn{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=on,this.minFilter=on,this.wrapR=Kn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},El=class El{constructor(e,t,n,r,s,a,o,l,c,h,d,f,p,x,y,b){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,r,s,a,o,l,c,h,d,f,p,x,y,b)}set(e,t,n,r,s,a,o,l,c,h,d,f,p,x,y,b){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=s,g[5]=a,g[9]=o,g[13]=l,g[2]=c,g[6]=h,g[10]=d,g[14]=f,g[3]=p,g[7]=x,g[11]=y,g[15]=b,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 El().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();let t=this.elements,n=e.elements,r=1/Ws.setFromMatrixColumn(e,0).length(),s=1/Ws.setFromMatrixColumn(e,1).length(),a=1/Ws.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*s,t[5]=n[5]*s,t[6]=n[6]*s,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,s=e.z,a=Math.cos(n),o=Math.sin(n),l=Math.cos(r),c=Math.sin(r),h=Math.cos(s),d=Math.sin(s);if(e.order==="XYZ"){let f=a*h,p=a*d,x=o*h,y=o*d;t[0]=l*h,t[4]=-l*d,t[8]=c,t[1]=p+x*c,t[5]=f-y*c,t[9]=-o*l,t[2]=y-f*c,t[6]=x+p*c,t[10]=a*l}else if(e.order==="YXZ"){let f=l*h,p=l*d,x=c*h,y=c*d;t[0]=f+y*o,t[4]=x*o-p,t[8]=a*c,t[1]=a*d,t[5]=a*h,t[9]=-o,t[2]=p*o-x,t[6]=y+f*o,t[10]=a*l}else if(e.order==="ZXY"){let f=l*h,p=l*d,x=c*h,y=c*d;t[0]=f-y*o,t[4]=-a*d,t[8]=x+p*o,t[1]=p+x*o,t[5]=a*h,t[9]=y-f*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){let f=a*h,p=a*d,x=o*h,y=o*d;t[0]=l*h,t[4]=x*c-p,t[8]=f*c+y,t[1]=l*d,t[5]=y*c+f,t[9]=p*c-x,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){let f=a*l,p=a*c,x=o*l,y=o*c;t[0]=l*h,t[4]=y-f*d,t[8]=x*d+p,t[1]=d,t[5]=a*h,t[9]=-o*h,t[2]=-c*h,t[6]=p*d+x,t[10]=f-y*d}else if(e.order==="XZY"){let f=a*l,p=a*c,x=o*l,y=o*c;t[0]=l*h,t[4]=-d,t[8]=c*h,t[1]=f*d+y,t[5]=a*h,t[9]=p*d-x,t[2]=x*d-p,t[6]=o*h,t[10]=y*d+f}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Vv,e,Wv)}lookAt(e,t,n){let r=this.elements;return ri.subVectors(e,t),ri.lengthSq()===0&&(ri.z=1),ri.normalize(),Tr.crossVectors(n,ri),Tr.lengthSq()===0&&(Math.abs(n.z)===1?ri.x+=1e-4:ri.z+=1e-4,ri.normalize(),Tr.crossVectors(n,ri)),Tr.normalize(),Mc.crossVectors(ri,Tr),r[0]=Tr.x,r[4]=Mc.x,r[8]=ri.x,r[1]=Tr.y,r[5]=Mc.y,r[9]=ri.y,r[2]=Tr.z,r[6]=Mc.z,r[10]=ri.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,s=this.elements,a=n[0],o=n[4],l=n[8],c=n[12],h=n[1],d=n[5],f=n[9],p=n[13],x=n[2],y=n[6],b=n[10],g=n[14],S=n[3],A=n[7],T=n[11],N=n[15],P=r[0],U=r[4],v=r[8],I=r[12],B=r[1],k=r[5],V=r[9],J=r[13],L=r[2],E=r[6],D=r[10],O=r[14],H=r[3],Y=r[7],le=r[11],fe=r[15];return s[0]=a*P+o*B+l*L+c*H,s[4]=a*U+o*k+l*E+c*Y,s[8]=a*v+o*V+l*D+c*le,s[12]=a*I+o*J+l*O+c*fe,s[1]=h*P+d*B+f*L+p*H,s[5]=h*U+d*k+f*E+p*Y,s[9]=h*v+d*V+f*D+p*le,s[13]=h*I+d*J+f*O+p*fe,s[2]=x*P+y*B+b*L+g*H,s[6]=x*U+y*k+b*E+g*Y,s[10]=x*v+y*V+b*D+g*le,s[14]=x*I+y*J+b*O+g*fe,s[3]=S*P+A*B+T*L+N*H,s[7]=S*U+A*k+T*E+N*Y,s[11]=S*v+A*V+T*D+N*le,s[15]=S*I+A*J+T*O+N*fe,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],s=e[12],a=e[1],o=e[5],l=e[9],c=e[13],h=e[2],d=e[6],f=e[10],p=e[14],x=e[3],y=e[7],b=e[11],g=e[15],S=l*p-c*f,A=o*p-c*d,T=o*f-l*d,N=a*p-c*h,P=a*f-l*h,U=a*d-o*h;return t*(y*S-b*A+g*T)-n*(x*S-b*N+g*P)+r*(x*A-y*N+g*U)-s*(x*T-y*P+b*U)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],d=e[9],f=e[10],p=e[11],x=e[12],y=e[13],b=e[14],g=e[15],S=t*o-n*a,A=t*l-r*a,T=t*c-s*a,N=n*l-r*o,P=n*c-s*o,U=r*c-s*l,v=h*y-d*x,I=h*b-f*x,B=h*g-p*x,k=d*b-f*y,V=d*g-p*y,J=f*g-p*b,L=S*J-A*V+T*k+N*B-P*I+U*v;if(L===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let E=1/L;return e[0]=(o*J-l*V+c*k)*E,e[1]=(r*V-n*J-s*k)*E,e[2]=(y*U-b*P+g*N)*E,e[3]=(f*P-d*U-p*N)*E,e[4]=(l*B-a*J-c*I)*E,e[5]=(t*J-r*B+s*I)*E,e[6]=(b*T-x*U-g*A)*E,e[7]=(h*U-f*T+p*A)*E,e[8]=(a*V-o*B+c*v)*E,e[9]=(n*B-t*V-s*v)*E,e[10]=(x*P-y*T+g*S)*E,e[11]=(d*T-h*P-p*S)*E,e[12]=(o*I-a*k-l*v)*E,e[13]=(t*k-n*I+r*v)*E,e[14]=(y*A-x*N-b*S)*E,e[15]=(h*N-d*A+f*S)*E,this}scale(e){let t=this.elements,n=e.x,r=e.y,s=e.z;return t[0]*=n,t[4]*=r,t[8]*=s,t[1]*=n,t[5]*=r,t[9]*=s,t[2]*=n,t[6]*=r,t[10]*=s,t[3]*=n,t[7]*=r,t[11]*=s,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),s=1-n,a=e.x,o=e.y,l=e.z,c=s*a,h=s*o;return this.set(c*a+n,c*o-r*l,c*l+r*o,0,c*o+r*l,h*o+n,h*l-r*a,0,c*l-r*o,h*l+r*a,s*l*l+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,s,a){return this.set(1,n,s,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,s=t._x,a=t._y,o=t._z,l=t._w,c=s+s,h=a+a,d=o+o,f=s*c,p=s*h,x=s*d,y=a*h,b=a*d,g=o*d,S=l*c,A=l*h,T=l*d,N=n.x,P=n.y,U=n.z;return r[0]=(1-(y+g))*N,r[1]=(p+T)*N,r[2]=(x-A)*N,r[3]=0,r[4]=(p-T)*P,r[5]=(1-(f+g))*P,r[6]=(b+S)*P,r[7]=0,r[8]=(x+A)*U,r[9]=(b-S)*U,r[10]=(1-(f+y))*U,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let s=this.determinant();if(s===0)return n.set(1,1,1),t.identity(),this;let a=Ws.set(r[0],r[1],r[2]).length(),o=Ws.set(r[4],r[5],r[6]).length(),l=Ws.set(r[8],r[9],r[10]).length();s<0&&(a=-a),Ai.copy(this);let c=1/a,h=1/o,d=1/l;return Ai.elements[0]*=c,Ai.elements[1]*=c,Ai.elements[2]*=c,Ai.elements[4]*=h,Ai.elements[5]*=h,Ai.elements[6]*=h,Ai.elements[8]*=d,Ai.elements[9]*=d,Ai.elements[10]*=d,t.setFromRotationMatrix(Ai),n.x=a,n.y=o,n.z=l,this}makePerspective(e,t,n,r,s,a,o=Ci,l=!1){let c=this.elements,h=2*s/(t-e),d=2*s/(n-r),f=(t+e)/(t-e),p=(n+r)/(n-r),x,y;if(l)x=s/(a-s),y=a*s/(a-s);else if(o===Ci)x=-(a+s)/(a-s),y=-2*a*s/(a-s);else if(o===sa)x=-a/(a-s),y=-a*s/(a-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=h,c[4]=0,c[8]=f,c[12]=0,c[1]=0,c[5]=d,c[9]=p,c[13]=0,c[2]=0,c[6]=0,c[10]=x,c[14]=y,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,s,a,o=Ci,l=!1){let c=this.elements,h=2/(t-e),d=2/(n-r),f=-(t+e)/(t-e),p=-(n+r)/(n-r),x,y;if(l)x=1/(a-s),y=a/(a-s);else if(o===Ci)x=-2/(a-s),y=-(a+s)/(a-s);else if(o===sa)x=-1/(a-s),y=-s/(a-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=h,c[4]=0,c[8]=0,c[12]=f,c[1]=0,c[5]=d,c[9]=0,c[13]=p,c[2]=0,c[6]=0,c[10]=x,c[14]=y,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let r=0;r<16;r++)if(t[r]!==n[r])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}};El.prototype.isMatrix4=!0;ot=El,Ws=new W,Ai=new ot,Vv=new W(0,0,0),Wv=new W(1,1,1),Tr=new W,Mc=new W,ri=new W,fg=new ot,pg=new Pt,qi=class i{constructor(e=0,t=0,n=0,r=i.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=r}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,s=r[0],a=r[4],o=r[8],l=r[1],c=r[5],h=r[9],d=r[2],f=r[6],p=r[10];switch(t){case"XYZ":this._y=Math.asin(bt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-a,s)):(this._x=Math.atan2(f,c),this._z=0);break;case"YXZ":this._x=Math.asin(-bt(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,s),this._z=0);break;case"ZXY":this._x=Math.asin(bt(f,-1,1)),Math.abs(f)<.9999999?(this._y=Math.atan2(-d,p),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-bt(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(f,p),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(bt(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-d,s)):(this._x=0,this._y=Math.atan2(o,p));break;case"XZY":this._z=Math.asin(-bt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(f,c),this._y=Math.atan2(o,s)):(this._x=Math.atan2(-h,p),this._y=0);break;default:Ke("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return fg.makeRotationFromQuaternion(e),this.setFromRotationMatrix(fg,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return pg.setFromEuler(this),this.setFromQuaternion(pg,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};qi.DEFAULT_ORDER="XYZ";la=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}},qv=0,mg=new W,qs=new Pt,ar=new ot,Ac=new W,Ga=new W,$v=new W,jv=new Pt,gg=new W(1,0,0),bg=new W(0,1,0),xg=new W(0,0,1),_g={type:"added"},Xv={type:"removed"},$s={type:"childadded",child:null},Hu={type:"childremoved",child:null},qt=class i extends Li{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:qv++}),this.uuid=Ii(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=i.DEFAULT_UP.clone();let e=new W,t=new qi,n=new Pt,r=new W(1,1,1);function s(){n.setFromEuler(t,!1)}function a(){t.setFromQuaternion(n,void 0,!1)}t._onChange(s),n._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:r},modelViewMatrix:{value:new ot},normalMatrix:{value:new ct}}),this.matrix=new ot,this.matrixWorld=new ot,this.matrixAutoUpdate=i.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=i.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new la,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(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return qs.setFromAxisAngle(e,t),this.quaternion.multiply(qs),this}rotateOnWorldAxis(e,t){return qs.setFromAxisAngle(e,t),this.quaternion.premultiply(qs),this}rotateX(e){return this.rotateOnAxis(gg,e)}rotateY(e){return this.rotateOnAxis(bg,e)}rotateZ(e){return this.rotateOnAxis(xg,e)}translateOnAxis(e,t){return mg.copy(e).applyQuaternion(this.quaternion),this.position.add(mg.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(gg,e)}translateY(e){return this.translateOnAxis(bg,e)}translateZ(e){return this.translateOnAxis(xg,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(ar.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Ac.copy(e):Ac.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),Ga.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?ar.lookAt(Ga,Ac,this.up):ar.lookAt(Ac,Ga,this.up),this.quaternion.setFromRotationMatrix(ar),r&&(ar.extractRotation(r.matrixWorld),qs.setFromRotationMatrix(ar),this.quaternion.premultiply(qs.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(et("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(_g),$s.child=e,this.dispatchEvent($s),$s.child=null):et("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Xv),Hu.child=e,this.dispatchEvent(Hu),Hu.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),ar.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),ar.multiply(e.parent.matrixWorld)),e.applyMatrix4(ar),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(_g),$s.child=e,this.dispatchEvent($s),$s.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let a=this.children[n].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let s=0,a=r.length;s<a;s++)r[s].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ga,e,$v),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ga,jv,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,r=e.z,s=this.matrix.elements;s[12]+=t-s[0]*t-s[4]*n-s[8]*r,s[13]+=n-s[1]*t-s[5]*n-s[9]*r,s[14]+=r-s[2]*t-s[6]*n-s[10]*r}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let r=this.children;for(let s=0,a=r.length;s<a;s++)r[s].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});let r={};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),this.static!==!1&&(r.static=this.static),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(o=>({...o})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function s(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=s(e.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c<h;c++){let d=l[c];s(e.shapes,d)}else s(e.shapes,l)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(s(e.materials,this.material[l]));r.material=o}else r.material=s(e.materials,this.material);if(this.children.length>0){r.children=[];for(let o=0;o<this.children.length;o++)r.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let o=0;o<this.animations.length;o++){let l=this.animations[o];r.animations.push(s(e.animations,l))}}if(t){let o=a(e.geometries),l=a(e.materials),c=a(e.textures),h=a(e.images),d=a(e.shapes),f=a(e.skeletons),p=a(e.animations),x=a(e.nodes);o.length>0&&(n.geometries=o),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),d.length>0&&(n.shapes=d),f.length>0&&(n.skeletons=f),p.length>0&&(n.animations=p),x.length>0&&(n.nodes=x)}return n.object=r,n;function a(o){let l=[];for(let c in o){let h=o[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){let r=e.children[n];this.add(r.clone())}return this}};qt.DEFAULT_UP=new W(0,1,0);qt.DEFAULT_MATRIX_AUTO_UPDATE=!0;qt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;pn=class extends qt{constructor(){super(),this.isGroup=!0,this.type="Group"}},Kv={type:"move"},ha=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new pn,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 pn,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new W,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new W),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new pn,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new W,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new W,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,s=null,a=null,o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(let y of e.hand.values()){let b=t.getJointPose(y,n),g=this._getHandJoint(c,y);b!==null&&(g.matrix.fromArray(b.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=b.radius),g.visible=b!==null}let h=c.joints["index-finger-tip"],d=c.joints["thumb-tip"],f=h.position.distanceTo(d.position),p=.02,x=.005;c.inputState.pinching&&f>p+x?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&f<=p-x&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,n),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&s!==null&&(r=s),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Kv)))}return o!==null&&(o.visible=r!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new pn;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},C0={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},Er={h:0,s:0,l:0},Tc={h:0,s:0,l:0};Ve=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Xt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,ut.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=ut.workingColorSpace){return this.r=e,this.g=t,this.b=n,ut.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=ut.workingColorSpace){if(e=zd(e,1),t=bt(t,0,1),n=bt(n,0,1),t===0)this.r=this.g=this.b=n;else{let s=n<=.5?n*(1+t):n+t-n*t,a=2*n-s;this.r=Gu(a,s,e+1/3),this.g=Gu(a,s,e),this.b=Gu(a,s,e-1/3)}return ut.colorSpaceToWorking(this,r),this}setStyle(e,t=Xt){function n(s){s!==void 0&&parseFloat(s)<1&&Ke("Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let s,a=r[1],o=r[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:Ke("Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let s=r[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);Ke("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Xt){let n=C0[e.toLowerCase()];return n!==void 0?this.setHex(n,t):Ke("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=fr(e.r),this.g=fr(e.g),this.b=fr(e.b),this}copyLinearToSRGB(e){return this.r=ia(e.r),this.g=ia(e.g),this.b=ia(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Xt){return ut.workingToColorSpace(Pn.copy(this),e),Math.round(bt(Pn.r*255,0,255))*65536+Math.round(bt(Pn.g*255,0,255))*256+Math.round(bt(Pn.b*255,0,255))}getHexString(e=Xt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ut.workingColorSpace){ut.workingToColorSpace(Pn.copy(this),t);let n=Pn.r,r=Pn.g,s=Pn.b,a=Math.max(n,r,s),o=Math.min(n,r,s),l,c,h=(o+a)/2;if(o===a)l=0,c=0;else{let d=a-o;switch(c=h<=.5?d/(a+o):d/(2-a-o),a){case n:l=(r-s)/d+(r<s?6:0);break;case r:l=(s-n)/d+2;break;case s:l=(n-r)/d+4;break}l/=6}return e.h=l,e.s=c,e.l=h,e}getRGB(e,t=ut.workingColorSpace){return ut.workingToColorSpace(Pn.copy(this),t),e.r=Pn.r,e.g=Pn.g,e.b=Pn.b,e}getStyle(e=Xt){ut.workingToColorSpace(Pn.copy(this),e);let t=Pn.r,n=Pn.g,r=Pn.b;return e!==Xt?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`}offsetHSL(e,t,n){return this.getHSL(Er),this.setHSL(Er.h+e,Er.s+t,Er.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Er),e.getHSL(Tc);let n=Ja(Er.h,Tc.h,t),r=Ja(Er.s,Tc.s,t),s=Ja(Er.l,Tc.l,t);return this.setHSL(n,r,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,s=e.elements;return this.r=s[0]*t+s[3]*n+s[6]*r,this.g=s[1]*t+s[4]*n+s[7]*r,this.b=s[2]*t+s[5]*n+s[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Pn=new Ve;Ve.NAMES=C0;no=class i{constructor(e,t=1,n=1e3){this.isFog=!0,this.name="",this.color=new Ve(e),this.near=t,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}}},Or=class extends qt{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 qi,this.environmentIntensity=1,this.environmentRotation=new qi,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},Ti=new W,or=new W,Vu=new W,cr=new W,js=new W,Xs=new W,yg=new W,Wu=new W,qu=new W,$u=new W,ju=new kt,Xu=new kt,Ku=new kt,Lr=class i{constructor(e=new W,t=new W,n=new W){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),Ti.subVectors(e,t),r.cross(Ti);let s=r.lengthSq();return s>0?r.multiplyScalar(1/Math.sqrt(s)):r.set(0,0,0)}static getBarycoord(e,t,n,r,s){Ti.subVectors(r,t),or.subVectors(n,t),Vu.subVectors(e,t);let a=Ti.dot(Ti),o=Ti.dot(or),l=Ti.dot(Vu),c=or.dot(or),h=or.dot(Vu),d=a*c-o*o;if(d===0)return s.set(0,0,0),null;let f=1/d,p=(c*l-o*h)*f,x=(a*h-o*l)*f;return s.set(1-p-x,x,p)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,cr)===null?!1:cr.x>=0&&cr.y>=0&&cr.x+cr.y<=1}static getInterpolation(e,t,n,r,s,a,o,l){return this.getBarycoord(e,t,n,r,cr)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,cr.x),l.addScaledVector(a,cr.y),l.addScaledVector(o,cr.z),l)}static getInterpolatedAttribute(e,t,n,r,s,a){return ju.setScalar(0),Xu.setScalar(0),Ku.setScalar(0),ju.fromBufferAttribute(e,t),Xu.fromBufferAttribute(e,n),Ku.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(ju,s.x),a.addScaledVector(Xu,s.y),a.addScaledVector(Ku,s.z),a}static isFrontFacing(e,t,n,r){return Ti.subVectors(n,t),or.subVectors(e,t),Ti.cross(or).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ti.subVectors(this.c,this.b),or.subVectors(this.a,this.b),Ti.cross(or).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return i.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return i.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,r,s){return i.getInterpolation(e,this.a,this.b,this.c,t,n,r,s)}containsPoint(e){return i.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return i.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,s=this.c,a,o;js.subVectors(r,n),Xs.subVectors(s,n),Wu.subVectors(e,n);let l=js.dot(Wu),c=Xs.dot(Wu);if(l<=0&&c<=0)return t.copy(n);qu.subVectors(e,r);let h=js.dot(qu),d=Xs.dot(qu);if(h>=0&&d<=h)return t.copy(r);let f=l*d-h*c;if(f<=0&&l>=0&&h<=0)return a=l/(l-h),t.copy(n).addScaledVector(js,a);$u.subVectors(e,s);let p=js.dot($u),x=Xs.dot($u);if(x>=0&&p<=x)return t.copy(s);let y=p*c-l*x;if(y<=0&&c>=0&&x<=0)return o=c/(c-x),t.copy(n).addScaledVector(Xs,o);let b=h*x-p*d;if(b<=0&&d-h>=0&&p-x>=0)return yg.subVectors(s,r),o=(d-h)/(d-h+(p-x)),t.copy(r).addScaledVector(yg,o);let g=1/(b+y+f);return a=y*g,o=f*g,t.copy(n).addScaledVector(js,a).addScaledVector(Xs,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},rn=class{constructor(e=new W(1/0,1/0,1/0),t=new W(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Ei.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Ei.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=Ei.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.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(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let s=n.getAttribute("position");if(t===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=s.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,Ei):Ei.fromBufferAttribute(s,a),Ei.applyMatrix4(e.matrixWorld),this.expandByPoint(Ei);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Ec.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),Ec.copy(n.boundingBox)),Ec.applyMatrix4(e.matrixWorld),this.union(Ec)}let r=e.children;for(let s=0,a=r.length;s<a;s++)this.expandByObject(r[s],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ei),Ei.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Va),Rc.subVectors(this.max,Va),Ks.subVectors(e.a,Va),Ys.subVectors(e.b,Va),Js.subVectors(e.c,Va),Rr.subVectors(Ys,Ks),Cr.subVectors(Js,Ys),ss.subVectors(Ks,Js);let t=[0,-Rr.z,Rr.y,0,-Cr.z,Cr.y,0,-ss.z,ss.y,Rr.z,0,-Rr.x,Cr.z,0,-Cr.x,ss.z,0,-ss.x,-Rr.y,Rr.x,0,-Cr.y,Cr.x,0,-ss.y,ss.x,0];return!Yu(t,Ks,Ys,Js,Rc)||(t=[1,0,0,0,1,0,0,0,1],!Yu(t,Ks,Ys,Js,Rc))?!1:(Cc.crossVectors(Rr,Cr),t=[Cc.x,Cc.y,Cc.z],Yu(t,Ks,Ys,Js,Rc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ei).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ei).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(lr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),lr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),lr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),lr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),lr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),lr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),lr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),lr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(lr),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},lr=[new W,new W,new W,new W,new W,new W,new W,new W],Ei=new W,Ec=new rn,Ks=new W,Ys=new W,Js=new W,Rr=new W,Cr=new W,ss=new W,Va=new W,Rc=new W,Cc=new W,as=new W;dr=Yv();Fr=class{static toHalfFloat(e){return Jv(e)}static fromHalfFloat(e){return Zv(e)}},fn=new W,Ic=new dt,Qv=0,Kt=class extends Li{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Qv++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=sl,this.updateRanges=[],this.gpuType=Tn,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,s=this.itemSize;r<s;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Ic.fromBufferAttribute(this,t),Ic.applyMatrix3(e),this.setXY(t,Ic.x,Ic.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)fn.fromBufferAttribute(this,t),fn.applyMatrix3(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)fn.fromBufferAttribute(this,t),fn.applyMatrix4(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)fn.fromBufferAttribute(this,t),fn.applyNormalMatrix(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)fn.fromBufferAttribute(this,t),fn.transformDirection(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Ri(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Nt(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Ri(t,this.array)),t}setX(e,t){return this.normalized&&(t=Nt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Ri(t,this.array)),t}setY(e,t){return this.normalized&&(t=Nt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Ri(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Nt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Ri(t,this.array)),t}setW(e,t){return this.normalized&&(t=Nt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Nt(t,this.array),n=Nt(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=Nt(t,this.array),n=Nt(n,this.array),r=Nt(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,s){return e*=this.itemSize,this.normalized&&(t=Nt(t,this.array),n=Nt(n,this.array),r=Nt(r,this.array),s=Nt(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==sl&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:"dispose"})}},io=class extends Kt{constructor(e,t,n){super(new Uint16Array(e),t,n)}},ro=class extends Kt{constructor(e,t,n){super(new Uint32Array(e),t,n)}},Qt=class extends Kt{constructor(e,t,n){super(new Float32Array(e),t,n)}},eS=new rn,Wa=new W,Ju=new W,Yn=class{constructor(e=new W,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t!==void 0?n.copy(t):eS.setFromPoints(e).getCenter(n);let r=0;for(let s=0,a=e.length;s<a;s++)r=Math.max(r,n.distanceToSquared(e[s]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Wa.subVectors(e,this.center);let t=Wa.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),r=(n-this.radius)*.5;this.center.addScaledVector(Wa,r/n),this.radius+=r}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Ju.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Wa.copy(e.center).add(Ju)),this.expandByPoint(Wa.copy(e.center).sub(Ju))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},tS=0,pi=new ot,Zu=new qt,Zs=new W,si=new rn,qa=new rn,vn=new W,mn=class i extends Li{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:tS++}),this.uuid=Ii(),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={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(wv(e)?ro:io)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let s=new ct().getNormalMatrix(e);n.applyNormalMatrix(s),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return pi.makeRotationFromQuaternion(e),this.applyMatrix4(pi),this}rotateX(e){return pi.makeRotationX(e),this.applyMatrix4(pi),this}rotateY(e){return pi.makeRotationY(e),this.applyMatrix4(pi),this}rotateZ(e){return pi.makeRotationZ(e),this.applyMatrix4(pi),this}translate(e,t,n){return pi.makeTranslation(e,t,n),this.applyMatrix4(pi),this}scale(e,t,n){return pi.makeScale(e,t,n),this.applyMatrix4(pi),this}lookAt(e){return Zu.lookAt(e),Zu.updateMatrix(),this.applyMatrix4(Zu.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Zs).negate(),this.translate(Zs.x,Zs.y,Zs.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let n=[];for(let r=0,s=e.length;r<s;r++){let a=e[r];n.push(a.x,a.y,a.z||0)}this.setAttribute("position",new Qt(n,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let s=e[r];t.setXYZ(r,s.x,s.y,s.z||0)}e.length>t.count&&Ke("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new rn);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){et("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new W(-1/0,-1/0,-1/0),new W(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,r=t.length;n<r;n++){let s=t[n];si.setFromBufferAttribute(s),this.morphTargetsRelative?(vn.addVectors(this.boundingBox.min,si.min),this.boundingBox.expandByPoint(vn),vn.addVectors(this.boundingBox.max,si.max),this.boundingBox.expandByPoint(vn)):(this.boundingBox.expandByPoint(si.min),this.boundingBox.expandByPoint(si.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&et('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 Yn);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){et("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new W,1/0);return}if(e){let n=this.boundingSphere.center;if(si.setFromBufferAttribute(e),t)for(let s=0,a=t.length;s<a;s++){let o=t[s];qa.setFromBufferAttribute(o),this.morphTargetsRelative?(vn.addVectors(si.min,qa.min),si.expandByPoint(vn),vn.addVectors(si.max,qa.max),si.expandByPoint(vn)):(si.expandByPoint(qa.min),si.expandByPoint(qa.max))}si.getCenter(n);let r=0;for(let s=0,a=e.count;s<a;s++)vn.fromBufferAttribute(e,s),r=Math.max(r,n.distanceToSquared(vn));if(t)for(let s=0,a=t.length;s<a;s++){let o=t[s],l=this.morphTargetsRelative;for(let c=0,h=o.count;c<h;c++)vn.fromBufferAttribute(o,c),l&&(Zs.fromBufferAttribute(e,c),vn.add(Zs)),r=Math.max(r,n.distanceToSquared(vn))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&et('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){et("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let n=t.position,r=t.normal,s=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Kt(new Float32Array(4*n.count),4));let a=this.getAttribute("tangent"),o=[],l=[];for(let v=0;v<n.count;v++)o[v]=new W,l[v]=new W;let c=new W,h=new W,d=new W,f=new dt,p=new dt,x=new dt,y=new W,b=new W;function g(v,I,B){c.fromBufferAttribute(n,v),h.fromBufferAttribute(n,I),d.fromBufferAttribute(n,B),f.fromBufferAttribute(s,v),p.fromBufferAttribute(s,I),x.fromBufferAttribute(s,B),h.sub(c),d.sub(c),p.sub(f),x.sub(f);let k=1/(p.x*x.y-x.x*p.y);isFinite(k)&&(y.copy(h).multiplyScalar(x.y).addScaledVector(d,-p.y).multiplyScalar(k),b.copy(d).multiplyScalar(p.x).addScaledVector(h,-x.x).multiplyScalar(k),o[v].add(y),o[I].add(y),o[B].add(y),l[v].add(b),l[I].add(b),l[B].add(b))}let S=this.groups;S.length===0&&(S=[{start:0,count:e.count}]);for(let v=0,I=S.length;v<I;++v){let B=S[v],k=B.start,V=B.count;for(let J=k,L=k+V;J<L;J+=3)g(e.getX(J+0),e.getX(J+1),e.getX(J+2))}let A=new W,T=new W,N=new W,P=new W;function U(v){N.fromBufferAttribute(r,v),P.copy(N);let I=o[v];A.copy(I),A.sub(N.multiplyScalar(N.dot(I))).normalize(),T.crossVectors(P,I);let k=T.dot(l[v])<0?-1:1;a.setXYZW(v,A.x,A.y,A.z,k)}for(let v=0,I=S.length;v<I;++v){let B=S[v],k=B.start,V=B.count;for(let J=k,L=k+V;J<L;J+=3)U(e.getX(J+0)),U(e.getX(J+1)),U(e.getX(J+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new Kt(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let f=0,p=n.count;f<p;f++)n.setXYZ(f,0,0,0);let r=new W,s=new W,a=new W,o=new W,l=new W,c=new W,h=new W,d=new W;if(e)for(let f=0,p=e.count;f<p;f+=3){let x=e.getX(f+0),y=e.getX(f+1),b=e.getX(f+2);r.fromBufferAttribute(t,x),s.fromBufferAttribute(t,y),a.fromBufferAttribute(t,b),h.subVectors(a,s),d.subVectors(r,s),h.cross(d),o.fromBufferAttribute(n,x),l.fromBufferAttribute(n,y),c.fromBufferAttribute(n,b),o.add(h),l.add(h),c.add(h),n.setXYZ(x,o.x,o.y,o.z),n.setXYZ(y,l.x,l.y,l.z),n.setXYZ(b,c.x,c.y,c.z)}else for(let f=0,p=t.count;f<p;f+=3)r.fromBufferAttribute(t,f+0),s.fromBufferAttribute(t,f+1),a.fromBufferAttribute(t,f+2),h.subVectors(a,s),d.subVectors(r,s),h.cross(d),n.setXYZ(f+0,h.x,h.y,h.z),n.setXYZ(f+1,h.x,h.y,h.z),n.setXYZ(f+2,h.x,h.y,h.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)vn.fromBufferAttribute(e,t),vn.normalize(),e.setXYZ(t,vn.x,vn.y,vn.z)}toNonIndexed(){function e(o,l){let c=o.array,h=o.itemSize,d=o.normalized,f=new c.constructor(l.length*h),p=0,x=0;for(let y=0,b=l.length;y<b;y++){o.isInterleavedBufferAttribute?p=l[y]*o.data.stride+o.offset:p=l[y]*h;for(let g=0;g<h;g++)f[x++]=c[p++]}return new Kt(f,h,d)}if(this.index===null)return Ke("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let t=new i,n=this.index.array,r=this.attributes;for(let o in r){let l=r[o],c=e(l,n);t.setAttribute(o,c)}let s=this.morphAttributes;for(let o in s){let l=[],c=s[o];for(let h=0,d=c.length;h<d;h++){let f=c[h],p=e(f,n);l.push(p)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;let a=this.groups;for(let o=0,l=a.length;o<l;o++){let c=a[o];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){let e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let l in n){let c=n[l];e.data.attributes[l]=c.toJSON(e.data)}let r={},s=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],h=[];for(let d=0,f=c.length;d<f;d++){let p=c[d];h.push(p.toJSON(e.data))}h.length>0&&(r[l]=h,s=!0)}s&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let c in r){let h=r[c];this.setAttribute(c,h.clone(t))}let s=e.morphAttributes;for(let c in s){let h=[],d=s[c];for(let f=0,p=d.length;f<p;f++)h.push(d[f].clone(t));this.morphAttributes[c]=h}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let c=0,h=a.length;c<h;c++){let d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}},Ur=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=sl,this.updateRanges=[],this.version=0,this.uuid=Ii()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let r=0,s=this.stride;r<s;r++)this.array[e+r]=t.array[n+r];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ii()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ii()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},zn=new W,kr=class i{constructor(e,t,n,r=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=r}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)zn.fromBufferAttribute(this,t),zn.applyMatrix4(e),this.setXYZ(t,zn.x,zn.y,zn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)zn.fromBufferAttribute(this,t),zn.applyNormalMatrix(e),this.setXYZ(t,zn.x,zn.y,zn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)zn.fromBufferAttribute(this,t),zn.transformDirection(e),this.setXYZ(t,zn.x,zn.y,zn.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=Ri(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Nt(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=Nt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Nt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Nt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Nt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=Ri(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Ri(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Ri(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Ri(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=Nt(t,this.array),n=Nt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=Nt(t,this.array),n=Nt(n,this.array),r=Nt(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this}setXYZW(e,t,n,r,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Nt(t,this.array),n=Nt(n,this.array),r=Nt(r,this.array),s=Nt(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this.data.array[e+3]=s,this}clone(e){if(e===void 0){eo("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let r=n*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[r+s])}return new Kt(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new i(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){eo("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let r=n*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[r+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},nS=0,Ln=class extends Li{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:nS++}),this.uuid=Ii(),this.name="",this.type="Material",this.blending=fs,this.side=Pi,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Yc,this.blendDst=Jc,this.blendEquation=Dr,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ve(0,0,0),this.blendAlpha=0,this.depthFunc=ps,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=ud,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ls,this.stencilZFail=ls,this.stencilZPass=ls,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(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){Ke(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Ke(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).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(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).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(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==fs&&(n.blending=this.blending),this.side!==Pi&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Yc&&(n.blendSrc=this.blendSrc),this.blendDst!==Jc&&(n.blendDst=this.blendDst),this.blendEquation!==Dr&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==ps&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==ud&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ls&&(n.stencilFail=this.stencilFail),this.stencilZFail!==ls&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==ls&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(s){let a=[];for(let o in s){let l=s[o];delete l.metadata,a.push(l)}return a}if(t){let s=r(e.textures),a=r(e.images);s.length>0&&(n.textures=s),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let r=t.length;n=new Array(r);for(let s=0;s!==r;++s)n[s]=t[s].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},hr=new W,Qu=new W,Pc=new W,Ir=new W,ed=new W,Lc=new W,td=new W,Br=class{constructor(e=new W,t=new W(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,hr)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=hr.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(hr.copy(this.origin).addScaledVector(this.direction,t),hr.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){Qu.copy(e).add(t).multiplyScalar(.5),Pc.copy(t).sub(e).normalize(),Ir.copy(this.origin).sub(Qu);let s=e.distanceTo(t)*.5,a=-this.direction.dot(Pc),o=Ir.dot(this.direction),l=-Ir.dot(Pc),c=Ir.lengthSq(),h=Math.abs(1-a*a),d,f,p,x;if(h>0)if(d=a*l-o,f=a*o-l,x=s*h,d>=0)if(f>=-x)if(f<=x){let y=1/h;d*=y,f*=y,p=d*(d+a*f+2*o)+f*(a*d+f+2*l)+c}else f=s,d=Math.max(0,-(a*f+o)),p=-d*d+f*(f+2*l)+c;else f=-s,d=Math.max(0,-(a*f+o)),p=-d*d+f*(f+2*l)+c;else f<=-x?(d=Math.max(0,-(-a*s+o)),f=d>0?-s:Math.min(Math.max(-s,-l),s),p=-d*d+f*(f+2*l)+c):f<=x?(d=0,f=Math.min(Math.max(-s,-l),s),p=f*(f+2*l)+c):(d=Math.max(0,-(a*s+o)),f=d>0?s:Math.min(Math.max(-s,-l),s),p=-d*d+f*(f+2*l)+c);else f=a>0?-s:s,d=Math.max(0,-(a*f+o)),p=-d*d+f*(f+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,d),r&&r.copy(Qu).addScaledVector(Pc,f),p}intersectSphere(e,t){hr.subVectors(e.center,this.origin);let n=hr.dot(this.direction),r=hr.dot(hr)-n*n,s=e.radius*e.radius;if(r>s)return null;let a=Math.sqrt(s-r),o=n-a,l=n+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,s,a,o,l,c=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,f=this.origin;return c>=0?(n=(e.min.x-f.x)*c,r=(e.max.x-f.x)*c):(n=(e.max.x-f.x)*c,r=(e.min.x-f.x)*c),h>=0?(s=(e.min.y-f.y)*h,a=(e.max.y-f.y)*h):(s=(e.max.y-f.y)*h,a=(e.min.y-f.y)*h),n>a||s>r||((s>n||isNaN(n))&&(n=s),(a<r||isNaN(r))&&(r=a),d>=0?(o=(e.min.z-f.z)*d,l=(e.max.z-f.z)*d):(o=(e.max.z-f.z)*d,l=(e.min.z-f.z)*d),n>l||o>r)||((o>n||n!==n)&&(n=o),(l<r||r!==r)&&(r=l),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,hr)!==null}intersectTriangle(e,t,n,r,s){ed.subVectors(t,e),Lc.subVectors(n,e),td.crossVectors(ed,Lc);let a=this.direction.dot(td),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Ir.subVectors(this.origin,e);let l=o*this.direction.dot(Lc.crossVectors(Ir,Lc));if(l<0)return null;let c=o*this.direction.dot(ed.cross(Ir));if(c<0||l+c>a)return null;let h=-o*Ir.dot(td);return h<0?null:this.at(h/a,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},gn=class extends Ln{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ve(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 qi,this.combine=Rl,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},vg=new ot,os=new Br,Dc=new Yn,Sg=new W,Nc=new W,Oc=new W,Fc=new W,nd=new W,Uc=new W,wg=new W,kc=new W,xt=class extends qt{constructor(e=new mn,t=new gn){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s<a;s++){let o=r[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,s=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(s&&o){Uc.set(0,0,0);for(let l=0,c=s.length;l<c;l++){let h=o[l],d=s[l];h!==0&&(nd.fromBufferAttribute(d,e),a?Uc.addScaledVector(nd,h):Uc.addScaledVector(nd.sub(t),h))}t.add(Uc)}return t}raycast(e,t){let n=this.geometry,r=this.material,s=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Dc.copy(n.boundingSphere),Dc.applyMatrix4(s),os.copy(e.ray).recast(e.near),!(Dc.containsPoint(os.origin)===!1&&(os.intersectSphere(Dc,Sg)===null||os.origin.distanceToSquared(Sg)>(e.far-e.near)**2))&&(vg.copy(s).invert(),os.copy(e.ray).applyMatrix4(vg),!(n.boundingBox!==null&&os.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,os)))}_computeIntersections(e,t,n){let r,s=this.geometry,a=this.material,o=s.index,l=s.attributes.position,c=s.attributes.uv,h=s.attributes.uv1,d=s.attributes.normal,f=s.groups,p=s.drawRange;if(o!==null)if(Array.isArray(a))for(let x=0,y=f.length;x<y;x++){let b=f[x],g=a[b.materialIndex],S=Math.max(b.start,p.start),A=Math.min(o.count,Math.min(b.start+b.count,p.start+p.count));for(let T=S,N=A;T<N;T+=3){let P=o.getX(T),U=o.getX(T+1),v=o.getX(T+2);r=Bc(this,g,e,n,c,h,d,P,U,v),r&&(r.faceIndex=Math.floor(T/3),r.face.materialIndex=b.materialIndex,t.push(r))}}else{let x=Math.max(0,p.start),y=Math.min(o.count,p.start+p.count);for(let b=x,g=y;b<g;b+=3){let S=o.getX(b),A=o.getX(b+1),T=o.getX(b+2);r=Bc(this,a,e,n,c,h,d,S,A,T),r&&(r.faceIndex=Math.floor(b/3),t.push(r))}}else if(l!==void 0)if(Array.isArray(a))for(let x=0,y=f.length;x<y;x++){let b=f[x],g=a[b.materialIndex],S=Math.max(b.start,p.start),A=Math.min(l.count,Math.min(b.start+b.count,p.start+p.count));for(let T=S,N=A;T<N;T+=3){let P=T,U=T+1,v=T+2;r=Bc(this,g,e,n,c,h,d,P,U,v),r&&(r.faceIndex=Math.floor(T/3),r.face.materialIndex=b.materialIndex,t.push(r))}}else{let x=Math.max(0,p.start),y=Math.min(l.count,p.start+p.count);for(let b=x,g=y;b<g;b+=3){let S=b,A=b+1,T=b+2;r=Bc(this,a,e,n,c,h,d,S,A,T),r&&(r.faceIndex=Math.floor(b/3),t.push(r))}}}};$a=new kt,Mg=new kt,Ag=new kt,rS=new kt,Tg=new ot,zc=new W,id=new Yn,Eg=new ot,rd=new Br,so=class extends xt{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=ld,this.bindMatrix=new ot,this.bindMatrixInverse=new ot,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new rn),this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,zc),this.boundingBox.expandByPoint(zc)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Yn),this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,zc),this.boundingSphere.expandByPoint(zc)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){let n=this.material,r=this.matrixWorld;n!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),id.copy(this.boundingSphere),id.applyMatrix4(r),e.ray.intersectsSphere(id)!==!1&&(Eg.copy(r).invert(),rd.copy(e.ray).applyMatrix4(Eg),!(this.boundingBox!==null&&rd.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,rd)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let e=new kt,t=this.geometry.attributes.skinWeight;for(let n=0,r=t.count;n<r;n++){e.fromBufferAttribute(t,n);let s=1/e.manhattanLength();s!==1/0?e.multiplyScalar(s):e.set(1,0,0,0),t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===ld?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===p0?this.bindMatrixInverse.copy(this.bindMatrix).invert():Ke("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,r=this.geometry;Mg.fromBufferAttribute(r.attributes.skinIndex,e),Ag.fromBufferAttribute(r.attributes.skinWeight,e),t.isVector4?($a.copy(t),t.set(0,0,0,0)):($a.set(...t,1),t.set(0,0,0)),$a.applyMatrix4(this.bindMatrix);for(let s=0;s<4;s++){let a=Ag.getComponent(s);if(a!==0){let o=Mg.getComponent(s);Tg.multiplyMatrices(n.bones[o].matrixWorld,n.boneInverses[o]),t.addScaledVector(rS.copy($a).applyMatrix4(Tg),a)}}return t.isVector4&&(t.w=$a.w),t.applyMatrix4(this.bindMatrixInverse)}},ua=class extends qt{constructor(){super(),this.isBone=!0,this.type="Bone"}},xs=class extends xn{constructor(e=null,t=1,n=1,r,s,a,o,l,c=on,h=on,d,f){super(null,a,o,l,c,h,r,s,d,f),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Rg=new ot,sS=new ot,ao=class i{constructor(e=[],t=[]){this.uuid=Ii(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.previousBoneMatrices=null,this.boneTexture=null,this.init()}init(){let e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){Ke("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let n=0,r=this.bones.length;n<r;n++)this.boneInverses.push(new ot)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let n=new ot;this.bones[e]&&n.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(n)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){let n=this.bones[e];n&&n.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){let n=this.bones[e];n&&(n.parent&&n.parent.isBone?(n.matrix.copy(n.parent.matrixWorld).invert(),n.matrix.multiply(n.matrixWorld)):n.matrix.copy(n.matrixWorld),n.matrix.decompose(n.position,n.quaternion,n.scale))}}update(){let e=this.bones,t=this.boneInverses,n=this.boneMatrices,r=this.boneTexture;for(let s=0,a=e.length;s<a;s++){let o=e[s]?e[s].matrixWorld:sS;Rg.multiplyMatrices(o,t[s]),Rg.toArray(n,s*16)}r!==null&&(r.needsUpdate=!0)}clone(){return new i(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4);t.set(this.boneMatrices);let n=new xs(t,e,e,ci,Tn);return n.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=n,this}getBoneByName(e){for(let t=0,n=this.bones.length;t<n;t++){let r=this.bones[t];if(r.name===e)return r}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,r=e.bones.length;n<r;n++){let s=e.bones[n],a=t[s];a===void 0&&(Ke("Skeleton: No bone found with UUID:",s),a=new ua),this.bones.push(a),this.boneInverses.push(new ot().fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){let e={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;let t=this.bones,n=this.boneInverses;for(let r=0,s=t.length;r<s;r++){let a=t[r];e.bones.push(a.uuid);let o=n[r];e.boneInverses.push(o.toArray())}return e}},zr=class extends Kt{constructor(e,t,n,r=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},Qs=new ot,Cg=new ot,Hc=[],Ig=new rn,aS=new ot,ja=new xt,Xa=new Yn,_s=class extends xt{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new zr(new Float32Array(n*16),16),this.previousInstanceMatrix=null,this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let r=0;r<n;r++)this.setMatrixAt(r,aS)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new rn),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Qs),Ig.copy(e.boundingBox).applyMatrix4(Qs),this.boundingBox.union(Ig)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new Yn),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Qs),Xa.copy(e.boundingSphere).applyMatrix4(Qs),this.boundingSphere.union(Xa)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.previousInstanceMatrix!==null&&(this.previousInstanceMatrix=e.previousInstanceMatrix.clone()),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){return this.instanceColor===null?t.setRGB(1,1,1):t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){return t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){let n=t.morphTargetInfluences,r=this.morphTexture.source.data.data,s=n.length+1,a=e*s+1;for(let o=0;o<n.length;o++)n[o]=r[a+o]}raycast(e,t){let n=this.matrixWorld,r=this.count;if(ja.geometry=this.geometry,ja.material=this.material,ja.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Xa.copy(this.boundingSphere),Xa.applyMatrix4(n),e.ray.intersectsSphere(Xa)!==!1))for(let s=0;s<r;s++){this.getMatrixAt(s,Qs),Cg.multiplyMatrices(n,Qs),ja.matrixWorld=Cg,ja.raycast(e,Hc);for(let a=0,o=Hc.length;a<o;a++){let l=Hc[a];l.instanceId=s,l.object=this,t.push(l)}Hc.length=0}}setColorAt(e,t){return this.instanceColor===null&&(this.instanceColor=new zr(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3),this}setMatrixAt(e,t){return t.toArray(this.instanceMatrix.array,e*16),this}setMorphAt(e,t){let n=t.morphTargetInfluences,r=n.length+1;this.morphTexture===null&&(this.morphTexture=new xs(new Float32Array(r*this.count),r,this.count,Ol,Tn));let s=this.morphTexture.source.data.data,a=0;for(let c=0;c<n.length;c++)a+=n[c];let o=this.geometry.morphTargetsRelative?1:1-a,l=r*e;return s[l]=o,s.set(n,l+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}},sd=new W,oS=new W,cS=new ct,Gi=class{constructor(e=new W(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=sd.subVectors(n,t).cross(oS.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(sd),s=this.normal.dot(r);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/s;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||cS.getNormalMatrix(e),r=this.coplanarPoint(sd).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},cs=new Yn,lS=new dt(.5,.5),Gc=new W,da=class{constructor(e=new Gi,t=new Gi,n=new Gi,r=new Gi,s=new Gi,a=new Gi){this.planes=[e,t,n,r,s,a]}set(e,t,n,r,s,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(s),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Ci,n=!1){let r=this.planes,s=e.elements,a=s[0],o=s[1],l=s[2],c=s[3],h=s[4],d=s[5],f=s[6],p=s[7],x=s[8],y=s[9],b=s[10],g=s[11],S=s[12],A=s[13],T=s[14],N=s[15];if(r[0].setComponents(c-a,p-h,g-x,N-S).normalize(),r[1].setComponents(c+a,p+h,g+x,N+S).normalize(),r[2].setComponents(c+o,p+d,g+y,N+A).normalize(),r[3].setComponents(c-o,p-d,g-y,N-A).normalize(),n)r[4].setComponents(l,f,b,T).normalize(),r[5].setComponents(c-l,p-f,g-b,N-T).normalize();else if(r[4].setComponents(c-l,p-f,g-b,N-T).normalize(),t===Ci)r[5].setComponents(c+l,p+f,g+b,N+T).normalize();else if(t===sa)r[5].setComponents(l,f,b,T).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),cs.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),cs.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(cs)}intersectsSprite(e){cs.center.set(0,0,0);let t=lS.distanceTo(e.center);return cs.radius=.7071067811865476+t,cs.applyMatrix4(e.matrixWorld),this.intersectsSphere(cs)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(Gc.x=r.normal.x>0?e.max.x:e.min.x,Gc.y=r.normal.y>0?e.max.y:e.min.y,Gc.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Gc)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},ys=class extends Ln{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Ve(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},hl=new W,ul=new W,Pg=new ot,Ka=new Br,Vc=new Yn,ad=new W,Lg=new W,vs=class extends qt{constructor(e=new mn,t=new ys){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let r=1,s=t.count;r<s;r++)hl.fromBufferAttribute(t,r-1),ul.fromBufferAttribute(t,r),n[r]=n[r-1],n[r]+=hl.distanceTo(ul);e.setAttribute("lineDistance",new Qt(n,1))}else Ke("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,s=e.params.Line.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Vc.copy(n.boundingSphere),Vc.applyMatrix4(r),Vc.radius+=s,e.ray.intersectsSphere(Vc)===!1)return;Pg.copy(r).invert(),Ka.copy(e.ray).applyMatrix4(Pg);let o=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=this.isLineSegments?2:1,h=n.index,f=n.attributes.position;if(h!==null){let p=Math.max(0,a.start),x=Math.min(h.count,a.start+a.count);for(let y=p,b=x-1;y<b;y+=c){let g=h.getX(y),S=h.getX(y+1),A=Wc(this,e,Ka,l,g,S,y);A&&t.push(A)}if(this.isLineLoop){let y=h.getX(x-1),b=h.getX(p),g=Wc(this,e,Ka,l,y,b,x-1);g&&t.push(g)}}else{let p=Math.max(0,a.start),x=Math.min(f.count,a.start+a.count);for(let y=p,b=x-1;y<b;y+=c){let g=Wc(this,e,Ka,l,y,y+1,y);g&&t.push(g)}if(this.isLineLoop){let y=Wc(this,e,Ka,l,x-1,p,x-1);y&&t.push(y)}}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s<a;s++){let o=r[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}};Dg=new W,Ng=new W,fa=class extends vs{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let r=0,s=t.count;r<s;r+=2)Dg.fromBufferAttribute(t,r),Ng.fromBufferAttribute(t,r+1),n[r]=r===0?0:n[r-1],n[r+1]=n[r]+Dg.distanceTo(Ng);e.setAttribute("lineDistance",new Qt(n,1))}else Ke("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},oo=class extends vs{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}},pa=class extends Ln{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Ve(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Og=new ot,dd=new Br,qc=new Yn,$c=new W,co=class extends qt{constructor(e=new mn,t=new pa){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,s=e.params.Points.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),qc.copy(n.boundingSphere),qc.applyMatrix4(r),qc.radius+=s,e.ray.intersectsSphere(qc)===!1)return;Og.copy(r).invert(),dd.copy(e.ray).applyMatrix4(Og);let o=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=n.index,d=n.attributes.position;if(c!==null){let f=Math.max(0,a.start),p=Math.min(c.count,a.start+a.count);for(let x=f,y=p;x<y;x++){let b=c.getX(x);$c.fromBufferAttribute(d,b),Fg($c,b,l,r,e,t,this)}}else{let f=Math.max(0,a.start),p=Math.min(d.count,a.start+a.count);for(let x=f,y=p;x<y;x++)$c.fromBufferAttribute(d,x),Fg($c,x,l,r,e,t,this)}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let r=t[n[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s<a;s++){let o=r[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}};lo=class extends xn{constructor(e=[],t=$r,n,r,s,a,o,l,c,h){super(e,t,n,r,s,a,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},Ss=class extends xn{constructor(e,t,n,r,s,a,o,l,c){super(e,t,n,r,s,a,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}},pr=class extends xn{constructor(e,t,n=Oi,r,s,a,o=on,l=on,c,h=Wi,d=1){if(h!==Wi&&h!==jr)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let f={width:e,height:t,depth:d};super(f,r,s,a,o,l,h,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ca(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},dl=class extends pr{constructor(e,t=Oi,n=$r,r,s,a=on,o=on,l,c=Wi){let h={width:e,height:e,depth:1},d=[h,h,h,h,h,h];super(e,e,t,n,r,s,a,o,l,c),this.image=d,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},ho=class extends xn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},Hr=class i extends mn{constructor(e=1,t=1,n=1,r=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:s,depthSegments:a};let o=this;r=Math.floor(r),s=Math.floor(s),a=Math.floor(a);let l=[],c=[],h=[],d=[],f=0,p=0;x("z","y","x",-1,-1,n,t,e,a,s,0),x("z","y","x",1,-1,n,t,-e,a,s,1),x("x","z","y",1,1,e,n,t,r,a,2),x("x","z","y",1,-1,e,n,-t,r,a,3),x("x","y","z",1,-1,e,t,n,r,s,4),x("x","y","z",-1,-1,e,t,-n,r,s,5),this.setIndex(l),this.setAttribute("position",new Qt(c,3)),this.setAttribute("normal",new Qt(h,3)),this.setAttribute("uv",new Qt(d,2));function x(y,b,g,S,A,T,N,P,U,v,I){let B=T/U,k=N/v,V=T/2,J=N/2,L=P/2,E=U+1,D=v+1,O=0,H=0,Y=new W;for(let le=0;le<D;le++){let fe=le*k-J;for(let be=0;be<E;be++){let Te=be*B-V;Y[y]=Te*S,Y[b]=fe*A,Y[g]=L,c.push(Y.x,Y.y,Y.z),Y[y]=0,Y[b]=0,Y[g]=P>0?1:-1,h.push(Y.x,Y.y,Y.z),d.push(be/U),d.push(1-le/v),O+=1}}for(let le=0;le<v;le++)for(let fe=0;fe<U;fe++){let be=f+fe+E*le,Te=f+fe+E*(le+1),Je=f+(fe+1)+E*(le+1),ke=f+(fe+1)+E*le;l.push(be,Te,ke),l.push(Te,Je,ke),H+=6}o.addGroup(p,H,I),p+=H,f+=O}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new i(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}},uo=class i extends mn{constructor(e=1,t=32,n=0,r=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:n,thetaLength:r},t=Math.max(3,t);let s=[],a=[],o=[],l=[],c=new W,h=new dt;a.push(0,0,0),o.push(0,0,1),l.push(.5,.5);for(let d=0,f=3;d<=t;d++,f+=3){let p=n+d/t*r;c.x=e*Math.cos(p),c.y=e*Math.sin(p),a.push(c.x,c.y,c.z),o.push(0,0,1),h.x=(a[f]/e+1)/2,h.y=(a[f+1]/e+1)/2,l.push(h.x,h.y)}for(let d=1;d<=t;d++)s.push(d,d+1,0);this.setIndex(s),this.setAttribute("position",new Qt(a,3)),this.setAttribute("normal",new Qt(o,3)),this.setAttribute("uv",new Qt(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new i(e.radius,e.segments,e.thetaStart,e.thetaLength)}},mi=class i extends mn{constructor(e=1,t=1,n=1,r=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let s=e/2,a=t/2,o=Math.floor(n),l=Math.floor(r),c=o+1,h=l+1,d=e/o,f=t/l,p=[],x=[],y=[],b=[];for(let g=0;g<h;g++){let S=g*f-a;for(let A=0;A<c;A++){let T=A*d-s;x.push(T,-S,0),y.push(0,0,1),b.push(A/o),b.push(1-g/l)}}for(let g=0;g<l;g++)for(let S=0;S<o;S++){let A=S+c*g,T=S+c*(g+1),N=S+1+c*(g+1),P=S+1+c*g;p.push(A,T,P),p.push(T,N,P)}this.setIndex(p),this.setAttribute("position",new Qt(x,3)),this.setAttribute("normal",new Qt(y,3)),this.setAttribute("uv",new Qt(b,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new i(e.width,e.height,e.widthSegments,e.heightSegments)}},Gr=class i extends mn{constructor(e=.5,t=1,n=32,r=1,s=0,a=Math.PI*2){super(),this.type="RingGeometry",this.parameters={innerRadius:e,outerRadius:t,thetaSegments:n,phiSegments:r,thetaStart:s,thetaLength:a},n=Math.max(3,n),r=Math.max(1,r);let o=[],l=[],c=[],h=[],d=e,f=(t-e)/r,p=new W,x=new dt;for(let y=0;y<=r;y++){for(let b=0;b<=n;b++){let g=s+b/n*a;p.x=d*Math.cos(g),p.y=d*Math.sin(g),l.push(p.x,p.y,p.z),c.push(0,0,1),x.x=(p.x/t+1)/2,x.y=(p.y/t+1)/2,h.push(x.x,x.y)}d+=f}for(let y=0;y<r;y++){let b=y*(n+1);for(let g=0;g<n;g++){let S=g+b,A=S,T=S+n+1,N=S+n+2,P=S+1;o.push(A,T,P),o.push(T,N,P)}}this.setIndex(o),this.setAttribute("position",new Qt(l,3)),this.setAttribute("normal",new Qt(c,3)),this.setAttribute("uv",new Qt(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new i(e.innerRadius,e.outerRadius,e.thetaSegments,e.phiSegments,e.thetaStart,e.thetaLength)}},fo=class extends Ln{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Ve(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}};I0={clone:Es,merge:Nn},uS=`void main() {
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
+}`,dS=`void main() {
+ gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
+}`,ai=class extends Ln{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=uS,this.fragmentShader=dS,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,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Es(e.uniforms),this.uniformsGroups=hS(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let r in this.uniforms){let a=this.uniforms[r].value;a&&a.isTexture?t.uniforms[r]={type:"t",value:a.toJSON(e).uuid}:a&&a.isColor?t.uniforms[r]={type:"c",value:a.getHex()}:a&&a.isVector2?t.uniforms[r]={type:"v2",value:a.toArray()}:a&&a.isVector3?t.uniforms[r]={type:"v3",value:a.toArray()}:a&&a.isVector4?t.uniforms[r]={type:"v4",value:a.toArray()}:a&&a.isMatrix3?t.uniforms[r]={type:"m3",value:a.toArray()}:a&&a.isMatrix4?t.uniforms[r]={type:"m4",value:a.toArray()}:t.uniforms[r]={value:a}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let r in this.extensions)this.extensions[r]===!0&&(n[r]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},fl=class extends ai{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},gi=class extends Ln{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Ve(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 Ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Bo,this.normalScale=new dt(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 qi,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Jn=class extends gi{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new dt(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return bt(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Ve(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new Ve(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Ve(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},po=class extends Ln{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Ve(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Bo,this.normalScale=new dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new qi,this.combine=Rl,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},pl=class extends Ln{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=g0,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},ml=class extends Ln{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};mo=class{static convertArray(e,t){return ds(e,t)}static isTypedArray(e){return M0(e)}static getKeyframeOrder(e){return P0(e)}static sortedArray(e,t,n){return fd(e,t,n)}static flattenJSON(e,t,n,r){Vd(e,t,n,r)}static subclip(e,t,n,r,s=30){return fS(e,t,n,r,s)}static makeClipAdditive(e,t=0,n=e,r=30){return pS(e,t,n,r)}},$i=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r!==void 0?r:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],s=t[n-1];e:{t:{let a;n:{i:if(!(e<r)){for(let o=n+2;;){if(r===void 0){if(e<s)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===o)break;if(s=r,r=t[++n],e<r)break t}a=t.length;break n}if(!(e>=s)){let o=t[1];e<o&&(n=2,s=o);for(let l=n-2;;){if(s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===l)break;if(r=s,s=t[--n-1],e>=s)break t}a=n,n=0;break n}break e}for(;n<a;){let o=n+a>>>1;e<t[o]?a=o:n=o+1}if(r=t[n],s=t[n-1],s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,s,r)}return this.interpolate_(n,s,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,s=e*r;for(let a=0;a!==r;++a)t[a]=n[s+a];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}},gl=class extends $i{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:hs,endingEnd:hs}}intervalChanged_(e,t,n){let r=this.parameterPositions,s=e-2,a=e+1,o=r[s],l=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case us:s=e,o=2*t-n;break;case Za:s=r.length-2,o=t+r[s]-r[s+1];break;default:s=e,o=n}if(l===void 0)switch(this.getSettings_().endingEnd){case us:a=e,l=2*n-t;break;case Za:a=1,l=n+r[1]-r[0];break;default:a=e-1,l=t}let c=(n-t)*.5,h=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(l-n),this._offsetPrev=s*h,this._offsetNext=a*h}interpolate_(e,t,n,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,h=this._offsetPrev,d=this._offsetNext,f=this._weightPrev,p=this._weightNext,x=(n-t)/(r-t),y=x*x,b=y*x,g=-f*b+2*f*y-f*x,S=(1+f)*b+(-1.5-2*f)*y+(-.5+f)*x+1,A=(-1-p)*b+(1.5+p)*y+.5*x,T=p*b-p*y;for(let N=0;N!==o;++N)s[N]=g*a[h+N]+S*a[c+N]+A*a[l+N]+T*a[d+N];return s}},go=class extends $i{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,h=(n-t)/(r-t),d=1-h;for(let f=0;f!==o;++f)s[f]=a[c+f]*d+a[l+f]*h;return s}},bl=class extends $i{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},xl=class extends $i{interpolate_(e,t,n,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,h=this.settings||this.DefaultSettings_,d=h.inTangents,f=h.outTangents;if(!d||!f){let y=(n-t)/(r-t),b=1-y;for(let g=0;g!==o;++g)s[g]=a[c+g]*b+a[l+g]*y;return s}let p=o*2,x=e-1;for(let y=0;y!==o;++y){let b=a[c+y],g=a[l+y],S=x*p+y*2,A=f[S],T=f[S+1],N=e*p+y*2,P=d[N],U=d[N+1],v=(n-t)/(r-t),I,B,k,V,J;for(let L=0;L<8;L++){I=v*v,B=I*v,k=1-v,V=k*k,J=V*k;let D=J*t+3*V*v*A+3*k*I*P+B*r-n;if(Math.abs(D)<1e-10)break;let O=3*V*(A-t)+6*k*v*(P-A)+3*I*(r-P);if(Math.abs(O)<1e-10)break;v=v-D/O,v=Math.max(0,Math.min(1,v))}s[y]=J*b+3*V*v*T+3*k*I*U+B*g}return s}},Zn=class{constructor(e,t,n,r){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=ds(t,this.TimeBufferType),this.values=ds(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:ds(e.times,Array),values:ds(e.values,Array)};let r=e.getInterpolation();r!==e.DefaultInterpolation&&(n.interpolation=r)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new bl(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new go(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new gl(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new xl(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.settings=this.settings),t}setInterpolation(e){let t;switch(e){case ms:t=this.InterpolantFactoryMethodDiscrete;break;case gs:t=this.InterpolantFactoryMethodLinear;break;case Kc:t=this.InterpolantFactoryMethodSmooth;break;case hd:t=this.InterpolantFactoryMethodBezier;break}if(t===void 0){let n="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(n);return Ke("KeyframeTrack:",n),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return ms;case this.InterpolantFactoryMethodLinear:return gs;case this.InterpolantFactoryMethodSmooth:return Kc;case this.InterpolantFactoryMethodBezier:return hd}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e}return this}trim(e,t){let n=this.times,r=n.length,s=0,a=r-1;for(;s!==r&&n[s]<e;)++s;for(;a!==-1&&n[a]>t;)--a;if(++a,s!==0||a!==r){s>=a&&(a=Math.max(a,1),s=a-1);let o=this.getValueSize();this.times=n.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(et("KeyframeTrack: Invalid value size in track.",this),e=!1);let n=this.times,r=this.values,s=n.length;s===0&&(et("KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){let l=n[o];if(typeof l=="number"&&isNaN(l)){et("KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){et("KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(r!==void 0&&M0(r))for(let o=0,l=r.length;o!==l;++o){let c=r[o];if(isNaN(c)){et("KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===Kc,s=e.length-1,a=1;for(let o=1;o<s;++o){let l=!1,c=e[o],h=e[o+1];if(c!==h&&(o!==1||c!==e[0]))if(r)l=!0;else{let d=o*n,f=d-n,p=d+n;for(let x=0;x!==n;++x){let y=t[d+x];if(y!==t[f+x]||y!==t[p+x]){l=!0;break}}}if(l){if(o!==a){e[a]=e[o];let d=o*n,f=a*n;for(let p=0;p!==n;++p)t[f+p]=t[d+p]}++a}}if(s>0){e[a]=e[s];for(let o=s*n,l=a*n,c=0;c!==n;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*n)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};Zn.prototype.ValueTypeName="";Zn.prototype.TimeBufferType=Float32Array;Zn.prototype.ValueBufferType=Float32Array;Zn.prototype.DefaultInterpolation=gs;mr=class extends Zn{constructor(e,t,n){super(e,t,n)}};mr.prototype.ValueTypeName="bool";mr.prototype.ValueBufferType=Array;mr.prototype.DefaultInterpolation=ms;mr.prototype.InterpolantFactoryMethodLinear=void 0;mr.prototype.InterpolantFactoryMethodSmooth=void 0;bo=class extends Zn{constructor(e,t,n,r){super(e,t,n,r)}};bo.prototype.ValueTypeName="color";ji=class extends Zn{constructor(e,t,n,r){super(e,t,n,r)}};ji.prototype.ValueTypeName="number";_l=class extends $i{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(n-t)/(r-t),c=e*o;for(let h=c+o;c!==h;c+=4)Pt.slerpFlat(s,0,a,c-o,a,c,l);return s}},Xi=class extends Zn{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new _l(this.times,this.values,this.getValueSize(),e)}};Xi.prototype.ValueTypeName="quaternion";Xi.prototype.InterpolantFactoryMethodSmooth=void 0;gr=class extends Zn{constructor(e,t,n){super(e,t,n)}};gr.prototype.ValueTypeName="string";gr.prototype.ValueBufferType=Array;gr.prototype.DefaultInterpolation=ms;gr.prototype.InterpolantFactoryMethodLinear=void 0;gr.prototype.InterpolantFactoryMethodSmooth=void 0;Ki=class extends Zn{constructor(e,t,n,r){super(e,t,n,r)}};Ki.prototype.ValueTypeName="vector";bi=class{constructor(e="",t=-1,n=[],r=mh){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=Ii(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let a=0,o=n.length;a!==o;++a)t.push(gS(n[a]).scale(r));let s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s.userData=JSON.parse(e.userData||"{}"),s}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let s=0,a=n.length;s!==a;++s)t.push(Zn.toJSON(n[s]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let s=t.length,a=[];for(let o=0;o<s;o++){let l=[],c=[];l.push((o+s-1)%s,o,(o+1)%s),c.push(0,1,0);let h=P0(l);l=fd(l,1,h),c=fd(c,1,h),!r&&l[0]===0&&(l.push(s),c.push(c[0])),a.push(new ji(".morphTargetInfluences["+t[o].name+"]",l,c).scale(1/n))}return new this(e,-1,a)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let r=e;n=r.geometry&&r.geometry.animations||r.animations}for(let r=0;r<n.length;r++)if(n[r].name===t)return n[r];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let r={},s=/^([\w-]*?)([\d]+)$/;for(let o=0,l=e.length;o<l;o++){let c=e[o],h=c.name.match(s);if(h&&h.length>1){let d=h[1],f=r[d];f||(r[d]=f=[]),f.push(c)}}let a=[];for(let o in r)a.push(this.CreateFromMorphTargetSequence(o,r[o],t,n));return a}static parseAnimation(e,t){if(Ke("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return et("AnimationClip: No animation in JSONLoader data."),null;let n=function(d,f,p,x,y){if(p.length!==0){let b=[],g=[];Vd(p,b,g,x),b.length!==0&&y.push(new d(f,b,g))}},r=[],s=e.name||"default",a=e.fps||30,o=e.blendMode,l=e.length||-1,c=e.hierarchy||[];for(let d=0;d<c.length;d++){let f=c[d].keys;if(!(!f||f.length===0))if(f[0].morphTargets){let p={},x;for(x=0;x<f.length;x++)if(f[x].morphTargets)for(let y=0;y<f[x].morphTargets.length;y++)p[f[x].morphTargets[y]]=-1;for(let y in p){let b=[],g=[];for(let S=0;S!==f[x].morphTargets.length;++S){let A=f[x];b.push(A.time),g.push(A.morphTarget===y?1:0)}r.push(new ji(".morphTargetInfluence["+y+"]",b,g))}l=p.length*a}else{let p=".bones["+t[d].name+"]";n(Ki,p+".position",f,"pos",r),n(Xi,p+".quaternion",f,"rot",r),n(Ki,p+".scale",f,"scl",r)}}return r.length===0?null:new this(s,l,r,o)}resetDuration(){let e=this.tracks,t=0;for(let n=0,r=e.length;n!==r;++n){let s=this.tracks[n];t=Math.max(t,s.times[s.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e=e&&this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){let e=[];for(let n=0;n<this.tracks.length;n++)e.push(this.tracks[n].clone());let t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}};Vi={enabled:!1,files:{},add:function(i,e){this.enabled!==!1&&(kg(i)||(this.files[i]=e))},get:function(i){if(this.enabled!==!1&&!kg(i))return this.files[i]},remove:function(i){delete this.files[i]},clear:function(){this.files={}}};yl=class{constructor(e,t,n){let r=this,s=!1,a=0,o=0,l,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(h){o++,s===!1&&r.onStart!==void 0&&r.onStart(h,a,o),s=!0},this.itemEnd=function(h){a++,r.onProgress!==void 0&&r.onProgress(h,a,o),a===o&&(s=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(h){r.onError!==void 0&&r.onError(h)},this.resolveURL=function(h){return l?l(h):h},this.setURLModifier=function(h){return l=h,this},this.addHandler=function(h,d){return c.push(h,d),this},this.removeHandler=function(h){let d=c.indexOf(h);return d!==-1&&c.splice(d,2),this},this.getHandler=function(h){for(let d=0,f=c.length;d<f;d+=2){let p=c[d],x=c[d+1];if(p.global&&(p.lastIndex=0),p.test(h))return x}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}},L0=new yl,oi=class{constructor(e){this.manager=e!==void 0?e:L0,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(e,t){let n=this;return new Promise(function(r,s){n.load(e,r,t,s)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};oi.DEFAULT_MATERIAL_NAME="__DEFAULT";ur={},pd=class extends Error{constructor(e,t){super(e),this.response=t}},Yi=class extends oi{constructor(e){super(e),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,t,n,r){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=Vi.get(`file:${e}`);if(s!==void 0){this.manager.itemStart(e),setTimeout(()=>{t&&t(s),this.manager.itemEnd(e)},0);return}if(ur[e]!==void 0){ur[e].push({onLoad:t,onProgress:n,onError:r});return}ur[e]=[],ur[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,l=this.responseType;fetch(a).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&Ke("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;let h=ur[e],d=c.body.getReader(),f=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),p=f?parseInt(f):0,x=p!==0,y=0,b=new ReadableStream({start(g){S();function S(){d.read().then(({done:A,value:T})=>{if(A)g.close();else{y+=T.byteLength;let N=new ProgressEvent("progress",{lengthComputable:x,loaded:y,total:p});for(let P=0,U=h.length;P<U;P++){let v=h[P];v.onProgress&&v.onProgress(N)}g.enqueue(T),S()}},A=>{g.error(A)})}}});return new Response(b)}else throw new pd(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(h=>new DOMParser().parseFromString(h,o));case"json":return c.json();default:if(o==="")return c.text();{let d=/charset="?([^;"\s]*)"?/i.exec(o),f=d&&d[1]?d[1].toLowerCase():void 0,p=new TextDecoder(f);return c.arrayBuffer().then(x=>p.decode(x))}}}).then(c=>{Vi.add(`file:${e}`,c);let h=ur[e];delete ur[e];for(let d=0,f=h.length;d<f;d++){let p=h[d];p.onLoad&&p.onLoad(c)}}).catch(c=>{let h=ur[e];if(h===void 0)throw this.manager.itemError(e),c;delete ur[e];for(let d=0,f=h.length;d<f;d++){let p=h[d];p.onError&&p.onError(c)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},ea=new WeakMap,vl=class extends oi{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=Vi.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);else{let d=ea.get(a);d===void 0&&(d=[],ea.set(a,d)),d.push({onLoad:t,onError:r})}return a}let o=aa("img");function l(){h(),t&&t(this);let d=ea.get(this)||[];for(let f=0;f<d.length;f++){let p=d[f];p.onLoad&&p.onLoad(this)}ea.delete(this),s.manager.itemEnd(e)}function c(d){h(),r&&r(d),Vi.remove(`image:${e}`);let f=ea.get(this)||[];for(let p=0;p<f.length;p++){let x=f[p];x.onError&&x.onError(d)}ea.delete(this),s.manager.itemError(e),s.manager.itemEnd(e)}function h(){o.removeEventListener("load",l,!1),o.removeEventListener("error",c,!1)}return o.addEventListener("load",l,!1),o.addEventListener("error",c,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),Vi.add(`image:${e}`,o),s.manager.itemStart(e),o.src=e,o}},xo=class extends oi{constructor(e){super(e)}load(e,t,n,r){let s=this,a=new xs,o=new Yi(this.manager);return o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(s.withCredentials),o.load(e,function(l){let c;try{c=s.parse(l)}catch(h){r!==void 0?r(h):et(h);return}c.image!==void 0?a.image=c.image:c.data!==void 0&&(a.image.width=c.width,a.image.height=c.height,a.image.data=c.data),a.wrapS=c.wrapS!==void 0?c.wrapS:Kn,a.wrapT=c.wrapT!==void 0?c.wrapT:Kn,a.magFilter=c.magFilter!==void 0?c.magFilter:zt,a.minFilter=c.minFilter!==void 0?c.minFilter:zt,a.anisotropy=c.anisotropy!==void 0?c.anisotropy:1,c.colorSpace!==void 0&&(a.colorSpace=c.colorSpace),c.flipY!==void 0&&(a.flipY=c.flipY),c.format!==void 0&&(a.format=c.format),c.type!==void 0&&(a.type=c.type),c.mipmaps!==void 0&&(a.mipmaps=c.mipmaps,a.minFilter=xi),c.mipmapCount===1&&(a.minFilter=zt),c.generateMipmaps!==void 0&&(a.generateMipmaps=c.generateMipmaps),a.needsUpdate=!0,t&&t(a,c)},n,r),a}},_o=class extends oi{constructor(e){super(e)}load(e,t,n,r){let s=new xn,a=new vl(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(o){s.image=o,s.needsUpdate=!0,t!==void 0&&t(s)},n,r),s}},Vr=class extends qt{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Ve(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}},ma=class extends Vr{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(qt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Ve(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){let t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}},od=new ot,Bg=new W,zg=new W,yo=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new dt(512,512),this.mapType=Qn,this.map=null,this.mapPass=null,this.matrix=new ot,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new da,this._frameExtents=new dt(1,1),this._viewportCount=1,this._viewports=[new kt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;Bg.setFromMatrixPosition(e.matrixWorld),t.position.copy(Bg),zg.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(zg),t.updateMatrixWorld(),od.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(od,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===sa||t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(od)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},jc=new W,Xc=new Pt,Hi=new W,vo=class extends qt{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ot,this.projectionMatrix=new ot,this.projectionMatrixInverse=new ot,this.coordinateSystem=Ci,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(jc,Xc,Hi),Hi.x===1&&Hi.y===1&&Hi.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(jc,Xc,Hi.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(jc,Xc,Hi),Hi.x===1&&Hi.y===1&&Hi.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(jc,Xc,Hi.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},Pr=new W,Hg=new dt,Gg=new dt,an=class extends vo{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=bs*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Ya*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return bs*2*Math.atan(Math.tan(Ya*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Pr.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Pr.x,Pr.y).multiplyScalar(-e/Pr.z),Pr.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Pr.x,Pr.y).multiplyScalar(-e/Pr.z)}getViewSize(e,t){return this.getViewBounds(e,Hg,Gg),t.subVectors(Gg,Hg)}setViewOffset(e,t,n,r,s,a){this.aspect=e/t,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=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(Ya*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,s=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let l=a.fullWidth,c=a.fullHeight;s+=a.offsetX*r/l,t-=a.offsetY*n/c,r*=a.width/l,n*=a.height/c}let o=this.filmOffset;o!==0&&(s+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},md=class extends yo{constructor(){super(new an(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=bs*2*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height*this.aspect,s=e.distance||t.far;(n!==t.fov||r!==t.aspect||s!==t.far)&&(t.fov=n,t.aspect=r,t.far=s,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},So=class extends Vr{constructor(e,t,n=0,r=Math.PI/3,s=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(qt.DEFAULT_UP),this.updateMatrix(),this.target=new qt,this.distance=n,this.angle=r,this.penumbra=s,this.decay=a,this.map=null,this.shadow=new md}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}},gd=class extends yo{constructor(){super(new an(90,1,.5,500)),this.isPointLightShadow=!0}},ws=class extends Vr{constructor(e,t,n=0,r=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=r,this.shadow=new gd}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}},Wr=class extends vo{constructor(e=-1,t=1,n=1,r=-1,s=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=s,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,s,a){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=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,s=n-e,a=n+e,o=r+t,l=r-t;if(this.view!==null&&this.view.enabled){let c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,a=s+c*this.view.width,o-=h*this.view.offsetY,l=o-h*this.view.height}this.projectionMatrix.makeOrthographic(s,a,o,l,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},bd=class extends yo{constructor(){super(new Wr(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},Di=class extends Vr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(qt.DEFAULT_UP),this.updateMatrix(),this.target=new qt,this.shadow=new bd}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}},Sl=class{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new W)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){let n=e.x,r=e.y,s=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.282095),t.addScaledVector(a[1],.488603*r),t.addScaledVector(a[2],.488603*s),t.addScaledVector(a[3],.488603*n),t.addScaledVector(a[4],1.092548*(n*r)),t.addScaledVector(a[5],1.092548*(r*s)),t.addScaledVector(a[6],.315392*(3*s*s-1)),t.addScaledVector(a[7],1.092548*(n*s)),t.addScaledVector(a[8],.546274*(n*n-r*r)),t}getIrradianceAt(e,t){let n=e.x,r=e.y,s=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.886227),t.addScaledVector(a[1],2*.511664*r),t.addScaledVector(a[2],2*.511664*s),t.addScaledVector(a[3],2*.511664*n),t.addScaledVector(a[4],2*.429043*n*r),t.addScaledVector(a[5],2*.429043*r*s),t.addScaledVector(a[6],.743125*s*s-.247708),t.addScaledVector(a[7],2*.429043*n*s),t.addScaledVector(a[8],.429043*(n*n-r*r)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){let n=this.coefficients;for(let r=0;r<9;r++)n[r].fromArray(e,t+r*3);return this}toArray(e=[],t=0){let n=this.coefficients;for(let r=0;r<9;r++)n[r].toArray(e,t+r*3);return e}static getBasisAt(e,t){let n=e.x,r=e.y,s=e.z;t[0]=.282095,t[1]=.488603*r,t[2]=.488603*s,t[3]=.488603*n,t[4]=1.092548*n*r,t[5]=1.092548*r*s,t[6]=.315392*(3*s*s-1),t[7]=1.092548*n*s,t[8]=.546274*(n*n-r*r)}},wo=class extends Vr{constructor(e=new Sl,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){let t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}},br=class{static extractUrlBase(e){let t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},cd=new WeakMap,Mo=class extends oi{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&Ke("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&Ke("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=Vi.get(`image-bitmap:${e}`);if(a!==void 0){if(s.manager.itemStart(e),a.then){a.then(c=>{cd.has(a)===!0?(r&&r(cd.get(a)),s.manager.itemError(e),s.manager.itemEnd(e)):(t&&t(c),s.manager.itemEnd(e))});return}setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);return}let o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader,o.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(c){Vi.add(`image-bitmap:${e}`,c),t&&t(c),s.manager.itemEnd(e)}).catch(function(c){r&&r(c),cd.set(l,c),Vi.remove(`image-bitmap:${e}`),s.manager.itemError(e),s.manager.itemEnd(e)});Vi.add(`image-bitmap:${e}`,l),s.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},ta=-90,na=1,wl=class extends qt{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new an(ta,na,e,t);r.layers=this.layers,this.add(r);let s=new an(ta,na,e,t);s.layers=this.layers,this.add(s);let a=new an(ta,na,e,t);a.layers=this.layers,this.add(a);let o=new an(ta,na,e,t);o.layers=this.layers,this.add(o);let l=new an(ta,na,e,t);l.layers=this.layers,this.add(l);let c=new an(ta,na,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,s,a,o,l]=t;for(let c of t)this.remove(c);if(e===Ci)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===sa)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[s,a,o,l,c,h]=this.children,d=e.getRenderTarget(),f=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),x=e.xr.enabled;e.xr.enabled=!1;let y=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let b=!1;e.isWebGLRenderer===!0?b=e.state.buffers.depth.getReversed():b=e.reversedDepthBuffer,e.setRenderTarget(n,0,r),b&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,1,r),b&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),b&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),b&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(n,4,r),b&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=y,e.setRenderTarget(n,5,r),b&&e.autoClear===!1&&e.clearDepth(),e.render(t,h),e.setRenderTarget(d,f,p),e.xr.enabled=x,n.texture.needsPMREMUpdate=!0}},Ml=class extends an{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},Al=class{constructor(e,t,n){this.binding=e,this.valueSize=n;let r,s,a;switch(t){case"quaternion":r=this._slerp,s=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case"string":case"bool":r=this._select,s=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(n*5);break;default:r=this._lerp,s=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=s,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,r=this.valueSize,s=e*r+r,a=this.cumulativeWeight;if(a===0){for(let o=0;o!==r;++o)n[s+o]=n[o];a=t}else{a+=t;let o=t/a;this._mixBufferRegion(n,s,0,o,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,r=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,r=e*t+t,s=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){let l=t*this._origIndex;this._mixBufferRegion(n,r,l,1-s,t)}a>0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(n[l]!==n[l+t]){o.setValue(n,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let s=n,a=r;s!==a;++s)t[s]=t[r+s%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,r,s){if(r>=.5)for(let a=0;a!==s;++a)e[t+a]=e[n+a]}_slerp(e,t,n,r){Pt.slerpFlat(e,t,e,t,e,n,r)}_slerpAdditive(e,t,n,r,s){let a=this._workIndex*s;Pt.multiplyQuaternionsFlat(e,a,e,t,e,n),Pt.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,n,r,s){let a=1-r;for(let o=0;o!==s;++o){let l=t+o;e[l]=e[l]*a+e[n+o]*r}}_lerpAdditive(e,t,n,r,s){for(let a=0;a!==s;++a){let o=t+a;e[o]=e[o]+e[n+a]*r}}},Wd="\\[\\]\\.:\\/",bS=new RegExp("["+Wd+"]","g"),qd="[^"+Wd+"]",xS="[^"+Wd.replace("\\.","")+"]",_S=/((?:WC+[\/:])*)/.source.replace("WC",qd),yS=/(WCOD+)?/.source.replace("WCOD",xS),vS=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",qd),SS=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",qd),wS=new RegExp("^"+_S+yS+vS+SS+"$"),MS=["material","materials","bones","map"],xd=class{constructor(e,t,n){let r=n||Ut.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,s=n.length;r!==s;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},Ut=class i{constructor(e,t,n){this.path=t,this.parsedPath=n||i.parseTrackName(t),this.node=i.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new i.Composite(e,t,n):new i(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(bS,"")}static parseTrackName(e){let t=wS.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(".");if(r!==void 0&&r!==-1){let s=n.nodeName.substring(r+1);MS.indexOf(s)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=s)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(s){for(let a=0;a<s.length;a++){let o=s[a];if(o.name===t||o.uuid===t)return o;let l=n(o.children);if(l)return l}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,s=n.length;r!==s;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,s=n.length;r!==s;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,s=n.length;r!==s;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,s=n.length;r!==s;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let e=this.node,t=this.parsedPath,n=t.objectName,r=t.propertyName,s=t.propertyIndex;if(e||(e=i.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){Ke("PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let c=t.objectIndex;switch(n){case"materials":if(!e.material){et("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){et("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}e=e.material.materials;break;case"bones":if(!e.skeleton){et("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let h=0;h<e.length;h++)if(e[h].name===c){c=h;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){et("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){et("PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}e=e.material.map;break;default:if(e[n]===void 0){et("PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(c!==void 0){if(e[c]===void 0){et("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[c]}}let a=e[r];if(a===void 0){let c=t.nodeName;et("PropertyBinding: Trying to update property for track: "+c+"."+r+" but it wasn't found.",e);return}let o=this.Versioning.None;this.targetObject=e,e.isMaterial===!0?o=this.Versioning.NeedsUpdate:e.isObject3D===!0&&(o=this.Versioning.MatrixWorldNeedsUpdate);let l=this.BindingType.Direct;if(s!==void 0){if(r==="morphTargetInfluences"){if(!e.geometry){et("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){et("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}e.morphTargetDictionary[s]!==void 0&&(s=e.morphTargetDictionary[s])}l=this.BindingType.ArrayElement,this.resolvedProperty=a,this.propertyIndex=s}else a.fromArray!==void 0&&a.toArray!==void 0?(l=this.BindingType.HasFromToArray,this.resolvedProperty=a):Array.isArray(a)?(l=this.BindingType.EntireArray,this.resolvedProperty=a):this.propertyName=r;this.getValue=this.GetterByBindingType[l],this.setValue=this.SetterByBindingTypeAndVersioning[l][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};Ut.Composite=xd;Ut.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};Ut.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};Ut.prototype.GetterByBindingType=[Ut.prototype._getValue_direct,Ut.prototype._getValue_array,Ut.prototype._getValue_arrayElement,Ut.prototype._getValue_toArray];Ut.prototype.SetterByBindingTypeAndVersioning=[[Ut.prototype._setValue_direct,Ut.prototype._setValue_direct_setNeedsUpdate,Ut.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Ut.prototype._setValue_array,Ut.prototype._setValue_array_setNeedsUpdate,Ut.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Ut.prototype._setValue_arrayElement,Ut.prototype._setValue_arrayElement_setNeedsUpdate,Ut.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Ut.prototype._setValue_fromArray,Ut.prototype._setValue_fromArray_setNeedsUpdate,Ut.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];Tl=class{constructor(e,t,n=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=r;let s=t.tracks,a=s.length,o=new Array(a),l={endingStart:hs,endingEnd:hs};for(let c=0;c!==a;++c){let h=s[c].createInterpolant(null);o[c]=h,h.settings&&Object.assign(l,h.settings),h.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=Fo,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){let r=this._clip.duration,s=e._clip.duration,a=s/r,o=r/s;e.warp(1,a,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){let r=this._mixer,s=r.time,a=this.timeScale,o=this._timeScaleInterpolant;o===null&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);let l=o.parameterPositions,c=o.sampleValues;return l[0]=s,l[1]=s+n,c[0]=e/a,c[1]=t/a,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,r){if(!this.enabled){this._updateWeight(e);return}let s=this._startTime;if(s!==null){let l=(e-s)*n;l<0||n===0?t=0:(this._startTime=null,t=n*l)}t*=this._updateTimeScale(e);let a=this._updateTime(t),o=this._updateWeight(e);if(o>0){let l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case Uo:for(let h=0,d=l.length;h!==d;++h)l[h].evaluate(a),c[h].accumulateAdditive(o);break;case mh:default:for(let h=0,d=l.length;h!==d;++h)l[h].evaluate(a),c[h].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,r=this.time+e,s=this._loopCount,a=n===m0;if(e===0)return s===-1?r:a&&(s&1)===1?t-r:r;if(n===_a){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(s===-1&&(e>=0?(s=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let o=Math.floor(r/t);r-=t*o,s+=Math.abs(o);let l=this.repetitions-s;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){let c=e<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=s,this.time=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this._loopCount=s,this.time=r;if(a&&(s&1)===1)return t-r}return r}_setEndings(e,t,n){let r=this._interpolantSettings;n?(r.endingStart=us,r.endingEnd=us):(e?r.endingStart=this.zeroSlopeAtStart?us:hs:r.endingStart=Za,t?r.endingEnd=this.zeroSlopeAtEnd?us:hs:r.endingEnd=Za)}_scheduleFading(e,t,n){let r=this._mixer,s=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,l=a.sampleValues;return o[0]=s,l[0]=t,o[1]=s+e,l[1]=n,this}},AS=new Float32Array(1),Ms=class extends Li{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(e,t){let n=e._localRoot||this._root,r=e._clip.tracks,s=r.length,a=e._propertyBindings,o=e._interpolants,l=n.uuid,c=this._bindingsByRootAndName,h=c[l];h===void 0&&(h={},c[l]=h);for(let d=0;d!==s;++d){let f=r[d],p=f.name,x=h[p];if(x!==void 0)++x.referenceCount,a[d]=x;else{if(x=a[d],x!==void 0){x._cacheIndex===null&&(++x.referenceCount,this._addInactiveBinding(x,l,p));continue}let y=t&&t._propertyBindings[d].binding.parsedPath;x=new Al(Ut.create(n,p,y),f.ValueTypeName,f.getValueSize()),++x.referenceCount,this._addInactiveBinding(x,l,p),a[d]=x}o[d].resultBuffer=x.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let n=(e._localRoot||this._root).uuid,r=e._clip.uuid,s=this._actionsByClip[r];this._bindAction(e,s&&s.knownActions[0]),this._addInactiveAction(e,r,n)}let t=e._propertyBindings;for(let n=0,r=t.length;n!==r;++n){let s=t[n];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let n=0,r=t.length;n!==r;++n){let s=t[n];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){let r=this._actions,s=this._actionsByClip,a=s[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,s[t]=a;else{let o=a.knownActions;e._byClipCacheIndex=o.length,o.push(e)}e._cacheIndex=r.length,r.push(e),a.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],r=e._cacheIndex;n._cacheIndex=r,t[r]=n,t.pop(),e._cacheIndex=null;let s=e._clip.uuid,a=this._actionsByClip,o=a[s],l=o.knownActions,c=l[l.length-1],h=e._byClipCacheIndex;c._byClipCacheIndex=h,l[h]=c,l.pop(),e._byClipCacheIndex=null;let d=o.actionByRoot,f=(e._localRoot||this._root).uuid;delete d[f],l.length===0&&delete a[s],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let n=0,r=t.length;n!==r;++n){let s=t[n];--s.referenceCount===0&&this._removeInactiveBinding(s)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,r=this._nActiveActions++,s=t[r];e._cacheIndex=r,t[r]=e,s._cacheIndex=n,t[n]=s}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,r=--this._nActiveActions,s=t[r];e._cacheIndex=r,t[r]=e,s._cacheIndex=n,t[n]=s}_addInactiveBinding(e,t,n){let r=this._bindingsByRootAndName,s=this._bindings,a=r[t];a===void 0&&(a={},r[t]=a),a[n]=e,e._cacheIndex=s.length,s.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,r=n.rootNode.uuid,s=n.path,a=this._bindingsByRootAndName,o=a[r],l=t[t.length-1],c=e._cacheIndex;l._cacheIndex=c,t[c]=l,t.pop(),delete o[s],Object.keys(o).length===0&&delete a[r]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,r=this._nActiveBindings++,s=t[r];e._cacheIndex=r,t[r]=e,s._cacheIndex=n,t[n]=s}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,r=--this._nActiveBindings,s=t[r];e._cacheIndex=r,t[r]=e,s._cacheIndex=n,t[n]=s}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];return n===void 0&&(n=new go(new Float32Array(2),new Float32Array(2),1,AS),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,r=--this._nActiveControlInterpolants,s=t[r];e.__cacheIndex=r,t[r]=e,s.__cacheIndex=n,t[n]=s}clipAction(e,t,n){let r=t||this._root,s=r.uuid,a=typeof e=="string"?bi.findByName(r,e):e,o=a!==null?a.uuid:e,l=this._actionsByClip[o],c=null;if(n===void 0&&(a!==null?n=a.blendMode:n=mh),l!==void 0){let d=l.actionByRoot[s];if(d!==void 0&&d.blendMode===n)return d;c=l.knownActions[0],a===null&&(a=c._clip)}if(a===null)return null;let h=new Tl(this,a,t,n);return this._bindAction(h,c),this._addInactiveAction(h,o,s),h}existingAction(e,t){let n=t||this._root,r=n.uuid,s=typeof e=="string"?bi.findByName(n,e):e,a=s?s.uuid:e,o=this._actionsByClip[a];return o!==void 0&&o.actionByRoot[r]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,r=this.time+=e,s=Math.sign(e),a=this._accuIndex^=1;for(let c=0;c!==n;++c)t[c]._update(r,e,s,a);let o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(e){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){let t=this._actions,n=e.uuid,r=this._actionsByClip,s=r[n];if(s!==void 0){let a=s.knownActions;for(let o=0,l=a.length;o!==l;++o){let c=a[o];this._deactivateAction(c);let h=c._cacheIndex,d=t[t.length-1];c._cacheIndex=null,c._byClipCacheIndex=null,d._cacheIndex=h,t[h]=d,t.pop(),this._removeInactiveBindingsForAction(c)}delete r[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let a in n){let o=n[a].actionByRoot,l=o[t];l!==void 0&&(this._deactivateAction(l),this._removeInactiveAction(l))}let r=this._bindingsByRootAndName,s=r[t];if(s!==void 0)for(let a in s){let o=s[a];o.restoreOriginalState(),this._removeInactiveBinding(o)}}uncacheAction(e,t){let n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}},Vg=new ot,Ao=class{constructor(e,t,n=0,r=1/0){this.ray=new Br(e,t),this.near=n,this.far=r,this.camera=null,this.layers=new la,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):et("Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return Vg.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(Vg),this}intersectObject(e,t=!0,n=[]){return _d(e,this,n,t),n.sort(Wg),n}intersectObjects(e,t=!0,n=[]){for(let r=0,s=e.length;r<s;r++)_d(e[r],this,n,t);return n.sort(Wg),n}};Jd=class Jd{constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let s=this.elements;return s[0]=e,s[2]=t,s[1]=n,s[3]=r,this}};Jd.prototype.isMatrix2=!0;yd=Jd,To=class extends fa{constructor(e=10,t=10,n=4473924,r=8947848){n=new Ve(n),r=new Ve(r);let s=t/2,a=e/t,o=e/2,l=[],c=[];for(let f=0,p=0,x=-o;f<=t;f++,x+=a){l.push(-o,0,x,o,0,x),l.push(x,0,-o,x,0,o);let y=f===s?n:r;y.toArray(c,p),p+=3,y.toArray(c,p),p+=3,y.toArray(c,p),p+=3,y.toArray(c,p),p+=3}let h=new mn;h.setAttribute("position",new Qt(l,3)),h.setAttribute("color",new Qt(c,3));let d=new ys({vertexColors:!0,toneMapped:!1});super(h,d),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}};typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"184"}}));typeof window<"u"&&(window.__THREE__?Ke("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="184")});function tb(){let i=null,e=!1,t=null,n=null;function r(s,a){t(s,a),n=i.requestAnimationFrame(r)}return{start:function(){e!==!0&&t!==null&&i!==null&&(n=i.requestAnimationFrame(r),e=!0)},stop:function(){i!==null&&i.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){i=s}}}function RS(i){let e=new WeakMap;function t(o,l){let c=o.array,h=o.usage,d=c.byteLength,f=i.createBuffer();i.bindBuffer(l,f),i.bufferData(l,c,h),o.onUploadCallback();let p;if(c instanceof Float32Array)p=i.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)p=i.HALF_FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?p=i.HALF_FLOAT:p=i.UNSIGNED_SHORT;else if(c instanceof Int16Array)p=i.SHORT;else if(c instanceof Uint32Array)p=i.UNSIGNED_INT;else if(c instanceof Int32Array)p=i.INT;else if(c instanceof Int8Array)p=i.BYTE;else if(c instanceof Uint8Array)p=i.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)p=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:f,type:p,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function n(o,l,c){let h=l.array,d=l.updateRanges;if(i.bindBuffer(c,o),d.length===0)i.bufferSubData(c,0,h);else{d.sort((p,x)=>p.start-x.start);let f=0;for(let p=1;p<d.length;p++){let x=d[f],y=d[p];y.start<=x.start+x.count+1?x.count=Math.max(x.count,y.start+y.count-x.start):(++f,d[f]=y)}d.length=f+1;for(let p=0,x=d.length;p<x;p++){let y=d[p];i.bufferSubData(c,y.start*h.BYTES_PER_ELEMENT,h,y.start,y.count)}l.clearUpdateRanges()}l.onUploadCallback()}function r(o){return o.isInterleavedBufferAttribute&&(o=o.data),e.get(o)}function s(o){o.isInterleavedBufferAttribute&&(o=o.data);let l=e.get(o);l&&(i.deleteBuffer(l.buffer),e.delete(o))}function a(o,l){if(o.isInterleavedBufferAttribute&&(o=o.data),o.isGLBufferAttribute){let h=e.get(o);(!h||h.version<o.version)&&e.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}let c=e.get(o);if(c===void 0)e.set(o,t(o,l));else if(c.version<o.version){if(c.size!==o.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(c.buffer,o,l),c.version=o.version}}return{get:r,remove:s,update:a}}function hM(i,e,t,n,r,s){let a=new Ve(0),o=r===!0?0:1,l,c,h=null,d=0,f=null;function p(S){let A=S.isScene===!0?S.background:null;if(A&&A.isTexture){let T=S.backgroundBlurriness>0;A=e.get(A,T)}return A}function x(S){let A=!1,T=p(S);T===null?b(a,o):T&&T.isColor&&(b(T,1),A=!0);let N=i.xr.getEnvironmentBlendMode();N==="additive"?t.buffers.color.setClear(0,0,0,1,s):N==="alpha-blend"&&t.buffers.color.setClear(0,0,0,0,s),(i.autoClear||A)&&(t.buffers.depth.setTest(!0),t.buffers.depth.setMask(!0),t.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function y(S,A){let T=p(A);T&&(T.isCubeTexture||T.mapping===Co)?(c===void 0&&(c=new xt(new Hr(1,1,1),new ai({name:"BackgroundCubeMaterial",uniforms:Es(Qi.backgroundCube.uniforms),vertexShader:Qi.backgroundCube.vertexShader,fragmentShader:Qi.backgroundCube.fragmentShader,side:An,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(N,P,U){this.matrixWorld.copyPosition(U.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(c)),c.material.uniforms.envMap.value=T,c.material.uniforms.backgroundBlurriness.value=A.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=A.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(lM.makeRotationFromEuler(A.backgroundRotation)).transpose(),T.isCubeTexture&&T.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(nb),c.material.toneMapped=ut.getTransfer(T.colorSpace)!==Dt,(h!==T||d!==T.version||f!==i.toneMapping)&&(c.material.needsUpdate=!0,h=T,d=T.version,f=i.toneMapping),c.layers.enableAll(),S.unshift(c,c.geometry,c.material,0,0,null)):T&&T.isTexture&&(l===void 0&&(l=new xt(new mi(2,2),new ai({name:"BackgroundMaterial",uniforms:Es(Qi.background.uniforms),vertexShader:Qi.background.vertexShader,fragmentShader:Qi.background.fragmentShader,side:Pi,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(l)),l.material.uniforms.t2D.value=T,l.material.uniforms.backgroundIntensity.value=A.backgroundIntensity,l.material.toneMapped=ut.getTransfer(T.colorSpace)!==Dt,T.matrixAutoUpdate===!0&&T.updateMatrix(),l.material.uniforms.uvTransform.value.copy(T.matrix),(h!==T||d!==T.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,h=T,d=T.version,f=i.toneMapping),l.layers.enableAll(),S.unshift(l,l.geometry,l.material,0,0,null))}function b(S,A){S.getRGB(xh,Gd(i)),t.buffers.color.setClear(xh.r,xh.g,xh.b,A,s)}function g(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(S,A=1){a.set(S),o=A,b(a,o)},getClearAlpha:function(){return o},setClearAlpha:function(S){o=S,b(a,o)},render:x,addToRenderList:y,dispose:g}}function uM(i,e){let t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},r=f(null),s=r,a=!1;function o(k,V,J,L,E){let D=!1,O=d(k,L,J,V);s!==O&&(s=O,c(s.object)),D=p(k,L,J,E),D&&x(k,L,J,E),E!==null&&e.update(E,i.ELEMENT_ARRAY_BUFFER),(D||a)&&(a=!1,T(k,V,J,L),E!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(E).buffer))}function l(){return i.createVertexArray()}function c(k){return i.bindVertexArray(k)}function h(k){return i.deleteVertexArray(k)}function d(k,V,J,L){let E=L.wireframe===!0,D=n[V.id];D===void 0&&(D={},n[V.id]=D);let O=k.isInstancedMesh===!0?k.id:0,H=D[O];H===void 0&&(H={},D[O]=H);let Y=H[J.id];Y===void 0&&(Y={},H[J.id]=Y);let le=Y[E];return le===void 0&&(le=f(l()),Y[E]=le),le}function f(k){let V=[],J=[],L=[];for(let E=0;E<t;E++)V[E]=0,J[E]=0,L[E]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:V,enabledAttributes:J,attributeDivisors:L,object:k,attributes:{},index:null}}function p(k,V,J,L){let E=s.attributes,D=V.attributes,O=0,H=J.getAttributes();for(let Y in H)if(H[Y].location>=0){let fe=E[Y],be=D[Y];if(be===void 0&&(Y==="instanceMatrix"&&k.instanceMatrix&&(be=k.instanceMatrix),Y==="instanceColor"&&k.instanceColor&&(be=k.instanceColor)),fe===void 0||fe.attribute!==be||be&&fe.data!==be.data)return!0;O++}return s.attributesNum!==O||s.index!==L}function x(k,V,J,L){let E={},D=V.attributes,O=0,H=J.getAttributes();for(let Y in H)if(H[Y].location>=0){let fe=D[Y];fe===void 0&&(Y==="instanceMatrix"&&k.instanceMatrix&&(fe=k.instanceMatrix),Y==="instanceColor"&&k.instanceColor&&(fe=k.instanceColor));let be={};be.attribute=fe,fe&&fe.data&&(be.data=fe.data),E[Y]=be,O++}s.attributes=E,s.attributesNum=O,s.index=L}function y(){let k=s.newAttributes;for(let V=0,J=k.length;V<J;V++)k[V]=0}function b(k){g(k,0)}function g(k,V){let J=s.newAttributes,L=s.enabledAttributes,E=s.attributeDivisors;J[k]=1,L[k]===0&&(i.enableVertexAttribArray(k),L[k]=1),E[k]!==V&&(i.vertexAttribDivisor(k,V),E[k]=V)}function S(){let k=s.newAttributes,V=s.enabledAttributes;for(let J=0,L=V.length;J<L;J++)V[J]!==k[J]&&(i.disableVertexAttribArray(J),V[J]=0)}function A(k,V,J,L,E,D,O){O===!0?i.vertexAttribIPointer(k,V,J,E,D):i.vertexAttribPointer(k,V,J,L,E,D)}function T(k,V,J,L){y();let E=L.attributes,D=J.getAttributes(),O=V.defaultAttributeValues;for(let H in D){let Y=D[H];if(Y.location>=0){let le=E[H];if(le===void 0&&(H==="instanceMatrix"&&k.instanceMatrix&&(le=k.instanceMatrix),H==="instanceColor"&&k.instanceColor&&(le=k.instanceColor)),le!==void 0){let fe=le.normalized,be=le.itemSize,Te=e.get(le);if(Te===void 0)continue;let Je=Te.buffer,ke=Te.type,oe=Te.bytesPerElement,Ee=ke===i.INT||ke===i.UNSIGNED_INT||le.gpuType===Ll;if(le.isInterleavedBufferAttribute){let _e=le.data,Ze=_e.stride,tt=le.offset;if(_e.isInstancedInterleavedBuffer){for(let Qe=0;Qe<Y.locationSize;Qe++)g(Y.location+Qe,_e.meshPerAttribute);k.isInstancedMesh!==!0&&L._maxInstanceCount===void 0&&(L._maxInstanceCount=_e.meshPerAttribute*_e.count)}else for(let Qe=0;Qe<Y.locationSize;Qe++)b(Y.location+Qe);i.bindBuffer(i.ARRAY_BUFFER,Je);for(let Qe=0;Qe<Y.locationSize;Qe++)A(Y.location+Qe,be/Y.locationSize,ke,fe,Ze*oe,(tt+be/Y.locationSize*Qe)*oe,Ee)}else{if(le.isInstancedBufferAttribute){for(let _e=0;_e<Y.locationSize;_e++)g(Y.location+_e,le.meshPerAttribute);k.isInstancedMesh!==!0&&L._maxInstanceCount===void 0&&(L._maxInstanceCount=le.meshPerAttribute*le.count)}else for(let _e=0;_e<Y.locationSize;_e++)b(Y.location+_e);i.bindBuffer(i.ARRAY_BUFFER,Je);for(let _e=0;_e<Y.locationSize;_e++)A(Y.location+_e,be/Y.locationSize,ke,fe,be*oe,be/Y.locationSize*_e*oe,Ee)}}else if(O!==void 0){let fe=O[H];if(fe!==void 0)switch(fe.length){case 2:i.vertexAttrib2fv(Y.location,fe);break;case 3:i.vertexAttrib3fv(Y.location,fe);break;case 4:i.vertexAttrib4fv(Y.location,fe);break;default:i.vertexAttrib1fv(Y.location,fe)}}}}S()}function N(){I();for(let k in n){let V=n[k];for(let J in V){let L=V[J];for(let E in L){let D=L[E];for(let O in D)h(D[O].object),delete D[O];delete L[E]}}delete n[k]}}function P(k){if(n[k.id]===void 0)return;let V=n[k.id];for(let J in V){let L=V[J];for(let E in L){let D=L[E];for(let O in D)h(D[O].object),delete D[O];delete L[E]}}delete n[k.id]}function U(k){for(let V in n){let J=n[V];for(let L in J){let E=J[L];if(E[k.id]===void 0)continue;let D=E[k.id];for(let O in D)h(D[O].object),delete D[O];delete E[k.id]}}}function v(k){for(let V in n){let J=n[V],L=k.isInstancedMesh===!0?k.id:0,E=J[L];if(E!==void 0){for(let D in E){let O=E[D];for(let H in O)h(O[H].object),delete O[H];delete E[D]}delete J[L],Object.keys(J).length===0&&delete n[V]}}}function I(){B(),a=!0,s!==r&&(s=r,c(s.object))}function B(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:o,reset:I,resetDefaultState:B,dispose:N,releaseStatesOfGeometry:P,releaseStatesOfObject:v,releaseStatesOfProgram:U,initAttributes:y,enableAttribute:b,disableUnusedAttributes:S}}function dM(i,e,t){let n;function r(l){n=l}function s(l,c){i.drawArrays(n,l,c),t.update(c,n,1)}function a(l,c,h){h!==0&&(i.drawArraysInstanced(n,l,c,h),t.update(c,n,h))}function o(l,c,h){if(h===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,c,0,h);let f=0;for(let p=0;p<h;p++)f+=c[p];t.update(f,n,1)}this.setMode=r,this.render=s,this.renderInstances=a,this.renderMultiDraw=o}function fM(i,e,t,n){let r;function s(){if(r!==void 0)return r;if(e.has("EXT_texture_filter_anisotropic")===!0){let U=e.get("EXT_texture_filter_anisotropic");r=i.getParameter(U.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}function a(U){return!(U!==ci&&n.convert(U)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(U){let v=U===Gn&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(U!==Qn&&n.convert(U)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&U!==Tn&&!v)}function l(U){if(U==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";U="mediump"}return U==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp",h=l(c);h!==c&&(Ke("WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);let d=t.logarithmicDepthBuffer===!0,f=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control");t.reversedDepthBuffer===!0&&f===!1&&Ke("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),x=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),y=i.getParameter(i.MAX_TEXTURE_SIZE),b=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),g=i.getParameter(i.MAX_VERTEX_ATTRIBS),S=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),A=i.getParameter(i.MAX_VARYING_VECTORS),T=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),N=i.getParameter(i.MAX_SAMPLES),P=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:x,maxTextureSize:y,maxCubemapSize:b,maxAttributes:g,maxVertexUniforms:S,maxVaryings:A,maxFragmentUniforms:T,maxSamples:N,samples:P}}function pM(i){let e=this,t=null,n=0,r=!1,s=!1,a=new Gi,o=new ct,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,f){let p=d.length!==0||f||n!==0||r;return r=f,n=d.length,p},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(d,f){t=h(d,f,0)},this.setState=function(d,f,p){let x=d.clippingPlanes,y=d.clipIntersection,b=d.clipShadows,g=i.get(d);if(!r||x===null||x.length===0||s&&!b)s?h(null):c();else{let S=s?0:n,A=S*4,T=g.clippingState||null;l.value=T,T=h(x,f,A,p);for(let N=0;N!==A;++N)T[N]=t[N];g.clippingState=T,this.numIntersection=y?this.numPlanes:0,this.numPlanes+=S}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function h(d,f,p,x){let y=d!==null?d.length:0,b=null;if(y!==0){if(b=l.value,x!==!0||b===null){let g=p+y*4,S=f.matrixWorldInverse;o.getNormalMatrix(S),(b===null||b.length<g)&&(b=new Float32Array(g));for(let A=0,T=p;A!==y;++A,T+=4)a.copy(d[A]).applyMatrix4(S,o),a.normal.toArray(b,T),b[T+3]=a.constant}l.value=b,l.needsUpdate=!0}return e.numPlanes=y,e.numIntersection=0,b}}function bM(i){let e=[],t=[],n=[],r=i,s=i-Kr+1+D0.length;for(let a=0;a<s;a++){let o=Math.pow(2,r);e.push(o);let l=1/o;a>i-Kr?l=D0[a-i+Kr-1]:a===0&&(l=0),t.push(l);let c=1/(o-2),h=-c,d=1+c,f=[h,h,d,h,d,d,h,h,d,d,h,d],p=6,x=6,y=3,b=2,g=1,S=new Float32Array(y*x*p),A=new Float32Array(b*x*p),T=new Float32Array(g*x*p);for(let P=0;P<p;P++){let U=P%3*2/3-1,v=P>2?0:-1,I=[U,v,0,U+2/3,v,0,U+2/3,v+1,0,U,v,0,U+2/3,v+1,0,U,v+1,0];S.set(I,y*x*P),A.set(f,b*x*P);let B=[P,P,P,P,P,P];T.set(B,g*x*P)}let N=new mn;N.setAttribute("position",new Kt(S,y)),N.setAttribute("uv",new Kt(A,b)),N.setAttribute("faceIndex",new Kt(T,g)),n.push(new xt(N,null)),r>Kr&&r--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function O0(i,e,t){let n=new Hn(i,e,t);return n.texture.mapping=Co,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function va(i,e,t,n,r){i.viewport.set(e,t,n,r),i.scissor.set(e,t,n,r)}function xM(i,e,t){return new ai({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:mM,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:vh(),fragmentShader:`
+
+ precision highp float;
+ precision highp int;
+
+ varying vec3 vOutputDirection;
+
+ uniform sampler2D envMap;
+ uniform float roughness;
+ uniform float mipInt;
+
+ #define ENVMAP_TYPE_CUBE_UV
+ #include <cube_uv_reflection_fragment>
+
+ #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:Ji,depthTest:!1,depthWrite:!1})}function _M(i,e,t){let n=new Float32Array(Rs),r=new W(0,1,0);return new ai({name:"SphericalGaussianBlur",defines:{n:Rs,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:vh(),fragmentShader:`
+
+ precision mediump float;
+ precision mediump int;
+
+ varying vec3 vOutputDirection;
+
+ uniform sampler2D envMap;
+ uniform int samples;
+ uniform float weights[ n ];
+ uniform bool latitudinal;
+ uniform float dTheta;
+ uniform float mipInt;
+ uniform vec3 poleAxis;
+
+ #define ENVMAP_TYPE_CUBE_UV
+ #include <cube_uv_reflection_fragment>
+
+ vec3 getSample( float theta, vec3 axis ) {
+
+ float cosTheta = cos( theta );
+ // Rodrigues' axis-angle rotation
+ vec3 sampleDirection = vOutputDirection * cosTheta
+ + cross( axis, vOutputDirection ) * sin( theta )
+ + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
+
+ return bilinearCubeUV( envMap, sampleDirection, mipInt );
+
+ }
+
+ void main() {
+
+ vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
+
+ if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
+
+ axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
+
+ }
+
+ axis = normalize( axis );
+
+ gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
+ gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
+
+ for ( int i = 1; i < n; i++ ) {
+
+ if ( i >= samples ) {
+
+ break;
+
+ }
+
+ float theta = dTheta * float( i );
+ gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
+ gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
+
+ }
+
+ }
+ `,blending:Ji,depthTest:!1,depthWrite:!1})}function F0(){return new ai({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:vh(),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:Ji,depthTest:!1,depthWrite:!1})}function U0(){return new ai({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:vh(),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:Ji,depthTest:!1,depthWrite:!1})}function vh(){return`
+
+ precision mediump float;
+ precision mediump int;
+
+ attribute float faceIndex;
+
+ varying vec3 vOutputDirection;
+
+ // RH coordinate system; PMREM face-indexing convention
+ vec3 getDirection( vec2 uv, float face ) {
+
+ uv = 2.0 * uv - 1.0;
+
+ vec3 direction = vec3( uv, 1.0 );
+
+ if ( face == 0.0 ) {
+
+ direction = direction.zyx; // ( 1, v, u ) pos x
+
+ } else if ( face == 1.0 ) {
+
+ direction = direction.xzy;
+ direction.xz *= -1.0; // ( -u, 1, -v ) pos y
+
+ } else if ( face == 2.0 ) {
+
+ direction.x *= -1.0; // ( -u, v, 1 ) pos z
+
+ } else if ( face == 3.0 ) {
+
+ direction = direction.zyx;
+ direction.xz *= -1.0; // ( -1, v, -u ) neg x
+
+ } else if ( face == 4.0 ) {
+
+ direction = direction.xzy;
+ direction.xy *= -1.0; // ( -u, -1, v ) neg y
+
+ } else if ( face == 5.0 ) {
+
+ direction.z *= -1.0; // ( u, v, -1 ) neg z
+
+ }
+
+ return direction;
+
+ }
+
+ void main() {
+
+ vOutputDirection = getDirection( uv, faceIndex );
+ gl_Position = vec4( position, 1.0 );
+
+ }
+ `}function yM(i){let e=new WeakMap,t=new WeakMap,n=null;function r(f,p=!1){return f==null?null:p?a(f):s(f)}function s(f){if(f&&f.isTexture){let p=f.mapping;if(p===Cl||p===Il)if(e.has(f)){let x=e.get(f).texture;return o(x,f.mapping)}else{let x=f.image;if(x&&x.height>0){let y=new Ma(x.height);return y.fromEquirectangularTexture(i,f),e.set(f,y),f.addEventListener("dispose",c),o(y.texture,f.mapping)}else return null}}return f}function a(f){if(f&&f.isTexture){let p=f.mapping,x=p===Cl||p===Il,y=p===$r||p===As;if(x||y){let b=t.get(f),g=b!==void 0?b.texture.pmremVersion:0;if(f.isRenderTargetTexture&&f.pmremVersion!==g)return n===null&&(n=new wa(i)),b=x?n.fromEquirectangular(f,b):n.fromCubemap(f,b),b.texture.pmremVersion=f.pmremVersion,t.set(f,b),b.texture;if(b!==void 0)return b.texture;{let S=f.image;return x&&S&&S.height>0||y&&S&&l(S)?(n===null&&(n=new wa(i)),b=x?n.fromEquirectangular(f):n.fromCubemap(f),b.texture.pmremVersion=f.pmremVersion,t.set(f,b),f.addEventListener("dispose",h),b.texture):null}}}return f}function o(f,p){return p===Cl?f.mapping=$r:p===Il&&(f.mapping=As),f}function l(f){let p=0,x=6;for(let y=0;y<x;y++)f[y]!==void 0&&p++;return p===x}function c(f){let p=f.target;p.removeEventListener("dispose",c);let x=e.get(p);x!==void 0&&(e.delete(p),x.dispose())}function h(f){let p=f.target;p.removeEventListener("dispose",h);let x=t.get(p);x!==void 0&&(t.delete(p),x.dispose())}function d(){e=new WeakMap,t=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:d}}function vM(i){let e={};function t(n){if(e[n]!==void 0)return e[n];let r=i.getExtension(n);return e[n]=r,r}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){let r=t(n);return r===null&&al("WebGLRenderer: "+n+" extension not supported."),r}}}function SM(i,e,t,n){let r={},s=new WeakMap;function a(d){let f=d.target;f.index!==null&&e.remove(f.index);for(let x in f.attributes)e.remove(f.attributes[x]);f.removeEventListener("dispose",a),delete r[f.id];let p=s.get(f);p&&(e.remove(p),s.delete(f)),n.releaseStatesOfGeometry(f),f.isInstancedBufferGeometry===!0&&delete f._maxInstanceCount,t.memory.geometries--}function o(d,f){return r[f.id]===!0||(f.addEventListener("dispose",a),r[f.id]=!0,t.memory.geometries++),f}function l(d){let f=d.attributes;for(let p in f)e.update(f[p],i.ARRAY_BUFFER)}function c(d){let f=[],p=d.index,x=d.attributes.position,y=0;if(x===void 0)return;if(p!==null){let S=p.array;y=p.version;for(let A=0,T=S.length;A<T;A+=3){let N=S[A+0],P=S[A+1],U=S[A+2];f.push(N,P,P,U,U,N)}}else{let S=x.array;y=x.version;for(let A=0,T=S.length/3-1;A<T;A+=3){let N=A+0,P=A+1,U=A+2;f.push(N,P,P,U,U,N)}}let b=new(x.count>=65535?ro:io)(f,1);b.version=y;let g=s.get(d);g&&e.remove(g),s.set(d,b)}function h(d){let f=s.get(d);if(f){let p=d.index;p!==null&&f.version<p.version&&c(d)}else c(d);return s.get(d)}return{get:o,update:l,getWireframeAttribute:h}}function wM(i,e,t){let n;function r(d){n=d}let s,a;function o(d){s=d.type,a=d.bytesPerElement}function l(d,f){i.drawElements(n,f,s,d*a),t.update(f,n,1)}function c(d,f,p){p!==0&&(i.drawElementsInstanced(n,f,s,d*a,p),t.update(f,n,p))}function h(d,f,p){if(p===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,s,d,0,p);let y=0;for(let b=0;b<p;b++)y+=f[b];t.update(y,n,1)}this.setMode=r,this.setIndex=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=h}function MM(i){let e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(s,a,o){switch(t.calls++,a){case i.TRIANGLES:t.triangles+=o*(s/3);break;case i.LINES:t.lines+=o*(s/2);break;case i.LINE_STRIP:t.lines+=o*(s-1);break;case i.LINE_LOOP:t.lines+=o*s;break;case i.POINTS:t.points+=o*s;break;default:et("WebGLInfo: Unknown draw mode:",a);break}}function r(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:r,update:n}}function AM(i,e,t){let n=new WeakMap,r=new kt;function s(a,o,l){let c=a.morphTargetInfluences,h=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,d=h!==void 0?h.length:0,f=n.get(o);if(f===void 0||f.count!==d){let I=function(){U.dispose(),n.delete(o),o.removeEventListener("dispose",I)};f!==void 0&&f.texture.dispose();let p=o.morphAttributes.position!==void 0,x=o.morphAttributes.normal!==void 0,y=o.morphAttributes.color!==void 0,b=o.morphAttributes.position||[],g=o.morphAttributes.normal||[],S=o.morphAttributes.color||[],A=0;p===!0&&(A=1),x===!0&&(A=2),y===!0&&(A=3);let T=o.attributes.position.count*A,N=1;T>e.maxTextureSize&&(N=Math.ceil(T/e.maxTextureSize),T=e.maxTextureSize);let P=new Float32Array(T*N*4*d),U=new to(P,T,N,d);U.type=Tn,U.needsUpdate=!0;let v=A*4;for(let B=0;B<d;B++){let k=b[B],V=g[B],J=S[B],L=T*N*4*B;for(let E=0;E<k.count;E++){let D=E*v;p===!0&&(r.fromBufferAttribute(k,E),P[L+D+0]=r.x,P[L+D+1]=r.y,P[L+D+2]=r.z,P[L+D+3]=0),x===!0&&(r.fromBufferAttribute(V,E),P[L+D+4]=r.x,P[L+D+5]=r.y,P[L+D+6]=r.z,P[L+D+7]=0),y===!0&&(r.fromBufferAttribute(J,E),P[L+D+8]=r.x,P[L+D+9]=r.y,P[L+D+10]=r.z,P[L+D+11]=J.itemSize===4?r.w:1)}}f={count:d,texture:U,size:new dt(T,N)},n.set(o,f),o.addEventListener("dispose",I)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)l.getUniforms().setValue(i,"morphTexture",a.morphTexture,t);else{let p=0;for(let y=0;y<c.length;y++)p+=c[y];let x=o.morphTargetsRelative?1:1-p;l.getUniforms().setValue(i,"morphTargetBaseInfluence",x),l.getUniforms().setValue(i,"morphTargetInfluences",c)}l.getUniforms().setValue(i,"morphTargetsTexture",f.texture,t),l.getUniforms().setValue(i,"morphTargetsTextureSize",f.size)}return{update:s}}function TM(i,e,t,n,r){let s=new WeakMap;function a(c){let h=r.render.frame,d=c.geometry,f=e.get(c,d);if(s.get(f)!==h&&(e.update(f),s.set(f,h)),c.isInstancedMesh&&(c.hasEventListener("dispose",l)===!1&&c.addEventListener("dispose",l),s.get(c)!==h&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),s.set(c,h))),c.isSkinnedMesh){let p=c.skeleton;s.get(p)!==h&&(p.update(),s.set(p,h))}return f}function o(){s=new WeakMap}function l(c){let h=c.target;h.removeEventListener("dispose",l),n.releaseStatesOfObject(h),t.remove(h.instanceMatrix),h.instanceColor!==null&&t.remove(h.instanceColor)}return{update:a,dispose:o}}function RM(i,e,t,n,r){let s=new Hn(e,t,{type:i,depthBuffer:n,stencilBuffer:r,depthTexture:n?new pr(e,t):void 0}),a=new Hn(e,t,{type:Gn,depthBuffer:!1,stencilBuffer:!1}),o=new mn;o.setAttribute("position",new Qt([-1,3,0,-1,-1,0,3,-1,0],3)),o.setAttribute("uv",new Qt([0,2,0,0,2,0],2));let l=new fl({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}),c=new xt(o,l),h=new Wr(-1,1,1,-1,0,1),d=null,f=null,p=!1,x,y=null,b=[],g=!1;this.setSize=function(S,A){s.setSize(S,A),a.setSize(S,A);for(let T=0;T<b.length;T++){let N=b[T];N.setSize&&N.setSize(S,A)}},this.setEffects=function(S){b=S,g=b.length>0&&b[0].isRenderPass===!0;let A=s.width,T=s.height;for(let N=0;N<b.length;N++){let P=b[N];P.setSize&&P.setSize(A,T)}},this.begin=function(S,A){if(p||S.toneMapping===Ni&&b.length===0)return!1;if(y=A,A!==null){let T=A.width,N=A.height;(s.width!==T||s.height!==N)&&this.setSize(T,N)}return g===!1&&S.setRenderTarget(s),x=S.toneMapping,S.toneMapping=Ni,!0},this.hasRenderPass=function(){return g},this.end=function(S,A){S.toneMapping=x,p=!0;let T=s,N=a;for(let P=0;P<b.length;P++){let U=b[P];if(U.enabled!==!1&&(U.render(S,N,T,A),U.needsSwap!==!1)){let v=T;T=N,N=v}}if(d!==S.outputColorSpace||f!==S.toneMapping){d=S.outputColorSpace,f=S.toneMapping,l.defines={},ut.getTransfer(d)===Dt&&(l.defines.SRGB_TRANSFER="");let P=EM[f];P&&(l.defines[P]=""),l.needsUpdate=!0}l.uniforms.tDiffuse.value=T.texture,S.setRenderTarget(y),S.render(c,h),y=null,p=!1},this.isCompositing=function(){return p},this.dispose=function(){s.depthTexture&&s.depthTexture.dispose(),s.dispose(),a.dispose(),o.dispose(),l.dispose()}}function Aa(i,e,t){let n=i[0];if(n<=0||n>0)return i;let r=e*t,s=k0[r];if(s===void 0&&(s=new Float32Array(r),k0[r]=s),e!==0){n.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,i[a].toArray(s,o)}return s}function _n(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function yn(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function Sh(i,e){let t=B0[e];t===void 0&&(t=new Int32Array(e),B0[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function CM(i,e){let t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function IM(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(_n(t,e))return;i.uniform2fv(this.addr,e),yn(t,e)}}function PM(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(_n(t,e))return;i.uniform3fv(this.addr,e),yn(t,e)}}function LM(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(_n(t,e))return;i.uniform4fv(this.addr,e),yn(t,e)}}function DM(i,e){let t=this.cache,n=e.elements;if(n===void 0){if(_n(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),yn(t,e)}else{if(_n(t,n))return;G0.set(n),i.uniformMatrix2fv(this.addr,!1,G0),yn(t,n)}}function NM(i,e){let t=this.cache,n=e.elements;if(n===void 0){if(_n(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),yn(t,e)}else{if(_n(t,n))return;H0.set(n),i.uniformMatrix3fv(this.addr,!1,H0),yn(t,n)}}function OM(i,e){let t=this.cache,n=e.elements;if(n===void 0){if(_n(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),yn(t,e)}else{if(_n(t,n))return;z0.set(n),i.uniformMatrix4fv(this.addr,!1,z0),yn(t,n)}}function FM(i,e){let t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function UM(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(_n(t,e))return;i.uniform2iv(this.addr,e),yn(t,e)}}function kM(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(_n(t,e))return;i.uniform3iv(this.addr,e),yn(t,e)}}function BM(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(_n(t,e))return;i.uniform4iv(this.addr,e),yn(t,e)}}function zM(i,e){let t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function HM(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(_n(t,e))return;i.uniform2uiv(this.addr,e),yn(t,e)}}function GM(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(_n(t,e))return;i.uniform3uiv(this.addr,e),yn(t,e)}}function VM(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(_n(t,e))return;i.uniform4uiv(this.addr,e),yn(t,e)}}function WM(i,e,t){let n=this.cache,r=t.allocateTextureUnit();n[0]!==r&&(i.uniform1i(this.addr,r),n[0]=r);let s;this.type===i.SAMPLER_2D_SHADOW?(af.compareFunction=t.isReversedDepthBuffer()?bh:gh,s=af):s=ib,t.setTexture2D(e||s,r)}function qM(i,e,t){let n=this.cache,r=t.allocateTextureUnit();n[0]!==r&&(i.uniform1i(this.addr,r),n[0]=r),t.setTexture3D(e||sb,r)}function $M(i,e,t){let n=this.cache,r=t.allocateTextureUnit();n[0]!==r&&(i.uniform1i(this.addr,r),n[0]=r),t.setTextureCube(e||ab,r)}function jM(i,e,t){let n=this.cache,r=t.allocateTextureUnit();n[0]!==r&&(i.uniform1i(this.addr,r),n[0]=r),t.setTexture2DArray(e||rb,r)}function XM(i){switch(i){case 5126:return CM;case 35664:return IM;case 35665:return PM;case 35666:return LM;case 35674:return DM;case 35675:return NM;case 35676:return OM;case 5124:case 35670:return FM;case 35667:case 35671:return UM;case 35668:case 35672:return kM;case 35669:case 35673:return BM;case 5125:return zM;case 36294:return HM;case 36295:return GM;case 36296:return VM;case 35678:case 36198:case 36298:case 36306:case 35682:return WM;case 35679:case 36299:case 36307:return qM;case 35680:case 36300:case 36308:case 36293:return $M;case 36289:case 36303:case 36311:case 36292:return jM}}function KM(i,e){i.uniform1fv(this.addr,e)}function YM(i,e){let t=Aa(e,this.size,2);i.uniform2fv(this.addr,t)}function JM(i,e){let t=Aa(e,this.size,3);i.uniform3fv(this.addr,t)}function ZM(i,e){let t=Aa(e,this.size,4);i.uniform4fv(this.addr,t)}function QM(i,e){let t=Aa(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function eA(i,e){let t=Aa(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function tA(i,e){let t=Aa(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function nA(i,e){i.uniform1iv(this.addr,e)}function iA(i,e){i.uniform2iv(this.addr,e)}function rA(i,e){i.uniform3iv(this.addr,e)}function sA(i,e){i.uniform4iv(this.addr,e)}function aA(i,e){i.uniform1uiv(this.addr,e)}function oA(i,e){i.uniform2uiv(this.addr,e)}function cA(i,e){i.uniform3uiv(this.addr,e)}function lA(i,e){i.uniform4uiv(this.addr,e)}function hA(i,e,t){let n=this.cache,r=e.length,s=Sh(t,r);_n(n,s)||(i.uniform1iv(this.addr,s),yn(n,s));let a;this.type===i.SAMPLER_2D_SHADOW?a=af:a=ib;for(let o=0;o!==r;++o)t.setTexture2D(e[o]||a,s[o])}function uA(i,e,t){let n=this.cache,r=e.length,s=Sh(t,r);_n(n,s)||(i.uniform1iv(this.addr,s),yn(n,s));for(let a=0;a!==r;++a)t.setTexture3D(e[a]||sb,s[a])}function dA(i,e,t){let n=this.cache,r=e.length,s=Sh(t,r);_n(n,s)||(i.uniform1iv(this.addr,s),yn(n,s));for(let a=0;a!==r;++a)t.setTextureCube(e[a]||ab,s[a])}function fA(i,e,t){let n=this.cache,r=e.length,s=Sh(t,r);_n(n,s)||(i.uniform1iv(this.addr,s),yn(n,s));for(let a=0;a!==r;++a)t.setTexture2DArray(e[a]||rb,s[a])}function pA(i){switch(i){case 5126:return KM;case 35664:return YM;case 35665:return JM;case 35666:return ZM;case 35674:return QM;case 35675:return eA;case 35676:return tA;case 5124:case 35670:return nA;case 35667:case 35671:return iA;case 35668:case 35672:return rA;case 35669:case 35673:return sA;case 5125:return aA;case 36294:return oA;case 36295:return cA;case 36296:return lA;case 35678:case 36198:case 36298:case 36306:case 35682:return hA;case 35679:case 36299:case 36307:return uA;case 35680:case 36300:case 36308:case 36293:return dA;case 36289:case 36303:case 36311:case 36292:return fA}}function V0(i,e){i.seq.push(e),i.map[e.id]=e}function mA(i,e,t){let n=i.name,r=n.length;for(rf.lastIndex=0;;){let s=rf.exec(n),a=rf.lastIndex,o=s[1],l=s[2]==="]",c=s[3];if(l&&(o=o|0),c===void 0||c==="["&&a+2===r){V0(t,c===void 0?new of(o,i,e):new cf(o,i,e));break}else{let d=t.map[o];d===void 0&&(d=new lf(o),V0(t,d)),t=d}}}function W0(i,e,t){let n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}function xA(i,e){let t=i.split(`
+`),n=[],r=Math.max(e-6,0),s=Math.min(e+6,t.length);for(let a=r;a<s;a++){let o=a+1;n.push(`${o===e?">":" "} ${o}: ${t[a]}`)}return n.join(`
+`)}function _A(i){ut._getMatrix(q0,ut.workingColorSpace,i);let e=`mat3( ${q0.elements.map(t=>t.toFixed(4))} )`;switch(ut.getTransfer(i)){case Qa:return[e,"LinearTransferOETF"];case Dt:return[e,"sRGBTransferOETF"];default:return Ke("WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function $0(i,e,t){let n=i.getShaderParameter(e,i.COMPILE_STATUS),s=(i.getShaderInfoLog(e)||"").trim();if(n&&s==="")return"";let a=/ERROR: 0:(\d+)/.exec(s);if(a){let o=parseInt(a[1]);return t.toUpperCase()+`
+
+`+s+`
+
+`+xA(i.getShaderSource(e),o)}else return s}function yA(i,e){let t=_A(e);return[`vec4 ${i}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`
+`)}function SA(i,e){let t=vA[e];return t===void 0?(Ke("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+i+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+i+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}function wA(){ut.getLuminanceCoefficients(_h);let i=_h.x.toFixed(4),e=_h.y.toFixed(4),t=_h.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(`
+`)}function MA(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Go).join(`
+`)}function AA(i){let e=[];for(let t in i){let n=i[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(`
+`)}function TA(i,e){let t={},n=i.getProgramParameter(e,i.ACTIVE_ATTRIBUTES);for(let r=0;r<n;r++){let s=i.getActiveAttrib(e,r),a=s.name,o=1;s.type===i.FLOAT_MAT2&&(o=2),s.type===i.FLOAT_MAT3&&(o=3),s.type===i.FLOAT_MAT4&&(o=4),t[a]={type:s.type,location:i.getAttribLocation(e,a),locationSize:o}}return t}function Go(i){return i!==""}function j0(i,e){let t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return i.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function X0(i,e){return i.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}function hf(i){return i.replace(EA,CA)}function CA(i,e){let t=ft[e];if(t===void 0){let n=RA.get(e);if(n!==void 0)t=ft[n],Ke('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return hf(t)}function K0(i){return i.replace(IA,PA)}function PA(i,e,t,n){let r="";for(let s=parseInt(e);s<parseInt(t);s++)r+=n.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return r}function Y0(i){let e=`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"?e+=`
+#define HIGH_PRECISION`:i.precision==="mediump"?e+=`
+#define MEDIUM_PRECISION`:i.precision==="lowp"&&(e+=`
+#define LOW_PRECISION`),e}function DA(i){return LA[i.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}function OA(i){return i.envMap===!1?"ENVMAP_TYPE_CUBE":NA[i.envMapMode]||"ENVMAP_TYPE_CUBE"}function UA(i){return i.envMap===!1?"ENVMAP_MODE_REFLECTION":FA[i.envMapMode]||"ENVMAP_MODE_REFLECTION"}function BA(i){return i.envMap===!1?"ENVMAP_BLENDING_NONE":kA[i.combine]||"ENVMAP_BLENDING_NONE"}function zA(i){let e=i.envMapCubeUVHeight;if(e===null)return null;let t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}function HA(i,e,t,n){let r=i.getContext(),s=t.defines,a=t.vertexShader,o=t.fragmentShader,l=DA(t),c=OA(t),h=UA(t),d=BA(t),f=zA(t),p=MA(t),x=AA(s),y=r.createProgram(),b,g,S=t.glslVersion?"#version "+t.glslVersion+`
+`:"";t.isRawShaderMaterial?(b=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x].filter(Go).join(`
+`),b.length>0&&(b+=`
+`),g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x].filter(Go).join(`
+`),g.length>0&&(g+=`
+`)):(b=[Y0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexNormals?"#define HAS_NORMAL":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.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(Go).join(`
+`),g=[Y0(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,x,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+h:"",t.envMap?"#define "+d:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Ni?"#define TONE_MAPPING":"",t.toneMapping!==Ni?ft.tonemapping_pars_fragment:"",t.toneMapping!==Ni?SA("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",ft.colorspace_pars_fragment,yA("linearToOutputTexel",t.outputColorSpace),wA(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
+`].filter(Go).join(`
+`)),a=hf(a),a=j0(a,t),a=X0(a,t),o=hf(o),o=j0(o,t),o=X0(o,t),a=K0(a),o=K0(o),t.isRawShaderMaterial!==!0&&(S=`#version 300 es
+`,b=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(`
+`)+`
+`+b,g=["#define varying in",t.glslVersion===Bd?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Bd?"":"#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(`
+`)+`
+`+g);let A=S+b+a,T=S+g+o,N=W0(r,r.VERTEX_SHADER,A),P=W0(r,r.FRAGMENT_SHADER,T);r.attachShader(y,N),r.attachShader(y,P),t.index0AttributeName!==void 0?r.bindAttribLocation(y,0,t.index0AttributeName):t.morphTargets===!0&&r.bindAttribLocation(y,0,"position"),r.linkProgram(y);function U(k){if(i.debug.checkShaderErrors){let V=r.getProgramInfoLog(y)||"",J=r.getShaderInfoLog(N)||"",L=r.getShaderInfoLog(P)||"",E=V.trim(),D=J.trim(),O=L.trim(),H=!0,Y=!0;if(r.getProgramParameter(y,r.LINK_STATUS)===!1)if(H=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(r,y,N,P);else{let le=$0(r,N,"vertex"),fe=$0(r,P,"fragment");et("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(y,r.VALIDATE_STATUS)+`
+
+Material Name: `+k.name+`
+Material Type: `+k.type+`
+
+Program Info Log: `+E+`
+`+le+`
+`+fe)}else E!==""?Ke("WebGLProgram: Program Info Log:",E):(D===""||O==="")&&(Y=!1);Y&&(k.diagnostics={runnable:H,programLog:E,vertexShader:{log:D,prefix:b},fragmentShader:{log:O,prefix:g}})}r.deleteShader(N),r.deleteShader(P),v=new Sa(r,y),I=TA(r,y)}let v;this.getUniforms=function(){return v===void 0&&U(this),v};let I;this.getAttributes=function(){return I===void 0&&U(this),I};let B=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return B===!1&&(B=r.getProgramParameter(y,gA)),B},this.destroy=function(){n.releaseStatesOfProgram(this),r.deleteProgram(y),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=bA++,this.cacheKey=e,this.usedTimes=1,this.program=y,this.vertexShader=N,this.fragmentShader=P,this}function VA(i){return i===Xr||i===No||i===Oo}function WA(i,e,t,n,r,s){let a=new la,o=new uf,l=new Set,c=[],h=new Map,d=n.logarithmicDepthBuffer,f=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 x(v){return l.add(v),v===0?"uv":`uv${v}`}function y(v,I,B,k,V,J){let L=k.fog,E=V.geometry,D=v.isMeshStandardMaterial||v.isMeshLambertMaterial||v.isMeshPhongMaterial?k.environment:null,O=v.isMeshStandardMaterial||v.isMeshLambertMaterial&&!v.envMap||v.isMeshPhongMaterial&&!v.envMap,H=e.get(v.envMap||D,O),Y=H&&H.mapping===Co?H.image.height:null,le=p[v.type];v.precision!==null&&(f=n.getMaxPrecision(v.precision),f!==v.precision&&Ke("WebGLProgram.getParameters:",v.precision,"not supported, using",f,"instead."));let fe=E.morphAttributes.position||E.morphAttributes.normal||E.morphAttributes.color,be=fe!==void 0?fe.length:0,Te=0;E.morphAttributes.position!==void 0&&(Te=1),E.morphAttributes.normal!==void 0&&(Te=2),E.morphAttributes.color!==void 0&&(Te=3);let Je,ke,oe,Ee;if(le){let rt=Qi[le];Je=rt.vertexShader,ke=rt.fragmentShader}else Je=v.vertexShader,ke=v.fragmentShader,o.update(v),oe=o.getVertexShaderID(v),Ee=o.getFragmentShaderID(v);let _e=i.getRenderTarget(),Ze=i.state.buffers.depth.getReversed(),tt=V.isInstancedMesh===!0,Qe=V.isBatchedMesh===!0,Et=!!v.map,it=!!v.matcap,mt=!!H,wt=!!v.aoMap,lt=!!v.lightMap,Bt=!!v.bumpMap,gt=!!v.normalMap,Yt=!!v.displacementMap,q=!!v.emissiveMap,$t=!!v.metalnessMap,ht=!!v.roughnessMap,Tt=v.anisotropy>0,Pe=v.clearcoat>0,Ot=v.dispersion>0,F=v.iridescence>0,M=v.sheen>0,Z=v.transmission>0,pe=Tt&&!!v.anisotropyMap,ge=Pe&&!!v.clearcoatMap,Se=Pe&&!!v.clearcoatNormalMap,Ce=Pe&&!!v.clearcoatRoughnessMap,ce=F&&!!v.iridescenceMap,me=F&&!!v.iridescenceThicknessMap,Be=M&&!!v.sheenColorMap,Le=M&&!!v.sheenRoughnessMap,ve=!!v.specularMap,Me=!!v.specularColorMap,je=!!v.specularIntensityMap,nt=Z&&!!v.transmissionMap,pt=Z&&!!v.thicknessMap,G=!!v.gradientMap,we=!!v.alphaMap,de=v.alphaTest>0,He=!!v.alphaHash,Ae=!!v.extensions,xe=Ni;v.toneMapped&&(_e===null||_e.isXRRenderTarget===!0)&&(xe=i.toneMapping);let Xe={shaderID:le,shaderType:v.type,shaderName:v.name,vertexShader:Je,fragmentShader:ke,defines:v.defines,customVertexShaderID:oe,customFragmentShaderID:Ee,isRawShaderMaterial:v.isRawShaderMaterial===!0,glslVersion:v.glslVersion,precision:f,batching:Qe,batchingColor:Qe&&V._colorsTexture!==null,instancing:tt,instancingColor:tt&&V.instanceColor!==null,instancingMorph:tt&&V.morphTexture!==null,outputColorSpace:_e===null?i.outputColorSpace:_e.isXRRenderTarget===!0?_e.texture.colorSpace:ut.workingColorSpace,alphaToCoverage:!!v.alphaToCoverage,map:Et,matcap:it,envMap:mt,envMapMode:mt&&H.mapping,envMapCubeUVHeight:Y,aoMap:wt,lightMap:lt,bumpMap:Bt,normalMap:gt,displacementMap:Yt,emissiveMap:q,normalMapObjectSpace:gt&&v.normalMapType===b0,normalMapTangentSpace:gt&&v.normalMapType===Bo,packedNormalMap:gt&&v.normalMapType===Bo&&VA(v.normalMap.format),metalnessMap:$t,roughnessMap:ht,anisotropy:Tt,anisotropyMap:pe,clearcoat:Pe,clearcoatMap:ge,clearcoatNormalMap:Se,clearcoatRoughnessMap:Ce,dispersion:Ot,iridescence:F,iridescenceMap:ce,iridescenceThicknessMap:me,sheen:M,sheenColorMap:Be,sheenRoughnessMap:Le,specularMap:ve,specularColorMap:Me,specularIntensityMap:je,transmission:Z,transmissionMap:nt,thicknessMap:pt,gradientMap:G,opaque:v.transparent===!1&&v.blending===fs&&v.alphaToCoverage===!1,alphaMap:we,alphaTest:de,alphaHash:He,combine:v.combine,mapUv:Et&&x(v.map.channel),aoMapUv:wt&&x(v.aoMap.channel),lightMapUv:lt&&x(v.lightMap.channel),bumpMapUv:Bt&&x(v.bumpMap.channel),normalMapUv:gt&&x(v.normalMap.channel),displacementMapUv:Yt&&x(v.displacementMap.channel),emissiveMapUv:q&&x(v.emissiveMap.channel),metalnessMapUv:$t&&x(v.metalnessMap.channel),roughnessMapUv:ht&&x(v.roughnessMap.channel),anisotropyMapUv:pe&&x(v.anisotropyMap.channel),clearcoatMapUv:ge&&x(v.clearcoatMap.channel),clearcoatNormalMapUv:Se&&x(v.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ce&&x(v.clearcoatRoughnessMap.channel),iridescenceMapUv:ce&&x(v.iridescenceMap.channel),iridescenceThicknessMapUv:me&&x(v.iridescenceThicknessMap.channel),sheenColorMapUv:Be&&x(v.sheenColorMap.channel),sheenRoughnessMapUv:Le&&x(v.sheenRoughnessMap.channel),specularMapUv:ve&&x(v.specularMap.channel),specularColorMapUv:Me&&x(v.specularColorMap.channel),specularIntensityMapUv:je&&x(v.specularIntensityMap.channel),transmissionMapUv:nt&&x(v.transmissionMap.channel),thicknessMapUv:pt&&x(v.thicknessMap.channel),alphaMapUv:we&&x(v.alphaMap.channel),vertexTangents:!!E.attributes.tangent&&(gt||Tt),vertexNormals:!!E.attributes.normal,vertexColors:v.vertexColors,vertexAlphas:v.vertexColors===!0&&!!E.attributes.color&&E.attributes.color.itemSize===4,pointsUvs:V.isPoints===!0&&!!E.attributes.uv&&(Et||we),fog:!!L,useFog:v.fog===!0,fogExp2:!!L&&L.isFogExp2,flatShading:v.wireframe===!1&&(v.flatShading===!0||E.attributes.normal===void 0&&gt===!1&&(v.isMeshLambertMaterial||v.isMeshPhongMaterial||v.isMeshStandardMaterial||v.isMeshPhysicalMaterial)),sizeAttenuation:v.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:Ze,skinning:V.isSkinnedMesh===!0,morphTargets:E.morphAttributes.position!==void 0,morphNormals:E.morphAttributes.normal!==void 0,morphColors:E.morphAttributes.color!==void 0,morphTargetsCount:be,morphTextureStride:Te,numDirLights:I.directional.length,numPointLights:I.point.length,numSpotLights:I.spot.length,numSpotLightMaps:I.spotLightMap.length,numRectAreaLights:I.rectArea.length,numHemiLights:I.hemi.length,numDirLightShadows:I.directionalShadowMap.length,numPointLightShadows:I.pointShadowMap.length,numSpotLightShadows:I.spotShadowMap.length,numSpotLightShadowsWithMaps:I.numSpotLightShadowsWithMaps,numLightProbes:I.numLightProbes,numLightProbeGrids:J.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:v.dithering,shadowMapEnabled:i.shadowMap.enabled&&B.length>0,shadowMapType:i.shadowMap.type,toneMapping:xe,decodeVideoTexture:Et&&v.map.isVideoTexture===!0&&ut.getTransfer(v.map.colorSpace)===Dt,decodeVideoTextureEmissive:q&&v.emissiveMap.isVideoTexture===!0&&ut.getTransfer(v.emissiveMap.colorSpace)===Dt,premultipliedAlpha:v.premultipliedAlpha,doubleSided:v.side===Dn,flipSided:v.side===An,useDepthPacking:v.depthPacking>=0,depthPacking:v.depthPacking||0,index0AttributeName:v.index0AttributeName,extensionClipCullDistance:Ae&&v.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ae&&v.extensions.multiDraw===!0||Qe)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:v.customProgramCacheKey()};return Xe.vertexUv1s=l.has(1),Xe.vertexUv2s=l.has(2),Xe.vertexUv3s=l.has(3),l.clear(),Xe}function b(v){let I=[];if(v.shaderID?I.push(v.shaderID):(I.push(v.customVertexShaderID),I.push(v.customFragmentShaderID)),v.defines!==void 0)for(let B in v.defines)I.push(B),I.push(v.defines[B]);return v.isRawShaderMaterial===!1&&(g(I,v),S(I,v),I.push(i.outputColorSpace)),I.push(v.customProgramCacheKey),I.join()}function g(v,I){v.push(I.precision),v.push(I.outputColorSpace),v.push(I.envMapMode),v.push(I.envMapCubeUVHeight),v.push(I.mapUv),v.push(I.alphaMapUv),v.push(I.lightMapUv),v.push(I.aoMapUv),v.push(I.bumpMapUv),v.push(I.normalMapUv),v.push(I.displacementMapUv),v.push(I.emissiveMapUv),v.push(I.metalnessMapUv),v.push(I.roughnessMapUv),v.push(I.anisotropyMapUv),v.push(I.clearcoatMapUv),v.push(I.clearcoatNormalMapUv),v.push(I.clearcoatRoughnessMapUv),v.push(I.iridescenceMapUv),v.push(I.iridescenceThicknessMapUv),v.push(I.sheenColorMapUv),v.push(I.sheenRoughnessMapUv),v.push(I.specularMapUv),v.push(I.specularColorMapUv),v.push(I.specularIntensityMapUv),v.push(I.transmissionMapUv),v.push(I.thicknessMapUv),v.push(I.combine),v.push(I.fogExp2),v.push(I.sizeAttenuation),v.push(I.morphTargetsCount),v.push(I.morphAttributeCount),v.push(I.numDirLights),v.push(I.numPointLights),v.push(I.numSpotLights),v.push(I.numSpotLightMaps),v.push(I.numHemiLights),v.push(I.numRectAreaLights),v.push(I.numDirLightShadows),v.push(I.numPointLightShadows),v.push(I.numSpotLightShadows),v.push(I.numSpotLightShadowsWithMaps),v.push(I.numLightProbes),v.push(I.shadowMapType),v.push(I.toneMapping),v.push(I.numClippingPlanes),v.push(I.numClipIntersection),v.push(I.depthPacking)}function S(v,I){a.disableAll(),I.instancing&&a.enable(0),I.instancingColor&&a.enable(1),I.instancingMorph&&a.enable(2),I.matcap&&a.enable(3),I.envMap&&a.enable(4),I.normalMapObjectSpace&&a.enable(5),I.normalMapTangentSpace&&a.enable(6),I.clearcoat&&a.enable(7),I.iridescence&&a.enable(8),I.alphaTest&&a.enable(9),I.vertexColors&&a.enable(10),I.vertexAlphas&&a.enable(11),I.vertexUv1s&&a.enable(12),I.vertexUv2s&&a.enable(13),I.vertexUv3s&&a.enable(14),I.vertexTangents&&a.enable(15),I.anisotropy&&a.enable(16),I.alphaHash&&a.enable(17),I.batching&&a.enable(18),I.dispersion&&a.enable(19),I.batchingColor&&a.enable(20),I.gradientMap&&a.enable(21),I.packedNormalMap&&a.enable(22),I.vertexNormals&&a.enable(23),v.push(a.mask),a.disableAll(),I.fog&&a.enable(0),I.useFog&&a.enable(1),I.flatShading&&a.enable(2),I.logarithmicDepthBuffer&&a.enable(3),I.reversedDepthBuffer&&a.enable(4),I.skinning&&a.enable(5),I.morphTargets&&a.enable(6),I.morphNormals&&a.enable(7),I.morphColors&&a.enable(8),I.premultipliedAlpha&&a.enable(9),I.shadowMapEnabled&&a.enable(10),I.doubleSided&&a.enable(11),I.flipSided&&a.enable(12),I.useDepthPacking&&a.enable(13),I.dithering&&a.enable(14),I.transmission&&a.enable(15),I.sheen&&a.enable(16),I.opaque&&a.enable(17),I.pointsUvs&&a.enable(18),I.decodeVideoTexture&&a.enable(19),I.decodeVideoTextureEmissive&&a.enable(20),I.alphaToCoverage&&a.enable(21),I.numLightProbeGrids>0&&a.enable(22),v.push(a.mask)}function A(v){let I=p[v.type],B;if(I){let k=Qi[I];B=I0.clone(k.uniforms)}else B=v.uniforms;return B}function T(v,I){let B=h.get(I);return B!==void 0?++B.usedTimes:(B=new HA(i,I,v,r),c.push(B),h.set(I,B)),B}function N(v){if(--v.usedTimes===0){let I=c.indexOf(v);c[I]=c[c.length-1],c.pop(),h.delete(v.cacheKey),v.destroy()}}function P(v){o.remove(v)}function U(){o.dispose()}return{getParameters:y,getProgramCacheKey:b,getUniforms:A,acquireProgram:T,releaseProgram:N,releaseShaderCache:P,programs:c,dispose:U}}function qA(){let i=new WeakMap;function e(a){return i.has(a)}function t(a){let o=i.get(a);return o===void 0&&(o={},i.set(a,o)),o}function n(a){i.delete(a)}function r(a,o,l){i.get(a)[o]=l}function s(){i=new WeakMap}return{has:e,get:t,remove:n,update:r,dispose:s}}function $A(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.materialVariant!==e.materialVariant?i.materialVariant-e.materialVariant:i.z!==e.z?i.z-e.z:i.id-e.id}function J0(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Z0(){let i=[],e=0,t=[],n=[],r=[];function s(){e=0,t.length=0,n.length=0,r.length=0}function a(f){let p=0;return f.isInstancedMesh&&(p+=2),f.isSkinnedMesh&&(p+=1),p}function o(f,p,x,y,b,g){let S=i[e];return S===void 0?(S={id:f.id,object:f,geometry:p,material:x,materialVariant:a(f),groupOrder:y,renderOrder:f.renderOrder,z:b,group:g},i[e]=S):(S.id=f.id,S.object=f,S.geometry=p,S.material=x,S.materialVariant=a(f),S.groupOrder=y,S.renderOrder=f.renderOrder,S.z=b,S.group=g),e++,S}function l(f,p,x,y,b,g){let S=o(f,p,x,y,b,g);x.transmission>0?n.push(S):x.transparent===!0?r.push(S):t.push(S)}function c(f,p,x,y,b,g){let S=o(f,p,x,y,b,g);x.transmission>0?n.unshift(S):x.transparent===!0?r.unshift(S):t.unshift(S)}function h(f,p){t.length>1&&t.sort(f||$A),n.length>1&&n.sort(p||J0),r.length>1&&r.sort(p||J0)}function d(){for(let f=e,p=i.length;f<p;f++){let x=i[f];if(x.id===null)break;x.id=null,x.object=null,x.geometry=null,x.material=null,x.group=null}}return{opaque:t,transmissive:n,transparent:r,init:s,push:l,unshift:c,finish:d,sort:h}}function jA(){let i=new WeakMap;function e(n,r){let s=i.get(n),a;return s===void 0?(a=new Z0,i.set(n,[a])):r>=s.length?(a=new Z0,s.push(a)):a=s[r],a}function t(){i=new WeakMap}return{get:e,dispose:t}}function XA(){let i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new W,color:new Ve};break;case"SpotLight":t={position:new W,direction:new W,color:new Ve,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new W,color:new Ve,distance:0,decay:0};break;case"HemisphereLight":t={direction:new W,skyColor:new Ve,groundColor:new Ve};break;case"RectAreaLight":t={color:new Ve,position:new W,halfWidth:new W,halfHeight:new W};break}return i[e.id]=t,t}}}function KA(){let i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new dt};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new dt};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new dt,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}function JA(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function ZA(i){let e=new XA,t=KA(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)n.probe.push(new W);let r=new W,s=new ot,a=new ot;function o(c){let h=0,d=0,f=0;for(let I=0;I<9;I++)n.probe[I].set(0,0,0);let p=0,x=0,y=0,b=0,g=0,S=0,A=0,T=0,N=0,P=0,U=0;c.sort(JA);for(let I=0,B=c.length;I<B;I++){let k=c[I],V=k.color,J=k.intensity,L=k.distance,E=null;if(k.shadow&&k.shadow.map&&(k.shadow.map.texture.format===Xr?E=k.shadow.map.texture:E=k.shadow.map.depthTexture||k.shadow.map.texture),k.isAmbientLight)h+=V.r*J,d+=V.g*J,f+=V.b*J;else if(k.isLightProbe){for(let D=0;D<9;D++)n.probe[D].addScaledVector(k.sh.coefficients[D],J);U++}else if(k.isDirectionalLight){let D=e.get(k);if(D.color.copy(k.color).multiplyScalar(k.intensity),k.castShadow){let O=k.shadow,H=t.get(k);H.shadowIntensity=O.intensity,H.shadowBias=O.bias,H.shadowNormalBias=O.normalBias,H.shadowRadius=O.radius,H.shadowMapSize=O.mapSize,n.directionalShadow[p]=H,n.directionalShadowMap[p]=E,n.directionalShadowMatrix[p]=k.shadow.matrix,S++}n.directional[p]=D,p++}else if(k.isSpotLight){let D=e.get(k);D.position.setFromMatrixPosition(k.matrixWorld),D.color.copy(V).multiplyScalar(J),D.distance=L,D.coneCos=Math.cos(k.angle),D.penumbraCos=Math.cos(k.angle*(1-k.penumbra)),D.decay=k.decay,n.spot[y]=D;let O=k.shadow;if(k.map&&(n.spotLightMap[N]=k.map,N++,O.updateMatrices(k),k.castShadow&&P++),n.spotLightMatrix[y]=O.matrix,k.castShadow){let H=t.get(k);H.shadowIntensity=O.intensity,H.shadowBias=O.bias,H.shadowNormalBias=O.normalBias,H.shadowRadius=O.radius,H.shadowMapSize=O.mapSize,n.spotShadow[y]=H,n.spotShadowMap[y]=E,T++}y++}else if(k.isRectAreaLight){let D=e.get(k);D.color.copy(V).multiplyScalar(J),D.halfWidth.set(k.width*.5,0,0),D.halfHeight.set(0,k.height*.5,0),n.rectArea[b]=D,b++}else if(k.isPointLight){let D=e.get(k);if(D.color.copy(k.color).multiplyScalar(k.intensity),D.distance=k.distance,D.decay=k.decay,k.castShadow){let O=k.shadow,H=t.get(k);H.shadowIntensity=O.intensity,H.shadowBias=O.bias,H.shadowNormalBias=O.normalBias,H.shadowRadius=O.radius,H.shadowMapSize=O.mapSize,H.shadowCameraNear=O.camera.near,H.shadowCameraFar=O.camera.far,n.pointShadow[x]=H,n.pointShadowMap[x]=E,n.pointShadowMatrix[x]=k.shadow.matrix,A++}n.point[x]=D,x++}else if(k.isHemisphereLight){let D=e.get(k);D.skyColor.copy(k.color).multiplyScalar(J),D.groundColor.copy(k.groundColor).multiplyScalar(J),n.hemi[g]=D,g++}}b>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=Ue.LTC_FLOAT_1,n.rectAreaLTC2=Ue.LTC_FLOAT_2):(n.rectAreaLTC1=Ue.LTC_HALF_1,n.rectAreaLTC2=Ue.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=d,n.ambient[2]=f;let v=n.hash;(v.directionalLength!==p||v.pointLength!==x||v.spotLength!==y||v.rectAreaLength!==b||v.hemiLength!==g||v.numDirectionalShadows!==S||v.numPointShadows!==A||v.numSpotShadows!==T||v.numSpotMaps!==N||v.numLightProbes!==U)&&(n.directional.length=p,n.spot.length=y,n.rectArea.length=b,n.point.length=x,n.hemi.length=g,n.directionalShadow.length=S,n.directionalShadowMap.length=S,n.pointShadow.length=A,n.pointShadowMap.length=A,n.spotShadow.length=T,n.spotShadowMap.length=T,n.directionalShadowMatrix.length=S,n.pointShadowMatrix.length=A,n.spotLightMatrix.length=T+N-P,n.spotLightMap.length=N,n.numSpotLightShadowsWithMaps=P,n.numLightProbes=U,v.directionalLength=p,v.pointLength=x,v.spotLength=y,v.rectAreaLength=b,v.hemiLength=g,v.numDirectionalShadows=S,v.numPointShadows=A,v.numSpotShadows=T,v.numSpotMaps=N,v.numLightProbes=U,n.version=YA++)}function l(c,h){let d=0,f=0,p=0,x=0,y=0,b=h.matrixWorldInverse;for(let g=0,S=c.length;g<S;g++){let A=c[g];if(A.isDirectionalLight){let T=n.directional[d];T.direction.setFromMatrixPosition(A.matrixWorld),r.setFromMatrixPosition(A.target.matrixWorld),T.direction.sub(r),T.direction.transformDirection(b),d++}else if(A.isSpotLight){let T=n.spot[p];T.position.setFromMatrixPosition(A.matrixWorld),T.position.applyMatrix4(b),T.direction.setFromMatrixPosition(A.matrixWorld),r.setFromMatrixPosition(A.target.matrixWorld),T.direction.sub(r),T.direction.transformDirection(b),p++}else if(A.isRectAreaLight){let T=n.rectArea[x];T.position.setFromMatrixPosition(A.matrixWorld),T.position.applyMatrix4(b),a.identity(),s.copy(A.matrixWorld),s.premultiply(b),a.extractRotation(s),T.halfWidth.set(A.width*.5,0,0),T.halfHeight.set(0,A.height*.5,0),T.halfWidth.applyMatrix4(a),T.halfHeight.applyMatrix4(a),x++}else if(A.isPointLight){let T=n.point[f];T.position.setFromMatrixPosition(A.matrixWorld),T.position.applyMatrix4(b),f++}else if(A.isHemisphereLight){let T=n.hemi[y];T.direction.setFromMatrixPosition(A.matrixWorld),T.direction.transformDirection(b),y++}}}return{setup:o,setupView:l,state:n}}function Q0(i){let e=new ZA(i),t=[],n=[],r=[];function s(f){d.camera=f,t.length=0,n.length=0,r.length=0}function a(f){t.push(f)}function o(f){n.push(f)}function l(f){r.push(f)}function c(){e.setup(t)}function h(f){e.setupView(t,f)}let d={lightsArray:t,shadowsArray:n,lightProbeGridArray:r,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:d,setupLights:c,setupLightsView:h,pushLight:a,pushShadow:o,pushLightProbeGrid:l}}function QA(i){let e=new WeakMap;function t(r,s=0){let a=e.get(r),o;return a===void 0?(o=new Q0(i),e.set(r,[o])):s>=a.length?(o=new Q0(i),a.push(o)):o=a[s],o}function n(){e=new WeakMap}return{get:t,dispose:n}}function rT(i,e,t){let n=new da,r=new dt,s=new dt,a=new kt,o=new pl,l=new ml,c={},h=t.maxTextureSize,d={[Pi]:An,[An]:Pi,[Dn]:Dn},f=new ai({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new dt},radius:{value:4}},vertexShader:eT,fragmentShader:tT}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let x=new mn;x.setAttribute("position",new Kt(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let y=new xt(x,f),b=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Eo;let g=this.type;this.render=function(P,U,v){if(b.enabled===!1||b.autoUpdate===!1&&b.needsUpdate===!1||P.length===0)return;this.type===jg&&(Ke("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=Eo);let I=i.getRenderTarget(),B=i.getActiveCubeFace(),k=i.getActiveMipmapLevel(),V=i.state;V.setBlending(Ji),V.buffers.depth.getReversed()===!0?V.buffers.color.setClear(0,0,0,0):V.buffers.color.setClear(1,1,1,1),V.buffers.depth.setTest(!0),V.setScissorTest(!1);let J=g!==this.type;J&&U.traverse(function(L){L.material&&(Array.isArray(L.material)?L.material.forEach(E=>E.needsUpdate=!0):L.material.needsUpdate=!0)});for(let L=0,E=P.length;L<E;L++){let D=P[L],O=D.shadow;if(O===void 0){Ke("WebGLShadowMap:",D,"has no shadow.");continue}if(O.autoUpdate===!1&&O.needsUpdate===!1)continue;r.copy(O.mapSize);let H=O.getFrameExtents();r.multiply(H),s.copy(O.mapSize),(r.x>h||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/H.x),r.x=s.x*H.x,O.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/H.y),r.y=s.y*H.y,O.mapSize.y=s.y));let Y=i.state.buffers.depth.getReversed();if(O.camera._reversedDepth=Y,O.map===null||J===!0){if(O.map!==null&&(O.map.depthTexture!==null&&(O.map.depthTexture.dispose(),O.map.depthTexture=null),O.map.dispose()),this.type===qr){if(D.isPointLight){Ke("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}O.map=new Hn(r.x,r.y,{format:Xr,type:Gn,minFilter:zt,magFilter:zt,generateMipmaps:!1}),O.map.texture.name=D.name+".shadowMap",O.map.depthTexture=new pr(r.x,r.y,Tn),O.map.depthTexture.name=D.name+".shadowMapDepth",O.map.depthTexture.format=Wi,O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=on,O.map.depthTexture.magFilter=on}else D.isPointLight?(O.map=new Ma(r.x),O.map.depthTexture=new dl(r.x,Oi)):(O.map=new Hn(r.x,r.y),O.map.depthTexture=new pr(r.x,r.y,Oi)),O.map.depthTexture.name=D.name+".shadowMap",O.map.depthTexture.format=Wi,this.type===Eo?(O.map.depthTexture.compareFunction=Y?bh:gh,O.map.depthTexture.minFilter=zt,O.map.depthTexture.magFilter=zt):(O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=on,O.map.depthTexture.magFilter=on);O.camera.updateProjectionMatrix()}let le=O.map.isWebGLCubeRenderTarget?6:1;for(let fe=0;fe<le;fe++){if(O.map.isWebGLCubeRenderTarget)i.setRenderTarget(O.map,fe),i.clear();else{fe===0&&(i.setRenderTarget(O.map),i.clear());let be=O.getViewport(fe);a.set(s.x*be.x,s.y*be.y,s.x*be.z,s.y*be.w),V.viewport(a)}if(D.isPointLight){let be=O.camera,Te=O.matrix,Je=D.distance||be.far;Je!==be.far&&(be.far=Je,be.updateProjectionMatrix()),Ho.setFromMatrixPosition(D.matrixWorld),be.position.copy(Ho),sf.copy(be.position),sf.add(nT[fe]),be.up.copy(iT[fe]),be.lookAt(sf),be.updateMatrixWorld(),Te.makeTranslation(-Ho.x,-Ho.y,-Ho.z),eb.multiplyMatrices(be.projectionMatrix,be.matrixWorldInverse),O._frustum.setFromProjectionMatrix(eb,be.coordinateSystem,be.reversedDepth)}else O.updateMatrices(D);n=O.getFrustum(),T(U,v,O.camera,D,this.type)}O.isPointLightShadow!==!0&&this.type===qr&&S(O,v),O.needsUpdate=!1}g=this.type,b.needsUpdate=!1,i.setRenderTarget(I,B,k)};function S(P,U){let v=e.update(y);f.defines.VSM_SAMPLES!==P.blurSamples&&(f.defines.VSM_SAMPLES=P.blurSamples,p.defines.VSM_SAMPLES=P.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),P.mapPass===null&&(P.mapPass=new Hn(r.x,r.y,{format:Xr,type:Gn})),f.uniforms.shadow_pass.value=P.map.depthTexture,f.uniforms.resolution.value=P.mapSize,f.uniforms.radius.value=P.radius,i.setRenderTarget(P.mapPass),i.clear(),i.renderBufferDirect(U,null,v,f,y,null),p.uniforms.shadow_pass.value=P.mapPass.texture,p.uniforms.resolution.value=P.mapSize,p.uniforms.radius.value=P.radius,i.setRenderTarget(P.map),i.clear(),i.renderBufferDirect(U,null,v,p,y,null)}function A(P,U,v,I){let B=null,k=v.isPointLight===!0?P.customDistanceMaterial:P.customDepthMaterial;if(k!==void 0)B=k;else if(B=v.isPointLight===!0?l:o,i.localClippingEnabled&&U.clipShadows===!0&&Array.isArray(U.clippingPlanes)&&U.clippingPlanes.length!==0||U.displacementMap&&U.displacementScale!==0||U.alphaMap&&U.alphaTest>0||U.map&&U.alphaTest>0||U.alphaToCoverage===!0){let V=B.uuid,J=U.uuid,L=c[V];L===void 0&&(L={},c[V]=L);let E=L[J];E===void 0&&(E=B.clone(),L[J]=E,U.addEventListener("dispose",N)),B=E}if(B.visible=U.visible,B.wireframe=U.wireframe,I===qr?B.side=U.shadowSide!==null?U.shadowSide:U.side:B.side=U.shadowSide!==null?U.shadowSide:d[U.side],B.alphaMap=U.alphaMap,B.alphaTest=U.alphaToCoverage===!0?.5:U.alphaTest,B.map=U.map,B.clipShadows=U.clipShadows,B.clippingPlanes=U.clippingPlanes,B.clipIntersection=U.clipIntersection,B.displacementMap=U.displacementMap,B.displacementScale=U.displacementScale,B.displacementBias=U.displacementBias,B.wireframeLinewidth=U.wireframeLinewidth,B.linewidth=U.linewidth,v.isPointLight===!0&&B.isMeshDistanceMaterial===!0){let V=i.properties.get(B);V.light=v}return B}function T(P,U,v,I,B){if(P.visible===!1)return;if(P.layers.test(U.layers)&&(P.isMesh||P.isLine||P.isPoints)&&(P.castShadow||P.receiveShadow&&B===qr)&&(!P.frustumCulled||n.intersectsObject(P))){P.modelViewMatrix.multiplyMatrices(v.matrixWorldInverse,P.matrixWorld);let J=e.update(P),L=P.material;if(Array.isArray(L)){let E=J.groups;for(let D=0,O=E.length;D<O;D++){let H=E[D],Y=L[H.materialIndex];if(Y&&Y.visible){let le=A(P,Y,I,B);P.onBeforeShadow(i,P,U,v,J,le,H),i.renderBufferDirect(v,null,J,le,P,H),P.onAfterShadow(i,P,U,v,J,le,H)}}}else if(L.visible){let E=A(P,L,I,B);P.onBeforeShadow(i,P,U,v,J,E,null),i.renderBufferDirect(v,null,J,E,P,null),P.onAfterShadow(i,P,U,v,J,E,null)}}let V=P.children;for(let J=0,L=V.length;J<L;J++)T(V[J],U,v,I,B)}function N(P){P.target.removeEventListener("dispose",N);for(let v in c){let I=c[v],B=P.target.uuid;B in I&&(I[B].dispose(),delete I[B])}}}function sT(i,e){function t(){let G=!1,we=new kt,de=null,He=new kt(0,0,0,0);return{setMask:function(Ae){de!==Ae&&!G&&(i.colorMask(Ae,Ae,Ae,Ae),de=Ae)},setLocked:function(Ae){G=Ae},setClear:function(Ae,xe,Xe,rt,jt){jt===!0&&(Ae*=rt,xe*=rt,Xe*=rt),we.set(Ae,xe,Xe,rt),He.equals(we)===!1&&(i.clearColor(Ae,xe,Xe,rt),He.copy(we))},reset:function(){G=!1,de=null,He.set(-1,0,0,0)}}}function n(){let G=!1,we=!1,de=null,He=null,Ae=null;return{setReversed:function(xe){if(we!==xe){let Xe=e.get("EXT_clip_control");xe?Xe.clipControlEXT(Xe.LOWER_LEFT_EXT,Xe.ZERO_TO_ONE_EXT):Xe.clipControlEXT(Xe.LOWER_LEFT_EXT,Xe.NEGATIVE_ONE_TO_ONE_EXT),we=xe;let rt=Ae;Ae=null,this.setClear(rt)}},getReversed:function(){return we},setTest:function(xe){xe?_e(i.DEPTH_TEST):Ze(i.DEPTH_TEST)},setMask:function(xe){de!==xe&&!G&&(i.depthMask(xe),de=xe)},setFunc:function(xe){if(we&&(xe=R0[xe]),He!==xe){switch(xe){case Zc:i.depthFunc(i.NEVER);break;case Qc:i.depthFunc(i.ALWAYS);break;case el:i.depthFunc(i.LESS);break;case ps:i.depthFunc(i.LEQUAL);break;case tl:i.depthFunc(i.EQUAL);break;case nl:i.depthFunc(i.GEQUAL);break;case il:i.depthFunc(i.GREATER);break;case rl:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}He=xe}},setLocked:function(xe){G=xe},setClear:function(xe){Ae!==xe&&(Ae=xe,we&&(xe=1-xe),i.clearDepth(xe))},reset:function(){G=!1,de=null,He=null,Ae=null,we=!1}}}function r(){let G=!1,we=null,de=null,He=null,Ae=null,xe=null,Xe=null,rt=null,jt=null;return{setTest:function(Rt){G||(Rt?_e(i.STENCIL_TEST):Ze(i.STENCIL_TEST))},setMask:function(Rt){we!==Rt&&!G&&(i.stencilMask(Rt),we=Rt)},setFunc:function(Rt,$n,ui){(de!==Rt||He!==$n||Ae!==ui)&&(i.stencilFunc(Rt,$n,ui),de=Rt,He=$n,Ae=ui)},setOp:function(Rt,$n,ui){(xe!==Rt||Xe!==$n||rt!==ui)&&(i.stencilOp(Rt,$n,ui),xe=Rt,Xe=$n,rt=ui)},setLocked:function(Rt){G=Rt},setClear:function(Rt){jt!==Rt&&(i.clearStencil(Rt),jt=Rt)},reset:function(){G=!1,we=null,de=null,He=null,Ae=null,xe=null,Xe=null,rt=null,jt=null}}}let s=new t,a=new n,o=new r,l=new WeakMap,c=new WeakMap,h={},d={},f={},p=new WeakMap,x=[],y=null,b=!1,g=null,S=null,A=null,T=null,N=null,P=null,U=null,v=new Ve(0,0,0),I=0,B=!1,k=null,V=null,J=null,L=null,E=null,D=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS),O=!1,H=0,Y=i.getParameter(i.VERSION);Y.indexOf("WebGL")!==-1?(H=parseFloat(/^WebGL (\d)/.exec(Y)[1]),O=H>=1):Y.indexOf("OpenGL ES")!==-1&&(H=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),O=H>=2);let le=null,fe={},be=i.getParameter(i.SCISSOR_BOX),Te=i.getParameter(i.VIEWPORT),Je=new kt().fromArray(be),ke=new kt().fromArray(Te);function oe(G,we,de,He){let Ae=new Uint8Array(4),xe=i.createTexture();i.bindTexture(G,xe),i.texParameteri(G,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(G,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let Xe=0;Xe<de;Xe++)G===i.TEXTURE_3D||G===i.TEXTURE_2D_ARRAY?i.texImage3D(we,0,i.RGBA,1,1,He,0,i.RGBA,i.UNSIGNED_BYTE,Ae):i.texImage2D(we+Xe,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,Ae);return xe}let Ee={};Ee[i.TEXTURE_2D]=oe(i.TEXTURE_2D,i.TEXTURE_2D,1),Ee[i.TEXTURE_CUBE_MAP]=oe(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),Ee[i.TEXTURE_2D_ARRAY]=oe(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),Ee[i.TEXTURE_3D]=oe(i.TEXTURE_3D,i.TEXTURE_3D,1,1),s.setClear(0,0,0,1),a.setClear(1),o.setClear(0),_e(i.DEPTH_TEST),a.setFunc(ps),Bt(!1),gt(vd),_e(i.CULL_FACE),wt(Ji);function _e(G){h[G]!==!0&&(i.enable(G),h[G]=!0)}function Ze(G){h[G]!==!1&&(i.disable(G),h[G]=!1)}function tt(G,we){return f[G]!==we?(i.bindFramebuffer(G,we),f[G]=we,G===i.DRAW_FRAMEBUFFER&&(f[i.FRAMEBUFFER]=we),G===i.FRAMEBUFFER&&(f[i.DRAW_FRAMEBUFFER]=we),!0):!1}function Qe(G,we){let de=x,He=!1;if(G){de=p.get(we),de===void 0&&(de=[],p.set(we,de));let Ae=G.textures;if(de.length!==Ae.length||de[0]!==i.COLOR_ATTACHMENT0){for(let xe=0,Xe=Ae.length;xe<Xe;xe++)de[xe]=i.COLOR_ATTACHMENT0+xe;de.length=Ae.length,He=!0}}else de[0]!==i.BACK&&(de[0]=i.BACK,He=!0);He&&i.drawBuffers(de)}function Et(G){return y!==G?(i.useProgram(G),y=G,!0):!1}let it={[Dr]:i.FUNC_ADD,[Kg]:i.FUNC_SUBTRACT,[Yg]:i.FUNC_REVERSE_SUBTRACT};it[Jg]=i.MIN,it[Zg]=i.MAX;let mt={[Qg]:i.ZERO,[e0]:i.ONE,[t0]:i.SRC_COLOR,[Yc]:i.SRC_ALPHA,[o0]:i.SRC_ALPHA_SATURATE,[s0]:i.DST_COLOR,[i0]:i.DST_ALPHA,[n0]:i.ONE_MINUS_SRC_COLOR,[Jc]:i.ONE_MINUS_SRC_ALPHA,[a0]:i.ONE_MINUS_DST_COLOR,[r0]:i.ONE_MINUS_DST_ALPHA,[c0]:i.CONSTANT_COLOR,[l0]:i.ONE_MINUS_CONSTANT_COLOR,[h0]:i.CONSTANT_ALPHA,[u0]:i.ONE_MINUS_CONSTANT_ALPHA};function wt(G,we,de,He,Ae,xe,Xe,rt,jt,Rt){if(G===Ji){b===!0&&(Ze(i.BLEND),b=!1);return}if(b===!1&&(_e(i.BLEND),b=!0),G!==Xg){if(G!==g||Rt!==B){if((S!==Dr||N!==Dr)&&(i.blendEquation(i.FUNC_ADD),S=Dr,N=Dr),Rt)switch(G){case fs:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Sd:i.blendFunc(i.ONE,i.ONE);break;case wd:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case Md:i.blendFuncSeparate(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE);break;default:et("WebGLState: Invalid blending: ",G);break}else switch(G){case fs:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Sd:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case wd:et("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Md:et("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:et("WebGLState: Invalid blending: ",G);break}A=null,T=null,P=null,U=null,v.set(0,0,0),I=0,g=G,B=Rt}return}Ae=Ae||we,xe=xe||de,Xe=Xe||He,(we!==S||Ae!==N)&&(i.blendEquationSeparate(it[we],it[Ae]),S=we,N=Ae),(de!==A||He!==T||xe!==P||Xe!==U)&&(i.blendFuncSeparate(mt[de],mt[He],mt[xe],mt[Xe]),A=de,T=He,P=xe,U=Xe),(rt.equals(v)===!1||jt!==I)&&(i.blendColor(rt.r,rt.g,rt.b,jt),v.copy(rt),I=jt),g=G,B=!1}function lt(G,we){G.side===Dn?Ze(i.CULL_FACE):_e(i.CULL_FACE);let de=G.side===An;we&&(de=!de),Bt(de),G.blending===fs&&G.transparent===!1?wt(Ji):wt(G.blending,G.blendEquation,G.blendSrc,G.blendDst,G.blendEquationAlpha,G.blendSrcAlpha,G.blendDstAlpha,G.blendColor,G.blendAlpha,G.premultipliedAlpha),a.setFunc(G.depthFunc),a.setTest(G.depthTest),a.setMask(G.depthWrite),s.setMask(G.colorWrite);let He=G.stencilWrite;o.setTest(He),He&&(o.setMask(G.stencilWriteMask),o.setFunc(G.stencilFunc,G.stencilRef,G.stencilFuncMask),o.setOp(G.stencilFail,G.stencilZFail,G.stencilZPass)),q(G.polygonOffset,G.polygonOffsetFactor,G.polygonOffsetUnits),G.alphaToCoverage===!0?_e(i.SAMPLE_ALPHA_TO_COVERAGE):Ze(i.SAMPLE_ALPHA_TO_COVERAGE)}function Bt(G){k!==G&&(G?i.frontFace(i.CW):i.frontFace(i.CCW),k=G)}function gt(G){G!==qg?(_e(i.CULL_FACE),G!==V&&(G===vd?i.cullFace(i.BACK):G===$g?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):Ze(i.CULL_FACE),V=G}function Yt(G){G!==J&&(O&&i.lineWidth(G),J=G)}function q(G,we,de){G?(_e(i.POLYGON_OFFSET_FILL),(L!==we||E!==de)&&(L=we,E=de,a.getReversed()&&(we=-we),i.polygonOffset(we,de))):Ze(i.POLYGON_OFFSET_FILL)}function $t(G){G?_e(i.SCISSOR_TEST):Ze(i.SCISSOR_TEST)}function ht(G){G===void 0&&(G=i.TEXTURE0+D-1),le!==G&&(i.activeTexture(G),le=G)}function Tt(G,we,de){de===void 0&&(le===null?de=i.TEXTURE0+D-1:de=le);let He=fe[de];He===void 0&&(He={type:void 0,texture:void 0},fe[de]=He),(He.type!==G||He.texture!==we)&&(le!==de&&(i.activeTexture(de),le=de),i.bindTexture(G,we||Ee[G]),He.type=G,He.texture=we)}function Pe(){let G=fe[le];G!==void 0&&G.type!==void 0&&(i.bindTexture(G.type,null),G.type=void 0,G.texture=void 0)}function Ot(){try{i.compressedTexImage2D(...arguments)}catch(G){et("WebGLState:",G)}}function F(){try{i.compressedTexImage3D(...arguments)}catch(G){et("WebGLState:",G)}}function M(){try{i.texSubImage2D(...arguments)}catch(G){et("WebGLState:",G)}}function Z(){try{i.texSubImage3D(...arguments)}catch(G){et("WebGLState:",G)}}function pe(){try{i.compressedTexSubImage2D(...arguments)}catch(G){et("WebGLState:",G)}}function ge(){try{i.compressedTexSubImage3D(...arguments)}catch(G){et("WebGLState:",G)}}function Se(){try{i.texStorage2D(...arguments)}catch(G){et("WebGLState:",G)}}function Ce(){try{i.texStorage3D(...arguments)}catch(G){et("WebGLState:",G)}}function ce(){try{i.texImage2D(...arguments)}catch(G){et("WebGLState:",G)}}function me(){try{i.texImage3D(...arguments)}catch(G){et("WebGLState:",G)}}function Be(G){return d[G]!==void 0?d[G]:i.getParameter(G)}function Le(G,we){d[G]!==we&&(i.pixelStorei(G,we),d[G]=we)}function ve(G){Je.equals(G)===!1&&(i.scissor(G.x,G.y,G.z,G.w),Je.copy(G))}function Me(G){ke.equals(G)===!1&&(i.viewport(G.x,G.y,G.z,G.w),ke.copy(G))}function je(G,we){let de=c.get(we);de===void 0&&(de=new WeakMap,c.set(we,de));let He=de.get(G);He===void 0&&(He=i.getUniformBlockIndex(we,G.name),de.set(G,He))}function nt(G,we){let He=c.get(we).get(G);l.get(we)!==He&&(i.uniformBlockBinding(we,He,G.__bindingPointIndex),l.set(we,He))}function pt(){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),a.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),h={},d={},le=null,fe={},f={},p=new WeakMap,x=[],y=null,b=!1,g=null,S=null,A=null,T=null,N=null,P=null,U=null,v=new Ve(0,0,0),I=0,B=!1,k=null,V=null,J=null,L=null,E=null,Je.set(0,0,i.canvas.width,i.canvas.height),ke.set(0,0,i.canvas.width,i.canvas.height),s.reset(),a.reset(),o.reset()}return{buffers:{color:s,depth:a,stencil:o},enable:_e,disable:Ze,bindFramebuffer:tt,drawBuffers:Qe,useProgram:Et,setBlending:wt,setMaterial:lt,setFlipSided:Bt,setCullFace:gt,setLineWidth:Yt,setPolygonOffset:q,setScissorTest:$t,activeTexture:ht,bindTexture:Tt,unbindTexture:Pe,compressedTexImage2D:Ot,compressedTexImage3D:F,texImage2D:ce,texImage3D:me,pixelStorei:Le,getParameter:Be,updateUBOMapping:je,uniformBlockBinding:nt,texStorage2D:Se,texStorage3D:Ce,texSubImage2D:M,texSubImage3D:Z,compressedTexSubImage2D:pe,compressedTexSubImage3D:ge,scissor:ve,viewport:Me,reset:pt}}function aT(i,e,t,n,r,s,a){let o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new dt,h=new WeakMap,d=new Set,f,p=new WeakMap,x=!1;try{x=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function y(F,M){return x?new OffscreenCanvas(F,M):aa("canvas")}function b(F,M,Z){let pe=1,ge=Ot(F);if((ge.width>Z||ge.height>Z)&&(pe=Z/Math.max(ge.width,ge.height)),pe<1)if(typeof HTMLImageElement<"u"&&F instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&F instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&F instanceof ImageBitmap||typeof VideoFrame<"u"&&F instanceof VideoFrame){let Se=Math.floor(pe*ge.width),Ce=Math.floor(pe*ge.height);f===void 0&&(f=y(Se,Ce));let ce=M?y(Se,Ce):f;return ce.width=Se,ce.height=Ce,ce.getContext("2d").drawImage(F,0,0,Se,Ce),Ke("WebGLRenderer: Texture has been resized from ("+ge.width+"x"+ge.height+") to ("+Se+"x"+Ce+")."),ce}else return"data"in F&&Ke("WebGLRenderer: Image in DataTexture is too big ("+ge.width+"x"+ge.height+")."),F;return F}function g(F){return F.generateMipmaps}function S(F){i.generateMipmap(F)}function A(F){return F.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:F.isWebGL3DRenderTarget?i.TEXTURE_3D:F.isWebGLArrayRenderTarget||F.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function T(F,M,Z,pe,ge,Se=!1){if(F!==null){if(i[F]!==void 0)return i[F];Ke("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+F+"'")}let Ce;pe&&(Ce=e.get("EXT_texture_norm16"),Ce||Ke("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let ce=M;if(M===i.RED&&(Z===i.FLOAT&&(ce=i.R32F),Z===i.HALF_FLOAT&&(ce=i.R16F),Z===i.UNSIGNED_BYTE&&(ce=i.R8),Z===i.UNSIGNED_SHORT&&Ce&&(ce=Ce.R16_EXT),Z===i.SHORT&&Ce&&(ce=Ce.R16_SNORM_EXT)),M===i.RED_INTEGER&&(Z===i.UNSIGNED_BYTE&&(ce=i.R8UI),Z===i.UNSIGNED_SHORT&&(ce=i.R16UI),Z===i.UNSIGNED_INT&&(ce=i.R32UI),Z===i.BYTE&&(ce=i.R8I),Z===i.SHORT&&(ce=i.R16I),Z===i.INT&&(ce=i.R32I)),M===i.RG&&(Z===i.FLOAT&&(ce=i.RG32F),Z===i.HALF_FLOAT&&(ce=i.RG16F),Z===i.UNSIGNED_BYTE&&(ce=i.RG8),Z===i.UNSIGNED_SHORT&&Ce&&(ce=Ce.RG16_EXT),Z===i.SHORT&&Ce&&(ce=Ce.RG16_SNORM_EXT)),M===i.RG_INTEGER&&(Z===i.UNSIGNED_BYTE&&(ce=i.RG8UI),Z===i.UNSIGNED_SHORT&&(ce=i.RG16UI),Z===i.UNSIGNED_INT&&(ce=i.RG32UI),Z===i.BYTE&&(ce=i.RG8I),Z===i.SHORT&&(ce=i.RG16I),Z===i.INT&&(ce=i.RG32I)),M===i.RGB_INTEGER&&(Z===i.UNSIGNED_BYTE&&(ce=i.RGB8UI),Z===i.UNSIGNED_SHORT&&(ce=i.RGB16UI),Z===i.UNSIGNED_INT&&(ce=i.RGB32UI),Z===i.BYTE&&(ce=i.RGB8I),Z===i.SHORT&&(ce=i.RGB16I),Z===i.INT&&(ce=i.RGB32I)),M===i.RGBA_INTEGER&&(Z===i.UNSIGNED_BYTE&&(ce=i.RGBA8UI),Z===i.UNSIGNED_SHORT&&(ce=i.RGBA16UI),Z===i.UNSIGNED_INT&&(ce=i.RGBA32UI),Z===i.BYTE&&(ce=i.RGBA8I),Z===i.SHORT&&(ce=i.RGBA16I),Z===i.INT&&(ce=i.RGBA32I)),M===i.RGB&&(Z===i.UNSIGNED_SHORT&&Ce&&(ce=Ce.RGB16_EXT),Z===i.SHORT&&Ce&&(ce=Ce.RGB16_SNORM_EXT),Z===i.UNSIGNED_INT_5_9_9_9_REV&&(ce=i.RGB9_E5),Z===i.UNSIGNED_INT_10F_11F_11F_REV&&(ce=i.R11F_G11F_B10F)),M===i.RGBA){let me=Se?Qa:ut.getTransfer(ge);Z===i.FLOAT&&(ce=i.RGBA32F),Z===i.HALF_FLOAT&&(ce=i.RGBA16F),Z===i.UNSIGNED_BYTE&&(ce=me===Dt?i.SRGB8_ALPHA8:i.RGBA8),Z===i.UNSIGNED_SHORT&&Ce&&(ce=Ce.RGBA16_EXT),Z===i.SHORT&&Ce&&(ce=Ce.RGBA16_SNORM_EXT),Z===i.UNSIGNED_SHORT_4_4_4_4&&(ce=i.RGBA4),Z===i.UNSIGNED_SHORT_5_5_5_1&&(ce=i.RGB5_A1)}return(ce===i.R16F||ce===i.R32F||ce===i.RG16F||ce===i.RG32F||ce===i.RGBA16F||ce===i.RGBA32F)&&e.get("EXT_color_buffer_float"),ce}function N(F,M){let Z;return F?M===null||M===Oi||M===xa?Z=i.DEPTH24_STENCIL8:M===Tn?Z=i.DEPTH32F_STENCIL8:M===ba&&(Z=i.DEPTH24_STENCIL8,Ke("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):M===null||M===Oi||M===xa?Z=i.DEPTH_COMPONENT24:M===Tn?Z=i.DEPTH_COMPONENT32F:M===ba&&(Z=i.DEPTH_COMPONENT16),Z}function P(F,M){return g(F)===!0||F.isFramebufferTexture&&F.minFilter!==on&&F.minFilter!==zt?Math.log2(Math.max(M.width,M.height))+1:F.mipmaps!==void 0&&F.mipmaps.length>0?F.mipmaps.length:F.isCompressedTexture&&Array.isArray(F.image)?M.mipmaps.length:1}function U(F){let M=F.target;M.removeEventListener("dispose",U),I(M),M.isVideoTexture&&h.delete(M),M.isHTMLTexture&&d.delete(M)}function v(F){let M=F.target;M.removeEventListener("dispose",v),k(M)}function I(F){let M=n.get(F);if(M.__webglInit===void 0)return;let Z=F.source,pe=p.get(Z);if(pe){let ge=pe[M.__cacheKey];ge.usedTimes--,ge.usedTimes===0&&B(F),Object.keys(pe).length===0&&p.delete(Z)}n.remove(F)}function B(F){let M=n.get(F);i.deleteTexture(M.__webglTexture);let Z=F.source,pe=p.get(Z);delete pe[M.__cacheKey],a.memory.textures--}function k(F){let M=n.get(F);if(F.depthTexture&&(F.depthTexture.dispose(),n.remove(F.depthTexture)),F.isWebGLCubeRenderTarget)for(let pe=0;pe<6;pe++){if(Array.isArray(M.__webglFramebuffer[pe]))for(let ge=0;ge<M.__webglFramebuffer[pe].length;ge++)i.deleteFramebuffer(M.__webglFramebuffer[pe][ge]);else i.deleteFramebuffer(M.__webglFramebuffer[pe]);M.__webglDepthbuffer&&i.deleteRenderbuffer(M.__webglDepthbuffer[pe])}else{if(Array.isArray(M.__webglFramebuffer))for(let pe=0;pe<M.__webglFramebuffer.length;pe++)i.deleteFramebuffer(M.__webglFramebuffer[pe]);else i.deleteFramebuffer(M.__webglFramebuffer);if(M.__webglDepthbuffer&&i.deleteRenderbuffer(M.__webglDepthbuffer),M.__webglMultisampledFramebuffer&&i.deleteFramebuffer(M.__webglMultisampledFramebuffer),M.__webglColorRenderbuffer)for(let pe=0;pe<M.__webglColorRenderbuffer.length;pe++)M.__webglColorRenderbuffer[pe]&&i.deleteRenderbuffer(M.__webglColorRenderbuffer[pe]);M.__webglDepthRenderbuffer&&i.deleteRenderbuffer(M.__webglDepthRenderbuffer)}let Z=F.textures;for(let pe=0,ge=Z.length;pe<ge;pe++){let Se=n.get(Z[pe]);Se.__webglTexture&&(i.deleteTexture(Se.__webglTexture),a.memory.textures--),n.remove(Z[pe])}n.remove(F)}let V=0;function J(){V=0}function L(){return V}function E(F){V=F}function D(){let F=V;return F>=r.maxTextures&&Ke("WebGLTextures: Trying to use "+F+" texture units while this GPU supports only "+r.maxTextures),V+=1,F}function O(F){let M=[];return M.push(F.wrapS),M.push(F.wrapT),M.push(F.wrapR||0),M.push(F.magFilter),M.push(F.minFilter),M.push(F.anisotropy),M.push(F.internalFormat),M.push(F.format),M.push(F.type),M.push(F.generateMipmaps),M.push(F.premultiplyAlpha),M.push(F.flipY),M.push(F.unpackAlignment),M.push(F.colorSpace),M.join()}function H(F,M){let Z=n.get(F);if(F.isVideoTexture&&Tt(F),F.isRenderTargetTexture===!1&&F.isExternalTexture!==!0&&F.version>0&&Z.__version!==F.version){let pe=F.image;if(pe===null)Ke("WebGLRenderer: Texture marked for update but no image data found.");else if(pe.complete===!1)Ke("WebGLRenderer: Texture marked for update but image is incomplete");else{Ze(Z,F,M);return}}else F.isExternalTexture&&(Z.__webglTexture=F.sourceTexture?F.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,Z.__webglTexture,i.TEXTURE0+M)}function Y(F,M){let Z=n.get(F);if(F.isRenderTargetTexture===!1&&F.version>0&&Z.__version!==F.version){Ze(Z,F,M);return}else F.isExternalTexture&&(Z.__webglTexture=F.sourceTexture?F.sourceTexture:null);t.bindTexture(i.TEXTURE_2D_ARRAY,Z.__webglTexture,i.TEXTURE0+M)}function le(F,M){let Z=n.get(F);if(F.isRenderTargetTexture===!1&&F.version>0&&Z.__version!==F.version){Ze(Z,F,M);return}t.bindTexture(i.TEXTURE_3D,Z.__webglTexture,i.TEXTURE0+M)}function fe(F,M){let Z=n.get(F);if(F.isCubeDepthTexture!==!0&&F.version>0&&Z.__version!==F.version){tt(Z,F,M);return}t.bindTexture(i.TEXTURE_CUBE_MAP,Z.__webglTexture,i.TEXTURE0+M)}let be={[Nr]:i.REPEAT,[Kn]:i.CLAMP_TO_EDGE,[ra]:i.MIRRORED_REPEAT},Te={[on]:i.NEAREST,[Pl]:i.NEAREST_MIPMAP_NEAREST,[Ts]:i.NEAREST_MIPMAP_LINEAR,[zt]:i.LINEAR,[ga]:i.LINEAR_MIPMAP_NEAREST,[xi]:i.LINEAR_MIPMAP_LINEAR},Je={[x0]:i.NEVER,[w0]:i.ALWAYS,[_0]:i.LESS,[gh]:i.LEQUAL,[y0]:i.EQUAL,[bh]:i.GEQUAL,[v0]:i.GREATER,[S0]:i.NOTEQUAL};function ke(F,M){if(M.type===Tn&&e.has("OES_texture_float_linear")===!1&&(M.magFilter===zt||M.magFilter===ga||M.magFilter===Ts||M.magFilter===xi||M.minFilter===zt||M.minFilter===ga||M.minFilter===Ts||M.minFilter===xi)&&Ke("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(F,i.TEXTURE_WRAP_S,be[M.wrapS]),i.texParameteri(F,i.TEXTURE_WRAP_T,be[M.wrapT]),(F===i.TEXTURE_3D||F===i.TEXTURE_2D_ARRAY)&&i.texParameteri(F,i.TEXTURE_WRAP_R,be[M.wrapR]),i.texParameteri(F,i.TEXTURE_MAG_FILTER,Te[M.magFilter]),i.texParameteri(F,i.TEXTURE_MIN_FILTER,Te[M.minFilter]),M.compareFunction&&(i.texParameteri(F,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(F,i.TEXTURE_COMPARE_FUNC,Je[M.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(M.magFilter===on||M.minFilter!==Ts&&M.minFilter!==xi||M.type===Tn&&e.has("OES_texture_float_linear")===!1)return;if(M.anisotropy>1||n.get(M).__currentAnisotropy){let Z=e.get("EXT_texture_filter_anisotropic");i.texParameterf(F,Z.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,r.getMaxAnisotropy())),n.get(M).__currentAnisotropy=M.anisotropy}}}function oe(F,M){let Z=!1;F.__webglInit===void 0&&(F.__webglInit=!0,M.addEventListener("dispose",U));let pe=M.source,ge=p.get(pe);ge===void 0&&(ge={},p.set(pe,ge));let Se=O(M);if(Se!==F.__cacheKey){ge[Se]===void 0&&(ge[Se]={texture:i.createTexture(),usedTimes:0},a.memory.textures++,Z=!0),ge[Se].usedTimes++;let Ce=ge[F.__cacheKey];Ce!==void 0&&(ge[F.__cacheKey].usedTimes--,Ce.usedTimes===0&&B(M)),F.__cacheKey=Se,F.__webglTexture=ge[Se].texture}return Z}function Ee(F,M,Z){return Math.floor(Math.floor(F/Z)/M)}function _e(F,M,Z,pe){let Se=F.updateRanges;if(Se.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,M.width,M.height,Z,pe,M.data);else{Se.sort((Le,ve)=>Le.start-ve.start);let Ce=0;for(let Le=1;Le<Se.length;Le++){let ve=Se[Ce],Me=Se[Le],je=ve.start+ve.count,nt=Ee(Me.start,M.width,4),pt=Ee(ve.start,M.width,4);Me.start<=je+1&&nt===pt&&Ee(Me.start+Me.count-1,M.width,4)===nt?ve.count=Math.max(ve.count,Me.start+Me.count-ve.start):(++Ce,Se[Ce]=Me)}Se.length=Ce+1;let ce=t.getParameter(i.UNPACK_ROW_LENGTH),me=t.getParameter(i.UNPACK_SKIP_PIXELS),Be=t.getParameter(i.UNPACK_SKIP_ROWS);t.pixelStorei(i.UNPACK_ROW_LENGTH,M.width);for(let Le=0,ve=Se.length;Le<ve;Le++){let Me=Se[Le],je=Math.floor(Me.start/4),nt=Math.ceil(Me.count/4),pt=je%M.width,G=Math.floor(je/M.width),we=nt,de=1;t.pixelStorei(i.UNPACK_SKIP_PIXELS,pt),t.pixelStorei(i.UNPACK_SKIP_ROWS,G),t.texSubImage2D(i.TEXTURE_2D,0,pt,G,we,de,Z,pe,M.data)}F.clearUpdateRanges(),t.pixelStorei(i.UNPACK_ROW_LENGTH,ce),t.pixelStorei(i.UNPACK_SKIP_PIXELS,me),t.pixelStorei(i.UNPACK_SKIP_ROWS,Be)}}function Ze(F,M,Z){let pe=i.TEXTURE_2D;(M.isDataArrayTexture||M.isCompressedArrayTexture)&&(pe=i.TEXTURE_2D_ARRAY),M.isData3DTexture&&(pe=i.TEXTURE_3D);let ge=oe(F,M),Se=M.source;t.bindTexture(pe,F.__webglTexture,i.TEXTURE0+Z);let Ce=n.get(Se);if(Se.version!==Ce.__version||ge===!0){if(t.activeTexture(i.TEXTURE0+Z),(typeof ImageBitmap<"u"&&M.image instanceof ImageBitmap)===!1){let de=ut.getPrimaries(ut.workingColorSpace),He=M.colorSpace===Fi?null:ut.getPrimaries(M.colorSpace),Ae=M.colorSpace===Fi||de===He?i.NONE:i.BROWSER_DEFAULT_WEBGL;t.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,M.flipY),t.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),t.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ae)}t.pixelStorei(i.UNPACK_ALIGNMENT,M.unpackAlignment);let me=b(M.image,!1,r.maxTextureSize);me=Pe(M,me);let Be=s.convert(M.format,M.colorSpace),Le=s.convert(M.type),ve=T(M.internalFormat,Be,Le,M.normalized,M.colorSpace,M.isVideoTexture);ke(pe,M);let Me,je=M.mipmaps,nt=M.isVideoTexture!==!0,pt=Ce.__version===void 0||ge===!0,G=Se.dataReady,we=P(M,me);if(M.isDepthTexture)ve=N(M.format===jr,M.type),pt&&(nt?t.texStorage2D(i.TEXTURE_2D,1,ve,me.width,me.height):t.texImage2D(i.TEXTURE_2D,0,ve,me.width,me.height,0,Be,Le,null));else if(M.isDataTexture)if(je.length>0){nt&&pt&&t.texStorage2D(i.TEXTURE_2D,we,ve,je[0].width,je[0].height);for(let de=0,He=je.length;de<He;de++)Me=je[de],nt?G&&t.texSubImage2D(i.TEXTURE_2D,de,0,0,Me.width,Me.height,Be,Le,Me.data):t.texImage2D(i.TEXTURE_2D,de,ve,Me.width,Me.height,0,Be,Le,Me.data);M.generateMipmaps=!1}else nt?(pt&&t.texStorage2D(i.TEXTURE_2D,we,ve,me.width,me.height),G&&_e(M,me,Be,Le)):t.texImage2D(i.TEXTURE_2D,0,ve,me.width,me.height,0,Be,Le,me.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){nt&&pt&&t.texStorage3D(i.TEXTURE_2D_ARRAY,we,ve,je[0].width,je[0].height,me.depth);for(let de=0,He=je.length;de<He;de++)if(Me=je[de],M.format!==ci)if(Be!==null)if(nt){if(G)if(M.layerUpdates.size>0){let Ae=$d(Me.width,Me.height,M.format,M.type);for(let xe of M.layerUpdates){let Xe=Me.data.subarray(xe*Ae/Me.data.BYTES_PER_ELEMENT,(xe+1)*Ae/Me.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,de,0,0,xe,Me.width,Me.height,1,Be,Xe)}M.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,de,0,0,0,Me.width,Me.height,me.depth,Be,Me.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,de,ve,Me.width,Me.height,me.depth,0,Me.data,0,0);else Ke("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else nt?G&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,de,0,0,0,Me.width,Me.height,me.depth,Be,Le,Me.data):t.texImage3D(i.TEXTURE_2D_ARRAY,de,ve,Me.width,Me.height,me.depth,0,Be,Le,Me.data)}else{nt&&pt&&t.texStorage2D(i.TEXTURE_2D,we,ve,je[0].width,je[0].height);for(let de=0,He=je.length;de<He;de++)Me=je[de],M.format!==ci?Be!==null?nt?G&&t.compressedTexSubImage2D(i.TEXTURE_2D,de,0,0,Me.width,Me.height,Be,Me.data):t.compressedTexImage2D(i.TEXTURE_2D,de,ve,Me.width,Me.height,0,Me.data):Ke("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):nt?G&&t.texSubImage2D(i.TEXTURE_2D,de,0,0,Me.width,Me.height,Be,Le,Me.data):t.texImage2D(i.TEXTURE_2D,de,ve,Me.width,Me.height,0,Be,Le,Me.data)}else if(M.isDataArrayTexture)if(nt){if(pt&&t.texStorage3D(i.TEXTURE_2D_ARRAY,we,ve,me.width,me.height,me.depth),G)if(M.layerUpdates.size>0){let de=$d(me.width,me.height,M.format,M.type);for(let He of M.layerUpdates){let Ae=me.data.subarray(He*de/me.data.BYTES_PER_ELEMENT,(He+1)*de/me.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,He,me.width,me.height,1,Be,Le,Ae)}M.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,me.width,me.height,me.depth,Be,Le,me.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,ve,me.width,me.height,me.depth,0,Be,Le,me.data);else if(M.isData3DTexture)nt?(pt&&t.texStorage3D(i.TEXTURE_3D,we,ve,me.width,me.height,me.depth),G&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,me.width,me.height,me.depth,Be,Le,me.data)):t.texImage3D(i.TEXTURE_3D,0,ve,me.width,me.height,me.depth,0,Be,Le,me.data);else if(M.isFramebufferTexture){if(pt)if(nt)t.texStorage2D(i.TEXTURE_2D,we,ve,me.width,me.height);else{let de=me.width,He=me.height;for(let Ae=0;Ae<we;Ae++)t.texImage2D(i.TEXTURE_2D,Ae,ve,de,He,0,Be,Le,null),de>>=1,He>>=1}}else if(M.isHTMLTexture){if("texElementImage2D"in i){let de=i.canvas;if(de.hasAttribute("layoutsubtree")||de.setAttribute("layoutsubtree","true"),me.parentNode!==de){de.appendChild(me),d.add(M),de.onpaint=rt=>{let jt=rt.changedElements;for(let Rt of d)jt.includes(Rt.image)&&(Rt.needsUpdate=!0)},de.requestPaint();return}let He=0,Ae=i.RGBA,xe=i.RGBA,Xe=i.UNSIGNED_BYTE;i.texElementImage2D(i.TEXTURE_2D,He,Ae,xe,Xe,me),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(je.length>0){if(nt&&pt){let de=Ot(je[0]);t.texStorage2D(i.TEXTURE_2D,we,ve,de.width,de.height)}for(let de=0,He=je.length;de<He;de++)Me=je[de],nt?G&&t.texSubImage2D(i.TEXTURE_2D,de,0,0,Be,Le,Me):t.texImage2D(i.TEXTURE_2D,de,ve,Be,Le,Me);M.generateMipmaps=!1}else if(nt){if(pt){let de=Ot(me);t.texStorage2D(i.TEXTURE_2D,we,ve,de.width,de.height)}G&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,Be,Le,me)}else t.texImage2D(i.TEXTURE_2D,0,ve,Be,Le,me);g(M)&&S(pe),Ce.__version=Se.version,M.onUpdate&&M.onUpdate(M)}F.__version=M.version}function tt(F,M,Z){if(M.image.length!==6)return;let pe=oe(F,M),ge=M.source;t.bindTexture(i.TEXTURE_CUBE_MAP,F.__webglTexture,i.TEXTURE0+Z);let Se=n.get(ge);if(ge.version!==Se.__version||pe===!0){t.activeTexture(i.TEXTURE0+Z);let Ce=ut.getPrimaries(ut.workingColorSpace),ce=M.colorSpace===Fi?null:ut.getPrimaries(M.colorSpace),me=M.colorSpace===Fi||Ce===ce?i.NONE:i.BROWSER_DEFAULT_WEBGL;t.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,M.flipY),t.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),t.pixelStorei(i.UNPACK_ALIGNMENT,M.unpackAlignment),t.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,me);let Be=M.isCompressedTexture||M.image[0].isCompressedTexture,Le=M.image[0]&&M.image[0].isDataTexture,ve=[];for(let xe=0;xe<6;xe++)!Be&&!Le?ve[xe]=b(M.image[xe],!0,r.maxCubemapSize):ve[xe]=Le?M.image[xe].image:M.image[xe],ve[xe]=Pe(M,ve[xe]);let Me=ve[0],je=s.convert(M.format,M.colorSpace),nt=s.convert(M.type),pt=T(M.internalFormat,je,nt,M.normalized,M.colorSpace),G=M.isVideoTexture!==!0,we=Se.__version===void 0||pe===!0,de=ge.dataReady,He=P(M,Me);ke(i.TEXTURE_CUBE_MAP,M);let Ae;if(Be){G&&we&&t.texStorage2D(i.TEXTURE_CUBE_MAP,He,pt,Me.width,Me.height);for(let xe=0;xe<6;xe++){Ae=ve[xe].mipmaps;for(let Xe=0;Xe<Ae.length;Xe++){let rt=Ae[Xe];M.format!==ci?je!==null?G?de&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,Xe,0,0,rt.width,rt.height,je,rt.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,Xe,pt,rt.width,rt.height,0,rt.data):Ke("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):G?de&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,Xe,0,0,rt.width,rt.height,je,nt,rt.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,Xe,pt,rt.width,rt.height,0,je,nt,rt.data)}}}else{if(Ae=M.mipmaps,G&&we){Ae.length>0&&He++;let xe=Ot(ve[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,He,pt,xe.width,xe.height)}for(let xe=0;xe<6;xe++)if(Le){G?de&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,0,0,0,ve[xe].width,ve[xe].height,je,nt,ve[xe].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,0,pt,ve[xe].width,ve[xe].height,0,je,nt,ve[xe].data);for(let Xe=0;Xe<Ae.length;Xe++){let jt=Ae[Xe].image[xe].image;G?de&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,Xe+1,0,0,jt.width,jt.height,je,nt,jt.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,Xe+1,pt,jt.width,jt.height,0,je,nt,jt.data)}}else{G?de&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,0,0,0,je,nt,ve[xe]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,0,pt,je,nt,ve[xe]);for(let Xe=0;Xe<Ae.length;Xe++){let rt=Ae[Xe];G?de&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,Xe+1,0,0,je,nt,rt.image[xe]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+xe,Xe+1,pt,je,nt,rt.image[xe])}}}g(M)&&S(i.TEXTURE_CUBE_MAP),Se.__version=ge.version,M.onUpdate&&M.onUpdate(M)}F.__version=M.version}function Qe(F,M,Z,pe,ge,Se){let Ce=s.convert(Z.format,Z.colorSpace),ce=s.convert(Z.type),me=T(Z.internalFormat,Ce,ce,Z.normalized,Z.colorSpace),Be=n.get(M),Le=n.get(Z);if(Le.__renderTarget=M,!Be.__hasExternalTextures){let ve=Math.max(1,M.width>>Se),Me=Math.max(1,M.height>>Se);ge===i.TEXTURE_3D||ge===i.TEXTURE_2D_ARRAY?t.texImage3D(ge,Se,me,ve,Me,M.depth,0,Ce,ce,null):t.texImage2D(ge,Se,me,ve,Me,0,Ce,ce,null)}t.bindFramebuffer(i.FRAMEBUFFER,F),ht(M)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,pe,ge,Le.__webglTexture,0,$t(M)):(ge===i.TEXTURE_2D||ge>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&ge<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,pe,ge,Le.__webglTexture,Se),t.bindFramebuffer(i.FRAMEBUFFER,null)}function Et(F,M,Z){if(i.bindRenderbuffer(i.RENDERBUFFER,F),M.depthBuffer){let pe=M.depthTexture,ge=pe&&pe.isDepthTexture?pe.type:null,Se=N(M.stencilBuffer,ge),Ce=M.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;ht(M)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,$t(M),Se,M.width,M.height):Z?i.renderbufferStorageMultisample(i.RENDERBUFFER,$t(M),Se,M.width,M.height):i.renderbufferStorage(i.RENDERBUFFER,Se,M.width,M.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,Ce,i.RENDERBUFFER,F)}else{let pe=M.textures;for(let ge=0;ge<pe.length;ge++){let Se=pe[ge],Ce=s.convert(Se.format,Se.colorSpace),ce=s.convert(Se.type),me=T(Se.internalFormat,Ce,ce,Se.normalized,Se.colorSpace);ht(M)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,$t(M),me,M.width,M.height):Z?i.renderbufferStorageMultisample(i.RENDERBUFFER,$t(M),me,M.width,M.height):i.renderbufferStorage(i.RENDERBUFFER,me,M.width,M.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function it(F,M,Z){let pe=M.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(i.FRAMEBUFFER,F),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");let ge=n.get(M.depthTexture);if(ge.__renderTarget=M,(!ge.__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)&&(M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0),pe){if(ge.__webglInit===void 0&&(ge.__webglInit=!0,M.depthTexture.addEventListener("dispose",U)),ge.__webglTexture===void 0){ge.__webglTexture=i.createTexture(),t.bindTexture(i.TEXTURE_CUBE_MAP,ge.__webglTexture),ke(i.TEXTURE_CUBE_MAP,M.depthTexture);let Be=s.convert(M.depthTexture.format),Le=s.convert(M.depthTexture.type),ve;M.depthTexture.format===Wi?ve=i.DEPTH_COMPONENT24:M.depthTexture.format===jr&&(ve=i.DEPTH24_STENCIL8);for(let Me=0;Me<6;Me++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Me,0,ve,M.width,M.height,0,Be,Le,null)}}else H(M.depthTexture,0);let Se=ge.__webglTexture,Ce=$t(M),ce=pe?i.TEXTURE_CUBE_MAP_POSITIVE_X+Z:i.TEXTURE_2D,me=M.depthTexture.format===jr?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;if(M.depthTexture.format===Wi)ht(M)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,me,ce,Se,0,Ce):i.framebufferTexture2D(i.FRAMEBUFFER,me,ce,Se,0);else if(M.depthTexture.format===jr)ht(M)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,me,ce,Se,0,Ce):i.framebufferTexture2D(i.FRAMEBUFFER,me,ce,Se,0);else throw new Error("Unknown depthTexture format")}function mt(F){let M=n.get(F),Z=F.isWebGLCubeRenderTarget===!0;if(M.__boundDepthTexture!==F.depthTexture){let pe=F.depthTexture;if(M.__depthDisposeCallback&&M.__depthDisposeCallback(),pe){let ge=()=>{delete M.__boundDepthTexture,delete M.__depthDisposeCallback,pe.removeEventListener("dispose",ge)};pe.addEventListener("dispose",ge),M.__depthDisposeCallback=ge}M.__boundDepthTexture=pe}if(F.depthTexture&&!M.__autoAllocateDepthBuffer)if(Z)for(let pe=0;pe<6;pe++)it(M.__webglFramebuffer[pe],F,pe);else{let pe=F.texture.mipmaps;pe&&pe.length>0?it(M.__webglFramebuffer[0],F,0):it(M.__webglFramebuffer,F,0)}else if(Z){M.__webglDepthbuffer=[];for(let pe=0;pe<6;pe++)if(t.bindFramebuffer(i.FRAMEBUFFER,M.__webglFramebuffer[pe]),M.__webglDepthbuffer[pe]===void 0)M.__webglDepthbuffer[pe]=i.createRenderbuffer(),Et(M.__webglDepthbuffer[pe],F,!1);else{let ge=F.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Se=M.__webglDepthbuffer[pe];i.bindRenderbuffer(i.RENDERBUFFER,Se),i.framebufferRenderbuffer(i.FRAMEBUFFER,ge,i.RENDERBUFFER,Se)}}else{let pe=F.texture.mipmaps;if(pe&&pe.length>0?t.bindFramebuffer(i.FRAMEBUFFER,M.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,M.__webglFramebuffer),M.__webglDepthbuffer===void 0)M.__webglDepthbuffer=i.createRenderbuffer(),Et(M.__webglDepthbuffer,F,!1);else{let ge=F.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Se=M.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,Se),i.framebufferRenderbuffer(i.FRAMEBUFFER,ge,i.RENDERBUFFER,Se)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function wt(F,M,Z){let pe=n.get(F);M!==void 0&&Qe(pe.__webglFramebuffer,F,F.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),Z!==void 0&&mt(F)}function lt(F){let M=F.texture,Z=n.get(F),pe=n.get(M);F.addEventListener("dispose",v);let ge=F.textures,Se=F.isWebGLCubeRenderTarget===!0,Ce=ge.length>1;if(Ce||(pe.__webglTexture===void 0&&(pe.__webglTexture=i.createTexture()),pe.__version=M.version,a.memory.textures++),Se){Z.__webglFramebuffer=[];for(let ce=0;ce<6;ce++)if(M.mipmaps&&M.mipmaps.length>0){Z.__webglFramebuffer[ce]=[];for(let me=0;me<M.mipmaps.length;me++)Z.__webglFramebuffer[ce][me]=i.createFramebuffer()}else Z.__webglFramebuffer[ce]=i.createFramebuffer()}else{if(M.mipmaps&&M.mipmaps.length>0){Z.__webglFramebuffer=[];for(let ce=0;ce<M.mipmaps.length;ce++)Z.__webglFramebuffer[ce]=i.createFramebuffer()}else Z.__webglFramebuffer=i.createFramebuffer();if(Ce)for(let ce=0,me=ge.length;ce<me;ce++){let Be=n.get(ge[ce]);Be.__webglTexture===void 0&&(Be.__webglTexture=i.createTexture(),a.memory.textures++)}if(F.samples>0&&ht(F)===!1){Z.__webglMultisampledFramebuffer=i.createFramebuffer(),Z.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,Z.__webglMultisampledFramebuffer);for(let ce=0;ce<ge.length;ce++){let me=ge[ce];Z.__webglColorRenderbuffer[ce]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,Z.__webglColorRenderbuffer[ce]);let Be=s.convert(me.format,me.colorSpace),Le=s.convert(me.type),ve=T(me.internalFormat,Be,Le,me.normalized,me.colorSpace,F.isXRRenderTarget===!0),Me=$t(F);i.renderbufferStorageMultisample(i.RENDERBUFFER,Me,ve,F.width,F.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+ce,i.RENDERBUFFER,Z.__webglColorRenderbuffer[ce])}i.bindRenderbuffer(i.RENDERBUFFER,null),F.depthBuffer&&(Z.__webglDepthRenderbuffer=i.createRenderbuffer(),Et(Z.__webglDepthRenderbuffer,F,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(Se){t.bindTexture(i.TEXTURE_CUBE_MAP,pe.__webglTexture),ke(i.TEXTURE_CUBE_MAP,M);for(let ce=0;ce<6;ce++)if(M.mipmaps&&M.mipmaps.length>0)for(let me=0;me<M.mipmaps.length;me++)Qe(Z.__webglFramebuffer[ce][me],F,M,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ce,me);else Qe(Z.__webglFramebuffer[ce],F,M,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+ce,0);g(M)&&S(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Ce){for(let ce=0,me=ge.length;ce<me;ce++){let Be=ge[ce],Le=n.get(Be),ve=i.TEXTURE_2D;(F.isWebGL3DRenderTarget||F.isWebGLArrayRenderTarget)&&(ve=F.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(ve,Le.__webglTexture),ke(ve,Be),Qe(Z.__webglFramebuffer,F,Be,i.COLOR_ATTACHMENT0+ce,ve,0),g(Be)&&S(ve)}t.unbindTexture()}else{let ce=i.TEXTURE_2D;if((F.isWebGL3DRenderTarget||F.isWebGLArrayRenderTarget)&&(ce=F.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(ce,pe.__webglTexture),ke(ce,M),M.mipmaps&&M.mipmaps.length>0)for(let me=0;me<M.mipmaps.length;me++)Qe(Z.__webglFramebuffer[me],F,M,i.COLOR_ATTACHMENT0,ce,me);else Qe(Z.__webglFramebuffer,F,M,i.COLOR_ATTACHMENT0,ce,0);g(M)&&S(ce),t.unbindTexture()}F.depthBuffer&&mt(F)}function Bt(F){let M=F.textures;for(let Z=0,pe=M.length;Z<pe;Z++){let ge=M[Z];if(g(ge)){let Se=A(F),Ce=n.get(ge).__webglTexture;t.bindTexture(Se,Ce),S(Se),t.unbindTexture()}}}let gt=[],Yt=[];function q(F){if(F.samples>0){if(ht(F)===!1){let M=F.textures,Z=F.width,pe=F.height,ge=i.COLOR_BUFFER_BIT,Se=F.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Ce=n.get(F),ce=M.length>1;if(ce)for(let Be=0;Be<M.length;Be++)t.bindFramebuffer(i.FRAMEBUFFER,Ce.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Be,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,Ce.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Be,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,Ce.__webglMultisampledFramebuffer);let me=F.texture.mipmaps;me&&me.length>0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Ce.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Ce.__webglFramebuffer);for(let Be=0;Be<M.length;Be++){if(F.resolveDepthBuffer&&(F.depthBuffer&&(ge|=i.DEPTH_BUFFER_BIT),F.stencilBuffer&&F.resolveStencilBuffer&&(ge|=i.STENCIL_BUFFER_BIT)),ce){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,Ce.__webglColorRenderbuffer[Be]);let Le=n.get(M[Be]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,Le,0)}i.blitFramebuffer(0,0,Z,pe,0,0,Z,pe,ge,i.NEAREST),l===!0&&(gt.length=0,Yt.length=0,gt.push(i.COLOR_ATTACHMENT0+Be),F.depthBuffer&&F.resolveDepthBuffer===!1&&(gt.push(Se),Yt.push(Se),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,Yt)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,gt))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),ce)for(let Be=0;Be<M.length;Be++){t.bindFramebuffer(i.FRAMEBUFFER,Ce.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Be,i.RENDERBUFFER,Ce.__webglColorRenderbuffer[Be]);let Le=n.get(M[Be]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,Ce.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Be,i.TEXTURE_2D,Le,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,Ce.__webglMultisampledFramebuffer)}else if(F.depthBuffer&&F.resolveDepthBuffer===!1&&l){let M=F.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[M])}}}function $t(F){return Math.min(r.maxSamples,F.samples)}function ht(F){let M=n.get(F);return F.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function Tt(F){let M=a.render.frame;h.get(F)!==M&&(h.set(F,M),F.update())}function Pe(F,M){let Z=F.colorSpace,pe=F.format,ge=F.type;return F.isCompressedTexture===!0||F.isVideoTexture===!0||Z!==bn&&Z!==Fi&&(ut.getTransfer(Z)===Dt?(pe!==ci||ge!==Qn)&&Ke("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):et("WebGLTextures: Unsupported texture color space:",Z)),M}function Ot(F){return typeof HTMLImageElement<"u"&&F instanceof HTMLImageElement?(c.width=F.naturalWidth||F.width,c.height=F.naturalHeight||F.height):typeof VideoFrame<"u"&&F instanceof VideoFrame?(c.width=F.displayWidth,c.height=F.displayHeight):(c.width=F.width,c.height=F.height),c}this.allocateTextureUnit=D,this.resetTextureUnits=J,this.getTextureUnits=L,this.setTextureUnits=E,this.setTexture2D=H,this.setTexture2DArray=Y,this.setTexture3D=le,this.setTextureCube=fe,this.rebindTextures=wt,this.setupRenderTarget=lt,this.updateRenderTargetMipmap=Bt,this.updateMultisampleRenderTarget=q,this.setupDepthRenderbuffer=mt,this.setupFrameBufferTexture=Qe,this.useMultisampledRTT=ht,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function oT(i,e){function t(n,r=Fi){let s,a=ut.getTransfer(r);if(n===Qn)return i.UNSIGNED_BYTE;if(n===Dl)return i.UNSIGNED_SHORT_4_4_4_4;if(n===Nl)return i.UNSIGNED_SHORT_5_5_5_1;if(n===Nd)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===Od)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===Ld)return i.BYTE;if(n===Dd)return i.SHORT;if(n===ba)return i.UNSIGNED_SHORT;if(n===Ll)return i.INT;if(n===Oi)return i.UNSIGNED_INT;if(n===Tn)return i.FLOAT;if(n===Gn)return i.HALF_FLOAT;if(n===Fd)return i.ALPHA;if(n===Ud)return i.RGB;if(n===ci)return i.RGBA;if(n===Wi)return i.DEPTH_COMPONENT;if(n===jr)return i.DEPTH_STENCIL;if(n===Ol)return i.RED;if(n===Fl)return i.RED_INTEGER;if(n===Xr)return i.RG;if(n===Ul)return i.RG_INTEGER;if(n===kl)return i.RGBA_INTEGER;if(n===Io||n===Po||n===Lo||n===Do)if(a===Dt)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(n===Io)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Po)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Lo)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Do)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(n===Io)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Po)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Lo)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Do)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Bl||n===zl||n===Hl||n===Gl)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(n===Bl)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===zl)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Hl)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Gl)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===Vl||n===Wl||n===ql||n===$l||n===jl||n===No||n===Xl)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(n===Vl||n===Wl)return a===Dt?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(n===ql)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(n===$l)return s.COMPRESSED_R11_EAC;if(n===jl)return s.COMPRESSED_SIGNED_R11_EAC;if(n===No)return s.COMPRESSED_RG11_EAC;if(n===Xl)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===Kl||n===Yl||n===Jl||n===Zl||n===Ql||n===eh||n===th||n===nh||n===ih||n===rh||n===sh||n===ah||n===oh||n===ch)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(n===Kl)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Yl)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Jl)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Zl)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===Ql)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===eh)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===th)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===nh)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===ih)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===rh)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===sh)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===ah)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===oh)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===ch)return a===Dt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===lh||n===hh||n===uh)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(n===lh)return a===Dt?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===hh)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===uh)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===dh||n===fh||n===Oo||n===ph)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(n===dh)return s.COMPRESSED_RED_RGTC1_EXT;if(n===fh)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Oo)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===ph)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===xa?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}function uT(i,e){function t(b,g){b.matrixAutoUpdate===!0&&b.updateMatrix(),g.value.copy(b.matrix)}function n(b,g){g.color.getRGB(b.fogColor.value,Gd(i)),g.isFog?(b.fogNear.value=g.near,b.fogFar.value=g.far):g.isFogExp2&&(b.fogDensity.value=g.density)}function r(b,g,S,A,T){g.isNodeMaterial?g.uniformsNeedUpdate=!1:g.isMeshBasicMaterial?s(b,g):g.isMeshLambertMaterial?(s(b,g),g.envMap&&(b.envMapIntensity.value=g.envMapIntensity)):g.isMeshToonMaterial?(s(b,g),d(b,g)):g.isMeshPhongMaterial?(s(b,g),h(b,g),g.envMap&&(b.envMapIntensity.value=g.envMapIntensity)):g.isMeshStandardMaterial?(s(b,g),f(b,g),g.isMeshPhysicalMaterial&&p(b,g,T)):g.isMeshMatcapMaterial?(s(b,g),x(b,g)):g.isMeshDepthMaterial?s(b,g):g.isMeshDistanceMaterial?(s(b,g),y(b,g)):g.isMeshNormalMaterial?s(b,g):g.isLineBasicMaterial?(a(b,g),g.isLineDashedMaterial&&o(b,g)):g.isPointsMaterial?l(b,g,S,A):g.isSpriteMaterial?c(b,g):g.isShadowMaterial?(b.color.value.copy(g.color),b.opacity.value=g.opacity):g.isShaderMaterial&&(g.uniformsNeedUpdate=!1)}function s(b,g){b.opacity.value=g.opacity,g.color&&b.diffuse.value.copy(g.color),g.emissive&&b.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity),g.map&&(b.map.value=g.map,t(g.map,b.mapTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,t(g.alphaMap,b.alphaMapTransform)),g.bumpMap&&(b.bumpMap.value=g.bumpMap,t(g.bumpMap,b.bumpMapTransform),b.bumpScale.value=g.bumpScale,g.side===An&&(b.bumpScale.value*=-1)),g.normalMap&&(b.normalMap.value=g.normalMap,t(g.normalMap,b.normalMapTransform),b.normalScale.value.copy(g.normalScale),g.side===An&&b.normalScale.value.negate()),g.displacementMap&&(b.displacementMap.value=g.displacementMap,t(g.displacementMap,b.displacementMapTransform),b.displacementScale.value=g.displacementScale,b.displacementBias.value=g.displacementBias),g.emissiveMap&&(b.emissiveMap.value=g.emissiveMap,t(g.emissiveMap,b.emissiveMapTransform)),g.specularMap&&(b.specularMap.value=g.specularMap,t(g.specularMap,b.specularMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest);let S=e.get(g),A=S.envMap,T=S.envMapRotation;A&&(b.envMap.value=A,b.envMapRotation.value.setFromMatrix4(hT.makeRotationFromEuler(T)).transpose(),A.isCubeTexture&&A.isRenderTargetTexture===!1&&b.envMapRotation.value.premultiply(ob),b.reflectivity.value=g.reflectivity,b.ior.value=g.ior,b.refractionRatio.value=g.refractionRatio),g.lightMap&&(b.lightMap.value=g.lightMap,b.lightMapIntensity.value=g.lightMapIntensity,t(g.lightMap,b.lightMapTransform)),g.aoMap&&(b.aoMap.value=g.aoMap,b.aoMapIntensity.value=g.aoMapIntensity,t(g.aoMap,b.aoMapTransform))}function a(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,g.map&&(b.map.value=g.map,t(g.map,b.mapTransform))}function o(b,g){b.dashSize.value=g.dashSize,b.totalSize.value=g.dashSize+g.gapSize,b.scale.value=g.scale}function l(b,g,S,A){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.size.value=g.size*S,b.scale.value=A*.5,g.map&&(b.map.value=g.map,t(g.map,b.uvTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,t(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function c(b,g){b.diffuse.value.copy(g.color),b.opacity.value=g.opacity,b.rotation.value=g.rotation,g.map&&(b.map.value=g.map,t(g.map,b.mapTransform)),g.alphaMap&&(b.alphaMap.value=g.alphaMap,t(g.alphaMap,b.alphaMapTransform)),g.alphaTest>0&&(b.alphaTest.value=g.alphaTest)}function h(b,g){b.specular.value.copy(g.specular),b.shininess.value=Math.max(g.shininess,1e-4)}function d(b,g){g.gradientMap&&(b.gradientMap.value=g.gradientMap)}function f(b,g){b.metalness.value=g.metalness,g.metalnessMap&&(b.metalnessMap.value=g.metalnessMap,t(g.metalnessMap,b.metalnessMapTransform)),b.roughness.value=g.roughness,g.roughnessMap&&(b.roughnessMap.value=g.roughnessMap,t(g.roughnessMap,b.roughnessMapTransform)),g.envMap&&(b.envMapIntensity.value=g.envMapIntensity)}function p(b,g,S){b.ior.value=g.ior,g.sheen>0&&(b.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),b.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(b.sheenColorMap.value=g.sheenColorMap,t(g.sheenColorMap,b.sheenColorMapTransform)),g.sheenRoughnessMap&&(b.sheenRoughnessMap.value=g.sheenRoughnessMap,t(g.sheenRoughnessMap,b.sheenRoughnessMapTransform))),g.clearcoat>0&&(b.clearcoat.value=g.clearcoat,b.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(b.clearcoatMap.value=g.clearcoatMap,t(g.clearcoatMap,b.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(b.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,t(g.clearcoatRoughnessMap,b.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(b.clearcoatNormalMap.value=g.clearcoatNormalMap,t(g.clearcoatNormalMap,b.clearcoatNormalMapTransform),b.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===An&&b.clearcoatNormalScale.value.negate())),g.dispersion>0&&(b.dispersion.value=g.dispersion),g.iridescence>0&&(b.iridescence.value=g.iridescence,b.iridescenceIOR.value=g.iridescenceIOR,b.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],b.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(b.iridescenceMap.value=g.iridescenceMap,t(g.iridescenceMap,b.iridescenceMapTransform)),g.iridescenceThicknessMap&&(b.iridescenceThicknessMap.value=g.iridescenceThicknessMap,t(g.iridescenceThicknessMap,b.iridescenceThicknessMapTransform))),g.transmission>0&&(b.transmission.value=g.transmission,b.transmissionSamplerMap.value=S.texture,b.transmissionSamplerSize.value.set(S.width,S.height),g.transmissionMap&&(b.transmissionMap.value=g.transmissionMap,t(g.transmissionMap,b.transmissionMapTransform)),b.thickness.value=g.thickness,g.thicknessMap&&(b.thicknessMap.value=g.thicknessMap,t(g.thicknessMap,b.thicknessMapTransform)),b.attenuationDistance.value=g.attenuationDistance,b.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(b.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(b.anisotropyMap.value=g.anisotropyMap,t(g.anisotropyMap,b.anisotropyMapTransform))),b.specularIntensity.value=g.specularIntensity,b.specularColor.value.copy(g.specularColor),g.specularColorMap&&(b.specularColorMap.value=g.specularColorMap,t(g.specularColorMap,b.specularColorMapTransform)),g.specularIntensityMap&&(b.specularIntensityMap.value=g.specularIntensityMap,t(g.specularIntensityMap,b.specularIntensityMapTransform))}function x(b,g){g.matcap&&(b.matcap.value=g.matcap)}function y(b,g){let S=e.get(g).light;b.referencePosition.value.setFromMatrixPosition(S.matrixWorld),b.nearDistance.value=S.shadow.camera.near,b.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:r}}function dT(i,e,t,n){let r={},s={},a=[],o=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function l(S,A){let T=A.program;n.uniformBlockBinding(S,T)}function c(S,A){let T=r[S.id];T===void 0&&(x(S),T=h(S),r[S.id]=T,S.addEventListener("dispose",b));let N=A.program;n.updateUBOMapping(S,N);let P=e.render.frame;s[S.id]!==P&&(f(S),s[S.id]=P)}function h(S){let A=d();S.__bindingPointIndex=A;let T=i.createBuffer(),N=S.__size,P=S.usage;return i.bindBuffer(i.UNIFORM_BUFFER,T),i.bufferData(i.UNIFORM_BUFFER,N,P),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,A,T),T}function d(){for(let S=0;S<o;S++)if(a.indexOf(S)===-1)return a.push(S),S;return et("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function f(S){let A=r[S.id],T=S.uniforms,N=S.__cache;i.bindBuffer(i.UNIFORM_BUFFER,A);for(let P=0,U=T.length;P<U;P++){let v=Array.isArray(T[P])?T[P]:[T[P]];for(let I=0,B=v.length;I<B;I++){let k=v[I];if(p(k,P,I,N)===!0){let V=k.__offset,J=Array.isArray(k.value)?k.value:[k.value],L=0;for(let E=0;E<J.length;E++){let D=J[E],O=y(D);typeof D=="number"||typeof D=="boolean"?(k.__data[0]=D,i.bufferSubData(i.UNIFORM_BUFFER,V+L,k.__data)):D.isMatrix3?(k.__data[0]=D.elements[0],k.__data[1]=D.elements[1],k.__data[2]=D.elements[2],k.__data[3]=0,k.__data[4]=D.elements[3],k.__data[5]=D.elements[4],k.__data[6]=D.elements[5],k.__data[7]=0,k.__data[8]=D.elements[6],k.__data[9]=D.elements[7],k.__data[10]=D.elements[8],k.__data[11]=0):ArrayBuffer.isView(D)?k.__data.set(new D.constructor(D.buffer,D.byteOffset,k.__data.length)):(D.toArray(k.__data,L),L+=O.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,V,k.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function p(S,A,T,N){let P=S.value,U=A+"_"+T;if(N[U]===void 0)return typeof P=="number"||typeof P=="boolean"?N[U]=P:ArrayBuffer.isView(P)?N[U]=P.slice():N[U]=P.clone(),!0;{let v=N[U];if(typeof P=="number"||typeof P=="boolean"){if(v!==P)return N[U]=P,!0}else{if(ArrayBuffer.isView(P))return!0;if(v.equals(P)===!1)return v.copy(P),!0}}return!1}function x(S){let A=S.uniforms,T=0,N=16;for(let U=0,v=A.length;U<v;U++){let I=Array.isArray(A[U])?A[U]:[A[U]];for(let B=0,k=I.length;B<k;B++){let V=I[B],J=Array.isArray(V.value)?V.value:[V.value];for(let L=0,E=J.length;L<E;L++){let D=J[L],O=y(D),H=T%N,Y=H%O.boundary,le=H+Y;T+=Y,le!==0&&N-le<O.storage&&(T+=N-le),V.__data=new Float32Array(O.storage/Float32Array.BYTES_PER_ELEMENT),V.__offset=T,T+=O.storage}}}let P=T%N;return P>0&&(T+=N-P),S.__size=T,S.__cache={},this}function y(S){let A={boundary:0,storage:0};return typeof S=="number"||typeof S=="boolean"?(A.boundary=4,A.storage=4):S.isVector2?(A.boundary=8,A.storage=8):S.isVector3||S.isColor?(A.boundary=16,A.storage=12):S.isVector4?(A.boundary=16,A.storage=16):S.isMatrix3?(A.boundary=48,A.storage=48):S.isMatrix4?(A.boundary=64,A.storage=64):S.isTexture?Ke("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(S)?(A.boundary=16,A.storage=S.byteLength):Ke("WebGLRenderer: Unsupported uniform value type.",S),A}function b(S){let A=S.target;A.removeEventListener("dispose",b);let T=a.indexOf(A.__bindingPointIndex);a.splice(T,1),i.deleteBuffer(r[A.id]),delete r[A.id],delete s[A.id]}function g(){for(let S in r)i.deleteBuffer(r[S]);a=[],r={},s={}}return{bind:l,update:c,dispose:g}}function pT(){return Zi===null&&(Zi=new xs(fT,16,16,Xr,Gn),Zi.name="DFG_LUT",Zi.minFilter=zt,Zi.magFilter=zt,Zi.wrapS=Kn,Zi.wrapT=Kn,Zi.generateMipmaps=!1,Zi.needsUpdate=!0),Zi}var CS,IS,PS,LS,DS,NS,OS,FS,US,kS,BS,zS,HS,GS,VS,WS,qS,$S,jS,XS,KS,YS,JS,ZS,QS,ew,tw,nw,iw,rw,sw,aw,ow,cw,lw,hw,uw,dw,fw,pw,mw,gw,bw,xw,_w,yw,vw,Sw,ww,Mw,Aw,Tw,Ew,Rw,Cw,Iw,Pw,Lw,Dw,Nw,Ow,Fw,Uw,kw,Bw,zw,Hw,Gw,Vw,Ww,qw,$w,jw,Xw,Kw,Yw,Jw,Zw,Qw,e1,t1,n1,i1,r1,s1,a1,o1,c1,l1,h1,u1,d1,f1,p1,m1,g1,b1,x1,_1,y1,v1,S1,w1,M1,A1,T1,E1,R1,C1,I1,P1,L1,D1,N1,O1,F1,U1,k1,B1,z1,H1,G1,V1,W1,q1,$1,j1,X1,K1,Y1,J1,Z1,Q1,eM,tM,nM,iM,rM,sM,aM,oM,cM,ft,Ue,Qi,xh,lM,nb,Kr,D0,Rs,mM,zo,N0,Qd,ef,tf,nf,gM,wa,Ma,EM,ib,af,rb,sb,ab,k0,B0,z0,H0,G0,of,cf,lf,rf,Sa,gA,bA,q0,vA,_h,EA,RA,IA,LA,NA,FA,kA,GA,uf,df,YA,eT,tT,nT,iT,eb,Ho,sf,cT,lT,ff,pf,hT,ob,fT,Zi,yh,Vn=un(()=>{Zd();Zd();CS=`#ifdef USE_ALPHAHASH
+ if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
+#endif`,IS=`#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`,PS=`#ifdef USE_ALPHAMAP
+ diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
+#endif`,LS=`#ifdef USE_ALPHAMAP
+ uniform sampler2D alphaMap;
+#endif`,DS=`#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`,NS=`#ifdef USE_ALPHATEST
+ uniform float alphaTest;
+#endif`,OS=`#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`,FS=`#ifdef USE_AOMAP
+ uniform sampler2D aoMap;
+ uniform float aoMapIntensity;
+#endif`,US=`#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`,kS=`#ifdef USE_BATCHING
+ mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
+#endif`,BS=`vec3 transformed = vec3( position );
+#ifdef USE_ALPHAHASH
+ vPosition = vec3( position );
+#endif`,zS=`vec3 objectNormal = vec3( normal );
+#ifdef USE_TANGENT
+ vec3 objectTangent = vec3( tangent.xyz );
+#endif`,HS=`float G_BlinnPhong_Implicit( ) {
+ return 0.25;
+}
+float D_BlinnPhong( const in float shininess, const in float dotNH ) {
+ return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
+}
+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`,GS=`#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`,VS=`#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`,WS=`#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`,qS=`#if NUM_CLIPPING_PLANES > 0
+ varying vec3 vClipPosition;
+ uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
+#endif`,$S=`#if NUM_CLIPPING_PLANES > 0
+ varying vec3 vClipPosition;
+#endif`,jS=`#if NUM_CLIPPING_PLANES > 0
+ vClipPosition = - mvPosition.xyz;
+#endif`,XS=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
+ diffuseColor *= vColor;
+#endif`,KS=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
+ varying vec4 vColor;
+#endif`,YS=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
+ varying vec4 vColor;
+#endif`,JS=`#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`,ZS=`#define PI 3.141592653589793
+#define PI2 6.283185307179586
+#define PI_HALF 1.5707963267948966
+#define RECIPROCAL_PI 0.3183098861837907
+#define RECIPROCAL_PI2 0.15915494309189535
+#define EPSILON 1e-6
+#ifndef saturate
+#define saturate( a ) clamp( a, 0.0, 1.0 )
+#endif
+#define whiteComplement( a ) ( 1.0 - saturate( a ) )
+float pow2( const in float x ) { return x*x; }
+vec3 pow2( const in vec3 x ) { return x*x; }
+float pow3( const in float x ) { return x*x*x; }
+float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
+float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
+float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
+highp float rand( const in vec2 uv ) {
+ const highp float a = 12.9898, b = 78.233, c = 43758.5453;
+ highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
+ return fract( sin( sn ) * c );
+}
+#ifdef HIGH_PRECISION
+ float precisionSafeLength( vec3 v ) { return length( v ); }
+#else
+ float precisionSafeLength( vec3 v ) {
+ float maxComponent = max3( abs( v ) );
+ return length( v / maxComponent ) * maxComponent;
+ }
+#endif
+struct IncidentLight {
+ vec3 color;
+ vec3 direction;
+ bool visible;
+};
+struct ReflectedLight {
+ vec3 directDiffuse;
+ vec3 directSpecular;
+ vec3 indirectDiffuse;
+ vec3 indirectSpecular;
+};
+#ifdef USE_ALPHAHASH
+ varying vec3 vPosition;
+#endif
+vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
+ return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
+}
+vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
+ return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
+}
+bool isPerspectiveMatrix( mat4 m ) {
+ return m[ 2 ][ 3 ] == - 1.0;
+}
+vec2 equirectUv( in vec3 dir ) {
+ float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
+ float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
+ return vec2( u, v );
+}
+vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
+ return RECIPROCAL_PI * diffuseColor;
+}
+vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
+ float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
+ return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
+}
+float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
+ float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
+ return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
+} // validated`,QS=`#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`,ew=`vec3 transformedNormal = objectNormal;
+#ifdef USE_TANGENT
+ vec3 transformedTangent = objectTangent;
+#endif
+#ifdef USE_BATCHING
+ mat3 bm = mat3( batchingMatrix );
+ transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
+ transformedNormal = bm * transformedNormal;
+ #ifdef USE_TANGENT
+ transformedTangent = bm * transformedTangent;
+ #endif
+#endif
+#ifdef USE_INSTANCING
+ mat3 im = mat3( instanceMatrix );
+ transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
+ transformedNormal = im * transformedNormal;
+ #ifdef USE_TANGENT
+ transformedTangent = im * transformedTangent;
+ #endif
+#endif
+transformedNormal = normalMatrix * transformedNormal;
+#ifdef FLIP_SIDED
+ transformedNormal = - transformedNormal;
+#endif
+#ifdef USE_TANGENT
+ transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
+ #ifdef FLIP_SIDED
+ transformedTangent = - transformedTangent;
+ #endif
+#endif`,tw=`#ifdef USE_DISPLACEMENTMAP
+ uniform sampler2D displacementMap;
+ uniform float displacementScale;
+ uniform float displacementBias;
+#endif`,nw=`#ifdef USE_DISPLACEMENTMAP
+ transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
+#endif`,iw=`#ifdef USE_EMISSIVEMAP
+ vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
+ #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
+ emissiveColor = sRGBTransferEOTF( emissiveColor );
+ #endif
+ totalEmissiveRadiance *= emissiveColor.rgb;
+#endif`,rw=`#ifdef USE_EMISSIVEMAP
+ uniform sampler2D emissiveMap;
+#endif`,sw="gl_FragColor = linearToOutputTexel( gl_FragColor );",aw=`vec4 LinearTransferOETF( in vec4 value ) {
+ return value;
+}
+vec4 sRGBTransferEOTF( in vec4 value ) {
+ return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
+}
+vec4 sRGBTransferOETF( in vec4 value ) {
+ return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
+}`,ow=`#ifdef USE_ENVMAP
+ #ifdef ENV_WORLDPOS
+ vec3 cameraToFrag;
+ if ( isOrthographic ) {
+ cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
+ } else {
+ cameraToFrag = normalize( vWorldPosition - cameraPosition );
+ }
+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
+ #ifdef ENVMAP_MODE_REFLECTION
+ vec3 reflectVec = reflect( cameraToFrag, worldNormal );
+ #else
+ vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
+ #endif
+ #else
+ vec3 reflectVec = vReflect;
+ #endif
+ #ifdef ENVMAP_TYPE_CUBE
+ vec4 envColor = textureCube( envMap, envMapRotation * 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`,cw=`#ifdef USE_ENVMAP
+ uniform float envMapIntensity;
+ uniform mat3 envMapRotation;
+ #ifdef ENVMAP_TYPE_CUBE
+ uniform samplerCube envMap;
+ #else
+ uniform sampler2D envMap;
+ #endif
+#endif`,lw=`#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`,hw=`#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`,uw=`#ifdef USE_ENVMAP
+ #ifdef ENV_WORLDPOS
+ vWorldPosition = worldPosition.xyz;
+ #else
+ vec3 cameraToVertex;
+ if ( isOrthographic ) {
+ cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
+ } else {
+ cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
+ }
+ vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
+ #ifdef ENVMAP_MODE_REFLECTION
+ vReflect = reflect( cameraToVertex, worldNormal );
+ #else
+ vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
+ #endif
+ #endif
+#endif`,dw=`#ifdef USE_FOG
+ vFogDepth = - mvPosition.z;
+#endif`,fw=`#ifdef USE_FOG
+ varying float vFogDepth;
+#endif`,pw=`#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`,mw=`#ifdef USE_FOG
+ uniform vec3 fogColor;
+ varying float vFogDepth;
+ #ifdef FOG_EXP2
+ uniform float fogDensity;
+ #else
+ uniform float fogNear;
+ uniform float fogFar;
+ #endif
+#endif`,gw=`#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
+}`,bw=`#ifdef USE_LIGHTMAP
+ uniform sampler2D lightMap;
+ uniform float lightMapIntensity;
+#endif`,xw=`LambertMaterial material;
+material.diffuseColor = diffuseColor.rgb;
+material.specularStrength = specularStrength;`,_w=`varying vec3 vViewPosition;
+struct LambertMaterial {
+ vec3 diffuseColor;
+ float specularStrength;
+};
+void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
+ vec3 irradiance = dotNL * directLight.color;
+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+#define RE_Direct RE_Direct_Lambert
+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,yw=`uniform bool receiveShadow;
+uniform vec3 ambientLightColor;
+#if defined( USE_LIGHT_PROBES )
+ uniform vec3 lightProbe[ 9 ];
+#endif
+vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
+ float x = normal.x, y = normal.y, z = normal.z;
+ vec3 result = shCoefficients[ 0 ] * 0.886227;
+ result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
+ result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
+ result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
+ result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
+ result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
+ result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
+ result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
+ result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
+ return result;
+}
+vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
+ vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
+ return irradiance;
+}
+vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
+ vec3 irradiance = ambientLightColor;
+ return irradiance;
+}
+float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
+ float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
+ if ( cutoffDistance > 0.0 ) {
+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
+ }
+ return distanceFalloff;
+}
+float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
+ return smoothstep( coneCosine, penumbraCosine, angleCosine );
+}
+#if NUM_DIR_LIGHTS > 0
+ struct DirectionalLight {
+ vec3 direction;
+ vec3 color;
+ };
+ uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
+ void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
+ light.color = directionalLight.color;
+ light.direction = directionalLight.direction;
+ light.visible = true;
+ }
+#endif
+#if NUM_POINT_LIGHTS > 0
+ struct PointLight {
+ vec3 position;
+ vec3 color;
+ float distance;
+ float decay;
+ };
+ uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
+ void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
+ vec3 lVector = pointLight.position - geometryPosition;
+ light.direction = normalize( lVector );
+ float lightDistance = length( lVector );
+ light.color = pointLight.color;
+ light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
+ light.visible = ( light.color != vec3( 0.0 ) );
+ }
+#endif
+#if NUM_SPOT_LIGHTS > 0
+ struct SpotLight {
+ vec3 position;
+ vec3 direction;
+ vec3 color;
+ float distance;
+ float decay;
+ float coneCos;
+ float penumbraCos;
+ };
+ uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
+ void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
+ vec3 lVector = spotLight.position - geometryPosition;
+ light.direction = normalize( lVector );
+ float angleCos = dot( light.direction, spotLight.direction );
+ float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
+ if ( spotAttenuation > 0.0 ) {
+ float lightDistance = length( lVector );
+ light.color = spotLight.color * spotAttenuation;
+ light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
+ light.visible = ( light.color != vec3( 0.0 ) );
+ } else {
+ light.color = vec3( 0.0 );
+ light.visible = false;
+ }
+ }
+#endif
+#if NUM_RECT_AREA_LIGHTS > 0
+ struct RectAreaLight {
+ vec3 color;
+ vec3 position;
+ vec3 halfWidth;
+ vec3 halfHeight;
+ };
+ uniform sampler2D ltc_1; uniform sampler2D ltc_2;
+ uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
+#endif
+#if NUM_HEMI_LIGHTS > 0
+ struct HemisphereLight {
+ vec3 direction;
+ vec3 skyColor;
+ vec3 groundColor;
+ };
+ uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
+ vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
+ float dotNL = dot( normal, hemiLight.direction );
+ float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
+ vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
+ return irradiance;
+ }
+#endif
+#include <lightprobes_pars_fragment>`,vw=`#ifdef USE_ENVMAP
+ vec3 getIBLIrradiance( const in vec3 normal ) {
+ #ifdef ENVMAP_TYPE_CUBE_UV
+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
+ return PI * envMapColor.rgb * envMapIntensity;
+ #else
+ return vec3( 0.0 );
+ #endif
+ }
+ vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
+ #ifdef ENVMAP_TYPE_CUBE_UV
+ vec3 reflectVec = reflect( - viewDir, normal );
+ reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );
+ reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
+ return envMapColor.rgb * envMapIntensity;
+ #else
+ return vec3( 0.0 );
+ #endif
+ }
+ #ifdef USE_ANISOTROPY
+ vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
+ #ifdef ENVMAP_TYPE_CUBE_UV
+ vec3 bentNormal = cross( bitangent, viewDir );
+ bentNormal = normalize( cross( bentNormal, bitangent ) );
+ bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
+ return getIBLRadiance( viewDir, bentNormal, roughness );
+ #else
+ return vec3( 0.0 );
+ #endif
+ }
+ #endif
+#endif`,Sw=`ToonMaterial material;
+material.diffuseColor = diffuseColor.rgb;`,ww=`varying vec3 vViewPosition;
+struct ToonMaterial {
+ vec3 diffuseColor;
+};
+void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
+ vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+#define RE_Direct RE_Direct_Toon
+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Mw=`BlinnPhongMaterial material;
+material.diffuseColor = diffuseColor.rgb;
+material.specularColor = specular;
+material.specularShininess = shininess;
+material.specularStrength = specularStrength;`,Aw=`varying vec3 vViewPosition;
+struct BlinnPhongMaterial {
+ vec3 diffuseColor;
+ vec3 specularColor;
+ float specularShininess;
+ float specularStrength;
+};
+void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
+ vec3 irradiance = dotNL * directLight.color;
+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+ reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
+}
+void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+#define RE_Direct RE_Direct_BlinnPhong
+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,Tw=`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_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`,Ew=`uniform sampler2D dfgLUT;
+struct PhysicalMaterial {
+ vec3 diffuseColor;
+ vec3 diffuseContribution;
+ vec3 specularColor;
+ vec3 specularColorBlended;
+ float roughness;
+ float metalness;
+ float specularF90;
+ float dispersion;
+ #ifdef USE_CLEARCOAT
+ float clearcoat;
+ float clearcoatRoughness;
+ vec3 clearcoatF0;
+ float clearcoatF90;
+ #endif
+ #ifdef USE_IRIDESCENCE
+ float iridescence;
+ float iridescenceIOR;
+ float iridescenceThickness;
+ vec3 iridescenceFresnel;
+ vec3 iridescenceF0;
+ vec3 iridescenceFresnelDielectric;
+ vec3 iridescenceFresnelMetallic;
+ #endif
+ #ifdef USE_SHEEN
+ vec3 sheenColor;
+ float sheenRoughness;
+ #endif
+ #ifdef IOR
+ float ior;
+ #endif
+ #ifdef USE_TRANSMISSION
+ float transmission;
+ float transmissionAlpha;
+ float thickness;
+ float attenuationDistance;
+ vec3 attenuationColor;
+ #endif
+ #ifdef USE_ANISOTROPY
+ float anisotropy;
+ float alphaT;
+ vec3 anisotropyT;
+ vec3 anisotropyB;
+ #endif
+};
+vec3 clearcoatSpecularDirect = vec3( 0.0 );
+vec3 clearcoatSpecularIndirect = vec3( 0.0 );
+vec3 sheenSpecularDirect = vec3( 0.0 );
+vec3 sheenSpecularIndirect = vec3(0.0 );
+vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
+ float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
+ float x2 = x * x;
+ float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
+ return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
+}
+float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
+ float a2 = pow2( alpha );
+ float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
+ float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
+ return 0.5 / max( gv + gl, EPSILON );
+}
+float D_GGX( const in float alpha, const in float dotNH ) {
+ float a2 = pow2( alpha );
+ float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
+ return RECIPROCAL_PI * a2 / pow2( denom );
+}
+#ifdef USE_ANISOTROPY
+ float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
+ float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
+ float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
+ 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 );
+}
+vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
+ const float LUT_SIZE = 64.0;
+ const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
+ const float LUT_BIAS = 0.5 / LUT_SIZE;
+ float dotNV = saturate( dot( N, V ) );
+ vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
+ uv = uv * LUT_SCALE + LUT_BIAS;
+ return uv;
+}
+float LTC_ClippedSphereFormFactor( const in vec3 f ) {
+ float l = length( f );
+ return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
+}
+vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
+ float x = dot( v1, v2 );
+ float y = abs( x );
+ float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
+ float b = 3.4175940 + ( 4.1616724 + y ) * y;
+ float v = a / b;
+ float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
+ return cross( v1, v2 ) * theta_sintheta;
+}
+vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
+ vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
+ vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
+ vec3 lightNormal = cross( v1, v2 );
+ if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
+ vec3 T1, T2;
+ T1 = normalize( V - N * dot( V, N ) );
+ T2 = - cross( N, T1 );
+ mat3 mat = mInv * 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 );
+}
+#if defined( USE_SHEEN )
+float D_Charlie( float roughness, float dotNH ) {
+ float alpha = pow2( roughness );
+ float invAlpha = 1.0 / alpha;
+ float cos2h = dotNH * dotNH;
+ float sin2h = max( 1.0 - cos2h, 0.0078125 );
+ return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
+}
+float V_Neubelt( float dotNV, float dotNL ) {
+ return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
+}
+vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
+ vec3 halfDir = normalize( lightDir + viewDir );
+ float dotNL = saturate( dot( normal, lightDir ) );
+ float dotNV = saturate( dot( normal, viewDir ) );
+ float dotNH = saturate( dot( normal, halfDir ) );
+ float D = D_Charlie( sheenRoughness, dotNH );
+ float V = V_Neubelt( dotNV, dotNL );
+ return sheenColor * ( D * V );
+}
+#endif
+float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
+ float dotNV = saturate( dot( normal, viewDir ) );
+ float r2 = roughness * roughness;
+ float 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 );
+}
+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;
+}
+#ifdef USE_IRIDESCENCE
+void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
+#else
+void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
+#endif
+ float dotNV = saturate( dot( normal, viewDir ) );
+ vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;
+ #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;
+}
+vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
+ vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
+ float dotNL = saturate( dot( normal, lightDir ) );
+ float dotNV = saturate( dot( normal, viewDir ) );
+ vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;
+ vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;
+ vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;
+ vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;
+ float Ess_V = dfgV.x + dfgV.y;
+ float Ess_L = dfgL.x + dfgL.y;
+ float Ems_V = 1.0 - Ess_V;
+ float Ems_L = 1.0 - Ess_L;
+ vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;
+ vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );
+ float compensationFactor = Ems_V * Ems_L;
+ vec3 multiScatter = Fms * compensationFactor;
+ return singleScatter + multiScatter;
+}
+#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
+ reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );
+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );
+}
+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 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );
+ #ifdef USE_SHEEN
+ float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
+ float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;
+ diffuse *= sheenEnergyComp;
+ #endif
+ reflectedLight.indirectDiffuse += diffuse;
+}
+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( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
+ computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );
+ #else
+ computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
+ computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, 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;
+}
+#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 );
+}`,Rw=`
+vec3 geometryPosition = - vViewPosition;
+vec3 geometryNormal = normal;
+vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
+vec3 geometryClearcoatNormal = vec3( 0.0 );
+#ifdef USE_CLEARCOAT
+ geometryClearcoatNormal = clearcoatNormal;
+#endif
+#ifdef USE_IRIDESCENCE
+ float dotNVi = saturate( dot( normal, geometryViewDir ) );
+ if ( material.iridescenceThickness == 0.0 ) {
+ material.iridescence = 0.0;
+ } else {
+ material.iridescence = saturate( material.iridescence );
+ }
+ if ( material.iridescence > 0.0 ) {
+ material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
+ material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );
+ material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );
+ material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
+ }
+#endif
+IncidentLight directLight;
+#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
+ PointLight pointLight;
+ #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
+ PointLightShadow pointLightShadow;
+ #endif
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
+ pointLight = pointLights[ i ];
+ getPointLightInfo( pointLight, geometryPosition, directLight );
+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( 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_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 = inverseTransformDirection( geometryNormal, viewMatrix );
+ irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );
+ #endif
+#endif
+#if defined( RE_IndirectSpecular )
+ vec3 radiance = vec3( 0.0 );
+ vec3 clearcoatRadiance = vec3( 0.0 );
+#endif`,Cw=`#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
+ radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
+ #else
+ radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
+ #endif
+ #ifdef USE_CLEARCOAT
+ clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
+ #endif
+#endif`,Iw=`#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`,Pw=`#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 ) );
+}
+#endif`,Lw=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
+ gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
+#endif`,Dw=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
+ uniform float logDepthBufFC;
+ varying float vFragDepth;
+ varying float vIsPerspective;
+#endif`,Nw=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
+ varying float vFragDepth;
+ varying float vIsPerspective;
+#endif`,Ow=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
+ vFragDepth = 1.0 + gl_Position.w;
+ vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
+#endif`,Fw=`#ifdef USE_MAP
+ vec4 sampledDiffuseColor = texture2D( map, vMapUv );
+ #ifdef DECODE_VIDEO_TEXTURE
+ sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
+ #endif
+ diffuseColor *= sampledDiffuseColor;
+#endif`,Uw=`#ifdef USE_MAP
+ uniform sampler2D map;
+#endif`,kw=`#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`,Bw=`#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`,zw=`float metalnessFactor = metalness;
+#ifdef USE_METALNESSMAP
+ vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
+ metalnessFactor *= texelMetalness.b;
+#endif`,Hw=`#ifdef USE_METALNESSMAP
+ uniform sampler2D metalnessMap;
+#endif`,Gw=`#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`,Vw=`#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`,Ww=`#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`,qw=`#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`,$w=`#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`,jw=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
+#ifdef FLAT_SHADED
+ vec3 fdx = dFdx( vViewPosition );
+ vec3 fdy = dFdy( vViewPosition );
+ vec3 normal = normalize( cross( fdx, fdy ) );
+#else
+ vec3 normal = normalize( vNormal );
+ #ifdef DOUBLE_SIDED
+ normal *= faceDirection;
+ #endif
+#endif
+#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
+ #ifdef USE_TANGENT
+ mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
+ #else
+ mat3 tbn = getTangentFrame( - vViewPosition, normal,
+ #if defined( USE_NORMALMAP )
+ vNormalMapUv
+ #elif defined( USE_CLEARCOAT_NORMALMAP )
+ vClearcoatNormalMapUv
+ #else
+ vUv
+ #endif
+ );
+ #endif
+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
+ tbn[0] *= faceDirection;
+ tbn[1] *= faceDirection;
+ #endif
+#endif
+#ifdef USE_CLEARCOAT_NORMALMAP
+ #ifdef USE_TANGENT
+ mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
+ #else
+ mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
+ #endif
+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
+ tbn2[0] *= faceDirection;
+ tbn2[1] *= faceDirection;
+ #endif
+#endif
+vec3 nonPerturbedNormal = normal;`,Xw=`#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`,Kw=`#ifndef FLAT_SHADED
+ varying vec3 vNormal;
+ #ifdef USE_TANGENT
+ varying vec3 vTangent;
+ varying vec3 vBitangent;
+ #endif
+#endif`,Yw=`#ifndef FLAT_SHADED
+ varying vec3 vNormal;
+ #ifdef USE_TANGENT
+ varying vec3 vTangent;
+ varying vec3 vBitangent;
+ #endif
+#endif`,Jw=`#ifndef FLAT_SHADED
+ vNormal = normalize( transformedNormal );
+ #ifdef USE_TANGENT
+ vTangent = normalize( transformedTangent );
+ vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
+ #endif
+#endif`,Zw=`#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`,Qw=`#ifdef USE_CLEARCOAT
+ vec3 clearcoatNormal = nonPerturbedNormal;
+#endif`,e1=`#ifdef USE_CLEARCOAT_NORMALMAP
+ vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
+ clearcoatMapN.xy *= clearcoatNormalScale;
+ clearcoatNormal = normalize( tbn2 * clearcoatMapN );
+#endif`,t1=`#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`,n1=`#ifdef USE_IRIDESCENCEMAP
+ uniform sampler2D iridescenceMap;
+#endif
+#ifdef USE_IRIDESCENCE_THICKNESSMAP
+ uniform sampler2D iridescenceThicknessMap;
+#endif`,i1=`#ifdef OPAQUE
+diffuseColor.a = 1.0;
+#endif
+#ifdef USE_TRANSMISSION
+diffuseColor.a *= material.transmissionAlpha;
+#endif
+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,r1=`vec3 packNormalToRGB( const in vec3 normal ) {
+ return normalize( normal ) * 0.5 + 0.5;
+}
+vec3 unpackRGBToNormal( const in vec3 rgb ) {
+ return 2.0 * rgb.xyz - 1.0;
+}
+const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
+const float Inv255 = 1. / 255.;
+const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
+const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
+const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
+const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
+vec4 packDepthToRGBA( const in float v ) {
+ if( v <= 0.0 )
+ return vec4( 0., 0., 0., 0. );
+ if( v >= 1.0 )
+ return vec4( 1., 1., 1., 1. );
+ float vuf;
+ float af = modf( v * PackFactors.a, vuf );
+ float bf = modf( vuf * ShiftRight8, vuf );
+ float gf = modf( vuf * ShiftRight8, vuf );
+ return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
+}
+vec3 packDepthToRGB( const in float v ) {
+ if( v <= 0.0 )
+ return vec3( 0., 0., 0. );
+ if( v >= 1.0 )
+ return vec3( 1., 1., 1. );
+ float vuf;
+ float bf = modf( v * PackFactors.b, vuf );
+ float gf = modf( vuf * ShiftRight8, vuf );
+ return vec3( vuf * Inv255, gf * PackUpscale, bf );
+}
+vec2 packDepthToRG( const in float v ) {
+ if( v <= 0.0 )
+ return vec2( 0., 0. );
+ if( v >= 1.0 )
+ return vec2( 1., 1. );
+ float vuf;
+ float gf = modf( v * 256., vuf );
+ return vec2( vuf * Inv255, gf );
+}
+float unpackRGBAToDepth( const in vec4 v ) {
+ return dot( v, UnpackFactors4 );
+}
+float unpackRGBToDepth( const in vec3 v ) {
+ return dot( v, UnpackFactors3 );
+}
+float unpackRGToDepth( const in vec2 v ) {
+ return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
+}
+vec4 pack2HalfToRGBA( const in vec2 v ) {
+ vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
+ return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
+}
+vec2 unpackRGBATo2Half( const in vec4 v ) {
+ return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
+}
+float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
+ return ( viewZ + near ) / ( near - far );
+}
+float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
+ #ifdef USE_REVERSED_DEPTH_BUFFER
+
+ return depth * ( far - near ) - far;
+ #else
+ return depth * ( near - far ) - near;
+ #endif
+}
+float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
+ return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
+}
+float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
+
+ #ifdef USE_REVERSED_DEPTH_BUFFER
+ return ( near * far ) / ( ( near - far ) * depth - near );
+ #else
+ return ( near * far ) / ( ( far - near ) * depth - far );
+ #endif
+}`,s1=`#ifdef PREMULTIPLIED_ALPHA
+ gl_FragColor.rgb *= gl_FragColor.a;
+#endif`,a1=`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;`,o1=`#ifdef DITHERING
+ gl_FragColor.rgb = dithering( gl_FragColor.rgb );
+#endif`,c1=`#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`,l1=`float roughnessFactor = roughness;
+#ifdef USE_ROUGHNESSMAP
+ vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
+ roughnessFactor *= texelRoughness.g;
+#endif`,h1=`#ifdef USE_ROUGHNESSMAP
+ uniform sampler2D roughnessMap;
+#endif`,u1=`#if NUM_SPOT_LIGHT_COORDS > 0
+ varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
+#endif
+#if NUM_SPOT_LIGHT_MAPS > 0
+ uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
+#endif
+#ifdef USE_SHADOWMAP
+ #if NUM_DIR_LIGHT_SHADOWS > 0
+ #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_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`,d1=`#if NUM_SPOT_LIGHT_COORDS > 0
+ uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
+ varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
+#endif
+#ifdef USE_SHADOWMAP
+ #if NUM_DIR_LIGHT_SHADOWS > 0
+ uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
+ varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
+ struct DirectionalLightShadow {
+ float shadowIntensity;
+ float shadowBias;
+ float shadowNormalBias;
+ float shadowRadius;
+ vec2 shadowMapSize;
+ };
+ uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
+ #endif
+ #if NUM_SPOT_LIGHT_SHADOWS > 0
+ struct SpotLightShadow {
+ float shadowIntensity;
+ float shadowBias;
+ float shadowNormalBias;
+ float shadowRadius;
+ vec2 shadowMapSize;
+ };
+ uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
+ #endif
+ #if NUM_POINT_LIGHT_SHADOWS > 0
+ uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
+ varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
+ struct PointLightShadow {
+ float shadowIntensity;
+ float shadowBias;
+ float shadowNormalBias;
+ float shadowRadius;
+ vec2 shadowMapSize;
+ float shadowCameraNear;
+ float shadowCameraFar;
+ };
+ uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
+ #endif
+#endif`,f1=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
+ #ifdef HAS_NORMAL
+ vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
+ #else
+ vec3 shadowWorldNormal = vec3( 0.0 );
+ #endif
+ vec4 shadowWorldPosition;
+#endif
+#if defined( USE_SHADOWMAP )
+ #if NUM_DIR_LIGHT_SHADOWS > 0
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
+ shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
+ vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
+ }
+ #pragma unroll_loop_end
+ #endif
+ #if NUM_POINT_LIGHT_SHADOWS > 0
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
+ shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
+ vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
+ }
+ #pragma unroll_loop_end
+ #endif
+#endif
+#if NUM_SPOT_LIGHT_COORDS > 0
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
+ shadowWorldPosition = worldPosition;
+ #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
+ shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
+ #endif
+ vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
+ }
+ #pragma unroll_loop_end
+#endif`,p1=`float getShadowMask() {
+ float shadow = 1.0;
+ #ifdef USE_SHADOWMAP
+ #if NUM_DIR_LIGHT_SHADOWS > 0
+ DirectionalLightShadow directionalLight;
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
+ directionalLight = directionalLightShadows[ i ];
+ shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
+ }
+ #pragma unroll_loop_end
+ #endif
+ #if NUM_SPOT_LIGHT_SHADOWS > 0
+ SpotLightShadow spotLight;
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
+ spotLight = spotLightShadows[ i ];
+ shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
+ }
+ #pragma unroll_loop_end
+ #endif
+ #if NUM_POINT_LIGHT_SHADOWS > 0 && ( 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;
+}`,m1=`#ifdef USE_SKINNING
+ mat4 boneMatX = getBoneMatrix( skinIndex.x );
+ mat4 boneMatY = getBoneMatrix( skinIndex.y );
+ mat4 boneMatZ = getBoneMatrix( skinIndex.z );
+ mat4 boneMatW = getBoneMatrix( skinIndex.w );
+#endif`,g1=`#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`,b1=`#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`,x1=`#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`,_1=`float specularStrength;
+#ifdef USE_SPECULARMAP
+ vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
+ specularStrength = texelSpecular.r;
+#else
+ specularStrength = 1.0;
+#endif`,y1=`#ifdef USE_SPECULARMAP
+ uniform sampler2D specularMap;
+#endif`,v1=`#if defined( TONE_MAPPING )
+ gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
+#endif`,S1=`#ifndef saturate
+#define saturate( a ) clamp( a, 0.0, 1.0 )
+#endif
+uniform float toneMappingExposure;
+vec3 LinearToneMapping( vec3 color ) {
+ return saturate( toneMappingExposure * color );
+}
+vec3 ReinhardToneMapping( vec3 color ) {
+ color *= toneMappingExposure;
+ return saturate( color / ( vec3( 1.0 ) + color ) );
+}
+vec3 CineonToneMapping( vec3 color ) {
+ color *= toneMappingExposure;
+ color = max( vec3( 0.0 ), color - 0.004 );
+ return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
+}
+vec3 RRTAndODTFit( vec3 v ) {
+ vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
+ vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
+ return a / b;
+}
+vec3 ACESFilmicToneMapping( vec3 color ) {
+ const mat3 ACESInputMat = mat3(
+ vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
+ vec3( 0.04823, 0.01566, 0.83777 )
+ );
+ const mat3 ACESOutputMat = mat3(
+ vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
+ vec3( -0.07367, -0.00605, 1.07602 )
+ );
+ color *= toneMappingExposure / 0.6;
+ color = ACESInputMat * color;
+ color = RRTAndODTFit( color );
+ color = ACESOutputMat * color;
+ return saturate( color );
+}
+const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
+ vec3( 1.6605, - 0.1246, - 0.0182 ),
+ vec3( - 0.5876, 1.1329, - 0.1006 ),
+ vec3( - 0.0728, - 0.0083, 1.1187 )
+);
+const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
+ vec3( 0.6274, 0.0691, 0.0164 ),
+ vec3( 0.3293, 0.9195, 0.0880 ),
+ vec3( 0.0433, 0.0113, 0.8956 )
+);
+vec3 agxDefaultContrastApprox( vec3 x ) {
+ vec3 x2 = x * x;
+ vec3 x4 = x2 * x2;
+ return + 15.5 * x4 * x2
+ - 40.14 * x4 * x
+ + 31.96 * x4
+ - 6.868 * x2 * x
+ + 0.4298 * x2
+ + 0.1191 * x
+ - 0.00232;
+}
+vec3 AgXToneMapping( vec3 color ) {
+ const mat3 AgXInsetMatrix = mat3(
+ vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
+ vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
+ vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
+ );
+ const mat3 AgXOutsetMatrix = mat3(
+ vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
+ vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
+ vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
+ );
+ const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;
+ color *= toneMappingExposure;
+ color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
+ color = AgXInsetMatrix * color;
+ color = max( color, 1e-10 ); color = log2( color );
+ color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
+ color = clamp( color, 0.0, 1.0 );
+ color = agxDefaultContrastApprox( color );
+ color = AgXOutsetMatrix * color;
+ color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
+ color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
+ color = clamp( color, 0.0, 1.0 );
+ return color;
+}
+vec3 NeutralToneMapping( vec3 color ) {
+ const float StartCompression = 0.8 - 0.04;
+ const float Desaturation = 0.15;
+ color *= toneMappingExposure;
+ float x = min( color.r, min( color.g, color.b ) );
+ float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
+ color -= offset;
+ float peak = max( color.r, max( color.g, color.b ) );
+ if ( peak < StartCompression ) return color;
+ float d = 1. - StartCompression;
+ float newPeak = 1. - d * d / ( peak + d - StartCompression );
+ color *= newPeak / peak;
+ float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
+ return mix( color, vec3( newPeak ), g );
+}
+vec3 CustomToneMapping( vec3 color ) { return color; }`,w1=`#ifdef USE_TRANSMISSION
+ material.transmission = transmission;
+ material.transmissionAlpha = 1.0;
+ material.thickness = thickness;
+ material.attenuationDistance = attenuationDistance;
+ material.attenuationColor = attenuationColor;
+ #ifdef USE_TRANSMISSIONMAP
+ material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
+ #endif
+ #ifdef USE_THICKNESSMAP
+ material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
+ #endif
+ vec3 pos = vWorldPosition;
+ vec3 v = normalize( cameraPosition - pos );
+ vec3 n = inverseTransformDirection( normal, viewMatrix );
+ vec4 transmitted = getIBLVolumeRefraction(
+ n, v, material.roughness, material.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`,M1=`#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`,A1=`#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`,T1=`#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`,E1=`#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`,R1=`#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`,C1=`varying vec2 vUv;
+uniform mat3 uvTransform;
+void main() {
+ vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
+ gl_Position = vec4( position.xy, 1.0, 1.0 );
+}`,I1=`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>
+}`,P1=`varying vec3 vWorldDirection;
+#include <common>
+void main() {
+ vWorldDirection = transformDirection( position, modelMatrix );
+ #include <begin_vertex>
+ #include <project_vertex>
+ gl_Position.z = gl_Position.w;
+}`,L1=`#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>
+}`,D1=`varying vec3 vWorldDirection;
+#include <common>
+void main() {
+ vWorldDirection = transformDirection( position, modelMatrix );
+ #include <begin_vertex>
+ #include <project_vertex>
+ gl_Position.z = gl_Position.w;
+}`,N1=`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>
+}`,O1=`#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;
+}`,F1=`#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
+}`,U1=`#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;
+}`,k1=`#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 );
+}`,B1=`varying vec3 vWorldDirection;
+#include <common>
+void main() {
+ vWorldDirection = transformDirection( position, modelMatrix );
+ #include <begin_vertex>
+ #include <project_vertex>
+}`,z1=`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>
+}`,H1=`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>
+}`,G1=`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>
+}`,V1=`#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>
+}`,W1=`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>
+}`,q1=`#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>
+}`,$1=`#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>
+}`,j1=`#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;
+}`,X1=`#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>
+}`,K1=`#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
+}`,Y1=`#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
+}`,J1=`#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>
+}`,Z1=`#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>
+}`,Q1=`#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
+}`,eM=`#define STANDARD
+#ifdef PHYSICAL
+ #define IOR
+ #define USE_SPECULAR
+#endif
+uniform vec3 diffuse;
+uniform vec3 emissive;
+uniform float roughness;
+uniform float metalness;
+uniform float opacity;
+#ifdef IOR
+ uniform float ior;
+#endif
+#ifdef USE_SPECULAR
+ uniform float specularIntensity;
+ uniform vec3 specularColor;
+ #ifdef USE_SPECULAR_COLORMAP
+ uniform sampler2D specularColorMap;
+ #endif
+ #ifdef USE_SPECULAR_INTENSITYMAP
+ uniform sampler2D specularIntensityMap;
+ #endif
+#endif
+#ifdef USE_CLEARCOAT
+ uniform float clearcoat;
+ uniform float clearcoatRoughness;
+#endif
+#ifdef USE_DISPERSION
+ uniform float dispersion;
+#endif
+#ifdef USE_IRIDESCENCE
+ uniform float iridescence;
+ uniform float iridescenceIOR;
+ uniform float iridescenceThicknessMinimum;
+ uniform float iridescenceThicknessMaximum;
+#endif
+#ifdef USE_SHEEN
+ uniform vec3 sheenColor;
+ uniform float sheenRoughness;
+ #ifdef USE_SHEEN_COLORMAP
+ uniform sampler2D sheenColorMap;
+ #endif
+ #ifdef USE_SHEEN_ROUGHNESSMAP
+ uniform sampler2D sheenRoughnessMap;
+ #endif
+#endif
+#ifdef USE_ANISOTROPY
+ uniform vec2 anisotropyVector;
+ #ifdef USE_ANISOTROPYMAP
+ uniform sampler2D anisotropyMap;
+ #endif
+#endif
+varying vec3 vViewPosition;
+#include <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>
+}`,tM=`#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>
+}`,nM=`#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>
+}`,iM=`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>
+}`,rM=`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>
+}`,sM=`#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>
+}`,aM=`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>
+}`,oM=`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>
+}`,cM=`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>
+}`,ft={alphahash_fragment:CS,alphahash_pars_fragment:IS,alphamap_fragment:PS,alphamap_pars_fragment:LS,alphatest_fragment:DS,alphatest_pars_fragment:NS,aomap_fragment:OS,aomap_pars_fragment:FS,batching_pars_vertex:US,batching_vertex:kS,begin_vertex:BS,beginnormal_vertex:zS,bsdfs:HS,iridescence_fragment:GS,bumpmap_pars_fragment:VS,clipping_planes_fragment:WS,clipping_planes_pars_fragment:qS,clipping_planes_pars_vertex:$S,clipping_planes_vertex:jS,color_fragment:XS,color_pars_fragment:KS,color_pars_vertex:YS,color_vertex:JS,common:ZS,cube_uv_reflection_fragment:QS,defaultnormal_vertex:ew,displacementmap_pars_vertex:tw,displacementmap_vertex:nw,emissivemap_fragment:iw,emissivemap_pars_fragment:rw,colorspace_fragment:sw,colorspace_pars_fragment:aw,envmap_fragment:ow,envmap_common_pars_fragment:cw,envmap_pars_fragment:lw,envmap_pars_vertex:hw,envmap_physical_pars_fragment:vw,envmap_vertex:uw,fog_vertex:dw,fog_pars_vertex:fw,fog_fragment:pw,fog_pars_fragment:mw,gradientmap_pars_fragment:gw,lightmap_pars_fragment:bw,lights_lambert_fragment:xw,lights_lambert_pars_fragment:_w,lights_pars_begin:yw,lights_toon_fragment:Sw,lights_toon_pars_fragment:ww,lights_phong_fragment:Mw,lights_phong_pars_fragment:Aw,lights_physical_fragment:Tw,lights_physical_pars_fragment:Ew,lights_fragment_begin:Rw,lights_fragment_maps:Cw,lights_fragment_end:Iw,lightprobes_pars_fragment:Pw,logdepthbuf_fragment:Lw,logdepthbuf_pars_fragment:Dw,logdepthbuf_pars_vertex:Nw,logdepthbuf_vertex:Ow,map_fragment:Fw,map_pars_fragment:Uw,map_particle_fragment:kw,map_particle_pars_fragment:Bw,metalnessmap_fragment:zw,metalnessmap_pars_fragment:Hw,morphinstance_vertex:Gw,morphcolor_vertex:Vw,morphnormal_vertex:Ww,morphtarget_pars_vertex:qw,morphtarget_vertex:$w,normal_fragment_begin:jw,normal_fragment_maps:Xw,normal_pars_fragment:Kw,normal_pars_vertex:Yw,normal_vertex:Jw,normalmap_pars_fragment:Zw,clearcoat_normal_fragment_begin:Qw,clearcoat_normal_fragment_maps:e1,clearcoat_pars_fragment:t1,iridescence_pars_fragment:n1,opaque_fragment:i1,packing:r1,premultiplied_alpha_fragment:s1,project_vertex:a1,dithering_fragment:o1,dithering_pars_fragment:c1,roughnessmap_fragment:l1,roughnessmap_pars_fragment:h1,shadowmap_pars_fragment:u1,shadowmap_pars_vertex:d1,shadowmap_vertex:f1,shadowmask_pars_fragment:p1,skinbase_vertex:m1,skinning_pars_vertex:g1,skinning_vertex:b1,skinnormal_vertex:x1,specularmap_fragment:_1,specularmap_pars_fragment:y1,tonemapping_fragment:v1,tonemapping_pars_fragment:S1,transmission_fragment:w1,transmission_pars_fragment:M1,uv_pars_fragment:A1,uv_pars_vertex:T1,uv_vertex:E1,worldpos_vertex:R1,background_vert:C1,background_frag:I1,backgroundCube_vert:P1,backgroundCube_frag:L1,cube_vert:D1,cube_frag:N1,depth_vert:O1,depth_frag:F1,distance_vert:U1,distance_frag:k1,equirect_vert:B1,equirect_frag:z1,linedashed_vert:H1,linedashed_frag:G1,meshbasic_vert:V1,meshbasic_frag:W1,meshlambert_vert:q1,meshlambert_frag:$1,meshmatcap_vert:j1,meshmatcap_frag:X1,meshnormal_vert:K1,meshnormal_frag:Y1,meshphong_vert:J1,meshphong_frag:Z1,meshphysical_vert:Q1,meshphysical_frag:eM,meshtoon_vert:tM,meshtoon_frag:nM,points_vert:iM,points_frag:rM,shadow_vert:sM,shadow_frag:aM,sprite_vert:oM,sprite_frag:cM},Ue={common:{diffuse:{value:new Ve(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ct},alphaMap:{value:null},alphaMapTransform:{value:new ct},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ct}},envmap:{envMap:{value:null},envMapRotation:{value:new ct},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ct}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ct}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ct},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ct},normalScale:{value:new dt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ct},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ct}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ct}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ct}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ve(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{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 W},probesMax:{value:new W},probesResolution:{value:new W}},points:{diffuse:{value:new Ve(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ct},alphaTest:{value:0},uvTransform:{value:new ct}},sprite:{diffuse:{value:new Ve(16777215)},opacity:{value:1},center:{value:new dt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ct},alphaMap:{value:null},alphaMapTransform:{value:new ct},alphaTest:{value:0}}},Qi={basic:{uniforms:Nn([Ue.common,Ue.specularmap,Ue.envmap,Ue.aomap,Ue.lightmap,Ue.fog]),vertexShader:ft.meshbasic_vert,fragmentShader:ft.meshbasic_frag},lambert:{uniforms:Nn([Ue.common,Ue.specularmap,Ue.envmap,Ue.aomap,Ue.lightmap,Ue.emissivemap,Ue.bumpmap,Ue.normalmap,Ue.displacementmap,Ue.fog,Ue.lights,{emissive:{value:new Ve(0)},envMapIntensity:{value:1}}]),vertexShader:ft.meshlambert_vert,fragmentShader:ft.meshlambert_frag},phong:{uniforms:Nn([Ue.common,Ue.specularmap,Ue.envmap,Ue.aomap,Ue.lightmap,Ue.emissivemap,Ue.bumpmap,Ue.normalmap,Ue.displacementmap,Ue.fog,Ue.lights,{emissive:{value:new Ve(0)},specular:{value:new Ve(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:ft.meshphong_vert,fragmentShader:ft.meshphong_frag},standard:{uniforms:Nn([Ue.common,Ue.envmap,Ue.aomap,Ue.lightmap,Ue.emissivemap,Ue.bumpmap,Ue.normalmap,Ue.displacementmap,Ue.roughnessmap,Ue.metalnessmap,Ue.fog,Ue.lights,{emissive:{value:new Ve(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ft.meshphysical_vert,fragmentShader:ft.meshphysical_frag},toon:{uniforms:Nn([Ue.common,Ue.aomap,Ue.lightmap,Ue.emissivemap,Ue.bumpmap,Ue.normalmap,Ue.displacementmap,Ue.gradientmap,Ue.fog,Ue.lights,{emissive:{value:new Ve(0)}}]),vertexShader:ft.meshtoon_vert,fragmentShader:ft.meshtoon_frag},matcap:{uniforms:Nn([Ue.common,Ue.bumpmap,Ue.normalmap,Ue.displacementmap,Ue.fog,{matcap:{value:null}}]),vertexShader:ft.meshmatcap_vert,fragmentShader:ft.meshmatcap_frag},points:{uniforms:Nn([Ue.points,Ue.fog]),vertexShader:ft.points_vert,fragmentShader:ft.points_frag},dashed:{uniforms:Nn([Ue.common,Ue.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ft.linedashed_vert,fragmentShader:ft.linedashed_frag},depth:{uniforms:Nn([Ue.common,Ue.displacementmap]),vertexShader:ft.depth_vert,fragmentShader:ft.depth_frag},normal:{uniforms:Nn([Ue.common,Ue.bumpmap,Ue.normalmap,Ue.displacementmap,{opacity:{value:1}}]),vertexShader:ft.meshnormal_vert,fragmentShader:ft.meshnormal_frag},sprite:{uniforms:Nn([Ue.sprite,Ue.fog]),vertexShader:ft.sprite_vert,fragmentShader:ft.sprite_frag},background:{uniforms:{uvTransform:{value:new ct},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ft.background_vert,fragmentShader:ft.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ct}},vertexShader:ft.backgroundCube_vert,fragmentShader:ft.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ft.cube_vert,fragmentShader:ft.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ft.equirect_vert,fragmentShader:ft.equirect_frag},distance:{uniforms:Nn([Ue.common,Ue.displacementmap,{referencePosition:{value:new W},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ft.distance_vert,fragmentShader:ft.distance_frag},shadow:{uniforms:Nn([Ue.lights,Ue.fog,{color:{value:new Ve(0)},opacity:{value:1}}]),vertexShader:ft.shadow_vert,fragmentShader:ft.shadow_frag}};Qi.physical={uniforms:Nn([Qi.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ct},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ct},clearcoatNormalScale:{value:new dt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ct},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ct},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ct},sheen:{value:0},sheenColor:{value:new Ve(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ct},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ct},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ct},transmissionSamplerSize:{value:new dt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ct},attenuationDistance:{value:0},attenuationColor:{value:new Ve(0)},specularColor:{value:new Ve(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ct},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ct},anisotropyVector:{value:new dt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ct}}]),vertexShader:ft.meshphysical_vert,fragmentShader:ft.meshphysical_frag};xh={r:0,b:0,g:0},lM=new ot,nb=new ct;nb.set(-1,0,0,0,1,0,0,0,1);Kr=4,D0=[.125,.215,.35,.446,.526,.582],Rs=20,mM=256,zo=new Wr,N0=new Ve,Qd=null,ef=0,tf=0,nf=!1,gM=new W,wa=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,s={}){let{size:a=256,position:o=gM}=s;Qd=this._renderer.getRenderTarget(),ef=this._renderer.getActiveCubeFace(),tf=this._renderer.getActiveMipmapLevel(),nf=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,n,r,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=U0(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=F0(),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(e){this._lodMax=Math.floor(Math.log2(e)),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 e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Qd,ef,tf),this._renderer.xr.enabled=nf,e.scissorTest=!1,va(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===$r||e.mapping===As?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Qd=this._renderer.getRenderTarget(),ef=this._renderer.getActiveCubeFace(),tf=this._renderer.getActiveMipmapLevel(),nf=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:zt,minFilter:zt,generateMipmaps:!1,type:Gn,format:ci,colorSpace:bn,depthBuffer:!1},r=O0(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=O0(e,t,n);let{_lodMax:s}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=bM(s)),this._blurMaterial=_M(s,e,t),this._ggxMaterial=xM(s,e,t)}return r}_compileMaterial(e){let t=new xt(new mn,e);this._renderer.compile(t,zo)}_sceneToCubeUV(e,t,n,r,s){let l=new an(90,1,t,n),c=[1,-1,1,1,1,1],h=[1,1,1,-1,-1,-1],d=this._renderer,f=d.autoClear,p=d.toneMapping;d.getClearColor(N0),d.toneMapping=Ni,d.autoClear=!1,d.state.buffers.depth.getReversed()&&(d.setRenderTarget(r),d.clearDepth(),d.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new xt(new Hr,new gn({name:"PMREM.Background",side:An,depthWrite:!1,depthTest:!1})));let y=this._backgroundBox,b=y.material,g=!1,S=e.background;S?S.isColor&&(b.color.copy(S),e.background=null,g=!0):(b.color.copy(N0),g=!0);for(let A=0;A<6;A++){let T=A%3;T===0?(l.up.set(0,c[A],0),l.position.set(s.x,s.y,s.z),l.lookAt(s.x+h[A],s.y,s.z)):T===1?(l.up.set(0,0,c[A]),l.position.set(s.x,s.y,s.z),l.lookAt(s.x,s.y+h[A],s.z)):(l.up.set(0,c[A],0),l.position.set(s.x,s.y,s.z),l.lookAt(s.x,s.y,s.z+h[A]));let N=this._cubeSize;va(r,T*N,A>2?N:0,N,N),d.setRenderTarget(r),g&&d.render(y,l),d.render(e,l)}d.toneMapping=p,d.autoClear=f,e.background=S}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===$r||e.mapping===As;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=U0()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=F0());let s=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=s;let o=s.uniforms;o.envMap.value=e;let l=this._cubeSize;va(t,0,0,3*l,2*l),n.setRenderTarget(t),n.render(a,zo)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let s=1;s<r;s++)this._applyGGXFilter(e,s-1,s);t.autoClear=n}_applyGGXFilter(e,t,n){let r=this._renderer,s=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let l=a.uniforms,c=n/(this._lodMeshes.length-1),h=t/(this._lodMeshes.length-1),d=Math.sqrt(c*c-h*h),f=0+c*1.25,p=d*f,{_lodMax:x}=this,y=this._sizeLods[n],b=3*y*(n>x-Kr?n-x+Kr:0),g=4*(this._cubeSize-y);l.envMap.value=e.texture,l.roughness.value=p,l.mipInt.value=x-t,va(s,b,g,3*y,2*y),r.setRenderTarget(s),r.render(o,zo),l.envMap.value=s.texture,l.roughness.value=0,l.mipInt.value=x-n,va(e,b,g,3*y,2*y),r.setRenderTarget(e),r.render(o,zo)}_blur(e,t,n,r,s){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,"latitudinal",s),this._halfBlur(a,e,n,n,r,"longitudinal",s)}_halfBlur(e,t,n,r,s,a,o){let l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&et("blur direction must be either latitudinal or longitudinal!");let h=3,d=this._lodMeshes[r];d.material=c;let f=c.uniforms,p=this._sizeLods[n]-1,x=isFinite(s)?Math.PI/(2*p):2*Math.PI/(2*Rs-1),y=s/x,b=isFinite(s)?1+Math.floor(h*y):Rs;b>Rs&&Ke(`sigmaRadians, ${s}, is too large and will clip, as it requested ${b} samples when the maximum is set to ${Rs}`);let g=[],S=0;for(let U=0;U<Rs;++U){let v=U/y,I=Math.exp(-v*v/2);g.push(I),U===0?S+=I:U<b&&(S+=2*I)}for(let U=0;U<g.length;U++)g[U]=g[U]/S;f.envMap.value=e.texture,f.samples.value=b,f.weights.value=g,f.latitudinal.value=a==="latitudinal",o&&(f.poleAxis.value=o);let{_lodMax:A}=this;f.dTheta.value=x,f.mipInt.value=A-n;let T=this._sizeLods[r],N=3*T*(r>A-Kr?r-A+Kr:0),P=4*(this._cubeSize-T);va(t,N,P,3*T,2*T),l.setRenderTarget(t),l.render(d,zo)}};Ma=class extends Hn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new lo(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.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 );
+
+ }
+ `},r=new Hr(5,5,5),s=new ai({name:"CubemapFromEquirect",uniforms:Es(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:An,blending:Ji});s.uniforms.tEquirect.value=t;let a=new xt(r,s),o=t.minFilter;return t.minFilter===xi&&(t.minFilter=zt),new wl(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,r);e.setRenderTarget(s)}};EM={[Ad]:"LINEAR_TONE_MAPPING",[Td]:"REINHARD_TONE_MAPPING",[Ed]:"CINEON_TONE_MAPPING",[Ro]:"ACES_FILMIC_TONE_MAPPING",[Cd]:"AGX_TONE_MAPPING",[Id]:"NEUTRAL_TONE_MAPPING",[Rd]:"CUSTOM_TONE_MAPPING"};ib=new xn,af=new pr(1,1),rb=new to,sb=new ll,ab=new lo,k0=[],B0=[],z0=new Float32Array(16),H0=new Float32Array(9),G0=new Float32Array(4);of=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=XM(t.type)}},cf=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=pA(t.type)}},lf=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let r=this.seq;for(let s=0,a=r.length;s!==a;++s){let o=r[s];o.setValue(e,t[o.id],n)}}},rf=/(\w+)(\])?(\[|\.)?/g;Sa=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let a=0;a<n;++a){let o=e.getActiveUniform(t,a),l=e.getUniformLocation(t,o.name);mA(o,l,this)}let r=[],s=[];for(let a of this.seq)a.type===e.SAMPLER_2D_SHADOW||a.type===e.SAMPLER_CUBE_SHADOW||a.type===e.SAMPLER_2D_ARRAY_SHADOW?r.push(a):s.push(a);r.length>0&&(this.seq=r.concat(s))}setValue(e,t,n,r){let s=this.map[t];s!==void 0&&s.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let s=0,a=t.length;s!==a;++s){let o=t[s],l=n[o.id];l.needsUpdate!==!1&&o.setValue(e,l.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,s=e.length;r!==s;++r){let a=e[r];a.id in t&&n.push(a)}return n}};gA=37297,bA=0;q0=new ct;vA={[Ad]:"Linear",[Td]:"Reinhard",[Ed]:"Cineon",[Ro]:"ACESFilmic",[Cd]:"AgX",[Id]:"Neutral",[Rd]:"Custom"};_h=new W;EA=/^[ \t]*#include +<([\w\d./]+)>/gm;RA=new Map;IA=/#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;LA={[Eo]:"SHADOWMAP_TYPE_PCF",[qr]:"SHADOWMAP_TYPE_VSM"};NA={[$r]:"ENVMAP_TYPE_CUBE",[As]:"ENVMAP_TYPE_CUBE",[Co]:"ENVMAP_TYPE_CUBE_UV"};FA={[As]:"ENVMAP_MODE_REFRACTION"};kA={[Rl]:"ENVMAP_BLENDING_MULTIPLY",[d0]:"ENVMAP_BLENDING_MIX",[f0]:"ENVMAP_BLENDING_ADD"};GA=0,uf=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),s=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(s)===!1&&(a.add(s),s.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new df(e),t.set(e,n)),n}},df=class{constructor(e){this.id=GA++,this.code=e,this.usedTimes=0}};YA=0;eT=`void main() {
+ gl_Position = vec4( position, 1.0 );
+}`,tT=`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 );
+}`,nT=[new W(1,0,0),new W(-1,0,0),new W(0,1,0),new W(0,-1,0),new W(0,0,1),new W(0,0,-1)],iT=[new W(0,-1,0),new W(0,-1,0),new W(0,0,1),new W(0,0,-1),new W(0,-1,0),new W(0,-1,0)],eb=new ot,Ho=new W,sf=new W;cT=`
+void main() {
+
+ gl_Position = vec4( position, 1.0 );
+
+}`,lT=`
+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;
+
+ }
+
+}`,ff=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new ho(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new ai({vertexShader:cT,fragmentShader:lT,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new xt(new mi(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},pf=class extends Li{constructor(e,t){super();let n=this,r=null,s=1,a=null,o="local-floor",l=1,c=null,h=null,d=null,f=null,p=null,x=null,y=typeof XRWebGLBinding<"u",b=new ff,g={},S=t.getContextAttributes(),A=null,T=null,N=[],P=[],U=new dt,v=null,I=new an;I.viewport=new kt;let B=new an;B.viewport=new kt;let k=[I,B],V=new Ml,J=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(oe){let Ee=N[oe];return Ee===void 0&&(Ee=new ha,N[oe]=Ee),Ee.getTargetRaySpace()},this.getControllerGrip=function(oe){let Ee=N[oe];return Ee===void 0&&(Ee=new ha,N[oe]=Ee),Ee.getGripSpace()},this.getHand=function(oe){let Ee=N[oe];return Ee===void 0&&(Ee=new ha,N[oe]=Ee),Ee.getHandSpace()};function E(oe){let Ee=P.indexOf(oe.inputSource);if(Ee===-1)return;let _e=N[Ee];_e!==void 0&&(_e.update(oe.inputSource,oe.frame,c||a),_e.dispatchEvent({type:oe.type,data:oe.inputSource}))}function D(){r.removeEventListener("select",E),r.removeEventListener("selectstart",E),r.removeEventListener("selectend",E),r.removeEventListener("squeeze",E),r.removeEventListener("squeezestart",E),r.removeEventListener("squeezeend",E),r.removeEventListener("end",D),r.removeEventListener("inputsourceschange",O);for(let oe=0;oe<N.length;oe++){let Ee=P[oe];Ee!==null&&(P[oe]=null,N[oe].disconnect(Ee))}J=null,L=null,b.reset();for(let oe in g)delete g[oe];e.setRenderTarget(A),p=null,f=null,d=null,r=null,T=null,ke.stop(),n.isPresenting=!1,e.setPixelRatio(v),e.setSize(U.width,U.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(oe){s=oe,n.isPresenting===!0&&Ke("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(oe){o=oe,n.isPresenting===!0&&Ke("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(oe){c=oe},this.getBaseLayer=function(){return f!==null?f:p},this.getBinding=function(){return d===null&&y&&(d=new XRWebGLBinding(r,t)),d},this.getFrame=function(){return x},this.getSession=function(){return r},this.setSession=async function(oe){if(r=oe,r!==null){if(A=e.getRenderTarget(),r.addEventListener("select",E),r.addEventListener("selectstart",E),r.addEventListener("selectend",E),r.addEventListener("squeeze",E),r.addEventListener("squeezestart",E),r.addEventListener("squeezeend",E),r.addEventListener("end",D),r.addEventListener("inputsourceschange",O),S.xrCompatible!==!0&&await t.makeXRCompatible(),v=e.getPixelRatio(),e.getSize(U),y&&"createProjectionLayer"in XRWebGLBinding.prototype){let _e=null,Ze=null,tt=null;S.depth&&(tt=S.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,_e=S.stencil?jr:Wi,Ze=S.stencil?xa:Oi);let Qe={colorFormat:t.RGBA8,depthFormat:tt,scaleFactor:s};d=this.getBinding(),f=d.createProjectionLayer(Qe),r.updateRenderState({layers:[f]}),e.setPixelRatio(1),e.setSize(f.textureWidth,f.textureHeight,!1),T=new Hn(f.textureWidth,f.textureHeight,{format:ci,type:Qn,depthTexture:new pr(f.textureWidth,f.textureHeight,Ze,void 0,void 0,void 0,void 0,void 0,void 0,_e),stencilBuffer:S.stencil,colorSpace:e.outputColorSpace,samples:S.antialias?4:0,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}else{let _e={antialias:S.antialias,alpha:!0,depth:S.depth,stencil:S.stencil,framebufferScaleFactor:s};p=new XRWebGLLayer(r,t,_e),r.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),T=new Hn(p.framebufferWidth,p.framebufferHeight,{format:ci,type:Qn,colorSpace:e.outputColorSpace,stencilBuffer:S.stencil,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}T.isXRRenderTarget=!0,this.setFoveation(l),c=null,a=await r.requestReferenceSpace(o),ke.setContext(r),ke.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return b.getDepthTexture()};function O(oe){for(let Ee=0;Ee<oe.removed.length;Ee++){let _e=oe.removed[Ee],Ze=P.indexOf(_e);Ze>=0&&(P[Ze]=null,N[Ze].disconnect(_e))}for(let Ee=0;Ee<oe.added.length;Ee++){let _e=oe.added[Ee],Ze=P.indexOf(_e);if(Ze===-1){for(let Qe=0;Qe<N.length;Qe++)if(Qe>=P.length){P.push(_e),Ze=Qe;break}else if(P[Qe]===null){P[Qe]=_e,Ze=Qe;break}if(Ze===-1)break}let tt=N[Ze];tt&&tt.connect(_e)}}let H=new W,Y=new W;function le(oe,Ee,_e){H.setFromMatrixPosition(Ee.matrixWorld),Y.setFromMatrixPosition(_e.matrixWorld);let Ze=H.distanceTo(Y),tt=Ee.projectionMatrix.elements,Qe=_e.projectionMatrix.elements,Et=tt[14]/(tt[10]-1),it=tt[14]/(tt[10]+1),mt=(tt[9]+1)/tt[5],wt=(tt[9]-1)/tt[5],lt=(tt[8]-1)/tt[0],Bt=(Qe[8]+1)/Qe[0],gt=Et*lt,Yt=Et*Bt,q=Ze/(-lt+Bt),$t=q*-lt;if(Ee.matrixWorld.decompose(oe.position,oe.quaternion,oe.scale),oe.translateX($t),oe.translateZ(q),oe.matrixWorld.compose(oe.position,oe.quaternion,oe.scale),oe.matrixWorldInverse.copy(oe.matrixWorld).invert(),tt[10]===-1)oe.projectionMatrix.copy(Ee.projectionMatrix),oe.projectionMatrixInverse.copy(Ee.projectionMatrixInverse);else{let ht=Et+q,Tt=it+q,Pe=gt-$t,Ot=Yt+(Ze-$t),F=mt*it/Tt*ht,M=wt*it/Tt*ht;oe.projectionMatrix.makePerspective(Pe,Ot,F,M,ht,Tt),oe.projectionMatrixInverse.copy(oe.projectionMatrix).invert()}}function fe(oe,Ee){Ee===null?oe.matrixWorld.copy(oe.matrix):oe.matrixWorld.multiplyMatrices(Ee.matrixWorld,oe.matrix),oe.matrixWorldInverse.copy(oe.matrixWorld).invert()}this.updateCamera=function(oe){if(r===null)return;let Ee=oe.near,_e=oe.far;b.texture!==null&&(b.depthNear>0&&(Ee=b.depthNear),b.depthFar>0&&(_e=b.depthFar)),V.near=B.near=I.near=Ee,V.far=B.far=I.far=_e,(J!==V.near||L!==V.far)&&(r.updateRenderState({depthNear:V.near,depthFar:V.far}),J=V.near,L=V.far),V.layers.mask=oe.layers.mask|6,I.layers.mask=V.layers.mask&-5,B.layers.mask=V.layers.mask&-3;let Ze=oe.parent,tt=V.cameras;fe(V,Ze);for(let Qe=0;Qe<tt.length;Qe++)fe(tt[Qe],Ze);tt.length===2?le(V,I,B):V.projectionMatrix.copy(I.projectionMatrix),be(oe,V,Ze)};function be(oe,Ee,_e){_e===null?oe.matrix.copy(Ee.matrixWorld):(oe.matrix.copy(_e.matrixWorld),oe.matrix.invert(),oe.matrix.multiply(Ee.matrixWorld)),oe.matrix.decompose(oe.position,oe.quaternion,oe.scale),oe.updateMatrixWorld(!0),oe.projectionMatrix.copy(Ee.projectionMatrix),oe.projectionMatrixInverse.copy(Ee.projectionMatrixInverse),oe.isPerspectiveCamera&&(oe.fov=bs*2*Math.atan(1/oe.projectionMatrix.elements[5]),oe.zoom=1)}this.getCamera=function(){return V},this.getFoveation=function(){if(!(f===null&&p===null))return l},this.setFoveation=function(oe){l=oe,f!==null&&(f.fixedFoveation=oe),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=oe)},this.hasDepthSensing=function(){return b.texture!==null},this.getDepthSensingMesh=function(){return b.getMesh(V)},this.getCameraTexture=function(oe){return g[oe]};let Te=null;function Je(oe,Ee){if(h=Ee.getViewerPose(c||a),x=Ee,h!==null){let _e=h.views;p!==null&&(e.setRenderTargetFramebuffer(T,p.framebuffer),e.setRenderTarget(T));let Ze=!1;_e.length!==V.cameras.length&&(V.cameras.length=0,Ze=!0);for(let it=0;it<_e.length;it++){let mt=_e[it],wt=null;if(p!==null)wt=p.getViewport(mt);else{let Bt=d.getViewSubImage(f,mt);wt=Bt.viewport,it===0&&(e.setRenderTargetTextures(T,Bt.colorTexture,Bt.depthStencilTexture),e.setRenderTarget(T))}let lt=k[it];lt===void 0&&(lt=new an,lt.layers.enable(it),lt.viewport=new kt,k[it]=lt),lt.matrix.fromArray(mt.transform.matrix),lt.matrix.decompose(lt.position,lt.quaternion,lt.scale),lt.projectionMatrix.fromArray(mt.projectionMatrix),lt.projectionMatrixInverse.copy(lt.projectionMatrix).invert(),lt.viewport.set(wt.x,wt.y,wt.width,wt.height),it===0&&(V.matrix.copy(lt.matrix),V.matrix.decompose(V.position,V.quaternion,V.scale)),Ze===!0&&V.cameras.push(lt)}let tt=r.enabledFeatures;if(tt&&tt.includes("depth-sensing")&&r.depthUsage=="gpu-optimized"&&y){d=n.getBinding();let it=d.getDepthInformation(_e[0]);it&&it.isValid&&it.texture&&b.init(it,r.renderState)}if(tt&&tt.includes("camera-access")&&y){e.state.unbindTexture(),d=n.getBinding();for(let it=0;it<_e.length;it++){let mt=_e[it].camera;if(mt){let wt=g[mt];wt||(wt=new ho,g[mt]=wt);let lt=d.getCameraImage(mt);wt.sourceTexture=lt}}}}for(let _e=0;_e<N.length;_e++){let Ze=P[_e],tt=N[_e];Ze!==null&&tt!==void 0&&tt.update(Ze,Ee,c||a)}Te&&Te(oe,Ee),Ee.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:Ee}),x=null}let ke=new tb;ke.setAnimationLoop(Je),this.setAnimationLoop=function(oe){Te=oe},this.dispose=function(){}}},hT=new ot,ob=new ct;ob.set(-1,0,0,0,1,0,0,0,1);fT=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]),Zi=null;yh=class{constructor(e={}){let{canvas:t=A0(),context:n=null,depth:r=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:f=!1,outputBufferType:p=Qn}=e;this.isWebGLRenderer=!0;let x;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");x=n.getContextAttributes().alpha}else x=a;let y=p,b=new Set([kl,Ul,Fl]),g=new Set([Qn,Oi,ba,xa,Dl,Nl]),S=new Uint32Array(4),A=new Int32Array(4),T=new W,N=null,P=null,U=[],v=[],I=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Ni,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let B=this,k=!1,V=null;this._outputColorSpace=Xt;let J=0,L=0,E=null,D=-1,O=null,H=new kt,Y=new kt,le=null,fe=new Ve(0),be=0,Te=t.width,Je=t.height,ke=1,oe=null,Ee=null,_e=new kt(0,0,Te,Je),Ze=new kt(0,0,Te,Je),tt=!1,Qe=new da,Et=!1,it=!1,mt=new ot,wt=new W,lt=new kt,Bt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},gt=!1;function Yt(){return E===null?ke:1}let q=n;function $t(C,j){return t.getContext(C,j)}try{let C={alpha:!0,depth:r,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${"184"}`),t.addEventListener("webglcontextlost",xe,!1),t.addEventListener("webglcontextrestored",Xe,!1),t.addEventListener("webglcontextcreationerror",rt,!1),q===null){let j="webgl2";if(q=$t(j,C),q===null)throw $t(j)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(C){throw et("WebGLRenderer: "+C.message),C}let ht,Tt,Pe,Ot,F,M,Z,pe,ge,Se,Ce,ce,me,Be,Le,ve,Me,je,nt,pt,G,we,de;function He(){ht=new vM(q),ht.init(),G=new oT(q,ht),Tt=new fM(q,ht,e,G),Pe=new sT(q,ht),Tt.reversedDepthBuffer&&f&&Pe.buffers.depth.setReversed(!0),Ot=new MM(q),F=new qA,M=new aT(q,ht,Pe,F,Tt,G,Ot),Z=new yM(B),pe=new RS(q),we=new uM(q,pe),ge=new SM(q,pe,Ot,we),Se=new TM(q,ge,pe,we,Ot),je=new AM(q,Tt,M),Le=new pM(F),Ce=new WA(B,Z,ht,Tt,we,Le),ce=new uT(B,F),me=new jA,Be=new QA(ht),Me=new hM(B,Z,Pe,Se,x,l),ve=new rT(B,Se,Tt),de=new dT(q,Ot,Tt,Pe),nt=new dM(q,ht,Ot),pt=new wM(q,ht,Ot),Ot.programs=Ce.programs,B.capabilities=Tt,B.extensions=ht,B.properties=F,B.renderLists=me,B.shadowMap=ve,B.state=Pe,B.info=Ot}He(),y!==Qn&&(I=new RM(y,t.width,t.height,r,s));let Ae=new pf(B,q);this.xr=Ae,this.getContext=function(){return q},this.getContextAttributes=function(){return q.getContextAttributes()},this.forceContextLoss=function(){let C=ht.get("WEBGL_lose_context");C&&C.loseContext()},this.forceContextRestore=function(){let C=ht.get("WEBGL_lose_context");C&&C.restoreContext()},this.getPixelRatio=function(){return ke},this.setPixelRatio=function(C){C!==void 0&&(ke=C,this.setSize(Te,Je,!1))},this.getSize=function(C){return C.set(Te,Je)},this.setSize=function(C,j,ie=!0){if(Ae.isPresenting){Ke("WebGLRenderer: Can't change size while VR device is presenting.");return}Te=C,Je=j,t.width=Math.floor(C*ke),t.height=Math.floor(j*ke),ie===!0&&(t.style.width=C+"px",t.style.height=j+"px"),I!==null&&I.setSize(t.width,t.height),this.setViewport(0,0,C,j)},this.getDrawingBufferSize=function(C){return C.set(Te*ke,Je*ke).floor()},this.setDrawingBufferSize=function(C,j,ie){Te=C,Je=j,ke=ie,t.width=Math.floor(C*ie),t.height=Math.floor(j*ie),this.setViewport(0,0,C,j)},this.setEffects=function(C){if(y===Qn){et("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(C){for(let j=0;j<C.length;j++)if(C[j].isOutputPass===!0){Ke("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}I.setEffects(C||[])},this.getCurrentViewport=function(C){return C.copy(H)},this.getViewport=function(C){return C.copy(_e)},this.setViewport=function(C,j,ie,ee){C.isVector4?_e.set(C.x,C.y,C.z,C.w):_e.set(C,j,ie,ee),Pe.viewport(H.copy(_e).multiplyScalar(ke).round())},this.getScissor=function(C){return C.copy(Ze)},this.setScissor=function(C,j,ie,ee){C.isVector4?Ze.set(C.x,C.y,C.z,C.w):Ze.set(C,j,ie,ee),Pe.scissor(Y.copy(Ze).multiplyScalar(ke).round())},this.getScissorTest=function(){return tt},this.setScissorTest=function(C){Pe.setScissorTest(tt=C)},this.setOpaqueSort=function(C){oe=C},this.setTransparentSort=function(C){Ee=C},this.getClearColor=function(C){return C.copy(Me.getClearColor())},this.setClearColor=function(){Me.setClearColor(...arguments)},this.getClearAlpha=function(){return Me.getClearAlpha()},this.setClearAlpha=function(){Me.setClearAlpha(...arguments)},this.clear=function(C=!0,j=!0,ie=!0){let ee=0;if(C){let Q=!1;if(E!==null){let Fe=E.texture.format;Q=b.has(Fe)}if(Q){let Fe=E.texture.type,We=g.has(Fe),De=Me.getClearColor(),Ie=Me.getClearAlpha(),qe=De.r,st=De.g,at=De.b;We?(S[0]=qe,S[1]=st,S[2]=at,S[3]=Ie,q.clearBufferuiv(q.COLOR,0,S)):(A[0]=qe,A[1]=st,A[2]=at,A[3]=Ie,q.clearBufferiv(q.COLOR,0,A))}else ee|=q.COLOR_BUFFER_BIT}j&&(ee|=q.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),ie&&(ee|=q.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),ee!==0&&q.clear(ee)},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(C){C.setRenderer(this),V=C},this.dispose=function(){t.removeEventListener("webglcontextlost",xe,!1),t.removeEventListener("webglcontextrestored",Xe,!1),t.removeEventListener("webglcontextcreationerror",rt,!1),Me.dispose(),me.dispose(),Be.dispose(),F.dispose(),Z.dispose(),Se.dispose(),we.dispose(),de.dispose(),Ce.dispose(),Ae.dispose(),Ae.removeEventListener("sessionstart",ns),Ae.removeEventListener("sessionend",ka),zi.stop()};function xe(C){C.preventDefault(),eo("WebGLRenderer: Context Lost."),k=!0}function Xe(){eo("WebGLRenderer: Context Restored."),k=!1;let C=Ot.autoReset,j=ve.enabled,ie=ve.autoUpdate,ee=ve.needsUpdate,Q=ve.type;He(),Ot.autoReset=C,ve.enabled=j,ve.autoUpdate=ie,ve.needsUpdate=ee,ve.type=Q}function rt(C){et("WebGLRenderer: A WebGL context could not be created. Reason: ",C.statusMessage)}function jt(C){let j=C.target;j.removeEventListener("dispose",jt),Rt(j)}function Rt(C){$n(C),F.remove(C)}function $n(C){let j=F.get(C).programs;j!==void 0&&(j.forEach(function(ie){Ce.releaseProgram(ie)}),C.isShaderMaterial&&Ce.releaseShaderCache(C))}this.renderBufferDirect=function(C,j,ie,ee,Q,Fe){j===null&&(j=Bt);let We=Q.isMesh&&Q.matrixWorld.determinant()<0,De=yc(C,j,ie,ee,Q);Pe.setMaterial(ee,We);let Ie=ie.index,qe=1;if(ee.wireframe===!0){if(Ie=ge.getWireframeAttribute(ie),Ie===void 0)return;qe=2}let st=ie.drawRange,at=ie.attributes.position,Ye=st.start*qe,Ct=(st.start+st.count)*qe;Fe!==null&&(Ye=Math.max(Ye,Fe.start*qe),Ct=Math.min(Ct,(Fe.start+Fe.count)*qe)),Ie!==null?(Ye=Math.max(Ye,0),Ct=Math.min(Ct,Ie.count)):at!=null&&(Ye=Math.max(Ye,0),Ct=Math.min(Ct,at.count));let Jt=Ct-Ye;if(Jt<0||Jt===1/0)return;we.setup(Q,ee,De,ie,Ie);let Wt,Mt=nt;if(Ie!==null&&(Wt=pe.get(Ie),Mt=pt,Mt.setIndex(Wt)),Q.isMesh)ee.wireframe===!0?(Pe.setLineWidth(ee.wireframeLinewidth*Yt()),Mt.setMode(q.LINES)):Mt.setMode(q.TRIANGLES);else if(Q.isLine){let Zt=ee.linewidth;Zt===void 0&&(Zt=1),Pe.setLineWidth(Zt*Yt()),Q.isLineSegments?Mt.setMode(q.LINES):Q.isLineLoop?Mt.setMode(q.LINE_LOOP):Mt.setMode(q.LINE_STRIP)}else Q.isPoints?Mt.setMode(q.POINTS):Q.isSprite&&Mt.setMode(q.TRIANGLES);if(Q.isBatchedMesh)if(ht.get("WEBGL_multi_draw"))Mt.renderMultiDraw(Q._multiDrawStarts,Q._multiDrawCounts,Q._multiDrawCount);else{let Zt=Q._multiDrawStarts,ze=Q._multiDrawCounts,Un=Q._multiDrawCount,vt=Ie?pe.get(Ie).bytesPerElement:1,Xn=F.get(ee).currentProgram.getUniforms();for(let sn=0;sn<Un;sn++)Xn.setValue(q,"_gl_DrawID",sn),Mt.render(Zt[sn]/vt,ze[sn])}else if(Q.isInstancedMesh)Mt.renderInstances(Ye,Jt,Q.count);else if(ie.isInstancedBufferGeometry){let Zt=ie._maxInstanceCount!==void 0?ie._maxInstanceCount:1/0,ze=Math.min(ie.instanceCount,Zt);Mt.renderInstances(Ye,Jt,ze)}else Mt.render(Ye,Jt)};function ui(C,j,ie){C.transparent===!0&&C.side===Dn&&C.forceSinglePass===!1?(C.side=An,C.needsUpdate=!0,rs(C,j,ie),C.side=Pi,C.needsUpdate=!0,rs(C,j,ie),C.side=Dn):rs(C,j,ie)}this.compile=function(C,j,ie=null){ie===null&&(ie=C),P=Be.get(ie),P.init(j),v.push(P),ie.traverseVisible(function(Q){Q.isLight&&Q.layers.test(j.layers)&&(P.pushLight(Q),Q.castShadow&&P.pushShadow(Q))}),C!==ie&&C.traverseVisible(function(Q){Q.isLight&&Q.layers.test(j.layers)&&(P.pushLight(Q),Q.castShadow&&P.pushShadow(Q))}),P.setupLights();let ee=new Set;return C.traverse(function(Q){if(!(Q.isMesh||Q.isPoints||Q.isLine||Q.isSprite))return;let Fe=Q.material;if(Fe)if(Array.isArray(Fe))for(let We=0;We<Fe.length;We++){let De=Fe[We];ui(De,ie,Q),ee.add(De)}else ui(Fe,ie,Q),ee.add(Fe)}),P=v.pop(),ee},this.compileAsync=function(C,j,ie=null){let ee=this.compile(C,j,ie);return new Promise(Q=>{function Fe(){if(ee.forEach(function(We){F.get(We).currentProgram.isReady()&&ee.delete(We)}),ee.size===0){Q(C);return}setTimeout(Fe,10)}ht.get("KHR_parallel_shader_compile")!==null?Fe():setTimeout(Fe,10)})};let Hs=null;function Ou(C){Hs&&Hs(C)}function ns(){zi.stop()}function ka(){zi.start()}let zi=new tb;zi.setAnimationLoop(Ou),typeof self<"u"&&zi.setContext(self),this.setAnimationLoop=function(C){Hs=C,Ae.setAnimationLoop(C),C===null?zi.stop():zi.start()},Ae.addEventListener("sessionstart",ns),Ae.addEventListener("sessionend",ka),this.render=function(C,j){if(j!==void 0&&j.isCamera!==!0){et("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(k===!0)return;V!==null&&V.renderStart(C,j);let ie=Ae.enabled===!0&&Ae.isPresenting===!0,ee=I!==null&&(E===null||ie)&&I.begin(B,E);if(C.matrixWorldAutoUpdate===!0&&C.updateMatrixWorld(),j.parent===null&&j.matrixWorldAutoUpdate===!0&&j.updateMatrixWorld(),Ae.enabled===!0&&Ae.isPresenting===!0&&(I===null||I.isCompositing()===!1)&&(Ae.cameraAutoUpdate===!0&&Ae.updateCamera(j),j=Ae.getCamera()),C.isScene===!0&&C.onBeforeRender(B,C,j,E),P=Be.get(C,v.length),P.init(j),P.state.textureUnits=M.getTextureUnits(),v.push(P),mt.multiplyMatrices(j.projectionMatrix,j.matrixWorldInverse),Qe.setFromProjectionMatrix(mt,Ci,j.reversedDepth),it=this.localClippingEnabled,Et=Le.init(this.clippingPlanes,it),N=me.get(C,U.length),N.init(),U.push(N),Ae.enabled===!0&&Ae.isPresenting===!0){let We=B.xr.getDepthSensingMesh();We!==null&&Ba(We,j,-1/0,B.sortObjects)}Ba(C,j,0,B.sortObjects),N.finish(),B.sortObjects===!0&&N.sort(oe,Ee),gt=Ae.enabled===!1||Ae.isPresenting===!1||Ae.hasDepthSensing()===!1,gt&&Me.addToRenderList(N,C),this.info.render.frame++,Et===!0&&Le.beginShadows();let Q=P.state.shadowsArray;if(ve.render(Q,C,j),Et===!0&&Le.endShadows(),this.info.autoReset===!0&&this.info.reset(),(ee&&I.hasRenderPass())===!1){let We=N.opaque,De=N.transmissive;if(P.setupLights(),j.isArrayCamera){let Ie=j.cameras;if(De.length>0)for(let qe=0,st=Ie.length;qe<st;qe++){let at=Ie[qe];za(We,De,C,at)}gt&&Me.render(C);for(let qe=0,st=Ie.length;qe<st;qe++){let at=Ie[qe];jn(N,C,at,at.viewport)}}else De.length>0&&za(We,De,C,j),gt&&Me.render(C),jn(N,C,j)}E!==null&&L===0&&(M.updateMultisampleRenderTarget(E),M.updateRenderTargetMipmap(E)),ee&&I.end(B),C.isScene===!0&&C.onAfterRender(B,C,j),we.resetDefaultState(),D=-1,O=null,v.pop(),v.length>0?(P=v[v.length-1],M.setTextureUnits(P.state.textureUnits),Et===!0&&Le.setGlobalState(B.clippingPlanes,P.state.camera)):P=null,U.pop(),U.length>0?N=U[U.length-1]:N=null,V!==null&&V.renderEnd()};function Ba(C,j,ie,ee){if(C.visible===!1)return;if(C.layers.test(j.layers)){if(C.isGroup)ie=C.renderOrder;else if(C.isLOD)C.autoUpdate===!0&&C.update(j);else if(C.isLightProbeGrid)P.pushLightProbeGrid(C);else if(C.isLight)P.pushLight(C),C.castShadow&&P.pushShadow(C);else if(C.isSprite){if(!C.frustumCulled||Qe.intersectsSprite(C)){ee&&lt.setFromMatrixPosition(C.matrixWorld).applyMatrix4(mt);let We=Se.update(C),De=C.material;De.visible&&N.push(C,We,De,ie,lt.z,null)}}else if((C.isMesh||C.isLine||C.isPoints)&&(!C.frustumCulled||Qe.intersectsObject(C))){let We=Se.update(C),De=C.material;if(ee&&(C.boundingSphere!==void 0?(C.boundingSphere===null&&C.computeBoundingSphere(),lt.copy(C.boundingSphere.center)):(We.boundingSphere===null&&We.computeBoundingSphere(),lt.copy(We.boundingSphere.center)),lt.applyMatrix4(C.matrixWorld).applyMatrix4(mt)),Array.isArray(De)){let Ie=We.groups;for(let qe=0,st=Ie.length;qe<st;qe++){let at=Ie[qe],Ye=De[at.materialIndex];Ye&&Ye.visible&&N.push(C,We,Ye,ie,lt.z,at)}}else De.visible&&N.push(C,We,De,ie,lt.z,null)}}let Fe=C.children;for(let We=0,De=Fe.length;We<De;We++)Ba(Fe[We],j,ie,ee)}function jn(C,j,ie,ee){let{opaque:Q,transmissive:Fe,transparent:We}=C;P.setupLightsView(ie),Et===!0&&Le.setGlobalState(B.clippingPlanes,ie),ee&&Pe.viewport(H.copy(ee)),Q.length>0&&is(Q,j,ie),Fe.length>0&&is(Fe,j,ie),We.length>0&&is(We,j,ie),Pe.buffers.depth.setTest(!0),Pe.buffers.depth.setMask(!0),Pe.buffers.color.setMask(!0),Pe.setPolygonOffset(!1)}function za(C,j,ie,ee){if((ie.isScene===!0?ie.overrideMaterial:null)!==null)return;if(P.state.transmissionRenderTarget[ee.id]===void 0){let Ye=ht.has("EXT_color_buffer_half_float")||ht.has("EXT_color_buffer_float");P.state.transmissionRenderTarget[ee.id]=new Hn(1,1,{generateMipmaps:!0,type:Ye?Gn:Qn,minFilter:xi,samples:Math.max(4,Tt.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:ut.workingColorSpace})}let Fe=P.state.transmissionRenderTarget[ee.id],We=ee.viewport||H;Fe.setSize(We.z*B.transmissionResolutionScale,We.w*B.transmissionResolutionScale);let De=B.getRenderTarget(),Ie=B.getActiveCubeFace(),qe=B.getActiveMipmapLevel();B.setRenderTarget(Fe),B.getClearColor(fe),be=B.getClearAlpha(),be<1&&B.setClearColor(16777215,.5),B.clear(),gt&&Me.render(ie);let st=B.toneMapping;B.toneMapping=Ni;let at=ee.viewport;if(ee.viewport!==void 0&&(ee.viewport=void 0),P.setupLightsView(ee),Et===!0&&Le.setGlobalState(B.clippingPlanes,ee),is(C,ie,ee),M.updateMultisampleRenderTarget(Fe),M.updateRenderTargetMipmap(Fe),ht.has("WEBGL_multisampled_render_to_texture")===!1){let Ye=!1;for(let Ct=0,Jt=j.length;Ct<Jt;Ct++){let Wt=j[Ct],{object:Mt,geometry:Zt,material:ze,group:Un}=Wt;if(ze.side===Dn&&Mt.layers.test(ee.layers)){let vt=ze.side;ze.side=An,ze.needsUpdate=!0,di(Mt,ie,ee,Zt,ze,Un),ze.side=vt,ze.needsUpdate=!0,Ye=!0}}Ye===!0&&(M.updateMultisampleRenderTarget(Fe),M.updateRenderTargetMipmap(Fe))}B.setRenderTarget(De,Ie,qe),B.setClearColor(fe,be),at!==void 0&&(ee.viewport=at),B.toneMapping=st}function is(C,j,ie){let ee=j.isScene===!0?j.overrideMaterial:null;for(let Q=0,Fe=C.length;Q<Fe;Q++){let We=C[Q],{object:De,geometry:Ie,group:qe}=We,st=We.material;st.allowOverride===!0&&ee!==null&&(st=ee),De.layers.test(ie.layers)&&di(De,j,ie,Ie,st,qe)}}function di(C,j,ie,ee,Q,Fe){C.onBeforeRender(B,j,ie,ee,Q,Fe),C.modelViewMatrix.multiplyMatrices(ie.matrixWorldInverse,C.matrixWorld),C.normalMatrix.getNormalMatrix(C.modelViewMatrix),Q.onBeforeRender(B,j,ie,ee,C,Fe),Q.transparent===!0&&Q.side===Dn&&Q.forceSinglePass===!1?(Q.side=An,Q.needsUpdate=!0,B.renderBufferDirect(ie,j,ee,Q,C,Fe),Q.side=Pi,Q.needsUpdate=!0,B.renderBufferDirect(ie,j,ee,Q,C,Fe),Q.side=Dn):B.renderBufferDirect(ie,j,ee,Q,C,Fe),C.onAfterRender(B,j,ie,ee,Q,Fe)}function rs(C,j,ie){j.isScene!==!0&&(j=Bt);let ee=F.get(C),Q=P.state.lights,Fe=P.state.shadowsArray,We=Q.state.version,De=Ce.getParameters(C,Q.state,Fe,j,ie,P.state.lightProbeGridArray),Ie=Ce.getProgramCacheKey(De),qe=ee.programs;ee.environment=C.isMeshStandardMaterial||C.isMeshLambertMaterial||C.isMeshPhongMaterial?j.environment:null,ee.fog=j.fog;let st=C.isMeshStandardMaterial||C.isMeshLambertMaterial&&!C.envMap||C.isMeshPhongMaterial&&!C.envMap;ee.envMap=Z.get(C.envMap||ee.environment,st),ee.envMapRotation=ee.environment!==null&&C.envMap===null?j.environmentRotation:C.envMapRotation,qe===void 0&&(C.addEventListener("dispose",jt),qe=new Map,ee.programs=qe);let at=qe.get(Ie);if(at!==void 0){if(ee.currentProgram===at&&ee.lightsStateVersion===We)return sr(C,De),at}else De.uniforms=Ce.getUniforms(C),V!==null&&C.isNodeMaterial&&V.build(C,ie,De),C.onBeforeCompile(De,B),at=Ce.acquireProgram(De,Ie),qe.set(Ie,at),ee.uniforms=De.uniforms;let Ye=ee.uniforms;return(!C.isShaderMaterial&&!C.isRawShaderMaterial||C.clipping===!0)&&(Ye.clippingPlanes=Le.uniform),sr(C,De),ee.needsLights=Mi(C),ee.lightsStateVersion=We,ee.needsLights&&(Ye.ambientLightColor.value=Q.state.ambient,Ye.lightProbe.value=Q.state.probe,Ye.directionalLights.value=Q.state.directional,Ye.directionalLightShadows.value=Q.state.directionalShadow,Ye.spotLights.value=Q.state.spot,Ye.spotLightShadows.value=Q.state.spotShadow,Ye.rectAreaLights.value=Q.state.rectArea,Ye.ltc_1.value=Q.state.rectAreaLTC1,Ye.ltc_2.value=Q.state.rectAreaLTC2,Ye.pointLights.value=Q.state.point,Ye.pointLightShadows.value=Q.state.pointShadow,Ye.hemisphereLights.value=Q.state.hemi,Ye.directionalShadowMatrix.value=Q.state.directionalShadowMatrix,Ye.spotLightMatrix.value=Q.state.spotLightMatrix,Ye.spotLightMap.value=Q.state.spotLightMap,Ye.pointShadowMatrix.value=Q.state.pointShadowMatrix),ee.lightProbeGrid=P.state.lightProbeGridArray.length>0,ee.currentProgram=at,ee.uniformsList=null,at}function Ha(C){if(C.uniformsList===null){let j=C.currentProgram.getUniforms();C.uniformsList=Sa.seqWithValue(j.seq,C.uniforms)}return C.uniformsList}function sr(C,j){let ie=F.get(C);ie.outputColorSpace=j.outputColorSpace,ie.batching=j.batching,ie.batchingColor=j.batchingColor,ie.instancing=j.instancing,ie.instancingColor=j.instancingColor,ie.instancingMorph=j.instancingMorph,ie.skinning=j.skinning,ie.morphTargets=j.morphTargets,ie.morphNormals=j.morphNormals,ie.morphColors=j.morphColors,ie.morphTargetsCount=j.morphTargetsCount,ie.numClippingPlanes=j.numClippingPlanes,ie.numIntersection=j.numClipIntersection,ie.vertexAlphas=j.vertexAlphas,ie.vertexTangents=j.vertexTangents,ie.toneMapping=j.toneMapping}function _c(C,j){if(C.length===0)return null;if(C.length===1)return C[0].texture!==null?C[0]:null;T.setFromMatrixPosition(j.matrixWorld);for(let ie=0,ee=C.length;ie<ee;ie++){let Q=C[ie];if(Q.texture!==null&&Q.boundingBox.containsPoint(T))return Q}return null}function yc(C,j,ie,ee,Q){j.isScene!==!0&&(j=Bt),M.resetTextureUnits();let Fe=j.fog,We=ee.isMeshStandardMaterial||ee.isMeshLambertMaterial||ee.isMeshPhongMaterial?j.environment:null,De=E===null?B.outputColorSpace:E.isXRRenderTarget===!0?E.texture.colorSpace:ut.workingColorSpace,Ie=ee.isMeshStandardMaterial||ee.isMeshLambertMaterial&&!ee.envMap||ee.isMeshPhongMaterial&&!ee.envMap,qe=Z.get(ee.envMap||We,Ie),st=ee.vertexColors===!0&&!!ie.attributes.color&&ie.attributes.color.itemSize===4,at=!!ie.attributes.tangent&&(!!ee.normalMap||ee.anisotropy>0),Ye=!!ie.morphAttributes.position,Ct=!!ie.morphAttributes.normal,Jt=!!ie.morphAttributes.color,Wt=Ni;ee.toneMapped&&(E===null||E.isXRRenderTarget===!0)&&(Wt=B.toneMapping);let Mt=ie.morphAttributes.position||ie.morphAttributes.normal||ie.morphAttributes.color,Zt=Mt!==void 0?Mt.length:0,ze=F.get(ee),Un=P.state.lights;if(Et===!0&&(it===!0||C!==O)){let It=C===O&&ee.id===D;Le.setState(ee,C,It)}let vt=!1;ee.version===ze.__version?(ze.needsLights&&ze.lightsStateVersion!==Un.state.version||ze.outputColorSpace!==De||Q.isBatchedMesh&&ze.batching===!1||!Q.isBatchedMesh&&ze.batching===!0||Q.isBatchedMesh&&ze.batchingColor===!0&&Q.colorTexture===null||Q.isBatchedMesh&&ze.batchingColor===!1&&Q.colorTexture!==null||Q.isInstancedMesh&&ze.instancing===!1||!Q.isInstancedMesh&&ze.instancing===!0||Q.isSkinnedMesh&&ze.skinning===!1||!Q.isSkinnedMesh&&ze.skinning===!0||Q.isInstancedMesh&&ze.instancingColor===!0&&Q.instanceColor===null||Q.isInstancedMesh&&ze.instancingColor===!1&&Q.instanceColor!==null||Q.isInstancedMesh&&ze.instancingMorph===!0&&Q.morphTexture===null||Q.isInstancedMesh&&ze.instancingMorph===!1&&Q.morphTexture!==null||ze.envMap!==qe||ee.fog===!0&&ze.fog!==Fe||ze.numClippingPlanes!==void 0&&(ze.numClippingPlanes!==Le.numPlanes||ze.numIntersection!==Le.numIntersection)||ze.vertexAlphas!==st||ze.vertexTangents!==at||ze.morphTargets!==Ye||ze.morphNormals!==Ct||ze.morphColors!==Jt||ze.toneMapping!==Wt||ze.morphTargetsCount!==Zt||!!ze.lightProbeGrid!=P.state.lightProbeGridArray.length>0)&&(vt=!0):(vt=!0,ze.__version=ee.version);let Xn=ze.currentProgram;vt===!0&&(Xn=rs(ee,j,Q),V&&ee.isNodeMaterial&&V.onUpdateProgram(ee,Xn,ze));let sn=!1,hn=!1,kn=!1,At=Xn.getUniforms(),Ft=ze.uniforms;if(Pe.useProgram(Xn.program)&&(sn=!0,hn=!0,kn=!0),ee.id!==D&&(D=ee.id,hn=!0),ze.needsLights){let It=_c(P.state.lightProbeGridArray,Q);ze.lightProbeGrid!==It&&(ze.lightProbeGrid=It,hn=!0)}if(sn||O!==C){Pe.buffers.depth.getReversed()&&C.reversedDepth!==!0&&(C._reversedDepth=!0,C.updateProjectionMatrix()),At.setValue(q,"projectionMatrix",C.projectionMatrix),At.setValue(q,"viewMatrix",C.matrixWorldInverse);let R=At.map.cameraPosition;R!==void 0&&R.setValue(q,wt.setFromMatrixPosition(C.matrixWorld)),Tt.logarithmicDepthBuffer&&At.setValue(q,"logDepthBufFC",2/(Math.log(C.far+1)/Math.LN2)),(ee.isMeshPhongMaterial||ee.isMeshToonMaterial||ee.isMeshLambertMaterial||ee.isMeshBasicMaterial||ee.isMeshStandardMaterial||ee.isShaderMaterial)&&At.setValue(q,"isOrthographic",C.isOrthographicCamera===!0),O!==C&&(O=C,hn=!0,kn=!0)}if(ze.needsLights&&(Un.state.directionalShadowMap.length>0&&At.setValue(q,"directionalShadowMap",Un.state.directionalShadowMap,M),Un.state.spotShadowMap.length>0&&At.setValue(q,"spotShadowMap",Un.state.spotShadowMap,M),Un.state.pointShadowMap.length>0&&At.setValue(q,"pointShadowMap",Un.state.pointShadowMap,M)),Q.isSkinnedMesh){At.setOptional(q,Q,"bindMatrix"),At.setOptional(q,Q,"bindMatrixInverse");let It=Q.skeleton;It&&(It.boneTexture===null&&It.computeBoneTexture(),At.setValue(q,"boneTexture",It.boneTexture,M))}Q.isBatchedMesh&&(At.setOptional(q,Q,"batchingTexture"),At.setValue(q,"batchingTexture",Q._matricesTexture,M),At.setOptional(q,Q,"batchingIdTexture"),At.setValue(q,"batchingIdTexture",Q._indirectTexture,M),At.setOptional(q,Q,"batchingColorTexture"),Q._colorsTexture!==null&&At.setValue(q,"batchingColorTexture",Q._colorsTexture,M));let Bn=ie.morphAttributes;if((Bn.position!==void 0||Bn.normal!==void 0||Bn.color!==void 0)&&je.update(Q,ie,Xn),(hn||ze.receiveShadow!==Q.receiveShadow)&&(ze.receiveShadow=Q.receiveShadow,At.setValue(q,"receiveShadow",Q.receiveShadow)),(ee.isMeshStandardMaterial||ee.isMeshLambertMaterial||ee.isMeshPhongMaterial)&&ee.envMap===null&&j.environment!==null&&(Ft.envMapIntensity.value=j.environmentIntensity),Ft.dfgLUT!==void 0&&(Ft.dfgLUT.value=pT()),hn){if(At.setValue(q,"toneMappingExposure",B.toneMappingExposure),ze.needsLights&&wr(Ft,kn),Fe&&ee.fog===!0&&ce.refreshFogUniforms(Ft,Fe),ce.refreshMaterialUniforms(Ft,ee,ke,Je,P.state.transmissionRenderTarget[C.id]),ze.needsLights&&ze.lightProbeGrid){let It=ze.lightProbeGrid;Ft.probesSH.value=It.texture,Ft.probesMin.value.copy(It.boundingBox.min),Ft.probesMax.value.copy(It.boundingBox.max),Ft.probesResolution.value.copy(It.resolution)}Sa.upload(q,Ha(ze),Ft,M)}if(ee.isShaderMaterial&&ee.uniformsNeedUpdate===!0&&(Sa.upload(q,Ha(ze),Ft,M),ee.uniformsNeedUpdate=!1),ee.isSpriteMaterial&&At.setValue(q,"center",Q.center),At.setValue(q,"modelViewMatrix",Q.modelViewMatrix),At.setValue(q,"normalMatrix",Q.normalMatrix),At.setValue(q,"modelMatrix",Q.matrixWorld),ee.uniformsGroups!==void 0){let It=ee.uniformsGroups;for(let R=0,u=It.length;R<u;R++){let m=It[R];de.update(m,Xn),de.bind(m,Xn)}}return Xn}function wr(C,j){C.ambientLightColor.needsUpdate=j,C.lightProbe.needsUpdate=j,C.directionalLights.needsUpdate=j,C.directionalLightShadows.needsUpdate=j,C.pointLights.needsUpdate=j,C.pointLightShadows.needsUpdate=j,C.spotLights.needsUpdate=j,C.spotLightShadows.needsUpdate=j,C.rectAreaLights.needsUpdate=j,C.hemisphereLights.needsUpdate=j}function Mi(C){return C.isMeshLambertMaterial||C.isMeshToonMaterial||C.isMeshPhongMaterial||C.isMeshStandardMaterial||C.isShadowMaterial||C.isShaderMaterial&&C.lights===!0}this.getActiveCubeFace=function(){return J},this.getActiveMipmapLevel=function(){return L},this.getRenderTarget=function(){return E},this.setRenderTargetTextures=function(C,j,ie){let ee=F.get(C);ee.__autoAllocateDepthBuffer=C.resolveDepthBuffer===!1,ee.__autoAllocateDepthBuffer===!1&&(ee.__useRenderToTexture=!1),F.get(C.texture).__webglTexture=j,F.get(C.depthTexture).__webglTexture=ee.__autoAllocateDepthBuffer?void 0:ie,ee.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(C,j){let ie=F.get(C);ie.__webglFramebuffer=j,ie.__useDefaultFramebuffer=j===void 0};let Fu=q.createFramebuffer();this.setRenderTarget=function(C,j=0,ie=0){E=C,J=j,L=ie;let ee=null,Q=!1,Fe=!1;if(C){let De=F.get(C);if(De.__useDefaultFramebuffer!==void 0){Pe.bindFramebuffer(q.FRAMEBUFFER,De.__webglFramebuffer),H.copy(C.viewport),Y.copy(C.scissor),le=C.scissorTest,Pe.viewport(H),Pe.scissor(Y),Pe.setScissorTest(le),D=-1;return}else if(De.__webglFramebuffer===void 0)M.setupRenderTarget(C);else if(De.__hasExternalTextures)M.rebindTextures(C,F.get(C.texture).__webglTexture,F.get(C.depthTexture).__webglTexture);else if(C.depthBuffer){let st=C.depthTexture;if(De.__boundDepthTexture!==st){if(st!==null&&F.has(st)&&(C.width!==st.image.width||C.height!==st.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");M.setupDepthRenderbuffer(C)}}let Ie=C.texture;(Ie.isData3DTexture||Ie.isDataArrayTexture||Ie.isCompressedArrayTexture)&&(Fe=!0);let qe=F.get(C).__webglFramebuffer;C.isWebGLCubeRenderTarget?(Array.isArray(qe[j])?ee=qe[j][ie]:ee=qe[j],Q=!0):C.samples>0&&M.useMultisampledRTT(C)===!1?ee=F.get(C).__webglMultisampledFramebuffer:Array.isArray(qe)?ee=qe[ie]:ee=qe,H.copy(C.viewport),Y.copy(C.scissor),le=C.scissorTest}else H.copy(_e).multiplyScalar(ke).floor(),Y.copy(Ze).multiplyScalar(ke).floor(),le=tt;if(ie!==0&&(ee=Fu),Pe.bindFramebuffer(q.FRAMEBUFFER,ee)&&Pe.drawBuffers(C,ee),Pe.viewport(H),Pe.scissor(Y),Pe.setScissorTest(le),Q){let De=F.get(C.texture);q.framebufferTexture2D(q.FRAMEBUFFER,q.COLOR_ATTACHMENT0,q.TEXTURE_CUBE_MAP_POSITIVE_X+j,De.__webglTexture,ie)}else if(Fe){let De=j;for(let Ie=0;Ie<C.textures.length;Ie++){let qe=F.get(C.textures[Ie]);q.framebufferTextureLayer(q.FRAMEBUFFER,q.COLOR_ATTACHMENT0+Ie,qe.__webglTexture,ie,De)}}else if(C!==null&&ie!==0){let De=F.get(C.texture);q.framebufferTexture2D(q.FRAMEBUFFER,q.COLOR_ATTACHMENT0,q.TEXTURE_2D,De.__webglTexture,ie)}D=-1},this.readRenderTargetPixels=function(C,j,ie,ee,Q,Fe,We,De=0){if(!(C&&C.isWebGLRenderTarget)){et("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ie=F.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&We!==void 0&&(Ie=Ie[We]),Ie){Pe.bindFramebuffer(q.FRAMEBUFFER,Ie);try{let qe=C.textures[De],st=qe.format,at=qe.type;if(C.textures.length>1&&q.readBuffer(q.COLOR_ATTACHMENT0+De),!Tt.textureFormatReadable(st)){et("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!Tt.textureTypeReadable(at)){et("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}j>=0&&j<=C.width-ee&&ie>=0&&ie<=C.height-Q&&q.readPixels(j,ie,ee,Q,G.convert(st),G.convert(at),Fe)}finally{let qe=E!==null?F.get(E).__webglFramebuffer:null;Pe.bindFramebuffer(q.FRAMEBUFFER,qe)}}},this.readRenderTargetPixelsAsync=async function(C,j,ie,ee,Q,Fe,We,De=0){if(!(C&&C.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ie=F.get(C).__webglFramebuffer;if(C.isWebGLCubeRenderTarget&&We!==void 0&&(Ie=Ie[We]),Ie)if(j>=0&&j<=C.width-ee&&ie>=0&&ie<=C.height-Q){Pe.bindFramebuffer(q.FRAMEBUFFER,Ie);let qe=C.textures[De],st=qe.format,at=qe.type;if(C.textures.length>1&&q.readBuffer(q.COLOR_ATTACHMENT0+De),!Tt.textureFormatReadable(st))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Tt.textureTypeReadable(at))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Ye=q.createBuffer();q.bindBuffer(q.PIXEL_PACK_BUFFER,Ye),q.bufferData(q.PIXEL_PACK_BUFFER,Fe.byteLength,q.STREAM_READ),q.readPixels(j,ie,ee,Q,G.convert(st),G.convert(at),0);let Ct=E!==null?F.get(E).__webglFramebuffer:null;Pe.bindFramebuffer(q.FRAMEBUFFER,Ct);let Jt=q.fenceSync(q.SYNC_GPU_COMMANDS_COMPLETE,0);return q.flush(),await E0(q,Jt,4),q.bindBuffer(q.PIXEL_PACK_BUFFER,Ye),q.getBufferSubData(q.PIXEL_PACK_BUFFER,0,Fe),q.deleteBuffer(Ye),q.deleteSync(Jt),Fe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(C,j=null,ie=0){let ee=Math.pow(2,-ie),Q=Math.floor(C.image.width*ee),Fe=Math.floor(C.image.height*ee),We=j!==null?j.x:0,De=j!==null?j.y:0;M.setTexture2D(C,0),q.copyTexSubImage2D(q.TEXTURE_2D,ie,0,0,We,De,Q,Fe),Pe.unbindTexture()};let vc=q.createFramebuffer(),ni=q.createFramebuffer();this.copyTextureToTexture=function(C,j,ie=null,ee=null,Q=0,Fe=0){let We,De,Ie,qe,st,at,Ye,Ct,Jt,Wt=C.isCompressedTexture?C.mipmaps[Fe]:C.image;if(ie!==null)We=ie.max.x-ie.min.x,De=ie.max.y-ie.min.y,Ie=ie.isBox3?ie.max.z-ie.min.z:1,qe=ie.min.x,st=ie.min.y,at=ie.isBox3?ie.min.z:0;else{let Ft=Math.pow(2,-Q);We=Math.floor(Wt.width*Ft),De=Math.floor(Wt.height*Ft),C.isDataArrayTexture?Ie=Wt.depth:C.isData3DTexture?Ie=Math.floor(Wt.depth*Ft):Ie=1,qe=0,st=0,at=0}ee!==null?(Ye=ee.x,Ct=ee.y,Jt=ee.z):(Ye=0,Ct=0,Jt=0);let Mt=G.convert(j.format),Zt=G.convert(j.type),ze;j.isData3DTexture?(M.setTexture3D(j,0),ze=q.TEXTURE_3D):j.isDataArrayTexture||j.isCompressedArrayTexture?(M.setTexture2DArray(j,0),ze=q.TEXTURE_2D_ARRAY):(M.setTexture2D(j,0),ze=q.TEXTURE_2D),Pe.activeTexture(q.TEXTURE0),Pe.pixelStorei(q.UNPACK_FLIP_Y_WEBGL,j.flipY),Pe.pixelStorei(q.UNPACK_PREMULTIPLY_ALPHA_WEBGL,j.premultiplyAlpha),Pe.pixelStorei(q.UNPACK_ALIGNMENT,j.unpackAlignment);let Un=Pe.getParameter(q.UNPACK_ROW_LENGTH),vt=Pe.getParameter(q.UNPACK_IMAGE_HEIGHT),Xn=Pe.getParameter(q.UNPACK_SKIP_PIXELS),sn=Pe.getParameter(q.UNPACK_SKIP_ROWS),hn=Pe.getParameter(q.UNPACK_SKIP_IMAGES);Pe.pixelStorei(q.UNPACK_ROW_LENGTH,Wt.width),Pe.pixelStorei(q.UNPACK_IMAGE_HEIGHT,Wt.height),Pe.pixelStorei(q.UNPACK_SKIP_PIXELS,qe),Pe.pixelStorei(q.UNPACK_SKIP_ROWS,st),Pe.pixelStorei(q.UNPACK_SKIP_IMAGES,at);let kn=C.isDataArrayTexture||C.isData3DTexture,At=j.isDataArrayTexture||j.isData3DTexture;if(C.isDepthTexture){let Ft=F.get(C),Bn=F.get(j),It=F.get(Ft.__renderTarget),R=F.get(Bn.__renderTarget);Pe.bindFramebuffer(q.READ_FRAMEBUFFER,It.__webglFramebuffer),Pe.bindFramebuffer(q.DRAW_FRAMEBUFFER,R.__webglFramebuffer);for(let u=0;u<Ie;u++)kn&&(q.framebufferTextureLayer(q.READ_FRAMEBUFFER,q.COLOR_ATTACHMENT0,F.get(C).__webglTexture,Q,at+u),q.framebufferTextureLayer(q.DRAW_FRAMEBUFFER,q.COLOR_ATTACHMENT0,F.get(j).__webglTexture,Fe,Jt+u)),q.blitFramebuffer(qe,st,We,De,Ye,Ct,We,De,q.DEPTH_BUFFER_BIT,q.NEAREST);Pe.bindFramebuffer(q.READ_FRAMEBUFFER,null),Pe.bindFramebuffer(q.DRAW_FRAMEBUFFER,null)}else if(Q!==0||C.isRenderTargetTexture||F.has(C)){let Ft=F.get(C),Bn=F.get(j);Pe.bindFramebuffer(q.READ_FRAMEBUFFER,vc),Pe.bindFramebuffer(q.DRAW_FRAMEBUFFER,ni);for(let It=0;It<Ie;It++)kn?q.framebufferTextureLayer(q.READ_FRAMEBUFFER,q.COLOR_ATTACHMENT0,Ft.__webglTexture,Q,at+It):q.framebufferTexture2D(q.READ_FRAMEBUFFER,q.COLOR_ATTACHMENT0,q.TEXTURE_2D,Ft.__webglTexture,Q),At?q.framebufferTextureLayer(q.DRAW_FRAMEBUFFER,q.COLOR_ATTACHMENT0,Bn.__webglTexture,Fe,Jt+It):q.framebufferTexture2D(q.DRAW_FRAMEBUFFER,q.COLOR_ATTACHMENT0,q.TEXTURE_2D,Bn.__webglTexture,Fe),Q!==0?q.blitFramebuffer(qe,st,We,De,Ye,Ct,We,De,q.COLOR_BUFFER_BIT,q.NEAREST):At?q.copyTexSubImage3D(ze,Fe,Ye,Ct,Jt+It,qe,st,We,De):q.copyTexSubImage2D(ze,Fe,Ye,Ct,qe,st,We,De);Pe.bindFramebuffer(q.READ_FRAMEBUFFER,null),Pe.bindFramebuffer(q.DRAW_FRAMEBUFFER,null)}else At?C.isDataTexture||C.isData3DTexture?q.texSubImage3D(ze,Fe,Ye,Ct,Jt,We,De,Ie,Mt,Zt,Wt.data):j.isCompressedArrayTexture?q.compressedTexSubImage3D(ze,Fe,Ye,Ct,Jt,We,De,Ie,Mt,Wt.data):q.texSubImage3D(ze,Fe,Ye,Ct,Jt,We,De,Ie,Mt,Zt,Wt):C.isDataTexture?q.texSubImage2D(q.TEXTURE_2D,Fe,Ye,Ct,We,De,Mt,Zt,Wt.data):C.isCompressedTexture?q.compressedTexSubImage2D(q.TEXTURE_2D,Fe,Ye,Ct,Wt.width,Wt.height,Mt,Wt.data):q.texSubImage2D(q.TEXTURE_2D,Fe,Ye,Ct,We,De,Mt,Zt,Wt);Pe.pixelStorei(q.UNPACK_ROW_LENGTH,Un),Pe.pixelStorei(q.UNPACK_IMAGE_HEIGHT,vt),Pe.pixelStorei(q.UNPACK_SKIP_PIXELS,Xn),Pe.pixelStorei(q.UNPACK_SKIP_ROWS,sn),Pe.pixelStorei(q.UNPACK_SKIP_IMAGES,hn),Fe===0&&j.generateMipmaps&&q.generateMipmap(ze),Pe.unbindTexture()},this.initRenderTarget=function(C){F.get(C).__webglFramebuffer===void 0&&M.setupRenderTarget(C)},this.initTexture=function(C){C.isCubeTexture?M.setTextureCube(C,0):C.isData3DTexture?M.setTexture3D(C,0):C.isDataArrayTexture||C.isCompressedArrayTexture?M.setTexture2DArray(C,0):M.setTexture2D(C,0),Pe.unbindTexture()},this.resetState=function(){J=0,L=0,E=null,Pe.reset(),we.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Ci}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=ut._getDrawingBufferColorSpace(e),t.unpackColorSpace=ut._getUnpackColorSpace()}}});function Cs(i){let e=new Map,t=new Map,n=i.clone();return cb(i,n,function(r,s){e.set(s,r),t.set(r,s)}),n.traverse(function(r){if(!r.isSkinnedMesh)return;let s=r,a=e.get(r),o=a.skeleton.bones;s.skeleton=a.skeleton.clone(),s.bindMatrix.copy(a.bindMatrix),s.skeleton.bones=o.map(function(l){return t.get(l)}),s.bind(s.skeleton,s.bindMatrix)}),n}function cb(i,e,t){t(i,e);for(let n=0;n<i.children.length;n++)cb(i.children[n],e.children[n],t)}var wh=un(()=>{});var Mb={};Ar(Mb,{HDRLoader:()=>Df});var Df,Ab=un(()=>{Vn();Df=class extends xo{constructor(e){super(e),this.type=Gn}parse(e){let a=function(v,I){switch(v){case 1:throw new Error("THREE.HDRLoader: Read Error: "+(I||""));case 2:throw new Error("THREE.HDRLoader: Write Error: "+(I||""));case 3:throw new Error("THREE.HDRLoader: Bad File Format: "+(I||""));default:case 4:throw new Error("THREE.HDRLoader: Memory Error: "+(I||""))}},d=function(v,I,B){I=I||1024;let V=v.pos,J=-1,L=0,E="",D=String.fromCharCode.apply(null,new Uint16Array(v.subarray(V,V+128)));for(;0>(J=D.indexOf(`
+`))&&L<I&&V<v.byteLength;)E+=D,L+=D.length,V+=128,D=String.fromCharCode.apply(null,new Uint16Array(v.subarray(V,V+128)));return-1<J?(B!==!1&&(v.pos+=L+J+1),E+D.slice(0,J)):!1},f=function(v){let I=/^#\?(\S+)/,B=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,k=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,V=/^\s*FORMAT=(\S+)\s*$/,J=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,L={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0},E,D;for((v.pos>=v.byteLength||!(E=d(v)))&&a(1,"no header found"),(D=E.match(I))||a(3,"bad initial token"),L.valid|=1,L.programtype=D[1],L.string+=E+`
+`;E=d(v),E!==!1;){if(L.string+=E+`
+`,E.charAt(0)==="#"){L.comments+=E+`
+`;continue}if((D=E.match(B))&&(L.gamma=parseFloat(D[1])),(D=E.match(k))&&(L.exposure=parseFloat(D[1])),(D=E.match(V))&&(L.valid|=2,L.format=D[1]),(D=E.match(J))&&(L.valid|=4,L.height=parseInt(D[1],10),L.width=parseInt(D[2],10)),L.valid&2&&L.valid&4)break}return L.valid&2||a(3,"missing format specifier"),L.valid&4||a(3,"missing image size specifier"),L},p=function(v,I,B){let k=I;if(k<8||k>32767||v[0]!==2||v[1]!==2||v[2]&128)return new Uint8Array(v);k!==(v[2]<<8|v[3])&&a(3,"wrong scanline width");let V=new Uint8Array(4*I*B);V.length||a(4,"unable to allocate buffer space");let J=0,L=0,E=4*k,D=new Uint8Array(4),O=new Uint8Array(E),H=B;for(;H>0&&L<v.byteLength;){L+4>v.byteLength&&a(1),D[0]=v[L++],D[1]=v[L++],D[2]=v[L++],D[3]=v[L++],(D[0]!=2||D[1]!=2||(D[2]<<8|D[3])!=k)&&a(3,"bad rgbe scanline format");let Y=0,le;for(;Y<E&&L<v.byteLength;){le=v[L++];let be=le>128;if(be&&(le-=128),(le===0||Y+le>E)&&a(3,"bad scanline data"),be){let Te=v[L++];for(let Je=0;Je<le;Je++)O[Y++]=Te}else O.set(v.subarray(L,L+le),Y),Y+=le,L+=le}let fe=k;for(let be=0;be<fe;be++){let Te=0;V[J]=O[be+Te],Te+=k,V[J+1]=O[be+Te],Te+=k,V[J+2]=O[be+Te],Te+=k,V[J+3]=O[be+Te],J+=4}H--}return V},x=function(v,I,B,k){let V=v[I+3],J=Math.pow(2,V-128)/255;B[k+0]=v[I+0]*J,B[k+1]=v[I+1]*J,B[k+2]=v[I+2]*J,B[k+3]=1},y=function(v,I,B,k){let V=v[I+3],J=Math.pow(2,V-128)/255;B[k+0]=Fr.toHalfFloat(Math.min(v[I+0]*J,65504)),B[k+1]=Fr.toHalfFloat(Math.min(v[I+1]*J,65504)),B[k+2]=Fr.toHalfFloat(Math.min(v[I+2]*J,65504)),B[k+3]=Fr.toHalfFloat(1)},b=new Uint8Array(e);b.pos=0;let g=f(b),S=g.width,A=g.height,T=p(b.subarray(b.pos),S,A),N,P,U;switch(this.type){case Tn:U=T.length/4;let v=new Float32Array(U*4);for(let B=0;B<U;B++)x(T,B*4,v,B*4);N=v,P=Tn;break;case Gn:U=T.length/4;let I=new Uint16Array(U*4);for(let B=0;B<U;B++)y(T,B*4,I,B*4);N=I,P=Gn;break;default:throw new Error("THREE.HDRLoader: Unsupported type: "+this.type)}return{width:S,height:A,data:N,header:g.string,gamma:g.gamma,exposure:g.exposure,type:P}}setDataType(e){return this.type=e,this}load(e,t,n,r){function s(a,o){switch(a.type){case Tn:case Gn:a.colorSpace=bn,a.minFilter=zt,a.magFilter=zt,a.generateMipmaps=!1,a.flipY=!0;break}t&&t(a,o)}return super.load(e,s,n,r)}}});function Bf(i,e){if(e===kd)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),i;if(e===ya||e===ko){let t=i.getIndex();if(t===null){let a=[],o=i.getAttribute("position");if(o!==void 0){for(let l=0;l<o.count;l++)a.push(l);i.setIndex(a),t=i.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),i}let n=t.count-2,r=[];if(e===ya)for(let a=1;a<=n;a++)r.push(t.getX(0)),r.push(t.getX(a)),r.push(t.getX(a+1));else for(let a=0;a<n;a++)a%2===0?(r.push(t.getX(a)),r.push(t.getX(a+1)),r.push(t.getX(a+2))):(r.push(t.getX(a+2)),r.push(t.getX(a+1)),r.push(t.getX(a)));r.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let s=i.clone();return s.setIndex(r),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),i}var Fb=un(()=>{Vn()});function nE(){let i={};return{get:function(e){return i[e]},add:function(e,t){i[e]=t},remove:function(e){delete i[e]},removeAll:function(){i={}}}}function cn(i,e,t){let n=i.json.materials[e];return n.extensions&&n.extensions[t]?n.extensions[t]:null}function sE(i){return i.DefaultMaterial===void 0&&(i.DefaultMaterial=new gi({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Pi})),i.DefaultMaterial}function Ds(i,e,t){for(let n in t.extensions)i[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function nr(i,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(i.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function aE(i,e,t){let n=!1,r=!1,s=!1;for(let c=0,h=e.length;c<h;c++){let d=e[c];if(d.POSITION!==void 0&&(n=!0),d.NORMAL!==void 0&&(r=!0),d.COLOR_0!==void 0&&(s=!0),n&&r&&s)break}if(!n&&!r&&!s)return Promise.resolve(i);let a=[],o=[],l=[];for(let c=0,h=e.length;c<h;c++){let d=e[c];if(n){let f=d.POSITION!==void 0?t.getDependency("accessor",d.POSITION):i.attributes.position;a.push(f)}if(r){let f=d.NORMAL!==void 0?t.getDependency("accessor",d.NORMAL):i.attributes.normal;o.push(f)}if(s){let f=d.COLOR_0!==void 0?t.getDependency("accessor",d.COLOR_0):i.attributes.color;l.push(f)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(c){let h=c[0],d=c[1],f=c[2];return n&&(i.morphAttributes.position=h),r&&(i.morphAttributes.normal=d),s&&(i.morphAttributes.color=f),i.morphTargetsRelative=!0,i})}function oE(i,e){if(i.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)i.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){let t=e.extras.targetNames;if(i.morphTargetInfluences.length===t.length){i.morphTargetDictionary={};for(let n=0,r=t.length;n<r;n++)i.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function cE(i){let e,t=i.extensions&&i.extensions[_t.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Gf(t.attributes):e=i.indices+":"+Gf(i.attributes)+":"+i.mode,i.targets!==void 0)for(let n=0,r=i.targets.length;n<r;n++)e+=":"+Gf(i.targets[n]);return e}function Gf(i){let e="",t=Object.keys(i).sort();for(let n=0,r=t.length;n<r;n++)e+=t[n]+":"+i[t[n]]+";";return e}function dp(i){switch(i){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function lE(i){return i.search(/\.jpe?g($|\?)/i)>0||i.search(/^data\:image\/jpeg/)===0?"image/jpeg":i.search(/\.webp($|\?)/i)>0||i.search(/^data\:image\/webp/)===0?"image/webp":i.search(/\.ktx2($|\?)/i)>0||i.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}function uE(i,e,t){let n=e.attributes,r=new rn;if(n.POSITION!==void 0){let o=t.json.accessors[n.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(r.set(new W(l[0],l[1],l[2]),new W(c[0],c[1],c[2])),o.normalized){let h=dp(Pa[o.componentType]);r.min.multiplyScalar(h),r.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let s=e.targets;if(s!==void 0){let o=new W,l=new W;for(let c=0,h=s.length;c<h;c++){let d=s[c];if(d.POSITION!==void 0){let f=t.json.accessors[d.POSITION],p=f.min,x=f.max;if(p!==void 0&&x!==void 0){if(l.setX(Math.max(Math.abs(p[0]),Math.abs(x[0]))),l.setY(Math.max(Math.abs(p[1]),Math.abs(x[1]))),l.setZ(Math.max(Math.abs(p[2]),Math.abs(x[2]))),f.normalized){let y=dp(Pa[f.componentType]);l.multiplyScalar(y)}o.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(o)}i.boundingBox=r;let a=new Yn;r.getCenter(a.center),a.radius=r.min.distanceTo(r.max)/2,i.boundingSphere=a}function zb(i,e,t){let n=e.attributes,r=[];function s(a,o){return t.getDependency("accessor",a).then(function(l){i.setAttribute(o,l)})}for(let a in n){let o=up[a]||a.toLowerCase();o in i.attributes||r.push(s(n[a],o))}if(e.indices!==void 0&&!i.index){let a=t.getDependency("accessor",e.indices).then(function(o){i.setIndex(o)});r.push(a)}return ut.workingColorSpace!==bn&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ut.workingColorSpace}" not supported.`),nr(i,e),uE(i,e,t),Promise.all(r).then(function(){return e.targets!==void 0?aE(i,e.targets,t):i})}var kh,_t,Vf,Wf,qf,$f,jf,Xf,Kf,Yf,Jf,Zf,Qf,ep,tp,np,ip,rp,Bh,sp,Hb,jo,Ub,ap,op,cp,lp,zh,iE,hp,_i,Pa,kb,Bb,zf,up,Yr,rE,Hf,hE,fp,Gb=un(()=>{Vn();Fb();wh();kh=class extends oi{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new $f(t)}),this.register(function(t){return new jf(t)}),this.register(function(t){return new np(t)}),this.register(function(t){return new ip(t)}),this.register(function(t){return new rp(t)}),this.register(function(t){return new Kf(t)}),this.register(function(t){return new Yf(t)}),this.register(function(t){return new Jf(t)}),this.register(function(t){return new Zf(t)}),this.register(function(t){return new qf(t)}),this.register(function(t){return new Qf(t)}),this.register(function(t){return new Xf(t)}),this.register(function(t){return new tp(t)}),this.register(function(t){return new ep(t)}),this.register(function(t){return new Vf(t)}),this.register(function(t){return new Bh(t,_t.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new Bh(t,_t.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new sp(t)})}load(e,t,n,r){let s=this,a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){let c=br.extractUrlBase(e);a=br.resolveURL(c,this.path)}else a=br.extractUrlBase(e);this.manager.itemStart(e);let o=function(c){r?r(c):console.error(c),s.manager.itemError(e),s.manager.itemEnd(e)},l=new Yi(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{s.parse(c,a,function(h){t(h),s.manager.itemEnd(e)},o)}catch(h){o(h)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let s,a={},o={},l=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===Hb){try{a[_t.KHR_BINARY_GLTF]=new ap(e)}catch(d){r&&r(d);return}s=JSON.parse(a[_t.KHR_BINARY_GLTF].content)}else s=JSON.parse(l.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){r&&r(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let c=new fp(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h<this.pluginCallbacks.length;h++){let d=this.pluginCallbacks[h](c);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),o[d.name]=d,a[d.name]=!0}if(s.extensionsUsed)for(let h=0;h<s.extensionsUsed.length;++h){let d=s.extensionsUsed[h],f=s.extensionsRequired||[];switch(d){case _t.KHR_MATERIALS_UNLIT:a[d]=new Wf;break;case _t.KHR_DRACO_MESH_COMPRESSION:a[d]=new op(s,this.dracoLoader);break;case _t.KHR_TEXTURE_TRANSFORM:a[d]=new cp;break;case _t.KHR_MESH_QUANTIZATION:a[d]=new lp;break;default:f.indexOf(d)>=0&&o[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,s){n.parse(e,t,r,s)})}};_t={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},Vf=class{constructor(e){this.parser=e,this.name=_t.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){let s=t[n];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n="light:"+e,r=t.cache.get(n);if(r)return r;let s=t.json,l=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e],c,h=new Ve(16777215);l.color!==void 0&&h.setRGB(l.color[0],l.color[1],l.color[2],bn);let d=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new Di(h),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new ws(h),c.distance=d;break;case"spot":c=new So(h),c.distance=d,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),nr(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),r=Promise.resolve(c),t.cache.add(n,r),r}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,s=n.json.nodes[e],o=(s.extensions&&s.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(l){return n._getNodeRef(t.cache,o,l)})}},Wf=class{constructor(){this.name=_t.KHR_MATERIALS_UNLIT}getMaterialType(){return gn}extendParams(e,t,n){let r=[];e.color=new Ve(1,1,1),e.opacity=1;let s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){let a=s.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],bn),e.opacity=a[3]}s.baseColorTexture!==void 0&&r.push(n.assignTexture(e,"map",s.baseColorTexture,Xt))}return Promise.all(r)}},qf=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);return n===null||n.emissiveStrength!==void 0&&(t.emissiveIntensity=n.emissiveStrength),Promise.resolve()}},$f=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(n.clearcoatFactor!==void 0&&(t.clearcoat=n.clearcoatFactor),n.clearcoatTexture!==void 0&&r.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture)),n.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=n.clearcoatRoughnessFactor),n.clearcoatRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture)),n.clearcoatNormalTexture!==void 0&&(r.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0)){let s=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new dt(s,s)}return Promise.all(r)}},jf=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_DISPERSION}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);return n===null||(t.dispersion=n.dispersion!==void 0?n.dispersion:0),Promise.resolve()}},Xf=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.iridescenceFactor!==void 0&&(t.iridescence=n.iridescenceFactor),n.iridescenceTexture!==void 0&&r.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture)),n.iridescenceIor!==void 0&&(t.iridescenceIOR=n.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),n.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum),n.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum),n.iridescenceThicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture)),Promise.all(r)}},Kf=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_SHEEN}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];if(t.sheenColor=new Ve(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){let s=n.sheenColorFactor;t.sheenColor.setRGB(s[0],s[1],s[2],bn)}return n.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=n.sheenRoughnessFactor),n.sheenColorTexture!==void 0&&r.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,Xt)),n.sheenRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture)),Promise.all(r)}},Yf=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.transmissionFactor!==void 0&&(t.transmission=n.transmissionFactor),n.transmissionTexture!==void 0&&r.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture)),Promise.all(r)}},Jf=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_VOLUME}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture)),t.attenuationDistance=n.attenuationDistance||1/0;let s=n.attenuationColor||[1,1,1];return t.attenuationColor=new Ve().setRGB(s[0],s[1],s[2],bn),Promise.all(r)}},Zf=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_IOR}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);return n===null||(t.ior=n.ior!==void 0?n.ior:1.5,t.ior===0&&(t.ior=1e3)),Promise.resolve()}},Qf=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_SPECULAR}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];t.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0&&r.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));let s=n.specularColorFactor||[1,1,1];return t.specularColor=new Ve().setRGB(s[0],s[1],s[2],bn),n.specularColorTexture!==void 0&&r.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,Xt)),Promise.all(r)}},ep=class{constructor(e){this.parser=e,this.name=_t.EXT_MATERIALS_BUMP}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return t.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0&&r.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture)),Promise.all(r)}},tp=class{constructor(e){this.parser=e,this.name=_t.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return cn(this.parser,e,this.name)!==null?Jn:null}extendMaterialParams(e,t){let n=cn(this.parser,e,this.name);if(n===null)return Promise.resolve();let r=[];return n.anisotropyStrength!==void 0&&(t.anisotropy=n.anisotropyStrength),n.anisotropyRotation!==void 0&&(t.anisotropyRotation=n.anisotropyRotation),n.anisotropyTexture!==void 0&&r.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture)),Promise.all(r)}},np=class{constructor(e){this.parser=e,this.name=_t.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let s=r.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}},ip=class{constructor(e){this.parser=e,this.name=_t.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=r.images[a.source],l=n.textureLoader;if(o.uri){let c=n.options.manager.getHandler(o.uri);c!==null&&(l=c)}return n.loadTextureImage(e,a.source,l)}},rp=class{constructor(e){this.parser=e,this.name=_t.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=r.images[a.source],l=n.textureLoader;if(o.uri){let c=n.options.manager.getHandler(o.uri);c!==null&&(l=c)}return n.loadTextureImage(e,a.source,l)}},Bh=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let r=n.extensions[this.name],s=this.parser.getDependency("buffer",r.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(o){let l=r.byteOffset||0,c=r.byteLength||0,h=r.count,d=r.byteStride,f=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(h,d,f,r.mode,r.filter).then(function(p){return p.buffer}):a.ready.then(function(){let p=new ArrayBuffer(h*d);return a.decodeGltfBuffer(new Uint8Array(p),h,d,f,r.mode,r.filter),p})})}else return null}},sp=class{constructor(e){this.name=_t.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let c of r.primitives)if(c.mode!==_i.TRIANGLES&&c.mode!==_i.TRIANGLE_STRIP&&c.mode!==_i.TRIANGLE_FAN&&c.mode!==void 0)return null;let a=n.extensions[this.name].attributes,o=[],l={};for(let c in a)o.push(this.parser.getDependency("accessor",a[c]).then(h=>(l[c]=h,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{let h=c.pop(),d=h.isGroup?h.children:[h],f=c[0].count,p=[];for(let x of d){let y=new ot,b=new W,g=new Pt,S=new W(1,1,1),A=new _s(x.geometry,x.material,f);for(let T=0;T<f;T++)l.TRANSLATION&&b.fromBufferAttribute(l.TRANSLATION,T),l.ROTATION&&g.fromBufferAttribute(l.ROTATION,T),l.SCALE&&S.fromBufferAttribute(l.SCALE,T),A.setMatrixAt(T,y.compose(b,g,S));for(let T in l)if(T==="_COLOR_0"){let N=l[T];A.instanceColor=new zr(N.array,N.itemSize,N.normalized)}else T!=="TRANSLATION"&&T!=="ROTATION"&&T!=="SCALE"&&x.geometry.setAttribute(T,l[T]);qt.prototype.copy.call(A,x),this.parser.assignFinalMaterial(A),p.push(A)}return h.isGroup?(h.clear(),h.add(...p),h):p[0]}))}},Hb="glTF",jo=12,Ub={JSON:1313821514,BIN:5130562},ap=class{constructor(e){this.name=_t.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,jo),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Hb)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");let r=this.header.length-jo,s=new DataView(e,jo),a=0;for(;a<r;){let o=s.getUint32(a,!0);a+=4;let l=s.getUint32(a,!0);if(a+=4,l===Ub.JSON){let c=new Uint8Array(e,jo+a,o);this.content=n.decode(c)}else if(l===Ub.BIN){let c=jo+a;this.body=e.slice(c,c+o)}a+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},op=class{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=_t.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,r=this.dracoLoader,s=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(let h in a){let d=up[h]||h.toLowerCase();o[d]=a[h]}for(let h in e.attributes){let d=up[h]||h.toLowerCase();if(a[h]!==void 0){let f=n.accessors[e.attributes[h]],p=Pa[f.componentType];c[d]=p.name,l[d]=f.normalized===!0}}return t.getDependency("bufferView",s).then(function(h){return new Promise(function(d,f){r.decodeDracoFile(h,function(p){for(let x in p.attributes){let y=p.attributes[x],b=l[x];b!==void 0&&(y.normalized=b)}d(p)},o,c,bn,f)})})}},cp=class{constructor(){this.name=_t.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}},lp=class{constructor(){this.name=_t.KHR_MESH_QUANTIZATION}},zh=class extends $i{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,s=e*r*3+r;for(let a=0;a!==r;a++)t[a]=n[s+a];return t}interpolate_(e,t,n,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=o*2,c=o*3,h=r-t,d=(n-t)/h,f=d*d,p=f*d,x=e*c,y=x-c,b=-2*p+3*f,g=p-f,S=1-b,A=g-f+d;for(let T=0;T!==o;T++){let N=a[y+T+o],P=a[y+T+l]*h,U=a[x+T+o],v=a[x+T]*h;s[T]=S*N+A*P+b*U+g*v}return s}},iE=new Pt,hp=class extends zh{interpolate_(e,t,n,r){let s=super.interpolate_(e,t,n,r);return iE.fromArray(s).normalize().toArray(s),s}},_i={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},Pa={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},kb={9728:on,9729:zt,9984:Pl,9985:ga,9986:Ts,9987:xi},Bb={33071:Kn,33648:ra,10497:Nr},zf={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},up={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Yr={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},rE={CUBICSPLINE:void 0,LINEAR:gs,STEP:ms},Hf={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};hE=new ot,fp=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new nE,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,s=!1,a=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){let o=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(o)===!0;let l=o.match(/Version\/(\d+)/);r=n&&l?parseInt(l[1],10):-1,s=o.indexOf("Firefox")>-1,a=s?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&r<17||s&&a<98?this.textureLoader=new _o(this.options.manager):this.textureLoader=new Mo(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Yi(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(a){let o={scene:a[0][r.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:r.asset,parser:n,userData:{}};return Ds(s,o,r),nr(o,r),Promise.all(n._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(let l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let r=0,s=t.length;r<s;r++){let a=t[r].joints;for(let o=0,l=a.length;o<l;o++)e[a[o]].isBone=!0}for(let r=0,s=e.length;r<s;r++){let a=e[r];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(n[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;let r=n.clone(),s=(a,o)=>{let l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(let[c,h]of a.children.entries())s(h,o.children[c])};return s(n,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let r=0;r<t.length;r++){let s=e(t[r]);s&&n.push(s)}return n}getDependency(e,t){let n=e+":"+t,r=this.cache.get(n);if(!r){switch(e){case"scene":r=this.loadScene(t);break;case"node":r=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":r=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":r=this.loadAccessor(t);break;case"bufferView":r=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":r=this.loadBuffer(t);break;case"material":r=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":r=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":r=this.loadSkin(t);break;case"animation":r=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!r)throw new Error("Unknown type: "+e);break}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,r=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(r.map(function(s,a){return n.getDependency(e,a)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[_t.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(s,a){n.load(br.resolveURL(t.uri,r.path),s,void 0,function(){a(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){let r=t.byteLength||0,s=t.byteOffset||0;return n.slice(s,s+r)})}loadAccessor(e){let t=this,n=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let a=zf[r.type],o=Pa[r.componentType],l=r.normalized===!0,c=new o(r.count*a);return Promise.resolve(new Kt(c,a,l))}let s=[];return r.bufferView!==void 0?s.push(this.getDependency("bufferView",r.bufferView)):s.push(null),r.sparse!==void 0&&(s.push(this.getDependency("bufferView",r.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",r.sparse.values.bufferView))),Promise.all(s).then(function(a){let o=a[0],l=zf[r.type],c=Pa[r.componentType],h=c.BYTES_PER_ELEMENT,d=h*l,f=r.byteOffset||0,p=r.bufferView!==void 0?n.bufferViews[r.bufferView].byteStride:void 0,x=r.normalized===!0,y,b;if(p&&p!==d){let g=Math.floor(f/p),S="InterleavedBuffer:"+r.bufferView+":"+r.componentType+":"+g+":"+r.count,A=t.cache.get(S);A||(y=new c(o,g*p,r.count*p/h),A=new Ur(y,p/h),t.cache.add(S,A)),b=new kr(A,l,f%p/h,x)}else o===null?y=new c(r.count*l):y=new c(o,f,r.count*l),b=new Kt(y,l,x);if(r.sparse!==void 0){let g=zf.SCALAR,S=Pa[r.sparse.indices.componentType],A=r.sparse.indices.byteOffset||0,T=r.sparse.values.byteOffset||0,N=new S(a[1],A,r.sparse.count*g),P=new c(a[2],T,r.sparse.count*l);o!==null&&(b=new Kt(b.array.slice(),b.itemSize,b.normalized)),b.normalized=!1;for(let U=0,v=N.length;U<v;U++){let I=N[U];if(b.setX(I,P[U*l]),l>=2&&b.setY(I,P[U*l+1]),l>=3&&b.setZ(I,P[U*l+2]),l>=4&&b.setW(I,P[U*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}b.normalized=x}return b})}loadTexture(e){let t=this.json,n=this.options,s=t.textures[e].source,a=t.images[s],o=this.textureLoader;if(a.uri){let l=n.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,n){let r=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];let c=this.loadImageSource(t,n).then(function(h){h.flipY=!1,h.name=a.name||o.name||"",h.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(h.name=o.uri);let f=(s.samplers||{})[a.sampler]||{};return h.magFilter=kb[f.magFilter]||zt,h.minFilter=kb[f.minFilter]||xi,h.wrapS=Bb[f.wrapS]||Nr,h.wrapT=Bb[f.wrapT]||Nr,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==on&&h.minFilter!==zt,r.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){let n=this,r=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());let a=r.images[e],o=self.URL||self.webkitURL,l=a.uri||"",c=!1;if(a.bufferView!==void 0)l=n.getDependency("bufferView",a.bufferView).then(function(d){c=!0;let f=new Blob([d],{type:a.mimeType});return l=o.createObjectURL(f),l});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let h=Promise.resolve(l).then(function(d){return new Promise(function(f,p){let x=f;t.isImageBitmapLoader===!0&&(x=function(y){let b=new xn(y);b.needsUpdate=!0,f(b)}),t.load(br.resolveURL(d,s.path),x,void 0,p)})}).then(function(d){return c===!0&&o.revokeObjectURL(l),nr(d,a),d.userData.mimeType=a.mimeType||lE(a.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=h,h}assignTexture(e,t,n,r){let s=this;return this.getDependency("texture",n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),s.extensions[_t.KHR_TEXTURE_TRANSFORM]){let o=n.extensions!==void 0?n.extensions[_t.KHR_TEXTURE_TRANSFORM]:void 0;if(o){let l=s.associations.get(a);a=s.extensions[_t.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,l)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let o="PointsMaterial:"+n.uuid,l=this.cache.get(o);l||(l=new pa,Ln.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,l.sizeAttenuation=!1,this.cache.add(o,l)),n=l}else if(e.isLine){let o="LineBasicMaterial:"+n.uuid,l=this.cache.get(o);l||(l=new ys,Ln.prototype.copy.call(l,n),l.color.copy(n.color),l.map=n.map,this.cache.add(o,l)),n=l}if(r||s||a){let o="ClonedMaterial:"+n.uuid+":";r&&(o+="derivative-tangents:"),s&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=n.clone(),s&&(l.vertexColors=!0),a&&(l.flatShading=!0),r&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(n))),n=l}e.material=n}getMaterialType(){return gi}loadMaterial(e){let t=this,n=this.json,r=this.extensions,s=n.materials[e],a,o={},l=s.extensions||{},c=[];if(l[_t.KHR_MATERIALS_UNLIT]){let d=r[_t.KHR_MATERIALS_UNLIT];a=d.getMaterialType(),c.push(d.extendParams(o,s,t))}else{let d=s.pbrMetallicRoughness||{};if(o.color=new Ve(1,1,1),o.opacity=1,Array.isArray(d.baseColorFactor)){let f=d.baseColorFactor;o.color.setRGB(f[0],f[1],f[2],bn),o.opacity=f[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",d.baseColorTexture,Xt)),o.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,o.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",d.metallicRoughnessTexture))),a=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,o)})))}s.doubleSided===!0&&(o.side=Dn);let h=s.alphaMode||Hf.OPAQUE;if(h===Hf.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,h===Hf.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==gn&&(c.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new dt(1,1),s.normalTexture.scale!==void 0)){let d=s.normalTexture.scale;o.normalScale.set(d,d)}if(s.occlusionTexture!==void 0&&a!==gn&&(c.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==gn){let d=s.emissiveFactor;o.emissive=new Ve().setRGB(d[0],d[1],d[2],bn)}return s.emissiveTexture!==void 0&&a!==gn&&c.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,Xt)),Promise.all(c).then(function(){let d=new a(o);return s.name&&(d.name=s.name),nr(d,s),t.associations.set(d,{materials:e}),s.extensions&&Ds(r,d,s),d})}createUniqueName(e){let t=Ut.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function s(o){return n[_t.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return zb(l,o,t)})}let a=[];for(let o=0,l=e.length;o<l;o++){let c=e[o],h=cE(c),d=r[h];if(d)a.push(d.promise);else{let f;c.extensions&&c.extensions[_t.KHR_DRACO_MESH_COMPRESSION]?f=s(c):f=zb(new mn,c,t),r[h]={primitive:c,promise:f},a.push(f)}}return Promise.all(a)}loadMesh(e){let t=this,n=this.json,r=this.extensions,s=n.meshes[e],a=s.primitives,o=[];for(let l=0,c=a.length;l<c;l++){let h=a[l].material===void 0?sE(this.cache):this.getDependency("material",a[l].material);o.push(h)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(l){let c=l.slice(0,l.length-1),h=l[l.length-1],d=[];for(let p=0,x=h.length;p<x;p++){let y=h[p],b=a[p],g,S=c[p];if(b.mode===_i.TRIANGLES||b.mode===_i.TRIANGLE_STRIP||b.mode===_i.TRIANGLE_FAN||b.mode===void 0)g=s.isSkinnedMesh===!0?new so(y,S):new xt(y,S),g.isSkinnedMesh===!0&&g.normalizeSkinWeights(),b.mode===_i.TRIANGLE_STRIP?g.geometry=Bf(g.geometry,ko):b.mode===_i.TRIANGLE_FAN&&(g.geometry=Bf(g.geometry,ya));else if(b.mode===_i.LINES)g=new fa(y,S);else if(b.mode===_i.LINE_STRIP)g=new vs(y,S);else if(b.mode===_i.LINE_LOOP)g=new oo(y,S);else if(b.mode===_i.POINTS)g=new co(y,S);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+b.mode);Object.keys(g.geometry.morphAttributes).length>0&&oE(g,s),g.name=t.createUniqueName(s.name||"mesh_"+e),nr(g,s),b.extensions&&Ds(r,g,b),t.assignFinalMaterial(g),d.push(g)}for(let p=0,x=d.length;p<x;p++)t.associations.set(d[p],{meshes:e,primitives:p});if(d.length===1)return s.extensions&&Ds(r,d[0],s),d[0];let f=new pn;s.extensions&&Ds(r,f,s),t.associations.set(f,{meshes:e});for(let p=0,x=d.length;p<x;p++)f.add(d[p]);return f})}loadCamera(e){let t,n=this.json.cameras[e],r=n[n.type];if(!r){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new an(Hd.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):n.type==="orthographic"&&(t=new Wr(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),nr(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let r=0,s=t.joints.length;r<s;r++)n.push(this._loadNodeShallow(t.joints[r]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(r){let s=r.pop(),a=r,o=[],l=[];for(let c=0,h=a.length;c<h;c++){let d=a[c];if(d){o.push(d);let f=new ot;s!==null&&f.fromArray(s.array,c*16),l.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new ao(o,l)})}loadAnimation(e){let t=this.json,n=this,r=t.animations[e],s=r.name?r.name:"animation_"+e,a=[],o=[],l=[],c=[],h=[];for(let d=0,f=r.channels.length;d<f;d++){let p=r.channels[d],x=r.samplers[p.sampler],y=p.target,b=y.node,g=r.parameters!==void 0?r.parameters[x.input]:x.input,S=r.parameters!==void 0?r.parameters[x.output]:x.output;y.node!==void 0&&(a.push(this.getDependency("node",b)),o.push(this.getDependency("accessor",g)),l.push(this.getDependency("accessor",S)),c.push(x),h.push(y))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(h)]).then(function(d){let f=d[0],p=d[1],x=d[2],y=d[3],b=d[4],g=[];for(let A=0,T=f.length;A<T;A++){let N=f[A],P=p[A],U=x[A],v=y[A],I=b[A];if(N===void 0)continue;N.updateMatrix&&N.updateMatrix();let B=n._createAnimationTracks(N,P,U,v,I);if(B)for(let k=0;k<B.length;k++)g.push(B[k])}let S=new bi(s,void 0,g);return nr(S,r),S})}createNodeMesh(e){let t=this.json,n=this,r=t.nodes[e];return r.mesh===void 0?null:n.getDependency("mesh",r.mesh).then(function(s){let a=n._getNodeRef(n.meshCache,r.mesh,s);return r.weights!==void 0&&a.traverse(function(o){if(o.isMesh)for(let l=0,c=r.weights.length;l<c;l++)o.morphTargetInfluences[l]=r.weights[l]}),a})}loadNode(e){let t=this.json,n=this,r=t.nodes[e],s=n._loadNodeShallow(e),a=[],o=r.children||[];for(let c=0,h=o.length;c<h;c++)a.push(n.getDependency("node",o[c]));let l=r.skin===void 0?Promise.resolve(null):n.getDependency("skin",r.skin);return Promise.all([s,Promise.all(a),l]).then(function(c){let h=c[0],d=c[1],f=c[2];f!==null&&h.traverse(function(p){p.isSkinnedMesh&&p.bind(f,hE)});for(let p=0,x=d.length;p<x;p++)h.add(d[p]);if(h.userData.pivot!==void 0&&d.length>0){let p=h.userData.pivot,x=d[0];h.pivot=new W().fromArray(p),h.position.x-=p[0],h.position.y-=p[1],h.position.z-=p[2],x.position.set(0,0,0),delete h.userData.pivot}return h})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let s=t.nodes[e],a=s.name?r.createUniqueName(s.name):"",o=[],l=r._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),s.camera!==void 0&&o.push(r.getDependency("camera",s.camera).then(function(c){return r._getNodeRef(r.cameraCache,s.camera,c)})),r._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){o.push(c)}),this.nodeCache[e]=Promise.all(o).then(function(c){let h;if(s.isBone===!0?h=new ua:c.length>1?h=new pn:c.length===1?h=c[0]:h=new qt,h!==c[0])for(let d=0,f=c.length;d<f;d++)h.add(c[d]);if(s.name&&(h.userData.name=s.name,h.name=a),nr(h,s),s.extensions&&Ds(n,h,s),s.matrix!==void 0){let d=new ot;d.fromArray(s.matrix),h.applyMatrix4(d)}else s.translation!==void 0&&h.position.fromArray(s.translation),s.rotation!==void 0&&h.quaternion.fromArray(s.rotation),s.scale!==void 0&&h.scale.fromArray(s.scale);if(!r.associations.has(h))r.associations.set(h,{});else if(s.mesh!==void 0&&r.meshCache.refs[s.mesh]>1){let d=r.associations.get(h);r.associations.set(h,{...d})}return r.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,s=new pn;n.name&&(s.name=r.createUniqueName(n.name)),nr(s,n),n.extensions&&Ds(t,s,n);let a=n.nodes||[],o=[];for(let l=0,c=a.length;l<c;l++)o.push(r.getDependency("node",a[l]));return Promise.all(o).then(function(l){for(let h=0,d=l.length;h<d;h++){let f=l[h];f.parent!==null?s.add(Cs(f)):s.add(f)}let c=h=>{let d=new Map;for(let[f,p]of r.associations)(f instanceof Ln||f instanceof xn)&&d.set(f,p);return h.traverse(f=>{let p=r.associations.get(f);p!=null&&d.set(f,p)}),d};return r.associations=c(s),s})}_createAnimationTracks(e,t,n,r,s){let a=[],o=e.name?e.name:e.uuid,l=[];function c(p){p.morphTargetInfluences&&l.push(p.name?p.name:p.uuid)}Yr[s.path]===Yr.weights?(c(e),e.isGroup&&e.children.forEach(c)):l.push(o);let h;switch(Yr[s.path]){case Yr.weights:h=ji;break;case Yr.rotation:h=Xi;break;case Yr.translation:case Yr.scale:h=Ki;break;default:n.itemSize===1?h=ji:h=Ki;break}let d=r.interpolation!==void 0?rE[r.interpolation]:gs,f=this._getArrayFromAccessor(n);for(let p=0,x=l.length;p<x;p++){let y=new h(l[p]+"."+Yr[s.path],t.array,f,d);r.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(y),a.push(y)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let n=dp(t.constructor),r=new Float32Array(t.length);for(let s=0,a=t.length;s<a;s++)r[s]=t[s]*n;t=r}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){let r=this instanceof Xi?hp:zh;return new r(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}});function dE(){let i,e;onmessage=function(a){let o=a.data;switch(o.type){case"init":i=o.decoderConfig,e=new Promise(function(h){i.onModuleLoaded=function(d){h({draco:d})},DracoDecoderModule(i)});break;case"decode":let l=o.buffer,c=o.taskConfig;e.then(h=>{let d=h.draco,f=new d.Decoder;try{let p=t(d,f,new Int8Array(l),c),x=p.attributes.map(y=>y.array.buffer);p.index&&x.push(p.index.array.buffer),self.postMessage({type:"decode",id:o.id,geometry:p},x)}catch(p){console.error(p),self.postMessage({type:"error",id:o.id,error:p.message})}finally{d.destroy(f)}});break}};function t(a,o,l,c){let h=c.attributeIDs,d=c.attributeTypes,f,p,x=o.GetEncodedGeometryType(l);if(x===a.TRIANGULAR_MESH)f=new a.Mesh,p=o.DecodeArrayToMesh(l,l.byteLength,f);else if(x===a.POINT_CLOUD)f=new a.PointCloud,p=o.DecodeArrayToPointCloud(l,l.byteLength,f);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!p.ok()||f.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+p.error_msg());let y={index:null,attributes:[]};for(let b in h){let g=self[d[b]],S,A;if(c.useUniqueIDs)A=h[b],S=o.GetAttributeByUniqueId(f,A);else{if(A=o.GetAttributeId(f,a[h[b]]),A===-1)continue;S=o.GetAttribute(f,A)}let T=r(a,o,f,b,g,S);b==="color"&&(T.vertexColorSpace=c.vertexColorSpace),y.attributes.push(T)}return x===a.TRIANGULAR_MESH&&(y.index=n(a,o,f)),a.destroy(f),y}function n(a,o,l){let h=l.num_faces()*3,d=h*4,f=a._malloc(d);o.GetTrianglesUInt32Array(l,d,f);let p=new Uint32Array(a.HEAPF32.buffer,f,h).slice();return a._free(f),{array:p,itemSize:1}}function r(a,o,l,c,h,d){let f=l.num_points(),p=d.num_components(),x=s(a,h),y=p*h.BYTES_PER_ELEMENT,b=Math.ceil(y/4)*4,g=b/h.BYTES_PER_ELEMENT,S=f*y,A=f*b,T=a._malloc(S);o.GetAttributeDataArrayForAllPoints(l,d,x,S,T);let N=new h(a.HEAPF32.buffer,T,S/h.BYTES_PER_ELEMENT),P;if(y===b)P=N.slice();else{P=new h(A/h.BYTES_PER_ELEMENT);let U=0;for(let v=0,I=N.length;v<I;v++){for(let B=0;B<p;B++)P[U+B]=N[v*p+B];U+=g}}return a._free(T),{name:c,count:f,itemSize:p,array:P,stride:g}}function s(a,o){switch(o){case Float32Array:return a.DT_FLOAT32;case Int8Array:return a.DT_INT8;case Int16Array:return a.DT_INT16;case Int32Array:return a.DT_INT32;case Uint8Array:return a.DT_UINT8;case Uint16Array:return a.DT_UINT16;case Uint32Array:return a.DT_UINT32}}}var pp,Hh,Vb=un(()=>{Vn();pp=new WeakMap,Hh=class extends oi{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,r){let s=new Yi(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,a=>{this.parse(a,t,r)},n,r)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,Xt,n).catch(n)}decodeDracoFile(e,t,n,r,s=bn,a=()=>{}){let o={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:r||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:s};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){let n=JSON.stringify(t);if(pp.has(e)){let l=pp.get(e);if(l.key===n)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let r,s=this.workerNextTaskID++,a=e.byteLength,o=this._getWorker(s,a).then(l=>(r=l,new Promise((c,h)=>{r._callbacks[s]={resolve:c,reject:h},r.postMessage({type:"decode",id:s,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{r&&s&&this._releaseTask(r,s)}),pp.set(e,{key:n,promise:o}),o}_createGeometry(e){let t=new mn;e.index&&t.setIndex(new Kt(e.index.array,1));for(let n=0;n<e.attributes.length;n++){let{name:r,array:s,itemSize:a,stride:o,vertexColorSpace:l}=e.attributes[n],c;if(a===o)c=new Kt(s,a);else{let h=new Ur(s,o);c=new kr(h,a,0)}r==="color"&&(this._assignVertexColorSpace(c,l),c.normalized=!(s instanceof Float32Array)),t.setAttribute(r,c)}return t}_assignVertexColorSpace(e,t){if(t!==Xt)return;let n=new Ve;for(let r=0,s=e.count;r<s;r++)n.fromBufferAttribute(e,r),ut.colorSpaceToWorking(n,Xt),e.setXYZ(r,n.r,n.g,n.b)}_loadLibrary(e,t){let n=new Yi(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((r,s)=>{n.load(e,r,void 0,s)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;let e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{let r=n[0];e||(this.decoderConfig.wasmBinary=n[1]);let s=dE.toString(),a=["/* draco decoder */",r,"","/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join(`
+`);this.workerSourceURL=URL.createObjectURL(new Blob([a]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){let r=new Worker(this.workerSourceURL);r._callbacks={},r._taskCosts={},r._taskLoad=0,r.postMessage({type:"init",decoderConfig:this.decoderConfig}),r.onmessage=function(s){let a=s.data;switch(a.type){case"decode":r._callbacks[a.id].resolve(a);break;case"error":r._callbacks[a.id].reject(a);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+a.type+'"')}},this.workerPool.push(r)}else this.workerPool.sort(function(r,s){return r._taskLoad>s._taskLoad?-1:1});let n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}});var Wb={};Ar(Wb,{MeshoptDecoder:()=>fE});var fE,qb=un(()=>{fE=(function(){var i="b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuixkbeeeddddillviebeoweuecj:Gdkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WboY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbrl79IV9Rbwq:VZkdbk:XYi5ud9:du8Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxcj;abad9Uc;WFbGcjdadca0EhmaialfgPar9Rgoadfhsavaoadz:jjjjbgzceVhHcbhOdndninaeaO9nmeaPax9RaD6mdamaeaO9RaOamfgoae6EgAcsfglc9WGhCabaOad2fhXaAcethQaxaDfhiaOaeaoaeao6E9RhLalcl4cifcd4hKazcj;cbfaAfhYcbh8AazcjdfhEaHh3incbh5dnawTmbaxa8Acd4fRbbh5kcbh8Eazcj;cbfhqinaih8Fdndndndna5a8Ecet4ciGgoc9:fPdebdkaPa8F9RaA6mrazcj;cbfa8EaA2fa8FaAz:jjjjb8Aa8FaAfhixdkazcj;cbfa8EaA2fcbaAz:kjjjb8Aa8FhixekaPa8F9RaK6mva8FaKfhidnaCTmbaPai9RcK6mbaocdtc:q:G:cjbfcj:G:cjbawEhaczhrcbhlinargoc9Wfghaqfhrdndndndndndnaaa8Fahco4fRbbalcoG4ciGcdtfydbPDbedvivvvlvkar9cb83bwar9cb83bbxlkarcbaiRbdai8Xbb9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbaqaofgrcGfcbaicdfa8J9c8N1:NfghRbbag9cjjjjjw:dg8J9qE86bbarcVfcbaha8J9c8M1:NfghRbbag9cjjjjjl:dg8J9qE86bbarc7fcbaha8J9c8L1:NfghRbbag9cjjjjjd:dg8J9qE86bbarctfcbaha8J9c8K1:NfghRbbag9cjjjjje:dg8J9qE86bbarc91fcbaha8J9c8J1:NfghRbbag9cjjjj;ab:dg8J9qE86bbarc4fcbaha8J9cg1:NfghRbbag9cjjjja:dg8J9qE86bbarc93fcbaha8J9ch1:NfghRbbag9cjjjjz:dgg9qE86bbarc94fcbahag9ca1:NfghRbbai8Xbe9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbarc95fcbaha8J9c8N1:NfgiRbbag9cjjjjjw:dg8J9qE86bbarc96fcbaia8J9c8M1:NfgiRbbag9cjjjjjl:dg8J9qE86bbarc97fcbaia8J9c8L1:NfgiRbbag9cjjjjjd:dg8J9qE86bbarc98fcbaia8J9c8K1:NfgiRbbag9cjjjjje:dg8J9qE86bbarc99fcbaia8J9c8J1:NfgiRbbag9cjjjj;ab:dg8J9qE86bbarc9:fcbaia8J9cg1:NfgiRbbag9cjjjja:dg8J9qE86bbarcufcbaia8J9ch1:NfgiRbbag9cjjjjz:dgg9qE86bbaiag9ca1:NfhixikaraiRblaiRbbghco4g8Ka8KciSg8KE86bbaqaofgrcGfaiclfa8Kfg8KRbbahcl4ciGg8La8LciSg8LE86bbarcVfa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc7fa8Ka8Lfg8KRbbahciGghahciSghE86bbarctfa8Kahfg8KRbbaiRbeghco4g8La8LciSg8LE86bbarc91fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc4fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc93fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc94fa8Kahfg8KRbbaiRbdghco4g8La8LciSg8LE86bbarc95fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc96fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc97fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc98fa8KahfghRbbaiRbigico4g8Ka8KciSg8KE86bbarc99faha8KfghRbbaicl4ciGg8Ka8KciSg8KE86bbarc9:faha8KfghRbbaicd4ciGg8Ka8KciSg8KE86bbarcufaha8KfgrRbbaiciGgiaiciSgiE86bbaraifhixdkaraiRbwaiRbbghcl4g8Ka8KcsSg8KE86bbaqaofgrcGfaicwfa8Kfg8KRbbahcsGghahcsSghE86bbarcVfa8KahfghRbbaiRbeg8Kcl4g8La8LcsSg8LE86bbarc7faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarctfaha8KfghRbbaiRbdg8Kcl4g8La8LcsSg8LE86bbarc91faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc4faha8KfghRbbaiRbig8Kcl4g8La8LcsSg8LE86bbarc93faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc94faha8KfghRbbaiRblg8Kcl4g8La8LcsSg8LE86bbarc95faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc96faha8KfghRbbaiRbvg8Kcl4g8La8LcsSg8LE86bbarc97faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc98faha8KfghRbbaiRbog8Kcl4g8La8LcsSg8LE86bbarc99faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc9:faha8KfghRbbaiRbrgicl4g8Ka8KcsSg8KE86bbarcufaha8KfgrRbbaicsGgiaicsSgiE86bbaraifhixekarai8Pbw83bwarai8Pbb83bbaiczfhikdnaoaC9pmbalcdfhlaoczfhraPai9RcL0mekkaoaC6moaimexokaCmva8FTmvkaqaAfhqa8Ecefg8Ecl9hmbkdndndndnawTmbasa8Acd4fRbbgociGPlbedrbkaATmdaza8Afh8Fazcj;cbfhhcbh8EaEhaina8FRbbhraahocbhlinaoahalfRbbgqce4cbaqceG9R7arfgr86bbaoadfhoaAalcefgl9hmbkaacefhaa8Fcefh8FahaAfhha8Ecefg8Ecl9hmbxikkaATmeaza8Afhaazcj;cbfhhcbhoceh8EaYh8FinaEaofhlaa8Vbbhrcbhoinala8FaofRbbcwtahaofRbbgqVc;:FiGce4cbaqceG9R7arfgr87bbaladfhlaLaocefgofmbka8FaQfh8FcdhoaacdfhaahaQfhha8EceGhlcbh8EalmbxdkkaATmbaocl4h8Eaza8AfRbbhqcwhoa3hlinalRbbaotaqVhqalcefhlaocwfgoca9hmbkcbhhaEh8FaYhainazcj;cbfahfRbbhrcwhoaahlinalRbbaotarVhralaAfhlaocwfgoca9hmbkara8E94aq7hqcbhoa8Fhlinalaqao486bbalcefhlaocwfgoca9hmbka8Fadfh8FaacefhaahcefghaA9hmbkkaEclfhEa3clfh3a8Aclfg8Aad6mbkaXazcjdfaAad2z:jjjjb8AazazcjdfaAcufad2fadz:jjjjb8AaAaOfhOaihxaimbkc9:hoxdkcbc99aPax9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaok:ysezu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnalaeci9UgrcHf6mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:kjjjb8Aav9cu83iUav9cu83i8Wav9cu83iyav9cu83iaav9cu83iKav9cu83izav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbavaiaqaDcsGfRbbgscl4gP9RcsGcdtfydbaxcefgOaPEhDavaias9RcsGcdtfydbaOaPTgzfgOascsGgPEhsaPThPdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiazfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaPfhiaOaPfhxxekaxcbalRbbgsEgHaDc;:eSgDfhOascsGhAdndnascl4gCmbaOcefhzxekaOhzavaiaC9RcsGcdtfydbhOkdndnaAmbazcefhxxekazhxavaias9RcsGcdtfydbhzkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhHascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaHhDxekaDcefhDkasce4cbasceG9R7amfgmhHkdndnaCcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhOaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkaOhsxekascefhskaPce4cbaPceG9R7amfgmhOkdndnaAcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhzaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkazhlxekalcefhlkaPce4cbaPceG9R7amfgmhzkdndnadcd9hmbabarcetfgDaH87ebaDclfaz87ebaDcdfaO87ebxekabarcdtfgDaHBdbaDcwfazBdbaDclfaOBdbkavc;abfaocitfgDaOBdbaDaHBdlavaicdtfaHBdbavc;abfaocefcsGcitfgDazBdbaDaOBdlavaicefgicsGcdtfaOBdbavc;abfaocdfcsGcitfgDaHBdbaDazBdlavaiaCTaCcsSVfgicsGcdtfazBdbaiaATaAcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnalaecvf9pmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk:4ioiue99dud99dud99dnaeTmbcbhiabhlindndnal8Uebgv:YgoJ:ji:1Salcof8UebgrciVgw:Y:vgDNJbbbZJbbb:;avcu9kEMgq:lJbbb9p9DTmbaq:Ohkxekcjjjj94hkkalclf8Uebhvalcdf8UebhxalarcefciGcetfak87ebdndnax:YgqaDNJbbbZJbbb:;axcu9kEMgm:lJbbb9p9DTmbam:Ohxxekcjjjj94hxkabaiarciGgkfcd7cetfax87ebdndnav:YgmaDNJbbbZJbbb:;avcu9kEMgP:lJbbb9p9DTmbaP:Ohvxekcjjjj94hvkalarcufciGcetfav87ebdndnawaw2:ZgPaPMaoaoN:taqaqN:tamamN:tgoJbbbbaoJbbbb9GE:raDNJbbbZMgD:lJbbb9p9DTmbaD:Ohrxekcjjjj94hrkalakcetfar87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2gdTmbinababydbgecwtcw91:Yaece91cjjj98Gcjjj;8if::NUdbabclfhbadcufgdmbkkk:Tvirud99eudndnadcl9hmbaeTmeindndnabRbbgiabcefgl8Sbbgvabcdfgo8Sbbgrf9R:YJbbuJabcifgwRbbgdce4adVgDcd4aDVgDcl4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax86bbdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao86bbdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai86bbdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad86bbabclfhbaecufgembxdkkaeTmbindndnab8Vebgiabcdfgl8Uebgvabclfgo8Uebgrf9R:YJbFu9habcofgw8Vebgdce4adVgDcd4aDVgDcl4aDVgDcw4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax87ebdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao87ebdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai87ebdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad87ebabcwfhbaecufgembkkk9teiucbcbyd:K:G:cjbgeabcifc98GfgbBd:K:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkk83dbcj:Gdk8Kbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbc:K:Gdkl8W:qbb",e="b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuixkbbebeeddddilve9Weeeviebeoweuecj:Gdkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WbwY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbDl79IV9Rbqq:W9Dklbzik94evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaeai86b:q:W:cjbaecitab8Piw83i:q:G:cjbaecefgecjd9hmbkk:JBl8Aud97dur978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaialfgxar9RhodnadTgmmbavaoad;8qbbkaicefhPcj;abad9Uc;WFbGcjdadca0EhsdndndnadTmbaoadfhzcbhHinaeaH9nmdaxaP9RaD6miabaHad2fhOaPaDfhAasaeaH9RaHasfae6EgCcsfgocl4cifcd4hXavcj;cbfaoc9WGgQcetfhLavcj;cbfaQci2fhKavcj;cbfaQfhYcbh8Aaoc;ab6hEincbh3dnawTmbaPa8Acd4fRbbh3kcbh5avcj;cbfh8Eindndndndna3a5cet4ciGgoc9:fPdebdkaxaA9RaQ6mwdnaQTmbavcj;cbfa5aQ2faAaQ;8qbbkaAaCfhAxdkaQTmeavcj;cbfa5aQ2fcbaQ;8kbxekaxaA9RaX6moaoclVcbawEhraAaXfhocbhidnaEmbaxao9Rc;Gb6mbcbhlina8EalfhidndndndndndnaAalco4fRbbgqciGarfPDbedibledibkaipxbbbbbbbbbbbbbbbbpklbxlkaiaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaoclffagRb:q:W:cjbfhoxikaiaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaocwffagRb:q:W:cjbfhoxdkaiaopbbbpklbaoczfhoxekaiaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbahaocdffagRb:q:W:cjbfhokdndndndndndnaqcd4ciGarfPDbedibledibkaiczfpxbbbbbbbbbbbbbbbbpklbxlkaiczfaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaoclffagRb:q:W:cjbfhoxikaiczfaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaocwffagRb:q:W:cjbfhoxdkaiczfaopbbbpklbaoczfhoxekaiczfaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbahaocdffagRb:q:W:cjbfhokdndndndndndnaqcl4ciGarfPDbedibledibkaicafpxbbbbbbbbbbbbbbbbpklbxlkaicafaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaoclffagRb:q:W:cjbfhoxikaicafaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaocwffagRb:q:W:cjbfhoxdkaicafaopbbbpklbaoczfhoxekaicafaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbahaocdffagRb:q:W:cjbfhokdndndndndndnaqco4arfPDbedibledibkaic8Wfpxbbbbbbbbbbbbbbbbpklbxlkaic8Wfaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Ngicitpbi:q:G:cjbaiRb:q:W:cjbgipsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbaiaoclffaqRb:q:W:cjbfhoxikaic8Wfaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Ngicitpbi:q:G:cjbaiRb:q:W:cjbgipsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbaiaocwffaqRb:q:W:cjbfhoxdkaic8Wfaopbbbpklbaoczfhoxekaic8WfaopbbdaoRbbgicitpbi:q:G:cjbaiRb:q:W:cjbgipsaoRbegqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbaiaocdffaqRb:q:W:cjbfhokalc;abfhialcjefaQ0meaihlaxao9Rc;Fb0mbkkdnaiaQ9pmbaici4hlinaxao9RcK6mwa8EaifhqdndndndndndnaAaico4fRbbalcoG4ciGarfPDbedibledibkaqpxbbbbbbbbbbbbbbbbpkbbxlkaqaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spkbbahaoclffagRb:q:W:cjbfhoxikaqaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spkbbahaocwffagRb:q:W:cjbfhoxdkaqaopbbbpkbbaoczfhoxekaqaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpkbbahaocdffagRb:q:W:cjbfhokalcdfhlaiczfgiaQ6mbkkaohAaoTmoka8EaQfh8Ea5cefg5cl9hmbkdndndndnawTmbaza8Acd4fRbbglciGPlbedwbkaQTmdavcjdfa8Afhlava8Afpbdbh8Jcbhoinalavcj;cbfaofpblbg8KaYaofpblbg8LpmbzeHdOiAlCvXoQrLg8MaLaofpblbg8NaKaofpblbgypmbzeHdOiAlCvXoQrLg8PpmbezHdiOAlvCXorQLg8Fcep9Ta8Fpxeeeeeeeeeeeeeeeegap9op9Hp9rg8Fa8Jp9Ug8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9Abbbaladfgla8Ja8Ma8PpmwDKYqk8AExm35Ps8E8Fg8Fcep9Ta8Faap9op9Hp9rg8Fp9Ug8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9Abbbaladfgla8Ja8Ka8LpmwKDYq8AkEx3m5P8Es8Fg8Ka8NaypmwKDYq8AkEx3m5P8Es8Fg8LpmbezHdiOAlvCXorQLg8Fcep9Ta8Faap9op9Hp9rg8Fp9Ug8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9Abbbaladfgla8Ja8Ka8LpmwDKYqk8AExm35Ps8E8Fg8Fcep9Ta8Faap9op9Hp9rg8Fp9Ugap9Abbbaladfglaaa8Fa8Fpmlvorlvorlvorlvorp9Ugap9Abbbaladfglaaa8Fa8FpmwDqkwDqkwDqkwDqkp9Ugap9Abbbaladfglaaa8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9AbbbaladfhlaoczfgoaQ6mbxikkaQTmeavcjdfa8Afhlava8Afpbdbh8Jcbhoinalavcj;cbfaofpblbg8KaYaofpblbg8LpmbzeHdOiAlCvXoQrLg8MaLaofpblbg8NaKaofpblbgypmbzeHdOiAlCvXoQrLg8PpmbezHdiOAlvCXorQLg8Fcep:nea8Fpxebebebebebebebebgap9op:bep9rg8Fa8Jp:oeg8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9Abbbaladfgla8Ja8Ma8PpmwDKYqk8AExm35Ps8E8Fg8Fcep:nea8Faap9op:bep9rg8Fp:oeg8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9Abbbaladfgla8Ja8Ka8LpmwKDYq8AkEx3m5P8Es8Fg8Ka8NaypmwKDYq8AkEx3m5P8Es8Fg8LpmbezHdiOAlvCXorQLg8Fcep:nea8Faap9op:bep9rg8Fp:oeg8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9Abbbaladfgla8Ja8Ka8LpmwDKYqk8AExm35Ps8E8Fg8Fcep:nea8Faap9op:bep9rg8Fp:oegap9Abbbaladfglaaa8Fa8Fpmlvorlvorlvorlvorp:oegap9Abbbaladfglaaa8Fa8FpmwDqkwDqkwDqkwDqkp:oegap9Abbbaladfglaaa8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9AbbbaladfhlaoczfgoaQ6mbxdkkaQTmbcbhocbalcl4gl9Rc8FGhiavcjdfa8Afhrava8Afpbdbhainaravcj;cbfaofpblbg8JaYaofpblbg8KpmbzeHdOiAlCvXoQrLg8LaLaofpblbg8MaKaofpblbg8NpmbzeHdOiAlCvXoQrLgypmbezHdiOAlvCXorQLg8Faip:Rea8Falp:Tep9qg8Faap9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9Abbbaradfgraaa8LaypmwDKYqk8AExm35Ps8E8Fg8Faip:Rea8Falp:Tep9qg8Fp9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9Abbbaradfgraaa8Ja8KpmwKDYq8AkEx3m5P8Es8Fg8Ja8Ma8NpmwKDYq8AkEx3m5P8Es8Fg8KpmbezHdiOAlvCXorQLg8Faip:Rea8Falp:Tep9qg8Fp9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9Abbbaradfgraaa8Ja8KpmwDKYqk8AExm35Ps8E8Fg8Faip:Rea8Falp:Tep9qg8Fp9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9AbbbaradfhraoczfgoaQ6mbkka8Aclfg8Aad6mbkdnaCad2goTmbaOavcjdfao;8qbbkdnammbavavcjdfaCcufad2fad;8qbbkaCaHfhHc9:hoaAhPaAmbxlkkaeTmbaDalfhrcbhocuhlinaralaD9RglfaD6mdasaeao9Raoasfae6Eaofgoae6mbkaial9RhPkcbc99axaP9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaokwbz:bjjjbkNsezu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnalaeci9UgrcHf6mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbav9cu83iUav9cu83i8Wav9cu83iyav9cu83iaav9cu83iKav9cu83izav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbavaiaqaDcsGfRbbgscl4gP9RcsGcdtfydbaxcefgOaPEhDavaias9RcsGcdtfydbaOaPTgzfgOascsGgPEhsaPThPdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiazfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaPfhiaOaPfhxxekaxcbalRbbgsEgHaDc;:eSgDfhOascsGhAdndnascl4gCmbaOcefhzxekaOhzavaiaC9RcsGcdtfydbhOkdndnaAmbazcefhxxekazhxavaias9RcsGcdtfydbhzkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhHascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaHhDxekaDcefhDkasce4cbasceG9R7amfgmhHkdndnaCcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhOaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkaOhsxekascefhskaPce4cbaPceG9R7amfgmhOkdndnaAcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhzaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkazhlxekalcefhlkaPce4cbaPceG9R7amfgmhzkdndnadcd9hmbabarcetfgDaH87ebaDclfaz87ebaDcdfaO87ebxekabarcdtfgDaHBdbaDcwfazBdbaDclfaOBdbkavc;abfaocitfgDaOBdbaDaHBdlavaicdtfaHBdbavc;abfaocefcsGcitfgDazBdbaDaOBdlavaicefgicsGcdtfaOBdbavc;abfaocdfcsGcitfgDaHBdbaDazBdlavaiaCTaCcsSVfgicsGcdtfazBdbaiaATaAcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnalaecvf9pmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk;Toio97eue97aec98Ghedndnadcl9hmbaeTmecbhdinababpbbbgicKp:RecKp:Sep;6eglaicwp:RecKp:Sep;6ealp;Geaiczp:RecKp:Sep;6egvp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egralpxbbbjbbbjbbbjbbbjgwp9op9rp;Keglpxbb;:9cbb;:9cbb;:9cbb;:9calalp;Meaoaop;Meavaravawp9op9rp;Keglalp;Mep;Kep;Kep;Jep;Negvp;Mepxbbn0bbn0bbn0bbn0grp;KepxFbbbFbbbFbbbFbbbp9oaipxbbbFbbbFbbbFbbbFp9op9qalavp;Mearp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaoavp;Mearp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbabczfhbadclfgdae6mbxdkkaeTmbcbhdinabczfgDaDpbbbgipxbbbbbbFFbbbbbbFFgwp9oabpbbbgoaipmbediwDqkzHOAKY8AEgvczp:Reczp:Sep;6eglaoaipmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eavczp:Sep;6egvp;Gealp;Gep;Kep;Legipxbbbbbbbbbbbbbbbbp:2egralpxbbbjbbbjbbbjbbbjgqp9op9rp;Keglpxb;:FSb;:FSb;:FSb;:FSalalp;Meaiaip;Meavaravaqp9op9rp;Keglalp;Mep;Kep;Kep;Jep;Negvp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbp9oaiavp;Mearp;Keczp:Rep9qgialavp;Mearp;KepxFFbbFFbbFFbbFFbbp9oglpmwDKYqk8AExm35Ps8E8Fp9qpkbbabaoawp9oaialpmbezHdiOAlvCXorQLp9qpkbbabcafhbadclfgdae6mbkkk;2ileue97euo97dnaec98GgiTmbcbheinabcKfpx:ji:1S:ji:1S:ji:1S:ji:1SabpbbbglabczfgvpbbbgopmlvorxmPsCXQL358E8Fgrczp:Segwpxibbbibbbibbbibbbp9qp;6egDp;NegqaDaDp;MegDaDp;KealaopmbediwDqkzHOAKY8AEgDczp:Reczp:Sep;6eglalp;MeaDczp:Sep;6egoaop;Mearczp:Reczp:Sep;6egrarp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gDp;KepxFFbbFFbbFFbbFFbbgkp9oaqaop;MeaDp;Keczp:Rep9qgoaqalp;MeaDp;Keakp9oaqarp;MeaDp;Keczp:Rep9qgDpmwDKYqk8AExm35Ps8E8Fglp5eawclp:RegqpEi:T:j83ibavalp5baqpEd:T:j83ibabcwfaoaDpmbezHdiOAlvCXorQLgDp5eaqpEe:T:j83ibabaDp5baqpEb:T:j83ibabcafhbaeclfgeai6mbkkkuee97dnadcd4ae2c98GgeTmbcbhdinababpbbbgicwp:Recwp:Sep;6eaicep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepkbbabczfhbadclfgdae6mbkkk:Sodw97euaec98Ghedndnadcl9hmbaeTmecbhdinabpxbbuJbbuJbbuJbbuJabpbbbgicKp:TeglaicYp:Tep9qgvcdp:Teavp9qgvclp:Teavp9qgop;6ep;Negvaicwp:RecKp:SegraipxFbbbFbbbFbbbFbbbgwp9ogDp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oavaDarp:Xeaiczp:RecKp:Segip:Uep;6ep;Meaqp;Keawp9op9qavaDaraip:Uep:Xep;6ep;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qavaoalcep:Rep9oalpxebbbebbbebbbebbbp9op9qp;6ep;Meaqp;KecKp:Rep9qpkbbabczfhbadclfgdae6mbxdkkaeTmbcbhdinabczfgkpxbFu9hbFu9hbFu9hbFu9habpbbbglakpbbbgrpmlvorxmPsCXQL358E8Fgvczp:TegqavcHp:Tep9qgicdp:Teaip9qgiclp:Teaip9qgicwp:Teaip9qgop;6ep;NegialarpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbglp9ograDczp:Segwp:Ueavczp:Reczp:SegDp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gvp;Kealp9oaiarawaDp:Uep:Xep;6ep;Meavp;Keczp:Rep9qgwaiaoaqcep:Rep9oaqpxebbbebbbebbbebbbp9op9qp;6ep;Meavp;Keczp:ReaiaDarp:Uep;6ep;Meavp;Kealp9op9qgipmwDKYqk8AExm35Ps8E8FpkbbabawaipmbezHdiOAlvCXorQLpkbbabcafhbadclfgdae6mbkkk9teiucbcbydj:G:cjbgeabcifc98GfgbBdj:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkxebcj:Gdklz:zbb",t=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),n=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!="object")return{supported:!1};var r=WebAssembly.validate(t)?o(e):o(i),s,a=WebAssembly.instantiate(r,{}).then(function(g){s=g.instance,s.exports.__wasm_call_ctors()});function o(g){for(var S=new Uint8Array(g.length),A=0;A<g.length;++A){var T=g.charCodeAt(A);S[A]=T>96?T-97:T>64?T-39:T+4}for(var N=0,A=0;A<g.length;++A)S[N++]=S[A]<60?n[S[A]]:(S[A]-60)*64+S[++A];return S.buffer.slice(0,N)}function l(g,S,A,T,N,P,U){var v=g.exports.sbrk,I=T+3&-4,B=v(I*N),k=v(P.length),V=new Uint8Array(g.exports.memory.buffer);V.set(P,k);var J=S(B,T,N,k,P.length);if(J==0&&U&&U(B,I,N),A.set(V.subarray(B,B+T*N)),v(B-v(0)),J!=0)throw new Error("Malformed buffer data: "+J)}var c={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp",COLOR:"meshopt_decodeFilterColor"},h={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"},d=[],f=0;function p(g){var S={object:new Worker(g),pending:0,requests:{}};return S.object.onmessage=function(A){var T=A.data;S.pending-=T.count,S.requests[T.id][T.action](T.value),delete S.requests[T.id]},S}function x(g){for(var S="self.ready = WebAssembly.instantiate(new Uint8Array(["+new Uint8Array(r)+"]), {}).then(function(result) { result.instance.exports.__wasm_call_ctors(); return result.instance; });self.onmessage = "+b.name+";"+l.toString()+b.toString(),A=new Blob([S],{type:"text/javascript"}),T=URL.createObjectURL(A),N=d.length;N<g;++N)d[N]=p(T);for(var N=g;N<d.length;++N)d[N].object.postMessage({});d.length=g,URL.revokeObjectURL(T)}function y(g,S,A,T,N){for(var P=d[0],U=1;U<d.length;++U)d[U].pending<P.pending&&(P=d[U]);return new Promise(function(v,I){var B=new Uint8Array(A),k=++f;P.pending+=g,P.requests[k]={resolve:v,reject:I},P.object.postMessage({id:k,count:g,size:S,source:B,mode:T,filter:N},[B.buffer])})}function b(g){var S=g.data;self.ready.then(function(A){if(!S.id)return self.close();try{var T=new Uint8Array(S.count*S.size);l(A,A.exports[S.mode],T,S.count,S.size,S.source,A.exports[S.filter]),self.postMessage({id:S.id,count:S.count,action:"resolve",value:T},[T.buffer])}catch(N){self.postMessage({id:S.id,count:S.count,action:"reject",value:N})}})}return{ready:a,supported:!0,useWorkers:function(g){x(g)},decodeVertexBuffer:function(g,S,A,T,N){l(s,s.exports.meshopt_decodeVertexBuffer,g,S,A,T,s.exports[c[N]])},decodeIndexBuffer:function(g,S,A,T){l(s,s.exports.meshopt_decodeIndexBuffer,g,S,A,T)},decodeIndexSequence:function(g,S,A,T){l(s,s.exports.meshopt_decodeIndexSequence,g,S,A,T)},decodeGltfBuffer:function(g,S,A,T,N,P){l(s,s.exports[h[N]],g,S,A,T,s.exports[c[P]])},decodeGltfBufferAsync:function(g,S,A,T,N){return d.length>0?y(g,S,A,h[T],c[N]):a.then(function(){var P=new Uint8Array(g*S);return l(s,s.exports[h[T]],P,g,S,A,s.exports[c[N]]),P})}}})()});function pE(i){typeof i=="string"&&i&&(jb=i.endsWith("/")?i:`${i}/`)}function Xb(){return mp||(mp=Promise.resolve().then(()=>(qb(),Wb)).then(i=>i.MeshoptDecoder).catch(()=>null)),mp}function Gh(){if(La)return La;La=new kh;let i=new Hh;return i.setDecoderPath(jb),La.setDRACOLoader(i),Xb().then(e=>{e&&La.setMeshoptDecoder(e)}),La}async function Kb(){let i=Gh();return await Xb(),i}var $b,La,jb,mp,Vh=un(()=>{Gb();Vb();$b="https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/libs/draco/gltf/",La=null,jb=$b,mp=null});function Rp(i){let e=i&&i.length?i.length/4:0;if(!e)return{intensity:.4,tint:{r:1,g:1,b:1}};let t=0,n=0,r=0,s=0;for(let h=0;h<i.length;h+=4){let d=i[h],f=i[h+1],p=i[h+2];t+=d,n+=f,r+=p,s+=.2126*d+.7152*f+.0722*p}let a=s/e/255,o=Math.min(1.35,Math.max(.4,.35+a*1.25)),l=(t+n+r)/(e*3);if(l<=6)return{intensity:o,tint:{r:1,g:1,b:1}};let c=h=>1+(h/e/l-1)*.33;return{intensity:o,tint:{r:c(t),g:c(n),b:c(r)}}}function Ko(i,{skinned:e=!1}={}){let t=Number(i?.max?.x)-Number(i?.min?.x),n=Number(i?.max?.y)-Number(i?.min?.y),r=Number(i?.max?.z)-Number(i?.min?.z);if(![t,n,r].every(c=>Number.isFinite(c)&&c>=0))return{scale:1,yOffset:0};let s=Math.max(t,n,r);if(s<=1e-6)return{scale:1,yOffset:0};let a;e&&n>1e-6?a=1.65/n:a=.75/s,a>.5&&a<2&&(a=1);let o=Number(i.min.y),l=Number.isFinite(o)?-o*a:0;return{scale:a,yOffset:l}}function Cp(i,e,t=1.6){let n=Number(e?.x)||0,r=Number(e?.z)||0,s=Math.hypot(n,r),a=s>1e-4?n/s:0,o=s>1e-4?r/s:-1,l=(Number(i?.x)||0)+a*t,c=(Number(i?.z)||0)+o*t;return{x:l,z:c}}function Ip(i,e){if(!Number.isFinite(i)||!Number.isFinite(e))return 0;let t=e-i;for(;t>Math.PI;)t-=2*Math.PI;for(;t<=-Math.PI;)t+=2*Math.PI;return t}function Yh(i){return Math.atan2(i[1].clientY-i[0].clientY,i[1].clientX-i[0].clientX)}function Jr(i){let e=String(i??"").trim();if(!e)return null;if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let t=new URL(e);return t.protocol==="https:"?t.href:null}catch{return null}}function Jh(i){let e=(Array.isArray(i)?i:[]).slice(0,20).map(t=>({src:String(t.src||""),title:String(t.title||"").slice(0,120),x:Number(t.x)||0,z:Number(t.z)||0,yaw:Number(t.yaw)||0,scale:Xh(Number(t.scale)||1,.25,4)})).filter(t=>Jr(t.src));return JSON.stringify({v:1,items:e})}function Zh(i){let e;try{e=JSON.parse(i??"null")}catch{return[]}if(!e||e.v!==1||!Array.isArray(e.items))return[];let t=[];for(let n of e.items){if(t.length>=20)break;let r=Jr(n?.src);if(!r)continue;let s=Number(n.x),a=Number(n.z);!Number.isFinite(s)||!Number.isFinite(a)||t.push({src:r,title:String(n.title||"").slice(0,120),x:Xh(s,-50,50),z:Xh(a,-50,50),yaw:Number.isFinite(Number(n.yaw))?Number(n.yaw):0,scale:Xh(Number(n.scale)||1,.25,4)})}return t}function WE(i){let e=new TextEncoder().encode(i),t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function qE(i){let e=String(i).replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),n=Uint8Array.from(t,r=>r.charCodeAt(0));return new TextDecoder().decode(n)}function Mx(i){let e=Jh(i);try{return JSON.parse(e).items.length?WE(e):""}catch{return""}}function Pp(i){if(!i)return[];try{return Zh(qE(i))}catch{return[]}}function Lp(i,e,t=1500){let n=Qh(i,e),r=Mx(e);if(!r)return n;let s=`${n}#s=${r}`;return s.length<=t?s:n}function Qh(i,e,t=4){let n=String(i||"").split("#")[0],r=(Array.isArray(e)?e:[]).map(c=>({src:Jr(c.src),title:String(c.title||"").slice(0,60)})).filter(c=>c.src),s=new Set,a=r.filter(c=>s.has(c.src)?!1:(s.add(c.src),!0)).slice(0,t);if(!a.length)return n;let o=new URLSearchParams;for(let c of a)o.append("src",c.src),o.append("title",c.title);let l=n.includes("?")?"&":"?";return`${n}${l}${o.toString()}`}var zE,HE,GE,VE,Kh,Ep,Xh,eu=un(()=>{zE=1.65,HE=.75,GE=.25,VE=4,Kh=20,Ep=1.6;Xh=(i,e,t)=>Math.min(t,Math.max(e,i))});function tR(i,e){return eR(i,e||{},0,0)}function Qo(i,e){if(e){for(var t=new Cn(i.length),n=0;n<i.length;++n)t[n]=i.charCodeAt(n);return t}if(Cx)return Cx.encode(i);for(var r=i.length,s=new Cn(i.length+(i.length>>1)),a=0,o=function(h){s[a++]=h},n=0;n<r;++n){if(a+5>s.length){var l=new Cn(a+8+(r-n<<1));l.set(s),s=l}var c=i.charCodeAt(n);c<128||e?o(c):c<2048?(o(192|c>>6),o(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|i.charCodeAt(++n)&1023,o(240|c>>18),o(128|c>>12&63),o(128|c>>6&63),o(128|c&63)):(o(224|c>>12),o(128|c>>6&63),o(128|c&63))}return Ox(s,0,a)}function zx(i,e){e||(e={});var t={},n=[];Bx(i,"",t,e);var r=0,s=0;for(var a in t){var o=t[a],l=o[0],c=o[1],h=c.level==0?0:8,d=Qo(a),f=d.length,p=c.comment,x=p&&Qo(p),y=x&&x.length,b=Up(c.extra);f>65535&&nu(11);var g=h?tR(l,c):l,S=g.length,A=QE();A.p(l),n.push(kx(c,{size:l.length,crc:A.d(),c:g,f:d,m:x,u:f!=a.length||x&&p.length!=y,o:r,compression:h})),r+=30+f+b+S,s+=76+2*(f+b)+(y||0)+S}for(var T=new Cn(s+22),N=r,P=s-r,U=0;U<n.length;++U){var d=n[U];Ix(T,d.o,d,d.f,d.u,d.c.length);var v=30+d.f.length+Up(d.extra);T.set(d.c,d.o+v),Ix(T,r,d,d.f,d.u,d.c.length,d.o,d.m),r+=16+v+(d.m?d.m.length:0)}return rR(T,r,n.length,P,N),T}var Cn,li,kp,Bp,zp,Ax,Px,Lx,$E,Np,Dx,rL,Tx,Op,xr,Lt,Zo,Os,Lt,Lt,Lt,Lt,tu,Lt,jE,XE,Nx,Ox,KE,nu,_r,Yo,Dp,Fp,Ex,Jo,Fx,Rx,YE,Ux,JE,ZE,QE,eR,kx,Rn,Bx,Cx,nR,iR,Up,Ix,rR,Hx=un(()=>{Cn=Uint8Array,li=Uint16Array,kp=Int32Array,Bp=new Cn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),zp=new Cn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ax=new Cn([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Px=function(i,e){for(var t=new li(31),n=0;n<31;++n)t[n]=e+=1<<i[n-1];for(var r=new kp(t[30]),n=1;n<30;++n)for(var s=t[n];s<t[n+1];++s)r[s]=s-t[n]<<5|n;return{b:t,r}},Lx=Px(Bp,2),$E=Lx.b,Np=Lx.r;$E[28]=258,Np[258]=28;Dx=Px(zp,0),rL=Dx.b,Tx=Dx.r,Op=new li(32768);for(Lt=0;Lt<32768;++Lt)xr=(Lt&43690)>>1|(Lt&21845)<<1,xr=(xr&52428)>>2|(xr&13107)<<2,xr=(xr&61680)>>4|(xr&3855)<<4,Op[Lt]=((xr&65280)>>8|(xr&255)<<8)>>1;Zo=(function(i,e,t){for(var n=i.length,r=0,s=new li(e);r<n;++r)i[r]&&++s[i[r]-1];var a=new li(e);for(r=1;r<e;++r)a[r]=a[r-1]+s[r-1]<<1;var o;if(t){o=new li(1<<e);var l=15-e;for(r=0;r<n;++r)if(i[r])for(var c=r<<4|i[r],h=e-i[r],d=a[i[r]-1]++<<h,f=d|(1<<h)-1;d<=f;++d)o[Op[d]>>l]=c}else for(o=new li(n),r=0;r<n;++r)i[r]&&(o[r]=Op[a[i[r]-1]++]>>15-i[r]);return o}),Os=new Cn(288);for(Lt=0;Lt<144;++Lt)Os[Lt]=8;for(Lt=144;Lt<256;++Lt)Os[Lt]=9;for(Lt=256;Lt<280;++Lt)Os[Lt]=7;for(Lt=280;Lt<288;++Lt)Os[Lt]=8;tu=new Cn(32);for(Lt=0;Lt<32;++Lt)tu[Lt]=5;jE=Zo(Os,9,0),XE=Zo(tu,5,0),Nx=function(i){return(i+7)/8|0},Ox=function(i,e,t){return(e==null||e<0)&&(e=0),(t==null||t>i.length)&&(t=i.length),new Cn(i.subarray(e,t))},KE=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],nu=function(i,e,t){var n=new Error(e||KE[i]);if(n.code=i,Error.captureStackTrace&&Error.captureStackTrace(n,nu),!t)throw n;return n},_r=function(i,e,t){t<<=e&7;var n=e/8|0;i[n]|=t,i[n+1]|=t>>8},Yo=function(i,e,t){t<<=e&7;var n=e/8|0;i[n]|=t,i[n+1]|=t>>8,i[n+2]|=t>>16},Dp=function(i,e){for(var t=[],n=0;n<i.length;++n)i[n]&&t.push({s:n,f:i[n]});var r=t.length,s=t.slice();if(!r)return{t:Ux,l:0};if(r==1){var a=new Cn(t[0].s+1);return a[t[0].s]=1,{t:a,l:1}}t.sort(function(N,P){return N.f-P.f}),t.push({s:-1,f:25001});var o=t[0],l=t[1],c=0,h=1,d=2;for(t[0]={s:-1,f:o.f+l.f,l:o,r:l};h!=r-1;)o=t[t[c].f<t[d].f?c++:d++],l=t[c!=h&&t[c].f<t[d].f?c++:d++],t[h++]={s:-1,f:o.f+l.f,l:o,r:l};for(var f=s[0].s,n=1;n<r;++n)s[n].s>f&&(f=s[n].s);var p=new li(f+1),x=Fp(t[h-1],p,0);if(x>e){var n=0,y=0,b=x-e,g=1<<b;for(s.sort(function(P,U){return p[U.s]-p[P.s]||P.f-U.f});n<r;++n){var S=s[n].s;if(p[S]>e)y+=g-(1<<x-p[S]),p[S]=e;else break}for(y>>=b;y>0;){var A=s[n].s;p[A]<e?y-=1<<e-p[A]++-1:++n}for(;n>=0&&y;--n){var T=s[n].s;p[T]==e&&(--p[T],++y)}x=e}return{t:new Cn(p),l:x}},Fp=function(i,e,t){return i.s==-1?Math.max(Fp(i.l,e,t+1),Fp(i.r,e,t+1)):e[i.s]=t},Ex=function(i){for(var e=i.length;e&&!i[--e];);for(var t=new li(++e),n=0,r=i[0],s=1,a=function(l){t[n++]=l},o=1;o<=e;++o)if(i[o]==r&&o!=e)++s;else{if(!r&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(r),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(r);s=1,r=i[o]}return{c:t.subarray(0,n),n:e}},Jo=function(i,e){for(var t=0,n=0;n<e.length;++n)t+=i[n]*e[n];return t},Fx=function(i,e,t){var n=t.length,r=Nx(e+2);i[r]=n&255,i[r+1]=n>>8,i[r+2]=i[r]^255,i[r+3]=i[r+1]^255;for(var s=0;s<n;++s)i[r+s+4]=t[s];return(r+4+n)*8},Rx=function(i,e,t,n,r,s,a,o,l,c,h){_r(e,h++,t),++r[256];for(var d=Dp(r,15),f=d.t,p=d.l,x=Dp(s,15),y=x.t,b=x.l,g=Ex(f),S=g.c,A=g.n,T=Ex(y),N=T.c,P=T.n,U=new li(19),v=0;v<S.length;++v)++U[S[v]&31];for(var v=0;v<N.length;++v)++U[N[v]&31];for(var I=Dp(U,7),B=I.t,k=I.l,V=19;V>4&&!B[Ax[V-1]];--V);var J=c+5<<3,L=Jo(r,Os)+Jo(s,tu)+a,E=Jo(r,f)+Jo(s,y)+a+14+3*V+Jo(U,B)+2*U[16]+3*U[17]+7*U[18];if(l>=0&&J<=L&&J<=E)return Fx(e,h,i.subarray(l,l+c));var D,O,H,Y;if(_r(e,h,1+(E<L)),h+=2,E<L){D=Zo(f,p,0),O=f,H=Zo(y,b,0),Y=y;var le=Zo(B,k,0);_r(e,h,A-257),_r(e,h+5,P-1),_r(e,h+10,V-4),h+=14;for(var v=0;v<V;++v)_r(e,h+3*v,B[Ax[v]]);h+=3*V;for(var fe=[S,N],be=0;be<2;++be)for(var Te=fe[be],v=0;v<Te.length;++v){var Je=Te[v]&31;_r(e,h,le[Je]),h+=B[Je],Je>15&&(_r(e,h,Te[v]>>5&127),h+=Te[v]>>12)}}else D=jE,O=Os,H=XE,Y=tu;for(var v=0;v<o;++v){var ke=n[v];if(ke>255){var Je=ke>>18&31;Yo(e,h,D[Je+257]),h+=O[Je+257],Je>7&&(_r(e,h,ke>>23&31),h+=Bp[Je]);var oe=ke&31;Yo(e,h,H[oe]),h+=Y[oe],oe>3&&(Yo(e,h,ke>>5&8191),h+=zp[oe])}else Yo(e,h,D[ke]),h+=O[ke]}return Yo(e,h,D[256]),h+O[256]},YE=new kp([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ux=new Cn(0),JE=function(i,e,t,n,r,s){var a=s.z||i.length,o=new Cn(n+a+5*(1+Math.ceil(a/7e3))+r),l=o.subarray(n,o.length-r),c=s.l,h=(s.r||0)&7;if(e){h&&(l[0]=s.r>>3);for(var d=YE[e-1],f=d>>13,p=d&8191,x=(1<<t)-1,y=s.p||new li(32768),b=s.h||new li(x+1),g=Math.ceil(t/3),S=2*g,A=function(mt){return(i[mt]^i[mt+1]<<g^i[mt+2]<<S)&x},T=new kp(25e3),N=new li(288),P=new li(32),U=0,v=0,I=s.i||0,B=0,k=s.w||0,V=0;I+2<a;++I){var J=A(I),L=I&32767,E=b[J];if(y[L]=E,b[J]=L,k<=I){var D=a-I;if((U>7e3||B>24576)&&(D>423||!c)){h=Rx(i,l,0,T,N,P,v,B,V,I-V,h),B=U=v=0,V=I;for(var O=0;O<286;++O)N[O]=0;for(var O=0;O<30;++O)P[O]=0}var H=2,Y=0,le=p,fe=L-E&32767;if(D>2&&J==A(I-fe))for(var be=Math.min(f,D)-1,Te=Math.min(32767,I),Je=Math.min(258,D);fe<=Te&&--le&&L!=E;){if(i[I+H]==i[I+H-fe]){for(var ke=0;ke<Je&&i[I+ke]==i[I+ke-fe];++ke);if(ke>H){if(H=ke,Y=fe,ke>be)break;for(var oe=Math.min(fe,ke-2),Ee=0,O=0;O<oe;++O){var _e=I-fe+O&32767,Ze=y[_e],tt=_e-Ze&32767;tt>Ee&&(Ee=tt,E=_e)}}}L=E,E=y[L],fe+=L-E&32767}if(Y){T[B++]=268435456|Np[H]<<18|Tx[Y];var Qe=Np[H]&31,Et=Tx[Y]&31;v+=Bp[Qe]+zp[Et],++N[257+Qe],++P[Et],k=I+H,++U}else T[B++]=i[I],++N[i[I]]}}for(I=Math.max(I,k);I<a;++I)T[B++]=i[I],++N[i[I]];h=Rx(i,l,c,T,N,P,v,B,V,I-V,h),c||(s.r=h&7|l[h/8|0]<<3,h-=7,s.h=b,s.p=y,s.i=I,s.w=k)}else{for(var I=s.w||0;I<a+c;I+=65535){var it=I+65535;it>=a&&(l[h/8|0]=c,it=a),h=Fx(l,h+1,i.subarray(I,it))}s.i=a}return Ox(o,0,n+Nx(h)+r)},ZE=(function(){for(var i=new Int32Array(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(t&1&&-306674912)^t>>>1;i[e]=t}return i})(),QE=function(){var i=-1;return{p:function(e){for(var t=i,n=0;n<e.length;++n)t=ZE[t&255^e[n]]^t>>>8;i=t},d:function(){return~i}}},eR=function(i,e,t,n,r){if(!r&&(r={l:1},e.dictionary)){var s=e.dictionary.subarray(-32768),a=new Cn(s.length+i.length);a.set(s),a.set(i,s.length),i=a,r.w=s.length}return JE(i,e.level==null?6:e.level,e.mem==null?r.l?Math.ceil(Math.max(8,Math.min(13,Math.log(i.length)))*1.5):20:12+e.mem,t,n,r)},kx=function(i,e){var t={};for(var n in i)t[n]=i[n];for(var n in e)t[n]=e[n];return t},Rn=function(i,e,t){for(;t;++e)i[e]=t,t>>>=8};Bx=function(i,e,t,n){for(var r in i){var s=i[r],a=e+r,o=n;Array.isArray(s)&&(o=kx(n,s[1]),s=s[0]),s instanceof Cn?t[a]=[s,o]:(t[a+="/"]=[new Cn(0),o],Bx(s,a,t,n))}},Cx=typeof TextEncoder<"u"&&new TextEncoder,nR=typeof TextDecoder<"u"&&new TextDecoder,iR=0;try{nR.decode(Ux,{stream:!0}),iR=1}catch{}Up=function(i){var e=0;if(i)for(var t in i){var n=i[t].length;n>65535&&nu(9),e+=n+4}return e},Ix=function(i,e,t,n,r,s,a,o){var l=n.length,c=t.extra,h=o&&o.length,d=Up(c);Rn(i,e,a!=null?33639248:67324752),e+=4,a!=null&&(i[e++]=20,i[e++]=t.os),i[e]=20,e+=2,i[e++]=t.flag<<1|(s<0&&8),i[e++]=r&&8,i[e++]=t.compression&255,i[e++]=t.compression>>8;var f=new Date(t.mtime==null?Date.now():t.mtime),p=f.getFullYear()-1980;if((p<0||p>119)&&nu(10),Rn(i,e,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),e+=4,s!=-1&&(Rn(i,e,t.crc),Rn(i,e+4,s<0?-s-2:s),Rn(i,e+8,t.size)),Rn(i,e+12,l),Rn(i,e+14,d),e+=16,a!=null&&(Rn(i,e,h),Rn(i,e+6,t.attrs),Rn(i,e+10,a),e+=14),i.set(n,e),e+=l,d)for(var x in c){var y=c[x],b=y.length;Rn(i,e,+x),Rn(i,e+2,b),i.set(y,e+4),e+=4+b}return h&&(i.set(o,e),e+=h),e},rR=function(i,e,t,n,r){Rn(i,e,101010256),Rn(i,e+8,t),Rn(i,e+10,t),Rn(i,e+12,n),Rn(i,e+16,r)}});var Kx={};Ar(Kx,{USDZExporter:()=>Gp});function Wx(i,e){let t=i.name;return t=t.replace(/[^A-Za-z0-9_]/g,""),/^[0-9]/.test(t)&&(t="_"+t),t===""&&(i.isCamera?t="Camera":t="Object"),e.has(t)&&(t=t+"_"+i.id),e.add(t),t}function sR(i,e,t){if(typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&i instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&i instanceof ImageBitmap){let n=t/Math.max(i.width,i.height),r=document.createElement("canvas");r.width=i.width*Math.min(1,n),r.height=i.height*Math.min(1,n);let s=r.getContext("2d");return e===!0&&(s.translate(0,r.height),s.scale(1,-1)),s.drawImage(i,0,0,r.width,r.height),r}else throw new Error("THREE.USDZExporter: No valid image data found. Unable to process texture.")}function qx(){return`#usda 1.0
+(
+ customLayerData = {
+ string creator = "Three.js USDZExporter"
+ }
+ defaultPrim = "Root"
+ metersPerUnit = 1
+ upAxis = "Y"
+)
+`}function $x(i,e,t,n,r,s){for(let a=0,o=i.children.length;a<o;a++){let l=i.children[a];if(l.visible===!1&&s.onlyVisible===!0)continue;let c;if(l.isMesh){let h=l.geometry,d=l.material;if(d.isMeshStandardMaterial){let f="geometries/Geometry_"+h.id+".usda";if(!(f in r)){let p=oR(h);r[f]=Qo(qx()+`
+`+p.toString())}d.uuid in t||(t[d.uuid]=d),c=aR(l,h,t[d.uuid],n)}else console.warn("THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)",l)}else l.isCamera?c=mR(l,n):c=jx(l,n);c&&(e.addChild(c),$x(l,c,t,n,r,s))}}function jx(i,e){let t=Wx(i,e);i.matrix.determinant()<0&&console.warn("THREE.USDZExporter: USDZ does not support negative scales",i);let n=new Wn(t,"Xform");if(i.pivot!==null){let r=i.position,s=i.quaternion,a=i.scale,o=i.pivot;n.addProperty(`float3 xformOp:translate = (${r.x.toPrecision(Ht)}, ${r.y.toPrecision(Ht)}, ${r.z.toPrecision(Ht)})`),n.addProperty(`float3 xformOp:translate:pivot = (${o.x.toPrecision(Ht)}, ${o.y.toPrecision(Ht)}, ${o.z.toPrecision(Ht)})`),n.addProperty(`quatf xformOp:orient = (${s.w.toPrecision(Ht)}, ${s.x.toPrecision(Ht)}, ${s.y.toPrecision(Ht)}, ${s.z.toPrecision(Ht)})`),n.addProperty(`float3 xformOp:scale = (${a.x.toPrecision(Ht)}, ${a.y.toPrecision(Ht)}, ${a.z.toPrecision(Ht)})`),n.addProperty('uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:translate:pivot", "xformOp:orient", "xformOp:scale", "!invert!xformOp:translate:pivot"]')}else{let r=Xx(i.matrix);n.addProperty(`matrix4d xformOp:transform = ${r}`),n.addProperty('uniform token[] xformOpOrder = ["xformOp:transform"]')}return n}function aR(i,e,t,n){let r=jx(i,n);return r.addMetadata("prepend references",`@./geometries/Geometry_${e.id}.usda@</Geometry>`),r.addMetadata("prepend apiSchemas",'["MaterialBindingAPI"]'),r.addProperty(`rel material:binding = </Materials/Material_${t.id}>`),r}function Xx(i){let e=i.elements;return`( ${iu(e,0)}, ${iu(e,4)}, ${iu(e,8)}, ${iu(e,12)} )`}function iu(i,e){return`(${i[e+0]}, ${i[e+1]}, ${i[e+2]}, ${i[e+3]})`}function oR(i){let e=new Wn("Geometry"),t=cR(i);return e.addChild(t),e}function cR(i){let e="Geometry",t=i.attributes,n=t.position.count,r=new Wn(e,"Mesh");r.addProperty(`int[] faceVertexCounts = [${lR(i)}]`),r.addProperty(`int[] faceVertexIndices = [${hR(i)}]`),r.addProperty(`normal3f[] normals = [${Hp(t.normal,n)}]`,['interpolation = "vertex"']),r.addProperty(`point3f[] points = [${Hp(t.position,n)}]`);for(let a=0;a<4;a++){let o=a>0?a:"",l=t["uv"+o];l!==void 0&&r.addProperty(`texCoord2f[] primvars:st${o} = [${uR(l)}]`,['interpolation = "vertex"'])}let s=t.color;return s!==void 0&&r.addProperty(`color3f[] primvars:displayColor = [${Hp(s,n)}]`,['interpolation = "vertex"']),r.addProperty('uniform token subdivisionScheme = "none"'),r}function lR(i){let e=i.index!==null?i.index.count:i.attributes.position.count;return Array(e/3).fill(3).join(", ")}function hR(i){let e=i.index,t=[];if(e!==null)for(let n=0;n<e.count;n++)t.push(e.getX(n));else{let n=i.attributes.position.count;for(let r=0;r<n;r++)t.push(r)}return t.join(", ")}function Hp(i,e){if(i===void 0)return console.warn("USDZExporter: Normals missing."),Array(e).fill("(0, 0, 0)").join(", ");let t=[];for(let n=0;n<i.count;n++){let r=i.getX(n),s=i.getY(n),a=i.getZ(n);t.push(`(${r.toPrecision(Ht)}, ${s.toPrecision(Ht)}, ${a.toPrecision(Ht)})`)}return t.join(", ")}function uR(i){let e=[];for(let t=0;t<i.count;t++){let n=i.getX(t),r=i.getY(t);e.push(`(${n.toPrecision(Ht)}, ${1-r.toPrecision(Ht)})`)}return e.join(", ")}function dR(i,e,t=!1){let n=new Wn("Materials");for(let r in i){let s=i[r];n.addChild(fR(s,e,t))}return n}function fR(i,e,t=!1){let n=new Wn(`Material_${i.id}`,"Material");function r(a,o,l){let c=a.source.id+"_"+a.flipY;e[c]=a;let h=a.channel>0?"st"+a.channel:"st",d={1e3:"repeat",1001:"clamp",1002:"mirror"},f=a.repeat.clone(),p=a.offset.clone(),x=a.rotation,y=Math.sin(x),b=Math.cos(x);p.y=1-p.y-f.y,t?(p.x=p.x/f.x,p.y=p.y/f.y,p.x+=y/f.x,p.y+=b-1):(p.x+=y*f.x,p.y+=(1-b)*f.y);let g=new Wn(`PrimvarReader_${o}`,"Shader");g.addProperty('uniform token info:id = "UsdPrimvarReader_float2"'),g.addProperty("float2 inputs:fallback = (0.0, 0.0)"),g.addProperty(`string inputs:varname = "${h}"`),g.addProperty("float2 outputs:result");let S=new Wn(`Transform2d_${o}`,"Shader");S.addProperty('uniform token info:id = "UsdTransform2d"'),S.addProperty(`float2 inputs:in.connect = </Materials/Material_${i.id}/PrimvarReader_${o}.outputs:result>`),S.addProperty(`float inputs:rotation = ${(x*(180/Math.PI)).toFixed(Ht)}`),S.addProperty(`float2 inputs:scale = ${Vx(f)}`),S.addProperty(`float2 inputs:translation = ${Vx(p)}`),S.addProperty("float2 outputs:result");let A=new Wn(`Texture_${a.id}_${o}`,"Shader");return A.addProperty('uniform token info:id = "UsdUVTexture"'),A.addProperty(`asset inputs:file = @textures/Texture_${c}.png@`),A.addProperty(`float2 inputs:st.connect = </Materials/Material_${i.id}/Transform2d_${o}.outputs:result>`),l!==void 0&&A.addProperty(`float4 inputs:scale = ${pR(l)}`),o==="normal"&&(A.addProperty("float4 inputs:scale = (2, 2, 2, 1)"),A.addProperty("float4 inputs:bias = (-1, -1, -1, 0)")),A.addProperty(`token inputs:sourceColorSpace = "${a.colorSpace===Fi?"raw":"sRGB"}"`),A.addProperty(`token inputs:wrapS = "${d[a.wrapS]}"`),A.addProperty(`token inputs:wrapT = "${d[a.wrapT]}"`),A.addProperty("float outputs:r"),A.addProperty("float outputs:g"),A.addProperty("float outputs:b"),A.addProperty("float3 outputs:rgb"),(i.transparent||i.alphaTest>0)&&A.addProperty("float outputs:a"),[g,S,A]}i.side===Dn&&console.warn("THREE.USDZExporter: USDZ does not support double sided materials",i);let s=new Wn("PreviewSurface","Shader");if(s.addProperty('uniform token info:id = "UsdPreviewSurface"'),i.map!==null?(s.addProperty(`color3f inputs:diffuseColor.connect = </Materials/Material_${i.id}/Texture_${i.map.id}_diffuse.outputs:rgb>`),i.transparent?s.addProperty(`float inputs:opacity.connect = </Materials/Material_${i.id}/Texture_${i.map.id}_diffuse.outputs:a>`):i.alphaTest>0&&(s.addProperty(`float inputs:opacity.connect = </Materials/Material_${i.id}/Texture_${i.map.id}_diffuse.outputs:a>`),s.addProperty(`float inputs:opacityThreshold = ${i.alphaTest}`)),r(i.map,"diffuse",i.color).forEach(o=>n.addChild(o))):s.addProperty(`color3f inputs:diffuseColor = ${Gx(i.color)}`),i.emissiveMap!==null){s.addProperty(`color3f inputs:emissiveColor.connect = </Materials/Material_${i.id}/Texture_${i.emissiveMap.id}_emissive.outputs:rgb>`);let a=new Ve(i.emissive.r*i.emissiveIntensity,i.emissive.g*i.emissiveIntensity,i.emissive.b*i.emissiveIntensity);r(i.emissiveMap,"emissive",a).forEach(l=>n.addChild(l))}else i.emissive.getHex()>0&&s.addProperty(`color3f inputs:emissiveColor = ${Gx(i.emissive)}`);if(i.normalMap!==null&&(s.addProperty(`normal3f inputs:normal.connect = </Materials/Material_${i.id}/Texture_${i.normalMap.id}_normal.outputs:rgb>`),r(i.normalMap,"normal").forEach(o=>n.addChild(o))),i.aoMap!==null){s.addProperty(`float inputs:occlusion.connect = </Materials/Material_${i.id}/Texture_${i.aoMap.id}_occlusion.outputs:r>`);let a=new Ve(i.aoMapIntensity,i.aoMapIntensity,i.aoMapIntensity);r(i.aoMap,"occlusion",a).forEach(l=>n.addChild(l))}if(i.roughnessMap!==null){s.addProperty(`float inputs:roughness.connect = </Materials/Material_${i.id}/Texture_${i.roughnessMap.id}_roughness.outputs:g>`);let a=new Ve(i.roughness,i.roughness,i.roughness);r(i.roughnessMap,"roughness",a).forEach(l=>n.addChild(l))}else s.addProperty(`float inputs:roughness = ${i.roughness}`);if(i.metalnessMap!==null){s.addProperty(`float inputs:metallic.connect = </Materials/Material_${i.id}/Texture_${i.metalnessMap.id}_metallic.outputs:b>`);let a=new Ve(i.metalness,i.metalness,i.metalness);r(i.metalnessMap,"metallic",a).forEach(l=>n.addChild(l))}else s.addProperty(`float inputs:metallic = ${i.metalness}`);if(i.alphaMap!==null?(s.addProperty(`float inputs:opacity.connect = </Materials/Material_${i.id}/Texture_${i.alphaMap.id}_opacity.outputs:r>`),s.addProperty("float inputs:opacityThreshold = 0.0001"),r(i.alphaMap,"opacity").forEach(o=>n.addChild(o))):s.addProperty(`float inputs:opacity = ${i.opacity}`),i.isMeshPhysicalMaterial){if(i.clearcoatMap!==null){s.addProperty(`float inputs:clearcoat.connect = </Materials/Material_${i.id}/Texture_${i.clearcoatMap.id}_clearcoat.outputs:r>`);let a=new Ve(i.clearcoat,i.clearcoat,i.clearcoat);r(i.clearcoatMap,"clearcoat",a).forEach(l=>n.addChild(l))}else s.addProperty(`float inputs:clearcoat = ${i.clearcoat}`);if(i.clearcoatRoughnessMap!==null){s.addProperty(`float inputs:clearcoatRoughness.connect = </Materials/Material_${i.id}/Texture_${i.clearcoatRoughnessMap.id}_clearcoatRoughness.outputs:g>`);let a=new Ve(i.clearcoatRoughness,i.clearcoatRoughness,i.clearcoatRoughness);r(i.clearcoatRoughnessMap,"clearcoatRoughness",a).forEach(l=>n.addChild(l))}else s.addProperty(`float inputs:clearcoatRoughness = ${i.clearcoatRoughness}`);s.addProperty(`float inputs:ior = ${i.ior}`)}return s.addProperty("int inputs:useSpecularWorkflow = 0"),s.addProperty("token outputs:surface"),n.addChild(s),n.addProperty(`token outputs:surface.connect = </Materials/Material_${i.id}/PreviewSurface.outputs:surface>`),n}function Gx(i){return`(${i.r}, ${i.g}, ${i.b})`}function pR(i){return`(${i.r}, ${i.g}, ${i.b}, 1.0)`}function Vx(i){return`(${i.x}, ${i.y})`}function mR(i,e){let t=Wx(i,e),n=Xx(i.matrix);i.matrix.determinant()<0&&console.warn("THREE.USDZExporter: USDZ does not support negative scales",i);let r=new Wn(t,"Camera");r.addProperty(`matrix4d xformOp:transform = ${n}`),r.addProperty('uniform token[] xformOpOrder = ["xformOp:transform"]');let s=i.isOrthographicCamera?"orthographic":"perspective";r.addProperty(`token projection = "${s}"`);let a=`(${i.near.toPrecision(Ht)}, ${i.far.toPrecision(Ht)})`;r.addProperty(`float2 clippingRange = ${a}`);let o;i.isOrthographicCamera?o=((Math.abs(i.left)+Math.abs(i.right))*10).toPrecision(Ht):o=i.getFilmWidth().toPrecision(Ht),r.addProperty(`float horizontalAperture = ${o}`);let l;if(i.isOrthographicCamera?l=((Math.abs(i.top)+Math.abs(i.bottom))*10).toPrecision(Ht):l=i.getFilmHeight().toPrecision(Ht),r.addProperty(`float verticalAperture = ${l}`),i.isPerspectiveCamera){let c=i.getFocalLength().toPrecision(Ht);r.addProperty(`float focalLength = ${c}`);let h=i.focus.toPrecision(Ht);r.addProperty(`float focusDistance = ${h}`)}return r}var Wn,Gp,Ht,Yx=un(()=>{Vn();Hx();Wn=class{constructor(e,t="",n=[],r=[]){this.name=e,this.type=t,this.metadata=n,this.properties=r,this.children=[]}addMetadata(e,t){this.metadata.push({key:e,value:t})}addProperty(e,t=[]){this.properties.push({property:e,metadata:t})}addChild(e){this.children.push(e)}toString(e=0){let t=" ".repeat(e),n=this.metadata.map(h=>{let d=h.key,f=h.value;if(Array.isArray(f)){let p=[];return p.push(`${d} = {`),f.forEach(x=>{p.push(`${t} ${x}`)}),p.push(`${t} }`),p.join(`
+`)}else return`${d} = ${f}`}),r=n.length?` (
+${n.map(h=>`${t} ${h}`).join(`
+`)}
+${t})`:"",s=this.properties.map(h=>{let d=h.property,f=h.metadata.length?` (
+${h.metadata.map(p=>`${t} ${p}`).join(`
+`)}
+${t} )`:"";return`${t} ${d}${f}`}),a=this.children.map(h=>h.toString(e+1)),o=[];if(s.length>0&&o.push(...s),a.length>0){s.length>0&&o.push("");for(let h=0;h<a.length;h++)o.push(a[h]),h<a.length-1&&o.push("")}let l=o.join(`
+`),c=this.type?this.type+" ":"";return`${t}def ${c}"${this.name}"${r}
+${t}{
+${l}
+${t}}`}},Gp=class{constructor(){this.textureUtils=null}setTextureUtils(e){this.textureUtils=e}parse(e,t,n,r){this.parseAsync(e,r).then(t).catch(n)}async parseAsync(e,t={}){t=Object.assign({ar:{anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}},includeAnchoringProperties:!0,onlyVisible:!0,quickLookCompatible:!1,maxTextureSize:1024},t);let n=new Set,r={},s="model.usda";r[s]=null;let a=new Wn("Root","Xform"),o=new Wn("Scenes","Scope");o.addMetadata("kind",'"sceneLibrary"'),a.addChild(o);let l="Scene",c=new Wn(l,"Xform");c.addMetadata("customData",["bool preliminary_collidesWithEnvironment = 0",`string sceneName = "${l}"`]),c.addMetadata("sceneName",`"${l}"`),t.includeAnchoringProperties&&(c.addProperty(`token preliminary:anchoring:type = "${t.ar.anchoring.type}"`),c.addProperty(`token preliminary:planeAnchoring:alignment = "${t.ar.planeAnchoring.alignment}"`)),o.addChild(c);let h,d={},f={};$x(e,c,d,n,r,t);let p=dR(d,f,t.quickLookCompatible);h=qx()+`
+`+a.toString()+`
+
+`+p.toString(),r[s]=Qo(h),h=null;for(let y in f){let b=f[y];if(b.isCompressedTexture===!0){if(this.textureUtils===null)throw new Error("THREE.USDZExporter: setTextureUtils() must be called to process compressed textures.");b=await this.textureUtils.decompress(b)}let g=sR(b.image,b.flipY,t.maxTextureSize),S=await new Promise(A=>g.toBlob(A,"image/png",1));r[`textures/Texture_${y}.png`]=new Uint8Array(await S.arrayBuffer())}let x=0;for(let y in r){let b=r[y],g=34+y.length;x+=g;let S=x&63;if(S!==4){let A=64-S,T=new Uint8Array(A);r[y]=[b,{extra:{12345:T}}]}x=b.length}return zx(r,{level:0})}};Ht=7});var Qp={};Ar(Qp,{MAX_AR_FOOTPRINT_M:()=>Yp,MAX_AR_HEIGHT_M:()=>Jp,bakeSkinnedMeshes:()=>Vp,bakedLocalPositions:()=>Jx,clampToPlaceableSize:()=>Zp,coerceMaterialsToStandard:()=>Wp,ensureNormals:()=>qp,fitToRoomScale:()=>Kp,glbUrlToUsdzBlob:()=>Qx,groundOnFloor:()=>Xp,objectToUsdzBlob:()=>Zx,sceneToUsdzBlob:()=>ru,usdzExportRoot:()=>$p});function Jx(i){let e=i.geometry.getAttribute("position"),t=new Float32Array(e.count*3),n=new W;for(let r=0;r<e.count;r++)n.fromBufferAttribute(e,r),i.applyBoneTransform(r,n),t[r*3]=n.x,t[r*3+1]=n.y,t[r*3+2]=n.z;return t}function Vp(i){i.updateMatrixWorld(!0);let e=[];i.traverse(t=>{t.isSkinnedMesh&&t.skeleton?.bones?.length&&e.push(t)});for(let t of e){if(!t.geometry.getAttribute("position"))continue;let n=t.geometry.clone();n.setAttribute("position",new Kt(Jx(t),3)),n.deleteAttribute("skinIndex"),n.deleteAttribute("skinWeight"),n.computeVertexNormals();let r=new xt(n,t.material);r.name=t.name,r.visible=t.visible,r.position.copy(t.position),r.quaternion.copy(t.quaternion),r.scale.copy(t.scale);let s=t.parent||i;s.add(r),s.remove(t)}}function Wp(i){i.traverse(e=>{if(!e.isMesh)return;(Array.isArray(e.material)?e.material:[e.material]).forEach((n,r)=>{if(!n||n.isMeshStandardMaterial)return;let s=new gi({color:n.color?n.color.clone():new Ve(16777215),map:n.map||null,normalMap:n.normalMap||null,roughness:typeof n.roughness=="number"?n.roughness:.85,metalness:typeof n.metalness=="number"?n.metalness:0,transparent:!!n.transparent,opacity:typeof n.opacity=="number"?n.opacity:1,side:n.side??Dn});Array.isArray(e.material)?e.material[r]=s:e.material=s})})}function qp(i){i.traverse(e=>{!e.isMesh||!e.geometry||e.geometry.getAttribute("normal")||e.geometry.getAttribute("position")&&e.geometry.computeVertexNormals()})}function $p(i){let e=new pn;e.name="Root";let t=new pn;return t.name="Model",t.add(i),e.add(t),e.updateMatrixWorld(!0),{root:e,stage:t}}function jp(i){i.updateMatrixWorld(!0);let e=new rn().setFromObject(i);if(e.isEmpty())return null;let t=e.min,n=e.max;return[t.x,t.y,t.z,n.x,n.y,n.z].every(Number.isFinite)?e:null}function Xp(i,e){let t=jp(e);if(!t)return!1;let n=t.getCenter(new W);return i.position.x-=n.x,i.position.y-=t.min.y,i.position.z-=n.z,e.updateMatrixWorld(!0),!0}function Kp(i,e){let t=jp(e);if(!t)return 1;let n=!1;e.traverse(s=>{s.isSkinnedMesh&&(n=!0)});let{scale:r}=Ko({min:{x:t.min.x,y:t.min.y,z:t.min.z},max:{x:t.max.x,y:t.max.y,z:t.max.z}},{skinned:n});return!(r>0)||r===1?1:(i.scale.multiplyScalar(r),e.updateMatrixWorld(!0),r)}function Zp(i,e,{maxFootprint:t=Yp,maxHeight:n=Jp}={}){let r=jp(e);if(!r)return 1;let s=r.getSize(new W),a=Math.max(s.x,s.z),o=Math.min(a>0?t/a:1,s.y>0?n/s.y:1);return!(o<1)||!Number.isFinite(o)?1:(i.scale.multiplyScalar(o),e.updateMatrixWorld(!0),o)}async function ru(i,{fit:e=!1,...t}={}){let{root:n,stage:r}=$p(i);Vp(n),Wp(n),qp(n),e&&Kp(r,n),Zp(r,n),Xp(r,n);let{USDZExporter:s}=await Promise.resolve().then(()=>(Yx(),Kx)),a=await new s().parseAsync(n,{quickLookCompatible:!0,includeAnchoringProperties:!0,ar:{anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}},...t});return new Blob([a],{type:"model/vnd.usdz+zip"})}async function Zx(i){i.updateMatrixWorld(!0);let e=Cs(i);return e.position.set(0,0,0),e.rotation.set(0,0,0),e.scale.copy(i.getWorldScale(new W)),e.updateMatrixWorld(!0),ru(e)}async function Qx(i,{signal:e,onProgress:t}={}){t?.("download");let n=await fetch(i,{signal:e});if(!n.ok)throw new Error(`model fetch ${n.status}`);let r=await n.arrayBuffer();t?.("parse");let s=await Kb(),a=await new Promise((l,c)=>{s.parse(r,"",l,c)}),o=a.scene||a.scenes?.[0];if(!o)throw new Error("that model contains no scene");return t?.("convert"),ru(o,{fit:!0})}var Yp,Jp,su=un(()=>{Vn();wh();Vh();eu();Yp=2.5,Jp=2.5});var f_=dn(()=>{"use strict";ArrayBuffer.isView||(ArrayBuffer.isView=i=>i!==null&&typeof i=="object"&&i.buffer instanceof ArrayBuffer);typeof globalThis>"u"&&typeof window<"u"&&(window.globalThis=window);typeof FormData>"u"&&(globalThis.FormData=class{})});var ic={};Ar(ic,{__addDisposableResource:()=>k_,__assign:()=>du,__asyncDelegator:()=>I_,__asyncGenerator:()=>C_,__asyncValues:()=>P_,__await:()=>Na,__awaiter:()=>w_,__classPrivateFieldGet:()=>O_,__classPrivateFieldIn:()=>U_,__classPrivateFieldSet:()=>F_,__createBinding:()=>pu,__decorate:()=>g_,__disposeResources:()=>B_,__esDecorate:()=>x_,__exportStar:()=>A_,__extends:()=>p_,__generator:()=>M_,__importDefault:()=>N_,__importStar:()=>D_,__makeTemplateObject:()=>L_,__metadata:()=>S_,__param:()=>b_,__propKey:()=>y_,__read:()=>dm,__rest:()=>m_,__rewriteRelativeImportExtension:()=>z_,__runInitializers:()=>__,__setFunctionName:()=>v_,__spread:()=>T_,__spreadArray:()=>R_,__spreadArrays:()=>E_,__values:()=>fu,default:()=>TR});function p_(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");hm(i,e);function t(){this.constructor=i}i.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function m_(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(t[n[r]]=i[n[r]]);return t}function g_(i,e,t,n){var r=arguments.length,s=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(i,e,t,n);else for(var o=i.length-1;o>=0;o--)(a=i[o])&&(s=(r<3?a(s):r>3?a(e,t,s):a(e,t))||s);return r>3&&s&&Object.defineProperty(e,t,s),s}function b_(i,e){return function(t,n){e(t,n,i)}}function x_(i,e,t,n,r,s){function a(g){if(g!==void 0&&typeof g!="function")throw new TypeError("Function expected");return g}for(var o=n.kind,l=o==="getter"?"get":o==="setter"?"set":"value",c=!e&&i?n.static?i:i.prototype:null,h=e||(c?Object.getOwnPropertyDescriptor(c,n.name):{}),d,f=!1,p=t.length-1;p>=0;p--){var x={};for(var y in n)x[y]=y==="access"?{}:n[y];for(var y in n.access)x.access[y]=n.access[y];x.addInitializer=function(g){if(f)throw new TypeError("Cannot add initializers after decoration has completed");s.push(a(g||null))};var b=(0,t[p])(o==="accessor"?{get:h.get,set:h.set}:h[l],x);if(o==="accessor"){if(b===void 0)continue;if(b===null||typeof b!="object")throw new TypeError("Object expected");(d=a(b.get))&&(h.get=d),(d=a(b.set))&&(h.set=d),(d=a(b.init))&&r.unshift(d)}else(d=a(b))&&(o==="field"?r.unshift(d):h[l]=d)}c&&Object.defineProperty(c,n.name,h),f=!0}function __(i,e,t){for(var n=arguments.length>2,r=0;r<e.length;r++)t=n?e[r].call(i,t):e[r].call(i);return n?t:void 0}function y_(i){return typeof i=="symbol"?i:"".concat(i)}function v_(i,e,t){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(i,"name",{configurable:!0,value:t?"".concat(t," ",e):e})}function S_(i,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,e)}function w_(i,e,t,n){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(h){try{c(n.next(h))}catch(d){a(d)}}function l(h){try{c(n.throw(h))}catch(d){a(d)}}function c(h){h.done?s(h.value):r(h.value).then(o,l)}c((n=n.apply(i,e||[])).next())})}function M_(i,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,r,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(c){return function(h){return l([c,h])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(t=0)),t;)try{if(n=1,r&&(s=c[0]&2?r.return:c[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,c[1])).done)return s;switch(r=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,r=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){t.label=c[1];break}if(c[0]===6&&t.label<s[1]){t.label=s[1],s=c;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(c);break}s[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(i,t)}catch(h){c=[6,h],r=0}finally{n=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function A_(i,e){for(var t in i)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&pu(e,i,t)}function fu(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function dm(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,s=[],a;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.push(r.value)}catch(o){a={error:o}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return s}function T_(){for(var i=[],e=0;e<arguments.length;e++)i=i.concat(dm(arguments[e]));return i}function E_(){for(var i=0,e=0,t=arguments.length;e<t;e++)i+=arguments[e].length;for(var n=Array(i),r=0,e=0;e<t;e++)for(var s=arguments[e],a=0,o=s.length;a<o;a++,r++)n[r]=s[a];return n}function R_(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return i.concat(s||Array.prototype.slice.call(e))}function Na(i){return this instanceof Na?(this.v=i,this):new Na(i)}function C_(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(i,e||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),r[Symbol.asyncIterator]=function(){return this},r;function a(p){return function(x){return Promise.resolve(x).then(p,d)}}function o(p,x){n[p]&&(r[p]=function(y){return new Promise(function(b,g){s.push([p,y,b,g])>1||l(p,y)})},x&&(r[p]=x(r[p])))}function l(p,x){try{c(n[p](x))}catch(y){f(s[0][3],y)}}function c(p){p.value instanceof Na?Promise.resolve(p.value.v).then(h,d):f(s[0][2],p)}function h(p){l("next",p)}function d(p){l("throw",p)}function f(p,x){p(x),s.shift(),s.length&&l(s[0][0],s[0][1])}}function I_(i){var e,t;return e={},n("next"),n("throw",function(r){throw r}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(r,s){e[r]=i[r]?function(a){return(t=!t)?{value:Na(i[r](a)),done:!1}:s?s(a):a}:s}}function P_(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof fu=="function"?fu(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=i[s]&&function(a){return new Promise(function(o,l){a=i[s](a),r(o,l,a.done,a.value)})}}function r(s,a,o,l){Promise.resolve(l).then(function(c){s({value:c,done:o})},a)}}function L_(i,e){return Object.defineProperty?Object.defineProperty(i,"raw",{value:e}):i.raw=e,i}function D_(i){if(i&&i.__esModule)return i;var e={};if(i!=null)for(var t=um(i),n=0;n<t.length;n++)t[n]!=="default"&&pu(e,i,t[n]);return MR(e,i),e}function N_(i){return i&&i.__esModule?i:{default:i}}function O_(i,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?i!==e||!n:!e.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(i):n?n.value:e.get(i)}function F_(i,e,t,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?i!==e||!r:!e.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(i,t):r?r.value=t:e.set(i,t),t}function U_(i,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof i=="function"?e===i:i.has(e)}function k_(i,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,r;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(r=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");r&&(n=function(){try{r.call(this)}catch(s){return Promise.reject(s)}}),i.stack.push({value:e,dispose:n,async:t})}else t&&i.stack.push({async:!0});return e}function B_(i){function e(s){i.error=i.hasError?new AR(s,i.error,"An error was suppressed during disposal."):s,i.hasError=!0}var t,n=0;function r(){for(;t=i.stack.pop();)try{if(!t.async&&n===1)return n=0,i.stack.push(t),Promise.resolve().then(r);if(t.dispose){var s=t.dispose.call(t.value);if(t.async)return n|=2,Promise.resolve(s).then(r,function(a){return e(a),r()})}else n|=1}catch(a){e(a)}if(n===1)return i.hasError?Promise.reject(i.error):Promise.resolve();if(i.hasError)throw i.error}return r()}function z_(i,e){return typeof i=="string"&&/^\.\.?\//.test(i)?i.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(t,n,r,s,a){return n?e?".jsx":".js":r&&(!s||!a)?t:r+s+"."+a.toLowerCase()+"js"}):i}var hm,du,pu,MR,um,AR,TR,rc=un(()=>{hm=function(i,e){return hm=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])},hm(i,e)};du=function(){return du=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])}return e},du.apply(this,arguments)};pu=Object.create?(function(i,e,t,n){n===void 0&&(n=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(i,n,r)}):(function(i,e,t,n){n===void 0&&(n=t),i[n]=e[t]});MR=Object.create?(function(i,e){Object.defineProperty(i,"default",{enumerable:!0,value:e})}):function(i,e){i.default=e},um=function(i){return um=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},um(i)};AR=typeof SuppressedError=="function"?SuppressedError:function(i,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=i,n.suppressed=e,n};TR={__extends:p_,__assign:du,__rest:m_,__decorate:g_,__param:b_,__esDecorate:x_,__runInitializers:__,__propKey:y_,__setFunctionName:v_,__metadata:S_,__awaiter:w_,__generator:M_,__createBinding:pu,__exportStar:A_,__values:fu,__read:dm,__spread:T_,__spreadArrays:E_,__spreadArray:R_,__await:Na,__asyncGenerator:C_,__asyncDelegator:I_,__asyncValues:P_,__makeTemplateObject:L_,__importStar:D_,__importDefault:N_,__classPrivateFieldGet:O_,__classPrivateFieldSet:F_,__classPrivateFieldIn:U_,__addDisposableResource:k_,__disposeResources:B_,__rewriteRelativeImportExtension:z_}});var sc=dn(Oa=>{"use strict";Oa.CloseCode=void 0;(function(i){i[i.CONSENTED=4e3]="CONSENTED",i[i.DEVMODE_RESTART=4010]="DEVMODE_RESTART"})(Oa.CloseCode||(Oa.CloseCode={}));var fm=class extends Error{constructor(e,t){super(t),this.name="ServerError",this.code=e}},pm=class extends Error{constructor(e){super(e),this.name="AbortError"}};Oa.AbortError=pm;Oa.ServerError=fm});var ac=dn((mu,H_)=>{(function(i,e){typeof mu=="object"&&typeof H_<"u"?e(mu):typeof define=="function"&&define.amd?define(["exports"],e):(i=typeof globalThis<"u"?globalThis:i||self,e(i.schema={}))})(mu,(function(i){"use strict";i.OPERATION=void 0,(function(R){R[R.ADD=128]="ADD",R[R.REPLACE=0]="REPLACE",R[R.DELETE=64]="DELETE",R[R.DELETE_AND_MOVE=96]="DELETE_AND_MOVE",R[R.MOVE_AND_ADD=160]="MOVE_AND_ADD",R[R.DELETE_AND_ADD=192]="DELETE_AND_ADD",R[R.CLEAR=10]="CLEAR",R[R.REVERSE=15]="REVERSE",R[R.MOVE=32]="MOVE",R[R.DELETE_BY_REFID=33]="DELETE_BY_REFID",R[R.ADD_BY_REFID=129]="ADD_BY_REFID"})(i.OPERATION||(i.OPERATION={})),Symbol.metadata??=Symbol.for("Symbol.metadata");let n="~track",r="~encoder",s="~decoder",a="~filter",o="~getByIndex",l="~deleteByIndex",c="~changes",h="~childType",d="~onEncodeEnd",f="~onDecodeEnd",p="~descriptors",x="~__numFields",y="~__refTypeFieldIndexes",b="~__viewFieldIndexes",g="$__fieldIndexesByViewTag",S;try{S=new TextEncoder}catch{}let A=new ArrayBuffer(8),T=new Int32Array(A),N=new Float32Array(A),P=new Float64Array(A),U=new BigInt64Array(A),I=typeof Buffer<"u"&&Buffer.byteLength?Buffer.byteLength:function(R,u){for(var m=0,_=0,w=0,z=R.length;w<z;w++)m=R.charCodeAt(w),m<128?_+=1:m<2048?_+=2:m<55296||m>=57344?_+=3:(w++,_+=4);return _};function B(R,u,m){for(var _=0,w=0,z=u.length;w<z;w++)_=u.charCodeAt(w),_<128?R[m.offset++]=_:_<2048?(R[m.offset]=192|_>>6,R[m.offset+1]=128|_&63,m.offset+=2):_<55296||_>=57344?(R[m.offset]=224|_>>12,R[m.offset+1]=128|_>>6&63,R[m.offset+2]=128|_&63,m.offset+=3):(w++,_=65536+((_&1023)<<10|u.charCodeAt(w)&1023),R[m.offset]=240|_>>18,R[m.offset+1]=128|_>>12&63,R[m.offset+2]=128|_>>6&63,R[m.offset+3]=128|_&63,m.offset+=4)}function k(R,u,m){R[m.offset++]=u&255}function V(R,u,m){R[m.offset++]=u&255}function J(R,u,m){R[m.offset++]=u&255,R[m.offset++]=u>>8&255}function L(R,u,m){R[m.offset++]=u&255,R[m.offset++]=u>>8&255}function E(R,u,m){R[m.offset++]=u&255,R[m.offset++]=u>>8&255,R[m.offset++]=u>>16&255,R[m.offset++]=u>>24&255}function D(R,u,m){let _=u>>24,w=u>>16,z=u>>8,X=u;R[m.offset++]=X&255,R[m.offset++]=z&255,R[m.offset++]=w&255,R[m.offset++]=_&255}function O(R,u,m){let _=Math.floor(u/Math.pow(2,32)),w=u>>>0;D(R,w,m),D(R,_,m)}function H(R,u,m){let _=u/Math.pow(2,32)>>0,w=u>>>0;D(R,w,m),D(R,_,m)}function Y(R,u,m){U[0]=BigInt.asIntN(64,u),E(R,T[0],m),E(R,T[1],m)}function le(R,u,m){U[0]=BigInt.asIntN(64,u),E(R,T[0],m),E(R,T[1],m)}function fe(R,u,m){N[0]=u,E(R,T[0],m)}function be(R,u,m){P[0]=u,E(R,T[0],m),E(R,T[1],m)}function Te(R,u,m){R[m.offset++]=u?1:0}function Je(R,u,m){u||(u="");let _=I(u,"utf8"),w=0;if(_<32)R[m.offset++]=_|160,w=1;else if(_<256)R[m.offset++]=217,R[m.offset++]=_%255,w=2;else if(_<65536)R[m.offset++]=218,L(R,_,m),w=3;else if(_<4294967296)R[m.offset++]=219,D(R,_,m),w=5;else throw new Error("String too long");return B(R,u,m),w+_}function ke(R,u,m){if(isNaN(u))return ke(R,0,m);if(isFinite(u)){if(u!==(u|0))return Math.abs(u)<=34028235e31&&(N[0]=u,Math.abs(Math.abs(N[0])-Math.abs(u))<1e-4)?(R[m.offset++]=202,fe(R,u,m),5):(R[m.offset++]=203,be(R,u,m),9)}else return ke(R,u>0?Number.MAX_SAFE_INTEGER:-Number.MAX_SAFE_INTEGER,m);return u>=0?u<128?(R[m.offset++]=u&255,1):u<256?(R[m.offset++]=204,R[m.offset++]=u&255,2):u<65536?(R[m.offset++]=205,L(R,u,m),3):u<4294967296?(R[m.offset++]=206,D(R,u,m),5):(R[m.offset++]=207,H(R,u,m),9):u>=-32?(R[m.offset++]=224|u+32,1):u>=-128?(R[m.offset++]=208,k(R,u,m),2):u>=-32768?(R[m.offset++]=209,J(R,u,m),3):u>=-2147483648?(R[m.offset++]=210,E(R,u,m),5):(R[m.offset++]=211,O(R,u,m),9)}let oe={int8:k,uint8:V,int16:J,uint16:L,int32:E,uint32:D,int64:O,uint64:H,bigint64:Y,biguint64:le,float32:fe,float64:be,boolean:Te,string:Je,number:ke,utf8Write:B,utf8Length:I},Ee=new ArrayBuffer(8),_e=new Int32Array(Ee),Ze=new Float32Array(Ee),tt=new Float64Array(Ee),Qe=new BigUint64Array(Ee),Et=new BigInt64Array(Ee);function it(R,u,m){m>R.length-u.offset&&(m=R.length-u.offset);for(var _="",w=0,z=u.offset,X=u.offset+m;z<X;z++){var ue=R[z];if((ue&128)===0){_+=String.fromCharCode(ue);continue}if((ue&224)===192){_+=String.fromCharCode((ue&31)<<6|R[++z]&63);continue}if((ue&240)===224){_+=String.fromCharCode((ue&15)<<12|(R[++z]&63)<<6|(R[++z]&63)<<0);continue}if((ue&248)===240){w=(ue&7)<<18|(R[++z]&63)<<12|(R[++z]&63)<<6|(R[++z]&63)<<0,w>=65536?(w-=65536,_+=String.fromCharCode((w>>>10)+55296,(w&1023)+56320)):_+=String.fromCharCode(w);continue}console.error("decode.utf8Read(): Invalid byte "+ue+" at offset "+z+". Skip to end of string: "+(u.offset+m));break}return u.offset+=m,_}function mt(R,u){return wt(R,u)<<24>>24}function wt(R,u){return R[u.offset++]}function lt(R,u){return Bt(R,u)<<16>>16}function Bt(R,u){return R[u.offset++]|R[u.offset++]<<8}function gt(R,u){return R[u.offset++]|R[u.offset++]<<8|R[u.offset++]<<16|R[u.offset++]<<24}function Yt(R,u){return gt(R,u)>>>0}function q(R,u){return _e[0]=gt(R,u),Ze[0]}function $t(R,u){return _e[0]=gt(R,u),_e[1]=gt(R,u),tt[0]}function ht(R,u){let m=Yt(R,u);return gt(R,u)*Math.pow(2,32)+m}function Tt(R,u){let m=Yt(R,u);return Yt(R,u)*Math.pow(2,32)+m}function Pe(R,u){return _e[0]=gt(R,u),_e[1]=gt(R,u),Et[0]}function Ot(R,u){return _e[0]=gt(R,u),_e[1]=gt(R,u),Qe[0]}function F(R,u){return wt(R,u)>0}function M(R,u){let m=R[u.offset++],_;return m<192?_=m&31:m===217?_=wt(R,u):m===218?_=Bt(R,u):m===219&&(_=Yt(R,u)),it(R,u,_)}function Z(R,u){let m=R[u.offset++];if(m<128)return m;if(m===202)return q(R,u);if(m===203)return $t(R,u);if(m===204)return wt(R,u);if(m===205)return Bt(R,u);if(m===206)return Yt(R,u);if(m===207)return Tt(R,u);if(m===208)return mt(R,u);if(m===209)return lt(R,u);if(m===210)return gt(R,u);if(m===211)return ht(R,u);if(m>223)return(255-m+1)*-1}function pe(R,u){let m=R[u.offset];return m<192&&m>160||m===217||m===218||m===219}let ge={utf8Read:it,int8:mt,uint8:wt,int16:lt,uint16:Bt,int32:gt,uint32:Yt,float32:q,float64:$t,int64:ht,uint64:Tt,bigint64:Pe,biguint64:Ot,boolean:F,string:M,number:Z,stringCheck:pe},Se={},Ce=new Map;function ce(R,u){u.constructor&&(Ce.set(u.constructor,R),Se[R]=u),u.encode&&(oe[R]=u.encode),u.decode&&(ge[R]=u.decode)}function me(R){return Se[R]}function Be(R){for(let u in R)ce(u,R[u]);return u=>ni(u)}let sn=class sn{static register(u){let m=Object.getPrototypeOf(u);if(m!==Ie){let _=sn.inheritedTypes.get(m);_||(_=new Set,sn.inheritedTypes.set(m,_)),_.add(u)}}static cache(u){let m=sn.cachedContexts.get(u);return m||(m=new sn(u),sn.cachedContexts.set(u,m)),m}constructor(u){this.types={},this.schemas=new Map,this.hasFilters=!1,this.parentFiltered={},u&&this.discoverTypes(u)}has(u){return this.schemas.has(u)}get(u){return this.types[u]}add(u,m=this.schemas.size){return this.schemas.has(u)?!1:(this.types[m]=u,u[Symbol.metadata]===void 0&&je.initialize(u),this.schemas.set(u,m),!0)}getTypeId(u){return this.schemas.get(u)}discoverTypes(u,m,_,w){if(w&&this.registerFilteredByParent(u,m,_),!this.add(u))return;sn.inheritedTypes.get(u)?.forEach(ue=>{this.discoverTypes(ue,m,_,w)});let z=u;for(;(z=Object.getPrototypeOf(z))&&z!==Ie&&z!==Function.prototype;)this.discoverTypes(z);let X=u[Symbol.metadata]??={};X[b]&&(this.hasFilters=!0);for(let ue in X){let ne=ue,ae=X[ne].type,he=X[ne].tag!==void 0;if(typeof ae!="string")if(typeof ae=="function")this.discoverTypes(ae,u,ne,w||he);else{let se=Object.values(ae)[0];if(typeof se=="string")continue;this.discoverTypes(se,u,ne,w||he)}}}registerFilteredByParent(u,m,_){let z=`${this.schemas.get(u)??this.schemas.size}`;m&&(z+=`-${this.schemas.get(m)}`),z+=`-${_}`,this.parentFiltered[z]=!0}debug(){let u="";for(let m in this.parentFiltered){let _=m.split("-").map(Number),w=_.pop();u+=`
+ `,u+=`${m}: ${_.reverse().map((z,X)=>{let ue=this.types[z],ne=ue[Symbol.metadata],ae=ue.name;return X===0&&(ae+=`[${ne[w].name}]`),`${ae}`}).join(" -> ")}`}return`TypeContext ->
+ Schema types: ${this.schemas.size}
+ hasFilters: ${this.hasFilters}
+ parentFiltered:${u}`}};sn.inheritedTypes=new Map,sn.cachedContexts=new Map;let Le=sn;function ve(R){if(Array.isArray(R))return{array:ve(R[0])};if(typeof R.type<"u")return R.type;if(Me(R))return Object.keys(R).every(u=>typeof R[u]=="string")?"string":"number";if(typeof R=="object"&&R!==null){let u=Object.keys(R).find(m=>Se[m]!==void 0);if(u)return R[u]=ve(R[u]),R}return R}function Me(R){if(typeof R=="function"&&R[Symbol.metadata])return!1;let u=Object.keys(R),m=u.filter(_=>/\d+/.test(_));return!!(m.length>0&&m.length===u.length/2&&R[R[m[0]]]==m[0]||u.length>0&&u.every(_=>typeof R[_]=="string"&&R[_]===_))}let je={addField(R,u,m,_,w){if(u>64)throw new Error(`Can't define field '${m}'.
+Schema instances may only have up to 64 fields.`);R[u]=Object.assign(R[u]||{},{type:ve(_),index:u,name:m}),Object.defineProperty(R,p,{value:R[p]||{},enumerable:!1,configurable:!0}),w?(R[p][m]=w,R[p][`_${m}`]={value:void 0,writable:!0,enumerable:!1,configurable:!0}):R[p][m]={value:void 0,writable:!0,enumerable:!0,configurable:!0},Object.defineProperty(R,x,{value:u,enumerable:!1,configurable:!0}),Object.defineProperty(R,m,{value:u,enumerable:!1,configurable:!0}),typeof R[u].type!="string"&&(R[y]===void 0&&Object.defineProperty(R,y,{value:[],enumerable:!1,configurable:!0}),R[y].push(u))},setTag(R,u,m){let _=R[u],w=R[_];w.tag=m,R[b]||(Object.defineProperty(R,b,{value:[],enumerable:!1,configurable:!0}),Object.defineProperty(R,g,{value:{},enumerable:!1,configurable:!0})),R[b].push(_),R[g][m]||(R[g][m]=[]),R[g][m].push(_)},setFields(R,u){let m=R.prototype.constructor;Le.register(m);let _=Object.getPrototypeOf(m),w=_&&_[Symbol.metadata],z=je.initialize(m);m[n]||(m[n]=Ie[n]),m[r]||(m[r]=Ie[r]),m[s]||(m[s]=Ie[s]),m.prototype.toJSON||(m.prototype.toJSON=Ie.prototype.toJSON);let X=z[x]??(w&&w[x])??-1;X++;for(let ue in u){let ne=ve(u[ue]),ae=typeof Object.keys(ne)[0]=="string"&&me(Object.keys(ne)[0]),he=ae?Object.values(ne)[0]:ne;je.addField(z,X,ue,ne,C(`_${ue}`,X,he,ae)),X++}return R},isDeprecated(R,u){return R[u].deprecated===!0},init(R){let u={};R[Symbol.metadata]=u,Object.defineProperty(u,x,{value:0,enumerable:!1,configurable:!0})},initialize(R){let u=Object.getPrototypeOf(R),m=u[Symbol.metadata],_=R[Symbol.metadata]??Object.create(null);return u!==Ie&&_===m&&(_=Object.create(null),m&&(Object.setPrototypeOf(_,m),Object.defineProperty(_,x,{value:m[x],enumerable:!1,configurable:!0,writable:!0}),m[b]!==void 0&&(Object.defineProperty(_,b,{value:[...m[b]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(_,g,{value:{...m[g]},enumerable:!1,configurable:!0,writable:!0})),m[y]!==void 0&&Object.defineProperty(_,y,{value:[...m[y]],enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(_,p,{value:{...m[p]},enumerable:!1,configurable:!0,writable:!0}))),Object.defineProperty(R,Symbol.metadata,{value:_,writable:!1,configurable:!0}),_},isValidInstance(R){return R.constructor[Symbol.metadata]&&Object.prototype.hasOwnProperty.call(R.constructor[Symbol.metadata],x)},getFields(R){let u=R[Symbol.metadata],m={};for(let _=0;_<=u[x];_++)m[u[_].name]=u[_].type;return m},hasViewTagAtIndex(R,u){return R?.[b]?.includes(u)}};function nt(R){return{indexes:{},operations:[],queueRootNode:R}}function pt(){return{next:void 0,tail:void 0}}function G(R,u){let m=R.indexes[u];m===void 0?R.indexes[u]=R.operations.push(u)-1:R.operations[m]=u}function we(R,u){let m=R.indexes[u];m===void 0&&(m=Object.values(R.indexes).at(-1),u=Object.entries(R.indexes).find(([_,w])=>w===m)?.[0]),R.operations[m]=void 0,delete R.indexes[u]}class de{constructor(u){this.isFiltered=!1,this.indexedOperations={},this.changes={indexes:{},operations:[]},this.allChanges={indexes:{},operations:[]},this.isNew=!0,this.ref=u,this.metadata=u.constructor[Symbol.metadata],this.metadata?.[b]&&(this.allFilteredChanges={indexes:{},operations:[]},this.filteredChanges={indexes:{},operations:[]})}setRoot(u){this.root=u;let m=this.root.add(this);this.checkIsFiltered(this.parent,this.parentIndex,m),m&&this.forEachChild((_,w)=>{_.root!==u?_.setRoot(u):u.add(_)})}setParent(u,m,_){if(this.addParent(u,_),!m)return;let w=m.add(this);m!==this.root&&(this.root=m,this.checkIsFiltered(u,_,w)),w&&this.forEachChild((z,X)=>{if(z.root===m){m.add(z),m.moveNextToParent(z);return}z.setParent(this.ref,m,X)})}forEachChild(u){if(this.ref[h]){if(typeof this.ref[h]!="string")for(let[m,_]of this.ref.entries())_&&u(_[c],this.indexes?.[m]??m)}else for(let m of this.metadata?.[y]??[]){let _=this.metadata[m],w=this.ref[_.name];w&&u(w[c],m)}}operation(u){this.filteredChanges!==void 0?(this.filteredChanges.operations.push(-u),this.root?.enqueueChangeTree(this,"filteredChanges")):(this.changes.operations.push(-u),this.root?.enqueueChangeTree(this,"changes"))}change(u,m=i.OPERATION.ADD){let _=this.isFiltered||this.metadata?.[u]?.tag!==void 0,w=_?this.filteredChanges:this.changes,z=this.indexedOperations[u];if(!z||z===i.OPERATION.DELETE){let X=z&&z===i.OPERATION.DELETE?i.OPERATION.DELETE_AND_ADD:m;this.indexedOperations[u]=X}G(w,u),_?(G(this.allFilteredChanges,u),this.root&&(this.root.enqueueChangeTree(this,"filteredChanges"),this.root.enqueueChangeTree(this,"allFilteredChanges"))):(G(this.allChanges,u),this.root?.enqueueChangeTree(this,"changes"))}shiftChangeIndexes(u){let m=this.isFiltered?this.filteredChanges:this.changes,_={},w={};for(let z in this.indexedOperations)_[Number(z)+u]=this.indexedOperations[z],w[Number(z)+u]=m.indexes[z];this.indexedOperations=_,m.indexes=w,m.operations=m.operations.map(z=>z+u)}shiftAllChangeIndexes(u,m=0){this.filteredChanges!==void 0?(this._shiftAllChangeIndexes(u,m,this.allFilteredChanges),this._shiftAllChangeIndexes(u,m,this.allChanges)):this._shiftAllChangeIndexes(u,m,this.allChanges)}_shiftAllChangeIndexes(u,m=0,_){let w={},z=0;for(let X in _.indexes)w[z++]=_.indexes[X];_.indexes=w;for(let X=0;X<_.operations.length;X++){let ue=_.operations[X];ue>m&&(_.operations[X]=ue+u)}}indexedOperation(u,m,_=u){this.indexedOperations[u]=m,this.filteredChanges!==void 0?(G(this.allFilteredChanges,_),G(this.filteredChanges,u),this.root?.enqueueChangeTree(this,"filteredChanges")):(G(this.allChanges,_),G(this.changes,u),this.root?.enqueueChangeTree(this,"changes"))}getType(u){return this.ref[h]||this.metadata[u].type}getChange(u){return this.indexedOperations[u]}getValue(u,m=!1){return this.ref[o](u,m)}delete(u,m,_=u){if(u===void 0){try{throw new Error(`@colyseus/schema ${this.ref.constructor.name}: trying to delete non-existing index '${u}'`)}catch(X){console.warn(X)}return}let w=this.filteredChanges!==void 0?this.filteredChanges:this.changes;this.indexedOperations[u]=m??i.OPERATION.DELETE,G(w,u),we(this.allChanges,_);let z=this.getValue(u);return z&&z[c]&&this.root?.remove(z[c]),this.filteredChanges!==void 0?(we(this.allFilteredChanges,_),this.root?.enqueueChangeTree(this,"filteredChanges")):this.root?.enqueueChangeTree(this,"changes"),z}endEncode(u){this.indexedOperations={},this[u]=nt(),this.ref[d]?.(),this.isNew=!1}discard(u=!1){this.ref[d]?.(),this.indexedOperations={},this.changes=nt(this.changes.queueRootNode),this.filteredChanges!==void 0&&(this.filteredChanges=nt(this.filteredChanges.queueRootNode)),u&&(this.allChanges=nt(this.allChanges.queueRootNode),this.allFilteredChanges!==void 0&&(this.allFilteredChanges=nt(this.allFilteredChanges.queueRootNode)))}discardAll(){let u=Object.keys(this.indexedOperations);for(let m=0,_=u.length;m<_;m++){let w=this.getValue(Number(u[m]));w&&w[c]&&w[c].discardAll()}this.discard()}get changed(){return Object.entries(this.indexedOperations).length>0}checkIsFiltered(u,m,_){this.root.types.hasFilters&&(this._checkFilteredByParent(u,m),this.filteredChanges!==void 0&&(this.root?.enqueueChangeTree(this,"filteredChanges"),_&&this.root?.enqueueChangeTree(this,"allFilteredChanges"))),this.isFiltered||(this.root?.enqueueChangeTree(this,"changes"),_&&this.root?.enqueueChangeTree(this,"allChanges"))}_checkFilteredByParent(u,m){if(!u)return;let _=je.isValidInstance(this.ref)?this.ref.constructor:this.ref[h],w,z=!je.isValidInstance(u);z?(w=u[c],u=w.parent,m=w.parentIndex):w=u[c];let X=u.constructor,ue=`${this.root.types.getTypeId(_)}`;X&&(ue+=`-${this.root.types.schemas.get(X)}`),ue+=`-${m}`;let ne=je.hasViewTagAtIndex(X?.[Symbol.metadata],m);this.isFiltered=u[c].isFiltered||this.root.types.parentFiltered[ue]||ne,this.isFiltered&&(this.isVisibilitySharedWithParent=w.isFiltered&&typeof _!="string"&&!ne&&z,this.filteredChanges||(this.filteredChanges=nt(),this.allFilteredChanges=nt()),this.changes.operations.length>0&&(this.changes.operations.forEach(ae=>G(this.filteredChanges,ae)),this.allChanges.operations.forEach(ae=>G(this.allFilteredChanges,ae)),this.changes=nt(),this.allChanges=nt()))}get parent(){return this.parentChain?.ref}get parentIndex(){return this.parentChain?.index}addParent(u,m){if(this.hasParent((_,w)=>_[c]===u[c])){this.parentChain.index=m;return}this.parentChain={ref:u,index:m,next:this.parentChain}}removeParent(u=this.parent){let m=this.parentChain,_=null;for(;m;){if(m.ref[c]===u[c])return _?_.next=m.next:this.parentChain=m.next,!0;_=m,m=m.next}return this.parentChain===void 0}findParent(u){let m=this.parentChain;for(;m;){if(u(m.ref,m.index))return m;m=m.next}}hasParent(u){return this.findParent(u)!==void 0}getAllParents(){let u=[],m=this.parentChain;for(;m;)u.push({ref:m.ref,index:m.index}),m=m.next;return u}}function He(R,u,m,_,w,z){typeof m=="string"?oe[m]?.(u,_,z):m[Symbol.metadata]!==void 0?(oe.number(u,_[c].refId,z),(w&i.OPERATION.ADD)===i.OPERATION.ADD&&R.tryEncodeTypeId(u,m,_.constructor,z)):oe.number(u,_[c].refId,z)}let Ae=function(R,u,m,_,w,z,X,ue,ne){if(u[z.offset++]=(_|w)&255,w===i.OPERATION.DELETE)return;let ae=m.ref,he=ne[_];He(R,u,ne[_].type,ae[he.name],w,z)},xe=function(R,u,m,_,w,z){if(u[z.offset++]=w&255,oe.number(u,_,z),w===i.OPERATION.DELETE)return;let X=m.ref;if((w&i.OPERATION.ADD)===i.OPERATION.ADD&&typeof X.set=="function"){let ae=m.ref.$indexes.get(_);oe.string(u,ae,z)}let ue=X[h],ne=X[o](_);He(R,u,ue,ne,w,z)},Xe=function(R,u,m,_,w,z,X,ue){let ne=m.ref,ae=ue&&m.isFiltered&&typeof m.getType(_)!="string",he;if(ae){let Oe=ne.tmpItems[_];if(!Oe)return;he=Oe[c].refId,w===i.OPERATION.DELETE?w=i.OPERATION.DELETE_BY_REFID:w===i.OPERATION.ADD&&(w=i.OPERATION.ADD_BY_REFID)}else he=_;if(u[z.offset++]=w&255,oe.number(u,he,z),w===i.OPERATION.DELETE||w===i.OPERATION.DELETE_BY_REFID)return;let se=m.getType(_),Ge=m.getValue(_,X);He(R,u,se,Ge,w,z)},rt=-1;function jt(R,u,m,_,w,z,X,ue){let ne=R.root,ae=m[o](_),he;if((u&i.OPERATION.DELETE)===i.OPERATION.DELETE){let se=ne.refIds.get(ae);se!==void 0&&ne.removeRef(se),u!==i.OPERATION.DELETE_AND_ADD&&m[l](_),he=void 0}if(u!==i.OPERATION.DELETE)if(Ie.is(w)){let se=ge.number(z,X);if(he=ne.refs.get(se),(u&i.OPERATION.ADD)===i.OPERATION.ADD){let Ge=R.getInstanceType(z,X,w);he||(he=R.createInstanceOfType(Ge)),ne.addRef(se,he,he!==ae||u===i.OPERATION.DELETE_AND_ADD&&he===ae)}}else if(typeof w=="string")he=ge[w](z,X);else{let se=me(Object.keys(w)[0]),Ge=ge.number(z,X),Oe=ne.refs.has(Ge)?ae||ne.refs.get(Ge):new se.constructor;if(he=Oe.clone(!0),he[h]=Object.values(w)[0],ae){let Re=ne.refIds.get(ae);if(Re!==void 0&&Ge!==Re){let ye=ae.entries(),$e;for(;($e=ye.next())&&!$e.done;){let[tn,nn]=$e.value;typeof nn=="object"&&(Re=ne.refIds.get(nn),ne.removeRef(Re)),ue.push({ref:ae,refId:Re,op:i.OPERATION.DELETE,field:tn,value:void 0,previousValue:nn})}}}ne.addRef(Ge,he,Oe!==ae||u===i.OPERATION.DELETE_AND_ADD&&Oe===ae)}return{value:he,previousValue:ae}}let Rt=function(R,u,m,_,w){let z=u[m.offset++],X=_.constructor[Symbol.metadata],ue=z>>6<<6,ne=z%(ue||255),ae=X[ne];if(ae===void 0)return console.warn("@colyseus/schema: field not defined at",{index:ne,ref:_.constructor.name,metadata:X}),rt;let{value:he,previousValue:se}=jt(R,ue,_,ne,ae.type,u,m,w);he!=null&&(_[ae.name]=he),se!==he&&w.push({ref:_,refId:R.currentRefId,op:ue,field:ae.name,value:he,previousValue:se})},$n=function(R,u,m,_,w){let z=u[m.offset++];if(z===i.OPERATION.CLEAR){R.removeChildRefs(_,w),_.clear();return}let X=ge.number(u,m),ue=_[h],ne;(z&i.OPERATION.ADD)===i.OPERATION.ADD?typeof _.set=="function"?(ne=ge.string(u,m),_.setIndex(X,ne)):ne=X:ne=_.getIndex(X);let{value:ae,previousValue:he}=jt(R,z,_,X,ue,u,m,w);if(ae!=null){if(typeof _.set=="function")_.$items.set(ne,ae);else if(typeof _.$setAt=="function")_.$setAt(X,ae,z);else if(typeof _.add=="function"){let se=_.add(ae);typeof se=="number"&&_.setIndex(se,se)}}he!==ae&&w.push({ref:_,refId:R.currentRefId,op:z,field:"",dynamicIndex:ne,value:ae,previousValue:he})},ui=function(R,u,m,_,w){let z=u[m.offset++],X;if(z===i.OPERATION.CLEAR){R.removeChildRefs(_,w),_.clear();return}else if(z===i.OPERATION.REVERSE){_.reverse();return}else if(z===i.OPERATION.DELETE_BY_REFID){let se=ge.number(u,m),Ge=R.root.refs.get(se);X=_.findIndex(Oe=>Oe===Ge),_[l](X),w.push({ref:_,refId:R.currentRefId,op:i.OPERATION.DELETE,field:"",dynamicIndex:X,value:void 0,previousValue:Ge});return}else if(z===i.OPERATION.ADD_BY_REFID){let se=ge.number(u,m),Ge=R.root.refs.get(se);Ge&&(X=_.findIndex(Oe=>Oe===Ge)),(X===-1||X===void 0)&&(X=_.length)}else X=ge.number(u,m);let ue=_[h],ne=X,{value:ae,previousValue:he}=jt(R,z,_,X,ue,u,m,w);ae!=null&&ae!==he&&_.$setAt(X,ae,z),he!==ae&&w.push({ref:_,refId:R.currentRefId,op:z,field:"",dynamicIndex:ne,value:ae,previousValue:he})};class Hs extends Error{}function Ou(R,u,m,_){let w,z=!1;switch(u){case"number":case"int8":case"uint8":case"int16":case"uint16":case"int32":case"uint32":case"int64":case"uint64":case"float32":case"float64":w="number",isNaN(R)&&console.log(`trying to encode "NaN" in ${m.constructor.name}#${_}`);break;case"bigint64":case"biguint64":w="bigint";break;case"string":w="string",z=!0;break;case"boolean":return;default:return}if(typeof R!==w&&(!z||z&&R!==null)){let X=`'${JSON.stringify(R)}'${R&&R.constructor&&` (${R.constructor.name})`||""}`;throw new Hs(`a '${w}' was expected, but ${X} was provided in ${m.constructor.name}#${_}`)}}function ns(R,u,m,_){if(!(R instanceof u))throw new Hs(`a '${u.name}' was expected, but '${R&&R.constructor.name}' was provided in ${m.constructor.name}#${_}`)}var ka,zi;let Ba=(R,u)=>{let m=R.toString(),_=u.toString();return m<_?-1:m>_?1:0},hn=class hn{static[(ka=r,zi=s,a)](u,m,_){return!_||typeof u[h]=="string"||_.isChangeTreeVisible(u.tmpItems[m]?.[c])}static is(u){return Array.isArray(u)||u.array!==void 0}static from(u){return new hn(...Array.from(u))}constructor(...u){this.items=[],this.tmpItems=[],this.deletedIndexes={},this.isMovingItems=!1,Object.defineProperty(this,h,{value:void 0,enumerable:!1,writable:!0,configurable:!0});let m=new Proxy(this,{get:(_,w)=>typeof w!="symbol"&&!isNaN(w)?this.items[w]:Reflect.get(_,w),set:(_,w,z)=>{if(typeof w!="symbol"&&!isNaN(w)){if(z==null)_.$deleteAt(w);else{if(z[c]){ns(z,_[h],_,w);let X=_.items[w];_.isMovingItems?(X!==void 0?z[c].isNew?_[c].indexedOperation(Number(w),i.OPERATION.MOVE_AND_ADD):(_[c].getChange(Number(w))&i.OPERATION.DELETE)===i.OPERATION.DELETE?_[c].indexedOperation(Number(w),i.OPERATION.DELETE_AND_MOVE):_[c].indexedOperation(Number(w),i.OPERATION.MOVE):z[c].isNew&&_[c].indexedOperation(Number(w),i.OPERATION.ADD),z[c].setParent(this,_[c].root,w)):_.$changeAt(Number(w),z),X!==void 0&&X[c].root?.remove(X[c])}else _.$changeAt(Number(w),z);_.items[w]=z,_.tmpItems[w]=z}return!0}else return Reflect.set(_,w,z)},deleteProperty:(_,w)=>(typeof w=="number"?_.$deleteAt(w):delete _[w],!0),has:(_,w)=>typeof w!="symbol"&&!isNaN(Number(w))?Reflect.has(this.items,w):Reflect.has(_,w)});return Object.defineProperty(this,c,{value:new de(m),enumerable:!1,writable:!0}),u.length>0&&this.push(...u),m}set length(u){u===0?this.clear():u<this.items.length?this.splice(u,this.length-u):console.warn("ArraySchema: can't set .length to a higher value than its length.")}get length(){return this.items.length}push(...u){let m=this.tmpItems.length,_=this[c];for(let w=0,z=u.length;w<z;w++,m++){let X=u[w];if(X==null)return;typeof X=="object"&&this[h]&&ns(X,this[h],this,w),_.indexedOperation(m,i.OPERATION.ADD,this.items.length),this.items.push(X),this.tmpItems.push(X),X[c]?.setParent(this,_.root,m)}return m}pop(){let u=-1;for(let m=this.tmpItems.length-1;m>=0;m--)if(this.deletedIndexes[m]!==!0){u=m;break}if(!(u<0))return this[c].delete(u,void 0,this.items.length-1),this.deletedIndexes[u]=!0,this.items.pop()}at(u){return u<0&&(u+=this.length),this.items[u]}$changeAt(u,m){if(m==null){console.error("ArraySchema items cannot be null nor undefined; Use `deleteAt(index)` instead.");return}if(this.items[u]===m)return;let _=this.items[u]!==void 0?typeof m=="object"?i.OPERATION.DELETE_AND_ADD:i.OPERATION.REPLACE:i.OPERATION.ADD,w=this[c];w.change(u,_),m[c]?.setParent(this,w.root,u)}$deleteAt(u,m){this[c].delete(u,m)}$setAt(u,m,_){u===0&&_===i.OPERATION.ADD&&this.items[u]!==void 0?this.items.unshift(m):_===i.OPERATION.DELETE_AND_MOVE?(this.items.splice(u,1),this.items[u]=m):this.items[u]=m}clear(){if(this.items.length===0)return;let u=this[c];u.forEachChild((m,_)=>{u.root?.remove(m)}),u.discard(!0),u.operation(i.OPERATION.CLEAR),this.items.length=0,this.tmpItems.length=0}concat(...u){return new hn(...this.items.concat(...u))}join(u){return this.items.join(u)}reverse(){return this[c].operation(i.OPERATION.REVERSE),this.items.reverse(),this.tmpItems.reverse(),this}shift(){if(this.items.length===0)return;let u=this[c],m=this.tmpItems.findIndex(w=>w===this.items[0]),_=this.items.findIndex(w=>w===this.items[0]);return u.delete(m,i.OPERATION.DELETE,_),u.shiftAllChangeIndexes(-1,_),this.deletedIndexes[m]=!0,this.items.shift()}slice(u,m){let _=new hn;return _.push(...this.items.slice(u,m)),_}sort(u=Ba){this.isMovingItems=!0;let m=this[c];return this.items.sort(u).forEach((w,z)=>m.change(z,i.OPERATION.REPLACE)),this.tmpItems.sort(u),this.isMovingItems=!1,this}splice(u,m,..._){let w=this[c],z=this.items.length,X=this.tmpItems.length,ue=_.length,ne=[];for(let ae=0;ae<X;ae++)this.deletedIndexes[ae]!==!0&&ne.push(ae);if(z>u){m===void 0&&(m=z-u);for(let ae=u;ae<u+m;ae++){let he=ne[ae];w.delete(he,i.OPERATION.DELETE),this.deletedIndexes[he]=!0}}else m=0;if(ue>0){if(ue>m)throw console.error("Inserting more elements than deleting during ArraySchema#splice()"),new Error("ArraySchema#splice(): insertCount must be equal or lower than deleteCount.");for(let ae=0;ae<ue;ae++){let he=(ne[u]??z)+ae;w.indexedOperation(he,this.deletedIndexes[he]?i.OPERATION.DELETE_AND_ADD:i.OPERATION.ADD),_[ae][c]?.setParent(this,w.root,he)}}return m>ue&&w.shiftAllChangeIndexes(-(m-ue),ne[u+ue]),w.filteredChanges!==void 0?w.root?.enqueueChangeTree(w,"filteredChanges"):w.root?.enqueueChangeTree(w,"changes"),this.items.splice(u,m,..._)}unshift(...u){let m=this[c];return m.shiftChangeIndexes(u.length),m.isFiltered?G(m.filteredChanges,this.items.length):G(m.allChanges,this.items.length),u.forEach((_,w)=>{m.change(w,i.OPERATION.ADD)}),this.tmpItems.unshift(...u),this.items.unshift(...u)}indexOf(u,m){return this.items.indexOf(u,m)}lastIndexOf(u,m=this.length-1){return this.items.lastIndexOf(u,m)}every(u,m){return this.items.every(u,m)}some(u,m){return this.items.some(u,m)}forEach(u,m){return this.items.forEach(u,m)}map(u,m){return this.items.map(u,m)}filter(u,m){return this.items.filter(u,m)}reduce(u,m){return this.items.reduce(u,m)}reduceRight(u,m){return this.items.reduceRight(u,m)}find(u,m){return this.items.find(u,m)}findIndex(u,m){return this.items.findIndex(u,m)}fill(u,m,_){throw new Error("ArraySchema#fill() not implemented")}copyWithin(u,m,_){throw new Error("ArraySchema#copyWithin() not implemented")}toString(){return this.items.toString()}toLocaleString(){return this.items.toLocaleString()}[Symbol.iterator](){return this.items[Symbol.iterator]()}static get[Symbol.species](){return hn}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}includes(u,m){return this.items.includes(u,m)}flatMap(u,m){throw new Error("ArraySchema#flatMap() is not supported.")}flat(u){throw new Error("ArraySchema#flat() is not supported.")}findLast(){return this.items.findLast.apply(this.items,arguments)}findLastIndex(...u){return this.items.findLastIndex.apply(this.items,arguments)}with(u,m){let _=this.items.slice();return u<0&&(u+=this.length),_[u]=m,new hn(..._)}toReversed(){return this.items.slice().reverse()}toSorted(u){return this.items.slice().sort(u)}toSpliced(u,m,..._){return this.items.toSpliced.apply(copy,arguments)}shuffle(){return this.move(u=>{let m=this.items.length;for(;m!=0;){let _=Math.floor(Math.random()*m);m--,[this[m],this[_]]=[this[_],this[m]]}})}move(u){return this.isMovingItems=!0,u(this),this.isMovingItems=!1,this}[o](u,m=!1){return m?this.items[u]:this.deletedIndexes[u]?this.items[u]:this.tmpItems[u]||this.items[u]}[l](u){this.items[u]=void 0,this.tmpItems[u]=void 0}[d](){this.tmpItems=this.items.slice(),this.deletedIndexes={}}[f](){this.items=this.items.filter(u=>u!==void 0),this.tmpItems=this.items.slice()}toArray(){return this.items.slice(0)}toJSON(){return this.toArray().map(u=>typeof u.toJSON=="function"?u.toJSON():u)}clone(u){let m;return u?(m=new hn,m.push(...this.items)):m=new hn(...this.map(_=>_[c]?_.clone():_)),m}};hn[ka]=Xe,hn[zi]=ui;let jn=hn;ce("array",{constructor:jn});var za,is;let kn=class kn{static[(za=r,is=s,a)](u,m,_){return!_||typeof u[h]=="string"||_.isChangeTreeVisible((u[o](m)??u.deletedItems[m])[c])}static is(u){return u.map!==void 0}constructor(u){this.$items=new Map,this.$indexes=new Map,this.deletedItems={};let m=new de(this);if(m.indexes={},Object.defineProperty(this,c,{value:m,enumerable:!1,writable:!0}),u)if(u instanceof Map||u instanceof kn)u.forEach((_,w)=>this.set(w,_));else for(let _ in u)this.set(_,u[_]);Object.defineProperty(this,h,{value:void 0,enumerable:!1,writable:!0,configurable:!0})}[Symbol.iterator](){return this.$items[Symbol.iterator]()}get[Symbol.toStringTag](){return this.$items[Symbol.toStringTag]}static get[Symbol.species](){return kn}set(u,m){if(m==null)throw new Error(`MapSchema#set('${u}', ${m}): trying to set ${m} value on '${u}'.`);typeof m=="object"&&this[h]&&ns(m,this[h],this,u),u=u.toString();let _=this[c],w=m[c]!==void 0,z,X;if(typeof _.indexes[u]<"u"){z=_.indexes[u],X=i.OPERATION.REPLACE;let ue=this.$items.get(u);if(ue===m)return;w&&(X=i.OPERATION.DELETE_AND_ADD,ue!==void 0&&ue[c].root?.remove(ue[c])),this.deletedItems[z]&&delete this.deletedItems[z]}else z=_.indexes[x]??0,X=i.OPERATION.ADD,this.$indexes.set(z,u),_.indexes[u]=z,_.indexes[x]=z+1;return this.$items.set(u,m),_.change(z,X),w&&m[c].setParent(this,_.root,z),this}get(u){return this.$items.get(u)}delete(u){if(!this.$items.has(u))return!1;let m=this[c].indexes[u];return this.deletedItems[m]=this[c].delete(m),this.$items.delete(u)}clear(){let u=this[c];u.discard(!0),u.indexes={},u.forEachChild((m,_)=>{u.root?.remove(m)}),this.$indexes.clear(),this.$items.clear(),u.operation(i.OPERATION.CLEAR)}has(u){return this.$items.has(u)}forEach(u){this.$items.forEach(u)}entries(){return this.$items.entries()}keys(){return this.$items.keys()}values(){return this.$items.values()}get size(){return this.$items.size}setIndex(u,m){this.$indexes.set(u,m)}getIndex(u){return this.$indexes.get(u)}[o](u){return this.$items.get(this.$indexes.get(u))}[l](u){let m=this.$indexes.get(u);this.$items.delete(m),this.$indexes.delete(u)}[d](){let u=this[c];for(let m in this.deletedItems){let _=parseInt(m),w=this.$indexes.get(_);delete u.indexes[w],this.$indexes.delete(_)}this.deletedItems={}}toJSON(){let u={};return this.forEach((m,_)=>{u[_]=typeof m.toJSON=="function"?m.toJSON():m}),u}clone(u){let m;return u?m=Object.assign(new kn,this):(m=new kn,this.forEach((_,w)=>{_[c]?m.set(w,_.clone()):m.set(w,_)})),m}};kn[za]=xe,kn[is]=$n;let di=kn;ce("map",{constructor:di});var rs,Ha;let At=class At{static[(rs=r,Ha=s,a)](u,m,_){return!_||typeof u[h]=="string"||_.isChangeTreeVisible((u[o](m)??u.deletedItems[m])[c])}static is(u){return u.collection!==void 0}constructor(u){this.$items=new Map,this.$indexes=new Map,this.deletedItems={},this.$refId=0,this[c]=new de(this),this[c].indexes={},u&&u.forEach(m=>this.add(m)),Object.defineProperty(this,h,{value:void 0,enumerable:!1,writable:!0,configurable:!0})}add(u){let m=this.$refId++;return u[c]!==void 0&&u[c].setParent(this,this[c].root,m),this[c].indexes[m]=m,this.$indexes.set(m,m),this.$items.set(m,u),this[c].change(m),m}at(u){let m=Array.from(this.$items.keys())[u];return this.$items.get(m)}entries(){return this.$items.entries()}delete(u){let m=this.$items.entries(),_,w;for(;(w=m.next())&&!w.done;)if(u===w.value[1]){_=w.value[0];break}return _===void 0?!1:(this.deletedItems[_]=this[c].delete(_),this.$indexes.delete(_),this.$items.delete(_))}clear(){let u=this[c];u.discard(!0),u.indexes={},u.forEachChild((m,_)=>{u.root?.remove(m)}),this.$indexes.clear(),this.$items.clear(),u.operation(i.OPERATION.CLEAR)}has(u){return Array.from(this.$items.values()).some(m=>m===u)}forEach(u){this.$items.forEach((m,_,w)=>u(m,_,this))}values(){return this.$items.values()}get size(){return this.$items.size}[Symbol.iterator](){return this.$items.values()}setIndex(u,m){this.$indexes.set(u,m)}getIndex(u){return this.$indexes.get(u)}[o](u){return this.$items.get(this.$indexes.get(u))}[l](u){let m=this.$indexes.get(u);this.$items.delete(m),this.$indexes.delete(u)}[d](){this.deletedItems={}}toArray(){return Array.from(this.$items.values())}toJSON(){let u=[];return this.forEach((m,_)=>{u.push(typeof m.toJSON=="function"?m.toJSON():m)}),u}clone(u){let m;return u?m=Object.assign(new At,this):(m=new At,this.forEach(_=>{_[c]?m.add(_.clone()):m.add(_)})),m}};At[rs]=xe,At[Ha]=$n;let sr=At;ce("collection",{constructor:sr});var _c,yc;let Ft=class Ft{static[(_c=r,yc=s,a)](u,m,_){return!_||typeof u[h]=="string"||_.visible.has((u[o](m)??u.deletedItems[m])[c])}static is(u){return u.set!==void 0}constructor(u){this.$items=new Map,this.$indexes=new Map,this.deletedItems={},this.$refId=0,this[c]=new de(this),this[c].indexes={},u&&u.forEach(m=>this.add(m)),Object.defineProperty(this,h,{value:void 0,enumerable:!1,writable:!0,configurable:!0})}add(u){if(this.has(u))return!1;let m=this.$refId++;u[c]!==void 0&&u[c].setParent(this,this[c].root,m);let _=this[c].indexes[m]?.op??i.OPERATION.ADD;return this[c].indexes[m]=m,this.$indexes.set(m,m),this.$items.set(m,u),this[c].change(m,_),m}entries(){return this.$items.entries()}delete(u){let m=this.$items.entries(),_,w;for(;(w=m.next())&&!w.done;)if(u===w.value[1]){_=w.value[0];break}return _===void 0?!1:(this.deletedItems[_]=this[c].delete(_),this.$indexes.delete(_),this.$items.delete(_))}clear(){let u=this[c];u.discard(!0),u.indexes={},this.$indexes.clear(),this.$items.clear(),u.operation(i.OPERATION.CLEAR)}has(u){let m=this.$items.values(),_=!1,w;for(;(w=m.next())&&!w.done;)if(u===w.value){_=!0;break}return _}forEach(u){this.$items.forEach((m,_,w)=>u(m,_,this))}values(){return this.$items.values()}get size(){return this.$items.size}[Symbol.iterator](){return this.$items.values()}setIndex(u,m){this.$indexes.set(u,m)}getIndex(u){return this.$indexes.get(u)}[o](u){return this.$items.get(this.$indexes.get(u))}[l](u){let m=this.$indexes.get(u);this.$items.delete(m),this.$indexes.delete(u)}[d](){this.deletedItems={}}toArray(){return Array.from(this.$items.values())}toJSON(){let u=[];return this.forEach((m,_)=>{u.push(typeof m.toJSON=="function"?m.toJSON():m)}),u}clone(u){let m;return u?m=Object.assign(new Ft,this):(m=new Ft,this.forEach(_=>{_[c]?m.add(_.clone()):m.add(_)})),m}};Ft[_c]=xe,Ft[yc]=$n;let wr=Ft;ce("set",{constructor:wr});let Mi=-1;function Fu(R){return Le.register(R),R}function vc(R=Mi){return function(u,m){let _=u.constructor,z=Object.getPrototypeOf(_)[Symbol.metadata],X=_[Symbol.metadata]??=Object.assign({},_[Symbol.metadata],z??Object.create(null));je.setTag(X,m,R)}}function ni(R,u){return function(m,_){let w=m.constructor;if(!R)throw new Error(`${w.name}: @type() reference provided for "${_}" is undefined. Make sure you don't have any circular dependencies.`);R=ve(R),Le.register(w);let X=Object.getPrototypeOf(w)[Symbol.metadata],ue=je.initialize(w),ne=ue[_];if(ue[ne]!==void 0){if(ue[ne].deprecated)return;if(ue[ne].type!==void 0)try{throw new Error(`@colyseus/schema: Duplicate '${_}' definition on '${w.name}'.
+Check @type() annotation`)}catch(ae){let he=ae.stack.split(`
+`)[4].trim();throw new Error(`${ae.message} ${he}`)}}else ne=ue[x]??(X&&X[x])??-1,ne++;if(u&&u.manual)je.addField(ue,ne,_,R,{enumerable:!0,configurable:!0,writable:!0});else{let ae=typeof Object.keys(R)[0]=="string"&&me(Object.keys(R)[0]),he=ae?Object.values(R)[0]:R;je.addField(ue,ne,_,R,C(`_${_}`,ne,he,ae))}}}function C(R,u,m,_){return{get:function(){return this[R]},set:function(w){let z=this[R]??void 0;if(w!==z){if(w!=null){_?(_.constructor===jn&&!(w instanceof jn)&&(w=new jn(...w)),_.constructor===di&&!(w instanceof di)&&(w=new di(w)),w[h]=m):typeof m!="string"?ns(w,m,this,R.substring(1)):Ou(w,m,this,R.substring(1));let X=this[c];z!==void 0&&z[c]?(X.root?.remove(z[c]),this.constructor[n](X,u,i.OPERATION.DELETE_AND_ADD)):this.constructor[n](X,u,i.OPERATION.ADD),w[c]?.setParent(this,X.root,u)}else z!==void 0&&this[c].delete(u);this[R]=w}},enumerable:!0,configurable:!0}}function j(R=!0){return function(u,m){let _=u.constructor,z=Object.getPrototypeOf(_)[Symbol.metadata],X=_[Symbol.metadata]??=Object.assign({},_[Symbol.metadata],z??Object.create(null)),ue=X[m];X[ue].deprecated=!0,R&&(X[p]??={},X[p][m]={get:function(){throw new Error(`${m} is deprecated.`)},set:function(ne){},enumerable:!1,configurable:!0}),Object.defineProperty(X,ue,{value:X[ue],enumerable:!1,configurable:!0})}}function ie(R,u,m){for(let _ in u)ni(u[_],m)(R.prototype,_);return R}function ee(R,u,m=Ie){let _={},w={},z={},X={};for(let he in R){let se=R[he];typeof se=="object"?(se.view!==void 0&&(X[he]=typeof se.view=="boolean"?Mi:se.view),_[he]=ve(se),Object.prototype.hasOwnProperty.call(se,"default")?z[he]=se.default:Array.isArray(se)||se.array!==void 0?z[he]=new jn:se.map!==void 0?z[he]=new di:se.collection!==void 0?z[he]=new sr:se.set!==void 0?z[he]=new wr:se.type!==void 0&&Ie.is(se.type)&&(!se.type.prototype.initialize||se.type.prototype.initialize.length===0)&&(z[he]=new se.type)):typeof se=="function"?Ie.is(se)?((!se.prototype.initialize||se.prototype.initialize.length===0)&&(z[he]=new se),_[he]=ve(se)):w[he]=se:_[he]=ve(se)}let ue=()=>{let he={};for(let se in z){let Ge=z[se];Ge&&typeof Ge.clone=="function"?he[se]=Ge.clone():he[se]=Ge}return he},ne=he=>{let se=Object.keys(_),Ge={};for(let Oe in he)se.includes(Oe)||(Ge[Oe]=he[Oe]);return Ge},ae=je.setFields(class extends m{constructor(...he){w.initialize&&typeof w.initialize=="function"?(super(Object.assign({},ue(),ne(he[0]||{}))),new.target===ae&&w.initialize.apply(this,he)):super(Object.assign({},ue(),he[0]||{}))}},_);ae._getDefaultValues=ue,Object.assign(ae.prototype,w);for(let he in X)vc(X[he])(ae.prototype,he);return u&&Object.defineProperty(ae,"name",{value:u}),ae.extends=(he,se)=>ee(he,se,ae),ae}function Q(R){return new Array(R).fill(0).map((u,m)=>m===R-1?"\u2514\u2500 ":" ").join("")}function Fe(R){let u=R[c].root,m={ops:{},refs:[]},_=u.changes.next;for(;_;){let w=_.changeTree;if(w===void 0){_=_.next;continue}let z=w.indexedOperations;m.refs.push(`refId#${w.refId}`);for(let X in z){let ue=z[X],ne=i.OPERATION[ue];m.ops[ne]||(m.ops[ne]=0),m.ops[i.OPERATION[ue]]++}_=_.next}return m}var We,De;let Bn=class Bn{static initialize(u){Object.defineProperty(u,c,{value:new de(u),enumerable:!1,writable:!0}),Object.defineProperties(u,u.constructor[Symbol.metadata]?.[p]||{})}static is(u){return typeof u[Symbol.metadata]=="object"}static[(We=r,De=s,n)](u,m,_=i.OPERATION.ADD){u.change(m,_)}static[a](u,m,_){let z=u.constructor[Symbol.metadata][m]?.tag;if(_===void 0)return z===void 0;if(z===void 0)return!0;if(z===Mi)return _.isChangeTreeVisible(u[c]);{let X=_.tags?.get(u[c]);return X&&X.has(z)}}constructor(u){Bn.initialize(this),u&&Object.assign(this,u)}assign(u){return Object.assign(this,u),this}setDirty(u,m){let _=this.constructor[Symbol.metadata];this[c].change(_[_[u]].index,m)}clone(){let u=Object.create(this.constructor.prototype);Bn.initialize(u);let m=this.constructor[Symbol.metadata];for(let _ in m){let w=m[_].name;typeof this[w]=="object"&&typeof this[w]?.clone=="function"?u[w]=this[w].clone():u[w]=this[w]}return u}toJSON(){let u={},m=this.constructor[Symbol.metadata];for(let _ in m){let w=m[_],z=w.name;!w.deprecated&&this[z]!==null&&typeof this[z]<"u"&&(u[z]=typeof this[z].toJSON=="function"?this[z].toJSON():this[z])}return u}discardAllChanges(){this[c].discardAll()}[o](u){let m=this.constructor[Symbol.metadata];return this[m[u].name]}[l](u){let m=this.constructor[Symbol.metadata];this[m[u].name]=void 0}static debugRefIds(u,m=!1,_=0,w,z=""){let X=m?` - ${JSON.stringify(u.toJSON())}`:"",ue=u[c],ne=w?w.root.refIds.get(u):ue.refId,ae=w?w.root:ue.root,he=ae?.refCount?.[ne]>1?` [\xD7${ae.refCount[ne]}]`:"",se=`${Q(_)}${z}${u.constructor.name} (refId: ${ne})${he}${X}
+`;return ue.forEachChild((Ge,Oe)=>{let Re=Oe;typeof Oe=="number"&&u.$indexes&&(Re=u.$indexes.get(Oe)??Oe);let ye=u.forEach!==void 0&&Re!==void 0?`["${Re}"]: `:"";se+=this.debugRefIds(Ge.ref,m,_+1,w,ye)}),se}static debugRefIdEncodingOrder(u,m="allChanges"){let _=[],w=u[c].root[m].next;for(;w;)w.changeTree&&_.push(w.changeTree.refId),w=w.next;return _}static debugRefIdsFromDecoder(u){return this.debugRefIds(u.state,!1,0,u)}static debugChanges(u,m=!1){let _=u[c],w=m?_.allChanges:_.changes,z=m?"allChanges":"changes",X=`${u.constructor.name} (${_.refId}) -> .${z}:
+`;function ue(ne){ne.operations.filter(ae=>ae).forEach(ae=>{let he=_.indexedOperations[ae];X+=`- [${ae}]: ${i.OPERATION[he]} (${JSON.stringify(_.getValue(Number(ae),m))})
+`})}return ue(w),!m&&_.filteredChanges&&_.filteredChanges.operations.filter(ne=>ne).length>0&&(X+=`${u.constructor.name} (${_.refId}) -> .filteredChanges:
+`,ue(_.filteredChanges)),m&&_.allFilteredChanges&&_.allFilteredChanges.operations.filter(ne=>ne).length>0&&(X+=`${u.constructor.name} (${_.refId}) -> .allFilteredChanges:
+`,ue(_.allFilteredChanges)),X}static debugChangesDeep(u,m="changes"){let _="",w=u[c],z=w.root,X=new Map,ue=[],ne=0;for(let[he,se]of Object.entries(z[m])){let Ge=z.changeTrees[he];if(!Ge)continue;let Oe=!1,Re=[],ye=Ge.parent?.[c];if(Ge===w)Oe=!0;else for(;ye!==void 0;){if(Re.push(ye),ye.ref===u){Oe=!0;break}ye=ye.parent?.[c]}Oe&&(ue.push(Ge.refId),ne+=Object.keys(se).length,X.set(Ge,Re.reverse()))}_+=`---
+`,_+=`root refId: ${w.refId}
+`,_+=`Total instances: ${ue.length} (refIds: ${ue.join(", ")})
+`,_+=`Total changes: ${ne}
+`,_+=`---
+`;let ae=new WeakSet;for(let[he,se]of X.entries()){se.forEach(($e,tn)=>{ae.has($e)||(_+=`${Q(tn)}${$e.ref.constructor.name} (refId: ${$e.refId})
+`,ae.add($e))});let Ge=he.indexedOperations,Oe=se.length,Re=Q(Oe),ye=Oe>0?`(${he.parentIndex}) `:"";_+=`${Re}${ye}${he.ref.constructor.name} (refId: ${he.refId}) - changes: ${Object.keys(Ge).length}
+`;for(let $e in Ge){let tn=Ge[$e];_+=`${Q(Oe+1)}${i.OPERATION[tn]}: ${$e}
+`}}return`${_}`}};Bn[We]=Ae,Bn[De]=Rt;let Ie=Bn;function qe(R,u,m,_){var w=arguments.length,z=w<3?u:_===null?_=Object.getOwnPropertyDescriptor(u,m):_,X;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")z=Reflect.decorate(R,u,m,_);else for(var ue=R.length-1;ue>=0;ue--)(X=R[ue])&&(z=(w<3?X(z):w>3?X(u,m,z):X(u,m))||z);return w>3&&z&&Object.defineProperty(u,m,z),z}typeof SuppressedError=="function"&&SuppressedError;class st{constructor(u){this.types=u,this.nextUniqueId=0,this.refCount={},this.changeTrees={},this.allChanges=pt(),this.allFilteredChanges=pt(),this.changes=pt(),this.filteredChanges=pt()}getNextUniqueId(){return this.nextUniqueId++}add(u){u.refId===void 0&&(u.refId=this.getNextUniqueId());let m=this.changeTrees[u.refId]===void 0;m&&(this.changeTrees[u.refId]=u);let _=this.refCount[u.refId];if(_===0){let w=u.allChanges.operations,z=w.length;for(;z--;)u.indexedOperations[w[z]]=i.OPERATION.ADD,G(u.changes,z)}return this.refCount[u.refId]=(_||0)+1,m}remove(u){let m=this.refCount[u.refId]-1;return m<=0?(u.root=void 0,delete this.changeTrees[u.refId],this.removeChangeFromChangeSet("allChanges",u),this.removeChangeFromChangeSet("changes",u),u.filteredChanges&&(this.removeChangeFromChangeSet("allFilteredChanges",u),this.removeChangeFromChangeSet("filteredChanges",u)),this.refCount[u.refId]=0,u.forEachChild((_,w)=>{_.removeParent(u.ref)&&(_.parentChain===void 0||_.parentChain&&this.refCount[_.refId]>0?this.remove(_):_.parentChain&&this.moveNextToParent(_))})):(this.refCount[u.refId]=m,this.recursivelyMoveNextToParent(u)),m}recursivelyMoveNextToParent(u){this.moveNextToParent(u),u.forEachChild((m,_)=>this.recursivelyMoveNextToParent(m))}moveNextToParent(u){u.filteredChanges?(this.moveNextToParentInChangeTreeList("filteredChanges",u),this.moveNextToParentInChangeTreeList("allFilteredChanges",u)):(this.moveNextToParentInChangeTreeList("changes",u),this.moveNextToParentInChangeTreeList("allChanges",u))}moveNextToParentInChangeTreeList(u,m){let _=this[u],w=m[u].queueRootNode;if(!w)return;let z=m.parent;if(!z||!z[c])return;let X=z[c][u]?.queueRootNode;if(!X||X===w)return;let ue=X.position;w.position>ue||(w.prev?w.prev.next=w.next:_.next=w.next,w.next?w.next.prev=w.prev:_.tail=w.prev,w.prev=X,w.next=X.next,X.next?X.next.prev=w:_.tail=w,X.next=w,this.updatePositionsAfterMove(_,w,ue+1))}enqueueChangeTree(u,m,_=u[m].queueRootNode){_||(u[m].queueRootNode=this.addToChangeTreeList(this[m],u))}addToChangeTreeList(u,m){let _={changeTree:m,next:void 0,prev:void 0,position:u.tail?u.tail.position+1:0};return u.next?(_.prev=u.tail,u.tail.next=_,u.tail=_):(u.next=_,u.tail=_),_}updatePositionsAfterRemoval(u,m){let _=u.next,w=0;for(;_;)w>=m&&(_.position=w),_=_.next,w++}updatePositionsAfterMove(u,m,_){let w=u.next,z=0;for(;w;)w.position=z,w=w.next,z++}removeChangeFromChangeSet(u,m){let _=this[u],w=m[u].queueRootNode;if(w&&w.changeTree===m){let z=w.position;return w.prev?w.prev.next=w.next:_.next=w.next,w.next?w.next.prev=w.prev:_.tail=w.prev,this.updatePositionsAfterRemoval(_,z),m[u].queueRootNode=void 0,!0}return!1}}let It=class It{constructor(u){this.sharedBuffer=Buffer.allocUnsafe(It.BUFFER_SIZE),this.context=Le.cache(u.constructor),this.root=new st(this.context),this.setState(u)}setState(u){this.state=u,this.state[c].setRoot(this.root)}encode(u={offset:0},m,_=this.sharedBuffer,w="changes",z=w==="allChanges",X=u.offset){let ue=m!==void 0,ne=this.state[c],ae=this.root[w];for(;ae=ae.next;){let he=ae.changeTree;if(ue){if(!m.isChangeTreeVisible(he)){m.invisible.add(he);continue}m.invisible.delete(he)}let se=he[w],Ge=he.ref,Oe=se.operations.length;if(Oe===0)continue;let Re=Ge.constructor,ye=Re[r],$e=Re[a],tn=Re[Symbol.metadata];(ue||u.offset>X||he!==ne)&&(_[u.offset++]=255,oe.number(_,he.refId,u));for(let nn=0;nn<Oe;nn++){let ii=se.operations[nn];if(ii<0){_[u.offset++]=Math.abs(ii)&255;continue}let fi=z?i.OPERATION.ADD:he.indexedOperations[ii];ii===void 0||fi===void 0||$e&&!$e(Ge,ii,m)||ye(this,_,he,ii,fi,u,z,ue,tn)}}if(u.offset>_.byteLength){let he=Math.ceil(u.offset/(Buffer.poolSize??8192))*(Buffer.poolSize??8192);return console.warn(`@colyseus/schema buffer overflow. Encoded state is higher than default BUFFER_SIZE. Use the following to increase default BUFFER_SIZE:
+
+ import { Encoder } from "@colyseus/schema";
+ Encoder.BUFFER_SIZE = ${Math.round(he/1024)} * 1024; // ${Math.round(he/1024)} KB
+`),_=Buffer.alloc(he,_),_===this.sharedBuffer&&(this.sharedBuffer=_),this.encode({offset:X},m,_,w,z)}else return _.subarray(0,u.offset)}encodeAll(u={offset:0},m=this.sharedBuffer){return this.encode(u,void 0,m,"allChanges",!0)}encodeAllView(u,m,_,w=this.sharedBuffer){let z=_.offset;return this.encode(_,u,w,"allFilteredChanges",!0,z),Buffer.concat([w.subarray(0,m),w.subarray(z,_.offset)])}encodeView(u,m,_,w=this.sharedBuffer){let z=_.offset;for(let[X,ue]of u.changes){let ne=this.root.changeTrees[X];if(ne===void 0){u.changes.delete(X);continue}let ae=Object.keys(ue);if(ae.length===0)continue;let se=ne.ref.constructor,Ge=se[r],Oe=se[Symbol.metadata];w[_.offset++]=255,oe.number(w,ne.refId,_);for(let Re=0,ye=ae.length;Re<ye;Re++){let $e=Number(ae[Re]),nn=ne.ref[o]($e)!==void 0&&ue[$e]||i.OPERATION.DELETE;Ge(this,w,ne,$e,nn,_,!1,!0,Oe)}}return u.changes.clear(),this.encode(_,u,w,"filteredChanges",!1,z),Buffer.concat([w.subarray(0,m),w.subarray(z,_.offset)])}discardChanges(){let u=this.root.changes.next;for(;u;)u.changeTree.endEncode("changes"),u=u.next;for(this.root.changes=pt(),u=this.root.filteredChanges.next;u;)u.changeTree.endEncode("filteredChanges"),u=u.next;this.root.filteredChanges=pt()}tryEncodeTypeId(u,m,_,w){let z=this.context.getTypeId(m),X=this.context.getTypeId(_);if(X===void 0){console.warn(`@colyseus/schema WARNING: Class "${_.name}" is not registered on TypeRegistry - Please either tag the class with @entity or define a @type() field.`);return}z!==X&&(u[w.offset++]=213,oe.number(u,X,w))}get hasChanges(){return this.root.changes.next!==void 0||this.root.filteredChanges.next!==void 0}};It.BUFFER_SIZE=typeof Buffer<"u"&&Buffer.poolSize||8*1024;let at=It;function Ye(R,u){if(u===-1||u>=R.length)return!1;let m=R.length-1;for(let _=u;_<m;_++)R[_]=R[_+1];return R.length=m,!0}class Ct extends Error{constructor(u){super(u),this.name="DecodingWarning"}}class Jt{constructor(){this.refs=new Map,this.refIds=new WeakMap,this.refCount={},this.deletedRefs=new Set,this.callbacks={},this.nextUniqueId=0}getNextUniqueId(){return this.nextUniqueId++}addRef(u,m,_=!0){this.refs.set(u,m),this.refIds.set(m,u),_&&(this.refCount[u]=(this.refCount[u]||0)+1),this.deletedRefs.has(u)&&this.deletedRefs.delete(u)}removeRef(u){let m=this.refCount[u];if(m===void 0){try{throw new Ct("trying to remove refId that doesn't exist: "+u)}catch(_){console.warn(_)}return}if(m===0){try{let _=this.refs.get(u);throw new Ct(`trying to remove refId '${u}' with 0 refCount (${_.constructor.name}: ${JSON.stringify(_)})`)}catch(_){console.warn(_)}return}(this.refCount[u]=m-1)<=0&&this.deletedRefs.add(u)}clearRefs(){this.refs.clear(),this.deletedRefs.clear(),this.callbacks={},this.refCount={}}garbageCollectDeletedRefs(){this.deletedRefs.forEach(u=>{if(this.refCount[u]>0)return;let m=this.refs.get(u);if(m.constructor[Symbol.metadata]!==void 0){let _=m.constructor[Symbol.metadata];for(let w in _){let z=_[w].name,X=typeof m[z]=="object"&&this.refIds.get(m[z]);X&&!this.deletedRefs.has(X)&&this.removeRef(X)}}else typeof m[h]=="function"&&Array.from(m.values()).forEach(_=>{let w=this.refIds.get(_);this.deletedRefs.has(w)||this.removeRef(w)});this.refs.delete(u),delete this.refCount[u],delete this.callbacks[u]}),this.deletedRefs.clear()}addCallback(u,m,_){if(u===void 0){let w=typeof m=="number"?i.OPERATION[m]:m;throw new Error(`Can't addCallback on '${w}' (refId is undefined)`)}return this.callbacks[u]||(this.callbacks[u]={}),this.callbacks[u][m]||(this.callbacks[u][m]=[]),this.callbacks[u][m].push(_),()=>this.removeCallback(u,m,_)}removeCallback(u,m,_){let w=this.callbacks?.[u]?.[m]?.indexOf(_);w!==void 0&&w!==-1&&Ye(this.callbacks[u][m],w)}}class Wt{constructor(u,m){this.currentRefId=0,this.setState(u),this.context=m||new Le(u.constructor)}setState(u){this.state=u,this.root=new Jt,this.root.addRef(0,u)}decode(u,m={offset:0},_=this.state){let w=[],z=this.root,X=u.byteLength,ue=_.constructor[s];for(this.currentRefId=0;m.offset<X;){if(u[m.offset]==255){m.offset++,_[f]?.();let ae=ge.number(u,m),he=z.refs.get(ae);he?(_=he,ue=_.constructor[s],this.currentRefId=ae):(console.error(`"refId" not found: ${ae}`,{previousRef:_,previousRefId:this.currentRefId}),console.warn("Please report this issue to the developers."),this.skipCurrentStructure(u,m,X));continue}if(ue(this,u,m,_,w)===rt){console.warn("@colyseus/schema: definition mismatch"),this.skipCurrentStructure(u,m,X);continue}}return _[f]?.(),this.triggerChanges?.(w),z.garbageCollectDeletedRefs(),w}skipCurrentStructure(u,m,_){let w={offset:m.offset};for(;m.offset<_&&!(u[m.offset]===255&&(w.offset=m.offset+1,this.root.refs.has(ge.number(u,w))));)m.offset++}getInstanceType(u,m,_){let w;if(u[m.offset]===213){m.offset++;let z=ge.number(u,m);w=this.context.get(z)}return w||_}createInstanceOfType(u){return new u}removeChildRefs(u,m){let _=typeof u[h]!="string",w=this.root.refIds.get(u);u.forEach((z,X)=>{m.push({ref:u,refId:w,op:i.OPERATION.DELETE,field:X,value:void 0,previousValue:z}),_&&this.root.removeRef(this.root.refIds.get(z))})}}class Mt extends Ie{}qe([ni("string")],Mt.prototype,"name",void 0),qe([ni("string")],Mt.prototype,"type",void 0),qe([ni("number")],Mt.prototype,"referencedType",void 0);class Zt extends Ie{constructor(){super(...arguments),this.fields=new jn}}qe([ni("number")],Zt.prototype,"id",void 0),qe([ni("number")],Zt.prototype,"extendsId",void 0),qe([ni([Mt])],Zt.prototype,"fields",void 0);class ze extends Ie{constructor(){super(...arguments),this.types=new jn}static encode(u,m={offset:0}){let _=u.context,w=new ze,z=new at(w),X=_.schemas.get(u.state.constructor);X>0&&(w.rootType=X);let ue=new Set,ne={},ae=se=>{if(se.extendsId===void 0||ue.has(se.extendsId)){ue.add(se.id),w.types.push(se);let Ge=ne[se.id];Ge!==void 0&&(delete ne[se.id],Ge.forEach(Oe=>ae(Oe)))}else ne[se.extendsId]===void 0&&(ne[se.extendsId]=[]),ne[se.extendsId].push(se)};_.schemas.forEach((se,Ge)=>{let Oe=new Zt;Oe.id=Number(se);let Re=Object.getPrototypeOf(Ge);Re!==Ie&&(Oe.extendsId=_.schemas.get(Re));let ye=Ge[Symbol.metadata];if(ye!==Re[Symbol.metadata])for(let $e in ye){let tn=Number($e),nn=ye[tn].name;if(!Object.prototype.hasOwnProperty.call(ye,nn))continue;let ii=new Mt;ii.name=nn;let fi,Mr=ye[tn];if(typeof Mr.type=="string")fi=Mr.type;else{let Sc;Ie.is(Mr.type)?(fi="ref",Sc=Mr.type):(fi=Object.keys(Mr.type)[0],typeof Mr.type[fi]=="string"?fi+=":"+Mr.type[fi]:Sc=Mr.type[fi]),ii.referencedType=Sc?_.getTypeId(Sc):-1}ii.type=fi,Oe.fields.push(ii)}ae(Oe)});for(let se in ne)ne[se].forEach(Ge=>w.types.push(Ge));return z.encodeAll(m).slice(0,m.offset)}static decode(u,m){let _=new ze;new Wt(_).decode(u,m);let z=new Le;_.types.forEach(ne=>{let ae=z.get(ne.extendsId)??Ie,he=class extends ae{};Le.register(he),z.add(he,ne.id)},{});let X=(ne,ae,he)=>{ae.fields.forEach((se,Ge)=>{let Oe=he+Ge;if(se.referencedType!==void 0){let Re=se.type,ye=z.get(se.referencedType);if(!ye){let $e=se.type.split(":");Re=$e[0],ye=$e[1]}Re==="ref"?je.addField(ne,Oe,se.name,ye):je.addField(ne,Oe,se.name,{[Re]:ye})}else je.addField(ne,Oe,se.name,se.type)})};_.types.forEach(ne=>{let ae=z.get(ne.id),he=je.initialize(ae),se=[],Ge=ne;do se.push(Ge),Ge=_.types.find(Re=>Re.id===Ge.extendsId);while(Ge);let Oe=0;se.reverse().forEach(Re=>{X(he,Re,Oe),Oe+=Re.fields.length})});let ue=new(z.get(_.rootType||0));return new Wt(ue,z)}}qe([ni([Zt])],ze.prototype,"types",void 0),qe([ni("number")],ze.prototype,"rootType",void 0);function Un(R){let u=R.root,m=u.callbacks,_=new WeakMap,w;R.triggerChanges=function(ue){let ne=new Set;for(let ae=0,he=ue.length;ae<he;ae++){let se=ue[ae],Ge=se.refId,Oe=se.ref,Re=m[Ge];if(Re){if((se.op&i.OPERATION.DELETE)===i.OPERATION.DELETE&&se.previousValue instanceof Ie){let ye=m[u.refIds.get(se.previousValue)]?.[i.OPERATION.DELETE];for(let $e=ye?.length-1;$e>=0;$e--)ye[$e]()}if(Oe instanceof Ie){if(!ne.has(Ge)){let ye=Re?.[i.OPERATION.REPLACE];for(let $e=ye?.length-1;$e>=0;$e--)ye[$e]()}if(Re.hasOwnProperty(se.field)){let ye=Re[se.field];for(let $e=ye?.length-1;$e>=0;$e--)ye[$e](se.value,se.previousValue)}}else{if((se.op&i.OPERATION.DELETE)===i.OPERATION.DELETE){if(se.previousValue!==void 0){let ye=Re[i.OPERATION.DELETE];for(let $e=ye?.length-1;$e>=0;$e--)ye[$e](se.previousValue,se.dynamicIndex??se.field)}if((se.op&i.OPERATION.ADD)===i.OPERATION.ADD){let ye=Re[i.OPERATION.ADD];for(let $e=ye?.length-1;$e>=0;$e--)ye[$e](se.value,se.dynamicIndex??se.field)}}else if((se.op&i.OPERATION.ADD)===i.OPERATION.ADD&&se.previousValue!==se.value){let ye=Re[i.OPERATION.ADD];for(let $e=ye?.length-1;$e>=0;$e--)ye[$e](se.value,se.dynamicIndex??se.field)}if(se.value!==se.previousValue&&(se.value!==void 0||se.previousValue!==void 0)){let ye=Re[i.OPERATION.REPLACE];for(let $e=ye?.length-1;$e>=0;$e--)ye[$e](se.value,se.dynamicIndex??se.field)}}ne.add(Ge)}}};function z(ue,ne){let ae=ne.instance?.constructor[Symbol.metadata]||ue,he=ne.instance&&typeof ne.instance.forEach=="function"||ue&&typeof ue[Symbol.metadata]>"u";if(ae&&!he){let se=function(Ge,Oe,Re,ye){return ye&&ne.instance[Oe]!==void 0&&!_.has(w)&&Re(ne.instance[Oe],void 0),u.addCallback(u.refIds.get(Ge),Oe,Re)};return new Proxy({listen:function(Oe,Re,ye=!0){if(ne.instance)return se(ne.instance,Oe,Re,ye);{let $e=()=>{};return ne.onInstanceAvailable((tn,nn)=>{$e=se(tn,Oe,Re,ye&&nn&&!_.has(w))}),()=>$e()}},onChange:function(Oe){return u.addCallback(u.refIds.get(ne.instance),i.OPERATION.REPLACE,Oe)},bindTo:function(Oe,Re){return Re||(Re=Object.keys(ae).map(ye=>ae[ye].name)),u.addCallback(u.refIds.get(ne.instance),i.OPERATION.REPLACE,()=>{Re.forEach(ye=>Oe[ye]=ne.instance[ye])})}},{get(Ge,Oe){let Re=ae[ae[Oe]];if(Re){let ye=ne.instance?.[Oe],$e=(tn=>{let nn=X(ne.instance).listen(Oe,(ii,fi)=>{tn(ii,!1),nn?.()},!1);u.refIds.get(ye)!==void 0&&tn(ye,!0)});return z(Re.type,{instance:u.refIds.get(ye)&&ye,parentInstance:ne.instance,onInstanceAvailable:$e})}else return Ge[Oe]},has(Ge,Oe){return ae[Oe]!==void 0},set(Ge,Oe,Re){throw new Error("not allowed")},deleteProperty(Ge,Oe){throw new Error("not allowed")}})}else{let se=function(Re,ye,$e){return $e&&Re.forEach((tn,nn)=>ye(tn,nn)),u.addCallback(u.refIds.get(Re),i.OPERATION.ADD,(tn,nn)=>{_.set(ye,!0),w=ye,ye(tn,nn),_.delete(ye),w=void 0})},Ge=function(Re,ye){return u.addCallback(u.refIds.get(Re),i.OPERATION.DELETE,ye)},Oe=function(Re,ye){return u.addCallback(u.refIds.get(Re),i.OPERATION.REPLACE,ye)};return new Proxy({onAdd:function(Re,ye=!0){if(ne.instance)return se(ne.instance,Re,ye&&!_.has(w));if(ne.onInstanceAvailable){let $e=()=>{};return ne.onInstanceAvailable((tn,nn)=>{$e=se(tn,Re,ye&&nn&&!_.has(w))}),()=>$e()}},onRemove:function(Re){if(ne.instance)return Ge(ne.instance,Re);if(ne.onInstanceAvailable){let ye=()=>{};return ne.onInstanceAvailable($e=>{ye=Ge($e,Re)}),()=>ye()}},onChange:function(Re){if(ne.instance)return Oe(ne.instance,Re);if(ne.onInstanceAvailable){let ye=()=>{};return ne.onInstanceAvailable($e=>{ye=Oe($e,Re)}),()=>ye()}}},{get(Re,ye){if(!Re[ye])throw new Error(`Can't access '${ye}' through callback proxy. access the instance directly.`);return Re[ye]},has(Re,ye){return Re[ye]!==void 0},set(Re,ye,$e){throw new Error("not allowed")},deleteProperty(Re,ye){throw new Error("not allowed")}})}}function X(ue){return z(void 0,{instance:ue})}return X}function vt(R,u){R.triggerChanges=u}class Xn{constructor(u=!1){this.iterable=u,this.visible=new WeakSet,this.invisible=new WeakSet,this.changes=new Map,u&&(this.items=[])}add(u,m=Mi,_=!0){let w=u?.[c],z=w.parent;if(w){if(!z&&w.refId!==0)throw new Error(`Cannot add a detached instance to the StateView. Make sure to assign the "${w.ref.constructor.name}" instance to the state before calling view.add()`)}else return console.warn("StateView#add(), invalid object:",u),!1;let X=u.constructor[Symbol.metadata];this.visible.add(w),this.iterable&&_&&this.items.push(u),_&&z&&this.addParentOf(w,m);let ue=this.changes.get(w.refId);ue===void 0&&(ue={},this.changes.set(w.refId,ue));let ne=!1;if(w.forEachChild((ae,he)=>{X&&X[he].tag!==void 0&&X[he].tag!==m||this.add(ae.ref,m,!1)&&(ne=!0)}),m!==Mi){this.tags||(this.tags=new WeakMap);let ae;this.tags.has(w)?ae=this.tags.get(w):(ae=new Set,this.tags.set(w,ae)),ae.add(m),X?.[g]?.[m]?.forEach(he=>{w.getChange(he)!==i.OPERATION.DELETE&&(ue[he]=i.OPERATION.ADD)})}else if(!w.isNew||ne){let ae=w.filteredChanges!==void 0?w.allFilteredChanges:w.allChanges,he=this.invisible.has(w);for(let se=0,Ge=ae.operations.length;se<Ge;se++){let Oe=ae.operations[se];if(Oe===void 0)continue;let Re=w.indexedOperations[Oe]??i.OPERATION.ADD,ye=X?.[Oe].tag;Re!==i.OPERATION.DELETE&&(he||ye===void 0||ye===m)&&(ue[Oe]=Re,ne=!0)}}return ne}addParentOf(u,m){let _=u.parent[c],w=u.parentIndex;if(!this.visible.has(_)){this.visible.add(_);let z=_.parent?.[c];z&&z.filteredChanges!==void 0&&this.addParentOf(_,m)}if(_.getChange(w)!==i.OPERATION.DELETE){let z=this.changes.get(_.refId);z===void 0&&(z={},this.changes.set(_.refId,z)),this.tags||(this.tags=new WeakMap);let X;this.tags.has(_)?X=this.tags.get(_):(X=new Set,this.tags.set(_,X)),X.add(m),z[w]=i.OPERATION.ADD}}remove(u,m=Mi,_=!1){let w=u[c];if(!w)return console.warn("StateView#remove(), invalid object:",u),this;this.visible.delete(w),this.iterable&&!_&&Ye(this.items,this.items.indexOf(u));let X=w.ref.constructor[Symbol.metadata],ue=this.changes.get(w.refId);if(ue===void 0&&(ue={},this.changes.set(w.refId,ue)),m===Mi){let ne=w.parent;if(ne&&!je.isValidInstance(ne)&&w.isFiltered){let ae=ne[c],he=this.changes.get(ae.refId);he===void 0?(he={},this.changes.set(ae.refId,he)):he[w.parentIndex]===i.OPERATION.ADD&&this.changes.delete(w.refId),he[w.parentIndex]=i.OPERATION.DELETE,this._recursiveDeleteVisibleChangeTree(w)}else X?.[b]?.forEach(ae=>ue[ae]=i.OPERATION.DELETE)}else X?.[g][m].forEach(ne=>ue[ne]=i.OPERATION.DELETE);if(this.tags&&this.tags.has(w)){let ne=this.tags.get(w);m===void 0?this.tags.delete(w):(ne.delete(m),ne.size===0&&this.tags.delete(w))}return this}has(u){return this.visible.has(u[c])}hasTag(u,m=Mi){return this.tags?.get(u[c])?.has(m)??!1}clear(){if(!this.iterable)throw new Error("StateView#clear() is only available for iterable StateView's. Use StateView(iterable: true) constructor.");for(let u=0,m=this.items.length;u<m;u++)this.remove(this.items[u],Mi,!0);this.items.length=0}isChangeTreeVisible(u){let m=this.visible.has(u);return!m&&u.isVisibilitySharedWithParent&&this.visible.has(u.parent[c])&&(this.visible.add(u),m=!0),m}_recursiveDeleteVisibleChangeTree(u){u.forEachChild(m=>{this.visible.delete(m),this._recursiveDeleteVisibleChangeTree(m)})}}ce("map",{constructor:di}),ce("array",{constructor:jn}),ce("set",{constructor:wr}),ce("collection",{constructor:sr}),i.$changes=c,i.$childType=h,i.$decoder=s,i.$deleteByIndex=l,i.$encoder=r,i.$filter=a,i.$getByIndex=o,i.$track=n,i.ArraySchema=jn,i.ChangeTree=de,i.CollectionSchema=sr,i.Decoder=Wt,i.Encoder=at,i.MapSchema=di,i.Metadata=je,i.Reflection=ze,i.ReflectionField=Mt,i.ReflectionType=Zt,i.Schema=Ie,i.SetSchema=wr,i.StateView=Xn,i.TypeContext=Le,i.decode=ge,i.decodeKeyValueOperation=$n,i.decodeSchemaOperation=Rt,i.defineCustomTypes=Be,i.defineTypes=ie,i.deprecated=j,i.dumpChanges=Fe,i.encode=oe,i.encodeArray=Xe,i.encodeKeyValueOperation=xe,i.encodeSchemaOperation=Ae,i.entity=Fu,i.getDecoderStateCallbacks=Un,i.getRawChangesCallback=vt,i.registerType=ce,i.schema=ee,i.type=ni,i.view=vc}))});var W_=dn(V_=>{"use strict";var G_=(rc(),Gs(ic)),Us=ac(),mm=class{constructor(e){this.events=e,this.isOpen=!1,this.lengthPrefixBuffer=new Uint8Array(9)}connect(e,t={}){let n=t.fingerprint&&{serverCertificateHashes:[{algorithm:"sha-256",value:new Uint8Array(t.fingerprint).buffer}]}||void 0;this.wt=new WebTransport(e,n),this.wt.ready.then(r=>{console.log("WebTransport ready!",r),this.isOpen=!0,this.unreliableReader=this.wt.datagrams.readable.getReader(),this.unreliableWriter=this.wt.datagrams.writable.getWriter(),this.wt.incomingBidirectionalStreams.getReader().read().then(a=>{this.reader=a.value.readable.getReader(),this.writer=a.value.writable.getWriter(),this.sendSeatReservation(t.room.roomId,t.sessionId,t.reconnectionToken),this.readIncomingData(),this.readIncomingUnreliableData()}).catch(a=>{console.error("failed to read incoming stream",a),console.error("TODO: close the connection")})}).catch(r=>{console.log("WebTransport not ready!",r),this._close()}),this.wt.closed.then(r=>{console.log("WebTransport closed w/ success",r),this.events.onclose({code:r.closeCode,reason:r.reason})}).catch(r=>{console.log("WebTransport closed w/ error",r),this.events.onerror(r),this.events.onclose({code:r.closeCode,reason:r.reason})}).finally(()=>{this._close()})}send(e){let t=Us.encode.number(this.lengthPrefixBuffer,e.length,{offset:0}),n=new Uint8Array(t+e.length);n.set(this.lengthPrefixBuffer.subarray(0,t),0),n.set(e,t),this.writer.write(n)}sendUnreliable(e){let t=Us.encode.number(this.lengthPrefixBuffer,e.length,{offset:0}),n=new Uint8Array(t+e.length);n.set(this.lengthPrefixBuffer.subarray(0,t),0),n.set(e,t),this.unreliableWriter.write(n)}close(e,t){try{this.wt.close({closeCode:e,reason:t})}catch(n){console.error(n)}}readIncomingData(){return G_.__awaiter(this,void 0,void 0,function*(){let e;for(;this.isOpen;){try{e=yield this.reader.read();let t=e.value,n={offset:0};do{let r=Us.decode.number(t,n);this.events.onmessage({data:t.subarray(n.offset,n.offset+r)}),n.offset+=r}while(n.offset<t.length)}catch(t){t.message.indexOf("session is closed")===-1&&console.error("H3Transport: failed to read incoming data",t);break}if(e.done)break}})}readIncomingUnreliableData(){return G_.__awaiter(this,void 0,void 0,function*(){let e;for(;this.isOpen;){try{e=yield this.unreliableReader.read();let t=e.value,n={offset:0};do{let r=Us.decode.number(t,n);this.events.onmessage({data:t.subarray(n.offset,n.offset+r)}),n.offset+=r}while(n.offset<t.length)}catch(t){t.message.indexOf("session is closed")===-1&&console.error("H3Transport: failed to read incoming data",t);break}if(e.done)break}})}sendSeatReservation(e,t,n){let r={offset:0},s=[];Us.encode.string(s,e,r),Us.encode.string(s,t,r),n&&Us.encode.string(s,n,r),this.writer.write(new Uint8Array(s).buffer)}_close(){this.isOpen=!1}};V_.H3TransportTransport=mm});var $_=dn((wL,q_)=>{"use strict";q_.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var X_=dn(j_=>{"use strict";var ER=$_(),gm=globalThis.WebSocket||ER,bm=class{constructor(e){this.events=e}send(e){this.ws.send(e)}sendUnreliable(e){console.warn("colyseus.js: The WebSocket transport does not support unreliable messages")}connect(e,t){try{this.ws=new gm(e,{headers:t,protocols:this.protocols})}catch{this.ws=new gm(e,this.protocols)}this.ws.binaryType="arraybuffer",this.ws.onopen=this.events.onopen,this.ws.onmessage=this.events.onmessage,this.ws.onclose=this.events.onclose,this.ws.onerror=this.events.onerror}close(e,t){this.ws.close(e,t)}get isOpen(){return this.ws.readyState===gm.OPEN}};j_.WebSocketTransport=bm});var Y_=dn(K_=>{"use strict";var RR=W_(),CR=X_(),xm=class{constructor(e){this.events={},e==="h3"?this.transport=new RR.H3TransportTransport(this.events):this.transport=new CR.WebSocketTransport(this.events)}connect(e,t){this.transport.connect.call(this.transport,e,t)}send(e){this.transport.send(e)}sendUnreliable(e){this.transport.sendUnreliable(e)}close(e,t){this.transport.close(e,t)}get isOpen(){return this.transport.isOpen}};K_.Connection=xm});var _m=dn(ks=>{"use strict";ks.Protocol=void 0;(function(i){i[i.HANDSHAKE=9]="HANDSHAKE",i[i.JOIN_ROOM=10]="JOIN_ROOM",i[i.ERROR=11]="ERROR",i[i.LEAVE_ROOM=12]="LEAVE_ROOM",i[i.ROOM_DATA=13]="ROOM_DATA",i[i.ROOM_STATE=14]="ROOM_STATE",i[i.ROOM_STATE_PATCH=15]="ROOM_STATE_PATCH",i[i.ROOM_DATA_SCHEMA=16]="ROOM_DATA_SCHEMA",i[i.ROOM_DATA_BYTES=17]="ROOM_DATA_BYTES"})(ks.Protocol||(ks.Protocol={}));ks.ErrorCode=void 0;(function(i){i[i.MATCHMAKE_NO_HANDLER=4210]="MATCHMAKE_NO_HANDLER",i[i.MATCHMAKE_INVALID_CRITERIA=4211]="MATCHMAKE_INVALID_CRITERIA",i[i.MATCHMAKE_INVALID_ROOM_ID=4212]="MATCHMAKE_INVALID_ROOM_ID",i[i.MATCHMAKE_UNHANDLED=4213]="MATCHMAKE_UNHANDLED",i[i.MATCHMAKE_EXPIRED=4214]="MATCHMAKE_EXPIRED",i[i.AUTH_FAILED=4215]="AUTH_FAILED",i[i.APPLICATION_ERROR=4216]="APPLICATION_ERROR"})(ks.ErrorCode||(ks.ErrorCode={}))});var vm=dn(ym=>{"use strict";var J_={};function IR(i,e){J_[i]=e}function PR(i){let e=J_[i];if(!e)throw new Error("missing serializer: "+i);return e}ym.getSerializer=PR;ym.registerSerializer=IR});var Sm=dn(Z_=>{"use strict";var LR=()=>({emit(i,...e){let t=this.events[i]||[];for(let n=0,r=t.length;n<r;n++)t[n](...e)},events:{},on(i,e){var t;return!((t=this.events[i])===null||t===void 0)&&t.push(e)||(this.events[i]=[e]),()=>{var n;this.events[i]=(n=this.events[i])===null||n===void 0?void 0:n.filter(r=>e!==r)}}});Z_.createNanoEvents=LR});var Q_=dn(wm=>{"use strict";var gu=class{constructor(){this.handlers=[]}register(e,t=!1){return this.handlers.push(e),this}invoke(...e){this.handlers.forEach(t=>t.apply(this,e))}invokeAsync(...e){return Promise.all(this.handlers.map(t=>t.apply(this,e)))}remove(e){let t=this.handlers.indexOf(e);this.handlers[t]=this.handlers[this.handlers.length-1],this.handlers.pop()}clear(){this.handlers=[]}};function DR(){let i=new gu;function e(t){return i.register(t,this===null)}return e.once=t=>{let n=function(...r){t.apply(this,r),i.remove(n)};i.register(n)},e.remove=t=>i.remove(t),e.invoke=(...t)=>i.invoke(...t),e.invokeAsync=(...t)=>i.invokeAsync(...t),e.clear=()=>i.clear(),e}wm.EventEmitter=gu;wm.createSignal=DR});var Tm=dn(Am=>{"use strict";var bu=ac();function NR(i){try{return bu.getDecoderStateCallbacks(i.serializer.decoder)}catch{return}}var Mm=class{setState(e,t){this.decoder.decode(e,t)}getState(){return this.state}patch(e,t){return this.decoder.decode(e,t)}teardown(){this.decoder.root.clearRefs()}handshake(e,t){this.state?(bu.Reflection.decode(e,t),this.decoder=new bu.Decoder(this.state)):(this.decoder=bu.Reflection.decode(e,t),this.state=this.decoder.state)}};Am.SchemaSerializer=Mm;Am.getStateCallbacks=NR});function xu(i){try{if(!Gt.trusted&&!Qr){let t=St.sharedLength||0;t<St.length&&(St.length=t)}let e;if(Gt.randomAccessStructure&&Ne[$]<64&&Ne[$]>=32&&ty?(e=ty(Ne,$,Si,Gt),Ne=null,!(i&&i.lazy)&&e&&(e=e.toJSON()),$=Si):e=ln(),wn&&($=wn.postBundlePosition,wn=null),Qr&&(St.restoreStructures=null),$==Si)St&&St.restoreStructures&&ry(),St=null,Ne=null,yr&&(yr=null);else{if($>Si)throw new Error("Unexpected end of MessagePack data");if(!Qr){let t;try{t=JSON.stringify(e,(n,r)=>typeof r=="bigint"?`${r}n`:r).slice(0,100)}catch(n){t="(JSON view not available "+n+")"}throw new Error("Data read, but end of buffer not reached "+t)}}return e}catch(e){throw St&&St.restoreStructures&&ry(),lc(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")||$>Si)&&(e.incomplete=!0),e}}function ry(){for(let i in St.restoreStructures)St[i]=St.restoreStructures[i];St.restoreStructures=null}function ln(){let i=Ne[$++];if(i<160)if(i<128){if(i<64)return i;{let e=St[i&63]||Gt.getStructures&&py()[i&63];return e?(e.read||(e.read=Lm(e,i&63)),e.read()):i}}else if(i<144)if(i-=128,Gt.mapsAsObjects){let e={};for(let t=0;t<i;t++){let n=by();n==="__proto__"&&(n="__proto_"),e[n]=ln()}return e}else{let e=new Map;for(let t=0;t<i;t++)e.set(ln(),ln());return e}else{i-=144;let e=new Array(i);for(let t=0;t<i;t++)e[t]=ln();return Gt.freezeData?Object.freeze(e):e}else if(i<192){let e=i-160;if(ir>=$)return Zr.slice($-vi,($+=e)-vi);if(ir==0&&Si<140){let t=e<16?Dm(e):gy(e);if(t!=null)return t}return Pm(e)}else{let e;switch(i){case 192:return null;case 193:return wn?(e=ln(),e>0?wn[1].slice(wn.position1,wn.position1+=e):wn[0].slice(wn.position0,wn.position0-=e)):_u;case 194:return!1;case 195:return!0;case 196:if(e=Ne[$++],e===void 0)throw new Error("Unexpected end of buffer");return Em(e);case 197:return e=yt.getUint16($),$+=2,Em(e);case 198:return e=yt.getUint32($),$+=4,Em(e);case 199:return Bs(Ne[$++]);case 200:return e=yt.getUint16($),$+=2,Bs(e);case 201:return e=yt.getUint32($),$+=4,Bs(e);case 202:if(e=yt.getFloat32($),Gt.useFloat32>2){let t=uc[(Ne[$]&127)<<1|Ne[$+1]>>7];return $+=4,(t*e+(e>0?.5:-.5)>>0)/t}return $+=4,e;case 203:return e=yt.getFloat64($),$+=8,e;case 204:return Ne[$++];case 205:return e=yt.getUint16($),$+=2,e;case 206:return e=yt.getUint32($),$+=4,e;case 207:return Gt.int64AsType==="number"?(e=yt.getUint32($)*4294967296,e+=yt.getUint32($+4)):Gt.int64AsType==="string"?e=yt.getBigUint64($).toString():Gt.int64AsType==="auto"?(e=yt.getBigUint64($),e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=yt.getBigUint64($),$+=8,e;case 208:return yt.getInt8($++);case 209:return e=yt.getInt16($),$+=2,e;case 210:return e=yt.getInt32($),$+=4,e;case 211:return Gt.int64AsType==="number"?(e=yt.getInt32($)*4294967296,e+=yt.getUint32($+4)):Gt.int64AsType==="string"?e=yt.getBigInt64($).toString():Gt.int64AsType==="auto"?(e=yt.getBigInt64($),e>=BigInt(-2)<<BigInt(52)&&e<=BigInt(2)<<BigInt(52)&&(e=Number(e))):e=yt.getBigInt64($),$+=8,e;case 212:if(e=Ne[$++],e==114)return hy(Ne[$++]&63);{let t=On[e];if(t)return t.read?($++,t.read(ln())):t.noBuffer?($++,t()):t(Ne.subarray($,++$));throw new Error("Unknown extension "+e)}case 213:return e=Ne[$],e==114?($++,hy(Ne[$++]&63,Ne[$++])):Bs(2);case 214:return Bs(4);case 215:return Bs(8);case 216:return Bs(16);case 217:return e=Ne[$++],ir>=$?Zr.slice($-vi,($+=e)-vi):FR(e);case 218:return e=yt.getUint16($),$+=2,ir>=$?Zr.slice($-vi,($+=e)-vi):UR(e);case 219:return e=yt.getUint32($),$+=4,ir>=$?Zr.slice($-vi,($+=e)-vi):kR(e);case 220:return e=yt.getUint16($),$+=2,ay(e);case 221:return e=yt.getUint32($),$+=4,ay(e);case 222:return e=yt.getUint16($),$+=2,oy(e);case 223:return e=yt.getUint32($),$+=4,oy(e);default:if(i>=224)return i-256;if(i===void 0){let t=new Error("Unexpected end of MessagePack data");throw t.incomplete=!0,t}throw new Error("Unknown MessagePack token "+i)}}}function Lm(i,e){function t(){if(t.count++>fy){let r=i.read=new Function("r","return function(){return "+(Gt.freezeData?"Object.freeze":"")+"({"+i.map(s=>s==="__proto__"?"__proto_:r()":OR.test(s)?s+":r()":"["+JSON.stringify(s)+"]:r()").join(",")+"})}")(ln);return i.highByte===0&&(i.read=sy(e,i.read)),r()}let n={};for(let r=0,s=i.length;r<s;r++){let a=i[r];a==="__proto__"&&(a="__proto_"),n[a]=ln()}return Gt.freezeData?Object.freeze(n):n}return t.count=0,i.highByte===0?sy(e,t):t}function py(){let i=_y(()=>(Ne=null,Gt.getStructures()));return St=Gt._mergeStructures(i,St)}function hc(i){let e;if(i<16&&(e=Dm(i)))return e;if(i>64&&Rm)return Rm.decode(Ne.subarray($,$+=i));let t=$+i,n=[];for(e="";$<t;){let r=Ne[$++];if((r&128)===0)n.push(r);else if((r&224)===192){let s=Ne[$++]&63;n.push((r&31)<<6|s)}else if((r&240)===224){let s=Ne[$++]&63,a=Ne[$++]&63;n.push((r&31)<<12|s<<6|a)}else if((r&248)===240){let s=Ne[$++]&63,a=Ne[$++]&63,o=Ne[$++]&63,l=(r&7)<<18|s<<12|a<<6|o;l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|l&1023),n.push(l)}else n.push(r);n.length>=4096&&(e+=Sn.apply(String,n),n.length=0)}return n.length>0&&(e+=Sn.apply(String,n)),e}function ay(i){let e=new Array(i);for(let t=0;t<i;t++)e[t]=ln();return Gt.freezeData?Object.freeze(e):e}function oy(i){if(Gt.mapsAsObjects){let e={};for(let t=0;t<i;t++){let n=by();n==="__proto__"&&(n="__proto_"),e[n]=ln()}return e}else{let e=new Map;for(let t=0;t<i;t++)e.set(ln(),ln());return e}}function gy(i){let e=$,t=new Array(i);for(let n=0;n<i;n++){let r=Ne[$++];if((r&128)>0){$=e;return}t[n]=r}return Sn.apply(String,t)}function Dm(i){if(i<4)if(i<2){if(i===0)return"";{let e=Ne[$++];if((e&128)>1){$-=1;return}return Sn(e)}}else{let e=Ne[$++],t=Ne[$++];if((e&128)>0||(t&128)>0){$-=2;return}if(i<3)return Sn(e,t);let n=Ne[$++];if((n&128)>0){$-=3;return}return Sn(e,t,n)}else{let e=Ne[$++],t=Ne[$++],n=Ne[$++],r=Ne[$++];if((e&128)>0||(t&128)>0||(n&128)>0||(r&128)>0){$-=4;return}if(i<6){if(i===4)return Sn(e,t,n,r);{let s=Ne[$++];if((s&128)>0){$-=5;return}return Sn(e,t,n,r,s)}}else if(i<8){let s=Ne[$++],a=Ne[$++];if((s&128)>0||(a&128)>0){$-=6;return}if(i<7)return Sn(e,t,n,r,s,a);let o=Ne[$++];if((o&128)>0){$-=7;return}return Sn(e,t,n,r,s,a,o)}else{let s=Ne[$++],a=Ne[$++],o=Ne[$++],l=Ne[$++];if((s&128)>0||(a&128)>0||(o&128)>0||(l&128)>0){$-=8;return}if(i<10){if(i===8)return Sn(e,t,n,r,s,a,o,l);{let c=Ne[$++];if((c&128)>0){$-=9;return}return Sn(e,t,n,r,s,a,o,l,c)}}else if(i<12){let c=Ne[$++],h=Ne[$++];if((c&128)>0||(h&128)>0){$-=10;return}if(i<11)return Sn(e,t,n,r,s,a,o,l,c,h);let d=Ne[$++];if((d&128)>0){$-=11;return}return Sn(e,t,n,r,s,a,o,l,c,h,d)}else{let c=Ne[$++],h=Ne[$++],d=Ne[$++],f=Ne[$++];if((c&128)>0||(h&128)>0||(d&128)>0||(f&128)>0){$-=12;return}if(i<14){if(i===12)return Sn(e,t,n,r,s,a,o,l,c,h,d,f);{let p=Ne[$++];if((p&128)>0){$-=13;return}return Sn(e,t,n,r,s,a,o,l,c,h,d,f,p)}}else{let p=Ne[$++],x=Ne[$++];if((p&128)>0||(x&128)>0){$-=14;return}if(i<15)return Sn(e,t,n,r,s,a,o,l,c,h,d,f,p,x);let y=Ne[$++];if((y&128)>0){$-=15;return}return Sn(e,t,n,r,s,a,o,l,c,h,d,f,p,x,y)}}}}}function cy(){let i=Ne[$++],e;if(i<192)e=i-160;else switch(i){case 217:e=Ne[$++];break;case 218:e=yt.getUint16($),$+=2;break;case 219:e=yt.getUint32($),$+=4;break;default:throw new Error("Expected string")}return hc(e)}function Em(i){return Gt.copyBuffers?Uint8Array.prototype.slice.call(Ne,$,$+=i):Ne.subarray($,$+=i)}function Bs(i){let e=Ne[$++];if(On[e]){let t;return On[e](Ne.subarray($,t=$+=i),n=>{$=n;try{return ln()}finally{$=t}})}else throw new Error("Unknown extension type "+e)}function by(){let i=Ne[$++];if(i>=160&&i<192){if(i=i-160,ir>=$)return Zr.slice($-vi,($+=i)-vi);if(!(ir==0&&Si<180))return Pm(i)}else return $--,xy(ln());let e=(i<<5^(i>1?yt.getUint16($):i>0?Ne[$]:0))&4095,t=ly[e],n=$,r=$+i-3,s,a=0;if(t&&t.bytes==i){for(;n<r;){if(s=yt.getUint32(n),s!=t[a++]){n=1879048192;break}n+=4}for(r+=3;n<r;)if(s=Ne[n++],s!=t[a++]){n=1879048192;break}if(n===r)return $=n,t.string;r-=3,n=$}for(t=[],ly[e]=t,t.bytes=i;n<r;)s=yt.getUint32(n),t.push(s),n+=4;for(r+=3;n<r;)s=Ne[n++],t.push(s);let o=i<16?Dm(i):gy(i);return o!=null?t.string=o:t.string=Pm(i)}function xy(i){if(typeof i=="string")return i;if(typeof i=="number"||typeof i=="boolean"||typeof i=="bigint")return i.toString();if(i==null)return i+"";if(Gt.allowArraysInMapKeys&&Array.isArray(i)&&i.flat().every(e=>["string","number","boolean","bigint"].includes(typeof e)))return i.flat().toString();throw new Error(`Invalid property type for record: ${typeof i}`)}function _y(i){iy&&iy();let e=Si,t=$,n=Im,r=vi,s=ir,a=Zr,o=Cm,l=yr,c=wn,h=new Uint8Array(Ne.slice(0,Si)),d=St,f=St.slice(0,St.length),p=Gt,x=Qr,y=i();return Si=e,$=t,Im=n,vi=r,ir=s,Zr=a,Cm=o,yr=l,wn=c,Ne=h,Qr=x,St=d,St.splice(0,St.length,...f),Gt=p,yt=new DataView(Ne.buffer,Ne.byteOffset,Ne.byteLength),y}function lc(){Ne=null,yr=null,St=null}function yy(i){i.unpack?On[i.type]=i.unpack:On[i.type]=i}function Ty(i){Ay[0]=i;let e=uc[(uy[3]&127)<<1|uy[2]>>7];return(e*i+(i>0?.5:-.5)>>0)/e}var Rm,Ne,Si,$,dy,Cm,Im,Gt,St,Zr,vi,ir,wn,yr,On,yt,ey,oc,_u,Qr,fy,ty,ny,iy,rr,OR,sy,Pm,FR,UR,kR,my,Sn,ly,hy,BR,Nm,zR,HR,uc,vy,yu,Sy,wy,My,dc,Ay,uy,Fa=un(()=>{try{Rm=new TextDecoder}catch{}$=0,dy=[],Cm=dy,Im=0,Gt={},vi=0,ir=0,On=[],ey={useRecords:!1,mapsAsObjects:!0},oc=class{},_u=new oc;_u.name="MessagePack 0xC1";Qr=!1,fy=2;try{new Function("")}catch{fy=1/0}rr=class i{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=!1&&(e.structures=[],e.maxSharedStructures||(e.maxSharedStructures=0))),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType="number")),Object.assign(this,e)}unpack(e,t){if(Ne)return _y(()=>(lc(),this?this.unpack(e,t):i.prototype.unpack.call(ey,e,t)));!e.buffer&&e.constructor===ArrayBuffer&&(e=typeof Buffer<"u"?Buffer.from(e):new Uint8Array(e)),typeof t=="object"?(Si=t.end||e.length,$=t.start||0):($=0,Si=t>-1?t:e.length),Im=0,ir=0,Zr=null,Cm=dy,wn=null,Ne=e;try{yt=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(n){throw Ne=null,e instanceof Uint8Array?n:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof i){if(Gt=this,this.structures)return St=this.structures,xu(t);(!St||St.length>0)&&(St=[])}else Gt=ey,(!St||St.length>0)&&(St=[]);return xu(t)}unpackMultiple(e,t){let n,r=0;try{Qr=!0;let s=e.length,a=this?this.unpack(e,s):yu.unpack(e,s);if(t){if(t(a,r,$)===!1)return;for(;$<s;)if(r=$,t(xu(),r,$)===!1)return}else{for(n=[a];$<s;)r=$,n.push(xu());return n}}catch(s){throw s.lastPosition=r,s.values=n,s}finally{Qr=!1,lc()}}_mergeStructures(e,t){ny&&(e=ny.call(this,e)),e=e||[],Object.isFrozen(e)&&(e=e.map(n=>n.slice(0)));for(let n=0,r=e.length;n<r;n++){let s=e[n];s&&(s.isShared=!0,n>=32&&(s.highByte=n-32>>5))}e.sharedLength=e.length;for(let n in t||[])if(n>=0){let r=e[n],s=t[n];s&&(r&&((e.restoreStructures||(e.restoreStructures=[]))[n]=r),e[n]=s)}return this.structures=e}decode(e,t){return this.unpack(e,t)}};OR=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;sy=(i,e)=>function(){let t=Ne[$++];if(t===0)return e();let n=i<32?-(i+(t<<5)):i+(t<<5),r=St[n]||py()[n];if(!r)throw new Error("Record id is not defined for "+n);return r.read||(r.read=Lm(r,i)),r.read()};Pm=hc,FR=hc,UR=hc,kR=hc,my=!1;Sn=String.fromCharCode;ly=new Array(4096);hy=(i,e)=>{let t=ln().map(xy),n=i;e!==void 0&&(i=i<32?-((e<<5)+i):(e<<5)+i,t.highByte=e);let r=St[i];return r&&(r.isShared||Qr)&&((St.restoreStructures||(St.restoreStructures=[]))[i]=r),St[i]=t,t.read=Lm(t,n),t.read()};On[0]=()=>{};On[0].noBuffer=!0;On[66]=i=>{let e=i.length,t=BigInt(i[0]&128?i[0]-256:i[0]);for(let n=1;n<e;n++)t<<=BigInt(8),t+=BigInt(i[n]);return t};BR={Error,TypeError,ReferenceError};On[101]=()=>{let i=ln();return(BR[i[0]]||Error)(i[1],{cause:i[2]})};On[105]=i=>{if(Gt.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=yt.getUint32($-4);yr||(yr=new Map);let t=Ne[$],n;t>=144&&t<160||t==220||t==221?n=[]:n={};let r={target:n};yr.set(e,r);let s=ln();return r.used?Object.assign(n,s):(r.target=s,s)};On[112]=i=>{if(Gt.structuredClone===!1)throw new Error("Structured clone extension is disabled");let e=yt.getUint32($-4),t=yr.get(e);return t.used=!0,t.target};On[115]=()=>new Set(ln());Nm=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map(i=>i+"Array"),zR=typeof globalThis=="object"?globalThis:window;On[116]=i=>{let e=i[0],t=Nm[e];if(!t){if(e===16){let n=new ArrayBuffer(i.length-1);return new Uint8Array(n).set(i.subarray(1)),n}throw new Error("Could not find typed array for code "+e)}return new zR[t](Uint8Array.prototype.slice.call(i,1).buffer)};On[120]=()=>{let i=ln();return new RegExp(i[0],i[1])};HR=[];On[98]=i=>{let e=(i[0]<<24)+(i[1]<<16)+(i[2]<<8)+i[3],t=$;return $+=e-i.length,wn=HR,wn=[cy(),cy()],wn.position0=0,wn.position1=0,wn.postBundlePosition=$,$=t,ln()};On[255]=i=>i.length==4?new Date((i[0]*16777216+(i[1]<<16)+(i[2]<<8)+i[3])*1e3):i.length==8?new Date(((i[0]<<22)+(i[1]<<14)+(i[2]<<6)+(i[3]>>2))/1e6+((i[3]&3)*4294967296+i[4]*16777216+(i[5]<<16)+(i[6]<<8)+i[7])*1e3):i.length==12?new Date(((i[0]<<24)+(i[1]<<16)+(i[2]<<8)+i[3])/1e6+((i[4]&128?-281474976710656:0)+i[6]*1099511627776+i[7]*4294967296+i[8]*16777216+(i[9]<<16)+(i[10]<<8)+i[11])*1e3):new Date("invalid");uc=new Array(147);for(let i=0;i<256;i++)uc[i]=+("1e"+Math.floor(45.15-i*.30103));vy=rr,yu=new rr({useRecords:!1}),Sy=yu.unpack,wy=yu.unpackMultiple,My=yu.unpack,dc={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4},Ay=new Float32Array(1),uy=new Uint8Array(Ay.buffer,0,4)});function Ry(i,e,t,n){let r=i.byteLength;if(r+1<256){var{target:s,position:a}=t(4+r);s[a++]=199,s[a++]=r+1}else if(r+1<65536){var{target:s,position:a}=t(5+r);s[a++]=200,s[a++]=r+1>>8,s[a++]=r+1&255}else{var{target:s,position:a,targetView:o}=t(7+r);s[a++]=201,o.setUint32(a,r+1),a+=4}s[a++]=116,s[a++]=e,i.buffer||(i=new Uint8Array(i)),s.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength),a)}function Cy(i,e){let t=i.byteLength;var n,r;if(t<256){var{target:n,position:r}=e(t+2);n[r++]=196,n[r++]=t}else if(t<65536){var{target:n,position:r}=e(t+3);n[r++]=197,n[r++]=t>>8,n[r++]=t&255}else{var{target:n,position:r,targetView:s}=e(t+5);n[r++]=198,s.setUint32(r,t),r+=4}n.set(i,r)}function qR(i,e,t,n){let r=i.length;switch(r){case 1:e[t++]=212;break;case 2:e[t++]=213;break;case 4:e[t++]=214;break;case 8:e[t++]=215;break;case 16:e[t++]=216;break;default:r<256?(e[t++]=199,e[t++]=r):r<65536?(e[t++]=200,e[t++]=r>>8,e[t++]=r&255):(e[t++]=201,e[t++]=r>>24,e[t++]=r>>16&255,e[t++]=r>>8&255,e[t++]=r&255)}return e[t++]=n,e.set(i,t),t+=r,t}function $R(i,e){let t,n=e.length*6,r=i.length-n;for(;t=e.pop();){let s=t.offset,a=t.id;i.copyWithin(s+n,s,r),n-=6;let o=s+n;i[o++]=214,i[o++]=105,i[o++]=a>>24,i[o++]=a>>16&255,i[o++]=a>>8&255,i[o++]=a&255,r=s}return i}function Iy(i,e,t){if(en.length>0){Vt.setUint32(en.position+i,K+t-en.position-i),en.stringsPosition=K-i;let n=en;en=null,e(n[0]),e(n[1])}}function Ly(i){if(i.Class){if(!i.pack&&!i.write)throw new Error("Extension has no pack or write function");if(i.pack&&!i.type)throw new Error("Extension has no type (numeric code to identify the extension)");Om.unshift(i.Class),wu.unshift(i)}yy(i)}function jR(i,e){return i.isCompatible=t=>{let n=!t||(e.lastNamedStructuresLength||0)===t.length;return n||e._mergeStructures(t),n},i}var Su,wu,Om,Mu,vu,Py,Ey,te,fc,Vt,K,qn,en,GR,VR,WR,Ua,vr,Dy,Ny,Oy,Fy,Uy,ky,By,zy,Fm,Um,km,Bm=un(()=>{Fa();Fa();Fa();try{Su=new TextEncoder}catch{}Mu=typeof Buffer<"u",vu=Mu?function(i){return Buffer.allocUnsafeSlow(i)}:Uint8Array,Py=Mu?Buffer:Uint8Array,Ey=Mu?4294967296:2144337920,K=0,en=null,VR=21760,WR=/[\u0080-\uFFFF]/,Ua=Symbol("record-id"),vr=class extends rr{constructor(e){super(e),this.offset=0;let t,n,r,s,a,o=Py.prototype.utf8Write?function(L,E){return te.utf8Write(L,E,te.byteLength-E)}:Su&&Su.encodeInto?function(L,E){return Su.encodeInto(L,te.subarray(E)).written}:!1,l=this;e||(e={});let c=e&&e.sequential,h=e.structures||e.saveStructures,d=e.maxSharedStructures;if(d==null&&(d=h?32:0),d>8160)throw new Error("Maximum maxSharedStructure is 8160");e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let f=e.maxOwnStructures;f==null&&(f=h?32:64),!this.structures&&e.useRecords!=!1&&(this.structures=[]);let p=d>32||f+d>64,x=d+64,y=d+f+64;if(y>8256)throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let b=[],g=0,S=0;this.pack=this.encode=function(L,E){if(te||(te=new vu(8192),Vt=te.dataView||(te.dataView=new DataView(te.buffer,0,8192)),K=0),qn=te.length-10,qn-K<2048?(te=new vu(te.length),Vt=te.dataView||(te.dataView=new DataView(te.buffer,0,te.length)),qn=te.length-10,K=0):K=K+7&2147483640,n=K,E&km&&(K+=E&255),a=l.structuredClone?new Map:null,l.bundleStrings&&typeof L!="string"?(en=[],en.size=1/0):en=null,s=l.structures,s){s.uninitialized&&(s=l._mergeStructures(l.getStructures()));let O=s.sharedLength||0;if(O>d)throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+s.sharedLength);if(!s.transitions){s.transitions=Object.create(null);for(let H=0;H<O;H++){let Y=s[H];if(!Y)continue;let le,fe=s.transitions;for(let be=0,Te=Y.length;be<Te;be++){let Je=Y[be];le=fe[Je],le||(le=fe[Je]=Object.create(null)),fe=le}fe[Ua]=H+64}this.lastNamedStructuresLength=O}c||(s.nextId=O+64)}r&&(r=!1);let D;try{l.randomAccessStructure&&L&&L.constructor&&L.constructor===Object?J(L):N(L);let O=en;if(en&&Iy(n,N,0),a&&a.idsToInsert){let H=a.idsToInsert.sort((be,Te)=>be.offset>Te.offset?1:-1),Y=H.length,le=-1;for(;O&&Y>0;){let be=H[--Y].offset+n;be<O.stringsPosition+n&&le===-1&&(le=0),be>O.position+n?le>=0&&(le+=6):(le>=0&&(Vt.setUint32(O.position+n,Vt.getUint32(O.position+n)+le),le=-1),O=O.previous,Y++)}le>=0&&O&&Vt.setUint32(O.position+n,Vt.getUint32(O.position+n)+le),K+=H.length*6,K>qn&&B(K),l.offset=K;let fe=$R(te.subarray(n,K),H);return a=null,fe}return l.offset=K,E&Fm?(te.start=n,te.end=K,te):te.subarray(n,K)}catch(O){throw D=O,O}finally{if(s&&(A(),r&&l.saveStructures)){let O=s.sharedLength||0,H=te.subarray(n,K),Y=jR(s,l);if(!D)return l.saveStructures(Y,Y.isCompatible)===!1?l.pack(L,E):(l.lastNamedStructuresLength=O,te.length>1073741824&&(te=null),H)}te.length>1073741824&&(te=null),E&Um&&(K=n)}};let A=()=>{S<10&&S++;let L=s.sharedLength||0;if(s.length>L&&!c&&(s.length=L),g>1e4)s.transitions=null,S=0,g=0,b.length>0&&(b=[]);else if(b.length>0&&!c){for(let E=0,D=b.length;E<D;E++)b[E][Ua]=0;b=[]}},T=L=>{var E=L.length;E<16?te[K++]=144|E:E<65536?(te[K++]=220,te[K++]=E>>8,te[K++]=E&255):(te[K++]=221,Vt.setUint32(K,E),K+=4);for(let D=0;D<E;D++)N(L[D])},N=L=>{K>qn&&(te=B(K));var E=typeof L,D;if(E==="string"){let O=L.length;if(en&&O>=4&&O<4096){if((en.size+=O)>VR){let fe,be=(en[0]?en[0].length*3+en[1].length:0)+10;K+be>qn&&(te=B(K+be));let Te;en.position?(Te=en,te[K]=200,K+=3,te[K++]=98,fe=K-n,K+=4,Iy(n,N,0),Vt.setUint16(fe+n-3,K-n-fe)):(te[K++]=214,te[K++]=98,fe=K-n,K+=4),en=["",""],en.previous=Te,en.size=0,en.position=fe}let le=WR.test(L);en[le?0:1]+=L,te[K++]=193,N(le?-O:O);return}let H;O<32?H=1:O<256?H=2:O<65536?H=3:H=5;let Y=O*3;if(K+Y>qn&&(te=B(K+Y)),O<64||!o){let le,fe,be,Te=K+H;for(le=0;le<O;le++)fe=L.charCodeAt(le),fe<128?te[Te++]=fe:fe<2048?(te[Te++]=fe>>6|192,te[Te++]=fe&63|128):(fe&64512)===55296&&((be=L.charCodeAt(le+1))&64512)===56320?(fe=65536+((fe&1023)<<10)+(be&1023),le++,te[Te++]=fe>>18|240,te[Te++]=fe>>12&63|128,te[Te++]=fe>>6&63|128,te[Te++]=fe&63|128):(te[Te++]=fe>>12|224,te[Te++]=fe>>6&63|128,te[Te++]=fe&63|128);D=Te-K-H}else D=o(L,K+H);D<32?te[K++]=160|D:D<256?(H<2&&te.copyWithin(K+2,K+1,K+1+D),te[K++]=217,te[K++]=D):D<65536?(H<3&&te.copyWithin(K+3,K+2,K+2+D),te[K++]=218,te[K++]=D>>8,te[K++]=D&255):(H<5&&te.copyWithin(K+5,K+3,K+3+D),te[K++]=219,Vt.setUint32(K,D),K+=4),K+=D}else if(E==="number")if(L>>>0===L)L<32||L<128&&this.useRecords===!1||L<64&&!this.randomAccessStructure?te[K++]=L:L<256?(te[K++]=204,te[K++]=L):L<65536?(te[K++]=205,te[K++]=L>>8,te[K++]=L&255):(te[K++]=206,Vt.setUint32(K,L),K+=4);else if(L>>0===L)L>=-32?te[K++]=256+L:L>=-128?(te[K++]=208,te[K++]=L+256):L>=-32768?(te[K++]=209,Vt.setInt16(K,L),K+=2):(te[K++]=210,Vt.setInt32(K,L),K+=4);else{let O;if((O=this.useFloat32)>0&&L<4294967296&&L>=-2147483648){te[K++]=202,Vt.setFloat32(K,L);let H;if(O<4||(H=L*uc[(te[K]&127)<<1|te[K+1]>>7])>>0===H){K+=4;return}else K--}te[K++]=203,Vt.setFloat64(K,L),K+=8}else if(E==="object"||E==="function")if(!L)te[K++]=192;else{if(a){let H=a.get(L);if(H){if(!H.id){let Y=a.idsToInsert||(a.idsToInsert=[]);H.id=Y.push(H)}te[K++]=214,te[K++]=112,Vt.setUint32(K,H.id),K+=4;return}else a.set(L,{offset:K-n})}let O=L.constructor;if(O===Object)I(L);else if(O===Array)T(L);else if(O===Map)if(this.mapAsEmptyObject)te[K++]=128;else{D=L.size,D<16?te[K++]=128|D:D<65536?(te[K++]=222,te[K++]=D>>8,te[K++]=D&255):(te[K++]=223,Vt.setUint32(K,D),K+=4);for(let[H,Y]of L)N(H),N(Y)}else{for(let H=0,Y=wu.length;H<Y;H++){let le=Om[H];if(L instanceof le){let fe=wu[H];if(fe.write){fe.type&&(te[K++]=212,te[K++]=fe.type,te[K++]=0);let oe=fe.write.call(this,L);oe===L?Array.isArray(L)?T(L):I(L):N(oe);return}let be=te,Te=Vt,Je=K;te=null;let ke;try{ke=fe.pack.call(this,L,oe=>(te=be,be=null,K+=oe,K>qn&&B(K),{target:te,targetView:Vt,position:K-oe}),N)}finally{be&&(te=be,Vt=Te,K=Je,qn=te.length-10)}ke&&(ke.length+K>qn&&B(ke.length+K),K=qR(ke,te,K,fe.type));return}}if(Array.isArray(L))T(L);else{if(L.toJSON){let H=L.toJSON();if(H!==L)return N(H)}if(E==="function")return N(this.writeFunction&&this.writeFunction(L));I(L)}}}else if(E==="boolean")te[K++]=L?195:194;else if(E==="bigint"){if(L<BigInt(1)<<BigInt(63)&&L>=-(BigInt(1)<<BigInt(63)))te[K++]=211,Vt.setBigInt64(K,L);else if(L<BigInt(1)<<BigInt(64)&&L>0)te[K++]=207,Vt.setBigUint64(K,L);else if(this.largeBigIntToFloat)te[K++]=203,Vt.setFloat64(K,Number(L));else{if(this.largeBigIntToString)return N(L.toString());if(this.useBigIntExtension&&L<BigInt(2)**BigInt(1023)&&L>-(BigInt(2)**BigInt(1023))){te[K++]=199,K++,te[K++]=66;let O=[],H;do{let Y=L&BigInt(255);H=(Y&BigInt(128))===(L<BigInt(0)?BigInt(128):BigInt(0)),O.push(Y),L>>=BigInt(8)}while(!((L===BigInt(0)||L===BigInt(-1))&&H));te[K-2]=O.length;for(let Y=O.length;Y>0;)te[K++]=Number(O[--Y]);return}else throw new RangeError(L+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string")}K+=8}else if(E==="undefined")this.encodeUndefinedAsNil?te[K++]=192:(te[K++]=212,te[K++]=0,te[K++]=0);else throw new Error("Unknown type: "+E)},P=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?L=>{let E;if(this.skipValues){E=[];for(let H in L)(typeof L.hasOwnProperty!="function"||L.hasOwnProperty(H))&&!this.skipValues.includes(L[H])&&E.push(H)}else E=Object.keys(L);let D=E.length;D<16?te[K++]=128|D:D<65536?(te[K++]=222,te[K++]=D>>8,te[K++]=D&255):(te[K++]=223,Vt.setUint32(K,D),K+=4);let O;if(this.coercibleKeyAsNumber)for(let H=0;H<D;H++){O=E[H];let Y=Number(O);N(isNaN(Y)?O:Y),N(L[O])}else for(let H=0;H<D;H++)N(O=E[H]),N(L[O])}:L=>{te[K++]=222;let E=K-n;K+=2;let D=0;for(let O in L)(typeof L.hasOwnProperty!="function"||L.hasOwnProperty(O))&&(N(O),N(L[O]),D++);if(D>65535)throw new Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');te[E+++n]=D>>8,te[E+n]=D&255},U=this.useRecords===!1?P:e.progressiveRecords&&!p?L=>{let E,D=s.transitions||(s.transitions=Object.create(null)),O=K++-n,H;for(let Y in L)if(typeof L.hasOwnProperty!="function"||L.hasOwnProperty(Y)){if(E=D[Y],E)D=E;else{let le=Object.keys(L),fe=D;D=s.transitions;let be=0;for(let Te=0,Je=le.length;Te<Je;Te++){let ke=le[Te];E=D[ke],E||(E=D[ke]=Object.create(null),be++),D=E}O+n+1==K?(K--,k(D,le,be)):V(D,le,O,be),H=!0,D=fe[Y]}N(L[Y])}if(!H){let Y=D[Ua];Y?te[O+n]=Y:V(D,Object.keys(L),O,0)}}:L=>{let E,D=s.transitions||(s.transitions=Object.create(null)),O=0;for(let Y in L)(typeof L.hasOwnProperty!="function"||L.hasOwnProperty(Y))&&(E=D[Y],E||(E=D[Y]=Object.create(null),O++),D=E);let H=D[Ua];H?H>=96&&p?(te[K++]=((H-=96)&31)+96,te[K++]=H>>5):te[K++]=H:k(D,D.__keys__||Object.keys(L),O);for(let Y in L)(typeof L.hasOwnProperty!="function"||L.hasOwnProperty(Y))&&N(L[Y])},v=typeof this.useRecords=="function"&&this.useRecords,I=v?L=>{v(L)?U(L):P(L)}:U,B=L=>{let E;if(L>16777216){if(L-n>Ey)throw new Error("Packed buffer would be larger than maximum buffer size");E=Math.min(Ey,Math.round(Math.max((L-n)*(L>67108864?1.25:2),4194304)/4096)*4096)}else E=(Math.max(L-n<<2,te.length-1)>>12)+1<<12;let D=new vu(E);return Vt=D.dataView||(D.dataView=new DataView(D.buffer,0,E)),L=Math.min(L,te.length),te.copy?te.copy(D,0,n,L):D.set(te.slice(n,L)),K-=n,n=0,qn=D.length-10,te=D},k=(L,E,D)=>{let O=s.nextId;O||(O=64),O<x&&this.shouldShareStructure&&!this.shouldShareStructure(E)?(O=s.nextOwnId,O<y||(O=x),s.nextOwnId=O+1):(O>=y&&(O=x),s.nextId=O+1);let H=E.highByte=O>=96&&p?O-96>>5:-1;L[Ua]=O,L.__keys__=E,s[O-64]=E,O<x?(E.isShared=!0,s.sharedLength=O-63,r=!0,H>=0?(te[K++]=(O&31)+96,te[K++]=H):te[K++]=O):(H>=0?(te[K++]=213,te[K++]=114,te[K++]=(O&31)+96,te[K++]=H):(te[K++]=212,te[K++]=114,te[K++]=O),D&&(g+=S*D),b.length>=f&&(b.shift()[Ua]=0),b.push(L),N(E))},V=(L,E,D,O)=>{let H=te,Y=K,le=qn,fe=n;te=fc,K=0,n=0,te||(fc=te=new vu(8192)),qn=te.length-10,k(L,E,O),fc=te;let be=K;if(te=H,K=Y,qn=le,n=fe,be>1){let Te=K+be-1;Te>qn&&B(Te);let Je=D+n;te.copyWithin(Je+be,Je+1,K),te.set(fc.slice(0,be),Je),K=Te}else te[D+n]=fc[0]},J=L=>{let E=GR(L,te,n,K,s,B,(D,O,H)=>{if(H)return r=!0;K=O;let Y=te;return N(D),A(),Y!==te?{position:K,targetView:Vt,target:te}:K},this);if(E===0)return I(L);K=E}}useBuffer(e){te=e,te.dataView||(te.dataView=new DataView(te.buffer,te.byteOffset,te.byteLength)),Vt=te.dataView,K=0}set position(e){K=e}get position(){return K}set buffer(e){te=e}get buffer(){return te}clearSharedData(){this.structures&&(this.structures=[]),this.typedStructs&&(this.typedStructs=[])}};Om=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,oc];wu=[{pack(i,e,t){let n=i.getTime()/1e3;if((this.useTimestamp32||i.getMilliseconds()===0)&&n>=0&&n<4294967296){let{target:r,targetView:s,position:a}=e(6);r[a++]=214,r[a++]=255,s.setUint32(a,n)}else if(n>0&&n<4294967296){let{target:r,targetView:s,position:a}=e(10);r[a++]=215,r[a++]=255,s.setUint32(a,i.getMilliseconds()*4e6+(n/1e3/4294967296>>0)),s.setUint32(a+4,n)}else if(isNaN(n)){if(this.onInvalidDate)return e(0),t(this.onInvalidDate());let{target:r,targetView:s,position:a}=e(3);r[a++]=212,r[a++]=255,r[a++]=255}else{let{target:r,targetView:s,position:a}=e(15);r[a++]=199,r[a++]=12,r[a++]=255,s.setUint32(a,i.getMilliseconds()*1e6),s.setBigInt64(a+4,BigInt(Math.floor(n)))}}},{pack(i,e,t){if(this.setAsEmptyObject)return e(0),t({});let n=Array.from(i),{target:r,position:s}=e(this.moreTypes?3:0);this.moreTypes&&(r[s++]=212,r[s++]=115,r[s++]=0),t(n)}},{pack(i,e,t){let{target:n,position:r}=e(this.moreTypes?3:0);this.moreTypes&&(n[r++]=212,n[r++]=101,n[r++]=0),t([i.name,i.message,i.cause])}},{pack(i,e,t){let{target:n,position:r}=e(this.moreTypes?3:0);this.moreTypes&&(n[r++]=212,n[r++]=120,n[r++]=0),t([i.source,i.flags])}},{pack(i,e){this.moreTypes?Ry(i,16,e):Cy(Mu?Buffer.from(i):new Uint8Array(i),e)}},{pack(i,e){let t=i.constructor;t!==Py&&this.moreTypes?Ry(i,Nm.indexOf(t.name),e):Cy(i,e)}},{pack(i,e){let{target:t,position:n}=e(1);t[n]=193}}];Dy=new vr({useRecords:!1}),Ny=Dy.pack,Oy=Dy.pack,Fy=vr,{NEVER:Uy,ALWAYS:ky,DECIMAL_ROUND:By,DECIMAL_FIT:zy}=dc,Fm=512,Um=1024,km=2048});function XR(i,e={}){if(!i||typeof i!="object")throw new Error("first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable");if(typeof i[Symbol.iterator]=="function")return KR(i,e);if(typeof i.then=="function"||typeof i[Symbol.asyncIterator]=="function")return YR(i,e);throw new Error("first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise")}function*KR(i,e){let t=new vr(e);for(let n of i)yield t.pack(n)}async function*YR(i,e){let t=new vr(e);for await(let n of i)yield t.pack(n)}function JR(i,e={}){if(!i||typeof i!="object")throw new Error("first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise");let t=new rr(e),n,r=s=>{let a;n&&(s=Buffer.concat([n,s]),n=void 0);try{a=t.unpackMultiple(s)}catch(o){if(o.incomplete)n=s.slice(o.lastPosition),a=o.values;else throw o}return a};if(typeof i[Symbol.iterator]=="function")return(function*(){for(let a of i)yield*r(a)})();if(typeof i[Symbol.asyncIterator]=="function")return(async function*(){for await(let a of i)yield*r(a)})()}var Hy,Gy,Vy=un(()=>{Bm();Fa();Hy=JR,Gy=XR});var Wy={};Ar(Wy,{ALWAYS:()=>ky,C1:()=>_u,DECIMAL_FIT:()=>zy,DECIMAL_ROUND:()=>By,Decoder:()=>vy,Encoder:()=>Fy,FLOAT32_OPTIONS:()=>dc,NEVER:()=>Uy,Packr:()=>vr,RESERVE_START_SPACE:()=>km,RESET_BUFFER_MODE:()=>Um,REUSE_BUFFER_MODE:()=>Fm,Unpackr:()=>rr,addExtension:()=>Ly,clearSource:()=>lc,decode:()=>My,decodeIter:()=>Hy,encode:()=>Oy,encodeIter:()=>Gy,isNativeAccelerationEnabled:()=>my,mapsAsObjects:()=>QR,pack:()=>Ny,roundFloat32:()=>Ty,unpack:()=>Sy,unpackMultiple:()=>wy,useRecords:()=>ZR});var ZR,QR,qy=un(()=>{Bm();Fa();Vy();ZR=!1,QR=!0});var Hm=dn(Ky=>{"use strict";var eC=Y_(),wi=_m(),$y=vm(),tC=Sm(),Au=Q_(),Fn=ac(),nC=Tm(),jy=sc(),Xy=(qy(),Gs(Wy)),zm=class i{constructor(e,t){this.onStateChange=Au.createSignal(),this.onError=Au.createSignal(),this.onLeave=Au.createSignal(),this.onJoin=Au.createSignal(),this.hasJoined=!1,this.onMessageHandlers=tC.createNanoEvents(),this.roomId=null,this.name=e,this.packr=new Xy.Packr,this.packr.encode(void 0),t&&(this.serializer=new($y.getSerializer("schema")),this.rootSchema=t,this.serializer.state=new t),this.onError((n,r)=>{var s;return(s=console.warn)===null||s===void 0?void 0:s.call(console,`colyseus.js - onError => (${n}) ${r}`)}),this.onLeave(()=>this.removeAllListeners())}connect(e,t,n=this,r,s){let a=new eC.Connection(r.protocol);if(n.connection=a,a.events.onmessage=i.prototype.onMessageCallback.bind(n),a.events.onclose=function(o){var l;if(!n.hasJoined){(l=console.warn)===null||l===void 0||l.call(console,`Room connection was closed unexpectedly (${o.code}): ${o.reason}`),n.onError.invoke(o.code,o.reason);return}o.code===jy.CloseCode.DEVMODE_RESTART&&t?t():(n.onLeave.invoke(o.code,o.reason),n.destroy())},a.events.onerror=function(o){var l;(l=console.warn)===null||l===void 0||l.call(console,`Room, onError (${o.code}): ${o.reason}`),n.onError.invoke(o.code,o.reason)},r.protocol==="h3"){let o=new URL(e);a.connect(o.origin,r)}else a.connect(e,s)}leave(e=!0){return new Promise(t=>{this.onLeave(n=>t(n)),this.connection?e?(this.packr.buffer[0]=wi.Protocol.LEAVE_ROOM,this.connection.send(this.packr.buffer.subarray(0,1))):this.connection.close():this.onLeave.invoke(jy.CloseCode.CONSENTED)})}onMessage(e,t){return this.onMessageHandlers.on(this.getMessageHandlerKey(e),t)}send(e,t){let n={offset:1};this.packr.buffer[0]=wi.Protocol.ROOM_DATA,typeof e=="string"?Fn.encode.string(this.packr.buffer,e,n):Fn.encode.number(this.packr.buffer,e,n),this.packr.position=0;let r=t!==void 0?this.packr.pack(t,2048+n.offset):this.packr.buffer.subarray(0,n.offset);this.connection.send(r)}sendUnreliable(e,t){let n={offset:1};this.packr.buffer[0]=wi.Protocol.ROOM_DATA,typeof e=="string"?Fn.encode.string(this.packr.buffer,e,n):Fn.encode.number(this.packr.buffer,e,n),this.packr.position=0;let r=t!==void 0?this.packr.pack(t,2048+n.offset):this.packr.buffer.subarray(0,n.offset);this.connection.sendUnreliable(r)}sendBytes(e,t){let n={offset:1};if(this.packr.buffer[0]=wi.Protocol.ROOM_DATA_BYTES,typeof e=="string"?Fn.encode.string(this.packr.buffer,e,n):Fn.encode.number(this.packr.buffer,e,n),t.byteLength+n.offset>this.packr.buffer.byteLength){let r=new Uint8Array(n.offset+t.byteLength);r.set(this.packr.buffer),this.packr.useBuffer(r)}this.packr.buffer.set(t,n.offset),this.connection.send(this.packr.buffer.subarray(0,n.offset+t.byteLength))}get state(){return this.serializer.getState()}removeAllListeners(){this.onJoin.clear(),this.onStateChange.clear(),this.onError.clear(),this.onLeave.clear(),this.onMessageHandlers.events={},this.serializer instanceof nC.SchemaSerializer&&(this.serializer.decoder.root.callbacks={})}onMessageCallback(e){let t=new Uint8Array(e.data),n={offset:1},r=t[0];if(r===wi.Protocol.JOIN_ROOM){let s=Fn.decode.utf8Read(t,n,t[n.offset++]);if(this.serializerId=Fn.decode.utf8Read(t,n,t[n.offset++]),!this.serializer){let a=$y.getSerializer(this.serializerId);this.serializer=new a}t.byteLength>n.offset&&this.serializer.handshake&&this.serializer.handshake(t,n),this.reconnectionToken=`${this.roomId}:${s}`,this.hasJoined=!0,this.onJoin.invoke(),this.packr.buffer[0]=wi.Protocol.JOIN_ROOM,this.connection.send(this.packr.buffer.subarray(0,1))}else if(r===wi.Protocol.ERROR){let s=Fn.decode.number(t,n),a=Fn.decode.string(t,n);this.onError.invoke(s,a)}else if(r===wi.Protocol.LEAVE_ROOM)this.leave();else if(r===wi.Protocol.ROOM_STATE)this.serializer.setState(t,n),this.onStateChange.invoke(this.serializer.getState());else if(r===wi.Protocol.ROOM_STATE_PATCH)this.serializer.patch(t,n),this.onStateChange.invoke(this.serializer.getState());else if(r===wi.Protocol.ROOM_DATA){let s=Fn.decode.stringCheck(t,n)?Fn.decode.string(t,n):Fn.decode.number(t,n),a=t.byteLength>n.offset?Xy.unpack(t,{start:n.offset}):void 0;this.dispatchMessage(s,a)}else if(r===wi.Protocol.ROOM_DATA_BYTES){let s=Fn.decode.stringCheck(t,n)?Fn.decode.string(t,n):Fn.decode.number(t,n);this.dispatchMessage(s,t.subarray(n.offset))}}dispatchMessage(e,t){var n;let r=this.getMessageHandlerKey(e);this.onMessageHandlers.events[r]?this.onMessageHandlers.emit(r,t):this.onMessageHandlers.events["*"]?this.onMessageHandlers.emit("*",e,t):(n=console.warn)===null||n===void 0||n.call(console,`colyseus.js: onMessage() not registered for type '${e}'.`)}destroy(){this.serializer&&this.serializer.teardown()}getMessageHandlerKey(e){switch(typeof e){case"string":return e;case"number":return`i${e}`;default:throw new Error("invalid message type.")}}};Ky.Room=zm});var Jy={};Ar(Jy,{del:()=>aC,get:()=>iC,patch:()=>sC,post:()=>rC,put:()=>oC,send:()=>Ui});function Yy(i,e){e.headers=i.headers||{},e.statusMessage=i.statusText,e.statusCode=i.status,e.data=i.response}function Ui(i,e,t){return new Promise(function(n,r){t=t||{};var s=new XMLHttpRequest,a,o,l,c=t.body,h=t.headers||{};t.timeout&&(s.timeout=t.timeout),s.ontimeout=s.onerror=function(d){d.timeout=d.type=="timeout",r(d)},s.onabort=function(d){d.aborted=!0,r(d)},s.open(i,e.href||e),s.onload=function(){for(l=s.getAllResponseHeaders().trim().split(/[\r\n]+/),Yy(s,s);o=l.shift();)o=o.split(": "),s.headers[o.shift().toLowerCase()]=o.join(": ");if(o=s.headers["content-type"],o&&~o.indexOf("application/json"))try{s.data=JSON.parse(s.data,t.reviver)}catch(d){return Yy(s,d),r(d)}(s.status>=400?r:n)(s)},typeof FormData<"u"&&c instanceof FormData||c&&typeof c=="object"&&(h["content-type"]="application/json",c=JSON.stringify(c)),s.withCredentials=!!t.withCredentials;for(a in h)s.setRequestHeader(a,h[a]);s.send(c),t.signal&&t.signal.addEventListener("abort",function(){s.abort()})})}var iC,rC,sC,aC,oC,Zy=un(()=>{iC=Ui.bind(Ui,"GET"),rC=Ui.bind(Ui,"POST"),sC=Ui.bind(Ui,"PATCH"),aC=Ui.bind(Ui,"DELETE"),oC=Ui.bind(Ui,"PUT")});var tv=dn(ev=>{"use strict";var Qy=sc(),cC=(Zy(),Gs(Jy));function lC(i){var e=Object.create(null);return i&&Object.keys(i).forEach(function(t){if(t!=="default"){var n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:function(){return i[t]}})}}),e.default=i,Object.freeze(e)}var hC=lC(cC),Gm=class{constructor(e,t={}){this.client=e,this.headers=t}get(e,t={}){return this.request("get",e,t)}post(e,t={}){return this.request("post",e,t)}del(e,t={}){return this.request("del",e,t)}put(e,t={}){return this.request("put",e,t)}request(e,t,n={}){return hC[e](this.client.getHttpEndpoint(t),this.getOptions(n)).catch(r=>{var s;if(r.aborted)throw new Qy.AbortError("Request aborted");let a=r.statusCode,o=((s=r.data)===null||s===void 0?void 0:s.error)||r.statusMessage||r.message;throw!a&&!o?r:new Qy.ServerError(a,o)})}getOptions(e){return e.headers=Object.assign({},this.headers,e.headers),this.authToken&&(e.headers.Authorization=`Bearer ${this.authToken}`),typeof cc<"u"&&cc.sys&&cc.sys.isNative||(e.withCredentials=!0),e}};ev.HTTP=Gm});var iv=dn(Tu=>{"use strict";var nv=(rc(),Gs(ic)),zs;function Wm(){if(!zs)try{zs=typeof cc<"u"&&cc.sys&&cc.sys.localStorage?cc.sys.localStorage:window.localStorage}catch{}return!zs&&typeof globalThis.indexedDB<"u"&&(zs=new Vm),zs||(zs={cache:{},setItem:function(i,e){this.cache[i]=e},getItem:function(i){this.cache[i]},removeItem:function(i){delete this.cache[i]}}),zs}function uC(i,e){Wm().setItem(i,e)}function dC(i){Wm().removeItem(i)}function fC(i,e){let t=Wm().getItem(i);typeof Promise>"u"||!(t instanceof Promise)?e(t):t.then(n=>e(n))}var Vm=class{constructor(){this.dbPromise=new Promise(e=>{let t=indexedDB.open("_colyseus_storage",1);t.onupgradeneeded=()=>t.result.createObjectStore("store"),t.onsuccess=()=>e(t.result)})}tx(e,t){return nv.__awaiter(this,void 0,void 0,function*(){let r=(yield this.dbPromise).transaction("store",e).objectStore("store");return t(r)})}setItem(e,t){return this.tx("readwrite",n=>n.put(t,e)).then()}getItem(e){return nv.__awaiter(this,void 0,void 0,function*(){let t=yield this.tx("readonly",n=>n.get(e));return new Promise(n=>{t.onsuccess=()=>n(t.result)})})}removeItem(e){return this.tx("readwrite",t=>t.delete(e)).then()}};Tu.getItem=fC;Tu.removeItem=dC;Tu.setItem=uC});var Xm=dn(rv=>{"use strict";var Mn=(rc(),Gs(ic)),qm=iv(),pC=Sm(),Eu,$m,es,Ru,jm=class{constructor(e){this.http=e,this.settings={path:"/auth",key:"colyseus-auth-token"},Eu.set(this,!1),$m.set(this,void 0),es.set(this,void 0),Ru.set(this,pC.createNanoEvents()),qm.getItem(this.settings.key,t=>this.token=t)}set token(e){this.http.authToken=e}get token(){return this.http.authToken}onChange(e){let t=Mn.__classPrivateFieldGet(this,Ru,"f").on("change",e);return Mn.__classPrivateFieldGet(this,Eu,"f")||Mn.__classPrivateFieldSet(this,$m,new Promise((n,r)=>{this.getUserData().then(s=>{this.emitChange(Object.assign(Object.assign({},s),{token:this.token}))}).catch(s=>{this.emitChange({user:null,token:void 0})}).finally(()=>{n()})}),"f"),Mn.__classPrivateFieldSet(this,Eu,!0,"f"),t}getUserData(){return Mn.__awaiter(this,void 0,void 0,function*(){if(this.token)return(yield this.http.get(`${this.settings.path}/userdata`)).data;throw new Error("missing auth.token")})}registerWithEmailAndPassword(e,t,n){return Mn.__awaiter(this,void 0,void 0,function*(){let r=(yield this.http.post(`${this.settings.path}/register`,{body:{email:e,password:t,options:n}})).data;return this.emitChange(r),r})}signInWithEmailAndPassword(e,t){return Mn.__awaiter(this,void 0,void 0,function*(){let n=(yield this.http.post(`${this.settings.path}/login`,{body:{email:e,password:t}})).data;return this.emitChange(n),n})}signInAnonymously(e){return Mn.__awaiter(this,void 0,void 0,function*(){let t=(yield this.http.post(`${this.settings.path}/anonymous`,{body:{options:e}})).data;return this.emitChange(t),t})}sendPasswordResetEmail(e){return Mn.__awaiter(this,void 0,void 0,function*(){return(yield this.http.post(`${this.settings.path}/forgot-password`,{body:{email:e}})).data})}signInWithProvider(e){return Mn.__awaiter(this,arguments,void 0,function*(t,n={}){return new Promise((r,s)=>{let a=n.width||480,o=n.height||768,l=this.token?`?token=${this.token}`:"",c=`Login with ${t[0].toUpperCase()+t.substring(1)}`,h=this.http.client.getHttpEndpoint(`${n.prefix||`${this.settings.path}/provider`}/${t}${l}`),d=screen.width/2-a/2,f=screen.height/2-o/2;Mn.__classPrivateFieldSet(this,es,window.open(h,c,"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width="+a+", height="+o+", top="+f+", left="+d),"f");let p=y=>{y.data.user===void 0&&y.data.token===void 0||(clearInterval(x),Mn.__classPrivateFieldGet(this,es,"f").close(),Mn.__classPrivateFieldSet(this,es,void 0,"f"),window.removeEventListener("message",p),y.data.error!==void 0?s(y.data.error):(r(y.data),this.emitChange(y.data)))},x=setInterval(()=>{(!Mn.__classPrivateFieldGet(this,es,"f")||Mn.__classPrivateFieldGet(this,es,"f").closed)&&(Mn.__classPrivateFieldSet(this,es,void 0,"f"),s("cancelled"),window.removeEventListener("message",p))},200);window.addEventListener("message",p)})})}signOut(){return Mn.__awaiter(this,void 0,void 0,function*(){this.emitChange({user:null,token:null})})}emitChange(e){e.token!==void 0&&(this.token=e.token,e.token===null?qm.removeItem(this.settings.key):qm.setItem(this.settings.key,e.token)),Mn.__classPrivateFieldGet(this,Ru,"f").emit("change",e)}};Eu=new WeakMap,$m=new WeakMap,es=new WeakMap,Ru=new WeakMap;rv.Auth=jm});var av=dn(sv=>{"use strict";function mC(i){var e;let t=((e=window?.location)===null||e===void 0?void 0:e.hostname)||"localhost",n=i.hostname.split("."),r=!i.hostname.includes("trycloudflare.com")&&!i.hostname.includes("discordsays.com")&&n.length>2?`/${n[0]}`:"";return i.pathname.startsWith("/.proxy")?`${i.protocol}//${t}${r}${i.pathname}${i.search}`:`${i.protocol}//${t}/.proxy/colyseus${r}${i.pathname}${i.search}`}sv.discordURLBuilder=mC});var cv=dn(Ym=>{"use strict";var Sr=(rc(),Gs(ic)),gC=sc(),bC=Hm(),xC=tv(),_C=Xm(),yC=av(),Km,Cu=class i extends Error{constructor(e,t){super(e),this.code=t,this.name="MatchMakeError",Object.setPrototypeOf(this,i.prototype)}},ov=typeof window<"u"&&typeof((Km=window?.location)===null||Km===void 0?void 0:Km.hostname)<"u"?`${window.location.protocol.replace("http","ws")}//${window.location.hostname}${window.location.port&&`:${window.location.port}`}`:"ws://127.0.0.1:2567",Iu=class{constructor(e=ov,t){var n,r;if(typeof e=="string"){let s=e.startsWith("/")?new URL(e,ov):new URL(e),a=s.protocol==="https:"||s.protocol==="wss:",o=Number(s.port||(a?443:80));this.settings={hostname:s.hostname,pathname:s.pathname,port:o,secure:a,searchParams:s.searchParams.toString()||void 0}}else e.port===void 0&&(e.port=e.secure?443:80),e.pathname===void 0&&(e.pathname=""),this.settings=e;this.settings.pathname.endsWith("/")&&(this.settings.pathname=this.settings.pathname.slice(0,-1)),this.http=new xC.HTTP(this,t?.headers||{}),this.auth=new _C.Auth(this.http),this.urlBuilder=t?.urlBuilder,!this.urlBuilder&&typeof window<"u"&&(!((r=(n=window?.location)===null||n===void 0?void 0:n.hostname)===null||r===void 0)&&r.includes("discordsays.com"))&&(this.urlBuilder=yC.discordURLBuilder,console.log("Colyseus SDK: Discord Embedded SDK detected. Using custom URL builder."))}joinOrCreate(e){return Sr.__awaiter(this,arguments,void 0,function*(t,n={},r){return yield this.createMatchMakeRequest("joinOrCreate",t,n,r)})}create(e){return Sr.__awaiter(this,arguments,void 0,function*(t,n={},r){return yield this.createMatchMakeRequest("create",t,n,r)})}join(e){return Sr.__awaiter(this,arguments,void 0,function*(t,n={},r){return yield this.createMatchMakeRequest("join",t,n,r)})}joinById(e){return Sr.__awaiter(this,arguments,void 0,function*(t,n={},r){return yield this.createMatchMakeRequest("joinById",t,n,r)})}reconnect(e,t){return Sr.__awaiter(this,void 0,void 0,function*(){if(typeof e=="string"&&typeof t=="string")throw new Error("DEPRECATED: .reconnect() now only accepts 'reconnectionToken' as argument.\nYou can get this token from previously connected `room.reconnectionToken`");let[n,r]=e.split(":");if(!n||!r)throw new Error(`Invalid reconnection token format.
+The format should be roomId:reconnectionToken`);return yield this.createMatchMakeRequest("reconnect",n,{reconnectionToken:r},t)})}consumeSeatReservation(e,t,n){return Sr.__awaiter(this,void 0,void 0,function*(){let r=this.createRoom(e.room.name,t);r.roomId=e.room.roomId,r.sessionId=e.sessionId;let s={sessionId:r.sessionId};e.reconnectionToken&&(s.reconnectionToken=e.reconnectionToken);let a=n||r;return r.connect(this.buildEndpoint(e.room,s,e.protocol),e.devMode&&(()=>Sr.__awaiter(this,void 0,void 0,function*(){console.info(`[Colyseus devMode]: ${String.fromCodePoint(128260)} Re-establishing connection with room id '${r.roomId}'...`);let o=0,l=8,c=()=>Sr.__awaiter(this,void 0,void 0,function*(){o++;try{yield this.consumeSeatReservation(e,t,a),console.info(`[Colyseus devMode]: ${String.fromCodePoint(9989)} Successfully re-established connection with room '${r.roomId}'`)}catch{o<l?(console.info(`[Colyseus devMode]: ${String.fromCodePoint(128260)} retrying... (${o} out of ${l})`),setTimeout(c,2e3)):console.info(`[Colyseus devMode]: ${String.fromCodePoint(10060)} Failed to reconnect. Is your server running? Please check server logs.`)}});setTimeout(c,2e3)})),a,e,this.http.headers),new Promise((o,l)=>{let c=(h,d)=>l(new gC.ServerError(h,d));a.onError.once(c),a.onJoin.once(()=>{a.onError.remove(c),o(a)})})})}createMatchMakeRequest(e,t){return Sr.__awaiter(this,arguments,void 0,function*(n,r,s={},a,o){let l=(yield this.http.post(`matchmake/${n}/${r}`,{headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)})).data;if(l.error)throw new Cu(l.error,l.code);return n==="reconnect"&&(l.reconnectionToken=s.reconnectionToken),yield this.consumeSeatReservation(l,a,o)})}createRoom(e,t){return new bC.Room(e,t)}buildEndpoint(e,t={},n="ws"){let r=this.settings.searchParams||"";this.http.authToken&&(t._authToken=this.http.authToken);for(let o in t)t.hasOwnProperty(o)&&(r+=(r?"&":"")+`${o}=${t[o]}`);n==="h3"&&(n="http");let s=this.settings.secure?`${n}s://`:`${n}://`;e.publicAddress?s+=`${e.publicAddress}`:s+=`${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}`;let a=`${s}/${e.processId}/${e.roomId}?${r}`;return this.urlBuilder?this.urlBuilder(new URL(a)):a}getHttpEndpoint(e=""){let t=e.startsWith("/")?e:`/${e}`,n=`${this.settings.secure?"https":"http"}://${this.settings.hostname}${this.getEndpointPort()}${this.settings.pathname}${t}`;return this.settings.searchParams&&(n+=`?${this.settings.searchParams}`),this.urlBuilder?this.urlBuilder(new URL(n)):n}getEndpointPort(){return this.settings.port!==80&&this.settings.port!==443?`:${this.settings.port}`:""}};Iu.VERSION="0.16.22";Ym.Client=Iu;Ym.MatchMakeError=Cu});var hv=dn(lv=>{"use strict";var Jm=class{setState(e){}getState(){return null}patch(e){}teardown(){}handshake(e){}};lv.NoneSerializer=Jm});var fv=dn(ki=>{"use strict";f_();var uv=cv(),dv=_m(),vC=Hm(),SC=Xm(),wC=sc(),Zm=Tm(),MC=hv(),Qm=vm();Qm.registerSerializer("schema",Zm.SchemaSerializer);Qm.registerSerializer("none",MC.NoneSerializer);ki.Client=uv.Client;ki.MatchMakeError=uv.MatchMakeError;Object.defineProperty(ki,"ErrorCode",{enumerable:!0,get:function(){return dv.ErrorCode}});Object.defineProperty(ki,"Protocol",{enumerable:!0,get:function(){return dv.Protocol}});ki.Room=vC.Room;ki.Auth=SC.Auth;ki.ServerError=wC.ServerError;ki.SchemaSerializer=Zm.SchemaSerializer;ki.getStateCallbacks=Zm.getStateCallbacks;ki.registerSerializer=Qm.registerSerializer});var pv={};Ar(pv,{StudioModel:()=>pc,StudioState:()=>Pu,StudioViewer:()=>mc});var Bi,pc,mc,Pu,mv=un(()=>{Bi=og(ac(),1),pc=class extends Bi.Schema{constructor(){super(),this.id="",this.src="",this.title="",this.relEast=0,this.relNorth=0,this.yawDeg=0,this.scale=1,this.height=0,this.ownerId="",this.ts=0}};(0,Bi.defineTypes)(pc,{id:"string",src:"string",title:"string",relEast:"float32",relNorth:"float32",yawDeg:"float32",scale:"float32",height:"float32",ownerId:"string",ts:"float64"});mc=class extends Bi.Schema{constructor(){super(),this.id="",this.name="",this.ownerId="",this.tsServer=0}};(0,Bi.defineTypes)(mc,{id:"string",name:"string",ownerId:"string",tsServer:"float64"});Pu=class extends Bi.Schema{constructor(){super(),this.roomKey="",this.models=new Bi.MapSchema,this.viewers=new Bi.MapSchema}};(0,Bi.defineTypes)(Pu,{roomKey:"string",models:{map:pc},viewers:{map:mc}})});Vn();wh();var En={origin:"https://three.ws",objectsManifest:"https://three.ws/cdn/objects/library/manifest.json",studioMcp:"https://three.ws/api/mcp-studio",animationManifest:"https://three.ws/animations/manifest.json",hdri:{studio:"https://three.ws/hdri/studio.hdr",outdoor:"https://three.ws/hdri/outdoor.hdr",sunset:"https://three.ws/hdri/sunset.hdr"},arLaunch:"https://three.ws/api/ar",roomServer:"wss://three-ws-multiplayer-93741856042.us-central1.run.app"},lb={assets:"three.ws",allowUrlOverride:!0,generate:{enabled:!0,endpoint:En.studioMcp,kind:"model",tier:"standard",timeoutMs:3e5,pollMs:3e3},rooms:{enabled:!0,server:En.roomServer},animations:{enabled:!0,manifestUrl:En.animationManifest,clip:"idle"},lighting:{preset:"studio",urls:En.hdri},arLaunchUrl:En.arLaunch,branding:{title:"AR Studio",backHref:null,backLabel:"Back",accent:"#8b7cf8"},shareBaseUrl:"",persistKey:"ar-studio:scene:v1",maxPlacements:20,persist:!0,onEvent:null};function mf(i){return!!i&&typeof i=="object"&&!Array.isArray(i)}function gf(i,e){if(!mf(e))return i;let t={...i};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=mf(r)&&mf(i?.[n])?gf(i[n],r):r);return t}function er(i){let e=String(i??"").trim();if(!e)return null;if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let t=new URL(e);return t.protocol==="https:"?t.href:null}catch{return null}}function bf(i={},e){let t=gf(lb,i),n=e instanceof URLSearchParams?e:new URLSearchParams(typeof e=="string"?e:typeof location<"u"?location.search:""),r=[],s="",a="";if(t.allowUrlOverride){let o=n.get("assets")||n.get("source"),l=o?er(o):null;l&&(t.assets=l);let c=n.getAll("src"),h=n.getAll("title");for(let d=0;d<c.length&&r.length<t.maxPlacements;d++){let f=er(c[d]);f&&r.push({src:f,title:String(h[d]||"").slice(0,120)})}s=String(n.get("room")||"").trim(),a=String(n.get("forge")||n.get("prompt")||"").trim()}return!t.shareBaseUrl&&typeof location<"u"&&(t.shareBaseUrl=`${location.origin}${location.pathname}`),{...t,urlModels:r,urlRoom:s,urlPrompt:a}}var mT=()=>{};function gT(){if(typeof window>"u")return!1;try{let i=new URLSearchParams(window.location.search);return i.has("ar-debug")&&i.get("ar-debug")!=="0"?!0:window.localStorage?.getItem("ar-studio:debug")==="1"}catch{return!1}}var Ps=gT(),Is=i=>typeof console<"u"&&typeof console[i]=="function"?console[i].bind(console):mT;function bT(i){Ps=!!i}function xT(){return Ps}var Mh=i=>(...e)=>{Ps&&Is(i)(...e)},ei={error:(...i)=>Is("error")(...i),warn:Mh("warn"),info:Mh("info"),debug:Mh("debug"),log:Mh("log")};function Ls(i){let e=`[${i}]`;return{error:(...t)=>Is("error")(e,...t),warn:(...t)=>{Ps&&Is("warn")(e,...t)},info:(...t)=>{Ps&&Is("info")(e,...t)},debug:(...t)=>{Ps&&Is("debug")(e,...t)},log:(...t)=>{Ps&&Is("log")(e,...t)}}}var hb=[[7,10,15,20,26,18,20,24,30,18]],ub=[[1,1,1,1,1,2,2,2,2,4]];function _T(i){return i*4+17}function db(i){let e=fb(i)>>>3,t=ub[0][i-1],n=hb[0][i-1];return e-n*t}function fb(i){let e=(16*i+128)*i+64;if(i>=2){let t=Math.floor(i/7)+2;e-=(25*t-10)*t-55,i>=7&&(e-=36)}return e}function yT(i){let e=new Uint8Array(i);e[i-1]=1;let t=1;for(let n=0;n<i;n++){for(let r=0;r<i;r++)e[r]=xf(e[r],t),r+1<i&&(e[r]^=e[r+1]);t=xf(t,2)}return e}function xf(i,e){let t=0;for(let n=7;n>=0;n--)t=t<<1^(t>>>7)*285,t^=(e>>>n&1)*i;return t&255}function vT(i,e){let t=new Uint8Array(e.length);for(let n of i){let r=n^t[0];t.copyWithin(0,1),t[t.length-1]=0;for(let s=0;s<t.length;s++)t[s]^=xf(e[s],r)}return t}function ST(i){for(let e=1;e<=10;e++){let t=db(e)*8;if(4+(e<10?8:16)+i*8<=t)return e}throw new Error("QR payload too large (>10 versions)")}function _f(i){let e=new TextEncoder().encode(i),t=ST(e.length),n=_T(t),r=t<10?8:16,s=[],a=(E,D)=>{for(let O=D-1;O>=0;O--)s.push(E>>>O&1)};a(4,4),a(e.length,r);for(let E of e)a(E,8);let o=db(t),l=o*8;for(let E=0;E<4&&s.length<l;E++)s.push(0);for(;s.length%8!==0;)s.push(0);let c=[236,17],h=0;for(;s.length<l;)a(c[h%2],8),h++;let d=new Uint8Array(o);for(let E=0;E<o;E++){let D=0;for(let O=0;O<8;O++)D=D<<1|s[E*8+O];d[E]=D}let f=ub[0][t-1],p=hb[0][t-1],x=fb(t)>>>3,y=Math.floor(x/f),b=f-x%f,g=[],S=yT(p),A=0;for(let E=0;E<f;E++){let D=y-p+(E<b?0:1),O=d.slice(A,A+D);A+=D;let H=vT(O,S);g.push({dat:O,ec:H})}let T=[];for(let E=0;E<y-p+1;E++)for(let D of g)E<D.dat.length&&T.push(D.dat[E]);for(let E=0;E<p;E++)for(let D of g)T.push(D.ec[E]);let N=Array.from({length:n},()=>new Array(n).fill(!1)),P=Array.from({length:n},()=>new Array(n).fill(!1)),U=(E,D,O)=>{N[D][E]=O,P[D][E]=!0},v=(E,D)=>{for(let O=-4;O<=4;O++)for(let H=-4;H<=4;H++){let Y=E+H,le=D+O;if(Y<0||Y>=n||le<0||le>=n)continue;let fe=Math.max(Math.abs(H),Math.abs(O));U(Y,le,fe!==2&&fe!==4)}};v(3,3),v(n-4,3),v(3,n-4);for(let E=0;E<n;E++)P[6][E]||U(E,6,E%2===0),P[E][6]||U(6,E,E%2===0);let B=(E=>{if(E===1)return[];let D=Math.floor(E/7)+2,O=E===32?26:Math.ceil((E*4+4)/(D*2-2))*2,H=[6];for(let Y=n-7;H.length<D;Y-=O)H.splice(1,0,Y);return H})(t);for(let E of B)for(let D of B)if(!(E===6&&D===6||E===6&&D===n-7||E===n-7&&D===6))for(let O=-2;O<=2;O++)for(let H=-2;H<=2;H++){let Y=Math.max(Math.abs(H),Math.abs(O));U(E+H,D+O,Y!==1)}for(let E=0;E<9;E++)U(8,E,!1);for(let E=0;E<8;E++)U(E,8,!1);for(let E=0;E<8;E++)U(n-1-E,8,!1);for(let E=0;E<7;E++)U(8,n-1-E,!1);if(U(8,n-8,!0),t>=7){let E=t;for(let O=0;O<12;O++)E=E<<1^(E>>>11)*7973;let D=(t<<12|E)>>>0;for(let O=0;O<18;O++){let H=(D>>>O&1)===1,Y=n-11+O%3,le=Math.floor(O/3);U(Y,le,H),U(le,Y,H)}}let k=0,V=E=>(T[E>>>3]>>>7-(E&7)&1)===1;for(let E=n-1;E>=1;E-=2){E===6&&(E=5);for(let D=0;D<n;D++)for(let O=0;O<2;O++){let H=E-O,le=(E+1&2)===0?n-1-D:D;!P[le][H]&&k<T.length*8&&(N[le][H]=V(k),k++)}}let J=1/0,L=null;for(let E=0;E<8;E++){let D=N.map(H=>H.slice());MT(D,P,E),AT(D,E);let O=ET(D);O<J&&(J=O,L=D)}return{size:n,modules:L}}function wT(i,e,t){switch(i){case 0:return(e+t)%2===0;case 1:return t%2===0;case 2:return e%3===0;case 3:return(e+t)%3===0;case 4:return(Math.floor(e/3)+Math.floor(t/2))%2===0;case 5:return e*t%2+e*t%3===0;case 6:return(e*t%2+e*t%3)%2===0;case 7:return((e+t)%2+e*t%3)%2===0}return!1}function MT(i,e,t){let n=i.length;for(let r=0;r<n;r++)for(let s=0;s<n;s++)!e[r][s]&&wT(t,s,r)&&(i[r][s]=!i[r][s])}function AT(i,e){let t=i.length,n=TT[0]<<3|e,r=n;for(let o=0;o<10;o++)r=r<<1^(r>>>9)*1335;let s=((n<<10|r)^21522)>>>0,a=(o,l,c)=>{i[l][o]=c};for(let o=0;o<=5;o++)a(8,o,(s>>>o&1)===1);a(8,7,(s>>>6&1)===1),a(8,8,(s>>>7&1)===1),a(7,8,(s>>>8&1)===1);for(let o=9;o<15;o++)a(14-o,8,(s>>>o&1)===1);for(let o=0;o<8;o++)a(t-1-o,8,(s>>>o&1)===1);for(let o=8;o<15;o++)a(8,t-15+o,(s>>>o&1)===1);a(8,t-8,!0)}var TT=[1,0,3,2];function ET(i){let e=i.length,t=0;for(let a=0;a<e;a++){let o=1;for(let l=1;l<e;l++)i[a][l]===i[a][l-1]?(o++,o===5?t+=3:o>5&&t++):o=1}for(let a=0;a<e;a++){let o=1;for(let l=1;l<e;l++)i[l][a]===i[l-1][a]?(o++,o===5?t+=3:o>5&&t++):o=1}for(let a=0;a<e-1;a++)for(let o=0;o<e-1;o++){let l=i[a][o];i[a][o+1]===l&&i[a+1][o]===l&&i[a+1][o+1]===l&&(t+=3)}let n=0;for(let a=0;a<e;a++)for(let o=0;o<e;o++)i[a][o]&&n++;let r=e*e,s=Math.floor(Math.abs(n*20-r*10)/r);return t+=s*10,t}function Vo(i,e={}){let t=e.scale??8,n=e.margin??2,r=e.dark??"#000",s=e.light??"#fff",{size:a,modules:o}=_f(i),l=(a+n*2)*t,c="";for(let h=0;h<a;h++)for(let d=0;d<a;d++)o[h][d]&&(c+=`<rect x="${(d+n)*t}" y="${(h+n)*t}" width="${t}" height="${t}"/>`);return`<svg xmlns="http://www.w3.org/2000/svg" width="${l}" height="${l}" viewBox="0 0 ${l} ${l}" shape-rendering="crispEdges"><rect width="${l}" height="${l}" fill="${s}"/><g fill="${r}">${c}</g></svg>`}function RT(i,e={}){let t=e.scale??8,n=e.margin??2,{size:r,modules:s}=_f(i),a=(r+n*2)*t,o=document.createElement("canvas");o.width=a,o.height=a;let l=o.getContext("2d");l.fillStyle="#fff",l.fillRect(0,0,a,a),l.fillStyle="#000";for(let c=0;c<r;c++)for(let h=0;h<r;h++)s[c][h]&&l.fillRect((h+n)*t,(c+n)*t,t,t);return o}var CT=1;function yf({endpoint:i,headers:e={},fetchImpl:t}={}){if(!i)throw new Error("ar-studio: MCP client needs an endpoint");let n=t||(typeof fetch<"u"?fetch.bind(globalThis):null);if(!n)throw new Error("ar-studio: no fetch implementation available");let r="";async function s(a,o,{signal:l}={}){let c=CT++,h=await n(i,{method:"POST",signal:l,headers:{"content-type":"application/json",accept:"application/json, text/event-stream",...r?{"mcp-session-id":r}:{},...e},body:JSON.stringify({jsonrpc:"2.0",id:c,method:a,...o?{params:o}:{}})}),d=h.headers.get("mcp-session-id");if(d&&(r=d),!h.ok){let p=await h.text().catch(()=>"");throw new Ta(`${a} failed (${h.status})`,{status:h.status,detail:p})}let f=await IT(h,c);if(f?.error)throw new Ta(f.error.message||"MCP error",{code:f.error.code});return f?.result??null}return{get sessionId(){return r},rpc:s,listTools(a){return s("tools/list",void 0,a).then(o=>o?.tools||[])},callTool(a,o={},l){return s("tools/call",{name:a,arguments:o},l)}}}var Ta=class extends Error{constructor(e,t={}){super(e),this.name="McpError",Object.assign(this,t)}};async function IT(i,e){if(!String(i.headers.get("content-type")||"").includes("text/event-stream"))return i.json();let n=await i.text();for(let r of n.split(/\n\n+/)){let s=r.split(`
+`).filter(a=>a.startsWith("data:")).map(a=>a.slice(5).trim()).join("");if(s)try{let a=JSON.parse(s);if(a.id===e||a.error)return a}catch{}}throw new Ta("MCP stream ended without a result")}function Ah(i){let e=i?.structuredContent??null,t=(i?.content||[]).filter(n=>n?.type==="text"&&typeof n.text=="string").map(n=>n.text).join(`
+`).trim();return{structured:e,text:t,isError:!!i?.isError}}var PT={nvidia:"free NVIDIA NIM",huggingface:"free Hunyuan3D",trellis:"Fast",trellis_selfhost:"TRELLIS",hunyuan3d:"Hunyuan3D",triposg:"TripoSG",meshy:"Meshy",tripo:"Tripo",rodin:"Rodin",stability:"Stability"};function pb(i){return PT[String(i||"").trim()]||null}function vf(i={}){let e=String(i.status||"").toLowerCase(),t=Number(i.etaSeconds)>0?Math.round(Number(i.etaSeconds)):null,n=t?`: ~${t}s`:"",r=pb(i.backend),s=r?` on the ${r} lane`:" on the free lane",a=!!i.coldStart,o=Number(i.coldSeconds)>0?Math.round(Number(i.coldSeconds)):null,l=r?` ${r}`:"";switch(e){case"submitting":case"submit":return`Sending your prompt${s}\u2026`;case"queued":case"pending":case"queue":return a?o?`Waking up the${l} GPU worker (about ${o}s), then sculpting starts`:`Waking up the${l} GPU worker, then sculpting starts`:`Queued${s}${n}`;case"image":case"texturing":return"Drafting the look\u2026";case"running":case"reconstruct":case"mesh":return`Building geometry & texturing${n}`;case"done":case"ready":return"Model ready: dropping it into the room";case"failed":case"error":return"Generation failed: try a more concrete, single-object prompt";default:return`Working${n}`}}function Sf(i,e=48){let t=String(i||"").replace(/\s+/g," ").trim();if(!t)return"Model";let n=t.split(/[,.;:]|\s+[--]\s+/)[0].trim()||t;if(n.length<=e)return n;let r=n.slice(0,e),s=r.lastIndexOf(" ");return`${(s>e*.6?r.slice(0,s):r).trim()}\u2026`}function LT(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function DT(i,e){for(let t of e)if(new RegExp(`(^|[^a-z0-9])${LT(t)}([^a-z0-9]|$)`,"i").test(i))return t;return null}var NT=["nude","nudes","naked","nsfw","porn","porno","pornographic","xxx","sex","sexual","sexy","erotic","erotica","hentai","rule34","r34","fetish","bdsm","bondage","lingerie","topless","bottomless","nipple","nipples","genital","genitalia","penis","vagina","vulva","breasts","boobs","cleavage","buttocks","thong","fellatio","cunnilingus","masturbation","orgasm","cum","creampie","milf","camgirl","stripper","escort","onlyfans"],OT=["loli","lolicon","shota","shotacon","toddlercon","underage","preteen","pre-teen","jailbait","child porn","childporn","child sex","child sexual","minor sex","csam"],FT=["gore","gory","gruesome","dismembered","dismemberment","decapitated","decapitation","beheading","mutilated","mutilation","disembowel","disemboweled","eviscerated","bloodbath","massacre","torture","tortured","snuff"],UT=["nazi","swastika","hitler","kkk","white power","heil","genocide","ethnic cleansing","terrorist","isis","al qaeda","al-qaeda"],kT=["ghost gun","ar-15","ar15","ak-47","ak47","assault rifle","submachine gun","handgun","pistol","firearm","firearms","silencer","suppressor","ammunition magazine","pipe bomb","ied","grenade","landmine","c4 explosive","meth","methamphetamine","cocaine","heroin","fentanyl","crack pipe","bong"],BT=[{id:"csam",terms:OT,message:"This prompt is not allowed."},{id:"sexual",terms:NT,message:"This studio cannot generate sexual or adult content. Describe a character, creature, or object without explicit themes."},{id:"gore",terms:FT,message:"This studio cannot generate graphically violent or gory content. Describe your subject without graphic violence."},{id:"hate",terms:UT,message:"This studio cannot generate hateful or extremist content or iconography."},{id:"weapon_drug",terms:kT,message:"This studio cannot generate real firearms, explosives, or drug paraphernalia. Stylized fantasy props (a sword, a wand) are fine."}];function mb(i){let e=String(i||"").toLowerCase();if(!e.trim())return{allowed:!0};for(let t of BT){let n=DT(e,t.terms);if(n)return{allowed:!1,category:t.id,message:t.message,matched:n}}return{allowed:!0}}function wf(i){let e=String(i??"").trim();if(e.length<3)return{ok:!1,reason:"Describe a concrete object: at least a few characters."};let t=mb(e);return t.allowed?{ok:!0,prompt:e}:{ok:!1,reason:t.message,category:t.category}}var gb={model:"forge_free",avatar:"text_to_avatar",mesh:"mesh_forge"},tr=class extends Error{constructor(e,t="failed"){super(e),this.name="ForgeError",this.code=t}};function Mf({endpoint:i=En.studioMcp,kind:e="model",tier:t="standard",timeoutMs:n=3e5,pollMs:r=3e3,headers:s,tools:a=gb,fetchImpl:o}={}){let l=yf({endpoint:i,headers:s,fetchImpl:o});async function c(h,{onProgress:d,kind:f,imageUrl:p="",signal:x,tier:y}={}){let b=wf(h);if(!b.ok)throw new tr(b.reason,b.category||"invalid_prompt");let g=b.prompt,S=f||e,A=a[S]||a.model,T=Date.now(),N=null,P=(k,V={})=>{d&&d({status:k,message:vf({status:k,etaSeconds:N,...V}),elapsedMs:Date.now()-T,etaSeconds:N})};P("submitting");let U=S==="model"?{prompt:g,...y||t?{tier:y||t}:{}}:{prompt:g,...p?{image_url:p}:{}},v=Ah(await l.callTool(A,U,{signal:x}));if(v.isError)throw new tr(v.structured?.message||v.text||"Generation failed.");let I=v.structured||{};for(;I.status==="pending"&&I.jobId;){if(Date.now()-T>n)throw new tr("Generation timed out. Try a simpler, single-object prompt.","timeout");if(N=Number(I.etaRemainingSeconds)>0?Number(I.etaRemainingSeconds):null,P("queued"),await zT(r,x),v=Ah(await l.callTool("check_job",{job_id:I.jobId},{signal:x})),v.isError)throw new tr(v.structured?.message||v.text||"Generation failed.");I=v.structured||{}}let B=Th(I.glbUrl,I.glb_url,I.url);if(!B)throw new tr(v.text||"The generator returned no model.","no_result");return P("done"),{src:B,title:Sf(g),prompt:g,kind:S,viewerUrl:Th(I.viewerUrl,""),arUrl:Th(I.arUrl,""),poster:Th(I.referenceImageUrl,""),rigged:!!I.rigged}}return{generate:c,mcp:l,endpoint:i}}function Th(...i){for(let e of i)if(typeof e=="string"&&e.trim())return e.trim();return""}function zT(i,e){return new Promise((t,n)=>{if(e?.aborted)return n(new tr("Cancelled.","aborted"));let r=setTimeout(t,i);e?.addEventListener("abort",()=>{clearTimeout(r),n(new tr("Cancelled.","aborted"))},{once:!0})})}function Wo({url:i,id:e,label:t="Models",hint:n="",searchable:r,map:s,rewriteUrl:a,fetchOptions:o}={}){if(!i)throw new Error("ar-studio: manifestSource needs a url");return{id:e||qT(t)||"models",label:t,hint:n,searchable:r,async list(){let l=await fetch(i,o);if(!l.ok)throw new Error(`catalogue ${l.status}`);let c=await l.json();return Ea(c,{map:s,rewriteUrl:a})}}}function bb(i){if(Array.isArray(i))return i;for(let e of["items","objects","avatars","creations","models","assets","results"])if(Array.isArray(i?.[e]))return i[e];return[]}var HT=["src","url","glb","glb_url","glbUrl","file","model","modelUrl"],GT=["title","label","name","prompt","displayName"],VT=["poster","thumb","thumbnail","image","preview_image_url","previewImageUrl","preview"];function Af(i,e){for(let t of e){let n=i?.[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function Ea(i,{map:e,rewriteUrl:t}={}){let n=bb(i),r=[];for(let s of n){if(!s||typeof s!="object")continue;let a=e?e(s):WT(s);if(!a)continue;let o=er(t?t(a.src):a.src);if(!o)continue;let l=a.poster?er(t?t(a.poster):a.poster):"";r.push({src:o,title:String(a.title||"").slice(0,160),poster:l||"",keywords:String(a.keywords||a.title||"").trim().toLowerCase()})}return r}function WT(i){let e=Af(i,HT);if(!e)return null;let t=Af(i,GT)||xb(e),n=[].concat(Array.isArray(i.categories)?i.categories:[]).concat(Array.isArray(i.tags)?i.tags:[]).join(" ");return{src:e,title:t,poster:Af(i,VT),keywords:`${t} ${n}`.trim().toLowerCase()}}function xb(i){let t=(String(i).split("?")[0].split("/").pop()||"Model").replace(/\.(glb|gltf)$/i,"").replace(/[_-]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Model"}function qT(i){return String(i).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function _b({items:i=[],id:e="catalogue",label:t="Catalogue",hint:n="",searchable:r}={}){let s=Ea(i);return{id:e,label:t,hint:n,searchable:r,async list(){return s}}}var Tf="ar-studio:recent:v1",$T=12;function Ef(i=Tf){try{let e=JSON.parse(localStorage.getItem(i)||"[]");return Array.isArray(e)?e.map(t=>({src:er(t?.src||t?.glb),title:String(t?.title||t?.prompt||"").slice(0,160),poster:t?.poster&&er(t.poster)||"",ts:Number(t?.ts)||0})).filter(t=>t.src):[]}catch{return[]}}function Rf({src:i,title:e="",poster:t=""},n=Tf){let r=er(i);if(r)try{let s=Ef(n).filter(a=>a.src!==r);s.unshift({src:r,title:String(e).slice(0,200),poster:t||"",ts:Date.now()}),localStorage.setItem(n,JSON.stringify(s.slice(0,$T)))}catch{}}function Eh(i={}){let e=i.recentKey||Tf;return{id:"recent",label:"Recent",hint:"",live:!0,emptyCopy:"Nothing here yet. Generate a model below, or paste a GLB link, and it lands in this tab.",async list(){return Ef(e).map(t=>({src:t.src,title:t.title,poster:t.poster,keywords:t.title.toLowerCase()}))}}}function Cf(i,e=En.origin){let t=String(i||""),n=t.match(/^https:\/\/pub-[a-z0-9]+\.r2\.dev\/(.+)$/i);return n?`${e.replace(/\/$/,"")}/cdn/${n[1]}`:t}function Rh(i={}){let e=(i.origin||En.origin).replace(/\/$/,""),t=i.objectsManifest||En.objectsManifest;return{...Wo({url:t,id:"objects",label:"Objects",searchable:!0,rewriteUrl:n=>Cf(n,e)}),hint:"Public-domain (CC0) props from three.ws: free to use anywhere, commercially too.",emptyCopy:"The object library is unreachable right now. Check your connection and retry."}}function If(i={}){let e=(i.origin||En.origin).replace(/\/$/,""),t=i.galleryEndpoint||`${e}/api/forge-gallery`;return{id:"community",label:"Community",hint:"Fresh models generated by the three.ws community.",emptyCopy:"The community feed is quiet right now. Check back in a bit.",async list(){let n=await fetch(`${t}?scope=community&limit=48`);if(!n.ok)throw new Error(`gallery ${n.status}`);return Ea(await n.json(),{rewriteUrl:r=>Cf(r,e)})}}}var Pf={id:"link",label:"Link",kind:"link"};function Lf(i,e={}){let t=Array.isArray(i)?i:[i],n=[];for(let s of t){let a=jT(s,e);Array.isArray(a)?n.push(...a):a&&n.push(a)}n.some(s=>s.kind==="link"||s.id==="link")||n.push(Pf);let r=new Set;return n.filter(s=>r.has(s.id)?!1:(r.add(s.id),!0))}function jT(i,e){if(!i)return null;if(typeof i=="object")return i;let t=String(i).trim();if(t==="three.ws"||t==="default")return[Eh(e),Rh(e)];if(t==="recent"||t==="recents")return Eh(e);if(t==="objects")return Rh(e);if(t==="community")return If(e);if(t==="link")return Pf;if(t==="none"||t==="empty")return null;if(/^https:\/\//i.test(t)||t.startsWith("/"))return Wo({url:t});throw new Error(`ar-studio: unknown asset source "${t}"`)}var Ch="https://three.ws",Ra=class extends Error{constructor(e,t){super(t),this.name="ArUrlError",this.code=e}};function yb(i){let e;try{e=new URL(String(i))}catch{throw new Ra("invalid_url","Provide a valid https URL to a .glb model.")}if(e.protocol!=="https:")throw new Ra("not_https","The model URL must be https.");if(!/\.(glb|gltf)$/i.test(e.pathname))throw new Ra("not_glb","The model URL must point at a .glb or .gltf file.");return e.toString()}function vb(i){let e=String(i||"");return/\b(iphone|ipad|ipod)\b/i.test(e)?"ios":/\bandroid\b/i.test(e)?"android":"desktop"}function Sb(i,{title:e="",fallbackUrl:t=""}={}){let n=new URLSearchParams({file:i,mode:"ar_preferred"});e&&n.set("title",e);let r=t?`S.browser_fallback_url=${encodeURIComponent(t)};`:"";return`intent://arvr.google.com/scene-viewer/1.2?${n.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;${r}end;`}function wb(i,e,t=""){let n=String(i||Ch).replace(/\/$/,""),r=t?`&title=${encodeURIComponent(t)}`:"";return`${n}/viewer?src=${encodeURIComponent(e)}${r}`}function Ih(i,e,t="",{live:n=!1,endpoint:r}={}){let s=r||`${String(i||Ch).replace(/\/$/,"")}/api/ar`,a=t?`&title=${encodeURIComponent(t)}`:"",o=n?"&kind=avatar":"";return`${s}?src=${encodeURIComponent(e)}${a}${o}`}function XT({glbUrl:i,userAgent:e,origin:t=Ch,title:n="",live:r=!1}={}){let s=yb(i),a=vb(e),o=wb(t,s,n),l=Sb(s,{title:n,fallbackUrl:o}),c=Ih(t,s,n,{live:r});return{target:a,action:a==="android"&&!r?"redirect":"page",asset:s,viewerUrl:o,sceneViewerUrl:l,launchUrl:c,live:r}}Vn();Vn();var Ph=class extends Or{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;let e=new Hr;e.deleteAttribute("uv");let t=new gi({side:An}),n=new gi,r=new ws(16777215,900,28,2);r.position.set(.418,16.199,.3),this.add(r);let s=new xt(e,t);s.position.set(-.757,13.219,.717),s.scale.set(31.713,28.305,28.591),this.add(s);let a=new _s(e,n,6),o=new qt;o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-.195,0),o.scale.set(2.328,7.905,4.651),o.updateMatrix(),a.setMatrixAt(0,o.matrix),o.position.set(-5.607,-.754,-.758),o.rotation.set(0,.994,0),o.scale.set(1.97,1.534,3.955),o.updateMatrix(),a.setMatrixAt(1,o.matrix),o.position.set(6.167,.857,7.803),o.rotation.set(0,.561,0),o.scale.set(3.927,6.285,3.687),o.updateMatrix(),a.setMatrixAt(2,o.matrix),o.position.set(-2.017,.018,6.124),o.rotation.set(0,.333,0),o.scale.set(2.002,4.566,2.064),o.updateMatrix(),a.setMatrixAt(3,o.matrix),o.position.set(2.291,-.756,-2.621),o.rotation.set(0,-.286,0),o.scale.set(1.546,1.552,1.496),o.updateMatrix(),a.setMatrixAt(4,o.matrix),o.position.set(-2.193,-.369,-5.547),o.rotation.set(0,.516,0),o.scale.set(3.875,3.487,2.986),o.updateMatrix(),a.setMatrixAt(5,o.matrix),this.add(a);let l=new xt(e,Ca(50));l.position.set(-16.116,14.37,8.208),l.scale.set(.1,2.428,2.739),this.add(l);let c=new xt(e,Ca(50));c.position.set(-16.109,18.021,-8.207),c.scale.set(.1,2.425,2.751),this.add(c);let h=new xt(e,Ca(17));h.position.set(14.904,12.198,-1.832),h.scale.set(.15,4.265,6.331),this.add(h);let d=new xt(e,Ca(43));d.position.set(-.462,8.89,14.52),d.scale.set(4.38,5.441,.088),this.add(d);let f=new xt(e,Ca(20));f.position.set(3.235,11.486,-12.541),f.scale.set(2.5,2,.1),this.add(f);let p=new xt(e,Ca(100));p.position.set(0,20,0),p.scale.set(1,.1,1),this.add(p)}dispose(){let e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(let t of e)t.dispose()}};function Ca(i){return new po({color:0,emissive:16777215,emissiveIntensity:i})}var Nf={high:{pixelRatioCap:2,shadows:!0,hdri:!0},medium:{pixelRatioCap:1.5,shadows:!0,hdri:!0},mobile:{pixelRatioCap:1,shadows:!1,hdri:!1}};function Of(i={}){let e=i.navigator??(typeof navigator<"u"?navigator:{}),t=i.window??(typeof window<"u"?window:{}),n=String(e.userAgent||""),r=/(iPhone|iPad|Android|Mobi)/i.test(n),s=(e.deviceMemory??8)<4,a=(e.hardwareConcurrency??8)<4,o=!!(t.matchMedia&&t.matchMedia("(any-pointer: coarse)").matches);return r&&(s||a)?"mobile":o||s||a?"medium":"high"}function Ff(i,e={}){let t=Nf[e.tier]?e.tier:"high",n=Nf[t];return i.outputColorSpace=Xt,i.toneMapping=Ro,i.toneMappingExposure=e.exposure??1.15,i.setPixelRatio(Math.min(typeof window<"u"?window.devicePixelRatio:1,n.pixelRatioCap)),i.shadowMap.enabled=n.shadows,n.shadows&&(i.shadowMap.type=qr),n}var Tb=new Map;async function Uf(i,e,t="studio",{urls:n=En.hdri}={}){let r=new wa(i);r.compileEquirectangularShader();let s=r.fromScene(new Ph,.04);e.environment=s.texture,e.environmentIntensity??=1;let a=t&&n?n[t]:null;if(!a)return r.dispose(),e.environment;try{let o=Tb.get(a);if(!o){let{HDRLoader:c}=await Promise.resolve().then(()=>(Ab(),Mb));o=await new c().loadAsync(a),Tb.set(a,o)}let l=r.fromEquirectangular(o);return e.environment===s.texture?e.environment=l.texture:l.dispose(),s.dispose(),e.environment}catch{return e.environment}finally{r.dispose()}}function KT(i,e,t,n=.35){let r=new rn().setFromObject(e);if(!Number.isFinite(r.min.y))return t??null;let a=Math.max(r.max.x-r.min.x,r.max.z-r.min.z,1)*6,o=t;return o||(o=new xt(new mi(1,1),new fo({opacity:n})),o.rotation.x=-Math.PI/2,o.receiveShadow=!0,i.add(o)),o.scale.set(a,a,1),o.position.set((r.min.x+r.max.x)/2,r.min.y,(r.min.z+r.max.z)/2),o}function Eb(){return`
+.ars-root {
+ --ars-accent: #8b7cf8;
+ --ars-accent-ink: #dcd6ff;
+ --ars-ink: #ecedf2;
+ --ars-ink-dim: #9aa0af;
+ --ars-ink-faint: #6b7080;
+ --ars-line: rgba(255, 255, 255, 0.1);
+ --ars-panel: rgba(12, 13, 17, 0.78);
+ --ars-warn: #fca5a5;
+ --ars-radius: 14px;
+ --ars-font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ position: absolute;
+ inset: 0;
+ display: block;
+ overflow: hidden;
+ background: radial-gradient(120% 120% at 50% 0%, #101321 0%, #07080c 55%, #000 100%);
+ color: var(--ars-ink);
+ font-family: var(--ars-font);
+ touch-action: none;
+ -webkit-user-select: none;
+ user-select: none;
+ color-scheme: dark;
+}
+.ars-root *, .ars-root *::before, .ars-root *::after { box-sizing: border-box; }
+/* A display rule must never beat the hidden attribute: an invisible panel that
+ still swallows taps is a dead page. */
+.ars-root [hidden] { display: none !important; }
+.ars-root.is-fullscreen {
+ position: fixed;
+ z-index: 2147483000;
+ height: 100dvh;
+}
+
+/* Layers: camera video \u2192 WebGL canvas \u2192 HUD */
+.ars-video {
+ position: absolute; inset: 0; width: 100%; height: 100%;
+ object-fit: cover; display: none; background: #000;
+}
+.ars-root.is-ar .ars-video { display: block; }
+.ars-canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.ars-hud {
+ position: absolute; inset: 0; z-index: 10;
+ display: flex; flex-direction: column; justify-content: space-between;
+ pointer-events: none;
+}
+.ars-hud > * { pointer-events: none; }
+.ars-hud a, .ars-hud button, .ars-hud input, .ars-hud form,
+.ars-hud .ars-top, .ars-hud .ars-dock, .ars-hud .ars-selbar,
+.ars-hud .ars-tray, .ars-hud .ars-modal { pointer-events: auto; }
+
+/* \u2500\u2500 Top bar \u2500\u2500 */
+.ars-top {
+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
+ padding: calc(env(safe-area-inset-top, 0px) + 10px) 14px 10px;
+}
+.ars-back, .ars-title {
+ display: inline-flex; align-items: center; gap: 7px;
+ color: var(--ars-ink); text-decoration: none; font-size: 13.5px; font-weight: 650;
+ background: var(--ars-panel); border: 1px solid var(--ars-line);
+ border-radius: 999px; padding: 8px 14px; backdrop-filter: blur(10px);
+ transition: background 0.15s, border-color 0.15s;
+}
+.ars-back:hover { background: rgba(30, 32, 40, 0.85); border-color: rgba(255, 255, 255, 0.22); }
+.ars-root :focus-visible { outline: 2px solid var(--ars-accent); outline-offset: 2px; }
+.ars-count {
+ font-size: 12.5px; font-weight: 650; color: var(--ars-accent-ink);
+ background: color-mix(in srgb, var(--ars-accent) 16%, transparent);
+ border: 1px solid color-mix(in srgb, var(--ars-accent) 40%, transparent);
+ border-radius: 999px; padding: 7px 12px; backdrop-filter: blur(10px);
+}
+.ars-spacer { flex: 1 1 auto; }
+.ars-icon-btn {
+ appearance: none; cursor: pointer; font: inherit; color: var(--ars-ink);
+ display: inline-flex; align-items: center; justify-content: center; gap: 7px;
+ background: var(--ars-panel); border: 1px solid var(--ars-line);
+ border-radius: 999px; padding: 8px 13px; font-size: 13px; font-weight: 650;
+ backdrop-filter: blur(10px);
+ transition: background 0.15s, border-color 0.15s, transform 0.06s;
+}
+.ars-icon-btn:hover { background: rgba(30, 32, 40, 0.85); border-color: rgba(255, 255, 255, 0.22); }
+.ars-icon-btn:active { transform: translateY(1px); }
+.ars-icon-btn[disabled] { opacity: 0.45; cursor: not-allowed; }
+.ars-icon-btn.is-active {
+ background: color-mix(in srgb, var(--ars-accent) 20%, transparent);
+ border-color: color-mix(in srgb, var(--ars-accent) 55%, transparent);
+ color: var(--ars-accent-ink);
+}
+
+/* \u2500\u2500 Generation progress chip \u2500\u2500 */
+.ars-chip {
+ position: absolute; top: calc(env(safe-area-inset-top, 0px) + 58px); left: 50%;
+ transform: translateX(-50%); z-index: 11;
+ display: inline-flex; align-items: center; gap: 9px; max-width: min(88vw, 480px);
+ background: var(--ars-panel); border: 1px solid var(--ars-line); border-radius: 999px;
+ padding: 9px 15px; font-size: 13px; backdrop-filter: blur(10px);
+ animation: ars-rise 0.25s ease;
+}
+.ars-chip[data-state="error"] { border-color: rgba(252, 165, 165, 0.5); color: var(--ars-warn); }
+.ars-chip[data-state="error"] .ars-spinner { display: none; }
+.ars-chip-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.ars-chip-elapsed { color: var(--ars-ink-faint); font-variant-numeric: tabular-nums; font-size: 12px; }
+.ars-spinner {
+ width: 14px; height: 14px; flex: 0 0 auto; border-radius: 50%;
+ border: 2px solid rgba(255, 255, 255, 0.18); border-top-color: var(--ars-accent);
+ animation: ars-spin 0.9s linear infinite;
+}
+@keyframes ars-spin { to { transform: rotate(360deg); } }
+@keyframes ars-rise { from { opacity: 0; transform: translate(-50%, 6px); } to { opacity: 1; transform: translate(-50%, 0); } }
+
+/* \u2500\u2500 Empty state \u2500\u2500 */
+.ars-empty {
+ position: absolute; inset: 0; z-index: 9; display: grid; place-items: center;
+ padding: 24px; pointer-events: none;
+}
+.ars-empty-card {
+ pointer-events: auto; text-align: center; max-width: 340px;
+ background: var(--ars-panel); border: 1px solid var(--ars-line);
+ border-radius: 20px; padding: 26px 22px; backdrop-filter: blur(12px);
+ display: flex; flex-direction: column; gap: 10px; align-items: center;
+}
+.ars-empty-art { font-size: 40px; line-height: 1; }
+.ars-empty-card h2 { margin: 0; font-size: 18px; letter-spacing: -0.01em; font-weight: 700; }
+.ars-empty-card p { margin: 0 0 6px; color: var(--ars-ink-dim); font-size: 13.5px; line-height: 1.55; }
+.ars-empty-row { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; }
+.ars-root.is-ar .ars-empty-card { background: rgba(12, 13, 17, 0.6); }
+
+/* \u2500\u2500 Buttons \u2500\u2500 */
+.ars-btn {
+ appearance: none; cursor: pointer; font: inherit; font-size: 13.5px; font-weight: 650;
+ color: var(--ars-ink); background: rgba(255, 255, 255, 0.07);
+ border: 1px solid rgba(255, 255, 255, 0.16); border-radius: 11px; padding: 10px 15px;
+ display: inline-flex; align-items: center; gap: 7px;
+ transition: background 0.15s, border-color 0.15s, transform 0.06s;
+}
+.ars-btn:hover { background: rgba(255, 255, 255, 0.12); border-color: rgba(255, 255, 255, 0.28); }
+.ars-btn:active { transform: translateY(1px); }
+.ars-btn[disabled] { opacity: 0.5; cursor: not-allowed; }
+.ars-btn-primary { background: var(--ars-accent); border-color: var(--ars-accent); color: #0d0b1e; }
+.ars-btn-primary:hover { filter: brightness(1.08); }
+
+/* \u2500\u2500 Status line \u2500\u2500 */
+.ars-status {
+ position: absolute; left: 50%; transform: translateX(-50%);
+ bottom: calc(env(safe-area-inset-bottom, 0px) + 186px); z-index: 12;
+ display: inline-flex; align-items: center; gap: 10px; max-width: 92%;
+ background: var(--ars-panel); border: 1px solid var(--ars-line); border-radius: 999px;
+ padding: 8px 14px; font-size: 12.5px; color: var(--ars-ink-dim);
+ backdrop-filter: blur(10px); animation: ars-rise 0.2s ease; text-align: center;
+}
+.ars-status.is-warn { color: var(--ars-warn); border-color: rgba(252, 165, 165, 0.42); }
+.ars-status-action {
+ appearance: none; cursor: pointer; font: inherit; font-size: 12.5px; font-weight: 700;
+ color: var(--ars-accent-ink); background: none; border: 0; padding: 0; text-decoration: underline;
+}
+
+/* \u2500\u2500 Selection toolbar \u2500\u2500 */
+.ars-selbar {
+ position: absolute; left: 50%; transform: translateX(-50%);
+ bottom: calc(env(safe-area-inset-bottom, 0px) + 132px); z-index: 11;
+ display: flex; align-items: center; gap: 6px; max-width: 94%;
+ background: var(--ars-panel); border: 1px solid var(--ars-line); border-radius: 999px;
+ padding: 6px 8px 6px 14px; backdrop-filter: blur(12px);
+ animation: ars-pop 0.18s ease;
+}
+@keyframes ars-pop { from { opacity: 0; transform: translate(-50%, 5px); } to { opacity: 1; transform: translate(-50%, 0); } }
+.ars-sel-name {
+ font-size: 12.5px; font-weight: 650; color: var(--ars-accent-ink);
+ max-width: 26vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+}
+.ars-selbar .ars-icon-btn { border-radius: 999px; padding: 7px 11px; font-size: 12.5px; background: rgba(255, 255, 255, 0.06); }
+/* The AR control lives in the top bar and already acts on the selected model, so
+ the selection toolbar stays icon-sized edit actions. Duplicating it here
+ collapsed to an unlabelled dot on a narrow phone. */
+.ars-top .ars-icon-btn[aria-busy="true"] { opacity: 0.7; cursor: progress; }
+
+/* \u2500\u2500 Bottom dock \u2500\u2500 */
+.ars-dock {
+ display: flex; align-items: center; gap: 9px; flex-wrap: nowrap;
+ padding: 12px 14px calc(env(safe-area-inset-bottom, 0px) + 14px);
+ background: linear-gradient(to top, rgba(4, 5, 8, 0.72), rgba(4, 5, 8, 0));
+}
+.ars-forge-form { flex: 1 1 auto; display: flex; align-items: center; gap: 8px; min-width: 0; }
+.ars-forge-input {
+ flex: 1 1 auto; min-width: 0; font: inherit; font-size: 14px; color: var(--ars-ink);
+ background: var(--ars-panel); border: 1px solid var(--ars-line);
+ border-radius: 999px; padding: 11px 16px; backdrop-filter: blur(10px);
+ transition: border-color 0.15s;
+}
+.ars-forge-input::placeholder { color: var(--ars-ink-faint); }
+.ars-forge-input:focus { border-color: color-mix(in srgb, var(--ars-accent) 55%, transparent); }
+.ars-forge-go {
+ appearance: none; cursor: pointer; font: inherit; font-size: 14px; font-weight: 700;
+ color: #0d0b1e; background: var(--ars-accent); border: 0; border-radius: 999px;
+ padding: 11px 17px; flex: 0 0 auto;
+}
+.ars-forge-go[disabled] { opacity: 0.55; cursor: not-allowed; }
+
+/* \u2500\u2500 Tray + modals \u2500\u2500 */
+.ars-tray, .ars-modal {
+ position: absolute; inset: 0; z-index: 20; display: flex;
+ background: rgba(4, 5, 8, 0.62); backdrop-filter: blur(4px);
+ animation: ars-fade 0.16s ease;
+}
+@keyframes ars-fade { from { opacity: 0; } to { opacity: 1; } }
+.ars-tray { align-items: flex-end; }
+.ars-modal { align-items: center; justify-content: center; padding: 22px; }
+.ars-tray-panel {
+ width: 100%; max-height: 78%; display: flex; flex-direction: column;
+ background: rgba(11, 12, 16, 0.97); border-top: 1px solid var(--ars-line);
+ border-radius: 20px 20px 0 0; animation: ars-slide 0.22s ease;
+}
+@keyframes ars-slide { from { transform: translateY(14px); opacity: 0; } to { transform: none; opacity: 1; } }
+.ars-tray-head {
+ display: flex; align-items: center; gap: 10px;
+ padding: 14px 16px 10px; border-bottom: 1px solid var(--ars-line);
+}
+.ars-tray-head h2 { margin: 0; font-size: 15px; font-weight: 700; }
+.ars-tabs {
+ display: flex; gap: 6px; padding: 10px 16px 0; overflow-x: auto;
+ scrollbar-width: none; position: relative;
+}
+.ars-tabs::-webkit-scrollbar { display: none; }
+.ars-tab {
+ appearance: none; cursor: pointer; font: inherit; font-size: 13px; font-weight: 650;
+ white-space: nowrap; color: var(--ars-ink-dim); background: rgba(255, 255, 255, 0.05);
+ border: 1px solid transparent; border-radius: 999px; padding: 8px 14px;
+ transition: background 0.15s, color 0.15s;
+}
+.ars-tab:hover { color: var(--ars-ink); background: rgba(255, 255, 255, 0.1); }
+.ars-tab.is-active {
+ color: var(--ars-accent-ink);
+ background: color-mix(in srgb, var(--ars-accent) 18%, transparent);
+ border-color: color-mix(in srgb, var(--ars-accent) 45%, transparent);
+}
+.ars-tray-body { flex: 1 1 auto; overflow-y: auto; padding: 14px 16px calc(env(safe-area-inset-bottom, 0px) + 18px); -webkit-overflow-scrolling: touch; }
+.ars-tray-loading, .ars-tray-empty {
+ display: flex; flex-direction: column; align-items: center; gap: 12px;
+ padding: 34px 16px; color: var(--ars-ink-dim); font-size: 13.5px; text-align: center;
+}
+.ars-tray-loading { flex-direction: row; justify-content: center; }
+.ars-item-list {
+ list-style: none; margin: 0; padding: 0;
+ display: grid; gap: 10px; grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));
+}
+.ars-item-add {
+ appearance: none; cursor: pointer; font: inherit; width: 100%; text-align: left;
+ display: flex; flex-direction: column; gap: 7px; color: var(--ars-ink);
+ background: rgba(255, 255, 255, 0.05); border: 1px solid var(--ars-line);
+ border-radius: var(--ars-radius); padding: 9px;
+ transition: background 0.15s, border-color 0.15s, transform 0.08s;
+}
+.ars-item-add:hover { background: rgba(255, 255, 255, 0.1); border-color: color-mix(in srgb, var(--ars-accent) 45%, transparent); transform: translateY(-1px); }
+.ars-item-add:active { transform: translateY(0); }
+.ars-item-thumb {
+ display: grid; place-items: center; aspect-ratio: 1 / 1; overflow: hidden;
+ border-radius: 10px; background: rgba(255, 255, 255, 0.04);
+}
+.ars-item-thumb img { width: 100%; height: 100%; object-fit: cover; }
+.ars-item-cube { font-size: 22px; color: var(--ars-ink-faint); }
+.ars-item-title {
+ font-size: 12.5px; font-weight: 600; line-height: 1.3;
+ display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
+}
+.ars-item-cta { font-size: 11.5px; font-weight: 700; color: var(--ars-accent-ink); }
+.ars-search {
+ width: 100%; font: inherit; font-size: 14px; color: var(--ars-ink);
+ background: rgba(255, 255, 255, 0.05); border: 1px solid var(--ars-line);
+ border-radius: 11px; padding: 10px 14px; margin-bottom: 8px;
+}
+.ars-hint { margin: 0 0 12px; color: var(--ars-ink-faint); font-size: 12px; line-height: 1.5; }
+.ars-hint a, .ars-tray-empty a { color: var(--ars-accent-ink); }
+.ars-link-row { display: flex; gap: 8px; align-items: center; }
+.ars-link-row input { flex: 1 1 auto; min-width: 0; }
+.ars-more { display: grid; place-items: center; padding: 14px 0 4px; }
+
+.ars-dialog {
+ width: min(420px, 100%); max-height: 88%; overflow-y: auto;
+ background: rgba(11, 12, 16, 0.98); border: 1px solid var(--ars-line);
+ border-radius: 20px; padding: 20px; text-align: center;
+ display: flex; flex-direction: column; gap: 12px; align-items: center;
+ animation: ars-slide 0.2s ease;
+}
+.ars-dialog h2 { margin: 0; font-size: 16px; font-weight: 700; }
+.ars-dialog p { margin: 0; color: var(--ars-ink-dim); font-size: 13px; line-height: 1.55; }
+.ars-qr-box { background: #fff; border-radius: 14px; padding: 12px; line-height: 0; }
+.ars-qr-box svg { width: min(240px, 60vw); height: auto; }
+.ars-code {
+ font-size: 26px; font-weight: 800; letter-spacing: 0.16em;
+ color: var(--ars-accent-ink); font-variant-numeric: tabular-nums;
+}
+.ars-link-out { font-size: 12px; color: var(--ars-ink-faint); word-break: break-all; }
+
+/* \u2500\u2500 AR hand-off sheet \u2500\u2500 */
+.ars-ar-sheet { gap: 14px; }
+.ars-ar-sheet .ars-btn { width: 100%; }
+.ars-ar-heading { letter-spacing: -0.01em; }
+.ars-ar-target { display: flex; flex-direction: column; align-items: center; gap: 10px; width: 100%; }
+.ars-ar-thumb {
+ width: min(210px, 52vw); aspect-ratio: 1; border-radius: 18px;
+ background: radial-gradient(120% 120% at 50% 0%, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.02));
+ border: 1px solid var(--ars-line);
+ display: grid; place-items: center; overflow: hidden;
+ font-size: 42px; color: var(--ars-ink-faint);
+}
+.ars-ar-thumb img { width: 100%; height: 100%; object-fit: contain; }
+.ars-ar-name { font-size: 15px; font-weight: 700; text-align: center; overflow-wrap: anywhere; }
+.ars-ar-picker { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; width: 100%; }
+.ars-ar-chip {
+ appearance: none; cursor: pointer; font: inherit; font-size: 12px; font-weight: 650;
+ color: var(--ars-ink-dim); background: rgba(255, 255, 255, 0.06);
+ border: 1px solid var(--ars-line); border-radius: 999px; padding: 6px 11px;
+ max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+}
+.ars-ar-chip:hover { background: rgba(255, 255, 255, 0.12); color: var(--ars-ink); }
+.ars-ar-chip:active { transform: translateY(1px); }
+.ars-ar-chip[aria-pressed="true"] {
+ background: color-mix(in srgb, var(--ars-accent) 20%, transparent);
+ border-color: color-mix(in srgb, var(--ars-accent) 55%, transparent);
+ color: var(--ars-accent-ink);
+}
+.ars-ar-hint { color: var(--ars-ink-faint) !important; font-size: 12.5px !important; }
+.ars-ar-status { min-height: 17px; display: flex; align-items: center; justify-content: center; gap: 7px; }
+.ars-ar-status.is-error { color: #ffb4b4 !important; }
+.ars-ar-status.is-ready { color: var(--ars-accent-ink) !important; }
+.ars-ar-status .ars-spinner { width: 12px; height: 12px; border-width: 2px; }
+.ars-ar-go[aria-busy="true"] { cursor: progress; }
+.ars-ar-go { font-size: 15px; padding: 13px 18px; }
+.ars-ar-go-icon { font-size: 15px; }
+.ars-dialog-row { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; }
+.ars-divider { width: 100%; height: 1px; background: var(--ars-line); margin: 2px 0; }
+
+/* WebXR: the dom-overlay shows the HUD over the passthrough camera; the empty
+ card and grid would only be in the way once the room itself is the backdrop. */
+.ars-root.is-xr .ars-empty, .ars-root.is-xr .ars-back { display: none; }
+
+@media (prefers-reduced-motion: reduce) {
+ .ars-root *, .ars-root *::before, .ars-root *::after {
+ animation-duration: 0.01ms !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: 0.01ms !important;
+ }
+}
+@media (max-width: 420px) {
+ .ars-title { display: none; }
+ .ars-item-list { grid-template-columns: repeat(auto-fill, minmax(108px, 1fr)); }
+ /* A phone this narrow cannot fit the prompt beside four controls without
+ squeezing it down to two visible characters. Give it its own row. */
+ .ars-dock { flex-wrap: wrap; row-gap: 10px; }
+ .ars-forge-form { order: -1; flex: 1 0 100%; }
+ .ars-dock .ars-icon-btn { flex: 0 0 auto; }
+ .ars-status { bottom: calc(env(safe-area-inset-bottom, 0px) + 152px); }
+ .ars-selbar { bottom: calc(env(safe-area-inset-bottom, 0px) + 100px); }
+}
+`}var Rb="ar-studio-styles";function YT(i=document){if(i.getElementById(Rb))return;let e=i.createElement("style");e.id=Rb,e.textContent=Eb(),i.head.appendChild(e)}function re(i,e={},t=[]){let n=document.createElement(i);for(let[r,s]of Object.entries(e))s==null||s===!1||(r==="class"?n.className=s:r==="text"?n.textContent=s:r==="html"?n.innerHTML=s:r==="hidden"?n.hidden=!!s:r.startsWith("on")&&typeof s=="function"?n.addEventListener(r.slice(2),s):n.setAttribute(r,s===!0?"":String(s)));for(let r of[].concat(t))r&&n.appendChild(typeof r=="string"?document.createTextNode(r):r);return n}function Cb(i,e){YT(i.ownerDocument||document);let t=e.branding||{},n=e.generate?.enabled!==!1,r=e.rooms?.enabled!==!1,s=re("video",{class:"ars-video",playsinline:!0,muted:!0,"aria-hidden":"true"}),a=re("canvas",{class:"ars-canvas"}),o=t.backHref?re("a",{class:"ars-back",href:t.backHref},[re("span",{"aria-hidden":"true",text:"\u2190"}),t.backLabel||"Back"]):null,l=re("span",{class:"ars-title",text:t.title||"AR Studio"}),c=re("span",{class:"ars-count",hidden:!0,role:"status","aria-live":"polite"}),h=r?re("button",{type:"button",class:"ars-icon-btn","aria-label":"Open a shared room so other people can build in this scene with you"},[re("span",{"aria-hidden":"true",text:"\u{1F465}"}),re("span",{class:"ars-room-label",text:"Share live"}),re("span",{class:"ars-room-code-label",hidden:!0})]):null,d=re("button",{type:"button",class:"ars-icon-btn",hidden:!0,"aria-label":"Show a QR code that opens this scene on your phone"},[re("span",{"aria-hidden":"true",text:"\u{1F4F1}"}),"Open on phone"]),f=re("button",{type:"button",class:"ars-icon-btn",hidden:!0,"aria-pressed":"false","aria-label":"View this in augmented reality"},[re("span",{"aria-hidden":"true",text:"\u2726"}),re("span",{class:"ars-ar-label",text:"AR"})]),p=re("button",{type:"button",class:"ars-icon-btn","aria-pressed":"false","aria-label":"Turn the camera on to see your models in the room"},[re("span",{"aria-hidden":"true",text:"\u{1F4F7}"}),"Camera"]),x=re("div",{class:"ars-top"},[o,l,c,re("span",{class:"ars-spacer"}),h,d,f,p]),y=re("div",{class:"ars-chip",hidden:!0,"data-state":"idle",role:"status","aria-live":"polite"},[re("span",{class:"ars-spinner","aria-hidden":"true"}),re("span",{class:"ars-chip-label"}),re("span",{class:"ars-chip-elapsed"})]),b=re("button",{type:"button",class:"ars-btn ars-btn-primary"},[re("span",{"aria-hidden":"true",text:"\u{1F4F7}"}),"Turn on the camera"]),g=re("button",{type:"button",class:"ars-btn",text:"Browse models"}),S=n?re("button",{type:"button",class:"ars-btn",text:"Generate one"}):null,A=re("div",{class:"ars-empty"},[re("div",{class:"ars-empty-card"},[re("div",{class:"ars-empty-art","aria-hidden":"true",text:"\u{1FA84}"}),re("h2",{text:"Put anything in your room"}),re("p",{text:n?"Add a model, or describe one and watch it appear. Turn on the camera and it stands on your actual floor.":"Add a model from the library, then turn on the camera and it stands on your actual floor."}),re("div",{class:"ars-empty-row"},[b,g,S])])]),T=re("div",{class:"ars-status",hidden:!0,role:"status","aria-live":"polite"}),N=re("span",{class:"ars-sel-name"}),P=re("div",{class:"ars-selbar",hidden:!0,role:"toolbar","aria-label":"Selected model"},[N,re("button",{type:"button",class:"ars-icon-btn","data-act":"rotate","aria-label":"Rotate the selected model"},[re("span",{"aria-hidden":"true",text:"\u27F3"})]),re("button",{type:"button",class:"ars-icon-btn","data-act":"duplicate","aria-label":"Duplicate the selected model"},[re("span",{"aria-hidden":"true",text:"\u29C9"})]),re("button",{type:"button",class:"ars-icon-btn","data-act":"remove","aria-label":"Remove the selected model"},[re("span",{"aria-hidden":"true",text:"\u2715"})])]),U=re("button",{type:"button",class:"ars-icon-btn","aria-expanded":"false","aria-label":"Add a model to the scene"},[re("span",{"aria-hidden":"true",text:"\uFF0B"}),"Add"]),v=re("input",{class:"ars-forge-input",type:"text",name:"prompt",autocomplete:"off",placeholder:"Describe something to generate\u2026","aria-label":"Describe a 3D model to generate",maxlength:"300"}),I=re("button",{type:"submit",class:"ars-forge-go","aria-label":"Generate this model"},["Make"]),B=n?re("form",{class:"ars-forge-form"},[v,I]):re("span",{class:"ars-spacer"}),k=re("button",{type:"button",class:"ars-icon-btn",disabled:!0,"aria-label":"Take a photo of the scene"},[re("span",{"aria-hidden":"true",text:"\u2B24"})]),V=re("button",{type:"button",class:"ars-icon-btn",hidden:!0,"aria-label":"Remove every model from the scene"},["Clear"]),J=re("div",{class:"ars-dock"},[U,B,k,V]),L=re("div",{class:"ars-tabs",role:"tablist","aria-label":"Model sources"}),E=re("div",{class:"ars-tray-body",role:"tabpanel",tabindex:"-1"}),D=re("button",{type:"button",class:"ars-icon-btn","aria-label":"Close the model browser"},[re("span",{"aria-hidden":"true",text:"\u2715"})]),O=re("div",{class:"ars-tray",hidden:!0,role:"dialog","aria-modal":"true","aria-label":"Add a model"},[re("div",{class:"ars-tray-panel"},[re("div",{class:"ars-tray-head"},[re("h2",{text:"Add a model"}),re("span",{class:"ars-spacer"}),D]),L,E])]),H=re("div",{class:"ars-qr-box"}),Y=re("a",{class:"ars-link-out",target:"_blank",rel:"noopener"}),le=re("button",{type:"button",class:"ars-btn",text:"Done"}),fe=re("div",{class:"ars-modal",hidden:!0,role:"dialog","aria-modal":"true","aria-label":"Open this scene on your phone"},[re("div",{class:"ars-dialog"},[re("h2",{text:"Open this scene on your phone"}),re("p",{text:"Scan it and the same models, in the same arrangement, open on the phone: ready to place in your room."}),H,Y,le])]),be=re("span",{class:"ars-ar-thumb","aria-hidden":"true"}),Te=re("span",{class:"ars-ar-name"}),Je=re("div",{class:"ars-ar-picker",hidden:!0,role:"group","aria-label":"Choose which model to place"}),ke=re("p",{class:"ars-ar-hint"}),oe=re("p",{class:"ars-ar-status",role:"status","aria-live":"polite"}),Ee=re("button",{type:"button",class:"ars-btn ars-btn-primary ars-ar-go"},[re("span",{class:"ars-ar-go-icon","aria-hidden":"true",text:"\u2B21"}),re("span",{class:"ars-ar-go-label",text:"Place in your space"})]),_e=re("button",{type:"button",class:"ars-btn ars-ar-xr",hidden:!0},[re("span",{"aria-hidden":"true",text:"\u2726"}),"Immersive AR: place the whole scene"]),Ze=re("button",{type:"button",class:"ars-btn ars-ar-qr",hidden:!0},[re("span",{"aria-hidden":"true",text:"\u{1F4F1}"}),"Open on your phone"]),tt=re("button",{type:"button",class:"ars-btn ars-ar-done",text:"Done"}),Qe=re("div",{class:"ars-modal",hidden:!0,role:"dialog","aria-modal":"true","aria-label":"Place a model in your space"},[re("div",{class:"ars-dialog ars-ar-sheet"},[re("h2",{class:"ars-ar-heading",text:"Place in your space"}),re("div",{class:"ars-ar-target"},[be,Te]),Je,ke,oe,Ee,_e,Ze,tt])]),Et=re("button",{type:"button",class:"ars-btn ars-btn-primary",text:"Start a shared room"}),it=re("input",{class:"ars-search",type:"text",placeholder:"Room code","aria-label":"Room code",maxlength:"20",autocomplete:"off",spellcheck:"false"}),mt=re("form",{class:"ars-link-row"},[it,re("button",{type:"submit",class:"ars-btn",text:"Join"})]),wt=re("div",{},[re("p",{text:"Open a room and anyone who joins sees the same scene. Every move, resize and rotate syncs live."}),re("div",{class:"ars-dialog-row"},[Et]),re("div",{class:"ars-divider"}),re("p",{text:"Got a code from someone?"}),mt]),lt=re("div",{class:"ars-code"}),Bt=re("p",{}),gt=re("div",{class:"ars-qr-box"}),Yt=re("button",{type:"button",class:"ars-btn ars-btn-primary",text:"Copy invite link"}),q=re("button",{type:"button",class:"ars-btn",text:"Leave room"}),$t=re("div",{hidden:!0},[lt,Bt,gt,re("div",{class:"ars-dialog-row"},[Yt,q])]),ht=re("button",{type:"button",class:"ars-btn",text:"Close"}),Tt=re("div",{class:"ars-modal",hidden:!0,role:"dialog","aria-modal":"true","aria-label":"Shared room"},[re("div",{class:"ars-dialog"},[re("h2",{text:"Build together"}),wt,$t,ht])]),Pe=re("div",{class:"ars-hud"},[x,A,T,y,P,J,O,fe,Qe,Tt]),Ot=re("div",{class:"ars-root"},[s,a,Pe]);t.accent&&Ot.style.setProperty("--ars-accent",t.accent),i.appendChild(Ot);let F=i.ownerDocument.defaultView?.getComputedStyle(i);return F&&F.position==="static"&&(i.style.position="relative"),i!==i.ownerDocument.body&&i.clientHeight<80&&!i.style.height&&(i.style.minHeight=i.style.minHeight||"70vh"),{root:Ot,video:s,canvas:a,hud:Pe,top:x,title:l,count:c,status:T,chip:y,cameraBtn:p,xrBtn:f,qrBtn:d,roomBtn:h,addBtn:U,photoBtn:k,clearBtn:V,forgeForm:n?B:null,forgeInput:n?v:null,forgeGo:n?I:null,empty:A,emptyCamera:b,emptyAdd:g,emptyForge:S,selbar:P,selName:N,tray:O,trayTabs:L,trayBody:E,trayClose:D,qrModal:fe,qrBox:H,qrLink:Y,qrClose:le,arModal:Qe,arThumb:be,arName:Te,arPicker:Je,arHint:ke,arStatus:oe,arGo:Ee,arXr:_e,arQr:Ze,arClose:tt,roomModal:Tt,roomIdle:wt,roomLive:$t,roomCreate:Et,roomJoinForm:mt,roomJoinInput:it,roomCode:lt,roomPresence:Bt,roomQr:gt,roomCopy:Yt,roomLeave:q,roomClose:ht}}Vn();var kf=class{constructor(e,t,n,r,s){this.xrLight=e,this.renderer=t,this.lightProbe=n,this.xrWebGLBinding=null,this.estimationStartCallback=s,this.frameCallback=this.onXRFrame.bind(this);let a=t.xr.getSession();if(r&&"XRWebGLBinding"in window){let o=new Ma(16);e.environment=o.texture;let l=t.getContext();switch(a.preferredReflectionFormat){case"srgba8":l.getExtension("EXT_sRGB");break;case"rgba16f":l.getExtension("OES_texture_half_float");break}this.xrWebGLBinding=new XRWebGLBinding(a,l),this.lightProbe.addEventListener("reflectionchange",()=>{this.updateReflection()})}a.requestAnimationFrame(this.frameCallback)}updateReflection(){let e=this.renderer.properties.get(this.xrLight.environment);if(e){let t=this.xrWebGLBinding.getReflectionCubeMap(this.lightProbe);t&&(e.__webglTexture=t,this.xrLight.environment.needsPMREMUpdate=!0)}}onXRFrame(e,t){if(!this.xrLight)return;t.session.requestAnimationFrame(this.frameCallback);let r=t.getLightEstimate(this.lightProbe);if(r){this.xrLight.lightProbe.sh.fromArray(r.sphericalHarmonicsCoefficients),this.xrLight.lightProbe.intensity=1;let s=Math.max(1,Math.max(r.primaryLightIntensity.x,Math.max(r.primaryLightIntensity.y,r.primaryLightIntensity.z)));this.xrLight.directionalLight.color.setRGB(r.primaryLightIntensity.x/s,r.primaryLightIntensity.y/s,r.primaryLightIntensity.z/s),this.xrLight.directionalLight.intensity=s,this.xrLight.directionalLight.position.copy(r.primaryLightDirection),this.estimationStartCallback&&(this.estimationStartCallback(),this.estimationStartCallback=null)}}dispose(){this.xrLight=null,this.renderer=null,this.lightProbe=null,this.xrWebGLBinding=null}},Lh=class extends pn{constructor(e,t=!0){super(),this.lightProbe=new wo,this.lightProbe.intensity=0,this.add(this.lightProbe),this.directionalLight=new Di,this.directionalLight.intensity=0,this.add(this.directionalLight),this.environment=null;let n=null,r=!1;e.xr.addEventListener("sessionstart",()=>{let s=e.xr.getSession();"requestLightProbe"in s&&s.requestLightProbe({reflectionFormat:s.preferredReflectionFormat}).then(a=>{n=new kf(this,e,a,t,()=>{r=!0,this.dispatchEvent({type:"estimationstart"})})})}),e.xr.addEventListener("sessionend",()=>{n&&(n.dispose(),n=null),r&&this.dispatchEvent({type:"estimationend"})}),this.dispose=()=>{n&&(n.dispose(),n=null),this.remove(this.lightProbe),this.lightProbe=null,this.remove(this.directionalLight),this.directionalLight=null,this.environment=null}}};var Dh=class{constructor({renderer:e,scene:t,baseLights:n=[],onChange:r}){this._renderer=e,this._scene=t,this._baseLights=n,this._onChange=r,this._xrLight=null,this._active=!1,this._savedEnv=t.environment,this._savedIntensities=n.map(s=>s.intensity),this._onEstimationStart=this._onEstimationStart.bind(this),this._onEstimationEnd=this._onEstimationEnd.bind(this)}start(){if(this._xrLight)return;let e=new Lh(this._renderer,!0);e.addEventListener("estimationstart",this._onEstimationStart),e.addEventListener("estimationend",this._onEstimationEnd),this._scene.add(e),this._xrLight=e}get active(){return this._active}_onEstimationStart(){if(this._xrLight){this._active=!0;for(let e of this._baseLights)e.intensity=0;this._xrLight.environment&&(this._scene.environment=this._xrLight.environment),this._onChange?.(!0)}}_onEstimationEnd(){this._active=!1,this._restoreBase(),this._onChange?.(!1)}_restoreBase(){this._baseLights.forEach((e,t)=>{e.intensity=this._savedIntensities[t]}),this._scene.environment=this._savedEnv}dispose(){this._xrLight&&(this._xrLight.removeEventListener("estimationstart",this._onEstimationStart),this._xrLight.removeEventListener("estimationend",this._onEstimationEnd),this._scene.remove(this._xrLight),this._xrLight.dispose?.(),this._xrLight=null),this._restoreBase(),this._active=!1}};Vn();function Pb(i,e,t=30){let n=i||{misses:0,lost:!1};if(e)return{state:{misses:0,lost:!1},changed:n.lost===!0,lost:!1};let r=n.misses+1,s=r>=t;return{state:{misses:r,lost:s},changed:s&&!n.lost,lost:s}}var JT=new Set(["hidden","visible-blurred"]);function Lb(i){return!JT.has(i)}function Ib(i){return i<0?0:i>1?1:i}function Db(i,e,t=0,n=!1){let r=Ib(e),s=n?0:Ib(t),a=n?.94:.86+s*.1,o=n?.5:.34+s*.18;return i.scale=a+(1-a)*r,i.opacity=o+(.96-o)*r,i.dot=r,i.colorMix=r,i}var ZT=.55;function Nb(i,e,t=ZT){let n=i.t+e,r=n>=t?1:n/t,s=1-(1-r)*(1-r);return i.t=n,i.scale=1+s*2,i.opacity=.85*(1-r),i.done=n>=t,i}var qo=class{constructor(e){this._renderer=e,this._mesh=null,this._enabled=!1}static sessionHasDepth(e){return!!e?.enabledFeatures?.includes?.("depth-sensing")}update(){if(this._mesh)return;let e=this._renderer.xr;if(typeof e.hasDepthSensing!="function"||!e.hasDepthSensing())return;let t=e.getDepthSensingMesh?.();t&&this._configure(t)}_configure(e){let t=e.material;t.colorWrite=!1,t.depthWrite=!0,t.depthTest=!1,e.frustumCulled=!1,this._mesh=e,this._enabled=!0}get enabled(){return this._enabled}dispose(){this._mesh&&(this._mesh.geometry?.dispose(),this._mesh.material?.dispose(),this._mesh=null),this._enabled=!1}};function $o(){return{active:!1,startDist:0,baseScale:1,scale:1}}function Nh(i,e,t){if(!Number.isFinite(e)||e<24)return!1;let n=Number.isFinite(t)&&t>0?t:1;return i.active=!0,i.startDist=e,i.baseScale=n,i.scale=n,!0}function Oh(i,e){if(!i.active||!Number.isFinite(e)||e<=0||i.startDist<=0)return null;let t=i.baseScale*(e/i.startDist);return i.scale=Math.min(4,Math.max(.25,t)),i.scale}function Fh(i){return i.active?(i.active=!1,i.scale):null}function Ia(i){let e=i[0].clientX-i[1].clientX,t=i[0].clientY-i[1].clientY;return Math.hypot(e,t)}function eE(){try{return typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches}catch{return!1}}function tE(){try{let e=document.createElement("canvas");e.width=e.height=128;let t=e.getContext("2d"),n=t.createRadialGradient(128/2,128/2,0,128/2,128/2,128/2);return n.addColorStop(0,"rgba(0,0,0,0.42)"),n.addColorStop(.55,"rgba(0,0,0,0.20)"),n.addColorStop(1,"rgba(0,0,0,0)"),t.fillStyle=n,t.fillRect(0,0,128,128),new Ss(e)}catch{return null}}var Uh=class{constructor({renderer:e,scene:t,camera:n,domOverlayRoot:r,getArmedContent:s,onPlaced:a,getScaleTarget:o,onScale:l,onHit:c,onTracking:h,onVisibility:d,onEnd:f,onFrame:p}){this._renderer=e,this._scene=t,this._camera=n,this._domOverlayRoot=r??null,this._getArmedContent=s,this._onPlaced=a,this._getScaleTarget=o,this._onScale=l,this._onHit=c,this._onTracking=h,this._onVisibility=d,this._onEnd=f,this._onFrame=p,this._session=null,this._hitTestSource=null,this._localSpace=null,this._ended=!1,this._paused=!1,this._trackingState={misses:0,lost:!1},this._depthOcclusion=null,this._placements=[],this._latestHit=null,this._latestHitMatrix=new ot,this._hasHit=!1,this._hadHit=!1,this._hitAmount=0,this._reticle=null,this._reticleRing=null,this._reticleDot=null,this._pulseRing=null,this._rv={scale:1,opacity:.9,dot:0,colorMix:0},this._pulse={t:0,scale:1,opacity:0,done:!1,active:!1},this._dimColor=new Ve(8023280),this._lockColor=new Ve(12891645),this._reducedMotion=!1,this._shadowTex=null,this._prevTime=0,this._savedBg=null,this._pinch=$o(),this._pinchEndedAt=-1/0,this._uiTouchActive=!1,this._handleEnd=this._handleEnd.bind(this),this._handleSelect=this._handleSelect.bind(this),this._handleVisibilityChange=this._handleVisibilityChange.bind(this),this._handleTouchStart=this._handleTouchStart.bind(this),this._handleTouchMove=this._handleTouchMove.bind(this),this._handleTouchEnd=this._handleTouchEnd.bind(this),this._handleBeforeSelect=this._handleBeforeSelect.bind(this)}static async isSupported(){try{return!!(navigator.xr&&await navigator.xr.isSessionSupported("immersive-ar"))}catch{return!1}}async start(){let e=this._renderer;e.xr.enabled=!0;let t={requiredFeatures:["hit-test"],optionalFeatures:["anchors","local-floor","depth-sensing","light-estimation"],depthSensing:{usagePreference:["gpu-optimized","cpu-optimized"],dataFormatPreference:["luminance-alpha","float32"]}};this._domOverlayRoot&&(t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:this._domOverlayRoot});let n=await navigator.xr.requestSession("immersive-ar",t);this._session=n,this._ended=!1,this._paused=!1,this._trackingState={misses:0,lost:!1},n.addEventListener("end",this._handleEnd),n.addEventListener("select",this._handleSelect),n.addEventListener("visibilitychange",this._handleVisibilityChange),await e.xr.setSession(n),this._localSpace=await n.requestReferenceSpace("local");let r=await n.requestReferenceSpace("viewer");if(this._hitTestSource=await n.requestHitTestSource({space:r}),this._depthOcclusion=qo.sessionHasDepth(n)?new qo(e):null,this._reducedMotion=eE(),this._hadHit=!1,this._hitAmount=0,this._pulse.active=!1,this._shadowTex=tE(),this._buildReticle(),this._buildPulseRing(),this._savedBg=this._scene.background,this._scene.background=null,e.setClearColor(0,0),this._domOverlayRoot){let s=this._domOverlayRoot;s.addEventListener("touchstart",this._handleTouchStart,{passive:!0}),s.addEventListener("touchmove",this._handleTouchMove,{passive:!0}),s.addEventListener("touchend",this._handleTouchEnd,{passive:!0}),s.addEventListener("touchcancel",this._handleTouchEnd,{passive:!0}),s.addEventListener("beforexrselect",this._handleBeforeSelect)}this._prevTime=0,e.setAnimationLoop((s,a)=>this._tick(s,a))}get placedCount(){return this._placements.length}_tick(e,t){let n=this._renderer,r=this._prevTime?Math.min(.1,(e-this._prevTime)/1e3):.016;if(this._prevTime=e,this._paused){n.render(this._scene,this._camera);return}if(t&&this._localSpace){let s=!!t.getViewerPose(this._localSpace),a=Pb(this._trackingState,s,30);this._trackingState=a.state,a.changed&&this._setTracking(!a.lost)}if(this._onFrame?.(r),t&&this._hitTestSource){let s=t.getHitTestResults(this._hitTestSource),a=s.length>0?s[0].getPose(this._localSpace):null;if(a)this._latestHit=s[0],this._latestHitMatrix.fromArray(a.transform.matrix),this._hadHit=!0,this._reticle&&(this._reticle.visible=!0,this._reticle.position.setFromMatrixPosition(this._latestHitMatrix),this._reticle.quaternion.setFromRotationMatrix(this._latestHitMatrix)),this._setHit(!0);else{this._latestHit=null;let o=this._hadHit&&!this._trackingState.lost;this._reticle&&(this._reticle.visible=o),this._setHit(!1)}}if(t)for(let s of this._placements){if(!s.anchor)continue;let a=t.getPose(s.anchor.anchorSpace,this._localSpace);if(a){let o=a.transform.position;s.group.position.set(o.x,o.y,o.z),s.shadow?.position.set(o.x,o.y+.004,o.z)}}this._updateReticleVisual(e,r),this._updatePulse(r),this._depthOcclusion?.update(),n.render(this._scene,this._camera)}async _handleSelect(){if(!this._latestHit||this._pinch.active||performance.now()-this._pinchEndedAt<350||this._uiTouchActive)return;let e=this._getArmedContent?.();if(!e)return;let t=this._latestHitMatrix.clone();e.position.setFromMatrixPosition(t),e.parent||this._scene.add(e);let n=this._buildShadow();n.position.copy(e.position),n.position.y+=.004,n.scale.setScalar(e.scale.x||1),this._fireConfirmPulse();try{navigator.vibrate?.(15)}catch{}let r=null;try{r=await this._latestHit.createAnchor?.()??null}catch{r=null}this._placements.push({group:e,anchor:r,shadow:n}),this._onPlaced?.(e,{position:{x:e.position.x,y:e.position.y,z:e.position.z},matrix:t},{degraded:r===null})}release(e){let t=this._placements.findIndex(r=>r.group===e);if(t===-1)return;let[n]=this._placements.splice(t,1);try{n.anchor?.delete?.()}catch{}n.shadow&&(this._scene.remove(n.shadow),n.shadow.geometry?.dispose(),n.shadow.material?.dispose())}_scaleTarget(){let e=this._getScaleTarget?.();return e||(this._placements.length?this._placements[this._placements.length-1].group:null)}_handleTouchStart(e){if(e.touches.length===1){this._uiTouchActive=!!e.touches[0].target?.closest?.("[data-xr-ui]");return}if(e.touches.length!==2)return;let t=this._scaleTarget();t&&Nh(this._pinch,Ia(e.touches),t.scale?.x??1)}_handleTouchMove(e){if(!this._pinch.active||e.touches.length!==2)return;let t=Oh(this._pinch,Ia(e.touches));if(t==null)return;let n=this._scaleTarget();if(!n)return;n.scale.setScalar(t),this._placements.find(s=>s.group===n)?.shadow?.scale.setScalar(t),this._onScale?.(t,{final:!1})}_handleTouchEnd(e){(!e.touches||e.touches.length===0)&&(this._uiTouchActive=!1);let t=Fh(this._pinch);t!=null&&(this._pinchEndedAt=performance.now(),this._onScale?.(t,{final:!0}))}_handleBeforeSelect(e){if(this._pinch.active||performance.now()-this._pinchEndedAt<350){e.preventDefault();return}e.target?.closest?.("[data-xr-ui]")&&e.preventDefault()}_buildReticle(){let e=new pn;e.renderOrder=999,e.visible=!1;let t=new xt(new Gr(.08,.11,40).rotateX(-Math.PI/2),new gn({color:this._dimColor.clone(),transparent:!0,opacity:.6,depthTest:!1}));t.renderOrder=999;let n=new xt(new uo(.032,32).rotateX(-Math.PI/2).translate(0,.001,0),new gn({color:this._lockColor.clone(),transparent:!0,opacity:0,depthTest:!1}));n.renderOrder=1e3,e.add(t,n),this._reticle=e,this._reticleRing=t,this._reticleDot=n,this._scene.add(e)}_buildPulseRing(){let e=new xt(new Gr(.1,.13,40).rotateX(-Math.PI/2),new gn({color:this._lockColor.clone(),transparent:!0,opacity:0,depthTest:!1}));e.renderOrder=1001,e.visible=!1,this._pulseRing=e,this._scene.add(e)}_buildShadow(){let e=new mi(.6,.6).rotateX(-Math.PI/2),t=new gn({map:this._shadowTex,color:this._shadowTex?16777215:0,transparent:!0,opacity:.9,depthWrite:!1}),n=new xt(e,t);return n.renderOrder=1,this._scene.add(n),n}_fireConfirmPulse(){this._reducedMotion||!this._pulseRing||(this._pulseRing.position.setFromMatrixPosition(this._latestHitMatrix),this._pulseRing.quaternion.setFromRotationMatrix(this._latestHitMatrix),this._pulse.t=0,this._pulse.active=!0,this._pulseRing.visible=!0)}_updateReticleVisual(e,t){let n=this._reticle;if(!n||!n.visible)return;let r=this._hasHit?1:0,s=Math.min(1,t*(r>this._hitAmount?16:9));this._hitAmount+=(r-this._hitAmount)*s;let a=this._reducedMotion?0:Math.sin(e*.0019)*.5+.5;Db(this._rv,this._hitAmount,a,this._reducedMotion),n.scale.setScalar(this._rv.scale);let o=this._reticleRing.material;o.opacity=this._rv.opacity,o.color.lerpColors(this._dimColor,this._lockColor,this._rv.colorMix),this._reticleDot.material.opacity=this._rv.dot*.95}_updatePulse(e){!this._pulse.active||!this._pulseRing||(Nb(this._pulse,e),this._pulseRing.scale.setScalar(this._pulse.scale),this._pulseRing.material.opacity=this._pulse.opacity,this._pulse.done&&(this._pulse.active=!1,this._pulseRing.visible=!1))}_setHit(e){e!==this._hasHit&&(this._hasHit=e,this._onHit?.(e))}_setTracking(e){!e&&this._reticle&&(this._reticle.visible=!1),this._onTracking?.(e)}_handleVisibilityChange(){let e=Lb(this._session?.visibilityState);this._paused=!e,!e&&this._reticle&&(this._reticle.visible=!1),this._onVisibility?.(e)}async end(){if(this._session)try{await this._session.end()}catch{}}_handleEnd(){if(this._ended)return;this._ended=!0;let e=this._renderer;if(this._session?.removeEventListener("visibilitychange",this._handleVisibilityChange),this._domOverlayRoot){let t=this._domOverlayRoot;t.removeEventListener("touchstart",this._handleTouchStart),t.removeEventListener("touchmove",this._handleTouchMove),t.removeEventListener("touchend",this._handleTouchEnd),t.removeEventListener("touchcancel",this._handleTouchEnd),t.removeEventListener("beforexrselect",this._handleBeforeSelect)}if(this._pinch=$o(),this._pinchEndedAt=-1/0,this._uiTouchActive=!1,e.setAnimationLoop(null),e.xr.enabled=!1,this._hitTestSource){try{this._hitTestSource.cancel()}catch{}this._hitTestSource=null}for(let t of[this._reticleRing,this._reticleDot,this._pulseRing])t?.geometry?.dispose(),t?.material?.dispose();this._reticle&&this._scene.remove(this._reticle),this._pulseRing&&this._scene.remove(this._pulseRing),this._reticle=this._reticleRing=this._reticleDot=this._pulseRing=null,this._pulse.active=!1;for(let t of this._placements){try{t.anchor?.delete?.()}catch{}t.shadow&&(this._scene.remove(t.shadow),t.shadow.geometry?.dispose(),t.shadow.material?.dispose())}this._placements=[],this._shadowTex?.dispose(),this._shadowTex=null,this._depthOcclusion?.dispose(),this._depthOcclusion=null,this._session=null,this._latestHit=null,this._hasHit=!1,this._hadHit=!1,this._hitAmount=0,this._paused=!1,this._trackingState={misses:0,lost:!1},this._scene.background=this._savedBg,e.setClearColor(0,0),this._onEnd?.()}};function Ob({run:i,maxActive:e=5,priorityOf:t=()=>0}){let n=[],r=0,s={run:i,maxActive:e,priorityOf:t};function a(){for(n.length>1&&n.sort((o,l)=>s.priorityOf(o.item)-s.priorityOf(l.item));r<s.maxActive&&n.length;){let o=n.shift();o.cancelled||(r++,Promise.resolve().then(()=>s.run(o.item)).then(o.resolve,o.reject).finally(()=>{r--,a()}))}}return{request(o){return new Promise((l,c)=>{n.push({item:o,resolve:l,reject:c,cancelled:!1}),a()})},cancel(o){let l=0;for(let c of n)!c.cancelled&&o(c.item)&&(c.cancelled=!0,c.reject(new Error("cancelled")),l++);return l},setMaxActive(o){s.maxActive=Math.max(1,o|0),a()},get active(){return r},get pending(){return n.reduce((o,l)=>o+(l.cancelled?0:1),0)}}}Vh();Vn();var mE=Object.freeze(["Hips","Spine","Spine1","Spine2","Neck","Head","LeftShoulder","LeftArm","LeftForeArm","LeftHand","LeftHandIndex1","LeftHandIndex2","LeftHandIndex3","LeftHandMiddle1","LeftHandMiddle2","LeftHandMiddle3","LeftHandPinky1","LeftHandPinky2","LeftHandPinky3","LeftHandRing1","LeftHandRing2","LeftHandRing3","LeftHandThumb1","LeftHandThumb2","LeftHandThumb3","RightShoulder","RightArm","RightForeArm","RightHand","RightHandIndex1","RightHandIndex2","RightHandIndex3","RightHandMiddle1","RightHandMiddle2","RightHandMiddle3","RightHandPinky1","RightHandPinky2","RightHandPinky3","RightHandRing1","RightHandRing2","RightHandRing3","RightHandThumb1","RightHandThumb2","RightHandThumb3","LeftUpLeg","LeftLeg","LeftFoot","LeftToeBase","RightUpLeg","RightLeg","RightFoot","RightToeBase"]),gE=(()=>{let i=new Map;for(let e of mE)i.set(e.toLowerCase(),e);return i})(),gp=new Map(Object.entries({pelvis:"Hips",neck01:"Neck",claviclel:"LeftShoulder",upperarml:"LeftArm",lowerarml:"LeftForeArm",handl:"LeftHand",clavicler:"RightShoulder",upperarmr:"RightArm",lowerarmr:"RightForeArm",handr:"RightHand",thighl:"LeftUpLeg",calfl:"LeftLeg",footl:"LeftFoot",balll:"LeftToeBase",thighr:"RightUpLeg",calfr:"RightLeg",footr:"RightFoot",ballr:"RightToeBase"}));for(let[i,e]of[["thumb","Thumb"],["index","Index"],["middle","Middle"],["ring","Ring"],["pinky","Pinky"]])for(let t=1;t<=3;t++)gp.set(`${i}0${t}l`,`LeftHand${e}${t}`),gp.set(`${i}0${t}r`,`RightHand${e}${t}`);var bE=(()=>{let i=new Map,e=s=>s.replace(/[-_.\s]+/g,"").toLowerCase(),t=(s,a)=>{let o=e(s);i.has(o)||i.set(o,a)},n=[["J_Bip_C_Hips","Hips"],["J_Bip_C_Spine","Spine"],["J_Bip_C_Chest","Spine1"],["J_Bip_C_UpperChest","Spine2"],["J_Bip_C_Neck","Neck"],["J_Bip_C_Head","Head"],["J_Bip_L_Shoulder","LeftShoulder"],["J_Bip_L_UpperArm","LeftArm"],["J_Bip_L_LowerArm","LeftForeArm"],["J_Bip_L_Hand","LeftHand"],["J_Bip_R_Shoulder","RightShoulder"],["J_Bip_R_UpperArm","RightArm"],["J_Bip_R_LowerArm","RightForeArm"],["J_Bip_R_Hand","RightHand"],["J_Bip_L_UpperLeg","LeftUpLeg"],["J_Bip_L_LowerLeg","LeftLeg"],["J_Bip_L_Foot","LeftFoot"],["J_Bip_L_ToeBase","LeftToeBase"],["J_Bip_L_Toes","LeftToeBase"],["J_Bip_R_UpperLeg","RightUpLeg"],["J_Bip_R_LowerLeg","RightLeg"],["J_Bip_R_Foot","RightFoot"],["J_Bip_R_ToeBase","RightToeBase"],["J_Bip_R_Toes","RightToeBase"]];for(let[s,a]of n)t(s,a);for(let[s,a]of[["Thumb","Thumb"],["Index","Index"],["Middle","Middle"],["Ring","Ring"],["Little","Pinky"]])for(let o=1;o<=3;o++)t(`J_Bip_L_${s}${o}`,`LeftHand${a}${o}`),t(`J_Bip_R_${s}${o}`,`RightHand${a}${o}`);for(let[s,a]of[["chest","Spine1"],["lowerChest","Spine1"],["chestLower","Spine1"],["upperChest","Spine2"],["chestUpper","Spine2"],["abdomen","Spine"],["abdomenLower","Spine"],["abdomenUpper","Spine1"],["hip","Hips"],["lowerNeck","Neck"],["upperNeck","Neck"],["neckLower","Neck"],["neckUpper","Neck"],["neckTwist01","Neck"],["neckTwist02","Neck"],["torso","Spine"],["waist","Spine"],["upperTorso","Spine1"],["torsoUpper","Spine1"],["lowerTorso","Hips"],["torsoLower","Hips"],["ribcage","Spine1"],["ribs","Spine1"],["mPelvis","Hips"],["mTorso","Spine"],["mChest","Spine1"],["mNeck","Neck"],["mHead","Head"],["root_M","Hips"],["hip_M","Hips"],["pelvis_M","Hips"],["spine1_M","Spine"],["spine2_M","Spine1"],["spine3_M","Spine2"],["chest_M","Spine2"],["neck_M","Neck"],["head_M","Head"],["spine0","Spine"],["hipMaster","Hips"],["lumbar","Spine"],["thoracic","Spine1"],["sternum","Spine2"],["cervical","Neck"],["cranium","Head"],["skull","Head"]])t(s,a);let r=[["leftUpperArm","LeftArm"],["lUpperArm","LeftArm"],["shoulderL","LeftArm"],["lShldr","LeftArm"],["lShldrBend","LeftArm"],["leftLowerArm","LeftForeArm"],["lLowerArm","LeftForeArm"],["elbowL","LeftForeArm"],["lForeArm","LeftForeArm"],["lForearmBend","LeftForeArm"],["forearmL","LeftForeArm"],["upperArmL","LeftArm"],["wristL","LeftHand"],["lHand","LeftHand"],["lCollar","LeftShoulder"],["collarL","LeftShoulder"],["lClavicle","LeftShoulder"],["leftUpperLeg","LeftUpLeg"],["lUpperLeg","LeftUpLeg"],["hipL","LeftUpLeg"],["lThigh","LeftUpLeg"],["lThighBend","LeftUpLeg"],["leftLowerLeg","LeftLeg"],["lLowerLeg","LeftLeg"],["kneeL","LeftLeg"],["shinL","LeftLeg"],["lShin","LeftLeg"],["lCalf","LeftLeg"],["ankleL","LeftFoot"],["lFoot","LeftFoot"],["leftToes","LeftToeBase"],["toeL","LeftToeBase"],["lToe","LeftToeBase"],["lToeBase","LeftToeBase"],["lArm","LeftArm"],["lShoulder","LeftShoulder"],["lLeg","LeftLeg"],["lUpLeg","LeftUpLeg"],["leftHip","LeftUpLeg"],["leftThigh","LeftUpLeg"],["leftKnee","LeftLeg"],["leftShin","LeftLeg"],["leftCalf","LeftLeg"],["leftAnkle","LeftFoot"],["leftElbow","LeftForeArm"],["leftWrist","LeftHand"],["leftCollar","LeftShoulder"],["leftClavicle","LeftShoulder"],["leftToe","LeftToeBase"],["mCollarLeft","LeftShoulder"],["mShoulderLeft","LeftArm"],["mElbowLeft","LeftForeArm"],["mWristLeft","LeftHand"],["mHipLeft","LeftUpLeg"],["mKneeLeft","LeftLeg"],["mAnkleLeft","LeftFoot"],["mFootLeft","LeftToeBase"],["mToeLeft","LeftToeBase"],["upperLegL","LeftUpLeg"],["lowerLegL","LeftLeg"],["lowerArmL","LeftForeArm"],["scapulaL","LeftShoulder"],["lHip","LeftUpLeg"],["lKnee","LeftLeg"],["lAnkle","LeftFoot"],["lElbow","LeftForeArm"],["lWrist","LeftHand"],["lToes","LeftToeBase"],["humerusL","LeftArm"],["lHumerus","LeftArm"],["ulnaL","LeftForeArm"],["lUlna","LeftForeArm"],["radiusL","LeftForeArm"],["lRadius","LeftForeArm"],["carpusL","LeftHand"],["lCarpus","LeftHand"],["femurL","LeftUpLeg"],["lFemur","LeftUpLeg"],["tibiaL","LeftLeg"],["lTibia","LeftLeg"],["fibulaL","LeftLeg"],["lFibula","LeftLeg"],["talusL","LeftFoot"],["lTalus","LeftFoot"],["tarsusL","LeftFoot"],["lTarsus","LeftFoot"],["calcaneusL","LeftFoot"],["lCalcaneus","LeftFoot"],["metatarsusL","LeftToeBase"],["lMetatarsus","LeftToeBase"]];for(let[s,a]of[["Thumb","Thumb"],["Index","Index"],["Middle","Middle"],["Ring","Ring"],["Pinky","Pinky"],["Little","Pinky"]]){let o=s.toLowerCase();for(let c=1;c<=3;c++){r.push([`l${s}${c}`,`LeftHand${a}${c}`]),r.push([`f_${o}.0${c}.L`,`LeftHand${a}${c}`]),r.push([`${o}.0${c}.L`,`LeftHand${a}${c}`]);let h=["Thumb","Index","Middle","Ring","Pinky"].indexOf(a)+1;h>0&&r.push([`finger${h}-${c}.L`,`LeftHand${a}${c}`])}(a==="Thumb"?["Metacarpal","Proximal","Distal"]:["Proximal","Intermediate","Distal"]).forEach((c,h)=>{r.push([`left${s}${c}`,`LeftHand${a}${h+1}`]),r.push([`${o}_${c.toLowerCase()}.L`,`LeftHand${a}${h+1}`])})}for(let s=1;s<=3;s++)r.push([`lMid${s}`,`LeftHandMiddle${s}`]);for(let[s,a]of[["Thumb","Thumb"],["Index","Index"],["Middle","Middle"],["Ring","Ring"],["Pinky","Pinky"],["Little","Pinky"]]){for(let o=1;o<=3;o++)r.push([`${s}${o}L`,`LeftHand${a}${o}`]),r.push([`${s}Finger${o}L`,`LeftHand${a}${o}`]);r.push([`${s}L`,`LeftHand${a}1`]),r.push([`${s}FingerL`,`LeftHand${a}1`])}for(let[s,a]of r){t(s,a);let o=a.replace(/^Left/,"Right"),l;/^left/.test(s)?l=s.replace(/^left/,"right"):/^l[A-Z]/.test(s)?l="r"+s.slice(1):/Left$/.test(s)?l=s.replace(/Left$/,"Right"):/L$/.test(s)?l=s.replace(/L$/,"R"):l=s,t(l,o)}return i})();function yi(i){if(typeof i!="string"||!i)return null;let e=Yb(i);if(e)return e;let t=i.replace(/[._]\d+$/,"");return t!==i?Yb(t):null}function Yb(i){let e=i;e=e.replace(/^(?:[A-Za-z][\w]*:)+/,""),e=e.replace(/^mixamorig\d*[_:]?/i,""),e=e.replace(/^Armature[_/]?/i,""),e=e.replace(/^(DEF|ORG|MCH)[-_]/i,""),e=e.replace(/^CH[_:]/i,""),e=e.replace(/^CC_Base_/i,""),e=e.replace(/^j_(?!bip|sec|adj)/i,""),e=e.replace(/^\d+\./,"").replace(/^!/,"").replace(/^joint[_:]/i,""),e=e.replace(/^Bip\d+[\s_]?/i,"");let t=e.replace(/[-_.\s]+/g,"").toLowerCase();return gE.get(t)??gp.get(t)??bE.get(t)??null}var xE=/shoulder|clavicle|collar|scapula/i,Jb=/upper.?arm|humerus/i,Zb=/clavicle|collar|scapula/i;function Qb(i,e={}){let t=typeof e.isAncestor=="function"?e.isAncestor:null,n=new Map;for(let o of i)n.set(o.canonical,(n.get(o.canonical)||0)+1);let r=(o,l,c)=>o.length<2||!t?o[0]:o.find(d=>l.some(f=>f!==d&&(c?t(d,f):t(f,d))))||o[0],s=(o,l,c)=>{o.canonical=c,n.set(l,(n.get(l)||1)-1),n.set(c,(n.get(c)||0)+1)},a=0;for(let o of["Left","Right"]){let l=`${o}Arm`,c=`${o}Shoulder`;if((n.get(l)||0)<2||(n.get(c)||0)>0)continue;let h=i.filter(x=>x.canonical===l),d=h.filter(x=>Jb.test(x.raw));if(d.length===0)continue;let f=h.filter(x=>xE.test(x.raw)&&!Jb.test(x.raw)),p=r(f,d,!0);p&&(s(p,l,c),a++)}for(let o of["Left","Right"]){let l=`${o}Arm`,c=`${o}Shoulder`;if((n.get(c)||0)<2||(n.get(l)||0)>0)continue;let h=i.filter(x=>x.canonical===c),d=h.filter(x=>Zb.test(x.raw));if(d.length===0)continue;let f=h.filter(x=>/shoulder/i.test(x.raw)&&!Zb.test(x.raw)),p=r(f,d,!1);p&&(s(p,c,l),a++)}return a}Vn();var ex=Object.freeze({Head:[-.11706881878098431,9438845082943482e-24,372654613409334e-22,.993123804804428],Hips:[.0010741148761599644,6537898515070053e-23,7022659074474357e-26,.9999994231384476],LeftArm:[-.003089573263103852,.08018148459223169,-.025041829737156785,.9964608827384491],LeftFoot:[.5523737034239063,.0002518875693487157,.0036538113016644914,.8335885543726441],LeftForeArm:[-26826767953574183e-23,12816740072681333e-23,.012369379808617674,.9999234962951223],LeftHand:[-.0012910117424963744,.002537815819541244,.010116448936771993,.9999447735952517],LeftHandIndex1:[.028803290204768833,.011362422123976328,.055965724298468224,.9979524555518633],LeftHandIndex2:[-.005195237841915152,.014315447122751807,.00021581682553071412,.9998840087229335],LeftHandIndex3:[-.0013151015878908295,-.016941197343945148,-.006458334440614796,.9998347644768737],LeftHandMiddle1:[.027532617383276645,-.031607746403852485,.016931179482824785,.9989775976007271],LeftHandMiddle2:[-.001267981765488788,.0010468621884392817,-.004466175725402764,.9999886747239598],LeftHandMiddle3:[-.0015803533040544947,.0018352886876119797,.0038040706030556736,.9999898315711762],LeftHandPinky1:[.009345046842530319,-.07377447953394943,-.04207784173776388,.9963430390695086],LeftHandPinky2:[-.0019002180814112143,.0002770864318134059,.0004968185265866393,.9999980327809131],LeftHandPinky3:[-.0014157518824255099,-.005595319155644295,-.004606740515194791,.9999727326242506],LeftHandRing1:[.018207541076892743,-.03436008716699126,-.036855349348364555,.9985637451229231],LeftHandRing2:[-.0006571286469542868,.015477225242721515,.01003471962236163,.9998296495318929],LeftHandRing3:[.001815607007583071,-.003099595768579846,.0072046170631637615,.999967594260012],LeftHandThumb1:[.1900227602341495,-.058826116539083484,.3478783626049766,.9161940209594684],LeftHandThumb2:[.01801363066187901,-.020968588375318502,-.22063576333056306,.9749644544258214],LeftHandThumb3:[-.014498565873099356,.03466160908487025,.011599642488048602,.9992266072970502],LeftLeg:[-.022987686472704008,-.0006608912898930547,7960712093047862e-20,.9997355266049326],LeftShoulder:[.5181706903502131,.5134387363832796,-.48299308003518876,.4843526489955184],LeftToeBase:[.23652217735689587,.0006644108661216591,-.002051152932444189,.9716236982227819],LeftUpLeg:[-4952055077835167e-20,.0032567616062252223,.9999946186652781,-.00039203576089550014],Neck:[.2225107795455935,-23352293238692193e-23,-19647139012020554e-24,.974930229804142],RightArm:[-.003089570938390283,-.08018164882954634,.025041835809991725,.9964608693782484],RightFoot:[.5523737112340288,-.00025188760500252676,-.0036538107149212758,.8335885491999105],RightForeArm:[-2706717415294191e-22,60675494372234465e-25,-.012369382961452784,.9999234962561284],RightHand:[-.0012910114923260908,-.002537815924782367,-.010116450486313036,.9999447735796301],RightHandIndex1:[.028803284769926347,-.01136242475457741,-.05596571258489258,.9979524563349205],RightHandIndex2:[-.005195229421057241,-.014315442233259087,-.00021582506177354608,.9998840088349297],RightHandIndex3:[-.0013151045827228072,.016941319655899355,.006458327385746035,.9998347624459482],RightHandMiddle1:[.027532662650122483,.03160778647114273,-.01693120529165708,.9989775946478099],RightHandMiddle2:[-.0012680273836480952,-.0010469047250576836,.004466199390698661,.9999886745158897],RightHandMiddle3:[-.0015803562094451136,-.001835288773706009,-.003804068167924464,.9999898315756854],RightHandPinky1:[.009345030274151258,.07377446325595405,.04207784564870347,.9963430402658229],RightHandPinky2:[-.0019002008217559384,-.0002769620503994165,-.0004968229018870381,.9999980328459891],RightHandPinky3:[-.0014157497333212687,.0055951881780210025,.004606743315319843,.9999727333471813],RightHandRing1:[.01820754441109714,.03436008722907556,.03685535429214536,.9985637448787448],RightHandRing2:[-.0006571335802527884,-.015477230302375519,-.010034723368684675,.999829649412505],RightHandRing3:[.0018156069598940002,.003099598646436032,-.007204626788931167,.9999675941811231],RightHandThumb1:[.19002276085311107,.05882618704962336,-.3478783387552461,.9161940229953188],RightHandThumb2:[.018013663274561078,.020968550782212388,.22063584956274163,.9749644350943654],RightHandThumb3:[-.014498582331377526,-.03466161961137741,-.011599713293476643,.9992266058762234],RightLeg:[-.022987685898989207,.0006609402907891899,-7960698692017099e-20,.9997355265857409],RightShoulder:[.5181706006117709,-.5134387953473804,.4829931766210871,.4843525890882128],RightToeBase:[.23652222014073046,-.0006644109035597298,.0020511526077556528,.9716236878087238],RightUpLeg:[49438593286575395e-21,.003256759408127677,.9999946186765544,.0003920356017771739],Spine:[-.018332562694809717,-14544833124647894e-23,26976261645093277e-26,.9998319444511763],Spine1:[-.03815628571181615,20010687323521798e-24,534807122500512e-23,.9992717837809081],Spine2:[-.056998031890724846,13546308636882866e-23,-8861325315468363e-25,.9983742907149431]}),tx=Object.freeze({Head:[-.005402766806732544,-15440620455356296e-23,834223242528311e-24,.9999854049488961],Hips:[.0010741148761599644,6537898515070053e-23,7022659074474357e-26,.9999994231384476],LeftArm:[.4889318420664182,.5108287295941205,-.5108290884863605,.48893078190839623],LeftFoot:[-7112359875637768e-20,.5349085331963127,.8448985998862468,-.004383145577274271],LeftForeArm:[.49521300584988104,.5047420653526237,-.5047420379230214,.4952120815979495],LeftHand:[.5009334720626235,.5016127781291206,-.4977959877649929,.49964931327533474],LeftHandIndex1:[.5480286232738694,.46388966319384123,-.47756977349452234,.506357703809076],LeftHandIndex2:[.5522711480640051,.4734474077351049,-.46714980714345783,.5026083894226862],LeftHandIndex3:[.5405471533897316,.46903549072233974,-.4790521335412708,.5082553896043159],LeftHandMiddle1:[.5069366564823887,.46312011824587895,-.5184714785961669,.5096295836965867],LeftHandMiddle2:[.5047591066222094,.46656986579426646,-.5196237813564338,.5074661907650336],LeftHandMiddle3:[.5066805225023663,.46639751835165716,-.5160243364733309,.509379123507728],LeftHandPinky1:[.4459394011607033,.4793433042957962,-.5586434331057456,.5092009093395086],LeftHandPinky2:[.4453638702749085,.48032344738196137,-.5573549331147079,.5101920146245817],LeftHandPinky3:[.4392981168466072,.4802964151504903,-.5615019919023976,.5109286011992389],LeftHandRing1:[.47371996160924823,.4931227775910745,-.5418410288696247,.4886999364902444],LeftHandRing2:[.48665266892609377,.49620490515614146,-.5291888435031511,.48673303168821197],LeftHandRing3:[.48945530931580683,.4902132045285772,-.5280743092981476,.4911843263440915],LeftHandThumb1:[.6991138207882592,.16132571576360077,-.40704633814367386,.5652673372230799],LeftHandThumb2:[.64766423234777,.2923511094450446,-.5391393932239583,.4520957758831027],LeftHandThumb3:[.6626872004096495,.3080994487427915,-.5067905211225114,.45725679518685386],LeftLeg:[.0006202111480182034,-.020805293540463354,.9997832430476497,-.00047118992773536965],LeftShoulder:[.4605450937998788,.4559956590278878,-.537559006794696,.5394409087622226],LeftToeBase:[-.002764355526654178,.7195640056310856,.6944147145329627,-.0028643286082629046],LeftUpLeg:[-4987623525000119e-20,.0021826506059020026,.9999975399461294,-.00039198262713485737],Neck:[.11170149382802401,-1628868597421303e-22,-18309282630496044e-24,.9937418056399563],RightArm:[.48893190585215524,-.510828798312402,.5108290283825504,.48893071200502375],RightFoot:[7112360405196955e-20,.5349085398019146,.844898595705669,.004383145306035045],RightForeArm:[.4952130023257164,-.5047420673116668,.5047420415306929,.49521208229448166],RightHand:[.5009334695181179,-.5016127792807403,.49779599067075153,.49964931459617906],RightHandIndex1:[.5480286139806538,-.4638896746971551,.47756977858103167,.5063577013132781],RightHandIndex2:[.5522711446711094,-.4734474082706649,.4671498147721218,.5026083883587248],RightHandIndex3:[.5405470934413514,-.4690354263302402,.47905220274050364,.5082554503330304],RightHandMiddle1:[.5069366680435416,-.4631200623546733,.5184715098400317,.5096295939664325],RightHandMiddle2:[.5047591061928465,-.46656986723577604,.5196237819671778,.5074661920185282],RightHandMiddle3:[.5066805195140975,-.4663975225827095,.5160243369168757,.5093791249234989],RightHandPinky1:[.44593939683725603,-.4793433241517071,.5586434219640141,.5092009094272859],RightHandPinky2:[.4453638073881448,-.4803233923217868,.5573549834847424,.5101920690951159],RightHandPinky3:[.4392981269307416,-.4802964267888911,.5615019867791732,.5109285899785551],RightHandRing1:[.473719957983008,-.49312277921221886,.541841035805614,.4886999335659278],RightHandRing2:[.48665266754747677,-.4962049100848307,.5291888437972645,.4867330306200585],RightHandRing3:[.4894553112113337,-.49021320332208906,.5280743062058759,.4911843318554558],RightHandThumb1:[.6991137732035737,-.16132569450370315,.40704638897707807,.5652673641991798],RightHandThumb2:[.6476641963757893,-.2923511418798965,.5391394672107036,.45209571648691005],RightHandThumb3:[.6626871862817486,-.3080994479425299,.5067905521115058,.4572567801626834],RightLeg:[-.0006202113471683521,-.020805295090456907,.9997832430151556,.00047119017271936915],RightShoulder:[.46054507521936333,-.45599564278848104,.5375590232993736,.5394409245169026],RightToeBase:[.0027643555231566678,.7195640416379069,.6944146772223956,.0028643286020973192],RightUpLeg:[49925034443819034e-21,.002182648459062353,.9999975399486299,.00039198198974856475],Spine:[-.017258617754264162,-800818266828763e-22,13823133775055108e-25,.9998510589648868],Spine1:[-.055396652424023016,-5997624651397324e-23,332759956947242e-23,.9984644264570511],Spine2:[-.11221710079276989,7513757486198981e-23,-8485311473269302e-24,.9936837134066652]}),UP=Object.freeze({Head:[0,1.644459,-.02811],Hips:[0,.984089,.005022],LeftArm:[.204124,1.50826,-.034115],LeftFoot:[.095793,.088025,-.010018],LeftForeArm:[.458234,1.508259,-.045252],LeftHand:[.725837,1.508259,-.050352],LeftHandIndex1:[.815413,1.499602,-.024435],LeftHandIndex2:[.847794,1.497747,-.020782],LeftHandIndex3:[.872293,1.496601,-.017998],LeftHandMiddle1:[.820067,1.500491,-.048839],LeftHandMiddle2:[.854745,1.498698,-.047572],LeftHandMiddle3:[.881683,1.49736,-.046832],LeftHandPinky1:[.810112,1.495569,-.08743],LeftHandPinky2:[.8359,1.495002,-.089537],LeftHandPinky3:[.856018,1.494638,-.091171],LeftHandRing1:[.81666,1.499944,-.069059],LeftHandRing2:[.850313,1.498728,-.071468],LeftHandRing3:[.87354,1.497943,-.072665],LeftHandThumb1:[.761831,1.487283,-.024616],LeftHandThumb2:[.783931,1.477329,-.003377],LeftHandThumb3:[.806009,1.466616,.003515],LeftLeg:[.09541,.505427,.007362],LeftShoulder:[.056656,1.508576,-.035092],LeftToeBase:[.096919,.022281,.128921],LeftUpLeg:[.095072,.936186,.005482],Neck:[0,1.516499,-.057245],RightArm:[-.204124,1.50826,-.034115],RightFoot:[-.095793,.088025,-.010018],RightForeArm:[-.458234,1.508259,-.045252],RightHand:[-.725837,1.508259,-.050352],RightHandIndex1:[-.815413,1.499602,-.024435],RightHandIndex2:[-.847794,1.497747,-.020783],RightHandIndex3:[-.872293,1.496601,-.017998],RightHandMiddle1:[-.820067,1.500491,-.048839],RightHandMiddle2:[-.854745,1.498698,-.047572],RightHandMiddle3:[-.881683,1.49736,-.046832],RightHandPinky1:[-.810112,1.495569,-.08743],RightHandPinky2:[-.8359,1.495002,-.089537],RightHandPinky3:[-.856018,1.494638,-.091171],RightHandRing1:[-.81666,1.499944,-.069059],RightHandRing2:[-.850313,1.498729,-.071468],RightHandRing3:[-.87354,1.497943,-.072665],RightHandThumb1:[-.761831,1.487283,-.024615],RightHandThumb2:[-.783931,1.477329,-.003377],RightHandThumb3:[-.806009,1.466616,.003515],RightLeg:[-.09541,.505427,.007362],RightShoulder:[-.056656,1.508576,-.035092],RightToeBase:[-.096919,.022281,.128921],RightUpLeg:[-.095072,.936186,.005482],Spine:[0,1.077013,.005222],Spine1:[0,1.184494,.00151],Spine2:[0,1.330917,-.014788]}),kP=Object.freeze({Head:"Neck",Hips:null,LeftArm:"LeftShoulder",LeftFoot:"LeftLeg",LeftForeArm:"LeftArm",LeftHand:"LeftForeArm",LeftHandIndex1:"LeftHand",LeftHandIndex2:"LeftHandIndex1",LeftHandIndex3:"LeftHandIndex2",LeftHandMiddle1:"LeftHand",LeftHandMiddle2:"LeftHandMiddle1",LeftHandMiddle3:"LeftHandMiddle2",LeftHandPinky1:"LeftHand",LeftHandPinky2:"LeftHandPinky1",LeftHandPinky3:"LeftHandPinky2",LeftHandRing1:"LeftHand",LeftHandRing2:"LeftHandRing1",LeftHandRing3:"LeftHandRing2",LeftHandThumb1:"LeftHand",LeftHandThumb2:"LeftHandThumb1",LeftHandThumb3:"LeftHandThumb2",LeftLeg:"LeftUpLeg",LeftShoulder:"Spine2",LeftToeBase:"LeftFoot",LeftUpLeg:"Hips",Neck:"Spine2",RightArm:"RightShoulder",RightFoot:"RightLeg",RightForeArm:"RightArm",RightHand:"RightForeArm",RightHandIndex1:"RightHand",RightHandIndex2:"RightHandIndex1",RightHandIndex3:"RightHandIndex2",RightHandMiddle1:"RightHand",RightHandMiddle2:"RightHandMiddle1",RightHandMiddle3:"RightHandMiddle2",RightHandPinky1:"RightHand",RightHandPinky2:"RightHandPinky1",RightHandPinky3:"RightHandPinky2",RightHandRing1:"RightHand",RightHandRing2:"RightHandRing1",RightHandRing3:"RightHandRing2",RightHandThumb1:"RightHand",RightHandThumb2:"RightHandThumb1",RightHandThumb3:"RightHandThumb2",RightLeg:"RightUpLeg",RightShoulder:"Spine2",RightToeBase:"RightFoot",RightUpLeg:"Hips",Spine:"Hips",Spine1:"Spine",Spine2:"Spine1"});var _E=.5,yE=new Map(Object.entries(ex).map(([i,e])=>[i,new Pt(e[0],e[1],e[2],e[3])])),vE=new Map(Object.entries(tx).map(([i,e])=>[i,new Pt(e[0],e[1],e[2],e[3])])),bp=1e-6,nx="morphTargetInfluences[",Wh=new W,Ns=new Pt;function SE(i,e){for(let t=e?.parent;t;t=t.parent)if(t===i)return!0;return!1}function xp(i){let e=[],t=new Set,n=a=>{if(!a?.name||t.has(a))return;t.add(a);let o=yi(a.name);o&&e.push({node:a,raw:a.name,canonical:o})},r=[];i.traverse(a=>{a.isSkinnedMesh&&r.push(a),a.isBone&&n(a)});for(let a of r)for(let o of a.skeleton?.bones||[])n(o);Qb(e,{isAncestor:(a,o)=>SE(a.node,o.node)});let s=new Set;return e.filter(a=>s.has(a.canonical)?!1:(s.add(a.canonical),!0))}function ix(i){let e=new Map;for(let{canonical:t,node:n}of xp(i))e.set(t,n.name);return e}function rx(i){let e=new Map;for(let{canonical:t,node:n}of xp(i))e.set(t,n.quaternion.clone());return e}function wE(i,e){let t=i.quaternion.clone();for(let n=i.parent;n&&n!==e;n=n.parent)t.premultiply(n.quaternion);return t}function sx(i){let e=new Map;for(let{canonical:t,node:n}of xp(i))e.set(t,wE(n,i));return e}function ax(i){let e=new Map;return i.traverse(t=>{if(!(!t?.morphTargetDictionary||!t.name))for(let n of Object.keys(t.morphTargetDictionary)){e.has(n)||e.set(n,[]);let r=e.get(n);r.includes(t.name)||r.push(t.name)}}),e}function ME(i,e){let t=new Map;if(!(i instanceof Map))return t;let n=e instanceof Map;for(let[r,s]of yE){let a=i.get(r);if(!a)continue;let o=vE.get(r),l=n?e.get(r):null,c,h=null;o&&l?(c=a.clone().multiply(l.clone().invert()).multiply(o).multiply(s.clone().invert()),h=o.clone().invert().multiply(l),1-Math.abs(h.w)<bp&&(h=null)):c=a.clone().multiply(s.clone().invert());let d=1-Math.abs(c.w)<bp;d&&!h||t.set(r,{L:d?null:c,R:h})}return t}function AE(i,{L:e,R:t}){for(let n=0;n<i.length;n+=4)Ns.set(i[n],i[n+1],i[n+2],i[n+3]),e&&Ns.premultiply(e),t&&Ns.multiply(t),i[n]=Ns.x,i[n+1]=Ns.y,i[n+2]=Ns.z,i[n+3]=Ns.w}function TE(i,e){for(let t=0;t<i.length;t+=3)Wh.set(i[t],i[t+1],i[t+2]).applyQuaternion(e),i[t]=Wh.x,i[t+1]=Wh.y,i[t+2]=Wh.z}function EE(i,e){if(i){let t=i.isQuaternion?i.clone():new Pt(i[0],i[1],i[2],i[3]);return t.invert(),1-Math.abs(t.w)<bp?null:t}return e.get("Hips")?.L||null}function ox(i){let e=null;if(i.traverse(n=>{!e&&n.isBone&&n.name&&yi(n.name)==="Hips"&&(e=n)}),e||i.traverse(n=>{!e&&n.name&&yi(n.name)==="Hips"&&(e=n)}),!e||!e.parent)return null;let t=new Pt;for(let n=e.parent;n&&n!==i;n=n.parent)t.premultiply(n.quaternion);return t}function cx(i){try{return new rn().setFromObject(i).min.y}catch{return NaN}}var Da=new W,RE=new Pt,qh=new W;function _p(i){let e=null;if(i.traverse(s=>{!e&&s.isBone&&s.name&&yi(s.name)==="Hips"&&(e=s)}),e||i.traverse(s=>{!e&&s.name&&yi(s.name)==="Hips"&&(e=s)}),!e||!e.parent)return 0;e.updateWorldMatrix(!0,!1),e.getWorldPosition(Da);let t=Da.y,n=cx(i);Number.isFinite(n)&&(t-=n),e.parent.matrixWorld.decompose(Da,RE,qh);let r=(qh.x+qh.y+qh.z)/3;return!(r>1e-6)||!(t>0)||!Number.isFinite(t)?0:t/r}function yp(i){let e=null;if(i.traverse(r=>{!e&&r.isBone&&r.name&&yi(r.name)==="Hips"&&(e=r)}),e||i.traverse(r=>{!e&&r.name&&yi(r.name)==="Hips"&&(e=r)}),!e||!e.parent)return 0;e.updateWorldMatrix(!0,!1);let t=cx(i);if(!Number.isFinite(t))return 0;e.getWorldPosition(Da);let n=e.parent.worldToLocal(new W(Da.x,t,Da.z));return Number.isFinite(n.y)?n.y:0}function lx(i){let e=i.tracks.find(t=>t.name.endsWith(".position")&&yi(t.name.split(".")[0])==="Hips");return!e||e.values.length<3?0:e.values[1]}function hx(i,e,t={}){let n=Number.isFinite(t.hipScale)&&t.hipScale>0?t.hipScale:1,r=Number.isFinite(t.hipOffsetY)?t.hipOffsetY:0,s=t.minCoverage??_E,a=ME(t.targetRest,t.targetWorldRest),o=EE(t.hipsParentWorldQuat,a),l=[],c=[],h=[],d=0;for(let y of i.tracks){let b=y.name.indexOf(".");if(b===-1)continue;let g=y.name.slice(0,b),S=y.name.slice(b+1);if(S.startsWith(nx)){let U=S.slice(nx.length,-1),v=t.morphTargets instanceof Map?t.morphTargets.get(U):null;if(!v?.length){l.push(U);continue}for(let I of v){let B=y.clone();B.name=`${I}.${S}`,h.push(B)}continue}let A=yi(g)||g;if(!(S==="quaternion"||S==="position"&&A==="Hips"))continue;d++;let N=e.get(A);if(!N){l.push(A);continue}let P=y.clone();if(P.name=`${N}.${S}`,S==="quaternion"){let U=a.get(A);U&&AE(P.values,U)}else{if(o&&TE(P.values,o),n!==1)for(let U=0;U<P.values.length;U++)P.values[U]*=n;if(r!==0)for(let U=1;U<P.values.length;U+=3)P.values[U]+=r}c.push(P)}let f=c.length,p=d>0?f/d:0;if(p<s)return{clip:null,matched:f,total:d,coverage:p,dropped:l,hipScale:n,face:0};let x=i.clone();return x.tracks=[...c,...h],{clip:x,matched:f,total:d,coverage:p,dropped:l,hipScale:n,face:h.length}}Vn();var CE=.6,IE=.38,PE=-.4,vp=new W,ux=new W,dx=new W,fx=new W,px=new Pt,mx=new Pt,Sp=new Pt;function LE(i){for(let e of i.children)if(e.isBone)return e;return null}function gx(i,e){if(!i||e&&(e.has("LeftArm")||e.has("RightArm")))return 0;i.updateMatrixWorld(!0);let t=[],n=1/0,r=-1/0;if(i.traverse(c=>{if(!c.isBone)return;let h=LE(c);if(!h)return;c.getWorldPosition(vp),h.getWorldPosition(ux);let d=ux.clone().sub(vp),f=d.length();if(f<1e-5)return;d.multiplyScalar(1/f);let p=vp.y;p<n&&(n=p),p>r&&(r=p),t.push({bone:c,worldY:p,dir:d})}),t.length===0||!Number.isFinite(n)||r<=n)return 0;let s=(n+r)/2,a=null,o=null;for(let c of t){let{dir:h,worldY:d}=c;d<s||Math.abs(h.y)>IE||h.y<PE||Math.abs(h.x)<CE||(h.x>0?(!a||h.x>a.dir.x)&&(a=c):(!o||h.x<o.dir.x)&&(o=c))}let l=0;for(let c of[a,o])c&&DE(c.bone,c.dir)&&l++;return l}function DE(i,e){let t=e.x>=0?1:-1;fx.set(t*.14,-1,.1).normalize(),dx.copy(e),px.setFromUnitVectors(dx,fx),i.getWorldQuaternion(mx),i.parent?i.parent.getWorldQuaternion(Sp):Sp.identity();let n=px.multiply(mx),r=Sp.invert().multiply(n);return i.quaternion.copy(r),i.updateMatrixWorld(!0),!0}var NE=45,bx=new W,xx=new Pt,_x=new W(0,1,0);function OE(i,e,t){if(!i||!e||!t)return null;let n=t.get("Hips");if(!n)return null;let r=e.getObjectByName(n);if(!r)return null;let s=i.tracks.find(f=>f.name===`${n}.quaternion`);if(!s||s.values.length<4)return null;let a=s.values,o=r.quaternion.x,l=r.quaternion.y,c=r.quaternion.z,h=r.quaternion.w;r.quaternion.set(a[0],a[1],a[2],a[3]),r.updateWorldMatrix(!0,!1),r.getWorldQuaternion(xx),bx.copy(_x).applyQuaternion(xx),r.quaternion.set(o,l,c,h),r.updateWorldMatrix(!0,!1);let d=Math.max(-1,Math.min(1,bx.dot(_x)));return Math.acos(d)*180/Math.PI}var FE=8,UE=Object.freeze(["Hips","LeftUpLeg","LeftLeg","LeftFoot","LeftToeBase","RightUpLeg","RightLeg","RightFoot","RightToeBase"]),yx=.35,$h=new Map,jh=class i{constructor(){this.model=null,this.mixer=null,this.clips=new Map,this.actions=new Map,this.currentName=null,this.currentAction=null,this.onChange=null,this._animationDefs=[],this._failed=new Set,this._canonicalToNode=null,this._canonicalClipsSupported=!1,this._avatarContext={},this._fallenReported=new Set,this._fallen=new Set,this._latestCrossfadeTarget=null,this.overlayAction=null,this.overlayName=null,this._overlayClips=new Map,this._overlayFinishHandler=null,this._settleFinishHandler=null}setAvatarContext(e){this._avatarContext=e&&typeof e=="object"?{...e}:{}}attach(e,t){this.detach(),t&&this.setAvatarContext(t),this.model=e,this.mixer=new Ms(e),this.actions.clear(),this.currentAction=null,this.currentName=null,this._fallen.clear(),this._canonicalToNode=ix(e),this._canonicalRest=rx(e),this._canonicalWorldRest=sx(e),this._hipsParentWorldQuat=ox(e),this._morphTargets=ax(e),this._hipTargetLocalY=_p(e),this._hipGroundLocalY=yp(e),this._canonicalClipsSupported=kE(e);for(let[n,r]of this.clips){let s=this._retarget(r);if(!s)continue;let a=this.mixer.clipAction(s);a.enabled=!0,this.actions.set(n,a)}}remeasureRigProportions(){if(!this.model||!this.mixer)return!1;let e=this.currentName;this._hipTargetLocalY=_p(this.model),this._hipGroundLocalY=yp(this.model),this.mixer.stopAllAction();for(let t of this.actions.values()){let n=t.getClip?.();n&&this.mixer.uncacheClip(n)}this.actions.clear(),this.currentAction=null,this.currentName=null,this._latestCrossfadeTarget=null,this.overlayAction=null,this.overlayName=null,this._overlayClips.clear(),this._detachOverlayFinish?.();for(let[t,n]of this.clips){let r=this._retarget(n);if(!r)continue;let s=this.mixer.clipAction(r);s.enabled=!0,this.actions.set(t,s)}return e&&this.actions.has(e)&&this.play(e),!0}_retarget(e){if(!this._canonicalToNode||this._canonicalToNode.size===0)return null;let t=1,n=lx(e);this._hipTargetLocalY>.05&&n>.05&&(t=Math.min(200,Math.max(.2,this._hipTargetLocalY/n)));let{clip:r}=hx(e,this._canonicalToNode,{targetRest:this._canonicalRest,targetWorldRest:this._canonicalWorldRest,hipsParentWorldQuat:this._hipsParentWorldQuat,morphTargets:this._morphTargets,hipScale:t,hipOffsetY:this._hipGroundLocalY||0});return r}_guardAgainstFallenPose(e,t){if(this._fallen.has(e))return!1;let n=t?.getClip?.(),r=OE(n,this.model,this._canonicalToNode);if(r==null||!Number.isFinite(r)||r<=NE)return!0;try{t.stop()}catch(l){ei.warn("[AnimationManager] failed to stop fallen-pose action:",l)}t.enabled=!1,this.actions.delete(e),this._fallen.add(e),this.currentAction===t&&(this.currentAction=null,this.currentName=null);let s=this._avatarContext.avatarUrl||"",a=this._avatarContext.avatarId||"",o=`${a||s}|${e}`;return this._fallenReported.has(o)||(this._fallenReported.add(o),ei.warn(`[AnimationManager] "${e}" retargeted to a fallen pose (${r.toFixed(1)}\xB0 off vertical): falling back to bind pose`),BE({avatarId:a,avatarUrl:s,clip:e,tiltDeg:Math.round(r*10)/10})),!1}detach(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this.mixer.getRoot()),this.mixer=null),this.model=null,this._canonicalToNode=null,this._canonicalRest=null,this._canonicalWorldRest=null,this._hipsParentWorldQuat=null,this._morphTargets=null,this._hipTargetLocalY=0,this._hipGroundLocalY=0,this._canonicalClipsSupported=!1,this.actions.clear(),this.currentAction=null,this.currentName=null,this._latestCrossfadeTarget=null,this._fallen.clear(),this.overlayAction=null,this.overlayName=null,this._overlayClips.clear(),this._overlayFinishHandler=null}setAnimationDefs(e){this._animationDefs=e}appendAnimationDefs(e){let t=new Set(this._animationDefs.map(n=>n.name));for(let n of e)t.has(n.name)||(this._animationDefs.push(n),t.add(n.name))}getAnimationDefs(){return this._animationDefs}isFailed(e){return this._failed.has(e)}supportsCanonicalClips(){return this._canonicalClipsSupported}relaxUndrivenArms(){return this.model?gx(this.model,this._canonicalToNode):0}canPlay(e){return this._fallen.has(e)?!1:this.clips.has(e)?!0:this._failed.has(e)?!1:this._animationDefs.some(t=>t.name===e)}async loadAnimation(e,t,n={}){if(this.clips.has(e))return this.clips.get(e);let r=$h.get(t);r||(r=i._fetchClip(e,t),$h.set(t,r),r.catch(()=>{$h.get(t)===r&&$h.delete(t)}));let s=await r;return this._registerParsedClip(e,s,n)}static async _fetchClip(e,t){let n=t.includes("/api/animations/"),r=new AbortController,s=setTimeout(()=>r.abort(),15e3),a;try{a=await fetch(t,{signal:r.signal,credentials:n?"include":"same-origin",redirect:"error"})}finally{clearTimeout(s)}if(!a.ok)throw new Error(`HTTP ${a.status} loading animation ${e}`);let o=await a.json(),l=n?o?.clip?.clip:o;if(!l&&o?.clip?.paywalled)throw new Error(`animation ${e} is a paid clip, unlock it at ${o.clip.download_url}`);if(!l)throw new Error(`clip payload missing from ${t}`);let c=bi.parse(l);return c.name=e,c}injectClip(e,t,n={}){if(!(!t||this.clips.has(e)))try{let r=bi.parse(t);r.name=e,this._registerParsedClip(e,r,n)}catch(r){ei.warn(`[AnimationManager] injectClip "${e}" parse error:`,r.message)}}_registerParsedClip(e,t,n){if(this.clips.set(e,t),this.model&&this.mixer){let r=this._retarget(t);if(r){let s=this.mixer.clipAction(r);s.enabled=!0,s.setLoop(n.loop===!1?_a:Fo),n.loop===!1&&(s.clampWhenFinished=!0),this.actions.set(e,s)}}return t}async loadAll(){let t=[...this._animationDefs],n=async()=>{let r;for(;r=t.shift();)try{await this.loadAnimation(r.name,r.url,{loop:r.loop!==!1})}catch(s){ei.warn(`[AnimationManager] failed to load "${r.name}":`,s.message),this._failed.add(r.name)}};await Promise.all(Array.from({length:4},n))}async ensureLoaded(e){if(this.clips.has(e))return!0;if(this._failed.has(e))return!1;let t=this._animationDefs.find(n=>n.name===e);if(!t)return!1;try{return await this.loadAnimation(t.name,t.url,{loop:t.loop!==!1}),!0}catch{return this._failed.add(e),!1}}async play(e){if(!await this.ensureLoaded(e))return(this._failed.has(e)||this._animationDefs.some(r=>r.name===e))&&ei.warn(`[AnimationManager] "${e}" unavailable`),!1;if(e===this.currentName)return!0;let n=this.actions.get(e);if(!n||!this._guardAgainstFallenPose(e,n))return!1;this.currentAction&&this.currentAction!==n&&this.currentAction.fadeOut(.01),n.reset().fadeIn(.01).play(),this.currentAction=n,this.currentName=e;try{this.onChange?.(e)}catch(r){ei.warn("[AnimationManager] onChange threw:",r)}return!0}async playOnce(e,{settleTo:t="idle",fade:n=yx}={}){n=Math.max(0,Math.min(n,5));let s=await this.ensureLoaded(e)?this.actions.get(e):null;if(!s||!this._guardAgainstFallenPose(e,s))return t?this.crossfadeTo(t,n):void 0;if(s.reset(),s.setLoop(_a,1),s.clampWhenFinished=!0,s.play(),this.currentAction&&this.currentAction!==s?this.currentAction.crossFadeTo(s,n,!0):s.fadeIn(n),this.currentAction=s,this.currentName=e,this._settleFinishHandler&&this.mixer&&(this.mixer.removeEventListener("finished",this._settleFinishHandler),this._settleFinishHandler=null),t&&this.mixer){let a=o=>{o.action===s&&(this.mixer.removeEventListener("finished",a),this._settleFinishHandler===a&&(this._settleFinishHandler=null),this.currentAction===s&&this.crossfadeTo(t,n))};this._settleFinishHandler=a,this.mixer.addEventListener("finished",a)}try{this.onChange?.(e)}catch(a){ei.warn("[AnimationManager] onChange threw:",a)}}freeze(){this.currentAction&&(this.currentAction.paused=!0),this.currentAction=null,this.currentName=null,this._latestCrossfadeTarget=null}async crossfadeTo(e,t=yx){if(t=Math.max(0,Math.min(t,5)),e===this.currentName)return;if(this._latestCrossfadeTarget=e,!await this.ensureLoaded(e)){(this._failed.has(e)||this._animationDefs.some(s=>s.name===e))&&ei.warn(`[AnimationManager] "${e}" unavailable`);return}if(this._latestCrossfadeTarget!==e||e===this.currentName)return;let r=this.actions.get(e);if(r&&this._guardAgainstFallenPose(e,r)){r.reset().play(),this.currentAction&&this.currentAction!==r?this.currentAction.crossFadeTo(r,t,!0):r.fadeIn(t),this.currentAction=r,this.currentName=e;try{this.onChange?.(e)}catch(s){ei.warn("[AnimationManager] onChange threw:",s)}}}_buildOverlayClip(e,t){let n=`${e}|${t?"upper":"full"}`,r=this._overlayClips.get(n);if(r)return r;let s=this.clips.get(e);if(!s)return null;let a=this._retarget(s);if(!a)return null;let o=a.tracks;if(t&&this._canonicalToNode){let c=new Set;for(let h of UE){let d=this._canonicalToNode.get(h);d&&c.add(d)}if(o=o.filter(h=>{let d=h.name.split(".")[0];return!c.has(d)}),o.length===0)return null}let l=new bi(`${e}__additive`,a.duration,o);return mo.makeClipAdditive(l),this._overlayClips.set(n,l),l}async playOverlay(e,{loop:t=!1,crossfade:n=.25,upperBodyOnly:r=!0,timeScale:s=1,onFinished:a=null}={}){if(n=Math.max(0,Math.min(n,5)),!await this.ensureLoaded(e)||!this.mixer)return!1;let l=this._buildOverlayClip(e,r);if(!l)return!1;let c=this.mixer.clipAction(l,void 0,Uo);this._detachOverlayFinish();let h=this.overlayAction;if(h&&h!==c&&h.fadeOut(n),c.enabled=!0,c.setLoop(t?Fo:_a,t?1/0:1),c.clampWhenFinished=!t,c.setEffectiveTimeScale(s),c.reset(),c.setEffectiveWeight(1),c.fadeIn(n),c.play(),this.overlayAction=c,this.overlayName=e,!t){let d=f=>{if(f.action===c){this.mixer.removeEventListener("finished",d),this._overlayFinishHandler===d&&(this._overlayFinishHandler=null),this.overlayAction===c&&(c.fadeOut(n),this.overlayAction=null,this.overlayName=null);try{a?.(e)}catch(p){ei.warn("[AnimationManager] overlay onFinished threw:",p)}}};this._overlayFinishHandler=d,this.mixer.addEventListener("finished",d)}return!0}_detachOverlayFinish(){this._overlayFinishHandler&&this.mixer&&this.mixer.removeEventListener("finished",this._overlayFinishHandler),this._overlayFinishHandler=null}stopOverlay({crossfade:e=.2}={}){e=Math.max(0,Math.min(e,5)),this._detachOverlayFinish(),this.overlayAction&&(this.overlayAction.fadeOut(e),this.overlayAction=null,this.overlayName=null)}hasOverlay(){return this.overlayAction!=null}setSpeed(e){this.currentAction?.setEffectiveTimeScale(e)}stopAll(){this.mixer?.stopAllAction(),this._detachOverlayFinish(),this.currentAction=null,this.currentName=null,this.overlayAction=null,this.overlayName=null;try{this.onChange?.(null)}catch(e){ei.warn("[AnimationManager] onChange threw:",e)}}update(e){this.mixer?.update(e)}getLoadedNames(){return[...this.clips.keys()]}isLoaded(e){return this.clips.has(e)}dispose(){this.detach(),this.clips.clear(),this._animationDefs=[],this._failed.clear()}};function kE(i){let e=!1,t=new Set;return i.traverse(n=>{if(n.isSkinnedMesh&&(e=!0),n.name){let r=yi(n.name);r&&t.add(r)}}),e&&t.size>=FE}function BE(i){try{let e=typeof window<"u"&&typeof window.reportClientError=="function"?window.reportClientError:null;if(!e)return;e(new Error("fallen-pose retarget"),i)}catch(e){ei.warn("[AnimationManager] fallen-pose report failed:",e)}}var Sx=Ls("ar-studio:idle"),Xo=null,vx="";function wx({manifestUrl:i=En.animationManifest,clip:e="idle"}={}){let t=`${i}#${e}`;return Xo&&vx===t||(vx=t,Xo=(async()=>{let n=await fetch(i,{cache:"force-cache"}).then(l=>{if(!l.ok)throw new Error(`HTTP ${l.status}`);return l.json()}),r=Array.isArray(n)?n:n?.clips||n?.animations||[],s=r.find(l=>l?.name===e)||r[0];if(!s?.url)throw new Error(`clip "${e}" missing from the manifest`);let a=new URL(s.url,i).href,o=await fetch(a,{cache:"force-cache"});if(!o.ok)throw new Error(`HTTP ${o.status}`);return o.json()})().catch(n=>(Sx.warn("idle clip unavailable:",n?.message||n),Xo=null,null))),Xo}async function wp(i,{manifestUrl:e,clip:t="idle",sourceUrl:n=""}={}){let r=await wx({manifestUrl:e,clip:t});if(!r||!i)return null;let s=new jh;try{if(s.attach(i,{avatarUrl:n}),!s.supportsCanonicalClips()||(s.relaxUndrivenArms(),s.injectClip(t,r,{loop:!0}),!await s.play(t)))return s.detach(),null;let o=s.currentAction,l=o?.getClip?.()?.duration||0;return o&&l>0&&(o.time=Math.random()*l),s.update(0),s}catch(a){Sx.warn("idle mount failed:",a?.message||a);try{s.detach()}catch{}return null}}async function Mp({canvas:i,video:e,isAR:t}){if(!i)return null;let n=i.width,r=i.height;if(!n||!r)return null;let s=document.createElement("canvas");s.width=n,s.height=r;let a=s.getContext("2d");if(!a)return null;if(t&&e&&!e.paused&&e.videoWidth)try{a.drawImage(e,0,0,n,r)}catch{}try{a.drawImage(i,0,0)}catch{return null}return new Promise(o=>s.toBlob(o,"image/png"))}async function Ap(i,{filename:e="ar-studio.png",title:t="AR Studio"}={}){let n=new File([i],e,{type:"image/png"});if(navigator.share&&navigator.canShare?.({files:[n]}))return await navigator.share({title:t,files:[n]}),"shared";let r=URL.createObjectURL(i),s=document.createElement("a");return s.href=r,s.download=e,s.click(),setTimeout(()=>URL.revokeObjectURL(r),4e3),"downloaded"}async function Tp(i,{title:e="AR Studio",text:t=""}={}){if(navigator.share)try{return await navigator.share({title:e,url:i,...t?{text:t}:{}}),"shared"}catch(n){if(n?.name==="AbortError")throw n}return await navigator.clipboard.writeText(i),"copied"}function e_(){return typeof navigator>"u"?!1:/iphone|ipad|ipod/i.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function em(){return e_()}function t_(){return typeof navigator<"u"&&/android/i.test(navigator.userAgent)}function tm(){return t_()}var au=null,n_="_apple_ar_quicklook_button_tapped";function i_(i){return`${String(i||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"model"}.usdz`}function r_(i,{onBannerTap:e,name:t=""}={}){au&&(au.remove(),au=null);let n=document.createElement("a");n.rel="ar",n.appendChild(document.createElement("img")),n.href=i,/^blob:/i.test(i)&&n.setAttribute("download",i_(t)),n.style.cssText="position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none;overflow:hidden;",n.setAttribute("aria-hidden","true"),typeof e=="function"&&n.addEventListener("message",r=>{r.data===n_&&e()}),document.body.appendChild(n),au=n,n.click()}function s_(i,{title:e="",link:t="",fallbackUrl:n=""}={}){let r=new URLSearchParams({file:i,mode:"ar_preferred"});e&&r.set("title",e),t&&r.set("link",t);let s=encodeURIComponent(n||location.href);location.href=`intent://arvr.google.com/scene-viewer/1.2?${r.toString()}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;S.browser_fallback_url=${s};end;`}async function nm(){try{if(navigator.xr&&await navigator.xr.isSessionSupported("immersive-ar"))return"webxr"}catch{}return em()?"quicklook":tm()?"sceneviewer":"none"}var gR=4,ti=new Map;function bR(){for(;ti.size>gR;){let[i,e]=ti.entries().next().value;ti.delete(i),e.href&&URL.revokeObjectURL(e.href)}}function xR(){for(let i of ti.values())i.href&&URL.revokeObjectURL(i.href);ti.clear()}function ou(i){let e=ti.get(i);return e?(ti.delete(i),e.href&&URL.revokeObjectURL(e.href),!0):!1}function cu(i){return!!(i&&ti.get(i)?.href)}async function a_(i,e){let t=ti.get(i);if(t)return ti.delete(i),ti.set(i,t),t.promise;let n={href:"",promise:null};return n.promise=(async()=>{let r=await e();return n.href=URL.createObjectURL(r),n.href})(),n.promise.catch(()=>{ti.get(i)===n&&ti.delete(i)}),ti.set(i,n),bR(),n.promise}async function ec({src:i="",title:e="",usdz:t="",key:n="",build:r}={},{onProgress:s,fallbackUrl:a="",signal:o}={}){if(!i&&!t&&!r)throw new Error("ar-studio: nothing to place");if(em()){let l=t;if(!l){let c=n||i;if(!c)throw new Error("ar-studio: a cache key or src is required");l=await a_(c,async()=>{if(r)return s?.("convert"),r();let{glbUrlToUsdzBlob:h}=await Promise.resolve().then(()=>(su(),Qp));return h(i,{signal:o,onProgress:s})})}return{viewer:"quicklook",href:l,open:c=>r_(l,{name:e,...c})}}if(tm()){if(!i)throw new Error("ar-studio: Scene Viewer needs a GLB URL");return{viewer:"sceneviewer",href:i,open:()=>s_(i,{title:e,fallbackUrl:a})}}return null}async function im(i={},e={}){let t=await ec(i,e);return t?(e.onProgress?.("open"),t.open(),t.viewer):"none"}var _R=80;function yR(i,{title:e,subtitle:t,callToAction:n}={}){if(typeof i!="string"||!i)return i;let r=[],s=(o,l)=>{let c=typeof l=="string"?l.trim().slice(0,_R):"";c&&r.push(`${o}=${encodeURIComponent(c)}`)};if(!n||typeof n!="string"||!n.trim()||(s("checkoutTitle",e),s("checkoutSubtitle",t),s("callToAction",n),!r.length))return i;let a=r.join("&");return i.includes("#")?`${i}&${a}`:`${i}#${a}`}var vR=Math.PI/180,SR=180/Math.PI;function o_({trackWidth:i,trackHeight:e,viewWidth:t,viewHeight:n,diagFovDeg:r=72}){let s=tc(i,t),a=tc(e,n),o=tc(t,s),l=tc(n,a),c=tc(r,72),h=Math.hypot(s,a)||1,d=2*Math.atan(s/h*Math.tan(c*vR/2)),f=o/l,x=2*Math.atan(Math.tan(d/2)/(f||1))*SR;return Number.isFinite(x)?Math.max(50,Math.min(90,x)):50}function tc(i,e){let t=Number(i);return Number.isFinite(t)&&t>0?t:Number(e)>0?Number(e):1}var c_=Math.PI/180;function wR(i,e,t){let n=(e-i+Math.PI)%(Math.PI*2)-Math.PI;return n<-Math.PI&&(n+=Math.PI*2),i+n*t}function l_(i,e){return Number.isFinite(i)&&Number.isFinite(e)}function h_({useAbsolute:i,prevYaw:e,alpha:t,baseAlpha:n,baseYaw:r,compassHeading:s,absoluteSmooth:a=.4}){if(i){let l=-s*c_;return wR(e,l,a)}let o=t-n;return o>180&&(o-=360),o<-180&&(o+=360),r+o*c_}function lu(i,e,t){let n=Number.isFinite(i)?i:0;return n<e?e:n>t?t:n}function rm(i,e,t=0){let n=(Math.round(Number(t)/90)*90%360+360)%360,r;switch(n){case 90:r=e;break;case 180:r=-i;break;case 270:r=-e;break;default:r=i;break}return Number.isFinite(r)?r:0}eu();var sm=Math.PI*2;function u_(i){return Number.isFinite(i)?(i%sm+sm)%sm:0}function am(i){return Number.isFinite(i)?(i%360+360)%360:0}function om(i){return{relEast:Number(i.x)||0,relNorth:-(Number(i.z)||0)||0,yawDeg:am(u_(i.yaw)*180/Math.PI),scale:Number(i.scale)||1,height:Number(i.height)||0}}function uu(i){return{x:Number(i.relEast)||0,z:-(Number(i.relNorth)||0),yaw:am(i.yawDeg)*Math.PI/180,scale:Number(i.scale)||1}}var hu="ABCDEFGHJKMNPQRSTUVWXYZ23456789",d_=6;function Fs(i){let e=String(i??"").trim();if(!e)return"";let t=e.match(/[?&]room=([^&#\s]+)/i);if(t)try{e=decodeURIComponent(t[1])}catch{e=t[1]}if(e=e.toUpperCase().replace(/[\s-]+/g,""),e.length!==d_)return"";for(let n of e)if(!hu.includes(n))return"";return e}function cm(i=Math.random){let e="";for(let t=0;t<d_;t++)e+=hu[Math.floor(i()*hu.length)%hu.length];return e}function lm(i){return`c-${Fs(i)}`}function nc(i,e){let t=String(i||"").split("#")[0],n=Fs(e);return n?`${t}${t.includes("?")?"&":"?"}room=${n}`:t}var ts=Ls("ar-studio:net"),AC="studio_world",TC=1,EC=15e3,gc=null;async function RC(){if(gc!==null)return gc;try{let[i,e]=await Promise.all([Promise.resolve().then(()=>og(fv(),1)),Promise.resolve().then(()=>(mv(),pv))]);gc={Client:i.Client,getStateCallbacks:i.getStateCallbacks,StudioState:e.StudioState}}catch(i){ts.warn('shared rooms need the optional "colyseus.js" dependency:',i?.message||i),gc=!1}return gc}async function CC(i,e,t){let n,r=new Promise((a,o)=>{n=setTimeout(()=>o(new Error("connect_timeout")),EC)}),s=i.joinOrCreate(AC,e,t);try{return await Promise.race([s,r])}finally{clearTimeout(n),s.then(a=>{try{a&&a.connection?.isOpen&&a.leave()}catch{}}).catch(()=>{})}}var Lu=class{constructor({roomKey:e,clientId:t="",name:n="",url:r=""}={}){this.roomKey=String(e||"").slice(0,64),this.clientId=String(t||"").slice(0,80),this.name=String(n||"").slice(0,120),this.url=String(r||"").replace(/\/$/,""),this.status="idle",this.error="",this.room=null,this.client=null,this._listeners={status:[],models:[],model:[],presence:[],reject:[]},this._retries=0,this._reconnectTimer=null,this._connectGen=0,this._destroyed=!1,this._presenceQueued=!1,this._modelsQueued=!1}on(e,t){return(this._listeners[e]||=[]).push(t),this}_emit(e,t){for(let n of this._listeners[e]||[])try{n(t)}catch(r){ts.warn(`${e} listener error:`,r?.message||r)}}_setStatus(e,t=""){this.status=e,this.error=t,this._emit("status",{status:e,error:t})}_closeRoom(){let e=this.room;if(e){this.room=null;try{e.removeAllListeners()}catch{}try{e.leave()}catch{}}}async connect(){if(this._destroyed)return;if(this._closeRoom(),!this.url||!this.roomKey){this._setStatus("unavailable");return}let e=await RC();if(!e){this._setStatus("unavailable","colyseus.js is not installed");return}let t=++this._connectGen;this._setStatus("connecting");try{this.client=new e.Client(this.url);let n=await CC(this.client,{roomKey:this.roomKey,clientId:this.clientId,name:this.name},e.StudioState);if(this._destroyed||t!==this._connectGen){try{n.leave()}catch{}return}this.room=n,this._retries=0;let r=e.getStateCallbacks(this.room),s=r(this.room.state)?.models;s&&(s.onAdd((o,l)=>{r(o).onChange(()=>this._emit("model",this._modelShape(o,l))),this._queueModels()}),s.onRemove((o,l)=>{this._emit("model",{id:l,removed:!0}),this._queueModels()}));let a=r(this.room.state)?.viewers;a&&(a.onAdd(()=>this._queuePresence()),a.onRemove(()=>this._queuePresence())),this.room.onMessage("model:reject",o=>this._emit("reject",o)),this.room.onLeave(o=>{this._destroyed||o===1e3||(this._setStatus("offline"),this._scheduleReconnect())}),this.room.onError((o,l)=>ts.warn("room error",o,l)),this._setStatus("online"),this._queueModels(),this._queuePresence()}catch(n){let r=n?.message||(n?.code!=null?`code ${n.code}`:String(n));ts.warn("connect failed:",r),this._setStatus("failed",r),this._scheduleReconnect()}}_scheduleReconnect(){if(this._reconnectTimer||this._destroyed)return;if(this._retries>=TC){this._setStatus("unavailable",this.error);return}this._retries++;let e=2500+Math.random()*1500;this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=null,this._destroyed||this.connect()},e)}_modelShape(e,t){return{id:t??e.id,src:e.src,title:e.title,relEast:e.relEast,relNorth:e.relNorth,yawDeg:e.yawDeg,scale:e.scale,height:e.height,ownerId:e.ownerId,mine:!!this.clientId&&e.ownerId===this.clientId}}_queueModels(){this._modelsQueued||this._destroyed||(this._modelsQueued=!0,Promise.resolve().then(()=>{this._modelsQueued=!1;let e=this.room?.state?.models;if(this._destroyed||!e)return;let t=[];e.forEach((n,r)=>t.push(this._modelShape(n,r))),this._emit("models",t)}))}_queuePresence(){this._presenceQueued||this._destroyed||(this._presenceQueued=!0,Promise.resolve().then(()=>{this._presenceQueued=!1;let e=this.room?.state?.viewers;if(this._destroyed||!e)return;let t=0,n=[];e.forEach(r=>{t++,r.name&&n.push(r.name)}),this._emit("presence",{count:t,names:n})}))}_live(){return this.status==="online"&&this.room&&this.room.connection?.isOpen===!0}spawn(e){if(!this._live())return!1;try{return this.room.send("model:spawn",{id:e.id,src:String(e.src||""),title:String(e.title||"").slice(0,120),relEast:Number(e.relEast)||0,relNorth:Number(e.relNorth)||0,yawDeg:Number(e.yawDeg)||0,scale:Number(e.scale)||1,height:Number(e.height)||0}),!0}catch(t){return ts.warn("spawn failed:",t?.message||t),!1}}update(e,t){if(!this._live()||!e)return!1;let n={id:String(e)};for(let r of["relEast","relNorth","yawDeg","scale"])Number.isFinite(t?.[r])&&(n[r]=t[r]);try{return this.room.send("model:update",n),!0}catch(r){return ts.warn("update failed:",r?.message||r),!1}}remove(e){if(!this._live()||!e)return!1;try{return this.room.send("model:remove",{id:String(e)}),!0}catch(t){return ts.warn("remove failed:",t?.message||t),!1}}heartbeat(){if(this._live())try{this.room.send("heartbeat",{})}catch(e){ts.warn("heartbeat failed:",e?.message||e)}}destroy(){this._destroyed=!0,this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._closeRoom(),this.client=null,this._setStatus("destroyed")}};var hi=Ls("ar-studio"),DC=1.55,eg=-1.25,tg=1.35,ng=1,ig=1.15,Du=60,bc=class{constructor(e,t={}){if(!e)throw new Error("ar-studio: a host element is required");this.host=e,this.config=bf(t),this.clientId=UC(this.config.persistKey),this.sources=Lf(this.config.assets,this.config),this._listeners=new Map,this._destroyed=!1,this.ui=Cb(e,this.config),(this.config.fullscreen??e===document.body)&&this.ui.root.classList.add("is-fullscreen"),this._initScene(),this._initState(),this._wireUI(),this._boot()}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e,t={}){for(let n of this._listeners.get(e)||[])try{n(t)}catch(r){hi.warn(`${e} listener error`,r)}try{this.config.onEvent?.(e,t)}catch(n){hi.warn("onEvent error",n)}try{this.ui.root.dispatchEvent(new CustomEvent(`ar-studio:${e}`,{detail:t,bubbles:!0}))}catch{}}_initScene(){this.renderer=new yh({canvas:this.ui.canvas,alpha:!0,antialias:!0,preserveDrawingBuffer:!0}),this.renderer.setClearColor(0,0),this.qualityTier=Of(),Ff(this.renderer,{tier:this.qualityTier}),this.scene=new Or,this.camera=new an(58,1,.02,200),this.camera.position.set(0,DC,0),this.cameraYaw=0,this.cameraPitch=-.24;let e=this.qualityTier==="mobile"?null:this.config.lighting?.preset??"studio";if(Uf(this.renderer,this.scene,e,{urls:this.config.lighting?.urls}).catch(t=>hi.warn("environment map failed",t)),this.hemi=new ma(16777215,4473941,ng),this.sun=new Di(16777215,ig),this.sun.position.set(2.5,6,3),this.scene.add(this.hemi,this.sun),this.grid=new To(24,48,3817298,2303802),this.grid.position.y=.001,this.grid.material.transparent=!0,this.grid.material.opacity=.75,this._fog=new no(395018,5,17),this.scene.fog=this._fog,this.scene.add(this.grid),this.rayPlane=new xt(new mi(80,80),new gn({visible:!1,side:2})),this.rayPlane.rotation.x=-Math.PI/2,this.scene.add(this.rayPlane),this.selRing=new xt(new Gr(.3,.34,48).rotateX(-Math.PI/2),new gn({color:9141496,transparent:!0,opacity:.85,depthTest:!1})),this.config.branding?.accent)try{this.selRing.material.color.set(this.config.branding.accent)}catch{}this.selRing.renderOrder=998,this.selRing.visible=!1,this.scene.add(this.selRing),this.shadowTex=OC(),this.reducedMotion=NC(),this._applyCameraLook()}_initState(){this.placements=[],this.selected=null,this.arActive=!1,this.mediaStream=null,this.arTransitioning=!1,this.xrSession=null,this.estimatedLight=null,this.arMode="none",this._cameraYielded=!1,this._cameraWasOn=!1,this._onArReturn=null,this._nativeArBusy=!1,this._arHandoff=null,this._arTarget=null,this._arToken=0,this._arWarmTimer=null,this._arRetry=null,this._arKeys=new Set,this.arTrackW=0,this.arTrackH=0,this._statusTimer=null,this._armed=null,this._templates=new Map,this._templatesReady=new Map,this._trayCache=new Map,this._trayTab=this.sources[0]?.id||"link",this._loadQueue=Ob({run:e=>Gh().loadAsync(e),maxActive:3}),this._maxPlacements=Math.min(Number(this.config.maxPlacements)||20,20),this.net=null,this.roomCode="",this._netModels=new Map,this._presence={count:1,names:[]},this._roomSynced=!1,this._roomHeartbeat=null,this.forge=this.config.generate?.enabled===!1?null:Mf({endpoint:this.config.generate.endpoint,kind:this.config.generate.kind,tier:this.config.generate.tier,timeoutMs:this.config.generate.timeoutMs,pollMs:this.config.generate.pollMs,headers:this.config.generate.headers}),this._forgeSeq=0,this._forgeBusy=!1,this.gyroBase=null,this._devAlpha=0,this._devBeta=90,this._devGamma=0,this._absoluteOrientation=!1,this._raycaster=new Ao,this._ndc=new dt,this._pointer=null,this._userLooked=!1,this._pinch=$o(),this._pinchEndedAt=-1/0,this._twist=null,this._rafId=null,this._prevT=0,this._lightTimer=null,this._roomTint=new Ve,this._lightProbe=FC(),this._recentKey=`${this.config.persistKey}:recent`,this.config.recentKey=this._recentKey}_wireUI(){let e=this.ui,t=(r,s,a,o)=>{r&&r.addEventListener(s,a,o)};t(e.cameraBtn,"click",()=>{this.arTransitioning||this.xrSession||(this.arActive?(this._stopCamera(),this._setStatus("Camera off: preview mode.")):this._startCamera())}),!navigator.mediaDevices?.getUserMedia&&e.cameraBtn&&(e.cameraBtn.disabled=!0,e.cameraBtn.setAttribute("aria-disabled","true"),e.cameraBtn.title="This browser cannot open a camera"),t(e.xrBtn,"click",()=>this._enterAR()),t(e.addBtn,"click",()=>e.tray.hidden?this._openTray():this._closeTray()),t(e.trayClose,"click",()=>this._closeTray()),t(e.tray,"click",r=>{r.target===e.tray&&this._closeTray()}),t(e.emptyAdd,"click",()=>this._openTray()),t(e.emptyCamera,"click",()=>this._startCamera()),t(e.emptyForge,"click",()=>e.forgeInput?.focus()),t(e.forgeForm,"submit",r=>{r.preventDefault(),this._startForge(e.forgeInput?.value)}),t(e.clearBtn,"click",()=>this._clearWithUndo()),t(e.photoBtn,"click",()=>this._capturePhoto()),t(e.qrBtn,"click",()=>this._openQr()),t(e.qrClose,"click",()=>this._closeQr()),t(e.qrModal,"click",r=>{r.target===e.qrModal&&this._closeQr()}),t(e.arClose,"click",()=>this._closeArSheet()),t(e.arModal,"click",r=>{r.target===e.arModal&&this._closeArSheet()}),t(e.arGo,"click",()=>this._onArGo()),t(e.arXr,"click",()=>{this._closeArSheet(),this._toggleXR()}),t(e.arQr,"click",()=>{this._closeArSheet(),this._openQr()}),t(e.arPicker,"click",r=>{let s=r.target.closest("[data-ar-id]");if(!s)return;let a=this.placements.find(o=>o.id===s.dataset.arId);a&&this._showArTarget(a)}),t(e.selbar,"click",r=>this._onSelbarClick(r)),t(e.roomBtn,"click",()=>this._openRoomModal()),t(e.roomClose,"click",()=>this._closeRoomModal()),t(e.roomModal,"click",r=>{r.target===e.roomModal&&this._closeRoomModal()}),t(e.roomCreate,"click",()=>this._createRoomFromUI()),t(e.roomJoinForm,"submit",r=>{r.preventDefault(),this._joinRoomFromUI()}),t(e.roomCopy,"click",()=>this._copyRoomInvite()),t(e.roomLeave,"click",()=>{this._leaveRoom(),this._renderRoomModal()});let n=e.canvas;t(n,"pointerdown",r=>this._onPointerDown(r)),t(n,"pointermove",r=>this._onPointerMove(r)),t(n,"pointerup",r=>this._onPointerUp(r)),t(n,"pointercancel",()=>{this._pointer=null}),t(n,"touchstart",r=>this._onTouchStart(r),{passive:!0}),t(n,"touchmove",r=>this._onTouchMove(r),{passive:!0}),t(n,"touchend",()=>this._onTouchEnd(),{passive:!0}),this._onKeyDown=this._onKeyDown.bind(this),document.addEventListener("keydown",this._onKeyDown),this._onOrientationAbsolute=r=>{this._absoluteOrientation=!0,this._onDeviceOrientation(r)},this._onOrientation=r=>{this._absoluteOrientation||this._onDeviceOrientation(r)},window.addEventListener("deviceorientationabsolute",this._onOrientationAbsolute,!0),window.addEventListener("deviceorientation",this._onOrientation,!0),this._onResize=()=>this._resize(),window.addEventListener("resize",this._onResize),this._onPageHide=()=>{this._stopCamera(),this.xrSession?.end(),this.net?.destroy()},window.addEventListener("pagehide",this._onPageHide),typeof ResizeObserver<"u"&&(this._ro=new ResizeObserver(()=>this._resize()),this._ro.observe(e.root)),this._wireTrayTabs()}_boot(){this._resize(),this._updateCount(),this._updateRoomButton(),this._startLoop(),nm().then(n=>{this.arMode=n;let r=this.ui.xrBtn;if(!r||n==="none")return;r.hidden=!1;let s=r.querySelector(".ars-ar-label");n==="webxr"?(s&&(s.textContent="Immersive AR"),r.setAttribute("aria-label","Enter immersive augmented reality and place models on real surfaces")):(s&&(s.textContent="Place in your space"),r.setAttribute("aria-label","Open this in your device AR viewer and place it in your real space"))}),!window.matchMedia?.("(pointer: coarse)").matches&&this.ui.qrBtn&&(this.ui.qrBtn.hidden=!1);let t=Fs(this.config.urlRoom||"");this._restoreScene({skipLocal:!!t}).then(()=>{t&&this._joinRoom(t),this.config.urlPrompt&&this.config.urlPrompt.length>=3&&this.ui.forgeInput&&(this.ui.forgeInput.value=this.config.urlPrompt,this._startForge(this.config.urlPrompt))})}_setStatus(e,{warn:t=!1,sticky:n=!1,actionLabel:r="",onAction:s=null}={}){let a=this.ui.status;if(a){if(clearTimeout(this._statusTimer),a.textContent="",!e){a.hidden=!0;return}a.hidden=!1,a.classList.toggle("is-warn",t),a.appendChild(re("span",{text:e})),r&&s&&a.appendChild(re("button",{type:"button",class:"ars-status-action",text:r,onclick:()=>{this._setStatus(null),s()}})),n||(this._statusTimer=setTimeout(()=>{a.hidden=!0},5200))}}_updateCount(){let e=this.placements.length,{count:t,clearBtn:n,empty:r,photoBtn:s}=this.ui;t&&(this.net&&this.net.status==="online"&&this._presence.count>1?(t.textContent=`${this._presence.count} here \xB7 ${e} ${e===1?"model":"models"}`,t.hidden=!1):(t.textContent=e===1?"1 model":`${e} models`,t.hidden=e===0)),n&&(n.hidden=e===0),r&&(r.hidden=e>0),s&&(s.disabled=e===0)}_logicalScale(e){return e.spawnT<1?e.group.userData._targetScale??1:e.group.scale.x}_saveScene(){if(this.config.persist!==!1)try{localStorage.setItem(this.config.persistKey,Jh(this.placements.filter(e=>this._isMine(e)).map(e=>({src:e.src,title:e.title,x:e.group.position.x,z:e.group.position.z,yaw:e.yaw,scale:this._logicalScale(e)}))))}catch{}}_select(e){this.selected=e;let{selbar:t,selName:n}=this.ui;if(t){if(!e){t.hidden=!0,this.selRing.visible=!1,this._emit("select",{placement:null});return}t.hidden=!1,n&&(n.textContent=e.title||"Model"),this.selRing.visible=!this.xrSession,this._positionSelRing(),this._warmQuickLook(),this._emit("select",{placement:rg(e,this)})}}_positionSelRing(){let e=this.selected;if(!e)return;this.selRing.position.set(e.group.position.x,e.group.position.y+.006,e.group.position.z);let t=Math.max(.24,e.baseRadius*e.group.scale.x*1.15);this.selRing.scale.setScalar(t/.34)}_loadTemplate(e){let t=this._templates.get(e);return t||(t=this._loadQueue.request(e).then(n=>{let r=!1;n.scene.traverse(c=>{c.isSkinnedMesh&&(r=!0)});let s=new rn().setFromObject(n.scene),a=Ko({min:{x:s.min.x,y:s.min.y,z:s.min.z},max:{x:s.max.x,y:s.max.y,z:s.max.z}},{skinned:r}),o=Math.max((s.max.x-s.min.x)*a.scale,(s.max.z-s.min.z)*a.scale)/2,l=(s.max.y-s.min.y)*a.scale;return{gltf:n,skinned:r,fit:a,radius:Number.isFinite(o)?o:.3,height:Number.isFinite(l)?l:.75}}),this._templates.set(e,t),t.then(n=>this._templatesReady.set(e,n)).catch(()=>this._templates.delete(e))),t}_instantiate(e,t){let n=Cs(e.gltf.scene);n.scale.setScalar(e.fit.scale),n.position.y=e.fit.yOffset;let r=new pn;r.add(n);let s=null;e.gltf.animations?.length&&(s=new Ms(n),s.clipAction(e.gltf.animations[0]).play());let a=null;return!s&&e.skinned&&this.config.animations?.enabled!==!1&&(a=wp(n,{manifestUrl:this.config.animations?.manifestUrl,clip:this.config.animations?.clip,sourceUrl:t}).catch(()=>null)),{group:r,mixer:s,idlePromise:a}}_makeShadow(e){if(!this.shadowTex)return null;let t=Math.max(.4,e*2.4),n=new xt(new mi(t,t).rotateX(-Math.PI/2),new gn({map:this.shadowTex,transparent:!0,opacity:.85,depthWrite:!1}));return n.renderOrder=1,n}_nudgeSpawn(e){let{x:t,z:n}=e;for(let r=0;r<8&&this.placements.some(o=>Math.hypot(o.group.position.x-t,o.group.position.z-n)<.45);r++){let a=r*2.399963;t=e.x+Math.cos(a)*.55*(1+r*.18),n=e.z+Math.sin(a)*.55*(1+r*.18)}return{x:t,z:n}}async _addModel({src:e,title:t="",poster:n=""}={},{x:r=null,z:s=null,yaw:a=null,scale:o=null,announce:l=!0,persist:c=!0,remote:h=!1,netId:d=null,ownerId:f=null}={}){let p=Jr(e);if(!p)return this._setStatus("That link is not a loadable https GLB.",{warn:!0}),null;if(this.placements.length>=this._maxPlacements)return this._setStatus(`Scene is full (${this._maxPlacements} models). Remove one to add more.`,{warn:!0}),null;l&&this._setStatus(`Loading ${t||"model"}\u2026`,{sticky:!0});let x;try{x=await this._loadTemplate(p)}catch(U){return hi.warn("model load failed",p,U),this._setStatus(`Couldn't load ${t||"that model"}: the file may be gone or blocked by CORS.`,{warn:!0,actionLabel:"Retry",onAction:()=>this._addModel({src:p,title:t})}),null}let{group:y,mixer:b,idlePromise:g}=this._instantiate(x,p),S=r,A=s;if(S===null||A===null){let U=Math.max(1.6,(x.height||0)*1.15),v=this.camera.getWorldDirection(new W),I=this._nudgeSpawn(Cp(this.camera.position,v,U));S=I.x,A=I.z}y.position.set(S,0,A);let T=a??Math.atan2(this.camera.position.x-S,this.camera.position.z-A);y.rotation.y=T,o&&y.scale.setScalar(Math.min(4,Math.max(.25,o))),this.scene.add(y);let N=this._makeShadow(x.radius);N&&(N.position.set(S,.004,A),N.scale.setScalar(y.scale.x),N.visible=!this.xrSession,this.scene.add(N));let P={id:`p-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`,src:p,title:String(t||"").slice(0,160),poster:n,group:y,shadow:N,mixer:b,idle:null,yaw:T,baseRadius:x.radius,height:x.height||0,spawnT:this.reducedMotion?1:0,netId:d||null,ownerId:h?f:null,remote:h,_lastNetSend:0};if(g?.then(U=>{U&&(this.placements.includes(P)?P.idle=U:U.detach())}),y.userData._targetScale=y.scale.x,this.reducedMotion||y.scale.setScalar(.001),this.placements.push(P),P.netId&&this._netModels.set(P.netId,P),h||(this._armed={src:p,title:P.title}),this._updateCount(),h||this._select(P),c&&this._saveScene(),!h&&this.net&&this.net.status==="online"){let U=`m${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`.slice(0,40);P.netId=U,P.ownerId=this.clientId,this._netModels.set(U,P),this.net.spawn(this._placementWire(P,U))}return l&&this._setStatus(h?`${t||"A model"} was added by someone in the room.`:"Placed. Drag to move, pinch to resize, twist to rotate."),h||this._framePreview(),this._emit("add",{placement:rg(P,this),remote:h}),P}_removePlacement(e,{persist:t=!0,broadcast:n=!0}={}){let r=this.placements.indexOf(e);r!==-1&&(this.placements.splice(r,1),e.netId&&(this._netModels.delete(e.netId),n&&this.net?.status==="online"&&this._isMine(e)&&this.net.remove(e.netId)),e.idle?.detach(),e.idle=null,this.xrSession?.release(e.group),this.scene.remove(e.group),e.shadow&&(this.scene.remove(e.shadow),e.shadow.geometry?.dispose(),e.shadow.material?.dispose()),this.selected===e&&this._select(this.placements[this.placements.length-1]??null),ou(this._arCacheKey(e)),this._arKeys.delete(this._arCacheKey(e)),this.ui.arModal&&!this.ui.arModal.hidden&&this._showArTarget(this._arTarget===e?this._arDefaultTarget():this._arTarget),this._updateCount(),t&&this._saveScene(),this._emit("remove",{src:e.src,title:e.title}))}_clearWithUndo(){if(!this.placements.length)return;let e=this.getScene();for(let t of[...this.placements])this._removePlacement(t,{persist:!1});this._saveScene(),this._emit("clear",{items:e}),this._setStatus("Scene cleared.",{actionLabel:"Undo",onAction:async()=>{for(let t of e)await this._addModel({src:t.src,title:t.title},{x:t.x,z:t.z,yaw:t.yaw,scale:t.scale,announce:!1})}})}_onSelbarClick(e){let t=e.target.closest("[data-act]"),n=this.selected;if(!t||!n)return;let r=t.dataset.act;if((r==="rotate"||r==="remove")&&!this._isMine(n)){this._setStatus("That model belongs to someone else in the room.",{warn:!0});return}r==="rotate"?(n.yaw+=Math.PI/4,n.group.rotation.y=n.yaw,n._lastNetSend=0,this._netBroadcastTransform(n),this._saveScene()):r==="duplicate"?this._addModel({src:n.src,title:n.title},{yaw:n.yaw,scale:this._logicalScale(n)}):r==="remove"&&(this._removePlacement(n),this._setStatus("Removed.",{actionLabel:"Undo",onAction:()=>this._addModel({src:n.src,title:n.title},{x:n.group.position.x,z:n.group.position.z,yaw:n.yaw,scale:this._logicalScale(n)})}))}async _restoreScene({skipLocal:e=!1}={}){let t=new URLSearchParams(String(location.hash||"").replace(/^#/,"")),n=e?[]:Pp(t.get("s")),r=n;if(!r.length&&!e&&this.config.persist!==!1)try{r=Zh(localStorage.getItem(this.config.persistKey))}catch{r=[]}for(let a of r)await this._addModel({src:a.src,title:a.title},{x:a.x,z:a.z,yaw:a.yaw,scale:a.scale,announce:!1,persist:!1});let s=new Set(this.placements.map(a=>a.src));for(let a of this.config.urlModels||[])s.has(a.src)||await this._addModel(a,{announce:!1});this.placements.length&&(this._select(this.placements[this.placements.length-1]),n.length?this._setStatus("Shared scene loaded, exactly as arranged. Clear to start fresh."):this._setStatus(this.config.urlModels?.length?"Models loaded: turn on the camera to see them in your space.":"Your scene is back.")),this._saveScene()}_applyCameraFov(){let e=this.mediaStream?.getVideoTracks?.()[0];if(e){let r=e.getSettings?.()??{};Number.isFinite(r.width)&&r.width>0&&(this.arTrackW=r.width),Number.isFinite(r.height)&&r.height>0&&(this.arTrackH=r.height)}if(!this.arActive||!(this.arTrackW>0)||!(this.arTrackH>0))return;let{width:t,height:n}=this._viewportSize();this.camera.fov=o_({trackWidth:this.arTrackW,trackHeight:this.arTrackH,viewWidth:t,viewHeight:n,diagFovDeg:72}),this.camera.updateProjectionMatrix()}_sampleCameraLight(){let e=this._lightProbe,t=this.ui.video;if(!this.arActive||!e?.ctx||!t?.videoWidth)return;let n;try{e.ctx.drawImage(t,0,0,16,16),n=e.ctx.getImageData(0,0,16,16).data}catch{return}let{intensity:r,tint:s}=Rp(n);this.hemi.intensity+=(r*ng-this.hemi.intensity)*.4,this.sun.intensity+=(r*ig-this.sun.intensity)*.4,this._roomTint.setRGB(s.r,s.g,s.b),this.hemi.color.lerp(this._roomTint,.4),this.sun.color.lerp(this._roomTint,.4)}_startLightMatching(){this._lightTimer||!this._lightProbe||(this._lightTimer=setInterval(()=>this._sampleCameraLight(),2e3),this._sampleCameraLight())}_stopLightMatching(){clearInterval(this._lightTimer),this._lightTimer=null,this.hemi.intensity=ng,this.sun.intensity=ig,this.hemi.color.setHex(16777215),this.sun.color.setHex(16777215)}async _startCamera(){if(!(this.arTransitioning||this.arActive||this.xrSession)){if(!navigator.mediaDevices?.getUserMedia){this._setStatus("This browser cannot open the camera: the 3D preview still works.",{warn:!0});return}this.arTransitioning=!0;try{this._setStatus("Starting camera\u2026",{sticky:!0});try{this.mediaStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"}},audio:!1})}catch(r){r?.name==="NotAllowedError"?this._setStatus("Camera permission is blocked. Allow it in your browser settings, then try again.",{warn:!0,sticky:!0,actionLabel:"Try again",onAction:()=>this._startCamera()}):this._setStatus(`The camera did not start (${r?.message??r}).`,{warn:!0,actionLabel:"Try again",onAction:()=>this._startCamera()});return}let{video:e,root:t,cameraBtn:n}=this.ui;e&&(e.srcObject=this.mediaStream),this.arActive=!0,t.classList.add("is-ar"),n?.classList.add("is-active"),n?.setAttribute("aria-pressed","true"),this.grid.visible=!1,this.scene.fog=null,this._userLooked=!0,e?.play?.().catch(()=>{}),this._applyCameraFov(),this._startLightMatching(),await this._startGyro(),this.arMode==="quicklook"||this.arMode==="sceneviewer"?this._setStatus("Camera on. This preview turns with your phone; to lock a model to your real floor, place it in AR.",{actionLabel:"Place in AR",onAction:()=>this._openArSheet()}):this._setStatus("Camera on: your models are in the room. Look around."),this._emit("camera",{active:!0})}finally{this.arTransitioning=!1}}}_stopCamera(){this.mediaStream&&(this.mediaStream.getTracks().forEach(s=>{try{s.stop()}catch{}}),this.mediaStream=null);let{video:e,root:t,cameraBtn:n}=this.ui;e&&(e.srcObject=null);let r=this.arActive;this.arActive=!1,this._stopLightMatching(),t?.classList.remove("is-ar"),n?.classList.remove("is-active"),n?.setAttribute("aria-pressed","false"),this.grid.visible=!this.xrSession,this.xrSession||(this.scene.fog=this._fog),this.camera.fov=58,this.camera.updateProjectionMatrix(),this.gyroBase=null,this._userLooked=!1,this.arTrackW=0,this.arTrackH=0,r&&this._emit("camera",{active:!1}),this._framePreview()}_yieldCameraToNativeAr(){this._cameraYielded||(this._cameraYielded=!0,this._cameraWasOn=this.arActive,this._stopCamera(),this._stopLoop(),this._onArReturn=()=>{typeof document<"u"&&document.visibilityState!=="visible"||this._reclaimCameraAfterNativeAr()},document.addEventListener("visibilitychange",this._onArReturn),window.addEventListener("focus",this._onArReturn))}_reclaimCameraAfterNativeAr(){this._cameraYielded&&(this._cameraYielded=!1,this._onArReturn&&(document.removeEventListener("visibilitychange",this._onArReturn),window.removeEventListener("focus",this._onArReturn),this._onArReturn=null),!(this._destroyed||this.xrSession)&&(this._startLoop(),!(this.arActive||!this._cameraWasOn)&&(this._cameraWasOn=!1,this._startCamera().catch(e=>hi.warn("camera did not come back after AR",e)))))}_screenAngle(){try{let e=screen.orientation?.angle;if(Number.isFinite(e))return e}catch{}return Number(window.orientation)||0}_onDeviceOrientation(e){if(l_(e.alpha,e.beta)&&(this._devAlpha=e.alpha,this._devBeta=e.beta,Number.isFinite(e.gamma)&&(this._devGamma=e.gamma)),!this.arActive||!this.gyroBase)return;let t=rm(this._devBeta,this._devGamma,this._screenAngle()),n=h_({useAbsolute:!1,prevYaw:this.cameraYaw,alpha:this._devAlpha,baseAlpha:this.gyroBase.alpha,baseYaw:this.gyroBase.yaw,compassHeading:null}),r=lu(this.gyroBase.pitch-(t-this.gyroBase.beta)*(Math.PI/180),eg,tg);Number.isFinite(n)&&(this.cameraYaw=n),Number.isFinite(r)&&(this.cameraPitch=r)}async _startGyro(){try{if(typeof DeviceOrientationEvent<"u"&&typeof DeviceOrientationEvent.requestPermission=="function"&&await DeviceOrientationEvent.requestPermission()!=="granted"){this._setStatus("Motion access is off: drag to look around instead.",{warn:!0});return}}catch{return}this.gyroBase={alpha:this._devAlpha,beta:rm(this._devBeta,this._devGamma,this._screenAngle()),yaw:this.cameraYaw,pitch:this.cameraPitch}}_viewportSize(){let e=this.ui.root.getBoundingClientRect();return{width:Math.max(1,Math.round(e.width||window.innerWidth)),height:Math.max(1,Math.round(e.height||window.innerHeight)),left:e.left,top:e.top}}_setNdc(e,t){let n=this._viewportSize();this._ndc.set((e-n.left)/n.width*2-1,-((t-n.top)/n.height)*2+1)}_placementAt(e,t){if(!this.placements.length)return null;this._setNdc(e,t),this._raycaster.setFromCamera(this._ndc,this.camera);let n=this._raycaster.intersectObjects(this.placements.map(s=>s.group),!0);if(!n.length)return null;let r=n[0].object;for(;r;){let s=this.placements.find(a=>a.group===r);if(s)return s;r=r.parent}return null}_floorPointAt(e,t){this._setNdc(e,t),this._raycaster.setFromCamera(this._ndc,this.camera);let n=this._raycaster.intersectObject(this.rayPlane);return n.length?n[0].point:null}_onPointerDown(e){this.xrSession||this._pinch.active||performance.now()-this._pinchEndedAt<350||(this._pointer={x:e.clientX,y:e.clientY,placement:this._placementAt(e.clientX,e.clientY),lookYaw:this.cameraYaw,lookPitch:this.cameraPitch,moved:!1})}_onPointerMove(e){let t=this._pointer;if(!t||this.xrSession||this._pinch.active)return;let n=e.clientX-t.x,r=e.clientY-t.y;if(Math.hypot(n,r)>6&&(t.moved=!0),!!t.moved)if(t.placement&&this._isMine(t.placement)){let s=this._floorPointAt(e.clientX,e.clientY);if(!s)return;let a=t.placement;a.group.position.x=s.x,a.group.position.z=s.z,a.shadow?.position.set(s.x,.004,s.z),this.selected===a&&this._positionSelRing(),this._netBroadcastTransform(a)}else!t.placement&&!(this.arActive&&this.gyroBase)&&(this._userLooked=!0,this.cameraYaw=t.lookYaw+n*.0042,this.cameraPitch=lu(t.lookPitch+r*.0032,eg,tg))}_onPointerUp(e){let t=this._pointer;if(!t||this.xrSession)return;!t.moved&&Math.hypot(e.clientX-t.x,e.clientY-t.y)<=8&&!this._pinch.active&&performance.now()-this._pinchEndedAt>=350?this._select(t.placement):t.placement&&t.moved&&this._isMine(t.placement)&&(t.placement._lastNetSend=0,this._netBroadcastTransform(t.placement),this._saveScene(),this._setStatus(null)),this._pointer=null}_gestureTarget(){let e=this.selected??this.placements[this.placements.length-1]??null;return e&&this._isMine(e)?e:null}_onTouchStart(e){if(this.xrSession||e.touches.length!==2)return;let t=this._gestureTarget();t&&(this._pointer=null,Nh(this._pinch,Ia(e.touches),t.group.scale.x),this._twist={startAngle:Yh(e.touches),baseYaw:t.yaw,placement:t})}_onTouchMove(e){if(this.xrSession||e.touches.length!==2)return;let t=this._twist?.placement;if(!t)return;let n=Oh(this._pinch,Ia(e.touches));n!=null&&(t.group.scale.setScalar(n),t.group.userData._targetScale=n,t.shadow?.scale.setScalar(n),this.selected===t&&this._positionSelRing()),t.yaw=this._twist.baseYaw+Ip(this._twist.startAngle,Yh(e.touches)),t.group.rotation.y=t.yaw,this._netBroadcastTransform(t)}_onTouchEnd(){this._warmQuickLook();let e=Fh(this._pinch),t=this._twist?.placement;e!=null&&(this._pinchEndedAt=performance.now(),this._saveScene()),t&&(t._lastNetSend=0,this._netBroadcastTransform(t)),this._twist=null}_onKeyDown(e){if(this._destroyed||!this.ui.root.isConnected)return;if(e.target.closest?.("input, textarea, select")){e.key==="Escape"&&e.target.blur();return}if(e.key==="Escape"){this.ui.tray.hidden?this.ui.roomModal.hidden?this.ui.arModal.hidden?this.ui.qrModal.hidden?this._select(null):this._closeQr():this._closeArSheet():this._closeRoomModal():this._closeTray();return}if(!this.ui.tray.hidden||!this.ui.qrModal.hidden||!this.ui.arModal.hidden||!this.ui.roomModal.hidden||this.xrSession)return;let t=this.selected;if(!t)return;let n=this._isMine(t);if(e.key.startsWith("Arrow")){if(!n)return;e.preventDefault();let r=e.shiftKey?.02:.1,s=this.camera.getWorldDirection(new W);s.y=0,s.lengthSq()<1e-6&&s.set(0,0,-1),s.normalize();let a=new W(-s.z,0,s.x),o=e.key==="ArrowUp"?s:e.key==="ArrowDown"?s.negate():e.key==="ArrowLeft"?a.negate():a;t.group.position.addScaledVector(o,r),t.shadow?.position.set(t.group.position.x,.004,t.group.position.z),this._positionSelRing(),this._netBroadcastTransform(t),this._saveScene()}else if(e.key==="r"||e.key==="R"){if(!n)return;t.yaw+=Math.PI/4,t.group.rotation.y=t.yaw,t._lastNetSend=0,this._netBroadcastTransform(t),this._saveScene()}else if(e.key==="d"||e.key==="D")e.preventDefault(),this._addModel({src:t.src,title:t.title},{yaw:t.yaw,scale:this._logicalScale(t)});else if(e.key==="Delete"||e.key==="Backspace"){if(!n)return;e.preventDefault(),this._removePlacement(t),this._setStatus("Removed.",{actionLabel:"Undo",onAction:()=>this._addModel({src:t.src,title:t.title},{x:t.group.position.x,z:t.group.position.z,yaw:t.yaw,scale:this._logicalScale(t)})})}}_wireTrayTabs(){let e=this.ui.trayTabs;if(e){for(let[t,n]of this.sources.entries()){let r=re("button",{type:"button",class:"ars-tab",role:"tab",id:`ars-tab-${t}-${n.id}`,"aria-selected":String(t===0),tabindex:t===0?"0":"-1","data-tab":n.id,text:n.label||n.id});r.addEventListener("click",()=>this._setTrayTab(n.id)),e.appendChild(r)}e.addEventListener("keydown",t=>{let n=[...e.querySelectorAll(".ars-tab")],r=n.indexOf(document.activeElement);if(r===-1)return;let s=n.length-1,a=t.key==="ArrowRight"?r===s?0:r+1:t.key==="ArrowLeft"?r===0?s:r-1:t.key==="Home"?0:t.key==="End"?s:-1;a!==-1&&(t.preventDefault(),this._setTrayTab(n[a].dataset.tab),n[a].focus())})}}_openTray(e=this._trayTab){let{tray:t,addBtn:n,trayClose:r}=this.ui;t&&(this._lastFocus=document.activeElement,t.hidden=!1,n?.setAttribute("aria-expanded","true"),this._setTrayTab(e),r?.focus?.())}_closeTray(){let{tray:e,addBtn:t}=this.ui;if(!e||e.hidden)return;let n=e.contains(document.activeElement);e.hidden=!0,t?.setAttribute("aria-expanded","false"),n&&this._restoreFocus(t)}_restoreFocus(e){(this._lastFocus&&document.contains(this._lastFocus)&&!this._lastFocus.hidden?this._lastFocus:e)?.focus?.(),this._lastFocus=null}_setTrayTab(e){this._trayTab=e;let t=[...this.ui.trayTabs?.querySelectorAll(".ars-tab")||[]];for(let n of t){let r=n.dataset.tab===e;n.classList.toggle("is-active",r),n.setAttribute("aria-selected",String(r)),n.tabIndex=r?0:-1,r&&(this.ui.trayBody?.setAttribute("aria-labelledby",n.id),n.scrollIntoView?.({block:"nearest",inline:"nearest"}))}this._renderTray()}async _renderTray(){let e=this.ui.trayBody;if(!e)return;let t=this._trayTab,n=this.sources.find(s=>s.id===t);if(!n)return;if(n.kind==="link"||n.id==="link"){this._renderLinkTab(e);return}e.textContent="",e.appendChild(re("div",{class:"ars-tray-loading"},[re("span",{class:"ars-spinner","aria-hidden":"true"}),"Loading models\u2026"]));let r;try{!n.live&&this._trayCache.has(t)?r=this._trayCache.get(t):(r=await n.list(),n.live||this._trayCache.set(t,r))}catch(s){if(hi.warn("source failed",t,s),this._trayTab!==t)return;e.textContent="",e.appendChild(re("div",{class:"ars-tray-empty"},[re("p",{text:`Couldn't load ${n.label||"these models"} right now.`}),re("button",{type:"button",class:"ars-btn",text:"Retry",onclick:()=>{this._trayCache.delete(t),this._renderTray()}})]));return}if(this._trayTab===t){if(!r.length){e.textContent="",e.appendChild(re("div",{class:"ars-tray-empty"},[re("p",{text:n.emptyCopy||"Nothing here yet."}),this.forge?re("button",{type:"button",class:"ars-btn ars-btn-primary",text:"Generate a model",onclick:()=>{this._closeTray(),this.ui.forgeInput?.focus()}}):null]));return}this._renderList(e,n,r)}}_renderList(e,t,n){e.textContent="";let r=t.searchable??n.length>24,s=Du,a=null;r&&(a=re("input",{class:"ars-search",type:"search",autocomplete:"off",placeholder:`Search ${n.length} models\u2026`,"aria-label":`Search ${t.label||"models"}`}),e.appendChild(a)),t.hint&&e.appendChild(re("p",{class:"ars-hint",text:t.hint}));let o=re("ul",{class:"ars-item-list"}),l=re("div",{class:"ars-more"});e.appendChild(o),e.appendChild(l);let c=()=>{let h=(a?.value||"").trim().toLowerCase(),d=h?n.filter(f=>(f.keywords||f.title||"").toLowerCase().includes(h)):n;o.textContent="";for(let f of d.slice(0,s))o.appendChild(this._trayItem(f));if(l.textContent="",d.length>s){let f=d.length-s;l.appendChild(re("button",{type:"button",class:"ars-btn",text:`Show ${Math.min(Du,f)} more (${f} left)`,onclick:()=>{s+=Du,c()}}))}else d.length||l.appendChild(re("p",{class:"ars-hint",text:"Nothing matches that search."}))};a?.addEventListener("input",()=>{s=Du,c()}),c()}_trayItem(e){let t=e.title||"Model",n=re("span",{class:"ars-item-thumb"});if(e.poster){let s=re("img",{src:e.poster,alt:"",loading:"lazy",decoding:"async"});s.addEventListener("error",()=>{n.textContent="",n.appendChild(re("span",{class:"ars-item-cube","aria-hidden":"true",text:"\u25C6"}))},{once:!0}),n.appendChild(s)}else n.appendChild(re("span",{class:"ars-item-cube","aria-hidden":"true",text:"\u25C6"}));let r=re("button",{type:"button",class:"ars-item-add",title:e.title||"","aria-label":`Add ${t} to your space`,onclick:()=>{this._closeTray(),this._addModel({src:e.src,title:t,poster:e.poster})}},[n,re("span",{class:"ars-item-title",text:t}),re("span",{class:"ars-item-cta",text:"Add"})]);return re("li",{class:"ars-item"},[r])}_renderLinkTab(e){e.textContent="";let t=re("input",{class:"ars-search",type:"url",inputmode:"url",required:!0,placeholder:"https://example.com/model.glb","aria-label":"GLB model URL"}),n=re("form",{},[re("label",{class:"ars-hint",for:"",text:"Paste a link to any .glb model"}),re("div",{class:"ars-link-row"},[t,re("button",{type:"submit",class:"ars-btn ars-btn-primary",text:"Add"})]),re("p",{class:"ars-hint",text:"Any https .glb works, as long as the host allows cross-origin requests."})]);n.addEventListener("submit",r=>{r.preventDefault();let s=Jr(t.value);if(!s){this._setStatus("That link is not a loadable https GLB.",{warn:!0}),t.focus();return}this._closeTray(),this._addModel({src:s,title:kC(s)})}),e.appendChild(n)}_forgeChip(e,t="",n=null){let r=this.ui.chip;if(!r)return;r.dataset.state=e,r.hidden=e==="idle";let s=r.querySelector(".ars-chip-label"),a=r.querySelector(".ars-chip-elapsed");s&&(s.textContent=t),a&&(a.textContent=n==null?"":`${Math.round(n)}s`)}async _startForge(e){let t=String(e||"").trim();if(!this.forge||t.length<3||this._forgeBusy)return null;this._forgeBusy=!0;let n=++this._forgeSeq;this.ui.forgeGo&&(this.ui.forgeGo.disabled=!0);let r=Date.now();this._forgeChip("working","Sending your prompt\u2026",0);let s=setInterval(()=>{if(this.ui.chip?.dataset.state==="working"){let a=this.ui.chip.querySelector(".ars-chip-label")?.textContent||"";this._forgeChip("working",a,(Date.now()-r)/1e3)}},1e3);try{let a=await this.forge.generate(t,{onProgress:o=>{n===this._forgeSeq&&this._forgeChip("working",o.message,o.elapsedMs/1e3)}});return n!==this._forgeSeq?null:(Rf({src:a.src,title:a.prompt,poster:a.poster},this._recentKey),this._trayCache.delete("recent"),this._forgeChip("idle"),this.ui.forgeInput&&(this.ui.forgeInput.value=""),await this._addModel({src:a.src,title:a.title,poster:a.poster},{announce:!1}),this._setStatus("Generated and placed. Pinch to resize, drag to move."),this._emit("generate",{model:a}),a)}catch(a){return n===this._forgeSeq&&(this._forgeChip("error",a?.message||"Generation failed."),setTimeout(()=>{this.ui.chip?.dataset.state==="error"&&this._forgeChip("idle")},6500)),this._emit("generate-error",{error:a,prompt:t}),null}finally{clearInterval(s),n===this._forgeSeq&&(this._forgeBusy=!1,this.ui.forgeGo&&(this.ui.forgeGo.disabled=!1))}}_enterAR(){return this.arMode==="webxr"?this._toggleXR():(this._openArSheet(),Promise.resolve())}_arCacheKey(e){return`${e.src}|${e.group.scale.x.toFixed(3)}`}async _targetUsdz(e){let{objectToUsdzBlob:t,glbUrlToUsdzBlob:n}=await Promise.resolve().then(()=>(su(),Qp));try{return await t(e.group)}catch(r){return hi.warn("live-scene USDZ export failed, refetching the source",r),n(e.src)}}_renderArPreview(e,t=384){if(this.xrSession)return null;let n=null;try{let r=Cs(e.group);r.position.set(0,0,0),r.rotation.set(0,0,0),r.updateMatrixWorld(!0);let s=new rn().setFromObject(r);if(s.isEmpty())return null;let a=s.getCenter(new W),o=Math.max(s.getSize(new W).length()/2,.01),l=new Or;l.add(r),l.add(new ma(16777215,3816008,3.4));let c=new Di(16777215,3.6);c.position.set(1.4,2.2,1.8);let h=new Di(14673151,1.5);h.position.set(-1.6,.9,-1.2),l.add(c,h);let d=32,f=new an(d,1,o/100,o*100),p=o/Math.sin(d*Math.PI/360)*1.06;f.position.set(a.x+p*.62,a.y+p*.42,a.z+p*.66),f.lookAt(a),n=new Hn(t,t,{depthBuffer:!0});let x=this.renderer.getRenderTarget();this.renderer.setRenderTarget(n),this.renderer.clear(),this.renderer.render(l,f);let y=new Uint8Array(t*t*4);this.renderer.readRenderTargetPixels(n,0,0,t,t,y),this.renderer.setRenderTarget(x);let b=document.createElement("canvas");b.width=t,b.height=t;let g=b.getContext("2d"),S=g.createImageData(t,t),A=t*4;for(let T=0;T<t;T++)S.data.set(y.subarray((t-1-T)*A,(t-T)*A),T*A);return g.putImageData(S,0,0),b.toDataURL("image/png")}catch(r){return hi.warn("AR preview render failed",r),null}finally{n?.dispose()}}_arDefaultTarget(){return this.selected||this.placements[this.placements.length-1]||null}_warmQuickLook(){this._destroyed||this.arMode!=="quicklook"||(clearTimeout(this._arWarmTimer),this._arWarmTimer=setTimeout(()=>{if(this._destroyed)return;let e=this._arDefaultTarget();if(!e)return;let t=this._arCacheKey(e);cu(t)||(this._arKeys.add(t),ec({src:e.src,title:e.title,key:t,build:()=>this._targetUsdz(e)}).catch(n=>{hi.warn("AR warm-up failed",n)}))},900))}_openArSheet(e){let t=this.ui;t.arModal&&(this._lastFocus=document.activeElement,t.arModal.hidden=!1,this._showArTarget(e||this._arDefaultTarget()),(t.arGo.hidden||t.arGo.disabled?t.arClose:t.arGo)?.focus?.(),this._emit("ar-sheet",{open:!0}))}_closeArSheet(){let{arModal:e,xrBtn:t}=this.ui;if(!e||e.hidden)return;let n=e.contains(document.activeElement);e.hidden=!0,this._arToken++,n&&this._restoreFocus(t),this._emit("ar-sheet",{open:!1})}_setArStatus(e,{state:t=""}={}){let n=this.ui.arStatus;n&&(n.textContent="",n.classList.toggle("is-error",t==="error"),n.classList.toggle("is-ready",t==="ready"),e&&(t==="busy"&&n.appendChild(re("span",{class:"ars-spinner","aria-hidden":"true"})),n.appendChild(re("span",{text:e}))))}_showArTarget(e){let t=this.ui;if(!t.arModal||t.arModal.hidden)return;this._arToken++,this._arHandoff=null,this._arTarget=e||null;let n=t.arGo.querySelector(".ars-ar-go-label");if(this._arRetry=null,t.arXr.hidden=this.arMode!=="webxr",t.arQr.hidden=!0,t.arPicker.hidden=!0,t.arPicker.textContent="",!e){t.arThumb.textContent="\u{1FA84}",t.arName.textContent="Nothing to place yet",t.arHint.textContent="Add a model to the scene and it can stand on your real floor at its real size.",this._setArStatus(null),t.arGo.hidden=!1,t.arGo.disabled=!1,t.arGo.removeAttribute("aria-busy"),n&&(n.textContent="Browse models"),t.arGo.querySelector(".ars-ar-go-icon").hidden=!0;return}t.arThumb.textContent="\u25C6";let r=this._renderArPreview(e)||e.poster;if(r){let s=re("img",{src:r,alt:""});s.addEventListener("error",()=>{t.arThumb.textContent="\u25C6"},{once:!0}),t.arThumb.textContent="",t.arThumb.appendChild(s)}if(t.arName.textContent=e.title||"Model",this.placements.length>1){t.arPicker.hidden=!1;for(let s of this.placements)t.arPicker.appendChild(re("button",{type:"button",class:"ars-ar-chip","data-ar-id":s.id,"aria-pressed":s===e?"true":"false",text:s.title||"Model"}))}if(this.arMode==="none"){t.arHint.textContent="AR needs a phone. Open this scene on your iPhone or Android and the model stands on your real floor.",this._setArStatus(null),t.arGo.hidden=!0,t.arQr.hidden=!1;return}t.arHint.textContent="Point your device at a flat surface, then drag to place it. It arrives at real size.",t.arGo.hidden=!1,t.arGo.querySelector(".ars-ar-go-icon").hidden=!1,n&&(n.textContent="Place in your space"),this._prepareArTarget(e)}async _prepareArTarget(e){let t=this.ui,n=this._arToken,r=this._arCacheKey(e),s=this.arMode!=="quicklook"||cu(r);s||(t.arGo.disabled=!0,t.arGo.setAttribute("aria-busy","true"),this._setArStatus("Preparing it for AR\u2026",{state:"busy"})),this._arKeys.add(r);try{let a=await ec({src:e.src,title:e.title,key:r,build:()=>this._targetUsdz(e)},{fallbackUrl:this.config.shareBaseUrl});if(n!==this._arToken||this._destroyed)return;this._arHandoff=a,t.arGo.disabled=!1,t.arGo.removeAttribute("aria-busy"),this._setArStatus(s?null:"Ready.",{state:"ready"});let o=document.activeElement===document.body||document.activeElement===t.arModal;!s&&o&&t.arGo.focus?.()}catch(a){if(n!==this._arToken||this._destroyed)return;hi.warn("AR preparation failed",a),t.arGo.disabled=!0,t.arGo.removeAttribute("aria-busy"),this._setArStatus(`Could not prepare this model for AR (${a?.message||a}).`,{state:"error"}),this._arRetry=e,t.arGo.disabled=!1,t.arGo.querySelector(".ars-ar-go-label").textContent="Try again",t.arGo.querySelector(".ars-ar-go-icon").hidden=!0,this._emit("native-ar-error",{error:a,src:e.src})}}_onArGo(){if(!this._arTarget){this._closeArSheet(),this._openTray();return}if(this._arRetry){this._showArTarget(this._arRetry);return}let e=this._arHandoff;if(!e)return;let{src:t,title:n}=this._arTarget;this._yieldCameraToNativeAr();try{e.open()}catch(r){hi.warn("native AR failed to open",r),this._setArStatus(`Could not open AR (${r?.message||r}).`,{state:"error"}),this._emit("native-ar-error",{error:r,src:t});return}this._emit("native-ar",{src:t,title:n,viewer:e.viewer}),this._closeArSheet(),this._setStatus("Point at the floor, then drag to place it.")}async _placeNative(e){let t=e||this.selected||this.placements[this.placements.length-1];if(!t)return this._setStatus("Add a model first, then place it in your space.",{warn:!0}),null;if(this._nativeArBusy)return null;this._nativeArBusy=!0;let n=this.ui.xrBtn;n?.setAttribute("aria-busy","true"),this._arKeys.add(this._arCacheKey(t));let r={download:"Fetching the model\u2026",parse:"Reading the model\u2026",convert:"Preparing it for AR\u2026",open:"Opening AR\u2026"};this._setStatus(r.download,{sticky:!0}),(this.arMode==="quicklook"||this.arMode==="sceneviewer")&&this._yieldCameraToNativeAr();try{let s=await im({src:t.src,title:t.title,key:this._arCacheKey(t),build:()=>this._targetUsdz(t)},{onProgress:a=>this._setStatus(r[a]||"Preparing AR\u2026",{sticky:!0}),fallbackUrl:this.config.shareBaseUrl});return s==="none"?this._setStatus("This device has no AR viewer. Open this scene on a phone instead.",{warn:!0,actionLabel:"Show QR",onAction:()=>this._openQr()}):this._setStatus("Point at the floor, then drag to place it."),this._emit("native-ar",{src:t.src,title:t.title,viewer:s}),s}catch(s){return hi.warn("native AR failed",s),this._setStatus(`Could not open AR for this model (${s?.message||s}).`,{warn:!0,actionLabel:"Try again",onAction:()=>this._placeNative(t)}),this._emit("native-ar-error",{error:s,src:t.src}),null}finally{this._nativeArBusy=!1,n?.removeAttribute("aria-busy")}}async _toggleXR(){if(this.xrSession){this.xrSession.end();return}if(!this.arTransitioning){this.arTransitioning=!0;try{this.arActive&&this._stopCamera();let e=new Uh({renderer:this.renderer,scene:this.scene,camera:this.camera,domOverlayRoot:this.ui.hud,getArmedContent:()=>this._armedContent(),onPlaced:t=>{let n=this.placements.find(r=>r.group===t);n&&(n.yaw=0,this._select(null)),this._saveScene(),this._setStatus(`Placed ${this.xrSession?.placedCount??""}: tap another spot to add one more.`)},getScaleTarget:()=>this.placements[this.placements.length-1]?.group??null,onScale:(t,{final:n})=>{n&&this._saveScene()},onHit:t=>this.ui.root.classList.toggle("xr-has-floor",t),onTracking:t=>{t?this._setStatus(null):this._setStatus("Tracking lost: move to a brighter spot with more texture.",{warn:!0,sticky:!0})},onFrame:t=>{for(let n of this.placements)n.mixer?.update(t),n.idle?.update(t)},onEnd:()=>this._onXREnd()});this._stopLoop(),await e.start(),this.xrSession=e,this.estimatedLight=new Dh({renderer:this.renderer,scene:this.scene,baseLights:[this.hemi,this.sun],onChange:t=>{t&&this._setStatus("Lit by your room: reflections and shadows match the real light.")}}),this.estimatedLight.start(),this.ui.root.classList.add("is-xr"),this.grid.visible=!1,this.scene.fog=null,this.selRing.visible=!1;for(let t of this.placements)t.shadow&&(t.shadow.visible=!1);this.ui.xrBtn?.classList.add("is-active"),this.ui.xrBtn?.setAttribute("aria-pressed","true"),this._setStatus("Point at the floor, then tap to place. Every tap adds another model."),this._emit("xr",{active:!0})}catch(e){hi.warn("XR session failed",e),this.estimatedLight?.dispose(),this.estimatedLight=null,this._startLoop(),this._setStatus("Could not start immersive AR on this device. Camera mode still works.",{warn:!0})}finally{this.arTransitioning=!1}}}_armedContent(){let e=this._armed?.src??this.placements[this.placements.length-1]?.src;if(!e)return this._setStatus("Pick a model first: Add or generate one, then tap the floor.",{warn:!0}),null;let t=this._templatesReady.get(e);if(!t)return this._loadTemplate(e),this._setStatus("Model is still loading: one moment, then tap again.",{sticky:!0}),null;let{group:n,mixer:r,idlePromise:s}=this._instantiate(t,e),a={id:`p-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`,src:e,title:this._armed?.title||"",poster:"",group:n,shadow:null,mixer:r,idle:null,yaw:0,baseRadius:t.radius,height:t.height||0,spawnT:1,netId:null,ownerId:null,remote:!1,_lastNetSend:0};return s?.then(o=>{o&&(this.placements.includes(a)?a.idle=o:o.detach())}),this.placements.push(a),this._updateCount(),this._emit("add",{placement:rg(a,this),remote:!1}),n}_onXREnd(){this.xrSession=null,this.estimatedLight?.dispose(),this.estimatedLight=null,this.ui.root.classList.remove("is-xr","xr-has-floor"),this.ui.xrBtn?.classList.remove("is-active"),this.ui.xrBtn?.setAttribute("aria-pressed","false");for(let e of this.placements)e.group.position.y=0,e.shadow&&(e.shadow.visible=!0,e.shadow.position.set(e.group.position.x,.004,e.group.position.z));this.grid.visible=!this.arActive,this.arActive||(this.scene.fog=this._fog),this._saveScene(),this._startLoop(),this._setStatus("Back to the studio view."),this._emit("xr",{active:!1})}async _capturePhoto(){this.renderer.render(this.scene,this.camera);let e=await Mp({canvas:this.ui.canvas,video:this.ui.video,isAR:this.arActive});if(!e){this._setStatus("Could not capture the frame.",{warn:!0});return}try{let t=await Ap(e,{filename:"ar-studio.png",title:this.config.branding?.title||"AR Studio"});this._setStatus(t==="shared"?"Shared.":"Saved to your downloads.")}catch(t){t?.name!=="AbortError"&&this._setStatus("Could not share that photo.",{warn:!0})}}_openQr(){let{qrModal:e,qrBox:t,qrLink:n}=this.ui;if(!e)return;this._lastFocus=document.activeElement;let r=this.shareUrl();if(t)try{t.innerHTML=Vo(r,{scale:6,margin:2,dark:"#0b0b0b",light:"#ffffff"})}catch{try{t.innerHTML=Vo(Qh(this.config.shareBaseUrl,this.getScene()),{scale:6,margin:2,dark:"#0b0b0b",light:"#ffffff"})}catch{t.textContent=r}}n&&(n.href=r,n.textContent=r.length>72?`${r.slice(0,69)}\u2026`:r),e.hidden=!1,this.ui.qrClose?.focus?.(),this._emit("share",{url:r})}_closeQr(){let{qrModal:e,qrBtn:t}=this.ui;if(!e||e.hidden)return;let n=e.contains(document.activeElement);e.hidden=!0,n&&this._restoreFocus(t)}_isMine(e){return!e.ownerId||e.ownerId===this.clientId}_placementShared(e){return om({x:e.group.position.x,z:e.group.position.z,yaw:e.yaw,scale:this._logicalScale(e),height:e.height||0})}_placementWire(e,t){return{id:t,src:e.src,title:e.title,...this._placementShared(e)}}_netBroadcastTransform(e){if(!this.net||this.net.status!=="online"||!e.netId||!this._isMine(e))return;let t=Date.now();if(t-(e._lastNetSend||0)<80)return;e._lastNetSend=t;let n=this._placementShared(e);this.net.update(e.netId,{relEast:n.relEast,relNorth:n.relNorth,yawDeg:n.yawDeg,scale:n.scale})}_applySharedTransform(e,t){let n=uu(t);e.group.position.set(n.x,0,n.z),e.yaw=n.yaw,e.group.rotation.y=n.yaw,e.group.scale.setScalar(n.scale),e.group.userData._targetScale=n.scale,e.spawnT=1,e.shadow&&(e.shadow.position.set(n.x,.004,n.z),e.shadow.scale.setScalar(n.scale)),this.selected===e&&this._positionSelRing()}_reconcileRemoteModels(e){let t=new Set(e.map(r=>r.id));for(let r of[...this.placements])r.remote&&r.netId&&!t.has(r.netId)&&this._removePlacement(r,{persist:!1,broadcast:!1});let n=0;for(let r of e){let s=this._netModels.get(r.id);if(s){this._isMine(s)||this._applySharedTransform(s,r);continue}let a=uu(r),o=!!r.mine||r.ownerId===this.clientId;o||n++,this._addModel({src:r.src,title:r.title},{x:a.x,z:a.z,yaw:a.yaw,scale:a.scale,remote:!0,netId:r.id,ownerId:o?this.clientId:r.ownerId,announce:!1,persist:!1})}this._updateCount(),this._roomSynced&&n>0&&this._setStatus(n===1?"Someone added a model to the room.":`${n} models were added to the room.`),this._roomSynced=!0}_applyRemoteModelChange(e){let t=this._netModels.get(e.id);if(t){if(e.removed){t.remote&&this._removePlacement(t,{persist:!1,broadcast:!1});return}this._isMine(t)||this._applySharedTransform(t,e)}}_wireNet(e){e.on("status",({status:t})=>{t==="online"?(this._setStatus(`Shared room ${this.roomCode} is live: edits sync to everyone here.`),this.ui.root.classList.add("is-room")):t==="connecting"?this._setStatus(`Joining room ${this.roomCode}\u2026`,{sticky:!0}):t==="unavailable"||t==="failed"?(this._setStatus("Shared rooms are offline right now: you can still build solo.",{warn:!0}),this._leaveRoom({silent:!0})):t==="offline"&&this._setStatus("Reconnecting to the room\u2026",{sticky:!0}),this._updateRoomButton(),this._emit("room",{status:t,code:this.roomCode})}),e.on("models",t=>this._reconcileRemoteModels(t)),e.on("model",t=>this._applyRemoteModelChange(t)),e.on("presence",t=>{let n=this._presence.count;this._presence=t,this._updateCount(),this.ui.roomModal.hidden||this._renderRoomModal(),n>0&&t.count>n?this._setStatus(t.count===2?"Someone joined: you're building together now.":"Someone else joined the room."):n>1&&t.count<n&&t.count>=1&&this._setStatus(t.count===1?"You're on your own in the room now.":"Someone left the room.")}),e.on("reject",t=>{let n=t?.reason==="room_full"?"the room is full":t?.reason==="owner_full"?"you have the maximum models in this room":"the room declined it";this._setStatus(`Couldn't share that model: ${n}.`,{warn:!0})})}_seedRoom(){if(!(!this.net||this.net.status!=="online"))for(let e of this.placements){if(e.netId)continue;let t=`m${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`.slice(0,40);e.netId=t,e.ownerId=this.clientId,e.remote=!1,this._netModels.set(t,e),this.net.spawn(this._placementWire(e,t))}}async _joinRoom(e,{seed:t=!1}={}){let n=Fs(e);if(!n){this._setStatus("That room code looks off: check the 6 characters and try again.",{warn:!0});return}this._leaveRoom({silent:!0}),this._roomSynced=!1,this.roomCode=n;let r=new Lu({roomKey:lm(n),clientId:this.clientId,name:"",url:this.config.rooms?.server||""});if(this.net=r,this._wireNet(r),await r.connect(),this.net===r&&r.status==="online"){t&&this._seedRoom(),this._roomHeartbeat=setInterval(()=>this.net?.heartbeat(),15e3);try{let s=new URL(location.href);s.searchParams.set("room",n),history.replaceState(null,"",s)}catch{}}this._updateRoomButton()}_createRoom(){return this._joinRoom(cm(),{seed:!0})}_leaveRoom({silent:e=!1}={}){if(this._roomHeartbeat&&(clearInterval(this._roomHeartbeat),this._roomHeartbeat=null),this.net){try{this.net.destroy()}catch{}this.net=null}for(let t of[...this.placements])t.remote&&!this._isMine(t)?this._removePlacement(t,{persist:!1,broadcast:!1}):(t.netId=null,t.remote=!1);this._netModels.clear(),this.roomCode="",this._presence={count:1,names:[]},this.ui.root.classList.remove("is-room");try{let t=new URL(location.href);t.searchParams.delete("room"),history.replaceState(null,"",t)}catch{}this._updateCount(),this._updateRoomButton(),e||this._setStatus("Left the shared room. Your models are still here.")}_updateRoomButton(){let e=this.ui.roomBtn;if(!e)return;let t=!!this.net&&(this.net.status==="online"||this.net.status==="connecting");e.classList.toggle("is-active",t);let n=e.querySelector(".ars-room-label"),r=e.querySelector(".ars-room-code-label");n&&(n.hidden=t),r&&(r.hidden=!t,r.textContent=t?this.roomCode||"Room":""),this.ui.roomModal.hidden||this._renderRoomModal()}_renderRoomModal(){let e=!!this.net&&this.net.status==="online",{roomIdle:t,roomLive:n,roomCode:r,roomPresence:s,roomQr:a}=this.ui;if(t&&(t.hidden=e),n&&(n.hidden=!e),!!e&&(r&&(r.textContent=this.roomCode),s&&(s.textContent=this._presence.count>1?`${this._presence.count} people are building here.`:"You are the only one here yet: share the code to invite someone."),a)){let o=nc(this.config.shareBaseUrl,this.roomCode);try{a.innerHTML=Vo(o,{scale:5,margin:2,dark:"#0b0b0b",light:"#ffffff"})}catch{a.textContent=o}}}_openRoomModal(){let e=this.ui.roomModal;e&&(this._lastFocus=document.activeElement,e.hidden=!1,this._renderRoomModal(),(this.net?.status==="online"?this.ui.roomCopy:this.ui.roomCreate)?.focus?.())}_closeRoomModal(){let e=this.ui.roomModal;if(!e||e.hidden)return;let t=e.contains(document.activeElement);e.hidden=!0,t&&this._restoreFocus(this.ui.roomBtn)}async _createRoomFromUI(){if(await this._createRoom(),this._renderRoomModal(),this.net?.status==="online"&&navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(nc(this.config.shareBaseUrl,this.roomCode)),this._setStatus(`Room ${this.roomCode} is live: invite link copied. Paste it to a friend.`)}catch{}}async _joinRoomFromUI(){let e=this.ui.roomJoinInput,t=Fs(e?.value);if(!t){this._setStatus("That room code looks off: check the 6 characters.",{warn:!0}),e?.focus?.();return}await this._joinRoom(t),this._renderRoomModal()}async _copyRoomInvite(){let e=nc(this.config.shareBaseUrl,this.roomCode),t=this.ui.roomCopy;try{let n=await Tp(e,{title:"Build with me in AR",text:`Join my AR Studio room: ${this.roomCode}`});if(t){let r=t.textContent;t.textContent=n==="shared"?"Shared \u2713":"Link copied \u2713",setTimeout(()=>{t.textContent=r},1600)}}catch(n){n?.name!=="AbortError"&&window.prompt("Copy this invite link:",e)}}_framePreview(){if(this.arActive||this.xrSession||this._userLooked||!this.placements.length)return;let e=0,t=0,n=0;for(let c of this.placements)e+=c.group.position.x,t+=c.group.position.z,n+=(c.height||.4)*(c.group.userData._targetScale??1);let r=this.placements.length,s=e/r,a=t/r,o=n/r*.5,l=Math.hypot(s-this.camera.position.x,a-this.camera.position.z);l>.05&&(this.cameraYaw=Math.atan2(s-this.camera.position.x,-(a-this.camera.position.z)),this.cameraPitch=lu(-Math.atan2(this.camera.position.y-o,l),eg,tg))}_applyCameraLook(){this.camera.rotation.set(0,0,0),this.camera.rotateY(this.cameraYaw),this.camera.rotateX(this.cameraPitch)}_tick(e){this._rafId=requestAnimationFrame(n=>this._tick(n));let t=this._prevT?Math.min(.1,(e-this._prevT)/1e3):.016;this._prevT=e;for(let n of this.placements)if(n.mixer?.update(t),n.idle?.update(t),n.spawnT<1){n.spawnT=Math.min(1,n.spawnT+t*3.2);let r=1-(1-n.spawnT)**3,s=n.group.userData._targetScale??1;n.group.scale.setScalar(Math.max(.001,s*r)),n.shadow?.scale.setScalar(Math.max(.001,s*r))}this.selected&&this._positionSelRing(),this._applyCameraLook(),this.renderer.render(this.scene,this.camera)}_startLoop(){this._rafId===null&&(this._prevT=0,this._rafId=requestAnimationFrame(e=>this._tick(e)))}_stopLoop(){this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}_resize(){let{width:e,height:t}=this._viewportSize();this.renderer.setSize(e,t,!1),this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this._applyCameraFov()}addModel(e,t){return this._addModel(e,t)}clear(){let e=this.getScene();for(let t of[...this.placements])this._removePlacement(t,{persist:!1});return this._saveScene(),this._emit("clear",{items:e}),e}getScene(){return this.placements.map(e=>({src:e.src,title:e.title,x:e.group.position.x,z:e.group.position.z,yaw:e.yaw,scale:this._logicalScale(e)}))}async setScene(e){this.clear();for(let t of Array.isArray(e)?e:[])await this._addModel({src:t.src,title:t.title},{x:t.x,z:t.z,yaw:t.yaw,scale:t.scale,announce:!1,persist:!1});this._saveScene()}shareUrl(){return Lp(this.config.shareBaseUrl,this.getScene())}generate(e){return this._startForge(e)}viewInYourSpace(e,t=""){let n=Jr(e);if(!n)return"";let r=Ih(this.config.origin,n,t,{endpoint:this.config.arLaunchUrl});return window.open(r,"_blank","noopener"),r}startCamera(){return this._startCamera()}stopCamera(){this._stopCamera()}toggleImmersive(){return this._toggleXR()}enterAR(){return this._enterAR()}placeInYourSpace(e){return this._placeNative(e)}openArSheet(e){this._openArSheet(e)}closeArSheet(){this._closeArSheet()}async openRoom(e){return e?await this._joinRoom(e):await this._createRoom(),this.roomCode}leaveRoom(){this._leaveRoom()}destroy(){if(!this._destroyed){this._destroyed=!0,this._stopLoop(),this._stopCamera(),this.xrSession?.end(),this.net?.destroy(),this._roomHeartbeat&&clearInterval(this._roomHeartbeat),clearTimeout(this._statusTimer),clearTimeout(this._arWarmTimer);for(let e of this._arKeys)ou(e);this._arKeys.clear(),clearInterval(this._lightTimer),document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("deviceorientationabsolute",this._onOrientationAbsolute,!0),window.removeEventListener("deviceorientation",this._onOrientation,!0),window.removeEventListener("resize",this._onResize),window.removeEventListener("pagehide",this._onPageHide),this._onArReturn&&(document.removeEventListener("visibilitychange",this._onArReturn),window.removeEventListener("focus",this._onArReturn),this._onArReturn=null),this._ro?.disconnect();for(let e of[...this.placements])this._removePlacement(e,{persist:!1,broadcast:!1});this.shadowTex?.dispose(),this.selRing.geometry.dispose(),this.selRing.material.dispose(),this.renderer.dispose(),this.ui.root.remove(),this._listeners.clear()}}};function NC(){try{return!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches}catch{return!1}}function OC(){try{let e=document.createElement("canvas");e.width=128,e.height=128;let t=e.getContext("2d"),n=t.createRadialGradient(128/2,128/2,0,128/2,128/2,128/2);return n.addColorStop(0,"rgba(0,0,0,0.40)"),n.addColorStop(.55,"rgba(0,0,0,0.18)"),n.addColorStop(1,"rgba(0,0,0,0)"),t.fillStyle=n,t.fillRect(0,0,128,128),new Ss(e)}catch{return null}}function FC(){try{let i=document.createElement("canvas");return i.width=16,i.height=16,{cnv:i,ctx:i.getContext("2d",{willReadFrequently:!0})}}catch{return null}}function UC(i){let e=`${i||"ar-studio"}:client`;try{let t=localStorage.getItem(e);return t||(t=crypto?.randomUUID?.()||`c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,localStorage.setItem(e,t)),t}catch{return`c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function kC(i){let t=(String(i).split("?")[0].split("/").pop()||"Model").replace(/\.(glb|gltf)$/i,"").replace(/[_-]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Linked model"}function rg(i,e){return{id:i.id,src:i.src,title:i.title,x:i.group.position.x,z:i.group.position.z,yaw:i.yaw,scale:e._logicalScale(i),mine:e._isMine(i)}}su();eu();Vh();function xc(i=document.body,e={}){let t=typeof i=="string"?document.querySelector(i):i;if(!t)throw new Error(`ar-studio: no element matched ${JSON.stringify(i)}`);return new bc(t,e)}var gv=(i,e)=>i==null?e:i!=="false"&&i!=="0",Nu=class extends HTMLElement{static get observedAttributes(){return["assets","title","accent","back-href","generate","rooms","room-server","origin","share-base"]}connectedCallback(){this.studio||(this.style.display||(this.style.display="block"),!this.style.minHeight&&!this.hasAttribute("embedded")&&(this.style.minHeight="70vh"),this.studio=xc(this,this.options()))}disconnectedCallback(){this.studio?.destroy(),this.studio=null}options(){let e=n=>this.getAttribute(n),t=e("assets");return{...t?{assets:t.includes(",")?t.split(",").map(n=>n.trim()):t}:{},...e("origin")?{origin:e("origin")}:{},...e("share-base")?{shareBaseUrl:e("share-base")}:{},branding:{title:e("title")||"AR Studio",accent:e("accent")||void 0,backHref:e("back-href")||null},generate:{enabled:gv(e("generate"),!0)},rooms:{enabled:gv(e("rooms"),!0),...e("room-server")?{server:e("room-server")}:{}},fullscreen:!1}}};function sg(i="ar-studio"){typeof customElements>"u"||customElements.get(i)||customElements.define(i,Nu)}sg();function bv(){if(document.querySelector("ar-studio"))return;let i=document.querySelector("[data-ar-studio]");i?xc(i,BC(i)):document.documentElement.hasAttribute("data-ar-studio-auto")&&xc(document.body)}function BC(i){let e=i.getAttribute("data-assets");return e?{assets:e}:{}}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",bv,{once:!0}):bv();export{zE as AVATAR_TARGET_HEIGHT_M,bc as ArStudio,Nu as ArStudioElement,Ra as ArUrlError,lb as DEFAULTS,$b as DEFAULT_DRACO_PATH,Ch as DEFAULT_ORIGIN,tr as ForgeError,gb as GENERATE_TOOLS,Pf as LINK_SOURCE,Yp as MAX_AR_FOOTPRINT_M,Jp as MAX_AR_HEIGHT_M,Kh as MAX_PLACEMENTS,Ta as McpError,HE as PROP_TARGET_SIZE_M,Nf as QUALITY_TIERS,n_ as QUICK_LOOK_BANNER_TAPPED,VE as SCALE_MAX,GE as SCALE_MIN,Ep as SPAWN_DISTANCE_M,En as THREE_WS,Ff as applyCinematicDefaults,nm as arCapability,yb as assertArAssetUrl,Vp as bakeSkinnedMeshes,Ih as buildArLaunchUrl,Sb as buildSceneViewerUrl,wb as buildViewerUrl,a_ as cachedUsdzUrl,em as canUseQuickLook,tm as canUseSceneViewer,Mp as captureComposite,bb as catalogueItems,Cf as cdnUrl,mb as checkPromptSafety,Zp as clampToPlaceableSize,xR as clearQuickLookCache,Wp as coerceMaterialsToStandard,xc as createArStudio,Mf as createForgeClient,Ls as createLogger,yf as createMcpClient,sg as defineArStudio,Zh as deserializeScene,vb as detectArTarget,Of as detectQualityTier,qp as ensureNormals,xb as filenameTitle,Kp as fitToRoomScale,Ko as fitTransform,_f as generateQR,cm as generateRoomCode,wx as getIdleClipJson,Qx as glbUrlToUsdzBlob,Xp as groundOnFloor,t_ as isAndroid,e_ as isIOS,cu as isQuickLookReady,xT as isVerbose,pb as laneLabel,Uf as loadEnvironment,om as localToShared,ei as log,Wo as manifestSource,gf as mergeConfig,wp as mountIdle,am as normDeg,u_ as normRad,Ea as normalizeCatalogue,Jr as normalizeGlbUrl,Fs as normalizeRoomCode,Zx as objectToUsdzBlob,r_ as openQuickLook,s_ as openSceneViewer,im as placeInYourSpace,XT as planArLaunch,ec as prepareNativeAr,Sf as promptTitle,Ef as readRecents,Eh as recentSource,ou as releaseQuickLook,Rf as rememberRecent,RT as renderQRToCanvas,Vo as renderQRToSVG,bf as resolveConfig,Lf as resolveSources,lm as roomKeyForCode,Rp as roomLightFromPixels,nc as roomShareUrl,er as safeUrl,Pp as sceneFromHashParam,Mx as sceneToHashParam,ru as sceneToUsdzBlob,Jh as serializeScene,pE as setDracoPath,bT as setVerbose,Ap as shareOrDownload,Tp as shareUrlOrCopy,Gh as sharedGLTFLoader,uu as sharedToLocal,Cp as spawnPointInFront,vf as stageNarration,_b as staticSource,Lp as studioSceneUrl,Qh as studioShareUrl,If as threeWsCommunitySource,Rh as threeWsObjectsSource,Yh as touchAngle,Ip as twistDelta,Ah as unwrapToolResult,KT as updateGroundContactShadow,$p as usdzExportRoot,i_ as usdzFilename,wf as validatePrompt,yR as withQuickLookBanner};
+/*! Bundled license information:
+
+three/build/three.core.js:
+three/build/three.module.js:
+ (**
+ * @license
+ * Copyright 2010-2026 Three.js Authors
+ * SPDX-License-Identifier: MIT
+ *)
+
+three/examples/jsm/libs/fflate.module.js:
+ (*!
+ fflate - fast JavaScript compression/decompression
+ <https://101arrowz.github.io/fflate>
+ Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
+ version 0.8.2
+ *)
+*/
diff --git a/packages/ar-studio/docs/index.html b/packages/ar-studio/docs/index.html
new file mode 100644
index 000000000..cb544110a
--- /dev/null
+++ b/packages/ar-studio/docs/index.html
@@ -0,0 +1,290 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<title>3D AR Studio: put anything in your room</title>
+<meta name="description" content="A complete augmented-reality studio for any web page: place any number of 3D models in your real space through the camera, generate new ones from a prompt, share the scene as a link, and build together live." />
+<meta property="og:type" content="website" />
+<meta property="og:title" content="3D AR Studio: put anything in your room" />
+<meta property="og:description" content="A complete augmented-reality studio for any web page: place any number of 3D models in your real space through the camera, generate new ones from a prompt, share the scene as a link, and build together live." />
+<meta name="twitter:card" content="summary_large_image" />
+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%238b7cf8'/%3E%3Cpath d='M16 6l9 5.2v10.4L16 27l-9-5.4V11.2z' fill='none' stroke='%23fff' stroke-width='2' stroke-linejoin='round'/%3E%3C/svg%3E" />
+<style>
+:root {
+ color-scheme: dark;
+ --bg: #07080c;
+ --panel: rgba(255, 255, 255, 0.04);
+ --line: rgba(255, 255, 255, 0.1);
+ --ink: #ecedf2;
+ --dim: #9aa0af;
+ --faint: #6b7080;
+ --accent: #8b7cf8;
+ --accent-ink: #dcd6ff;
+ --radius: 16px;
+ --font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
+}
+* { box-sizing: border-box; }
+html { scroll-behavior: smooth; }
+body {
+ margin: 0;
+ font-family: var(--font);
+ background: radial-gradient(120% 90% at 50% 0%, #141827 0%, #0a0b11 45%, #06070a 100%);
+ color: var(--ink);
+ line-height: 1.6;
+ -webkit-font-smoothing: antialiased;
+}
+a { color: var(--accent-ink); }
+.wrap { max-width: 1040px; margin: 0 auto; padding: 0 20px; }
+header.site {
+ position: sticky; top: 0; z-index: 50;
+ backdrop-filter: blur(12px);
+ background: rgba(7, 8, 12, 0.72);
+ border-bottom: 1px solid var(--line);
+}
+header.site .wrap { display: flex; align-items: center; gap: 16px; height: 60px; }
+.brand { display: flex; align-items: center; gap: 9px; font-weight: 750; letter-spacing: -0.01em; text-decoration: none; color: var(--ink); }
+.brand .dot { width: 10px; height: 10px; border-radius: 3px; background: linear-gradient(135deg, var(--accent), #4fd1c5); box-shadow: 0 0 18px rgba(139, 124, 248, 0.7); }
+nav.site { margin-left: auto; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
+nav.site a {
+ color: var(--dim); text-decoration: none; font-size: 14px; font-weight: 600;
+ padding: 7px 11px; border-radius: 9px; transition: color .15s, background .15s;
+}
+nav.site a:hover, nav.site a[aria-current="page"] { color: var(--ink); background: rgba(255, 255, 255, 0.07); }
+h1, h2, h3 { line-height: 1.2; letter-spacing: -0.02em; margin: 0 0 12px; }
+h1 { font-size: clamp(34px, 6vw, 56px); font-weight: 800; }
+h2 { font-size: clamp(23px, 3.4vw, 31px); font-weight: 750; margin-top: 8px; }
+h3 { font-size: 17px; font-weight: 700; }
+p { margin: 0 0 14px; color: var(--dim); }
+p.lead { font-size: clamp(16px, 2.1vw, 19px); color: #c3c8d4; max-width: 62ch; }
+section { padding: 56px 0; border-top: 1px solid var(--line); }
+section:first-of-type { border-top: 0; }
+.eyebrow { font-size: 12px; font-weight: 750; letter-spacing: 0.14em; text-transform: uppercase; color: var(--accent); margin-bottom: 12px; }
+.row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
+.btn {
+ display: inline-flex; align-items: center; gap: 8px; text-decoration: none;
+ font-size: 15px; font-weight: 700; padding: 12px 20px; border-radius: 12px;
+ background: rgba(255, 255, 255, 0.06); border: 1px solid var(--line); color: var(--ink);
+ transition: background .15s, border-color .15s, transform .06s;
+ cursor: pointer;
+}
+.btn:hover { background: rgba(255, 255, 255, 0.11); border-color: rgba(255, 255, 255, 0.24); }
+.btn:active { transform: translateY(1px); }
+.btn.primary { background: var(--accent); border-color: var(--accent); color: #0d0b1e; }
+.btn.primary:hover { filter: brightness(1.08); }
+.grid { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(232px, 1fr)); }
+.card {
+ background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
+ padding: 18px 18px 16px;
+}
+.card h3 { margin-bottom: 6px; }
+.card p { font-size: 14px; margin: 0; }
+.card .ico { font-size: 22px; line-height: 1; margin-bottom: 10px; display: block; }
+pre {
+ margin: 0 0 14px; padding: 16px 18px; overflow-x: auto;
+ background: #0b0d13; border: 1px solid var(--line); border-radius: 13px;
+ font-family: var(--mono); font-size: 13.5px; line-height: 1.65; color: #d7dbe6;
+}
+code { font-family: var(--mono); font-size: 0.92em; }
+p code, li code, td code { background: rgba(255, 255, 255, 0.07); padding: 1.5px 6px; border-radius: 6px; color: var(--accent-ink); }
+table { width: 100%; border-collapse: collapse; font-size: 14px; margin-bottom: 16px; display: block; overflow-x: auto; }
+th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line); vertical-align: top; }
+th { color: var(--ink); font-weight: 700; white-space: nowrap; }
+td { color: var(--dim); }
+ul { color: var(--dim); padding-left: 22px; }
+li { margin-bottom: 7px; }
+.stage {
+ position: relative; height: min(72vh, 620px); min-height: 420px;
+ border: 1px solid var(--line); border-radius: 18px; overflow: hidden;
+ background: #06070a; box-shadow: 0 30px 80px -40px rgba(139, 124, 248, 0.5);
+}
+.pill {
+ display: inline-flex; align-items: center; gap: 7px; font-size: 12.5px; font-weight: 650;
+ color: var(--accent-ink); background: rgba(139, 124, 248, 0.14);
+ border: 1px solid rgba(139, 124, 248, 0.38); border-radius: 999px; padding: 6px 13px;
+ margin-bottom: 18px;
+}
+footer.site { border-top: 1px solid var(--line); padding: 34px 0 60px; color: var(--faint); font-size: 13.5px; }
+footer.site a { color: var(--dim); }
+.tabs { display: flex; gap: 6px; margin-bottom: 12px; flex-wrap: wrap; }
+.tab {
+ appearance: none; cursor: pointer; font: inherit; font-size: 13px; font-weight: 650;
+ color: var(--dim); background: rgba(255, 255, 255, 0.05); border: 1px solid transparent;
+ border-radius: 999px; padding: 7px 14px;
+}
+.tab[aria-selected="true"] { color: var(--accent-ink); background: rgba(139, 124, 248, 0.16); border-color: rgba(139, 124, 248, 0.4); }
+[hidden] { display: none !important; }
+@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
+</style>
+<script type="module" src="./ar-studio.min.js"></script>
+</head>
+<body>
+
+<header class="site"><div class="wrap">
+ <a class="brand" href="./index.html"><span class="dot" aria-hidden="true"></span> 3D AR Studio</a>
+ <nav class="site">
+ <a href="./index.html" aria-current="page">Overview</a>
+ <a href="./studio.html">Live demo</a>
+ <a href="./mcp.html">MCP server</a>
+ <a href="https://github.com/nirholas/3D-AR-Studio">GitHub</a>
+ <a href="https://www.npmjs.com/package/3d-ar-studio">npm</a>
+ </nav>
+</div></header>
+
+<section class="wrap" style="padding-top:56px">
+ <span class="pill">Apache-2.0 · one script tag · works on iPhone and Android</span>
+ <h1>Put anything in your room.</h1>
+ <p class="lead">
+ A complete augmented-reality studio you can drop into any web page. Place as many 3D models
+ as you like in your real space through the camera, describe a new one and watch it appear,
+ arrange everything by hand, then share the whole scene as a link, a QR code, or a live room
+ someone else can build in with you.
+ </p>
+ <div class="row" style="margin:22px 0 30px">
+ <a class="btn primary" href="./studio.html">Open the live demo</a>
+ <a class="btn" href="#quickstart">Add it to your site</a>
+ <a class="btn" href="https://github.com/nirholas/3D-AR-Studio">Star on GitHub</a>
+ </div>
+ <div class="stage"><ar-studio embedded style="position:absolute;inset:0;min-height:0"
+ title="Live demo" share-base="https://nirholas.github.io/3D-AR-Studio/studio.html"></ar-studio></div>
+ <p style="font-size:13px;color:var(--faint);margin-top:12px">
+ That frame is the real package, running the same code you install. On a phone, tap
+ <strong>Place in your space</strong> and the model is anchored to your actual floor by
+ ARKit or ARCore. <strong>Camera</strong> is the in-page preview beside it: it turns with
+ the phone, it does not track the room.
+ </p>
+</section>
+
+<section class="wrap" id="quickstart">
+ <div class="eyebrow">Quick start</div>
+ <h2>One line, and you have AR.</h2>
+ <p class="lead">No build step, no API key, no account. The models and the text-to-3D lane are free and keyless.</p>
+ <h3>Plain HTML</h3>
+<pre><code>&lt;script type="module" src="https://unpkg.com/3d-ar-studio/dist/ar-studio.min.js"&gt;&lt;/script&gt;
+&lt;ar-studio&gt;&lt;/ar-studio&gt;</code></pre>
+ <h3>npm</h3>
+<pre><code>npm i 3d-ar-studio three</code></pre>
+<pre><code>import { createArStudio } from '3d-ar-studio'
+
+const studio = createArStudio('#stage', {
+ assets: 'https://your.cdn/models.json', // your catalogue, or leave it out for the free CC0 library
+ branding: { title: 'Acme AR', accent: '#00b894' },
+})
+
+studio.on('add', ({ placement }) =&gt; console.log('placed', placement.title))</code></pre>
+ <h3>Scaffold a deployable page</h3>
+<pre><code>npx 3d-ar-studio create my-ar-site # a ready-to-publish folder
+npx 3d-ar-studio deploy # push it and turn on GitHub Pages</code></pre>
+</section>
+
+<section class="wrap">
+ <div class="eyebrow">What you get</div>
+ <h2>Not a model viewer. A studio.</h2>
+ <div class="grid">
+ <div class="card"><span class="ico" aria-hidden="true">🏠</span>
+ <h3>Many models, one room</h3>
+ <p>Place, drag, pinch-resize, twist-rotate and duplicate as many models as you want in a single live camera view. Every other web-AR drop-in stops at one.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">✍️</span>
+ <h3>Generate without leaving the camera</h3>
+ <p>Type "a brass desk lamp" into the dock. The generation runs behind the live view and the finished model drops into the room. Free, keyless, no account.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">✦</span>
+ <h3>Real WebXR, not a fallback</h3>
+ <p>An always-armed hit-test reticle, one XRAnchor per model, real-world light estimation, and depth occlusion so models hide behind your furniture.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">📱</span>
+ <h3>Real ARKit on iPhone, not an approximation</h3>
+ <p>Tap <strong>Place in your space</strong> and Apple's own "View in AR" sheet opens: true plane detection, true scale, true occlusion. The model is converted to USDZ on the device, stood on the floor rather than left at the height it was modelled at, and prepared before the tap, because iOS opens Quick Look only while the gesture is still live. Android without WebXR gets Scene Viewer.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">🔗</span>
+ <h3>Scenes are links</h3>
+ <p>The whole arrangement (models, positions, rotations, scales) round-trips through the URL. Compose on a laptop, scan the QR, it reopens exactly on your phone.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">👥</span>
+ <h3>Build together, live</h3>
+ <p>Open a room, share a six-character code, and every add and move syncs to everyone in it in real time, with live presence.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">🕺</span>
+ <h3>Characters actually move</h3>
+ <p>Any humanoid GLB with no baked animation gets an idle clip retargeted onto its own skeleton: Mixamo, VRM, Avaturn, Unreal, Daz. No rig allow-list, no T-poses.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">🤖</span>
+ <h3>Agents can drive it</h3>
+ <p>A bundled MCP server lets Claude, ChatGPT or any agent generate a model, compose an arrangement, and hand your user one link that opens it in their room.</p></div>
+ </div>
+</section>
+
+<section class="wrap" id="assets">
+ <div class="eyebrow">Your models</div>
+ <h2>Bring your own catalogue.</h2>
+ <p class="lead">
+ Out of the box the tray is filled from three.ws: a few hundred public-domain (CC0) props,
+ free for commercial use, served with open CORS. Swap in your own with one option
+ a URL, an array, or a function.
+ </p>
+<pre><code>// 1. A JSON file anywhere. Five common shapes are read without reshaping.
+createArStudio(el, { assets: 'https://cdn.acme.com/models.json' })
+
+// 2. A list you hold in code.
+import { staticSource } from '3d-ar-studio/sources'
+createArStudio(el, { assets: staticSource({
+ label: 'Our furniture',
+ items: [{ src: 'https://cdn.acme.com/chair.glb', title: 'Aero chair', poster: '…' }],
+}) })
+
+// 3. Several tabs at once, in order.
+createArStudio(el, { assets: ['recent', myCatalogue, 'objects', 'link'] })
+
+// 4. Anything else: a source is just an object with a list().
+createArStudio(el, { assets: {
+ id: 'search', label: 'Search', searchable: true,
+ async list() {
+ const r = await fetch('/api/models').then((x) =&gt; x.json())
+ return r.map((m) =&gt; ({ src: m.glb, title: m.name, poster: m.thumb }))
+ },
+} })</code></pre>
+ <p>Your users can also point the studio somewhere else themselves, without touching your code:
+ add <code>?assets=https://…/manifest.json</code> to the page URL. Only https URLs are accepted, and every
+ model source is re-validated before it reaches the loader.</p>
+</section>
+
+<section class="wrap" id="options">
+ <div class="eyebrow">Configuration</div>
+ <h2>Options</h2>
+ <table>
+ <thead><tr><th>Option</th><th>Default</th><th>What it does</th></tr></thead>
+ <tbody>
+ <tr><td><code>assets</code></td><td><code>'three.ws'</code></td><td>Where models come from: a preset, a manifest URL, a source object, or an array of them.</td></tr>
+ <tr><td><code>generate</code></td><td>enabled, free three.ws lane</td><td><code>{ enabled, endpoint, kind, tier }</code>. <code>endpoint</code> is any MCP server exposing a compatible generate tool.</td></tr>
+ <tr><td><code>rooms</code></td><td>enabled</td><td><code>{ enabled, server }</code>. Point <code>server</code> at your own Colyseus deployment to host shared rooms yourself.</td></tr>
+ <tr><td><code>animations</code></td><td>three.ws idle clip</td><td><code>{ enabled, manifestUrl, clip }</code>. The clip retargeted onto humanoid models that ship no animation.</td></tr>
+ <tr><td><code>lighting</code></td><td><code>'studio'</code> HDRI</td><td><code>{ preset, urls }</code>. Set <code>preset: null</code> for procedural lighting only and zero HDRI download.</td></tr>
+ <tr><td><code>branding</code></td><td> </td><td><code>{ title, accent, backHref, backLabel }</code>.</td></tr>
+ <tr><td><code>shareBaseUrl</code></td><td>this page</td><td>Where share links and QR codes point.</td></tr>
+ <tr><td><code>persistKey</code></td><td><code>'ar-studio:scene:v1'</code></td><td>localStorage key for the saved scene. Change it to run two studios on one origin.</td></tr>
+ <tr><td><code>maxPlacements</code></td><td><code>20</code></td><td>Cap on simultaneous models. Keeps low-end phones interactive.</td></tr>
+ <tr><td><code>allowUrlOverride</code></td><td><code>true</code></td><td>Honour <code>?assets=</code>, <code>?src=</code>, <code>?room=</code> and <code>?forge=</code> on the hosting page's URL.</td></tr>
+ <tr><td><code>onEvent</code></td><td><code>null</code></td><td>Called with <code>(event, detail)</code> for every notable action: wire it to your analytics.</td></tr>
+ </tbody>
+ </table>
+ <h3>Events</h3>
+ <p>Subscribe with <code>studio.on(name, fn)</code>, or listen for <code>ar-studio:&lt;name&gt;</code> DOM events on the mounted element:
+ <code>add</code>, <code>remove</code>, <code>select</code>, <code>clear</code>, <code>generate</code>,
+ <code>generate-error</code>, <code>camera</code>, <code>xr</code>, <code>room</code>, <code>share</code>.</p>
+</section>
+
+<section class="wrap">
+ <div class="eyebrow">Provenance</div>
+ <h2>Extracted from a studio people already use.</h2>
+ <p class="lead">
+ This is not a demo written to look good in a README. The rendering ladder, the anchor
+ lifecycle, the retargeting pipeline, the scene format and the shared-room protocol are
+ lifted from the AR surfaces running in production on
+ <a href="https://three.ws">three.ws</a>, and generalized so they work on your site
+ with your models.
+ </p>
+</section>
+
+
+<footer class="site"><div class="wrap">
+ <p><strong style="color:var(--ink)">3D AR Studio</strong> is open source under Apache-2.0.
+ Models and the free text-to-3D lane are served by <a href="https://three.ws">three.ws</a>; point it at your own catalogue with one option.</p>
+ <p><a href="https://github.com/nirholas/3D-AR-Studio">GitHub</a> · <a href="https://www.npmjs.com/package/3d-ar-studio">npm</a> · <a href="https://registry.modelcontextprotocol.io/?q=3d-ar-studio">MCP registry</a> · <a href="https://three.ws">three.ws</a></p>
+</div></footer>
+</body>
+</html>
diff --git a/packages/ar-studio/docs/mcp.html b/packages/ar-studio/docs/mcp.html
new file mode 100644
index 000000000..2c85ed40e
--- /dev/null
+++ b/packages/ar-studio/docs/mcp.html
@@ -0,0 +1,199 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<title>MCP server: 3D AR Studio</title>
+<meta name="description" content="Let an agent generate 3D models, compose an AR scene, and hand a person one link that opens it in their room." />
+<meta property="og:type" content="website" />
+<meta property="og:title" content="MCP server: 3D AR Studio" />
+<meta property="og:description" content="Let an agent generate 3D models, compose an AR scene, and hand a person one link that opens it in their room." />
+<meta name="twitter:card" content="summary_large_image" />
+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%238b7cf8'/%3E%3Cpath d='M16 6l9 5.2v10.4L16 27l-9-5.4V11.2z' fill='none' stroke='%23fff' stroke-width='2' stroke-linejoin='round'/%3E%3C/svg%3E" />
+<style>
+:root {
+ color-scheme: dark;
+ --bg: #07080c;
+ --panel: rgba(255, 255, 255, 0.04);
+ --line: rgba(255, 255, 255, 0.1);
+ --ink: #ecedf2;
+ --dim: #9aa0af;
+ --faint: #6b7080;
+ --accent: #8b7cf8;
+ --accent-ink: #dcd6ff;
+ --radius: 16px;
+ --font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
+}
+* { box-sizing: border-box; }
+html { scroll-behavior: smooth; }
+body {
+ margin: 0;
+ font-family: var(--font);
+ background: radial-gradient(120% 90% at 50% 0%, #141827 0%, #0a0b11 45%, #06070a 100%);
+ color: var(--ink);
+ line-height: 1.6;
+ -webkit-font-smoothing: antialiased;
+}
+a { color: var(--accent-ink); }
+.wrap { max-width: 1040px; margin: 0 auto; padding: 0 20px; }
+header.site {
+ position: sticky; top: 0; z-index: 50;
+ backdrop-filter: blur(12px);
+ background: rgba(7, 8, 12, 0.72);
+ border-bottom: 1px solid var(--line);
+}
+header.site .wrap { display: flex; align-items: center; gap: 16px; height: 60px; }
+.brand { display: flex; align-items: center; gap: 9px; font-weight: 750; letter-spacing: -0.01em; text-decoration: none; color: var(--ink); }
+.brand .dot { width: 10px; height: 10px; border-radius: 3px; background: linear-gradient(135deg, var(--accent), #4fd1c5); box-shadow: 0 0 18px rgba(139, 124, 248, 0.7); }
+nav.site { margin-left: auto; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
+nav.site a {
+ color: var(--dim); text-decoration: none; font-size: 14px; font-weight: 600;
+ padding: 7px 11px; border-radius: 9px; transition: color .15s, background .15s;
+}
+nav.site a:hover, nav.site a[aria-current="page"] { color: var(--ink); background: rgba(255, 255, 255, 0.07); }
+h1, h2, h3 { line-height: 1.2; letter-spacing: -0.02em; margin: 0 0 12px; }
+h1 { font-size: clamp(34px, 6vw, 56px); font-weight: 800; }
+h2 { font-size: clamp(23px, 3.4vw, 31px); font-weight: 750; margin-top: 8px; }
+h3 { font-size: 17px; font-weight: 700; }
+p { margin: 0 0 14px; color: var(--dim); }
+p.lead { font-size: clamp(16px, 2.1vw, 19px); color: #c3c8d4; max-width: 62ch; }
+section { padding: 56px 0; border-top: 1px solid var(--line); }
+section:first-of-type { border-top: 0; }
+.eyebrow { font-size: 12px; font-weight: 750; letter-spacing: 0.14em; text-transform: uppercase; color: var(--accent); margin-bottom: 12px; }
+.row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
+.btn {
+ display: inline-flex; align-items: center; gap: 8px; text-decoration: none;
+ font-size: 15px; font-weight: 700; padding: 12px 20px; border-radius: 12px;
+ background: rgba(255, 255, 255, 0.06); border: 1px solid var(--line); color: var(--ink);
+ transition: background .15s, border-color .15s, transform .06s;
+ cursor: pointer;
+}
+.btn:hover { background: rgba(255, 255, 255, 0.11); border-color: rgba(255, 255, 255, 0.24); }
+.btn:active { transform: translateY(1px); }
+.btn.primary { background: var(--accent); border-color: var(--accent); color: #0d0b1e; }
+.btn.primary:hover { filter: brightness(1.08); }
+.grid { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(232px, 1fr)); }
+.card {
+ background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
+ padding: 18px 18px 16px;
+}
+.card h3 { margin-bottom: 6px; }
+.card p { font-size: 14px; margin: 0; }
+.card .ico { font-size: 22px; line-height: 1; margin-bottom: 10px; display: block; }
+pre {
+ margin: 0 0 14px; padding: 16px 18px; overflow-x: auto;
+ background: #0b0d13; border: 1px solid var(--line); border-radius: 13px;
+ font-family: var(--mono); font-size: 13.5px; line-height: 1.65; color: #d7dbe6;
+}
+code { font-family: var(--mono); font-size: 0.92em; }
+p code, li code, td code { background: rgba(255, 255, 255, 0.07); padding: 1.5px 6px; border-radius: 6px; color: var(--accent-ink); }
+table { width: 100%; border-collapse: collapse; font-size: 14px; margin-bottom: 16px; display: block; overflow-x: auto; }
+th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line); vertical-align: top; }
+th { color: var(--ink); font-weight: 700; white-space: nowrap; }
+td { color: var(--dim); }
+ul { color: var(--dim); padding-left: 22px; }
+li { margin-bottom: 7px; }
+.stage {
+ position: relative; height: min(72vh, 620px); min-height: 420px;
+ border: 1px solid var(--line); border-radius: 18px; overflow: hidden;
+ background: #06070a; box-shadow: 0 30px 80px -40px rgba(139, 124, 248, 0.5);
+}
+.pill {
+ display: inline-flex; align-items: center; gap: 7px; font-size: 12.5px; font-weight: 650;
+ color: var(--accent-ink); background: rgba(139, 124, 248, 0.14);
+ border: 1px solid rgba(139, 124, 248, 0.38); border-radius: 999px; padding: 6px 13px;
+ margin-bottom: 18px;
+}
+footer.site { border-top: 1px solid var(--line); padding: 34px 0 60px; color: var(--faint); font-size: 13.5px; }
+footer.site a { color: var(--dim); }
+.tabs { display: flex; gap: 6px; margin-bottom: 12px; flex-wrap: wrap; }
+.tab {
+ appearance: none; cursor: pointer; font: inherit; font-size: 13px; font-weight: 650;
+ color: var(--dim); background: rgba(255, 255, 255, 0.05); border: 1px solid transparent;
+ border-radius: 999px; padding: 7px 14px;
+}
+.tab[aria-selected="true"] { color: var(--accent-ink); background: rgba(139, 124, 248, 0.16); border-color: rgba(139, 124, 248, 0.4); }
+[hidden] { display: none !important; }
+@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
+</style>
+
+</head>
+<body>
+
+<header class="site"><div class="wrap">
+ <a class="brand" href="./index.html"><span class="dot" aria-hidden="true"></span> 3D AR Studio</a>
+ <nav class="site">
+ <a href="./index.html">Overview</a>
+ <a href="./studio.html">Live demo</a>
+ <a href="./mcp.html" aria-current="page">MCP server</a>
+ <a href="https://github.com/nirholas/3D-AR-Studio">GitHub</a>
+ <a href="https://www.npmjs.com/package/3d-ar-studio">npm</a>
+ </nav>
+</div></header>
+
+<section class="wrap" style="padding-top:48px">
+ <span class="pill">Model Context Protocol</span>
+ <h1>Let an agent build the scene.</h1>
+ <p class="lead">
+ The package ships an MCP server. Point Claude, ChatGPT, Cursor or your own agent at it and
+ it can generate 3D models, compose an arrangement, and hand a person one link that opens
+ that arrangement in their actual room.
+ </p>
+ <h2>Install</h2>
+<pre><code>{
+ "mcpServers": {
+ "3d-ar-studio": {
+ "command": "npx",
+ "args": ["-y", "3d-ar-studio-mcp"]
+ }
+ }
+}</code></pre>
+ <p>No API key. Every tool below is free and keyless.</p>
+
+ <h2>Tools</h2>
+ <table>
+ <thead><tr><th>Tool</th><th>What it does</th></tr></thead>
+ <tbody>
+ <tr><td><code>generate_3d_model</code></td><td>Turn a text prompt into a downloadable, textured GLB. Returns the model URL plus links that open it in AR.</td></tr>
+ <tr><td><code>check_generation</code></td><td>Collect a generation that was still rendering when the first call returned.</td></tr>
+ <tr><td><code>search_models</code></td><td>Search the free CC0 library (or any catalogue you configure) by name, category and tag.</td></tr>
+ <tr><td><code>compose_ar_scene</code></td><td>Arrange several models into one scene and return a single link (and a QR-friendly short form) that reopens it exactly.</td></tr>
+ <tr><td><code>export_ar</code></td><td>Turn any GLB URL into a device-aware "View in your space" link: Quick Look on iOS, Scene Viewer on Android, WebGL on desktop.</td></tr>
+ <tr><td><code>create_ar_page</code></td><td>Emit a complete, self-contained HTML page that embeds the studio, configured for the caller's models: ready to commit and publish.</td></tr>
+ </tbody>
+ </table>
+
+ <h2>What a session looks like</h2>
+<pre><code>&gt; Put a mid-century lamp and a potted fern in my living room.
+
+ generate_3d_model { prompt: "a brass mid-century desk lamp" } → lamp.glb
+ search_models { query: "potted plant" } → fern.glb
+ compose_ar_scene { models: [{ src: lamp.glb, x: 0, z: -1.4 },
+ { src: fern.glb, x: 0.9, z: -1.2 }] }
+
+ → https://your-page.example/ar/#s=… (open it on a phone; both objects
+ stand in the room, exactly where they were arranged)</code></pre>
+
+ <h2>Configuration</h2>
+ <table>
+ <thead><tr><th>Environment variable</th><th>Default</th><th>What it changes</th></tr></thead>
+ <tbody>
+ <tr><td><code>AR_STUDIO_PAGE_URL</code></td><td>the hosted demo</td><td>The page <code>compose_ar_scene</code> links to. Set it to your own deployment.</td></tr>
+ <tr><td><code>AR_STUDIO_ASSETS</code></td><td>the free CC0 library</td><td>Catalogue URL <code>search_models</code> searches.</td></tr>
+ <tr><td><code>AR_STUDIO_MCP_ENDPOINT</code></td><td>three.ws 3D Studio</td><td>The MCP endpoint used for generation.</td></tr>
+ <tr><td><code>AR_STUDIO_ORIGIN</code></td><td><code>https://three.ws</code></td><td>Origin for the hosted "View in your space" launcher and viewer links.</td></tr>
+ </tbody>
+ </table>
+ <p style="margin-top:24px"><a class="btn primary" href="./studio.html">See what it builds</a>
+ <a class="btn" href="https://github.com/nirholas/3D-AR-Studio#mcp-server">Full MCP docs</a></p>
+</section>
+
+
+<footer class="site"><div class="wrap">
+ <p><strong style="color:var(--ink)">3D AR Studio</strong> is open source under Apache-2.0.
+ Models and the free text-to-3D lane are served by <a href="https://three.ws">three.ws</a>; point it at your own catalogue with one option.</p>
+ <p><a href="https://github.com/nirholas/3D-AR-Studio">GitHub</a> · <a href="https://www.npmjs.com/package/3d-ar-studio">npm</a> · <a href="https://registry.modelcontextprotocol.io/?q=3d-ar-studio">MCP registry</a> · <a href="https://three.ws">three.ws</a></p>
+</div></footer>
+</body>
+</html>
diff --git a/packages/ar-studio/docs/studio.html b/packages/ar-studio/docs/studio.html
new file mode 100644
index 000000000..cddebe307
--- /dev/null
+++ b/packages/ar-studio/docs/studio.html
@@ -0,0 +1,130 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<title>Live demo: 3D AR Studio</title>
+<meta name="description" content="The full 3D AR Studio, running the published build. Open it on a phone and tap Camera." />
+<meta property="og:type" content="website" />
+<meta property="og:title" content="Live demo: 3D AR Studio" />
+<meta property="og:description" content="The full 3D AR Studio, running the published build. Open it on a phone and tap Camera." />
+<meta name="twitter:card" content="summary_large_image" />
+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%238b7cf8'/%3E%3Cpath d='M16 6l9 5.2v10.4L16 27l-9-5.4V11.2z' fill='none' stroke='%23fff' stroke-width='2' stroke-linejoin='round'/%3E%3C/svg%3E" />
+<style>
+:root {
+ color-scheme: dark;
+ --bg: #07080c;
+ --panel: rgba(255, 255, 255, 0.04);
+ --line: rgba(255, 255, 255, 0.1);
+ --ink: #ecedf2;
+ --dim: #9aa0af;
+ --faint: #6b7080;
+ --accent: #8b7cf8;
+ --accent-ink: #dcd6ff;
+ --radius: 16px;
+ --font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
+}
+* { box-sizing: border-box; }
+html { scroll-behavior: smooth; }
+body {
+ margin: 0;
+ font-family: var(--font);
+ background: radial-gradient(120% 90% at 50% 0%, #141827 0%, #0a0b11 45%, #06070a 100%);
+ color: var(--ink);
+ line-height: 1.6;
+ -webkit-font-smoothing: antialiased;
+}
+a { color: var(--accent-ink); }
+.wrap { max-width: 1040px; margin: 0 auto; padding: 0 20px; }
+header.site {
+ position: sticky; top: 0; z-index: 50;
+ backdrop-filter: blur(12px);
+ background: rgba(7, 8, 12, 0.72);
+ border-bottom: 1px solid var(--line);
+}
+header.site .wrap { display: flex; align-items: center; gap: 16px; height: 60px; }
+.brand { display: flex; align-items: center; gap: 9px; font-weight: 750; letter-spacing: -0.01em; text-decoration: none; color: var(--ink); }
+.brand .dot { width: 10px; height: 10px; border-radius: 3px; background: linear-gradient(135deg, var(--accent), #4fd1c5); box-shadow: 0 0 18px rgba(139, 124, 248, 0.7); }
+nav.site { margin-left: auto; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
+nav.site a {
+ color: var(--dim); text-decoration: none; font-size: 14px; font-weight: 600;
+ padding: 7px 11px; border-radius: 9px; transition: color .15s, background .15s;
+}
+nav.site a:hover, nav.site a[aria-current="page"] { color: var(--ink); background: rgba(255, 255, 255, 0.07); }
+h1, h2, h3 { line-height: 1.2; letter-spacing: -0.02em; margin: 0 0 12px; }
+h1 { font-size: clamp(34px, 6vw, 56px); font-weight: 800; }
+h2 { font-size: clamp(23px, 3.4vw, 31px); font-weight: 750; margin-top: 8px; }
+h3 { font-size: 17px; font-weight: 700; }
+p { margin: 0 0 14px; color: var(--dim); }
+p.lead { font-size: clamp(16px, 2.1vw, 19px); color: #c3c8d4; max-width: 62ch; }
+section { padding: 56px 0; border-top: 1px solid var(--line); }
+section:first-of-type { border-top: 0; }
+.eyebrow { font-size: 12px; font-weight: 750; letter-spacing: 0.14em; text-transform: uppercase; color: var(--accent); margin-bottom: 12px; }
+.row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
+.btn {
+ display: inline-flex; align-items: center; gap: 8px; text-decoration: none;
+ font-size: 15px; font-weight: 700; padding: 12px 20px; border-radius: 12px;
+ background: rgba(255, 255, 255, 0.06); border: 1px solid var(--line); color: var(--ink);
+ transition: background .15s, border-color .15s, transform .06s;
+ cursor: pointer;
+}
+.btn:hover { background: rgba(255, 255, 255, 0.11); border-color: rgba(255, 255, 255, 0.24); }
+.btn:active { transform: translateY(1px); }
+.btn.primary { background: var(--accent); border-color: var(--accent); color: #0d0b1e; }
+.btn.primary:hover { filter: brightness(1.08); }
+.grid { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(232px, 1fr)); }
+.card {
+ background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
+ padding: 18px 18px 16px;
+}
+.card h3 { margin-bottom: 6px; }
+.card p { font-size: 14px; margin: 0; }
+.card .ico { font-size: 22px; line-height: 1; margin-bottom: 10px; display: block; }
+pre {
+ margin: 0 0 14px; padding: 16px 18px; overflow-x: auto;
+ background: #0b0d13; border: 1px solid var(--line); border-radius: 13px;
+ font-family: var(--mono); font-size: 13.5px; line-height: 1.65; color: #d7dbe6;
+}
+code { font-family: var(--mono); font-size: 0.92em; }
+p code, li code, td code { background: rgba(255, 255, 255, 0.07); padding: 1.5px 6px; border-radius: 6px; color: var(--accent-ink); }
+table { width: 100%; border-collapse: collapse; font-size: 14px; margin-bottom: 16px; display: block; overflow-x: auto; }
+th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line); vertical-align: top; }
+th { color: var(--ink); font-weight: 700; white-space: nowrap; }
+td { color: var(--dim); }
+ul { color: var(--dim); padding-left: 22px; }
+li { margin-bottom: 7px; }
+.stage {
+ position: relative; height: min(72vh, 620px); min-height: 420px;
+ border: 1px solid var(--line); border-radius: 18px; overflow: hidden;
+ background: #06070a; box-shadow: 0 30px 80px -40px rgba(139, 124, 248, 0.5);
+}
+.pill {
+ display: inline-flex; align-items: center; gap: 7px; font-size: 12.5px; font-weight: 650;
+ color: var(--accent-ink); background: rgba(139, 124, 248, 0.14);
+ border: 1px solid rgba(139, 124, 248, 0.38); border-radius: 999px; padding: 6px 13px;
+ margin-bottom: 18px;
+}
+footer.site { border-top: 1px solid var(--line); padding: 34px 0 60px; color: var(--faint); font-size: 13.5px; }
+footer.site a { color: var(--dim); }
+.tabs { display: flex; gap: 6px; margin-bottom: 12px; flex-wrap: wrap; }
+.tab {
+ appearance: none; cursor: pointer; font: inherit; font-size: 13px; font-weight: 650;
+ color: var(--dim); background: rgba(255, 255, 255, 0.05); border: 1px solid transparent;
+ border-radius: 999px; padding: 7px 14px;
+}
+.tab[aria-selected="true"] { color: var(--accent-ink); background: rgba(139, 124, 248, 0.16); border-color: rgba(139, 124, 248, 0.4); }
+[hidden] { display: none !important; }
+@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
+</style>
+<script type="module" src="./ar-studio.min.js"></script>
+</head>
+<body>
+
+
+<div style="position:fixed;inset:0"><ar-studio id="studio" style="position:absolute;inset:0;min-height:0"
+ title="AR Studio" back-href="./index.html"></ar-studio></div>
+
+
+</body>
+</html>
diff --git a/packages/ar-studio/docs/version.json b/packages/ar-studio/docs/version.json
new file mode 100644
index 000000000..ed0ac3de1
--- /dev/null
+++ b/packages/ar-studio/docs/version.json
@@ -0,0 +1,6 @@
+{
+ "name": "3d-ar-studio",
+ "version": "0.3.2",
+ "homepage": "https://nirholas.github.io/3D-AR-Studio/",
+ "bundle": "./ar-studio.min.js"
+}
diff --git a/packages/ar-studio/eslint.config.js b/packages/ar-studio/eslint.config.js
new file mode 100644
index 000000000..0a1c92b28
--- /dev/null
+++ b/packages/ar-studio/eslint.config.js
@@ -0,0 +1,70 @@
+// Lint rules for this package.
+//
+// Deliberately small: the repository's own conventions (no placeholder code, no
+// dead paths, every state designed) are not things a linter can check, and a
+// wall of style rules would only bury the two or three that catch real bugs.
+
+import js from '@eslint/js';
+
+export default [
+ js.configs.recommended,
+ {
+ files: ['**/*.js', '**/*.mjs'],
+ languageOptions: {
+ ecmaVersion: 2023,
+ sourceType: 'module',
+ globals: {
+ window: 'readonly',
+ document: 'readonly',
+ navigator: 'readonly',
+ location: 'readonly',
+ history: 'readonly',
+ screen: 'readonly',
+ fetch: 'readonly',
+ console: 'readonly',
+ localStorage: 'readonly',
+ performance: 'readonly',
+ requestAnimationFrame: 'readonly',
+ cancelAnimationFrame: 'readonly',
+ setTimeout: 'readonly',
+ clearTimeout: 'readonly',
+ setInterval: 'readonly',
+ clearInterval: 'readonly',
+ crypto: 'readonly',
+ URL: 'readonly',
+ URLSearchParams: 'readonly',
+ Blob: 'readonly',
+ File: 'readonly',
+ FileReader: 'readonly',
+ Image: 'readonly',
+ CustomEvent: 'readonly',
+ HTMLElement: 'readonly',
+ customElements: 'readonly',
+ ResizeObserver: 'readonly',
+ TextEncoder: 'readonly',
+ TextDecoder: 'readonly',
+ btoa: 'readonly',
+ atob: 'readonly',
+ DeviceOrientationEvent: 'readonly',
+ AbortSignal: 'readonly',
+ AbortController: 'readonly',
+ process: 'readonly',
+ globalThis: 'readonly',
+ },
+ },
+ rules: {
+ 'no-unused-vars': ['error', { argsIgnorePattern: '^_', caughtErrors: 'none' }],
+ 'no-console': 'off',
+ eqeqeq: ['error', 'smart'],
+ 'prefer-const': 'error',
+ 'no-var': 'error',
+ },
+ },
+ {
+ // The MCP server and the CLI run in Node, where the DOM globals above are
+ // meaningless but Node's own are not.
+ files: ['mcp/**/*.js', 'bin/**/*.mjs', 'scripts/**/*.mjs', 'site/**/*.mjs', 'test/**/*.mjs'],
+ languageOptions: { globals: { process: 'readonly', console: 'readonly', fetch: 'readonly', globalThis: 'readonly' } },
+ },
+ { ignores: ['dist/**', 'docs/**', 'node_modules/**', 'templates/**'] },
+];
diff --git a/packages/ar-studio/llms-full.txt b/packages/ar-studio/llms-full.txt
new file mode 100644
index 000000000..dbbb40864
--- /dev/null
+++ b/packages/ar-studio/llms-full.txt
@@ -0,0 +1,485 @@
+# 3D-AR-Studio
+
+> Drop a full augmented-reality studio into any web page. Place any number of 3D models in your real room through the camera, generate new ones from a text prompt, arrange them, then share the scene as a link, a QR code, or a live room. WebXR + Quick Look + Scene Viewer, a free CC0 model library, and an MCP server for agents.
+
+# 3D AR Studio
+
+**Drop a full augmented-reality studio into any web page.**
+
+Place as many 3D models as you like in your real room through the camera, describe a new one
+and watch it appear, arrange everything by hand, then share the whole scene as a link, a QR
+code, or a live room someone else can build in with you.
+
+[**Live demo**](https://nirholas.github.io/3D-AR-Studio/) · [npm](https://www.npmjs.com/package/3d-ar-studio) · [MCP server](#mcp-server)
+
+```html
+<script type="module" src="https://unpkg.com/3d-ar-studio/dist/ar-studio.min.js"></script>
+<ar-studio></ar-studio>
+```
+
+That is a working AR studio. No build step, no API key, no account. It comes wired to a free
+library of a few hundred public-domain models and a free, keyless text-to-3D lane; point it at
+your own catalogue with one option when you are ready.
+
+---
+
+## Why this exists
+
+Every web-AR drop-in places exactly one model and then hands off to a native viewer, which
+ends the session. This one keeps the whole scene in your page:
+
+- **Many models, one room.** Place, drag, pinch-resize, twist-rotate and duplicate as many
+ models as you want in a single live camera view.
+- **Generate without leaving the camera.** Type "a brass desk lamp" into the dock. The
+ generation runs behind the live view and the finished model drops into the room.
+- **Real WebXR where it exists.** An always-armed hit-test reticle, one `XRAnchor` per placed
+ model, real-world light estimation, and depth occlusion so models hide behind your furniture.
+- **Real ARKit and ARCore everywhere else.** iPhones have no WebXR, so tapping **Place in your
+ space** opens Apple's AR Quick Look for real: true plane detection, true scale, true
+ occlusion, the system's own "View in AR" sheet. The model is converted to USDZ on the device
+ (a real conversion via three.js's `USDZExporter`, no server involved) and, because it is
+ exported from the copy already standing in your scene, it arrives at the size you pinched it
+ to and in the pose it was in, stood on the floor rather than hanging at the height it happened
+ to be modelled at. Android without WebXR gets Scene Viewer. Desktop gets a grid
+ preview and a QR hand-off to a phone.
+- **Scenes are links.** Models, positions, rotations and scales round-trip through the URL.
+ Compose on a laptop, scan the QR, it reopens exactly on your phone.
+- **Build together, live.** Open a room, share a six-character code, and every add and move
+ syncs to everyone in it.
+- **Characters actually move.** Any humanoid GLB with no baked animation gets an idle clip
+ retargeted onto its own skeleton. No rig allow-list, no T-poses.
+- **Agents can drive it.** A bundled MCP server lets Claude, ChatGPT or your own agent
+ generate a model, compose an arrangement, and hand a person one link that opens it in
+ their room.
+
+The rendering ladder, anchor lifecycle, retargeting pipeline, scene format and shared-room
+protocol are extracted from the AR surfaces running in production on
+[three.ws](https://three.ws), and generalized so they work on your site with your models.
+
+---
+
+## Install
+
+```bash
+npm i 3d-ar-studio three
+```
+
+`three` is a peer dependency, so you keep one copy of it and pick the version. The CDN bundle
+(`dist/ar-studio.min.js`) has three.js inside it and needs nothing else.
+
+```js
+import { createArStudio } from '3d-ar-studio'
+
+const studio = createArStudio('#stage', {
+ branding: { title: 'Acme AR', accent: '#00b894' },
+})
+
+studio.on('add', ({ placement }) => console.log('placed', placement.title))
+```
+
+The studio fills its host element absolutely, so give the host a height (any positioned box
+with a real height works; a `<div>` with no height gets a sensible `70vh` default rather than
+rendering invisibly).
+
+### Scaffold a deployable page
+
+```bash
+npx 3d-ar-studio create my-ar-site # a folder you can publish as-is
+cd my-ar-site
+npx 3d-ar-studio dev # look at it locally
+npx 3d-ar-studio deploy # push it and turn on GitHub Pages
+```
+
+`deploy` prints every `git` and `gh` command before it runs it. It needs
+[git](https://git-scm.com) and the [GitHub CLI](https://cli.github.com); without them it tells
+you the three manual steps instead of failing silently.
+
+Templates: `static` (one HTML file, no build), `vite`, `react`.
+
+Both `3d-ar-studio` and `ar-studio` run the CLI. The MCP server is a separate
+binary in its own package, so `npx 3d-ar-studio-mcp` resolves cleanly: see
+[MCP server](#mcp-server).
+
+---
+
+## Your own models
+
+The tray is filled from three.ws by default: a few hundred public-domain (CC0) props, free for
+commercial use, served with open CORS. Swap in your own with the `assets` option.
+
+**A JSON file anywhere.** Five common shapes are read without reshaping:
+
+```js
+createArStudio(el, { assets: 'https://cdn.acme.com/models.json' })
+```
+
+```jsonc
+// Any of these work:
+[ { "url": "https://cdn.acme.com/chair.glb", "name": "Aero chair" } ]
+{ "items": [ … ] }
+{ "objects": [ … ] } // three.ws object library
+{ "creations": [ … ] } // three.ws forge gallery
+{ "models": [ … ] }
+```
+
+Per entry, the model URL is read from the first present of `src`, `url`, `glb`, `glb_url`,
+`glbUrl`, `file` or `model`; the label from `title`, `label`, `name` or `prompt`; and the
+thumbnail from `poster`, `thumb`, `thumbnail`, `image` or `preview_image_url`. Anything that
+is not an https (or site-relative) URL is dropped rather than handed to the loader.
+
+**A list you hold in code:**
+
+```js
+import { staticSource } from '3d-ar-studio/sources'
+
+createArStudio(el, {
+ assets: staticSource({
+ label: 'Our furniture',
+ items: [{ src: 'https://cdn.acme.com/chair.glb', title: 'Aero chair', poster: '…' }],
+ }),
+})
+```
+
+**Several tabs at once, in the order you want them:**
+
+```js
+createArStudio(el, { assets: ['recent', myCatalogue, 'objects', 'link'] })
+```
+
+Built-in keys: `'three.ws'` (the default set), `'recent'`, `'objects'`, `'community'`, `'link'`.
+
+**Anything else.** A source is an object with a `list()`:
+
+```js
+createArStudio(el, {
+ assets: {
+ id: 'search',
+ label: 'Search',
+ searchable: true,
+ async list() {
+ const rows = await fetch('/api/models').then((r) => r.json())
+ return rows.map((m) => ({ src: m.glb, title: m.name, poster: m.thumb }))
+ },
+ },
+})
+```
+
+Throwing from `list()` is fine: the tray renders a designed error state with a Retry button.
+
+**Your users can retarget it too**, without touching your code: `?assets=https://…/manifest.json`
+on the page URL. Only https URLs are accepted, and every model source is re-validated before it
+reaches the loader, so a hostile link can add a catalogue but can never smuggle a
+`javascript:` or `data:` model into the scene. Set `allowUrlOverride: false` to switch that off.
+
+### CORS
+
+Models are loaded by the browser, so the host serving your `.glb` files has to allow
+cross-origin requests (`access-control-allow-origin`). If a model fails to load, that is
+almost always why, and the studio says so in the status line rather than failing silently.
+
+---
+
+## Options
+
+| Option | Default | What it does |
+| --- | --- | --- |
+| `assets` | `'three.ws'` | Where models come from: a preset key, a manifest URL, a source object, or an array of them. |
+| `generate` | enabled | `{ enabled, endpoint, kind, tier, timeoutMs, pollMs }`. `endpoint` is any MCP server exposing a compatible generate tool. |
+| `rooms` | enabled | `{ enabled, server }`. Point `server` at your own Colyseus deployment to host shared rooms yourself. |
+| `animations` | three.ws idle clip | `{ enabled, manifestUrl, clip }`. The clip retargeted onto humanoid models that ship no animation. |
+| `lighting` | `'studio'` HDRI | `{ preset, urls }`. `preset: null` uses procedural lighting only and downloads no HDRI. |
+| `branding` |: | `{ title, accent, backHref, backLabel }`. |
+| `shareBaseUrl` | this page | Where share links and QR codes point. |
+| `origin` | `https://three.ws` | Origin for the hosted "View in your space" launcher and viewer links. |
+| `persistKey` | `'ar-studio:scene:v1'` | localStorage key for the saved scene. Change it to run two studios on one origin. |
+| `persist` | `true` | Restore the last scene on load. |
+| `maxPlacements` | `20` | Cap on simultaneous models. Keeps low-end phones interactive. |
+| `fullscreen` | auto | Render as a fixed full-screen layer. Defaults to true only when mounted on `document.body`. |
+| `allowUrlOverride` | `true` | Honour `?assets=`, `?src=`, `?room=` and `?forge=` on the hosting page's URL. |
+| `onEvent` | `null` | Called with `(event, detail)` for every notable action. Wire it to your analytics. |
+
+### URL parameters
+
+| Parameter | Effect |
+| --- | --- |
+| `?assets=<https url>` | Swap the catalogue. |
+| `?src=<glb>&title=<name>` | Load models into the scene. Repeatable. |
+| `#s=<payload>` | Reopen a full arrangement, transforms included. Written by `shareUrl()`. |
+| `?room=<code>` | Join a shared room. |
+| `?forge=<prompt>` | Start a generation on load. |
+
+### Methods
+
+```js
+await studio.addModel({ src, title }) // place a model
+studio.clear() // remove everything; returns what was there
+studio.getScene() // [{ src, title, x, z, yaw, scale }]
+await studio.setScene(items) // replace the arrangement
+studio.shareUrl() // a link that reopens it exactly
+await studio.generate('a brass desk lamp') // text to 3D, into the room
+studio.viewInYourSpace(src, title) // open the hosted launch page for one model
+await studio.startCamera() // needs a user gesture on iOS
+await studio.enterAR() // best AR path for this device
+studio.openArSheet() // the "Place in your space" hand-off sheet
+studio.closeArSheet()
+await studio.placeInYourSpace() // straight to the native viewer, no sheet
+await studio.toggleImmersive() // enter or leave WebXR specifically
+await studio.openRoom() // returns the room code
+studio.destroy() // releases camera, socket and GPU context
+```
+
+### Events
+
+`studio.on(name, fn)` returns an unsubscribe function. The same events also fire as
+`ar-studio:<name>` DOM events on the mounted element.
+
+| Event | Detail |
+| --- | --- |
+| `add` | `{ placement, remote }` |
+| `remove` | `{ src, title }` |
+| `select` | `{ placement }` (null when deselected) |
+| `clear` | `{ items }` |
+| `generate` | `{ model }` |
+| `generate-error` | `{ error, prompt }` |
+| `camera` | `{ active }` |
+| `xr` | `{ active }` |
+| `native-ar` | `{ src, title, viewer }` where viewer is `quicklook`, `sceneviewer` or `none` |
+| `native-ar-error` | `{ error, src }` |
+| `ar-sheet` | `{ open }` when the hand-off sheet opens or closes |
+| `room` | `{ status, code }` |
+| `share` | `{ url }` |
+
+---
+
+## Web component
+
+```html
+<ar-studio
+ assets="https://cdn.acme.com/models.json"
+ title="Acme AR"
+ accent="#00b894"
+ generate="true"
+ rooms="true"
+></ar-studio>
+```
+
+`element.studio` is the live instance. Importing `3d-ar-studio/auto` (what the CDN bundle
+does) registers the element for you.
+
+---
+
+## Keyboard and accessibility
+
+Every control is a real button with an accessible name, the source tabs implement the full
+ARIA tablist contract, and each dialog takes and returns focus.
+
+| Key | Action |
+| --- | --- |
+| Arrows | Nudge the selected model, camera-relative. Hold Shift for fine steps. |
+| `R` | Rotate 45°. |
+| `D` | Duplicate. |
+| Delete / Backspace | Remove, with an undo in the status line. |
+| Escape | Close the open panel, or deselect. |
+
+`prefers-reduced-motion` removes the spawn-in animation and every transition.
+
+---
+
+## MCP server
+
+```bash
+npx 3d-ar-studio-mcp
+```
+
+```json
+{
+ "mcpServers": {
+ "3d-ar-studio": {
+ "command": "npx",
+ "args": ["-y", "3d-ar-studio-mcp"]
+ }
+ }
+}
+```
+
+No API key. Every tool is free and keyless.
+
+| Tool | What it does |
+| --- | --- |
+| `generate_3d_model` | Turn a text prompt into a textured GLB. Returns the model plus links that open it in AR. |
+| `check_generation` | Collect a generation that was still rendering when the first call returned. |
+| `search_models` | Search the free CC0 library (or any catalogue you configure) by name, category and tag. |
+| `compose_ar_scene` | Arrange several models into one scene and return a single link that reopens it exactly. |
+| `export_ar` | Turn any GLB URL into a device-aware "View in your space" link. |
+| `create_ar_page` | Emit a complete, self-contained HTML page embedding the studio, ready to commit. |
+
+| Environment variable | Default | What it changes |
+| --- | --- | --- |
+| `AR_STUDIO_PAGE_URL` | the hosted demo | The page `compose_ar_scene` links to. Set it to your own deployment. |
+| `AR_STUDIO_ASSETS` | the free CC0 library | Catalogue `search_models` searches. |
+| `AR_STUDIO_MCP_ENDPOINT` | three.ws 3D Studio | The MCP endpoint used for generation. |
+| `AR_STUDIO_ORIGIN` | `https://three.ws` | Origin for hosted AR launch and viewer links. |
+
+A session looks like this:
+
+```
+> Put a mid-century lamp and a potted fern in my living room.
+
+ generate_3d_model { prompt: "a brass mid-century desk lamp" } → lamp.glb
+ search_models { query: "potted plant" } → fern.glb
+ compose_ar_scene { models: [{ src: lamp.glb, x: 0, z: -1.4 },
+ { src: fern.glb, x: 0.9, z: -1.2 }] }
+
+ → one link; open it on a phone and both objects stand in the room.
+```
+
+---
+
+## Device support
+
+| Device | Path | What you get |
+| --- | --- | --- |
+| Android Chrome | WebXR `immersive-ar` | The whole scene in the room: hit-test placement, per-model anchors, light estimation, depth occlusion. |
+| iOS Safari | AR Quick Look | One model at a time in Apple's own viewer, with real ARKit tracking, scale and occlusion. The model is converted to USDZ on the device. Camera passthrough with gyro world-lock composes the multi-model scene in-page alongside it. |
+| Android without WebXR | Scene Viewer | One model at a time through ARCore, with a browser fallback if ARCore is missing. |
+| Desktop | Preview | Grid floor, drag-look, QR hand-off to a phone. |
+| Headsets | WebXR | Same as Android Chrome. |
+
+The **AR** button in the top bar always takes the best path the device has, labels itself so it
+never promises the wrong one, and acts on the selected model (or the last one placed).
+
+Camera and WebXR both need a secure context: `https://` or `localhost`.
+
+### Placing one model in someone's real room
+
+On a device with WebXR the AR button goes straight into an immersive session. Everywhere else
+it opens the **hand-off sheet**: which model is going, a picker when the scene holds more than
+one, and a single primary button that opens the device's own AR viewer.
+
+The sheet exists for one specific reason, and it is worth knowing about if you are building
+your own UI on top of this package:
+
+> **iOS opens AR Quick Look only while the page still holds the user gesture that asked for
+> it.** Converting a GLB to USDZ takes a second or two. Start the conversion inside the tap
+> handler and by the time the `<a rel="ar">` is clicked the gesture has expired, Safari
+> silently declines, and the button looks broken. That is the single most common reason a
+> "View in AR" button does nothing on an iPhone.
+
+There is a second trap right behind it, and it is worse because the failure looks like success:
+
+> **Safari decides whether a URL is an AR asset from its file extension.** A `blob:` URL has no
+> path, so it has no extension. Hand one to `<a rel="ar">` with no filename and Safari still
+> opens Quick Look, but as a generic 3D preview: the viewer comes up in **Object** mode with AR
+> unavailable. Setting `download="something.usdz"` on the anchor gives Safari the name it
+> sniffs, and Quick Look enters AR. `openQuickLook()` does this for you.
+
+So the package splits preparing from opening, and never does them in one tap:
+
+```js
+import { prepareNativeAr, isQuickLookReady } from '3d-ar-studio';
+
+// Ahead of the tap: convert, cache, and keep the result.
+const handoff = await prepareNativeAr({
+ src: 'https://example.com/chair.glb',
+ title: 'Chair',
+ key: '[email protected]', // cache identity; include the scale if you bake one in
+});
+
+// Inside the tap, synchronously. No await between the click and open().
+button.addEventListener('click', () => handoff?.open());
+```
+
+`prepareNativeAr` resolves to `null` on a device with no native AR viewer, `{ viewer:
+'quicklook' }` on iOS with a `blob:` USDZ ready to open, and `{ viewer: 'sceneviewer' }` on
+Android, where nothing needs converting at all. Conversions are cached (four at a time,
+least-recently-used, object URLs revoked on eviction); `isQuickLookReady(key)`,
+`releaseQuickLook(key)` and `clearQuickLookCache()` let you drive that cache yourself.
+
+The studio warms the cache in the background for whichever model the button would send, which
+is why the second tap of the day is instant. `placeInYourSpace()` still exists and still does
+both halves in one call: reach for it when the USDZ is already cached, or when you are calling
+it from your own already-prepared button.
+
+Exporting from the live scene rather than refetching the GLB is deliberate too: no second
+download, no second CORS round trip, and the person gets the pose and the size they are
+looking at. `objectToUsdzBlob(object3D)` is exported if you want that for your own three.js
+scene.
+
+### Why a model hangs in the air instead of resting on your floor
+
+The third trap, and the one that survives both of the others:
+
+> **AR Quick Look anchors the scene's ORIGIN to the plane it detects, and never looks at the
+> geometry.** A GLB authored around its bounding-box centre arrives half-buried; one authored
+> around a distant scene origin arrives floating across the room at whatever height it was
+> modelled at. Both read as broken tracking, and no anchoring property fixes either: the
+> content has to be moved.
+
+Every export from this package is therefore stood on `y = 0` with its footprint centred over
+the origin before it is written. `groundOnFloor()` is exported if you want to do that to your
+own scene.
+
+Two smaller ones ride along with it:
+
+> **`USDZExporter` walks `scene.children` and writes each node's LOCAL matrix**, so the
+> transform on the object you hand it is never written at all. Set a scale on the root and the
+> file comes out at the original size with no warning. `usdzExportRoot()` wraps content in an
+> identity root plus a `Model` stage node, and every placement this package applies rides on
+> the stage, which does get written.
+
+> **USDZ is metres** (`metersPerUnit = 1`). A 75 cm prop authored in centimetres arrives 75 m
+> tall, too large for any plane ARKit found indoors, and swims around the viewer. Pass
+> `{ fit: true }` to `sceneToUsdzBlob()` (`glbUrlToUsdzBlob()` already does) to normalize a
+> model straight off the network. Anything already within 2x of a believable real-world size
+> is left exactly as authored.
+
+And the one that looks most like broken tracking of all:
+
+> **Quick Look does not place a model until ARKit has found a plane big enough to hold it.**
+> Until then it hangs aligned to the camera and travels with the phone. Past a certain size
+> there is no such plane in an ordinary room, so it never lands at all. Every export is capped
+> at `MAX_AR_FOOTPRINT_M` (2.5 m) and `MAX_AR_HEIGHT_M` (2.5 m) by `clampToPlaceableSize()`.
+> A ceiling, not a normalizer: furniture, people and props go through untouched.
+
+### The camera is one client at a time
+
+The studio releases its `getUserMedia` passthrough on the way into the device's AR viewer and
+restarts it when you come back. Leave the page's stream running and ARKit starts against a
+camera another process is already holding: the model appears, and then world tracking and
+plane detection never converge, so it drifts with the phone instead of settling. If you drive
+the hand-off yourself from your own camera UI, stop your tracks before you call `open()`.
+
+Passthrough itself is a gyroscope over a video feed: it turns with you, and that is all. It has
+no plane detection and no positional tracking, so it will never hold a model to a spot on a
+real floor. On iOS that is what Quick Look is for, and the studio's status line says so.
+
+---
+
+## Development
+
+```bash
+npm install
+npm test # 75 unit tests, no browser needed
+npm run build # dist/ bundles
+npm run build:site # docs/ (the GitHub Pages site)
+npm run test:browser # 35 end-to-end checks in a real browser (needs Playwright)
+npm run inspect # MCP Inspector against the local server
+```
+
+The published site is committed under `docs/` and served by GitHub Pages from the `main`
+branch. There is no CI workflow: `npm run build && npm run build:site`, commit, push.
+
+---
+
+## Licence and credits
+
+Apache-2.0.
+
+The bundle includes [three.js](https://threejs.org) (MIT) and
+[colyseus.js](https://colyseus.io) (MIT). The default model library is CC0 content from
+[Poly Haven](https://polyhaven.com), and the default generation and animation lanes are hosted
+by [three.ws](https://three.ws). None of them is required: every one is a URL you can change.
+
+## Star History
+
+[![Star History Chart](https://api.star-history.com/svg?repos=nirholas/3D-AR-Studio&type=Date)](https://www.star-history.com/#nirholas/3D-AR-Studio&Date)
diff --git a/packages/ar-studio/llms.txt b/packages/ar-studio/llms.txt
new file mode 100644
index 000000000..e6862eac2
--- /dev/null
+++ b/packages/ar-studio/llms.txt
@@ -0,0 +1,28 @@
+# 3D-AR-Studio
+
+> Drop a full augmented-reality studio into any web page. Place any number of 3D models in your real room through the camera, generate new ones from a text prompt, arrange them, then share the scene as a link, a QR code, or a live room. WebXR + Quick Look + Scene Viewer, a free CC0 model library, and an MCP server for agents.
+
+3D-AR-Studio is an open-source repository by nirholas, part of the three.ws ecosystem.
+
+## Docs
+
+- [README](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/README.md): install, usage and reference
+- [Why this exists](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/README.md#why-this-exists)
+- [Install](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/README.md#install)
+- [Your own models](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/README.md#your-own-models)
+- [Options](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/README.md#options)
+- [Web component](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/README.md#web-component)
+- [Keyboard and accessibility](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/README.md#keyboard-and-accessibility)
+- [MCP server](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/README.md#mcp-server)
+- [Device support](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/README.md#device-support)
+- [AGENTS.md](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/AGENTS.md): guidance for coding agents
+- [Full text for LLMs](https://github.com/nirholas/3D-AR-Studio/blob/HEAD/llms-full.txt): the README inlined
+
+## Project
+
+- [Source](https://github.com/nirholas/3D-AR-Studio)
+- [Issues](https://github.com/nirholas/3D-AR-Studio/issues)
+- [Discussions](https://github.com/nirholas/3D-AR-Studio/discussions)
+- [Homepage](https://nirholas.github.io/3D-AR-Studio/)
+- [three.ws](https://three.ws): the platform this is part of
+- [All repositories by nirholas](https://github.com/nirholas/nirholas#readme)
diff --git a/packages/ar-studio/mcp-package/README.md b/packages/ar-studio/mcp-package/README.md
new file mode 100644
index 000000000..02c980835
--- /dev/null
+++ b/packages/ar-studio/mcp-package/README.md
@@ -0,0 +1,34 @@
+# 3d-ar-studio-mcp
+
+The MCP server for [3D AR Studio](https://github.com/nirholas/3D-AR-Studio). It lets an agent
+generate 3D models, search a free public-domain library, arrange several into one scene, and
+hand a person a single link that opens the whole arrangement in augmented reality on their
+phone.
+
+```json
+{
+ "mcpServers": {
+ "3d-ar-studio": {
+ "command": "npx",
+ "args": ["-y", "3d-ar-studio-mcp"]
+ }
+ }
+}
+```
+
+No API key. Every tool is free and keyless.
+
+| Tool | What it does |
+| --- | --- |
+| `generate_3d_model` | Turn a text prompt into a textured GLB, with links that open it in AR. |
+| `check_generation` | Collect a generation that was still rendering. |
+| `search_models` | Search the CC0 library, or any catalogue you configure. |
+| `compose_ar_scene` | Arrange several models and return one link that reopens the arrangement. |
+| `export_ar` | Turn any GLB URL into a device-aware "View in your space" link. |
+| `create_ar_page` | Emit a complete, deployable HTML page embedding the studio. |
+
+Configuration, tool schemas and the studio itself are documented in the
+[main README](https://github.com/nirholas/3D-AR-Studio#mcp-server).
+
+This package is a thin wrapper: it exists so `npx 3d-ar-studio-mcp` resolves, and delegates
+everything to [`3d-ar-studio`](https://www.npmjs.com/package/3d-ar-studio).
diff --git a/packages/ar-studio/mcp-package/bin.mjs b/packages/ar-studio/mcp-package/bin.mjs
new file mode 100755
index 000000000..e122b5560
--- /dev/null
+++ b/packages/ar-studio/mcp-package/bin.mjs
@@ -0,0 +1,16 @@
+#!/usr/bin/env node
+// `npx 3d-ar-studio-mcp`
+//
+// This package exists purely so that command works: the studio itself lives in
+// `3d-ar-studio`, whose own binary is the project scaffolder, and npx resolves a
+// binary by package name. Everything here is one line of delegation, so the
+// server can never drift from the library it belongs to.
+
+import { main } from '3d-ar-studio/mcp';
+
+main().catch((err) => {
+ // stdout is the protocol channel: diagnostics must go to stderr or they
+ // corrupt the JSON-RPC stream.
+ console.error('[3d-ar-studio-mcp]', err?.stack || err?.message || err);
+ process.exit(1);
+});
diff --git a/packages/ar-studio/mcp-package/package.json b/packages/ar-studio/mcp-package/package.json
new file mode 100644
index 000000000..8882daeb1
--- /dev/null
+++ b/packages/ar-studio/mcp-package/package.json
@@ -0,0 +1,48 @@
+{
+ "name": "3d-ar-studio-mcp",
+ "version": "0.3.2",
+ "mcpName": "io.github.nirholas/3d-ar-studio",
+ "description": "MCP server for 3D AR Studio: generate 3D models, search a free CC0 library, arrange them into one scene, and hand back a link that opens the whole arrangement in augmented reality on a phone.",
+ "type": "module",
+ "license": "Apache-2.0",
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "homepage": "https://nirholas.github.io/3D-AR-Studio/",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/3D-AR-Studio.git",
+ "directory": "mcp-package"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/3D-AR-Studio/issues"
+ },
+ "keywords": [
+ "mcp",
+ "model-context-protocol",
+ "ar",
+ "augmented-reality",
+ "3d",
+ "glb",
+ "text-to-3d",
+ "webxr",
+ "quick-look",
+ "scene-viewer",
+ "three.ws"
+ ],
+ "bin": {
+ "3d-ar-studio-mcp": "./bin.mjs"
+ },
+ "main": "./bin.mjs",
+ "files": [
+ "bin.mjs",
+ "README.md"
+ ],
+ "dependencies": {
+ "3d-ar-studio": "^0.3.2"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/ar-studio/mcp/index.js b/packages/ar-studio/mcp/index.js
new file mode 100644
index 000000000..5de5d289f
--- /dev/null
+++ b/packages/ar-studio/mcp/index.js
@@ -0,0 +1,73 @@
+// The 3D AR Studio MCP server (stdio).
+//
+// npx 3d-ar-studio-mcp
+//
+// Gives an agent the studio's own capabilities: generate a 3D model, search the
+// ready-made library, arrange several models into one scene, turn any model into
+// a device-aware "View in your space" link, and emit a deployable AR page.
+//
+// Free and keyless. Nothing here reads a credential.
+
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+import { createRequire } from 'node:module';
+
+import { createTools, readEnv } from './tools.js';
+
+const { version } = createRequire(import.meta.url)('../package.json');
+
+/**
+ * Build the server with every tool registered. Exported so a host can mount it
+ * on a transport of its own choosing.
+ *
+ * @param {object} [opts]
+ * @param {NodeJS.ProcessEnv} [opts.env]
+ * @returns {McpServer}
+ */
+export function createServer({ env } = {}) {
+ const server = new McpServer(
+ { name: '3d-ar-studio', version },
+ {
+ capabilities: { tools: {} },
+ instructions:
+ 'Put 3D things in a person\'s real room. Search the ready-made library first (search_models) and '
+ + 'generate only what you cannot find (generate_3d_model). For more than one object, arrange them '
+ + 'with compose_ar_scene and give the person the single link it returns: that link reopens the whole '
+ + 'arrangement in their room. Always hand back a link rather than only a .glb file: a bare model file '
+ + 'is not something a person can look at. AR links are meant to be opened on a phone.',
+ },
+ );
+
+ for (const tool of createTools({ env: env ? readEnv(env) : undefined })) {
+ server.registerTool(
+ tool.name,
+ {
+ title: tool.title,
+ description: tool.description,
+ inputSchema: tool.schema,
+ annotations: tool.annotations,
+ },
+ async (args) => {
+ try {
+ return await tool.run(args ?? {});
+ } catch (err) {
+ const message = err?.message || 'That did not work.';
+ return {
+ content: [{ type: 'text', text: message }],
+ structuredContent: { error: true, message },
+ isError: true,
+ };
+ }
+ },
+ );
+ }
+ return server;
+}
+
+/** Run the server over stdio. This is what the `3d-ar-studio-mcp` binary calls. */
+export async function main() {
+ const server = createServer();
+ await server.connect(new StdioServerTransport());
+}
+
+export { createTools, readEnv, renderPage, sceneUrl } from './tools.js';
diff --git a/packages/ar-studio/mcp/tools.js b/packages/ar-studio/mcp/tools.js
new file mode 100644
index 000000000..7a86fbbff
--- /dev/null
+++ b/packages/ar-studio/mcp/tools.js
@@ -0,0 +1,326 @@
+// The tools the MCP server exposes.
+//
+// Each one is a plain async function over the same modules the browser studio
+// uses, so an agent and a person are driving identical code paths: the same
+// generation pipeline, the same catalogue reader, the same scene encoder, the
+// same AR link builder. Nothing here is a separate "agent version" that can
+// drift from what the page does.
+//
+// Everything is free and keyless. No tool takes a credential, and none is
+// required for the studio itself to work.
+
+import { z } from 'zod';
+
+import { createForgeClient } from '../src/forge/client.js';
+import { validatePrompt } from '../src/forge/safety.js';
+import { promptTitle } from '../src/forge/narration.js';
+import { normalizeCatalogue } from '../src/sources/manifest.js';
+import { cdnUrl } from '../src/sources/three-ws.js';
+import { THREE_WS } from '../src/config.js';
+import {
+ assertArAssetUrl, buildArLaunchUrl, buildSceneViewerUrl, buildViewerUrl, detectArTarget,
+} from '../src/ar-launch.js';
+import { sceneToHashParam, studioShareUrl, normalizeGlbUrl } from '../src/studio/scene-math.js';
+
+/** Everything the tools read from the environment, resolved once. */
+export function readEnv(env = process.env) {
+ return {
+ pageUrl: env.AR_STUDIO_PAGE_URL || 'https://nirholas.github.io/3D-AR-Studio/studio.html',
+ assets: env.AR_STUDIO_ASSETS || THREE_WS.objectsManifest,
+ endpoint: env.AR_STUDIO_MCP_ENDPOINT || THREE_WS.studioMcp,
+ origin: (env.AR_STUDIO_ORIGIN || THREE_WS.origin).replace(/\/$/, ''),
+ };
+}
+
+const MODEL_SHAPE = z.object({
+ src: z.string().describe('https URL of a .glb model.'),
+ title: z.string().max(120).optional().describe('Label shown for this model.'),
+ x: z.number().optional().describe('Metres right of the viewer. Default 0.'),
+ z: z.number().optional().describe('Metres in front of the viewer, negative is further away. Default -1.6.'),
+ yaw: z.number().optional().describe('Rotation in radians about the vertical axis.'),
+ scale: z.number().min(0.25).max(4).optional().describe('Uniform scale, 0.25 to 4.'),
+});
+
+/**
+ * Build the tool table.
+ * @param {object} [opts]
+ * @param {ReturnType<typeof readEnv>} [opts.env]
+ * @param {ReturnType<typeof createForgeClient>} [opts.forge] Injectable for tests.
+ */
+export function createTools({ env = readEnv(), forge } = {}) {
+ const client = forge || createForgeClient({ endpoint: env.endpoint });
+
+ /** Every link that matters for one finished model. */
+ const linksFor = (glbUrl, title, live = false) => ({
+ glbUrl,
+ arLaunchUrl: buildArLaunchUrl(env.origin, glbUrl, title, { live }),
+ viewerUrl: buildViewerUrl(env.origin, glbUrl, title),
+ sceneViewerUrl: buildSceneViewerUrl(glbUrl, { title, fallbackUrl: buildViewerUrl(env.origin, glbUrl, title) }),
+ studioUrl: sceneUrl([{ src: glbUrl, title }], env.pageUrl),
+ });
+
+ return [
+ {
+ name: 'generate_3d_model',
+ title: 'Generate a 3D model from text',
+ description:
+ 'Turn a text prompt into a textured, downloadable 3D model (GLB). Free and keyless. Describe a '
+ + 'SINGLE object, character, or creature: "a brass mid-century desk lamp", not a whole scene. '
+ + 'Returns the model URL plus links that open it in the viewer, in the user\'s room through their '
+ + 'phone camera, and in the AR studio. Use kind:"avatar" for a character: it comes back rigged, so '
+ + 'it idles and animates instead of standing in a T-pose.',
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ schema: {
+ prompt: z.string().min(3).max(600).describe('The single object or character to model.'),
+ kind: z.enum(['model', 'avatar', 'mesh']).optional()
+ .describe('model (a prop, default), avatar (a rigged character), or mesh (art-directed, prompt refined first).'),
+ tier: z.enum(['draft', 'standard', 'high']).optional().describe('Detail level. Higher is slower.'),
+ },
+ async run({ prompt, kind = 'model', tier }) {
+ const check = validatePrompt(prompt);
+ if (!check.ok) return fail(check.reason);
+ const model = await client.generate(check.prompt, { kind, tier });
+ const live = kind === 'avatar' || model.rigged;
+ const links = linksFor(model.src, model.title, live);
+ return ok(
+ `Generated "${model.title}".\n`
+ + `Open it in your room (a phone routes itself to Quick Look or Scene Viewer): ${links.arLaunchUrl}\n`
+ + `Place it in the AR studio with other models: ${links.studioUrl}\n`
+ + `Model file: ${links.glbUrl}`,
+ { ...links, prompt: model.prompt, kind, format: 'glb', ...(live ? { rigged: true } : {}) },
+ );
+ },
+ },
+
+ {
+ name: 'check_generation',
+ title: 'Collect a generation that was still rendering',
+ description:
+ 'Collect a 3D generation that was still rendering when generate_3d_model returned. Pass the job_id '
+ + 'from that result. While it is still working you get updated timing; when it is done you get the model.',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
+ schema: { job_id: z.string().min(1).describe('The job_id from a pending generation.') },
+ async run({ job_id: jobId }) {
+ const result = await client.mcp.callTool('check_job', { job_id: jobId });
+ const data = result?.structuredContent || {};
+ const text = (result?.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n');
+ if (result?.isError) return fail(data.message || text || 'That job could not be collected.');
+ const src = data.glbUrl || data.glb_url;
+ if (!src) return ok(text || 'Still rendering. Try again shortly.', { status: 'pending', jobId, ...data });
+ const links = linksFor(src, data.prompt ? promptTitle(data.prompt) : '');
+ return ok(`Ready.\nOpen it in your room: ${links.arLaunchUrl}\nModel file: ${links.glbUrl}`, {
+ status: 'done', ...links, ...(data.prompt ? { prompt: data.prompt } : {}),
+ });
+ },
+ },
+
+ {
+ name: 'search_models',
+ title: 'Search the ready-made model library',
+ description:
+ 'Search the ready-made 3D model catalogue by name, category and tag. The default catalogue is a few '
+ + 'hundred public-domain (CC0) props, free to use commercially. Faster and more predictable than '
+ + 'generating when a common object will do: search first, generate what you cannot find.',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
+ schema: {
+ query: z.string().max(120).optional().describe('Words to match against names, categories and tags. Omit to browse.'),
+ limit: z.number().int().min(1).max(50).optional().describe('How many results to return. Default 12.'),
+ catalogue: z.string().url().optional().describe('A different catalogue URL to search instead of the default.'),
+ },
+ async run({ query = '', limit = 12, catalogue }) {
+ const url = catalogue || env.assets;
+ const res = await fetch(url);
+ if (!res.ok) return fail(`The catalogue at ${url} answered ${res.status}.`);
+ const items = normalizeCatalogue(await res.json(), { rewriteUrl: (u) => cdnUrl(u, env.origin) });
+ const q = query.trim().toLowerCase();
+ const terms = q ? q.split(/\s+/) : [];
+ const matches = terms.length
+ ? items.filter((it) => terms.every((t) => (it.keywords || it.title).includes(t)))
+ : items;
+ const page = matches.slice(0, limit).map((it) => ({
+ src: it.src,
+ title: it.title,
+ poster: it.poster || undefined,
+ arLaunchUrl: buildArLaunchUrl(env.origin, it.src, it.title),
+ }));
+ if (!page.length) {
+ return ok(
+ `Nothing in the catalogue matches "${query}". ${items.length} models are available: `
+ + 'try a broader word, or generate one with generate_3d_model.',
+ { total: items.length, matched: 0, models: [] },
+ );
+ }
+ return ok(
+ `${matches.length} of ${items.length} models match "${query || 'anything'}". Showing ${page.length}:\n`
+ + page.map((m) => `· ${m.title}: ${m.src}`).join('\n'),
+ { total: items.length, matched: matches.length, models: page },
+ );
+ },
+ },
+
+ {
+ name: 'compose_ar_scene',
+ title: 'Arrange models into one AR scene and get a link',
+ description:
+ 'Arrange several models into a single scene and get one link that reopens it exactly: same models, '
+ + 'same positions, rotations and scales. Open that link on a phone and the whole arrangement stands in '
+ + 'the real room. Coordinates are metres on the floor: x is right, z is forward with negative values '
+ + 'further away, so { x: 0, z: -2 } is two metres in front of the viewer. This is the tool to reach for '
+ + 'when someone wants to see more than one thing at once.',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
+ schema: {
+ models: z.array(MODEL_SHAPE).min(1).max(20).describe('The models to arrange, in placement order.'),
+ page_url: z.string().url().optional().describe('The page hosting the studio. Defaults to the hosted demo.'),
+ title: z.string().max(120).optional().describe('A name for the scene, used in the summary.'),
+ },
+ async run({ models, page_url: pageUrl, title }) {
+ const placements = [];
+ const rejected = [];
+ for (const [i, m] of models.entries()) {
+ const src = normalizeGlbUrl(m.src);
+ if (!src) { rejected.push(m.src); continue; }
+ placements.push({
+ src,
+ title: m.title || `Model ${i + 1}`,
+ x: Number.isFinite(m.x) ? m.x : 0,
+ z: Number.isFinite(m.z) ? m.z : -1.6 - i * 0.1,
+ yaw: Number.isFinite(m.yaw) ? m.yaw : 0,
+ scale: Number.isFinite(m.scale) ? m.scale : 1,
+ });
+ }
+ if (!placements.length) {
+ return fail('None of those models are loadable https .glb URLs, so there is no scene to build.');
+ }
+ const base = pageUrl || env.pageUrl;
+ const url = sceneUrl(placements, base);
+ const short = studioShareUrl(base, placements);
+ const note = rejected.length ? `\n${rejected.length} entr${rejected.length === 1 ? 'y was' : 'ies were'} skipped: only https .glb URLs can be placed.` : '';
+ return ok(
+ `${title ? `"${title}": ` : ''}${placements.length} model${placements.length === 1 ? '' : 's'} arranged.\n`
+ + `Open on a phone and tap Camera to see it in the room: ${url}${note}`,
+ { sceneUrl: url, modelsOnlyUrl: short, models: placements, skipped: rejected },
+ );
+ },
+ },
+
+ {
+ name: 'export_ar',
+ title: 'Turn a model into a "View in your space" link',
+ description:
+ 'Turn any public GLB URL into a one-tap "View in your space" experience. The returned link routes '
+ + 'itself by device: Apple Quick Look on iPhone and iPad, Google Scene Viewer on Android, an '
+ + 'interactive WebGL viewer on desktop. Use it right after generating or finding a model so the '
+ + 'person can put it on their actual desk.',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
+ schema: {
+ glb_url: z.string().url().describe('Public https URL of a .glb or .gltf model.'),
+ title: z.string().max(120).optional().describe('Name shown in the AR experience.'),
+ kind: z.enum(['model', 'avatar']).optional().describe('avatar marks a rigged character, which stays animated.'),
+ user_agent: z.string().optional().describe('If you know the viewer\'s User-Agent, the response names the viewer they will get.'),
+ },
+ async run({ glb_url: glbUrl, title = '', kind = 'model', user_agent: userAgent }) {
+ let asset;
+ try {
+ asset = assertArAssetUrl(glbUrl);
+ } catch (err) {
+ return fail(err.message);
+ }
+ const links = linksFor(asset, title, kind === 'avatar');
+ const target = userAgent ? detectArTarget(userAgent) : null;
+ const viewerName = target === 'ios' ? 'Apple Quick Look' : target === 'android' ? 'Google Scene Viewer' : target === 'desktop' ? 'the WebGL viewer' : null;
+ return ok(
+ `Ready for AR. Open on a phone to place it in your space: ${links.arLaunchUrl}\n`
+ + (viewerName ? `That device will open ${viewerName}.\n` : '')
+ + `Interactive viewer: ${links.viewerUrl}`,
+ { ...links, format: 'glb', ...(target ? { target } : {}) },
+ );
+ },
+ },
+
+ {
+ name: 'create_ar_page',
+ title: 'Generate a deployable AR page',
+ description:
+ 'Return a complete, self-contained HTML page that embeds the AR studio, configured for the caller\'s '
+ + 'models. Write it to a file, commit it, and it works on GitHub Pages, Netlify, Vercel, or any static '
+ + 'host: no build step and no API key. Use it when someone asks to "add AR to my site" rather than '
+ + 'just to see a model.',
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
+ schema: {
+ title: z.string().max(80).optional().describe('Page and studio title.'),
+ assets: z.string().optional().describe('Catalogue URL for the model tray. Defaults to the free CC0 library.'),
+ accent: z.string().max(24).optional().describe('Accent colour, any CSS colour.'),
+ models: z.array(MODEL_SHAPE).max(20).optional().describe('Models pre-loaded into the scene on open.'),
+ generate: z.boolean().optional().describe('Show the text-to-3D prompt box. Default true.'),
+ },
+ async run(args) {
+ const html = renderPage(args);
+ return ok(
+ `Here is a complete AR page (${(html.length / 1024).toFixed(1)} kB). Save it as index.html and publish it: `
+ + 'no build step, no key, nothing else to install.\n\n'
+ + html,
+ { html, filename: 'index.html', bytes: html.length },
+ );
+ },
+ },
+ ];
+}
+
+// ── Result envelopes ────────────────────────────────────────────────────────
+
+function ok(text, structuredContent) {
+ return { content: [{ type: 'text', text }], ...(structuredContent ? { structuredContent } : {}) };
+}
+
+function fail(message) {
+ return { content: [{ type: 'text', text: message }], structuredContent: { error: true, message }, isError: true };
+}
+
+/** A studio link carrying both the model list and the full arrangement hash. */
+export function sceneUrl(placements, pageUrl) {
+ const base = studioShareUrl(pageUrl, placements);
+ const hash = sceneToHashParam(placements);
+ return hash ? `${base}#s=${hash}` : base;
+}
+
+const escapeHtml = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+}[c]));
+
+/** Render a standalone page that embeds the studio. Exported so the CLI reuses it. */
+export function renderPage({ title = 'AR Studio', assets, accent = '#8b7cf8', models = [], generate = true } = {}) {
+ const config = {
+ branding: { title, accent },
+ ...(assets ? { assets } : {}),
+ ...(generate === false ? { generate: { enabled: false } } : {}),
+ fullscreen: false,
+ };
+ const preload = (models || [])
+ .map((m) => ({ src: normalizeGlbUrl(m.src), title: m.title || '' }))
+ .filter((m) => m.src);
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<title>${escapeHtml(title)}</title>
+<meta name="description" content="Place 3D models in your real room, straight from the browser." />
+<style>
+ html, body { margin: 0; height: 100%; background: #06070a; color: #ecedf2;
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
+ #stage { position: fixed; inset: 0; }
+ noscript { display: block; padding: 32px; text-align: center; color: #9aa0af; }
+</style>
+</head>
+<body>
+<div id="stage"></div>
+<noscript>This page needs JavaScript to render 3D models in your space.</noscript>
+<script type="module">
+import { createArStudio } from 'https://unpkg.com/3d-ar-studio/dist/ar-studio.min.js';
+
+const studio = createArStudio('#stage', ${JSON.stringify(config, null, 2).replace(/\n/g, '\n')});
+${preload.length ? `\nfor (const model of ${JSON.stringify(preload, null, 2)}) {\n\tawait studio.addModel(model, { announce: false });\n}\n` : ''}</script>
+</body>
+</html>
+`;
+}
diff --git a/packages/ar-studio/package.json b/packages/ar-studio/package.json
new file mode 100644
index 000000000..e4afc6765
--- /dev/null
+++ b/packages/ar-studio/package.json
@@ -0,0 +1,115 @@
+{
+ "name": "3d-ar-studio",
+ "version": "0.3.2",
+ "mcpName": "io.github.nirholas/3d-ar-studio",
+ "description": "Drop a full augmented-reality studio into any web page: place any number of 3D models in your real room through the camera, generate new ones from a text prompt, arrange them, share the scene as a link or QR code, and build together in a live shared room. WebXR + Quick Look + Scene Viewer, a free CC0 model library and keyless text-to-3D out of the box, and an MCP server so agents can compose AR scenes too.",
+ "type": "module",
+ "license": "Apache-2.0",
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "homepage": "https://nirholas.github.io/3D-AR-Studio/",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/ar-studio"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/3D-AR-Studio/issues"
+ },
+ "keywords": [
+ "ar",
+ "augmented-reality",
+ "webxr",
+ "threejs",
+ "3d",
+ "glb",
+ "gltf",
+ "quick-look",
+ "usdz",
+ "scene-viewer",
+ "arcore",
+ "arkit",
+ "text-to-3d",
+ "mcp",
+ "model-context-protocol",
+ "web-component",
+ "three.ws"
+ ],
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "types": "./types/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./types/index.d.ts",
+ "default": "./src/index.js"
+ },
+ "./element": "./src/element.js",
+ "./auto": "./src/auto.js",
+ "./ar-launch": "./src/ar-launch.js",
+ "./sources": "./src/sources/index.js",
+ "./forge": "./src/forge/client.js",
+ "./mcp": "./mcp/index.js",
+ "./dist/*": "./dist/*",
+ "./package.json": "./package.json"
+ },
+ "bin": {
+ "3d-ar-studio": "./bin/cli.mjs",
+ "ar-studio": "./bin/cli.mjs",
+ "3d-ar-studio-mcp": "./bin/mcp.mjs"
+ },
+ "files": [
+ "src",
+ "mcp",
+ "bin",
+ "dist",
+ "!dist/*.map",
+ "templates",
+ "types",
+ "server.json",
+ "README.md",
+ "LICENSE",
+ "CHANGELOG.md"
+ ],
+ "scripts": {
+ "build": "node scripts/build.mjs",
+ "build:site": "node site/build.mjs",
+ "test": "node --test \"test/**/*.test.mjs\"",
+ "lint": "eslint src mcp bin scripts site test",
+ "test:browser": "node scripts/smoke-browser.mjs",
+ "dev": "node bin/cli.mjs dev --dir site/public",
+ "inspect": "npx -y @modelcontextprotocol/inspector node bin/mcp.mjs",
+ "prepack": "node scripts/build.mjs"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.31.0",
+ "zod": "^3.23.8"
+ },
+ "peerDependencies": {
+ "@colyseus/schema": "^3.0.0",
+ "colyseus.js": "^0.16.0",
+ "three": ">=0.160.0"
+ },
+ "peerDependenciesMeta": {
+ "three": {
+ "optional": false
+ },
+ "colyseus.js": {
+ "optional": true
+ },
+ "@colyseus/schema": {
+ "optional": true
+ }
+ },
+ "devDependencies": {
+ "@colyseus/schema": "^3.0.0",
+ "colyseus.js": "^0.16.22",
+ "esbuild": "^0.28.0",
+ "eslint": "^9.20.0",
+ "three": "^0.184.0"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/ar-studio/scripts/build.mjs b/packages/ar-studio/scripts/build.mjs
new file mode 100644
index 000000000..116c9ff5f
--- /dev/null
+++ b/packages/ar-studio/scripts/build.mjs
@@ -0,0 +1,53 @@
+// Build the browser bundles.
+//
+// Two artefacts, both ES modules:
+//
+// dist/ar-studio.js everything bundled (three.js and the room client
+// included), registers <ar-studio>, readable, with a
+// source map. This is what a `<script type="module">`
+// tag on a plain HTML page loads.
+// dist/ar-studio.min.js the same, minified, for production pages.
+//
+// Package consumers who already bundle (Vite, webpack, Rollup) import the source
+// under `src/` instead and share their own copy of three.
+
+import { build } from 'esbuild';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const pkg = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'));
+
+const banner = `/*! ${pkg.name} v${pkg.version} · ${pkg.homepage}
+ * ${pkg.license} licensed. Bundles three.js (MIT) and colyseus.js (MIT). */`;
+
+await mkdir(resolve(root, 'dist'), { recursive: true });
+
+const common = {
+ entryPoints: [resolve(root, 'src/auto.js')],
+ bundle: true,
+ format: 'esm',
+ target: ['es2022', 'safari16', 'chrome111', 'firefox115'],
+ platform: 'browser',
+ banner: { js: banner },
+ logLevel: 'info',
+ // The WASM decoder modules are fetched at runtime from a CDN, never inlined.
+ external: [],
+};
+
+await build({ ...common, outfile: resolve(root, 'dist/ar-studio.js'), sourcemap: true });
+const min = await build({
+ ...common,
+ outfile: resolve(root, 'dist/ar-studio.min.js'),
+ minify: true,
+ sourcemap: false,
+ metafile: true,
+});
+
+const bytes = Object.values(min.metafile.outputs)[0]?.bytes ?? 0;
+await writeFile(
+ resolve(root, 'dist/BUILD.txt'),
+ `${pkg.name} ${pkg.version}\nminified bundle: ${(bytes / 1024).toFixed(0)} kB\n`,
+);
+console.log(`\nminified bundle: ${(bytes / 1024).toFixed(0)} kB`);
diff --git a/packages/ar-studio/scripts/smoke-browser.mjs b/packages/ar-studio/scripts/smoke-browser.mjs
new file mode 100644
index 000000000..47ac19917
--- /dev/null
+++ b/packages/ar-studio/scripts/smoke-browser.mjs
@@ -0,0 +1,267 @@
+// End-to-end check in a real browser.
+//
+// The unit suite covers the pure logic; this covers the half that only a browser
+// can answer: does the bundle boot, does a WebGL context come up, does the tray
+// load a live catalogue, and does a real GLB actually make it into the scene.
+// It is deliberately not part of `npm test`, because it needs Playwright and a
+// downloaded browser, which no consumer of this package should have to install.
+//
+// npm i -D playwright && npx playwright install chromium
+// node scripts/smoke-browser.mjs
+//
+// Exits non-zero on any console error, any page error, or any failed step.
+
+import { createServer } from 'node:http';
+import { readFile } from 'node:fs/promises';
+import { dirname, extname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const PORT = Number(process.env.PORT || 4173);
+
+let chromium;
+try {
+ ({ chromium } = await import('playwright'));
+} catch {
+ console.error('This check needs Playwright:\n npm i -D playwright && npx playwright install chromium\n');
+ process.exit(2);
+}
+
+const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.map': 'application/json' };
+const server = createServer(async (req, res) => {
+ const path = String(req.url).split('?')[0];
+ const file = resolve(ROOT, 'docs', `.${path === '/' ? '/index.html' : path}`);
+ try {
+ res.writeHead(200, { 'content-type': TYPES[extname(file)] || 'application/octet-stream' });
+ res.end(await readFile(file));
+ } catch {
+ res.writeHead(404).end('not found');
+ }
+});
+await new Promise((r) => server.listen(PORT, r));
+
+const browser = await chromium.launch();
+const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
+const problems = [];
+page.on('console', (m) => { if (m.type() === 'error') problems.push(`console: ${m.text()}`); });
+page.on('pageerror', (e) => problems.push(`pageerror: ${e.message}`));
+
+const steps = [];
+const step = (name, ok, detail = '') => {
+ steps.push({ name, ok, detail });
+ console.log(`${ok ? ' ok ' : ' FAIL '} ${name}${detail ? `: ${detail}` : ''}`);
+};
+
+try {
+ await page.goto(`http://localhost:${PORT}/studio.html`, { waitUntil: 'networkidle' });
+ await page.waitForTimeout(1500);
+
+ const boot = await page.evaluate(() => {
+ const canvas = document.querySelector('.ars-canvas');
+ return {
+ mounted: !!document.querySelector('.ars-root'),
+ pixels: canvas ? canvas.width * canvas.height : 0,
+ tabs: [...document.querySelectorAll('.ars-tab')].map((b) => b.textContent),
+ empty: !document.querySelector('.ars-empty')?.hidden,
+ webgl: !!document.querySelector('ar-studio')?.studio?.renderer?.getContext(),
+ };
+ });
+ step('the studio mounts', boot.mounted);
+ step('a WebGL context is live', boot.webgl);
+ step('the canvas has real pixels', boot.pixels > 100000, `${boot.pixels} px`);
+ step('the empty state is shown before anything is placed', boot.empty);
+ step('source tabs render', boot.tabs.length >= 2, boot.tabs.join(', '));
+
+ await page.click('button[aria-label="Add a model to the scene"]');
+ await page.click('.ars-tab[data-tab="objects"]');
+ await page.waitForSelector('.ars-item-add', { timeout: 30000 });
+ const items = await page.evaluate(() => document.querySelectorAll('.ars-item-add').length);
+ step('the live catalogue loads', items > 0, `${items} models listed`);
+
+ await page.click('.ars-item-add');
+ await page.waitForFunction(() => document.querySelector('ar-studio').studio.placements.length > 0, { timeout: 45000 });
+ const placed = await page.evaluate(() => {
+ const s = document.querySelector('ar-studio').studio;
+ return { count: s.placements.length, share: s.shareUrl(), title: s.placements[0].title };
+ });
+ step('a real GLB loads into the scene', placed.count === 1, placed.title);
+ step('the scene has a shareable link', placed.share.includes('#s='));
+
+ const restored = await page.evaluate(async () => {
+ const s = document.querySelector('ar-studio').studio;
+ const before = s.getScene();
+ await s.setScene(before);
+ return JSON.stringify(s.getScene()) === JSON.stringify(before);
+ });
+ step('the arrangement round-trips through setScene', restored);
+
+ await page.evaluate(() => document.querySelector('ar-studio').studio.clear());
+ const cleared = await page.evaluate(() => document.querySelector('ar-studio').studio.placements.length);
+ step('clearing empties the scene', cleared === 0);
+
+ // The iOS path converts the GLB to USDZ on the device. Headless Chromium is
+ // not iOS, but the conversion is the hard part and it runs identically here,
+ // so this proves the bytes Quick Look would receive are real.
+ const usdz = await page.evaluate(async () => {
+ const mod = await import('./ar-studio.min.js');
+ const t0 = performance.now();
+ const blob = await mod.glbUrlToUsdzBlob('https://three.ws/cdn/objects/polyhaven/glb/adjustable_wrench.glb');
+ const head = new Uint8Array(await blob.slice(0, 4).arrayBuffer());
+ const text = new TextDecoder('latin1').decode(new Uint8Array(await blob.arrayBuffer()));
+ return {
+ bytes: blob.size,
+ type: blob.type,
+ zip: head[0] === 0x50 && head[1] === 0x4b,
+ // three's exporter writes the scene as model.usda (older builds emitted
+ // .usdc); Quick Look reads either, so accept both rather than pinning
+ // this check to one version of the exporter.
+ hasUsd: /\.usd[ac]\b/.test(text),
+ entries: (text.match(/\.(usd[ac]|png|jpg)/g) || []).slice(0, 4).join(' '),
+ // Entries are stored uncompressed (Quick Look requires it), so the USD
+ // scene description is readable straight out of the archive.
+ anchored: /preliminary:anchoring:type = "plane"/.test(text)
+ && /preliminary:planeAnchoring:alignment = "horizontal"/.test(text),
+ metres: /metersPerUnit = 1/.test(text) && /upAxis = "Y"/.test(text),
+ staged: /def Xform "Model"/.test(text),
+ ms: Math.round(performance.now() - t0),
+ };
+ });
+ step('a GLB converts to real USDZ bytes on the device', usdz.zip && usdz.hasUsd && usdz.bytes > 10000,
+ `${(usdz.bytes / 1024).toFixed(0)} kB, ${usdz.type}, ${usdz.ms} ms, contains ${usdz.entries}`);
+ // Without these three the model opens in Quick Look and then hangs in the air
+ // instead of resting on the floor, which reads as broken tracking.
+ step('the USDZ asks ARKit for horizontal plane anchoring', usdz.anchored === true);
+ step('the USDZ declares metres and Y-up, the units Quick Look places by', usdz.metres === true);
+ step('the model rides on a stage node, so its placement survives the exporter',
+ usdz.staged === true);
+
+ const caps = await page.evaluate(async () => {
+ const mod = await import('./ar-studio.min.js');
+ return {
+ capability: await mod.arCapability(),
+ banner: mod.withQuickLookBanner('blob:abc', { title: 'Crate', callToAction: 'Buy' }),
+ filename: mod.usdzFilename('Adjustable Wrench'),
+ };
+ });
+ step('AR capability resolves without throwing', typeof caps.capability === 'string', caps.capability);
+ step('the Quick Look banner is attached as fragment params', caps.banner === 'blob:abc#checkoutTitle=Crate&callToAction=Buy');
+ step('a model title becomes a .usdz filename', caps.filename === 'adjustable-wrench.usdz', caps.filename);
+
+ await page.screenshot({ path: resolve(ROOT, 'smoke.png') });
+
+ // Device routing: an iPhone must land on Quick Look and an Android phone on
+ // Scene Viewer, because neither exposes WebXR and the camera-passthrough
+ // approximation is not what either of those users should get.
+ for (const [device, ua, want] of [
+ ['iPhone', 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1', 'quicklook'],
+ ['Android', 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36', 'sceneviewer'],
+ ]) {
+ const ctx = await browser.newContext({ userAgent: ua, viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
+ const p2 = await ctx.newPage();
+ await p2.goto(`http://localhost:${PORT}/studio.html`, { waitUntil: 'networkidle' });
+ await p2.waitForTimeout(1200);
+ const got = await p2.evaluate(async () => {
+ const mod = await import('./ar-studio.min.js');
+ const studio = document.querySelector('ar-studio').studio;
+ return {
+ capability: await mod.arCapability(),
+ mode: studio.arMode,
+ buttonShown: !document.querySelector('.ars-ar-label')?.closest('button')?.hidden,
+ label: document.querySelector('.ars-ar-label')?.textContent,
+ };
+ });
+ step(`${device} routes to its native AR viewer`, got.capability === want, `${got.capability}, button "${got.label}"`);
+ step(`${device} is offered the AR button`, got.buttonShown === true);
+
+ // The whole feature, end to end: put a real model in the scene, open the
+ // hand-off sheet the AR button opens, and prove the button in it is armed
+ // with something the device's AR viewer can actually open.
+ await p2.evaluate(() => document.querySelector('ar-studio').studio.addModel({
+ src: 'https://three.ws/cdn/objects/polyhaven/glb/adjustable_wrench.glb', title: 'Wrench',
+ }));
+ await p2.waitForFunction(() => document.querySelector('ar-studio').studio.placements.length > 0, { timeout: 45000 });
+ // Quick Look must never be handed a blob URL from a stale gesture, so the
+ // anchor click is intercepted rather than followed: Chromium would try to
+ // download the USDZ and tear the page down mid-check.
+ await p2.evaluate(() => {
+ window.__arClicks = [];
+ const real = window.HTMLAnchorElement.prototype.click;
+ window.HTMLAnchorElement.prototype.click = function patched() {
+ if (this.rel === 'ar') { window.__arClicks.push(this.href); return; }
+ return real.call(this);
+ };
+ });
+ await p2.click('.ars-ar-label');
+ await p2.waitForSelector('.ars-ar-go:not([disabled])', { timeout: 60000 });
+ const sheet = await p2.evaluate(() => {
+ const studio = document.querySelector('ar-studio').studio;
+ return {
+ open: !document.querySelector('.ars-modal[aria-label="Place a model in your space"]').hidden,
+ name: document.querySelector('.ars-ar-name')?.textContent,
+ goLabel: document.querySelector('.ars-ar-go-label')?.textContent,
+ status: document.querySelector('.ars-ar-status')?.textContent,
+ viewer: studio._arHandoff?.viewer,
+ href: studio._arHandoff?.href,
+ focused: document.activeElement?.className || '',
+ };
+ });
+ step(`${device} opens the AR hand-off sheet`, sheet.open && sheet.name === 'Wrench', `"${sheet.goLabel}", ${sheet.status}`);
+ step(`${device} arms the sheet with a real ${want} hand-off`, sheet.viewer === want,
+ `${sheet.viewer}: ${String(sheet.href).slice(0, 46)}`);
+ step(`${device} keeps focus inside the dialog`, sheet.focused.includes('ars-ar-'), sheet.focused);
+
+ if (want === 'quicklook') {
+ step('the prepared asset is a USDZ blob', /^blob:/.test(sheet.href), sheet.href.slice(0, 70));
+ await p2.click('.ars-ar-go');
+ const clicks = await p2.evaluate(() => window.__arClicks);
+ step('tapping Place activates an <a rel="ar"> straight away', clicks.length === 1, clicks[0]?.slice(0, 46));
+ // Safari sniffs the file type from the name. Without one it opens Quick
+ // Look in Object mode with AR unavailable, which looks like working
+ // software right up to the moment someone tries to use it.
+ const dl = await p2.evaluate(() => document.querySelector('a[rel="ar"]')?.getAttribute('download'));
+ step('the anchor names the blob, so Safari opens AR and not Object mode',
+ dl === 'wrench.usdz', String(dl));
+ const closed = await p2.evaluate(() => document.querySelector('.ars-modal[aria-label="Place a model in your space"]').hidden);
+ step('the sheet closes once the AR viewer has been handed the model', closed === true);
+ // The camera is one client at a time on a phone. Hold the page's stream
+ // open and ARKit never gets clean plane detection, so the model drifts
+ // with the device instead of anchoring. Headless Chromium has no camera,
+ // so the passthrough state is staged directly.
+ const yielded = await p2.evaluate(async () => {
+ const studio = document.querySelector('ar-studio').studio;
+ let stopped = false;
+ studio.arActive = true;
+ studio.mediaStream = { getTracks: () => [{ stop() { stopped = true; } }], getVideoTracks: () => [] };
+ studio._cameraYielded = false;
+ await studio.placeInYourSpace();
+ return { stopped, active: studio.arActive, yielded: studio._cameraYielded };
+ });
+ step('the page releases the camera before the AR viewer opens',
+ yielded.stopped === true && yielded.active === false && yielded.yielded === true);
+ // Second tap: the conversion is cached, so the sheet must arm without
+ // ever disabling the button. A stall here is the dead-button bug.
+ const t0 = Date.now();
+ await p2.click('.ars-ar-label');
+ await p2.waitForFunction(() => {
+ const studio = document.querySelector('ar-studio').studio;
+ return studio._arHandoff && !document.querySelector('.ars-ar-go').disabled;
+ }, { timeout: 10000 });
+ step('a second open is instant, from the cached USDZ', Date.now() - t0 < 1500, `${Date.now() - t0} ms`);
+ } else {
+ step('Scene Viewer needs no conversion, so the button is armed on open',
+ sheet.href === 'https://three.ws/cdn/objects/polyhaven/glb/adjustable_wrench.glb');
+ }
+ await ctx.close();
+ }
+} catch (err) {
+ step('run completed', false, err.message);
+}
+
+step('no console or page errors', problems.length === 0, problems.join(' | '));
+
+await browser.close();
+server.close();
+
+const failed = steps.filter((s) => !s.ok);
+console.log(`\n${steps.length - failed.length}/${steps.length} checks passed`);
+process.exit(failed.length ? 1 : 0);
diff --git a/packages/ar-studio/server.json b/packages/ar-studio/server.json
new file mode 100644
index 000000000..efc894755
--- /dev/null
+++ b/packages/ar-studio/server.json
@@ -0,0 +1,49 @@
+{
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
+ "name": "io.github.nirholas/3d-ar-studio",
+ "title": "3D AR Studio",
+ "description": "Put 3D models in someone's real room: generate, arrange, and hand back one AR link.",
+ "websiteUrl": "https://nirholas.github.io/3D-AR-Studio/",
+ "repository": {
+ "url": "https://github.com/nirholas/3D-AR-Studio",
+ "source": "github"
+ },
+ "version": "0.3.2",
+ "packages": [
+ {
+ "registryType": "npm",
+ "identifier": "3d-ar-studio-mcp",
+ "version": "0.3.2",
+ "runtimeHint": "npx",
+ "transport": {
+ "type": "stdio"
+ },
+ "environmentVariables": [
+ {
+ "name": "AR_STUDIO_PAGE_URL",
+ "description": "The page that composed AR scenes link to. Defaults to the hosted demo; set it to your own deployment of the studio.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "AR_STUDIO_ASSETS",
+ "description": "Catalogue URL that search_models searches. Defaults to the free CC0 model library.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "AR_STUDIO_MCP_ENDPOINT",
+ "description": "MCP endpoint used for text-to-3D generation. Defaults to the free, keyless three.ws 3D Studio connector.",
+ "isRequired": false,
+ "format": "string"
+ },
+ {
+ "name": "AR_STUDIO_ORIGIN",
+ "description": "Origin serving the hosted 'View in your space' launcher and the 3D viewer. Defaults to https://three.ws.",
+ "isRequired": false,
+ "format": "string"
+ }
+ ]
+ }
+ ]
+}
diff --git a/packages/ar-studio/site/build.mjs b/packages/ar-studio/site/build.mjs
new file mode 100644
index 000000000..e26d0b084
--- /dev/null
+++ b/packages/ar-studio/site/build.mjs
@@ -0,0 +1,74 @@
+// Build the GitHub Pages site into docs/.
+//
+// GitHub Pages serves this repository from the `docs/` folder on `main`, which
+// is why the output is committed: no Actions workflow, no deploy step, no
+// secrets. Push and the site is live.
+//
+// The bundle is copied in rather than linked from a CDN so the demo keeps
+// working if a CDN has a bad day, and so what the page runs is exactly the
+// build in this commit.
+
+import { cp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { layout } from './layout.mjs';
+import { homePage, studioPage, mcpPage } from './pages.mjs';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const out = resolve(root, 'docs');
+const pkg = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'));
+
+await rm(out, { recursive: true, force: true });
+await mkdir(out, { recursive: true });
+
+// Jekyll would otherwise swallow files and folders beginning with an underscore.
+await writeFile(resolve(out, '.nojekyll'), '');
+
+// Only the minified bundle ships to the site: the readable build and its source
+// map are for package consumers debugging against `dist/`, and adding six
+// megabytes to every clone of this repo to serve them here would be rude.
+await cp(resolve(root, 'dist/ar-studio.min.js'), resolve(out, 'ar-studio.min.js'));
+
+const SCRIPT = '<script type="module" src="./ar-studio.min.js"></script>';
+
+const pages = [
+ {
+ file: 'index.html',
+ nav: 'home',
+ title: '3D AR Studio: put anything in your room',
+ description:
+ 'A complete augmented-reality studio for any web page: place any number of 3D models in your real space through the camera, generate new ones from a prompt, share the scene as a link, and build together live.',
+ body: homePage(),
+ head: SCRIPT,
+ },
+ {
+ file: 'studio.html',
+ nav: 'studio',
+ title: 'Live demo: 3D AR Studio',
+ description: 'The full 3D AR Studio, running the published build. Open it on a phone and tap Camera.',
+ body: studioPage(),
+ head: SCRIPT,
+ bare: true,
+ },
+ {
+ file: 'mcp.html',
+ nav: 'mcp',
+ title: 'MCP server: 3D AR Studio',
+ description: 'Let an agent generate 3D models, compose an AR scene, and hand a person one link that opens it in their room.',
+ body: mcpPage(),
+ },
+];
+
+for (const page of pages) {
+ await writeFile(resolve(out, page.file), layout(page));
+}
+
+// A machine-readable pointer for anything that wants to find the build.
+await writeFile(resolve(out, 'version.json'), `${JSON.stringify({
+ name: pkg.name,
+ version: pkg.version,
+ homepage: pkg.homepage,
+ bundle: './ar-studio.min.js',
+}, null, 2)}\n`);
+
+console.log(`docs/ built: ${pages.length} pages + bundle (v${pkg.version})`);
diff --git a/packages/ar-studio/site/layout.mjs b/packages/ar-studio/site/layout.mjs
new file mode 100644
index 000000000..0932cc3fe
--- /dev/null
+++ b/packages/ar-studio/site/layout.mjs
@@ -0,0 +1,166 @@
+// The shared shell every page on the docs site renders into.
+//
+// No framework, no build step beyond string interpolation: the site is three
+// static pages, and the studio itself is the only heavy thing on any of them.
+
+export const CSS = `
+:root {
+ color-scheme: dark;
+ --bg: #07080c;
+ --panel: rgba(255, 255, 255, 0.04);
+ --line: rgba(255, 255, 255, 0.1);
+ --ink: #ecedf2;
+ --dim: #9aa0af;
+ --faint: #6b7080;
+ --accent: #8b7cf8;
+ --accent-ink: #dcd6ff;
+ --radius: 16px;
+ --font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
+}
+* { box-sizing: border-box; }
+html { scroll-behavior: smooth; }
+body {
+ margin: 0;
+ font-family: var(--font);
+ background: radial-gradient(120% 90% at 50% 0%, #141827 0%, #0a0b11 45%, #06070a 100%);
+ color: var(--ink);
+ line-height: 1.6;
+ -webkit-font-smoothing: antialiased;
+}
+a { color: var(--accent-ink); }
+.wrap { max-width: 1040px; margin: 0 auto; padding: 0 20px; }
+header.site {
+ position: sticky; top: 0; z-index: 50;
+ backdrop-filter: blur(12px);
+ background: rgba(7, 8, 12, 0.72);
+ border-bottom: 1px solid var(--line);
+}
+header.site .wrap { display: flex; align-items: center; gap: 16px; height: 60px; }
+.brand { display: flex; align-items: center; gap: 9px; font-weight: 750; letter-spacing: -0.01em; text-decoration: none; color: var(--ink); }
+.brand .dot { width: 10px; height: 10px; border-radius: 3px; background: linear-gradient(135deg, var(--accent), #4fd1c5); box-shadow: 0 0 18px rgba(139, 124, 248, 0.7); }
+nav.site { margin-left: auto; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
+nav.site a {
+ color: var(--dim); text-decoration: none; font-size: 14px; font-weight: 600;
+ padding: 7px 11px; border-radius: 9px; transition: color .15s, background .15s;
+}
+nav.site a:hover, nav.site a[aria-current="page"] { color: var(--ink); background: rgba(255, 255, 255, 0.07); }
+h1, h2, h3 { line-height: 1.2; letter-spacing: -0.02em; margin: 0 0 12px; }
+h1 { font-size: clamp(34px, 6vw, 56px); font-weight: 800; }
+h2 { font-size: clamp(23px, 3.4vw, 31px); font-weight: 750; margin-top: 8px; }
+h3 { font-size: 17px; font-weight: 700; }
+p { margin: 0 0 14px; color: var(--dim); }
+p.lead { font-size: clamp(16px, 2.1vw, 19px); color: #c3c8d4; max-width: 62ch; }
+section { padding: 56px 0; border-top: 1px solid var(--line); }
+section:first-of-type { border-top: 0; }
+.eyebrow { font-size: 12px; font-weight: 750; letter-spacing: 0.14em; text-transform: uppercase; color: var(--accent); margin-bottom: 12px; }
+.row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
+.btn {
+ display: inline-flex; align-items: center; gap: 8px; text-decoration: none;
+ font-size: 15px; font-weight: 700; padding: 12px 20px; border-radius: 12px;
+ background: rgba(255, 255, 255, 0.06); border: 1px solid var(--line); color: var(--ink);
+ transition: background .15s, border-color .15s, transform .06s;
+ cursor: pointer;
+}
+.btn:hover { background: rgba(255, 255, 255, 0.11); border-color: rgba(255, 255, 255, 0.24); }
+.btn:active { transform: translateY(1px); }
+.btn.primary { background: var(--accent); border-color: var(--accent); color: #0d0b1e; }
+.btn.primary:hover { filter: brightness(1.08); }
+.grid { display: grid; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(232px, 1fr)); }
+.card {
+ background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
+ padding: 18px 18px 16px;
+}
+.card h3 { margin-bottom: 6px; }
+.card p { font-size: 14px; margin: 0; }
+.card .ico { font-size: 22px; line-height: 1; margin-bottom: 10px; display: block; }
+pre {
+ margin: 0 0 14px; padding: 16px 18px; overflow-x: auto;
+ background: #0b0d13; border: 1px solid var(--line); border-radius: 13px;
+ font-family: var(--mono); font-size: 13.5px; line-height: 1.65; color: #d7dbe6;
+}
+code { font-family: var(--mono); font-size: 0.92em; }
+p code, li code, td code { background: rgba(255, 255, 255, 0.07); padding: 1.5px 6px; border-radius: 6px; color: var(--accent-ink); }
+table { width: 100%; border-collapse: collapse; font-size: 14px; margin-bottom: 16px; display: block; overflow-x: auto; }
+th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line); vertical-align: top; }
+th { color: var(--ink); font-weight: 700; white-space: nowrap; }
+td { color: var(--dim); }
+ul { color: var(--dim); padding-left: 22px; }
+li { margin-bottom: 7px; }
+.stage {
+ position: relative; height: min(72vh, 620px); min-height: 420px;
+ border: 1px solid var(--line); border-radius: 18px; overflow: hidden;
+ background: #06070a; box-shadow: 0 30px 80px -40px rgba(139, 124, 248, 0.5);
+}
+.pill {
+ display: inline-flex; align-items: center; gap: 7px; font-size: 12.5px; font-weight: 650;
+ color: var(--accent-ink); background: rgba(139, 124, 248, 0.14);
+ border: 1px solid rgba(139, 124, 248, 0.38); border-radius: 999px; padding: 6px 13px;
+ margin-bottom: 18px;
+}
+footer.site { border-top: 1px solid var(--line); padding: 34px 0 60px; color: var(--faint); font-size: 13.5px; }
+footer.site a { color: var(--dim); }
+.tabs { display: flex; gap: 6px; margin-bottom: 12px; flex-wrap: wrap; }
+.tab {
+ appearance: none; cursor: pointer; font: inherit; font-size: 13px; font-weight: 650;
+ color: var(--dim); background: rgba(255, 255, 255, 0.05); border: 1px solid transparent;
+ border-radius: 999px; padding: 7px 14px;
+}
+.tab[aria-selected="true"] { color: var(--accent-ink); background: rgba(139, 124, 248, 0.16); border-color: rgba(139, 124, 248, 0.4); }
+[hidden] { display: none !important; }
+@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
+`;
+
+/**
+ * @param {object} page
+ * @param {string} page.title Browser tab + og:title
+ * @param {string} page.description
+ * @param {string} page.body Page HTML
+ * @param {string} [page.head] Extra <head> content
+ * @param {string} [page.nav] Current nav key
+ * @param {string} [page.base] Site base path for links
+ * @param {boolean} [page.bare] Skip the header/footer chrome
+ */
+export function layout({ title, description, body, head = '', nav = '', base = './', bare = false }) {
+ const link = (href, key, label) =>
+ `<a href="${base}${href}"${nav === key ? ' aria-current="page"' : ''}>${label}</a>`;
+ const chrome = bare ? '' : `
+<header class="site"><div class="wrap">
+ <a class="brand" href="${base}index.html"><span class="dot" aria-hidden="true"></span> 3D AR Studio</a>
+ <nav class="site">
+ ${link('index.html', 'home', 'Overview')}
+ ${link('studio.html', 'studio', 'Live demo')}
+ ${link('mcp.html', 'mcp', 'MCP server')}
+ <a href="https://github.com/nirholas/3D-AR-Studio">GitHub</a>
+ <a href="https://www.npmjs.com/package/3d-ar-studio">npm</a>
+ </nav>
+</div></header>`;
+ const foot = bare ? '' : `
+<footer class="site"><div class="wrap">
+ <p><strong style="color:var(--ink)">3D AR Studio</strong> is open source under Apache-2.0.
+ Models and the free text-to-3D lane are served by <a href="https://three.ws">three.ws</a>; point it at your own catalogue with one option.</p>
+ <p><a href="https://github.com/nirholas/3D-AR-Studio">GitHub</a> · <a href="https://www.npmjs.com/package/3d-ar-studio">npm</a> · <a href="https://registry.modelcontextprotocol.io/?q=3d-ar-studio">MCP registry</a> · <a href="https://three.ws">three.ws</a></p>
+</div></footer>`;
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<title>${title}</title>
+<meta name="description" content="${description}" />
+<meta property="og:type" content="website" />
+<meta property="og:title" content="${title}" />
+<meta property="og:description" content="${description}" />
+<meta name="twitter:card" content="summary_large_image" />
+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%238b7cf8'/%3E%3Cpath d='M16 6l9 5.2v10.4L16 27l-9-5.4V11.2z' fill='none' stroke='%23fff' stroke-width='2' stroke-linejoin='round'/%3E%3C/svg%3E" />
+<style>${CSS}</style>
+${head}
+</head>
+<body>
+${chrome}
+${body}
+${foot}
+</body>
+</html>
+`;
+}
diff --git a/packages/ar-studio/site/pages.mjs b/packages/ar-studio/site/pages.mjs
new file mode 100644
index 000000000..1f78cf606
--- /dev/null
+++ b/packages/ar-studio/site/pages.mjs
@@ -0,0 +1,222 @@
+// The three pages of the docs site. Content lives here as plain HTML strings so
+// there is no template language to learn and no markdown renderer to ship.
+
+export function homePage() {
+ return `
+<section class="wrap" style="padding-top:56px">
+ <span class="pill">Apache-2.0 · one script tag · works on iPhone and Android</span>
+ <h1>Put anything in your room.</h1>
+ <p class="lead">
+ A complete augmented-reality studio you can drop into any web page. Place as many 3D models
+ as you like in your real space through the camera, describe a new one and watch it appear,
+ arrange everything by hand, then share the whole scene as a link, a QR code, or a live room
+ someone else can build in with you.
+ </p>
+ <div class="row" style="margin:22px 0 30px">
+ <a class="btn primary" href="./studio.html">Open the live demo</a>
+ <a class="btn" href="#quickstart">Add it to your site</a>
+ <a class="btn" href="https://github.com/nirholas/3D-AR-Studio">Star on GitHub</a>
+ </div>
+ <div class="stage"><ar-studio embedded style="position:absolute;inset:0;min-height:0"
+ title="Live demo" share-base="https://nirholas.github.io/3D-AR-Studio/studio.html"></ar-studio></div>
+ <p style="font-size:13px;color:var(--faint);margin-top:12px">
+ That frame is the real package, running the same code you install. On a phone, tap
+ <strong>Place in your space</strong> and the model is anchored to your actual floor by
+ ARKit or ARCore. <strong>Camera</strong> is the in-page preview beside it: it turns with
+ the phone, it does not track the room.
+ </p>
+</section>
+
+<section class="wrap" id="quickstart">
+ <div class="eyebrow">Quick start</div>
+ <h2>One line, and you have AR.</h2>
+ <p class="lead">No build step, no API key, no account. The models and the text-to-3D lane are free and keyless.</p>
+ <h3>Plain HTML</h3>
+<pre><code>&lt;script type="module" src="https://unpkg.com/3d-ar-studio/dist/ar-studio.min.js"&gt;&lt;/script&gt;
+&lt;ar-studio&gt;&lt;/ar-studio&gt;</code></pre>
+ <h3>npm</h3>
+<pre><code>npm i 3d-ar-studio three</code></pre>
+<pre><code>import { createArStudio } from '3d-ar-studio'
+
+const studio = createArStudio('#stage', {
+ assets: 'https://your.cdn/models.json', // your catalogue, or leave it out for the free CC0 library
+ branding: { title: 'Acme AR', accent: '#00b894' },
+})
+
+studio.on('add', ({ placement }) =&gt; console.log('placed', placement.title))</code></pre>
+ <h3>Scaffold a deployable page</h3>
+<pre><code>npx 3d-ar-studio create my-ar-site # a ready-to-publish folder
+npx 3d-ar-studio deploy # push it and turn on GitHub Pages</code></pre>
+</section>
+
+<section class="wrap">
+ <div class="eyebrow">What you get</div>
+ <h2>Not a model viewer. A studio.</h2>
+ <div class="grid">
+ <div class="card"><span class="ico" aria-hidden="true">🏠</span>
+ <h3>Many models, one room</h3>
+ <p>Place, drag, pinch-resize, twist-rotate and duplicate as many models as you want in a single live camera view. Every other web-AR drop-in stops at one.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">✍️</span>
+ <h3>Generate without leaving the camera</h3>
+ <p>Type "a brass desk lamp" into the dock. The generation runs behind the live view and the finished model drops into the room. Free, keyless, no account.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">✦</span>
+ <h3>Real WebXR, not a fallback</h3>
+ <p>An always-armed hit-test reticle, one XRAnchor per model, real-world light estimation, and depth occlusion so models hide behind your furniture.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">📱</span>
+ <h3>Real ARKit on iPhone, not an approximation</h3>
+ <p>Tap <strong>Place in your space</strong> and Apple's own "View in AR" sheet opens: true plane detection, true scale, true occlusion. The model is converted to USDZ on the device, stood on the floor rather than left at the height it was modelled at, and prepared before the tap, because iOS opens Quick Look only while the gesture is still live. Android without WebXR gets Scene Viewer.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">🔗</span>
+ <h3>Scenes are links</h3>
+ <p>The whole arrangement (models, positions, rotations, scales) round-trips through the URL. Compose on a laptop, scan the QR, it reopens exactly on your phone.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">👥</span>
+ <h3>Build together, live</h3>
+ <p>Open a room, share a six-character code, and every add and move syncs to everyone in it in real time, with live presence.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">🕺</span>
+ <h3>Characters actually move</h3>
+ <p>Any humanoid GLB with no baked animation gets an idle clip retargeted onto its own skeleton: Mixamo, VRM, Avaturn, Unreal, Daz. No rig allow-list, no T-poses.</p></div>
+ <div class="card"><span class="ico" aria-hidden="true">🤖</span>
+ <h3>Agents can drive it</h3>
+ <p>A bundled MCP server lets Claude, ChatGPT or any agent generate a model, compose an arrangement, and hand your user one link that opens it in their room.</p></div>
+ </div>
+</section>
+
+<section class="wrap" id="assets">
+ <div class="eyebrow">Your models</div>
+ <h2>Bring your own catalogue.</h2>
+ <p class="lead">
+ Out of the box the tray is filled from three.ws: a few hundred public-domain (CC0) props,
+ free for commercial use, served with open CORS. Swap in your own with one option
+ a URL, an array, or a function.
+ </p>
+<pre><code>// 1. A JSON file anywhere. Five common shapes are read without reshaping.
+createArStudio(el, { assets: 'https://cdn.acme.com/models.json' })
+
+// 2. A list you hold in code.
+import { staticSource } from '3d-ar-studio/sources'
+createArStudio(el, { assets: staticSource({
+ label: 'Our furniture',
+ items: [{ src: 'https://cdn.acme.com/chair.glb', title: 'Aero chair', poster: '…' }],
+}) })
+
+// 3. Several tabs at once, in order.
+createArStudio(el, { assets: ['recent', myCatalogue, 'objects', 'link'] })
+
+// 4. Anything else: a source is just an object with a list().
+createArStudio(el, { assets: {
+ id: 'search', label: 'Search', searchable: true,
+ async list() {
+ const r = await fetch('/api/models').then((x) =&gt; x.json())
+ return r.map((m) =&gt; ({ src: m.glb, title: m.name, poster: m.thumb }))
+ },
+} })</code></pre>
+ <p>Your users can also point the studio somewhere else themselves, without touching your code:
+ add <code>?assets=https://…/manifest.json</code> to the page URL. Only https URLs are accepted, and every
+ model source is re-validated before it reaches the loader.</p>
+</section>
+
+<section class="wrap" id="options">
+ <div class="eyebrow">Configuration</div>
+ <h2>Options</h2>
+ <table>
+ <thead><tr><th>Option</th><th>Default</th><th>What it does</th></tr></thead>
+ <tbody>
+ <tr><td><code>assets</code></td><td><code>'three.ws'</code></td><td>Where models come from: a preset, a manifest URL, a source object, or an array of them.</td></tr>
+ <tr><td><code>generate</code></td><td>enabled, free three.ws lane</td><td><code>{ enabled, endpoint, kind, tier }</code>. <code>endpoint</code> is any MCP server exposing a compatible generate tool.</td></tr>
+ <tr><td><code>rooms</code></td><td>enabled</td><td><code>{ enabled, server }</code>. Point <code>server</code> at your own Colyseus deployment to host shared rooms yourself.</td></tr>
+ <tr><td><code>animations</code></td><td>three.ws idle clip</td><td><code>{ enabled, manifestUrl, clip }</code>. The clip retargeted onto humanoid models that ship no animation.</td></tr>
+ <tr><td><code>lighting</code></td><td><code>'studio'</code> HDRI</td><td><code>{ preset, urls }</code>. Set <code>preset: null</code> for procedural lighting only and zero HDRI download.</td></tr>
+ <tr><td><code>branding</code></td><td> </td><td><code>{ title, accent, backHref, backLabel }</code>.</td></tr>
+ <tr><td><code>shareBaseUrl</code></td><td>this page</td><td>Where share links and QR codes point.</td></tr>
+ <tr><td><code>persistKey</code></td><td><code>'ar-studio:scene:v1'</code></td><td>localStorage key for the saved scene. Change it to run two studios on one origin.</td></tr>
+ <tr><td><code>maxPlacements</code></td><td><code>20</code></td><td>Cap on simultaneous models. Keeps low-end phones interactive.</td></tr>
+ <tr><td><code>allowUrlOverride</code></td><td><code>true</code></td><td>Honour <code>?assets=</code>, <code>?src=</code>, <code>?room=</code> and <code>?forge=</code> on the hosting page's URL.</td></tr>
+ <tr><td><code>onEvent</code></td><td><code>null</code></td><td>Called with <code>(event, detail)</code> for every notable action: wire it to your analytics.</td></tr>
+ </tbody>
+ </table>
+ <h3>Events</h3>
+ <p>Subscribe with <code>studio.on(name, fn)</code>, or listen for <code>ar-studio:&lt;name&gt;</code> DOM events on the mounted element:
+ <code>add</code>, <code>remove</code>, <code>select</code>, <code>clear</code>, <code>generate</code>,
+ <code>generate-error</code>, <code>camera</code>, <code>xr</code>, <code>room</code>, <code>share</code>.</p>
+</section>
+
+<section class="wrap">
+ <div class="eyebrow">Provenance</div>
+ <h2>Extracted from a studio people already use.</h2>
+ <p class="lead">
+ This is not a demo written to look good in a README. The rendering ladder, the anchor
+ lifecycle, the retargeting pipeline, the scene format and the shared-room protocol are
+ lifted from the AR surfaces running in production on
+ <a href="https://three.ws">three.ws</a>, and generalized so they work on your site
+ with your models.
+ </p>
+</section>
+`;
+}
+
+export function studioPage() {
+ return `
+<div style="position:fixed;inset:0"><ar-studio id="studio" style="position:absolute;inset:0;min-height:0"
+ title="AR Studio" back-href="./index.html"></ar-studio></div>
+`;
+}
+
+export function mcpPage() {
+ return `
+<section class="wrap" style="padding-top:48px">
+ <span class="pill">Model Context Protocol</span>
+ <h1>Let an agent build the scene.</h1>
+ <p class="lead">
+ The package ships an MCP server. Point Claude, ChatGPT, Cursor or your own agent at it and
+ it can generate 3D models, compose an arrangement, and hand a person one link that opens
+ that arrangement in their actual room.
+ </p>
+ <h2>Install</h2>
+<pre><code>{
+ "mcpServers": {
+ "3d-ar-studio": {
+ "command": "npx",
+ "args": ["-y", "3d-ar-studio-mcp"]
+ }
+ }
+}</code></pre>
+ <p>No API key. Every tool below is free and keyless.</p>
+
+ <h2>Tools</h2>
+ <table>
+ <thead><tr><th>Tool</th><th>What it does</th></tr></thead>
+ <tbody>
+ <tr><td><code>generate_3d_model</code></td><td>Turn a text prompt into a downloadable, textured GLB. Returns the model URL plus links that open it in AR.</td></tr>
+ <tr><td><code>check_generation</code></td><td>Collect a generation that was still rendering when the first call returned.</td></tr>
+ <tr><td><code>search_models</code></td><td>Search the free CC0 library (or any catalogue you configure) by name, category and tag.</td></tr>
+ <tr><td><code>compose_ar_scene</code></td><td>Arrange several models into one scene and return a single link (and a QR-friendly short form) that reopens it exactly.</td></tr>
+ <tr><td><code>export_ar</code></td><td>Turn any GLB URL into a device-aware "View in your space" link: Quick Look on iOS, Scene Viewer on Android, WebGL on desktop.</td></tr>
+ <tr><td><code>create_ar_page</code></td><td>Emit a complete, self-contained HTML page that embeds the studio, configured for the caller's models: ready to commit and publish.</td></tr>
+ </tbody>
+ </table>
+
+ <h2>What a session looks like</h2>
+<pre><code>&gt; Put a mid-century lamp and a potted fern in my living room.
+
+ generate_3d_model { prompt: "a brass mid-century desk lamp" } → lamp.glb
+ search_models { query: "potted plant" } → fern.glb
+ compose_ar_scene { models: [{ src: lamp.glb, x: 0, z: -1.4 },
+ { src: fern.glb, x: 0.9, z: -1.2 }] }
+
+ → https://your-page.example/ar/#s=… (open it on a phone; both objects
+ stand in the room, exactly where they were arranged)</code></pre>
+
+ <h2>Configuration</h2>
+ <table>
+ <thead><tr><th>Environment variable</th><th>Default</th><th>What it changes</th></tr></thead>
+ <tbody>
+ <tr><td><code>AR_STUDIO_PAGE_URL</code></td><td>the hosted demo</td><td>The page <code>compose_ar_scene</code> links to. Set it to your own deployment.</td></tr>
+ <tr><td><code>AR_STUDIO_ASSETS</code></td><td>the free CC0 library</td><td>Catalogue URL <code>search_models</code> searches.</td></tr>
+ <tr><td><code>AR_STUDIO_MCP_ENDPOINT</code></td><td>three.ws 3D Studio</td><td>The MCP endpoint used for generation.</td></tr>
+ <tr><td><code>AR_STUDIO_ORIGIN</code></td><td><code>https://three.ws</code></td><td>Origin for the hosted "View in your space" launcher and viewer links.</td></tr>
+ </tbody>
+ </table>
+ <p style="margin-top:24px"><a class="btn primary" href="./studio.html">See what it builds</a>
+ <a class="btn" href="https://github.com/nirholas/3D-AR-Studio#mcp-server">Full MCP docs</a></p>
+</section>
+`;
+}
diff --git a/packages/ar-studio/src/anim/animation-arm-relax.js b/packages/ar-studio/src/anim/animation-arm-relax.js
new file mode 100644
index 000000000..6ab7f519a
--- /dev/null
+++ b/packages/ar-studio/src/anim/animation-arm-relax.js
@@ -0,0 +1,137 @@
+// Un-driven arm relaxation: a last-resort guard so an avatar never renders with
+// its arms frozen in the authored T-pose.
+//
+// The canonical idle/walk clips only drive bones the retargeter could name-map
+// (see animation-retarget.js). A correctly-rigged avatar (mixamorig:*
+// arms from workers/rig) maps its whole arm chain, so the idle clip swings the
+// arms naturally and this module never touches it. But a legacy or composite GLB,
+// or an arbitrary GLB a user drops into AR, can carry arm bones under a naming
+// convention the canonicalizer doesn't recognize. The retargeter then DROPS the
+// arm tracks while torso + legs still map (coverage stays above the 0.5 floor), so
+// the clip plays and the body idles while both arms stay stuck out sideways at the
+// authored bind pose. That reads as broken, and CLAUDE.md's avatar rule is explicit:
+// never a bind-pose T-pose.
+//
+// This finds those un-driven arms GEOMETRICALLY (no name needed) and swings each
+// down to a relaxed rest. It is gated hard: it runs ONLY when neither canonical
+// upper-arm bone name-mapped, so a rig whose arms the clip already drives is never
+// touched. Worst case on an already-broken avatar is arms at a slightly imperfect
+// angle instead of a stiff T, which is strictly better. Pure module (three only) so
+// it unit-tests in Node.
+
+import { Quaternion, Vector3 } from 'three';
+
+// A bone counts as "arm-like" when the direction to its child bone is dominated by
+// the lateral (world X) axis and is not steeply vertical, i.e. it sticks out to
+// the side the way a T-posed upper arm does. A clavicle points up-and-out (larger
+// |y|) and is excluded by the vertical cap, so the proximal pick lands on the upper
+// arm itself.
+const LATERAL_DOMINANCE = 0.6; // |dir.x| must exceed this share of the unit length
+const VERTICAL_CAP = 0.38; // |dir.y| above this reads as clavicle/spine, not arm
+const ALREADY_RELAXED_Y = -0.4; // arms already hanging (dir.y below this) are left alone
+
+const _boneWorld = new Vector3();
+const _childWorld = new Vector3();
+const _childDir = new Vector3();
+const _target = new Vector3();
+const _worldDelta = new Quaternion();
+const _boneWorldQ = new Quaternion();
+const _parentWorldQ = new Quaternion();
+
+// First child of `bone` that is itself a bone (the next joint down the chain).
+function firstChildBone(bone) {
+ for (const c of bone.children) {
+ if (c.isBone) return c;
+ }
+ return null;
+}
+
+/**
+ * Swing un-driven arms down to a relaxed rest, in place.
+ *
+ * @param {import('three').Object3D} model the attached avatar root
+ * @param {Map<string,string>} canonicalToNode canonical→node map from the retargeter
+ * @returns {number} how many arms were relaxed (0, 1, or 2)
+ */
+export function relaxUndrivenArms(model, canonicalToNode) {
+ if (!model) return 0;
+ // Gate: if either upper arm name-mapped, the clip drives the arms, so hands off.
+ // (A one-sided map is left alone too: relaxing only one arm would look worse than
+ // a symmetric idle, and the asymmetric case is vanishingly rare.)
+ if (canonicalToNode && (canonicalToNode.has('LeftArm') || canonicalToNode.has('RightArm'))) {
+ return 0;
+ }
+
+ model.updateMatrixWorld(true);
+
+ // Collect every bone that has a child bone, with its world position and the world
+ // direction to that child. One pass; also tracks the vertical mid-point so we can
+ // require arm candidates to sit in the upper body.
+ const bones = [];
+ let minY = Infinity, maxY = -Infinity;
+ model.traverse((node) => {
+ if (!node.isBone) return;
+ const child = firstChildBone(node);
+ if (!child) return;
+ node.getWorldPosition(_boneWorld);
+ child.getWorldPosition(_childWorld);
+ const dir = _childWorld.clone().sub(_boneWorld);
+ const len = dir.length();
+ if (len < 1e-5) return;
+ dir.multiplyScalar(1 / len);
+ const y = _boneWorld.y;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ bones.push({ bone: node, worldY: y, dir });
+ });
+ if (bones.length === 0 || !Number.isFinite(minY) || maxY <= minY) return 0;
+
+ const midY = (minY + maxY) / 2;
+
+ // Arm candidates: lateral-dominant child direction, not steeply vertical, sitting
+ // in the upper half of the rig. Split by which way they point (a T-pose sends the
+ // two arms in opposite X directions), so we relax at most one arm per side.
+ let bestPos = null; // strongest +X-pointing candidate (one arm)
+ let bestNeg = null; // strongest -X-pointing candidate (the other arm)
+ for (const cand of bones) {
+ const { dir, worldY } = cand;
+ if (worldY < midY) continue; // not upper body
+ if (Math.abs(dir.y) > VERTICAL_CAP) continue; // clavicle / spine, not the arm
+ if (dir.y < ALREADY_RELAXED_Y) continue; // already hanging down
+ if (Math.abs(dir.x) < LATERAL_DOMINANCE) continue;
+ if (dir.x > 0) {
+ if (!bestPos || dir.x > bestPos.dir.x) bestPos = cand;
+ } else {
+ if (!bestNeg || dir.x < bestNeg.dir.x) bestNeg = cand;
+ }
+ }
+
+ let relaxed = 0;
+ for (const cand of [bestPos, bestNeg]) {
+ if (cand && relaxArm(cand.bone, cand.dir)) relaxed++;
+ }
+ return relaxed;
+}
+
+// Rotate one arm bone so its child direction swings from wherever it points now
+// (roughly ±X in a T-pose) to a relaxed rest: mostly straight down, biased a touch
+// outward on its own side and a touch forward, so the arm hangs naturally instead
+// of clipping into the torso. Sets the bone's LOCAL quaternion; because the clip
+// never drives this (un-mapped) bone, the mixer leaves the pose in place every frame.
+function relaxArm(bone, childDir) {
+ const side = childDir.x >= 0 ? 1 : -1;
+ _target.set(side * 0.14, -1, 0.1).normalize();
+ _childDir.copy(childDir);
+ _worldDelta.setFromUnitVectors(_childDir, _target);
+
+ bone.getWorldQuaternion(_boneWorldQ);
+ if (bone.parent) bone.parent.getWorldQuaternion(_parentWorldQ);
+ else _parentWorldQ.identity();
+
+ // desiredWorld = worldDelta · boneWorld ; localQ = parentWorld⁻¹ · desiredWorld
+ const desiredWorld = _worldDelta.multiply(_boneWorldQ);
+ const localQ = _parentWorldQ.invert().multiply(desiredWorld);
+ bone.quaternion.copy(localQ);
+ bone.updateMatrixWorld(true);
+ return true;
+}
diff --git a/packages/ar-studio/src/anim/animation-canonical-rest.js b/packages/ar-studio/src/anim/animation-canonical-rest.js
new file mode 100644
index 000000000..2524253fd
--- /dev/null
+++ b/packages/ar-studio/src/anim/animation-canonical-rest.js
@@ -0,0 +1,240 @@
+// GENERATED by scripts/build-canonical-rest.mjs from public/avatars/cz.glb.
+// Do not edit by hand: re-run the generator instead.
+//
+// CANONICAL_REST: each canonical bone's LOCAL rest (bind-pose) quaternion
+// [x,y,z,w] on the Avaturn reference rig the clip library is authored against.
+// CANONICAL_REST_WORLD: the same bones' WORLD (model-space) bind rotations,
+// composed up cz's scene graph. Both feed src/animation-retarget.js's bind
+// correction q' = L·q·R (L = Rt·WT⁻¹·WS·Rs⁻¹, R = WS⁻¹·WT), which replays a
+// clip bone's motion as the SAME world-space delta on a target rig of any rest
+// pose: fixing the ~30° limb skew a local-only premultiply produced on
+// non-cz rigs (A-pose vs T-pose), while still correcting the Hips up-axis
+// convention. Local values are verbatim from cz.glb so retargeting onto cz is
+// identity (L=R=I within FP noise) → byte-for-byte round-trip.
+
+export const CANONICAL_REST = Object.freeze({
+ Head: [-0.11706881878098431, 9.438845082943482e-9, 3.72654613409334e-8, 0.993123804804428],
+ Hips: [0.0010741148761599644, 6.537898515070053e-8, 7.022659074474357e-11, 0.9999994231384476],
+ LeftArm: [-0.003089573263103852, 0.08018148459223169, -0.025041829737156785, 0.9964608827384491],
+ LeftFoot: [0.5523737034239063, 0.0002518875693487157, 0.0036538113016644914, 0.8335885543726441],
+ LeftForeArm: [-2.6826767953574183e-7, 1.2816740072681333e-7, 0.012369379808617674, 0.9999234962951223],
+ LeftHand: [-0.0012910117424963744, 0.002537815819541244, 0.010116448936771993, 0.9999447735952517],
+ LeftHandIndex1: [0.028803290204768833, 0.011362422123976328, 0.055965724298468224, 0.9979524555518633],
+ LeftHandIndex2: [-0.005195237841915152, 0.014315447122751807, 0.00021581682553071412, 0.9998840087229335],
+ LeftHandIndex3: [-0.0013151015878908295, -0.016941197343945148, -0.006458334440614796, 0.9998347644768737],
+ LeftHandMiddle1: [0.027532617383276645, -0.031607746403852485, 0.016931179482824785, 0.9989775976007271],
+ LeftHandMiddle2: [-0.001267981765488788, 0.0010468621884392817, -0.004466175725402764, 0.9999886747239598],
+ LeftHandMiddle3: [-0.0015803533040544947, 0.0018352886876119797, 0.0038040706030556736, 0.9999898315711762],
+ LeftHandPinky1: [0.009345046842530319, -0.07377447953394943, -0.04207784173776388, 0.9963430390695086],
+ LeftHandPinky2: [-0.0019002180814112143, 0.0002770864318134059, 0.0004968185265866393, 0.9999980327809131],
+ LeftHandPinky3: [-0.0014157518824255099, -0.005595319155644295, -0.004606740515194791, 0.9999727326242506],
+ LeftHandRing1: [0.018207541076892743, -0.03436008716699126, -0.036855349348364555, 0.9985637451229231],
+ LeftHandRing2: [-0.0006571286469542868, 0.015477225242721515, 0.01003471962236163, 0.9998296495318929],
+ LeftHandRing3: [0.001815607007583071, -0.003099595768579846, 0.0072046170631637615, 0.999967594260012],
+ LeftHandThumb1: [0.1900227602341495, -0.058826116539083484, 0.3478783626049766, 0.9161940209594684],
+ LeftHandThumb2: [0.01801363066187901, -0.020968588375318502, -0.22063576333056306, 0.9749644544258214],
+ LeftHandThumb3: [-0.014498565873099356, 0.03466160908487025, 0.011599642488048602, 0.9992266072970502],
+ LeftLeg: [-0.022987686472704008, -0.0006608912898930547, 0.00007960712093047862, 0.9997355266049326],
+ LeftShoulder: [0.5181706903502131, 0.5134387363832796, -0.48299308003518876, 0.4843526489955184],
+ LeftToeBase: [0.23652217735689587, 0.0006644108661216591, -0.002051152932444189, 0.9716236982227819],
+ LeftUpLeg: [-0.00004952055077835167, 0.0032567616062252223, 0.9999946186652781, -0.00039203576089550014],
+ Neck: [0.2225107795455935, -2.3352293238692193e-7, -1.9647139012020554e-8, 0.974930229804142],
+ RightArm: [-0.003089570938390283, -0.08018164882954634, 0.025041835809991725, 0.9964608693782484],
+ RightFoot: [0.5523737112340288, -0.00025188760500252676, -0.0036538107149212758, 0.8335885491999105],
+ RightForeArm: [-2.706717415294191e-7, 6.0675494372234465e-9, -0.012369382961452784, 0.9999234962561284],
+ RightHand: [-0.0012910114923260908, -0.002537815924782367, -0.010116450486313036, 0.9999447735796301],
+ RightHandIndex1: [0.028803284769926347, -0.01136242475457741, -0.05596571258489258, 0.9979524563349205],
+ RightHandIndex2: [-0.005195229421057241, -0.014315442233259087, -0.00021582506177354608, 0.9998840088349297],
+ RightHandIndex3: [-0.0013151045827228072, 0.016941319655899355, 0.006458327385746035, 0.9998347624459482],
+ RightHandMiddle1: [0.027532662650122483, 0.03160778647114273, -0.01693120529165708, 0.9989775946478099],
+ RightHandMiddle2: [-0.0012680273836480952, -0.0010469047250576836, 0.004466199390698661, 0.9999886745158897],
+ RightHandMiddle3: [-0.0015803562094451136, -0.001835288773706009, -0.003804068167924464, 0.9999898315756854],
+ RightHandPinky1: [0.009345030274151258, 0.07377446325595405, 0.04207784564870347, 0.9963430402658229],
+ RightHandPinky2: [-0.0019002008217559384, -0.0002769620503994165, -0.0004968229018870381, 0.9999980328459891],
+ RightHandPinky3: [-0.0014157497333212687, 0.0055951881780210025, 0.004606743315319843, 0.9999727333471813],
+ RightHandRing1: [0.01820754441109714, 0.03436008722907556, 0.03685535429214536, 0.9985637448787448],
+ RightHandRing2: [-0.0006571335802527884, -0.015477230302375519, -0.010034723368684675, 0.999829649412505],
+ RightHandRing3: [0.0018156069598940002, 0.003099598646436032, -0.007204626788931167, 0.9999675941811231],
+ RightHandThumb1: [0.19002276085311107, 0.05882618704962336, -0.3478783387552461, 0.9161940229953188],
+ RightHandThumb2: [0.018013663274561078, 0.020968550782212388, 0.22063584956274163, 0.9749644350943654],
+ RightHandThumb3: [-0.014498582331377526, -0.03466161961137741, -0.011599713293476643, 0.9992266058762234],
+ RightLeg: [-0.022987685898989207, 0.0006609402907891899, -0.00007960698692017099, 0.9997355265857409],
+ RightShoulder: [0.5181706006117709, -0.5134387953473804, 0.4829931766210871, 0.4843525890882128],
+ RightToeBase: [0.23652222014073046, -0.0006644109035597298, 0.0020511526077556528, 0.9716236878087238],
+ RightUpLeg: [0.000049438593286575395, 0.003256759408127677, 0.9999946186765544, 0.0003920356017771739],
+ Spine: [-0.018332562694809717, -1.4544833124647894e-7, 2.6976261645093277e-10, 0.9998319444511763],
+ Spine1: [-0.03815628571181615, 2.0010687323521798e-8, 5.34807122500512e-9, 0.9992717837809081],
+ Spine2: [-0.056998031890724846, 1.3546308636882866e-7, -8.861325315468363e-10, 0.9983742907149431],
+});
+
+export const CANONICAL_REST_WORLD = Object.freeze({
+ Head: [-0.005402766806732544, -1.5440620455356296e-7, 8.34223242528311e-10, 0.9999854049488961],
+ Hips: [0.0010741148761599644, 6.537898515070053e-8, 7.022659074474357e-11, 0.9999994231384476],
+ LeftArm: [0.4889318420664182, 0.5108287295941205, -0.5108290884863605, 0.48893078190839623],
+ LeftFoot: [-0.00007112359875637768, 0.5349085331963127, 0.8448985998862468, -0.004383145577274271],
+ LeftForeArm: [0.49521300584988104, 0.5047420653526237, -0.5047420379230214, 0.4952120815979495],
+ LeftHand: [0.5009334720626235, 0.5016127781291206, -0.4977959877649929, 0.49964931327533474],
+ LeftHandIndex1: [0.5480286232738694, 0.46388966319384123, -0.47756977349452234, 0.506357703809076],
+ LeftHandIndex2: [0.5522711480640051, 0.4734474077351049, -0.46714980714345783, 0.5026083894226862],
+ LeftHandIndex3: [0.5405471533897316, 0.46903549072233974, -0.4790521335412708, 0.5082553896043159],
+ LeftHandMiddle1: [0.5069366564823887, 0.46312011824587895, -0.5184714785961669, 0.5096295836965867],
+ LeftHandMiddle2: [0.5047591066222094, 0.46656986579426646, -0.5196237813564338, 0.5074661907650336],
+ LeftHandMiddle3: [0.5066805225023663, 0.46639751835165716, -0.5160243364733309, 0.509379123507728],
+ LeftHandPinky1: [0.4459394011607033, 0.4793433042957962, -0.5586434331057456, 0.5092009093395086],
+ LeftHandPinky2: [0.4453638702749085, 0.48032344738196137, -0.5573549331147079, 0.5101920146245817],
+ LeftHandPinky3: [0.4392981168466072, 0.4802964151504903, -0.5615019919023976, 0.5109286011992389],
+ LeftHandRing1: [0.47371996160924823, 0.4931227775910745, -0.5418410288696247, 0.4886999364902444],
+ LeftHandRing2: [0.48665266892609377, 0.49620490515614146, -0.5291888435031511, 0.48673303168821197],
+ LeftHandRing3: [0.48945530931580683, 0.4902132045285772, -0.5280743092981476, 0.4911843263440915],
+ LeftHandThumb1: [0.6991138207882592, 0.16132571576360077, -0.40704633814367386, 0.5652673372230799],
+ LeftHandThumb2: [0.64766423234777, 0.2923511094450446, -0.5391393932239583, 0.4520957758831027],
+ LeftHandThumb3: [0.6626872004096495, 0.3080994487427915, -0.5067905211225114, 0.45725679518685386],
+ LeftLeg: [0.0006202111480182034, -0.020805293540463354, 0.9997832430476497, -0.00047118992773536965],
+ LeftShoulder: [0.4605450937998788, 0.4559956590278878, -0.537559006794696, 0.5394409087622226],
+ LeftToeBase: [-0.002764355526654178, 0.7195640056310856, 0.6944147145329627, -0.0028643286082629046],
+ LeftUpLeg: [-0.00004987623525000119, 0.0021826506059020026, 0.9999975399461294, -0.00039198262713485737],
+ Neck: [0.11170149382802401, -1.628868597421303e-7, -1.8309282630496044e-8, 0.9937418056399563],
+ RightArm: [0.48893190585215524, -0.510828798312402, 0.5108290283825504, 0.48893071200502375],
+ RightFoot: [0.00007112360405196955, 0.5349085398019146, 0.844898595705669, 0.004383145306035045],
+ RightForeArm: [0.4952130023257164, -0.5047420673116668, 0.5047420415306929, 0.49521208229448166],
+ RightHand: [0.5009334695181179, -0.5016127792807403, 0.49779599067075153, 0.49964931459617906],
+ RightHandIndex1: [0.5480286139806538, -0.4638896746971551, 0.47756977858103167, 0.5063577013132781],
+ RightHandIndex2: [0.5522711446711094, -0.4734474082706649, 0.4671498147721218, 0.5026083883587248],
+ RightHandIndex3: [0.5405470934413514, -0.4690354263302402, 0.47905220274050364, 0.5082554503330304],
+ RightHandMiddle1: [0.5069366680435416, -0.4631200623546733, 0.5184715098400317, 0.5096295939664325],
+ RightHandMiddle2: [0.5047591061928465, -0.46656986723577604, 0.5196237819671778, 0.5074661920185282],
+ RightHandMiddle3: [0.5066805195140975, -0.4663975225827095, 0.5160243369168757, 0.5093791249234989],
+ RightHandPinky1: [0.44593939683725603, -0.4793433241517071, 0.5586434219640141, 0.5092009094272859],
+ RightHandPinky2: [0.4453638073881448, -0.4803233923217868, 0.5573549834847424, 0.5101920690951159],
+ RightHandPinky3: [0.4392981269307416, -0.4802964267888911, 0.5615019867791732, 0.5109285899785551],
+ RightHandRing1: [0.473719957983008, -0.49312277921221886, 0.541841035805614, 0.4886999335659278],
+ RightHandRing2: [0.48665266754747677, -0.4962049100848307, 0.5291888437972645, 0.4867330306200585],
+ RightHandRing3: [0.4894553112113337, -0.49021320332208906, 0.5280743062058759, 0.4911843318554558],
+ RightHandThumb1: [0.6991137732035737, -0.16132569450370315, 0.40704638897707807, 0.5652673641991798],
+ RightHandThumb2: [0.6476641963757893, -0.2923511418798965, 0.5391394672107036, 0.45209571648691005],
+ RightHandThumb3: [0.6626871862817486, -0.3080994479425299, 0.5067905521115058, 0.4572567801626834],
+ RightLeg: [-0.0006202113471683521, -0.020805295090456907, 0.9997832430151556, 0.00047119017271936915],
+ RightShoulder: [0.46054507521936333, -0.45599564278848104, 0.5375590232993736, 0.5394409245169026],
+ RightToeBase: [0.0027643555231566678, 0.7195640416379069, 0.6944146772223956, 0.0028643286020973192],
+ RightUpLeg: [0.000049925034443819034, 0.002182648459062353, 0.9999975399486299, 0.00039198198974856475],
+ Spine: [-0.017258617754264162, -8.00818266828763e-8, 1.3823133775055108e-9, 0.9998510589648868],
+ Spine1: [-0.055396652424023016, -5.997624651397324e-8, 3.32759956947242e-9, 0.9984644264570511],
+ Spine2: [-0.11221710079276989, 7.513757486198981e-8, -8.485311473269302e-9, 0.9936837134066652],
+});
+
+// CANONICAL_REST_POSITION: each bone's WORLD (model-space) bind position in
+// metres, and CANONICAL_PARENT: its nearest canonical ancestor. Together with
+// the rotations above they describe the reference skeleton completely enough to
+// run forward and inverse kinematics in plain JS (src/sign-rig.js), which is how
+// the signing lane authors poses by anatomical target instead of by hand-tuned
+// joint angles.
+
+export const CANONICAL_REST_POSITION = Object.freeze({
+ Head: [0, 1.644459, -0.02811],
+ Hips: [0, 0.984089, 0.005022],
+ LeftArm: [0.204124, 1.50826, -0.034115],
+ LeftFoot: [0.095793, 0.088025, -0.010018],
+ LeftForeArm: [0.458234, 1.508259, -0.045252],
+ LeftHand: [0.725837, 1.508259, -0.050352],
+ LeftHandIndex1: [0.815413, 1.499602, -0.024435],
+ LeftHandIndex2: [0.847794, 1.497747, -0.020782],
+ LeftHandIndex3: [0.872293, 1.496601, -0.017998],
+ LeftHandMiddle1: [0.820067, 1.500491, -0.048839],
+ LeftHandMiddle2: [0.854745, 1.498698, -0.047572],
+ LeftHandMiddle3: [0.881683, 1.49736, -0.046832],
+ LeftHandPinky1: [0.810112, 1.495569, -0.08743],
+ LeftHandPinky2: [0.8359, 1.495002, -0.089537],
+ LeftHandPinky3: [0.856018, 1.494638, -0.091171],
+ LeftHandRing1: [0.81666, 1.499944, -0.069059],
+ LeftHandRing2: [0.850313, 1.498728, -0.071468],
+ LeftHandRing3: [0.87354, 1.497943, -0.072665],
+ LeftHandThumb1: [0.761831, 1.487283, -0.024616],
+ LeftHandThumb2: [0.783931, 1.477329, -0.003377],
+ LeftHandThumb3: [0.806009, 1.466616, 0.003515],
+ LeftLeg: [0.09541, 0.505427, 0.007362],
+ LeftShoulder: [0.056656, 1.508576, -0.035092],
+ LeftToeBase: [0.096919, 0.022281, 0.128921],
+ LeftUpLeg: [0.095072, 0.936186, 0.005482],
+ Neck: [0, 1.516499, -0.057245],
+ RightArm: [-0.204124, 1.50826, -0.034115],
+ RightFoot: [-0.095793, 0.088025, -0.010018],
+ RightForeArm: [-0.458234, 1.508259, -0.045252],
+ RightHand: [-0.725837, 1.508259, -0.050352],
+ RightHandIndex1: [-0.815413, 1.499602, -0.024435],
+ RightHandIndex2: [-0.847794, 1.497747, -0.020783],
+ RightHandIndex3: [-0.872293, 1.496601, -0.017998],
+ RightHandMiddle1: [-0.820067, 1.500491, -0.048839],
+ RightHandMiddle2: [-0.854745, 1.498698, -0.047572],
+ RightHandMiddle3: [-0.881683, 1.49736, -0.046832],
+ RightHandPinky1: [-0.810112, 1.495569, -0.08743],
+ RightHandPinky2: [-0.8359, 1.495002, -0.089537],
+ RightHandPinky3: [-0.856018, 1.494638, -0.091171],
+ RightHandRing1: [-0.81666, 1.499944, -0.069059],
+ RightHandRing2: [-0.850313, 1.498729, -0.071468],
+ RightHandRing3: [-0.87354, 1.497943, -0.072665],
+ RightHandThumb1: [-0.761831, 1.487283, -0.024615],
+ RightHandThumb2: [-0.783931, 1.477329, -0.003377],
+ RightHandThumb3: [-0.806009, 1.466616, 0.003515],
+ RightLeg: [-0.09541, 0.505427, 0.007362],
+ RightShoulder: [-0.056656, 1.508576, -0.035092],
+ RightToeBase: [-0.096919, 0.022281, 0.128921],
+ RightUpLeg: [-0.095072, 0.936186, 0.005482],
+ Spine: [0, 1.077013, 0.005222],
+ Spine1: [0, 1.184494, 0.00151],
+ Spine2: [0, 1.330917, -0.014788],
+});
+
+export const CANONICAL_PARENT = Object.freeze({
+ Head: 'Neck',
+ Hips: null,
+ LeftArm: 'LeftShoulder',
+ LeftFoot: 'LeftLeg',
+ LeftForeArm: 'LeftArm',
+ LeftHand: 'LeftForeArm',
+ LeftHandIndex1: 'LeftHand',
+ LeftHandIndex2: 'LeftHandIndex1',
+ LeftHandIndex3: 'LeftHandIndex2',
+ LeftHandMiddle1: 'LeftHand',
+ LeftHandMiddle2: 'LeftHandMiddle1',
+ LeftHandMiddle3: 'LeftHandMiddle2',
+ LeftHandPinky1: 'LeftHand',
+ LeftHandPinky2: 'LeftHandPinky1',
+ LeftHandPinky3: 'LeftHandPinky2',
+ LeftHandRing1: 'LeftHand',
+ LeftHandRing2: 'LeftHandRing1',
+ LeftHandRing3: 'LeftHandRing2',
+ LeftHandThumb1: 'LeftHand',
+ LeftHandThumb2: 'LeftHandThumb1',
+ LeftHandThumb3: 'LeftHandThumb2',
+ LeftLeg: 'LeftUpLeg',
+ LeftShoulder: 'Spine2',
+ LeftToeBase: 'LeftFoot',
+ LeftUpLeg: 'Hips',
+ Neck: 'Spine2',
+ RightArm: 'RightShoulder',
+ RightFoot: 'RightLeg',
+ RightForeArm: 'RightArm',
+ RightHand: 'RightForeArm',
+ RightHandIndex1: 'RightHand',
+ RightHandIndex2: 'RightHandIndex1',
+ RightHandIndex3: 'RightHandIndex2',
+ RightHandMiddle1: 'RightHand',
+ RightHandMiddle2: 'RightHandMiddle1',
+ RightHandMiddle3: 'RightHandMiddle2',
+ RightHandPinky1: 'RightHand',
+ RightHandPinky2: 'RightHandPinky1',
+ RightHandPinky3: 'RightHandPinky2',
+ RightHandRing1: 'RightHand',
+ RightHandRing2: 'RightHandRing1',
+ RightHandRing3: 'RightHandRing2',
+ RightHandThumb1: 'RightHand',
+ RightHandThumb2: 'RightHandThumb1',
+ RightHandThumb3: 'RightHandThumb2',
+ RightLeg: 'RightUpLeg',
+ RightShoulder: 'Spine2',
+ RightToeBase: 'RightFoot',
+ RightUpLeg: 'Hips',
+ Spine: 'Hips',
+ Spine1: 'Spine',
+ Spine2: 'Spine1',
+});
diff --git a/packages/ar-studio/src/anim/animation-manager.js b/packages/ar-studio/src/anim/animation-manager.js
new file mode 100644
index 000000000..9e660580c
--- /dev/null
+++ b/packages/ar-studio/src/anim/animation-manager.js
@@ -0,0 +1,997 @@
+import {
+ AdditiveAnimationBlendMode,
+ AnimationClip,
+ AnimationMixer,
+ AnimationUtils,
+ LoopRepeat,
+ LoopOnce,
+ Quaternion,
+ Vector3,
+} from 'three';
+import { canonicalizeBoneName } from './glb-canonicalize.js';
+import {
+ canonicalNodeMapFromObject,
+ canonicalRestMapFromObject,
+ canonicalWorldRestMapFromObject,
+ clipHipBaselineY,
+ hipGroundLocalY,
+ hipRestLocalHeight,
+ hipsParentWorldQuat,
+ morphTargetMapFromObject,
+ retargetClip,
+} from './animation-retarget.js';
+import { relaxUndrivenArms } from './animation-arm-relax.js';
+import { log } from '../log.js';
+
+// Past this many degrees off vertical, the rig's Hips have tipped onto their
+// back: the catastrophic "lying down" retarget failure. The bind-correction in
+// animation-retarget.js keeps every healthy rig's at-rest Hips under ~18°
+// (measured across cz + michelle × the featured clips, locked in
+// verified against the upright invariant), so 45° is a generous catastrophe
+// floor that only ever trips a genuinely broken retarget, never a healthy one
+// (dance, the most hip-led clip, peaks at ~30° mid-clip but rests near 18°).
+const CATASTROPHE_TILT_DEG = 45;
+
+// Reused scratch so the guard's once-per-clip measurement allocates nothing.
+const _worldUp = new Vector3();
+const _wq = new Quaternion();
+const _UP = new Vector3(0, 1, 0);
+
+/**
+ * At-rest Hips tilt (degrees off world vertical) a retargeted clip would impose
+ * on a model: the same world-matrix reconstruction the lying-down bug was
+ * diagnosed with, but evaluated from the clip's first Hips keyframe so it costs
+ * nothing per frame. Sets the Hips bone to the clip's keyframe-0 rotation,
+ * composes world matrices, and measures the angle between the bone's world
+ * up-axis and vertical. Restores the bone afterwards so it's side-effect free.
+ * Returns null when there's nothing to measure (no Hips, no quaternion track),
+ * which callers treat as "can't assess": never as a failure.
+ *
+ * @param {THREE.AnimationClip|null} retargetedClip clip already renamed to the rig's nodes
+ * @param {THREE.Object3D|null} model the attached rig (world matrices may be stale)
+ * @param {Map<string,string>|null} canonicalToNode canonical bone → rig node name
+ * @returns {number|null} degrees off vertical, or null
+ */
+export function measureHipsTiltDeg(retargetedClip, model, canonicalToNode) {
+ if (!retargetedClip || !model || !canonicalToNode) return null;
+ const hipsName = canonicalToNode.get('Hips');
+ if (!hipsName) return null;
+ const hips = model.getObjectByName(hipsName);
+ if (!hips) return null;
+ const qTrack = retargetedClip.tracks.find((t) => t.name === `${hipsName}.quaternion`);
+ if (!qTrack || qTrack.values.length < 4) return null;
+
+ const v = qTrack.values;
+ const restX = hips.quaternion.x;
+ const restY = hips.quaternion.y;
+ const restZ = hips.quaternion.z;
+ const restW = hips.quaternion.w;
+
+ hips.quaternion.set(v[0], v[1], v[2], v[3]);
+ hips.updateWorldMatrix(true, false);
+ hips.getWorldQuaternion(_wq);
+ _worldUp.copy(_UP).applyQuaternion(_wq);
+
+ // Restore the authored rest so the measurement leaves no trace; the mixer
+ // drives the real pose from here on.
+ hips.quaternion.set(restX, restY, restZ, restW);
+ hips.updateWorldMatrix(true, false);
+
+ const dot = Math.max(-1, Math.min(1, _worldUp.dot(_UP)));
+ return (Math.acos(dot) * 180) / Math.PI;
+}
+
+// Minimum number of canonical bones a skinned model must expose before the
+// pre-baked clip library can drive it meaningfully. The clips address tracks by
+// canonical Avaturn bone names; a model sharing only a stray bone or two would
+// twitch a single joint rather than perform the motion. Eight covers the torso
+// + a limb, which is enough to read as a real humanoid performance.
+const MIN_CANONICAL_BONES = 8;
+
+// Canonical bones that belong to the lower body. When a gesture plays as an
+// upper-body overlay (so the avatar can wave while it keeps walking), every
+// track addressing one of these bones is stripped from the additive clip: the
+// base locomotion layer owns the hips, legs, and feet; the overlay only adds
+// motion to the spine, arms, neck, and head. Hips is included so the overlay
+// never fights the walk cycle's root sway.
+const LOWER_BODY_CANONICAL = Object.freeze([
+ 'Hips',
+ 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase',
+ 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase',
+]);
+
+/**
+ * Manages pre-baked animation clips for skinned agents.
+ *
+ * Clips are authored at build time (scripts/build-animations.mjs):
+ * - Mixamo FBX → retargeted to canonical Avaturn skeleton → JSON
+ * - No FBXLoader or retargeting in the browser; just fetch + parse.
+ *
+ * Usage:
+ * const mgr = new AnimationManager();
+ * mgr.attach(skinnedModel);
+ * await mgr.loadAll(); // reads manifest, fetches clips lazily on first play
+ * mgr.play('idle');
+ * mgr.crossfadeTo('dance', 0.4);
+ */
+
+const DEFAULT_CROSSFADE = 0.35; // seconds
+
+// Module-level cache of parsed base clips, keyed by URL. A world scene builds
+// dozens of AnimationManagers (local player, remote players, NPCs, pedestrians)
+// and every one of them used to re-fetch and re-parse the same clip JSON:
+// megabytes of JSON and thousands of AnimationClip.parse calls per world entry.
+// The base clip is never mutated (_retarget reads it and emits a new bound
+// clip), so one parsed instance can back every rig. The cache stores the
+// in-flight promise so concurrent loaders coalesce into a single fetch; a
+// failed load is evicted so a retry can succeed.
+const _clipCache = new Map();
+
+export class AnimationManager {
+ constructor() {
+ /** @type {THREE.Object3D|null} */
+ this.model = null;
+ /** @type {AnimationMixer|null} */
+ this.mixer = null;
+ /** @type {Map<string, THREE.AnimationClip>} */
+ this.clips = new Map();
+ /** @type {Map<string, THREE.AnimationAction>} */
+ this.actions = new Map();
+ /** @type {string|null} */
+ this.currentName = null;
+ /** @type {THREE.AnimationAction|null} */
+ this.currentAction = null;
+ /** @type {Function|null} Fired with the new clip name (or null) on every change. */
+ this.onChange = null;
+ /** @type {Array<{name:string, url:string, label:string, icon:string, loop:boolean}>} */
+ this._animationDefs = [];
+ /** @type {Set<string>} Clip names that failed to load: buttons grayed out in UI. */
+ this._failed = new Set();
+ /** @type {Map<string,string>|null} canonical bone → actual node name on the attached model. */
+ this._canonicalToNode = null;
+ /** @type {boolean} Whether the attached model's rig can play the canonical clip library. */
+ this._canonicalClipsSupported = false;
+ /** @type {{ avatarId?: string, avatarUrl?: string }} Context for the fallen-pose guard's reports. */
+ this._avatarContext = {};
+ /** @type {Set<string>} `${avatarUrl}|${clip}` keys whose fallen-pose has already been reported (debounce). */
+ this._fallenReported = new Set();
+ /** @type {Set<string>} Clip names disabled because they retargeted to a fallen pose on this rig. */
+ this._fallen = new Set();
+ /** @type {string|null} Name of the most-recently-requested crossfade target. Used to cancel stale async requests. */
+ this._latestCrossfadeTarget = null;
+ /** @type {THREE.AnimationAction|null} The additive upper-body overlay action (gesture-over-walk), if any. */
+ this.overlayAction = null;
+ /** @type {string|null} Name of the active overlay gesture clip. */
+ this.overlayName = null;
+ /** @type {Map<string, THREE.AnimationClip>} Cache of built additive overlay clips, keyed by `${name}|${upperBodyOnly}`. */
+ this._overlayClips = new Map();
+ /** @type {Function|null} mixer 'finished' listener for the current one-shot overlay. */
+ this._overlayFinishHandler = null;
+ /** @type {Function|null} mixer 'finished' listener for the settle-to-idle after a playOnce. */
+ this._settleFinishHandler = null;
+ }
+
+ /**
+ * Tell the manager which avatar is attached so the fallen-pose guard can
+ * report actionable context. Both fields are optional; url alone is enough.
+ * @param {{ avatarId?: string, avatarUrl?: string }} ctx
+ */
+ setAvatarContext(ctx) {
+ this._avatarContext = ctx && typeof ctx === 'object' ? { ...ctx } : {};
+ }
+
+ // ── Model binding ──────────────────────────────────────────────────────────
+
+ /**
+ * Attach to a loaded model. Call this every time a new model is loaded.
+ * Re-creates actions for any clips that are already in memory.
+ * @param {THREE.Object3D} model
+ * @param {{ avatarId?: string, avatarUrl?: string }} [context] avatar id/url for the fallen-pose guard
+ */
+ attach(model, context) {
+ this.detach();
+ if (context) this.setAvatarContext(context);
+ this.model = model;
+ this.mixer = new AnimationMixer(model);
+ this.actions.clear();
+ this.currentAction = null;
+ this.currentName = null;
+ this._fallen.clear();
+ // Build the canonical→node map once. Every clip is retargeted through it,
+ // so the library drives ANY humanoid rig: Mixamo, VRM-via-Mixamo,
+ // CharacterStudio, Blender: not just an already-canonical Avaturn rig.
+ this._canonicalToNode = canonicalNodeMapFromObject(model);
+ // Captured here, while the model is still in its authored bind pose, so
+ // the retargeter can re-express each clip in the rig's own rest frame
+ // (a Mixamo rig bakes the up-axis as a −90°X Hips rest the clips would
+ // otherwise overwrite, tipping the avatar onto its back).
+ this._canonicalRest = canonicalRestMapFromObject(model);
+ // World-frame companion to _canonicalRest, captured in the same bind pose.
+ // Supplying it lets the retargeter use the world-delta-preserving correction
+ // (L = Rt·WT⁻¹·WS·Rs⁻¹) instead of the local-only premultiply fallback, which
+ // skews an A-pose clip's limbs ~30° on a T-pose rig. Matches the server
+ // (retargetClipToObject) and rig (retargetClipToRig) paths.
+ this._canonicalWorldRest = canonicalWorldRestMapFromObject(model);
+ // World rotation of the Hips' parent (within the model), so root motion is
+ // re-expressed in the rig's own frame and travels the right way on any rig.
+ this._hipsParentWorldQuat = hipsParentWorldQuat(model);
+ // Blendshapes this avatar carries, so a clip's face lanes (the non-manual
+ // markers a signed question needs) can be re-pointed at its own meshes. An
+ // avatar with no face shapes simply gets no face lanes.
+ this._morphTargets = morphTargetMapFromObject(model);
+ // Rest height of the Hips in the parent's local units (metres for a
+ // metre-native rig, ~100 for a centimetre-scale Mixamo armature). Hip
+ // tracks set the Hips' *local* position, so _retarget scales each clip by
+ // this ÷ the clip's authored baseline: without it a 0.01-scaled rig's
+ // hips collapse to the floor (metre-valued track × 0.01 parent ≈ 1cm).
+ this._hipTargetLocalY = hipRestLocalHeight(model);
+ // Where this rig's floor sits in the hips-parent's local frame (0 for a
+ // ground-native export). The retarget adds it to the hip track so the
+ // clip's ground lands on the model's actual ground.
+ this._hipGroundLocalY = hipGroundLocalY(model);
+ this._canonicalClipsSupported = _modelSupportsCanonicalClips(model);
+
+ for (const [name, clip] of this.clips) {
+ const bound = this._retarget(clip);
+ if (!bound) continue;
+ const action = this.mixer.clipAction(bound);
+ action.enabled = true;
+ this.actions.set(name, action);
+ }
+ }
+
+ /**
+ * Re-measure the height-dependent retarget inputs and rebuild every bound
+ * action. Call after a skeleton-space proportion edit (leg length, stature,
+ * foot size: see src/avatar-proportions.js) has moved the rig's hips.
+ *
+ * A clip's hip translation is authored around one hip height and rescaled
+ * onto the rig's actual height at attach time. Lengthen the legs and that
+ * factor is stale: the root travels the old distance while longer legs cover
+ * more ground per stride, and the avatar foot-slides. Re-measuring and
+ * re-retargeting fixes the stride without re-attaching, which matters because
+ * attach() also re-captures the rest frames: and those must be read in the
+ * bind pose, which a mid-animation rig is not in.
+ *
+ * Safe precisely because proportions never touch bone *rotations*: the
+ * captured local/world rest rotations, the canonical→node map and the morph
+ * map all stay valid. The caller must have the rig at rest when it calls
+ * (applyProportionsToRoot leaves it there).
+ *
+ * @returns {boolean} true when the rig was re-measured
+ */
+ remeasureRigProportions() {
+ if (!this.model || !this.mixer) return false;
+ const resume = this.currentName;
+ this._hipTargetLocalY = hipRestLocalHeight(this.model);
+ this._hipGroundLocalY = hipGroundLocalY(this.model);
+
+ this.mixer.stopAllAction();
+ for (const action of this.actions.values()) {
+ const clip = action.getClip?.();
+ if (clip) this.mixer.uncacheClip(clip);
+ }
+ this.actions.clear();
+ this.currentAction = null;
+ this.currentName = null;
+ this._latestCrossfadeTarget = null;
+ // Overlays are built from the old retarget too, so drop the cache and let
+ // the next gesture rebuild against the new proportions.
+ this.overlayAction = null;
+ this.overlayName = null;
+ this._overlayClips.clear();
+ this._detachOverlayFinish?.();
+
+ for (const [name, clip] of this.clips) {
+ const bound = this._retarget(clip);
+ if (!bound) continue;
+ const action = this.mixer.clipAction(bound);
+ action.enabled = true;
+ this.actions.set(name, action);
+ }
+ if (resume && this.actions.has(resume)) this.play(resume);
+ return true;
+ }
+
+ /**
+ * Retarget a canonical-skeleton library clip onto the attached model's actual
+ * bone names. Returns null when the rig shares too few bones to perform the
+ * motion (a static prop, a non-humanoid rig), so callers skip building a dead
+ * action. A clip whose tracks already match the rig 1:1 round-trips unchanged.
+ * @param {THREE.AnimationClip} clip
+ * @returns {THREE.AnimationClip|null}
+ */
+ _retarget(clip) {
+ if (!this._canonicalToNode || this._canonicalToNode.size === 0) return null;
+ // Scale the clip's hip translation into the rig's local frame. For a
+ // metre-native rig this is ≈1 (no-op); for a centimetre-scale armature it
+ // is ~100, which is what keeps the dancer standing on the stage instead of
+ // sinking a metre through it. Clamped so a degenerate baseline can't fling
+ // the root away.
+ let hipScale = 1;
+ const baseline = clipHipBaselineY(clip);
+ if (this._hipTargetLocalY > 0.05 && baseline > 0.05) {
+ hipScale = Math.min(200, Math.max(0.2, this._hipTargetLocalY / baseline));
+ }
+ const { clip: out } = retargetClip(clip, this._canonicalToNode, {
+ targetRest: this._canonicalRest,
+ targetWorldRest: this._canonicalWorldRest,
+ hipsParentWorldQuat: this._hipsParentWorldQuat,
+ morphTargets: this._morphTargets,
+ hipScale,
+ hipOffsetY: this._hipGroundLocalY || 0,
+ });
+ return out;
+ }
+
+ /**
+ * Runtime "fallen pose" guard. Before an action plays, sample the at-rest Hips
+ * world up-axis the retargeted clip would impose. If it tips past
+ * CATASTROPHE_TILT_DEG the retarget failed (the rig would lie on its back), so
+ * we disable that action, leave the rig in its authored bind pose: the same
+ * fallback the viewer already prefers over a broken retarget: and report once
+ * through the existing client-error channel with enough context to diagnose.
+ * Sampled once per (avatar, clip), never per frame.
+ *
+ * @param {string} name clip name
+ * @param {THREE.AnimationAction} action
+ * @returns {boolean} true if the clip is safe to play; false if it was rejected
+ */
+ _guardAgainstFallenPose(name, action) {
+ if (this._fallen.has(name)) return false;
+ const clip = action?.getClip?.();
+ const tiltDeg = measureHipsTiltDeg(clip, this.model, this._canonicalToNode);
+ // NaN means the measurement couldn't complete (degenerate world matrix, missing
+ // bone quaternion, etc.): treat as safe rather than incorrectly flagging the
+ // clip as fallen. NaN comparisons are always false, so without this check a NaN
+ // would fall through the guard and falsely reject the clip.
+ if (tiltDeg == null || !Number.isFinite(tiltDeg) || tiltDeg <= CATASTROPHE_TILT_DEG) return true;
+
+ // Reject: stop and disable the action, drop it so it can't be selected
+ // again, and fall back to the authored bind pose (do not play the broken
+ // clip). If it was the current action, clear playback state.
+ try {
+ action.stop();
+ } catch (e) {
+ log.warn('[AnimationManager] failed to stop fallen-pose action:', e);
+ }
+ action.enabled = false;
+ this.actions.delete(name);
+ this._fallen.add(name);
+ if (this.currentAction === action) {
+ this.currentAction = null;
+ this.currentName = null;
+ }
+
+ const avatarUrl = this._avatarContext.avatarUrl || '';
+ const avatarId = this._avatarContext.avatarId || '';
+ const dedupeKey = `${avatarId || avatarUrl}|${name}`;
+ if (!this._fallenReported.has(dedupeKey)) {
+ this._fallenReported.add(dedupeKey);
+ log.warn(
+ `[AnimationManager] "${name}" retargeted to a fallen pose (${tiltDeg.toFixed(1)}° off vertical): falling back to bind pose`,
+ );
+ reportFallenPose({
+ avatarId,
+ avatarUrl,
+ clip: name,
+ tiltDeg: Math.round(tiltDeg * 10) / 10,
+ });
+ }
+ return false;
+ }
+
+ /** Detach, stop all actions, dispose mixer. */
+ detach() {
+ if (this.mixer) {
+ this.mixer.stopAllAction();
+ this.mixer.uncacheRoot(this.mixer.getRoot());
+ this.mixer = null;
+ }
+ this.model = null;
+ this._canonicalToNode = null;
+ this._canonicalRest = null;
+ this._canonicalWorldRest = null;
+ this._hipsParentWorldQuat = null;
+ this._morphTargets = null;
+ this._hipTargetLocalY = 0;
+ this._hipGroundLocalY = 0;
+ this._canonicalClipsSupported = false;
+ this.actions.clear();
+ this.currentAction = null;
+ this.currentName = null;
+ this._latestCrossfadeTarget = null;
+ this._fallen.clear();
+ // Overlay clips are retargeted to the (now-gone) model's bones: drop them
+ // so a freshly-attached rig rebuilds its own.
+ this.overlayAction = null;
+ this.overlayName = null;
+ this._overlayClips.clear();
+ this._overlayFinishHandler = null;
+ }
+
+ // ── Definitions ────────────────────────────────────────────────────────────
+
+ /**
+ * Register animation definitions (from manifest.json).
+ * @param {Array<{name:string, url:string, label?:string, icon?:string, loop?:boolean}>} defs
+ */
+ setAnimationDefs(defs) {
+ this._animationDefs = defs;
+ }
+
+ /**
+ * Append additional defs (e.g. user/public clips from the API) without
+ * replacing the manifest-sourced ones. Skips defs whose name is already
+ * registered to avoid duplicates when called multiple times.
+ * @param {Array<{name:string, url:string, label?:string, icon?:string, loop?:boolean}>} defs
+ */
+ appendAnimationDefs(defs) {
+ const existing = new Set(this._animationDefs.map((d) => d.name));
+ for (const def of defs) {
+ if (!existing.has(def.name)) {
+ this._animationDefs.push(def);
+ existing.add(def.name);
+ }
+ }
+ }
+
+ /** @returns {Array} */
+ getAnimationDefs() {
+ return this._animationDefs;
+ }
+
+ /** @param {string} name @returns {boolean} */
+ isFailed(name) {
+ return this._failed.has(name);
+ }
+
+ /**
+ * Whether the currently attached model can be driven by the pre-baked
+ * canonical clip library. True only for a skinned humanoid whose skeleton
+ * shares enough bones with the canonical Avaturn rig that a retargeted clip
+ * actually moves it. A static mesh (no skeleton) or a non-humanoid rig
+ * returns false, so callers can hide animation affordances that would
+ * otherwise play to no visible effect.
+ * @returns {boolean}
+ */
+ supportsCanonicalClips() {
+ return this._canonicalClipsSupported;
+ }
+
+ /**
+ * Guard against frozen T-pose arms. When the attached rig's upper-arm bones
+ * could NOT be name-mapped, the retargeted clip drives the torso and legs but
+ * leaves both arms stuck out at the authored bind pose. Swing those un-driven
+ * arms down to a relaxed rest so the avatar never reads as broken. No-op when
+ * the arms name-mapped (the clip already drives them) or no model is attached.
+ * Call once, after attach() and before the first play/crossfade.
+ * @returns {number} arms relaxed (0, 1, or 2)
+ */
+ relaxUndrivenArms() {
+ if (!this.model) return 0;
+ return relaxUndrivenArms(this.model, this._canonicalToNode);
+ }
+
+ /**
+ * Whether a named clip can actually be driven on the attached rig: it's
+ * either already loaded, or registered in the defs and not yet known to
+ * have failed. Lets callers (e.g. the paid club stage) drop un-performable
+ * steps from a routine before playback instead of crossfading to a silent
+ * no-op and leaving the avatar frozen.
+ * @param {string} name
+ * @returns {boolean}
+ */
+ canPlay(name) {
+ // A clip already rejected by the fallen-pose guard must not pass this
+ // filter: it would make club.js route a routine step to it, then silently
+ // no-op the crossfade, leaving the dancer frozen for the full step duration.
+ if (this._fallen.has(name)) return false;
+ if (this.clips.has(name)) return true;
+ if (this._failed.has(name)) return false;
+ return this._animationDefs.some((d) => d.name === name);
+ }
+
+ // ── Loading ────────────────────────────────────────────────────────────────
+
+ /**
+ * Load a single clip from a pre-baked JSON URL and register it.
+ * Idempotent: returns the cached clip if already loaded.
+ *
+ * Handles two response shapes:
+ * - Static clip JSON: { name, duration, tracks } (manifest clips)
+ * - API clip response: { clip: { clip: { name, duration, tracks } } }
+ * (/api/animations/clips/:id: detected by URL containing /api/animations/)
+ *
+ * @param {string} name
+ * @param {string} url URL to a clip JSON or /api/animations/clips/:id endpoint
+ * @param {{ loop?: boolean }} [opts]
+ * @returns {Promise<THREE.AnimationClip>}
+ */
+ async loadAnimation(name, url, opts = {}) {
+ if (this.clips.has(name)) return this.clips.get(name);
+
+ let pending = _clipCache.get(url);
+ if (!pending) {
+ pending = AnimationManager._fetchClip(name, url);
+ _clipCache.set(url, pending);
+ // Evict on failure so a transient network error doesn't poison the URL
+ // for every future rig in the session.
+ pending.catch(() => { if (_clipCache.get(url) === pending) _clipCache.delete(url); });
+ }
+ const clip = await pending;
+ return this._registerParsedClip(name, clip, opts);
+ }
+
+ /** @private Fetch + parse one clip JSON into a shared base AnimationClip. */
+ static async _fetchClip(name, url) {
+ const isApiClip = url.includes('/api/animations/');
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 15_000);
+ let res;
+ try {
+ res = await fetch(url, {
+ signal: controller.signal,
+ // API clips need auth; static clips are same-origin assets. Use
+ // 'same-origin' (not 'omit') so a credential-gated host proxy (e.g.
+ // a private-forwarded Codespaces port) still receives the auth cookie
+ // and serves the asset instead of 302-ing it to a login tunnel.
+ credentials: isApiClip ? 'include' : 'same-origin',
+ redirect: 'error',
+ });
+ } finally {
+ clearTimeout(timeoutId);
+ }
+ if (!res.ok) throw new Error(`HTTP ${res.status} loading animation ${name}`);
+ const json = await res.json();
+ // API responses wrap the baked clip one level deeper.
+ const clipJson = isApiClip ? json?.clip?.clip : json;
+ // A clip listed for sale answers with metadata only. Say so, rather than
+ // letting a paywall read as a corrupt payload.
+ if (!clipJson && json?.clip?.paywalled) {
+ throw new Error(`animation ${name} is a paid clip, unlock it at ${json.clip.download_url}`);
+ }
+ if (!clipJson) throw new Error(`clip payload missing from ${url}`);
+ const clip = AnimationClip.parse(clipJson);
+ clip.name = name;
+ return clip;
+ }
+
+ /**
+ * Register a clip from already-fetched JSON: skips all network I/O.
+ * Useful for callers that pre-fetch clip data alongside other parallel loads
+ * so animations are ready before the first render frame.
+ * @param {string} name
+ * @param {object} clipJson Raw AnimationClip JSON (same shape as the files in /animations/clips/)
+ * @param {{ loop?: boolean }} [opts]
+ */
+ injectClip(name, clipJson, opts = {}) {
+ if (!clipJson || this.clips.has(name)) return;
+ try {
+ const clip = AnimationClip.parse(clipJson);
+ clip.name = name;
+ this._registerParsedClip(name, clip, opts);
+ } catch (err) {
+ log.warn(`[AnimationManager] injectClip "${name}" parse error:`, err.message);
+ }
+ }
+
+ /** @private Shared finalization for both load paths. */
+ _registerParsedClip(name, clip, opts) {
+ this.clips.set(name, clip);
+
+ if (this.model && this.mixer) {
+ const bound = this._retarget(clip);
+ if (bound) {
+ const action = this.mixer.clipAction(bound);
+ action.enabled = true;
+ action.setLoop(opts.loop === false ? LoopOnce : LoopRepeat);
+ if (opts.loop === false) action.clampWhenFinished = true;
+ this.actions.set(name, action);
+ }
+ }
+ return clip;
+ }
+
+ /**
+ * Load all registered definitions in parallel.
+ * Failed clips are logged and added to _failed; they do not throw.
+ */
+ async loadAll() {
+ const CONCURRENCY = 4;
+ const queue = [...this._animationDefs];
+ const worker = async () => {
+ let def;
+ while ((def = queue.shift())) {
+ try {
+ await this.loadAnimation(def.name, def.url, { loop: def.loop !== false });
+ } catch (err) {
+ log.warn(`[AnimationManager] failed to load "${def.name}":`, err.message);
+ this._failed.add(def.name);
+ }
+ }
+ };
+ await Promise.all(Array.from({ length: CONCURRENCY }, worker));
+ }
+
+ /**
+ * Lazily load a single clip by name (from registered defs) if not yet loaded.
+ * Used so the first click on a strip button triggers a load without blocking startup.
+ * @param {string} name
+ * @returns {Promise<boolean>} true if ready
+ */
+ async ensureLoaded(name) {
+ if (this.clips.has(name)) return true;
+ if (this._failed.has(name)) return false;
+ const def = this._animationDefs.find((d) => d.name === name);
+ if (!def) return false;
+ try {
+ await this.loadAnimation(def.name, def.url, { loop: def.loop !== false });
+ return true;
+ } catch {
+ this._failed.add(name);
+ return false;
+ }
+ }
+
+ // ── Playback ───────────────────────────────────────────────────────────────
+
+ /**
+ * Play a named clip immediately (hard cut, no crossfade).
+ * Lazily loads if not yet in memory.
+ * @param {string} name
+ * @returns {Promise<boolean>} true if the clip started playing, false if unavailable or rejected
+ */
+ async play(name) {
+ const ready = await this.ensureLoaded(name);
+ if (!ready) {
+ if (this._failed.has(name) || this._animationDefs.some((d) => d.name === name))
+ log.warn(`[AnimationManager] "${name}" unavailable`);
+ return false;
+ }
+ // Re-check after async load so concurrent play() calls don't all reset
+ // the action's timeline back to 0 once the clip finally resolves.
+ if (name === this.currentName) return true;
+ const action = this.actions.get(name);
+ if (!action) return false;
+ // Reject a retarget that would lie the avatar on its back; fall back to the
+ // authored bind pose rather than play a fallen clip.
+ if (!this._guardAgainstFallenPose(name, action)) return false;
+
+ if (this.currentAction && this.currentAction !== action) {
+ this.currentAction.fadeOut(0.01);
+ }
+ action.reset().fadeIn(0.01).play();
+ this.currentAction = action;
+ this.currentName = name;
+ try { this.onChange?.(name); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }
+ return true;
+ }
+
+ /**
+ * Play a one-shot clip exactly once, then settle into a looping clip
+ * (`idle` by default) with a crossfade: instead of clamping and freezing on
+ * the final frame, which reads as a hard snap on a looping thumbnail. This is
+ * the seamless path for manifest clips whose `loop` field is false
+ * (`celebrate`, `wave`, …). Lazily loads both the one-shot and the settle clip.
+ *
+ * @param {string} name
+ * @param {{ settleTo?: string|null, fade?: number }} [opts]
+ */
+ async playOnce(name, { settleTo = 'idle', fade = DEFAULT_CROSSFADE } = {}) {
+ fade = Math.max(0, Math.min(fade, 5));
+ const ready = await this.ensureLoaded(name);
+ const action = ready ? this.actions.get(name) : null;
+ // Reject a fallen-pose retarget the same way an unavailable clip is handled:
+ // settle into the looping fallback rather than play the broken one-shot.
+ if (!action || !this._guardAgainstFallenPose(name, action)) {
+ // One-shot unavailable on this rig: fall back to the settle clip so
+ // the avatar is never left frozen in its bind pose.
+ if (settleTo) return this.crossfadeTo(settleTo, fade);
+ return;
+ }
+
+ action.reset();
+ action.setLoop(LoopOnce, 1);
+ // Hold the final frame until the settle crossfade picks it up: without
+ // this the action would snap back to frame 0 the instant it completes.
+ action.clampWhenFinished = true;
+ action.play();
+ if (this.currentAction && this.currentAction !== action) {
+ this.currentAction.crossFadeTo(action, fade, true);
+ } else {
+ action.fadeIn(fade);
+ }
+ this.currentAction = action;
+ this.currentName = name;
+
+ // Tear down any previous settle listener before registering a new one so
+ // interrupted one-shots don't accumulate listeners on the mixer.
+ if (this._settleFinishHandler && this.mixer) {
+ this.mixer.removeEventListener('finished', this._settleFinishHandler);
+ this._settleFinishHandler = null;
+ }
+ if (settleTo && this.mixer) {
+ const onFinished = (e) => {
+ if (e.action !== action) return;
+ this.mixer.removeEventListener('finished', onFinished);
+ if (this._settleFinishHandler === onFinished) this._settleFinishHandler = null;
+ // Only settle if nothing else took over the avatar meanwhile.
+ if (this.currentAction === action) this.crossfadeTo(settleTo, fade);
+ };
+ this._settleFinishHandler = onFinished;
+ this.mixer.addEventListener('finished', onFinished);
+ }
+ try { this.onChange?.(name); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }
+ }
+
+ /**
+ * Freeze the active clip on its current pose and release it as the active
+ * action so the host viewer's render loop can settle (it stops scheduling
+ * frames once nothing is animating). The paused action keeps applying its
+ * held pose whenever the mixer does tick again (e.g. on scroll-back-in), so
+ * the avatar shows a clean static pose rather than a T-pose.
+ *
+ * Used for `prefers-reduced-motion`: a calm held pose with no looping motion
+ * and no continuous GPU/CPU cost.
+ */
+ freeze() {
+ if (this.currentAction) this.currentAction.paused = true;
+ this.currentAction = null;
+ this.currentName = null;
+ this._latestCrossfadeTarget = null;
+ }
+
+ /**
+ * Crossfade from the current clip to a named clip.
+ * Lazily loads if not yet in memory.
+ * @param {string} name
+ * @param {number} [duration] seconds
+ */
+ async crossfadeTo(name, duration = DEFAULT_CROSSFADE) {
+ duration = Math.max(0, Math.min(duration, 5));
+ if (name === this.currentName) return;
+ // Record this as the latest-requested clip before the async load so that
+ // if a newer crossfadeTo call arrives while this one is fetching, we can
+ // detect the race and abort: preventing a slow-loading walk clip from
+ // overriding an idle/dance that was applied while it was still fetching.
+ this._latestCrossfadeTarget = name;
+ const ready = await this.ensureLoaded(name);
+ if (!ready) {
+ if (this._failed.has(name) || this._animationDefs.some((d) => d.name === name))
+ log.warn(`[AnimationManager] "${name}" unavailable`);
+ return;
+ }
+ // Re-check after the async load: if a newer crossfadeTo superseded this
+ // request while the clip was fetching, discard this stale crossfade.
+ // Also catches the common case where stepAvatar queues many identical calls.
+ if (this._latestCrossfadeTarget !== name) return;
+ if (name === this.currentName) return;
+ const next = this.actions.get(name);
+ if (!next) return;
+ // Reject a fallen-pose retarget: keep the current clip (or the authored
+ // bind pose when nothing is playing) instead of crossfading onto a body
+ // that would land on its back.
+ if (!this._guardAgainstFallenPose(name, next)) return;
+
+ next.reset().play();
+ if (this.currentAction && this.currentAction !== next) {
+ this.currentAction.crossFadeTo(next, duration, true);
+ } else {
+ next.fadeIn(duration);
+ }
+ this.currentAction = next;
+ this.currentName = name;
+ try { this.onChange?.(name); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }
+ }
+
+ // ── Additive overlay (gesture-over-locomotion) ──────────────────────────────
+
+ /**
+ * Build (and cache) an additive clip for the named library clip, retargeted to
+ * the attached rig. The clip is made additive relative to its own first frame
+ * the standard three.js technique (see webgl_animation_skinning_additive_blending)
+ * so playing it adds its pose delta on top of whatever the base layer is doing.
+ * When `upperBodyOnly` is set, every lower-body track (hips, legs, feet) is
+ * dropped first so locomotion keeps full control of the legs.
+ *
+ * @param {string} name
+ * @param {boolean} upperBodyOnly
+ * @returns {THREE.AnimationClip|null}
+ */
+ _buildOverlayClip(name, upperBodyOnly) {
+ const cacheKey = `${name}|${upperBodyOnly ? 'upper' : 'full'}`;
+ const cached = this._overlayClips.get(cacheKey);
+ if (cached) return cached;
+
+ const raw = this.clips.get(name);
+ if (!raw) return null;
+ const retargeted = this._retarget(raw);
+ if (!retargeted) return null;
+
+ let tracks = retargeted.tracks;
+ if (upperBodyOnly && this._canonicalToNode) {
+ const lowerNodes = new Set();
+ for (const canonical of LOWER_BODY_CANONICAL) {
+ const node = this._canonicalToNode.get(canonical);
+ if (node) lowerNodes.add(node);
+ }
+ tracks = tracks.filter((t) => {
+ const node = t.name.split('.')[0];
+ return !lowerNodes.has(node);
+ });
+ if (tracks.length === 0) return null; // rig shares no upper-body bones
+ }
+
+ const overlay = new AnimationClip(`${name}__additive`, retargeted.duration, tracks);
+ // Subtract frame 0 so the clip becomes a pose-delta the mixer can add.
+ AnimationUtils.makeClipAdditive(overlay);
+ this._overlayClips.set(cacheKey, overlay);
+ return overlay;
+ }
+
+ /**
+ * Play a gesture as an additive overlay on top of the current base clip, so the
+ * avatar can (e.g.) wave or cheer while it keeps walking. The base
+ * idle/walk/run action is untouched: only this additive layer is added.
+ *
+ * @param {string} name clip name (library or appended def)
+ * @param {{ loop?: boolean, crossfade?: number, upperBodyOnly?: boolean, timeScale?: number, onFinished?: Function }} [opts]
+ * @returns {Promise<boolean>} true if the overlay started
+ */
+ async playOverlay(name, { loop = false, crossfade = 0.25, upperBodyOnly = true, timeScale = 1, onFinished = null } = {}) {
+ crossfade = Math.max(0, Math.min(crossfade, 5));
+ const ready = await this.ensureLoaded(name);
+ if (!ready || !this.mixer) return false;
+
+ const overlayClip = this._buildOverlayClip(name, upperBodyOnly);
+ if (!overlayClip) return false;
+
+ const next = this.mixer.clipAction(overlayClip, undefined, AdditiveAnimationBlendMode);
+ // Tear down any previous overlay listener and fade the old overlay out.
+ this._detachOverlayFinish();
+ const prev = this.overlayAction;
+ if (prev && prev !== next) prev.fadeOut(crossfade);
+
+ next.enabled = true;
+ next.setLoop(loop ? LoopRepeat : LoopOnce, loop ? Infinity : 1);
+ next.clampWhenFinished = !loop;
+ next.setEffectiveTimeScale(timeScale);
+ next.reset();
+ next.setEffectiveWeight(1);
+ next.fadeIn(crossfade);
+ next.play();
+
+ this.overlayAction = next;
+ this.overlayName = name;
+
+ if (!loop) {
+ const handler = (e) => {
+ if (e.action !== next) return;
+ this.mixer.removeEventListener('finished', handler);
+ if (this._overlayFinishHandler === handler) this._overlayFinishHandler = null;
+ // Fade the held final frame out and clear, unless something already
+ // replaced this overlay.
+ if (this.overlayAction === next) {
+ next.fadeOut(crossfade);
+ this.overlayAction = null;
+ this.overlayName = null;
+ }
+ try { onFinished?.(name); } catch (err) { log.warn('[AnimationManager] overlay onFinished threw:', err); }
+ };
+ this._overlayFinishHandler = handler;
+ this.mixer.addEventListener('finished', handler);
+ }
+ return true;
+ }
+
+ /** @private Detach the pending one-shot overlay 'finished' listener. */
+ _detachOverlayFinish() {
+ if (this._overlayFinishHandler && this.mixer) {
+ this.mixer.removeEventListener('finished', this._overlayFinishHandler);
+ }
+ this._overlayFinishHandler = null;
+ }
+
+ /**
+ * Fade out and clear the active additive overlay, returning the avatar to the
+ * pure base layer. No-op when no overlay is playing.
+ * @param {{ crossfade?: number }} [opts]
+ */
+ stopOverlay({ crossfade = 0.2 } = {}) {
+ crossfade = Math.max(0, Math.min(crossfade, 5));
+ this._detachOverlayFinish();
+ if (this.overlayAction) {
+ this.overlayAction.fadeOut(crossfade);
+ this.overlayAction = null;
+ this.overlayName = null;
+ }
+ }
+
+ /** @returns {boolean} whether an additive overlay is currently playing. */
+ hasOverlay() {
+ return this.overlayAction != null;
+ }
+
+ /**
+ * Scale playback speed of the active clip. 1 = normal; >1 plays faster
+ * (used to make a walk cycle read as a run).
+ * @param {number} scale
+ */
+ setSpeed(scale) {
+ this.currentAction?.setEffectiveTimeScale(scale);
+ }
+
+ /** Stop all animations. */
+ stopAll() {
+ this.mixer?.stopAllAction();
+ this._detachOverlayFinish();
+ this.currentAction = null;
+ this.currentName = null;
+ this.overlayAction = null;
+ this.overlayName = null;
+ try { this.onChange?.(null); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }
+ }
+
+ /**
+ * Tick the mixer. Call from the render loop.
+ * @param {number} delta seconds since last frame
+ */
+ update(delta) {
+ this.mixer?.update(delta);
+ }
+
+ /** @returns {string[]} */
+ getLoadedNames() {
+ return [...this.clips.keys()];
+ }
+
+ /** @param {string} name @returns {boolean} */
+ isLoaded(name) {
+ return this.clips.has(name);
+ }
+
+ dispose() {
+ this.detach();
+ this.clips.clear();
+ this._animationDefs = [];
+ this._failed.clear();
+ }
+}
+
+// A pre-baked clip only deforms the mesh when its tracks address real skeleton
+// bones. Require both a SkinnedMesh and enough canonically-named bones so we
+// don't mistake a static prop (whose node happens to be named "Head") for a
+// rig the library can animate.
+function _modelSupportsCanonicalClips(model) {
+ let hasSkinnedMesh = false;
+ const canonical = new Set();
+ model.traverse((node) => {
+ if (node.isSkinnedMesh) hasSkinnedMesh = true;
+ if (node.name) {
+ const c = canonicalizeBoneName(node.name);
+ if (c) canonical.add(c);
+ }
+ });
+ return hasSkinnedMesh && canonical.size >= MIN_CANONICAL_BONES;
+}
+
+// Surface a fallen-pose retarget through the existing client-error pipeline
+// (public/error-reporter.js → POST /api/client-errors, logged "[client-error]").
+// That hook is a no-op on dev hosts and fails silent, exactly what we want here.
+// Guarded for Node/SSR (vitest, the apply_animation MCP tool) where neither
+// `window` nor the hook exists: the guard's logic still runs; only the report
+// is skipped.
+function reportFallenPose(context) {
+ try {
+ const hook =
+ typeof window !== 'undefined' &&
+ typeof window.reportClientError === 'function'
+ ? window.reportClientError
+ : null;
+ if (!hook) return;
+ hook(new Error('fallen-pose retarget'), context);
+ } catch (e) {
+ log.warn('[AnimationManager] fallen-pose report failed:', e);
+ }
+}
diff --git a/packages/ar-studio/src/anim/animation-retarget.js b/packages/ar-studio/src/anim/animation-retarget.js
new file mode 100644
index 000000000..c5650dfef
--- /dev/null
+++ b/packages/ar-studio/src/anim/animation-retarget.js
@@ -0,0 +1,750 @@
+// Runtime animation retargeting: apply a canonical-skeleton clip to an
+// arbitrary rigged model whose bones may be named differently (Mixamo, Blender,
+// Rigify, snake_case, …) and proportioned differently (tall, short, chunky).
+//
+// The pre-baked library in /public/animations/clips addresses tracks by the
+// canonical Avaturn bone names (Hips, Spine, LeftArm, …). A loaded GLB rig might
+// name the same bones `mixamorig:Hips`, `DEF-spine`, `left_arm`, etc. To drive
+// (and export) that rig we rewrite each track's bone name to the *actual* node
+// name on the target, drop tracks the rig has no bone for, and rescale the hip
+// translation so root motion lands at the new rig's height instead of the
+// authoring rig's. We retarget only the true-motion channels: joint rotations
+// and the root (Hips) translation: and skip the clips' per-bone position/scale
+// channels, which encode the *authoring* rig's bone lengths and would crush a
+// differently-proportioned avatar into a heap. The result binds cleanly in both
+// THREE.AnimationMixer (preview) and THREE.GLTFExporter (animated-GLB export).
+//
+// Pure module: three + the canonicalizer only: so it runs unchanged in the
+// browser (the /pose gallery) and in Node (the apply_animation MCP tool, vitest).
+
+import { AnimationClip, Box3, Quaternion, Vector3 } from 'three';
+import { canonicalizeBoneName, resolveArmShoulderCollisions } from './glb-canonicalize.js';
+import { CANONICAL_REST, CANONICAL_REST_WORLD } from './animation-canonical-rest.js';
+
+// A clip retargets cleanly only when enough of its tracks find a home on the
+// target rig. Below this the motion would read as a few twitching joints rather
+// than a performance, so callers surface an actionable "can't retarget" error.
+export const MIN_COVERAGE = 0.5;
+
+// Rest (bind-pose) local rotation of each canonical bone *on the authoring rig*
+// the clips were baked against (the Avaturn-rigged public/avatars/cz.glb). The
+// library stores absolute local rotations, so a clip only looks right when the
+// target bone's rest matches the authoring rest: otherwise we must replay the
+// motion in the target's own rest frame (see `bindCorrections`).
+//
+// The full skeleton is covered (generated from cz.glb into
+// animation-canonical-rest.js), not just Hips. Hips carries the up-axis
+// convention: Mixamo/FBX bake a +90°X on the armature and a −90°X on Hips, and
+// copying the clip's Hips rotation verbatim wipes that out and tips the body onto
+// its back. The limb bones carry the pose convention: cz rests in an A-pose,
+// Mixamo in a T-pose: so without per-limb correction an upright avatar still
+// plays clips with the arms/legs in the wrong frame. Because the values are cz's
+// own rest, retargeting back onto cz yields an identity correction per bone
+// (skipped below), so a matching rig round-trips byte-for-byte.
+const SOURCE_REST = new Map(
+ Object.entries(CANONICAL_REST).map(([bone, q]) => [bone, new Quaternion(q[0], q[1], q[2], q[3])]),
+);
+
+// World-space (model-frame) bind rotation of each canonical bone on the authoring
+// rig. Paired with SOURCE_REST so the bind correction can preserve a clip bone's
+// *world* motion delta (not just its local deviation) when the target rig rests
+// in a different pose: see `bindCorrections`.
+const SOURCE_WORLD_REST = new Map(
+ Object.entries(CANONICAL_REST_WORLD).map(([bone, q]) => [
+ bone,
+ new Quaternion(q[0], q[1], q[2], q[3]),
+ ]),
+);
+
+// A quaternion within this of identity (|w| ≈ 1) is treated as no rotation, so a
+// rig that already matches the authoring convention round-trips bit-for-bit.
+const BIND_EPSILON = 1e-6;
+
+// Track property prefix for a blendshape lane, e.g.
+// `Face.morphTargetInfluences[browInnerUp]`.
+const MORPH_PROPERTY = 'morphTargetInfluences[';
+
+const _v = new Vector3();
+const _q = new Quaternion();
+
+/**
+ * @typedef {Object} RetargetResult
+ * @property {AnimationClip|null} clip Retargeted clip (track names rewritten to
+ * the target's bone names), or null when coverage is below MIN_COVERAGE.
+ * @property {number} matched Tracks successfully mapped onto the target.
+ * @property {number} total Tracks in the source clip.
+ * @property {number} coverage matched / total (0-1).
+ * @property {string[]} dropped Canonical bone names the target rig lacks.
+ * @property {number} hipScale Factor applied to hip translation (1 = none).
+ * @property {number} face Blendshape lanes bound on the target (0 = no face).
+ */
+
+// Whether Object3D `a` is an ancestor of `b`. Feeds the hierarchy tie-break in
+// resolveArmShoulderCollisions: the clavicle parents the upper arm.
+function isAncestorObject(a, b) {
+ for (let n = b?.parent; n; n = n.parent) if (n === a) return true;
+ return false;
+}
+
+/**
+ * Resolve every canonical bone the graph carries, in the order the maps below
+ * read it: node-graph bones first, then skeleton bones some exporters name only
+ * there. Each graph node is considered once, the clavicle/upper-arm collision is
+ * resolved against the live hierarchy (see resolveArmShoulderCollisions), and
+ * only then does first-wins pick one node per canonical name.
+ *
+ * Resolution has to happen BEFORE the first-wins claim: a Rigify rig lists
+ * `shoulder.L` (the clavicle) ahead of `upper_arm.L` and both normalize onto
+ * `LeftArm`, so claiming first would drop the upper arm before anything could
+ * notice the two bones were fighting over one name.
+ *
+ * @param {import('three').Object3D} root
+ * @returns {Array<{node: import('three').Object3D, raw: string, canonical: string}>}
+ */
+function canonicalBoneEntries(root) {
+ const entries = [];
+ const seen = new Set();
+ const consider = (node) => {
+ if (!node?.name || seen.has(node)) return;
+ seen.add(node);
+ const canonical = canonicalizeBoneName(node.name);
+ if (canonical) entries.push({ node, raw: node.name, canonical });
+ };
+ const skinned = [];
+ root.traverse((node) => {
+ if (node.isSkinnedMesh) skinned.push(node);
+ if (node.isBone) consider(node);
+ });
+ for (const sm of skinned) {
+ for (const bone of sm.skeleton?.bones || []) consider(bone);
+ }
+ resolveArmShoulderCollisions(entries, {
+ isAncestor: (a, b) => isAncestorObject(a.node, b.node),
+ });
+ const claimed = new Set();
+ return entries.filter((e) => {
+ if (claimed.has(e.canonical)) return false;
+ claimed.add(e.canonical);
+ return true;
+ });
+}
+
+/**
+ * Build a `canonical bone → target node name` map by walking an Object3D graph.
+ * Used server-side (apply_animation) where there's no GltfRig wrapper. Prefers
+ * SkinnedMesh skeleton bones, falls back to any named Bone nodes.
+ *
+ * @param {import('three').Object3D} root
+ * @returns {Map<string,string>}
+ */
+export function canonicalNodeMapFromObject(root) {
+ const map = new Map();
+ for (const { canonical, node } of canonicalBoneEntries(root)) map.set(canonical, node.name);
+ return map;
+}
+
+/**
+ * Same walk as {@link canonicalNodeMapFromObject}, but keyed to the live nodes
+ * rather than their names. Callers that need to *write* to the skeleton (the
+ * skeleton-space proportion editor in src/avatar-proportions.js) need the node
+ * itself; resolving by name afterwards would break on the duplicate bone names
+ * a merged accessory or garment can introduce.
+ *
+ * @param {import('three').Object3D} root
+ * @returns {Map<string,import('three').Object3D>}
+ */
+export function canonicalBoneNodesFromObject(root) {
+ const map = new Map();
+ if (!root?.traverse) return map;
+ for (const { canonical, node } of canonicalBoneEntries(root)) map.set(canonical, node);
+ return map;
+}
+
+/**
+ * Build the same map from a GltfRig/MannequinRig (src/pose-rig.js), which has
+ * already resolved canonical → node. We read each node's live `.name` so the
+ * rewritten track binds to the real graph node.
+ *
+ * @param {{ getBones: () => Array<{key:string,node:import('three').Object3D}> }} rig
+ * @returns {Map<string,string>}
+ */
+export function canonicalNodeMapFromRig(rig) {
+ const map = new Map();
+ for (const { key, node } of rig.getBones?.() || []) {
+ if (node?.name) map.set(key, node.name);
+ }
+ return map;
+}
+
+/**
+ * Capture each canonical bone's rest (bind-pose) local rotation by walking an
+ * Object3D graph: the companion to {@link canonicalNodeMapFromObject}, read in
+ * the same first-bone-wins order so the rest quaternion belongs to the very node
+ * a track gets renamed onto. Call while the model is in its authored bind pose
+ * (i.e. before any clip has been sampled), which is the case at attach time.
+ *
+ * @param {import('three').Object3D} root
+ * @returns {Map<string,import('three').Quaternion>}
+ */
+export function canonicalRestMapFromObject(root) {
+ const map = new Map();
+ for (const { canonical, node } of canonicalBoneEntries(root)) {
+ map.set(canonical, node.quaternion.clone());
+ }
+ return map;
+}
+
+/**
+ * Rest-rotation map from a GltfRig/MannequinRig, mirroring
+ * {@link canonicalNodeMapFromRig}.
+ *
+ * @param {{ getBones: () => Array<{key:string,node:import('three').Object3D}> }} rig
+ * @returns {Map<string,import('three').Quaternion>}
+ */
+export function canonicalRestMapFromRig(rig) {
+ const map = new Map();
+ for (const { key, node } of rig.getBones?.() || []) {
+ if (node && !map.has(key)) map.set(key, node.quaternion.clone());
+ }
+ return map;
+}
+
+// World (model-frame) bind rotation of a node: the pure-quaternion product of its
+// ancestors' rotations down to `stopAt` (exclusive), times the node's own. Stops
+// at the model root so a placement rotation the viewer applies to the whole avatar
+// is excluded: the same frame SOURCE_WORLD_REST is measured in. Requires local
+// rotations to be at bind pose (true at attach time).
+function worldRestQuat(node, stopAt) {
+ const q = node.quaternion.clone();
+ for (let n = node.parent; n && n !== stopAt; n = n.parent) q.premultiply(n.quaternion);
+ return q;
+}
+
+/**
+ * World bind-rotation map by walking an Object3D graph: the world-frame companion
+ * to {@link canonicalRestMapFromObject}, read in the same first-bone-wins order.
+ * Excludes `root` so it matches {@link hipsParentWorldQuat}'s within-model frame.
+ *
+ * @param {import('three').Object3D} root
+ * @returns {Map<string,import('three').Quaternion>}
+ */
+export function canonicalWorldRestMapFromObject(root) {
+ const map = new Map();
+ for (const { canonical, node } of canonicalBoneEntries(root)) {
+ map.set(canonical, worldRestQuat(node, root));
+ }
+ return map;
+}
+
+/**
+ * World bind-rotation map from a GltfRig/MannequinRig. The rig is posed at the
+ * origin (within-model == world), so we compose all the way to the top.
+ *
+ * @param {{ getBones: () => Array<{key:string,node:import('three').Object3D}> }} rig
+ * @returns {Map<string,import('three').Quaternion>}
+ */
+export function canonicalWorldRestMapFromRig(rig) {
+ const map = new Map();
+ for (const { key, node } of rig.getBones?.() || []) {
+ if (node && !map.has(key)) map.set(key, worldRestQuat(node, null));
+ }
+ return map;
+}
+
+/**
+ * Map every blendshape name the target carries to the mesh nodes that own it, so
+ * a face lane authored once can be re-pointed at this avatar. Faces are commonly
+ * split across several meshes (head, teeth, brows), and all of them need driving.
+ *
+ * @param {import('three').Object3D} root
+ * @returns {Map<string,string[]>}
+ */
+export function morphTargetMapFromObject(root) {
+ const map = new Map();
+ root.traverse((node) => {
+ if (!node?.morphTargetDictionary || !node.name) return;
+ for (const shape of Object.keys(node.morphTargetDictionary)) {
+ if (!map.has(shape)) map.set(shape, []);
+ const meshes = map.get(shape);
+ if (!meshes.includes(node.name)) meshes.push(node.name);
+ }
+ });
+ return map;
+}
+
+/**
+ * Per-bone bind correction `{L, R}` such that `q' = L · q · R` re-expresses a clip
+ * bone's keyframe so it produces the SAME world-space rotation delta on a target
+ * rig that rests in a different pose:
+ *
+ * L = Rt · WT⁻¹ · WS · Rs⁻¹ R = WS⁻¹ · WT
+ *
+ * where Rs/Rt are the source/target LOCAL bind rotations and WS/WT their WORLD
+ * (model-frame) bind rotations. This is the standard world-delta-preserving
+ * retarget (trgLocal = WTp⁻¹·WSp · q · WS⁻¹·WT, with the parent worlds derived as
+ * WSp = WS·Rs⁻¹, WTp = WT·Rt⁻¹). It collapses to:
+ * • the pure axis-convention reframe for the Hips (different parent frame, same
+ * world rest: e.g. a Mixamo Hips baked at −90°X), and
+ * • the correct limb reframe for an A-pose clip on a T-pose rig, which a
+ * local-only `Rt·Rs⁻¹` premultiply skewed by ~30°.
+ *
+ * When world rests are unavailable we fall back to the prior local-only premultiply
+ * (`L = Rt·Rs⁻¹`, `R = I`) so callers that don't supply them still work. Bones whose
+ * correction is identity are omitted, so a matching rig skips the work and
+ * round-trips unchanged.
+ *
+ * @param {Map<string,import('three').Quaternion>|null} targetRest target LOCAL bind
+ * @param {Map<string,import('three').Quaternion>|null} [targetWorldRest] target WORLD bind
+ * @returns {Map<string,{L:import('three').Quaternion,R:import('three').Quaternion|null}>}
+ */
+function bindCorrections(targetRest, targetWorldRest) {
+ const out = new Map();
+ if (!(targetRest instanceof Map)) return out;
+ const haveWorld = targetWorldRest instanceof Map;
+ for (const [canonical, Rs] of SOURCE_REST) {
+ const Rt = targetRest.get(canonical);
+ if (!Rt) continue;
+ const WS = SOURCE_WORLD_REST.get(canonical);
+ const WT = haveWorld ? targetWorldRest.get(canonical) : null;
+ let L;
+ let R = null;
+ if (WS && WT) {
+ // L = Rt · WT⁻¹ · WS · Rs⁻¹
+ L = Rt.clone()
+ .multiply(WT.clone().invert())
+ .multiply(WS)
+ .multiply(Rs.clone().invert());
+ // R = WS⁻¹ · WT
+ R = WS.clone().invert().multiply(WT);
+ if (1 - Math.abs(R.w) < BIND_EPSILON) R = null; // identity post-factor
+ } else {
+ // Fallback: local-only premultiply (prior behaviour).
+ L = Rt.clone().multiply(Rs.clone().invert());
+ }
+ const identityL = 1 - Math.abs(L.w) < BIND_EPSILON;
+ if (identityL && !R) continue; // nothing to do → round-trips unchanged
+ out.set(canonical, { L: identityL ? null : L, R });
+ }
+ return out;
+}
+
+// Apply the bind correction `q ← L · q · R` to every [x,y,z,w] keyframe in place.
+// Either factor may be null (identity).
+function correctQuaternionTrack(values, { L, R }) {
+ for (let i = 0; i < values.length; i += 4) {
+ _q.set(values[i], values[i + 1], values[i + 2], values[i + 3]);
+ if (L) _q.premultiply(L);
+ if (R) _q.multiply(R);
+ values[i] = _q.x;
+ values[i + 1] = _q.y;
+ values[i + 2] = _q.z;
+ values[i + 3] = _q.w;
+ }
+}
+
+// Rotate every [x,y,z] keyframe of a position track by `c` in place, so root
+// motion stays aligned once the parent armature's axis convention is corrected.
+function rotateVectorTrack(values, c) {
+ for (let i = 0; i < values.length; i += 3) {
+ _v.set(values[i], values[i + 1], values[i + 2]).applyQuaternion(c);
+ values[i] = _v.x;
+ values[i + 1] = _v.y;
+ values[i + 2] = _v.z;
+ }
+}
+
+// Rotation to apply to the Hips position (root-motion) track. The clip authors
+// hip translation in the authoring rig's hips-parent frame, whose world rotation
+// is identity (cz's armature has none). To preserve world motion on the target,
+// rotate by the inverse of the target's hips-parent world rotation. When the
+// caller can't supply that (a bare retargetClip call), fall back to the Hips
+// bone correction: exact for any rig whose hips are upright at bind, i.e. every
+// real humanoid. Returns null when no rotation is needed.
+function hipPositionCorrection(hipsParentWorldQuat, corrections) {
+ if (hipsParentWorldQuat) {
+ const q = hipsParentWorldQuat.isQuaternion
+ ? hipsParentWorldQuat.clone()
+ : new Quaternion(
+ hipsParentWorldQuat[0],
+ hipsParentWorldQuat[1],
+ hipsParentWorldQuat[2],
+ hipsParentWorldQuat[3],
+ );
+ q.invert();
+ return 1 - Math.abs(q.w) < BIND_EPSILON ? null : q;
+ }
+ // Fallback: the Hips correction's premultiply (parent-frame) factor, which for
+ // the Hips carries the axis-convention reframe (its post-factor is identity
+ // when source and target share a world rest).
+ return corrections.get('Hips')?.L || null;
+}
+
+/**
+ * World rotation of the target Hips' parent, measured *within the model* (i.e.
+ * relative to `root`, so a placement rotation the viewer applies to the whole
+ * avatar is excluded). Inverting it lets {@link retargetClip} re-express a clip's
+ * authored hip translation in the target's hips-parent frame, so root motion
+ * travels the same world direction on a Mixamo `+90°X` armature, an RPM rig, etc.
+ * Requires the graph's local rotations to be at bind pose (true at attach time).
+ *
+ * @param {import('three').Object3D} root
+ * @returns {import('three').Quaternion|null}
+ */
+export function hipsParentWorldQuat(root) {
+ let hips = null;
+ root.traverse((n) => {
+ if (!hips && n.isBone && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;
+ });
+ if (!hips) {
+ root.traverse((n) => {
+ if (!hips && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;
+ });
+ }
+ if (!hips || !hips.parent) return null;
+ const q = new Quaternion();
+ for (let n = hips.parent; n && n !== root; n = n.parent) q.premultiply(n.quaternion);
+ return q;
+}
+
+/**
+ * World-space rest height of the target's hips, used to scale root translation
+ * onto a differently-sized rig. Returns 0 if it can't be determined (callers
+ * then skip hip scaling). Requires world matrices to be current.
+ *
+ * @param {{ getNode: (k:string) => import('three').Object3D|null }} rig
+ * @returns {number}
+ */
+export function hipRestHeight(rig) {
+ const hips = rig.getNode?.('Hips');
+ if (!hips) return 0;
+ hips.updateWorldMatrix(true, false);
+ hips.getWorldPosition(_v);
+ return _v.y;
+}
+
+// Bounding-box bottom of the model, or NaN when it can't be computed. Guarded:
+// three's pose-aware SkinnedMesh.computeBoundingBox walks skin attributes per
+// vertex and throws on synthetic rigs whose geometry lacks them; a rig we can't
+// measure just keeps the pre-floor behavior instead of failing the mount.
+function safeFloorY(root) {
+ try {
+ return new Box3().setFromObject(root).min.y;
+ } catch {
+ return NaN;
+ }
+}
+
+const _hipScalePos = new Vector3();
+const _hipScaleQuat = new Quaternion();
+const _hipScaleScale = new Vector3();
+
+/**
+ * Rest height of an Object3D rig's Hips expressed in the *hips-parent's local
+ * units*, i.e. world height divided by the parent's accumulated world scale.
+ * Hip-position tracks are authored in metres and set the Hips bone's *local*
+ * position, so the scale factor that lands them at the right place is this local
+ * height ÷ the clip's authored baseline: not the world height. The two agree
+ * for a metre-native rig (parent scale ≈ 1) but diverge hard for a centimetre
+ * rig (e.g. a Mixamo armature exported at `scale 0.01`, whose Hips local sits
+ * near −100): matching world heights there would collapse the hip track to ~1cm
+ * of motion and sink the avatar a metre into the floor. Returns 0 when the hips
+ * or a usable parent scale can't be determined (caller then skips hip scaling).
+ *
+ * @param {import('three').Object3D} root
+ * @returns {number}
+ */
+export function hipRestLocalHeight(root) {
+ let hips = null;
+ root.traverse((n) => {
+ if (!hips && n.isBone && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;
+ });
+ if (!hips) {
+ root.traverse((n) => {
+ if (!hips && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;
+ });
+ }
+ if (!hips || !hips.parent) return 0;
+ hips.updateWorldMatrix(true, false);
+ hips.getWorldPosition(_hipScalePos);
+ let worldY = _hipScalePos.y;
+ // Measure above the model's own floor (its bounding-box bottom), not above
+ // world y=0. Viewers recenter content around the origin (setContent
+ // subtracts the bbox center) and origin-centered GLB exports put the floor
+ // below zero; measured from world zero, both read as "hips at or below the
+ // ground", which skipped scaling and let the metre-authored hip track fling
+ // a small rig into the air. Clips author ground at 0, so hips-above-floor
+ // is the like-for-like height. For a ground-native rig floorY is 0 and
+ // nothing changes.
+ const floorY = safeFloorY(root);
+ if (Number.isFinite(floorY)) worldY -= floorY;
+ hips.parent.matrixWorld.decompose(_hipScalePos, _hipScaleQuat, _hipScaleScale);
+ const parentScale = (_hipScaleScale.x + _hipScaleScale.y + _hipScaleScale.z) / 3;
+ if (!(parentScale > 1e-6) || !(worldY > 0) || !Number.isFinite(worldY)) return 0;
+ return worldY / parentScale;
+}
+
+/**
+ * The model's floor (bounding-box bottom) expressed in the hips-parent's local
+ * frame: the Y a hip-position track must be offset by so the clip's ground
+ * (authored at 0) lands on this rig's actual ground. 0 for a ground-native rig
+ * (floor at local 0); negative for an origin-centered export (floor below the
+ * local origin). Returns 0 when it can't be determined, which leaves the
+ * retarget exactly as before.
+ *
+ * @param {import('three').Object3D} root
+ * @returns {number}
+ */
+export function hipGroundLocalY(root) {
+ let hips = null;
+ root.traverse((n) => {
+ if (!hips && n.isBone && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;
+ });
+ if (!hips) {
+ root.traverse((n) => {
+ if (!hips && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;
+ });
+ }
+ if (!hips || !hips.parent) return 0;
+ hips.updateWorldMatrix(true, false);
+ const floorY = safeFloorY(root);
+ if (!Number.isFinite(floorY)) return 0;
+ hips.getWorldPosition(_hipScalePos);
+ // The floor point under the hips, mapped into the parent's local frame so
+ // the offset composes with the track's local-position values.
+ const local = hips.parent.worldToLocal(new Vector3(_hipScalePos.x, floorY, _hipScalePos.z));
+ return Number.isFinite(local.y) ? local.y : 0;
+}
+
+// First Y value of a `Hips.position` track: the height the clip's root motion
+// was authored around. The retarget scales other-height rigs by target/source.
+export function clipHipBaselineY(clip) {
+ const track = clip.tracks.find(
+ (t) =>
+ t.name.endsWith('.position') && canonicalizeBoneName(t.name.split('.')[0]) === 'Hips',
+ );
+ if (!track || track.values.length < 3) return 0;
+ return track.values[1]; // [x, y, z, …]: Y of the first keyframe
+}
+
+/**
+ * Core rewrite. Splits each track into `bone.property`, canonicalizes the bone,
+ * looks up the target's node name, and emits a renamed track. Hip position
+ * tracks are scaled by `hipScale`. Returns null clip when coverage is too low.
+ *
+ * @param {AnimationClip} clip
+ * @param {Map<string,string>} canonicalToNode
+ * @param {{ hipScale?: number, hipOffsetY?: number, minCoverage?: number, morphTargets?: Map<string,string[]> }} [opts]
+ * @returns {RetargetResult}
+ */
+export function retargetClip(clip, canonicalToNode, opts = {}) {
+ const hipScale = Number.isFinite(opts.hipScale) && opts.hipScale > 0 ? opts.hipScale : 1;
+ const hipOffsetY = Number.isFinite(opts.hipOffsetY) ? opts.hipOffsetY : 0;
+ const minCoverage = opts.minCoverage ?? MIN_COVERAGE;
+ const corrections = bindCorrections(opts.targetRest, opts.targetWorldRest);
+ const hipsPosCorrection = hipPositionCorrection(opts.hipsParentWorldQuat, corrections);
+ const dropped = [];
+ const tracks = [];
+ const faceTracks = [];
+ // Denominator counts only *retargetable* tracks (see below), so a clip baked
+ // with per-bone position/scale channels still reports honest coverage.
+ let total = 0;
+
+ for (const track of clip.tracks) {
+ const dot = track.name.indexOf('.');
+ if (dot === -1) continue;
+ const boneRaw = track.name.slice(0, dot);
+ const property = track.name.slice(dot + 1);
+
+ // Face (morph-target) lanes. Signing carries grammar on the face: raised
+ // brows make a question, furrowed brows a wh-question: so a clip may drive
+ // blendshapes as well as bones. They are authored against a placeholder node
+ // (`Face.morphTargetInfluences[browInnerUp]`) and re-pointed here at whatever
+ // mesh on THIS avatar owns that shape, because the mesh is named differently
+ // on every rig and a face is often split across several. An avatar with no
+ // such shape simply loses the lane: the sign still performs, just without the
+ // marker. They never count toward bone coverage, so a face-less rig is not
+ // judged to have failed the retarget.
+ if (property.startsWith(MORPH_PROPERTY)) {
+ const shape = property.slice(MORPH_PROPERTY.length, -1);
+ const meshes = opts.morphTargets instanceof Map ? opts.morphTargets.get(shape) : null;
+ if (!meshes?.length) {
+ dropped.push(shape);
+ continue;
+ }
+ for (const meshName of meshes) {
+ const next = track.clone();
+ next.name = `${meshName}.${property}`;
+ faceTracks.push(next);
+ }
+ continue;
+ }
+
+ const canonical = canonicalizeBoneName(boneRaw) || boneRaw;
+
+ // The clips are baked from cz with a full position/quaternion/scale channel
+ // per bone. A bone's local scale and its local position (its fixed offset
+ // from its parent: i.e. the skeleton's bone lengths) are *structure of the
+ // authoring rig*, not motion. Rewriting them onto a differently-proportioned
+ // or differently-scaled avatar overwrites that rig's own bone lengths with
+ // cz's centimetre-vs-metre offsets and folds the whole skeleton into a heap
+ // even though every bone "matches", so coverage lies at 100%. Only joint
+ // rotations and the root (Hips) translation are true motion; retarget those
+ // and skip the structural channels so every rig keeps its own proportions.
+ const retargetable =
+ property === 'quaternion' || (property === 'position' && canonical === 'Hips');
+ if (!retargetable) continue;
+
+ total++;
+ const nodeName = canonicalToNode.get(canonical);
+ if (!nodeName) {
+ dropped.push(canonical);
+ continue;
+ }
+ const next = track.clone();
+ next.name = `${nodeName}.${property}`;
+ if (property === 'quaternion') {
+ // Bind correction q ← L·q·R: replay the clip bone's motion as the same
+ // world-space delta on the target's rest pose, so a clip authored for one
+ // rest pose (cz's A-pose) drives a differently-rigged avatar (a Mixamo
+ // T-pose, or a Hips baked at −90°X that would otherwise read as "lying
+ // down") without skewing limbs.
+ const correction = corrections.get(canonical);
+ if (correction) correctQuaternionTrack(next.values, correction);
+ } else {
+ // Root motion (Hips.position): the clip authors hip translation in the
+ // authoring rig's world-Y-up frame; re-express it in the target's
+ // hips-parent frame so it travels the same world direction on any rig,
+ // then scale for height.
+ if (hipsPosCorrection) rotateVectorTrack(next.values, hipsPosCorrection);
+ if (hipScale !== 1) {
+ for (let i = 0; i < next.values.length; i++) next.values[i] *= hipScale;
+ }
+ // Land the clip's ground (authored at 0) on this rig's actual floor:
+ // origin-centered exports keep their floor below the local origin, and
+ // without this offset the scaled track still hovers the body a
+ // floor-height above the mesh.
+ if (hipOffsetY !== 0) {
+ for (let i = 1; i < next.values.length; i += 3) next.values[i] += hipOffsetY;
+ }
+ }
+ tracks.push(next);
+ }
+
+ const matched = tracks.length;
+ const coverage = total > 0 ? matched / total : 0;
+ if (coverage < minCoverage) {
+ return { clip: null, matched, total, coverage, dropped, hipScale, face: 0 };
+ }
+ const out = clip.clone();
+ out.tracks = [...tracks, ...faceTracks];
+ return { clip: out, matched, total, coverage, dropped, hipScale, face: faceTracks.length };
+}
+
+/**
+ * High-level: retarget a canonical clip onto a rig (GltfRig/MannequinRig),
+ * computing hip scaling from the rig's actual proportions.
+ *
+ * The bind correction (and hip scaling) is measured from the rig's LIVE bone
+ * transforms, so they must read the rig's true rest pose: not whatever pose a
+ * previously-previewed clip left the bones in. A preview mixer leaves the bones
+ * mid-animation after it stops, so without this the second clip a user plays is
+ * retargeted against a garbage "rest" and its limbs skew by 60-90° (an avatar
+ * that plays one clip fine, then plays the next with its arms stuck overhead).
+ * We restore the rig to its bind pose first; the caller's mixer immediately
+ * re-poses it on the next frame, so the reset is invisible. Aside from that
+ * normalization the clip itself is not mutated.
+ *
+ * @param {AnimationClip} clip
+ * @param {object} rig
+ * @param {{ scaleHips?: boolean, minCoverage?: number }} [opts]
+ * @returns {RetargetResult}
+ */
+export function retargetClipToRig(clip, rig, opts = {}) {
+ rig.resetPose?.(); // read the bind pose, not a leftover preview pose
+ const map = canonicalNodeMapFromRig(rig);
+ const targetRest = canonicalRestMapFromRig(rig);
+ const targetWorldRest = canonicalWorldRestMapFromRig(rig);
+ let hipScale = 1;
+ if (opts.scaleHips !== false) {
+ const targetY = hipRestHeight(rig);
+ const sourceY = clipHipBaselineY(clip);
+ if (targetY > 0.05 && sourceY > 0.05) {
+ // Clamp so a wildly off baseline (or a near-zero in-place clip) can't
+ // fling the root metres away.
+ hipScale = Math.min(5, Math.max(0.2, targetY / sourceY));
+ }
+ }
+ // Walk the hips' ancestor chain to the top so root motion is corrected for the
+ // rig's axis convention (the rig is posed at origin, so within-model == world).
+ let hipsParent = null;
+ const hipsNode = rig.getNode?.('Hips');
+ if (hipsNode?.parent) {
+ hipsParent = new Quaternion();
+ for (let n = hipsNode.parent; n; n = n.parent) hipsParent.premultiply(n.quaternion);
+ }
+ return retargetClip(clip, map, {
+ hipScale,
+ minCoverage: opts.minCoverage,
+ targetRest,
+ targetWorldRest,
+ hipsParentWorldQuat: hipsParent,
+ morphTargets: opts.morphTargets ?? (rig.root ? morphTargetMapFromObject(rig.root) : undefined),
+ });
+}
+
+/**
+ * Retarget onto a raw Object3D graph (server-side apply_animation). No hip
+ * scaling by default: the caller may pass an explicit factor.
+ *
+ * @param {AnimationClip} clip
+ * @param {import('three').Object3D} root
+ * @param {{ hipScale?: number, minCoverage?: number }} [opts]
+ * @returns {RetargetResult}
+ */
+export function retargetClipToObject(clip, root, opts = {}) {
+ const map = canonicalNodeMapFromObject(root);
+ const targetRest = opts.targetRest || canonicalRestMapFromObject(root);
+ const targetWorldRest = opts.targetWorldRest || canonicalWorldRestMapFromObject(root);
+ const hipsParentWorld = opts.hipsParentWorldQuat || hipsParentWorldQuat(root);
+ return retargetClip(clip, map, {
+ ...opts,
+ targetRest,
+ targetWorldRest,
+ hipsParentWorldQuat: hipsParentWorld,
+ morphTargets: opts.morphTargets ?? morphTargetMapFromObject(root),
+ });
+}
+
+/**
+ * Resample a clip's timing to play at `factor`× speed (1.8 turns a walk into a
+ * run). Used so an exported GLB carries the tempo the user previewed, not just
+ * a mixer timeScale that doesn't survive the file. Pure: returns a clone.
+ *
+ * @param {AnimationClip} clip
+ * @param {number} factor >1 faster, <1 slower
+ * @returns {AnimationClip}
+ */
+export function scaleClipSpeed(clip, factor) {
+ if (!(factor > 0) || factor === 1) return clip;
+ const out = clip.clone();
+ const inv = 1 / factor;
+ for (const track of out.tracks) {
+ for (let i = 0; i < track.times.length; i++) track.times[i] *= inv;
+ }
+ out.duration = clip.duration * inv;
+ return out;
+}
+
+/**
+ * Convenience: parse a clip from its three.js JSON (the on-disk clip format),
+ * naming it. Centralised so browser and server load clips identically.
+ *
+ * @param {object} json
+ * @param {string} name
+ * @returns {AnimationClip}
+ */
+export function parseClipJSON(json, name) {
+ const clip = AnimationClip.parse(json);
+ if (name) clip.name = name;
+ return clip;
+}
diff --git a/packages/ar-studio/src/anim/glb-canonicalize.js b/packages/ar-studio/src/anim/glb-canonicalize.js
new file mode 100644
index 000000000..86a4a1e62
--- /dev/null
+++ b/packages/ar-studio/src/anim/glb-canonicalize.js
@@ -0,0 +1,846 @@
+// GLB bone-name canonicalizer: rewrites joint node names in an uploaded
+// humanoid GLB so they match one canonical bone set, letting the
+// pre-baked Mixamo animation library play on any rig variant.
+//
+// Handled name variants:
+// • Mixamo: `mixamorig:LeftArm`, `mixamorig1:LeftArm`, `mixamorigLeftArm`
+// • Blender: `Armature_LeftArm`, `Armature/LeftArm`, `upperarm.L` (.L/.R side)
+// • Rigify: `DEF-LeftArm`, `ORG-LeftArm`, `MCH-LeftArm`
+// • CharacterStudio: `CH_Hips`, `CH_LeftUpLeg` (CH_ prefix stripped)
+// • HumanIK / Maya: `Character1:Hips`, `Character1:LeftArm`, `subject:LeftUpLeg` (namespace strip)
+// • Unreal mannequin: `pelvis`, `clavicle_l`, `upperarm_l`, `thigh_l`, `calf_l`, … (alias map)
+// • VRM / VRoid: `J_Bip_C_Hips`, `J_Bip_L_UpperArm`, `J_Bip_L_Little1` (alias map)
+// • VRM 1.0: `upperChest`, `leftUpperArm`, `leftLowerLeg`, `leftToes` (camelCase)
+// • Daz / Genesis: `hip`, `abdomen`, `lShldr`, `lForeArm`, `lThigh`, `lShin`, `lCollar`
+// • MakeHuman: `upperarm.L`, `shin.L`, `clavicle.L` (shared with Unreal/Blender stems)
+// • Simple rigs: `shoulderL`, `elbowL`, `wristL`, `hipL`, `kneeL`, `ankleL`, `chest`
+// • SMPL / SMPL-X: `left_hip`, `left_knee`, `left_ankle`, `left_elbow`, `left_wrist` (side-word joints)
+// • Roblox R15/R6: `LowerTorso`, `UpperTorso`, `Torso`, `LeftUpperArm`, `Left Arm`
+// • Second Life: `mPelvis`, `mTorso`, `mChest`, `mCollarLeft`, `mShoulderLeft`, `mKneeRight`
+// • Anatomical: `lumbar`, `thoracic`, `cervical`, `cranium`, `humerus.L`,
+// `ulna.L`, `femur.L`, `tibia.L`, `talus.L` (scan / anatomy-kit rigs)
+// • snake_case: `left_arm`, `Left_Arm`
+// • kebab-case: `left-arm`
+// • lowercase: `leftarm`, `lefthand`
+//
+// Finger chains are mapped per convention as well, and they are load-bearing: 30
+// of the 53 tracks in every clip in /public/animations/clips address a finger
+// joint, so a rig whose hands don't name-map scores ~40% retarget coverage, falls
+// under MIN_COVERAGE in animation-retarget.js, and gets NO action built at all.
+// Covered spellings: `index_01_l` (Unreal), `leftIndexProximal` (VRM 1.0),
+// `lIndex1` / `lMid1` (Daz), `f_index.01.L` + `thumb.01.L` (Rigify),
+// `finger2-1.L` (MakeHuman), `Index1.L` / `IndexFinger1_R` (Blender / Advanced
+// Skeleton), `J_Bip_L_Little1` (VRoid), `index_proximal.L` (anatomical).
+// Measured end to end by scripts/animation-dignity-sweep.mjs.
+//
+// Skeletons that aren't humanoid (quadrupeds, custom prop rigs) deliberately
+// fall through unchanged: there's no safe automatic mapping for those, and
+// callers fall back to a known-good rig rather than render a bind-pose T-pose.
+//
+// Constraint-driven CONTROL RIGS also fall through on purpose. Blender rigs of
+// the Auto-Rig-Pro / "cwf_ + def_ + tracker" family export a deform layer whose
+// bones are LEAVES hanging off tracker nodes, not a chain: `def_arm_1.R` is not
+// a child of `def_arm_0.R`, it hangs off `c_arm_1_tracker.R`. In Blender those
+// trackers carry Copy-Rotation/Damped-Track constraints; glTF has no constraint
+// system, so they export as inert nodes. Rotating a mapped `def_` bone would move
+// its own skin while the next segment stayed put: the arm comes apart. Mapping
+// that layer is strictly worse than the default-rig fallback, so we do not.
+// Verified against real stored avatars; see scripts/audit-rig-coverage.mjs.
+// The remedy for these uploads is re-rigging (workers/rig), not name mapping.
+//
+// This module is pure JS: works in Node (vitest) and in the browser. It
+// rewrites the GLB JSON chunk in-place and repacks the binary container so
+// the result is a valid GLB that swaps in 1:1 at the same R2 storage key.
+
+import { Matrix4, Quaternion, Vector3 } from 'three';
+
+const GLB_MAGIC = 0x46546c67; // 'glTF' little-endian
+const CHUNK_TYPE_JSON = 0x4e4f534a; // 'JSON'
+
+// Quaternion is "axis-aligned enough" / scale is "uniform enough" below this.
+const ORIENT_EPS = 1e-5;
+// Joint world-matrix elements must match within this before/after the fold, or
+// the fold is reverted (it would have altered the mesh).
+const ORIENT_WORLD_EPS = 1e-4;
+
+// Canonical humanoid bone set. Mirrors the rig used by scripts/build-animations.mjs
+// (cz.glb / Avaturn reference rig): every animation clip in /public/animations/clips
+// addresses tracks by these exact names.
+export const CANONICAL_BONES = Object.freeze([
+ 'Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head',
+ 'LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand',
+ 'LeftHandIndex1', 'LeftHandIndex2', 'LeftHandIndex3',
+ 'LeftHandMiddle1', 'LeftHandMiddle2', 'LeftHandMiddle3',
+ 'LeftHandPinky1', 'LeftHandPinky2', 'LeftHandPinky3',
+ 'LeftHandRing1', 'LeftHandRing2', 'LeftHandRing3',
+ 'LeftHandThumb1', 'LeftHandThumb2', 'LeftHandThumb3',
+ 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand',
+ 'RightHandIndex1', 'RightHandIndex2', 'RightHandIndex3',
+ 'RightHandMiddle1', 'RightHandMiddle2', 'RightHandMiddle3',
+ 'RightHandPinky1', 'RightHandPinky2', 'RightHandPinky3',
+ 'RightHandRing1', 'RightHandRing2', 'RightHandRing3',
+ 'RightHandThumb1', 'RightHandThumb2', 'RightHandThumb3',
+ 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase',
+ 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase',
+]);
+
+// Lookup map: separator-stripped, lowercased variant → canonical name.
+// Built once at module load so canonicalizeBoneName() runs in O(1).
+const LOOKUP = (() => {
+ const m = new Map();
+ for (const canonical of CANONICAL_BONES) {
+ m.set(canonical.toLowerCase(), canonical);
+ }
+ return m;
+})();
+
+// Unreal Engine mannequin skeleton → canonical aliases. UE names the same
+// joints `pelvis`, `clavicle_l`, `upperarm_l`, `thigh_l`, `calf_l`, `ball_l`,
+// … which share no spelling with the canonical/Mixamo set. Keyed by the same
+// separator-stripped lowercase form `_lookupBone` produces (`clavicle_l` →
+// `claviclel`). The spine chain (`spine_01/02/03`) is deliberately OMITTED:
+// its stripped form `spine02` collides with Mixamo's `Spine` + `_02` de-dup
+// suffix, which canonicalizeBoneName already resolves to `Spine`. The torso
+// then rides on `Hips` while every limb, foot, and the neck retarget cleanly
+// well above the 8-bone floor a readable performance needs.
+const UNREAL_ALIASES = new Map(Object.entries({
+ pelvis: 'Hips',
+ neck01: 'Neck',
+ claviclel: 'LeftShoulder', upperarml: 'LeftArm', lowerarml: 'LeftForeArm', handl: 'LeftHand',
+ clavicler: 'RightShoulder', upperarmr: 'RightArm', lowerarmr: 'RightForeArm', handr: 'RightHand',
+ thighl: 'LeftUpLeg', calfl: 'LeftLeg', footl: 'LeftFoot', balll: 'LeftToeBase',
+ thighr: 'RightUpLeg', calfr: 'RightLeg', footr: 'RightFoot', ballr: 'RightToeBase',
+}));
+
+// Unreal's finger chain: `index_01_l`, `middle_02_r`, `thumb_03_l`, `pinky_01_l`,
+// `ring_02_l`. The zero-padded joint index is what keeps these out of the
+// side-suffix finger table below (`Index1L` normalises to `index1l`, never
+// `index01l`), so an otherwise-mapped mannequin arrived with 30 of its 52 joints
+// unmapped. That is not a cosmetic loss: 30 of the clip library's 53 tracks are
+// finger tracks, so a fingerless mannequin scored 40% coverage and fell under the
+// MIN_COVERAGE gate in animation-retarget.js: the rig built no action at all and
+// stood in its bind pose. Found by scripts/animation-dignity-sweep.mjs.
+for (const [uf, cf] of [
+ ['thumb', 'Thumb'], ['index', 'Index'], ['middle', 'Middle'],
+ ['ring', 'Ring'], ['pinky', 'Pinky'],
+]) {
+ for (let n = 1; n <= 3; n++) {
+ UNREAL_ALIASES.set(`${uf}0${n}l`, `LeftHand${cf}${n}`);
+ UNREAL_ALIASES.set(`${uf}0${n}r`, `RightHand${cf}${n}`);
+ }
+}
+
+// Extended humanoid alias map: VRM/VRoid, VRM 1.0, Daz/Genesis, MakeHuman, and
+// simple/generic rigs. Keyed by the same separator-stripped, lowercased form
+// `_lookupBone` produces (e.g. `J_Bip_L_UpperArm` → `jbiplupperarm`,
+// `shoulderL` → `shoulderl`). Consulted AFTER the canonical/Mixamo and Unreal
+// tables, so it only ever resolves names those don't already cover: it can
+// never shadow a canonical spelling. Every entry maps onto the canonical bone
+// set the clip library drives, so any rig using these conventions animates
+// (idle + walk with legs moving) instead of freezing in its bind-pose T-pose.
+const EXTRA_ALIASES = (() => {
+ const m = new Map();
+ const norm = (s) => s.replace(/[-_.\s]+/g, '').toLowerCase();
+ // First spelling wins, so listing-order is the priority.
+ const put = (variant, canonical) => { const k = norm(variant); if (!m.has(k)) m.set(k, canonical); };
+
+ // VRM 0.x / VRoid skeletons (`J_Bip_<C|L|R>_<bone>`). The side lives in the
+ // prefix, so each is mapped explicitly rather than via the side helper below.
+ const VRM = [
+ ['J_Bip_C_Hips', 'Hips'], ['J_Bip_C_Spine', 'Spine'], ['J_Bip_C_Chest', 'Spine1'],
+ ['J_Bip_C_UpperChest', 'Spine2'], ['J_Bip_C_Neck', 'Neck'], ['J_Bip_C_Head', 'Head'],
+ ['J_Bip_L_Shoulder', 'LeftShoulder'], ['J_Bip_L_UpperArm', 'LeftArm'], ['J_Bip_L_LowerArm', 'LeftForeArm'], ['J_Bip_L_Hand', 'LeftHand'],
+ ['J_Bip_R_Shoulder', 'RightShoulder'], ['J_Bip_R_UpperArm', 'RightArm'], ['J_Bip_R_LowerArm', 'RightForeArm'], ['J_Bip_R_Hand', 'RightHand'],
+ ['J_Bip_L_UpperLeg', 'LeftUpLeg'], ['J_Bip_L_LowerLeg', 'LeftLeg'], ['J_Bip_L_Foot', 'LeftFoot'], ['J_Bip_L_ToeBase', 'LeftToeBase'], ['J_Bip_L_Toes', 'LeftToeBase'],
+ ['J_Bip_R_UpperLeg', 'RightUpLeg'], ['J_Bip_R_LowerLeg', 'RightLeg'], ['J_Bip_R_Foot', 'RightFoot'], ['J_Bip_R_ToeBase', 'RightToeBase'], ['J_Bip_R_Toes', 'RightToeBase'],
+ ];
+ for (const [v, c] of VRM) put(v, c);
+ // VRoid finger chains: Thumb/Index/Middle/Ring map 1:1; "Little" is the pinky.
+ for (const [vf, cf] of [['Thumb', 'Thumb'], ['Index', 'Index'], ['Middle', 'Middle'], ['Ring', 'Ring'], ['Little', 'Pinky']]) {
+ for (let n = 1; n <= 3; n++) {
+ put(`J_Bip_L_${vf}${n}`, `LeftHand${cf}${n}`);
+ put(`J_Bip_R_${vf}${n}`, `RightHand${cf}${n}`);
+ }
+ }
+
+ // Centre / torso bones with no side (VRM 1.0, Daz, generic single-chest rigs).
+ for (const [v, c] of [
+ ['chest', 'Spine1'], ['lowerChest', 'Spine1'], ['chestLower', 'Spine1'],
+ ['upperChest', 'Spine2'], ['chestUpper', 'Spine2'],
+ ['abdomen', 'Spine'], ['abdomenLower', 'Spine'], ['abdomenUpper', 'Spine1'],
+ ['hip', 'Hips'],
+ ['lowerNeck', 'Neck'], ['upperNeck', 'Neck'], ['neckLower', 'Neck'], ['neckUpper', 'Neck'],
+ // Reallusion CC3/CC4 splits the neck into twist joints; either drives the head chain.
+ ['neckTwist01', 'Neck'], ['neckTwist02', 'Neck'],
+ // Roblox R15 (`LowerTorso`/`UpperTorso`) and R6 (`Torso`), plus the generic
+ // single-torso spellings simple rigs use. The pelvis IS the lower torso in
+ // R15, and the chest maps to Spine1 like VRM's `chest`.
+ ['torso', 'Spine'], ['waist', 'Spine'],
+ ['upperTorso', 'Spine1'], ['torsoUpper', 'Spine1'],
+ ['lowerTorso', 'Hips'], ['torsoLower', 'Hips'],
+ ['ribcage', 'Spine1'], ['ribs', 'Spine1'],
+ // Second Life / OpenSim centre chain (`m`-prefixed body bones).
+ ['mPelvis', 'Hips'], ['mTorso', 'Spine'], ['mChest', 'Spine1'],
+ ['mNeck', 'Neck'], ['mHead', 'Head'],
+ // Advanced Skeleton (Maya) tags centre bones with an `_M` side token:
+ // `Root_M`, `Spine1_M`, `Spine2_M`, `Chest_M`, `Neck_M`, `Head_M`. Its LIMBS
+ // use `_L`/`_R` and already resolve through the sided table, which is why
+ // these rigs arrived with working arms and legs but no Hips: and no Hips
+ // means the retargeter has no root to anchor to, so nothing animated at all.
+ // AS numbers its spine from 1 at the base, one deeper than the canonical
+ // chain, hence the shift (`Spine1_M` → Spine, `Spine2_M` → Spine1).
+ ['root_M', 'Hips'], ['hip_M', 'Hips'], ['pelvis_M', 'Hips'],
+ ['spine1_M', 'Spine'], ['spine2_M', 'Spine1'], ['spine3_M', 'Spine2'],
+ ['chest_M', 'Spine2'], ['neck_M', 'Neck'], ['head_M', 'Head'],
+ // A zero-indexed spine base (`j_spine_0`, `spine_00`) is the first spine
+ // joint; the `_1`/`_2` links already resolve as Spine1/Spine2.
+ ['spine0', 'Spine'],
+ // UniGLTF/VRM-converter root joint.
+ ['hipMaster', 'Hips'],
+ // Anatomical-Latin rigs. Scan pipelines, medical/anatomy kits, and the
+ // ZBrush/Blender anatomy libraries name every joint for the bone itself
+ // rather than for its role: `pelvis` (already mapped via the Unreal table),
+ // `lumbar`, `thoracic`, `sternum`, `cervical`, `cranium`, with `humerus.L`,
+ // `femur.L` and friends on the limbs below. The whole convention previously
+ // mapped 3 of 52 joints and animated nothing at all.
+ ['lumbar', 'Spine'], ['thoracic', 'Spine1'], ['sternum', 'Spine2'],
+ ['cervical', 'Neck'], ['cranium', 'Head'], ['skull', 'Head'],
+ ]) put(v, c);
+
+ // Side-paired limb bones, given as the LEFT spelling + its canonical; the
+ // right twin is derived by swapping the side token (left→right, leading l→r,
+ // trailing L→R). Covers VRM 1.0 camelCase, Daz/Genesis (`lShldr`, `lThigh`),
+ // and simple rigs (`shoulderL`, `elbowL`, `hipL`).
+ const SIDED = [
+ ['leftUpperArm', 'LeftArm'], ['lUpperArm', 'LeftArm'], ['shoulderL', 'LeftArm'], ['lShldr', 'LeftArm'], ['lShldrBend', 'LeftArm'],
+ ['leftLowerArm', 'LeftForeArm'], ['lLowerArm', 'LeftForeArm'], ['elbowL', 'LeftForeArm'], ['lForeArm', 'LeftForeArm'], ['lForearmBend', 'LeftForeArm'],
+ // Rigify/Blender anatomical spelling (`forearm.L`, `upper_arm.L`): the side
+ // is a `.L`/`.R` SUFFIX, so it normalises to `forearml`, which none of the
+ // side-PREFIX spellings above (`lForeArm`, `lLowerArm`) reach. Without this
+ // the elbow bone drops and every Rigify-rigged character (Quaternius, many
+ // Blender exports) animates with a rigid, unbending forearm.
+ ['forearmL', 'LeftForeArm'], ['upperArmL', 'LeftArm'],
+ ['wristL', 'LeftHand'], ['lHand', 'LeftHand'],
+ ['lCollar', 'LeftShoulder'], ['collarL', 'LeftShoulder'], ['lClavicle', 'LeftShoulder'],
+ ['leftUpperLeg', 'LeftUpLeg'], ['lUpperLeg', 'LeftUpLeg'], ['hipL', 'LeftUpLeg'], ['lThigh', 'LeftUpLeg'], ['lThighBend', 'LeftUpLeg'],
+ ['leftLowerLeg', 'LeftLeg'], ['lLowerLeg', 'LeftLeg'], ['kneeL', 'LeftLeg'], ['shinL', 'LeftLeg'], ['lShin', 'LeftLeg'], ['lCalf', 'LeftLeg'],
+ ['ankleL', 'LeftFoot'], ['lFoot', 'LeftFoot'],
+ ['leftToes', 'LeftToeBase'], ['toeL', 'LeftToeBase'], ['lToe', 'LeftToeBase'], ['lToeBase', 'LeftToeBase'],
+ // Generic side-prefix auto-riggers (some Meshy/Tripo + simple rigs) emit the
+ // canonical short bone name behind a bare `L_`/`R_` side token: `L_Arm`,
+ // `L_Leg`, `L_UpLeg`, `L_Shoulder`. The right twin is derived by the l→r rule.
+ ['lArm', 'LeftArm'], ['lShoulder', 'LeftShoulder'], ['lLeg', 'LeftLeg'], ['lUpLeg', 'LeftUpLeg'],
+ // SMPL / SMPL-X and other research-pipeline skeletons (text-to-avatar
+ // generators, mocap tooling) spell every limb joint as a side word plus the
+ // anatomical joint: `left_hip`, `left_knee`, `left_ankle`, `left_elbow`,
+ // `left_wrist`, `left_collar`. The same spellings appear in hand-built
+ // `leftKnee`-style rigs. Without these the whole lower body drops and a
+ // SMPL-derived avatar glides around on frozen legs.
+ ['leftHip', 'LeftUpLeg'], ['leftThigh', 'LeftUpLeg'],
+ ['leftKnee', 'LeftLeg'], ['leftShin', 'LeftLeg'], ['leftCalf', 'LeftLeg'],
+ ['leftAnkle', 'LeftFoot'],
+ ['leftElbow', 'LeftForeArm'],
+ ['leftWrist', 'LeftHand'],
+ ['leftCollar', 'LeftShoulder'], ['leftClavicle', 'LeftShoulder'],
+ ['leftToe', 'LeftToeBase'],
+ // Second Life / OpenSim limb chain: `m`-prefixed with a trailing side word
+ // (`mCollarLeft`, `mShoulderLeft`, `mKneeLeft`). `mShoulder` is the upper
+ // arm (the clavicle is `mCollar`), and the ankle is the articulating foot
+ // joint; `mFoot` (the ball, between ankle and toe) drives the toe bone.
+ ['mCollarLeft', 'LeftShoulder'], ['mShoulderLeft', 'LeftArm'],
+ ['mElbowLeft', 'LeftForeArm'], ['mWristLeft', 'LeftHand'],
+ ['mHipLeft', 'LeftUpLeg'], ['mKneeLeft', 'LeftLeg'],
+ ['mAnkleLeft', 'LeftFoot'], ['mFootLeft', 'LeftToeBase'], ['mToeLeft', 'LeftToeBase'],
+ // Side-SUFFIX leg spellings (`UpperLeg.L`, `LowerLeg.R`, `LowerArm.L`). The
+ // arm twins were added with the Rigify forearm fix, but the LEG twins were
+ // not, and the side-PREFIX entries above (`leftUpperLeg`, `lUpperLeg`) never
+ // reach `upperlegl`. Found by scripts/audit-rig-coverage.mjs against real
+ // stored avatars: a Blender-exported rig using this convention lost BOTH leg
+ // joints on each side and animated gliding on frozen legs.
+ ['upperLegL', 'LeftUpLeg'], ['lowerLegL', 'LeftLeg'], ['lowerArmL', 'LeftForeArm'],
+ // The scapula is the clavicle in Advanced Skeleton / Daz-derived rigs.
+ ['scapulaL', 'LeftShoulder'],
+ // Bare side-PREFIX anatomical joints (`j_L_hip`, `L_knee`, `R_ankle`). The
+ // suffix twins (`hipL`, `kneeL`, `ankleL`) exist above but never reach the
+ // prefix spelling. Same audit finding as the `j_` strip: Sketchfab-exported
+ // rigs using this convention mapped zero bones.
+ ['lHip', 'LeftUpLeg'], ['lKnee', 'LeftLeg'], ['lAnkle', 'LeftFoot'],
+ ['lElbow', 'LeftForeArm'], ['lWrist', 'LeftHand'], ['lToes', 'LeftToeBase'],
+ // Anatomical-Latin limbs, in both the side-SUFFIX (`humerus.L`) and
+ // side-PREFIX (`l_humerus`) spellings these rigs ship in. The clavicle
+ // (`scapula`) is already covered above. Radius and ulna are both forearm
+ // joints and fibula is a lower-leg joint: whichever the rig actually skins
+ // to is the one the retargeter binds (first-bone-wins), and either drives
+ // the same limb segment.
+ ['humerusL', 'LeftArm'], ['lHumerus', 'LeftArm'],
+ ['ulnaL', 'LeftForeArm'], ['lUlna', 'LeftForeArm'],
+ ['radiusL', 'LeftForeArm'], ['lRadius', 'LeftForeArm'],
+ ['carpusL', 'LeftHand'], ['lCarpus', 'LeftHand'],
+ ['femurL', 'LeftUpLeg'], ['lFemur', 'LeftUpLeg'],
+ ['tibiaL', 'LeftLeg'], ['lTibia', 'LeftLeg'],
+ ['fibulaL', 'LeftLeg'], ['lFibula', 'LeftLeg'],
+ ['talusL', 'LeftFoot'], ['lTalus', 'LeftFoot'],
+ ['tarsusL', 'LeftFoot'], ['lTarsus', 'LeftFoot'],
+ ['calcaneusL', 'LeftFoot'], ['lCalcaneus', 'LeftFoot'],
+ ['metatarsusL', 'LeftToeBase'], ['lMetatarsus', 'LeftToeBase'],
+ ];
+
+ // Finger conventions the side-suffix `Index1L` family below does not reach.
+ // Fingers are 30 of the clip library's 53 tracks, so a rig whose hands don't
+ // name-map scores ~40% coverage and falls under animation-retarget.js's
+ // MIN_COVERAGE gate: production then builds NO action for it and the avatar
+ // stands in its bind pose. Every convention here was measured doing exactly
+ // that by scripts/animation-dignity-sweep.mjs before these entries landed.
+ for (const [vf, cf] of [
+ ['Thumb', 'Thumb'], ['Index', 'Index'], ['Middle', 'Middle'],
+ ['Ring', 'Ring'], ['Pinky', 'Pinky'], ['Little', 'Pinky'],
+ ]) {
+ const lf = vf.toLowerCase();
+ for (let n = 1; n <= 3; n++) {
+ // Daz / Genesis side-PREFIX numbering: `lIndex1`, `rPinky3`. (Genesis
+ // abbreviates the middle finger to `lMid1`, handled just below.)
+ SIDED.push([`l${vf}${n}`, `LeftHand${cf}${n}`]);
+ // Blender Rigify: `f_index.01.L`, `f_pinky.03.R`, and the thumb's own
+ // `thumb.01.L` spelling (Rigify drops the `f_` there).
+ SIDED.push([`f_${lf}.0${n}.L`, `LeftHand${cf}${n}`]);
+ SIDED.push([`${lf}.0${n}.L`, `LeftHand${cf}${n}`]);
+ // MakeHuman numbers the digits 1..5 from the thumb: `finger1-2.L` is the
+ // thumb's middle phalanx, `finger5-1.R` the right pinky's first.
+ const digit = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky'].indexOf(cf) + 1;
+ if (digit > 0) SIDED.push([`finger${digit}-${n}.L`, `LeftHand${cf}${n}`]);
+ }
+ // VRM 1.0 and anatomical rigs name the phalanges instead of numbering them:
+ // proximal / intermediate / distal, with the thumb starting at its
+ // metacarpal (which is the canonical set's `Thumb1`). VRM 1.0 puts the side
+ // first (`leftIndexProximal`); anatomy-kit rigs put it last
+ // (`index_proximal.L`). Both spellings are listed so either resolves.
+ const phalanges =
+ cf === 'Thumb'
+ ? ['Metacarpal', 'Proximal', 'Distal']
+ : ['Proximal', 'Intermediate', 'Distal'];
+ phalanges.forEach((phalanx, i) => {
+ SIDED.push([`left${vf}${phalanx}`, `LeftHand${cf}${i + 1}`]);
+ SIDED.push([`${lf}_${phalanx.toLowerCase()}.L`, `LeftHand${cf}${i + 1}`]);
+ });
+ }
+ // Genesis abbreviates only the middle finger.
+ for (let n = 1; n <= 3; n++) SIDED.push([`lMid${n}`, `LeftHandMiddle${n}`]);
+ // Side-suffix finger chains, both conventions found in real uploaded avatars by
+ // scripts/audit-rig-coverage.mjs:
+ // • Blender / MakeHuman: `Index.L`, `Index2.L`, `Middle1.L`, `Thumb.L`, `Ring2.R`
+ // • Advanced Skeleton/Maya: `IndexFinger1_R`, `MiddleFinger2_L`, `ThumbFinger3_R`
+ // The un-numbered spelling (`Thumb.L`, `Index.L`) is the FIRST phalanx: those
+ // rigs number only the joints after it. Metacarpals (`Palm1.L`) are deliberately
+ // skipped: the canonical set has no metacarpal, so there is nothing to drive.
+ for (const [vf, cf] of [
+ ['Thumb', 'Thumb'], ['Index', 'Index'], ['Middle', 'Middle'],
+ ['Ring', 'Ring'], ['Pinky', 'Pinky'], ['Little', 'Pinky'],
+ ]) {
+ for (let n = 1; n <= 3; n++) {
+ SIDED.push([`${vf}${n}L`, `LeftHand${cf}${n}`]);
+ SIDED.push([`${vf}Finger${n}L`, `LeftHand${cf}${n}`]);
+ }
+ SIDED.push([`${vf}L`, `LeftHand${cf}1`]);
+ SIDED.push([`${vf}FingerL`, `LeftHand${cf}1`]);
+ }
+
+ for (const [lv, lc] of SIDED) {
+ put(lv, lc);
+ const rc = lc.replace(/^Left/, 'Right');
+ let rv;
+ if (/^left/.test(lv)) rv = lv.replace(/^left/, 'right');
+ else if (/^l[A-Z]/.test(lv)) rv = 'r' + lv.slice(1);
+ else if (/Left$/.test(lv)) rv = lv.replace(/Left$/, 'Right');
+ else if (/L$/.test(lv)) rv = lv.replace(/L$/, 'R');
+ else rv = lv;
+ put(rv, rc);
+ }
+ return m;
+})();
+
+/**
+ * Reduce a bone name to its canonical form, or null if it doesn't
+ * correspond to a recognised humanoid bone.
+ *
+ * @param {string} name
+ * @returns {string|null}
+ */
+export function canonicalizeBoneName(name) {
+ if (typeof name !== 'string' || !name) return null;
+ const direct = _lookupBone(name);
+ if (direct) return direct;
+ // glTF/FBX node de-dup suffix: exporters (CharacterStudio, Blender's glTF
+ // writer, FBX2glTF) append `_NN` to keep node names unique, producing
+ // `mixamorig:Hips_01`, `Spine1_03`, `LeftForeArm_010`. The plain lookup
+ // can't see past the suffix, so retry once with a trailing `_<digits>`
+ // removed: but only when the un-stripped form didn't already resolve, so a
+ // genuinely numbered bone like `left_hand_index_1` still maps to
+ // `LeftHandIndex1` before we'd ever strip its index.
+ // `_NN` (glTF/FBX) and `.NNN` (Blender) are both node-de-dup suffixes.
+ const deduped = name.replace(/[._]\d+$/, '');
+ if (deduped !== name) return _lookupBone(deduped);
+ return null;
+}
+
+// Reduce a single bone-name variant to canonical form via the lookup table.
+// Strips vendor prefixes and separators; returns null on no match.
+function _lookupBone(name) {
+ let s = name;
+ // Strip a leading Maya / FBX / MotionBuilder namespace (one or more
+ // `identifier:` segments). Autodesk HumanIK exports every joint behind a
+ // character namespace: `Character1:Hips`, `Character1:LeftArm`,
+ // `Character1:LeftUpLeg`: whose stems are already canonical, so removing the
+ // namespace makes the whole HumanIK / MotionBuilder rig drivable. Maya
+ // referenced rigs and OptiTrack/mocap subjects use the same `subject:bone`
+ // (and nested `char:ns:bone`) convention. Runs first so it also normalises
+ // the colon form of any vendor prefix below (`mixamorig:`, `Armature:`).
+ // Safe by construction: a stripped name that isn't a real bone (`prop:Sword`
+ // → `Sword`) simply falls through to null and is left untouched.
+ s = s.replace(/^(?:[A-Za-z][\w]*:)+/, '');
+ // Strip well-known vendor prefixes (case-insensitive, in priority order).
+ s = s.replace(/^mixamorig\d*[_:]?/i, '');
+ s = s.replace(/^Armature[_/]?/i, '');
+ s = s.replace(/^(DEF|ORG|MCH)[-_]/i, '');
+ // CharacterStudio exports prefix every joint `CH_` (`CH_Hips`, `CH_LeftUpLeg`),
+ // whose stems are otherwise canonical: strip it like any other vendor prefix.
+ s = s.replace(/^CH[_:]/i, '');
+ // Reallusion Character Creator 3/4 prefixes every joint `CC_Base_`
+ // (`CC_Base_Hip`, `CC_Base_L_Upperarm`, `CC_Base_L_Calf`, `CC_Base_NeckTwist01`);
+ // once the prefix is gone the stems resolve through the sided/centre alias
+ // tables below. Without this an entire CC export maps zero bones and lands in
+ // a bind-pose T-pose.
+ s = s.replace(/^CC_Base_/i, '');
+ // Sketchfab / Maya joint exports prefix every joint `j_` (`j_pelvis`, `j_L_hip`,
+ // `j_spine_0`). Stripping it leaves stems the canonical + sided tables resolve.
+ // The negative lookahead protects VRM/VRoid, whose `J_Bip_*` / `J_Sec_*` names
+ // are matched WHOLE by the alias table: stripping `J_` there would corrupt the
+ // key and drop an entire VRoid rig. Found by scripts/audit-rig-coverage.mjs:
+ // these rigs previously mapped ZERO bones and shipped a bind-pose T-pose.
+ s = s.replace(/^j_(?!bip|sec|adj)/i, '');
+ // UniGLTF / VRM-converter exports number every node and may flag it with `!`:
+ // `5.joint_HipMaster`, `10.!joint_LeftToe`, `95.!Root`. Strip the index, the
+ // flag, and the `joint_` noun so the residual bone name resolves.
+ s = s.replace(/^\d+\./, '').replace(/^!/, '').replace(/^joint[_:]/i, '');
+ // 3ds Max Biped names joints `Bip01 Pelvis`, `Bip001 L UpperArm`, … with a
+ // space- or underscore-separated `Bip<NN>` prefix (the digits identify the
+ // character). Strip it so `Pelvis`/`Spine`/`L UpperArm`/`L Thigh`/`L Calf`
+ // reach the canonical + sided tables instead of T-posing.
+ s = s.replace(/^Bip\d+[\s_]?/i, '');
+ // Collapse separators so `Left_Arm`, `left-arm`, `left arm`, `LeftArm`,
+ // `upperarm.L` all reach the same lookup key (`.` covers Blender/MakeHuman).
+ const key = s.replace(/[-_.\s]+/g, '').toLowerCase();
+ // Canonical/Mixamo/Rigify spellings first, then the Unreal-mannequin aliases,
+ // then the extended VRM/Daz/MakeHuman/simple-rig table (lowest priority, so it
+ // only catches names the first two don't already resolve).
+ return LOOKUP.get(key) ?? UNREAL_ALIASES.get(key) ?? EXTRA_ALIASES.get(key) ?? null;
+}
+
+// A joint spelled like the shoulder blade / collar bone rather than the limb.
+const CLAVICLE_SPELLING = /shoulder|clavicle|collar|scapula/i;
+// A joint spelled like the upper arm itself.
+const UPPER_ARM_SPELLING = /upper.?arm|humerus/i;
+// Clavicle-only spellings: `shoulder` is deliberately absent, because SMPL-style
+// rigs use it FOR the upper arm (`left_shoulder`) and name the clavicle
+// `left_collar`. Used by the mirror-image pass.
+const COLLAR_ONLY_SPELLING = /clavicle|collar|scapula/i;
+
+/**
+ * Resolve the clavicle / upper-arm naming collision on a canonicalization plan.
+ *
+ * Anatomical rigs give the two bones names that normalize onto ONE canonical
+ * name, and no name-only table can separate them, because the same spelling
+ * means different bones on different rigs:
+ *
+ * - Rigify names the clavicle `shoulder.L` and the upper arm `upper_arm.L`;
+ * both resolve to `LeftArm`, so the clip's arm rotation binds to the
+ * clavicle and the arm swings from the shoulder blade.
+ * - SMPL names the clavicle `left_collar` and the upper arm `left_shoulder`;
+ * both resolve to `LeftShoulder`, leaving `LeftArm` vacant and the arm clip
+ * unbound entirely.
+ * - The hand-built hobby rig spells its upper arm `shoulderL` with no clavicle
+ * at all, so re-pointing that spelling would freeze its arms.
+ *
+ * The collision is therefore resolved by contention, not by spelling: a target
+ * is only reassigned when two joints contest it AND the sibling target is free,
+ * so a rig without the collision is never touched. When more than one contender
+ * is eligible and the caller supplies an `isAncestor` test, skeleton hierarchy
+ * breaks the tie: the clavicle is the parent of the upper arm.
+ *
+ * Mutates each entry's `canonical` in place.
+ *
+ * @param {Array<{raw: string, canonical: string}>} plan candidate assignments
+ * @param {{ isAncestor?: (a: object, b: object) => boolean }} [opts]
+ * @returns {number} entries reassigned
+ */
+export function resolveArmShoulderCollisions(plan, opts = {}) {
+ const isAncestor = typeof opts.isAncestor === 'function' ? opts.isAncestor : null;
+ const count = new Map();
+ for (const p of plan) count.set(p.canonical, (count.get(p.canonical) || 0) + 1);
+
+ // When spelling leaves more than one entry eligible, hierarchy decides: the
+ // clavicle is an ANCESTOR of the upper arm. `related` holds the contenders on
+ // the other side of that relation. Falls back to document order when the
+ // caller gave us no hierarchy to read (or none of the pairs are related).
+ const byHierarchy = (eligible, related, aboveRelated) => {
+ if (eligible.length < 2 || !isAncestor) return eligible[0];
+ const match = eligible.find((e) =>
+ related.some((o) => o !== e && (aboveRelated ? isAncestor(e, o) : isAncestor(o, e))),
+ );
+ return match || eligible[0];
+ };
+
+ const move = (entry, from, to) => {
+ entry.canonical = to;
+ count.set(from, (count.get(from) || 1) - 1);
+ count.set(to, (count.get(to) || 0) + 1);
+ };
+
+ let changed = 0;
+ // Arm contested (Rigify): demote the clavicle-spelled contender to Shoulder.
+ for (const side of ['Left', 'Right']) {
+ const arm = `${side}Arm`;
+ const shoulder = `${side}Shoulder`;
+ if ((count.get(arm) || 0) < 2 || (count.get(shoulder) || 0) > 0) continue;
+ const contenders = plan.filter((p) => p.canonical === arm);
+ const upperArms = contenders.filter((p) => UPPER_ARM_SPELLING.test(p.raw));
+ if (upperArms.length === 0) continue;
+ const eligible = contenders.filter(
+ (p) => CLAVICLE_SPELLING.test(p.raw) && !UPPER_ARM_SPELLING.test(p.raw),
+ );
+ const pick = byHierarchy(eligible, upperArms, true);
+ if (!pick) continue;
+ move(pick, arm, shoulder);
+ changed++;
+ }
+
+ // Shoulder contested (SMPL): promote the shoulder-spelled contender to Arm.
+ for (const side of ['Left', 'Right']) {
+ const arm = `${side}Arm`;
+ const shoulder = `${side}Shoulder`;
+ if ((count.get(shoulder) || 0) < 2 || (count.get(arm) || 0) > 0) continue;
+ const contenders = plan.filter((p) => p.canonical === shoulder);
+ const collars = contenders.filter((p) => COLLAR_ONLY_SPELLING.test(p.raw));
+ if (collars.length === 0) continue;
+ const eligible = contenders.filter(
+ (p) => /shoulder/i.test(p.raw) && !COLLAR_ONLY_SPELLING.test(p.raw),
+ );
+ const pick = byHierarchy(eligible, collars, false);
+ if (!pick) continue;
+ move(pick, shoulder, arm);
+ changed++;
+ }
+ return changed;
+}
+
+// Whether glTF node `a` is an ancestor of node `b`, walking up `parentOf`.
+// Tolerates the cyclic parentage a malformed GLB can carry: the visited set
+// stops the walk instead of looping forever.
+function isAncestorNode(parentOf, aIndex, bIndex) {
+ if (aIndex == null || bIndex == null || aIndex === bIndex) return false;
+ const seen = new Set([bIndex]);
+ for (let cur = parentOf.get(bIndex); cur != null && !seen.has(cur); cur = parentOf.get(cur)) {
+ if (cur === aIndex) return true;
+ seen.add(cur);
+ }
+ return false;
+}
+
+/**
+ * Walk a parsed glTF JSON object and canonicalize joint-node names in place.
+ * Only nodes referenced from `skins[].joints[]` are touched: non-bone nodes
+ * (meshes, cameras, lights) keep their original names.
+ *
+ * @param {object} json - parsed glTF JSON
+ * @returns {{ renamed: number, samples: Array<{ from: string, to: string }> }}
+ */
+export function canonicalizeJointNodes(json) {
+ if (!json || !Array.isArray(json.nodes) || !Array.isArray(json.skins)) {
+ return { renamed: 0, samples: [] };
+ }
+ const jointIndices = new Set();
+ for (const skin of json.skins) {
+ if (Array.isArray(skin.joints)) {
+ for (const idx of skin.joints) jointIndices.add(idx);
+ }
+ }
+ // Pass 1: resolve each joint to a canonical target (or null).
+ const plan = [];
+ for (const idx of jointIndices) {
+ const node = json.nodes[idx];
+ if (!node || typeof node.name !== 'string') continue;
+ const canonical = canonicalizeBoneName(node.name);
+ if (!canonical || canonical === node.name) continue;
+ plan.push({ node, index: idx, raw: node.name, canonical });
+ }
+
+ // Pass 1.5/1.6: the clavicle/upper-arm collision, resolved by the shared
+ // resolver the runtime lane also uses.
+ const parentOf = new Map();
+ json.nodes.forEach((n, i) => {
+ if (Array.isArray(n.children)) for (const c of n.children) parentOf.set(c, i);
+ });
+ resolveArmShoulderCollisions(plan, {
+ isAncestor: (a, b) => isAncestorNode(parentOf, a.index, b.index),
+ });
+
+ // Pass 2: apply. A canonical name is assigned at most once: when two joints
+ // still resolve to the same target after collision resolution (SMPL's
+ // ankle+foot chain, CC's NeckTwist01/02), or the target spelling already
+ // belongs to a joint that isn't being renamed, later renames are skipped.
+ // Duplicate node names make the animation bind ambiguous (getObjectByName
+ // picks an arbitrary twin), which is strictly worse than leaving the extra
+ // joint unmapped. glTF joints are listed parent-first, so first-wins keeps
+ // the parent joint (the one that actually articulates the limb).
+ const planned = new Set(plan.map((p) => p.node));
+ const taken = new Set();
+ for (const idx of jointIndices) {
+ const node = json.nodes[idx];
+ if (node && typeof node.name === 'string' && !planned.has(node)) taken.add(node.name);
+ }
+ let renamed = 0;
+ const samples = [];
+ for (const p of plan) {
+ if (taken.has(p.canonical)) continue;
+ taken.add(p.canonical);
+ if (samples.length < 5) samples.push({ from: p.raw, to: p.canonical });
+ p.node.name = p.canonical;
+ renamed++;
+ }
+ return { renamed, samples };
+}
+
+// Local TRS → Matrix4 for a glTF node.
+function nodeLocalMatrix(node) {
+ const t = new Vector3();
+ const r = new Quaternion();
+ const s = new Vector3(1, 1, 1);
+ if (node.translation) t.fromArray(node.translation);
+ if (node.rotation) r.fromArray(node.rotation);
+ if (node.scale) s.fromArray(node.scale);
+ return new Matrix4().compose(t, r, s);
+}
+
+// World matrices for a set of node indices, each walked to its scene root.
+function worldMatricesFor(json, indices, parentOf) {
+ const local = json.nodes.map(nodeLocalMatrix);
+ const cache = new Map();
+ const visiting = new Set();
+ const world = (idx) => {
+ if (cache.has(idx)) return cache.get(idx);
+ // Guard against cyclic parentage in malformed GLBs: treat the cycle root
+ // as a top-level node (identity parent) rather than blowing the call stack.
+ if (visiting.has(idx)) return local[idx].clone();
+ visiting.add(idx);
+ const p = parentOf.get(idx);
+ const m = p == null ? local[idx].clone() : world(p).clone().multiply(local[idx]);
+ visiting.delete(idx);
+ cache.set(idx, m);
+ return m;
+ };
+ const out = new Map();
+ for (const idx of indices) out.set(idx, world(idx));
+ return out;
+}
+
+/**
+ * Fold a Mixamo/FBX up-axis bake out of the rig. Mixamo exports put a +90°X on
+ * the armature node and a −90°X on Hips; the net is upright, but a clip authored
+ * for an identity-Hips rig overwrites the −90°X and tips the body over (the
+ * "lying down" bug). The runtime retargeter (animation-retarget.js) corrects for
+ * this on the fly, but normalizing at ingest means stored avatars are already
+ * axis-aligned and need no correction.
+ *
+ * The fold pushes the armature's rotation down into each child (rotating its
+ * translation, pre-multiplying its rotation) and zeroes the armature's rotation.
+ * Bone *world* matrices are preserved exactly: provided the armature's scale is
+ * uniform, so rotation commutes with it: which means the skinned mesh and its
+ * inverse-bind matrices (in the untouched BIN chunk) still resolve to the same
+ * bind pose. A counter-rotated Hips collapses to identity. Verified by comparing
+ * world matrices before/after; reverts on any mismatch. Mutates `json` in place.
+ *
+ * @param {object} json parsed glTF JSON
+ * @returns {{ corrected: boolean, hipsIdentity?: boolean }}
+ */
+export function canonicalizeArmatureOrientation(json) {
+ if (!json || !Array.isArray(json.nodes) || !Array.isArray(json.skins)) {
+ return { corrected: false };
+ }
+ const parentOf = new Map();
+ json.nodes.forEach((n, i) => {
+ if (Array.isArray(n.children)) for (const c of n.children) parentOf.set(c, i);
+ });
+ const jointIdx = new Set();
+ for (const skin of json.skins) {
+ if (Array.isArray(skin.joints)) for (const j of skin.joints) jointIdx.add(j);
+ }
+ if (jointIdx.size === 0) return { corrected: false };
+
+ let hips = -1;
+ for (const idx of jointIdx) {
+ const n = json.nodes[idx];
+ if (n && typeof n.name === 'string' && canonicalizeBoneName(n.name) === 'Hips') {
+ hips = idx;
+ break;
+ }
+ }
+ if (hips < 0) return { corrected: false };
+ const pIdx = parentOf.get(hips);
+ if (pIdx == null) return { corrected: false };
+ const parent = json.nodes[pIdx];
+
+ const r = new Quaternion();
+ if (parent.rotation) r.fromArray(parent.rotation);
+ if (1 - Math.abs(r.w) < ORIENT_EPS) return { corrected: false }; // already axis-aligned
+
+ // Rotation only commutes with the parent's scale when that scale is uniform.
+ const s = parent.scale;
+ if (s && (Math.abs(s[0] - s[1]) > ORIENT_EPS || Math.abs(s[1] - s[2]) > ORIENT_EPS)) {
+ return { corrected: false };
+ }
+
+ const children = Array.isArray(parent.children) ? parent.children : [];
+ if (children.length === 0) return { corrected: false };
+
+ // Snapshot the children (for revert) and all affected world matrices (to verify
+ // the fold didn't move anything the mesh depends on).
+ const checkSet = new Set([...jointIdx, ...children]);
+ const before = worldMatricesFor(json, checkSet, parentOf);
+ const snapshot = children.map((c) => ({
+ idx: c,
+ translation: json.nodes[c].translation ? json.nodes[c].translation.slice() : null,
+ rotation: json.nodes[c].rotation ? json.nodes[c].rotation.slice() : null,
+ }));
+ const parentRotBefore = parent.rotation ? parent.rotation.slice() : null;
+
+ for (const c of children) {
+ const node = json.nodes[c];
+ const t = new Vector3();
+ if (node.translation) t.fromArray(node.translation);
+ t.applyQuaternion(r);
+ node.translation = [t.x, t.y, t.z];
+ const cr = new Quaternion();
+ if (node.rotation) cr.fromArray(node.rotation);
+ cr.premultiply(r);
+ node.rotation = [cr.x, cr.y, cr.z, cr.w];
+ }
+ parent.rotation = [0, 0, 0, 1];
+
+ const after = worldMatricesFor(json, checkSet, parentOf);
+ let ok = true;
+ for (const idx of checkSet) {
+ const a = before.get(idx).elements;
+ const b = after.get(idx).elements;
+ for (let k = 0; k < 16; k++) {
+ if (Math.abs(a[k] - b[k]) > ORIENT_WORLD_EPS) {
+ ok = false;
+ break;
+ }
+ }
+ if (!ok) break;
+ }
+ if (!ok) {
+ for (const snap of snapshot) {
+ const node = json.nodes[snap.idx];
+ if (snap.translation) node.translation = snap.translation;
+ else delete node.translation;
+ if (snap.rotation) node.rotation = snap.rotation;
+ else delete node.rotation;
+ }
+ if (parentRotBefore) parent.rotation = parentRotBefore;
+ else delete parent.rotation;
+ return { corrected: false };
+ }
+
+ const hipsQ = new Quaternion();
+ if (json.nodes[hips].rotation) hipsQ.fromArray(json.nodes[hips].rotation);
+ return { corrected: true, hipsIdentity: 1 - Math.abs(hipsQ.w) < ORIENT_EPS };
+}
+
+/**
+ * Canonicalize joint bone names in a GLB ArrayBuffer. Returns a new buffer
+ * with renamed nodes (and the count of bones rewritten); the original buffer
+ * is left untouched. If no bones needed renaming the original buffer is
+ * returned by reference so callers can skip a redundant re-upload.
+ *
+ * Throws on a malformed GLB header so upload code can surface a clear error.
+ *
+ * @param {ArrayBuffer} arrayBuffer
+ * @returns {{ buffer: ArrayBuffer, renamed: number, samples: Array<{from:string,to:string}> }}
+ */
+export function canonicalizeGLBBones(arrayBuffer) {
+ if (!(arrayBuffer instanceof ArrayBuffer)) {
+ throw new TypeError('canonicalizeGLBBones: ArrayBuffer required');
+ }
+ if (arrayBuffer.byteLength < 20) {
+ throw new Error('canonicalizeGLBBones: buffer too small to be a GLB');
+ }
+ const view = new DataView(arrayBuffer);
+ if (view.getUint32(0, true) !== GLB_MAGIC) {
+ throw new Error('canonicalizeGLBBones: not a GLB (bad magic number)');
+ }
+ if (view.getUint32(4, true) !== 2) {
+ throw new Error('canonicalizeGLBBones: only GLB v2 is supported');
+ }
+
+ // Parse chunk 0 (JSON, required by spec).
+ const c0Len = view.getUint32(12, true);
+ const c0Type = view.getUint32(16, true);
+ if (c0Type !== CHUNK_TYPE_JSON) {
+ throw new Error('canonicalizeGLBBones: chunk 0 must be JSON');
+ }
+ const jsonBytes = new Uint8Array(arrayBuffer, 20, c0Len);
+ let json;
+ try {
+ json = JSON.parse(new TextDecoder().decode(jsonBytes));
+ } catch (err) {
+ throw new Error('canonicalizeGLBBones: JSON chunk parse failed: ' + err.message);
+ }
+
+ const { renamed, samples } = canonicalizeJointNodes(json);
+ const orientation = canonicalizeArmatureOrientation(json);
+ if (renamed === 0 && !orientation.corrected) {
+ return { buffer: arrayBuffer, renamed: 0, samples: [], orientationCorrected: false };
+ }
+
+ // Repack. Chunk 1 (BIN) is optional: preserve it verbatim if present.
+ const c1Offset = 20 + c0Len;
+ let c1Len = 0, c1Type = 0, binBytes = null;
+ if (c1Offset + 8 <= arrayBuffer.byteLength) {
+ c1Len = view.getUint32(c1Offset, true);
+ c1Type = view.getUint32(c1Offset + 4, true);
+ binBytes = new Uint8Array(arrayBuffer, c1Offset + 8, c1Len);
+ }
+
+ // Re-serialise JSON; GLB requires each chunk's data to be 4-byte aligned,
+ // padded with 0x20 (space) for the JSON chunk per the glTF 2.0 spec.
+ let newJsonBytes = new TextEncoder().encode(JSON.stringify(json));
+ const jsonPad = (4 - (newJsonBytes.length % 4)) % 4;
+ if (jsonPad) {
+ const padded = new Uint8Array(newJsonBytes.length + jsonPad);
+ padded.set(newJsonBytes);
+ for (let i = 0; i < jsonPad; i++) padded[newJsonBytes.length + i] = 0x20;
+ newJsonBytes = padded;
+ }
+
+ const totalLen = 12 + 8 + newJsonBytes.length + (binBytes ? 8 + binBytes.length : 0);
+ const out = new ArrayBuffer(totalLen);
+ const outView = new DataView(out);
+ const outU8 = new Uint8Array(out);
+
+ outView.setUint32(0, GLB_MAGIC, true);
+ outView.setUint32(4, 2, true);
+ outView.setUint32(8, totalLen, true);
+
+ outView.setUint32(12, newJsonBytes.length, true);
+ outView.setUint32(16, CHUNK_TYPE_JSON, true);
+ outU8.set(newJsonBytes, 20);
+
+ if (binBytes) {
+ const binOffset = 20 + newJsonBytes.length;
+ outView.setUint32(binOffset, c1Len, true);
+ outView.setUint32(binOffset + 4, c1Type, true);
+ outU8.set(binBytes, binOffset + 8);
+ }
+
+ return { buffer: out, renamed, samples, orientationCorrected: orientation.corrected };
+}
diff --git a/packages/ar-studio/src/ar-launch.js b/packages/ar-studio/src/ar-launch.js
new file mode 100644
index 000000000..cdc429555
--- /dev/null
+++ b/packages/ar-studio/src/ar-launch.js
@@ -0,0 +1,124 @@
+// "View in your space": device-aware AR routing for a single model.
+//
+// Pure and dependency-free, so it runs identically in a browser, in a Node
+// server, and inside the MCP server in this package. Given a GLB URL and a
+// User-Agent it decides how that model should reach someone's room:
+//
+// iOS → Apple AR Quick Look (a USDZ generated from the GLB in-page by
+// model-viewer's three.js USDZExporter: a real conversion, no
+// server-side USD tooling anywhere).
+// Android → Google Scene Viewer through an ARCore intent:// URL, with a
+// browser fallback so a device without ARCore lands on the viewer
+// instead of an error screen.
+// desktop → the interactive WebGL viewer.
+//
+// Ported from the three.ws AR lane (Apache-2.0), with the origin and the viewer
+// path made configurable so it can front your own pages.
+
+/** Where the hosted launch page and viewer live by default. */
+export const DEFAULT_ORIGIN = 'https://three.ws';
+
+export class ArUrlError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.name = 'ArUrlError';
+ this.code = code;
+ }
+}
+
+/**
+ * Accept a model URL an AR viewer will actually open: https, pointing at a
+ * .glb/.gltf file. Query strings are fine. Anything else throws a coded error
+ * the boundary turns into a clean message: device AR intents must never be
+ * handed a non-https URL.
+ *
+ * @param {unknown} glbUrl
+ * @returns {string} the normalized URL
+ */
+export function assertArAssetUrl(glbUrl) {
+ let u;
+ try {
+ u = new URL(String(glbUrl));
+ } catch {
+ throw new ArUrlError('invalid_url', 'Provide a valid https URL to a .glb model.');
+ }
+ if (u.protocol !== 'https:') throw new ArUrlError('not_https', 'The model URL must be https.');
+ if (!/\.(glb|gltf)$/i.test(u.pathname)) {
+ throw new ArUrlError('not_glb', 'The model URL must point at a .glb or .gltf file.');
+ }
+ return u.toString();
+}
+
+/** Classify the AR target from a User-Agent string. */
+export function detectArTarget(userAgent) {
+ const ua = String(userAgent || '');
+ // iPadOS 13+ reports a Mac UA; server-side we only have the string, so match
+ // the explicit iOS device tokens.
+ if (/\b(iphone|ipad|ipod)\b/i.test(ua)) return 'ios';
+ if (/\bandroid\b/i.test(ua)) return 'android';
+ return 'desktop';
+}
+
+/**
+ * The Android Scene Viewer ARCore intent URL for a GLB.
+ * @param {string} glbUrl
+ * @param {{title?: string, fallbackUrl?: string}} [opts]
+ */
+export function buildSceneViewerUrl(glbUrl, { title = '', fallbackUrl = '' } = {}) {
+ const params = new URLSearchParams({ file: glbUrl, mode: 'ar_preferred' });
+ if (title) params.set('title', title);
+ const fallback = fallbackUrl ? `S.browser_fallback_url=${encodeURIComponent(fallbackUrl)};` : '';
+ return (
+ `intent://arvr.google.com/scene-viewer/1.2?${params.toString()}`
+ + '#Intent;scheme=https;package=com.google.ar.core;'
+ + `action=android.intent.action.VIEW;${fallback}end;`
+ );
+}
+
+/** The interactive WebGL viewer URL for a GLB. */
+export function buildViewerUrl(origin, glbUrl, title = '') {
+ const base = String(origin || DEFAULT_ORIGIN).replace(/\/$/, '');
+ const t = title ? `&title=${encodeURIComponent(title)}` : '';
+ return `${base}/viewer?src=${encodeURIComponent(glbUrl)}${t}`;
+}
+
+/**
+ * The hosted, device-branching AR launch URL. Open it on any phone and it routes
+ * itself: Quick Look on iOS, Scene Viewer on Android, the viewer on desktop.
+ *
+ * @param {string} origin
+ * @param {string} glbUrl
+ * @param {string} [title]
+ * @param {{live?: boolean, endpoint?: string}} [opts] `live` marks a rigged avatar.
+ */
+export function buildArLaunchUrl(origin, glbUrl, title = '', { live = false, endpoint } = {}) {
+ const base = endpoint || `${String(origin || DEFAULT_ORIGIN).replace(/\/$/, '')}/api/ar`;
+ const t = title ? `&title=${encodeURIComponent(title)}` : '';
+ const k = live ? '&kind=avatar' : '';
+ return `${base}?src=${encodeURIComponent(glbUrl)}${t}${k}`;
+}
+
+/**
+ * Resolve every link for one model at once. `target` tells a caller which one the
+ * current device will actually use.
+ *
+ * @param {object} p
+ * @param {string} p.glbUrl
+ * @param {string} [p.userAgent]
+ * @param {string} [p.origin]
+ * @param {string} [p.title]
+ * @param {boolean} [p.live] A rigged avatar rather than a static prop.
+ * @returns {{target:'ios'|'android'|'desktop', action:'redirect'|'page', asset:string,
+ * viewerUrl:string, sceneViewerUrl:string, launchUrl:string, live:boolean}}
+ */
+export function planArLaunch({ glbUrl, userAgent, origin = DEFAULT_ORIGIN, title = '', live = false } = {}) {
+ const asset = assertArAssetUrl(glbUrl);
+ const target = detectArTarget(userAgent);
+ const viewerUrl = buildViewerUrl(origin, asset, title);
+ const sceneViewerUrl = buildSceneViewerUrl(asset, { title, fallbackUrl: viewerUrl });
+ const launchUrl = buildArLaunchUrl(origin, asset, title, { live });
+ // A live avatar always gets the launch page: a straight Scene Viewer redirect
+ // would place a frozen body and hide the animated path entirely.
+ const action = target === 'android' && !live ? 'redirect' : 'page';
+ return { target, action, asset, viewerUrl, sceneViewerUrl, launchUrl, live };
+}
diff --git a/packages/ar-studio/src/auto.js b/packages/ar-studio/src/auto.js
new file mode 100644
index 000000000..176031abd
--- /dev/null
+++ b/packages/ar-studio/src/auto.js
@@ -0,0 +1,30 @@
+// The zero-configuration entry point: importing this file registers <ar-studio>
+// and, if the page has no <ar-studio> element at all, mounts one full-screen.
+//
+// <script type="module" src="https://unpkg.com/3d-ar-studio/dist/ar-studio.js"></script>
+//
+// That single line is a working AR studio. Anything more deliberate should
+// import `createArStudio` instead.
+
+import { defineArStudio } from './element.js';
+import { createArStudio } from './index.js';
+
+defineArStudio();
+
+function autoMount() {
+ if (document.querySelector('ar-studio')) return;
+ const target = document.querySelector('[data-ar-studio]');
+ if (target) createArStudio(target, readOptions(target));
+ else if (document.documentElement.hasAttribute('data-ar-studio-auto')) createArStudio(document.body);
+}
+
+function readOptions(node) {
+ const assets = node.getAttribute('data-assets');
+ return assets ? { assets } : {};
+}
+
+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', autoMount, { once: true });
+else autoMount();
+
+export * from './index.js';
+export { defineArStudio, ArStudioElement } from './element.js';
diff --git a/packages/ar-studio/src/config.js b/packages/ar-studio/src/config.js
new file mode 100644
index 000000000..a17104da2
--- /dev/null
+++ b/packages/ar-studio/src/config.js
@@ -0,0 +1,165 @@
+// Configuration for an AR Studio instance.
+//
+// Everything the studio talks to is a URL, and every URL is overridable: that
+// is the whole point of this package. Drop it on your site and it pulls models
+// from three.ws by default; point `assets` at your own manifest (or pass your
+// own source objects) and it pulls from you instead, with no other change.
+//
+// Three layers, later wins:
+// 1. DEFAULTS below.
+// 2. The options object passed to createArStudio() / the <ar-studio> element.
+// 3. URL parameters on the hosting page, when `allowUrlOverride` is on:
+// ?assets=<https manifest url> swap the catalogue
+// ?src=<glb>&title=<name> deep-link models into the scene (repeatable)
+// ?room=<code> join a shared room
+// ?forge=<prompt> start a generation on load
+//
+// URL overrides are untrusted input. `assets` is accepted only as an https URL
+// and every model source it yields is re-validated by normalizeGlbUrl() before
+// it can reach the loader, so a hostile link can add a catalogue but can never
+// smuggle a `javascript:` or `data:` model into the scene.
+
+/** The public three.ws surfaces this package uses by default. All keyless, all CORS-open. */
+export const THREE_WS = {
+ origin: 'https://three.ws',
+ /** CC0 prop library (Poly Haven), served first-party with open CORS. */
+ objectsManifest: 'https://three.ws/cdn/objects/library/manifest.json',
+ /** The free, keyless 3D Studio MCP endpoint: the ChatGPT 3D Studio pipeline. */
+ studioMcp: 'https://three.ws/api/mcp-studio',
+ /** Pre-baked animation clips used to idle any humanoid rig. */
+ animationManifest: 'https://three.ws/animations/manifest.json',
+ /** Curated CC0 HDRIs for image-based lighting. */
+ hdri: {
+ studio: 'https://three.ws/hdri/studio.hdr',
+ outdoor: 'https://three.ws/hdri/outdoor.hdr',
+ sunset: 'https://three.ws/hdri/sunset.hdr',
+ },
+ /** Device-aware "View in your space" launcher (iOS Quick Look / Android Scene Viewer). */
+ arLaunch: 'https://three.ws/api/ar',
+ /** Colyseus host behind shared rooms. */
+ roomServer: 'wss://three-ws-multiplayer-93741856042.us-central1.run.app',
+};
+
+export const DEFAULTS = {
+ /** Catalogue(s) the "Add" tray offers. See src/sources/index.js for the accepted shapes. */
+ assets: 'three.ws',
+ /** Honour ?assets= / ?src= / ?room= / ?forge= on the hosting page's URL. */
+ allowUrlOverride: true,
+ /** Text-to-3D generation from inside the camera view. */
+ generate: {
+ enabled: true,
+ endpoint: THREE_WS.studioMcp,
+ /** 'model' (forge_free) or 'avatar' (text_to_avatar: rigged, walks and idles). */
+ kind: 'model',
+ tier: 'standard',
+ /** Give up on a single generation after this long. */
+ timeoutMs: 300000,
+ pollMs: 3000,
+ },
+ /** Live collaborative rooms. Set `enabled: false` to hide the Share-live control. */
+ rooms: {
+ enabled: true,
+ server: THREE_WS.roomServer,
+ },
+ /** Idle animation for humanoid models with no baked clips. */
+ animations: {
+ enabled: true,
+ manifestUrl: THREE_WS.animationManifest,
+ clip: 'idle',
+ },
+ /** Image-based lighting. `preset` picks from `urls`; null disables the HDRI fetch. */
+ lighting: {
+ preset: 'studio',
+ urls: THREE_WS.hdri,
+ },
+ /** "View in your space" hand-off for a single model (native AR viewers). */
+ arLaunchUrl: THREE_WS.arLaunch,
+ /** Chrome. `backHref: null` hides the back button entirely. */
+ branding: {
+ title: 'AR Studio',
+ backHref: null,
+ backLabel: 'Back',
+ accent: '#8b7cf8',
+ },
+ /** Base URL that share links + QR codes point at. Defaults to the page itself. */
+ shareBaseUrl: '',
+ /** localStorage key for the persisted scene. Change it to run two studios on one origin. */
+ persistKey: 'ar-studio:scene:v1',
+ /** Cap on simultaneous placements. Keeps low-end phones interactive. */
+ maxPlacements: 20,
+ /** Restore the last scene on load. */
+ persist: true,
+ /** Analytics/telemetry hook: called with (event, detail) for every notable action. */
+ onEvent: null,
+};
+
+function isPlainObject(v) {
+ return !!v && typeof v === 'object' && !Array.isArray(v);
+}
+
+/** Deep-merge `patch` onto `base` without mutating either. Arrays and class instances replace. */
+export function mergeConfig(base, patch) {
+ if (!isPlainObject(patch)) return base;
+ const out = { ...base };
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === undefined) continue;
+ out[k] = isPlainObject(v) && isPlainObject(base?.[k]) ? mergeConfig(base[k], v) : v;
+ }
+ return out;
+}
+
+/** Accept an https URL (or a same-origin relative path) from untrusted input. */
+export function safeUrl(raw) {
+ const s = String(raw ?? '').trim();
+ if (!s) return null;
+ if (s.startsWith('/') && !s.startsWith('//')) return s;
+ try {
+ const u = new URL(s);
+ return u.protocol === 'https:' ? u.href : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Resolve the effective config: defaults ← options ← URL parameters.
+ *
+ * @param {object} [options]
+ * @param {URLSearchParams|string} [search] Page query string (defaults to location.search).
+ * @returns {object} config, plus `urlModels` / `urlRoom` / `urlPrompt` read from the URL.
+ */
+export function resolveConfig(options = {}, search) {
+ const cfg = mergeConfig(DEFAULTS, options);
+ const params = search instanceof URLSearchParams
+ ? search
+ : new URLSearchParams(
+ typeof search === 'string'
+ ? search
+ : (typeof location !== 'undefined' ? location.search : ''),
+ );
+
+ const urlModels = [];
+ let urlRoom = '';
+ let urlPrompt = '';
+
+ if (cfg.allowUrlOverride) {
+ const assets = params.get('assets') || params.get('source');
+ const assetsUrl = assets ? safeUrl(assets) : null;
+ if (assetsUrl) cfg.assets = assetsUrl;
+
+ const srcs = params.getAll('src');
+ const titles = params.getAll('title');
+ for (let i = 0; i < srcs.length && urlModels.length < cfg.maxPlacements; i++) {
+ const src = safeUrl(srcs[i]);
+ if (src) urlModels.push({ src, title: String(titles[i] || '').slice(0, 120) });
+ }
+ urlRoom = String(params.get('room') || '').trim();
+ urlPrompt = String(params.get('forge') || params.get('prompt') || '').trim();
+ }
+
+ if (!cfg.shareBaseUrl && typeof location !== 'undefined') {
+ cfg.shareBaseUrl = `${location.origin}${location.pathname}`;
+ }
+
+ return { ...cfg, urlModels, urlRoom, urlPrompt };
+}
diff --git a/packages/ar-studio/src/element.js b/packages/ar-studio/src/element.js
new file mode 100644
index 000000000..bff73c950
--- /dev/null
+++ b/packages/ar-studio/src/element.js
@@ -0,0 +1,62 @@
+// <ar-studio>: the studio as a custom element.
+//
+// <script type="module" src="https://unpkg.com/3d-ar-studio/dist/ar-studio.js"></script>
+// <ar-studio assets="https://your.cdn/models.json" title="Acme AR"></ar-studio>
+//
+// Every attribute maps onto a config field, so a page with no build step and no
+// JavaScript of its own still gets the whole studio. Attributes are read once at
+// connect; call `element.studio` for the live instance to change anything after.
+
+import { createArStudio } from './index.js';
+
+const BOOL = (v, fallback) => (v === null || v === undefined ? fallback : v !== 'false' && v !== '0');
+
+export class ArStudioElement extends HTMLElement {
+ static get observedAttributes() {
+ return ['assets', 'title', 'accent', 'back-href', 'generate', 'rooms', 'room-server', 'origin', 'share-base'];
+ }
+
+ connectedCallback() {
+ if (this.studio) return;
+ // A custom element has no intrinsic size; without this the canvas mounts at
+ // zero height and the studio looks like it failed to load.
+ if (!this.style.display) this.style.display = 'block';
+ if (!this.style.minHeight && !this.hasAttribute('embedded')) this.style.minHeight = '70vh';
+ this.studio = createArStudio(this, this.options());
+ }
+
+ disconnectedCallback() {
+ this.studio?.destroy();
+ this.studio = null;
+ }
+
+ /** The config this element's attributes describe. */
+ options() {
+ const attr = (name) => this.getAttribute(name);
+ const assets = attr('assets');
+ return {
+ ...(assets ? { assets: assets.includes(',') ? assets.split(',').map((s) => s.trim()) : assets } : {}),
+ ...(attr('origin') ? { origin: attr('origin') } : {}),
+ ...(attr('share-base') ? { shareBaseUrl: attr('share-base') } : {}),
+ branding: {
+ title: attr('title') || 'AR Studio',
+ accent: attr('accent') || undefined,
+ backHref: attr('back-href') || null,
+ },
+ generate: { enabled: BOOL(attr('generate'), true) },
+ rooms: {
+ enabled: BOOL(attr('rooms'), true),
+ ...(attr('room-server') ? { server: attr('room-server') } : {}),
+ },
+ fullscreen: false,
+ };
+ }
+}
+
+/** Register `<ar-studio>`. Safe to call more than once. */
+export function defineArStudio(tag = 'ar-studio') {
+ if (typeof customElements === 'undefined') return;
+ if (!customElements.get(tag)) customElements.define(tag, ArStudioElement);
+}
+
+export default defineArStudio;
diff --git a/packages/ar-studio/src/forge/client.js b/packages/ar-studio/src/forge/client.js
new file mode 100644
index 000000000..469d2ccf3
--- /dev/null
+++ b/packages/ar-studio/src/forge/client.js
@@ -0,0 +1,147 @@
+// Text-to-3D generation for the studio.
+//
+// Wraps the three.ws 3D Studio MCP connector: the free, keyless pipeline behind
+// the ChatGPT 3D Studio) into one promise-shaped call with live progress.
+// Create a client with createForgeClient(), then await its generate(prompt,
+// { onProgress }) method; onProgress receives each status update.
+// // → { src, title, viewerUrl, arUrl, kind, prompt }
+//
+// Long jobs are handled the way the protocol intends: the first call either
+// returns the finished model or a `pending` job handle, and this client polls the
+// connector's own `check_job` tool until it lands. Nothing is faked: no timer
+// pretends to be progress, and the ETA shown is the one the API reported.
+//
+// Point `endpoint` at any MCP server exposing a compatible generate tool and the
+// studio generates from your pipeline instead.
+
+import { createMcpClient, unwrapToolResult } from './mcp-http.js';
+import { stageNarration, promptTitle } from './narration.js';
+import { validatePrompt } from './safety.js';
+import { THREE_WS } from '../config.js';
+
+/** Tool name per generation kind, on the three.ws connector. */
+export const GENERATE_TOOLS = {
+ model: 'forge_free', // a prop or object
+ avatar: 'text_to_avatar', // a character; rigged avatars idle and animate in-scene
+ mesh: 'mesh_forge', // art-directed mesh, prompt refined by a director model first
+};
+
+export class ForgeError extends Error {
+ constructor(message, code = 'failed') {
+ super(message);
+ this.name = 'ForgeError';
+ this.code = code;
+ }
+}
+
+/**
+ * @param {object} [opts]
+ * @param {string} [opts.endpoint] MCP endpoint. Defaults to the free three.ws connector.
+ * @param {'model'|'avatar'|'mesh'} [opts.kind]
+ * @param {'draft'|'standard'|'high'} [opts.tier]
+ * @param {number} [opts.timeoutMs] Give up after this long (default 5 min).
+ * @param {number} [opts.pollMs] Gap between check_job polls (default 3 s).
+ * @param {Record<string,string>} [opts.headers]
+ * @param {Record<string,string>} [opts.tools] Override the tool name per kind.
+ */
+export function createForgeClient({
+ endpoint = THREE_WS.studioMcp,
+ kind = 'model',
+ tier = 'standard',
+ timeoutMs = 300000,
+ pollMs = 3000,
+ headers,
+ tools = GENERATE_TOOLS,
+ fetchImpl,
+} = {}) {
+ const mcp = createMcpClient({ endpoint, headers, fetchImpl });
+
+ /**
+ * Generate one model.
+ *
+ * @param {string} prompt
+ * @param {object} [opts]
+ * @param {(state: {status: string, message: string, elapsedMs: number, etaSeconds: number|null}) => void} [opts.onProgress]
+ * @param {'model'|'avatar'|'mesh'} [opts.kind]
+ * @param {string} [opts.imageUrl] Reference image (avatar/mesh kinds).
+ * @param {AbortSignal} [opts.signal]
+ * @returns {Promise<{src:string,title:string,kind:string,prompt:string,viewerUrl:string,arUrl:string,poster:string}>}
+ */
+ async function generate(prompt, {
+ onProgress, kind: kindOverride, imageUrl = '', signal, tier: tierOverride,
+ } = {}) {
+ const check = validatePrompt(prompt);
+ if (!check.ok) throw new ForgeError(check.reason, check.category || 'invalid_prompt');
+ const text = check.prompt;
+ const useKind = kindOverride || kind;
+ const tool = tools[useKind] || tools.model;
+ const started = Date.now();
+ let etaSeconds = null;
+
+ const report = (status, extra = {}) => {
+ if (!onProgress) return;
+ onProgress({
+ status,
+ message: stageNarration({ status, etaSeconds, ...extra }),
+ elapsedMs: Date.now() - started,
+ etaSeconds,
+ });
+ };
+
+ report('submitting');
+ const args = useKind === 'model'
+ ? { prompt: text, ...(tierOverride || tier ? { tier: tierOverride || tier } : {}) }
+ : { prompt: text, ...(imageUrl ? { image_url: imageUrl } : {}) };
+
+ let result = unwrapToolResult(await mcp.callTool(tool, args, { signal }));
+ if (result.isError) throw new ForgeError(result.structured?.message || result.text || 'Generation failed.');
+
+ // A job that outlives the connector's inline wait budget hands back a poll
+ // handle; collect it through the server's own check_job tool.
+ let data = result.structured || {};
+ while (data.status === 'pending' && data.jobId) {
+ if (Date.now() - started > timeoutMs) {
+ throw new ForgeError('Generation timed out. Try a simpler, single-object prompt.', 'timeout');
+ }
+ etaSeconds = Number(data.etaRemainingSeconds) > 0 ? Number(data.etaRemainingSeconds) : null;
+ report('queued');
+ await delay(pollMs, signal);
+ result = unwrapToolResult(await mcp.callTool('check_job', { job_id: data.jobId }, { signal }));
+ if (result.isError) throw new ForgeError(result.structured?.message || result.text || 'Generation failed.');
+ data = result.structured || {};
+ }
+
+ const src = firstString(data.glbUrl, data.glb_url, data.url);
+ if (!src) throw new ForgeError(result.text || 'The generator returned no model.', 'no_result');
+ report('done');
+
+ return {
+ src,
+ title: promptTitle(text),
+ prompt: text,
+ kind: useKind,
+ viewerUrl: firstString(data.viewerUrl, ''),
+ arUrl: firstString(data.arUrl, ''),
+ poster: firstString(data.referenceImageUrl, ''),
+ rigged: Boolean(data.rigged),
+ };
+ }
+
+ return { generate, mcp, endpoint };
+}
+
+function firstString(...vals) {
+ for (const v of vals) if (typeof v === 'string' && v.trim()) return v.trim();
+ return '';
+}
+
+function delay(ms, signal) {
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) return reject(new ForgeError('Cancelled.', 'aborted'));
+ const t = setTimeout(resolve, ms);
+ signal?.addEventListener('abort', () => {
+ clearTimeout(t);
+ reject(new ForgeError('Cancelled.', 'aborted'));
+ }, { once: true });
+ });
+}
diff --git a/packages/ar-studio/src/forge/mcp-http.js b/packages/ar-studio/src/forge/mcp-http.js
new file mode 100644
index 000000000..00aaf6e36
--- /dev/null
+++ b/packages/ar-studio/src/forge/mcp-http.js
@@ -0,0 +1,107 @@
+// A minimal Model Context Protocol client over HTTP, small enough to ship to a
+// browser (no SDK, no dependencies, ~2 kB).
+//
+// The three.ws 3D Studio connector: the same endpoint ChatGPT talks to: is a
+// keyless, CORS-open MCP server. Rather than inventing a private REST shape for
+// generation, this package speaks MCP to it directly, so the studio's in-camera
+// "type a prompt, get a model" lane IS the ChatGPT 3D Studio pipeline, byte for
+// byte, and pointing it at any other MCP server is a one-line config change.
+//
+// Streamable HTTP servers may answer a POST with either `application/json` or an
+// SSE stream; both are handled here, and the SSE branch resolves on the first
+// message carrying the matching JSON-RPC id.
+
+let nextId = 1;
+
+/**
+ * @param {object} opts
+ * @param {string} opts.endpoint MCP endpoint URL (streamable HTTP).
+ * @param {Record<string,string>} [opts.headers] Extra headers (auth, tracing).
+ * @param {typeof fetch} [opts.fetchImpl]
+ */
+export function createMcpClient({ endpoint, headers = {}, fetchImpl } = {}) {
+ if (!endpoint) throw new Error('ar-studio: MCP client needs an endpoint');
+ const doFetch = fetchImpl || (typeof fetch !== 'undefined' ? fetch.bind(globalThis) : null);
+ if (!doFetch) throw new Error('ar-studio: no fetch implementation available');
+ let sessionId = '';
+
+ async function rpc(method, params, { signal } = {}) {
+ const id = nextId++;
+ const res = await doFetch(endpoint, {
+ method: 'POST',
+ signal,
+ headers: {
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ ...(sessionId ? { 'mcp-session-id': sessionId } : {}),
+ ...headers,
+ },
+ body: JSON.stringify({ jsonrpc: '2.0', id, method, ...(params ? { params } : {}) }),
+ });
+ const sid = res.headers.get('mcp-session-id');
+ if (sid) sessionId = sid;
+ if (!res.ok) {
+ const detail = await res.text().catch(() => '');
+ throw new McpError(`${method} failed (${res.status})`, { status: res.status, detail });
+ }
+ const body = await readBody(res, id);
+ if (body?.error) throw new McpError(body.error.message || 'MCP error', { code: body.error.code });
+ return body?.result ?? null;
+ }
+
+ return {
+ get sessionId() { return sessionId; },
+ rpc,
+ /** List the server's tools. */
+ listTools(opts) {
+ return rpc('tools/list', undefined, opts).then((r) => r?.tools || []);
+ },
+ /**
+ * Call a tool. Returns the raw MCP result: `{ content, structuredContent, isError }`.
+ */
+ callTool(name, args = {}, opts) {
+ return rpc('tools/call', { name, arguments: args }, opts);
+ },
+ };
+}
+
+export class McpError extends Error {
+ constructor(message, extra = {}) {
+ super(message);
+ this.name = 'McpError';
+ Object.assign(this, extra);
+ }
+}
+
+async function readBody(res, id) {
+ const type = String(res.headers.get('content-type') || '');
+ if (!type.includes('text/event-stream')) return res.json();
+ // SSE: resolve on the first `data:` payload whose id matches this call.
+ const text = await res.text();
+ for (const block of text.split(/\n\n+/)) {
+ const data = block
+ .split('\n')
+ .filter((l) => l.startsWith('data:'))
+ .map((l) => l.slice(5).trim())
+ .join('');
+ if (!data) continue;
+ try {
+ const msg = JSON.parse(data);
+ if (msg.id === id || msg.error) return msg;
+ } catch {
+ // A non-JSON keep-alive frame; keep scanning.
+ }
+ }
+ throw new McpError('MCP stream ended without a result');
+}
+
+/** Pull the useful half out of an MCP tool result: structured data plus the text. */
+export function unwrapToolResult(result) {
+ const structured = result?.structuredContent ?? null;
+ const text = (result?.content || [])
+ .filter((c) => c?.type === 'text' && typeof c.text === 'string')
+ .map((c) => c.text)
+ .join('\n')
+ .trim();
+ return { structured, text, isError: Boolean(result?.isError) };
+}
diff --git a/packages/ar-studio/src/forge/narration.js b/packages/ar-studio/src/forge/narration.js
new file mode 100644
index 000000000..cafe5d74c
--- /dev/null
+++ b/packages/ar-studio/src/forge/narration.js
@@ -0,0 +1,88 @@
+// Turning a live generation state into one honest line of copy.
+//
+// Every state below comes straight off the pipeline. Nothing here invents a
+// stage the worker has not entered, and no number is fabricated: an ETA is
+// rendered only when the API reported one, and the cold-start line appears only
+// when the API said the GPU worker is spinning up. That is the difference
+// between a progress indicator people trust and a fake progress bar.
+
+const LANES = {
+ nvidia: 'free NVIDIA NIM',
+ huggingface: 'free Hunyuan3D',
+ trellis: 'Fast',
+ trellis_selfhost: 'TRELLIS',
+ hunyuan3d: 'Hunyuan3D',
+ triposg: 'TripoSG',
+ meshy: 'Meshy',
+ tripo: 'Tripo',
+ rodin: 'Rodin',
+ stability: 'Stability',
+};
+
+/** Human name for a generation backend id, or null when it is unknown. */
+export function laneLabel(id) {
+ return LANES[String(id || '').trim()] || null;
+}
+
+/**
+ * One line of narration for a generation state.
+ *
+ * @param {object} state
+ * @param {string} [state.status] submitting | queued | image | running | done | failed
+ * @param {number} [state.etaSeconds] Seconds remaining, when the API reported one.
+ * @param {string} [state.backend] Lane id, when known.
+ * @param {boolean} [state.coldStart] The worker is booting.
+ * @param {number} [state.coldSeconds] Reported spin-up budget.
+ * @returns {string}
+ */
+export function stageNarration(state = {}) {
+ const status = String(state.status || '').toLowerCase();
+ const eta = Number(state.etaSeconds) > 0 ? Math.round(Number(state.etaSeconds)) : null;
+ const etaSuffix = eta ? `: ~${eta}s` : '';
+ const lane = laneLabel(state.backend);
+ const laneSuffix = lane ? ` on the ${lane} lane` : ' on the free lane';
+ const cold = Boolean(state.coldStart);
+ const coldSeconds = Number(state.coldSeconds) > 0 ? Math.round(Number(state.coldSeconds)) : null;
+ const coldWho = lane ? ` ${lane}` : '';
+
+ switch (status) {
+ case 'submitting':
+ case 'submit':
+ return `Sending your prompt${laneSuffix}…`;
+ case 'queued':
+ case 'pending':
+ case 'queue':
+ if (cold) {
+ return coldSeconds
+ ? `Waking up the${coldWho} GPU worker (about ${coldSeconds}s), then sculpting starts`
+ : `Waking up the${coldWho} GPU worker, then sculpting starts`;
+ }
+ return `Queued${laneSuffix}${etaSuffix}`;
+ case 'image':
+ case 'texturing':
+ return 'Drafting the look…';
+ case 'running':
+ case 'reconstruct':
+ case 'mesh':
+ return `Building geometry & texturing${etaSuffix}`;
+ case 'done':
+ case 'ready':
+ return 'Model ready: dropping it into the room';
+ case 'failed':
+ case 'error':
+ return 'Generation failed: try a more concrete, single-object prompt';
+ default:
+ return `Working${etaSuffix}`;
+ }
+}
+
+/** Trim a prompt into a card-sized label: the first clause, never mid-word. */
+export function promptTitle(prompt, max = 48) {
+ const text = String(prompt || '').replace(/\s+/g, ' ').trim();
+ if (!text) return 'Model';
+ const clause = text.split(/[,.;:]|\s+[--]\s+/)[0].trim() || text;
+ if (clause.length <= max) return clause;
+ const cut = clause.slice(0, max);
+ const space = cut.lastIndexOf(' ');
+ return `${(space > max * 0.6 ? cut.slice(0, space) : cut).trim()}…`;
+}
diff --git a/packages/ar-studio/src/forge/safety.js b/packages/ar-studio/src/forge/safety.js
new file mode 100644
index 000000000..f81c996c9
--- /dev/null
+++ b/packages/ar-studio/src/forge/safety.js
@@ -0,0 +1,120 @@
+// Prompt safety gate for text-to-3D generation.
+//
+// A studio you can drop on a public page will be typed into by the public. This
+// classifier refuses the highest-harm categories before any GPU work starts, so
+// a hosted demo stays appropriate for a general audience (including the 13+ bar
+// app stores hold conversational 3D tools to). It is deliberately a whole-word
+// keyword classifier, not a model call: zero latency, zero dependency, zero cost,
+// and it runs in the browser as well as in the MCP server.
+//
+// This is a client-side courtesy, not the authority. The generation backend runs
+// its own gate; this one exists so an obviously-disallowed prompt fails instantly
+// with a useful message instead of after a round trip.
+//
+// Ported from the three.ws 3D Studio connector's gate (Apache-2.0).
+
+function escapeRe(s) {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+// Whole-word match, so "assassin" never trips "ass" and Scunthorpe is safe.
+function hasTerm(text, terms) {
+ for (const t of terms) {
+ const re = new RegExp(`(^|[^a-z0-9])${escapeRe(t)}([^a-z0-9]|$)`, 'i');
+ if (re.test(text)) return t;
+ }
+ return null;
+}
+
+const SEXUAL_TERMS = [
+ 'nude', 'nudes', 'naked', 'nsfw', 'porn', 'porno', 'pornographic', 'xxx',
+ 'sex', 'sexual', 'sexy', 'erotic', 'erotica', 'hentai', 'rule34', 'r34',
+ 'fetish', 'bdsm', 'bondage', 'lingerie', 'topless', 'bottomless', 'nipple',
+ 'nipples', 'genital', 'genitalia', 'penis', 'vagina', 'vulva', 'breasts',
+ 'boobs', 'cleavage', 'buttocks', 'thong', 'fellatio', 'cunnilingus',
+ 'masturbation', 'orgasm', 'cum', 'creampie', 'milf', 'camgirl', 'stripper',
+ 'escort', 'onlyfans',
+];
+
+// Zero tolerance. Every term is unambiguous on purpose: this category refuses
+// with a blunt message, and a false accusation is a worse failure than a missed
+// abbreviation. The short term for it is deliberately absent because it fires on
+// "a CP/M terminal".
+const CSAM_TERMS = [
+ 'loli', 'lolicon', 'shota', 'shotacon', 'toddlercon', 'underage', 'preteen',
+ 'pre-teen', 'jailbait', 'child porn', 'childporn', 'child sex', 'child sexual',
+ 'minor sex', 'csam',
+];
+
+const GORE_TERMS = [
+ 'gore', 'gory', 'gruesome', 'dismembered', 'dismemberment', 'decapitated',
+ 'decapitation', 'beheading', 'mutilated', 'mutilation', 'disembowel',
+ 'disemboweled', 'eviscerated', 'bloodbath', 'massacre', 'torture',
+ 'tortured', 'snuff',
+];
+
+const HATE_TERMS = [
+ 'nazi', 'swastika', 'hitler', 'kkk', 'white power', 'heil', 'genocide',
+ 'ethnic cleansing', 'terrorist', 'isis', 'al qaeda', 'al-qaeda',
+];
+
+// Real, usable weapons and drugs only. Stylized fantasy props (sword, bow, wand)
+// are creative work and stay allowed.
+const WEAPON_DRUG_TERMS = [
+ 'ghost gun', 'ar-15', 'ar15', 'ak-47', 'ak47', 'assault rifle',
+ 'submachine gun', 'handgun', 'pistol', 'firearm', 'firearms', 'silencer',
+ 'suppressor', 'ammunition magazine', 'pipe bomb', 'ied', 'grenade',
+ 'landmine', 'c4 explosive', 'meth', 'methamphetamine', 'cocaine', 'heroin',
+ 'fentanyl', 'crack pipe', 'bong',
+];
+
+const CATEGORIES = [
+ { id: 'csam', terms: CSAM_TERMS, message: 'This prompt is not allowed.' },
+ {
+ id: 'sexual',
+ terms: SEXUAL_TERMS,
+ message: 'This studio cannot generate sexual or adult content. Describe a character, creature, or object without explicit themes.',
+ },
+ {
+ id: 'gore',
+ terms: GORE_TERMS,
+ message: 'This studio cannot generate graphically violent or gory content. Describe your subject without graphic violence.',
+ },
+ {
+ id: 'hate',
+ terms: HATE_TERMS,
+ message: 'This studio cannot generate hateful or extremist content or iconography.',
+ },
+ {
+ id: 'weapon_drug',
+ terms: WEAPON_DRUG_TERMS,
+ message: 'This studio cannot generate real firearms, explosives, or drug paraphernalia. Stylized fantasy props (a sword, a wand) are fine.',
+ },
+];
+
+/**
+ * Classify a generation prompt.
+ *
+ * @param {string} prompt
+ * @returns {{allowed: boolean, category?: string, message?: string, matched?: string}}
+ */
+export function checkPromptSafety(prompt) {
+ const text = String(prompt || '').toLowerCase();
+ if (!text.trim()) return { allowed: true };
+ for (const cat of CATEGORIES) {
+ const matched = hasTerm(text, cat.terms);
+ if (matched) return { allowed: false, category: cat.id, message: cat.message, matched };
+ }
+ return { allowed: true };
+}
+
+/** Is this prompt long enough to be a real subject? */
+export function validatePrompt(raw) {
+ const text = String(raw ?? '').trim();
+ if (text.length < 3) {
+ return { ok: false, reason: 'Describe a concrete object: at least a few characters.' };
+ }
+ const safety = checkPromptSafety(text);
+ if (!safety.allowed) return { ok: false, reason: safety.message, category: safety.category };
+ return { ok: true, prompt: text };
+}
diff --git a/packages/ar-studio/src/index.js b/packages/ar-studio/src/index.js
new file mode 100644
index 000000000..952eef3f3
--- /dev/null
+++ b/packages/ar-studio/src/index.js
@@ -0,0 +1,98 @@
+// 3D AR Studio: drop a full augmented-reality studio into any web page.
+//
+// import { createArStudio } from '3d-ar-studio'
+// Call createArStudio with the element to mount into (usually document.body).
+//
+// That is the whole integration. It mounts a camera-backed 3D scene, a model
+// browser wired to a public CC0 library, a prompt box that generates new models,
+// WebXR placement on devices that support it, shareable scene links, QR hand-off
+// to a phone, and live shared rooms.
+//
+// Point it somewhere else with one option:
+//
+// createArStudio(el, { assets: 'https://your.cdn/models.json' })
+//
+// See README.md for the full option list, and src/config.js for the defaults.
+
+export { ArStudio } from './studio/studio.js';
+export { DEFAULTS, THREE_WS, mergeConfig, resolveConfig, safeUrl } from './config.js';
+export { createLogger, log, setVerbose, isVerbose } from './log.js';
+
+// Sources: bring your own catalogue.
+export {
+ resolveSources, manifestSource, staticSource, recentSource,
+ threeWsObjectsSource, threeWsCommunitySource, LINK_SOURCE,
+} from './sources/index.js';
+export { normalizeCatalogue, catalogueItems, filenameTitle } from './sources/manifest.js';
+export { readRecents, rememberRecent } from './sources/recents.js';
+export { cdnUrl } from './sources/three-ws.js';
+
+// Generation: the free, keyless text-to-3D pipeline (or your own MCP server).
+export { createForgeClient, GENERATE_TOOLS, ForgeError } from './forge/client.js';
+export { createMcpClient, unwrapToolResult, McpError } from './forge/mcp-http.js';
+export { checkPromptSafety, validatePrompt } from './forge/safety.js';
+export { stageNarration, promptTitle, laneLabel } from './forge/narration.js';
+
+// "View in your space": device-aware AR routing (also safe to import in Node).
+export {
+ planArLaunch, assertArAssetUrl, detectArTarget, buildArLaunchUrl,
+ buildSceneViewerUrl, buildViewerUrl, ArUrlError, DEFAULT_ORIGIN,
+} from './ar-launch.js';
+export {
+ arCapability, prepareNativeAr, placeInYourSpace, withQuickLookBanner,
+ canUseQuickLook, canUseSceneViewer, openQuickLook, openSceneViewer, usdzFilename,
+ cachedUsdzUrl, isQuickLookReady, releaseQuickLook, clearQuickLookCache,
+ isIOS, isAndroid, QUICK_LOOK_BANNER_TAPPED,
+} from './studio/native-ar.js';
+export {
+ glbUrlToUsdzBlob, objectToUsdzBlob, sceneToUsdzBlob, bakeSkinnedMeshes,
+ coerceMaterialsToStandard, ensureNormals, usdzExportRoot, groundOnFloor, fitToRoomScale,
+ clampToPlaceableSize, MAX_AR_FOOTPRINT_M, MAX_AR_HEIGHT_M,
+} from './studio/usdz.js';
+
+// Scene math and links: useful for building your own UI on top.
+export {
+ fitTransform, spawnPointInFront, normalizeGlbUrl, serializeScene, deserializeScene,
+ sceneToHashParam, sceneFromHashParam, studioSceneUrl, studioShareUrl,
+ roomLightFromPixels, twistDelta, touchAngle,
+ MAX_PLACEMENTS, SCALE_MIN, SCALE_MAX, SPAWN_DISTANCE_M,
+ AVATAR_TARGET_HEIGHT_M, PROP_TARGET_SIZE_M,
+} from './studio/scene-math.js';
+export {
+ generateRoomCode, normalizeRoomCode, roomShareUrl, roomKeyForCode,
+ localToShared, sharedToLocal, normDeg, normRad,
+} from './studio/coords.js';
+export { renderQRToSVG, renderQRToCanvas, generateQR } from './qr.js';
+
+// Rendering + capture, for hosts building adjacent 3D surfaces.
+export {
+ applyCinematicDefaults, detectQualityTier, loadEnvironment,
+ updateGroundContactShadow, QUALITY_TIERS,
+} from './studio/render.js';
+export { captureComposite, shareOrDownload, shareUrlOrCopy } from './studio/capture.js';
+export { sharedGLTFLoader, setDracoPath, DEFAULT_DRACO_PATH } from './studio/loaders.js';
+export { mountIdle, getIdleClipJson } from './studio/idle.js';
+
+import { ArStudio } from './studio/studio.js';
+
+/**
+ * Mount a studio.
+ *
+ * @param {HTMLElement|string} [host] Element or CSS selector. Defaults to `document.body`.
+ * @param {object} [options] See src/config.js.
+ * @returns {ArStudio}
+ *
+ * @example
+ * const studio = createArStudio('#stage', {
+ * assets: 'https://cdn.acme.com/models.json',
+ * branding: { title: 'Acme AR', accent: '#00b894' },
+ * })
+ * studio.on('add', ({ placement }) => console.log('placed', placement.title))
+ */
+export function createArStudio(host = document.body, options = {}) {
+ const el = typeof host === 'string' ? document.querySelector(host) : host;
+ if (!el) throw new Error(`ar-studio: no element matched ${JSON.stringify(host)}`);
+ return new ArStudio(el, options);
+}
+
+export default createArStudio;
diff --git a/packages/ar-studio/src/log.js b/packages/ar-studio/src/log.js
new file mode 100644
index 000000000..2fa33e89a
--- /dev/null
+++ b/packages/ar-studio/src/log.js
@@ -0,0 +1,64 @@
+// Tiny gated logger. A shipped page's console should be quiet: noise hides real
+// problems. Diagnostics print only when the host opts in (`?ar-debug` in the
+// URL, `localStorage['ar-studio:debug'] = '1'`, or `setLogLevel('debug')`);
+// errors always print, because a real error is a bug to fix, not noise to mute.
+
+const noop = () => {};
+
+function optedIn() {
+ if (typeof window === 'undefined') return false;
+ try {
+ const params = new URLSearchParams(window.location.search);
+ if (params.has('ar-debug') && params.get('ar-debug') !== '0') return true;
+ return window.localStorage?.getItem('ar-studio:debug') === '1';
+ } catch {
+ // Sandboxed iframe / storage disabled: treat as no opt-in.
+ return false;
+ }
+}
+
+let verbose = optedIn();
+
+const bind = (method) =>
+ typeof console !== 'undefined' && typeof console[method] === 'function'
+ ? console[method].bind(console)
+ : noop;
+
+/** Turn verbose diagnostics on or off at runtime. */
+export function setVerbose(on) {
+ verbose = Boolean(on);
+}
+
+/** Whether verbose diagnostics are currently enabled. */
+export function isVerbose() {
+ return verbose;
+}
+
+const gate = (method) => (...args) => {
+ if (verbose) bind(method)(...args);
+};
+
+export const log = {
+ error: (...a) => bind('error')(...a),
+ warn: gate('warn'),
+ info: gate('info'),
+ debug: gate('debug'),
+ log: gate('log'),
+};
+
+/**
+ * A logger that prefixes every line with `[tag]`.
+ * @param {string} tag
+ */
+export function createLogger(tag) {
+ const prefix = `[${tag}]`;
+ return {
+ error: (...a) => bind('error')(prefix, ...a),
+ warn: (...a) => { if (verbose) bind('warn')(prefix, ...a); },
+ info: (...a) => { if (verbose) bind('info')(prefix, ...a); },
+ debug: (...a) => { if (verbose) bind('debug')(prefix, ...a); },
+ log: (...a) => { if (verbose) bind('log')(prefix, ...a); },
+ };
+}
+
+export default log;
diff --git a/packages/ar-studio/src/qr.js b/packages/ar-studio/src/qr.js
new file mode 100644
index 000000000..e114c6471
--- /dev/null
+++ b/packages/ar-studio/src/qr.js
@@ -0,0 +1,421 @@
+/**
+ * Minimal QR-code generator (zero-dep, ESM).
+ *
+ * Implements QR Model 2, byte mode, error-correction level L, versions 1-10.
+ * That's enough to encode URLs up to ~174 UTF-8 bytes at ECL=L: which covers
+ * every explorer URL we'd embed in an ERC-8004 agent QR.
+ *
+ * Derived from Project Nayuki's public-domain QR code generator
+ * (https://www.nayuki.io/page/qr-code-generator-library) reduced to the
+ * minimum path this app needs. Pure JS, no external deps.
+ */
+
+// ───────────────────────────────────────────────────────────────────────────
+// Generator
+// ───────────────────────────────────────────────────────────────────────────
+
+const ECL = 0; // L (1 = M, 2 = Q, 3 = H). We only need L.
+
+const EC_CODEWORDS_PER_BLOCK = [
+ // ECL_L
+ [7, 10, 15, 20, 26, 18, 20, 24, 30, 18],
+];
+const NUM_EC_BLOCKS = [[1, 1, 1, 1, 1, 2, 2, 2, 2, 4]];
+
+/** Returns the bitmask size (modules per side) for a given version (1..10). */
+function sizeForVersion(ver) {
+ return ver * 4 + 17;
+}
+
+/** Total number of data codewords for a given version + ECL. */
+function numDataCodewords(ver) {
+ const total = numRawDataModules(ver) >>> 3;
+ const ecBlocks = NUM_EC_BLOCKS[ECL][ver - 1];
+ const ecPerBlock = EC_CODEWORDS_PER_BLOCK[ECL][ver - 1];
+ return total - ecPerBlock * ecBlocks;
+}
+
+function numRawDataModules(ver) {
+ let result = (16 * ver + 128) * ver + 64;
+ if (ver >= 2) {
+ const numAlign = Math.floor(ver / 7) + 2;
+ result -= (25 * numAlign - 10) * numAlign - 55;
+ if (ver >= 7) result -= 36;
+ }
+ return result;
+}
+
+// Reed-Solomon in GF(256)
+function rsGenerator(degree) {
+ const result = new Uint8Array(degree);
+ result[degree - 1] = 1;
+ let root = 1;
+ for (let i = 0; i < degree; i++) {
+ for (let j = 0; j < degree; j++) {
+ result[j] = rsMul(result[j], root);
+ if (j + 1 < degree) result[j] ^= result[j + 1];
+ }
+ root = rsMul(root, 0x02);
+ }
+ return result;
+}
+function rsMul(x, y) {
+ let z = 0;
+ for (let i = 7; i >= 0; i--) {
+ z = (z << 1) ^ ((z >>> 7) * 0x11d);
+ z ^= ((y >>> i) & 1) * x;
+ }
+ return z & 0xff;
+}
+function rsRemainder(data, gen) {
+ const result = new Uint8Array(gen.length);
+ for (const b of data) {
+ const factor = b ^ result[0];
+ result.copyWithin(0, 1);
+ result[result.length - 1] = 0;
+ for (let i = 0; i < result.length; i++) result[i] ^= rsMul(gen[i], factor);
+ }
+ return result;
+}
+
+// Pick the smallest version (1..10) that fits `dataLen` bytes in byte mode at ECL=L.
+function pickVersion(dataLen) {
+ for (let v = 1; v <= 10; v++) {
+ const bitsAvailable = numDataCodewords(v) * 8;
+ // byte mode: 4 (mode) + (v<10 ? 8 : 16) char-count + 8*len
+ const charCountBits = v < 10 ? 8 : 16;
+ const needed = 4 + charCountBits + dataLen * 8;
+ if (needed <= bitsAvailable) return v;
+ }
+ throw new Error('QR payload too large (>10 versions)');
+}
+
+/**
+ * Generate a QR code matrix for the given string.
+ *
+ * @param {string} text
+ * @returns {{ size: number, modules: boolean[][] }}
+ */
+export function generateQR(text) {
+ const bytes = new TextEncoder().encode(text);
+ const ver = pickVersion(bytes.length);
+ const size = sizeForVersion(ver);
+ const charCountBits = ver < 10 ? 8 : 16;
+
+ // --- 1. Build bitstream ------------------------------------------------
+ const bits = [];
+ const pushBits = (val, n) => {
+ for (let i = n - 1; i >= 0; i--) bits.push((val >>> i) & 1);
+ };
+ pushBits(0b0100, 4); // byte mode
+ pushBits(bytes.length, charCountBits);
+ for (const b of bytes) pushBits(b, 8);
+
+ const dataCodewords = numDataCodewords(ver);
+ const capacityBits = dataCodewords * 8;
+ // terminator
+ for (let i = 0; i < 4 && bits.length < capacityBits; i++) bits.push(0);
+ // byte-align
+ while (bits.length % 8 !== 0) bits.push(0);
+ // pad
+ const pads = [0xec, 0x11];
+ let padIdx = 0;
+ while (bits.length < capacityBits) {
+ pushBits(pads[padIdx % 2], 8);
+ padIdx++;
+ }
+ const data = new Uint8Array(dataCodewords);
+ for (let i = 0; i < dataCodewords; i++) {
+ let v = 0;
+ for (let j = 0; j < 8; j++) v = (v << 1) | bits[i * 8 + j];
+ data[i] = v;
+ }
+
+ // --- 2. Reed-Solomon EC ------------------------------------------------
+ const numBlocks = NUM_EC_BLOCKS[ECL][ver - 1];
+ const ecLen = EC_CODEWORDS_PER_BLOCK[ECL][ver - 1];
+ const rawCodewords = numRawDataModules(ver) >>> 3;
+ const shortBlockLen = Math.floor(rawCodewords / numBlocks);
+ const numShort = numBlocks - (rawCodewords % numBlocks);
+
+ const blocks = [];
+ const gen = rsGenerator(ecLen);
+ let offset = 0;
+ for (let i = 0; i < numBlocks; i++) {
+ const dataLen = shortBlockLen - ecLen + (i < numShort ? 0 : 1);
+ const dat = data.slice(offset, offset + dataLen);
+ offset += dataLen;
+ const ec = rsRemainder(dat, gen);
+ blocks.push({ dat, ec });
+ }
+ // Interleave
+ const out = [];
+ for (let i = 0; i < shortBlockLen - ecLen + 1; i++) {
+ for (const b of blocks) {
+ if (i < b.dat.length) out.push(b.dat[i]);
+ }
+ }
+ for (let i = 0; i < ecLen; i++) {
+ for (const b of blocks) out.push(b.ec[i]);
+ }
+
+ // --- 3. Matrix ---------------------------------------------------------
+ const modules = Array.from({ length: size }, () => new Array(size).fill(false));
+ const isFn = Array.from({ length: size }, () => new Array(size).fill(false));
+
+ const setFn = (x, y, dark) => {
+ modules[y][x] = dark;
+ isFn[y][x] = true;
+ };
+
+ // Finder + separators
+ const drawFinder = (cx, cy) => {
+ for (let dy = -4; dy <= 4; dy++) {
+ for (let dx = -4; dx <= 4; dx++) {
+ const x = cx + dx;
+ const y = cy + dy;
+ if (x < 0 || x >= size || y < 0 || y >= size) continue;
+ const d = Math.max(Math.abs(dx), Math.abs(dy));
+ setFn(x, y, d !== 2 && d !== 4);
+ }
+ }
+ };
+ drawFinder(3, 3);
+ drawFinder(size - 4, 3);
+ drawFinder(3, size - 4);
+
+ // Timing
+ for (let i = 0; i < size; i++) {
+ if (!isFn[6][i]) setFn(i, 6, i % 2 === 0);
+ if (!isFn[i][6]) setFn(6, i, i % 2 === 0);
+ }
+
+ // Alignment patterns
+ const alignPositions = (ver) => {
+ if (ver === 1) return [];
+ const num = Math.floor(ver / 7) + 2;
+ const step = ver === 32 ? 26 : Math.ceil((ver * 4 + 4) / (num * 2 - 2)) * 2;
+ const result = [6];
+ for (let pos = size - 7; result.length < num; pos -= step) result.splice(1, 0, pos);
+ return result;
+ };
+ const aps = alignPositions(ver);
+ for (const x of aps) {
+ for (const y of aps) {
+ if ((x === 6 && y === 6) || (x === 6 && y === size - 7) || (x === size - 7 && y === 6))
+ continue;
+ for (let dy = -2; dy <= 2; dy++) {
+ for (let dx = -2; dx <= 2; dx++) {
+ const d = Math.max(Math.abs(dx), Math.abs(dy));
+ setFn(x + dx, y + dy, d !== 1);
+ }
+ }
+ }
+ }
+
+ // Reserve format info area
+ for (let i = 0; i < 9; i++) setFn(8, i, false);
+ for (let i = 0; i < 8; i++) setFn(i, 8, false);
+ for (let i = 0; i < 8; i++) setFn(size - 1 - i, 8, false);
+ for (let i = 0; i < 7; i++) setFn(8, size - 1 - i, false);
+ setFn(8, size - 8, true); // dark module
+
+ // Version info (ver >= 7)
+ if (ver >= 7) {
+ let rem = ver;
+ for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
+ const bits = ((ver << 12) | rem) >>> 0;
+ for (let i = 0; i < 18; i++) {
+ const bit = ((bits >>> i) & 1) === 1;
+ const a = size - 11 + (i % 3);
+ const b = Math.floor(i / 3);
+ setFn(a, b, bit);
+ setFn(b, a, bit);
+ }
+ }
+
+ // --- 4. Place data by zig-zag -----------------------------------------
+ let bitIdx = 0;
+ const bitAt = (i) => ((out[i >>> 3] >>> (7 - (i & 7))) & 1) === 1;
+ for (let right = size - 1; right >= 1; right -= 2) {
+ if (right === 6) right = 5;
+ for (let vert = 0; vert < size; vert++) {
+ for (let j = 0; j < 2; j++) {
+ const x = right - j;
+ const upward = ((right + 1) & 2) === 0;
+ const y = upward ? size - 1 - vert : vert;
+ if (!isFn[y][x] && bitIdx < out.length * 8) {
+ modules[y][x] = bitAt(bitIdx);
+ bitIdx++;
+ }
+ }
+ }
+ }
+
+ // --- 5. Try all 8 masks; pick lowest penalty --------------------------
+ let bestPenalty = Infinity;
+ let bestModules = null;
+ for (let mask = 0; mask < 8; mask++) {
+ const m = modules.map((row) => row.slice());
+ applyMask(m, isFn, mask);
+ applyFormatInfo(m, mask);
+ const p = penalty(m);
+ if (p < bestPenalty) {
+ bestPenalty = p;
+ bestModules = m;
+ }
+ }
+ return { size, modules: bestModules };
+}
+
+function maskFn(mask, x, y) {
+ switch (mask) {
+ case 0:
+ return (x + y) % 2 === 0;
+ case 1:
+ return y % 2 === 0;
+ case 2:
+ return x % 3 === 0;
+ case 3:
+ return (x + y) % 3 === 0;
+ case 4:
+ return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
+ case 5:
+ return ((x * y) % 2) + ((x * y) % 3) === 0;
+ case 6:
+ return (((x * y) % 2) + ((x * y) % 3)) % 2 === 0;
+ case 7:
+ return (((x + y) % 2) + ((x * y) % 3)) % 2 === 0;
+ }
+ return false;
+}
+
+function applyMask(modules, isFn, mask) {
+ const size = modules.length;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ if (!isFn[y][x] && maskFn(mask, x, y)) modules[y][x] = !modules[y][x];
+ }
+ }
+}
+
+function applyFormatInfo(modules, mask) {
+ const size = modules.length;
+ const data = (ECL_BITS[ECL] << 3) | mask;
+ let rem = data;
+ for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
+ const bits = (((data << 10) | rem) ^ 0x5412) >>> 0;
+ const setBit = (x, y, b) => {
+ modules[y][x] = b;
+ };
+ for (let i = 0; i <= 5; i++) setBit(8, i, ((bits >>> i) & 1) === 1);
+ setBit(8, 7, ((bits >>> 6) & 1) === 1);
+ setBit(8, 8, ((bits >>> 7) & 1) === 1);
+ setBit(7, 8, ((bits >>> 8) & 1) === 1);
+ for (let i = 9; i < 15; i++) setBit(14 - i, 8, ((bits >>> i) & 1) === 1);
+ for (let i = 0; i < 8; i++) setBit(size - 1 - i, 8, ((bits >>> i) & 1) === 1);
+ for (let i = 8; i < 15; i++) setBit(8, size - 15 + i, ((bits >>> i) & 1) === 1);
+ setBit(8, size - 8, true);
+}
+
+const ECL_BITS = [1, 0, 3, 2]; // index by ECL 0..3 → {L,M,Q,H}
+
+function penalty(modules) {
+ const size = modules.length;
+ let p = 0;
+ // N1: runs of 5+
+ for (let y = 0; y < size; y++) {
+ let run = 1;
+ for (let x = 1; x < size; x++) {
+ if (modules[y][x] === modules[y][x - 1]) {
+ run++;
+ if (run === 5) p += 3;
+ else if (run > 5) p++;
+ } else run = 1;
+ }
+ }
+ for (let x = 0; x < size; x++) {
+ let run = 1;
+ for (let y = 1; y < size; y++) {
+ if (modules[y][x] === modules[y - 1][x]) {
+ run++;
+ if (run === 5) p += 3;
+ else if (run > 5) p++;
+ } else run = 1;
+ }
+ }
+ // N2: 2×2 blocks
+ for (let y = 0; y < size - 1; y++) {
+ for (let x = 0; x < size - 1; x++) {
+ const c = modules[y][x];
+ if (modules[y][x + 1] === c && modules[y + 1][x] === c && modules[y + 1][x + 1] === c)
+ p += 3;
+ }
+ }
+ // N3: finder-like patterns: skipped for brevity; penalty approximation is fine for URLs.
+ // N4: light/dark imbalance
+ let dark = 0;
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) if (modules[y][x]) dark++;
+ const total = size * size;
+ const k = Math.floor(Math.abs(dark * 20 - total * 10) / total);
+ p += k * 10;
+ return p;
+}
+
+// ───────────────────────────────────────────────────────────────────────────
+// Renderers
+// ───────────────────────────────────────────────────────────────────────────
+
+/**
+ * Render a QR code as an SVG string. Works in any environment that can hold a
+ * string: no canvas required. Useful as a fallback when 2D canvas is
+ * unavailable or as a directly embeddable inline SVG.
+ *
+ * @param {string} text
+ * @param {{ scale?: number, margin?: number, dark?: string, light?: string }} [opts]
+ * @returns {string} SVG markup
+ */
+export function renderQRToSVG(text, opts = {}) {
+ const scale = opts.scale ?? 8;
+ const margin = opts.margin ?? 2;
+ const dark = opts.dark ?? '#000';
+ const light = opts.light ?? '#fff';
+ const { size, modules } = generateQR(text);
+ const px = (size + margin * 2) * scale;
+ let rects = '';
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ if (modules[y][x]) {
+ rects += `<rect x="${(x + margin) * scale}" y="${(y + margin) * scale}" width="${scale}" height="${scale}"/>`;
+ }
+ }
+ }
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${px} ${px}" shape-rendering="crispEdges"><rect width="${px}" height="${px}" fill="${light}"/><g fill="${dark}">${rects}</g></svg>`;
+}
+
+/**
+ * Render a QR code into a canvas. Returns the canvas.
+ * @param {string} text
+ * @param {{ scale?: number, margin?: number }} [opts]
+ */
+export function renderQRToCanvas(text, opts = {}) {
+ const scale = opts.scale ?? 8;
+ const margin = opts.margin ?? 2;
+ const { size, modules } = generateQR(text);
+ const pixels = (size + margin * 2) * scale;
+ const canvas = document.createElement('canvas');
+ canvas.width = pixels;
+ canvas.height = pixels;
+ const ctx = canvas.getContext('2d');
+ ctx.fillStyle = '#fff';
+ ctx.fillRect(0, 0, pixels, pixels);
+ ctx.fillStyle = '#000';
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ if (modules[y][x]) {
+ ctx.fillRect((x + margin) * scale, (y + margin) * scale, scale, scale);
+ }
+ }
+ }
+ return canvas;
+}
diff --git a/packages/ar-studio/src/sources/index.js b/packages/ar-studio/src/sources/index.js
new file mode 100644
index 000000000..61d3fe9b8
--- /dev/null
+++ b/packages/ar-studio/src/sources/index.js
@@ -0,0 +1,71 @@
+// Asset sources: where the "Add" tray gets its models.
+//
+// A source is a plain object. Nothing here is a class you must extend:
+//
+// {
+// id: 'objects', // stable key, used for the tab
+// label: 'Objects', // tab label
+// hint: 'Free CC0 props…', // optional line under the search box
+// searchable: true, // render a client-side filter box
+// async list() -> [{ src, title, poster?, keywords? }]
+// }
+//
+// `list()` is called once per tab and cached; return everything you have and the
+// tray handles slicing + filtering. Throwing from `list()` is fine: the tray
+// renders a designed error state with a Retry button.
+//
+// The `assets` config accepts, in order of convenience:
+// 'three.ws' the built-in default set (CC0 objects + recents + link)
+// 'https://…/manifest.json' any JSON catalogue (see manifestSource for shapes)
+// { … } one source object
+// [ 'recent', {…}, 'https://…' ] a mixed list, rendered as tabs in order
+
+import { manifestSource } from './manifest.js';
+import { staticSource } from './static.js';
+import { recentSource } from './recents.js';
+import { threeWsObjectsSource, threeWsCommunitySource } from './three-ws.js';
+
+export { manifestSource, staticSource, recentSource, threeWsObjectsSource, threeWsCommunitySource };
+
+/** The tray's paste-a-link tab. Rendered specially (a form, not a list). */
+export const LINK_SOURCE = { id: 'link', label: 'Link', kind: 'link' };
+
+/**
+ * Turn whatever the host passed as `assets` into an ordered list of sources.
+ *
+ * @param {string|object|Array} assets
+ * @param {object} cfg Resolved studio config (for the recents key and origin).
+ * @returns {Array<object>}
+ */
+export function resolveSources(assets, cfg = {}) {
+ const list = Array.isArray(assets) ? assets : [assets];
+ const out = [];
+ for (const entry of list) {
+ const resolved = resolveOne(entry, cfg);
+ if (Array.isArray(resolved)) out.push(...resolved);
+ else if (resolved) out.push(resolved);
+ }
+ // Always end with the paste-a-link tab unless the host supplied one already.
+ if (!out.some((s) => s.kind === 'link' || s.id === 'link')) out.push(LINK_SOURCE);
+ // De-duplicate by id, first wins, so a host adding 'recent' explicitly in
+ // front of the default set doesn't get two Recent tabs.
+ const seen = new Set();
+ return out.filter((s) => (seen.has(s.id) ? false : (seen.add(s.id), true)));
+}
+
+function resolveOne(entry, cfg) {
+ if (!entry) return null;
+ if (typeof entry === 'object') return entry;
+ const key = String(entry).trim();
+
+ if (key === 'three.ws' || key === 'default') {
+ return [recentSource(cfg), threeWsObjectsSource(cfg)];
+ }
+ if (key === 'recent' || key === 'recents') return recentSource(cfg);
+ if (key === 'objects') return threeWsObjectsSource(cfg);
+ if (key === 'community') return threeWsCommunitySource(cfg);
+ if (key === 'link') return LINK_SOURCE;
+ if (key === 'none' || key === 'empty') return null;
+ if (/^https:\/\//i.test(key) || key.startsWith('/')) return manifestSource({ url: key });
+ throw new Error(`ar-studio: unknown asset source "${key}"`);
+}
diff --git a/packages/ar-studio/src/sources/manifest.js b/packages/ar-studio/src/sources/manifest.js
new file mode 100644
index 000000000..4287ebe43
--- /dev/null
+++ b/packages/ar-studio/src/sources/manifest.js
@@ -0,0 +1,129 @@
+// A source backed by any JSON catalogue at a URL.
+//
+// This is the escape hatch that makes the studio yours: host a JSON file
+// anywhere with open CORS and point `assets` at it. Five shapes are accepted so
+// an existing manifest usually needs no reshaping at all:
+//
+// [ { url, name } … ] a bare array
+// { items: [ … ] } the canonical wrapper
+// { objects: [ … ] } three.ws object library
+// { avatars: [ … ] } three.ws avatar library
+// { creations: [ … ] } three.ws forge gallery
+// { models: [ … ] } common third-party wrapper
+//
+// Per-item, the model URL is read from the first present of
+// `src | url | glb | glb_url | glbUrl | file | model`, the label from
+// `title | label | name | prompt`, and the thumbnail from
+// `poster | thumb | thumbnail | image | preview_image_url | previewImageUrl`.
+// Anything that is not an https (or site-relative) URL is dropped rather than
+// handed to the loader.
+
+import { safeUrl } from '../config.js';
+
+/**
+ * @param {object} opts
+ * @param {string} opts.url JSON catalogue URL.
+ * @param {string} [opts.id] Tab key. Defaults to a slug of the label.
+ * @param {string} [opts.label] Tab label. Defaults to 'Models'.
+ * @param {string} [opts.hint] Line rendered under the search box.
+ * @param {boolean} [opts.searchable] Show the filter box. Defaults to true when
+ * the catalogue returns more than 24 items.
+ * @param {(item: object) => object|null} [opts.map] Custom per-item mapper. Return
+ * `{ src, title, poster, keywords }` or null to drop the entry.
+ * @param {(url: string) => string} [opts.rewriteUrl] Rewrite each asset URL, e.g. to
+ * route a CDN through a proxy that answers CORS.
+ * @param {RequestInit} [opts.fetchOptions]
+ */
+export function manifestSource({
+ url, id, label = 'Models', hint = '', searchable, map, rewriteUrl, fetchOptions,
+} = {}) {
+ if (!url) throw new Error('ar-studio: manifestSource needs a url');
+ return {
+ id: id || slug(label) || 'models',
+ label,
+ hint,
+ searchable,
+ async list() {
+ const res = await fetch(url, fetchOptions);
+ if (!res.ok) throw new Error(`catalogue ${res.status}`);
+ const data = await res.json();
+ return normalizeCatalogue(data, { map, rewriteUrl });
+ },
+ };
+}
+
+/** Pull the item array out of any of the accepted wrapper shapes. */
+export function catalogueItems(data) {
+ if (Array.isArray(data)) return data;
+ for (const key of ['items', 'objects', 'avatars', 'creations', 'models', 'assets', 'results']) {
+ if (Array.isArray(data?.[key])) return data[key];
+ }
+ return [];
+}
+
+const SRC_KEYS = ['src', 'url', 'glb', 'glb_url', 'glbUrl', 'file', 'model', 'modelUrl'];
+const TITLE_KEYS = ['title', 'label', 'name', 'prompt', 'displayName'];
+const POSTER_KEYS = ['poster', 'thumb', 'thumbnail', 'image', 'preview_image_url', 'previewImageUrl', 'preview'];
+
+function pick(obj, keys) {
+ for (const k of keys) {
+ const v = obj?.[k];
+ if (typeof v === 'string' && v.trim()) return v.trim();
+ }
+ return '';
+}
+
+/**
+ * Normalize any catalogue payload into tray items. Exported so a host writing a
+ * custom source can reuse the same tolerant reader.
+ *
+ * @param {unknown} data
+ * @param {{ map?: Function, rewriteUrl?: Function }} [opts]
+ * @returns {Array<{src:string,title:string,poster:string,keywords:string}>}
+ */
+export function normalizeCatalogue(data, { map, rewriteUrl } = {}) {
+ const raw = catalogueItems(data);
+ const out = [];
+ for (const entry of raw) {
+ if (!entry || typeof entry !== 'object') continue;
+ const item = map ? map(entry) : defaultMap(entry);
+ if (!item) continue;
+ const src = safeUrl(rewriteUrl ? rewriteUrl(item.src) : item.src);
+ if (!src) continue;
+ const poster = item.poster ? safeUrl(rewriteUrl ? rewriteUrl(item.poster) : item.poster) : '';
+ out.push({
+ src,
+ title: String(item.title || '').slice(0, 160),
+ poster: poster || '',
+ keywords: String(item.keywords || item.title || '').trim().toLowerCase(),
+ });
+ }
+ return out;
+}
+
+function defaultMap(entry) {
+ const src = pick(entry, SRC_KEYS);
+ if (!src) return null;
+ const title = pick(entry, TITLE_KEYS) || filenameTitle(src);
+ const tags = []
+ .concat(Array.isArray(entry.categories) ? entry.categories : [])
+ .concat(Array.isArray(entry.tags) ? entry.tags : [])
+ .join(' ');
+ return {
+ src,
+ title,
+ poster: pick(entry, POSTER_KEYS),
+ keywords: `${title} ${tags}`.trim().toLowerCase(),
+ };
+}
+
+/** A readable label from a file name: `alarm_clock_01.glb` → `Alarm clock 01`. */
+export function filenameTitle(url) {
+ const base = String(url).split('?')[0].split('/').pop() || 'Model';
+ const stem = base.replace(/\.(glb|gltf)$/i, '').replace(/[_-]+/g, ' ').trim();
+ return stem ? stem.charAt(0).toUpperCase() + stem.slice(1) : 'Model';
+}
+
+function slug(s) {
+ return String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
+}
diff --git a/packages/ar-studio/src/sources/recents.js b/packages/ar-studio/src/sources/recents.js
new file mode 100644
index 000000000..5efc32304
--- /dev/null
+++ b/packages/ar-studio/src/sources/recents.js
@@ -0,0 +1,61 @@
+// The models this browser generated or placed recently, held in localStorage.
+//
+// It is the tab that makes the studio feel like yours after one use: generate a
+// model, close the tab, come back tomorrow, it is still the first thing you see.
+// Storage failures (private mode, disabled storage, a quota wall) degrade to an
+// empty list, never a thrown error.
+
+import { safeUrl } from '../config.js';
+
+const DEFAULT_KEY = 'ar-studio:recent:v1';
+const MAX = 12;
+
+/** Read the recents list for a storage key. Corrupt or hostile payloads read as empty. */
+export function readRecents(key = DEFAULT_KEY) {
+ try {
+ const raw = JSON.parse(localStorage.getItem(key) || '[]');
+ if (!Array.isArray(raw)) return [];
+ return raw
+ .map((e) => ({
+ src: safeUrl(e?.src || e?.glb),
+ title: String(e?.title || e?.prompt || '').slice(0, 160),
+ poster: e?.poster ? safeUrl(e.poster) || '' : '',
+ ts: Number(e?.ts) || 0,
+ }))
+ .filter((e) => e.src);
+ } catch {
+ return [];
+ }
+}
+
+/** Push one model to the front of the recents list (de-duplicated by source). */
+export function rememberRecent({ src, title = '', poster = '' }, key = DEFAULT_KEY) {
+ const url = safeUrl(src);
+ if (!url) return;
+ try {
+ const list = readRecents(key).filter((e) => e.src !== url);
+ list.unshift({ src: url, title: String(title).slice(0, 200), poster: poster || '', ts: Date.now() });
+ localStorage.setItem(key, JSON.stringify(list.slice(0, MAX)));
+ } catch {
+ // Storage unavailable: recents are a convenience, never a gate.
+ }
+}
+
+/**
+ * @param {object} [cfg] Studio config: `recentKey` overrides the storage key.
+ */
+export function recentSource(cfg = {}) {
+ const key = cfg.recentKey || DEFAULT_KEY;
+ return {
+ id: 'recent',
+ label: 'Recent',
+ hint: '',
+ live: true, // re-read on every open: this list changes as you work
+ emptyCopy: 'Nothing here yet. Generate a model below, or paste a GLB link, and it lands in this tab.',
+ async list() {
+ return readRecents(key).map((e) => ({
+ src: e.src, title: e.title, poster: e.poster, keywords: e.title.toLowerCase(),
+ }));
+ },
+ };
+}
diff --git a/packages/ar-studio/src/sources/static.js b/packages/ar-studio/src/sources/static.js
new file mode 100644
index 000000000..8cfa7fa67
--- /dev/null
+++ b/packages/ar-studio/src/sources/static.js
@@ -0,0 +1,29 @@
+// A source built from a list you hold in code. The simplest way to ship your own
+// products into the studio:
+//
+// staticSource({ label: 'Our catalogue', items: [
+// { src: 'https://cdn.acme.com/chair.glb', title: 'Aero chair', poster: '…' },
+// ] })
+
+import { normalizeCatalogue } from './manifest.js';
+
+/**
+ * @param {object} opts
+ * @param {Array<object>} opts.items Entries in any of the shapes manifestSource accepts.
+ * @param {string} [opts.id]
+ * @param {string} [opts.label]
+ * @param {string} [opts.hint]
+ * @param {boolean} [opts.searchable]
+ */
+export function staticSource({ items = [], id = 'catalogue', label = 'Catalogue', hint = '', searchable } = {}) {
+ const normalized = normalizeCatalogue(items);
+ return {
+ id,
+ label,
+ hint,
+ searchable,
+ async list() {
+ return normalized;
+ },
+ };
+}
diff --git a/packages/ar-studio/src/sources/three-ws.js b/packages/ar-studio/src/sources/three-ws.js
new file mode 100644
index 000000000..f40579180
--- /dev/null
+++ b/packages/ar-studio/src/sources/three-ws.js
@@ -0,0 +1,66 @@
+// The built-in three.ws catalogues.
+//
+// three.ws hosts the model library this package pulls from by default: a few
+// hundred CC0 props (Poly Haven, packed to web GLB) plus the community feed of
+// models people generated on the platform. Both are keyless and free. Assets are
+// served first-party through https://three.ws/cdn/<key>, which answers
+// `access-control-allow-origin: *`, so they load from any origin: your GitHub
+// Pages demo included.
+//
+// Nothing here is required. Point `assets` at your own manifest and three.ws
+// drops out of the picture entirely.
+
+import { THREE_WS } from '../config.js';
+import { manifestSource, normalizeCatalogue } from './manifest.js';
+
+/**
+ * Rewrite a raw bucket URL onto the first-party CDN path, which is the copy that
+ * answers CORS. Leaves anything else untouched.
+ */
+export function cdnUrl(url, origin = THREE_WS.origin) {
+ const s = String(url || '');
+ const m = s.match(/^https:\/\/pub-[a-z0-9]+\.r2\.dev\/(.+)$/i);
+ return m ? `${origin.replace(/\/$/, '')}/cdn/${m[1]}` : s;
+}
+
+/** The CC0 prop library: hundreds of public-domain objects, free for commercial use. */
+export function threeWsObjectsSource(cfg = {}) {
+ const origin = (cfg.origin || THREE_WS.origin).replace(/\/$/, '');
+ const url = cfg.objectsManifest || THREE_WS.objectsManifest;
+ return {
+ ...manifestSource({
+ url,
+ id: 'objects',
+ label: 'Objects',
+ searchable: true,
+ rewriteUrl: (u) => cdnUrl(u, origin),
+ }),
+ hint: 'Public-domain (CC0) props from three.ws: free to use anywhere, commercially too.',
+ emptyCopy: 'The object library is unreachable right now. Check your connection and retry.',
+ };
+}
+
+/**
+ * Models the three.ws community generated. Read-only and free.
+ *
+ * Note: unlike the CDN catalogue above, this endpoint answers CORS for a fixed
+ * allow-list of origins, so it is not part of the default tab set: enable it
+ * with `assets: ['recent', 'objects', 'community']` when your page is served
+ * from three.ws, from localhost against a dev API, or through your own proxy
+ * (`endpoint` below points it anywhere).
+ */
+export function threeWsCommunitySource(cfg = {}) {
+ const origin = (cfg.origin || THREE_WS.origin).replace(/\/$/, '');
+ const endpoint = cfg.galleryEndpoint || `${origin}/api/forge-gallery`;
+ return {
+ id: 'community',
+ label: 'Community',
+ hint: 'Fresh models generated by the three.ws community.',
+ emptyCopy: 'The community feed is quiet right now. Check back in a bit.',
+ async list() {
+ const res = await fetch(`${endpoint}?scope=community&limit=48`);
+ if (!res.ok) throw new Error(`gallery ${res.status}`);
+ return normalizeCatalogue(await res.json(), { rewriteUrl: (u) => cdnUrl(u, origin) });
+ },
+ };
+}
diff --git a/packages/ar-studio/src/studio/anchor-lifecycle.js b/packages/ar-studio/src/studio/anchor-lifecycle.js
new file mode 100644
index 000000000..4e0763fa8
--- /dev/null
+++ b/packages/ar-studio/src/studio/anchor-lifecycle.js
@@ -0,0 +1,171 @@
+// Pure lifecycle policy for the WebXR floor-anchor session.
+//
+// AR's happy path is easy; production readiness lives entirely in the unhappy
+// ones: the app gets backgrounded, ARCore loses tracking in low light, a device
+// advertises anchors it can't honour, the user taps before the first GPS fix.
+// Each of those must resolve to a defined, recoverable outcome. The rules that
+// decide those outcomes live here, free of DOM / Three.js / wall-clock, so every
+// branch is provable without a phone.
+//
+// `./multi-place.js` consumes these helpers; it owns only the
+// side effects (callbacks, render loop, pin persistence), never the policy.
+
+// ── Tracking loss ───────────────────────────────────────────────────────────
+// A single frame with no viewer pose is normal jitter; a sustained run of them
+// means the device has lost its fix on the room. Surface "lost" only after a
+// short run (not a one-frame blip) and recover the instant a pose returns
+// transition-only, exactly like the hit-test reticle's searching/found state.
+
+/** Consecutive pose-less frames before we declare tracking lost (~0.5s @ 60fps). */
+export const TRACKING_LOSS_FRAMES = 30;
+
+/**
+ * Advance the tracking-health state machine by one frame.
+ * @param {{misses:number, lost:boolean}|null} prev Prior state (null = fresh).
+ * @param {boolean} hasPose Whether this frame yielded a viewer pose.
+ * @param {number} [threshold=TRACKING_LOSS_FRAMES] Misses tolerated before "lost".
+ * @returns {{state:{misses:number,lost:boolean}, changed:boolean, lost:boolean}}
+ * `changed` is true only on the lost↔recovered transition, so callers can fire
+ * a host callback once per state change instead of every frame.
+ */
+export function nextTrackingState(prev, hasPose, threshold = TRACKING_LOSS_FRAMES) {
+ const cur = prev || { misses: 0, lost: false };
+ if (hasPose) {
+ // A pose this frame clears the miss streak; report recovery if we were lost.
+ return { state: { misses: 0, lost: false }, changed: cur.lost === true, lost: false };
+ }
+ const misses = cur.misses + 1;
+ const lost = misses >= threshold;
+ return { state: { misses, lost }, changed: lost && !cur.lost, lost };
+}
+
+// ── Visibility / interruption ────────────────────────────────────────────────
+// XRSession.visibilityState ('visible' | 'visible-blurred' | 'hidden'): only the
+// first means the session is in the foreground and worth animating.
+
+/** visibilityState values where the session is interrupted (backgrounded/blurred). */
+export const XR_PAUSED_STATES = new Set(['hidden', 'visible-blurred']);
+
+/**
+ * @param {string} visibilityState XRSession.visibilityState.
+ * @returns {boolean} true when the session is foreground-visible.
+ */
+export function isXrVisible(visibilityState) {
+ return !XR_PAUSED_STATES.has(visibilityState);
+}
+
+// ── Degraded-anchor honesty ──────────────────────────────────────────────────
+// When createAnchor() yields no XRAnchor the agent is frozen at the tap pose
+// it still works and still saves a pin, but it may drift. Say so rather than
+// pretending it's rock-solid.
+
+/**
+ * @param {boolean} degraded true when no real XRAnchor backs the placement.
+ * @returns {string} Honest, user-facing placement copy.
+ */
+export function placementHint(degraded) {
+ return degraded
+ ? 'Placed: it may drift a little on this device'
+ : 'Placed: walk around, it stays put';
+}
+
+// ── Reticle look (task 04: searching ↔ locked) ────────────────────────────────
+// The floor reticle reads as two states: dim + breathing while it hunts for a
+// surface, bright + full with a filled centre once it locks. The mapping from the
+// eased lock amount (and a breathing phase) to concrete scale/opacity/dot/colour
+// values lives here as a pure function so the *look* is unit-tested rather than
+// eyeballed on a phone: `./multi-place.js` only feeds it inputs and pushes the
+// results onto Three.js materials. Writes into a caller-owned `out` object so the
+// render loop reuses one buffer and adds zero per-frame allocations.
+
+function _clamp01(n) {
+ return n < 0 ? 0 : n > 1 ? 1 : n;
+}
+
+/**
+ * @param {{scale:number,opacity:number,dot:number,colorMix:number}} out Reused buffer.
+ * @param {number} hit Eased 0→1 lock amount (0 = searching, 1 = locked).
+ * @param {number} breathe 0→1 searching pulse phase (ignored when reduced).
+ * @param {boolean} reduced prefers-reduced-motion: flatten to calm static values.
+ * @returns {{scale:number,opacity:number,dot:number,colorMix:number}} `out`.
+ */
+export function reticleVisual(out, hit, breathe = 0, reduced = false) {
+ const h = _clamp01(hit);
+ const b = reduced ? 0 : _clamp01(breathe);
+ // Searching: smaller + dimmer, gently breathing. Reduced motion holds a calm
+ // mid value with no pulse. Locked values are the same regardless of motion pref.
+ const searchScale = reduced ? 0.94 : 0.86 + b * 0.10;
+ const searchOpacity = reduced ? 0.5 : 0.34 + b * 0.18;
+ out.scale = searchScale + (1 - searchScale) * h; // → 1.0 at full lock
+ out.opacity = searchOpacity + (0.96 - searchOpacity) * h;
+ out.dot = h; // inner dot fills in as the surface locks
+ out.colorMix = h; // dim purple → bright lock colour
+ return out;
+}
+
+// ── Confirm pulse (task 04: the commit beat) ──────────────────────────────────
+// On a successful anchor a single ring expands and fades out from the tap point
+// the visible half of the confirm beat (the haptic + ✓ copy are the other halves).
+// One-shot, eased, allocation-free: advance a caller-owned state object each frame
+// until `done`.
+
+/** Duration of the confirm pulse-out ring, in seconds. */
+export const RETICLE_PULSE_SECONDS = 0.55;
+
+/**
+ * @param {{t:number,scale:number,opacity:number,done:boolean}} out Reused state.
+ * @param {number} dt Seconds since the last frame.
+ * @param {number} [duration=RETICLE_PULSE_SECONDS]
+ * @returns {{t:number,scale:number,opacity:number,done:boolean}} `out`.
+ */
+export function advancePulse(out, dt, duration = RETICLE_PULSE_SECONDS) {
+ const next = out.t + dt;
+ const k = next >= duration ? 1 : next / duration;
+ const eased = 1 - (1 - k) * (1 - k); // ease-out
+ out.t = next;
+ out.scale = 1 + eased * 2; // 1 → 3×
+ out.opacity = 0.85 * (1 - k); // 0.85 → 0
+ out.done = next >= duration;
+ return out;
+}
+
+// ── Pre-GPS replay gate ──────────────────────────────────────────────────────
+// The one durable side effect of a placement is the GPS pin, and it must save
+// EXACTLY once. A tap with a live fix saves immediately; a tap during GPS
+// warm-up holds the pose and saves on the first fix; leaving before that fix
+// drops it (the user walked away: don't surprise them with a late pin). The
+// gate owns the held pose and the consumed-guard so no caller can double-save,
+// save zero times, or save a pose that was abandoned.
+
+/**
+ * @param {(pose:any)=>void} persist Side effect that durably saves one pose.
+ * @returns {{
+ * place:(pose:any, ready:boolean)=>'persisted'|'held',
+ * onFix:(ready:boolean)=>boolean,
+ * drop:()=>void,
+ * hasPending:()=>boolean,
+ * }}
+ */
+export function createPersistGate(persist) {
+ let pending = null;
+ return {
+ // A tap landed. With a live fix, persist now; otherwise hold for the fix.
+ place(pose, ready) {
+ if (ready) { persist(pose); return 'persisted'; }
+ pending = pose;
+ return 'held';
+ },
+ // The first GPS fix landed. Persist a held pose once, then forget it.
+ // Returns true iff this call performed the (single) persist.
+ onFix(ready) {
+ if (!ready || pending === null) return false;
+ const pose = pending;
+ pending = null;
+ persist(pose);
+ return true;
+ },
+ // Session ended before a fix: drop the held pose. Idempotent.
+ drop() { pending = null; },
+ hasPending() { return pending !== null; },
+ };
+}
diff --git a/packages/ar-studio/src/studio/camera-fov.js b/packages/ar-studio/src/studio/camera-fov.js
new file mode 100644
index 000000000..6edb79d7c
--- /dev/null
+++ b/packages/ar-studio/src/studio/camera-fov.js
@@ -0,0 +1,83 @@
+// Pure camera-FOV math for the AR camera passthrough.
+//
+// Why this exists
+// ───────────────
+// In AR the Three.js camera must share the REAL rear camera's field of view, or
+// the avatar renders at the wrong scale: too small and it looks like a toy on the
+// floor, too large and it clips through real objects. The phone exposes the video
+// track's pixel dimensions (`track.getSettings()`), and rear cameras run at a
+// roughly fixed ~72° DIAGONAL FOV, so we can recover the horizontal FOV from the
+// sensor aspect and then the vertical FOV (what Three.js wants) from the VIEWPORT
+// aspect: which is what actually fills the screen.
+//
+// This was inlined in enableAR() and only ran ONCE, so rotating portrait↔landscape
+// left the avatar at the portrait scale. Extracted here as a pure function the
+// resize/orientation path can re-run every time the viewport changes, and the test
+// suite verifies the optics directly (mirrors ./sensor-fusion.js).
+//
+// No DOM, no Three.js: plain numbers in, a clamped vertical-FOV in degrees out.
+
+// Typical rear-camera diagonal field of view in degrees. iOS/Android rear cameras
+// cluster tightly around this; it is the one constant the device does not report.
+export const DEFAULT_DIAG_FOV_DEG = 72;
+
+// Three.js PerspectiveCamera.fov is sane between these. We clamp so a degenerate
+// track dimension (0×0, 1×1) or an extreme aspect can never produce a NaN/∞ or a
+// fish-eye/pinhole projection that detaches the avatar from the floor.
+export const VFOV_MIN_DEG = 50;
+export const VFOV_MAX_DEG = 90;
+
+const DEG = Math.PI / 180;
+const RAD = 180 / Math.PI;
+
+/**
+ * Vertical FOV (degrees) for the Three.js camera, derived from the rear-camera
+ * sensor and the on-screen viewport.
+ *
+ * Steps: the sensor's diagonal FOV → its HORIZONTAL FOV (via the sensor aspect)
+ * → the VERTICAL FOV that fills a viewport of `viewAspect`. Using the sensor
+ * aspect for the first step and the viewport aspect for the second is what keeps
+ * the scale correct as the viewport rotates while the camera sensor does not.
+ *
+ * Every input is defended: a non-finite or non-positive dimension/aspect falls
+ * back to a sensible value, and the result is clamped to [VFOV_MIN, VFOV_MAX], so
+ * this is always safe to call straight from a resize handler.
+ *
+ * @param {object} p
+ * @param {number} p.trackWidth video track pixel width (sensor)
+ * @param {number} p.trackHeight video track pixel height (sensor)
+ * @param {number} p.viewWidth viewport CSS pixel width
+ * @param {number} p.viewHeight viewport CSS pixel height
+ * @param {number} [p.diagFovDeg] sensor diagonal FOV (default ~72°)
+ * @returns {number} vertical FOV in degrees, clamped
+ */
+export function deriveVerticalFovDeg({
+ trackWidth,
+ trackHeight,
+ viewWidth,
+ viewHeight,
+ diagFovDeg = DEFAULT_DIAG_FOV_DEG,
+}) {
+ const tw = posOr(trackWidth, viewWidth);
+ const th = posOr(trackHeight, viewHeight);
+ const vw = posOr(viewWidth, tw);
+ const vh = posOr(viewHeight, th);
+ const diag = posOr(diagFovDeg, DEFAULT_DIAG_FOV_DEG);
+
+ // Sensor diagonal → sensor horizontal FOV.
+ const diagPx = Math.hypot(tw, th) || 1;
+ const hFovRad = 2 * Math.atan((tw / diagPx) * Math.tan((diag * DEG) / 2));
+
+ // Sensor horizontal FOV → viewport vertical FOV (viewport aspect drives this).
+ const viewAspect = vw / vh;
+ const vFovRad = 2 * Math.atan(Math.tan(hFovRad / 2) / (viewAspect || 1));
+ const vFovDeg = vFovRad * RAD;
+
+ if (!Number.isFinite(vFovDeg)) return VFOV_MIN_DEG;
+ return Math.max(VFOV_MIN_DEG, Math.min(VFOV_MAX_DEG, vFovDeg));
+}
+
+function posOr(v, fallback) {
+ const n = Number(v);
+ return Number.isFinite(n) && n > 0 ? n : (Number(fallback) > 0 ? Number(fallback) : 1);
+}
diff --git a/packages/ar-studio/src/studio/capture.js b/packages/ar-studio/src/studio/capture.js
new file mode 100644
index 000000000..539853482
--- /dev/null
+++ b/packages/ar-studio/src/studio/capture.js
@@ -0,0 +1,89 @@
+// Photo capture for the AR view.
+//
+// Flattens the live camera feed and the WebGL canvas into one PNG and offers it
+// through the native share sheet, with a desktop download fallback and a final
+// URL-share → clipboard chain when the frame cannot be read. A screenshot of
+// your models standing in your actual room is the thing people send to a friend,
+// so it is a first-class button, not an afterthought.
+//
+// Requires the renderer to be built with `preserveDrawingBuffer: true`, or the
+// canvas reads back blank between frames.
+//
+// Ported from the three.ws IRL/XR share lane (Apache-2.0).
+
+/**
+ * Flatten the camera feed (when in AR) and the 3D canvas into one PNG blob.
+ *
+ * @param {object} opts
+ * @param {HTMLCanvasElement} opts.canvas The WebGL canvas, drawn on top with alpha.
+ * @param {HTMLVideoElement} [opts.video] The camera passthrough, drawn behind.
+ * @param {boolean} [opts.isAR] True when the camera feed is the backdrop.
+ * @returns {Promise<Blob|null>} PNG blob, or null when the canvas has no pixels yet.
+ */
+export async function captureComposite({ canvas, video, isAR }) {
+ if (!canvas) return null;
+ const w = canvas.width;
+ const h = canvas.height; // renderer pixel size, not CSS size
+ if (!w || !h) return null;
+
+ const out = document.createElement('canvas');
+ out.width = w;
+ out.height = h;
+ const ctx = out.getContext('2d');
+ if (!ctx) return null;
+
+ if (isAR && video && !video.paused && video.videoWidth) {
+ try {
+ ctx.drawImage(video, 0, 0, w, h);
+ } catch {
+ // Tainted or not yet playing: skip the backdrop, keep the models.
+ }
+ }
+ try {
+ ctx.drawImage(canvas, 0, 0);
+ } catch {
+ return null;
+ }
+
+ return new Promise((resolve) => out.toBlob(resolve, 'image/png'));
+}
+
+/**
+ * Share a blob through the native sheet, falling back to a download.
+ *
+ * @param {Blob} blob
+ * @param {{filename?: string, title?: string}} [opts]
+ * @returns {Promise<'shared'|'downloaded'>}
+ */
+export async function shareOrDownload(blob, { filename = 'ar-studio.png', title = 'AR Studio' } = {}) {
+ const file = new File([blob], filename, { type: 'image/png' });
+ if (navigator.share && navigator.canShare?.({ files: [file] })) {
+ await navigator.share({ title, files: [file] });
+ return 'shared';
+ }
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(url), 4000);
+ return 'downloaded';
+}
+
+/**
+ * Share a URL through the native sheet, falling back to a clipboard copy.
+ * @returns {Promise<'shared'|'copied'>}
+ */
+export async function shareUrlOrCopy(url, { title = 'AR Studio', text = '' } = {}) {
+ if (navigator.share) {
+ try {
+ await navigator.share({ title, url, ...(text ? { text } : {}) });
+ return 'shared';
+ } catch (err) {
+ // A cancelled sheet is a decision, not a failure: do not fall through.
+ if (err?.name === 'AbortError') throw err;
+ }
+ }
+ await navigator.clipboard.writeText(url);
+ return 'copied';
+}
diff --git a/packages/ar-studio/src/studio/coords.js b/packages/ar-studio/src/studio/coords.js
new file mode 100644
index 000000000..ebc861e64
--- /dev/null
+++ b/packages/ar-studio/src/studio/coords.js
@@ -0,0 +1,123 @@
+// Pure coordinate and room-key helpers for the shared AR Studio. DOM-free and
+// Three-free so they unit-test directly.
+//
+// Two frames:
+// • LOCAL: the studio's own scene. A model sits at (x, z) metres on the floor
+// with yaw in radians (Three's Y rotation). Origin is where this device's
+// view started; +x is right, −z is "into the scene / forward".
+// • SHARED (logical): what rides the wire so every device agrees. relEast /
+// relNorth metres from the room's common origin, yaw in degrees. We map
+// forward (−z) → north and right (+x) → east. When two phones are co-located
+// via a QR marker, the marker frame makes these logical coords land on the
+// same physical spot; otherwise each device just re-bases them to its own
+// floor origin, so everyone sees the same ARRANGEMENT in their own space.
+
+const TAU = Math.PI * 2;
+
+/** Normalize any radian angle into [0, 2π). */
+export function normRad(a) {
+ if (!Number.isFinite(a)) return 0;
+ return ((a % TAU) + TAU) % TAU;
+}
+
+/** Normalize any degree angle into [0, 360). */
+export function normDeg(d) {
+ if (!Number.isFinite(d)) return 0;
+ return ((d % 360) + 360) % 360;
+}
+
+/**
+ * Local scene transform → shared logical transform (for sending over the wire).
+ * @param {{ x:number, z:number, yaw:number, scale?:number, height?:number }} t
+ * yaw in RADIANS.
+ * @returns {{ relEast:number, relNorth:number, yawDeg:number, scale:number, height:number }}
+ */
+export function localToShared(t) {
+ return {
+ relEast: Number(t.x) || 0,
+ // `|| 0` also collapses the -0 that negating +0 produces: cleaner on the wire.
+ relNorth: -(Number(t.z) || 0) || 0,
+ yawDeg: normDeg((normRad(t.yaw) * 180) / Math.PI),
+ scale: Number(t.scale) || 1,
+ height: Number(t.height) || 0,
+ };
+}
+
+/**
+ * Shared logical transform (from the wire) → local scene transform.
+ * @param {{ relEast:number, relNorth:number, yawDeg:number, scale?:number }} s
+ * @returns {{ x:number, z:number, yaw:number, scale:number }} yaw in RADIANS.
+ */
+export function sharedToLocal(s) {
+ return {
+ x: Number(s.relEast) || 0,
+ z: -(Number(s.relNorth) || 0),
+ yaw: (normDeg(s.yawDeg) * Math.PI) / 180,
+ scale: Number(s.scale) || 1,
+ };
+}
+
+// ── Room codes ────────────────────────────────────────────────────────────────
+// A human-shareable, URL-safe code. Unambiguous alphabet: no 0/O/1/I/L: so a
+// code read aloud or typed from a screen doesn't collide. Six chars ≈ 32^6 ≈ 1e9
+// combinations, ample for concurrent ephemeral rooms.
+const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
+const CODE_LEN = 6;
+
+/**
+ * Normalize user-typed room input into a canonical code, or '' if unusable.
+ * Accepts a bare code or a pasted ?room=CODE URL. Upper-cases, drops
+ * the separators a human adds (spaces, hyphens), then validates STRICTLY against
+ * the alphabet + length: the generator never emits an ambiguous glyph, so a code
+ * carrying one is a mistype, not a near-miss to silently "fix".
+ * @param {unknown} raw
+ * @returns {string}
+ */
+export function normalizeRoomCode(raw) {
+ let s = String(raw ?? '').trim();
+ if (!s) return '';
+ const m = s.match(/[?&]room=([^&#\s]+)/i);
+ if (m) { try { s = decodeURIComponent(m[1]); } catch { s = m[1]; } }
+ s = s.toUpperCase().replace(/[\s-]+/g, '');
+ if (s.length !== CODE_LEN) return '';
+ for (const ch of s) if (!CODE_ALPHABET.includes(ch)) return '';
+ return s;
+}
+
+/**
+ * Generate a fresh room code. `rand` defaults to Math.random but is injectable
+ * so tests are deterministic (and so this never trips the workflow-script clock
+ * ban: app code only).
+ * @param {() => number} [rand]
+ * @returns {string}
+ */
+export function generateRoomCode(rand = Math.random) {
+ let out = '';
+ for (let i = 0; i < CODE_LEN; i++) {
+ out += CODE_ALPHABET[Math.floor(rand() * CODE_ALPHABET.length) % CODE_ALPHABET.length];
+ }
+ return out;
+}
+
+/**
+ * The Colyseus filterBy key for a room code. A code IS its own key; kept as a
+ * function so a future co-located (marker) key can funnel through one place.
+ * @param {string} code
+ * @returns {string}
+ */
+export function roomKeyForCode(code) {
+ return `c-${normalizeRoomCode(code)}`;
+}
+
+/**
+ * Build the shareable join URL for a room code, against the page hosting the
+ * studio.
+ * @param {string} baseUrl e.g. 'https://acme.com/ar/'
+ * @param {string} code
+ */
+export function roomShareUrl(baseUrl, code) {
+ const base = String(baseUrl || '').split('#')[0];
+ const c = normalizeRoomCode(code);
+ if (!c) return base;
+ return `${base}${base.includes('?') ? '&' : '?'}room=${c}`;
+}
diff --git a/packages/ar-studio/src/studio/depth-occlusion.js b/packages/ar-studio/src/studio/depth-occlusion.js
new file mode 100644
index 000000000..1139cb43e
--- /dev/null
+++ b/packages/ar-studio/src/studio/depth-occlusion.js
@@ -0,0 +1,120 @@
+// Real-world occlusion for WebXR via the depth-sensing API.
+//
+// On a depth-capable device the placed agent should hide behind real geometry
+// a couch, a doorway, a person walking in front: instead of always painting on
+// top of the camera feed. That single perception upgrade is what separates an
+// object that lives in the room from a sticker pasted on video.
+//
+// Mechanism (three.js gpu-optimized depth path): when the live session
+// negotiated `depth-sensing` with `gpu-optimized` usage, three's WebXRManager
+// pulls the per-frame XRWebGLDepthInformation, wraps it as an ExternalTexture,
+// and: every presenting frame: renders a fullscreen occluder quad *itself*,
+// ahead of the scene (`projectObject(getDepthSensingMesh(), camera, -Infinity)`
+// inside WebGLRenderer.render). That quad's fragment shader writes the
+// *real-world* depth into the depth buffer, so any agent fragment behind real
+// geometry fails the normal depth test and is discarded: true occlusion, no
+// custom shader of our own, and no need to add the mesh to the scene graph.
+// (Adding it would put the same mesh in the render list a second time and draw a
+// redundant fullscreen depth pass every frame.)
+//
+// This helper therefore does the two things three's built-in path leaves to the
+// app: (1) gate the whole thing on the feature actually being negotiated, and
+// (2) configure three's occluder material so it writes depth but *no colour*
+// the shader emits only gl_FragDepth, so the default colorWrite:true would paint
+// undefined garbage over the camera passthrough. It also frees the occluder's
+// GPU resources on exit, which three's own session-end reset() does not.
+//
+// Degrades silently: when the session has no depth-sensing feature (most devices
+// today) or the UA only offered cpu-optimized data, three never builds the mesh,
+// this never configures anything, and behavior is byte-for-byte identical to the
+// pre-occlusion path: no error, no console noise, the AR button works as before.
+
+export class DepthOcclusion {
+ /**
+ * @param {import('three').WebGLRenderer} renderer Active XR renderer. The
+ * occluder mesh is owned and drawn by `renderer.xr` itself, so the scene is
+ * never needed here: this only reads + configures what three exposes.
+ */
+ constructor(renderer) {
+ this._renderer = renderer;
+ /** @type {import('three').Mesh|null} three's occluder, once configured. */
+ this._mesh = null;
+ this._enabled = false;
+ }
+
+ /**
+ * Cheap one-shot check: did the live session actually negotiate depth-sensing?
+ * Use it right after `renderer.xr.setSession` to decide whether to stand up the
+ * occluder at all: on every other device this is false and the per-frame tick
+ * never touches depth. The optional chaining guards UAs that don't populate
+ * `enabledFeatures` (the spec leaves it optional).
+ * @param {XRSession|null|undefined} session
+ * @returns {boolean}
+ */
+ static sessionHasDepth(session) {
+ return !!session?.enabledFeatures?.includes?.('depth-sensing');
+ }
+
+ /**
+ * Per-frame hook. Configures three's occluder material the first frame real
+ * depth data is available, then returns immediately on every subsequent frame
+ * three owns the mesh and updates the depth texture in place, so no further
+ * work (and zero allocation) is needed in steady state. Must run before the
+ * frame's `renderer.render` so the material is set before three draws the quad.
+ * Safe to call when depth-sensing is unsupported: the renderer reports no depth
+ * and this is a no-op.
+ */
+ update() {
+ if (this._mesh) return; // configured: three drives the texture + draw each frame
+ const xr = this._renderer.xr;
+ // Three only builds the occluder for the gpu-optimized path; if the UA
+ // handed back cpu-optimized data this stays false forever and we degrade.
+ if (typeof xr.hasDepthSensing !== 'function' || !xr.hasDepthSensing()) return;
+ const mesh = xr.getDepthSensingMesh?.();
+ if (mesh) this._configure(mesh);
+ }
+
+ /** @param {import('three').Mesh} mesh three's cached depth-sensing occluder. */
+ _configure(mesh) {
+ const material = mesh.material;
+ // The occluder exists only to stamp real-world depth: it must paint no
+ // colour, or the passthrough camera feed shows shader garbage where the
+ // agent isn't drawn (three's occlusion shader emits gl_FragDepth only and
+ // never assigns a colour, so the default colorWrite:true is undefined out).
+ material.colorWrite = false;
+ material.depthWrite = true;
+ // Fullscreen depth fill on a freshly-cleared buffer: always write, never
+ // gate on a prior depth value.
+ material.depthTest = false;
+ // The vertex shader emits clip-space coordinates directly and ignores the
+ // model matrix, so the mesh's world bounds are meaningless: never let
+ // frustum culling drop it as the camera moves around the room.
+ mesh.frustumCulled = false;
+ this._mesh = mesh;
+ this._enabled = true;
+ }
+
+ /** True once the occluder is live (configured for the current session). */
+ get enabled() {
+ return this._enabled;
+ }
+
+ /**
+ * Free the occluder on session exit. three's session-end `reset()` only nulls
+ * its references to the mesh + texture: it never disposes the geometry,
+ * material, or compiled program: so without this each AR entry would leak a
+ * fullscreen quad + shader program. By the time this runs the render loop is
+ * already stopped and no further frame draws the mesh, so freeing it is safe;
+ * three rebuilds a fresh occluder on the next session. The depth texture itself
+ * is an external handle owned by the XR runtime: material.dispose() never
+ * touches uniform textures, so it is correctly left alone.
+ */
+ dispose() {
+ if (this._mesh) {
+ this._mesh.geometry?.dispose();
+ this._mesh.material?.dispose();
+ this._mesh = null;
+ }
+ this._enabled = false;
+ }
+}
diff --git a/packages/ar-studio/src/studio/estimated-lighting.js b/packages/ar-studio/src/studio/estimated-lighting.js
new file mode 100644
index 000000000..eaa8322b4
--- /dev/null
+++ b/packages/ar-studio/src/studio/estimated-lighting.js
@@ -0,0 +1,104 @@
+// Real-world lighting for WebXR placements, via the WebXR Lighting Estimation
+// API (three's XREstimatedLight addon).
+//
+// A model lit by fixed studio lights always reads as pasted onto the camera
+// feed: its highlights point the wrong way, its whites are the wrong colour,
+// and a chrome surface reflects a room that isn't there. This wrapper replaces
+// the studio's baked lights with the room's ACTUAL light the moment the device
+// starts estimating it:
+//
+// • a LightProbe carrying the room's ambient spherical harmonics (soft fill
+// from every direction, the real colour of the space),
+// • a DirectionalLight aimed along the room's primary light with its measured
+// colour + intensity (a warm lamp vs cool daylight lands correctly), and
+// • a live environment cube map so metal/glass models reflect the real room.
+//
+// The swap is reversible and self-healing: until estimation actually starts the
+// baked lights stay on (no dark flash), and on session end: or if the device
+// never estimates: everything is restored byte-for-byte. Depends only on a
+// three.js addon; no new package, no custom shader.
+
+import { XREstimatedLight } from 'three/addons/webxr/XREstimatedLight.js';
+
+/**
+ * @param {object} opts
+ * @param {import('three').WebGLRenderer} opts.renderer Active XR renderer.
+ * @param {import('three').Scene} opts.scene
+ * @param {import('three').Light[]} opts.baseLights The studio's own lights,
+ * dimmed to zero while real estimation drives the scene and restored on end.
+ * @param {(active: boolean) => void} [opts.onChange] Fired true when real
+ * estimation takes over, false when it reverts: drives a "lit by your room"
+ * status line, purely informational.
+ */
+export class EstimatedLighting {
+ constructor({ renderer, scene, baseLights = [], onChange }) {
+ this._renderer = renderer;
+ this._scene = scene;
+ this._baseLights = baseLights;
+ this._onChange = onChange;
+
+ this._xrLight = null;
+ this._active = false;
+ this._savedEnv = scene.environment;
+ this._savedIntensities = baseLights.map((l) => l.intensity);
+
+ this._onEstimationStart = this._onEstimationStart.bind(this);
+ this._onEstimationEnd = this._onEstimationEnd.bind(this);
+ }
+
+ /**
+ * Stand up the estimated light. Call AFTER `renderer.xr.setSession` so the
+ * addon's own `sessionstart` listener fires and requests the light probe.
+ * A no-op-safe call: if the UA never delivers an estimate, the baked lights
+ * simply stay on and nothing here ever activates.
+ */
+ start() {
+ if (this._xrLight) return;
+ // environmentEstimation:true → also request the reflection cube map.
+ const xrLight = new XREstimatedLight(this._renderer, true);
+ xrLight.addEventListener('estimationstart', this._onEstimationStart);
+ xrLight.addEventListener('estimationend', this._onEstimationEnd);
+ this._scene.add(xrLight);
+ this._xrLight = xrLight;
+ }
+
+ get active() {
+ return this._active;
+ }
+
+ _onEstimationStart() {
+ if (!this._xrLight) return;
+ this._active = true;
+ // Hand the scene over to the real room: kill the baked lights so they
+ // don't double-expose, and reflect the real environment on PBR surfaces.
+ for (const l of this._baseLights) l.intensity = 0;
+ if (this._xrLight.environment) this._scene.environment = this._xrLight.environment;
+ this._onChange?.(true);
+ }
+
+ _onEstimationEnd() {
+ // The device stopped estimating (walked into the dark, lost tracking):
+ // fall back to the baked look rather than an unlit scene.
+ this._active = false;
+ this._restoreBase();
+ this._onChange?.(false);
+ }
+
+ _restoreBase() {
+ this._baseLights.forEach((l, i) => { l.intensity = this._savedIntensities[i]; });
+ this._scene.environment = this._savedEnv;
+ }
+
+ /** Tear down on session end. Restores the baked lights + environment. */
+ dispose() {
+ if (this._xrLight) {
+ this._xrLight.removeEventListener('estimationstart', this._onEstimationStart);
+ this._xrLight.removeEventListener('estimationend', this._onEstimationEnd);
+ this._scene.remove(this._xrLight);
+ this._xrLight.dispose?.();
+ this._xrLight = null;
+ }
+ this._restoreBase();
+ this._active = false;
+ }
+}
diff --git a/packages/ar-studio/src/studio/idle.js b/packages/ar-studio/src/studio/idle.js
new file mode 100644
index 000000000..569253bdb
--- /dev/null
+++ b/packages/ar-studio/src/studio/idle.js
@@ -0,0 +1,99 @@
+// Idle animation for any humanoid model, with no rig allowlist.
+//
+// A character standing in your room in a bind-pose T is the single fastest way
+// to break the illusion, and most GLBs of people ship with no baked clip at all.
+// So instead of shipping a curated list of supported rigs, the studio maps the
+// model's own bone names onto a canonical skeleton (Mixamo, Avaturn, Unreal,
+// VRM/VRoid, Daz, MakeHuman, Blender `.L`, and plain `shoulderL` conventions are
+// all covered) and retargets a pre-baked idle clip onto it.
+//
+// Rigs that genuinely cannot be driven (no skin, a non-humanoid prop) fail the
+// support gate and simply stay static: exactly as they would have anyway.
+// Animation is upside here, never a gate: every failure path returns null and
+// the model still shows up.
+//
+// The clip JSON is fetched once per page and shared by every model on it.
+
+import { AnimationManager } from '../anim/animation-manager.js';
+import { THREE_WS } from '../config.js';
+import { createLogger } from '../log.js';
+
+const log = createLogger('ar-studio:idle');
+
+let _clipPromise = null;
+let _clipKey = '';
+
+/**
+ * Fetch (once) the idle clip JSON from an animation manifest.
+ *
+ * @param {{manifestUrl?: string, clip?: string}} [opts]
+ * @returns {Promise<object|null>} raw AnimationClip JSON, or null when unavailable
+ */
+export function getIdleClipJson({ manifestUrl = THREE_WS.animationManifest, clip = 'idle' } = {}) {
+ const key = `${manifestUrl}#${clip}`;
+ if (_clipPromise && _clipKey === key) return _clipPromise;
+ _clipKey = key;
+ _clipPromise = (async () => {
+ const manifest = await fetch(manifestUrl, { cache: 'force-cache' }).then((r) => {
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.json();
+ });
+ const list = Array.isArray(manifest) ? manifest : (manifest?.clips || manifest?.animations || []);
+ const def = list.find((d) => d?.name === clip) || list[0];
+ if (!def?.url) throw new Error(`clip "${clip}" missing from the manifest`);
+ const url = new URL(def.url, manifestUrl).href;
+ const res = await fetch(url, { cache: 'force-cache' });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
+ })().catch((err) => {
+ log.warn('idle clip unavailable:', err?.message || err);
+ _clipPromise = null; // let a later mount retry rather than poisoning the page
+ return null;
+ });
+ return _clipPromise;
+}
+
+/**
+ * Attach an idle-playing AnimationManager to a freshly loaded model. Call BEFORE
+ * adding it to the scene: the retarget maps are captured from the authored bind
+ * pose.
+ *
+ * @param {import('three').Object3D} model The loaded gltf.scene (or a clone).
+ * @param {{manifestUrl?: string, clip?: string, sourceUrl?: string}} [opts]
+ * @returns {Promise<AnimationManager|null>} a manager already playing idle: call
+ * `.update(dt)` each frame and `.detach()` when the model is removed: or null
+ * when this rig cannot be driven.
+ */
+export async function mountIdle(model, { manifestUrl, clip = 'idle', sourceUrl = '' } = {}) {
+ const clipJson = await getIdleClipJson({ manifestUrl, clip });
+ if (!clipJson || !model) return null;
+ const mgr = new AnimationManager();
+ try {
+ mgr.attach(model, { avatarUrl: sourceUrl });
+ if (!mgr.supportsCanonicalClips()) {
+ mgr.detach();
+ return null;
+ }
+ // A rig whose arm bones did not name-map would idle its torso and legs with
+ // both arms frozen out in a T. Swing those undriven arms down first (a no-op
+ // when the arms do map), so a room full of models never shows that.
+ mgr.relaxUndrivenArms();
+ mgr.injectClip(clip, clipJson, { loop: true });
+ const playing = await mgr.play(clip);
+ if (!playing) {
+ mgr.detach();
+ return null;
+ }
+ // Desynchronize: start each model at a random phase so a group of them does
+ // not breathe in eerie lockstep.
+ const action = mgr.currentAction;
+ const duration = action?.getClip?.()?.duration || 0;
+ if (action && duration > 0) action.time = Math.random() * duration;
+ mgr.update(0);
+ return mgr;
+ } catch (err) {
+ log.warn('idle mount failed:', err?.message || err);
+ try { mgr.detach(); } catch { /* already clean */ }
+ return null;
+ }
+}
diff --git a/packages/ar-studio/src/studio/load-queue.js b/packages/ar-studio/src/studio/load-queue.js
new file mode 100644
index 000000000..daae5277a
--- /dev/null
+++ b/packages/ar-studio/src/studio/load-queue.js
@@ -0,0 +1,62 @@
+// A priority-ordered, concurrency-capped async runner.
+//
+// Ten models tapped in quick succession must not open ten simultaneous GLB
+// downloads on a phone: the network thrashes, the first model takes as long as
+// the last, and the frame rate collapses while they all decode at once. This
+// queue runs at most `maxActive` jobs, ordered by `priorityOf` (lower runs
+// sooner), and lets a caller cancel work that is no longer wanted.
+//
+// Ported from the three.ws IRL loader (Apache-2.0).
+
+// Generic priority queue with a concurrency cap. `run(item)` returns a promise;
+// jobs start nearest-first via `priorityOf(item)` (lower number = sooner). The
+// queue never rejects the caller's promise on cancellation silently: a
+// cancelled job rejects with an Error('cancelled') the caller can ignore.
+export function createLoadQueue({ run, maxActive = 5, priorityOf = () => 0 }) {
+ const queue = []; // [{ item, resolve, reject, cancelled }]
+ let active = 0;
+ const cfg = { run, maxActive, priorityOf };
+
+ function pump() {
+ // Re-sort on every pump so freshly-updated distances (the user moved) reorder
+ // the pending loads before the next slot opens. O(n log n) over a small list.
+ if (queue.length > 1) queue.sort((a, b) => cfg.priorityOf(a.item) - cfg.priorityOf(b.item));
+ while (active < cfg.maxActive && queue.length) {
+ const job = queue.shift();
+ if (job.cancelled) continue;
+ active++;
+ Promise.resolve()
+ .then(() => cfg.run(job.item))
+ .then(job.resolve, job.reject)
+ .finally(() => { active--; pump(); });
+ }
+ }
+
+ return {
+ // Enqueue `item`; resolves with `run(item)`'s result when a slot runs it.
+ request(item) {
+ return new Promise((resolve, reject) => {
+ queue.push({ item, resolve, reject, cancelled: false });
+ pump();
+ });
+ },
+ // Drop still-queued jobs matching `pred` (already-running jobs finish).
+ // Returns how many were cancelled.
+ cancel(pred) {
+ let n = 0;
+ for (const job of queue) {
+ if (!job.cancelled && pred(job.item)) {
+ job.cancelled = true;
+ job.reject(new Error('cancelled'));
+ n++;
+ }
+ }
+ return n;
+ },
+ // Live-tune the concurrency cap (the perf watchdog lowers it on low-end
+ // devices) and immediately pump in case the cap rose.
+ setMaxActive(n) { cfg.maxActive = Math.max(1, n | 0); pump(); },
+ get active() { return active; },
+ get pending() { return queue.reduce((c, j) => c + (j.cancelled ? 0 : 1), 0); },
+ };
+}
diff --git a/packages/ar-studio/src/studio/loaders.js b/packages/ar-studio/src/studio/loaders.js
new file mode 100644
index 000000000..bf5ce9871
--- /dev/null
+++ b/packages/ar-studio/src/studio/loaders.js
@@ -0,0 +1,73 @@
+// One GLTF loader for the whole studio, wired for the compression the real world
+// ships: Draco (most Sketchfab / pipeline exports) and EXT_meshopt_compression
+// (what most server-side GLB bakers emit, three.ws avatars included). A studio
+// that loads arbitrary caller-supplied GLBs has to handle both or it fails on
+// perfectly valid files.
+//
+// Decoder binaries are fetched from a CDN by default because they are WASM blobs
+// that do not belong in an npm package's install footprint. Self-host them and
+// point `dracoPath` at your own copy when you would rather not reach out.
+
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+
+/** Where the Draco decoder (wasm + js) is fetched from when nothing else is set. */
+export const DEFAULT_DRACO_PATH = 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/libs/draco/gltf/';
+
+let _loader = null;
+let _dracoPath = DEFAULT_DRACO_PATH;
+let _meshoptPromise = null;
+
+/** Point the Draco decoder at a different host. Call before the first load. */
+export function setDracoPath(path) {
+ if (typeof path === 'string' && path) _dracoPath = path.endsWith('/') ? path : `${path}/`;
+}
+
+function meshoptDecoder() {
+ if (!_meshoptPromise) {
+ _meshoptPromise = import('three/addons/libs/meshopt_decoder.module.js')
+ .then((m) => m.MeshoptDecoder)
+ .catch(() => null);
+ }
+ return _meshoptPromise;
+}
+
+/**
+ * The shared loader. Draco is attached synchronously; meshopt resolves async and
+ * attaches as soon as it is ready, so plain and Draco GLBs never wait on it.
+ * @returns {GLTFLoader}
+ */
+export function sharedGLTFLoader() {
+ if (_loader) return _loader;
+ _loader = new GLTFLoader();
+ const draco = new DRACOLoader();
+ draco.setDecoderPath(_dracoPath);
+ _loader.setDRACOLoader(draco);
+ meshoptDecoder().then((d) => {
+ if (d) _loader.setMeshoptDecoder(d);
+ });
+ return _loader;
+}
+
+/**
+ * The shared loader, once every optional decoder that can attach has attached.
+ *
+ * `sharedGLTFLoader()` returns before meshopt resolves, which is right for the
+ * queue (a plain GLB should not wait on a WASM download it will never use) and
+ * wrong for a one-shot parse: hand a meshopt-compressed GLB to a loader whose
+ * decoder is still in flight and it throws "no DRACOLoader instance provided"'s
+ * meshopt equivalent on a file that is perfectly valid. Anything that parses a
+ * single caller-supplied GLB should await this instead.
+ *
+ * @returns {Promise<GLTFLoader>}
+ */
+export async function sharedGLTFLoaderReady() {
+ const loader = sharedGLTFLoader();
+ await meshoptDecoder();
+ return loader;
+}
+
+/** Drop the cached loader (tests, or after changing the Draco path mid-session). */
+export function resetLoader() {
+ _loader = null;
+}
diff --git a/packages/ar-studio/src/studio/multi-place.js b/packages/ar-studio/src/studio/multi-place.js
new file mode 100644
index 000000000..26a11c851
--- /dev/null
+++ b/packages/ar-studio/src/studio/multi-place.js
@@ -0,0 +1,560 @@
+// WebXR immersive-ar MULTI-placement session for the AR Studio.
+//
+// The flagship WebXRSession (./webxr.js) anchors exactly one content group and
+// retires its reticle after the first tap: right for "pin my agent", wrong for
+// a studio where every tap should drop ANOTHER model. This controller keeps the
+// hit-test reticle armed for the whole session: each screen tap asks the host
+// for the currently armed content (a fresh Group), places it at the reticle,
+// and binds it to its own XRAnchor so every placed model is independently glued
+// to the real world. Pinch (via the dom-overlay) resizes the most recent: or
+// host-selected: placement.
+//
+// Deliberately shares the pure helpers with the flagship session
+// (anchor-lifecycle reticle visuals + tracking state, pinch-scale math,
+// depth-occlusion) so the two AR surfaces look and feel identical.
+
+import {
+ CanvasTexture, CircleGeometry, Color, Group, Matrix4, Mesh, MeshBasicMaterial,
+ PlaneGeometry, RingGeometry,
+} from 'three';
+
+import {
+ advancePulse, isXrVisible, nextTrackingState, reticleVisual, TRACKING_LOSS_FRAMES,
+} from './anchor-lifecycle.js';
+import { DepthOcclusion } from './depth-occlusion.js';
+import { createPinchState, pinchEnd, pinchMove, pinchStart, touchDist } from './pinch.js';
+
+function prefersReducedMotion() {
+ try {
+ return typeof window !== 'undefined'
+ && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ } catch {
+ return false;
+ }
+}
+
+function makeShadowTexture() {
+ try {
+ const size = 128;
+ const cnv = document.createElement('canvas');
+ cnv.width = cnv.height = size;
+ const ctx = cnv.getContext('2d');
+ const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
+ g.addColorStop(0, 'rgba(0,0,0,0.42)');
+ g.addColorStop(0.55, 'rgba(0,0,0,0.20)');
+ g.addColorStop(1, 'rgba(0,0,0,0)');
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, size, size);
+ return new CanvasTexture(cnv);
+ } catch {
+ return null;
+ }
+}
+
+export class MultiPlaceSession {
+ /**
+ * @param {object} opts
+ * @param {import('three').WebGLRenderer} opts.renderer
+ * @param {import('three').Scene} opts.scene
+ * @param {import('three').Camera} opts.camera
+ * @param {Element} [opts.domOverlayRoot] In-session HUD (prompt bar, tray,
+ * exit). Touches are only observable through it during immersive-ar, so it
+ * also carries the pinch gesture. Taps that begin on an element bearing
+ * [data-xr-ui] never place a model.
+ * @param {() => (import('three').Group|null)} opts.getArmedContent Called on
+ * each placement tap; returns a READY group to place (the host clones its
+ * armed template), or null when nothing is armed (tap is ignored).
+ * @param {(group: import('three').Group, pose: { position: {x,y,z}, matrix: Matrix4 }, meta: { degraded: boolean }) => void} [opts.onPlaced]
+ * Fired after each placement is anchored.
+ * @param {() => (import('three').Group|null)} [opts.getScaleTarget] Which
+ * group a pinch resizes; defaults to the most recent placement.
+ * @param {(scale: number, meta: { final: boolean }) => void} [opts.onScale]
+ * @param {(has: boolean) => void} [opts.onHit]
+ * @param {(ok: boolean) => void} [opts.onTracking]
+ * @param {(visible: boolean) => void} [opts.onVisibility]
+ * @param {() => void} [opts.onEnd]
+ * @param {(dt: number) => void} [opts.onFrame] Per-frame host hook (mixers).
+ */
+ constructor({
+ renderer, scene, camera, domOverlayRoot,
+ getArmedContent, onPlaced, getScaleTarget, onScale,
+ onHit, onTracking, onVisibility, onEnd, onFrame,
+ }) {
+ this._renderer = renderer;
+ this._scene = scene;
+ this._camera = camera;
+ this._domOverlayRoot = domOverlayRoot ?? null;
+ this._getArmedContent = getArmedContent;
+ this._onPlaced = onPlaced;
+ this._getScaleTarget = getScaleTarget;
+ this._onScale = onScale;
+ this._onHit = onHit;
+ this._onTracking = onTracking;
+ this._onVisibility = onVisibility;
+ this._onEnd = onEnd;
+ this._onFrame = onFrame;
+
+ this._session = null;
+ this._hitTestSource = null;
+ this._localSpace = null;
+ this._ended = false;
+ this._paused = false;
+ this._trackingState = { misses: 0, lost: false };
+ this._depthOcclusion = null;
+
+ /** @type {Array<{ group: Group, anchor: XRAnchor|null, shadow: Mesh }>} */
+ this._placements = [];
+
+ this._latestHit = null;
+ this._latestHitMatrix = new Matrix4();
+ this._hasHit = false;
+ this._hadHit = false;
+ this._hitAmount = 0;
+
+ this._reticle = null;
+ this._reticleRing = null;
+ this._reticleDot = null;
+ this._pulseRing = null;
+ this._rv = { scale: 1, opacity: 0.9, dot: 0, colorMix: 0 };
+ this._pulse = { t: 0, scale: 1, opacity: 0, done: false, active: false };
+ this._dimColor = new Color(0x7a6cf0);
+ this._lockColor = new Color(0xc4b5fd);
+ this._reducedMotion = false;
+ this._shadowTex = null;
+ this._prevTime = 0;
+ this._savedBg = null;
+
+ this._pinch = createPinchState();
+ this._pinchEndedAt = -Infinity;
+ // A tap that starts on HUD chrome must not place a model when it bubbles
+ // into the XR select. Tracked from the overlay's touchstart.
+ this._uiTouchActive = false;
+
+ this._handleEnd = this._handleEnd.bind(this);
+ this._handleSelect = this._handleSelect.bind(this);
+ this._handleVisibilityChange = this._handleVisibilityChange.bind(this);
+ this._handleTouchStart = this._handleTouchStart.bind(this);
+ this._handleTouchMove = this._handleTouchMove.bind(this);
+ this._handleTouchEnd = this._handleTouchEnd.bind(this);
+ this._handleBeforeSelect = this._handleBeforeSelect.bind(this);
+ }
+
+ static async isSupported() {
+ try {
+ return !!(navigator.xr && (await navigator.xr.isSessionSupported('immersive-ar')));
+ } catch {
+ return false;
+ }
+ }
+
+ async start() {
+ const renderer = this._renderer;
+ renderer.xr.enabled = true;
+
+ const sessionInit = {
+ requiredFeatures: ['hit-test'],
+ // `light-estimation` unlocks real-world lighting + reflections
+ // (./estimated-lighting.js); optional so devices without it fall
+ // back to the baked studio lights, exactly as before.
+ optionalFeatures: ['anchors', 'local-floor', 'depth-sensing', 'light-estimation'],
+ depthSensing: {
+ usagePreference: ['gpu-optimized', 'cpu-optimized'],
+ dataFormatPreference: ['luminance-alpha', 'float32'],
+ },
+ };
+ if (this._domOverlayRoot) {
+ sessionInit.optionalFeatures.push('dom-overlay');
+ sessionInit.domOverlay = { root: this._domOverlayRoot };
+ }
+
+ const session = await navigator.xr.requestSession('immersive-ar', sessionInit);
+ this._session = session;
+ this._ended = false;
+ this._paused = false;
+ this._trackingState = { misses: 0, lost: false };
+ session.addEventListener('end', this._handleEnd);
+ session.addEventListener('select', this._handleSelect);
+ session.addEventListener('visibilitychange', this._handleVisibilityChange);
+
+ await renderer.xr.setSession(session);
+
+ this._localSpace = await session.requestReferenceSpace('local');
+ const viewerSpace = await session.requestReferenceSpace('viewer');
+ this._hitTestSource = await session.requestHitTestSource({ space: viewerSpace });
+
+ this._depthOcclusion = DepthOcclusion.sessionHasDepth(session)
+ ? new DepthOcclusion(renderer)
+ : null;
+
+ this._reducedMotion = prefersReducedMotion();
+ this._hadHit = false;
+ this._hitAmount = 0;
+ this._pulse.active = false;
+ this._shadowTex = makeShadowTexture();
+ this._buildReticle();
+ this._buildPulseRing();
+
+ this._savedBg = this._scene.background;
+ this._scene.background = null;
+ renderer.setClearColor(0x000000, 0);
+
+ if (this._domOverlayRoot) {
+ const root = this._domOverlayRoot;
+ root.addEventListener('touchstart', this._handleTouchStart, { passive: true });
+ root.addEventListener('touchmove', this._handleTouchMove, { passive: true });
+ root.addEventListener('touchend', this._handleTouchEnd, { passive: true });
+ root.addEventListener('touchcancel', this._handleTouchEnd, { passive: true });
+ root.addEventListener('beforexrselect', this._handleBeforeSelect);
+ }
+
+ this._prevTime = 0;
+ renderer.setAnimationLoop((time, frame) => this._tick(time, frame));
+ }
+
+ /** Number of models placed in this immersive session. */
+ get placedCount() {
+ return this._placements.length;
+ }
+
+ _tick(time, frame) {
+ const renderer = this._renderer;
+ const dt = this._prevTime ? Math.min(0.1, (time - this._prevTime) / 1000) : 0.016;
+ this._prevTime = time;
+
+ if (this._paused) {
+ renderer.render(this._scene, this._camera);
+ return;
+ }
+
+ if (frame && this._localSpace) {
+ const hasPose = !!frame.getViewerPose(this._localSpace);
+ const t = nextTrackingState(this._trackingState, hasPose, TRACKING_LOSS_FRAMES);
+ this._trackingState = t.state;
+ if (t.changed) this._setTracking(!t.lost);
+ }
+
+ this._onFrame?.(dt);
+
+ // The reticle stays live for the WHOLE session: that is the studio's
+ // entire difference from the single-shot session: always ready to place
+ // one more.
+ if (frame && this._hitTestSource) {
+ const hits = frame.getHitTestResults(this._hitTestSource);
+ const pose = hits.length > 0 ? hits[0].getPose(this._localSpace) : null;
+ if (pose) {
+ this._latestHit = hits[0];
+ this._latestHitMatrix.fromArray(pose.transform.matrix);
+ this._hadHit = true;
+ if (this._reticle) {
+ this._reticle.visible = true;
+ this._reticle.position.setFromMatrixPosition(this._latestHitMatrix);
+ this._reticle.quaternion.setFromRotationMatrix(this._latestHitMatrix);
+ }
+ this._setHit(true);
+ } else {
+ this._latestHit = null;
+ const keep = this._hadHit && !this._trackingState.lost;
+ if (this._reticle) this._reticle.visible = keep;
+ this._setHit(false);
+ }
+ }
+
+ // Every anchored placement re-reads its live anchor pose so each model
+ // stays independently glued as tracking refines. Anchor-less placements
+ // (createAnchor unsupported/rejected) stay frozen at their tap pose.
+ if (frame) {
+ for (const p of this._placements) {
+ if (!p.anchor) continue;
+ const pose = frame.getPose(p.anchor.anchorSpace, this._localSpace);
+ if (pose) {
+ const t = pose.transform.position;
+ p.group.position.set(t.x, t.y, t.z);
+ p.shadow?.position.set(t.x, t.y + 0.004, t.z);
+ }
+ }
+ }
+
+ this._updateReticleVisual(time, dt);
+ this._updatePulse(dt);
+ this._depthOcclusion?.update();
+
+ renderer.render(this._scene, this._camera);
+ }
+
+ // ── Placement ─────────────────────────────────────────────────────────────
+
+ async _handleSelect() {
+ if (!this._latestHit) return;
+ if (this._pinch.active || performance.now() - this._pinchEndedAt < 350) return;
+ if (this._uiTouchActive) return;
+
+ const group = this._getArmedContent?.();
+ if (!group) return;
+
+ const matrix = this._latestHitMatrix.clone();
+ group.position.setFromMatrixPosition(matrix);
+ if (!group.parent) this._scene.add(group);
+
+ const shadow = this._buildShadow();
+ shadow.position.copy(group.position);
+ shadow.position.y += 0.004;
+ shadow.scale.setScalar(group.scale.x || 1);
+
+ this._fireConfirmPulse();
+ try { navigator.vibrate?.(15); } catch { /* haptics are a bonus, never a failure path */ }
+
+ let anchor = null;
+ try {
+ anchor = (await this._latestHit.createAnchor?.()) ?? null;
+ } catch {
+ anchor = null;
+ }
+ this._placements.push({ group, anchor, shadow });
+ this._onPlaced?.(group, {
+ position: { x: group.position.x, y: group.position.y, z: group.position.z },
+ matrix,
+ }, { degraded: anchor === null });
+ }
+
+ /**
+ * Detach a group placed this session (the host deleted the model). Its
+ * anchor and contact shadow are released; removing the group from the scene
+ * stays the host's call.
+ */
+ release(group) {
+ const i = this._placements.findIndex((p) => p.group === group);
+ if (i === -1) return;
+ const [p] = this._placements.splice(i, 1);
+ try { p.anchor?.delete?.(); } catch { /* the session already released it */ }
+ if (p.shadow) {
+ this._scene.remove(p.shadow);
+ p.shadow.geometry?.dispose();
+ p.shadow.material?.dispose();
+ }
+ }
+
+ // ── Pinch (dom-overlay) ───────────────────────────────────────────────────
+
+ _scaleTarget() {
+ const fromHost = this._getScaleTarget?.();
+ if (fromHost) return fromHost;
+ return this._placements.length
+ ? this._placements[this._placements.length - 1].group
+ : null;
+ }
+
+ _handleTouchStart(e) {
+ if (e.touches.length === 1) {
+ // Remember whether this touch began on HUD chrome: its select must not place.
+ this._uiTouchActive = !!e.touches[0].target?.closest?.('[data-xr-ui]');
+ return;
+ }
+ if (e.touches.length !== 2) return;
+ const target = this._scaleTarget();
+ if (!target) return;
+ pinchStart(this._pinch, touchDist(e.touches), target.scale?.x ?? 1);
+ }
+
+ _handleTouchMove(e) {
+ if (!this._pinch.active || e.touches.length !== 2) return;
+ const s = pinchMove(this._pinch, touchDist(e.touches));
+ if (s == null) return;
+ const target = this._scaleTarget();
+ if (!target) return;
+ target.scale.setScalar(s);
+ const p = this._placements.find((x) => x.group === target);
+ p?.shadow?.scale.setScalar(s);
+ this._onScale?.(s, { final: false });
+ }
+
+ _handleTouchEnd(e) {
+ if (!e.touches || e.touches.length === 0) this._uiTouchActive = false;
+ const s = pinchEnd(this._pinch);
+ if (s == null) return;
+ this._pinchEndedAt = performance.now();
+ this._onScale?.(s, { final: true });
+ }
+
+ _handleBeforeSelect(e) {
+ if (this._pinch.active || performance.now() - this._pinchEndedAt < 350) {
+ e.preventDefault();
+ return;
+ }
+ // Taps on HUD controls (tray, prompt bar, exit) are UI, never placement.
+ if (e.target?.closest?.('[data-xr-ui]')) e.preventDefault();
+ }
+
+ // ── Reticle / pulse / shadow (same look as the flagship session) ─────────
+
+ _buildReticle() {
+ const group = new Group();
+ group.renderOrder = 999;
+ group.visible = false;
+ const ring = new Mesh(
+ new RingGeometry(0.08, 0.11, 40).rotateX(-Math.PI / 2),
+ new MeshBasicMaterial({ color: this._dimColor.clone(), transparent: true, opacity: 0.6, depthTest: false }),
+ );
+ ring.renderOrder = 999;
+ const dot = new Mesh(
+ new CircleGeometry(0.032, 32).rotateX(-Math.PI / 2).translate(0, 0.001, 0),
+ new MeshBasicMaterial({ color: this._lockColor.clone(), transparent: true, opacity: 0, depthTest: false }),
+ );
+ dot.renderOrder = 1000;
+ group.add(ring, dot);
+ this._reticle = group;
+ this._reticleRing = ring;
+ this._reticleDot = dot;
+ this._scene.add(group);
+ }
+
+ _buildPulseRing() {
+ const ring = new Mesh(
+ new RingGeometry(0.10, 0.13, 40).rotateX(-Math.PI / 2),
+ new MeshBasicMaterial({ color: this._lockColor.clone(), transparent: true, opacity: 0, depthTest: false }),
+ );
+ ring.renderOrder = 1001;
+ ring.visible = false;
+ this._pulseRing = ring;
+ this._scene.add(ring);
+ }
+
+ _buildShadow() {
+ const geo = new PlaneGeometry(0.6, 0.6).rotateX(-Math.PI / 2);
+ const mat = new MeshBasicMaterial({
+ map: this._shadowTex, color: this._shadowTex ? 0xffffff : 0x000000,
+ transparent: true, opacity: 0.9, depthWrite: false,
+ });
+ const mesh = new Mesh(geo, mat);
+ mesh.renderOrder = 1;
+ this._scene.add(mesh);
+ return mesh;
+ }
+
+ _fireConfirmPulse() {
+ if (this._reducedMotion || !this._pulseRing) return;
+ this._pulseRing.position.setFromMatrixPosition(this._latestHitMatrix);
+ this._pulseRing.quaternion.setFromRotationMatrix(this._latestHitMatrix);
+ this._pulse.t = 0;
+ this._pulse.active = true;
+ this._pulseRing.visible = true;
+ }
+
+ _updateReticleVisual(time, dt) {
+ const group = this._reticle;
+ if (!group || !group.visible) return;
+ const target = this._hasHit ? 1 : 0;
+ const rate = Math.min(1, dt * (target > this._hitAmount ? 16 : 9));
+ this._hitAmount += (target - this._hitAmount) * rate;
+ const breathe = this._reducedMotion ? 0 : Math.sin(time * 0.0019) * 0.5 + 0.5;
+ reticleVisual(this._rv, this._hitAmount, breathe, this._reducedMotion);
+ group.scale.setScalar(this._rv.scale);
+ const ringMat = this._reticleRing.material;
+ ringMat.opacity = this._rv.opacity;
+ ringMat.color.lerpColors(this._dimColor, this._lockColor, this._rv.colorMix);
+ this._reticleDot.material.opacity = this._rv.dot * 0.95;
+ }
+
+ _updatePulse(dt) {
+ if (!this._pulse.active || !this._pulseRing) return;
+ advancePulse(this._pulse, dt);
+ this._pulseRing.scale.setScalar(this._pulse.scale);
+ this._pulseRing.material.opacity = this._pulse.opacity;
+ if (this._pulse.done) {
+ this._pulse.active = false;
+ this._pulseRing.visible = false;
+ }
+ }
+
+ // ── Lifecycle ─────────────────────────────────────────────────────────────
+
+ _setHit(has) {
+ if (has === this._hasHit) return;
+ this._hasHit = has;
+ this._onHit?.(has);
+ }
+
+ _setTracking(ok) {
+ if (!ok && this._reticle) this._reticle.visible = false;
+ this._onTracking?.(ok);
+ }
+
+ _handleVisibilityChange() {
+ const visible = isXrVisible(this._session?.visibilityState);
+ this._paused = !visible;
+ if (!visible && this._reticle) this._reticle.visible = false;
+ this._onVisibility?.(visible);
+ }
+
+ async end() {
+ if (this._session) {
+ try {
+ await this._session.end();
+ } catch { /* already ending */ }
+ }
+ }
+
+ _handleEnd() {
+ if (this._ended) return;
+ this._ended = true;
+
+ const renderer = this._renderer;
+ this._session?.removeEventListener('visibilitychange', this._handleVisibilityChange);
+ if (this._domOverlayRoot) {
+ const root = this._domOverlayRoot;
+ root.removeEventListener('touchstart', this._handleTouchStart);
+ root.removeEventListener('touchmove', this._handleTouchMove);
+ root.removeEventListener('touchend', this._handleTouchEnd);
+ root.removeEventListener('touchcancel', this._handleTouchEnd);
+ root.removeEventListener('beforexrselect', this._handleBeforeSelect);
+ }
+ this._pinch = createPinchState();
+ this._pinchEndedAt = -Infinity;
+ this._uiTouchActive = false;
+
+ renderer.setAnimationLoop(null);
+ renderer.xr.enabled = false;
+
+ if (this._hitTestSource) {
+ try { this._hitTestSource.cancel(); } catch { /* the session already tore it down */ }
+ this._hitTestSource = null;
+ }
+
+ for (const child of [this._reticleRing, this._reticleDot, this._pulseRing]) {
+ child?.geometry?.dispose();
+ child?.material?.dispose();
+ }
+ if (this._reticle) this._scene.remove(this._reticle);
+ if (this._pulseRing) this._scene.remove(this._pulseRing);
+ this._reticle = this._reticleRing = this._reticleDot = this._pulseRing = null;
+ this._pulse.active = false;
+
+ // Placed groups stay in the scene (the host re-lays them out in fallback
+ // mode); anchors and per-placement shadows are session resources: release.
+ for (const p of this._placements) {
+ try { p.anchor?.delete?.(); } catch { /* the session already released it */ }
+ if (p.shadow) {
+ this._scene.remove(p.shadow);
+ p.shadow.geometry?.dispose();
+ p.shadow.material?.dispose();
+ }
+ }
+ this._placements = [];
+ this._shadowTex?.dispose();
+ this._shadowTex = null;
+
+ this._depthOcclusion?.dispose();
+ this._depthOcclusion = null;
+ this._session = null;
+ this._latestHit = null;
+ this._hasHit = false;
+ this._hadHit = false;
+ this._hitAmount = 0;
+ this._paused = false;
+ this._trackingState = { misses: 0, lost: false };
+
+ this._scene.background = this._savedBg;
+ renderer.setClearColor(0x000000, 0);
+
+ this._onEnd?.();
+ }
+}
diff --git a/packages/ar-studio/src/studio/native-ar.js b/packages/ar-studio/src/studio/native-ar.js
new file mode 100644
index 000000000..2d96288ab
--- /dev/null
+++ b/packages/ar-studio/src/studio/native-ar.js
@@ -0,0 +1,340 @@
+// Handing one model to the device's own AR viewer, from the browser.
+//
+// This is the path that actually puts an object on someone's floor at real
+// size, with real tracking, real occlusion and real lighting: Apple's AR Quick
+// Look on iOS and Google's Scene Viewer on Android. Both are native apps, so
+// there is no feature-detectable API and UA branching is the correct answer
+// here rather than a shortcut.
+//
+// The studio's own WebXR session is better still where it exists (it keeps the
+// whole multi-model scene in-page), so `arCapability()` puts it first and these
+// two are what everyone else gets instead of a camera-passthrough approximation.
+
+/** Apple's AR Quick Look, available on iOS and iPadOS Safari. */
+export function isIOS() {
+ if (typeof navigator === 'undefined') return false;
+ return /iphone|ipad|ipod/i.test(navigator.userAgent)
+ || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
+}
+
+export function canUseQuickLook() {
+ return isIOS();
+}
+
+export function isAndroid() {
+ return typeof navigator !== 'undefined' && /android/i.test(navigator.userAgent);
+}
+
+export function canUseSceneViewer() {
+ return isAndroid();
+}
+
+// Safari delivers the Quick Look banner-tap `message` event on the anchor that
+// launched the session, so the anchor must stay in the DOM while the viewer is
+// open. One live anchor at a time: replacing it drops the previous listener.
+let _anchor = null;
+
+/** The literal `message` payload Safari sends when the Quick Look banner is tapped. */
+export const QUICK_LOOK_BANNER_TAPPED = '_apple_ar_quicklook_button_tapped';
+
+/**
+ * A filesystem-safe `<name>.usdz` for a model title.
+ *
+ * This is not cosmetic. See `openQuickLook`: the extension in this name is what
+ * tells Safari the blob it is being handed is an AR asset.
+ *
+ * @param {string} [title]
+ * @returns {string}
+ */
+export function usdzFilename(title) {
+ const slug = String(title || '')
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 60);
+ return `${slug || 'model'}.usdz`;
+}
+
+/**
+ * Open a USDZ in Quick Look. Safari activates it when an `<a rel="ar">` is
+ * clicked programmatically, which is why this builds an anchor rather than
+ * navigating.
+ *
+ * THE `download` ATTRIBUTE IS LOAD-BEARING and the single least obvious line in
+ * this package. Safari decides whether a URL is an AR asset by looking at its
+ * file extension. A `blob:` URL has no path and therefore no extension, so
+ * without a filename Safari does open Quick Look, but as a generic 3D file
+ * preview: the viewer comes up in Object mode with AR unavailable, which reads
+ * as "AR is broken" while everything else looks perfectly fine. `download`
+ * supplies the name Safari sniffs, and Quick Look enters AR. This is exactly
+ * what <model-viewer> does for its own generated USDZ, and why an app built on
+ * model-viewer reaches ARKit while a hand-rolled anchor does not.
+ *
+ * @param {string} usdzUrl
+ * @param {{onBannerTap?: () => void, name?: string}} [opts] `name` becomes the
+ * Quick Look filename; pass the model's title.
+ */
+export function openQuickLook(usdzUrl, { onBannerTap, name = '' } = {}) {
+ if (_anchor) { _anchor.remove(); _anchor = null; }
+ const a = document.createElement('a');
+ // Attribute order mirrors model-viewer's: rel, then the child image, then
+ // href. Safari is known to be picky about the anchor being complete before
+ // it is activated.
+ a.rel = 'ar';
+ // iOS needs a child element for a programmatic click to open Quick Look.
+ a.appendChild(document.createElement('img'));
+ a.href = usdzUrl;
+ if (/^blob:/i.test(usdzUrl)) a.setAttribute('download', usdzFilename(name));
+ // Present but invisible.
+ a.style.cssText = 'position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none;overflow:hidden;';
+ a.setAttribute('aria-hidden', 'true');
+ if (typeof onBannerTap === 'function') {
+ a.addEventListener('message', (e) => {
+ if (e.data === QUICK_LOOK_BANNER_TAPPED) onBannerTap();
+ });
+ }
+ document.body.appendChild(a);
+ _anchor = a;
+ a.click();
+}
+
+/**
+ * Open a GLB in Google Scene Viewer through an ARCore intent. Falls the browser
+ * back to `fallbackUrl` (default: this page) when ARCore is missing.
+ *
+ * @param {string} glbUrl
+ * @param {{title?: string, link?: string, fallbackUrl?: string}} [opts]
+ */
+export function openSceneViewer(glbUrl, { title = '', link = '', fallbackUrl = '' } = {}) {
+ const params = new URLSearchParams({ file: glbUrl, mode: 'ar_preferred' });
+ if (title) params.set('title', title);
+ if (link) params.set('link', link);
+ const fallback = encodeURIComponent(fallbackUrl || location.href);
+ location.href = `intent://arvr.google.com/scene-viewer/1.2?${params.toString()}`
+ + '#Intent;scheme=https;package=com.google.ar.core;'
+ + 'action=android.intent.action.VIEW;'
+ + `S.browser_fallback_url=${fallback};end;`;
+}
+
+/**
+ * The best AR path this device can actually deliver, best first.
+ *
+ * 'webxr' immersive-ar: the whole scene stays in the page, anchored.
+ * 'quicklook' iOS/iPadOS: ARKit placement of ONE model, in Apple's viewer.
+ * 'sceneviewer' Android without WebXR: ARCore placement of ONE model.
+ * 'none' desktop and locked-down webviews: hand off to a phone instead.
+ *
+ * Never throws: a blocked or missing API is simply not that capability.
+ *
+ * @returns {Promise<'webxr'|'quicklook'|'sceneviewer'|'none'>}
+ */
+export async function arCapability() {
+ try {
+ if (navigator.xr && (await navigator.xr.isSessionSupported('immersive-ar'))) return 'webxr';
+ } catch {
+ // A throwing support probe is just "not webxr".
+ }
+ if (canUseQuickLook()) return 'quicklook';
+ if (canUseSceneViewer()) return 'sceneviewer';
+ return 'none';
+}
+
+// ── The USDZ cache ────────────────────────────────────────────────────────
+//
+// Two taps on "Place in your space" must not pay for two conversions, and the
+// studio pre-warms this entry the moment it knows which model the button will
+// send, so the tap itself is usually instant.
+//
+// Bounded on purpose: each entry pins a USDZ blob in memory, and a phone that
+// has browsed twenty models should not be holding twenty of them. Eviction
+// revokes the object URL, which is the only way that memory ever comes back.
+
+const MAX_CACHED_USDZ = 4;
+
+/** @type {Map<string, {promise: Promise<string>, href: string}>} */
+const _usdzCache = new Map();
+
+function evictOldestUsdz() {
+ while (_usdzCache.size > MAX_CACHED_USDZ) {
+ const [key, entry] = _usdzCache.entries().next().value;
+ _usdzCache.delete(key);
+ if (entry.href) URL.revokeObjectURL(entry.href);
+ }
+}
+
+/** Drop every cached USDZ and release the memory behind it. */
+export function clearQuickLookCache() {
+ for (const entry of _usdzCache.values()) {
+ if (entry.href) URL.revokeObjectURL(entry.href);
+ }
+ _usdzCache.clear();
+}
+
+/** Drop one cached USDZ and release the memory behind it. */
+export function releaseQuickLook(key) {
+ const entry = _usdzCache.get(key);
+ if (!entry) return false;
+ _usdzCache.delete(key);
+ if (entry.href) URL.revokeObjectURL(entry.href);
+ return true;
+}
+
+/** Is a Quick Look asset for this key already converted and ready to open? */
+export function isQuickLookReady(key) {
+ return Boolean(key && _usdzCache.get(key)?.href);
+}
+
+/**
+ * Convert once per key and hand back a `blob:` URL Quick Look can open.
+ *
+ * @param {string} key Cache identity. Include anything that changes the bytes
+ * (the source URL, and the scale when it is baked in).
+ * @param {() => Promise<Blob>} build
+ * @returns {Promise<string>}
+ */
+export async function cachedUsdzUrl(key, build) {
+ const hit = _usdzCache.get(key);
+ if (hit) {
+ // Re-inserting makes the map least-recently-used rather than insertion
+ // ordered, so the model someone keeps opening is not the one evicted.
+ _usdzCache.delete(key);
+ _usdzCache.set(key, hit);
+ return hit.promise;
+ }
+ const entry = { href: '', promise: null };
+ entry.promise = (async () => {
+ const blob = await build();
+ entry.href = URL.createObjectURL(blob);
+ return entry.href;
+ })();
+ // A conversion that throws must not poison the key forever: the next tap
+ // should be able to try again.
+ entry.promise.catch(() => {
+ if (_usdzCache.get(key) === entry) _usdzCache.delete(key);
+ });
+ _usdzCache.set(key, entry);
+ evictOldestUsdz();
+ return entry.promise;
+}
+
+/**
+ * Everything the device's AR viewer needs, WITHOUT opening it yet.
+ *
+ * The split matters more than it looks. Safari only honours a `rel="ar"`
+ * activation while the page still holds user activation, and converting a GLB
+ * to USDZ takes seconds: do the conversion inside the tap handler and by the
+ * time the anchor is clicked the gesture has expired and iOS silently declines
+ * to open Quick Look, which reads as a dead button. So callers prepare first
+ * (before the tap, or behind a progress UI) and call the returned `open()`
+ * synchronously from a real tap.
+ *
+ * @param {object} model
+ * @param {string} model.src https URL of the .glb
+ * @param {string} [model.title] Name shown in the AR viewer's banner
+ * @param {string} [model.usdz] A ready-made USDZ, skipping conversion
+ * @param {string} [model.key] Cache identity; defaults to `src`
+ * @param {() => Promise<Blob>} [model.build] Produce the USDZ without refetching
+ * @param {object} [opts]
+ * @param {(stage: 'download'|'parse'|'convert') => void} [opts.onProgress]
+ * @param {string} [opts.fallbackUrl] Where Android lands without ARCore
+ * @param {AbortSignal} [opts.signal]
+ * @returns {Promise<null | {viewer:'quicklook'|'sceneviewer', href: string,
+ * open: (o?: {onBannerTap?: () => void}) => void}>} null when this device has
+ * no native AR viewer at all.
+ */
+export async function prepareNativeAr({ src = '', title = '', usdz = '', key = '', build } = {}, {
+ onProgress, fallbackUrl = '', signal,
+} = {}) {
+ if (!src && !usdz && !build) throw new Error('ar-studio: nothing to place');
+
+ if (canUseQuickLook()) {
+ let href = usdz;
+ if (!href) {
+ const cacheKey = key || src;
+ if (!cacheKey) throw new Error('ar-studio: a cache key or src is required');
+ href = await cachedUsdzUrl(cacheKey, async () => {
+ if (build) {
+ onProgress?.('convert');
+ return build();
+ }
+ // Imported here rather than at module scope so a page that never opens
+ // native AR never downloads the exporter.
+ const { glbUrlToUsdzBlob } = await import('./usdz.js');
+ return glbUrlToUsdzBlob(src, { signal, onProgress });
+ });
+ }
+ return {
+ viewer: 'quicklook',
+ href,
+ open: (o) => openQuickLook(href, { name: title, ...o }),
+ };
+ }
+
+ if (canUseSceneViewer()) {
+ if (!src) throw new Error('ar-studio: Scene Viewer needs a GLB URL');
+ return {
+ viewer: 'sceneviewer',
+ href: src,
+ open: () => openSceneViewer(src, { title, fallbackUrl }),
+ };
+ }
+
+ return null;
+}
+
+/**
+ * Prepare and open ONE model in the device's native AR viewer, in one call.
+ *
+ * Convenient, and the right shape when the USDZ is already cached (the studio
+ * pre-warms it). When it is not, prefer `prepareNativeAr()` and open from a
+ * tap: see the note there about Safari and user activation.
+ *
+ * @param {object} model See `prepareNativeAr`
+ * @param {object} [opts]
+ * @param {(stage: 'download'|'parse'|'convert'|'open') => void} [opts.onProgress]
+ * @param {string} [opts.fallbackUrl]
+ * @param {AbortSignal} [opts.signal]
+ * @returns {Promise<'quicklook'|'sceneviewer'|'none'>} which viewer opened
+ */
+export async function placeInYourSpace(model = {}, opts = {}) {
+ const handoff = await prepareNativeAr(model, opts);
+ if (!handoff) return 'none';
+ opts.onProgress?.('open');
+ handoff.open();
+ return handoff.viewer;
+}
+
+// Quick Look renders its banner on one line and truncates long strings itself;
+// clamp the fields so a runaway prompt-as-name cannot fill the URL.
+const BANNER_FIELD_MAX = 80;
+
+/**
+ * Append Quick Look banner fields to a USDZ URL as fragment parameters. This is
+ * the one piece of page-controlled UI Apple allows inside the sealed viewer.
+ *
+ * Deliberately string surgery rather than `new URL()`: the USDZ here is usually
+ * a blob: object URL, which URL parsing mangles.
+ *
+ * @param {string} url
+ * @param {{title?: string, subtitle?: string, callToAction?: string}} [fields]
+ * @returns {string}
+ */
+export function withQuickLookBanner(url, { title, subtitle, callToAction } = {}) {
+ if (typeof url !== 'string' || !url) return url;
+ const params = [];
+ const push = (key, value) => {
+ const v = typeof value === 'string' ? value.trim().slice(0, BANNER_FIELD_MAX) : '';
+ if (v) params.push(`${key}=${encodeURIComponent(v)}`);
+ };
+ // Quick Look renders the banner only when it has a button to render: a lone
+ // title produces a banner with an empty action. Apple treats these as one
+ // set, so this does too, and a caller that wants the banner passes the set.
+ if (!callToAction || typeof callToAction !== 'string' || !callToAction.trim()) return url;
+ push('checkoutTitle', title);
+ push('checkoutSubtitle', subtitle);
+ push('callToAction', callToAction);
+ if (!params.length) return url;
+ const joined = params.join('&');
+ return url.includes('#') ? `${url}&${joined}` : `${url}#${joined}`;
+}
diff --git a/packages/ar-studio/src/studio/net.js b/packages/ar-studio/src/studio/net.js
new file mode 100644
index 000000000..d60ad8634
--- /dev/null
+++ b/packages/ar-studio/src/studio/net.js
@@ -0,0 +1,302 @@
+// Shared rooms: two phones, one scene, live.
+//
+// Open a room and anyone who loads the same page with `?room=CODE` joins the
+// same arrangement: every add, move, resize, rotate and remove syncs to
+// everyone in it, with a live count of who is there. It runs on the same
+// Colyseus world server that backs the three.ws multiplayer surfaces; point
+// `server` at your own deployment to host it yourself.
+//
+// Optional by design. `colyseus.js` is an optional peer dependency, loaded
+// dynamically the first time someone opens a room: if it is not installed, or no
+// server is configured, or the socket cannot be reached after one retry, the
+// status goes to `unavailable` and the studio simply stays single-player. It
+// never loops on a dead endpoint.
+//
+// Transforms ride in the room's shared logical frame (relEast / relNorth metres,
+// yawDeg) so every device agrees on an arrangement while mapping it onto its own
+// floor. See ./coords.js.
+//
+// Ported from the three.ws AR Studio room client (Apache-2.0).
+
+import { createLogger } from '../log.js';
+
+const log = createLogger('ar-studio:net');
+const ROOM_NAME = 'studio_world';
+const MAX_RETRIES = 1;
+/** Generous enough for a scale-to-zero host's cold start, tight enough to fail honestly. */
+export const CONNECT_TIMEOUT_MS = 15000;
+
+let _deps = null;
+
+/**
+ * Load colyseus.js and the room schema on demand. Resolves null when the
+ * optional dependency is absent, which is the "rooms are simply off" path.
+ */
+async function loadDeps() {
+ if (_deps !== null) return _deps;
+ try {
+ const [colyseus, schemas] = await Promise.all([
+ import('colyseus.js'),
+ import('./schemas.js'),
+ ]);
+ _deps = { Client: colyseus.Client, getStateCallbacks: colyseus.getStateCallbacks, StudioState: schemas.StudioState };
+ } catch (err) {
+ log.warn('shared rooms need the optional "colyseus.js" dependency:', err?.message || err);
+ _deps = false;
+ }
+ return _deps;
+}
+
+/**
+ * Join a room with a hard client-side timeout. Colyseus's own joinOrCreate waits
+ * for a JOIN_ROOM handshake with no timeout, so a socket that opens but never
+ * completes leaves the promise pending forever: which strands the UI in
+ * "Connecting…" with no error to catch and no reconnect to run.
+ */
+async function joinWithTimeout(client, options, StudioState) {
+ let timer;
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error('connect_timeout')), CONNECT_TIMEOUT_MS);
+ });
+ const join = client.joinOrCreate(ROOM_NAME, options, StudioState);
+ try {
+ return await Promise.race([join, timeout]);
+ } finally {
+ clearTimeout(timer);
+ // A join that resolves after the timeout must not orphan a live socket.
+ join.then((room) => {
+ try { if (room && room.connection?.isOpen) room.leave(); } catch { /* already gone */ }
+ }).catch(() => {});
+ }
+}
+
+export class StudioNet {
+ /**
+ * @param {object} opts
+ * @param {string} opts.roomKey Shared match key derived from the room code.
+ * @param {string} [opts.clientId] Stable per-browser id: decides model ownership.
+ * @param {string} [opts.name] Optional display name for presence.
+ * @param {string} opts.url Colyseus server URL (wss://…).
+ */
+ constructor({ roomKey, clientId = '', name = '', url = '' } = {}) {
+ this.roomKey = String(roomKey || '').slice(0, 64);
+ this.clientId = String(clientId || '').slice(0, 80);
+ this.name = String(name || '').slice(0, 120);
+ this.url = String(url || '').replace(/\/$/, '');
+ this.status = 'idle';
+ this.error = '';
+ this.room = null;
+ this.client = null;
+ this._listeners = { status: [], models: [], model: [], presence: [], reject: [] };
+ this._retries = 0;
+ this._reconnectTimer = null;
+ this._connectGen = 0;
+ this._destroyed = false;
+ this._presenceQueued = false;
+ this._modelsQueued = false;
+ }
+
+ /** Subscribe: 'status' | 'models' | 'model' | 'presence' | 'reject'. */
+ on(event, fn) {
+ (this._listeners[event] ||= []).push(fn);
+ return this;
+ }
+
+ _emit(event, payload) {
+ for (const fn of this._listeners[event] || []) {
+ try { fn(payload); } catch (e) { log.warn(`${event} listener error:`, e?.message || e); }
+ }
+ }
+
+ _setStatus(status, error = '') {
+ this.status = status;
+ this.error = error;
+ this._emit('status', { status, error });
+ }
+
+ _closeRoom() {
+ const room = this.room;
+ if (!room) return;
+ this.room = null;
+ try { room.removeAllListeners(); } catch { /* already torn down */ }
+ try { room.leave(); } catch { /* already gone */ }
+ }
+
+ async connect() {
+ if (this._destroyed) return;
+ this._closeRoom();
+ if (!this.url || !this.roomKey) { this._setStatus('unavailable'); return; }
+ const deps = await loadDeps();
+ if (!deps) { this._setStatus('unavailable', 'colyseus.js is not installed'); return; }
+
+ const gen = ++this._connectGen;
+ this._setStatus('connecting');
+ try {
+ this.client = new deps.Client(this.url);
+ const room = await joinWithTimeout(this.client, {
+ roomKey: this.roomKey,
+ clientId: this.clientId,
+ name: this.name,
+ }, deps.StudioState);
+ if (this._destroyed || gen !== this._connectGen) {
+ try { room.leave(); } catch { /* already gone */ }
+ return;
+ }
+ this.room = room;
+ this._retries = 0;
+
+ const $ = deps.getStateCallbacks(this.room);
+
+ // Any add / per-field change / remove re-emits the full model list so the
+ // studio reconciles against it. The join handshake fires onAdd once per
+ // existing model, so the burst is coalesced into one emit next tick.
+ const $models = $(this.room.state)?.models;
+ if ($models) {
+ $models.onAdd((model, id) => {
+ $(model).onChange(() => this._emit('model', this._modelShape(model, id)));
+ this._queueModels();
+ });
+ $models.onRemove((model, id) => {
+ this._emit('model', { id, removed: true });
+ this._queueModels();
+ });
+ }
+
+ const $viewers = $(this.room.state)?.viewers;
+ if ($viewers) {
+ $viewers.onAdd(() => this._queuePresence());
+ $viewers.onRemove(() => this._queuePresence());
+ }
+
+ this.room.onMessage('model:reject', (msg) => this._emit('reject', msg));
+ this.room.onLeave((code) => {
+ if (this._destroyed || code === 1000) return;
+ this._setStatus('offline');
+ this._scheduleReconnect();
+ });
+ this.room.onError((code, message) => log.warn('room error', code, message));
+
+ this._setStatus('online');
+ this._queueModels();
+ this._queuePresence();
+ } catch (err) {
+ const reason = err?.message || (err?.code != null ? `code ${err.code}` : String(err));
+ log.warn('connect failed:', reason);
+ this._setStatus('failed', reason);
+ this._scheduleReconnect();
+ }
+ }
+
+ _scheduleReconnect() {
+ if (this._reconnectTimer || this._destroyed) return;
+ if (this._retries >= MAX_RETRIES) { this._setStatus('unavailable', this.error); return; }
+ this._retries++;
+ const delay = 2500 + Math.random() * 1500;
+ this._reconnectTimer = setTimeout(() => {
+ this._reconnectTimer = null;
+ if (!this._destroyed) this.connect();
+ }, delay);
+ }
+
+ _modelShape(m, id) {
+ return {
+ id: id ?? m.id,
+ src: m.src,
+ title: m.title,
+ relEast: m.relEast,
+ relNorth: m.relNorth,
+ yawDeg: m.yawDeg,
+ scale: m.scale,
+ height: m.height,
+ ownerId: m.ownerId,
+ mine: !!this.clientId && m.ownerId === this.clientId,
+ };
+ }
+
+ _queueModels() {
+ if (this._modelsQueued || this._destroyed) return;
+ this._modelsQueued = true;
+ Promise.resolve().then(() => {
+ this._modelsQueued = false;
+ const map = this.room?.state?.models;
+ if (this._destroyed || !map) return;
+ const models = [];
+ map.forEach((m, id) => models.push(this._modelShape(m, id)));
+ this._emit('models', models);
+ });
+ }
+
+ _queuePresence() {
+ if (this._presenceQueued || this._destroyed) return;
+ this._presenceQueued = true;
+ Promise.resolve().then(() => {
+ this._presenceQueued = false;
+ const map = this.room?.state?.viewers;
+ if (this._destroyed || !map) return;
+ let count = 0;
+ const names = [];
+ map.forEach((v) => { count++; if (v.name) names.push(v.name); });
+ this._emit('presence', { count, names });
+ });
+ }
+
+ _live() {
+ return this.status === 'online' && this.room && this.room.connection?.isOpen === true;
+ }
+
+ /** Add a model to the shared scene. `model` is in the shared logical frame. */
+ spawn(model) {
+ if (!this._live()) return false;
+ try {
+ this.room.send('model:spawn', {
+ id: model.id,
+ src: String(model.src || ''),
+ title: String(model.title || '').slice(0, 120),
+ relEast: Number(model.relEast) || 0,
+ relNorth: Number(model.relNorth) || 0,
+ yawDeg: Number(model.yawDeg) || 0,
+ scale: Number(model.scale) || 1,
+ height: Number(model.height) || 0,
+ });
+ return true;
+ } catch (e) {
+ log.warn('spawn failed:', e?.message || e);
+ return false;
+ }
+ }
+
+ /** Move, resize or rotate a model you own. Partial patch. */
+ update(id, patch) {
+ if (!this._live() || !id) return false;
+ const msg = { id: String(id) };
+ for (const k of ['relEast', 'relNorth', 'yawDeg', 'scale']) {
+ if (Number.isFinite(patch?.[k])) msg[k] = patch[k];
+ }
+ try { this.room.send('model:update', msg); return true; } catch (e) {
+ log.warn('update failed:', e?.message || e);
+ return false;
+ }
+ }
+
+ /** Remove a model you own. */
+ remove(id) {
+ if (!this._live() || !id) return false;
+ try { this.room.send('model:remove', { id: String(id) }); return true; } catch (e) {
+ log.warn('remove failed:', e?.message || e);
+ return false;
+ }
+ }
+
+ heartbeat() {
+ if (!this._live()) return;
+ try { this.room.send('heartbeat', {}); } catch (e) { log.warn('heartbeat failed:', e?.message || e); }
+ }
+
+ destroy() {
+ this._destroyed = true;
+ if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }
+ this._closeRoom();
+ this.client = null;
+ this._setStatus('destroyed');
+ }
+}
diff --git a/packages/ar-studio/src/studio/pinch.js b/packages/ar-studio/src/studio/pinch.js
new file mode 100644
index 000000000..d8748a426
--- /dev/null
+++ b/packages/ar-studio/src/studio/pinch.js
@@ -0,0 +1,100 @@
+// Pure pinch-to-resize math for WebXR AR placement (no DOM, no THREE).
+//
+// A two-finger pinch during an immersive-ar session resizes the placed agent,
+// matching the native Scene Viewer / Quick Look gesture users already know.
+// The state machine is deliberately tiny and allocation-free so the session
+// controller (./multi-place.js) can drive it from raw touch points every frame:
+//
+// Call createPinchState once, pinchStart(state, dist, currentScale) when two
+// fingers go down, pinchMove(state, dist) as they move (returns the new scale,
+// or null when not pinching) and pinchEnd(state) when a finger lifts (returns
+// the final scale, or null when not pinching).
+//
+// Scale is the ratio of the current finger distance to the distance at pinch
+// start, applied to the scale the content already had: so consecutive pinches
+// compose naturally instead of snapping back to 1. Clamped to sane bounds: a
+// life-size avatar squeezed to a desk figurine (MIN) or grown to a statue (MAX).
+
+export const PINCH_SCALE_MIN = 0.25;
+export const PINCH_SCALE_MAX = 4;
+
+/** Minimum finger distance (px) considered a real pinch: rejects palm noise. */
+export const PINCH_DEADZONE_PX = 24;
+
+export function createPinchState() {
+ return { active: false, startDist: 0, baseScale: 1, scale: 1 };
+}
+
+/**
+ * Begin a pinch. Ignored (returns false) when the finger spread is inside the
+ * dead zone or inputs are not finite: the caller keeps treating input as taps.
+ *
+ * @param {ReturnType<createPinchState>} p
+ * @param {number} dist Distance between the two touch points, px.
+ * @param {number} baseScale The content's current uniform scale.
+ * @returns {boolean} true when the pinch is engaged.
+ */
+export function pinchStart(p, dist, baseScale) {
+ if (!Number.isFinite(dist) || dist < PINCH_DEADZONE_PX) return false;
+ const base = Number.isFinite(baseScale) && baseScale > 0 ? baseScale : 1;
+ p.active = true;
+ p.startDist = dist;
+ p.baseScale = base;
+ p.scale = base;
+ return true;
+}
+
+/**
+ * Advance an engaged pinch. Returns the new clamped scale, or null when no
+ * pinch is engaged or the distance is degenerate (caller applies nothing).
+ *
+ * @param {ReturnType<createPinchState>} p
+ * @param {number} dist Current distance between the two touch points, px.
+ * @returns {number|null}
+ */
+export function pinchMove(p, dist) {
+ if (!p.active || !Number.isFinite(dist) || dist <= 0 || p.startDist <= 0) return null;
+ const next = p.baseScale * (dist / p.startDist);
+ p.scale = Math.min(PINCH_SCALE_MAX, Math.max(PINCH_SCALE_MIN, next));
+ return p.scale;
+}
+
+/**
+ * End the pinch (a finger lifted). Returns the final scale to persist, or
+ * null when no pinch was engaged (a plain tap: nothing to save).
+ *
+ * @param {ReturnType<createPinchState>} p
+ * @returns {number|null}
+ */
+export function pinchEnd(p) {
+ if (!p.active) return null;
+ p.active = false;
+ return p.scale;
+}
+
+/**
+ * Clamp a persisted pin scale for rendering. Anything non-finite or
+ * non-positive (legacy pins, absent column) renders at natural size.
+ *
+ * @param {unknown} v Raw anchor_scale from the API (may be null/undefined).
+ * @returns {number}
+ */
+export function clampPinScale(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n) || n <= 0) return 1;
+ return Math.min(PINCH_SCALE_MAX, Math.max(PINCH_SCALE_MIN, n));
+}
+
+/**
+ * Euclidean distance between two touch points, in CSS pixels: the raw
+ * geometry both AR pinch lanes (WebXR's dom-overlay and camera-mode's plain
+ * canvas) feed into pinchStart/pinchMove.
+ *
+ * @param {TouchList|Touch[]} touches
+ * @returns {number}
+ */
+export function touchDist(touches) {
+ const dx = touches[0].clientX - touches[1].clientX;
+ const dy = touches[0].clientY - touches[1].clientY;
+ return Math.hypot(dx, dy);
+}
diff --git a/packages/ar-studio/src/studio/render.js b/packages/ar-studio/src/studio/render.js
new file mode 100644
index 000000000..b26a35548
--- /dev/null
+++ b/packages/ar-studio/src/studio/render.js
@@ -0,0 +1,145 @@
+// Rendering defaults that make a model look like it belongs in the room.
+//
+// Three things separate "a 3D object pasted on a camera feed" from "an object in
+// the room": filmic tone mapping (so bright materials roll off instead of
+// clipping to white), correct sRGB output (so colours are the colours the artist
+// authored), and image-based lighting from a real photographic environment (so
+// metal and glass reflect something plausible). This module applies all three,
+// picks a quality tier from real device signals, and never blocks the first
+// frame on a download.
+//
+// Ported from the three.ws shared renderer defaults (Apache-2.0), with the HDRI
+// set made configurable.
+
+import {
+ ACESFilmicToneMapping, SRGBColorSpace, VSMShadowMap, PMREMGenerator,
+ Box3, PlaneGeometry, ShadowMaterial, Mesh,
+} from 'three';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { THREE_WS } from '../config.js';
+
+/** Render budgets per tier. 'mobile' matches a low-end phone profile. */
+export const QUALITY_TIERS = {
+ high: { pixelRatioCap: 2, shadows: true, hdri: true },
+ medium: { pixelRatioCap: 1.5, shadows: true, hdri: true },
+ mobile: { pixelRatioCap: 1, shadows: false, hdri: false },
+};
+
+/**
+ * Pick a quality tier from real capability signals rather than a UA guess alone.
+ * @param {{navigator?: object, window?: object}} [env]
+ * @returns {'high'|'medium'|'mobile'}
+ */
+export function detectQualityTier(env = {}) {
+ const nav = env.navigator ?? (typeof navigator !== 'undefined' ? navigator : {});
+ const win = env.window ?? (typeof window !== 'undefined' ? window : {});
+ const ua = String(nav.userAgent || '');
+ const isMobile = /(iPhone|iPad|Android|Mobi)/i.test(ua);
+ const lowMem = (nav.deviceMemory ?? 8) < 4;
+ const lowCores = (nav.hardwareConcurrency ?? 8) < 4;
+ const coarse = !!(win.matchMedia && win.matchMedia('(any-pointer: coarse)').matches);
+ if (isMobile && (lowMem || lowCores)) return 'mobile';
+ if (coarse || lowMem || lowCores) return 'medium';
+ return 'high';
+}
+
+/**
+ * Apply tone mapping, colour space, pixel-ratio cap and shadow type. Call once,
+ * straight after constructing the renderer.
+ *
+ * @param {import('three').WebGLRenderer} renderer
+ * @param {{exposure?: number, tier?: 'high'|'medium'|'mobile'}} [opts]
+ * @returns {{pixelRatioCap:number, shadows:boolean, hdri:boolean}} the applied budget
+ */
+export function applyCinematicDefaults(renderer, opts = {}) {
+ const tier = QUALITY_TIERS[opts.tier] ? opts.tier : 'high';
+ const budget = QUALITY_TIERS[tier];
+ renderer.outputColorSpace = SRGBColorSpace;
+ renderer.toneMapping = ACESFilmicToneMapping;
+ renderer.toneMappingExposure = opts.exposure ?? 1.15;
+ renderer.setPixelRatio(Math.min(typeof window !== 'undefined' ? window.devicePixelRatio : 1, budget.pixelRatioCap));
+ renderer.shadowMap.enabled = budget.shadows;
+ if (budget.shadows) renderer.shadowMap.type = VSMShadowMap;
+ return budget;
+}
+
+const _envCache = new Map();
+
+/**
+ * Light the scene from an environment map.
+ *
+ * The procedural room environment is installed FIRST, synchronously, every time:
+ * it costs about a millisecond and lights the very first frame. A real HDRI (one
+ * or two megabytes) then replaces it when it arrives, so the visible change is a
+ * refinement of an already-correct image rather than the moment the world
+ * becomes lit. It is also the permanent answer on the mobile tier and whenever
+ * the fetch fails.
+ *
+ * @param {import('three').WebGLRenderer} renderer
+ * @param {import('three').Scene} scene
+ * @param {string|null} preset Key into `urls`, or null for the procedural room only.
+ * @param {{urls?: Record<string,string>}} [opts]
+ * @returns {Promise<import('three').Texture>} the installed environment map
+ */
+export async function loadEnvironment(renderer, scene, preset = 'studio', { urls = THREE_WS.hdri } = {}) {
+ const pmrem = new PMREMGenerator(renderer);
+ pmrem.compileEquirectangularShader();
+ const roomTarget = pmrem.fromScene(new RoomEnvironment(), 0.04);
+ scene.environment = roomTarget.texture;
+ scene.environmentIntensity ??= 1;
+
+ const url = preset && urls ? urls[preset] : null;
+ if (!url) {
+ // The render target stays valid after the generator is disposed, so this
+ // frees the scratch without touching the environment map itself.
+ pmrem.dispose();
+ return scene.environment;
+ }
+ try {
+ let hdr = _envCache.get(url);
+ if (!hdr) {
+ const { HDRLoader } = await import('three/addons/loaders/HDRLoader.js');
+ hdr = await new HDRLoader().loadAsync(url);
+ _envCache.set(url, hdr);
+ }
+ const envTarget = pmrem.fromEquirectangular(hdr);
+ // Another call may have re-pointed the environment while this HDRI was in
+ // flight. Losing that race means ours is stale: free it rather than stamp
+ // it over the newer one.
+ if (scene.environment === roomTarget.texture) scene.environment = envTarget.texture;
+ else envTarget.dispose();
+ roomTarget.dispose();
+ return scene.environment;
+ } catch {
+ // The room environment installed above stands, so the scene is still lit.
+ return scene.environment;
+ } finally {
+ pmrem.dispose();
+ }
+}
+
+/**
+ * A shadow-catching plane: invisible except where a shadow falls on it, so a
+ * model reads as resting on a surface without drawing a floor.
+ *
+ * @param {import('three').Scene} scene
+ * @param {import('three').Object3D} target
+ * @param {import('three').Mesh} [existing] Reuse a previous catcher.
+ * @param {number} [opacity]
+ */
+export function updateGroundContactShadow(scene, target, existing, opacity = 0.35) {
+ const b = new Box3().setFromObject(target);
+ if (!Number.isFinite(b.min.y)) return existing ?? null;
+ const footprint = Math.max(b.max.x - b.min.x, b.max.z - b.min.z, 1);
+ const size = footprint * 6;
+ let plane = existing;
+ if (!plane) {
+ plane = new Mesh(new PlaneGeometry(1, 1), new ShadowMaterial({ opacity }));
+ plane.rotation.x = -Math.PI / 2;
+ plane.receiveShadow = true;
+ scene.add(plane);
+ }
+ plane.scale.set(size, size, 1);
+ plane.position.set((b.min.x + b.max.x) / 2, b.min.y, (b.min.z + b.max.z) / 2);
+ return plane;
+}
diff --git a/packages/ar-studio/src/studio/scene-math.js b/packages/ar-studio/src/studio/scene-math.js
new file mode 100644
index 000000000..45b6d3cc9
--- /dev/null
+++ b/packages/ar-studio/src/studio/scene-math.js
@@ -0,0 +1,345 @@
+// Pure scene math and (de)serialization for the AR Studio.
+//
+// Everything here is DOM-free and Three-free so it can be unit-tested directly:
+// model normalization (a forge prop and a full avatar land in the room at a
+// believable size, resting ON the floor), spawn placement (new models appear on
+// the floor in front of wherever the camera looks), the two-finger twist gesture
+// (rotate a placed model in place), and the localStorage scene format (what
+// survives a refresh, validated so a corrupt or hostile blob can never spawn a
+// non-GLB URL or a NaN transform into the scene).
+
+/** Standing height (m) a skinned/humanoid model is normalized to. */
+export const AVATAR_TARGET_HEIGHT_M = 1.65;
+
+/** Longest dimension (m) a static prop is normalized to. */
+export const PROP_TARGET_SIZE_M = 0.75;
+
+/** Placement scale bounds: mirrors the pinch clamp in ./pinch.js. */
+export const SCALE_MIN = 0.25;
+export const SCALE_MAX = 4;
+
+/** Hard cap on simultaneous placements: keeps low-end phones interactive. */
+export const MAX_PLACEMENTS = 20;
+
+/** How far (m) in front of the camera a newly added model lands. */
+export const SPAWN_DISTANCE_M = 1.6;
+
+/**
+ * Read the room's light from a downsampled camera frame (RGBA bytes). Returns a
+ * light INTENSITY multiplier (dim room → <1, bright room → >1) and a white-
+ * balance TINT (a warm-lamp room casts warm, daylight casts cool) so a placed
+ * model belongs to the room instead of glowing neutral on top of it. Pure: the
+ * caller does the canvas read and applies the result to the scene lights.
+ *
+ * @param {Uint8ClampedArray|number[]} data RGBA pixels (length divisible by 4).
+ * @returns {{ intensity: number, tint: { r: number, g: number, b: number } }}
+ * intensity in [0.4, 1.35]; tint near {1,1,1} for neutral light, each channel
+ * pulled a third of the way toward the room's cast. A black/empty frame
+ * returns neutral tint and the floor intensity.
+ */
+export function roomLightFromPixels(data) {
+ const px = data && data.length ? data.length / 4 : 0;
+ if (!px) return { intensity: 0.4, tint: { r: 1, g: 1, b: 1 } };
+ let rSum = 0, gSum = 0, bSum = 0, lumaSum = 0;
+ for (let i = 0; i < data.length; i += 4) {
+ const r = data[i], g = data[i + 1], b = data[i + 2];
+ rSum += r; gSum += g; bSum += b;
+ lumaSum += 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ }
+ const luma = lumaSum / px / 255; // 0 (black) → 1 (blown out)
+ const intensity = Math.min(1.35, Math.max(0.4, 0.35 + luma * 1.25));
+
+ // Normalize the mean colour to its own brightness so only the CAST remains,
+ // then pull a third of the way toward it (full tint would recolour the
+ // model's own albedo). A near-black frame has no reliable cast → stay neutral.
+ const mean = (rSum + gSum + bSum) / (px * 3);
+ if (mean <= 6) return { intensity, tint: { r: 1, g: 1, b: 1 } };
+ const pull = (sum) => 1 + ((sum / px / mean) - 1) * 0.33;
+ return { intensity, tint: { r: pull(rSum), g: pull(gSum), b: pull(bSum) } };
+}
+
+/**
+ * Normalize a raw model bounding box into a floor-resting placement transform.
+ *
+ * @param {{min:{x:number,y:number,z:number}, max:{x:number,y:number,z:number}}} box
+ * World-space bounds of the freshly loaded model (Box3-shaped, plain numbers).
+ * @param {{ skinned?: boolean }} [opts] skinned = has a SkinnedMesh (treat as
+ * an avatar and normalize by height rather than longest dimension).
+ * @returns {{ scale: number, yOffset: number }}
+ * scale: uniform scale to apply; yOffset: translate so the model's lowest
+ * point sits exactly on y=0 AFTER scaling. Degenerate/empty boxes come back
+ * as identity so a broken export still shows up instead of vanishing.
+ */
+export function fitTransform(box, { skinned = false } = {}) {
+ const dx = Number(box?.max?.x) - Number(box?.min?.x);
+ const dy = Number(box?.max?.y) - Number(box?.min?.y);
+ const dz = Number(box?.max?.z) - Number(box?.min?.z);
+ if (![dx, dy, dz].every((v) => Number.isFinite(v) && v >= 0)) {
+ return { scale: 1, yOffset: 0 };
+ }
+ const longest = Math.max(dx, dy, dz);
+ if (longest <= 1e-6) return { scale: 1, yOffset: 0 };
+
+ let scale;
+ if (skinned && dy > 1e-6) {
+ scale = AVATAR_TARGET_HEIGHT_M / dy;
+ } else {
+ scale = PROP_TARGET_SIZE_M / longest;
+ }
+ // A model authored at real-world size should stay real-world size: only
+ // shrink giants and grow miniatures, never rescale something already within
+ // 2x of its target. This keeps furniture-scale scans believable.
+ if (scale > 0.5 && scale < 2) scale = 1;
+
+ const minY = Number(box.min.y);
+ const yOffset = Number.isFinite(minY) ? -minY * scale : 0;
+ return { scale, yOffset };
+}
+
+/**
+ * Floor point where a newly added model spawns: project the camera's forward
+ * direction onto the floor plane at a fixed distance, so the model lands in the
+ * middle of the view no matter where the user is looking (including straight
+ * up: the fallback drops it in front of the camera's horizontal heading).
+ *
+ * @param {{x:number,y:number,z:number}} camPos
+ * @param {{x:number,y:number,z:number}} camForward Unit-ish look vector.
+ * @param {number} [distance]
+ * @returns {{x:number,z:number}}
+ */
+export function spawnPointInFront(camPos, camForward, distance = SPAWN_DISTANCE_M) {
+ const fx = Number(camForward?.x) || 0;
+ const fz = Number(camForward?.z) || 0;
+ const len = Math.hypot(fx, fz);
+ // Looking straight up/down: fall back to -Z (the initial camera heading).
+ const nx = len > 1e-4 ? fx / len : 0;
+ const nz = len > 1e-4 ? fz / len : -1;
+ const px = (Number(camPos?.x) || 0) + nx * distance;
+ const pz = (Number(camPos?.z) || 0) + nz * distance;
+ return { x: px, z: pz };
+}
+
+/**
+ * Two-finger twist: signed angle (radians) between two touch-pair orientations.
+ * Wrapped to (-PI, PI] so a twist across the ±180° boundary never spins the
+ * model the long way round.
+ *
+ * @param {number} startAngle atan2 angle of the touch pair at gesture start.
+ * @param {number} nowAngle atan2 angle of the touch pair now.
+ * @returns {number} delta yaw to ADD to the model's yaw at gesture start.
+ */
+export function twistDelta(startAngle, nowAngle) {
+ if (!Number.isFinite(startAngle) || !Number.isFinite(nowAngle)) return 0;
+ let d = nowAngle - startAngle;
+ while (d > Math.PI) d -= 2 * Math.PI;
+ while (d <= -Math.PI) d += 2 * Math.PI;
+ return d;
+}
+
+/** atan2 orientation of a two-touch pair: feed into twistDelta. */
+export function touchAngle(touches) {
+ return Math.atan2(
+ touches[1].clientY - touches[0].clientY,
+ touches[1].clientX - touches[0].clientX,
+ );
+}
+
+/**
+ * Accept a GLB source the studio is willing to load: an https URL or a
+ * site-relative path. Anything else (http, data:, blob:, javascript:,
+ * protocol-relative) is rejected: these persist in localStorage and arrive
+ * via ?src=, so they are untrusted input.
+ *
+ * @param {unknown} raw
+ * @returns {string|null} normalized URL string, or null when rejected.
+ */
+export function normalizeGlbUrl(raw) {
+ const s = String(raw ?? '').trim();
+ if (!s) return null;
+ if (s.startsWith('/') && !s.startsWith('//')) return s;
+ try {
+ const u = new URL(s);
+ return u.protocol === 'https:' ? u.href : null;
+ } catch {
+ return null;
+ }
+}
+
+const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
+
+/**
+ * Serialize live placements for localStorage. Only source + transform survive
+ * a refresh: meshes are re-loaded from their URLs on restore.
+ *
+ * @param {Array<{ src: string, title?: string, x: number, z: number,
+ * yaw: number, scale: number }>} placements
+ * @returns {string} JSON payload.
+ */
+export function serializeScene(placements) {
+ const items = (Array.isArray(placements) ? placements : [])
+ .slice(0, MAX_PLACEMENTS)
+ .map((p) => ({
+ src: String(p.src || ''),
+ title: String(p.title || '').slice(0, 120),
+ x: Number(p.x) || 0,
+ z: Number(p.z) || 0,
+ yaw: Number(p.yaw) || 0,
+ scale: clamp(Number(p.scale) || 1, SCALE_MIN, SCALE_MAX),
+ }))
+ .filter((p) => normalizeGlbUrl(p.src));
+ return JSON.stringify({ v: 1, items });
+}
+
+/**
+ * Parse + validate a persisted scene. Hostile or corrupt input degrades to an
+ * empty scene, never a throw and never an unvetted URL.
+ *
+ * @param {string|null|undefined} json
+ * @returns {Array<{ src: string, title: string, x: number, z: number,
+ * yaw: number, scale: number }>}
+ */
+export function deserializeScene(json) {
+ let data;
+ try {
+ data = JSON.parse(json ?? 'null');
+ } catch {
+ return [];
+ }
+ if (!data || data.v !== 1 || !Array.isArray(data.items)) return [];
+ const out = [];
+ for (const it of data.items) {
+ if (out.length >= MAX_PLACEMENTS) break;
+ const src = normalizeGlbUrl(it?.src);
+ if (!src) continue;
+ const x = Number(it.x);
+ const z = Number(it.z);
+ if (!Number.isFinite(x) || !Number.isFinite(z)) continue;
+ out.push({
+ src,
+ title: String(it.title || '').slice(0, 120),
+ x: clamp(x, -50, 50),
+ z: clamp(z, -50, 50),
+ yaw: Number.isFinite(Number(it.yaw)) ? Number(it.yaw) : 0,
+ scale: clamp(Number(it.scale) || 1, SCALE_MIN, SCALE_MAX),
+ });
+ }
+ return out;
+}
+
+/**
+ * Models requested via the URL: every ?src= (repeatable) paired positionally
+ * with an optional ?title=. Invalid sources are dropped, capped to the scene
+ * limit. Used for deep links and the desktop→phone QR handoff.
+ *
+ * @param {URLSearchParams} params
+ * @returns {Array<{ src: string, title: string }>}
+ */
+export function parseSrcParams(params) {
+ const srcs = params.getAll('src');
+ const titles = params.getAll('title');
+ const out = [];
+ for (let i = 0; i < srcs.length && out.length < MAX_PLACEMENTS; i++) {
+ const src = normalizeGlbUrl(srcs[i]);
+ if (!src) continue;
+ out.push({ src, title: String(titles[i] || '').slice(0, 120) });
+ }
+ return out;
+}
+
+// ── Full-scene links (#s= hash) ───────────────────────────────────────────────
+// The ?src= list reopens the same MODELS; the hash carries the whole
+// ARRANGEMENT (positions, yaw, scale) so a composed scene round-trips exactly.
+// base64url over the same validated JSON the localStorage scene uses: the
+// decoder funnels through deserializeScene, so a hostile hash degrades to an
+// empty scene exactly like a hostile storage blob.
+
+function toBase64Url(s) {
+ const bytes = new TextEncoder().encode(s);
+ let bin = '';
+ for (const b of bytes) bin += String.fromCharCode(b);
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+function fromBase64Url(s) {
+ const b64 = String(s).replace(/-/g, '+').replace(/_/g, '/');
+ const bin = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4));
+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
+ return new TextDecoder().decode(bytes);
+}
+
+/**
+ * Encode the current placements (sources + transforms) as a URL-hash payload.
+ *
+ * @param {Array<{ src: string, title?: string, x: number, z: number,
+ * yaw: number, scale: number }>} placements
+ * @returns {string} base64url payload for `#s=`, or '' when nothing is shareable.
+ */
+export function sceneToHashParam(placements) {
+ const json = serializeScene(placements);
+ try {
+ return JSON.parse(json).items.length ? toBase64Url(json) : '';
+ } catch {
+ return '';
+ }
+}
+
+/**
+ * Decode a `#s=` payload back into validated scene items. Hostile, truncated,
+ * or foreign input degrades to an empty list: never a throw.
+ *
+ * @param {string|null|undefined} raw The value after `#s=`.
+ * @returns {ReturnType<typeof deserializeScene>}
+ */
+export function sceneFromHashParam(raw) {
+ if (!raw) return [];
+ try {
+ return deserializeScene(fromBase64Url(raw));
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Full-fidelity share URL: the ?src= list (for link previews and old clients)
+ * plus the `#s=` arrangement hash. Falls back to the plain model list when the
+ * payload would push the link past QR-friendly length.
+ *
+ * @param {string} baseUrl The page hosting the studio, e.g. 'https://acme.com/ar/'.
+ * @param {Array<{src:string,title?:string,x?:number,z?:number,yaw?:number,scale?:number}>} placements
+ * @param {number} [maxUrlLength]
+ * @returns {string}
+ */
+export function studioSceneUrl(baseUrl, placements, maxUrlLength = 1500) {
+ const base = studioShareUrl(baseUrl, placements);
+ const hash = sceneToHashParam(placements);
+ if (!hash) return base;
+ const full = `${base}#s=${hash}`;
+ return full.length <= maxUrlLength ? full : base;
+}
+
+/**
+ * The shareable URL that reopens the current scene's MODELS (sources only
+ * transforms ride in the hash above). Capped so the QR stays scannable.
+ *
+ * @param {string} baseUrl The page hosting the studio.
+ * @param {Array<{src:string,title?:string}>} placements
+ * @param {number} [max] How many models to embed in the link.
+ * @returns {string}
+ */
+export function studioShareUrl(baseUrl, placements, max = 4) {
+ const base = String(baseUrl || '').split('#')[0];
+ const list = (Array.isArray(placements) ? placements : [])
+ .map((p) => ({ src: normalizeGlbUrl(p.src), title: String(p.title || '').slice(0, 60) }))
+ .filter((p) => p.src);
+ // De-duplicate by source: five copies of one crate share a single URL entry.
+ const seen = new Set();
+ const unique = list.filter((p) => (seen.has(p.src) ? false : (seen.add(p.src), true))).slice(0, max);
+ if (!unique.length) return base;
+ const q = new URLSearchParams();
+ for (const p of unique) {
+ q.append('src', p.src);
+ q.append('title', p.title);
+ }
+ const join = base.includes('?') ? '&' : '?';
+ return `${base}${join}${q.toString()}`;
+}
diff --git a/packages/ar-studio/src/studio/schemas.js b/packages/ar-studio/src/studio/schemas.js
new file mode 100644
index 000000000..2d62bdc9e
--- /dev/null
+++ b/packages/ar-studio/src/studio/schemas.js
@@ -0,0 +1,95 @@
+// Schema definitions for the shared AR Studio world (studio_world room), shared
+// between the room server and ./net.js (the client in this package).
+//
+// Unlike irl_world (presence + reactions only, pins are private-by-location and
+// REST-gated), studio_world IS a shared scene transport by design: a studio room
+// is an INTENTIONAL collaborative session two or more people opt into by holding
+// the same room key (a shared code, or the same QR marker they both scan). So the
+// placed models ARE the synced state: every add/move/scale/rotate/remove
+// delta-broadcasts to everyone in the room, and a late joiner receives the whole
+// current scene on join. This lives on the WalkRoom side of the privacy line
+// (an opted-into shared world), never by loosening irl_world.
+//
+// Coordinate frame: relEast / relNorth are shared LOGICAL metres from the room's
+// common origin, decoupled from any one device's camera. A plain (non-co-located)
+// viewer maps them to their own local floor (origin = where they started); two
+// phones that scanned the same QR marker map them to the SAME physical spot via
+// the same marker frame. Yaw is degrees. This is the one
+// schema-level difference from WalkRoom's world-frame x/z: everything else
+// (owner gating, caps, rate limits, delta sync) mirrors it.
+//
+// IMPORTANT: @colyseus/schema's binary protocol is POSITIONAL. Field indices are
+// load-bearing across a rolling deploy: always APPEND new fields at the end,
+// never insert in the middle, or an older still-connected client is shifted off
+// the wire format mid-deploy.
+
+import { Schema, MapSchema, defineTypes } from '@colyseus/schema';
+
+// One placed model in the shared scene. `src` is the GLB URL every client loads
+// (validated server-side: https or site-relative, length-capped). Transforms are
+// in the room's shared logical frame (see header). `ownerId` is a stable per-
+// browser key (the studio's forge:cid), so a reconnecting author keeps ownership.
+export class StudioModel extends Schema {
+ constructor() {
+ super();
+ this.id = '';
+ this.src = ''; // GLB url (https or site-relative)
+ this.title = ''; // human label, for the remote-model UI
+ this.relEast = 0; // shared logical metres, +east
+ this.relNorth = 0; // shared logical metres, +north
+ this.yawDeg = 0; // 0-360 heading
+ this.scale = 1; // uniform scale, clamped [0.25, 4]
+ this.height = 0; // fitted model height (m), for spawn-distance parity
+ this.ownerId = ''; // stable browser key of the placer
+ this.ts = 0; // server epoch ms of the last change
+ }
+}
+defineTypes(StudioModel, {
+ id: 'string',
+ src: 'string',
+ title: 'string',
+ relEast: 'float32',
+ relNorth: 'float32',
+ yawDeg: 'float32',
+ scale: 'float32',
+ height: 'float32',
+ ownerId: 'string',
+ ts: 'float64',
+});
+
+// A live participant in the room. Presence only: count + optional display name,
+// so the studio can show "3 people building here." No location ever rides this.
+export class StudioViewer extends Schema {
+ constructor() {
+ super();
+ this.id = ''; // ephemeral session id
+ this.name = ''; // short display name (optional)
+ this.ownerId = ''; // stable browser key (ties a viewer to their models)
+ this.tsServer = 0; // last heartbeat epoch ms (drives the reaper)
+ }
+}
+defineTypes(StudioViewer, {
+ id: 'string',
+ name: 'string',
+ ownerId: 'string',
+ tsServer: 'float64',
+});
+
+export class StudioState extends Schema {
+ constructor() {
+ super();
+ // The room key (shared code or marker id) this instance serves: the
+ // filterBy match key, identical for every participant in the instance.
+ this.roomKey = '';
+ // The shared scene: every placed model, keyed by id. Populated by
+ // StudioRoom on model:spawn and pruned on model:remove / owner cleanup.
+ this.models = new MapSchema();
+ // Live participants, keyed by session id (presence + reaper).
+ this.viewers = new MapSchema();
+ }
+}
+defineTypes(StudioState, {
+ roomKey: 'string',
+ models: { map: StudioModel },
+ viewers: { map: StudioViewer },
+});
diff --git a/packages/ar-studio/src/studio/sensor-fusion.js b/packages/ar-studio/src/studio/sensor-fusion.js
new file mode 100644
index 000000000..d498c9dfb
--- /dev/null
+++ b/packages/ar-studio/src/studio/sensor-fusion.js
@@ -0,0 +1,135 @@
+// Pure sensor-fusion helpers for the gyro world-lock camera.
+//
+// Why this exists
+// ───────────────
+// The world-lock camera is driven by `deviceorientation` (alpha/beta) and, on
+// iOS, `webkitCompassHeading`. Real devices deliver `null`, `NaN`, uncalibrated,
+// and discontinuous readings constantly: a magnetometer that walks into a
+// magnetic dead-zone keeps reporting its LAST heading forever; a dropped frame
+// arrives with `NaN` Euler angles; the compass bearing wraps 359°→1° as the user
+// turns. A single bad value flowing untreated into `cameraYaw`/`cameraPitch`
+// makes the avatar snap, spin, freeze, or vanish: the single worst reliability
+// failure the AR experience can have.
+//
+// This module is the pure decision logic that keeps a bad reading from ever
+// reaching the camera. No DOM, no Three.js, no sensors, no clock: plain numbers
+// in, plain numbers out: so the studio wires it to the live event stream while
+// the test suite verifies the math directly (mirrors ./camera-fov.js as a
+// pure, unit-tested core).
+//
+// Coordinate conventions, shared with the studio's camera look:
+// cameraYaw (rad): world Y-rotation; renderedBearing = −cameraYaw.
+// Compass bearing: 0-359° clockwise from true north (0 = N, 90 = E).
+// World yaw from a bearing: yaw = −(deg · π/180) (matches compassToYaw).
+
+const DEG = Math.PI / 180;
+
+// A heading older than this (ms) is treated as dead. iOS fires orientation
+// events at ~60 Hz, so a gap this long means the magnetometer stopped updating
+// (uncalibrated, or in a magnetic dead-zone): fall back to the relative gyro
+// path rather than keep steering by a frozen bearing.
+export const COMPASS_STALE_MS = 1500;
+
+// Shortest-path angular interpolation (radians). Mirrors `lerpAngle` in
+// the studio; kept here so the pure core has no dependency on the DOM
+// bundle. Eases `from` toward `to` along the shortest arc, so crossing the
+// 359°→1° compass boundary is a ~2° move, never a ~360° one.
+export function shortestAngleLerp(from, to, t) {
+ let diff = ((to - from + Math.PI) % (Math.PI * 2)) - Math.PI;
+ if (diff < -Math.PI) diff += Math.PI * 2;
+ return from + diff * t;
+}
+
+// A deviceorientation reading is usable only if BOTH Euler angles are real,
+// finite numbers. `null`/`undefined`/`NaN`/`±Infinity` are all rejected so one
+// bad frame can never poison the camera quaternion. Callers hold the last valid
+// reading on a `false` here rather than substituting 0/90 (which would yank the
+// view's yaw to page-north and slam the pitch to the horizon).
+export function isFiniteReading(alpha, beta) {
+ return Number.isFinite(alpha) && Number.isFinite(beta);
+}
+
+// True while the last good compass sample is recent enough to trust. `lastGoodAt`
+// is the timestamp (same clock as `now`) of the last finite heading; a non-finite
+// `lastGoodAt` (never seen a compass) is never fresh.
+export function isCompassFresh(lastGoodAt, now, staleMs = COMPASS_STALE_MS) {
+ return Number.isFinite(lastGoodAt) && now - lastGoodAt <= staleMs;
+}
+
+// The absolute (north-referenced) yaw path is only correct when a GPS world-anchor
+// gives the scene an absolute origin AND a fresh compass bearing exists. Without
+// GPS the avatar would jump off-frame to its compass bearing the instant it locks;
+// without a fresh compass we are steering by a dead heading: both fall back to the
+// relative gyro path.
+export function shouldUseAbsoluteYaw({ gpsModeActive, compassHeading, compassFresh }) {
+ return Boolean(gpsModeActive) && compassHeading !== null && compassHeading !== undefined && compassFresh;
+}
+
+// Resolve the target `cameraYaw` for one orientation frame.
+//
+// absolute path: ease toward the true bearing along the shortest arc so the
+// avatar stays planted on its real-world direction for every
+// viewer, and a 359°→1° wrap never spins.
+// relative path: integrate alpha deltas from the lock baseline so the view
+// rotates with the phone while the avatar holds its pinned spot.
+//
+// All inputs are finite by contract (the caller holds the last valid reading);
+// the result is therefore always finite.
+export function resolveLockYaw({
+ useAbsolute,
+ prevYaw,
+ alpha,
+ baseAlpha,
+ baseYaw,
+ compassHeading,
+ absoluteSmooth = 0.4,
+}) {
+ if (useAbsolute) {
+ const target = -compassHeading * DEG;
+ return shortestAngleLerp(prevYaw, target, absoluteSmooth);
+ }
+ let dAlpha = alpha - baseAlpha;
+ if (dAlpha > 180) dAlpha -= 360;
+ if (dAlpha < -180) dAlpha += 360;
+ return baseYaw + dAlpha * DEG;
+}
+
+// Clamp a pitch into the camera's range, guaranteeing a finite result. A `NaN`
+// that slipped past upstream guards collapses to 0 (always inside the symmetric
+// range) instead of propagating: `Math.max/min` would otherwise return `NaN`.
+export function clampPitch(pitch, min, max) {
+ const p = Number.isFinite(pitch) ? pitch : 0;
+ return p < min ? min : p > max ? max : p;
+}
+
+// ── Screen-orientation frame correction (task-02) ───────────────────────────
+// The pitch path integrates `beta` (front↔back tilt) on the assumption the phone
+// is held PORTRAIT. Rotate to landscape and the physical "look up / look down" the
+// user does no longer moves `beta`: it moves `gamma` (left↔right tilt), and the
+// sign flips between the two landscape directions. Left uncorrected, tilting the
+// phone up in landscape slides the avatar sideways instead of raising the view.
+//
+// `screen.orientation.angle` (0 | 90 | 180 | 270) tells us how the screen is
+// rotated relative to its natural (portrait) frame. We fold it in to recover the
+// PORTRAIT-EQUIVALENT pitch angle, so every downstream baseline/delta computation
+// keeps working unchanged regardless of how the device is held.
+//
+// angle 0 (portrait) → +beta
+// angle 90 (landscape, ⟲ 90°) → +gamma
+// angle 180 (portrait, upside-down)→ −beta
+// angle 270 (landscape, ⟳ 90°) → −gamma
+//
+// Returns a finite number by contract when given finite beta/gamma; a non-finite
+// component for the active axis collapses to 0 (horizon) rather than poisoning the
+// camera.
+export function screenPitchDeg(beta, gamma, screenAngle = 0) {
+ const a = ((Math.round(Number(screenAngle) / 90) * 90) % 360 + 360) % 360;
+ let v;
+ switch (a) {
+ case 90: v = gamma; break;
+ case 180: v = -beta; break;
+ case 270: v = -gamma; break;
+ default: v = beta; break; // 0 / unknown → portrait
+ }
+ return Number.isFinite(v) ? v : 0;
+}
diff --git a/packages/ar-studio/src/studio/studio.js b/packages/ar-studio/src/studio/studio.js
new file mode 100644
index 000000000..0e43b83fb
--- /dev/null
+++ b/packages/ar-studio/src/studio/studio.js
@@ -0,0 +1,2763 @@
+// AR Studio: a live, multi-model AR scene through the device camera.
+//
+// Every other web-AR drop-in places exactly one model and hands off to a native
+// viewer. This one keeps the whole scene in your page: place any number of
+// models, arrange them by hand, generate new ones from a prompt without leaving
+// the camera, share the arrangement as a link or a QR code, and build in the
+// same room as someone else in real time.
+//
+// Rendering ladder, best first: every device gets the richest path it can:
+//
+// 1. WebXR immersive-ar (Android Chrome, headsets): a hit-test reticle that
+// stays armed for the whole session, one XRAnchor per placed model,
+// real-world lighting estimation, and depth occlusion so a model hides
+// behind your couch instead of painting over it.
+// 2. Camera passthrough (iOS Safari, and anywhere else with a camera):
+// transparent WebGL over the live feed, gyro world-lock, and room-light
+// matching sampled from the actual video frames.
+// 3. Preview (desktop, no camera): the same scene on a grid floor with
+// drag-look and a QR hand-off to a phone.
+//
+// The scene persists to localStorage and round-trips through the URL, so an
+// arrangement composed on a laptop reopens exactly on a phone.
+//
+// Ported and generalized from the three.ws AR Studio (Apache-2.0).
+
+import {
+ AnimationMixer, Box3, CanvasTexture, Color, DirectionalLight, Fog, GridHelper, Group,
+ HemisphereLight, Mesh, MeshBasicMaterial, PerspectiveCamera, PlaneGeometry,
+ Raycaster, RingGeometry, Scene, Vector2, Vector3, WebGLRenderer, WebGLRenderTarget,
+} from 'three';
+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
+
+import { resolveConfig } from '../config.js';
+import { createLogger } from '../log.js';
+import { renderQRToSVG } from '../qr.js';
+import { createForgeClient } from '../forge/client.js';
+import { resolveSources } from '../sources/index.js';
+import { rememberRecent } from '../sources/recents.js';
+import { buildArLaunchUrl } from '../ar-launch.js';
+
+import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './render.js';
+import { buildUI, el } from './ui.js';
+import { EstimatedLighting } from './estimated-lighting.js';
+import { MultiPlaceSession } from './multi-place.js';
+import { createLoadQueue } from './load-queue.js';
+import { sharedGLTFLoader } from './loaders.js';
+import { mountIdle } from './idle.js';
+import { captureComposite, shareOrDownload, shareUrlOrCopy } from './capture.js';
+import {
+ arCapability, isQuickLookReady, placeInYourSpace, prepareNativeAr, releaseQuickLook,
+} from './native-ar.js';
+import { deriveVerticalFovDeg, DEFAULT_DIAG_FOV_DEG } from './camera-fov.js';
+import { clampPitch, isFiniteReading, resolveLockYaw, screenPitchDeg } from './sensor-fusion.js';
+import {
+ createPinchState, pinchEnd, pinchMove, pinchStart, touchDist,
+ PINCH_SCALE_MAX, PINCH_SCALE_MIN,
+} from './pinch.js';
+import {
+ deserializeScene, fitTransform, MAX_PLACEMENTS, normalizeGlbUrl, roomLightFromPixels,
+ sceneFromHashParam, serializeScene, SPAWN_DISTANCE_M, spawnPointInFront,
+ studioSceneUrl, studioShareUrl, touchAngle, twistDelta,
+} from './scene-math.js';
+import {
+ generateRoomCode, localToShared, normalizeRoomCode, roomKeyForCode, roomShareUrl, sharedToLocal,
+} from './coords.js';
+import { StudioNet } from './net.js';
+
+const log = createLogger('ar-studio');
+
+const EYE_HEIGHT_M = 1.55;
+const PITCH_MIN = -1.25;
+const PITCH_MAX = 1.35;
+const HEMI_BASE = 1.0;
+const SUN_BASE = 1.15;
+const LIST_SLICE = 60;
+
+/** One live studio. Prefer `createArStudio()` over constructing this directly. */
+export class ArStudio {
+ /**
+ * @param {HTMLElement} host Where the studio mounts.
+ * @param {object} [options] See src/config.js for every field.
+ */
+ constructor(host, options = {}) {
+ if (!host) throw new Error('ar-studio: a host element is required');
+ this.host = host;
+ this.config = resolveConfig(options);
+ this.clientId = readClientId(this.config.persistKey);
+ this.sources = resolveSources(this.config.assets, this.config);
+ this._listeners = new Map();
+ this._destroyed = false;
+
+ this.ui = buildUI(host, this.config);
+ if (this.config.fullscreen ?? (host === document.body)) this.ui.root.classList.add('is-fullscreen');
+
+ this._initScene();
+ this._initState();
+ this._wireUI();
+ this._boot();
+ }
+
+ // ── Events ────────────────────────────────────────────────────────────────
+
+ /**
+ * Subscribe to a studio event. Returns an unsubscribe function.
+ * Events: `add` `remove` `select` `clear` `generate` `generate-error`
+ * `camera` `xr` `room` `share`.
+ */
+ on(event, fn) {
+ if (!this._listeners.has(event)) this._listeners.set(event, new Set());
+ this._listeners.get(event).add(fn);
+ return () => this.off(event, fn);
+ }
+
+ off(event, fn) {
+ this._listeners.get(event)?.delete(fn);
+ }
+
+ _emit(event, detail = {}) {
+ for (const fn of this._listeners.get(event) || []) {
+ try { fn(detail); } catch (err) { log.warn(`${event} listener error`, err); }
+ }
+ try { this.config.onEvent?.(event, detail); } catch (err) { log.warn('onEvent error', err); }
+ try {
+ this.ui.root.dispatchEvent(new CustomEvent(`ar-studio:${event}`, { detail, bubbles: true }));
+ } catch { /* no CustomEvent in this host */ }
+ }
+
+ // ── Scene ─────────────────────────────────────────────────────────────────
+
+ _initScene() {
+ this.renderer = new WebGLRenderer({
+ canvas: this.ui.canvas, alpha: true, antialias: true, preserveDrawingBuffer: true,
+ });
+ this.renderer.setClearColor(0x000000, 0);
+ this.qualityTier = detectQualityTier();
+ applyCinematicDefaults(this.renderer, { tier: this.qualityTier });
+
+ this.scene = new Scene();
+ this.camera = new PerspectiveCamera(58, 1, 0.02, 200);
+ this.camera.position.set(0, EYE_HEIGHT_M, 0);
+ this.cameraYaw = 0;
+ // Tilted down enough that the floor, and anything standing on it, is in
+ // frame before the viewer touches anything.
+ this.cameraPitch = -0.24;
+
+ const preset = this.qualityTier === 'mobile' ? null : (this.config.lighting?.preset ?? 'studio');
+ loadEnvironment(this.renderer, this.scene, preset, { urls: this.config.lighting?.urls })
+ .catch((err) => log.warn('environment map failed', err));
+
+ this.hemi = new HemisphereLight(0xffffff, 0x444455, HEMI_BASE);
+ this.sun = new DirectionalLight(0xffffff, SUN_BASE);
+ this.sun.position.set(2.5, 6, 3);
+ this.scene.add(this.hemi, this.sun);
+
+ // Preview-mode floor: a calm grid that hides the moment the camera feed
+ // becomes the ground truth. The invisible ray plane is the drag target in
+ // both modes. Distance fog fades the far lines out instead of letting them
+ // collapse into a moire band along the horizon, which is what a flat grid
+ // viewed at a shallow angle does otherwise. It starts well beyond any
+ // placement, so it never touches a model.
+ this.grid = new GridHelper(24, 48, 0x3a3f52, 0x23273a);
+ this.grid.position.y = 0.001;
+ this.grid.material.transparent = true;
+ this.grid.material.opacity = 0.75;
+ this._fog = new Fog(0x06070a, 5, 17);
+ this.scene.fog = this._fog;
+ this.scene.add(this.grid);
+ this.rayPlane = new Mesh(new PlaneGeometry(80, 80), new MeshBasicMaterial({ visible: false, side: 2 }));
+ this.rayPlane.rotation.x = -Math.PI / 2;
+ this.scene.add(this.rayPlane);
+
+ this.selRing = new Mesh(
+ new RingGeometry(0.3, 0.34, 48).rotateX(-Math.PI / 2),
+ new MeshBasicMaterial({ color: 0x8b7cf8, transparent: true, opacity: 0.85, depthTest: false }),
+ );
+ if (this.config.branding?.accent) {
+ try { this.selRing.material.color.set(this.config.branding.accent); } catch { /* keep default */ }
+ }
+ this.selRing.renderOrder = 998;
+ this.selRing.visible = false;
+ this.scene.add(this.selRing);
+
+ this.shadowTex = makeShadowTexture();
+ this.reducedMotion = prefersReducedMotion();
+ this._applyCameraLook();
+ }
+
+ _initState() {
+ /** @type {Array<object>} */
+ this.placements = [];
+ this.selected = null;
+ this.arActive = false;
+ this.mediaStream = null;
+ this.arTransitioning = false;
+ this.xrSession = null;
+ this.estimatedLight = null;
+ /** 'webxr' | 'quicklook' | 'sceneviewer' | 'none', resolved at boot. */
+ this.arMode = 'none';
+ /** True while the device's own AR viewer has the stage we stood down for. */
+ this._cameraYielded = false;
+ this._cameraWasOn = false;
+ this._onArReturn = null;
+ this._nativeArBusy = false;
+ /** The hand-off the AR sheet's button will fire, once it is prepared. */
+ this._arHandoff = null;
+ this._arTarget = null;
+ /** Bumped on every sheet open and target change so a slow, stale
+ * conversion can never enable the button for the wrong model. */
+ this._arToken = 0;
+ this._arWarmTimer = null;
+ /** Set when a conversion failed and the sheet's button is a retry. */
+ this._arRetry = null;
+ /** USDZ cache keys this studio created, so destroy() frees only its own. */
+ this._arKeys = new Set();
+ this.arTrackW = 0;
+ this.arTrackH = 0;
+
+ this._statusTimer = null;
+ this._armed = null;
+ this._templates = new Map();
+ this._templatesReady = new Map();
+ this._trayCache = new Map();
+ this._trayTab = this.sources[0]?.id || 'link';
+ this._loadQueue = createLoadQueue({ run: (src) => sharedGLTFLoader().loadAsync(src), maxActive: 3 });
+ this._maxPlacements = Math.min(Number(this.config.maxPlacements) || MAX_PLACEMENTS, MAX_PLACEMENTS);
+
+ this.net = null;
+ this.roomCode = '';
+ this._netModels = new Map();
+ this._presence = { count: 1, names: [] };
+ this._roomSynced = false;
+ this._roomHeartbeat = null;
+
+ this.forge = this.config.generate?.enabled === false ? null : createForgeClient({
+ endpoint: this.config.generate.endpoint,
+ kind: this.config.generate.kind,
+ tier: this.config.generate.tier,
+ timeoutMs: this.config.generate.timeoutMs,
+ pollMs: this.config.generate.pollMs,
+ headers: this.config.generate.headers,
+ });
+ this._forgeSeq = 0;
+ this._forgeBusy = false;
+
+ this.gyroBase = null;
+ this._devAlpha = 0;
+ this._devBeta = 90;
+ this._devGamma = 0;
+ this._absoluteOrientation = false;
+ this._raycaster = new Raycaster();
+ this._ndc = new Vector2();
+ this._pointer = null;
+ this._userLooked = false;
+ this._pinch = createPinchState();
+ this._pinchEndedAt = -Infinity;
+ this._twist = null;
+ this._rafId = null;
+ this._prevT = 0;
+ this._lightTimer = null;
+ this._roomTint = new Color();
+ this._lightProbe = makeLightProbe();
+ this._recentKey = `${this.config.persistKey}:recent`;
+ this.config.recentKey = this._recentKey;
+ }
+
+ // ── Wiring ────────────────────────────────────────────────────────────────
+
+ _wireUI() {
+ const u = this.ui;
+ const bind = (node, type, fn, opts) => {
+ if (!node) return;
+ node.addEventListener(type, fn, opts);
+ };
+
+ bind(u.cameraBtn, 'click', () => {
+ if (this.arTransitioning || this.xrSession) return;
+ if (this.arActive) {
+ this._stopCamera();
+ this._setStatus('Camera off: preview mode.');
+ } else {
+ this._startCamera();
+ }
+ });
+ if (!navigator.mediaDevices?.getUserMedia && u.cameraBtn) {
+ u.cameraBtn.disabled = true;
+ u.cameraBtn.setAttribute('aria-disabled', 'true');
+ u.cameraBtn.title = 'This browser cannot open a camera';
+ }
+
+ bind(u.xrBtn, 'click', () => this._enterAR());
+ bind(u.addBtn, 'click', () => (u.tray.hidden ? this._openTray() : this._closeTray()));
+ bind(u.trayClose, 'click', () => this._closeTray());
+ bind(u.tray, 'click', (e) => { if (e.target === u.tray) this._closeTray(); });
+ bind(u.emptyAdd, 'click', () => this._openTray());
+ bind(u.emptyCamera, 'click', () => this._startCamera());
+ bind(u.emptyForge, 'click', () => u.forgeInput?.focus());
+
+ bind(u.forgeForm, 'submit', (e) => {
+ e.preventDefault();
+ this._startForge(u.forgeInput?.value);
+ });
+
+ bind(u.clearBtn, 'click', () => this._clearWithUndo());
+ bind(u.photoBtn, 'click', () => this._capturePhoto());
+ bind(u.qrBtn, 'click', () => this._openQr());
+ bind(u.qrClose, 'click', () => this._closeQr());
+ bind(u.qrModal, 'click', (e) => { if (e.target === u.qrModal) this._closeQr(); });
+
+ bind(u.arClose, 'click', () => this._closeArSheet());
+ bind(u.arModal, 'click', (e) => { if (e.target === u.arModal) this._closeArSheet(); });
+ bind(u.arGo, 'click', () => this._onArGo());
+ bind(u.arXr, 'click', () => { this._closeArSheet(); this._toggleXR(); });
+ bind(u.arQr, 'click', () => { this._closeArSheet(); this._openQr(); });
+ bind(u.arPicker, 'click', (e) => {
+ const chip = e.target.closest('[data-ar-id]');
+ if (!chip) return;
+ const next = this.placements.find((pl) => pl.id === chip.dataset.arId);
+ if (next) this._showArTarget(next);
+ });
+
+ bind(u.selbar, 'click', (e) => this._onSelbarClick(e));
+
+ bind(u.roomBtn, 'click', () => this._openRoomModal());
+ bind(u.roomClose, 'click', () => this._closeRoomModal());
+ bind(u.roomModal, 'click', (e) => { if (e.target === u.roomModal) this._closeRoomModal(); });
+ bind(u.roomCreate, 'click', () => this._createRoomFromUI());
+ bind(u.roomJoinForm, 'submit', (e) => {
+ e.preventDefault();
+ this._joinRoomFromUI();
+ });
+ bind(u.roomCopy, 'click', () => this._copyRoomInvite());
+ bind(u.roomLeave, 'click', () => {
+ this._leaveRoom();
+ this._renderRoomModal();
+ });
+
+ // Canvas gestures
+ const c = u.canvas;
+ bind(c, 'pointerdown', (e) => this._onPointerDown(e));
+ bind(c, 'pointermove', (e) => this._onPointerMove(e));
+ bind(c, 'pointerup', (e) => this._onPointerUp(e));
+ bind(c, 'pointercancel', () => { this._pointer = null; });
+ bind(c, 'touchstart', (e) => this._onTouchStart(e), { passive: true });
+ bind(c, 'touchmove', (e) => this._onTouchMove(e), { passive: true });
+ bind(c, 'touchend', () => this._onTouchEnd(), { passive: true });
+
+ this._onKeyDown = this._onKeyDown.bind(this);
+ document.addEventListener('keydown', this._onKeyDown);
+
+ this._onOrientationAbsolute = (e) => { this._absoluteOrientation = true; this._onDeviceOrientation(e); };
+ this._onOrientation = (e) => { if (!this._absoluteOrientation) this._onDeviceOrientation(e); };
+ window.addEventListener('deviceorientationabsolute', this._onOrientationAbsolute, true);
+ window.addEventListener('deviceorientation', this._onOrientation, true);
+
+ this._onResize = () => this._resize();
+ window.addEventListener('resize', this._onResize);
+ this._onPageHide = () => {
+ this._stopCamera();
+ this.xrSession?.end();
+ this.net?.destroy();
+ };
+ window.addEventListener('pagehide', this._onPageHide);
+
+ // The host element can resize without the window doing so (a flex layout,
+ // a drawer opening), and a stale drawing buffer looks like a broken canvas.
+ if (typeof ResizeObserver !== 'undefined') {
+ this._ro = new ResizeObserver(() => this._resize());
+ this._ro.observe(u.root);
+ }
+
+ this._wireTrayTabs();
+ }
+
+ _boot() {
+ this._resize();
+ this._updateCount();
+ this._updateRoomButton();
+ this._startLoop();
+
+ // One AR button, labelled for what this device will actually do. An iPhone
+ // has no WebXR, but it has ARKit through Quick Look, and offering it the
+ // camera-passthrough approximation instead would be strictly worse: the
+ // native viewer gets real plane detection, real scale and real occlusion.
+ arCapability().then((cap) => {
+ this.arMode = cap;
+ const btn = this.ui.xrBtn;
+ if (!btn || cap === 'none') return;
+ btn.hidden = false;
+ const label = btn.querySelector('.ars-ar-label');
+ if (cap === 'webxr') {
+ if (label) label.textContent = 'Immersive AR';
+ btn.setAttribute('aria-label', 'Enter immersive augmented reality and place models on real surfaces');
+ } else {
+ if (label) label.textContent = 'Place in your space';
+ btn.setAttribute('aria-label', 'Open this in your device AR viewer and place it in your real space');
+ }
+ });
+ // Desktop leads with the QR hand-off; a phone is already the target device.
+ const coarse = window.matchMedia?.('(pointer: coarse)').matches;
+ if (!coarse && this.ui.qrBtn) this.ui.qrBtn.hidden = false;
+
+ const bootRoom = normalizeRoomCode(this.config.urlRoom || '');
+ this._restoreScene({ skipLocal: !!bootRoom }).then(() => {
+ if (bootRoom) this._joinRoom(bootRoom);
+ if (this.config.urlPrompt && this.config.urlPrompt.length >= 3 && this.ui.forgeInput) {
+ this.ui.forgeInput.value = this.config.urlPrompt;
+ this._startForge(this.config.urlPrompt);
+ }
+ });
+ }
+
+ // ── Status + counters ─────────────────────────────────────────────────────
+
+ _setStatus(message, { warn = false, sticky = false, actionLabel = '', onAction = null } = {}) {
+ const node = this.ui.status;
+ if (!node) return;
+ clearTimeout(this._statusTimer);
+ node.textContent = '';
+ if (!message) {
+ node.hidden = true;
+ return;
+ }
+ node.hidden = false;
+ node.classList.toggle('is-warn', warn);
+ node.appendChild(el('span', { text: message }));
+ if (actionLabel && onAction) {
+ node.appendChild(el('button', {
+ type: 'button', class: 'ars-status-action', text: actionLabel,
+ onclick: () => { this._setStatus(null); onAction(); },
+ }));
+ }
+ if (!sticky) this._statusTimer = setTimeout(() => { node.hidden = true; }, 5200);
+ }
+
+ _updateCount() {
+ const n = this.placements.length;
+ const { count, clearBtn, empty, photoBtn } = this.ui;
+ if (count) {
+ if (this.net && this.net.status === 'online' && this._presence.count > 1) {
+ count.textContent = `${this._presence.count} here · ${n} ${n === 1 ? 'model' : 'models'}`;
+ count.hidden = false;
+ } else {
+ count.textContent = n === 1 ? '1 model' : `${n} models`;
+ count.hidden = n === 0;
+ }
+ }
+ if (clearBtn) clearBtn.hidden = n === 0;
+ if (empty) empty.hidden = n > 0;
+ if (photoBtn) photoBtn.disabled = n === 0;
+ }
+
+ // ── Placements ────────────────────────────────────────────────────────────
+
+ // A placement's LOGICAL scale: the size the user chose, independent of the
+ // spawn-in animation. While a model eases in, group.scale is a fraction of the
+ // target, and persisting that would clamp it to the minimum on the next load.
+ _logicalScale(p) {
+ if (p.spawnT < 1) return p.group.userData._targetScale ?? 1;
+ return p.group.scale.x;
+ }
+
+ _saveScene() {
+ if (this.config.persist === false) return;
+ try {
+ localStorage.setItem(this.config.persistKey, serializeScene(
+ this.placements.filter((p) => this._isMine(p)).map((p) => ({
+ src: p.src,
+ title: p.title,
+ x: p.group.position.x,
+ z: p.group.position.z,
+ yaw: p.yaw,
+ scale: this._logicalScale(p),
+ })),
+ ));
+ } catch {
+ // Storage full or blocked: the live scene is unaffected.
+ }
+ }
+
+ _select(p) {
+ this.selected = p;
+ const { selbar, selName } = this.ui;
+ if (!selbar) return;
+ if (!p) {
+ selbar.hidden = true;
+ this.selRing.visible = false;
+ this._emit('select', { placement: null });
+ return;
+ }
+ selbar.hidden = false;
+ if (selName) selName.textContent = p.title || 'Model';
+ this.selRing.visible = !this.xrSession;
+ this._positionSelRing();
+ this._warmQuickLook();
+ this._emit('select', { placement: publicPlacement(p, this) });
+ }
+
+ _positionSelRing() {
+ const p = this.selected;
+ if (!p) return;
+ this.selRing.position.set(p.group.position.x, p.group.position.y + 0.006, p.group.position.z);
+ const r = Math.max(0.24, p.baseRadius * p.group.scale.x * 1.15);
+ this.selRing.scale.setScalar(r / 0.34);
+ }
+
+ // One load per GLB source no matter how many copies are placed.
+ _loadTemplate(src) {
+ let tpl = this._templates.get(src);
+ if (!tpl) {
+ tpl = this._loadQueue.request(src).then((gltf) => {
+ let skinned = false;
+ gltf.scene.traverse((o) => { if (o.isSkinnedMesh) skinned = true; });
+ const box = new Box3().setFromObject(gltf.scene);
+ const fit = fitTransform({
+ min: { x: box.min.x, y: box.min.y, z: box.min.z },
+ max: { x: box.max.x, y: box.max.y, z: box.max.z },
+ }, { skinned });
+ const radius = Math.max((box.max.x - box.min.x) * fit.scale, (box.max.z - box.min.z) * fit.scale) / 2;
+ const height = (box.max.y - box.min.y) * fit.scale;
+ return {
+ gltf, skinned, fit,
+ radius: Number.isFinite(radius) ? radius : 0.3,
+ height: Number.isFinite(height) ? height : 0.75,
+ };
+ });
+ this._templates.set(src, tpl);
+ tpl.then((t) => this._templatesReady.set(src, t))
+ .catch(() => this._templates.delete(src)); // a failed load stays retryable
+ }
+ return tpl;
+ }
+
+ // Cloned per placement so ten copies of one crate are ten independent models.
+ // SkeletonUtils handles skinned characters; a plain .clone() breaks bone binding.
+ _instantiate(tpl, src) {
+ const inner = cloneSkinnedScene(tpl.gltf.scene);
+ inner.scale.setScalar(tpl.fit.scale);
+ inner.position.y = tpl.fit.yOffset;
+ const group = new Group();
+ group.add(inner);
+ let mixer = null;
+ if (tpl.gltf.animations?.length) {
+ mixer = new AnimationMixer(inner);
+ mixer.clipAction(tpl.gltf.animations[0]).play();
+ }
+ // A humanoid with no baked clip gets the universal idle retargeted onto its
+ // own rig: never a bind-pose statue. Best-effort and async: props and
+ // undriveable rigs resolve null and stay static.
+ let idlePromise = null;
+ if (!mixer && tpl.skinned && this.config.animations?.enabled !== false) {
+ idlePromise = mountIdle(inner, {
+ manifestUrl: this.config.animations?.manifestUrl,
+ clip: this.config.animations?.clip,
+ sourceUrl: src,
+ }).catch(() => null);
+ }
+ return { group, mixer, idlePromise };
+ }
+
+ _makeShadow(radius) {
+ if (!this.shadowTex) return null;
+ const d = Math.max(0.4, radius * 2.4);
+ const mesh = new Mesh(
+ new PlaneGeometry(d, d).rotateX(-Math.PI / 2),
+ new MeshBasicMaterial({ map: this.shadowTex, transparent: true, opacity: 0.85, depthWrite: false }),
+ );
+ mesh.renderOrder = 1;
+ return mesh;
+ }
+
+ // Spread same-spot spawns into a small ring so "add, add, add" reads as a
+ // line-up instead of a z-fighting pile.
+ _nudgeSpawn(pt) {
+ let { x, z } = pt;
+ for (let attempt = 0; attempt < 8; attempt++) {
+ const clash = this.placements.some((p) => Math.hypot(p.group.position.x - x, p.group.position.z - z) < 0.45);
+ if (!clash) break;
+ const a = attempt * 2.399963; // golden angle
+ x = pt.x + Math.cos(a) * 0.55 * (1 + attempt * 0.18);
+ z = pt.z + Math.sin(a) * 0.55 * (1 + attempt * 0.18);
+ }
+ return { x, z };
+ }
+
+ async _addModel({ src, title = '', poster = '' } = {}, {
+ x = null, z = null, yaw = null, scale = null, announce = true, persist = true,
+ remote = false, netId = null, ownerId = null,
+ } = {}) {
+ const url = normalizeGlbUrl(src);
+ if (!url) {
+ this._setStatus('That link is not a loadable https GLB.', { warn: true });
+ return null;
+ }
+ if (this.placements.length >= this._maxPlacements) {
+ this._setStatus(`Scene is full (${this._maxPlacements} models). Remove one to add more.`, { warn: true });
+ return null;
+ }
+ if (announce) this._setStatus(`Loading ${title || 'model'}…`, { sticky: true });
+
+ let tpl;
+ try {
+ tpl = await this._loadTemplate(url);
+ } catch (err) {
+ log.warn('model load failed', url, err);
+ this._setStatus(`Couldn't load ${title || 'that model'}: the file may be gone or blocked by CORS.`, {
+ warn: true, actionLabel: 'Retry', onAction: () => this._addModel({ src: url, title }),
+ });
+ return null;
+ }
+
+ const { group, mixer, idlePromise } = this._instantiate(tpl, url);
+ let px = x;
+ let pz = z;
+ if (px === null || pz === null) {
+ // Tall models land further back so they do not fill the frame the moment
+ // they appear.
+ const dist = Math.max(SPAWN_DISTANCE_M, (tpl.height || 0) * 1.15);
+ const fwd = this.camera.getWorldDirection(new Vector3());
+ const spot = this._nudgeSpawn(spawnPointInFront(this.camera.position, fwd, dist));
+ px = spot.x;
+ pz = spot.z;
+ }
+ group.position.set(px, 0, pz);
+ const yawV = yaw ?? Math.atan2(this.camera.position.x - px, this.camera.position.z - pz);
+ group.rotation.y = yawV;
+ if (scale) group.scale.setScalar(Math.min(PINCH_SCALE_MAX, Math.max(PINCH_SCALE_MIN, scale)));
+ this.scene.add(group);
+
+ const shadow = this._makeShadow(tpl.radius);
+ if (shadow) {
+ shadow.position.set(px, 0.004, pz);
+ shadow.scale.setScalar(group.scale.x);
+ shadow.visible = !this.xrSession; // the XR session draws its own anchored shadows
+ this.scene.add(shadow);
+ }
+
+ const placement = {
+ id: `p-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
+ src: url,
+ title: String(title || '').slice(0, 160),
+ poster,
+ group,
+ shadow,
+ mixer,
+ idle: null,
+ yaw: yawV,
+ baseRadius: tpl.radius,
+ height: tpl.height || 0,
+ spawnT: this.reducedMotion ? 1 : 0,
+ netId: netId || null,
+ ownerId: remote ? ownerId : null,
+ remote,
+ _lastNetSend: 0,
+ };
+ idlePromise?.then((mgr) => {
+ if (!mgr) return;
+ // Removed before the clip arrived: release the manager rather than leak it.
+ if (this.placements.includes(placement)) placement.idle = mgr;
+ else mgr.detach();
+ });
+ group.userData._targetScale = group.scale.x;
+ if (!this.reducedMotion) group.scale.setScalar(0.001);
+
+ this.placements.push(placement);
+ if (placement.netId) this._netModels.set(placement.netId, placement);
+ if (!remote) this._armed = { src: url, title: placement.title };
+ this._updateCount();
+ if (!remote) this._select(placement);
+ if (persist) this._saveScene();
+
+ // Broadcast a locally-added model to the shared room exactly once.
+ if (!remote && this.net && this.net.status === 'online') {
+ const wireId = `m${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`.slice(0, 40);
+ placement.netId = wireId;
+ placement.ownerId = this.clientId;
+ this._netModels.set(wireId, placement);
+ this.net.spawn(this._placementWire(placement, wireId));
+ }
+
+ if (announce) {
+ this._setStatus(remote
+ ? `${title || 'A model'} was added by someone in the room.`
+ : 'Placed. Drag to move, pinch to resize, twist to rotate.');
+ }
+ if (!remote) this._framePreview();
+ this._emit('add', { placement: publicPlacement(placement, this), remote });
+ return placement;
+ }
+
+ _removePlacement(p, { persist = true, broadcast = true } = {}) {
+ const i = this.placements.indexOf(p);
+ if (i === -1) return;
+ this.placements.splice(i, 1);
+ if (p.netId) {
+ this._netModels.delete(p.netId);
+ if (broadcast && this.net?.status === 'online' && this._isMine(p)) this.net.remove(p.netId);
+ }
+ p.idle?.detach();
+ p.idle = null;
+ this.xrSession?.release(p.group);
+ this.scene.remove(p.group);
+ if (p.shadow) {
+ this.scene.remove(p.shadow);
+ p.shadow.geometry?.dispose();
+ p.shadow.material?.dispose();
+ }
+ // Geometry and materials belong to the shared template: other copies still
+ // use them, so only the per-placement shadow above is disposed.
+ if (this.selected === p) this._select(this.placements[this.placements.length - 1] ?? null);
+ releaseQuickLook(this._arCacheKey(p));
+ this._arKeys.delete(this._arCacheKey(p));
+ // The sheet may be listing a model that no longer exists.
+ if (this.ui.arModal && !this.ui.arModal.hidden) {
+ this._showArTarget(this._arTarget === p ? this._arDefaultTarget() : this._arTarget);
+ }
+ this._updateCount();
+ if (persist) this._saveScene();
+ this._emit('remove', { src: p.src, title: p.title });
+ }
+
+ _clearWithUndo() {
+ if (!this.placements.length) return;
+ const items = this.getScene();
+ for (const p of [...this.placements]) this._removePlacement(p, { persist: false });
+ this._saveScene();
+ this._emit('clear', { items });
+ this._setStatus('Scene cleared.', {
+ actionLabel: 'Undo',
+ onAction: async () => {
+ for (const it of items) {
+ await this._addModel({ src: it.src, title: it.title }, {
+ x: it.x, z: it.z, yaw: it.yaw, scale: it.scale, announce: false,
+ });
+ }
+ },
+ });
+ }
+
+ _onSelbarClick(e) {
+ const btn = e.target.closest('[data-act]');
+ const p = this.selected;
+ if (!btn || !p) return;
+ const act = btn.dataset.act;
+ if ((act === 'rotate' || act === 'remove') && !this._isMine(p)) {
+ this._setStatus('That model belongs to someone else in the room.', { warn: true });
+ return;
+ }
+ if (act === 'rotate') {
+ p.yaw += Math.PI / 4;
+ p.group.rotation.y = p.yaw;
+ p._lastNetSend = 0;
+ this._netBroadcastTransform(p);
+ this._saveScene();
+ } else if (act === 'duplicate') {
+ this._addModel({ src: p.src, title: p.title }, { yaw: p.yaw, scale: this._logicalScale(p) });
+ } else if (act === 'remove') {
+ this._removePlacement(p);
+ this._setStatus('Removed.', {
+ actionLabel: 'Undo',
+ onAction: () => this._addModel({ src: p.src, title: p.title }, {
+ x: p.group.position.x, z: p.group.position.z, yaw: p.yaw, scale: this._logicalScale(p),
+ }),
+ });
+ }
+ }
+
+ // ── Restore + deep links ──────────────────────────────────────────────────
+
+ async _restoreScene({ skipLocal = false } = {}) {
+ // A `#s=` hash is a full shared arrangement: it opens like a document,
+ // replacing the working scene rather than merging into it.
+ const hashParams = new URLSearchParams(String(location.hash || '').replace(/^#/, ''));
+ const shared = skipLocal ? [] : sceneFromHashParam(hashParams.get('s'));
+
+ let items = shared;
+ if (!items.length && !skipLocal && this.config.persist !== false) {
+ try { items = deserializeScene(localStorage.getItem(this.config.persistKey)); } catch { items = []; }
+ }
+ for (const it of items) {
+ await this._addModel({ src: it.src, title: it.title }, {
+ x: it.x, z: it.z, yaw: it.yaw, scale: it.scale, announce: false, persist: false,
+ });
+ }
+ // Deep-linked models land in front of the camera, skipping any already
+ // restored at an arranged spot.
+ const have = new Set(this.placements.map((p) => p.src));
+ for (const it of this.config.urlModels || []) {
+ if (have.has(it.src)) continue;
+ await this._addModel(it, { announce: false });
+ }
+ if (this.placements.length) {
+ this._select(this.placements[this.placements.length - 1]);
+ if (shared.length) this._setStatus('Shared scene loaded, exactly as arranged. Clear to start fresh.');
+ else this._setStatus(this.config.urlModels?.length ? 'Models loaded: turn on the camera to see them in your space.' : 'Your scene is back.');
+ }
+ this._saveScene();
+ }
+
+ // ── Camera passthrough ────────────────────────────────────────────────────
+
+ _applyCameraFov() {
+ const track = this.mediaStream?.getVideoTracks?.()[0];
+ if (track) {
+ const s = track.getSettings?.() ?? {};
+ if (Number.isFinite(s.width) && s.width > 0) this.arTrackW = s.width;
+ if (Number.isFinite(s.height) && s.height > 0) this.arTrackH = s.height;
+ }
+ if (!this.arActive || !(this.arTrackW > 0) || !(this.arTrackH > 0)) return;
+ const { width, height } = this._viewportSize();
+ this.camera.fov = deriveVerticalFovDeg({
+ trackWidth: this.arTrackW,
+ trackHeight: this.arTrackH,
+ viewWidth: width,
+ viewHeight: height,
+ diagFovDeg: DEFAULT_DIAG_FOV_DEG,
+ });
+ this.camera.updateProjectionMatrix();
+ }
+
+ // Passthrough has no lighting-estimation API, so the room is read from the
+ // video itself: mean brightness drives intensity, mean colour drives a gentle
+ // white balance. A model in a dim bedroom stops glowing like a studio shot.
+ _sampleCameraLight() {
+ const probe = this._lightProbe;
+ const video = this.ui.video;
+ if (!this.arActive || !probe?.ctx || !video?.videoWidth) return;
+ let data;
+ try {
+ probe.ctx.drawImage(video, 0, 0, 16, 16);
+ data = probe.ctx.getImageData(0, 0, 16, 16).data;
+ } catch {
+ return; // frame not readable yet
+ }
+ const { intensity, tint } = roomLightFromPixels(data);
+ this.hemi.intensity += (intensity * HEMI_BASE - this.hemi.intensity) * 0.4;
+ this.sun.intensity += (intensity * SUN_BASE - this.sun.intensity) * 0.4;
+ this._roomTint.setRGB(tint.r, tint.g, tint.b);
+ this.hemi.color.lerp(this._roomTint, 0.4);
+ this.sun.color.lerp(this._roomTint, 0.4);
+ }
+
+ _startLightMatching() {
+ if (this._lightTimer || !this._lightProbe) return;
+ this._lightTimer = setInterval(() => this._sampleCameraLight(), 2000);
+ this._sampleCameraLight();
+ }
+
+ _stopLightMatching() {
+ clearInterval(this._lightTimer);
+ this._lightTimer = null;
+ this.hemi.intensity = HEMI_BASE;
+ this.sun.intensity = SUN_BASE;
+ this.hemi.color.setHex(0xffffff);
+ this.sun.color.setHex(0xffffff);
+ }
+
+ async _startCamera() {
+ if (this.arTransitioning || this.arActive || this.xrSession) return;
+ if (!navigator.mediaDevices?.getUserMedia) {
+ this._setStatus('This browser cannot open the camera: the 3D preview still works.', { warn: true });
+ return;
+ }
+ this.arTransitioning = true;
+ try {
+ this._setStatus('Starting camera…', { sticky: true });
+ try {
+ this.mediaStream = await navigator.mediaDevices.getUserMedia({
+ video: { facingMode: { ideal: 'environment' } },
+ audio: false,
+ });
+ } catch (err) {
+ if (err?.name === 'NotAllowedError') {
+ this._setStatus('Camera permission is blocked. Allow it in your browser settings, then try again.', {
+ warn: true, sticky: true, actionLabel: 'Try again', onAction: () => this._startCamera(),
+ });
+ } else {
+ this._setStatus(`The camera did not start (${err?.message ?? err}).`, {
+ warn: true, actionLabel: 'Try again', onAction: () => this._startCamera(),
+ });
+ }
+ return;
+ }
+ const { video, root, cameraBtn } = this.ui;
+ if (video) video.srcObject = this.mediaStream;
+ this.arActive = true;
+ root.classList.add('is-ar');
+ cameraBtn?.classList.add('is-active');
+ cameraBtn?.setAttribute('aria-pressed', 'true');
+ this.grid.visible = false;
+ this.scene.fog = null;
+ this._userLooked = true;
+ video?.play?.().catch(() => { /* autoplay policy: the srcObject still renders */ });
+ this._applyCameraFov();
+ this._startLightMatching();
+ await this._startGyro();
+ // Be honest about what this view is. Passthrough is a phone's gyroscope
+ // over a camera feed: it turns with you, but it has no plane detection
+ // and no positional tracking, so walking around does not hold a model
+ // to a spot on the real floor. Reading that as broken tracking is
+ // exactly the wrong conclusion to leave someone with when the device
+ // has a real AR viewer one tap away.
+ if (this.arMode === 'quicklook' || this.arMode === 'sceneviewer') {
+ this._setStatus('Camera on. This preview turns with your phone; to lock a model to your real floor, place it in AR.', {
+ actionLabel: 'Place in AR', onAction: () => this._openArSheet(),
+ });
+ } else {
+ this._setStatus('Camera on: your models are in the room. Look around.');
+ }
+ this._emit('camera', { active: true });
+ } finally {
+ this.arTransitioning = false;
+ }
+ }
+
+ _stopCamera() {
+ if (this.mediaStream) {
+ this.mediaStream.getTracks().forEach((t) => { try { t.stop(); } catch { /* already stopped */ } });
+ this.mediaStream = null;
+ }
+ const { video, root, cameraBtn } = this.ui;
+ if (video) video.srcObject = null;
+ const was = this.arActive;
+ this.arActive = false;
+ this._stopLightMatching();
+ root?.classList.remove('is-ar');
+ cameraBtn?.classList.remove('is-active');
+ cameraBtn?.setAttribute('aria-pressed', 'false');
+ this.grid.visible = !this.xrSession;
+ if (!this.xrSession) this.scene.fog = this._fog;
+ this.camera.fov = 58;
+ this.camera.updateProjectionMatrix();
+ this.gyroBase = null;
+ this._userLooked = false;
+ this.arTrackW = 0;
+ this.arTrackH = 0;
+ if (was) this._emit('camera', { active: false });
+ this._framePreview();
+ }
+
+ /**
+ * Hand the rear camera to the device's own AR viewer, and take it back after.
+ *
+ * The camera is a single-client resource on a phone. Leave the page's
+ * `getUserMedia` stream running and Quick Look starts ARKit against a camera
+ * another process is already holding: the model appears, and then world
+ * tracking and plane detection never converge, so it drifts with the phone
+ * instead of settling on the floor. It looks exactly like a broken anchor and
+ * it is not one. The immersive WebXR path has always released the camera for
+ * the same reason; the native hand-off has to as well.
+ *
+ * Synchronous on purpose: it runs in the same tick as the tap that opens the
+ * viewer, and an `await` in front of it costs the user gesture Safari needs.
+ */
+ _yieldCameraToNativeAr() {
+ if (this._cameraYielded) return;
+ this._cameraYielded = true;
+ this._cameraWasOn = this.arActive;
+ this._stopCamera();
+ // Nothing on this page is visible under the AR viewer, and a WebGL loop
+ // still running at 60fps behind it is competing with ARKit for the same
+ // GPU and the same thermal budget on a device that is about to do plane
+ // detection. Stop drawing until the person comes back.
+ this._stopLoop();
+ // Quick Look presents over the page rather than navigating away, so the
+ // return is a visibility change, not a load. `focus` is the backstop for
+ // the iOS versions that never mark the page hidden underneath it.
+ this._onArReturn = () => {
+ if (typeof document !== 'undefined' && document.visibilityState !== 'visible') return;
+ this._reclaimCameraAfterNativeAr();
+ };
+ document.addEventListener('visibilitychange', this._onArReturn);
+ window.addEventListener('focus', this._onArReturn);
+ }
+
+ /** Restart the passthrough the person had running before AR took the camera. */
+ _reclaimCameraAfterNativeAr() {
+ if (!this._cameraYielded) return;
+ this._cameraYielded = false;
+ if (this._onArReturn) {
+ document.removeEventListener('visibilitychange', this._onArReturn);
+ window.removeEventListener('focus', this._onArReturn);
+ this._onArReturn = null;
+ }
+ if (this._destroyed || this.xrSession) return;
+ this._startLoop();
+ if (this.arActive || !this._cameraWasOn) return;
+ this._cameraWasOn = false;
+ // Permission is already granted for this page, so this normally resolves
+ // without a prompt. When a browser insists on a fresh gesture, _startCamera
+ // puts a "Try again" action in the status line rather than failing silently.
+ this._startCamera().catch((err) => log.warn('camera did not come back after AR', err));
+ }
+
+ _screenAngle() {
+ try {
+ const a = screen.orientation?.angle;
+ if (Number.isFinite(a)) return a;
+ } catch { /* older browsers */ }
+ return Number(window.orientation) || 0;
+ }
+
+ _onDeviceOrientation(e) {
+ if (isFiniteReading(e.alpha, e.beta)) {
+ this._devAlpha = e.alpha;
+ this._devBeta = e.beta;
+ if (Number.isFinite(e.gamma)) this._devGamma = e.gamma;
+ }
+ if (!this.arActive || !this.gyroBase) return;
+ const b = screenPitchDeg(this._devBeta, this._devGamma, this._screenAngle());
+ const nextYaw = resolveLockYaw({
+ useAbsolute: false,
+ prevYaw: this.cameraYaw,
+ alpha: this._devAlpha,
+ baseAlpha: this.gyroBase.alpha,
+ baseYaw: this.gyroBase.yaw,
+ compassHeading: null,
+ });
+ const nextPitch = clampPitch(this.gyroBase.pitch - (b - this.gyroBase.beta) * (Math.PI / 180), PITCH_MIN, PITCH_MAX);
+ if (Number.isFinite(nextYaw)) this.cameraYaw = nextYaw;
+ if (Number.isFinite(nextPitch)) this.cameraPitch = nextPitch;
+ }
+
+ async _startGyro() {
+ // iOS 13+ gates DeviceOrientationEvent behind a user-gesture permission; the
+ // camera tap we are inside satisfies it.
+ try {
+ if (typeof DeviceOrientationEvent !== 'undefined' && typeof DeviceOrientationEvent.requestPermission === 'function') {
+ const state = await DeviceOrientationEvent.requestPermission();
+ if (state !== 'granted') {
+ this._setStatus('Motion access is off: drag to look around instead.', { warn: true });
+ return;
+ }
+ }
+ } catch {
+ return; // declined prompt: drag-look still works
+ }
+ this.gyroBase = {
+ alpha: this._devAlpha,
+ beta: screenPitchDeg(this._devBeta, this._devGamma, this._screenAngle()),
+ yaw: this.cameraYaw,
+ pitch: this.cameraPitch,
+ };
+ }
+ // ── Pointer + touch gestures (XR has its own) ─────────────────────────────
+
+ _viewportSize() {
+ const r = this.ui.root.getBoundingClientRect();
+ return {
+ width: Math.max(1, Math.round(r.width || window.innerWidth)),
+ height: Math.max(1, Math.round(r.height || window.innerHeight)),
+ left: r.left,
+ top: r.top,
+ };
+ }
+
+ _setNdc(clientX, clientY) {
+ const v = this._viewportSize();
+ this._ndc.set(((clientX - v.left) / v.width) * 2 - 1, -((clientY - v.top) / v.height) * 2 + 1);
+ }
+
+ _placementAt(clientX, clientY) {
+ if (!this.placements.length) return null;
+ this._setNdc(clientX, clientY);
+ this._raycaster.setFromCamera(this._ndc, this.camera);
+ const hits = this._raycaster.intersectObjects(this.placements.map((p) => p.group), true);
+ if (!hits.length) return null;
+ let obj = hits[0].object;
+ while (obj) {
+ const found = this.placements.find((p) => p.group === obj);
+ if (found) return found;
+ obj = obj.parent;
+ }
+ return null;
+ }
+
+ _floorPointAt(clientX, clientY) {
+ this._setNdc(clientX, clientY);
+ this._raycaster.setFromCamera(this._ndc, this.camera);
+ const hits = this._raycaster.intersectObject(this.rayPlane);
+ return hits.length ? hits[0].point : null;
+ }
+
+ _onPointerDown(e) {
+ if (this.xrSession) return;
+ if (this._pinch.active || performance.now() - this._pinchEndedAt < 350) return;
+ this._pointer = {
+ x: e.clientX,
+ y: e.clientY,
+ placement: this._placementAt(e.clientX, e.clientY),
+ lookYaw: this.cameraYaw,
+ lookPitch: this.cameraPitch,
+ moved: false,
+ };
+ }
+
+ _onPointerMove(e) {
+ const down = this._pointer;
+ if (!down || this.xrSession || this._pinch.active) return;
+ const dx = e.clientX - down.x;
+ const dy = e.clientY - down.y;
+ if (Math.hypot(dx, dy) > 6) down.moved = true;
+ if (!down.moved) return;
+
+ if (down.placement && this._isMine(down.placement)) {
+ // Drag a model along the floor.
+ const pt = this._floorPointAt(e.clientX, e.clientY);
+ if (!pt) return;
+ const p = down.placement;
+ p.group.position.x = pt.x;
+ p.group.position.z = pt.z;
+ p.shadow?.position.set(pt.x, 0.004, pt.z);
+ if (this.selected === p) this._positionSelRing();
+ this._netBroadcastTransform(p);
+ } else if (!down.placement && !(this.arActive && this.gyroBase)) {
+ // Drag-look, but only when the gyro is not already steering the view.
+ this._userLooked = true;
+ this.cameraYaw = down.lookYaw + dx * 0.0042;
+ this.cameraPitch = clampPitch(down.lookPitch + dy * 0.0032, PITCH_MIN, PITCH_MAX);
+ }
+ }
+
+ _onPointerUp(e) {
+ const down = this._pointer;
+ if (!down || this.xrSession) return;
+ const wasTap = !down.moved
+ && Math.hypot(e.clientX - down.x, e.clientY - down.y) <= 8
+ && !this._pinch.active
+ && performance.now() - this._pinchEndedAt >= 350;
+ if (wasTap) {
+ this._select(down.placement); // null deselects
+ } else if (down.placement && down.moved && this._isMine(down.placement)) {
+ down.placement._lastNetSend = 0; // force the settle broadcast through
+ this._netBroadcastTransform(down.placement);
+ this._saveScene();
+ this._setStatus(null);
+ }
+ this._pointer = null;
+ }
+
+ /** Two fingers: pinch resizes, twist rotates: on the selected (or last) model. */
+ _gestureTarget() {
+ const t = this.selected ?? this.placements[this.placements.length - 1] ?? null;
+ return t && this._isMine(t) ? t : null;
+ }
+
+ _onTouchStart(e) {
+ if (this.xrSession || e.touches.length !== 2) return;
+ const target = this._gestureTarget();
+ if (!target) return;
+ this._pointer = null; // the pair owns the gesture: no drag, no tap
+ pinchStart(this._pinch, touchDist(e.touches), target.group.scale.x);
+ this._twist = { startAngle: touchAngle(e.touches), baseYaw: target.yaw, placement: target };
+ }
+
+ _onTouchMove(e) {
+ if (this.xrSession || e.touches.length !== 2) return;
+ const target = this._twist?.placement;
+ if (!target) return;
+ const s = pinchMove(this._pinch, touchDist(e.touches));
+ if (s != null) {
+ target.group.scale.setScalar(s);
+ target.group.userData._targetScale = s;
+ target.shadow?.scale.setScalar(s);
+ if (this.selected === target) this._positionSelRing();
+ }
+ target.yaw = this._twist.baseYaw + twistDelta(this._twist.startAngle, touchAngle(e.touches));
+ target.group.rotation.y = target.yaw;
+ this._netBroadcastTransform(target);
+ }
+
+ _onTouchEnd() {
+ this._warmQuickLook();
+ const s = pinchEnd(this._pinch);
+ const target = this._twist?.placement;
+ if (s != null) {
+ this._pinchEndedAt = performance.now();
+ this._saveScene();
+ }
+ if (target) {
+ target._lastNetSend = 0;
+ this._netBroadcastTransform(target);
+ }
+ this._twist = null;
+ }
+
+ // ── Keyboard ──────────────────────────────────────────────────────────────
+ // Arrows nudge the selected model camera-relative (Shift for fine), R rotates,
+ // D duplicates, Delete removes, Escape closes whatever is open. The mouse
+ // never has to leave the scene.
+
+ _onKeyDown(e) {
+ if (this._destroyed) return;
+ if (!this.ui.root.isConnected) return;
+ if (e.target.closest?.('input, textarea, select')) {
+ if (e.key === 'Escape') e.target.blur();
+ return;
+ }
+ if (e.key === 'Escape') {
+ if (!this.ui.tray.hidden) this._closeTray();
+ else if (!this.ui.roomModal.hidden) this._closeRoomModal();
+ else if (!this.ui.arModal.hidden) this._closeArSheet();
+ else if (!this.ui.qrModal.hidden) this._closeQr();
+ else this._select(null);
+ return;
+ }
+ if (!this.ui.tray.hidden || !this.ui.qrModal.hidden || !this.ui.arModal.hidden
+ || !this.ui.roomModal.hidden || this.xrSession) return;
+ const p = this.selected;
+ if (!p) return;
+ const editable = this._isMine(p);
+
+ if (e.key.startsWith('Arrow')) {
+ if (!editable) return;
+ e.preventDefault();
+ const step = e.shiftKey ? 0.02 : 0.1;
+ const fwd = this.camera.getWorldDirection(new Vector3());
+ fwd.y = 0;
+ if (fwd.lengthSq() < 1e-6) fwd.set(0, 0, -1);
+ fwd.normalize();
+ const right = new Vector3(-fwd.z, 0, fwd.x);
+ const move = e.key === 'ArrowUp' ? fwd
+ : e.key === 'ArrowDown' ? fwd.negate()
+ : e.key === 'ArrowLeft' ? right.negate()
+ : right;
+ p.group.position.addScaledVector(move, step);
+ p.shadow?.position.set(p.group.position.x, 0.004, p.group.position.z);
+ this._positionSelRing();
+ this._netBroadcastTransform(p);
+ this._saveScene();
+ } else if (e.key === 'r' || e.key === 'R') {
+ if (!editable) return;
+ p.yaw += Math.PI / 4;
+ p.group.rotation.y = p.yaw;
+ p._lastNetSend = 0;
+ this._netBroadcastTransform(p);
+ this._saveScene();
+ } else if (e.key === 'd' || e.key === 'D') {
+ e.preventDefault();
+ this._addModel({ src: p.src, title: p.title }, { yaw: p.yaw, scale: this._logicalScale(p) });
+ } else if (e.key === 'Delete' || e.key === 'Backspace') {
+ if (!editable) return;
+ e.preventDefault();
+ this._removePlacement(p);
+ this._setStatus('Removed.', {
+ actionLabel: 'Undo',
+ onAction: () => this._addModel({ src: p.src, title: p.title }, {
+ x: p.group.position.x, z: p.group.position.z, yaw: p.yaw, scale: this._logicalScale(p),
+ }),
+ });
+ }
+ }
+
+ // ── Model tray ────────────────────────────────────────────────────────────
+
+ _wireTrayTabs() {
+ const strip = this.ui.trayTabs;
+ if (!strip) return;
+ for (const [i, source] of this.sources.entries()) {
+ const btn = el('button', {
+ type: 'button',
+ class: 'ars-tab',
+ role: 'tab',
+ id: `ars-tab-${i}-${source.id}`,
+ 'aria-selected': String(i === 0),
+ tabindex: i === 0 ? '0' : '-1',
+ 'data-tab': source.id,
+ text: source.label || source.id,
+ });
+ btn.addEventListener('click', () => this._setTrayTab(source.id));
+ strip.appendChild(btn);
+ }
+ // A role="tablist" owes the keyboard the arrow-key contract.
+ strip.addEventListener('keydown', (e) => {
+ const tabs = [...strip.querySelectorAll('.ars-tab')];
+ const i = tabs.indexOf(document.activeElement);
+ if (i === -1) return;
+ const last = tabs.length - 1;
+ const next = e.key === 'ArrowRight' ? (i === last ? 0 : i + 1)
+ : e.key === 'ArrowLeft' ? (i === 0 ? last : i - 1)
+ : e.key === 'Home' ? 0
+ : e.key === 'End' ? last
+ : -1;
+ if (next === -1) return;
+ e.preventDefault();
+ this._setTrayTab(tabs[next].dataset.tab);
+ tabs[next].focus();
+ });
+ }
+
+ _openTray(tab = this._trayTab) {
+ const { tray, addBtn, trayClose } = this.ui;
+ if (!tray) return;
+ this._lastFocus = document.activeElement;
+ tray.hidden = false;
+ addBtn?.setAttribute('aria-expanded', 'true');
+ this._setTrayTab(tab);
+ trayClose?.focus?.();
+ }
+
+ _closeTray() {
+ const { tray, addBtn } = this.ui;
+ if (!tray || tray.hidden) return;
+ const hadFocus = tray.contains(document.activeElement);
+ tray.hidden = true;
+ addBtn?.setAttribute('aria-expanded', 'false');
+ if (hadFocus) this._restoreFocus(addBtn);
+ }
+
+ // Closing a dialog must hand the keyboard back to whatever opened it; dropping
+ // focus on <body> strands a keyboard user at the top of the document.
+ _restoreFocus(fallback) {
+ const target = this._lastFocus && document.contains(this._lastFocus) && !this._lastFocus.hidden
+ ? this._lastFocus
+ : fallback;
+ target?.focus?.();
+ this._lastFocus = null;
+ }
+
+ _setTrayTab(tab) {
+ this._trayTab = tab;
+ const tabs = [...(this.ui.trayTabs?.querySelectorAll('.ars-tab') || [])];
+ for (const b of tabs) {
+ const on = b.dataset.tab === tab;
+ b.classList.toggle('is-active', on);
+ b.setAttribute('aria-selected', String(on));
+ b.tabIndex = on ? 0 : -1;
+ if (on) {
+ this.ui.trayBody?.setAttribute('aria-labelledby', b.id);
+ b.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
+ }
+ }
+ this._renderTray();
+ }
+
+ async _renderTray() {
+ const body = this.ui.trayBody;
+ if (!body) return;
+ const tab = this._trayTab;
+ const source = this.sources.find((s) => s.id === tab);
+ if (!source) return;
+ if (source.kind === 'link' || source.id === 'link') {
+ this._renderLinkTab(body);
+ return;
+ }
+
+ body.textContent = '';
+ body.appendChild(el('div', { class: 'ars-tray-loading' }, [
+ el('span', { class: 'ars-spinner', 'aria-hidden': 'true' }), 'Loading models…',
+ ]));
+
+ let items;
+ try {
+ // `live` sources (recents) change as you work, so they are never cached.
+ if (!source.live && this._trayCache.has(tab)) items = this._trayCache.get(tab);
+ else {
+ items = await source.list();
+ if (!source.live) this._trayCache.set(tab, items);
+ }
+ } catch (err) {
+ log.warn('source failed', tab, err);
+ if (this._trayTab !== tab) return;
+ body.textContent = '';
+ body.appendChild(el('div', { class: 'ars-tray-empty' }, [
+ el('p', { text: `Couldn't load ${source.label || 'these models'} right now.` }),
+ el('button', {
+ type: 'button', class: 'ars-btn', text: 'Retry',
+ onclick: () => { this._trayCache.delete(tab); this._renderTray(); },
+ }),
+ ]));
+ return;
+ }
+ if (this._trayTab !== tab) return;
+
+ if (!items.length) {
+ body.textContent = '';
+ body.appendChild(el('div', { class: 'ars-tray-empty' }, [
+ el('p', { text: source.emptyCopy || 'Nothing here yet.' }),
+ this.forge
+ ? el('button', {
+ type: 'button', class: 'ars-btn ars-btn-primary', text: 'Generate a model',
+ onclick: () => { this._closeTray(); this.ui.forgeInput?.focus(); },
+ })
+ : null,
+ ]));
+ return;
+ }
+ this._renderList(body, source, items);
+ }
+
+ _renderList(body, source, items) {
+ body.textContent = '';
+ const searchable = source.searchable ?? items.length > 24;
+ let shown = LIST_SLICE;
+ let search = null;
+
+ if (searchable) {
+ search = el('input', {
+ class: 'ars-search', type: 'search', autocomplete: 'off',
+ placeholder: `Search ${items.length} models…`,
+ 'aria-label': `Search ${source.label || 'models'}`,
+ });
+ body.appendChild(search);
+ }
+ if (source.hint) body.appendChild(el('p', { class: 'ars-hint', text: source.hint }));
+
+ const list = el('ul', { class: 'ars-item-list' });
+ const more = el('div', { class: 'ars-more' });
+ body.appendChild(list);
+ body.appendChild(more);
+
+ const paint = () => {
+ const q = (search?.value || '').trim().toLowerCase();
+ const matches = q ? items.filter((o) => (o.keywords || o.title || '').toLowerCase().includes(q)) : items;
+ list.textContent = '';
+ for (const item of matches.slice(0, shown)) list.appendChild(this._trayItem(item));
+ more.textContent = '';
+ if (matches.length > shown) {
+ const left = matches.length - shown;
+ more.appendChild(el('button', {
+ type: 'button', class: 'ars-btn',
+ text: `Show ${Math.min(LIST_SLICE, left)} more (${left} left)`,
+ onclick: () => { shown += LIST_SLICE; paint(); },
+ }));
+ } else if (!matches.length) {
+ more.appendChild(el('p', { class: 'ars-hint', text: 'Nothing matches that search.' }));
+ }
+ };
+ search?.addEventListener('input', () => { shown = LIST_SLICE; paint(); });
+ paint();
+ }
+
+ _trayItem(item) {
+ const label = item.title || 'Model';
+ const thumb = el('span', { class: 'ars-item-thumb' });
+ if (item.poster) {
+ const img = el('img', { src: item.poster, alt: '', loading: 'lazy', decoding: 'async' });
+ // A thumbnail that 404s would otherwise leave a broken-image glyph in the
+ // grid, which makes the whole tray look broken.
+ img.addEventListener('error', () => {
+ thumb.textContent = '';
+ thumb.appendChild(el('span', { class: 'ars-item-cube', 'aria-hidden': 'true', text: '◆' }));
+ }, { once: true });
+ thumb.appendChild(img);
+ } else {
+ thumb.appendChild(el('span', { class: 'ars-item-cube', 'aria-hidden': 'true', text: '◆' }));
+ }
+ const btn = el('button', {
+ type: 'button', class: 'ars-item-add',
+ title: item.title || '',
+ 'aria-label': `Add ${label} to your space`,
+ onclick: () => {
+ this._closeTray();
+ this._addModel({ src: item.src, title: label, poster: item.poster });
+ },
+ }, [
+ thumb,
+ el('span', { class: 'ars-item-title', text: label }),
+ el('span', { class: 'ars-item-cta', text: 'Add' }),
+ ]);
+ return el('li', { class: 'ars-item' }, [btn]);
+ }
+
+ _renderLinkTab(body) {
+ body.textContent = '';
+ const input = el('input', {
+ class: 'ars-search', type: 'url', inputmode: 'url', required: true,
+ placeholder: 'https://example.com/model.glb', 'aria-label': 'GLB model URL',
+ });
+ const form = el('form', {}, [
+ el('label', { class: 'ars-hint', for: '', text: 'Paste a link to any .glb model' }),
+ el('div', { class: 'ars-link-row' }, [input, el('button', { type: 'submit', class: 'ars-btn ars-btn-primary', text: 'Add' })]),
+ el('p', { class: 'ars-hint', text: 'Any https .glb works, as long as the host allows cross-origin requests.' }),
+ ]);
+ form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const url = normalizeGlbUrl(input.value);
+ if (!url) {
+ this._setStatus('That link is not a loadable https GLB.', { warn: true });
+ input.focus();
+ return;
+ }
+ this._closeTray();
+ this._addModel({ src: url, title: filenameLabel(url) });
+ });
+ body.appendChild(form);
+ }
+
+ // ── Generation ────────────────────────────────────────────────────────────
+
+ _forgeChip(state, label = '', elapsedS = null) {
+ const chip = this.ui.chip;
+ if (!chip) return;
+ chip.dataset.state = state;
+ chip.hidden = state === 'idle';
+ const text = chip.querySelector('.ars-chip-label');
+ const time = chip.querySelector('.ars-chip-elapsed');
+ if (text) text.textContent = label;
+ if (time) time.textContent = elapsedS == null ? '' : `${Math.round(elapsedS)}s`;
+ }
+
+ async _startForge(rawPrompt) {
+ const prompt = String(rawPrompt || '').trim();
+ if (!this.forge || prompt.length < 3 || this._forgeBusy) return null;
+ this._forgeBusy = true;
+ const seq = ++this._forgeSeq;
+ if (this.ui.forgeGo) this.ui.forgeGo.disabled = true;
+ const started = Date.now();
+ this._forgeChip('working', 'Sending your prompt…', 0);
+ const ticker = setInterval(() => {
+ if (this.ui.chip?.dataset.state === 'working') {
+ const label = this.ui.chip.querySelector('.ars-chip-label')?.textContent || '';
+ this._forgeChip('working', label, (Date.now() - started) / 1000);
+ }
+ }, 1000);
+
+ try {
+ const model = await this.forge.generate(prompt, {
+ onProgress: (s) => {
+ if (seq !== this._forgeSeq) return;
+ this._forgeChip('working', s.message, s.elapsedMs / 1000);
+ },
+ });
+ if (seq !== this._forgeSeq) return null;
+ rememberRecent({ src: model.src, title: model.prompt, poster: model.poster }, this._recentKey);
+ this._trayCache.delete('recent');
+ this._forgeChip('idle');
+ if (this.ui.forgeInput) this.ui.forgeInput.value = '';
+ await this._addModel({ src: model.src, title: model.title, poster: model.poster }, { announce: false });
+ this._setStatus('Generated and placed. Pinch to resize, drag to move.');
+ this._emit('generate', { model });
+ return model;
+ } catch (err) {
+ if (seq === this._forgeSeq) {
+ this._forgeChip('error', err?.message || 'Generation failed.');
+ setTimeout(() => {
+ if (this.ui.chip?.dataset.state === 'error') this._forgeChip('idle');
+ }, 6500);
+ }
+ this._emit('generate-error', { error: err, prompt });
+ return null;
+ } finally {
+ clearInterval(ticker);
+ if (seq === this._forgeSeq) {
+ this._forgeBusy = false;
+ if (this.ui.forgeGo) this.ui.forgeGo.disabled = false;
+ }
+ }
+ }
+
+ // ── Entering AR ───────────────────────────────────────────────────────────
+
+ /**
+ * Take this device into AR by its best available path. WebXR keeps the whole
+ * scene in the page; everything else hands one model to the platform's own AR
+ * viewer, which is the only way to get real ARKit / ARCore placement there.
+ */
+ _enterAR() {
+ // Immersive AR keeps the whole arrangement in the page, so a device that
+ // has it goes straight in: an extra sheet in front of a one-tap experience
+ // is friction, not polish. Everywhere else the hand-off is not instant and
+ // not obvious, and the sheet is what makes it both.
+ if (this.arMode === 'webxr') return this._toggleXR();
+ this._openArSheet();
+ return Promise.resolve();
+ }
+
+ // ── The AR hand-off sheet ─────────────────────────────────────────────────
+
+ /**
+ * Cache identity for one placement's USDZ. The scale is in the key because it
+ * is baked into the export: someone who pinches a chair to half size and taps
+ * AR must get the half-size chair, not the cached full-size one.
+ */
+ _arCacheKey(p) {
+ return `${p.src}|${p.group.scale.x.toFixed(3)}`;
+ }
+
+ /**
+ * The USDZ bytes for one placement.
+ *
+ * Exported from the copy already standing in the scene, so there is no second
+ * download and Quick Look receives the pose and the size on screen. A model
+ * the exporter chokes on falls back to a clean conversion of the original
+ * file rather than failing the tap.
+ */
+ async _targetUsdz(p) {
+ const { objectToUsdzBlob, glbUrlToUsdzBlob } = await import('./usdz.js');
+ try {
+ return await objectToUsdzBlob(p.group);
+ } catch (err) {
+ log.warn('live-scene USDZ export failed, refetching the source', err);
+ return glbUrlToUsdzBlob(p.src);
+ }
+ }
+
+ /**
+ * A picture of the model the sheet is about to send, rendered from the model
+ * itself.
+ *
+ * A catalogue poster would be easier, but half the ways a model reaches this
+ * studio (a pasted URL, a generation still warming its thumbnail) have no
+ * poster at all, and a 200px empty box with a placeholder glyph in it is the
+ * kind of detail that makes a product feel unfinished. This renders the real
+ * thing, at the size and in the pose it is standing in the scene, off-screen
+ * into a render target so the live canvas never flickers.
+ *
+ * Best-effort by design: a context loss or a stubbed WebGL implementation
+ * returns null and the sheet falls back to its glyph.
+ *
+ * @param {object} p The placement to portray
+ * @param {number} [size] Square edge, in device pixels
+ * @returns {string|null} a data: URL
+ */
+ _renderArPreview(p, size = 384) {
+ // An immersive session owns the renderer and its frame buffer; borrowing it
+ // for a thumbnail mid-session is not worth a dropped XR frame.
+ if (this.xrSession) return null;
+ let target = null;
+ try {
+ const model = cloneSkinnedScene(p.group);
+ model.position.set(0, 0, 0);
+ model.rotation.set(0, 0, 0);
+ model.updateMatrixWorld(true);
+
+ const box = new Box3().setFromObject(model);
+ if (box.isEmpty()) return null;
+ const center = box.getCenter(new Vector3());
+ const radius = Math.max(box.getSize(new Vector3()).length() / 2, 0.01);
+
+ const scene = new Scene();
+ scene.add(model);
+ // Lit brighter than the room is: this is a product shot of the model,
+ // not a preview of the scene's lighting, and dark props read as a
+ // silhouette at anything subtler.
+ scene.add(new HemisphereLight(0xffffff, 0x3a3a48, 3.4));
+ const key = new DirectionalLight(0xffffff, 3.6);
+ key.position.set(1.4, 2.2, 1.8);
+ const fill = new DirectionalLight(0xdfe4ff, 1.5);
+ fill.position.set(-1.6, 0.9, -1.2);
+ scene.add(key, fill);
+
+ const fov = 32;
+ const cam = new PerspectiveCamera(fov, 1, radius / 100, radius * 100);
+ // Three-quarter view from slightly above: the angle a product shot uses,
+ // and the one that reads as a solid object rather than a flat card.
+ const dist = (radius / Math.sin((fov * Math.PI) / 360)) * 1.06;
+ cam.position.set(center.x + dist * 0.62, center.y + dist * 0.42, center.z + dist * 0.66);
+ cam.lookAt(center);
+
+ target = new WebGLRenderTarget(size, size, { depthBuffer: true });
+ const prevTarget = this.renderer.getRenderTarget();
+ this.renderer.setRenderTarget(target);
+ this.renderer.clear();
+ this.renderer.render(scene, cam);
+ const pixels = new Uint8Array(size * size * 4);
+ this.renderer.readRenderTargetPixels(target, 0, 0, size, size, pixels);
+ this.renderer.setRenderTarget(prevTarget);
+
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ const ctx = canvas.getContext('2d');
+ const image = ctx.createImageData(size, size);
+ // WebGL reads bottom-up; a canvas is top-down.
+ const stride = size * 4;
+ for (let row = 0; row < size; row++) {
+ image.data.set(pixels.subarray((size - 1 - row) * stride, (size - row) * stride), row * stride);
+ }
+ ctx.putImageData(image, 0, 0);
+ return canvas.toDataURL('image/png');
+ } catch (err) {
+ log.warn('AR preview render failed', err);
+ return null;
+ } finally {
+ target?.dispose();
+ }
+ }
+
+ /** Which model the AR button would send right now. */
+ _arDefaultTarget() {
+ return this.selected || this.placements[this.placements.length - 1] || null;
+ }
+
+ /**
+ * Convert the likely AR target ahead of the tap, so the tap is instant.
+ *
+ * This is the whole reason Quick Look works here rather than appearing to do
+ * nothing: Safari opens `rel="ar"` only while the page holds user activation,
+ * and a conversion started inside the tap handler outlives it. Warming is
+ * debounced because a pinch changes the cache key on every frame.
+ */
+ _warmQuickLook() {
+ if (this._destroyed || this.arMode !== 'quicklook') return;
+ clearTimeout(this._arWarmTimer);
+ this._arWarmTimer = setTimeout(() => {
+ if (this._destroyed) return;
+ const target = this._arDefaultTarget();
+ if (!target) return;
+ const key = this._arCacheKey(target);
+ if (isQuickLookReady(key)) return;
+ this._arKeys.add(key);
+ prepareNativeAr(
+ { src: target.src, title: target.title, key, build: () => this._targetUsdz(target) },
+ ).catch((err) => {
+ // A warm-up failure is not the user's problem yet: the sheet retries
+ // the same conversion in front of them, with a real error and a
+ // retry button, if they ever ask for it.
+ log.warn('AR warm-up failed', err);
+ });
+ }, 900);
+ }
+
+ /**
+ * Open the sheet that hands one model to the device's AR viewer.
+ * @param {object} [placement] Defaults to the selected model, then the last one.
+ */
+ _openArSheet(placement) {
+ const u = this.ui;
+ if (!u.arModal) return;
+ this._lastFocus = document.activeElement;
+ u.arModal.hidden = false;
+ this._showArTarget(placement || this._arDefaultTarget());
+ // aria-modal is a promise that focus is inside the dialog.
+ (u.arGo.hidden || u.arGo.disabled ? u.arClose : u.arGo)?.focus?.();
+ this._emit('ar-sheet', { open: true });
+ }
+
+ _closeArSheet() {
+ const { arModal, xrBtn } = this.ui;
+ if (!arModal || arModal.hidden) return;
+ const hadFocus = arModal.contains(document.activeElement);
+ arModal.hidden = true;
+ this._arToken++; // abandon any conversion still in flight for this sheet
+ if (hadFocus) this._restoreFocus(xrBtn);
+ this._emit('ar-sheet', { open: false });
+ }
+
+ _setArStatus(message, { state = '' } = {}) {
+ const node = this.ui.arStatus;
+ if (!node) return;
+ node.textContent = '';
+ node.classList.toggle('is-error', state === 'error');
+ node.classList.toggle('is-ready', state === 'ready');
+ if (!message) return;
+ if (state === 'busy') node.appendChild(el('span', { class: 'ars-spinner', 'aria-hidden': 'true' }));
+ node.appendChild(el('span', { text: message }));
+ }
+
+ /** Render the sheet for one target and start preparing it. */
+ _showArTarget(target) {
+ const u = this.ui;
+ if (!u.arModal || u.arModal.hidden) return;
+ this._arToken++;
+ this._arHandoff = null;
+ this._arTarget = target || null;
+
+ const goLabel = u.arGo.querySelector('.ars-ar-go-label');
+ this._arRetry = null;
+ u.arXr.hidden = this.arMode !== 'webxr';
+ u.arQr.hidden = true;
+ u.arPicker.hidden = true;
+ u.arPicker.textContent = '';
+
+ if (!target) {
+ u.arThumb.textContent = '🪄';
+ u.arName.textContent = 'Nothing to place yet';
+ u.arHint.textContent = 'Add a model to the scene and it can stand on your real floor at its real size.';
+ this._setArStatus(null);
+ u.arGo.hidden = false;
+ u.arGo.disabled = false;
+ u.arGo.removeAttribute('aria-busy');
+ if (goLabel) goLabel.textContent = 'Browse models';
+ // The hexagon means "place this"; there is nothing to place yet.
+ u.arGo.querySelector('.ars-ar-go-icon').hidden = true;
+ return;
+ }
+
+ u.arThumb.textContent = '◆';
+ const preview = this._renderArPreview(target) || target.poster;
+ if (preview) {
+ const img = el('img', { src: preview, alt: '' });
+ // A poster that 404s would leave a broken-image glyph in the sheet.
+ img.addEventListener('error', () => { u.arThumb.textContent = '◆'; }, { once: true });
+ u.arThumb.textContent = '';
+ u.arThumb.appendChild(img);
+ }
+ u.arName.textContent = target.title || 'Model';
+
+ if (this.placements.length > 1) {
+ u.arPicker.hidden = false;
+ for (const p of this.placements) {
+ u.arPicker.appendChild(el('button', {
+ type: 'button', class: 'ars-ar-chip', 'data-ar-id': p.id,
+ 'aria-pressed': p === target ? 'true' : 'false',
+ text: p.title || 'Model',
+ }));
+ }
+ }
+
+ if (this.arMode === 'none') {
+ u.arHint.textContent = 'AR needs a phone. Open this scene on your iPhone or Android and the model stands on your real floor.';
+ this._setArStatus(null);
+ u.arGo.hidden = true;
+ u.arQr.hidden = false;
+ return;
+ }
+
+ u.arHint.textContent = 'Point your device at a flat surface, then drag to place it. It arrives at real size.';
+ u.arGo.hidden = false;
+ u.arGo.querySelector('.ars-ar-go-icon').hidden = false;
+ if (goLabel) goLabel.textContent = 'Place in your space';
+ this._prepareArTarget(target);
+ }
+
+ /**
+ * Get the hand-off ready before the person taps for it.
+ *
+ * Scene Viewer needs nothing prepared, so it enables straight away. Quick
+ * Look needs a USDZ, which is why the button says so while it converts
+ * instead of sitting there looking broken for two seconds.
+ */
+ async _prepareArTarget(target) {
+ const u = this.ui;
+ const token = this._arToken;
+ const key = this._arCacheKey(target);
+ const warm = this.arMode !== 'quicklook' || isQuickLookReady(key);
+
+ if (!warm) {
+ u.arGo.disabled = true;
+ u.arGo.setAttribute('aria-busy', 'true');
+ this._setArStatus('Preparing it for AR…', { state: 'busy' });
+ }
+ this._arKeys.add(key);
+ try {
+ const handoff = await prepareNativeAr({
+ src: target.src, title: target.title, key, build: () => this._targetUsdz(target),
+ }, { fallbackUrl: this.config.shareBaseUrl });
+ if (token !== this._arToken || this._destroyed) return;
+ this._arHandoff = handoff;
+ u.arGo.disabled = false;
+ u.arGo.removeAttribute('aria-busy');
+ this._setArStatus(warm ? null : 'Ready.', { state: 'ready' });
+ // Put the thumb back on the button that is now armed, but never steal
+ // focus from a control the person moved to while they waited.
+ const idle = document.activeElement === document.body || document.activeElement === u.arModal;
+ if (!warm && idle) u.arGo.focus?.();
+ } catch (err) {
+ if (token !== this._arToken || this._destroyed) return;
+ log.warn('AR preparation failed', err);
+ u.arGo.disabled = true;
+ u.arGo.removeAttribute('aria-busy');
+ this._setArStatus(`Could not prepare this model for AR (${err?.message || err}).`, { state: 'error' });
+ // The primary button stays the primary action: it just becomes the
+ // retry, rather than leaving a dead button and a second one to hunt for.
+ this._arRetry = target;
+ u.arGo.disabled = false;
+ u.arGo.querySelector('.ars-ar-go-label').textContent = 'Try again';
+ u.arGo.querySelector('.ars-ar-go-icon').hidden = true;
+ this._emit('native-ar-error', { error: err, src: target.src });
+ }
+ }
+
+ /**
+ * The tap that opens AR.
+ *
+ * Everything expensive already happened, so this is deliberately synchronous
+ * from the click through to the anchor activation: put an `await` in front of
+ * `open()` and iOS drops the user gesture and silently refuses to open Quick
+ * Look.
+ */
+ _onArGo() {
+ if (!this._arTarget) {
+ this._closeArSheet();
+ this._openTray();
+ return;
+ }
+ if (this._arRetry) {
+ this._showArTarget(this._arRetry);
+ return;
+ }
+ const handoff = this._arHandoff;
+ if (!handoff) return;
+ const { src, title } = this._arTarget;
+ this._yieldCameraToNativeAr();
+ try {
+ handoff.open();
+ } catch (err) {
+ log.warn('native AR failed to open', err);
+ this._setArStatus(`Could not open AR (${err?.message || err}).`, { state: 'error' });
+ this._emit('native-ar-error', { error: err, src });
+ return;
+ }
+ this._emit('native-ar', { src, title, viewer: handoff.viewer });
+ this._closeArSheet();
+ this._setStatus('Point at the floor, then drag to place it.');
+ }
+
+ /**
+ * Open one model in the device's native AR viewer. On iOS the GLB is
+ * converted to USDZ on the device first, which is why this reports progress:
+ * a couple of silent seconds after a tap reads as a dead button.
+ *
+ * @param {object} [placement] Defaults to the selected model, then the last one.
+ */
+ async _placeNative(placement) {
+ const target = placement || this.selected || this.placements[this.placements.length - 1];
+ if (!target) {
+ this._setStatus('Add a model first, then place it in your space.', { warn: true });
+ return null;
+ }
+ if (this._nativeArBusy) return null;
+ this._nativeArBusy = true;
+ const btn = this.ui.xrBtn;
+ btn?.setAttribute('aria-busy', 'true');
+
+ this._arKeys.add(this._arCacheKey(target));
+ const STAGES = {
+ download: 'Fetching the model…',
+ parse: 'Reading the model…',
+ convert: 'Preparing it for AR…',
+ open: 'Opening AR…',
+ };
+ this._setStatus(STAGES.download, { sticky: true });
+ if (this.arMode === 'quicklook' || this.arMode === 'sceneviewer') this._yieldCameraToNativeAr();
+ try {
+ const opened = await placeInYourSpace(
+ {
+ src: target.src,
+ title: target.title,
+ key: this._arCacheKey(target),
+ build: () => this._targetUsdz(target),
+ },
+ {
+ onProgress: (stage) => this._setStatus(STAGES[stage] || 'Preparing AR…', { sticky: true }),
+ fallbackUrl: this.config.shareBaseUrl,
+ },
+ );
+ if (opened === 'none') {
+ this._setStatus('This device has no AR viewer. Open this scene on a phone instead.', {
+ warn: true, actionLabel: 'Show QR', onAction: () => this._openQr(),
+ });
+ } else {
+ this._setStatus('Point at the floor, then drag to place it.');
+ }
+ this._emit('native-ar', { src: target.src, title: target.title, viewer: opened });
+ return opened;
+ } catch (err) {
+ log.warn('native AR failed', err);
+ this._setStatus(`Could not open AR for this model (${err?.message || err}).`, {
+ warn: true, actionLabel: 'Try again', onAction: () => this._placeNative(target),
+ });
+ this._emit('native-ar-error', { error: err, src: target.src });
+ return null;
+ } finally {
+ this._nativeArBusy = false;
+ btn?.removeAttribute('aria-busy');
+ }
+ }
+
+ // ── WebXR immersive session ───────────────────────────────────────────────
+
+ async _toggleXR() {
+ if (this.xrSession) {
+ this.xrSession.end();
+ return;
+ }
+ if (this.arTransitioning) return;
+ this.arTransitioning = true;
+ try {
+ if (this.arActive) this._stopCamera(); // the immersive session owns the rear camera
+ const session = new MultiPlaceSession({
+ renderer: this.renderer,
+ scene: this.scene,
+ camera: this.camera,
+ domOverlayRoot: this.ui.hud,
+ getArmedContent: () => this._armedContent(),
+ onPlaced: (group) => {
+ const p = this.placements.find((x) => x.group === group);
+ if (p) {
+ p.yaw = 0;
+ this._select(null); // the ring is a fallback-mode affordance
+ }
+ this._saveScene();
+ this._setStatus(`Placed ${this.xrSession?.placedCount ?? ''}: tap another spot to add one more.`);
+ },
+ getScaleTarget: () => this.placements[this.placements.length - 1]?.group ?? null,
+ onScale: (s, { final }) => { if (final) this._saveScene(); },
+ onHit: (has) => this.ui.root.classList.toggle('xr-has-floor', has),
+ onTracking: (ok) => {
+ if (!ok) this._setStatus('Tracking lost: move to a brighter spot with more texture.', { warn: true, sticky: true });
+ else this._setStatus(null);
+ },
+ onFrame: (dt) => {
+ for (const p of this.placements) {
+ p.mixer?.update(dt);
+ p.idle?.update(dt);
+ }
+ },
+ onEnd: () => this._onXREnd(),
+ });
+ this._stopLoop();
+ await session.start();
+ this.xrSession = session;
+ // Real-world lighting and reflections: created after start() so the
+ // addon's sessionstart listener requests the light probe.
+ this.estimatedLight = new EstimatedLighting({
+ renderer: this.renderer,
+ scene: this.scene,
+ baseLights: [this.hemi, this.sun],
+ onChange: (on) => {
+ if (on) this._setStatus('Lit by your room: reflections and shadows match the real light.');
+ },
+ });
+ this.estimatedLight.start();
+ this.ui.root.classList.add('is-xr');
+ this.grid.visible = false;
+ this.scene.fog = null;
+ this.selRing.visible = false;
+ for (const p of this.placements) if (p.shadow) p.shadow.visible = false;
+ this.ui.xrBtn?.classList.add('is-active');
+ this.ui.xrBtn?.setAttribute('aria-pressed', 'true');
+ this._setStatus('Point at the floor, then tap to place. Every tap adds another model.');
+ this._emit('xr', { active: true });
+ } catch (err) {
+ log.warn('XR session failed', err);
+ this.estimatedLight?.dispose();
+ this.estimatedLight = null;
+ this._startLoop();
+ this._setStatus('Could not start immersive AR on this device. Camera mode still works.', { warn: true });
+ } finally {
+ this.arTransitioning = false;
+ }
+ }
+
+ /** What the next reticle tap places. An XR select cannot await, so only an
+ * already-resolved template is placeable. */
+ _armedContent() {
+ const src = this._armed?.src ?? this.placements[this.placements.length - 1]?.src;
+ if (!src) {
+ this._setStatus('Pick a model first: Add or generate one, then tap the floor.', { warn: true });
+ return null;
+ }
+ const tpl = this._templatesReady.get(src);
+ if (!tpl) {
+ this._loadTemplate(src);
+ this._setStatus('Model is still loading: one moment, then tap again.', { sticky: true });
+ return null;
+ }
+ const { group, mixer, idlePromise } = this._instantiate(tpl, src);
+ const placement = {
+ id: `p-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
+ src,
+ title: this._armed?.title || '',
+ poster: '',
+ group,
+ shadow: null,
+ mixer,
+ idle: null,
+ yaw: 0,
+ baseRadius: tpl.radius,
+ height: tpl.height || 0,
+ spawnT: 1,
+ netId: null,
+ ownerId: null,
+ remote: false,
+ _lastNetSend: 0,
+ };
+ idlePromise?.then((mgr) => {
+ if (!mgr) return;
+ if (this.placements.includes(placement)) placement.idle = mgr;
+ else mgr.detach();
+ });
+ this.placements.push(placement);
+ this._updateCount();
+ this._emit('add', { placement: publicPlacement(placement, this), remote: false });
+ return group;
+ }
+
+ _onXREnd() {
+ this.xrSession = null;
+ this.estimatedLight?.dispose();
+ this.estimatedLight = null;
+ this.ui.root.classList.remove('is-xr', 'xr-has-floor');
+ this.ui.xrBtn?.classList.remove('is-active');
+ this.ui.xrBtn?.setAttribute('aria-pressed', 'false');
+ // Ground anything the session placed mid-air back onto the floor plane so
+ // the fallback layout stays coherent, then resume our own loop.
+ for (const p of this.placements) {
+ p.group.position.y = 0;
+ if (p.shadow) {
+ p.shadow.visible = true;
+ p.shadow.position.set(p.group.position.x, 0.004, p.group.position.z);
+ }
+ }
+ this.grid.visible = !this.arActive;
+ if (!this.arActive) this.scene.fog = this._fog;
+ this._saveScene();
+ this._startLoop();
+ this._setStatus('Back to the studio view.');
+ this._emit('xr', { active: false });
+ }
+
+ // ── Photo + QR ────────────────────────────────────────────────────────────
+
+ async _capturePhoto() {
+ this.renderer.render(this.scene, this.camera); // fresh pixels under preserveDrawingBuffer
+ const blob = await captureComposite({ canvas: this.ui.canvas, video: this.ui.video, isAR: this.arActive });
+ if (!blob) {
+ this._setStatus('Could not capture the frame.', { warn: true });
+ return;
+ }
+ try {
+ const how = await shareOrDownload(blob, {
+ filename: 'ar-studio.png',
+ title: this.config.branding?.title || 'AR Studio',
+ });
+ this._setStatus(how === 'shared' ? 'Shared.' : 'Saved to your downloads.');
+ } catch (err) {
+ if (err?.name !== 'AbortError') this._setStatus('Could not share that photo.', { warn: true });
+ }
+ }
+
+ _openQr() {
+ const { qrModal, qrBox, qrLink } = this.ui;
+ if (!qrModal) return;
+ this._lastFocus = document.activeElement;
+ const url = this.shareUrl();
+ if (qrBox) {
+ try {
+ qrBox.innerHTML = renderQRToSVG(url, { scale: 6, margin: 2, dark: '#0b0b0b', light: '#ffffff' });
+ } catch {
+ // The arrangement hash can outgrow the encoder; a models-only QR still
+ // beats a wall of text, and the full link below keeps the arrangement.
+ try {
+ qrBox.innerHTML = renderQRToSVG(studioShareUrl(this.config.shareBaseUrl, this.getScene()), {
+ scale: 6, margin: 2, dark: '#0b0b0b', light: '#ffffff',
+ });
+ } catch {
+ qrBox.textContent = url;
+ }
+ }
+ }
+ if (qrLink) {
+ qrLink.href = url;
+ qrLink.textContent = url.length > 72 ? `${url.slice(0, 69)}…` : url;
+ }
+ qrModal.hidden = false;
+ // aria-modal is a promise that focus is inside the dialog.
+ this.ui.qrClose?.focus?.();
+ this._emit('share', { url });
+ }
+
+ _closeQr() {
+ const { qrModal, qrBtn } = this.ui;
+ if (!qrModal || qrModal.hidden) return;
+ const hadFocus = qrModal.contains(document.activeElement);
+ qrModal.hidden = true;
+ if (hadFocus) this._restoreFocus(qrBtn);
+ }
+
+ // ── Shared rooms ──────────────────────────────────────────────────────────
+
+ // A model I control: single-player models (no ownerId) and my own room models.
+ // Other people's room models stay visible and live but are not mine to edit
+ // the server owner-gates too, so this is the local half of the same rule.
+ _isMine(p) {
+ return !p.ownerId || p.ownerId === this.clientId;
+ }
+
+ _placementShared(p) {
+ return localToShared({
+ x: p.group.position.x,
+ z: p.group.position.z,
+ yaw: p.yaw,
+ scale: this._logicalScale(p),
+ height: p.height || 0,
+ });
+ }
+
+ _placementWire(p, wireId) {
+ return { id: wireId, src: p.src, title: p.title, ...this._placementShared(p) };
+ }
+
+ // Throttled to ~12 Hz so a drag does not flood the socket.
+ _netBroadcastTransform(p) {
+ if (!this.net || this.net.status !== 'online' || !p.netId || !this._isMine(p)) return;
+ const now = Date.now();
+ if (now - (p._lastNetSend || 0) < 80) return;
+ p._lastNetSend = now;
+ const s = this._placementShared(p);
+ this.net.update(p.netId, { relEast: s.relEast, relNorth: s.relNorth, yawDeg: s.yawDeg, scale: s.scale });
+ }
+
+ _applySharedTransform(p, m) {
+ const l = sharedToLocal(m);
+ p.group.position.set(l.x, 0, l.z);
+ p.yaw = l.yaw;
+ p.group.rotation.y = l.yaw;
+ p.group.scale.setScalar(l.scale);
+ p.group.userData._targetScale = l.scale;
+ p.spawnT = 1; // an update is not a spawn: no scale-in pop
+ if (p.shadow) {
+ p.shadow.position.set(l.x, 0.004, l.z);
+ p.shadow.scale.setScalar(l.scale);
+ }
+ if (this.selected === p) this._positionSelRing();
+ }
+
+ // Reconcile the room's full model list against local placements: add what
+ // appeared, drop remote ones that left, refresh other people's transforms. My
+ // own live models are authored locally and never overwritten by their echo.
+ _reconcileRemoteModels(models) {
+ const serverIds = new Set(models.map((m) => m.id));
+ for (const p of [...this.placements]) {
+ if (p.remote && p.netId && !serverIds.has(p.netId)) {
+ this._removePlacement(p, { persist: false, broadcast: false });
+ }
+ }
+ let fresh = 0;
+ for (const m of models) {
+ const existing = this._netModels.get(m.id);
+ if (existing) {
+ if (!this._isMine(existing)) this._applySharedTransform(existing, m);
+ continue;
+ }
+ const local = sharedToLocal(m);
+ const mine = !!m.mine || m.ownerId === this.clientId;
+ if (!mine) fresh++;
+ this._addModel({ src: m.src, title: m.title }, {
+ x: local.x, z: local.z, yaw: local.yaw, scale: local.scale,
+ remote: true, netId: m.id, ownerId: mine ? this.clientId : m.ownerId,
+ announce: false, persist: false,
+ });
+ }
+ this._updateCount();
+ // After the join burst settles, a new model from someone else is live
+ // activity worth surfacing: but never during the initial sync.
+ if (this._roomSynced && fresh > 0) {
+ this._setStatus(fresh === 1 ? 'Someone added a model to the room.' : `${fresh} models were added to the room.`);
+ }
+ this._roomSynced = true;
+ }
+
+ _applyRemoteModelChange(m) {
+ const p = this._netModels.get(m.id);
+ if (!p) return;
+ if (m.removed) {
+ if (p.remote) this._removePlacement(p, { persist: false, broadcast: false });
+ return;
+ }
+ if (!this._isMine(p)) this._applySharedTransform(p, m);
+ }
+
+ _wireNet(net) {
+ net.on('status', ({ status }) => {
+ if (status === 'online') {
+ this._setStatus(`Shared room ${this.roomCode} is live: edits sync to everyone here.`);
+ this.ui.root.classList.add('is-room');
+ } else if (status === 'connecting') {
+ this._setStatus(`Joining room ${this.roomCode}…`, { sticky: true });
+ } else if (status === 'unavailable' || status === 'failed') {
+ this._setStatus('Shared rooms are offline right now: you can still build solo.', { warn: true });
+ this._leaveRoom({ silent: true });
+ } else if (status === 'offline') {
+ this._setStatus('Reconnecting to the room…', { sticky: true });
+ }
+ this._updateRoomButton();
+ this._emit('room', { status, code: this.roomCode });
+ });
+ net.on('models', (models) => this._reconcileRemoteModels(models));
+ net.on('model', (m) => this._applyRemoteModelChange(m));
+ net.on('presence', (p) => {
+ const prev = this._presence.count;
+ this._presence = p;
+ this._updateCount();
+ if (!this.ui.roomModal.hidden) this._renderRoomModal();
+ if (prev > 0 && p.count > prev) {
+ this._setStatus(p.count === 2 ? "Someone joined: you're building together now." : 'Someone else joined the room.');
+ } else if (prev > 1 && p.count < prev && p.count >= 1) {
+ this._setStatus(p.count === 1 ? "You're on your own in the room now." : 'Someone left the room.');
+ }
+ });
+ net.on('reject', (msg) => {
+ const why = msg?.reason === 'room_full' ? 'the room is full'
+ : msg?.reason === 'owner_full' ? 'you have the maximum models in this room'
+ : 'the room declined it';
+ this._setStatus(`Couldn't share that model: ${why}.`, { warn: true });
+ });
+ }
+
+ // Push every model I already have into a freshly created room, so a solo scene
+ // becomes the shared starting point instead of vanishing.
+ _seedRoom() {
+ if (!this.net || this.net.status !== 'online') return;
+ for (const p of this.placements) {
+ if (p.netId) continue;
+ const wireId = `m${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`.slice(0, 40);
+ p.netId = wireId;
+ p.ownerId = this.clientId;
+ p.remote = false;
+ this._netModels.set(wireId, p);
+ this.net.spawn(this._placementWire(p, wireId));
+ }
+ }
+
+ // seed=true is right for CREATE (I am the first one there). JOIN never seeds:
+ // entering a room means entering ITS scene, so my solo models stay local and
+ // cannot duplicate the server's authoritative copies on a rejoin.
+ async _joinRoom(code, { seed = false } = {}) {
+ const norm = normalizeRoomCode(code);
+ if (!norm) {
+ this._setStatus('That room code looks off: check the 6 characters and try again.', { warn: true });
+ return;
+ }
+ this._leaveRoom({ silent: true });
+ this._roomSynced = false;
+ this.roomCode = norm;
+ const net = new StudioNet({
+ roomKey: roomKeyForCode(norm),
+ clientId: this.clientId,
+ name: '',
+ url: this.config.rooms?.server || '',
+ });
+ this.net = net;
+ this._wireNet(net);
+ await net.connect();
+ // A failed connect fires status 'failed' synchronously and the handler nulls
+ // `this.net`, so re-check identity rather than dereferencing a dead field.
+ if (this.net === net && net.status === 'online') {
+ if (seed) this._seedRoom();
+ this._roomHeartbeat = setInterval(() => this.net?.heartbeat(), 15000);
+ try {
+ const url = new URL(location.href);
+ url.searchParams.set('room', norm);
+ history.replaceState(null, '', url);
+ } catch { /* history is unavailable in some embeds */ }
+ }
+ this._updateRoomButton();
+ }
+
+ _createRoom() {
+ return this._joinRoom(generateRoomCode(), { seed: true });
+ }
+
+ _leaveRoom({ silent = false } = {}) {
+ if (this._roomHeartbeat) {
+ clearInterval(this._roomHeartbeat);
+ this._roomHeartbeat = null;
+ }
+ if (this.net) {
+ try { this.net.destroy(); } catch { /* already destroyed */ }
+ this.net = null;
+ }
+ // Remote models leave with the room; my own stay as a local scene.
+ for (const p of [...this.placements]) {
+ if (p.remote && !this._isMine(p)) this._removePlacement(p, { persist: false, broadcast: false });
+ else { p.netId = null; p.remote = false; }
+ }
+ this._netModels.clear();
+ this.roomCode = '';
+ this._presence = { count: 1, names: [] };
+ this.ui.root.classList.remove('is-room');
+ try {
+ const url = new URL(location.href);
+ url.searchParams.delete('room');
+ history.replaceState(null, '', url);
+ } catch { /* history unavailable */ }
+ this._updateCount();
+ this._updateRoomButton();
+ if (!silent) this._setStatus('Left the shared room. Your models are still here.');
+ }
+
+ _updateRoomButton() {
+ const btn = this.ui.roomBtn;
+ if (!btn) return;
+ const live = !!this.net && (this.net.status === 'online' || this.net.status === 'connecting');
+ btn.classList.toggle('is-active', live);
+ // Two labels rather than one rewritten string, so a host that translated the
+ // idle label does not lose it the first time the room state changes.
+ const idle = btn.querySelector('.ars-room-label');
+ const code = btn.querySelector('.ars-room-code-label');
+ if (idle) idle.hidden = live;
+ if (code) {
+ code.hidden = !live;
+ code.textContent = live ? (this.roomCode || 'Room') : '';
+ }
+ if (!this.ui.roomModal.hidden) this._renderRoomModal();
+ }
+
+ _renderRoomModal() {
+ const online = !!this.net && this.net.status === 'online';
+ const { roomIdle, roomLive, roomCode, roomPresence, roomQr } = this.ui;
+ if (roomIdle) roomIdle.hidden = online;
+ if (roomLive) roomLive.hidden = !online;
+ if (!online) return;
+ if (roomCode) roomCode.textContent = this.roomCode;
+ if (roomPresence) {
+ roomPresence.textContent = this._presence.count > 1
+ ? `${this._presence.count} people are building here.`
+ : 'You are the only one here yet: share the code to invite someone.';
+ }
+ if (roomQr) {
+ const url = roomShareUrl(this.config.shareBaseUrl, this.roomCode);
+ try {
+ roomQr.innerHTML = renderQRToSVG(url, { scale: 5, margin: 2, dark: '#0b0b0b', light: '#ffffff' });
+ } catch {
+ roomQr.textContent = url;
+ }
+ }
+ }
+
+ _openRoomModal() {
+ const m = this.ui.roomModal;
+ if (!m) return;
+ this._lastFocus = document.activeElement;
+ m.hidden = false;
+ this._renderRoomModal();
+ (this.net?.status === 'online' ? this.ui.roomCopy : this.ui.roomCreate)?.focus?.();
+ }
+
+ _closeRoomModal() {
+ const m = this.ui.roomModal;
+ if (!m || m.hidden) return;
+ const hadFocus = m.contains(document.activeElement);
+ m.hidden = true;
+ if (hadFocus) this._restoreFocus(this.ui.roomBtn);
+ }
+
+ async _createRoomFromUI() {
+ await this._createRoom();
+ this._renderRoomModal();
+ // One-tap invite: put the join link on the clipboard immediately, still
+ // inside this click's user activation, so hosting is create → paste.
+ if (this.net?.status === 'online' && navigator.clipboard?.writeText) {
+ try {
+ await navigator.clipboard.writeText(roomShareUrl(this.config.shareBaseUrl, this.roomCode));
+ this._setStatus(`Room ${this.roomCode} is live: invite link copied. Paste it to a friend.`);
+ } catch { /* clipboard blocked: the Copy button is still there */ }
+ }
+ }
+
+ async _joinRoomFromUI() {
+ const input = this.ui.roomJoinInput;
+ const code = normalizeRoomCode(input?.value);
+ if (!code) {
+ this._setStatus('That room code looks off: check the 6 characters.', { warn: true });
+ input?.focus?.();
+ return;
+ }
+ await this._joinRoom(code);
+ this._renderRoomModal();
+ }
+
+ async _copyRoomInvite() {
+ const url = roomShareUrl(this.config.shareBaseUrl, this.roomCode);
+ const btn = this.ui.roomCopy;
+ try {
+ const how = await shareUrlOrCopy(url, {
+ title: 'Build with me in AR',
+ text: `Join my AR Studio room: ${this.roomCode}`,
+ });
+ if (btn) {
+ const old = btn.textContent;
+ btn.textContent = how === 'shared' ? 'Shared ✓' : 'Link copied ✓';
+ setTimeout(() => { btn.textContent = old; }, 1600);
+ }
+ } catch (err) {
+ if (err?.name !== 'AbortError') window.prompt('Copy this invite link:', url);
+ }
+ }
+
+ // ── Render loop ───────────────────────────────────────────────────────────
+
+ // Desktop preview has no gyro and no real room to look at, so a model dropped
+ // on the floor lands below the eyeline and reads as "nothing happened". Tilt
+ // the view down to actually frame what is in the scene: but only until the
+ // viewer takes the camera themselves, after which their aim is the truth.
+ _framePreview() {
+ if (this.arActive || this.xrSession || this._userLooked || !this.placements.length) return;
+ let sx = 0;
+ let sz = 0;
+ let sh = 0;
+ for (const p of this.placements) {
+ sx += p.group.position.x;
+ sz += p.group.position.z;
+ sh += (p.height || 0.4) * (p.group.userData._targetScale ?? 1);
+ }
+ const n = this.placements.length;
+ const cx = sx / n;
+ const cz = sz / n;
+ const centre = (sh / n) * 0.5;
+ const dist = Math.hypot(cx - this.camera.position.x, cz - this.camera.position.z);
+ if (!(dist > 0.05)) return;
+ this.cameraYaw = Math.atan2(cx - this.camera.position.x, -(cz - this.camera.position.z));
+ this.cameraPitch = clampPitch(-Math.atan2(this.camera.position.y - centre, dist), PITCH_MIN, PITCH_MAX);
+ }
+
+ _applyCameraLook() {
+ this.camera.rotation.set(0, 0, 0);
+ this.camera.rotateY(this.cameraYaw);
+ this.camera.rotateX(this.cameraPitch);
+ }
+
+ _tick(t) {
+ this._rafId = requestAnimationFrame((next) => this._tick(next));
+ const dt = this._prevT ? Math.min(0.1, (t - this._prevT) / 1000) : 0.016;
+ this._prevT = t;
+
+ for (const p of this.placements) {
+ p.mixer?.update(dt);
+ p.idle?.update(dt);
+ if (p.spawnT < 1) {
+ p.spawnT = Math.min(1, p.spawnT + dt * 3.2);
+ const e = 1 - (1 - p.spawnT) ** 3; // ease-out cubic
+ const target = p.group.userData._targetScale ?? 1;
+ p.group.scale.setScalar(Math.max(0.001, target * e));
+ p.shadow?.scale.setScalar(Math.max(0.001, target * e));
+ }
+ }
+ if (this.selected) this._positionSelRing();
+ this._applyCameraLook();
+ this.renderer.render(this.scene, this.camera);
+ }
+
+ _startLoop() {
+ if (this._rafId === null) {
+ this._prevT = 0;
+ this._rafId = requestAnimationFrame((t) => this._tick(t));
+ }
+ }
+
+ _stopLoop() {
+ if (this._rafId !== null) {
+ cancelAnimationFrame(this._rafId);
+ this._rafId = null;
+ }
+ }
+
+ _resize() {
+ const { width, height } = this._viewportSize();
+ this.renderer.setSize(width, height, false);
+ this.camera.aspect = width / height;
+ this.camera.updateProjectionMatrix();
+ this._applyCameraFov();
+ }
+
+ // ── Public API ────────────────────────────────────────────────────────────
+
+ /**
+ * Add a model to the scene.
+ * @param {{src: string, title?: string, poster?: string}} model
+ * @param {object} [opts] `x` `z` `yaw` `scale` `announce` `persist`
+ * @returns {Promise<object|null>} the placement, or null when it could not load
+ */
+ addModel(model, opts) {
+ return this._addModel(model, opts);
+ }
+
+ /** Remove every model. Returns what was removed, so a host can offer its own undo. */
+ clear() {
+ const items = this.getScene();
+ for (const p of [...this.placements]) this._removePlacement(p, { persist: false });
+ this._saveScene();
+ this._emit('clear', { items });
+ return items;
+ }
+
+ /** The current arrangement as plain data: `[{ src, title, x, z, yaw, scale }]`. */
+ getScene() {
+ return this.placements.map((p) => ({
+ src: p.src,
+ title: p.title,
+ x: p.group.position.x,
+ z: p.group.position.z,
+ yaw: p.yaw,
+ scale: this._logicalScale(p),
+ }));
+ }
+
+ /** Replace the scene with an arrangement in the shape `getScene()` returns. */
+ async setScene(items) {
+ this.clear();
+ for (const it of Array.isArray(items) ? items : []) {
+ await this._addModel({ src: it.src, title: it.title }, {
+ x: it.x, z: it.z, yaw: it.yaw, scale: it.scale, announce: false, persist: false,
+ });
+ }
+ this._saveScene();
+ }
+
+ /** A link that reopens this exact arrangement, models and transforms included. */
+ shareUrl() {
+ return studioSceneUrl(this.config.shareBaseUrl, this.getScene());
+ }
+
+ /** Generate a model from a prompt and drop it into the scene. */
+ generate(prompt) {
+ return this._startForge(prompt);
+ }
+
+ /** Hand one model to the device's own AR viewer (Quick Look / Scene Viewer). */
+ viewInYourSpace(src, title = '') {
+ const url = normalizeGlbUrl(src);
+ if (!url) return '';
+ const launch = buildArLaunchUrl(this.config.origin, url, title, { endpoint: this.config.arLaunchUrl });
+ window.open(launch, '_blank', 'noopener');
+ return launch;
+ }
+
+ /** Turn the camera passthrough on. Call it from a user gesture (iOS requires one). */
+ startCamera() { return this._startCamera(); }
+
+ /** Turn the camera passthrough off. */
+ stopCamera() { this._stopCamera(); }
+
+ /** Enter or leave the immersive WebXR session. */
+ toggleImmersive() { return this._toggleXR(); }
+
+ /**
+ * Take this device into AR by its best path: the immersive session where
+ * WebXR exists, otherwise the platform's own AR viewer.
+ */
+ enterAR() { return this._enterAR(); }
+
+ /**
+ * Open one model in the device's native AR viewer (Quick Look on iOS, Scene
+ * Viewer on Android). Defaults to the selected model.
+ * @param {object} [placement]
+ */
+ placeInYourSpace(placement) { return this._placeNative(placement); }
+
+ /**
+ * Open the AR hand-off sheet: the screen that prepares one model and then
+ * opens the device's own AR viewer from a single tap.
+ * @param {object} [placement] Defaults to the selected model, then the last one.
+ */
+ openArSheet(placement) { this._openArSheet(placement); }
+
+ /** Close the AR hand-off sheet. */
+ closeArSheet() { this._closeArSheet(); }
+
+ /** Open a shared room (a new one when `code` is omitted). Returns the code. */
+ async openRoom(code) {
+ if (code) await this._joinRoom(code);
+ else await this._createRoom();
+ return this.roomCode;
+ }
+
+ /** Leave the shared room, keeping your own models. */
+ leaveRoom() { this._leaveRoom(); }
+
+ /** Tear the studio down: camera, socket, listeners, GPU context, DOM. */
+ destroy() {
+ if (this._destroyed) return;
+ this._destroyed = true;
+ this._stopLoop();
+ this._stopCamera();
+ this.xrSession?.end();
+ this.net?.destroy();
+ if (this._roomHeartbeat) clearInterval(this._roomHeartbeat);
+ clearTimeout(this._statusTimer);
+ clearTimeout(this._arWarmTimer);
+ // Only this studio's own conversions: a second studio on the page may be
+ // sharing the cache and still needs its entries.
+ for (const key of this._arKeys) releaseQuickLook(key);
+ this._arKeys.clear();
+ clearInterval(this._lightTimer);
+ document.removeEventListener('keydown', this._onKeyDown);
+ window.removeEventListener('deviceorientationabsolute', this._onOrientationAbsolute, true);
+ window.removeEventListener('deviceorientation', this._onOrientation, true);
+ window.removeEventListener('resize', this._onResize);
+ window.removeEventListener('pagehide', this._onPageHide);
+ if (this._onArReturn) {
+ document.removeEventListener('visibilitychange', this._onArReturn);
+ window.removeEventListener('focus', this._onArReturn);
+ this._onArReturn = null;
+ }
+ this._ro?.disconnect();
+ for (const p of [...this.placements]) this._removePlacement(p, { persist: false, broadcast: false });
+ this.shadowTex?.dispose();
+ this.selRing.geometry.dispose();
+ this.selRing.material.dispose();
+ this.renderer.dispose();
+ this.ui.root.remove();
+ this._listeners.clear();
+ }
+}
+
+// ── Module-private helpers ───────────────────────────────────────────────────
+
+function prefersReducedMotion() {
+ try {
+ return !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ } catch {
+ return false;
+ }
+}
+
+function makeShadowTexture() {
+ try {
+ const size = 128;
+ const cnv = document.createElement('canvas');
+ cnv.width = size;
+ cnv.height = size;
+ const ctx = cnv.getContext('2d');
+ const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
+ g.addColorStop(0, 'rgba(0,0,0,0.40)');
+ g.addColorStop(0.55, 'rgba(0,0,0,0.18)');
+ g.addColorStop(1, 'rgba(0,0,0,0)');
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, size, size);
+ return new CanvasTexture(cnv);
+ } catch {
+ return null;
+ }
+}
+
+function makeLightProbe() {
+ try {
+ const cnv = document.createElement('canvas');
+ cnv.width = 16;
+ cnv.height = 16;
+ return { cnv, ctx: cnv.getContext('2d', { willReadFrequently: true }) };
+ } catch {
+ return null;
+ }
+}
+
+/** A stable per-browser id. It decides who owns which model in a shared room. */
+function readClientId(scope) {
+ const key = `${scope || 'ar-studio'}:client`;
+ try {
+ let id = localStorage.getItem(key);
+ if (!id) {
+ id = crypto?.randomUUID?.() || `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+ localStorage.setItem(key, id);
+ }
+ return id;
+ } catch {
+ return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+ }
+}
+
+/** A readable label from a model URL: `alarm_clock_01.glb` → `Alarm clock 01`. */
+function filenameLabel(url) {
+ const base = String(url).split('?')[0].split('/').pop() || 'Model';
+ const stem = base.replace(/\.(glb|gltf)$/i, '').replace(/[_-]+/g, ' ').trim();
+ return stem ? stem.charAt(0).toUpperCase() + stem.slice(1) : 'Linked model';
+}
+
+/** The shape a placement takes when it leaves the studio in an event. */
+function publicPlacement(p, studio) {
+ return {
+ id: p.id,
+ src: p.src,
+ title: p.title,
+ x: p.group.position.x,
+ z: p.group.position.z,
+ yaw: p.yaw,
+ scale: studio._logicalScale(p),
+ mine: studio._isMine(p),
+ };
+}
diff --git a/packages/ar-studio/src/studio/styles.js b/packages/ar-studio/src/studio/styles.js
new file mode 100644
index 000000000..a7d877c2f
--- /dev/null
+++ b/packages/ar-studio/src/studio/styles.js
@@ -0,0 +1,366 @@
+// The studio's stylesheet, as a string.
+//
+// Everything is scoped under `.ars-root`, so dropping the studio into an
+// existing page cannot leak a single rule into it, and the host can restyle any
+// part by targeting the same classes with equal specificity. Colours come from
+// custom properties on the root, so a one-line `accent` config recolours the
+// whole surface.
+
+export function studioStyles() {
+ return `
+.ars-root {
+ --ars-accent: #8b7cf8;
+ --ars-accent-ink: #dcd6ff;
+ --ars-ink: #ecedf2;
+ --ars-ink-dim: #9aa0af;
+ --ars-ink-faint: #6b7080;
+ --ars-line: rgba(255, 255, 255, 0.1);
+ --ars-panel: rgba(12, 13, 17, 0.78);
+ --ars-warn: #fca5a5;
+ --ars-radius: 14px;
+ --ars-font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ position: absolute;
+ inset: 0;
+ display: block;
+ overflow: hidden;
+ background: radial-gradient(120% 120% at 50% 0%, #101321 0%, #07080c 55%, #000 100%);
+ color: var(--ars-ink);
+ font-family: var(--ars-font);
+ touch-action: none;
+ -webkit-user-select: none;
+ user-select: none;
+ color-scheme: dark;
+}
+.ars-root *, .ars-root *::before, .ars-root *::after { box-sizing: border-box; }
+/* A display rule must never beat the hidden attribute: an invisible panel that
+ still swallows taps is a dead page. */
+.ars-root [hidden] { display: none !important; }
+.ars-root.is-fullscreen {
+ position: fixed;
+ z-index: 2147483000;
+ height: 100dvh;
+}
+
+/* Layers: camera video → WebGL canvas → HUD */
+.ars-video {
+ position: absolute; inset: 0; width: 100%; height: 100%;
+ object-fit: cover; display: none; background: #000;
+}
+.ars-root.is-ar .ars-video { display: block; }
+.ars-canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.ars-hud {
+ position: absolute; inset: 0; z-index: 10;
+ display: flex; flex-direction: column; justify-content: space-between;
+ pointer-events: none;
+}
+.ars-hud > * { pointer-events: none; }
+.ars-hud a, .ars-hud button, .ars-hud input, .ars-hud form,
+.ars-hud .ars-top, .ars-hud .ars-dock, .ars-hud .ars-selbar,
+.ars-hud .ars-tray, .ars-hud .ars-modal { pointer-events: auto; }
+
+/* ── Top bar ── */
+.ars-top {
+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
+ padding: calc(env(safe-area-inset-top, 0px) + 10px) 14px 10px;
+}
+.ars-back, .ars-title {
+ display: inline-flex; align-items: center; gap: 7px;
+ color: var(--ars-ink); text-decoration: none; font-size: 13.5px; font-weight: 650;
+ background: var(--ars-panel); border: 1px solid var(--ars-line);
+ border-radius: 999px; padding: 8px 14px; backdrop-filter: blur(10px);
+ transition: background 0.15s, border-color 0.15s;
+}
+.ars-back:hover { background: rgba(30, 32, 40, 0.85); border-color: rgba(255, 255, 255, 0.22); }
+.ars-root :focus-visible { outline: 2px solid var(--ars-accent); outline-offset: 2px; }
+.ars-count {
+ font-size: 12.5px; font-weight: 650; color: var(--ars-accent-ink);
+ background: color-mix(in srgb, var(--ars-accent) 16%, transparent);
+ border: 1px solid color-mix(in srgb, var(--ars-accent) 40%, transparent);
+ border-radius: 999px; padding: 7px 12px; backdrop-filter: blur(10px);
+}
+.ars-spacer { flex: 1 1 auto; }
+.ars-icon-btn {
+ appearance: none; cursor: pointer; font: inherit; color: var(--ars-ink);
+ display: inline-flex; align-items: center; justify-content: center; gap: 7px;
+ background: var(--ars-panel); border: 1px solid var(--ars-line);
+ border-radius: 999px; padding: 8px 13px; font-size: 13px; font-weight: 650;
+ backdrop-filter: blur(10px);
+ transition: background 0.15s, border-color 0.15s, transform 0.06s;
+}
+.ars-icon-btn:hover { background: rgba(30, 32, 40, 0.85); border-color: rgba(255, 255, 255, 0.22); }
+.ars-icon-btn:active { transform: translateY(1px); }
+.ars-icon-btn[disabled] { opacity: 0.45; cursor: not-allowed; }
+.ars-icon-btn.is-active {
+ background: color-mix(in srgb, var(--ars-accent) 20%, transparent);
+ border-color: color-mix(in srgb, var(--ars-accent) 55%, transparent);
+ color: var(--ars-accent-ink);
+}
+
+/* ── Generation progress chip ── */
+.ars-chip {
+ position: absolute; top: calc(env(safe-area-inset-top, 0px) + 58px); left: 50%;
+ transform: translateX(-50%); z-index: 11;
+ display: inline-flex; align-items: center; gap: 9px; max-width: min(88vw, 480px);
+ background: var(--ars-panel); border: 1px solid var(--ars-line); border-radius: 999px;
+ padding: 9px 15px; font-size: 13px; backdrop-filter: blur(10px);
+ animation: ars-rise 0.25s ease;
+}
+.ars-chip[data-state="error"] { border-color: rgba(252, 165, 165, 0.5); color: var(--ars-warn); }
+.ars-chip[data-state="error"] .ars-spinner { display: none; }
+.ars-chip-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.ars-chip-elapsed { color: var(--ars-ink-faint); font-variant-numeric: tabular-nums; font-size: 12px; }
+.ars-spinner {
+ width: 14px; height: 14px; flex: 0 0 auto; border-radius: 50%;
+ border: 2px solid rgba(255, 255, 255, 0.18); border-top-color: var(--ars-accent);
+ animation: ars-spin 0.9s linear infinite;
+}
+@keyframes ars-spin { to { transform: rotate(360deg); } }
+@keyframes ars-rise { from { opacity: 0; transform: translate(-50%, 6px); } to { opacity: 1; transform: translate(-50%, 0); } }
+
+/* ── Empty state ── */
+.ars-empty {
+ position: absolute; inset: 0; z-index: 9; display: grid; place-items: center;
+ padding: 24px; pointer-events: none;
+}
+.ars-empty-card {
+ pointer-events: auto; text-align: center; max-width: 340px;
+ background: var(--ars-panel); border: 1px solid var(--ars-line);
+ border-radius: 20px; padding: 26px 22px; backdrop-filter: blur(12px);
+ display: flex; flex-direction: column; gap: 10px; align-items: center;
+}
+.ars-empty-art { font-size: 40px; line-height: 1; }
+.ars-empty-card h2 { margin: 0; font-size: 18px; letter-spacing: -0.01em; font-weight: 700; }
+.ars-empty-card p { margin: 0 0 6px; color: var(--ars-ink-dim); font-size: 13.5px; line-height: 1.55; }
+.ars-empty-row { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; }
+.ars-root.is-ar .ars-empty-card { background: rgba(12, 13, 17, 0.6); }
+
+/* ── Buttons ── */
+.ars-btn {
+ appearance: none; cursor: pointer; font: inherit; font-size: 13.5px; font-weight: 650;
+ color: var(--ars-ink); background: rgba(255, 255, 255, 0.07);
+ border: 1px solid rgba(255, 255, 255, 0.16); border-radius: 11px; padding: 10px 15px;
+ display: inline-flex; align-items: center; gap: 7px;
+ transition: background 0.15s, border-color 0.15s, transform 0.06s;
+}
+.ars-btn:hover { background: rgba(255, 255, 255, 0.12); border-color: rgba(255, 255, 255, 0.28); }
+.ars-btn:active { transform: translateY(1px); }
+.ars-btn[disabled] { opacity: 0.5; cursor: not-allowed; }
+.ars-btn-primary { background: var(--ars-accent); border-color: var(--ars-accent); color: #0d0b1e; }
+.ars-btn-primary:hover { filter: brightness(1.08); }
+
+/* ── Status line ── */
+.ars-status {
+ position: absolute; left: 50%; transform: translateX(-50%);
+ bottom: calc(env(safe-area-inset-bottom, 0px) + 186px); z-index: 12;
+ display: inline-flex; align-items: center; gap: 10px; max-width: 92%;
+ background: var(--ars-panel); border: 1px solid var(--ars-line); border-radius: 999px;
+ padding: 8px 14px; font-size: 12.5px; color: var(--ars-ink-dim);
+ backdrop-filter: blur(10px); animation: ars-rise 0.2s ease; text-align: center;
+}
+.ars-status.is-warn { color: var(--ars-warn); border-color: rgba(252, 165, 165, 0.42); }
+.ars-status-action {
+ appearance: none; cursor: pointer; font: inherit; font-size: 12.5px; font-weight: 700;
+ color: var(--ars-accent-ink); background: none; border: 0; padding: 0; text-decoration: underline;
+}
+
+/* ── Selection toolbar ── */
+.ars-selbar {
+ position: absolute; left: 50%; transform: translateX(-50%);
+ bottom: calc(env(safe-area-inset-bottom, 0px) + 132px); z-index: 11;
+ display: flex; align-items: center; gap: 6px; max-width: 94%;
+ background: var(--ars-panel); border: 1px solid var(--ars-line); border-radius: 999px;
+ padding: 6px 8px 6px 14px; backdrop-filter: blur(12px);
+ animation: ars-pop 0.18s ease;
+}
+@keyframes ars-pop { from { opacity: 0; transform: translate(-50%, 5px); } to { opacity: 1; transform: translate(-50%, 0); } }
+.ars-sel-name {
+ font-size: 12.5px; font-weight: 650; color: var(--ars-accent-ink);
+ max-width: 26vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+}
+.ars-selbar .ars-icon-btn { border-radius: 999px; padding: 7px 11px; font-size: 12.5px; background: rgba(255, 255, 255, 0.06); }
+/* The AR control lives in the top bar and already acts on the selected model, so
+ the selection toolbar stays icon-sized edit actions. Duplicating it here
+ collapsed to an unlabelled dot on a narrow phone. */
+.ars-top .ars-icon-btn[aria-busy="true"] { opacity: 0.7; cursor: progress; }
+
+/* ── Bottom dock ── */
+.ars-dock {
+ display: flex; align-items: center; gap: 9px; flex-wrap: nowrap;
+ padding: 12px 14px calc(env(safe-area-inset-bottom, 0px) + 14px);
+ background: linear-gradient(to top, rgba(4, 5, 8, 0.72), rgba(4, 5, 8, 0));
+}
+.ars-forge-form { flex: 1 1 auto; display: flex; align-items: center; gap: 8px; min-width: 0; }
+.ars-forge-input {
+ flex: 1 1 auto; min-width: 0; font: inherit; font-size: 14px; color: var(--ars-ink);
+ background: var(--ars-panel); border: 1px solid var(--ars-line);
+ border-radius: 999px; padding: 11px 16px; backdrop-filter: blur(10px);
+ transition: border-color 0.15s;
+}
+.ars-forge-input::placeholder { color: var(--ars-ink-faint); }
+.ars-forge-input:focus { border-color: color-mix(in srgb, var(--ars-accent) 55%, transparent); }
+.ars-forge-go {
+ appearance: none; cursor: pointer; font: inherit; font-size: 14px; font-weight: 700;
+ color: #0d0b1e; background: var(--ars-accent); border: 0; border-radius: 999px;
+ padding: 11px 17px; flex: 0 0 auto;
+}
+.ars-forge-go[disabled] { opacity: 0.55; cursor: not-allowed; }
+
+/* ── Tray + modals ── */
+.ars-tray, .ars-modal {
+ position: absolute; inset: 0; z-index: 20; display: flex;
+ background: rgba(4, 5, 8, 0.62); backdrop-filter: blur(4px);
+ animation: ars-fade 0.16s ease;
+}
+@keyframes ars-fade { from { opacity: 0; } to { opacity: 1; } }
+.ars-tray { align-items: flex-end; }
+.ars-modal { align-items: center; justify-content: center; padding: 22px; }
+.ars-tray-panel {
+ width: 100%; max-height: 78%; display: flex; flex-direction: column;
+ background: rgba(11, 12, 16, 0.97); border-top: 1px solid var(--ars-line);
+ border-radius: 20px 20px 0 0; animation: ars-slide 0.22s ease;
+}
+@keyframes ars-slide { from { transform: translateY(14px); opacity: 0; } to { transform: none; opacity: 1; } }
+.ars-tray-head {
+ display: flex; align-items: center; gap: 10px;
+ padding: 14px 16px 10px; border-bottom: 1px solid var(--ars-line);
+}
+.ars-tray-head h2 { margin: 0; font-size: 15px; font-weight: 700; }
+.ars-tabs {
+ display: flex; gap: 6px; padding: 10px 16px 0; overflow-x: auto;
+ scrollbar-width: none; position: relative;
+}
+.ars-tabs::-webkit-scrollbar { display: none; }
+.ars-tab {
+ appearance: none; cursor: pointer; font: inherit; font-size: 13px; font-weight: 650;
+ white-space: nowrap; color: var(--ars-ink-dim); background: rgba(255, 255, 255, 0.05);
+ border: 1px solid transparent; border-radius: 999px; padding: 8px 14px;
+ transition: background 0.15s, color 0.15s;
+}
+.ars-tab:hover { color: var(--ars-ink); background: rgba(255, 255, 255, 0.1); }
+.ars-tab.is-active {
+ color: var(--ars-accent-ink);
+ background: color-mix(in srgb, var(--ars-accent) 18%, transparent);
+ border-color: color-mix(in srgb, var(--ars-accent) 45%, transparent);
+}
+.ars-tray-body { flex: 1 1 auto; overflow-y: auto; padding: 14px 16px calc(env(safe-area-inset-bottom, 0px) + 18px); -webkit-overflow-scrolling: touch; }
+.ars-tray-loading, .ars-tray-empty {
+ display: flex; flex-direction: column; align-items: center; gap: 12px;
+ padding: 34px 16px; color: var(--ars-ink-dim); font-size: 13.5px; text-align: center;
+}
+.ars-tray-loading { flex-direction: row; justify-content: center; }
+.ars-item-list {
+ list-style: none; margin: 0; padding: 0;
+ display: grid; gap: 10px; grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));
+}
+.ars-item-add {
+ appearance: none; cursor: pointer; font: inherit; width: 100%; text-align: left;
+ display: flex; flex-direction: column; gap: 7px; color: var(--ars-ink);
+ background: rgba(255, 255, 255, 0.05); border: 1px solid var(--ars-line);
+ border-radius: var(--ars-radius); padding: 9px;
+ transition: background 0.15s, border-color 0.15s, transform 0.08s;
+}
+.ars-item-add:hover { background: rgba(255, 255, 255, 0.1); border-color: color-mix(in srgb, var(--ars-accent) 45%, transparent); transform: translateY(-1px); }
+.ars-item-add:active { transform: translateY(0); }
+.ars-item-thumb {
+ display: grid; place-items: center; aspect-ratio: 1 / 1; overflow: hidden;
+ border-radius: 10px; background: rgba(255, 255, 255, 0.04);
+}
+.ars-item-thumb img { width: 100%; height: 100%; object-fit: cover; }
+.ars-item-cube { font-size: 22px; color: var(--ars-ink-faint); }
+.ars-item-title {
+ font-size: 12.5px; font-weight: 600; line-height: 1.3;
+ display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
+}
+.ars-item-cta { font-size: 11.5px; font-weight: 700; color: var(--ars-accent-ink); }
+.ars-search {
+ width: 100%; font: inherit; font-size: 14px; color: var(--ars-ink);
+ background: rgba(255, 255, 255, 0.05); border: 1px solid var(--ars-line);
+ border-radius: 11px; padding: 10px 14px; margin-bottom: 8px;
+}
+.ars-hint { margin: 0 0 12px; color: var(--ars-ink-faint); font-size: 12px; line-height: 1.5; }
+.ars-hint a, .ars-tray-empty a { color: var(--ars-accent-ink); }
+.ars-link-row { display: flex; gap: 8px; align-items: center; }
+.ars-link-row input { flex: 1 1 auto; min-width: 0; }
+.ars-more { display: grid; place-items: center; padding: 14px 0 4px; }
+
+.ars-dialog {
+ width: min(420px, 100%); max-height: 88%; overflow-y: auto;
+ background: rgba(11, 12, 16, 0.98); border: 1px solid var(--ars-line);
+ border-radius: 20px; padding: 20px; text-align: center;
+ display: flex; flex-direction: column; gap: 12px; align-items: center;
+ animation: ars-slide 0.2s ease;
+}
+.ars-dialog h2 { margin: 0; font-size: 16px; font-weight: 700; }
+.ars-dialog p { margin: 0; color: var(--ars-ink-dim); font-size: 13px; line-height: 1.55; }
+.ars-qr-box { background: #fff; border-radius: 14px; padding: 12px; line-height: 0; }
+.ars-qr-box svg { width: min(240px, 60vw); height: auto; }
+.ars-code {
+ font-size: 26px; font-weight: 800; letter-spacing: 0.16em;
+ color: var(--ars-accent-ink); font-variant-numeric: tabular-nums;
+}
+.ars-link-out { font-size: 12px; color: var(--ars-ink-faint); word-break: break-all; }
+
+/* ── AR hand-off sheet ── */
+.ars-ar-sheet { gap: 14px; }
+.ars-ar-sheet .ars-btn { width: 100%; }
+.ars-ar-heading { letter-spacing: -0.01em; }
+.ars-ar-target { display: flex; flex-direction: column; align-items: center; gap: 10px; width: 100%; }
+.ars-ar-thumb {
+ width: min(210px, 52vw); aspect-ratio: 1; border-radius: 18px;
+ background: radial-gradient(120% 120% at 50% 0%, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.02));
+ border: 1px solid var(--ars-line);
+ display: grid; place-items: center; overflow: hidden;
+ font-size: 42px; color: var(--ars-ink-faint);
+}
+.ars-ar-thumb img { width: 100%; height: 100%; object-fit: contain; }
+.ars-ar-name { font-size: 15px; font-weight: 700; text-align: center; overflow-wrap: anywhere; }
+.ars-ar-picker { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; width: 100%; }
+.ars-ar-chip {
+ appearance: none; cursor: pointer; font: inherit; font-size: 12px; font-weight: 650;
+ color: var(--ars-ink-dim); background: rgba(255, 255, 255, 0.06);
+ border: 1px solid var(--ars-line); border-radius: 999px; padding: 6px 11px;
+ max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+}
+.ars-ar-chip:hover { background: rgba(255, 255, 255, 0.12); color: var(--ars-ink); }
+.ars-ar-chip:active { transform: translateY(1px); }
+.ars-ar-chip[aria-pressed="true"] {
+ background: color-mix(in srgb, var(--ars-accent) 20%, transparent);
+ border-color: color-mix(in srgb, var(--ars-accent) 55%, transparent);
+ color: var(--ars-accent-ink);
+}
+.ars-ar-hint { color: var(--ars-ink-faint) !important; font-size: 12.5px !important; }
+.ars-ar-status { min-height: 17px; display: flex; align-items: center; justify-content: center; gap: 7px; }
+.ars-ar-status.is-error { color: #ffb4b4 !important; }
+.ars-ar-status.is-ready { color: var(--ars-accent-ink) !important; }
+.ars-ar-status .ars-spinner { width: 12px; height: 12px; border-width: 2px; }
+.ars-ar-go[aria-busy="true"] { cursor: progress; }
+.ars-ar-go { font-size: 15px; padding: 13px 18px; }
+.ars-ar-go-icon { font-size: 15px; }
+.ars-dialog-row { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; }
+.ars-divider { width: 100%; height: 1px; background: var(--ars-line); margin: 2px 0; }
+
+/* WebXR: the dom-overlay shows the HUD over the passthrough camera; the empty
+ card and grid would only be in the way once the room itself is the backdrop. */
+.ars-root.is-xr .ars-empty, .ars-root.is-xr .ars-back { display: none; }
+
+@media (prefers-reduced-motion: reduce) {
+ .ars-root *, .ars-root *::before, .ars-root *::after {
+ animation-duration: 0.01ms !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: 0.01ms !important;
+ }
+}
+@media (max-width: 420px) {
+ .ars-title { display: none; }
+ .ars-item-list { grid-template-columns: repeat(auto-fill, minmax(108px, 1fr)); }
+ /* A phone this narrow cannot fit the prompt beside four controls without
+ squeezing it down to two visible characters. Give it its own row. */
+ .ars-dock { flex-wrap: wrap; row-gap: 10px; }
+ .ars-forge-form { order: -1; flex: 1 0 100%; }
+ .ars-dock .ars-icon-btn { flex: 0 0 auto; }
+ .ars-status { bottom: calc(env(safe-area-inset-bottom, 0px) + 152px); }
+ .ars-selbar { bottom: calc(env(safe-area-inset-bottom, 0px) + 100px); }
+}
+`;
+}
diff --git a/packages/ar-studio/src/studio/ui.js b/packages/ar-studio/src/studio/ui.js
new file mode 100644
index 000000000..1defd3e78
--- /dev/null
+++ b/packages/ar-studio/src/studio/ui.js
@@ -0,0 +1,267 @@
+// The studio's DOM.
+//
+// Built in code rather than shipped as an HTML file so the whole surface is one
+// import: `createArStudio(document.body)` and you have a working AR studio, with
+// no markup to copy, no stylesheet to link, and no ids to keep in sync.
+//
+// Every control is a real button with a real accessible name, the tab strip
+// implements the full ARIA tablist contract (arrow keys, roving tabindex), and
+// every dialog is a real `role="dialog"` that takes and returns focus. The
+// stylesheet is injected once per document and scoped under `.ars-root`.
+
+import { studioStyles } from './styles.js';
+
+const STYLE_ID = 'ar-studio-styles';
+
+/** Inject the stylesheet once per document. */
+export function ensureStyles(doc = document) {
+ if (doc.getElementById(STYLE_ID)) return;
+ const style = doc.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = studioStyles();
+ doc.head.appendChild(style);
+}
+
+function el(tag, attrs = {}, children = []) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v === null || v === undefined || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k === 'html') node.innerHTML = v;
+ else if (k === 'hidden') node.hidden = Boolean(v);
+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v === true ? '' : String(v));
+ }
+ for (const child of [].concat(children)) {
+ if (child) node.appendChild(typeof child === 'string' ? document.createTextNode(child) : child);
+ }
+ return node;
+}
+
+export { el };
+
+/**
+ * Build the studio's DOM inside `host` and return every node the controller
+ * drives. The host keeps whatever children it already had: the studio appends
+ * its own root: so it can be mounted inside an existing layout.
+ *
+ * @param {HTMLElement} host
+ * @param {object} cfg Resolved config (branding, generate, rooms).
+ * @returns {Record<string, HTMLElement>}
+ */
+export function buildUI(host, cfg) {
+ ensureStyles(host.ownerDocument || document);
+
+ const t = cfg.branding || {};
+ const canGenerate = cfg.generate?.enabled !== false;
+ const canRoom = cfg.rooms?.enabled !== false;
+
+ const video = el('video', { class: 'ars-video', playsinline: true, muted: true, 'aria-hidden': 'true' });
+ const canvas = el('canvas', { class: 'ars-canvas' });
+
+ // ── Top bar ──────────────────────────────────────────────────────────────
+ const back = t.backHref
+ ? el('a', { class: 'ars-back', href: t.backHref }, [el('span', { 'aria-hidden': 'true', text: '←' }), t.backLabel || 'Back'])
+ : null;
+ const title = el('span', { class: 'ars-title', text: t.title || 'AR Studio' });
+ const count = el('span', { class: 'ars-count', hidden: true, role: 'status', 'aria-live': 'polite' });
+ const roomBtn = canRoom
+ ? el('button', { type: 'button', class: 'ars-icon-btn', 'aria-label': 'Open a shared room so other people can build in this scene with you' }, [
+ el('span', { 'aria-hidden': 'true', text: '👥' }),
+ el('span', { class: 'ars-room-label', text: 'Share live' }),
+ el('span', { class: 'ars-room-code-label', hidden: true }),
+ ])
+ : null;
+ const qrBtn = el('button', { type: 'button', class: 'ars-icon-btn', hidden: true, 'aria-label': 'Show a QR code that opens this scene on your phone' }, [
+ el('span', { 'aria-hidden': 'true', text: '📱' }), 'Open on phone',
+ ]);
+ // One AR button that always does the best thing this device can do: an
+ // immersive WebXR session where that exists, otherwise the device's own AR
+ // viewer (Quick Look / Scene Viewer). The label is set at boot, once the
+ // capability is known, so it never promises the wrong experience.
+ const xrBtn = el('button', { type: 'button', class: 'ars-icon-btn', hidden: true, 'aria-pressed': 'false', 'aria-label': 'View this in augmented reality' }, [
+ el('span', { 'aria-hidden': 'true', text: '✦' }),
+ el('span', { class: 'ars-ar-label', text: 'AR' }),
+ ]);
+ const cameraBtn = el('button', { type: 'button', class: 'ars-icon-btn', 'aria-pressed': 'false', 'aria-label': 'Turn the camera on to see your models in the room' }, [
+ el('span', { 'aria-hidden': 'true', text: '📷' }), 'Camera',
+ ]);
+
+ const top = el('div', { class: 'ars-top' }, [
+ back, title, count,
+ el('span', { class: 'ars-spacer' }),
+ roomBtn, qrBtn, xrBtn, cameraBtn,
+ ]);
+
+ // ── Progress chip ────────────────────────────────────────────────────────
+ const chip = el('div', { class: 'ars-chip', hidden: true, 'data-state': 'idle', role: 'status', 'aria-live': 'polite' }, [
+ el('span', { class: 'ars-spinner', 'aria-hidden': 'true' }),
+ el('span', { class: 'ars-chip-label' }),
+ el('span', { class: 'ars-chip-elapsed' }),
+ ]);
+
+ // ── Empty state ──────────────────────────────────────────────────────────
+ const emptyCamera = el('button', { type: 'button', class: 'ars-btn ars-btn-primary' }, [
+ el('span', { 'aria-hidden': 'true', text: '📷' }), 'Turn on the camera',
+ ]);
+ const emptyAdd = el('button', { type: 'button', class: 'ars-btn', text: 'Browse models' });
+ const emptyForge = canGenerate ? el('button', { type: 'button', class: 'ars-btn', text: 'Generate one' }) : null;
+ const empty = el('div', { class: 'ars-empty' }, [
+ el('div', { class: 'ars-empty-card' }, [
+ el('div', { class: 'ars-empty-art', 'aria-hidden': 'true', text: '🪄' }),
+ el('h2', { text: 'Put anything in your room' }),
+ el('p', {
+ text: canGenerate
+ ? 'Add a model, or describe one and watch it appear. Turn on the camera and it stands on your actual floor.'
+ : 'Add a model from the library, then turn on the camera and it stands on your actual floor.',
+ }),
+ el('div', { class: 'ars-empty-row' }, [emptyCamera, emptyAdd, emptyForge]),
+ ]),
+ ]);
+
+ // ── Status + selection ───────────────────────────────────────────────────
+ const status = el('div', { class: 'ars-status', hidden: true, role: 'status', 'aria-live': 'polite' });
+ const selName = el('span', { class: 'ars-sel-name' });
+ const selbar = el('div', { class: 'ars-selbar', hidden: true, role: 'toolbar', 'aria-label': 'Selected model' }, [
+ selName,
+ el('button', { type: 'button', class: 'ars-icon-btn', 'data-act': 'rotate', 'aria-label': 'Rotate the selected model' }, [el('span', { 'aria-hidden': 'true', text: '⟳' })]),
+ el('button', { type: 'button', class: 'ars-icon-btn', 'data-act': 'duplicate', 'aria-label': 'Duplicate the selected model' }, [el('span', { 'aria-hidden': 'true', text: '⧉' })]),
+ el('button', { type: 'button', class: 'ars-icon-btn', 'data-act': 'remove', 'aria-label': 'Remove the selected model' }, [el('span', { 'aria-hidden': 'true', text: '✕' })]),
+ ]);
+
+ // ── Dock ─────────────────────────────────────────────────────────────────
+ const addBtn = el('button', { type: 'button', class: 'ars-icon-btn', 'aria-expanded': 'false', 'aria-label': 'Add a model to the scene' }, [
+ el('span', { 'aria-hidden': 'true', text: '+' }), 'Add',
+ ]);
+ const forgeInput = el('input', {
+ class: 'ars-forge-input', type: 'text', name: 'prompt', autocomplete: 'off',
+ placeholder: 'Describe something to generate…', 'aria-label': 'Describe a 3D model to generate',
+ maxlength: '300',
+ });
+ const forgeGo = el('button', { type: 'submit', class: 'ars-forge-go', 'aria-label': 'Generate this model' }, ['Make']);
+ const forgeForm = canGenerate ? el('form', { class: 'ars-forge-form' }, [forgeInput, forgeGo]) : el('span', { class: 'ars-spacer' });
+ const photoBtn = el('button', { type: 'button', class: 'ars-icon-btn', disabled: true, 'aria-label': 'Take a photo of the scene' }, [el('span', { 'aria-hidden': 'true', text: '⬤' })]);
+ const clearBtn = el('button', { type: 'button', class: 'ars-icon-btn', hidden: true, 'aria-label': 'Remove every model from the scene' }, ['Clear']);
+ const dock = el('div', { class: 'ars-dock' }, [addBtn, forgeForm, photoBtn, clearBtn]);
+
+ // ── Tray ─────────────────────────────────────────────────────────────────
+ const trayTabs = el('div', { class: 'ars-tabs', role: 'tablist', 'aria-label': 'Model sources' });
+ const trayBody = el('div', { class: 'ars-tray-body', role: 'tabpanel', tabindex: '-1' });
+ const trayClose = el('button', { type: 'button', class: 'ars-icon-btn', 'aria-label': 'Close the model browser' }, [el('span', { 'aria-hidden': 'true', text: '✕' })]);
+ const tray = el('div', { class: 'ars-tray', hidden: true, role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Add a model' }, [
+ el('div', { class: 'ars-tray-panel' }, [
+ el('div', { class: 'ars-tray-head' }, [el('h2', { text: 'Add a model' }), el('span', { class: 'ars-spacer' }), trayClose]),
+ trayTabs,
+ trayBody,
+ ]),
+ ]);
+
+ // ── QR dialog ────────────────────────────────────────────────────────────
+ const qrBox = el('div', { class: 'ars-qr-box' });
+ const qrLink = el('a', { class: 'ars-link-out', target: '_blank', rel: 'noopener' });
+ const qrClose = el('button', { type: 'button', class: 'ars-btn', text: 'Done' });
+ const qrModal = el('div', { class: 'ars-modal', hidden: true, role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Open this scene on your phone' }, [
+ el('div', { class: 'ars-dialog' }, [
+ el('h2', { text: 'Open this scene on your phone' }),
+ el('p', { text: 'Scan it and the same models, in the same arrangement, open on the phone: ready to place in your room.' }),
+ qrBox, qrLink, qrClose,
+ ]),
+ ]);
+
+ // ── AR hand-off sheet ────────────────────────────────────────────────────
+ // The one screen between "I want this in my room" and the device's own AR
+ // viewer. It exists because that hand-off is not instant on iOS: the GLB has
+ // to become a USDZ first, and Safari will only open Quick Look while the page
+ // still holds a user gesture. So the sheet prepares in the background, says
+ // so, and then puts a real button under the person's thumb: one tap, straight
+ // into ARKit, no dead wait.
+ const arThumb = el('span', { class: 'ars-ar-thumb', 'aria-hidden': 'true' });
+ const arName = el('span', { class: 'ars-ar-name' });
+ const arPicker = el('div', { class: 'ars-ar-picker', hidden: true, role: 'group', 'aria-label': 'Choose which model to place' });
+ const arHint = el('p', { class: 'ars-ar-hint' });
+ const arStatus = el('p', { class: 'ars-ar-status', role: 'status', 'aria-live': 'polite' });
+ const arGo = el('button', { type: 'button', class: 'ars-btn ars-btn-primary ars-ar-go' }, [
+ el('span', { class: 'ars-ar-go-icon', 'aria-hidden': 'true', text: '⬡' }),
+ el('span', { class: 'ars-ar-go-label', text: 'Place in your space' }),
+ ]);
+ const arXr = el('button', { type: 'button', class: 'ars-btn ars-ar-xr', hidden: true }, [
+ el('span', { 'aria-hidden': 'true', text: '✦' }), 'Immersive AR: place the whole scene',
+ ]);
+ const arQr = el('button', { type: 'button', class: 'ars-btn ars-ar-qr', hidden: true }, [
+ el('span', { 'aria-hidden': 'true', text: '📱' }), 'Open on your phone',
+ ]);
+ const arClose = el('button', { type: 'button', class: 'ars-btn ars-ar-done', text: 'Done' });
+ const arModal = el('div', { class: 'ars-modal', hidden: true, role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Place a model in your space' }, [
+ el('div', { class: 'ars-dialog ars-ar-sheet' }, [
+ el('h2', { class: 'ars-ar-heading', text: 'Place in your space' }),
+ el('div', { class: 'ars-ar-target' }, [arThumb, arName]),
+ arPicker,
+ arHint,
+ arStatus,
+ arGo, arXr, arQr, arClose,
+ ]),
+ ]);
+
+ // ── Room dialog ──────────────────────────────────────────────────────────
+ const roomCreate = el('button', { type: 'button', class: 'ars-btn ars-btn-primary', text: 'Start a shared room' });
+ const roomJoinInput = el('input', { class: 'ars-search', type: 'text', placeholder: 'Room code', 'aria-label': 'Room code', maxlength: '20', autocomplete: 'off', spellcheck: 'false' });
+ const roomJoinForm = el('form', { class: 'ars-link-row' }, [roomJoinInput, el('button', { type: 'submit', class: 'ars-btn', text: 'Join' })]);
+ const roomIdle = el('div', {}, [
+ el('p', { text: 'Open a room and anyone who joins sees the same scene. Every move, resize and rotate syncs live.' }),
+ el('div', { class: 'ars-dialog-row' }, [roomCreate]),
+ el('div', { class: 'ars-divider' }),
+ el('p', { text: 'Got a code from someone?' }),
+ roomJoinForm,
+ ]);
+ const roomCode = el('div', { class: 'ars-code' });
+ const roomPresence = el('p', {});
+ const roomQr = el('div', { class: 'ars-qr-box' });
+ const roomCopy = el('button', { type: 'button', class: 'ars-btn ars-btn-primary', text: 'Copy invite link' });
+ const roomLeave = el('button', { type: 'button', class: 'ars-btn', text: 'Leave room' });
+ const roomLive = el('div', { hidden: true }, [
+ roomCode, roomPresence, roomQr,
+ el('div', { class: 'ars-dialog-row' }, [roomCopy, roomLeave]),
+ ]);
+ const roomClose = el('button', { type: 'button', class: 'ars-btn', text: 'Close' });
+ const roomModal = el('div', { class: 'ars-modal', hidden: true, role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Shared room' }, [
+ el('div', { class: 'ars-dialog' }, [
+ el('h2', { text: 'Build together' }),
+ roomIdle, roomLive, roomClose,
+ ]),
+ ]);
+
+ const hud = el('div', { class: 'ars-hud' }, [top, empty, status, chip, selbar, dock, tray, qrModal, arModal, roomModal]);
+ const root = el('div', { class: 'ars-root' }, [video, canvas, hud]);
+ if (t.accent) root.style.setProperty('--ars-accent', t.accent);
+ host.appendChild(root);
+ // The studio fills its host absolutely, so the host has to be a positioned box
+ // with a real height. A statically-positioned or zero-height container would
+ // otherwise render a canvas nobody can see or click, which reads as "the
+ // library is broken" rather than "my div has no height".
+ const style = host.ownerDocument.defaultView?.getComputedStyle(host);
+ if (style && style.position === 'static') host.style.position = 'relative';
+ if (host !== host.ownerDocument.body && host.clientHeight < 80 && !host.style.height) {
+ host.style.minHeight = host.style.minHeight || '70vh';
+ }
+
+ return {
+ root, video, canvas, hud, top, title, count, status, chip,
+ cameraBtn, xrBtn, qrBtn, roomBtn, addBtn, photoBtn, clearBtn,
+ forgeForm: canGenerate ? forgeForm : null, forgeInput: canGenerate ? forgeInput : null, forgeGo: canGenerate ? forgeGo : null,
+ empty, emptyCamera, emptyAdd, emptyForge,
+ selbar, selName,
+ tray, trayTabs, trayBody, trayClose,
+ qrModal, qrBox, qrLink, qrClose,
+ arModal, arThumb, arName, arPicker, arHint, arStatus, arGo, arXr, arQr, arClose,
+ roomModal, roomIdle, roomLive, roomCreate, roomJoinForm, roomJoinInput,
+ roomCode, roomPresence, roomQr, roomCopy, roomLeave, roomClose,
+ };
+}
+
+/** Escape a string for interpolation into innerHTML. */
+export function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ }[c]));
+}
diff --git a/packages/ar-studio/src/studio/usdz.js b/packages/ar-studio/src/studio/usdz.js
new file mode 100644
index 000000000..b1f985c17
--- /dev/null
+++ b/packages/ar-studio/src/studio/usdz.js
@@ -0,0 +1,372 @@
+// GLB to USDZ, in the browser.
+//
+// This is what makes "Place in your space" real on an iPhone. Apple's AR Quick
+// Look is the only way to get true ARKit placement on iOS, and it reads USDZ,
+// not glTF. There is no server here doing the conversion: the model is loaded
+// into a scene, prepared, and exported with three.js's own USDZExporter, on the
+// device, in a couple of seconds.
+//
+// Three preparation steps matter, and skipping any of them produces a model
+// that loads but looks broken:
+//
+// 1. Skinned meshes are baked to static geometry. USDZExporter carries no
+// skeletons: it writes raw vertex attributes plus each node's world
+// matrix. Export a rigged character without baking and Quick Look shows a
+// collapsed pile with limbs balled at the hips.
+// 2. Materials are coerced to MeshStandardMaterial. USDZ speaks
+// UsdPreviewSurface, which maps cleanly from Standard only; unlit, Phong
+// and Toon materials are dropped with a warning.
+// 3. Missing normals are computed. Position-only meshes (decimated props,
+// procedural geometry) otherwise export flat and unlit.
+//
+// Ported from the three.ws USDZ pipeline (Apache-2.0).
+
+import {
+ Box3, BufferAttribute, Color, DoubleSide, Group, Mesh, MeshStandardMaterial, Vector3,
+} from 'three';
+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
+import { sharedGLTFLoaderReady } from './loaders.js';
+import { fitTransform } from './scene-math.js';
+
+/**
+ * CPU-skin one SkinnedMesh at its current pose, returning deformed positions in
+ * the mesh's own local space. The caller must have updated world matrices.
+ *
+ * @param {import('three').SkinnedMesh} mesh
+ * @returns {Float32Array} vertexCount * 3
+ */
+export function bakedLocalPositions(mesh) {
+ const posAttr = mesh.geometry.getAttribute('position');
+ const out = new Float32Array(posAttr.count * 3);
+ const v = new Vector3();
+ for (let i = 0; i < posAttr.count; i++) {
+ v.fromBufferAttribute(posAttr, i);
+ mesh.applyBoneTransform(i, v);
+ out[i * 3] = v.x;
+ out[i * 3 + 1] = v.y;
+ out[i * 3 + 2] = v.z;
+ }
+ return out;
+}
+
+/** Replace every SkinnedMesh with a static Mesh frozen at the current pose. */
+export function bakeSkinnedMeshes(scene) {
+ scene.updateMatrixWorld(true);
+ const skinned = [];
+ scene.traverse((obj) => {
+ if (obj.isSkinnedMesh && obj.skeleton?.bones?.length) skinned.push(obj);
+ });
+
+ for (const mesh of skinned) {
+ if (!mesh.geometry.getAttribute('position')) continue;
+ const baked = mesh.geometry.clone();
+ baked.setAttribute('position', new BufferAttribute(bakedLocalPositions(mesh), 3));
+ // Skinning data is meaningless on a static mesh and confuses the exporter.
+ baked.deleteAttribute('skinIndex');
+ baked.deleteAttribute('skinWeight');
+ // Normals were authored for the bind pose; recompute so the shading
+ // matches the geometry Quick Look actually receives.
+ baked.computeVertexNormals();
+
+ const replacement = new Mesh(baked, mesh.material);
+ replacement.name = mesh.name;
+ replacement.visible = mesh.visible;
+ // applyBoneTransform returns local-space vertices, so the replacement
+ // keeps the original's local transform and the exporter applies it.
+ replacement.position.copy(mesh.position);
+ replacement.quaternion.copy(mesh.quaternion);
+ replacement.scale.copy(mesh.scale);
+
+ const parent = mesh.parent || scene;
+ parent.add(replacement);
+ parent.remove(mesh);
+ }
+}
+
+/** Coerce every material to MeshStandardMaterial, in place. */
+export function coerceMaterialsToStandard(scene) {
+ scene.traverse((obj) => {
+ if (!obj.isMesh) return;
+ const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
+ mats.forEach((m, i) => {
+ if (!m || m.isMeshStandardMaterial) return;
+ const replacement = new MeshStandardMaterial({
+ color: m.color ? m.color.clone() : new Color(0xffffff),
+ map: m.map || null,
+ normalMap: m.normalMap || null,
+ roughness: typeof m.roughness === 'number' ? m.roughness : 0.85,
+ metalness: typeof m.metalness === 'number' ? m.metalness : 0,
+ transparent: !!m.transparent,
+ opacity: typeof m.opacity === 'number' ? m.opacity : 1,
+ side: m.side ?? DoubleSide,
+ });
+ if (Array.isArray(obj.material)) obj.material[i] = replacement;
+ else obj.material = replacement;
+ });
+ });
+}
+
+/** Give every renderable mesh a normal attribute. */
+export function ensureNormals(scene) {
+ scene.traverse((obj) => {
+ if (!obj.isMesh || !obj.geometry) return;
+ if (obj.geometry.getAttribute('normal')) return;
+ if (!obj.geometry.getAttribute('position')) return;
+ obj.geometry.computeVertexNormals();
+ });
+}
+
+/**
+ * Wrap content in a fresh, identity-transform root and a `stage` node that
+ * carries the export's own placement.
+ *
+ * THIS WRAPPER IS NOT TIDINESS, IT IS A CORRECTNESS FIX. `USDZExporter` walks
+ * `scene.children` and writes each node's LOCAL matrix, so the transform on the
+ * object you hand it is never written at all. Set a scale on the root and the
+ * export silently comes out at the original size; set a position and it is
+ * silently dropped. Everything this module needs to place a model (the pinch
+ * scale, the floor offset, the recentre) therefore lives on `stage`, which is a
+ * child and so does get written.
+ *
+ * @param {import('three').Object3D} object
+ * @returns {{root: import('three').Group, stage: import('three').Group}}
+ */
+export function usdzExportRoot(object) {
+ const root = new Group();
+ root.name = 'Root';
+ const stage = new Group();
+ stage.name = 'Model';
+ stage.add(object);
+ root.add(stage);
+ root.updateMatrixWorld(true);
+ return { root, stage };
+}
+
+/** World-space bounds of a prepared export root, or null when it holds nothing. */
+function measure(root) {
+ root.updateMatrixWorld(true);
+ const box = new Box3().setFromObject(root);
+ if (box.isEmpty()) return null;
+ const min = box.min, max = box.max;
+ if (![min.x, min.y, min.z, max.x, max.y, max.z].every(Number.isFinite)) return null;
+ return box;
+}
+
+/**
+ * Stand the model on y=0 with its footprint centred on the origin.
+ *
+ * This is the single thing that decides whether AR Quick Look puts a model on
+ * someone's floor or leaves it hanging in mid-air. Quick Look anchors the
+ * scene's ORIGIN to the horizontal plane it detects and does not look at the
+ * geometry: a GLB authored with its origin at the bounding-box centre arrives
+ * half-buried, one authored around a distant scene origin arrives floating
+ * across the room at eye level, and in both cases the model reads as "not
+ * tracking" because it never touches the ground the person is pointing at.
+ * Neither is a Quick Look bug and no anchoring property fixes it; the content
+ * has to be moved.
+ *
+ * @param {import('three').Group} stage The node from `usdzExportRoot`.
+ * @param {import('three').Group} root
+ * @returns {boolean} false when there was nothing to ground.
+ */
+export function groundOnFloor(stage, root) {
+ const box = measure(root);
+ if (!box) return false;
+ const centre = box.getCenter(new Vector3());
+ stage.position.x -= centre.x;
+ stage.position.y -= box.min.y;
+ stage.position.z -= centre.z;
+ root.updateMatrixWorld(true);
+ return true;
+}
+
+/**
+ * Give the model a believable real-world size.
+ *
+ * USDZ is metres (`metersPerUnit = 1`), and a model authored in centimetres
+ * arrives a hundred times too big. A ten-metre chair cannot sit on a plane
+ * ARKit found in a living room, so Quick Look shows it swimming around the
+ * viewer rather than resting anywhere: the same symptom as a broken anchor,
+ * from a completely different cause.
+ *
+ * Uses the studio's own normalization rule, so a model placed through the
+ * studio and the same model converted straight from its URL land at the same
+ * size. Models already within 2x of a believable size are left exactly as
+ * authored: real furniture scans stay real.
+ *
+ * @param {import('three').Group} stage
+ * @param {import('three').Group} root
+ * @returns {number} the scale applied (1 when the model was already sane).
+ */
+export function fitToRoomScale(stage, root) {
+ const box = measure(root);
+ if (!box) return 1;
+ let skinned = false;
+ root.traverse((o) => { if (o.isSkinnedMesh) skinned = true; });
+ const { scale } = fitTransform(
+ { min: { x: box.min.x, y: box.min.y, z: box.min.z }, max: { x: box.max.x, y: box.max.y, z: box.max.z } },
+ { skinned },
+ );
+ if (!(scale > 0) || scale === 1) return 1;
+ stage.scale.multiplyScalar(scale);
+ root.updateMatrixWorld(true);
+ return scale;
+}
+
+/**
+ * Largest footprint (m) AR Quick Look can be relied on to find a plane for.
+ *
+ * Quick Look does not place a model until ARKit has found a horizontal plane
+ * BIG ENOUGH TO FIT IT. Until then the model hangs aligned to the camera and
+ * travels with the phone, which every person reads as broken tracking rather
+ * than as "still looking". Past roughly this size there is no such plane in an
+ * ordinary room, so the model never lands at all.
+ */
+export const MAX_AR_FOOTPRINT_M = 2.5;
+
+/** Tallest (m) a model can be and still belong in a room with a ceiling. */
+export const MAX_AR_HEIGHT_M = 2.5;
+
+/**
+ * Keep the export inside a size ARKit can actually place.
+ *
+ * A ceiling, not a normalizer: real furniture, a person, a car-door-sized prop
+ * all pass through untouched. It exists because the size someone pinched a
+ * model to is now honoured (it used to be silently dropped), and the studio
+ * lets that reach 4x. Four times a standing avatar is a seven-metre figure that
+ * no living-room floor plane will ever fit.
+ *
+ * @param {import('three').Group} stage
+ * @param {import('three').Group} root
+ * @param {{maxFootprint?: number, maxHeight?: number}} [limits]
+ * @returns {number} the scale applied (1 when it already fit).
+ */
+export function clampToPlaceableSize(stage, root, {
+ maxFootprint = MAX_AR_FOOTPRINT_M, maxHeight = MAX_AR_HEIGHT_M,
+} = {}) {
+ const box = measure(root);
+ if (!box) return 1;
+ const size = box.getSize(new Vector3());
+ const footprint = Math.max(size.x, size.z);
+ // The floor plane has to fit the footprint; the room has to fit the height.
+ // Whichever is tighter decides.
+ const scale = Math.min(
+ footprint > 0 ? maxFootprint / footprint : 1,
+ size.y > 0 ? maxHeight / size.y : 1,
+ );
+ if (!(scale < 1) || !Number.isFinite(scale)) return 1;
+ stage.scale.multiplyScalar(scale);
+ root.updateMatrixWorld(true);
+ return scale;
+}
+
+/**
+ * Convert a loaded scene to USDZ bytes. Mutates the scene, so pass a clone or a
+ * scene you are done with.
+ *
+ * The model is always grounded before it is written: see `groundOnFloor` for
+ * why that, and not any anchoring flag, is what makes AR Quick Look put it on
+ * the floor.
+ *
+ * @param {import('three').Object3D} scene
+ * @param {object} [options]
+ * @param {boolean} [options.fit] Normalize an absurdly authored size to a
+ * believable real-world one. On for a raw file straight off the network, off
+ * for a model the studio has already normalized and the person has resized.
+ * Everything else is passed through to three's USDZExporter.
+ * @returns {Promise<Blob>} model/vnd.usdz+zip
+ */
+export async function sceneToUsdzBlob(scene, { fit = false, ...options } = {}) {
+ const { root, stage } = usdzExportRoot(scene);
+ bakeSkinnedMeshes(root);
+ coerceMaterialsToStandard(root);
+ ensureNormals(root);
+ // Size first, then stand it on the floor: grounding measures the model at the
+ // size it will actually be exported at, and a model too big for any plane in
+ // the room never gets placed on one at all.
+ if (fit) fitToRoomScale(stage, root);
+ clampToPlaceableSize(stage, root);
+ groundOnFloor(stage, root);
+ // Loaded on demand: nobody who never taps "Place in your space" should pay
+ // for the exporter.
+ const { USDZExporter } = await import('three/addons/exporters/USDZExporter.js');
+ const bytes = await new USDZExporter().parseAsync(root, {
+ // Quick Look is the only thing that ever reads these bytes, and it applies
+ // texture repeat and offset in a different order to every other USD
+ // renderer (Apple FB10036297). This flag pre-compensates, so a model with
+ // tiled textures does not arrive in someone's room with the tiling
+ // visibly wrong. It is a no-op on the untiled default.
+ quickLookCompatible: true,
+ // Rest the model on the horizontal surface the person points at, which is
+ // what "place it on your floor" means. Stated rather than left to the
+ // exporter's default so a future default cannot quietly change it.
+ includeAnchoringProperties: true,
+ ar: { anchoring: { type: 'plane' }, planeAnchoring: { alignment: 'horizontal' } },
+ ...options,
+ });
+ return new Blob([bytes], { type: 'model/vnd.usdz+zip' });
+}
+
+/**
+ * Convert an object that is ALREADY in a live scene to USDZ, without touching
+ * the network.
+ *
+ * This is the fast path, and on a phone the difference is the whole feature.
+ * Re-fetching and re-parsing the GLB costs seconds and a second CORS round trip
+ * on a file the page has already decoded; worse, it exports the model's rest
+ * pose at its authored size. Cloning the live object exports what the person is
+ * actually looking at: the current animation pose, and the size they pinched it
+ * to, which is the size Quick Look will stand in their room.
+ *
+ * The clone is what gets baked and mutated, so the live scene is untouched.
+ * Position and yaw are zeroed because the AR viewer re-anchors the model to the
+ * surface the user picks; carrying the studio's floor coordinates through would
+ * only offset it from their own reticle. World scale is preserved: it is the
+ * real-world size, and `sceneToUsdzBlob` is what makes it survive the export.
+ *
+ * No `fit`: this model went through the studio's own normalization when it was
+ * placed, and the size on top of that is the one the person pinched.
+ *
+ * @param {import('three').Object3D} object
+ * @returns {Promise<Blob>} model/vnd.usdz+zip
+ */
+export async function objectToUsdzBlob(object) {
+ object.updateMatrixWorld(true);
+ // SkeletonUtils.clone rebinds skinned meshes to the cloned bones and copies
+ // their current transforms, so the pose survives; Object3D.clone does not.
+ const copy = cloneSkinnedScene(object);
+ copy.position.set(0, 0, 0);
+ copy.rotation.set(0, 0, 0);
+ copy.scale.copy(object.getWorldScale(new Vector3()));
+ copy.updateMatrixWorld(true);
+ return sceneToUsdzBlob(copy);
+}
+
+/**
+ * Fetch a GLB and convert it to a USDZ blob.
+ *
+ * @param {string} glbUrl
+ * @param {{signal?: AbortSignal, onProgress?: (stage: string) => void}} [opts]
+ * @returns {Promise<Blob>}
+ */
+export async function glbUrlToUsdzBlob(glbUrl, { signal, onProgress } = {}) {
+ onProgress?.('download');
+ const res = await fetch(glbUrl, { signal });
+ if (!res.ok) throw new Error(`model fetch ${res.status}`);
+ const buffer = await res.arrayBuffer();
+
+ onProgress?.('parse');
+ // Awaited rather than taken synchronously: a meshopt-compressed GLB handed to
+ // a loader whose decoder is still downloading fails on a valid file.
+ const loader = await sharedGLTFLoaderReady();
+ const gltf = await new Promise((resolve, reject) => {
+ loader.parse(buffer, '', resolve, reject);
+ });
+ const scene = gltf.scene || gltf.scenes?.[0];
+ if (!scene) throw new Error('that model contains no scene');
+
+ onProgress?.('convert');
+ // Straight off the network and never seen by the studio's normalizer, so this
+ // is the one path that has to defend against a model authored in centimetres.
+ return sceneToUsdzBlob(scene, { fit: true });
+}
diff --git a/packages/ar-studio/templates/react/README.md b/packages/ar-studio/templates/react/README.md
new file mode 100644
index 000000000..85af6d33d
--- /dev/null
+++ b/packages/ar-studio/templates/react/README.md
@@ -0,0 +1,26 @@
+# React component
+
+Copy `src/ArStudio.jsx` into your app and install the two packages:
+
+```bash
+npm i 3d-ar-studio three
+```
+
+```jsx
+import ArStudio from './ArStudio';
+
+export default function Page() {
+ return (
+ <ArStudio
+ options={{ branding: { title: 'Acme AR' }, assets: 'https://your.cdn/models.json' }}
+ onReady={(studio) => studio.on('add', ({ placement }) => console.log(placement.title))}
+ style={{ height: '80vh' }}
+ />
+ );
+}
+```
+
+The component mounts the studio once and destroys it on unmount, which releases
+the camera stream and the WebGL context. Everything else is driven through the
+instance handed to `onReady`: `addModel`, `clear`, `getScene`, `setScene`,
+`shareUrl`, `generate`, `openRoom`.
diff --git a/packages/ar-studio/templates/react/src/ArStudio.jsx b/packages/ar-studio/templates/react/src/ArStudio.jsx
new file mode 100644
index 000000000..e569008f3
--- /dev/null
+++ b/packages/ar-studio/templates/react/src/ArStudio.jsx
@@ -0,0 +1,27 @@
+import { useEffect, useRef } from 'react';
+import { createArStudio } from '3d-ar-studio';
+
+/**
+ * The AR studio as a React component.
+ *
+ * The studio owns a WebGL context and a camera stream, so it is mounted once per
+ * container and torn down on unmount. `options` is read when the studio mounts;
+ * to change something later, reach for the instance through `onReady`.
+ */
+export default function ArStudio({ options = {}, onReady, style, className }) {
+ const host = useRef(null);
+ const ready = useRef(onReady);
+ ready.current = onReady;
+
+ useEffect(() => {
+ if (!host.current) return undefined;
+ const studio = createArStudio(host.current, { fullscreen: false, ...options });
+ ready.current?.(studio);
+ return () => studio.destroy();
+ // Options are intentionally not a dependency: re-creating a WebGL context
+ // on every render would be ruinous. Drive changes through the instance.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return <div ref={host} className={className} style={{ position: 'relative', minHeight: '70vh', ...style }} />;
+}
diff --git a/packages/ar-studio/templates/static/.nojekyll b/packages/ar-studio/templates/static/.nojekyll
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/ar-studio/templates/static/README.md b/packages/ar-studio/templates/static/README.md
new file mode 100644
index 000000000..5bbd1031d
--- /dev/null
+++ b/packages/ar-studio/templates/static/README.md
@@ -0,0 +1,41 @@
+# __TITLE__
+
+An augmented-reality studio, built with [3D AR Studio](https://github.com/nirholas/3D-AR-Studio).
+Open `index.html` on a phone, tap **Camera**, and the models stand on your actual floor.
+
+## Run it locally
+
+```bash
+npx 3d-ar-studio dev
+```
+
+Then open the printed URL. Camera and WebXR need a secure context, so use `https://`
+or `localhost` (both count as secure); a bare LAN IP over `http://` will not get camera access.
+
+## Publish it
+
+Any static host works, because this is one HTML file with no build step.
+
+**GitHub Pages, in one command:**
+
+```bash
+npx 3d-ar-studio deploy
+```
+
+That creates the repository if it does not exist, pushes, and turns Pages on.
+
+**By hand:** commit this folder, then in your repository go to
+*Settings → Pages* and serve from the branch root.
+
+## Point it at your own models
+
+Add an `assets` option in `index.html`:
+
+```js
+createArStudio('#stage', { assets: 'https://your.cdn/models.json' })
+```
+
+The catalogue can be a bare array or an object wrapping one, and each entry needs
+only a model URL (`src`, `url`, `glb`, or `glb_url`); a `title` and `poster` make
+the tray look better. Full details:
+<https://github.com/nirholas/3D-AR-Studio#your-own-models>
diff --git a/packages/ar-studio/templates/static/index.html b/packages/ar-studio/templates/static/index.html
new file mode 100644
index 000000000..89a758c62
--- /dev/null
+++ b/packages/ar-studio/templates/static/index.html
@@ -0,0 +1,35 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<title>__TITLE__</title>
+<meta name="description" content="Place 3D models in your real room, straight from the browser." />
+<meta property="og:title" content="__TITLE__" />
+<meta property="og:description" content="Place 3D models in your real room, straight from the browser." />
+<style>
+ html, body { margin: 0; height: 100%; background: #06070a; color: #ecedf2;
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
+ #stage { position: fixed; inset: 0; }
+ noscript { display: block; padding: 40px; text-align: center; color: #9aa0af; line-height: 1.6; }
+</style>
+</head>
+<body>
+<div id="stage"></div>
+<noscript>This page needs JavaScript to render 3D models in your space.</noscript>
+<script type="module">
+import { createArStudio } from 'https://unpkg.com/3d-ar-studio/dist/ar-studio.min.js';
+
+createArStudio('#stage', {
+ branding: { title: '__TITLE__', accent: '__ACCENT__' },
+
+ // Where models come from. Leave it out for the free public-domain library,
+ // or point it at your own JSON catalogue:
+ // assets: 'https://your.cdn/models.json',
+ // See https://github.com/nirholas/3D-AR-Studio#your-own-models
+
+ fullscreen: false,
+});
+</script>
+</body>
+</html>
diff --git a/packages/ar-studio/templates/vite/README.md b/packages/ar-studio/templates/vite/README.md
new file mode 100644
index 000000000..d95fc6916
--- /dev/null
+++ b/packages/ar-studio/templates/vite/README.md
@@ -0,0 +1,23 @@
+# __TITLE__
+
+An augmented-reality studio built with [3D AR Studio](https://github.com/nirholas/3D-AR-Studio)
+and bundled with Vite, so `three` is shared with the rest of your app instead of
+being downloaded twice.
+
+```bash
+npm install
+npm run dev # http://localhost:5173
+npm run build # static output in dist/
+```
+
+Camera and WebXR need a secure context. `localhost` counts as one; to test on a
+phone over your LAN, run `npm run dev -- --host` behind an https tunnel.
+
+## Point it at your own models
+
+```js
+createArStudio('#stage', { assets: 'https://your.cdn/models.json' })
+```
+
+See <https://github.com/nirholas/3D-AR-Studio#your-own-models> for every accepted
+catalogue shape, and for writing a source of your own.
diff --git a/packages/ar-studio/templates/vite/index.html b/packages/ar-studio/templates/vite/index.html
new file mode 100644
index 000000000..660317eea
--- /dev/null
+++ b/packages/ar-studio/templates/vite/index.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <title>__TITLE__</title>
+ <style>
+ html, body { margin: 0; height: 100%; background: #06070a; }
+ #stage { position: fixed; inset: 0; }
+ </style>
+</head>
+<body>
+ <div id="stage"></div>
+ <script type="module" src="/src/main.js"></script>
+</body>
+</html>
diff --git a/packages/ar-studio/templates/vite/package.json b/packages/ar-studio/templates/vite/package.json
new file mode 100644
index 000000000..4c8c5e646
--- /dev/null
+++ b/packages/ar-studio/templates/vite/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "__SLUG__",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "build": "vite build",
+ "preview": "vite preview"
+ },
+ "dependencies": {
+ "3d-ar-studio": "^0.1.0",
+ "three": "^0.184.0"
+ },
+ "devDependencies": {
+ "vite": "^6.0.0"
+ }
+}
diff --git a/packages/ar-studio/templates/vite/src/main.js b/packages/ar-studio/templates/vite/src/main.js
new file mode 100644
index 000000000..390951bdc
--- /dev/null
+++ b/packages/ar-studio/templates/vite/src/main.js
@@ -0,0 +1,11 @@
+import { createArStudio } from '3d-ar-studio';
+
+const studio = createArStudio('#stage', {
+ branding: { title: '__TITLE__', accent: '__ACCENT__' },
+ // assets: 'https://your.cdn/models.json',
+ fullscreen: false,
+});
+
+// Everything the studio does is observable.
+studio.on('add', ({ placement }) => console.log('placed', placement.title));
+studio.on('generate', ({ model }) => console.log('generated', model.src));
diff --git a/packages/ar-studio/test/ar-launch.test.mjs b/packages/ar-studio/test/ar-launch.test.mjs
new file mode 100644
index 000000000..926d0ce35
--- /dev/null
+++ b/packages/ar-studio/test/ar-launch.test.mjs
@@ -0,0 +1,69 @@
+// AR launch routing decides which native viewer a person's phone opens. Getting
+// it wrong is invisible on the developer's laptop and total on the user's phone,
+// so every branch is pinned here.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import {
+ assertArAssetUrl, buildArLaunchUrl, buildSceneViewerUrl, buildViewerUrl,
+ detectArTarget, planArLaunch, ArUrlError,
+} from '../src/ar-launch.js';
+
+const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1';
+const PIXEL = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36';
+const MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';
+
+test('devices are classified from the User-Agent', () => {
+ assert.equal(detectArTarget(IPHONE), 'ios');
+ assert.equal(detectArTarget(PIXEL), 'android');
+ assert.equal(detectArTarget(MAC), 'desktop');
+ assert.equal(detectArTarget(''), 'desktop');
+ assert.equal(detectArTarget(undefined), 'desktop');
+});
+
+test('only an https .glb or .gltf is ever handed to a device AR intent', () => {
+ assert.equal(assertArAssetUrl('https://a.com/x.glb'), 'https://a.com/x.glb');
+ assert.equal(assertArAssetUrl('https://a.com/x.gltf?v=2'), 'https://a.com/x.gltf?v=2');
+ for (const [bad, code] of [
+ ['http://a.com/x.glb', 'not_https'],
+ ['https://a.com/x.png', 'not_glb'],
+ ['not a url', 'invalid_url'],
+ ]) {
+ assert.throws(() => assertArAssetUrl(bad), (err) => err instanceof ArUrlError && err.code === code, bad);
+ }
+});
+
+test('Android gets a Scene Viewer redirect for a prop', () => {
+ const plan = planArLaunch({ glbUrl: 'https://a.com/x.glb', userAgent: PIXEL, title: 'Crate' });
+ assert.equal(plan.target, 'android');
+ assert.equal(plan.action, 'redirect');
+ assert.match(plan.sceneViewerUrl, /^intent:\/\/arvr\.google\.com\/scene-viewer\/1\.2\?/);
+ // The browser fallback keeps a device without ARCore out of an error screen.
+ assert.match(plan.sceneViewerUrl, /S\.browser_fallback_url=/);
+});
+
+test('iOS and desktop get the launch page rather than a redirect', () => {
+ assert.equal(planArLaunch({ glbUrl: 'https://a.com/x.glb', userAgent: IPHONE }).action, 'page');
+ assert.equal(planArLaunch({ glbUrl: 'https://a.com/x.glb', userAgent: MAC }).action, 'page');
+});
+
+test('a rigged avatar always gets the page, so the animated path stays reachable', () => {
+ const plan = planArLaunch({ glbUrl: 'https://a.com/hero.glb', userAgent: PIXEL, live: true });
+ assert.equal(plan.action, 'page');
+ assert.match(plan.launchUrl, /kind=avatar/);
+});
+
+test('links are built against the configured origin', () => {
+ assert.equal(
+ buildViewerUrl('https://acme.com/', 'https://a.com/x.glb', 'Crate'),
+ 'https://acme.com/viewer?src=https%3A%2F%2Fa.com%2Fx.glb&title=Crate',
+ );
+ assert.match(buildArLaunchUrl('https://acme.com', 'https://a.com/x.glb'), /^https:\/\/acme\.com\/api\/ar\?src=/);
+ // A host running its own launcher points the endpoint wherever it likes.
+ assert.match(
+ buildArLaunchUrl('https://acme.com', 'https://a.com/x.glb', '', { endpoint: 'https://acme.com/ar/open' }),
+ /^https:\/\/acme\.com\/ar\/open\?src=/,
+ );
+ assert.ok(!buildSceneViewerUrl('https://a.com/x.glb').includes('title='));
+});
diff --git a/packages/ar-studio/test/config-sources.test.mjs b/packages/ar-studio/test/config-sources.test.mjs
new file mode 100644
index 000000000..1a36d3e3d
--- /dev/null
+++ b/packages/ar-studio/test/config-sources.test.mjs
@@ -0,0 +1,102 @@
+// Configuration and asset sources: the two surfaces a host actually touches.
+// The URL-override path is the one that takes untrusted input, so it gets the
+// most attention here.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { DEFAULTS, mergeConfig, resolveConfig, safeUrl } from '../src/config.js';
+import { resolveSources } from '../src/sources/index.js';
+import { catalogueItems, filenameTitle, normalizeCatalogue } from '../src/sources/manifest.js';
+import { staticSource } from '../src/sources/static.js';
+import { cdnUrl } from '../src/sources/three-ws.js';
+
+test('mergeConfig deep-merges objects and replaces arrays', () => {
+ const merged = mergeConfig(
+ { a: { b: 1, c: 2 }, list: [1, 2] },
+ { a: { c: 3 }, list: [9] },
+ );
+ assert.deepEqual(merged, { a: { b: 1, c: 3 }, list: [9] });
+ // The base is never mutated.
+ assert.deepEqual(mergeConfig({ x: 1 }, undefined), { x: 1 });
+});
+
+test('safeUrl accepts https and site-relative paths only', () => {
+ assert.equal(safeUrl('https://a.com/m.json'), 'https://a.com/m.json');
+ assert.equal(safeUrl('/models.json'), '/models.json');
+ assert.equal(safeUrl('http://a.com/m.json'), null);
+ assert.equal(safeUrl('javascript:alert(1)'), null);
+ assert.equal(safeUrl('//evil.com/m.json'), null);
+});
+
+test('URL parameters can retarget the catalogue, but only over https', () => {
+ assert.equal(resolveConfig({}, '?assets=https://a.com/m.json').assets, 'https://a.com/m.json');
+ assert.equal(resolveConfig({}, '?assets=http://a.com/m.json').assets, DEFAULTS.assets);
+ assert.equal(resolveConfig({}, '?assets=javascript:alert(1)').assets, DEFAULTS.assets);
+});
+
+test('a host can switch URL overrides off entirely', () => {
+ const cfg = resolveConfig({ allowUrlOverride: false }, '?assets=https://a.com/m.json&src=https://a.com/x.glb&room=ABC234');
+ assert.equal(cfg.assets, DEFAULTS.assets);
+ assert.deepEqual(cfg.urlModels, []);
+ assert.equal(cfg.urlRoom, '');
+});
+
+test('deep-linked models are paired with titles and validated', () => {
+ const cfg = resolveConfig({}, '?src=https://a.com/1.glb&title=One&src=http://a.com/2.glb&title=Two');
+ assert.deepEqual(cfg.urlModels, [{ src: 'https://a.com/1.glb', title: 'One' }]);
+});
+
+test('resolveSources turns every accepted shape into a tab list', () => {
+ assert.deepEqual(resolveSources('three.ws', {}).map((s) => s.id), ['recent', 'objects', 'link']);
+ assert.deepEqual(resolveSources('https://a.com/m.json', {}).map((s) => s.id), ['models', 'link']);
+ assert.deepEqual(
+ resolveSources(['recent', staticSource({ id: 'ours', items: [] }), 'objects'], {}).map((s) => s.id),
+ ['recent', 'ours', 'objects', 'link'],
+ );
+ // A link tab is always available, and never duplicated.
+ assert.equal(resolveSources(['link', 'link'], {}).filter((s) => s.id === 'link').length, 1);
+ assert.throws(() => resolveSources('nonsense', {}), /unknown asset source/);
+});
+
+test('catalogues are read in every common shape', () => {
+ const entry = { url: 'https://a.com/x.glb', name: 'X' };
+ for (const shape of [[entry], { items: [entry] }, { objects: [entry] }, { creations: [entry] }, { models: [entry] }]) {
+ assert.equal(catalogueItems(shape).length, 1, JSON.stringify(shape));
+ }
+ assert.deepEqual(catalogueItems({ nothing: true }), []);
+});
+
+test('catalogue entries are normalized and hostile URLs dropped', () => {
+ const items = normalizeCatalogue({
+ objects: [
+ { url: 'https://a.com/wrench.glb', label: 'Wrench', thumb: 'https://a.com/w.png', categories: ['tools'], tags: ['metal'] },
+ { glb_url: 'https://a.com/lamp.glb', prompt: 'a brass lamp' },
+ { url: 'javascript:alert(1)', name: 'Bad' },
+ { name: 'No URL at all' },
+ ],
+ });
+ assert.equal(items.length, 2);
+ assert.equal(items[0].title, 'Wrench');
+ assert.ok(items[0].keywords.includes('tools') && items[0].keywords.includes('metal'));
+ assert.equal(items[1].title, 'a brass lamp');
+});
+
+test('a rewriteUrl hook can route a catalogue through another host', () => {
+ const items = normalizeCatalogue([{ url: 'https://pub-abc123.r2.dev/objects/x.glb' }], {
+ rewriteUrl: (u) => cdnUrl(u, 'https://three.ws'),
+ });
+ assert.equal(items[0].src, 'https://three.ws/cdn/objects/x.glb');
+ // Anything that is not a bucket URL passes through untouched.
+ assert.equal(cdnUrl('https://acme.com/x.glb'), 'https://acme.com/x.glb');
+});
+
+test('filenames become readable labels when a catalogue has no titles', () => {
+ assert.equal(filenameTitle('https://a.com/alarm_clock_01.glb'), 'Alarm clock 01');
+ assert.equal(filenameTitle('https://a.com/x.glb?v=2'), 'X');
+});
+
+test('staticSource normalizes what it is given, once', async () => {
+ const source = staticSource({ items: [{ src: 'https://a.com/x.glb', title: 'X' }, { src: 'ftp://nope' }] });
+ assert.deepEqual(await source.list(), [{ src: 'https://a.com/x.glb', title: 'X', poster: '', keywords: 'x' }]);
+});
diff --git a/packages/ar-studio/test/forge-rooms.test.mjs b/packages/ar-studio/test/forge-rooms.test.mjs
new file mode 100644
index 000000000..1442cc30b
--- /dev/null
+++ b/packages/ar-studio/test/forge-rooms.test.mjs
@@ -0,0 +1,154 @@
+// Generation and shared-room plumbing: the safety gate, the pending-job loop,
+// and the coordinate frame two devices have to agree on.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { checkPromptSafety, validatePrompt } from '../src/forge/safety.js';
+import { stageNarration, promptTitle, laneLabel } from '../src/forge/narration.js';
+import { createForgeClient, ForgeError } from '../src/forge/client.js';
+import { unwrapToolResult } from '../src/forge/mcp-http.js';
+import {
+ generateRoomCode, normalizeRoomCode, roomKeyForCode, roomShareUrl,
+ localToShared, sharedToLocal, normDeg, normRad,
+} from '../src/studio/coords.js';
+import {
+ createPinchState, pinchStart, pinchMove, pinchEnd, clampPinScale,
+ PINCH_SCALE_MAX, PINCH_SCALE_MIN, PINCH_DEADZONE_PX,
+} from '../src/studio/pinch.js';
+
+test('the safety gate refuses the highest-harm categories and lets creative work through', () => {
+ for (const allowed of ['a brass desk lamp', 'a knight with a sword', 'an assassin bug', 'a CP/M terminal', 'a scunthorpe road sign']) {
+ assert.equal(checkPromptSafety(allowed).allowed, true, allowed);
+ }
+ for (const [prompt, category] of [['a nude figure', 'sexual'], ['a dismembered body', 'gore'], ['a swastika banner', 'hate'], ['an AK-47', 'weapon_drug']]) {
+ const verdict = checkPromptSafety(prompt);
+ assert.equal(verdict.allowed, false, prompt);
+ assert.equal(verdict.category, category);
+ assert.ok(verdict.message.length > 20, 'a refusal must say what to do instead');
+ }
+});
+
+test('validatePrompt rejects the too-short as well as the disallowed', () => {
+ assert.equal(validatePrompt('ab').ok, false);
+ assert.equal(validatePrompt(' a lamp ').prompt, 'a lamp');
+ assert.equal(validatePrompt('a nude figure').ok, false);
+});
+
+test('narration never invents a stage or a number', () => {
+ assert.match(stageNarration({ status: 'queued' }), /Queued on the free lane/);
+ assert.match(stageNarration({ status: 'queued', etaSeconds: 42 }), /~42s/);
+ // No ETA reported means no ETA shown.
+ assert.ok(!stageNarration({ status: 'running' }).includes('~'));
+ assert.match(stageNarration({ status: 'queued', coldStart: true, coldSeconds: 30, backend: 'nvidia' }), /Waking up the free NVIDIA NIM GPU worker \(about 30s\)/);
+ assert.match(stageNarration({ status: 'failed' }), /try a more concrete/);
+ assert.equal(laneLabel('nvidia'), 'free NVIDIA NIM');
+ assert.equal(laneLabel('nope'), null);
+});
+
+test('a card label is the first clause of a long prompt, never a mid-word cut', () => {
+ assert.equal(promptTitle('a brass desk lamp, mid-century, glossy'), 'a brass desk lamp');
+ assert.ok(!promptTitle('a'.repeat(80)).includes(' '));
+ assert.equal(promptTitle(''), 'Model');
+});
+
+test('the forge client polls a pending job through check_job until it lands', async () => {
+ const calls = [];
+ const fetchImpl = async (_url, init) => {
+ const body = JSON.parse(init.body);
+ calls.push(body.params.name);
+ const result = calls.length === 1
+ ? { structuredContent: { status: 'pending', jobId: 'job-1', etaRemainingSeconds: 5 }, content: [] }
+ : { structuredContent: { glbUrl: 'https://cdn.example.com/out.glb', viewerUrl: 'https://v/x', arUrl: 'https://a/x' }, content: [] };
+ return {
+ ok: true,
+ headers: new Map([['content-type', 'application/json']]),
+ json: async () => ({ jsonrpc: '2.0', id: body.id, result }),
+ };
+ };
+ const client = createForgeClient({ pollMs: 1, fetchImpl });
+ const seen = [];
+ const model = await client.generate('a brass desk lamp', { onProgress: (s) => seen.push(s.status) });
+ assert.deepEqual(calls, ['forge_free', 'check_job']);
+ assert.equal(model.src, 'https://cdn.example.com/out.glb');
+ assert.ok(seen.includes('submitting') && seen.includes('queued') && seen.includes('done'));
+});
+
+test('a generator error surfaces as a ForgeError with the server\'s own message', async () => {
+ const fetchImpl = async (_url, init) => ({
+ ok: true,
+ headers: new Map([['content-type', 'application/json']]),
+ json: async () => ({
+ jsonrpc: '2.0',
+ id: JSON.parse(init.body).id,
+ result: { isError: true, structuredContent: { message: 'The 3D generator is busy right now.' }, content: [] },
+ }),
+ });
+ const client = createForgeClient({ fetchImpl });
+ await assert.rejects(
+ client.generate('a brass desk lamp'),
+ (err) => err instanceof ForgeError && /busy/.test(err.message),
+ );
+});
+
+test('the client speaks the SSE half of streamable HTTP too', async () => {
+ const fetchImpl = async (_url, init) => ({
+ ok: true,
+ headers: new Map([['content-type', 'text/event-stream']]),
+ text: async () => `event: message\ndata: ${JSON.stringify({
+ jsonrpc: '2.0',
+ id: JSON.parse(init.body).id,
+ result: { structuredContent: { glbUrl: 'https://cdn.example.com/sse.glb' }, content: [] },
+ })}\n\n`,
+ });
+ const client = createForgeClient({ fetchImpl });
+ assert.equal((await client.generate('a teapot')).src, 'https://cdn.example.com/sse.glb');
+});
+
+test('unwrapToolResult pulls out both halves of a tool result', () => {
+ const unwrapped = unwrapToolResult({ content: [{ type: 'text', text: 'hi' }], structuredContent: { a: 1 } });
+ assert.deepEqual(unwrapped, { structured: { a: 1 }, text: 'hi', isError: false });
+});
+
+test('room codes are unambiguous, and typos are rejected rather than guessed at', () => {
+ const code = generateRoomCode(() => 0.5);
+ assert.equal(code.length, 6);
+ assert.ok(!/[01OIL]/.test(code), 'the alphabet must have no look-alike glyphs');
+ assert.equal(normalizeRoomCode(' abc-234 '), 'ABC234');
+ assert.equal(normalizeRoomCode('https://acme.com/ar/?room=ABC234'), 'ABC234');
+ assert.equal(normalizeRoomCode('ABC23'), '', 'too short is a mistype, not a near miss');
+ assert.equal(normalizeRoomCode('ABC2O4'), '', 'a letter the generator never emits is a mistype');
+ assert.equal(roomKeyForCode('abc234'), 'c-ABC234');
+ assert.equal(roomShareUrl('https://acme.com/ar/', 'abc234'), 'https://acme.com/ar/?room=ABC234');
+ assert.equal(roomShareUrl('https://acme.com/ar/', 'nope'), 'https://acme.com/ar/');
+});
+
+test('a transform survives the trip through the shared logical frame', () => {
+ const local = { x: 1.5, z: -2.25, yaw: Math.PI / 3, scale: 1.4, height: 1.7 };
+ const back = sharedToLocal(localToShared(local));
+ assert.ok(Math.abs(back.x - local.x) < 1e-9);
+ assert.ok(Math.abs(back.z - local.z) < 1e-9);
+ assert.ok(Math.abs(back.yaw - local.yaw) < 1e-9);
+ assert.equal(back.scale, 1.4);
+ // Forward (-z) is north, so a model in front of you is north of you.
+ assert.ok(localToShared({ x: 0, z: -2, yaw: 0 }).relNorth > 0);
+ assert.equal(normDeg(-90), 270);
+ assert.ok(Math.abs(normRad(-Math.PI) - Math.PI) < 1e-9);
+});
+
+test('pinch scaling composes across gestures and clamps at both ends', () => {
+ const p = createPinchState();
+ assert.equal(pinchStart(p, 10, 1), false, 'a palm-width spread is not a pinch');
+ assert.equal(pinchStart(p, 100, 1), true);
+ assert.ok(Math.abs(pinchMove(p, 200) - 2) < 1e-9);
+ assert.equal(pinchEnd(p), 2);
+ // A second pinch starts from where the first left off.
+ pinchStart(p, 100, 2);
+ assert.ok(Math.abs(pinchMove(p, 150) - 3) < 1e-9);
+ assert.equal(pinchMove(p, 100000), PINCH_SCALE_MAX);
+ assert.equal(pinchMove(p, 1), PINCH_SCALE_MIN);
+ assert.equal(pinchEnd(createPinchState()), null, 'a plain tap has nothing to persist');
+ assert.equal(clampPinScale(null), 1);
+ assert.equal(clampPinScale(99), PINCH_SCALE_MAX);
+ assert.ok(PINCH_DEADZONE_PX > 0);
+});
diff --git a/packages/ar-studio/test/mcp.test.mjs b/packages/ar-studio/test/mcp.test.mjs
new file mode 100644
index 000000000..a4c7e2ad0
--- /dev/null
+++ b/packages/ar-studio/test/mcp.test.mjs
@@ -0,0 +1,152 @@
+// The MCP tools are the agent-facing contract. These tests run them against
+// injected fakes so the suite stays offline and deterministic; the shapes they
+// assert are the ones the real server returns.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { createTools, readEnv, renderPage, sceneUrl } from '../mcp/tools.js';
+import { createServer } from '../mcp/index.js';
+
+const ENV = readEnv({ AR_STUDIO_PAGE_URL: 'https://acme.com/ar/', AR_STUDIO_ORIGIN: 'https://three.ws' });
+const byName = (tools, name) => tools.find((t) => t.name === name);
+
+test('every tool is registered with a schema and honest annotations', () => {
+ const tools = createTools({ env: ENV });
+ assert.deepEqual(tools.map((t) => t.name).sort(), [
+ 'check_generation', 'compose_ar_scene', 'create_ar_page',
+ 'export_ar', 'generate_3d_model', 'search_models',
+ ]);
+ for (const tool of tools) {
+ assert.ok(tool.description.length > 80, `${tool.name} needs a description an agent can act on`);
+ assert.ok(tool.schema && typeof tool.schema === 'object', `${tool.name} needs an input schema`);
+ assert.equal(typeof tool.annotations.readOnlyHint, 'boolean', `${tool.name} must declare readOnlyHint`);
+ }
+ // Only generation is a write; everything else must say so.
+ const writes = tools.filter((t) => !t.annotations.readOnlyHint).map((t) => t.name);
+ assert.deepEqual(writes, ['generate_3d_model']);
+});
+
+test('the server builds and registers its tools', async () => {
+ const server = createServer({ env: { AR_STUDIO_PAGE_URL: 'https://acme.com/ar/' } });
+ assert.ok(server);
+});
+
+test('compose_ar_scene returns one link that carries the whole arrangement', async () => {
+ const tool = byName(createTools({ env: ENV }), 'compose_ar_scene');
+ const res = await tool.run({
+ models: [
+ { src: 'https://a.com/lamp.glb', title: 'Lamp', x: 0, z: -1.4 },
+ { src: 'https://a.com/fern.glb', title: 'Fern', x: 0.9, z: -1.2, scale: 1.3 },
+ ],
+ title: 'Living room',
+ });
+ assert.ok(!res.isError);
+ assert.match(res.structuredContent.sceneUrl, /^https:\/\/acme\.com\/ar\/\?src=.*#s=/);
+ assert.equal(res.structuredContent.models.length, 2);
+ assert.equal(res.structuredContent.models[1].scale, 1.3);
+});
+
+test('compose_ar_scene skips unusable models and says so, but still builds a scene', async () => {
+ const tool = byName(createTools({ env: ENV }), 'compose_ar_scene');
+ const res = await tool.run({ models: [{ src: 'https://a.com/ok.glb' }, { src: 'javascript:alert(1)' }] });
+ assert.ok(!res.isError);
+ assert.equal(res.structuredContent.models.length, 1);
+ assert.equal(res.structuredContent.skipped.length, 1);
+ assert.match(res.content[0].text, /skipped/);
+});
+
+test('compose_ar_scene fails cleanly when nothing is placeable', async () => {
+ const tool = byName(createTools({ env: ENV }), 'compose_ar_scene');
+ const res = await tool.run({ models: [{ src: 'http://a.com/x.glb' }] });
+ assert.equal(res.isError, true);
+ assert.match(res.structuredContent.message, /https \.glb/);
+});
+
+test('export_ar names the viewer the caller\'s device will actually open', async () => {
+ const tool = byName(createTools({ env: ENV }), 'export_ar');
+ const res = await tool.run({
+ glb_url: 'https://a.com/x.glb',
+ title: 'Crate',
+ user_agent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) Safari/604.1',
+ });
+ assert.equal(res.structuredContent.target, 'ios');
+ assert.match(res.content[0].text, /Quick Look/);
+ assert.ok(res.structuredContent.arLaunchUrl.startsWith('https://three.ws/api/ar?src='));
+});
+
+test('export_ar refuses a URL no AR viewer could open', async () => {
+ const tool = byName(createTools({ env: ENV }), 'export_ar');
+ const res = await tool.run({ glb_url: 'https://a.com/photo.png' });
+ assert.equal(res.isError, true);
+ assert.match(res.structuredContent.message, /\.glb/);
+});
+
+test('generate_3d_model refuses a disallowed prompt before doing any work', async () => {
+ let called = false;
+ const forge = { generate: async () => { called = true; }, mcp: {} };
+ const tool = byName(createTools({ env: ENV, forge }), 'generate_3d_model');
+ const res = await tool.run({ prompt: 'a nude figure' });
+ assert.equal(res.isError, true);
+ assert.equal(called, false, 'the safety gate must run before the generator');
+});
+
+test('generate_3d_model hands back links, not just a file', async () => {
+ const forge = {
+ generate: async (prompt) => ({ src: 'https://cdn.example.com/out.glb', title: 'A lamp', prompt, rigged: false }),
+ mcp: {},
+ };
+ const tool = byName(createTools({ env: ENV, forge }), 'generate_3d_model');
+ const res = await tool.run({ prompt: 'a brass desk lamp' });
+ assert.ok(!res.isError);
+ const c = res.structuredContent;
+ assert.equal(c.glbUrl, 'https://cdn.example.com/out.glb');
+ assert.ok(c.arLaunchUrl.includes('/api/ar?src='));
+ assert.ok(c.studioUrl.startsWith('https://acme.com/ar/?src='));
+ assert.match(res.content[0].text, /Open it in your room/);
+});
+
+test('search_models filters a real catalogue payload', async (t) => {
+ const catalogue = {
+ objects: [
+ { url: 'https://pub-abc.r2.dev/o/wrench.glb', label: 'Adjustable Wrench', categories: ['tools'] },
+ { url: 'https://pub-abc.r2.dev/o/fern.glb', label: 'Potted Fern', categories: ['plants'] },
+ ],
+ };
+ const original = globalThis.fetch;
+ globalThis.fetch = async () => ({ ok: true, json: async () => catalogue });
+ t.after(() => { globalThis.fetch = original; });
+
+ const tool = byName(createTools({ env: ENV }), 'search_models');
+ const hit = await tool.run({ query: 'plants' });
+ assert.equal(hit.structuredContent.matched, 1);
+ assert.equal(hit.structuredContent.models[0].title, 'Potted Fern');
+ // Bucket URLs are rewritten onto the CORS-open first-party path.
+ assert.ok(hit.structuredContent.models[0].src.startsWith('https://three.ws/cdn/'));
+
+ const miss = await tool.run({ query: 'spaceship' });
+ assert.ok(!miss.isError, 'no matches is an answer, not an error');
+ assert.equal(miss.structuredContent.matched, 0);
+ assert.match(miss.content[0].text, /generate_3d_model/);
+});
+
+test('create_ar_page emits a page that runs as written', async () => {
+ const tool = byName(createTools({ env: ENV }), 'create_ar_page');
+ const res = await tool.run({ title: 'Acme AR', assets: 'https://acme.com/models.json', models: [{ src: 'https://a.com/x.glb' }] });
+ const html = res.structuredContent.html;
+ assert.match(html, /^<!doctype html>/);
+ assert.match(html, /createArStudio/);
+ assert.match(html, /https:\/\/acme\.com\/models\.json/);
+ assert.match(html, /https:\/\/a\.com\/x\.glb/);
+ // No unreplaced template tokens ever reach a user's file.
+ assert.ok(!html.includes('__'), 'the emitted page must not contain template placeholders');
+});
+
+test('renderPage escapes a title that contains markup', () => {
+ assert.match(renderPage({ title: '</title><script>alert(1)</script>' }), /&lt;script&gt;/);
+});
+
+test('sceneUrl is stable for the same arrangement', () => {
+ const models = [{ src: 'https://a.com/x.glb', title: 'X', x: 1, z: -2, yaw: 0, scale: 1 }];
+ assert.equal(sceneUrl(models, 'https://acme.com/ar/'), sceneUrl(models, 'https://acme.com/ar/'));
+});
diff --git a/packages/ar-studio/test/native-ar.test.mjs b/packages/ar-studio/test/native-ar.test.mjs
new file mode 100644
index 000000000..9f73ae53d
--- /dev/null
+++ b/packages/ar-studio/test/native-ar.test.mjs
@@ -0,0 +1,210 @@
+// The device hand-off is the part of this package that only ever runs on a
+// phone, which is exactly why it is pinned here. Two rules carry the whole
+// feature and both are invisible on a laptop:
+//
+// 1. Preparation and opening are separate. iOS opens AR Quick Look only while
+// the page still holds the user gesture that asked for it, and converting a
+// GLB to USDZ takes seconds. Convert inside the tap handler and Safari
+// silently declines: the button looks dead. So `prepareNativeAr` must never
+// open anything, and the handoff it returns must open synchronously.
+// 2. One conversion per model. A cache miss on the second tap is a two-second
+// stall a person reads as a bug.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1';
+const PIXEL = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36';
+const MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';
+
+function define(name, value) {
+ Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });
+}
+
+/** Minimal browser surface: the module only touches these. */
+function installDom(userAgent) {
+ const revoked = [];
+ const clicked = [];
+ let n = 0;
+ // Node ships a read-only `navigator`, so stubbing it needs defineProperty.
+ define('navigator', { userAgent, platform: 'iPhone', maxTouchPoints: 5 });
+ define('location', { href: 'https://example.test/studio' });
+ globalThis.URL.createObjectURL = () => `blob:https://example.test/obj-${++n}`;
+ globalThis.URL.revokeObjectURL = (u) => revoked.push(u);
+ const body = { children: [], appendChild(el) { this.children.push(el); return el; } };
+ define('document', {
+ body,
+ createElement: (tag) => ({
+ tag,
+ style: {},
+ children: [],
+ listeners: {},
+ appendChild(el) { this.children.push(el); return el; },
+ setAttribute(k, v) { this[k] = v; },
+ addEventListener(type, fn) { this.listeners[type] = fn; },
+ remove() { body.children = body.children.filter((c) => c !== this); },
+ click() { clicked.push(this); },
+ }),
+ });
+ return { revoked, clicked };
+}
+
+function uninstallDom() {
+ delete globalThis.navigator;
+ delete globalThis.document;
+ delete globalThis.location;
+}
+
+const blob = (text = 'usdz') => ({ size: text.length, type: 'model/vnd.usdz+zip' });
+
+test('a desktop browser reports no native AR viewer at all', async (t) => {
+ installDom(MAC);
+ t.after(uninstallDom);
+ const { prepareNativeAr, canUseQuickLook, canUseSceneViewer } = await import(`../src/studio/native-ar.js?desktop`);
+ assert.equal(canUseQuickLook(), false);
+ assert.equal(canUseSceneViewer(), false);
+ assert.equal(await prepareNativeAr({ src: 'https://a.test/x.glb' }), null);
+});
+
+test('Android prepares a Scene Viewer hand-off without converting anything', async (t) => {
+ installDom(PIXEL);
+ t.after(uninstallDom);
+ const { prepareNativeAr } = await import(`../src/studio/native-ar.js?android`);
+ let built = 0;
+ const handoff = await prepareNativeAr(
+ { src: 'https://a.test/x.glb', title: 'Chair', build: async () => { built++; return blob(); } },
+ );
+ assert.equal(handoff.viewer, 'sceneviewer');
+ assert.equal(built, 0, 'Scene Viewer takes the GLB directly: no USDZ is needed');
+ assert.equal(handoff.href, 'https://a.test/x.glb');
+});
+
+test('iOS converts once per key, and opening never converts', async (t) => {
+ const { clicked } = installDom(IPHONE);
+ t.after(uninstallDom);
+ const mod = await import(`../src/studio/native-ar.js?ios-cache`);
+ let built = 0;
+ const model = {
+ src: 'https://a.test/chair.glb',
+ title: 'Chair',
+ key: 'chair|1.000',
+ build: async () => { built++; return blob(); },
+ };
+
+ assert.equal(mod.isQuickLookReady('chair|1.000'), false);
+ const first = await mod.prepareNativeAr(model);
+ assert.equal(first.viewer, 'quicklook');
+ assert.equal(built, 1);
+ assert.match(first.href, /^blob:/);
+ assert.equal(mod.isQuickLookReady('chair|1.000'), true);
+
+ const second = await mod.prepareNativeAr(model);
+ assert.equal(built, 1, 'a second tap reuses the converted USDZ');
+ assert.equal(second.href, first.href);
+
+ // The open path is synchronous on purpose: an await here loses the gesture.
+ assert.equal(clicked.length, 0, 'preparing must never open the viewer');
+ second.open();
+ assert.equal(clicked.length, 1);
+ assert.equal(clicked[0].rel, 'ar');
+ assert.equal(clicked[0].href, second.href);
+ assert.equal(clicked[0].children.length, 1, 'iOS needs a child element inside the anchor');
+ // The bug this pins: without a filename Safari cannot tell a blob URL is a
+ // USDZ, opens Quick Look in Object mode, and AR is silently unavailable.
+ assert.equal(clicked[0].download, 'chair.usdz');
+
+ assert.equal(mod.releaseQuickLook('chair|1.000'), true);
+ assert.equal(mod.isQuickLookReady('chair|1.000'), false);
+});
+
+test('a scaled model is a different cache entry, because the size is baked in', async (t) => {
+ installDom(IPHONE);
+ t.after(uninstallDom);
+ const mod = await import(`../src/studio/native-ar.js?ios-scale`);
+ const keys = [];
+ const make = (key) => mod.prepareNativeAr({
+ src: 'https://a.test/chair.glb', key, build: async () => { keys.push(key); return blob(); },
+ });
+ await make('chair|1.000');
+ await make('chair|0.500');
+ assert.deepEqual(keys, ['chair|1.000', 'chair|0.500']);
+ mod.clearQuickLookCache();
+});
+
+test('the cache is bounded, and eviction revokes the blob it was holding', async (t) => {
+ const { revoked } = installDom(IPHONE);
+ t.after(uninstallDom);
+ const mod = await import(`../src/studio/native-ar.js?ios-evict`);
+ const hrefs = [];
+ for (let i = 0; i < 6; i++) {
+ const h = await mod.cachedUsdzUrl(`m${i}`, async () => blob());
+ hrefs.push(h);
+ }
+ assert.equal(mod.isQuickLookReady('m0'), false, 'the oldest entry is gone');
+ assert.equal(mod.isQuickLookReady('m5'), true);
+ assert.ok(revoked.includes(hrefs[0]), 'eviction is the only thing that frees that memory');
+ mod.clearQuickLookCache();
+ assert.equal(mod.isQuickLookReady('m5'), false);
+});
+
+test('a failed conversion is retryable rather than cached forever', async (t) => {
+ installDom(IPHONE);
+ t.after(uninstallDom);
+ const mod = await import(`../src/studio/native-ar.js?ios-fail`);
+ let attempts = 0;
+ const build = async () => {
+ attempts++;
+ if (attempts === 1) throw new Error('exporter blew up');
+ return blob();
+ };
+ await assert.rejects(mod.cachedUsdzUrl('flaky', build), /exporter blew up/);
+ assert.equal(mod.isQuickLookReady('flaky'), false);
+ assert.match(await mod.cachedUsdzUrl('flaky', build), /^blob:/);
+ assert.equal(attempts, 2);
+ mod.clearQuickLookCache();
+});
+
+test('a blob URL always reaches Quick Look under a .usdz filename', async (t) => {
+ const { clicked } = installDom(IPHONE);
+ t.after(uninstallDom);
+ const { openQuickLook, usdzFilename } = await import(`../src/studio/native-ar.js?filename`);
+
+ assert.equal(usdzFilename('Adjustable Wrench'), 'adjustable-wrench.usdz');
+ assert.equal(usdzFilename(' ~!@# '), 'model.usdz', 'a title with no usable characters still names the file');
+ assert.equal(usdzFilename(''), 'model.usdz');
+ assert.equal(usdzFilename('x'.repeat(200)).length, 60 + '.usdz'.length);
+
+ openQuickLook('blob:https://a.test/abc', { name: 'Trench Car' });
+ assert.equal(clicked[0].download, 'trench-car.usdz');
+
+ // A real https .usdz already carries its extension; adding `download` there
+ // would only risk turning an AR launch into a file save.
+ openQuickLook('https://a.test/chair.usdz');
+ assert.equal(clicked[1].download, undefined);
+});
+
+test('the checkout banner is all-or-nothing, the way Quick Look renders it', async (t) => {
+ installDom(IPHONE);
+ t.after(uninstallDom);
+ const { withQuickLookBanner } = await import(`../src/studio/native-ar.js?banner`);
+ assert.equal(withQuickLookBanner('blob:x'), 'blob:x', 'no fields, no fragment');
+ // A title with no action would render a banner with an empty button.
+ assert.equal(withQuickLookBanner('blob:x', { title: 'Chair' }), 'blob:x');
+ assert.equal(
+ withQuickLookBanner('blob:x', { title: 'a & b', callToAction: 'Buy' }),
+ 'blob:x#checkoutTitle=a%20%26%20b&callToAction=Buy',
+ );
+ const long = withQuickLookBanner('blob:x', { title: 'z'.repeat(200), callToAction: 'Buy' });
+ assert.equal(long.length, 'blob:x#checkoutTitle='.length + 80 + '&callToAction=Buy'.length);
+ assert.equal(
+ withQuickLookBanner('blob:x#already', { subtitle: 'sub', callToAction: 'Buy' }),
+ 'blob:x#already&checkoutSubtitle=sub&callToAction=Buy',
+ );
+});
+
+test('nothing to place is a thrown error, not a silent no-op', async (t) => {
+ installDom(IPHONE);
+ t.after(uninstallDom);
+ const { prepareNativeAr } = await import(`../src/studio/native-ar.js?empty`);
+ await assert.rejects(prepareNativeAr({}), /nothing to place/);
+});
diff --git a/packages/ar-studio/test/scene-math.test.mjs b/packages/ar-studio/test/scene-math.test.mjs
new file mode 100644
index 000000000..7cc02189a
--- /dev/null
+++ b/packages/ar-studio/test/scene-math.test.mjs
@@ -0,0 +1,148 @@
+// The scene format is a contract: it is persisted to localStorage, sent over the
+// wire to other people's browsers, and pasted into URLs by strangers. These
+// tests pin both halves of that: that a legitimate arrangement round-trips
+// exactly, and that hostile input degrades to an empty scene instead of
+// smuggling a non-GLB URL or a NaN transform into the renderer.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import {
+ deserializeScene, fitTransform, normalizeGlbUrl, parseSrcParams, roomLightFromPixels,
+ sceneFromHashParam, sceneToHashParam, serializeScene, spawnPointInFront,
+ studioSceneUrl, studioShareUrl, twistDelta, MAX_PLACEMENTS, SCALE_MIN, SCALE_MAX,
+} from '../src/studio/scene-math.js';
+
+test('normalizeGlbUrl accepts https and site-relative, rejects everything else', () => {
+ assert.equal(normalizeGlbUrl('https://a.com/x.glb'), 'https://a.com/x.glb');
+ assert.equal(normalizeGlbUrl('/models/x.glb'), '/models/x.glb');
+ for (const hostile of [
+ 'http://a.com/x.glb', 'javascript:alert(1)', 'data:model/gltf-binary;base64,AAA',
+ 'blob:https://a.com/1', '//evil.com/x.glb', '', null, undefined, 42,
+ ]) {
+ assert.equal(normalizeGlbUrl(hostile), null, `${String(hostile)} must be rejected`);
+ }
+});
+
+test('a placed arrangement round-trips through the hash exactly', () => {
+ const placements = [
+ { src: 'https://a.com/lamp.glb', title: 'Lamp', x: 0.4, z: -1.8, yaw: 1.2, scale: 1.4 },
+ { src: 'https://a.com/fern.glb', title: 'Fern', x: -0.9, z: -2.2, yaw: 0, scale: 0.8 },
+ ];
+ const restored = sceneFromHashParam(sceneToHashParam(placements));
+ assert.equal(restored.length, 2);
+ assert.deepEqual(restored[0], placements[0]);
+ assert.deepEqual(restored[1], placements[1]);
+});
+
+test('a hostile or corrupt scene payload degrades to empty, never throws', () => {
+ for (const bad of [null, undefined, '', 'not json', '{}', '[]', '{"v":2,"items":[]}', 'eyJhIjox']) {
+ assert.deepEqual(deserializeScene(bad), []);
+ assert.deepEqual(sceneFromHashParam(bad), []);
+ }
+ const smuggled = JSON.stringify({ v: 1, items: [{ src: 'javascript:alert(1)', x: 0, z: 0 }] });
+ assert.deepEqual(deserializeScene(smuggled), []);
+ const nan = JSON.stringify({ v: 1, items: [{ src: 'https://a.com/x.glb', x: 'NaN', z: 0 }] });
+ assert.deepEqual(deserializeScene(nan), []);
+});
+
+test('scale and position are clamped on the way back in', () => {
+ const wild = JSON.stringify({
+ v: 1,
+ items: [{ src: 'https://a.com/x.glb', x: 9999, z: -9999, yaw: 0, scale: 500 }],
+ });
+ const [item] = deserializeScene(wild);
+ assert.equal(item.scale, SCALE_MAX);
+ assert.equal(item.x, 50);
+ assert.equal(item.z, -50);
+});
+
+test('serialization is capped at the placement limit', () => {
+ const many = Array.from({ length: MAX_PLACEMENTS + 12 }, (_, i) => ({
+ src: `https://a.com/${i}.glb`, x: 0, z: 0, yaw: 0, scale: 1,
+ }));
+ assert.equal(JSON.parse(serializeScene(many)).items.length, MAX_PLACEMENTS);
+});
+
+test('share URLs carry the models, and the scene URL adds the arrangement', () => {
+ const placements = [{ src: 'https://a.com/x.glb', title: 'X', x: 1, z: 2, yaw: 0.5, scale: 1.2 }];
+ const short = studioShareUrl('https://acme.com/ar/', placements);
+ assert.match(short, /^https:\/\/acme\.com\/ar\/\?src=https%3A%2F%2Fa\.com%2Fx\.glb&title=X$/);
+ assert.ok(studioSceneUrl('https://acme.com/ar/', placements).includes('#s='));
+ // An existing query string is preserved rather than clobbered.
+ assert.ok(studioShareUrl('https://acme.com/ar/?utm=x', placements).includes('?utm=x&src='));
+});
+
+test('a scene too dense for a scannable QR falls back to the models-only link', () => {
+ const placements = Array.from({ length: 12 }, (_, i) => ({
+ src: `https://cdn.example.com/very/long/path/segment/number/${i}/model-${i}.glb`,
+ title: `Model number ${i} with a fairly long descriptive name`,
+ x: i * 0.31, z: -i * 0.47, yaw: i * 0.19, scale: 1 + i * 0.05,
+ }));
+ assert.ok(!studioSceneUrl('https://acme.com/ar/', placements, 400).includes('#s='));
+});
+
+test('duplicate sources collapse to one entry in a share link', () => {
+ const same = Array.from({ length: 5 }, () => ({ src: 'https://a.com/crate.glb', title: 'Crate' }));
+ assert.equal(studioShareUrl('https://acme.com/ar/', same).match(/src=/g).length, 1);
+});
+
+test('parseSrcParams pairs sources with titles and drops bad ones', () => {
+ const params = new URLSearchParams();
+ params.append('src', 'https://a.com/1.glb');
+ params.append('title', 'One');
+ params.append('src', 'javascript:alert(1)');
+ params.append('title', 'Bad');
+ const parsed = parseSrcParams(params);
+ assert.equal(parsed.length, 1);
+ assert.deepEqual(parsed[0], { src: 'https://a.com/1.glb', title: 'One' });
+});
+
+test('fitTransform normalizes props by size and characters by height', () => {
+ // A 40 m statue of a person is scaled to human height and rests on the floor.
+ const giant = fitTransform({ min: { x: -1, y: 0, z: -1 }, max: { x: 1, y: 40, z: 1 } }, { skinned: true });
+ assert.ok(Math.abs(giant.scale * 40 - 1.65) < 1e-6);
+ assert.ok(Object.is(giant.yOffset, 0) || Object.is(giant.yOffset, -0));
+ // A prop authored below the floor is lifted onto it.
+ const sunken = fitTransform({ min: { x: 0, y: -2, z: 0 }, max: { x: 1, y: 0, z: 1 } });
+ assert.ok(sunken.yOffset > 0);
+ // Anything already close to real-world size is left alone.
+ assert.equal(fitTransform({ min: { x: 0, y: 0, z: 0 }, max: { x: 1, y: 1, z: 1 } }).scale, 1);
+ // A degenerate box still renders rather than vanishing.
+ assert.deepEqual(fitTransform({ min: { x: 0, y: 0, z: 0 }, max: { x: 0, y: 0, z: 0 } }), { scale: 1, yOffset: 0 });
+ assert.deepEqual(fitTransform(null), { scale: 1, yOffset: 0 });
+});
+
+test('a model spawns on the floor in front of the camera, even looking straight up', () => {
+ const front = spawnPointInFront({ x: 0, y: 1.5, z: 0 }, { x: 0, y: 0, z: -1 }, 2);
+ assert.ok(Math.abs(front.z + 2) < 1e-6);
+ // Straight up has no horizontal heading: fall back to the initial facing.
+ const up = spawnPointInFront({ x: 0, y: 1.5, z: 0 }, { x: 0, y: 1, z: 0 }, 2);
+ assert.ok(Math.abs(up.z + 2) < 1e-6);
+});
+
+test('twist never spins the long way round the boundary', () => {
+ assert.ok(Math.abs(twistDelta(3.0, -3.0) - (2 * Math.PI - 6)) < 1e-9);
+ assert.equal(twistDelta(NaN, 1), 0);
+});
+
+test('room light reads brightness and colour cast from camera pixels', () => {
+ const pixels = (r, g, b, n = 64) => {
+ const out = new Uint8ClampedArray(n * 4);
+ for (let i = 0; i < n; i++) { out[i * 4] = r; out[i * 4 + 1] = g; out[i * 4 + 2] = b; out[i * 4 + 3] = 255; }
+ return out;
+ };
+ const dark = roomLightFromPixels(pixels(4, 4, 4));
+ const bright = roomLightFromPixels(pixels(240, 240, 240));
+ assert.ok(dark.intensity < bright.intensity);
+ // A near-black frame carries no reliable cast, so the tint stays neutral.
+ assert.deepEqual(dark.tint, { r: 1, g: 1, b: 1 });
+ const warm = roomLightFromPixels(pixels(220, 170, 120));
+ assert.ok(warm.tint.r > 1 && warm.tint.b < 1);
+ assert.deepEqual(roomLightFromPixels([]), { intensity: 0.4, tint: { r: 1, g: 1, b: 1 } });
+});
+
+test('SCALE bounds are the ones the pinch gesture clamps to', () => {
+ assert.equal(SCALE_MIN, 0.25);
+ assert.equal(SCALE_MAX, 4);
+});
diff --git a/packages/ar-studio/test/usdz-export.test.mjs b/packages/ar-studio/test/usdz-export.test.mjs
new file mode 100644
index 000000000..490dce63b
--- /dev/null
+++ b/packages/ar-studio/test/usdz-export.test.mjs
@@ -0,0 +1,182 @@
+// What decides whether AR Quick Look stands a model on someone's floor.
+//
+// Three rules, and every one of them is invisible on a laptop because the
+// symptom only exists inside ARKit: a model that opens fine, tracks fine, and
+// hangs in mid-air or swims around the room instead of resting on the ground.
+//
+// 1. The root's own transform is NOT exported. `USDZExporter` walks
+// `scene.children` and writes each node's LOCAL matrix, so a scale set on
+// the object handed to it is silently dropped. Everything this package
+// needs to place a model therefore has to live on a child.
+// 2. The content has to be moved onto the floor. Quick Look anchors the
+// scene ORIGIN to the plane it detects and never looks at the geometry, so
+// a GLB authored around a distant origin arrives floating. No anchoring
+// flag fixes that; only moving the model does.
+// 3. USDZ is metres. A model authored in centimetres arrives a hundred times
+// too big, too large for any plane ARKit found indoors, and reads as a
+// broken anchor rather than a wrong size.
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { Box3, BoxGeometry, Group, Mesh, MeshStandardMaterial, Vector3 } from 'three';
+import { unzipSync } from 'three/addons/libs/fflate.module.js';
+
+import {
+ clampToPlaceableSize, fitToRoomScale, groundOnFloor, MAX_AR_FOOTPRINT_M,
+ MAX_AR_HEIGHT_M, sceneToUsdzBlob, usdzExportRoot,
+} from '../src/studio/usdz.js';
+
+/** A box of the given size, sitting with its own centre at `at`. */
+function boxAt(size, at = [0, 0, 0]) {
+ const mesh = new Mesh(new BoxGeometry(...size), new MeshStandardMaterial());
+ mesh.position.set(...at);
+ return mesh;
+}
+
+function boundsOf(object) {
+ object.updateMatrixWorld(true);
+ return new Box3().setFromObject(object);
+}
+
+async function usda(scene, options) {
+ const blob = await sceneToUsdzBlob(scene, options);
+ const files = unzipSync(new Uint8Array(await blob.arrayBuffer()));
+ return new TextDecoder().decode(files['model.usda']);
+}
+
+/** The four rows of a named Xform's transform in a model.usda. */
+function transformOf(text, name) {
+ const node = text.slice(text.indexOf(`def Xform "${name}"`));
+ const row = /matrix4d xformOp:transform = \( \(([^)]*)\), \(([^)]*)\), \(([^)]*)\), \(([^)]*)\) \)/.exec(node);
+ assert.ok(row, `${name} has no transform`);
+ const num = (i) => row[i].split(',').map((n) => Number(n.trim()));
+ const [sx] = num(1);
+ const [x, y, z] = num(4);
+ return { scaleX: sx, x, y, z };
+}
+
+test('usdzExportRoot keeps the source transform, which the exporter drops off a root', async () => {
+ // A studio placement carries its size on the group the caller hands over.
+ const placement = new Group();
+ placement.scale.setScalar(2);
+ placement.add(boxAt([1, 1, 1], [0, 0.5, 0]));
+
+ const { root, stage } = usdzExportRoot(placement);
+ assert.equal(stage.children[0], placement, 'the source hangs under the stage');
+ assert.equal(root.children[0], stage, 'and the stage under an identity root');
+ // The scale is now on a CHILD of the exported root, so it survives.
+ assert.ok(Math.abs(boundsOf(root).max.y - 2) < 1e-6, 'a 2x placement measures 2m tall');
+});
+
+test('a model authored away from the origin is stood on the floor and centred', () => {
+ // Geometry 10m up and 4m sideways: the shape a Quick Look user sees hanging
+ // at eye level across the room, never touching anything.
+ const { root, stage } = usdzExportRoot(boxAt([1, 2, 1], [4, 10, -3]));
+ assert.equal(groundOnFloor(stage, root), true);
+
+ const box = boundsOf(root);
+ assert.ok(Math.abs(box.min.y) < 1e-6, `feet on y=0, got ${box.min.y}`);
+ const centre = box.getCenter(new Vector3());
+ assert.ok(Math.abs(centre.x) < 1e-6 && Math.abs(centre.z) < 1e-6, 'footprint over the origin');
+ assert.ok(Math.abs(box.max.y - 2) < 1e-6, 'and it is still 2m tall');
+});
+
+test('grounding an empty scene reports it instead of writing NaN transforms', () => {
+ const { root, stage } = usdzExportRoot(new Group());
+ assert.equal(groundOnFloor(stage, root), false);
+ assert.deepEqual(stage.position.toArray(), [0, 0, 0]);
+});
+
+test('a centimetre-authored model is brought back to room scale', () => {
+ // 75cm prop exported in centimetres: 75 units, i.e. 75 metres in USDZ.
+ const { root, stage } = usdzExportRoot(boxAt([30, 75, 30]));
+ const applied = fitToRoomScale(stage, root);
+ assert.ok(applied < 1, 'it was shrunk');
+ assert.ok(Math.abs(boundsOf(root).max.y - boundsOf(root).min.y - 0.75) < 1e-6, '75cm tall');
+});
+
+test('a model already at real-world size is left exactly as authored', () => {
+ const { root, stage } = usdzExportRoot(boxAt([0.5, 0.9, 0.5]));
+ assert.equal(fitToRoomScale(stage, root), 1);
+ assert.deepEqual(stage.scale.toArray(), [1, 1, 1]);
+});
+
+test('the exported USDZ carries horizontal plane anchoring', async () => {
+ const text = await usda(boxAt([1, 1, 1], [0, 0.5, 0]));
+ assert.match(text, /token preliminary:anchoring:type = "plane"/);
+ assert.match(text, /token preliminary:planeAnchoring:alignment = "horizontal"/);
+ assert.match(text, /metersPerUnit = 1/);
+ assert.match(text, /upAxis = "Y"/);
+});
+
+test('the exported USDZ writes the floor offset a phone actually reads', async () => {
+ const text = await usda(boxAt([1, 2, 1], [0, 10, 0]));
+ const t = transformOf(text, 'Model');
+ // The stage cancels the 9m gap between the box's underside and the origin.
+ assert.ok(Math.abs(t.y + 9) < 1e-3, `expected the stage to drop the model 9m, got ${t.y}`);
+});
+
+test('fit only runs when it is asked for, so a pinched size is never undone', async () => {
+ const pinched = new Group();
+ pinched.scale.setScalar(3); // someone dragged a 0.75m prop up to 2.25m
+ pinched.add(boxAt([0.75, 0.75, 0.75], [0, 0.375, 0]));
+
+ const kept = await usda(pinched);
+ assert.ok(Math.abs(transformOf(kept, 'Model').y) < 1e-6, 'already on the floor, no drop');
+ // Somewhere under the root that 3x has to be written, or Quick Look shows the
+ // original size and the pinch gesture silently did nothing. It rides on the
+ // pinched group itself, which is now a child and therefore exported.
+ assert.match(kept, /matrix4d xformOp:transform = \( \(3, 0, 0, 0\)/, 'the 3x pinch reaches the file');
+ // And with fit on, the same model would have been dragged back to 0.75m.
+ const refitted = await usda(
+ (() => { const g = new Group(); g.scale.setScalar(3); g.add(boxAt([0.75, 0.75, 0.75], [0, 0.375, 0])); return g; })(),
+ { fit: true },
+ );
+ assert.ok(transformOf(refitted, 'Model').scaleX < 0.4, 'fit would have pulled the 2.25m prop back to 0.75m');
+});
+
+test('a model too big for any plane in a room is brought back to one that fits', () => {
+ // Quick Look does not place a model until ARKit finds a plane big enough to
+ // fit it. A 7m figure never gets one, so it hangs aligned to the camera and
+ // travels with the phone: the exact symptom people report as broken tracking.
+ const huge = new Group();
+ huge.scale.setScalar(4); // the studio's pinch ceiling, on a standing avatar
+ huge.add(boxAt([0.5, 1.7, 0.4], [0, 0.85, 0]));
+
+ const { root, stage } = usdzExportRoot(huge);
+ const applied = clampToPlaceableSize(stage, root);
+ assert.ok(applied < 1, 'it was brought down');
+ const size = boundsOf(root).getSize(new Vector3());
+ assert.ok(Math.max(size.x, size.z) <= MAX_AR_FOOTPRINT_M + 1e-6, 'footprint fits a floor plane');
+ assert.ok(size.y <= MAX_AR_HEIGHT_M + 1e-6, `still ${size.y.toFixed(2)}m tall`);
+});
+
+test('furniture-sized models pass the ceiling untouched', () => {
+ // A two-metre sofa is a thing AR Quick Look places every day.
+ const { root, stage } = usdzExportRoot(boxAt([2.1, 0.8, 0.9], [0, 0.4, 0]));
+ assert.equal(clampToPlaceableSize(stage, root), 1);
+ assert.deepEqual(stage.scale.toArray(), [1, 1, 1]);
+});
+
+test('a pinched model reaches AR at a size ARKit can place, still on the floor', async () => {
+ const pinched = new Group();
+ pinched.scale.setScalar(4);
+ pinched.add(boxAt([0.5, 1.7, 0.4], [0, 0.85, 0]));
+ const { root, stage } = usdzExportRoot(pinched);
+ clampToPlaceableSize(stage, root);
+ groundOnFloor(stage, root);
+ const box = boundsOf(root);
+ assert.ok(Math.abs(box.min.y) < 1e-6, `feet on y=0, got ${box.min.y}`);
+ const height = box.max.y - box.min.y;
+ assert.ok(height <= MAX_AR_HEIGHT_M + 1e-6, `${height.toFixed(2)}m tall`);
+ // The pinch is honoured up to the ceiling rather than thrown away: a model
+ // somebody deliberately made bigger still arrives bigger than its default.
+ assert.ok(height > 1.7, `expected taller than the unpinched 1.7m, got ${height.toFixed(2)}m`);
+
+ // And the same model, all the way through the exporter, still lands on y=0.
+ const another = new Group();
+ another.scale.setScalar(4);
+ another.add(boxAt([0.5, 1.7, 0.4], [0, 0.85, 0]));
+ assert.ok(Math.abs(transformOf(await usda(another), 'Model').y) < 1e-6);
+});
diff --git a/packages/ar-studio/types/element.d.ts b/packages/ar-studio/types/element.d.ts
new file mode 100644
index 000000000..41aaf4d32
--- /dev/null
+++ b/packages/ar-studio/types/element.d.ts
@@ -0,0 +1,10 @@
+import type { ArStudio, StudioOptions } from './index';
+
+export declare class ArStudioElement extends HTMLElement {
+ studio: ArStudio | null;
+ options(): StudioOptions;
+}
+
+/** Register `<ar-studio>`. Safe to call more than once. */
+export declare function defineArStudio(tag?: string): void;
+export default defineArStudio;
diff --git a/packages/ar-studio/types/index.d.ts b/packages/ar-studio/types/index.d.ts
new file mode 100644
index 000000000..6b260dd4c
--- /dev/null
+++ b/packages/ar-studio/types/index.d.ts
@@ -0,0 +1,357 @@
+// Type definitions for 3d-ar-studio.
+//
+// Hand-written rather than generated, so the shapes documented here are the ones
+// a host actually touches. Everything the studio exposes is plain data.
+
+export interface ModelInput {
+ /** https URL of a .glb or .gltf model, or a site-relative path. */
+ src: string;
+ /** Label shown in the tray and the selection bar. */
+ title?: string;
+ /** Thumbnail URL. */
+ poster?: string;
+}
+
+export interface Placement extends Required<Pick<ModelInput, 'src' | 'title'>> {
+ id: string;
+ /** Metres right of the scene origin. */
+ x: number;
+ /** Metres forward of the scene origin; negative is further away. */
+ z: number;
+ /** Rotation about the vertical axis, in radians. */
+ yaw: number;
+ /** Uniform scale, 0.25 to 4. */
+ scale: number;
+ /** False for a model placed by someone else in a shared room. */
+ mine: boolean;
+}
+
+export interface SceneItem {
+ src: string;
+ title: string;
+ x: number;
+ z: number;
+ yaw: number;
+ scale: number;
+}
+
+export interface AssetItem {
+ src: string;
+ title: string;
+ poster?: string;
+ /** Lower-cased text the tray's filter box matches against. */
+ keywords?: string;
+}
+
+export interface AssetSource {
+ /** Stable key; also the tab's identity. */
+ id: string;
+ /** Tab label. */
+ label?: string;
+ /** Line rendered under the search box. */
+ hint?: string;
+ /** Copy shown when `list()` returns nothing. */
+ emptyCopy?: string;
+ /** Show a client-side filter box. Defaults to true above 24 items. */
+ searchable?: boolean;
+ /** Re-read on every open instead of being cached. */
+ live?: boolean;
+ /** `'link'` renders the paste-a-URL form instead of a grid. */
+ kind?: 'link';
+ list?(): Promise<AssetItem[]>;
+}
+
+export type AssetsOption = string | AssetSource | Array<string | AssetSource>;
+
+export interface GenerateOptions {
+ enabled?: boolean;
+ /** MCP endpoint exposing a compatible generate tool. */
+ endpoint?: string;
+ kind?: 'model' | 'avatar' | 'mesh';
+ tier?: 'draft' | 'standard' | 'high';
+ timeoutMs?: number;
+ pollMs?: number;
+ headers?: Record<string, string>;
+}
+
+export interface StudioOptions {
+ assets?: AssetsOption;
+ allowUrlOverride?: boolean;
+ generate?: GenerateOptions;
+ rooms?: { enabled?: boolean; server?: string };
+ animations?: { enabled?: boolean; manifestUrl?: string; clip?: string };
+ lighting?: { preset?: 'studio' | 'outdoor' | 'sunset' | null; urls?: Record<string, string> };
+ branding?: { title?: string; accent?: string; backHref?: string | null; backLabel?: string };
+ /** Where share links and QR codes point. Defaults to the hosting page. */
+ shareBaseUrl?: string;
+ /** Origin used for the hosted "View in your space" launcher and viewer links. */
+ origin?: string;
+ arLaunchUrl?: string;
+ persistKey?: string;
+ persist?: boolean;
+ maxPlacements?: number;
+ /** Render as a fixed full-screen layer. Defaults to true only on `document.body`. */
+ fullscreen?: boolean;
+ onEvent?(event: StudioEventName, detail: Record<string, unknown>): void;
+}
+
+export type StudioEventName =
+ | 'add' | 'remove' | 'select' | 'clear'
+ | 'generate' | 'generate-error'
+ | 'camera' | 'xr' | 'room' | 'share'
+ | 'native-ar' | 'native-ar-error' | 'ar-sheet';
+
+export interface GeneratedModel {
+ src: string;
+ title: string;
+ prompt: string;
+ kind: string;
+ viewerUrl: string;
+ arUrl: string;
+ poster: string;
+ rigged: boolean;
+}
+
+export declare class ArStudio {
+ constructor(host: HTMLElement, options?: StudioOptions);
+ readonly config: Required<StudioOptions> & Record<string, unknown>;
+ readonly placements: unknown[];
+ readonly roomCode: string;
+ on(event: StudioEventName, fn: (detail: any) => void): () => void;
+ off(event: StudioEventName, fn: (detail: any) => void): void;
+ addModel(model: ModelInput, opts?: Partial<SceneItem> & { announce?: boolean; persist?: boolean }): Promise<Placement | null>;
+ clear(): SceneItem[];
+ getScene(): SceneItem[];
+ setScene(items: SceneItem[]): Promise<void>;
+ shareUrl(): string;
+ generate(prompt: string): Promise<GeneratedModel | null>;
+ viewInYourSpace(src: string, title?: string): string;
+ startCamera(): Promise<void>;
+ stopCamera(): void;
+ toggleImmersive(): Promise<void>;
+ /** Enter AR by the best path this device supports. */
+ enterAR(): Promise<unknown>;
+ /** Open one model in the device's native AR viewer. Defaults to the selection. */
+ placeInYourSpace(placement?: unknown): Promise<'quicklook' | 'sceneviewer' | 'none' | null>;
+ /** Open the AR hand-off sheet: prepare one model, then open the device viewer from one tap. */
+ openArSheet(placement?: unknown): void;
+ /** Close the AR hand-off sheet. */
+ closeArSheet(): void;
+ readonly arMode: ArCapability;
+ openRoom(code?: string): Promise<string>;
+ leaveRoom(): void;
+ destroy(): void;
+}
+
+/** Mount a studio into an element (or CSS selector). Defaults to `document.body`. */
+export declare function createArStudio(host?: HTMLElement | string, options?: StudioOptions): ArStudio;
+export default createArStudio;
+
+// ── Sources ─────────────────────────────────────────────────────────────────
+export declare function manifestSource(opts: {
+ url: string;
+ id?: string;
+ label?: string;
+ hint?: string;
+ searchable?: boolean;
+ map?: (entry: any) => AssetItem | null;
+ rewriteUrl?: (url: string) => string;
+ fetchOptions?: RequestInit;
+}): AssetSource;
+export declare function staticSource(opts: { items: any[]; id?: string; label?: string; hint?: string; searchable?: boolean }): AssetSource;
+export declare function recentSource(cfg?: { recentKey?: string }): AssetSource;
+export declare function threeWsObjectsSource(cfg?: Record<string, unknown>): AssetSource;
+export declare function threeWsCommunitySource(cfg?: Record<string, unknown>): AssetSource;
+export declare function resolveSources(assets: AssetsOption, cfg?: Record<string, unknown>): AssetSource[];
+export declare function normalizeCatalogue(data: unknown, opts?: { map?: Function; rewriteUrl?: Function }): AssetItem[];
+export declare function catalogueItems(data: unknown): any[];
+export declare function filenameTitle(url: string): string;
+export declare function readRecents(key?: string): Array<{ src: string; title: string; poster: string; ts: number }>;
+export declare function rememberRecent(model: ModelInput, key?: string): void;
+export declare function cdnUrl(url: string, origin?: string): string;
+export declare const LINK_SOURCE: AssetSource;
+
+// ── Generation ──────────────────────────────────────────────────────────────
+export declare class ForgeError extends Error { code: string }
+export declare function createForgeClient(opts?: GenerateOptions & { tools?: Record<string, string>; fetchImpl?: typeof fetch }): {
+ generate(prompt: string, opts?: {
+ onProgress?(state: { status: string; message: string; elapsedMs: number; etaSeconds: number | null }): void;
+ kind?: 'model' | 'avatar' | 'mesh';
+ tier?: 'draft' | 'standard' | 'high';
+ imageUrl?: string;
+ signal?: AbortSignal;
+ }): Promise<GeneratedModel>;
+ mcp: ReturnType<typeof createMcpClient>;
+ endpoint: string;
+};
+export declare function createMcpClient(opts: { endpoint: string; headers?: Record<string, string>; fetchImpl?: typeof fetch }): {
+ rpc(method: string, params?: unknown, opts?: { signal?: AbortSignal }): Promise<any>;
+ listTools(opts?: { signal?: AbortSignal }): Promise<any[]>;
+ callTool(name: string, args?: Record<string, unknown>, opts?: { signal?: AbortSignal }): Promise<any>;
+ readonly sessionId: string;
+};
+export declare class McpError extends Error { code?: number; status?: number; detail?: string }
+export declare function unwrapToolResult(result: any): { structured: any; text: string; isError: boolean };
+export declare function checkPromptSafety(prompt: string): { allowed: boolean; category?: string; message?: string; matched?: string };
+export declare function validatePrompt(prompt: string): { ok: boolean; prompt?: string; reason?: string; category?: string };
+export declare function stageNarration(state: Record<string, unknown>): string;
+export declare function promptTitle(prompt: string, max?: number): string;
+export declare function laneLabel(id: string): string | null;
+export declare const GENERATE_TOOLS: Record<string, string>;
+
+// ── AR routing ──────────────────────────────────────────────────────────────
+export type ArTarget = 'ios' | 'android' | 'desktop';
+export interface ArPlan {
+ target: ArTarget;
+ action: 'redirect' | 'page';
+ asset: string;
+ viewerUrl: string;
+ sceneViewerUrl: string;
+ launchUrl: string;
+ live: boolean;
+}
+export declare class ArUrlError extends Error { code: 'invalid_url' | 'not_https' | 'not_glb' }
+export declare function planArLaunch(p: { glbUrl: string; userAgent?: string; origin?: string; title?: string; live?: boolean }): ArPlan;
+export declare function assertArAssetUrl(glbUrl: unknown): string;
+export declare function detectArTarget(userAgent?: string): ArTarget;
+export declare function buildArLaunchUrl(origin: string, glbUrl: string, title?: string, opts?: { live?: boolean; endpoint?: string }): string;
+export declare function buildSceneViewerUrl(glbUrl: string, opts?: { title?: string; fallbackUrl?: string }): string;
+export declare function buildViewerUrl(origin: string, glbUrl: string, title?: string): string;
+export type ArCapability = 'webxr' | 'quicklook' | 'sceneviewer' | 'none';
+/** The best AR path this device can actually deliver, best first. */
+export declare function arCapability(): Promise<ArCapability>;
+/** Open one model in the device's own AR viewer (Quick Look / Scene Viewer). */
+export declare function placeInYourSpace(
+ model: NativeArModel,
+ opts?: NativeArOptions,
+): Promise<'quicklook' | 'sceneviewer' | 'none'>;
+
+export interface NativeArModel {
+ src?: string;
+ title?: string;
+ /** A ready-made USDZ, skipping conversion entirely. */
+ usdz?: string;
+ /** Cache identity for the converted USDZ. Defaults to `src`. */
+ key?: string;
+ /** Produce the USDZ without refetching the GLB (export from a live scene). */
+ build?: () => Promise<Blob>;
+}
+
+export interface NativeArOptions {
+ onProgress?: (stage: 'download' | 'parse' | 'convert' | 'open') => void;
+ fallbackUrl?: string;
+ signal?: AbortSignal;
+}
+
+export interface NativeArHandoff {
+ viewer: 'quicklook' | 'sceneviewer';
+ href: string;
+ /** Call this synchronously from a real tap: iOS opens Quick Look only while the gesture is live. */
+ open(opts?: { onBannerTap?: () => void }): void;
+}
+
+/**
+ * Prepare the device AR hand-off WITHOUT opening it, so the tap that opens it
+ * stays inside the user gesture Safari requires. Resolves null on a device with
+ * no native AR viewer.
+ */
+export declare function prepareNativeAr(
+ model: NativeArModel,
+ opts?: NativeArOptions,
+): Promise<NativeArHandoff | null>;
+
+/** Convert once per key and hand back a `blob:` URL Quick Look can open. */
+export declare function cachedUsdzUrl(key: string, build: () => Promise<Blob>): Promise<string>;
+/** Is a Quick Look asset for this key already converted and ready to open? */
+export declare function isQuickLookReady(key: string): boolean;
+/** Drop one cached USDZ and revoke its object URL. */
+export declare function releaseQuickLook(key: string): boolean;
+/** Drop every cached USDZ and release the memory behind it. */
+export declare function clearQuickLookCache(): void;
+/**
+ * Append Quick Look checkout-banner fields to a USDZ URL. Returns the URL
+ * unchanged unless `callToAction` is present: Quick Look renders the banner
+ * only as a complete set, and a title alone yields a banner with a dead button.
+ */
+export declare function withQuickLookBanner(url: string, fields?: { title?: string; subtitle?: string; callToAction?: string }): string;
+/** Fetch a GLB and convert it to a USDZ blob, on the device. */
+export declare function glbUrlToUsdzBlob(glbUrl: string, opts?: { signal?: AbortSignal; onProgress?: (stage: string) => void }): Promise<Blob>;
+/** Convert an object already standing in a live scene to USDZ: no refetch, current pose and size. */
+export declare function objectToUsdzBlob(object: any): Promise<Blob>;
+export declare function sceneToUsdzBlob(scene: any, options?: Record<string, unknown>): Promise<Blob>;
+export declare function bakeSkinnedMeshes(scene: any): void;
+export declare function coerceMaterialsToStandard(scene: any): void;
+export declare function ensureNormals(scene: any): void;
+export declare function canUseQuickLook(): boolean;
+export declare function canUseSceneViewer(): boolean;
+/**
+ * Open a USDZ in Quick Look.
+ *
+ * When `usdzUrl` is a `blob:` URL the anchor is given `download="<name>.usdz"`,
+ * because Safari decides whether a URL is an AR asset from its file extension:
+ * without it Quick Look opens in Object mode with AR unavailable.
+ */
+export declare function openQuickLook(usdzUrl: string, opts?: { onBannerTap?: () => void; name?: string }): void;
+/** A filesystem-safe `<slug>.usdz` name for a model title. */
+export declare function usdzFilename(title?: string): string;
+export declare function openSceneViewer(glbUrl: string, opts?: { title?: string; link?: string; fallbackUrl?: string }): void;
+export declare function isIOS(): boolean;
+export declare function isAndroid(): boolean;
+export declare const QUICK_LOOK_BANNER_TAPPED: string;
+export declare const DEFAULT_ORIGIN: string;
+
+// ── Scene math and links ────────────────────────────────────────────────────
+export declare function fitTransform(box: { min: { x: number; y: number; z: number }; max: { x: number; y: number; z: number } }, opts?: { skinned?: boolean }): { scale: number; yOffset: number };
+export declare function spawnPointInFront(camPos: { x: number; y: number; z: number }, camForward: { x: number; y: number; z: number }, distance?: number): { x: number; z: number };
+export declare function normalizeGlbUrl(raw: unknown): string | null;
+export declare function serializeScene(placements: SceneItem[]): string;
+export declare function deserializeScene(json: string | null | undefined): SceneItem[];
+export declare function sceneToHashParam(placements: SceneItem[]): string;
+export declare function sceneFromHashParam(raw: string | null | undefined): SceneItem[];
+export declare function studioSceneUrl(baseUrl: string, placements: SceneItem[], maxUrlLength?: number): string;
+export declare function studioShareUrl(baseUrl: string, placements: Array<{ src: string; title?: string }>, max?: number): string;
+export declare function roomLightFromPixels(data: Uint8ClampedArray | number[]): { intensity: number; tint: { r: number; g: number; b: number } };
+export declare function twistDelta(startAngle: number, nowAngle: number): number;
+export declare function touchAngle(touches: TouchList | Touch[]): number;
+export declare function generateRoomCode(rand?: () => number): string;
+export declare function normalizeRoomCode(raw: unknown): string;
+export declare function roomShareUrl(baseUrl: string, code: string): string;
+export declare function roomKeyForCode(code: string): string;
+export declare function localToShared(t: { x: number; z: number; yaw: number; scale?: number; height?: number }): { relEast: number; relNorth: number; yawDeg: number; scale: number; height: number };
+export declare function sharedToLocal(s: { relEast: number; relNorth: number; yawDeg: number; scale?: number }): { x: number; z: number; yaw: number; scale: number };
+export declare function normDeg(d: number): number;
+export declare function normRad(a: number): number;
+export declare function renderQRToSVG(text: string, opts?: { scale?: number; margin?: number; dark?: string; light?: string }): string;
+export declare function renderQRToCanvas(text: string, canvas: HTMLCanvasElement, opts?: Record<string, unknown>): void;
+export declare function generateQR(text: string): { size: number; modules: boolean[][] };
+export declare const MAX_PLACEMENTS: number;
+export declare const SCALE_MIN: number;
+export declare const SCALE_MAX: number;
+export declare const SPAWN_DISTANCE_M: number;
+export declare const AVATAR_TARGET_HEIGHT_M: number;
+export declare const PROP_TARGET_SIZE_M: number;
+
+// ── Rendering + capture ─────────────────────────────────────────────────────
+export declare function applyCinematicDefaults(renderer: any, opts?: { exposure?: number; tier?: 'high' | 'medium' | 'mobile' }): { pixelRatioCap: number; shadows: boolean; hdri: boolean };
+export declare function detectQualityTier(env?: Record<string, unknown>): 'high' | 'medium' | 'mobile';
+export declare function loadEnvironment(renderer: any, scene: any, preset?: string | null, opts?: { urls?: Record<string, string> }): Promise<any>;
+export declare function updateGroundContactShadow(scene: any, target: any, existing?: any, opacity?: number): any;
+export declare function captureComposite(opts: { canvas: HTMLCanvasElement; video?: HTMLVideoElement; isAR?: boolean }): Promise<Blob | null>;
+export declare function shareOrDownload(blob: Blob, opts?: { filename?: string; title?: string }): Promise<'shared' | 'downloaded'>;
+export declare function shareUrlOrCopy(url: string, opts?: { title?: string; text?: string }): Promise<'shared' | 'copied'>;
+export declare function sharedGLTFLoader(): any;
+export declare function setDracoPath(path: string): void;
+export declare function mountIdle(model: any, opts?: { manifestUrl?: string; clip?: string; sourceUrl?: string }): Promise<any | null>;
+export declare function getIdleClipJson(opts?: { manifestUrl?: string; clip?: string }): Promise<object | null>;
+export declare const QUALITY_TIERS: Record<string, { pixelRatioCap: number; shadows: boolean; hdri: boolean }>;
+export declare const DEFAULT_DRACO_PATH: string;
+
+// ── Config ──────────────────────────────────────────────────────────────────
+export declare const DEFAULTS: StudioOptions;
+export declare const THREE_WS: Record<string, any>;
+export declare function mergeConfig<T>(base: T, patch: Partial<T>): T;
+export declare function resolveConfig(options?: StudioOptions, search?: URLSearchParams | string): StudioOptions & { urlModels: ModelInput[]; urlRoom: string; urlPrompt: string };
+export declare function safeUrl(raw: unknown): string | null;
+export declare function createLogger(tag: string): Record<'error' | 'warn' | 'info' | 'debug' | 'log', (...args: unknown[]) => void>;
+export declare function setVerbose(on: boolean): void;
+export declare function isVerbose(): boolean;
diff --git a/src/ar-studio.js b/src/ar-studio.js
index 356e78ec8..d4dd119b3 100644
--- a/src/ar-studio.js
+++ b/src/ar-studio.js
@@ -31,13 +31,13 @@ import {
import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
import { applyCinematicDefaults, detectQualityTier, loadEnvironment } from './shared/cinematic-render.js';
-import { EstimatedLighting } from './ar/estimated-lighting.js';
+import { EstimatedLighting } from '../packages/ar-studio/src/studio/estimated-lighting.js';
import {
generateRoomCode, localToShared, normalizeRoomCode, roomKeyForCode,
roomShareUrl, sharedToLocal,
-} from './ar/studio-coords.js';
+} from '../packages/ar-studio/src/studio/coords.js';
import { StudioNet } from './ar/studio-net.js';
-import { MultiPlaceSession } from './ar/multi-place.js';
+import { MultiPlaceSession } from '../packages/ar-studio/src/studio/multi-place.js';
import { canUseQuickLook, openQuickLook } from './ar/quick-look.js';
import { canUseSceneViewer, openSceneViewer } from './ar/scene-viewer.js';
import { glbBlobToUsdzBlob } from './usdz-pipeline.js';
@@ -46,13 +46,13 @@ import { cardTitleFromPrompt } from './model-lib.js';
import {
createPinchState, pinchEnd, pinchMove, pinchStart, touchDist,
PINCH_SCALE_MAX, PINCH_SCALE_MIN,
-} from './ar/pinch-scale.js';
+} from '../packages/ar-studio/src/studio/pinch.js';
import {
deserializeScene, fitTransform, MAX_PLACEMENTS, normalizeGlbUrl,
parseSrcParams, roomLightFromPixels, sceneFromHashParam, serializeScene,
SPAWN_DISTANCE_M, spawnPointInFront, studioSceneUrl, studioShareUrl,
touchAngle, twistDelta,
-} from './ar/studio-scene.js';
+} from '../packages/ar-studio/src/studio/scene-math.js';
import { renderQRToSVG } from './erc8004/qr.js';
import { deriveVerticalFovDeg, DEFAULT_DIAG_FOV_DEG } from './irl/camera-fov.js';
import { createLoadQueue, loadGLTF } from './irl/load-queue.js';
@@ -67,6 +67,8 @@ const $ = (id) => document.getElementById(id);
const esc = (s) =>
String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+/** Canonical studio page; the base every share link and QR is built against. */
+const STUDIO_BASE_URL = 'https://three.ws/ar/studio';
const SCENE_KEY = 'twx_ar_studio_scene_v1';
// Shared with /ar (AR Forge) on purpose: a model forged on either page shows up
// in the other's recents — one history, two doors.
@@ -880,10 +882,10 @@ function renderRoomModal() {
const box = $('ars-room-qr');
if (box) {
try {
- box.innerHTML = renderQRToSVG(roomShareUrl('https://three.ws', roomCode), {
+ box.innerHTML = renderQRToSVG(roomShareUrl(STUDIO_BASE_URL, roomCode), {
scale: 5, margin: 2, dark: '#0b0b0b', light: '#ffffff',
});
- } catch { box.textContent = roomShareUrl('https://three.ws', roomCode); }
+ } catch { box.textContent = roomShareUrl(STUDIO_BASE_URL, roomCode); }
}
}
}
@@ -917,7 +919,7 @@ $('ars-room-create')?.addEventListener('click', async () => {
// create → find button → copy. Best-effort; the Copy button remains as backup.
if (net && net.status === 'online' && navigator.clipboard?.writeText) {
try {
- await navigator.clipboard.writeText(roomShareUrl(location.origin, roomCode));
+ await navigator.clipboard.writeText(roomShareUrl(`${location.origin}/ar/studio`, roomCode));
setStatus(`Room ${roomCode} is live — invite link copied. Paste it to a friend.`);
} catch { /* clipboard blocked — the Copy button below still works */ }
}
@@ -938,7 +940,7 @@ $('ars-room-join-form')?.addEventListener('submit', async (e) => {
});
$('ars-room-copy')?.addEventListener('click', () => {
- const url = roomShareUrl(location.origin, roomCode);
+ const url = roomShareUrl(`${location.origin}/ar/studio`, roomCode);
const btn = $('ars-room-copy');
const done = () => {
if (!btn) return;
@@ -2198,7 +2200,7 @@ photoBtn?.addEventListener('click', async () => {
qrBtn?.addEventListener('click', () => {
if (!qrModal) return;
- const url = studioSceneUrl('https://three.ws', placements.map((p) => ({
+ const url = studioSceneUrl(STUDIO_BASE_URL, placements.map((p) => ({
src: p.src,
title: p.title,
x: p.group.position.x,
@@ -2214,7 +2216,7 @@ qrBtn?.addEventListener('click', () => {
// Arrangement hash too dense for the encoder → a models-only QR still
// beats a wall of text (the full link below keeps the arrangement).
try {
- box.innerHTML = renderQRToSVG(studioShareUrl('https://three.ws', placements), {
+ box.innerHTML = renderQRToSVG(studioShareUrl(STUDIO_BASE_URL, placements), {
scale: 6, margin: 2, dark: '#0b0b0b', light: '#ffffff',
});
} catch {
diff --git a/src/ar/studio-net.js b/src/ar/studio-net.js
index ace65ff89..1d608bc42 100644
--- a/src/ar/studio-net.js
+++ b/src/ar/studio-net.js
@@ -1,33 +1,11 @@
-// Realtime client for the shared AR Studio — wraps colyseus.js with a tiny event
-// API so src/ar-studio.js can join a shared room and live-sync placed models
-// without knowing anything about Colyseus. Mirrors src/irl-net.js in shape
-// (status model, single-retry reconnect, no storms) so the two transports read
-// the same.
-//
-// What it does: joins the `studio_world` room for a given roomKey (a shared code,
-// or a QR-marker id when co-located) and relays the shared scene — every model's
-// add / change / remove — plus live presence (who else is in the room). Local
-// edits are sent up via spawn/update/remove; the server owner-gates, caps, and
-// rate-limits, then delta-broadcasts to every peer.
-//
-// Transforms ride in the room's shared LOGICAL frame (relEast / relNorth metres,
-// yawDeg) — see multiplayer/src/studio-schemas.js. Mapping to/from each device's
-// local scene is the caller's job (src/ar/studio-coords.js).
-//
-// Graceful degradation: no server configured, or the socket can't be reached
-// after one retry → a distinct status (`unavailable` / `failed`) and the studio
-// simply stays single-player. Never loops on a dead endpoint.
+// three.ws binding for the shared-room client. The room protocol, reconnect and
+// timeout logic live in the 3d-ar-studio package (packages/ar-studio); this file
+// only supplies what is specific to the hosted site: which Colyseus host to dial.
+// Rooms run on the SAME server as /walk and /irl (a new room, not a new process).
-import { Client, getStateCallbacks } from 'colyseus.js';
-import { StudioState } from '../../multiplayer/src/studio-schemas.js';
-import { joinRoomWithTimeout } from '../shared/colyseus-connect.js';
-import { log } from '../shared/log.js';
+import { StudioNet as PackageStudioNet } from '../../packages/ar-studio/src/studio/net.js';
-const ROOM_NAME = 'studio_world';
-const MAX_RETRIES = 1;
-
-// Resolve the Colyseus host the same way irl-net does — the studio world runs on
-// the SAME server as /walk and /irl (a new room, not a new process).
+// Resolve the Colyseus host the same way irl-net does.
function defaultServerUrl() {
if (typeof window !== 'undefined') {
if (window.STUDIO_SERVER_URL) return String(window.STUDIO_SERVER_URL).trim().replace(/\/$/, '');
@@ -43,14 +21,14 @@ function defaultServerUrl() {
try {
const envUrl = import.meta?.env?.VITE_IRL_SERVER_URL || import.meta?.env?.VITE_WALK_SERVER_URL;
if (envUrl) return String(envUrl).trim().replace(/\/$/, '');
- } catch (_) {}
+ } catch { /* import.meta.env is absent outside Vite */ }
if (typeof location !== 'undefined') {
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = location.hostname;
const fwd = host.match(/^(.*)-(\d+)\.(app\.github\.dev|githubpreview\.dev|gitpod\.io)$/);
if (fwd) return `${proto}//${fwd[1]}-2567.${fwd[3]}`;
let isProd = false;
- try { isProd = import.meta?.env?.PROD === true; } catch (_) {}
+ try { isProd = import.meta?.env?.PROD === true; } catch { /* import.meta.env is absent outside Vite */ }
const isLocalHost = host === 'localhost' || host === '127.0.0.1';
if (!isProd || isLocalHost) return `${proto}//${host}:2567`;
return '';
@@ -58,236 +36,9 @@ function defaultServerUrl() {
return '';
}
-export class StudioNet {
- /**
- * @param {object} opts
- * @param {string} opts.roomKey Shared match key (code or marker id).
- * @param {string} [opts.clientId] Stable per-browser id → model ownership.
- * @param {string} [opts.name] Optional display name for presence.
- * @param {string} [opts.url] Override server URL (tests).
- */
- constructor({ roomKey, clientId = '', name = '', url } = {}) {
- this.roomKey = String(roomKey || '').slice(0, 64);
- this.clientId = String(clientId || '').slice(0, 80);
- this.name = String(name || '').slice(0, 120);
- this.url = (url ?? defaultServerUrl()) || '';
- this.status = 'idle';
- this.error = '';
- this.room = null;
- this.client = null;
- this._listeners = { status: [], models: [], model: [], presence: [], reject: [] };
- this._retries = 0;
- this._reconnectTimer = null;
- this._connectGen = 0;
- this._destroyed = false;
- this._presenceQueued = false;
- }
-
- on(event, fn) {
- (this._listeners[event] ||= []).push(fn);
- return this;
- }
-
- _emit(event, payload) {
- for (const fn of this._listeners[event] || []) {
- try { fn(payload); } catch (e) { log.warn(`[studio-net] ${event} listener error:`, e?.message || e); }
- }
- }
-
- _setStatus(status, error = '') {
- this.status = status;
- this.error = error;
- this._emit('status', { status, error });
- }
-
- _closeRoom() {
- const room = this.room;
- if (!room) return;
- this.room = null;
- try { room.removeAllListeners(); } catch {}
- try { room.leave(); } catch {}
- }
-
- async connect() {
- if (this._destroyed) return;
- this._closeRoom();
- if (!this.url) { this._setStatus('unavailable'); return; }
- if (!this.roomKey) { this._setStatus('unavailable'); return; }
- const gen = ++this._connectGen;
- this._setStatus('connecting');
- try {
- this.client = new Client(this.url);
- const room = await joinRoomWithTimeout(this.client, ROOM_NAME, {
- roomKey: this.roomKey,
- clientId: this.clientId,
- name: this.name,
- }, StudioState);
- if (this._destroyed || gen !== this._connectGen) {
- try { room.leave(); } catch {}
- return;
- }
- this.room = room;
- this._retries = 0;
-
- const $ = getStateCallbacks(this.room);
-
- // The shared scene: any model add / per-field change / remove re-emits the
- // full model list so the studio reconciles its local placements against it.
- // The join handshake fires onAdd once per existing model, so we coalesce
- // the burst into a single emit next tick.
- const $models = $(this.room.state)?.models;
- if ($models) {
- $models.onAdd((model, id) => {
- $(model).onChange(() => this._emit('model', this._modelShape(model, id)));
- this._queueModels();
- });
- $models.onRemove((model, id) => {
- this._emit('model', { id, removed: true });
- this._queueModels();
- });
- }
-
- const $viewers = $(this.room.state)?.viewers;
- if ($viewers) {
- $viewers.onAdd(() => this._queuePresence());
- $viewers.onRemove(() => this._queuePresence());
- }
-
- // A rejected op (room/owner full) — surface it so the UI can explain.
- this.room.onMessage('model:reject', (msg) => this._emit('reject', msg));
-
- this.room.onLeave((code) => {
- if (this._destroyed || code === 1000) return;
- this._setStatus('offline');
- this._scheduleReconnect();
- });
- this.room.onError((code, message) => log.warn('[studio-net] room.onError', code, message));
-
- this._setStatus('online');
- // Emit the initial scene + presence once the handshake burst settles.
- this._queueModels();
- this._queuePresence();
- } catch (err) {
- const reason = err?.message || (err?.code != null ? `code ${err.code}` : String(err));
- log.warn('[studio-net] connect failed:', reason);
- this._setStatus('failed', reason);
- this._scheduleReconnect();
- }
- }
-
- _scheduleReconnect() {
- if (this._reconnectTimer || this._destroyed) return;
- if (this._retries >= MAX_RETRIES) { this._setStatus('unavailable', this.error); return; }
- this._retries++;
- const delay = 2500 + Math.random() * 1500;
- this._reconnectTimer = setTimeout(() => {
- this._reconnectTimer = null;
- if (this._destroyed) return;
- this.connect();
- }, delay);
- }
-
- _modelShape(m, id) {
- return {
- id: id ?? m.id,
- src: m.src,
- title: m.title,
- relEast: m.relEast,
- relNorth: m.relNorth,
- yawDeg: m.yawDeg,
- scale: m.scale,
- height: m.height,
- ownerId: m.ownerId,
- mine: !!this.clientId && m.ownerId === this.clientId,
- };
- }
-
- _queueModels() {
- if (this._modelsQueued || this._destroyed) return;
- this._modelsQueued = true;
- Promise.resolve().then(() => {
- this._modelsQueued = false;
- if (this._destroyed || !this.room) return;
- const map = this.room.state?.models;
- if (!map) return;
- const models = [];
- map.forEach((m, id) => models.push(this._modelShape(m, id)));
- this._emit('models', models);
- });
- }
-
- _queuePresence() {
- if (this._presenceQueued || this._destroyed) return;
- this._presenceQueued = true;
- Promise.resolve().then(() => {
- this._presenceQueued = false;
- if (this._destroyed || !this.room) return;
- const map = this.room.state?.viewers;
- if (!map) return;
- let count = 0;
- const names = [];
- map.forEach((v) => { count++; if (v.name) names.push(v.name); });
- this._emit('presence', { count, names });
- });
- }
-
- _live() {
- return this.status === 'online' && this.room && this.room.connection?.isOpen === true;
- }
-
- /** Add a model to the shared scene. `model` is in the shared logical frame. */
- spawn(model) {
- if (!this._live()) return false;
- try {
- this.room.send('model:spawn', {
- id: model.id,
- src: String(model.src || ''),
- title: String(model.title || '').slice(0, 120),
- relEast: Number(model.relEast) || 0,
- relNorth: Number(model.relNorth) || 0,
- yawDeg: Number(model.yawDeg) || 0,
- scale: Number(model.scale) || 1,
- height: Number(model.height) || 0,
- });
- return true;
- } catch (e) {
- log.warn('[studio-net] spawn failed:', e?.message || e);
- return false;
- }
- }
-
- /** Move / resize / rotate a model you own. Partial patch. */
- update(id, patch) {
- if (!this._live() || !id) return false;
- const msg = { id: String(id) };
- for (const k of ['relEast', 'relNorth', 'yawDeg', 'scale']) {
- if (Number.isFinite(patch?.[k])) msg[k] = patch[k];
- }
- try { this.room.send('model:update', msg); return true; } catch (e) {
- log.warn('[studio-net] update failed:', e?.message || e);
- return false;
- }
- }
-
- /** Remove a model you own. */
- remove(id) {
- if (!this._live() || !id) return false;
- try { this.room.send('model:remove', { id: String(id) }); return true; } catch (e) {
- log.warn('[studio-net] remove failed:', e?.message || e);
- return false;
- }
- }
-
- heartbeat() {
- if (!this._live()) return;
- try { this.room.send('heartbeat', {}); } catch (e) { log.warn('[studio-net] heartbeat failed:', e?.message || e); }
- }
-
- destroy() {
- this._destroyed = true;
- if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }
- this._closeRoom();
- try { this.client = null; } catch {}
- this._setStatus('destroyed');
+export class StudioNet extends PackageStudioNet {
+ /** @param {ConstructorParameters<typeof PackageStudioNet>[0]} [opts] */
+ constructor(opts = {}) {
+ super({ ...opts, url: opts.url ?? defaultServerUrl() });
}
}
diff --git a/src/ar/webxr.js b/src/ar/webxr.js
index 21db77781..59251157e 100644
--- a/src/ar/webxr.js
+++ b/src/ar/webxr.js
@@ -15,9 +15,9 @@ import {
import {
advancePulse, isXrVisible, nextTrackingState, reticleVisual, TRACKING_LOSS_FRAMES,
-} from './anchor-lifecycle.js';
-import { DepthOcclusion } from './depth-occlusion.js';
-import { createPinchState, pinchEnd, pinchMove, pinchStart, touchDist } from './pinch-scale.js';
+} from '../../packages/ar-studio/src/studio/anchor-lifecycle.js';
+import { DepthOcclusion } from '../../packages/ar-studio/src/studio/depth-occlusion.js';
+import { createPinchState, pinchEnd, pinchMove, pinchStart, touchDist } from '../../packages/ar-studio/src/studio/pinch.js';
/** prefers-reduced-motion: calm, static reticle/confirm states when set. */
function _prefersReducedMotion() {
diff --git a/tests/ar-studio-coords.test.js b/tests/ar-studio-coords.test.js
index 291f03f09..66601b29b 100644
--- a/tests/ar-studio-coords.test.js
+++ b/tests/ar-studio-coords.test.js
@@ -16,7 +16,7 @@ import {
roomKeyForCode,
roomShareUrl,
sharedToLocal,
-} from '../src/ar/studio-coords.js';
+} from '../packages/ar-studio/src/studio/coords.js';
describe('angle normalization', () => {
it('wraps radians into [0, 2π) and degrees into [0, 360)', () => {
@@ -93,7 +93,7 @@ describe('room codes', () => {
it('derives a stable filterBy key and a valid share URL', () => {
const code = generateRoomCode(() => 0.42);
expect(roomKeyForCode(code)).toBe(`c-${code}`);
- expect(roomShareUrl('https://three.ws', code)).toBe(`https://three.ws/ar/studio?room=${code}`);
- expect(roomShareUrl('https://three.ws', 'bad')).toBe('https://three.ws/ar/studio');
+ expect(roomShareUrl('https://three.ws/ar/studio', code)).toBe(`https://three.ws/ar/studio?room=${code}`);
+ expect(roomShareUrl('https://three.ws/ar/studio', 'bad')).toBe('https://three.ws/ar/studio');
});
});
diff --git a/tests/ar-studio-package-parity.test.js b/tests/ar-studio-package-parity.test.js
new file mode 100644
index 000000000..db8337ebf
--- /dev/null
+++ b/tests/ar-studio-package-parity.test.js
@@ -0,0 +1,49 @@
+// The in-app AR Studio (/ar/studio) and the 3d-ar-studio package share one
+// implementation: src/ar-studio.js imports the package's core modules from
+// packages/ar-studio. The one thing that exists in two places by necessity is the
+// Colyseus wire schema (the room server in multiplayer/ cannot import a client
+// package), so this suite fails the moment the two layouts drift.
+
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const read = (p) => readFileSync(new URL(`../${p}`, import.meta.url), 'utf8');
+
+/** Every `defineTypes(Class, { ... })` call, whitespace-normalised, keyed by class. */
+function definedTypes(source) {
+ const out = {};
+ const re = /defineTypes\(\s*(\w+)\s*,\s*(\{[\s\S]*?\n\})\s*\)/g;
+ for (const m of source.matchAll(re)) {
+ out[m[1]] = m[2].replace(/\/\/.*$/gm, '').replace(/\s+/g, ' ').trim();
+ }
+ return out;
+}
+
+describe('studio room wire schema', () => {
+ const server = definedTypes(read('multiplayer/src/studio-schemas.js'));
+ const client = definedTypes(read('packages/ar-studio/src/studio/schemas.js'));
+
+ it('declares the same classes on both sides', () => {
+ expect(Object.keys(server).sort()).toEqual(['StudioModel', 'StudioState', 'StudioViewer']);
+ expect(Object.keys(client).sort()).toEqual(Object.keys(server).sort());
+ });
+
+ it.each(['StudioModel', 'StudioViewer', 'StudioState'])('%s has the same field layout', (name) => {
+ expect(client[name]).toBe(server[name]);
+ });
+});
+
+describe('one implementation', () => {
+ it('the page code imports the package core instead of keeping a copy', () => {
+ const app = read('src/ar-studio.js');
+ for (const mod of ['multi-place', 'scene-math', 'coords', 'pinch', 'estimated-lighting']) {
+ expect(app).toContain(`packages/ar-studio/src/studio/${mod}.js`);
+ }
+ });
+
+ it('the hosted net client only adds the three.ws server resolution', () => {
+ const net = read('src/ar/studio-net.js');
+ expect(net).toContain('extends PackageStudioNet');
+ expect(net).not.toContain("from 'colyseus.js'");
+ });
+});
diff --git a/tests/ar-studio-scene.test.js b/tests/ar-studio-scene.test.js
index e1d4d2513..7d665c3c2 100644
--- a/tests/ar-studio-scene.test.js
+++ b/tests/ar-studio-scene.test.js
@@ -26,7 +26,7 @@ import {
studioShareUrl,
touchAngle,
twistDelta,
-} from '../src/ar/studio-scene.js';
+} from '../packages/ar-studio/src/studio/scene-math.js';
const box = (w, h, d, minY = 0) => ({
min: { x: -w / 2, y: minY, z: -d / 2 },
@@ -219,15 +219,15 @@ describe('studioSceneUrl', () => {
const scene = [{ src: 'https://x.co/a.glb', title: 'A', x: 1, z: 2, yaw: 0.5, scale: 1.2 }];
it('appends the arrangement hash to the src-list URL', () => {
- const url = studioSceneUrl('https://three.ws', scene);
+ const url = studioSceneUrl('https://three.ws/ar/studio', scene);
const [base, hash] = url.split('#s=');
- expect(base).toBe(studioShareUrl('https://three.ws', scene));
+ expect(base).toBe(studioShareUrl('https://three.ws/ar/studio', scene));
expect(sceneFromHashParam(hash)).toEqual(scene);
});
it('falls back to the src-only URL when the payload would be QR-hostile', () => {
- const url = studioSceneUrl('https://three.ws', scene, 40);
- expect(url).toBe(studioShareUrl('https://three.ws', scene));
+ const url = studioSceneUrl('https://three.ws/ar/studio', scene, 40);
+ expect(url).toBe(studioShareUrl('https://three.ws/ar/studio', scene));
expect(url).not.toContain('#s=');
});
});
@@ -282,7 +282,7 @@ describe('roomLightFromPixels', () => {
describe('studioShareUrl', () => {
it('embeds unique sources up to the cap', () => {
- const url = studioShareUrl('https://three.ws', [
+ const url = studioShareUrl('https://three.ws/ar/studio', [
{ src: 'https://x.co/a.glb', title: 'A' },
{ src: 'https://x.co/a.glb', title: 'A again' }, // duplicate source
{ src: 'https://x.co/b.glb', title: 'B' },
@@ -292,7 +292,7 @@ describe('studioShareUrl', () => {
});
it('returns the bare studio URL for an empty or invalid scene', () => {
- expect(studioShareUrl('https://three.ws', [])).toBe('https://three.ws/ar/studio');
- expect(studioShareUrl('https://three.ws', [{ src: 'data:x' }])).toBe('https://three.ws/ar/studio');
+ expect(studioShareUrl('https://three.ws/ar/studio', [])).toBe('https://three.ws/ar/studio');
+ expect(studioShareUrl('https://three.ws/ar/studio', [{ src: 'data:x' }])).toBe('https://three.ws/ar/studio');
});
});