Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
chore: move to Bun 1.4.2, and stop the MCP bundle starting itself on import (#68)
Matthew Kissingerdc873a681c45
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9813bad5..d698c6f2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -28,15 +28,15 @@ jobs:- name: Setup Bunuses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:- bun-version: 1.3.14+ bun-version: 1.4.2- name: Setup Nodeuses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4with:- node-version: 22.23.1+ node-version: 22.23.2- name: Setup npm- run: npm install --global [email protected]+ run: npm install --global [email protected]- name: Check toolchain metadatarun: bun run check:toolchain@@ -76,11 +76,11 @@ jobs:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:- bun-version: 1.3.14+ bun-version: 1.4.2- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4with:- node-version: 22.23.1- - run: npm install --global [email protected]+ node-version: 22.23.2+ - run: npm install --global [email protected]- run: bun install --frozen-lockfile- run: bun run build:runtime- name: Pack without publishing@@ -112,9 +112,9 @@ jobs:# Consumers install only Node/npm. Bun builds the tarball in the separate producer job.- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4with:- node-version: 22.23.1+ node-version: 22.23.2architecture: ${{ matrix.arch }}- - run: npm install --global [email protected]+ - run: npm install --global [email protected]- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0with:name: node-package-candidate@@ -134,7 +134,7 @@ jobs:env:EXPECTED_ARCH: ${{ matrix.arch }}run: >-- node -e "const fs=require('node:fs'),assert=require('node:assert/strict'),crypto=require('node:crypto');const r=JSON.parse(fs.readFileSync('package-smoke.json','utf8'));assert.equal(r.status,'passed');assert.equal(r.platform,'darwin');assert.equal(r.arch,process.env.EXPECTED_ARCH);assert.equal(r.node,'v22.23.1');assert.equal(r.npm,'12.0.1');assert.equal(r.tarballSha256,crypto.createHash('sha256').update(fs.readFileSync(r.tarball)).digest('hex'));for(const check of ['packaged-node-worker','source-reference-edit-images','server-restart-persistence','exact-source-export'])assert(r.checks.includes(check));"+ node -e "const fs=require('node:fs'),assert=require('node:assert/strict'),crypto=require('node:crypto');const r=JSON.parse(fs.readFileSync('package-smoke.json','utf8'));assert.equal(r.status,'passed');assert.equal(r.platform,'darwin');assert.equal(r.arch,process.env.EXPECTED_ARCH);assert.equal(r.node,'v22.23.2');assert.equal(r.npm,'12.0.2');assert.equal(r.tarballSha256,crypto.createHash('sha256').update(fs.readFileSync(r.tarball)).digest('hex'));for(const check of ['packaged-node-worker','source-reference-edit-images','server-restart-persistence','exact-source-export'])assert(r.checks.includes(check));"- name: Retain macOS package receiptif: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.ymlindex ab5b9dbb..269f31f5 100644--- a/.github/workflows/pages.yml+++ b/.github/workflows/pages.yml@@ -48,7 +48,7 @@ jobs:- name: Setup Bunuses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:- bun-version: 1.3.14+ bun-version: 1.4.2- name: Install the enginerun: bun install --frozen-lockfilediff --git a/CHANGELOG.md b/CHANGELOG.mdindex adc70806..694b05f9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,26 @@Changes to `@kiln/engine`. Source and installable packages are distributed throughGitHub. The package is not published on the npm registry.+## Toolchain moved to Bun 1.4.2, and the MCP bundle stopped starting itself — 2026-09-11++- Development toolchain pins move to Bun 1.4.2, Node 22.23.2 and npm 12.0.2.+ Bun 1.4 also fixes the early-exit behaviour above at its source: the pre-fix+ CLI, which produced empty output in 6 of 8 concurrent runs on 1.3.14, produced+ full output in 16 of 16 on 1.4.2. The `withProcessAlive` guard stays -- it+ holds for anyone still on 1.3.x, and nothing in the runtime contract promises+ otherwise. The offline suite runs about 18% faster.+- **`dist/mcp-server.mjs` started a stdio server when merely imported, and had+ done so for as long as the bundle has existed.** The source guarded its entry+ block with `import.meta.main`, a Bun property that no Bun release lowers+ correctly for a `--target=node` bundle. Every lowering emits+ `__require.main == __require.module`; under Node ESM both sides are+ `undefined`, so the guard was always true. Bun 1.4 then stopped emitting the+ `__require` helper that line still references, which turned the same+ expression into a `ReferenceError` before the server could speak -- loud where+ it had been silent, and how this was finally caught. Both entries now decide+ from `process.argv[1]` through a shared `isDirectEntry`, which needs no+ lowering and means the same thing on both runtimes.+## `kiln` commands no longer exit 0 in silence under Bun — 2026-09-11- Under Bun, a CLI command could exit 0 having written nothing at all: no output,diff --git a/bun.lock b/bun.lockindex 2ff3590d..6ca5aeeb 100644--- a/bun.lock+++ b/bun.lock@@ -29,7 +29,7 @@"@biomejs/biome": "^2.5.3","@google/genai": "^2.17.1","@strands-agents/sdk": "1.13.0",- "@types/bun": "^1.3.14",+ "@types/bun": "^1.4.2","ai": "^6.0.222","openai": "^6.46.0","typescript": "^7.0.2",@@ -242,7 +242,7 @@"@tweenjs/tween.js": ["@tweenjs/[email protected]", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],- "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.2" } }, "sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ=="],"@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],@@ -326,7 +326,7 @@"buffer-equal-constant-time": ["[email protected]", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="],- "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="],"bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],diff --git a/coverage-thresholds.json b/coverage-thresholds.jsonindex 02d0ed3a..dd04e9fc 100644--- a/coverage-thresholds.json+++ b/coverage-thresholds.json@@ -1,7 +1,9 @@{"measuredBaseline": {- "functions": 95.93,- "lines": 92.54+ "functions": 95.43,+ "lines": 92.58,+ "measuredUnder": "[email protected]",+ "measuredOn": "2026-09-11"},"thresholds": {"functions": 92,diff --git a/dist/agent-providers.mjs b/dist/agent-providers.mjsindex 25ae3e6d..0c25ea14 100644--- a/dist/agent-providers.mjs+++ b/dist/agent-providers.mjs@@ -279,11 +279,11 @@ function harnessIdToAgentModelId(id) {return null;}export {- toCachedSystemPrompt,- resolveOpenRouterReasoning,- resolveKilnAgentModel,- modelConsumesSystemPromptCachePoints,- makeOpenRouterModel,+ harnessIdToAgentModelId,makeKilnModel,- harnessIdToAgentModelId+ makeOpenRouterModel,+ modelConsumesSystemPromptCachePoints,+ resolveKilnAgentModel,+ resolveOpenRouterReasoning,+ toCachedSystemPrompt};diff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex a52ad502..cc617215 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -1,4 +1,3 @@-import { createRequire } from "node:module";var __defProp = Object.defineProperty;var __returnValue = (v) => v;function __exportSetter(name, newValue) {@@ -13,8 +12,17 @@ var __export = (target, all) => {set: __exportSetter.bind(all, name)});};-var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);-var __require = /* @__PURE__ */ createRequire(import.meta.url);+var __esm = (fn, res, err) => () => {+ if (fn)+ try {+ res = fn(fn = 0);+ } catch (e) {+ err = [e];+ }+ if (err)+ throw err[0];+ return res;+};// src/geometry-catalog.tsvar geometryPrimitives;@@ -3152,7 +3160,7 @@ function readSemanticMetadataV1FromExtras(extras) {const result = validateSemanticMetadataV1(value);return result.valid ? result.value : undefined;}-var KILN_SEMANTIC_EXTRAS_KEY = "kilnSemantic", KILN_SEMANTIC_SCHEMA_VERSION = 1, KILN_SEMANTIC_ROLES, isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isNonEmptyString2 = (value) => typeof value === "string" && value.trim().length > 0 && value === value.trim(), isFiniteTuple = (value, length2) => Array.isArray(value) && value.length === length2 && value.every((component) => typeof component === "number" && Number.isFinite(component)), cloneTuple3 = (value) => [+var KILN_SEMANTIC_EXTRAS_KEY = "kilnSemantic", KILN_SEMANTIC_SCHEMA_VERSION = 1, KILN_SEMANTIC_ROLES, isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isNonEmptyString2 = (value) => typeof value === "string" && value.trim().length > 0 && value === value.trim(), isFiniteTuple = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), cloneTuple3 = (value) => [value[0],value[1],value[2]@@ -3314,8 +3322,8 @@ function validateCharacterJointDescriptorV1(value) {const forwardValid = validateUnitVector(forwardAxis, "localForwardAxis", issues);const bendValid = validateUnitVector(bendAxis, "localBendAxis", issues);if (forwardValid && bendValid) {- const dot2 = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];- if (Math.abs(dot2) > 0.000001) {+ const dot = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];+ if (Math.abs(dot) > 0.000001) {issues.push({code: "NON_ORTHOGONAL_AXES",path: "localBendAxis",@@ -3642,7 +3650,7 @@ function characterBodyPlanRecipe(bodyPlan, customGraph) {const roles = customGraph?.joints.map((joint) => joint.role).join(", ");return `Resolved body plan: CUSTOM. Expand only the declared semantic graph${roles ? ` (${roles})` : ""}; preserve every explicit parent edge, end effector, contact, and local axis without adding another body-plan preset.`;}-var KILN_CHARACTER_JOINT_EXTRAS_KEY = "kilnCharacterJoint", KILN_CHARACTER_RIG_EXTRAS_KEY = "kilnCharacterRig", KILN_CHARACTER_JOINT_SCHEMA_VERSION = 1, CHARACTER_BODY_PLANS2, CHARACTER_JOINT_SIDES, IDENTITY_QUATERNION, UNIT_SCALE, FORWARD_AXIS, BEND_AXIS, isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isFiniteTuple2 = (value, length2) => Array.isArray(value) && value.length === length2 && value.every((component) => typeof component === "number" && Number.isFinite(component)), tuple3 = (value) => [value[0], value[1], value[2]], tuple4 = (value) => [+var KILN_CHARACTER_JOINT_EXTRAS_KEY = "kilnCharacterJoint", KILN_CHARACTER_RIG_EXTRAS_KEY = "kilnCharacterRig", KILN_CHARACTER_JOINT_SCHEMA_VERSION = 1, CHARACTER_BODY_PLANS2, CHARACTER_JOINT_SIDES, IDENTITY_QUATERNION, UNIT_SCALE, FORWARD_AXIS, BEND_AXIS, isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isFiniteTuple2 = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), tuple3 = (value) => [value[0], value[1], value[2]], tuple4 = (value) => [value[0],value[1],value[2],@@ -5756,59 +5764,59 @@ var init_textures = __esm(() => {// src/material-resources.tsimport { createHash } from "node:crypto";-function provenance(descriptor2, hash) {+function provenance(descriptor, hash) {return {schemaVersion: 1,- resourceId: descriptor2.id,+ resourceId: descriptor.id,contentHash: hash,hashAlgorithm: "sha256",- usage: descriptor2.usage,- colorSpace: descriptor2.colorSpace,- resourceVersion: descriptor2.version,+ usage: descriptor.usage,+ colorSpace: descriptor.colorSpace,+ resourceVersion: descriptor.version,recipeVersion: 1,- delivery: descriptor2.delivery+ delivery: descriptor.delivery};}-function readPngDimensions(descriptor2, bytes) {+function readPngDimensions(descriptor, bytes) {const signature = [137, 80, 78, 71, 13, 10, 26, 10];if (bytes.byteLength < 24 || !signature.every((value, index) => bytes[index] === value) || String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR") {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "declared image/png bytes do not have a valid PNG signature and IHDR format");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "declared image/png bytes do not have a valid PNG signature and IHDR format");}const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);return { width: view.getUint32(16, false), height: view.getUint32(20, false) };}-function verifyResourcePayload(descriptor2, payload) {+function verifyResourcePayload(descriptor, payload) {if (!payload || typeof payload !== "object" || Array.isArray(payload)) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host payload must be { bytes, mime }");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host payload must be { bytes, mime }");}const keys = Object.keys(payload).sort();if (keys.length !== 2 || keys[0] !== "bytes" || keys[1] !== "mime") {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host payload must contain only bytes and MIME");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host payload must contain only bytes and MIME");}if (!(payload.bytes instanceof Uint8Array)) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host bytes must be Uint8Array");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host bytes must be Uint8Array");}- if (payload.mime !== descriptor2.mime) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `host MIME ${String(payload.mime)} does not match approved ${descriptor2.mime}`);+ if (payload.mime !== descriptor.mime) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `host MIME ${String(payload.mime)} does not match approved ${descriptor.mime}`);}const bytes = payload.bytes;if (bytes.byteLength > TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `encoded-byte limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes}; received ${bytes.byteLength}`);+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `encoded-byte limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes}; received ${bytes.byteLength}`);}- if (bytes.byteLength !== descriptor2.byteLength) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `expected ${descriptor2.byteLength} bytes, received ${bytes.byteLength}`);+ if (bytes.byteLength !== descriptor.byteLength) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `expected ${descriptor.byteLength} bytes, received ${bytes.byteLength}`);}- const { width, height } = readPngDimensions(descriptor2, bytes);+ const { width, height } = readPngDimensions(descriptor, bytes);if (width < 1 || height < 1 || width > TEXTURE_RESOLVER_LIMITS_V1.maxWidth || height > TEXTURE_RESOLVER_LIMITS_V1.maxHeight) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `dimension limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxWidth}x${TEXTURE_RESOLVER_LIMITS_V1.maxHeight}; received ${width}x${height}`);+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `dimension limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxWidth}x${TEXTURE_RESOLVER_LIMITS_V1.maxHeight}; received ${width}x${height}`);}const pixels = width * height;if (!Number.isSafeInteger(pixels) || pixels > TEXTURE_RESOLVER_LIMITS_V1.maxPixels) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`);+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`);}const hash = sha256(bytes);- if (hash !== descriptor2.contentHash) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `content hash ${hash} does not match the pinned ${descriptor2.contentHash}`);+ if (hash !== descriptor.contentHash) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `content hash ${hash} does not match the pinned ${descriptor.contentHash}`);}return hash;}@@ -5870,12 +5878,12 @@ class ApprovedTextureResourceCache {const hash = this.#hashById.get(id);if (hash)return this.#resolution(id, hash);- const descriptor2 = this.#registry[id];- if (descriptor2.delivery !== "embedded") {+ const descriptor = this.#registry[id];+ if (descriptor.delivery !== "embedded") {throw new ApprovedTextureResourceUnavailableError(id, "it is delivered at runtime; use resolveAsync() or load()");}const decoded = bytesFromBase64(EMBEDDED_RESOURCE_BASE64[id]);- this.#cacheBytes(id, verifyResourcePayload(descriptor2, { bytes: decoded, mime: descriptor2.mime }), decoded);+ this.#cacheBytes(id, verifyResourcePayload(descriptor, { bytes: decoded, mime: descriptor.mime }), decoded);return this.#resolution(id, this.#hashById.get(id));}async resolveAsync(id) {@@ -5888,7 +5896,7 @@ class ApprovedTextureResourceCache {return this.resolve(id);let pending = this.#pendingById.get(id);if (!pending) {- const descriptor2 = this.#registry[id];+ const descriptor = this.#registry[id];const resolver = this.#resolver;pending = (async () => {if (!resolver) {@@ -5905,7 +5913,7 @@ class ApprovedTextureResourceCache {let payload;try {payload = await Promise.race([- Promise.resolve().then(() => resolver(descriptor2, Object.freeze({+ Promise.resolve().then(() => resolver(descriptor, Object.freeze({signal: controller.signal,deadlineMs: this.#resolverDeadlineMs}))),@@ -5915,7 +5923,7 @@ class ApprovedTextureResourceCache {if (timer !== undefined)clearTimeout(timer);}- this.#cacheBytes(id, verifyResourcePayload(descriptor2, payload), payload.bytes);+ this.#cacheBytes(id, verifyResourcePayload(descriptor, payload), payload.bytes);return this.#resolution(id, this.#hashById.get(id));})().finally(() => {this.#pendingById.delete(id);@@ -5960,19 +5968,19 @@ class ApprovedTextureResourceCache {function approvedTextureCatalogV1(options = {}) {const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;return APPROVED_TEXTURE_RESOURCE_IDS.filter((id) => {- const descriptor2 = cache.descriptor(id);- if (descriptor2.quality === "placeholder" && options.includePlaceholders !== true)+ const descriptor = cache.descriptor(id);+ if (descriptor.quality === "placeholder" && options.includePlaceholders !== true)return false;return cache.available(id);}).map((id) => {- const descriptor2 = cache.descriptor(id);+ const descriptor = cache.descriptor(id);return {id,- label: descriptor2.label,- usage: descriptor2.usage,- delivery: descriptor2.delivery,- allowedSlots: descriptor2.allowedSlots,- recipeIds: descriptor2.recipeIds+ label: descriptor.label,+ usage: descriptor.usage,+ delivery: descriptor.delivery,+ allowedSlots: descriptor.allowedSlots,+ recipeIds: descriptor.recipeIds};});}@@ -6008,9 +6016,9 @@ function collectMaterialResourceProvenance(root) {const materials = Array.isArray(material) ? material : material ? [material] : [];for (const item of materials) {for (const texture of materialTextures(item)) {- const record2 = readMaterialResourceProvenance(texture);- if (record2)- records.set(`${record2.resourceId}:${record2.contentHash}:${record2.usage}`, record2);+ const record = readMaterialResourceProvenance(texture);+ if (record)+ records.set(`${record.resourceId}:${record.contentHash}:${record.usage}`, record);}}});@@ -6075,10 +6083,10 @@ function positive(value, name) {}function normalizedQuaternion(value) {const source = value ?? [0, 0, 0, 1];- const length2 = Math.hypot(source[0], source[1], source[2], source[3]);- if (!Number.isFinite(length2) || length2 <= 0.000000001)+ const length = Math.hypot(source[0], source[1], source[2], source[3]);+ if (!Number.isFinite(length) || length <= 0.000000001)throw new TypeError("socket rotation must be a finite quaternion");- return [source[0] / length2, source[1] / length2, source[2] / length2, source[3] / length2];+ return [source[0] / length, source[1] / length, source[2] / length, source[3] / length];}function semantic2(roles, options = {}) {return {@@ -6210,8 +6218,8 @@ function createWheelAssembly(name, materials, options) {]}));(steeringPivot ?? root).add(spinPivot);- const defaults2 = createWheelGeometrySet(radius, width);- const tire = new THREE3.Mesh(options.geometries?.tire ?? defaults2.tire, materials.tire);+ const defaults = createWheelGeometrySet(radius, width);+ const tire = new THREE3.Mesh(options.geometries?.tire ?? defaults.tire, materials.tire);const rim = new THREE3.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);const hub = new THREE3.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);tire.name = `Tire_${options.side}_${index}`;@@ -6410,8 +6418,8 @@ function legacyAssemblies(root) {});}function resolveVehicleWheelAssemblies(root) {- const semantic3 = semanticAssemblies(root);- return semantic3.length > 0 ? semantic3 : legacyAssemblies(root);+ const semantic = semanticAssemblies(root);+ return semantic.length > 0 ? semantic : legacyAssemblies(root);}function hasCanonicalVehicleFront(root) {let found = false;@@ -6485,8 +6493,8 @@ function cloneReference(reference) {}function currentEvidence(sequence, surface, fidelity) {if (fidelity.version === "kiln.view-fidelity.v1") {- const valid2 = SHA256.test(fidelity.inputGlbSha256) && fidelity.rendererId.trim().length > 0 && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded);- if (!valid2) {+ const valid = SHA256.test(fidelity.inputGlbSha256) && fidelity.rendererId.trim().length > 0 && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded);+ if (!valid) {return {sequence,surface,@@ -6591,7 +6599,7 @@ var init_evidence_history = __esm(() => {});// src/views/background.ts-var GRID_BACKGROUND_RGB, GRID_BACKGROUND_HEX = "#1a1a1a";+var GRID_BACKGROUND_RGB;var init_background = __esm(() => {GRID_BACKGROUND_RGB = [26, 26, 26];});@@ -6831,14 +6839,6 @@ function measureBounds(root) {const { bbox } = collectTriangles(root);return { min: [...bbox.min], max: [...bbox.max] };}-function coverage(rgb2, size) {- let filled = 0;- for (let i = 0;i < size * size; i++) {- if (rgb2[i * 3] !== BG[0] || rgb2[i * 3 + 1] !== BG[1] || rgb2[i * 3 + 2] !== BG[2])- filled++;- }- return filled / (size * size);-}function hideNodeInScene(root, match) {const test = typeof match === "function" ? match : (name) => {const t = match.toLowerCase();@@ -6896,10 +6896,10 @@ function triple(v, label) {}function listCameraSubjects(root) {const result = [];- const visit = (node2, path) => {- result.push({ node: node2, path, name: node2.name });+ const visit = (node, path) => {+ result.push({ node, path, name: node.name });const counts = new Map;- for (const child of node2.children ?? []) {+ for (const child of node.children ?? []) {const count = counts.get(child.name) ?? 0;counts.set(child.name, count + 1);visit(child, `${path}/${encodeURIComponent(child.name)}[${count}]`);@@ -7294,12 +7294,12 @@ function validatePbrRenderRequest(input) {target[1] - position[1],target[2] - position[2]];- const cross2 = [+ const cross = [view[1] * up[2] - view[2] * up[1],view[2] * up[0] - view[0] * up[2],view[0] * up[1] - view[1] * up[0]];- if (Math.hypot(...cross2) <= Math.hypot(...view) * Math.hypot(...up) * 0.000000001) {+ if (Math.hypot(...cross) <= Math.hypot(...view) * Math.hypot(...up) * 0.000000001) {throw new TypeError(`PbrRenderRequest.cameras[${index}].up must not be collinear with view`);}const number = (key) => {@@ -7373,9 +7373,9 @@ function chunk(type, data) {out.writeUInt32BE(crc32(crcInput), 8 + data.length);return out;}-function encodePng(rgb2, width, height) {- if (rgb2.length !== width * height * 3) {- throw new Error(`encodePng: expected ${width * height * 3} bytes, got ${rgb2.length}`);+function encodePng(rgb, width, height) {+ if (rgb.length !== width * height * 3) {+ throw new Error(`encodePng: expected ${width * height * 3} bytes, got ${rgb.length}`);}const ihdr = Buffer.alloc(13);ihdr.writeUInt32BE(width, 0);@@ -7389,7 +7389,7 @@ function encodePng(rgb2, width, height) {for (let y = 0;y < height; y++) {const rowStart = y * (1 + width * 3);raw[rowStart] = 0;- raw.set(rgb2.subarray(y * width * 3, (y + 1) * width * 3), rowStart + 1);+ raw.set(rgb.subarray(y * width * 3, (y + 1) * width * 3), rowStart + 1);}return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),@@ -7444,7 +7444,7 @@ function decodePng(png) {if (raw.length !== height * (1 + stride)) {throw new Error(`decodePng: expected ${height * (1 + stride)} raw bytes, got ${raw.length}`);}- const rgb2 = new Uint8Array(width * height * 3);+ const rgb = new Uint8Array(width * height * 3);const cur = new Uint8Array(stride);const prior = new Uint8Array(stride);for (let y = 0;y < height; y++) {@@ -7478,13 +7478,13 @@ function decodePng(png) {for (let px = 0;px < width; px++) {const src = px * channels;const dst = (y * width + px) * 3;- rgb2[dst] = cur[src];- rgb2[dst + 1] = cur[src + 1];- rgb2[dst + 2] = cur[src + 2];+ rgb[dst] = cur[src];+ rgb[dst + 1] = cur[src + 1];+ rgb[dst + 2] = cur[src + 2];}prior.set(cur);}- return { rgb: rgb2, width, height };+ return { rgb, width, height };}var CRC_TABLE, PNG_SIGNATURE;var init_png = __esm(() => {@@ -7525,11 +7525,11 @@ function prepareClip(root, clip) {const raw = track.name;if (!raw)continue;- const dot3 = raw.lastIndexOf(".");- if (dot3 === -1)+ const dot = raw.lastIndexOf(".");+ if (dot === -1)continue;- const nodeName = raw.slice(0, dot3);- const property = raw.slice(dot3 + 1);+ const nodeName = raw.slice(0, dot);+ const property = raw.slice(dot + 1);if (property !== "position" && property !== "quaternion" && property !== "scale")continue;const times = track.times ? Array.from(track.times) : [];@@ -7648,7 +7648,7 @@ function planFrameTimes(duration, count) {out.push(duration * i / (count - 1));return out;}-function stampLabel(rgb2, width, height, x0, y0, text, scale = 3) {+function stampLabel(rgb, width, height, x0, y0, text, scale = 3) {const gw = 3 * scale;const gh = 5 * scale;const gap = scale;@@ -7660,9 +7660,9 @@ function stampLabel(rgb2, width, height, x0, y0, text, scale = 3) {if (x < 0 || y < 0 || x >= width || y >= height)continue;const p = (y * width + x) * 3;- rgb2[p] = LABEL_BG[0];- rgb2[p + 1] = LABEL_BG[1];- rgb2[p + 2] = LABEL_BG[2];+ rgb[p] = LABEL_BG[0];+ rgb[p + 1] = LABEL_BG[1];+ rgb[p + 2] = LABEL_BG[2];}}let cx = x0 + pad;@@ -7681,9 +7681,9 @@ function stampLabel(rgb2, width, height, x0, y0, text, scale = 3) {if (x < 0 || y < 0 || x >= width || y >= height)continue;const p = (y * width + x) * 3;- rgb2[p] = LABEL_FG[0];- rgb2[p + 1] = LABEL_FG[1];- rgb2[p + 2] = LABEL_FG[2];+ rgb[p] = LABEL_FG[0];+ rgb[p + 1] = LABEL_FG[1];+ rgb[p + 2] = LABEL_FG[2];}}}@@ -7743,7 +7743,7 @@ var init_pose = __esm(() => {});// src/views/annotate.ts-function stampAxisGnomon(rgb2, size, viewDir) {+function stampAxisGnomon(rgb, size, viewDir) {const zl = Math.hypot(viewDir[0], viewDir[1], viewDir[2]) || 1;const z = [viewDir[0] / zl, viewDir[1] / zl, viewDir[2] / zl];const up = Math.abs(z[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];@@ -7780,20 +7780,20 @@ function stampAxisGnomon(rgb2, size, viewDir) {if (x < 0 || y < 0 || x >= size || y >= size)continue;const p = (y * size + x) * 3;- rgb2[p] = color[0];- rgb2[p + 1] = color[1];- rgb2[p + 2] = color[2];+ rgb[p] = color[0];+ rgb[p + 1] = color[1];+ rgb[p + 2] = color[2];}}}- stampLabel(rgb2, size, size, Math.round(ex) + 2, Math.round(ey) - 6, label, 1);+ stampLabel(rgb, size, size, Math.round(ex) + 2, Math.round(ey) - 6, label, 1);}}-function annotateViewCell(rgb2, size, view) {+function annotateViewCell(rgb, size, view) {const inset = Math.max(2, Math.round(size / 96));const width = size - inset * 2;if (width < 7 || (4 * view.name.length + 1) * inset <= width) {- stampLabel(rgb2, size, size, inset, inset, view.name, inset);+ stampLabel(rgb, size, size, inset, inset, view.name, inset);} else {const minimumScale = size >= 128 ? 2 : 1;const scale = Math.max(minimumScale, Math.floor(width / (4 * view.name.length + 1)));@@ -7814,10 +7814,10 @@ function annotateViewCell(rgb2, size, view) {}} elseremaining = "";- stampLabel(rgb2, size, size, inset, inset + row * 7 * scale, line, scale);+ stampLabel(rgb, size, size, inset, inset + row * 7 * scale, line, scale);}}- stampAxisGnomon(rgb2, size, view.dir);+ stampAxisGnomon(rgb, size, view.dir);}var GNOMON_AXES;var init_annotate = __esm(() => {@@ -7876,8 +7876,8 @@ function compositeViewPngGrid(pngs, cols = GRID_COLS, views) {for (let i = 0;i < decoded.length; i++)annotateViewCell(decoded[i].rgb, size, views[i]);}- const { rgb: rgb2, width, height } = compositeCellGrid(decoded.map((d) => d.rgb), size, cols);- return { png: encodePng(rgb2, width, height), width, height, cellSize: size };+ const { rgb, width, height } = compositeCellGrid(decoded.map((d) => d.rgb), size, cols);+ return { png: encodePng(rgb, width, height), width, height, cellSize: size };}var PAD = 4, PAD_COLOR, GRID_COLS = 3;var init_grid = __esm(() => {@@ -7887,14 +7887,6 @@ var init_grid = __esm(() => {});// src/views/capture-limits.ts-var exports_capture_limits = {};-__export(exports_capture_limits, {- resolveCaptureLimits: () => resolveCaptureLimits,- enforcePngCaptureBudget: () => enforcePngCaptureBudget,- enforceCapturePixels: () => enforceCapturePixels,- enforceCaptureBytes: () => enforceCaptureBytes,- DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS-});function resolveCaptureLimits(limits = {}) {const result = { ...DEFAULT_CAPTURE_LIMITS };for (const key of ["maxTotalPixels", "maxOutputBytes"]) {@@ -7947,9 +7939,9 @@ var init_capture_limits = __esm(() => {// src/views/capture-cache.tsvar exports_capture_cache = {};__export(exports_capture_cache, {- createCachedRenderPort: () => createCachedRenderPort,+ MemoryCaptureCache: () => MemoryCaptureCache,captureCpuCell: () => captureCpuCell,- MemoryCaptureCache: () => MemoryCaptureCache+ createCachedRenderPort: () => createCachedRenderPort});import { createHash as createHash2 } from "node:crypto";function clone(entry) {@@ -8130,11 +8122,11 @@ function createCachedRenderPort(port, options) {async function captureCpuCell(cache, identity, produce) {const snapshot = structuredClone(identity);const key = digest(text({ version: "kiln.capture-cache.v1", kind: "cpu", ...snapshot }));- const valid = (result2) => {+ const valid = (result) => {try {- enforcePngCaptureBudget([result2.png]);- const image = decodePng(result2.png);- return result2.inputGlbSha256 === snapshot.artifactGlbSha256 && image.width === snapshot.size && image.height === snapshot.size && result2.width === snapshot.size && result2.height === snapshot.size;+ enforcePngCaptureBudget([result.png]);+ const image = decodePng(result.png);+ return result.inputGlbSha256 === snapshot.artifactGlbSha256 && image.width === snapshot.size && image.height === snapshot.size && result.width === snapshot.size && result.height === snapshot.size;} catch {return false;}@@ -8223,17 +8215,12 @@ var init_authoring_diagnostic = __esm(() => {});// src/qa/types.ts-function isQaFinding(value) {- if (!isRecord5(value))- return false;- return typeof value.code === "string" && /^[A-Z][A-Z0-9_]*$/.test(value.code) && (value.disposition === "observe" || value.disposition === "warn" || value.disposition === "block") && QA_DIMENSIONS.includes(value.dimension) && typeof value.profile === "string" && value.profile.length > 0 && typeof value.message === "string" && value.message.length > 0;-}function createAssetQaReportV1(intent, options = {}) {const findings = [...options.findings ?? []];const evaluated = new Set(options.evaluatedDimensions ?? []);for (const finding of findings)evaluated.add(finding.dimension);- const dimensions2 = Object.fromEntries(QA_DIMENSIONS.map((dimension) => {+ const dimensions = Object.fromEntries(QA_DIMENSIONS.map((dimension) => {const dimensionFindings = findings.filter((finding) => finding.dimension === dimension);const result = {status: evaluated.has(dimension) ? statusForFindings(dimensionFindings) : "notEvaluated",@@ -8242,17 +8229,17 @@ function createAssetQaReportV1(intent, options = {}) {};return [dimension, result];}));- const statuses = QA_DIMENSIONS.map((dimension) => dimensions2[dimension].status);+ const statuses = QA_DIMENSIONS.map((dimension) => dimensions[dimension].status);const disposition = statuses.includes("block") ? "block" : statuses.includes("warn") ? "warn" : statuses.every((status) => status === "notEvaluated") ? "notEvaluated" : "pass";return {schemaVersion: 1,category: intent.category,qaProfile: intent.qaProfile,disposition,- dimensions: dimensions2+ dimensions};}-var QA_DIMENSIONS, isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), statusForFindings = (findings) => {+var QA_DIMENSIONS, statusForFindings = (findings) => {if (findings.some((finding) => finding.disposition === "block"))return "block";if (findings.some((finding) => finding.disposition === "warn"))@@ -8471,8 +8458,8 @@ function nonNegative(value, name) {throw new RangeError(`${name} must be finite and >= 0`);return value;}-function roleMetadata(roles2, relationships = [], frames = []) {- return { roles: roles2, relationships, frames, sockets: [] };+function roleMetadata(roles, relationships = [], frames = []) {+ return { roles, relationships, frames, sockets: [] };}function relationship(kind, target) {return { kind, target, targetType: "role" };@@ -8535,7 +8522,7 @@ function buildFace(roofRoot, profile, sideSign) {return roofRoot.matrixWorld.clone().multiply(localToRoof);};const direction = (axis) => axis.clone().transformDirection(world());- const point = (x, z3) => new THREE4.Vector3(x, 0, z3).applyMatrix4(world());+ const point = (x, z) => new THREE4.Vector3(x, 0, z).applyMatrix4(world());return {side,ridgeAxis: profile.ridgeAxis,@@ -8719,7 +8706,7 @@ function wallRunAxis(wall) {function wallNeighbors(wall) {return wall === "front" || wall === "back" ? ["left", "right"] : ["front", "back"];}-function createShellWall(name, wall, material, length2, height, thickness, openings) {+function createShellWall(name, wall, material, length, height, thickness, openings) {const axis = wallRunAxis(wall);const root = new THREE4.Object3D;root.name = `${name}_Wall_${wall}`;@@ -8729,15 +8716,15 @@ function createShellWall(name, wall, material, length2, height, thickness, openirelationship("adjacent-to", `wall.${neighbors[1]}`),relationship("adjacent-to", "floor")]));- const sorted = openings.map((opening2, index) => ({- ...opening2,- id: opening2.id ?? `${opening2.kind ?? "door"}-${index + 1}`,- kind: opening2.kind ?? "door",- offset: opening2.offset ?? 0,- width: positive2(opening2.width ?? (opening2.kind === "window" ? 1 : 1.1), "opening.width"),- height: positive2(opening2.height ?? (opening2.kind === "window" ? 1 : 2.1), "opening.height"),- sill: opening2.kind === "window" ? nonNegative(opening2.sill ?? 1, "opening.sill") : 0,- depth: positive2(opening2.depth ?? thickness, "opening.depth")+ const sorted = openings.map((opening, index) => ({+ ...opening,+ id: opening.id ?? `${opening.kind ?? "door"}-${index + 1}`,+ kind: opening.kind ?? "door",+ offset: opening.offset ?? 0,+ width: positive2(opening.width ?? (opening.kind === "window" ? 1 : 1.1), "opening.width"),+ height: positive2(opening.height ?? (opening.kind === "window" ? 1 : 2.1), "opening.height"),+ sill: opening.kind === "window" ? nonNegative(opening.sill ?? 1, "opening.sill") : 0,+ depth: positive2(opening.depth ?? thickness, "opening.depth")})).sort((a, b) => a.offset - b.offset);if (sorted.length > 1)throw new RangeError("the minimal gable shell supports at most one opening per wall");@@ -8753,15 +8740,15 @@ function createShellWall(name, wall, material, length2, height, thickness, openiconst markers = [];const opening = sorted[0];if (!opening)- panel("solid", -length2 / 2, length2 / 2, 0, height);+ panel("solid", -length / 2, length / 2, 0, height);else {const left = opening.offset - opening.width / 2;const right = opening.offset + opening.width / 2;const top = opening.sill + opening.height;- if (left <= -length2 / 2 || right >= length2 / 2 || top >= height)+ if (left <= -length / 2 || right >= length / 2 || top >= height)throw new RangeError(`opening on wall.${wall} must fit strictly inside the wall boundary`);- panel("left", -length2 / 2, left, 0, height);- panel("right", right, length2 / 2, 0, height);+ panel("left", -length / 2, left, 0, height);+ panel("right", right, length / 2, 0, height);panel("lintel", left, right, top, height);if (opening.sill > 0)panel("sill", left, right, 0, opening.sill);@@ -8880,16 +8867,16 @@ function createRoofSurfaceLayout(name, material, options) {const rows = Math.max(1, Math.ceil(downhill / rowHeight));const columns = Math.max(1, Math.ceil(along / tileWidth));for (let row = 0;row < rows; row++) {- const length2 = Math.min(rowHeight * 1.08, downhill);+ const length = Math.min(rowHeight * 1.08, downhill);for (let column = 0;column < columns; column++) {const offset = row % 2 === 0 ? 0 : tileWidth / 2;const x = -along / 2 + tileWidth * (column + 0.5) + offset;if (x + tileWidth / 2 <= along / 2 + EPSILON)specs.push({width: tileWidth * 0.96,- length: length2,+ length,x,- z: Math.min(downhill - length2 / 2, row * rowHeight + length2 / 2)+ z: Math.min(downhill - length / 2, row * rowHeight + length / 2)});}}@@ -9025,26 +9012,26 @@ function gearGeo(opts = {}) {}function bladeGeo(opts = {}) {const {- length: length2 = 1.5,+ length = 1.5,baseWidth = 0.1,thickness = 0.015,tipLength = 0.25,edgeBevel = 0} = opts;- if (length2 <= 0 || baseWidth <= 0 || thickness <= 0) {+ if (length <= 0 || baseWidth <= 0 || thickness <= 0) {throw new Error("bladeGeo: length, baseWidth, thickness must all be > 0");}- if (tipLength >= length2) {+ if (tipLength >= length) {throw new Error("bladeGeo: tipLength must be less than length");}const hw = baseWidth / 2;const ht = thickness / 2;- const shoulderY = length2 - tipLength;+ const shoulderY = length - tipLength;const outline = [[-hw, 0],[hw, 0],[hw, shoulderY],- [0, length2],+ [0, length],[-hw, shoulderY]];const n = outline.length;@@ -9232,8 +9219,8 @@ function normalizeSurfaceNormals(geo) {for (let i = 0;i < normal.count; i++) {const x = normal.getX(i);const y = normal.getY(i);- const z3 = normal.getZ(i);- const len = Math.hypot(x, y, z3);+ const z = normal.getZ(i);+ const len = Math.hypot(x, y, z);if (!Number.isFinite(len) || len < 0.000000000001) {normal.setXYZ(i, 0, 1, 0);repaired = true;@@ -9241,7 +9228,7 @@ function normalizeSurfaceNormals(geo) {}if (Math.abs(len - 1) <= 0.000001)continue;- normal.setXYZ(i, x / len, y / len, z3 / len);+ normal.setXYZ(i, x / len, y / len, z / len);repaired = true;}if (repaired)@@ -9316,10 +9303,10 @@ var init_ops = __esm(() => {// src/geometry.tsimport * as THREE7 from "three";-function finiteArray(values, label, length2) {+function finiteArray(values, label, length) {const result = Array.from(values);- if (length2 !== undefined && result.length !== length2)- throw new Error(`${label}: expected ${length2} values, got ${result.length}`);+ if (length !== undefined && result.length !== length)+ throw new Error(`${label}: expected ${length} values, got ${result.length}`);if (!result.every((n) => Number.isFinite(Math.fround(n))))throw new Error(`${label}: all values must be finite Float32 values`);return result;@@ -9582,7 +9569,7 @@ function deform(geometry, options, map) {throw new Error("deformation interval must be finite and increasing");[low, high] = options.interval;}- const length2 = high - low;+ const length = high - low;const out = geometry.clone();const position = out.getAttribute("position");for (let i = 0;i < points.length; i++) {@@ -9590,11 +9577,11 @@ function deform(geometry, options, map) {const epsilon = Math.max(1, Math.abs(low), Math.abs(high)) * 0.0000001;if (point.y < low - epsilon || point.y > high + epsilon)continue;- const t = length2 > epsilon ? THREE8.MathUtils.clamp((point.y - low) / length2, 0, 1) : 0;+ const t = length > epsilon ? THREE8.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;const weight = options.falloff?.(t) ?? 1;if (!Number.isFinite(weight) || weight < 0 || weight > 1)throw new Error("deformation falloff must return a finite weight between 0 and 1");- const mapped = map(point.clone(), t, low, length2);+ const mapped = map(point.clone(), t, low, length);if (![mapped.x, mapped.y, mapped.z].every(Number.isFinite))throw new Error("deformation callback must return finite coordinates");point.lerp(mapped, weight).applyMatrix4(matrix);@@ -9618,10 +9605,10 @@ function bend(geometry, options) {if (!Number.isFinite(options.angle))throw new Error("bend angle must be finite degrees");const angle = THREE8.MathUtils.degToRad(options.angle);- return deform(geometry, options, (p, t, low, length2) => {- if (Math.abs(angle) < 0.0000000001 || length2 === 0)+ return deform(geometry, options, (p, t, low, length) => {+ if (Math.abs(angle) < 0.0000000001 || length === 0)return p;- const radius = length2 / angle, theta = angle * t;+ const radius = length / angle, theta = angle * t;return new THREE8.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);});}@@ -9651,7 +9638,7 @@ function profilePoints(profile) {points.pop();if (points.length < 3)throw new Error("profile requires three distinct points");- const cross2 = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);+ const cross = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);for (let i = 0;i < points.length; i++) {const a = points[i], b = points[(i + 1) % points.length];if (a.distanceToSquared(b) < 0.00000000000000000001)@@ -9660,7 +9647,7 @@ function profilePoints(profile) {if (j === i + 1 || i === 0 && j === points.length - 1)continue;const c = points[j], d = points[(j + 1) % points.length];- if (cross2(a, b, c) * cross2(a, b, d) <= 0 && cross2(c, d, a) * cross2(c, d, b) <= 0 && Math.max(Math.min(a.x, b.x), Math.min(c.x, d.x)) <= Math.min(Math.max(a.x, b.x), Math.max(c.x, d.x)) + 0.0000000001 && Math.max(Math.min(a.y, b.y), Math.min(c.y, d.y)) <= Math.min(Math.max(a.y, b.y), Math.max(c.y, d.y)) + 0.0000000001)+ if (cross(a, b, c) * cross(a, b, d) <= 0 && cross(c, d, a) * cross(c, d, b) <= 0 && Math.max(Math.min(a.x, b.x), Math.min(c.x, d.x)) <= Math.min(Math.max(a.x, b.x), Math.max(c.x, d.x)) + 0.0000000001 && Math.max(Math.min(a.y, b.y), Math.min(c.y, d.y)) <= Math.min(Math.max(a.y, b.y), Math.max(c.y, d.y)) + 0.0000000001)throw new Error("profile self-intersects or touches itself");}}@@ -9748,10 +9735,10 @@ function loftProfiles(sections, options = {}) {return out;}function sweepProfile(profile, path, options = {}) {- const points = profilePoints(profile), closed = options.closed ?? false, twist2 = options.twist ?? 0;- if (!Number.isFinite(twist2))+ const points = profilePoints(profile), closed = options.closed ?? false, twist = options.twist ?? 0;+ if (!Number.isFinite(twist))throw new Error("sweepProfile twist must be finite degrees");- if (closed && Math.abs(twist2 / 360 - Math.round(twist2 / 360)) > 0.00000001)+ if (closed && Math.abs(twist / 360 - Math.round(twist / 360)) > 0.00000001)throw new Error("closed sweep twist must be a multiple of 360 degrees");if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))throw new Error("sweepProfile requires finite path points (two open or three closed)");@@ -9795,11 +9782,11 @@ function sweepProfile(profile, path, options = {}) {const up = options.up ? new THREE9.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE9.Vector3(0, 0, 1) : new THREE9.Vector3(1, 0, 0);if (![up.x, up.y, up.z].every(Number.isFinite) || up.lengthSq() < 0.00000000000000000001)throw new Error("sweepProfile up must be a finite nonzero vector");- let z3 = up.clone().addScaledVector(tangents[0], -up.dot(tangents[0]));- if (z3.lengthSq() < 0.000000000001)+ let z = up.clone().addScaledVector(tangents[0], -up.dot(tangents[0]));+ if (z.lengthSq() < 0.000000000001)throw new Error("sweepProfile up must not be parallel to the first path tangent");- z3.normalize();- const normals = [z3.clone()];+ z.normalize();+ const normals = [z.clone()];if (closed) {stations.push(stations[0].clone());tangents.push(tangents[0].clone());@@ -9807,8 +9794,8 @@ function sweepProfile(profile, path, options = {}) {}const distances = [0];for (let i = 1;i < stations.length; i++) {- z3 = z3.clone().applyQuaternion(new THREE9.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));- normals.push(z3);+ z = z.clone().applyQuaternion(new THREE9.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));+ normals.push(z);distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));}const total = distances[distances.length - 1];@@ -9817,7 +9804,7 @@ function sweepProfile(profile, path, options = {}) {correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));const rings = stations.map((station, i) => {const tangent = tangents[i], t = distances[i] / total;- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE9.MathUtils.degToRad(twist2)) * t);+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE9.MathUtils.degToRad(twist)) * t);const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));});@@ -9876,16 +9863,16 @@ function threeToManifold(src, mod, label, context) {let vertexOffset = 0, meshCount = 0;const stride = context.preserve ? 5 : 3;src.traverse((child) => {- const mesh2 = child;- if (!mesh2.isMesh)+ const mesh = child;+ if (!mesh.isMesh)return;- const geometry = mesh2.geometry, position = geometry.getAttribute("position");+ const geometry = mesh.geometry, position = geometry.getAttribute("position");if (!position)return;meshCount++;const index = geometry.index, count = index?.count ?? position.count;if (count % 3 !== 0)- throw new Error(`CSG ${label}: mesh "${mesh2.name || "(unnamed)"}" has ${count} ${index ? "indices" : "vertices"}, which is not a whole number of triangles. Every CSG input must be a triangle mesh.`);+ throw new Error(`CSG ${label}: mesh "${mesh.name || "(unnamed)"}" has ${count} ${index ? "indices" : "vertices"}, which is not a whole number of triangles. Every CSG input must be a triangle mesh.`);if (position.itemSize !== 3)throw new Error(`CSG ${label}: positions must have three components`);const uv = geometry.getAttribute("uv");@@ -9895,11 +9882,11 @@ function threeToManifold(src, mod, label, context) {if (uv)context.anyUV = true;else- context.missingUV.add(mesh2.name || label);+ context.missingUV.add(mesh.name || label);}const point = new THREE10.Vector3;for (let i = 0;i < position.count; i++) {- point.fromBufferAttribute(position, i).applyMatrix4(mesh2.matrixWorld);+ point.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))throw new Error(`CSG ${label}: transformed positions must be finite Float32 coordinates`);properties.push(point.x, point.y, point.z);@@ -9910,8 +9897,8 @@ function threeToManifold(src, mod, label, context) {properties.push(u, v);}}- const materials = Array.isArray(mesh2.material) ? mesh2.material : [mesh2.material];- const spans = sourceSpans(mesh2, count).sort((a, b) => a.start - b.start);+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];+ const spans = sourceSpans(mesh, count).sort((a, b) => a.start - b.start);let covered = 0;for (const span of spans) {if (!Number.isInteger(span.start) || !Number.isInteger(span.count) || span.start !== covered || span.count <= 0 || span.count % 3 || span.start % 3 || span.start + span.count > count || !materials[span.materialIndex])@@ -9928,7 +9915,7 @@ function threeToManifold(src, mod, label, context) {];if (triangle.some((j) => !Number.isInteger(j) || j < 0 || j >= position.count))throw new Error(`CSG ${label}: index outside positions`);- if (mesh2.matrixWorld.determinant() < 0)+ if (mesh.matrixWorld.determinant() < 0)[triangle[1], triangle[2]] = [triangle[2], triangle[1]];indices.push(...triangle.map((j) => j + vertexOffset));const prior = geometry.userData.kilnCsgProvenance;@@ -10217,19 +10204,19 @@ function bevelCrossSection(cs, bevel, style, segments, label) {dilated.delete();return out;}-function normalizeTaper(taper2) {- if (taper2 === undefined)+function normalizeTaper(taper) {+ if (taper === undefined)return [1, 1];- if (typeof taper2 === "number") {- if (!Number.isFinite(taper2) || taper2 < 0) {- throw new Error(`taper must be a finite number >= 0 (got ${taper2}).`);+ if (typeof taper === "number") {+ if (!Number.isFinite(taper) || taper < 0) {+ throw new Error(`taper must be a finite number >= 0 (got ${taper}).`);}- return [taper2, taper2];+ return [taper, taper];}- if (!Array.isArray(taper2) || taper2.length !== 2 || !taper2.every((v) => Number.isFinite(v) && v >= 0)) {- throw new Error(`taper must be a number or [x, y] pair of numbers >= 0 (got ${JSON.stringify(taper2)}).`);+ if (!Array.isArray(taper) || taper.length !== 2 || !taper.every((v) => Number.isFinite(v) && v >= 0)) {+ throw new Error(`taper must be a number or [x, y] pair of numbers >= 0 (got ${JSON.stringify(taper)}).`);}- return [taper2[0], taper2[1]];+ return [taper[0], taper[1]];}async function extrudeProfile(profile, options = {}) {assertFiniteProfile(profile, "extrudeProfile");@@ -10239,8 +10226,8 @@ async function extrudeProfile(profile, options = {}) {bevel = 0,bevelStyle = "round",segments = 12,- twist: twist2 = 0,- taper: taper2,+ twist = 0,+ taper,divisions,axis = "y",center = true,@@ -10271,8 +10258,8 @@ async function extrudeProfile(profile, options = {}) {if (bevel > 0) {section = track(bevelCrossSection(section, bevel, bevelStyle, segments, "extrudeProfile"));}- const nDivisions = divisions ?? (twist2 !== 0 ? 16 : 1);- const solid = section.extrude(depth, nDivisions, twist2, normalizeTaper(taper2), center);+ const nDivisions = divisions ?? (twist !== 0 ? 16 : 1);+ const solid = section.extrude(depth, nDivisions, twist, normalizeTaper(taper), center);try {return orientSweep(manifoldToGeometry(solid, { smooth }), axis);} finally {@@ -10413,8 +10400,8 @@ function strictRecord(value, path) {if (!Object.prototype.propertyIsEnumerable.call(value, key)) {throw new ProceduralTextureError(`${path}.${key} must be an enumerable JSON field.`);}- const descriptor2 = Object.getOwnPropertyDescriptor(value, key);- if (!descriptor2 || !("value" in descriptor2)) {+ const descriptor = Object.getOwnPropertyDescriptor(value, key);+ if (!descriptor || !("value" in descriptor)) {throw new ProceduralTextureError(`${path}.${key} must be a plain JSON data field.`);}}@@ -10441,9 +10428,9 @@ function strictArray(value, path) {}return value;}-function assertKeys(record2, allowed, path) {+function assertKeys(record, allowed, path) {const allow = new Set(allowed);- for (const key of Object.keys(record2)) {+ for (const key of Object.keys(record)) {if (!allow.has(key)) {throw new ProceduralTextureError(`${path} has unknown key ${JSON.stringify(key)}.`);}@@ -10499,8 +10486,8 @@ function angle(value, path) {const normalized = (bounded % 360 + 360) % 360;return Object.is(normalized, -0) ? 0 : normalized;}-function blend(record2, path) {- const value = record2["blend"] ?? "normal";+function blend(record, path) {+ const value = record["blend"] ?? "normal";if (!BLENDS.includes(value)) {throw new ProceduralTextureError(`${path}.blend ${JSON.stringify(value)} is not one of ${BLENDS.join(", ")}.`);}@@ -10508,70 +10495,70 @@ function blend(record2, path) {}function canonicalLayer(value, index) {const path = `proceduralTexture.layers[${index}]`;- const record2 = strictRecord(value, path);- const op = record2["op"];+ const record = strictRecord(value, path);+ const op = record["op"];if (!OPS.includes(op)) {throw new ProceduralTextureError(`${path}.op ${JSON.stringify(op)} is not one of ${OPS.join(", ")}.`);}- const validatedBlend = blend(record2, path);- const validatedOpacity = unit(record2["opacity"], `${path}.opacity`, 1);+ const validatedBlend = blend(record, path);+ const validatedOpacity = unit(record["opacity"], `${path}.opacity`, 1);const common = {blend: index === 0 ? "normal" : validatedBlend,opacity: index === 0 ? 1 : validatedOpacity};switch (op) {case "solid":- assertKeys(record2, ["op", "color", "blend", "opacity"], path);- return { op, color: color(record2["color"], `${path}.color`), ...common };+ assertKeys(record, ["op", "color", "blend", "opacity"], path);+ return { op, color: color(record["color"], `${path}.color`), ...common };case "checker":- assertKeys(record2, ["op", "colorA", "colorB", "squares", "blend", "opacity"], path);+ assertKeys(record, ["op", "colorA", "colorB", "squares", "blend", "opacity"], path);return {op,- colorA: color(record2["colorA"], `${path}.colorA`),- colorB: color(record2["colorB"], `${path}.colorB`),- squares: integer(record2["squares"], `${path}.squares`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ squares: integer(record["squares"], `${path}.squares`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),...common};case "stripes":- assertKeys(record2, ["op", "colorA", "colorB", "count", "angleDeg", "blend", "opacity"], path);+ assertKeys(record, ["op", "colorA", "colorB", "count", "angleDeg", "blend", "opacity"], path);return {op,- colorA: color(record2["colorA"], `${path}.colorA`),- colorB: color(record2["colorB"], `${path}.colorB`),- count: integer(record2["count"], `${path}.count`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- angleDeg: angle(record2["angleDeg"], `${path}.angleDeg`),+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ count: integer(record["count"], `${path}.count`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ angleDeg: angle(record["angleDeg"], `${path}.angleDeg`),...common};case "gradient":- assertKeys(record2, ["op", "from", "to", "angleDeg", "blend", "opacity"], path);+ assertKeys(record, ["op", "from", "to", "angleDeg", "blend", "opacity"], path);return {op,- from: color(record2["from"], `${path}.from`),- to: color(record2["to"], `${path}.to`),- angleDeg: angle(record2["angleDeg"], `${path}.angleDeg`),+ from: color(record["from"], `${path}.from`),+ to: color(record["to"], `${path}.to`),+ angleDeg: angle(record["angleDeg"], `${path}.angleDeg`),...common};case "bricks":- assertKeys(record2, ["op", "brick", "mortar", "rows", "cols", "mortarWidth", "stagger", "blend", "opacity"], path);+ assertKeys(record, ["op", "brick", "mortar", "rows", "cols", "mortarWidth", "stagger", "blend", "opacity"], path);return {op,- brick: color(record2["brick"], `${path}.brick`),- mortar: color(record2["mortar"], `${path}.mortar`),- rows: integer(record2["rows"], `${path}.rows`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- cols: integer(record2["cols"], `${path}.cols`, 4, 1, MAX_PROCEDURAL_PATTERN_COUNT),- mortarWidth: unit(record2["mortarWidth"], `${path}.mortarWidth`, 0.06),- stagger: unit(record2["stagger"], `${path}.stagger`, 0.5),+ brick: color(record["brick"], `${path}.brick`),+ mortar: color(record["mortar"], `${path}.mortar`),+ rows: integer(record["rows"], `${path}.rows`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ cols: integer(record["cols"], `${path}.cols`, 4, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ mortarWidth: unit(record["mortarWidth"], `${path}.mortarWidth`, 0.06),+ stagger: unit(record["stagger"], `${path}.stagger`, 0.5),...common};case "noise":- assertKeys(record2, ["op", "colorA", "colorB", "scale", "octaves", "seed", "blend", "opacity"], path);+ assertKeys(record, ["op", "colorA", "colorB", "scale", "octaves", "seed", "blend", "opacity"], path);return {op,- colorA: color(record2["colorA"], `${path}.colorA`),- colorB: color(record2["colorB"], `${path}.colorB`),- scale: integer(record2["scale"], `${path}.scale`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- octaves: integer(record2["octaves"], `${path}.octaves`, 3, 1, MAX_NOISE_OCTAVES),- seed: integer(record2["seed"], `${path}.seed`, 0, -2147483648, 2147483647),+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ scale: integer(record["scale"], `${path}.scale`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ octaves: integer(record["octaves"], `${path}.octaves`, 3, 1, MAX_NOISE_OCTAVES),+ seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),...common};default:@@ -10579,17 +10566,17 @@ function canonicalLayer(value, index) {}}function migrateProceduralTextureSpecV1(input) {- const record2 = strictRecord(input, "proceduralTexture");- assertKeys(record2, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");- if (record2["schemaVersion"] !== undefined && record2["schemaVersion"] !== 1) {- throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(record2["schemaVersion"])}.`);+ const record = strictRecord(input, "proceduralTexture");+ assertKeys(record, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");+ if (record["schemaVersion"] !== undefined && record["schemaVersion"] !== 1) {+ throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(record["schemaVersion"])}.`);}return {schemaVersion: 2,- ...record2["size"] !== undefined ? { size: record2["size"] } : {},- ...record2["usage"] !== undefined ? { usage: record2["usage"] } : {},- ...record2["name"] !== undefined ? { name: record2["name"] } : {},- layers: record2["layers"]+ ...record["size"] !== undefined ? { size: record["size"] } : {},+ ...record["usage"] !== undefined ? { usage: record["usage"] } : {},+ ...record["name"] !== undefined ? { name: record["name"] } : {},+ layers: record["layers"]};}function canonicalizeProceduralTextureSpecV2(input) {@@ -10625,14 +10612,14 @@ function canonicalJson(value) {return JSON.stringify(value);if (Array.isArray(value))return `[${value.map(canonicalJson).join(",")}]`;- const record2 = value;- return `{${Object.keys(record2).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record2[key])}`).join(",")}}`;+ const record = value;+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;}function canonicalProceduralTextureJsonV2(input) {return canonicalJson(canonicalizeProceduralTextureSpecV2(input));}-function sha256Hex(text2) {- const source = new TextEncoder().encode(text2);+function sha256Hex(text) {+ const source = new TextEncoder().encode(text);const bitLength = source.length * 8;const paddedLength = Math.ceil((source.length + 9) / 64) * 64;const bytes = new Uint8Array(paddedLength);@@ -10656,10 +10643,10 @@ function sha256Hex(text2) {for (let i = 0;i < 16; i++)w[i] = view.getUint32(offset + i * 4, false);for (let i = 16;i < 64; i++) {- const a2 = w[i - 15];- const b2 = w[i - 2];- const s0 = rotateRight(a2, 7) ^ rotateRight(a2, 18) ^ a2 >>> 3;- const s1 = rotateRight(b2, 17) ^ rotateRight(b2, 19) ^ b2 >>> 10;+ const a = w[i - 15];+ const b = w[i - 2];+ const s0 = rotateRight(a, 7) ^ rotateRight(a, 18) ^ a >>> 3;+ const s1 = rotateRight(b, 17) ^ rotateRight(b, 19) ^ b >>> 10;w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;}let [a, b, c, d, e, f, g, hh] = h;@@ -10690,29 +10677,29 @@ function hashProceduralTextureSpecV2(input) {}function canonicalTextureRef(value, slot) {const path = `portableMaterial.textures.${slot}`;- const record2 = strictRecord(value, path);- if (record2["kind"] === "procedural") {- assertKeys(record2, ["kind", "spec"], path);- const spec = canonicalizeProceduralTextureSpecV2(record2["spec"]);+ const record = strictRecord(value, path);+ if (record["kind"] === "procedural") {+ assertKeys(record, ["kind", "spec"], path);+ const spec = canonicalizeProceduralTextureSpecV2(record["spec"]);const expected = MATERIAL_TEXTURE_USAGE[slot];if (spec.usage !== expected) {throw new ProceduralTextureError(`${path} requires procedural usage ${JSON.stringify(expected)}, got ${JSON.stringify(spec.usage)}.`);}return { kind: "procedural", spec };}- if (record2["kind"] === "resource") {- assertKeys(record2, ["kind", "resourceId"], path);- const resourceId2 = record2["resourceId"];- if (typeof resourceId2 !== "string" || resourceId2.length > 128 || !/^kiln\.[a-z0-9][a-z0-9._-]+$/.test(resourceId2)) {+ if (record["kind"] === "resource") {+ assertKeys(record, ["kind", "resourceId"], path);+ const resourceId = record["resourceId"];+ if (typeof resourceId !== "string" || resourceId.length > 128 || !/^kiln\.[a-z0-9][a-z0-9._-]+$/.test(resourceId)) {throw new ProceduralTextureError(`${path}.resourceId must be a bounded kiln.* resource ID.`);}- return { kind: "resource", resourceId: resourceId2 };+ return { kind: "resource", resourceId };}throw new ProceduralTextureError(`${path}.kind must be "procedural" or "resource".`);}function canonicalizePortableMaterialSpecV2(input) {- const record2 = strictRecord(input, "portableMaterial");- assertKeys(record2, [+ const record = strictRecord(input, "portableMaterial");+ assertKeys(record, ["schemaVersion","model","name",@@ -10726,13 +10713,13 @@ function canonicalizePortableMaterialSpecV2(input) {"doubleSided","textures"], "portableMaterial");- if (record2["schemaVersion"] !== 2) {+ if (record["schemaVersion"] !== 2) {throw new ProceduralTextureError("portableMaterial.schemaVersion must be 2.");}- if (record2["model"] !== "pbrMetallicRoughness") {+ if (record["model"] !== "pbrMetallicRoughness") {throw new ProceduralTextureError('portableMaterial.model must be "pbrMetallicRoughness"; executable shader models are not portable.');}- const textureInput = record2["textures"] ?? {};+ const textureInput = record["textures"] ?? {};const textureRecord = strictRecord(textureInput, "portableMaterial.textures");const slots = Object.keys(MATERIAL_TEXTURE_USAGE);assertKeys(textureRecord, slots, "portableMaterial.textures");@@ -10752,26 +10739,26 @@ function canonicalizePortableMaterialSpecV2(input) {if (proceduralTexels > MAX_PORTABLE_MATERIAL_TEXELS) {throw new ProceduralTextureError(`portableMaterial procedural texture budget is ${proceduralTexels} texels, above ${MAX_PORTABLE_MATERIAL_TEXELS}.`);}- const alphaMode = record2["alphaMode"] ?? "opaque";+ const alphaMode = record["alphaMode"] ?? "opaque";if (alphaMode !== "opaque" && alphaMode !== "mask" && alphaMode !== "blend") {throw new ProceduralTextureError("portableMaterial.alphaMode must be opaque, mask, or blend.");}- if (record2["doubleSided"] !== undefined && typeof record2["doubleSided"] !== "boolean") {+ if (record["doubleSided"] !== undefined && typeof record["doubleSided"] !== "boolean") {throw new ProceduralTextureError("portableMaterial.doubleSided must be boolean.");}- const name = optionalName(record2["name"], "portableMaterial.name");+ const name = optionalName(record["name"], "portableMaterial.name");return {schemaVersion: 2,model: "pbrMetallicRoughness",...name !== undefined ? { name } : {},- ...record2["baseColor"] !== undefined ? { baseColor: color(record2["baseColor"], "portableMaterial.baseColor") } : {},- roughness: unit(record2["roughness"], "portableMaterial.roughness", 1),- metalness: unit(record2["metalness"], "portableMaterial.metalness", 0),- ...record2["emissive"] !== undefined ? { emissive: color(record2["emissive"], "portableMaterial.emissive") } : {},- emissiveIntensity: finite2(record2["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),+ ...record["baseColor"] !== undefined ? { baseColor: color(record["baseColor"], "portableMaterial.baseColor") } : {},+ roughness: unit(record["roughness"], "portableMaterial.roughness", 1),+ metalness: unit(record["metalness"], "portableMaterial.metalness", 0),+ ...record["emissive"] !== undefined ? { emissive: color(record["emissive"], "portableMaterial.emissive") } : {},+ emissiveIntensity: finite2(record["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),alphaMode,- alphaCutoff: unit(record2["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),- doubleSided: record2["doubleSided"] === true,+ alphaCutoff: unit(record["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),+ doubleSided: record["doubleSided"] === true,textures};}@@ -11004,11 +10991,11 @@ function compileProceduralTextureSpecV2(input) {}function proceduralTexture(spec) {const compiled = compileProceduralTextureSpecV2(spec);- const { size, usage: usage2, name, layers } = compiled.spec;+ const { size, usage, name, layers } = compiled.spec;const tex = new THREE11.DataTexture(compiled.pixels, size, size, THREE11.RGBAFormat, THREE11.UnsignedByteType);if (name)tex.name = name;- tex.colorSpace = usage2 === "albedo" || usage2 === "emissive" ? THREE11.SRGBColorSpace : THREE11.NoColorSpace;+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE11.SRGBColorSpace : THREE11.NoColorSpace;tex.wrapS = THREE11.RepeatWrapping;tex.wrapT = THREE11.RepeatWrapping;tex.minFilter = THREE11.LinearMipmapLinearFilter;@@ -11018,7 +11005,7 @@ function proceduralTexture(spec) {tex.userData["kilnProcedural"] = {schemaVersion: 2,size,- usage: usage2,+ usage,...name ? { name } : {},layers,canonicalJson: compiled.canonicalJson,@@ -11077,10 +11064,10 @@ function normalMapFromHeight(source, opts = {}) {tex.needsUpdate = true;return tex;}-var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color2) => [- color2 >> 16 & 255,- color2 >> 8 & 255,- color2 & 255+var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color) => [+ color >> 16 & 255,+ color >> 8 & 255,+ color & 255], lerp = (a, b, t) => a + (b - a) * t;var init_procedural_texture = __esm(() => {init_procedural_material_v2();@@ -11098,12 +11085,12 @@ async function compilePortableMaterialSpecV2(input) {if (!isApprovedResourceId(ref.resourceId)) {throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not an approved texture resource ID.`);}- const descriptor2 = cache.descriptor(ref.resourceId);- if (!descriptor2.allowedSlots.includes(slot)) {+ const descriptor = cache.descriptor(ref.resourceId);+ if (!descriptor.allowedSlots.includes(slot)) {throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not approved for that slot.`);}- if (descriptor2.usage !== SLOT_USAGE[slot]) {- throw new ProceduralTextureError(`portableMaterial.textures.${slot} requires ${SLOT_USAGE[slot]} data, but ${JSON.stringify(ref.resourceId)} provides ${descriptor2.usage}.`);+ if (descriptor.usage !== SLOT_USAGE[slot]) {+ throw new ProceduralTextureError(`portableMaterial.textures.${slot} requires ${SLOT_USAGE[slot]} data, but ${JSON.stringify(ref.resourceId)} provides ${descriptor.usage}.`);}}const loaded = new Map;@@ -11242,8 +11229,8 @@ function repairZeroNormals(geo) {for (let i = 0;i < normal.count; i++) {const x = normal.getX(i);const y = normal.getY(i);- const z3 = normal.getZ(i);- if (!Number.isFinite(x + y + z3) || Math.hypot(x, y, z3) < 0.000001)+ const z = normal.getZ(i);+ if (!Number.isFinite(x + y + z) || Math.hypot(x, y, z) < 0.000001)broken.add(i);}if (broken.size === 0)@@ -11334,15 +11321,15 @@ function cylindricalProjectToUVs(geo) {for (let i = 0;i < pos.count; i++) {const x = pos.getX(i);const y = pos.getY(i);- const z3 = pos.getZ(i);+ const z = pos.getZ(i);if (nrm && Math.abs(nrm.getY(i)) > 0.7) {uv[i * 2] = (x - bb.min.x) / spanX;- uv[i * 2 + 1] = (z3 - bb.min.z) / spanZ;+ uv[i * 2 + 1] = (z - bb.min.z) / spanZ;continue;}- const a = Math.atan2(z3, x);+ const a = Math.atan2(z, x);uv[i * 2] = span > 0.000001 ? (a - minA) / span : 0.5;- uv[i * 2 + 1] = height > 0.000001 ? (y - minY) / height : Math.hypot(x, z3) / maxR;+ uv[i * 2 + 1] = height > 0.000001 ? (y - minY) / height : Math.hypot(x, z) / maxR;}geo.setAttribute("uv", new THREE13.BufferAttribute(uv, 2));}@@ -11384,19 +11371,19 @@ var init_uv_shapes = () => {};// src/material-recipe-runtime.tsimport * as THREE14 from "three";async function applyMaterialRecipeV1(request, options = {}) {- const resolved2 = resolveMaterialRecipeV1(request);+ const resolved = resolveMaterialRecipeV1(request);const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;const loaded = new Map;- for (const [slot, id] of Object.entries(resolved2.textureResources)) {+ for (const [slot, id] of Object.entries(resolved.textureResources)) {if (id)loaded.set(slot, await cache.load(id));}const materialOptions = {- roughness: resolved2.roughnessFactor,- metalness: resolved2.metallicFactor,- alphaMode: lowerAlphaMode(resolved2.alphaMode),- ...resolved2.alphaMode === "MASK" ? { alphaCutoff: resolved2.alphaCutoff ?? 0.5 } : {},- doubleSided: resolved2.doubleSided,+ roughness: resolved.roughnessFactor,+ metalness: resolved.metallicFactor,+ alphaMode: lowerAlphaMode(resolved.alphaMode),+ ...resolved.alphaMode === "MASK" ? { alphaCutoff: resolved.alphaCutoff ?? 0.5 } : {},+ doubleSided: resolved.doubleSided,...loaded.get("baseColor") ? { albedo: loaded.get("baseColor").texture } : {},...loaded.get("normal") ? { normal: loaded.get("normal").texture } : {},...loaded.get("metallicRoughness") ? { metallicRoughness: loaded.get("metallicRoughness").texture } : {},@@ -11405,11 +11392,11 @@ async function applyMaterialRecipeV1(request, options = {}) {};const material = pbrMaterial(materialOptions);material.name = options.name ?? request.id;- material.color.setRGB(resolved2.baseColorFactor[0], resolved2.baseColorFactor[1], resolved2.baseColorFactor[2], THREE14.LinearSRGBColorSpace);- material.opacity = resolved2.baseColorFactor[3];- material.emissive.setRGB(resolved2.emissiveFactor[0], resolved2.emissiveFactor[1], resolved2.emissiveFactor[2], THREE14.LinearSRGBColorSpace);+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE14.LinearSRGBColorSpace);+ material.opacity = resolved.baseColorFactor[3];+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE14.LinearSRGBColorSpace);const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));- const provenance2 = {+ const provenance = {schemaVersion: 1,recipeId: request.id,recipeVersion: 1,@@ -11426,8 +11413,8 @@ async function applyMaterialRecipeV1(request, options = {}) {portableModel: "pbrMetallicRoughness",resources};- material.userData["kilnMaterialRecipe"] = provenance2;- return { material, resolved: resolved2, provenance: provenance2 };+ material.userData["kilnMaterialRecipe"] = provenance;+ return { material, resolved, provenance };}async function materialRecipe(id, overrides, options = {}) {return (await applyMaterialRecipeV1(createMaterialRecipeRequestV1(id, overrides), options)).material;@@ -11530,26 +11517,26 @@ function createPart(name, geometry2, material, options = {}) {function capsuleGeo(radius, height, segments = 6) {return new THREE15.CapsuleGeometry(radius, height, 2, segments);}-function capsuleXGeo(radius, length2, segments = 6) {- const geo = capsuleGeo(radius, length2, segments);+function capsuleXGeo(radius, length, segments = 6) {+ const geo = capsuleGeo(radius, length, segments);geo.rotateZ(-Math.PI / 2);return geo;}-function capsuleZGeo(radius, length2, segments = 6) {- const geo = capsuleGeo(radius, length2, segments);+function capsuleZGeo(radius, length, segments = 6) {+ const geo = capsuleGeo(radius, length, segments);geo.rotateX(Math.PI / 2);return geo;}function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {return new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);}-function cylinderXGeo(radiusTop, radiusBottom, length2, segments = 8) {- const geo = cylinderGeo(radiusTop, radiusBottom, length2, segments);+function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {+ const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);geo.rotateZ(-Math.PI / 2);return geo;}-function cylinderZGeo(radiusTop, radiusBottom, length2, segments = 8) {- const geo = cylinderGeo(radiusTop, radiusBottom, length2, segments);+function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {+ const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);geo.rotateX(Math.PI / 2);return geo;}@@ -11562,13 +11549,13 @@ function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {function coneGeo(radius, height, segments = 8) {return new THREE15.ConeGeometry(radius, height, segments);}-function coneXGeo(radius, length2, segments = 8) {- const geo = coneGeo(radius, length2, segments);+function coneXGeo(radius, length, segments = 8) {+ const geo = coneGeo(radius, length, segments);geo.rotateZ(-Math.PI / 2);return geo;}-function coneZGeo(radius, length2, segments = 8) {- const geo = coneGeo(radius, length2, segments);+function coneZGeo(radius, length, segments = 8) {+ const geo = coneGeo(radius, length, segments);geo.rotateX(Math.PI / 2);return geo;}@@ -11621,10 +11608,10 @@ function crossedQuadsGeo(opts = {}) {const yPivot = opts.yPivot ?? 0;const geometries = [];for (let i = 0;i < planes; i++) {- const angle2 = i / planes * Math.PI;+ const angle = i / planes * Math.PI;const quad = new THREE15.PlaneGeometry(w, h);quad.translate(0, h * (0.5 - yPivot), 0);- quad.rotateY(angle2);+ quad.rotateY(angle);geometries.push(quad);}const out = new THREE15.BufferGeometry;@@ -11780,11 +11767,11 @@ function beamBetween(name, start, end, radius, material, options = {}) {const a = new THREE15.Vector3(...start);const b = new THREE15.Vector3(...end);const direction = b.clone().sub(a);- const length2 = direction.length();- if (length2 <= 0.0001) {- throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length2.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);+ const length = direction.length();+ if (length <= 0.0001) {+ throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);}- const mesh = new THREE15.Mesh(cylinderGeo(radius, radius, length2, options.segments ?? 8), material);+ const mesh = new THREE15.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);mesh.name = `Mesh_${name}`;mesh.position.copy(a.add(b).multiplyScalar(0.5));mesh.quaternion.setFromUnitVectors(new THREE15.Vector3(0, 1, 0), direction.normalize());@@ -11859,7 +11846,7 @@ function createLadder(name, options) {return { leftRail, rightRail, rungs };}function wallWithOpening(name, material, options) {- const { length: length2, height, thickness, axis = "z", opening, parent } = options;+ const { length, height, thickness, axis = "z", opening, parent } = options;const group = new THREE15.Object3D;group.name = name;const overlap = 0.02;@@ -11875,7 +11862,7 @@ function wallWithOpening(name, material, options) {createPart(`${name}${suffix}`, geo, material, { position: pos, parent: group });};if (!opening) {- panel("", -length2 / 2, length2 / 2, 0, height);+ panel("", -length / 2, length / 2, 0, height);} else {const ow = opening.width ?? (opening.kind === "window" ? 1 : 1.1);const oh = opening.height ?? (opening.kind === "window" ? 1 : 2.1);@@ -11884,8 +11871,8 @@ function wallWithOpening(name, material, options) {const right = off + ow / 2;const sill = opening.kind === "window" ? Math.max(opening.sill ?? 1, 0) : 0;const top = Math.min(sill + oh, height);- panel("_L", -length2 / 2, left, 0, height);- panel("_R", right, length2 / 2, 0, height);+ panel("_L", -length / 2, left, 0, height);+ panel("_R", right, length / 2, 0, height);panel("_Lintel", left - overlap, right + overlap, top, height);if (sill > 0)panel("_Sill", left - overlap, right + overlap, 0, sill);@@ -11907,8 +11894,8 @@ function room(name, material, options = {}) {const openings = options.openings ?? [{ wall: "front", kind: "door" }];const root = new THREE15.Object3D;root.name = name;- const openingFor = (wall2) => {- const found = openings.find((op) => op.wall === wall2);+ const openingFor = (wall) => {+ const found = openings.find((op) => op.wall === wall);if (!found)return;const { wall: _wall, ...rest } = found;@@ -11954,8 +11941,8 @@ function createRoofPlanes2(name, material, options) {}if ((options.ridgeAxis ?? "x") === "x") {const halfRun = options.width / 2 + (options.overhang ?? 0.3);- const angle2 = Math.atan2(options.height, halfRun);- result.slopes[1].rotation.set(-angle2, Math.PI, 0);+ const angle = Math.atan2(options.height, halfRun);+ result.slopes[1].rotation.set(-angle, Math.PI, 0);}return result;}@@ -11998,16 +11985,16 @@ function createStairs(name, material, options) {parent.add(root);return { root, steps: stepList };}-function requireColor(color2, fn) {- if (typeof color2 === "number" || typeof color2 === "string")+function requireColor(color, fn) {+ if (typeof color === "number" || typeof color === "string")return;- const got = color2 && typeof color2 === "object" ? `an object with keys [${Object.keys(color2).join(", ")}]` : String(color2);+ const got = color && typeof color === "object" ? `an object with keys [${Object.keys(color).join(", ")}]` : String(color);throw new Error(`${fn}(color, options?): color must be a hex number like 0x8c4a32 or a CSS string, got ${got}. ` + `Material settings go in the SECOND argument: ${fn}(0x8c4a32, { roughness: 0.5, metalness: 0.9 }).`);}-function gameMaterial(color2, options = {}) {- requireColor(color2, "gameMaterial");+function gameMaterial(color, options = {}) {+ requireColor(color, "gameMaterial");return new THREE15.MeshStandardMaterial({- color: color2,+ color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,emissive: options.emissive ?? 0,@@ -12015,18 +12002,18 @@ function gameMaterial(color2, options = {}) {flatShading: options.flatShading ?? true});}-function basicMaterial(color2, options = {}) {- requireColor(color2, "basicMaterial");+function basicMaterial(color, options = {}) {+ requireColor(color, "basicMaterial");return new THREE15.MeshBasicMaterial({- color: color2,+ color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1});}-function glassMaterial(color2, options = {}) {- requireColor(color2, "glassMaterial");+function glassMaterial(color, options = {}) {+ requireColor(color, "glassMaterial");return new THREE15.MeshStandardMaterial({- color: color2,+ color,transparent: true,opacity: options.opacity ?? 0.35,roughness: options.roughness ?? 0.1,@@ -12034,10 +12021,10 @@ function glassMaterial(color2, options = {}) {side: THREE15.DoubleSide});}-function lambertMaterial(color2, options = {}) {- requireColor(color2, "lambertMaterial");+function lambertMaterial(color, options = {}) {+ requireColor(color, "lambertMaterial");return new THREE15.MeshLambertMaterial({- color: color2,+ color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0});@@ -12204,12 +12191,12 @@ function validateAsset(root, category) {}return { valid: true, errors, warnings };}-function buildSandboxGlobals(usage2, options = {}) {+function buildSandboxGlobals(usage, options = {}) {const wrap = (name, fn) => {- if (!usage2)+ if (!usage)return fn;const wrapped = (...args) => {- usage2[name] = (usage2[name] ?? 0) + 1;+ usage[name] = (usage[name] ?? 0) + 1;return fn(...args);};return wrapped;@@ -12237,9 +12224,9 @@ function buildSandboxGlobals(usage2, options = {}) {try {key = `${name}::${JSON.stringify(args)}`;} catch {- const result2 = fn(...args);- stampKilnRange(name, result2);- return result2;+ const result = fn(...args);+ stampKilnRange(name, result);+ return result;}const hit = geoCache.get(key);if (hit)@@ -12548,24 +12535,7 @@ async function validateFinalGlbBytes(bytes, uri = "model.glb") {});return normalizeReport(raw);}-async function assertFinalGlbValid(bytes, uri = "model.glb") {- const report = await validateFinalGlbBytes(bytes, uri);- if (report.issues.numErrors > 0)- throw new GltfValidationError(report);- return report;-}-var GltfValidationError;-var init_gltf = __esm(() => {- GltfValidationError = class GltfValidationError extends Error {- report;- constructor(report) {- const first = report.issues.messages.find((issue) => issue.severity === 0);- super(`Final GLB failed Khronos validation with ${report.issues.numErrors} error(s)` + (first ? `: ${first.code} — ${first.message}` : "."));- this.name = "GltfValidationError";- this.report = report;- }- };-});+var init_gltf = () => {};// src/qa/registry.tsimport { createHash as createHash3 } from "node:crypto";@@ -13195,19 +13165,19 @@ function markerBounds(matrix) {}return bounds;}-function geometryPlaneNormal(geometry2, relativeMatrix) {- geometry2.computeBoundingBox();- const local = geometry2.boundingBox;+function geometryPlaneNormal(geometry, relativeMatrix) {+ geometry.computeBoundingBox();+ const local = geometry.boundingBox;if (!local)return;const size = local.getSize(new THREE17.Vector3);- const dimensions2 = [+ const dimensions = [["x", size.x],["y", size.y],["z", size.z]];- dimensions2.sort((a, b) => a[1] - b[1]);- const axis = dimensions2[0]?.[0];+ dimensions.sort((a, b) => a[1] - b[1]);+ const axis = dimensions[0]?.[0];if (!axis)return;const normal = new THREE17.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);@@ -13215,8 +13185,8 @@ function geometryPlaneNormal(geometry2, relativeMatrix) {normal.multiplyScalar(-1);return normal.normalize();}-function geometryEvidence(geometry2, relativeMatrix) {- const position = geometry2.getAttribute("position");+function geometryEvidence(geometry, relativeMatrix) {+ const position = geometry.getAttribute("position");const bounds = emptyBounds();const vertices = [];if (position?.itemSize !== 3)@@ -13228,7 +13198,7 @@ function geometryEvidence(geometry2, relativeMatrix) {expandBounds(bounds, point);}const triangles = [];- const indices = geometry2.getIndex();+ const indices = geometry.getIndex();const addTriangle = (a, b, c) => {const va = vertices[a];const vb = vertices[b];@@ -13245,7 +13215,7 @@ function geometryEvidence(geometry2, relativeMatrix) {addTriangle(index, index + 1, index + 2);}}- const planeNormal = geometryPlaneNormal(geometry2, relativeMatrix);+ const planeNormal = geometryPlaneNormal(geometry, relativeMatrix);return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };}function collectArchitectureEvidence(scene) {@@ -13262,7 +13232,7 @@ function collectArchitectureEvidence(scene) {directRoles.forEach((role) => {allRoles.add(role);});- const roles2 = [...new Set([...inheritedRoles, ...directRoles])];+ const roles = [...new Set([...inheritedRoles, ...directRoles])];const segment = `${node.name.trim() || node.type || "Object3D"}[${siblingIndex}]`;const nodePath = parentPath ? `${parentPath}/${segment}` : segment;const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);@@ -13280,13 +13250,13 @@ function collectArchitectureEvidence(scene) {nodePath,directRoles,directRelationships,- roles: roles2,+ roles,isMesh,...evidence});}node.children.forEach((child, index) => {- visit(child, nodePath, index, roles2);+ visit(child, nodePath, index, roles);});};visit(scene, "", 0, []);@@ -13356,8 +13326,8 @@ function highEdgeVertices(aggregateValue, rise) {const maximumY = aggregateValue.bounds.max.y;return aggregateValue.vertices.filter((point) => point.y >= maximumY - band);}-function ridgeCrossSectionDistance(positive3, negative, lateralAxis, rise) {- const a = highEdgeVertices(positive3, rise);+function ridgeCrossSectionDistance(positive, negative, lateralAxis, rise) {+ const a = highEdgeVertices(positive, rise);const b = highEdgeVertices(negative, rise);let distance = Infinity;for (const pointA of a) {@@ -13370,19 +13340,19 @@ function ridgeCrossSectionDistance(positive3, negative, lateralAxis, rise) {function roofFindings(context, architecture, evidence) {if (!requestedGable(architecture) && !taggedGable(evidence))return [];- const positive3 = aggregateRole(evidence, "roof.slope.positive");+ const positive = aggregateRole(evidence, "roof.slope.positive");const negative = aggregateRole(evidence, "roof.slope.negative");const tagged = taggedGable(evidence);const exactDisposition = tagged ? "block" : "warn";const findings = [];- if (!positive3 || !negative) {+ if (!positive || !negative) {findings.push(architectureFinding(context, {code: "ARCH_ROOF_AXIS",disposition: exactDisposition,- message: `A gable requires exactly two semantic slope roles; found ${positive3 ? 1 : 0} positive and ${negative ? 1 : 0} negative slope surfaces.`,+ message: `A gable requires exactly two semantic slope roles; found ${positive ? 1 : 0} positive and ${negative ? 1 : 0} negative slope surfaces.`,measurement: {name: "semanticSlopeRoleCount",- actual: Number(Boolean(positive3)) + Number(Boolean(negative)),+ actual: Number(Boolean(positive)) + Number(Boolean(negative)),expected: 2,threshold: 2},@@ -13402,11 +13372,11 @@ function roofFindings(context, architecture, evidence) {}));return findings;}- if (!positive3 || !negative)+ if (!positive || !negative)return findings;const ridgeAxis = architecture.roof.ridgeAxis;const lateralAxis = ridgeAxis === "x" ? "z" : "x";- const positiveNormal = averageNormal(positive3.normals);+ const positiveNormal = averageNormal(positive.normals);const negativeNormal = averageNormal(negative.normals);const lateralProduct = positiveNormal && negativeNormal ? positiveNormal[lateralAxis] * negativeNormal[lateralAxis] : null;if (lateralProduct === null || lateralProduct >= -0.0025) {@@ -13426,9 +13396,9 @@ function roofFindings(context, architecture, evidence) {const { spanX, spanZ } = architecture.footprint;const expectedRidgeSpan = (ridgeAxis === "x" ? spanX : spanZ) + architecture.roof.overhang * 2;const expectedLateralSpan = (lateralAxis === "x" ? spanX : spanZ) + architecture.roof.overhang * 2;- const ridgeCoverage = Math.min(extent(positive3.bounds, ridgeAxis) / expectedRidgeSpan, extent(negative.bounds, ridgeAxis) / expectedRidgeSpan);- const roofMinLateral = Math.min(positive3.bounds.min[lateralAxis], negative.bounds.min[lateralAxis]);- const roofMaxLateral = Math.max(positive3.bounds.max[lateralAxis], negative.bounds.max[lateralAxis]);+ const ridgeCoverage = Math.min(extent(positive.bounds, ridgeAxis) / expectedRidgeSpan, extent(negative.bounds, ridgeAxis) / expectedRidgeSpan);+ const roofMinLateral = Math.min(positive.bounds.min[lateralAxis], negative.bounds.min[lateralAxis]);+ const roofMaxLateral = Math.max(positive.bounds.max[lateralAxis], negative.bounds.max[lateralAxis]);const lateralCoverage = intervalCoverage(roofMinLateral, roofMaxLateral, -expectedLateralSpan / 2, expectedLateralSpan / 2);if (ridgeCoverage < 0.9 || lateralCoverage < 0.9) {const actual = Math.min(ridgeCoverage, lateralCoverage);@@ -13442,7 +13412,7 @@ function roofFindings(context, architecture, evidence) {expected: ">= 0.9",threshold: 0.9},- affected: { node: positive3.parts[0]?.nodeName ?? "roof.slope.positive" }+ affected: { node: positive.parts[0]?.nodeName ?? "roof.slope.positive" }}));}const panels = evidence.parts.filter((part) => part.isMesh && (part.directRoles.some((role) => role.startsWith("roof.panel.")) || hasRole(part, "roof.surface.panels") || hasRolePrefix(part, "roof.") && /panel|sheet|shingle|seam|corrugat/i.test(part.nodeName)));@@ -13467,7 +13437,7 @@ function roofFindings(context, architecture, evidence) {}}));}- const ridgeDistance = ridgeCrossSectionDistance(positive3, negative, lateralAxis, architecture.roof.rise);+ const ridgeDistance = ridgeCrossSectionDistance(positive, negative, lateralAxis, architecture.roof.rise);const ridgeTolerance = Math.max(0.04, expectedLateralSpan * 0.0125);if (!Number.isFinite(ridgeDistance) || ridgeDistance > ridgeTolerance) {findings.push(architectureFinding(context, {@@ -13503,7 +13473,7 @@ function endFindings(context, architecture, evidence) {const closedEnds = architecture.roof.closedEnds;if (!closedEnds)return [];- const positive3 = aggregateRole(evidence, "roof.gable.positive");+ const positive = aggregateRole(evidence, "roof.gable.positive");const negative = aggregateRole(evidence, "roof.gable.negative");const hasTaggedRoof = taggedGable(evidence);const disposition = hasTaggedRoof ? "block" : "warn";@@ -13514,7 +13484,7 @@ function endFindings(context, architecture, evidence) {const expectedArea = lateralSpan * architecture.roof.rise / 2;const findings = [];for (const [end, aggregateValue] of [- ["positive", positive3],+ ["positive", positive],["negative", negative]]) {if (!aggregateValue) {@@ -13581,7 +13551,7 @@ function endFindings(context, architecture, evidence) {}return findings;}-function pointInProjectedTriangle(x, z3, triangle) {+function pointInProjectedTriangle(x, z, triangle) {const ax = triangle.a.x;const az = triangle.a.z;const bx = triangle.b.x;@@ -13591,8 +13561,8 @@ function pointInProjectedTriangle(x, z3, triangle) {const denominator = (bz - cz) * (ax - cx) + (cx - bx) * (az - cz);if (Math.abs(denominator) <= EPSILON2)return { inside: false, weights: [0, 0, 0] };- const wa = ((bz - cz) * (x - cx) + (cx - bx) * (z3 - cz)) / denominator;- const wb = ((cz - az) * (x - cx) + (ax - cx) * (z3 - cz)) / denominator;+ const wa = ((bz - cz) * (x - cx) + (cx - bx) * (z - cz)) / denominator;+ const wb = ((cz - az) * (x - cx) + (ax - cx) * (z - cz)) / denominator;const wc = 1 - wa - wb;const tolerance = 0.00001;return {@@ -13600,10 +13570,10 @@ function pointInProjectedTriangle(x, z3, triangle) {weights: [wa, wb, wc]};}-function nearestRoofHeight(triangles, x, z3, targetY) {+function nearestRoofHeight(triangles, x, z, targetY) {const heights = [];for (const triangle of triangles) {- const projected = pointInProjectedTriangle(x, z3, triangle);+ const projected = pointInProjectedTriangle(x, z, triangle);if (!projected.inside)continue;const [wa, wb, wc] = projected.weights;@@ -13637,8 +13607,8 @@ function envelopeFindings(context, architecture, evidence) {for (const offset of offsets) {const ridge = offset * ridgeSpan;const x = ridgeAxis === "x" ? ridge : lateral;- const z3 = ridgeAxis === "x" ? lateral : ridge;- const roofY = nearestRoofHeight(roof.triangles, x, z3, wallTop);+ const z = ridgeAxis === "x" ? lateral : ridge;+ const roofY = nearestRoofHeight(roof.triangles, x, z, wallTop);if (roofY !== undefined)separations.push(roofY - wallTop);}@@ -13687,8 +13657,8 @@ function shrunkenPortalBounds(bounds, wall) {}return result;}-function portalRoleWall(roles2) {- for (const role of roles2) {+function portalRoleWall(roles) {+ for (const role of roles) {const match = /^opening\.(front|back|left|right)\.(?:door|portal|entry)(?:\.|$)/.exec(role);if (match)return match[1];@@ -13844,7 +13814,7 @@ function roofModeFindings(context, architecture, evidence) {if (mode === "auto")return [];const roofParts = evidence.parts.filter((part) => hasRolePrefix(part, "roof."));- const removableRelationships = roofParts.flatMap((part) => part.directRelationships.filter((relationship2) => relationship2.kind === "separable-from"));+ const removableRelationships = roofParts.flatMap((part) => part.directRelationships.filter((relationship) => relationship.kind === "separable-from"));const present = roofParts.length > 0;const valid = mode === "none" ? !present : mode === "fixed" ? present && removableRelationships.length === 0 : present && removableRelationships.length > 0;if (valid)@@ -14159,12 +14129,12 @@ function block(intent, code, message, options) {});}function targetName(trackName) {- const dot3 = trackName.lastIndexOf(".");- return dot3 > 0 ? trackName.slice(0, dot3) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(0, dot) : undefined;}function propertyName(trackName) {- const dot3 = trackName.lastIndexOf(".");- return dot3 > 0 ? trackName.slice(dot3 + 1) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(dot + 1) : undefined;}function blockerKey(finding) {return [@@ -14304,8 +14274,8 @@ function heldItemFindings(intent, nodes) {if (!held?.required)return [];const item = nodes.find((evidence) => {- const roles2 = readSemanticMetadataV1(evidence.node)?.roles ?? [];- return evidence.node.userData["kilnHeldItem"] === true || roles2.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");+ const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];+ return evidence.node.userData["kilnHeldItem"] === true || roles.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");});if (!item) {return [@@ -14325,8 +14295,8 @@ function heldItemFindings(intent, nodes) {break;cursor = cursor.parent;}- const roleMatches = (descriptor2) => {- const candidates = [descriptor2.role, ...descriptor2.aliases];+ const roleMatches = (descriptor) => {+ const candidates = [descriptor.role, ...descriptor.aliases];return candidates.some((role) => role === held.attachmentRole || role.split(/[._-]/).includes(held.attachmentRole));};if (attachment?.endEffector && roleMatches(attachment))@@ -14448,8 +14418,8 @@ function endpointDelta(track, size) {const lastOffset = track.values.length - size;const last = Array.from({ length: size }, (_, index) => Number(track.values[lastOffset + index]));if (track.name.endsWith(".quaternion") && size === 4) {- const dot3 = Math.abs(first.reduce((sum, value, index) => sum + value * last[index], 0));- return Math.abs(1 - Math.min(1, dot3));+ const dot = Math.abs(first.reduce((sum, value, index) => sum + value * last[index], 0));+ return Math.abs(1 - Math.min(1, dot));}return Math.max(...first.map((value, index) => Math.abs(value - last[index])));}@@ -14618,8 +14588,8 @@ function rootMotionFindings(intent, root, clips) {}function declaredHeldItem(nodes) {return nodes.find((evidence) => {- const roles2 = readSemanticMetadataV1(evidence.node)?.roles ?? [];- return evidence.node.userData["kilnHeldItem"] === true || roles2.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");+ const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];+ return evidence.node.userData["kilnHeldItem"] === true || roles.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");});}function characterJointScale(root) {@@ -14658,15 +14628,15 @@ function heldItemMotionFindings(intent, root, clips) {let maximumDrift = 0;let maximumFraction = 0;for (const fraction of CHARACTER_SAMPLE_FRACTIONS) {- const clone2 = root.clone(true);+ const clone = root.clone(true);for (const track of clip.tracks)- applyTrackAt(clone2, track, fraction * clip.duration);- clone2.updateMatrixWorld(true);- const cloneItem = clone2.getObjectByName(item.node.name);- const cloneAttachment = collectCharacterJointNodes(clone2).find((joint) => joint.descriptor.role === attachment.role)?.node;+ applyTrackAt(clone, track, fraction * clip.duration);+ clone.updateMatrixWorld(true);+ const cloneItem = clone.getObjectByName(item.node.name);+ const cloneAttachment = collectCharacterJointNodes(clone).find((joint) => joint.descriptor.role === attachment.role)?.node;if (!cloneItem || !cloneAttachment)continue;- const inverse = clone2.matrixWorld.clone().invert();+ const inverse = clone.matrixWorld.clone().invert();const itemPoint = cloneItem.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);const gripPoint = cloneAttachment.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);const distance = itemPoint.distanceTo(gripPoint);@@ -14778,8 +14748,8 @@ function characterScale(points) {const size = bounds.getSize(new THREE19.Vector3);return Math.max(size.x, size.y, size.z, 1);}-function pairKey(descriptor2) {- return descriptor2.role.split(/[._-]/).filter((token) => token !== "left" && token !== "right").join(".");+function pairKey(descriptor) {+ return descriptor.role.split(/[._-]/).filter((token) => token !== "left" && token !== "right").join(".");}function bilateralSymmetryFindings(context, root) {const points = jointPoints(root);@@ -14826,9 +14796,9 @@ function restChainFindings(context, root) {const minimumSegment = Math.max(0.01, scale * REST_ORDER_RATIO);const chains = trusted.bodyPlan === "biped" ? BIPED_CHAINS : QUADRUPED_CHAINS;const findings = [];- for (const roles2 of chains) {- const chain = roles2.map((role) => byRole.get(role)).filter((value) => !!value);- if (chain.length !== roles2.length)+ for (const roles of chains) {+ const chain = roles.map((role) => byRole.get(role)).filter((value) => !!value);+ if (chain.length !== roles.length)continue;for (let index = 1;index < chain.length; index++) {const parent = chain[index - 1];@@ -14838,7 +14808,7 @@ function restChainFindings(context, root) {continue;findings.push(advisory(context, {code: "CHAR_REST_CHAIN_ORDER",- message: `Rest chain ${roles2.join(" -> ")} is vertically inverted or collapsed at ` + `${parent.evidence.descriptor.role} -> ${child.evidence.descriptor.role}.`,+ message: `Rest chain ${roles.join(" -> ")} is vertically inverted or collapsed at ` + `${parent.evidence.descriptor.role} -> ${child.evidence.descriptor.role}.`,affected: { node: child.evidence.node.name, nodePath: child.evidence.nodePath },measurement: {name: "parentToChildVerticalDrop",@@ -14859,7 +14829,7 @@ function restChainFindings(context, root) {continue;findings.push(advisory(context, {code: "CHAR_REST_SEGMENT_LENGTH",- message: `Rest chain ${roles2.join(" -> ")} has collapsed or grossly unmatched segment lengths.`,+ message: `Rest chain ${roles.join(" -> ")} has collapsed or grossly unmatched segment lengths.`,affected: { node: chain[1].evidence.node.name, nodePath: chain[1].evidence.nodePath },measurement: {name: "chainSegmentLengthRatio",@@ -14879,17 +14849,17 @@ function forwardMarkerFindings(context, root) {return markers.flatMap((marker) => {const quaternion = marker.node.getWorldQuaternion(new THREE19.Quaternion);const actual = new THREE19.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();- const angle2 = THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(actual.dot(expected), -1, 1)));- if (angle2 <= FORWARD_ANGLE_DEGREES)+ const angle = THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(actual.dot(expected), -1, 1)));+ if (angle <= FORWARD_ANGLE_DEGREES)return [];return [advisory(context, {code: "CHAR_FORWARD_MARKER",- message: `Declared forward marker ${marker.descriptor.role} differs from canonical +X by ` + `${angle2.toFixed(3)} degrees.`,+ message: `Declared forward marker ${marker.descriptor.role} differs from canonical +X by ` + `${angle.toFixed(3)} degrees.`,affected: { node: marker.node.name, nodePath: marker.nodePath },measurement: {name: "forwardMarkerAngle",- actual: angle2,+ actual: angle,expected: 0,threshold: FORWARD_ANGLE_DEGREES,unit: "degrees"@@ -14900,12 +14870,12 @@ function forwardMarkerFindings(context, root) {});}function trackTarget(trackName) {- const dot3 = trackName.lastIndexOf(".");- return dot3 > 0 ? trackName.slice(0, dot3) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(0, dot) : undefined;}function trackProperty(trackName) {- const dot3 = trackName.lastIndexOf(".");- return dot3 > 0 ? trackName.slice(dot3 + 1) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(dot + 1) : undefined;}function applyTrack(root, track, time) {const target = trackTarget(track.name);@@ -14924,13 +14894,13 @@ function applyTrack(root, track, time) {function sampleClip(root, clip) {const inverse = rootInverse(root);return SAMPLE_FRACTIONS.map((fraction) => {- const clone2 = root.clone(true);+ const clone = root.clone(true);for (const track of clip.tracks)- applyTrack(clone2, track, fraction * clip.duration);- clone2.updateMatrixWorld(true);+ applyTrack(clone, track, fraction * clip.duration);+ clone.updateMatrixWorld(true);return {fraction,- byRole: new Map(collectCharacterJointNodes(clone2).map((evidence) => [+ byRole: new Map(collectCharacterJointNodes(clone).map((evidence) => [evidence.descriptor.role,{point: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse),@@ -14957,8 +14927,8 @@ function lateralEnergyFindings(context, root, clips) {const findings = [];for (const clip of clips) {const samples = sampleClip(root, clip);- const roles2 = [...samples[0].byRole.keys()].filter(limbRole).sort();- for (const role of roles2) {+ const roles = [...samples[0].byRole.keys()].filter(limbRole).sort();+ for (const role of roles) {let sagittal = 0;let lateral = 0;let maximumLateral = 0;@@ -15044,13 +15014,13 @@ function phaseOppositionFindings(context, root, clips) {}return findings;}-function signedBendDegrees(descriptor2, quaternion) {- const rest = new THREE19.Quaternion(...descriptor2.rest.rotation);+function signedBendDegrees(descriptor, quaternion) {+ const rest = new THREE19.Quaternion(...descriptor.rest.rotation);const delta = rest.invert().multiply(quaternion).normalize();const axis = new THREE19.Vector3(delta.x, delta.y, delta.z);- const signedMagnitude = axis.dot(new THREE19.Vector3(...descriptor2.localBendAxis));- const angle2 = 2 * Math.atan2(signedMagnitude, delta.w);- return THREE19.MathUtils.radToDeg(THREE19.MathUtils.euclideanModulo(angle2 + Math.PI, Math.PI * 2) - Math.PI);+ const signedMagnitude = axis.dot(new THREE19.Vector3(...descriptor.localBendAxis));+ const angle = 2 * Math.atan2(signedMagnitude, delta.w);+ return THREE19.MathUtils.radToDeg(THREE19.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);}function bendDirectionFindings(context, root, clips) {const joints = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role));@@ -15064,9 +15034,9 @@ function bendDirectionFindings(context, root, clips) {let maximumFraction = 0;for (const fraction of SAMPLE_FRACTIONS) {const value = track.createInterpolant().evaluate(fraction * clip.duration);- const bend2 = signedBendDegrees(joint.descriptor, new THREE19.Quaternion().fromArray(value).normalize());- if (Math.abs(bend2) > Math.abs(maximum)) {- maximum = bend2;+ const bend = signedBendDegrees(joint.descriptor, new THREE19.Quaternion().fromArray(value).normalize());+ if (Math.abs(bend) > Math.abs(maximum)) {+ maximum = bend;maximumFraction = fraction;}}@@ -15223,16 +15193,16 @@ function probeLocalFrameFromQuaternion(id, origin, quaternion) {if (Math.abs(quaternionLength - 1) > 0.000001) {throw new TypeError("Probe frame quaternion must be normalized within 1e-6.");}- const [x, y, z3, w] = quaternion;+ const [x, y, z, w] = quaternion;const xx = x * x;const yy = y * y;- const zz = z3 * z3;+ const zz = z * z;const xy = x * y;- const xz = x * z3;- const yz = y * z3;+ const xz = x * z;+ const yz = y * z;const wx = w * x;const wy = w * y;- const wz = w * z3;+ const wz = w * z;return createProbeLocalFrame3({id,origin,@@ -15244,7 +15214,7 @@ function probeLocalFrameFromQuaternion(id, origin, quaternion) {function createOrientedProbeBox3(input) {if (!input.id.trim())throw new TypeError("Oriented probe box ID must be non-empty.");- if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent2) => extent2 <= 0)) {+ if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent) => extent <= 0)) {throw new TypeError("Oriented probe box half-extents must be finite and greater than zero.");}return {@@ -15468,8 +15438,8 @@ function bilateralSymmetryFindings2(context, root, wheels) {const centerDelta = Math.hypot(a.x - b.x, a.y - b.y, a.z + b.z);const radiusDelta = Math.abs((left.radius ?? 0) - (right.radius ?? 0));const widthDelta = Math.abs((left.width ?? 0) - (right.width ?? 0));- const scale2 = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(0.01, scale2 * SYMMETRY_RATIO);+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(0.01, scale * SYMMETRY_RATIO);const maximum = Math.max(centerDelta, radiusDelta, widthDelta);if (maximum <= threshold)continue;@@ -15524,8 +15494,8 @@ function objectBoundsInFrame2(object, frame) {const matrix = worldToFrame.clone().multiply(part.matrixWorld);for (const x of [box.min.x, box.max.x])for (const y of [box.min.y, box.max.y])- for (const z3 of [box.min.z, box.max.z]) {- bounds.expandByPoint(new THREE20.Vector3(x, y, z3).applyMatrix4(matrix));+ for (const z of [box.min.z, box.max.z]) {+ bounds.expandByPoint(new THREE20.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -15540,8 +15510,8 @@ function probeBox(id, root, bounds) {const size = bounds.getSize(new THREE20.Vector3);const position = new THREE20.Vector3;const quaternion = new THREE20.Quaternion;- const scale2 = new THREE20.Vector3;- root.matrixWorld.decompose(position, quaternion, scale2);+ const scale = new THREE20.Vector3;+ root.matrixWorld.decompose(position, quaternion, scale);const xAxis = new THREE20.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();const yAxis = new THREE20.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();const zAxis = new THREE20.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();@@ -15555,9 +15525,9 @@ function probeBox(id, root, bounds) {zAxis: tuple2(zAxis)}),halfExtents: [- size.x * Math.abs(scale2.x) / 2,- size.y * Math.abs(scale2.y) / 2,- size.z * Math.abs(scale2.z) / 2+ size.x * Math.abs(scale.x) / 2,+ size.y * Math.abs(scale.y) / 2,+ size.z * Math.abs(scale.z) / 2]});}@@ -15663,7 +15633,7 @@ function weldedBoundaryEdges(root, loop) {if (!positions)return;const matrix = inverse.clone().multiply(node.matrixWorld);- const keys = Array.from({ length: positions.count }, (_, index2) => vertexKey(new THREE20.Vector3().fromBufferAttribute(positions, index2).applyMatrix4(matrix)));+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE20.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));const index = node.geometry.getIndex();const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);for (let offset = 0;offset + 2 < indices.length; offset += 3) {@@ -15687,11 +15657,11 @@ function trackProfileFindings(context, root, intent) {const loops = [];const roadWheels = [];root.traverse((node) => {- const roles2 = semanticRoles(node);- if (roles2.some((role) => role.startsWith("track.loop.")) || roles2.some((role) => role.startsWith("support.track."))) {+ const roles = semanticRoles(node);+ if (roles.some((role) => role.startsWith("track.loop.")) || roles.some((role) => role.startsWith("support.track."))) {loops.push(node);}- if (roles2.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {+ if (roles.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {roadWheels.push(node);}});@@ -15806,8 +15776,8 @@ function finding(context, value) {viewHints: value.viewHints ?? ["vehicle.underbody", "vehicle.wheel-section"]};}-function localPoint2(rootInverse2, value) {- return value.clone().applyMatrix4(rootInverse2);+function localPoint2(rootInverse, value) {+ return value.clone().applyMatrix4(rootInverse);}function rootAxis(root, axis) {root.updateWorldMatrix(true, false);@@ -15992,14 +15962,14 @@ function duplicateAssemblyFindings(context, root, wheels) {const right = wheels[b];const sameDeclaredCorner = left.side !== undefined && left.side === right.side && left.index !== undefined && left.index === right.index;const centerDelta = localPoint2(inverse, left.centerWorld).distanceTo(localPoint2(inverse, right.centerWorld));- const scale2 = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(CENTER_MINIMUM, scale2 * CENTER_RATIO);+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(CENTER_MINIMUM, scale * CENTER_RATIO);if (!sameDeclaredCorner && centerDelta > threshold)continue;- const semantic3 = left.source === "semantic" && right.source === "semantic";+ const semantic = left.source === "semantic" && right.source === "semantic";findings.push(finding(context, {code: "VEH_DUPLICATE_ASSEMBLY",- disposition: semantic3 ? "block" : "warn",+ disposition: semantic ? "block" : "warn",message: `Wheel assemblies ${left.id} and ${right.id} resolve to the same ` + `${sameDeclaredCorner ? `${left.side}-${left.index} corner` : "scale-relative center"}.`,affected: { node: right.root.name },measurement: {@@ -16048,7 +16018,7 @@ function contactFindings2(context, root, intent, wheels) {}return findings;}-function renderableMinYInRoot(rootInverse2, node) {+function renderableMinYInRoot(rootInverse, node) {let minimum = Infinity;node.traverse((part) => {if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))@@ -16057,11 +16027,11 @@ function renderableMinYInRoot(rootInverse2, node) {const bounds = part.geometry.boundingBox;if (!bounds)return;- const matrix = rootInverse2.clone().multiply(part.matrixWorld);+ const matrix = rootInverse.clone().multiply(part.matrixWorld);for (const x of [bounds.min.x, bounds.max.x]) {for (const y of [bounds.min.y, bounds.max.y]) {- for (const z3 of [bounds.min.z, bounds.max.z]) {- minimum = Math.min(minimum, new THREE21.Vector3(x, y, z3).applyMatrix4(matrix).y);+ for (const z of [bounds.min.z, bounds.max.z]) {+ minimum = Math.min(minimum, new THREE21.Vector3(x, y, z).applyMatrix4(matrix).y);}}}@@ -16076,16 +16046,16 @@ function supportContactFindings(context, root, intent) {const explicitContacts = [];const supports = [];root.traverse((node) => {- const roles2 = readSemanticMetadataV1(node)?.roles ?? [];- const isWheelContact = roles2.some((role) => role.startsWith("wheel.contact."));- if (!isWheelContact && roles2.some((role) => role.startsWith("contact."))) {+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ const isWheelContact = roles.some((role) => role.startsWith("wheel.contact."));+ if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {explicitContacts.push({node,contactY: localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(node.matrixWorld)).y,source: "contact"});}- if (roles2.some((role) => role.startsWith("support."))) {+ if (roles.some((role) => role.startsWith("support."))) {const contactY = renderableMinYInRoot(inverse, node);if (contactY !== undefined)supports.push({ node, contactY, source: "support" });@@ -16213,7 +16183,7 @@ function propulsionFindings(context, root, intent) {});const findings = [];root.updateWorldMatrix(true, false);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();for (const kind of expectedKinds) {const candidates = components.filter((part) => part.kind === kind);if (candidates.length === 0) {@@ -16230,7 +16200,7 @@ function propulsionFindings(context, root, intent) {const box = new THREE21.Box3().setFromObject(component.node);const center = box.isEmpty() ? undefined : box.getCenter(new THREE21.Vector3);const pivotCenter = pivot ? new THREE21.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;- const delta = center && pivotCenter ? localPoint2(rootInverse2, center).distanceTo(localPoint2(rootInverse2, pivotCenter)) : Infinity;+ const delta = center && pivotCenter ? localPoint2(rootInverse, center).distanceTo(localPoint2(rootInverse, pivotCenter)) : Infinity;const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);const canonicalAxis = kind === "rotor" ? new THREE21.Vector3(0, 1, 0) : new THREE21.Vector3(1, 0, 0);@@ -16301,7 +16271,7 @@ var init_vehicle2 = __esm(() => {owner: KILN_ENGINE_QA_OWNER,promotion: conformancePromotionAuthorization("vehicle-qa-v1", "src/qa/vehicle.test.ts", "4bffa0dff0ed33be2ce7003ee36ac33efc5b4900e57d390898e43551912e626b"),defaultMode: "enforce",- evaluate: (context) => evaluateVehicleQa(context).filter((finding2) => finding2.disposition === "block")+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition === "block")};VEHICLE_ADVISORY_QA_RULE = {id: "VEHICLE_ADVISORY_PROFILE",@@ -16310,7 +16280,7 @@ var init_vehicle2 = __esm(() => {ruleClass: "heuristic",owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",- evaluate: (context) => evaluateVehicleQa(context).filter((finding2) => finding2.disposition !== "block")+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition !== "block")};VEHICLE_QA_RULES = [VEHICLE_QA_RULE,@@ -16335,22 +16305,22 @@ function pathOf(node, root) {}return names.reverse().join("/");}-function localPoint3(rootInverse2, node) {- return node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse2);+function localPoint3(rootInverse, node) {+ return node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse);}-function meshLocalBox(mesh, rootInverse2) {+function meshLocalBox(mesh, rootInverse) {if (!(mesh.geometry instanceof THREE22.BufferGeometry))return;mesh.geometry.computeBoundingBox();const source = mesh.geometry.boundingBox;if (!source || source.isEmpty())return;- const transform = rootInverse2.clone().multiply(mesh.matrixWorld);+ const transform = rootInverse.clone().multiply(mesh.matrixWorld);const result = new THREE22.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {- for (const z3 of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE22.Vector3(x, y, z3).applyMatrix4(transform));+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE22.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -16366,8 +16336,8 @@ function collectRenderableBounds(root) {const box = meshLocalBox(node, inverse);if (!box)return;- const roles2 = rolesOf(node);- values.push({ node, box, roles: roles2, source: roles2.length > 0 ? "semantic" : "fallback" });+ const roles = rolesOf(node);+ values.push({ node, box, roles, source: roles.length > 0 ? "semantic" : "fallback" });});return values;}@@ -16388,15 +16358,15 @@ function evaluateVegetationContactQa(context) {const semanticSupports = [];root.traverse((node) => {const metadata = readSemanticMetadataV1(node);- const roles2 = metadata?.roles ?? [];- if (roles2.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {+ const roles = metadata?.roles ?? [];+ if (roles.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {const frame = metadata?.frames.find((value) => value.id === "ground-contact" || value.id === "vegetation-ground-contact");contacts.push({node,...frame ? { frameTranslation: frame.translation } : {}});}- if (roles2.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {+ if (roles.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {semanticSupports.push(node);}});@@ -16497,8 +16467,8 @@ function evaluateVegetationScopeQa(context) {const materialEvidence = materialNames(value.node).some((name) => CLUTTER_NAME.test(name));const footprintRatio = size.x * size.z / Math.max(0.000000001, overallSize.x * overallSize.z);const flatEvidence = footprintRatio >= 0.35 && size.y <= Math.max(0.08, overallSize.y * 0.08) && center.y <= VEGETATION_CONTACT_TOLERANCE_METERS + size.y;- const evidence2 = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);- if (evidence2.length < 2)+ const evidence = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);+ if (evidence.length < 2)continue;findings.push(finding2(context, {code: "VEG_SCOPE_EXTRA",@@ -16531,7 +16501,7 @@ function unionVolume(boxes) {const size = union.getSize(new THREE22.Vector3);return size.x * size.y * size.z;}-function projectedOccupancy(boxes, axes2) {+function projectedOccupancy(boxes, axes) {if (boxes.length === 0)return 0;const minimum = [Infinity, Infinity];@@ -16540,8 +16510,8 @@ function projectedOccupancy(boxes, axes2) {const min = [box.min.x, box.min.y, box.min.z];const max = [box.max.x, box.max.y, box.max.z];for (const dimension of [0, 1]) {- minimum[dimension] = Math.min(minimum[dimension], min[axes2[dimension]]);- maximum[dimension] = Math.max(maximum[dimension], max[axes2[dimension]]);+ minimum[dimension] = Math.min(minimum[dimension], min[axes[dimension]]);+ maximum[dimension] = Math.max(maximum[dimension], max[axes[dimension]]);}}const spans = [maximum[0] - minimum[0], maximum[1] - minimum[1]];@@ -16551,10 +16521,10 @@ function projectedOccupancy(boxes, axes2) {for (const box of boxes) {const min = [box.min.x, box.min.y, box.min.z];const max = [box.max.x, box.max.y, box.max.z];- const x0 = Math.max(0, Math.floor((min[axes2[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes2[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const y0 = Math.max(0, Math.floor((min[axes2[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));- const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes2[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ const x0 = Math.max(0, Math.floor((min[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const y0 = Math.max(0, Math.floor((min[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));for (let y = y0;y <= y1; y++) {for (let x = x0;x <= x1; x++)occupied[y * RASTER_SIZE + x] = 1;@@ -16569,9 +16539,9 @@ function matchesAny(value, patterns) {function measurementSource(values) {if (values.length === 0)return "none";- const semantic3 = values.some((value) => value.source === "semantic");+ const semantic = values.some((value) => value.source === "semantic");const fallback = values.some((value) => value.source === "fallback");- return semantic3 && fallback ? "mixed" : semantic3 ? "semantic" : "fallback";+ return semantic && fallback ? "mixed" : semantic ? "semantic" : "fallback";}function roleOrNameSource(value, patterns) {if (value.roles.some((role) => patterns.some((pattern) => pattern.test(role))))@@ -16595,7 +16565,7 @@ function growthCandidates(root) {function boxDistanceToPoint(box, point) {return box.distanceToPoint(point);}-function endpointRadius(position, axis, axisValue, tolerance, scale2) {+function endpointRadius(position, axis, axisValue, tolerance, scale) {const radialAxes = [0, 1, 2].filter((value) => value !== axis);const points = [];const point = new THREE22.Vector3;@@ -16613,8 +16583,8 @@ function endpointRadius(position, axis, axisValue, tolerance, scale2) {}let radius = 0;for (const value of points) {- const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale2.getComponent(radialAxes[0]));- const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale2.getComponent(radialAxes[1]));+ const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale.getComponent(radialAxes[0]));+ const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale.getComponent(radialAxes[1]));radius = Math.max(radius, Math.hypot(a, b));}return { center, radius };@@ -16622,12 +16592,12 @@ function endpointRadius(position, axis, axisValue, tolerance, scale2) {function growthNodeMeasurement(root, candidate, allCandidates, band) {if (!(candidate.node instanceof THREE22.Mesh))return;- const geometry2 = candidate.node.geometry;- const position = geometry2.getAttribute("position");+ const geometry = candidate.node.geometry;+ const position = geometry.getAttribute("position");if (!position || position.count < 2)return;- geometry2.computeBoundingBox();- const geometryBox = geometry2.boundingBox;+ geometry.computeBoundingBox();+ const geometryBox = geometry.boundingBox;if (!geometryBox || geometryBox.isEmpty())return;root.updateWorldMatrix(true, true);@@ -16663,10 +16633,10 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {}const baseRadius = firstIsBase ? first.radius : second.radius;const tipRadius = firstIsBase ? second.radius : first.radius;- const length3 = firstPoint.distanceTo(secondPoint);+ const length = firstPoint.distanceTo(secondPoint);const averageRadius = (baseRadius + tipRadius) / 2;const taperRatio = baseRadius > 0.000000001 ? tipRadius / baseRadius : null;- const lengthRadiusRatio = averageRadius > 0.000000001 ? length3 / averageRadius : null;+ const lengthRadiusRatio = averageRadius > 0.000000001 ? length / averageRadius : null;const selected = band[candidate.kind];const taperOutlier = taperRatio !== null && (taperRatio < selected.taper[0] || taperRatio > selected.taper[1]);const lengthRadiusOutlier = lengthRadiusRatio !== null && (lengthRadiusRatio < selected.lengthRadius[0] || lengthRadiusRatio > selected.lengthRadius[1]);@@ -16675,7 +16645,7 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {nodePath: pathOf(candidate.node, root),kind: candidate.kind,source: candidate.growthSource,- lengthMeters: stable3(length3),+ lengthMeters: stable3(length),baseRadiusMeters: stable3(baseRadius),tipRadiusMeters: stable3(tipRadius),taperRatio: taperRatio === null ? null : stable3(taperRatio),@@ -16795,12 +16765,12 @@ function evaluateVegetationFoliageAttachmentQa(context) {}function relativeTransformSignature(root, node) {const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);- const scale2 = new THREE22.Vector3;+ const scale = new THREE22.Vector3;const quaternion = new THREE22.Quaternion;- matrix.decompose(new THREE22.Vector3, quaternion, scale2);+ matrix.decompose(new THREE22.Vector3, quaternion, scale);if (quaternion.w < 0)quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);- const values = [...scale2.toArray(), ...quaternion.toArray()].map((value) => stable3(value));+ const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable3(value));return values.join(",");}function measureVegetationRepetition(intent, root) {@@ -16978,8 +16948,8 @@ function materialValue(material) {if (!(material instanceof THREE22.MeshStandardMaterial) && !(material instanceof THREE22.MeshBasicMaterial)) {return;}- const color2 = material.color;- return 0.2126 * color2.r + 0.7152 * color2.g + 0.0722 * color2.b;+ const color = material.color;+ return 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;}function measureVegetationFoliageMaterials(intent, root) {const values = [];@@ -17174,8 +17144,8 @@ function transformedBox(source, transform) {const result = new THREE23.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {- for (const z3 of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE23.Vector3(x, y, z3).applyMatrix4(transform));+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE23.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -17183,23 +17153,23 @@ function transformedBox(source, transform) {}function collectParts(root) {root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverse((node) => {- const roles2 = rolesOf2(node);+ const roles = rolesOf2(node);const renderable = node instanceof THREE23.Mesh;let box;if (renderable && node.geometry instanceof THREE23.BufferGeometry) {node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {- box = transformedBox(node.geometry.boundingBox, rootInverse2.clone().multiply(node.matrixWorld));+ box = transformedBox(node.geometry.boundingBox, rootInverse.clone().multiply(node.matrixWorld));}- } else if (roles2.length > 0) {- box = transformedBox(new THREE23.Box3(new THREE23.Vector3(-0.5, -0.5, -0.5), new THREE23.Vector3(0.5, 0.5, 0.5)), rootInverse2.clone().multiply(node.matrixWorld));+ } else if (roles.length > 0) {+ box = transformedBox(new THREE23.Box3(new THREE23.Vector3(-0.5, -0.5, -0.5), new THREE23.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));}if (box?.isEmpty())box = undefined;- result.push({ node, roles: roles2, ...box ? { box } : {}, renderable });+ result.push({ node, roles, ...box ? { box } : {}, renderable });});return result;}@@ -17269,9 +17239,9 @@ function allowedClearanceContactRoles(assembly) {const result = new Set;for (const part of [assembly.pivot, assembly.clearance]) {const metadata = part ? readSemanticMetadataV1(part.node) : undefined;- for (const relationship2 of metadata?.relationships ?? []) {- if (relationship2.targetType === "role" && /^(?:mountedTo|allowsContact|allowsClearanceContact)$/.test(relationship2.kind) && /^prop\.articulation\.support\.[^.]+$/.test(relationship2.target)) {- result.add(relationship2.target);+ for (const relationship of metadata?.relationships ?? []) {+ if (relationship.targetType === "role" && /^(?:mountedTo|allowsContact|allowsClearanceContact)$/.test(relationship.kind) && /^prop\.articulation\.support\.[^.]+$/.test(relationship.target)) {+ result.add(relationship.target);}}}@@ -17870,35 +17840,35 @@ function isEvidence(value) {const candidate = value;return candidate.schemaVersion === 1 && typeof candidate.silhouetteIoU === "number" && typeof candidate.colorAgreement === "number" && typeof candidate.reference === "object" && typeof candidate.rendered === "object";}-function referenceComparisonFindings(evidence2, profile) {- if (evidence2.reference.coverage <= 0 || evidence2.rendered.coverage <= 0)+function referenceComparisonFindings(evidence, profile) {+ if (evidence.reference.coverage <= 0 || evidence.rendered.coverage <= 0)return [];const findings = [];- if (evidence2.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {+ if (evidence.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {findings.push({code: "REF_SILHOUETTE_AGREEMENT",disposition: "observe",dimension: "promptAlignment",profile,- message: `The asset's outline agrees with the reference image on ${(evidence2.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,+ message: `The asset's outline agrees with the reference image on ${(evidence.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,measurement: {name: "silhouetteIoU",- actual: evidence2.silhouetteIoU,+ actual: evidence.silhouetteIoU,threshold: SILHOUETTE_IOU_OBSERVE},repairText: "Compare the reference against the rendered views and adjust the overall proportions — the outline is the part that disagrees, not the detail."});}- if (evidence2.colorAgreement < COLOR_AGREEMENT_OBSERVE) {+ if (evidence.colorAgreement < COLOR_AGREEMENT_OBSERVE) {findings.push({code: "REF_COLOR_AGREEMENT",disposition: "observe",dimension: "promptAlignment",profile,- message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence2.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,+ message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,measurement: {name: "colorAgreement",- actual: evidence2.colorAgreement,+ actual: evidence.colorAgreement,threshold: COLOR_AGREEMENT_OBSERVE},repairText: "Set the base colours from the reference image rather than from the prompt wording, then re-render."@@ -17917,19 +17887,19 @@ var init_reference_comparison = __esm(() => {owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",evaluate(context) {- const evidence2 = context.derivedEvidence?.["referenceComparison"];- if (!isEvidence(evidence2))+ const evidence = context.derivedEvidence?.["referenceComparison"];+ if (!isEvidence(evidence))return [];- return referenceComparisonFindings(evidence2, "reference.comparison");+ return referenceComparisonFindings(evidence, "reference.comparison");}});});// src/qa/self-intersection.tsimport * as THREE25 from "three";-function triangleCount(geometry2) {- const index = geometry2.getIndex();- const position = geometry2.getAttribute("position");+function triangleCount(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");if (!position)return 0;return Math.floor((index ? index.count : position.count) / 3);@@ -17960,8 +17930,8 @@ function collectParts3(root, skipped) {return parts;}function meshToArrays(mesh) {- const geometry2 = mesh.geometry;- const position = geometry2.getAttribute("position");+ const geometry = mesh.geometry;+ const position = geometry.getAttribute("position");if (!position)return null;const matrix = mesh.matrixWorld;@@ -17973,7 +17943,7 @@ function meshToArrays(mesh) {verts[i * 3 + 1] = v.y;verts[i * 3 + 2] = v.z;}- const index = geometry2.getIndex();+ const index = geometry.getIndex();let tris;if (index) {if (index.count % 3 !== 0)@@ -18020,7 +17990,7 @@ async function analyzePartPenetration(root) {const Module = await import("manifold-3d");const wasm = await Module.default();wasm.setup();- const { Manifold, Mesh: Mesh9 } = wasm;+ const { Manifold, Mesh } = wasm;const cache = new Map;const build = (part) => {if (cache.has(part.mesh))@@ -18029,7 +17999,7 @@ async function analyzePartPenetration(root) {try {const arrays = meshToArrays(part.mesh);if (arrays) {- const mesh = new Mesh9({ numProp: 3, ...arrays });+ const mesh = new Mesh({ numProp: 3, ...arrays });mesh.merge();solid = new Manifold(mesh);} else {@@ -18082,8 +18052,8 @@ async function analyzePartPenetration(root) {return base;}function readEvidence(context) {- const evidence2 = context.derivedEvidence?.["partPenetration"];- return evidence2?.schemaVersion === 1 ? evidence2 : undefined;+ const evidence = context.derivedEvidence?.["partPenetration"];+ return evidence?.schemaVersion === 1 ? evidence : undefined;}var MAX_PART_TRIANGLES = 20000, MAX_NARROW_PHASE_PAIRS = 64, CONTACT_VOLUME_FRACTION = 0.001, round = (n) => Math.round(n * 1e9) / 1e9, SELF_INTERSECTION_QA_RULE;var init_self_intersection = __esm(() => {@@ -18096,10 +18066,10 @@ var init_self_intersection = __esm(() => {owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",evaluate(context) {- const evidence2 = readEvidence(context);- if (!evidence2)+ const evidence = readEvidence(context);+ if (!evidence)return [];- const findings = evidence2.penetrations.map((pair) => ({+ const findings = evidence.penetrations.map((pair) => ({code: "GEO_PART_SELF_INTERSECTION",disposition: "observe",dimension: "visualQuality",@@ -18113,13 +18083,13 @@ var init_self_intersection = __esm(() => {},repairText: "Move one part clear of the other, or subtract it with boolDiff so the overlap becomes a real cut instead of two solids in the same place."}));- if (evidence2.truncated) {+ if (evidence.truncated) {findings.push({code: "GEO_PART_SELF_INTERSECTION_TRUNCATED",disposition: "observe",dimension: "visualQuality",profile: "geometry.selfIntersection",- message: `Only ${evidence2.pairsTested} of ${evidence2.candidatePairs} overlapping part pairs were checked (analysis budget). Parts beyond that were not examined.`+ message: `Only ${evidence.pairsTested} of ${evidence.candidatePairs} overlapping part pairs were checked (analysis budget). Parts beyond that were not examined.`});}return findings;@@ -18150,8 +18120,8 @@ function transformedBox2(source, transform) {const result = new THREE26.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {- for (const z3 of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE26.Vector3(x, y, z3).applyMatrix4(transform));+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE26.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -18163,20 +18133,20 @@ function orientedBoxFromLocalBounds(root, node, source) {return;const position = new THREE26.Vector3;const rotation = new THREE26.Quaternion;- const scale2 = new THREE26.Vector3;- relative.decompose(position, rotation, scale2);- const recomposed = new THREE26.Matrix4().compose(position, rotation, scale2);+ const scale = new THREE26.Vector3;+ relative.decompose(position, rotation, scale);+ const recomposed = new THREE26.Matrix4().compose(position, rotation, scale);const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));if (residual > 0.00001)return;const center = source.getCenter(new THREE26.Vector3).applyMatrix4(relative);const sourceHalf = source.getSize(new THREE26.Vector3).multiplyScalar(0.5);const halfExtents = [- Math.abs(sourceHalf.x * scale2.x),- Math.abs(sourceHalf.y * scale2.y),- Math.abs(sourceHalf.z * scale2.z)+ Math.abs(sourceHalf.x * scale.x),+ Math.abs(sourceHalf.y * scale.y),+ Math.abs(sourceHalf.z * scale.z)];- if (halfExtents.some((extent2) => !Number.isFinite(extent2) || extent2 <= 0.000000001))+ if (halfExtents.some((extent) => !Number.isFinite(extent) || extent <= 0.000000001))return;rotation.normalize();return createOrientedProbeBox3({@@ -18187,10 +18157,10 @@ function orientedBoxFromLocalBounds(root, node, source) {}function collectParts4(root) {root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverse((node) => {- const roles2 = rolesOf3(node);+ const roles = rolesOf3(node);const renderable = node instanceof THREE26.Mesh;let box;let orientedBox;@@ -18200,18 +18170,18 @@ function collectParts4(root) {if (node.geometry.boundingBox) {source = node.geometry.boundingBox;}- } else if (roles2.length > 0) {+ } else if (roles.length > 0) {source = new THREE26.Box3(new THREE26.Vector3(-0.5, -0.5, -0.5), new THREE26.Vector3(0.5, 0.5, 0.5));}if (source) {- box = transformedBox2(source, rootInverse2.clone().multiply(node.matrixWorld));+ box = transformedBox2(source, rootInverse.clone().multiply(node.matrixWorld));orientedBox = orientedBoxFromLocalBounds(root, node, source);}if (box?.isEmpty())box = undefined;result.push({node,- roles: roles2,+ roles,...box ? { box } : {},...orientedBox ? { orientedBox } : {},renderable@@ -18228,8 +18198,8 @@ function resolveSocket(root, node, socket) {if (!frame)return;root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();- const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse2);+ const rootInverse = root.matrixWorld.clone().invert();+ const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);const rootInverseQuaternion = root.getWorldQuaternion(new THREE26.Quaternion).invert();const rotation = node.getWorldQuaternion(new THREE26.Quaternion).multiply(new THREE26.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();return {@@ -18249,9 +18219,9 @@ function resolveEnvironmentSockets(root) {for (const socket of metadata?.sockets ?? []) {if (!socket.type.startsWith("environment."))continue;- const resolved2 = resolveSocket(root, node, socket);- if (resolved2)- result.push(resolved2);+ const resolved = resolveSocket(root, node, socket);+ if (resolved)+ result.push(resolved);}});return result.sort((a, b) => `${a.type}:${a.id}`.localeCompare(`${b.type}:${b.id}`));@@ -18287,11 +18257,11 @@ function evaluateEnvironmentSocketQa(context) {}for (const axis of ["x", "z"]) {const negative = socketByType(sockets, `environment.tile.${axis}-negative`);- const positive3 = socketByType(sockets, `environment.tile.${axis}-positive`);- if (!negative || !positive3)+ const positive = socketByType(sockets, `environment.tile.${axis}-positive`);+ if (!negative || !positive)continue;- const cross3 = axis === "x" ? 2 : 0;- const crossDelta = Math.hypot(negative.translation[1] - positive3.translation[1], negative.translation[cross3] - positive3.translation[cross3]);+ const cross = axis === "x" ? 2 : 0;+ const crossDelta = Math.hypot(negative.translation[1] - positive.translation[1], negative.translation[cross] - positive.translation[cross]);if (crossDelta <= SOCKET_ALIGNMENT_TOLERANCE_METERS)continue;findings.push(finding4(context, {@@ -18299,7 +18269,7 @@ function evaluateEnvironmentSocketQa(context) {disposition: "block",dimension: "categoryReadiness",message: `Opposing ${axis.toUpperCase()} tile sockets differ by ${crossDelta.toFixed(6)} m in their paired height/cross-axis frame.`,- affected: { node: positive3.node, attribute: positive3.id },+ affected: { node: positive.node, attribute: positive.id },measurement: {name: "socketCrossAxisDelta",actual: stable5(crossDelta),@@ -18317,8 +18287,8 @@ function materialSignature(material) {const values = Array.isArray(material) ? material : [material];return values.map((value) => {const standard = value;- const color2 = standard.color?.getHexString?.() ?? "none";- return `${value.type}:${value.name}:${color2}`;+ const color = standard.color?.getHexString?.() ?? "none";+ return `${value.type}:${value.name}:${color}`;}).sort().join("|");}function boundarySamples(root, axis, side, bins = 12) {@@ -18360,15 +18330,15 @@ function boundarySamples(root, axis, side, bins = 12) {}function edgePairMeasurements(root, axis, sockets) {const negative = boundarySamples(root, axis, "negative");- const positive3 = boundarySamples(root, axis, "positive");+ const positive = boundarySamples(root, axis, "positive");const negativeByBin = new Map(negative.map((sample) => [sample.bin, sample]));- const pairs = positive3.flatMap((sample) => {+ const pairs = positive.flatMap((sample) => {const other = negativeByBin.get(sample.bin);return other ? [[other, sample]] : [];});const unionBins = new Set([...negative.map((sample) => sample.bin),- ...positive3.map((sample) => sample.bin)+ ...positive.map((sample) => sample.bin)]);const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE26.MathUtils.radToDeg(Math.acos(THREE26.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;@@ -18751,12 +18721,12 @@ function artifactEvidence(context) {function finding5(context, value, profile = "vfx.w7") {return { ...value, profile: context.intent.qaProfile || profile };}-function measureVfxRuntimeCostV1(evidence2) {+function measureVfxRuntimeCostV1(evidence) {let blendedScreenAreaRatio = 0;let transparentLayerCount = 0;let overdrawProxy = 0;let textureMemoryBytes = 0;- for (const material of evidence2.materials) {+ for (const material of evidence.materials) {textureMemoryBytes += material.textureMemoryBytes;if (material.alphaMode !== "blend")continue;@@ -18770,7 +18740,7 @@ function measureVfxRuntimeCostV1(evidence2) {transparentLayerCount,overdrawProxy: stable6(overdrawProxy),textureMemoryBytes,- shaderSidecarRequired: evidence2.sidecar !== undefined+ shaderSidecarRequired: evidence.sidecar !== undefined};}function exactVfxIntent(context) {@@ -18794,8 +18764,8 @@ function exactVfxIntent(context) {]};}- const evidence2 = artifactEvidence(context);- if (!evidence2) {+ const evidence = artifactEvidence(context);+ if (!evidence) {return {findings: [finding5(context, {@@ -18809,17 +18779,17 @@ function exactVfxIntent(context) {]};}- return { intent: validated.value, evidence: evidence2 };+ return { intent: validated.value, evidence };}function evaluateVfxExactQa(context) {if (context.intent.category !== "vfx")return [];- const resolved2 = exactVfxIntent(context);- if ("findings" in resolved2)- return resolved2.findings;- const { intent, evidence: evidence2 } = resolved2;+ const resolved = exactVfxIntent(context);+ if ("findings" in resolved)+ return resolved.findings;+ const { intent, evidence } = resolved;const findings = [];- const effectMaterials = evidence2.materials.filter((material) => material.effectSurface !== false);+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface !== false);if (effectMaterials.length === 0) {findings.push(finding5(context, {code: "VFX_EFFECT_SURFACE_MISSING",@@ -18890,7 +18860,7 @@ function evaluateVfxExactQa(context) {}const facingFields = ["mode", "normalAxis", "directionAxis"];for (const field of facingFields) {- if (intent.facing[field] === evidence2.facing[field])+ if (intent.facing[field] === evidence.facing[field])continue;if (intent.facing.source !== "explicit")continue;@@ -18901,14 +18871,14 @@ function evaluateVfxExactQa(context) {message: `Explicit VFX facing ${field} does not match the emitted runtime contract.`,measurement: {name: `facing.${field}`,- actual: evidence2.facing[field] ?? null,+ actual: evidence.facing[field] ?? null,expected: intent.facing[field] ?? null},repairText: `Stamp and implement the requested ${field}; preserve the canonical Kiln frame.`}));}const requestedAnimation = intent.animation;- const actualAnimation = evidence2.animation;+ const actualAnimation = evidence.animation;for (const field of ["playback", "endpointBehavior", "driver"]) {if (requestedAnimation[field] === actualAnimation[field])continue;@@ -18951,7 +18921,7 @@ function evaluateVfxExactQa(context) {repairText: "Make the final loop sample equal the initial sample for every driven channel."}));}- if (requestedAnimation.driver === "clip" && !evidence2.clips.some((clip) => clip.name === requestedAnimation.clipName && Math.abs(clip.durationSeconds - requestedAnimation.durationSeconds) <= 0.000001)) {+ if (requestedAnimation.driver === "clip" && !evidence.clips.some((clip) => clip.name === requestedAnimation.clipName && Math.abs(clip.durationSeconds - requestedAnimation.durationSeconds) <= 0.000001)) {findings.push(finding5(context, {code: "VFX_REQUIRED_CLIP_MISSING",disposition: "block",@@ -18961,7 +18931,7 @@ function evaluateVfxExactQa(context) {repairText: `Emit clip ${requestedAnimation.clipName ?? "<declared clip>"} with the requested duration.`}));}- if (requestedAnimation.driver === "timeUniform" && !evidence2.uniforms.includes(requestedAnimation.timeUniformName ?? "")) {+ if (requestedAnimation.driver === "timeUniform" && !evidence.uniforms.includes(requestedAnimation.timeUniformName ?? "")) {findings.push(finding5(context, {code: "VFX_REQUIRED_TIME_UNIFORM_MISSING",disposition: "block",@@ -18969,13 +18939,13 @@ function evaluateVfxExactQa(context) {message: "The declared runtime time uniform is absent from the sidecar evidence.",measurement: {name: "timeUniformName",- actual: evidence2.uniforms.join(","),+ actual: evidence.uniforms.join(","),expected: requestedAnimation.timeUniformName ?? null},repairText: `Expose ${requestedAnimation.timeUniformName ?? "the declared uniform"} in the runtime sidecar.`}));}- if (intent.portability === "portable" && evidence2.sidecar !== undefined) {+ if (intent.portability === "portable" && evidence.sidecar !== undefined) {findings.push(finding5(context, {code: "VFX_UNDECLARED_SIDECAR",disposition: "block",@@ -18984,7 +18954,7 @@ function evaluateVfxExactQa(context) {repairText: "Bake the portable appearance into standard glTF materials or update trusted intent before spend."}));}- if (intent.portability === "sidecar" && (evidence2.sidecar?.id !== intent.sidecar?.id || evidence2.sidecar?.version !== intent.sidecar?.version)) {+ if (intent.portability === "sidecar" && (evidence.sidecar?.id !== intent.sidecar?.id || evidence.sidecar?.version !== intent.sidecar?.version)) {findings.push(finding5(context, {code: "VFX_SIDECAR_IDENTITY_MISMATCH",disposition: "block",@@ -18992,7 +18962,7 @@ function evaluateVfxExactQa(context) {message: "Runtime VFX sidecar identity/version does not match trusted intent.",measurement: {name: "sidecarIdentity",- actual: evidence2.sidecar ? `${evidence2.sidecar.id}@${evidence2.sidecar.version}` : null,+ actual: evidence.sidecar ? `${evidence.sidecar.id}@${evidence.sidecar.version}` : null,expected: intent.sidecar ? `${intent.sidecar.id}@${intent.sidecar.version}` : null},repairText: "Attach the exact declared sidecar identity and keep the GLB fallback honest."@@ -19005,12 +18975,12 @@ function evaluateVfxAdvisoryQa(context) {return [];const intent = context.intent.vfx;const validated = validateVfxIntentV1(intent);- const evidence2 = artifactEvidence(context);- if (!validated.valid || !validated.value || !evidence2)+ const evidence = artifactEvidence(context);+ if (!validated.valid || !validated.value || !evidence)return [];const findings = [];if (validated.value.facing.source === "inferred") {- const mismatch = ["mode", "normalAxis", "directionAxis"].some((field) => validated.value?.facing[field] !== evidence2.facing[field]);+ const mismatch = ["mode", "normalAxis", "directionAxis"].some((field) => validated.value?.facing[field] !== evidence.facing[field]);if (mismatch) {findings.push(finding5(context, {code: "VFX_FACING_INFERRED_DRIFT",@@ -19021,7 +18991,7 @@ function evaluateVfxAdvisoryQa(context) {}));}}- const cost = measureVfxRuntimeCostV1(evidence2);+ const cost = measureVfxRuntimeCostV1(evidence);findings.push(finding5(context, {code: "VFX_RUNTIME_COST_REPORT",disposition: "observe",@@ -19108,7 +19078,7 @@ function evaluateAssetScopeQa(context) {}, "scope.w7")];}-var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), stable6 = (value) => Math.round(value * 1e6) / 1e6, finiteTuple2 = (value, length3) => Array.isArray(value) && value.length === length3 && value.every((component) => typeof component === "number" && Number.isFinite(component)), VFX_EXACT_QA_RULE, VFX_ADVISORY_QA_RULE, MODULAR_JOIN_QA_RULE, ASSET_SCOPE_QA_RULE, W7_BREADTH_QA_RULES;+var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), stable6 = (value) => Math.round(value * 1e6) / 1e6, finiteTuple2 = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), VFX_EXACT_QA_RULE, VFX_ADVISORY_QA_RULE, MODULAR_JOIN_QA_RULE, ASSET_SCOPE_QA_RULE, W7_BREADTH_QA_RULES;var init_breadth2 = __esm(() => {init_breadth();init_registry();@@ -19178,10 +19148,10 @@ function isTexture(value) {function isAnimationClip(value) {return record3(value) && typeof value.name === "string" && typeof value.duration === "number" && Number.isFinite(value.duration) && Array.isArray(value.tracks);}-function localRenderableBox(rootInverse2, node) {+function localRenderableBox(rootInverse, node) {if (isSpriteNode(node)) {- const transform2 = rootInverse2.clone().multiply(node.matrixWorld);- return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform2);+ const transform = rootInverse.clone().multiply(node.matrixWorld);+ return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);}if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)return;@@ -19189,12 +19159,12 @@ function localRenderableBox(rootInverse2, node) {const source = node.geometry.boundingBox;if (!source || source.isEmpty())return;- const transform = rootInverse2.clone().multiply(node.matrixWorld);+ const transform = rootInverse.clone().multiply(node.matrixWorld);const result = new THREE27.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {- for (const z3 of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE27.Vector3(x, y, z3).applyMatrix4(transform));+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -19239,8 +19209,8 @@ function materialTextures2(material) {}function materialTextureBytes(material) {return materialTextures2(material).reduce((sum, texture) => {- const dimensions2 = textureDimensions(texture);- return sum + (dimensions2 ? Math.ceil(dimensions2[0] * dimensions2[1] * 4 * (4 / 3)) : 0);+ const dimensions = textureDimensions(texture);+ return sum + (dimensions ? Math.ceil(dimensions[0] * dimensions[1] * 4 * (4 / 3)) : 0);}, 0);}function alphaMode(material) {@@ -19256,15 +19226,15 @@ function alphaData(material) {return (standard.opacity ?? 1) < 1 || standard.alphaMap !== undefined && standard.alphaMap !== null || textureHasAlpha2(standard.alphaMap) || textureHasAlpha2(standard.map) || (standard.alphaTest ?? 0) > 0 && standard.alphaMap !== undefined && standard.alphaMap !== null;}function surfaceRole(nodes, intent) {- const evidence2 = nodes.flatMap((node) => [+ const evidence = nodes.flatMap((node) => [node.name,...readSemanticMetadataV1(node)?.roles ?? []]);- if (evidence2.some((value) => /(?:^|[._ -])beam(?:$|[._ -])/i.test(value)))+ if (evidence.some((value) => /(?:^|[._ -])beam(?:$|[._ -])/i.test(value)))return "beam";- if (evidence2.some((value) => /(?:^|[._ -])trail(?:$|[._ -])/i.test(value)))+ if (evidence.some((value) => /(?:^|[._ -])trail(?:$|[._ -])/i.test(value)))return "trail";- if (evidence2.some((value) => /(?:^|[._ -])(?:volume|aura|portal)(?:$|[._ -])/i.test(value))) {+ if (evidence.some((value) => /(?:^|[._ -])(?:volume|aura|portal)(?:$|[._ -])/i.test(value))) {return "volume";}if (intent.subtype === "beam")@@ -19347,13 +19317,13 @@ function dominantGeometryAxis(root, mode) {const bounds = node.geometry.boundingBox;if (!bounds || bounds.isEmpty())return;- const size2 = bounds.getSize(new THREE27.Vector3);- const axes2 = [- { score: size2.x, direction: new THREE27.Vector3(1, 0, 0) },- { score: size2.y, direction: new THREE27.Vector3(0, 1, 0) },- { score: size2.z, direction: new THREE27.Vector3(0, 0, 1) }+ const size = bounds.getSize(new THREE27.Vector3);+ const axes = [+ { score: size.x, direction: new THREE27.Vector3(1, 0, 0) },+ { score: size.y, direction: new THREE27.Vector3(0, 1, 0) },+ { score: size.z, direction: new THREE27.Vector3(0, 0, 1) }];- const selected = axes2.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);+ const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const relative = inverse.clone().multiply(node.matrixWorld);const direction = selected.direction.transformDirection(relative);const score = selected.score * node.getWorldScale(new THREE27.Vector3).length();@@ -19464,10 +19434,10 @@ function analyzeAssetScopeObservationV1(root) {root.traverse((node) => {if ((isMeshNode(node) || isSpriteNode(node)) && node.visible)renderableCount++;- const roles2 = readSemanticMetadataV1(node)?.roles ?? [];- if (roles2.some((role) => MEMBER_ROLE.test(role)))+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ if (roles.some((role) => MEMBER_ROLE.test(role)))members.add(node);- for (const role of roles2)+ for (const role of roles)if (DRESSING_ROLE.test(role))dressing.add(role);if (node !== root && DRESSING_NAME.test(node.name))@@ -19493,7 +19463,7 @@ function pathOf2(root, node) {}function analyzeSockets(root) {root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();const rootWorldRotation = root.getWorldQuaternion(new THREE27.Quaternion).invert();const values = [];root.traverse((node) => {@@ -19507,7 +19477,7 @@ function analyzeSockets(root) {continue;const frameRotation = new THREE27.Quaternion(...frame.rotation);const worldRotation = rootWorldRotation.clone().multiply(nodeWorldRotation).multiply(frameRotation);- const position = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse2);+ const position = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);const normal = new THREE27.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();values.push({contract: {@@ -19597,20 +19567,20 @@ function sceneNodes(context) {return [];const nodes = [];const seen = new Set;- const add2 = (node) => {+ const add = (node) => {if (!seen.has(node)) {seen.add(node);nodes.push(node);}};if (typeof context.scene.traverse === "function") {- context.scene.traverse(add2);+ context.scene.traverse(add);return nodes;}const pending = [context.scene];while (pending.length > 0) {const node = pending.shift();- add2(node);+ add(node);for (const child of node.children ?? [])pending.push(child);}@@ -19747,10 +19717,10 @@ function zeroScaleFindings(context) {const required = new Set(context.intent.requiredParts);const findings = [];for (const node of sceneNodes(context)) {- const scale2 = node.scale;- if (!scale2)+ const scale = node.scale;+ if (!scale)continue;- const zeroAxes = ["x", "y", "z"].filter((axis) => Number.isFinite(scale2[axis]) && Math.abs(scale2[axis]) <= ZERO_SCALE_EPSILON);+ const zeroAxes = ["x", "y", "z"].filter((axis) => Number.isFinite(scale[axis]) && Math.abs(scale[axis]) <= ZERO_SCALE_EPSILON);if (zeroAxes.length === 0)continue;const outputBearing = isRenderable(node) || descendantsContainRenderable(node) || required.has(nodeName(node));@@ -19771,10 +19741,10 @@ function clipList(context) {return (context.clips ?? []).filter((clip) => typeof clip === "object" && clip !== null);}function trackTarget2(trackName) {- const dot4 = trackName.indexOf(".");- if (dot4 <= 0)+ const dot = trackName.indexOf(".");+ if (dot <= 0)return;- const path = trackName.slice(0, dot4);+ const path = trackName.slice(0, dot);const slash = path.lastIndexOf("/");return path.slice(slash + 1) || undefined;}@@ -19968,7 +19938,7 @@ function appendFinalGltfQa(intent, sceneReport, gltfReport) {metrics: {exportIntegrity: {gltfErrors: gltfReport.issues.numErrors,- gltfWarnings: gltfFindings.filter((finding6) => finding6.disposition === "warn").length+ gltfWarnings: gltfFindings.filter((finding) => finding.disposition === "warn").length}}});@@ -20085,8 +20055,8 @@ var init_run = __esm(() => {stage;gltfValidation;constructor(report, stage, gltfValidation) {- const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding6) => finding6.disposition === "block");- const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding6) => `${finding6.code}: ${finding6.message}${finding6.repairText ? ` FIX: ${finding6.repairText}` : ""}`);+ const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding) => finding.disposition === "block");+ const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding) => `${finding.code}: ${finding.message}${finding.repairText ? ` FIX: ${finding.repairText}` : ""}`);const overflow = blockers.length > MAX_DETAILED_BLOCKERS ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)` : "";super(`Asset QA blocked at ${stage}: ${detailed.join(" | ") || "unknown blocker"}${overflow}`);this.name = "AssetQaBlockedError";@@ -20155,25 +20125,25 @@ function signedAxis2(vector) {function finalEffectAxis(nodes, mode) {let best;for (const node of nodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic3?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());- const scale2 = node.getWorldScale();- const scaleMagnitude = Math.hypot(scale2[0], scale2[1], scale2[2]);+ const scale = node.getWorldScale();+ const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);for (const primitive of node.getMesh()?.listPrimitives() ?? []) {const position = primitive.getAttribute("POSITION");if (!position)continue;const min = position.getMin([]);const max = position.getMax([]);- const axes2 = [+ const axes = [{ score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },{ score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },{ score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }];- const selected = axes2.reduce((candidate2, value) => mode === "length" ? value.score > candidate2.score ? value : candidate2 : value.score < candidate2.score ? value : candidate2);+ const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const candidate = {score: selected.score * scaleMagnitude,direction: selected.direction.transformDirection(matrix)@@ -20192,16 +20162,16 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);const meshes = [...new Set(renderableNodes.map((node) => node.getMesh()).filter(Boolean))];const primitives = meshes.flatMap((mesh) => mesh?.listPrimitives() ?? []);- let triangleCount2 = 0;+ let triangleCount = 0;for (const primitive of primitives) {const indices = primitive.getIndices();const position = primitive.getAttribute("POSITION");- triangleCount2 += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;+ triangleCount += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;}const effectSurfaceMaterials = new Set;for (const node of renderableNodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic3?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}for (const primitive of node.getMesh()?.listPrimitives() ?? []) {@@ -20229,8 +20199,8 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {});const facingSemantics = new Set;for (const node of renderableNodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- for (const role of semantic3?.roles ?? []) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ for (const role of semantic?.roles ?? []) {const match = /^vfx\.facing\.(fixed|camera-spherical|camera-y-axis)$/.exec(role);if (match)facingSemantics.add(match[1]);@@ -20242,7 +20212,7 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {schemaVersion: 1,meshCount: meshes.length,primitiveCount: primitives.length,- triangleCount: Math.floor(triangleCount2),+ triangleCount: Math.floor(triangleCount),materials,facingSemantics: [...facingSemantics].sort(),...normalAxis ? { normalAxis } : {},@@ -20256,12 +20226,12 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {function finalFinding(intent, value) {return { ...value, profile: intent.qaProfile || "vfx.w7.final-glb" };}-function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {+function evaluateFinalVfxGlbEvidenceV1(intent, evidence) {if (intent.category !== "vfx" || !intent.vfx)return [];const contract = intent.vfx;const findings = [];- if (evidence2.meshCount === 0 || evidence2.primitiveCount === 0 || evidence2.triangleCount === 0) {+ if (evidence.meshCount === 0 || evidence.primitiveCount === 0 || evidence.triangleCount === 0) {findings.push(finalFinding(intent, {code: "VFX_GLTF_RENDERABLE_MISSING",disposition: "block",@@ -20269,13 +20239,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB contains no renderable VFX geometry.",measurement: {name: "finalVfxTriangles",- actual: evidence2.triangleCount,+ actual: evidence.triangleCount,expected: ">=1"},repairText: "Export the effect surface as portable geometry before final-byte approval."}));}- const effectMaterials = evidence2.materials.filter((material) => material.effectSurface);+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface);if (effectMaterials.length === 0) {findings.push(finalFinding(intent, {code: "VFX_GLTF_EFFECT_SURFACE_MISSING",@@ -20335,7 +20305,7 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {}));}}- if (contract.facing.mode !== "fixed" && !evidence2.facingSemantics.includes(contract.facing.mode)) {+ if (contract.facing.mode !== "fixed" && !evidence.facingSemantics.includes(contract.facing.mode)) {findings.push(finalFinding(intent, {code: "VFX_GLTF_FACING_SEMANTIC_MISSING",disposition: "block",@@ -20343,13 +20313,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: `Final GLB does not carry the ${contract.facing.mode} runtime-facing semantic.`,measurement: {name: "finalFacingSemantics",- actual: evidence2.facingSemantics.join(",") || null,+ actual: evidence.facingSemantics.join(",") || null,expected: contract.facing.mode},repairText: "Preserve the exporter-derived billboard semantic on the renderable quad node."}));}- if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence2.normalAxis) {+ if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence.normalAxis) {findings.push(finalFinding(intent, {code: "VFX_GLTF_NORMAL_AXIS_MISMATCH",disposition: "block",@@ -20357,12 +20327,12 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB effect-surface normal axis differs from explicit VFX intent.",measurement: {name: "finalNormalAxis",- actual: evidence2.normalAxis ?? null,+ actual: evidence.normalAxis ?? null,expected: contract.facing.normalAxis ?? null}}));}- if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence2.directionAxis) {+ if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence.directionAxis) {findings.push(finalFinding(intent, {code: "VFX_GLTF_DIRECTION_AXIS_MISMATCH",disposition: "block",@@ -20370,13 +20340,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB effect-surface direction axis differs from explicit VFX intent.",measurement: {name: "finalDirectionAxis",- actual: evidence2.directionAxis ?? null,+ actual: evidence.directionAxis ?? null,expected: contract.facing.directionAxis}}));}if (contract.animation.driver === "clip") {- const clip = evidence2.clips.find((candidate) => candidate.name === contract.animation.clipName);+ const clip = evidence.clips.find((candidate) => candidate.name === contract.animation.clipName);if (!clip || Math.abs(clip.durationSeconds - contract.animation.durationSeconds) > 0.000001) {findings.push(finalFinding(intent, {code: "VFX_GLTF_REQUIRED_CLIP_MISSING",@@ -20399,24 +20369,24 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {async function appendFinalVfxGlbQa(intent, report, bytes) {if (intent.category !== "vfx")return report;- const evidence2 = await analyzeFinalVfxGlbBytesV1(bytes);+ const evidence = await analyzeFinalVfxGlbBytesV1(bytes);const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);- findings.push(...evaluateFinalVfxGlbEvidenceV1(intent, evidence2));+ findings.push(...evaluateFinalVfxGlbEvidenceV1(intent, evidence));const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);if (!evaluatedDimensions.includes("exportIntegrity"))evaluatedDimensions.push("exportIntegrity");const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));metrics.exportIntegrity = {...metrics.exportIntegrity ?? {},- finalVfxMeshCount: evidence2.meshCount,- finalVfxPrimitiveCount: evidence2.primitiveCount,- finalVfxTriangles: evidence2.triangleCount,- finalVfxMaterialCount: evidence2.materials.length,- finalVfxEffectMaterialCount: evidence2.materials.filter((material) => material.effectSurface).length,- finalVfxFacingSemantics: evidence2.facingSemantics.join(","),- finalVfxNormalAxis: evidence2.normalAxis ?? null,- finalVfxDirectionAxis: evidence2.directionAxis ?? null,- finalVfxClipCount: evidence2.clips.length+ finalVfxMeshCount: evidence.meshCount,+ finalVfxPrimitiveCount: evidence.primitiveCount,+ finalVfxTriangles: evidence.triangleCount,+ finalVfxMaterialCount: evidence.materials.length,+ finalVfxEffectMaterialCount: evidence.materials.filter((material) => material.effectSurface).length,+ finalVfxFacingSemantics: evidence.facingSemantics.join(","),+ finalVfxNormalAxis: evidence.normalAxis ?? null,+ finalVfxDirectionAxis: evidence.directionAxis ?? null,+ finalVfxClipCount: evidence.clips.length};return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });}@@ -20550,7 +20520,7 @@ function evaluateMaterialBudgetV1(metrics, options) {});}if (metrics.decodedImageBytesRgba8 > limits.maxDecodedBytesRgba8) {- const scale2 = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);+ const scale = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);warnings.push({code: "MATERIAL_DECODED_MEMORY_BUDGET",disposition: "warn",@@ -20563,7 +20533,7 @@ function evaluateMaterialBudgetV1(metrics, options) {threshold: limits.maxDecodedBytesRgba8,unit: "bytes"},- advice: `Downscale image width and height by approximately ${(Math.min(1, scale2) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`+ advice: `Downscale image width and height by approximately ${(Math.min(1, scale) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`});}if (metrics.blendedSurfaceAreaRatio > limits.maxBlendedSurfaceAreaRatio) {@@ -20590,13 +20560,13 @@ var MATERIAL_BUDGET_PROFILES_V1, materialTextures3 = (material) => [material.getNormalTexture(),material.getOcclusionTexture(),material.getEmissiveTexture()-], hasTexture = (material) => materialTextures3(material).some(Boolean), transformPoint = (matrix, x, y, z3) => {- const w = matrix[3] * x + matrix[7] * y + matrix[11] * z3 + matrix[15];+], hasTexture = (material) => materialTextures3(material).some(Boolean), transformPoint = (matrix, x, y, z) => {+ const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];const reciprocal = w === 0 ? 1 : 1 / w;return [- (matrix[0] * x + matrix[4] * y + matrix[8] * z3 + matrix[12]) * reciprocal,- (matrix[1] * x + matrix[5] * y + matrix[9] * z3 + matrix[13]) * reciprocal,- (matrix[2] * x + matrix[6] * y + matrix[10] * z3 + matrix[14]) * reciprocal+ (matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12]) * reciprocal,+ (matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13]) * reciprocal,+ (matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]) * reciprocal];}, accessorPoint = (accessor, index, matrix) => {const array = accessor.getArray();@@ -20665,11 +20635,11 @@ var init_material_metrics = __esm(() => {// src/texture-resolver.tsfunction createTextureResolver(cache = DEFAULT_APPROVED_TEXTURE_CACHE) {return Object.freeze({- async loadApprovedTexture(resourceId2) {- if (typeof resourceId2 !== "string") {+ async loadApprovedTexture(resourceId) {+ if (typeof resourceId !== "string") {throw new RangeError("Unsupported approved texture resource ID.");}- return (await cache.load(resourceId2)).texture;+ return (await cache.load(resourceId)).texture;},async materialRecipe(id, overrides) {if (typeof id !== "string")@@ -20968,32 +20938,32 @@ function analyzeGeneratedSourceSafety(ast) {const issues = [];const seen = new Set;const staticStrings = collectStaticStringBindings(ast);- const add2 = (issue) => {+ const add = (issue) => {const key = issueKey(issue);if (seen.has(key))return;seen.add(key);issues.push(issue);};- const ambient = (name, line) => add2({+ const ambient = (name, line) => add({code: "UNSAFE_GLOBAL_ACCESS",message: `Generated code cannot access ambient capability \`${name}\`.`,fixHint: "Use only the documented sandbox globals and approved resource helpers.",line});- const dynamicCode = (line) => add2({+ const dynamicCode = (line) => add({code: "DYNAMIC_CODE_ACCESS",message: "Generated code cannot access constructor chains or dynamic-code constructors.",fixHint: "Call documented sandbox helpers directly; do not derive constructors at runtime.",line});- const unsafeThree = (name, line) => add2({+ const unsafeThree = (name, line) => add({code: "UNSAFE_THREE_CONSTRUCTOR",message: `Generated code cannot access raw THREE constructor \`${name}\`.`,fixHint: "Use approved texture loading, proceduralTexture, pbrMaterial, or materialRecipe instead.",line});- const unsafeThreeNamespace = (code, line) => add2({+ const unsafeThreeNamespace = (code, line) => add({code,message: code === "UNSAFE_THREE_ALIAS" ? "Generated code cannot alias the THREE namespace." : "Generated code cannot use non-static computed access on the THREE namespace.",fixHint: "Use a documented direct THREE constructor or a sandbox material/texture helper.",@@ -21012,7 +20982,7 @@ function analyzeGeneratedSourceSafety(ast) {ambient("this", node.loc?.start.line);},ImportExpression(node) {- add2({+ add({code: "DYNAMIC_IMPORT",message: "Generated code cannot use dynamic import.",fixHint: "Remove import(); all supported helpers are already sandbox globals.",@@ -21235,8 +21205,8 @@ function analyzeRotationUnits(ast, source) {}function classifyRotationArray(arr, fn, source) {const rendered = () => {- const text2 = source.slice(arr.start, arr.end).replace(/\s+/g, " ");- return text2.length > 64 ? `${text2.slice(0, 61)}...` : text2;+ const text = source.slice(arr.start, arr.end).replace(/\s+/g, " ");+ return text.length > 64 ? `${text.slice(0, 61)}...` : text;};let sawPI = false;let onlyConversions = true;@@ -21533,234 +21503,9 @@ var init_validation = __esm(() => {// src/kit.tsimport { execFile } from "node:child_process";-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";import { promisify } from "node:util";import { KHRMaterialsVariants, KHRTextureBasisu } from "@gltf-transform/extensions";-async function findKtxEncoder() {- if (cachedEncoder !== undefined)- return cachedEncoder ?? undefined;- for (const candidate of KTX_ENCODER_CANDIDATES) {- try {- await run(candidate, ["--version"], { timeout: 1e4 });- cachedEncoder = candidate;- return candidate;- } catch {}- }- cachedEncoder = null;- return;-}-function disposeIfOrphaned(texture) {- const stillUsed = texture.listParents().some((parent) => parent.propertyType !== "Root");- if (!stillUsed)- texture.dispose();-}-async function packOcclusionIntoMetallicRoughness(doc) {- const sharp = (await import("sharp")).default;- let packed = 0;- for (const material of doc.getRoot().listMaterials()) {- const occlusion = material.getOcclusionTexture();- const metallicRoughness = material.getMetallicRoughnessTexture();- if (!occlusion || !metallicRoughness || occlusion === metallicRoughness)- continue;- if (!isPng(occlusion) || !isPng(metallicRoughness))- continue;- const occlusionBytes = occlusion.getImage();- const mrBytes = metallicRoughness.getImage();- if (!occlusionBytes || !mrBytes)- continue;- try {- const [occImage, mrImage] = await Promise.all([- sharp(Buffer.from(occlusionBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true }),- sharp(Buffer.from(mrBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true })- ]);- if (occImage.info.width !== mrImage.info.width || occImage.info.height !== mrImage.info.height) {- continue;- }- const { width, height } = mrImage.info;- const merged = Buffer.allocUnsafe(width * height * 3);- for (let i = 0, o = 0;o < merged.length; i += 4, o += 3) {- merged[o] = occImage.data[i] ?? 255;- merged[o + 1] = mrImage.data[i + 1] ?? 255;- merged[o + 2] = mrImage.data[i + 2] ?? 255;- }- const png = await sharp(merged, { raw: { width, height, channels: 3 } }).png({ compressionLevel: 9 }).toBuffer();- metallicRoughness.setImage(new Uint8Array(png));- material.setOcclusionTexture(metallicRoughness);- const info = material.getOcclusionTextureInfo();- const mrInfo = material.getMetallicRoughnessTextureInfo();- if (info && mrInfo)- info.setTexCoord(mrInfo.getTexCoord());- disposeIfOrphaned(occlusion);- packed += 1;- } catch {}- }- return packed;-}-function recolorForPalette(doc, material, slots, variantName) {- const clone2 = doc.createMaterial(`${material.getName()}__${variantName}`).copy(material);- if (material.getBaseColorTexture())- return { material: clone2, changed: false };- const index = buildSlotIndex(slots);- const base = material.getBaseColorFactor();- const emissive = material.getEmissiveFactor();- const slot = chooseSlot(index, {- baseLinear: [base[0], base[1], base[2]],- emissiveLinear: [emissive[0], emissive[1], emissive[2]],- transparent: material.getAlphaMode() === "BLEND" || material.getAlpha() < 0.98- });- if (slot === undefined)- return { material: clone2, changed: false };- const chosen = slots[slot];- if (!chosen)- return { material: clone2, changed: false };- const [r, g, b] = hexToLinearRgb(chosen.color);- if (chosen.kind === "glow") {- clone2.setEmissiveFactor([r, g, b]);- } else {- clone2.setBaseColorFactor([r, g, b, base[3]]);- if (typeof chosen.roughness === "number")- clone2.setRoughnessFactor(chosen.roughness);- if (typeof chosen.metalness === "number")- clone2.setMetallicFactor(chosen.metalness);- if (chosen.kind === "glass" && typeof chosen.opacity === "number") {- clone2.setBaseColorFactor([r, g, b, chosen.opacity]);- }- }- return { material: clone2, changed: true };-}-function addPaletteVariants(doc, specs) {- const extension = doc.createExtension(KHRMaterialsVariants);- const names = [];- let materialsCreated = 0;- const variants = specs.map((spec) => {- names.push(spec.name);- return { spec, variant: extension.createVariant(spec.name) };- });- for (const mesh of doc.getRoot().listMeshes()) {- for (const primitive of mesh.listPrimitives()) {- const base = primitive.getMaterial();- if (!base)- continue;- const mappings = variants.map(({ spec, variant }) => {- const { material, changed } = recolorForPalette(doc, base, spec.slots, spec.name);- if (!changed) {- material.dispose();- return;- }- materialsCreated += 1;- return extension.createMapping().addVariant(variant).setMaterial(material);- }).filter((value) => value !== undefined);- if (mappings.length === 0)- continue;- const list = extension.createMappingList();- for (const mapping of mappings)- list.addMapping(mapping);- primitive.setExtension("KHR_materials_variants", list);- }- }- if (names.length === 0 || materialsCreated === 0)- extension.dispose();- return { names: materialsCreated > 0 ? names : [], materialsCreated };-}-async function encodeTexturesToKtx2(doc, encoder) {- const textures = doc.getRoot().listTextures().filter(isPng);- if (textures.length === 0)- return { encoded: 0, before: 0, after: 0 };- const dir = await mkdtemp(join(tmpdir(), "kiln-ktx2-"));- const staged = [];- let encoded = 0;- let before = 0;- let after = 0;- try {- for (const [index, texture] of textures.entries()) {- const bytes = texture.getImage();- if (!bytes)- continue;- const src = join(dir, `t${index}.png`);- const dst = join(dir, `t${index}.ktx2`);- await writeFile(src, bytes);- const srgb = doc.getRoot().listMaterials().some((material) => material.getBaseColorTexture() === texture || material.getEmissiveTexture() === texture);- await run(encoder, [- "create",- "--format",- srgb ? "R8G8B8A8_SRGB" : "R8G8B8A8_UNORM",- "--encode",- KTX_ENCODE_MODE,- "--generate-mipmap",- src,- dst- ], { timeout: 120000 });- const out = await readFile(dst);- before += bytes.byteLength;- after += out.byteLength;- staged.push({ texture, original: bytes, encodedBytes: new Uint8Array(out) });- }- } finally {- await rm(dir, { recursive: true, force: true });- }- if (staged.length === 0)- return { encoded: 0, before, after };- if (after >= before * KTX2_SIZE_ACCEPT_RATIO) {- return { encoded: 0, before, after };- }- for (const entry of staged) {- entry.texture.setImage(entry.encodedBytes).setMimeType("image/ktx2");- encoded += 1;- }- doc.createExtension(KHRTextureBasisu).setRequired(true);- return { encoded, before, after };-}-async function applyKitContract(doc, options = {}) {- const ormPacked = options.packOrm === false ? 0 : await packOcclusionIntoMetallicRoughness(doc);- const specs = options.variants ?? [];- const { names, materialsCreated } = specs.length ? addPaletteVariants(doc, specs) : { names: [], materialsCreated: 0 };- let ktx2 = {- applied: false,- skipped: "disabled by caller",- texturesEncoded: 0,- bytesBefore: 0,- bytesAfter: 0- };- if (options.ktx2 !== false) {- const encoder = await findKtxEncoder();- if (!encoder) {- ktx2 = {- applied: false,- skipped: "no KTX-Software encoder on PATH (set KILN_KTX_BIN to override)",- texturesEncoded: 0,- bytesBefore: 0,- bytesAfter: 0- };- } else {- try {- const result = await encodeTexturesToKtx2(doc, encoder);- ktx2 = {- applied: result.encoded > 0,- ...result.encoded > 0 ? {} : {- skipped: result.before === 0 ? "no PNG textures to encode" : `KTX2 was not smaller (${result.after} vs ${result.before} bytes); kept PNG`- },- encoder,- texturesEncoded: result.encoded,- bytesBefore: result.before,- bytesAfter: result.after- };- } catch (error) {- ktx2 = {- applied: false,- skipped: `encoder failed: ${error instanceof Error ? error.message : String(error)}`,- encoder,- texturesEncoded: 0,- bytesBefore: 0,- bytesAfter: 0- };- }- }- }- return { ormPacked, variantsAdded: names, variantMaterialsCreated: materialsCreated, ktx2 };-}-var run, KTX_ENCODER_CANDIDATES, KTX_ENCODE_MODE = "basis-lz", KTX2_SIZE_ACCEPT_RATIO = 0.9, cachedEncoder, isPng = (texture) => texture.getMimeType() === "image/png";+var run, KTX_ENCODER_CANDIDATES;var init_kit = __esm(() => {run = promisify(execFile);KTX_ENCODER_CANDIDATES = Object.freeze([@@ -21828,7 +21573,7 @@ async function bakeSceneTextures(root, warnings) {const materials = Array.isArray(material) ? material : material ? [material] : [];for (const item of materials) {const bag = item;- for (const [slot, usage2] of SLOT_USAGE2) {+ for (const [slot, usage] of SLOT_USAGE2) {const texture = bag[slot];if (!isTexture2(texture))continue;@@ -21839,7 +21584,7 @@ async function bakeSceneTextures(root, warnings) {node: node.name || "(unnamed node)",material: item.name || "(unnamed material)",slot,- usage: usage2+ usage});pending.set(texture, existing);}@@ -21867,8 +21612,8 @@ async function bakeSceneTextures(root, warnings) {bytes};const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";- const recipe2 = entry.texture.userData["kilnProcedural"];- const primaryUsage = recipe2?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");+ const recipe = entry.texture.userData["kilnProcedural"];+ const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");entry.texture.userData["kilnTexture"] = {usage: primaryUsage,colorSpace,@@ -21894,16 +21639,16 @@ async function bakeSceneTextures(root, warnings) {colorSpace,imageSha256,sha1,- ...recipe2 ? { procedural: recipe2 } : {}+ ...recipe ? { procedural: recipe } : {}});}return baked.sort((a, b) => `${a.node}:${a.material}:${a.texture}:${a.slot}`.localeCompare(`${b.node}:${b.material}:${b.texture}:${b.slot}`));}-function computeTangentBasis(geometry2) {- const index = geometry2.getIndex();- const position = geometry2.getAttribute("position");- const normal = geometry2.getAttribute("normal");- const uv = geometry2.getAttribute("uv");+function computeTangentBasis(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");+ const normal = geometry.getAttribute("normal");+ const uv = geometry.getAttribute("uv");if (!position || !normal || !uv) {throw new Error("position, normal, and uv are all required");}@@ -21921,7 +21666,7 @@ function computeTangentBasis(geometry2) {const z1 = position.getZ(b) - position.getZ(a);const x2 = position.getX(c) - position.getX(a);const y2 = position.getY(c) - position.getY(a);- const z22 = position.getZ(c) - position.getZ(a);+ const z2 = position.getZ(c) - position.getZ(a);const s1 = uv.getX(b) - uv.getX(a);const t1 = uv.getY(b) - uv.getY(a);const s2 = uv.getX(c) - uv.getX(a);@@ -21932,10 +21677,10 @@ function computeTangentBasis(geometry2) {const r = 1 / det;const sdx = (t2 * x1 - t1 * x2) * r;const sdy = (t2 * y1 - t1 * y2) * r;- const sdz = (t2 * z1 - t1 * z22) * r;+ const sdz = (t2 * z1 - t1 * z2) * r;const tdx = (s1 * x2 - s2 * x1) * r;const tdy = (s1 * y2 - s2 * y1) * r;- const tdz = (s1 * z22 - s2 * z1) * r;+ const tdz = (s1 * z2 - s2 * z1) * r;for (const v of [a, b, c]) {const o = v * 3;tan1[o] = (tan1[o] ?? 0) + sdx;@@ -21970,7 +21715,7 @@ function computeTangentBasis(geometry2) {out[v * 4 + 2] = tmp.z;out[v * 4 + 3] = w;}- geometry2.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));+ geometry.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));}function ensureNormalMapTangents(root, warnings) {let count = 0;@@ -21983,19 +21728,19 @@ function ensureNormalMapTangents(root, warnings) {const needsTangents = materials.some((m) => m?.normalMap);if (!needsTangents)return;- const geometry2 = mesh.geometry;- if (!geometry2 || done.has(geometry2) || geometry2.getAttribute("tangent"))+ const geometry = mesh.geometry;+ if (!geometry || done.has(geometry) || geometry.getAttribute("tangent"))return;- done.add(geometry2);+ done.add(geometry);const name = mesh.name || "(unnamed mesh)";- if (!geometry2.getAttribute("uv")) {+ if (!geometry.getAttribute("uv")) {warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but has no UV coordinates, so tangents could not be computed — and the normal map cannot be sampled either. Unwrap it first: mesh.geometry = await autoUnwrap(mesh.geometry).`);return;}- if (!geometry2.getAttribute("normal"))- geometry2.computeVertexNormals();+ if (!geometry.getAttribute("normal"))+ geometry.computeVertexNormals();try {- computeTangentBasis(geometry2);+ computeTangentBasis(geometry);count++;} catch (err) {warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but tangents could not be computed (${err instanceof Error ? err.message : String(err)}). Each runtime will generate its own tangent basis.`);@@ -22024,10 +21769,10 @@ function rounded(value) {function tuple5(vector) {return [rounded(vector.x), rounded(vector.y), rounded(vector.z)];}-function chainIdFor(descriptor2, byRole) {- if (AXIAL_ROLES.has(descriptor2.role))+function chainIdFor(descriptor, byRole) {+ if (AXIAL_ROLES.has(descriptor.role))return "axial";- let current = descriptor2;+ let current = descriptor;const seen = new Set([current.role]);while (current.parentRole && !AXIAL_ROLES.has(current.parentRole)) {const parent = byRole.get(current.parentRole);@@ -22039,28 +21784,28 @@ function chainIdFor(descriptor2, byRole) {return current.role;}function colorFor(value) {- let hash3 = 2166136261;+ let hash = 2166136261;for (let index = 0;index < value.length; index++) {- hash3 ^= value.charCodeAt(index);- hash3 = Math.imul(hash3, 16777619);+ hash ^= value.charCodeAt(index);+ hash = Math.imul(hash, 16777619);}- return CHAIN_COLORS[Math.abs(hash3) % CHAIN_COLORS.length];+ return CHAIN_COLORS[Math.abs(hash) % CHAIN_COLORS.length];}function buildCharacterDiagnosticDescriptor(root, findings = []) {root.updateMatrixWorld(true);- const rootInverse2 = root.matrixWorld.clone().invert();- const evidence2 = collectCharacterJointNodes(root);- const descriptorByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint.descriptor]));- const evidenceByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint]));+ const rootInverse = root.matrixWorld.clone().invert();+ const evidence = collectCharacterJointNodes(root);+ const descriptorByRole = new Map(evidence.map((joint) => [joint.descriptor.role, joint.descriptor]));+ const evidenceByRole = new Map(evidence.map((joint) => [joint.descriptor.role, joint]));const invalidFindingNodePaths = [- ...new Set(findings.filter((finding6) => finding6.code === "CHAR_PARENT_EDGE").map((finding6) => finding6.affected?.nodePath).filter((path) => Boolean(path)))+ ...new Set(findings.filter((finding) => finding.code === "CHAR_PARENT_EDGE").map((finding) => finding.affected?.nodePath).filter((path) => Boolean(path)))].sort();const invalidPaths = new Set(invalidFindingNodePaths);- const joints = evidence2.map((joint) => {- const relative = rootInverse2.clone().multiply(joint.node.matrixWorld);+ const joints = evidence.map((joint) => {+ const relative = rootInverse.clone().multiply(joint.node.matrixWorld);const position = new THREE30.Vector3().setFromMatrixPosition(relative);const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);- const bend2 = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -22073,12 +21818,12 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {color: colorFor(chainId),assetPosition: tuple5(position),forwardAxisEnd: tuple5(forward),- bendAxisEnd: tuple5(bend2),+ bendAxisEnd: tuple5(bend),endEffector: joint.descriptor.endEffector,contact: joint.descriptor.contact};});- const edges = evidence2.filter((joint) => joint.descriptor.parentRole).map((joint) => {+ const edges = evidence.filter((joint) => joint.descriptor.parentRole).map((joint) => {const parentRole = joint.descriptor.parentRole;const parent = evidenceByRole.get(parentRole);const chainId = chainIdFor(joint.descriptor, descriptorByRole);@@ -22277,16 +22022,16 @@ function composeLocalMatrix(node) {}const x2 = q.x + q.x;const y2 = q.y + q.y;- const z22 = q.z + q.z;+ const z2 = q.z + q.z;const xx = q.x * x2;const xy = q.x * y2;- const xz = q.x * z22;+ const xz = q.x * z2;const yy = q.y * y2;- const yz = q.y * z22;- const zz = q.z * z22;+ const yz = q.y * z2;+ const zz = q.z * z2;const wx = q.w * x2;const wy = q.w * y2;- const wz = q.w * z22;+ const wz = q.w * z2;return new Float64Array([(1 - (yy + zz)) * s.x,(xy + wz) * s.x,@@ -22306,15 +22051,15 @@ function composeLocalMatrix(node) {1]);}-function transformPoint2(matrix, x, y, z3) {+function transformPoint2(matrix, x, y, z) {return [- matrix[0] * x + matrix[4] * y + matrix[8] * z3 + matrix[12],- matrix[1] * x + matrix[5] * y + matrix[9] * z3 + matrix[13],- matrix[2] * x + matrix[6] * y + matrix[10] * z3 + matrix[14]+ matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],+ matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],+ matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]];}-function matchesRole(roles2, prefixes) {- return Boolean(prefixes?.some((prefix) => roles2.some((role) => role.startsWith(prefix))));+function matchesRole(roles, prefixes) {+ return Boolean(prefixes?.some((prefix) => roles.some((role) => role.startsWith(prefix))));}function semanticRoles2(node) {const metadata = readSemanticMetadataV1FromExtras(node.userData ?? {});@@ -22337,9 +22082,9 @@ function collectScene(root, requestValue) {const world = multiplyMatrices(parentMatrix, local);const visible = ancestorVisible && node.visible !== false;const segment = `${node.name?.trim() || node.type || "Node"}[${siblingIndex}]`;- const nodePath5 = parentPath ? `${parentPath}/${segment}` : segment;- const roles2 = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];- const omitted = matchesRole(roles2, requestValue.omitRolePrefixes);+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ const roles = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];+ const omitted = matchesRole(roles, requestValue.omitRolePrefixes);if (visible && !omitted && node.isMesh && node.geometry) {const materials = Array.isArray(node.material) ? node.material : [node.material];const material = materials[0];@@ -22347,13 +22092,13 @@ function collectScene(root, requestValue) {const position = node.geometry.getAttribute?.("position");if (position?.itemSize === 3) {const worldPositions = [];- for (let index2 = 0;index2 < position.count; index2++) {- const point = transformPoint2(world, position.array[index2 * 3], position.array[index2 * 3 + 1], position.array[index2 * 3 + 2]);+ for (let index = 0;index < position.count; index++) {+ const point = transformPoint2(world, position.array[index * 3], position.array[index * 3 + 1], position.array[index * 3 + 2]);worldPositions.push(point);}const materialColor = material?.color;- const color2 = materialColor ? [clamp012(materialColor.r), clamp012(materialColor.g), clamp012(materialColor.b)] : [0.7, 0.7, 0.7];- const focused = matchesRole(roles2, requestValue.focusRolePrefixes);+ const color = materialColor ? [clamp012(materialColor.r), clamp012(materialColor.g), clamp012(materialColor.b)] : [0.7, 0.7, 0.7];+ const focused = matchesRole(roles, requestValue.focusRolePrefixes);const addTriangle = (a, b, c) => {const points = [worldPositions[a], worldPositions[b], worldPositions[c]];if (points.some((point) => !point || point.some((value) => !Number.isFinite(value)))) {@@ -22374,10 +22119,10 @@ function collectScene(root, requestValue) {});triangles.push({vertices,- color: color2,+ color,nodeName: node.name ?? "",- nodePath: nodePath5,- semanticRoles: roles2+ nodePath,+ semanticRoles: roles});};const index = node.geometry.index;@@ -22393,7 +22138,7 @@ function collectScene(root, requestValue) {}}(node.children ?? []).forEach((child, index) => {- visit(child, world, nodePath5, index, visible && !omitted, roles2);+ visit(child, world, nodePath, index, visible && !omitted, roles);});};visit(root, IDENTITY, "", 0, true, []);@@ -22406,8 +22151,8 @@ function collectScene(root, requestValue) {};}function normalize3(vector) {- const length3 = Math.hypot(...vector) || 1;- return [vector[0] / length3, vector[1] / length3, vector[2] / length3];+ const length = Math.hypot(...vector) || 1;+ return [vector[0] / length, vector[1] / length, vector[2] / length];}function cross3(a, b) {return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];@@ -22416,12 +22161,12 @@ function dot4(a, b) {return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];}function stableColor(key) {- let hash3 = 2166136261;+ let hash = 2166136261;for (let index = 0;index < key.length; index++) {- hash3 ^= key.charCodeAt(index);- hash3 = Math.imul(hash3, 16777619);+ hash ^= key.charCodeAt(index);+ hash = Math.imul(hash, 16777619);}- return [96 + (hash3 & 127), 96 + (hash3 >>> 8 & 127), 96 + (hash3 >>> 16 & 127)];+ return [96 + (hash & 127), 96 + (hash >>> 8 & 127), 96 + (hash >>> 16 & 127)];}function projectScene(scene, camera, size) {const zAxis = normalize3(camera.dir);@@ -22434,26 +22179,26 @@ function projectScene(scene, camera, size) {(frame.min[1] + frame.max[1]) / 2,(frame.min[2] + frame.max[2]) / 2];- let extent2 = 0.000001;+ let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {const point = [(corner & 1 ? frame.max[0] : frame.min[0]) - center[0],(corner & 2 ? frame.max[1] : frame.min[1]) - center[1],(corner & 4 ? frame.max[2] : frame.min[2]) - center[2]];- extent2 = Math.max(extent2, Math.abs(dot4(point, xAxis)), Math.abs(dot4(point, yAxis)));+ extent = Math.max(extent, Math.abs(dot4(point, xAxis)), Math.abs(dot4(point, yAxis)));}- const scale2 = size * 0.45 / extent2;+ const scale = size * 0.45 / extent;const half = size / 2;return scene.triangles.flatMap((triangle) => {const v = triangle.vertices;const edgeA = [v[3] - v[0], v[4] - v[1], v[5] - v[2]];const edgeB = [v[6] - v[0], v[7] - v[1], v[8] - v[2]];const normalRaw = cross3(edgeA, edgeB);- const length3 = Math.hypot(...normalRaw);- if (length3 < 0.000000000001)+ const length = Math.hypot(...normalRaw);+ if (length < 0.000000000001)return [];- const normal = normalRaw.map((component) => component / length3);+ const normal = normalRaw.map((component) => component / length);const xs = [];const ys = [];const zs = [];@@ -22464,8 +22209,8 @@ function projectScene(scene, camera, size) {v[index * 3 + 1] - center[1],v[index * 3 + 2] - center[2]];- xs.push(half + dot4(point, xAxis) * scale2);- ys.push(half - dot4(point, yAxis) * scale2);+ xs.push(half + dot4(point, xAxis) * scale);+ ys.push(half - dot4(point, yAxis) * scale);zs.push(dot4(point, zAxis));worldY.push(v[index * 3 + 1]);}@@ -22482,7 +22227,7 @@ function projectScene(scene, camera, size) {];});}-function drawLine(rgb2, size, from, to, color2) {+function drawLine(rgb, size, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);const x1 = Math.round(to[0]);@@ -22495,9 +22240,9 @@ function drawLine(rgb2, size, from, to, color2) {while (true) {if (x0 >= 0 && x0 < size && y0 >= 0 && y0 < size) {const offset = (y0 * size + x0) * 3;- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}if (x0 === x1 && y0 === y1)break;@@ -22512,12 +22257,12 @@ function drawLine(rgb2, size, from, to, color2) {}}}-function drawRegionBox(rgb2, size, region) {+function drawRegionBox(rgb, size, region) {const [minX, minY, maxX, maxY] = region.pixelBounds;- drawLine(rgb2, size, [minX, minY], [maxX, minY], region.color);- drawLine(rgb2, size, [maxX, minY], [maxX, maxY], region.color);- drawLine(rgb2, size, [maxX, maxY], [minX, maxY], region.color);- drawLine(rgb2, size, [minX, maxY], [minX, minY], region.color);+ drawLine(rgb, size, [minX, minY], [maxX, minY], region.color);+ drawLine(rgb, size, [maxX, minY], [maxX, maxY], region.color);+ drawLine(rgb, size, [maxX, maxY], [minX, maxY], region.color);+ drawLine(rgb, size, [minX, maxY], [minX, minY], region.color);}function renderDiagnosticView(root, requestValue, options = {}) {const camera = cameraById.get(requestValue.cameraId);@@ -22528,11 +22273,11 @@ function renderDiagnosticView(root, requestValue, options = {}) {const scene = collectScene(root, requestValue);const triangles = projectScene(scene, camera, size);const background = [18, 20, 24];- const rgb2 = new Uint8Array(size * size * 3);+ const rgb = new Uint8Array(size * size * 3);for (let pixel = 0;pixel < size * size; pixel++) {- rgb2[pixel * 3] = background[0];- rgb2[pixel * 3 + 1] = background[1];- rgb2[pixel * 3 + 2] = background[2];+ rgb[pixel * 3] = background[0];+ rgb[pixel * 3 + 1] = background[1];+ rgb[pixel * 3 + 2] = background[2];}const depth = new Float64Array(size * size).fill(-Infinity);const depths = triangles.flatMap((triangle) => triangle.z);@@ -22594,50 +22339,50 @@ function renderDiagnosticView(root, requestValue, options = {}) {continue;depth[pixel] = pixelDepth;const offset = pixel * 3;- let color2;+ let color;if (requestValue.variant === "material-grazing-light") {const grazingDirection = normalize3([0.25, 0.08, 1]);const light = 0.08 + 0.92 * Math.max(0, dot4(triangle.normal, grazingDirection));- color2 = triangle.source.color.map((value) => Math.round(clamp012(value * light) * 255));+ color = triangle.source.color.map((value) => Math.round(clamp012(value * light) * 255));} else if (requestValue.buffer === "silhouette-unlit") {- color2 = [235, 238, 242];+ color = [235, 238, 242];} else if (requestValue.buffer === "normals-backface") {- color2 = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];+ color = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];} else if (requestValue.buffer === "depth-contact") {const worldY = w1 * triangle.worldY[0] + w2 * triangle.worldY[1] + w0 * triangle.worldY[2];if (Math.abs(worldY - groundY) <= contactTolerance)- color2 = [58, 220, 126];+ color = [58, 220, 126];else if (worldY < groundY - contactTolerance)- color2 = [245, 94, 72];+ color = [245, 94, 72];else {const value = Math.round(48 + 190 * ((pixelDepth - minDepth) / depthRange));- color2 = [value, value, value];+ color = [value, value, value];}} else {- color2 = regionColor;+ color = regionColor;}- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}}}if (requestValue.buffer === "wireframe") {for (const triangle of triangles) {- const color2 = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];+ const color = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];for (const [a, b] of [[0, 1],[1, 2],[2, 0]]) {- drawLine(rgb2, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color2);+ drawLine(rgb, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color);}}}const regions = [...regionMap.values()].sort((a, b) => a.nodePath.localeCompare(b.nodePath));if (requestValue.buffer === "semantic-overlay") {for (const region of regions)- drawRegionBox(rgb2, size, region);+ drawRegionBox(rgb, size, region);}return {id: requestValue.id,@@ -22647,15 +22392,12 @@ function renderDiagnosticView(root, requestValue, options = {}) {...requestValue.variant ? { variant: requestValue.variant } : {},width: size,height: size,- rgb: rgb2,- png: encodePng(rgb2, size, size),+ rgb,+ png: encodePng(rgb, size, size),regions,...requestValue.phaseFractions ? { phaseFractions: requestValue.phaseFractions } : {}};}-function renderDiagnosticViews(root, requests, options = {}) {- return requests.map((viewRequest) => renderDiagnosticView(root, viewRequest, options));-}var GENERIC_DIAGNOSTIC_BUFFER_IDS, frozenCamera = (id, name, dir) => Object.freeze({ id, name, dir: Object.freeze([...dir]) }), GENERIC_DIAGNOSTIC_CAMERAS, EXTRA_CAMERAS, cameraById, request = (value) => Object.freeze({...value,...value.omitRolePrefixes ? { omitRolePrefixes: Object.freeze([...value.omitRolePrefixes]) } : {},@@ -22753,11 +22495,6 @@ var init_diagnostic = __esm(() => {});// src/views/camera-capture.ts-var exports_camera_capture = {};-__export(exports_camera_capture, {- validateAdvancedCapture: () => validateAdvancedCapture,- renderCaptureGrid: () => renderCaptureGrid-});function validateAdvancedCapture(config) {for (const key of Object.keys(config))if (!["version", "shots", "cols", "size", "output"].includes(key))@@ -22785,7 +22522,7 @@ async function renderCaptureGrid(root, config, render, limits) {for (const shot of shots) {const dir = shot.camera.position.map((n, i) => n - shot.camera.target[i]);const view = { name: shot.name, dir };- const png2 = await withCameraVisibility(root, shot, async () => {+ const png = await withCameraVisibility(root, shot, async () => {if (render) {const result = await render({ root, label: shot.name, view, size, camera: shot.camera });derivativeReceipts.push(result.receipt);@@ -22793,15 +22530,15 @@ async function renderCaptureGrid(root, config, render, limits) {}return encodePng(rasterizeCamera(root, shot.camera, size), size, size);});- const decoded = decodePng(png2);+ const decoded = decodePng(png);if (decoded.width !== size || decoded.height !== size)throw new Error("capture cell dimensions do not match request");annotateViewCell(decoded.rgb, size, view);cells.push(decoded.rgb);perFramePngs.push(encodePng(decoded.rgb, size, size));}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);- const png = encodePng(rgb2, width, height);+ const { rgb, width, height } = compositeCellGrid(cells, size, cols);+ const png = encodePng(rgb, width, height);enforceCaptureBytes(config.output === "separate" ? perFramePngs : [png], limits);return {png,@@ -22830,17 +22567,6 @@ var init_camera_capture = __esm(() => {});// src/views/capture.ts-var exports_capture = {};-__export(exports_capture, {- resolveGridCapture: () => resolveGridCapture,- resolveCapture: () => resolveCapture,- describeCapture: () => describeCapture,- captureCellLabel: () => captureCellLabel,- MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,- DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,- CaptureConfigError: () => CaptureConfigError,- CAPTURE_PRESETS: () => CAPTURE_PRESETS-});function captureCellLabel(azimuthDeg, elevationDeg) {const az = Math.round((azimuthDeg % 360 + 360) % 360);const el = Math.round(elevationDeg);@@ -22903,18 +22629,11 @@ function resolveCapture(config) {};}function resolveGridCapture(config, envVariant) {- const resolved2 = resolveCapture(config);+ const resolved = resolveCapture(config);if (config)- return resolved2;+ return resolved;const views = resolveGridViews(envVariant);- return views === resolved2.views ? resolved2 : { ...resolved2, views };-}-function describeCapture(resolved2) {- const angles = resolved2.views.map((v) => {- const { azimuthDeg, elevationDeg } = orbitAnglesOf(v.dir);- return `${v.name} (az ${azimuthDeg}, el ${elevationDeg})`;- }).join("; ");- return `${resolved2.preset} grid, ${resolved2.views.length} cell${resolved2.views.length === 1 ? "" : "s"}: ${angles}`;+ return views === resolved.views ? resolved : { ...resolved, views };}var CAPTURE_PRESETS, DEFAULT_CAPTURE_PRESET = "3x2", MAX_CAPTURE_CELLS = 9, PRESET_COLS, PRESET_CAPACITY, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW, PRESET_VIEWS, CaptureConfigError;var init_capture = __esm(() => {@@ -22988,9 +22707,9 @@ function minimalMatches(root, predicate) {}function selectArchitectureRoofNodes(root) {const candidate = root;- const semantic3 = minimalMatches(candidate, hasArchitectureRoofRole);- if (semantic3.length > 0)- return { mode: "semantic", nodes: semantic3 };+ const semantic = minimalMatches(candidate, hasArchitectureRoofRole);+ if (semantic.length > 0)+ return { mode: "semantic", nodes: semantic };const legacy = minimalMatches(candidate, (node) => legacyRoofName(node.name));return legacy.length > 0 ? { mode: "legacy-name", nodes: legacy } : { mode: "none", nodes: [] };}@@ -23123,20 +22842,20 @@ function flatMaterial(material) {};}const [r, g, b, factorAlpha] = material.getBaseColorFactor();- const alphaMode2 = material.getAlphaMode();- const opacity = alphaMode2 === "BLEND" ? factorAlpha : alphaMode2 === "MASK" && factorAlpha < material.getAlphaCutoff() ? 0 : 1;+ const alphaMode = material.getAlphaMode();+ const opacity = alphaMode === "BLEND" ? factorAlpha : alphaMode === "MASK" && factorAlpha < material.getAlphaCutoff() ? 0 : 1;return {color: { r, g, b },opacity,doubleSided: material.getDoubleSided(),metalness: material.getMetallicFactor(),roughness: material.getRoughnessFactor(),- alphaMode: alphaMode2,+ alphaMode,alphaCutoff: material.getAlphaCutoff(),emissive: material.getEmissiveFactor()};}-function preserveTexture(source, usage2, cache) {+function preserveTexture(source, usage, cache) {if (!source)return null;const encoded = source.getImage();@@ -23148,14 +22867,14 @@ function preserveTexture(source, usage2, cache) {byUsage = new Map;cache.set(source, byUsage);}- const existing = byUsage.get(usage2);+ const existing = byUsage.get(usage);if (existing)return existing;const texture = new Texture;texture.name = source.getName();- texture.colorSpace = usage2 === "color" ? SRGBColorSpace5 : NoColorSpace4;+ texture.colorSpace = usage === "color" ? SRGBColorSpace5 : NoColorSpace4;texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };- byUsage.set(usage2, texture);+ byUsage.set(usage, texture);return texture;}function noteMaterialTextures(material, reasons) {@@ -23191,13 +22910,13 @@ function instanceMatrices(node) {const scales = extension.getAttribute("SCALE");const translation = [];const rotation = [];- const scale2 = [];+ const scale = [];const matrices = [];for (let index = 0;index < count; index++) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);- scales?.getElement(index, scale2);- const local = new Matrix47().compose(new Vector326(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion14(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector326(scales ? scale2[0] : 1, scales ? scale2[1] : 1, scales ? scale2[2] : 1));+ scales?.getElement(index, scale);+ const local = new Matrix47().compose(new Vector326(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion14(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector326(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));matrices.push(world.clone().multiply(local));}return { matrices, count };@@ -23215,17 +22934,17 @@ async function loadGlbGeometryFlatScene(bytes) {const reasons = new Set;const meshes = [];let instanceCount = 0;- const sceneNodes2 = new Set;+ const sceneNodes = new Set;const visit = (node) => {- if (sceneNodes2.has(node))+ if (sceneNodes.has(node))return;- sceneNodes2.add(node);+ sceneNodes.add(node);for (const child of node.listChildren())visit(child);};for (const child of scene.listChildren())visit(child);- for (const node of sceneNodes2) {+ for (const node of sceneNodes) {const mesh = node.getMesh();if (!mesh)continue;@@ -23248,7 +22967,7 @@ async function loadGlbGeometryFlatScene(bytes) {}const material = primitive.getMaterial();noteMaterialTextures(material, reasons);- const geometry2 = {+ const geometry = {getAttribute(name) {return name === "position" ? { array: positions, itemSize: 3, count: positionAccessor.getCount() } : undefined;},@@ -23258,7 +22977,7 @@ async function loadGlbGeometryFlatScene(bytes) {meshes.push({isMesh: true,visible: true,- geometry: geometry2,+ geometry,material: flatMaterial(material),matrixWorld: { elements: [...matrix.elements] }});@@ -23299,12 +23018,12 @@ function localInstanceMatrices(node) {const scales = extension.getAttribute("SCALE");const translation = [];const rotation = [];- const scale2 = [];+ const scale = [];return Array.from({ length: count }, (_, index) => {translations?.getElement(index, translation);rotations?.getElement(index, rotation);- scales?.getElement(index, scale2);- return new Matrix47().compose(new Vector326(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion14(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector326(...scales ? scale2.slice(0, 3) : [1, 1, 1]));+ scales?.getElement(index, scale);+ return new Matrix47().compose(new Vector326(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion14(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector326(...scales ? scale.slice(0, 3) : [1, 1, 1]));});}async function loadGlbReviewScene(bytes) {@@ -23356,21 +23075,21 @@ async function loadGlbReviewScene(bytes) {const material = primitive.getMaterial();noteMaterialTextures(material, reasons);const flat = flatMaterial(material);- const geometry2 = new BufferGeometry14;- geometry2.setAttribute("position", new BufferAttribute8(Float32Array.from(decodedAccessor(position)), 3));+ const geometry = new BufferGeometry14;+ geometry.setAttribute("position", new BufferAttribute8(Float32Array.from(decodedAccessor(position)), 3));const normal = primitive.getAttribute("NORMAL");if (normal) {- geometry2.setAttribute("normal", new BufferAttribute8(Float32Array.from(decodedAccessor(normal)), 3));+ geometry.setAttribute("normal", new BufferAttribute8(Float32Array.from(decodedAccessor(normal)), 3));}const uv = primitive.getAttribute("TEXCOORD_0");if (uv) {- geometry2.setAttribute("uv", new BufferAttribute8(Float32Array.from(decodedAccessor(uv)), 2));+ geometry.setAttribute("uv", new BufferAttribute8(Float32Array.from(decodedAccessor(uv)), 2));}const tangent = primitive.getAttribute("TANGENT");if (tangent) {- geometry2.setAttribute("tangent", new BufferAttribute8(Float32Array.from(decodedAccessor(tangent)), 4));+ geometry.setAttribute("tangent", new BufferAttribute8(Float32Array.from(decodedAccessor(tangent)), 4));}- geometry2.setIndex(new BufferAttribute8(indices, 1));+ geometry.setIndex(new BufferAttribute8(indices, 1));const threeMaterial = new MeshStandardMaterial5({opacity: flat.opacity,transparent: flat.alphaMode === "BLEND",@@ -23393,7 +23112,7 @@ async function loadGlbReviewScene(bytes) {threeMaterial.aoMapIntensity = material.getOcclusionStrength();}for (const [index, matrix] of matrices.entries()) {- const mesh = new Mesh10(geometry2, threeMaterial);+ const mesh = new Mesh10(geometry, threeMaterial);const baseName = source.getName() || sourceMesh.getName() || "Mesh";mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;mesh.matrixAutoUpdate = false;@@ -23474,178 +23193,7 @@ var init_handler = __esm(() => {});// src/evaluator/subprocess.ts-var exports_subprocess = {};-__export(exports_subprocess, {- sanitizedEvaluatorEnv: () => sanitizedEvaluatorEnv,- renderGLBViaSubprocess: () => renderGLBViaSubprocess,- renderGLBViaProcessLaunch: () => renderGLBViaProcessLaunch,- EvaluatorSubprocessError: () => EvaluatorSubprocessError-});-import { spawn } from "node:child_process";-import { fileURLToPath } from "node:url";-function sanitizedEvaluatorEnv(source = process.env) {- const env = { NODE_ENV: "production", NO_COLOR: "1" };- for (const key of ["PATH", "Path", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TZ"]) {- if (source[key] !== undefined)- env[key] = source[key];- }- return env;-}-function boundedInteger(value, fallback, max) {- const resolved2 = value ?? fallback;- if (!Number.isInteger(resolved2) || resolved2 < 1 || resolved2 > max) {- throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator controls are invalid.");- }- return resolved2;-}-function terminateProcess(child, detached) {- if (!child.pid || child.killed)- return;- try {- if (detached && process.platform !== "win32")- process.kill(-child.pid, "SIGKILL");- else- child.kill("SIGKILL");- } catch (error) {- if (error.code !== "ESRCH")- throw error;- }-}-async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launch) {- if (controls.signal?.aborted) {- throw new EvaluatorSubprocessError("CANCELLED", "Evaluator request was cancelled.");- }- if (options.textureResolver) {- throw new EvaluatorSubprocessError("INPUT_INVALID", "Subprocess evaluation does not accept host resolver capabilities.");- }- const deadlineMs = boundedInteger(controls.deadlineMs, DEFAULT_DEADLINE_MS, 120000);- const maxGlbBytes = boundedInteger(controls.maxGlbBytes, DEFAULT_MAX_GLB_BYTES, 64 * 1024 * 1024);- const maxResponseBytes = boundedInteger(controls.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);- const request2 = {- version: EVALUATOR_REQUEST_VERSION,- requestId: "render-1",- operation: "execute-export-glb",- code,- options,- limits: { maxGlbBytes }- };- const requestJson = JSON.stringify(request2);- if (Buffer.byteLength(requestJson, "utf8") > MAX_EVALUATOR_REQUEST_BYTES) {- throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator request exceeds its size limit.");- }- const sourceModule = import.meta.url.endsWith(".ts");- const workerPath = fileURLToPath(new URL(process.versions.bun && sourceModule ? "./worker.ts" : sourceModule ? "../../dist/evaluator-worker.mjs" : "./evaluator-worker.mjs", import.meta.url));- const maxHeapMb = boundedInteger(controls.maxHeapMb, 512, 4096);- if (maxHeapMb < 64 || process.versions.bun && controls.maxHeapMb !== undefined) {- throw new EvaluatorSubprocessError("INPUT_INVALID", "Heap limits require a Node worker and 64–4096 MiB.");- }- const defaultLaunch = {- command: process.execPath,- args: process.versions.bun ? [workerPath] : [`--max-old-space-size=${maxHeapMb}`, workerPath],- env: sanitizedEvaluatorEnv()- };- const resolvedLaunch = launch ?? defaultLaunch;- const detached = resolvedLaunch.detached === true;- return await new Promise((resolve, reject) => {- const spawnOptions = {- env: resolvedLaunch.env,- windowsHide: true,- stdio: ["pipe", "ignore", "pipe", "pipe"],- ...detached ? { detached: true } : {}- };- const child = spawn(resolvedLaunch.command, resolvedLaunch.args, spawnOptions);- const protocol = child.stdio[3];- if (!protocol) {- terminateProcess(child, detached);- reject(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker did not start."));- return;- }- const chunks = [];- let responseBytes = 0;- let stderrBytes = 0;- let settled = false;- const finish = (error, result) => {- if (settled)- return;- settled = true;- clearTimeout(timer);- controls.signal?.removeEventListener("abort", abort);- if (error)- reject(error);- else- resolve(result);- };- const timer = setTimeout(() => {- finish(new EvaluatorSubprocessError("DEADLINE_EXCEEDED", "Evaluator deadline exceeded."));- terminateProcess(child, detached);- }, deadlineMs);- const abort = () => {- finish(new EvaluatorSubprocessError("CANCELLED", "Evaluator request was cancelled."));- terminateProcess(child, detached);- };- const pipeFailed = (error) => {- if (settled)- return;- if (["EPIPE", "ECONNRESET", "ERR_STREAM_DESTROYED", "ERR_STREAM_PREMATURE_CLOSE"].includes(error.code ?? ""))- return;- finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker pipe failed."));- terminateProcess(child, detached);- };- child.stdin?.on("error", pipeFailed);- protocol.on("error", (error) => {- if (process.platform === "win32" && process.versions.bun && error.code === "EBADF")- return;- pipeFailed(error);- });- child.stderr?.on("error", pipeFailed);- controls.signal?.addEventListener("abort", abort, { once: true });- if (controls.signal?.aborted)- abort();- protocol.on("data", (chunk2) => {- responseBytes += chunk2.byteLength;- if (responseBytes > maxResponseBytes) {- finish(new EvaluatorSubprocessError("OUTPUT_LIMIT_EXCEEDED", "Evaluator output limit exceeded."));- terminateProcess(child, detached);- return;- }- chunks.push(Buffer.from(chunk2));- });- child.stderr?.on("data", (chunk2) => {- stderrBytes = Math.min(MAX_STDERR_BYTES, stderrBytes + chunk2.byteLength);- });- child.on("error", () => {- finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker failed to start."));- });- child.on("close", (exitCode) => {- if (settled)- return;- if (exitCode !== 0 || chunks.length === 0) {- finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker failed."));- return;- }- try {- const result = decodeEvaluatorResultV1(Buffer.concat(chunks).toString("utf8"), maxGlbBytes);- if (!result.ok) {- if (result.error.code === "QA_BLOCKED" && result.error.qa) {- finish(new AssetQaBlockedError(result.error.qa.report, result.error.qa.stage, result.error.qa.gltfValidation));- return;- }- finish(new EvaluatorSubprocessError(result.error.code, evaluatorOutcomeMessage(result.error.code), result.error.diagnostic));- return;- }- finish(undefined, result.render);- } catch {- finish(new EvaluatorSubprocessError("PROTOCOL_ERROR", "Evaluator returned invalid data."));- }- });- if (!settled)- child.stdin?.end(requestJson);- });-}-async function renderGLBViaSubprocess(code, options = {}, controls = {}) {- return renderGLBViaProcessLaunch(code, options, controls);-}-var DEFAULT_DEADLINE_MS = 60000, DEFAULT_MAX_GLB_BYTES, DEFAULT_MAX_RESPONSE_BYTES, MAX_STDERR_BYTES, EvaluatorSubprocessError;+var DEFAULT_MAX_GLB_BYTES, DEFAULT_MAX_RESPONSE_BYTES, MAX_STDERR_BYTES;var init_subprocess = __esm(() => {init_authoring_diagnostic();init_run();@@ -23653,353 +23201,13 @@ var init_subprocess = __esm(() => {DEFAULT_MAX_GLB_BYTES = 16 * 1024 * 1024;DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;MAX_STDERR_BYTES = 16 * 1024;- EvaluatorSubprocessError = class EvaluatorSubprocessError extends Error {- diagnostic;- code;- constructor(code, message, diagnostic) {- super(diagnostic ? `${message} ${authoringDiagnosticAdvice(diagnostic)}` : message);- this.diagnostic = diagnostic;- this.name = "EvaluatorSubprocessError";- this.code = code;- }- };});// src/evaluator/isolation.ts-var exports_isolation = {};-__export(exports_isolation, {- renderGLBViaIsolatedEvaluator: () => renderGLBViaIsolatedEvaluator,- isolationReadinessFailureCode: () => isolationReadinessFailureCode,- isolatedEvaluatorLaunch: () => isolatedEvaluatorLaunch,- decodeEvaluatorIsolationTransport: () => decodeEvaluatorIsolationTransport,- decodeEvaluatorIsolationReadiness: () => decodeEvaluatorIsolationReadiness,- assertIsolatedEvaluatorReady: () => assertIsolatedEvaluatorReady,- EvaluatorIsolationReadinessError: () => EvaluatorIsolationReadinessError-});-import { spawn as spawn2 } from "node:child_process";-import { existsSync } from "node:fs";-import { posix } from "node:path";-import { fileURLToPath as fileURLToPath2 } from "node:url";-function isolationReadinessFailureCode(error) {- if (!(error instanceof EvaluatorIsolationReadinessError))- return;- return READINESS_FAILURE_CODES.includes(error.readinessCode) ? error.readinessCode : undefined;-}-function isolationUnavailable() {- throw new EvaluatorSubprocessError("ISOLATION_UNAVAILABLE", "Isolated evaluator is unavailable.");-}-function requiredAbsolutePath(value) {- if (!posix.isAbsolute(value) || posix.normalize(value) !== value)- isolationUnavailable();- return value;-}-function requiredRuntimeRoot(value) {- const root = requiredAbsolutePath(value);- if (root !== DEFAULT_RUNTIME_ROOT)- isolationUnavailable();- return root;-}-function workerInsideRuntime(workerPath, runtimeRoot) {- const normalized = requiredAbsolutePath(workerPath);- const packageRoot = posix.join(runtimeRoot, "node_modules") + posix.sep;- if (!normalized.startsWith(packageRoot))- isolationUnavailable();- return normalized;-}-function runtimeMounts(runtimeRoot, pathExists) {- const mounts = ["/usr", "/lib", "/lib64", posix.join(runtimeRoot, "node_modules")];- const existing = mounts.filter((path) => pathExists(path));- if (!existing.includes("/usr") || !existing.includes(posix.join(runtimeRoot, "node_modules"))) {- isolationUnavailable();- }- return existing;-}-function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx") {- const platform = host.platform ?? process.platform;- if (platform !== "linux")- isolationUnavailable();- const runtimeRoot = requiredRuntimeRoot(host.runtimeRoot ?? DEFAULT_RUNTIME_ROOT);- const pathExists = host.pathExists ?? existsSync;- const bwrapPath = requiredAbsolutePath(host.bwrapPath ?? DEFAULT_BWRAP_PATH);- const setprivPath = requiredAbsolutePath(host.setprivPath ?? DEFAULT_SETPRIV_PATH);- const prlimitPath = requiredAbsolutePath(host.prlimitPath ?? DEFAULT_PRLIMIT_PATH);- const nodePath5 = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);- for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath5]) {- if (!pathExists(executable))- isolationUnavailable();- }- const resolvedWorkerPath = workerInsideRuntime(workerPath, runtimeRoot);- if (!pathExists(resolvedWorkerPath))- isolationUnavailable();- const bwrapArgs = [- "--unshare-all",- "--die-with-parent",- "--new-session",- "--disable-userns",- "--cap-drop",- "ALL",- "--clearenv",- "--setenv",- "NODE_ENV",- "production",- "--setenv",- "NO_COLOR",- "1",- "--proc",- "/proc",- "--dev",- "/dev",- "--tmpfs",- "/tmp",- "--dir",- runtimeRoot,- "--dir",- posix.join(runtimeRoot, "node_modules")- ];- for (const mount of runtimeMounts(runtimeRoot, pathExists)) {- bwrapArgs.push("--ro-bind", mount, mount);- }- const nodeArgs = [nodePath5, "--max-old-space-size=512", "--disable-proto=throw"];- if (loader === "tsx")- nodeArgs.push("--import", "tsx");- nodeArgs.push(resolvedWorkerPath);- bwrapArgs.push("--chdir", runtimeRoot, "--preserve-fds", "1", "--", prlimitPath, "--cpu=65:65", "--as=6442450944:6442450944", "--fsize=100663296:100663296", "--nofile=64:64", "--nproc=64:64", "--", ...nodeArgs);- return {- command: setprivPath,- args: [- "--no-new-privs",- "--inh-caps=-all",- "--ambient-caps=-all",- "--",- bwrapPath,- ...bwrapArgs- ],- env: sanitizedEvaluatorEnv({}),- detached: true- };-}-function isolatedEvaluatorLaunch(workerPath, host = {}) {- return isolatedEvaluatorLaunchWithLoader(workerPath, host, "tsx");-}-async function renderGLBViaIsolatedEvaluator(code, options = {}, controls = {}) {- const workerPath = fileURLToPath2(new URL("./worker.ts", import.meta.url));- const launch = isolatedEvaluatorLaunch(workerPath, controls.host);- const { host: _, ...processControls } = controls;- return renderGLBViaProcessLaunch(code, options, processControls, launch);-}-function decodeEvaluatorIsolationReadiness(value) {- if (typeof value !== "object" || value === null || Array.isArray(value))- isolationUnavailable();- const record5 = value;- if (Object.keys(record5).sort().join(",") === "failure,mode,version" && record5.version === READINESS_VERSION && record5.mode === "isolated" && [- "loader-probe-boot",- "invariant-namespace",- "invariant-environment",- "invariant-filesystem",- "invariant-network",- "invariant-generated-policy"- ].includes(String(record5.failure))) {- return record5;- }- if (Object.keys(record5).sort().join(",") !== "checks,mode,version" || record5.version !== READINESS_VERSION || record5.mode !== "isolated" || !Array.isArray(record5.checks) || record5.checks.length !== READINESS_CHECKS.length || record5.checks.join(",") !== READINESS_CHECKS.join(",")) {- isolationUnavailable();- }- return record5;-}-function decodeEvaluatorIsolationTransport(value) {- if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).sort().join(",") !== "transport,version") {- isolationUnavailable();- }- const record5 = value;- if (record5.version !== TRANSPORT_VERSION || record5.transport !== "fd3")- isolationUnavailable();- return record5;-}-function terminateReadinessChild(child) {- try {- if (child.pid)- process.kill(-child.pid, "SIGKILL");- } catch {}-}-async function assertIsolationTransport(launch) {- return await new Promise((resolve, reject) => {- const child = spawn2(launch.command, launch.args, {- env: launch.env,- windowsHide: true,- detached: true,- stdio: ["ignore", "pipe", "ignore", "pipe"]- });- const stdoutChunks = [];- const protocolChunks = [];- let stdoutBytes = 0;- let protocolBytes = 0;- let settled = false;- const fail = (readinessCode) => {- if (settled)- return;- settled = true;- clearTimeout(timer);- reject(new EvaluatorIsolationReadinessError(readinessCode));- };- const timer = setTimeout(() => {- terminateReadinessChild(child);- fail("deadline");- }, PROBE_DEADLINE_MS);- child.stdout?.on("data", (chunk2) => {- stdoutBytes += chunk2.byteLength;- if (stdoutBytes > MAX_TRANSPORT_STDOUT_BYTES) {- terminateReadinessChild(child);- fail("wrapper-launch");- return;- }- stdoutChunks.push(Buffer.from(chunk2));- });- const protocol = child.stdio[3];- if (!protocol) {- terminateReadinessChild(child);- fail("fd3-transport");- return;- }- protocol.on("data", (chunk2) => {- protocolBytes += chunk2.byteLength;- if (protocolBytes > MAX_READINESS_PROTOCOL_BYTES) {- terminateReadinessChild(child);- fail("fd3-transport");- return;- }- protocolChunks.push(Buffer.from(chunk2));- });- child.once("error", () => fail("wrapper-launch"));- child.once("close", (code) => {- if (settled)- return;- const stdout = Buffer.concat(stdoutChunks).toString("utf8");- if (stdout !== TRANSPORT_STDOUT_MARKER)- return fail("wrapper-launch");- if (code !== 0 || protocolChunks.length === 0)- return fail("fd3-transport");- try {- decodeEvaluatorIsolationTransport(JSON.parse(Buffer.concat(protocolChunks).toString("utf8")));- settled = true;- clearTimeout(timer);- resolve();- } catch {- fail("fd3-transport");- }- });- });-}-async function runIsolationProbe(launch) {- return await new Promise((resolve, reject) => {- const child = spawn2(launch.command, launch.args, {- env: launch.env,- windowsHide: true,- detached: true,- stdio: ["ignore", "ignore", "ignore", "pipe"]- });- const protocol = child.stdio[3];- const chunks = [];- let bytes = 0;- let settled = false;- const fail = (readinessCode) => {- if (settled)- return;- settled = true;- clearTimeout(timer);- reject(new EvaluatorIsolationReadinessError(readinessCode));- };- const timer = setTimeout(() => {- terminateReadinessChild(child);- fail("deadline");- }, PROBE_DEADLINE_MS);- if (!protocol) {- terminateReadinessChild(child);- fail("fd3-transport");- return;- }- protocol.on("data", (chunk2) => {- bytes += chunk2.byteLength;- if (bytes > MAX_READINESS_PROTOCOL_BYTES) {- terminateReadinessChild(child);- fail("loader-probe-boot");- return;- }- chunks.push(Buffer.from(chunk2));- });- child.once("error", () => fail("wrapper-launch"));- child.once("close", (code) => {- if (settled)- return;- if (chunks.length === 0)- return fail("loader-probe-boot");- try {- const result = decodeEvaluatorIsolationReadiness(JSON.parse(Buffer.concat(chunks).toString("utf8")));- if ("failure" in result)- return fail(result.failure);- if (code !== 0)- return fail("loader-probe-boot");- settled = true;- clearTimeout(timer);- resolve(result);- } catch {- fail("loader-probe-boot");- }- });- });-}-async function assertIsolatedEvaluatorReady(host = {}) {- if (typeof process.getuid !== "function" || process.getuid() === 0) {- throw new EvaluatorIsolationReadinessError("invariant-namespace");- }- const transportPath = fileURLToPath2(new URL("./transport-worker.mjs", import.meta.url));- const probePath = fileURLToPath2(new URL("./probe-worker.ts", import.meta.url));- let transportLaunch;- let probeLaunch;- try {- transportLaunch = isolatedEvaluatorLaunchWithLoader(transportPath, host, "module");- probeLaunch = isolatedEvaluatorLaunch(probePath, host);- } catch {- throw new EvaluatorIsolationReadinessError("wrapper-launch");- }- await assertIsolationTransport(transportLaunch);- return await runIsolationProbe(probeLaunch);-}-var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", READINESS_VERSION = "kiln.evaluator.isolation-readiness.v1", TRANSPORT_VERSION = "kiln.evaluator.isolation-transport.v1", TRANSPORT_STDOUT_MARKER = `kiln-evaluator-transport-boot-v1-`, PROBE_DEADLINE_MS = 8000, MAX_READINESS_PROTOCOL_BYTES, MAX_TRANSPORT_STDOUT_BYTES = 256, READINESS_FAILURE_CODES, READINESS_CHECKS, EvaluatorIsolationReadinessError;+var MAX_READINESS_PROTOCOL_BYTES;var init_isolation = __esm(() => {init_subprocess();MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;- READINESS_FAILURE_CODES = [- "wrapper-launch",- "fd3-transport",- "loader-probe-boot",- "invariant-namespace",- "invariant-environment",- "invariant-filesystem",- "invariant-network",- "invariant-generated-policy",- "deadline"- ];- READINESS_CHECKS = [- "user-namespace",- "no-new-privileges",- "capabilities-empty",- "environment-exact",- "product-filesystem-denied",- "host-filesystem-denied",- "runtime-filesystem-read-only",- "network-namespace-empty",- "metadata-and-local-network-denied",- "generated-capabilities-denied"- ];- EvaluatorIsolationReadinessError = class EvaluatorIsolationReadinessError extends EvaluatorSubprocessError {- readinessCode;- constructor(readinessCode) {- super("ISOLATION_UNAVAILABLE", "Isolated evaluator readiness check failed.");- this.name = "EvaluatorIsolationReadinessError";- this.readinessCode = readinessCode;- }- };});// src/evaluator/index.ts@@ -24011,10 +23219,6 @@ var init_evaluator = __esm(() => {});// src/views/renderer-id.ts-var exports_renderer_id = {};-__export(exports_renderer_id, {- CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID-});import { readFileSync } from "node:fs";function engineVersion() {for (const path of ["../package.json", "../../package.json"]) {@@ -24035,66 +23239,13 @@ var init_renderer_id = __esm(() => {// src/views/scene-raster.tsimport * as THREE31 from "three";-async function rasterizeComposedScene(parts, opts = {}) {- const views = opts.views?.length ? opts.views : SCENE_VIEWS;- const size = opts.size ?? 320;- const group = new THREE31.Group;- const baseByInput = new Map;- for (const part of parts) {- if (part.code === undefined === (part.glb === undefined)) {- throw new TypeError("Composed part must provide exactly one of code or glb.");- }- const key = part.glb ?? part.code;- let base = baseByInput.get(key);- if (!base) {- const glb = part.glb ? Uint8Array.from(part.glb) : (await resolveEvaluatorPortV1(opts.evaluatorPort, opts.evaluatorProfile ?? "trusted-local").render(part.code)).glb;- base = (await loadGlbReviewScene(glb)).root;- baseByInput.set(key, base);- }- const inst = base.clone(true);- inst.position.set(part.pos[0], part.pos[1], part.pos[2]);- inst.rotation.set(0, part.rotYDeg * DEG2, 0);- inst.scale.setScalar(part.scale);- group.add(inst);- }- group.updateMatrixWorld(true);- const cols = Math.min(Math.max(views.length, 1), 3);- const rows = Math.ceil(views.length / cols);- const width = cols * size + (cols + 1) * PAD2;- const height = rows * size + (rows + 1) * PAD2;- const grid = new Uint8Array(width * height * 3);- for (let i = 0;i < width * height; i++) {- grid[i * 3] = PAD_COLOR2[0];- grid[i * 3 + 1] = PAD_COLOR2[1];- grid[i * 3 + 2] = PAD_COLOR2[2];- }- for (let vi = 0;vi < views.length; vi++) {- const cell = rasterizeView(group, views[vi].dir, { size });- const col = vi % cols;- const row = Math.floor(vi / cols);- const x0 = PAD2 + col * (size + PAD2);- const y0 = PAD2 + row * (size + PAD2);- for (let y = 0;y < size; y++) {- const src = y * size * 3;- const dst = ((y0 + y) * width + x0) * 3;- grid.set(cell.subarray(src, src + size * 3), dst);- }- }- return { png: encodePng(grid, width, height), width, height, views: views.map((v) => v.name) };-}-var DEG2, PAD2 = 4, PAD_COLOR2, SCENE_VIEWS;+var DEG2;var init_scene_raster = __esm(() => {init_evaluator();init_glb();init_png();init_raster();DEG2 = Math.PI / 180;- PAD_COLOR2 = [10, 11, 13];- SCENE_VIEWS = [- { name: "Hero 3/4", dir: [0.7, 0.45, 0.7] },- { name: "Reverse 3/4", dir: [-0.7, 0.45, -0.7] },- { name: "Top", dir: [0, 1, 0.0001] }- ];});// src/views/vehicle.ts@@ -24118,8 +23269,8 @@ function chassisBounds(root, inverse) {const matrix = inverse.clone().multiply(part.matrixWorld);for (const x of [box.min.x, box.max.x])for (const y of [box.min.y, box.max.y])- for (const z3 of [box.min.z, box.max.z]) {- bounds.expandByPoint(new THREE32.Vector3(x, y, z3).applyMatrix4(matrix));+ for (const z of [box.min.z, box.max.z]) {+ bounds.expandByPoint(new THREE32.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -24132,10 +23283,10 @@ function describeVehicleDiagnostics(root) {const assemblies = resolveVehicleWheelAssemblies(root);const wheels = assemblies.map((wheel) => ({id: wheel.id,- center: tuple7(wheel.centerWorld.clone().applyMatrix4(inverse)),+ center: tuple6(wheel.centerWorld.clone().applyMatrix4(inverse)),radius: wheel.radius ?? 0,width: wheel.width ?? 0,- axle: tuple7(wheel.spinAxisWorld.clone().transformDirection(inverse)),+ axle: tuple6(wheel.spinAxisWorld.clone().transformDirection(inverse)),loadBearing: wheel.loadBearing}));const byAxle = new Map;@@ -24176,7 +23327,7 @@ function describeVehicleDiagnostics(root) {return {schemaVersion: 1,forwardArrow: { start: [0, 0, 0], end: [1, 0, 0] },- ...chassis ? { chassisBox: { min: tuple7(chassis.min), max: tuple7(chassis.max) } } : {},+ ...chassis ? { chassisBox: { min: tuple6(chassis.min), max: tuple6(chassis.max) } } : {},axles,wheels,...supportPlaneY !== undefined ? { supportPlaneY } : {},@@ -24186,41 +23337,41 @@ function describeVehicleDiagnostics(root) {function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}-function rod(name, start, end, radius, color2, role) {+function rod(name, start, end, radius, color, role) {const from = new THREE32.Vector3(...start);const to = new THREE32.Vector3(...end);const direction = to.clone().sub(from);- const length3 = direction.length();- const geometry2 = length3 > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length3, 8) : new THREE32.SphereGeometry(radius, 8, 6);- const result = new THREE32.Mesh(geometry2, new THREE32.MeshBasicMaterial({ color: color2 }));+ const length = direction.length();+ const geometry = length > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length, 8) : new THREE32.SphereGeometry(radius, 8, 6);+ const result = new THREE32.Mesh(geometry, new THREE32.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);- if (length3 > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length3));+ if (length > 0.000000001) {+ result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}-function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagnostics(root)) {+function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {const overlay = new THREE32.Group;overlay.name = "VehicleDiagnosticOverlay";- const chassisSpan = descriptor2.chassisBox ? Math.max(descriptor2.chassisBox.max[0] - descriptor2.chassisBox.min[0], descriptor2.chassisBox.max[1] - descriptor2.chassisBox.min[1], descriptor2.chassisBox.max[2] - descriptor2.chassisBox.min[2]) : 1;+ const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;const thickness = Math.max(0.01, chassisSpan * 0.008);const arrow = new THREE32.Group;arrow.name = "Diagnostic_Forward_+X";tagDiagnostic(arrow, "diagnostic.vehicle.forward");- arrow.add(rod("Diagnostic_Forward_Shaft", descriptor2.forwardArrow.start, [descriptor2.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));+ arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";- arrowHead.position.set(descriptor2.forwardArrow.end[0] - 0.12, 0, 0);+ arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);- for (const axle of descriptor2.axles) {+ for (const axle of descriptor.axles) {overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));}- for (const wheel of descriptor2.wheels) {+ for (const wheel of descriptor.wheels) {const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);@@ -24231,11 +23382,11 @@ function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagntagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}- if (descriptor2.chassisBox) {+ if (descriptor.chassisBox) {const chassis = new THREE32.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");- const { min, max } = descriptor2.chassisBox;+ const { min, max } = descriptor.chassisBox;const corners = [[min[0], min[1], min[2]],[max[0], min[1], min[2]],@@ -24265,13 +23416,13 @@ function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagn}overlay.add(chassis);}- if (descriptor2.supportPlaneY !== undefined) {+ if (descriptor.supportPlaneY !== undefined) {const plane = new THREE32.Group;plane.name = "Diagnostic_SupportPlane";tagDiagnostic(plane, "diagnostic.vehicle.support-plane");- const halfX = Math.max(1, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[0]), Math.abs(descriptor2.chassisBox.max[0])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;- const halfZ = Math.max(0.8, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[2]), Math.abs(descriptor2.chassisBox.max[2])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;- const y = descriptor2.supportPlaneY;+ const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;+ const halfZ = Math.max(0.8, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[2]), Math.abs(descriptor.chassisBox.max[2])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;+ const y = descriptor.supportPlaneY;const planeLines = [[[-halfX, y, -halfZ],@@ -24324,8 +23475,8 @@ function compositeForCapture(root, overlay) {children: [root, overlay]};}-function selectWheelSectionRequest(requestValue, descriptor2) {- const target = descriptor2.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor2.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor2.wheels[0];+function selectWheelSectionRequest(requestValue, descriptor) {+ const target = descriptor.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor.wheels[0];if (!target?.id.startsWith("wheel.assembly."))return requestValue;const suffix = target.id.replace(/[^a-zA-Z0-9.-]/g, "-");@@ -24339,12 +23490,12 @@ function selectWheelSectionRequest(requestValue, descriptor2) {function captureVehicleDiagnosticViews(root, intent, size = 256) {if (intent.category !== "vehicle")return [];- const descriptor2 = describeVehicleDiagnostics(root);- const overlay = createVehicleDiagnosticOverlay(root, descriptor2);+ const descriptor = describeVehicleDiagnostics(root);+ const overlay = createVehicleDiagnosticOverlay(root, descriptor);const composite = compositeForCapture(root, overlay);const requests = planDiagnosticViews(intent).extra.filter((value) => value.variant === "vehicle-underbody" || value.variant === "vehicle-wheel-section");return requests.map((baseRequest) => {- const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor2) : baseRequest;+ const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor) : baseRequest;const frame = renderDiagnosticView(composite, requestValue, { size });return {id: frame.id,@@ -24356,11 +23507,11 @@ function captureVehicleDiagnosticViews(root, intent, size = 256) {height: frame.height,png: frame.png,regions: frame.regions,- descriptor: descriptor2+ descriptor};});}-var tuple7 = (value) => [value.x, value.y, value.z];+var tuple6 = (value) => [value.x, value.y, value.z];var init_vehicle3 = __esm(() => {init_contracts();init_vehicle();@@ -24370,93 +23521,24 @@ var init_vehicle3 = __esm(() => {// src/views/index.tsvar exports_views = {};__export(exports_views, {- withCameraVisibility: () => withCameraVisibility,- validateResolvedAssetCamera: () => validateResolvedAssetCamera,- validateAdvancedCapture: () => validateAdvancedCapture,- stampAxisGnomon: () => stampAxisGnomon,- snapSceneToPalette: () => snapSceneToPalette,- selectCameraSubject: () => selectCameraSubject,- selectArchitectureRoofNodes: () => selectArchitectureRoofNodes,- resolveGridViews: () => resolveGridViews,- resolveGridCapture: () => resolveGridCapture,- resolveCaptureLimits: () => resolveCaptureLimits,- resolveCapture: () => resolveCapture,- resolveAssetCamera: () => resolveAssetCamera,- renderViewGrid: () => renderViewGrid,- renderInteriorGrid: () => renderInteriorGrid,- renderGlbViewGrid: () => renderGlbViewGrid,- renderGlbViewCell: () => renderGlbViewCell,- renderDiagnosticViews: () => renderDiagnosticViews,- renderDiagnosticView: () => renderDiagnosticView,- renderCodeViewGrid: () => renderCodeViewGrid,- renderClipAnimation: () => renderClipAnimation,- renderCaptureGrid: () => renderCaptureGrid,- rasterizeView: () => rasterizeView,- rasterizeComposedScene: () => rasterizeComposedScene,- rasterizeCamera: () => rasterizeCamera,- prepareClip: () => prepareClip,- poseSceneAtTime: () => poseSceneAtTime,- planFrameTimes: () => planFrameTimes,- planDiagnosticViews: () => planDiagnosticViews,- planCharacterDiagnosticRequests: () => planCharacterDiagnosticRequests,- orbitDir: () => orbitDir,- orbitAnglesOf: () => orbitAnglesOf,- measureBounds: () => measureBounds,- loadGlbReviewScene: () => loadGlbReviewScene,- loadGlbGeometryFlatScene: () => loadGlbGeometryFlatScene,- listCameraSubjects: () => listCameraSubjects,- hideNodeInScene: () => hideNodeInScene,- hideArchitectureRoofInScene: () => hideArchitectureRoofInScene,- hasArchitectureRoofRole: () => hasArchitectureRoofRole,- geometryFlatTextureReasonCode: () => geometryFlatTextureReasonCode,- findClip: () => findClip,- encodePng: () => encodePng,- describeVehicleDiagnostics: () => describeVehicleDiagnostics,- describeCapture: () => describeCapture,- decodePng: () => decodePng,- createVehicleDiagnosticOverlay: () => createVehicleDiagnosticOverlay,- createCachedRenderPort: () => createCachedRenderPort,- coverage: () => coverage,- compositeViewPngGrid: () => compositeViewPngGrid,- compositeCellGrid: () => compositeCellGrid,- clipNames: () => clipNames,- captureVehicleDiagnosticViews: () => captureVehicleDiagnosticViews,- captureCpuCell: () => captureCpuCell,- captureCellLabel: () => captureCellLabel,- cameraFromBounds: () => cameraFromBounds,- buildCharacterDiagnosticDescriptor: () => buildCharacterDiagnosticDescriptor,- annotateViewCell: () => annotateViewCell,- ViewEvidenceHistoryStore: () => ViewEvidenceHistoryStore,- SIX_VIEWS_REAR_QUARTER: () => SIX_VIEWS_REAR_QUARTER,- SIX_VIEWS: () => SIX_VIEWS,- SCENE_VIEWS: () => SCENE_VIEWS,- MemoryCaptureCache: () => MemoryCaptureCache,- MIN_ELEVATION_DEG: () => MIN_ELEVATION_DEG,- MAX_ELEVATION_DEG: () => MAX_ELEVATION_DEG,- MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,- INTERIOR_VIEWS: () => INTERIOR_VIEWS,- GlbGeometryFlatError: () => GlbGeometryFlatError,- GRID_COLS: () => GRID_COLS,- GRID_BACKGROUND_RGB: () => GRID_BACKGROUND_RGB,- GRID_BACKGROUND_HEX: () => GRID_BACKGROUND_HEX,- GLB_GEOMETRY_FLAT_REASON: () => GLB_GEOMETRY_FLAT_REASON,- GENERIC_DIAGNOSTIC_REQUESTS: () => GENERIC_DIAGNOSTIC_REQUESTS,- GENERIC_DIAGNOSTIC_CAMERAS: () => GENERIC_DIAGNOSTIC_CAMERAS,- GENERIC_DIAGNOSTIC_BUFFER_IDS: () => GENERIC_DIAGNOSTIC_BUFFER_IDS,- DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,- DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS,- CaptureConfigError: () => CaptureConfigError,CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID,- CHARACTER_MOTION_DIAGNOSTIC_PHASES: () => CHARACTER_MOTION_DIAGNOSTIC_PHASES,- CAPTURE_PRESETS: () => CAPTURE_PRESETS,- ARCHITECTURE_ROOF_ROLE_PREFIXES: () => ARCHITECTURE_ROOF_ROLE_PREFIXES+ cameraFromBounds: () => cameraFromBounds,+ listCameraSubjects: () => listCameraSubjects,+ loadGlbReviewScene: () => loadGlbReviewScene,+ measureBounds: () => measureBounds,+ renderCaptureGrid: () => renderCaptureGrid,+ renderClipAnimation: () => renderClipAnimation,+ renderGlbViewCell: () => renderGlbViewCell,+ renderGlbViewGrid: () => renderGlbViewGrid,+ renderInteriorGrid: () => renderInteriorGrid,+ resolveGridCapture: () => resolveGridCapture});-function setLinearColor(color2, rgb2) {- if (!color2)+function setLinearColor(color, rgb) {+ if (!color)return;- color2.r = rgb2[0];- color2.g = rgb2[1];- color2.b = rgb2[2];+ color.r = rgb[0];+ color.g = rgb[1];+ color.b = rgb[2];}function snapMaterialToPalette(mat, slots, idx) {if (!mat.color)@@ -24477,8 +23559,8 @@ function snapMaterialToPalette(mat, slots, idx) {return false;const slot = slots[slotI];const kind = slot.kind ?? "opaque";- const rgb2 = hexToLinearRgb(slot.color);- setLinearColor(mat.color, rgb2);+ const rgb = hexToLinearRgb(slot.color);+ setLinearColor(mat.color, rgb);if (mat.metalness !== undefined)mat.metalness = slot.metalness ?? 0;if (mat.roughness !== undefined)@@ -24494,7 +23576,7 @@ function snapMaterialToPalette(mat, slots, idx) {}if (mat.emissive) {if (kind === "glow") {- setLinearColor(mat.emissive, rgb2);+ setLinearColor(mat.emissive, rgb);mat.emissiveIntensity = Math.max(mat.emissiveIntensity ?? 1, 1);} else {setLinearColor(mat.emissive, [0, 0, 0]);@@ -24531,19 +23613,19 @@ async function renderViewGrid(root, opts = {}) {if (opts.capture?.shots || opts.capture?.version)return renderCaptureGrid(root, opts.capture, undefined, opts.captureLimits);const size = opts.size ?? 384;- const resolved2 = resolveGridCapture(opts.capture, process.env["KILN_GRID_VARIANT"]);- const views = opts.views ?? resolved2.views;- const cols = opts.cols ?? resolved2.cols;+ const resolved = resolveGridCapture(opts.capture, process.env["KILN_GRID_VARIANT"]);+ const views = opts.views ?? resolved.views;+ const cols = opts.cols ?? resolved.cols;enforceCapturePixels(views.length, size, cols, opts.captureLimits);if (opts.snapPalette?.length)snapSceneToPalette(root, opts.snapPalette);- const wantsZoom = resolved2.zooms.some((z3) => z3 !== undefined);+ const wantsZoom = resolved.zooms.some((z) => z !== undefined);const sceneBounds = wantsZoom ? measureBounds(root) : undefined;const cache = opts.snapPalette?.length ? undefined : opts.captureCache;let reused = 0;const cells = [];for (let vi = 0;vi < views.length; vi++) {- const zoom = resolved2.zooms[vi];+ const zoom = resolved.zooms[vi];const rasterOptions = {size,backfaceCull: opts.backfaceCull,@@ -24552,11 +23634,11 @@ async function renderViewGrid(root, opts = {}) {};let cell;if (cache && opts.artifactGlbSha256) {- const { CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2 } = await Promise.resolve().then(() => (init_renderer_id(), exports_renderer_id));+ await Promise.resolve().then(() => init_renderer_id());const camera2 = cameraFromBounds(rasterOptions.frameBounds ?? measureBounds(root), views[vi].dir);const result = await captureCpuCell(cache, {artifactGlbSha256: opts.artifactGlbSha256,- rendererId: `${CPU_RASTER_RENDERER_ID2}/legacy-fit`,+ rendererId: `${CPU_RASTER_RENDERER_ID}/legacy-fit`,camera: camera2,size,backfaceCull: opts.backfaceCull ?? true@@ -24577,34 +23659,34 @@ async function renderViewGrid(root, opts = {}) {annotateViewCell(cell, size, views[vi]);cells.push(cell);}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);- const png = encodePng(rgb2, width, height);+ const { rgb, width, height } = compositeCellGrid(cells, size, cols);+ const png = encodePng(rgb, width, height);enforceCaptureBytes([png], opts.captureLimits);return {png,width,height,views: views.map((v) => v.name),- capture: { preset: resolved2.preset, cols, cells: views.length },+ capture: { preset: resolved.preset, cols, cells: views.length },...cache && opts.artifactGlbSha256 ? { captureCache: { hit: reused === views.length, reused, total: views.length } } : {}};}async function hashGlbViewInput(bytes) {const copy = Uint8Array.from(bytes);- const digest2 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));- return `sha256:${[...digest2].map((value) => value.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));+ return `sha256:${[...digest].map((value) => value.toString(16).padStart(2, "0")).join("")}`;}async function renderGlbViewCell(bytes, view, options = {}) {const exactBytes = Uint8Array.from(bytes);const loaded = await loadGlbGeometryFlatScene(exactBytes);const size = options.size ?? 256;- const rgb2 = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull) : rasterizeView(loaded.root, view.dir, {+ const rgb = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull) : rasterizeView(loaded.root, view.dir, {size,...options.backfaceCull !== undefined ? { backfaceCull: options.backfaceCull } : {},...options.frameBounds ? { frameBounds: options.frameBounds } : {}});return {- png: encodePng(rgb2, size, size),+ png: encodePng(rgb, size, size),width: size,height: size,inputGlbSha256: await hashGlbViewInput(exactBytes),@@ -24637,11 +23719,6 @@ function expandFrameBounds(b, factor) {}return { min, max };}-async function renderCodeViewGrid(code, opts = {}) {- const { evaluatorPort, evaluatorProfile, ...viewOptions } = opts;- const rendered = await resolveEvaluatorPortV1(evaluatorPort, evaluatorProfile ?? "trusted-local").render(code);- return renderGlbViewGrid(rendered.glb, viewOptions);-}function resolveCamera(name) {const key = (name ?? "right").trim().toLowerCase().replace(/[_\s]+/g, "-");return ANIM_CAMERAS[key] ?? ANIM_CAMERAS[ANIM_CAMERA_ALIASES[key] ?? ""] ?? ANIM_CAMERAS["right"];@@ -24761,8 +23838,8 @@ async function renderClipAnimation(root, clips, opts = {}) {pngs: cells.map((c) => encodePng(c, size, size))};}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size);- return { ...baseMeta, width, height, png: encodePng(rgb2, width, height) };+ const { rgb, width, height } = compositeCellGrid(cells, size);+ return { ...baseMeta, width, height, png: encodePng(rgb, width, height) };}function normalizeVec(v) {const len = Math.hypot(v[0], v[1], v[2]) || 1;@@ -24815,9 +23892,9 @@ async function renderInteriorGrid(root, opts = {}) {stampLabel(cell, size, size, labelScale, labelScale, view.name, labelScale);cells.push(cell);}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);+ const { rgb, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);return {- png: encodePng(rgb2, width, height),+ png: encodePng(rgb, width, height),width,height,views: INTERIOR_VIEWS.map((v) => v.name),@@ -24893,7 +23970,7 @@ var init_views = __esm(() => {// src/views/character-capture.tsimport * as THREE33 from "three";-function drawLine2(rgb2, width, height, from, to, color2) {+function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);const x1 = Math.round(to[0]);@@ -24906,9 +23983,9 @@ function drawLine2(rgb2, width, height, from, to, color2) {while (true) {if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {const offset = (y0 * width + x0) * 3;- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}if (x0 === x1 && y0 === y1)break;@@ -24923,9 +24000,9 @@ function drawLine2(rgb2, width, height, from, to, color2) {}}}-function drawCross(rgb2, width, height, point, color2, radius = 3) {- drawLine2(rgb2, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color2);- drawLine2(rgb2, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color2);+function drawCross(rgb, width, height, point, color, radius = 3) {+ drawLine2(rgb, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color);+ drawLine2(rgb, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color);}function projector(root, cameraId, size) {root.updateMatrixWorld(true);@@ -24933,48 +24010,48 @@ function projector(root, cameraId, size) {if (bounds.isEmpty())bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));const center = bounds.getCenter(new THREE33.Vector3);- const camera2 = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);+ const camera = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);const upHint = new THREE33.Vector3(0, 1, 0);- const xAxis = new THREE33.Vector3().crossVectors(upHint, camera2).normalize();- const yAxis = new THREE33.Vector3().crossVectors(camera2, xAxis).normalize();- let extent2 = 0.000001;+ const xAxis = new THREE33.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE33.Vector3().crossVectors(camera, xAxis).normalize();+ let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);- extent2 = Math.max(extent2, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));+ extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));}- const scale2 = size * 0.45 / extent2;+ const scale = size * 0.45 / extent;return (assetPoint) => {const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);- return [size / 2 + world.dot(xAxis) * scale2, size / 2 - world.dot(yAxis) * scale2];+ return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}-function skeletonCapture(root, request2, findings, size) {+function skeletonCapture(root, request, findings, size) {const baseRequest = {- id: request2.id,- label: request2.label,- cameraId: request2.cameraId,+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,buffer: "semantic-overlay",scope: "category",variant: "character-skeleton",- focusRolePrefixes: request2.focusRolePrefixes+ focusRolePrefixes: request.focusRolePrefixes};const frame = renderDiagnosticView(root, baseRequest, { size });- const descriptor2 = buildCharacterDiagnosticDescriptor(root, findings);- const project2 = projector(root, request2.cameraId, size);- const byRole = new Map(descriptor2.joints.map((joint) => [joint.role, joint]));- for (const edge of descriptor2.edges) {+ const descriptor = buildCharacterDiagnosticDescriptor(root, findings);+ const project = projector(root, request.cameraId, size);+ const byRole = new Map(descriptor.joints.map((joint) => [joint.role, joint]));+ for (const edge of descriptor.edges) {const parent = byRole.get(edge.parentRole);const child = byRole.get(edge.childRole);if (!parent || !child)continue;- drawLine2(frame.rgb, frame.width, frame.height, project2(parent.assetPosition), project2(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);- }- for (const joint of descriptor2.joints) {- const point = project2(joint.assetPosition);- const color2 = rgbFromHex(joint.color);- drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color2);- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.forwardAxisEnd), [64, 220, 255]);- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.bendAxisEnd), [255, 105, 210]);+ drawLine2(frame.rgb, frame.width, frame.height, project(parent.assetPosition), project(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);+ }+ for (const joint of descriptor.joints) {+ const point = project(joint.assetPosition);+ const color = rgbFromHex(joint.color);+ drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color);+ drawLine2(frame.rgb, frame.width, frame.height, point, project(joint.forwardAxisEnd), [64, 220, 255]);+ drawLine2(frame.rgb, frame.width, frame.height, point, project(joint.bendAxisEnd), [255, 105, 210]);stampLabel(frame.rgb, frame.width, frame.height, Math.max(0, Math.min(frame.width - 2, Math.round(point[0] + 3))), Math.max(0, Math.min(frame.height - 7, Math.round(point[1] - 6))), joint.label.toUpperCase().replace(/[^A-Z0-9]+/g, " ").slice(0, 18), 1);frame.regions.push({nodeName: joint.nodeName,@@ -24986,17 +24063,17 @@ function skeletonCapture(root, request2, findings, size) {Math.min(frame.width - 1, Math.round(point[0]) + 4),Math.min(frame.height - 1, Math.round(point[1]) + 4)],- color: color2,+ color,triangleCount: 0});}- const arrow = descriptor2.canonicalForwardArrow;- drawLine2(frame.rgb, frame.width, frame.height, project2(arrow.start), project2(arrow.end), [255, 220, 64]);+ const arrow = descriptor.canonicalForwardArrow;+ drawLine2(frame.rgb, frame.width, frame.height, project(arrow.start), project(arrow.end), [255, 220, 64]);frame.regions.sort((a, b) => a.nodePath.localeCompare(b.nodePath));return {id: frame.id,label: frame.label,- cameraId: request2.cameraId,+ cameraId: request.cameraId,kind: "skeleton",width: frame.width,height: frame.height,@@ -25017,32 +24094,32 @@ async function captureCharacterDiagnosticViews(root, clips, intent, findings = [const requests = planCharacterDiagnosticRequests(intent);const captures = [];try {- for (const request2 of requests) {- if (request2.variant === "character-skeleton") {- captures.push(skeletonCapture(root, request2, findings, size));+ for (const request of requests) {+ if (request.variant === "character-skeleton") {+ captures.push(skeletonCapture(root, request, findings, size));continue;}- if (!request2.clipName)+ if (!request.clipName)continue;const strip = await renderClipAnimation(root, clips, {- clip: request2.clipName,- camera: request2.cameraId,- frames: request2.phaseFractions?.length ?? 6,+ clip: request.clipName,+ camera: request.cameraId,+ frames: request.phaseFractions?.length ?? 6,size});if (!strip.ok || !strip.png || !strip.width || !strip.height)continue;captures.push({- id: request2.id,- label: request2.label,- cameraId: request2.cameraId,+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,kind: "motion-strip",width: strip.width,height: strip.height,png: strip.png,regions: [],- clipName: request2.clipName,- phaseFractions: request2.phaseFractions+ clipName: request.clipName,+ phaseFractions: request.phaseFractions});}} finally {@@ -25068,27 +24145,7 @@ var init_character_capture = __esm(() => {});// src/render.ts-var exports_render = {};-__export(exports_render, {- snapGlbToPalette: () => snapGlbToPalette,- settleContacts: () => settleContacts,- resolveEvaluatorMode: () => resolveEvaluatorMode,- renderSceneToGLB: () => renderSceneToGLB,- renderGLBInProcess: () => renderGLBInProcess,- renderGLB: () => renderGLB,- packKitGlb: () => packKitGlb,- optimizeGlbBytes: () => optimizeGlbBytes,- measureGlbBounds: () => measureGlbBounds,- inspectSceneStructure: () => inspectSceneStructure,- inspectGlbIntegration: () => inspectGlbIntegration,- inspectGeneratedAnimation: () => inspectGeneratedAnimation,- gradeGlbBytes: () => gradeGlbBytes,- executeKilnCode: () => executeKilnCode,- composeSceneGLB: () => composeSceneGLB,- bindBakedTextureProvenanceToFinalGlb: () => bindBakedTextureProvenanceToFinalGlb-});import * as THREE34 from "three";-import { createHash as createHash5 } from "node:crypto";import { Document, WebIO as WebIO3, getBounds } from "@gltf-transform/core";import {EXTMeshGPUInstancing as EXTMeshGPUInstancing3,@@ -25100,25 +24157,11 @@ import {instance,palette,flatten,- join as join2,+ join,weld,prune,mergeDocuments} from "@gltf-transform/functions";-async function measureGlbBounds(bytes) {- const doc = await engineIO().readBinary(bytes);- const root = doc.getRoot();- const scene = root.getDefaultScene() ?? root.listScenes()[0];- if (!scene)- return;- const { min, max } = getBounds(scene);- if (!min.every(Number.isFinite) || !max.every(Number.isFinite))- return;- return {- min: [min[0], min[1], min[2]],- max: [max[0], max[1], max[2]]- };-}function ensureDefaultScene(doc) {const root = doc.getRoot();const scene = root.getDefaultScene() ?? root.listScenes()[0];@@ -25127,8 +24170,8 @@ function ensureDefaultScene(doc) {return scene;}async function sha256Hex2(bytes) {- const digest2 = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer);- return [...new Uint8Array(digest2)].map((value) => value.toString(16).padStart(2, "0")).join("");+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer);+ return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");}async function inspectGlbIntegration(bytes, opts = {}) {const doc = await engineIO().readBinary(bytes);@@ -25334,28 +24377,28 @@ function bridgeTexture(doc, threeTex, cache) {cache.set(threeTex, t);return t;}-function bridgeGeometry(doc, buf, geometry2, material, meshName) {- if (!geometry2.getAttribute("normal")) {- geometry2.computeVertexNormals();+function bridgeGeometry(doc, buf, geometry, material, meshName) {+ if (!geometry.getAttribute("normal")) {+ geometry.computeVertexNormals();}const prim = doc.createPrimitive().setMaterial(Array.isArray(material) ? material[0] : material);- const posAttr = geometry2.getAttribute("position");+ const posAttr = geometry.getAttribute("position");if (posAttr) {prim.setAttribute("POSITION", doc.createAccessor(meshName + "_pos").setArray(geometryAttributeValues(posAttr)).setType(TYPE_VEC3).setBuffer(buf));}- const normAttr = geometry2.getAttribute("normal");+ const normAttr = geometry.getAttribute("normal");if (normAttr) {prim.setAttribute("NORMAL", doc.createAccessor(meshName + "_norm").setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));}- const uvAttr = geometry2.getAttribute("uv");+ const uvAttr = geometry.getAttribute("uv");if (uvAttr) {prim.setAttribute("TEXCOORD_0", doc.createAccessor(meshName + "_uv").setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));}- const tangentAttr = geometry2.getAttribute("tangent");+ const tangentAttr = geometry.getAttribute("tangent");if (tangentAttr?.itemSize === 4) {prim.setAttribute("TANGENT", doc.createAccessor(meshName + "_tangent").setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));}- const indexAttr = geometry2.getIndex();+ const indexAttr = geometry.getIndex();if (indexAttr) {const IndexArray = posAttr && posAttr.count > 65535 ? Uint32Array : Uint16Array;prim.setIndices(doc.createAccessor(meshName + "_idx").setArray(new IndexArray(indexAttr.array)).setType(TYPE_SCALAR).setBuffer(buf));@@ -25364,15 +24407,15 @@ function bridgeGeometry(doc, buf, geometry2, material, meshName) {if (!Array.isArray(material))return mesh.addPrimitive(prim);const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);- const groups = [...geometry2.groups].sort((a, b) => a.start - b.start);+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);let covered = 0;for (const group of groups) {if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);}const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);- for (const semantic3 of prim.listSemantics())- part.setAttribute(semantic3, prim.getAttribute(semantic3));+ for (const semantic of prim.listSemantics())+ part.setAttribute(semantic, prim.getAttribute(semantic));const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;part.setIndices(doc.createAccessor(meshName + "_group_indices").setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));mesh.addPrimitive(part);@@ -25407,13 +24450,13 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)}}if (semanticForExport !== undefined) {- const semantic3 = validateSemanticMetadataV1(semanticForExport);- if (!semantic3.valid || !semantic3.value) {- const detail = semantic3.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");+ const semantic = validateSemanticMetadataV1(semanticForExport);+ if (!semantic.valid || !semantic.value) {+ const detail = semantic.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on node ${threeObj.name || "<unnamed>"}: ${detail}`);}gtNode.setExtras({- [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic3.value)+ [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic.value)});}gtNode.setTranslation([threeObj.position.x, threeObj.position.y, threeObj.position.z]);@@ -25446,13 +24489,13 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;let gtMesh = meshCache.get(cacheKey);if (!gtMesh) {- const geometry2 = new THREE34.PlaneGeometry(1, 1);+ const geometry = new THREE34.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {- geometry2.translate(0.5 - centerX, 0.5 - centerY, 0);+ geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}if (rotation !== 0)- geometry2.rotateZ(rotation);- gtMesh = bridgeGeometry(doc, buf, geometry2, gtMat, sprite.name || "sprite-quad");+ geometry.rotateZ(rotation);+ gtMesh = bridgeGeometry(doc, buf, geometry, gtMat, sprite.name || "sprite-quad");meshCache.set(cacheKey, gtMesh);}gtNode.setMesh(gtMesh);@@ -25471,11 +24514,11 @@ function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {const anim = doc.createAnimation(clip.name);for (const track of clip.tracks) {const dotIdx = track.name.lastIndexOf(".");- const nodeName2 = track.name.substring(0, dotIdx);+ const nodeName = track.name.substring(0, dotIdx);const property = track.name.substring(dotIdx + 1);- const targetNode = nodeMap.get(nodeName2);+ const targetNode = nodeMap.get(nodeName);if (!targetNode) {- warnings.push(`Animation target "${nodeName2}" not found - skipped`);+ warnings.push(`Animation target "${nodeName}" not found - skipped`);continue;}let targetPath;@@ -25490,11 +24533,11 @@ function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {targetPath = "scale";valueType = TYPE_VEC3;} else {- warnings.push(`Unsupported animation property "${property}" on "${nodeName2}" - skipped`);+ warnings.push(`Unsupported animation property "${property}" on "${nodeName}" - skipped`);continue;}- const inputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);- const outputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);+ const inputAcc = doc.createAccessor(clip.name + "_" + nodeName + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);+ const outputAcc = doc.createAccessor(clip.name + "_" + nodeName + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);const sampler = doc.createAnimationSampler().setInput(inputAcc).setOutput(outputAcc).setInterpolation("LINEAR");const channel = doc.createAnimationChannel().setTargetNode(targetNode).setTargetPath(targetPath).setSampler(sampler);anim.addSampler(sampler);@@ -25532,80 +24575,6 @@ function reviewClipExtras(clips) {}))};}-function finalTextureForSlot(material, slot) {- switch (slot) {- case "map":- return material.getBaseColorTexture();- case "normalMap":- return material.getNormalTexture();- case "roughnessMap":- case "metalnessMap":- return material.getMetallicRoughnessTexture();- case "emissiveMap":- return material.getEmissiveTexture();- case "aoMap":- return material.getOcclusionTexture();- default:- return null;- }-}-async function bindBakedTextureProvenanceToFinalGlb(baked, finalGlb) {- if (baked.length === 0)- return [];- const doc = await engineIO().readBinary(finalGlb);- const root = doc.getRoot();- const byMaterialName = new Map;- for (const material of root.listMaterials()) {- const name = material.getName() || "(unnamed material)";- const list = byMaterialName.get(name) ?? [];- list.push(material);- byMaterialName.set(name, list);- }- const nodesByName = new Map;- for (const node of root.listNodes()) {- const list = nodesByName.get(node.getName()) ?? [];- list.push(node);- nodesByName.set(node.getName(), list);- }- const artifactGlbSha256 = `sha256:${await sha256Hex2(finalGlb)}`;- return baked.flatMap((entry) => {- const resolved2 = new Set;- for (const binding of entry.bindings) {- const nodeMaterials = (nodesByName.get(binding.node) ?? []).flatMap((node) => node.getMesh()?.listPrimitives().flatMap((primitive) => {- const material = primitive.getMaterial();- return material ? [material] : [];- }) ?? []);- const materials = nodeMaterials.filter((material) => (material.getName() || "(unnamed material)") === binding.material);- const candidates = materials.length ? materials : byMaterialName.get(binding.material) ?? [];- for (const material of candidates) {- const texture2 = finalTextureForSlot(material, binding.slot);- if (texture2)- resolved2.add(texture2);- }- }- if (resolved2.size === 0 && entry.texture !== "(unnamed texture)") {- for (const texture2 of root.listTextures()) {- if (texture2.getName() === entry.texture)- resolved2.add(texture2);- }- }- if (resolved2.size !== 1)- return [];- const texture = [...resolved2][0];- const image = texture.getImage();- const mime = texture.getMimeType();- if (!image || !mime)- return [];- return [- {- ...entry,- artifactGlbSha256,- finalMime: mime,- finalImageSha256: `sha256:${createHash5("sha256").update(image).digest("hex")}`- }- ];- });-}function resolveOptimize(opt) {if (opt)return opt;@@ -25655,7 +24624,7 @@ async function consolidateMaterials(doc, mode) {const effective = mode === "full" && (animatedOrSkinned || semanticGraph) ? "palette" : mode;const steps = [palette({ min: PALETTE_MIN })];if (effective === "full") {- steps.push(flatten(), join2({ keepNamed: true }));+ steps.push(flatten(), join({ keepNamed: true }));}steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));await doc.transform(...steps);@@ -25873,250 +24842,6 @@ async function renderGLBInProcess(code, opts = {}) {integrationManifest: scene.integrationManifest};}-function resolveEvaluatorMode(env = process.env) {- const value = env["KILN_EVALUATOR_MODE"];- if (value === undefined || value === "" || value === "in-process")- return "in-process";- if (value === "subprocess")- return "subprocess";- if (value === "isolated")- return "isolated";- throw new Error("Invalid KILN_EVALUATOR_MODE.");-}-async function renderGLB(code, opts = {}) {- const mode = resolveEvaluatorMode();- if (mode === "in-process")- return renderGLBInProcess(code, opts);- if (mode === "subprocess") {- const { renderGLBViaSubprocess: renderGLBViaSubprocess2 } = await Promise.resolve().then(() => (init_subprocess(), exports_subprocess));- return renderGLBViaSubprocess2(code, opts);- }- const { renderGLBViaIsolatedEvaluator: renderGLBViaIsolatedEvaluator2 } = await Promise.resolve().then(() => (init_isolation(), exports_isolation));- return renderGLBViaIsolatedEvaluator2(code, opts);-}-async function gradeGlbBytes(bytes, opts = {}) {- try {- const doc = await engineIO().readBinary(bytes);- return gradeInstanceability(collectGlbMetrics(doc), opts);- } catch {- return;- }-}-async function optimizeGlbBytes(bytes, opts = {}) {- const requested = opts.mode ?? "palette";- try {- const io = engineIO();- const doc = await io.readBinary(bytes);- let instancing;- if (opts.instance && opts.instance !== "off") {- instancing = await applyGpuInstancing(doc, opts.instance, opts.role);- }- let summary;- let mode;- if (requested !== "off") {- if (requested === "auto") {- if (collectGlbMetrics(doc).uniqueMaterials >= PALETTE_MIN)- mode = "palette";- } else {- mode = requested;- }- }- if (mode)- summary = await consolidateMaterials(doc, mode);- if (!summary && !instancing)- return;- ensureDefaultScene(doc);- const outBytes = await io.writeBinary(doc);- const gltfValidation = await assertFinalGlbValid(outBytes);- let report;- try {- report = gradeInstanceability(collectGlbMetrics(doc), { category: opts.category });- } catch {- report = undefined;- }- return {- bytes: outBytes,- gltfValidation,- ...report ? { report } : {},- ...summary ? { summary } : {},- ...instancing ? { instancing } : {}- };- } catch (error) {- if (error instanceof GltfValidationError)- throw error;- return;- }-}-async function packKitGlb(bytes, opts = {}) {- let doc;- try {- doc = await engineIO().readBinary(bytes);- } catch {- return;- }- const summary = await applyKitContract(doc, opts);- const changed = summary.ormPacked > 0 || summary.variantsAdded.length > 0 || summary.ktx2.applied;- if (!changed)- return;- ensureDefaultScene(doc);- const outBytes = await engineIO().writeBinary(doc);- const gltfValidation = await assertFinalGlbValid(outBytes);- return { bytes: outBytes, summary, gltfValidation };-}-async function snapGlbToPalette(bytes, slots, opts = {}) {- if (slots.length === 0)- return;- try {- const io = engineIO();- const doc = await io.readBinary(bytes);- const before = collectGlbMetrics(doc);- const idx = buildSlotIndex(slots);- let snapped = 0;- let skipped = 0;- for (const mat of doc.getRoot().listMaterials()) {- if (mat.getBaseColorTexture()) {- skipped++;- continue;- }- const base = mat.getBaseColorFactor();- const emissive = mat.getEmissiveFactor();- const transparent = mat.getAlphaMode() === "BLEND" || mat.getAlpha() < 0.98;- const slotI = chooseSlot(idx, {- baseLinear: [base[0], base[1], base[2]],- emissiveLinear: [emissive[0], emissive[1], emissive[2]],- transparent- });- if (slotI === undefined) {- skipped++;- continue;- }- const slot = slots[slotI];- const kind = slot.kind ?? "opaque";- const [lr, lg, lb] = hexToLinearRgb(slot.color);- const alpha = kind === "glass" ? slot.opacity ?? 0.4 : 1;- mat.setBaseColorFactor([lr, lg, lb, alpha]);- mat.setMetallicFactor(slot.metalness ?? 0);- mat.setRoughnessFactor(slot.roughness ?? (kind === "glass" ? 0.1 : 0.85));- if (kind === "glass")- mat.setAlphaMode("BLEND");- else if (mat.getAlphaMode() === "BLEND")- mat.setAlphaMode("OPAQUE");- mat.setEmissiveFactor(kind === "glow" ? [lr, lg, lb] : [0, 0, 0]);- snapped++;- }- await doc.transform(dedup());- await consolidateMaterials(doc, "palette");- const after = collectGlbMetrics(doc);- const summary = {- mode: "palette",- materialsBefore: before.uniqueMaterials,- materialsAfter: after.uniqueMaterials,- drawsBefore: before.drawCalls,- drawsAfter: after.drawCalls- };- ensureDefaultScene(doc);- const outBytes = await io.writeBinary(doc);- const gltfValidation = await assertFinalGlbValid(outBytes);- let report;- try {- report = gradeInstanceability(after, { category: opts.category });- } catch {- report = undefined;- }- return {- bytes: outBytes,- ...report ? { report } : {},- summary,- snapped,- skipped,- gltfValidation- };- } catch (error) {- if (error instanceof GltfValidationError)- throw error;- return;- }-}-function eulerDegToQuat(deg) {- const e = new THREE34.Euler(THREE34.MathUtils.degToRad(deg[0]), THREE34.MathUtils.degToRad(deg[1]), THREE34.MathUtils.degToRad(deg[2]), "XYZ");- const q = new THREE34.Quaternion().setFromEuler(e);- return [q.x, q.y, q.z, q.w];-}-async function composeSceneGLB(parts, opts = {}) {- const warnings = [];- const io = engineIO();- const master = new Document;- const masterScene = master.createScene(opts.sceneName ?? "Scene");- master.getRoot().setDefaultScene(masterScene);- let composed = 0;- for (let i = 0;i < parts.length; i++) {- const part = parts[i];- try {- const src = await io.readBinary(part.bytes);- const srcScene = src.getRoot().listScenes()[0];- const map = mergeDocuments(master, src);- const wrap = master.createNode(part.name ?? `part_${i}`).setTranslation([part.transform.pos[0], part.transform.pos[1], part.transform.pos[2]]).setRotation(eulerDegToQuat(part.transform.rotDeg)).setScale([part.transform.scale[0], part.transform.scale[1], part.transform.scale[2]]);- const mergedScene = srcScene ? map.get(srcScene) : undefined;- if (mergedScene) {- for (const child of mergedScene.listChildren())- wrap.addChild(child);- mergedScene.dispose();- }- masterScene.addChild(wrap);- composed++;- } catch (err) {- warnings.push(`part ${i} (${part.name ?? ""}) skipped: ${err instanceof Error ? err.message : String(err)}`);- }- }- if (composed === 0)- throw new Error("composeSceneGLB: no parts could be merged");- if (!opts.keepAnimations) {- for (const anim of master.getRoot().listAnimations())- anim.dispose();- }- try {- await master.transform(dedup());- } catch (err) {- warnings.push(`dedup failed: ${err instanceof Error ? err.message : String(err)}`);- }- const optimizeMode = opts.optimize ?? "palette";- let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;- if (optimizeMode === "auto" && collectGlbMetrics(master).uniqueMaterials >= PALETTE_MIN) {- effectiveOptimize = "palette";- }- if (effectiveOptimize !== "off") {- try {- await consolidateMaterials(master, effectiveOptimize);- } catch (err) {- warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);- }- }- const rootBuffers = master.getRoot().listBuffers();- if (rootBuffers.length > 1) {- const main = rootBuffers[0];- for (const acc of master.getRoot().listAccessors())- acc.setBuffer(main);- for (let i = 1;i < rootBuffers.length; i++)- rootBuffers[i].dispose();- }- const metrics = collectGlbMetrics(master);- ensureDefaultScene(master);- const bytes = await io.writeBinary(master);- const gltfValidation = await assertFinalGlbValid(bytes, "scene.glb");- for (const issue of gltfValidation.issues.messages) {- if (issue.severity !== 1)- continue;- warnings.push(`glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ""}: ${issue.message}`);- }- return {- bytes,- tris: metrics.triangles,- draws: metrics.drawCalls,- materials: metrics.uniqueMaterials,- warnings,- gltfValidation- };-}function inspectGeneratedAnimation(root, clips) {const warnings = [];if (clips.length === 0)@@ -26133,10 +24858,10 @@ function inspectGeneratedAnimation(root, clips) {warnings.push(`Track "${track.name}" is missing a node.property separator`);continue;}- const nodeName2 = track.name.substring(0, dotIdx);+ const nodeName = track.name.substring(0, dotIdx);const property = track.name.substring(dotIdx + 1);- if (!nodeNames.has(nodeName2)) {- warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName2}" — rename the pivot or fix the track`);+ if (!nodeNames.has(nodeName)) {+ warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName}" — rename the pivot or fix the track`);}if (!["position", "quaternion", "scale"].includes(property)) {warnings.push(`Animation track "${clip.name}:${track.name}" uses unsupported property "${property}"`);@@ -26259,58 +24984,6 @@ function inspectSceneStructure(root, opts = {}) {}return warnings;}-function settleContacts(root, opts = {}) {- const maxGap = opts.maxGap ?? 0.05;- const overlap = opts.overlap ?? 0.01;- const settled = [];- for (let pass = 0;pass < 8; pass++) {- const meshes = collectMeshStats(root);- if (meshes.length < 2)- return settled;- let pick;- for (let i = 0;i < meshes.length; i++) {- const a = meshes[i];- const ax = a.box.clone().expandByScalar(0.02);- if (meshes.some((b, j) => j !== i && ax.intersectsBox(b.box)))- continue;- let nearestGap;- for (let j = 0;j < meshes.length; j++) {- if (i === j)- continue;- const gap = minimalGapVector(a.box, meshes[j].box);- if (!nearestGap || gap.length() < nearestGap.length())- nearestGap = gap;- }- if (!nearestGap || nearestGap.length() === 0 || nearestGap.length() > maxGap)- continue;- const volume = a.size.x * a.size.y * a.size.z;- if (!pick || volume < pick.volume)- pick = { stats: a, gap: nearestGap, volume };- }- if (!pick)- break;- const delta = pick.gap.clone();- const dominant = ["x", "y", "z"].reduce((d, axis) => Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d, "x");- delta[dominant] += Math.sign(delta[dominant]) * overlap;- let target;- root.traverse((obj) => {- if (!target && obj.name === pick.stats.name && obj.isMesh)- target = obj;- });- if (!target)- break;- const parent = target.parent ?? root;- const p0 = new THREE34.Vector3;- target.getWorldPosition(p0);- const p1 = p0.clone().add(delta);- const l0 = parent.worldToLocal(p0.clone());- const l1 = parent.worldToLocal(p1.clone());- target.position.add(l1.sub(l0));- target.updateMatrixWorld(true);- settled.push(pick.stats.name);- }- return settled;-}var engineIO = () => new WebIO3().registerExtensions([EXTMeshGPUInstancing3, KHRMaterialsVariants3, KHRTextureBasisu3]), TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;var init_render = __esm(() => {init_authoring_diagnostic();@@ -26339,7 +25012,6 @@ var init_render = __esm(() => {});// src/evaluator/protocol.ts-import { createHash as createHash6 } from "node:crypto";function evaluatorOutcomeMessage(code) {return EVALUATOR_OUTCOME_MESSAGES[code];}@@ -26351,135 +25023,7 @@ function resolveEvaluatorPortV1(port, profile) {}return trustedInProcessEvaluatorPortV1;}-function isRecord6(value) {- return typeof value === "object" && value !== null && !Array.isArray(value);-}-function hasExactKeys(value, allowed) {- return Object.keys(value).every((key) => allowed.includes(key));-}-function fail(kind) {- throw new Error(`invalid evaluator ${kind}`);-}-function validRequestId(value) {- return typeof value === "string" && /^[A-Za-z0-9._-]{1,64}$/.test(value);-}-function validInteger(value, min, max) {- return Number.isInteger(value) && Number(value) >= min && Number(value) <= max;-}-function validQaReport(value) {- const dimensions2 = isRecord6(value) && isRecord6(value.dimensions) ? value.dimensions : undefined;- if (!isRecord6(value) || !hasExactKeys(value, ["schemaVersion", "category", "qaProfile", "disposition", "dimensions"]) || value.schemaVersion !== 1 || !isAssetCategory(value.category) || typeof value.qaProfile !== "string" || value.qaProfile.length < 1 || value.qaProfile.length > 128 || !["pass", "warn", "block", "notEvaluated", "legacy-unassessed"].includes(String(value.disposition)) || !dimensions2 || !hasExactKeys(dimensions2, QA_DIMENSIONS) || !QA_DIMENSIONS.every((dimension) => (dimension in dimensions2))) {- return false;- }- return QA_DIMENSIONS.every((dimension) => {- const result = dimensions2[dimension];- return isRecord6(result) && hasExactKeys(result, ["status", "findings", "metrics"]) && ["pass", "warn", "block", "notEvaluated"].includes(String(result.status)) && Array.isArray(result.findings) && result.findings.length <= 1000 && result.findings.every(isQaFinding) && (result.metrics === undefined || isRecord6(result.metrics));- });-}-function validGltfValidation(value) {- const issues = isRecord6(value) && isRecord6(value.issues) ? value.issues : undefined;- if (!issues || !Array.isArray(issues.messages)) {- return false;- }- return ["numErrors", "numWarnings", "numInfos", "numHints"].every((key) => validInteger(issues[key], 0, Number.MAX_SAFE_INTEGER)) && issues.messages.length <= 1000 && issues.messages.every((issue) => isRecord6(issue) && typeof issue.code === "string" && typeof issue.message === "string" && typeof issue.severity === "number" && Number.isFinite(issue.severity));-}-function isSha256(value) {- return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);-}-function decodeEvaluatorResultV1(json, maxGlbBytes, expectedRequestId) {- let value;- try {- value = JSON.parse(json);- } catch {- return fail("result");- }- if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "ok", "render", "error"]) || value.version !== EVALUATOR_RESULT_VERSION || !validRequestId(value.requestId) || typeof value.ok !== "boolean") {- return fail("result");- }- if (expectedRequestId !== undefined && value.requestId !== expectedRequestId)- fail("result");- if (!value.ok) {- if (value.render !== undefined)- return fail("result");- if (!isRecord6(value.error) || !hasExactKeys(value.error, ["code", "message", "qa", "diagnostic"])) {- return fail("result");- }- const codes = [- "INPUT_INVALID",- "EXECUTION_REJECTED",- "QA_BLOCKED",- "DEADLINE_EXCEEDED",- "CANCELLED",- "OUTPUT_LIMIT_EXCEEDED",- "ISOLATION_UNAVAILABLE",- "WORKER_FAILED",- "PROTOCOL_ERROR"- ];- if (!codes.includes(value.error.code) || typeof value.error.message !== "string" || value.error.message !== evaluatorOutcomeMessage(value.error.code)) {- return fail("result");- }- if (value.error.diagnostic !== undefined && (value.error.code !== "EXECUTION_REJECTED" || value.error.diagnostic !== "UNBOUND_VARIABLE" && value.error.diagnostic !== "GEAR_RADII_ORDER" && value.error.diagnostic !== "ROUNDED_BOX_RADIUS"))- return fail("result");- if (value.error.qa !== undefined) {- if (value.error.code !== "QA_BLOCKED" || !isRecord6(value.error.qa) || !hasExactKeys(value.error.qa, ["report", "stage", "gltfValidation"]) || !validQaReport(value.error.qa.report) || !["scene", "final-glb"].includes(String(value.error.qa.stage)) || value.error.qa.gltfValidation !== undefined && !validGltfValidation(value.error.qa.gltfValidation)) {- return fail("result");- }- } else if (value.error.code === "QA_BLOCKED") {- return fail("result");- }- return value;- }- if (value.error !== undefined || !isRecord6(value.render))- fail("result");- const renderKeys = [- "glbBase64",- "artifactGlbSha256",- "tris",- "meta",- "warnings",- "diagnosticViews",- "materialMetrics",- "materialRecipeApplications",- "materialResourceProvenance",- "bakedTextures",- "integrationManifest"- ];- if (!hasExactKeys(value.render, renderKeys) || typeof value.render.glbBase64 !== "string" || !validInteger(value.render.tris, 0, Number.MAX_SAFE_INTEGER) || !isRecord6(value.render.meta) || !Array.isArray(value.render.warnings) || !value.render.warnings.every((warning) => typeof warning === "string") || !isRecord6(value.render.integrationManifest)) {- fail("result");- }- const glb = Buffer.from(value.render.glbBase64, "base64");- if (glb.byteLength > maxGlbBytes || glb.toString("base64") !== value.render.glbBase64)- fail("result");- if (!isSha256(value.render.artifactGlbSha256))- fail("result");- const actualHash = `sha256:${createHash6("sha256").update(glb).digest("hex")}`;- if (actualHash !== value.render.artifactGlbSha256)- fail("result");- const diagnosticViews = value.render.diagnosticViews;- if (diagnosticViews !== undefined && !Array.isArray(diagnosticViews))- fail("result");- const decodedViews = diagnosticViews?.map((candidate) => {- if (!isRecord6(candidate) || typeof candidate.pngBase64 !== "string")- return fail("result");- const png = Buffer.from(candidate.pngBase64, "base64");- if (png.toString("base64") !== candidate.pngBase64)- return fail("result");- const { pngBase64: _2, ...view } = candidate;- return { ...view, png };- });- const { glbBase64: _, diagnosticViews: __, ...rest } = value.render;- return {- version: EVALUATOR_RESULT_VERSION,- requestId: value.requestId,- ok: true,- render: {- ...rest,- glb,- ...decodedViews ? { diagnosticViews: decodedViews } : {}- }- };-}-var EVALUATOR_REQUEST_VERSION = "kiln.evaluator.request.v1", EVALUATOR_RESULT_VERSION = "kiln.evaluator.result.v1", MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV1;+var MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV1;var init_protocol = __esm(() => {init_authoring_diagnostic();init_contracts();@@ -26513,8 +25057,8 @@ var init_protocol = __esm(() => {async render(code, options = {}, controls = {}) {if (controls.signal?.aborted)throw new EvaluatorPortError("CANCELLED");- const { renderGLBInProcess: renderGLBInProcess2 } = await Promise.resolve().then(() => (init_render(), exports_render));- const result = await renderGLBInProcess2(code, options);+ await Promise.resolve().then(() => init_render());+ const result = await renderGLBInProcess(code, options);if (controls.signal?.aborted)throw new EvaluatorPortError("CANCELLED");return result;@@ -26523,18 +25067,11 @@ var init_protocol = __esm(() => {});// src/views/port.ts-var exports_port = {};-__export(exports_port, {- sha256Bytes: () => sha256Bytes,- captureViewsViaPort: () => captureViewsViaPort,- captureViewPngsViaPort: () => captureViewPngsViaPort,- DEFAULT_VIEW_RENDER_TIMEOUT_MS: () => DEFAULT_VIEW_RENDER_TIMEOUT_MS-});async function sha256Bytes(bytes) {const input = new Uint8Array(bytes.byteLength);input.set(bytes);- const digest2 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", input));- return `sha256:${[...digest2].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", input));+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;}async function captureViewPngsViaPort(port, glb, timeoutMs, viewDirs, size, cameras, limits) {let timer;@@ -26613,38 +25150,38 @@ async function captureViewPngsViaPort(port, glb, timeoutMs, viewDirs, size, cameasync function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIMEOUT_MS, capture, limits) {if (capture?.shots || capture?.version) {try {- const { loadGlbReviewScene: loadGlbReviewScene2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const { renderCaptureGrid: renderCaptureGrid2 } = await Promise.resolve().then(() => (init_camera_capture(), exports_camera_capture));- const { renderSceneToGLB: renderSceneToGLB2 } = await Promise.resolve().then(() => (init_render(), exports_render));- const loaded = await loadGlbReviewScene2(Uint8Array.from(glb));+ await Promise.resolve().then(() => init_views());+ await Promise.resolve().then(() => init_camera_capture());+ await Promise.resolve().then(() => init_render());+ const loaded = await loadGlbReviewScene(Uint8Array.from(glb));let rendererId = "";- const grid = await renderCaptureGrid2(loaded.root, capture, async (input) => {- const derivative = await renderSceneToGLB2(input.root, {+ const grid = await renderCaptureGrid(loaded.root, capture, async (input) => {+ const derivative = await renderSceneToGLB(input.root, {derivative: true});- const result2 = await captureViewPngsViaPort(port, derivative.bytes, timeoutMs, [input.view.dir], input.size, [input.camera], limits);- if (!result2.ok)- throw new Error(result2.reason);- if (!result2.derivativeFidelityAttested || !result2.inputGlbSha256)+ const result = await captureViewPngsViaPort(port, derivative.bytes, timeoutMs, [input.view.dir], input.size, [input.camera], limits);+ if (!result.ok)+ throw new Error(result.reason);+ if (!result.derivativeFidelityAttested || !result.inputGlbSha256)throw new Error("advanced capture requires derivative material receipt");- if (rendererId && rendererId !== result2.rendererId)+ if (rendererId && rendererId !== result.rendererId)throw new Error("capture renderer changed between cells");- rendererId = result2.rendererId;+ rendererId = result.rendererId;return {- png: Buffer.from(result2.pngs[0]),+ png: Buffer.from(result.pngs[0]),receipt: {version: "kiln.view-fidelity.v1",derivativeLabel: input.label,requested: "full-preferred",delivered: "full-material",exactArtifact: false,- rendererId: result2.rendererId,+ rendererId: result.rendererId,materialFaithful: true,degraded: false,- inputGlbSha256: result2.inputGlbSha256,+ inputGlbSha256: result.inputGlbSha256,camera: input.camera,cameraFidelity: "echo-validated",- ...result2.captureCache ? { captureCache: result2.captureCache } : {}+ ...result.captureCache ? { captureCache: result.captureCache } : {}}};}, limits);@@ -26664,22 +25201,22 @@ async function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIreturn { ok: false, reason: error instanceof Error ? error.message : String(error) };}}- let resolved2;+ let resolved;try {- resolved2 = resolveGridCapture(capture, process.env["KILN_GRID_VARIANT"]);- enforceCapturePixels(resolved2.views.length, 384, resolved2.cols, limits);+ resolved = resolveGridCapture(capture, process.env["KILN_GRID_VARIANT"]);+ enforceCapturePixels(resolved.views.length, 384, resolved.cols, limits);} catch (err) {return { ok: false, reason: err instanceof Error ? err.message : String(err) };}- const views = resolved2.views;- const shape = { preset: resolved2.preset, cols: resolved2.cols, cells: views.length };+ const views = resolved.views;+ const shape = { preset: resolved.preset, cols: resolved.cols, cells: views.length };let cameras;- if (resolved2.zooms.some((z4) => z4 !== undefined)) {+ if (resolved.zooms.some((z) => z !== undefined)) {try {- const { loadGlbReviewScene: loadGlbReviewScene2, measureBounds: measureBounds2, cameraFromBounds: cameraFromBounds2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const loaded = await loadGlbReviewScene2(Uint8Array.from(glb));- const bounds = measureBounds2(loaded.root);- cameras = views.map((view, i) => cameraFromBounds2(bounds, view.dir, resolved2.zooms[i] ?? 1));+ await Promise.resolve().then(() => init_views());+ const loaded = await loadGlbReviewScene(Uint8Array.from(glb));+ const bounds = measureBounds(loaded.root);+ cameras = views.map((view, i) => cameraFromBounds(bounds, view.dir, resolved.zooms[i] ?? 1));} catch (error) {return { ok: false, reason: error instanceof Error ? error.message : String(error) };}@@ -26688,7 +25225,7 @@ async function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIif (!result.ok)return result;try {- const grid = compositeViewPngGrid(result.pngs, resolved2.cols, views);+ const grid = compositeViewPngGrid(result.pngs, resolved.cols, views);enforceCaptureBytes([grid.png], limits);return {ok: true,@@ -26713,18 +25250,6 @@ var init_port = __esm(() => {});// src/views/inspect.ts-var exports_inspect = {};-__export(exports_inspect, {- renderInspectView: () => renderInspectView,- prepareInspectView: () => prepareInspectView,- listPartNames: () => listPartNames,- INSPECT_SIZE: () => INSPECT_SIZE,- INSPECT_MIN_ZOOM: () => INSPECT_MIN_ZOOM,- INSPECT_MAX_ZOOM: () => INSPECT_MAX_ZOOM,- INSPECT_MAX_PART_NAMES: () => INSPECT_MAX_PART_NAMES,- INSPECT_DEFAULT_ZOOM: () => INSPECT_DEFAULT_ZOOM,- INSPECT_CAMERAS: () => INSPECT_CAMERAS-});function listPartNames(root, cap = INSPECT_MAX_PART_NAMES) {const names = [];const seen = new Set;@@ -26836,27 +25361,6 @@ function prepareInspectView(root, opts = {}) {frameBounds: expandBounds2(bounds, zoom)};}-function renderInspectView(root, opts = {}) {- const prepared = prepareInspectView(root, opts);- if (!prepared.ok)- return prepared;- const rgb2 = rasterizeView(prepared.root, prepared.viewSpec.dir, {- size: prepared.size,- frameBounds: prepared.frameBounds- });- return {- ok: true,- ...prepared.part ? { part: prepared.part } : {},- view: prepared.view,- azimuthDeg: prepared.azimuthDeg,- elevationDeg: prepared.elevationDeg,- zoom: prepared.zoom,- isolated: prepared.isolated,- width: prepared.size,- height: prepared.size,- png: encodePng(rgb2, prepared.size, prepared.size)- };-}var INSPECT_SIZE = 512, INSPECT_DEFAULT_ZOOM = 1.2, INSPECT_MIN_ZOOM = 1, INSPECT_MAX_ZOOM = 4, INSPECT_MAX_PART_NAMES = 40, INSPECT_CAMERAS;var init_inspect = __esm(() => {init_raster();@@ -26872,11 +25376,6 @@ var init_inspect = __esm(() => {});// src/views/measurement.ts-var exports_measurement = {};-__export(exports_measurement, {- measureAttachment: () => measureAttachment,- describeSubjectFrame: () => describeSubjectFrame-});import { Box3 as Box316, Vector3 as Vector330 } from "three";function describeSubjectFrame(root, subject) {const selected = selectCameraSubject(root, subject);@@ -26911,9 +25410,9 @@ function describeSubjectFrame(root, subject) {};}function measureAttachment(root, input) {- const endpoint = (request2) => {- const selected = selectCameraSubject(root, request2.subject);- const local = request2.point ?? [0, 0, 0];+ const endpoint = (request) => {+ const selected = selectCameraSubject(root, request.subject);+ const local = request.point ?? [0, 0, 0];if (local.length !== 3 || local.some((n) => !Number.isFinite(n)))throw new Error("attachment point must be three finite subject-local coordinates");selected.node.updateWorldMatrix(true, false);@@ -28200,80 +26699,7 @@ import { z as z4 } from "zod";// src/program-store.tsvar MAX_PROGRAM_BYTES = 1024 * 1024;-var canonicalProgramRefPattern = /^sha256:[a-f0-9]{64}(?![\s\S])/;var programRefPattern = /^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\s\S])/;-function assertProgramRef(ref) {- if (typeof ref !== "string" || !programRefPattern.test(ref))- throw new Error("Invalid program reference; use a p_ handle or full sha256 reference returned by Kiln.");-}-function* shortProgramRefCandidates(canonical2) {- if (!canonicalProgramRefPattern.test(canonical2) || canonical2.length !== 71)- throw new Error("Invalid canonical program reference.");- for (let length2 = 12;length2 <= 64; length2 += 4)- yield `p_${canonical2.slice(7, 7 + length2)}`;-}-async function programReference(code) {- const bytes = new TextEncoder().encode(code);- if (bytes.length > MAX_PROGRAM_BYTES)- throw new Error("Program exceeds the 1 MiB source limit.");- if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== code)- throw new Error("Program must be valid Unicode.");- const hash2 = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));- return `sha256:${Array.from(hash2, (b) => b.toString(16).padStart(2, "0")).join("")}`;-}--class MemoryProgramStore {- maxBytes;- programs = new Map;- handles = new Map;- constructor(maxBytes = 64 * 1024 * 1024) {- this.maxBytes = maxBytes;- }- bytes = 0;- async put(code) {- const ref = await programReference(code);- if (!this.programs.has(ref)) {- const size = new TextEncoder().encode(code).length;- if (this.bytes + size > this.maxBytes)- throw new Error("Program store is full; export your work and start a new store.");- this.programs.set(ref, code);- this.bytes += size;- }- return ref;- }- async stats() {- return {- entries: this.programs.size,- bytes: this.bytes,- maxSourceBytes: MAX_PROGRAM_BYTES,- maxBytes: this.maxBytes,- eviction: "none"- };- }- async get(ref) {- assertProgramRef(ref);- const canonical2 = ref.startsWith("p_") ? this.handles.get(ref) : ref;- const code = canonical2 === undefined ? undefined : this.programs.get(canonical2);- if (code === undefined)- throw new Error(`Program not found: ${ref}. Import the source into this store again.`);- return code;- }- async shortRef(ref) {- await this.get(ref);- if (ref.startsWith("p_"))- return ref;- for (const handle of shortProgramRefCandidates(ref)) {- const owner = this.handles.get(handle);- if (owner === ref)- return handle;- if (owner === undefined) {- this.handles.set(handle, ref);- return handle;- }- }- throw new Error("Unable to register an immutable program handle.");- }-}// src/tools/programs.tsimport { z as z2 } from "zod";@@ -28299,51 +26725,6 @@ var inputSchema = z3.object({init_protocol();import * as acorn2 from "acorn";import * as walk2 from "acorn-walk";-function copy(result) {- return { ...structuredClone(result), glb: Buffer.from(result.glb) };-}--class MemoryBuildCache {- maxBytes;- entries = new Map;- bytes = 0;- constructor(maxBytes = 64 * 1024 * 1024) {- this.maxBytes = maxBytes;- if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)- throw new Error("Build cache size must be a nonnegative integer.");- }- async get(key) {- const entry = this.entries.get(key);- if (!entry)- return;- this.entries.delete(key);- this.entries.set(key, entry);- return copy(entry.result);- }- async put(key, result) {- const { glb, ...metadata } = result;- const size = glb.byteLength + Buffer.byteLength(JSON.stringify(metadata));- if (size > this.maxBytes)- return;- const old = this.entries.get(key);- if (old) {- this.bytes -= old.bytes;- this.entries.delete(key);- }- while (this.bytes + size > this.maxBytes) {- const first = this.entries.keys().next().value;- if (first === undefined)- break;- this.bytes -= this.entries.get(first).bytes;- this.entries.delete(first);- }- this.entries.set(key, { result: copy(result), bytes: size });- this.bytes += size;- }- stats() {- return { entries: this.entries.size, bytes: this.bytes, maxBytes: this.maxBytes };- }-}// src/tools/registry.tsinit_validation();@@ -28420,9 +26801,9 @@ function diffLines(a, b) {const n = a.length;const m = b.length;const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));- for (let i2 = n - 1;i2 >= 0; i2--) {- for (let j2 = m - 1;j2 >= 0; j2--) {- lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);+ for (let i = n - 1;i >= 0; i--) {+ for (let j = m - 1;j >= 0; j--) {+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);}}const ops = [];@@ -28562,20 +26943,20 @@ function resolveViewRenderTimeoutMs(input) {...remainingGenerationBudgetMs !== undefined ? { remainingGenerationBudgetMs } : {},...rendererDeadlineMs !== undefined ? { rendererDeadlineMs } : {}});- let resolved2 = timeoutMs;+ let resolved = timeoutMs;if (input.resolver && hostContextAvailable) {try {- resolved2 = boundedTimeout(input.resolver(resolverContext), timeoutMs);+ resolved = boundedTimeout(input.resolver(resolverContext), timeoutMs);} catch {- resolved2 = timeoutMs;+ resolved = timeoutMs;}}if (rendererDeadlineMs !== undefined)- resolved2 = Math.min(resolved2, rendererDeadlineMs);+ resolved = Math.min(resolved, rendererDeadlineMs);if (remainingGenerationBudgetMs !== undefined) {- resolved2 = Math.min(resolved2, remainingGenerationBudgetMs);+ resolved = Math.min(resolved, remainingGenerationBudgetMs);}- return boundedTimeout(resolved2, timeoutMs);+ return boundedTimeout(resolved, timeoutMs);}// src/tools/registry.ts@@ -28585,8 +26966,8 @@ function proceduralTextureMaterialContract(rendered, context) {if (required.length === 0)return;const available = new Set((rendered.bakedTextures ?? []).map((entry) => entry.usage));- const present = required.filter((usage2) => available.has(usage2));- const missing = required.filter((usage2) => !available.has(usage2));+ const present = required.filter((usage) => available.has(usage));+ const missing = required.filter((usage) => !available.has(usage));return { required, present, missing };}function missingProceduralTextureResult(rendered, context) {@@ -28625,8 +27006,8 @@ async function evaluateGeneratedSource(code, context, optimize = "off") {}async function loadEvaluatedReviewScene(code, context) {const rendered = await evaluateGeneratedSource(code, context);- const { loadGlbReviewScene: loadGlbReviewScene2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const scene = await loadGlbReviewScene2(rendered.glb);+ await Promise.resolve().then(() => init_views());+ const scene = await loadGlbReviewScene(rendered.glb);return { rendered, ...scene };}var viewEvidenceHistoryByContext = new WeakMap;@@ -28642,8 +27023,8 @@ function withViewEvidenceHistory(context) {return { ...context, viewEvidenceHistory: history };}async function sha256Glb(bytes) {- const digest2 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));- return `sha256:${[...digest2].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;}async function renderDerivativeCell(input, context) {let derivativeRoot = input.root;@@ -28654,9 +27035,9 @@ async function renderDerivativeCell(input, context) {if (!mesh.isMesh)return;const prepare = (material) => {- const copy2 = material.clone();- copy2.side = THREE35.DoubleSide;- return copy2;+ const copy = material.clone();+ copy.side = THREE35.DoubleSide;+ return copy;};mesh.material = Array.isArray(mesh.material) ? mesh.material.map(prepare) : prepare(mesh.material);});@@ -28684,23 +27065,23 @@ async function renderDerivativeCell(input, context) {...trustedCategory(context) ? { category: trustedCategory(context) } : {},...context.intent ? { intent: context.intent } : {}});- const { cameraFromBounds: cameraFromBounds2, measureBounds: measureBounds2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const camera2 = input.camera ?? cameraFromBounds2(input.frameBounds ?? measureBounds2(input.root), input.view.dir, 1, undefined, measureBounds2(input.root));+ await Promise.resolve().then(() => init_views());+ const camera = input.camera ?? cameraFromBounds(input.frameBounds ?? measureBounds(input.root), input.view.dir, 1, undefined, measureBounds(input.root));const derivativeGlb = Uint8Array.from(rendered.bytes);const inputGlbSha256 = await sha256Glb(derivativeGlb);let degradeReason;const derivativeReasonCodes = [];if (context.viewRenderPort) {- const { captureViewPngsViaPort: captureViewPngsViaPort2 } = await Promise.resolve().then(() => (init_port(), exports_port));- const ported = await captureViewPngsViaPort2(context.viewRenderPort, derivativeGlb, resolveInLoopViewRenderTimeoutMs(context, "derivative-cell"), [input.view.dir], input.size, [camera2], context.captureLimits);+ await Promise.resolve().then(() => init_port());+ const ported = await captureViewPngsViaPort(context.viewRenderPort, derivativeGlb, resolveInLoopViewRenderTimeoutMs(context, "derivative-cell"), [input.view.dir], input.size, [camera], context.captureLimits);if (ported.ok && ported.derivativeFidelityAttested) {if (ported.inputGlbSha256 !== inputGlbSha256) {throw new Error(`validated derivative receipt hash mismatch (${ported.inputGlbSha256} != ${inputGlbSha256})`);}- const receipt2 = {+ const receipt = {version: "kiln.view-fidelity.v1",derivativeLabel: input.label,- camera: camera2,+ camera,cameraFidelity: "echo-validated",...ported.captureCache ? { captureCache: ported.captureCache } : {},requested: "full-preferred",@@ -28718,7 +27099,7 @@ async function renderDerivativeCell(input, context) {neededPbr: true});} catch {}- return { png: Buffer.from(ported.pngs[0]), receipt: receipt2 };+ return { png: Buffer.from(ported.pngs[0]), receipt };}if (ported.ok) {degradeReason = "view render port returned no derivative material/hash receipt";@@ -28736,17 +27117,17 @@ async function renderDerivativeCell(input, context) {}if (context.viewRenderRequired)throw new Error(`Required GPU render failed: ${degradeReason}`);- const { renderGlbViewCell: renderGlbViewCell2, CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const produceFlat = async () => renderGlbViewCell2(derivativeGlb, input.view, {+ await Promise.resolve().then(() => init_views());+ const produceFlat = async () => renderGlbViewCell(derivativeGlb, input.view, {size: input.size,- camera: camera2,+ camera,...input.backfaceCull !== undefined ? { backfaceCull: input.backfaceCull } : {},...input.frameBounds ? { frameBounds: input.frameBounds } : {}});const flat = context.captureCache ? await (await Promise.resolve().then(() => (init_capture_cache(), exports_capture_cache))).captureCpuCell(context.captureCache, {artifactGlbSha256: inputGlbSha256,- rendererId: CPU_RASTER_RENDERER_ID2,- camera: camera2,+ rendererId: CPU_RASTER_RENDERER_ID,+ camera,size: input.size,backfaceCull: input.backfaceCull ?? true}, produceFlat) : await produceFlat();@@ -28762,7 +27143,7 @@ async function renderDerivativeCell(input, context) {const receipt = {version: "kiln.view-fidelity.v1",derivativeLabel: input.label,- camera: camera2,+ camera,cameraFidelity: "engine-resolved",...flat.captureCache ? {captureCache: {@@ -28775,7 +27156,7 @@ async function renderDerivativeCell(input, context) {delivered: "geometry-flat",materialFaithful: false,exactArtifact: false,- rendererId: CPU_RASTER_RENDERER_ID2,+ rendererId: CPU_RASTER_RENDERER_ID,inputGlbSha256,degraded: true,degradeReason,@@ -28783,7 +27164,7 @@ async function renderDerivativeCell(input, context) {};try {context.onViewsRendered?.({- renderer: CPU_RASTER_RENDERER_ID2,+ renderer: CPU_RASTER_RENDERER_ID,degraded: true,degradedReason: degradeReason,neededPbr: true@@ -28911,12 +27292,12 @@ function runListPrimitives(input) {const all = listPrimitives();const category = input.category?.trim().toLowerCase();const primitives = category ? all.filter((p) => p.category.toLowerCase() === category) : all;- const text2 = primitives.map((p) => `${p.signature} -> ${p.returns}+ const text = primitives.map((p) => `${p.signature} -> ${p.returns}${p.description}e.g. ${p.example}`).join(``);- return { primitives, text: text2 };+ return { primitives, text };}function runValidate(input, context) {const category = trustedCategory(context);@@ -29012,12 +27393,12 @@ async function runRender(input, context) {}async function runScreenshot(input, context) {try {- const { renderGlbViewGrid: renderGlbViewGrid2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);const warnings = inspectSceneStructure(root, {category: trustedCategory(context)});- const grid = await renderGlbViewGrid2(rendered.glb);+ const grid = await renderGlbViewGrid(rendered.glb);return {ok: true,views: grid.views,@@ -29043,7 +27424,7 @@ function screenshotMedia(output) {}async function runRenderViews(input, context) {try {- const { renderGlbViewGrid: renderGlbViewGrid2, CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2, resolveGridCapture: resolveGridCapture2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root, rendered, reasonCodes } = await loadEvaluatedReviewScene(input.code, context);const materialContractFailure = missingProceduralTextureResult(rendered, context);if (materialContractFailure)@@ -29052,10 +27433,10 @@ async function runRenderViews(input, context) {const structuralWarnings = inspectSceneStructure(root, { category });const metrics = collectSceneMetrics(root);if ("shots" in (input.capture ?? {})) {- const { renderCaptureGrid: renderCaptureGrid2, listCameraSubjects: listCameraSubjects2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const grid2 = await renderCaptureGrid2(root, input.capture, (cell) => renderDerivativeCell(cell, context));- const receipts = grid2.derivativeReceipts;- const materialFaithful2 = receipts.every((r) => r.materialFaithful);+ await Promise.resolve().then(() => init_views());+ const grid = await renderCaptureGrid(root, input.capture, (cell) => renderDerivativeCell(cell, context));+ const receipts = grid.derivativeReceipts;+ const materialFaithful = receipts.every((r) => r.materialFaithful);return {ok: true,...rendered.buildCache ? { buildCache: rendered.buildCache } : {},@@ -29065,24 +27446,24 @@ async function runRenderViews(input, context) {...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},bbox: metrics.bbox,lowestPart: metrics.lowestPart,- views: grid2.views,- capture: grid2.capture,- ...grid2.captureCache ? { captureCache: grid2.captureCache } : {},- gridWidth: grid2.width,- gridHeight: grid2.height,- cameraShots: grid2.cameraShots,- parts: listCameraSubjects2(root).slice(0, 80).map(({ path, name }) => ({ path, name })),+ views: grid.views,+ capture: grid.capture,+ ...grid.captureCache ? { captureCache: grid.captureCache } : {},+ gridWidth: grid.width,+ gridHeight: grid.height,+ cameraShots: grid.cameraShots,+ parts: listCameraSubjects(root).slice(0, 80).map(({ path, name }) => ({ path, name })),derivativeReceipts: receipts,- ..."output" in input.capture && input.capture.output === "separate" ? { framesBase64: grid2.perFramePngs.map((p) => p.toString("base64")) } : { pngBase64: grid2.png.toString("base64") },+ ..."output" in input.capture && input.capture.output === "separate" ? { framesBase64: grid.perFramePngs.map((p) => p.toString("base64")) } : { pngBase64: grid.png.toString("base64") },viewFidelity: {version: "kiln.view-fidelity.v1",requested: "full-preferred",- delivered: materialFaithful2 ? "full-material" : "geometry-flat",- materialFaithful: materialFaithful2,+ delivered: materialFaithful ? "full-material" : "geometry-flat",+ materialFaithful,exactArtifact: false,rendererId: [...new Set(receipts.map((r) => r.rendererId))].join(", "),inputGlbSha256: await sha256Glb(Uint8Array.from(rendered.glb)),- degraded: !materialFaithful2+ degraded: !materialFaithful},warnings: [...structuralWarnings, ...rendered.warnings]};@@ -29092,10 +27473,10 @@ async function runRenderViews(input, context) {let drawnBy;let materialFaithful = false;if (context.viewRenderPort && (neededPbr || context.viewRenderRequired)) {- const { captureViewsViaPort: captureViewsViaPort2 } = await Promise.resolve().then(() => (init_port(), exports_port));- const ported = await captureViewsViaPort2(context.viewRenderPort, rendered.glb, resolveInLoopViewRenderTimeoutMs(context, "in-loop-grid"), input.capture);+ await Promise.resolve().then(() => init_port());+ const ported = await captureViewsViaPort(context.viewRenderPort, rendered.glb, resolveInLoopViewRenderTimeoutMs(context, "in-loop-grid"), input.capture);if (ported.ok) {- const resolvedViews = resolveGridCapture2(input.capture, process.env["KILN_GRID_VARIANT"]);+ const resolvedViews = resolveGridCapture(input.capture, process.env["KILN_GRID_VARIANT"]);grid = {png: ported.png,views: resolvedViews.views.map((v) => v.name),@@ -29108,7 +27489,7 @@ async function runRenderViews(input, context) {drawnBy = { renderer: ported.rendererId, degraded: false, neededPbr };} else {drawnBy = {- renderer: CPU_RASTER_RENDERER_ID2,+ renderer: CPU_RASTER_RENDERER_ID,degraded: true,degradedReason: ported.reason,neededPbr@@ -29118,13 +27499,13 @@ async function runRenderViews(input, context) {if (!grid && context.viewRenderRequired)throw new Error(`Required GPU render failed: ${drawnBy?.degradedReason ?? "renderer unavailable"}`);if (!grid) {- grid = await renderGlbViewGrid2(rendered.glb, {+ grid = await renderGlbViewGrid(rendered.glb, {...input.capture ? { capture: input.capture } : {},...context.captureCache ? { captureCache: context.captureCache } : {}});}- drawnBy ??= context.viewRenderPort ? { renderer: CPU_RASTER_RENDERER_ID2, degraded: false, neededPbr } : {- renderer: CPU_RASTER_RENDERER_ID2,+ drawnBy ??= context.viewRenderPort ? { renderer: CPU_RASTER_RENDERER_ID, degraded: false, neededPbr } : {+ renderer: CPU_RASTER_RENDERER_ID,degraded: neededPbr,...neededPbr ? {degradedReason: "material-faithful view render port unavailable"@@ -29133,8 +27514,8 @@ async function runRenderViews(input, context) {};const hashInput = new Uint8Array(rendered.glb.byteLength);hashInput.set(rendered.glb);- const digest2 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", hashInput));- const inputGlbSha256 = `sha256:${[...digest2].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", hashInput));+ const inputGlbSha256 = `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;const viewFidelity = {version: "kiln.view-fidelity.v1",requested: "full-preferred",@@ -29203,12 +27584,12 @@ function createKilnRenderViewsDef(context = {}) {var kilnRenderViewsDef = createKilnRenderViewsDef();async function runScreenshotAnimation(input, context) {try {- const { renderClipAnimation: renderClipAnimation2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root, clips } = await loadEvaluatedReviewScene(input.code, context);const warnings = inspectSceneStructure(root, {category: trustedCategory(context)});- const r = await renderClipAnimation2(root, clips, {+ const r = await renderClipAnimation(root, clips, {clip: input.clip,...input.shot ? { shot: input.shot } : {},...input.frames !== undefined ? { frames: input.frames } : {},@@ -29289,19 +27670,19 @@ function createKilnScreenshotAnimationDef(context = {}) {var kilnScreenshotAnimationDef = createKilnScreenshotAnimationDef();async function runViewInterior(input, context) {try {- const { renderInteriorGrid: renderInteriorGrid2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root } = await loadEvaluatedReviewScene(input.code, context);- const nodeName2 = input.nodeName?.trim() ? input.nodeName : undefined;- const grid = await renderInteriorGrid2(root, {+ const nodeName = input.nodeName?.trim() ? input.nodeName : undefined;+ const grid = await renderInteriorGrid(root, {...input.capture ? { capture: input.capture } : {},- ...nodeName2 ? { nodeName: nodeName2 } : {},+ ...nodeName ? { nodeName } : {},renderDerivativeCell: (cell) => renderDerivativeCell(cell, context)});const warnings = inspectSceneStructure(root, {category: trustedCategory(context)});if (grid.roofsHidden === 0) {- warnings.push(nodeName2 ? `No node named "${nodeName2}" was found, so the roof could not be lifted and the interior is still occluded. Check that name, or omit nodeName so the roof is found by its semantic role instead.` : 'No roof was found, so nothing could be lifted and the interior is still occluded. Build the roof with createRoofPlanes/createGableRoof (which tag it as a roof), or name the roof group "Roof".');+ warnings.push(nodeName ? `No node named "${nodeName}" was found, so the roof could not be lifted and the interior is still occluded. Check that name, or omit nodeName so the roof is found by its semantic role instead.` : 'No roof was found, so nothing could be lifted and the interior is still occluded. Build the roof with createRoofPlanes/createGableRoof (which tag it as a roof), or name the roof group "Roof".');}const viewFidelity = derivativeReviewFidelity(grid.derivativeReceipts);const viewEvidence = viewFidelity ? context.viewEvidenceHistory?.record("kiln_view_interior", viewFidelity) : undefined;@@ -29357,10 +27738,10 @@ var inspectInput = z4.object({var inspectBufferInput = inspectInput.omit({ code: true });async function runInspect(input, context) {try {- const { prepareInspectView: prepareInspectView2 } = await Promise.resolve().then(() => (init_inspect(), exports_inspect));+ await Promise.resolve().then(() => init_inspect());const { root } = await loadEvaluatedReviewScene(input.code, context);- const { measureAttachment: measureAttachment2, describeSubjectFrame: describeSubjectFrame2 } = await Promise.resolve().then(() => (init_measurement(), exports_measurement));- const measurement = input.measure ? measureAttachment2(root, input.measure) : undefined;+ await Promise.resolve().then(() => init_measurement());+ const measurement = input.measure ? measureAttachment(root, input.measure) : undefined;if (input.shot) {if ([input.part,@@ -29371,12 +27752,12 @@ async function runInspect(input, context) {input.isolate].some((v) => v !== undefined))throw new Error("shot cannot be combined with legacy inspection controls");- const { renderCaptureGrid: renderCaptureGrid2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const grid = await renderCaptureGrid2(root, { version: "kiln.capture.v1", shots: [input.shot], size: 512 }, (cell) => renderDerivativeCell(cell, context));+ await Promise.resolve().then(() => init_views());+ const grid = await renderCaptureGrid(root, { version: "kiln.capture.v1", shots: [input.shot], size: 512 }, (cell) => renderDerivativeCell(cell, context));return {ok: true,cameraShot: grid.cameraShots[0],- subjectFrame: describeSubjectFrame2(root, input.shot.subject),+ subjectFrame: describeSubjectFrame(root, input.shot.subject),...measurement ? { measurement } : {},pngBase64: grid.perFramePngs[0].toString("base64"),width: 512,@@ -29384,7 +27765,7 @@ async function runInspect(input, context) {viewFidelity: derivativeReviewFidelity(grid.derivativeReceipts)};}- const r = prepareInspectView2(root, {+ const r = prepareInspectView(root, {...input.part !== undefined ? { part: input.part } : {},...input.view !== undefined ? { view: input.view } : {},...input.azimuthDeg !== undefined ? { azimuthDeg: input.azimuthDeg } : {},@@ -29542,12 +27923,12 @@ function createKilnToolRegistry(context = {}) {];}var kilnToolRegistry = createKilnToolRegistry();-async function guardCaptureBudget(name, input, context, run2) {+async function guardCaptureBudget(name, input, context, run) {try {- const { enforceCapturePixels: enforceCapturePixels2, enforceCaptureBytes: enforceCaptureBytes2 } = await Promise.resolve().then(() => (init_capture_limits(), exports_capture_limits));+ await Promise.resolve().then(() => init_capture_limits());const args = input;if (name === "kiln_edit" && args.render === false)- return await run2();+ return await run();let cells = 6, size = 384, cols = 3, compose = true;if (name === "kiln_inspect") {cells = 1;@@ -29567,18 +27948,18 @@ async function guardCaptureBudget(name, input, context, run2) {size = args.capture.size ?? 384;cols = args.capture.cols ?? Math.min(3, cells);} else {- const { resolveGridCapture: resolveGridCapture2 } = await Promise.resolve().then(() => (init_capture(), exports_capture));- const resolved2 = resolveGridCapture2(args.capture);- cells = resolved2.views.length;- cols = resolved2.cols;+ await Promise.resolve().then(() => init_capture());+ const resolved = resolveGridCapture(args.capture);+ cells = resolved.views.length;+ cols = resolved.cols;}}- enforceCapturePixels2(cells, size, cols, context.captureLimits, compose);- const out = await run2();+ enforceCapturePixels(cells, size, cols, context.captureLimits, compose);+ const out = await run();if (out && typeof out === "object") {const media = out;const encoded = media.framesBase64 ?? (media.pngBase64 ? [media.pngBase64] : []);- enforceCaptureBytes2(encoded.map((value) => Buffer.from(value, "base64")), context.captureLimits);+ enforceCaptureBytes(encoded.map((value) => Buffer.from(value, "base64")), context.captureLimits);}return out;} catch (error) {@@ -30078,13 +28459,13 @@ class MetricsCollector {}this.cleanups = [];}- recordResultUsage(usage2) {- if (!usage2)+ recordResultUsage(usage) {+ if (!usage)return;const next = { ...this.usage };let recorded = false;for (const field of USAGE_FIELDS) {- const value = usage2[field];+ const value = usage[field];if (typeof value === "number") {next[field] = (next[field] ?? 0) + value;recorded = true;@@ -30152,20 +28533,20 @@ import {TextBlock} from "@strands-agents/sdk";var STALE_RENDER_PLACEHOLDER = "[earlier render image omitted — superseded by a newer render]";-function isImageBlock(block2) {- return block2.type === "imageBlock";+function isImageBlock(block) {+ return block.type === "imageBlock";}-function isToolResultBlock(block2) {- const b = block2;+function isToolResultBlock(block) {+ const b = block;return b.type === "toolResultBlock" && Array.isArray(b.content);}function pruneStaleRenderImages(messages, opts = {}) {const keep = opts.keep ?? 1;const bearing = [];for (const message of messages) {- for (const block2 of message.content) {- if (isToolResultBlock(block2) && block2.content.some(isImageBlock)) {- bearing.push(block2);+ for (const block of message.content) {+ if (isToolResultBlock(block) && block.content.some(isImageBlock)) {+ bearing.push(block);}}}@@ -30230,8 +28611,8 @@ import { BeforeToolsEvent } from "@strands-agents/sdk";var KILN_MUTATOR_TOOLS = new Set(["kiln_draft", "kiln_edit"]);function toolNamesInBatch(message) {const names = [];- for (const block2 of message.content) {- const b = block2;+ for (const block of message.content) {+ const b = block;if (b.type === "toolUseBlock" && typeof b.name === "string")names.push(b.name);}@@ -30265,10 +28646,10 @@ var OPENROUTER_EFFORTS = new Set(["xhigh", "high", "medium", "low", "minimal", "function modelConsumesSystemPromptCachePoints(model) {return model instanceof AnthropicModel || model instanceof BedrockModel;}-function toCachedSystemPrompt(text2, model) {+function toCachedSystemPrompt(text, model) {if (!modelConsumesSystemPromptCachePoints(model))- return text2;- return [new TextBlock2(text2), new CachePointBlock({ cacheType: "default" })];+ return text;+ return [new TextBlock2(text), new CachePointBlock({ cacheType: "default" })];}// src/agent/grade-refine.ts@@ -30370,9 +28751,9 @@ function lastMessageText(message) {if (!message)return;const parts = [];- for (const block2 of message.content) {- if (block2.type === "textBlock") {- const t = block2.text;+ for (const block of message.content) {+ if (block.type === "textBlock") {+ const t = block.text;if (typeof t === "string")parts.push(t);}@@ -30387,9 +28768,9 @@ async function runKilnAgent(opts) {const maxSteps = generationCallBudget.receipt().limit;const metrics = new MetricsCollector(opts.onEvent, maxSteps, generationCallBudget, opts.modelCallRole ?? "author", opts.modelCallAdmission);const surface = resolveToolSurface(opts.toolSurface);- const trustedCategory2 = opts.intent?.category ?? opts.category ?? "prop";+ const trustedCategory = opts.intent?.category ?? opts.category ?? "prop";const gradeAssessmentOptions = {- category: trustedCategory2,+ category: trustedCategory,...opts.intent ? { intent: opts.intent } : {},...opts.evaluatorPort ? { evaluatorPort: opts.evaluatorPort } : {},...opts.evaluatorProfile ? { evaluatorProfile: opts.evaluatorProfile } : {}@@ -30400,7 +28781,7 @@ async function runKilnAgent(opts) {const unifiedSink = { edits: [] };let counters;try {- const tools = buildAgentTools(surface, { ...opts, category: trustedCategory2, generationCallBudget }, { sink, editSink, unifiedSink });+ const tools = buildAgentTools(surface, { ...opts, category: trustedCategory, generationCallBudget }, { sink, editSink, unifiedSink });const allTools = opts.extraTools ? [...tools, ...opts.extraTools] : tools;const plugins = [];let systemPrompt;@@ -30450,7 +28831,7 @@ Before submitting, call kiln_screenshot once on your final code and check ` + "tconst userPrompt = buildUserPrompt({prompt: promptText,mode: "glb",- category: trustedCategory2,+ category: trustedCategory,...opts.intent ? { intent: opts.intent } : {},includeAnimation: opts.includeAnimation ?? false,...opts.style ? { style: opts.style } : {},@@ -30485,12 +28866,12 @@ ${surface === "unified" ? KILN_REFERENCE_IMAGE_DIRECTIVE_UNIFIED : KILN_REFERENCconst currentUnifiedRender = surface !== "unified" || unifiedSink.rendered === true && unifiedSink.renderedCode === captured;const salvage = captured && currentUnifiedRender ? await assessProgramGrade(captured, gradeAssessmentOptions) : undefined;if (!salvage?.ok) {- const collected2 = metrics.readMetrics();+ const collected = metrics.readMetrics();const qaNote = salvage?.qaBlocked ? ` (best-effort program rendered but was QA-blocked: ${salvage.error ?? "unknown blocker"})` : "";return {- toolCalls: collected2.toolCalls,- steps: collected2.steps,- ...collected2.usage ? { usage: collected2.usage } : {},+ toolCalls: collected.toolCalls,+ steps: collected.steps,+ ...collected.usage ? { usage: collected.usage } : {},...counters ? { counters } : {},error: `${metrics.capReason() ?? `kiln agent exceeded ${maxSteps} model calls (step cap) — aborted to bound cost`}${qaNote}`};@@ -30498,11 +28879,11 @@ ${surface === "unified" ? KILN_REFERENCE_IMAGE_DIRECTIVE_UNIFIED : KILN_REFERENCcapped = true;code = captured;} else if (surface === "unified" && !unifiedSink.finalized) {- const collected2 = metrics.readMetrics();+ const collected = metrics.readMetrics();return {- toolCalls: collected2.toolCalls,- steps: collected2.steps,- ...collected2.usage ? { usage: collected2.usage } : {},+ toolCalls: collected.toolCalls,+ steps: collected.steps,+ ...collected.usage ? { usage: collected.usage } : {},...counters ? { counters } : {},error: "kiln agent ended without a successful kiln_finalize of the current rendered buffer"};@@ -30595,7 +28976,7 @@ ${surface === "unified" ? KILN_REFERENCE_IMAGE_DIRECTIVE_UNIFIED : KILN_REFERENC}}export {- runKilnAgent,+ buildAgentTools,resolveToolSurface,- buildAgentTools+ runKilnAgent};diff --git a/dist/build.json b/dist/build.jsonindex e7adc587..1b26704f 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,11 +2,11 @@"schemaVersion": 1,"entries": {"mcp": {- "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",+ "identity": "sha256:af2a6684f46ede84dfc4e6fd6767dcdd9c328ba67e15eeccbce8772d3da9febc","engineVersion": "0.6.0",- "toolchain": "[email protected]",- "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",- "dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",+ "toolchain": "[email protected]",+ "sourceHash": "565273136255da40d3f931c9d8fd3cccc8dd8f5c613faa62c4631a7d65e97f88",+ "dependencyHash": "f18af97c1af621530742984fe6d5c51b351c11664bb61584cb3a7af91f68a541","dependencies": {"@gltf-transform/core": "^4.4.1","@gltf-transform/extensions": "^4.4.1",@@ -27,14 +27,14 @@},"target": "node","file": "mcp-server.mjs",- "bundleHash": "sha256:d3e0c45fdf10b553dbef69024deb044f9c08ba45b517aec784dc8c4a2f1c386b"+ "bundleHash": "sha256:639f5984ce3bd837a1ffe6415430c0feb5366e8b8d1d4cc9cd6493209ccc616d"},"cli": {- "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",+ "identity": "sha256:af2a6684f46ede84dfc4e6fd6767dcdd9c328ba67e15eeccbce8772d3da9febc","engineVersion": "0.6.0",- "toolchain": "[email protected]",- "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",- "dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",+ "toolchain": "[email protected]",+ "sourceHash": "565273136255da40d3f931c9d8fd3cccc8dd8f5c613faa62c4631a7d65e97f88",+ "dependencyHash": "f18af97c1af621530742984fe6d5c51b351c11664bb61584cb3a7af91f68a541","dependencies": {"@gltf-transform/core": "^4.4.1","@gltf-transform/extensions": "^4.4.1",@@ -55,14 +55,14 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:2858b8cab4cce9fb30685743240b257dddd185daa0611bba07645ec153fb6e61"+ "bundleHash": "sha256:0eb6b7077598c1d61761e6391f2c776980dd8aed1ebaf5f584aa54fcd8e53e2f"},"worker": {- "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",+ "identity": "sha256:af2a6684f46ede84dfc4e6fd6767dcdd9c328ba67e15eeccbce8772d3da9febc","engineVersion": "0.6.0",- "toolchain": "[email protected]",- "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",- "dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",+ "toolchain": "[email protected]",+ "sourceHash": "565273136255da40d3f931c9d8fd3cccc8dd8f5c613faa62c4631a7d65e97f88",+ "dependencyHash": "f18af97c1af621530742984fe6d5c51b351c11664bb61584cb3a7af91f68a541","dependencies": {"@gltf-transform/core": "^4.4.1","@gltf-transform/extensions": "^4.4.1",@@ -83,14 +83,14 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:bb463f3b33b7474ed8f2c0626fa4bde8c64101182b11aac042491f7077e6cbdd"+ "bundleHash": "sha256:c8d8e432a5ae29b4f6621bf64bb4b7f6f7b77cf9fd4d8094779c6c5749f811f2"},"agent-run": {- "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",+ "identity": "sha256:af2a6684f46ede84dfc4e6fd6767dcdd9c328ba67e15eeccbce8772d3da9febc","engineVersion": "0.6.0",- "toolchain": "[email protected]",- "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",- "dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",+ "toolchain": "[email protected]",+ "sourceHash": "565273136255da40d3f931c9d8fd3cccc8dd8f5c613faa62c4631a7d65e97f88",+ "dependencyHash": "f18af97c1af621530742984fe6d5c51b351c11664bb61584cb3a7af91f68a541","dependencies": {"@gltf-transform/core": "^4.4.1","@gltf-transform/extensions": "^4.4.1",@@ -111,14 +111,14 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:2fcd14c02e8a8b168396623ca851f206529b2e5559eb87162ed4de3c699d73ee"+ "bundleHash": "sha256:4253f648f9c8395aaecfa2201a69feeaa503e5c58b81a891fbd5a41df0277f6c"},"agent-providers": {- "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",+ "identity": "sha256:af2a6684f46ede84dfc4e6fd6767dcdd9c328ba67e15eeccbce8772d3da9febc","engineVersion": "0.6.0",- "toolchain": "[email protected]",- "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",- "dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",+ "toolchain": "[email protected]",+ "sourceHash": "565273136255da40d3f931c9d8fd3cccc8dd8f5c613faa62c4631a7d65e97f88",+ "dependencyHash": "f18af97c1af621530742984fe6d5c51b351c11664bb61584cb3a7af91f68a541","dependencies": {"@gltf-transform/core": "^4.4.1","@gltf-transform/extensions": "^4.4.1",@@ -139,7 +139,7 @@},"target": "node","file": "agent-providers.mjs",- "bundleHash": "sha256:367808f475150d9591ba39b7abe48531015adc447ae369ad471b5b91289033a6"+ "bundleHash": "sha256:0a05d7630c6f7f1394ce7ecf063daae69c7137a364f9a975c595b39b35ac6eb5"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex d717ba09..4e9d2464 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -1,5 +1,4 @@#!/usr/bin/env node-import { createRequire } from "node:module";var __defProp = Object.defineProperty;var __returnValue = (v) => v;function __exportSetter(name, newValue) {@@ -14,8 +13,17 @@ var __export = (target, all) => {set: __exportSetter.bind(all, name)});};-var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);-var __require = /* @__PURE__ */ createRequire(import.meta.url);+var __esm = (fn, res, err) => () => {+ if (fn)+ try {+ res = fn(fn = 0);+ } catch (e) {+ err = [e];+ }+ if (err)+ throw err[0];+ return res;+};// src/cli-output.tsimport { mkdir } from "node:fs/promises";@@ -2782,7 +2790,7 @@ function readSemanticMetadataV1FromExtras(extras) {const result = validateSemanticMetadataV1(value);return result.valid ? result.value : undefined;}-var KILN_SEMANTIC_EXTRAS_KEY = "kilnSemantic", KILN_SEMANTIC_SCHEMA_VERSION = 1, KILN_SEMANTIC_ROLES, isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isNonEmptyString2 = (value) => typeof value === "string" && value.trim().length > 0 && value === value.trim(), isFiniteTuple = (value, length2) => Array.isArray(value) && value.length === length2 && value.every((component) => typeof component === "number" && Number.isFinite(component)), cloneTuple3 = (value) => [+var KILN_SEMANTIC_EXTRAS_KEY = "kilnSemantic", KILN_SEMANTIC_SCHEMA_VERSION = 1, KILN_SEMANTIC_ROLES, isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isNonEmptyString2 = (value) => typeof value === "string" && value.trim().length > 0 && value === value.trim(), isFiniteTuple = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), cloneTuple3 = (value) => [value[0],value[1],value[2]@@ -3905,8 +3913,8 @@ function validateCharacterJointDescriptorV1(value) {const forwardValid = validateUnitVector(forwardAxis, "localForwardAxis", issues);const bendValid = validateUnitVector(bendAxis, "localBendAxis", issues);if (forwardValid && bendValid) {- const dot2 = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];- if (Math.abs(dot2) > 0.000001) {+ const dot = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];+ if (Math.abs(dot) > 0.000001) {issues.push({code: "NON_ORTHOGONAL_AXES",path: "localBendAxis",@@ -4211,7 +4219,7 @@ function collectCharacterJointNodes(root) {visit(root, "", 0);return joints;}-var KILN_CHARACTER_JOINT_EXTRAS_KEY = "kilnCharacterJoint", KILN_CHARACTER_RIG_EXTRAS_KEY = "kilnCharacterRig", KILN_CHARACTER_JOINT_SCHEMA_VERSION = 1, CHARACTER_BODY_PLANS2, CHARACTER_JOINT_SIDES, IDENTITY_QUATERNION, UNIT_SCALE, FORWARD_AXIS, BEND_AXIS, isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isFiniteTuple2 = (value, length2) => Array.isArray(value) && value.length === length2 && value.every((component) => typeof component === "number" && Number.isFinite(component)), tuple3 = (value) => [value[0], value[1], value[2]], tuple4 = (value) => [+var KILN_CHARACTER_JOINT_EXTRAS_KEY = "kilnCharacterJoint", KILN_CHARACTER_RIG_EXTRAS_KEY = "kilnCharacterRig", KILN_CHARACTER_JOINT_SCHEMA_VERSION = 1, CHARACTER_BODY_PLANS2, CHARACTER_JOINT_SIDES, IDENTITY_QUATERNION, UNIT_SCALE, FORWARD_AXIS, BEND_AXIS, isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isFiniteTuple2 = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), tuple3 = (value) => [value[0], value[1], value[2]], tuple4 = (value) => [value[0],value[1],value[2],@@ -4395,12 +4403,12 @@ function block(intent, code, message, options) {});}function targetName(trackName) {- const dot2 = trackName.lastIndexOf(".");- return dot2 > 0 ? trackName.slice(0, dot2) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(0, dot) : undefined;}function propertyName(trackName) {- const dot2 = trackName.lastIndexOf(".");- return dot2 > 0 ? trackName.slice(dot2 + 1) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(dot + 1) : undefined;}function blockerKey(finding) {return [@@ -4684,8 +4692,8 @@ function endpointDelta(track, size) {const lastOffset = track.values.length - size;const last = Array.from({ length: size }, (_, index) => Number(track.values[lastOffset + index]));if (track.name.endsWith(".quaternion") && size === 4) {- const dot2 = Math.abs(first.reduce((sum, value, index) => sum + value * last[index], 0));- return Math.abs(1 - Math.min(1, dot2));+ const dot = Math.abs(first.reduce((sum, value, index) => sum + value * last[index], 0));+ return Math.abs(1 - Math.min(1, dot));}return Math.max(...first.map((value, index) => Math.abs(value - last[index])));}@@ -5136,12 +5144,12 @@ function forwardMarkerFindings(context, root) {});}function trackTarget(trackName) {- const dot2 = trackName.lastIndexOf(".");- return dot2 > 0 ? trackName.slice(0, dot2) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(0, dot) : undefined;}function trackProperty(trackName) {- const dot2 = trackName.lastIndexOf(".");- return dot2 > 0 ? trackName.slice(dot2 + 1) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(dot + 1) : undefined;}function applyTrack(root, track, time) {const target = trackTarget(track.name);@@ -5442,10 +5450,10 @@ function positive(value, name) {}function normalizedQuaternion(value) {const source = value ?? [0, 0, 0, 1];- const length2 = Math.hypot(source[0], source[1], source[2], source[3]);- if (!Number.isFinite(length2) || length2 <= 0.000000001)+ const length = Math.hypot(source[0], source[1], source[2], source[3]);+ if (!Number.isFinite(length) || length <= 0.000000001)throw new TypeError("socket rotation must be a finite quaternion");- return [source[0] / length2, source[1] / length2, source[2] / length2, source[3] / length2];+ return [source[0] / length, source[1] / length, source[2] / length, source[3] / length];}function semantic2(roles, options = {}) {return {@@ -5777,8 +5785,8 @@ function legacyAssemblies(root) {});}function resolveVehicleWheelAssemblies(root) {- const semantic3 = semanticAssemblies(root);- return semantic3.length > 0 ? semantic3 : legacyAssemblies(root);+ const semantic = semanticAssemblies(root);+ return semantic.length > 0 ? semantic : legacyAssemblies(root);}function hasCanonicalVehicleFront(root) {let found = false;@@ -5863,7 +5871,7 @@ function probeLocalFrameFromQuaternion(id, origin, quaternion) {function createOrientedProbeBox3(input) {if (!input.id.trim())throw new TypeError("Oriented probe box ID must be non-empty.");- if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent2) => extent2 <= 0)) {+ if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent) => extent <= 0)) {throw new TypeError("Oriented probe box half-extents must be finite and greater than zero.");}return {@@ -6087,8 +6095,8 @@ function bilateralSymmetryFindings2(context, root, wheels) {const centerDelta = Math.hypot(a.x - b.x, a.y - b.y, a.z + b.z);const radiusDelta = Math.abs((left.radius ?? 0) - (right.radius ?? 0));const widthDelta = Math.abs((left.width ?? 0) - (right.width ?? 0));- const scale2 = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(0.01, scale2 * SYMMETRY_RATIO);+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(0.01, scale * SYMMETRY_RATIO);const maximum = Math.max(centerDelta, radiusDelta, widthDelta);if (maximum <= threshold)continue;@@ -6159,8 +6167,8 @@ function probeBox(id, root, bounds) {const size = bounds.getSize(new THREE7.Vector3);const position = new THREE7.Vector3;const quaternion = new THREE7.Quaternion;- const scale2 = new THREE7.Vector3;- root.matrixWorld.decompose(position, quaternion, scale2);+ const scale = new THREE7.Vector3;+ root.matrixWorld.decompose(position, quaternion, scale);const xAxis = new THREE7.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();const yAxis = new THREE7.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();const zAxis = new THREE7.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();@@ -6174,9 +6182,9 @@ function probeBox(id, root, bounds) {zAxis: tuple(zAxis)}),halfExtents: [- size.x * Math.abs(scale2.x) / 2,- size.y * Math.abs(scale2.y) / 2,- size.z * Math.abs(scale2.z) / 2+ size.x * Math.abs(scale.x) / 2,+ size.y * Math.abs(scale.y) / 2,+ size.z * Math.abs(scale.z) / 2]});}@@ -6282,7 +6290,7 @@ function weldedBoundaryEdges(root, loop) {if (!positions)return;const matrix = inverse.clone().multiply(node.matrixWorld);- const keys = Array.from({ length: positions.count }, (_, index2) => vertexKey(new THREE7.Vector3().fromBufferAttribute(positions, index2).applyMatrix4(matrix)));+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE7.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));const index = node.geometry.getIndex();const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);for (let offset = 0;offset + 2 < indices.length; offset += 3) {@@ -6306,11 +6314,11 @@ function trackProfileFindings(context, root, intent) {const loops = [];const roadWheels = [];root.traverse((node) => {- const roles2 = semanticRoles(node);- if (roles2.some((role) => role.startsWith("track.loop.")) || roles2.some((role) => role.startsWith("support.track."))) {+ const roles = semanticRoles(node);+ if (roles.some((role) => role.startsWith("track.loop.")) || roles.some((role) => role.startsWith("support.track."))) {loops.push(node);}- if (roles2.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {+ if (roles.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {roadWheels.push(node);}});@@ -6425,8 +6433,8 @@ function finding(context, value) {viewHints: value.viewHints ?? ["vehicle.underbody", "vehicle.wheel-section"]};}-function localPoint2(rootInverse2, value) {- return value.clone().applyMatrix4(rootInverse2);+function localPoint2(rootInverse, value) {+ return value.clone().applyMatrix4(rootInverse);}function rootAxis(root, axis) {root.updateWorldMatrix(true, false);@@ -6611,14 +6619,14 @@ function duplicateAssemblyFindings(context, root, wheels) {const right = wheels[b];const sameDeclaredCorner = left.side !== undefined && left.side === right.side && left.index !== undefined && left.index === right.index;const centerDelta = localPoint2(inverse, left.centerWorld).distanceTo(localPoint2(inverse, right.centerWorld));- const scale2 = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(CENTER_MINIMUM, scale2 * CENTER_RATIO);+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(CENTER_MINIMUM, scale * CENTER_RATIO);if (!sameDeclaredCorner && centerDelta > threshold)continue;- const semantic3 = left.source === "semantic" && right.source === "semantic";+ const semantic = left.source === "semantic" && right.source === "semantic";findings.push(finding(context, {code: "VEH_DUPLICATE_ASSEMBLY",- disposition: semantic3 ? "block" : "warn",+ disposition: semantic ? "block" : "warn",message: `Wheel assemblies ${left.id} and ${right.id} resolve to the same ` + `${sameDeclaredCorner ? `${left.side}-${left.index} corner` : "scale-relative center"}.`,affected: { node: right.root.name },measurement: {@@ -6667,7 +6675,7 @@ function contactFindings2(context, root, intent, wheels) {}return findings;}-function renderableMinYInRoot(rootInverse2, node) {+function renderableMinYInRoot(rootInverse, node) {let minimum = Infinity;node.traverse((part) => {if (!(part instanceof THREE8.Mesh) || !(part.geometry instanceof THREE8.BufferGeometry))@@ -6676,7 +6684,7 @@ function renderableMinYInRoot(rootInverse2, node) {const bounds = part.geometry.boundingBox;if (!bounds)return;- const matrix = rootInverse2.clone().multiply(part.matrixWorld);+ const matrix = rootInverse.clone().multiply(part.matrixWorld);for (const x of [bounds.min.x, bounds.max.x]) {for (const y of [bounds.min.y, bounds.max.y]) {for (const z of [bounds.min.z, bounds.max.z]) {@@ -6695,16 +6703,16 @@ function supportContactFindings(context, root, intent) {const explicitContacts = [];const supports = [];root.traverse((node) => {- const roles2 = readSemanticMetadataV1(node)?.roles ?? [];- const isWheelContact = roles2.some((role) => role.startsWith("wheel.contact."));- if (!isWheelContact && roles2.some((role) => role.startsWith("contact."))) {+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ const isWheelContact = roles.some((role) => role.startsWith("wheel.contact."));+ if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {explicitContacts.push({node,contactY: localPoint2(inverse, new THREE8.Vector3().setFromMatrixPosition(node.matrixWorld)).y,source: "contact"});}- if (roles2.some((role) => role.startsWith("support."))) {+ if (roles.some((role) => role.startsWith("support."))) {const contactY = renderableMinYInRoot(inverse, node);if (contactY !== undefined)supports.push({ node, contactY, source: "support" });@@ -6832,7 +6840,7 @@ function propulsionFindings(context, root, intent) {});const findings = [];root.updateWorldMatrix(true, false);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();for (const kind of expectedKinds) {const candidates = components.filter((part) => part.kind === kind);if (candidates.length === 0) {@@ -6849,7 +6857,7 @@ function propulsionFindings(context, root, intent) {const box = new THREE8.Box3().setFromObject(component.node);const center = box.isEmpty() ? undefined : box.getCenter(new THREE8.Vector3);const pivotCenter = pivot ? new THREE8.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;- const delta = center && pivotCenter ? localPoint2(rootInverse2, center).distanceTo(localPoint2(rootInverse2, pivotCenter)) : Infinity;+ const delta = center && pivotCenter ? localPoint2(rootInverse, center).distanceTo(localPoint2(rootInverse, pivotCenter)) : Infinity;const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);const canonicalAxis = kind === "rotor" ? new THREE8.Vector3(0, 1, 0) : new THREE8.Vector3(1, 0, 0);@@ -6920,7 +6928,7 @@ var init_vehicle2 = __esm(() => {owner: KILN_ENGINE_QA_OWNER,promotion: conformancePromotionAuthorization("vehicle-qa-v1", "src/qa/vehicle.test.ts", "4bffa0dff0ed33be2ce7003ee36ac33efc5b4900e57d390898e43551912e626b"),defaultMode: "enforce",- evaluate: (context) => evaluateVehicleQa(context).filter((finding2) => finding2.disposition === "block")+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition === "block")};VEHICLE_ADVISORY_QA_RULE = {id: "VEHICLE_ADVISORY_PROFILE",@@ -6929,7 +6937,7 @@ var init_vehicle2 = __esm(() => {ruleClass: "heuristic",owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",- evaluate: (context) => evaluateVehicleQa(context).filter((finding2) => finding2.disposition !== "block")+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition !== "block")};VEHICLE_QA_RULES = [VEHICLE_QA_RULE,@@ -6954,17 +6962,17 @@ function pathOf(node, root) {}return names.reverse().join("/");}-function localPoint3(rootInverse2, node) {- return node.getWorldPosition(new THREE9.Vector3).applyMatrix4(rootInverse2);+function localPoint3(rootInverse, node) {+ return node.getWorldPosition(new THREE9.Vector3).applyMatrix4(rootInverse);}-function meshLocalBox(mesh, rootInverse2) {+function meshLocalBox(mesh, rootInverse) {if (!(mesh.geometry instanceof THREE9.BufferGeometry))return;mesh.geometry.computeBoundingBox();const source = mesh.geometry.boundingBox;if (!source || source.isEmpty())return;- const transform = rootInverse2.clone().multiply(mesh.matrixWorld);+ const transform = rootInverse.clone().multiply(mesh.matrixWorld);const result = new THREE9.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {@@ -6985,8 +6993,8 @@ function collectRenderableBounds(root) {const box = meshLocalBox(node, inverse);if (!box)return;- const roles2 = rolesOf(node);- values.push({ node, box, roles: roles2, source: roles2.length > 0 ? "semantic" : "fallback" });+ const roles = rolesOf(node);+ values.push({ node, box, roles, source: roles.length > 0 ? "semantic" : "fallback" });});return values;}@@ -7007,15 +7015,15 @@ function evaluateVegetationContactQa(context) {const semanticSupports = [];root.traverse((node) => {const metadata = readSemanticMetadataV1(node);- const roles2 = metadata?.roles ?? [];- if (roles2.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {+ const roles = metadata?.roles ?? [];+ if (roles.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {const frame = metadata?.frames.find((value) => value.id === "ground-contact" || value.id === "vegetation-ground-contact");contacts.push({node,...frame ? { frameTranslation: frame.translation } : {}});}- if (roles2.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {+ if (roles.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {semanticSupports.push(node);}});@@ -7116,8 +7124,8 @@ function evaluateVegetationScopeQa(context) {const materialEvidence = materialNames(value.node).some((name) => CLUTTER_NAME.test(name));const footprintRatio = size.x * size.z / Math.max(0.000000001, overallSize.x * overallSize.z);const flatEvidence = footprintRatio >= 0.35 && size.y <= Math.max(0.08, overallSize.y * 0.08) && center.y <= VEGETATION_CONTACT_TOLERANCE_METERS + size.y;- const evidence2 = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);- if (evidence2.length < 2)+ const evidence = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);+ if (evidence.length < 2)continue;findings.push(finding2(context, {code: "VEG_SCOPE_EXTRA",@@ -7150,7 +7158,7 @@ function unionVolume(boxes) {const size = union.getSize(new THREE9.Vector3);return size.x * size.y * size.z;}-function projectedOccupancy(boxes, axes2) {+function projectedOccupancy(boxes, axes) {if (boxes.length === 0)return 0;const minimum = [Infinity, Infinity];@@ -7159,8 +7167,8 @@ function projectedOccupancy(boxes, axes2) {const min = [box.min.x, box.min.y, box.min.z];const max = [box.max.x, box.max.y, box.max.z];for (const dimension of [0, 1]) {- minimum[dimension] = Math.min(minimum[dimension], min[axes2[dimension]]);- maximum[dimension] = Math.max(maximum[dimension], max[axes2[dimension]]);+ minimum[dimension] = Math.min(minimum[dimension], min[axes[dimension]]);+ maximum[dimension] = Math.max(maximum[dimension], max[axes[dimension]]);}}const spans = [maximum[0] - minimum[0], maximum[1] - minimum[1]];@@ -7170,10 +7178,10 @@ function projectedOccupancy(boxes, axes2) {for (const box of boxes) {const min = [box.min.x, box.min.y, box.min.z];const max = [box.max.x, box.max.y, box.max.z];- const x0 = Math.max(0, Math.floor((min[axes2[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes2[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const y0 = Math.max(0, Math.floor((min[axes2[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));- const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes2[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ const x0 = Math.max(0, Math.floor((min[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const y0 = Math.max(0, Math.floor((min[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));for (let y = y0;y <= y1; y++) {for (let x = x0;x <= x1; x++)occupied[y * RASTER_SIZE + x] = 1;@@ -7188,9 +7196,9 @@ function matchesAny(value, patterns) {function measurementSource(values) {if (values.length === 0)return "none";- const semantic3 = values.some((value) => value.source === "semantic");+ const semantic = values.some((value) => value.source === "semantic");const fallback = values.some((value) => value.source === "fallback");- return semantic3 && fallback ? "mixed" : semantic3 ? "semantic" : "fallback";+ return semantic && fallback ? "mixed" : semantic ? "semantic" : "fallback";}function roleOrNameSource(value, patterns) {if (value.roles.some((role) => patterns.some((pattern) => pattern.test(role))))@@ -7214,7 +7222,7 @@ function growthCandidates(root) {function boxDistanceToPoint(box, point) {return box.distanceToPoint(point);}-function endpointRadius(position, axis, axisValue, tolerance, scale2) {+function endpointRadius(position, axis, axisValue, tolerance, scale) {const radialAxes = [0, 1, 2].filter((value) => value !== axis);const points = [];const point = new THREE9.Vector3;@@ -7232,8 +7240,8 @@ function endpointRadius(position, axis, axisValue, tolerance, scale2) {}let radius = 0;for (const value of points) {- const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale2.getComponent(radialAxes[0]));- const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale2.getComponent(radialAxes[1]));+ const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale.getComponent(radialAxes[0]));+ const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale.getComponent(radialAxes[1]));radius = Math.max(radius, Math.hypot(a, b));}return { center, radius };@@ -7282,10 +7290,10 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {}const baseRadius = firstIsBase ? first.radius : second.radius;const tipRadius = firstIsBase ? second.radius : first.radius;- const length3 = firstPoint.distanceTo(secondPoint);+ const length = firstPoint.distanceTo(secondPoint);const averageRadius = (baseRadius + tipRadius) / 2;const taperRatio = baseRadius > 0.000000001 ? tipRadius / baseRadius : null;- const lengthRadiusRatio = averageRadius > 0.000000001 ? length3 / averageRadius : null;+ const lengthRadiusRatio = averageRadius > 0.000000001 ? length / averageRadius : null;const selected = band[candidate.kind];const taperOutlier = taperRatio !== null && (taperRatio < selected.taper[0] || taperRatio > selected.taper[1]);const lengthRadiusOutlier = lengthRadiusRatio !== null && (lengthRadiusRatio < selected.lengthRadius[0] || lengthRadiusRatio > selected.lengthRadius[1]);@@ -7294,7 +7302,7 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {nodePath: pathOf(candidate.node, root),kind: candidate.kind,source: candidate.growthSource,- lengthMeters: stable3(length3),+ lengthMeters: stable3(length),baseRadiusMeters: stable3(baseRadius),tipRadiusMeters: stable3(tipRadius),taperRatio: taperRatio === null ? null : stable3(taperRatio),@@ -7414,12 +7422,12 @@ function evaluateVegetationFoliageAttachmentQa(context) {}function relativeTransformSignature(root, node) {const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);- const scale2 = new THREE9.Vector3;+ const scale = new THREE9.Vector3;const quaternion = new THREE9.Quaternion;- matrix.decompose(new THREE9.Vector3, quaternion, scale2);+ matrix.decompose(new THREE9.Vector3, quaternion, scale);if (quaternion.w < 0)quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);- const values = [...scale2.toArray(), ...quaternion.toArray()].map((value) => stable3(value));+ const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable3(value));return values.join(",");}function measureVegetationRepetition(intent, root) {@@ -7802,23 +7810,23 @@ function transformedBox(source, transform) {}function collectParts(root) {root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverse((node) => {- const roles2 = rolesOf2(node);+ const roles = rolesOf2(node);const renderable = node instanceof THREE10.Mesh;let box;if (renderable && node.geometry instanceof THREE10.BufferGeometry) {node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {- box = transformedBox(node.geometry.boundingBox, rootInverse2.clone().multiply(node.matrixWorld));+ box = transformedBox(node.geometry.boundingBox, rootInverse.clone().multiply(node.matrixWorld));}- } else if (roles2.length > 0) {- box = transformedBox(new THREE10.Box3(new THREE10.Vector3(-0.5, -0.5, -0.5), new THREE10.Vector3(0.5, 0.5, 0.5)), rootInverse2.clone().multiply(node.matrixWorld));+ } else if (roles.length > 0) {+ box = transformedBox(new THREE10.Box3(new THREE10.Vector3(-0.5, -0.5, -0.5), new THREE10.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));}if (box?.isEmpty())box = undefined;- result.push({ node, roles: roles2, ...box ? { box } : {}, renderable });+ result.push({ node, roles, ...box ? { box } : {}, renderable });});return result;}@@ -8489,35 +8497,35 @@ function isEvidence(value) {const candidate = value;return candidate.schemaVersion === 1 && typeof candidate.silhouetteIoU === "number" && typeof candidate.colorAgreement === "number" && typeof candidate.reference === "object" && typeof candidate.rendered === "object";}-function referenceComparisonFindings(evidence2, profile) {- if (evidence2.reference.coverage <= 0 || evidence2.rendered.coverage <= 0)+function referenceComparisonFindings(evidence, profile) {+ if (evidence.reference.coverage <= 0 || evidence.rendered.coverage <= 0)return [];const findings = [];- if (evidence2.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {+ if (evidence.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {findings.push({code: "REF_SILHOUETTE_AGREEMENT",disposition: "observe",dimension: "promptAlignment",profile,- message: `The asset's outline agrees with the reference image on ${(evidence2.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,+ message: `The asset's outline agrees with the reference image on ${(evidence.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,measurement: {name: "silhouetteIoU",- actual: evidence2.silhouetteIoU,+ actual: evidence.silhouetteIoU,threshold: SILHOUETTE_IOU_OBSERVE},repairText: "Compare the reference against the rendered views and adjust the overall proportions — the outline is the part that disagrees, not the detail."});}- if (evidence2.colorAgreement < COLOR_AGREEMENT_OBSERVE) {+ if (evidence.colorAgreement < COLOR_AGREEMENT_OBSERVE) {findings.push({code: "REF_COLOR_AGREEMENT",disposition: "observe",dimension: "promptAlignment",profile,- message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence2.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,+ message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,measurement: {name: "colorAgreement",- actual: evidence2.colorAgreement,+ actual: evidence.colorAgreement,threshold: COLOR_AGREEMENT_OBSERVE},repairText: "Set the base colours from the reference image rather than from the prompt wording, then re-render."@@ -8536,10 +8544,10 @@ var init_reference_comparison = __esm(() => {owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",evaluate(context) {- const evidence2 = context.derivedEvidence?.["referenceComparison"];- if (!isEvidence(evidence2))+ const evidence = context.derivedEvidence?.["referenceComparison"];+ if (!isEvidence(evidence))return [];- return referenceComparisonFindings(evidence2, "reference.comparison");+ return referenceComparisonFindings(evidence, "reference.comparison");}});});@@ -8639,7 +8647,7 @@ async function analyzePartPenetration(root) {const Module = await import("manifold-3d");const wasm = await Module.default();wasm.setup();- const { Manifold, Mesh: Mesh6 } = wasm;+ const { Manifold, Mesh } = wasm;const cache = new Map;const build = (part) => {if (cache.has(part.mesh))@@ -8648,7 +8656,7 @@ async function analyzePartPenetration(root) {try {const arrays = meshToArrays(part.mesh);if (arrays) {- const mesh = new Mesh6({ numProp: 3, ...arrays });+ const mesh = new Mesh({ numProp: 3, ...arrays });mesh.merge();solid = new Manifold(mesh);} else {@@ -8701,8 +8709,8 @@ async function analyzePartPenetration(root) {return base;}function readEvidence(context) {- const evidence2 = context.derivedEvidence?.["partPenetration"];- return evidence2?.schemaVersion === 1 ? evidence2 : undefined;+ const evidence = context.derivedEvidence?.["partPenetration"];+ return evidence?.schemaVersion === 1 ? evidence : undefined;}var MAX_PART_TRIANGLES = 20000, MAX_NARROW_PHASE_PAIRS = 64, CONTACT_VOLUME_FRACTION = 0.001, round = (n) => Math.round(n * 1e9) / 1e9, SELF_INTERSECTION_QA_RULE;var init_self_intersection = __esm(() => {@@ -8715,10 +8723,10 @@ var init_self_intersection = __esm(() => {owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",evaluate(context) {- const evidence2 = readEvidence(context);- if (!evidence2)+ const evidence = readEvidence(context);+ if (!evidence)return [];- const findings = evidence2.penetrations.map((pair) => ({+ const findings = evidence.penetrations.map((pair) => ({code: "GEO_PART_SELF_INTERSECTION",disposition: "observe",dimension: "visualQuality",@@ -8732,13 +8740,13 @@ var init_self_intersection = __esm(() => {},repairText: "Move one part clear of the other, or subtract it with boolDiff so the overlap becomes a real cut instead of two solids in the same place."}));- if (evidence2.truncated) {+ if (evidence.truncated) {findings.push({code: "GEO_PART_SELF_INTERSECTION_TRUNCATED",disposition: "observe",dimension: "visualQuality",profile: "geometry.selfIntersection",- message: `Only ${evidence2.pairsTested} of ${evidence2.candidatePairs} overlapping part pairs were checked (analysis budget). Parts beyond that were not examined.`+ message: `Only ${evidence.pairsTested} of ${evidence.candidatePairs} overlapping part pairs were checked (analysis budget). Parts beyond that were not examined.`});}return findings;@@ -8782,20 +8790,20 @@ function orientedBoxFromLocalBounds(root, node, source) {return;const position = new THREE13.Vector3;const rotation = new THREE13.Quaternion;- const scale2 = new THREE13.Vector3;- relative.decompose(position, rotation, scale2);- const recomposed = new THREE13.Matrix4().compose(position, rotation, scale2);+ const scale = new THREE13.Vector3;+ relative.decompose(position, rotation, scale);+ const recomposed = new THREE13.Matrix4().compose(position, rotation, scale);const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));if (residual > 0.00001)return;const center = source.getCenter(new THREE13.Vector3).applyMatrix4(relative);const sourceHalf = source.getSize(new THREE13.Vector3).multiplyScalar(0.5);const halfExtents = [- Math.abs(sourceHalf.x * scale2.x),- Math.abs(sourceHalf.y * scale2.y),- Math.abs(sourceHalf.z * scale2.z)+ Math.abs(sourceHalf.x * scale.x),+ Math.abs(sourceHalf.y * scale.y),+ Math.abs(sourceHalf.z * scale.z)];- if (halfExtents.some((extent2) => !Number.isFinite(extent2) || extent2 <= 0.000000001))+ if (halfExtents.some((extent) => !Number.isFinite(extent) || extent <= 0.000000001))return;rotation.normalize();return createOrientedProbeBox3({@@ -8806,10 +8814,10 @@ function orientedBoxFromLocalBounds(root, node, source) {}function collectParts4(root) {root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverse((node) => {- const roles2 = rolesOf3(node);+ const roles = rolesOf3(node);const renderable = node instanceof THREE13.Mesh;let box;let orientedBox;@@ -8819,18 +8827,18 @@ function collectParts4(root) {if (node.geometry.boundingBox) {source = node.geometry.boundingBox;}- } else if (roles2.length > 0) {+ } else if (roles.length > 0) {source = new THREE13.Box3(new THREE13.Vector3(-0.5, -0.5, -0.5), new THREE13.Vector3(0.5, 0.5, 0.5));}if (source) {- box = transformedBox2(source, rootInverse2.clone().multiply(node.matrixWorld));+ box = transformedBox2(source, rootInverse.clone().multiply(node.matrixWorld));orientedBox = orientedBoxFromLocalBounds(root, node, source);}if (box?.isEmpty())box = undefined;result.push({node,- roles: roles2,+ roles,...box ? { box } : {},...orientedBox ? { orientedBox } : {},renderable@@ -8847,8 +8855,8 @@ function resolveSocket(root, node, socket) {if (!frame)return;root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();- const point = new THREE13.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse2);+ const rootInverse = root.matrixWorld.clone().invert();+ const point = new THREE13.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);const rootInverseQuaternion = root.getWorldQuaternion(new THREE13.Quaternion).invert();const rotation = node.getWorldQuaternion(new THREE13.Quaternion).multiply(new THREE13.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();return {@@ -8868,9 +8876,9 @@ function resolveEnvironmentSockets(root) {for (const socket of metadata?.sockets ?? []) {if (!socket.type.startsWith("environment."))continue;- const resolved2 = resolveSocket(root, node, socket);- if (resolved2)- result.push(resolved2);+ const resolved = resolveSocket(root, node, socket);+ if (resolved)+ result.push(resolved);}});return result.sort((a, b) => `${a.type}:${a.id}`.localeCompare(`${b.type}:${b.id}`));@@ -8906,11 +8914,11 @@ function evaluateEnvironmentSocketQa(context) {}for (const axis of ["x", "z"]) {const negative = socketByType(sockets, `environment.tile.${axis}-negative`);- const positive2 = socketByType(sockets, `environment.tile.${axis}-positive`);- if (!negative || !positive2)+ const positive = socketByType(sockets, `environment.tile.${axis}-positive`);+ if (!negative || !positive)continue;- const cross2 = axis === "x" ? 2 : 0;- const crossDelta = Math.hypot(negative.translation[1] - positive2.translation[1], negative.translation[cross2] - positive2.translation[cross2]);+ const cross = axis === "x" ? 2 : 0;+ const crossDelta = Math.hypot(negative.translation[1] - positive.translation[1], negative.translation[cross] - positive.translation[cross]);if (crossDelta <= SOCKET_ALIGNMENT_TOLERANCE_METERS)continue;findings.push(finding4(context, {@@ -8918,7 +8926,7 @@ function evaluateEnvironmentSocketQa(context) {disposition: "block",dimension: "categoryReadiness",message: `Opposing ${axis.toUpperCase()} tile sockets differ by ${crossDelta.toFixed(6)} m in their paired height/cross-axis frame.`,- affected: { node: positive2.node, attribute: positive2.id },+ affected: { node: positive.node, attribute: positive.id },measurement: {name: "socketCrossAxisDelta",actual: stable5(crossDelta),@@ -8979,15 +8987,15 @@ function boundarySamples(root, axis, side, bins = 12) {}function edgePairMeasurements(root, axis, sockets) {const negative = boundarySamples(root, axis, "negative");- const positive2 = boundarySamples(root, axis, "positive");+ const positive = boundarySamples(root, axis, "positive");const negativeByBin = new Map(negative.map((sample) => [sample.bin, sample]));- const pairs = positive2.flatMap((sample) => {+ const pairs = positive.flatMap((sample) => {const other = negativeByBin.get(sample.bin);return other ? [[other, sample]] : [];});const unionBins = new Set([...negative.map((sample) => sample.bin),- ...positive2.map((sample) => sample.bin)+ ...positive.map((sample) => sample.bin)]);const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE13.MathUtils.radToDeg(Math.acos(THREE13.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;@@ -9370,12 +9378,12 @@ function artifactEvidence(context) {function finding5(context, value, profile = "vfx.w7") {return { ...value, profile: context.intent.qaProfile || profile };}-function measureVfxRuntimeCostV1(evidence2) {+function measureVfxRuntimeCostV1(evidence) {let blendedScreenAreaRatio = 0;let transparentLayerCount = 0;let overdrawProxy = 0;let textureMemoryBytes = 0;- for (const material of evidence2.materials) {+ for (const material of evidence.materials) {textureMemoryBytes += material.textureMemoryBytes;if (material.alphaMode !== "blend")continue;@@ -9389,7 +9397,7 @@ function measureVfxRuntimeCostV1(evidence2) {transparentLayerCount,overdrawProxy: stable6(overdrawProxy),textureMemoryBytes,- shaderSidecarRequired: evidence2.sidecar !== undefined+ shaderSidecarRequired: evidence.sidecar !== undefined};}function exactVfxIntent(context) {@@ -9413,8 +9421,8 @@ function exactVfxIntent(context) {]};}- const evidence2 = artifactEvidence(context);- if (!evidence2) {+ const evidence = artifactEvidence(context);+ if (!evidence) {return {findings: [finding5(context, {@@ -9428,17 +9436,17 @@ function exactVfxIntent(context) {]};}- return { intent: validated.value, evidence: evidence2 };+ return { intent: validated.value, evidence };}function evaluateVfxExactQa(context) {if (context.intent.category !== "vfx")return [];- const resolved2 = exactVfxIntent(context);- if ("findings" in resolved2)- return resolved2.findings;- const { intent, evidence: evidence2 } = resolved2;+ const resolved = exactVfxIntent(context);+ if ("findings" in resolved)+ return resolved.findings;+ const { intent, evidence } = resolved;const findings = [];- const effectMaterials = evidence2.materials.filter((material) => material.effectSurface !== false);+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface !== false);if (effectMaterials.length === 0) {findings.push(finding5(context, {code: "VFX_EFFECT_SURFACE_MISSING",@@ -9509,7 +9517,7 @@ function evaluateVfxExactQa(context) {}const facingFields = ["mode", "normalAxis", "directionAxis"];for (const field of facingFields) {- if (intent.facing[field] === evidence2.facing[field])+ if (intent.facing[field] === evidence.facing[field])continue;if (intent.facing.source !== "explicit")continue;@@ -9520,14 +9528,14 @@ function evaluateVfxExactQa(context) {message: `Explicit VFX facing ${field} does not match the emitted runtime contract.`,measurement: {name: `facing.${field}`,- actual: evidence2.facing[field] ?? null,+ actual: evidence.facing[field] ?? null,expected: intent.facing[field] ?? null},repairText: `Stamp and implement the requested ${field}; preserve the canonical Kiln frame.`}));}const requestedAnimation = intent.animation;- const actualAnimation = evidence2.animation;+ const actualAnimation = evidence.animation;for (const field of ["playback", "endpointBehavior", "driver"]) {if (requestedAnimation[field] === actualAnimation[field])continue;@@ -9570,7 +9578,7 @@ function evaluateVfxExactQa(context) {repairText: "Make the final loop sample equal the initial sample for every driven channel."}));}- if (requestedAnimation.driver === "clip" && !evidence2.clips.some((clip) => clip.name === requestedAnimation.clipName && Math.abs(clip.durationSeconds - requestedAnimation.durationSeconds) <= 0.000001)) {+ if (requestedAnimation.driver === "clip" && !evidence.clips.some((clip) => clip.name === requestedAnimation.clipName && Math.abs(clip.durationSeconds - requestedAnimation.durationSeconds) <= 0.000001)) {findings.push(finding5(context, {code: "VFX_REQUIRED_CLIP_MISSING",disposition: "block",@@ -9580,7 +9588,7 @@ function evaluateVfxExactQa(context) {repairText: `Emit clip ${requestedAnimation.clipName ?? "<declared clip>"} with the requested duration.`}));}- if (requestedAnimation.driver === "timeUniform" && !evidence2.uniforms.includes(requestedAnimation.timeUniformName ?? "")) {+ if (requestedAnimation.driver === "timeUniform" && !evidence.uniforms.includes(requestedAnimation.timeUniformName ?? "")) {findings.push(finding5(context, {code: "VFX_REQUIRED_TIME_UNIFORM_MISSING",disposition: "block",@@ -9588,13 +9596,13 @@ function evaluateVfxExactQa(context) {message: "The declared runtime time uniform is absent from the sidecar evidence.",measurement: {name: "timeUniformName",- actual: evidence2.uniforms.join(","),+ actual: evidence.uniforms.join(","),expected: requestedAnimation.timeUniformName ?? null},repairText: `Expose ${requestedAnimation.timeUniformName ?? "the declared uniform"} in the runtime sidecar.`}));}- if (intent.portability === "portable" && evidence2.sidecar !== undefined) {+ if (intent.portability === "portable" && evidence.sidecar !== undefined) {findings.push(finding5(context, {code: "VFX_UNDECLARED_SIDECAR",disposition: "block",@@ -9603,7 +9611,7 @@ function evaluateVfxExactQa(context) {repairText: "Bake the portable appearance into standard glTF materials or update trusted intent before spend."}));}- if (intent.portability === "sidecar" && (evidence2.sidecar?.id !== intent.sidecar?.id || evidence2.sidecar?.version !== intent.sidecar?.version)) {+ if (intent.portability === "sidecar" && (evidence.sidecar?.id !== intent.sidecar?.id || evidence.sidecar?.version !== intent.sidecar?.version)) {findings.push(finding5(context, {code: "VFX_SIDECAR_IDENTITY_MISMATCH",disposition: "block",@@ -9611,7 +9619,7 @@ function evaluateVfxExactQa(context) {message: "Runtime VFX sidecar identity/version does not match trusted intent.",measurement: {name: "sidecarIdentity",- actual: evidence2.sidecar ? `${evidence2.sidecar.id}@${evidence2.sidecar.version}` : null,+ actual: evidence.sidecar ? `${evidence.sidecar.id}@${evidence.sidecar.version}` : null,expected: intent.sidecar ? `${intent.sidecar.id}@${intent.sidecar.version}` : null},repairText: "Attach the exact declared sidecar identity and keep the GLB fallback honest."@@ -9624,12 +9632,12 @@ function evaluateVfxAdvisoryQa(context) {return [];const intent = context.intent.vfx;const validated = validateVfxIntentV1(intent);- const evidence2 = artifactEvidence(context);- if (!validated.valid || !validated.value || !evidence2)+ const evidence = artifactEvidence(context);+ if (!validated.valid || !validated.value || !evidence)return [];const findings = [];if (validated.value.facing.source === "inferred") {- const mismatch = ["mode", "normalAxis", "directionAxis"].some((field) => validated.value?.facing[field] !== evidence2.facing[field]);+ const mismatch = ["mode", "normalAxis", "directionAxis"].some((field) => validated.value?.facing[field] !== evidence.facing[field]);if (mismatch) {findings.push(finding5(context, {code: "VFX_FACING_INFERRED_DRIFT",@@ -9640,7 +9648,7 @@ function evaluateVfxAdvisoryQa(context) {}));}}- const cost = measureVfxRuntimeCostV1(evidence2);+ const cost = measureVfxRuntimeCostV1(evidence);findings.push(finding5(context, {code: "VFX_RUNTIME_COST_REPORT",disposition: "observe",@@ -9727,7 +9735,7 @@ function evaluateAssetScopeQa(context) {}, "scope.w7")];}-var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), stable6 = (value) => Math.round(value * 1e6) / 1e6, finiteTuple2 = (value, length3) => Array.isArray(value) && value.length === length3 && value.every((component) => typeof component === "number" && Number.isFinite(component)), VFX_EXACT_QA_RULE, VFX_ADVISORY_QA_RULE, MODULAR_JOIN_QA_RULE, ASSET_SCOPE_QA_RULE, W7_BREADTH_QA_RULES;+var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), stable6 = (value) => Math.round(value * 1e6) / 1e6, finiteTuple2 = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), VFX_EXACT_QA_RULE, VFX_ADVISORY_QA_RULE, MODULAR_JOIN_QA_RULE, ASSET_SCOPE_QA_RULE, W7_BREADTH_QA_RULES;var init_breadth2 = __esm(() => {init_breadth();init_registry();@@ -9797,10 +9805,10 @@ function isTexture(value) {function isAnimationClip(value) {return record3(value) && typeof value.name === "string" && typeof value.duration === "number" && Number.isFinite(value.duration) && Array.isArray(value.tracks);}-function localRenderableBox(rootInverse2, node) {+function localRenderableBox(rootInverse, node) {if (isSpriteNode(node)) {- const transform2 = rootInverse2.clone().multiply(node.matrixWorld);- return new THREE14.Box3(new THREE14.Vector3(-0.5, -0.5, -0.0005), new THREE14.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform2);+ const transform = rootInverse.clone().multiply(node.matrixWorld);+ return new THREE14.Box3(new THREE14.Vector3(-0.5, -0.5, -0.0005), new THREE14.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);}if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)return;@@ -9808,7 +9816,7 @@ function localRenderableBox(rootInverse2, node) {const source = node.geometry.boundingBox;if (!source || source.isEmpty())return;- const transform = rootInverse2.clone().multiply(node.matrixWorld);+ const transform = rootInverse.clone().multiply(node.matrixWorld);const result = new THREE14.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {@@ -9858,8 +9866,8 @@ function materialTextures(material) {}function materialTextureBytes(material) {return materialTextures(material).reduce((sum, texture) => {- const dimensions2 = textureDimensions(texture);- return sum + (dimensions2 ? Math.ceil(dimensions2[0] * dimensions2[1] * 4 * (4 / 3)) : 0);+ const dimensions = textureDimensions(texture);+ return sum + (dimensions ? Math.ceil(dimensions[0] * dimensions[1] * 4 * (4 / 3)) : 0);}, 0);}function alphaMode(material) {@@ -9875,15 +9883,15 @@ function alphaData(material) {return (standard.opacity ?? 1) < 1 || standard.alphaMap !== undefined && standard.alphaMap !== null || textureHasAlpha2(standard.alphaMap) || textureHasAlpha2(standard.map) || (standard.alphaTest ?? 0) > 0 && standard.alphaMap !== undefined && standard.alphaMap !== null;}function surfaceRole(nodes, intent) {- const evidence2 = nodes.flatMap((node) => [+ const evidence = nodes.flatMap((node) => [node.name,...readSemanticMetadataV1(node)?.roles ?? []]);- if (evidence2.some((value) => /(?:^|[._ -])beam(?:$|[._ -])/i.test(value)))+ if (evidence.some((value) => /(?:^|[._ -])beam(?:$|[._ -])/i.test(value)))return "beam";- if (evidence2.some((value) => /(?:^|[._ -])trail(?:$|[._ -])/i.test(value)))+ if (evidence.some((value) => /(?:^|[._ -])trail(?:$|[._ -])/i.test(value)))return "trail";- if (evidence2.some((value) => /(?:^|[._ -])(?:volume|aura|portal)(?:$|[._ -])/i.test(value))) {+ if (evidence.some((value) => /(?:^|[._ -])(?:volume|aura|portal)(?:$|[._ -])/i.test(value))) {return "volume";}if (intent.subtype === "beam")@@ -9966,13 +9974,13 @@ function dominantGeometryAxis(root, mode) {const bounds = node.geometry.boundingBox;if (!bounds || bounds.isEmpty())return;- const size2 = bounds.getSize(new THREE14.Vector3);- const axes2 = [- { score: size2.x, direction: new THREE14.Vector3(1, 0, 0) },- { score: size2.y, direction: new THREE14.Vector3(0, 1, 0) },- { score: size2.z, direction: new THREE14.Vector3(0, 0, 1) }+ const size = bounds.getSize(new THREE14.Vector3);+ const axes = [+ { score: size.x, direction: new THREE14.Vector3(1, 0, 0) },+ { score: size.y, direction: new THREE14.Vector3(0, 1, 0) },+ { score: size.z, direction: new THREE14.Vector3(0, 0, 1) }];- const selected = axes2.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);+ const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const relative = inverse.clone().multiply(node.matrixWorld);const direction = selected.direction.transformDirection(relative);const score = selected.score * node.getWorldScale(new THREE14.Vector3).length();@@ -10083,10 +10091,10 @@ function analyzeAssetScopeObservationV1(root) {root.traverse((node) => {if ((isMeshNode(node) || isSpriteNode(node)) && node.visible)renderableCount++;- const roles2 = readSemanticMetadataV1(node)?.roles ?? [];- if (roles2.some((role) => MEMBER_ROLE.test(role)))+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ if (roles.some((role) => MEMBER_ROLE.test(role)))members.add(node);- for (const role of roles2)+ for (const role of roles)if (DRESSING_ROLE.test(role))dressing.add(role);if (node !== root && DRESSING_NAME.test(node.name))@@ -10112,7 +10120,7 @@ function pathOf2(root, node) {}function analyzeSockets(root) {root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();const rootWorldRotation = root.getWorldQuaternion(new THREE14.Quaternion).invert();const values = [];root.traverse((node) => {@@ -10126,7 +10134,7 @@ function analyzeSockets(root) {continue;const frameRotation = new THREE14.Quaternion(...frame.rotation);const worldRotation = rootWorldRotation.clone().multiply(nodeWorldRotation).multiply(frameRotation);- const position = new THREE14.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse2);+ const position = new THREE14.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);const normal = new THREE14.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();values.push({contract: {@@ -10216,10 +10224,10 @@ function isQaFinding(value) {function createAssetQaReportV1(intent, options = {}) {const findings = [...options.findings ?? []];const evaluated = new Set(options.evaluatedDimensions ?? []);- for (const finding6 of findings)- evaluated.add(finding6.dimension);- const dimensions2 = Object.fromEntries(QA_DIMENSIONS.map((dimension) => {- const dimensionFindings = findings.filter((finding6) => finding6.dimension === dimension);+ for (const finding of findings)+ evaluated.add(finding.dimension);+ const dimensions = Object.fromEntries(QA_DIMENSIONS.map((dimension) => {+ const dimensionFindings = findings.filter((finding) => finding.dimension === dimension);const result = {status: evaluated.has(dimension) ? statusForFindings(dimensionFindings) : "notEvaluated",findings: dimensionFindings,@@ -10227,20 +10235,20 @@ function createAssetQaReportV1(intent, options = {}) {};return [dimension, result];}));- const statuses = QA_DIMENSIONS.map((dimension) => dimensions2[dimension].status);+ const statuses = QA_DIMENSIONS.map((dimension) => dimensions[dimension].status);const disposition = statuses.includes("block") ? "block" : statuses.includes("warn") ? "warn" : statuses.every((status) => status === "notEvaluated") ? "notEvaluated" : "pass";return {schemaVersion: 1,category: intent.category,qaProfile: intent.qaProfile,disposition,- dimensions: dimensions2+ dimensions};}var QA_DIMENSIONS, isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), statusForFindings = (findings) => {- if (findings.some((finding6) => finding6.disposition === "block"))+ if (findings.some((finding) => finding.disposition === "block"))return "block";- if (findings.some((finding6) => finding6.disposition === "warn"))+ if (findings.some((finding) => finding.disposition === "warn"))return "warn";return "pass";};@@ -10263,20 +10271,20 @@ function sceneNodes(context) {return [];const nodes = [];const seen = new Set;- const add2 = (node) => {+ const add = (node) => {if (!seen.has(node)) {seen.add(node);nodes.push(node);}};if (typeof context.scene.traverse === "function") {- context.scene.traverse(add2);+ context.scene.traverse(add);return nodes;}const pending = [context.scene];while (pending.length > 0) {const node = pending.shift();- add2(node);+ add(node);for (const child of node.children ?? [])pending.push(child);}@@ -10413,10 +10421,10 @@ function zeroScaleFindings(context) {const required = new Set(context.intent.requiredParts);const findings = [];for (const node of sceneNodes(context)) {- const scale2 = node.scale;- if (!scale2)+ const scale = node.scale;+ if (!scale)continue;- const zeroAxes = ["x", "y", "z"].filter((axis) => Number.isFinite(scale2[axis]) && Math.abs(scale2[axis]) <= ZERO_SCALE_EPSILON);+ const zeroAxes = ["x", "y", "z"].filter((axis) => Number.isFinite(scale[axis]) && Math.abs(scale[axis]) <= ZERO_SCALE_EPSILON);if (zeroAxes.length === 0)continue;const outputBearing = isRenderable(node) || descendantsContainRenderable(node) || required.has(nodeName(node));@@ -10437,10 +10445,10 @@ function clipList(context) {return (context.clips ?? []).filter((clip) => typeof clip === "object" && clip !== null);}function trackTarget2(trackName) {- const dot3 = trackName.indexOf(".");- if (dot3 <= 0)+ const dot = trackName.indexOf(".");+ if (dot <= 0)return;- const path = trackName.slice(0, dot3);+ const path = trackName.slice(0, dot);const slash = path.lastIndexOf("/");return path.slice(slash + 1) || undefined;}@@ -10598,19 +10606,6 @@ var init_universal = __esm(() => {});// src/qa/run.ts-var exports_run = {};-__export(exports_run, {- runDeterministicSceneQa: () => runDeterministicSceneQa,- qaPolicyFromEnv: () => qaPolicyFromEnv,- qaBlockingEnabled: () => qaBlockingEnabled,- gltfReportFindings: () => gltfReportFindings,- appendRuntimeCostQa: () => appendRuntimeCostQa,- appendReferenceComparisonQa: () => appendReferenceComparisonQa,- appendMaterialMetricsQa: () => appendMaterialMetricsQa,- appendFinalGltfQa: () => appendFinalGltfQa,- DETERMINISTIC_QA_REGISTRY: () => DETERMINISTIC_QA_REGISTRY,- AssetQaBlockedError: () => AssetQaBlockedError-});function runDeterministicSceneQa(context, policy = {}) {const result = DETERMINISTIC_QA_REGISTRY.run(withDerivedW7BreadthEvidence(context), policy);return createAssetQaReportV1(context.intent, {@@ -10647,7 +10642,7 @@ function appendFinalGltfQa(intent, sceneReport, gltfReport) {metrics: {exportIntegrity: {gltfErrors: gltfReport.issues.numErrors,- gltfWarnings: gltfFindings.filter((finding6) => finding6.disposition === "warn").length+ gltfWarnings: gltfFindings.filter((finding) => finding.disposition === "warn").length}}});@@ -10718,22 +10713,6 @@ function appendMaterialMetricsQa(intent, report, materialMetrics, budgetWarnings};return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });}-function appendReferenceComparisonQa(intent, report, evidence2) {- const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);- findings.push(...referenceComparisonFindings(evidence2, "reference.comparison"));- const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);- if (!evaluatedDimensions.includes("promptAlignment"))- evaluatedDimensions.push("promptAlignment");- const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));- metrics.promptAlignment = {- ...metrics.promptAlignment ?? {},- referenceSilhouetteIoU: evidence2.silhouetteIoU,- referenceColorAgreement: evidence2.colorAgreement,- referenceCoverageRatio: evidence2.coverageRatio,- referenceShadowPixels: evidence2.reference.shadowPixels- };- return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });-}function qaPolicyFromEnv(env = process.env) {const mode = env["KILN_QA_MODE"];return mode === "observe" || mode === "off" ? { defaultMode: mode } : {};@@ -10780,8 +10759,8 @@ var init_run = __esm(() => {stage;gltfValidation;constructor(report, stage, gltfValidation) {- const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding6) => finding6.disposition === "block");- const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding6) => `${finding6.code}: ${finding6.message}${finding6.repairText ? ` FIX: ${finding6.repairText}` : ""}`);+ const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding) => finding.disposition === "block");+ const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding) => `${finding.code}: ${finding.message}${finding.repairText ? ` FIX: ${finding.repairText}` : ""}`);const overflow = blockers.length > MAX_DETAILED_BLOCKERS ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)` : "";super(`Asset QA blocked at ${stage}: ${detailed.join(" | ") || "unknown blocker"}${overflow}`);this.name = "AssetQaBlockedError";@@ -10994,8 +10973,8 @@ function nonNegative(value, name) {throw new RangeError(`${name} must be finite and >= 0`);return value;}-function roleMetadata(roles2, relationships = [], frames = []) {- return { roles: roles2, relationships, frames, sockets: [] };+function roleMetadata(roles, relationships = [], frames = []) {+ return { roles, relationships, frames, sockets: [] };}function relationship(kind, target) {return { kind, target, targetType: "role" };@@ -11242,7 +11221,7 @@ function wallRunAxis(wall) {function wallNeighbors(wall) {return wall === "front" || wall === "back" ? ["left", "right"] : ["front", "back"];}-function createShellWall(name, wall, material, length3, height, thickness, openings) {+function createShellWall(name, wall, material, length, height, thickness, openings) {const axis = wallRunAxis(wall);const root = new THREE15.Object3D;root.name = `${name}_Wall_${wall}`;@@ -11252,15 +11231,15 @@ function createShellWall(name, wall, material, length3, height, thickness, openirelationship("adjacent-to", `wall.${neighbors[1]}`),relationship("adjacent-to", "floor")]));- const sorted = openings.map((opening2, index) => ({- ...opening2,- id: opening2.id ?? `${opening2.kind ?? "door"}-${index + 1}`,- kind: opening2.kind ?? "door",- offset: opening2.offset ?? 0,- width: positive2(opening2.width ?? (opening2.kind === "window" ? 1 : 1.1), "opening.width"),- height: positive2(opening2.height ?? (opening2.kind === "window" ? 1 : 2.1), "opening.height"),- sill: opening2.kind === "window" ? nonNegative(opening2.sill ?? 1, "opening.sill") : 0,- depth: positive2(opening2.depth ?? thickness, "opening.depth")+ const sorted = openings.map((opening, index) => ({+ ...opening,+ id: opening.id ?? `${opening.kind ?? "door"}-${index + 1}`,+ kind: opening.kind ?? "door",+ offset: opening.offset ?? 0,+ width: positive2(opening.width ?? (opening.kind === "window" ? 1 : 1.1), "opening.width"),+ height: positive2(opening.height ?? (opening.kind === "window" ? 1 : 2.1), "opening.height"),+ sill: opening.kind === "window" ? nonNegative(opening.sill ?? 1, "opening.sill") : 0,+ depth: positive2(opening.depth ?? thickness, "opening.depth")})).sort((a, b) => a.offset - b.offset);if (sorted.length > 1)throw new RangeError("the minimal gable shell supports at most one opening per wall");@@ -11276,15 +11255,15 @@ function createShellWall(name, wall, material, length3, height, thickness, openiconst markers = [];const opening = sorted[0];if (!opening)- panel("solid", -length3 / 2, length3 / 2, 0, height);+ panel("solid", -length / 2, length / 2, 0, height);else {const left = opening.offset - opening.width / 2;const right = opening.offset + opening.width / 2;const top = opening.sill + opening.height;- if (left <= -length3 / 2 || right >= length3 / 2 || top >= height)+ if (left <= -length / 2 || right >= length / 2 || top >= height)throw new RangeError(`opening on wall.${wall} must fit strictly inside the wall boundary`);- panel("left", -length3 / 2, left, 0, height);- panel("right", right, length3 / 2, 0, height);+ panel("left", -length / 2, left, 0, height);+ panel("right", right, length / 2, 0, height);panel("lintel", left, right, top, height);if (opening.sill > 0)panel("sill", left, right, 0, opening.sill);@@ -11403,16 +11382,16 @@ function createRoofSurfaceLayout(name, material, options) {const rows = Math.max(1, Math.ceil(downhill / rowHeight));const columns = Math.max(1, Math.ceil(along / tileWidth));for (let row = 0;row < rows; row++) {- const length3 = Math.min(rowHeight * 1.08, downhill);+ const length = Math.min(rowHeight * 1.08, downhill);for (let column = 0;column < columns; column++) {const offset = row % 2 === 0 ? 0 : tileWidth / 2;const x = -along / 2 + tileWidth * (column + 0.5) + offset;if (x + tileWidth / 2 <= along / 2 + EPSILON3)specs.push({width: tileWidth * 0.96,- length: length3,+ length,x,- z: Math.min(downhill - length3 / 2, row * rowHeight + length3 / 2)+ z: Math.min(downhill - length / 2, row * rowHeight + length / 2)});}}@@ -11548,26 +11527,26 @@ function gearGeo(opts = {}) {}function bladeGeo(opts = {}) {const {- length: length3 = 1.5,+ length = 1.5,baseWidth = 0.1,thickness = 0.015,tipLength = 0.25,edgeBevel = 0} = opts;- if (length3 <= 0 || baseWidth <= 0 || thickness <= 0) {+ if (length <= 0 || baseWidth <= 0 || thickness <= 0) {throw new Error("bladeGeo: length, baseWidth, thickness must all be > 0");}- if (tipLength >= length3) {+ if (tipLength >= length) {throw new Error("bladeGeo: tipLength must be less than length");}const hw = baseWidth / 2;const ht = thickness / 2;- const shoulderY = length3 - tipLength;+ const shoulderY = length - tipLength;const outline = [[-hw, 0],[hw, 0],[hw, shoulderY],- [0, length3],+ [0, length],[-hw, shoulderY]];const n = outline.length;@@ -11680,12 +11659,12 @@ function mirror(name, source, axis, parent) {axis === "y" ? -sourcePos[1] : sourcePos[1],axis === "z" ? -sourcePos[2] : sourcePos[2]];- const scale2 = [+ const scale = [axis === "x" ? -1 : 1,axis === "y" ? -1 : 1,axis === "z" ? -1 : 1];- return createInstance(name, source, { position: pos, scale: scale2, parent });+ return createInstance(name, source, { position: pos, scale, parent });}function mergeVertices(geometry, opts = {}) {const { tolerance = 0.0001, positionOnly = false } = typeof opts === "number" ? { tolerance: opts } : opts;@@ -11709,9 +11688,9 @@ function subdivide(geometry, iterations = 1, opts = {}) {if (preserveUV) {subOpts.uvSmooth = false;input.computeBoundingBox();- const extent2 = input.boundingBox.getSize(new THREE17.Vector3);+ const extent = input.boundingBox.getSize(new THREE17.Vector3);input.boundingBox.getCenter(center);- const size = Math.max(extent2.x, extent2.y, extent2.z);+ const size = Math.max(extent.x, extent.y, extent.z);normalizationScale = size > 0 ? 1e4 / size : 1;input.translate(-center.x, -center.y, -center.z).scale(normalizationScale, normalizationScale, normalizationScale);}@@ -11839,10 +11818,10 @@ var init_ops = __esm(() => {// src/geometry.tsimport * as THREE18 from "three";-function finiteArray(values, label, length3) {+function finiteArray(values, label, length) {const result = Array.from(values);- if (length3 !== undefined && result.length !== length3)- throw new Error(`${label}: expected ${length3} values, got ${result.length}`);+ if (length !== undefined && result.length !== length)+ throw new Error(`${label}: expected ${length} values, got ${result.length}`);if (!result.every((n) => Number.isFinite(Math.fround(n))))throw new Error(`${label}: all values must be finite Float32 values`);return result;@@ -11995,8 +11974,8 @@ function parametricSurface(sample, options = {}) {};const join = (a, b, label) => {const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);- const scale2 = Math.max(1, ...pa.map(Math.abs), ...pb.map(Math.abs));- if (Math.hypot(...pa.map((x, k) => x - pb[k])) > scale2 * 0.000001)+ const scale = Math.max(1, ...pa.map(Math.abs), ...pb.map(Math.abs));+ if (Math.hypot(...pa.map((x, k) => x - pb[k])) > scale * 0.000001)throw new Error(`parametricSurface ${label}: endpoint positions do not match`);groups[find(b)] = find(a);for (let k = 0;k < 3; k++)@@ -12105,7 +12084,7 @@ function deform(geometry, options, map) {throw new Error("deformation interval must be finite and increasing");[low, high] = options.interval;}- const length3 = high - low;+ const length = high - low;const out = geometry.clone();const position = out.getAttribute("position");for (let i = 0;i < points.length; i++) {@@ -12113,11 +12092,11 @@ function deform(geometry, options, map) {const epsilon = Math.max(1, Math.abs(low), Math.abs(high)) * 0.0000001;if (point.y < low - epsilon || point.y > high + epsilon)continue;- const t = length3 > epsilon ? THREE19.MathUtils.clamp((point.y - low) / length3, 0, 1) : 0;+ const t = length > epsilon ? THREE19.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;const weight = options.falloff?.(t) ?? 1;if (!Number.isFinite(weight) || weight < 0 || weight > 1)throw new Error("deformation falloff must return a finite weight between 0 and 1");- const mapped = map(point.clone(), t, low, length3);+ const mapped = map(point.clone(), t, low, length);if (![mapped.x, mapped.y, mapped.z].every(Number.isFinite))throw new Error("deformation callback must return finite coordinates");point.lerp(mapped, weight).applyMatrix4(matrix);@@ -12141,10 +12120,10 @@ function bend(geometry, options) {if (!Number.isFinite(options.angle))throw new Error("bend angle must be finite degrees");const angle = THREE19.MathUtils.degToRad(options.angle);- return deform(geometry, options, (p, t, low, length3) => {- if (Math.abs(angle) < 0.0000000001 || length3 === 0)+ return deform(geometry, options, (p, t, low, length) => {+ if (Math.abs(angle) < 0.0000000001 || length === 0)return p;- const radius = length3 / angle, theta = angle * t;+ const radius = length / angle, theta = angle * t;return new THREE19.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);});}@@ -12174,7 +12153,7 @@ function profilePoints(profile) {points.pop();if (points.length < 3)throw new Error("profile requires three distinct points");- const cross2 = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);+ const cross = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);for (let i = 0;i < points.length; i++) {const a = points[i], b = points[(i + 1) % points.length];if (a.distanceToSquared(b) < 0.00000000000000000001)@@ -12183,7 +12162,7 @@ function profilePoints(profile) {if (j === i + 1 || i === 0 && j === points.length - 1)continue;const c = points[j], d = points[(j + 1) % points.length];- if (cross2(a, b, c) * cross2(a, b, d) <= 0 && cross2(c, d, a) * cross2(c, d, b) <= 0 && Math.max(Math.min(a.x, b.x), Math.min(c.x, d.x)) <= Math.min(Math.max(a.x, b.x), Math.max(c.x, d.x)) + 0.0000000001 && Math.max(Math.min(a.y, b.y), Math.min(c.y, d.y)) <= Math.min(Math.max(a.y, b.y), Math.max(c.y, d.y)) + 0.0000000001)+ if (cross(a, b, c) * cross(a, b, d) <= 0 && cross(c, d, a) * cross(c, d, b) <= 0 && Math.max(Math.min(a.x, b.x), Math.min(c.x, d.x)) <= Math.min(Math.max(a.x, b.x), Math.max(c.x, d.x)) + 0.0000000001 && Math.max(Math.min(a.y, b.y), Math.min(c.y, d.y)) <= Math.min(Math.max(a.y, b.y), Math.max(c.y, d.y)) + 0.0000000001)throw new Error("profile self-intersects or touches itself");}}@@ -12271,10 +12250,10 @@ function loftProfiles(sections, options = {}) {return out;}function sweepProfile(profile, path, options = {}) {- const points = profilePoints(profile), closed = options.closed ?? false, twist2 = options.twist ?? 0;- if (!Number.isFinite(twist2))+ const points = profilePoints(profile), closed = options.closed ?? false, twist = options.twist ?? 0;+ if (!Number.isFinite(twist))throw new Error("sweepProfile twist must be finite degrees");- if (closed && Math.abs(twist2 / 360 - Math.round(twist2 / 360)) > 0.00000001)+ if (closed && Math.abs(twist / 360 - Math.round(twist / 360)) > 0.00000001)throw new Error("closed sweep twist must be a multiple of 360 degrees");if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))throw new Error("sweepProfile requires finite path points (two open or three closed)");@@ -12308,10 +12287,10 @@ function sweepProfile(profile, path, options = {}) {return incoming.clone().add(outgoing).normalize();});const scales = stations.map((_, i) => {- const scale2 = typeof options.scale === "number" ? [options.scale, options.scale] : options.scale?.[i] ?? [1, 1];- if (scale2.length !== 2 || !scale2.every((n) => Number.isFinite(n) && n > 0))+ const scale = typeof options.scale === "number" ? [options.scale, options.scale] : options.scale?.[i] ?? [1, 1];+ if (scale.length !== 2 || !scale.every((n) => Number.isFinite(n) && n > 0))throw new Error("sweepProfile scale requires positive finite pairs");- return scale2;+ return scale;});if (Array.isArray(options.scale) && options.scale.length !== stations.length)throw new Error("sweepProfile scale needs one pair per path station");@@ -12340,9 +12319,9 @@ function sweepProfile(profile, path, options = {}) {correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));const rings = stations.map((station, i) => {const tangent = tangents[i], t = distances[i] / total;- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE20.MathUtils.degToRad(twist2)) * t);- const axisX = tangent.clone().cross(axisZ).normalize(), scale2 = scales[i];- return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale2[0]).addScaledVector(axisZ, p.y * scale2[1]));+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE20.MathUtils.degToRad(twist)) * t);+ const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];+ return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));});if (closed)rings[rings.length - 1] = rings[0].map((p) => p.clone());@@ -12399,16 +12378,16 @@ function threeToManifold(src, mod, label, context) {let vertexOffset = 0, meshCount = 0;const stride = context.preserve ? 5 : 3;src.traverse((child) => {- const mesh2 = child;- if (!mesh2.isMesh)+ const mesh = child;+ if (!mesh.isMesh)return;- const geometry = mesh2.geometry, position = geometry.getAttribute("position");+ const geometry = mesh.geometry, position = geometry.getAttribute("position");if (!position)return;meshCount++;const index = geometry.index, count = index?.count ?? position.count;if (count % 3 !== 0)- throw new Error(`CSG ${label}: mesh "${mesh2.name || "(unnamed)"}" has ${count} ${index ? "indices" : "vertices"}, which is not a whole number of triangles. Every CSG input must be a triangle mesh.`);+ throw new Error(`CSG ${label}: mesh "${mesh.name || "(unnamed)"}" has ${count} ${index ? "indices" : "vertices"}, which is not a whole number of triangles. Every CSG input must be a triangle mesh.`);if (position.itemSize !== 3)throw new Error(`CSG ${label}: positions must have three components`);const uv = geometry.getAttribute("uv");@@ -12418,11 +12397,11 @@ function threeToManifold(src, mod, label, context) {if (uv)context.anyUV = true;else- context.missingUV.add(mesh2.name || label);+ context.missingUV.add(mesh.name || label);}const point = new THREE21.Vector3;for (let i = 0;i < position.count; i++) {- point.fromBufferAttribute(position, i).applyMatrix4(mesh2.matrixWorld);+ point.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))throw new Error(`CSG ${label}: transformed positions must be finite Float32 coordinates`);properties.push(point.x, point.y, point.z);@@ -12433,8 +12412,8 @@ function threeToManifold(src, mod, label, context) {properties.push(u, v);}}- const materials = Array.isArray(mesh2.material) ? mesh2.material : [mesh2.material];- const spans = sourceSpans(mesh2, count).sort((a, b) => a.start - b.start);+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];+ const spans = sourceSpans(mesh, count).sort((a, b) => a.start - b.start);let covered = 0;for (const span of spans) {if (!Number.isInteger(span.start) || !Number.isInteger(span.count) || span.start !== covered || span.count <= 0 || span.count % 3 || span.start % 3 || span.start + span.count > count || !materials[span.materialIndex])@@ -12451,7 +12430,7 @@ function threeToManifold(src, mod, label, context) {];if (triangle.some((j) => !Number.isInteger(j) || j < 0 || j >= position.count))throw new Error(`CSG ${label}: index outside positions`);- if (mesh2.matrixWorld.determinant() < 0)+ if (mesh.matrixWorld.determinant() < 0)[triangle[1], triangle[2]] = [triangle[2], triangle[1]];indices.push(...triangle.map((j) => j + vertexOffset));const prior = geometry.userData.kilnCsgProvenance;@@ -12740,19 +12719,19 @@ function bevelCrossSection(cs, bevel, style, segments, label) {dilated.delete();return out;}-function normalizeTaper(taper2) {- if (taper2 === undefined)+function normalizeTaper(taper) {+ if (taper === undefined)return [1, 1];- if (typeof taper2 === "number") {- if (!Number.isFinite(taper2) || taper2 < 0) {- throw new Error(`taper must be a finite number >= 0 (got ${taper2}).`);+ if (typeof taper === "number") {+ if (!Number.isFinite(taper) || taper < 0) {+ throw new Error(`taper must be a finite number >= 0 (got ${taper}).`);}- return [taper2, taper2];+ return [taper, taper];}- if (!Array.isArray(taper2) || taper2.length !== 2 || !taper2.every((v) => Number.isFinite(v) && v >= 0)) {- throw new Error(`taper must be a number or [x, y] pair of numbers >= 0 (got ${JSON.stringify(taper2)}).`);+ if (!Array.isArray(taper) || taper.length !== 2 || !taper.every((v) => Number.isFinite(v) && v >= 0)) {+ throw new Error(`taper must be a number or [x, y] pair of numbers >= 0 (got ${JSON.stringify(taper)}).`);}- return [taper2[0], taper2[1]];+ return [taper[0], taper[1]];}async function extrudeProfile(profile, options = {}) {assertFiniteProfile(profile, "extrudeProfile");@@ -12762,8 +12741,8 @@ async function extrudeProfile(profile, options = {}) {bevel = 0,bevelStyle = "round",segments = 12,- twist: twist2 = 0,- taper: taper2,+ twist = 0,+ taper,divisions,axis = "y",center = true,@@ -12794,8 +12773,8 @@ async function extrudeProfile(profile, options = {}) {if (bevel > 0) {section = track(bevelCrossSection(section, bevel, bevelStyle, segments, "extrudeProfile"));}- const nDivisions = divisions ?? (twist2 !== 0 ? 16 : 1);- const solid = section.extrude(depth, nDivisions, twist2, normalizeTaper(taper2), center);+ const nDivisions = divisions ?? (twist !== 0 ? 16 : 1);+ const solid = section.extrude(depth, nDivisions, twist, normalizeTaper(taper), center);try {return orientSweep(manifoldToGeometry(solid, { smooth }), axis);} finally {@@ -13052,31 +13031,31 @@ function pbrMaterial(opts = {}) {}if (opts.aoMapIntensity !== undefined)mat.aoMapIntensity = opts.aoMapIntensity;- const alphaMode2 = opts.alphaMode ?? "opaque";- if (alphaMode2 !== "opaque" && alphaMode2 !== "mask" && alphaMode2 !== "blend") {+ const alphaMode = opts.alphaMode ?? "opaque";+ if (alphaMode !== "opaque" && alphaMode !== "mask" && alphaMode !== "blend") {throw new TypeError('alphaMode must be one of "opaque", "mask", or "blend".');}if (opts.doubleSided !== undefined && typeof opts.doubleSided !== "boolean") {throw new TypeError("doubleSided must be a boolean when provided.");}- if (opts.alphaCutoff !== undefined && alphaMode2 !== "mask") {+ if (opts.alphaCutoff !== undefined && alphaMode !== "mask") {throw new TypeError('alphaCutoff is valid only when alphaMode is "mask".');}if (opts.alphaCutoff !== undefined && (!Number.isFinite(opts.alphaCutoff) || opts.alphaCutoff < 0 || opts.alphaCutoff > 1)) {throw new RangeError("alphaCutoff must be a finite number in [0,1].");}- if (alphaMode2 === "mask") {+ if (alphaMode === "mask") {mat.alphaTest = opts.alphaCutoff ?? 0.5;mat.transparent = false;- } else if (alphaMode2 === "blend") {+ } else if (alphaMode === "blend") {mat.alphaTest = 0;mat.transparent = true;}if (opts.doubleSided)mat.side = THREE22.DoubleSide;mat.userData["kilnMaterial"] = {- alphaMode: alphaMode2,- ...alphaMode2 === "mask" ? { alphaCutoff: mat.alphaTest } : {},+ alphaMode,+ ...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},doubleSided: opts.doubleSided === true};return mat;@@ -13151,9 +13130,9 @@ function strictArray(value, path) {}return value;}-function assertKeys(record4, allowed, path) {+function assertKeys(record, allowed, path) {const allow = new Set(allowed);- for (const key of Object.keys(record4)) {+ for (const key of Object.keys(record)) {if (!allow.has(key)) {throw new ProceduralTextureError(`${path} has unknown key ${JSON.stringify(key)}.`);}@@ -13209,8 +13188,8 @@ function angle(value, path) {const normalized = (bounded % 360 + 360) % 360;return Object.is(normalized, -0) ? 0 : normalized;}-function blend(record4, path) {- const value = record4["blend"] ?? "normal";+function blend(record, path) {+ const value = record["blend"] ?? "normal";if (!BLENDS.includes(value)) {throw new ProceduralTextureError(`${path}.blend ${JSON.stringify(value)} is not one of ${BLENDS.join(", ")}.`);}@@ -13218,70 +13197,70 @@ function blend(record4, path) {}function canonicalLayer(value, index) {const path = `proceduralTexture.layers[${index}]`;- const record4 = strictRecord(value, path);- const op = record4["op"];+ const record = strictRecord(value, path);+ const op = record["op"];if (!OPS.includes(op)) {throw new ProceduralTextureError(`${path}.op ${JSON.stringify(op)} is not one of ${OPS.join(", ")}.`);}- const validatedBlend = blend(record4, path);- const validatedOpacity = unit(record4["opacity"], `${path}.opacity`, 1);+ const validatedBlend = blend(record, path);+ const validatedOpacity = unit(record["opacity"], `${path}.opacity`, 1);const common = {blend: index === 0 ? "normal" : validatedBlend,opacity: index === 0 ? 1 : validatedOpacity};switch (op) {case "solid":- assertKeys(record4, ["op", "color", "blend", "opacity"], path);- return { op, color: color(record4["color"], `${path}.color`), ...common };+ assertKeys(record, ["op", "color", "blend", "opacity"], path);+ return { op, color: color(record["color"], `${path}.color`), ...common };case "checker":- assertKeys(record4, ["op", "colorA", "colorB", "squares", "blend", "opacity"], path);+ assertKeys(record, ["op", "colorA", "colorB", "squares", "blend", "opacity"], path);return {op,- colorA: color(record4["colorA"], `${path}.colorA`),- colorB: color(record4["colorB"], `${path}.colorB`),- squares: integer(record4["squares"], `${path}.squares`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ squares: integer(record["squares"], `${path}.squares`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),...common};case "stripes":- assertKeys(record4, ["op", "colorA", "colorB", "count", "angleDeg", "blend", "opacity"], path);+ assertKeys(record, ["op", "colorA", "colorB", "count", "angleDeg", "blend", "opacity"], path);return {op,- colorA: color(record4["colorA"], `${path}.colorA`),- colorB: color(record4["colorB"], `${path}.colorB`),- count: integer(record4["count"], `${path}.count`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- angleDeg: angle(record4["angleDeg"], `${path}.angleDeg`),+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ count: integer(record["count"], `${path}.count`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ angleDeg: angle(record["angleDeg"], `${path}.angleDeg`),...common};case "gradient":- assertKeys(record4, ["op", "from", "to", "angleDeg", "blend", "opacity"], path);+ assertKeys(record, ["op", "from", "to", "angleDeg", "blend", "opacity"], path);return {op,- from: color(record4["from"], `${path}.from`),- to: color(record4["to"], `${path}.to`),- angleDeg: angle(record4["angleDeg"], `${path}.angleDeg`),+ from: color(record["from"], `${path}.from`),+ to: color(record["to"], `${path}.to`),+ angleDeg: angle(record["angleDeg"], `${path}.angleDeg`),...common};case "bricks":- assertKeys(record4, ["op", "brick", "mortar", "rows", "cols", "mortarWidth", "stagger", "blend", "opacity"], path);+ assertKeys(record, ["op", "brick", "mortar", "rows", "cols", "mortarWidth", "stagger", "blend", "opacity"], path);return {op,- brick: color(record4["brick"], `${path}.brick`),- mortar: color(record4["mortar"], `${path}.mortar`),- rows: integer(record4["rows"], `${path}.rows`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- cols: integer(record4["cols"], `${path}.cols`, 4, 1, MAX_PROCEDURAL_PATTERN_COUNT),- mortarWidth: unit(record4["mortarWidth"], `${path}.mortarWidth`, 0.06),- stagger: unit(record4["stagger"], `${path}.stagger`, 0.5),+ brick: color(record["brick"], `${path}.brick`),+ mortar: color(record["mortar"], `${path}.mortar`),+ rows: integer(record["rows"], `${path}.rows`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ cols: integer(record["cols"], `${path}.cols`, 4, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ mortarWidth: unit(record["mortarWidth"], `${path}.mortarWidth`, 0.06),+ stagger: unit(record["stagger"], `${path}.stagger`, 0.5),...common};case "noise":- assertKeys(record4, ["op", "colorA", "colorB", "scale", "octaves", "seed", "blend", "opacity"], path);+ assertKeys(record, ["op", "colorA", "colorB", "scale", "octaves", "seed", "blend", "opacity"], path);return {op,- colorA: color(record4["colorA"], `${path}.colorA`),- colorB: color(record4["colorB"], `${path}.colorB`),- scale: integer(record4["scale"], `${path}.scale`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- octaves: integer(record4["octaves"], `${path}.octaves`, 3, 1, MAX_NOISE_OCTAVES),- seed: integer(record4["seed"], `${path}.seed`, 0, -2147483648, 2147483647),+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ scale: integer(record["scale"], `${path}.scale`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ octaves: integer(record["octaves"], `${path}.octaves`, 3, 1, MAX_NOISE_OCTAVES),+ seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),...common};default:@@ -13289,17 +13268,17 @@ function canonicalLayer(value, index) {}}function migrateProceduralTextureSpecV1(input) {- const record4 = strictRecord(input, "proceduralTexture");- assertKeys(record4, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");- if (record4["schemaVersion"] !== undefined && record4["schemaVersion"] !== 1) {- throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(record4["schemaVersion"])}.`);+ const record = strictRecord(input, "proceduralTexture");+ assertKeys(record, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");+ if (record["schemaVersion"] !== undefined && record["schemaVersion"] !== 1) {+ throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(record["schemaVersion"])}.`);}return {schemaVersion: 2,- ...record4["size"] !== undefined ? { size: record4["size"] } : {},- ...record4["usage"] !== undefined ? { usage: record4["usage"] } : {},- ...record4["name"] !== undefined ? { name: record4["name"] } : {},- layers: record4["layers"]+ ...record["size"] !== undefined ? { size: record["size"] } : {},+ ...record["usage"] !== undefined ? { usage: record["usage"] } : {},+ ...record["name"] !== undefined ? { name: record["name"] } : {},+ layers: record["layers"]};}function canonicalizeProceduralTextureSpecV2(input) {@@ -13335,8 +13314,8 @@ function canonicalJson(value) {return JSON.stringify(value);if (Array.isArray(value))return `[${value.map(canonicalJson).join(",")}]`;- const record4 = value;- return `{${Object.keys(record4).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record4[key])}`).join(",")}}`;+ const record = value;+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;}function canonicalProceduralTextureJsonV2(input) {return canonicalJson(canonicalizeProceduralTextureSpecV2(input));@@ -13366,10 +13345,10 @@ function sha256Hex(text) {for (let i = 0;i < 16; i++)w[i] = view.getUint32(offset + i * 4, false);for (let i = 16;i < 64; i++) {- const a2 = w[i - 15];- const b2 = w[i - 2];- const s0 = rotateRight(a2, 7) ^ rotateRight(a2, 18) ^ a2 >>> 3;- const s1 = rotateRight(b2, 17) ^ rotateRight(b2, 19) ^ b2 >>> 10;+ const a = w[i - 15];+ const b = w[i - 2];+ const s0 = rotateRight(a, 7) ^ rotateRight(a, 18) ^ a >>> 3;+ const s1 = rotateRight(b, 17) ^ rotateRight(b, 19) ^ b >>> 10;w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;}let [a, b, c, d, e, f, g, hh] = h;@@ -13400,19 +13379,19 @@ function hashProceduralTextureSpecV2(input) {}function canonicalTextureRef(value, slot) {const path = `portableMaterial.textures.${slot}`;- const record4 = strictRecord(value, path);- if (record4["kind"] === "procedural") {- assertKeys(record4, ["kind", "spec"], path);- const spec = canonicalizeProceduralTextureSpecV2(record4["spec"]);+ const record = strictRecord(value, path);+ if (record["kind"] === "procedural") {+ assertKeys(record, ["kind", "spec"], path);+ const spec = canonicalizeProceduralTextureSpecV2(record["spec"]);const expected = MATERIAL_TEXTURE_USAGE[slot];if (spec.usage !== expected) {throw new ProceduralTextureError(`${path} requires procedural usage ${JSON.stringify(expected)}, got ${JSON.stringify(spec.usage)}.`);}return { kind: "procedural", spec };}- if (record4["kind"] === "resource") {- assertKeys(record4, ["kind", "resourceId"], path);- const resourceId = record4["resourceId"];+ if (record["kind"] === "resource") {+ assertKeys(record, ["kind", "resourceId"], path);+ const resourceId = record["resourceId"];if (typeof resourceId !== "string" || resourceId.length > 128 || !/^kiln\.[a-z0-9][a-z0-9._-]+$/.test(resourceId)) {throw new ProceduralTextureError(`${path}.resourceId must be a bounded kiln.* resource ID.`);}@@ -13421,8 +13400,8 @@ function canonicalTextureRef(value, slot) {throw new ProceduralTextureError(`${path}.kind must be "procedural" or "resource".`);}function canonicalizePortableMaterialSpecV2(input) {- const record4 = strictRecord(input, "portableMaterial");- assertKeys(record4, [+ const record = strictRecord(input, "portableMaterial");+ assertKeys(record, ["schemaVersion","model","name",@@ -13436,13 +13415,13 @@ function canonicalizePortableMaterialSpecV2(input) {"doubleSided","textures"], "portableMaterial");- if (record4["schemaVersion"] !== 2) {+ if (record["schemaVersion"] !== 2) {throw new ProceduralTextureError("portableMaterial.schemaVersion must be 2.");}- if (record4["model"] !== "pbrMetallicRoughness") {+ if (record["model"] !== "pbrMetallicRoughness") {throw new ProceduralTextureError('portableMaterial.model must be "pbrMetallicRoughness"; executable shader models are not portable.');}- const textureInput = record4["textures"] ?? {};+ const textureInput = record["textures"] ?? {};const textureRecord = strictRecord(textureInput, "portableMaterial.textures");const slots = Object.keys(MATERIAL_TEXTURE_USAGE);assertKeys(textureRecord, slots, "portableMaterial.textures");@@ -13462,26 +13441,26 @@ function canonicalizePortableMaterialSpecV2(input) {if (proceduralTexels > MAX_PORTABLE_MATERIAL_TEXELS) {throw new ProceduralTextureError(`portableMaterial procedural texture budget is ${proceduralTexels} texels, above ${MAX_PORTABLE_MATERIAL_TEXELS}.`);}- const alphaMode2 = record4["alphaMode"] ?? "opaque";- if (alphaMode2 !== "opaque" && alphaMode2 !== "mask" && alphaMode2 !== "blend") {+ const alphaMode = record["alphaMode"] ?? "opaque";+ if (alphaMode !== "opaque" && alphaMode !== "mask" && alphaMode !== "blend") {throw new ProceduralTextureError("portableMaterial.alphaMode must be opaque, mask, or blend.");}- if (record4["doubleSided"] !== undefined && typeof record4["doubleSided"] !== "boolean") {+ if (record["doubleSided"] !== undefined && typeof record["doubleSided"] !== "boolean") {throw new ProceduralTextureError("portableMaterial.doubleSided must be boolean.");}- const name = optionalName(record4["name"], "portableMaterial.name");+ const name = optionalName(record["name"], "portableMaterial.name");return {schemaVersion: 2,model: "pbrMetallicRoughness",...name !== undefined ? { name } : {},- ...record4["baseColor"] !== undefined ? { baseColor: color(record4["baseColor"], "portableMaterial.baseColor") } : {},- roughness: unit(record4["roughness"], "portableMaterial.roughness", 1),- metalness: unit(record4["metalness"], "portableMaterial.metalness", 0),- ...record4["emissive"] !== undefined ? { emissive: color(record4["emissive"], "portableMaterial.emissive") } : {},- emissiveIntensity: finite(record4["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),- alphaMode: alphaMode2,- alphaCutoff: unit(record4["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),- doubleSided: record4["doubleSided"] === true,+ ...record["baseColor"] !== undefined ? { baseColor: color(record["baseColor"], "portableMaterial.baseColor") } : {},+ roughness: unit(record["roughness"], "portableMaterial.roughness", 1),+ metalness: unit(record["metalness"], "portableMaterial.metalness", 0),+ ...record["emissive"] !== undefined ? { emissive: color(record["emissive"], "portableMaterial.emissive") } : {},+ emissiveIntensity: finite(record["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),+ alphaMode,+ alphaCutoff: unit(record["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),+ doubleSided: record["doubleSided"] === true,textures};}@@ -13714,11 +13693,11 @@ function compileProceduralTextureSpecV2(input) {}function proceduralTexture(spec) {const compiled = compileProceduralTextureSpecV2(spec);- const { size, usage: usage2, name, layers } = compiled.spec;+ const { size, usage, name, layers } = compiled.spec;const tex = new THREE23.DataTexture(compiled.pixels, size, size, THREE23.RGBAFormat, THREE23.UnsignedByteType);if (name)tex.name = name;- tex.colorSpace = usage2 === "albedo" || usage2 === "emissive" ? THREE23.SRGBColorSpace : THREE23.NoColorSpace;+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE23.SRGBColorSpace : THREE23.NoColorSpace;tex.wrapS = THREE23.RepeatWrapping;tex.wrapT = THREE23.RepeatWrapping;tex.minFilter = THREE23.LinearMipmapLinearFilter;@@ -13728,7 +13707,7 @@ function proceduralTexture(spec) {tex.userData["kilnProcedural"] = {schemaVersion: 2,size,- usage: usage2,+ usage,...name ? { name } : {},layers,canonicalJson: compiled.canonicalJson,@@ -13787,10 +13766,10 @@ function normalMapFromHeight(source, opts = {}) {tex.needsUpdate = true;return tex;}-var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color2) => [- color2 >> 16 & 255,- color2 >> 8 & 255,- color2 & 255+var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color) => [+ color >> 16 & 255,+ color >> 8 & 255,+ color & 255], lerp = (a, b, t) => a + (b - a) * t;var init_procedural_texture = __esm(() => {init_procedural_material_v2();@@ -15305,27 +15284,27 @@ function resolveMaterialRecipeV1(value) {if (!validation.valid || !validation.value) {throw new TypeError(validation.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; "));}- const recipe2 = MATERIAL_RECIPE_LIBRARY_V1[validation.value.id];+ const recipe = MATERIAL_RECIPE_LIBRARY_V1[validation.value.id];const over = validation.value.overrides ?? {};- const baseAlpha = over.opacity ?? recipe2.defaults.baseColorFactor[3];+ const baseAlpha = over.opacity ?? recipe.defaults.baseColorFactor[3];const baseColorFactor = over.baseColor ? rgba(over.baseColor, baseAlpha) : Object.freeze([- recipe2.defaults.baseColorFactor[0],- recipe2.defaults.baseColorFactor[1],- recipe2.defaults.baseColorFactor[2],+ recipe.defaults.baseColorFactor[0],+ recipe.defaults.baseColorFactor[1],+ recipe.defaults.baseColorFactor[2],baseAlpha]);const emissiveIntensity = over.emissiveIntensity;- const emissiveFactor = over.emissiveColor ? rgb(over.emissiveColor, over.emissiveIntensity ?? 1) : emissiveIntensity !== undefined ? Object.freeze(recipe2.defaults.emissiveFactor.map((component) => component * emissiveIntensity)) : recipe2.defaults.emissiveFactor;+ const emissiveFactor = over.emissiveColor ? rgb(over.emissiveColor, over.emissiveIntensity ?? 1) : emissiveIntensity !== undefined ? Object.freeze(recipe.defaults.emissiveFactor.map((component) => component * emissiveIntensity)) : recipe.defaults.emissiveFactor;return Object.freeze({baseColorFactor,- metallicFactor: over.metalness ?? recipe2.defaults.metallicFactor,- roughnessFactor: over.roughness ?? recipe2.defaults.roughnessFactor,+ metallicFactor: over.metalness ?? recipe.defaults.metallicFactor,+ roughnessFactor: over.roughness ?? recipe.defaults.roughnessFactor,emissiveFactor,- alphaMode: recipe2.defaults.alphaMode,- ...recipe2.defaults.alphaMode === "MASK" ? { alphaCutoff: over.alphaCutoff ?? recipe2.defaults.alphaCutoff ?? 0.5 } : {},- doubleSided: over.doubleSided ?? recipe2.defaults.doubleSided,+ alphaMode: recipe.defaults.alphaMode,+ ...recipe.defaults.alphaMode === "MASK" ? { alphaCutoff: over.alphaCutoff ?? recipe.defaults.alphaCutoff ?? 0.5 } : {},+ doubleSided: over.doubleSided ?? recipe.defaults.doubleSided,textureResources: Object.freeze({- ...recipe2.defaults.textureResources,+ ...recipe.defaults.textureResources,...over.textureResources ?? {}})});@@ -15339,11 +15318,11 @@ var MATERIAL_RECIPE_IDS, MATERIAL_RECIPE_OVERRIDE_KEYS, APPROVED_TEXTURE_RESOURCalpha]);}, rgb = (hex, intensity = 1) => {- const color2 = rgba(hex);+ const color = rgba(hex);return Object.freeze([- color2[0] * intensity,- color2[1] * intensity,- color2[2] * intensity+ color[0] * intensity,+ color[1] * intensity,+ color[2] * intensity]);}, defaults = (baseColor, roughnessFactor, metallicFactor = 0, over = {}) => Object.freeze({baseColorFactor: rgba(baseColor),@@ -15620,59 +15599,59 @@ var init_material_recipes = __esm(() => {// src/material-resources.tsimport { createHash as createHash2 } from "node:crypto";-function provenance(descriptor2, hash) {+function provenance(descriptor, hash) {return {schemaVersion: 1,- resourceId: descriptor2.id,+ resourceId: descriptor.id,contentHash: hash,hashAlgorithm: "sha256",- usage: descriptor2.usage,- colorSpace: descriptor2.colorSpace,- resourceVersion: descriptor2.version,+ usage: descriptor.usage,+ colorSpace: descriptor.colorSpace,+ resourceVersion: descriptor.version,recipeVersion: 1,- delivery: descriptor2.delivery+ delivery: descriptor.delivery};}-function readPngDimensions(descriptor2, bytes) {+function readPngDimensions(descriptor, bytes) {const signature = [137, 80, 78, 71, 13, 10, 26, 10];if (bytes.byteLength < 24 || !signature.every((value, index) => bytes[index] === value) || String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR") {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "declared image/png bytes do not have a valid PNG signature and IHDR format");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "declared image/png bytes do not have a valid PNG signature and IHDR format");}const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);return { width: view.getUint32(16, false), height: view.getUint32(20, false) };}-function verifyResourcePayload(descriptor2, payload) {+function verifyResourcePayload(descriptor, payload) {if (!payload || typeof payload !== "object" || Array.isArray(payload)) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host payload must be { bytes, mime }");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host payload must be { bytes, mime }");}const keys = Object.keys(payload).sort();if (keys.length !== 2 || keys[0] !== "bytes" || keys[1] !== "mime") {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host payload must contain only bytes and MIME");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host payload must contain only bytes and MIME");}if (!(payload.bytes instanceof Uint8Array)) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host bytes must be Uint8Array");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host bytes must be Uint8Array");}- if (payload.mime !== descriptor2.mime) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `host MIME ${String(payload.mime)} does not match approved ${descriptor2.mime}`);+ if (payload.mime !== descriptor.mime) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `host MIME ${String(payload.mime)} does not match approved ${descriptor.mime}`);}const bytes = payload.bytes;if (bytes.byteLength > TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `encoded-byte limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes}; received ${bytes.byteLength}`);+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `encoded-byte limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes}; received ${bytes.byteLength}`);}- if (bytes.byteLength !== descriptor2.byteLength) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `expected ${descriptor2.byteLength} bytes, received ${bytes.byteLength}`);+ if (bytes.byteLength !== descriptor.byteLength) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `expected ${descriptor.byteLength} bytes, received ${bytes.byteLength}`);}- const { width, height } = readPngDimensions(descriptor2, bytes);+ const { width, height } = readPngDimensions(descriptor, bytes);if (width < 1 || height < 1 || width > TEXTURE_RESOLVER_LIMITS_V1.maxWidth || height > TEXTURE_RESOLVER_LIMITS_V1.maxHeight) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `dimension limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxWidth}x${TEXTURE_RESOLVER_LIMITS_V1.maxHeight}; received ${width}x${height}`);+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `dimension limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxWidth}x${TEXTURE_RESOLVER_LIMITS_V1.maxHeight}; received ${width}x${height}`);}const pixels = width * height;if (!Number.isSafeInteger(pixels) || pixels > TEXTURE_RESOLVER_LIMITS_V1.maxPixels) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`);+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`);}const hash = sha256(bytes);- if (hash !== descriptor2.contentHash) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `content hash ${hash} does not match the pinned ${descriptor2.contentHash}`);+ if (hash !== descriptor.contentHash) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `content hash ${hash} does not match the pinned ${descriptor.contentHash}`);}return hash;}@@ -15734,12 +15713,12 @@ class ApprovedTextureResourceCache {const hash = this.#hashById.get(id);if (hash)return this.#resolution(id, hash);- const descriptor2 = this.#registry[id];- if (descriptor2.delivery !== "embedded") {+ const descriptor = this.#registry[id];+ if (descriptor.delivery !== "embedded") {throw new ApprovedTextureResourceUnavailableError(id, "it is delivered at runtime; use resolveAsync() or load()");}const decoded = bytesFromBase64(EMBEDDED_RESOURCE_BASE64[id]);- this.#cacheBytes(id, verifyResourcePayload(descriptor2, { bytes: decoded, mime: descriptor2.mime }), decoded);+ this.#cacheBytes(id, verifyResourcePayload(descriptor, { bytes: decoded, mime: descriptor.mime }), decoded);return this.#resolution(id, this.#hashById.get(id));}async resolveAsync(id) {@@ -15752,7 +15731,7 @@ class ApprovedTextureResourceCache {return this.resolve(id);let pending = this.#pendingById.get(id);if (!pending) {- const descriptor2 = this.#registry[id];+ const descriptor = this.#registry[id];const resolver = this.#resolver;pending = (async () => {if (!resolver) {@@ -15769,7 +15748,7 @@ class ApprovedTextureResourceCache {let payload;try {payload = await Promise.race([- Promise.resolve().then(() => resolver(descriptor2, Object.freeze({+ Promise.resolve().then(() => resolver(descriptor, Object.freeze({signal: controller.signal,deadlineMs: this.#resolverDeadlineMs}))),@@ -15779,7 +15758,7 @@ class ApprovedTextureResourceCache {if (timer !== undefined)clearTimeout(timer);}- this.#cacheBytes(id, verifyResourcePayload(descriptor2, payload), payload.bytes);+ this.#cacheBytes(id, verifyResourcePayload(descriptor, payload), payload.bytes);return this.#resolution(id, this.#hashById.get(id));})().finally(() => {this.#pendingById.delete(id);@@ -15789,28 +15768,28 @@ class ApprovedTextureResourceCache {return pending;}async load(id) {- const resolved2 = await this.resolveAsync(id);+ const resolved = await this.resolveAsync(id);const variantKey = [- resolved2.provenance.contentHash,- resolved2.provenance.usage,- resolved2.provenance.colorSpace+ resolved.provenance.contentHash,+ resolved.provenance.usage,+ resolved.provenance.colorSpace].join(":");let pending = this.#textureByVariant.get(variantKey);if (!pending) {- pending = loadTexture(resolved2.bytes, {- usage: resolved2.provenance.usage,+ pending = loadTexture(resolved.bytes, {+ usage: resolved.provenance.usage,name: id}).then((texture) => {const metadata = texture.userData["kilnTexture"];texture.userData["kilnTexture"] = {...metadata,- approvedResource: resolved2.provenance+ approvedResource: resolved.provenance};return texture;});this.#textureByVariant.set(variantKey, pending);}- return { ...resolved2, texture: await pending };+ return { ...resolved, texture: await pending };}stats() {return {@@ -15853,9 +15832,9 @@ function collectMaterialResourceProvenance(root) {const materials = Array.isArray(material) ? material : material ? [material] : [];for (const item of materials) {for (const texture of materialTextures2(item)) {- const record4 = readMaterialResourceProvenance(texture);- if (record4)- records.set(`${record4.resourceId}:${record4.contentHash}:${record4.usage}`, record4);+ const record = readMaterialResourceProvenance(texture);+ if (record)+ records.set(`${record.resourceId}:${record.contentHash}:${record.usage}`, record);}}});@@ -15917,12 +15896,12 @@ async function compilePortableMaterialSpecV2(input) {if (!isApprovedResourceId(ref.resourceId)) {throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not an approved texture resource ID.`);}- const descriptor2 = cache.descriptor(ref.resourceId);- if (!descriptor2.allowedSlots.includes(slot)) {+ const descriptor = cache.descriptor(ref.resourceId);+ if (!descriptor.allowedSlots.includes(slot)) {throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not approved for that slot.`);}- if (descriptor2.usage !== SLOT_USAGE[slot]) {- throw new ProceduralTextureError(`portableMaterial.textures.${slot} requires ${SLOT_USAGE[slot]} data, but ${JSON.stringify(ref.resourceId)} provides ${descriptor2.usage}.`);+ if (descriptor.usage !== SLOT_USAGE[slot]) {+ throw new ProceduralTextureError(`portableMaterial.textures.${slot} requires ${SLOT_USAGE[slot]} data, but ${JSON.stringify(ref.resourceId)} provides ${descriptor.usage}.`);}}const loaded = new Map;@@ -16203,19 +16182,19 @@ var init_uv_shapes = () => {};// src/material-recipe-runtime.tsimport * as THREE26 from "three";async function applyMaterialRecipeV1(request, options = {}) {- const resolved2 = resolveMaterialRecipeV1(request);+ const resolved = resolveMaterialRecipeV1(request);const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;const loaded = new Map;- for (const [slot, id] of Object.entries(resolved2.textureResources)) {+ for (const [slot, id] of Object.entries(resolved.textureResources)) {if (id)loaded.set(slot, await cache.load(id));}const materialOptions = {- roughness: resolved2.roughnessFactor,- metalness: resolved2.metallicFactor,- alphaMode: lowerAlphaMode(resolved2.alphaMode),- ...resolved2.alphaMode === "MASK" ? { alphaCutoff: resolved2.alphaCutoff ?? 0.5 } : {},- doubleSided: resolved2.doubleSided,+ roughness: resolved.roughnessFactor,+ metalness: resolved.metallicFactor,+ alphaMode: lowerAlphaMode(resolved.alphaMode),+ ...resolved.alphaMode === "MASK" ? { alphaCutoff: resolved.alphaCutoff ?? 0.5 } : {},+ doubleSided: resolved.doubleSided,...loaded.get("baseColor") ? { albedo: loaded.get("baseColor").texture } : {},...loaded.get("normal") ? { normal: loaded.get("normal").texture } : {},...loaded.get("metallicRoughness") ? { metallicRoughness: loaded.get("metallicRoughness").texture } : {},@@ -16224,11 +16203,11 @@ async function applyMaterialRecipeV1(request, options = {}) {};const material = pbrMaterial(materialOptions);material.name = options.name ?? request.id;- material.color.setRGB(resolved2.baseColorFactor[0], resolved2.baseColorFactor[1], resolved2.baseColorFactor[2], THREE26.LinearSRGBColorSpace);- material.opacity = resolved2.baseColorFactor[3];- material.emissive.setRGB(resolved2.emissiveFactor[0], resolved2.emissiveFactor[1], resolved2.emissiveFactor[2], THREE26.LinearSRGBColorSpace);+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE26.LinearSRGBColorSpace);+ material.opacity = resolved.baseColorFactor[3];+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE26.LinearSRGBColorSpace);const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));- const provenance2 = {+ const provenance = {schemaVersion: 1,recipeId: request.id,recipeVersion: 1,@@ -16245,8 +16224,8 @@ async function applyMaterialRecipeV1(request, options = {}) {portableModel: "pbrMetallicRoughness",resources};- material.userData["kilnMaterialRecipe"] = provenance2;- return { material, resolved: resolved2, provenance: provenance2 };+ material.userData["kilnMaterialRecipe"] = provenance;+ return { material, resolved, provenance };}async function materialRecipe(id, overrides, options = {}) {return (await applyMaterialRecipeV1(createMaterialRecipeRequestV1(id, overrides), options)).material;@@ -16349,26 +16328,26 @@ function createPart(name, geometry2, material, options = {}) {function capsuleGeo(radius, height, segments = 6) {return new THREE27.CapsuleGeometry(radius, height, 2, segments);}-function capsuleXGeo(radius, length3, segments = 6) {- const geo = capsuleGeo(radius, length3, segments);+function capsuleXGeo(radius, length, segments = 6) {+ const geo = capsuleGeo(radius, length, segments);geo.rotateZ(-Math.PI / 2);return geo;}-function capsuleZGeo(radius, length3, segments = 6) {- const geo = capsuleGeo(radius, length3, segments);+function capsuleZGeo(radius, length, segments = 6) {+ const geo = capsuleGeo(radius, length, segments);geo.rotateX(Math.PI / 2);return geo;}function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {return new THREE27.CylinderGeometry(radiusTop, radiusBottom, height, segments);}-function cylinderXGeo(radiusTop, radiusBottom, length3, segments = 8) {- const geo = cylinderGeo(radiusTop, radiusBottom, length3, segments);+function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {+ const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);geo.rotateZ(-Math.PI / 2);return geo;}-function cylinderZGeo(radiusTop, radiusBottom, length3, segments = 8) {- const geo = cylinderGeo(radiusTop, radiusBottom, length3, segments);+function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {+ const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);geo.rotateX(Math.PI / 2);return geo;}@@ -16381,13 +16360,13 @@ function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {function coneGeo(radius, height, segments = 8) {return new THREE27.ConeGeometry(radius, height, segments);}-function coneXGeo(radius, length3, segments = 8) {- const geo = coneGeo(radius, length3, segments);+function coneXGeo(radius, length, segments = 8) {+ const geo = coneGeo(radius, length, segments);geo.rotateZ(-Math.PI / 2);return geo;}-function coneZGeo(radius, length3, segments = 8) {- const geo = coneGeo(radius, length3, segments);+function coneZGeo(radius, length, segments = 8) {+ const geo = coneGeo(radius, length, segments);geo.rotateX(Math.PI / 2);return geo;}@@ -16440,10 +16419,10 @@ function crossedQuadsGeo(opts = {}) {const yPivot = opts.yPivot ?? 0;const geometries = [];for (let i = 0;i < planes; i++) {- const angle2 = i / planes * Math.PI;+ const angle = i / planes * Math.PI;const quad = new THREE27.PlaneGeometry(w, h);quad.translate(0, h * (0.5 - yPivot), 0);- quad.rotateY(angle2);+ quad.rotateY(angle);geometries.push(quad);}const out = new THREE27.BufferGeometry;@@ -16599,11 +16578,11 @@ function beamBetween(name, start, end, radius, material, options = {}) {const a = new THREE27.Vector3(...start);const b = new THREE27.Vector3(...end);const direction = b.clone().sub(a);- const length3 = direction.length();- if (length3 <= 0.0001) {- throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length3.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);+ const length = direction.length();+ if (length <= 0.0001) {+ throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);}- const mesh = new THREE27.Mesh(cylinderGeo(radius, radius, length3, options.segments ?? 8), material);+ const mesh = new THREE27.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);mesh.name = `Mesh_${name}`;mesh.position.copy(a.add(b).multiplyScalar(0.5));mesh.quaternion.setFromUnitVectors(new THREE27.Vector3(0, 1, 0), direction.normalize());@@ -16678,7 +16657,7 @@ function createLadder(name, options) {return { leftRail, rightRail, rungs };}function wallWithOpening(name, material, options) {- const { length: length3, height, thickness, axis = "z", opening, parent } = options;+ const { length, height, thickness, axis = "z", opening, parent } = options;const group = new THREE27.Object3D;group.name = name;const overlap = 0.02;@@ -16694,7 +16673,7 @@ function wallWithOpening(name, material, options) {createPart(`${name}${suffix}`, geo, material, { position: pos, parent: group });};if (!opening) {- panel("", -length3 / 2, length3 / 2, 0, height);+ panel("", -length / 2, length / 2, 0, height);} else {const ow = opening.width ?? (opening.kind === "window" ? 1 : 1.1);const oh = opening.height ?? (opening.kind === "window" ? 1 : 2.1);@@ -16703,8 +16682,8 @@ function wallWithOpening(name, material, options) {const right = off + ow / 2;const sill = opening.kind === "window" ? Math.max(opening.sill ?? 1, 0) : 0;const top = Math.min(sill + oh, height);- panel("_L", -length3 / 2, left, 0, height);- panel("_R", right, length3 / 2, 0, height);+ panel("_L", -length / 2, left, 0, height);+ panel("_R", right, length / 2, 0, height);panel("_Lintel", left - overlap, right + overlap, top, height);if (sill > 0)panel("_Sill", left - overlap, right + overlap, 0, sill);@@ -16726,8 +16705,8 @@ function room(name, material, options = {}) {const openings = options.openings ?? [{ wall: "front", kind: "door" }];const root = new THREE27.Object3D;root.name = name;- const openingFor = (wall2) => {- const found = openings.find((op) => op.wall === wall2);+ const openingFor = (wall) => {+ const found = openings.find((op) => op.wall === wall);if (!found)return;const { wall: _wall, ...rest } = found;@@ -16773,8 +16752,8 @@ function createRoofPlanes2(name, material, options) {}if ((options.ridgeAxis ?? "x") === "x") {const halfRun = options.width / 2 + (options.overhang ?? 0.3);- const angle2 = Math.atan2(options.height, halfRun);- result.slopes[1].rotation.set(-angle2, Math.PI, 0);+ const angle = Math.atan2(options.height, halfRun);+ result.slopes[1].rotation.set(-angle, Math.PI, 0);}return result;}@@ -16817,16 +16796,16 @@ function createStairs(name, material, options) {parent.add(root);return { root, steps: stepList };}-function requireColor(color2, fn) {- if (typeof color2 === "number" || typeof color2 === "string")+function requireColor(color, fn) {+ if (typeof color === "number" || typeof color === "string")return;- const got = color2 && typeof color2 === "object" ? `an object with keys [${Object.keys(color2).join(", ")}]` : String(color2);+ const got = color && typeof color === "object" ? `an object with keys [${Object.keys(color).join(", ")}]` : String(color);throw new Error(`${fn}(color, options?): color must be a hex number like 0x8c4a32 or a CSS string, got ${got}. ` + `Material settings go in the SECOND argument: ${fn}(0x8c4a32, { roughness: 0.5, metalness: 0.9 }).`);}-function gameMaterial(color2, options = {}) {- requireColor(color2, "gameMaterial");+function gameMaterial(color, options = {}) {+ requireColor(color, "gameMaterial");return new THREE27.MeshStandardMaterial({- color: color2,+ color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,emissive: options.emissive ?? 0,@@ -16834,18 +16813,18 @@ function gameMaterial(color2, options = {}) {flatShading: options.flatShading ?? true});}-function basicMaterial(color2, options = {}) {- requireColor(color2, "basicMaterial");+function basicMaterial(color, options = {}) {+ requireColor(color, "basicMaterial");return new THREE27.MeshBasicMaterial({- color: color2,+ color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1});}-function glassMaterial(color2, options = {}) {- requireColor(color2, "glassMaterial");+function glassMaterial(color, options = {}) {+ requireColor(color, "glassMaterial");return new THREE27.MeshStandardMaterial({- color: color2,+ color,transparent: true,opacity: options.opacity ?? 0.35,roughness: options.roughness ?? 0.1,@@ -16853,10 +16832,10 @@ function glassMaterial(color2, options = {}) {side: THREE27.DoubleSide});}-function lambertMaterial(color2, options = {}) {- requireColor(color2, "lambertMaterial");+function lambertMaterial(color, options = {}) {+ requireColor(color, "lambertMaterial");return new THREE27.MeshLambertMaterial({- color: color2,+ color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0});@@ -17023,12 +17002,12 @@ function validateAsset(root, category) {}return { valid: true, errors, warnings };}-function buildSandboxGlobals(usage2, options = {}) {+function buildSandboxGlobals(usage, options = {}) {const wrap = (name, fn) => {- if (!usage2)+ if (!usage)return fn;const wrapped = (...args) => {- usage2[name] = (usage2[name] ?? 0) + 1;+ usage[name] = (usage[name] ?? 0) + 1;return fn(...args);};return wrapped;@@ -17056,9 +17035,9 @@ function buildSandboxGlobals(usage2, options = {}) {try {key = `${name}::${JSON.stringify(args)}`;} catch {- const result2 = fn(...args);- stampKilnRange(name, result2);- return result2;+ const result = fn(...args);+ stampKilnRange(name, result);+ return result;}const hit = geoCache.get(key);if (hit)@@ -17367,24 +17346,7 @@ async function validateFinalGlbBytes(bytes, uri = "model.glb") {});return normalizeReport(raw);}-async function assertFinalGlbValid(bytes, uri = "model.glb") {- const report = await validateFinalGlbBytes(bytes, uri);- if (report.issues.numErrors > 0)- throw new GltfValidationError(report);- return report;-}-var GltfValidationError;-var init_gltf = __esm(() => {- GltfValidationError = class GltfValidationError extends Error {- report;- constructor(report) {- const first = report.issues.messages.find((issue) => issue.severity === 0);- super(`Final GLB failed Khronos validation with ${report.issues.numErrors} error(s)` + (first ? `: ${first.code} — ${first.message}` : "."));- this.name = "GltfValidationError";- this.report = report;- }- };-});+var init_gltf = () => {};// src/qa/breadth-final.tsimport { WebIO } from "@gltf-transform/core";@@ -17444,25 +17406,25 @@ function signedAxis2(vector) {function finalEffectAxis(nodes, mode) {let best;for (const node of nodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic3?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());- const scale2 = node.getWorldScale();- const scaleMagnitude = Math.hypot(scale2[0], scale2[1], scale2[2]);+ const scale = node.getWorldScale();+ const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);for (const primitive of node.getMesh()?.listPrimitives() ?? []) {const position = primitive.getAttribute("POSITION");if (!position)continue;const min = position.getMin([]);const max = position.getMax([]);- const axes2 = [+ const axes = [{ score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },{ score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },{ score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }];- const selected = axes2.reduce((candidate2, value) => mode === "length" ? value.score > candidate2.score ? value : candidate2 : value.score < candidate2.score ? value : candidate2);+ const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const candidate = {score: selected.score * scaleMagnitude,direction: selected.direction.transformDirection(matrix)@@ -17481,16 +17443,16 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);const meshes = [...new Set(renderableNodes.map((node) => node.getMesh()).filter(Boolean))];const primitives = meshes.flatMap((mesh) => mesh?.listPrimitives() ?? []);- let triangleCount2 = 0;+ let triangleCount = 0;for (const primitive of primitives) {const indices = primitive.getIndices();const position = primitive.getAttribute("POSITION");- triangleCount2 += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;+ triangleCount += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;}const effectSurfaceMaterials = new Set;for (const node of renderableNodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic3?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}for (const primitive of node.getMesh()?.listPrimitives() ?? []) {@@ -17518,8 +17480,8 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {});const facingSemantics = new Set;for (const node of renderableNodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- for (const role of semantic3?.roles ?? []) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ for (const role of semantic?.roles ?? []) {const match = /^vfx\.facing\.(fixed|camera-spherical|camera-y-axis)$/.exec(role);if (match)facingSemantics.add(match[1]);@@ -17531,7 +17493,7 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {schemaVersion: 1,meshCount: meshes.length,primitiveCount: primitives.length,- triangleCount: Math.floor(triangleCount2),+ triangleCount: Math.floor(triangleCount),materials,facingSemantics: [...facingSemantics].sort(),...normalAxis ? { normalAxis } : {},@@ -17545,12 +17507,12 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {function finalFinding(intent, value) {return { ...value, profile: intent.qaProfile || "vfx.w7.final-glb" };}-function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {+function evaluateFinalVfxGlbEvidenceV1(intent, evidence) {if (intent.category !== "vfx" || !intent.vfx)return [];const contract = intent.vfx;const findings = [];- if (evidence2.meshCount === 0 || evidence2.primitiveCount === 0 || evidence2.triangleCount === 0) {+ if (evidence.meshCount === 0 || evidence.primitiveCount === 0 || evidence.triangleCount === 0) {findings.push(finalFinding(intent, {code: "VFX_GLTF_RENDERABLE_MISSING",disposition: "block",@@ -17558,13 +17520,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB contains no renderable VFX geometry.",measurement: {name: "finalVfxTriangles",- actual: evidence2.triangleCount,+ actual: evidence.triangleCount,expected: ">=1"},repairText: "Export the effect surface as portable geometry before final-byte approval."}));}- const effectMaterials = evidence2.materials.filter((material) => material.effectSurface);+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface);if (effectMaterials.length === 0) {findings.push(finalFinding(intent, {code: "VFX_GLTF_EFFECT_SURFACE_MISSING",@@ -17624,7 +17586,7 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {}));}}- if (contract.facing.mode !== "fixed" && !evidence2.facingSemantics.includes(contract.facing.mode)) {+ if (contract.facing.mode !== "fixed" && !evidence.facingSemantics.includes(contract.facing.mode)) {findings.push(finalFinding(intent, {code: "VFX_GLTF_FACING_SEMANTIC_MISSING",disposition: "block",@@ -17632,13 +17594,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: `Final GLB does not carry the ${contract.facing.mode} runtime-facing semantic.`,measurement: {name: "finalFacingSemantics",- actual: evidence2.facingSemantics.join(",") || null,+ actual: evidence.facingSemantics.join(",") || null,expected: contract.facing.mode},repairText: "Preserve the exporter-derived billboard semantic on the renderable quad node."}));}- if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence2.normalAxis) {+ if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence.normalAxis) {findings.push(finalFinding(intent, {code: "VFX_GLTF_NORMAL_AXIS_MISMATCH",disposition: "block",@@ -17646,12 +17608,12 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB effect-surface normal axis differs from explicit VFX intent.",measurement: {name: "finalNormalAxis",- actual: evidence2.normalAxis ?? null,+ actual: evidence.normalAxis ?? null,expected: contract.facing.normalAxis ?? null}}));}- if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence2.directionAxis) {+ if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence.directionAxis) {findings.push(finalFinding(intent, {code: "VFX_GLTF_DIRECTION_AXIS_MISMATCH",disposition: "block",@@ -17659,13 +17621,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB effect-surface direction axis differs from explicit VFX intent.",measurement: {name: "finalDirectionAxis",- actual: evidence2.directionAxis ?? null,+ actual: evidence.directionAxis ?? null,expected: contract.facing.directionAxis}}));}if (contract.animation.driver === "clip") {- const clip = evidence2.clips.find((candidate) => candidate.name === contract.animation.clipName);+ const clip = evidence.clips.find((candidate) => candidate.name === contract.animation.clipName);if (!clip || Math.abs(clip.durationSeconds - contract.animation.durationSeconds) > 0.000001) {findings.push(finalFinding(intent, {code: "VFX_GLTF_REQUIRED_CLIP_MISSING",@@ -17688,24 +17650,24 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {async function appendFinalVfxGlbQa(intent, report, bytes) {if (intent.category !== "vfx")return report;- const evidence2 = await analyzeFinalVfxGlbBytesV1(bytes);+ const evidence = await analyzeFinalVfxGlbBytesV1(bytes);const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);- findings.push(...evaluateFinalVfxGlbEvidenceV1(intent, evidence2));+ findings.push(...evaluateFinalVfxGlbEvidenceV1(intent, evidence));const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);if (!evaluatedDimensions.includes("exportIntegrity"))evaluatedDimensions.push("exportIntegrity");const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));metrics.exportIntegrity = {...metrics.exportIntegrity ?? {},- finalVfxMeshCount: evidence2.meshCount,- finalVfxPrimitiveCount: evidence2.primitiveCount,- finalVfxTriangles: evidence2.triangleCount,- finalVfxMaterialCount: evidence2.materials.length,- finalVfxEffectMaterialCount: evidence2.materials.filter((material) => material.effectSurface).length,- finalVfxFacingSemantics: evidence2.facingSemantics.join(","),- finalVfxNormalAxis: evidence2.normalAxis ?? null,- finalVfxDirectionAxis: evidence2.directionAxis ?? null,- finalVfxClipCount: evidence2.clips.length+ finalVfxMeshCount: evidence.meshCount,+ finalVfxPrimitiveCount: evidence.primitiveCount,+ finalVfxTriangles: evidence.triangleCount,+ finalVfxMaterialCount: evidence.materials.length,+ finalVfxEffectMaterialCount: evidence.materials.filter((material) => material.effectSurface).length,+ finalVfxFacingSemantics: evidence.facingSemantics.join(","),+ finalVfxNormalAxis: evidence.normalAxis ?? null,+ finalVfxDirectionAxis: evidence.directionAxis ?? null,+ finalVfxClipCount: evidence.clips.length};return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });}@@ -17839,7 +17801,7 @@ function evaluateMaterialBudgetV1(metrics, options) {});}if (metrics.decodedImageBytesRgba8 > limits.maxDecodedBytesRgba8) {- const scale2 = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);+ const scale = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);warnings.push({code: "MATERIAL_DECODED_MEMORY_BUDGET",disposition: "warn",@@ -17852,7 +17814,7 @@ function evaluateMaterialBudgetV1(metrics, options) {threshold: limits.maxDecodedBytesRgba8,unit: "bytes"},- advice: `Downscale image width and height by approximately ${(Math.min(1, scale2) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`+ advice: `Downscale image width and height by approximately ${(Math.min(1, scale) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`});}if (metrics.blendedSurfaceAreaRatio > limits.maxBlendedSurfaceAreaRatio) {@@ -17954,11 +17916,11 @@ var init_material_metrics = __esm(() => {// src/texture-resolver.tsfunction createTextureResolver(cache = DEFAULT_APPROVED_TEXTURE_CACHE) {return Object.freeze({- async loadApprovedTexture(resourceId2) {- if (typeof resourceId2 !== "string") {+ async loadApprovedTexture(resourceId) {+ if (typeof resourceId !== "string") {throw new RangeError("Unsupported approved texture resource ID.");}- return (await cache.load(resourceId2)).texture;+ return (await cache.load(resourceId)).texture;},async materialRecipe(id, overrides) {if (typeof id !== "string")@@ -19179,32 +19141,32 @@ function analyzeGeneratedSourceSafety(ast) {const issues = [];const seen = new Set;const staticStrings = collectStaticStringBindings(ast);- const add2 = (issue) => {+ const add = (issue) => {const key = issueKey(issue);if (seen.has(key))return;seen.add(key);issues.push(issue);};- const ambient = (name, line) => add2({+ const ambient = (name, line) => add({code: "UNSAFE_GLOBAL_ACCESS",message: `Generated code cannot access ambient capability \`${name}\`.`,fixHint: "Use only the documented sandbox globals and approved resource helpers.",line});- const dynamicCode = (line) => add2({+ const dynamicCode = (line) => add({code: "DYNAMIC_CODE_ACCESS",message: "Generated code cannot access constructor chains or dynamic-code constructors.",fixHint: "Call documented sandbox helpers directly; do not derive constructors at runtime.",line});- const unsafeThree = (name, line) => add2({+ const unsafeThree = (name, line) => add({code: "UNSAFE_THREE_CONSTRUCTOR",message: `Generated code cannot access raw THREE constructor \`${name}\`.`,fixHint: "Use approved texture loading, proceduralTexture, pbrMaterial, or materialRecipe instead.",line});- const unsafeThreeNamespace = (code, line) => add2({+ const unsafeThreeNamespace = (code, line) => add({code,message: code === "UNSAFE_THREE_ALIAS" ? "Generated code cannot alias the THREE namespace." : "Generated code cannot use non-static computed access on the THREE namespace.",fixHint: "Use a documented direct THREE constructor or a sandbox material/texture helper.",@@ -19223,7 +19185,7 @@ function analyzeGeneratedSourceSafety(ast) {ambient("this", node.loc?.start.line);},ImportExpression(node) {- add2({+ add({code: "DYNAMIC_IMPORT",message: "Generated code cannot use dynamic import.",fixHint: "Remove import(); all supported helpers are already sandbox globals.",@@ -19744,234 +19706,9 @@ var init_validation = __esm(() => {// src/kit.tsimport { execFile } from "node:child_process";-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";import { promisify } from "node:util";import { KHRMaterialsVariants, KHRTextureBasisu } from "@gltf-transform/extensions";-async function findKtxEncoder() {- if (cachedEncoder !== undefined)- return cachedEncoder ?? undefined;- for (const candidate of KTX_ENCODER_CANDIDATES) {- try {- await run(candidate, ["--version"], { timeout: 1e4 });- cachedEncoder = candidate;- return candidate;- } catch {}- }- cachedEncoder = null;- return;-}-function disposeIfOrphaned(texture) {- const stillUsed = texture.listParents().some((parent) => parent.propertyType !== "Root");- if (!stillUsed)- texture.dispose();-}-async function packOcclusionIntoMetallicRoughness(doc) {- const sharp = (await import("sharp")).default;- let packed = 0;- for (const material of doc.getRoot().listMaterials()) {- const occlusion = material.getOcclusionTexture();- const metallicRoughness = material.getMetallicRoughnessTexture();- if (!occlusion || !metallicRoughness || occlusion === metallicRoughness)- continue;- if (!isPng(occlusion) || !isPng(metallicRoughness))- continue;- const occlusionBytes = occlusion.getImage();- const mrBytes = metallicRoughness.getImage();- if (!occlusionBytes || !mrBytes)- continue;- try {- const [occImage, mrImage] = await Promise.all([- sharp(Buffer.from(occlusionBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true }),- sharp(Buffer.from(mrBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true })- ]);- if (occImage.info.width !== mrImage.info.width || occImage.info.height !== mrImage.info.height) {- continue;- }- const { width, height } = mrImage.info;- const merged = Buffer.allocUnsafe(width * height * 3);- for (let i = 0, o = 0;o < merged.length; i += 4, o += 3) {- merged[o] = occImage.data[i] ?? 255;- merged[o + 1] = mrImage.data[i + 1] ?? 255;- merged[o + 2] = mrImage.data[i + 2] ?? 255;- }- const png = await sharp(merged, { raw: { width, height, channels: 3 } }).png({ compressionLevel: 9 }).toBuffer();- metallicRoughness.setImage(new Uint8Array(png));- material.setOcclusionTexture(metallicRoughness);- const info = material.getOcclusionTextureInfo();- const mrInfo = material.getMetallicRoughnessTextureInfo();- if (info && mrInfo)- info.setTexCoord(mrInfo.getTexCoord());- disposeIfOrphaned(occlusion);- packed += 1;- } catch {}- }- return packed;-}-function recolorForPalette(doc, material, slots, variantName) {- const clone = doc.createMaterial(`${material.getName()}__${variantName}`).copy(material);- if (material.getBaseColorTexture())- return { material: clone, changed: false };- const index = buildSlotIndex(slots);- const base = material.getBaseColorFactor();- const emissive = material.getEmissiveFactor();- const slot = chooseSlot(index, {- baseLinear: [base[0], base[1], base[2]],- emissiveLinear: [emissive[0], emissive[1], emissive[2]],- transparent: material.getAlphaMode() === "BLEND" || material.getAlpha() < 0.98- });- if (slot === undefined)- return { material: clone, changed: false };- const chosen = slots[slot];- if (!chosen)- return { material: clone, changed: false };- const [r, g, b] = hexToLinearRgb(chosen.color);- if (chosen.kind === "glow") {- clone.setEmissiveFactor([r, g, b]);- } else {- clone.setBaseColorFactor([r, g, b, base[3]]);- if (typeof chosen.roughness === "number")- clone.setRoughnessFactor(chosen.roughness);- if (typeof chosen.metalness === "number")- clone.setMetallicFactor(chosen.metalness);- if (chosen.kind === "glass" && typeof chosen.opacity === "number") {- clone.setBaseColorFactor([r, g, b, chosen.opacity]);- }- }- return { material: clone, changed: true };-}-function addPaletteVariants(doc, specs) {- const extension = doc.createExtension(KHRMaterialsVariants);- const names = [];- let materialsCreated = 0;- const variants = specs.map((spec) => {- names.push(spec.name);- return { spec, variant: extension.createVariant(spec.name) };- });- for (const mesh of doc.getRoot().listMeshes()) {- for (const primitive of mesh.listPrimitives()) {- const base = primitive.getMaterial();- if (!base)- continue;- const mappings = variants.map(({ spec, variant }) => {- const { material, changed } = recolorForPalette(doc, base, spec.slots, spec.name);- if (!changed) {- material.dispose();- return;- }- materialsCreated += 1;- return extension.createMapping().addVariant(variant).setMaterial(material);- }).filter((value) => value !== undefined);- if (mappings.length === 0)- continue;- const list = extension.createMappingList();- for (const mapping of mappings)- list.addMapping(mapping);- primitive.setExtension("KHR_materials_variants", list);- }- }- if (names.length === 0 || materialsCreated === 0)- extension.dispose();- return { names: materialsCreated > 0 ? names : [], materialsCreated };-}-async function encodeTexturesToKtx2(doc, encoder) {- const textures = doc.getRoot().listTextures().filter(isPng);- if (textures.length === 0)- return { encoded: 0, before: 0, after: 0 };- const dir = await mkdtemp(join(tmpdir(), "kiln-ktx2-"));- const staged = [];- let encoded = 0;- let before = 0;- let after = 0;- try {- for (const [index, texture] of textures.entries()) {- const bytes = texture.getImage();- if (!bytes)- continue;- const src = join(dir, `t${index}.png`);- const dst = join(dir, `t${index}.ktx2`);- await writeFile(src, bytes);- const srgb = doc.getRoot().listMaterials().some((material) => material.getBaseColorTexture() === texture || material.getEmissiveTexture() === texture);- await run(encoder, [- "create",- "--format",- srgb ? "R8G8B8A8_SRGB" : "R8G8B8A8_UNORM",- "--encode",- KTX_ENCODE_MODE,- "--generate-mipmap",- src,- dst- ], { timeout: 120000 });- const out = await readFile(dst);- before += bytes.byteLength;- after += out.byteLength;- staged.push({ texture, original: bytes, encodedBytes: new Uint8Array(out) });- }- } finally {- await rm(dir, { recursive: true, force: true });- }- if (staged.length === 0)- return { encoded: 0, before, after };- if (after >= before * KTX2_SIZE_ACCEPT_RATIO) {- return { encoded: 0, before, after };- }- for (const entry of staged) {- entry.texture.setImage(entry.encodedBytes).setMimeType("image/ktx2");- encoded += 1;- }- doc.createExtension(KHRTextureBasisu).setRequired(true);- return { encoded, before, after };-}-async function applyKitContract(doc, options = {}) {- const ormPacked = options.packOrm === false ? 0 : await packOcclusionIntoMetallicRoughness(doc);- const specs = options.variants ?? [];- const { names, materialsCreated } = specs.length ? addPaletteVariants(doc, specs) : { names: [], materialsCreated: 0 };- let ktx2 = {- applied: false,- skipped: "disabled by caller",- texturesEncoded: 0,- bytesBefore: 0,- bytesAfter: 0- };- if (options.ktx2 !== false) {- const encoder = await findKtxEncoder();- if (!encoder) {- ktx2 = {- applied: false,- skipped: "no KTX-Software encoder on PATH (set KILN_KTX_BIN to override)",- texturesEncoded: 0,- bytesBefore: 0,- bytesAfter: 0- };- } else {- try {- const result = await encodeTexturesToKtx2(doc, encoder);- ktx2 = {- applied: result.encoded > 0,- ...result.encoded > 0 ? {} : {- skipped: result.before === 0 ? "no PNG textures to encode" : `KTX2 was not smaller (${result.after} vs ${result.before} bytes); kept PNG`- },- encoder,- texturesEncoded: result.encoded,- bytesBefore: result.before,- bytesAfter: result.after- };- } catch (error) {- ktx2 = {- applied: false,- skipped: `encoder failed: ${error instanceof Error ? error.message : String(error)}`,- encoder,- texturesEncoded: 0,- bytesBefore: 0,- bytesAfter: 0- };- }- }- }- return { ormPacked, variantsAdded: names, variantMaterialsCreated: materialsCreated, ktx2 };-}-var run, KTX_ENCODER_CANDIDATES, KTX_ENCODE_MODE = "basis-lz", KTX2_SIZE_ACCEPT_RATIO = 0.9, cachedEncoder, isPng = (texture) => texture.getMimeType() === "image/png";+var run, KTX_ENCODER_CANDIDATES;var init_kit = __esm(() => {run = promisify(execFile);KTX_ENCODER_CANDIDATES = Object.freeze([@@ -20039,7 +19776,7 @@ async function bakeSceneTextures(root, warnings) {const materials = Array.isArray(material) ? material : material ? [material] : [];for (const item of materials) {const bag = item;- for (const [slot, usage2] of SLOT_USAGE2) {+ for (const [slot, usage] of SLOT_USAGE2) {const texture = bag[slot];if (!isTexture2(texture))continue;@@ -20050,7 +19787,7 @@ async function bakeSceneTextures(root, warnings) {node: node.name || "(unnamed node)",material: item.name || "(unnamed material)",slot,- usage: usage2+ usage});pending.set(texture, existing);}@@ -20078,8 +19815,8 @@ async function bakeSceneTextures(root, warnings) {bytes};const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";- const recipe2 = entry.texture.userData["kilnProcedural"];- const primaryUsage = recipe2?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");+ const recipe = entry.texture.userData["kilnProcedural"];+ const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");entry.texture.userData["kilnTexture"] = {usage: primaryUsage,colorSpace,@@ -20105,16 +19842,16 @@ async function bakeSceneTextures(root, warnings) {colorSpace,imageSha256,sha1,- ...recipe2 ? { procedural: recipe2 } : {}+ ...recipe ? { procedural: recipe } : {}});}return baked.sort((a, b) => `${a.node}:${a.material}:${a.texture}:${a.slot}`.localeCompare(`${b.node}:${b.material}:${b.texture}:${b.slot}`));}-function computeTangentBasis(geometry2) {- const index = geometry2.getIndex();- const position = geometry2.getAttribute("position");- const normal = geometry2.getAttribute("normal");- const uv = geometry2.getAttribute("uv");+function computeTangentBasis(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");+ const normal = geometry.getAttribute("normal");+ const uv = geometry.getAttribute("uv");if (!position || !normal || !uv) {throw new Error("position, normal, and uv are all required");}@@ -20181,7 +19918,7 @@ function computeTangentBasis(geometry2) {out[v * 4 + 2] = tmp.z;out[v * 4 + 3] = w;}- geometry2.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));+ geometry.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));}function ensureNormalMapTangents(root, warnings) {let count = 0;@@ -20194,19 +19931,19 @@ function ensureNormalMapTangents(root, warnings) {const needsTangents = materials.some((m) => m?.normalMap);if (!needsTangents)return;- const geometry2 = mesh.geometry;- if (!geometry2 || done.has(geometry2) || geometry2.getAttribute("tangent"))+ const geometry = mesh.geometry;+ if (!geometry || done.has(geometry) || geometry.getAttribute("tangent"))return;- done.add(geometry2);+ done.add(geometry);const name = mesh.name || "(unnamed mesh)";- if (!geometry2.getAttribute("uv")) {+ if (!geometry.getAttribute("uv")) {warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but has no UV coordinates, so tangents could not be computed — and the normal map cannot be sampled either. Unwrap it first: mesh.geometry = await autoUnwrap(mesh.geometry).`);return;}- if (!geometry2.getAttribute("normal"))- geometry2.computeVertexNormals();+ if (!geometry.getAttribute("normal"))+ geometry.computeVertexNormals();try {- computeTangentBasis(geometry2);+ computeTangentBasis(geometry);count++;} catch (err) {warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but tangents could not be computed (${err instanceof Error ? err.message : String(err)}). Each runtime will generate its own tangent basis.`);@@ -20235,10 +19972,10 @@ function rounded(value) {function tuple2(vector) {return [rounded(vector.x), rounded(vector.y), rounded(vector.z)];}-function chainIdFor(descriptor2, byRole) {- if (AXIAL_ROLES.has(descriptor2.role))+function chainIdFor(descriptor, byRole) {+ if (AXIAL_ROLES.has(descriptor.role))return "axial";- let current = descriptor2;+ let current = descriptor;const seen = new Set([current.role]);while (current.parentRole && !AXIAL_ROLES.has(current.parentRole)) {const parent = byRole.get(current.parentRole);@@ -20259,19 +19996,19 @@ function colorFor(value) {}function buildCharacterDiagnosticDescriptor(root, findings = []) {root.updateMatrixWorld(true);- const rootInverse2 = root.matrixWorld.clone().invert();- const evidence2 = collectCharacterJointNodes(root);- const descriptorByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint.descriptor]));- const evidenceByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint]));+ const rootInverse = root.matrixWorld.clone().invert();+ const evidence = collectCharacterJointNodes(root);+ const descriptorByRole = new Map(evidence.map((joint) => [joint.descriptor.role, joint.descriptor]));+ const evidenceByRole = new Map(evidence.map((joint) => [joint.descriptor.role, joint]));const invalidFindingNodePaths = [- ...new Set(findings.filter((finding6) => finding6.code === "CHAR_PARENT_EDGE").map((finding6) => finding6.affected?.nodePath).filter((path) => Boolean(path)))+ ...new Set(findings.filter((finding) => finding.code === "CHAR_PARENT_EDGE").map((finding) => finding.affected?.nodePath).filter((path) => Boolean(path)))].sort();const invalidPaths = new Set(invalidFindingNodePaths);- const joints = evidence2.map((joint) => {- const relative = rootInverse2.clone().multiply(joint.node.matrixWorld);+ const joints = evidence.map((joint) => {+ const relative = rootInverse.clone().multiply(joint.node.matrixWorld);const position = new THREE30.Vector3().setFromMatrixPosition(relative);const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);- const bend2 = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -20284,12 +20021,12 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {color: colorFor(chainId),assetPosition: tuple2(position),forwardAxisEnd: tuple2(forward),- bendAxisEnd: tuple2(bend2),+ bendAxisEnd: tuple2(bend),endEffector: joint.descriptor.endEffector,contact: joint.descriptor.contact};});- const edges = evidence2.filter((joint) => joint.descriptor.parentRole).map((joint) => {+ const edges = evidence.filter((joint) => joint.descriptor.parentRole).map((joint) => {const parentRole = joint.descriptor.parentRole;const parent = evidenceByRole.get(parentRole);const chainId = chainIdFor(joint.descriptor, descriptorByRole);@@ -20398,9 +20135,9 @@ function chunk(type, data) {out.writeUInt32BE(crc32(crcInput), 8 + data.length);return out;}-function encodePng(rgb2, width, height) {- if (rgb2.length !== width * height * 3) {- throw new Error(`encodePng: expected ${width * height * 3} bytes, got ${rgb2.length}`);+function encodePng(rgb, width, height) {+ if (rgb.length !== width * height * 3) {+ throw new Error(`encodePng: expected ${width * height * 3} bytes, got ${rgb.length}`);}const ihdr = Buffer.alloc(13);ihdr.writeUInt32BE(width, 0);@@ -20414,7 +20151,7 @@ function encodePng(rgb2, width, height) {for (let y = 0;y < height; y++) {const rowStart = y * (1 + width * 3);raw[rowStart] = 0;- raw.set(rgb2.subarray(y * width * 3, (y + 1) * width * 3), rowStart + 1);+ raw.set(rgb.subarray(y * width * 3, (y + 1) * width * 3), rowStart + 1);}return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),@@ -20469,7 +20206,7 @@ function decodePng(png) {if (raw.length !== height * (1 + stride)) {throw new Error(`decodePng: expected ${height * (1 + stride)} raw bytes, got ${raw.length}`);}- const rgb2 = new Uint8Array(width * height * 3);+ const rgb = new Uint8Array(width * height * 3);const cur = new Uint8Array(stride);const prior = new Uint8Array(stride);for (let y = 0;y < height; y++) {@@ -20503,13 +20240,13 @@ function decodePng(png) {for (let px = 0;px < width; px++) {const src = px * channels;const dst = (y * width + px) * 3;- rgb2[dst] = cur[src];- rgb2[dst + 1] = cur[src + 1];- rgb2[dst + 2] = cur[src + 2];+ rgb[dst] = cur[src];+ rgb[dst + 1] = cur[src + 1];+ rgb[dst + 2] = cur[src + 2];}prior.set(cur);}- return { rgb: rgb2, width, height };+ return { rgb, width, height };}var CRC_TABLE, PNG_SIGNATURE;var init_png = __esm(() => {@@ -20671,8 +20408,8 @@ function transformPoint2(matrix, x, y, z) {matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]];}-function matchesRole(roles2, prefixes) {- return Boolean(prefixes?.some((prefix) => roles2.some((role) => role.startsWith(prefix))));+function matchesRole(roles, prefixes) {+ return Boolean(prefixes?.some((prefix) => roles.some((role) => role.startsWith(prefix))));}function semanticRoles2(node) {const metadata = readSemanticMetadataV1FromExtras(node.userData ?? {});@@ -20695,9 +20432,9 @@ function collectScene(root, requestValue) {const world = multiplyMatrices(parentMatrix, local);const visible = ancestorVisible && node.visible !== false;const segment = `${node.name?.trim() || node.type || "Node"}[${siblingIndex}]`;- const nodePath5 = parentPath ? `${parentPath}/${segment}` : segment;- const roles2 = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];- const omitted = matchesRole(roles2, requestValue.omitRolePrefixes);+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ const roles = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];+ const omitted = matchesRole(roles, requestValue.omitRolePrefixes);if (visible && !omitted && node.isMesh && node.geometry) {const materials = Array.isArray(node.material) ? node.material : [node.material];const material = materials[0];@@ -20705,13 +20442,13 @@ function collectScene(root, requestValue) {const position = node.geometry.getAttribute?.("position");if (position?.itemSize === 3) {const worldPositions = [];- for (let index2 = 0;index2 < position.count; index2++) {- const point = transformPoint2(world, position.array[index2 * 3], position.array[index2 * 3 + 1], position.array[index2 * 3 + 2]);+ for (let index = 0;index < position.count; index++) {+ const point = transformPoint2(world, position.array[index * 3], position.array[index * 3 + 1], position.array[index * 3 + 2]);worldPositions.push(point);}const materialColor = material?.color;- const color2 = materialColor ? [clamp01(materialColor.r), clamp01(materialColor.g), clamp01(materialColor.b)] : [0.7, 0.7, 0.7];- const focused = matchesRole(roles2, requestValue.focusRolePrefixes);+ const color = materialColor ? [clamp01(materialColor.r), clamp01(materialColor.g), clamp01(materialColor.b)] : [0.7, 0.7, 0.7];+ const focused = matchesRole(roles, requestValue.focusRolePrefixes);const addTriangle = (a, b, c) => {const points = [worldPositions[a], worldPositions[b], worldPositions[c]];if (points.some((point) => !point || point.some((value) => !Number.isFinite(value)))) {@@ -20732,10 +20469,10 @@ function collectScene(root, requestValue) {});triangles.push({vertices,- color: color2,+ color,nodeName: node.name ?? "",- nodePath: nodePath5,- semanticRoles: roles2+ nodePath,+ semanticRoles: roles});};const index = node.geometry.index;@@ -20751,7 +20488,7 @@ function collectScene(root, requestValue) {}}(node.children ?? []).forEach((child, index) => {- visit(child, world, nodePath5, index, visible && !omitted, roles2);+ visit(child, world, nodePath, index, visible && !omitted, roles);});};visit(root, IDENTITY, "", 0, true, []);@@ -20764,8 +20501,8 @@ function collectScene(root, requestValue) {};}function normalize2(vector) {- const length3 = Math.hypot(...vector) || 1;- return [vector[0] / length3, vector[1] / length3, vector[2] / length3];+ const length = Math.hypot(...vector) || 1;+ return [vector[0] / length, vector[1] / length, vector[2] / length];}function cross2(a, b) {return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];@@ -20792,26 +20529,26 @@ function projectScene(scene, camera, size) {(frame.min[1] + frame.max[1]) / 2,(frame.min[2] + frame.max[2]) / 2];- let extent2 = 0.000001;+ let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {const point = [(corner & 1 ? frame.max[0] : frame.min[0]) - center[0],(corner & 2 ? frame.max[1] : frame.min[1]) - center[1],(corner & 4 ? frame.max[2] : frame.min[2]) - center[2]];- extent2 = Math.max(extent2, Math.abs(dot3(point, xAxis)), Math.abs(dot3(point, yAxis)));+ extent = Math.max(extent, Math.abs(dot3(point, xAxis)), Math.abs(dot3(point, yAxis)));}- const scale2 = size * 0.45 / extent2;+ const scale = size * 0.45 / extent;const half = size / 2;return scene.triangles.flatMap((triangle) => {const v = triangle.vertices;const edgeA = [v[3] - v[0], v[4] - v[1], v[5] - v[2]];const edgeB = [v[6] - v[0], v[7] - v[1], v[8] - v[2]];const normalRaw = cross2(edgeA, edgeB);- const length3 = Math.hypot(...normalRaw);- if (length3 < 0.000000000001)+ const length = Math.hypot(...normalRaw);+ if (length < 0.000000000001)return [];- const normal = normalRaw.map((component) => component / length3);+ const normal = normalRaw.map((component) => component / length);const xs = [];const ys = [];const zs = [];@@ -20822,8 +20559,8 @@ function projectScene(scene, camera, size) {v[index * 3 + 1] - center[1],v[index * 3 + 2] - center[2]];- xs.push(half + dot3(point, xAxis) * scale2);- ys.push(half - dot3(point, yAxis) * scale2);+ xs.push(half + dot3(point, xAxis) * scale);+ ys.push(half - dot3(point, yAxis) * scale);zs.push(dot3(point, zAxis));worldY.push(v[index * 3 + 1]);}@@ -20840,7 +20577,7 @@ function projectScene(scene, camera, size) {];});}-function drawLine(rgb2, size, from, to, color2) {+function drawLine(rgb, size, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);const x1 = Math.round(to[0]);@@ -20853,9 +20590,9 @@ function drawLine(rgb2, size, from, to, color2) {while (true) {if (x0 >= 0 && x0 < size && y0 >= 0 && y0 < size) {const offset = (y0 * size + x0) * 3;- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}if (x0 === x1 && y0 === y1)break;@@ -20870,12 +20607,12 @@ function drawLine(rgb2, size, from, to, color2) {}}}-function drawRegionBox(rgb2, size, region) {+function drawRegionBox(rgb, size, region) {const [minX, minY, maxX, maxY] = region.pixelBounds;- drawLine(rgb2, size, [minX, minY], [maxX, minY], region.color);- drawLine(rgb2, size, [maxX, minY], [maxX, maxY], region.color);- drawLine(rgb2, size, [maxX, maxY], [minX, maxY], region.color);- drawLine(rgb2, size, [minX, maxY], [minX, minY], region.color);+ drawLine(rgb, size, [minX, minY], [maxX, minY], region.color);+ drawLine(rgb, size, [maxX, minY], [maxX, maxY], region.color);+ drawLine(rgb, size, [maxX, maxY], [minX, maxY], region.color);+ drawLine(rgb, size, [minX, maxY], [minX, minY], region.color);}function renderDiagnosticView(root, requestValue, options = {}) {const camera = cameraById.get(requestValue.cameraId);@@ -20886,11 +20623,11 @@ function renderDiagnosticView(root, requestValue, options = {}) {const scene = collectScene(root, requestValue);const triangles = projectScene(scene, camera, size);const background = [18, 20, 24];- const rgb2 = new Uint8Array(size * size * 3);+ const rgb = new Uint8Array(size * size * 3);for (let pixel = 0;pixel < size * size; pixel++) {- rgb2[pixel * 3] = background[0];- rgb2[pixel * 3 + 1] = background[1];- rgb2[pixel * 3 + 2] = background[2];+ rgb[pixel * 3] = background[0];+ rgb[pixel * 3 + 1] = background[1];+ rgb[pixel * 3 + 2] = background[2];}const depth = new Float64Array(size * size).fill(-Infinity);const depths = triangles.flatMap((triangle) => triangle.z);@@ -20952,50 +20689,50 @@ function renderDiagnosticView(root, requestValue, options = {}) {continue;depth[pixel] = pixelDepth;const offset = pixel * 3;- let color2;+ let color;if (requestValue.variant === "material-grazing-light") {const grazingDirection = normalize2([0.25, 0.08, 1]);const light = 0.08 + 0.92 * Math.max(0, dot3(triangle.normal, grazingDirection));- color2 = triangle.source.color.map((value) => Math.round(clamp01(value * light) * 255));+ color = triangle.source.color.map((value) => Math.round(clamp01(value * light) * 255));} else if (requestValue.buffer === "silhouette-unlit") {- color2 = [235, 238, 242];+ color = [235, 238, 242];} else if (requestValue.buffer === "normals-backface") {- color2 = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];+ color = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];} else if (requestValue.buffer === "depth-contact") {const worldY = w1 * triangle.worldY[0] + w2 * triangle.worldY[1] + w0 * triangle.worldY[2];if (Math.abs(worldY - groundY) <= contactTolerance)- color2 = [58, 220, 126];+ color = [58, 220, 126];else if (worldY < groundY - contactTolerance)- color2 = [245, 94, 72];+ color = [245, 94, 72];else {const value = Math.round(48 + 190 * ((pixelDepth - minDepth) / depthRange));- color2 = [value, value, value];+ color = [value, value, value];}} else {- color2 = regionColor;+ color = regionColor;}- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}}}if (requestValue.buffer === "wireframe") {for (const triangle of triangles) {- const color2 = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];+ const color = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];for (const [a, b] of [[0, 1],[1, 2],[2, 0]]) {- drawLine(rgb2, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color2);+ drawLine(rgb, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color);}}}const regions = [...regionMap.values()].sort((a, b) => a.nodePath.localeCompare(b.nodePath));if (requestValue.buffer === "semantic-overlay") {for (const region of regions)- drawRegionBox(rgb2, size, region);+ drawRegionBox(rgb, size, region);}return {id: requestValue.id,@@ -21005,15 +20742,12 @@ function renderDiagnosticView(root, requestValue, options = {}) {...requestValue.variant ? { variant: requestValue.variant } : {},width: size,height: size,- rgb: rgb2,- png: encodePng(rgb2, size, size),+ rgb,+ png: encodePng(rgb, size, size),regions,...requestValue.phaseFractions ? { phaseFractions: requestValue.phaseFractions } : {}};}-function renderDiagnosticViews(root, requests, options = {}) {- return requests.map((viewRequest) => renderDiagnosticView(root, viewRequest, options));-}var GENERIC_DIAGNOSTIC_BUFFER_IDS, frozenCamera = (id, name, dir) => Object.freeze({ id, name, dir: Object.freeze([...dir]) }), GENERIC_DIAGNOSTIC_CAMERAS, EXTRA_CAMERAS, cameraById, request = (value) => Object.freeze({...value,...value.omitRolePrefixes ? { omitRolePrefixes: Object.freeze([...value.omitRolePrefixes]) } : {},@@ -21133,22 +20867,22 @@ function prepareClip(root, clip) {const raw = track.name;if (!raw)continue;- const dot4 = raw.lastIndexOf(".");- if (dot4 === -1)+ const dot = raw.lastIndexOf(".");+ if (dot === -1)continue;- const nodeName2 = raw.slice(0, dot4);- const property = raw.slice(dot4 + 1);+ const nodeName = raw.slice(0, dot);+ const property = raw.slice(dot + 1);if (property !== "position" && property !== "quaternion" && property !== "scale")continue;const times = track.times ? Array.from(track.times) : [];const values = track.values ? Array.from(track.values) : [];if (times.length === 0 || values.length === 0)continue;- if (!nodeNames.has(nodeName2))+ if (!nodeNames.has(nodeName))unresolved.push(raw);if (times[times.length - 1] > maxTime)maxTime = times[times.length - 1];- tracks.push({ nodeName: nodeName2, prop: property, stride: PROP_STRIDE[property], times, values });+ tracks.push({ nodeName, prop: property, stride: PROP_STRIDE[property], times, values });}const duration = clip.duration && clip.duration > 0 ? clip.duration : maxTime;return { name: clip.name ?? "(unnamed)", duration, tracks, unresolved };@@ -21256,11 +20990,11 @@ function planFrameTimes(duration, count) {out.push(duration * i / (count - 1));return out;}-function stampLabel(rgb2, width, height, x0, y0, text, scale2 = 3) {- const gw = 3 * scale2;- const gh = 5 * scale2;- const gap = scale2;- const pad = scale2;+function stampLabel(rgb, width, height, x0, y0, text, scale = 3) {+ const gw = 3 * scale;+ const gh = 5 * scale;+ const gap = scale;+ const pad = scale;const totalW = text.length * gw + (text.length - 1) * gap + pad * 2;const totalH = gh + pad * 2;for (let y = y0;y < y0 + totalH; y++) {@@ -21268,9 +21002,9 @@ function stampLabel(rgb2, width, height, x0, y0, text, scale2 = 3) {if (x < 0 || y < 0 || x >= width || y >= height)continue;const p = (y * width + x) * 3;- rgb2[p] = LABEL_BG[0];- rgb2[p + 1] = LABEL_BG[1];- rgb2[p + 2] = LABEL_BG[2];+ rgb[p] = LABEL_BG[0];+ rgb[p + 1] = LABEL_BG[1];+ rgb[p + 2] = LABEL_BG[2];}}let cx = x0 + pad;@@ -21282,16 +21016,16 @@ function stampLabel(rgb2, width, height, x0, y0, text, scale2 = 3) {for (let col = 0;col < 3; col++) {if (!(bits & 1 << 2 - col))continue;- for (let sy = 0;sy < scale2; sy++) {- for (let sx = 0;sx < scale2; sx++) {- const x = cx + col * scale2 + sx;- const y = cy + row * scale2 + sy;+ for (let sy = 0;sy < scale; sy++) {+ for (let sx = 0;sx < scale; sx++) {+ const x = cx + col * scale + sx;+ const y = cy + row * scale + sy;if (x < 0 || y < 0 || x >= width || y >= height)continue;const p = (y * width + x) * 3;- rgb2[p] = LABEL_FG[0];- rgb2[p + 1] = LABEL_FG[1];- rgb2[p + 2] = LABEL_FG[2];+ rgb[p] = LABEL_FG[0];+ rgb[p + 1] = LABEL_FG[1];+ rgb[p + 2] = LABEL_FG[2];}}}@@ -21351,7 +21085,7 @@ var init_pose = __esm(() => {});// src/views/annotate.ts-function stampAxisGnomon(rgb2, size, viewDir) {+function stampAxisGnomon(rgb, size, viewDir) {const zl = Math.hypot(viewDir[0], viewDir[1], viewDir[2]) || 1;const z = [viewDir[0] / zl, viewDir[1] / zl, viewDir[2] / zl];const up = Math.abs(z[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];@@ -21370,7 +21104,7 @@ function stampAxisGnomon(rgb2, size, viewDir) {const len = Math.max(12, Math.round(size * 0.055));const ox = len + 10;const oy = size - len - 10;- for (const { label, axis, color: color2 } of GNOMON_AXES) {+ for (const { label, axis, color } of GNOMON_AXES) {const dx = axis[0] * bx[0] + axis[1] * bx[1] + axis[2] * bx[2];const dy = axis[0] * by[0] + axis[1] * by[1] + axis[2] * by[2];if (Math.hypot(dx, dy) < 0.25)@@ -21388,25 +21122,25 @@ function stampAxisGnomon(rgb2, size, viewDir) {if (x < 0 || y < 0 || x >= size || y >= size)continue;const p = (y * size + x) * 3;- rgb2[p] = color2[0];- rgb2[p + 1] = color2[1];- rgb2[p + 2] = color2[2];+ rgb[p] = color[0];+ rgb[p + 1] = color[1];+ rgb[p + 2] = color[2];}}}- stampLabel(rgb2, size, size, Math.round(ex) + 2, Math.round(ey) - 6, label, 1);+ stampLabel(rgb, size, size, Math.round(ex) + 2, Math.round(ey) - 6, label, 1);}}-function annotateViewCell(rgb2, size, view) {+function annotateViewCell(rgb, size, view) {const inset = Math.max(2, Math.round(size / 96));const width = size - inset * 2;if (width < 7 || (4 * view.name.length + 1) * inset <= width) {- stampLabel(rgb2, size, size, inset, inset, view.name, inset);+ stampLabel(rgb, size, size, inset, inset, view.name, inset);} else {const minimumScale = size >= 128 ? 2 : 1;- const scale2 = Math.max(minimumScale, Math.floor(width / (4 * view.name.length + 1)));- const columns = Math.max(1, Math.floor((width / scale2 - 1) / 4));- const rows = Math.min(3, Math.floor((size - inset * 2) / (7 * scale2)));+ const scale = Math.max(minimumScale, Math.floor(width / (4 * view.name.length + 1)));+ const columns = Math.max(1, Math.floor((width / scale - 1) / 4));+ const rows = Math.min(3, Math.floor((size - inset * 2) / (7 * scale)));let remaining = view.name.toUpperCase();for (let row = 0;row < rows && remaining; row++) {let line = remaining;@@ -21422,10 +21156,10 @@ function annotateViewCell(rgb2, size, view) {}} elseremaining = "";- stampLabel(rgb2, size, size, inset, inset + row * 7 * scale2, line, scale2);+ stampLabel(rgb, size, size, inset, inset + row * 7 * scale, line, scale);}}- stampAxisGnomon(rgb2, size, view.dir);+ stampAxisGnomon(rgb, size, view.dir);}var GNOMON_AXES;var init_annotate = __esm(() => {@@ -21484,8 +21218,8 @@ function compositeViewPngGrid(pngs, cols = GRID_COLS, views) {for (let i = 0;i < decoded.length; i++)annotateViewCell(decoded[i].rgb, size, views[i]);}- const { rgb: rgb2, width, height } = compositeCellGrid(decoded.map((d) => d.rgb), size, cols);- return { png: encodePng(rgb2, width, height), width, height, cellSize: size };+ const { rgb, width, height } = compositeCellGrid(decoded.map((d) => d.rgb), size, cols);+ return { png: encodePng(rgb, width, height), width, height, cellSize: size };}var PAD = 4, PAD_COLOR, GRID_COLS = 3;var init_grid = __esm(() => {@@ -21495,14 +21229,6 @@ var init_grid = __esm(() => {});// src/views/capture-limits.ts-var exports_capture_limits = {};-__export(exports_capture_limits, {- resolveCaptureLimits: () => resolveCaptureLimits,- enforcePngCaptureBudget: () => enforcePngCaptureBudget,- enforceCapturePixels: () => enforceCapturePixels,- enforceCaptureBytes: () => enforceCaptureBytes,- DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS-});function resolveCaptureLimits(limits = {}) {const result = { ...DEFAULT_CAPTURE_LIMITS };for (const key of ["maxTotalPixels", "maxOutputBytes"]) {@@ -21553,7 +21279,7 @@ var init_capture_limits = __esm(() => {});// src/views/background.ts-var GRID_BACKGROUND_RGB, GRID_BACKGROUND_HEX = "#1a1a1a";+var GRID_BACKGROUND_RGB;var init_background = __esm(() => {GRID_BACKGROUND_RGB = [26, 26, 26];});@@ -21716,7 +21442,7 @@ function rasterizeView(root, dir, opts = {}) {const p = [px, py, pz];ext = Math.max(ext, Math.abs(dot4(p, x)), Math.abs(dot4(p, y)));}- const scale2 = size * 0.45 / ext;+ const scale = size * 0.45 / ext;const half = size / 2;const zbuf = new Float64Array(size * size).fill(-Infinity);const sx = new Float64Array(3);@@ -21740,8 +21466,8 @@ function rasterizeView(root, dir, opts = {}) {const py = tri.v[i * 3 + 1] - center[1];const pz = tri.v[i * 3 + 2] - center[2];const p = [px, py, pz];- sx[i] = half + dot4(p, x) * scale2;- sy[i] = half - dot4(p, y) * scale2;+ sx[i] = half + dot4(p, x) * scale;+ sy[i] = half - dot4(p, y) * scale;sz[i] = dot4(p, z);}const lambert = Math.max(0, dot4(N, KEY_DIR));@@ -21793,14 +21519,6 @@ function measureBounds(root) {const { bbox } = collectTriangles(root);return { min: [...bbox.min], max: [...bbox.max] };}-function coverage(rgb2, size) {- let filled = 0;- for (let i = 0;i < size * size; i++) {- if (rgb2[i * 3] !== BG[0] || rgb2[i * 3 + 1] !== BG[1] || rgb2[i * 3 + 2] !== BG[2])- filled++;- }- return filled / (size * size);-}function hideNodeInScene(root, match) {const test = typeof match === "function" ? match : (name) => {const t = match.toLowerCase();@@ -21858,10 +21576,10 @@ function triple(v, label) {}function listCameraSubjects(root) {const result = [];- const visit = (node2, path) => {- result.push({ node: node2, path, name: node2.name });+ const visit = (node, path) => {+ result.push({ node, path, name: node.name });const counts = new Map;- for (const child of node2.children ?? []) {+ for (const child of node.children ?? []) {const count = counts.get(child.name) ?? 0;counts.set(child.name, count + 1);visit(child, `${path}/${encodeURIComponent(child.name)}[${count}]`);@@ -21895,10 +21613,10 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {if (x.length() < 0.000000001)throw new Error("camera up must not be collinear with view");const y = z.clone().cross(x);- let extent2 = 0.000001;+ let extent = 0.000001;for (let i = 0;i < 8; i++) {const p = new Vector325((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);- extent2 = Math.max(extent2, Math.abs(p.dot(x)), Math.abs(p.dot(y)));+ extent = Math.max(extent, Math.abs(p.dot(x)), Math.abs(p.dot(y)));}const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));const depthMax = bounds.max.map((v, i) => Math.max(v, sceneBounds.max[i]));@@ -21913,7 +21631,7 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {aspect: 1,near: Math.max(0.000001, distance - radius),far: distance + radius + 1,- halfHeight: extent2 * padding / 0.9+ halfHeight: extent * padding / 0.9};}function validateResolvedAssetCamera(value) {@@ -21963,23 +21681,23 @@ function resolveAssetCamera(root, shot = {}) {const bounds = measureBounds(selected.node);if (!collectTriangles(selected.node).tris.length)throw new Error(`subject ${selected.path} has no visible geometry`);- const request2 = shot.camera ?? { type: "orbit" };+ const request = shot.camera ?? { type: "orbit" };let camera;- if (request2.type === "orbit") {- strict(request2, ["type", "azimuthDeg", "elevationDeg", "relativeTo", "padding"], "camera");- const relative = request2.relativeTo ?? "world";+ if (request.type === "orbit") {+ strict(request, ["type", "azimuthDeg", "elevationDeg", "relativeTo", "padding"], "camera");+ const relative = request.relativeTo ?? "world";if (!["world", "asset", "part"].includes(relative))throw new Error("invalid relativeTo");- const dir = vec(orbitDir(finite2(request2.azimuthDeg ?? 45, "azimuthDeg"), finite2(request2.elevationDeg ?? 25, "elevationDeg")));+ const dir = vec(orbitDir(finite2(request.azimuthDeg ?? 45, "azimuthDeg"), finite2(request.elevationDeg ?? 25, "elevationDeg")));let up;if (relative !== "world") {const node = relative === "part" ? selected.node : rootNode;dir.transformDirection(node.matrixWorld);up = tuple5(new Vector325(0, 1, 0).transformDirection(node.matrixWorld));}- camera = cameraFromBounds(bounds, tuple5(dir), request2.padding ?? 1.2, up, measureBounds(root));- } else if (request2.type === "explicit") {- strict(request2, [+ camera = cameraFromBounds(bounds, tuple5(dir), request.padding ?? 1.2, up, measureBounds(root));+ } else if (request.type === "explicit") {+ strict(request, ["type","projection","position",@@ -21995,56 +21713,56 @@ function resolveAssetCamera(root, shot = {}) {"padding","targetOffset"], "camera");- if (request2.projection === "orthographic" && request2.fovDeg !== undefined || request2.projection === "perspective" && request2.halfHeight !== undefined)+ if (request.projection === "orthographic" && request.fovDeg !== undefined || request.projection === "perspective" && request.halfHeight !== undefined)throw new Error("projection and lens fields conflict");- const relative = request2.relativeTo ?? "world";+ const relative = request.relativeTo ?? "world";if (!["world", "asset", "part", "local"].includes(relative))throw new Error("invalid relativeTo");- if (relative === "local" !== Boolean(request2.frame))+ if (relative === "local" !== Boolean(request.frame))throw new Error("local coordinates require frame; frame is only valid for local coordinates");- if (request2.framing !== undefined && !["explicit", "bounds"].includes(request2.framing))+ if (request.framing !== undefined && !["explicit", "bounds"].includes(request.framing))throw new Error("invalid framing");- if (request2.target === undefined && request2.framing !== "bounds")+ if (request.target === undefined && request.framing !== "bounds")throw new Error("explicit framing requires target");- if (request2.padding !== undefined && request2.framing !== "bounds")+ if (request.padding !== undefined && request.framing !== "bounds")throw new Error("padding requires bounds framing");- if (request2.framing === "bounds" && request2.halfHeight !== undefined)+ if (request.framing === "bounds" && request.halfHeight !== undefined)throw new Error("bounds framing derives halfHeight");let matrix = new Matrix46;if (relative === "asset" || relative === "part")matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;- if (request2.frame) {- strict(request2.frame, ["origin", "rotation"], "frame");- const rotation = triple(request2.frame.rotation ?? [0, 0, 0], "frame.rotation");+ if (request.frame) {+ strict(request.frame, ["origin", "rotation"], "frame");+ const rotation = triple(request.frame.rotation ?? [0, 0, 0], "frame.rotation");matrix.makeRotationFromEuler(new Euler4(...rotation.map((n) => n * Math.PI / 180), "XYZ"));- matrix.setPosition(...triple(request2.frame.origin ?? [0, 0, 0], "frame.origin"));+ matrix.setPosition(...triple(request.frame.origin ?? [0, 0, 0], "frame.origin"));}- const position = vec(triple(request2.position, "position")).applyMatrix4(matrix);- const target = request2.target ? vec(triple(request2.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);- const up = vec(triple(request2.up ?? [0, 1, 0], "up")).transformDirection(matrix);- const offset = vec(triple(request2.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector325().setFromMatrixPosition(matrix));+ const position = vec(triple(request.position, "position")).applyMatrix4(matrix);+ const target = request.target ? vec(triple(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);+ const up = vec(triple(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);+ const offset = vec(triple(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector325().setFromMatrixPosition(matrix));const radius = vec(bounds.max).sub(vec(bounds.min)).length();camera = {version: "kiln.camera.v1",- projection: request2.projection,+ projection: request.projection,position: tuple5(position),target: tuple5(target.clone().add(offset)),up: tuple5(up),aspect: 1,- near: request2.near ?? 0.001,- far: request2.far ?? Math.max(100, position.distanceTo(target) + radius * 4),- ...request2.projection === "orthographic" ? { halfHeight: request2.halfHeight ?? Math.max(radius / 2, 0.000001) } : { fovDeg: request2.fovDeg ?? 50 }+ near: request.near ?? 0.001,+ far: request.far ?? Math.max(100, position.distanceTo(target) + radius * 4),+ ...request.projection === "orthographic" ? { halfHeight: request.halfHeight ?? Math.max(radius / 2, 0.000001) } : { fovDeg: request.fovDeg ?? 50 }};- if (request2.framing === "bounds") {+ if (request.framing === "bounds") {const direction = position.clone().sub(target);if (direction.lengthSq() < 0.00000000000000000001)throw new Error("bounds framing position and target must differ");- const padding = request2.padding ?? 1.2;+ const padding = request.padding ?? 1.2;const fit = cameraFromBounds(bounds, tuple5(direction), padding, tuple5(up), measureBounds(root));- if (request2.projection === "orthographic")- camera = { ...fit, near: request2.near ?? fit.near, far: request2.far ?? fit.far };+ if (request.projection === "orthographic")+ camera = { ...fit, near: request.near ?? fit.near, far: request.far ?? fit.far };else {- const fov = finite2(request2.fovDeg ?? 50, "fovDeg");+ const fov = finite2(request.fovDeg ?? 50, "fovDeg");if (fov <= 0 || fov >= 180)throw new Error("invalid fovDeg");const distance = Math.max(radius / 2, 0.000001) * padding / Math.sin(fov * Math.PI / 360);@@ -22053,7 +21771,7 @@ function resolveAssetCamera(root, shot = {}) {...camera,position: tuple5(center.clone().add(direction.normalize().multiplyScalar(distance))),target: tuple5(center),- far: request2.far ?? Math.max(100, distance + radius * 4)+ far: request.far ?? Math.max(100, distance + radius * 4)};}camera.position = tuple5(vec(camera.position).add(offset));@@ -22070,9 +21788,9 @@ function resolveAssetCamera(root, shot = {}) {visibility: shot.visibility ?? "context"};}-async function withCameraVisibility(root, shot, run2) {+async function withCameraVisibility(root, shot, run) {if (shot.visibility === "context")- return run2();+ return run();const keep = new Set;selectCameraSubject(root, { path: shot.subject.path }).node.traverse((n) => keep.add(n));const restore = [];@@ -22083,7 +21801,7 @@ async function withCameraVisibility(root, shot, run2) {}});try {- return await run2();+ return await run();} finally {for (const [node, visible] of restore)node.visible = visible;@@ -22120,7 +21838,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true) {if (tri.alpha <= 0)continue;const light = Math.min(1, 0.25 + 1.1 * Math.max(0, normal.dot(key)));- const color2 = tri.color.map((c) => Math.round(srgb(c * light) * 255));+ const color = tri.color.map((c) => Math.round(srgb(c * light) * 255));let polygon = world.map((p) => {const d = p.clone().sub(position);return new Vector325(d.dot(x), d.dot(y), -d.dot(z));@@ -22150,7 +21868,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true) {continue;depth[index] = d;for (let channel = 0;channel < 3; channel++)- out[index * 3 + channel] = Math.round(color2[channel] * tri.alpha + out[index * 3 + channel] * (1 - tri.alpha));+ out[index * 3 + channel] = Math.round(color[channel] * tri.alpha + out[index * 3 + channel] * (1 - tri.alpha));}}}@@ -22256,12 +21974,12 @@ function validatePbrRenderRequest(input) {target[1] - position[1],target[2] - position[2]];- const cross4 = [+ const cross = [view[1] * up[2] - view[2] * up[1],view[2] * up[0] - view[0] * up[2],view[0] * up[1] - view[1] * up[0]];- if (Math.hypot(...cross4) <= Math.hypot(...view) * Math.hypot(...up) * 0.000000001) {+ if (Math.hypot(...cross) <= Math.hypot(...view) * Math.hypot(...up) * 0.000000001) {throw new TypeError(`PbrRenderRequest.cameras[${index}].up must not be collinear with view`);}const number = (key) => {@@ -22320,9 +22038,9 @@ var init_render_port = __esm(() => {// src/views/capture-cache.tsvar exports_capture_cache = {};__export(exports_capture_cache, {- createCachedRenderPort: () => createCachedRenderPort,+ MemoryCaptureCache: () => MemoryCaptureCache,captureCpuCell: () => captureCpuCell,- MemoryCaptureCache: () => MemoryCaptureCache+ createCachedRenderPort: () => createCachedRenderPort});import { createHash as createHash4 } from "node:crypto";function clone(entry) {@@ -22391,19 +22109,19 @@ function canonical(value) {return value;throw new Error("Capture identity must be data");}-function usable(result, request2, hash) {+function usable(result, request, hash) {try {if (!result.ok || !result.rendererId?.trim() || result.derivativeFidelity?.materialFaithful !== true || result.derivativeFidelity.inputGlbSha256 !== hash)return false;- const count = (request2.cameras ?? request2.viewDirs).length;+ const count = (request.cameras ?? request.viewDirs).length;if (result.viewsPng?.length !== count)return false;- if (request2.cameras && (result.width !== request2.width || result.height !== request2.height || text(result.cameras) !== text(request2.cameras)))+ if (request.cameras && (result.width !== request.width || result.height !== request.height || text(result.cameras) !== text(request.cameras)))return false;enforcePngCaptureBudget(result.viewsPng);for (const png of result.viewsPng) {const image = decodePng(png);- if (image.width !== image.height || request2.cameras && (image.width !== request2.width || image.height !== request2.height))+ if (image.width !== image.height || request.cameras && (image.width !== request.width || image.height !== request.height))return false;}return true;@@ -22419,19 +22137,19 @@ function createCachedRenderPort(port, options) {if (!identity || input.beautySize !== undefined || !(input.cameras ?? input.viewDirs)?.length)return port(input);const validated = validatePbrRenderRequest(input);- const request2 = { ...validated, glb: Uint8Array.from(validated.glb) };- const hash = digest(request2.glb);- const selectors = request2.cameras ?? request2.viewDirs;+ const request = { ...validated, glb: Uint8Array.from(validated.glb) };+ const hash = digest(request.glb);+ const selectors = request.cameras ?? request.viewDirs;const keys = selectors.map((selector) => digest(text({version: "kiln.capture-cache.v1",kind: "gpu",identity,artifact: hash,selector,- size: request2.size,- width: request2.width,- height: request2.height,- lighting: request2.lightingPresetId+ size: request.size,+ width: request.width,+ height: request.height,+ lighting: request.lightingPresetId})));const cells = [];const missing = [];@@ -22440,8 +22158,8 @@ function createCachedRenderPort(port, options) {return;});const single = {- ...request2,- ...request2.cameras ? { cameras: [request2.cameras[i]] } : { viewDirs: [request2.viewDirs[i]] }+ ...request,+ ...request.cameras ? { cameras: [request.cameras[i]] } : { viewDirs: [request.viewDirs[i]] }};if (cached?.kind === "gpu" && usable(cached.result, single, hash))cells[i] = cached.result;@@ -22450,8 +22168,8 @@ function createCachedRenderPort(port, options) {}if (missing.length) {const subrequest = {- ...request2,- ...request2.cameras ? { cameras: missing.map((i) => request2.cameras[i]) } : { viewDirs: missing.map((i) => request2.viewDirs[i]) }+ ...request,+ ...request.cameras ? { cameras: missing.map((i) => request.cameras[i]) } : { viewDirs: missing.map((i) => request.viewDirs[i]) }};const produced = await port(subrequest);const afterIdentity = await Promise.resolve().then(() => options.identity()).catch(() => {@@ -22491,7 +22209,7 @@ function createCachedRenderPort(port, options) {return {...first,viewsPng: cells.map((c) => Uint8Array.from(c.viewsPng[0])),- ...request2.cameras ? { cameras: structuredClone(request2.cameras) } : {},+ ...request.cameras ? { cameras: structuredClone(request.cameras) } : {},captureCache: {hit: missing.length === 0,reused: selectors.length - missing.length,@@ -22503,11 +22221,11 @@ function createCachedRenderPort(port, options) {async function captureCpuCell(cache, identity, produce) {const snapshot = structuredClone(identity);const key = digest(text({ version: "kiln.capture-cache.v1", kind: "cpu", ...snapshot }));- const valid = (result2) => {+ const valid = (result) => {try {- enforcePngCaptureBudget([result2.png]);- const image = decodePng(result2.png);- return result2.inputGlbSha256 === snapshot.artifactGlbSha256 && image.width === snapshot.size && image.height === snapshot.size && result2.width === snapshot.size && result2.height === snapshot.size;+ enforcePngCaptureBudget([result.png]);+ const image = decodePng(result.png);+ return result.inputGlbSha256 === snapshot.artifactGlbSha256 && image.width === snapshot.size && image.height === snapshot.size && result.width === snapshot.size && result.height === snapshot.size;} catch {return false;}@@ -22531,11 +22249,6 @@ var init_capture_cache = __esm(() => {});// src/views/camera-capture.ts-var exports_camera_capture = {};-__export(exports_camera_capture, {- validateAdvancedCapture: () => validateAdvancedCapture,- renderCaptureGrid: () => renderCaptureGrid-});function validateAdvancedCapture(config) {for (const key of Object.keys(config))if (!["version", "shots", "cols", "size", "output"].includes(key))@@ -22563,7 +22276,7 @@ async function renderCaptureGrid(root, config, render, limits) {for (const shot of shots) {const dir = shot.camera.position.map((n, i) => n - shot.camera.target[i]);const view = { name: shot.name, dir };- const png2 = await withCameraVisibility(root, shot, async () => {+ const png = await withCameraVisibility(root, shot, async () => {if (render) {const result = await render({ root, label: shot.name, view, size, camera: shot.camera });derivativeReceipts.push(result.receipt);@@ -22571,15 +22284,15 @@ async function renderCaptureGrid(root, config, render, limits) {}return encodePng(rasterizeCamera(root, shot.camera, size), size, size);});- const decoded = decodePng(png2);+ const decoded = decodePng(png);if (decoded.width !== size || decoded.height !== size)throw new Error("capture cell dimensions do not match request");annotateViewCell(decoded.rgb, size, view);cells.push(decoded.rgb);perFramePngs.push(encodePng(decoded.rgb, size, size));}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);- const png = encodePng(rgb2, width, height);+ const { rgb, width, height } = compositeCellGrid(cells, size, cols);+ const png = encodePng(rgb, width, height);enforceCaptureBytes(config.output === "separate" ? perFramePngs : [png], limits);return {png,@@ -22608,17 +22321,6 @@ var init_camera_capture = __esm(() => {});// src/views/capture.ts-var exports_capture = {};-__export(exports_capture, {- resolveGridCapture: () => resolveGridCapture,- resolveCapture: () => resolveCapture,- describeCapture: () => describeCapture,- captureCellLabel: () => captureCellLabel,- MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,- DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,- CaptureConfigError: () => CaptureConfigError,- CAPTURE_PRESETS: () => CAPTURE_PRESETS-});function captureCellLabel(azimuthDeg, elevationDeg) {const az = Math.round((azimuthDeg % 360 + 360) % 360);const el = Math.round(elevationDeg);@@ -22681,18 +22383,11 @@ function resolveCapture(config) {};}function resolveGridCapture(config, envVariant) {- const resolved2 = resolveCapture(config);+ const resolved = resolveCapture(config);if (config)- return resolved2;+ return resolved;const views = resolveGridViews(envVariant);- return views === resolved2.views ? resolved2 : { ...resolved2, views };-}-function describeCapture(resolved2) {- const angles = resolved2.views.map((v) => {- const { azimuthDeg, elevationDeg } = orbitAnglesOf(v.dir);- return `${v.name} (az ${azimuthDeg}, el ${elevationDeg})`;- }).join("; ");- return `${resolved2.preset} grid, ${resolved2.views.length} cell${resolved2.views.length === 1 ? "" : "s"}: ${angles}`;+ return views === resolved.views ? resolved : { ...resolved, views };}var CAPTURE_PRESETS, DEFAULT_CAPTURE_PRESET = "3x2", MAX_CAPTURE_CELLS = 9, PRESET_COLS, PRESET_CAPACITY, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW, PRESET_VIEWS, CaptureConfigError;var init_capture = __esm(() => {@@ -22766,9 +22461,9 @@ function minimalMatches(root, predicate) {}function selectArchitectureRoofNodes(root) {const candidate = root;- const semantic3 = minimalMatches(candidate, hasArchitectureRoofRole);- if (semantic3.length > 0)- return { mode: "semantic", nodes: semantic3 };+ const semantic = minimalMatches(candidate, hasArchitectureRoofRole);+ if (semantic.length > 0)+ return { mode: "semantic", nodes: semantic };const legacy = minimalMatches(candidate, (node) => legacyRoofName(node.name));return legacy.length > 0 ? { mode: "legacy-name", nodes: legacy } : { mode: "none", nodes: [] };}@@ -22901,20 +22596,20 @@ function flatMaterial(material) {};}const [r, g, b, factorAlpha] = material.getBaseColorFactor();- const alphaMode2 = material.getAlphaMode();- const opacity = alphaMode2 === "BLEND" ? factorAlpha : alphaMode2 === "MASK" && factorAlpha < material.getAlphaCutoff() ? 0 : 1;+ const alphaMode = material.getAlphaMode();+ const opacity = alphaMode === "BLEND" ? factorAlpha : alphaMode === "MASK" && factorAlpha < material.getAlphaCutoff() ? 0 : 1;return {color: { r, g, b },opacity,doubleSided: material.getDoubleSided(),metalness: material.getMetallicFactor(),roughness: material.getRoughnessFactor(),- alphaMode: alphaMode2,+ alphaMode,alphaCutoff: material.getAlphaCutoff(),emissive: material.getEmissiveFactor()};}-function preserveTexture(source, usage2, cache) {+function preserveTexture(source, usage, cache) {if (!source)return null;const encoded = source.getImage();@@ -22926,14 +22621,14 @@ function preserveTexture(source, usage2, cache) {byUsage = new Map;cache.set(source, byUsage);}- const existing = byUsage.get(usage2);+ const existing = byUsage.get(usage);if (existing)return existing;const texture = new Texture;texture.name = source.getName();- texture.colorSpace = usage2 === "color" ? SRGBColorSpace5 : NoColorSpace4;+ texture.colorSpace = usage === "color" ? SRGBColorSpace5 : NoColorSpace4;texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };- byUsage.set(usage2, texture);+ byUsage.set(usage, texture);return texture;}function noteMaterialTextures(material, reasons) {@@ -22969,13 +22664,13 @@ function instanceMatrices(node) {const scales = extension.getAttribute("SCALE");const translation = [];const rotation = [];- const scale2 = [];+ const scale = [];const matrices = [];for (let index = 0;index < count; index++) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);- scales?.getElement(index, scale2);- const local = new Matrix47().compose(new Vector326(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion14(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector326(scales ? scale2[0] : 1, scales ? scale2[1] : 1, scales ? scale2[2] : 1));+ scales?.getElement(index, scale);+ const local = new Matrix47().compose(new Vector326(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion14(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector326(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));matrices.push(world.clone().multiply(local));}return { matrices, count };@@ -22993,17 +22688,17 @@ async function loadGlbGeometryFlatScene(bytes) {const reasons = new Set;const meshes = [];let instanceCount = 0;- const sceneNodes2 = new Set;+ const sceneNodes = new Set;const visit = (node) => {- if (sceneNodes2.has(node))+ if (sceneNodes.has(node))return;- sceneNodes2.add(node);+ sceneNodes.add(node);for (const child of node.listChildren())visit(child);};for (const child of scene.listChildren())visit(child);- for (const node of sceneNodes2) {+ for (const node of sceneNodes) {const mesh = node.getMesh();if (!mesh)continue;@@ -23026,7 +22721,7 @@ async function loadGlbGeometryFlatScene(bytes) {}const material = primitive.getMaterial();noteMaterialTextures(material, reasons);- const geometry2 = {+ const geometry = {getAttribute(name) {return name === "position" ? { array: positions, itemSize: 3, count: positionAccessor.getCount() } : undefined;},@@ -23036,7 +22731,7 @@ async function loadGlbGeometryFlatScene(bytes) {meshes.push({isMesh: true,visible: true,- geometry: geometry2,+ geometry,material: flatMaterial(material),matrixWorld: { elements: [...matrix.elements] }});@@ -23077,12 +22772,12 @@ function localInstanceMatrices(node) {const scales = extension.getAttribute("SCALE");const translation = [];const rotation = [];- const scale2 = [];+ const scale = [];return Array.from({ length: count }, (_, index) => {translations?.getElement(index, translation);rotations?.getElement(index, rotation);- scales?.getElement(index, scale2);- return new Matrix47().compose(new Vector326(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion14(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector326(...scales ? scale2.slice(0, 3) : [1, 1, 1]));+ scales?.getElement(index, scale);+ return new Matrix47().compose(new Vector326(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion14(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector326(...scales ? scale.slice(0, 3) : [1, 1, 1]));});}async function loadGlbReviewScene(bytes) {@@ -23134,21 +22829,21 @@ async function loadGlbReviewScene(bytes) {const material = primitive.getMaterial();noteMaterialTextures(material, reasons);const flat = flatMaterial(material);- const geometry2 = new BufferGeometry14;- geometry2.setAttribute("position", new BufferAttribute8(Float32Array.from(decodedAccessor(position)), 3));+ const geometry = new BufferGeometry14;+ geometry.setAttribute("position", new BufferAttribute8(Float32Array.from(decodedAccessor(position)), 3));const normal = primitive.getAttribute("NORMAL");if (normal) {- geometry2.setAttribute("normal", new BufferAttribute8(Float32Array.from(decodedAccessor(normal)), 3));+ geometry.setAttribute("normal", new BufferAttribute8(Float32Array.from(decodedAccessor(normal)), 3));}const uv = primitive.getAttribute("TEXCOORD_0");if (uv) {- geometry2.setAttribute("uv", new BufferAttribute8(Float32Array.from(decodedAccessor(uv)), 2));+ geometry.setAttribute("uv", new BufferAttribute8(Float32Array.from(decodedAccessor(uv)), 2));}const tangent = primitive.getAttribute("TANGENT");if (tangent) {- geometry2.setAttribute("tangent", new BufferAttribute8(Float32Array.from(decodedAccessor(tangent)), 4));+ geometry.setAttribute("tangent", new BufferAttribute8(Float32Array.from(decodedAccessor(tangent)), 4));}- geometry2.setIndex(new BufferAttribute8(indices, 1));+ geometry.setIndex(new BufferAttribute8(indices, 1));const threeMaterial = new MeshStandardMaterial5({opacity: flat.opacity,transparent: flat.alphaMode === "BLEND",@@ -23171,7 +22866,7 @@ async function loadGlbReviewScene(bytes) {threeMaterial.aoMapIntensity = material.getOcclusionStrength();}for (const [index, matrix] of matrices.entries()) {- const mesh = new Mesh10(geometry2, threeMaterial);+ const mesh = new Mesh10(geometry, threeMaterial);const baseName = source.getName() || sourceMesh.getName() || "Mesh";mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;mesh.matrixAutoUpdate = false;@@ -23252,25 +22947,9 @@ var init_handler = __esm(() => {});// src/evaluator/isolation.ts-var exports_isolation = {};-__export(exports_isolation, {- renderGLBViaIsolatedEvaluator: () => renderGLBViaIsolatedEvaluator,- isolationReadinessFailureCode: () => isolationReadinessFailureCode,- isolatedEvaluatorLaunch: () => isolatedEvaluatorLaunch,- decodeEvaluatorIsolationTransport: () => decodeEvaluatorIsolationTransport,- decodeEvaluatorIsolationReadiness: () => decodeEvaluatorIsolationReadiness,- assertIsolatedEvaluatorReady: () => assertIsolatedEvaluatorReady,- EvaluatorIsolationReadinessError: () => EvaluatorIsolationReadinessError-});-import { spawn } from "node:child_process";import { existsSync } from "node:fs";import { posix } from "node:path";-import { fileURLToPath } from "node:url";-function isolationReadinessFailureCode(error) {- if (!(error instanceof EvaluatorIsolationReadinessError))- return;- return READINESS_FAILURE_CODES.includes(error.readinessCode) ? error.readinessCode : undefined;-}+import { fileURLToPath as fileURLToPath2 } from "node:url";function isolationUnavailable() {throw new EvaluatorSubprocessError("ISOLATION_UNAVAILABLE", "Isolated evaluator is unavailable.");}@@ -23309,8 +22988,8 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"const bwrapPath = requiredAbsolutePath(host.bwrapPath ?? DEFAULT_BWRAP_PATH);const setprivPath = requiredAbsolutePath(host.setprivPath ?? DEFAULT_SETPRIV_PATH);const prlimitPath = requiredAbsolutePath(host.prlimitPath ?? DEFAULT_PRLIMIT_PATH);- const nodePath5 = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);- for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath5]) {+ const nodePath = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);+ for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath]) {if (!pathExists(executable))isolationUnavailable();}@@ -23345,7 +23024,7 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"for (const mount of runtimeMounts(runtimeRoot, pathExists)) {bwrapArgs.push("--ro-bind", mount, mount);}- const nodeArgs = [nodePath5, "--max-old-space-size=512", "--disable-proto=throw"];+ const nodeArgs = [nodePath, "--max-old-space-size=512", "--disable-proto=throw"];if (loader === "tsx")nodeArgs.push("--import", "tsx");nodeArgs.push(resolvedWorkerPath);@@ -23368,224 +23047,15 @@ function isolatedEvaluatorLaunch(workerPath, host = {}) {return isolatedEvaluatorLaunchWithLoader(workerPath, host, "tsx");}async function renderGLBViaIsolatedEvaluator(code, options = {}, controls = {}) {- const workerPath = fileURLToPath(new URL("./worker.ts", import.meta.url));+ const workerPath = fileURLToPath2(new URL("./worker.ts", import.meta.url));const launch = isolatedEvaluatorLaunch(workerPath, controls.host);const { host: _, ...processControls } = controls;return renderGLBViaProcessLaunch(code, options, processControls, launch);}-function decodeEvaluatorIsolationReadiness(value) {- if (typeof value !== "object" || value === null || Array.isArray(value))- isolationUnavailable();- const record5 = value;- if (Object.keys(record5).sort().join(",") === "failure,mode,version" && record5.version === READINESS_VERSION && record5.mode === "isolated" && [- "loader-probe-boot",- "invariant-namespace",- "invariant-environment",- "invariant-filesystem",- "invariant-network",- "invariant-generated-policy"- ].includes(String(record5.failure))) {- return record5;- }- if (Object.keys(record5).sort().join(",") !== "checks,mode,version" || record5.version !== READINESS_VERSION || record5.mode !== "isolated" || !Array.isArray(record5.checks) || record5.checks.length !== READINESS_CHECKS.length || record5.checks.join(",") !== READINESS_CHECKS.join(",")) {- isolationUnavailable();- }- return record5;-}-function decodeEvaluatorIsolationTransport(value) {- if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).sort().join(",") !== "transport,version") {- isolationUnavailable();- }- const record5 = value;- if (record5.version !== TRANSPORT_VERSION || record5.transport !== "fd3")- isolationUnavailable();- return record5;-}-function terminateReadinessChild(child) {- try {- if (child.pid)- process.kill(-child.pid, "SIGKILL");- } catch {}-}-async function assertIsolationTransport(launch) {- return await new Promise((resolve, reject) => {- const child = spawn(launch.command, launch.args, {- env: launch.env,- windowsHide: true,- detached: true,- stdio: ["ignore", "pipe", "ignore", "pipe"]- });- const stdoutChunks = [];- const protocolChunks = [];- let stdoutBytes = 0;- let protocolBytes = 0;- let settled = false;- const fail = (readinessCode) => {- if (settled)- return;- settled = true;- clearTimeout(timer);- reject(new EvaluatorIsolationReadinessError(readinessCode));- };- const timer = setTimeout(() => {- terminateReadinessChild(child);- fail("deadline");- }, PROBE_DEADLINE_MS);- child.stdout?.on("data", (chunk2) => {- stdoutBytes += chunk2.byteLength;- if (stdoutBytes > MAX_TRANSPORT_STDOUT_BYTES) {- terminateReadinessChild(child);- fail("wrapper-launch");- return;- }- stdoutChunks.push(Buffer.from(chunk2));- });- const protocol = child.stdio[3];- if (!protocol) {- terminateReadinessChild(child);- fail("fd3-transport");- return;- }- protocol.on("data", (chunk2) => {- protocolBytes += chunk2.byteLength;- if (protocolBytes > MAX_READINESS_PROTOCOL_BYTES) {- terminateReadinessChild(child);- fail("fd3-transport");- return;- }- protocolChunks.push(Buffer.from(chunk2));- });- child.once("error", () => fail("wrapper-launch"));- child.once("close", (code) => {- if (settled)- return;- const stdout = Buffer.concat(stdoutChunks).toString("utf8");- if (stdout !== TRANSPORT_STDOUT_MARKER)- return fail("wrapper-launch");- if (code !== 0 || protocolChunks.length === 0)- return fail("fd3-transport");- try {- decodeEvaluatorIsolationTransport(JSON.parse(Buffer.concat(protocolChunks).toString("utf8")));- settled = true;- clearTimeout(timer);- resolve();- } catch {- fail("fd3-transport");- }- });- });-}-async function runIsolationProbe(launch) {- return await new Promise((resolve, reject) => {- const child = spawn(launch.command, launch.args, {- env: launch.env,- windowsHide: true,- detached: true,- stdio: ["ignore", "ignore", "ignore", "pipe"]- });- const protocol = child.stdio[3];- const chunks = [];- let bytes = 0;- let settled = false;- const fail = (readinessCode) => {- if (settled)- return;- settled = true;- clearTimeout(timer);- reject(new EvaluatorIsolationReadinessError(readinessCode));- };- const timer = setTimeout(() => {- terminateReadinessChild(child);- fail("deadline");- }, PROBE_DEADLINE_MS);- if (!protocol) {- terminateReadinessChild(child);- fail("fd3-transport");- return;- }- protocol.on("data", (chunk2) => {- bytes += chunk2.byteLength;- if (bytes > MAX_READINESS_PROTOCOL_BYTES) {- terminateReadinessChild(child);- fail("loader-probe-boot");- return;- }- chunks.push(Buffer.from(chunk2));- });- child.once("error", () => fail("wrapper-launch"));- child.once("close", (code) => {- if (settled)- return;- if (chunks.length === 0)- return fail("loader-probe-boot");- try {- const result = decodeEvaluatorIsolationReadiness(JSON.parse(Buffer.concat(chunks).toString("utf8")));- if ("failure" in result)- return fail(result.failure);- if (code !== 0)- return fail("loader-probe-boot");- settled = true;- clearTimeout(timer);- resolve(result);- } catch {- fail("loader-probe-boot");- }- });- });-}-async function assertIsolatedEvaluatorReady(host = {}) {- if (typeof process.getuid !== "function" || process.getuid() === 0) {- throw new EvaluatorIsolationReadinessError("invariant-namespace");- }- const transportPath = fileURLToPath(new URL("./transport-worker.mjs", import.meta.url));- const probePath = fileURLToPath(new URL("./probe-worker.ts", import.meta.url));- let transportLaunch;- let probeLaunch;- try {- transportLaunch = isolatedEvaluatorLaunchWithLoader(transportPath, host, "module");- probeLaunch = isolatedEvaluatorLaunch(probePath, host);- } catch {- throw new EvaluatorIsolationReadinessError("wrapper-launch");- }- await assertIsolationTransport(transportLaunch);- return await runIsolationProbe(probeLaunch);-}-var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", READINESS_VERSION = "kiln.evaluator.isolation-readiness.v1", TRANSPORT_VERSION = "kiln.evaluator.isolation-transport.v1", TRANSPORT_STDOUT_MARKER = `kiln-evaluator-transport-boot-v1-`, PROBE_DEADLINE_MS = 8000, MAX_READINESS_PROTOCOL_BYTES, MAX_TRANSPORT_STDOUT_BYTES = 256, READINESS_FAILURE_CODES, READINESS_CHECKS, EvaluatorIsolationReadinessError;+var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", MAX_READINESS_PROTOCOL_BYTES;var init_isolation = __esm(() => {init_subprocess();MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;- READINESS_FAILURE_CODES = [- "wrapper-launch",- "fd3-transport",- "loader-probe-boot",- "invariant-namespace",- "invariant-environment",- "invariant-filesystem",- "invariant-network",- "invariant-generated-policy",- "deadline"- ];- READINESS_CHECKS = [- "user-namespace",- "no-new-privileges",- "capabilities-empty",- "environment-exact",- "product-filesystem-denied",- "host-filesystem-denied",- "runtime-filesystem-read-only",- "network-namespace-empty",- "metadata-and-local-network-denied",- "generated-capabilities-denied"- ];- EvaluatorIsolationReadinessError = class EvaluatorIsolationReadinessError extends EvaluatorSubprocessError {- readinessCode;- constructor(readinessCode) {- super("ISOLATION_UNAVAILABLE", "Isolated evaluator readiness check failed.");- this.name = "EvaluatorIsolationReadinessError";- this.readinessCode = readinessCode;- }- };});// src/evaluator/index.ts@@ -23609,8 +23079,8 @@ function cloneReference(reference) {}function currentEvidence(sequence, surface, fidelity) {if (fidelity.version === "kiln.view-fidelity.v1") {- const valid2 = SHA256.test(fidelity.inputGlbSha256) && fidelity.rendererId.trim().length > 0 && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded);- if (!valid2) {+ const valid = SHA256.test(fidelity.inputGlbSha256) && fidelity.rendererId.trim().length > 0 && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded);+ if (!valid) {return {sequence,surface,@@ -23715,10 +23185,6 @@ var init_evidence_history = __esm(() => {});// src/views/renderer-id.ts-var exports_renderer_id = {};-__export(exports_renderer_id, {- CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID-});import { readFileSync } from "node:fs";function engineVersion() {for (const path of ["../package.json", "../../package.json"]) {@@ -23739,66 +23205,13 @@ var init_renderer_id = __esm(() => {// src/views/scene-raster.tsimport * as THREE31 from "three";-async function rasterizeComposedScene(parts, opts = {}) {- const views = opts.views?.length ? opts.views : SCENE_VIEWS;- const size = opts.size ?? 320;- const group = new THREE31.Group;- const baseByInput = new Map;- for (const part of parts) {- if (part.code === undefined === (part.glb === undefined)) {- throw new TypeError("Composed part must provide exactly one of code or glb.");- }- const key = part.glb ?? part.code;- let base = baseByInput.get(key);- if (!base) {- const glb = part.glb ? Uint8Array.from(part.glb) : (await resolveEvaluatorPortV1(opts.evaluatorPort, opts.evaluatorProfile ?? "trusted-local").render(part.code)).glb;- base = (await loadGlbReviewScene(glb)).root;- baseByInput.set(key, base);- }- const inst = base.clone(true);- inst.position.set(part.pos[0], part.pos[1], part.pos[2]);- inst.rotation.set(0, part.rotYDeg * DEG2, 0);- inst.scale.setScalar(part.scale);- group.add(inst);- }- group.updateMatrixWorld(true);- const cols = Math.min(Math.max(views.length, 1), 3);- const rows = Math.ceil(views.length / cols);- const width = cols * size + (cols + 1) * PAD2;- const height = rows * size + (rows + 1) * PAD2;- const grid = new Uint8Array(width * height * 3);- for (let i = 0;i < width * height; i++) {- grid[i * 3] = PAD_COLOR2[0];- grid[i * 3 + 1] = PAD_COLOR2[1];- grid[i * 3 + 2] = PAD_COLOR2[2];- }- for (let vi = 0;vi < views.length; vi++) {- const cell = rasterizeView(group, views[vi].dir, { size });- const col = vi % cols;- const row = Math.floor(vi / cols);- const x0 = PAD2 + col * (size + PAD2);- const y0 = PAD2 + row * (size + PAD2);- for (let y = 0;y < size; y++) {- const src = y * size * 3;- const dst = ((y0 + y) * width + x0) * 3;- grid.set(cell.subarray(src, src + size * 3), dst);- }- }- return { png: encodePng(grid, width, height), width, height, views: views.map((v) => v.name) };-}-var DEG2, PAD2 = 4, PAD_COLOR2, SCENE_VIEWS;+var DEG2;var init_scene_raster = __esm(() => {init_evaluator();init_glb();init_png();init_raster();DEG2 = Math.PI / 180;- PAD_COLOR2 = [10, 11, 13];- SCENE_VIEWS = [- { name: "Hero 3/4", dir: [0.7, 0.45, 0.7] },- { name: "Reverse 3/4", dir: [-0.7, 0.45, -0.7] },- { name: "Top", dir: [0, 1, 0.0001] }- ];});// src/views/vehicle.ts@@ -23836,10 +23249,10 @@ function describeVehicleDiagnostics(root) {const assemblies = resolveVehicleWheelAssemblies(root);const wheels = assemblies.map((wheel) => ({id: wheel.id,- center: tuple7(wheel.centerWorld.clone().applyMatrix4(inverse)),+ center: tuple6(wheel.centerWorld.clone().applyMatrix4(inverse)),radius: wheel.radius ?? 0,width: wheel.width ?? 0,- axle: tuple7(wheel.spinAxisWorld.clone().transformDirection(inverse)),+ axle: tuple6(wheel.spinAxisWorld.clone().transformDirection(inverse)),loadBearing: wheel.loadBearing}));const byAxle = new Map;@@ -23880,7 +23293,7 @@ function describeVehicleDiagnostics(root) {return {schemaVersion: 1,forwardArrow: { start: [0, 0, 0], end: [1, 0, 0] },- ...chassis ? { chassisBox: { min: tuple7(chassis.min), max: tuple7(chassis.max) } } : {},+ ...chassis ? { chassisBox: { min: tuple6(chassis.min), max: tuple6(chassis.max) } } : {},axles,wheels,...supportPlaneY !== undefined ? { supportPlaneY } : {},@@ -23890,41 +23303,41 @@ function describeVehicleDiagnostics(root) {function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}-function rod(name, start, end, radius, color2, role) {+function rod(name, start, end, radius, color, role) {const from = new THREE32.Vector3(...start);const to = new THREE32.Vector3(...end);const direction = to.clone().sub(from);- const length3 = direction.length();- const geometry2 = length3 > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length3, 8) : new THREE32.SphereGeometry(radius, 8, 6);- const result = new THREE32.Mesh(geometry2, new THREE32.MeshBasicMaterial({ color: color2 }));+ const length = direction.length();+ const geometry = length > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length, 8) : new THREE32.SphereGeometry(radius, 8, 6);+ const result = new THREE32.Mesh(geometry, new THREE32.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);- if (length3 > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length3));+ if (length > 0.000000001) {+ result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}-function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagnostics(root)) {+function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {const overlay = new THREE32.Group;overlay.name = "VehicleDiagnosticOverlay";- const chassisSpan = descriptor2.chassisBox ? Math.max(descriptor2.chassisBox.max[0] - descriptor2.chassisBox.min[0], descriptor2.chassisBox.max[1] - descriptor2.chassisBox.min[1], descriptor2.chassisBox.max[2] - descriptor2.chassisBox.min[2]) : 1;+ const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;const thickness = Math.max(0.01, chassisSpan * 0.008);const arrow = new THREE32.Group;arrow.name = "Diagnostic_Forward_+X";tagDiagnostic(arrow, "diagnostic.vehicle.forward");- arrow.add(rod("Diagnostic_Forward_Shaft", descriptor2.forwardArrow.start, [descriptor2.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));+ arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";- arrowHead.position.set(descriptor2.forwardArrow.end[0] - 0.12, 0, 0);+ arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);- for (const axle of descriptor2.axles) {+ for (const axle of descriptor.axles) {overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));}- for (const wheel of descriptor2.wheels) {+ for (const wheel of descriptor.wheels) {const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);@@ -23935,11 +23348,11 @@ function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagntagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}- if (descriptor2.chassisBox) {+ if (descriptor.chassisBox) {const chassis = new THREE32.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");- const { min, max } = descriptor2.chassisBox;+ const { min, max } = descriptor.chassisBox;const corners = [[min[0], min[1], min[2]],[max[0], min[1], min[2]],@@ -23969,13 +23382,13 @@ function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagn}overlay.add(chassis);}- if (descriptor2.supportPlaneY !== undefined) {+ if (descriptor.supportPlaneY !== undefined) {const plane = new THREE32.Group;plane.name = "Diagnostic_SupportPlane";tagDiagnostic(plane, "diagnostic.vehicle.support-plane");- const halfX = Math.max(1, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[0]), Math.abs(descriptor2.chassisBox.max[0])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;- const halfZ = Math.max(0.8, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[2]), Math.abs(descriptor2.chassisBox.max[2])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;- const y = descriptor2.supportPlaneY;+ const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;+ const halfZ = Math.max(0.8, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[2]), Math.abs(descriptor.chassisBox.max[2])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;+ const y = descriptor.supportPlaneY;const planeLines = [[[-halfX, y, -halfZ],@@ -24028,8 +23441,8 @@ function compositeForCapture(root, overlay) {children: [root, overlay]};}-function selectWheelSectionRequest(requestValue, descriptor2) {- const target = descriptor2.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor2.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor2.wheels[0];+function selectWheelSectionRequest(requestValue, descriptor) {+ const target = descriptor.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor.wheels[0];if (!target?.id.startsWith("wheel.assembly."))return requestValue;const suffix = target.id.replace(/[^a-zA-Z0-9.-]/g, "-");@@ -24043,12 +23456,12 @@ function selectWheelSectionRequest(requestValue, descriptor2) {function captureVehicleDiagnosticViews(root, intent, size = 256) {if (intent.category !== "vehicle")return [];- const descriptor2 = describeVehicleDiagnostics(root);- const overlay = createVehicleDiagnosticOverlay(root, descriptor2);+ const descriptor = describeVehicleDiagnostics(root);+ const overlay = createVehicleDiagnosticOverlay(root, descriptor);const composite = compositeForCapture(root, overlay);const requests = planDiagnosticViews(intent).extra.filter((value) => value.variant === "vehicle-underbody" || value.variant === "vehicle-wheel-section");return requests.map((baseRequest) => {- const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor2) : baseRequest;+ const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor) : baseRequest;const frame = renderDiagnosticView(composite, requestValue, { size });return {id: frame.id,@@ -24060,11 +23473,11 @@ function captureVehicleDiagnosticViews(root, intent, size = 256) {height: frame.height,png: frame.png,regions: frame.regions,- descriptor: descriptor2+ descriptor};});}-var tuple7 = (value) => [value.x, value.y, value.z];+var tuple6 = (value) => [value.x, value.y, value.z];var init_vehicle3 = __esm(() => {init_contracts();init_vehicle();@@ -24074,93 +23487,24 @@ var init_vehicle3 = __esm(() => {// src/views/index.tsvar exports_views = {};__export(exports_views, {- withCameraVisibility: () => withCameraVisibility,- validateResolvedAssetCamera: () => validateResolvedAssetCamera,- validateAdvancedCapture: () => validateAdvancedCapture,- stampAxisGnomon: () => stampAxisGnomon,- snapSceneToPalette: () => snapSceneToPalette,- selectCameraSubject: () => selectCameraSubject,- selectArchitectureRoofNodes: () => selectArchitectureRoofNodes,- resolveGridViews: () => resolveGridViews,- resolveGridCapture: () => resolveGridCapture,- resolveCaptureLimits: () => resolveCaptureLimits,- resolveCapture: () => resolveCapture,- resolveAssetCamera: () => resolveAssetCamera,- renderViewGrid: () => renderViewGrid,- renderInteriorGrid: () => renderInteriorGrid,- renderGlbViewGrid: () => renderGlbViewGrid,- renderGlbViewCell: () => renderGlbViewCell,- renderDiagnosticViews: () => renderDiagnosticViews,- renderDiagnosticView: () => renderDiagnosticView,- renderCodeViewGrid: () => renderCodeViewGrid,- renderClipAnimation: () => renderClipAnimation,- renderCaptureGrid: () => renderCaptureGrid,- rasterizeView: () => rasterizeView,- rasterizeComposedScene: () => rasterizeComposedScene,- rasterizeCamera: () => rasterizeCamera,- prepareClip: () => prepareClip,- poseSceneAtTime: () => poseSceneAtTime,- planFrameTimes: () => planFrameTimes,- planDiagnosticViews: () => planDiagnosticViews,- planCharacterDiagnosticRequests: () => planCharacterDiagnosticRequests,- orbitDir: () => orbitDir,- orbitAnglesOf: () => orbitAnglesOf,- measureBounds: () => measureBounds,- loadGlbReviewScene: () => loadGlbReviewScene,- loadGlbGeometryFlatScene: () => loadGlbGeometryFlatScene,- listCameraSubjects: () => listCameraSubjects,- hideNodeInScene: () => hideNodeInScene,- hideArchitectureRoofInScene: () => hideArchitectureRoofInScene,- hasArchitectureRoofRole: () => hasArchitectureRoofRole,- geometryFlatTextureReasonCode: () => geometryFlatTextureReasonCode,- findClip: () => findClip,- encodePng: () => encodePng,- describeVehicleDiagnostics: () => describeVehicleDiagnostics,- describeCapture: () => describeCapture,- decodePng: () => decodePng,- createVehicleDiagnosticOverlay: () => createVehicleDiagnosticOverlay,- createCachedRenderPort: () => createCachedRenderPort,- coverage: () => coverage,- compositeViewPngGrid: () => compositeViewPngGrid,- compositeCellGrid: () => compositeCellGrid,- clipNames: () => clipNames,- captureVehicleDiagnosticViews: () => captureVehicleDiagnosticViews,- captureCpuCell: () => captureCpuCell,- captureCellLabel: () => captureCellLabel,- cameraFromBounds: () => cameraFromBounds,- buildCharacterDiagnosticDescriptor: () => buildCharacterDiagnosticDescriptor,- annotateViewCell: () => annotateViewCell,- ViewEvidenceHistoryStore: () => ViewEvidenceHistoryStore,- SIX_VIEWS_REAR_QUARTER: () => SIX_VIEWS_REAR_QUARTER,- SIX_VIEWS: () => SIX_VIEWS,- SCENE_VIEWS: () => SCENE_VIEWS,- MemoryCaptureCache: () => MemoryCaptureCache,- MIN_ELEVATION_DEG: () => MIN_ELEVATION_DEG,- MAX_ELEVATION_DEG: () => MAX_ELEVATION_DEG,- MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,- INTERIOR_VIEWS: () => INTERIOR_VIEWS,- GlbGeometryFlatError: () => GlbGeometryFlatError,- GRID_COLS: () => GRID_COLS,- GRID_BACKGROUND_RGB: () => GRID_BACKGROUND_RGB,- GRID_BACKGROUND_HEX: () => GRID_BACKGROUND_HEX,- GLB_GEOMETRY_FLAT_REASON: () => GLB_GEOMETRY_FLAT_REASON,- GENERIC_DIAGNOSTIC_REQUESTS: () => GENERIC_DIAGNOSTIC_REQUESTS,- GENERIC_DIAGNOSTIC_CAMERAS: () => GENERIC_DIAGNOSTIC_CAMERAS,- GENERIC_DIAGNOSTIC_BUFFER_IDS: () => GENERIC_DIAGNOSTIC_BUFFER_IDS,- DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,- DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS,- CaptureConfigError: () => CaptureConfigError,CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID,- CHARACTER_MOTION_DIAGNOSTIC_PHASES: () => CHARACTER_MOTION_DIAGNOSTIC_PHASES,- CAPTURE_PRESETS: () => CAPTURE_PRESETS,- ARCHITECTURE_ROOF_ROLE_PREFIXES: () => ARCHITECTURE_ROOF_ROLE_PREFIXES+ cameraFromBounds: () => cameraFromBounds,+ listCameraSubjects: () => listCameraSubjects,+ loadGlbReviewScene: () => loadGlbReviewScene,+ measureBounds: () => measureBounds,+ renderCaptureGrid: () => renderCaptureGrid,+ renderClipAnimation: () => renderClipAnimation,+ renderGlbViewCell: () => renderGlbViewCell,+ renderGlbViewGrid: () => renderGlbViewGrid,+ renderInteriorGrid: () => renderInteriorGrid,+ resolveGridCapture: () => resolveGridCapture});-function setLinearColor(color2, rgb2) {- if (!color2)+function setLinearColor(color, rgb) {+ if (!color)return;- color2.r = rgb2[0];- color2.g = rgb2[1];- color2.b = rgb2[2];+ color.r = rgb[0];+ color.g = rgb[1];+ color.b = rgb[2];}function snapMaterialToPalette(mat, slots, idx) {if (!mat.color)@@ -24181,8 +23525,8 @@ function snapMaterialToPalette(mat, slots, idx) {return false;const slot = slots[slotI];const kind = slot.kind ?? "opaque";- const rgb2 = hexToLinearRgb(slot.color);- setLinearColor(mat.color, rgb2);+ const rgb = hexToLinearRgb(slot.color);+ setLinearColor(mat.color, rgb);if (mat.metalness !== undefined)mat.metalness = slot.metalness ?? 0;if (mat.roughness !== undefined)@@ -24198,7 +23542,7 @@ function snapMaterialToPalette(mat, slots, idx) {}if (mat.emissive) {if (kind === "glow") {- setLinearColor(mat.emissive, rgb2);+ setLinearColor(mat.emissive, rgb);mat.emissiveIntensity = Math.max(mat.emissiveIntensity ?? 1, 1);} else {setLinearColor(mat.emissive, [0, 0, 0]);@@ -24235,19 +23579,19 @@ async function renderViewGrid(root, opts = {}) {if (opts.capture?.shots || opts.capture?.version)return renderCaptureGrid(root, opts.capture, undefined, opts.captureLimits);const size = opts.size ?? 384;- const resolved2 = resolveGridCapture(opts.capture, process.env["KILN_GRID_VARIANT"]);- const views = opts.views ?? resolved2.views;- const cols = opts.cols ?? resolved2.cols;+ const resolved = resolveGridCapture(opts.capture, process.env["KILN_GRID_VARIANT"]);+ const views = opts.views ?? resolved.views;+ const cols = opts.cols ?? resolved.cols;enforceCapturePixels(views.length, size, cols, opts.captureLimits);if (opts.snapPalette?.length)snapSceneToPalette(root, opts.snapPalette);- const wantsZoom = resolved2.zooms.some((z) => z !== undefined);+ const wantsZoom = resolved.zooms.some((z) => z !== undefined);const sceneBounds = wantsZoom ? measureBounds(root) : undefined;const cache = opts.snapPalette?.length ? undefined : opts.captureCache;let reused = 0;const cells = [];for (let vi = 0;vi < views.length; vi++) {- const zoom = resolved2.zooms[vi];+ const zoom = resolved.zooms[vi];const rasterOptions = {size,backfaceCull: opts.backfaceCull,@@ -24256,11 +23600,11 @@ async function renderViewGrid(root, opts = {}) {};let cell;if (cache && opts.artifactGlbSha256) {- const { CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2 } = await Promise.resolve().then(() => (init_renderer_id(), exports_renderer_id));+ await Promise.resolve().then(() => init_renderer_id());const camera2 = cameraFromBounds(rasterOptions.frameBounds ?? measureBounds(root), views[vi].dir);const result = await captureCpuCell(cache, {artifactGlbSha256: opts.artifactGlbSha256,- rendererId: `${CPU_RASTER_RENDERER_ID2}/legacy-fit`,+ rendererId: `${CPU_RASTER_RENDERER_ID}/legacy-fit`,camera: camera2,size,backfaceCull: opts.backfaceCull ?? true@@ -24281,34 +23625,34 @@ async function renderViewGrid(root, opts = {}) {annotateViewCell(cell, size, views[vi]);cells.push(cell);}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);- const png = encodePng(rgb2, width, height);+ const { rgb, width, height } = compositeCellGrid(cells, size, cols);+ const png = encodePng(rgb, width, height);enforceCaptureBytes([png], opts.captureLimits);return {png,width,height,views: views.map((v) => v.name),- capture: { preset: resolved2.preset, cols, cells: views.length },+ capture: { preset: resolved.preset, cols, cells: views.length },...cache && opts.artifactGlbSha256 ? { captureCache: { hit: reused === views.length, reused, total: views.length } } : {}};}async function hashGlbViewInput(bytes) {const copy = Uint8Array.from(bytes);- const digest2 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));- return `sha256:${[...digest2].map((value) => value.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));+ return `sha256:${[...digest].map((value) => value.toString(16).padStart(2, "0")).join("")}`;}async function renderGlbViewCell(bytes, view, options = {}) {const exactBytes = Uint8Array.from(bytes);const loaded = await loadGlbGeometryFlatScene(exactBytes);const size = options.size ?? 256;- const rgb2 = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull) : rasterizeView(loaded.root, view.dir, {+ const rgb = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull) : rasterizeView(loaded.root, view.dir, {size,...options.backfaceCull !== undefined ? { backfaceCull: options.backfaceCull } : {},...options.frameBounds ? { frameBounds: options.frameBounds } : {}});return {- png: encodePng(rgb2, size, size),+ png: encodePng(rgb, size, size),width: size,height: size,inputGlbSha256: await hashGlbViewInput(exactBytes),@@ -24341,11 +23685,6 @@ function expandFrameBounds(b, factor) {}return { min, max };}-async function renderCodeViewGrid(code, opts = {}) {- const { evaluatorPort, evaluatorProfile, ...viewOptions } = opts;- const rendered = await resolveEvaluatorPortV1(evaluatorPort, evaluatorProfile ?? "trusted-local").render(code);- return renderGlbViewGrid(rendered.glb, viewOptions);-}function resolveCamera(name) {const key = (name ?? "right").trim().toLowerCase().replace(/[_\s]+/g, "-");return ANIM_CAMERAS[key] ?? ANIM_CAMERAS[ANIM_CAMERA_ALIASES[key] ?? ""] ?? ANIM_CAMERAS["right"];@@ -24465,8 +23804,8 @@ async function renderClipAnimation(root, clips, opts = {}) {pngs: cells.map((c) => encodePng(c, size, size))};}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size);- return { ...baseMeta, width, height, png: encodePng(rgb2, width, height) };+ const { rgb, width, height } = compositeCellGrid(cells, size);+ return { ...baseMeta, width, height, png: encodePng(rgb, width, height) };}function normalizeVec(v) {const len = Math.hypot(v[0], v[1], v[2]) || 1;@@ -24519,9 +23858,9 @@ async function renderInteriorGrid(root, opts = {}) {stampLabel(cell, size, size, labelScale, labelScale, view.name, labelScale);cells.push(cell);}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);+ const { rgb, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);return {- png: encodePng(rgb2, width, height),+ png: encodePng(rgb, width, height),width,height,views: INTERIOR_VIEWS.map((v) => v.name),@@ -24597,7 +23936,7 @@ var init_views = __esm(() => {// src/views/character-capture.tsimport * as THREE33 from "three";-function drawLine2(rgb2, width, height, from, to, color2) {+function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);const x1 = Math.round(to[0]);@@ -24610,9 +23949,9 @@ function drawLine2(rgb2, width, height, from, to, color2) {while (true) {if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {const offset = (y0 * width + x0) * 3;- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}if (x0 === x1 && y0 === y1)break;@@ -24627,9 +23966,9 @@ function drawLine2(rgb2, width, height, from, to, color2) {}}}-function drawCross(rgb2, width, height, point, color2, radius = 3) {- drawLine2(rgb2, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color2);- drawLine2(rgb2, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color2);+function drawCross(rgb, width, height, point, color, radius = 3) {+ drawLine2(rgb, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color);+ drawLine2(rgb, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color);}function projector(root, cameraId, size) {root.updateMatrixWorld(true);@@ -24637,48 +23976,48 @@ function projector(root, cameraId, size) {if (bounds.isEmpty())bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));const center = bounds.getCenter(new THREE33.Vector3);- const camera2 = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);+ const camera = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);const upHint = new THREE33.Vector3(0, 1, 0);- const xAxis = new THREE33.Vector3().crossVectors(upHint, camera2).normalize();- const yAxis = new THREE33.Vector3().crossVectors(camera2, xAxis).normalize();- let extent2 = 0.000001;+ const xAxis = new THREE33.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE33.Vector3().crossVectors(camera, xAxis).normalize();+ let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);- extent2 = Math.max(extent2, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));+ extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));}- const scale2 = size * 0.45 / extent2;+ const scale = size * 0.45 / extent;return (assetPoint) => {const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);- return [size / 2 + world.dot(xAxis) * scale2, size / 2 - world.dot(yAxis) * scale2];+ return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}-function skeletonCapture(root, request2, findings, size) {+function skeletonCapture(root, request, findings, size) {const baseRequest = {- id: request2.id,- label: request2.label,- cameraId: request2.cameraId,+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,buffer: "semantic-overlay",scope: "category",variant: "character-skeleton",- focusRolePrefixes: request2.focusRolePrefixes+ focusRolePrefixes: request.focusRolePrefixes};const frame = renderDiagnosticView(root, baseRequest, { size });- const descriptor2 = buildCharacterDiagnosticDescriptor(root, findings);- const project2 = projector(root, request2.cameraId, size);- const byRole = new Map(descriptor2.joints.map((joint) => [joint.role, joint]));- for (const edge of descriptor2.edges) {+ const descriptor = buildCharacterDiagnosticDescriptor(root, findings);+ const project = projector(root, request.cameraId, size);+ const byRole = new Map(descriptor.joints.map((joint) => [joint.role, joint]));+ for (const edge of descriptor.edges) {const parent = byRole.get(edge.parentRole);const child = byRole.get(edge.childRole);if (!parent || !child)continue;- drawLine2(frame.rgb, frame.width, frame.height, project2(parent.assetPosition), project2(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);- }- for (const joint of descriptor2.joints) {- const point = project2(joint.assetPosition);- const color2 = rgbFromHex(joint.color);- drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color2);- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.forwardAxisEnd), [64, 220, 255]);- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.bendAxisEnd), [255, 105, 210]);+ drawLine2(frame.rgb, frame.width, frame.height, project(parent.assetPosition), project(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);+ }+ for (const joint of descriptor.joints) {+ const point = project(joint.assetPosition);+ const color = rgbFromHex(joint.color);+ drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color);+ drawLine2(frame.rgb, frame.width, frame.height, point, project(joint.forwardAxisEnd), [64, 220, 255]);+ drawLine2(frame.rgb, frame.width, frame.height, point, project(joint.bendAxisEnd), [255, 105, 210]);stampLabel(frame.rgb, frame.width, frame.height, Math.max(0, Math.min(frame.width - 2, Math.round(point[0] + 3))), Math.max(0, Math.min(frame.height - 7, Math.round(point[1] - 6))), joint.label.toUpperCase().replace(/[^A-Z0-9]+/g, " ").slice(0, 18), 1);frame.regions.push({nodeName: joint.nodeName,@@ -24690,17 +24029,17 @@ function skeletonCapture(root, request2, findings, size) {Math.min(frame.width - 1, Math.round(point[0]) + 4),Math.min(frame.height - 1, Math.round(point[1]) + 4)],- color: color2,+ color,triangleCount: 0});}- const arrow = descriptor2.canonicalForwardArrow;- drawLine2(frame.rgb, frame.width, frame.height, project2(arrow.start), project2(arrow.end), [255, 220, 64]);+ const arrow = descriptor.canonicalForwardArrow;+ drawLine2(frame.rgb, frame.width, frame.height, project(arrow.start), project(arrow.end), [255, 220, 64]);frame.regions.sort((a, b) => a.nodePath.localeCompare(b.nodePath));return {id: frame.id,label: frame.label,- cameraId: request2.cameraId,+ cameraId: request.cameraId,kind: "skeleton",width: frame.width,height: frame.height,@@ -24721,32 +24060,32 @@ async function captureCharacterDiagnosticViews(root, clips, intent, findings = [const requests = planCharacterDiagnosticRequests(intent);const captures = [];try {- for (const request2 of requests) {- if (request2.variant === "character-skeleton") {- captures.push(skeletonCapture(root, request2, findings, size));+ for (const request of requests) {+ if (request.variant === "character-skeleton") {+ captures.push(skeletonCapture(root, request, findings, size));continue;}- if (!request2.clipName)+ if (!request.clipName)continue;const strip = await renderClipAnimation(root, clips, {- clip: request2.clipName,- camera: request2.cameraId,- frames: request2.phaseFractions?.length ?? 6,+ clip: request.clipName,+ camera: request.cameraId,+ frames: request.phaseFractions?.length ?? 6,size});if (!strip.ok || !strip.png || !strip.width || !strip.height)continue;captures.push({- id: request2.id,- label: request2.label,- cameraId: request2.cameraId,+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,kind: "motion-strip",width: strip.width,height: strip.height,png: strip.png,regions: [],- clipName: request2.clipName,- phaseFractions: request2.phaseFractions+ clipName: request.clipName,+ phaseFractions: request.phaseFractions});}} finally {@@ -24772,27 +24111,7 @@ var init_character_capture = __esm(() => {});// src/render.ts-var exports_render = {};-__export(exports_render, {- snapGlbToPalette: () => snapGlbToPalette,- settleContacts: () => settleContacts,- resolveEvaluatorMode: () => resolveEvaluatorMode,- renderSceneToGLB: () => renderSceneToGLB,- renderGLBInProcess: () => renderGLBInProcess,- renderGLB: () => renderGLB,- packKitGlb: () => packKitGlb,- optimizeGlbBytes: () => optimizeGlbBytes,- measureGlbBounds: () => measureGlbBounds,- inspectSceneStructure: () => inspectSceneStructure,- inspectGlbIntegration: () => inspectGlbIntegration,- inspectGeneratedAnimation: () => inspectGeneratedAnimation,- gradeGlbBytes: () => gradeGlbBytes,- executeKilnCode: () => executeKilnCode,- composeSceneGLB: () => composeSceneGLB,- bindBakedTextureProvenanceToFinalGlb: () => bindBakedTextureProvenanceToFinalGlb-});import * as THREE34 from "three";-import { createHash as createHash5 } from "node:crypto";import { Document, WebIO as WebIO3, getBounds } from "@gltf-transform/core";import {EXTMeshGPUInstancing as EXTMeshGPUInstancing3,@@ -24804,25 +24123,11 @@ import {instance,palette,flatten,- join as join2,+ join,weld,prune,mergeDocuments} from "@gltf-transform/functions";-async function measureGlbBounds(bytes) {- const doc = await engineIO().readBinary(bytes);- const root = doc.getRoot();- const scene = root.getDefaultScene() ?? root.listScenes()[0];- if (!scene)- return;- const { min, max } = getBounds(scene);- if (!min.every(Number.isFinite) || !max.every(Number.isFinite))- return;- return {- min: [min[0], min[1], min[2]],- max: [max[0], max[1], max[2]]- };-}function ensureDefaultScene(doc) {const root = doc.getRoot();const scene = root.getDefaultScene() ?? root.listScenes()[0];@@ -24831,8 +24136,8 @@ function ensureDefaultScene(doc) {return scene;}async function sha256Hex2(bytes) {- const digest2 = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer);- return [...new Uint8Array(digest2)].map((value) => value.toString(16).padStart(2, "0")).join("");+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer);+ return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");}async function inspectGlbIntegration(bytes, opts = {}) {const doc = await engineIO().readBinary(bytes);@@ -25038,28 +24343,28 @@ function bridgeTexture(doc, threeTex, cache) {cache.set(threeTex, t);return t;}-function bridgeGeometry(doc, buf, geometry2, material, meshName) {- if (!geometry2.getAttribute("normal")) {- geometry2.computeVertexNormals();+function bridgeGeometry(doc, buf, geometry, material, meshName) {+ if (!geometry.getAttribute("normal")) {+ geometry.computeVertexNormals();}const prim = doc.createPrimitive().setMaterial(Array.isArray(material) ? material[0] : material);- const posAttr = geometry2.getAttribute("position");+ const posAttr = geometry.getAttribute("position");if (posAttr) {prim.setAttribute("POSITION", doc.createAccessor(meshName + "_pos").setArray(geometryAttributeValues(posAttr)).setType(TYPE_VEC3).setBuffer(buf));}- const normAttr = geometry2.getAttribute("normal");+ const normAttr = geometry.getAttribute("normal");if (normAttr) {prim.setAttribute("NORMAL", doc.createAccessor(meshName + "_norm").setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));}- const uvAttr = geometry2.getAttribute("uv");+ const uvAttr = geometry.getAttribute("uv");if (uvAttr) {prim.setAttribute("TEXCOORD_0", doc.createAccessor(meshName + "_uv").setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));}- const tangentAttr = geometry2.getAttribute("tangent");+ const tangentAttr = geometry.getAttribute("tangent");if (tangentAttr?.itemSize === 4) {prim.setAttribute("TANGENT", doc.createAccessor(meshName + "_tangent").setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));}- const indexAttr = geometry2.getIndex();+ const indexAttr = geometry.getIndex();if (indexAttr) {const IndexArray = posAttr && posAttr.count > 65535 ? Uint32Array : Uint16Array;prim.setIndices(doc.createAccessor(meshName + "_idx").setArray(new IndexArray(indexAttr.array)).setType(TYPE_SCALAR).setBuffer(buf));@@ -25068,15 +24373,15 @@ function bridgeGeometry(doc, buf, geometry2, material, meshName) {if (!Array.isArray(material))return mesh.addPrimitive(prim);const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);- const groups = [...geometry2.groups].sort((a, b) => a.start - b.start);+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);let covered = 0;for (const group of groups) {if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);}const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);- for (const semantic3 of prim.listSemantics())- part.setAttribute(semantic3, prim.getAttribute(semantic3));+ for (const semantic of prim.listSemantics())+ part.setAttribute(semantic, prim.getAttribute(semantic));const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;part.setIndices(doc.createAccessor(meshName + "_group_indices").setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));mesh.addPrimitive(part);@@ -25111,13 +24416,13 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)}}if (semanticForExport !== undefined) {- const semantic3 = validateSemanticMetadataV1(semanticForExport);- if (!semantic3.valid || !semantic3.value) {- const detail = semantic3.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");+ const semantic = validateSemanticMetadataV1(semanticForExport);+ if (!semantic.valid || !semantic.value) {+ const detail = semantic.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on node ${threeObj.name || "<unnamed>"}: ${detail}`);}gtNode.setExtras({- [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic3.value)+ [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic.value)});}gtNode.setTranslation([threeObj.position.x, threeObj.position.y, threeObj.position.z]);@@ -25150,13 +24455,13 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;let gtMesh = meshCache.get(cacheKey);if (!gtMesh) {- const geometry2 = new THREE34.PlaneGeometry(1, 1);+ const geometry = new THREE34.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {- geometry2.translate(0.5 - centerX, 0.5 - centerY, 0);+ geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}if (rotation !== 0)- geometry2.rotateZ(rotation);- gtMesh = bridgeGeometry(doc, buf, geometry2, gtMat, sprite.name || "sprite-quad");+ geometry.rotateZ(rotation);+ gtMesh = bridgeGeometry(doc, buf, geometry, gtMat, sprite.name || "sprite-quad");meshCache.set(cacheKey, gtMesh);}gtNode.setMesh(gtMesh);@@ -25175,11 +24480,11 @@ function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {const anim = doc.createAnimation(clip.name);for (const track of clip.tracks) {const dotIdx = track.name.lastIndexOf(".");- const nodeName2 = track.name.substring(0, dotIdx);+ const nodeName = track.name.substring(0, dotIdx);const property = track.name.substring(dotIdx + 1);- const targetNode = nodeMap.get(nodeName2);+ const targetNode = nodeMap.get(nodeName);if (!targetNode) {- warnings.push(`Animation target "${nodeName2}" not found - skipped`);+ warnings.push(`Animation target "${nodeName}" not found - skipped`);continue;}let targetPath;@@ -25194,11 +24499,11 @@ function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {targetPath = "scale";valueType = TYPE_VEC3;} else {- warnings.push(`Unsupported animation property "${property}" on "${nodeName2}" - skipped`);+ warnings.push(`Unsupported animation property "${property}" on "${nodeName}" - skipped`);continue;}- const inputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);- const outputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);+ const inputAcc = doc.createAccessor(clip.name + "_" + nodeName + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);+ const outputAcc = doc.createAccessor(clip.name + "_" + nodeName + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);const sampler = doc.createAnimationSampler().setInput(inputAcc).setOutput(outputAcc).setInterpolation("LINEAR");const channel = doc.createAnimationChannel().setTargetNode(targetNode).setTargetPath(targetPath).setSampler(sampler);anim.addSampler(sampler);@@ -25236,80 +24541,6 @@ function reviewClipExtras(clips) {}))};}-function finalTextureForSlot(material, slot) {- switch (slot) {- case "map":- return material.getBaseColorTexture();- case "normalMap":- return material.getNormalTexture();- case "roughnessMap":- case "metalnessMap":- return material.getMetallicRoughnessTexture();- case "emissiveMap":- return material.getEmissiveTexture();- case "aoMap":- return material.getOcclusionTexture();- default:- return null;- }-}-async function bindBakedTextureProvenanceToFinalGlb(baked, finalGlb) {- if (baked.length === 0)- return [];- const doc = await engineIO().readBinary(finalGlb);- const root = doc.getRoot();- const byMaterialName = new Map;- for (const material of root.listMaterials()) {- const name = material.getName() || "(unnamed material)";- const list = byMaterialName.get(name) ?? [];- list.push(material);- byMaterialName.set(name, list);- }- const nodesByName = new Map;- for (const node of root.listNodes()) {- const list = nodesByName.get(node.getName()) ?? [];- list.push(node);- nodesByName.set(node.getName(), list);- }- const artifactGlbSha256 = `sha256:${await sha256Hex2(finalGlb)}`;- return baked.flatMap((entry) => {- const resolved2 = new Set;- for (const binding of entry.bindings) {- const nodeMaterials = (nodesByName.get(binding.node) ?? []).flatMap((node) => node.getMesh()?.listPrimitives().flatMap((primitive) => {- const material = primitive.getMaterial();- return material ? [material] : [];- }) ?? []);- const materials = nodeMaterials.filter((material) => (material.getName() || "(unnamed material)") === binding.material);- const candidates = materials.length ? materials : byMaterialName.get(binding.material) ?? [];- for (const material of candidates) {- const texture2 = finalTextureForSlot(material, binding.slot);- if (texture2)- resolved2.add(texture2);- }- }- if (resolved2.size === 0 && entry.texture !== "(unnamed texture)") {- for (const texture2 of root.listTextures()) {- if (texture2.getName() === entry.texture)- resolved2.add(texture2);- }- }- if (resolved2.size !== 1)- return [];- const texture = [...resolved2][0];- const image = texture.getImage();- const mime = texture.getMimeType();- if (!image || !mime)- return [];- return [- {- ...entry,- artifactGlbSha256,- finalMime: mime,- finalImageSha256: `sha256:${createHash5("sha256").update(image).digest("hex")}`- }- ];- });-}function resolveOptimize(opt) {if (opt)return opt;@@ -25359,7 +24590,7 @@ async function consolidateMaterials(doc, mode) {const effective = mode === "full" && (animatedOrSkinned || semanticGraph) ? "palette" : mode;const steps = [palette({ min: PALETTE_MIN })];if (effective === "full") {- steps.push(flatten(), join2({ keepNamed: true }));+ steps.push(flatten(), join({ keepNamed: true }));}steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));await doc.transform(...steps);@@ -25587,240 +24818,6 @@ function resolveEvaluatorMode(env = process.env) {return "isolated";throw new Error("Invalid KILN_EVALUATOR_MODE.");}-async function renderGLB(code, opts = {}) {- const mode = resolveEvaluatorMode();- if (mode === "in-process")- return renderGLBInProcess(code, opts);- if (mode === "subprocess") {- const { renderGLBViaSubprocess: renderGLBViaSubprocess2 } = await Promise.resolve().then(() => (init_subprocess(), exports_subprocess));- return renderGLBViaSubprocess2(code, opts);- }- const { renderGLBViaIsolatedEvaluator: renderGLBViaIsolatedEvaluator2 } = await Promise.resolve().then(() => (init_isolation(), exports_isolation));- return renderGLBViaIsolatedEvaluator2(code, opts);-}-async function gradeGlbBytes(bytes, opts = {}) {- try {- const doc = await engineIO().readBinary(bytes);- return gradeInstanceability(collectGlbMetrics(doc), opts);- } catch {- return;- }-}-async function optimizeGlbBytes(bytes, opts = {}) {- const requested = opts.mode ?? "palette";- try {- const io = engineIO();- const doc = await io.readBinary(bytes);- let instancing;- if (opts.instance && opts.instance !== "off") {- instancing = await applyGpuInstancing(doc, opts.instance, opts.role);- }- let summary;- let mode;- if (requested !== "off") {- if (requested === "auto") {- if (collectGlbMetrics(doc).uniqueMaterials >= PALETTE_MIN)- mode = "palette";- } else {- mode = requested;- }- }- if (mode)- summary = await consolidateMaterials(doc, mode);- if (!summary && !instancing)- return;- ensureDefaultScene(doc);- const outBytes = await io.writeBinary(doc);- const gltfValidation = await assertFinalGlbValid(outBytes);- let report;- try {- report = gradeInstanceability(collectGlbMetrics(doc), { category: opts.category });- } catch {- report = undefined;- }- return {- bytes: outBytes,- gltfValidation,- ...report ? { report } : {},- ...summary ? { summary } : {},- ...instancing ? { instancing } : {}- };- } catch (error) {- if (error instanceof GltfValidationError)- throw error;- return;- }-}-async function packKitGlb(bytes, opts = {}) {- let doc;- try {- doc = await engineIO().readBinary(bytes);- } catch {- return;- }- const summary = await applyKitContract(doc, opts);- const changed = summary.ormPacked > 0 || summary.variantsAdded.length > 0 || summary.ktx2.applied;- if (!changed)- return;- ensureDefaultScene(doc);- const outBytes = await engineIO().writeBinary(doc);- const gltfValidation = await assertFinalGlbValid(outBytes);- return { bytes: outBytes, summary, gltfValidation };-}-async function snapGlbToPalette(bytes, slots, opts = {}) {- if (slots.length === 0)- return;- try {- const io = engineIO();- const doc = await io.readBinary(bytes);- const before = collectGlbMetrics(doc);- const idx = buildSlotIndex(slots);- let snapped = 0;- let skipped = 0;- for (const mat of doc.getRoot().listMaterials()) {- if (mat.getBaseColorTexture()) {- skipped++;- continue;- }- const base = mat.getBaseColorFactor();- const emissive = mat.getEmissiveFactor();- const transparent = mat.getAlphaMode() === "BLEND" || mat.getAlpha() < 0.98;- const slotI = chooseSlot(idx, {- baseLinear: [base[0], base[1], base[2]],- emissiveLinear: [emissive[0], emissive[1], emissive[2]],- transparent- });- if (slotI === undefined) {- skipped++;- continue;- }- const slot = slots[slotI];- const kind = slot.kind ?? "opaque";- const [lr, lg, lb] = hexToLinearRgb(slot.color);- const alpha = kind === "glass" ? slot.opacity ?? 0.4 : 1;- mat.setBaseColorFactor([lr, lg, lb, alpha]);- mat.setMetallicFactor(slot.metalness ?? 0);- mat.setRoughnessFactor(slot.roughness ?? (kind === "glass" ? 0.1 : 0.85));- if (kind === "glass")- mat.setAlphaMode("BLEND");- else if (mat.getAlphaMode() === "BLEND")- mat.setAlphaMode("OPAQUE");- mat.setEmissiveFactor(kind === "glow" ? [lr, lg, lb] : [0, 0, 0]);- snapped++;- }- await doc.transform(dedup());- await consolidateMaterials(doc, "palette");- const after = collectGlbMetrics(doc);- const summary = {- mode: "palette",- materialsBefore: before.uniqueMaterials,- materialsAfter: after.uniqueMaterials,- drawsBefore: before.drawCalls,- drawsAfter: after.drawCalls- };- ensureDefaultScene(doc);- const outBytes = await io.writeBinary(doc);- const gltfValidation = await assertFinalGlbValid(outBytes);- let report;- try {- report = gradeInstanceability(after, { category: opts.category });- } catch {- report = undefined;- }- return {- bytes: outBytes,- ...report ? { report } : {},- summary,- snapped,- skipped,- gltfValidation- };- } catch (error) {- if (error instanceof GltfValidationError)- throw error;- return;- }-}-function eulerDegToQuat(deg) {- const e = new THREE34.Euler(THREE34.MathUtils.degToRad(deg[0]), THREE34.MathUtils.degToRad(deg[1]), THREE34.MathUtils.degToRad(deg[2]), "XYZ");- const q = new THREE34.Quaternion().setFromEuler(e);- return [q.x, q.y, q.z, q.w];-}-async function composeSceneGLB(parts, opts = {}) {- const warnings = [];- const io = engineIO();- const master = new Document;- const masterScene = master.createScene(opts.sceneName ?? "Scene");- master.getRoot().setDefaultScene(masterScene);- let composed = 0;- for (let i = 0;i < parts.length; i++) {- const part = parts[i];- try {- const src = await io.readBinary(part.bytes);- const srcScene = src.getRoot().listScenes()[0];- const map = mergeDocuments(master, src);- const wrap = master.createNode(part.name ?? `part_${i}`).setTranslation([part.transform.pos[0], part.transform.pos[1], part.transform.pos[2]]).setRotation(eulerDegToQuat(part.transform.rotDeg)).setScale([part.transform.scale[0], part.transform.scale[1], part.transform.scale[2]]);- const mergedScene = srcScene ? map.get(srcScene) : undefined;- if (mergedScene) {- for (const child of mergedScene.listChildren())- wrap.addChild(child);- mergedScene.dispose();- }- masterScene.addChild(wrap);- composed++;- } catch (err) {- warnings.push(`part ${i} (${part.name ?? ""}) skipped: ${err instanceof Error ? err.message : String(err)}`);- }- }- if (composed === 0)- throw new Error("composeSceneGLB: no parts could be merged");- if (!opts.keepAnimations) {- for (const anim of master.getRoot().listAnimations())- anim.dispose();- }- try {- await master.transform(dedup());- } catch (err) {- warnings.push(`dedup failed: ${err instanceof Error ? err.message : String(err)}`);- }- const optimizeMode = opts.optimize ?? "palette";- let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;- if (optimizeMode === "auto" && collectGlbMetrics(master).uniqueMaterials >= PALETTE_MIN) {- effectiveOptimize = "palette";- }- if (effectiveOptimize !== "off") {- try {- await consolidateMaterials(master, effectiveOptimize);- } catch (err) {- warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);- }- }- const rootBuffers = master.getRoot().listBuffers();- if (rootBuffers.length > 1) {- const main = rootBuffers[0];- for (const acc of master.getRoot().listAccessors())- acc.setBuffer(main);- for (let i = 1;i < rootBuffers.length; i++)- rootBuffers[i].dispose();- }- const metrics = collectGlbMetrics(master);- ensureDefaultScene(master);- const bytes = await io.writeBinary(master);- const gltfValidation = await assertFinalGlbValid(bytes, "scene.glb");- for (const issue of gltfValidation.issues.messages) {- if (issue.severity !== 1)- continue;- warnings.push(`glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ""}: ${issue.message}`);- }- return {- bytes,- tris: metrics.triangles,- draws: metrics.drawCalls,- materials: metrics.uniqueMaterials,- warnings,- gltfValidation- };-}function inspectGeneratedAnimation(root, clips) {const warnings = [];if (clips.length === 0)@@ -25837,10 +24834,10 @@ function inspectGeneratedAnimation(root, clips) {warnings.push(`Track "${track.name}" is missing a node.property separator`);continue;}- const nodeName2 = track.name.substring(0, dotIdx);+ const nodeName = track.name.substring(0, dotIdx);const property = track.name.substring(dotIdx + 1);- if (!nodeNames.has(nodeName2)) {- warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName2}" — rename the pivot or fix the track`);+ if (!nodeNames.has(nodeName)) {+ warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName}" — rename the pivot or fix the track`);}if (!["position", "quaternion", "scale"].includes(property)) {warnings.push(`Animation track "${clip.name}:${track.name}" uses unsupported property "${property}"`);@@ -25963,58 +24960,6 @@ function inspectSceneStructure(root, opts = {}) {}return warnings;}-function settleContacts(root, opts = {}) {- const maxGap = opts.maxGap ?? 0.05;- const overlap = opts.overlap ?? 0.01;- const settled = [];- for (let pass = 0;pass < 8; pass++) {- const meshes = collectMeshStats(root);- if (meshes.length < 2)- return settled;- let pick;- for (let i = 0;i < meshes.length; i++) {- const a = meshes[i];- const ax = a.box.clone().expandByScalar(0.02);- if (meshes.some((b, j) => j !== i && ax.intersectsBox(b.box)))- continue;- let nearestGap;- for (let j = 0;j < meshes.length; j++) {- if (i === j)- continue;- const gap = minimalGapVector(a.box, meshes[j].box);- if (!nearestGap || gap.length() < nearestGap.length())- nearestGap = gap;- }- if (!nearestGap || nearestGap.length() === 0 || nearestGap.length() > maxGap)- continue;- const volume = a.size.x * a.size.y * a.size.z;- if (!pick || volume < pick.volume)- pick = { stats: a, gap: nearestGap, volume };- }- if (!pick)- break;- const delta = pick.gap.clone();- const dominant = ["x", "y", "z"].reduce((d, axis) => Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d, "x");- delta[dominant] += Math.sign(delta[dominant]) * overlap;- let target;- root.traverse((obj) => {- if (!target && obj.name === pick.stats.name && obj.isMesh)- target = obj;- });- if (!target)- break;- const parent = target.parent ?? root;- const p0 = new THREE34.Vector3;- target.getWorldPosition(p0);- const p1 = p0.clone().add(delta);- const l0 = parent.worldToLocal(p0.clone());- const l1 = parent.worldToLocal(p1.clone());- target.position.add(l1.sub(l0));- target.updateMatrixWorld(true);- settled.push(pick.stats.name);- }- return settled;-}var engineIO = () => new WebIO3().registerExtensions([EXTMeshGPUInstancing3, KHRMaterialsVariants3, KHRTextureBasisu3]), TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;var init_render = __esm(() => {init_authoring_diagnostic();@@ -26043,26 +24988,7 @@ var init_render = __esm(() => {});// src/evaluator/protocol.ts-var exports_protocol = {};-__export(exports_protocol, {- trustedInProcessEvaluatorPortV1: () => trustedInProcessEvaluatorPortV1,- resolveEvaluatorPortV1: () => resolveEvaluatorPortV1,- evaluatorOutcomeMessage: () => evaluatorOutcomeMessage,- encodeRenderResultV1: () => encodeRenderResultV1,- decodeEvaluatorResultV1: () => decodeEvaluatorResultV1,- decodeEvaluatorRequestV1: () => decodeEvaluatorRequestV1,- createEvaluatorRequestV1: () => createEvaluatorRequestV1,- createEvaluatorPortV1: () => createEvaluatorPortV1,- MAX_EVALUATOR_REQUEST_BYTES: () => MAX_EVALUATOR_REQUEST_BYTES,- MAX_EVALUATOR_CODE_BYTES: () => MAX_EVALUATOR_CODE_BYTES,- EvaluatorPortError: () => EvaluatorPortError,- EVALUATOR_RESULT_VERSION: () => EVALUATOR_RESULT_VERSION,- EVALUATOR_REQUEST_VERSION: () => EVALUATOR_REQUEST_VERSION,- DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES: () => DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES,- DEFAULT_EVALUATOR_MAX_GLB_BYTES: () => DEFAULT_EVALUATOR_MAX_GLB_BYTES,- DEFAULT_EVALUATOR_DEADLINE_MS: () => DEFAULT_EVALUATOR_DEADLINE_MS-});-import { createHash as createHash6 } from "node:crypto";+import { createHash as createHash5 } from "node:crypto";function evaluatorOutcomeMessage(code) {return EVALUATOR_OUTCOME_MESSAGES[code];}@@ -26090,12 +25016,12 @@ function validInteger(value, min, max) {return Number.isInteger(value) && Number(value) >= min && Number(value) <= max;}function validQaReport(value) {- const dimensions2 = isRecord6(value) && isRecord6(value.dimensions) ? value.dimensions : undefined;- if (!isRecord6(value) || !hasExactKeys(value, ["schemaVersion", "category", "qaProfile", "disposition", "dimensions"]) || value.schemaVersion !== 1 || !isAssetCategory(value.category) || typeof value.qaProfile !== "string" || value.qaProfile.length < 1 || value.qaProfile.length > 128 || !["pass", "warn", "block", "notEvaluated", "legacy-unassessed"].includes(String(value.disposition)) || !dimensions2 || !hasExactKeys(dimensions2, QA_DIMENSIONS) || !QA_DIMENSIONS.every((dimension) => (dimension in dimensions2))) {+ const dimensions = isRecord6(value) && isRecord6(value.dimensions) ? value.dimensions : undefined;+ if (!isRecord6(value) || !hasExactKeys(value, ["schemaVersion", "category", "qaProfile", "disposition", "dimensions"]) || value.schemaVersion !== 1 || !isAssetCategory(value.category) || typeof value.qaProfile !== "string" || value.qaProfile.length < 1 || value.qaProfile.length > 128 || !["pass", "warn", "block", "notEvaluated", "legacy-unassessed"].includes(String(value.disposition)) || !dimensions || !hasExactKeys(dimensions, QA_DIMENSIONS) || !QA_DIMENSIONS.every((dimension) => (dimension in dimensions))) {return false;}return QA_DIMENSIONS.every((dimension) => {- const result = dimensions2[dimension];+ const result = dimensions[dimension];return isRecord6(result) && hasExactKeys(result, ["status", "findings", "metrics"]) && ["pass", "warn", "block", "notEvaluated"].includes(String(result.status)) && Array.isArray(result.findings) && result.findings.length <= 1000 && result.findings.every(isQaFinding) && (result.metrics === undefined || isRecord6(result.metrics));});}@@ -26106,85 +25032,6 @@ function validGltfValidation(value) {}return ["numErrors", "numWarnings", "numInfos", "numHints"].every((key) => validInteger(issues[key], 0, Number.MAX_SAFE_INTEGER)) && issues.messages.length <= 1000 && issues.messages.every((issue) => isRecord6(issue) && typeof issue.code === "string" && typeof issue.message === "string" && typeof issue.severity === "number" && Number.isFinite(issue.severity));}-function boundedControl(value, fallback, max) {- const resolved2 = value ?? fallback;- if (!validInteger(resolved2, 1, max)) {- throw new EvaluatorPortError("INPUT_INVALID");- }- return resolved2;-}-function createEvaluatorRequestV1(input) {- if (input.options?.textureResolver) {- throw new EvaluatorPortError("INPUT_INVALID", "Evaluator requests do not accept a host resolver capability.");- }- const maxGlbBytes = boundedControl(input.maxGlbBytes, DEFAULT_EVALUATOR_MAX_GLB_BYTES, 64 * 1024 * 1024);- const { textureResolver: _, ...options } = input.options ?? {};- const request2 = {- version: EVALUATOR_REQUEST_VERSION,- requestId: input.requestId,- operation: "execute-export-glb",- code: input.code,- options,- limits: { maxGlbBytes }- };- const json = JSON.stringify(request2);- const decoded = decodeEvaluatorRequestV1(json);- return { request: decoded, json };-}-function parseOptions(value) {- if (!isRecord6(value) || !hasExactKeys(value, ["optimize", "instance", "intent", "category", "geometryPolicy"])) {- return fail("request");- }- const options = {};- if (value.geometryPolicy !== undefined) {- if (!["warn", "strict"].includes(String(value.geometryPolicy)))- fail("request");- options.geometryPolicy = value.geometryPolicy;- }- if (value.optimize !== undefined) {- if (!["off", "auto", "palette", "full"].includes(String(value.optimize)))- fail("request");- options.optimize = value.optimize;- }- if (value.instance !== undefined) {- if (!["off", "auto", "on"].includes(String(value.instance)))- fail("request");- options.instance = value.instance;- }- if (value.category !== undefined) {- if (!isAssetCategory(value.category))- fail("request");- options.category = value.category;- }- if (value.intent !== undefined) {- const result = validateAssetIntentV1(value.intent);- if (!result.valid)- fail("request");- options.intent = result.value;- }- return options;-}-function decodeEvaluatorRequestV1(json) {- if (Buffer.byteLength(json, "utf8") > MAX_EVALUATOR_REQUEST_BYTES)- fail("request");- let value;- try {- value = JSON.parse(json);- } catch {- return fail("request");- }- if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "operation", "code", "options", "limits"]) || value.version !== EVALUATOR_REQUEST_VERSION || !validRequestId(value.requestId) || value.operation !== "execute-export-glb" || typeof value.code !== "string" || Buffer.byteLength(value.code, "utf8") > MAX_EVALUATOR_CODE_BYTES || !isRecord6(value.limits) || !hasExactKeys(value.limits, ["maxGlbBytes"]) || !validInteger(value.limits.maxGlbBytes, 1, 64 * 1024 * 1024)) {- return fail("request");- }- return {- version: EVALUATOR_REQUEST_VERSION,- requestId: value.requestId,- operation: "execute-export-glb",- code: value.code,- options: parseOptions(value.options),- limits: { maxGlbBytes: value.limits.maxGlbBytes }- };-}function encodeRenderResultV1(requestId, render) {const { glb, diagnosticViews, buildCache: _hostCacheReceipt, ...rest } = render;return {@@ -26272,7 +25119,7 @@ function decodeEvaluatorResultV1(json, maxGlbBytes, expectedRequestId) {fail("result");if (!isSha256(value.render.artifactGlbSha256))fail("result");- const actualHash = `sha256:${createHash6("sha256").update(glb).digest("hex")}`;+ const actualHash = `sha256:${createHash5("sha256").update(glb).digest("hex")}`;if (actualHash !== value.render.artifactGlbSha256)fail("result");const diagnosticViews = value.render.diagnosticViews;@@ -26284,7 +25131,7 @@ function decodeEvaluatorResultV1(json, maxGlbBytes, expectedRequestId) {const png = Buffer.from(candidate.pngBase64, "base64");if (png.toString("base64") !== candidate.pngBase64)return fail("result");- const { pngBase64: _2, ...view } = candidate;+ const { pngBase64: _, ...view } = candidate;return { ...view, png };});const { glbBase64: _, diagnosticViews: __, ...rest } = value.render;@@ -26299,78 +25146,7 @@ function decodeEvaluatorResultV1(json, maxGlbBytes, expectedRequestId) {}};}-function createEvaluatorPortV1(transport, defaults2 = {}) {- let sequence = 0;- return {- async render(code, options = {}, controls = {}) {- const signal = controls.signal ?? defaults2.signal;- if (signal?.aborted)- throw new EvaluatorPortError("CANCELLED");- const deadlineMs = boundedControl(controls.deadlineMs ?? defaults2.deadlineMs, DEFAULT_EVALUATOR_DEADLINE_MS, 120000);- const maxGlbBytes = boundedControl(controls.maxGlbBytes ?? defaults2.maxGlbBytes, DEFAULT_EVALUATOR_MAX_GLB_BYTES, 64 * 1024 * 1024);- const maxResponseBytes = boundedControl(controls.maxResponseBytes ?? defaults2.maxResponseBytes, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);- const requestId = `eval-${++sequence}`;- const built = createEvaluatorRequestV1({ requestId, code, options, maxGlbBytes });- let timer;- let response;- const transportController = new AbortController;- let abort;- try {- const cancelled = new Promise((_, reject) => {- abort = () => {- reject(new EvaluatorPortError("CANCELLED"));- transportController.abort();- };- signal?.addEventListener("abort", abort, { once: true });- });- response = await Promise.race([- transport(built.json, {- deadlineMs,- maxResponseBytes,- signal: transportController.signal- }),- cancelled,- new Promise((_, reject) => {- timer = setTimeout(() => {- reject(new EvaluatorPortError("DEADLINE_EXCEEDED"));- transportController.abort();- }, deadlineMs);- })- ]);- } catch (error) {- if (error instanceof EvaluatorPortError)- throw error;- throw new EvaluatorPortError("WORKER_FAILED");- } finally {- clearTimeout(timer);- if (abort)- signal?.removeEventListener("abort", abort);- }- if (signal?.aborted)- throw new EvaluatorPortError("CANCELLED");- if (typeof response !== "string")- throw new EvaluatorPortError("PROTOCOL_ERROR");- if (Buffer.byteLength(response, "utf8") > maxResponseBytes) {- throw new EvaluatorPortError("OUTPUT_LIMIT_EXCEEDED");- }- let result;- try {- result = decodeEvaluatorResultV1(response, maxGlbBytes, requestId);- } catch {- throw new EvaluatorPortError("PROTOCOL_ERROR");- }- if (!result.ok) {- if (result.error.code === "QA_BLOCKED" && result.error.qa) {- const { AssetQaBlockedError: AssetQaBlockedError2 } = await Promise.resolve().then(() => (init_run(), exports_run));- throw new AssetQaBlockedError2(result.error.qa.report, result.error.qa.stage, result.error.qa.gltfValidation);- }- throw new EvaluatorPortError(result.error.code, undefined, result.error.diagnostic);- }- return result.render;- }- };-}-var EVALUATOR_REQUEST_VERSION = "kiln.evaluator.request.v1", EVALUATOR_RESULT_VERSION = "kiln.evaluator.result.v1", MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_DEADLINE_MS = 60000, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV1;+var EVALUATOR_REQUEST_VERSION = "kiln.evaluator.request.v1", EVALUATOR_RESULT_VERSION = "kiln.evaluator.result.v1", MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV1;var init_protocol = __esm(() => {init_authoring_diagnostic();init_contracts();@@ -26404,8 +25180,8 @@ var init_protocol = __esm(() => {async render(code, options = {}, controls = {}) {if (controls.signal?.aborted)throw new EvaluatorPortError("CANCELLED");- const { renderGLBInProcess: renderGLBInProcess2 } = await Promise.resolve().then(() => (init_render(), exports_render));- const result = await renderGLBInProcess2(code, options);+ await Promise.resolve().then(() => init_render());+ const result = await renderGLBInProcess(code, options);if (controls.signal?.aborted)throw new EvaluatorPortError("CANCELLED");return result;@@ -26414,15 +25190,8 @@ var init_protocol = __esm(() => {});// src/evaluator/subprocess.ts-var exports_subprocess = {};-__export(exports_subprocess, {- sanitizedEvaluatorEnv: () => sanitizedEvaluatorEnv,- renderGLBViaSubprocess: () => renderGLBViaSubprocess,- renderGLBViaProcessLaunch: () => renderGLBViaProcessLaunch,- EvaluatorSubprocessError: () => EvaluatorSubprocessError-});-import { spawn as spawn2 } from "node:child_process";-import { fileURLToPath as fileURLToPath2 } from "node:url";+import { spawn } from "node:child_process";+import { fileURLToPath as fileURLToPath3 } from "node:url";function sanitizedEvaluatorEnv(source = process.env) {const env = { NODE_ENV: "production", NO_COLOR: "1" };for (const key of ["PATH", "Path", "SystemRoot", "SYSTEMROOT", "TEMP", "TMP", "TZ"]) {@@ -26432,11 +25201,11 @@ function sanitizedEvaluatorEnv(source = process.env) {return env;}function boundedInteger(value, fallback, max) {- const resolved2 = value ?? fallback;- if (!Number.isInteger(resolved2) || resolved2 < 1 || resolved2 > max) {+ const resolved = value ?? fallback;+ if (!Number.isInteger(resolved) || resolved < 1 || resolved > max) {throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator controls are invalid.");}- return resolved2;+ return resolved;}function terminateProcess(child, detached) {if (!child.pid || child.killed)@@ -26461,7 +25230,7 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launconst deadlineMs = boundedInteger(controls.deadlineMs, DEFAULT_DEADLINE_MS, 120000);const maxGlbBytes = boundedInteger(controls.maxGlbBytes, DEFAULT_MAX_GLB_BYTES, 64 * 1024 * 1024);const maxResponseBytes = boundedInteger(controls.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);- const request2 = {+ const request = {version: EVALUATOR_REQUEST_VERSION,requestId: "render-1",operation: "execute-export-glb",@@ -26469,12 +25238,12 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launoptions,limits: { maxGlbBytes }};- const requestJson = JSON.stringify(request2);+ const requestJson = JSON.stringify(request);if (Buffer.byteLength(requestJson, "utf8") > MAX_EVALUATOR_REQUEST_BYTES) {throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator request exceeds its size limit.");}const sourceModule = import.meta.url.endsWith(".ts");- const workerPath = fileURLToPath2(new URL(process.versions.bun && sourceModule ? "./worker.ts" : sourceModule ? "../../dist/evaluator-worker.mjs" : "./evaluator-worker.mjs", import.meta.url));+ const workerPath = fileURLToPath3(new URL(process.versions.bun && sourceModule ? "./worker.ts" : sourceModule ? "../../dist/evaluator-worker.mjs" : "./evaluator-worker.mjs", import.meta.url));const maxHeapMb = boundedInteger(controls.maxHeapMb, 512, 4096);if (maxHeapMb < 64 || process.versions.bun && controls.maxHeapMb !== undefined) {throw new EvaluatorSubprocessError("INPUT_INVALID", "Heap limits require a Node worker and 64–4096 MiB.");@@ -26493,7 +25262,7 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launstdio: ["pipe", "ignore", "pipe", "pipe"],...detached ? { detached: true } : {}};- const child = spawn2(resolvedLaunch.command, resolvedLaunch.args, spawnOptions);+ const child = spawn(resolvedLaunch.command, resolvedLaunch.args, spawnOptions);const protocol = child.stdio[3];if (!protocol) {terminateProcess(child, detached);@@ -26541,17 +25310,17 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launcontrols.signal?.addEventListener("abort", abort, { once: true });if (controls.signal?.aborted)abort();- protocol.on("data", (chunk2) => {- responseBytes += chunk2.byteLength;+ protocol.on("data", (chunk) => {+ responseBytes += chunk.byteLength;if (responseBytes > maxResponseBytes) {finish(new EvaluatorSubprocessError("OUTPUT_LIMIT_EXCEEDED", "Evaluator output limit exceeded."));terminateProcess(child, detached);return;}- chunks.push(Buffer.from(chunk2));+ chunks.push(Buffer.from(chunk));});- child.stderr?.on("data", (chunk2) => {- stderrBytes = Math.min(MAX_STDERR_BYTES, stderrBytes + chunk2.byteLength);+ child.stderr?.on("data", (chunk) => {+ stderrBytes = Math.min(MAX_STDERR_BYTES, stderrBytes + chunk.byteLength);});child.on("error", () => {finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker failed to start."));@@ -26611,14 +25380,14 @@ function assertProgramRef(ref) {throw new Error("Invalid program reference; use a p_ handle or full sha256 reference returned by Kiln.");}async function retainProgram(store, code) {- const canonical2 = await store.put(code);- return store.shortRef ? store.shortRef(canonical2) : canonical2;+ const canonical = await store.put(code);+ return store.shortRef ? store.shortRef(canonical) : canonical;}-function* shortProgramRefCandidates(canonical2) {- if (!canonicalProgramRefPattern.test(canonical2) || canonical2.length !== 71)+function* shortProgramRefCandidates(canonical) {+ if (!canonicalProgramRefPattern.test(canonical) || canonical.length !== 71)throw new Error("Invalid canonical program reference.");- for (let length3 = 12;length3 <= 64; length3 += 4)- yield `p_${canonical2.slice(7, 7 + length3)}`;+ for (let length = 12;length <= 64; length += 4)+ yield `p_${canonical.slice(7, 7 + length)}`;}async function programReference(code) {const bytes = new TextEncoder().encode(code);@@ -26660,8 +25429,8 @@ class MemoryProgramStore {}async get(ref) {assertProgramRef(ref);- const canonical2 = ref.startsWith("p_") ? this.handles.get(ref) : ref;- const code = canonical2 === undefined ? undefined : this.programs.get(canonical2);+ const canonical = ref.startsWith("p_") ? this.handles.get(ref) : ref;+ const code = canonical === undefined ? undefined : this.programs.get(canonical);if (code === undefined)throw new Error(`Program not found: ${ref}. Import the source into this store again.`);return code;@@ -26690,9 +25459,9 @@ var init_program_store = __esm(() => {});// src/program-store-node.ts-import { link, lstat, mkdir as mkdir2, readFile as readFile2, readdir, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";+import { link, lstat, mkdir as mkdir2, readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";import { randomUUID } from "node:crypto";-import { join as join3, resolve } from "node:path";+import { join as join2, resolve as resolve2 } from "node:path";class FileProgramStore {directory;@@ -26707,7 +25476,7 @@ class FileProgramStore {if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))continue;try {- bytes += (await stat(join3(this.directory, entry.name))).size;+ bytes += (await stat(join2(this.directory, entry.name))).size;entries++;} catch (error) {if (error.code !== "ENOENT")@@ -26722,21 +25491,21 @@ class FileProgramStore {}async get(ref) {assertProgramRef(ref);- const canonical2 = ref.startsWith("p_") ? await this.readHandle(ref) : ref;- if (canonical2 === undefined)+ const canonical = ref.startsWith("p_") ? await this.readHandle(ref) : ref;+ if (canonical === undefined)throw this.notFound(ref);- const path = join3(this.directory, `${canonical2.slice(7)}.js`);+ const path = join2(this.directory, `${canonical.slice(7)}.js`);let code;try {if ((await stat(path)).size > MAX_PROGRAM_BYTES)throw new Error("Stored program exceeds the 1 MiB source limit.");- code = await readFile2(path, "utf8");+ code = await readFile(path, "utf8");} catch (error) {if (error.code === "ENOENT")throw this.notFound(ref);throw error;}- if (await programReference(code) !== canonical2)+ if (await programReference(code) !== canonical)throw new Error(`Program integrity check failed: ${ref}`);return code;}@@ -26744,15 +25513,15 @@ class FileProgramStore {return new Error(`Program not found: ${ref}. Use the same KILN_PROGRAM_STORE or import the source again.`);}async readHandle(handle) {- const path = join3(this.directory, "refs", `${handle}.ref`);+ const path = join2(this.directory, "refs", `${handle}.ref`);try {const info = await lstat(path);if (!info.isFile() || info.size !== 71)throw new Error(`Program handle integrity check failed: ${handle}`);- const canonical2 = await readFile2(path, "utf8");- if (!canonicalProgramRefPattern.test(canonical2) || !canonical2.slice(7).startsWith(handle.slice(2)))+ const canonical = await readFile(path, "utf8");+ if (!canonicalProgramRefPattern.test(canonical) || !canonical.slice(7).startsWith(handle.slice(2)))throw new Error(`Program handle integrity check failed: ${handle}`);- return canonical2;+ return canonical;} catch (error) {if (error.code === "ENOENT")return;@@ -26763,7 +25532,7 @@ class FileProgramStore {await this.get(ref);if (ref.startsWith("p_"))return ref;- const directory = join3(this.directory, "refs");+ const directory = join2(this.directory, "refs");await mkdir2(directory, { recursive: true });for (const handle of shortProgramRefCandidates(ref)) {const owner = await this.readHandle(handle);@@ -26771,11 +25540,11 @@ class FileProgramStore {return handle;if (owner !== undefined)continue;- const temporary = join3(directory, `.write-${randomUUID()}`);- await writeFile2(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });+ const temporary = join2(directory, `.write-${randomUUID()}`);+ await writeFile(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link(temporary, join3(directory, `${handle}.ref`));+ await link(temporary, join2(directory, `${handle}.ref`));return handle;} catch (error) {if (error.code !== "EEXIST")@@ -26792,9 +25561,9 @@ class FileProgramStore {async put(code) {const ref = await programReference(code);await mkdir2(this.directory, { recursive: true });- const target = join3(this.directory, `${ref.slice(7)}.js`);- const temporary = join3(this.directory, `.write-${randomUUID()}`);- await writeFile2(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });+ const target = join2(this.directory, `${ref.slice(7)}.js`);+ const temporary = join2(this.directory, `.write-${randomUUID()}`);+ await writeFile(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });try {try {await link(temporary, target);@@ -26810,14 +25579,14 @@ class FileProgramStore {}}function localProgramStore() {- return new FileProgramStore(resolve(process.env["KILN_PROGRAM_STORE"] ?? ".kiln/programs"));+ return new FileProgramStore(resolve2(process.env["KILN_PROGRAM_STORE"] ?? ".kiln/programs"));}var init_program_store_node = __esm(() => {init_program_store();});// src/build-cache.ts-import { createHash as createHash7 } from "node:crypto";+import { createHash as createHash6 } from "node:crypto";import * as acorn2 from "acorn";import * as walk2 from "acorn-walk";function sourceHasAmbientInputs(code) {@@ -26937,7 +25706,7 @@ function createCachedEvaluatorPort(evaluator, options) {} catch {return evaluator.render(code, renderOptions, controls);}- const key = `sha256:${createHash7("sha256").update(serialized).digest("hex")}`;+ const key = `sha256:${createHash6("sha256").update(serialized).digest("hex")}`;const cached = await options.cache.get(key).catch(() => {return;});@@ -26981,32 +25750,32 @@ var init_build_cache = __esm(() => {});// src/build-cache-node.ts-import { createHash as createHash8, randomUUID as randomUUID2 } from "node:crypto";+import { createHash as createHash7, randomUUID as randomUUID2 } from "node:crypto";import {mkdir as mkdir3,- readFile as readFile3,+ readFile as readFile2,readdir as readdir2,rename,stat as stat2,unlink as unlink2,utimes,- writeFile as writeFile3+ writeFile as writeFile2} from "node:fs/promises";-import { join as join4, resolve as resolve2 } from "node:path";+import { join as join3, resolve as resolve3 } from "node:path";class FileBuildCache {maxBytes;directory;constructor(directory, maxBytes = 128 * 1024 * 1024) {this.maxBytes = maxBytes;- this.directory = resolve2(directory);+ this.directory = resolve3(directory);if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 1024 * 1024 * 1024)throw new Error("File build cache size must be 0..1 GiB.");}path(key) {if (!keyPattern.test(key))throw new Error("Invalid build cache key.");- return join4(this.directory, `${key.slice(7)}.json`);+ return join3(this.directory, `${key.slice(7)}.json`);}async get(key) {const path = this.path(key);@@ -27014,7 +25783,7 @@ class FileBuildCache {const entry = await stat2(path);if (entry.size > this.maxBytes || entry.size > 96 * 1024 * 1024)return;- const envelope = JSON.parse(await readFile3(path, "utf8"));+ const envelope = JSON.parse(await readFile2(path, "utf8"));if (envelope.version !== 1 || envelope.key !== key || typeof envelope.payload !== "string" || envelope.checksum !== digest2(envelope.payload))return;const decoded = decodeEvaluatorResultV1(envelope.payload, 64 * 1024 * 1024);@@ -27034,8 +25803,8 @@ class FileBuildCache {if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))return;await mkdir3(this.directory, { recursive: true });- const temporary = join4(this.directory, `.write-${randomUUID2()}`);- await writeFile3(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });+ const temporary = join3(this.directory, `.write-${randomUUID2()}`);+ await writeFile2(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });try {await rename(temporary, path);} finally {@@ -27048,7 +25817,7 @@ class FileBuildCache {for (const name of await readdir2(this.directory)) {if (!filePattern.test(name))continue;- const path = join4(this.directory, name);+ const path = join3(this.directory, name);try {const item = await stat2(path);entries.push({ path, size: item.size, used: item.mtimeMs });@@ -27064,7 +25833,7 @@ class FileBuildCache {}}}-var keyPattern, filePattern, digest2 = (text2) => createHash8("sha256").update(text2).digest("hex");+var keyPattern, filePattern, digest2 = (text) => createHash7("sha256").update(text).digest("hex");var init_build_cache_node = __esm(() => {init_protocol();keyPattern = /^sha256:[a-f0-9]{64}$/;@@ -27072,21 +25841,21 @@ var init_build_cache_node = __esm(() => {});// src/runtime-identity.ts-import { createHash as createHash9 } from "node:crypto";-import { readFile as readFile4, readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";-import { createRequire as createRequire2 } from "node:module";-import { dirname as dirname2, join as join5, relative } from "node:path";+import { createHash as createHash8 } from "node:crypto";+import { readFile as readFile3, readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";+import { createRequire } from "node:module";+import { dirname as dirname2, join as join4, relative } from "node:path";async function installedRuntimeIdentity(root, limits = {}) {let bytes = 0;let files = 0;const maxBytes = limits.maxBytes ?? 512 * 1024 * 1024;const maxFiles = limits.maxFiles ?? 40000;- const manifest = async (directory) => JSON.parse(await readFile4(join5(directory, "package.json"), "utf8"));+ const manifest = async (directory) => JSON.parse(await readFile3(join4(directory, "package.json"), "utf8"));let readers = 0;const waiting = [];const read = async (path) => {if (readers >= 24)- await new Promise((resolve3) => waiting.push(resolve3));+ await new Promise((resolve) => waiting.push(resolve));elsereaders++;try {@@ -27094,7 +25863,7 @@ async function installedRuntimeIdentity(root, limits = {}) {if (++files > maxFiles || bytes + info.size > maxBytes)throw new Error("Installed runtime fingerprint exceeds its scan budget.");bytes += info.size;- return await readFile4(path);+ return await readFile3(path);} finally {const next = waiting.shift();if (next)@@ -27107,17 +25876,17 @@ async function installedRuntimeIdentity(root, limits = {}) {const pkg = await manifest(root);if (pkg.name !== "@kiln/engine")throw new Error("Not a Kiln installation.");- const build = JSON.parse(await readFile4(join5(root, "dist", "build.json"), "utf8"));+ const build = JSON.parse(await readFile3(join4(root, "dist", "build.json"), "utf8"));const worker = build.entries?.worker;if (build.schemaVersion !== 1 || worker?.file !== "evaluator-worker.mjs" || !/^sha256:[a-f0-9]{64}$/.test(worker.identity))throw new Error("No valid packaged worker identity.");- const workerHash = `sha256:${digest3(await read(join5(root, "dist", worker.file)))}`;+ const workerHash = `sha256:${digest3(await read(join4(root, "dist", worker.file)))}`;if (worker.bundleHash !== workerHash)throw new Error("Packaged worker differs from its build manifest.");const records = [];const visited = new Map;async function resolvePackage(parent, name) {- const require2 = createRequire2(join5(parent, "package.json"));+ const require2 = createRequire(join4(parent, "package.json"));let found;try {found = require2.resolve(`${name}/package.json`);@@ -27126,7 +25895,7 @@ async function installedRuntimeIdentity(root, limits = {}) {found = require2.resolve(name);} catch {for (const modules of require2.resolve.paths(name) ?? []) {- const candidate = join5(modules, name);+ const candidate = join4(modules, name);try {if ((await manifest(candidate)).name === name)return await realpath(candidate);@@ -27152,7 +25921,7 @@ async function installedRuntimeIdentity(root, limits = {}) {return (await Promise.all(entries.map(async (entry) => {if (entry.name === "node_modules" || entry.name === ".git")return [];- const path = join5(directory, entry.name);+ const path = join4(directory, entry.name);if (entry.isSymbolicLink())throw new Error("Dependency contains an untracked internal symlink.");if (entry.isDirectory())@@ -27163,16 +25932,16 @@ async function installedRuntimeIdentity(root, limits = {}) {}))).flat();}async function visit(directory, path) {- const canonical3 = await realpath(directory);- const previous = visited.get(canonical3);+ const canonical = await realpath(directory);+ const previous = visited.get(canonical);if (previous) {records.push([path, `same-package:${previous}`]);return;}- visited.set(canonical3, path);- const metadata = await manifest(canonical3);- records.push([path, digest3(JSON.stringify(await tree(canonical3, canonical3)))]);- await dependencies(canonical3, metadata, path);+ visited.set(canonical, path);+ const metadata = await manifest(canonical);+ records.push([path, digest3(JSON.stringify(await tree(canonical, canonical)))]);+ await dependencies(canonical, metadata, path);}async function dependencies(directory, metadata, prefix) {const names = [@@ -27216,12 +25985,12 @@ async function installedRuntimeIdentity(root, limits = {}) {return { reason: error instanceof Error ? error.message : String(error), files, bytes };}}-var digest3 = (bytes) => createHash9("sha256").update(bytes).digest("hex"), compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;+var digest3 = (bytes) => createHash8("sha256").update(bytes).digest("hex"), compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;var init_runtime_identity = () => {};// src/local-runtime.ts-import { dirname as dirname3, join as join6, resolve as resolve3 } from "node:path";-import { fileURLToPath as fileURLToPath3 } from "node:url";+import { dirname as dirname3, join as join5, resolve as resolve4 } from "node:path";+import { fileURLToPath as fileURLToPath4 } from "node:url";function integer2(env, name, fallback, min, max) {const value = env[name] === undefined ? fallback : Number(env[name]);if (!Number.isInteger(value) || value < min || value > max)@@ -27244,35 +26013,35 @@ function createLocalToolContext(base = {}, env = process.env) {throw new Error("KILN_QA_MODE overrides are not transported to the local worker. Remove the override or explicitly select trusted KILN_EVALUATOR_MODE=in-process.");}const optimize = ["auto", "palette", "full"].includes(env.KILN_BAKE_OPTIMIZE ?? "") ? env.KILN_BAKE_OPTIMIZE : "off";- const instance2 = ["off", "auto", "on"].includes(env.KILN_BAKE_INSTANCE ?? "") ? env.KILN_BAKE_INSTANCE : "auto";+ const instance = ["off", "auto", "on"].includes(env.KILN_BAKE_INSTANCE ?? "") ? env.KILN_BAKE_INSTANCE : "auto";const maxGlbBytes = 16 * 1024 * 1024;const maxResponseBytes = 32 * 1024 * 1024;const evaluatorPort = {async render(code, options = {}, controls = {}) {if (controls.signal?.aborted) {- const { EvaluatorPortError: EvaluatorPortError2 } = await Promise.resolve().then(() => (init_protocol(), exports_protocol));- throw new EvaluatorPortError2("CANCELLED");+ await Promise.resolve().then(() => init_protocol());+ throw new EvaluatorPortError("CANCELLED");}if (options.geometryPolicy !== undefined && !["warn", "strict"].includes(options.geometryPolicy))throw new Error("geometryPolicy must be warn or strict");- const resolved2 = {+ const resolved = {optimize,- instance: instance2,+ instance,...options,geometryPolicy: geometryPolicy === "strict" ? "strict" : options.geometryPolicy ?? "warn"};if (mode === "in-process") {- const result = await renderGLBInProcess(code, resolved2);+ const result = await renderGLBInProcess(code, resolved);if (controls.signal?.aborted) {- const { EvaluatorPortError: EvaluatorPortError2 } = await Promise.resolve().then(() => (init_protocol(), exports_protocol));- throw new EvaluatorPortError2("CANCELLED");+ await Promise.resolve().then(() => init_protocol());+ throw new EvaluatorPortError("CANCELLED");}return result;}const limits = { deadlineMs, maxGlbBytes, maxResponseBytes, ...controls };if (mode === "isolated")- return renderGLBViaIsolatedEvaluator(code, resolved2, limits);- return renderGLBViaSubprocess(code, resolved2, {+ return renderGLBViaIsolatedEvaluator(code, resolved, limits);+ return renderGLBViaSubprocess(code, resolved, {...limits,...!process.versions.bun ? { maxHeapMb: heapMb } : {}});@@ -27290,27 +26059,27 @@ function createLocalToolContext(base = {}, env = process.env) {return {...base,geometryPolicy,- programStore: base.programStore ?? new FileProgramStore(resolve3(env.KILN_PROGRAM_STORE ?? ".kiln/programs")),+ programStore: base.programStore ?? new FileProgramStore(resolve4(env.KILN_PROGRAM_STORE ?? ".kiln/programs")),evaluatorPort,assetBuildOptions: {optimize,- instance: instance2,+ instance,geometryPolicy,qaMode: env.KILN_QA_MODE ?? "enforce",evaluatorMode: mode},buildCache: new MemoryBuildCache,- evaluatorCacheIdentity: `kiln-local-${process.pid}-${++scope}:${JSON.stringify({ mode, optimize, instance: instance2, geometryPolicy, qa: env.KILN_QA_MODE, deadlineMs, heapMb })}`,+ evaluatorCacheIdentity: `kiln-local-${process.pid}-${++scope}:${JSON.stringify({ mode, optimize, instance, geometryPolicy, qa: env.KILN_QA_MODE, deadlineMs, heapMb })}`,localExecution};}-async function createPackagedLocalToolContext(base = {}, env = process.env, installationRoot = fileURLToPath3(new URL("../", import.meta.url))) {+async function createPackagedLocalToolContext(base = {}, env = process.env, installationRoot = fileURLToPath4(new URL("../", import.meta.url))) {const context = createLocalToolContext(base, env);const managed = () => {- const identity2 = context.evaluatorCacheIdentity;+ const identity = context.evaluatorCacheIdentity;const cached = createCachedEvaluatorPort(context.evaluatorPort, {cache: context.buildCache,- identity: () => typeof identity2 === "function" ? identity2() : identity2+ identity: () => typeof identity === "function" ? identity() : identity});context.evaluatorPort = {render: (code, options, controls) => cached.render(code, {@@ -27342,7 +26111,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst}const cacheBytes = integer2(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;const store = context.programStore;- const directory = resolve3(env.KILN_BUILD_CACHE_DIR ?? join6(store instanceof FileProgramStore ? dirname3(store.directory) : ".kiln", "cache", "builds"));+ const directory = resolve4(env.KILN_BUILD_CACHE_DIR ?? join5(store instanceof FileProgramStore ? dirname3(store.directory) : ".kiln", "cache", "builds"));context.buildCache = new FileBuildCache(directory, cacheBytes);context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({execution: context.localExecution,@@ -27374,22 +26143,22 @@ var init_local_runtime = __esm(() => {// src/assets.tsimport { z } from "zod";import { zipSync, unzipSync } from "three/addons/libs/fflate.module.js";-function validateRecordShape(record5) {- const manifest = assetManifestSchema.parse(record5.manifest);- const names = Object.keys(record5.files);+function validateRecordShape(record) {+ const manifest = assetManifestSchema.parse(record.manifest);+ const names = Object.keys(record.files);if (names.length !== Object.keys(manifest.files).length || !names.includes("asset.glb"))throw new Error("Asset file inventory mismatch");let total = 0;for (const name of names) {- if (!allowedFiles.has(name) || !manifest.files[name] || manifest.files[name].bytes !== record5.files[name].length)+ if (!allowedFiles.has(name) || !manifest.files[name] || manifest.files[name].bytes !== record.files[name].length)throw new Error("Invalid asset file inventory");- total += record5.files[name].length;+ total += record.files[name].length;}if (total > ASSET_LIMIT || manifest.editable !== names.includes("source.kiln.js"))throw new Error("Invalid asset size or source inventory");- if ((record5.files["source.kiln.js"]?.length ?? 0) > 1024 * 1024)+ if ((record.files["source.kiln.js"]?.length ?? 0) > 1024 * 1024)throw new Error("Source exceeds 1 MiB");- validateAssetGlb(record5.files["asset.glb"]);+ validateAssetGlb(record.files["asset.glb"]);}function validateAssetGlb(bytes) {if (bytes.length < 20 || bytes.length > ASSET_LIMIT)@@ -27411,13 +26180,13 @@ function encodeAssetBundle(records) {throw new Error("Bundle requires 1..100 revisions");const files = {};let total = 0;- for (const record5 of records) {- validateRecordShape(record5);- const prefix = `${record5.manifest.assetId}/${record5.manifest.revisionId}/`;+ for (const record of records) {+ validateRecordShape(record);+ const prefix = `${record.manifest.assetId}/${record.manifest.revisionId}/`;if (files[`${prefix}manifest.json`])throw new Error("Duplicate bundle revision");- files[`${prefix}manifest.json`] = new TextEncoder().encode(JSON.stringify(record5.manifest, null, 2));- for (const [name, bytes] of Object.entries(record5.files))+ files[`${prefix}manifest.json`] = new TextEncoder().encode(JSON.stringify(record.manifest, null, 2));+ for (const [name, bytes] of Object.entries(record.files))files[prefix + name] = bytes;}for (const bytes of Object.values(files))@@ -27451,16 +26220,16 @@ function decodeAssetBundle(bytes) {const prefix = `${manifest.assetId}/${manifest.revisionId}/`;if (path !== `${prefix}manifest.json`)throw new Error("Bundle identity mismatch");- const record5 = { manifest, files: {} };+ const record = { manifest, files: {} };used.add(path);for (const name of Object.keys(manifest.files)) {if (!files[prefix + name])throw new Error("Bundle file missing");- record5.files[name] = files[prefix + name];+ record.files[name] = files[prefix + name];used.add(prefix + name);}- validateRecordShape(record5);- records.push(record5);+ validateRecordShape(record);+ records.push(record);}if (!records.length || used.size !== Object.keys(files).length)throw new Error("Incomplete asset bundle");@@ -27674,13 +26443,13 @@ Note: ${entry.promptNotes}` : ""}`;const unknown = requested.filter((_, index) => !selected[index]);if (unknown.length)return missing(`Unknown helpers: ${unknown.join(", ")}.`);- const primitives2 = selected.filter((entry) => Boolean(entry));+ const primitives = selected.filter((entry) => Boolean(entry));return {- primitives: primitives2,- total: primitives2.length,+ primitives,+ total: primitives.length,nextOffset: null,categories,- text: [`${primitives2.length} requested helpers.`, ...primitives2.map(detail)].join(`+ text: [`${primitives.length} requested helpers.`, ...primitives.map(detail)].join(``)};@@ -27700,7 +26469,7 @@ Note: ${entry.promptNotes}` : ""}`;return missing(`No helper matches ${input.name ? `name "${input.name}"` : `query "${input.query ?? input.category}"`}.`);const overview = input.overview ?? !(input.name || input.query || input.category || input.offset || input.limit);if (overview) {- const text3 = [+ const text = ['Kiln helper overview. Use {names:["boxGeo","createPart"]} for up to six signatures/examples together, {name:"boxGeo"} for one, {query:"holes"} for an operation, or {category:"geometry"} to browse.',...categories.map((group) => `${group}: ${matches.filter((entry) => entry.category === group).map((entry) => entry.name).join(", ")}`).filter((line) => !line.endsWith(": ")),"Custom geometry: THREE.BufferGeometry, indexed triangles and ordinary functions are available. GLB exports position, normal, UV0, tangent, indices and material groups. Query meshGeo, parametricSurface, sweepProfile, loftProfiles or twist for focused examples.",@@ -27717,20 +26486,20 @@ Note: ${entry.promptNotes}` : ""}`;nextOffset: null,categories,capabilities,- text: text3+ text};}const offset = input.offset ?? 0;const primitives = matches.slice(offset, offset + (input.limit ?? 6));const nextOffset = offset + primitives.length < matches.length ? offset + primitives.length : null;- const text2 = [+ const text = [`${matches.length} matching helpers. Showing ${primitives.length ? offset + 1 : 0}–${offset + primitives.length}.`,...primitives.map(detail),...nextOffset === null ? [] : [`More results: repeat this query with offset:${nextOffset}.`]].join(``);- return { primitives, total: matches.length, nextOffset, categories, text: text2 };+ return { primitives, total: matches.length, nextOffset, categories, text };},text: (output) => output.text};@@ -27820,9 +26589,9 @@ function diffLines(a, b) {const n = a.length;const m = b.length;const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));- for (let i2 = n - 1;i2 >= 0; i2--) {- for (let j2 = m - 1;j2 >= 0; j2--) {- lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);+ for (let i = n - 1;i >= 0; i--) {+ for (let j = m - 1;j >= 0; j--) {+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);}}const ops = [];@@ -27959,20 +26728,20 @@ function resolveViewRenderTimeoutMs(input) {...remainingGenerationBudgetMs !== undefined ? { remainingGenerationBudgetMs } : {},...rendererDeadlineMs !== undefined ? { rendererDeadlineMs } : {}});- let resolved2 = timeoutMs;+ let resolved = timeoutMs;if (input.resolver && hostContextAvailable) {try {- resolved2 = boundedTimeout(input.resolver(resolverContext), timeoutMs);+ resolved = boundedTimeout(input.resolver(resolverContext), timeoutMs);} catch {- resolved2 = timeoutMs;+ resolved = timeoutMs;}}if (rendererDeadlineMs !== undefined)- resolved2 = Math.min(resolved2, rendererDeadlineMs);+ resolved = Math.min(resolved, rendererDeadlineMs);if (remainingGenerationBudgetMs !== undefined) {- resolved2 = Math.min(resolved2, remainingGenerationBudgetMs);+ resolved = Math.min(resolved, remainingGenerationBudgetMs);}- return boundedTimeout(resolved2, timeoutMs);+ return boundedTimeout(resolved, timeoutMs);}var MIN_VIEW_RENDER_TIMEOUT_MS = 1, MAX_VIEW_RENDER_TIMEOUT_MS = 120000, WARM_UP_STATES;var init_view_render_timeout = __esm(() => {@@ -27980,18 +26749,11 @@ var init_view_render_timeout = __esm(() => {});// src/views/port.ts-var exports_port = {};-__export(exports_port, {- sha256Bytes: () => sha256Bytes,- captureViewsViaPort: () => captureViewsViaPort,- captureViewPngsViaPort: () => captureViewPngsViaPort,- DEFAULT_VIEW_RENDER_TIMEOUT_MS: () => DEFAULT_VIEW_RENDER_TIMEOUT_MS-});async function sha256Bytes(bytes) {const input = new Uint8Array(bytes.byteLength);input.set(bytes);- const digest4 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", input));- return `sha256:${[...digest4].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", input));+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;}async function captureViewPngsViaPort(port, glb, timeoutMs, viewDirs, size, cameras, limits) {let timer;@@ -28070,38 +26832,38 @@ async function captureViewPngsViaPort(port, glb, timeoutMs, viewDirs, size, cameasync function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIMEOUT_MS, capture, limits) {if (capture?.shots || capture?.version) {try {- const { loadGlbReviewScene: loadGlbReviewScene2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const { renderCaptureGrid: renderCaptureGrid2 } = await Promise.resolve().then(() => (init_camera_capture(), exports_camera_capture));- const { renderSceneToGLB: renderSceneToGLB2 } = await Promise.resolve().then(() => (init_render(), exports_render));- const loaded = await loadGlbReviewScene2(Uint8Array.from(glb));+ await Promise.resolve().then(() => init_views());+ await Promise.resolve().then(() => init_camera_capture());+ await Promise.resolve().then(() => init_render());+ const loaded = await loadGlbReviewScene(Uint8Array.from(glb));let rendererId = "";- const grid = await renderCaptureGrid2(loaded.root, capture, async (input) => {- const derivative = await renderSceneToGLB2(input.root, {+ const grid = await renderCaptureGrid(loaded.root, capture, async (input) => {+ const derivative = await renderSceneToGLB(input.root, {derivative: true});- const result2 = await captureViewPngsViaPort(port, derivative.bytes, timeoutMs, [input.view.dir], input.size, [input.camera], limits);- if (!result2.ok)- throw new Error(result2.reason);- if (!result2.derivativeFidelityAttested || !result2.inputGlbSha256)+ const result = await captureViewPngsViaPort(port, derivative.bytes, timeoutMs, [input.view.dir], input.size, [input.camera], limits);+ if (!result.ok)+ throw new Error(result.reason);+ if (!result.derivativeFidelityAttested || !result.inputGlbSha256)throw new Error("advanced capture requires derivative material receipt");- if (rendererId && rendererId !== result2.rendererId)+ if (rendererId && rendererId !== result.rendererId)throw new Error("capture renderer changed between cells");- rendererId = result2.rendererId;+ rendererId = result.rendererId;return {- png: Buffer.from(result2.pngs[0]),+ png: Buffer.from(result.pngs[0]),receipt: {version: "kiln.view-fidelity.v1",derivativeLabel: input.label,requested: "full-preferred",delivered: "full-material",exactArtifact: false,- rendererId: result2.rendererId,+ rendererId: result.rendererId,materialFaithful: true,degraded: false,- inputGlbSha256: result2.inputGlbSha256,+ inputGlbSha256: result.inputGlbSha256,camera: input.camera,cameraFidelity: "echo-validated",- ...result2.captureCache ? { captureCache: result2.captureCache } : {}+ ...result.captureCache ? { captureCache: result.captureCache } : {}}};}, limits);@@ -28121,22 +26883,22 @@ async function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIreturn { ok: false, reason: error instanceof Error ? error.message : String(error) };}}- let resolved2;+ let resolved;try {- resolved2 = resolveGridCapture(capture, process.env["KILN_GRID_VARIANT"]);- enforceCapturePixels(resolved2.views.length, 384, resolved2.cols, limits);+ resolved = resolveGridCapture(capture, process.env["KILN_GRID_VARIANT"]);+ enforceCapturePixels(resolved.views.length, 384, resolved.cols, limits);} catch (err) {return { ok: false, reason: err instanceof Error ? err.message : String(err) };}- const views = resolved2.views;- const shape = { preset: resolved2.preset, cols: resolved2.cols, cells: views.length };+ const views = resolved.views;+ const shape = { preset: resolved.preset, cols: resolved.cols, cells: views.length };let cameras;- if (resolved2.zooms.some((z4) => z4 !== undefined)) {+ if (resolved.zooms.some((z) => z !== undefined)) {try {- const { loadGlbReviewScene: loadGlbReviewScene2, measureBounds: measureBounds2, cameraFromBounds: cameraFromBounds2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const loaded = await loadGlbReviewScene2(Uint8Array.from(glb));- const bounds = measureBounds2(loaded.root);- cameras = views.map((view, i) => cameraFromBounds2(bounds, view.dir, resolved2.zooms[i] ?? 1));+ await Promise.resolve().then(() => init_views());+ const loaded = await loadGlbReviewScene(Uint8Array.from(glb));+ const bounds = measureBounds(loaded.root);+ cameras = views.map((view, i) => cameraFromBounds(bounds, view.dir, resolved.zooms[i] ?? 1));} catch (error) {return { ok: false, reason: error instanceof Error ? error.message : String(error) };}@@ -28145,7 +26907,7 @@ async function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIif (!result.ok)return result;try {- const grid = compositeViewPngGrid(result.pngs, resolved2.cols, views);+ const grid = compositeViewPngGrid(result.pngs, resolved.cols, views);enforceCaptureBytes([grid.png], limits);return {ok: true,@@ -28170,18 +26932,6 @@ var init_port = __esm(() => {});// src/views/inspect.ts-var exports_inspect = {};-__export(exports_inspect, {- renderInspectView: () => renderInspectView,- prepareInspectView: () => prepareInspectView,- listPartNames: () => listPartNames,- INSPECT_SIZE: () => INSPECT_SIZE,- INSPECT_MIN_ZOOM: () => INSPECT_MIN_ZOOM,- INSPECT_MAX_ZOOM: () => INSPECT_MAX_ZOOM,- INSPECT_MAX_PART_NAMES: () => INSPECT_MAX_PART_NAMES,- INSPECT_DEFAULT_ZOOM: () => INSPECT_DEFAULT_ZOOM,- INSPECT_CAMERAS: () => INSPECT_CAMERAS-});function listPartNames(root, cap = INSPECT_MAX_PART_NAMES) {const names = [];const seen = new Set;@@ -28293,27 +27043,6 @@ function prepareInspectView(root, opts = {}) {frameBounds: expandBounds2(bounds, zoom)};}-function renderInspectView(root, opts = {}) {- const prepared = prepareInspectView(root, opts);- if (!prepared.ok)- return prepared;- const rgb2 = rasterizeView(prepared.root, prepared.viewSpec.dir, {- size: prepared.size,- frameBounds: prepared.frameBounds- });- return {- ok: true,- ...prepared.part ? { part: prepared.part } : {},- view: prepared.view,- azimuthDeg: prepared.azimuthDeg,- elevationDeg: prepared.elevationDeg,- zoom: prepared.zoom,- isolated: prepared.isolated,- width: prepared.size,- height: prepared.size,- png: encodePng(rgb2, prepared.size, prepared.size)- };-}var INSPECT_SIZE = 512, INSPECT_DEFAULT_ZOOM = 1.2, INSPECT_MIN_ZOOM = 1, INSPECT_MAX_ZOOM = 4, INSPECT_MAX_PART_NAMES = 40, INSPECT_CAMERAS;var init_inspect = __esm(() => {init_raster();@@ -28329,11 +27058,6 @@ var init_inspect = __esm(() => {});// src/views/measurement.ts-var exports_measurement = {};-__export(exports_measurement, {- measureAttachment: () => measureAttachment,- describeSubjectFrame: () => describeSubjectFrame-});import { Box3 as Box316, Vector3 as Vector330 } from "three";function describeSubjectFrame(root, subject) {const selected = selectCameraSubject(root, subject);@@ -28368,9 +27092,9 @@ function describeSubjectFrame(root, subject) {};}function measureAttachment(root, input) {- const endpoint = (request2) => {- const selected = selectCameraSubject(root, request2.subject);- const local = request2.point ?? [0, 0, 0];+ const endpoint = (request) => {+ const selected = selectCameraSubject(root, request.subject);+ const local = request.point ?? [0, 0, 0];if (local.length !== 3 || local.some((n) => !Number.isFinite(n)))throw new Error("attachment point must be three finite subject-local coordinates");selected.node.updateWorldMatrix(true, false);@@ -28397,9 +27121,8 @@ var init_measurement = __esm(() => {// src/assets-resources.tsvar exports_assets_resources = {};__export(exports_assets_resources, {- readAssetResource: () => readAssetResource,- assetMime: () => assetMime,- assetLinks: () => assetLinks+ assetLinks: () => assetLinks,+ readAssetResource: () => readAssetResource});function assetLinks(collection, manifest) {return [...Object.keys(manifest.files), "manifest.json", "editable.zip"].map((name) => ({@@ -28417,11 +27140,11 @@ async function readAssetResource(library, uri) {if (!match)throw new Error("Unknown asset resource");const collection = match[1];- const asset2 = match[2];+ const asset = match[2];const revision = match[3];const name = match[4];- const record5 = await library.read(collection, asset2, revision);- const bytes = name === "editable.zip" ? encodeAssetBundle([record5]) : name === "manifest.json" ? new TextEncoder().encode(JSON.stringify(record5.manifest, null, 2)) : record5.files[name];+ const record = await library.read(collection, asset, revision);+ const bytes = name === "editable.zip" ? encodeAssetBundle([record]) : name === "manifest.json" ? new TextEncoder().encode(JSON.stringify(record.manifest, null, 2)) : record.files[name];if (!bytes)throw new Error("Asset file unavailable");return { bytes, mimeType: assetMime(name), name };@@ -28462,13 +27185,11 @@ var init_widget_transfer = __esm(() => {// src/asset-widget.tsvar exports_asset_widget = {};__export(exports_asset_widget, {- readAssetWidgetHtml: () => readAssetWidgetHtml,assetWidgetData: () => assetWidgetData});-import { readFile as readFile5 } from "node:fs/promises";async function assetWidgetData(library, selector) {- const record5 = await library.read(selector.collection, selector.asset.assetId, selector.asset.revisionId);- if (Object.values(record5.files).reduce((sum, bytes) => sum + bytes.length, 0) > WIDGET_TRANSFER_LIMIT)+ const record = await library.read(selector.collection, selector.asset.assetId, selector.asset.revisionId);+ if (Object.values(record.files).reduce((sum, bytes) => sum + bytes.length, 0) > WIDGET_TRANSFER_LIMIT)return {kilnAsset: {error: "This asset exceeds the 16 MiB chat preview limit. Open it with kiln view."@@ -28476,15 +27197,12 @@ async function assetWidgetData(library, selector) {};return {kilnAsset: {- manifest: record5.manifest,+ manifest: record.manifest,downloadUrls: selector.downloadUrls,- files: encodeWidgetFiles(record5.files)+ files: encodeWidgetFiles(record.files)}};}-async function readAssetWidgetHtml() {- return readFile5(new URL("../dist/viewer/chat.html", import.meta.url), "utf8");-}var init_asset_widget = __esm(() => {init_widget_transfer();});@@ -28497,8 +27215,8 @@ function proceduralTextureMaterialContract(rendered, context) {if (required.length === 0)return;const available = new Set((rendered.bakedTextures ?? []).map((entry) => entry.usage));- const present = required.filter((usage2) => available.has(usage2));- const missing = required.filter((usage2) => !available.has(usage2));+ const present = required.filter((usage) => available.has(usage));+ const missing = required.filter((usage) => !available.has(usage));return { required, present, missing };}function missingProceduralTextureResult(rendered, context) {@@ -28536,8 +27254,8 @@ async function evaluateGeneratedSource(code, context, optimize = "off") {}async function loadEvaluatedReviewScene(code, context) {const rendered = await evaluateGeneratedSource(code, context);- const { loadGlbReviewScene: loadGlbReviewScene2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const scene = await loadGlbReviewScene2(rendered.glb);+ await Promise.resolve().then(() => init_views());+ const scene = await loadGlbReviewScene(rendered.glb);return { rendered, ...scene };}function withViewEvidenceHistory(context) {@@ -28551,8 +27269,8 @@ function withViewEvidenceHistory(context) {return { ...context, viewEvidenceHistory: history };}async function sha256Glb(bytes) {- const digest4 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));- return `sha256:${[...digest4].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;}async function renderDerivativeCell(input, context) {let derivativeRoot = input.root;@@ -28563,9 +27281,9 @@ async function renderDerivativeCell(input, context) {if (!mesh.isMesh)return;const prepare = (material) => {- const copy2 = material.clone();- copy2.side = THREE35.DoubleSide;- return copy2;+ const copy = material.clone();+ copy.side = THREE35.DoubleSide;+ return copy;};mesh.material = Array.isArray(mesh.material) ? mesh.material.map(prepare) : prepare(mesh.material);});@@ -28593,23 +27311,23 @@ async function renderDerivativeCell(input, context) {...trustedCategory(context) ? { category: trustedCategory(context) } : {},...context.intent ? { intent: context.intent } : {}});- const { cameraFromBounds: cameraFromBounds2, measureBounds: measureBounds2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const camera2 = input.camera ?? cameraFromBounds2(input.frameBounds ?? measureBounds2(input.root), input.view.dir, 1, undefined, measureBounds2(input.root));+ await Promise.resolve().then(() => init_views());+ const camera = input.camera ?? cameraFromBounds(input.frameBounds ?? measureBounds(input.root), input.view.dir, 1, undefined, measureBounds(input.root));const derivativeGlb = Uint8Array.from(rendered.bytes);const inputGlbSha256 = await sha256Glb(derivativeGlb);let degradeReason;const derivativeReasonCodes = [];if (context.viewRenderPort) {- const { captureViewPngsViaPort: captureViewPngsViaPort2 } = await Promise.resolve().then(() => (init_port(), exports_port));- const ported = await captureViewPngsViaPort2(context.viewRenderPort, derivativeGlb, resolveInLoopViewRenderTimeoutMs(context, "derivative-cell"), [input.view.dir], input.size, [camera2], context.captureLimits);+ await Promise.resolve().then(() => init_port());+ const ported = await captureViewPngsViaPort(context.viewRenderPort, derivativeGlb, resolveInLoopViewRenderTimeoutMs(context, "derivative-cell"), [input.view.dir], input.size, [camera], context.captureLimits);if (ported.ok && ported.derivativeFidelityAttested) {if (ported.inputGlbSha256 !== inputGlbSha256) {throw new Error(`validated derivative receipt hash mismatch (${ported.inputGlbSha256} != ${inputGlbSha256})`);}- const receipt2 = {+ const receipt = {version: "kiln.view-fidelity.v1",derivativeLabel: input.label,- camera: camera2,+ camera,cameraFidelity: "echo-validated",...ported.captureCache ? { captureCache: ported.captureCache } : {},requested: "full-preferred",@@ -28627,7 +27345,7 @@ async function renderDerivativeCell(input, context) {neededPbr: true});} catch {}- return { png: Buffer.from(ported.pngs[0]), receipt: receipt2 };+ return { png: Buffer.from(ported.pngs[0]), receipt };}if (ported.ok) {degradeReason = "view render port returned no derivative material/hash receipt";@@ -28645,17 +27363,17 @@ async function renderDerivativeCell(input, context) {}if (context.viewRenderRequired)throw new Error(`Required GPU render failed: ${degradeReason}`);- const { renderGlbViewCell: renderGlbViewCell2, CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const produceFlat = async () => renderGlbViewCell2(derivativeGlb, input.view, {+ await Promise.resolve().then(() => init_views());+ const produceFlat = async () => renderGlbViewCell(derivativeGlb, input.view, {size: input.size,- camera: camera2,+ camera,...input.backfaceCull !== undefined ? { backfaceCull: input.backfaceCull } : {},...input.frameBounds ? { frameBounds: input.frameBounds } : {}});const flat = context.captureCache ? await (await Promise.resolve().then(() => (init_capture_cache(), exports_capture_cache))).captureCpuCell(context.captureCache, {artifactGlbSha256: inputGlbSha256,- rendererId: CPU_RASTER_RENDERER_ID2,- camera: camera2,+ rendererId: CPU_RASTER_RENDERER_ID,+ camera,size: input.size,backfaceCull: input.backfaceCull ?? true}, produceFlat) : await produceFlat();@@ -28671,7 +27389,7 @@ async function renderDerivativeCell(input, context) {const receipt = {version: "kiln.view-fidelity.v1",derivativeLabel: input.label,- camera: camera2,+ camera,cameraFidelity: "engine-resolved",...flat.captureCache ? {captureCache: {@@ -28684,7 +27402,7 @@ async function renderDerivativeCell(input, context) {delivered: "geometry-flat",materialFaithful: false,exactArtifact: false,- rendererId: CPU_RASTER_RENDERER_ID2,+ rendererId: CPU_RASTER_RENDERER_ID,inputGlbSha256,degraded: true,degradeReason,@@ -28692,7 +27410,7 @@ async function renderDerivativeCell(input, context) {};try {context.onViewsRendered?.({- renderer: CPU_RASTER_RENDERER_ID2,+ renderer: CPU_RASTER_RENDERER_ID,degraded: true,degradedReason: degradeReason,neededPbr: true@@ -28733,12 +27451,12 @@ function runListPrimitives(input) {const all = listPrimitives();const category = input.category?.trim().toLowerCase();const primitives = category ? all.filter((p) => p.category.toLowerCase() === category) : all;- const text2 = primitives.map((p) => `${p.signature} -> ${p.returns}+ const text = primitives.map((p) => `${p.signature} -> ${p.returns}${p.description}e.g. ${p.example}`).join(``);- return { primitives, text: text2 };+ return { primitives, text };}function runValidate(input, context) {const category = trustedCategory(context);@@ -28834,12 +27552,12 @@ async function runRender(input, context) {}async function runScreenshot(input, context) {try {- const { renderGlbViewGrid: renderGlbViewGrid2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);const warnings = inspectSceneStructure(root, {category: trustedCategory(context)});- const grid = await renderGlbViewGrid2(rendered.glb);+ const grid = await renderGlbViewGrid(rendered.glb);return {ok: true,views: grid.views,@@ -28865,7 +27583,7 @@ function screenshotMedia(output) {}async function runRenderViews(input, context) {try {- const { renderGlbViewGrid: renderGlbViewGrid2, CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2, resolveGridCapture: resolveGridCapture2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root, rendered, reasonCodes } = await loadEvaluatedReviewScene(input.code, context);const materialContractFailure = missingProceduralTextureResult(rendered, context);if (materialContractFailure)@@ -28874,10 +27592,10 @@ async function runRenderViews(input, context) {const structuralWarnings = inspectSceneStructure(root, { category });const metrics = collectSceneMetrics(root);if ("shots" in (input.capture ?? {})) {- const { renderCaptureGrid: renderCaptureGrid2, listCameraSubjects: listCameraSubjects2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const grid2 = await renderCaptureGrid2(root, input.capture, (cell) => renderDerivativeCell(cell, context));- const receipts = grid2.derivativeReceipts;- const materialFaithful2 = receipts.every((r) => r.materialFaithful);+ await Promise.resolve().then(() => init_views());+ const grid = await renderCaptureGrid(root, input.capture, (cell) => renderDerivativeCell(cell, context));+ const receipts = grid.derivativeReceipts;+ const materialFaithful = receipts.every((r) => r.materialFaithful);return {ok: true,...rendered.buildCache ? { buildCache: rendered.buildCache } : {},@@ -28887,24 +27605,24 @@ async function runRenderViews(input, context) {...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},bbox: metrics.bbox,lowestPart: metrics.lowestPart,- views: grid2.views,- capture: grid2.capture,- ...grid2.captureCache ? { captureCache: grid2.captureCache } : {},- gridWidth: grid2.width,- gridHeight: grid2.height,- cameraShots: grid2.cameraShots,- parts: listCameraSubjects2(root).slice(0, 80).map(({ path, name }) => ({ path, name })),+ views: grid.views,+ capture: grid.capture,+ ...grid.captureCache ? { captureCache: grid.captureCache } : {},+ gridWidth: grid.width,+ gridHeight: grid.height,+ cameraShots: grid.cameraShots,+ parts: listCameraSubjects(root).slice(0, 80).map(({ path, name }) => ({ path, name })),derivativeReceipts: receipts,- ..."output" in input.capture && input.capture.output === "separate" ? { framesBase64: grid2.perFramePngs.map((p) => p.toString("base64")) } : { pngBase64: grid2.png.toString("base64") },+ ..."output" in input.capture && input.capture.output === "separate" ? { framesBase64: grid.perFramePngs.map((p) => p.toString("base64")) } : { pngBase64: grid.png.toString("base64") },viewFidelity: {version: "kiln.view-fidelity.v1",requested: "full-preferred",- delivered: materialFaithful2 ? "full-material" : "geometry-flat",- materialFaithful: materialFaithful2,+ delivered: materialFaithful ? "full-material" : "geometry-flat",+ materialFaithful,exactArtifact: false,rendererId: [...new Set(receipts.map((r) => r.rendererId))].join(", "),inputGlbSha256: await sha256Glb(Uint8Array.from(rendered.glb)),- degraded: !materialFaithful2+ degraded: !materialFaithful},warnings: [...structuralWarnings, ...rendered.warnings]};@@ -28914,10 +27632,10 @@ async function runRenderViews(input, context) {let drawnBy;let materialFaithful = false;if (context.viewRenderPort && (neededPbr || context.viewRenderRequired)) {- const { captureViewsViaPort: captureViewsViaPort2 } = await Promise.resolve().then(() => (init_port(), exports_port));- const ported = await captureViewsViaPort2(context.viewRenderPort, rendered.glb, resolveInLoopViewRenderTimeoutMs(context, "in-loop-grid"), input.capture);+ await Promise.resolve().then(() => init_port());+ const ported = await captureViewsViaPort(context.viewRenderPort, rendered.glb, resolveInLoopViewRenderTimeoutMs(context, "in-loop-grid"), input.capture);if (ported.ok) {- const resolvedViews = resolveGridCapture2(input.capture, process.env["KILN_GRID_VARIANT"]);+ const resolvedViews = resolveGridCapture(input.capture, process.env["KILN_GRID_VARIANT"]);grid = {png: ported.png,views: resolvedViews.views.map((v) => v.name),@@ -28930,7 +27648,7 @@ async function runRenderViews(input, context) {drawnBy = { renderer: ported.rendererId, degraded: false, neededPbr };} else {drawnBy = {- renderer: CPU_RASTER_RENDERER_ID2,+ renderer: CPU_RASTER_RENDERER_ID,degraded: true,degradedReason: ported.reason,neededPbr@@ -28940,13 +27658,13 @@ async function runRenderViews(input, context) {if (!grid && context.viewRenderRequired)throw new Error(`Required GPU render failed: ${drawnBy?.degradedReason ?? "renderer unavailable"}`);if (!grid) {- grid = await renderGlbViewGrid2(rendered.glb, {+ grid = await renderGlbViewGrid(rendered.glb, {...input.capture ? { capture: input.capture } : {},...context.captureCache ? { captureCache: context.captureCache } : {}});}- drawnBy ??= context.viewRenderPort ? { renderer: CPU_RASTER_RENDERER_ID2, degraded: false, neededPbr } : {- renderer: CPU_RASTER_RENDERER_ID2,+ drawnBy ??= context.viewRenderPort ? { renderer: CPU_RASTER_RENDERER_ID, degraded: false, neededPbr } : {+ renderer: CPU_RASTER_RENDERER_ID,degraded: neededPbr,...neededPbr ? {degradedReason: "material-faithful view render port unavailable"@@ -28955,8 +27673,8 @@ async function runRenderViews(input, context) {};const hashInput = new Uint8Array(rendered.glb.byteLength);hashInput.set(rendered.glb);- const digest4 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", hashInput));- const inputGlbSha256 = `sha256:${[...digest4].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", hashInput));+ const inputGlbSha256 = `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;const viewFidelity = {version: "kiln.view-fidelity.v1",requested: "full-preferred",@@ -29023,12 +27741,12 @@ function createKilnRenderViewsDef(context = {}) {}async function runScreenshotAnimation(input, context) {try {- const { renderClipAnimation: renderClipAnimation2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root, clips } = await loadEvaluatedReviewScene(input.code, context);const warnings = inspectSceneStructure(root, {category: trustedCategory(context)});- const r = await renderClipAnimation2(root, clips, {+ const r = await renderClipAnimation(root, clips, {clip: input.clip,...input.shot ? { shot: input.shot } : {},...input.frames !== undefined ? { frames: input.frames } : {},@@ -29107,19 +27825,19 @@ function createKilnScreenshotAnimationDef(context = {}) {}async function runViewInterior(input, context) {try {- const { renderInteriorGrid: renderInteriorGrid2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root } = await loadEvaluatedReviewScene(input.code, context);- const nodeName2 = input.nodeName?.trim() ? input.nodeName : undefined;- const grid = await renderInteriorGrid2(root, {+ const nodeName = input.nodeName?.trim() ? input.nodeName : undefined;+ const grid = await renderInteriorGrid(root, {...input.capture ? { capture: input.capture } : {},- ...nodeName2 ? { nodeName: nodeName2 } : {},+ ...nodeName ? { nodeName } : {},renderDerivativeCell: (cell) => renderDerivativeCell(cell, context)});const warnings = inspectSceneStructure(root, {category: trustedCategory(context)});if (grid.roofsHidden === 0) {- warnings.push(nodeName2 ? `No node named "${nodeName2}" was found, so the roof could not be lifted and the interior is still occluded. Check that name, or omit nodeName so the roof is found by its semantic role instead.` : 'No roof was found, so nothing could be lifted and the interior is still occluded. Build the roof with createRoofPlanes/createGableRoof (which tag it as a roof), or name the roof group "Roof".');+ warnings.push(nodeName ? `No node named "${nodeName}" was found, so the roof could not be lifted and the interior is still occluded. Check that name, or omit nodeName so the roof is found by its semantic role instead.` : 'No roof was found, so nothing could be lifted and the interior is still occluded. Build the roof with createRoofPlanes/createGableRoof (which tag it as a roof), or name the roof group "Roof".');}const viewFidelity = derivativeReviewFidelity(grid.derivativeReceipts);const viewEvidence = viewFidelity ? context.viewEvidenceHistory?.record("kiln_view_interior", viewFidelity) : undefined;@@ -29157,10 +27875,10 @@ function createKilnViewInteriorDef(context = {}) {}async function runInspect(input, context) {try {- const { prepareInspectView: prepareInspectView2 } = await Promise.resolve().then(() => (init_inspect(), exports_inspect));+ await Promise.resolve().then(() => init_inspect());const { root } = await loadEvaluatedReviewScene(input.code, context);- const { measureAttachment: measureAttachment2, describeSubjectFrame: describeSubjectFrame2 } = await Promise.resolve().then(() => (init_measurement(), exports_measurement));- const measurement = input.measure ? measureAttachment2(root, input.measure) : undefined;+ await Promise.resolve().then(() => init_measurement());+ const measurement = input.measure ? measureAttachment(root, input.measure) : undefined;if (input.shot) {if ([input.part,@@ -29171,12 +27889,12 @@ async function runInspect(input, context) {input.isolate].some((v) => v !== undefined))throw new Error("shot cannot be combined with legacy inspection controls");- const { renderCaptureGrid: renderCaptureGrid2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const grid = await renderCaptureGrid2(root, { version: "kiln.capture.v1", shots: [input.shot], size: 512 }, (cell) => renderDerivativeCell(cell, context));+ await Promise.resolve().then(() => init_views());+ const grid = await renderCaptureGrid(root, { version: "kiln.capture.v1", shots: [input.shot], size: 512 }, (cell) => renderDerivativeCell(cell, context));return {ok: true,cameraShot: grid.cameraShots[0],- subjectFrame: describeSubjectFrame2(root, input.shot.subject),+ subjectFrame: describeSubjectFrame(root, input.shot.subject),...measurement ? { measurement } : {},pngBase64: grid.perFramePngs[0].toString("base64"),width: 512,@@ -29184,7 +27902,7 @@ async function runInspect(input, context) {viewFidelity: derivativeReviewFidelity(grid.derivativeReceipts)};}- const r = prepareInspectView2(root, {+ const r = prepareInspectView(root, {...input.part !== undefined ? { part: input.part } : {},...input.view !== undefined ? { view: input.view } : {},...input.azimuthDeg !== undefined ? { azimuthDeg: input.azimuthDeg } : {},@@ -29329,7 +28047,7 @@ function createKilnToolRegistry(context = {}) {function withBuildCache(context) {if (context.evaluatorCacheManaged || context.cacheEvaluations === false || context.evaluatorPort && !context.evaluatorCacheIdentity)return context;- const scope2 = `kiln-local-registry-${++localCacheScope}`;+ const scope = `kiln-local-registry-${++localCacheScope}`;const evaluator = {render: (...args) => resolveEvaluatorPortV1(context.evaluatorPort, context.evaluatorProfile ?? "trusted-local").render(...args)};@@ -29343,7 +28061,7 @@ function withBuildCache(context) {return declared;const env = typeof process === "undefined" ? {} : process.env;return JSON.stringify([- declared ?? scope2,+ declared ?? scope,env["KILN_QA_MODE"],env["KILN_BAKE_OPTIMIZE"],env["KILN_BAKE_INSTANCE"]@@ -29352,12 +28070,12 @@ function withBuildCache(context) {})};}-async function guardCaptureBudget(name, input, context, run2) {+async function guardCaptureBudget(name, input, context, run) {try {- const { enforceCapturePixels: enforceCapturePixels2, enforceCaptureBytes: enforceCaptureBytes2 } = await Promise.resolve().then(() => (init_capture_limits(), exports_capture_limits));+ await Promise.resolve().then(() => init_capture_limits());const args = input;if (name === "kiln_edit" && args.render === false)- return await run2();+ return await run();let cells = 6, size = 384, cols = 3, compose = true;if (name === "kiln_inspect") {cells = 1;@@ -29377,18 +28095,18 @@ async function guardCaptureBudget(name, input, context, run2) {size = args.capture.size ?? 384;cols = args.capture.cols ?? Math.min(3, cells);} else {- const { resolveGridCapture: resolveGridCapture2 } = await Promise.resolve().then(() => (init_capture(), exports_capture));- const resolved2 = resolveGridCapture2(args.capture);- cells = resolved2.views.length;- cols = resolved2.cols;+ await Promise.resolve().then(() => init_capture());+ const resolved = resolveGridCapture(args.capture);+ cells = resolved.views.length;+ cols = resolved.cols;}}- enforceCapturePixels2(cells, size, cols, context.captureLimits, compose);- const out = await run2();+ enforceCapturePixels(cells, size, cols, context.captureLimits, compose);+ const out = await run();if (out && typeof out === "object") {const media = out;const encoded = media.framesBase64 ?? (media.pngBase64 ? [media.pngBase64] : []);- enforceCaptureBytes2(encoded.map((value) => Buffer.from(value, "base64")), context.captureLimits);+ enforceCaptureBytes(encoded.map((value) => Buffer.from(value, "base64")), context.captureLimits);}return out;} catch (error) {@@ -29446,27 +28164,27 @@ function createKilnAssetDefs(context) {throw new Error("No asset library configured. The local CLI/MCP host supplies workspace collections; embedded hosts must inject assetLibrary.");return context.assetLibrary;};- const links = async (collection, asset2) => ({+ const links = async (collection, asset) => ({ok: true,collection,asset: {- assetId: asset2.assetId,- revisionId: asset2.revisionId,- parentRevision: asset2.parentRevision,- name: asset2.name,- tags: asset2.tags,- createdAt: asset2.createdAt,- editable: asset2.editable,- files: asset2.files,- build: asset2.build && {- engine: asset2.build.engine,- rebuild: asset2.build.rebuild,- warningCount: asset2.build.warnings.length,- warnings: asset2.build.warnings.slice(0, 3).map((warning) => warning.slice(0, 200))+ assetId: asset.assetId,+ revisionId: asset.revisionId,+ parentRevision: asset.parentRevision,+ name: asset.name,+ tags: asset.tags,+ createdAt: asset.createdAt,+ editable: asset.editable,+ files: asset.files,+ build: asset.build && {+ engine: asset.build.engine,+ rebuild: asset.build.rebuild,+ warningCount: asset.build.warnings.length,+ warnings: asset.build.warnings.slice(0, 3).map((warning) => warning.slice(0, 200))}},- resources: (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).assetLinks(collection, asset2),- downloadUrls: await context.assetDownloadUrls?.(collection, asset2.assetId, asset2.revisionId)+ resources: (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).assetLinks(collection, asset),+ downloadUrls: await context.assetDownloadUrls?.(collection, asset.assetId, asset.revisionId)});const saveInput = z4.object({collection: assetSelector.collection,@@ -29524,7 +28242,7 @@ function createKilnAssetDefs(context) {};}const dependencies = rendered.materialResourceProvenance ?? [];- const asset2 = await target.save(input.collection, {+ const asset = await target.save(input.collection, {...input,code,glb: rendered.glb,@@ -29547,7 +28265,7 @@ function createKilnAssetDefs(context) {rebuild: dependencies.some((d) => d.delivery === "runtime") ? "external-dependencies-required" : "engine-required"}});- return links(input.collection, asset2);+ return links(input.collection, asset);}},{@@ -29579,14 +28297,14 @@ function createKilnAssetDefs(context) {}if (!input.assetId || !input.revisionId)throw new Error("get/restore requires assetId and revisionId");- const record5 = await target.read(input.collection, input.assetId, input.revisionId);+ const record = await target.read(input.collection, input.assetId, input.revisionId);if (input.action === "get")- return links(input.collection, record5.manifest);- const code = record5.files["source.kiln.js"];+ return links(input.collection, record.manifest);+ const code = record.files["source.kiln.js"];if (!code)throw new Error("Source unavailable: this asset contains only a GLB");return {- ...await links(input.collection, record5.manifest),+ ...await links(input.collection, record.manifest),programRef: await retainProgram(context.programStore, new TextDecoder().decode(code))};}@@ -29648,9 +28366,9 @@ function createKilnAssetDefs(context) {run: async (raw) => {const input = importInput.parse(raw);const target = library();- const record5 = await target.read(input.sourceCollection, input.assetId, input.revisionId);- await target.import(input.collection, [record5]);- return links(input.collection, record5.manifest);+ const record = await target.read(input.sourceCollection, input.assetId, input.revisionId);+ await target.import(input.collection, [record]);+ return links(input.collection, record.manifest);}}];@@ -29805,7 +28523,7 @@ var init_registry2 = __esm(() => {});// src/cli-render-mode.ts-import { createHash as createHash10 } from "node:crypto";+import { createHash as createHash9 } from "node:crypto";function resolveRenderMode(value) {if (value === "auto" || value === "cpu" || value === "gpu")return value;@@ -29816,7 +28534,7 @@ function makeRemoteRenderPort(url, token) {const body = {glb_base64: Buffer.from(req.glb).toString("base64")};- const inputGlbSha256 = `sha256:${createHash10("sha256").update(req.glb).digest("hex")}`;+ const inputGlbSha256 = `sha256:${createHash9("sha256").update(req.glb).digest("hex")}`;body["input_glb_sha256"] = inputGlbSha256;if (req.cameras) {body["cameras"] = req.cameras;@@ -29953,24 +28671,17 @@ var init_cli_render_mode = __esm(() => {});// src/assets-node.ts-var exports_assets_node = {};-__export(exports_assets_node, {- verifyAssetRecord: () => verifyAssetRecord,- localAssetLibrary: () => localAssetLibrary,- collectionConfigPath: () => collectionConfigPath,- FileAssetLibrary: () => FileAssetLibrary-});-import { createHash as createHash11, randomUUID as randomUUID3 } from "node:crypto";+import { createHash as createHash10, randomUUID as randomUUID3 } from "node:crypto";import { readFileSync as readFileSync2 } from "node:fs";-import { lstat as lstat2, mkdir as mkdir4, readFile as readFile6, readdir as readdir4, realpath as realpath2, rename as rename2, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";-import { dirname as dirname4, join as join7, relative as relative2, resolve as resolve4, sep } from "node:path";-async function verifyAssetRecord(record5) {- for (const [name, info] of Object.entries(record5.manifest.files)) {- const bytes = record5.files[name];+import { lstat as lstat2, mkdir as mkdir4, readFile as readFile4, readdir as readdir4, realpath as realpath2, rename as rename2, rm, writeFile as writeFile3 } from "node:fs/promises";+import { dirname as dirname4, join as join6, relative as relative2, resolve as resolve5, sep } from "node:path";+async function verifyAssetRecord(record) {+ for (const [name, info] of Object.entries(record.manifest.files)) {+ const bytes = record.files[name];if (!bytes || bytes.length !== info.bytes || digest4(bytes) !== info.sha256)throw new Error(`Asset integrity failure: ${name}`);}- validateRecordShape(record5);+ validateRecordShape(record);}class FileAssetLibrary {@@ -29978,7 +28689,7 @@ class FileAssetLibrary {constructor(roots) {if (!Object.keys(roots).length)throw new Error("Configure at least one collection");- this.roots = Object.fromEntries(Object.entries(roots).map(([id, path]) => [assetIdSchema.parse(id), resolve4(path)]));+ this.roots = Object.fromEntries(Object.entries(roots).map(([id, path]) => [assetIdSchema.parse(id), resolve5(path)]));}collections() {return Object.keys(this.roots).map((id) => ({ id, label: id }));@@ -29992,16 +28703,16 @@ class FileAssetLibrary {async path(collection, ...parts) {const root = this.directory(collection);await mkdir4(root, { recursive: true });- const canonical3 = await realpath2(root);+ const canonical = await realpath2(root);let path = root;for (const part of parts) {assetIdSchema.parse(part);- path = join7(path, part);+ path = join6(path, part);try {const entry = await lstat2(path);if (entry.isSymbolicLink())throw new Error("Collection symlinks are not supported");- const rel = relative2(canonical3, await realpath2(path));+ const rel = relative2(canonical, await realpath2(path));if (rel === ".." || rel.startsWith(`..${sep}`))throw new Error("Collection path escapes root");} catch (error) {@@ -30014,10 +28725,10 @@ class FileAssetLibrary {async list(collection) {const root = await this.path(collection);const records = [];- for (const asset2 of await readdir4(root, { withFileTypes: true })) {- if (!asset2.isDirectory() || !assetIdSchema.safeParse(asset2.name).success)+ for (const asset of await readdir4(root, { withFileTypes: true })) {+ if (!asset.isDirectory() || !assetIdSchema.safeParse(asset.name).success)continue;- const revisions = await this.path(collection, asset2.name, "revisions");+ const revisions = await this.path(collection, asset.name, "revisions");let entries;try {entries = await readdir4(revisions, { withFileTypes: true });@@ -30029,9 +28740,9 @@ class FileAssetLibrary {for (const revision of entries) {if (!revision.isDirectory() || !revision.name.startsWith("r_"))continue;- const dir = await this.path(collection, asset2.name, "revisions", revision.name);+ const dir = await this.path(collection, asset.name, "revisions", revision.name);const manifest = assetManifestSchema.parse(JSON.parse(new TextDecoder().decode(await this.file(dir, "manifest.json", 1024 * 1024))));- if (manifest.assetId !== asset2.name || manifest.revisionId !== revision.name)+ if (manifest.assetId !== asset.name || manifest.revisionId !== revision.name)throw new Error("Asset identity mismatch");records.push(manifest);}@@ -30039,11 +28750,11 @@ class FileAssetLibrary {return records.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.revisionId.localeCompare(b.revisionId));}async file(dir, name, limit = ASSET_LIMIT) {- const path = join7(dir, name);+ const path = join6(dir, name);const info = await lstat2(path);if (!info.isFile() || info.isSymbolicLink() || info.size > limit)throw new Error("Invalid collection file");- return new Uint8Array(await readFile6(path));+ return new Uint8Array(await readFile4(path));}async read(collection, assetId, revisionId) {const dir = await this.path(collection, assetId, "revisions", revisionId);@@ -30056,9 +28767,9 @@ class FileAssetLibrary {throw new Error("Invalid collection filename");files[name] = await this.file(dir, name);}- const record5 = { manifest, files };- await verifyAssetRecord(record5);- return record5;+ const record = { manifest, files };+ await verifyAssetRecord(record);+ return record;}async save(collection, draft) {const assetId = draft.assetId ?? `a_${randomUUID3().replaceAll("-", "")}`;@@ -30096,19 +28807,19 @@ class FileAssetLibrary {async import(collection, records) {if (!records.length || records.length > 100)throw new Error("Import requires 1..100 revisions");- for (const record5 of records)- await verifyAssetRecord(record5);- for (const record5 of records) {- const { manifest, files } = record5;+ for (const record of records)+ await verifyAssetRecord(record);+ for (const record of records) {+ const { manifest, files } = record;const dest = await this.path(collection, manifest.assetId, "revisions", manifest.revisionId);const parent = dirname4(dest);await mkdir4(parent, { recursive: true });- const stage = join7(parent, `.write-${randomUUID3()}`);+ const stage = join6(parent, `.write-${randomUUID3()}`);await mkdir4(stage);try {for (const [name, bytes] of Object.entries(files))- await writeFile4(join7(stage, name), bytes, { flag: "wx" });- await writeFile4(join7(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}+ await writeFile3(join6(stage, name), bytes, { flag: "wx" });+ await writeFile3(join6(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}`, {flag: "wx"});@@ -30122,15 +28833,15 @@ class FileAssetLibrary {throw error;}} finally {- await rm2(stage, { recursive: true, force: true });+ await rm(stage, { recursive: true, force: true });}}return records.map((r) => r.manifest);}}function collectionConfigPath(env = process.env) {- const workspace = env.KILN_PROGRAM_STORE ? dirname4(dirname4(resolve4(env.KILN_PROGRAM_STORE))) : process.cwd();- return join7(workspace, ".kiln", "collections.json");+ const workspace = env.KILN_PROGRAM_STORE ? dirname4(dirname4(resolve5(env.KILN_PROGRAM_STORE))) : process.cwd();+ return join6(workspace, ".kiln", "collections.json");}function localAssetLibrary(env = process.env) {if (env.KILN_COLLECTIONS) {@@ -30141,35 +28852,35 @@ function localAssetLibrary(env = process.env) {}const config = collectionConfigPath(env);try {- const text2 = readFileSync2(config, "utf8");- if (!text2.trim())+ const text = readFileSync2(config, "utf8");+ if (!text.trim())throw new Error("Collection configuration is empty");- return localAssetLibrary({ ...env, KILN_COLLECTIONS: text2 });+ return localAssetLibrary({ ...env, KILN_COLLECTIONS: text });} catch (error) {if (error.code !== "ENOENT")throw error;}const workspace = dirname4(dirname4(config));- return new FileAssetLibrary({ project: join7(workspace, "assets", "kiln") });+ return new FileAssetLibrary({ project: join6(workspace, "assets", "kiln") });}-var digest4 = (bytes) => `sha256:${createHash11("sha256").update(bytes).digest("hex")}`;+var digest4 = (bytes) => `sha256:${createHash10("sha256").update(bytes).digest("hex")}`;var init_assets_node = __esm(() => {init_assets();});// src/asset-viewer.tsimport { createServer } from "node:http";-import { readFile as readFile7 } from "node:fs/promises";-import { dirname as dirname5, join as join8 } from "node:path";-import { fileURLToPath as fileURLToPath4 } from "node:url";+import { readFile as readFile5 } from "node:fs/promises";+import { dirname as dirname5, join as join7 } from "node:path";+import { fileURLToPath as fileURLToPath5 } from "node:url";async function startAssetViewer(library, options = {}) {- const staticDirectory = options.staticDirectory ?? (import.meta.url.endsWith(".ts") ? join8(dirname5(fileURLToPath4(import.meta.url)), "..", "dist", "viewer") : join8(dirname5(fileURLToPath4(import.meta.url)), "viewer"));+ const staticDirectory = options.staticDirectory ?? (import.meta.url.endsWith(".ts") ? join7(dirname5(fileURLToPath5(import.meta.url)), "..", "dist", "viewer") : join7(dirname5(fileURLToPath5(import.meta.url)), "viewer"));const server = createServer(async (req, res) => {res.setHeader("X-Content-Type-Options", "nosniff");res.setHeader("Referrer-Policy", "no-referrer");res.setHeader("Cache-Control", "no-store");- const address2 = server.address();- const origin = `http://127.0.0.1:${typeof address2 === "object" && address2 ? address2.port : 0}`;+ const address = server.address();+ const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`;if (req.headers.host !== origin.slice(7) || req.headers.origin && req.headers.origin !== origin) {res.writeHead(403);res.end("Forbidden origin");@@ -30197,20 +28908,20 @@ async function startAssetViewer(library, options = {}) {if (url.pathname === "/api/standalone" && options.standalone)return send(options.standalone.bytes, options.standalone.name.endsWith(".zip") ? "application/zip" : "model/gltf-binary");if (url.pathname === "/api/bundle") {- const selected2 = url.searchParams.getAll("revision");- if (!selected2.length || selected2.length > 100)+ const selected = url.searchParams.getAll("revision");+ if (!selected.length || selected.length > 100)throw new Error("Select 1..100 revisions");- const records = await Promise.all(selected2.map((value) => {- const [collection, asset2, revision, extra] = value.split("/");- if (!collection || !asset2 || !revision || extra)+ const records = await Promise.all(selected.map((value) => {+ const [collection, asset, revision, extra] = value.split("/");+ if (!collection || !asset || !revision || extra)throw new Error("Invalid revision");- return library.read(collection, asset2, revision);+ return library.read(collection, asset, revision);}));return send(encodeAssetBundle(records), "application/zip", "kiln-assets.zip");}if (url.pathname.startsWith("/files/")) {- const file2 = await readAssetResource(library, `kiln://assets/${url.pathname.slice(7)}`);- return send(file2.bytes, file2.mimeType, url.searchParams.has("download") ? file2.name : undefined);+ const file = await readAssetResource(library, `kiln://assets/${url.pathname.slice(7)}`);+ return send(file.bytes, file.mimeType, url.searchParams.has("download") ? file.name : undefined);}const staticFiles = {"/": ["index.html", "text/html; charset=utf-8"],@@ -30224,23 +28935,23 @@ async function startAssetViewer(library, options = {}) {return;}res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self' blob: data:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'");- return send(await readFile7(join8(staticDirectory, file[0])), file[1]);+ return send(await readFile5(join7(staticDirectory, file[0])), file[1]);} catch (error) {res.statusCode = 400;send(JSON.stringify({ error: error instanceof Error ? error.message : "Asset unavailable" }));}});- await new Promise((resolve5, reject) => {+ await new Promise((resolve, reject) => {server.once("error", reject);- server.listen(options.port ?? 4318, "127.0.0.1", resolve5);+ server.listen(options.port ?? 4318, "127.0.0.1", resolve);});const address = server.address();if (!address || typeof address === "string")throw new Error("Viewer did not bind");return {url: `http://127.0.0.1:${address.port}/`,- close: () => new Promise((resolve5, reject) => {- server.close((error) => error ? reject(error) : resolve5());+ close: () => new Promise((resolve, reject) => {+ server.close((error) => error ? reject(error) : resolve());server.closeAllConnections();})};@@ -30253,11 +28964,11 @@ var init_asset_viewer = __esm(() => {// src/asset-cli.tsvar exports_asset_cli = {};__export(exports_asset_cli, {- assetMain: () => assetMain,- ASSET_USAGE: () => ASSET_USAGE+ ASSET_USAGE: () => ASSET_USAGE,+ assetMain: () => assetMain});-import { readFile as readFile8, writeFile as writeFile5, stat as stat4, mkdir as mkdir5, rename as rename3 } from "node:fs/promises";-import { basename, resolve as resolve5, dirname as dirname6 } from "node:path";+import { readFile as readFile6, writeFile as writeFile4, stat as stat4, mkdir as mkdir5, rename as rename3 } from "node:fs/promises";+import { basename, resolve as resolve6, dirname as dirname6 } from "node:path";import { randomUUID as randomUUID4 } from "node:crypto";async function assetMain(argv) {const command = argv[0];@@ -30304,7 +29015,7 @@ async function assetMain(argv) {const fileBytes = async (path) => {if ((await stat4(path)).size > ASSET_LIMIT)throw new Error("File exceeds 64 MiB");- return new Uint8Array(await readFile8(path));+ return new Uint8Array(await readFile6(path));};if (command === "collections") {if (positional[0] === "add") {@@ -30315,13 +29026,13 @@ async function assetMain(argv) {throw new Error("collections add requires name and directory");assetIdSchema.parse(name);const roots = Object.fromEntries(library.collections().map((c) => [c.id, library.directory(c.id)]));- if (roots[name] && roots[name] !== resolve5(directory))+ if (roots[name] && roots[name] !== resolve6(directory))throw new Error("Collection name already points to another directory");- roots[name] = resolve5(directory);+ roots[name] = resolve6(directory);const path = collectionConfigPath();await mkdir5(dirname6(path), { recursive: true });const temporary = `${path}.${randomUUID4()}.tmp`;- await writeFile5(temporary, JSON.stringify(roots, null, 2), { flag: "wx" });+ await writeFile4(temporary, JSON.stringify(roots, null, 2), { flag: "wx" });await rename3(temporary, path);console.log(`Collection ${name}: ${roots[name]}. Restart running MCP/viewer processes to load it.`);} else@@ -30354,29 +29065,29 @@ async function assetMain(argv) {const [assetId, revisionId] = positional;if (!assetId || !revisionId)throw new Error(`${command} requires asset ID and revision ID`);- const record5 = await library.read(collection, assetId, revisionId);+ const record = await library.read(collection, assetId, revisionId);if (command === "asset") {if (flags.restore) {- const source = record5.files["source.kiln.js"];+ const source = record.files["source.kiln.js"];if (!source)throw new Error("Source unavailable");console.log(JSON.stringify({- asset: record5.manifest,+ asset: record.manifest,programRef: await retainProgram(localProgramStore(), new TextDecoder().decode(source))}, null, 2));} else- console.log(JSON.stringify(record5.manifest, null, 2));+ console.log(JSON.stringify(record.manifest, null, 2));} else {if (!flags.out)throw new Error("export requires --out");const format = flags.format ?? "bundle";if (!["bundle", "glb", "source"].includes(format))throw new Error("Unknown export format");- const bytes = format === "bundle" ? encodeAssetBundle([record5]) : record5.files[format === "glb" ? "asset.glb" : "source.kiln.js"];+ const bytes = format === "bundle" ? encodeAssetBundle([record]) : record.files[format === "glb" ? "asset.glb" : "source.kiln.js"];if (!bytes)throw new Error("Source unavailable");- await writeFile5(await prepareDestination(resolve5(flags.out)), bytes, { flag: "wx" });- console.log(`Saved ${resolve5(flags.out)}`);+ await writeFile4(await prepareDestination(resolve6(flags.out)), bytes, { flag: "wx" });+ console.log(`Saved ${resolve6(flags.out)}`);}} else if (command === "import") {const file = positional[0];@@ -30391,8 +29102,8 @@ async function assetMain(argv) {const file = positional[0];if (file) {if ((await stat4(file)).isDirectory()) {- const { FileAssetLibrary: FileAssetLibrary2 } = await Promise.resolve().then(() => (init_assets_node(), exports_assets_node));- target = new FileAssetLibrary2({ project: resolve5(file) });+ await Promise.resolve().then(() => init_assets_node());+ target = new FileAssetLibrary({ project: resolve6(file) });} elsestandalone = { name: basename(file), bytes: await fileBytes(file) };}@@ -30435,16 +29146,30 @@ var init_asset_cli = __esm(() => {// src/cli.tsinit_cli_output();+import { open, readFile as readFile7, writeFile as writeFile5 } from "node:fs/promises";+import { resolve as resolvePath } from "node:path";++// src/direct-entry.ts+import { realpathSync } from "node:fs";+import { resolve } from "node:path";+import { fileURLToPath } from "node:url";+function isDirectEntry(moduleUrl) {+ if (!process.argv[1])+ return false;+ try {+ return realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(moduleUrl));+ } catch {+ return false;+ }+}++// src/cli.tsinit_local_runtime();init_registry2();init_cli_render_mode();init_program_store_node();init_program_store();init_asset_cli();-import { open, readFile as readFile9, writeFile as writeFile6 } from "node:fs/promises";-import { realpathSync } from "node:fs";-import { resolve as resolvePath } from "node:path";-import { fileURLToPath as fileURLToPath5 } from "node:url";var USAGE = `kiln — vision-in-the-loop 3D asset generationUSAGE@@ -30580,7 +29305,7 @@ async function emit(code, args, context) {console.log(` build ${result.buildCache.hit ? "reused" : "created"} ${result.buildCache.key}`);const out = args.out ?? (args.views ? undefined : "out.glb");if (out) {- await writeFile6(await prepareDestination(resolvePath(out)), result.glb);+ await writeFile5(await prepareDestination(resolvePath(out)), result.glb);console.log(` ${out} ${result.tris} tris ${(result.glb.length / 1024).toFixed(1)} KB`);} else {console.log(` ${result.tris} tris ${(result.glb.length / 1024).toFixed(1)} KB`);@@ -30612,7 +29337,7 @@ async function emit(code, args, context) {const media = def.media?.(output);if (!media)throw new Error("kiln_render returned no image");- await writeFile6(await prepareDestination(resolvePath(args.views)), media.png);+ await writeFile5(await prepareDestination(resolvePath(args.views)), media.png);console.log(` ${args.views} (${describeDrawnBy(output, context)})`);}}@@ -30624,7 +29349,7 @@ async function cmdRender(args) {console.error(USAGE);return 2;}- const code = file.startsWith("sha256:") || programRefPattern.test(file) ? await localProgramStore().get(file) : await readFile9(resolvePath(file), "utf8");+ const code = file.startsWith("sha256:") || programRefPattern.test(file) ? await localProgramStore().get(file) : await readFile7(resolvePath(file), "utf8");const context = await createPackagedLocalToolContext(await buildRenderPort(args.render, args.renderPort));console.log(`rendering ${file}`);await emit(code, args, context);@@ -30651,28 +29376,28 @@ async function cmdGenerate(args) {}const [{ runKilnAgent }, { makeKilnModel, resolveKilnAgentModel }] = generation;const context = await createPackagedLocalToolContext(await buildRenderPort(args.render, args.renderPort));- const descriptor2 = resolveKilnAgentModel(args.model);- const model = makeKilnModel(descriptor2);+ const descriptor = resolveKilnAgentModel(args.model);+ const model = makeKilnModel(descriptor);console.log(`generating "${prompt}"`);console.log(` model ${args.model} max-steps ${args.maxSteps} render ${args.render}`);- const run2 = await runKilnAgent({+ const run = await runKilnAgent({model,prompt,maxSteps: args.maxSteps,...args.category ? { category: args.category } : {},...context});- if (!run2.code) {+ if (!run.code) {console.error("the agent finished without submitting a program");- if (run2.lastText)- console.error(` last message: ${run2.lastText.slice(0, 400)}`);+ if (run.lastText)+ console.error(` last message: ${run.lastText.slice(0, 400)}`);return 1;}- console.log(` ${run2.steps} steps, ${run2.toolCalls.length} tool calls`);+ console.log(` ${run.steps} steps, ${run.toolCalls.length} tool calls`);const outPath = args.out ?? "out.glb";- await emit(run2.code, { ...args, out: outPath }, context);+ await emit(run.code, { ...args, out: outPath }, context);const source = outPath.replace(/\.glb$/i, ".kiln.js");- await writeFile6(await prepareDestination(resolvePath(source)), run2.code, "utf8");+ await writeFile5(await prepareDestination(resolvePath(source)), run.code, "utf8");console.log(` ${source} (the program — edit and re-render it)`);return 0;}@@ -30684,7 +29409,7 @@ async function cmdSource(args) {if (input.startsWith("sha256:") || programRefPattern.test(input)) {const code = await store.get(input);if (args.out) {- await writeFile6(await prepareDestination(resolvePath(args.out)), code, {+ await writeFile5(await prepareDestination(resolvePath(args.out)), code, {encoding: "utf8",flag: "wx"});@@ -30694,16 +29419,16 @@ async function cmdSource(args) {} else {if (args.out)throw new Error("Use source <programRef> --out <new-file.js> to export a saved revision.");- console.log(await retainProgram(store, await readFile9(resolvePath(input), "utf8")));+ console.log(await retainProgram(store, await readFile7(resolvePath(input), "utf8")));}return 0;}-async function withProcessAlive(run2) {+async function withProcessAlive(run) {const held = setInterval(() => {return;}, 1 << 30);try {- return await run2();+ return await run();} finally {clearInterval(held);}@@ -30756,16 +29481,7 @@ async function runMain(argv) {return 1;}}-function isDirectCliEntry() {- if (!process.argv[1])- return false;- try {- return realpathSync(resolvePath(process.argv[1])) === realpathSync(fileURLToPath5(import.meta.url));- } catch {- return false;- }-}-if (isDirectCliEntry()) {+if (isDirectEntry(import.meta.url)) {main(process.argv.slice(2)).then((code) => {process.exitCode = code;}).catch((err) => {@@ -30774,7 +29490,7 @@ if (isDirectCliEntry()) {});}export {- withProcessAlive,+ main,parseArgs,- main+ withProcessAlive};diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex 530e5d11..815fc963 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -1,6 +1,14 @@-import { createRequire } from "node:module";-var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);-var __require = /* @__PURE__ */ createRequire(import.meta.url);+var __esm = (fn, res, err) => () => {+ if (fn)+ try {+ res = fn(fn = 0);+ } catch (e) {+ err = [e];+ }+ if (err)+ throw err[0];+ return res;+};// src/evaluator/authoring-diagnostic.tsfunction authoringDiagnosticAdvice(diagnostic) {@@ -2288,7 +2296,7 @@ function readSemanticMetadataV1FromExtras(extras) {const result = validateSemanticMetadataV1(value);return result.valid ? result.value : undefined;}-var KILN_SEMANTIC_EXTRAS_KEY = "kilnSemantic", KILN_SEMANTIC_SCHEMA_VERSION = 1, KILN_SEMANTIC_ROLES, isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isNonEmptyString2 = (value) => typeof value === "string" && value.trim().length > 0 && value === value.trim(), isFiniteTuple = (value, length2) => Array.isArray(value) && value.length === length2 && value.every((component) => typeof component === "number" && Number.isFinite(component)), cloneTuple3 = (value) => [+var KILN_SEMANTIC_EXTRAS_KEY = "kilnSemantic", KILN_SEMANTIC_SCHEMA_VERSION = 1, KILN_SEMANTIC_ROLES, isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isNonEmptyString2 = (value) => typeof value === "string" && value.trim().length > 0 && value === value.trim(), isFiniteTuple = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), cloneTuple3 = (value) => [value[0],value[1],value[2]@@ -2450,8 +2458,8 @@ function validateCharacterJointDescriptorV1(value) {const forwardValid = validateUnitVector(forwardAxis, "localForwardAxis", issues);const bendValid = validateUnitVector(bendAxis, "localBendAxis", issues);if (forwardValid && bendValid) {- const dot2 = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];- if (Math.abs(dot2) > 0.000001) {+ const dot = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];+ if (Math.abs(dot) > 0.000001) {issues.push({code: "NON_ORTHOGONAL_AXES",path: "localBendAxis",@@ -2756,7 +2764,7 @@ function collectCharacterJointNodes(root) {visit(root, "", 0);return joints;}-var KILN_CHARACTER_JOINT_EXTRAS_KEY = "kilnCharacterJoint", KILN_CHARACTER_RIG_EXTRAS_KEY = "kilnCharacterRig", KILN_CHARACTER_JOINT_SCHEMA_VERSION = 1, CHARACTER_BODY_PLANS2, CHARACTER_JOINT_SIDES, IDENTITY_QUATERNION, UNIT_SCALE, FORWARD_AXIS, BEND_AXIS, isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isFiniteTuple2 = (value, length2) => Array.isArray(value) && value.length === length2 && value.every((component) => typeof component === "number" && Number.isFinite(component)), tuple3 = (value) => [value[0], value[1], value[2]], tuple4 = (value) => [+var KILN_CHARACTER_JOINT_EXTRAS_KEY = "kilnCharacterJoint", KILN_CHARACTER_RIG_EXTRAS_KEY = "kilnCharacterRig", KILN_CHARACTER_JOINT_SCHEMA_VERSION = 1, CHARACTER_BODY_PLANS2, CHARACTER_JOINT_SIDES, IDENTITY_QUATERNION, UNIT_SCALE, FORWARD_AXIS, BEND_AXIS, isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isFiniteTuple2 = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), tuple3 = (value) => [value[0], value[1], value[2]], tuple4 = (value) => [value[0],value[1],value[2],@@ -3120,7 +3128,7 @@ function wallRunAxis(wall) {function wallNeighbors(wall) {return wall === "front" || wall === "back" ? ["left", "right"] : ["front", "back"];}-function createShellWall(name, wall, material, length2, height, thickness, openings) {+function createShellWall(name, wall, material, length, height, thickness, openings) {const axis = wallRunAxis(wall);const root = new THREE2.Object3D;root.name = `${name}_Wall_${wall}`;@@ -3130,15 +3138,15 @@ function createShellWall(name, wall, material, length2, height, thickness, openirelationship("adjacent-to", `wall.${neighbors[1]}`),relationship("adjacent-to", "floor")]));- const sorted = openings.map((opening2, index) => ({- ...opening2,- id: opening2.id ?? `${opening2.kind ?? "door"}-${index + 1}`,- kind: opening2.kind ?? "door",- offset: opening2.offset ?? 0,- width: positive(opening2.width ?? (opening2.kind === "window" ? 1 : 1.1), "opening.width"),- height: positive(opening2.height ?? (opening2.kind === "window" ? 1 : 2.1), "opening.height"),- sill: opening2.kind === "window" ? nonNegative(opening2.sill ?? 1, "opening.sill") : 0,- depth: positive(opening2.depth ?? thickness, "opening.depth")+ const sorted = openings.map((opening, index) => ({+ ...opening,+ id: opening.id ?? `${opening.kind ?? "door"}-${index + 1}`,+ kind: opening.kind ?? "door",+ offset: opening.offset ?? 0,+ width: positive(opening.width ?? (opening.kind === "window" ? 1 : 1.1), "opening.width"),+ height: positive(opening.height ?? (opening.kind === "window" ? 1 : 2.1), "opening.height"),+ sill: opening.kind === "window" ? nonNegative(opening.sill ?? 1, "opening.sill") : 0,+ depth: positive(opening.depth ?? thickness, "opening.depth")})).sort((a, b) => a.offset - b.offset);if (sorted.length > 1)throw new RangeError("the minimal gable shell supports at most one opening per wall");@@ -3154,15 +3162,15 @@ function createShellWall(name, wall, material, length2, height, thickness, openiconst markers = [];const opening = sorted[0];if (!opening)- panel("solid", -length2 / 2, length2 / 2, 0, height);+ panel("solid", -length / 2, length / 2, 0, height);else {const left = opening.offset - opening.width / 2;const right = opening.offset + opening.width / 2;const top = opening.sill + opening.height;- if (left <= -length2 / 2 || right >= length2 / 2 || top >= height)+ if (left <= -length / 2 || right >= length / 2 || top >= height)throw new RangeError(`opening on wall.${wall} must fit strictly inside the wall boundary`);- panel("left", -length2 / 2, left, 0, height);- panel("right", right, length2 / 2, 0, height);+ panel("left", -length / 2, left, 0, height);+ panel("right", right, length / 2, 0, height);panel("lintel", left, right, top, height);if (opening.sill > 0)panel("sill", left, right, 0, opening.sill);@@ -3281,16 +3289,16 @@ function createRoofSurfaceLayout(name, material, options) {const rows = Math.max(1, Math.ceil(downhill / rowHeight));const columns = Math.max(1, Math.ceil(along / tileWidth));for (let row = 0;row < rows; row++) {- const length2 = Math.min(rowHeight * 1.08, downhill);+ const length = Math.min(rowHeight * 1.08, downhill);for (let column = 0;column < columns; column++) {const offset = row % 2 === 0 ? 0 : tileWidth / 2;const x = -along / 2 + tileWidth * (column + 0.5) + offset;if (x + tileWidth / 2 <= along / 2 + EPSILON)specs.push({width: tileWidth * 0.96,- length: length2,+ length,x,- z: Math.min(downhill - length2 / 2, row * rowHeight + length2 / 2)+ z: Math.min(downhill - length / 2, row * rowHeight + length / 2)});}}@@ -3426,26 +3434,26 @@ function gearGeo(opts = {}) {}function bladeGeo(opts = {}) {const {- length: length2 = 1.5,+ length = 1.5,baseWidth = 0.1,thickness = 0.015,tipLength = 0.25,edgeBevel = 0} = opts;- if (length2 <= 0 || baseWidth <= 0 || thickness <= 0) {+ if (length <= 0 || baseWidth <= 0 || thickness <= 0) {throw new Error("bladeGeo: length, baseWidth, thickness must all be > 0");}- if (tipLength >= length2) {+ if (tipLength >= length) {throw new Error("bladeGeo: tipLength must be less than length");}const hw = baseWidth / 2;const ht = thickness / 2;- const shoulderY = length2 - tipLength;+ const shoulderY = length - tipLength;const outline = [[-hw, 0],[hw, 0],[hw, shoulderY],- [0, length2],+ [0, length],[-hw, shoulderY]];const n = outline.length;@@ -3717,10 +3725,10 @@ var init_ops = __esm(() => {// src/geometry.tsimport * as THREE5 from "three";-function finiteArray(values, label, length2) {+function finiteArray(values, label, length) {const result = Array.from(values);- if (length2 !== undefined && result.length !== length2)- throw new Error(`${label}: expected ${length2} values, got ${result.length}`);+ if (length !== undefined && result.length !== length)+ throw new Error(`${label}: expected ${length} values, got ${result.length}`);if (!result.every((n) => Number.isFinite(Math.fround(n))))throw new Error(`${label}: all values must be finite Float32 values`);return result;@@ -3983,7 +3991,7 @@ function deform(geometry, options, map) {throw new Error("deformation interval must be finite and increasing");[low, high] = options.interval;}- const length2 = high - low;+ const length = high - low;const out = geometry.clone();const position = out.getAttribute("position");for (let i = 0;i < points.length; i++) {@@ -3991,11 +3999,11 @@ function deform(geometry, options, map) {const epsilon = Math.max(1, Math.abs(low), Math.abs(high)) * 0.0000001;if (point.y < low - epsilon || point.y > high + epsilon)continue;- const t = length2 > epsilon ? THREE6.MathUtils.clamp((point.y - low) / length2, 0, 1) : 0;+ const t = length > epsilon ? THREE6.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;const weight = options.falloff?.(t) ?? 1;if (!Number.isFinite(weight) || weight < 0 || weight > 1)throw new Error("deformation falloff must return a finite weight between 0 and 1");- const mapped = map(point.clone(), t, low, length2);+ const mapped = map(point.clone(), t, low, length);if (![mapped.x, mapped.y, mapped.z].every(Number.isFinite))throw new Error("deformation callback must return finite coordinates");point.lerp(mapped, weight).applyMatrix4(matrix);@@ -4019,10 +4027,10 @@ function bend(geometry, options) {if (!Number.isFinite(options.angle))throw new Error("bend angle must be finite degrees");const angle = THREE6.MathUtils.degToRad(options.angle);- return deform(geometry, options, (p, t, low, length2) => {- if (Math.abs(angle) < 0.0000000001 || length2 === 0)+ return deform(geometry, options, (p, t, low, length) => {+ if (Math.abs(angle) < 0.0000000001 || length === 0)return p;- const radius = length2 / angle, theta = angle * t;+ const radius = length / angle, theta = angle * t;return new THREE6.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);});}@@ -4149,10 +4157,10 @@ function loftProfiles(sections, options = {}) {return out;}function sweepProfile(profile, path, options = {}) {- const points = profilePoints(profile), closed = options.closed ?? false, twist2 = options.twist ?? 0;- if (!Number.isFinite(twist2))+ const points = profilePoints(profile), closed = options.closed ?? false, twist = options.twist ?? 0;+ if (!Number.isFinite(twist))throw new Error("sweepProfile twist must be finite degrees");- if (closed && Math.abs(twist2 / 360 - Math.round(twist2 / 360)) > 0.00000001)+ if (closed && Math.abs(twist / 360 - Math.round(twist / 360)) > 0.00000001)throw new Error("closed sweep twist must be a multiple of 360 degrees");if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))throw new Error("sweepProfile requires finite path points (two open or three closed)");@@ -4218,7 +4226,7 @@ function sweepProfile(profile, path, options = {}) {correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));const rings = stations.map((station, i) => {const tangent = tangents[i], t = distances[i] / total;- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE7.MathUtils.degToRad(twist2)) * t);+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE7.MathUtils.degToRad(twist)) * t);const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));});@@ -4277,16 +4285,16 @@ function threeToManifold(src, mod, label, context) {let vertexOffset = 0, meshCount = 0;const stride = context.preserve ? 5 : 3;src.traverse((child) => {- const mesh2 = child;- if (!mesh2.isMesh)+ const mesh = child;+ if (!mesh.isMesh)return;- const geometry = mesh2.geometry, position = geometry.getAttribute("position");+ const geometry = mesh.geometry, position = geometry.getAttribute("position");if (!position)return;meshCount++;const index = geometry.index, count = index?.count ?? position.count;if (count % 3 !== 0)- throw new Error(`CSG ${label}: mesh "${mesh2.name || "(unnamed)"}" has ${count} ${index ? "indices" : "vertices"}, which is not a whole number of triangles. Every CSG input must be a triangle mesh.`);+ throw new Error(`CSG ${label}: mesh "${mesh.name || "(unnamed)"}" has ${count} ${index ? "indices" : "vertices"}, which is not a whole number of triangles. Every CSG input must be a triangle mesh.`);if (position.itemSize !== 3)throw new Error(`CSG ${label}: positions must have three components`);const uv = geometry.getAttribute("uv");@@ -4296,11 +4304,11 @@ function threeToManifold(src, mod, label, context) {if (uv)context.anyUV = true;else- context.missingUV.add(mesh2.name || label);+ context.missingUV.add(mesh.name || label);}const point = new THREE8.Vector3;for (let i = 0;i < position.count; i++) {- point.fromBufferAttribute(position, i).applyMatrix4(mesh2.matrixWorld);+ point.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))throw new Error(`CSG ${label}: transformed positions must be finite Float32 coordinates`);properties.push(point.x, point.y, point.z);@@ -4311,8 +4319,8 @@ function threeToManifold(src, mod, label, context) {properties.push(u, v);}}- const materials = Array.isArray(mesh2.material) ? mesh2.material : [mesh2.material];- const spans = sourceSpans(mesh2, count).sort((a, b) => a.start - b.start);+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];+ const spans = sourceSpans(mesh, count).sort((a, b) => a.start - b.start);let covered = 0;for (const span of spans) {if (!Number.isInteger(span.start) || !Number.isInteger(span.count) || span.start !== covered || span.count <= 0 || span.count % 3 || span.start % 3 || span.start + span.count > count || !materials[span.materialIndex])@@ -4329,7 +4337,7 @@ function threeToManifold(src, mod, label, context) {];if (triangle.some((j) => !Number.isInteger(j) || j < 0 || j >= position.count))throw new Error(`CSG ${label}: index outside positions`);- if (mesh2.matrixWorld.determinant() < 0)+ if (mesh.matrixWorld.determinant() < 0)[triangle[1], triangle[2]] = [triangle[2], triangle[1]];indices.push(...triangle.map((j) => j + vertexOffset));const prior = geometry.userData.kilnCsgProvenance;@@ -4618,19 +4626,19 @@ function bevelCrossSection(cs, bevel, style, segments, label) {dilated.delete();return out;}-function normalizeTaper(taper2) {- if (taper2 === undefined)+function normalizeTaper(taper) {+ if (taper === undefined)return [1, 1];- if (typeof taper2 === "number") {- if (!Number.isFinite(taper2) || taper2 < 0) {- throw new Error(`taper must be a finite number >= 0 (got ${taper2}).`);+ if (typeof taper === "number") {+ if (!Number.isFinite(taper) || taper < 0) {+ throw new Error(`taper must be a finite number >= 0 (got ${taper}).`);}- return [taper2, taper2];+ return [taper, taper];}- if (!Array.isArray(taper2) || taper2.length !== 2 || !taper2.every((v) => Number.isFinite(v) && v >= 0)) {- throw new Error(`taper must be a number or [x, y] pair of numbers >= 0 (got ${JSON.stringify(taper2)}).`);+ if (!Array.isArray(taper) || taper.length !== 2 || !taper.every((v) => Number.isFinite(v) && v >= 0)) {+ throw new Error(`taper must be a number or [x, y] pair of numbers >= 0 (got ${JSON.stringify(taper)}).`);}- return [taper2[0], taper2[1]];+ return [taper[0], taper[1]];}async function extrudeProfile(profile, options = {}) {assertFiniteProfile(profile, "extrudeProfile");@@ -4640,8 +4648,8 @@ async function extrudeProfile(profile, options = {}) {bevel = 0,bevelStyle = "round",segments = 12,- twist: twist2 = 0,- taper: taper2,+ twist = 0,+ taper,divisions,axis = "y",center = true,@@ -4672,8 +4680,8 @@ async function extrudeProfile(profile, options = {}) {if (bevel > 0) {section = track(bevelCrossSection(section, bevel, bevelStyle, segments, "extrudeProfile"));}- const nDivisions = divisions ?? (twist2 !== 0 ? 16 : 1);- const solid = section.extrude(depth, nDivisions, twist2, normalizeTaper(taper2), center);+ const nDivisions = divisions ?? (twist !== 0 ? 16 : 1);+ const solid = section.extrude(depth, nDivisions, twist, normalizeTaper(taper), center);try {return orientSweep(manifoldToGeometry(solid, { smooth }), axis);} finally {@@ -5029,9 +5037,9 @@ function strictArray(value, path) {}return value;}-function assertKeys(record2, allowed, path) {+function assertKeys(record, allowed, path) {const allow = new Set(allowed);- for (const key of Object.keys(record2)) {+ for (const key of Object.keys(record)) {if (!allow.has(key)) {throw new ProceduralTextureError(`${path} has unknown key ${JSON.stringify(key)}.`);}@@ -5087,8 +5095,8 @@ function angle(value, path) {const normalized = (bounded % 360 + 360) % 360;return Object.is(normalized, -0) ? 0 : normalized;}-function blend(record2, path) {- const value = record2["blend"] ?? "normal";+function blend(record, path) {+ const value = record["blend"] ?? "normal";if (!BLENDS.includes(value)) {throw new ProceduralTextureError(`${path}.blend ${JSON.stringify(value)} is not one of ${BLENDS.join(", ")}.`);}@@ -5096,70 +5104,70 @@ function blend(record2, path) {}function canonicalLayer(value, index) {const path = `proceduralTexture.layers[${index}]`;- const record2 = strictRecord(value, path);- const op = record2["op"];+ const record = strictRecord(value, path);+ const op = record["op"];if (!OPS.includes(op)) {throw new ProceduralTextureError(`${path}.op ${JSON.stringify(op)} is not one of ${OPS.join(", ")}.`);}- const validatedBlend = blend(record2, path);- const validatedOpacity = unit(record2["opacity"], `${path}.opacity`, 1);+ const validatedBlend = blend(record, path);+ const validatedOpacity = unit(record["opacity"], `${path}.opacity`, 1);const common = {blend: index === 0 ? "normal" : validatedBlend,opacity: index === 0 ? 1 : validatedOpacity};switch (op) {case "solid":- assertKeys(record2, ["op", "color", "blend", "opacity"], path);- return { op, color: color(record2["color"], `${path}.color`), ...common };+ assertKeys(record, ["op", "color", "blend", "opacity"], path);+ return { op, color: color(record["color"], `${path}.color`), ...common };case "checker":- assertKeys(record2, ["op", "colorA", "colorB", "squares", "blend", "opacity"], path);+ assertKeys(record, ["op", "colorA", "colorB", "squares", "blend", "opacity"], path);return {op,- colorA: color(record2["colorA"], `${path}.colorA`),- colorB: color(record2["colorB"], `${path}.colorB`),- squares: integer(record2["squares"], `${path}.squares`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ squares: integer(record["squares"], `${path}.squares`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),...common};case "stripes":- assertKeys(record2, ["op", "colorA", "colorB", "count", "angleDeg", "blend", "opacity"], path);+ assertKeys(record, ["op", "colorA", "colorB", "count", "angleDeg", "blend", "opacity"], path);return {op,- colorA: color(record2["colorA"], `${path}.colorA`),- colorB: color(record2["colorB"], `${path}.colorB`),- count: integer(record2["count"], `${path}.count`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- angleDeg: angle(record2["angleDeg"], `${path}.angleDeg`),+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ count: integer(record["count"], `${path}.count`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ angleDeg: angle(record["angleDeg"], `${path}.angleDeg`),...common};case "gradient":- assertKeys(record2, ["op", "from", "to", "angleDeg", "blend", "opacity"], path);+ assertKeys(record, ["op", "from", "to", "angleDeg", "blend", "opacity"], path);return {op,- from: color(record2["from"], `${path}.from`),- to: color(record2["to"], `${path}.to`),- angleDeg: angle(record2["angleDeg"], `${path}.angleDeg`),+ from: color(record["from"], `${path}.from`),+ to: color(record["to"], `${path}.to`),+ angleDeg: angle(record["angleDeg"], `${path}.angleDeg`),...common};case "bricks":- assertKeys(record2, ["op", "brick", "mortar", "rows", "cols", "mortarWidth", "stagger", "blend", "opacity"], path);+ assertKeys(record, ["op", "brick", "mortar", "rows", "cols", "mortarWidth", "stagger", "blend", "opacity"], path);return {op,- brick: color(record2["brick"], `${path}.brick`),- mortar: color(record2["mortar"], `${path}.mortar`),- rows: integer(record2["rows"], `${path}.rows`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- cols: integer(record2["cols"], `${path}.cols`, 4, 1, MAX_PROCEDURAL_PATTERN_COUNT),- mortarWidth: unit(record2["mortarWidth"], `${path}.mortarWidth`, 0.06),- stagger: unit(record2["stagger"], `${path}.stagger`, 0.5),+ brick: color(record["brick"], `${path}.brick`),+ mortar: color(record["mortar"], `${path}.mortar`),+ rows: integer(record["rows"], `${path}.rows`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ cols: integer(record["cols"], `${path}.cols`, 4, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ mortarWidth: unit(record["mortarWidth"], `${path}.mortarWidth`, 0.06),+ stagger: unit(record["stagger"], `${path}.stagger`, 0.5),...common};case "noise":- assertKeys(record2, ["op", "colorA", "colorB", "scale", "octaves", "seed", "blend", "opacity"], path);+ assertKeys(record, ["op", "colorA", "colorB", "scale", "octaves", "seed", "blend", "opacity"], path);return {op,- colorA: color(record2["colorA"], `${path}.colorA`),- colorB: color(record2["colorB"], `${path}.colorB`),- scale: integer(record2["scale"], `${path}.scale`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- octaves: integer(record2["octaves"], `${path}.octaves`, 3, 1, MAX_NOISE_OCTAVES),- seed: integer(record2["seed"], `${path}.seed`, 0, -2147483648, 2147483647),+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ scale: integer(record["scale"], `${path}.scale`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ octaves: integer(record["octaves"], `${path}.octaves`, 3, 1, MAX_NOISE_OCTAVES),+ seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),...common};default:@@ -5167,17 +5175,17 @@ function canonicalLayer(value, index) {}}function migrateProceduralTextureSpecV1(input) {- const record2 = strictRecord(input, "proceduralTexture");- assertKeys(record2, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");- if (record2["schemaVersion"] !== undefined && record2["schemaVersion"] !== 1) {- throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(record2["schemaVersion"])}.`);+ const record = strictRecord(input, "proceduralTexture");+ assertKeys(record, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");+ if (record["schemaVersion"] !== undefined && record["schemaVersion"] !== 1) {+ throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(record["schemaVersion"])}.`);}return {schemaVersion: 2,- ...record2["size"] !== undefined ? { size: record2["size"] } : {},- ...record2["usage"] !== undefined ? { usage: record2["usage"] } : {},- ...record2["name"] !== undefined ? { name: record2["name"] } : {},- layers: record2["layers"]+ ...record["size"] !== undefined ? { size: record["size"] } : {},+ ...record["usage"] !== undefined ? { usage: record["usage"] } : {},+ ...record["name"] !== undefined ? { name: record["name"] } : {},+ layers: record["layers"]};}function canonicalizeProceduralTextureSpecV2(input) {@@ -5213,8 +5221,8 @@ function canonicalJson(value) {return JSON.stringify(value);if (Array.isArray(value))return `[${value.map(canonicalJson).join(",")}]`;- const record2 = value;- return `{${Object.keys(record2).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record2[key])}`).join(",")}}`;+ const record = value;+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;}function canonicalProceduralTextureJsonV2(input) {return canonicalJson(canonicalizeProceduralTextureSpecV2(input));@@ -5244,10 +5252,10 @@ function sha256Hex(text) {for (let i = 0;i < 16; i++)w[i] = view.getUint32(offset + i * 4, false);for (let i = 16;i < 64; i++) {- const a2 = w[i - 15];- const b2 = w[i - 2];- const s0 = rotateRight(a2, 7) ^ rotateRight(a2, 18) ^ a2 >>> 3;- const s1 = rotateRight(b2, 17) ^ rotateRight(b2, 19) ^ b2 >>> 10;+ const a = w[i - 15];+ const b = w[i - 2];+ const s0 = rotateRight(a, 7) ^ rotateRight(a, 18) ^ a >>> 3;+ const s1 = rotateRight(b, 17) ^ rotateRight(b, 19) ^ b >>> 10;w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;}let [a, b, c, d, e, f, g, hh] = h;@@ -5278,19 +5286,19 @@ function hashProceduralTextureSpecV2(input) {}function canonicalTextureRef(value, slot) {const path = `portableMaterial.textures.${slot}`;- const record2 = strictRecord(value, path);- if (record2["kind"] === "procedural") {- assertKeys(record2, ["kind", "spec"], path);- const spec = canonicalizeProceduralTextureSpecV2(record2["spec"]);+ const record = strictRecord(value, path);+ if (record["kind"] === "procedural") {+ assertKeys(record, ["kind", "spec"], path);+ const spec = canonicalizeProceduralTextureSpecV2(record["spec"]);const expected = MATERIAL_TEXTURE_USAGE[slot];if (spec.usage !== expected) {throw new ProceduralTextureError(`${path} requires procedural usage ${JSON.stringify(expected)}, got ${JSON.stringify(spec.usage)}.`);}return { kind: "procedural", spec };}- if (record2["kind"] === "resource") {- assertKeys(record2, ["kind", "resourceId"], path);- const resourceId = record2["resourceId"];+ if (record["kind"] === "resource") {+ assertKeys(record, ["kind", "resourceId"], path);+ const resourceId = record["resourceId"];if (typeof resourceId !== "string" || resourceId.length > 128 || !/^kiln\.[a-z0-9][a-z0-9._-]+$/.test(resourceId)) {throw new ProceduralTextureError(`${path}.resourceId must be a bounded kiln.* resource ID.`);}@@ -5299,8 +5307,8 @@ function canonicalTextureRef(value, slot) {throw new ProceduralTextureError(`${path}.kind must be "procedural" or "resource".`);}function canonicalizePortableMaterialSpecV2(input) {- const record2 = strictRecord(input, "portableMaterial");- assertKeys(record2, [+ const record = strictRecord(input, "portableMaterial");+ assertKeys(record, ["schemaVersion","model","name",@@ -5314,13 +5322,13 @@ function canonicalizePortableMaterialSpecV2(input) {"doubleSided","textures"], "portableMaterial");- if (record2["schemaVersion"] !== 2) {+ if (record["schemaVersion"] !== 2) {throw new ProceduralTextureError("portableMaterial.schemaVersion must be 2.");}- if (record2["model"] !== "pbrMetallicRoughness") {+ if (record["model"] !== "pbrMetallicRoughness") {throw new ProceduralTextureError('portableMaterial.model must be "pbrMetallicRoughness"; executable shader models are not portable.');}- const textureInput = record2["textures"] ?? {};+ const textureInput = record["textures"] ?? {};const textureRecord = strictRecord(textureInput, "portableMaterial.textures");const slots = Object.keys(MATERIAL_TEXTURE_USAGE);assertKeys(textureRecord, slots, "portableMaterial.textures");@@ -5340,26 +5348,26 @@ function canonicalizePortableMaterialSpecV2(input) {if (proceduralTexels > MAX_PORTABLE_MATERIAL_TEXELS) {throw new ProceduralTextureError(`portableMaterial procedural texture budget is ${proceduralTexels} texels, above ${MAX_PORTABLE_MATERIAL_TEXELS}.`);}- const alphaMode = record2["alphaMode"] ?? "opaque";+ const alphaMode = record["alphaMode"] ?? "opaque";if (alphaMode !== "opaque" && alphaMode !== "mask" && alphaMode !== "blend") {throw new ProceduralTextureError("portableMaterial.alphaMode must be opaque, mask, or blend.");}- if (record2["doubleSided"] !== undefined && typeof record2["doubleSided"] !== "boolean") {+ if (record["doubleSided"] !== undefined && typeof record["doubleSided"] !== "boolean") {throw new ProceduralTextureError("portableMaterial.doubleSided must be boolean.");}- const name = optionalName(record2["name"], "portableMaterial.name");+ const name = optionalName(record["name"], "portableMaterial.name");return {schemaVersion: 2,model: "pbrMetallicRoughness",...name !== undefined ? { name } : {},- ...record2["baseColor"] !== undefined ? { baseColor: color(record2["baseColor"], "portableMaterial.baseColor") } : {},- roughness: unit(record2["roughness"], "portableMaterial.roughness", 1),- metalness: unit(record2["metalness"], "portableMaterial.metalness", 0),- ...record2["emissive"] !== undefined ? { emissive: color(record2["emissive"], "portableMaterial.emissive") } : {},- emissiveIntensity: finite(record2["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),+ ...record["baseColor"] !== undefined ? { baseColor: color(record["baseColor"], "portableMaterial.baseColor") } : {},+ roughness: unit(record["roughness"], "portableMaterial.roughness", 1),+ metalness: unit(record["metalness"], "portableMaterial.metalness", 0),+ ...record["emissive"] !== undefined ? { emissive: color(record["emissive"], "portableMaterial.emissive") } : {},+ emissiveIntensity: finite(record["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),alphaMode,- alphaCutoff: unit(record2["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),- doubleSided: record2["doubleSided"] === true,+ alphaCutoff: unit(record["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),+ doubleSided: record["doubleSided"] === true,textures};}@@ -5592,11 +5600,11 @@ function compileProceduralTextureSpecV2(input) {}function proceduralTexture(spec) {const compiled = compileProceduralTextureSpecV2(spec);- const { size, usage: usage2, name, layers } = compiled.spec;+ const { size, usage, name, layers } = compiled.spec;const tex = new THREE10.DataTexture(compiled.pixels, size, size, THREE10.RGBAFormat, THREE10.UnsignedByteType);if (name)tex.name = name;- tex.colorSpace = usage2 === "albedo" || usage2 === "emissive" ? THREE10.SRGBColorSpace : THREE10.NoColorSpace;+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE10.SRGBColorSpace : THREE10.NoColorSpace;tex.wrapS = THREE10.RepeatWrapping;tex.wrapT = THREE10.RepeatWrapping;tex.minFilter = THREE10.LinearMipmapLinearFilter;@@ -5606,7 +5614,7 @@ function proceduralTexture(spec) {tex.userData["kilnProcedural"] = {schemaVersion: 2,size,- usage: usage2,+ usage,...name ? { name } : {},layers,canonicalJson: compiled.canonicalJson,@@ -5665,10 +5673,10 @@ function normalMapFromHeight(source, opts = {}) {tex.needsUpdate = true;return tex;}-var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color2) => [- color2 >> 16 & 255,- color2 >> 8 & 255,- color2 & 255+var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color) => [+ color >> 16 & 255,+ color >> 8 & 255,+ color & 255], lerp = (a, b, t) => a + (b - a) * t;var init_procedural_texture = __esm(() => {init_procedural_material_v2();@@ -7217,11 +7225,11 @@ var MATERIAL_RECIPE_IDS, MATERIAL_RECIPE_OVERRIDE_KEYS, APPROVED_TEXTURE_RESOURCalpha]);}, rgb = (hex, intensity = 1) => {- const color2 = rgba(hex);+ const color = rgba(hex);return Object.freeze([- color2[0] * intensity,- color2[1] * intensity,- color2[2] * intensity+ color[0] * intensity,+ color[1] * intensity,+ color[2] * intensity]);}, defaults = (baseColor, roughnessFactor, metallicFactor = 0, over = {}) => Object.freeze({baseColorFactor: rgba(baseColor),@@ -7498,59 +7506,59 @@ var init_material_recipes = __esm(() => {// src/material-resources.tsimport { createHash } from "node:crypto";-function provenance(descriptor2, hash) {+function provenance(descriptor, hash) {return {schemaVersion: 1,- resourceId: descriptor2.id,+ resourceId: descriptor.id,contentHash: hash,hashAlgorithm: "sha256",- usage: descriptor2.usage,- colorSpace: descriptor2.colorSpace,- resourceVersion: descriptor2.version,+ usage: descriptor.usage,+ colorSpace: descriptor.colorSpace,+ resourceVersion: descriptor.version,recipeVersion: 1,- delivery: descriptor2.delivery+ delivery: descriptor.delivery};}-function readPngDimensions(descriptor2, bytes) {+function readPngDimensions(descriptor, bytes) {const signature = [137, 80, 78, 71, 13, 10, 26, 10];if (bytes.byteLength < 24 || !signature.every((value, index) => bytes[index] === value) || String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR") {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "declared image/png bytes do not have a valid PNG signature and IHDR format");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "declared image/png bytes do not have a valid PNG signature and IHDR format");}const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);return { width: view.getUint32(16, false), height: view.getUint32(20, false) };}-function verifyResourcePayload(descriptor2, payload) {+function verifyResourcePayload(descriptor, payload) {if (!payload || typeof payload !== "object" || Array.isArray(payload)) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host payload must be { bytes, mime }");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host payload must be { bytes, mime }");}const keys = Object.keys(payload).sort();if (keys.length !== 2 || keys[0] !== "bytes" || keys[1] !== "mime") {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host payload must contain only bytes and MIME");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host payload must contain only bytes and MIME");}if (!(payload.bytes instanceof Uint8Array)) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host bytes must be Uint8Array");+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host bytes must be Uint8Array");}- if (payload.mime !== descriptor2.mime) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `host MIME ${String(payload.mime)} does not match approved ${descriptor2.mime}`);+ if (payload.mime !== descriptor.mime) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `host MIME ${String(payload.mime)} does not match approved ${descriptor.mime}`);}const bytes = payload.bytes;if (bytes.byteLength > TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `encoded-byte limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes}; received ${bytes.byteLength}`);+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `encoded-byte limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes}; received ${bytes.byteLength}`);}- if (bytes.byteLength !== descriptor2.byteLength) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `expected ${descriptor2.byteLength} bytes, received ${bytes.byteLength}`);+ if (bytes.byteLength !== descriptor.byteLength) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `expected ${descriptor.byteLength} bytes, received ${bytes.byteLength}`);}- const { width, height } = readPngDimensions(descriptor2, bytes);+ const { width, height } = readPngDimensions(descriptor, bytes);if (width < 1 || height < 1 || width > TEXTURE_RESOLVER_LIMITS_V1.maxWidth || height > TEXTURE_RESOLVER_LIMITS_V1.maxHeight) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `dimension limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxWidth}x${TEXTURE_RESOLVER_LIMITS_V1.maxHeight}; received ${width}x${height}`);+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `dimension limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxWidth}x${TEXTURE_RESOLVER_LIMITS_V1.maxHeight}; received ${width}x${height}`);}const pixels = width * height;if (!Number.isSafeInteger(pixels) || pixels > TEXTURE_RESOLVER_LIMITS_V1.maxPixels) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`);+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`);}const hash = sha256(bytes);- if (hash !== descriptor2.contentHash) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `content hash ${hash} does not match the pinned ${descriptor2.contentHash}`);+ if (hash !== descriptor.contentHash) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `content hash ${hash} does not match the pinned ${descriptor.contentHash}`);}return hash;}@@ -7612,12 +7620,12 @@ class ApprovedTextureResourceCache {const hash = this.#hashById.get(id);if (hash)return this.#resolution(id, hash);- const descriptor2 = this.#registry[id];- if (descriptor2.delivery !== "embedded") {+ const descriptor = this.#registry[id];+ if (descriptor.delivery !== "embedded") {throw new ApprovedTextureResourceUnavailableError(id, "it is delivered at runtime; use resolveAsync() or load()");}const decoded = bytesFromBase64(EMBEDDED_RESOURCE_BASE64[id]);- this.#cacheBytes(id, verifyResourcePayload(descriptor2, { bytes: decoded, mime: descriptor2.mime }), decoded);+ this.#cacheBytes(id, verifyResourcePayload(descriptor, { bytes: decoded, mime: descriptor.mime }), decoded);return this.#resolution(id, this.#hashById.get(id));}async resolveAsync(id) {@@ -7630,7 +7638,7 @@ class ApprovedTextureResourceCache {return this.resolve(id);let pending = this.#pendingById.get(id);if (!pending) {- const descriptor2 = this.#registry[id];+ const descriptor = this.#registry[id];const resolver = this.#resolver;pending = (async () => {if (!resolver) {@@ -7647,7 +7655,7 @@ class ApprovedTextureResourceCache {let payload;try {payload = await Promise.race([- Promise.resolve().then(() => resolver(descriptor2, Object.freeze({+ Promise.resolve().then(() => resolver(descriptor, Object.freeze({signal: controller.signal,deadlineMs: this.#resolverDeadlineMs}))),@@ -7657,7 +7665,7 @@ class ApprovedTextureResourceCache {if (timer !== undefined)clearTimeout(timer);}- this.#cacheBytes(id, verifyResourcePayload(descriptor2, payload), payload.bytes);+ this.#cacheBytes(id, verifyResourcePayload(descriptor, payload), payload.bytes);return this.#resolution(id, this.#hashById.get(id));})().finally(() => {this.#pendingById.delete(id);@@ -7710,9 +7718,9 @@ function collectMaterialResourceProvenance(root) {const materials = Array.isArray(material) ? material : material ? [material] : [];for (const item of materials) {for (const texture of materialTextures(item)) {- const record2 = readMaterialResourceProvenance(texture);- if (record2)- records.set(`${record2.resourceId}:${record2.contentHash}:${record2.usage}`, record2);+ const record = readMaterialResourceProvenance(texture);+ if (record)+ records.set(`${record.resourceId}:${record.contentHash}:${record.usage}`, record);}}});@@ -7774,12 +7782,12 @@ async function compilePortableMaterialSpecV2(input) {if (!isApprovedResourceId(ref.resourceId)) {throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not an approved texture resource ID.`);}- const descriptor2 = cache.descriptor(ref.resourceId);- if (!descriptor2.allowedSlots.includes(slot)) {+ const descriptor = cache.descriptor(ref.resourceId);+ if (!descriptor.allowedSlots.includes(slot)) {throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not approved for that slot.`);}- if (descriptor2.usage !== SLOT_USAGE[slot]) {- throw new ProceduralTextureError(`portableMaterial.textures.${slot} requires ${SLOT_USAGE[slot]} data, but ${JSON.stringify(ref.resourceId)} provides ${descriptor2.usage}.`);+ if (descriptor.usage !== SLOT_USAGE[slot]) {+ throw new ProceduralTextureError(`portableMaterial.textures.${slot} requires ${SLOT_USAGE[slot]} data, but ${JSON.stringify(ref.resourceId)} provides ${descriptor.usage}.`);}}const loaded = new Map;@@ -7840,10 +7848,10 @@ function positive2(value, name) {}function normalizedQuaternion(value) {const source = value ?? [0, 0, 0, 1];- const length2 = Math.hypot(source[0], source[1], source[2], source[3]);- if (!Number.isFinite(length2) || length2 <= 0.000000001)+ const length = Math.hypot(source[0], source[1], source[2], source[3]);+ if (!Number.isFinite(length) || length <= 0.000000001)throw new TypeError("socket rotation must be a finite quaternion");- return [source[0] / length2, source[1] / length2, source[2] / length2, source[3] / length2];+ return [source[0] / length, source[1] / length, source[2] / length, source[3] / length];}function semantic2(roles, options = {}) {return {@@ -7975,8 +7983,8 @@ function createWheelAssembly(name, materials, options) {]}));(steeringPivot ?? root).add(spinPivot);- const defaults2 = createWheelGeometrySet(radius, width);- const tire = new THREE11.Mesh(options.geometries?.tire ?? defaults2.tire, materials.tire);+ const defaults = createWheelGeometrySet(radius, width);+ const tire = new THREE11.Mesh(options.geometries?.tire ?? defaults.tire, materials.tire);const rim = new THREE11.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);const hub = new THREE11.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);tire.name = `Tire_${options.side}_${index}`;@@ -8175,8 +8183,8 @@ function legacyAssemblies(root) {});}function resolveVehicleWheelAssemblies(root) {- const semantic3 = semanticAssemblies(root);- return semantic3.length > 0 ? semantic3 : legacyAssemblies(root);+ const semantic = semanticAssemblies(root);+ return semantic.length > 0 ? semantic : legacyAssemblies(root);}function hasCanonicalVehicleFront(root) {let found = false;@@ -8443,19 +8451,19 @@ var init_uv_shapes = () => {};// src/material-recipe-runtime.tsimport * as THREE14 from "three";async function applyMaterialRecipeV1(request, options = {}) {- const resolved2 = resolveMaterialRecipeV1(request);+ const resolved = resolveMaterialRecipeV1(request);const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;const loaded = new Map;- for (const [slot, id] of Object.entries(resolved2.textureResources)) {+ for (const [slot, id] of Object.entries(resolved.textureResources)) {if (id)loaded.set(slot, await cache.load(id));}const materialOptions = {- roughness: resolved2.roughnessFactor,- metalness: resolved2.metallicFactor,- alphaMode: lowerAlphaMode(resolved2.alphaMode),- ...resolved2.alphaMode === "MASK" ? { alphaCutoff: resolved2.alphaCutoff ?? 0.5 } : {},- doubleSided: resolved2.doubleSided,+ roughness: resolved.roughnessFactor,+ metalness: resolved.metallicFactor,+ alphaMode: lowerAlphaMode(resolved.alphaMode),+ ...resolved.alphaMode === "MASK" ? { alphaCutoff: resolved.alphaCutoff ?? 0.5 } : {},+ doubleSided: resolved.doubleSided,...loaded.get("baseColor") ? { albedo: loaded.get("baseColor").texture } : {},...loaded.get("normal") ? { normal: loaded.get("normal").texture } : {},...loaded.get("metallicRoughness") ? { metallicRoughness: loaded.get("metallicRoughness").texture } : {},@@ -8464,11 +8472,11 @@ async function applyMaterialRecipeV1(request, options = {}) {};const material = pbrMaterial(materialOptions);material.name = options.name ?? request.id;- material.color.setRGB(resolved2.baseColorFactor[0], resolved2.baseColorFactor[1], resolved2.baseColorFactor[2], THREE14.LinearSRGBColorSpace);- material.opacity = resolved2.baseColorFactor[3];- material.emissive.setRGB(resolved2.emissiveFactor[0], resolved2.emissiveFactor[1], resolved2.emissiveFactor[2], THREE14.LinearSRGBColorSpace);+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE14.LinearSRGBColorSpace);+ material.opacity = resolved.baseColorFactor[3];+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE14.LinearSRGBColorSpace);const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));- const provenance2 = {+ const provenance = {schemaVersion: 1,recipeId: request.id,recipeVersion: 1,@@ -8485,8 +8493,8 @@ async function applyMaterialRecipeV1(request, options = {}) {portableModel: "pbrMetallicRoughness",resources};- material.userData["kilnMaterialRecipe"] = provenance2;- return { material, resolved: resolved2, provenance: provenance2 };+ material.userData["kilnMaterialRecipe"] = provenance;+ return { material, resolved, provenance };}async function materialRecipe(id, overrides, options = {}) {return (await applyMaterialRecipeV1(createMaterialRecipeRequestV1(id, overrides), options)).material;@@ -8589,26 +8597,26 @@ function createPart(name, geometry2, material, options = {}) {function capsuleGeo(radius, height, segments = 6) {return new THREE15.CapsuleGeometry(radius, height, 2, segments);}-function capsuleXGeo(radius, length2, segments = 6) {- const geo = capsuleGeo(radius, length2, segments);+function capsuleXGeo(radius, length, segments = 6) {+ const geo = capsuleGeo(radius, length, segments);geo.rotateZ(-Math.PI / 2);return geo;}-function capsuleZGeo(radius, length2, segments = 6) {- const geo = capsuleGeo(radius, length2, segments);+function capsuleZGeo(radius, length, segments = 6) {+ const geo = capsuleGeo(radius, length, segments);geo.rotateX(Math.PI / 2);return geo;}function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {return new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);}-function cylinderXGeo(radiusTop, radiusBottom, length2, segments = 8) {- const geo = cylinderGeo(radiusTop, radiusBottom, length2, segments);+function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {+ const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);geo.rotateZ(-Math.PI / 2);return geo;}-function cylinderZGeo(radiusTop, radiusBottom, length2, segments = 8) {- const geo = cylinderGeo(radiusTop, radiusBottom, length2, segments);+function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {+ const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);geo.rotateX(Math.PI / 2);return geo;}@@ -8621,13 +8629,13 @@ function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {function coneGeo(radius, height, segments = 8) {return new THREE15.ConeGeometry(radius, height, segments);}-function coneXGeo(radius, length2, segments = 8) {- const geo = coneGeo(radius, length2, segments);+function coneXGeo(radius, length, segments = 8) {+ const geo = coneGeo(radius, length, segments);geo.rotateZ(-Math.PI / 2);return geo;}-function coneZGeo(radius, length2, segments = 8) {- const geo = coneGeo(radius, length2, segments);+function coneZGeo(radius, length, segments = 8) {+ const geo = coneGeo(radius, length, segments);geo.rotateX(Math.PI / 2);return geo;}@@ -8680,10 +8688,10 @@ function crossedQuadsGeo(opts = {}) {const yPivot = opts.yPivot ?? 0;const geometries = [];for (let i = 0;i < planes; i++) {- const angle2 = i / planes * Math.PI;+ const angle = i / planes * Math.PI;const quad = new THREE15.PlaneGeometry(w, h);quad.translate(0, h * (0.5 - yPivot), 0);- quad.rotateY(angle2);+ quad.rotateY(angle);geometries.push(quad);}const out = new THREE15.BufferGeometry;@@ -8839,11 +8847,11 @@ function beamBetween(name, start, end, radius, material, options = {}) {const a = new THREE15.Vector3(...start);const b = new THREE15.Vector3(...end);const direction = b.clone().sub(a);- const length2 = direction.length();- if (length2 <= 0.0001) {- throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length2.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);+ const length = direction.length();+ if (length <= 0.0001) {+ throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);}- const mesh = new THREE15.Mesh(cylinderGeo(radius, radius, length2, options.segments ?? 8), material);+ const mesh = new THREE15.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);mesh.name = `Mesh_${name}`;mesh.position.copy(a.add(b).multiplyScalar(0.5));mesh.quaternion.setFromUnitVectors(new THREE15.Vector3(0, 1, 0), direction.normalize());@@ -8918,7 +8926,7 @@ function createLadder(name, options) {return { leftRail, rightRail, rungs };}function wallWithOpening(name, material, options) {- const { length: length2, height, thickness, axis = "z", opening, parent } = options;+ const { length, height, thickness, axis = "z", opening, parent } = options;const group = new THREE15.Object3D;group.name = name;const overlap = 0.02;@@ -8934,7 +8942,7 @@ function wallWithOpening(name, material, options) {createPart(`${name}${suffix}`, geo, material, { position: pos, parent: group });};if (!opening) {- panel("", -length2 / 2, length2 / 2, 0, height);+ panel("", -length / 2, length / 2, 0, height);} else {const ow = opening.width ?? (opening.kind === "window" ? 1 : 1.1);const oh = opening.height ?? (opening.kind === "window" ? 1 : 2.1);@@ -8943,8 +8951,8 @@ function wallWithOpening(name, material, options) {const right = off + ow / 2;const sill = opening.kind === "window" ? Math.max(opening.sill ?? 1, 0) : 0;const top = Math.min(sill + oh, height);- panel("_L", -length2 / 2, left, 0, height);- panel("_R", right, length2 / 2, 0, height);+ panel("_L", -length / 2, left, 0, height);+ panel("_R", right, length / 2, 0, height);panel("_Lintel", left - overlap, right + overlap, top, height);if (sill > 0)panel("_Sill", left - overlap, right + overlap, 0, sill);@@ -8966,8 +8974,8 @@ function room(name, material, options = {}) {const openings = options.openings ?? [{ wall: "front", kind: "door" }];const root = new THREE15.Object3D;root.name = name;- const openingFor = (wall2) => {- const found = openings.find((op) => op.wall === wall2);+ const openingFor = (wall) => {+ const found = openings.find((op) => op.wall === wall);if (!found)return;const { wall: _wall, ...rest } = found;@@ -9013,8 +9021,8 @@ function createRoofPlanes2(name, material, options) {}if ((options.ridgeAxis ?? "x") === "x") {const halfRun = options.width / 2 + (options.overhang ?? 0.3);- const angle2 = Math.atan2(options.height, halfRun);- result.slopes[1].rotation.set(-angle2, Math.PI, 0);+ const angle = Math.atan2(options.height, halfRun);+ result.slopes[1].rotation.set(-angle, Math.PI, 0);}return result;}@@ -9057,16 +9065,16 @@ function createStairs(name, material, options) {parent.add(root);return { root, steps: stepList };}-function requireColor(color2, fn) {- if (typeof color2 === "number" || typeof color2 === "string")+function requireColor(color, fn) {+ if (typeof color === "number" || typeof color === "string")return;- const got = color2 && typeof color2 === "object" ? `an object with keys [${Object.keys(color2).join(", ")}]` : String(color2);+ const got = color && typeof color === "object" ? `an object with keys [${Object.keys(color).join(", ")}]` : String(color);throw new Error(`${fn}(color, options?): color must be a hex number like 0x8c4a32 or a CSS string, got ${got}. ` + `Material settings go in the SECOND argument: ${fn}(0x8c4a32, { roughness: 0.5, metalness: 0.9 }).`);}-function gameMaterial(color2, options = {}) {- requireColor(color2, "gameMaterial");+function gameMaterial(color, options = {}) {+ requireColor(color, "gameMaterial");return new THREE15.MeshStandardMaterial({- color: color2,+ color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,emissive: options.emissive ?? 0,@@ -9074,18 +9082,18 @@ function gameMaterial(color2, options = {}) {flatShading: options.flatShading ?? true});}-function basicMaterial(color2, options = {}) {- requireColor(color2, "basicMaterial");+function basicMaterial(color, options = {}) {+ requireColor(color, "basicMaterial");return new THREE15.MeshBasicMaterial({- color: color2,+ color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1});}-function glassMaterial(color2, options = {}) {- requireColor(color2, "glassMaterial");+function glassMaterial(color, options = {}) {+ requireColor(color, "glassMaterial");return new THREE15.MeshStandardMaterial({- color: color2,+ color,transparent: true,opacity: options.opacity ?? 0.35,roughness: options.roughness ?? 0.1,@@ -9093,10 +9101,10 @@ function glassMaterial(color2, options = {}) {side: THREE15.DoubleSide});}-function lambertMaterial(color2, options = {}) {- requireColor(color2, "lambertMaterial");+function lambertMaterial(color, options = {}) {+ requireColor(color, "lambertMaterial");return new THREE15.MeshLambertMaterial({- color: color2,+ color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0});@@ -9263,12 +9271,12 @@ function validateAsset(root, category) {}return { valid: true, errors, warnings };}-function buildSandboxGlobals(usage2, options = {}) {+function buildSandboxGlobals(usage, options = {}) {const wrap = (name, fn) => {- if (!usage2)+ if (!usage)return fn;const wrapped = (...args) => {- usage2[name] = (usage2[name] ?? 0) + 1;+ usage[name] = (usage[name] ?? 0) + 1;return fn(...args);};return wrapped;@@ -9296,9 +9304,9 @@ function buildSandboxGlobals(usage2, options = {}) {try {key = `${name}::${JSON.stringify(args)}`;} catch {- const result2 = fn(...args);- stampKilnRange(name, result2);- return result2;+ const result = fn(...args);+ stampKilnRange(name, result);+ return result;}const hit = geoCache.get(key);if (hit)@@ -10237,19 +10245,19 @@ function markerBounds(matrix) {}return bounds;}-function geometryPlaneNormal(geometry2, relativeMatrix) {- geometry2.computeBoundingBox();- const local = geometry2.boundingBox;+function geometryPlaneNormal(geometry, relativeMatrix) {+ geometry.computeBoundingBox();+ const local = geometry.boundingBox;if (!local)return;const size = local.getSize(new THREE17.Vector3);- const dimensions2 = [+ const dimensions = [["x", size.x],["y", size.y],["z", size.z]];- dimensions2.sort((a, b) => a[1] - b[1]);- const axis = dimensions2[0]?.[0];+ dimensions.sort((a, b) => a[1] - b[1]);+ const axis = dimensions[0]?.[0];if (!axis)return;const normal = new THREE17.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);@@ -10257,8 +10265,8 @@ function geometryPlaneNormal(geometry2, relativeMatrix) {normal.multiplyScalar(-1);return normal.normalize();}-function geometryEvidence(geometry2, relativeMatrix) {- const position = geometry2.getAttribute("position");+function geometryEvidence(geometry, relativeMatrix) {+ const position = geometry.getAttribute("position");const bounds = emptyBounds();const vertices = [];if (position?.itemSize !== 3)@@ -10270,7 +10278,7 @@ function geometryEvidence(geometry2, relativeMatrix) {expandBounds(bounds, point);}const triangles = [];- const indices = geometry2.getIndex();+ const indices = geometry.getIndex();const addTriangle = (a, b, c) => {const va = vertices[a];const vb = vertices[b];@@ -10287,7 +10295,7 @@ function geometryEvidence(geometry2, relativeMatrix) {addTriangle(index, index + 1, index + 2);}}- const planeNormal = geometryPlaneNormal(geometry2, relativeMatrix);+ const planeNormal = geometryPlaneNormal(geometry, relativeMatrix);return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };}function collectArchitectureEvidence(scene) {@@ -10304,7 +10312,7 @@ function collectArchitectureEvidence(scene) {directRoles.forEach((role) => {allRoles.add(role);});- const roles2 = [...new Set([...inheritedRoles, ...directRoles])];+ const roles = [...new Set([...inheritedRoles, ...directRoles])];const segment = `${node.name.trim() || node.type || "Object3D"}[${siblingIndex}]`;const nodePath = parentPath ? `${parentPath}/${segment}` : segment;const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);@@ -10322,13 +10330,13 @@ function collectArchitectureEvidence(scene) {nodePath,directRoles,directRelationships,- roles: roles2,+ roles,isMesh,...evidence});}node.children.forEach((child, index) => {- visit(child, nodePath, index, roles2);+ visit(child, nodePath, index, roles);});};visit(scene, "", 0, []);@@ -10398,8 +10406,8 @@ function highEdgeVertices(aggregateValue, rise) {const maximumY = aggregateValue.bounds.max.y;return aggregateValue.vertices.filter((point) => point.y >= maximumY - band);}-function ridgeCrossSectionDistance(positive3, negative, lateralAxis, rise) {- const a = highEdgeVertices(positive3, rise);+function ridgeCrossSectionDistance(positive, negative, lateralAxis, rise) {+ const a = highEdgeVertices(positive, rise);const b = highEdgeVertices(negative, rise);let distance = Infinity;for (const pointA of a) {@@ -10412,19 +10420,19 @@ function ridgeCrossSectionDistance(positive3, negative, lateralAxis, rise) {function roofFindings(context, architecture, evidence) {if (!requestedGable(architecture) && !taggedGable(evidence))return [];- const positive3 = aggregateRole(evidence, "roof.slope.positive");+ const positive = aggregateRole(evidence, "roof.slope.positive");const negative = aggregateRole(evidence, "roof.slope.negative");const tagged = taggedGable(evidence);const exactDisposition = tagged ? "block" : "warn";const findings = [];- if (!positive3 || !negative) {+ if (!positive || !negative) {findings.push(architectureFinding(context, {code: "ARCH_ROOF_AXIS",disposition: exactDisposition,- message: `A gable requires exactly two semantic slope roles; found ${positive3 ? 1 : 0} positive and ${negative ? 1 : 0} negative slope surfaces.`,+ message: `A gable requires exactly two semantic slope roles; found ${positive ? 1 : 0} positive and ${negative ? 1 : 0} negative slope surfaces.`,measurement: {name: "semanticSlopeRoleCount",- actual: Number(Boolean(positive3)) + Number(Boolean(negative)),+ actual: Number(Boolean(positive)) + Number(Boolean(negative)),expected: 2,threshold: 2},@@ -10444,11 +10452,11 @@ function roofFindings(context, architecture, evidence) {}));return findings;}- if (!positive3 || !negative)+ if (!positive || !negative)return findings;const ridgeAxis = architecture.roof.ridgeAxis;const lateralAxis = ridgeAxis === "x" ? "z" : "x";- const positiveNormal = averageNormal(positive3.normals);+ const positiveNormal = averageNormal(positive.normals);const negativeNormal = averageNormal(negative.normals);const lateralProduct = positiveNormal && negativeNormal ? positiveNormal[lateralAxis] * negativeNormal[lateralAxis] : null;if (lateralProduct === null || lateralProduct >= -0.0025) {@@ -10468,9 +10476,9 @@ function roofFindings(context, architecture, evidence) {const { spanX, spanZ } = architecture.footprint;const expectedRidgeSpan = (ridgeAxis === "x" ? spanX : spanZ) + architecture.roof.overhang * 2;const expectedLateralSpan = (lateralAxis === "x" ? spanX : spanZ) + architecture.roof.overhang * 2;- const ridgeCoverage = Math.min(extent(positive3.bounds, ridgeAxis) / expectedRidgeSpan, extent(negative.bounds, ridgeAxis) / expectedRidgeSpan);- const roofMinLateral = Math.min(positive3.bounds.min[lateralAxis], negative.bounds.min[lateralAxis]);- const roofMaxLateral = Math.max(positive3.bounds.max[lateralAxis], negative.bounds.max[lateralAxis]);+ const ridgeCoverage = Math.min(extent(positive.bounds, ridgeAxis) / expectedRidgeSpan, extent(negative.bounds, ridgeAxis) / expectedRidgeSpan);+ const roofMinLateral = Math.min(positive.bounds.min[lateralAxis], negative.bounds.min[lateralAxis]);+ const roofMaxLateral = Math.max(positive.bounds.max[lateralAxis], negative.bounds.max[lateralAxis]);const lateralCoverage = intervalCoverage(roofMinLateral, roofMaxLateral, -expectedLateralSpan / 2, expectedLateralSpan / 2);if (ridgeCoverage < 0.9 || lateralCoverage < 0.9) {const actual = Math.min(ridgeCoverage, lateralCoverage);@@ -10484,7 +10492,7 @@ function roofFindings(context, architecture, evidence) {expected: ">= 0.9",threshold: 0.9},- affected: { node: positive3.parts[0]?.nodeName ?? "roof.slope.positive" }+ affected: { node: positive.parts[0]?.nodeName ?? "roof.slope.positive" }}));}const panels = evidence.parts.filter((part) => part.isMesh && (part.directRoles.some((role) => role.startsWith("roof.panel.")) || hasRole(part, "roof.surface.panels") || hasRolePrefix(part, "roof.") && /panel|sheet|shingle|seam|corrugat/i.test(part.nodeName)));@@ -10509,7 +10517,7 @@ function roofFindings(context, architecture, evidence) {}}));}- const ridgeDistance = ridgeCrossSectionDistance(positive3, negative, lateralAxis, architecture.roof.rise);+ const ridgeDistance = ridgeCrossSectionDistance(positive, negative, lateralAxis, architecture.roof.rise);const ridgeTolerance = Math.max(0.04, expectedLateralSpan * 0.0125);if (!Number.isFinite(ridgeDistance) || ridgeDistance > ridgeTolerance) {findings.push(architectureFinding(context, {@@ -10545,7 +10553,7 @@ function endFindings(context, architecture, evidence) {const closedEnds = architecture.roof.closedEnds;if (!closedEnds)return [];- const positive3 = aggregateRole(evidence, "roof.gable.positive");+ const positive = aggregateRole(evidence, "roof.gable.positive");const negative = aggregateRole(evidence, "roof.gable.negative");const hasTaggedRoof = taggedGable(evidence);const disposition = hasTaggedRoof ? "block" : "warn";@@ -10556,7 +10564,7 @@ function endFindings(context, architecture, evidence) {const expectedArea = lateralSpan * architecture.roof.rise / 2;const findings = [];for (const [end, aggregateValue] of [- ["positive", positive3],+ ["positive", positive],["negative", negative]]) {if (!aggregateValue) {@@ -10729,8 +10737,8 @@ function shrunkenPortalBounds(bounds, wall) {}return result;}-function portalRoleWall(roles2) {- for (const role of roles2) {+function portalRoleWall(roles) {+ for (const role of roles) {const match = /^opening\.(front|back|left|right)\.(?:door|portal|entry)(?:\.|$)/.exec(role);if (match)return match[1];@@ -10886,7 +10894,7 @@ function roofModeFindings(context, architecture, evidence) {if (mode === "auto")return [];const roofParts = evidence.parts.filter((part) => hasRolePrefix(part, "roof."));- const removableRelationships = roofParts.flatMap((part) => part.directRelationships.filter((relationship2) => relationship2.kind === "separable-from"));+ const removableRelationships = roofParts.flatMap((part) => part.directRelationships.filter((relationship) => relationship.kind === "separable-from"));const present = roofParts.length > 0;const valid = mode === "none" ? !present : mode === "fixed" ? present && removableRelationships.length === 0 : present && removableRelationships.length > 0;if (valid)@@ -11201,12 +11209,12 @@ function block(intent, code, message, options) {});}function targetName(trackName) {- const dot2 = trackName.lastIndexOf(".");- return dot2 > 0 ? trackName.slice(0, dot2) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(0, dot) : undefined;}function propertyName(trackName) {- const dot2 = trackName.lastIndexOf(".");- return dot2 > 0 ? trackName.slice(dot2 + 1) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(dot + 1) : undefined;}function blockerKey(finding) {return [@@ -11346,8 +11354,8 @@ function heldItemFindings(intent, nodes) {if (!held?.required)return [];const item = nodes.find((evidence) => {- const roles2 = readSemanticMetadataV1(evidence.node)?.roles ?? [];- return evidence.node.userData["kilnHeldItem"] === true || roles2.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");+ const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];+ return evidence.node.userData["kilnHeldItem"] === true || roles.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");});if (!item) {return [@@ -11367,8 +11375,8 @@ function heldItemFindings(intent, nodes) {break;cursor = cursor.parent;}- const roleMatches = (descriptor2) => {- const candidates = [descriptor2.role, ...descriptor2.aliases];+ const roleMatches = (descriptor) => {+ const candidates = [descriptor.role, ...descriptor.aliases];return candidates.some((role) => role === held.attachmentRole || role.split(/[._-]/).includes(held.attachmentRole));};if (attachment?.endEffector && roleMatches(attachment))@@ -11490,8 +11498,8 @@ function endpointDelta(track, size) {const lastOffset = track.values.length - size;const last = Array.from({ length: size }, (_, index) => Number(track.values[lastOffset + index]));if (track.name.endsWith(".quaternion") && size === 4) {- const dot2 = Math.abs(first.reduce((sum, value, index) => sum + value * last[index], 0));- return Math.abs(1 - Math.min(1, dot2));+ const dot = Math.abs(first.reduce((sum, value, index) => sum + value * last[index], 0));+ return Math.abs(1 - Math.min(1, dot));}return Math.max(...first.map((value, index) => Math.abs(value - last[index])));}@@ -11660,8 +11668,8 @@ function rootMotionFindings(intent, root, clips) {}function declaredHeldItem(nodes) {return nodes.find((evidence) => {- const roles2 = readSemanticMetadataV1(evidence.node)?.roles ?? [];- return evidence.node.userData["kilnHeldItem"] === true || roles2.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");+ const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];+ return evidence.node.userData["kilnHeldItem"] === true || roles.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");});}function characterJointScale(root) {@@ -11820,8 +11828,8 @@ function characterScale(points) {const size = bounds.getSize(new THREE19.Vector3);return Math.max(size.x, size.y, size.z, 1);}-function pairKey(descriptor2) {- return descriptor2.role.split(/[._-]/).filter((token) => token !== "left" && token !== "right").join(".");+function pairKey(descriptor) {+ return descriptor.role.split(/[._-]/).filter((token) => token !== "left" && token !== "right").join(".");}function bilateralSymmetryFindings(context, root) {const points = jointPoints(root);@@ -11868,9 +11876,9 @@ function restChainFindings(context, root) {const minimumSegment = Math.max(0.01, scale * REST_ORDER_RATIO);const chains = trusted.bodyPlan === "biped" ? BIPED_CHAINS : QUADRUPED_CHAINS;const findings = [];- for (const roles2 of chains) {- const chain = roles2.map((role) => byRole.get(role)).filter((value) => !!value);- if (chain.length !== roles2.length)+ for (const roles of chains) {+ const chain = roles.map((role) => byRole.get(role)).filter((value) => !!value);+ if (chain.length !== roles.length)continue;for (let index = 1;index < chain.length; index++) {const parent = chain[index - 1];@@ -11880,7 +11888,7 @@ function restChainFindings(context, root) {continue;findings.push(advisory(context, {code: "CHAR_REST_CHAIN_ORDER",- message: `Rest chain ${roles2.join(" -> ")} is vertically inverted or collapsed at ` + `${parent.evidence.descriptor.role} -> ${child.evidence.descriptor.role}.`,+ message: `Rest chain ${roles.join(" -> ")} is vertically inverted or collapsed at ` + `${parent.evidence.descriptor.role} -> ${child.evidence.descriptor.role}.`,affected: { node: child.evidence.node.name, nodePath: child.evidence.nodePath },measurement: {name: "parentToChildVerticalDrop",@@ -11901,7 +11909,7 @@ function restChainFindings(context, root) {continue;findings.push(advisory(context, {code: "CHAR_REST_SEGMENT_LENGTH",- message: `Rest chain ${roles2.join(" -> ")} has collapsed or grossly unmatched segment lengths.`,+ message: `Rest chain ${roles.join(" -> ")} has collapsed or grossly unmatched segment lengths.`,affected: { node: chain[1].evidence.node.name, nodePath: chain[1].evidence.nodePath },measurement: {name: "chainSegmentLengthRatio",@@ -11921,17 +11929,17 @@ function forwardMarkerFindings(context, root) {return markers.flatMap((marker) => {const quaternion = marker.node.getWorldQuaternion(new THREE19.Quaternion);const actual = new THREE19.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();- const angle2 = THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(actual.dot(expected), -1, 1)));- if (angle2 <= FORWARD_ANGLE_DEGREES)+ const angle = THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(actual.dot(expected), -1, 1)));+ if (angle <= FORWARD_ANGLE_DEGREES)return [];return [advisory(context, {code: "CHAR_FORWARD_MARKER",- message: `Declared forward marker ${marker.descriptor.role} differs from canonical +X by ` + `${angle2.toFixed(3)} degrees.`,+ message: `Declared forward marker ${marker.descriptor.role} differs from canonical +X by ` + `${angle.toFixed(3)} degrees.`,affected: { node: marker.node.name, nodePath: marker.nodePath },measurement: {name: "forwardMarkerAngle",- actual: angle2,+ actual: angle,expected: 0,threshold: FORWARD_ANGLE_DEGREES,unit: "degrees"@@ -11942,12 +11950,12 @@ function forwardMarkerFindings(context, root) {});}function trackTarget(trackName) {- const dot2 = trackName.lastIndexOf(".");- return dot2 > 0 ? trackName.slice(0, dot2) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(0, dot) : undefined;}function trackProperty(trackName) {- const dot2 = trackName.lastIndexOf(".");- return dot2 > 0 ? trackName.slice(dot2 + 1) : undefined;+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(dot + 1) : undefined;}function applyTrack(root, track, time) {const target = trackTarget(track.name);@@ -11999,8 +12007,8 @@ function lateralEnergyFindings(context, root, clips) {const findings = [];for (const clip of clips) {const samples = sampleClip(root, clip);- const roles2 = [...samples[0].byRole.keys()].filter(limbRole).sort();- for (const role of roles2) {+ const roles = [...samples[0].byRole.keys()].filter(limbRole).sort();+ for (const role of roles) {let sagittal = 0;let lateral = 0;let maximumLateral = 0;@@ -12086,13 +12094,13 @@ function phaseOppositionFindings(context, root, clips) {}return findings;}-function signedBendDegrees(descriptor2, quaternion) {- const rest = new THREE19.Quaternion(...descriptor2.rest.rotation);+function signedBendDegrees(descriptor, quaternion) {+ const rest = new THREE19.Quaternion(...descriptor.rest.rotation);const delta = rest.invert().multiply(quaternion).normalize();const axis = new THREE19.Vector3(delta.x, delta.y, delta.z);- const signedMagnitude = axis.dot(new THREE19.Vector3(...descriptor2.localBendAxis));- const angle2 = 2 * Math.atan2(signedMagnitude, delta.w);- return THREE19.MathUtils.radToDeg(THREE19.MathUtils.euclideanModulo(angle2 + Math.PI, Math.PI * 2) - Math.PI);+ const signedMagnitude = axis.dot(new THREE19.Vector3(...descriptor.localBendAxis));+ const angle = 2 * Math.atan2(signedMagnitude, delta.w);+ return THREE19.MathUtils.radToDeg(THREE19.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);}function bendDirectionFindings(context, root, clips) {const joints = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role));@@ -12106,9 +12114,9 @@ function bendDirectionFindings(context, root, clips) {let maximumFraction = 0;for (const fraction of SAMPLE_FRACTIONS) {const value = track.createInterpolant().evaluate(fraction * clip.duration);- const bend2 = signedBendDegrees(joint.descriptor, new THREE19.Quaternion().fromArray(value).normalize());- if (Math.abs(bend2) > Math.abs(maximum)) {- maximum = bend2;+ const bend = signedBendDegrees(joint.descriptor, new THREE19.Quaternion().fromArray(value).normalize());+ if (Math.abs(bend) > Math.abs(maximum)) {+ maximum = bend;maximumFraction = fraction;}}@@ -12286,7 +12294,7 @@ function probeLocalFrameFromQuaternion(id, origin, quaternion) {function createOrientedProbeBox3(input) {if (!input.id.trim())throw new TypeError("Oriented probe box ID must be non-empty.");- if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent2) => extent2 <= 0)) {+ if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent) => extent <= 0)) {throw new TypeError("Oriented probe box half-extents must be finite and greater than zero.");}return {@@ -12510,8 +12518,8 @@ function bilateralSymmetryFindings2(context, root, wheels) {const centerDelta = Math.hypot(a.x - b.x, a.y - b.y, a.z + b.z);const radiusDelta = Math.abs((left.radius ?? 0) - (right.radius ?? 0));const widthDelta = Math.abs((left.width ?? 0) - (right.width ?? 0));- const scale2 = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(0.01, scale2 * SYMMETRY_RATIO);+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(0.01, scale * SYMMETRY_RATIO);const maximum = Math.max(centerDelta, radiusDelta, widthDelta);if (maximum <= threshold)continue;@@ -12582,8 +12590,8 @@ function probeBox(id, root, bounds) {const size = bounds.getSize(new THREE20.Vector3);const position = new THREE20.Vector3;const quaternion = new THREE20.Quaternion;- const scale2 = new THREE20.Vector3;- root.matrixWorld.decompose(position, quaternion, scale2);+ const scale = new THREE20.Vector3;+ root.matrixWorld.decompose(position, quaternion, scale);const xAxis = new THREE20.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();const yAxis = new THREE20.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();const zAxis = new THREE20.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();@@ -12597,9 +12605,9 @@ function probeBox(id, root, bounds) {zAxis: tuple(zAxis)}),halfExtents: [- size.x * Math.abs(scale2.x) / 2,- size.y * Math.abs(scale2.y) / 2,- size.z * Math.abs(scale2.z) / 2+ size.x * Math.abs(scale.x) / 2,+ size.y * Math.abs(scale.y) / 2,+ size.z * Math.abs(scale.z) / 2]});}@@ -12705,7 +12713,7 @@ function weldedBoundaryEdges(root, loop) {if (!positions)return;const matrix = inverse.clone().multiply(node.matrixWorld);- const keys = Array.from({ length: positions.count }, (_, index2) => vertexKey(new THREE20.Vector3().fromBufferAttribute(positions, index2).applyMatrix4(matrix)));+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE20.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));const index = node.geometry.getIndex();const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);for (let offset = 0;offset + 2 < indices.length; offset += 3) {@@ -12729,11 +12737,11 @@ function trackProfileFindings(context, root, intent) {const loops = [];const roadWheels = [];root.traverse((node) => {- const roles2 = semanticRoles(node);- if (roles2.some((role) => role.startsWith("track.loop.")) || roles2.some((role) => role.startsWith("support.track."))) {+ const roles = semanticRoles(node);+ if (roles.some((role) => role.startsWith("track.loop.")) || roles.some((role) => role.startsWith("support.track."))) {loops.push(node);}- if (roles2.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {+ if (roles.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {roadWheels.push(node);}});@@ -12848,8 +12856,8 @@ function finding(context, value) {viewHints: value.viewHints ?? ["vehicle.underbody", "vehicle.wheel-section"]};}-function localPoint2(rootInverse2, value) {- return value.clone().applyMatrix4(rootInverse2);+function localPoint2(rootInverse, value) {+ return value.clone().applyMatrix4(rootInverse);}function rootAxis(root, axis) {root.updateWorldMatrix(true, false);@@ -13034,14 +13042,14 @@ function duplicateAssemblyFindings(context, root, wheels) {const right = wheels[b];const sameDeclaredCorner = left.side !== undefined && left.side === right.side && left.index !== undefined && left.index === right.index;const centerDelta = localPoint2(inverse, left.centerWorld).distanceTo(localPoint2(inverse, right.centerWorld));- const scale2 = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(CENTER_MINIMUM, scale2 * CENTER_RATIO);+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(CENTER_MINIMUM, scale * CENTER_RATIO);if (!sameDeclaredCorner && centerDelta > threshold)continue;- const semantic3 = left.source === "semantic" && right.source === "semantic";+ const semantic = left.source === "semantic" && right.source === "semantic";findings.push(finding(context, {code: "VEH_DUPLICATE_ASSEMBLY",- disposition: semantic3 ? "block" : "warn",+ disposition: semantic ? "block" : "warn",message: `Wheel assemblies ${left.id} and ${right.id} resolve to the same ` + `${sameDeclaredCorner ? `${left.side}-${left.index} corner` : "scale-relative center"}.`,affected: { node: right.root.name },measurement: {@@ -13090,7 +13098,7 @@ function contactFindings2(context, root, intent, wheels) {}return findings;}-function renderableMinYInRoot(rootInverse2, node) {+function renderableMinYInRoot(rootInverse, node) {let minimum = Infinity;node.traverse((part) => {if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))@@ -13099,7 +13107,7 @@ function renderableMinYInRoot(rootInverse2, node) {const bounds = part.geometry.boundingBox;if (!bounds)return;- const matrix = rootInverse2.clone().multiply(part.matrixWorld);+ const matrix = rootInverse.clone().multiply(part.matrixWorld);for (const x of [bounds.min.x, bounds.max.x]) {for (const y of [bounds.min.y, bounds.max.y]) {for (const z of [bounds.min.z, bounds.max.z]) {@@ -13118,16 +13126,16 @@ function supportContactFindings(context, root, intent) {const explicitContacts = [];const supports = [];root.traverse((node) => {- const roles2 = readSemanticMetadataV1(node)?.roles ?? [];- const isWheelContact = roles2.some((role) => role.startsWith("wheel.contact."));- if (!isWheelContact && roles2.some((role) => role.startsWith("contact."))) {+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ const isWheelContact = roles.some((role) => role.startsWith("wheel.contact."));+ if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {explicitContacts.push({node,contactY: localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(node.matrixWorld)).y,source: "contact"});}- if (roles2.some((role) => role.startsWith("support."))) {+ if (roles.some((role) => role.startsWith("support."))) {const contactY = renderableMinYInRoot(inverse, node);if (contactY !== undefined)supports.push({ node, contactY, source: "support" });@@ -13255,7 +13263,7 @@ function propulsionFindings(context, root, intent) {});const findings = [];root.updateWorldMatrix(true, false);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();for (const kind of expectedKinds) {const candidates = components.filter((part) => part.kind === kind);if (candidates.length === 0) {@@ -13272,7 +13280,7 @@ function propulsionFindings(context, root, intent) {const box = new THREE21.Box3().setFromObject(component.node);const center = box.isEmpty() ? undefined : box.getCenter(new THREE21.Vector3);const pivotCenter = pivot ? new THREE21.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;- const delta = center && pivotCenter ? localPoint2(rootInverse2, center).distanceTo(localPoint2(rootInverse2, pivotCenter)) : Infinity;+ const delta = center && pivotCenter ? localPoint2(rootInverse, center).distanceTo(localPoint2(rootInverse, pivotCenter)) : Infinity;const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);const canonicalAxis = kind === "rotor" ? new THREE21.Vector3(0, 1, 0) : new THREE21.Vector3(1, 0, 0);@@ -13343,7 +13351,7 @@ var init_vehicle2 = __esm(() => {owner: KILN_ENGINE_QA_OWNER,promotion: conformancePromotionAuthorization("vehicle-qa-v1", "src/qa/vehicle.test.ts", "4bffa0dff0ed33be2ce7003ee36ac33efc5b4900e57d390898e43551912e626b"),defaultMode: "enforce",- evaluate: (context) => evaluateVehicleQa(context).filter((finding2) => finding2.disposition === "block")+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition === "block")};VEHICLE_ADVISORY_QA_RULE = {id: "VEHICLE_ADVISORY_PROFILE",@@ -13352,7 +13360,7 @@ var init_vehicle2 = __esm(() => {ruleClass: "heuristic",owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",- evaluate: (context) => evaluateVehicleQa(context).filter((finding2) => finding2.disposition !== "block")+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition !== "block")};VEHICLE_QA_RULES = [VEHICLE_QA_RULE,@@ -13377,17 +13385,17 @@ function pathOf(node, root) {}return names.reverse().join("/");}-function localPoint3(rootInverse2, node) {- return node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse2);+function localPoint3(rootInverse, node) {+ return node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse);}-function meshLocalBox(mesh, rootInverse2) {+function meshLocalBox(mesh, rootInverse) {if (!(mesh.geometry instanceof THREE22.BufferGeometry))return;mesh.geometry.computeBoundingBox();const source = mesh.geometry.boundingBox;if (!source || source.isEmpty())return;- const transform = rootInverse2.clone().multiply(mesh.matrixWorld);+ const transform = rootInverse.clone().multiply(mesh.matrixWorld);const result = new THREE22.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {@@ -13408,8 +13416,8 @@ function collectRenderableBounds(root) {const box = meshLocalBox(node, inverse);if (!box)return;- const roles2 = rolesOf(node);- values.push({ node, box, roles: roles2, source: roles2.length > 0 ? "semantic" : "fallback" });+ const roles = rolesOf(node);+ values.push({ node, box, roles, source: roles.length > 0 ? "semantic" : "fallback" });});return values;}@@ -13430,15 +13438,15 @@ function evaluateVegetationContactQa(context) {const semanticSupports = [];root.traverse((node) => {const metadata = readSemanticMetadataV1(node);- const roles2 = metadata?.roles ?? [];- if (roles2.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {+ const roles = metadata?.roles ?? [];+ if (roles.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {const frame = metadata?.frames.find((value) => value.id === "ground-contact" || value.id === "vegetation-ground-contact");contacts.push({node,...frame ? { frameTranslation: frame.translation } : {}});}- if (roles2.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {+ if (roles.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {semanticSupports.push(node);}});@@ -13539,8 +13547,8 @@ function evaluateVegetationScopeQa(context) {const materialEvidence = materialNames(value.node).some((name) => CLUTTER_NAME.test(name));const footprintRatio = size.x * size.z / Math.max(0.000000001, overallSize.x * overallSize.z);const flatEvidence = footprintRatio >= 0.35 && size.y <= Math.max(0.08, overallSize.y * 0.08) && center.y <= VEGETATION_CONTACT_TOLERANCE_METERS + size.y;- const evidence2 = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);- if (evidence2.length < 2)+ const evidence = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);+ if (evidence.length < 2)continue;findings.push(finding2(context, {code: "VEG_SCOPE_EXTRA",@@ -13573,7 +13581,7 @@ function unionVolume(boxes) {const size = union.getSize(new THREE22.Vector3);return size.x * size.y * size.z;}-function projectedOccupancy(boxes, axes2) {+function projectedOccupancy(boxes, axes) {if (boxes.length === 0)return 0;const minimum = [Infinity, Infinity];@@ -13582,8 +13590,8 @@ function projectedOccupancy(boxes, axes2) {const min = [box.min.x, box.min.y, box.min.z];const max = [box.max.x, box.max.y, box.max.z];for (const dimension of [0, 1]) {- minimum[dimension] = Math.min(minimum[dimension], min[axes2[dimension]]);- maximum[dimension] = Math.max(maximum[dimension], max[axes2[dimension]]);+ minimum[dimension] = Math.min(minimum[dimension], min[axes[dimension]]);+ maximum[dimension] = Math.max(maximum[dimension], max[axes[dimension]]);}}const spans = [maximum[0] - minimum[0], maximum[1] - minimum[1]];@@ -13593,10 +13601,10 @@ function projectedOccupancy(boxes, axes2) {for (const box of boxes) {const min = [box.min.x, box.min.y, box.min.z];const max = [box.max.x, box.max.y, box.max.z];- const x0 = Math.max(0, Math.floor((min[axes2[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes2[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const y0 = Math.max(0, Math.floor((min[axes2[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));- const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes2[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ const x0 = Math.max(0, Math.floor((min[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const y0 = Math.max(0, Math.floor((min[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));for (let y = y0;y <= y1; y++) {for (let x = x0;x <= x1; x++)occupied[y * RASTER_SIZE + x] = 1;@@ -13611,9 +13619,9 @@ function matchesAny(value, patterns) {function measurementSource(values) {if (values.length === 0)return "none";- const semantic3 = values.some((value) => value.source === "semantic");+ const semantic = values.some((value) => value.source === "semantic");const fallback = values.some((value) => value.source === "fallback");- return semantic3 && fallback ? "mixed" : semantic3 ? "semantic" : "fallback";+ return semantic && fallback ? "mixed" : semantic ? "semantic" : "fallback";}function roleOrNameSource(value, patterns) {if (value.roles.some((role) => patterns.some((pattern) => pattern.test(role))))@@ -13637,7 +13645,7 @@ function growthCandidates(root) {function boxDistanceToPoint(box, point) {return box.distanceToPoint(point);}-function endpointRadius(position, axis, axisValue, tolerance, scale2) {+function endpointRadius(position, axis, axisValue, tolerance, scale) {const radialAxes = [0, 1, 2].filter((value) => value !== axis);const points = [];const point = new THREE22.Vector3;@@ -13655,8 +13663,8 @@ function endpointRadius(position, axis, axisValue, tolerance, scale2) {}let radius = 0;for (const value of points) {- const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale2.getComponent(radialAxes[0]));- const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale2.getComponent(radialAxes[1]));+ const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale.getComponent(radialAxes[0]));+ const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale.getComponent(radialAxes[1]));radius = Math.max(radius, Math.hypot(a, b));}return { center, radius };@@ -13664,12 +13672,12 @@ function endpointRadius(position, axis, axisValue, tolerance, scale2) {function growthNodeMeasurement(root, candidate, allCandidates, band) {if (!(candidate.node instanceof THREE22.Mesh))return;- const geometry2 = candidate.node.geometry;- const position = geometry2.getAttribute("position");+ const geometry = candidate.node.geometry;+ const position = geometry.getAttribute("position");if (!position || position.count < 2)return;- geometry2.computeBoundingBox();- const geometryBox = geometry2.boundingBox;+ geometry.computeBoundingBox();+ const geometryBox = geometry.boundingBox;if (!geometryBox || geometryBox.isEmpty())return;root.updateWorldMatrix(true, true);@@ -13705,10 +13713,10 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {}const baseRadius = firstIsBase ? first.radius : second.radius;const tipRadius = firstIsBase ? second.radius : first.radius;- const length3 = firstPoint.distanceTo(secondPoint);+ const length = firstPoint.distanceTo(secondPoint);const averageRadius = (baseRadius + tipRadius) / 2;const taperRatio = baseRadius > 0.000000001 ? tipRadius / baseRadius : null;- const lengthRadiusRatio = averageRadius > 0.000000001 ? length3 / averageRadius : null;+ const lengthRadiusRatio = averageRadius > 0.000000001 ? length / averageRadius : null;const selected = band[candidate.kind];const taperOutlier = taperRatio !== null && (taperRatio < selected.taper[0] || taperRatio > selected.taper[1]);const lengthRadiusOutlier = lengthRadiusRatio !== null && (lengthRadiusRatio < selected.lengthRadius[0] || lengthRadiusRatio > selected.lengthRadius[1]);@@ -13717,7 +13725,7 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {nodePath: pathOf(candidate.node, root),kind: candidate.kind,source: candidate.growthSource,- lengthMeters: stable3(length3),+ lengthMeters: stable3(length),baseRadiusMeters: stable3(baseRadius),tipRadiusMeters: stable3(tipRadius),taperRatio: taperRatio === null ? null : stable3(taperRatio),@@ -13837,12 +13845,12 @@ function evaluateVegetationFoliageAttachmentQa(context) {}function relativeTransformSignature(root, node) {const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);- const scale2 = new THREE22.Vector3;+ const scale = new THREE22.Vector3;const quaternion = new THREE22.Quaternion;- matrix.decompose(new THREE22.Vector3, quaternion, scale2);+ matrix.decompose(new THREE22.Vector3, quaternion, scale);if (quaternion.w < 0)quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);- const values = [...scale2.toArray(), ...quaternion.toArray()].map((value) => stable3(value));+ const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable3(value));return values.join(",");}function measureVegetationRepetition(intent, root) {@@ -14020,8 +14028,8 @@ function materialValue(material) {if (!(material instanceof THREE22.MeshStandardMaterial) && !(material instanceof THREE22.MeshBasicMaterial)) {return;}- const color2 = material.color;- return 0.2126 * color2.r + 0.7152 * color2.g + 0.0722 * color2.b;+ const color = material.color;+ return 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;}function measureVegetationFoliageMaterials(intent, root) {const values = [];@@ -14225,23 +14233,23 @@ function transformedBox(source, transform) {}function collectParts(root) {root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverse((node) => {- const roles2 = rolesOf2(node);+ const roles = rolesOf2(node);const renderable = node instanceof THREE23.Mesh;let box;if (renderable && node.geometry instanceof THREE23.BufferGeometry) {node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {- box = transformedBox(node.geometry.boundingBox, rootInverse2.clone().multiply(node.matrixWorld));+ box = transformedBox(node.geometry.boundingBox, rootInverse.clone().multiply(node.matrixWorld));}- } else if (roles2.length > 0) {- box = transformedBox(new THREE23.Box3(new THREE23.Vector3(-0.5, -0.5, -0.5), new THREE23.Vector3(0.5, 0.5, 0.5)), rootInverse2.clone().multiply(node.matrixWorld));+ } else if (roles.length > 0) {+ box = transformedBox(new THREE23.Box3(new THREE23.Vector3(-0.5, -0.5, -0.5), new THREE23.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));}if (box?.isEmpty())box = undefined;- result.push({ node, roles: roles2, ...box ? { box } : {}, renderable });+ result.push({ node, roles, ...box ? { box } : {}, renderable });});return result;}@@ -14311,9 +14319,9 @@ function allowedClearanceContactRoles(assembly) {const result = new Set;for (const part of [assembly.pivot, assembly.clearance]) {const metadata = part ? readSemanticMetadataV1(part.node) : undefined;- for (const relationship2 of metadata?.relationships ?? []) {- if (relationship2.targetType === "role" && /^(?:mountedTo|allowsContact|allowsClearanceContact)$/.test(relationship2.kind) && /^prop\.articulation\.support\.[^.]+$/.test(relationship2.target)) {- result.add(relationship2.target);+ for (const relationship of metadata?.relationships ?? []) {+ if (relationship.targetType === "role" && /^(?:mountedTo|allowsContact|allowsClearanceContact)$/.test(relationship.kind) && /^prop\.articulation\.support\.[^.]+$/.test(relationship.target)) {+ result.add(relationship.target);}}}@@ -14912,35 +14920,35 @@ function isEvidence(value) {const candidate = value;return candidate.schemaVersion === 1 && typeof candidate.silhouetteIoU === "number" && typeof candidate.colorAgreement === "number" && typeof candidate.reference === "object" && typeof candidate.rendered === "object";}-function referenceComparisonFindings(evidence2, profile) {- if (evidence2.reference.coverage <= 0 || evidence2.rendered.coverage <= 0)+function referenceComparisonFindings(evidence, profile) {+ if (evidence.reference.coverage <= 0 || evidence.rendered.coverage <= 0)return [];const findings = [];- if (evidence2.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {+ if (evidence.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {findings.push({code: "REF_SILHOUETTE_AGREEMENT",disposition: "observe",dimension: "promptAlignment",profile,- message: `The asset's outline agrees with the reference image on ${(evidence2.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,+ message: `The asset's outline agrees with the reference image on ${(evidence.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,measurement: {name: "silhouetteIoU",- actual: evidence2.silhouetteIoU,+ actual: evidence.silhouetteIoU,threshold: SILHOUETTE_IOU_OBSERVE},repairText: "Compare the reference against the rendered views and adjust the overall proportions — the outline is the part that disagrees, not the detail."});}- if (evidence2.colorAgreement < COLOR_AGREEMENT_OBSERVE) {+ if (evidence.colorAgreement < COLOR_AGREEMENT_OBSERVE) {findings.push({code: "REF_COLOR_AGREEMENT",disposition: "observe",dimension: "promptAlignment",profile,- message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence2.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,+ message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,measurement: {name: "colorAgreement",- actual: evidence2.colorAgreement,+ actual: evidence.colorAgreement,threshold: COLOR_AGREEMENT_OBSERVE},repairText: "Set the base colours from the reference image rather than from the prompt wording, then re-render."@@ -14959,19 +14967,19 @@ var init_reference_comparison = __esm(() => {owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",evaluate(context) {- const evidence2 = context.derivedEvidence?.["referenceComparison"];- if (!isEvidence(evidence2))+ const evidence = context.derivedEvidence?.["referenceComparison"];+ if (!isEvidence(evidence))return [];- return referenceComparisonFindings(evidence2, "reference.comparison");+ return referenceComparisonFindings(evidence, "reference.comparison");}});});// src/qa/self-intersection.tsimport * as THREE25 from "three";-function triangleCount(geometry2) {- const index = geometry2.getIndex();- const position = geometry2.getAttribute("position");+function triangleCount(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");if (!position)return 0;return Math.floor((index ? index.count : position.count) / 3);@@ -15002,8 +15010,8 @@ function collectParts3(root, skipped) {return parts;}function meshToArrays(mesh) {- const geometry2 = mesh.geometry;- const position = geometry2.getAttribute("position");+ const geometry = mesh.geometry;+ const position = geometry.getAttribute("position");if (!position)return null;const matrix = mesh.matrixWorld;@@ -15015,7 +15023,7 @@ function meshToArrays(mesh) {verts[i * 3 + 1] = v.y;verts[i * 3 + 2] = v.z;}- const index = geometry2.getIndex();+ const index = geometry.getIndex();let tris;if (index) {if (index.count % 3 !== 0)@@ -15062,7 +15070,7 @@ async function analyzePartPenetration(root) {const Module = await import("manifold-3d");const wasm = await Module.default();wasm.setup();- const { Manifold, Mesh: Mesh9 } = wasm;+ const { Manifold, Mesh } = wasm;const cache = new Map;const build = (part) => {if (cache.has(part.mesh))@@ -15071,7 +15079,7 @@ async function analyzePartPenetration(root) {try {const arrays = meshToArrays(part.mesh);if (arrays) {- const mesh = new Mesh9({ numProp: 3, ...arrays });+ const mesh = new Mesh({ numProp: 3, ...arrays });mesh.merge();solid = new Manifold(mesh);} else {@@ -15124,8 +15132,8 @@ async function analyzePartPenetration(root) {return base;}function readEvidence(context) {- const evidence2 = context.derivedEvidence?.["partPenetration"];- return evidence2?.schemaVersion === 1 ? evidence2 : undefined;+ const evidence = context.derivedEvidence?.["partPenetration"];+ return evidence?.schemaVersion === 1 ? evidence : undefined;}var MAX_PART_TRIANGLES = 20000, MAX_NARROW_PHASE_PAIRS = 64, CONTACT_VOLUME_FRACTION = 0.001, round = (n) => Math.round(n * 1e9) / 1e9, SELF_INTERSECTION_QA_RULE;var init_self_intersection = __esm(() => {@@ -15138,10 +15146,10 @@ var init_self_intersection = __esm(() => {owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",evaluate(context) {- const evidence2 = readEvidence(context);- if (!evidence2)+ const evidence = readEvidence(context);+ if (!evidence)return [];- const findings = evidence2.penetrations.map((pair) => ({+ const findings = evidence.penetrations.map((pair) => ({code: "GEO_PART_SELF_INTERSECTION",disposition: "observe",dimension: "visualQuality",@@ -15155,13 +15163,13 @@ var init_self_intersection = __esm(() => {},repairText: "Move one part clear of the other, or subtract it with boolDiff so the overlap becomes a real cut instead of two solids in the same place."}));- if (evidence2.truncated) {+ if (evidence.truncated) {findings.push({code: "GEO_PART_SELF_INTERSECTION_TRUNCATED",disposition: "observe",dimension: "visualQuality",profile: "geometry.selfIntersection",- message: `Only ${evidence2.pairsTested} of ${evidence2.candidatePairs} overlapping part pairs were checked (analysis budget). Parts beyond that were not examined.`+ message: `Only ${evidence.pairsTested} of ${evidence.candidatePairs} overlapping part pairs were checked (analysis budget). Parts beyond that were not examined.`});}return findings;@@ -15205,20 +15213,20 @@ function orientedBoxFromLocalBounds(root, node, source) {return;const position = new THREE26.Vector3;const rotation = new THREE26.Quaternion;- const scale2 = new THREE26.Vector3;- relative.decompose(position, rotation, scale2);- const recomposed = new THREE26.Matrix4().compose(position, rotation, scale2);+ const scale = new THREE26.Vector3;+ relative.decompose(position, rotation, scale);+ const recomposed = new THREE26.Matrix4().compose(position, rotation, scale);const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));if (residual > 0.00001)return;const center = source.getCenter(new THREE26.Vector3).applyMatrix4(relative);const sourceHalf = source.getSize(new THREE26.Vector3).multiplyScalar(0.5);const halfExtents = [- Math.abs(sourceHalf.x * scale2.x),- Math.abs(sourceHalf.y * scale2.y),- Math.abs(sourceHalf.z * scale2.z)+ Math.abs(sourceHalf.x * scale.x),+ Math.abs(sourceHalf.y * scale.y),+ Math.abs(sourceHalf.z * scale.z)];- if (halfExtents.some((extent2) => !Number.isFinite(extent2) || extent2 <= 0.000000001))+ if (halfExtents.some((extent) => !Number.isFinite(extent) || extent <= 0.000000001))return;rotation.normalize();return createOrientedProbeBox3({@@ -15229,10 +15237,10 @@ function orientedBoxFromLocalBounds(root, node, source) {}function collectParts4(root) {root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverse((node) => {- const roles2 = rolesOf3(node);+ const roles = rolesOf3(node);const renderable = node instanceof THREE26.Mesh;let box;let orientedBox;@@ -15242,18 +15250,18 @@ function collectParts4(root) {if (node.geometry.boundingBox) {source = node.geometry.boundingBox;}- } else if (roles2.length > 0) {+ } else if (roles.length > 0) {source = new THREE26.Box3(new THREE26.Vector3(-0.5, -0.5, -0.5), new THREE26.Vector3(0.5, 0.5, 0.5));}if (source) {- box = transformedBox2(source, rootInverse2.clone().multiply(node.matrixWorld));+ box = transformedBox2(source, rootInverse.clone().multiply(node.matrixWorld));orientedBox = orientedBoxFromLocalBounds(root, node, source);}if (box?.isEmpty())box = undefined;result.push({node,- roles: roles2,+ roles,...box ? { box } : {},...orientedBox ? { orientedBox } : {},renderable@@ -15270,8 +15278,8 @@ function resolveSocket(root, node, socket) {if (!frame)return;root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();- const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse2);+ const rootInverse = root.matrixWorld.clone().invert();+ const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);const rootInverseQuaternion = root.getWorldQuaternion(new THREE26.Quaternion).invert();const rotation = node.getWorldQuaternion(new THREE26.Quaternion).multiply(new THREE26.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();return {@@ -15291,9 +15299,9 @@ function resolveEnvironmentSockets(root) {for (const socket of metadata?.sockets ?? []) {if (!socket.type.startsWith("environment."))continue;- const resolved2 = resolveSocket(root, node, socket);- if (resolved2)- result.push(resolved2);+ const resolved = resolveSocket(root, node, socket);+ if (resolved)+ result.push(resolved);}});return result.sort((a, b) => `${a.type}:${a.id}`.localeCompare(`${b.type}:${b.id}`));@@ -15329,11 +15337,11 @@ function evaluateEnvironmentSocketQa(context) {}for (const axis of ["x", "z"]) {const negative = socketByType(sockets, `environment.tile.${axis}-negative`);- const positive3 = socketByType(sockets, `environment.tile.${axis}-positive`);- if (!negative || !positive3)+ const positive = socketByType(sockets, `environment.tile.${axis}-positive`);+ if (!negative || !positive)continue;- const cross2 = axis === "x" ? 2 : 0;- const crossDelta = Math.hypot(negative.translation[1] - positive3.translation[1], negative.translation[cross2] - positive3.translation[cross2]);+ const cross = axis === "x" ? 2 : 0;+ const crossDelta = Math.hypot(negative.translation[1] - positive.translation[1], negative.translation[cross] - positive.translation[cross]);if (crossDelta <= SOCKET_ALIGNMENT_TOLERANCE_METERS)continue;findings.push(finding4(context, {@@ -15341,7 +15349,7 @@ function evaluateEnvironmentSocketQa(context) {disposition: "block",dimension: "categoryReadiness",message: `Opposing ${axis.toUpperCase()} tile sockets differ by ${crossDelta.toFixed(6)} m in their paired height/cross-axis frame.`,- affected: { node: positive3.node, attribute: positive3.id },+ affected: { node: positive.node, attribute: positive.id },measurement: {name: "socketCrossAxisDelta",actual: stable5(crossDelta),@@ -15359,8 +15367,8 @@ function materialSignature(material) {const values = Array.isArray(material) ? material : [material];return values.map((value) => {const standard = value;- const color2 = standard.color?.getHexString?.() ?? "none";- return `${value.type}:${value.name}:${color2}`;+ const color = standard.color?.getHexString?.() ?? "none";+ return `${value.type}:${value.name}:${color}`;}).sort().join("|");}function boundarySamples(root, axis, side, bins = 12) {@@ -15402,15 +15410,15 @@ function boundarySamples(root, axis, side, bins = 12) {}function edgePairMeasurements(root, axis, sockets) {const negative = boundarySamples(root, axis, "negative");- const positive3 = boundarySamples(root, axis, "positive");+ const positive = boundarySamples(root, axis, "positive");const negativeByBin = new Map(negative.map((sample) => [sample.bin, sample]));- const pairs = positive3.flatMap((sample) => {+ const pairs = positive.flatMap((sample) => {const other = negativeByBin.get(sample.bin);return other ? [[other, sample]] : [];});const unionBins = new Set([...negative.map((sample) => sample.bin),- ...positive3.map((sample) => sample.bin)+ ...positive.map((sample) => sample.bin)]);const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE26.MathUtils.radToDeg(Math.acos(THREE26.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;@@ -15793,12 +15801,12 @@ function artifactEvidence(context) {function finding5(context, value, profile = "vfx.w7") {return { ...value, profile: context.intent.qaProfile || profile };}-function measureVfxRuntimeCostV1(evidence2) {+function measureVfxRuntimeCostV1(evidence) {let blendedScreenAreaRatio = 0;let transparentLayerCount = 0;let overdrawProxy = 0;let textureMemoryBytes = 0;- for (const material of evidence2.materials) {+ for (const material of evidence.materials) {textureMemoryBytes += material.textureMemoryBytes;if (material.alphaMode !== "blend")continue;@@ -15812,7 +15820,7 @@ function measureVfxRuntimeCostV1(evidence2) {transparentLayerCount,overdrawProxy: stable6(overdrawProxy),textureMemoryBytes,- shaderSidecarRequired: evidence2.sidecar !== undefined+ shaderSidecarRequired: evidence.sidecar !== undefined};}function exactVfxIntent(context) {@@ -15836,8 +15844,8 @@ function exactVfxIntent(context) {]};}- const evidence2 = artifactEvidence(context);- if (!evidence2) {+ const evidence = artifactEvidence(context);+ if (!evidence) {return {findings: [finding5(context, {@@ -15851,17 +15859,17 @@ function exactVfxIntent(context) {]};}- return { intent: validated.value, evidence: evidence2 };+ return { intent: validated.value, evidence };}function evaluateVfxExactQa(context) {if (context.intent.category !== "vfx")return [];- const resolved2 = exactVfxIntent(context);- if ("findings" in resolved2)- return resolved2.findings;- const { intent, evidence: evidence2 } = resolved2;+ const resolved = exactVfxIntent(context);+ if ("findings" in resolved)+ return resolved.findings;+ const { intent, evidence } = resolved;const findings = [];- const effectMaterials = evidence2.materials.filter((material) => material.effectSurface !== false);+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface !== false);if (effectMaterials.length === 0) {findings.push(finding5(context, {code: "VFX_EFFECT_SURFACE_MISSING",@@ -15932,7 +15940,7 @@ function evaluateVfxExactQa(context) {}const facingFields = ["mode", "normalAxis", "directionAxis"];for (const field of facingFields) {- if (intent.facing[field] === evidence2.facing[field])+ if (intent.facing[field] === evidence.facing[field])continue;if (intent.facing.source !== "explicit")continue;@@ -15943,14 +15951,14 @@ function evaluateVfxExactQa(context) {message: `Explicit VFX facing ${field} does not match the emitted runtime contract.`,measurement: {name: `facing.${field}`,- actual: evidence2.facing[field] ?? null,+ actual: evidence.facing[field] ?? null,expected: intent.facing[field] ?? null},repairText: `Stamp and implement the requested ${field}; preserve the canonical Kiln frame.`}));}const requestedAnimation = intent.animation;- const actualAnimation = evidence2.animation;+ const actualAnimation = evidence.animation;for (const field of ["playback", "endpointBehavior", "driver"]) {if (requestedAnimation[field] === actualAnimation[field])continue;@@ -15993,7 +16001,7 @@ function evaluateVfxExactQa(context) {repairText: "Make the final loop sample equal the initial sample for every driven channel."}));}- if (requestedAnimation.driver === "clip" && !evidence2.clips.some((clip) => clip.name === requestedAnimation.clipName && Math.abs(clip.durationSeconds - requestedAnimation.durationSeconds) <= 0.000001)) {+ if (requestedAnimation.driver === "clip" && !evidence.clips.some((clip) => clip.name === requestedAnimation.clipName && Math.abs(clip.durationSeconds - requestedAnimation.durationSeconds) <= 0.000001)) {findings.push(finding5(context, {code: "VFX_REQUIRED_CLIP_MISSING",disposition: "block",@@ -16003,7 +16011,7 @@ function evaluateVfxExactQa(context) {repairText: `Emit clip ${requestedAnimation.clipName ?? "<declared clip>"} with the requested duration.`}));}- if (requestedAnimation.driver === "timeUniform" && !evidence2.uniforms.includes(requestedAnimation.timeUniformName ?? "")) {+ if (requestedAnimation.driver === "timeUniform" && !evidence.uniforms.includes(requestedAnimation.timeUniformName ?? "")) {findings.push(finding5(context, {code: "VFX_REQUIRED_TIME_UNIFORM_MISSING",disposition: "block",@@ -16011,13 +16019,13 @@ function evaluateVfxExactQa(context) {message: "The declared runtime time uniform is absent from the sidecar evidence.",measurement: {name: "timeUniformName",- actual: evidence2.uniforms.join(","),+ actual: evidence.uniforms.join(","),expected: requestedAnimation.timeUniformName ?? null},repairText: `Expose ${requestedAnimation.timeUniformName ?? "the declared uniform"} in the runtime sidecar.`}));}- if (intent.portability === "portable" && evidence2.sidecar !== undefined) {+ if (intent.portability === "portable" && evidence.sidecar !== undefined) {findings.push(finding5(context, {code: "VFX_UNDECLARED_SIDECAR",disposition: "block",@@ -16026,7 +16034,7 @@ function evaluateVfxExactQa(context) {repairText: "Bake the portable appearance into standard glTF materials or update trusted intent before spend."}));}- if (intent.portability === "sidecar" && (evidence2.sidecar?.id !== intent.sidecar?.id || evidence2.sidecar?.version !== intent.sidecar?.version)) {+ if (intent.portability === "sidecar" && (evidence.sidecar?.id !== intent.sidecar?.id || evidence.sidecar?.version !== intent.sidecar?.version)) {findings.push(finding5(context, {code: "VFX_SIDECAR_IDENTITY_MISMATCH",disposition: "block",@@ -16034,7 +16042,7 @@ function evaluateVfxExactQa(context) {message: "Runtime VFX sidecar identity/version does not match trusted intent.",measurement: {name: "sidecarIdentity",- actual: evidence2.sidecar ? `${evidence2.sidecar.id}@${evidence2.sidecar.version}` : null,+ actual: evidence.sidecar ? `${evidence.sidecar.id}@${evidence.sidecar.version}` : null,expected: intent.sidecar ? `${intent.sidecar.id}@${intent.sidecar.version}` : null},repairText: "Attach the exact declared sidecar identity and keep the GLB fallback honest."@@ -16047,12 +16055,12 @@ function evaluateVfxAdvisoryQa(context) {return [];const intent = context.intent.vfx;const validated = validateVfxIntentV1(intent);- const evidence2 = artifactEvidence(context);- if (!validated.valid || !validated.value || !evidence2)+ const evidence = artifactEvidence(context);+ if (!validated.valid || !validated.value || !evidence)return [];const findings = [];if (validated.value.facing.source === "inferred") {- const mismatch = ["mode", "normalAxis", "directionAxis"].some((field) => validated.value?.facing[field] !== evidence2.facing[field]);+ const mismatch = ["mode", "normalAxis", "directionAxis"].some((field) => validated.value?.facing[field] !== evidence.facing[field]);if (mismatch) {findings.push(finding5(context, {code: "VFX_FACING_INFERRED_DRIFT",@@ -16063,7 +16071,7 @@ function evaluateVfxAdvisoryQa(context) {}));}}- const cost = measureVfxRuntimeCostV1(evidence2);+ const cost = measureVfxRuntimeCostV1(evidence);findings.push(finding5(context, {code: "VFX_RUNTIME_COST_REPORT",disposition: "observe",@@ -16150,7 +16158,7 @@ function evaluateAssetScopeQa(context) {}, "scope.w7")];}-var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), stable6 = (value) => Math.round(value * 1e6) / 1e6, finiteTuple2 = (value, length3) => Array.isArray(value) && value.length === length3 && value.every((component) => typeof component === "number" && Number.isFinite(component)), VFX_EXACT_QA_RULE, VFX_ADVISORY_QA_RULE, MODULAR_JOIN_QA_RULE, ASSET_SCOPE_QA_RULE, W7_BREADTH_QA_RULES;+var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), stable6 = (value) => Math.round(value * 1e6) / 1e6, finiteTuple2 = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), VFX_EXACT_QA_RULE, VFX_ADVISORY_QA_RULE, MODULAR_JOIN_QA_RULE, ASSET_SCOPE_QA_RULE, W7_BREADTH_QA_RULES;var init_breadth2 = __esm(() => {init_breadth();init_registry();@@ -16220,10 +16228,10 @@ function isTexture(value) {function isAnimationClip(value) {return record3(value) && typeof value.name === "string" && typeof value.duration === "number" && Number.isFinite(value.duration) && Array.isArray(value.tracks);}-function localRenderableBox(rootInverse2, node) {+function localRenderableBox(rootInverse, node) {if (isSpriteNode(node)) {- const transform2 = rootInverse2.clone().multiply(node.matrixWorld);- return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform2);+ const transform = rootInverse.clone().multiply(node.matrixWorld);+ return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);}if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)return;@@ -16231,7 +16239,7 @@ function localRenderableBox(rootInverse2, node) {const source = node.geometry.boundingBox;if (!source || source.isEmpty())return;- const transform = rootInverse2.clone().multiply(node.matrixWorld);+ const transform = rootInverse.clone().multiply(node.matrixWorld);const result = new THREE27.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {@@ -16281,8 +16289,8 @@ function materialTextures2(material) {}function materialTextureBytes(material) {return materialTextures2(material).reduce((sum, texture) => {- const dimensions2 = textureDimensions(texture);- return sum + (dimensions2 ? Math.ceil(dimensions2[0] * dimensions2[1] * 4 * (4 / 3)) : 0);+ const dimensions = textureDimensions(texture);+ return sum + (dimensions ? Math.ceil(dimensions[0] * dimensions[1] * 4 * (4 / 3)) : 0);}, 0);}function alphaMode(material) {@@ -16298,15 +16306,15 @@ function alphaData(material) {return (standard.opacity ?? 1) < 1 || standard.alphaMap !== undefined && standard.alphaMap !== null || textureHasAlpha2(standard.alphaMap) || textureHasAlpha2(standard.map) || (standard.alphaTest ?? 0) > 0 && standard.alphaMap !== undefined && standard.alphaMap !== null;}function surfaceRole(nodes, intent) {- const evidence2 = nodes.flatMap((node) => [+ const evidence = nodes.flatMap((node) => [node.name,...readSemanticMetadataV1(node)?.roles ?? []]);- if (evidence2.some((value) => /(?:^|[._ -])beam(?:$|[._ -])/i.test(value)))+ if (evidence.some((value) => /(?:^|[._ -])beam(?:$|[._ -])/i.test(value)))return "beam";- if (evidence2.some((value) => /(?:^|[._ -])trail(?:$|[._ -])/i.test(value)))+ if (evidence.some((value) => /(?:^|[._ -])trail(?:$|[._ -])/i.test(value)))return "trail";- if (evidence2.some((value) => /(?:^|[._ -])(?:volume|aura|portal)(?:$|[._ -])/i.test(value))) {+ if (evidence.some((value) => /(?:^|[._ -])(?:volume|aura|portal)(?:$|[._ -])/i.test(value))) {return "volume";}if (intent.subtype === "beam")@@ -16389,13 +16397,13 @@ function dominantGeometryAxis(root, mode) {const bounds = node.geometry.boundingBox;if (!bounds || bounds.isEmpty())return;- const size2 = bounds.getSize(new THREE27.Vector3);- const axes2 = [- { score: size2.x, direction: new THREE27.Vector3(1, 0, 0) },- { score: size2.y, direction: new THREE27.Vector3(0, 1, 0) },- { score: size2.z, direction: new THREE27.Vector3(0, 0, 1) }+ const size = bounds.getSize(new THREE27.Vector3);+ const axes = [+ { score: size.x, direction: new THREE27.Vector3(1, 0, 0) },+ { score: size.y, direction: new THREE27.Vector3(0, 1, 0) },+ { score: size.z, direction: new THREE27.Vector3(0, 0, 1) }];- const selected = axes2.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);+ const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const relative = inverse.clone().multiply(node.matrixWorld);const direction = selected.direction.transformDirection(relative);const score = selected.score * node.getWorldScale(new THREE27.Vector3).length();@@ -16506,10 +16514,10 @@ function analyzeAssetScopeObservationV1(root) {root.traverse((node) => {if ((isMeshNode(node) || isSpriteNode(node)) && node.visible)renderableCount++;- const roles2 = readSemanticMetadataV1(node)?.roles ?? [];- if (roles2.some((role) => MEMBER_ROLE.test(role)))+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ if (roles.some((role) => MEMBER_ROLE.test(role)))members.add(node);- for (const role of roles2)+ for (const role of roles)if (DRESSING_ROLE.test(role))dressing.add(role);if (node !== root && DRESSING_NAME.test(node.name))@@ -16535,7 +16543,7 @@ function pathOf2(root, node) {}function analyzeSockets(root) {root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();+ const rootInverse = root.matrixWorld.clone().invert();const rootWorldRotation = root.getWorldQuaternion(new THREE27.Quaternion).invert();const values = [];root.traverse((node) => {@@ -16549,7 +16557,7 @@ function analyzeSockets(root) {continue;const frameRotation = new THREE27.Quaternion(...frame.rotation);const worldRotation = rootWorldRotation.clone().multiply(nodeWorldRotation).multiply(frameRotation);- const position = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse2);+ const position = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);const normal = new THREE27.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();values.push({contract: {@@ -16634,10 +16642,10 @@ var init_breadth_evidence = __esm(() => {function createAssetQaReportV1(intent, options = {}) {const findings = [...options.findings ?? []];const evaluated = new Set(options.evaluatedDimensions ?? []);- for (const finding6 of findings)- evaluated.add(finding6.dimension);- const dimensions2 = Object.fromEntries(QA_DIMENSIONS.map((dimension) => {- const dimensionFindings = findings.filter((finding6) => finding6.dimension === dimension);+ for (const finding of findings)+ evaluated.add(finding.dimension);+ const dimensions = Object.fromEntries(QA_DIMENSIONS.map((dimension) => {+ const dimensionFindings = findings.filter((finding) => finding.dimension === dimension);const result = {status: evaluated.has(dimension) ? statusForFindings(dimensionFindings) : "notEvaluated",findings: dimensionFindings,@@ -16645,20 +16653,20 @@ function createAssetQaReportV1(intent, options = {}) {};return [dimension, result];}));- const statuses = QA_DIMENSIONS.map((dimension) => dimensions2[dimension].status);+ const statuses = QA_DIMENSIONS.map((dimension) => dimensions[dimension].status);const disposition = statuses.includes("block") ? "block" : statuses.includes("warn") ? "warn" : statuses.every((status) => status === "notEvaluated") ? "notEvaluated" : "pass";return {schemaVersion: 1,category: intent.category,qaProfile: intent.qaProfile,disposition,- dimensions: dimensions2+ dimensions};}var QA_DIMENSIONS, statusForFindings = (findings) => {- if (findings.some((finding6) => finding6.disposition === "block"))+ if (findings.some((finding) => finding.disposition === "block"))return "block";- if (findings.some((finding6) => finding6.disposition === "warn"))+ if (findings.some((finding) => finding.disposition === "warn"))return "warn";return "pass";};@@ -16681,20 +16689,20 @@ function sceneNodes(context) {return [];const nodes = [];const seen = new Set;- const add2 = (node) => {+ const add = (node) => {if (!seen.has(node)) {seen.add(node);nodes.push(node);}};if (typeof context.scene.traverse === "function") {- context.scene.traverse(add2);+ context.scene.traverse(add);return nodes;}const pending = [context.scene];while (pending.length > 0) {const node = pending.shift();- add2(node);+ add(node);for (const child of node.children ?? [])pending.push(child);}@@ -16831,10 +16839,10 @@ function zeroScaleFindings(context) {const required = new Set(context.intent.requiredParts);const findings = [];for (const node of sceneNodes(context)) {- const scale2 = node.scale;- if (!scale2)+ const scale = node.scale;+ if (!scale)continue;- const zeroAxes = ["x", "y", "z"].filter((axis) => Number.isFinite(scale2[axis]) && Math.abs(scale2[axis]) <= ZERO_SCALE_EPSILON);+ const zeroAxes = ["x", "y", "z"].filter((axis) => Number.isFinite(scale[axis]) && Math.abs(scale[axis]) <= ZERO_SCALE_EPSILON);if (zeroAxes.length === 0)continue;const outputBearing = isRenderable(node) || descendantsContainRenderable(node) || required.has(nodeName(node));@@ -16855,10 +16863,10 @@ function clipList(context) {return (context.clips ?? []).filter((clip) => typeof clip === "object" && clip !== null);}function trackTarget2(trackName) {- const dot3 = trackName.indexOf(".");- if (dot3 <= 0)+ const dot = trackName.indexOf(".");+ if (dot <= 0)return;- const path = trackName.slice(0, dot3);+ const path = trackName.slice(0, dot);const slash = path.lastIndexOf("/");return path.slice(slash + 1) || undefined;}@@ -17052,7 +17060,7 @@ function appendFinalGltfQa(intent, sceneReport, gltfReport) {metrics: {exportIntegrity: {gltfErrors: gltfReport.issues.numErrors,- gltfWarnings: gltfFindings.filter((finding6) => finding6.disposition === "warn").length+ gltfWarnings: gltfFindings.filter((finding) => finding.disposition === "warn").length}}});@@ -17169,8 +17177,8 @@ var init_run = __esm(() => {stage;gltfValidation;constructor(report, stage, gltfValidation) {- const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding6) => finding6.disposition === "block");- const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding6) => `${finding6.code}: ${finding6.message}${finding6.repairText ? ` FIX: ${finding6.repairText}` : ""}`);+ const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding) => finding.disposition === "block");+ const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding) => `${finding.code}: ${finding.message}${finding.repairText ? ` FIX: ${finding.repairText}` : ""}`);const overflow = blockers.length > MAX_DETAILED_BLOCKERS ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)` : "";super(`Asset QA blocked at ${stage}: ${detailed.join(" | ") || "unknown blocker"}${overflow}`);this.name = "AssetQaBlockedError";@@ -17239,25 +17247,25 @@ function signedAxis2(vector) {function finalEffectAxis(nodes, mode) {let best;for (const node of nodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic3?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());- const scale2 = node.getWorldScale();- const scaleMagnitude = Math.hypot(scale2[0], scale2[1], scale2[2]);+ const scale = node.getWorldScale();+ const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);for (const primitive of node.getMesh()?.listPrimitives() ?? []) {const position = primitive.getAttribute("POSITION");if (!position)continue;const min = position.getMin([]);const max = position.getMax([]);- const axes2 = [+ const axes = [{ score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },{ score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },{ score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }];- const selected = axes2.reduce((candidate2, value) => mode === "length" ? value.score > candidate2.score ? value : candidate2 : value.score < candidate2.score ? value : candidate2);+ const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const candidate = {score: selected.score * scaleMagnitude,direction: selected.direction.transformDirection(matrix)@@ -17276,16 +17284,16 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);const meshes = [...new Set(renderableNodes.map((node) => node.getMesh()).filter(Boolean))];const primitives = meshes.flatMap((mesh) => mesh?.listPrimitives() ?? []);- let triangleCount2 = 0;+ let triangleCount = 0;for (const primitive of primitives) {const indices = primitive.getIndices();const position = primitive.getAttribute("POSITION");- triangleCount2 += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;+ triangleCount += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;}const effectSurfaceMaterials = new Set;for (const node of renderableNodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic3?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}for (const primitive of node.getMesh()?.listPrimitives() ?? []) {@@ -17313,8 +17321,8 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {});const facingSemantics = new Set;for (const node of renderableNodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- for (const role of semantic3?.roles ?? []) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ for (const role of semantic?.roles ?? []) {const match = /^vfx\.facing\.(fixed|camera-spherical|camera-y-axis)$/.exec(role);if (match)facingSemantics.add(match[1]);@@ -17326,7 +17334,7 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {schemaVersion: 1,meshCount: meshes.length,primitiveCount: primitives.length,- triangleCount: Math.floor(triangleCount2),+ triangleCount: Math.floor(triangleCount),materials,facingSemantics: [...facingSemantics].sort(),...normalAxis ? { normalAxis } : {},@@ -17340,12 +17348,12 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {function finalFinding(intent, value) {return { ...value, profile: intent.qaProfile || "vfx.w7.final-glb" };}-function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {+function evaluateFinalVfxGlbEvidenceV1(intent, evidence) {if (intent.category !== "vfx" || !intent.vfx)return [];const contract = intent.vfx;const findings = [];- if (evidence2.meshCount === 0 || evidence2.primitiveCount === 0 || evidence2.triangleCount === 0) {+ if (evidence.meshCount === 0 || evidence.primitiveCount === 0 || evidence.triangleCount === 0) {findings.push(finalFinding(intent, {code: "VFX_GLTF_RENDERABLE_MISSING",disposition: "block",@@ -17353,13 +17361,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB contains no renderable VFX geometry.",measurement: {name: "finalVfxTriangles",- actual: evidence2.triangleCount,+ actual: evidence.triangleCount,expected: ">=1"},repairText: "Export the effect surface as portable geometry before final-byte approval."}));}- const effectMaterials = evidence2.materials.filter((material) => material.effectSurface);+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface);if (effectMaterials.length === 0) {findings.push(finalFinding(intent, {code: "VFX_GLTF_EFFECT_SURFACE_MISSING",@@ -17419,7 +17427,7 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {}));}}- if (contract.facing.mode !== "fixed" && !evidence2.facingSemantics.includes(contract.facing.mode)) {+ if (contract.facing.mode !== "fixed" && !evidence.facingSemantics.includes(contract.facing.mode)) {findings.push(finalFinding(intent, {code: "VFX_GLTF_FACING_SEMANTIC_MISSING",disposition: "block",@@ -17427,13 +17435,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: `Final GLB does not carry the ${contract.facing.mode} runtime-facing semantic.`,measurement: {name: "finalFacingSemantics",- actual: evidence2.facingSemantics.join(",") || null,+ actual: evidence.facingSemantics.join(",") || null,expected: contract.facing.mode},repairText: "Preserve the exporter-derived billboard semantic on the renderable quad node."}));}- if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence2.normalAxis) {+ if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence.normalAxis) {findings.push(finalFinding(intent, {code: "VFX_GLTF_NORMAL_AXIS_MISMATCH",disposition: "block",@@ -17441,12 +17449,12 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB effect-surface normal axis differs from explicit VFX intent.",measurement: {name: "finalNormalAxis",- actual: evidence2.normalAxis ?? null,+ actual: evidence.normalAxis ?? null,expected: contract.facing.normalAxis ?? null}}));}- if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence2.directionAxis) {+ if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence.directionAxis) {findings.push(finalFinding(intent, {code: "VFX_GLTF_DIRECTION_AXIS_MISMATCH",disposition: "block",@@ -17454,13 +17462,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB effect-surface direction axis differs from explicit VFX intent.",measurement: {name: "finalDirectionAxis",- actual: evidence2.directionAxis ?? null,+ actual: evidence.directionAxis ?? null,expected: contract.facing.directionAxis}}));}if (contract.animation.driver === "clip") {- const clip = evidence2.clips.find((candidate) => candidate.name === contract.animation.clipName);+ const clip = evidence.clips.find((candidate) => candidate.name === contract.animation.clipName);if (!clip || Math.abs(clip.durationSeconds - contract.animation.durationSeconds) > 0.000001) {findings.push(finalFinding(intent, {code: "VFX_GLTF_REQUIRED_CLIP_MISSING",@@ -17483,24 +17491,24 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {async function appendFinalVfxGlbQa(intent, report, bytes) {if (intent.category !== "vfx")return report;- const evidence2 = await analyzeFinalVfxGlbBytesV1(bytes);+ const evidence = await analyzeFinalVfxGlbBytesV1(bytes);const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);- findings.push(...evaluateFinalVfxGlbEvidenceV1(intent, evidence2));+ findings.push(...evaluateFinalVfxGlbEvidenceV1(intent, evidence));const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);if (!evaluatedDimensions.includes("exportIntegrity"))evaluatedDimensions.push("exportIntegrity");const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));metrics.exportIntegrity = {...metrics.exportIntegrity ?? {},- finalVfxMeshCount: evidence2.meshCount,- finalVfxPrimitiveCount: evidence2.primitiveCount,- finalVfxTriangles: evidence2.triangleCount,- finalVfxMaterialCount: evidence2.materials.length,- finalVfxEffectMaterialCount: evidence2.materials.filter((material) => material.effectSurface).length,- finalVfxFacingSemantics: evidence2.facingSemantics.join(","),- finalVfxNormalAxis: evidence2.normalAxis ?? null,- finalVfxDirectionAxis: evidence2.directionAxis ?? null,- finalVfxClipCount: evidence2.clips.length+ finalVfxMeshCount: evidence.meshCount,+ finalVfxPrimitiveCount: evidence.primitiveCount,+ finalVfxTriangles: evidence.triangleCount,+ finalVfxMaterialCount: evidence.materials.length,+ finalVfxEffectMaterialCount: evidence.materials.filter((material) => material.effectSurface).length,+ finalVfxFacingSemantics: evidence.facingSemantics.join(","),+ finalVfxNormalAxis: evidence.normalAxis ?? null,+ finalVfxDirectionAxis: evidence.directionAxis ?? null,+ finalVfxClipCount: evidence.clips.length};return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });}@@ -17634,7 +17642,7 @@ function evaluateMaterialBudgetV1(metrics, options) {});}if (metrics.decodedImageBytesRgba8 > limits.maxDecodedBytesRgba8) {- const scale2 = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);+ const scale = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);warnings.push({code: "MATERIAL_DECODED_MEMORY_BUDGET",disposition: "warn",@@ -17647,7 +17655,7 @@ function evaluateMaterialBudgetV1(metrics, options) {threshold: limits.maxDecodedBytesRgba8,unit: "bytes"},- advice: `Downscale image width and height by approximately ${(Math.min(1, scale2) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`+ advice: `Downscale image width and height by approximately ${(Math.min(1, scale) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`});}if (metrics.blendedSurfaceAreaRatio > limits.maxBlendedSurfaceAreaRatio) {@@ -17749,11 +17757,11 @@ var init_material_metrics = __esm(() => {// src/texture-resolver.tsfunction createTextureResolver(cache = DEFAULT_APPROVED_TEXTURE_CACHE) {return Object.freeze({- async loadApprovedTexture(resourceId2) {- if (typeof resourceId2 !== "string") {+ async loadApprovedTexture(resourceId) {+ if (typeof resourceId !== "string") {throw new RangeError("Unsupported approved texture resource ID.");}- return (await cache.load(resourceId2)).texture;+ return (await cache.load(resourceId)).texture;},async materialRecipe(id, overrides) {if (typeof id !== "string")@@ -18722,32 +18730,32 @@ function analyzeGeneratedSourceSafety(ast) {const issues = [];const seen = new Set;const staticStrings = collectStaticStringBindings(ast);- const add2 = (issue) => {+ const add = (issue) => {const key = issueKey(issue);if (seen.has(key))return;seen.add(key);issues.push(issue);};- const ambient = (name, line) => add2({+ const ambient = (name, line) => add({code: "UNSAFE_GLOBAL_ACCESS",message: `Generated code cannot access ambient capability \`${name}\`.`,fixHint: "Use only the documented sandbox globals and approved resource helpers.",line});- const dynamicCode = (line) => add2({+ const dynamicCode = (line) => add({code: "DYNAMIC_CODE_ACCESS",message: "Generated code cannot access constructor chains or dynamic-code constructors.",fixHint: "Call documented sandbox helpers directly; do not derive constructors at runtime.",line});- const unsafeThree = (name, line) => add2({+ const unsafeThree = (name, line) => add({code: "UNSAFE_THREE_CONSTRUCTOR",message: `Generated code cannot access raw THREE constructor \`${name}\`.`,fixHint: "Use approved texture loading, proceduralTexture, pbrMaterial, or materialRecipe instead.",line});- const unsafeThreeNamespace = (code, line) => add2({+ const unsafeThreeNamespace = (code, line) => add({code,message: code === "UNSAFE_THREE_ALIAS" ? "Generated code cannot alias the THREE namespace." : "Generated code cannot use non-static computed access on the THREE namespace.",fixHint: "Use a documented direct THREE constructor or a sandbox material/texture helper.",@@ -18766,7 +18774,7 @@ function analyzeGeneratedSourceSafety(ast) {ambient("this", node.loc?.start.line);},ImportExpression(node) {- add2({+ add({code: "DYNAMIC_IMPORT",message: "Generated code cannot use dynamic import.",fixHint: "Remove import(); all supported helpers are already sandbox globals.",@@ -19089,7 +19097,7 @@ async function bakeSceneTextures(root, warnings) {const materials = Array.isArray(material) ? material : material ? [material] : [];for (const item of materials) {const bag = item;- for (const [slot, usage2] of SLOT_USAGE2) {+ for (const [slot, usage] of SLOT_USAGE2) {const texture = bag[slot];if (!isTexture2(texture))continue;@@ -19100,7 +19108,7 @@ async function bakeSceneTextures(root, warnings) {node: node.name || "(unnamed node)",material: item.name || "(unnamed material)",slot,- usage: usage2+ usage});pending.set(texture, existing);}@@ -19128,8 +19136,8 @@ async function bakeSceneTextures(root, warnings) {bytes};const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";- const recipe2 = entry.texture.userData["kilnProcedural"];- const primaryUsage = recipe2?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");+ const recipe = entry.texture.userData["kilnProcedural"];+ const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");entry.texture.userData["kilnTexture"] = {usage: primaryUsage,colorSpace,@@ -19155,16 +19163,16 @@ async function bakeSceneTextures(root, warnings) {colorSpace,imageSha256,sha1,- ...recipe2 ? { procedural: recipe2 } : {}+ ...recipe ? { procedural: recipe } : {}});}return baked.sort((a, b) => `${a.node}:${a.material}:${a.texture}:${a.slot}`.localeCompare(`${b.node}:${b.material}:${b.texture}:${b.slot}`));}-function computeTangentBasis(geometry2) {- const index = geometry2.getIndex();- const position = geometry2.getAttribute("position");- const normal = geometry2.getAttribute("normal");- const uv = geometry2.getAttribute("uv");+function computeTangentBasis(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");+ const normal = geometry.getAttribute("normal");+ const uv = geometry.getAttribute("uv");if (!position || !normal || !uv) {throw new Error("position, normal, and uv are all required");}@@ -19231,7 +19239,7 @@ function computeTangentBasis(geometry2) {out[v * 4 + 2] = tmp.z;out[v * 4 + 3] = w;}- geometry2.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));+ geometry.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));}function ensureNormalMapTangents(root, warnings) {let count = 0;@@ -19244,19 +19252,19 @@ function ensureNormalMapTangents(root, warnings) {const needsTangents = materials.some((m) => m?.normalMap);if (!needsTangents)return;- const geometry2 = mesh.geometry;- if (!geometry2 || done.has(geometry2) || geometry2.getAttribute("tangent"))+ const geometry = mesh.geometry;+ if (!geometry || done.has(geometry) || geometry.getAttribute("tangent"))return;- done.add(geometry2);+ done.add(geometry);const name = mesh.name || "(unnamed mesh)";- if (!geometry2.getAttribute("uv")) {+ if (!geometry.getAttribute("uv")) {warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but has no UV coordinates, so tangents could not be computed — and the normal map cannot be sampled either. Unwrap it first: mesh.geometry = await autoUnwrap(mesh.geometry).`);return;}- if (!geometry2.getAttribute("normal"))- geometry2.computeVertexNormals();+ if (!geometry.getAttribute("normal"))+ geometry.computeVertexNormals();try {- computeTangentBasis(geometry2);+ computeTangentBasis(geometry);count++;} catch (err) {warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but tangents could not be computed (${err instanceof Error ? err.message : String(err)}). Each runtime will generate its own tangent basis.`);@@ -19285,10 +19293,10 @@ function rounded(value) {function tuple2(vector) {return [rounded(vector.x), rounded(vector.y), rounded(vector.z)];}-function chainIdFor(descriptor2, byRole) {- if (AXIAL_ROLES.has(descriptor2.role))+function chainIdFor(descriptor, byRole) {+ if (AXIAL_ROLES.has(descriptor.role))return "axial";- let current = descriptor2;+ let current = descriptor;const seen = new Set([current.role]);while (current.parentRole && !AXIAL_ROLES.has(current.parentRole)) {const parent = byRole.get(current.parentRole);@@ -19309,19 +19317,19 @@ function colorFor(value) {}function buildCharacterDiagnosticDescriptor(root, findings = []) {root.updateMatrixWorld(true);- const rootInverse2 = root.matrixWorld.clone().invert();- const evidence2 = collectCharacterJointNodes(root);- const descriptorByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint.descriptor]));- const evidenceByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint]));+ const rootInverse = root.matrixWorld.clone().invert();+ const evidence = collectCharacterJointNodes(root);+ const descriptorByRole = new Map(evidence.map((joint) => [joint.descriptor.role, joint.descriptor]));+ const evidenceByRole = new Map(evidence.map((joint) => [joint.descriptor.role, joint]));const invalidFindingNodePaths = [- ...new Set(findings.filter((finding6) => finding6.code === "CHAR_PARENT_EDGE").map((finding6) => finding6.affected?.nodePath).filter((path) => Boolean(path)))+ ...new Set(findings.filter((finding) => finding.code === "CHAR_PARENT_EDGE").map((finding) => finding.affected?.nodePath).filter((path) => Boolean(path)))].sort();const invalidPaths = new Set(invalidFindingNodePaths);- const joints = evidence2.map((joint) => {- const relative = rootInverse2.clone().multiply(joint.node.matrixWorld);+ const joints = evidence.map((joint) => {+ const relative = rootInverse.clone().multiply(joint.node.matrixWorld);const position = new THREE30.Vector3().setFromMatrixPosition(relative);const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);- const bend2 = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -19334,12 +19342,12 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {color: colorFor(chainId),assetPosition: tuple2(position),forwardAxisEnd: tuple2(forward),- bendAxisEnd: tuple2(bend2),+ bendAxisEnd: tuple2(bend),endEffector: joint.descriptor.endEffector,contact: joint.descriptor.contact};});- const edges = evidence2.filter((joint) => joint.descriptor.parentRole).map((joint) => {+ const edges = evidence.filter((joint) => joint.descriptor.parentRole).map((joint) => {const parentRole = joint.descriptor.parentRole;const parent = evidenceByRole.get(parentRole);const chainId = chainIdFor(joint.descriptor, descriptorByRole);@@ -19448,9 +19456,9 @@ function chunk(type, data) {out.writeUInt32BE(crc32(crcInput), 8 + data.length);return out;}-function encodePng(rgb2, width, height) {- if (rgb2.length !== width * height * 3) {- throw new Error(`encodePng: expected ${width * height * 3} bytes, got ${rgb2.length}`);+function encodePng(rgb, width, height) {+ if (rgb.length !== width * height * 3) {+ throw new Error(`encodePng: expected ${width * height * 3} bytes, got ${rgb.length}`);}const ihdr = Buffer.alloc(13);ihdr.writeUInt32BE(width, 0);@@ -19464,7 +19472,7 @@ function encodePng(rgb2, width, height) {for (let y = 0;y < height; y++) {const rowStart = y * (1 + width * 3);raw[rowStart] = 0;- raw.set(rgb2.subarray(y * width * 3, (y + 1) * width * 3), rowStart + 1);+ raw.set(rgb.subarray(y * width * 3, (y + 1) * width * 3), rowStart + 1);}return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),@@ -19519,7 +19527,7 @@ function decodePng(png) {if (raw.length !== height * (1 + stride)) {throw new Error(`decodePng: expected ${height * (1 + stride)} raw bytes, got ${raw.length}`);}- const rgb2 = new Uint8Array(width * height * 3);+ const rgb = new Uint8Array(width * height * 3);const cur = new Uint8Array(stride);const prior = new Uint8Array(stride);for (let y = 0;y < height; y++) {@@ -19553,13 +19561,13 @@ function decodePng(png) {for (let px = 0;px < width; px++) {const src = px * channels;const dst = (y * width + px) * 3;- rgb2[dst] = cur[src];- rgb2[dst + 1] = cur[src + 1];- rgb2[dst + 2] = cur[src + 2];+ rgb[dst] = cur[src];+ rgb[dst + 1] = cur[src + 1];+ rgb[dst + 2] = cur[src + 2];}prior.set(cur);}- return { rgb: rgb2, width, height };+ return { rgb, width, height };}var CRC_TABLE, PNG_SIGNATURE;var init_png = __esm(() => {@@ -19721,8 +19729,8 @@ function transformPoint2(matrix, x, y, z) {matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]];}-function matchesRole(roles2, prefixes) {- return Boolean(prefixes?.some((prefix) => roles2.some((role) => role.startsWith(prefix))));+function matchesRole(roles, prefixes) {+ return Boolean(prefixes?.some((prefix) => roles.some((role) => role.startsWith(prefix))));}function semanticRoles2(node) {const metadata = readSemanticMetadataV1FromExtras(node.userData ?? {});@@ -19745,9 +19753,9 @@ function collectScene(root, requestValue) {const world = multiplyMatrices(parentMatrix, local);const visible = ancestorVisible && node.visible !== false;const segment = `${node.name?.trim() || node.type || "Node"}[${siblingIndex}]`;- const nodePath5 = parentPath ? `${parentPath}/${segment}` : segment;- const roles2 = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];- const omitted = matchesRole(roles2, requestValue.omitRolePrefixes);+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ const roles = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];+ const omitted = matchesRole(roles, requestValue.omitRolePrefixes);if (visible && !omitted && node.isMesh && node.geometry) {const materials = Array.isArray(node.material) ? node.material : [node.material];const material = materials[0];@@ -19755,13 +19763,13 @@ function collectScene(root, requestValue) {const position = node.geometry.getAttribute?.("position");if (position?.itemSize === 3) {const worldPositions = [];- for (let index2 = 0;index2 < position.count; index2++) {- const point = transformPoint2(world, position.array[index2 * 3], position.array[index2 * 3 + 1], position.array[index2 * 3 + 2]);+ for (let index = 0;index < position.count; index++) {+ const point = transformPoint2(world, position.array[index * 3], position.array[index * 3 + 1], position.array[index * 3 + 2]);worldPositions.push(point);}const materialColor = material?.color;- const color2 = materialColor ? [clamp01(materialColor.r), clamp01(materialColor.g), clamp01(materialColor.b)] : [0.7, 0.7, 0.7];- const focused = matchesRole(roles2, requestValue.focusRolePrefixes);+ const color = materialColor ? [clamp01(materialColor.r), clamp01(materialColor.g), clamp01(materialColor.b)] : [0.7, 0.7, 0.7];+ const focused = matchesRole(roles, requestValue.focusRolePrefixes);const addTriangle = (a, b, c) => {const points = [worldPositions[a], worldPositions[b], worldPositions[c]];if (points.some((point) => !point || point.some((value) => !Number.isFinite(value)))) {@@ -19782,10 +19790,10 @@ function collectScene(root, requestValue) {});triangles.push({vertices,- color: color2,+ color,nodeName: node.name ?? "",- nodePath: nodePath5,- semanticRoles: roles2+ nodePath,+ semanticRoles: roles});};const index = node.geometry.index;@@ -19801,7 +19809,7 @@ function collectScene(root, requestValue) {}}(node.children ?? []).forEach((child, index) => {- visit(child, world, nodePath5, index, visible && !omitted, roles2);+ visit(child, world, nodePath, index, visible && !omitted, roles);});};visit(root, IDENTITY, "", 0, true, []);@@ -19814,8 +19822,8 @@ function collectScene(root, requestValue) {};}function normalize2(vector) {- const length3 = Math.hypot(...vector) || 1;- return [vector[0] / length3, vector[1] / length3, vector[2] / length3];+ const length = Math.hypot(...vector) || 1;+ return [vector[0] / length, vector[1] / length, vector[2] / length];}function cross2(a, b) {return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];@@ -19842,26 +19850,26 @@ function projectScene(scene, camera, size) {(frame.min[1] + frame.max[1]) / 2,(frame.min[2] + frame.max[2]) / 2];- let extent2 = 0.000001;+ let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {const point = [(corner & 1 ? frame.max[0] : frame.min[0]) - center[0],(corner & 2 ? frame.max[1] : frame.min[1]) - center[1],(corner & 4 ? frame.max[2] : frame.min[2]) - center[2]];- extent2 = Math.max(extent2, Math.abs(dot3(point, xAxis)), Math.abs(dot3(point, yAxis)));+ extent = Math.max(extent, Math.abs(dot3(point, xAxis)), Math.abs(dot3(point, yAxis)));}- const scale2 = size * 0.45 / extent2;+ const scale = size * 0.45 / extent;const half = size / 2;return scene.triangles.flatMap((triangle) => {const v = triangle.vertices;const edgeA = [v[3] - v[0], v[4] - v[1], v[5] - v[2]];const edgeB = [v[6] - v[0], v[7] - v[1], v[8] - v[2]];const normalRaw = cross2(edgeA, edgeB);- const length3 = Math.hypot(...normalRaw);- if (length3 < 0.000000000001)+ const length = Math.hypot(...normalRaw);+ if (length < 0.000000000001)return [];- const normal = normalRaw.map((component) => component / length3);+ const normal = normalRaw.map((component) => component / length);const xs = [];const ys = [];const zs = [];@@ -19872,8 +19880,8 @@ function projectScene(scene, camera, size) {v[index * 3 + 1] - center[1],v[index * 3 + 2] - center[2]];- xs.push(half + dot3(point, xAxis) * scale2);- ys.push(half - dot3(point, yAxis) * scale2);+ xs.push(half + dot3(point, xAxis) * scale);+ ys.push(half - dot3(point, yAxis) * scale);zs.push(dot3(point, zAxis));worldY.push(v[index * 3 + 1]);}@@ -19890,7 +19898,7 @@ function projectScene(scene, camera, size) {];});}-function drawLine(rgb2, size, from, to, color2) {+function drawLine(rgb, size, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);const x1 = Math.round(to[0]);@@ -19903,9 +19911,9 @@ function drawLine(rgb2, size, from, to, color2) {while (true) {if (x0 >= 0 && x0 < size && y0 >= 0 && y0 < size) {const offset = (y0 * size + x0) * 3;- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}if (x0 === x1 && y0 === y1)break;@@ -19920,12 +19928,12 @@ function drawLine(rgb2, size, from, to, color2) {}}}-function drawRegionBox(rgb2, size, region) {+function drawRegionBox(rgb, size, region) {const [minX, minY, maxX, maxY] = region.pixelBounds;- drawLine(rgb2, size, [minX, minY], [maxX, minY], region.color);- drawLine(rgb2, size, [maxX, minY], [maxX, maxY], region.color);- drawLine(rgb2, size, [maxX, maxY], [minX, maxY], region.color);- drawLine(rgb2, size, [minX, maxY], [minX, minY], region.color);+ drawLine(rgb, size, [minX, minY], [maxX, minY], region.color);+ drawLine(rgb, size, [maxX, minY], [maxX, maxY], region.color);+ drawLine(rgb, size, [maxX, maxY], [minX, maxY], region.color);+ drawLine(rgb, size, [minX, maxY], [minX, minY], region.color);}function renderDiagnosticView(root, requestValue, options = {}) {const camera = cameraById.get(requestValue.cameraId);@@ -19936,11 +19944,11 @@ function renderDiagnosticView(root, requestValue, options = {}) {const scene = collectScene(root, requestValue);const triangles = projectScene(scene, camera, size);const background = [18, 20, 24];- const rgb2 = new Uint8Array(size * size * 3);+ const rgb = new Uint8Array(size * size * 3);for (let pixel = 0;pixel < size * size; pixel++) {- rgb2[pixel * 3] = background[0];- rgb2[pixel * 3 + 1] = background[1];- rgb2[pixel * 3 + 2] = background[2];+ rgb[pixel * 3] = background[0];+ rgb[pixel * 3 + 1] = background[1];+ rgb[pixel * 3 + 2] = background[2];}const depth = new Float64Array(size * size).fill(-Infinity);const depths = triangles.flatMap((triangle) => triangle.z);@@ -20002,50 +20010,50 @@ function renderDiagnosticView(root, requestValue, options = {}) {continue;depth[pixel] = pixelDepth;const offset = pixel * 3;- let color2;+ let color;if (requestValue.variant === "material-grazing-light") {const grazingDirection = normalize2([0.25, 0.08, 1]);const light = 0.08 + 0.92 * Math.max(0, dot3(triangle.normal, grazingDirection));- color2 = triangle.source.color.map((value) => Math.round(clamp01(value * light) * 255));+ color = triangle.source.color.map((value) => Math.round(clamp01(value * light) * 255));} else if (requestValue.buffer === "silhouette-unlit") {- color2 = [235, 238, 242];+ color = [235, 238, 242];} else if (requestValue.buffer === "normals-backface") {- color2 = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];+ color = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];} else if (requestValue.buffer === "depth-contact") {const worldY = w1 * triangle.worldY[0] + w2 * triangle.worldY[1] + w0 * triangle.worldY[2];if (Math.abs(worldY - groundY) <= contactTolerance)- color2 = [58, 220, 126];+ color = [58, 220, 126];else if (worldY < groundY - contactTolerance)- color2 = [245, 94, 72];+ color = [245, 94, 72];else {const value = Math.round(48 + 190 * ((pixelDepth - minDepth) / depthRange));- color2 = [value, value, value];+ color = [value, value, value];}} else {- color2 = regionColor;+ color = regionColor;}- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}}}if (requestValue.buffer === "wireframe") {for (const triangle of triangles) {- const color2 = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];+ const color = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];for (const [a, b] of [[0, 1],[1, 2],[2, 0]]) {- drawLine(rgb2, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color2);+ drawLine(rgb, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color);}}}const regions = [...regionMap.values()].sort((a, b) => a.nodePath.localeCompare(b.nodePath));if (requestValue.buffer === "semantic-overlay") {for (const region of regions)- drawRegionBox(rgb2, size, region);+ drawRegionBox(rgb, size, region);}return {id: requestValue.id,@@ -20055,8 +20063,8 @@ function renderDiagnosticView(root, requestValue, options = {}) {...requestValue.variant ? { variant: requestValue.variant } : {},width: size,height: size,- rgb: rgb2,- png: encodePng(rgb2, size, size),+ rgb,+ png: encodePng(rgb, size, size),regions,...requestValue.phaseFractions ? { phaseFractions: requestValue.phaseFractions } : {}};@@ -20180,22 +20188,22 @@ function prepareClip(root, clip) {const raw = track.name;if (!raw)continue;- const dot4 = raw.lastIndexOf(".");- if (dot4 === -1)+ const dot = raw.lastIndexOf(".");+ if (dot === -1)continue;- const nodeName2 = raw.slice(0, dot4);- const property = raw.slice(dot4 + 1);+ const nodeName = raw.slice(0, dot);+ const property = raw.slice(dot + 1);if (property !== "position" && property !== "quaternion" && property !== "scale")continue;const times = track.times ? Array.from(track.times) : [];const values = track.values ? Array.from(track.values) : [];if (times.length === 0 || values.length === 0)continue;- if (!nodeNames.has(nodeName2))+ if (!nodeNames.has(nodeName))unresolved.push(raw);if (times[times.length - 1] > maxTime)maxTime = times[times.length - 1];- tracks.push({ nodeName: nodeName2, prop: property, stride: PROP_STRIDE[property], times, values });+ tracks.push({ nodeName, prop: property, stride: PROP_STRIDE[property], times, values });}const duration = clip.duration && clip.duration > 0 ? clip.duration : maxTime;return { name: clip.name ?? "(unnamed)", duration, tracks, unresolved };@@ -20303,11 +20311,11 @@ function planFrameTimes(duration, count) {out.push(duration * i / (count - 1));return out;}-function stampLabel(rgb2, width, height, x0, y0, text, scale2 = 3) {- const gw = 3 * scale2;- const gh = 5 * scale2;- const gap = scale2;- const pad = scale2;+function stampLabel(rgb, width, height, x0, y0, text, scale = 3) {+ const gw = 3 * scale;+ const gh = 5 * scale;+ const gap = scale;+ const pad = scale;const totalW = text.length * gw + (text.length - 1) * gap + pad * 2;const totalH = gh + pad * 2;for (let y = y0;y < y0 + totalH; y++) {@@ -20315,9 +20323,9 @@ function stampLabel(rgb2, width, height, x0, y0, text, scale2 = 3) {if (x < 0 || y < 0 || x >= width || y >= height)continue;const p = (y * width + x) * 3;- rgb2[p] = LABEL_BG[0];- rgb2[p + 1] = LABEL_BG[1];- rgb2[p + 2] = LABEL_BG[2];+ rgb[p] = LABEL_BG[0];+ rgb[p + 1] = LABEL_BG[1];+ rgb[p + 2] = LABEL_BG[2];}}let cx = x0 + pad;@@ -20329,16 +20337,16 @@ function stampLabel(rgb2, width, height, x0, y0, text, scale2 = 3) {for (let col = 0;col < 3; col++) {if (!(bits & 1 << 2 - col))continue;- for (let sy = 0;sy < scale2; sy++) {- for (let sx = 0;sx < scale2; sx++) {- const x = cx + col * scale2 + sx;- const y = cy + row * scale2 + sy;+ for (let sy = 0;sy < scale; sy++) {+ for (let sx = 0;sx < scale; sx++) {+ const x = cx + col * scale + sx;+ const y = cy + row * scale + sy;if (x < 0 || y < 0 || x >= width || y >= height)continue;const p = (y * width + x) * 3;- rgb2[p] = LABEL_FG[0];- rgb2[p + 1] = LABEL_FG[1];- rgb2[p + 2] = LABEL_FG[2];+ rgb[p] = LABEL_FG[0];+ rgb[p + 1] = LABEL_FG[1];+ rgb[p + 2] = LABEL_FG[2];}}}@@ -20602,7 +20610,7 @@ function rasterizeView(root, dir, opts = {}) {const p = [px, py, pz];ext = Math.max(ext, Math.abs(dot4(p, x)), Math.abs(dot4(p, y)));}- const scale2 = size * 0.45 / ext;+ const scale = size * 0.45 / ext;const half = size / 2;const zbuf = new Float64Array(size * size).fill(-Infinity);const sx = new Float64Array(3);@@ -20626,8 +20634,8 @@ function rasterizeView(root, dir, opts = {}) {const py = tri.v[i * 3 + 1] - center[1];const pz = tri.v[i * 3 + 2] - center[2];const p = [px, py, pz];- sx[i] = half + dot4(p, x) * scale2;- sy[i] = half - dot4(p, y) * scale2;+ sx[i] = half + dot4(p, x) * scale;+ sy[i] = half - dot4(p, y) * scale;sz[i] = dot4(p, z);}const lambert = Math.max(0, dot4(N, KEY_DIR));@@ -20717,10 +20725,10 @@ function triple(v, label) {}function listCameraSubjects(root) {const result = [];- const visit = (node2, path) => {- result.push({ node: node2, path, name: node2.name });+ const visit = (node, path) => {+ result.push({ node, path, name: node.name });const counts = new Map;- for (const child of node2.children ?? []) {+ for (const child of node.children ?? []) {const count = counts.get(child.name) ?? 0;counts.set(child.name, count + 1);visit(child, `${path}/${encodeURIComponent(child.name)}[${count}]`);@@ -20754,10 +20762,10 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {if (x.length() < 0.000000001)throw new Error("camera up must not be collinear with view");const y = z.clone().cross(x);- let extent2 = 0.000001;+ let extent = 0.000001;for (let i = 0;i < 8; i++) {const p = new Vector325((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);- extent2 = Math.max(extent2, Math.abs(p.dot(x)), Math.abs(p.dot(y)));+ extent = Math.max(extent, Math.abs(p.dot(x)), Math.abs(p.dot(y)));}const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));const depthMax = bounds.max.map((v, i) => Math.max(v, sceneBounds.max[i]));@@ -20772,7 +20780,7 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {aspect: 1,near: Math.max(0.000001, distance - radius),far: distance + radius + 1,- halfHeight: extent2 * padding / 0.9+ halfHeight: extent * padding / 0.9};}function validateResolvedAssetCamera(value) {@@ -20822,23 +20830,23 @@ function resolveAssetCamera(root, shot = {}) {const bounds = measureBounds(selected.node);if (!collectTriangles(selected.node).tris.length)throw new Error(`subject ${selected.path} has no visible geometry`);- const request2 = shot.camera ?? { type: "orbit" };+ const request = shot.camera ?? { type: "orbit" };let camera;- if (request2.type === "orbit") {- strict(request2, ["type", "azimuthDeg", "elevationDeg", "relativeTo", "padding"], "camera");- const relative = request2.relativeTo ?? "world";+ if (request.type === "orbit") {+ strict(request, ["type", "azimuthDeg", "elevationDeg", "relativeTo", "padding"], "camera");+ const relative = request.relativeTo ?? "world";if (!["world", "asset", "part"].includes(relative))throw new Error("invalid relativeTo");- const dir = vec(orbitDir(finite2(request2.azimuthDeg ?? 45, "azimuthDeg"), finite2(request2.elevationDeg ?? 25, "elevationDeg")));+ const dir = vec(orbitDir(finite2(request.azimuthDeg ?? 45, "azimuthDeg"), finite2(request.elevationDeg ?? 25, "elevationDeg")));let up;if (relative !== "world") {const node = relative === "part" ? selected.node : rootNode;dir.transformDirection(node.matrixWorld);up = tuple5(new Vector325(0, 1, 0).transformDirection(node.matrixWorld));}- camera = cameraFromBounds(bounds, tuple5(dir), request2.padding ?? 1.2, up, measureBounds(root));- } else if (request2.type === "explicit") {- strict(request2, [+ camera = cameraFromBounds(bounds, tuple5(dir), request.padding ?? 1.2, up, measureBounds(root));+ } else if (request.type === "explicit") {+ strict(request, ["type","projection","position",@@ -20854,56 +20862,56 @@ function resolveAssetCamera(root, shot = {}) {"padding","targetOffset"], "camera");- if (request2.projection === "orthographic" && request2.fovDeg !== undefined || request2.projection === "perspective" && request2.halfHeight !== undefined)+ if (request.projection === "orthographic" && request.fovDeg !== undefined || request.projection === "perspective" && request.halfHeight !== undefined)throw new Error("projection and lens fields conflict");- const relative = request2.relativeTo ?? "world";+ const relative = request.relativeTo ?? "world";if (!["world", "asset", "part", "local"].includes(relative))throw new Error("invalid relativeTo");- if (relative === "local" !== Boolean(request2.frame))+ if (relative === "local" !== Boolean(request.frame))throw new Error("local coordinates require frame; frame is only valid for local coordinates");- if (request2.framing !== undefined && !["explicit", "bounds"].includes(request2.framing))+ if (request.framing !== undefined && !["explicit", "bounds"].includes(request.framing))throw new Error("invalid framing");- if (request2.target === undefined && request2.framing !== "bounds")+ if (request.target === undefined && request.framing !== "bounds")throw new Error("explicit framing requires target");- if (request2.padding !== undefined && request2.framing !== "bounds")+ if (request.padding !== undefined && request.framing !== "bounds")throw new Error("padding requires bounds framing");- if (request2.framing === "bounds" && request2.halfHeight !== undefined)+ if (request.framing === "bounds" && request.halfHeight !== undefined)throw new Error("bounds framing derives halfHeight");let matrix = new Matrix46;if (relative === "asset" || relative === "part")matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;- if (request2.frame) {- strict(request2.frame, ["origin", "rotation"], "frame");- const rotation = triple(request2.frame.rotation ?? [0, 0, 0], "frame.rotation");+ if (request.frame) {+ strict(request.frame, ["origin", "rotation"], "frame");+ const rotation = triple(request.frame.rotation ?? [0, 0, 0], "frame.rotation");matrix.makeRotationFromEuler(new Euler4(...rotation.map((n) => n * Math.PI / 180), "XYZ"));- matrix.setPosition(...triple(request2.frame.origin ?? [0, 0, 0], "frame.origin"));+ matrix.setPosition(...triple(request.frame.origin ?? [0, 0, 0], "frame.origin"));}- const position = vec(triple(request2.position, "position")).applyMatrix4(matrix);- const target = request2.target ? vec(triple(request2.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);- const up = vec(triple(request2.up ?? [0, 1, 0], "up")).transformDirection(matrix);- const offset = vec(triple(request2.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector325().setFromMatrixPosition(matrix));+ const position = vec(triple(request.position, "position")).applyMatrix4(matrix);+ const target = request.target ? vec(triple(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);+ const up = vec(triple(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);+ const offset = vec(triple(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector325().setFromMatrixPosition(matrix));const radius = vec(bounds.max).sub(vec(bounds.min)).length();camera = {version: "kiln.camera.v1",- projection: request2.projection,+ projection: request.projection,position: tuple5(position),target: tuple5(target.clone().add(offset)),up: tuple5(up),aspect: 1,- near: request2.near ?? 0.001,- far: request2.far ?? Math.max(100, position.distanceTo(target) + radius * 4),- ...request2.projection === "orthographic" ? { halfHeight: request2.halfHeight ?? Math.max(radius / 2, 0.000001) } : { fovDeg: request2.fovDeg ?? 50 }+ near: request.near ?? 0.001,+ far: request.far ?? Math.max(100, position.distanceTo(target) + radius * 4),+ ...request.projection === "orthographic" ? { halfHeight: request.halfHeight ?? Math.max(radius / 2, 0.000001) } : { fovDeg: request.fovDeg ?? 50 }};- if (request2.framing === "bounds") {+ if (request.framing === "bounds") {const direction = position.clone().sub(target);if (direction.lengthSq() < 0.00000000000000000001)throw new Error("bounds framing position and target must differ");- const padding = request2.padding ?? 1.2;+ const padding = request.padding ?? 1.2;const fit = cameraFromBounds(bounds, tuple5(direction), padding, tuple5(up), measureBounds(root));- if (request2.projection === "orthographic")- camera = { ...fit, near: request2.near ?? fit.near, far: request2.far ?? fit.far };+ if (request.projection === "orthographic")+ camera = { ...fit, near: request.near ?? fit.near, far: request.far ?? fit.far };else {- const fov = finite2(request2.fovDeg ?? 50, "fovDeg");+ const fov = finite2(request.fovDeg ?? 50, "fovDeg");if (fov <= 0 || fov >= 180)throw new Error("invalid fovDeg");const distance = Math.max(radius / 2, 0.000001) * padding / Math.sin(fov * Math.PI / 360);@@ -20912,7 +20920,7 @@ function resolveAssetCamera(root, shot = {}) {...camera,position: tuple5(center.clone().add(direction.normalize().multiplyScalar(distance))),target: tuple5(center),- far: request2.far ?? Math.max(100, distance + radius * 4)+ far: request.far ?? Math.max(100, distance + radius * 4)};}camera.position = tuple5(vec(camera.position).add(offset));@@ -20929,9 +20937,9 @@ function resolveAssetCamera(root, shot = {}) {visibility: shot.visibility ?? "context"};}-async function withCameraVisibility(root, shot, run2) {+async function withCameraVisibility(root, shot, run) {if (shot.visibility === "context")- return run2();+ return run();const keep = new Set;selectCameraSubject(root, { path: shot.subject.path }).node.traverse((n) => keep.add(n));const restore = [];@@ -20942,7 +20950,7 @@ async function withCameraVisibility(root, shot, run2) {}});try {- return await run2();+ return await run();} finally {for (const [node, visible] of restore)node.visible = visible;@@ -20979,7 +20987,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true) {if (tri.alpha <= 0)continue;const light = Math.min(1, 0.25 + 1.1 * Math.max(0, normal.dot(key)));- const color2 = tri.color.map((c) => Math.round(srgb(c * light) * 255));+ const color = tri.color.map((c) => Math.round(srgb(c * light) * 255));let polygon = world.map((p) => {const d = p.clone().sub(position);return new Vector325(d.dot(x), d.dot(y), -d.dot(z));@@ -21009,7 +21017,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true) {continue;depth[index] = d;for (let channel = 0;channel < 3; channel++)- out[index * 3 + channel] = Math.round(color2[channel] * tri.alpha + out[index * 3 + channel] * (1 - tri.alpha));+ out[index * 3 + channel] = Math.round(color[channel] * tri.alpha + out[index * 3 + channel] * (1 - tri.alpha));}}}@@ -21039,61 +21047,6 @@ var init_render_port = __esm(() => {});// src/views/capture-cache.ts-function clone(entry) {- const result = structuredClone(entry);- if (result.kind === "cpu")- result.result.png = Buffer.from(result.result.png);- return result;-}--class MemoryCaptureCache {- maxBytes;- entries = new Map;- bytes = 0;- constructor(maxBytes = 64 * 1024 * 1024) {- this.maxBytes = maxBytes;- if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)- throw new Error("Capture cache bytes must be a nonnegative integer");- }- async get(key) {- const value = this.entries.get(key);- if (!value)- return;- this.entries.delete(key);- this.entries.set(key, value);- return clone(value.entry);- }- async put(key, value) {- const entry = clone(value);- let bytes;- if (entry.kind === "gpu") {- const { viewsPng, beautyPng, ...metadata } = entry.result;- bytes = (viewsPng ?? []).reduce((sum, png) => sum + png.byteLength, 0) + (beautyPng?.byteLength ?? 0) + Buffer.byteLength(JSON.stringify(metadata));- } else {- const { png, ...metadata } = entry.result;- bytes = png.byteLength + Buffer.byteLength(JSON.stringify(metadata));- }- if (bytes > this.maxBytes)- return;- const old = this.entries.get(key);- if (old) {- this.bytes -= old.bytes;- this.entries.delete(key);- }- while (this.bytes + bytes > this.maxBytes) {- const first = this.entries.keys().next().value;- if (first === undefined)- break;- this.bytes -= this.entries.get(first).bytes;- this.entries.delete(first);- }- this.entries.set(key, { entry, bytes });- this.bytes += bytes;- }- stats() {- return { entries: this.entries.size, bytes: this.bytes, maxBytes: this.maxBytes };- }-}var init_capture_cache = __esm(() => {init_render_port();init_png();@@ -21398,10 +21351,10 @@ function describeVehicleDiagnostics(root) {const assemblies = resolveVehicleWheelAssemblies(root);const wheels = assemblies.map((wheel) => ({id: wheel.id,- center: tuple7(wheel.centerWorld.clone().applyMatrix4(inverse)),+ center: tuple6(wheel.centerWorld.clone().applyMatrix4(inverse)),radius: wheel.radius ?? 0,width: wheel.width ?? 0,- axle: tuple7(wheel.spinAxisWorld.clone().transformDirection(inverse)),+ axle: tuple6(wheel.spinAxisWorld.clone().transformDirection(inverse)),loadBearing: wheel.loadBearing}));const byAxle = new Map;@@ -21442,7 +21395,7 @@ function describeVehicleDiagnostics(root) {return {schemaVersion: 1,forwardArrow: { start: [0, 0, 0], end: [1, 0, 0] },- ...chassis ? { chassisBox: { min: tuple7(chassis.min), max: tuple7(chassis.max) } } : {},+ ...chassis ? { chassisBox: { min: tuple6(chassis.min), max: tuple6(chassis.max) } } : {},axles,wheels,...supportPlaneY !== undefined ? { supportPlaneY } : {},@@ -21452,41 +21405,41 @@ function describeVehicleDiagnostics(root) {function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}-function rod(name, start, end, radius, color2, role) {+function rod(name, start, end, radius, color, role) {const from = new THREE32.Vector3(...start);const to = new THREE32.Vector3(...end);const direction = to.clone().sub(from);- const length3 = direction.length();- const geometry2 = length3 > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length3, 8) : new THREE32.SphereGeometry(radius, 8, 6);- const result = new THREE32.Mesh(geometry2, new THREE32.MeshBasicMaterial({ color: color2 }));+ const length = direction.length();+ const geometry = length > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length, 8) : new THREE32.SphereGeometry(radius, 8, 6);+ const result = new THREE32.Mesh(geometry, new THREE32.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);- if (length3 > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length3));+ if (length > 0.000000001) {+ result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}-function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagnostics(root)) {+function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {const overlay = new THREE32.Group;overlay.name = "VehicleDiagnosticOverlay";- const chassisSpan = descriptor2.chassisBox ? Math.max(descriptor2.chassisBox.max[0] - descriptor2.chassisBox.min[0], descriptor2.chassisBox.max[1] - descriptor2.chassisBox.min[1], descriptor2.chassisBox.max[2] - descriptor2.chassisBox.min[2]) : 1;+ const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;const thickness = Math.max(0.01, chassisSpan * 0.008);const arrow = new THREE32.Group;arrow.name = "Diagnostic_Forward_+X";tagDiagnostic(arrow, "diagnostic.vehicle.forward");- arrow.add(rod("Diagnostic_Forward_Shaft", descriptor2.forwardArrow.start, [descriptor2.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));+ arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";- arrowHead.position.set(descriptor2.forwardArrow.end[0] - 0.12, 0, 0);+ arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);- for (const axle of descriptor2.axles) {+ for (const axle of descriptor.axles) {overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));}- for (const wheel of descriptor2.wheels) {+ for (const wheel of descriptor.wheels) {const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);@@ -21497,11 +21450,11 @@ function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagntagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}- if (descriptor2.chassisBox) {+ if (descriptor.chassisBox) {const chassis = new THREE32.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");- const { min, max } = descriptor2.chassisBox;+ const { min, max } = descriptor.chassisBox;const corners = [[min[0], min[1], min[2]],[max[0], min[1], min[2]],@@ -21531,13 +21484,13 @@ function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagn}overlay.add(chassis);}- if (descriptor2.supportPlaneY !== undefined) {+ if (descriptor.supportPlaneY !== undefined) {const plane = new THREE32.Group;plane.name = "Diagnostic_SupportPlane";tagDiagnostic(plane, "diagnostic.vehicle.support-plane");- const halfX = Math.max(1, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[0]), Math.abs(descriptor2.chassisBox.max[0])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;- const halfZ = Math.max(0.8, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[2]), Math.abs(descriptor2.chassisBox.max[2])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;- const y = descriptor2.supportPlaneY;+ const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;+ const halfZ = Math.max(0.8, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[2]), Math.abs(descriptor.chassisBox.max[2])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;+ const y = descriptor.supportPlaneY;const planeLines = [[[-halfX, y, -halfZ],@@ -21590,8 +21543,8 @@ function compositeForCapture(root, overlay) {children: [root, overlay]};}-function selectWheelSectionRequest(requestValue, descriptor2) {- const target = descriptor2.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor2.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor2.wheels[0];+function selectWheelSectionRequest(requestValue, descriptor) {+ const target = descriptor.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor.wheels[0];if (!target?.id.startsWith("wheel.assembly."))return requestValue;const suffix = target.id.replace(/[^a-zA-Z0-9.-]/g, "-");@@ -21605,12 +21558,12 @@ function selectWheelSectionRequest(requestValue, descriptor2) {function captureVehicleDiagnosticViews(root, intent, size = 256) {if (intent.category !== "vehicle")return [];- const descriptor2 = describeVehicleDiagnostics(root);- const overlay = createVehicleDiagnosticOverlay(root, descriptor2);+ const descriptor = describeVehicleDiagnostics(root);+ const overlay = createVehicleDiagnosticOverlay(root, descriptor);const composite = compositeForCapture(root, overlay);const requests = planDiagnosticViews(intent).extra.filter((value) => value.variant === "vehicle-underbody" || value.variant === "vehicle-wheel-section");return requests.map((baseRequest) => {- const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor2) : baseRequest;+ const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor) : baseRequest;const frame = renderDiagnosticView(composite, requestValue, { size });return {id: frame.id,@@ -21622,11 +21575,11 @@ function captureVehicleDiagnosticViews(root, intent, size = 256) {height: frame.height,png: frame.png,regions: frame.regions,- descriptor: descriptor2+ descriptor};});}-var tuple7 = (value) => [value.x, value.y, value.z];+var tuple6 = (value) => [value.x, value.y, value.z];var init_vehicle3 = __esm(() => {init_contracts();init_vehicle();@@ -21753,8 +21706,8 @@ async function renderClipAnimation(root, clips, opts = {}) {pngs: cells.map((c) => encodePng(c, size, size))};}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size);- return { ...baseMeta, width, height, png: encodePng(rgb2, width, height) };+ const { rgb, width, height } = compositeCellGrid(cells, size);+ return { ...baseMeta, width, height, png: encodePng(rgb, width, height) };}var ANIM_CAMERAS, ANIM_CAMERA_ALIASES;var init_views = __esm(() => {@@ -21812,7 +21765,7 @@ var init_views = __esm(() => {// src/views/character-capture.tsimport * as THREE33 from "three";-function drawLine2(rgb2, width, height, from, to, color2) {+function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);const x1 = Math.round(to[0]);@@ -21825,9 +21778,9 @@ function drawLine2(rgb2, width, height, from, to, color2) {while (true) {if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {const offset = (y0 * width + x0) * 3;- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}if (x0 === x1 && y0 === y1)break;@@ -21842,9 +21795,9 @@ function drawLine2(rgb2, width, height, from, to, color2) {}}}-function drawCross(rgb2, width, height, point, color2, radius = 3) {- drawLine2(rgb2, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color2);- drawLine2(rgb2, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color2);+function drawCross(rgb, width, height, point, color, radius = 3) {+ drawLine2(rgb, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color);+ drawLine2(rgb, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color);}function projector(root, cameraId, size) {root.updateMatrixWorld(true);@@ -21852,48 +21805,48 @@ function projector(root, cameraId, size) {if (bounds.isEmpty())bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));const center = bounds.getCenter(new THREE33.Vector3);- const camera2 = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);+ const camera = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);const upHint = new THREE33.Vector3(0, 1, 0);- const xAxis = new THREE33.Vector3().crossVectors(upHint, camera2).normalize();- const yAxis = new THREE33.Vector3().crossVectors(camera2, xAxis).normalize();- let extent2 = 0.000001;+ const xAxis = new THREE33.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE33.Vector3().crossVectors(camera, xAxis).normalize();+ let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);- extent2 = Math.max(extent2, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));+ extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));}- const scale2 = size * 0.45 / extent2;+ const scale = size * 0.45 / extent;return (assetPoint) => {const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);- return [size / 2 + world.dot(xAxis) * scale2, size / 2 - world.dot(yAxis) * scale2];+ return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}-function skeletonCapture(root, request2, findings, size) {+function skeletonCapture(root, request, findings, size) {const baseRequest = {- id: request2.id,- label: request2.label,- cameraId: request2.cameraId,+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,buffer: "semantic-overlay",scope: "category",variant: "character-skeleton",- focusRolePrefixes: request2.focusRolePrefixes+ focusRolePrefixes: request.focusRolePrefixes};const frame = renderDiagnosticView(root, baseRequest, { size });- const descriptor2 = buildCharacterDiagnosticDescriptor(root, findings);- const project2 = projector(root, request2.cameraId, size);- const byRole = new Map(descriptor2.joints.map((joint) => [joint.role, joint]));- for (const edge of descriptor2.edges) {+ const descriptor = buildCharacterDiagnosticDescriptor(root, findings);+ const project = projector(root, request.cameraId, size);+ const byRole = new Map(descriptor.joints.map((joint) => [joint.role, joint]));+ for (const edge of descriptor.edges) {const parent = byRole.get(edge.parentRole);const child = byRole.get(edge.childRole);if (!parent || !child)continue;- drawLine2(frame.rgb, frame.width, frame.height, project2(parent.assetPosition), project2(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);- }- for (const joint of descriptor2.joints) {- const point = project2(joint.assetPosition);- const color2 = rgbFromHex(joint.color);- drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color2);- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.forwardAxisEnd), [64, 220, 255]);- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.bendAxisEnd), [255, 105, 210]);+ drawLine2(frame.rgb, frame.width, frame.height, project(parent.assetPosition), project(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);+ }+ for (const joint of descriptor.joints) {+ const point = project(joint.assetPosition);+ const color = rgbFromHex(joint.color);+ drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color);+ drawLine2(frame.rgb, frame.width, frame.height, point, project(joint.forwardAxisEnd), [64, 220, 255]);+ drawLine2(frame.rgb, frame.width, frame.height, point, project(joint.bendAxisEnd), [255, 105, 210]);stampLabel(frame.rgb, frame.width, frame.height, Math.max(0, Math.min(frame.width - 2, Math.round(point[0] + 3))), Math.max(0, Math.min(frame.height - 7, Math.round(point[1] - 6))), joint.label.toUpperCase().replace(/[^A-Z0-9]+/g, " ").slice(0, 18), 1);frame.regions.push({nodeName: joint.nodeName,@@ -21905,17 +21858,17 @@ function skeletonCapture(root, request2, findings, size) {Math.min(frame.width - 1, Math.round(point[0]) + 4),Math.min(frame.height - 1, Math.round(point[1]) + 4)],- color: color2,+ color,triangleCount: 0});}- const arrow = descriptor2.canonicalForwardArrow;- drawLine2(frame.rgb, frame.width, frame.height, project2(arrow.start), project2(arrow.end), [255, 220, 64]);+ const arrow = descriptor.canonicalForwardArrow;+ drawLine2(frame.rgb, frame.width, frame.height, project(arrow.start), project(arrow.end), [255, 220, 64]);frame.regions.sort((a, b) => a.nodePath.localeCompare(b.nodePath));return {id: frame.id,label: frame.label,- cameraId: request2.cameraId,+ cameraId: request.cameraId,kind: "skeleton",width: frame.width,height: frame.height,@@ -21936,32 +21889,32 @@ async function captureCharacterDiagnosticViews(root, clips, intent, findings = [const requests = planCharacterDiagnosticRequests(intent);const captures = [];try {- for (const request2 of requests) {- if (request2.variant === "character-skeleton") {- captures.push(skeletonCapture(root, request2, findings, size));+ for (const request of requests) {+ if (request.variant === "character-skeleton") {+ captures.push(skeletonCapture(root, request, findings, size));continue;}- if (!request2.clipName)+ if (!request.clipName)continue;const strip = await renderClipAnimation(root, clips, {- clip: request2.clipName,- camera: request2.cameraId,- frames: request2.phaseFractions?.length ?? 6,+ clip: request.clipName,+ camera: request.cameraId,+ frames: request.phaseFractions?.length ?? 6,size});if (!strip.ok || !strip.png || !strip.width || !strip.height)continue;captures.push({- id: request2.id,- label: request2.label,- cameraId: request2.cameraId,+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,kind: "motion-strip",width: strip.width,height: strip.height,png: strip.png,regions: [],- clipName: request2.clipName,- phaseFractions: request2.phaseFractions+ clipName: request.clipName,+ phaseFractions: request.phaseFractions});}} finally {@@ -22219,28 +22172,28 @@ function bridgeTexture(doc, threeTex, cache) {cache.set(threeTex, t);return t;}-function bridgeGeometry(doc, buf, geometry2, material, meshName) {- if (!geometry2.getAttribute("normal")) {- geometry2.computeVertexNormals();+function bridgeGeometry(doc, buf, geometry, material, meshName) {+ if (!geometry.getAttribute("normal")) {+ geometry.computeVertexNormals();}const prim = doc.createPrimitive().setMaterial(Array.isArray(material) ? material[0] : material);- const posAttr = geometry2.getAttribute("position");+ const posAttr = geometry.getAttribute("position");if (posAttr) {prim.setAttribute("POSITION", doc.createAccessor(meshName + "_pos").setArray(geometryAttributeValues(posAttr)).setType(TYPE_VEC3).setBuffer(buf));}- const normAttr = geometry2.getAttribute("normal");+ const normAttr = geometry.getAttribute("normal");if (normAttr) {prim.setAttribute("NORMAL", doc.createAccessor(meshName + "_norm").setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));}- const uvAttr = geometry2.getAttribute("uv");+ const uvAttr = geometry.getAttribute("uv");if (uvAttr) {prim.setAttribute("TEXCOORD_0", doc.createAccessor(meshName + "_uv").setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));}- const tangentAttr = geometry2.getAttribute("tangent");+ const tangentAttr = geometry.getAttribute("tangent");if (tangentAttr?.itemSize === 4) {prim.setAttribute("TANGENT", doc.createAccessor(meshName + "_tangent").setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));}- const indexAttr = geometry2.getIndex();+ const indexAttr = geometry.getIndex();if (indexAttr) {const IndexArray = posAttr && posAttr.count > 65535 ? Uint32Array : Uint16Array;prim.setIndices(doc.createAccessor(meshName + "_idx").setArray(new IndexArray(indexAttr.array)).setType(TYPE_SCALAR).setBuffer(buf));@@ -22249,15 +22202,15 @@ function bridgeGeometry(doc, buf, geometry2, material, meshName) {if (!Array.isArray(material))return mesh.addPrimitive(prim);const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);- const groups = [...geometry2.groups].sort((a, b) => a.start - b.start);+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);let covered = 0;for (const group of groups) {if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);}const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);- for (const semantic3 of prim.listSemantics())- part.setAttribute(semantic3, prim.getAttribute(semantic3));+ for (const semantic of prim.listSemantics())+ part.setAttribute(semantic, prim.getAttribute(semantic));const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;part.setIndices(doc.createAccessor(meshName + "_group_indices").setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));mesh.addPrimitive(part);@@ -22292,13 +22245,13 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)}}if (semanticForExport !== undefined) {- const semantic3 = validateSemanticMetadataV1(semanticForExport);- if (!semantic3.valid || !semantic3.value) {- const detail = semantic3.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");+ const semantic = validateSemanticMetadataV1(semanticForExport);+ if (!semantic.valid || !semantic.value) {+ const detail = semantic.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on node ${threeObj.name || "<unnamed>"}: ${detail}`);}gtNode.setExtras({- [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic3.value)+ [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic.value)});}gtNode.setTranslation([threeObj.position.x, threeObj.position.y, threeObj.position.z]);@@ -22331,13 +22284,13 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;let gtMesh = meshCache.get(cacheKey);if (!gtMesh) {- const geometry2 = new THREE34.PlaneGeometry(1, 1);+ const geometry = new THREE34.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {- geometry2.translate(0.5 - centerX, 0.5 - centerY, 0);+ geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}if (rotation !== 0)- geometry2.rotateZ(rotation);- gtMesh = bridgeGeometry(doc, buf, geometry2, gtMat, sprite.name || "sprite-quad");+ geometry.rotateZ(rotation);+ gtMesh = bridgeGeometry(doc, buf, geometry, gtMat, sprite.name || "sprite-quad");meshCache.set(cacheKey, gtMesh);}gtNode.setMesh(gtMesh);@@ -22356,11 +22309,11 @@ function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {const anim = doc.createAnimation(clip.name);for (const track of clip.tracks) {const dotIdx = track.name.lastIndexOf(".");- const nodeName2 = track.name.substring(0, dotIdx);+ const nodeName = track.name.substring(0, dotIdx);const property = track.name.substring(dotIdx + 1);- const targetNode = nodeMap.get(nodeName2);+ const targetNode = nodeMap.get(nodeName);if (!targetNode) {- warnings.push(`Animation target "${nodeName2}" not found - skipped`);+ warnings.push(`Animation target "${nodeName}" not found - skipped`);continue;}let targetPath;@@ -22375,11 +22328,11 @@ function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {targetPath = "scale";valueType = TYPE_VEC3;} else {- warnings.push(`Unsupported animation property "${property}" on "${nodeName2}" - skipped`);+ warnings.push(`Unsupported animation property "${property}" on "${nodeName}" - skipped`);continue;}- const inputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);- const outputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);+ const inputAcc = doc.createAccessor(clip.name + "_" + nodeName + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);+ const outputAcc = doc.createAccessor(clip.name + "_" + nodeName + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);const sampler = doc.createAnimationSampler().setInput(inputAcc).setOutput(outputAcc).setInterpolation("LINEAR");const channel = doc.createAnimationChannel().setTargetNode(targetNode).setTargetPath(targetPath).setSampler(sampler);anim.addSampler(sampler);@@ -22700,10 +22653,10 @@ function inspectGeneratedAnimation(root, clips) {warnings.push(`Track "${track.name}" is missing a node.property separator`);continue;}- const nodeName2 = track.name.substring(0, dotIdx);+ const nodeName = track.name.substring(0, dotIdx);const property = track.name.substring(dotIdx + 1);- if (!nodeNames.has(nodeName2)) {- warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName2}" — rename the pivot or fix the track`);+ if (!nodeNames.has(nodeName)) {+ warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName}" — rename the pivot or fix the track`);}if (!["position", "quaternion", "scale"].includes(property)) {warnings.push(`Animation track "${clip.name}:${track.name}" uses unsupported property "${property}"`);@@ -22868,25 +22821,25 @@ function failure(requestId, code, diagnostic, qa) {};}function boundedMaxResponseBytes(value) {- const resolved2 = value ?? DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES;- if (!Number.isInteger(resolved2) || resolved2 < 1 || resolved2 > 96 * 1024 * 1024) {+ const resolved = value ?? DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES;+ if (!Number.isInteger(resolved) || resolved < 1 || resolved > 96 * 1024 * 1024) {throw new EvaluatorPortError("INPUT_INVALID");}- return resolved2;+ return resolved;}function boundedDeadlineMs(value) {- const resolved2 = value ?? DEFAULT_EVALUATOR_DEADLINE_MS;- if (!Number.isInteger(resolved2) || resolved2 < 1 || resolved2 > 120000) {+ const resolved = value ?? DEFAULT_EVALUATOR_DEADLINE_MS;+ if (!Number.isInteger(resolved) || resolved < 1 || resolved > 120000) {throw new EvaluatorPortError("INPUT_INVALID");}- return resolved2;+ return resolved;}async function evaluateEvaluatorRequestV1(requestJson, dependencies = {}, controls = {}) {const maxResponseBytes = boundedMaxResponseBytes(controls.maxResponseBytes);const deadlineMs = boundedDeadlineMs(controls.deadlineMs);- let request2;+ let request;try {- request2 = decodeEvaluatorRequestV1(requestJson);+ request = decodeEvaluatorRequestV1(requestJson);} catch {return JSON.stringify(failure("invalid", "INPUT_INVALID"));}@@ -22894,27 +22847,27 @@ async function evaluateEvaluatorRequestV1(requestJson, dependencies = {}, controlet timer;try {const render = await Promise.race([- (dependencies.render ?? renderGLBInProcess)(request2.code, request2.options),+ (dependencies.render ?? renderGLBInProcess)(request.code, request.options),new Promise((_, reject) => {timer = setTimeout(() => reject(new EvaluatorPortError("DEADLINE_EXCEEDED")), deadlineMs);})]);- if (render.glb.byteLength > request2.limits.maxGlbBytes) {- wire = failure(request2.requestId, "OUTPUT_LIMIT_EXCEEDED");+ if (render.glb.byteLength > request.limits.maxGlbBytes) {+ wire = failure(request.requestId, "OUTPUT_LIMIT_EXCEEDED");} else {- wire = encodeRenderResultV1(request2.requestId, render);+ wire = encodeRenderResultV1(request.requestId, render);}} catch (error) {if (error instanceof AssetQaBlockedError) {- wire = failure(request2.requestId, "QA_BLOCKED", undefined, {+ wire = failure(request.requestId, "QA_BLOCKED", undefined, {report: error.report,stage: error.stage,...error.gltfValidation ? { gltfValidation: error.gltfValidation } : {}});} else if (error instanceof EvaluatorPortError && error.code === "DEADLINE_EXCEEDED") {- wire = failure(request2.requestId, "DEADLINE_EXCEEDED");+ wire = failure(request.requestId, "DEADLINE_EXCEEDED");} else {- wire = failure(request2.requestId, "EXECUTION_REJECTED", error instanceof AuthoringDiagnosticError ? error.diagnostic : undefined);+ wire = failure(request.requestId, "EXECUTION_REJECTED", error instanceof AuthoringDiagnosticError ? error.diagnostic : undefined);}} finally {clearTimeout(timer);@@ -22939,8 +22892,8 @@ import { writeFileSync } from "node:fs";async function readBoundedInput() {const chunks = [];let bytes = 0;- for await (const chunk2 of process.stdin) {- const buffer = Buffer.from(chunk2);+ for await (const chunk of process.stdin) {+ const buffer = Buffer.from(chunk);bytes += buffer.byteLength;if (bytes > MAX_EVALUATOR_REQUEST_BYTES)throw new Error("request limit");diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjsindex fe43bf82..10581025 100644--- a/dist/mcp-server.mjs+++ b/dist/mcp-server.mjs@@ -1,6 +1,5 @@#!/usr/bin/env bun// @bun-import { createRequire } from "node:module";var __defProp = Object.defineProperty;var __returnValue = (v) => v;function __exportSetter(name, newValue) {@@ -15,8 +14,17 @@ var __export = (target, all) => {set: __exportSetter.bind(all, name)});};-var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);-var __require = /* @__PURE__ */ createRequire(import.meta.url);+var __esm = (fn, res, err) => () => {+ if (fn)+ try {+ res = fn(fn = 0);+ } catch (e) {+ err = [e];+ }+ if (err)+ throw err[0];+ return res;+};// src/assets.tsimport { z } from "zod";@@ -110,7 +118,7 @@ var init_assets = __esm(() => {});// src/views/background.ts-var GRID_BACKGROUND_RGB, GRID_BACKGROUND_HEX = "#1a1a1a";+var GRID_BACKGROUND_RGB;var init_background = __esm(() => {GRID_BACKGROUND_RGB = [26, 26, 26];});@@ -123,8 +131,8 @@ function orbitDir(azimuthDeg, elevationDeg) {return [cosEl * Math.cos(az), Math.sin(el), cosEl * Math.sin(az)];}function orbitAnglesOf(dir) {- const [x, y, z2] = normalize(dir);- const azimuthDeg = (Math.atan2(z2, x) * 180 / Math.PI % 360 + 360) % 360;+ const [x, y, z] = normalize(dir);+ const azimuthDeg = (Math.atan2(z, x) * 180 / Math.PI % 360 + 360) % 360;return {azimuthDeg: +azimuthDeg.toFixed(2),elevationDeg: +(Math.asin(Math.min(1, Math.max(-1, y))) * 180 / Math.PI).toFixed(2)@@ -180,10 +188,10 @@ function collectTriangles(root) {for (let i = 0;i < pos.count; i++) {const x = arr[i * 3];const y = arr[i * 3 + 1];- const z2 = arr[i * 3 + 2];- const wx = m[0] * x + m[4] * y + m[8] * z2 + m[12];- const wy = m[1] * x + m[5] * y + m[9] * z2 + m[13];- const wz = m[2] * x + m[6] * y + m[10] * z2 + m[14];+ const z = arr[i * 3 + 2];+ const wx = m[0] * x + m[4] * y + m[8] * z + m[12];+ const wy = m[1] * x + m[5] * y + m[9] * z + m[13];+ const wz = m[2] * x + m[6] * y + m[10] * z + m[14];world[i * 3] = wx;world[i * 3 + 1] = wy;world[i * 3 + 2] = wz;@@ -254,10 +262,10 @@ function rasterizeView(root, dir, opts = {}) {}if (tris.length === 0)return out;- const z2 = normalize(dir);- const upHint = Math.abs(z2[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];- const x = normalize(cross(upHint, z2));- const y = cross(z2, x);+ const z = normalize(dir);+ const upHint = Math.abs(z[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];+ const x = normalize(cross(upHint, z));+ const y = cross(z, x);const frameMin = opts.frameBounds ? opts.frameBounds.min : bbox.min;const frameMax = opts.frameBounds ? opts.frameBounds.max : bbox.max;const center = [@@ -287,7 +295,7 @@ function rasterizeView(root, dir, opts = {}) {if (nLen < 0.000000000001)continue;const N = [n[0] / nLen, n[1] / nLen, n[2] / nLen];- const facing = dot(N, z2);+ const facing = dot(N, z);if (cull && facing <= 0 && !tri.doubleSided)continue;if (tri.alpha <= 0)@@ -299,7 +307,7 @@ function rasterizeView(root, dir, opts = {}) {const p = [px, py, pz];sx[i] = half + dot(p, x) * scale;sy[i] = half - dot(p, y) * scale;- sz[i] = dot(p, z2);+ sz[i] = dot(p, z);}const lambert = Math.max(0, dot(N, KEY_DIR));const lit = Math.min(1, AMBIENT + KEY_INTENSITY * lambert);@@ -350,14 +358,6 @@ function measureBounds(root) {const { bbox } = collectTriangles(root);return { min: [...bbox.min], max: [...bbox.max] };}-function coverage(rgb, size) {- let filled = 0;- for (let i = 0;i < size * size; i++) {- if (rgb[i * 3] !== BG[0] || rgb[i * 3 + 1] !== BG[1] || rgb[i * 3 + 2] !== BG[2])- filled++;- }- return filled / (size * size);-}function hideNodeInScene(root, match) {const test = typeof match === "function" ? match : (name) => {const t = match.toLowerCase();@@ -415,10 +415,10 @@ function triple(v, label) {}function listCameraSubjects(root) {const result = [];- const visit = (node2, path) => {- result.push({ node: node2, path, name: node2.name });+ const visit = (node, path) => {+ result.push({ node, path, name: node.name });const counts = new Map;- for (const child of node2.children ?? []) {+ for (const child of node.children ?? []) {const count = counts.get(child.name) ?? 0;counts.set(child.name, count + 1);visit(child, `${path}/${encodeURIComponent(child.name)}[${count}]`);@@ -444,14 +444,14 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {if (!Number.isFinite(padding) || padding <= 0 || padding > 100)throw new Error("padding must be in (0,100]");const target = vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);- const z2 = vec(dir).normalize();- if (!z2.length())+ const z = vec(dir).normalize();+ if (!z.length())throw new Error("camera direction must be non-zero");- const hint = up ? vec(up) : Math.abs(z2.y) > 0.99 ? new Vector3(0, 0, -1) : new Vector3(0, 1, 0);- const x = hint.clone().cross(z2).normalize();+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector3(0, 0, -1) : new Vector3(0, 1, 0);+ const x = hint.clone().cross(z).normalize();if (x.length() < 0.000000001)throw new Error("camera up must not be collinear with view");- const y = z2.clone().cross(x);+ const y = z.clone().cross(x);let extent = 0.000001;for (let i = 0;i < 8; i++) {const p = new Vector3((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);@@ -464,7 +464,7 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {return {version: "kiln.camera.v1",projection: "orthographic",- position: tuple(target.clone().addScaledVector(z2, distance)),+ position: tuple(target.clone().addScaledVector(z, distance)),target: tuple(target),up: tuple(y),aspect: 1,@@ -524,13 +524,13 @@ function resolveAssetCamera(root, shot = {}) {let camera;if (request.type === "orbit") {strict(request, ["type", "azimuthDeg", "elevationDeg", "relativeTo", "padding"], "camera");- const relative2 = request.relativeTo ?? "world";- if (!["world", "asset", "part"].includes(relative2))+ const relative = request.relativeTo ?? "world";+ if (!["world", "asset", "part"].includes(relative))throw new Error("invalid relativeTo");const dir = vec(orbitDir(finite(request.azimuthDeg ?? 45, "azimuthDeg"), finite(request.elevationDeg ?? 25, "elevationDeg")));let up;- if (relative2 !== "world") {- const node = relative2 === "part" ? selected.node : rootNode;+ if (relative !== "world") {+ const node = relative === "part" ? selected.node : rootNode;dir.transformDirection(node.matrixWorld);up = tuple(new Vector3(0, 1, 0).transformDirection(node.matrixWorld));}@@ -554,10 +554,10 @@ function resolveAssetCamera(root, shot = {}) {], "camera");if (request.projection === "orthographic" && request.fovDeg !== undefined || request.projection === "perspective" && request.halfHeight !== undefined)throw new Error("projection and lens fields conflict");- const relative2 = request.relativeTo ?? "world";- if (!["world", "asset", "part", "local"].includes(relative2))+ const relative = request.relativeTo ?? "world";+ if (!["world", "asset", "part", "local"].includes(relative))throw new Error("invalid relativeTo");- if (relative2 === "local" !== Boolean(request.frame))+ if (relative === "local" !== Boolean(request.frame))throw new Error("local coordinates require frame; frame is only valid for local coordinates");if (request.framing !== undefined && !["explicit", "bounds"].includes(request.framing))throw new Error("invalid framing");@@ -568,8 +568,8 @@ function resolveAssetCamera(root, shot = {}) {if (request.framing === "bounds" && request.halfHeight !== undefined)throw new Error("bounds framing derives halfHeight");let matrix = new Matrix4;- if (relative2 === "asset" || relative2 === "part")- matrix = (relative2 === "asset" ? rootNode : selected.node).matrixWorld;+ if (relative === "asset" || relative === "part")+ matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;if (request.frame) {strict(request.frame, ["origin", "rotation"], "frame");const rotation = triple(request.frame.rotation ?? [0, 0, 0], "frame.rotation");@@ -650,7 +650,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true) {const camera = validateResolvedAssetCamera(input);if (!Number.isInteger(size) || size < 1 || size > 2048)throw new Error("camera size must be an integer in 1..2048");- const z2 = vec(camera.position).sub(vec(camera.target)).normalize(), x = vec(camera.up).cross(z2).normalize(), y = z2.clone().cross(x), position = vec(camera.position);+ const z = vec(camera.position).sub(vec(camera.target)).normalize(), x = vec(camera.up).cross(z).normalize(), y = z.clone().cross(x), position = vec(camera.position);const out = new Uint8Array(size * size * 3);for (let i = 0;i < size * size; i++)out.set(GRID_BACKGROUND_RGB, i * 3);@@ -672,7 +672,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true) {for (const tri of collectTriangles(root).tris) {const world = [0, 1, 2].map((i) => new Vector3(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));const normal = world[1].clone().sub(world[0]).cross(world[2].clone().sub(world[0])).normalize();- if (backfaceCull && !tri.doubleSided && normal.dot(camera.projection === "perspective" ? position.clone().sub(world[0]) : z2) <= 0)+ if (backfaceCull && !tri.doubleSided && normal.dot(camera.projection === "perspective" ? position.clone().sub(world[0]) : z) <= 0)continue;if (tri.alpha <= 0)continue;@@ -680,7 +680,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true) {const color = tri.color.map((c) => Math.round(srgb(c * light) * 255));let polygon = world.map((p) => {const d = p.clone().sub(position);- return new Vector3(d.dot(x), d.dot(y), -d.dot(z2));+ return new Vector3(d.dot(x), d.dot(y), -d.dot(z));});polygon = clip(clip(polygon, camera.near, true), camera.far, false);for (let t = 1;t < polygon.length - 1; t++) {@@ -813,12 +813,12 @@ function validatePbrRenderRequest(input) {target[1] - position[1],target[2] - position[2]];- const cross2 = [+ const cross = [view[1] * up[2] - view[2] * up[1],view[2] * up[0] - view[0] * up[2],view[0] * up[1] - view[1] * up[0]];- if (Math.hypot(...cross2) <= Math.hypot(...view) * Math.hypot(...up) * 0.000000001) {+ if (Math.hypot(...cross) <= Math.hypot(...view) * Math.hypot(...up) * 0.000000001) {throw new TypeError(`PbrRenderRequest.cameras[${index}].up must not be collinear with view`);}const number = (key) => {@@ -1044,11 +1044,11 @@ function prepareClip(root, clip) {const raw = track.name;if (!raw)continue;- const dot2 = raw.lastIndexOf(".");- if (dot2 === -1)+ const dot = raw.lastIndexOf(".");+ if (dot === -1)continue;- const nodeName = raw.slice(0, dot2);- const property = raw.slice(dot2 + 1);+ const nodeName = raw.slice(0, dot);+ const property = raw.slice(dot + 1);if (property !== "position" && property !== "quaternion" && property !== "scale")continue;const times = track.times ? Array.from(track.times) : [];@@ -1264,19 +1264,19 @@ var init_pose = __esm(() => {// src/views/annotate.tsfunction stampAxisGnomon(rgb, size, viewDir) {const zl = Math.hypot(viewDir[0], viewDir[1], viewDir[2]) || 1;- const z2 = [viewDir[0] / zl, viewDir[1] / zl, viewDir[2] / zl];- const up = Math.abs(z2[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];+ const z = [viewDir[0] / zl, viewDir[1] / zl, viewDir[2] / zl];+ const up = Math.abs(z[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];const cx = [- up[1] * z2[2] - up[2] * z2[1],- up[2] * z2[0] - up[0] * z2[2],- up[0] * z2[1] - up[1] * z2[0]+ up[1] * z[2] - up[2] * z[1],+ up[2] * z[0] - up[0] * z[2],+ up[0] * z[1] - up[1] * z[0]];const xl = Math.hypot(cx[0], cx[1], cx[2]) || 1;const bx = [cx[0] / xl, cx[1] / xl, cx[2] / xl];const by = [- z2[1] * bx[2] - z2[2] * bx[1],- z2[2] * bx[0] - z2[0] * bx[2],- z2[0] * bx[1] - z2[1] * bx[0]+ z[1] * bx[2] - z[2] * bx[1],+ z[2] * bx[0] - z[0] * bx[2],+ z[0] * bx[1] - z[1] * bx[0]];const len = Math.max(12, Math.round(size * 0.055));const ox = len + 10;@@ -1406,14 +1406,6 @@ var init_grid = __esm(() => {});// src/views/capture-limits.ts-var exports_capture_limits = {};-__export(exports_capture_limits, {- resolveCaptureLimits: () => resolveCaptureLimits,- enforcePngCaptureBudget: () => enforcePngCaptureBudget,- enforceCapturePixels: () => enforceCapturePixels,- enforceCaptureBytes: () => enforceCaptureBytes,- DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS-});function resolveCaptureLimits(limits = {}) {const result = { ...DEFAULT_CAPTURE_LIMITS };for (const key of ["maxTotalPixels", "maxOutputBytes"]) {@@ -1466,9 +1458,9 @@ var init_capture_limits = __esm(() => {// src/views/capture-cache.tsvar exports_capture_cache = {};__export(exports_capture_cache, {- createCachedRenderPort: () => createCachedRenderPort,+ MemoryCaptureCache: () => MemoryCaptureCache,captureCpuCell: () => captureCpuCell,- MemoryCaptureCache: () => MemoryCaptureCache+ createCachedRenderPort: () => createCachedRenderPort});import { createHash as createHash2 } from "node:crypto";function clone(entry) {@@ -1537,9 +1529,9 @@ function canonical(value) {return value;throw new Error("Capture identity must be data");}-function usable(result, request, hash2) {+function usable(result, request, hash) {try {- if (!result.ok || !result.rendererId?.trim() || result.derivativeFidelity?.materialFaithful !== true || result.derivativeFidelity.inputGlbSha256 !== hash2)+ if (!result.ok || !result.rendererId?.trim() || result.derivativeFidelity?.materialFaithful !== true || result.derivativeFidelity.inputGlbSha256 !== hash)return false;const count = (request.cameras ?? request.viewDirs).length;if (result.viewsPng?.length !== count)@@ -1566,13 +1558,13 @@ function createCachedRenderPort(port, options) {return port(input);const validated = validatePbrRenderRequest(input);const request = { ...validated, glb: Uint8Array.from(validated.glb) };- const hash2 = digest2(request.glb);+ const hash = digest2(request.glb);const selectors = request.cameras ?? request.viewDirs;const keys = selectors.map((selector) => digest2(text({version: "kiln.capture-cache.v1",kind: "gpu",identity,- artifact: hash2,+ artifact: hash,selector,size: request.size,width: request.width,@@ -1589,7 +1581,7 @@ function createCachedRenderPort(port, options) {...request,...request.cameras ? { cameras: [request.cameras[i]] } : { viewDirs: [request.viewDirs[i]] }};- if (cached?.kind === "gpu" && usable(cached.result, single, hash2))+ if (cached?.kind === "gpu" && usable(cached.result, single, hash))cells[i] = cached.result;elsemissing.push(i);@@ -1609,7 +1601,7 @@ function createCachedRenderPort(port, options) {rendererId: produced.rendererId,error: "capture producer changed during render"};- if (!usable(produced, subrequest, hash2)) {+ if (!usable(produced, subrequest, hash)) {return missing.length === selectors.length ? produced : {ok: false,rendererId: produced.rendererId,@@ -1649,11 +1641,11 @@ function createCachedRenderPort(port, options) {async function captureCpuCell(cache, identity, produce) {const snapshot = structuredClone(identity);const key = digest2(text({ version: "kiln.capture-cache.v1", kind: "cpu", ...snapshot }));- const valid = (result2) => {+ const valid = (result) => {try {- enforcePngCaptureBudget([result2.png]);- const image = decodePng(result2.png);- return result2.inputGlbSha256 === snapshot.artifactGlbSha256 && image.width === snapshot.size && image.height === snapshot.size && result2.width === snapshot.size && result2.height === snapshot.size;+ enforcePngCaptureBudget([result.png]);+ const image = decodePng(result.png);+ return result.inputGlbSha256 === snapshot.artifactGlbSha256 && image.width === snapshot.size && image.height === snapshot.size && result.width === snapshot.size && result.height === snapshot.size;} catch {return false;}@@ -4803,7 +4795,7 @@ function readSemanticMetadataV1FromExtras(extras) {const result = validateSemanticMetadataV1(value);return result.valid ? result.value : undefined;}-var KILN_SEMANTIC_EXTRAS_KEY = "kilnSemantic", KILN_SEMANTIC_SCHEMA_VERSION = 1, KILN_SEMANTIC_ROLES, isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isNonEmptyString2 = (value) => typeof value === "string" && value.trim().length > 0 && value === value.trim(), isFiniteTuple = (value, length2) => Array.isArray(value) && value.length === length2 && value.every((component) => typeof component === "number" && Number.isFinite(component)), cloneTuple3 = (value) => [+var KILN_SEMANTIC_EXTRAS_KEY = "kilnSemantic", KILN_SEMANTIC_SCHEMA_VERSION = 1, KILN_SEMANTIC_ROLES, isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isNonEmptyString2 = (value) => typeof value === "string" && value.trim().length > 0 && value === value.trim(), isFiniteTuple = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), cloneTuple3 = (value) => [value[0],value[1],value[2]@@ -4894,11475 +4886,3533 @@ var init_types = __esm(() => {];});-// src/qa/registry.ts-import { createHash as createHash3 } from "node:crypto";-function canonicalCalibrationReportEvidence(report) {- return JSON.stringify({- schemaVersion: report.schemaVersion,- reportId: report.reportId,- thresholdId: report.thresholdId,- thresholdSha256: report.thresholdSha256,- heldOutSetVersion: report.heldOutSetVersion,- heldOutSetSha256: report.heldOutSetSha256,- reviewAuthorityScheme: report.reviewAuthorityScheme,- reviewAuthorityKeyId: report.reviewAuthorityKeyId,- reviewAuthorityPublicKeySha256: report.reviewAuthorityPublicKeySha256,- ruleCode: report.ruleCode,- source: report.source,- generatedAt: report.generatedAt,- labeledCases: report.labeledCases,- evaluatedCases: report.evaluatedCases,- insufficientEvidenceCases: report.insufficientEvidenceCases,- humanDisagreementCases: report.humanDisagreementCases,- validExamples: report.validExamples,- defectiveExamples: report.defectiveExamples,- truePositive: report.truePositive,- falsePositive: report.falsePositive,- trueNegative: report.trueNegative,- falseNegative: report.falseNegative,- precision: report.precision,- recall: report.recall,- meanConfidence: report.meanConfidence,- styles: report.styles,- falseBlocks: report.falseBlocks- });+// src/geometry-export.ts+function geometryAttributeValues(attribute) {+ const values = new Float32Array(attribute.count * attribute.itemSize);+ for (let vertex = 0;vertex < attribute.count; vertex++) {+ for (let component = 0;component < attribute.itemSize; component++) {+ values[vertex * attribute.itemSize + component] = attribute.getComponent(vertex, component);+ }+ }+ return values;}-function calibrationReportEvidenceSha256(report) {- return createHash3("sha256").update(canonicalCalibrationReportEvidence(report)).digest("hex");+function inspectGeometryExport(root, policy = "warn") {+ const warnings = [];+ root.traverse((node) => {+ const mesh = node;+ if (!mesh.isMesh)+ return;+ const geometry = mesh.geometry;+ const name = mesh.name || "<unnamed mesh>";+ const unsupported = (feature) => {+ const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.`;+ if (policy === "strict")+ throw new TypeError(message);+ warnings.push(message);+ };+ const position = geometry.getAttribute("position");+ if (!position || position.itemSize !== 3)+ throw new TypeError(`${name}: position requires xyz vertices.`);+ for (const [key, attribute] of Object.entries(geometry.attributes)) {+ const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key];+ if (expected === undefined) {+ unsupported(key);+ continue;+ }+ if (attribute.itemSize !== expected || attribute.count !== position.count) {+ throw new TypeError(`${name}: ${key} requires ${position.count} vertices with ${expected} components each.`);+ }+ for (let vertex = 0;vertex < attribute.count; vertex++) {+ for (let component = 0;component < attribute.itemSize; component++) {+ if (!Number.isFinite(attribute.getComponent(vertex, component))) {+ throw new TypeError(`${name}: ${key} contains a non-finite value at vertex ${vertex}.`);+ }+ }+ }+ }+ const index = geometry.getIndex();+ if ((index?.count ?? position.count) % 3 !== 0)+ throw new TypeError(`${name}: triangle indices/vertices must be a multiple of three.`);+ if (index) {+ for (let i = 0;i < index.count; i++) {+ const value = index.getX(i);+ if (!Number.isInteger(value) || value < 0 || value >= position.count)+ throw new TypeError(`${name}: index ${i} is outside the position attribute.`);+ }+ }+ for (const key of Object.keys(geometry.morphAttributes))+ unsupported(`morph ${key}`);+ if (mesh.isSkinnedMesh)+ unsupported("skinning");+ for (const key of ["kilnAttributeWarnings", "kilnGeometryWarnings"]) {+ const notes = geometry.userData[key];+ if (!Array.isArray(notes))+ continue;+ for (const note of notes) {+ if (typeof note === "string")+ warnings.push(`${name}: ${note}`);+ else if (note && typeof note === "object" && "code" in note)+ warnings.push(`${name}: ${String(note.code)}${"message" in note ? ` ${String(note.message)}` : ""}`);+ }+ }+ });+ return warnings;}-function conformancePromotionAuthorization(fixtureSetId, fixturePath, evidenceSha256, owner = KILN_ENGINE_QA_OWNER, frozenAt = "2026-07-09T00:00:00.000Z", authorizedMode = "enforce", rendererId = LEGACY_CPU_RASTER_RENDERER_ID) {- return {- basis: "conformance",- authorizedMode,- fixtureSetId,- fixturePath,- evidenceSha256,- frozenAt,- authorizedBy: owner.id,- rendererId+var EXPORTED_GEOMETRY_ATTRIBUTES;+var init_geometry_export = __esm(() => {+ EXPORTED_GEOMETRY_ATTRIBUTES = {+ position: 3,+ normal: 3,+ uv: 2,+ tangent: 4};+});++// src/palette-snap.ts+function srgbChannelToLinear(c) {+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;}-function evidenceId(promotion) {- return promotion.basis === "conformance" ? promotion.fixtureSetId : promotion.packetId;+function hexToLinearRgb(hex) {+ const h = hex.trim().replace(/^#/, "");+ const full = h.length === 3 ? h[0] + h[0] + h[1] + h[1] + h[2] + h[2] : h;+ const n = Number.parseInt(full.slice(0, 6).padEnd(6, "0"), 16);+ const r = (n >> 16 & 255) / 255;+ const g = (n >> 8 & 255) / 255;+ const b = (n & 255) / 255;+ return [srgbChannelToLinear(r), srgbChannelToLinear(g), srgbChannelToLinear(b)];}-function assertOwner(owner, ruleId) {- if (!owner || !OWNER_ID_PATTERN.test(owner.id) || owner.id === "unknown") {- throw new TypeError(`QA rule ${ruleId} must name a stable rule owner`);- }- if (owner.authority !== "named" && owner.authority !== "delegated") {- throw new TypeError(`QA rule ${ruleId} has an invalid owner authority`);- }+function linToOklab(r, g, b) {+ const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;+ const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;+ const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;+ const l_ = Math.cbrt(l), m_ = Math.cbrt(m), s_ = Math.cbrt(s);+ return [+ 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,+ 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,+ 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_+ ];}-function assertNonNegativeInteger(value, path, ruleId) {- if (!Number.isInteger(value) || value < 0) {- throw new TypeError(`QA rule ${ruleId} calibration ${path} must be a non-negative integer`);- }+function buildSlotIndex(slots) {+ const opaque = [];+ const neutral = [];+ const chromatic = [];+ const glass = [];+ const glow = [];+ slots.forEach((s, i) => {+ const kind = s.kind ?? "opaque";+ const [r, g, b] = hexToLinearRgb(s.color);+ const lab = linToOklab(r, g, b);+ if (kind === "glass") {+ glass.push(i);+ return;+ }+ if (kind === "glow") {+ glow.push({ i, lab });+ return;+ }+ opaque.push({ i, lab });+ if (relChroma(lab) >= REL_CHROMA_GATE)+ chromatic.push({ i, lab });+ else+ neutral.push({ i, lab });+ });+ return { slots, opaque, neutral, chromatic, glass, glow };}-function assertCalibrationPromotion(rule, promotion) {- const report = promotion.report;- if (report.schemaVersion !== 1) {- throw new TypeError(`QA rule ${rule.id} calibration report schemaVersion must be 1`);- }- if (!OWNER_ID_PATTERN.test(report.reportId) || promotion.packetId !== report.reportId) {- throw new TypeError(`QA rule ${rule.id} calibration packet/report identity mismatch`);- }- if (report.thresholdId !== QA_026_CALIBRATION_THRESHOLD_ID || report.thresholdSha256 !== QA_026_CALIBRATION_THRESHOLD_SHA256) {- throw new TypeError(`QA rule ${rule.id} calibration threshold identity mismatch`);- }- if (report.heldOutSetVersion !== QA_026_HELD_OUT_SET_VERSION || report.heldOutSetSha256 !== QA_026_HELD_OUT_SET_SHA256) {- throw new TypeError(`QA rule ${rule.id} calibration held-out set identity mismatch`);+function nearestIn(cands, lab, dist) {+ let best = cands[0].i, bd = Infinity;+ for (const c of cands) {+ const d = dist(c.lab, lab);+ if (d < bd) {+ bd = d;+ best = c.i;+ }}- if (report.reviewAuthorityScheme !== QA_026_REVIEW_AUTHORITY_SCHEME || report.reviewAuthorityKeyId !== QA_026_REVIEW_AUTHORITY_KEY_ID || report.reviewAuthorityPublicKeySha256 !== QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256) {- throw new TypeError(`QA rule ${rule.id} calibration review authority identity mismatch`);+ return best;+}+function nearestOpaqueSlot(idx, lin) {+ if (idx.opaque.length === 0)+ return;+ const lab = linToOklab(lin[0], lin[1], lin[2]);+ if (relChroma(lab) >= REL_CHROMA_GATE) {+ return idx.chromatic.length ? nearestIn(idx.chromatic, lab, dE2Chroma) : nearestIn(idx.opaque, lab, dE2);}- if (report.ruleCode !== rule.id) {- throw new TypeError(`QA rule ${rule.id} calibration report targets ${report.ruleCode}`);+ return idx.neutral.length ? nearestIn(idx.neutral, lab, dE2) : nearestIn(idx.opaque, lab, dE2);+}+function nearestGlowSlot(idx, emissiveLin) {+ if (idx.glow.length === 0)+ return;+ return nearestIn(idx.glow, linToOklab(emissiveLin[0], emissiveLin[1], emissiveLin[2]), dE2);+}+function chooseSlot(idx, m) {+ const emi = m.emissiveLinear;+ const isEmissive = !!emi && (emi[0] > 0.0025 || emi[1] > 0.0025 || emi[2] > 0.0025);+ if (isEmissive) {+ const g = nearestGlowSlot(idx, emi);+ if (g !== undefined)+ return g;}- const expectedSource = rule.ruleClass === "vlm" ? "vlm" : "deterministic-heuristic";- if (report.source !== expectedSource) {- throw new TypeError(`QA rule ${rule.id} calibration source must be ${expectedSource}`);+ if (m.transparent && idx.glass.length > 0) {+ if (idx.glass.length === 1)+ return idx.glass[0];+ const lab = linToOklab(m.baseLinear[0], m.baseLinear[1], m.baseLinear[2]);+ let best = idx.glass[0], bd = Infinity;+ for (const gi of idx.glass) {+ const [r, g, b] = hexToLinearRgb(idx.slots[gi].color);+ const d = dE2(linToOklab(r, g, b), lab);+ if (d < bd) {+ bd = d;+ best = gi;+ }+ }+ return best;}- if (!Number.isFinite(Date.parse(report.generatedAt))) {- throw new TypeError(`QA rule ${rule.id} calibration report generatedAt is invalid`);- }- if (Date.parse(promotion.frozenAt) < Date.parse(report.generatedAt)) {- throw new TypeError(`QA rule ${rule.id} calibration cannot be frozen before its report`);- }- const actualReportSha256 = calibrationReportEvidenceSha256(report);- if (promotion.evidenceSha256 !== actualReportSha256) {- throw new TypeError(`QA rule ${rule.id} calibration report SHA-256 mismatch`);- }- for (const field of [- "labeledCases",- "evaluatedCases",- "insufficientEvidenceCases",- "humanDisagreementCases",- "validExamples",- "defectiveExamples",- "truePositive",- "falsePositive",- "trueNegative",- "falseNegative",- "styles",- "falseBlocks"- ]) {- assertNonNegativeInteger(report[field], field, rule.id);- }- if (!Number.isFinite(report.precision) || report.precision < 0 || report.precision > 1 || !Number.isFinite(report.recall) || report.recall < 0 || report.recall > 1) {- throw new TypeError(`QA rule ${rule.id} calibration precision/recall must be within [0, 1]`);- }- if (report.validExamples !== report.trueNegative + report.falsePositive) {- throw new TypeError(`QA rule ${rule.id} calibration valid-example confusion counts mismatch`);+ return nearestOpaqueSlot(idx, m.baseLinear);+}+var dE2 = (a, b) => {+ const dl = a[0] - b[0], da = a[1] - b[1], db = a[2] - b[2];+ return dl * dl + da * da + db * db;+}, L_WEIGHT_CHROMA = 0.3, dE2Chroma = (a, b) => {+ const dl = a[0] - b[0], da = a[1] - b[1], db = a[2] - b[2];+ return L_WEIGHT_CHROMA * dl * dl + da * da + db * db;+}, chroma = (lab) => Math.hypot(lab[1], lab[2]), REL_CHROMA_GATE = 0.04, relChroma = (lab) => chroma(lab) / Math.max(lab[0], 0.25);++// src/character.ts+import * as THREE from "three";+function validRole(value) {+ return typeof value === "string" && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value);+}+function validateUnitVector(value, path, issues) {+ if (!isFiniteTuple2(value, 3)) {+ issues.push({ code: "INVALID_AXIS", path, message: `${path} must be three finite numbers.` });+ return false;}- if (report.defectiveExamples !== report.truePositive + report.falseNegative) {- throw new TypeError(`QA rule ${rule.id} calibration defective-example confusion counts mismatch`);+ const magnitude = Math.hypot(...value);+ if (Math.abs(magnitude - 1) > 0.000001) {+ issues.push({ code: "NON_UNIT_AXIS", path, message: `${path} must be normalized.` });+ return false;}- if (report.evaluatedCases !== report.validExamples + report.defectiveExamples) {- throw new TypeError(`QA rule ${rule.id} calibration evaluated-case count mismatch`);+ return true;+}+function cloneCharacterJointDescriptorV1(descriptor) {+ return {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ role: descriptor.role,+ aliases: [...descriptor.aliases],+ ...descriptor.parentRole ? { parentRole: descriptor.parentRole } : {},+ side: descriptor.side,+ rest: {+ translation: tuple3(descriptor.rest.translation),+ rotation: tuple4(descriptor.rest.rotation),+ scale: tuple3(descriptor.rest.scale)+ },+ localForwardAxis: tuple3(descriptor.localForwardAxis),+ localBendAxis: tuple3(descriptor.localBendAxis),+ endEffector: descriptor.endEffector,+ contact: descriptor.contact+ };+}+function validateCharacterJointDescriptorV1(value) {+ const issues = [];+ if (!isRecord4(value)) {+ return {+ valid: false,+ issues: [+ { code: "EXPECTED_OBJECT", path: "", message: "Joint descriptor must be an object." }+ ]+ };}- if (report.labeledCases !== report.evaluatedCases + report.insufficientEvidenceCases + report.humanDisagreementCases) {- throw new TypeError(`QA rule ${rule.id} calibration labeled-case count mismatch`);+ if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {+ issues.push({+ code: "UNSUPPORTED_SCHEMA_VERSION",+ path: "schemaVersion",+ message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`+ });}- const warn = QA_026_WARN_PROMOTION_MINIMUMS;- if (report.evaluatedCases < warn.evaluatedCases || report.validExamples < warn.validExamples || report.defectiveExamples < warn.defectiveExamples || report.styles < warn.styles) {- throw new Error(`QA rule ${rule.id} calibration does not meet the warn promotion minimums`);+ if (!validRole(value.role)) {+ issues.push({+ code: "INVALID_ROLE",+ path: "role",+ message: "role must be a stable lowercase ID."+ });}- const expectedPrecision = roundedRatio(report.truePositive, report.truePositive + report.falsePositive);- const expectedRecall = roundedRatio(report.truePositive, report.truePositive + report.falseNegative);- if (!Number.isFinite(expectedPrecision) || !Number.isFinite(expectedRecall) || report.precision !== expectedPrecision || report.recall !== expectedRecall) {- throw new TypeError(`QA rule ${rule.id} calibration metrics do not match confusion counts`);+ if (!Array.isArray(value.aliases) || value.aliases.some((alias) => typeof alias !== "string" || alias.trim().length === 0)) {+ issues.push({+ code: "INVALID_ALIASES",+ path: "aliases",+ message: "aliases must be non-empty strings."+ });+ } else if (new Set(value.aliases).size !== value.aliases.length) {+ issues.push({ code: "DUPLICATE_ALIAS", path: "aliases", message: "aliases must be unique." });}- if (report.insufficientEvidenceCases !== 0 || report.humanDisagreementCases !== 0) {- throw new Error(`QA rule ${rule.id} calibration has unresolved evidence or human disagreement`);+ if (value.parentRole !== undefined && !validRole(value.parentRole)) {+ issues.push({+ code: "INVALID_PARENT_ROLE",+ path: "parentRole",+ message: "parentRole must be a stable lowercase ID."+ });}- if (report.precision < warn.precision || report.recall < warn.recall) {- throw new Error(`QA rule ${rule.id} calibration does not meet the warn promotion minimums`);+ if (!CHARACTER_JOINT_SIDES.includes(value.side)) {+ issues.push({+ code: "INVALID_SIDE",+ path: "side",+ message: "side must be left, right, or center."+ });}- if (report.source === "vlm") {- if (report.meanConfidence === null || !Number.isFinite(report.meanConfidence) || report.meanConfidence < warn.vlmMeanConfidence || report.meanConfidence > 1) {- throw new Error(`QA rule ${rule.id} VLM calibration confidence is below the warn minimum`);+ if (!isRecord4(value.rest)) {+ issues.push({ code: "INVALID_REST", path: "rest", message: "rest transform is required." });+ } else {+ if (!isFiniteTuple2(value.rest.translation, 3)) {+ issues.push({+ code: "INVALID_REST_TRANSLATION",+ path: "rest.translation",+ message: "rest.translation must be three finite meters."+ });}- if (promotion.authorizedMode !== "warn") {- throw new Error(`VLM QA rule ${rule.id} promotion is permanently capped at warn`);+ if (!isFiniteTuple2(value.rest.rotation, 4)) {+ issues.push({+ code: "INVALID_REST_ROTATION",+ path: "rest.rotation",+ message: "rest.rotation must be a finite quaternion."+ });+ } else if (Math.abs(Math.hypot(...value.rest.rotation) - 1) > 0.000001) {+ issues.push({+ code: "NON_UNIT_REST_ROTATION",+ path: "rest.rotation",+ message: "rest.rotation must be normalized."+ });+ }+ if (!isFiniteTuple2(value.rest.scale, 3) || value.rest.scale.some((component) => component <= 0)) {+ issues.push({+ code: "INVALID_REST_SCALE",+ path: "rest.scale",+ message: "rest.scale must contain three positive finite values."+ });}- } else if (report.meanConfidence !== null) {- throw new TypeError(`QA rule ${rule.id} deterministic calibration meanConfidence must be null`);}- if (promotion.authorizedMode === "warn") {- if (report.falseBlocks !== 0) {- throw new Error(`QA rule ${rule.id} warning calibration cannot report false blocks`);+ const forwardAxis = value.localForwardAxis;+ const bendAxis = value.localBendAxis;+ const forwardValid = validateUnitVector(forwardAxis, "localForwardAxis", issues);+ const bendValid = validateUnitVector(bendAxis, "localBendAxis", issues);+ if (forwardValid && bendValid) {+ const dot = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];+ if (Math.abs(dot) > 0.000001) {+ issues.push({+ code: "NON_ORTHOGONAL_AXES",+ path: "localBendAxis",+ message: "local forward and bend axes must be orthogonal."+ });}- return;}- const enforce = QA_026_ENFORCE_PROMOTION_MINIMUMS;- if (report.evaluatedCases < enforce.evaluatedCases || report.validExamples < enforce.validExamples || report.defectiveExamples < enforce.defectiveExamples || report.precision < enforce.precision || report.recall < enforce.recall || report.styles < enforce.styles || report.falsePositive !== 0 || report.falseBlocks !== enforce.falseBlocks) {- throw new Error(`QA rule ${rule.id} calibration does not meet the enforce promotion minimums`);+ if (typeof value.endEffector !== "boolean") {+ issues.push({+ code: "INVALID_END_EFFECTOR",+ path: "endEffector",+ message: "endEffector must be boolean."+ });}-}-function assertPromotionShape(rule, promotion) {- if (promotion.authorizedMode !== "warn" && promotion.authorizedMode !== "enforce") {- throw new TypeError(`QA rule ${rule.id} promotion must explicitly authorize warn or enforce`);+ if (typeof value.contact !== "boolean") {+ issues.push({ code: "INVALID_CONTACT", path: "contact", message: "contact must be boolean." });}- if (!evidenceId(promotion).trim()) {- throw new TypeError(`QA rule ${rule.id} promotion evidence must have a stable id`);+ if (issues.length > 0)+ return { valid: false, issues };+ return {+ valid: true,+ value: cloneCharacterJointDescriptorV1(value),+ issues+ };+}+function createCharacterJointDescriptorV1(input) {+ const descriptor = {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ role: input.role,+ aliases: [...input.aliases ?? []],+ ...input.parentRole ? { parentRole: input.parentRole } : {},+ side: input.side ?? "center",+ rest: {+ translation: tuple3(input.rest?.translation ?? [0, 0, 0]),+ rotation: tuple4(input.rest?.rotation ?? IDENTITY_QUATERNION),+ scale: tuple3(input.rest?.scale ?? UNIT_SCALE)+ },+ localForwardAxis: tuple3(input.localForwardAxis ?? FORWARD_AXIS),+ localBendAxis: tuple3(input.localBendAxis ?? BEND_AXIS),+ endEffector: input.endEffector ?? false,+ contact: input.contact ?? false+ };+ const validation = validateCharacterJointDescriptorV1(descriptor);+ if (!validation.valid || !validation.value) {+ throw new TypeError(`Invalid CharacterJointDescriptorV1: ${validation.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`);}- if (promotion.basis === "conformance" && (!promotion.fixturePath.startsWith("src/qa/") || !promotion.fixturePath.endsWith(".test.ts"))) {- throw new TypeError(`QA rule ${rule.id} conformance evidence must name a repository-relative src/qa/*.test.ts fixture`);+ return validation.value;+}+function validateCharacterRigGraphV1(value) {+ const issues = [];+ if (!isRecord4(value)) {+ return {+ valid: false,+ issues: [{ code: "EXPECTED_OBJECT", path: "", message: "Rig graph must be an object." }]+ };}- if (!SHA256_PATTERN.test(promotion.evidenceSha256)) {- throw new TypeError(`QA rule ${rule.id} promotion evidence must have a lowercase SHA-256`);+ if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {+ issues.push({+ code: "UNSUPPORTED_SCHEMA_VERSION",+ path: "schemaVersion",+ message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`+ });}- if (typeof promotion.rendererId !== "string" || !promotion.rendererId.trim()) {- throw new TypeError(`QA rule ${rule.id} promotion evidence must name its producing rendererId ` + `(e.g. "cpu-raster:0.6.0"; pre-existing evidence uses "${LEGACY_CPU_RASTER_RENDERER_ID}")`);+ if (!CHARACTER_BODY_PLANS2.includes(value.bodyPlan)) {+ issues.push({+ code: "INVALID_BODY_PLAN",+ path: "bodyPlan",+ message: "bodyPlan is unsupported."+ });}- if (!RENDERER_ID_PATTERN.test(promotion.rendererId)) {- throw new TypeError(`QA rule ${rule.id} promotion rendererId "${promotion.rendererId}" must start with a ` + `renderer family prefix followed by ':' (e.g. "cpu-raster:", "dawn-vulkan:")`);+ if (!Array.isArray(value.joints) || value.joints.length === 0) {+ issues.push({ code: "INVALID_JOINTS", path: "joints", message: "joints must not be empty." });}- if (!Number.isFinite(Date.parse(promotion.frozenAt))) {- throw new TypeError(`QA rule ${rule.id} promotion evidence must have a frozenAt timestamp`);- }- if (promotion.authorizedBy !== rule.owner.id) {- throw new TypeError(`QA rule ${rule.id} promotion must be authorized by its named rule owner`);- }- if (promotion.basis === "conformance") {- if (rule.ruleClass !== "exact") {- throw new TypeError(`Non-exact QA rule ${rule.id} cannot use conformance promotion evidence`);- }- } else {- if (rule.ruleClass === "exact") {- throw new TypeError(`Exact QA rule ${rule.id} cannot use QA-026 calibration evidence`);- }- assertCalibrationPromotion(rule, promotion);- }-}-function assertModeAuthorized(rule, mode) {- assertOwner(rule.owner, rule.id);- if (!QA_RULE_MODES.includes(mode)) {- throw new TypeError(`QA rule ${rule.id} received unsupported rollout mode ${String(mode)}`);- }- if (mode === "off" || mode === "observe") {- if (rule.promotion)- assertPromotionShape(rule, rule.promotion);- return;- }- if (rule.ruleClass === "appearance") {- throw new Error(`Appearance QA rule ${rule.id} cannot exceed observe; appearance findings derive from rendered output and are never gates`);- }- const promotion = rule.promotion;- if (!promotion) {- throw new Error(`QA rule ${rule.id} cannot enter ${mode} without frozen promotion evidence and owner authorization`);- }- assertPromotionShape(rule, promotion);- if (rule.ruleClass === "vlm" && mode === "enforce") {- throw new Error(`VLM QA rule ${rule.id} cannot be enforced; VLM findings are never blockers`);- }- if (mode === "enforce" && promotion.authorizedMode !== "enforce") {- throw new Error(`QA rule ${rule.id} promotion authorizes warn, not enforce; a new owner approval is required`);- }- if (rule.ruleClass === "exact" && promotion.basis !== "conformance") {- throw new Error(`Exact QA rule ${rule.id} requires conformance-fixture promotion evidence`);- }- if (rule.ruleClass !== "exact" && promotion.basis !== "qa-026-calibration") {- throw new Error(`QA rule ${rule.id} requires frozen QA-026 calibration evidence`);- }-}-function policyDecision(rule, mode) {- const promotion = rule.promotion;- return {- ruleId: rule.id,- profile: rule.profile,- mode,- ruleClass: rule.ruleClass,- owner: { ...rule.owner },- ...promotion ? {- promotionBasis: promotion.basis,- authorizedMode: promotion.authorizedMode,- evidenceId: evidenceId(promotion)- } : {}- };-}-function applies(rule, context) {- const { scope } = rule;- if (scope.kind === "universal")- return true;- if (scope.kind === "category")- return context.intent.category === scope.category;- if (scope.kind === "subtype") {- return context.intent.category === scope.category && context.intent.subtype === scope.subtype;- }- return context.intent.capabilities.includes(scope.capability);-}-function effectiveMode(rule, policy) {- return policy.byRule?.[rule.id] ?? policy.byProfile?.[rule.profile] ?? policy.defaultMode ?? rule.defaultMode;-}-function applyMode(finding, mode) {- if (mode === "observe")- return { ...finding, disposition: "observe" };- if (mode === "warn")- return { ...finding, disposition: "warn" };- return finding;-}--class QaRegistry {- #rules = [];- #ids = new Set;- constructor(rules = []) {- for (const rule of rules)- this.register(rule);+ const joints = [];+ if (Array.isArray(value.joints)) {+ value.joints.forEach((joint, index) => {+ const result = validateCharacterJointDescriptorV1(joint);+ if (result.value)+ joints.push(result.value);+ for (const issue of result.issues) {+ issues.push({ ...issue, path: `joints[${index}]${issue.path ? `.${issue.path}` : ""}` });+ }+ });}- register(rule) {- if (!/^[A-Z][A-Z0-9_]*$/.test(rule.id)) {- throw new TypeError(`QA rule id must be a stable uppercase code: ${rule.id}`);+ const byRole = new Map;+ const aliasOwners = new Map;+ joints.forEach((joint, index) => {+ const prior = byRole.get(joint.role);+ if (prior !== undefined) {+ issues.push({+ code: "DUPLICATE_JOINT_ROLE",+ path: `joints[${index}].role`,+ message: `role ${joint.role} duplicates joints[${prior}].role.`+ });+ } else+ byRole.set(joint.role, index);+ for (const alias of joint.aliases) {+ const owner = aliasOwners.get(alias);+ if (owner && owner !== joint.role) {+ issues.push({+ code: "AMBIGUOUS_JOINT_ALIAS",+ path: `joints[${index}].aliases`,+ message: `alias ${alias} is already owned by ${owner}.`+ });+ } else+ aliasOwners.set(alias, joint.role);}- if (this.#ids.has(rule.id))- throw new Error(`Duplicate QA rule id: ${rule.id}`);- if (!QA_RULE_CLASSES.includes(rule.ruleClass)) {- throw new TypeError(`QA rule ${rule.id} has an invalid rule class: ${rule.ruleClass}`);+ });+ joints.forEach((joint, index) => {+ if (joint.parentRole && !byRole.has(joint.parentRole)) {+ issues.push({+ code: "UNKNOWN_PARENT_ROLE",+ path: `joints[${index}].parentRole`,+ message: `parentRole ${joint.parentRole} is not declared.`+ });}- assertModeAuthorized(rule, rule.defaultMode);- this.#ids.add(rule.id);- this.#rules.push(rule);- return this;- }- list(context) {- return context ? this.#rules.filter((rule) => applies(rule, context)) : [...this.#rules];- }- describePolicy(policy = {}) {- return this.#rules.map((rule) => {- const mode = effectiveMode(rule, policy);- assertModeAuthorized(rule, mode);- return policyDecision(rule, mode);- });- }- run(context, policy = {}) {- const findings = [];- const executedRules = [];- const skippedRules = [];- const decisions = [];- for (const rule of this.#rules) {- if (!applies(rule, context))- continue;- const mode = effectiveMode(rule, policy);- assertModeAuthorized(rule, mode);- decisions.push(policyDecision(rule, mode));- if (mode === "off") {- skippedRules.push(rule.id);- continue;+ const seen = new Set([joint.role]);+ let cursor = joint.parentRole;+ while (cursor) {+ if (seen.has(cursor)) {+ issues.push({+ code: "JOINT_PARENT_CYCLE",+ path: `joints[${index}].parentRole`,+ message: `parent chain for ${joint.role} contains a cycle at ${cursor}.`+ });+ break;}- executedRules.push(rule.id);- for (const finding of rule.evaluate(context))- findings.push(applyMode(finding, mode));+ seen.add(cursor);+ const parentIndex = byRole.get(cursor);+ cursor = parentIndex === undefined ? undefined : joints[parentIndex]?.parentRole;}- return { findings, executedRules, skippedRules, decisions };- }-}-var QA_RULE_MODES, QA_RULE_CLASSES, LEGACY_CPU_RASTER_RENDERER_ID = "cpu-raster:legacy", QA_026_CALIBRATION_THRESHOLD_ID = "kiln.asset-quality-calibration.thresholds.v1", QA_026_CALIBRATION_THRESHOLD_SHA256 = "054ce5088b6b0685bbc0492f8bed0121311cf18920c5697bd6dce66dcb7b2cf9", QA_026_HELD_OUT_SET_VERSION = "kiln.asset-quality.held-out.v1", QA_026_HELD_OUT_SET_SHA256 = "27c17e0e9dbcf22915550b46a94e6afaafe80584f30429e4eb97435163a176bd", QA_026_REVIEW_AUTHORITY_SCHEME = "ed25519", QA_026_REVIEW_AUTHORITY_KEY_ID = "kiln-studio.asset-quality-review.prod.v1", QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256 = "08791ade50e377dfb3dc6bc1e852419515fbdaadabcd3880770507a2f192a528", QA_026_WARN_PROMOTION_MINIMUMS, QA_026_ENFORCE_PROMOTION_MINIMUMS, KILN_ENGINE_QA_OWNER, SHA256_PATTERN, OWNER_ID_PATTERN, RENDERER_ID_PATTERN, roundedRatio = (numerator, denominator) => Math.round(numerator / denominator * 1e6) / 1e6;-var init_registry = __esm(() => {- QA_RULE_MODES = ["off", "observe", "warn", "enforce"];- QA_RULE_CLASSES = ["exact", "heuristic", "vlm", "appearance"];- QA_026_WARN_PROMOTION_MINIMUMS = Object.freeze({- evaluatedCases: 20,- validExamples: 5,- defectiveExamples: 5,- precision: 0.9,- recall: 0.7,- vlmMeanConfidence: 0.75,- styles: 1- });- QA_026_ENFORCE_PROMOTION_MINIMUMS = Object.freeze({- evaluatedCases: 60,- validExamples: 30,- defectiveExamples: 30,- precision: 0.9,- recall: 0.9,- styles: 3,- falseBlocks: 0- });- KILN_ENGINE_QA_OWNER = Object.freeze({- id: "kiln-engine-maintainers",- authority: "named"});- SHA256_PATTERN = /^[a-f0-9]{64}$/;- OWNER_ID_PATTERN = /^[a-z0-9][a-z0-9:._/-]*$/;- RENDERER_ID_PATTERN = /^[a-z0-9-]+:/;-});--// src/qa/material.ts-import * as THREE from "three";-function textureMeta(texture) {- return texture.userData["kilnTexture"];-}-function affected(mesh, material, texture, attribute) {+ if (issues.length > 0)+ return { valid: false, issues };return {- node: mesh.name || "(unnamed mesh)",- material: material.name || "(unnamed material)",- ...texture ? { texture: texture.name || "(unnamed texture)" } : {},- ...attribute ? { attribute } : {}+ valid: true,+ value: {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ bodyPlan: value.bodyPlan,+ joints: joints.map(cloneCharacterJointDescriptorV1)+ },+ issues};}-function textureHasAlpha(texture) {- const meta = textureMeta(texture);- if (meta)- return meta.hasAlpha;- const image = texture.image;- const data = image?.data;- if (!data || data.length < 4)- return false;- for (let i = 3;i < data.length; i += 4) {- if ((data[i] ?? 255) < 255)- return true;+function createCharacterRigGraphV1(input) {+ const graph = {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ bodyPlan: input.bodyPlan,+ joints: input.joints.map((joint) => ("schemaVersion" in joint) ? cloneCharacterJointDescriptorV1(joint) : createCharacterJointDescriptorV1(joint))+ };+ const result = validateCharacterRigGraphV1(graph);+ if (!result.valid || !result.value) {+ throw new TypeError(`Invalid CharacterRigGraphV1: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`);}- return false;+ return result.value;}-function encodedTextureIsExportable(texture) {- const encoded = texture.userData["encoded"];- if (!encoded || typeof encoded.mime !== "string")- return false;- const bytes = encoded.bytes;- if (!bytes || typeof bytes.length !== "number" || bytes.length < 4)- return false;- if (encoded.mime === "image/png") {- return bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71;- }- if (encoded.mime === "image/jpeg") {- return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;- }- if (encoded.mime === "image/webp") {- return bytes.length >= 12 && bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80;- }- return false;-}-function validateTextureSlot(findings, mesh, material, texture, slot, expected) {- if (!texture)- return;- const meta = textureMeta(texture);- const actual = texture.colorSpace === THREE.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";- if (!meta || !encodedTextureIsExportable(texture)) {- findings.push({- code: "MAT_TEXTURE_DECODE_FAILED",- disposition: "block",- dimension: "exportIntegrity",- profile: "material.portablePbr",- message: `${slot} texture has no verified decoded/exportable image payload.`,- affected: affected(mesh, material, texture, slot),- repairText: "Use loadApprovedTexture(resourceId) or proceduralTexture() before assigning it. A texture built in code is baked to PNG automatically, so reaching this means its pixels were unreadable — it must be a DataTexture holding 8-bit RGB or RGBA bytes, not float data or an image element."- });- }- if (actual !== expected) {- findings.push({- code: "MAT_TEXTURE_COLOR_SPACE",- disposition: "block",- dimension: "exportIntegrity",- profile: "material.portablePbr",- message: `${slot} texture must use ${expected} data interpretation, not ${actual}.`,- affected: affected(mesh, material, texture, slot),- measurement: { name: "colorSpace", actual, expected },- repairText: `Choose an approved resource whose declared usage matches '${slot === "map" ? "albedo" : slot}', or for a texture built in code set texture.colorSpace = ${expected === "srgb" ? "THREE.SRGBColorSpace" : "THREE.NoColorSpace"} — it is never set for you, because reinterpreting an author's pixels silently is exactly the failure this check exists to catch.`- });- }- const image = texture.image;- if (!image || !Number.isFinite(image.width) || !Number.isFinite(image.height) || (image.width ?? 0) <= 0 || (image.height ?? 0) <= 0) {- findings.push({- code: "MAT_TEXTURE_INVALID_DIMENSIONS",- disposition: "block",- dimension: "exportIntegrity",- profile: "material.portablePbr",- message: `${slot} texture has invalid or undecodable dimensions.`,- affected: affected(mesh, material, texture, slot),- repairText: "Use a decodable PNG, JPEG, or WebP with positive dimensions."- });- }- if (!mesh.geometry.getAttribute("uv")) {- findings.push({- code: "MAT_TEXTURE_UV_MISSING",- disposition: "block",- dimension: "exportIntegrity",- profile: "material.portablePbr",- message: `${slot} texture is used on geometry without TEXCOORD_0 UVs.`,- affected: affected(mesh, material, texture, slot),- repairText: "Unwrap the geometry before assigning a texture-backed material."- });- }+function readCharacterRigGraphV1(target) {+ const value = target.userData?.[KILN_CHARACTER_RIG_EXTRAS_KEY];+ const result = validateCharacterRigGraphV1(value);+ return result.valid ? result.value : undefined;}-function validateMaterial2(mesh, material, requiresPrecomputedTangents) {- const findings = [];- const standard = material;- if (!standard.isMeshStandardMaterial)- return findings;- for (const [name, value] of [- ["roughness", standard.roughness],- ["metalness", standard.metalness],- ["opacity", standard.opacity],- ["emissiveIntensity", standard.emissiveIntensity]- ]) {- if (!Number.isFinite(value)) {- findings.push({- code: "MAT_NONFINITE_FACTOR",- disposition: "block",- dimension: "exportIntegrity",- profile: "material.portablePbr",- message: `Material factor ${name} is non-finite.`,- affected: affected(mesh, material),- measurement: { name, actual: String(value) }- });- }- }- validateTextureSlot(findings, mesh, standard, standard.map, "map", "srgb");- validateTextureSlot(findings, mesh, standard, standard.emissiveMap, "emissive", "srgb");- validateTextureSlot(findings, mesh, standard, standard.normalMap, "normal", "linear");- validateTextureSlot(findings, mesh, standard, standard.roughnessMap, "metallicRoughness", "linear");- validateTextureSlot(findings, mesh, standard, standard.metalnessMap, "metallicRoughness", "linear");- validateTextureSlot(findings, mesh, standard, standard.aoMap, "occlusion", "linear");- if (standard.normalMap && !mesh.geometry.getAttribute("tangent")) {- findings.push({- code: "MAT_NORMAL_TANGENTS_MISSING",- disposition: requiresPrecomputedTangents ? "block" : "warn",- dimension: "categoryReadiness",- profile: "material.portablePbr",- message: requiresPrecomputedTangents ? "The trusted consumer profile requires precomputed tangents for normal-mapped geometry." : "Normal-mapped geometry has no precomputed tangents; the consumer must derive them.",- affected: affected(mesh, material, standard.normalMap, "normal"),- repairText: "Generate and export TANGENT data for the normal-mapped geometry."- });- }- if (standard.roughnessMap && standard.metalnessMap && standard.roughnessMap !== standard.metalnessMap) {- findings.push({- code: "MAT_SEPARATE_METALLIC_ROUGHNESS",- disposition: "block",- dimension: "exportIntegrity",- profile: "material.portablePbr",- message: "glTF requires one packed metallic-roughness texture (G=roughness, B=metalness).",- affected: affected(mesh, material),- repairText: "Pack both channels and pass the result as metallicRoughness."- });- }- if (mesh.geometry.userData["kilnGeometryRole"] === "foliageCard") {- const validMask = standard.alphaTest > 0 && !standard.transparent;- if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE.DoubleSide || !mesh.geometry.getAttribute("uv")) {- findings.push({- code: "MAT_FOLIAGE_CARD_CONTRACT",- disposition: "block",- dimension: "categoryReadiness",- profile: "material.foliageCard",- message: "Foliage cards require UVs, an alpha-bearing base-color texture, MASK cutoff, and double-sided output.",- affected: affected(mesh, material, standard.map ?? undefined),- repairText: "Use foliageMaterial() with an alpha-bearing albedo texture."- });- }- }- return findings;+function axisQuaternion(from, to) {+ const value = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(...from), new THREE.Vector3(...to));+ return [value.x, value.y, value.z, value.w];}-function inspectSceneMaterials(context) {- const root = context.scene;- if (!root?.traverse)- return [];- const findings = [];- const requiresPrecomputedTangents = context.intent.capabilities.includes("precomputedTangents");- root.traverse((node) => {- const mesh = node;- if (!mesh.isMesh || !mesh.geometry)- return;- const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];- for (const material of materials) {- if (material) {- findings.push(...validateMaterial2(mesh, material, requiresPrecomputedTangents));+function stampCharacterJointDescriptorV1(target, input) {+ const descriptor = createCharacterJointDescriptorV1(input);+ const frames = [+ { id: "rest", translation: [0, 0, 0], rotation: IDENTITY_QUATERNION },+ {+ id: "forward",+ translation: [0, 0, 0],+ rotation: axisQuaternion(FORWARD_AXIS, descriptor.localForwardAxis)+ },+ {+ id: "bend",+ translation: [0, 0, 0],+ rotation: axisQuaternion([0, 1, 0], descriptor.localBendAxis)+ },+ ...descriptor.endEffector ? [+ {+ id: "end-effector",+ translation: [0, 0, 0],+ rotation: IDENTITY_QUATERNION}- }+ ] : [],+ ...descriptor.contact ? [+ {+ id: "contact",+ translation: [0, 0, 0],+ rotation: IDENTITY_QUATERNION+ }+ ] : []+ ];+ stampSemanticMetadataV1(target, {+ roles: [+ "skeleton.joint",+ `joint.${descriptor.role}`,+ `joint.side.${descriptor.side}`,+ ...descriptor.aliases.map((alias) => `joint.alias.${alias}`),+ ...descriptor.endEffector ? ["joint.end-effector"] : [],+ ...descriptor.contact ? ["contact.ground"] : []+ ],+ relationships: descriptor.parentRole ? [{ kind: "parent-joint", target: `joint.${descriptor.parentRole}`, targetType: "role" }] : [],+ frames,+ sockets: [+ ...descriptor.endEffector ? [+ {+ id: "end-effector",+ type: "character.attachment",+ frame: "end-effector",+ compatibleTypes: ["character.held-item"]+ }+ ] : [],+ ...descriptor.contact ? [+ {+ id: "ground-contact",+ type: "character.contact",+ frame: "contact",+ compatibleTypes: ["world.ground"]+ }+ ] : []+ ]});- return findings;+ target.userData[KILN_CHARACTER_JOINT_EXTRAS_KEY] = cloneCharacterJointDescriptorV1(descriptor);+ return target;}-var MATERIAL_QA_RULE;-var init_material = __esm(() => {- init_registry();- MATERIAL_QA_RULE = {- id: "MATERIAL_PORTABLE_PBR_RULE",- profile: "material.portablePbr",- scope: { kind: "universal" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("material-portable-pbr-v1", "src/qa/material.test.ts", "27f7469603ba986acfac2c6acbfb293ad787717aecdf4a3d03cae625f86f45e7"),- defaultMode: "enforce",- evaluate: inspectSceneMaterials- };-});--// src/qa/architecture-repairs.ts-function architectureRepairRecipe(code) {- return ARCHITECTURE_REPAIR_RECIPES[code];+function readCharacterJointDescriptorV1(target) {+ const value = target.userData?.[KILN_CHARACTER_JOINT_EXTRAS_KEY];+ const result = validateCharacterJointDescriptorV1(value);+ return result.valid ? result.value : undefined;}-function withArchitectureRepair(finding) {- const recipe = architectureRepairRecipe(finding.code);- if (!recipe)- return finding;- return {- ...finding,- repairText: finding.repairText ?? recipe.repairText,- viewHints: [...new Set([...finding.viewHints ?? [], ...recipe.viewHints])]- };+function characterJointNodeName(chainName, role) {+ const safeChain = chainName.trim().replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "");+ const safeRole = role.replace(/[^A-Za-z0-9]+/g, "_");+ if (!safeChain)+ throw new TypeError("createJointChain chainName must contain a letter or number.");+ return `Joint_${safeChain}_${safeRole}`;}-var ARCHITECTURE_REPAIR_RECIPES;-var init_architecture_repairs = __esm(() => {- ARCHITECTURE_REPAIR_RECIPES = Object.freeze({- ARCH_ROOF_AXIS: Object.freeze({- code: "ARCH_ROOF_AXIS",- repairText: "Edit only the reported roof slope or panel: keep the declared ridge axis fixed, mirror the two slope frames, and rotate panel span 90 degrees in roof-local space so it runs ridge-to-eave. Recheck both gable elevations and the top wireframe.",- viewHints: Object.freeze([- "architecture.gable.positive",- "architecture.gable.negative",- "generic.top.wireframe"- ])- }),- ARCH_OPEN_GABLE: Object.freeze({- code: "ARCH_OPEN_GABLE",- repairText: "Add or complete only the reported roof.gable end panel. Its projected triangle must cover the full wall-top-to-ridge cross-section and meet both slopes; preserve intentional openings and the opposite end.",- viewHints: Object.freeze([- "architecture.gable.positive",- "architecture.gable.negative",- "generic.front.semantic-overlay"- ])- }),- ARCH_RIDGE_GAP: Object.freeze({- code: "ARCH_RIDGE_GAP",- repairText: "Move only the reported slope high edge in its roof-local downhill direction until both high edges share the declared ridge line within tolerance. Do not change footprint, pitch, eaves, or overhang.",- viewHints: Object.freeze([- "architecture.gable.positive",- "architecture.gable.negative",- "generic.top.depth-contact"- ])- }),- ARCH_ENVELOPE_GAP: Object.freeze({- code: "ARCH_ENVELOPE_GAP",- repairText: "At the reported wall-boundary samples, align the roof underside to the wall top plate within tolerance. Preserve the declared exterior overhang and do not close sides marked as an open pavilion.",- viewHints: Object.freeze([- "architecture.cutaway.dollhouse",- "generic.front.depth-contact",- "generic.right.depth-contact"- ])- }),- ARCH_BLOCKED_PORTAL: Object.freeze({- code: "ARCH_BLOCKED_PORTAL",- repairText: "Remove or split only the reported blocker inside the opening clearance prism so the tagged exterior portal connects to the interior at the requested width, height, and depth. A painted door on a solid wall is not an opening.",- viewHints: Object.freeze([- "architecture.portal.eye",- "architecture.cutaway.plan",- "generic.front.depth-contact"- ])- })- });-});--// src/qa/architecture.ts-import * as THREE2 from "three";-function semanticMetadata(node) {- return readSemanticMetadataV1FromExtras(node.userData);-}-function markerBounds(matrix) {- const bounds = emptyBounds();- for (let corner = 0;corner < 8; corner++) {- expandBounds(bounds, new THREE2.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));- }- return bounds;-}-function geometryPlaneNormal(geometry, relativeMatrix) {- geometry.computeBoundingBox();- const local = geometry.boundingBox;- if (!local)- return;- const size = local.getSize(new THREE2.Vector3);- const dimensions = [- ["x", size.x],- ["y", size.y],- ["z", size.z]- ];- dimensions.sort((a, b) => a[1] - b[1]);- const axis = dimensions[0]?.[0];- if (!axis)- return;- const normal = new THREE2.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);- if (normal.y < 0)- normal.multiplyScalar(-1);- return normal.normalize();-}-function geometryEvidence(geometry, relativeMatrix) {- const position = geometry.getAttribute("position");- const bounds = emptyBounds();- const vertices = [];- if (position?.itemSize !== 3)- return { bounds, vertices, triangles: [] };- for (let index = 0;index < position.count; index++) {- const point = new THREE2.Vector3(position.getX(index), position.getY(index), position.getZ(index));- point.applyMatrix4(relativeMatrix);- vertices.push(point);- expandBounds(bounds, point);+function createJointChain(chainName, segments, options = {}) {+ if (segments.length === 0)+ throw new TypeError("createJointChain requires at least one segment.");+ const seen = new Set;+ const nodes = [];+ const descriptors = [];+ const byRole = new Map;+ let parent = options.parent;+ let parentRole = options.parentRole;+ for (const segment of segments) {+ if (seen.has(segment.role))+ throw new TypeError(`Duplicate joint-chain role: ${segment.role}.`);+ seen.add(segment.role);+ const descriptor = createCharacterJointDescriptorV1({+ role: segment.role,+ aliases: segment.aliases,+ ...parentRole ? { parentRole } : {},+ side: segment.side,+ rest: {+ translation: segment.offset,+ rotation: segment.restRotation,+ scale: segment.restScale+ },+ localForwardAxis: segment.localForwardAxis,+ localBendAxis: segment.localBendAxis,+ endEffector: segment.endEffector,+ contact: segment.contact+ });+ const node = new THREE.Object3D;+ node.name = characterJointNodeName(chainName, segment.role);+ node.position.fromArray(descriptor.rest.translation);+ node.quaternion.fromArray(descriptor.rest.rotation);+ node.scale.fromArray(descriptor.rest.scale);+ stampCharacterJointDescriptorV1(node, descriptor);+ if (parent)+ parent.add(node);+ parent = node;+ parentRole = descriptor.role;+ nodes.push(node);+ descriptors.push(descriptor);+ byRole.set(descriptor.role, node);}- const triangles = [];- const indices = geometry.getIndex();- const addTriangle = (a, b, c) => {- const va = vertices[a];- const vb = vertices[b];- const vc = vertices[c];- if (va && vb && vc)- triangles.push({ a: va, b: vb, c: vc });+ return {+ root: nodes[0],+ end: nodes[nodes.length - 1],+ nodes,+ byRole,+ descriptors};- if (indices) {- for (let index = 0;index + 2 < indices.count; index += 3) {- addTriangle(indices.getX(index), indices.getX(index + 1), indices.getX(index + 2));- }- } else {- for (let index = 0;index + 2 < vertices.length; index += 3) {- addTriangle(index, index + 1, index + 2);- }- }- const planeNormal = geometryPlaneNormal(geometry, relativeMatrix);- return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };}-function collectArchitectureEvidence(scene) {- if (!(scene instanceof THREE2.Object3D))- return;- scene.updateMatrixWorld(true);- const rootInverse = scene.matrixWorld.clone().invert();- const parts = [];- const allRoles = new Set;- const visit = (node, parentPath, siblingIndex, inheritedRoles) => {- const metadata = semanticMetadata(node);- const directRoles = metadata?.roles ?? [];- const directRelationships = metadata?.relationships ?? [];- directRoles.forEach((role) => {- allRoles.add(role);- });- const roles = [...new Set([...inheritedRoles, ...directRoles])];+function collectCharacterJointNodes(root) {+ const joints = [];+ const visit = (node, parentPath, siblingIndex) => {const segment = `${node.name.trim() || node.type || "Object3D"}[${siblingIndex}]`;const nodePath = parentPath ? `${parentPath}/${segment}` : segment;- const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);- const mesh = node;- const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE2.BufferGeometry;- const evidence = isMesh ? geometryEvidence(mesh.geometry, relativeMatrix) : {- bounds: markerBounds(relativeMatrix),- vertices: [],- triangles: []- };- if (isMesh || directRoles.length > 0) {- parts.push({- node,- nodeName: node.name || node.type,- nodePath,- directRoles,- directRelationships,- roles,- isMesh,- ...evidence- });- }+ const descriptor = readCharacterJointDescriptorV1(node);+ if (descriptor)+ joints.push({ node, nodePath, descriptor });node.children.forEach((child, index) => {- visit(child, nodePath, index, roles);+ visit(child, nodePath, index);});};- visit(scene, "", 0, []);- return { root: scene, parts, semanticRoles: allRoles };-}-function aggregate(parts) {- if (parts.length === 0)- return;- const bounds = emptyBounds();- const vertices = [];- const triangles = [];- const normals = [];- for (const part of parts) {- if (boundsFinite(part.bounds)) {- expandBounds(bounds, part.bounds.min);- expandBounds(bounds, part.bounds.max);- }- vertices.push(...part.vertices);- triangles.push(...part.triangles);- if (part.planeNormal)- normals.push(part.planeNormal);- }- if (!boundsFinite(bounds))- return;- return { parts: [...parts], bounds, vertices, triangles, normals };-}-function aggregateRole(evidence, role) {- return aggregate(evidence.parts.filter((part) => hasRole(part, role)));-}-function architectureFinding(context, value) {- return withArchitectureRepair({- ...value,- profile: context.intent.qaProfile,- dimension: "categoryReadiness"- });-}-function averageNormal(normals) {- if (normals.length === 0)- return;- const result = normals.reduce((sum, normal) => sum.add(normal), new THREE2.Vector3);- return result.lengthSq() > EPSILON ? result.normalize() : undefined;-}-function intervalCoverage(min, max, expectedMin, expectedMax) {- const expected = expectedMax - expectedMin;- if (expected <= EPSILON)- return 1;- return Math.max(0, Math.min(max, expectedMax) - Math.max(min, expectedMin)) / expected;-}-function intervalSeparation(aMin, aMax, bMin, bMax) {- if (aMax < bMin)- return bMin - aMax;- if (bMax < aMin)- return aMin - bMax;- return 0;-}-function requestedGable(architecture) {- return architecture.roof.type === "gable";-}-function taggedGable(evidence) {- return [...evidence.semanticRoles].some((role) => role === "architecture.shell.gable" || role.startsWith("roof.slope.") || role.startsWith("roof.gable."));-}-function isOpenPavilion(architecture, evidence) {- return /(?:^|[. _-])(?:open[. _-])?pavilion(?:$|[. _-])/i.test(architecture.subtype) || evidence.semanticRoles.has("architecture.open-pavilion");-}-function highEdgeVertices(aggregateValue, rise) {- const band = Math.max(0.006, rise * 0.02);- const maximumY = aggregateValue.bounds.max.y;- return aggregateValue.vertices.filter((point) => point.y >= maximumY - band);+ visit(root, "", 0);+ return joints;}-function ridgeCrossSectionDistance(positive, negative, lateralAxis, rise) {- const a = highEdgeVertices(positive, rise);- const b = highEdgeVertices(negative, rise);- let distance = Infinity;- for (const pointA of a) {- for (const pointB of b) {- distance = Math.min(distance, Math.hypot(pointA[lateralAxis] - pointB[lateralAxis], pointA.y - pointB.y));+var KILN_CHARACTER_JOINT_EXTRAS_KEY = "kilnCharacterJoint", KILN_CHARACTER_RIG_EXTRAS_KEY = "kilnCharacterRig", KILN_CHARACTER_JOINT_SCHEMA_VERSION = 1, CHARACTER_BODY_PLANS2, CHARACTER_JOINT_SIDES, IDENTITY_QUATERNION, UNIT_SCALE, FORWARD_AXIS, BEND_AXIS, isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isFiniteTuple2 = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), tuple3 = (value) => [value[0], value[1], value[2]], tuple4 = (value) => [+ value[0],+ value[1],+ value[2],+ value[3]+], presetJoint = (role, parentRole, translation, options = {}) => createCharacterJointDescriptorV1({+ role,+ ...parentRole ? { parentRole } : {},+ ...options,+ rest: { translation }+}), BIPED_RIG_PRESET_V1, QUADRUPED_RIG_PRESET_V1;+var init_character = __esm(() => {+ init_contracts();+ CHARACTER_BODY_PLANS2 = [+ "biped",+ "quadruped",+ "avian",+ "serpentine",+ "multi-limb",+ "wheeled",+ "custom"+ ];+ CHARACTER_JOINT_SIDES = ["left", "right", "center"];+ IDENTITY_QUATERNION = [0, 0, 0, 1];+ UNIT_SCALE = [1, 1, 1];+ FORWARD_AXIS = [1, 0, 0];+ BEND_AXIS = [0, 0, 1];+ BIPED_RIG_PRESET_V1 = createCharacterRigGraphV1({+ bodyPlan: "biped",+ joints: [+ presetJoint("hips", undefined, [0, 1, 0], { aliases: ["pelvis"] }),+ presetJoint("spine", "hips", [0, 0.45, 0], { aliases: ["torso"] }),+ presetJoint("head", "spine", [0, 0.55, 0]),+ presetJoint("shoulder.left", "spine", [0, 0.3, -0.25], { side: "left" }),+ presetJoint("elbow.left", "shoulder.left", [0, -0.35, 0], { side: "left" }),+ presetJoint("wrist.left", "elbow.left", [0, -0.35, 0], {+ side: "left",+ aliases: ["hand.left", "grip.left"],+ endEffector: true+ }),+ presetJoint("shoulder.right", "spine", [0, 0.3, 0.25], { side: "right" }),+ presetJoint("elbow.right", "shoulder.right", [0, -0.35, 0], { side: "right" }),+ presetJoint("wrist.right", "elbow.right", [0, -0.35, 0], {+ side: "right",+ aliases: ["hand.right", "grip.right"],+ endEffector: true+ }),+ presetJoint("hip.left", "hips", [0, -0.1, -0.14], { side: "left" }),+ presetJoint("knee.left", "hip.left", [0, -0.45, 0], { side: "left" }),+ presetJoint("ankle.left", "knee.left", [0, -0.45, 0], {+ side: "left",+ aliases: ["foot.left"],+ endEffector: true,+ contact: true+ }),+ presetJoint("hip.right", "hips", [0, -0.1, 0.14], { side: "right" }),+ presetJoint("knee.right", "hip.right", [0, -0.45, 0], { side: "right" }),+ presetJoint("ankle.right", "knee.right", [0, -0.45, 0], {+ side: "right",+ aliases: ["foot.right"],+ endEffector: true,+ contact: true+ })+ ]+ });+ QUADRUPED_RIG_PRESET_V1 = createCharacterRigGraphV1({+ bodyPlan: "quadruped",+ joints: [+ presetJoint("hips", undefined, [0, 0.8, 0], { aliases: ["pelvis"] }),+ presetJoint("spine", "hips", [0.7, 0, 0]),+ presetJoint("neck", "spine", [0.45, 0.1, 0]),+ presetJoint("head", "neck", [0.3, 0, 0]),+ presetJoint("shoulder.fore.left", "spine", [0.2, -0.1, -0.28], { side: "left" }),+ presetJoint("elbow.fore.left", "shoulder.fore.left", [0, -0.4, 0], { side: "left" }),+ presetJoint("paw.fore.left", "elbow.fore.left", [0, -0.3, 0], {+ side: "left",+ endEffector: true,+ contact: true+ }),+ presetJoint("shoulder.fore.right", "spine", [0.2, -0.1, 0.28], { side: "right" }),+ presetJoint("elbow.fore.right", "shoulder.fore.right", [0, -0.4, 0], { side: "right" }),+ presetJoint("paw.fore.right", "elbow.fore.right", [0, -0.3, 0], {+ side: "right",+ endEffector: true,+ contact: true+ }),+ presetJoint("hip.hind.left", "hips", [0, -0.1, -0.28], { side: "left" }),+ presetJoint("knee.hind.left", "hip.hind.left", [0, -0.4, 0], { side: "left" }),+ presetJoint("paw.hind.left", "knee.hind.left", [0, -0.3, 0], {+ side: "left",+ endEffector: true,+ contact: true+ }),+ presetJoint("hip.hind.right", "hips", [0, -0.1, 0.28], { side: "right" }),+ presetJoint("knee.hind.right", "hip.hind.right", [0, -0.4, 0], { side: "right" }),+ presetJoint("paw.hind.right", "knee.hind.right", [0, -0.3, 0], {+ side: "right",+ endEffector: true,+ contact: true+ })+ ]+ });+});++// src/architecture.ts+import * as THREE2 from "three";+function positive(value, name) {+ if (!Number.isFinite(value) || value <= 0)+ throw new RangeError(`${name} must be finite and > 0`);+ return value;+}+function nonNegative(value, name) {+ if (!Number.isFinite(value) || value < 0)+ throw new RangeError(`${name} must be finite and >= 0`);+ return value;+}+function roleMetadata(roles, relationships = [], frames = []) {+ return { roles, relationships, frames, sockets: [] };+}+function relationship(kind, target) {+ return { kind, target, targetType: "role" };+}+function setTransform(object, matrix) {+ matrix.decompose(object.position, object.quaternion, object.scale);+}+function resolvePitch(halfRun, rise, pitchDegrees) {+ positive(halfRun, "roof half-run");+ if (rise === undefined && pitchDegrees === undefined)+ pitchDegrees = 30;+ if (pitchDegrees !== undefined) {+ if (!Number.isFinite(pitchDegrees) || pitchDegrees <= 0 || pitchDegrees >= 89) {+ throw new RangeError("pitchDegrees must be finite, > 0, and < 89");}}- return distance;+ if (rise !== undefined)+ positive(rise, "rise");+ const resolvedPitch = pitchDegrees ?? Math.atan2(rise, halfRun) / DEG;+ const resolvedRise = rise ?? Math.tan(resolvedPitch * DEG) * halfRun;+ const expected = Math.tan(resolvedPitch * DEG) * halfRun;+ if (Math.abs(resolvedRise - expected) > Math.max(EPSILON, expected * 0.000001)) {+ throw new RangeError("rise and pitchDegrees disagree for the requested footprint");+ }+ return { rise: resolvedRise, pitchDegrees: resolvedPitch };}-function roofFindings(context, architecture, evidence) {- if (!requestedGable(architecture) && !taggedGable(evidence))- return [];- const positive = aggregateRole(evidence, "roof.slope.positive");- const negative = aggregateRole(evidence, "roof.slope.negative");- const tagged = taggedGable(evidence);- const exactDisposition = tagged ? "block" : "warn";- const findings = [];- if (!positive || !negative) {- findings.push(architectureFinding(context, {- code: "ARCH_ROOF_AXIS",- disposition: exactDisposition,- message: `A gable requires exactly two semantic slope roles; found ${positive ? 1 : 0} positive and ${negative ? 1 : 0} negative slope surfaces.`,- measurement: {- name: "semanticSlopeRoleCount",- actual: Number(Boolean(positive)) + Number(Boolean(negative)),- expected: 2,- threshold: 2+function resolveRoofProfile(options) {+ const spanX = positive(options.spanX, "spanX");+ const spanZ = positive(options.spanZ, "spanZ");+ const ridgeAxis = options.ridgeAxis ?? "x";+ const overhang = nonNegative(options.overhang ?? 0.3, "overhang");+ const thickness = positive(options.thickness ?? 0.08, "thickness");+ const halfRun = (ridgeAxis === "x" ? spanZ : spanX) / 2;+ const pitch = resolvePitch(halfRun, options.rise, options.pitchDegrees);+ return {+ spanX,+ spanZ,+ ridgeAxis,+ overhang,+ thickness,+ ...pitch,+ ridgeY: pitch.rise,+ eaveY: -Math.tan(pitch.pitchDegrees * DEG) * overhang+ };+}+function buildFace(roofRoot, profile, sideSign) {+ const side = sideSign > 0 ? "positive" : "negative";+ const halfFoot = (profile.ridgeAxis === "x" ? profile.spanZ : profile.spanX) / 2;+ const horizontalRun = halfFoot + profile.overhang;+ const verticalRun = profile.ridgeY - profile.eaveY;+ const downhillLength = Math.hypot(horizontalRun, verticalRun);+ const alongRidge = (profile.ridgeAxis === "x" ? profile.spanX : profile.spanZ) + profile.overhang * 2;+ const downhill = profile.ridgeAxis === "x" ? new THREE2.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE2.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();+ const tangent = profile.ridgeAxis === "x" ? new THREE2.Vector3(sideSign, 0, 0) : new THREE2.Vector3(0, 0, -sideSign);+ const normal = downhill.clone().cross(tangent).normalize();+ const localToRoof = new THREE2.Matrix4().makeBasis(tangent, normal, downhill);+ localToRoof.setPosition(0, profile.ridgeY, 0);+ const world = () => {+ roofRoot.updateWorldMatrix(true, false);+ return roofRoot.matrixWorld.clone().multiply(localToRoof);+ };+ const direction = (axis) => axis.clone().transformDirection(world());+ const point = (x, z) => new THREE2.Vector3(x, 0, z).applyMatrix4(world());+ return {+ side,+ ridgeAxis: profile.ridgeAxis,+ roofRoot,+ localToRoof,+ get localToWorld() {+ return world();+ },+ get ridgeTangent() {+ return direction(new THREE2.Vector3(1, 0, 0));+ },+ get downhillDirection() {+ return direction(new THREE2.Vector3(0, 0, 1));+ },+ get outwardNormal() {+ return direction(new THREE2.Vector3(0, 1, 0));+ },+ get ridgeStart() {+ return point(-alongRidge / 2, 0);+ },+ get ridgeEnd() {+ return point(alongRidge / 2, 0);+ },+ get eaveStart() {+ return point(-alongRidge / 2, downhillLength);+ },+ get eaveEnd() {+ return point(alongRidge / 2, downhillLength);+ },+ dimensions: { alongRidge, downhill: downhillLength, thickness: profile.thickness }+ };+}+function buildRoof(name, material, profile, parent) {+ const root = new THREE2.Object3D;+ root.name = name;+ if (parent)+ parent.add(root);+ stampSemanticMetadataV1(root, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "assembly")], [relationship("separable-from", "architecture.shell.gable")]));+ const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)];+ const buildSlope = (face) => {+ const geometry = new THREE2.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);+ const mesh = new THREE2.Mesh(geometry, material);+ mesh.name = `Mesh_${name}_${face.side}`;+ const center = new THREE2.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);+ setTransform(mesh, face.localToRoof.clone().multiply(center));+ const coveredWall = profile.ridgeAxis === "x" ? face.side === "positive" ? "wall.right" : "wall.left" : face.side === "positive" ? "wall.front" : "wall.back";+ stampSemanticMetadataV1(mesh, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side)], [+ relationship("adjacent-to", semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side === "positive" ? "negative" : "positive")),+ relationship("coverage-of", coveredWall),+ relationship("separable-from", "architecture.shell.gable")+ ], [+ { id: "surface", translation: [0, profile.thickness / 2, 0], rotation: [0, 0, 0, 1] },+ {+ id: "ridge",+ translation: [0, profile.thickness / 2, -face.dimensions.downhill / 2],+ rotation: [0, 0, 0, 1]},- affected: { node: evidence.root.name || "architecture-root" }- }));- }- const semanticRoofRoles = [...evidence.semanticRoles].filter((role) => role.startsWith("roof."));- if (semanticRoofRoles.length === 0) {- const inferredRoof = evidence.parts.find((part) => part.isMesh && /(?:^|[_ .-])roof(?:$|[_ .-])/i.test(part.nodeName));- findings.push(architectureFinding(context, {- code: "ARCH_MISSING_ROOF_ROLES",- disposition: "warn",- message: "The architecture has no portable roof.* semantic roles, so ridge, coverage, diagnostic cutaway, and separability checks cannot be exact.",- affected: inferredRoof ? { node: inferredRoof.nodeName, nodePath: inferredRoof.nodePath } : { node: evidence.root.name || "architecture-root" },- viewHints: ["generic.top.semantic-overlay", "architecture.cutaway.dollhouse"],- repairText: "Build the roof with the gable shell helper or stamp roof.slope.positive/negative and roof.gable.positive/negative roles plus separable-from relationships."- }));- return findings;- }- if (!positive || !negative)- return findings;- const ridgeAxis = architecture.roof.ridgeAxis;- const lateralAxis = ridgeAxis === "x" ? "z" : "x";- const positiveNormal = averageNormal(positive.normals);- const negativeNormal = averageNormal(negative.normals);- const lateralProduct = positiveNormal && negativeNormal ? positiveNormal[lateralAxis] * negativeNormal[lateralAxis] : null;- if (lateralProduct === null || lateralProduct >= -0.0025) {- findings.push(architectureFinding(context, {- code: "ARCH_ROOF_AXIS",- disposition: exactDisposition,- message: "The two semantic gable slopes do not face opposite downhill directions in the declared roof-local frame.",- affected: { node: negative.parts[0]?.nodeName ?? "roof.slope.negative" },- measurement: {- name: "slopeLateralNormalProduct",- actual: lateralProduct,- expected: "< -0.0025",- threshold: -0.0025+ {+ id: "eave",+ translation: [0, profile.thickness / 2, face.dimensions.downhill / 2],+ rotation: [0, 0, 0, 1]}- }));- }- const { spanX, spanZ } = architecture.footprint;- const expectedRidgeSpan = (ridgeAxis === "x" ? spanX : spanZ) + architecture.roof.overhang * 2;- const expectedLateralSpan = (lateralAxis === "x" ? spanX : spanZ) + architecture.roof.overhang * 2;- const ridgeCoverage = Math.min(extent(positive.bounds, ridgeAxis) / expectedRidgeSpan, extent(negative.bounds, ridgeAxis) / expectedRidgeSpan);- const roofMinLateral = Math.min(positive.bounds.min[lateralAxis], negative.bounds.min[lateralAxis]);- const roofMaxLateral = Math.max(positive.bounds.max[lateralAxis], negative.bounds.max[lateralAxis]);- const lateralCoverage = intervalCoverage(roofMinLateral, roofMaxLateral, -expectedLateralSpan / 2, expectedLateralSpan / 2);- if (ridgeCoverage < 0.9 || lateralCoverage < 0.9) {- const actual = Math.min(ridgeCoverage, lateralCoverage);- findings.push(architectureFinding(context, {- code: "ARCH_ROOF_AXIS",- disposition: exactDisposition,- message: `The semantic slopes cover ${(ridgeCoverage * 100).toFixed(1)}% of the ridge span and ${(lateralCoverage * 100).toFixed(1)}% of the ridge-to-eave span.`,- measurement: {- name: "minimumRoofFootprintCoverageRatio",- actual,- expected: ">= 0.9",- threshold: 0.9- },- affected: { node: positive.parts[0]?.nodeName ?? "roof.slope.positive" }- }));- }- const panels = evidence.parts.filter((part) => part.isMesh && (part.directRoles.some((role) => role.startsWith("roof.panel.")) || hasRole(part, "roof.surface.panels") || hasRolePrefix(part, "roof.") && /panel|sheet|shingle|seam|corrugat/i.test(part.nodeName)));- const wrongPanel = panels.find((panel) => {- const ridgeExtent = extent(panel.bounds, ridgeAxis);- const downhillExtent = Math.hypot(extent(panel.bounds, lateralAxis), extent(panel.bounds, "y"));- return ridgeExtent > downhillExtent * 1.05;+ ]));+ root.add(mesh);+ return mesh;+ };+ const slopes = [buildSlope(faces[0]), buildSlope(faces[1])];+ return {+ root,+ slopes,+ faces: [faces[0], faces[1]],+ rise: profile.rise,+ pitchDegrees: profile.pitchDegrees+ };+}+function createGableRoof(name, material, options) {+ return buildRoof(name, material, resolveRoofProfile(options), options.parent);+}+function createRoofPlanes(name, material, options) {+ const ridgeAxis = options.ridgeAxis ?? "x";+ const overhang = nonNegative(options.overhang ?? 0.3, "overhang");+ const halfFoot = (ridgeAxis === "x" ? positive(options.width, "width") : positive(options.depth, "depth")) / 2;+ const totalRun = halfFoot + overhang;+ const height = positive(options.height, "height");+ const pitchDegrees = Math.atan2(height, totalRun) / DEG;+ const profile = resolveRoofProfile({+ spanX: options.depth,+ spanZ: options.width,+ ridgeAxis,+ overhang,+ thickness: options.thickness,+ rise: Math.tan(pitchDegrees * DEG) * halfFoot});- if (wrongPanel) {- const ridgeExtent = extent(wrongPanel.bounds, ridgeAxis);- const downhillExtent = Math.hypot(extent(wrongPanel.bounds, lateralAxis), extent(wrongPanel.bounds, "y"));- findings.push(architectureFinding(context, {- code: "ARCH_ROOF_AXIS",- disposition: exactDisposition,- message: `Roof panel ${wrongPanel.nodeName} runs along the ridge instead of ridge-to-eave.`,- affected: { node: wrongPanel.nodeName, nodePath: wrongPanel.nodePath },- measurement: {- name: "panelRidgeToDownhillExtentRatio",- actual: ridgeExtent / Math.max(EPSILON, downhillExtent),- expected: "<= 1.05",- threshold: 1.05- }- }));- }- const ridgeDistance = ridgeCrossSectionDistance(positive, negative, lateralAxis, architecture.roof.rise);- const ridgeTolerance = Math.max(0.04, expectedLateralSpan * 0.0125);- if (!Number.isFinite(ridgeDistance) || ridgeDistance > ridgeTolerance) {- findings.push(architectureFinding(context, {- code: "ARCH_RIDGE_GAP",- disposition: exactDisposition,- message: `The two slope high edges miss the declared ridge by ${Number.isFinite(ridgeDistance) ? ridgeDistance.toFixed(3) : "an unmeasurable"} m.`,- affected: { node: negative.parts[0]?.nodeName ?? "roof.slope.negative" },- measurement: {- name: "ridgeCrossSectionGap",- actual: Number.isFinite(ridgeDistance) ? ridgeDistance : null,- expected: `<= ${ridgeTolerance}`,- threshold: ridgeTolerance,- unit: "m"- }- }));+ profile.ridgeY = height;+ profile.eaveY = 0;+ profile.pitchDegrees = pitchDegrees;+ return buildRoof(name, material, profile, options.parent);+}+function openingFitsTriangle(opening, span, rise) {+ const half = span / 2;+ const left = opening.offset - opening.width / 2;+ const right = opening.offset + opening.width / 2;+ const top = opening.bottom + opening.height;+ const maxAt = (u) => rise * (1 - Math.abs(u) / half);+ return left > -half && right < half && opening.bottom >= 0 && top < Math.min(maxAt(left), maxAt(right));+}+function createGableEndPanel(name, material, options) {+ const span = positive(options.span, "span");+ const rise = positive(options.rise, "rise");+ const thickness = positive(options.thickness ?? 0.15, "thickness");+ const ridgeAxis = options.ridgeAxis ?? "x";+ const side = options.side ?? "positive";+ const half = span / 2;+ const shape = new THREE2.Shape;+ shape.moveTo(-half, 0);+ shape.lineTo(half, 0);+ shape.lineTo(0, rise);+ shape.closePath();+ const normalized = (options.openings ?? []).map((opening) => ({+ id: opening.id,+ offset: opening.offset ?? 0,+ bottom: opening.bottom ?? 0.25,+ width: positive(opening.width, "opening.width"),+ height: positive(opening.height, "opening.height")+ }));+ for (const opening of normalized) {+ if (!openingFitsTriangle(opening, span, rise))+ throw new RangeError("gable opening must fit strictly inside the triangular boundary");+ const left = opening.offset - opening.width / 2;+ const right = opening.offset + opening.width / 2;+ const bottom = opening.bottom;+ const top = bottom + opening.height;+ const hole = new THREE2.Path;+ hole.moveTo(left, bottom);+ hole.lineTo(left, top);+ hole.lineTo(right, top);+ hole.lineTo(right, bottom);+ hole.closePath();+ shape.holes.push(hole);}- return findings;+ const geometry = new THREE2.ExtrudeGeometry(shape, {+ depth: thickness,+ bevelEnabled: false,+ steps: 1+ });+ geometry.translate(0, 0, -thickness / 2);+ if (ridgeAxis === "x")+ geometry.rotateY(-Math.PI / 2);+ geometry.computeVertexNormals();+ const root = new THREE2.Mesh(geometry, material);+ root.name = `Mesh_${name}`;+ stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [+ relationship("adjacent-to", "roof.slope.positive"),+ relationship("adjacent-to", "roof.slope.negative"),+ relationship("coverage-of", ridgeAxis === "x" ? side === "positive" ? "wall.front" : "wall.back" : side === "positive" ? "wall.right" : "wall.left"),+ relationship("separable-from", "architecture.shell.gable")+ ], [+ { id: "base", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ {+ id: "apex",+ translation: ridgeAxis === "x" ? [0, rise, 0] : [0, rise, 0],+ rotation: [0, 0, 0, 1]+ }+ ]));+ const markers = normalized.map((opening, index) => {+ const marker = new THREE2.Object3D;+ marker.name = `Opening_${name}_${opening.id ?? index + 1}`;+ marker.position.set(ridgeAxis === "z" ? opening.offset : 0, opening.bottom + opening.height / 2, ridgeAxis === "x" ? opening.offset : 0);+ marker.scale.set(ridgeAxis === "x" ? thickness : opening.width, opening.height, ridgeAxis === "x" ? opening.width : thickness);+ stampSemanticMetadataV1(marker, roleMetadata([`opening.gable.${side}.${opening.id ?? index + 1}`], [relationship("cutout-of", `roof.gable.${side}`)]));+ root.add(marker);+ return marker;+ });+ if (options.parent)+ options.parent.add(root);+ return { root, geometry, openings: markers };}-function projectedGableArea(aggregateValue, lateralAxis) {- let area = 0;- for (const triangle of aggregateValue.triangles) {- const abLateral = triangle.b[lateralAxis] - triangle.a[lateralAxis];- const abY = triangle.b.y - triangle.a.y;- const acLateral = triangle.c[lateralAxis] - triangle.a[lateralAxis];- const acY = triangle.c.y - triangle.a.y;- area += Math.abs(abLateral * acY - abY * acLateral) / 2;+function wallRunAxis(wall) {+ return wall === "front" || wall === "back" ? "z" : "x";+}+function wallNeighbors(wall) {+ return wall === "front" || wall === "back" ? ["left", "right"] : ["front", "back"];+}+function createShellWall(name, wall, material, length, height, thickness, openings) {+ const axis = wallRunAxis(wall);+ const root = new THREE2.Object3D;+ root.name = `${name}_Wall_${wall}`;+ const neighbors = wallNeighbors(wall);+ stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [+ relationship("adjacent-to", `wall.${neighbors[0]}`),+ relationship("adjacent-to", `wall.${neighbors[1]}`),+ relationship("adjacent-to", "floor")+ ]));+ const sorted = openings.map((opening, index) => ({+ ...opening,+ id: opening.id ?? `${opening.kind ?? "door"}-${index + 1}`,+ kind: opening.kind ?? "door",+ offset: opening.offset ?? 0,+ width: positive(opening.width ?? (opening.kind === "window" ? 1 : 1.1), "opening.width"),+ height: positive(opening.height ?? (opening.kind === "window" ? 1 : 2.1), "opening.height"),+ sill: opening.kind === "window" ? nonNegative(opening.sill ?? 1, "opening.sill") : 0,+ depth: positive(opening.depth ?? thickness, "opening.depth")+ })).sort((a, b) => a.offset - b.offset);+ if (sorted.length > 1)+ throw new RangeError("the minimal gable shell supports at most one opening per wall");+ const panel = (suffix, lo, hi, y0, y1) => {+ if (hi - lo <= EPSILON || y1 - y0 <= EPSILON)+ return;+ const geometry = axis === "x" ? new THREE2.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE2.BoxGeometry(thickness, y1 - y0, hi - lo);+ const mesh = new THREE2.Mesh(geometry, material);+ mesh.name = `Mesh_${name}_${wall}_${suffix}`;+ mesh.position.set(axis === "x" ? (lo + hi) / 2 : 0, (y0 + y1) / 2, axis === "z" ? (lo + hi) / 2 : 0);+ root.add(mesh);+ };+ const markers = [];+ const opening = sorted[0];+ if (!opening)+ panel("solid", -length / 2, length / 2, 0, height);+ else {+ const left = opening.offset - opening.width / 2;+ const right = opening.offset + opening.width / 2;+ const top = opening.sill + opening.height;+ if (left <= -length / 2 || right >= length / 2 || top >= height)+ throw new RangeError(`opening on wall.${wall} must fit strictly inside the wall boundary`);+ panel("left", -length / 2, left, 0, height);+ panel("right", right, length / 2, 0, height);+ panel("lintel", left, right, top, height);+ if (opening.sill > 0)+ panel("sill", left, right, 0, opening.sill);+ const marker = new THREE2.Object3D;+ marker.name = `Opening_${wall}_${opening.id}`;+ marker.position.set(axis === "x" ? opening.offset : 0, opening.sill + opening.height / 2, axis === "z" ? opening.offset : 0);+ marker.scale.set(axis === "x" ? opening.width : opening.depth, opening.height, axis === "z" ? opening.width : opening.depth);+ stampSemanticMetadataV1(marker, roleMetadata([`opening.${wall}.${opening.kind}`], [+ relationship("cutout-of", `wall.${wall}`),+ relationship(opening.kind === "door" ? "portal-through" : "aperture-through", `wall.${wall}`)+ ], [{ id: "clearance", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }]));+ root.add(marker);+ markers.push(marker);}- return area;+ return { root, openings: markers };}-function endFindings(context, architecture, evidence) {- if (!requestedGable(architecture) || isOpenPavilion(architecture, evidence))- return [];- const closedEnds = architecture.roof.closedEnds;- if (!closedEnds)- return [];- const positive = aggregateRole(evidence, "roof.gable.positive");- const negative = aggregateRole(evidence, "roof.gable.negative");- const hasTaggedRoof = taggedGable(evidence);- const disposition = hasTaggedRoof ? "block" : "warn";- const ridgeAxis = architecture.roof.ridgeAxis;- const lateralAxis = ridgeAxis === "x" ? "z" : "x";- const lateralSpan = lateralAxis === "x" ? architecture.footprint.spanX : architecture.footprint.spanZ;- const ridgeSpan = ridgeAxis === "x" ? architecture.footprint.spanX : architecture.footprint.spanZ;- const expectedArea = lateralSpan * architecture.roof.rise / 2;- const findings = [];- for (const [end, aggregateValue] of [- ["positive", positive],- ["negative", negative]- ]) {- if (!aggregateValue) {- findings.push(architectureFinding(context, {- code: "ARCH_OPEN_GABLE",- disposition,- message: `closedEnds=true but roof.gable.${end} is missing.`,- affected: { node: `roof.gable.${end}` },- measurement: {- name: `${end}GableCoverageRatio`,- actual: 0,- expected: ">= 0.9 boundary coverage",- threshold: 0.9- }- }));- continue;- }- const wallRole = ridgeAxis === "x" ? end === "positive" ? "wall.front" : "wall.back" : end === "positive" ? "wall.right" : "wall.left";- const endWall = aggregate(evidence.parts.filter((part) => part.isMesh && hasRole(part, wallRole)));- const gableCenter = (aggregateValue.bounds.min[ridgeAxis] + aggregateValue.bounds.max[ridgeAxis]) / 2;- const expectedCenter = (end === "positive" ? 1 : -1) * (ridgeSpan / 2);- const endSeparation = endWall ? intervalSeparation(aggregateValue.bounds.min[ridgeAxis], aggregateValue.bounds.max[ridgeAxis], endWall.bounds.min[ridgeAxis], endWall.bounds.max[ridgeAxis]) : Math.abs(gableCenter - expectedCenter);- const endTolerance = 0.05;- if (endSeparation > endTolerance) {- findings.push(architectureFinding(context, {- code: "ARCH_OPEN_GABLE",- disposition,- message: `roof.gable.${end} is ${endSeparation.toFixed(3)} m away from its ${wallRole} end boundary, so it does not close the shell.`,- affected: {- node: aggregateValue.parts[0]?.nodeName ?? `roof.gable.${end}`,- nodePath: aggregateValue.parts[0]?.nodePath- },- measurement: {- name: `${end}GableEndSeparation`,- actual: endSeparation,- expected: `<= ${endTolerance}`,- threshold: endTolerance,- unit: "m"- }- }));- continue;- }- const lateralCoverage = extent(aggregateValue.bounds, lateralAxis) / lateralSpan;- const heightCoverage = extent(aggregateValue.bounds, "y") / architecture.roof.rise;- const areaCoverage = expectedArea > EPSILON ? projectedGableArea(aggregateValue, lateralAxis) / expectedArea : 1;- const boundaryCoverage = Math.min(lateralCoverage, heightCoverage);- if (boundaryCoverage < 0.9 || areaCoverage < 0.45) {- findings.push(architectureFinding(context, {- code: "ARCH_OPEN_GABLE",- disposition,- message: `roof.gable.${end} is sparse: boundary coverage ${(boundaryCoverage * 100).toFixed(1)}%, projected filled area ${(areaCoverage * 100).toFixed(1)}%.`,- affected: {- node: aggregateValue.parts[0]?.nodeName ?? `roof.gable.${end}`,- nodePath: aggregateValue.parts[0]?.nodePath- },- measurement: {- name: `${end}GableMinimumCoverageRatio`,- actual: Math.min(boundaryCoverage, areaCoverage / 0.5),- expected: ">= 0.9 boundary and >= 0.45 area",- threshold: 0.9- }- }));- }- }- return findings;-}-function pointInProjectedTriangle(x, z3, triangle) {- const ax = triangle.a.x;- const az = triangle.a.z;- const bx = triangle.b.x;- const bz = triangle.b.z;- const cx = triangle.c.x;- const cz = triangle.c.z;- const denominator = (bz - cz) * (ax - cx) + (cx - bx) * (az - cz);- if (Math.abs(denominator) <= EPSILON)- return { inside: false, weights: [0, 0, 0] };- const wa = ((bz - cz) * (x - cx) + (cx - bx) * (z3 - cz)) / denominator;- const wb = ((cz - az) * (x - cx) + (ax - cx) * (z3 - cz)) / denominator;- const wc = 1 - wa - wb;- const tolerance = 0.00001;- return {- inside: wa >= -tolerance && wb >= -tolerance && wc >= -tolerance,- weights: [wa, wb, wc]+function createGableShell(name, materials, options) {+ const spanX = positive(options.spanX, "spanX");+ const spanZ = positive(options.spanZ, "spanZ");+ const wallHeight = positive(options.wallHeight ?? 2.8, "wallHeight");+ const wallThickness = positive(options.wallThickness ?? 0.15, "wallThickness");+ const floorThickness = positive(options.floorThickness ?? 0.1, "floorThickness");+ const ridgeAxis = options.ridgeAxis ?? "x";+ const closedEnds = options.closedEnds ?? true;+ const enterable = options.enterable ?? true;+ const shellOpenings = options.openings ?? (enterable ? [{ wall: "front", kind: "door" }] : []);+ const root = new THREE2.Object3D;+ root.name = name;+ if (options.parent)+ options.parent.add(root);+ stampSemanticMetadataV1(root, roleMetadata(["architecture.shell.gable"], [relationship("contains", "floor"), relationship("contains", "roof.assembly")]));+ const wallSpecs = {+ front: { length: spanZ, position: [spanX / 2, 0, 0] },+ back: { length: spanZ, position: [-spanX / 2, 0, 0] },+ left: { length: spanX, position: [0, 0, -spanZ / 2] },+ right: { length: spanX, position: [0, 0, spanZ / 2] }};-}-function nearestRoofHeight(triangles, x, z3, targetY) {- const heights = [];- for (const triangle of triangles) {- const projected = pointInProjectedTriangle(x, z3, triangle);- if (!projected.inside)- continue;- const [wa, wb, wc] = projected.weights;- heights.push(wa * triangle.a.y + wb * triangle.b.y + wc * triangle.c.y);+ const walls = {};+ const openingMarkers = [];+ for (const wall of ["front", "back", "left", "right"]) {+ const built = createShellWall(name, wall, materials.wall, wallSpecs[wall].length, wallHeight, wallThickness, shellOpenings.filter((opening) => opening.wall === wall));+ built.root.position.set(...wallSpecs[wall].position);+ root.add(built.root);+ walls[wall] = built.root;+ openingMarkers.push(...built.openings);}- return heights.sort((a, b) => Math.abs(a - targetY) - Math.abs(b - targetY))[0];+ const floor = new THREE2.Mesh(new THREE2.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);+ floor.name = `Mesh_${name}_Floor`;+ floor.position.y = -floorThickness / 2;+ stampSemanticMetadataV1(floor, roleMetadata(["floor"], ["front", "back", "left", "right"].map((wall) => relationship("adjacent-to", `wall.${wall}`))));+ root.add(floor);+ const roof = createGableRoof("Roof", materials.roof, {+ ...options,+ spanX,+ spanZ,+ ridgeAxis,+ parent: root+ });+ roof.root.position.y = wallHeight;+ let gables = [];+ if (closedEnds) {+ const gableMaterial = materials.gable ?? materials.wall;+ const span = ridgeAxis === "x" ? spanZ : spanX;+ const ridgeSpan = ridgeAxis === "x" ? spanX : spanZ;+ const positiveEnd = createGableEndPanel(`${name}_Gable_positive`, gableMaterial, {+ span,+ rise: roof.rise,+ thickness: wallThickness,+ ridgeAxis,+ side: "positive",+ openings: options.gableOpenings?.positive,+ parent: roof.root+ });+ const negativeEnd = createGableEndPanel(`${name}_Gable_negative`, gableMaterial, {+ span,+ rise: roof.rise,+ thickness: wallThickness,+ ridgeAxis,+ side: "negative",+ openings: options.gableOpenings?.negative,+ parent: roof.root+ });+ const coordinate = ridgeSpan / 2;+ positiveEnd.root.position.set(ridgeAxis === "x" ? coordinate : 0, 0, ridgeAxis === "z" ? coordinate : 0);+ negativeEnd.root.position.set(ridgeAxis === "x" ? -coordinate : 0, 0, ridgeAxis === "z" ? -coordinate : 0);+ gables = [positiveEnd.root, negativeEnd.root];+ openingMarkers.push(...positiveEnd.openings, ...negativeEnd.openings);+ }+ return { root, walls, floor, roof, gables, openings: openingMarkers };}-function envelopeFindings(context, architecture, evidence) {- if (!requestedGable(architecture) || isOpenPavilion(architecture, evidence))- return [];- const roof = aggregate(evidence.parts.filter((part) => part.isMesh && (hasRole(part, "roof.slope.positive") || hasRole(part, "roof.slope.negative"))));- if (!roof || roof.triangles.length === 0)- return [];- const ridgeAxis = architecture.roof.ridgeAxis;- const lateralAxis = ridgeAxis === "x" ? "z" : "x";- const ridgeSpan = ridgeAxis === "x" ? architecture.footprint.spanX : architecture.footprint.spanZ;- const lateralSpan = lateralAxis === "x" ? architecture.footprint.spanX : architecture.footprint.spanZ;- const wallRoles = ridgeAxis === "x" ? ["wall.left", "wall.right"] : ["wall.front", "wall.back"];- const findings = [];- const gapTolerance = 0.05;- const penetrationTolerance = 0.12;- for (const [sideIndex, wallRole] of wallRoles.entries()) {- const wall = aggregateRole(evidence, wallRole);- if (!wall)- continue;- const sign = sideIndex === 0 ? -1 : 1;- const lateral = sign * (lateralSpan / 2);- const wallTop = wall.bounds.max.y;- const offsets = [-0.4, 0, 0.4];- const separations = [];- for (const offset of offsets) {- const ridge = offset * ridgeSpan;- const x = ridgeAxis === "x" ? ridge : lateral;- const z3 = ridgeAxis === "x" ? lateral : ridge;- const roofY = nearestRoofHeight(roof.triangles, x, z3, wallTop);- if (roofY !== undefined)- separations.push(roofY - wallTop);- }- if (separations.length === 0)- continue;- const worstGap = Math.max(...separations);- const worstPenetration = -Math.min(...separations);- if (worstGap > gapTolerance || worstPenetration > penetrationTolerance) {- const daylight = worstGap > gapTolerance;- findings.push(architectureFinding(context, {- code: "ARCH_ENVELOPE_GAP",- disposition: "warn",- message: daylight ? `${wallRole} has a ${worstGap.toFixed(3)} m daylight gap to the roof underside at sampled bearing points.` : `${wallRole} penetrates the roof envelope by ${worstPenetration.toFixed(3)} m at sampled bearing points.`,- affected: {- node: wall.parts[0]?.nodeName ?? wallRole,- nodePath: wall.parts[0]?.nodePath- },- measurement: {- name: daylight ? "maximumWallRoofGap" : "maximumWallRoofPenetration",- actual: daylight ? worstGap : worstPenetration,- expected: daylight ? `<= ${gapTolerance}` : `<= ${penetrationTolerance}`,- threshold: daylight ? gapTolerance : penetrationTolerance,- unit: "m"- }- }));+function createRoofSurfaceLayout(name, material, options) {+ const parent = options.parent ?? options.face.roofRoot;+ const root = new THREE2.Object3D;+ root.name = name;+ parent.add(root);+ stampSemanticMetadataV1(root, roleMetadata([`roof.surface.${options.kind}`], [relationship("coverage-of", `roof.slope.${options.face.side}`)]));+ root.updateWorldMatrix(true, false);+ const faceToRoot = root.matrixWorld.clone().invert().multiply(options.face.localToWorld);+ const thickness = positive(options.thickness ?? 0.025, "thickness");+ const along = options.face.dimensions.alongRidge;+ const downhill = options.face.dimensions.downhill;+ const specs = [];+ if (options.kind === "panels") {+ const count = Math.max(1, Math.ceil(along / positive(options.panelWidth ?? 0.9, "panelWidth")));+ const width = along / count;+ for (let i = 0;i < count; i++)+ specs.push({+ width: width * 0.98,+ length: downhill,+ x: -along / 2 + width * (i + 0.5),+ z: downhill / 2+ });+ } else if (options.kind === "shingles") {+ const rowHeight = positive(options.rowHeight ?? 0.32, "rowHeight");+ const tileWidth = positive(options.panelWidth ?? 0.42, "panelWidth");+ const rows = Math.max(1, Math.ceil(downhill / rowHeight));+ const columns = Math.max(1, Math.ceil(along / tileWidth));+ for (let row = 0;row < rows; row++) {+ const length = Math.min(rowHeight * 1.08, downhill);+ for (let column = 0;column < columns; column++) {+ const offset = row % 2 === 0 ? 0 : tileWidth / 2;+ const x = -along / 2 + tileWidth * (column + 0.5) + offset;+ if (x + tileWidth / 2 <= along / 2 + EPSILON)+ specs.push({+ width: tileWidth * 0.96,+ length,+ x,+ z: Math.min(downhill - length / 2, row * rowHeight + length / 2)+ });+ }}+ } else {+ const spacing = positive(options.spacing ?? (options.kind === "seams" ? 0.6 : 0.18), "spacing");+ const count = Math.max(2, Math.floor(along / spacing) + 1);+ const width = options.kind === "seams" ? 0.025 : 0.018;+ for (let i = 0;i < count; i++)+ specs.push({+ width,+ length: downhill,+ x: -along / 2 + along * i / (count - 1),+ z: downhill / 2+ });}- return findings;-}-function boundsOverlap(a, b, tolerance = 0) {- return a.min.x < b.max.x - tolerance && a.max.x > b.min.x + tolerance && a.min.y < b.max.y - tolerance && a.max.y > b.min.y + tolerance && a.min.z < b.max.z - tolerance && a.max.z > b.min.z + tolerance;+ const items = specs.map((spec, index) => {+ const mesh = new THREE2.Mesh(new THREE2.BoxGeometry(spec.width, thickness, spec.length), material);+ mesh.name = `Mesh_${name}_${index + 1}`;+ const local = new THREE2.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);+ setTransform(mesh, faceToRoot.clone().multiply(local));+ root.add(mesh);+ return mesh;+ });+ return { root, items };}-function shrunkenPortalBounds(bounds, wall) {- const result = { min: bounds.min.clone(), max: bounds.max.clone() };- const widthAxis = wall === "front" || wall === "back" ? "z" : "x";- const normalAxis = widthAxis === "x" ? "z" : "x";- const widthInset = Math.min(0.04, extent(result, widthAxis) * 0.08);- const heightInset = Math.min(0.04, extent(result, "y") * 0.04);- result.min[widthAxis] += widthInset;- result.max[widthAxis] -= widthInset;- result.min.y += heightInset;- result.max.y -= heightInset;- if (extent(result, normalAxis) <= EPSILON) {- result.min[normalAxis] -= 0.01;- result.max[normalAxis] += 0.01;+var DEG, EPSILON = 0.0000001;+var init_architecture = __esm(() => {+ init_contracts();+ DEG = Math.PI / 180;+});++// src/gears.ts+import * as THREE3 from "three";+function gearGeo(opts = {}) {+ const {+ teeth = 12,+ rootRadius = 0.8,+ tipRadius = 1,+ boreRadius = 0.2,+ height = 0.3,+ toothWidthFrac = 0.5+ } = opts;+ if (teeth < 3)+ throw new Error("gearGeo: teeth must be >= 3");+ if (tipRadius <= rootRadius || boreRadius >= rootRadius) {+ throw new AuthoringDiagnosticError("GEAR_RADII_ORDER");}- return result;-}-function portalRoleWall(roles) {- for (const role of roles) {- const match = /^opening\.(front|back|left|right)\.(?:door|portal|entry)(?:\.|$)/.exec(role);- if (match)- return match[1];+ const sector = Math.PI * 2 / teeth;+ const alpha = (1 - toothWidthFrac) * (sector / 2);+ const crown = [];+ for (let i = 0;i < teeth; i++) {+ const base = i * sector;+ const a0 = base;+ const a1 = base + alpha;+ const a2 = base + sector - alpha;+ crown.push([rootRadius * Math.cos(a0), rootRadius * Math.sin(a0)]);+ crown.push([tipRadius * Math.cos(a1), tipRadius * Math.sin(a1)]);+ crown.push([tipRadius * Math.cos(a2), tipRadius * Math.sin(a2)]);}- return;-}-function portalFindings(context, architecture, evidence) {- if (!architecture.enterable && !context.intent.capabilities.includes("enterable"))- return [];- const requested = architecture.portal ?? { width: 1.1, height: 2.1, depth: 0.15 };- const markers = evidence.parts.filter((part) => !part.isMesh && portalRoleWall(part.directRoles) !== undefined);- if (markers.length === 0) {- return [- architectureFinding(context, {- code: "ARCH_BLOCKED_PORTAL",- disposition: "block",- message: "enterable=true requires a non-rendered semantic opening.<wall>.door clearance node; no exterior-to-interior portal was found.",- affected: { node: evidence.root.name || "architecture-root" },- measurement: {- name: "semanticPortalCount",- actual: 0,- expected: ">= 1",- threshold: 1- }- })- ];+ const N = crown.length;+ const bore = [];+ for (let i = 0;i < N; i++) {+ const t = Math.atan2(crown[i][1], crown[i][0]);+ bore.push([boreRadius * Math.cos(t), boreRadius * Math.sin(t)]);}- const failures = [];- for (const marker of markers) {- const wall = portalRoleWall(marker.directRoles);- const widthAxis = wall === "front" || wall === "back" ? "z" : "x";- const depthAxis = widthAxis === "x" ? "z" : "x";- const width = extent(marker.bounds, widthAxis);- const height = extent(marker.bounds, "y");- const depth = extent(marker.bounds, depthAxis);- const claimedWall = aggregate(evidence.parts.filter((part) => part.isMesh && hasRole(part, `wall.${wall}`) && !hasRolePrefix(part, "opening.")));- const placementCoverage = claimedWall ? Math.min(intervalCoverage(marker.bounds.min[depthAxis], marker.bounds.max[depthAxis], claimedWall.bounds.min[depthAxis], claimedWall.bounds.max[depthAxis]), intervalCoverage(claimedWall.bounds.min[widthAxis], claimedWall.bounds.max[widthAxis], marker.bounds.min[widthAxis], marker.bounds.max[widthAxis]), intervalCoverage(claimedWall.bounds.min.y, claimedWall.bounds.max.y, marker.bounds.min.y, marker.bounds.max.y)) : 0;- const misplaced = placementCoverage < 0.9;- const clearance = shrunkenPortalBounds(marker.bounds, wall);- const blocker = evidence.parts.find((part) => {- if (!part.isMesh)- return false;- if (hasRolePrefix(part, "roof.") || hasRole(part, "floor") || hasRolePrefix(part, "opening.")) {- return false;- }- if (context.intent.capabilities.includes("openable") && part.roles.some((role) => role === "door.leaf" || role.startsWith("door.leaf."))) {- return false;- }- return boundsOverlap(part.bounds, clearance, 0.004);- });- const undersized = width + 0.01 < requested.width || height + 0.01 < requested.height || depth + 0.01 < requested.depth;- if (!blocker && !undersized && !misplaced)- return [];- failures.push({- marker,- wall,- ...blocker ? { blocker } : {},- width,- height,- depth,- placementCoverage,- undersized,- misplaced- });+ const halfH = height / 2;+ const positions = [];+ const indices = [];+ for (let i = 0;i < N; i++) {+ const p = crown[i];+ positions.push(p[0], halfH, p[1]);}- const failure = failures[0];- const undersizedBy = Math.max(0, requested.width - failure.width, requested.height - failure.height, requested.depth - failure.depth);- return [- architectureFinding(context, {- code: "ARCH_BLOCKED_PORTAL",- disposition: "block",- message: failure.blocker ? `Portal ${failure.marker.nodeName} is blocked by ${failure.blocker.nodeName}; the semantic clearance does not connect exterior to interior.` : failure.undersized ? `Portal ${failure.marker.nodeName} is smaller than the requested ${requested.width.toFixed(2)} x ${requested.height.toFixed(2)} x ${requested.depth.toFixed(2)} m clearance.` : `Portal ${failure.marker.nodeName} overlaps only ${(failure.placementCoverage * 100).toFixed(1)}% of its claimed wall passage, so it does not connect exterior to interior through wall.${failure.wall}.`,- affected: failure.blocker ? { node: failure.blocker.nodeName, nodePath: failure.blocker.nodePath } : { node: failure.marker.nodeName, nodePath: failure.marker.nodePath },- measurement: failure.blocker ? {- name: "portalBlockerCount",- actual: 1,- expected: 0,- threshold: 0- } : failure.undersized ? {- name: "maximumPortalClearanceDeficit",- actual: undersizedBy,- expected: 0,- threshold: 0.01,- unit: "m"- } : {- name: "portalClaimedWallCoverageRatio",- actual: failure.placementCoverage,- expected: ">= 0.9",- threshold: 0.9- },- viewHints: ["architecture.portal.eye"]- })- ];+ for (let i = 0;i < N; i++) {+ const p = crown[i];+ positions.push(p[0], -halfH, p[1]);+ }+ for (let i = 0;i < N; i++) {+ const p = bore[i];+ positions.push(p[0], halfH, p[1]);+ }+ for (let i = 0;i < N; i++) {+ const p = bore[i];+ positions.push(p[0], -halfH, p[1]);+ }+ const crownTop = 0;+ const crownBot = N;+ const boreTop = 2 * N;+ const boreBot = 3 * N;+ for (let i = 0;i < N; i++) {+ const j = (i + 1) % N;+ const cA = crownTop + i;+ const cB = crownTop + j;+ const bA = boreTop + i;+ const bB = boreTop + j;+ indices.push(bA, cB, cA);+ if (boreRadius > 0)+ indices.push(bA, bB, cB);+ }+ for (let i = 0;i < N; i++) {+ const j = (i + 1) % N;+ const cA = crownBot + i;+ const cB = crownBot + j;+ const bA = boreBot + i;+ const bB = boreBot + j;+ indices.push(bA, cA, cB);+ if (boreRadius > 0)+ indices.push(bA, cB, bB);+ }+ for (let i = 0;i < N; i++) {+ const j = (i + 1) % N;+ const tA = crownTop + i;+ const tB = crownTop + j;+ const bA = crownBot + i;+ const bB = crownBot + j;+ indices.push(tA, tB, bB);+ indices.push(tA, bB, bA);+ }+ for (let i = 0;boreRadius > 0 && i < N; i++) {+ const j = (i + 1) % N;+ const tA = boreTop + i;+ const tB = boreTop + j;+ const bA = boreBot + i;+ const bB = boreBot + j;+ indices.push(tA, bA, bB);+ indices.push(tA, bB, tB);+ }+ const geo = new THREE3.BufferGeometry;+ geo.setAttribute("position", new THREE3.Float32BufferAttribute(positions, 3));+ geo.setIndex(indices);+ const nonIndexed = geo.toNonIndexed();+ nonIndexed.computeVertexNormals();+ return nonIndexed;}-function storeyFindings(context, architecture, evidence) {- const requested = architecture.storeyCount ?? 1;- const indexes = new Set;- for (const role of evidence.semanticRoles) {- const match = /^(?:architecture\.)?floor\.storey\.(\d+)$/.exec(role);- if (match)- indexes.add(Number(match[1]));+function bladeGeo(opts = {}) {+ const {+ length = 1.5,+ baseWidth = 0.1,+ thickness = 0.015,+ tipLength = 0.25,+ edgeBevel = 0+ } = opts;+ if (length <= 0 || baseWidth <= 0 || thickness <= 0) {+ throw new Error("bladeGeo: length, baseWidth, thickness must all be > 0");}- if (requested === 1 && indexes.size === 0)- return [];- const actual = indexes.size;- if (actual === requested)- return [];- return [- architectureFinding(context, {- code: "ARCH_STOREY_COUNT",- disposition: "block",- message: `Requested ${requested} storeys but found ${actual} distinct portable floor.storey.<index> roles.`,- affected: { node: evidence.root.name || "architecture-root" },- measurement: {- name: "semanticStoreyCount",- actual,- expected: requested,- threshold: requested- },- viewHints: ["architecture.cutaway.dollhouse", "generic.top.semantic-overlay"],- repairText: "Add or remove only the requested floor levels, stamp each level once as floor.storey.<1-5>, and keep stairs and clearances aligned between consecutive levels."- })- ];-}-function interiorModeFindings(context, architecture, evidence) {- const mode = architecture.interiorMode ?? (architecture.enterable ? "navigable" : "none");- const interiorEvidence = evidence.parts.filter((part) => part.roles.some((role) => role === "architecture.interior.shell" || role.startsWith("interior.")));- const valid = mode === "shell" ? interiorEvidence.length > 0 : mode !== "none" || interiorEvidence.length === 0;- if (valid)- return [];- return [- architectureFinding(context, {- code: "ARCH_INTERIOR_MODE",- disposition: "block",- message: mode === "shell" ? "interiorMode=shell requires a portable architecture.interior.shell semantic volume." : "interiorMode=none conflicts with semantic interior geometry.",- affected: {- node: interiorEvidence[0]?.nodeName ?? evidence.root.name ?? "architecture-root",- nodePath: interiorEvidence[0]?.nodePath- },- measurement: {- name: "semanticInteriorShellCount",- actual: interiorEvidence.length,- expected: mode === "shell" ? ">= 1" : 0,- threshold: mode === "shell" ? 1 : 0- },- viewHints: ["architecture.cutaway.dollhouse", "architecture.floor-plan"],- repairText: mode === "shell" ? "Add one non-rendering architecture.interior.shell volume matching the usable inner envelope; do not fake the interior with a painted exterior face." : "Remove the unrequested interior semantic volume or change trusted intent to shell/navigable before generation."- })+ if (tipLength >= length) {+ throw new Error("bladeGeo: tipLength must be less than length");+ }+ const hw = baseWidth / 2;+ const ht = thickness / 2;+ const shoulderY = length - tipLength;+ const outline = [+ [-hw, 0],+ [hw, 0],+ [hw, shoulderY],+ [0, length],+ [-hw, shoulderY]];+ const n = outline.length;+ const positions = [];+ const indices = [];+ if (edgeBevel <= 0) {+ for (const [x, y] of outline)+ positions.push(x, y, ht);+ for (const [x, y] of outline)+ positions.push(x, y, -ht);+ for (let i = 1;i < n - 1; i++) {+ indices.push(0, i, i + 1);+ }+ for (let i = 1;i < n - 1; i++) {+ indices.push(n, n + i + 1, n + i);+ }+ for (let i = 0;i < n; i++) {+ const j = (i + 1) % n;+ const tA = i;+ const tB = j;+ const bA = n + i;+ const bB = n + j;+ indices.push(tA, bA, bB);+ indices.push(tA, bB, tB);+ }+ } else {+ const zFlat = ht;+ const zRidge = ht * (1 - edgeBevel);+ const vertsPerRing = 4;+ for (const [x, y] of outline) {+ positions.push(x, y, zFlat);+ positions.push(x, y, zRidge);+ positions.push(x, y, -zRidge);+ positions.push(x, y, -zFlat);+ }+ const ringIdx = (i, k) => i * vertsPerRing + k;+ for (let i = 1;i < n - 1; i++) {+ indices.push(ringIdx(0, 0), ringIdx(i, 0), ringIdx(i + 1, 0));+ }+ for (let i = 1;i < n - 1; i++) {+ indices.push(ringIdx(0, 3), ringIdx(i + 1, 3), ringIdx(i, 3));+ }+ const layerPairs = [+ [0, 1],+ [1, 2],+ [2, 3],+ [3, 0]+ ];+ for (const [kA, kB] of layerPairs) {+ for (let i = 0;i < n; i++) {+ const j = (i + 1) % n;+ const a = ringIdx(i, kA);+ const b = ringIdx(j, kA);+ const c = ringIdx(j, kB);+ const d = ringIdx(i, kB);+ indices.push(a, d, c);+ indices.push(a, c, b);+ }+ }+ }+ const geo = new THREE3.BufferGeometry;+ geo.setAttribute("position", new THREE3.Float32BufferAttribute(positions, 3));+ geo.setIndex(indices);+ const nonIndexed = geo.toNonIndexed();+ nonIndexed.computeVertexNormals();+ return nonIndexed;}-function roofModeFindings(context, architecture, evidence) {- const mode = architecture.roofMode ?? (architecture.roof.type === "none" ? "none" : "auto");- if (mode === "auto")- return [];- const roofParts = evidence.parts.filter((part) => hasRolePrefix(part, "roof."));- const removableRelationships = roofParts.flatMap((part) => part.directRelationships.filter((relationship) => relationship.kind === "separable-from"));- const present = roofParts.length > 0;- const valid = mode === "none" ? !present : mode === "fixed" ? present && removableRelationships.length === 0 : present && removableRelationships.length > 0;- if (valid)- return [];- const measurement = mode === "removable" ? {- name: "removableRoofRelationshipCount",- actual: removableRelationships.length,- expected: ">= 1",- threshold: 1- } : {- name: "semanticRoofPartCount",- actual: roofParts.length,- expected: mode === "none" ? 0 : ">= 1",- threshold: mode === "none" ? 0 : 1- };- return [- architectureFinding(context, {- code: "ARCH_ROOF_MODE",- disposition: "block",- message: `roofMode=${mode} conflicts with ${roofParts.length} semantic roof parts and ${removableRelationships.length} separable-from relationships.`,- affected: {- node: roofParts[0]?.nodeName ?? evidence.root.name ?? "architecture-root",- nodePath: roofParts[0]?.nodePath- },- measurement,- viewHints: ["generic.top.semantic-overlay", "architecture.cutaway.dollhouse"],- repairText: "Match trusted roofMode exactly: omit all roof.* roles for none, keep fixed roofs attached, or stamp one roof assembly with a separable-from relationship for removable."- })- ];+var init_gears = __esm(() => {+ init_authoring_diagnostic();+});++// src/ops.ts+import * as THREE4 from "three";+import { LoopSubdivision } from "three-subdivide";+import { mergeVertices as threeMergeVertices } from "three/examples/jsm/utils/BufferGeometryUtils.js";+function arrayLinear(namePrefix, source, count, offset, parent) {+ const out = [];+ const base = source.position.toArray();+ for (let i = 1;i < count; i++) {+ const pos = [+ base[0] + offset[0] * i,+ base[1] + offset[1] * i,+ base[2] + offset[2] * i+ ];+ out.push(createInstance(`${namePrefix}${i}`, source, { position: pos, parent }));+ }+ return out;}-function domeFindings(context, architecture, evidence) {- const requested = architecture.roof.type === "dome" || /(?:^|[. _-])rotunda(?:$|[. _-])/i.test(architecture.subtype);- if (!requested)- return [];- const dome = aggregate(evidence.parts.filter((part) => part.isMesh && (hasRole(part, "roof.dome") || hasRole(part, "roof.surface.dome"))));- const spanXCoverage = dome ? extent(dome.bounds, "x") / architecture.footprint.spanX : 0;- const spanZCoverage = dome ? extent(dome.bounds, "z") / architecture.footprint.spanZ : 0;- const riseCoverage = dome ? extent(dome.bounds, "y") / architecture.roof.rise : 0;- const minimumCoverage = Math.min(spanXCoverage, spanZCoverage, riseCoverage);- if (minimumCoverage >= 0.9)- return [];- return [- architectureFinding(context, {- code: "ARCH_DOME_PROFILE",- disposition: "block",- message: `The semantic rotunda dome covers ${(spanXCoverage * 100).toFixed(1)}% X, ${(spanZCoverage * 100).toFixed(1)}% Z, and ${(riseCoverage * 100).toFixed(1)}% of declared rise.`,- affected: {- node: dome?.parts[0]?.nodeName ?? evidence.root.name ?? "architecture-root",- nodePath: dome?.parts[0]?.nodePath- },- measurement: {- name: "minimumDomeCoverageRatio",- actual: minimumCoverage,- expected: ">= 0.9",- threshold: 0.9- },- viewHints: ["generic.top.semantic-overlay", "architecture.cutaway.dollhouse"],- repairText: "Rebuild the roof.dome hemisphere to cover the declared circular rotunda footprint and rise; preserve any intentional oculus as a bounded opening rather than shrinking the whole dome."- })+function arrayRadial(namePrefix, source, count, axis = "y", parent) {+ const out = [];+ const basePos = source.position.clone();+ const axisVec = axis === "x" ? new THREE4.Vector3(1, 0, 0) : axis === "z" ? new THREE4.Vector3(0, 0, 1) : new THREE4.Vector3(0, 1, 0);+ for (let i = 1;i < count; i++) {+ const angle = i / count * Math.PI * 2;+ const m = new THREE4.Matrix4().makeRotationAxis(axisVec, angle);+ const rotated = basePos.clone().applyMatrix4(m);+ const eulerDeg = axis === "y" ? [0, angle * 180 / Math.PI, 0] : axis === "x" ? [angle * 180 / Math.PI, 0, 0] : [0, 0, angle * 180 / Math.PI];+ out.push(createInstance(`${namePrefix}${i}`, source, {+ position: [rotated.x, rotated.y, rotated.z],+ rotation: eulerDeg,+ parent+ }));+ }+ return out;+}+function mirror(name, source, axis, parent) {+ const sourcePos = source.position.toArray();+ const pos = [+ axis === "x" ? -sourcePos[0] : sourcePos[0],+ axis === "y" ? -sourcePos[1] : sourcePos[1],+ axis === "z" ? -sourcePos[2] : sourcePos[2]+ ];+ const scale = [+ axis === "x" ? -1 : 1,+ axis === "y" ? -1 : 1,+ axis === "z" ? -1 : 1];+ return createInstance(name, source, { position: pos, scale, parent });}-function scaleBandFinding(context, band) {- if (band.actual >= band.minimum && band.actual <= band.maximum)- return;- return architectureFinding(context, {- code: band.code,- disposition: "warn",- message: `${band.label} is ${band.actual.toFixed(3)} m; the realistic-scale observation band is ${band.minimum.toFixed(3)}–${band.maximum.toFixed(3)} m.`,- ...band.affected ? { affected: { node: band.affected.nodeName, nodePath: band.affected.nodePath } } : {},- measurement: {- name: band.label,- actual: band.actual,- expected: `${band.minimum}..${band.maximum}`,- threshold: band.actual < band.minimum ? band.minimum : band.maximum,- unit: band.unit- },- viewHints: ["architecture.cutaway.dollhouse"],- repairText: "Adjust only the reported architecture dimension into the realistic band, or explicitly select scaleMode=stylized to retain intentional exaggeration."- });+function mergeVertices(geometry, opts = {}) {+ const { tolerance = 0.0001, positionOnly = false } = typeof opts === "number" ? { tolerance: opts } : opts;+ if (!positionOnly)+ return threeMergeVertices(geometry, tolerance);+ const stripped = new THREE4.BufferGeometry;+ const pos = geometry.getAttribute("position");+ if (!pos)+ return geometry;+ stripped.setAttribute("position", new THREE4.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));+ if (geometry.index) {+ stripped.setIndex(new THREE4.BufferAttribute(new Uint32Array(geometry.index.array), 1));+ }+ return threeMergeVertices(stripped, tolerance);}-function scaleFindings(context, architecture, evidence) {- if (architecture.scaleMode === "stylized")- return [];- const scaleBands = ARCHITECTURE_REALISTIC_SCALE_BANDS;- const bands = [- {- code: "ARCH_SCALE_CEILING_HEIGHT",- label: "ceilingHeight",- actual: architecture.wallHeight,- minimum: scaleBands.ceilingHeight.minimum,- maximum: scaleBands.ceilingHeight.maximum,- unit: "m"- },- {- code: "ARCH_SCALE_FOOTPRINT_X",- label: "footprintSpanX",- actual: architecture.footprint.spanX,- minimum: scaleBands.footprint.minimum,- maximum: scaleBands.footprint.maximum,- unit: "m"- },- {- code: "ARCH_SCALE_FOOTPRINT_Z",- label: "footprintSpanZ",- actual: architecture.footprint.spanZ,- minimum: scaleBands.footprint.minimum,- maximum: scaleBands.footprint.maximum,- unit: "m"- }- ];- const portal = evidence.parts.find((part) => !part.isMesh && portalRoleWall(part.directRoles) !== undefined);- if (portal) {- const wall = portalRoleWall(portal.directRoles);- const widthAxis = wall === "front" || wall === "back" ? "z" : "x";- bands.push({- code: "ARCH_SCALE_DOOR_WIDTH",- label: "doorClearWidth",- actual: extent(portal.bounds, widthAxis),- minimum: scaleBands.doorWidth.minimum,- maximum: scaleBands.doorWidth.maximum,- unit: "m",- affected: portal- }, {- code: "ARCH_SCALE_DOOR_HEIGHT",- label: "doorClearHeight",- actual: extent(portal.bounds, "y"),- minimum: scaleBands.doorHeight.minimum,- maximum: scaleBands.doorHeight.maximum,- unit: "m",- affected: portal- });+function subdivide(geometry, iterations = 1, opts = {}) {+ const { weld = true, preserveUV = false, ...subOpts } = opts;+ const input = weld && !preserveUV ? mergeVertices(geometry, { positionOnly: true }) : geometry.clone();+ const center = new THREE4.Vector3;+ let normalizationScale = 1;+ if (preserveUV) {+ subOpts.uvSmooth = false;+ input.computeBoundingBox();+ const extent = input.boundingBox.getSize(new THREE4.Vector3);+ input.boundingBox.getCenter(center);+ const size = Math.max(extent.x, extent.y, extent.z);+ normalizationScale = size > 0 ? 1e4 / size : 1;+ input.translate(-center.x, -center.y, -center.z).scale(normalizationScale, normalizationScale, normalizationScale);}- const wallParts = evidence.parts.filter((part) => part.isMesh && part.roles.some((role) => role.startsWith("wall.")));- for (const wall of wallParts) {- const thickness = Math.min(extent(wall.bounds, "x"), extent(wall.bounds, "z"));- bands.push({- code: "ARCH_SCALE_WALL_THICKNESS",- label: "wallThickness",- actual: thickness,- minimum: scaleBands.wallThickness.minimum,- maximum: scaleBands.wallThickness.maximum,- unit: "m",- affected: wall- });+ const output = normalizeSurfaceNormals(LoopSubdivision.modify(input, iterations, subOpts));+ if (preserveUV)+ output.scale(1 / normalizationScale, 1 / normalizationScale, 1 / normalizationScale).translate(center.x, center.y, center.z);+ output.deleteAttribute("tangent");+ output.computeBoundingBox();+ output.computeBoundingSphere();+ if (geometry.getAttribute("uv") && !output.getAttribute("uv")) {+ output.userData.kilnAttributeWarnings = [+ {+ code: "SUBDIVIDE_UV_DROPPED",+ message: "Position-only subdivision discarded UVs. Use preserveUV: true or unwrap the output."+ }+ ];}- const steps = evidence.parts.filter((part) => part.isMesh && part.directRoles.some((role) => role.startsWith("stair.step")));- for (const step of steps) {- bands.push({- code: "ARCH_SCALE_STAIR_RISER",- label: "stairRiser",- actual: extent(step.bounds, "y"),- minimum: scaleBands.stairRiser.minimum,- maximum: scaleBands.stairRiser.maximum,- unit: "m",- affected: step- }, {- code: "ARCH_SCALE_STAIR_TREAD",- label: "stairTread",- actual: Math.min(extent(step.bounds, "x"), extent(step.bounds, "z")),- minimum: scaleBands.stairTread.minimum,- maximum: scaleBands.stairTread.maximum,- unit: "m",- affected: step- });+ if (geometry.userData.kilnCsgProvenance || geometry.userData.kilnRanges) {+ delete output.userData.kilnCsgProvenance;+ delete output.userData.kilnRanges;+ output.userData.kilnAttributeWarnings = [+ ...output.userData.kilnAttributeWarnings ?? [],+ {+ code: "SUBDIVIDE_PROVENANCE_DROPPED",+ message: "Subdivision changed triangle topology. Source face/range provenance was discarded rather than guessed."+ }+ ];}- return bands.flatMap((band) => {- const finding = scaleBandFinding(context, band);- return finding ? [finding] : [];- });-}-function evaluateArchitectureQa(context) {- const architecture = context.intent.architecture;- if (!architecture || context.intent.category !== "architecture")- return [];- const evidence = collectArchitectureEvidence(context.scene);- if (!evidence)- return [];- return [- ...storeyFindings(context, architecture, evidence),- ...interiorModeFindings(context, architecture, evidence),- ...roofModeFindings(context, architecture, evidence),- ...domeFindings(context, architecture, evidence),- ...roofFindings(context, architecture, evidence),- ...endFindings(context, architecture, evidence),- ...envelopeFindings(context, architecture, evidence),- ...portalFindings(context, architecture, evidence),- ...scaleFindings(context, architecture, evidence)- ];+ return output;}-var PROFILE_RULE_ID = "ARCHITECTURE_PROFILE", EPSILON = 0.000001, ARCHITECTURE_REALISTIC_SCALE_BANDS, emptyBounds = () => ({- min: new THREE2.Vector3(Infinity, Infinity, Infinity),- max: new THREE2.Vector3(-Infinity, -Infinity, -Infinity)-}), expandBounds = (bounds, point) => {- bounds.min.min(point);- bounds.max.max(point);-}, boundsFinite = (bounds) => Number.isFinite(bounds.min.x), extent = (bounds, axis) => bounds.max[axis] - bounds.min[axis], hasRole = (part, role) => part.roles.includes(role), hasRolePrefix = (part, prefix) => part.roles.some((role) => role.startsWith(prefix)), ARCHITECTURE_QA_RULE, ARCHITECTURE_ADVISORY_QA_RULE, ARCHITECTURE_QA_RULES;-var init_architecture = __esm(() => {- init_contracts();- init_architecture_repairs();- init_registry();- ARCHITECTURE_REALISTIC_SCALE_BANDS = Object.freeze({- doorWidth: Object.freeze({ minimum: 0.75, maximum: 2.5, unit: "m" }),- doorHeight: Object.freeze({ minimum: 1.8, maximum: 3.2, unit: "m" }),- ceilingHeight: Object.freeze({ minimum: 2.1, maximum: 6, unit: "m" }),- stairRiser: Object.freeze({ minimum: 0.1, maximum: 0.25, unit: "m" }),- stairTread: Object.freeze({ minimum: 0.2, maximum: 0.45, unit: "m" }),- wallThickness: Object.freeze({ minimum: 0.05, maximum: 0.6, unit: "m" }),- footprint: Object.freeze({ minimum: 1.5, maximum: 200, unit: "m" })- });- ARCHITECTURE_QA_RULE = {- id: PROFILE_RULE_ID,- profile: "architecture.default",- scope: { kind: "category", category: "architecture" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "e5ad1245240f1244c592849df2977c74d26e535dffebc9ad5a2adf6db743d573"),- defaultMode: "enforce",- evaluate: (context) => evaluateArchitectureQa(context).filter((finding) => finding.disposition === "block")- };- ARCHITECTURE_ADVISORY_QA_RULE = {- id: "ARCHITECTURE_ADVISORY_PROFILE",- profile: "architecture.advisory",- scope: { kind: "category", category: "architecture" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: (context) => evaluateArchitectureQa(context).filter((finding) => finding.disposition !== "block")- };- ARCHITECTURE_QA_RULES = [- ARCHITECTURE_QA_RULE,- ARCHITECTURE_ADVISORY_QA_RULE- ];-});--// src/character.ts-import * as THREE3 from "three";-function validRole(value) {- return typeof value === "string" && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value);+function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {+ const vectors = points.map((p) => new THREE4.Vector3(p[0], p[1], p[2]));+ const curve = new THREE4.CatmullRomCurve3(vectors, closed);+ return new THREE4.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);}-function validateUnitVector(value, path, issues) {- if (!isFiniteTuple2(value, 3)) {- issues.push({ code: "INVALID_AXIS", path, message: `${path} must be three finite numbers.` });- return false;- }- const magnitude = Math.hypot(...value);- if (Math.abs(magnitude - 1) > 0.000001) {- issues.push({ code: "NON_UNIT_AXIS", path, message: `${path} must be normalized.` });- return false;+function normalizeSurfaceNormals(geo) {+ const normal = geo.getAttribute("normal");+ if (!normal)+ return geo;+ let repaired = false;+ for (let i = 0;i < normal.count; i++) {+ const x = normal.getX(i);+ const y = normal.getY(i);+ const z = normal.getZ(i);+ const len = Math.hypot(x, y, z);+ if (!Number.isFinite(len) || len < 0.000000000001) {+ normal.setXYZ(i, 0, 1, 0);+ repaired = true;+ continue;+ }+ if (Math.abs(len - 1) <= 0.000001)+ continue;+ normal.setXYZ(i, x / len, y / len, z / len);+ repaired = true;}- return true;+ if (repaired)+ normal.needsUpdate = true;+ return geo;}-function cloneCharacterJointDescriptorV1(descriptor) {- return {- schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,- role: descriptor.role,- aliases: [...descriptor.aliases],- ...descriptor.parentRole ? { parentRole: descriptor.parentRole } : {},- side: descriptor.side,- rest: {- translation: tuple3(descriptor.rest.translation),- rotation: tuple4(descriptor.rest.rotation),- scale: tuple3(descriptor.rest.scale)- },- localForwardAxis: tuple3(descriptor.localForwardAxis),- localBendAxis: tuple3(descriptor.localBendAxis),- endEffector: descriptor.endEffector,- contact: descriptor.contact- };+function lathe(profile, segments = 12) {+ const points2d = profile.map((p) => new THREE4.Vector2(p[0], p[1]));+ return normalizeSurfaceNormals(new THREE4.LatheGeometry(points2d, segments));}-function validateCharacterJointDescriptorV1(value) {- const issues = [];- if (!isRecord4(value)) {- return {- valid: false,- issues: [- { code: "EXPECTED_OBJECT", path: "", message: "Joint descriptor must be an object." }- ]- };+function revolveGeo(profile, options = {}) {+ const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;+ const points2d = profile.map((p) => new THREE4.Vector2(p[0], p[1]));+ const geo = normalizeSurfaceNormals(new THREE4.LatheGeometry(points2d, segments, 0, angle));+ const n = new THREE4.Vector3(axis[0], axis[1], axis[2]);+ if (n.lengthSq() < 0.000000000001) {+ throw new Error(`revolveGeo: axis must be a non-zero vector (got [${axis.join(",")}]).`);}- if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {- issues.push({- code: "UNSUPPORTED_SCHEMA_VERSION",- path: "schemaVersion",- message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`- });+ n.normalize();+ if (n.x !== 0 || n.y !== 1 || n.z !== 0) {+ const q = new THREE4.Quaternion().setFromUnitVectors(new THREE4.Vector3(0, 1, 0), n);+ geo.applyQuaternion(q);}- if (!validRole(value.role)) {- issues.push({- code: "INVALID_ROLE",- path: "role",- message: "role must be a stable lowercase ID."- });+ return geo;+}+function pipeAlongPath(points, radius, options = {}) {+ const { bendRadius = 0, closed = false, tubularSegments = 32, radialSegments = 8 } = options;+ if (points.length < 2) {+ throw new Error(`pipeAlongPath: need at least 2 points (got ${points.length}).`);}- if (!Array.isArray(value.aliases) || value.aliases.some((alias) => typeof alias !== "string" || alias.trim().length === 0)) {- issues.push({- code: "INVALID_ALIASES",- path: "aliases",- message: "aliases must be non-empty strings."- });- } else if (new Set(value.aliases).size !== value.aliases.length) {- issues.push({ code: "DUPLICATE_ALIAS", path: "aliases", message: "aliases must be unique." });+ let pathPoints = points;+ if (bendRadius > 0 && points.length >= 3) {+ const smoothed = [];+ smoothed.push(points[0]);+ for (let i = 1;i < points.length - 1; i++) {+ const prev = new THREE4.Vector3(...points[i - 1]);+ const cur = new THREE4.Vector3(...points[i]);+ const next = new THREE4.Vector3(...points[i + 1]);+ const inDir = cur.clone().sub(prev);+ const outDir = next.clone().sub(cur);+ const inLen = inDir.length();+ const outLen = outDir.length();+ const inOffset = Math.min(bendRadius, inLen / 2);+ const outOffset = Math.min(bendRadius, outLen / 2);+ const before = cur.clone().sub(inDir.clone().normalize().multiplyScalar(inOffset));+ const after = cur.clone().add(outDir.clone().normalize().multiplyScalar(outOffset));+ smoothed.push([before.x, before.y, before.z]);+ smoothed.push([after.x, after.y, after.z]);+ }+ smoothed.push(points[points.length - 1]);+ pathPoints = smoothed;}- if (value.parentRole !== undefined && !validRole(value.parentRole)) {- issues.push({- code: "INVALID_PARENT_ROLE",- path: "parentRole",- message: "parentRole must be a stable lowercase ID."- });- }- if (!CHARACTER_JOINT_SIDES.includes(value.side)) {- issues.push({- code: "INVALID_SIDE",- path: "side",- message: "side must be left, right, or center."- });- }- if (!isRecord4(value.rest)) {- issues.push({ code: "INVALID_REST", path: "rest", message: "rest transform is required." });+ const vectors = pathPoints.map((p) => new THREE4.Vector3(p[0], p[1], p[2]));+ const curve = new THREE4.CatmullRomCurve3(vectors, closed);+ return new THREE4.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);+}+function bezierCurve(controlPoints, samples = 32) {+ const vecs = controlPoints.map((p) => new THREE4.Vector3(p[0], p[1], p[2]));+ let curve;+ if (vecs.length === 3) {+ curve = new THREE4.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);+ } else if (vecs.length === 4) {+ curve = new THREE4.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);} else {- if (!isFiniteTuple2(value.rest.translation, 3)) {- issues.push({- code: "INVALID_REST_TRANSLATION",- path: "rest.translation",- message: "rest.translation must be three finite meters."- });- }- if (!isFiniteTuple2(value.rest.rotation, 4)) {- issues.push({- code: "INVALID_REST_ROTATION",- path: "rest.rotation",- message: "rest.rotation must be a finite quaternion."- });- } else if (Math.abs(Math.hypot(...value.rest.rotation) - 1) > 0.000001) {- issues.push({- code: "NON_UNIT_REST_ROTATION",- path: "rest.rotation",- message: "rest.rotation must be normalized."- });- }- if (!isFiniteTuple2(value.rest.scale, 3) || value.rest.scale.some((component) => component <= 0)) {- issues.push({- code: "INVALID_REST_SCALE",- path: "rest.scale",- message: "rest.scale must contain three positive finite values."- });- }+ throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);}- const forwardAxis = value.localForwardAxis;- const bendAxis = value.localBendAxis;- const forwardValid = validateUnitVector(forwardAxis, "localForwardAxis", issues);- const bendValid = validateUnitVector(bendAxis, "localBendAxis", issues);- if (forwardValid && bendValid) {- const dot3 = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];- if (Math.abs(dot3) > 0.000001) {- issues.push({- code: "NON_ORTHOGONAL_AXES",- path: "localBendAxis",- message: "local forward and bend axes must be orthogonal."- });+ return curve.getPoints(samples).map((v) => [v.x, v.y, v.z]);+}+var init_ops = __esm(() => {+ init_primitives();+});++// src/geometry.ts+import * as THREE5 from "three";+function finiteArray(values, label, length) {+ const result = Array.from(values);+ if (length !== undefined && result.length !== length)+ throw new Error(`${label}: expected ${length} values, got ${result.length}`);+ if (!result.every((n) => Number.isFinite(Math.fround(n))))+ throw new Error(`${label}: all values must be finite Float32 values`);+ return result;+}+function meshGeo(data) {+ const positions = finiteArray(data.positions, "meshGeo positions");+ if (positions.length < 9 || positions.length % 3)+ throw new Error("meshGeo positions: need at least three xyz vertices");+ const count = positions.length / 3;+ const geometry = new THREE5.BufferGeometry;+ geometry.setAttribute("position", new THREE5.Float32BufferAttribute(positions, 3));+ if (data.indices) {+ const indices = Array.from(data.indices);+ if (!indices.length || indices.length % 3)+ throw new Error("meshGeo indices: need complete triangles");+ if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))+ throw new Error("meshGeo index out of bounds or not an integer");+ geometry.setIndex(indices);+ } else if (count % 3)+ throw new Error("meshGeo: non-indexed positions must form complete triangles");+ if (data.normals) {+ const normals = finiteArray(data.normals, "meshGeo normals", count * 3);+ geometry.setAttribute("normal", new THREE5.Float32BufferAttribute(normals, 3));+ for (let i = 0;i < count; i++)+ if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)+ throw new Error("meshGeo normals: zero-length normal");+ geometry.normalizeNormals();+ } else+ geometry.computeVertexNormals();+ if (data.uvs)+ geometry.setAttribute("uv", new THREE5.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));+ if (data.tangents) {+ const tangents = finiteArray(data.tangents, "meshGeo tangents", count * 4);+ for (let i = 0;i < count; i++) {+ if (Math.abs(Math.hypot(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]) - 1) > 0.0001 || Math.abs(tangents[i * 4 + 3]) !== 1)+ throw new Error("meshGeo tangents: expected unit xyz and handedness +1 or -1");}+ geometry.setAttribute("tangent", new THREE5.Float32BufferAttribute(tangents, 4));}- if (typeof value.endEffector !== "boolean") {- issues.push({- code: "INVALID_END_EFFECTOR",- path: "endEffector",- message: "endEffector must be boolean."- });- }- if (typeof value.contact !== "boolean") {- issues.push({ code: "INVALID_CONTACT", path: "contact", message: "contact must be boolean." });- }- if (issues.length > 0)- return { valid: false, issues };- return {- valid: true,- value: cloneCharacterJointDescriptorV1(value),- issues- };+ geometry.computeBoundingBox();+ geometry.computeBoundingSphere();+ return geometry;}-function createCharacterJointDescriptorV1(input) {- const descriptor = {- schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,- role: input.role,- aliases: [...input.aliases ?? []],- ...input.parentRole ? { parentRole: input.parentRole } : {},- side: input.side ?? "center",- rest: {- translation: tuple3(input.rest?.translation ?? [0, 0, 0]),- rotation: tuple4(input.rest?.rotation ?? IDENTITY_QUATERNION),- scale: tuple3(input.rest?.scale ?? UNIT_SCALE)- },- localForwardAxis: tuple3(input.localForwardAxis ?? FORWARD_AXIS),- localBendAxis: tuple3(input.localBendAxis ?? BEND_AXIS),- endEffector: input.endEffector ?? false,- contact: input.contact ?? false+function geometryDiagnostics(geometry, tolerance = 0.000001) {+ if (!Number.isFinite(tolerance) || tolerance <= 0)+ throw new Error("geometryDiagnostics tolerance must be positive");+ const p = geometry.getAttribute("position");+ if (p?.itemSize !== 3)+ throw new Error("geometryDiagnostics requires xyz positions");+ const result = {+ vertices: p.count,+ triangles: 0,+ boundaryEdges: 0,+ nonManifoldEdges: 0,+ orientationConflicts: 0,+ degenerateTriangles: 0,+ invalidIndices: 0,+ nonFiniteVertices: 0};- const validation = validateCharacterJointDescriptorV1(descriptor);- if (!validation.valid || !validation.value) {- throw new TypeError(`Invalid CharacterJointDescriptorV1: ${validation.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`);- }- return validation.value;-}-function validateCharacterRigGraphV1(value) {- const issues = [];- if (!isRecord4(value)) {- return {- valid: false,- issues: [{ code: "EXPECTED_OBJECT", path: "", message: "Rig graph must be an object." }]- };- }- if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {- issues.push({- code: "UNSUPPORTED_SCHEMA_VERSION",- path: "schemaVersion",- message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`- });- }- if (!CHARACTER_BODY_PLANS2.includes(value.bodyPlan)) {- issues.push({- code: "INVALID_BODY_PLAN",- path: "bodyPlan",- message: "bodyPlan is unsupported."- });- }- if (!Array.isArray(value.joints) || value.joints.length === 0) {- issues.push({ code: "INVALID_JOINTS", path: "joints", message: "joints must not be empty." });- }- const joints = [];- if (Array.isArray(value.joints)) {- value.joints.forEach((joint, index) => {- const result = validateCharacterJointDescriptorV1(joint);- if (result.value)- joints.push(result.value);- for (const issue of result.issues) {- issues.push({ ...issue, path: `joints[${index}]${issue.path ? `.${issue.path}` : ""}` });- }- });+ const ids = [];+ const points = new Map;+ for (let i = 0;i < p.count; i++) {+ const xyz = [p.getX(i), p.getY(i), p.getZ(i)];+ if (!xyz.every(Number.isFinite))+ result.nonFiniteVertices++;+ const key = xyz.map((x) => Math.round(x / tolerance)).join(",");+ if (!points.has(key))+ points.set(key, points.size);+ ids.push(points.get(key));}- const byRole = new Map;- const aliasOwners = new Map;- joints.forEach((joint, index) => {- const prior = byRole.get(joint.role);- if (prior !== undefined) {- issues.push({- code: "DUPLICATE_JOINT_ROLE",- path: `joints[${index}].role`,- message: `role ${joint.role} duplicates joints[${prior}].role.`- });- } else- byRole.set(joint.role, index);- for (const alias of joint.aliases) {- const owner = aliasOwners.get(alias);- if (owner && owner !== joint.role) {- issues.push({- code: "AMBIGUOUS_JOINT_ALIAS",- path: `joints[${index}].aliases`,- message: `alias ${alias} is already owned by ${owner}.`- });- } else- aliasOwners.set(alias, joint.role);+ const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);+ const edges = new Map;+ const a = new THREE5.Vector3, b = new THREE5.Vector3, c = new THREE5.Vector3;+ for (let i = 0;i < indices.length; i += 3) {+ result.triangles++;+ const triangle = indices.slice(i, i + 3);+ if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {+ result.invalidIndices++;+ continue;}- });- joints.forEach((joint, index) => {- if (joint.parentRole && !byRole.has(joint.parentRole)) {- issues.push({- code: "UNKNOWN_PARENT_ROLE",- path: `joints[${index}].parentRole`,- message: `parentRole ${joint.parentRole} is not declared.`- });+ const [ia, ib, ic] = triangle;+ a.fromBufferAttribute(p, ia);+ b.fromBufferAttribute(p, ib);+ c.fromBufferAttribute(p, ic);+ if (b.sub(a).cross(c.sub(a)).lengthSq() <= tolerance ** 4)+ result.degenerateTriangles++;+ for (const [start, end] of [+ [ia, ib],+ [ib, ic],+ [ic, ia]+ ]) {+ const u = ids[start], v = ids[end];+ if (u === v)+ continue;+ const key = u < v ? `${u}:${v}` : `${v}:${u}`;+ const edge = edges.get(key) ?? { count: 0, direction: 0 };+ edge.count++;+ edge.direction += u < v ? 1 : -1;+ edges.set(key, edge);}- const seen = new Set([joint.role]);- let cursor = joint.parentRole;- while (cursor) {- if (seen.has(cursor)) {- issues.push({- code: "JOINT_PARENT_CYCLE",- path: `joints[${index}].parentRole`,- message: `parent chain for ${joint.role} contains a cycle at ${cursor}.`- });- break;- }- seen.add(cursor);- const parentIndex = byRole.get(cursor);- cursor = parentIndex === undefined ? undefined : joints[parentIndex]?.parentRole;+ }+ for (const edge of edges.values()) {+ if (edge.count === 1)+ result.boundaryEdges++;+ else if (edge.count > 2)+ result.nonManifoldEdges++;+ else if (edge.direction !== 0)+ result.orientationConflicts++;+ }+ return result;+}+function parametricSurface(sample, options = {}) {+ const {+ u = [0, 1],+ v = [0, 1],+ uSegments: nu = 24,+ vSegments: nv = 24,+ periodicU = false,+ periodicV = false,+ orientation = "uv"+ } = options;+ for (const [name, n] of [+ ["uSegments", nu],+ ["vSegments", nv]+ ])+ if (!Number.isSafeInteger(n) || n < 1)+ throw new Error(`parametricSurface ${name} must be a positive integer`);+ for (const [name, range] of [+ ["u", u],+ ["v", v]+ ])+ if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1])+ throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);+ if (orientation !== "uv" && orientation !== "vu")+ throw new Error("parametricSurface orientation must be uv or vu");+ const positions = [], uvs = [], indices = [];+ for (let j = 0;j <= nv; j++)+ for (let i = 0;i <= nu; i++) {+ const point = sample(u[0] + (u[1] - u[0]) * i / nu, v[0] + (v[1] - v[0]) * j / nv);+ if (point.length !== 3 || !point.every(Number.isFinite))+ throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);+ positions.push(...point);+ uvs.push(i / nu, j / nv);}- });- if (issues.length > 0)- return { valid: false, issues };- return {- valid: true,- value: {- schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,- bodyPlan: value.bodyPlan,- joints: joints.map(cloneCharacterJointDescriptorV1)- },- issues+ const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);+ const find = (i) => {+ while (groups[i] !== i)+ i = groups[i];+ return i;};-}-function createCharacterRigGraphV1(input) {- const graph = {- schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,- bodyPlan: input.bodyPlan,- joints: input.joints.map((joint) => ("schemaVersion" in joint) ? cloneCharacterJointDescriptorV1(joint) : createCharacterJointDescriptorV1(joint))+ const join = (a, b, label) => {+ const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);+ const scale = Math.max(1, ...pa.map(Math.abs), ...pb.map(Math.abs));+ if (Math.hypot(...pa.map((x, k) => x - pb[k])) > scale * 0.000001)+ throw new Error(`parametricSurface ${label}: endpoint positions do not match`);+ groups[find(b)] = find(a);+ for (let k = 0;k < 3; k++)+ positions[b * 3 + k] = positions[a * 3 + k];};- const result = validateCharacterRigGraphV1(graph);- if (!result.valid || !result.value) {- throw new TypeError(`Invalid CharacterRigGraphV1: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`);+ if (periodicU)+ for (let j = 0;j <= nv; j++)+ join(j * (nu + 1), j * (nu + 1) + nu, "periodicU");+ if (periodicV)+ for (let i = 0;i <= nu; i++)+ join(i, nv * (nu + 1) + i, "periodicV");+ for (let j = 0;j < nv; j++)+ for (let i = 0;i < nu; i++) {+ const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;+ indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);+ }+ const out = meshGeo({ positions, indices, uvs });+ if (periodicU || periodicV) {+ const normal = out.getAttribute("normal");+ const sums = new Map;+ for (let i = 0;i < normal.count; i++) {+ const id = find(i);+ const sum = sums.get(id) ?? new THREE5.Vector3;+ sum.add(new THREE5.Vector3().fromBufferAttribute(normal, i));+ sums.set(id, sum);+ }+ for (let i = 0;i < normal.count; i++) {+ const n = sums.get(find(i)).clone().normalize();+ normal.setXYZ(i, n.x, n.y, n.z);+ }}- return result.value;-}-function readCharacterRigGraphV1(target) {- const value = target.userData?.[KILN_CHARACTER_RIG_EXTRAS_KEY];- const result = validateCharacterRigGraphV1(value);- return result.valid ? result.value : undefined;-}-function axisQuaternion(from, to) {- const value = new THREE3.Quaternion().setFromUnitVectors(new THREE3.Vector3(...from), new THREE3.Vector3(...to));- return [value.x, value.y, value.z, value.w];-}-function stampCharacterJointDescriptorV1(target, input) {- const descriptor = createCharacterJointDescriptorV1(input);- const frames = [- { id: "rest", translation: [0, 0, 0], rotation: IDENTITY_QUATERNION },- {- id: "forward",- translation: [0, 0, 0],- rotation: axisQuaternion(FORWARD_AXIS, descriptor.localForwardAxis)- },- {- id: "bend",- translation: [0, 0, 0],- rotation: axisQuaternion([0, 1, 0], descriptor.localBendAxis)- },- ...descriptor.endEffector ? [- {- id: "end-effector",- translation: [0, 0, 0],- rotation: IDENTITY_QUATERNION- }- ] : [],- ...descriptor.contact ? [- {- id: "contact",- translation: [0, 0, 0],- rotation: IDENTITY_QUATERNION- }- ] : []- ];- stampSemanticMetadataV1(target, {- roles: [- "skeleton.joint",- `joint.${descriptor.role}`,- `joint.side.${descriptor.side}`,- ...descriptor.aliases.map((alias) => `joint.alias.${alias}`),- ...descriptor.endEffector ? ["joint.end-effector"] : [],- ...descriptor.contact ? ["contact.ground"] : []- ],- relationships: descriptor.parentRole ? [{ kind: "parent-joint", target: `joint.${descriptor.parentRole}`, targetType: "role" }] : [],- frames,- sockets: [- ...descriptor.endEffector ? [- {- id: "end-effector",- type: "character.attachment",- frame: "end-effector",- compatibleTypes: ["character.held-item"]- }- ] : [],- ...descriptor.contact ? [- {- id: "ground-contact",- type: "character.contact",- frame: "contact",- compatibleTypes: ["world.ground"]- }- ] : []- ]- });- target.userData[KILN_CHARACTER_JOINT_EXTRAS_KEY] = cloneCharacterJointDescriptorV1(descriptor);- return target;+ return out;}-function readCharacterJointDescriptorV1(target) {- const value = target.userData?.[KILN_CHARACTER_JOINT_EXTRAS_KEY];- const result = validateCharacterJointDescriptorV1(value);- return result.valid ? result.value : undefined;+function creaseNormals(geometry, options = {}) {+ const angle = options.angle ?? 60;+ if (!Number.isFinite(angle) || angle < 0 || angle > 180)+ throw new Error("creaseNormals angle must be between 0 and 180 degrees");+ const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();+ const position = out.getAttribute("position");+ if (position?.itemSize !== 3 || position.count % 3 !== 0)+ throw new Error("creaseNormals requires complete xyz triangles");+ out.computeBoundingBox();+ const diagonal = out.boundingBox.getSize(new THREE5.Vector3).length();+ const tolerance = options.tolerance ?? Math.max(diagonal * 0.00000001, 0.000000000001);+ if (!Number.isFinite(tolerance) || tolerance <= 0)+ throw new Error("creaseNormals tolerance must be positive and finite");+ const adjacent = new Map;+ const keys = [];+ const faces = [];+ for (let i = 0;i < position.count; i += 3) {+ const a = new THREE5.Vector3().fromBufferAttribute(position, i);+ const b = new THREE5.Vector3().fromBufferAttribute(position, i + 1);+ const c = new THREE5.Vector3().fromBufferAttribute(position, i + 2);+ const face = b.sub(a).cross(c.sub(a)).normalize();+ faces.push(face);+ for (let j = i;j < i + 3; j++) {+ const point = new THREE5.Vector3().fromBufferAttribute(position, j);+ if (![point.x, point.y, point.z].every(Number.isFinite))+ throw new Error("creaseNormals positions must be finite");+ const key = point.toArray().map((n) => Math.round(n / tolerance)).join(",");+ keys.push(key);+ const neighbors = adjacent.get(key) ?? new Set;+ neighbors.add(i / 3);+ adjacent.set(key, neighbors);+ }+ }+ const normals = new Float32Array(position.count * 3);+ const threshold = Math.cos(THREE5.MathUtils.degToRad(angle));+ for (let i = 0;i < position.count; i++) {+ const face = faces[Math.floor(i / 3)], sum = new THREE5.Vector3;+ for (const other of adjacent.get(keys[i]))+ if (face.dot(faces[other]) >= threshold - 0.000000000001)+ sum.add(faces[other]);+ sum.normalize().toArray(normals, i * 3);+ }+ out.setAttribute("normal", new THREE5.BufferAttribute(normals, 3));+ out.deleteAttribute("tangent");+ out.computeBoundingSphere();+ return out;}-function characterJointNodeName(chainName, role) {- const safeChain = chainName.trim().replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "");- const safeRole = role.replace(/[^A-Za-z0-9]+/g, "_");- if (!safeChain)- throw new TypeError("createJointChain chainName must contain a letter or number.");- return `Joint_${safeChain}_${safeRole}`;+var init_geometry = () => {};++// src/deform.ts+import * as THREE6 from "three";+function geometryFrameMatrix(frame = {}) {+ const origin = frame.origin ?? [0, 0, 0], rotation = frame.rotation ?? [0, 0, 0];+ if (origin.length !== 3 || rotation.length !== 3 || ![...origin, ...rotation].every(Number.isFinite))+ throw new Error("geometry frame requires finite xyz origin and rotation");+ return new THREE6.Matrix4().compose(new THREE6.Vector3(...origin), new THREE6.Quaternion().setFromEuler(new THREE6.Euler(...rotation.map(THREE6.MathUtils.degToRad), "XYZ")), new THREE6.Vector3(1, 1, 1));}-function createJointChain(chainName, segments, options = {}) {- if (segments.length === 0)- throw new TypeError("createJointChain requires at least one segment.");- const seen = new Set;- const nodes = [];- const descriptors = [];- const byRole = new Map;- let parent = options.parent;- let parentRole = options.parentRole;- for (const segment of segments) {- if (seen.has(segment.role))- throw new TypeError(`Duplicate joint-chain role: ${segment.role}.`);- seen.add(segment.role);- const descriptor = createCharacterJointDescriptorV1({- role: segment.role,- aliases: segment.aliases,- ...parentRole ? { parentRole } : {},- side: segment.side,- rest: {- translation: segment.offset,- rotation: segment.restRotation,- scale: segment.restScale- },- localForwardAxis: segment.localForwardAxis,- localBendAxis: segment.localBendAxis,- endEffector: segment.endEffector,- contact: segment.contact- });- const node = new THREE3.Object3D;- node.name = characterJointNodeName(chainName, segment.role);- node.position.fromArray(descriptor.rest.translation);- node.quaternion.fromArray(descriptor.rest.rotation);- node.scale.fromArray(descriptor.rest.scale);- stampCharacterJointDescriptorV1(node, descriptor);- if (parent)- parent.add(node);- parent = node;- parentRole = descriptor.role;- nodes.push(node);- descriptors.push(descriptor);- byRole.set(descriptor.role, node);+function deform(geometry, options, map) {+ const source = geometry.getAttribute("position");+ if (source?.itemSize !== 3 || source.count === 0)+ throw new Error("deformation requires nonempty xyz positions");+ const matrix = geometryFrameMatrix(options.frame), inverse = matrix.clone().invert();+ const points = Array.from({ length: source.count }, (_, i) => new THREE6.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));+ if (points.some((p) => ![p.x, p.y, p.z].every(Number.isFinite)))+ throw new Error("deformation positions must be finite");+ let low = Infinity, high = -Infinity;+ for (const point of points) {+ low = Math.min(low, point.y);+ high = Math.max(high, point.y);}- return {- root: nodes[0],- end: nodes[nodes.length - 1],- nodes,- byRole,- descriptors- };+ if (options.interval) {+ if (options.interval.length !== 2 || !options.interval.every(Number.isFinite) || options.interval[1] <= options.interval[0])+ throw new Error("deformation interval must be finite and increasing");+ [low, high] = options.interval;+ }+ const length = high - low;+ const out = geometry.clone();+ const position = out.getAttribute("position");+ for (let i = 0;i < points.length; i++) {+ const point = points[i];+ const epsilon = Math.max(1, Math.abs(low), Math.abs(high)) * 0.0000001;+ if (point.y < low - epsilon || point.y > high + epsilon)+ continue;+ const t = length > epsilon ? THREE6.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;+ const weight = options.falloff?.(t) ?? 1;+ if (!Number.isFinite(weight) || weight < 0 || weight > 1)+ throw new Error("deformation falloff must return a finite weight between 0 and 1");+ const mapped = map(point.clone(), t, low, length);+ if (![mapped.x, mapped.y, mapped.z].every(Number.isFinite))+ throw new Error("deformation callback must return finite coordinates");+ point.lerp(mapped, weight).applyMatrix4(matrix);+ if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))+ throw new Error("deformation output must fit finite Float32 coordinates");+ position.setXYZ(i, point.x, point.y, point.z);+ }+ position.needsUpdate = true;+ out.deleteAttribute("tangent");+ out.computeVertexNormals();+ out.computeBoundingBox();+ out.computeBoundingSphere();+ return out;}-function collectCharacterJointNodes(root) {- const joints = [];- const visit = (node, parentPath, siblingIndex) => {- const segment = `${node.name.trim() || node.type || "Object3D"}[${siblingIndex}]`;- const nodePath = parentPath ? `${parentPath}/${segment}` : segment;- const descriptor = readCharacterJointDescriptorV1(node);- if (descriptor)- joints.push({ node, nodePath, descriptor });- node.children.forEach((child, index) => {- visit(child, nodePath, index);- });- };- visit(root, "", 0);- return joints;+function twist(geometry, options) {+ if (!Number.isFinite(options.angle))+ throw new Error("twist angle must be finite degrees");+ return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE6.Vector3(0, 1, 0), THREE6.MathUtils.degToRad(options.angle) * t));}-var KILN_CHARACTER_JOINT_EXTRAS_KEY = "kilnCharacterJoint", KILN_CHARACTER_RIG_EXTRAS_KEY = "kilnCharacterRig", KILN_CHARACTER_JOINT_SCHEMA_VERSION = 1, CHARACTER_BODY_PLANS2, CHARACTER_JOINT_SIDES, IDENTITY_QUATERNION, UNIT_SCALE, FORWARD_AXIS, BEND_AXIS, isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), isFiniteTuple2 = (value, length2) => Array.isArray(value) && value.length === length2 && value.every((component) => typeof component === "number" && Number.isFinite(component)), tuple3 = (value) => [value[0], value[1], value[2]], tuple4 = (value) => [- value[0],- value[1],- value[2],- value[3]-], presetJoint = (role, parentRole, translation, options = {}) => createCharacterJointDescriptorV1({- role,- ...parentRole ? { parentRole } : {},- ...options,- rest: { translation }-}), BIPED_RIG_PRESET_V1, QUADRUPED_RIG_PRESET_V1;-var init_character = __esm(() => {- init_contracts();- CHARACTER_BODY_PLANS2 = [- "biped",- "quadruped",- "avian",- "serpentine",- "multi-limb",- "wheeled",- "custom"- ];- CHARACTER_JOINT_SIDES = ["left", "right", "center"];- IDENTITY_QUATERNION = [0, 0, 0, 1];- UNIT_SCALE = [1, 1, 1];- FORWARD_AXIS = [1, 0, 0];- BEND_AXIS = [0, 0, 1];- BIPED_RIG_PRESET_V1 = createCharacterRigGraphV1({- bodyPlan: "biped",- joints: [- presetJoint("hips", undefined, [0, 1, 0], { aliases: ["pelvis"] }),- presetJoint("spine", "hips", [0, 0.45, 0], { aliases: ["torso"] }),- presetJoint("head", "spine", [0, 0.55, 0]),- presetJoint("shoulder.left", "spine", [0, 0.3, -0.25], { side: "left" }),- presetJoint("elbow.left", "shoulder.left", [0, -0.35, 0], { side: "left" }),- presetJoint("wrist.left", "elbow.left", [0, -0.35, 0], {- side: "left",- aliases: ["hand.left", "grip.left"],- endEffector: true- }),- presetJoint("shoulder.right", "spine", [0, 0.3, 0.25], { side: "right" }),- presetJoint("elbow.right", "shoulder.right", [0, -0.35, 0], { side: "right" }),- presetJoint("wrist.right", "elbow.right", [0, -0.35, 0], {- side: "right",- aliases: ["hand.right", "grip.right"],- endEffector: true- }),- presetJoint("hip.left", "hips", [0, -0.1, -0.14], { side: "left" }),- presetJoint("knee.left", "hip.left", [0, -0.45, 0], { side: "left" }),- presetJoint("ankle.left", "knee.left", [0, -0.45, 0], {- side: "left",- aliases: ["foot.left"],- endEffector: true,- contact: true- }),- presetJoint("hip.right", "hips", [0, -0.1, 0.14], { side: "right" }),- presetJoint("knee.right", "hip.right", [0, -0.45, 0], { side: "right" }),- presetJoint("ankle.right", "knee.right", [0, -0.45, 0], {- side: "right",- aliases: ["foot.right"],- endEffector: true,- contact: true- })- ]- });- QUADRUPED_RIG_PRESET_V1 = createCharacterRigGraphV1({- bodyPlan: "quadruped",- joints: [- presetJoint("hips", undefined, [0, 0.8, 0], { aliases: ["pelvis"] }),- presetJoint("spine", "hips", [0.7, 0, 0]),- presetJoint("neck", "spine", [0.45, 0.1, 0]),- presetJoint("head", "neck", [0.3, 0, 0]),- presetJoint("shoulder.fore.left", "spine", [0.2, -0.1, -0.28], { side: "left" }),- presetJoint("elbow.fore.left", "shoulder.fore.left", [0, -0.4, 0], { side: "left" }),- presetJoint("paw.fore.left", "elbow.fore.left", [0, -0.3, 0], {- side: "left",- endEffector: true,- contact: true- }),- presetJoint("shoulder.fore.right", "spine", [0.2, -0.1, 0.28], { side: "right" }),- presetJoint("elbow.fore.right", "shoulder.fore.right", [0, -0.4, 0], { side: "right" }),- presetJoint("paw.fore.right", "elbow.fore.right", [0, -0.3, 0], {- side: "right",- endEffector: true,- contact: true- }),- presetJoint("hip.hind.left", "hips", [0, -0.1, -0.28], { side: "left" }),- presetJoint("knee.hind.left", "hip.hind.left", [0, -0.4, 0], { side: "left" }),- presetJoint("paw.hind.left", "knee.hind.left", [0, -0.3, 0], {- side: "left",- endEffector: true,- contact: true- }),- presetJoint("hip.hind.right", "hips", [0, -0.1, 0.28], { side: "right" }),- presetJoint("knee.hind.right", "hip.hind.right", [0, -0.4, 0], { side: "right" }),- presetJoint("paw.hind.right", "knee.hind.right", [0, -0.3, 0], {- side: "right",- endEffector: true,- contact: true- })- ]+function bend(geometry, options) {+ if (!Number.isFinite(options.angle))+ throw new Error("bend angle must be finite degrees");+ const angle = THREE6.MathUtils.degToRad(options.angle);+ return deform(geometry, options, (p, t, low, length) => {+ if (Math.abs(angle) < 0.0000000001 || length === 0)+ return p;+ const radius = length / angle, theta = angle * t;+ return new THREE6.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);});-});--// src/qa/character-repairs.ts-function characterRepairRecipe(code) {- return CHARACTER_REPAIR_RECIPES[code];}-function withCharacterRepair(finding) {- const found = characterRepairRecipe(finding.code);- if (!found)- return finding;- return {- ...finding,- repairText: finding.repairText ?? found.repairText,- viewHints: [...new Set([...finding.viewHints ?? [], ...found.viewHints])]- };+function taper(geometry, options) {+ const start = options.startScale ?? [1, 1], end = options.endScale;+ if (start.length !== 2 || end.length !== 2 || ![...start, ...end].every((n) => Number.isFinite(n) && n > 0))+ throw new Error("taper scales must be two finite positive values");+ return deform(geometry, options, (p, t) => p.set(p.x * THREE6.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE6.MathUtils.lerp(start[1], end[1], t)));}-var skeletonViews, motionViews, recipe = (code, repairText, viewHints) => Object.freeze({ code, repairText, viewHints: Object.freeze([...viewHints]) }), CHARACTER_REPAIR_RECIPES;-var init_character_repairs = __esm(() => {- skeletonViews = Object.freeze(["character.skeleton.front", "character.skeleton.right"]);- motionViews = Object.freeze(["character.motion-strip.front", "character.motion-strip.right"]);- CHARACTER_REPAIR_RECIPES = Object.freeze({- CHAR_DUPLICATE_ANIMATED_NODE_NAME: recipe("CHAR_DUPLICATE_ANIMATED_NODE_NAME", "Rename only the reported duplicate Joint_* pivot and update its animation-track target so every animated node name is unique.", skeletonViews),- CHAR_DUPLICATE_JOINT_ROLE: recipe("CHAR_DUPLICATE_JOINT_ROLE", "Give the reported joint its intended unique semantic role; do not remove or merge unrelated branches.", skeletonViews),- CHAR_PARENT_EDGE: recipe("CHAR_PARENT_EDGE", "Reparent only the reported joint directly under its declared parent role while preserving its asset-local rest pose.", skeletonViews),- CHAR_BIPED_REQUIRED_ROLE: recipe("CHAR_BIPED_REQUIRED_ROLE", "Add the reported missing biped joint role and declared parent edge without redesigning already-valid chains.", skeletonViews),- CHAR_QUADRUPED_REQUIRED_ROLE: recipe("CHAR_QUADRUPED_REQUIRED_ROLE", "Add the reported missing quadruped joint role and declared parent edge without changing the other three limb chains.", skeletonViews),- CHAR_CUSTOM_GRAPH_MISSING: recipe("CHAR_CUSTOM_GRAPH_MISSING", "Declare the requested custom rig graph before authoring animation; do not substitute biped assumptions.", skeletonViews),- CHAR_CUSTOM_REQUIRED_ROLE: recipe("CHAR_CUSTOM_REQUIRED_ROLE", "Add only the reported role from the trusted custom graph and attach it to its declared parent.", skeletonViews),- CHAR_HELD_ITEM_MISSING: recipe("CHAR_HELD_ITEM_MISSING", "Add the declared held item as its own node under the requested grip end effector.", skeletonViews),- CHAR_HELD_ITEM_ATTACHMENT: recipe("CHAR_HELD_ITEM_ATTACHMENT", "Reparent only the held-item node under the reported hand, wrist, or grip end effector; never attach it to a shoulder or elbow.", skeletonViews),- CHAR_HELD_ITEM_GRIP_BREAK: recipe("CHAR_HELD_ITEM_GRIP_BREAK", "Keep the reported held item under its declared grip end effector and remove only the item-local animation keys that change its grip distance.", motionViews),- CHAR_CONTACT_MISSING: recipe("CHAR_CONTACT_MISSING", "Tag the requested foot, paw, or terminal support as a ground contact without changing body plan.", ["character.skeleton.front", "generic.front.depth-contact"]),- CHAR_CONTACT_FLOATING: recipe("CHAR_CONTACT_FLOATING", "Move only the reported contact down to asset-local Y=0 while preserving its parent chain and lateral placement.", ["character.skeleton.front", "generic.front.depth-contact"]),- CHAR_CONTACT_BURIED: recipe("CHAR_CONTACT_BURIED", "Move only the reported contact up to asset-local Y=0 while preserving its parent chain and lateral placement.", ["character.skeleton.front", "generic.front.depth-contact"]),- CHAR_CLIP_MISSING: recipe("CHAR_CLIP_MISSING", "Author exactly the reported requested clip name using existing unique Joint_* targets.", motionViews),- CHAR_CLIP_DUPLICATE: recipe("CHAR_CLIP_DUPLICATE", "Keep one clip with the requested name and remove or correctly rename the duplicate; preserve requested clip names exactly.", motionViews),- CHAR_CLIP_UNEXPECTED: recipe("CHAR_CLIP_UNEXPECTED", "Remove the unrequested clip without changing any requested clip.", motionViews),- CHAR_CLIP_DURATION: recipe("CHAR_CLIP_DURATION", "Set the reported clip to one finite positive duration and keep all keys inside it.", motionViews),- CHAR_ANIMATION_NONFINITE: recipe("CHAR_ANIMATION_NONFINITE", "Replace only the reported non-finite key time or value with the intended finite value.", motionViews),- CHAR_KEY_TIME_ORDER: recipe("CHAR_KEY_TIME_ORDER", "Sort the reported track keys into strictly increasing unique times without changing their poses.", motionViews),- CHAR_KEY_OUT_OF_RANGE: recipe("CHAR_KEY_OUT_OF_RANGE", "Move only the reported key inside the inclusive [0, clip duration] interval.", motionViews),- CHAR_TRACK_VALUE_COUNT: recipe("CHAR_TRACK_VALUE_COUNT", "Provide exactly one complete value tuple for every reported key time.", motionViews),- CHAR_LOOP_ENDPOINT: recipe("CHAR_LOOP_ENDPOINT", "For the declared looping clip, make the reported track end pose equal its start pose; do not change one-shot clips.", motionViews),- CHAR_ROOT_MOTION_BACKWARD: recipe("CHAR_ROOT_MOTION_BACKWARD", "Reverse only the declared locomotion root translation so net travel is toward canonical +X.", motionViews),- CHAR_ROOT_MOTION_LATERAL: recipe("CHAR_ROOT_MOTION_LATERAL", "Rotate or rewrite only the declared locomotion root translation so +X travel dominates Z travel.", motionViews)+function displace(geometry, offset, options = {}) {+ return deform(geometry, options, (p, t) => {+ const delta = offset([p.x, p.y, p.z], t);+ if (delta.length !== 3 || !delta.every(Number.isFinite))+ throw new Error("displace callback must return three finite offsets");+ return p.add(new THREE6.Vector3(...delta));});-});--// src/qa/character.ts-import * as THREE4 from "three";-function isClipLike(value) {- if (typeof value !== "object" || value === null)- return false;- const clip = value;- return typeof clip.name === "string" && Array.isArray(clip.tracks);}-function collectNodes(root) {- const nodes = [];- const visit = (node, parentPath, siblingIndex) => {- const segment = `${node.name.trim() || node.type || "Object3D"}[${siblingIndex}]`;- const nodePath = parentPath ? `${parentPath}/${segment}` : segment;- nodes.push({ node, nodePath });- node.children.forEach((child, index) => {- visit(child, nodePath, index);- });- };- visit(root, "", 0);- return nodes;-}-function characterIntent(intent) {- return intent.character;-}-function block(intent, code, message, options) {- return withCharacterRepair({- code,- disposition: "block",- profile: intent.qaProfile,- message,- ...options- });-}-function targetName(trackName) {- const dot3 = trackName.lastIndexOf(".");- return dot3 > 0 ? trackName.slice(0, dot3) : undefined;-}-function propertyName(trackName) {- const dot3 = trackName.lastIndexOf(".");- return dot3 > 0 ? trackName.slice(dot3 + 1) : undefined;-}-function blockerKey(finding) {- return [- finding.code,- finding.affected?.nodePath ?? "",- finding.affected?.clip ?? "",- finding.affected?.track ?? "",- String(finding.measurement?.expected ?? "")- ].join("|");-}-function dedupeFindings(findings) {- const byKey = new Map;- for (const finding of findings)- byKey.set(blockerKey(finding), finding);- return [...byKey.values()].sort((a, b) => blockerKey(a).localeCompare(blockerKey(b)));-}-function duplicateNameFindings(intent, nodes, clips) {- const animatedTargets = new Set(clips.flatMap((clip) => clip.tracks.map((track) => targetName(track.name)).filter(Boolean)));- const byName = new Map;- for (const evidence of nodes) {- if (!evidence.node.name)- continue;- if (!evidence.node.name.startsWith("Joint_") && !animatedTargets.has(evidence.node.name))- continue;- const values = byName.get(evidence.node.name) ?? [];- values.push(evidence);- byName.set(evidence.node.name, values);- }- const findings = [];- for (const [name, matches] of [...byName.entries()].sort(([a], [b]) => a.localeCompare(b))) {- if (matches.length < 2)- continue;- const paths = matches.map((match) => match.nodePath).sort();- findings.push(block(intent, "CHAR_DUPLICATE_ANIMATED_NODE_NAME", `Animated node name ${JSON.stringify(name)} resolves to multiple exact paths: ${paths.join(", ")}.`, {- dimension: "exportIntegrity",- affected: { node: name, nodePath: paths[0] },- measurement: {- name: "animatedNodeNameCount",- actual: matches.length,- expected: 1- },- viewHints: ["character.skeleton.front", "character.skeleton.right"]- }));+var init_deform = () => {};++// src/sweep.ts+import * as THREE7 from "three";+function profilePoints(profile) {+ if (profile.length < 3 || profile.some((p) => p.length !== 2 || !p.every(Number.isFinite)))+ throw new Error("profile requires at least three finite xy points");+ const points = profile.map((p) => new THREE7.Vector2(...p));+ if (points[0].distanceTo(points[points.length - 1]) < 0.0000000001)+ points.pop();+ if (points.length < 3)+ throw new Error("profile requires three distinct points");+ const cross = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);+ for (let i = 0;i < points.length; i++) {+ const a = points[i], b = points[(i + 1) % points.length];+ if (a.distanceToSquared(b) < 0.00000000000000000001)+ throw new Error("profile has duplicate adjacent points");+ for (let j = i + 1;j < points.length; j++) {+ if (j === i + 1 || i === 0 && j === points.length - 1)+ continue;+ const c = points[j], d = points[(j + 1) % points.length];+ if (cross(a, b, c) * cross(a, b, d) <= 0 && cross(c, d, a) * cross(c, d, b) <= 0 && Math.max(Math.min(a.x, b.x), Math.min(c.x, d.x)) <= Math.min(Math.max(a.x, b.x), Math.max(c.x, d.x)) + 0.0000000001 && Math.max(Math.min(a.y, b.y), Math.min(c.y, d.y)) <= Math.min(Math.max(a.y, b.y), Math.max(c.y, d.y)) + 0.0000000001)+ throw new Error("profile self-intersects or touches itself");+ }}- return findings;+ const area = THREE7.ShapeUtils.area(points);+ if (Math.abs(area) < 0.000000000001)+ throw new Error("profile area must be nonzero");+ if (area < 0)+ points.splice(1, points.length - 1, ...points.slice(1).reverse());+ return points;}-function parentAndRoleFindings(intent, root) {- const joints = collectCharacterJointNodes(root);- const byRole = new Map;- for (const joint of joints) {- const values = byRole.get(joint.descriptor.role) ?? [];- values.push(joint);- byRole.set(joint.descriptor.role, values);- }- const findings = [];- for (const [role, matches] of [...byRole.entries()].sort(([a], [b]) => a.localeCompare(b))) {- if (matches.length < 2)- continue;- const paths = matches.map((match) => match.nodePath).sort();- findings.push(block(intent, "CHAR_DUPLICATE_JOINT_ROLE", `Joint role ${role} is declared at ${paths.join(", ")}.`, {- dimension: "categoryReadiness",- affected: { node: role, nodePath: paths[0] },- measurement: { name: "jointRoleCount", actual: matches.length, expected: 1 },- viewHints: ["character.skeleton.front", "character.skeleton.right"]- }));- }- for (const joint of joints) {- const expected = joint.descriptor.parentRole;- if (!expected)- continue;- const actualDescriptor = joint.node.parent ? readCharacterJointDescriptorV1(joint.node.parent) : undefined;- const actual = actualDescriptor?.role ?? joint.node.parent?.name ?? "(none)";- if (actualDescriptor?.role === expected)- continue;- findings.push(block(intent, "CHAR_PARENT_EDGE", `Broken joint edge ${expected} -> ${joint.descriptor.role}: actual direct parent is ${actual}.`, {- dimension: "categoryReadiness",- affected: { node: joint.node.name, nodePath: joint.nodePath },- measurement: { name: "parentRole", actual, expected },- viewHints: ["character.skeleton.front", "character.skeleton.right"]- }));+function buildLoft(rings, profiles, closed, cap) {+ const n = rings[0].length, positions = [], uvs = [], indices = [];+ const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE7.Vector3).multiplyScalar(1 / n));+ const lengths = [0];+ for (let i = 1;i < centers.length; i++)+ lengths.push(lengths[i - 1] + centers[i].distanceTo(centers[i - 1]));+ const total = lengths[lengths.length - 1];+ if (total < 0.0000000001)+ throw new Error("loft section centers must progress along a nonzero path");+ for (let i = 0;i < rings.length; i++) {+ const ring = rings[i], distance = [0];+ for (let j = 1;j <= n; j++)+ distance.push(distance[j - 1] + ring[j % n].distanceTo(ring[j - 1]));+ for (let j = 0;j <= n; j++) {+ positions.push(...ring[j % n].toArray());+ uvs.push(distance[j] / distance[n], lengths[i] / total);+ }}- return { findings, byRole };-}-function requiredGraphFindings(intent, graph, actualByRole, code) {- const findings = [];- for (const expected of graph.joints) {- const actual = actualByRole.get(expected.role)?.[0];- if (!actual) {- findings.push(block(intent, code, `Explicit ${graph.bodyPlan} articulation is missing joint role ${expected.role}.`, {- dimension: "categoryReadiness",- affected: { node: expected.role },- measurement: { name: "requiredJointRole", actual: false, expected: expected.role },- viewHints: ["character.skeleton.front", "character.skeleton.right"]- }));- continue;+ for (let i = 0;i < rings.length - 1; i++)+ for (let j = 0;j < n; j++) {+ const a = i * (n + 1) + j, b = a + 1, c = a + n + 1, d = c + 1;+ indices.push(a, c, b, b, c, d);}- if (expected.parentRole && actual.descriptor.parentRole !== expected.parentRole) {- findings.push(block(intent, "CHAR_PARENT_EDGE", `Role ${expected.role} declares parent ${actual.descriptor.parentRole ?? "(none)"}; ${expected.parentRole} is required by the ${graph.bodyPlan} graph.`, {- dimension: "categoryReadiness",- affected: { node: actual.node.name, nodePath: actual.nodePath },- measurement: {- name: "declaredParentRole",- actual: actual.descriptor.parentRole ?? "(none)",- expected: expected.parentRole- },- viewHints: ["character.skeleton.front", "character.skeleton.right"]- }));+ if (cap && !closed)+ for (const station of [0, rings.length - 1]) {+ const ring = rings[station], profile = profiles[station];+ const start = positions.length / 3;+ const bounds = new THREE7.Box2().setFromPoints(profile);+ const size = bounds.getSize(new THREE7.Vector2);+ for (let j = 0;j < n; j++) {+ positions.push(...ring[j].toArray());+ uvs.push((profile[j].x - bounds.min.x) / (size.x || 1), (profile[j].y - bounds.min.y) / (size.y || 1));+ }+ for (const tri of THREE7.ShapeUtils.triangulateShape(profile, [])) {+ if (station === 0)+ indices.push(...tri.map((j) => start + j));+ else+ indices.push(...tri.toReversed().map((j) => start + j));+ }}+ const out = meshGeo({ positions, indices, uvs });+ const normal = out.getAttribute("normal");+ for (let i = 0;i < rings.length; i++) {+ const a = i * (n + 1), b = a + n;+ const sum = new THREE7.Vector3().fromBufferAttribute(normal, a).add(new THREE7.Vector3().fromBufferAttribute(normal, b)).normalize();+ normal.setXYZ(a, sum.x, sum.y, sum.z);+ normal.setXYZ(b, sum.x, sum.y, sum.z);}- return findings;-}-function rigProfileFindings(intent, root, byRole) {- const trusted = characterIntent(intent);- if (!trusted || !intent.capabilities.includes("articulated"))- return [];- if (trusted.bodyPlan === "biped") {- return requiredGraphFindings(intent, BIPED_RIG_PRESET_V1, byRole, "CHAR_BIPED_REQUIRED_ROLE");- }- if (trusted.bodyPlan === "quadruped") {- return requiredGraphFindings(intent, QUADRUPED_RIG_PRESET_V1, byRole, "CHAR_QUADRUPED_REQUIRED_ROLE");- }- const customGraph = trusted.rigGraph ?? readCharacterRigGraphV1(root);- if (!customGraph) {- return [- block(intent, "CHAR_CUSTOM_GRAPH_MISSING", `Explicit articulated ${trusted.bodyPlan} character requires its declared semantic rig graph; no biped fallback is allowed.`, {- dimension: "categoryReadiness",- affected: { node: root.name },- measurement: { name: "customRigGraphPresent", actual: false, expected: true },- viewHints: ["character.skeleton.front", "character.skeleton.right"]- })- ];- }- return requiredGraphFindings(intent, customGraph, byRole, "CHAR_CUSTOM_REQUIRED_ROLE");+ if (closed)+ for (let j = 0;j <= n; j++) {+ const a = j, b = (rings.length - 1) * (n + 1) + j;+ const sum = new THREE7.Vector3().fromBufferAttribute(normal, a).add(new THREE7.Vector3().fromBufferAttribute(normal, b)).normalize();+ normal.setXYZ(a, sum.x, sum.y, sum.z);+ normal.setXYZ(b, sum.x, sum.y, sum.z);+ }+ return out;}-function heldItemFindings(intent, nodes) {- const held = characterIntent(intent)?.heldItem;- if (!held?.required)- return [];- const item = nodes.find((evidence) => {- const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];- return evidence.node.userData["kilnHeldItem"] === true || roles.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");+function loftProfiles(sections, options = {}) {+ if (sections.length < 2)+ throw new Error("loftProfiles needs at least two sections");+ const profiles = sections.map((section) => profilePoints(section.profile));+ if (profiles.some((p) => p.length !== profiles[0].length))+ throw new Error("loftProfiles sections must have the same point count and correspondence");+ const rings = sections.map((section, i) => {+ const frame = geometryFrameMatrix(section.frame);+ return profiles[i].map((p) => new THREE7.Vector3(p.x, 0, p.y).applyMatrix4(frame));});- if (!item) {- return [- block(intent, "CHAR_HELD_ITEM_MISSING", "Trusted intent requires a held item, but none is declared.", {- dimension: "categoryReadiness",- affected: { node: held.attachmentRole },- measurement: { name: "heldItemPresent", actual: false, expected: true },- viewHints: ["character.skeleton.front", "character.skeleton.right"]- })- ];- }- let cursor = item.node.parent;- let attachment;- while (cursor) {- attachment = readCharacterJointDescriptorV1(cursor);- if (attachment)- break;- cursor = cursor.parent;- }- const roleMatches = (descriptor) => {- const candidates = [descriptor.role, ...descriptor.aliases];- return candidates.some((role) => role === held.attachmentRole || role.split(/[._-]/).includes(held.attachmentRole));- };- if (attachment?.endEffector && roleMatches(attachment))- return [];- return [- block(intent, "CHAR_HELD_ITEM_ATTACHMENT", `Held item at ${item.nodePath} must be under ${held.attachmentRole} end effector; actual attachment is ${attachment?.role ?? "(non-joint)"}.`, {- dimension: "categoryReadiness",- affected: { node: item.node.name, nodePath: item.nodePath },- measurement: {- name: "heldItemAttachmentRole",- actual: attachment?.role ?? "(non-joint)",- expected: held.attachmentRole- },- viewHints: ["character.skeleton.front", "character.skeleton.right"]- })- ];-}-function contactFindings(intent, root) {- const trusted = characterIntent(intent);- if (!trusted?.grounded)- return [];- const contacts = collectCharacterJointNodes(root).filter((joint) => joint.descriptor.contact);- if (contacts.length === 0) {- return [- block(intent, "CHAR_CONTACT_MISSING", "Grounded character declares no contact joint.", {- dimension: "categoryReadiness",- affected: { node: root.name },- measurement: { name: "groundContactCount", actual: 0, expected: ">=1" },- viewHints: ["character.skeleton.front", "generic.front.depth-contact"]- })- ];- }- root.updateMatrixWorld(true);- const rootInverse = root.matrixWorld.clone().invert();- const tolerance = Number.isFinite(trusted.contactTolerance) && (trusted.contactTolerance ?? 0) >= 0 ? trusted.contactTolerance : CONTACT_TOLERANCE;- const findings = [];- for (const contact of contacts) {- const point = contact.node.getWorldPosition(new THREE4.Vector3).applyMatrix4(rootInverse);- if (point.y > tolerance) {- findings.push(block(intent, "CHAR_CONTACT_FLOATING", `Ground contact ${contact.descriptor.role} is ${point.y.toFixed(6)} m above asset-local ground.`, {- dimension: "categoryReadiness",- affected: { node: contact.node.name, nodePath: contact.nodePath },- measurement: {- name: "contactY",- actual: point.y,- expected: 0,- threshold: tolerance,- unit: "m"- },- viewHints: ["character.skeleton.front", "generic.front.depth-contact"]- }));- } else if (point.y < -tolerance) {- findings.push(block(intent, "CHAR_CONTACT_BURIED", `Ground contact ${contact.descriptor.role} is ${Math.abs(point.y).toFixed(6)} m below asset-local ground.`, {- dimension: "categoryReadiness",- affected: { node: contact.node.name, nodePath: contact.nodePath },- measurement: {- name: "contactY",- actual: point.y,- expected: 0,- threshold: tolerance,- unit: "m"- },- viewHints: ["character.skeleton.front", "generic.front.depth-contact"]- }));+ const out = buildLoft(rings, profiles, false, options.cap ?? true);+ out.userData.kilnGeometryWarnings = [+ {+ code: "LOFT_SELF_INTERSECTION_UNCHECKED",+ message: "Corresponding profiles are connected directly. Caps and closed boundaries do not prove the loft is free of self-intersections."}- }- return findings;+ ];+ return out;}-function requestedClipFindings(intent, clips, requested) {- const findings = [];- const requestedNames = new Set(requested.map((clip) => clip.name));- const counts = new Map;- for (const clip of clips)- counts.set(clip.name, (counts.get(clip.name) ?? 0) + 1);- for (const [name, count] of [...counts.entries()].sort(([a], [b]) => a.localeCompare(b))) {- if (count < 2)- continue;- findings.push(block(intent, "CHAR_CLIP_DUPLICATE", `Clip ${name} appears ${count} times.`, {- dimension: "exportIntegrity",- affected: { clip: name },- measurement: { name: "clipCount", actual: count, expected: 1 },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));+function sweepProfile(profile, path, options = {}) {+ const points = profilePoints(profile), closed = options.closed ?? false, twist = options.twist ?? 0;+ if (!Number.isFinite(twist))+ throw new Error("sweepProfile twist must be finite degrees");+ if (closed && Math.abs(twist / 360 - Math.round(twist / 360)) > 0.00000001)+ throw new Error("closed sweep twist must be a multiple of 360 degrees");+ if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))+ throw new Error("sweepProfile requires finite path points (two open or three closed)");+ const stations = path.map((p) => new THREE7.Vector3(...p));+ if (closed && stations[0].distanceTo(stations[stations.length - 1]) < 0.0000000001)+ throw new Error("closed sweep path should omit its repeated endpoint");+ const segments = [];+ for (let i = 0;i < stations.length - (closed ? 0 : 1); i++) {+ const direction = stations[(i + 1) % stations.length].clone().sub(stations[i]);+ if (direction.length() < 0.0000000001)+ throw new Error("sweepProfile path stations must be distinct");+ segments.push(direction.normalize());}- for (const request of requested) {- const count = counts.get(request.name) ?? 0;- if (count === 0) {- findings.push(block(intent, "CHAR_CLIP_MISSING", `Requested clip ${request.name} is missing.`, {- dimension: "categoryReadiness",- affected: { clip: request.name },- measurement: { name: "clipCount", actual: 0, expected: 1 },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));- }+ const warnings = [];+ const radius = Math.max(...points.map((p) => p.length()));+ const tangents = stations.map((_, i) => {+ if (!closed && i === 0)+ return segments[0].clone();+ if (!closed && i === stations.length - 1)+ return segments[segments.length - 1].clone();+ const incoming = segments[(i - 1 + segments.length) % segments.length], outgoing = segments[i];+ if (incoming.dot(outgoing) < -0.9999)+ throw new Error("sweepProfile path has a reversal; split it into separate sweeps");+ const angle = incoming.angleTo(outgoing);+ const distance = Math.min(stations[i].distanceTo(stations[(i - 1 + stations.length) % stations.length]), stations[i].distanceTo(stations[(i + 1) % stations.length]));+ if (radius * Math.tan(angle / 2) >= distance * 0.5)+ warnings.push({+ code: "SWEEP_TIGHT_TURN",+ message: `Path station ${i} turns tightly relative to the profile; reduce its size or widen the turn. Self-intersection is possible.`+ });+ return incoming.clone().add(outgoing).normalize();+ });+ const scales = stations.map((_, i) => {+ const scale = typeof options.scale === "number" ? [options.scale, options.scale] : options.scale?.[i] ?? [1, 1];+ if (scale.length !== 2 || !scale.every((n) => Number.isFinite(n) && n > 0))+ throw new Error("sweepProfile scale requires positive finite pairs");+ return scale;+ });+ if (Array.isArray(options.scale) && options.scale.length !== stations.length)+ throw new Error("sweepProfile scale needs one pair per path station");+ const up = options.up ? new THREE7.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE7.Vector3(0, 0, 1) : new THREE7.Vector3(1, 0, 0);+ if (![up.x, up.y, up.z].every(Number.isFinite) || up.lengthSq() < 0.00000000000000000001)+ throw new Error("sweepProfile up must be a finite nonzero vector");+ let z = up.clone().addScaledVector(tangents[0], -up.dot(tangents[0]));+ if (z.lengthSq() < 0.000000000001)+ throw new Error("sweepProfile up must not be parallel to the first path tangent");+ z.normalize();+ const normals = [z.clone()];+ if (closed) {+ stations.push(stations[0].clone());+ tangents.push(tangents[0].clone());+ scales.push(scales[0]);}- for (const name of [...counts.keys()].sort()) {- if (requestedNames.has(name))- continue;- findings.push(block(intent, "CHAR_CLIP_UNEXPECTED", `Clip ${name} was not requested by trusted intent.`, {- dimension: "categoryReadiness",- affected: { clip: name },- measurement: { name: "requestedClip", actual: name, expected: "absent" },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));+ const distances = [0];+ for (let i = 1;i < stations.length; i++) {+ z = z.clone().applyQuaternion(new THREE7.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));+ normals.push(z);+ distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));}- return findings;+ const total = distances[distances.length - 1];+ let correction = 0;+ if (closed)+ correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));+ const rings = stations.map((station, i) => {+ const tangent = tangents[i], t = distances[i] / total;+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE7.MathUtils.degToRad(twist)) * t);+ const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];+ return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));+ });+ if (closed)+ rings[rings.length - 1] = rings[0].map((p) => p.clone());+ const out = buildLoft(rings, rings.map(() => points), closed, options.cap ?? true);+ warnings.push({+ code: "SWEEP_SELF_INTERSECTION_UNCHECKED",+ message: "Transported frames and caps do not prove a sweep is free of self-intersections. Review tight turns and nearby path segments."+ });+ out.userData.kilnGeometryWarnings = warnings;+ return out;}-function valueSize(track) {- const explicit = track.getValueSize?.();- if (typeof explicit === "number" && Number.isInteger(explicit) && explicit > 0)- return explicit;- if (track.times.length > 0 && track.values.length % track.times.length === 0) {- return track.values.length / track.times.length;- }- return;+var init_sweep = __esm(() => {+ init_geometry();+ init_deform();+});++// src/solids.ts+import * as THREE8 from "three";+async function getManifoldModule() {+ if (_module)+ return _module;+ if (_initPromise)+ return _initPromise;+ _initPromise = (async () => {+ const mod = await import("manifold-3d");+ const m = await mod.default();+ m.setup();+ _module = m;+ return m;+ })();+ return _initPromise;}-function endpointDelta(track, size) {- const first = Array.from({ length: size }, (_, index) => Number(track.values[index]));- const lastOffset = track.values.length - size;- const last = Array.from({ length: size }, (_, index) => Number(track.values[lastOffset + index]));- if (track.name.endsWith(".quaternion") && size === 4) {- const dot3 = Math.abs(first.reduce((sum, value, index) => sum + value * last[index], 0));- return Math.abs(1 - Math.min(1, dot3));- }- return Math.max(...first.map((value, index) => Math.abs(value - last[index])));+function sourceSpans(mesh, count) {+ const prior = mesh.geometry.userData.kilnCsgProvenance;+ if (prior?.runs?.length)+ return prior.runs.map((r) => ({+ start: r.start * 3,+ count: r.count * 3,+ materialIndex: r.materialIndex,+ name: r.sourceName+ }));+ const ranges = mesh.geometry.userData.kilnRanges;+ const name = mesh.name || ranges?.[0]?.name || "unnamed";+ return Array.isArray(mesh.material) ? mesh.geometry.groups.map((g) => ({+ start: g.start,+ count: g.count,+ materialIndex: g.materialIndex ?? 0,+ name+ })) : [{ start: 0, count, materialIndex: 0, name }];}-function animationDataFindings(intent, clips, requested, root) {- const findings = [];- const playback = new Map(requested.map((clip) => [clip.name, clip.playback]));- const trusted = characterIntent(intent);- const hipsName = root ? collectCharacterJointNodes(root).find((joint) => joint.descriptor.role === "hips")?.node.name : undefined;- const rootMotionNames = new Set([trusted?.rootMotionNode, root?.name, hipsName].filter((name) => Boolean(name)));- for (const clip of clips) {- const durationValid = Number.isFinite(clip.duration) && clip.duration > 0;- if (!durationValid) {- findings.push(block(intent, "CHAR_CLIP_DURATION", `Clip ${clip.name} duration must be finite and positive.`, {- dimension: "exportIntegrity",- affected: { clip: clip.name },- measurement: { name: "clipDuration", actual: clip.duration, expected: ">0", unit: "s" },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));- }- for (const track of clip.tracks) {- const times = Array.from(track.times, Number);- const values = Array.from(track.values, Number);- const nonFiniteTime = times.findIndex((value) => !Number.isFinite(value));- const nonFiniteValue = values.findIndex((value) => !Number.isFinite(value));- if (nonFiniteTime >= 0 || nonFiniteValue >= 0) {- findings.push(block(intent, "CHAR_ANIMATION_NONFINITE", `Clip ${clip.name} track ${track.name} contains a non-finite ${nonFiniteTime >= 0 ? "time" : "value"}.`, {- dimension: "exportIntegrity",- affected: { clip: clip.name, track: track.name },- measurement: {- name: nonFiniteTime >= 0 ? "nonFiniteTimeIndex" : "nonFiniteValueIndex",- actual: nonFiniteTime >= 0 ? nonFiniteTime : nonFiniteValue,- expected: "none"- },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));- }- const badOrder = times.findIndex((time, index) => index > 0 && time <= times[index - 1]);- if (badOrder >= 0) {- findings.push(block(intent, "CHAR_KEY_TIME_ORDER", `Clip ${clip.name} track ${track.name} key times must be strictly increasing and unique.`, {- dimension: "exportIntegrity",- affected: { clip: clip.name, track: track.name },- measurement: {- name: "firstNonIncreasingKey",- actual: badOrder,- expected: "strictly increasing"- },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));- }- if (durationValid) {- const outside = times.findIndex((time) => Number.isFinite(time) && (time < 0 || time > clip.duration));- if (outside >= 0) {- findings.push(block(intent, "CHAR_KEY_OUT_OF_RANGE", `Clip ${clip.name} track ${track.name} key ${outside} lies outside [0, ${clip.duration}].`, {- dimension: "exportIntegrity",- affected: { clip: clip.name, track: track.name },- measurement: {- name: "keyTime",- actual: times[outside],- expected: `0..${clip.duration}`,- unit: "s"- },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));- }+function threeToManifold(src, mod, label, context) {+ src.updateWorldMatrix(true, true);+ const properties = [], indices = [], runs = [], originals = [], faceIds = [];+ let vertexOffset = 0, meshCount = 0;+ const stride = context.preserve ? 5 : 3;+ src.traverse((child) => {+ const mesh = child;+ if (!mesh.isMesh)+ return;+ const geometry = mesh.geometry, position = geometry.getAttribute("position");+ if (!position)+ return;+ meshCount++;+ const index = geometry.index, count = index?.count ?? position.count;+ if (count % 3 !== 0)+ throw new Error(`CSG ${label}: mesh "${mesh.name || "(unnamed)"}" has ${count} ${index ? "indices" : "vertices"}, which is not a whole number of triangles. Every CSG input must be a triangle mesh.`);+ if (position.itemSize !== 3)+ throw new Error(`CSG ${label}: positions must have three components`);+ const uv = geometry.getAttribute("uv");+ if (context.preserve && uv && (uv.itemSize !== 2 || uv.count !== position.count))+ throw new Error(`CSG ${label}: uv must have two components per vertex`);+ if (context.preserve) {+ if (uv)+ context.anyUV = true;+ else+ context.missingUV.add(mesh.name || label);+ }+ const point = new THREE8.Vector3;+ for (let i = 0;i < position.count; i++) {+ point.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);+ if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))+ throw new Error(`CSG ${label}: transformed positions must be finite Float32 coordinates`);+ properties.push(point.x, point.y, point.z);+ if (context.preserve) {+ const u = uv?.getX(i) ?? 0, v = uv?.getY(i) ?? 0;+ if (!Number.isFinite(u) || !Number.isFinite(v))+ throw new Error(`CSG ${label}: UVs must be finite`);+ properties.push(u, v);}- const size = valueSize(track);- if (!size || values.length !== times.length * size) {- findings.push(block(intent, "CHAR_TRACK_VALUE_COUNT", `Clip ${clip.name} track ${track.name} does not contain one complete value per key time.`, {- dimension: "exportIntegrity",- affected: { clip: clip.name, track: track.name },- measurement: {- name: "trackValueCount",- actual: values.length,- expected: size ? times.length * size : "integral tuple count"- },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));- } else if (playback.get(clip.name) === "loop" && !(trusted?.rootMotion === "forward" && track.name.endsWith(".position") && rootMotionNames.has(targetName(track.name) ?? "")) && times.length > 1 && nonFiniteValue < 0 && endpointDelta(track, size) > LOOP_TOLERANCE) {- const delta = endpointDelta(track, size);- findings.push(block(intent, "CHAR_LOOP_ENDPOINT", `Looping clip ${clip.name} track ${track.name} ends ${delta} away from its start pose.`, {- dimension: "categoryReadiness",- affected: { clip: clip.name, track: track.name },- measurement: {- name: "loopEndpointDelta",- actual: delta,- expected: 0,- threshold: LOOP_TOLERANCE- },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));+ }+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];+ const spans = sourceSpans(mesh, count).sort((a, b) => a.start - b.start);+ let covered = 0;+ for (const span of spans) {+ if (!Number.isInteger(span.start) || !Number.isInteger(span.count) || span.start !== covered || span.count <= 0 || span.count % 3 || span.start % 3 || span.start + span.count > count || !materials[span.materialIndex])+ throw new Error(`CSG ${label}: material/source groups must cover triangles exactly once with valid materials`);+ const id = mod.Manifold.reserveIDs(1);+ context.sources.set(id, { name: span.name, material: materials[span.materialIndex] });+ runs.push(indices.length);+ originals.push(id);+ for (let i = span.start;i < span.start + span.count; i += 3) {+ const triangle = [+ index?.getX(i) ?? i,+ index?.getX(i + 1) ?? i + 1,+ index?.getX(i + 2) ?? i + 2+ ];+ if (triangle.some((j) => !Number.isInteger(j) || j < 0 || j >= position.count))+ throw new Error(`CSG ${label}: index outside positions`);+ if (mesh.matrixWorld.determinant() < 0)+ [triangle[1], triangle[2]] = [triangle[2], triangle[1]];+ indices.push(...triangle.map((j) => j + vertexOffset));+ const prior = geometry.userData.kilnCsgProvenance;+ faceIds.push(prior?.faceIds?.[i / 3] ?? i / 3);}+ covered += span.count;}- }- return findings;-}-function applyTrackAt(root, track, time) {- const nodeName = targetName(track.name);- const property = propertyName(track.name);- const node = nodeName ? root.getObjectByName(nodeName) : undefined;- if (!node || !property || !track.createInterpolant)- return;- const value = track.createInterpolant().evaluate(time);- if (property === "position")- node.position.fromArray(value);- else if (property === "scale")- node.scale.fromArray(value);- else if (property === "quaternion") {- node.quaternion.fromArray(value).normalize();- }+ if (covered !== count)+ throw new Error(`CSG ${label}: material/source groups do not cover every triangle`);+ vertexOffset += position.count;+ });+ if (!indices.length)+ throw new Error(`CSG ${label}: contributes no triangles${meshCount === 0 ? " (nothing in it is a mesh — an empty Group, or a part that was never added to it)" : " (its meshes have no geometry)"}. Every CSG operand must be a solid with triangles.`);+ runs.push(indices.length);+ const mesh = new mod.Mesh({+ numProp: stride,+ vertProperties: new Float32Array(properties),+ triVerts: new Uint32Array(indices),+ runIndex: new Uint32Array(runs),+ runOriginalID: new Uint32Array(originals),+ ...context.preserve ? { faceID: new Uint32Array(faceIds) } : {}+ });+ mesh.merge();+ return mod.Manifold.ofMesh(mesh);}-function locomotionClipNames(character) {- const loopingMotion = character.clips.filter((clip) => clip.playback === "loop" && /(?:walk|run|fly|swim|slither|roll|locom)/i.test(clip.name)).map((clip) => clip.name);- if (loopingMotion.length > 0)- return loopingMotion;- return character.clips.filter((clip) => clip.playback === "loop").map((clip) => clip.name);+function assertNonEmptyResult(m, op, hint) {+ if (m.numTri() === 0)+ throw new Error(`${op}: the result is empty (zero triangles). ${hint}`);}-function rootMotionFindings(intent, root, clips) {- const trusted = characterIntent(intent);- if (trusted?.rootMotion !== "forward")- return [];- const names = new Set(locomotionClipNames(trusted));- const findings = [];- const hips = collectCharacterJointNodes(root).find((joint) => joint.descriptor.role === "hips");- for (const clip of clips.filter((candidate) => names.has(candidate.name))) {- const positionTracks = clip.tracks.filter((track) => track.name.endsWith(".position"));- const preferredName = trusted.rootMotionNode ?? root.name;- const rootTrack = positionTracks.find((track) => targetName(track.name) === preferredName) ?? positionTracks.find((track) => targetName(track.name) === hips?.node.name) ?? positionTracks[0];- if (!rootTrack || rootTrack.times.length === 0 || !rootTrack.createInterpolant)- continue;- const interpolant = rootTrack.createInterpolant();- const first = Array.from(interpolant.evaluate(0), Number);- const last = Array.from(interpolant.evaluate(clip.duration), Number);- const dx = Number(last[0]) - Number(first[0]);- const dz = Number(last[2]) - Number(first[2]);- if (!Number.isFinite(dx) || !Number.isFinite(dz))- continue;- if (dx < -ROOT_MOTION_TOLERANCE) {- findings.push(block(intent, "CHAR_ROOT_MOTION_BACKWARD", `Forward locomotion clip ${clip.name} travels ${dx.toFixed(6)} m along X.`, {- dimension: "categoryReadiness",- affected: { clip: clip.name, track: rootTrack.name },- measurement: {- name: "rootMotionDeltaX",- actual: dx,- expected: ">=0",- threshold: ROOT_MOTION_TOLERANCE,- unit: "m"- },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));- }- if (Math.abs(dz) > ROOT_MOTION_TOLERANCE && Math.abs(dz) > Math.max(Math.abs(dx) * 1.25, ROOT_MOTION_TOLERANCE)) {- findings.push(block(intent, "CHAR_ROOT_MOTION_LATERAL", `Forward locomotion clip ${clip.name} is Z-dominant (dx=${dx.toFixed(6)}, dz=${dz.toFixed(6)}).`, {- dimension: "categoryReadiness",- affected: { clip: clip.name, track: rootTrack.name },- measurement: {- name: "rootMotionLateralToForward",- actual: Math.abs(dz) / Math.max(Math.abs(dx), ROOT_MOTION_TOLERANCE),- expected: "<=1.25",- threshold: 1.25- },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));+function manifoldToGeometry(m, opts = {}) {+ const mesh = m.getMesh(), positions = new Float32Array(mesh.vertProperties.length / mesh.numProp * 3);+ const uvs = opts.preserveUV && mesh.numProp >= 5 ? new Float32Array(positions.length / 3 * 2) : undefined;+ for (let i = 0, v = 0;i < mesh.vertProperties.length; i += mesh.numProp, v++) {+ positions.set(mesh.vertProperties.subarray(i, i + 3), v * 3);+ if (uvs)+ uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);+ }+ const geometry = new THREE8.BufferGeometry;+ geometry.setAttribute("position", new THREE8.BufferAttribute(positions, 3));+ geometry.setIndex(new THREE8.BufferAttribute(new Uint32Array(mesh.triVerts), 1));+ if (uvs)+ geometry.setAttribute("uv", new THREE8.BufferAttribute(uvs, 2));+ const out = opts.smooth ? geometry : geometry.toNonIndexed();+ out.computeVertexNormals();+ if (opts.smooth && uvs) {+ const cornerNormals = creaseNormals(out, { angle: 180 }).getAttribute("normal");+ const normal = out.getAttribute("normal");+ for (let corner = 0;corner < out.index.count; corner++) {+ normal.setXYZ(out.index.getX(corner), cornerNormals.getX(corner), cornerNormals.getY(corner), cornerNormals.getZ(corner));}}- return findings;+ out.computeBoundingBox();+ out.computeBoundingSphere();+ return out;}-function declaredHeldItem(nodes) {- return nodes.find((evidence) => {- const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];- return evidence.node.userData["kilnHeldItem"] === true || roles.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");+function firstMaterial(src) {+ let material;+ src.traverse((child) => {+ const mesh = child;+ if (!material && mesh.isMesh)+ material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;});+ return material ?? new THREE8.MeshStandardMaterial;}-function characterJointScale(root) {- root.updateMatrixWorld(true);- const inverse = root.matrixWorld.clone().invert();- const bounds = new THREE4.Box3;- for (const joint of collectCharacterJointNodes(root)) {- bounds.expandByPoint(joint.node.getWorldPosition(new THREE4.Vector3).applyMatrix4(inverse));- }- if (bounds.isEmpty())- return 1;- const size = bounds.getSize(new THREE4.Vector3);- return Math.max(size.x, size.y, size.z, 1);-}-function heldItemMotionFindings(intent, root, clips) {- const held = characterIntent(intent)?.heldItem;- if (!held?.required || clips.length === 0)- return [];- const item = declaredHeldItem(collectNodes(root));- if (!item)- return [];- let attachmentNode = item.node.parent;- let attachment = attachmentNode ? readCharacterJointDescriptorV1(attachmentNode) : undefined;- while (attachmentNode && !attachment) {- attachmentNode = attachmentNode.parent;- attachment = attachmentNode ? readCharacterJointDescriptorV1(attachmentNode) : undefined;- }- if (!attachmentNode || !attachment?.endEffector)- return [];- const tolerance = Math.max(0.01, characterJointScale(root) * GRIP_MOTION_RATIO);- const findings = [];- for (const clip of clips) {- if (!Number.isFinite(clip.duration) || clip.duration <= 0)- continue;- let baseline;- let maximumDrift = 0;- let maximumFraction = 0;- for (const fraction of CHARACTER_SAMPLE_FRACTIONS) {- const clone2 = root.clone(true);- for (const track of clip.tracks)- applyTrackAt(clone2, track, fraction * clip.duration);- clone2.updateMatrixWorld(true);- const cloneItem = clone2.getObjectByName(item.node.name);- const cloneAttachment = collectCharacterJointNodes(clone2).find((joint) => joint.descriptor.role === attachment.role)?.node;- if (!cloneItem || !cloneAttachment)+function outputMesh(result, name, parts, opts, context, isHull) {+ const geometry = manifoldToGeometry(result, {+ smooth: opts.smooth,+ preserveUV: context.preserve && context.anyUV && !isHull+ });+ const native = result.getMesh(), materials = [], sourceRuns = [];+ if (!isHull)+ for (let i = 0;i < native.runOriginalID.length; i++) {+ const source = context.sources.get(native.runOriginalID[i]);+ const start = native.runIndex[i] / 3, count = (native.runIndex[i + 1] - native.runIndex[i]) / 3;+ if (!count)continue;- const inverse = clone2.matrixWorld.clone().invert();- const itemPoint = cloneItem.getWorldPosition(new THREE4.Vector3).applyMatrix4(inverse);- const gripPoint = cloneAttachment.getWorldPosition(new THREE4.Vector3).applyMatrix4(inverse);- const distance = itemPoint.distanceTo(gripPoint);- baseline ??= distance;- const drift = Math.abs(distance - baseline);- if (drift > maximumDrift) {- maximumDrift = drift;- maximumFraction = fraction;+ const material = source?.material ?? firstMaterial(parts[0]);+ let materialIndex = context.preserve ? materials.indexOf(material) : 0;+ if (context.preserve && materialIndex < 0) {+ materialIndex = materials.length;+ materials.push(material);}+ sourceRuns.push({+ sourceName: source?.name ?? "unknown",+ start,+ count,+ materialIndex,+ backside: !!((native.runFlags?.[i] ?? 0) & 1)+ });+ if (context.preserve)+ geometry.addGroup(start * 3, count * 3, materialIndex);}- if (maximumDrift <= tolerance)- continue;- findings.push(block(intent, "CHAR_HELD_ITEM_GRIP_BREAK", `Held item ${item.node.name} breaks its declared ${attachment.role} grip relationship in ${clip.name} at phase ${maximumFraction}.`, {- dimension: "categoryReadiness",- affected: {- node: item.node.name,- nodePath: item.nodePath,- clip: clip.name- },- measurement: {- name: "heldItemGripDistanceDrift",- actual: maximumDrift,- expected: 0,- threshold: tolerance,- unit: "m"- },- viewHints: ["character.motion-strip.front", "character.motion-strip.right"]- }));- }- return findings;-}-function evaluateCharacterQa(context) {- if (context.intent.category !== "character")- return [];- const root = context.scene instanceof THREE4.Object3D ? context.scene : undefined;- const clips = (context.clips ?? []).filter(isClipLike);- const findings = [];- if (root) {- const nodes = collectNodes(root);- findings.push(...duplicateNameFindings(context.intent, nodes, clips));- const rig = parentAndRoleFindings(context.intent, root);- findings.push(...rig.findings);- findings.push(...rigProfileFindings(context.intent, root, rig.byRole));- findings.push(...heldItemFindings(context.intent, nodes));- findings.push(...contactFindings(context.intent, root));- findings.push(...rootMotionFindings(context.intent, root, clips));- findings.push(...heldItemMotionFindings(context.intent, root, clips));- }- const requested = characterIntent(context.intent)?.clips ?? [];- findings.push(...requestedClipFindings(context.intent, clips, requested));- findings.push(...animationDataFindings(context.intent, clips, requested, root));- return dedupeFindings(findings);-}-var PROFILE_RULE_ID2 = "CHARACTER_PROFILE", CONTACT_TOLERANCE = 0.02, LOOP_TOLERANCE = 0.00001, ROOT_MOTION_TOLERANCE = 0.01, GRIP_MOTION_RATIO = 0.02, CHARACTER_SAMPLE_FRACTIONS, CHARACTER_QA_RULE;-var init_character2 = __esm(() => {- init_character();- init_contracts();- init_character_repairs();- init_registry();- CHARACTER_SAMPLE_FRACTIONS = Object.freeze([0, 0.25, 0.5, 0.75, 1]);- CHARACTER_QA_RULE = Object.freeze({- id: PROFILE_RULE_ID2,- profile: "character",- scope: { kind: "category", category: "character" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("character-qa-v1", "src/qa/character.test.ts", "53086f1350c61cb8ddd32a5a4a97d23256e5dbde2e5b9765e47a3c76045bd6ed"),- defaultMode: "enforce",- evaluate: evaluateCharacterQa- });-});--// src/qa/character-advisory.ts-import * as THREE5 from "three";-function isClipLike2(value) {- if (typeof value !== "object" || value === null)- return false;- const candidate = value;- return typeof candidate.name === "string" && typeof candidate.duration === "number" && Array.isArray(candidate.tracks);+ const total = (geometry.index?.count ?? geometry.getAttribute("position").count) / 3;+ geometry.userData.kilnCsgProvenance = {+ schemaVersion: 1,+ runs: sourceRuns,+ faceIds: isHull ? [] : Array.from(native.faceID),+ unknownTriangles: isHull ? total : sourceRuns.filter((r) => r.sourceName === "unknown").reduce((sum, r) => sum + r.count, 0)+ };+ geometry.userData.kilnRanges = sourceRuns.length ? sourceRuns.map((r) => ({+ name: r.sourceName,+ start: r.start,+ count: r.count,+ certainty: r.sourceName === "unknown" ? "unknown" : "source-run"+ })) : [{ name: "generated hull", start: 0, count: total, certainty: "unknown" }];+ const warnings = [];+ if (context.preserve && context.anyUV && context.missingUV.size)+ warnings.push({+ code: "CSG_UV_MISSING",+ message: `UVs were absent on ${[...context.missingUV].join(", ")}; those surfaces use zero UVs. Unwrap the result if they need a texture.`+ });+ if (isHull && context.preserve)+ warnings.push({+ code: "HULL_ATTRIBUTES_GENERATED",+ message: "A convex hull creates new faces. Source UVs and material boundaries cannot be assigned faithfully; output uses the first material and no UVs."+ });+ geometry.userData.kilnAttributeWarnings = warnings;+ const output = new THREE8.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));+ output.name = `Mesh_${name}`;+ return output;}-function characterIntent2(intent) {- return intent.character;+function splitPartsAndOpts(items) {+ const last = items[items.length - 1];+ if (last && !last.isObject3D)+ return { parts: items.slice(0, -1), opts: last };+ return { parts: items, opts: {} };}-function advisory(context, value) {- return {- ...value,- disposition: "warn",- dimension: "categoryReadiness",- profile: context.intent.qaProfile+async function runBoolean(op, name, parts, opts) {+ const mod = await getManifoldModule(), context = {+ preserve: opts.preserveAttributes ?? false,+ sources: new Map,+ anyUV: false,+ missingUV: new Set};+ const owned = new Set;+ const track = (m) => {+ owned.add(m);+ return m;+ };+ try {+ const operands = parts.map((p, i) => track(threeToManifold(p, mod, op === "boolDiff" ? i === 0 ? "boolDiff body" : `boolDiff cutter ${i}` : op === "boolIntersect" ? `boolIntersect operand ${i === 0 ? "a" : "b"}` : `${op} operand ${i + 1}`, context)));+ let result;+ if (op === "boolUnion")+ result = track(mod.Manifold.union(operands));+ else if (op === "boolDiff") {+ const cutters = operands.length === 2 ? operands[1] : track(mod.Manifold.union(operands.slice(1)));+ result = track(operands[0].subtract(cutters));+ } else if (op === "boolIntersect")+ result = track(operands[0].intersect(operands[1]));+ else+ result = track(operands.length === 1 ? operands[0].hull() : mod.Manifold.hull(operands));+ const hint = op === "boolDiff" ? "The cutters removed the entire body — check their size and position, or subtract fewer of them." : op === "boolIntersect" ? "The two operands do not overlap — position them so their volumes actually intersect." : op === "hull" ? "The inputs are coplanar or collinear, so they enclose no volume." : "Every operand was empty after merging.";+ assertNonEmptyResult(result, op, hint);+ return outputMesh(result, name, parts, { ...opts, smooth: opts.smooth ?? op === "hull" }, context, op === "hull");+ } finally {+ for (const ownedManifold of owned)+ ownedManifold.delete();+ }}-function rootInverse(root) {- root.updateMatrixWorld(true);- return root.matrixWorld.clone().invert();-}-function jointPoints(root) {- const inverse = rootInverse(root);- return collectCharacterJointNodes(root).map((evidence) => ({- evidence,- local: evidence.node.getWorldPosition(new THREE5.Vector3).applyMatrix4(inverse)- }));+async function boolUnion(name, ...items) {+ const { parts, opts } = splitPartsAndOpts(items);+ if (parts.length < 2)+ throw new Error("boolUnion requires at least two parts");+ return runBoolean("boolUnion", name, parts, opts);}-function characterScale(points) {- if (points.length === 0)- return 1;- const bounds = new THREE5.Box3;- for (const point of points)- bounds.expandByPoint(point.local);- const size = bounds.getSize(new THREE5.Vector3);- return Math.max(size.x, size.y, size.z, 1);+async function boolDiff(name, body, ...items) {+ const { parts, opts } = splitPartsAndOpts(items);+ if (parts.length < 1)+ throw new Error("boolDiff requires at least one cutter");+ return runBoolean("boolDiff", name, [body, ...parts], opts);}-function pairKey(descriptor) {- return descriptor.role.split(/[._-]/).filter((token) => token !== "left" && token !== "right").join(".");+async function boolIntersect(name, a, b, opts = {}) {+ return runBoolean("boolIntersect", name, [a, b], opts);}-function bilateralSymmetryFindings(context, root) {- const points = jointPoints(root);- const scale = characterScale(points);- const threshold = Math.max(0.02, scale * REST_SYMMETRY_RATIO);- const left = new Map(points.filter((point) => point.evidence.descriptor.side === "left").map((point) => [pairKey(point.evidence.descriptor), point]));- const right = new Map(points.filter((point) => point.evidence.descriptor.side === "right").map((point) => [pairKey(point.evidence.descriptor), point]));- const findings = [];- for (const key of [...new Set([...left.keys(), ...right.keys()])].sort()) {- const a = left.get(key);- const b = right.get(key);- if (!a || !b)- continue;- const mirrorDelta = Math.hypot(a.local.x - b.local.x, a.local.y - b.local.y, a.local.z + b.local.z);- const sideSwapped = a.local.z > b.local.z;- if (!sideSwapped && mirrorDelta <= threshold)- continue;- findings.push(advisory(context, {- code: "CHAR_REST_BILATERAL_SYMMETRY",- message: `Bilateral rest pair ${a.evidence.descriptor.role} / ${b.evidence.descriptor.role} ` + `${sideSwapped ? "appears left/right swapped" : "is grossly asymmetric"} ` + `(mirror delta ${mirrorDelta.toFixed(6)} m).`,- affected: {- node: b.evidence.node.name,- nodePath: b.evidence.nodePath- },- measurement: {- name: "bilateralMirrorDelta",- actual: mirrorDelta,- expected: 0,- threshold,- unit: "m"- },- viewHints: [...SKELETON_VIEWS]- }));- }- return findings;+async function hull(name, ...items) {+ const { parts, opts } = splitPartsAndOpts(items);+ if (parts.length < 1)+ throw new Error("hull requires at least one part");+ return runBoolean("hull", name, parts, opts);}-function restChainFindings(context, root) {- const trusted = characterIntent2(context.intent);- if (trusted?.bodyPlan !== "biped" && trusted?.bodyPlan !== "quadruped")- return [];- const points = jointPoints(root);- const byRole = new Map(points.map((point) => [point.evidence.descriptor.role, point]));- const scale = characterScale(points);- const minimumSegment = Math.max(0.01, scale * REST_ORDER_RATIO);- const chains = trusted.bodyPlan === "biped" ? BIPED_CHAINS : QUADRUPED_CHAINS;- const findings = [];- for (const roles of chains) {- const chain = roles.map((role) => byRole.get(role)).filter((value) => !!value);- if (chain.length !== roles.length)- continue;- for (let index = 1;index < chain.length; index++) {- const parent = chain[index - 1];- const child = chain[index];- const verticalDrop = parent.local.y - child.local.y;- if (verticalDrop >= minimumSegment)- continue;- findings.push(advisory(context, {- code: "CHAR_REST_CHAIN_ORDER",- message: `Rest chain ${roles.join(" -> ")} is vertically inverted or collapsed at ` + `${parent.evidence.descriptor.role} -> ${child.evidence.descriptor.role}.`,- affected: { node: child.evidence.node.name, nodePath: child.evidence.nodePath },- measurement: {- name: "parentToChildVerticalDrop",- actual: verticalDrop,- expected: `>=${minimumSegment}`,- threshold: minimumSegment,- unit: "m"- },- viewHints: [...SKELETON_VIEWS]- }));- }- const lengths = [- chain[0].local.distanceTo(chain[1].local),- chain[1].local.distanceTo(chain[2].local)+var _module = null, _initPromise = null;+var init_solids = __esm(() => {+ init_geometry();+});++// src/implicit.ts+async function implicitSurface(sample, options) {+ const {+ bounds,+ edgeLength,+ maxCells = 1e6,+ maxEvaluations = 8000000,+ level = 0,+ tolerance = -1,+ smooth = true+ } = options;+ if (bounds?.min.length !== 3 || bounds.max.length !== 3 || ![...bounds.min, ...bounds.max].every(Number.isFinite) || bounds.min.some((v, i) => v >= bounds.max[i]))+ throw new Error("implicitSurface bounds must be finite and increasing on every axis");+ if (!Number.isFinite(edgeLength) || edgeLength <= 0)+ throw new Error("implicitSurface edgeLength must be positive and finite");+ if (!Number.isSafeInteger(maxCells) || maxCells < 1 || !Number.isSafeInteger(maxEvaluations) || maxEvaluations < 1)+ throw new Error("implicitSurface maxCells and maxEvaluations must be positive safe integers");+ if (!Number.isFinite(level) || !Number.isFinite(tolerance) || tolerance !== -1 && tolerance <= 0)+ throw new Error("implicitSurface level must be finite; tolerance must be -1 or positive");+ const estimatedGridCells = bounds.min.reduce((product, min, i) => product * Math.ceil((bounds.max[i] - min) / edgeLength), 1);+ if (!Number.isSafeInteger(estimatedGridCells) || estimatedGridCells > maxCells)+ throw new Error(`implicitSurface estimated grid ${estimatedGridCells} exceeds maxCells ${maxCells}; increase edgeLength or narrow bounds`);+ const mod = await getManifoldModule();+ let evaluations = 0;+ const solid = mod.Manifold.levelSet((point) => {+ evaluations++;+ if (evaluations > maxEvaluations)+ throw new Error(`implicitSurface exceeded maxEvaluations ${maxEvaluations}`);+ const value = sample([point[0], point[1], point[2]]);+ if (!Number.isFinite(value))+ throw new Error("implicitSurface callback must return a finite number");+ return value;+ }, { min: [...bounds.min], max: [...bounds.max] }, edgeLength, level, tolerance);+ try {+ if (solid.numTri() === 0)+ throw new Error("implicitSurface result is empty; the field does not enclose a positive-inside region in these bounds");+ const out = manifoldToGeometry(solid, { smooth });+ out.userData.kilnImplicit = {+ schemaVersion: 1,+ experimental: true,+ edgeLength,+ estimatedGridCells,+ evaluations,+ maxCells,+ maxEvaluations+ };+ out.userData.kilnGeometryWarnings = [+ {+ code: "EXPERIMENTAL_IMPLICIT_SURFACE",+ message: "Implicit sampling is resolution-dependent and produces geometry without UVs. Review thin features and bounds; closed topology is not a claim of CAD accuracy."+ }];- const ratio = Math.max(...lengths) / Math.max(Math.min(...lengths), 0.000000001);- if (Math.min(...lengths) >= minimumSegment && ratio <= 2.5)- continue;- findings.push(advisory(context, {- code: "CHAR_REST_SEGMENT_LENGTH",- message: `Rest chain ${roles.join(" -> ")} has collapsed or grossly unmatched segment lengths.`,- affected: { node: chain[1].evidence.node.name, nodePath: chain[1].evidence.nodePath },- measurement: {- name: "chainSegmentLengthRatio",- actual: ratio,- expected: "<=2.5",- threshold: 2.5- },- viewHints: [...SKELETON_VIEWS]- }));+ return out;+ } finally {+ solid.delete();}- return findings;-}-function forwardMarkerFindings(context, root) {- root.updateMatrixWorld(true);- const expected = new THREE5.Vector3(1, 0, 0).transformDirection(root.matrixWorld);- const markers = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:toe|muzzle|head)(?:$|[._-])/i.test(joint.descriptor.role));- return markers.flatMap((marker) => {- const quaternion = marker.node.getWorldQuaternion(new THREE5.Quaternion);- const actual = new THREE5.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();- const angle = THREE5.MathUtils.radToDeg(Math.acos(THREE5.MathUtils.clamp(actual.dot(expected), -1, 1)));- if (angle <= FORWARD_ANGLE_DEGREES)- return [];- return [- advisory(context, {- code: "CHAR_FORWARD_MARKER",- message: `Declared forward marker ${marker.descriptor.role} differs from canonical +X by ` + `${angle.toFixed(3)} degrees.`,- affected: { node: marker.node.name, nodePath: marker.nodePath },- measurement: {- name: "forwardMarkerAngle",- actual: angle,- expected: 0,- threshold: FORWARD_ANGLE_DEGREES,- unit: "degrees"- },- viewHints: [...SKELETON_VIEWS]- })- ];- });-}-function trackTarget(trackName) {- const dot3 = trackName.lastIndexOf(".");- return dot3 > 0 ? trackName.slice(0, dot3) : undefined;}-function trackProperty(trackName) {- const dot3 = trackName.lastIndexOf(".");- return dot3 > 0 ? trackName.slice(dot3 + 1) : undefined;-}-function applyTrack(root, track, time) {- const target = trackTarget(track.name);- const property = trackProperty(track.name);- const node = target ? root.getObjectByName(target) : undefined;- if (!node || !property || !track.createInterpolant)- return;- const value = track.createInterpolant().evaluate(time);- if (property === "position")- node.position.fromArray(value);- else if (property === "scale")- node.scale.fromArray(value);- else if (property === "quaternion")- node.quaternion.fromArray(value).normalize();+var init_implicit = __esm(() => {+ init_solids();+});++// src/profile.ts+function assertFiniteProfile(profile, label) {+ if (!Array.isArray(profile) || profile.length < 3) {+ throw new Error(`${label}: need at least 3 points to form a closed outline.`);+ }+ for (let i = 0;i < profile.length; i++) {+ const p = profile[i];+ if (!Array.isArray(p) || p.length < 2 || !Number.isFinite(p[0]) || !Number.isFinite(p[1])) {+ throw new Error(`${label}: point ${i} is not a finite [x, y] pair (got ${JSON.stringify(p)}).`);+ }+ }}-function sampleClip(root, clip) {- const inverse = rootInverse(root);- return SAMPLE_FRACTIONS.map((fraction) => {- const clone2 = root.clone(true);- for (const track of clip.tracks)- applyTrack(clone2, track, fraction * clip.duration);- clone2.updateMatrixWorld(true);- return {- fraction,- byRole: new Map(collectCharacterJointNodes(clone2).map((evidence) => [- evidence.descriptor.role,- {- point: evidence.node.getWorldPosition(new THREE5.Vector3).applyMatrix4(inverse),- evidence- }- ]))- };- });+function assertPositive(value, label) {+ if (!Number.isFinite(value) || value <= 0) {+ throw new Error(`${label} must be a positive number (got ${value}).`);+ }}-function locomotionClips(context) {- const trusted = characterIntent2(context.intent);- if (!trusted || trusted.locomotion === "stationary")- return [];- const names = new Set(trusted.clips.filter((clip) => clip.playback === "loop").map((clip) => clip.name));- return (context.clips ?? []).filter(isClipLike2).filter((clip) => names.size === 0 || names.has(clip.name));+function orientSweep(geo, axis) {+ if (axis === "y")+ geo.rotateX(-Math.PI / 2);+ else if (axis === "x")+ geo.rotateY(Math.PI / 2);+ else if (axis !== "z")+ throw new Error(`axis must be 'x', 'y', or 'z' (got ${String(axis)}).`);+ return geo;}-function limbRole(role) {- return /(?:shoulder|elbow|wrist|hip|knee|ankle|paw|toe|wing)/i.test(role);+function bevelCrossSection(cs, bevel, style, segments, label) {+ const join = JOIN_FOR_STYLE[style];+ if (!join) {+ throw new Error(`${label}: bevelStyle must be 'round' or 'chamfer' (got ${String(style)}).`);+ }+ const eroded = cs.offset(-bevel, join, 2, segments);+ if (eroded.isEmpty()) {+ eroded.delete();+ throw new Error(`${label}: bevel ${bevel} is too large for this profile — eroding by it leaves nothing. ` + `Use a bevel smaller than half the narrowest part of the outline.`);+ }+ const dilated = eroded.offset(2 * bevel, join, 2, segments);+ const out = dilated.offset(-bevel, join, 2, segments);+ eroded.delete();+ dilated.delete();+ return out;}-function lateralEnergyFindings(context, root, clips) {- const rest = jointPoints(root);- const scale = characterScale(rest);- const minimumEnergy = scale * scale * 0.0001;- const findings = [];- for (const clip of clips) {- const samples = sampleClip(root, clip);- const roles = [...samples[0].byRole.keys()].filter(limbRole).sort();- for (const role of roles) {- let sagittal = 0;- let lateral = 0;- let maximumLateral = 0;- let maximumFraction = 0;- for (let index = 1;index < samples.length; index++) {- const before = samples[index - 1].byRole.get(role)?.point;- const after = samples[index].byRole.get(role)?.point;- if (!before || !after)- continue;- const delta = after.clone().sub(before);- sagittal += delta.x * delta.x + delta.y * delta.y;- lateral += delta.z * delta.z;- if (Math.abs(delta.z) > maximumLateral) {- maximumLateral = Math.abs(delta.z);- maximumFraction = samples[index].fraction;- }- }- if (lateral + sagittal < minimumEnergy || lateral <= sagittal * LATERAL_ENERGY_RATIO)- continue;- const evidence = samples[0].byRole.get(role).evidence;- findings.push(advisory(context, {- code: "CHAR_GAIT_LATERAL_ENERGY",- message: `Locomotion chain ${role} in ${clip.name} is lateral-motion dominant; ` + `largest offending step ends at phase ${maximumFraction}.`,- affected: { node: evidence.node.name, nodePath: evidence.nodePath, clip: clip.name },- measurement: {- name: "lateralToSagittalEnergy",- actual: lateral / Math.max(sagittal, minimumEnergy),- expected: `<=${LATERAL_ENERGY_RATIO}`,- threshold: LATERAL_ENERGY_RATIO- },- viewHints: [...MOTION_VIEWS]- }));+function normalizeTaper(taper) {+ if (taper === undefined)+ return [1, 1];+ if (typeof taper === "number") {+ if (!Number.isFinite(taper) || taper < 0) {+ throw new Error(`taper must be a finite number >= 0 (got ${taper}).`);}+ return [taper, taper];}- return findings;-}-function correlation(a, b) {- if (a.length !== b.length || a.length < 3)- return;- const meanA = a.reduce((sum, value) => sum + value, 0) / a.length;- const meanB = b.reduce((sum, value) => sum + value, 0) / b.length;- let numerator = 0;- let varianceA = 0;- let varianceB = 0;- for (let index = 0;index < a.length; index++) {- const da = a[index] - meanA;- const db = b[index] - meanB;- numerator += da * db;- varianceA += da * da;- varianceB += db * db;+ if (!Array.isArray(taper) || taper.length !== 2 || !taper.every((v) => Number.isFinite(v) && v >= 0)) {+ throw new Error(`taper must be a number or [x, y] pair of numbers >= 0 (got ${JSON.stringify(taper)}).`);}- const denominator = Math.sqrt(varianceA * varianceB);- return denominator > 0.000000001 ? numerator / denominator : undefined;+ return [taper[0], taper[1]];}-function phaseOppositionFindings(context, root, clips) {- const trusted = characterIntent2(context.intent);- if (trusted?.bodyPlan !== "biped" || !/(?:walk|run)/i.test(trusted.locomotion))- return [];- const findings = [];- for (const clip of clips) {- const samples = sampleClip(root, clip);- const left = samples.map((sample) => sample.byRole.get("ankle.left")?.point.x);- const right = samples.map((sample) => sample.byRole.get("ankle.right")?.point.x);- if (left.some((value) => value === undefined) || right.some((value) => value === undefined)) {- continue;+async function extrudeProfile(profile, options = {}) {+ assertFiniteProfile(profile, "extrudeProfile");+ const {+ depth = 1,+ holes = [],+ bevel = 0,+ bevelStyle = "round",+ segments = 12,+ twist = 0,+ taper,+ divisions,+ axis = "y",+ center = true,+ smooth = false+ } = options;+ assertPositive(depth, "extrudeProfile: depth");+ if (bevel < 0)+ throw new Error(`extrudeProfile: bevel must be >= 0 (got ${bevel}).`);+ for (let i = 0;i < holes.length; i++) {+ assertFiniteProfile(holes[i], `extrudeProfile: holes[${i}]`);+ }+ const mod = await getManifoldModule();+ const { CrossSection: CS } = mod;+ const disposable = [];+ const track = (cs) => {+ disposable.push(cs);+ return cs;+ };+ try {+ let section = track(new CS([profile], "NonZero"));+ if (holes.length > 0) {+ const holeSections = holes.map((h) => track(new CS([h], "NonZero")));+ section = track(CS.difference(section, CS.union(holeSections)));+ if (section.isEmpty()) {+ throw new Error("extrudeProfile: the holes consume the whole profile — nothing left to extrude.");+ }}- const phaseCorrelation = correlation(left, right);- if (phaseCorrelation === undefined || phaseCorrelation <= PHASE_CORRELATION_THRESHOLD)- continue;- const evidence = samples[0].byRole.get("ankle.right").evidence;- findings.push(advisory(context, {- code: "CHAR_GAIT_SAME_PHASE",- message: `Biped ${clip.name} drives left and right legs in the same phase ` + `(correlation ${phaseCorrelation.toFixed(6)}).`,- affected: { node: evidence.node.name, nodePath: evidence.nodePath, clip: clip.name },- measurement: {- name: "leftRightLegPhaseCorrelation",- actual: phaseCorrelation,- expected: "<=0.25",- threshold: PHASE_CORRELATION_THRESHOLD- },- viewHints: [...MOTION_VIEWS]- }));+ if (bevel > 0) {+ section = track(bevelCrossSection(section, bevel, bevelStyle, segments, "extrudeProfile"));+ }+ const nDivisions = divisions ?? (twist !== 0 ? 16 : 1);+ const solid = section.extrude(depth, nDivisions, twist, normalizeTaper(taper), center);+ try {+ return orientSweep(manifoldToGeometry(solid, { smooth }), axis);+ } finally {+ solid.delete();+ }+ } finally {+ for (const cs of disposable)+ cs.delete();}- return findings;-}-function signedBendDegrees(descriptor, quaternion) {- const rest = new THREE5.Quaternion(...descriptor.rest.rotation);- const delta = rest.invert().multiply(quaternion).normalize();- const axis = new THREE5.Vector3(delta.x, delta.y, delta.z);- const signedMagnitude = axis.dot(new THREE5.Vector3(...descriptor.localBendAxis));- const angle = 2 * Math.atan2(signedMagnitude, delta.w);- return THREE5.MathUtils.radToDeg(THREE5.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);}-function bendDirectionFindings(context, root, clips) {- const joints = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role));- const findings = [];- for (const clip of clips) {- for (const joint of joints) {- const track = clip.tracks.find((candidate) => trackTarget(candidate.name) === joint.node.name && trackProperty(candidate.name) === "quaternion" && candidate.createInterpolant);- if (!track?.createInterpolant)- continue;- let maximum = 0;- let maximumFraction = 0;- for (const fraction of SAMPLE_FRACTIONS) {- const value = track.createInterpolant().evaluate(fraction * clip.duration);- const bend = signedBendDegrees(joint.descriptor, new THREE5.Quaternion().fromArray(value).normalize());- if (Math.abs(bend) > Math.abs(maximum)) {- maximum = bend;- maximumFraction = fraction;- }- }- if (maximum >= -REVERSE_BEND_DEGREES)- continue;- findings.push(advisory(context, {- code: "CHAR_JOINT_REVERSE_BEND",- message: `${joint.descriptor.role} bends opposite its declared local bend axis at ` + `${clip.name} phase ${maximumFraction}.`,- affected: {- node: joint.node.name,- nodePath: joint.nodePath,- clip: clip.name,- track: track.name- },- measurement: {- name: "signedMaximumFlexion",- actual: maximum,- expected: `>=-${REVERSE_BEND_DEGREES}`,- threshold: REVERSE_BEND_DEGREES,- unit: "degrees"- },- viewHints: [...MOTION_VIEWS]- }));+async function revolveProfile(profile, options = {}) {+ assertFiniteProfile(profile, "revolveProfile");+ const {+ segments = 24,+ angle = 360,+ bevel = 0,+ bevelStyle = "round",+ bevelSegments = 12,+ axis = "y",+ smooth = true+ } = options;+ if (bevel < 0)+ throw new Error(`revolveProfile: bevel must be >= 0 (got ${bevel}).`);+ if (!Number.isFinite(angle) || angle <= 0 || angle > 360) {+ throw new Error(`revolveProfile: angle must be in (0, 360] degrees (got ${angle}).`);+ }+ const mod = await getManifoldModule();+ const { CrossSection: CS } = mod;+ const disposable = [];+ try {+ let section = new CS([profile], "NonZero");+ disposable.push(section);+ if (bevel > 0) {+ section = bevelCrossSection(section, bevel, bevelStyle, bevelSegments, "revolveProfile");+ disposable.push(section);}+ const solid = section.revolve(segments, angle);+ try {+ return orientSweep(manifoldToGeometry(solid, { smooth }), axis);+ } finally {+ solid.delete();+ }+ } finally {+ for (const cs of disposable)+ cs.delete();}- return findings;}-function footSlideFindings(context, root, clips) {- const trusted = characterIntent2(context.intent);- if (!trusted?.grounded)- return [];- const rest = jointPoints(root);- const threshold = Math.max(0.02, characterScale(rest) * FOOT_SLIDE_RATIO);- const contactTolerance = Math.max(0.02, threshold * 0.4);- const contacts = rest.filter((point) => point.evidence.descriptor.contact).map((point) => point.evidence.descriptor.role);- const findings = [];- for (const clip of clips) {- const samples = sampleClip(root, clip);- for (const role of contacts) {- let anchor;- let maximum = 0;- let maximumFraction = 0;- for (const sample of samples) {- const entry = sample.byRole.get(role);- if (!entry || entry.point.y > contactTolerance) {- anchor = undefined;- continue;- }- anchor ??= entry.point.clone();- const slide = Math.hypot(entry.point.x - anchor.x, entry.point.z - anchor.z);- if (slide > maximum) {- maximum = slide;- maximumFraction = sample.fraction;+async function roundedBoxGeo(width, height, depth, radius, options = {}) {+ assertPositive(width, "roundedBoxGeo: width");+ assertPositive(height, "roundedBoxGeo: height");+ assertPositive(depth, "roundedBoxGeo: depth");+ assertPositive(radius, "roundedBoxGeo: radius");+ const { style = "round", segments = 12, smooth } = options;+ const smallest = Math.min(width, height, depth);+ if (radius >= smallest / 2) {+ throw new AuthoringDiagnosticError("ROUNDED_BOX_RADIUS");+ }+ const mod = await getManifoldModule();+ const ManifoldCls = mod.Manifold;+ const parts = [];+ try {+ let solid;+ if (style === "round") {+ const corners = [];+ for (const sx of [-1, 1]) {+ for (const sy of [-1, 1]) {+ for (const sz of [-1, 1]) {+ const s = ManifoldCls.sphere(radius, segments).translate([+ sx * (width - 2 * radius) / 2,+ sy * (height - 2 * radius) / 2,+ sz * (depth - 2 * radius) / 2+ ]);+ parts.push(s);+ corners.push(s);+ }}}- if (maximum <= threshold)- continue;- const evidence = samples[0].byRole.get(role)?.evidence;- findings.push(advisory(context, {- code: "CHAR_FOOT_SLIDE",- message: `Planted contact ${role} slides ${maximum.toFixed(6)} m horizontally in ` + `${clip.name} by phase ${maximumFraction}.`,- affected: {- node: evidence?.node.name ?? role,- ...evidence ? { nodePath: evidence.nodePath } : {},- clip: clip.name- },- measurement: {- name: "plantedContactHorizontalSlide",- actual: maximum,- expected: 0,- threshold,- unit: "m"- },- viewHints: [...MOTION_VIEWS, "generic.front.depth-contact"]- }));+ solid = ManifoldCls.hull(corners);+ } else if (style === "chamfer") {+ const boxes = [+ ManifoldCls.cube([width, height - 2 * radius, depth - 2 * radius], true),+ ManifoldCls.cube([width - 2 * radius, height, depth - 2 * radius], true),+ ManifoldCls.cube([width - 2 * radius, height - 2 * radius, depth], true)+ ];+ parts.push(...boxes);+ solid = ManifoldCls.hull(boxes);+ } else {+ throw new Error(`roundedBoxGeo: style must be 'round' or 'chamfer' (got ${String(style)}).`);+ }+ try {+ return manifoldToGeometry(solid, { smooth: smooth ?? style === "round" });+ } finally {+ solid.delete();}+ } finally {+ for (const p of parts)+ p.delete();}- return findings;}-function evaluateCharacterAdvisoryQa(context) {- if (context.intent.category !== "character" || !(context.scene instanceof THREE5.Object3D)) {- return [];+function circleProfile(radius, segments = 24, center = [0, 0]) {+ assertPositive(radius, "circleProfile: radius");+ if (!Number.isInteger(segments) || segments < 3) {+ throw new Error(`circleProfile: segments must be an integer >= 3 (got ${segments}).`);}- const root = context.scene;- const clips = locomotionClips(context);- return [- ...bilateralSymmetryFindings(context, root),- ...restChainFindings(context, root),- ...forwardMarkerFindings(context, root),- ...lateralEnergyFindings(context, root, clips),- ...phaseOppositionFindings(context, root, clips),- ...bendDirectionFindings(context, root, clips),- ...footSlideFindings(context, root, clips)- ].sort((a, b) => `${a.code}:${a.affected?.nodePath ?? ""}:${a.affected?.clip ?? ""}`.localeCompare(`${b.code}:${b.affected?.nodePath ?? ""}:${b.affected?.clip ?? ""}`));+ const out = [];+ for (let i = 0;i < segments; i++) {+ const t = i / segments * Math.PI * 2;+ out.push([center[0] + Math.cos(t) * radius, center[1] + Math.sin(t) * radius]);+ }+ return out;}-var SKELETON_VIEWS, MOTION_VIEWS, REST_SYMMETRY_RATIO = 0.08, REST_ORDER_RATIO = 0.01, FORWARD_ANGLE_DEGREES = 45, LATERAL_ENERGY_RATIO = 1.5, PHASE_CORRELATION_THRESHOLD = 0.25, REVERSE_BEND_DEGREES = 15, FOOT_SLIDE_RATIO = 0.05, SAMPLE_FRACTIONS, BIPED_CHAINS, QUADRUPED_CHAINS, CHARACTER_ADVISORY_QA_RULE;-var init_character_advisory = __esm(() => {- init_character();- init_registry();- SKELETON_VIEWS = ["character.skeleton.front", "character.skeleton.right"];- MOTION_VIEWS = ["character.motion-strip.front", "character.motion-strip.right"];- SAMPLE_FRACTIONS = [0, 0.25, 0.5, 0.75, 1];- BIPED_CHAINS = [- ["shoulder.left", "elbow.left", "wrist.left"],- ["shoulder.right", "elbow.right", "wrist.right"],- ["hip.left", "knee.left", "ankle.left"],- ["hip.right", "knee.right", "ankle.right"]- ];- QUADRUPED_CHAINS = [- ["shoulder.fore.left", "elbow.fore.left", "paw.fore.left"],- ["shoulder.fore.right", "elbow.fore.right", "paw.fore.right"],- ["hip.hind.left", "knee.hind.left", "paw.hind.left"],- ["hip.hind.right", "knee.hind.right", "paw.hind.right"]- ];- CHARACTER_ADVISORY_QA_RULE = Object.freeze({- id: "CHARACTER_ADVISORY_PROFILE",- profile: "character.advisory",- scope: { kind: "category", category: "character" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: evaluateCharacterAdvisoryQa- });+var JOIN_FOR_STYLE;+var init_profile = __esm(() => {+ init_solids();+ init_authoring_diagnostic();+ JOIN_FOR_STYLE = {+ round: "Round",+ chamfer: "Square"+ };});-// src/vehicle.ts-import * as THREE6 from "three";-function assertId(value, name) {- if (!ID_PATTERN.test(value))- throw new TypeError(`${name} must be a stable identifier`);- return value;-}-function positive(value, name) {- if (!Number.isFinite(value) || value <= 0)- throw new RangeError(`${name} must be finite and > 0`);- return value;-}-function normalizedQuaternion(value) {- const source = value ?? [0, 0, 0, 1];- const length2 = Math.hypot(source[0], source[1], source[2], source[3]);- if (!Number.isFinite(length2) || length2 <= 0.000000001)- throw new TypeError("socket rotation must be a finite quaternion");- return [source[0] / length2, source[1] / length2, source[2] / length2, source[3] / length2];-}-function semantic2(roles, options = {}) {- return {- roles,- relationships: options.relationships ?? [],- frames: options.frames ?? [],- sockets: options.sockets ?? []+// src/textures.ts+import * as THREE9 from "three";+async function loadTexture(source, opts = {}) {+ let bytes;+ if (typeof source === "string") {+ const fs = await import("node:fs");+ const path = await import("node:path");+ const abs = path.isAbsolute(source) ? source : path.resolve(source);+ bytes = new Uint8Array(fs.readFileSync(abs));+ } else if (typeof Buffer !== "undefined" && Buffer.isBuffer(source)) {+ bytes = new Uint8Array(source);+ } else {+ bytes = source;+ }+ const mime = sniffMime(bytes);+ const sharp = (await import("sharp")).default;+ const img = sharp(bytes);+ const meta = await img.metadata();+ const { data } = await img.ensureAlpha().raw({ depth: "uchar" }).toBuffer({ resolveWithObject: true });+ if (!meta.width || !meta.height) {+ throw new Error("loadTexture: could not read image dimensions");+ }+ const tex = new THREE9.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE9.RGBAFormat, THREE9.UnsignedByteType);+ const usage = opts.usage ?? "albedo";+ const colorSpace = usage === "albedo" || usage === "emissive" ? "srgb" : "linear";+ let hasAlpha = false;+ for (let offset = 3;offset < data.length; offset += 4) {+ if ((data[offset] ?? 255) < 255) {+ hasAlpha = true;+ break;+ }+ }+ tex.colorSpace = colorSpace === "srgb" ? THREE9.SRGBColorSpace : THREE9.NoColorSpace;+ if (opts.name)+ tex.name = opts.name;+ tex.needsUpdate = true;+ tex.wrapS = THREE9.RepeatWrapping;+ tex.wrapT = THREE9.RepeatWrapping;+ tex.minFilter = THREE9.LinearMipmapLinearFilter;+ tex.magFilter = THREE9.LinearFilter;+ tex.generateMipmaps = true;+ tex.userData["encoded"] = {+ mime,+ bytes};-}-function socketRole(kind, id) {- if (kind === "chassis")- return KILN_SEMANTIC_ROLES.chassisMain;- return semanticRole(SOCKET_ROLE_BASE[kind], id);-}-function createTypedSocket(kind, input, parent) {- const id = assertId(input.id, `${kind} socket id`);- if (!input.position.every(Number.isFinite))- throw new TypeError(`${kind}.${id} position must be finite`);- const rotation = normalizedQuaternion(input.rotation);- const node = new THREE6.Object3D;- node.name = `Socket_${kind}_${id}`;- node.position.set(...input.position);- node.quaternion.set(...rotation);- const socket = {- id,- type: `vehicle.${kind}`,- frame: "socket",- compatibleTypes: [...input.compatibleTypes ?? [`vehicle.${kind}`]]+ tex.userData["kilnTexture"] = {+ usage,+ colorSpace,+ width: meta.width,+ height: meta.height,+ hasAlpha};- stampSemanticMetadataV1(node, semantic2([semanticRole(KILN_SEMANTIC_ROLES.socket, kind, id), socketRole(kind, id)], {- frames: [{ id: "socket", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],- sockets: [socket],- relationships: [- { kind: "owned-by", target: KILN_SEMANTIC_ROLES.vehicleFrame, targetType: "role" }- ]- }));- parent.add(node);- return node;+ return tex;}-function createVehicleFrame(name, options = {}) {- const root = new THREE6.Object3D;- root.name = name;- stampSemanticMetadataV1(root, semantic2([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {- frames: [- { id: "origin", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },- { id: "forward.+x", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },- { id: "up.+y", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },- { id: "right.+z", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }- ]- }));- if (options.parent)- options.parent.add(root);- const chassis = createTypedSocket("chassis", options.chassis ?? { id: "main", position: [0, 0, 0] }, root);- const build = (kind, values) => (values ?? []).map((value) => createTypedSocket(kind, value, root));- return {- root,- chassis,- axles: build("axle", options.axles),- seats: build("seat", options.seats),- contacts: build("contact", options.contacts),- steering: build("steering", options.steering),- propulsion: build("propulsion", options.propulsion)- };+function sniffMime(bytes) {+ if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {+ return "image/png";+ }+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {+ return "image/jpeg";+ }+ if (bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80) {+ return "image/webp";+ }+ return "image/png";}-function cylinderZ(radius, width, segments = 16) {- const geometry = new THREE6.CylinderGeometry(radius, radius, width, segments);- geometry.rotateX(Math.PI / 2);- return geometry;+function textureMetadata(texture) {+ return texture.userData["kilnTexture"];}-function createWheelGeometrySet(radius, width) {- positive(radius, "radius");- positive(width, "width");- if (width >= radius * 2)- throw new RangeError("wheel width must be less than its diameter");- const tube = width / 2;- return {- tire: new THREE6.TorusGeometry(radius - tube, tube, 8, 20),- rim: cylinderZ(radius * 0.68, width * 0.8),- hub: cylinderZ(radius * 0.34, width * 0.94)- };+function requireTextureUsage(texture, usage) {+ const meta = textureMetadata(texture);+ if (meta && meta.usage !== usage) {+ throw new TypeError(`Texture ${JSON.stringify(texture.name || "(unnamed)")} was loaded for ${meta.usage}, not ${usage}.`);+ }+ texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE9.SRGBColorSpace : THREE9.NoColorSpace;}-function createWheelAssembly(name, materials, options) {- const radius = positive(options.radius, "radius");- const width = positive(options.width, "width");- const rimRadius = positive(options.rimRadius ?? radius * 0.68, "rimRadius");- const hubRadius = positive(options.hubRadius ?? radius * 0.34, "hubRadius");- const rimWidth = positive(options.rimWidth ?? width * 0.8, "rimWidth");- const hubWidth = positive(options.hubWidth ?? width * 0.94, "hubWidth");- if (rimRadius >= radius || hubRadius >= rimRadius)- throw new RangeError("wheel radii must satisfy hub < rim < tire");- if (rimWidth > width || hubWidth > width)- throw new RangeError("rim/hub width must not exceed tire width");- const index = assertId(String(options.index), "wheel index");- const key = `${options.side}.${index}`;- const parent = options.parent;- const root = new THREE6.Object3D;- root.name = `${name}_Assembly_${options.side}_${index}`;- let steeringPivot;- if (options.steering) {- steeringPivot = new THREE6.Object3D;- steeringPivot.name = `SteeringPivot_${options.side}_${index}`;- steeringPivot.position.set(...options.position ?? [0, 0, 0]);- stampSemanticMetadataV1(steeringPivot, semantic2([semanticRole(ROLE.steeringPivot, key)], {- frames: [{ id: "steering-axis.+y", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],- relationships: [- { kind: "steers", target: semanticRole(ROLE.wheelAssembly, key), targetType: "role" }- ]- }));- root.add(steeringPivot);+function pbrMaterial(opts = {}) {+ const mat = new THREE9.MeshStandardMaterial;+ const isTex = (v) => !!v?.isTexture;+ if (isTex(opts.albedo)) {+ requireTextureUsage(opts.albedo, "albedo");+ mat.map = opts.albedo;+ mat.color = new THREE9.Color(16777215);+ } else if (opts.albedo !== undefined) {+ mat.color = new THREE9.Color(opts.albedo);}- const spinPivot = new THREE6.Object3D;- spinPivot.name = `WheelPivot_${options.side}_${index}`;- if (!steeringPivot)- spinPivot.position.set(...options.position ?? [0, 0, 0]);- stampSemanticMetadataV1(spinPivot, semantic2([- semanticRole(ROLE.wheelAssembly, key),- semanticRole(ROLE.wheelPivot, key),- ...options.loadBearing === false ? [] : [semanticRole(ROLE.wheelLoadBearing, key)]- ], {- frames: [- { id: "axle-center", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },- { id: "spin-axis.+z", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }- ],- relationships: [- { kind: "mounted-on", target: semanticRole(ROLE.axle, index), targetType: "role" },- { kind: "contains", target: semanticRole(ROLE.wheelTire, key), targetType: "role" },- { kind: "contains", target: semanticRole(ROLE.wheelRim, key), targetType: "role" },- { kind: "contains", target: semanticRole(ROLE.wheelHub, key), targetType: "role" }- ]- }));- (steeringPivot ?? root).add(spinPivot);- const defaults = createWheelGeometrySet(radius, width);- const tire = new THREE6.Mesh(options.geometries?.tire ?? defaults.tire, materials.tire);- const rim = new THREE6.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);- const hub = new THREE6.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);- tire.name = `Tire_${options.side}_${index}`;- rim.name = `Rim_${options.side}_${index}`;- hub.name = `Hub_${options.side}_${index}`;- stampSemanticMetadataV1(tire, semantic2([semanticRole(ROLE.wheelTire, key)], {- relationships: [- { kind: "descends-from", target: semanticRole(ROLE.wheelPivot, key), targetType: "role" }- ]- }));- stampSemanticMetadataV1(rim, semantic2([semanticRole(ROLE.wheelRim, key)], {- relationships: [- { kind: "contained-by", target: semanticRole(ROLE.wheelTire, key), targetType: "role" }- ]- }));- stampSemanticMetadataV1(hub, semantic2([semanticRole(ROLE.wheelHub, key)], {- relationships: [- { kind: "contained-by", target: semanticRole(ROLE.wheelRim, key), targetType: "role" }- ]- }));- spinPivot.add(tire, rim, hub);- const contact = new THREE6.Object3D;- contact.name = `Contact_${options.side}_${index}`;- contact.position.y = -radius;- stampSemanticMetadataV1(contact, semantic2([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {- frames: [{ id: "contact", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],- relationships: [{ kind: "supports", target: ROLE.vehicleFrame, targetType: "role" }]- }));- spinPivot.add(contact);- if (parent)- parent.add(root);- return {- root,- ...steeringPivot ? { steeringPivot } : {},- spinPivot,- tire,- rim,- hub,- contact,- radius,- width,- side: options.side,- index,- spinAxis: VEHICLE_AXES.wheelAxle+ if (opts.normal) {+ requireTextureUsage(opts.normal, "normal");+ mat.normalMap = opts.normal;+ }+ const roughnessTexture = isTex(opts.roughness) ? opts.roughness : undefined;+ const metalnessTexture = isTex(opts.metalness) ? opts.metalness : undefined;+ if (opts.metallicRoughness && (roughnessTexture || metalnessTexture)) {+ throw new TypeError("Use metallicRoughness for the packed G/B map; do not also pass texture-valued roughness/metalness.");+ }+ if (roughnessTexture && metalnessTexture && roughnessTexture !== metalnessTexture) {+ throw new TypeError("Separate roughness and metalness textures are ambiguous in glTF. Pack G=roughness/B=metalness and pass metallicRoughness.");+ }+ if (roughnessTexture && !metalnessTexture || !roughnessTexture && metalnessTexture) {+ throw new TypeError("A texture-valued roughness or metalness must be the same packed G/B texture in both slots, or use metallicRoughness.");+ }+ const packedMr = opts.metallicRoughness ?? roughnessTexture;+ if (packedMr) {+ requireTextureUsage(packedMr, "metallicRoughness");+ mat.roughnessMap = packedMr;+ mat.metalnessMap = packedMr;+ }+ if (typeof opts.roughness === "number") {+ mat.roughness = opts.roughness;+ } else if (packedMr) {+ mat.roughness = 1;+ } else {+ mat.roughness = 0.8;+ }+ if (typeof opts.metalness === "number") {+ mat.metalness = opts.metalness;+ } else if (packedMr) {+ mat.metalness = 1;+ }+ if (isTex(opts.emissive)) {+ requireTextureUsage(opts.emissive, "emissive");+ mat.emissiveMap = opts.emissive;+ mat.emissive = new THREE9.Color(16777215);+ } else if (opts.emissive !== undefined) {+ mat.emissive = new THREE9.Color(opts.emissive);+ }+ if (opts.emissiveIntensity !== undefined) {+ mat.emissiveIntensity = opts.emissiveIntensity;+ }+ if (opts.aoMap) {+ requireTextureUsage(opts.aoMap, "occlusion");+ mat.aoMap = opts.aoMap;+ }+ if (opts.aoMapIntensity !== undefined)+ mat.aoMapIntensity = opts.aoMapIntensity;+ const alphaMode = opts.alphaMode ?? "opaque";+ if (alphaMode !== "opaque" && alphaMode !== "mask" && alphaMode !== "blend") {+ throw new TypeError('alphaMode must be one of "opaque", "mask", or "blend".');+ }+ if (opts.doubleSided !== undefined && typeof opts.doubleSided !== "boolean") {+ throw new TypeError("doubleSided must be a boolean when provided.");+ }+ if (opts.alphaCutoff !== undefined && alphaMode !== "mask") {+ throw new TypeError('alphaCutoff is valid only when alphaMode is "mask".');+ }+ if (opts.alphaCutoff !== undefined && (!Number.isFinite(opts.alphaCutoff) || opts.alphaCutoff < 0 || opts.alphaCutoff > 1)) {+ throw new RangeError("alphaCutoff must be a finite number in [0,1].");+ }+ if (alphaMode === "mask") {+ mat.alphaTest = opts.alphaCutoff ?? 0.5;+ mat.transparent = false;+ } else if (alphaMode === "blend") {+ mat.alphaTest = 0;+ mat.transparent = true;+ }+ if (opts.doubleSided)+ mat.side = THREE9.DoubleSide;+ mat.userData["kilnMaterial"] = {+ alphaMode,+ ...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},+ doubleSided: opts.doubleSided === true};+ return mat;}-function roles(node) {- return readSemanticMetadataV1(node)?.roles ?? [];-}-function descendantWithRole(root, prefix) {- let found;- root.traverse((node) => {- if (!found && roles(node).some((role) => role.startsWith(prefix)))- found = node;+function foliageMaterial(albedo, opts = {}) {+ return pbrMaterial({+ albedo,+ roughness: opts.roughness ?? 0.9,+ metalness: 0,+ alphaMode: "mask",+ alphaCutoff: opts.alphaCutoff ?? 0.5,+ doubleSided: opts.doubleSided ?? true});- return found;}-function ancestorWithRole(node, prefix) {- let current = node.parent;- while (current) {- if (roles(current).some((role) => role.startsWith(prefix)))- return current;- current = current.parent;+var TEXTURE_USAGES;+var init_textures = __esm(() => {+ TEXTURE_USAGES = [+ "albedo",+ "emissive",+ "normal",+ "roughness",+ "metalness",+ "metallicRoughness",+ "occlusion"+ ];+});++// src/procedural-material-v2.ts+function strictRecord(value, path) {+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ throw new ProceduralTextureError(`${path} must be a plain JSON object.`);}- return;+ const prototype = Object.getPrototypeOf(value);+ if (prototype !== Object.prototype && prototype !== null) {+ throw new ProceduralTextureError(`${path} must be a plain JSON object with no custom prototype.`);+ }+ for (const key of Reflect.ownKeys(value)) {+ if (typeof key !== "string") {+ throw new ProceduralTextureError(`${path} must not contain symbol keys.`);+ }+ if (FORBIDDEN_KEYS.has(key)) {+ throw new ProceduralTextureError(`${path} contains forbidden key ${JSON.stringify(key)}.`);+ }+ if (!Object.prototype.propertyIsEnumerable.call(value, key)) {+ throw new ProceduralTextureError(`${path}.${key} must be an enumerable JSON field.`);+ }+ const descriptor = Object.getOwnPropertyDescriptor(value, key);+ if (!descriptor || !("value" in descriptor)) {+ throw new ProceduralTextureError(`${path}.${key} must be a plain JSON data field.`);+ }+ }+ return value;}-function parseWheelRole(role) {- const parts = role.split(".");- const side = parts.at(-2);- return {- ...side === "left" || side === "right" ? { side } : {},- ...parts.at(-1) ? { index: parts.at(-1) } : {}- };+function strictArray(value, path) {+ if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) {+ throw new ProceduralTextureError(`${path} must be a plain JSON array.`);+ }+ for (const key of Reflect.ownKeys(value)) {+ if (typeof key !== "string") {+ throw new ProceduralTextureError(`${path} must not contain symbol keys.`);+ }+ if (key === "length")+ continue;+ if (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length) {+ throw new ProceduralTextureError(`${path} has non-index JSON array key ${JSON.stringify(key)}.`);+ }+ }+ for (let index = 0;index < value.length; index++) {+ if (!Object.hasOwn(value, index)) {+ throw new ProceduralTextureError(`${path} must be a dense JSON array (missing index ${index}).`);+ }+ }+ return value;}-function objectBoundsInFrame(object, frame) {- object.updateWorldMatrix(true, true);- frame.updateWorldMatrix(true, false);- const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE6.Box3;- let found = false;- object.traverse((node) => {- if (!(node instanceof THREE6.Mesh) || !(node.geometry instanceof THREE6.BufferGeometry))- return;- node.geometry.computeBoundingBox();- const local = node.geometry.boundingBox;- if (!local)- return;- const matrix = worldToFrame.clone().multiply(node.matrixWorld);- for (const x of [local.min.x, local.max.x])- for (const y of [local.min.y, local.max.y])- for (const z3 of [local.min.z, local.max.z]) {- bounds.expandByPoint(new THREE6.Vector3(x, y, z3).applyMatrix4(matrix));- found = true;- }- });- return found ? bounds : undefined;+function assertKeys(record, allowed, path) {+ const allow = new Set(allowed);+ for (const key of Object.keys(record)) {+ if (!allow.has(key)) {+ throw new ProceduralTextureError(`${path} has unknown key ${JSON.stringify(key)}.`);+ }+ }}-function dimensions(object, frame) {- if (!object)- return;- const bounds = objectBoundsInFrame(object, frame);- if (!bounds)- return;- const size = bounds.getSize(new THREE6.Vector3);- return {- center: bounds.getCenter(new THREE6.Vector3),- radius: Math.max(size.x, size.y) / 2,- width: size.z- };+function color(value, path) {+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 16777215) {+ throw new ProceduralTextureError(`${path} must be a color integer between 0x000000 and 0xffffff, got ${JSON.stringify(value)}.`);+ }+ return value;}-function resolved(source, id, root, pivot, parts) {- pivot.updateWorldMatrix(true, false);- const tire = dimensions(parts.tire, pivot);- const rim = dimensions(parts.rim, pivot);- const hub = dimensions(parts.hub, pivot);- const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE6.Vector3;- const toWorld = (value) => value.clone().applyMatrix4(pivot.matrixWorld);- return {- id,- source,- ...parts.side ? { side: parts.side } : {},- ...parts.index ? { index: parts.index } : {},- root,- pivot,- ...parts.steeringPivot ? { steeringPivot: parts.steeringPivot } : {},- ...parts.tire ? { tire: parts.tire } : {},- ...parts.rim ? { rim: parts.rim } : {},- ...parts.hub ? { hub: parts.hub } : {},- ...parts.contact ? { contact: parts.contact } : {},- centerWorld: toWorld(centerLocal),- pivotCenterWorld: new THREE6.Vector3().setFromMatrixPosition(pivot.matrixWorld),- ...tire ? { tireCenterWorld: toWorld(tire.center) } : {},- ...rim ? { rimCenterWorld: toWorld(rim.center) } : {},- ...hub ? { hubCenterWorld: toWorld(hub.center) } : {},- spinAxisWorld: new THREE6.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),- ...tire ? { radius: tire.radius, width: tire.width } : {},- ...rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {},- ...hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {},- loadBearing: hasSemanticRole(roles(pivot), ROLE.wheelLoadBearing)- };+function integer(value, path, fallback, min, max) {+ if (value === undefined)+ return fallback;+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {+ throw new ProceduralTextureError(`${path} must be a whole number between ${min} and ${max}, got ${JSON.stringify(value)}.`);+ }+ return value;}-function semanticAssemblies(root) {- const result = [];- root.traverse((node) => {- const assemblyRole = roles(node).find((role) => semanticRoleMatches(role, ROLE.wheelAssembly));- if (!assemblyRole)- return;- const parsed = parseWheelRole(assemblyRole);- result.push(resolved("semantic", assemblyRole, node, node, {- ...parsed,- tire: descendantWithRole(node, `${ROLE.wheelTire}.`),- rim: descendantWithRole(node, `${ROLE.wheelRim}.`),- hub: descendantWithRole(node, `${ROLE.wheelHub}.`),- contact: descendantWithRole(node, `${ROLE.wheelContact}.`),- steeringPivot: ancestorWithRole(node, `${ROLE.steeringPivot}.`)- }));- });- return result;+function finite2(value, path, fallback, min, max) {+ if (value === undefined)+ return fallback;+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {+ throw new ProceduralTextureError(`${path} must be a finite number between ${min} and ${max}, got ${JSON.stringify(value)}.`);+ }+ return value;}-function legacyCorner(name) {- const value = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");- if (!/(wheel|tire|rim|hub)/.test(value))- return;- const side = /(?:left|(^|-)l($|-)|fl|rl)/.test(value) ? "left" : /(?:right|(^|-)r($|-)|fr|rr)/.test(value) ? "right" : undefined;- const index = /(?:front|(^|-)f($|-)|fl|fr)/.test(value) ? "front" : /(?:rear|back|(^|-)r[lr]($|-)|rl|rr)/.test(value) ? "rear" : value.match(/\d+/)?.[0];- return {- key: `${side ?? "unknown"}.${index ?? value}`,- ...side ? { side } : {},- ...index ? { index } : {}- };+function unit(value, path, fallback) {+ return finite2(value, path, fallback, 0, 1);}-function legacyAssemblies(root) {- const groups = new Map;- root.traverse((node) => {- const corner = legacyCorner(node.name);- if (!corner)- return;- const entry = groups.get(corner.key) ?? {- ...corner.side ? { side: corner.side } : {},- ...corner.index ? { index: corner.index } : {}- };- const lower = node.name.toLowerCase();- if (lower.includes("pivot"))- entry.pivot = node;- else if (lower.includes("rim"))- entry.rim = node;- else if (lower.includes("hub"))- entry.hub = node;- else- entry.tire = node;- groups.set(corner.key, entry);- });- return [...groups.entries()].map(([key, parts]) => {- const pivot = parts.pivot ?? parts.tire?.parent ?? parts.rim?.parent ?? parts.hub?.parent ?? root;- return resolved("legacy", key, pivot, pivot, parts);+function optionalName(value, path) {+ if (value === undefined)+ return;+ const hasControlCharacter = typeof value === "string" && [...value].some((character) => {+ const code = character.charCodeAt(0);+ return code < 32 || code === 127;});+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_PROCEDURAL_NAME_LENGTH || hasControlCharacter) {+ throw new ProceduralTextureError(`${path} must be 1..${MAX_PROCEDURAL_NAME_LENGTH} visible characters.`);+ }+ return value;}-function resolveVehicleWheelAssemblies(root) {- const semantic3 = semanticAssemblies(root);- return semantic3.length > 0 ? semantic3 : legacyAssemblies(root);+function usage(value, path, fallback) {+ if (value === undefined)+ return fallback;+ if (!TEXTURE_USAGES.includes(value)) {+ throw new ProceduralTextureError(`${path} must be one of ${TEXTURE_USAGES.join(", ")}, got ${JSON.stringify(value)}.`);+ }+ return value;}-function hasCanonicalVehicleFront(root) {- let found = false;- root.traverse((node) => {- const metadata = readSemanticMetadataV1(node);- if (metadata?.roles.includes(ROLE.vehicleFrame) && metadata.roles.includes(ROLE.vehicleForward) && metadata.frames.some((frame) => frame.id === "forward.+x")) {- found = true;- }- });- return found;+function angle(value, path) {+ const bounded = finite2(value, path, 0, -36000, 36000);+ const normalized = (bounded % 360 + 360) % 360;+ return Object.is(normalized, -0) ? 0 : normalized;}-var ROLE, VEHICLE_AXES, ID_PATTERN, SOCKET_ROLE_BASE;-var init_vehicle = __esm(() => {- init_contracts();- ROLE = KILN_SEMANTIC_ROLES;- VEHICLE_AXES = Object.freeze({- forward: Object.freeze([1, 0, 0]),- up: Object.freeze([0, 1, 0]),- right: Object.freeze([0, 0, 1]),- wheelAxle: Object.freeze([0, 0, 1])- });- ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;- SOCKET_ROLE_BASE = Object.freeze({- chassis: KILN_SEMANTIC_ROLES.chassis,- axle: KILN_SEMANTIC_ROLES.axle,- seat: KILN_SEMANTIC_ROLES.seat,- contact: KILN_SEMANTIC_ROLES.contact,- steering: KILN_SEMANTIC_ROLES.steering,- propulsion: KILN_SEMANTIC_ROLES.propulsion- });-});--// src/qa/geometry-relations.ts-function createProbeLocalFrame3(input) {- if (!input.id.trim())- throw new TypeError("Probe frame ID must be non-empty.");- if (!finiteVector(input.origin))- throw new TypeError("Probe frame origin must be finite.");- const basis = [input.xAxis, input.yAxis, input.zAxis];- for (const [index, value] of basis.entries()) {- if (!finiteVector(value) || Math.abs(length2(value) - 1) > 0.000001) {- throw new TypeError(`Probe frame axis ${index} must be finite and normalized within 1e-6.`);- }+function blend(record, path) {+ const value = record["blend"] ?? "normal";+ if (!BLENDS.includes(value)) {+ throw new ProceduralTextureError(`${path}.blend ${JSON.stringify(value)} is not one of ${BLENDS.join(", ")}.`);}- if (Math.abs(dot3(input.xAxis, input.yAxis)) > 0.000001 || Math.abs(dot3(input.xAxis, input.zAxis)) > 0.000001 || Math.abs(dot3(input.yAxis, input.zAxis)) > 0.000001 || dot3(cross2(input.xAxis, input.yAxis), input.zAxis) < 1 - 0.000001) {- throw new TypeError("Probe frame axes must be orthonormal and right-handed.");+ return value;+}+function canonicalLayer(value, index) {+ const path = `proceduralTexture.layers[${index}]`;+ const record = strictRecord(value, path);+ const op = record["op"];+ if (!OPS.includes(op)) {+ throw new ProceduralTextureError(`${path}.op ${JSON.stringify(op)} is not one of ${OPS.join(", ")}.`);+ }+ const validatedBlend = blend(record, path);+ const validatedOpacity = unit(record["opacity"], `${path}.opacity`, 1);+ const common = {+ blend: index === 0 ? "normal" : validatedBlend,+ opacity: index === 0 ? 1 : validatedOpacity+ };+ switch (op) {+ case "solid":+ assertKeys(record, ["op", "color", "blend", "opacity"], path);+ return { op, color: color(record["color"], `${path}.color`), ...common };+ case "checker":+ assertKeys(record, ["op", "colorA", "colorB", "squares", "blend", "opacity"], path);+ return {+ op,+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ squares: integer(record["squares"], `${path}.squares`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ ...common+ };+ case "stripes":+ assertKeys(record, ["op", "colorA", "colorB", "count", "angleDeg", "blend", "opacity"], path);+ return {+ op,+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ count: integer(record["count"], `${path}.count`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ angleDeg: angle(record["angleDeg"], `${path}.angleDeg`),+ ...common+ };+ case "gradient":+ assertKeys(record, ["op", "from", "to", "angleDeg", "blend", "opacity"], path);+ return {+ op,+ from: color(record["from"], `${path}.from`),+ to: color(record["to"], `${path}.to`),+ angleDeg: angle(record["angleDeg"], `${path}.angleDeg`),+ ...common+ };+ case "bricks":+ assertKeys(record, ["op", "brick", "mortar", "rows", "cols", "mortarWidth", "stagger", "blend", "opacity"], path);+ return {+ op,+ brick: color(record["brick"], `${path}.brick`),+ mortar: color(record["mortar"], `${path}.mortar`),+ rows: integer(record["rows"], `${path}.rows`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ cols: integer(record["cols"], `${path}.cols`, 4, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ mortarWidth: unit(record["mortarWidth"], `${path}.mortarWidth`, 0.06),+ stagger: unit(record["stagger"], `${path}.stagger`, 0.5),+ ...common+ };+ case "noise":+ assertKeys(record, ["op", "colorA", "colorB", "scale", "octaves", "seed", "blend", "opacity"], path);+ return {+ op,+ colorA: color(record["colorA"], `${path}.colorA`),+ colorB: color(record["colorB"], `${path}.colorB`),+ scale: integer(record["scale"], `${path}.scale`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),+ octaves: integer(record["octaves"], `${path}.octaves`, 3, 1, MAX_NOISE_OCTAVES),+ seed: integer(record["seed"], `${path}.seed`, 0, -2147483648, 2147483647),+ ...common+ };+ default:+ throw new ProceduralTextureError(`${path}.op is unsupported.`);+ }+}+function migrateProceduralTextureSpecV1(input) {+ const record = strictRecord(input, "proceduralTexture");+ assertKeys(record, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");+ if (record["schemaVersion"] !== undefined && record["schemaVersion"] !== 1) {+ throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(record["schemaVersion"])}.`);}return {- id: input.id,- origin: stableVector(input.origin),- xAxis: stableVector(input.xAxis),- yAxis: stableVector(input.yAxis),- zAxis: stableVector(input.zAxis)+ schemaVersion: 2,+ ...record["size"] !== undefined ? { size: record["size"] } : {},+ ...record["usage"] !== undefined ? { usage: record["usage"] } : {},+ ...record["name"] !== undefined ? { name: record["name"] } : {},+ layers: record["layers"]};}-function probeLocalFrameFromQuaternion(id, origin, quaternion) {- if (!quaternion.every((component) => Number.isFinite(component))) {- throw new TypeError("Probe frame quaternion must be finite.");+function canonicalizeProceduralTextureSpecV2(input) {+ const initial = strictRecord(input, "proceduralTexture");+ const source = initial["schemaVersion"] === undefined || initial["schemaVersion"] === 1 ? strictRecord(migrateProceduralTextureSpecV1(initial), "proceduralTexture") : initial;+ assertKeys(source, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");+ if (source["schemaVersion"] !== 2) {+ throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 2, got ${JSON.stringify(source["schemaVersion"])}.`);}- const quaternionLength = Math.hypot(...quaternion);- if (Math.abs(quaternionLength - 1) > 0.000001) {- throw new TypeError("Probe frame quaternion must be normalized within 1e-6.");+ const size = source["size"] ?? 256;+ if (typeof size !== "number" || !Number.isInteger(size) || size < MIN_PROCEDURAL_SIZE || size > MAX_PROCEDURAL_SIZE || (size & size - 1) !== 0) {+ throw new ProceduralTextureError(`proceduralTexture.size must be a power of two between ${MIN_PROCEDURAL_SIZE} and ${MAX_PROCEDURAL_SIZE}, got ${JSON.stringify(source["size"])}.`);}- const [x, y, z3, w] = quaternion;- const xx = x * x;- const yy = y * y;- const zz = z3 * z3;- const xy = x * y;- const xz = x * z3;- const yz = y * z3;- const wx = w * x;- const wy = w * y;- const wz = w * z3;- return createProbeLocalFrame3({- id,- origin,- xAxis: [1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy)],- yAxis: [2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx)],- zAxis: [2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy)]- });-}-function createOrientedProbeBox3(input) {- if (!input.id.trim())- throw new TypeError("Oriented probe box ID must be non-empty.");- if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent2) => extent2 <= 0)) {- throw new TypeError("Oriented probe box half-extents must be finite and greater than zero.");+ const rawLayers = source["layers"];+ if (!Array.isArray(rawLayers) || rawLayers.length === 0) {+ throw new ProceduralTextureError("proceduralTexture.layers must be a non-empty array — the bottom layer is the base pattern.");+ }+ const layers = strictArray(rawLayers, "proceduralTexture.layers");+ if (layers.length > MAX_PROCEDURAL_LAYERS) {+ throw new ProceduralTextureError(`proceduralTexture: ${layers.length} layers exceeds the maximum of ${MAX_PROCEDURAL_LAYERS}.`);}+ const name = optionalName(source["name"], "proceduralTexture.name");return {- id: input.id,- frame: createProbeLocalFrame3(input.frame),- halfExtents: stableVector(input.halfExtents)+ schemaVersion: 2,+ size,+ usage: usage(source["usage"], "proceduralTexture.usage", "albedo"),+ ...name !== undefined ? { name } : {},+ layers: layers.map(canonicalLayer)};}-function worldPointToProbeLocal(frame, worldPoint) {- const offset = subtract2(worldPoint, frame.origin);- return stableVector([- dot3(offset, frame.xAxis),- dot3(offset, frame.yAxis),- dot3(offset, frame.zAxis)- ]);-}-function worldVectorToProbeLocal(frame, worldVector) {- return stableVector([- dot3(worldVector, frame.xAxis),- dot3(worldVector, frame.yAxis),- dot3(worldVector, frame.zAxis)- ]);-}-function projection(box, axisWorld) {- const center = dot3(box.frame.origin, axisWorld);- const radius = axes(box.frame).reduce((total, boxAxis, index) => total + Math.abs(dot3(boxAxis, axisWorld)) * box.halfExtents[index], 0);- return { min: center - radius, max: center + radius };+function canonicalJson(value) {+ if (value === null || typeof value !== "object")+ return JSON.stringify(value);+ if (Array.isArray(value))+ return `[${value.map(canonicalJson).join(",")}]`;+ const record = value;+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;}-function orientFromReferenceToSubject(axisWorld, subject, reference) {- return dot3(subtract2(subject.frame.origin, reference.frame.origin), axisWorld) < 0 ? scale(axisWorld, -1) : axisWorld;+function canonicalProceduralTextureJsonV2(input) {+ return canonicalJson(canonicalizeProceduralTextureSpecV2(input));}-function candidateSatAxes(subject, reference) {- const subjectAxes = axes(subject.frame);- const referenceAxes = axes(reference.frame);- const candidates = [];- const pushUnique = (rawAxis, label) => {- if (length2(rawAxis) <= EPSILON2)- return;- const axis = normalize2(rawAxis);- if (candidates.some((candidate) => Math.abs(dot3(candidate.axis, axis)) > 1 - 0.000000001))- return;- candidates.push({ axis, label });- };- for (let index = 0;index < 3; index++) {- pushUnique(referenceAxes[index], `reference.${["x", "y", "z"][index]}`);- }- for (let index = 0;index < 3; index++) {- pushUnique(subjectAxes[index], `subject.${["x", "y", "z"][index]}`);- }- for (let subjectIndex = 0;subjectIndex < 3; subjectIndex++) {- for (let referenceIndex = 0;referenceIndex < 3; referenceIndex++) {- pushUnique(cross2(subjectAxes[subjectIndex], referenceAxes[referenceIndex]), `cross.subject.${["x", "y", "z"][subjectIndex]}.reference.${["x", "y", "z"][referenceIndex]}`);+function sha256Hex(text) {+ const source = new TextEncoder().encode(text);+ const bitLength = source.length * 8;+ const paddedLength = Math.ceil((source.length + 9) / 64) * 64;+ const bytes = new Uint8Array(paddedLength);+ bytes.set(source);+ bytes[source.length] = 128;+ const view = new DataView(bytes.buffer);+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296), false);+ view.setUint32(paddedLength - 4, bitLength >>> 0, false);+ const h = new Uint32Array([+ 1779033703,+ 3144134277,+ 1013904242,+ 2773480762,+ 1359893119,+ 2600822924,+ 528734635,+ 1541459225+ ]);+ const w = new Uint32Array(64);+ for (let offset = 0;offset < bytes.length; offset += 64) {+ for (let i = 0;i < 16; i++)+ w[i] = view.getUint32(offset + i * 4, false);+ for (let i = 16;i < 64; i++) {+ const a = w[i - 15];+ const b = w[i - 2];+ const s0 = rotateRight(a, 7) ^ rotateRight(a, 18) ^ a >>> 3;+ const s1 = rotateRight(b, 17) ^ rotateRight(b, 19) ^ b >>> 10;+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;+ }+ let [a, b, c, d, e, f, g, hh] = h;+ for (let i = 0;i < 64; i++) {+ const s1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);+ const choice = e & f ^ ~e & g;+ const temp1 = hh + s1 + choice + SHA256_K[i] + w[i] >>> 0;+ const s0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);+ const majority = a & b ^ a & c ^ b & c;+ const temp2 = s0 + majority >>> 0;+ hh = g;+ g = f;+ f = e;+ e = d + temp1 >>> 0;+ d = c;+ c = b;+ b = a;+ a = temp1 + temp2 >>> 0;}+ const next = [a, b, c, d, e, f, g, hh];+ for (let i = 0;i < 8; i++)+ h[i] = h[i] + next[i] >>> 0;}- return candidates;+ return [...h].map((value) => value.toString(16).padStart(8, "0")).join("");}-function sat(subject, reference) {- let maximumSeparation = -Infinity;- let separatingAxis = reference.frame.xAxis;- let separatingLabel = "reference.x";- let minimumOverlap = Infinity;- let overlapAxis = reference.frame.xAxis;- let overlapLabel = "reference.x";- for (const candidate of candidateSatAxes(subject, reference)) {- const subjectProjection = projection(subject, candidate.axis);- const referenceProjection = projection(reference, candidate.axis);- const gap = Math.max(subjectProjection.min - referenceProjection.max, referenceProjection.min - subjectProjection.max);- if (gap > maximumSeparation) {- maximumSeparation = gap;- separatingAxis = candidate.axis;- separatingLabel = candidate.label;- }- const overlap = Math.min(subjectProjection.max, referenceProjection.max) - Math.max(subjectProjection.min, referenceProjection.min);- if (overlap < minimumOverlap) {- minimumOverlap = overlap;- overlapAxis = candidate.axis;- overlapLabel = candidate.label;+function hashProceduralTextureSpecV2(input) {+ return `sha256:${sha256Hex(canonicalProceduralTextureJsonV2(input))}`;+}+function canonicalTextureRef(value, slot) {+ const path = `portableMaterial.textures.${slot}`;+ const record = strictRecord(value, path);+ if (record["kind"] === "procedural") {+ assertKeys(record, ["kind", "spec"], path);+ const spec = canonicalizeProceduralTextureSpecV2(record["spec"]);+ const expected = MATERIAL_TEXTURE_USAGE[slot];+ if (spec.usage !== expected) {+ throw new ProceduralTextureError(`${path} requires procedural usage ${JSON.stringify(expected)}, got ${JSON.stringify(spec.usage)}.`);}+ return { kind: "procedural", spec };}- if (maximumSeparation > 0) {- return {- separation: stable2(maximumSeparation),- penetration: 0,- axisWorld: orientFromReferenceToSubject(separatingAxis, subject, reference),- axisLabel: separatingLabel- };+ if (record["kind"] === "resource") {+ assertKeys(record, ["kind", "resourceId"], path);+ const resourceId = record["resourceId"];+ if (typeof resourceId !== "string" || resourceId.length > 128 || !/^kiln\.[a-z0-9][a-z0-9._-]+$/.test(resourceId)) {+ throw new ProceduralTextureError(`${path}.resourceId must be a bounded kiln.* resource ID.`);+ }+ return { kind: "resource", resourceId };}- return {- separation: 0,- penetration: stable2(Math.max(0, minimumOverlap)),- axisWorld: orientFromReferenceToSubject(overlapAxis, subject, reference),- axisLabel: overlapLabel- };-}-function supportPoint(box, direction) {- let point = [...box.frame.origin];- axes(box.frame).forEach((boxAxis, index) => {- const projectionValue = dot3(boxAxis, direction);- if (Math.abs(projectionValue) <= EPSILON2)- return;- point = add(point, scale(boxAxis, Math.sign(projectionValue) * box.halfExtents[index]));- });- return stableVector(point);+ throw new ProceduralTextureError(`${path}.kind must be "procedural" or "resource".`);}-function evidence(subject, reference, points, axisWorld, axisLabel) {+function canonicalizePortableMaterialSpecV2(input) {+ const record = strictRecord(input, "portableMaterial");+ assertKeys(record, [+ "schemaVersion",+ "model",+ "name",+ "baseColor",+ "roughness",+ "metalness",+ "emissive",+ "emissiveIntensity",+ "alphaMode",+ "alphaCutoff",+ "doubleSided",+ "textures"+ ], "portableMaterial");+ if (record["schemaVersion"] !== 2) {+ throw new ProceduralTextureError("portableMaterial.schemaVersion must be 2.");+ }+ if (record["model"] !== "pbrMetallicRoughness") {+ throw new ProceduralTextureError('portableMaterial.model must be "pbrMetallicRoughness"; executable shader models are not portable.');+ }+ const textureInput = record["textures"] ?? {};+ const textureRecord = strictRecord(textureInput, "portableMaterial.textures");+ const slots = Object.keys(MATERIAL_TEXTURE_USAGE);+ assertKeys(textureRecord, slots, "portableMaterial.textures");+ if (Object.keys(textureRecord).length > MAX_PORTABLE_MATERIAL_TEXTURES) {+ throw new ProceduralTextureError(`portableMaterial has more than ${MAX_PORTABLE_MATERIAL_TEXTURES} texture slots.`);+ }+ const textures = {};+ let proceduralTexels = 0;+ for (const slot of slots) {+ if (textureRecord[slot] === undefined)+ continue;+ const ref = canonicalTextureRef(textureRecord[slot], slot);+ textures[slot] = ref;+ if (ref.kind === "procedural")+ proceduralTexels += ref.spec.size * ref.spec.size;+ }+ if (proceduralTexels > MAX_PORTABLE_MATERIAL_TEXELS) {+ throw new ProceduralTextureError(`portableMaterial procedural texture budget is ${proceduralTexels} texels, above ${MAX_PORTABLE_MATERIAL_TEXELS}.`);+ }+ const alphaMode = record["alphaMode"] ?? "opaque";+ if (alphaMode !== "opaque" && alphaMode !== "mask" && alphaMode !== "blend") {+ throw new ProceduralTextureError("portableMaterial.alphaMode must be opaque, mask, or blend.");+ }+ if (record["doubleSided"] !== undefined && typeof record["doubleSided"] !== "boolean") {+ throw new ProceduralTextureError("portableMaterial.doubleSided must be boolean.");+ }+ const name = optionalName(record["name"], "portableMaterial.name");return {- subjectId: subject.id,- referenceId: reference.id,- coordinateSpace: "reference-local",- referenceFrameId: reference.frame.id,- ...axisWorld ? { axis: worldVectorToProbeLocal(reference.frame, axisWorld) } : {},- ...axisLabel ? { axisLabel } : {},- points+ schemaVersion: 2,+ model: "pbrMetallicRoughness",+ ...name !== undefined ? { name } : {},+ ...record["baseColor"] !== undefined ? { baseColor: color(record["baseColor"], "portableMaterial.baseColor") } : {},+ roughness: unit(record["roughness"], "portableMaterial.roughness", 1),+ metalness: unit(record["metalness"], "portableMaterial.metalness", 0),+ ...record["emissive"] !== undefined ? { emissive: color(record["emissive"], "portableMaterial.emissive") } : {},+ emissiveIntensity: finite2(record["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),+ alphaMode,+ alphaCutoff: unit(record["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),+ doubleSided: record["doubleSided"] === true,+ textures};}-function satEvidencePoints(subject, reference, axisWorld) {- return [- {- label: `${reference.id}.support`,- position: worldPointToProbeLocal(reference.frame, supportPoint(reference, axisWorld))- },- {- label: `${subject.id}.support`,- position: worldPointToProbeLocal(reference.frame, supportPoint(subject, scale(axisWorld, -1)))+var MAX_PROCEDURAL_SIZE = 1024, MIN_PROCEDURAL_SIZE = 4, MAX_PROCEDURAL_LAYERS = 8, MAX_NOISE_OCTAVES = 6, MAX_PROCEDURAL_NAME_LENGTH = 80, MAX_PROCEDURAL_PATTERN_COUNT = 256, MAX_PORTABLE_MATERIAL_TEXTURES = 5, MAX_PORTABLE_MATERIAL_TEXELS, ProceduralTextureError, OPS, BLENDS, FORBIDDEN_KEYS, SHA256_K, rotateRight = (value, bits) => value >>> bits | value << 32 - bits, MATERIAL_TEXTURE_USAGE;+var init_procedural_material_v2 = __esm(() => {+ init_textures();+ MAX_PORTABLE_MATERIAL_TEXELS = 4 * 1024 * 1024;+ ProceduralTextureError = class ProceduralTextureError extends Error {+ constructor(message) {+ super(message);+ this.name = "ProceduralTextureError";}- ];-}-function probeOrientedPenetration(subject, reference, options = {}) {- const maxDepth = options.maxDepth ?? 0;- const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;- assertNonNegative(maxDepth, "maxDepth");- assertNonNegative(tolerance, "tolerance");- const relation = sat(subject, reference);- return {- relation: "penetration",- pass: relation.penetration <= maxDepth + tolerance,- measurements: {- penetrationDepth: relation.penetration,- separation: relation.separation,- maxDepth,- tolerance- },- evidence: evidence(subject, reference, satEvidencePoints(subject, reference, relation.axisWorld), relation.axisWorld, relation.axisLabel)- };-}-var EPSILON2 = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value) => value.length === 3 && value.every((component) => Number.isFinite(component)), add = (a, b) => [- a[0] + b[0],- a[1] + b[1],- a[2] + b[2]-], subtract2 = (a, b) => [- a[0] - b[0],- a[1] - b[1],- a[2] - b[2]-], scale = (value, amount) => [- value[0] * amount,- value[1] * amount,- value[2] * amount-], dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], cross2 = (a, b) => [- a[1] * b[2] - a[2] * b[1],- a[2] * b[0] - a[0] * b[2],- a[0] * b[1] - a[1] * b[0]-], length2 = (value) => Math.hypot(value[0], value[1], value[2]), normalize2 = (value) => {- const magnitude = length2(value);- if (magnitude <= EPSILON2)- throw new TypeError("Cannot normalize a zero-length probe axis.");- return scale(value, 1 / magnitude);-}, stable2 = (value) => {- if (Math.abs(value) < 0.0000000001)- return 0;- return Number(value.toFixed(9));-}, stableVector = (value) => [- stable2(value[0]),- stable2(value[1]),- stable2(value[2])-], assertNonNegative = (value, name) => {- if (!Number.isFinite(value) || value < 0) {- throw new TypeError(`${name} must be a finite non-negative number.`);- }-}, axes = (frame) => [- frame.xAxis,- frame.yAxis,- frame.zAxis-];--// src/qa/vehicle-advisory.ts-import * as THREE7 from "three";-function advisory2(context, value) {- return {- ...value,- disposition: "warn",- dimension: "categoryReadiness",- profile: context.intent.qaProfile,- viewHints: value.viewHints ?? [...VEHICLE_VIEWS]};+ OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise"];+ BLENDS = ["normal", "multiply", "screen", "overlay"];+ FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);+ SHA256_K = new Uint32Array([+ 1116352408,+ 1899447441,+ 3049323471,+ 3921009573,+ 961987163,+ 1508970993,+ 2453635748,+ 2870763221,+ 3624381080,+ 310598401,+ 607225278,+ 1426881987,+ 1925078388,+ 2162078206,+ 2614888103,+ 3248222580,+ 3835390401,+ 4022224774,+ 264347078,+ 604807628,+ 770255983,+ 1249150122,+ 1555081692,+ 1996064986,+ 2554220882,+ 2821834349,+ 2952996808,+ 3210313671,+ 3336571891,+ 3584528711,+ 113926993,+ 338241895,+ 666307205,+ 773529912,+ 1294757372,+ 1396182291,+ 1695183700,+ 1986661051,+ 2177026350,+ 2456956037,+ 2730485921,+ 2820302411,+ 3259730800,+ 3345764771,+ 3516065817,+ 3600352804,+ 4094571909,+ 275423344,+ 430227734,+ 506948616,+ 659060556,+ 883997877,+ 958139571,+ 1322822218,+ 1537002063,+ 1747873779,+ 1955562222,+ 2024104815,+ 2227730452,+ 2361852424,+ 2428436474,+ 2756734187,+ 3204031479,+ 3329325298+ ]);+ MATERIAL_TEXTURE_USAGE = {+ baseColor: "albedo",+ normal: "normal",+ metallicRoughness: "metallicRoughness",+ emissive: "emissive",+ occlusion: "occlusion"+ };+});++// src/procedural-texture.ts+import * as THREE10 from "three";+function hash2(x, y, seed) {+ let h = Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0;+ h = h ^ h >>> 13;+ h = Math.imul(h, 1274126177) | 0;+ h = h ^ h >>> 16;+ return (h >>> 0) / 4294967296;}-function localPoint(inverse, point) {- return point.clone().applyMatrix4(inverse);-}-function wheelPairs(wheels) {- const groups = new Map;- for (const wheel of wheels) {- if (!wheel.index)- continue;- const group = groups.get(wheel.index) ?? [];- group.push(wheel);- groups.set(wheel.index, group);- }- return [...groups.entries()].flatMap(([index, group]) => {- const left = group.find((wheel) => wheel.side === "left");- const right = group.find((wheel) => wheel.side === "right");- return left && right ? [[index, left, right]] : [];- });-}-function bilateralSymmetryFindings2(context, root, wheels) {- root.updateMatrixWorld(true);- const inverse = root.matrixWorld.clone().invert();- const findings = [];- for (const [index, left, right] of wheelPairs(wheels)) {- const a = localPoint(inverse, left.centerWorld);- const b = localPoint(inverse, right.centerWorld);- const centerDelta = Math.hypot(a.x - b.x, a.y - b.y, a.z + b.z);- const radiusDelta = Math.abs((left.radius ?? 0) - (right.radius ?? 0));- const widthDelta = Math.abs((left.width ?? 0) - (right.width ?? 0));- const scale2 = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(0.01, scale2 * SYMMETRY_RATIO);- const maximum = Math.max(centerDelta, radiusDelta, widthDelta);- if (maximum <= threshold)- continue;- const measurementName = maximum === centerDelta ? "bilateralCenterMirrorDelta" : maximum === radiusDelta ? "bilateralRadiusDelta" : "bilateralWidthDelta";- findings.push(advisory2(context, {- code: "VEH_BILATERAL_SYMMETRY",- message: `Axle ${index} left/right assemblies differ in center, radius, or width ` + `(center=${centerDelta.toFixed(6)}, radius=${radiusDelta.toFixed(6)}, width=${widthDelta.toFixed(6)} m).`,- affected: { node: right.root.name },- measurement: {- name: measurementName,- actual: maximum,- expected: 0,- threshold,- unit: "m"- }- }));- }- return findings;-}-function semanticRoles(node) {- return readSemanticMetadataV1(node)?.roles ?? [];+function valueNoise(u, v, period, seed) {+ const x = u * period;+ const y = v * period;+ const xi = Math.floor(x);+ const yi = Math.floor(y);+ const xf = x - xi;+ const yf = y - yi;+ const wrap = (n) => (n % period + period) % period;+ const x0 = wrap(xi);+ const y0 = wrap(yi);+ const x1 = wrap(xi + 1);+ const y1 = wrap(yi + 1);+ const sx = smoothstep(xf);+ const sy = smoothstep(yf);+ const n00 = hash2(x0, y0, seed);+ const n10 = hash2(x1, y0, seed);+ const n01 = hash2(x0, y1, seed);+ const n11 = hash2(x1, y1, seed);+ const top = n00 + sx * (n10 - n00);+ const bottom = n01 + sx * (n11 - n01);+ return top + sy * (bottom - top);}-function trackSide(node) {- for (const role of semanticRoles(node)) {- const match = role.match(/(?:track\.loop|support\.track|track\.road-wheel)\.(left|right)(?:\.|$)/);- if (match?.[1] === "left" || match?.[1] === "right")- return match[1];+function fbm(u, v, period, octaves, seed) {+ let sum = 0;+ let amplitude = 1;+ let total = 0;+ let p = period;+ for (let o = 0;o < octaves; o++) {+ sum += valueNoise(u, v, p, seed + o * 101) * amplitude;+ total += amplitude;+ amplitude *= 0.5;+ p *= 2;}- return;-}-function isFender(node) {- return semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) || /fender|wheel[ _.-]?arch/i.test(node.name);+ return total > 0 ? sum / total : 0;}-function isChassisMesh(node) {- if (!(node instanceof THREE7.Mesh) || isFender(node))- return false;- return semanticRoles(node).some((role) => /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role)) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name);+function project(u, v, angleDeg) {+ const a = angleDeg * Math.PI / 180;+ return (u - 0.5) * Math.cos(a) + (v - 0.5) * Math.sin(a) + 0.5;}-function objectBoundsInFrame2(object, frame) {- object.updateWorldMatrix(true, true);- frame.updateWorldMatrix(true, false);- const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE7.Box3;- let found = false;- object.traverse((part) => {- if (!(part instanceof THREE7.Mesh) || !(part.geometry instanceof THREE7.BufferGeometry))- return;- part.geometry.computeBoundingBox();- const box = part.geometry.boundingBox;- if (!box)- return;- const matrix = worldToFrame.clone().multiply(part.matrixWorld);- for (const x of [box.min.x, box.max.x])- for (const y of [box.min.y, box.max.y])- for (const z3 of [box.min.z, box.max.z]) {- bounds.expandByPoint(new THREE7.Vector3(x, y, z3).applyMatrix4(matrix));- found = true;- }- });- return found ? bounds : undefined;+function evalLayer(layer, u, v) {+ switch (layer.op) {+ case "solid":+ return rgbOf(layer.color);+ case "checker": {+ const cx = Math.floor(u * layer.squares);+ const cy = Math.floor(v * layer.squares);+ return rgbOf((cx + cy) % 2 === 0 ? layer.colorA : layer.colorB);+ }+ case "stripes": {+ const t = project(u, v, layer.angleDeg);+ return rgbOf(Math.floor(t * layer.count) % 2 === 0 ? layer.colorA : layer.colorB);+ }+ case "gradient": {+ const t = Math.min(1, Math.max(0, project(u, v, layer.angleDeg)));+ const from = rgbOf(layer.from);+ const to = rgbOf(layer.to);+ return [lerp(from[0], to[0], t), lerp(from[1], to[1], t), lerp(from[2], to[2], t)];+ }+ case "bricks": {+ const row = Math.floor(v * layer.rows);+ const shifted = (u + (row % 2 === 0 ? 0 : layer.stagger / layer.cols) + 1) % 1;+ const inCol = shifted * layer.cols % 1;+ const inRow = v * layer.rows % 1;+ const isMortar = inCol < layer.mortarWidth || inCol > 1 - layer.mortarWidth || inRow < layer.mortarWidth || inRow > 1 - layer.mortarWidth;+ return rgbOf(isMortar ? layer.mortar : layer.brick);+ }+ case "noise": {+ const n = fbm(u, v, layer.scale, layer.octaves, layer.seed);+ const a = rgbOf(layer.colorA);+ const b = rgbOf(layer.colorB);+ return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];+ }+ }}-function tuple2(value) {- return [value.x, value.y, value.z];+function blendChannel(mode, base, top) {+ const b = base / 255;+ const t = top / 255;+ let out;+ switch (mode) {+ case "multiply":+ out = b * t;+ break;+ case "screen":+ out = 1 - (1 - b) * (1 - t);+ break;+ case "overlay":+ out = b < 0.5 ? 2 * b * t : 1 - 2 * (1 - b) * (1 - t);+ break;+ default:+ out = t;+ }+ return out * 255;}-function probeBox(id, root, bounds) {- root.updateWorldMatrix(true, false);- const center = bounds.getCenter(new THREE7.Vector3).applyMatrix4(root.matrixWorld);- const size = bounds.getSize(new THREE7.Vector3);- const position = new THREE7.Vector3;- const quaternion = new THREE7.Quaternion;- const scale2 = new THREE7.Vector3;- root.matrixWorld.decompose(position, quaternion, scale2);- const xAxis = new THREE7.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();- const yAxis = new THREE7.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();- const zAxis = new THREE7.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();- return createOrientedProbeBox3({- id,- frame: createProbeLocalFrame3({- id: `${id}.frame`,- origin: tuple2(center),- xAxis: tuple2(xAxis),- yAxis: tuple2(yAxis),- zAxis: tuple2(zAxis)- }),- halfExtents: [- size.x * Math.abs(scale2.x) / 2,- size.y * Math.abs(scale2.y) / 2,- size.z * Math.abs(scale2.z) / 2- ]- });-}-function chassisMeshes(root) {- const meshes = [];- root.traverse((node) => {- if (isChassisMesh(node))- meshes.push(node);- });- return meshes;-}-function penetrationFindings(context, root, wheels) {- const chassis = chassisMeshes(root);- const findings = [];- for (const wheel of wheels) {- if (!wheel.tire || wheel.radius === undefined)- continue;- const tireBounds = objectBoundsInFrame2(wheel.tire, root);- if (!tireBounds)- continue;- const threshold = Math.max(0.02, wheel.radius * PENETRATION_RATIO);- for (const body of chassis) {- const bodyBounds = objectBoundsInFrame2(body, root);- if (!bodyBounds)- continue;- const result = probeOrientedPenetration(probeBox(`${wheel.id}.tire`, root, tireBounds), probeBox(body.name || "vehicle.chassis", root, bodyBounds), { maxDepth: threshold });- if (result.pass)- continue;- findings.push(advisory2(context, {- code: "VEH_WHEEL_CHASSIS_PENETRATION",- message: `Wheel ${wheel.id} penetrates chassis ${body.name || "(unnamed)"} by ` + `${result.measurements.penetrationDepth?.toFixed(6)} m beyond the allowed non-fender overlap.`,- affected: { node: wheel.tire.name || wheel.root.name },- measurement: {- name: "tireChassisPenetrationDepth",- actual: result.measurements.penetrationDepth ?? 0,- expected: 0,- threshold,- unit: "m"- },- viewHints: ["vehicle.underbody", "vehicle.wheel-section.right"]- }));+function compileProceduralTextureSpecV2(input) {+ const spec = canonicalizeProceduralTextureSpecV2(input);+ const { size, layers } = spec;+ const data = new Uint8Array(size * size * 4);+ for (let y = 0;y < size; y++) {+ const v = (y + 0.5) / size;+ for (let x = 0;x < size; x++) {+ const u = (x + 0.5) / size;+ let r = 0;+ let g = 0;+ let b = 0;+ for (const [i, layer] of layers.entries()) {+ const [lr, lg, lb] = evalLayer(layer, u, v);+ if (i === 0) {+ r = lr;+ g = lg;+ b = lb;+ continue;+ }+ r = lerp(r, blendChannel(layer.blend, r, lr), layer.opacity);+ g = lerp(g, blendChannel(layer.blend, g, lg), layer.opacity);+ b = lerp(b, blendChannel(layer.blend, b, lb), layer.opacity);+ }+ const o = (y * size + x) * 4;+ data[o] = Math.max(0, Math.min(255, Math.round(r)));+ data[o + 1] = Math.max(0, Math.min(255, Math.round(g)));+ data[o + 2] = Math.max(0, Math.min(255, Math.round(b)));+ data[o + 3] = 255;}}- return findings;-}-function wholeAssetBounds(root) {- return objectBoundsInFrame2(root, root);-}-function orientationFindings(context, root, intent) {- if (intent.subtype === "fixed-wing" || intent.subtype === "rotorcraft" || intent.subtype === "walking" || intent.subtype === "custom") {- return [];- }- const bounds = wholeAssetBounds(root);- if (!bounds)- return [];- const size = bounds.getSize(new THREE7.Vector3);- const ratio = size.z / Math.max(size.x, 0.000000001);- if (ratio <= ORIENTATION_RATIO)- return [];- return [- advisory2(context, {- code: "VEH_ORIENTATION_SIDEWAYS",- message: `${intent.subtype} bounds are Z-dominant despite canonical +X travel ` + `(spanX=${size.x.toFixed(6)}, spanZ=${size.z.toFixed(6)} m).`,- affected: { node: root.name || "vehicle-root" },- measurement: {- name: "boundsSpanZToSpanX",- actual: ratio,- expected: `<=${ORIENTATION_RATIO}`,- threshold: ORIENTATION_RATIO- },- viewHints: ["generic.top.semantic-overlay", "vehicle.underbody"]- })- ];-}-function nodePath(root, target) {- let found = "";- const visit = (node, parent, index) => {- if (found)- return;- const segment = `${node.name.trim() || node.type || "Object3D"}[${index}]`;- const path = parent ? `${parent}/${segment}` : segment;- if (node === target) {- found = path;- return;- }- node.children.forEach((child, childIndex) => {- visit(child, path, childIndex);- });+ return {+ spec,+ pixels: data,+ canonicalJson: canonicalProceduralTextureJsonV2(spec),+ recipeHash: hashProceduralTextureSpecV2(spec)};- visit(root, "", 0);- return found;}-function weldedBoundaryEdges(root, loop) {- root.updateMatrixWorld(true);- const inverse = loop.matrixWorld.clone().invert();- const edges = new Map;- let triangleCount = 0;- const vertexKey = (point) => [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(",");- loop.traverse((node) => {- if (!(node instanceof THREE7.Mesh) || !(node.geometry instanceof THREE7.BufferGeometry))- return;- const positions = node.geometry.getAttribute("position");- if (!positions)- return;- const matrix = inverse.clone().multiply(node.matrixWorld);- const keys = Array.from({ length: positions.count }, (_, index2) => vertexKey(new THREE7.Vector3().fromBufferAttribute(positions, index2).applyMatrix4(matrix)));- const index = node.geometry.getIndex();- const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);- for (let offset = 0;offset + 2 < indices.length; offset += 3) {- triangleCount++;- const triangle = [indices[offset], indices[offset + 1], indices[offset + 2]];- for (let edge = 0;edge < 3; edge++) {- const a = keys[triangle[edge]];- const b = keys[triangle[(edge + 1) % 3]];- const id = a < b ? `${a}|${b}` : `${b}|${a}`;- edges.set(id, (edges.get(id) ?? 0) + 1);- }- }- });- if (triangleCount === 0)- return;- return [...edges.values()].filter((count) => count === 1).length;+function proceduralTexture(spec) {+ const compiled = compileProceduralTextureSpecV2(spec);+ const { size, usage, name, layers } = compiled.spec;+ const tex = new THREE10.DataTexture(compiled.pixels, size, size, THREE10.RGBAFormat, THREE10.UnsignedByteType);+ if (name)+ tex.name = name;+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE10.SRGBColorSpace : THREE10.NoColorSpace;+ tex.wrapS = THREE10.RepeatWrapping;+ tex.wrapT = THREE10.RepeatWrapping;+ tex.minFilter = THREE10.LinearMipmapLinearFilter;+ tex.magFilter = THREE10.LinearFilter;+ tex.generateMipmaps = true;+ tex.needsUpdate = true;+ tex.userData["kilnProcedural"] = {+ schemaVersion: 2,+ size,+ usage,+ ...name ? { name } : {},+ layers,+ canonicalJson: compiled.canonicalJson,+ recipeHash: compiled.recipeHash+ };+ return tex;}-function trackProfileFindings(context, root, intent) {- if (intent.subtype !== "tracked")- return [];- const loops = [];- const roadWheels = [];- root.traverse((node) => {- const roles2 = semanticRoles(node);- if (roles2.some((role) => role.startsWith("track.loop.")) || roles2.some((role) => role.startsWith("support.track."))) {- loops.push(node);- }- if (roles2.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {- roadWheels.push(node);- }- });- if (loops.length === 0) {- return [- advisory2(context, {- code: "VEH_TRACK_LOOP_MISSING",- message: "Tracked vehicle exposes no semantic track.loop.* assembly to inspect.",- affected: { node: root.name || "vehicle-root" },- measurement: { name: "trackLoopCount", actual: 0, expected: ">=1", threshold: 1 },- viewHints: ["vehicle.underbody", "generic.right.semantic-overlay"]- })- ];+function normalMapFromHeight(source, opts = {}) {+ const image = source.image;+ const data = image?.data;+ const width = image?.width ?? 0;+ const height = image?.height ?? 0;+ if (!data || !width || !height) {+ throw new ProceduralTextureError("normalMapFromHeight: the source texture has no readable pixels. Pass a proceduralTexture() result or a loadApprovedTexture() result, not a texture built from an image element.");}- const findings = [];- for (const loop of loops) {- const loopSide = trackSide(loop);- const declaredClosed = loop.userData["kilnTrackLoopClosed"];- const boundaryEdges = weldedBoundaryEdges(root, loop);- if (declaredClosed === false || boundaryEdges !== undefined && boundaryEdges > 0) {- findings.push(advisory2(context, {- code: "VEH_TRACK_LOOP_OPEN",- message: `Track loop ${loop.name || "(unnamed)"} is open ` + `(boundary edges ${boundaryEdges ?? "declared"}).`,- affected: { node: loop.name || "track-loop", nodePath: nodePath(root, loop) },- measurement: {- name: "trackLoopBoundaryEdgeCount",- actual: boundaryEdges ?? 1,- expected: 0,- threshold: 0- },- viewHints: ["vehicle.underbody", "generic.right.wireframe"]- }));- }- const loopBounds = objectBoundsInFrame2(loop, root);- if (!loopBounds)- continue;- const expanded = loopBounds.clone().expandByScalar(TRACK_CONTAINMENT_TOLERANCE);- for (const roadWheel of roadWheels.filter((candidate) => !loopSide || !trackSide(candidate) || trackSide(candidate) === loopSide)) {- const wheelBounds = objectBoundsInFrame2(roadWheel, root);- if (!wheelBounds)- continue;- const center = wheelBounds.getCenter(new THREE7.Vector3);- if (expanded.containsPoint(center))- continue;- const clamped = center.clone().clamp(expanded.min, expanded.max);- const overflow = center.distanceTo(clamped);- findings.push(advisory2(context, {- code: "VEH_TRACK_ROAD_WHEEL_ESCAPED",- message: `Road wheel ${roadWheel.name || "(unnamed)"} escapes track loop ` + `${loop.name || "(unnamed)"} by ${overflow.toFixed(6)} m.`,- affected: {- node: roadWheel.name || "track-road-wheel",- nodePath: nodePath(root, roadWheel)- },- measurement: {- name: "roadWheelTrackContainmentOverflow",- actual: overflow,- expected: 0,- threshold: TRACK_CONTAINMENT_TOLERANCE,- unit: "m"- },- viewHints: ["vehicle.underbody", "generic.right.semantic-overlay"]- }));- }+ const channels = data.length / (width * height);+ if (channels !== 3 && channels !== 4) {+ throw new ProceduralTextureError(`normalMapFromHeight: the source has ${data.length} bytes for ${width}x${height}, which is neither RGB nor RGBA.`);}- return findings;-}-function evaluateVehicleAdvisoryQa(context) {- if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE7.Object3D)) {- return [];+ const strength = opts.strength ?? 2;+ if (!Number.isFinite(strength) || strength <= 0) {+ throw new ProceduralTextureError(`normalMapFromHeight: strength must be a positive number, got ${JSON.stringify(opts.strength)}.`);}- const intent = context.intent.vehicle;- if (!intent)- return [];- const root = context.scene;- root.updateMatrixWorld(true);- const wheels = resolveVehicleWheelAssemblies(root);- return [- ...bilateralSymmetryFindings2(context, root, wheels),- ...penetrationFindings(context, root, wheels),- ...orientationFindings(context, root, intent),- ...trackProfileFindings(context, root, intent)- ].sort((a, b) => `${a.code}:${a.affected?.nodePath ?? a.affected?.node ?? ""}`.localeCompare(`${b.code}:${b.affected?.nodePath ?? b.affected?.node ?? ""}`));-}-var SYMMETRY_RATIO = 0.08, PENETRATION_RATIO = 0.25, ORIENTATION_RATIO = 1.15, TRACK_CONTAINMENT_TOLERANCE = 0.02, VEHICLE_VIEWS, VEHICLE_W6_ADVISORY_QA_RULE;-var init_vehicle_advisory = __esm(() => {- init_contracts();- init_vehicle();- init_registry();- VEHICLE_VIEWS = [- "vehicle.underbody",- "vehicle.wheel-section.right",- "generic.top.semantic-overlay"- ];- VEHICLE_W6_ADVISORY_QA_RULE = Object.freeze({- id: "VEHICLE_W6_ADVISORY_PROFILE",- profile: "vehicle.w6-advisory",- scope: { kind: "category", category: "vehicle" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: evaluateVehicleAdvisoryQa- });-});--// src/qa/vehicle.ts-import * as THREE8 from "three";-function finding(context, value) {- return {- ...value,- profile: context.intent.qaProfile || PROFILE,- dimension: "categoryReadiness",- viewHints: value.viewHints ?? ["vehicle.underbody", "vehicle.wheel-section"]+ const lum = (x, y) => {+ const xw = (x % width + width) % width;+ const yw = (y % height + height) % height;+ const o = (yw * width + xw) * channels;+ return (0.299 * (data[o] ?? 0) + 0.587 * (data[o + 1] ?? 0) + 0.114 * (data[o + 2] ?? 0)) / 255;};-}-function localPoint2(rootInverse2, value) {- return value.clone().applyMatrix4(rootInverse2);-}-function rootAxis(root, axis) {- root.updateWorldMatrix(true, false);- return axis.clone().transformDirection(root.matrixWorld);-}-function angleDegrees(a, b) {- return THREE8.MathUtils.radToDeg(Math.acos(THREE8.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));-}-function isDescendant(node, ancestor) {- let current = node;- while (current) {- if (current === ancestor)- return true;- current = current.parent ?? undefined;- }- return false;-}-function componentDisposition(wheel) {- return wheel.source === "semantic" ? "block" : "warn";-}-function wheelCountFindings(context, intent, wheels) {- const findings = [];- if (wheels.length !== intent.wheelCount) {- findings.push(finding(context, {- code: "VEH_WHEEL_COUNT",- disposition: "block",- message: `Trusted vehicle intent requires ${intent.wheelCount} wheel assemblies; resolved ${wheels.length}.`,- measurement: {- name: "wheelAssemblyCount",- actual: wheels.length,- expected: intent.wheelCount,- threshold: intent.wheelCount- },- repairText: "Create exactly the requested number of axle-centered wheel assemblies and remove duplicate or ungrouped wheel parts."- }));- }- const axleIds = new Set(wheels.map((wheel) => wheel.index).filter(Boolean));- if (intent.axleCount > 0 && axleIds.size !== intent.axleCount) {- findings.push(finding(context, {- code: "VEH_AXLE_COUNT",- disposition: "block",- message: `Trusted vehicle intent requires ${intent.axleCount} axles; wheel grouping resolved ${axleIds.size}.`,- measurement: {- name: "wheelAxleCount",- actual: axleIds.size,- expected: intent.axleCount,- threshold: intent.axleCount- }- }));- }- return findings;-}-function wheelGeometryFindings(context, root, wheels) {- const findings = [];- const expectedAxle = rootAxis(root, new THREE8.Vector3(0, 0, 1));- for (const wheel of wheels) {- const disposition = componentDisposition(wheel);- const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);- const pivotInverse = wheel.pivot.matrixWorld.clone().invert();- const componentCenters = [wheel.tireCenterWorld, wheel.rimCenterWorld, wheel.hubCenterWorld].filter((center) => !!center).map((center) => localPoint2(pivotInverse, center));- let centerDelta = 0;- for (let a = 0;a < componentCenters.length; a++) {- for (let b = a + 1;b < componentCenters.length; b++) {- centerDelta = Math.max(centerDelta, componentCenters[a].distanceTo(componentCenters[b]));- }- }- if (!wheel.tire || !wheel.rim || !wheel.hub || centerDelta > centerTolerance) {- findings.push(finding(context, {- code: "VEH_WHEEL_CONCENTRICITY",- disposition,- message: `Wheel ${wheel.id} tire, rim, and hub must share one axle center.`,- affected: { node: wheel.root.name },- measurement: {- name: "maximumComponentCenterDelta",- actual: Number.isFinite(centerDelta) ? centerDelta : null,- expected: 0,- threshold: centerTolerance,- unit: "m"- },- repairText: `Move the tire, rim, and hub of ${wheel.id} to its axle-centered wheel pivot.`- }));- }- const nested = wheel.radius !== undefined && wheel.rimRadius !== undefined && wheel.hubRadius !== undefined && wheel.hubRadius < wheel.rimRadius && wheel.rimRadius < wheel.radius && wheel.rimWidth !== undefined && wheel.hubWidth !== undefined && wheel.width !== undefined && wheel.rimWidth <= wheel.width + 0.000001 && wheel.hubWidth <= wheel.width + 0.000001;- if (!nested) {- findings.push(finding(context, {- code: "VEH_WHEEL_RADIUS",- disposition,- message: `Wheel ${wheel.id} must satisfy hub radius < rim radius < tire radius and keep rim/hub widths inside the tire envelope.`,- affected: { node: wheel.root.name },- measurement: {- name: "nestedRadii",- actual: false,- expected: true- },- repairText: `Resize ${wheel.id} so its hub is nested inside its rim and its rim is nested inside its tire.`- }));- }- const axleAngle = angleDegrees(wheel.spinAxisWorld, expectedAxle);- if (axleAngle > AXIS_TOLERANCE_DEGREES) {- findings.push(finding(context, {- code: "VEH_WHEEL_AXLE_AXIS",- disposition,- message: `Wheel ${wheel.id} spin axis must align with vehicle-local +Z.`,- affected: { node: wheel.pivot.name },- measurement: {- name: "axleAxisAngle",- actual: axleAngle,- expected: 0,- threshold: AXIS_TOLERANCE_DEGREES,- unit: "degrees"- },- repairText: `Orient ${wheel.pivot.name} so its local +Z is the axle/spin axis.`- }));- }- const pivotDelta = localPoint2(pivotInverse, wheel.pivotCenterWorld).distanceTo(localPoint2(pivotInverse, wheel.centerWorld));- const descendants = [wheel.tire, wheel.rim, wheel.hub].every((part) => isDescendant(part, wheel.pivot));- if (!descendants || pivotDelta > centerTolerance) {- findings.push(finding(context, {- code: "VEH_WHEEL_PIVOT",- disposition,- message: `Wheel ${wheel.id} pivot must be at the axle center and own every moving component.`,- affected: { node: wheel.pivot.name },- measurement: {- name: "pivotCenterDelta",- actual: pivotDelta,- expected: 0,- threshold: centerTolerance,- unit: "m"- },- repairText: `Place ${wheel.pivot.name} at the axle center and parent tire, rim, and hub beneath it.`- }));- }- }- return findings;-}-function axlePairFindings(context, root, wheels) {- root.updateWorldMatrix(true, false);- const inverse = root.matrixWorld.clone().invert();- const groups = new Map;- for (const wheel of wheels) {- if (!wheel.index)- continue;- const group = groups.get(wheel.index) ?? [];- group.push(wheel);- groups.set(wheel.index, group);- }- const findings = [];- for (const [index, pair] of groups) {- const left = pair.find((wheel) => wheel.side === "left");- const right = pair.find((wheel) => wheel.side === "right");- if (!left || !right)- continue;- const leftCenter = localPoint2(inverse, left.centerWorld);- const rightCenter = localPoint2(inverse, right.centerWorld);- const delta = Math.hypot(leftCenter.x - rightCenter.x, leftCenter.y - rightCenter.y);- if (delta > PAIR_TOLERANCE) {- findings.push(finding(context, {- code: "VEH_AXLE_PAIR",- disposition: left.source === "semantic" && right.source === "semantic" ? "block" : "warn",- message: `Axle ${index} left/right wheel centers disagree in vehicle-local X/Y.`,- affected: { node: right.root.name },- measurement: {- name: "pairedCenterXYDelta",- actual: delta,- expected: 0,- threshold: PAIR_TOLERANCE,- unit: "m"- },- repairText: `Align both wheels on axle ${index} to the same local X and Y coordinates.`- }));+ const out = new Uint8Array(width * height * 4);+ for (let y = 0;y < height; y++) {+ for (let x = 0;x < width; x++) {+ const dx = (lum(x + 1, y) - lum(x - 1, y)) * strength;+ const dy = (lum(x, y + 1) - lum(x, y - 1)) * strength;+ let nx = -dx;+ let ny = -dy;+ const nz = 1;+ const len = Math.hypot(nx, ny, nz) || 1;+ nx /= len;+ ny /= len;+ const o = (y * width + x) * 4;+ out[o] = Math.round((nx * 0.5 + 0.5) * 255);+ out[o + 1] = Math.round((ny * 0.5 + 0.5) * 255);+ out[o + 2] = Math.round(nz / len * 0.5 * 255 + 127.5);+ out[o + 3] = 255;}}- return findings;+ const tex = new THREE10.DataTexture(out, width, height, THREE10.RGBAFormat, THREE10.UnsignedByteType);+ tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : "");+ tex.colorSpace = THREE10.NoColorSpace;+ tex.wrapS = THREE10.RepeatWrapping;+ tex.wrapT = THREE10.RepeatWrapping;+ tex.minFilter = THREE10.LinearMipmapLinearFilter;+ tex.magFilter = THREE10.LinearFilter;+ tex.generateMipmaps = true;+ tex.needsUpdate = true;+ return tex;}-function duplicateAssemblyFindings(context, root, wheels) {- root.updateMatrixWorld(true);- const inverse = root.matrixWorld.clone().invert();- const findings = [];- for (let a = 0;a < wheels.length; a++) {- for (let b = a + 1;b < wheels.length; b++) {- const left = wheels[a];- const right = wheels[b];- const sameDeclaredCorner = left.side !== undefined && left.side === right.side && left.index !== undefined && left.index === right.index;- const centerDelta = localPoint2(inverse, left.centerWorld).distanceTo(localPoint2(inverse, right.centerWorld));- const scale2 = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(CENTER_MINIMUM, scale2 * CENTER_RATIO);- if (!sameDeclaredCorner && centerDelta > threshold)- continue;- const semantic3 = left.source === "semantic" && right.source === "semantic";- findings.push(finding(context, {- code: "VEH_DUPLICATE_ASSEMBLY",- disposition: semantic3 ? "block" : "warn",- message: `Wheel assemblies ${left.id} and ${right.id} resolve to the same ` + `${sameDeclaredCorner ? `${left.side}-${left.index} corner` : "scale-relative center"}.`,- affected: { node: right.root.name },- measurement: {- name: "duplicateAssemblyCenterDelta",- actual: centerDelta,- expected: `>${threshold}`,- threshold,- unit: "m"- },- viewHints: [- "vehicle.underbody",- "vehicle.wheel-section.right",- "generic.top.semantic-overlay"- ],- repairText: `Remove only duplicate assembly ${right.id} at the reported center; preserve ${left.id} and rebuild the actually missing corner from trusted wheel/axle intent.`- }));- }- }- return findings;-}-function contactFindings2(context, root, intent, wheels) {- if (intent.supportPolicy !== "grounded")- return [];- root.updateWorldMatrix(true, false);- const inverse = root.matrixWorld.clone().invert();- const findings = [];- for (const wheel of wheels.filter((value) => value.loadBearing)) {- const center = localPoint2(inverse, wheel.centerWorld);- const contactY = center.y - (wheel.radius ?? 0);- if (wheel.radius === undefined || Math.abs(contactY) > CONTACT_TOLERANCE2) {- findings.push(finding(context, {- code: "VEH_CONTACT_PLANE",- disposition: componentDisposition(wheel),- message: `Load-bearing wheel ${wheel.id} must touch the shared ground plane Y=0 without floating or burial.`,- affected: { node: wheel.tire?.name ?? wheel.root.name },- measurement: {- name: "tireContactY",- actual: wheel.radius === undefined ? null : contactY,- expected: 0,- threshold: CONTACT_TOLERANCE2,- unit: "m"- },- repairText: `Set ${wheel.id} axle-center Y to its tire radius so its contact point is Y=0.`- }));- }- }- return findings;-}-function renderableMinYInRoot(rootInverse2, node) {- let minimum = Infinity;- node.traverse((part) => {- if (!(part instanceof THREE8.Mesh) || !(part.geometry instanceof THREE8.BufferGeometry))- return;- part.geometry.computeBoundingBox();- const bounds = part.geometry.boundingBox;- if (!bounds)- return;- const matrix = rootInverse2.clone().multiply(part.matrixWorld);- for (const x of [bounds.min.x, bounds.max.x]) {- for (const y of [bounds.min.y, bounds.max.y]) {- for (const z3 of [bounds.min.z, bounds.max.z]) {- minimum = Math.min(minimum, new THREE8.Vector3(x, y, z3).applyMatrix4(matrix).y);- }- }- }- });- return Number.isFinite(minimum) ? minimum : undefined;-}-function supportContactFindings(context, root, intent) {- if (intent.supportPolicy !== "grounded")- return [];- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- const explicitContacts = [];- const supports = [];- root.traverse((node) => {- const roles2 = readSemanticMetadataV1(node)?.roles ?? [];- const isWheelContact = roles2.some((role) => role.startsWith("wheel.contact."));- if (!isWheelContact && roles2.some((role) => role.startsWith("contact."))) {- explicitContacts.push({- node,- contactY: localPoint2(inverse, new THREE8.Vector3().setFromMatrixPosition(node.matrixWorld)).y,- source: "contact"- });- }- if (roles2.some((role) => role.startsWith("support."))) {- const contactY = renderableMinYInRoot(inverse, node);- if (contactY !== undefined)- supports.push({ node, contactY, source: "support" });- }- });- const measurements = explicitContacts.length > 0 ? explicitContacts : supports;- const findings = measurements.flatMap((measurement) => {- if (Math.abs(measurement.contactY) <= CONTACT_TOLERANCE2)- return [];- return [- finding(context, {- code: "VEH_CONTACT_PLANE",- disposition: "block",- message: `Load-bearing ${measurement.source} ${measurement.node.name || "(unnamed)"} must touch the shared ground plane Y=0 without floating or burial.`,- affected: { node: measurement.node.name || "vehicle-support" },- measurement: {- name: "supportContactY",- actual: measurement.contactY,- expected: 0,- threshold: CONTACT_TOLERANCE2,- unit: "m"- },- repairText: `Move ${measurement.node.name || "the support"} so its declared contact rests at vehicle-local Y=0.`- })- ];- });- if (intent.wheelCount === 0) {- for (const expected of intent.supportAssemblies) {- const matches = [...explicitContacts, ...supports].filter((measurement) => (readSemanticMetadataV1(measurement.node)?.roles ?? []).some((role) => role === `support.${expected}` || role.startsWith(`support.${expected}.`) || role === `contact.${expected}` || role.startsWith(`contact.${expected}.`)));- if (matches.length > 0)- continue;- findings.push(finding(context, {- code: "VEH_SUPPORT_SET_MISSING",- disposition: "block",- message: `Trusted grounded ${intent.subtype} intent requires semantic ${expected} supports or contacts.`,- affected: { node: root.name || "vehicle-root" },- measurement: {- name: `${expected}SupportCount`,- actual: 0,- expected: ">=1",- threshold: 1- },- viewHints: ["vehicle.underbody", "generic.front.depth-contact"],- repairText: `Add only the declared ${expected} support set, tag each load-bearing part/contact semantically, and place every contact on vehicle-local Y=0.`- }));- }- if (measurements.length > 1) {- const values = measurements.map((measurement) => measurement.contactY);- const range = Math.max(...values) - Math.min(...values);- if (range > CONTACT_TOLERANCE2) {- findings.push(finding(context, {- code: "VEH_SUPPORT_PLANE",- disposition: "block",- message: `Declared non-wheel supports do not share one stable vehicle-local contact plane.`,- affected: { node: root.name || "vehicle-root" },- measurement: {- name: "supportContactPlaneRange",- actual: range,- expected: 0,- threshold: CONTACT_TOLERANCE2,- unit: "m"- },- viewHints: ["vehicle.underbody", "generic.front.depth-contact"],- repairText: "Move only the reported skid, landing-gear, track, or other support contacts onto one vehicle-local Y=0 plane while preserving their stance."- }));- }- }- }- return findings;-}-function steeringFindings(context, root, intent, wheels) {- if (intent.steering === "none" || wheels.length === 0)- return [];- root.updateWorldMatrix(true, false);- const inverse = root.matrixWorld.clone().invert();- const expectedAxis = rootAxis(root, new THREE8.Vector3(0, 1, 0));- const localCenters = wheels.map((wheel) => ({- wheel,- center: localPoint2(inverse, wheel.centerWorld)- }));- const extreme = intent.steering === "rear" ? Math.min(...localCenters.map((entry) => entry.center.x)) : Math.max(...localCenters.map((entry) => entry.center.x));- const targets = intent.steering === "all" ? localCenters : localCenters.filter((entry) => Math.abs(entry.center.x - extreme) <= PAIR_TOLERANCE);- const findings = [];- for (const { wheel } of targets) {- const steering = wheel.steeringPivot;- const centerDelta = steering ? localPoint2(inverse, new THREE8.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;- const axisAngle = steering ? angleDegrees(new THREE8.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;- if (!steering || !isDescendant(wheel.pivot, steering) || centerDelta > CENTER_MINIMUM || axisAngle > AXIS_TOLERANCE_DEGREES) {- const axisInvalid = axisAngle > AXIS_TOLERANCE_DEGREES;- findings.push(finding(context, {- code: "VEH_STEERING_PIVOT",- disposition: componentDisposition(wheel),- message: `Declared steering wheel ${wheel.id} requires a centered +Y steering pivot owning its spin pivot.`,- affected: { node: steering?.name ?? wheel.pivot.name },- measurement: {- name: axisInvalid ? "steeringAxisAngle" : "steeringPivotCenterDelta",- actual: axisInvalid ? Number.isFinite(axisAngle) ? axisAngle : null : Number.isFinite(centerDelta) ? centerDelta : null,- expected: 0,- threshold: axisInvalid ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,- unit: axisInvalid ? "degrees" : "m"- },- repairText: `Move the steering pivot for ${wheel.id} to the axle center, orient local +Y as steering axis, and parent the wheel spin pivot beneath it.`- }));- }- }- return findings;-}-function propulsionFindings(context, root, intent) {- const expectedKinds = intent.propulsionAssemblies.filter((value) => value === "rotor" || value === "propeller");- if (expectedKinds.length === 0)- return [];- const pivots = new Map;- const components = [];- root.traverse((node) => {- const metadata = readSemanticMetadataV1(node);- for (const role of metadata?.roles ?? []) {- if (role.startsWith("propulsion.pivot."))- pivots.set(role.slice("propulsion.pivot.".length), node);- for (const kind of ["rotor", "propeller"]) {- if (role.startsWith(`propulsion.${kind}.`)) {- components.push({ id: role.slice(`propulsion.${kind}.`.length), kind, node });- }- }- }- });- const findings = [];- root.updateWorldMatrix(true, false);- const rootInverse2 = root.matrixWorld.clone().invert();- for (const kind of expectedKinds) {- const candidates = components.filter((part) => part.kind === kind);- if (candidates.length === 0) {- findings.push(finding(context, {- code: "VEH_ROTOR_PIVOT",- disposition: "block",- message: `Trusted vehicle intent requires a semantic ${kind} assembly and centered pivot.`,- measurement: { name: `${kind}AssemblyCount`, actual: 0, expected: 1, threshold: 1 }- }));- continue;- }- for (const component of candidates) {- const pivot = pivots.get(component.id);- const box = new THREE8.Box3().setFromObject(component.node);- const center = box.isEmpty() ? undefined : box.getCenter(new THREE8.Vector3);- const pivotCenter = pivot ? new THREE8.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;- const delta = center && pivotCenter ? localPoint2(rootInverse2, center).distanceTo(localPoint2(rootInverse2, pivotCenter)) : Infinity;- const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";- const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);- const canonicalAxis = kind === "rotor" ? new THREE8.Vector3(0, 1, 0) : new THREE8.Vector3(1, 0, 0);- const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE8.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;- if (!pivot || !isDescendant(component.node, pivot) || delta > CENTER_MINIMUM || !axisFrame || axisAngle > AXIS_TOLERANCE_DEGREES) {- findings.push(finding(context, {- code: "VEH_ROTOR_PIVOT",- disposition: "block",- message: `${kind} ${component.id} requires a centered owning pivot with ${frameId}.`,- affected: { node: pivot?.name ?? component.node.name },- measurement: {- name: axisAngle > AXIS_TOLERANCE_DEGREES ? "propulsionAxisAngle" : "propulsionPivotCenterDelta",- actual: axisAngle > AXIS_TOLERANCE_DEGREES ? Number.isFinite(axisAngle) ? axisAngle : null : Number.isFinite(delta) ? delta : null,- expected: 0,- threshold: axisAngle > AXIS_TOLERANCE_DEGREES ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,- unit: axisAngle > AXIS_TOLERANCE_DEGREES ? "degrees" : "m"- },- repairText: `Place the ${kind} pivot at the mast/shaft center, parent the moving geometry beneath it, and declare ${frameId}.`- }));- }- }- }- return findings;-}-function evaluateVehicleQa(context) {- if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE8.Object3D))- return [];- const intent = context.intent.vehicle;- if (!intent)- return [];- const root = context.scene;- root.updateMatrixWorld(true);- const wheels = resolveVehicleWheelAssemblies(root);- const findings = [];- if (!hasCanonicalVehicleFront(root)) {- findings.push(finding(context, {- code: "VEH_FRONT_AXIS",- disposition: "block",- message: "Generated vehicles must declare the trusted semantic +X front frame.",- affected: { node: root.name || "vehicle-root" },- measurement: { name: "canonicalFrontDeclared", actual: false, expected: true },- repairText: "Author the vehicle beneath createVehicleFrame() and preserve vehicle.front.+x semantics."- }));- }- if (intent.wheelCount > 0 || intent.subtype === "wheeled") {- findings.push(...wheelCountFindings(context, intent, wheels));- findings.push(...wheelGeometryFindings(context, root, wheels));- findings.push(...axlePairFindings(context, root, wheels));- findings.push(...duplicateAssemblyFindings(context, root, wheels));- findings.push(...contactFindings2(context, root, intent, wheels));- findings.push(...steeringFindings(context, root, intent, wheels));- }- findings.push(...supportContactFindings(context, root, intent));- findings.push(...propulsionFindings(context, root, intent));- return findings;-}-var PROFILE = "vehicle.semantic", CENTER_RATIO = 0.03, CENTER_MINIMUM = 0.01, AXIS_TOLERANCE_DEGREES = 1, PAIR_TOLERANCE = 0.015, CONTACT_TOLERANCE2 = 0.02, VEHICLE_QA_RULE, VEHICLE_ADVISORY_QA_RULE, VEHICLE_QA_RULES;-var init_vehicle2 = __esm(() => {- init_contracts();- init_vehicle();- init_registry();- init_vehicle_advisory();- VEHICLE_QA_RULE = {- id: "VEHICLE_PROFILE",- profile: PROFILE,- scope: { kind: "category", category: "vehicle" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("vehicle-qa-v1", "src/qa/vehicle.test.ts", "4bffa0dff0ed33be2ce7003ee36ac33efc5b4900e57d390898e43551912e626b"),- defaultMode: "enforce",- evaluate: (context) => evaluateVehicleQa(context).filter((finding2) => finding2.disposition === "block")- };- VEHICLE_ADVISORY_QA_RULE = {- id: "VEHICLE_ADVISORY_PROFILE",- profile: "vehicle.advisory",- scope: { kind: "category", category: "vehicle" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: (context) => evaluateVehicleQa(context).filter((finding2) => finding2.disposition !== "block")- };- VEHICLE_QA_RULES = [- VEHICLE_QA_RULE,- VEHICLE_ADVISORY_QA_RULE,- VEHICLE_W6_ADVISORY_QA_RULE- ];-});--// src/qa/vegetation.ts-import * as THREE9 from "three";-function rolesOf(node) {- return readSemanticMetadataV1(node)?.roles ?? [];-}-function pathOf(node, root) {- const names = [];- let cursor = node;- while (cursor) {- names.push(cursor.name || cursor.type);- if (cursor === root)- break;- cursor = cursor.parent;- }- return names.reverse().join("/");-}-function localPoint3(rootInverse2, node) {- return node.getWorldPosition(new THREE9.Vector3).applyMatrix4(rootInverse2);-}-function meshLocalBox(mesh, rootInverse2) {- if (!(mesh.geometry instanceof THREE9.BufferGeometry))- return;- mesh.geometry.computeBoundingBox();- const source = mesh.geometry.boundingBox;- if (!source || source.isEmpty())- return;- const transform = rootInverse2.clone().multiply(mesh.matrixWorld);- const result = new THREE9.Box3;- for (const x of [source.min.x, source.max.x]) {- for (const y of [source.min.y, source.max.y]) {- for (const z3 of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE9.Vector3(x, y, z3).applyMatrix4(transform));- }- }- }- return result;-}-function collectRenderableBounds(root) {- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- const values = [];- root.traverse((node) => {- if (!(node instanceof THREE9.Mesh))- return;- const box = meshLocalBox(node, inverse);- if (!box)- return;- const roles2 = rolesOf(node);- values.push({ node, box, roles: roles2, source: roles2.length > 0 ? "semantic" : "fallback" });- });- return values;-}-function finding2(context, value) {- return { ...value, profile: context.intent.qaProfile || PROFILE2 };-}-function vegetationIntent(intent) {- return intent.category === "vegetation" ? intent.vegetation : undefined;-}-function evaluateVegetationContactQa(context) {- const trusted = vegetationIntent(context.intent);- if (!trusted?.grounded || !(context.scene instanceof THREE9.Object3D))- return [];- const root = context.scene;- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- const contacts = [];- const semanticSupports = [];- root.traverse((node) => {- const metadata = readSemanticMetadataV1(node);- const roles2 = metadata?.roles ?? [];- if (roles2.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {- const frame = metadata?.frames.find((value) => value.id === "ground-contact" || value.id === "vegetation-ground-contact");- contacts.push({- node,- ...frame ? { frameTranslation: frame.translation } : {}- });- }- if (roles2.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {- semanticSupports.push(node);- }- });- if (contacts.length === 0) {- return [- finding2(context, {- code: "VEG_CONTACT_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: "Standalone grounded vegetation requires one semantic ground-contact marker.",- affected: { node: root.name || "vegetation-root" },- measurement: { name: "groundContactCount", actual: 0, expected: ">=1" },- viewHints: ["right", "vegetation.base-contact"],- repairText: "Add a vegetation.contact.ground semantic marker at asset-local Y=0 and seat the plant base on it."- })- ];- }- const findings = [];- for (const contact of contacts) {- const contactPoint = contact.frameTranslation ? new THREE9.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);- const y = contactPoint.y;- if (Math.abs(y) <= VEGETATION_CONTACT_TOLERANCE_METERS)- continue;- const floating = y > 0;- findings.push(finding2(context, {- code: floating ? "VEG_CONTACT_FLOATING" : "VEG_CONTACT_BURIED",- disposition: "block",- dimension: "categoryReadiness",- message: `${contact.node.name || "Vegetation contact"} is ${Math.abs(y).toFixed(6)} m ${floating ? "above" : "below"} asset-local ground.`,- affected: {- node: contact.node.name || "vegetation-contact",- nodePath: pathOf(contact.node, root)- },- measurement: {- name: "contactY",- actual: stable3(y),- expected: 0,- threshold: VEGETATION_CONTACT_TOLERANCE_METERS,- unit: "m"- },- viewHints: ["right", "vegetation.base-contact"],- repairText: `Move ${contact.node.name || "the contact marker"} or its ground-contact frame to asset-local Y=0 without moving unrelated canopy parts.`- }));- }- for (const support of semanticSupports) {- let minimumY = Infinity;- support.traverse((node) => {- if (!(node instanceof THREE9.Mesh))- return;- const box = meshLocalBox(node, inverse);- if (box)- minimumY = Math.min(minimumY, box.min.y);- });- if (!Number.isFinite(minimumY) || minimumY >= -VEGETATION_CONTACT_TOLERANCE_METERS)- continue;- findings.push(finding2(context, {- code: "VEG_MATERIAL_BURIED",- disposition: "block",- dimension: "categoryReadiness",- message: `${support.name || "Vegetation support"} extends materially below the standalone ground plane.`,- affected: { node: support.name || "vegetation-support", nodePath: pathOf(support, root) },- measurement: {- name: "supportMinimumY",- actual: stable3(minimumY),- expected: 0,- threshold: VEGETATION_CONTACT_TOLERANCE_METERS,- unit: "m"- },- viewHints: ["right", "vegetation.base-contact"],- repairText: "Raise or trim the declared trunk/stem/root support so its visible material stops at Y=0."- }));- }- return findings;-}-function materialNames(node) {- if (!(node instanceof THREE9.Mesh))- return [];- const materials = Array.isArray(node.material) ? node.material : [node.material];- return materials.filter(Boolean).map((material) => material.name ?? "");-}-function evaluateVegetationScopeQa(context) {- const trusted = vegetationIntent(context.intent);- if (!trusted?.standalone || !(context.scene instanceof THREE9.Object3D))- return [];- const root = context.scene;- const renderables = collectRenderableBounds(root);- if (renderables.length === 0)- return [];- const overall = renderables.reduce((box, value) => box.union(value.box), new THREE9.Box3);- const overallSize = overall.getSize(new THREE9.Vector3);- const findings = [];- for (const value of renderables) {- const size = value.box.getSize(new THREE9.Vector3);- const center = value.box.getCenter(new THREE9.Vector3);- const names = [value.node.name, ...value.roles];- const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));- const roleEvidence = value.roles.some((role) => /(?:terrain|soil|rock|pot|planter|base)/i.test(role));- const materialEvidence = materialNames(value.node).some((name) => CLUTTER_NAME.test(name));- const footprintRatio = size.x * size.z / Math.max(0.000000001, overallSize.x * overallSize.z);- const flatEvidence = footprintRatio >= 0.35 && size.y <= Math.max(0.08, overallSize.y * 0.08) && center.y <= VEGETATION_CONTACT_TOLERANCE_METERS + size.y;- const evidence2 = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);- if (evidence2.length < 2)- continue;- findings.push(finding2(context, {- code: "VEG_SCOPE_EXTRA",- disposition: "warn",- dimension: "promptAlignment",- message: `${value.node.name || "Renderable"} is likely unrequested standalone-vegetation base clutter; review before removal.`,- affected: {- node: value.node.name || "vegetation-extra",- nodePath: pathOf(value.node, root)- },- measurement: {- name: "scopeEvidence",- actual: [- nameEvidence ? "name" : "",- roleEvidence ? "role" : "",- materialEvidence ? "material" : "",- flatEvidence ? "flat-footprint" : ""- ].filter(Boolean).join(","),- expected: "standalone plant/fungus only"- },- viewHints: ["top", "three-quarter", "vegetation.base-contact"]- }));- }- return findings;-}-function unionVolume(boxes) {- if (boxes.length === 0)- return 0;- const union = boxes.reduce((result, box) => result.union(box), new THREE9.Box3);- const size = union.getSize(new THREE9.Vector3);- return size.x * size.y * size.z;-}-function projectedOccupancy(boxes, axes2) {- if (boxes.length === 0)- return 0;- const minimum = [Infinity, Infinity];- const maximum = [-Infinity, -Infinity];- for (const box of boxes) {- const min = [box.min.x, box.min.y, box.min.z];- const max = [box.max.x, box.max.y, box.max.z];- for (const dimension of [0, 1]) {- minimum[dimension] = Math.min(minimum[dimension], min[axes2[dimension]]);- maximum[dimension] = Math.max(maximum[dimension], max[axes2[dimension]]);- }- }- const spans = [maximum[0] - minimum[0], maximum[1] - minimum[1]];- if (spans[0] <= 0.000000001 || spans[1] <= 0.000000001)- return 0;- const occupied = new Uint8Array(RASTER_SIZE * RASTER_SIZE);- for (const box of boxes) {- const min = [box.min.x, box.min.y, box.min.z];- const max = [box.max.x, box.max.y, box.max.z];- const x0 = Math.max(0, Math.floor((min[axes2[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes2[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const y0 = Math.max(0, Math.floor((min[axes2[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));- const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes2[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));- for (let y = y0;y <= y1; y++) {- for (let x = x0;x <= x1; x++)- occupied[y * RASTER_SIZE + x] = 1;- }- }- return stable3(occupied.reduce((sum, value) => sum + value, 0) / occupied.length);-}-function matchesAny(value, patterns) {- const candidates = [value.node.name, ...value.roles];- return candidates.some((candidate) => patterns.some((pattern) => pattern.test(candidate)));-}-function measurementSource(values) {- if (values.length === 0)- return "none";- const semantic3 = values.some((value) => value.source === "semantic");- const fallback = values.some((value) => value.source === "fallback");- return semantic3 && fallback ? "mixed" : semantic3 ? "semantic" : "fallback";-}-function roleOrNameSource(value, patterns) {- if (value.roles.some((role) => patterns.some((pattern) => pattern.test(role))))- return "semantic";- if (patterns.some((pattern) => pattern.test(value.node.name)))- return "fallback";- return;-}-function growthCandidates(root) {- const result = [];- for (const value of collectRenderableBounds(root)) {- const branchSource = roleOrNameSource(value, BRANCH_PATTERNS);- const trunkSource = roleOrNameSource(value, TRUNK_PATTERNS);- if (branchSource)- result.push({ ...value, kind: "branch", growthSource: branchSource });- else if (trunkSource)- result.push({ ...value, kind: "trunk", growthSource: trunkSource });- }- return result;-}-function boxDistanceToPoint(box, point) {- return box.distanceToPoint(point);-}-function endpointRadius(position, axis, axisValue, tolerance, scale2) {- const radialAxes = [0, 1, 2].filter((value) => value !== axis);- const points = [];- const point = new THREE9.Vector3;- for (let index = 0;index < position.count; index++) {- point.fromBufferAttribute(position, index);- if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)- points.push(point.clone());- }- if (points.length === 0)- return;- const center = new THREE9.Vector3;- center.setComponent(axis, axisValue);- for (const radialAxis of radialAxes) {- center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);- }- let radius = 0;- for (const value of points) {- const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale2.getComponent(radialAxes[0]));- const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale2.getComponent(radialAxes[1]));- radius = Math.max(radius, Math.hypot(a, b));- }- return { center, radius };-}-function growthNodeMeasurement(root, candidate, allCandidates, band) {- if (!(candidate.node instanceof THREE9.Mesh))- return;- const geometry = candidate.node.geometry;- const position = geometry.getAttribute("position");- if (!position || position.count < 2)- return;- geometry.computeBoundingBox();- const geometryBox = geometry.boundingBox;- if (!geometryBox || geometryBox.isEmpty())- return;- root.updateWorldMatrix(true, true);- const relative2 = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);- const relativeScale = new THREE9.Vector3;- relative2.decompose(new THREE9.Vector3, new THREE9.Quaternion, relativeScale);- const size = geometryBox.getSize(new THREE9.Vector3);- const scaledSizes = [- Math.abs(size.x * relativeScale.x),- Math.abs(size.y * relativeScale.y),- Math.abs(size.z * relativeScale.z)- ];- const axis = scaledSizes.indexOf(Math.max(...scaledSizes));- const minimum = geometryBox.min.getComponent(axis);- const maximum = geometryBox.max.getComponent(axis);- const tolerance = Math.max(0.000001, (maximum - minimum) * 0.0001);- const first = endpointRadius(position, axis, minimum, tolerance, relativeScale);- const second = endpointRadius(position, axis, maximum, tolerance, relativeScale);- if (!first || !second)- return;- const firstPoint = first.center.clone().applyMatrix4(relative2);- const secondPoint = second.center.clone().applyMatrix4(relative2);- const supportBoxes = allCandidates.filter((value) => value !== candidate).map((value) => value.box);- let firstIsBase;- if (candidate.kind === "trunk") {- firstIsBase = firstPoint.y <= secondPoint.y;- } else if (supportBoxes.length > 0) {- const firstGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, firstPoint)));- const secondGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, secondPoint)));- firstIsBase = Math.abs(firstGap - secondGap) > 0.000001 ? firstGap < secondGap : first.radius >= second.radius;- } else {- firstIsBase = first.radius >= second.radius;- }- const baseRadius = firstIsBase ? first.radius : second.radius;- const tipRadius = firstIsBase ? second.radius : first.radius;- const length3 = firstPoint.distanceTo(secondPoint);- const averageRadius = (baseRadius + tipRadius) / 2;- const taperRatio = baseRadius > 0.000000001 ? tipRadius / baseRadius : null;- const lengthRadiusRatio = averageRadius > 0.000000001 ? length3 / averageRadius : null;- const selected = band[candidate.kind];- const taperOutlier = taperRatio !== null && (taperRatio < selected.taper[0] || taperRatio > selected.taper[1]);- const lengthRadiusOutlier = lengthRadiusRatio !== null && (lengthRadiusRatio < selected.lengthRadius[0] || lengthRadiusRatio > selected.lengthRadius[1]);- return {- node: candidate.node.name || candidate.kind,- nodePath: pathOf(candidate.node, root),- kind: candidate.kind,- source: candidate.growthSource,- lengthMeters: stable3(length3),- baseRadiusMeters: stable3(baseRadius),- tipRadiusMeters: stable3(tipRadius),- taperRatio: taperRatio === null ? null : stable3(taperRatio),- lengthRadiusRatio: lengthRadiusRatio === null ? null : stable3(lengthRadiusRatio),- expectedTaperRatio: `${selected.taper[0]}..${selected.taper[1]}`,- expectedLengthRadiusRatio: `${selected.lengthRadius[0]}..${selected.lengthRadius[1]}`,- taperOutlier,- lengthRadiusOutlier- };-}-function measureVegetationGrowth(intent, root) {- const trusted = vegetationIntent(intent);- const subtype = trusted?.subtype ?? "custom";- const candidates = growthCandidates(root);- const nodes = candidates.map((candidate) => growthNodeMeasurement(root, candidate, candidates, VEGETATION_GROWTH_BANDS_V1[subtype])).filter((value) => Boolean(value));- return {- schemaVersion: 1,- subtype,- source: measurementSource(nodes),- trunkCount: nodes.filter((value) => value.kind === "trunk").length,- branchCount: nodes.filter((value) => value.kind === "branch").length,- nodes- };-}-function evaluateVegetationGrowthQa(context) {- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE9.Object3D))- return [];- const measured = measureVegetationGrowth(context.intent, context.scene);- const findings = [];- for (const node of measured.nodes) {- if (node.taperOutlier) {- findings.push(finding2(context, {- code: "VEG_GROWTH_TAPER_OUTLIER",- disposition: "warn",- dimension: "categoryReadiness",- message: `${node.kind} taper measurement is outside the ${measured.subtype} measurement band.`,- affected: { node: node.node, nodePath: node.nodePath },- measurement: {- name: "tipToBaseRadiusRatio",- actual: node.taperRatio ?? "unmeasurable",- expected: node.expectedTaperRatio,- unit: "ratio"- },- viewHints: ["front", "right", "three-quarter"]- }));- }- if (node.lengthRadiusOutlier) {- findings.push(finding2(context, {- code: "VEG_GROWTH_LENGTH_RADIUS_OUTLIER",- disposition: "warn",- dimension: "categoryReadiness",- message: `${node.kind} length/radius measurement is outside the ${measured.subtype} measurement band.`,- affected: { node: node.node, nodePath: node.nodePath },- measurement: {- name: "lengthToAverageRadiusRatio",- actual: node.lengthRadiusRatio ?? "unmeasurable",- expected: node.expectedLengthRadiusRatio,- unit: "ratio"- },- viewHints: ["front", "right", "three-quarter"]- }));- }- }- return findings;-}-function distanceBetweenBoxes(a, b) {- const dx = Math.max(0, a.min.x - b.max.x, b.min.x - a.max.x);- const dy = Math.max(0, a.min.y - b.max.y, b.min.y - a.max.y);- const dz = Math.max(0, a.min.z - b.max.z, b.min.z - a.max.z);- return Math.hypot(dx, dy, dz);-}-function measureVegetationFoliageAttachment(root) {- const renderables = collectRenderableBounds(root);- const support = renderables.filter((value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS));- const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));- const clusters = foliage.map((value) => {- const size = value.box.getSize(new THREE9.Vector3);- const threshold = stable3(Math.max(0.03, Math.min(0.18, size.length() * 0.12)));- const nearest = support.map((candidate) => ({ candidate, gap: distanceBetweenBoxes(value.box, candidate.box) })).sort((a, b) => a.gap - b.gap || (a.candidate.node.name || "").localeCompare(b.candidate.node.name || ""))[0];- const source = roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback";- return {- node: value.node.name || "foliage-cluster",- nodePath: pathOf(value.node, root),- source,- nearestSupport: nearest?.candidate.node.name || null,- gapMeters: nearest ? stable3(nearest.gap) : null,- thresholdMeters: threshold,- detached: !nearest || nearest.gap > threshold- };- });- return {- schemaVersion: 1,- source: measurementSource(clusters),- supportNodeCount: support.length,- foliageClusterCount: foliage.length,- clusters- };-}-function evaluateVegetationFoliageAttachmentQa(context) {- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE9.Object3D))- return [];- return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding2(context, {- code: "VEG_FOLIAGE_DETACHED",- disposition: "warn",- dimension: "categoryReadiness",- message: `${cluster.node} is detached from the nearest inferred or semantic branch/twig support.`,- affected: { node: cluster.node, nodePath: cluster.nodePath },- measurement: {- name: "foliageSupportGap",- actual: cluster.gapMeters ?? "no support found",- expected: `<=${cluster.thresholdMeters}`,- threshold: cluster.thresholdMeters,- unit: "m"- },- viewHints: ["front", "right", "three-quarter"]- }));-}-function relativeTransformSignature(root, node) {- const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);- const scale2 = new THREE9.Vector3;- const quaternion = new THREE9.Quaternion;- matrix.decompose(new THREE9.Vector3, quaternion, scale2);- if (quaternion.w < 0)- quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);- const values = [...scale2.toArray(), ...quaternion.toArray()].map((value) => stable3(value));- return values.join(",");-}-function measureVegetationRepetition(intent, root) {- root.updateWorldMatrix(true, true);- const foliage = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));- const bySignature = new Map;- for (const value of foliage) {- const signature = relativeTransformSignature(root, value.node);- const entries = bySignature.get(signature) ?? [];- entries.push(value);- bySignature.set(signature, entries);- }- const identicalTransformGroups = [...bySignature.entries()].filter(([, values]) => values.length >= 3).map(([signature, values]) => ({- signature,- nodes: values.map((value) => value.node.name || "foliage-cluster").sort()- })).sort((a, b) => a.signature.localeCompare(b.signature));- const supports = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, TRUNK_PATTERNS));- const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE9.Box3);- const centers = foliage.map((value) => value.box.getCenter(new THREE9.Vector3));- const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE9.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE9.Vector3);- const radial = centers.map((value) => ({- angle: Math.atan2(value.z - center.z, value.x - center.x),- radius: Math.hypot(value.x - center.x, value.z - center.z)- })).filter((value) => value.radius > 0.000001).sort((a, b) => a.angle - b.angle);- let radialGapRangeRadians = null;- let radialRadiusSpreadRatio = null;- let perfectRadialLockstep = false;- if (radial.length >= 4) {- const gaps = radial.map((value, index) => {- const next = radial[(index + 1) % radial.length];- const raw = next.angle - value.angle;- return raw > 0 ? raw : raw + Math.PI * 2;- });- radialGapRangeRadians = stable3(Math.max(...gaps) - Math.min(...gaps));- const radii = radial.map((value) => value.radius);- const meanRadius = radii.reduce((sum, value) => sum + value, 0) / radii.length;- radialRadiusSpreadRatio = stable3((Math.max(...radii) - Math.min(...radii)) / meanRadius);- perfectRadialLockstep = radialGapRangeRadians <= 0.02 && radialRadiusSpreadRatio <= 0.02;- }- const suppressedForTopiary = vegetationIntent(intent)?.canopyProfile === "topiary";- return {- schemaVersion: 1,- source: measurementSource(foliage.map((value) => ({- source: roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback"- }))),- clusterCount: foliage.length,- identicalTransformGroups,- radialGapRangeRadians,- radialRadiusSpreadRatio,- perfectRadialLockstep,- suppressedForTopiary- };-}-function evaluateVegetationRepetitionQa(context) {- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE9.Object3D))- return [];- const measured = measureVegetationRepetition(context.intent, context.scene);- if (measured.suppressedForTopiary)- return [];- const findings = measured.identicalTransformGroups.map((group) => finding2(context, {- code: "VEG_CLUSTER_TRANSFORM_REPEAT",- disposition: "warn",- dimension: "visualQuality",- message: `${group.nodes.length} foliage clusters use an identical scale/rotation signature.`,- affected: { node: group.nodes[0], nodePath: group.nodes.join(",") },- measurement: {- name: "identicalClusterTransformCount",- actual: group.nodes.length,- expected: "<3 outside formal topiary intent"- },- viewHints: ["front", "right", "top", "three-quarter"]- }));- if (measured.perfectRadialLockstep) {- findings.push(finding2(context, {- code: "VEG_CLUSTER_RADIAL_LOCKSTEP",- disposition: "warn",- dimension: "visualQuality",- message: "Foliage clusters form a perfect equal-radius, equal-angle radial sequence.",- measurement: {- name: "radialGapAndRadiusSpread",- actual: `${measured.radialGapRangeRadians},${measured.radialRadiusSpreadRatio}`,- expected: "angle gap range >0.02 or radius spread ratio >0.02",- unit: "ratio"- },- viewHints: ["top", "three-quarter"]- }));- }- return findings;-}-function measureVegetationCanopy(intent, root) {- const profile = vegetationIntent(intent)?.canopyProfile ?? "broadleaf";- const renderables = collectRenderableBounds(root);- const canopy = renderables.filter((value) => matchesAny(value, CANOPY_PATTERNS));- const trunk = renderables.filter((value) => matchesAny(value, TRUNK_PATTERNS));- const semanticCanopy = canopy.some((value) => value.roles.length > 0);- const source = canopy.length === 0 ? "none" : semanticCanopy ? "semantic" : "fallback";- const canopyBoxes = canopy.map((value) => value.box);- const trunkVolume = unionVolume(trunk.map((value) => value.box));- const ratio = trunkVolume > 0.000000001 ? unionVolume(canopyBoxes) / trunkVolume : null;- return {- schemaVersion: 1,- profile,- source,- canopyNodeCount: canopy.length,- trunkNodeCount: trunk.length,- frontOccupancy: projectedOccupancy(canopyBoxes, [2, 1]),- sideOccupancy: projectedOccupancy(canopyBoxes, [0, 1]),- topOccupancy: projectedOccupancy(canopyBoxes, [0, 2]),- canopyToTrunkVolumeRatio: ratio === null ? null : stable3(ratio)- };-}-function evaluateVegetationCanopyQa(context) {- const trusted = vegetationIntent(context.intent);- if (!trusted || !(context.scene instanceof THREE9.Object3D))- return [];- const measurements = measureVegetationCanopy(context.intent, context.scene);- const bands = PROFILE_BANDS[measurements.profile];- const sparseFactor = trusted.growthState === "sparse" ? 0.55 : 1;- const values = [- ["FRONT", "frontOccupancy", measurements.frontOccupancy, bands.occupancy.front, "front"],- ["SIDE", "sideOccupancy", measurements.sideOccupancy, bands.occupancy.side, "right"],- ["TOP", "topOccupancy", measurements.topOccupancy, bands.occupancy.top, "top"]- ];- const findings = [];- if (measurements.canopyNodeCount === 0 && measurements.profile !== "bare/dead") {- findings.push(finding2(context, {- code: "VEG_CANOPY_MISSING",- disposition: "warn",- dimension: "categoryReadiness",- message: `The ${trusted.subtype} profile resolved no semantic or inferred canopy renderables.`,- measurement: { name: "canopyNodeCount", actual: 0, expected: ">=1" },- viewHints: ["front", "right", "top"]- }));- return findings;- }- for (const [suffix, name, actual, [minimum, maximum], view] of values) {- const adjustedMinimum = minimum * sparseFactor;- if (actual >= adjustedMinimum && actual <= maximum)- continue;- findings.push(finding2(context, {- code: `VEG_CANOPY_OCCUPANCY_${suffix}`,- disposition: "warn",- dimension: "categoryReadiness",- message: `${measurements.profile} ${name} is outside its measured ${trusted.growthState} profile band.`,- measurement: {- name,- actual,- expected: `${stable3(adjustedMinimum)}..${maximum}`,- threshold: adjustedMinimum,- unit: "ratio"- },- viewHints: [view, "three-quarter"]- }));- }- const ratio = measurements.canopyToTrunkVolumeRatio;- if (ratio !== null && (ratio < bands.ratio[0] || ratio > bands.ratio[1])) {- findings.push(finding2(context, {- code: "VEG_CANOPY_TRUNK_RATIO",- disposition: "warn",- dimension: "categoryReadiness",- message: `${measurements.profile} canopy-to-trunk volume ratio is outside its subtype band.`,- measurement: {- name: "canopyToTrunkVolumeRatio",- actual: ratio,- expected: `${bands.ratio[0]}..${bands.ratio[1]}`,- threshold: bands.ratio[0],- unit: "ratio"- },- viewHints: ["front", "right", "top"]- }));- }- return findings;-}-function materialValue(material) {- if (!(material instanceof THREE9.MeshStandardMaterial) && !(material instanceof THREE9.MeshBasicMaterial)) {- return;- }- const color = material.color;- return 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;-}-function measureVegetationFoliageMaterials(intent, root) {- const values = [];- let foliageNodeCount = 0;- root.traverse((node) => {- if (!(node instanceof THREE9.Mesh))- return;- const bounds = {- node,- box: new THREE9.Box3,- roles: rolesOf(node),- source: rolesOf(node).length > 0 ? "semantic" : "fallback"- };- if (!matchesAny(bounds, CANOPY_PATTERNS))- return;- foliageNodeCount++;- const materials = Array.isArray(node.material) ? node.material : [node.material];- for (const material of materials) {- const value = materialValue(material);- if (value !== undefined)- values.push(value);- }- });- const buckets = new Set(values.map((value) => Math.round(value * 20) / 20));- const valueRange = values.length > 0 ? Math.max(...values) - Math.min(...values) : 0;- const optimized = intent.material.mode === "flatOptimized";- return {- schemaVersion: 1,- mode: intent.material.mode,- foliageNodeCount,- valueRoleCount: buckets.size,- valueRange: stable3(valueRange),- coherent: optimized ? buckets.size <= 1 : buckets.size >= 2 && buckets.size <= 6 && valueRange >= 0.03- };-}-function evaluateVegetationMaterialQa(context) {- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE9.Object3D))- return [];- const measured = measureVegetationFoliageMaterials(context.intent, context.scene);- if (measured.foliageNodeCount === 0 || measured.coherent)- return [];- const optimized = measured.mode === "flatOptimized";- return [- finding2(context, {- code: "VEG_FOLIAGE_VALUE_ROLES",- disposition: "warn",- dimension: "visualQuality",- message: optimized ? "Optimized vegetation should retain one coherent foliage value role." : "Rich organic vegetation should use two to six restrained foliage value roles with visible value separation.",- measurement: {- name: "foliageValueRoles",- actual: `${measured.valueRoleCount} roles; range ${measured.valueRange}`,- expected: optimized ? "1 role" : "2..6 roles; range >=0.03"- },- viewHints: ["front", "three-quarter"]- })- ];-}-function evaluateVegetationAdvisoryQa(context) {- return [- ...evaluateVegetationScopeQa(context),- ...evaluateVegetationGrowthQa(context),- ...evaluateVegetationCanopyQa(context),- ...evaluateVegetationFoliageAttachmentQa(context),- ...evaluateVegetationRepetitionQa(context),- ...evaluateVegetationMaterialQa(context)- ];-}-var PROFILE2 = "vegetation.semantic", VEGETATION_CONTACT_TOLERANCE_METERS = 0.02, RASTER_SIZE = 48, stable3 = (value) => Math.round(value * 1e6) / 1e6, CLUTTER_NAME, CANOPY_PATTERNS, TRUNK_PATTERNS, BRANCH_PATTERNS, VEGETATION_GROWTH_BANDS_V1, PROFILE_BANDS, VEGETATION_CONTACT_QA_RULE, VEGETATION_ADVISORY_QA_RULE, VEGETATION_QA_RULES;-var init_vegetation = __esm(() => {- init_contracts();- init_registry();- CLUTTER_NAME = /(?:^|[._ -])(?:terrain|soil|dirt|mound|rock|stone|pot|planter|grass[._ -]?skirt|base[._ -]?(?:disk|plate))(?:$|[._ -])/i;- CANOPY_PATTERNS = [/(?:^|[._ -])(?:canopy|foliage|leaf|leaves|needle|frond)(?:$|[._ -])/i];- TRUNK_PATTERNS = [/(?:^|[._ -])(?:trunk|stem|stalk|branch-primary)(?:$|[._ -])/i];- BRANCH_PATTERNS = [- /(?:^|[._ -])(?:branch|twig|bough|limb)(?:$|[._ -])/i,- /^vegetation\.branch(?:\.|$)/i- ];- VEGETATION_GROWTH_BANDS_V1 = Object.freeze({- tree: {- trunk: { taper: [0.35, 1.05], lengthRadius: [4, 80] },- branch: { taper: [0.12, 1.05], lengthRadius: [4, 100] }- },- conifer: {- trunk: { taper: [0.25, 1.05], lengthRadius: [6, 110] },- branch: { taper: [0.1, 1.05], lengthRadius: [5, 140] }- },- shrub: {- trunk: { taper: [0.25, 1.1], lengthRadius: [2, 65] },- branch: { taper: [0.1, 1.1], lengthRadius: [2, 80] }- },- grass: {- trunk: { taper: [0.05, 1.15], lengthRadius: [6, 260] },- branch: { taper: [0.05, 1.15], lengthRadius: [5, 260] }- },- "frond/palm": {- trunk: { taper: [0.35, 1.05], lengthRadius: [6, 140] },- branch: { taper: [0.04, 1.1], lengthRadius: [8, 300] }- },- vine: {- trunk: { taper: [0.1, 1.15], lengthRadius: [8, 320] },- branch: { taper: [0.04, 1.15], lengthRadius: [8, 360] }- },- "crop/flower": {- trunk: { taper: [0.15, 1.1], lengthRadius: [5, 220] },- branch: { taper: [0.05, 1.15], lengthRadius: [4, 240] }- },- succulent: {- trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },- branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] }- },- fungus: {- trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },- branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] }- },- aquatic: {- trunk: { taper: [0.08, 1.15], lengthRadius: [4, 260] },- branch: { taper: [0.04, 1.15], lengthRadius: [4, 300] }- },- "bare/dead": {- trunk: { taper: [0.25, 1.05], lengthRadius: [4, 100] },- branch: { taper: [0.08, 1.05], lengthRadius: [3, 140] }- },- custom: {- trunk: { taper: [0.05, 1.25], lengthRadius: [1.2, 320] },- branch: { taper: [0.03, 1.25], lengthRadius: [1.2, 360] }- }- });- PROFILE_BANDS = Object.freeze({- broadleaf: {- occupancy: { front: [0.4, 0.99], side: [0.4, 0.99], top: [0.32, 0.99] },- ratio: [1.5, 120]- },- conifer: {- occupancy: { front: [0.32, 0.97], side: [0.32, 0.97], top: [0.2, 0.95] },- ratio: [1, 100]- },- topiary: {- occupancy: { front: [0.62, 1], side: [0.62, 1], top: [0.58, 1] },- ratio: [1, 120]- },- "bare/dead": {- occupancy: { front: [0, 0.08], side: [0, 0.08], top: [0, 0.08] },- ratio: [0, 0.2]- }- });- VEGETATION_CONTACT_QA_RULE = {- id: "VEGETATION_CONTACT_PROFILE",- profile: PROFILE2,- scope: { kind: "category", category: "vegetation" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("vegetation-contact-v1", "src/qa/vegetation.test.ts", "8ad8f1753fc76e5e1b0114ad7d7f2c6c02c6f1c60953727027219424422a8ac4"),- defaultMode: "enforce",- evaluate: evaluateVegetationContactQa- };- VEGETATION_ADVISORY_QA_RULE = {- id: "VEGETATION_ADVISORY_PROFILE",- profile: "vegetation.advisory",- scope: { kind: "category", category: "vegetation" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: evaluateVegetationAdvisoryQa- };- VEGETATION_QA_RULES = [- VEGETATION_CONTACT_QA_RULE,- VEGETATION_ADVISORY_QA_RULE- ];-});--// src/qa/prop.ts-import * as THREE10 from "three";-function finding3(context, value) {- return { ...value, profile: context.intent.qaProfile || PROFILE3 };-}-function rolesOf2(node) {- return readSemanticMetadataV1(node)?.roles ?? [];-}-function nodePath2(root, node) {- const names = [];- let cursor = node;- while (cursor) {- names.push(cursor.name || cursor.type);- if (cursor === root)- break;- cursor = cursor.parent;- }- return names.reverse().join("/");-}-function transformedBox(source, transform) {- const result = new THREE10.Box3;- for (const x of [source.min.x, source.max.x]) {- for (const y of [source.min.y, source.max.y]) {- for (const z3 of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE10.Vector3(x, y, z3).applyMatrix4(transform));- }- }- }- return result;-}-function collectParts(root) {- root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();- const result = [];- root.traverse((node) => {- const roles2 = rolesOf2(node);- const renderable = node instanceof THREE10.Mesh;- let box;- if (renderable && node.geometry instanceof THREE10.BufferGeometry) {- node.geometry.computeBoundingBox();- if (node.geometry.boundingBox) {- box = transformedBox(node.geometry.boundingBox, rootInverse2.clone().multiply(node.matrixWorld));- }- } else if (roles2.length > 0) {- box = transformedBox(new THREE10.Box3(new THREE10.Vector3(-0.5, -0.5, -0.5), new THREE10.Vector3(0.5, 0.5, 0.5)), rootInverse2.clone().multiply(node.matrixWorld));- }- if (box?.isEmpty())- box = undefined;- result.push({ node, roles: roles2, ...box ? { box } : {}, renderable });- });- return result;-}-function descendantOf(node, ancestor) {- let cursor = node;- while (cursor) {- if (cursor === ancestor)- return true;- cursor = cursor.parent;- }- return false;-}-function boxesOverlap(a, b, inset = 0) {- return a.min.x < b.max.x - inset && a.max.x > b.min.x + inset && a.min.y < b.max.y - inset && a.max.y > b.min.y + inset && a.min.z < b.max.z - inset && a.max.z > b.min.z + inset;-}-function motionAssemblies(parts) {- const values = new Map;- const get = (kind, id) => {- const key = `${kind}:${id}`;- let value = values.get(key);- if (!value) {- value = { kind, id };- values.set(key, value);- }- return value;- };- for (const part of parts) {- for (const role of part.roles) {- const pivot = /^prop\.pivot\.(hinge|slider|spinner)\.([^.]+)$/.exec(role);- if (pivot)- get(pivot[1], pivot[2]).pivot = part;- const moving = /^prop\.motion\.(hinge|slider|spinner)\.([^.]+)$/.exec(role);- if (moving)- get(moving[1], moving[2]).moving = part;- const clearance = /^prop\.clearance\.(?:hinge\.|slider\.|spinner\.)?([^.]+)$/.exec(role);- if (clearance) {- const direct = Array.from(values.values()).find((value) => value.id === clearance[1]);- if (direct)- direct.clearance = part;- }- }- }- for (const part of parts) {- for (const role of part.roles) {- const match = /^prop\.clearance\.(?:(hinge|slider|spinner)\.)?([^.]+)$/.exec(role);- if (!match)- continue;- if (match[1])- get(match[1], match[2]).clearance = part;- else {- const candidates = Array.from(values.values()).filter((value) => value.id === match[2]);- if (candidates.length === 1)- candidates[0].clearance = part;- }- }- }- return Array.from(values.values()).sort((a, b) => `${a.kind}:${a.id}`.localeCompare(`${b.kind}:${b.id}`));-}-function hasMotionAxis(part) {- const frames = readSemanticMetadataV1(part.node)?.frames ?? [];- return frames.some((frame) => /^(?:prop\.)?(?:motion-)?axis\.[+-]?[xyz]$/.test(frame.id));-}-function usesExplicitLegacyProfile(context) {- return context.intent.qaProfile === "prop.legacy" || context.intent.qaProfile === "prop.legacy-control";-}-function allowedClearanceContactRoles(assembly) {- const result = new Set;- for (const part of [assembly.pivot, assembly.clearance]) {- const metadata = part ? readSemanticMetadataV1(part.node) : undefined;- for (const relationship of metadata?.relationships ?? []) {- if (relationship.targetType === "role" && /^(?:mountedTo|allowsContact|allowsClearanceContact)$/.test(relationship.kind) && /^prop\.articulation\.support\.[^.]+$/.test(relationship.target)) {- result.add(relationship.target);- }- }- }- return result;-}-function legacyArticulationEvidence(context, root) {- const joints = [];- root.traverse((node) => {- if (/^(?:Joint|Pivot)[_.-]/i.test(node.name))- joints.push(node.name);- });- if (joints.length === 0)- return false;- const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE10.AnimationClip);- if ((context.intent.animation?.clips.length ?? 0) === 0 && clips.length === 0)- return true;- const targets = new Set(clips.flatMap((clip) => clip.tracks.map((track) => track.name.split(".")[0] ?? "")));- return joints.some((joint) => targets.has(joint));-}-function evaluatePropArticulationQa(context) {- if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE10.Object3D)) {- return [];- }- const root = context.scene;- const parts = collectParts(root);- const assemblies = motionAssemblies(parts);- if (assemblies.length === 0) {- if (usesExplicitLegacyProfile(context) && legacyArticulationEvidence(context, root))- return [];- return [- finding3(context, {- code: "PROP_ARTICULATION_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: "articulated=true requires a semantic hinge, slider, or spinner assembly with a real pivot and moving subtree.",- affected: { node: root.name || "prop-root" },- measurement: { name: "motionAssemblyCount", actual: 0, expected: ">=1", threshold: 1 },- viewHints: ["front", "right", "top"],- repairText: "Create prop.pivot.<hinge|slider|spinner>.<id>, parent only prop.motion.<kind>.<id> beneath it, and add an axis frame plus prop.clearance.<id>."- })- ];- }- const findings = [];- for (const assembly of assemblies) {- const label = `${assembly.kind}.${assembly.id}`;- if (!assembly.pivot) {- findings.push(finding3(context, {- code: "PROP_ARTICULATION_PIVOT_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: `Motion assembly ${label} has no semantic pivot.`,- affected: { node: assembly.moving?.node.name || label },- measurement: { name: "pivotCount", actual: 0, expected: 1, threshold: 1 },- viewHints: ["right", "top"],- repairText: `Add prop.pivot.${label} at the physical hinge/rail/axle origin.`- }));- continue;- }- if (!hasMotionAxis(assembly.pivot)) {- findings.push(finding3(context, {- code: "PROP_ARTICULATION_AXIS_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: `Motion pivot ${label} has no declared local axis frame.`,- affected: {- node: assembly.pivot.node.name || label,- nodePath: nodePath2(root, assembly.pivot.node)- },- measurement: { name: "motionAxisFrameCount", actual: 0, expected: 1, threshold: 1 },- viewHints: ["right", "top"],- repairText: `Add a normalized axis.+x, axis.+y, or axis.+z frame to prop.pivot.${label}.`- }));- }- if (!assembly.moving || !descendantOf(assembly.moving.node, assembly.pivot.node)) {- findings.push(finding3(context, {- code: "PROP_ARTICULATION_SUBTREE_INVALID",- disposition: "block",- dimension: "categoryReadiness",- message: `Motion assembly ${label} does not own exactly its declared moving subtree beneath the pivot.`,- affected: {- node: assembly.moving?.node.name || assembly.pivot.node.name || label,- nodePath: assembly.moving ? nodePath2(root, assembly.moving.node) : undefined- },- measurement: {- name: "movingSubtreeParentedToPivot",- actual: assembly.moving ? descendantOf(assembly.moving.node, assembly.pivot.node) : false,- expected: true- },- viewHints: ["front", "right"],- repairText: `Parent only prop.motion.${label} beneath prop.pivot.${label}; keep the static body outside that subtree.`- }));- }- if (!assembly.clearance?.box) {- findings.push(finding3(context, {- code: "PROP_ARTICULATION_CLEARANCE_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: `Motion assembly ${label} has no measurable semantic sweep/clearance prism.`,- affected: { node: assembly.pivot.node.name || label },- measurement: { name: "clearanceMarkerCount", actual: 0, expected: 1, threshold: 1 },- viewHints: ["front", "right", "top"],- repairText: `Add a non-rendered scaled prop.clearance.${label} marker covering the requested motion sweep.`- }));- continue;- }- const allowedStationaryRoles = allowedClearanceContactRoles(assembly);- const blocker = parts.find((part) => part.renderable && part.box && !descendantOf(part.node, assembly.pivot.node) && !part.roles.some((role) => allowedStationaryRoles.has(role)) && boxesOverlap(part.box, assembly.clearance.box, CLEARANCE_TOLERANCE_METERS));- if (blocker) {- findings.push(finding3(context, {- code: "PROP_ARTICULATION_CLEARANCE_BLOCKED",- disposition: "block",- dimension: "categoryReadiness",- message: `Motion sweep ${label} is blocked by ${blocker.node.name || "an unnamed mesh"}.`,- affected: {- node: blocker.node.name || "prop-motion-blocker",- nodePath: nodePath2(root, blocker.node)- },- measurement: {- name: "motionClearanceBlockerCount",- actual: 1,- expected: 0,- threshold: 0- },- viewHints: ["front", "right", "top"],- repairText: `Remove only the reported blocker from prop.clearance.${label}; do not move unrelated geometry.`- }));- }- }- return findings;-}-function rolePart(parts, expression) {- return parts.find((part) => part.roles.some((role) => expression.test(role)));-}-function interiorUsable(box) {- const size = box.getSize(new THREE10.Vector3);- return size.x >= 0.08 && size.y >= 0.08 && size.z >= 0.08;-}-function evaluatePropContainerQa(context) {- if (context.intent.category !== "prop" || !(context.scene instanceof THREE10.Object3D))- return [];- const explicitlyOpen = context.intent.capabilities.includes("openable");- const explicitContainment = /^(?:open-)?(?:container|chest|case|box)$/i.test(context.intent.subtype ?? "");- if (!explicitlyOpen && !explicitContainment)- return [];- const root = context.scene;- const parts = collectParts(root);- const interior = rolePart(parts, /^prop\.container\.interior(?:\.|$)/);- const opening = rolePart(parts, /^prop\.container\.opening(?:\.|$)/);- const hasSemanticContainerEvidence = Boolean(interior || opening);- if (!hasSemanticContainerEvidence) {- const names = [];- root.traverse((node) => names.push(node.name));- if (usesExplicitLegacyProfile(context) && names.some((name) => /^(?:Joint|Pivot)[_.-].*(?:lid|door|hatch)/i.test(name)) && names.some((name) => /(?:Mesh[_.-])?(?:lid|door|hatch)/i.test(name))) {- return [];- }- if (!explicitlyOpen)- return [];- return [- finding3(context, {- code: "PROP_CONTAINER_OPENING_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: "openable=true has no semantic opening/interior markers or canonical jointed lid.",- affected: { node: root.name || "prop-root" },- measurement: {- name: "containerOpeningEvidenceCount",- actual: 0,- expected: ">=1",- threshold: 1- },- viewHints: ["front", "right", "top"],- repairText: "Author distinct prop.container.opening.main and prop.container.interior.main clearance markers; do not fill the interior with a solid mesh."- })- ];- }- const findings = [];- if (!interior?.box) {- findings.push(finding3(context, {- code: "PROP_CONTAINER_INTERIOR_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: "The semantic container profile has no measurable interior negative-space prism.",- affected: { node: root.name || "prop-root" },- measurement: { name: "containerInteriorMarkerCount", actual: 0, expected: 1, threshold: 1 },- viewHints: ["front", "top"],- repairText: "Add a non-rendered scaled prop.container.interior.main marker inside the shell."- }));- } else if (!interiorUsable(interior.box)) {- const size = interior.box.getSize(new THREE10.Vector3);- findings.push(finding3(context, {- code: "PROP_CONTAINER_INTERIOR_UNUSABLE",- disposition: "block",- dimension: "categoryReadiness",- message: "The declared container interior has no usable three-dimensional negative space.",- affected: {- node: interior.node.name || "container-interior",- nodePath: nodePath2(root, interior.node)- },- measurement: {- name: "minimumInteriorExtent",- actual: stable4(Math.min(size.x, size.y, size.z)),- expected: ">=0.08",- threshold: 0.08,- unit: "m"- },- viewHints: ["front", "top"],- repairText: "Enlarge the interior marker and remove solid filler so all three clear extents are at least 0.08 m."- }));- }- if (!opening?.box) {- findings.push(finding3(context, {- code: "PROP_CONTAINER_OPENING_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: "The semantic container profile has no measurable opening into its interior.",- affected: { node: root.name || "prop-root" },- measurement: { name: "containerOpeningMarkerCount", actual: 0, expected: 1, threshold: 1 },- viewHints: ["front", "top"],- repairText: "Add a non-rendered scaled prop.container.opening.main marker connecting outside to the interior."- }));- } else {- const blocker = parts.find((part) => part.renderable && part.box && !part.roles.some((role) => role.startsWith("prop.container.shell") || role.startsWith("prop.container.lid") || role.startsWith("prop.motion.")) && boxesOverlap(part.box, opening.box, CLEARANCE_TOLERANCE_METERS));- if (blocker) {- findings.push(finding3(context, {- code: "PROP_CONTAINER_OPENING_BLOCKED",- disposition: "block",- dimension: "categoryReadiness",- message: `Container opening is blocked by ${blocker.node.name || "an unnamed solid filler"}.`,- affected: {- node: blocker.node.name || "container-blocker",- nodePath: nodePath2(root, blocker.node)- },- measurement: {- name: "containerOpeningBlockerCount",- actual: 1,- expected: 0,- threshold: 0- },- viewHints: ["front", "top"],- repairText: "Remove or split only the reported filler so the opening connects to the interior negative space."- }));- }- }- return findings;-}-function horizontalDirection(part, root) {- if (!(part.node instanceof THREE10.Mesh) || !(part.node.geometry instanceof THREE10.BufferGeometry)) {- return;- }- part.node.geometry.computeBoundingBox();- const box = part.node.geometry.boundingBox;- if (!box)- return;- const size = box.getSize(new THREE10.Vector3);- const axis = size.x >= size.z ? new THREE10.Vector3(1, 0, 0) : new THREE10.Vector3(0, 0, 1);- root.updateWorldMatrix(true, true);- const rootQuaternion = root.getWorldQuaternion(new THREE10.Quaternion).invert();- return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE10.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();-}-function evaluatePropCircularAssemblyQa(context) {- if (context.intent.category !== "prop" || !(context.scene instanceof THREE10.Object3D))- return [];- const root = context.scene;- const parts = collectParts(root);- const tagged = parts.some((part) => part.roles.some((role) => role === "prop.circular.assembly" || role.startsWith("prop.circular.member.")));- const namedProfile = /(?:barrel|drum)/i.test(context.intent.subtype ?? "");- if (!tagged && !namedProfile)- return [];- const memberParts = parts.filter((part) => part.box && (part.roles.some((role) => role.startsWith("prop.circular.member.")) || namedProfile && /(?:stave|ring[_.-]?segment)/i.test(part.node.name)));- if (memberParts.length < 3)- return [];- const centers = memberParts.map((part) => part.box.getCenter(new THREE10.Vector3));- const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE10.Vector3).multiplyScalar(1 / centers.length);- const members = memberParts.map((part, index) => {- const center = centers[index];- return {- part,- center,- angle: Math.atan2(center.z - ringCenter.z, center.x - ringCenter.x),- horizontalDirection: horizontalDirection(part, root)- };- });- members.sort((a, b) => a.angle - b.angle);- const gaps = members.map((member, index) => {- const next = members[(index + 1) % members.length];- return (next.angle - member.angle + Math.PI * 2) % (Math.PI * 2);- });- const expectedGap = Math.PI * 2 / members.length;- const maximumGap = Math.max(...gaps);- const findings = [];- if (maximumGap > Math.max(Math.PI / 3, expectedGap * 1.5)) {- findings.push(finding3(context, {- code: "PROP_CIRCULAR_RING_INCOMPLETE",- disposition: "warn",- dimension: "visualQuality",- message: `Circular assembly has a likely missing sector of ${(maximumGap * 180 / Math.PI).toFixed(2)} degrees.`,- affected: { node: root.name || "prop-root" },- measurement: {- name: "maximumAngularGap",- actual: stable4(maximumGap * 180 / Math.PI),- expected: `<=${stable4(Math.max(60, expectedGap * 1.5 * 180 / Math.PI))}`,- unit: "deg"- },- viewHints: ["top", "three-quarter"]- }));- }- const expectedOrientation = parts.some((part) => part.roles.includes("prop.circular.expected.radial")) ? "radial" : "tangent";- const wrong = members.filter((member) => {- if (!member.horizontalDirection)- return false;- const radial = member.center.clone().sub(ringCenter).setY(0).normalize();- const tangent = new THREE10.Vector3(-radial.z, 0, radial.x);- const radialScore = Math.abs(member.horizontalDirection.dot(radial));- const tangentScore = Math.abs(member.horizontalDirection.dot(tangent));- return expectedOrientation === "tangent" ? tangentScore + 0.1 < radialScore : radialScore + 0.1 < tangentScore;- });- if (wrong.length > 0) {- findings.push(finding3(context, {- code: "PROP_CIRCULAR_MEMBER_ORIENTATION",- disposition: "warn",- dimension: "visualQuality",- message: `${wrong.length} circular members appear ${expectedOrientation === "tangent" ? "radial" : "tangent"} instead of ${expectedOrientation}.`,- affected: {- node: wrong[0].part.node.name || "circular-member",- nodePath: nodePath2(root, wrong[0].part.node)- },- measurement: {- name: "misorientedCircularMemberCount",- actual: wrong.length,- expected: 0,- threshold: 0- },- viewHints: ["top", "three-quarter"]- }));- }- return findings;-}-function evaluatePropScalePivotQa(context) {- if (context.intent.category !== "prop" || !(context.scene instanceof THREE10.Object3D))- return [];- const root = context.scene;- const parts = collectParts(root);- const renderable = parts.filter((part) => part.renderable && part.box);- if (renderable.length === 0)- return [];- const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE10.Box3);- const size = bounds.getSize(new THREE10.Vector3);- const findings = [];- for (const axis of ["x", "y", "z"]) {- const expected = context.intent.bounds?.[axis];- if (expected === undefined)- continue;- const actual = size[axis];- const tolerance = Math.max(0.05, expected * 0.2);- if (Math.abs(actual - expected) <= tolerance)- continue;- findings.push(finding3(context, {- code: "PROP_SCALE_BOUNDS_MISMATCH",- disposition: "warn",- dimension: "promptAlignment",- message: `Prop ${axis.toUpperCase()} extent is ${actual.toFixed(4)} m, outside the declared ${expected.toFixed(4)} m scale band.`,- affected: { node: root.name || "prop-root", attribute: `bounds.${axis}` },- measurement: {- name: `bounds.${axis}`,- actual: stable4(actual),- expected: stable4(expected),- threshold: stable4(tolerance),- unit: "m"- },- viewHints: ["front", "right", "top"]- }));- }- if (context.intent.capabilities.includes("grounded")) {- if (Math.abs(bounds.min.y) > GROUND_TOLERANCE_METERS) {- findings.push(finding3(context, {- code: "PROP_GROUND_MISMATCH",- disposition: "warn",- dimension: "categoryReadiness",- message: `Grounded prop base is ${Math.abs(bounds.min.y).toFixed(6)} m ${bounds.min.y > 0 ? "above" : "below"} asset-local Y=0.`,- affected: { node: root.name || "prop-root" },- measurement: {- name: "minimumY",- actual: stable4(bounds.min.y),- expected: 0,- threshold: GROUND_TOLERANCE_METERS,- unit: "m"- },- viewHints: ["right", "three-quarter"]- }));- }- }- const placement = parts.find((part) => part.roles.includes("prop.pivot.placement"));- if (placement) {- const point = placement.node.getWorldPosition(new THREE10.Vector3);- point.applyMatrix4(root.matrixWorld.clone().invert());- const horizontalOutside = point.x < bounds.min.x - GROUND_TOLERANCE_METERS || point.x > bounds.max.x + GROUND_TOLERANCE_METERS || point.z < bounds.min.z - GROUND_TOLERANCE_METERS || point.z > bounds.max.z + GROUND_TOLERANCE_METERS;- const verticalDelta = Math.abs(point.y - bounds.min.y);- if (horizontalOutside || verticalDelta > GROUND_TOLERANCE_METERS) {- findings.push(finding3(context, {- code: "PROP_PLACEMENT_PIVOT_OFF_BASE",- disposition: "warn",- dimension: "categoryReadiness",- message: "Declared placement pivot is not on the prop support base.",- affected: {- node: placement.node.name || "placement-pivot",- nodePath: nodePath2(root, placement.node)- },- measurement: {- name: "placementPivotBaseDelta",- actual: stable4(verticalDelta),- expected: 0,- threshold: GROUND_TOLERANCE_METERS,- unit: "m"- },- viewHints: ["right", "top"]- }));- }- }- return findings;-}-var PROFILE3 = "prop.capability", GROUND_TOLERANCE_METERS = 0.02, CLEARANCE_TOLERANCE_METERS = 0.004, stable4 = (value) => Math.round(value * 1e6) / 1e6, PROP_EXACT_QA_RULE, PROP_ADVISORY_QA_RULE, PROP_QA_RULES;-var init_prop = __esm(() => {- init_contracts();- init_registry();- PROP_EXACT_QA_RULE = Object.freeze({- id: "PROP_CAPABILITY_EXACT_PROFILE",- profile: PROFILE3,- scope: { kind: "category", category: "prop" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("prop-capability-v1", "src/qa/prop.test.ts", "a152104990fa6b92eea3c201ce39497a5d165ee19080a29e42b96ebe450d936c"),- defaultMode: "enforce",- evaluate: (context) => [- ...evaluatePropArticulationQa(context),- ...evaluatePropContainerQa(context)- ]- });- PROP_ADVISORY_QA_RULE = Object.freeze({- id: "PROP_ADVISORY_PROFILE",- profile: "prop.advisory",- scope: { kind: "category", category: "prop" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: (context) => [- ...evaluatePropCircularAssemblyQa(context),- ...evaluatePropScalePivotQa(context)- ]- });- PROP_QA_RULES = [- PROP_EXACT_QA_RULE,- PROP_ADVISORY_QA_RULE- ];-});--// src/qa/part-connectivity.ts-import * as THREE11 from "three";-function collectParts2(root, exempt) {- const parts = [];- root.updateWorldMatrix(true, true);- root.traverse((node) => {- const mesh = node;- if (!mesh.isMesh || !mesh.geometry)- return;- const name = mesh.name || "(unnamed mesh)";- if (EXEMPT_NAME.test(name)) {- exempt.push(name);- return;- }- const box = new THREE11.Box3().setFromObject(mesh);- if (box.isEmpty())- return;- parts.push({ name, box });- });- return parts;-}-function boxGap(a, b) {- const dx = Math.max(0, Math.max(a.min.x - b.max.x, b.min.x - a.max.x));- const dy = Math.max(0, Math.max(a.min.y - b.max.y, b.min.y - a.max.y));- const dz = Math.max(0, Math.max(a.min.z - b.max.z, b.min.z - a.max.z));- return Math.hypot(dx, dy, dz);-}-function analyzePartConnectivity(root) {- const exempt = [];- const parts = collectParts2(root, exempt);- const report = {- partsAnalyzed: parts.length,- mainComponentSize: parts.length,- exempt,- groups: []- };- if (parts.length < 2)- return report;- const adjacency = parts.map(() => []);- for (let i = 0;i < parts.length; i++) {- for (let j = i + 1;j < parts.length; j++) {- if (boxGap(parts[i].box, parts[j].box) <= CONNECTIVITY_TOLERANCE) {- adjacency[i].push(j);- adjacency[j].push(i);- }- }- }- const component = new Int32Array(parts.length).fill(-1);- const components = [];- for (let seed = 0;seed < parts.length; seed++) {- if (component[seed] !== -1)- continue;- const id = components.length;- const members = [];- const stack = [seed];- component[seed] = id;- while (stack.length > 0) {- const current = stack.pop();- members.push(current);- for (const next of adjacency[current]) {- if (component[next] === -1) {- component[next] = id;- stack.push(next);- }- }- }- members.sort((x, y) => x - y);- components.push(members);- }- if (components.length < 2)- return report;- let mainIndex = 0;- for (let i = 1;i < components.length; i++) {- const bigger = components[i].length > components[mainIndex].length;- const tie = components[i].length === components[mainIndex].length && components[i][0] < components[mainIndex][0];- if (bigger || tie)- mainIndex = i;- }- const main = components[mainIndex];- report.mainComponentSize = main.length;- for (const [index, members] of components.entries()) {- if (index === mainIndex)- continue;- let gap = Number.POSITIVE_INFINITY;- for (const m of members) {- for (const b of main) {- gap = Math.min(gap, boxGap(parts[m].box, parts[b].box));- }- }- report.groups.push({- parts: members.map((m) => parts[m].name),- gap: Math.round(gap * 1e6) / 1e6- });- }- report.groups.sort((a, b) => b.parts.length - a.parts.length || a.gap - b.gap);- return report;-}-var CONNECTIVITY_TOLERANCE = 0.02, EXEMPT_NAME, PART_CONNECTIVITY_QA_RULE;-var init_part_connectivity = __esm(() => {- init_registry();- EXEMPT_NAME = /(?:^|_)(?:leaf|leaves|foliage|frond|card|decal|billboard|petal)/i;- PART_CONNECTIVITY_QA_RULE = Object.freeze({- id: "GEO_PART_CONNECTIVITY",- profile: "geometry.partConnectivity",- scope: { kind: "universal" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate(context) {- if (!(context.scene instanceof THREE11.Object3D))- return [];- const report = analyzePartConnectivity(context.scene);- if (report.groups.length === 0)- return [];- return report.groups.map((group) => {- const listed = group.parts.map((p) => JSON.stringify(p)).join(", ");- const subject = group.parts.length === 1 ? `Part ${listed} is` : `A group of ${group.parts.length} parts (${listed}) is`;- return {- code: "GEO_PART_CONNECTIVITY",- disposition: "observe",- dimension: "visualQuality",- profile: "geometry.partConnectivity",- message: `${subject} not attached to the main body — the nearest gap is ${group.gap.toFixed(3)} m. ${group.parts.length === 1 ? "It floats on its own." : "These parts touch each other but nothing else, so one join is missing rather than several parts being misplaced."}`,- affected: { node: group.parts[0] },- measurement: {- name: "gapToMainComponent",- actual: group.gap,- expected: CONNECTIVITY_TOLERANCE- },- repairText: `Attach it with snapTo(${JSON.stringify(group.parts[0])}Part, hostPart), or reposition the group so it contacts the body. If it is meant to stand apart, say so in the part name (foliage, card, decal) so this check skips it.`- };- });- }- });-});--// src/qa/reference-comparison.ts-function isEvidence(value) {- if (typeof value !== "object" || value === null)- return false;- const candidate = value;- return candidate.schemaVersion === 1 && typeof candidate.silhouetteIoU === "number" && typeof candidate.colorAgreement === "number" && typeof candidate.reference === "object" && typeof candidate.rendered === "object";-}-function referenceComparisonFindings(evidence2, profile) {- if (evidence2.reference.coverage <= 0 || evidence2.rendered.coverage <= 0)- return [];- const findings = [];- if (evidence2.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {- findings.push({- code: "REF_SILHOUETTE_AGREEMENT",- disposition: "observe",- dimension: "promptAlignment",- profile,- message: `The asset's outline agrees with the reference image on ${(evidence2.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,- measurement: {- name: "silhouetteIoU",- actual: evidence2.silhouetteIoU,- threshold: SILHOUETTE_IOU_OBSERVE- },- repairText: "Compare the reference against the rendered views and adjust the overall proportions — the outline is the part that disagrees, not the detail."- });- }- if (evidence2.colorAgreement < COLOR_AGREEMENT_OBSERVE) {- findings.push({- code: "REF_COLOR_AGREEMENT",- disposition: "observe",- dimension: "promptAlignment",- profile,- message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence2.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,- measurement: {- name: "colorAgreement",- actual: evidence2.colorAgreement,- threshold: COLOR_AGREEMENT_OBSERVE- },- repairText: "Set the base colours from the reference image rather than from the prompt wording, then re-render."- });- }- return findings;-}-var SILHOUETTE_IOU_OBSERVE = 0.55, COLOR_AGREEMENT_OBSERVE = 0.5, REFERENCE_COMPARISON_QA_RULE;-var init_reference_comparison = __esm(() => {- init_registry();- REFERENCE_COMPARISON_QA_RULE = Object.freeze({- id: "REF_COMPARISON",- profile: "reference.comparison",- scope: { kind: "universal" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate(context) {- const evidence2 = context.derivedEvidence?.["referenceComparison"];- if (!isEvidence(evidence2))- return [];- return referenceComparisonFindings(evidence2, "reference.comparison");- }- });-});--// src/qa/self-intersection.ts-import * as THREE12 from "three";-function triangleCount(geometry) {- const index = geometry.getIndex();- const position = geometry.getAttribute("position");- if (!position)- return 0;- return Math.floor((index ? index.count : position.count) / 3);-}-function collectParts3(root, skipped) {- const parts = [];- root.updateWorldMatrix(true, true);- root.traverse((node) => {- const mesh = node;- if (!mesh.isMesh || !mesh.geometry)- return;- const name = mesh.name || "(unnamed mesh)";- const triangles = triangleCount(mesh.geometry);- if (triangles === 0)- return;- if (triangles > MAX_PART_TRIANGLES) {- skipped.push({- part: name,- reason: `${triangles} triangles exceeds the ${MAX_PART_TRIANGLES}-triangle analysis budget`- });- return;- }- const box = new THREE12.Box3().setFromObject(mesh);- if (box.isEmpty())- return;- parts.push({ name, mesh, box, triangles });- });- return parts;-}-function meshToArrays(mesh) {- const geometry = mesh.geometry;- const position = geometry.getAttribute("position");- if (!position)- return null;- const matrix = mesh.matrixWorld;- const v = new THREE12.Vector3;- const verts = new Float32Array(position.count * 3);- for (let i = 0;i < position.count; i++) {- v.set(position.getX(i), position.getY(i), position.getZ(i)).applyMatrix4(matrix);- verts[i * 3] = v.x;- verts[i * 3 + 1] = v.y;- verts[i * 3 + 2] = v.z;- }- const index = geometry.getIndex();- let tris;- if (index) {- if (index.count % 3 !== 0)- return null;- tris = new Uint32Array(index.count);- for (let i = 0;i < index.count; i++)- tris[i] = index.getX(i);- } else {- if (position.count % 3 !== 0)- return null;- tris = new Uint32Array(position.count);- for (let i = 0;i < position.count; i++)- tris[i] = i;- }- return { vertProperties: verts, triVerts: tris };-}-async function analyzePartPenetration(root) {- const skipped = [];- const parts = collectParts3(root, skipped);- const base = {- schemaVersion: 1,- source: "engine-scene-analysis",- partsAnalyzed: parts.length,- candidatePairs: 0,- pairsTested: 0,- truncated: false,- skipped,- penetrations: []- };- if (parts.length < 2)- return base;- const candidates = [];- for (let i = 0;i < parts.length; i++) {- for (let j = i + 1;j < parts.length; j++) {- if (parts[i].box.intersectsBox(parts[j].box))- candidates.push([parts[i], parts[j]]);- }- }- base.candidatePairs = candidates.length;- if (candidates.length === 0)- return base;- const tested = candidates.slice(0, MAX_NARROW_PHASE_PAIRS);- base.truncated = candidates.length > tested.length;- const Module = await import("manifold-3d");- const wasm = await Module.default();- wasm.setup();- const { Manifold, Mesh: Mesh6 } = wasm;- const cache = new Map;- const build = (part) => {- if (cache.has(part.mesh))- return cache.get(part.mesh);- let solid = null;- try {- const arrays = meshToArrays(part.mesh);- if (arrays) {- const mesh = new Mesh6({ numProp: 3, ...arrays });- mesh.merge();- solid = new Manifold(mesh);- } else {- skipped.push({ part: part.name, reason: "its triangle list is malformed" });- }- } catch (err) {- skipped.push({- part: part.name,- reason: `it is not a closed solid, so it encloses no volume (${err instanceof Error ? err.message : String(err)})`- });- solid = null;- }- cache.set(part.mesh, solid);- return solid;- };- const penetrations = [];- try {- for (const [a, b] of tested) {- const sa = build(a);- const sb = build(b);- if (!sa || !sb)- continue;- base.pairsTested++;- let overlap = null;- try {- overlap = Manifold.intersection(sa, sb);- const volume = overlap.volume();- if (volume > 0) {- const smaller = Math.min(Math.abs(sa.volume()), Math.abs(sb.volume()));- const fraction = smaller > 0 ? volume / smaller : 0;- if (fraction > CONTACT_VOLUME_FRACTION) {- penetrations.push({- a: a.name,- b: b.name,- volume: round(volume),- fraction: round(fraction)- });- }- }- } finally {- overlap?.delete();- }- }- } finally {- for (const solid of cache.values())- solid?.delete();- }- penetrations.sort((x, y) => y.fraction - x.fraction || `${x.a}:${x.b}`.localeCompare(`${y.a}:${y.b}`));- base.penetrations = penetrations;- return base;-}-function readEvidence(context) {- const evidence2 = context.derivedEvidence?.["partPenetration"];- return evidence2?.schemaVersion === 1 ? evidence2 : undefined;-}-var MAX_PART_TRIANGLES = 20000, MAX_NARROW_PHASE_PAIRS = 64, CONTACT_VOLUME_FRACTION = 0.001, round = (n) => Math.round(n * 1e9) / 1e9, SELF_INTERSECTION_QA_RULE;-var init_self_intersection = __esm(() => {- init_registry();- SELF_INTERSECTION_QA_RULE = Object.freeze({- id: "GEO_PART_SELF_INTERSECTION",- profile: "geometry.selfIntersection",- scope: { kind: "universal" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate(context) {- const evidence2 = readEvidence(context);- if (!evidence2)- return [];- const findings = evidence2.penetrations.map((pair) => ({- code: "GEO_PART_SELF_INTERSECTION",- disposition: "observe",- dimension: "visualQuality",- profile: "geometry.selfIntersection",- message: `Parts ${JSON.stringify(pair.a)} and ${JSON.stringify(pair.b)} occupy the same space: they share ${pair.volume.toPrecision(3)} m³, which is ${(pair.fraction * 100).toFixed(1)}% of the smaller part.`,- affected: { node: pair.a },- measurement: {- name: "intersectionVolumeFraction",- actual: pair.fraction,- expected: CONTACT_VOLUME_FRACTION- },- repairText: "Move one part clear of the other, or subtract it with boolDiff so the overlap becomes a real cut instead of two solids in the same place."- }));- if (evidence2.truncated) {- findings.push({- code: "GEO_PART_SELF_INTERSECTION_TRUNCATED",- disposition: "observe",- dimension: "visualQuality",- profile: "geometry.selfIntersection",- message: `Only ${evidence2.pairsTested} of ${evidence2.candidatePairs} overlapping part pairs were checked (analysis budget). Parts beyond that were not examined.`- });- }- return findings;- }- });-});--// src/qa/environment.ts-import * as THREE13 from "three";-function finding4(context, value) {- return { ...value, profile: context.intent.qaProfile || PROFILE4 };-}-function rolesOf3(node) {- return readSemanticMetadataV1(node)?.roles ?? [];-}-function nodePath3(root, node) {- const names = [];- let cursor = node;- while (cursor) {- names.push(cursor.name || cursor.type);- if (cursor === root)- break;- cursor = cursor.parent;- }- return names.reverse().join("/");-}-function transformedBox2(source, transform) {- const result = new THREE13.Box3;- for (const x of [source.min.x, source.max.x]) {- for (const y of [source.min.y, source.max.y]) {- for (const z3 of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE13.Vector3(x, y, z3).applyMatrix4(transform));- }- }- }- return result;-}-function orientedBoxFromLocalBounds(root, node, source) {- const relative2 = root.matrixWorld.clone().invert().multiply(node.matrixWorld);- if (!relative2.elements.every(Number.isFinite))- return;- const position = new THREE13.Vector3;- const rotation = new THREE13.Quaternion;- const scale2 = new THREE13.Vector3;- relative2.decompose(position, rotation, scale2);- const recomposed = new THREE13.Matrix4().compose(position, rotation, scale2);- const residual = Math.max(...relative2.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));- if (residual > 0.00001)- return;- const center = source.getCenter(new THREE13.Vector3).applyMatrix4(relative2);- const sourceHalf = source.getSize(new THREE13.Vector3).multiplyScalar(0.5);- const halfExtents = [- Math.abs(sourceHalf.x * scale2.x),- Math.abs(sourceHalf.y * scale2.y),- Math.abs(sourceHalf.z * scale2.z)- ];- if (halfExtents.some((extent2) => !Number.isFinite(extent2) || extent2 <= 0.000000001))- return;- rotation.normalize();- return createOrientedProbeBox3({- id: `${node.name || node.type}:${node.uuid}`,- frame: probeLocalFrameFromQuaternion(`${node.name || node.type}:asset-local`, [stable5(center.x), stable5(center.y), stable5(center.z)], [rotation.x, rotation.y, rotation.z, rotation.w]),- halfExtents- });-}-function collectParts4(root) {- root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();- const result = [];- root.traverse((node) => {- const roles2 = rolesOf3(node);- const renderable = node instanceof THREE13.Mesh;- let box;- let orientedBox;- let source;- if (renderable && node.geometry instanceof THREE13.BufferGeometry) {- node.geometry.computeBoundingBox();- if (node.geometry.boundingBox) {- source = node.geometry.boundingBox;- }- } else if (roles2.length > 0) {- source = new THREE13.Box3(new THREE13.Vector3(-0.5, -0.5, -0.5), new THREE13.Vector3(0.5, 0.5, 0.5));- }- if (source) {- box = transformedBox2(source, rootInverse2.clone().multiply(node.matrixWorld));- orientedBox = orientedBoxFromLocalBounds(root, node, source);- }- if (box?.isEmpty())- box = undefined;- result.push({- node,- roles: roles2,- ...box ? { box } : {},- ...orientedBox ? { orientedBox } : {},- renderable- });- });- return result;-}-function quaternionTuple(value) {- return [stable5(value.x), stable5(value.y), stable5(value.z), stable5(value.w)];-}-function resolveSocket(root, node, socket) {- const metadata = readSemanticMetadataV1(node);- const frame = metadata?.frames.find((candidate) => candidate.id === socket.frame);- if (!frame)- return;- root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();- const point = new THREE13.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse2);- const rootInverseQuaternion = root.getWorldQuaternion(new THREE13.Quaternion).invert();- const rotation = node.getWorldQuaternion(new THREE13.Quaternion).multiply(new THREE13.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();- return {- id: socket.id,- type: socket.type,- node: node.name || node.type,- translation: [stable5(point.x), stable5(point.y), stable5(point.z)],- rotation: quaternionTuple(rotation),- compatibleTypes: [...socket.compatibleTypes],- ...socket.allowedRotationsDegrees ? { allowedRotationsDegrees: [...socket.allowedRotationsDegrees] } : {}- };-}-function resolveEnvironmentSockets(root) {- const result = [];- root.traverse((node) => {- const metadata = readSemanticMetadataV1(node);- for (const socket of metadata?.sockets ?? []) {- if (!socket.type.startsWith("environment."))- continue;- const resolved2 = resolveSocket(root, node, socket);- if (resolved2)- result.push(resolved2);- }- });- return result.sort((a, b) => `${a.type}:${a.id}`.localeCompare(`${b.type}:${b.id}`));-}-function socketByType(sockets, type) {- return sockets.find((socket) => socket.type === type);-}-function evaluateEnvironmentSocketQa(context) {- if (context.intent.category !== "environment" || !(context.scene instanceof THREE13.Object3D)) {- return [];- }- const root = context.scene;- const sockets = resolveEnvironmentSockets(root);- const findings = [];- for (const pair of SOCKET_PAIR_CONTRACTS) {- const declared = [...pair.negative, ...pair.positive].some((type) => sockets.some((socket) => socket.type === type));- if (!declared)- continue;- for (const side of [pair.negative, pair.positive]) {- if (side.some((type) => sockets.some((socket) => socket.type === type)))- continue;- findings.push(finding4(context, {- code: "ENV_SOCKET_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: `Declared ${pair.label} is incomplete; its opposite socket is missing.`,- affected: { node: root.name || "environment-root" },- measurement: { name: "declaredPairSocketCount", actual: 0, expected: 1, threshold: 1 },- viewHints: ["top", "generic.top.semantic-overlay"],- repairText: `Complete the declared ${pair.label} with ${side.join(" or ")} without inventing unrelated axes or joins.`- }));- }- }- for (const axis of ["x", "z"]) {- const negative = socketByType(sockets, `environment.tile.${axis}-negative`);- const positive2 = socketByType(sockets, `environment.tile.${axis}-positive`);- if (!negative || !positive2)- continue;- const cross3 = axis === "x" ? 2 : 0;- const crossDelta = Math.hypot(negative.translation[1] - positive2.translation[1], negative.translation[cross3] - positive2.translation[cross3]);- if (crossDelta <= SOCKET_ALIGNMENT_TOLERANCE_METERS)- continue;- findings.push(finding4(context, {- code: "ENV_SOCKET_PAIR_MISALIGNED",- disposition: "block",- dimension: "categoryReadiness",- message: `Opposing ${axis.toUpperCase()} tile sockets differ by ${crossDelta.toFixed(6)} m in their paired height/cross-axis frame.`,- affected: { node: positive2.node, attribute: positive2.id },- measurement: {- name: "socketCrossAxisDelta",- actual: stable5(crossDelta),- expected: 0,- threshold: SOCKET_ALIGNMENT_TOLERANCE_METERS,- unit: "m"- },- viewHints: ["top", "generic.top.semantic-overlay"],- repairText: `Align the ${axis}-negative/${axis}-positive socket frames in height and cross-axis offset.`- }));- }- return findings;-}-function materialSignature(material) {- const values = Array.isArray(material) ? material : [material];- return values.map((value) => {- const standard = value;- const color = standard.color?.getHexString?.() ?? "none";- return `${value.type}:${value.name}:${color}`;- }).sort().join("|");-}-function boundarySamples(root, axis, side, bins = 12) {- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- const bounds = new THREE13.Box3().setFromObject(root);- const localBounds = transformedBox2(bounds, root.matrixWorld.clone().invert());- const edge = side === "negative" ? localBounds.min[axis] : localBounds.max[axis];- const axisExtent = localBounds.max[axis] - localBounds.min[axis];- const band = Math.max(0.002, axisExtent * 0.005);- const crossAxis = axis === "x" ? "z" : "x";- const crossMin = localBounds.min[crossAxis];- const crossExtent = Math.max(0.000000001, localBounds.max[crossAxis] - crossMin);- const byBin = new Map;- root.traverse((node) => {- if (!(node instanceof THREE13.Mesh) || !(node.geometry instanceof THREE13.BufferGeometry))- return;- const positions = node.geometry.getAttribute("position");- if (positions?.itemSize !== 3)- return;- const normals = node.geometry.getAttribute("normal");- const transform = inverse.clone().multiply(node.matrixWorld);- const normalMatrix = new THREE13.Matrix3().getNormalMatrix(transform);- const material = materialSignature(node.material);- for (let index = 0;index < positions.count; index++) {- const point = new THREE13.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);- if (Math.abs(point[axis] - edge) > band)- continue;- const t = THREE13.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);- const bin = Math.min(bins - 1, Math.floor(t * bins));- const normal = normals ? new THREE13.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE13.Vector3(0, 1, 0);- const current = byBin.get(bin);- if (!current || point.y > current.height || point.y === current.height && normal.y > current.normal.y) {- byBin.set(bin, { bin, height: point.y, normal, material });- }- }- });- return Array.from(byBin.values()).sort((a, b) => a.bin - b.bin);-}-function edgePairMeasurements(root, axis, sockets) {- const negative = boundarySamples(root, axis, "negative");- const positive2 = boundarySamples(root, axis, "positive");- const negativeByBin = new Map(negative.map((sample) => [sample.bin, sample]));- const pairs = positive2.flatMap((sample) => {- const other = negativeByBin.get(sample.bin);- return other ? [[other, sample]] : [];- });- const unionBins = new Set([- ...negative.map((sample) => sample.bin),- ...positive2.map((sample) => sample.bin)- ]);- const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;- const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE13.MathUtils.radToDeg(Math.acos(THREE13.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;- const materialMismatch = pairs.some(([a, b]) => a.material !== b.material);- const negativeSocket = socketByType(sockets, `environment.tile.${axis}-negative`);- const positiveSocket = socketByType(sockets, `environment.tile.${axis}-positive`);- const crossIndex = axis === "x" ? 2 : 0;- const socketCrossAxisDelta = negativeSocket && positiveSocket ? Math.hypot(negativeSocket.translation[1] - positiveSocket.translation[1], negativeSocket.translation[crossIndex] - positiveSocket.translation[crossIndex]) : null;- return {- axis,- source: negativeSocket && positiveSocket ? "semantic" : "fallback",- sampleCoverage: unionBins.size === 0 ? 0 : pairs.length / unionBins.size,- maximumHeightDelta: stable5(maximumHeightDelta),- maximumNormalDeltaDegrees: stable5(maximumNormalDeltaDegrees),- materialMismatch,- socketCrossAxisDelta: socketCrossAxisDelta === null ? null : stable5(socketCrossAxisDelta)- };-}-function evaluateEnvironmentTileEdgeQa(context) {- if (context.intent.category !== "environment" || !context.intent.capabilities.includes("tileable") || !(context.scene instanceof THREE13.Object3D)) {- return [];- }- const root = context.scene;- const sockets = resolveEnvironmentSockets(root);- const findings = [];- for (const axis of ["x", "z"]) {- const measured = edgePairMeasurements(root, axis, sockets);- const disposition = measured.source === "semantic" ? "block" : "warn";- if (measured.sampleCoverage < 0.5) {- findings.push(finding4(context, {- code: "ENV_TILE_EDGE_EVIDENCE_SPARSE",- disposition,- dimension: "categoryReadiness",- message: `${axis.toUpperCase()} tile edges share only ${(measured.sampleCoverage * 100).toFixed(1)}% sampled boundary coverage.`,- affected: { node: root.name || "environment-root", attribute: `${axis}-edge` },- measurement: {- name: "pairedBoundarySampleCoverage",- actual: measured.sampleCoverage,- expected: ">=0.5",- threshold: 0.5,- unit: "ratio"- },- viewHints: ["top", "right"],- repairText: `Author matching ${axis}-negative/${axis}-positive boundary vertices and semantic tile sockets.`- }));- continue;- }- if (measured.maximumHeightDelta > EDGE_HEIGHT_TOLERANCE_METERS) {- findings.push(finding4(context, {- code: "ENV_TILE_EDGE_HEIGHT_SEAM",- disposition,- dimension: "categoryReadiness",- message: `${axis.toUpperCase()} tile boundaries differ by ${measured.maximumHeightDelta.toFixed(6)} m.`,- affected: { node: root.name || "environment-root", attribute: `${axis}-edge-height` },- measurement: {- name: "maximumBoundaryHeightDelta",- actual: measured.maximumHeightDelta,- expected: 0,- threshold: EDGE_HEIGHT_TOLERANCE_METERS,- unit: "m"- },- viewHints: ["top", "right"],- repairText: `Match the sampled ${axis}-negative/${axis}-positive boundary heights without flattening the tile interior.`- }));- }- if (measured.maximumNormalDeltaDegrees > EDGE_NORMAL_TOLERANCE_DEGREES) {- findings.push(finding4(context, {- code: "ENV_TILE_EDGE_NORMAL_SEAM",- disposition,- dimension: "categoryReadiness",- message: `${axis.toUpperCase()} tile boundary normals differ by ${measured.maximumNormalDeltaDegrees.toFixed(3)} degrees.`,- affected: { node: root.name || "environment-root", attribute: `${axis}-edge-normal` },- measurement: {- name: "maximumBoundaryNormalDelta",- actual: measured.maximumNormalDeltaDegrees,- expected: 0,- threshold: EDGE_NORMAL_TOLERANCE_DEGREES,- unit: "deg"- },- viewHints: ["top", "three-quarter"],- repairText: `Align the ${axis}-edge vertex normals while preserving intentional interior shading.`- }));- }- if (measured.materialMismatch) {- findings.push(finding4(context, {- code: "ENV_TILE_EDGE_MATERIAL_SEAM",- disposition,- dimension: "visualQuality",- message: `${axis.toUpperCase()} tile boundaries use different material signatures.`,- affected: { node: root.name || "environment-root", attribute: `${axis}-edge-material` },- measurement: { name: "boundaryMaterialMismatch", actual: true, expected: false },- viewHints: ["top", "three-quarter"],- repairText: `Use the same portable PBR material role on both ${axis} boundary samples.`- }));- }- }- return findings;-}-function isCorridor(part) {- return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));-}-function evaluateEnvironmentNavigabilityQa(context) {- if (context.intent.category !== "environment" || !context.intent.capabilities.includes("navigable") || !(context.scene instanceof THREE13.Object3D)) {- return [];- }- const root = context.scene;- const parts = collectParts4(root);- const corridors = parts.filter((part) => isCorridor(part));- if (corridors.length === 0) {- return [- finding4(context, {- code: "ENV_NAV_CLEARANCE_UNASSESSED",- disposition: "warn",- dimension: "categoryReadiness",- message: "navigable=true has no measurable semantic corridor prism; geometry inference cannot hard-gate traversal.",- affected: { node: root.name || "environment-root" },- measurement: { name: "semanticCorridorCount", actual: 0, expected: ">=1", threshold: 1 },- viewHints: ["top", "right"],- repairText: "Add a scaled non-rendered environment.navigation.corridor.<id> marker through the intended route."- })- ];- }- const findings = [];- for (const corridor of corridors) {- if (!corridor.orientedBox) {- findings.push(finding4(context, {- code: "ENV_NAV_CLEARANCE_UNASSESSED",- disposition: "warn",- dimension: "categoryReadiness",- message: `Traversal corridor ${corridor.node.name || "(unnamed)"} has a sheared or degenerate transform that cannot be measured safely.`,- affected: {- node: corridor.node.name || "navigation-corridor",- nodePath: nodePath3(root, corridor.node)- },- measurement: { name: "orientedCorridorEvidence", actual: false, expected: true },- viewHints: ["top", "right"],- repairText: "Author the corridor marker with a finite non-sheared local transform."- }));- continue;- }- const width = Math.min(corridor.orientedBox.halfExtents[0] * 2, corridor.orientedBox.halfExtents[2] * 2);- const height = corridor.orientedBox.halfExtents[1] * 2;- if (width + 0.000001 < 0.8) {- findings.push(finding4(context, {- code: "ENV_NAV_CORRIDOR_TOO_NARROW",- disposition: "warn",- dimension: "categoryReadiness",- message: `Traversal corridor ${corridor.node.name || "(unnamed)"} is only ${width.toFixed(4)} m wide.`,- affected: {- node: corridor.node.name || "navigation-corridor",- nodePath: nodePath3(root, corridor.node)- },- measurement: {- name: "minimumCorridorWidth",- actual: stable5(width),- expected: ">=0.8",- threshold: 0.8,- unit: "m"- },- viewHints: ["top", "right"],- repairText: "Widen only the declared corridor to at least 0.8 m while preserving surrounding structure."- }));- }- if (height + 0.000001 < 1.8) {- findings.push(finding4(context, {- code: "ENV_NAV_HEADROOM_TOO_LOW",- disposition: "warn",- dimension: "categoryReadiness",- message: `Traversal corridor ${corridor.node.name || "(unnamed)"} has only ${height.toFixed(4)} m headroom.`,- affected: {- node: corridor.node.name || "navigation-corridor",- nodePath: nodePath3(root, corridor.node)- },- measurement: {- name: "minimumCorridorHeadroom",- actual: stable5(height),- expected: ">=1.8",- threshold: 1.8,- unit: "m"- },- viewHints: ["right", "three-quarter"],- repairText: "Raise or clear only the corridor ceiling to provide at least 1.8 m headroom."- }));- }- const blocker = parts.find((part) => part.renderable && part.orientedBox && part.node !== corridor.node && !part.roles.some((role) => role.startsWith("environment.ground") || role.startsWith("environment.surface") || role.startsWith("environment.path.surface") || role.startsWith("environment.bridge.deck")) && !probeOrientedPenetration(part.orientedBox, corridor.orientedBox, {- maxDepth: 0,- tolerance: 0.004- }).pass);- if (blocker) {- findings.push(finding4(context, {- code: "ENV_NAV_CORRIDOR_BLOCKED",- disposition: "block",- dimension: "categoryReadiness",- message: `Traversal corridor ${corridor.node.name || "(unnamed)"} is blocked by ${blocker.node.name || "an unnamed mesh"}.`,- affected: {- node: blocker.node.name || "navigation-blocker",- nodePath: nodePath3(root, blocker.node)- },- measurement: { name: "corridorBlockerCount", actual: 1, expected: 0, threshold: 0 },- viewHints: ["top", "right"],- repairText: "Remove or split only the reported blocker from the declared navigation corridor."- }));- }- }- return findings;-}-function horizontalOverlap(a, b) {- return a.min.x < b.max.x && a.max.x > b.min.x && a.min.z < b.max.z && a.max.z > b.min.z;-}-function intentionalGround(part) {- return part.roles.some((role) => role.startsWith("environment.ground") || role.startsWith("environment.terrain.volume") || role.startsWith("environment.cliff.volume"));-}-function functionalLayer(part) {- return part.roles.some((role) => role.startsWith("environment.functional") || role.startsWith("environment.layer") || role.startsWith("environment.path") || role.startsWith("environment.road") || role.startsWith("environment.bridge") || role.startsWith("environment.gate"));-}-function evaluateEnvironmentGroundQa(context) {- if (context.intent.category !== "environment" || !(context.scene instanceof THREE13.Object3D)) {- return [];- }- const root = context.scene;- const parts = collectParts4(root).filter((part) => part.renderable && part.box);- const findings = [];- for (const part of parts) {- const box = part.box;- if (intentionalGround(part))- continue;- if (functionalLayer(part) && box.min.y < -GROUND_TOLERANCE_METERS2) {- findings.push(finding4(context, {- code: "ENV_FUNCTIONAL_PART_BURIED",- disposition: "warn",- dimension: "categoryReadiness",- message: `${part.node.name || "Functional environment part"} is buried ${Math.abs(box.min.y).toFixed(6)} m below asset-local ground.`,- affected: {- node: part.node.name || "environment-part",- nodePath: nodePath3(root, part.node)- },- measurement: {- name: "minimumY",- actual: stable5(box.min.y),- expected: ">=-0.02",- threshold: GROUND_TOLERANCE_METERS2,- unit: "m"- },- viewHints: ["right", "three-quarter"]- }));- }- if (functionalLayer(part) && box.min.y > GROUND_TOLERANCE_METERS2) {- const supported = parts.some((support) => support !== part && support.box && horizontalOverlap(box, support.box) && Math.abs(support.box.max.y - box.min.y) <= 0.04);- if (!supported) {- findings.push(finding4(context, {- code: "ENV_LAYER_UNSUPPORTED",- disposition: "warn",- dimension: "categoryReadiness",- message: `${part.node.name || "Environment layer"} floats without a contacting support.`,- affected: {- node: part.node.name || "environment-layer",- nodePath: nodePath3(root, part.node)- },- measurement: { name: "supportContactCount", actual: 0, expected: ">=1", threshold: 1 },- viewHints: ["right", "three-quarter"]- }));- }- }- const size = box.getSize(new THREE13.Vector3);- if (box.min.y < -0.05 && size.y <= Math.max(0.05, Math.min(size.x, size.z) * 0.03) && Math.max(size.x, size.z) >= 1) {- findings.push(finding4(context, {- code: "ENV_GROUND_UNDECLARED_SKIRT",- disposition: "warn",- dimension: "promptAlignment",- message: `${part.node.name || "Environment layer"} resembles an undeclared below-ground skirt rather than intentional terrain volume.`,- affected: {- node: part.node.name || "environment-skirt",- nodePath: nodePath3(root, part.node)- },- measurement: {- name: "skirtThickness",- actual: stable5(size.y),- expected: "declared terrain volume or supported layer",- unit: "m"- },- viewHints: ["right", "three-quarter"]- }));- }- }- return findings;-}-var PROFILE4 = "environment.semantic", EDGE_HEIGHT_TOLERANCE_METERS = 0.02, EDGE_NORMAL_TOLERANCE_DEGREES = 8, SOCKET_ALIGNMENT_TOLERANCE_METERS = 0.02, GROUND_TOLERANCE_METERS2 = 0.02, stable5 = (value) => Math.round(value * 1e6) / 1e6, SOCKET_PAIR_CONTRACTS, ENVIRONMENT_EXACT_QA_RULE, ENVIRONMENT_ADVISORY_QA_RULE, ENVIRONMENT_QA_RULES;-var init_environment2 = __esm(() => {- init_contracts();- init_registry();- init_environment();- SOCKET_PAIR_CONTRACTS = [- {- label: "X tile axis",- negative: ["environment.tile.x-negative"],- positive: ["environment.tile.x-positive"]- },- {- label: "Z tile axis",- negative: ["environment.tile.z-negative"],- positive: ["environment.tile.z-positive"]- },- {- label: "road join",- negative: ["environment.road.start"],- positive: ["environment.road.end"]- },- {- label: "bridge join",- negative: ["environment.bridge.start"],- positive: ["environment.bridge.end"]- },- {- label: "wall/gate join",- negative: ["environment.wall.left", "environment.gate.left"],- positive: ["environment.wall.right", "environment.gate.right"]- }- ];- ENVIRONMENT_EXACT_QA_RULE = Object.freeze({- id: "ENVIRONMENT_EXACT_PROFILE",- profile: PROFILE4,- scope: { kind: "category", category: "environment" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("environment-semantic-v1", "src/qa/environment.test.ts", "13b0c50894074bf93a5dd9eb1c93e519b030312e030e5123493a4833a1438b28"),- defaultMode: "enforce",- evaluate: (context) => [- ...evaluateEnvironmentSocketQa(context),- ...evaluateEnvironmentTileEdgeQa(context).filter((value) => value.disposition === "block"),- ...evaluateEnvironmentNavigabilityQa(context).filter((value) => value.disposition === "block")- ]- });- ENVIRONMENT_ADVISORY_QA_RULE = Object.freeze({- id: "ENVIRONMENT_ADVISORY_PROFILE",- profile: "environment.advisory",- scope: { kind: "category", category: "environment" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: (context) => [- ...evaluateEnvironmentTileEdgeQa(context).filter((value) => value.disposition !== "block"),- ...evaluateEnvironmentNavigabilityQa(context).filter((value) => value.disposition !== "block"),- ...evaluateEnvironmentGroundQa(context)- ]- });- ENVIRONMENT_QA_RULES = [- ENVIRONMENT_EXACT_QA_RULE,- ENVIRONMENT_ADVISORY_QA_RULE- ];-});--// src/qa/breadth.ts-function validModularJoinObservation(value) {- if (!record2(value))- return false;- return typeof value.aSocketId === "string" && value.aSocketId.length > 0 && typeof value.bSocketId === "string" && value.bSocketId.length > 0 && finiteTuple2(value.aWorldPosition, 3) && finiteTuple2(value.bWorldPosition, 3) && finiteTuple2(value.aWorldNormal, 3) && finiteTuple2(value.bWorldNormal, 3) && typeof value.relativeRotationDegrees === "number" && Number.isFinite(value.relativeRotationDegrees) && (value.toleranceMeters === undefined || typeof value.toleranceMeters === "number" && Number.isFinite(value.toleranceMeters) && value.toleranceMeters >= 0) && (value.normalToleranceDegrees === undefined || typeof value.normalToleranceDegrees === "number" && Number.isFinite(value.normalToleranceDegrees) && value.normalToleranceDegrees >= 0);-}-function validVfxArtifactEvidence(value) {- if (!record2(value) || value.schemaVersion !== 1)- return false;- if (!record2(value.facing) || !record2(value.animation))- return false;- if (!Array.isArray(value.materials))- return false;- if (!Array.isArray(value.clips) || !Array.isArray(value.uniforms))- return false;- if (!value.uniforms.every((name) => typeof name === "string" && name.length > 0))- return false;- if (!value.clips.every((clip) => record2(clip) && typeof clip.name === "string" && clip.name.length > 0 && typeof clip.durationSeconds === "number" && Number.isFinite(clip.durationSeconds) && clip.durationSeconds >= 0)) {- return false;- }- return value.materials.every((material) => record2(material) && typeof material.id === "string" && material.id.length > 0 && ["card", "beam", "trail", "volume", "core"].includes(String(material.surfaceRole)) && ["opaque", "mask", "blend"].includes(String(material.alphaMode)) && (material.effectSurface === undefined || typeof material.effectSurface === "boolean") && typeof material.alphaData === "boolean" && typeof material.doubleSided === "boolean" && typeof material.screenAreaRatio === "number" && Number.isFinite(material.screenAreaRatio) && material.screenAreaRatio >= 0 && typeof material.transparentLayers === "number" && Number.isInteger(material.transparentLayers) && material.transparentLayers >= 0 && typeof material.textureMemoryBytes === "number" && Number.isInteger(material.textureMemoryBytes) && material.textureMemoryBytes >= 0);-}-function artifactEvidence(context) {- if (context.derivedEvidence?.source !== "engine-scene-analysis")- return;- const candidate = context.derivedEvidence.vfxArtifact;- return validVfxArtifactEvidence(candidate) ? candidate : undefined;-}-function finding5(context, value, profile = "vfx.w7") {- return { ...value, profile: context.intent.qaProfile || profile };-}-function measureVfxRuntimeCostV1(evidence2) {- let blendedScreenAreaRatio = 0;- let transparentLayerCount = 0;- let overdrawProxy = 0;- let textureMemoryBytes = 0;- for (const material of evidence2.materials) {- textureMemoryBytes += material.textureMemoryBytes;- if (material.alphaMode !== "blend")- continue;- blendedScreenAreaRatio += material.screenAreaRatio;- transparentLayerCount += material.transparentLayers;- overdrawProxy += material.screenAreaRatio * Math.max(1, material.transparentLayers);- }- return {- schemaVersion: 1,- blendedScreenAreaRatio: stable6(blendedScreenAreaRatio),- transparentLayerCount,- overdrawProxy: stable6(overdrawProxy),- textureMemoryBytes,- shaderSidecarRequired: evidence2.sidecar !== undefined- };-}-function exactVfxIntent(context) {- const candidate = context.intent.vfx;- const validated = validateVfxIntentV1(candidate);- if (!validated.valid || !validated.value) {- return {- findings: [- finding5(context, {- code: "VFX_INTENT_INVALID",- disposition: "block",- dimension: "categoryReadiness",- message: `Trusted VFX intent is missing or invalid: ${validated.issues.map((issue) => `${issue.path || "<root>"}:${issue.code}`).join(", ")}`,- measurement: {- name: "vfxIntentIssueCount",- actual: validated.issues.length,- expected: 0- },- repairText: "Return to request normalization; model-authored source cannot repair trusted intent."- })- ]- };- }- const evidence2 = artifactEvidence(context);- if (!evidence2) {- return {- findings: [- finding5(context, {- code: "VFX_RUNTIME_CONTRACT_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: "VFX output is missing its versioned facing/material/animation runtime evidence.",- measurement: { name: "vfxEvidencePresent", actual: false, expected: true },- repairText: "Return a renderable Three.js scene so the engine can analyze actual materials, facing behavior, clips/uniforms, and sidecar availability."- })- ]- };- }- return { intent: validated.value, evidence: evidence2 };-}-function evaluateVfxExactQa(context) {- if (context.intent.category !== "vfx")- return [];- const resolved2 = exactVfxIntent(context);- if ("findings" in resolved2)- return resolved2.findings;- const { intent, evidence: evidence2 } = resolved2;- const findings = [];- const effectMaterials = evidence2.materials.filter((material) => material.effectSurface !== false);- if (effectMaterials.length === 0) {- findings.push(finding5(context, {- code: "VFX_EFFECT_SURFACE_MISSING",- disposition: "block",- dimension: "exportIntegrity",- message: "VFX output has no explicitly analyzed effect-surface material.",- measurement: { name: "effectMaterialCount", actual: 0, expected: ">=1" },- repairText: "Stamp effect-rendering nodes with vfx.effect.surface.* and keep opaque support geometry in vfx.support.* roles."- }));- }- for (const material of effectMaterials) {- if (material.alphaMode !== intent.transparency) {- findings.push(finding5(context, {- code: "VFX_TRANSPARENCY_MODE_MISMATCH",- disposition: "block",- dimension: "exportIntegrity",- message: `${material.id} exported ${material.alphaMode} but trusted VFX intent requires ${intent.transparency}.`,- affected: { material: material.id },- measurement: {- name: "alphaMode",- actual: material.alphaMode,- expected: intent.transparency- },- repairText: `Set ${material.id} to the declared ${intent.transparency} alpha mode without changing unrelated materials.`- }));- }- if (intent.transparency !== "opaque" && !material.alphaData) {- findings.push(finding5(context, {- code: "VFX_ALPHA_DATA_MISSING",- disposition: "block",- dimension: "exportIntegrity",- message: `${material.id} declares ${intent.transparency} but has no alpha-bearing factor or texture data.`,- affected: { material: material.id },- measurement: { name: "alphaData", actual: false, expected: true },- repairText: `Add alpha-bearing data to ${material.id}; do not leave an opaque effect-card rectangle.`- }));- }- if (material.doubleSided !== intent.doubleSided) {- findings.push(finding5(context, {- code: "VFX_SIDEDNESS_MISMATCH",- disposition: "block",- dimension: "exportIntegrity",- message: `${material.id} sidedness does not match trusted VFX intent.`,- affected: { material: material.id },- measurement: {- name: "doubleSided",- actual: material.doubleSided,- expected: intent.doubleSided- },- repairText: `Set ${material.id} doubleSided=${intent.doubleSided}.`- }));- }- if (intent.transparency === "mask" && (material.alphaCutoff === undefined || !Number.isFinite(material.alphaCutoff) || material.alphaCutoff <= 0 || material.alphaCutoff > 1)) {- findings.push(finding5(context, {- code: "VFX_ALPHA_CUTOFF_INVALID",- disposition: "block",- dimension: "exportIntegrity",- message: `${material.id} uses MASK without a finite cutoff in (0, 1].`,- affected: { material: material.id },- measurement: {- name: "alphaCutoff",- actual: material.alphaCutoff ?? null,- expected: "0 < cutoff <= 1"- },- repairText: `Set a valid alpha cutoff on ${material.id}.`- }));- }- }- const facingFields = ["mode", "normalAxis", "directionAxis"];- for (const field of facingFields) {- if (intent.facing[field] === evidence2.facing[field])- continue;- if (intent.facing.source !== "explicit")- continue;- findings.push(finding5(context, {- code: "VFX_FACING_CONTRACT_MISMATCH",- disposition: "block",- dimension: "categoryReadiness",- message: `Explicit VFX facing ${field} does not match the emitted runtime contract.`,- measurement: {- name: `facing.${field}`,- actual: evidence2.facing[field] ?? null,- expected: intent.facing[field] ?? null- },- repairText: `Stamp and implement the requested ${field}; preserve the canonical Kiln frame.`- }));- }- const requestedAnimation = intent.animation;- const actualAnimation = evidence2.animation;- for (const field of ["playback", "endpointBehavior", "driver"]) {- if (requestedAnimation[field] === actualAnimation[field])- continue;- findings.push(finding5(context, {- code: "VFX_ANIMATION_POLICY_MISMATCH",- disposition: "block",- dimension: "categoryReadiness",- message: `VFX animation ${field} does not match trusted intent.`,- measurement: {- name: `animation.${field}`,- actual: actualAnimation[field],- expected: requestedAnimation[field]- },- repairText: `Implement the declared ${field} without changing the effect subtype.`- }));- }- if (Math.abs(requestedAnimation.durationSeconds - actualAnimation.durationSeconds) > 0.000001) {- findings.push(finding5(context, {- code: "VFX_ANIMATION_DURATION_MISMATCH",- disposition: "block",- dimension: "categoryReadiness",- message: "VFX animation duration does not match trusted intent.",- measurement: {- name: "animation.durationSeconds",- actual: actualAnimation.durationSeconds,- expected: requestedAnimation.durationSeconds,- threshold: 0.000001,- unit: "s"- },- repairText: "Use the declared duration and resample endpoint keys deterministically."- }));- }- if (requestedAnimation.playback === "loop" && !actualAnimation.endpointMatches) {- findings.push(finding5(context, {- code: "VFX_LOOP_ENDPOINT_MISMATCH",- disposition: "block",- dimension: "categoryReadiness",- message: "Looping VFX does not return to its start state at the declared endpoint.",- measurement: { name: "endpointMatches", actual: false, expected: true },- repairText: "Make the final loop sample equal the initial sample for every driven channel."- }));- }- if (requestedAnimation.driver === "clip" && !evidence2.clips.some((clip) => clip.name === requestedAnimation.clipName && Math.abs(clip.durationSeconds - requestedAnimation.durationSeconds) <= 0.000001)) {- findings.push(finding5(context, {- code: "VFX_REQUIRED_CLIP_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: "The declared VFX clip name/duration is absent from the artifact evidence.",- affected: { clip: requestedAnimation.clipName ?? "<missing>" },- repairText: `Emit clip ${requestedAnimation.clipName ?? "<declared clip>"} with the requested duration.`- }));- }- if (requestedAnimation.driver === "timeUniform" && !evidence2.uniforms.includes(requestedAnimation.timeUniformName ?? "")) {- findings.push(finding5(context, {- code: "VFX_REQUIRED_TIME_UNIFORM_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: "The declared runtime time uniform is absent from the sidecar evidence.",- measurement: {- name: "timeUniformName",- actual: evidence2.uniforms.join(","),- expected: requestedAnimation.timeUniformName ?? null- },- repairText: `Expose ${requestedAnimation.timeUniformName ?? "the declared uniform"} in the runtime sidecar.`- }));- }- if (intent.portability === "portable" && evidence2.sidecar !== undefined) {- findings.push(finding5(context, {- code: "VFX_UNDECLARED_SIDECAR",- disposition: "block",- dimension: "exportIntegrity",- message: "Portable VFX unexpectedly requires a runtime shader sidecar.",- repairText: "Bake the portable appearance into standard glTF materials or update trusted intent before spend."- }));- }- if (intent.portability === "sidecar" && (evidence2.sidecar?.id !== intent.sidecar?.id || evidence2.sidecar?.version !== intent.sidecar?.version)) {- findings.push(finding5(context, {- code: "VFX_SIDECAR_IDENTITY_MISMATCH",- disposition: "block",- dimension: "exportIntegrity",- message: "Runtime VFX sidecar identity/version does not match trusted intent.",- measurement: {- name: "sidecarIdentity",- actual: evidence2.sidecar ? `${evidence2.sidecar.id}@${evidence2.sidecar.version}` : null,- expected: intent.sidecar ? `${intent.sidecar.id}@${intent.sidecar.version}` : null- },- repairText: "Attach the exact declared sidecar identity and keep the GLB fallback honest."- }));- }- return findings;-}-function evaluateVfxAdvisoryQa(context) {- if (context.intent.category !== "vfx")- return [];- const intent = context.intent.vfx;- const validated = validateVfxIntentV1(intent);- const evidence2 = artifactEvidence(context);- if (!validated.valid || !validated.value || !evidence2)- return [];- const findings = [];- if (validated.value.facing.source === "inferred") {- const mismatch = ["mode", "normalAxis", "directionAxis"].some((field) => validated.value?.facing[field] !== evidence2.facing[field]);- if (mismatch) {- findings.push(finding5(context, {- code: "VFX_FACING_INFERRED_DRIFT",- disposition: "observe",- dimension: "categoryReadiness",- message: "Inferred VFX facing differs from emitted metadata; review the named views.",- viewHints: ["front", "right", "three-quarter"]- }));- }- }- const cost = measureVfxRuntimeCostV1(evidence2);- findings.push(finding5(context, {- code: "VFX_RUNTIME_COST_REPORT",- disposition: "observe",- dimension: "runtimeCost",- message: "VFX transparency/runtime cost is reported separately from instanceability.",- measurement: {- name: "vfxRuntimeCost",- actual: `blendArea=${cost.blendedScreenAreaRatio};layers=${cost.transparentLayerCount};overdraw=${cost.overdrawProxy};textureBytes=${cost.textureMemoryBytes};sidecar=${cost.shaderSidecarRequired}`- },- viewHints: ["front", "right", "three-quarter"]- }));- if (cost.overdrawProxy > 2 || cost.textureMemoryBytes > 32 * 1024 * 1024) {- findings.push(finding5(context, {- code: "VFX_RUNTIME_PRESSURE",- disposition: "observe",- dimension: "runtimeCost",- message: "VFX exceeds the observe-mode overdraw or texture-memory review threshold.",- measurement: {- name: "overdrawProxy",- actual: cost.overdrawProxy,- threshold: 2,- unit: "screen-layers"- }- }));- }- return findings;-}-function evaluateModularJoinQa(context) {- if (context.intent.scope.scope !== "modularSet" || !context.intent.scope.explicit)- return [];- const modularKit = context.derivedEvidence?.modularKit;- const modularJoin = context.derivedEvidence?.modularJoin;- const validation = validateModularKitContractV1(modularKit);- if (!validation.valid || !validation.value || !validModularJoinObservation(modularJoin)) {- return [- finding5(context, {- code: "MODULAR_CONTRACT_INVALID",- disposition: "block",- dimension: "categoryReadiness",- message: `Explicit modular-set intent requires a valid grid/units/socket contract and join observation: ${validation.issues.map((issue) => issue.code).join(", ")}`,- repairText: "Emit the requested modular socket metadata; do not infer a noun-specific primitive."- }, "modular.w7")- ];- }- const result = evaluateModularJoinV1(validation.value, modularJoin);- if (result.pass)- return [];- return result.codes.map((code) => finding5(context, {- code,- disposition: "block",- dimension: "categoryReadiness",- message: `Explicit modular join failed ${code}: seam=${result.seamMeters} m, overlap=${result.overlapMeters} m, lateral=${result.lateralOffsetMeters} m.`,- measurement: {- name: "modularJoinError",- actual: Math.max(result.seamMeters, result.overlapMeters, result.lateralOffsetMeters),- expected: 0,- threshold: result.toleranceMeters,- unit: "m"- },- repairText: "Snap the named compatible sockets on the declared meter grid using an allowed rotation."- }, "modular.w7"));-}-function evaluateAssetScopeQa(context) {- const scope = context.intent.scope;- const scopeObservation = context.derivedEvidence?.assetScope;- if (context.derivedEvidence?.source !== "engine-scene-analysis" || !record2(scopeObservation) || typeof scopeObservation.topLevelAssetRoots !== "number" || typeof scopeObservation.reusableMemberCount !== "number" || !Array.isArray(scopeObservation.sceneDressingRoles)) {- return [];- }- const result = assessAssetScopeV1(scope, scopeObservation);- if (result.status === "pass" || !result.code)- return [];- return [- finding5(context, {- code: result.code,- disposition: "observe",- dimension: "promptAlignment",- message: `Requested ${result.requested} scope produced ${result.observed} evidence: ${result.evidence.join("; ")}.`,- measurement: {- name: "explicitSingleViolation",- actual: result.explicitSingleViolation,- expected: false- },- viewHints: ["top", "three-quarter"]- }, "scope.w7")- ];-}-var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), stable6 = (value) => Math.round(value * 1e6) / 1e6, finiteTuple2 = (value, length3) => Array.isArray(value) && value.length === length3 && value.every((component) => typeof component === "number" && Number.isFinite(component)), VFX_EXACT_QA_RULE, VFX_ADVISORY_QA_RULE, MODULAR_JOIN_QA_RULE, ASSET_SCOPE_QA_RULE, W7_BREADTH_QA_RULES;-var init_breadth2 = __esm(() => {- init_breadth();- init_registry();- VFX_EXACT_QA_RULE = {- id: "VFX_EXACT_PROFILE",- profile: "vfx.w7.exact",- scope: { kind: "category", category: "vfx" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("vfx-w7-conformance-v1", "src/qa/breadth-corpus.test.ts", "58837182f467de6757194d54c8b42682d21d3d9355daecab694888cd742d2405"),- defaultMode: "enforce",- evaluate: evaluateVfxExactQa- };- VFX_ADVISORY_QA_RULE = {- id: "VFX_ADVISORY_PROFILE",- profile: "vfx.w7.advisory",- scope: { kind: "category", category: "vfx" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: evaluateVfxAdvisoryQa- };- MODULAR_JOIN_QA_RULE = {- id: "MODULAR_JOIN_PROFILE",- profile: "modular.w7.exact",- scope: { kind: "universal" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("modular-w7-conformance-v1", "src/qa/breadth-corpus.test.ts", "58837182f467de6757194d54c8b42682d21d3d9355daecab694888cd742d2405"),- defaultMode: "enforce",- evaluate: evaluateModularJoinQa- };- ASSET_SCOPE_QA_RULE = {- id: "ASSET_SCOPE_PROFILE",- profile: "scope.w7.advisory",- scope: { kind: "universal" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: evaluateAssetScopeQa- };- W7_BREADTH_QA_RULES = [- VFX_EXACT_QA_RULE,- VFX_ADVISORY_QA_RULE,- MODULAR_JOIN_QA_RULE,- ASSET_SCOPE_QA_RULE- ];-});--// src/qa/breadth-evidence.ts-import * as THREE14 from "three";-function record3(value) {- return typeof value === "object" && value !== null && !Array.isArray(value);-}-function isObject3D(value) {- return record3(value) && value.isObject3D === true && typeof value.traverse === "function";-}-function isMeshNode(value) {- return value.isMesh === true;-}-function isSpriteNode(value) {- return value.isSprite === true;-}-function isTexture(value) {- return record3(value) && value.isTexture === true;-}-function isAnimationClip(value) {- return record3(value) && typeof value.name === "string" && typeof value.duration === "number" && Number.isFinite(value.duration) && Array.isArray(value.tracks);-}-function localRenderableBox(rootInverse2, node) {- if (isSpriteNode(node)) {- const transform2 = rootInverse2.clone().multiply(node.matrixWorld);- return new THREE14.Box3(new THREE14.Vector3(-0.5, -0.5, -0.0005), new THREE14.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform2);- }- if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)- return;- node.geometry.computeBoundingBox();- const source = node.geometry.boundingBox;- if (!source || source.isEmpty())- return;- const transform = rootInverse2.clone().multiply(node.matrixWorld);- const result = new THREE14.Box3;- for (const x of [source.min.x, source.max.x]) {- for (const y of [source.min.y, source.max.y]) {- for (const z3 of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE14.Vector3(x, y, z3).applyMatrix4(transform));- }- }- }- return result;-}-function textureDimensions(texture) {- const image = texture.image;- return image && typeof image.width === "number" && Number.isFinite(image.width) && image.width > 0 && typeof image.height === "number" && Number.isFinite(image.height) && image.height > 0 ? [image.width, image.height] : undefined;-}-function textureHasAlpha2(texture) {- if (!texture)- return false;- const image = texture.image;- if (!image?.data || !image.width || !image.height)- return false;- const pixelCount = image.width * image.height;- if (pixelCount <= 0 || image.data.length < pixelCount * 4)- return false;- for (let index = 3;index < pixelCount * 4; index += 4) {- if ((image.data[index] ?? 255) < 255)- return true;- }- return false;-}-function materialTextures(material) {- const candidate = material;- const textures = new Set;- for (const key of [- "map",- "alphaMap",- "emissiveMap",- "normalMap",- "roughnessMap",- "metalnessMap",- "aoMap"- ]) {- const value = candidate[key];- if (isTexture(value))- textures.add(value);- }- return [...textures];-}-function materialTextureBytes(material) {- return materialTextures(material).reduce((sum, texture) => {- const dimensions2 = textureDimensions(texture);- return sum + (dimensions2 ? Math.ceil(dimensions2[0] * dimensions2[1] * 4 * (4 / 3)) : 0);- }, 0);-}-function alphaMode(material) {- const standard = material;- if ((standard.alphaTest ?? 0) > 0)- return "mask";- if (standard.transparent || (standard.opacity ?? 1) < 1 || standard.alphaMap)- return "blend";- return "opaque";-}-function alphaData(material) {- const standard = material;- return (standard.opacity ?? 1) < 1 || standard.alphaMap !== undefined && standard.alphaMap !== null || textureHasAlpha2(standard.alphaMap) || textureHasAlpha2(standard.map) || (standard.alphaTest ?? 0) > 0 && standard.alphaMap !== undefined && standard.alphaMap !== null;-}-function surfaceRole(nodes, intent) {- const evidence2 = nodes.flatMap((node) => [- node.name,- ...readSemanticMetadataV1(node)?.roles ?? []- ]);- if (evidence2.some((value) => /(?:^|[._ -])beam(?:$|[._ -])/i.test(value)))- return "beam";- if (evidence2.some((value) => /(?:^|[._ -])trail(?:$|[._ -])/i.test(value)))- return "trail";- if (evidence2.some((value) => /(?:^|[._ -])(?:volume|aura|portal)(?:$|[._ -])/i.test(value))) {- return "volume";- }- if (intent.subtype === "beam")- return "beam";- if (intent.subtype === "trail")- return "trail";- if (intent.subtype === "volume-like" || intent.subtype === "aura" || intent.subtype === "portal") {- return "volume";- }- return "card";-}-function isEffectSurface(nodes) {- return nodes.some((node) => isSpriteNode(node) || (readSemanticMetadataV1(node)?.roles ?? []).some((role) => EFFECT_SURFACE_ROLE.test(role)));-}-function coverageRatio(boxes, overall) {- if (boxes.length === 0 || overall.isEmpty())- return 0;- const overallSize = overall.getSize(new THREE14.Vector3);- const denominator = Math.max(0.000000001, overallSize.x * overallSize.y, overallSize.z * overallSize.y, overallSize.x * overallSize.z);- const area = boxes.reduce((sum, box) => {- const size = box.getSize(new THREE14.Vector3);- return sum + Math.max(size.x * size.y, size.z * size.y, size.x * size.z);- }, 0);- return stable7(Math.min(1, area / denominator));-}-function collectMaterialEvidence(root, intent) {- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- const byMaterial = new Map;- const overall = new THREE14.Box3;- root.traverse((node) => {- const box = localRenderableBox(inverse, node);- if (!box || !isMeshNode(node) && !isSpriteNode(node))- return;- overall.union(box);- const materials = Array.isArray(node.material) ? node.material : [node.material];- for (const material of materials) {- if (!material)- continue;- const value = byMaterial.get(material) ?? { nodes: [], boxes: [] };- value.nodes.push(node);- value.boxes.push(box);- byMaterial.set(material, value);- }- });- return [...byMaterial.entries()].map(([material, value], index) => {- const mode = alphaMode(material);- const standard = material;- return {- id: material.name || `material.${index}`,- surfaceRole: surfaceRole(value.nodes, intent),- effectSurface: isEffectSurface(value.nodes),- alphaMode: mode,- alphaData: alphaData(material),- doubleSided: material.side === THREE14.DoubleSide,- ...mode === "mask" ? { alphaCutoff: standard.alphaTest ?? 0 } : {},- screenAreaRatio: coverageRatio(value.boxes, overall),- transparentLayers: mode === "blend" ? value.nodes.length : 0,- textureMemoryBytes: materialTextureBytes(material)- };- }).sort((a, b) => a.id.localeCompare(b.id));-}-function signedAxis(vector) {- const values = [- { axis: "X", value: vector.x },- { axis: "Y", value: vector.y },- { axis: "Z", value: vector.z }- ];- const dominant = [...values].sort((a, b) => Math.abs(b.value) - Math.abs(a.value))[0];- return `${dominant.value < 0 ? "-" : "+"}${dominant.axis}`;-}-function dominantGeometryAxis(root, mode) {- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- let best;- root.traverse((node) => {- if (!isMeshNode(node) || !node.geometry?.isBufferGeometry || !isEffectSurface([node]))- return;- node.geometry.computeBoundingBox();- const bounds = node.geometry.boundingBox;- if (!bounds || bounds.isEmpty())- return;- const size2 = bounds.getSize(new THREE14.Vector3);- const axes2 = [- { score: size2.x, direction: new THREE14.Vector3(1, 0, 0) },- { score: size2.y, direction: new THREE14.Vector3(0, 1, 0) },- { score: size2.z, direction: new THREE14.Vector3(0, 0, 1) }- ];- const selected = axes2.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);- const relative2 = inverse.clone().multiply(node.matrixWorld);- const direction = selected.direction.transformDirection(relative2);- const score = selected.score * node.getWorldScale(new THREE14.Vector3).length();- if (!best || (mode === "length" ? score > best.score : score < best.score)) {- best = { score, direction };- }- });- if (best)- return signedAxis(best.direction);- const overall = new THREE14.Box3;- root.traverse((node) => {- const box = localRenderableBox(inverse, node);- if (box)- overall.union(box);- });- if (overall.isEmpty())- return "+X";- const size = overall.getSize(new THREE14.Vector3);- const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE14.Vector3(1, 0, 0) : size.y >= size.z ? new THREE14.Vector3(0, 1, 0) : new THREE14.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE14.Vector3(1, 0, 0) : size.y <= size.z ? new THREE14.Vector3(0, 1, 0) : new THREE14.Vector3(0, 0, 1);- return signedAxis(vector);-}-function analyzedFacing(root, intent) {- let cameraFacing = false;- root.traverse((node) => {- if (isSpriteNode(node))- cameraFacing = true;- });- return {- source: cameraFacing ? "explicit" : "inferred",- mode: cameraFacing ? "camera-spherical" : "fixed",- normalAxis: cameraFacing ? "+X" : dominantGeometryAxis(root, "normal"),- ...(intent.subtype === "beam" || intent.subtype === "trail") && {- directionAxis: dominantGeometryAxis(root, "length")- }- };-}-function clipEndpointMatches(clip) {- if (!clip || clip.tracks.length === 0)- return false;- return clip.tracks.every((track) => {- const stride = track.getValueSize();- if (stride <= 0 || track.values.length < stride * 2)- return false;- for (let index = 0;index < stride; index++) {- const first = Number(track.values[index]);- const last = Number(track.values[track.values.length - stride + index]);- if (!Number.isFinite(first) || !Number.isFinite(last) || Math.abs(first - last) > 0.000001) {- return false;- }- }- return true;- });-}-function shaderMaterials(root) {- const values = new Set;- root.traverse((node) => {- if (!isMeshNode(node) && !isSpriteNode(node))- return;- const materials = Array.isArray(node.material) ? node.material : [node.material];- for (const material of materials) {- if (material.isShaderMaterial || material.isNodeMaterial) {- values.add(material);- }- }- });- return [...values];-}-function shaderUniforms(materials) {- const values = new Set;- for (const material of materials) {- const uniforms = material.uniforms;- if (record3(uniforms))- for (const key of Object.keys(uniforms))- values.add(key);- }- return [...values].sort();-}-function analyzeVfxArtifactEvidenceV1(intent, root, clips = []) {- const actualClips = clips.filter(isAnimationClip);- const selectedClip = actualClips.find((clip) => clip.name === intent.animation.clipName) ?? actualClips[0];- const shaders = shaderMaterials(root);- const uniforms = shaderUniforms(shaders);- const actualDriver = selectedClip ? "clip" : uniforms.length > 0 ? "timeUniform" : "none";- const endpointMatches = selectedClip ? clipEndpointMatches(selectedClip) : false;- const playback = actualDriver === "none" ? "static" : actualDriver === "clip" ? endpointMatches ? "loop" : "oneShot" : endpointMatches ? "loop" : "oneShot";- const durationSeconds = selectedClip?.duration ?? 0;- return {- schemaVersion: 1,- facing: analyzedFacing(root, intent),- animation: {- playback,- durationSeconds: stable7(durationSeconds),- endpointBehavior: playback === "static" ? "none" : playback === "loop" ? "matchStart" : "holdLast",- driver: actualDriver,- ...selectedClip ? { clipName: selectedClip.name } : {},- ...actualDriver === "timeUniform" && intent.animation.timeUniformName ? { timeUniformName: intent.animation.timeUniformName } : {},- endpointMatches- },- materials: collectMaterialEvidence(root, intent),- clips: actualClips.map((clip) => ({ name: clip.name, durationSeconds: stable7(clip.duration) })),- uniforms- };-}-function analyzeAssetScopeObservationV1(root) {- let renderableCount = 0;- const members = new Set;- const dressing = new Set;- root.traverse((node) => {- if ((isMeshNode(node) || isSpriteNode(node)) && node.visible)- renderableCount++;- const roles2 = readSemanticMetadataV1(node)?.roles ?? [];- if (roles2.some((role) => MEMBER_ROLE.test(role)))- members.add(node);- for (const role of roles2)- if (DRESSING_ROLE.test(role))- dressing.add(role);- if (node !== root && DRESSING_NAME.test(node.name))- dressing.add(`name:${node.name}`);- });- const memberCount = members.size > 0 ? members.size : renderableCount > 0 ? 1 : 0;- return {- topLevelAssetRoots: memberCount,- reusableMemberCount: memberCount,- sceneDressingRoles: [...dressing].sort()- };-}-function pathOf2(root, node) {- const values = [];- let cursor = node;- while (cursor) {- values.push(cursor.name || cursor.type);- if (cursor === root)- break;- cursor = cursor.parent;- }- return values.reverse().join("/");-}-function analyzeSockets(root) {- root.updateWorldMatrix(true, true);- const rootInverse2 = root.matrixWorld.clone().invert();- const rootWorldRotation = root.getWorldQuaternion(new THREE14.Quaternion).invert();- const values = [];- root.traverse((node) => {- const metadata = readSemanticMetadataV1(node);- if (!metadata)- return;- const nodeWorldRotation = node.getWorldQuaternion(new THREE14.Quaternion);- for (const socket of metadata.sockets) {- const frame = metadata.frames.find((candidate) => candidate.id === socket.frame);- if (!frame)- continue;- const frameRotation = new THREE14.Quaternion(...frame.rotation);- const worldRotation = rootWorldRotation.clone().multiply(nodeWorldRotation).multiply(frameRotation);- const position = new THREE14.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse2);- const normal = new THREE14.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();- values.push({- contract: {- id: socket.id,- pieceId: pathOf2(root, node),- type: socket.type,- compatibleTypes: [...socket.compatibleTypes],- frame: {- translation: [...frame.translation],- rotation: [...frame.rotation]- },- allowedRotationsDegrees: [...socket.allowedRotationsDegrees ?? []]- },- worldPosition: [stable7(position.x), stable7(position.y), stable7(position.z)],- worldNormal: [stable7(normal.x), stable7(normal.y), stable7(normal.z)],- worldRotation- });- }- });- return values.sort((a, b) => a.contract.id.localeCompare(b.contract.id));-}-function analyzeModularEvidenceV1(root, trustedGrid) {- const sockets = analyzeSockets(root);- const kit = {- schemaVersion: 1,- units: "m",- grid: [trustedGrid[0], trustedGrid[1], trustedGrid[2]],- sockets: sockets.map((value) => value.contract)- };- const pair = sockets.flatMap((a, index) => sockets.slice(index + 1).map((b) => [a, b])).find(([a, b]) => a.contract.pieceId !== b.contract.pieceId && a.contract.compatibleTypes.includes(b.contract.type) && b.contract.compatibleTypes.includes(a.contract.type));- if (!pair)- return { kit };- const relative2 = pair[0].worldRotation.clone().invert().multiply(pair[1].worldRotation);- const euler = new THREE14.Euler().setFromQuaternion(relative2, "YXZ");- const rotation = THREE14.MathUtils.euclideanModulo(THREE14.MathUtils.radToDeg(euler.y), 360);- return {- kit,- join: {- aSocketId: pair[0].contract.id,- bSocketId: pair[1].contract.id,- aWorldPosition: pair[0].worldPosition,- bWorldPosition: pair[1].worldPosition,- aWorldNormal: pair[0].worldNormal,- bWorldNormal: pair[1].worldNormal,- relativeRotationDegrees: stable7(rotation)- }- };-}-function deriveW7BreadthEvidence(context) {- if (!isObject3D(context.scene))- return context.derivedEvidence;- const derived = {- source: "engine-scene-analysis",- assetScope: analyzeAssetScopeObservationV1(context.scene)- };- if (context.intent.category === "vfx" && context.intent.vfx) {- derived.vfxArtifact = analyzeVfxArtifactEvidenceV1(context.intent.vfx, context.scene, context.clips);- }- if (context.intent.scope.scope === "modularSet") {- const modular = analyzeModularEvidenceV1(context.scene, context.intent.modular?.grid ?? [1, 1, 1]);- if (modular.kit)- derived.modularKit = modular.kit;- if (modular.join)- derived.modularJoin = modular.join;- }- return derived;-}-function withDerivedW7BreadthEvidence(context) {- const derivedEvidence = deriveW7BreadthEvidence(context);- return derivedEvidence ? { ...context, derivedEvidence } : context;-}-var stable7 = (value) => Math.round(value * 1e6) / 1e6, EFFECT_SURFACE_ROLE, MEMBER_ROLE, DRESSING_ROLE, DRESSING_NAME;-var init_breadth_evidence = __esm(() => {- init_contracts();- EFFECT_SURFACE_ROLE = /^vfx\.effect\.surface(?:\.|$)/;- MEMBER_ROLE = /^(?:asset|scope|cluster|modular)\.member(?:\.|$)|^modular\.piece(?:\.|$)/;- DRESSING_ROLE = /^(?:scene\.dressing|scope\.extra|environment\.dressing)(?:\.|$)/;- DRESSING_NAME = /(?:diorama|display[-_ ]?plate|terrain[-_ ]?base|backdrop)/i;-});--// src/qa/universal.ts-function isSceneNode(value) {- return typeof value === "object" && value !== null;-}-function sceneNodes(context) {- if (!isSceneNode(context.scene))- return [];- const nodes = [];- const seen = new Set;- const add2 = (node) => {- if (!seen.has(node)) {- seen.add(node);- nodes.push(node);- }- };- if (typeof context.scene.traverse === "function") {- context.scene.traverse(add2);- return nodes;- }- const pending = [context.scene];- while (pending.length > 0) {- const node = pending.shift();- add2(node);- for (const child of node.children ?? [])- pending.push(child);- }- return nodes;-}-function nodeName(node) {- return node.name?.trim() || "(unnamed)";-}-function nodePath4(node) {- const names = [];- const seen = new Set;- let cursor = node;- while (cursor && !seen.has(cursor)) {- seen.add(cursor);- names.unshift(nodeName(cursor));- cursor = cursor.parent;- }- return names.join("/");-}-function affectedNode(node, extra = {}) {- return { node: nodeName(node), nodePath: nodePath4(node), ...extra };-}-function isRenderable(node) {- if (node.isSprite)- return true;- if (!(node.isMesh || node.isLine || node.isPoints))- return false;- const position = node.geometry?.attributes?.position;- return typeof position?.count === "number" ? position.count > 0 : Boolean(position?.array?.length);-}-function descendantsContainRenderable(node) {- const pending = [...node.children ?? []];- while (pending.length > 0) {- const child = pending.shift();- if (isRenderable(child))- return true;- pending.push(...child.children ?? []);- }- return false;-}-function finiteComponents(value) {- if (!value)- return true;- const values = "w" in value ? [value.x, value.y, value.z, value.w] : [value.x, value.y, value.z];- return values.every(Number.isFinite);-}-function iterableValues(value) {- if (!value)- return [];- const out = [];- for (let i = 0;i < value.length; i++)- out.push(value[i]);- return out;-}-function emptyOutputFindings(context) {- const nodes = sceneNodes(context);- if (nodes.some(isRenderable))- return [];- return [- {- code: "UNIVERSAL_EMPTY_OUTPUT",- disposition: "block",- dimension: "exportIntegrity",- profile: "universal",- message: "The generated scene contains no renderable geometry.",- measurement: { name: "renderableNodeCount", actual: 0, expected: 1 },- repairText: "Return at least one non-empty renderable mesh or Sprite from build()."- }- ];-}-function finiteDataFindings(context) {- const findings = [];- for (const node of sceneNodes(context)) {- const badTransform = !finiteComponents(node.position) || !finiteComponents(node.quaternion) || !finiteComponents(node.scale) || iterableValues(node.matrix?.elements).some((value) => !Number.isFinite(value));- if (badTransform) {- findings.push({- code: "UNIVERSAL_NONFINITE_TRANSFORM",- disposition: "block",- dimension: "exportIntegrity",- profile: "universal",- message: `Node ${JSON.stringify(nodeName(node))} contains a non-finite transform value.`,- affected: affectedNode(node),- repairText: "Replace NaN/Infinity transform components with finite numbers."- });- }- for (const [attributeName, attribute] of Object.entries(node.geometry?.attributes ?? {})) {- const values = iterableValues(attribute.array);- const badIndex = values.findIndex((value) => !Number.isFinite(value));- if (badIndex >= 0) {- findings.push({- code: "UNIVERSAL_NONFINITE_ATTRIBUTE",- disposition: "block",- dimension: "exportIntegrity",- profile: "universal",- message: `Geometry attribute ${attributeName} on ${JSON.stringify(nodeName(node))} contains a non-finite value.`,- affected: affectedNode(node, { attribute: attributeName }),- measurement: { name: "arrayIndex", actual: badIndex },- repairText: `Rebuild the ${attributeName} attribute with finite numeric data.`- });- }- }- }- return findings;-}-function invalidIndexFindings(context) {- const findings = [];- for (const node of sceneNodes(context)) {- const index = node.geometry?.index;- if (!index?.array)- continue;- const vertexCount = node.geometry?.attributes?.position?.count ?? 0;- const values = iterableValues(index.array);- const badPosition = values.findIndex((value) => !Number.isInteger(value) || value < 0 || value >= vertexCount);- if (badPosition >= 0) {- findings.push({- code: "UNIVERSAL_INVALID_INDEX",- disposition: "block",- dimension: "exportIntegrity",- profile: "universal",- message: `Geometry index on ${JSON.stringify(nodeName(node))} references an invalid vertex.`,- affected: affectedNode(node, { attribute: "index" }),- measurement: {- name: "indexValue",- actual: values[badPosition] ?? null,- threshold: vertexCount - 1- },- repairText: "Rebuild the index so every value is an integer within the POSITION accessor."- });- }- }- return findings;-}-function zeroScaleFindings(context) {- const required = new Set(context.intent.requiredParts);- const findings = [];- for (const node of sceneNodes(context)) {- const scale2 = node.scale;- if (!scale2)- continue;- const zeroAxes = ["x", "y", "z"].filter((axis) => Number.isFinite(scale2[axis]) && Math.abs(scale2[axis]) <= ZERO_SCALE_EPSILON);- if (zeroAxes.length === 0)- continue;- const outputBearing = isRenderable(node) || descendantsContainRenderable(node) || required.has(nodeName(node));- findings.push({- code: outputBearing ? "UNIVERSAL_ZERO_SCALE_RENDERABLE" : "UNIVERSAL_ZERO_SCALE_ORGANIZATIONAL",- disposition: outputBearing ? "block" : "warn",- dimension: outputBearing ? "exportIntegrity" : "categoryReadiness",- profile: "universal",- message: outputBearing ? `Renderable or required node ${JSON.stringify(nodeName(node))} has zero scale.` : `Organizational node ${JSON.stringify(nodeName(node))} has zero scale.`,- affected: affectedNode(node),- measurement: { name: "zeroScaleAxes", actual: zeroAxes.join(",") },- repairText: outputBearing ? "Use a finite non-zero scale for geometry and required semantic nodes." : "Remove the zero scale unless the organizational node is intentionally disabled."- });- }- return findings;-}-function clipList(context) {- return (context.clips ?? []).filter((clip) => typeof clip === "object" && clip !== null);-}-function trackTarget2(trackName) {- const dot4 = trackName.indexOf(".");- if (dot4 <= 0)- return;- const path = trackName.slice(0, dot4);- const slash = path.lastIndexOf("/");- return path.slice(slash + 1) || undefined;-}-function requiredTrackTargets(context) {- const requested = new Set(context.intent.animation?.clips ?? []);- const targets = new Set;- for (const clip of clipList(context)) {- if (!clip.name || !requested.has(clip.name))- continue;- for (const track of clip.tracks ?? []) {- if (track.name) {- const target = trackTarget2(track.name);- if (target)- targets.add(target);- }- }- }- return targets;-}-function duplicateNameFindings2(context) {- const byName = new Map;- for (const node of sceneNodes(context)) {- const name = node.name?.trim();- if (!name)- continue;- const nodes = byName.get(name) ?? [];- nodes.push(node);- byName.set(name, nodes);- }- const required = new Set([...context.intent.requiredParts, ...requiredTrackTargets(context)]);- const findings = [];- for (const [name, nodes] of byName) {- if (nodes.length < 2)- continue;- const contractCritical = required.has(name);- findings.push({- code: contractCritical ? "UNIVERSAL_DUPLICATE_REQUIRED_NODE_NAME" : "UNIVERSAL_DUPLICATE_NODE_NAME",- disposition: contractCritical ? "block" : "warn",- dimension: "categoryReadiness",- profile: "universal",- message: `${nodes.length} scene nodes share the name ${JSON.stringify(name)}.`,- affected: { node: name, nodePath: nodes.map(nodePath4).join(" | ") },- measurement: { name: "duplicateCount", actual: nodes.length, expected: 1 },- repairText: contractCritical ? "Give every required or animated target a unique name." : "Use unique names when nodes must be addressed independently."- });- }- return findings;-}-function animationTargetFindings(context) {- const animation = context.intent.animation;- if (!animation || animation.clips.length === 0)- return [];- const nodes = sceneNodes(context);- const names = new Set(nodes.map((node) => node.name?.trim()).filter(Boolean));- const clips = clipList(context);- const byName = new Map(clips.map((clip) => [clip.name, clip]));- const findings = [];- for (const requiredClip of animation.clips) {- const clip = byName.get(requiredClip);- if (!clip) {- findings.push({- code: "UNIVERSAL_REQUIRED_CLIP_MISSING",- disposition: "block",- dimension: "exportIntegrity",- profile: "universal",- message: `Required animation clip ${JSON.stringify(requiredClip)} is missing.`,- affected: { clip: requiredClip },- repairText: `Create and return the required ${requiredClip} clip from animate().`- });- continue;- }- for (const track of clip.tracks ?? []) {- const trackName = track.name ?? "";- const target = trackTarget2(trackName);- if (!target || !names.has(target)) {- findings.push({- code: "UNIVERSAL_REQUIRED_ANIMATION_TARGET_UNRESOLVED",- disposition: "block",- dimension: "exportIntegrity",- profile: "universal",- message: `Required clip ${JSON.stringify(requiredClip)} has an unresolved track target.`,- affected: { clip: requiredClip, track: trackName, ...target ? { node: target } : {} },- repairText: "Rename the track target to exactly match one unique scene node."- });- }- }- }- return findings;-}-var ZERO_SCALE_EPSILON = 0.00000001, UNIVERSAL_QA_RULES;-var init_universal = __esm(() => {- init_registry();- UNIVERSAL_QA_RULES = [- {- id: "UNIVERSAL_SCENE_CONTENT_RULE",- profile: "universal",- scope: { kind: "universal" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),- defaultMode: "enforce",- evaluate: emptyOutputFindings- },- {- id: "UNIVERSAL_FINITE_DATA_RULE",- profile: "universal",- scope: { kind: "universal" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),- defaultMode: "enforce",- evaluate: finiteDataFindings- },- {- id: "UNIVERSAL_INDEX_RULE",- profile: "universal",- scope: { kind: "universal" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),- defaultMode: "enforce",- evaluate: invalidIndexFindings- },- {- id: "UNIVERSAL_ZERO_SCALE_RULE",- profile: "universal",- scope: { kind: "universal" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),- defaultMode: "enforce",- evaluate: zeroScaleFindings- },- {- id: "UNIVERSAL_NODE_NAME_RULE",- profile: "universal",- scope: { kind: "universal" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),- defaultMode: "enforce",- evaluate: duplicateNameFindings2- },- {- id: "UNIVERSAL_ANIMATION_TARGET_RULE",- profile: "universal",- scope: { kind: "universal" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),- defaultMode: "enforce",- evaluate: animationTargetFindings- }- ];-});--// src/qa/run.ts-var exports_run = {};-__export(exports_run, {- runDeterministicSceneQa: () => runDeterministicSceneQa,- qaPolicyFromEnv: () => qaPolicyFromEnv,- qaBlockingEnabled: () => qaBlockingEnabled,- gltfReportFindings: () => gltfReportFindings,- appendRuntimeCostQa: () => appendRuntimeCostQa,- appendReferenceComparisonQa: () => appendReferenceComparisonQa,- appendMaterialMetricsQa: () => appendMaterialMetricsQa,- appendFinalGltfQa: () => appendFinalGltfQa,- DETERMINISTIC_QA_REGISTRY: () => DETERMINISTIC_QA_REGISTRY,- AssetQaBlockedError: () => AssetQaBlockedError-});-function runDeterministicSceneQa(context, policy = {}) {- const result = DETERMINISTIC_QA_REGISTRY.run(withDerivedW7BreadthEvidence(context), policy);- return createAssetQaReportV1(context.intent, {- findings: result.findings,- evaluatedDimensions: ["exportIntegrity", "categoryReadiness"]- });-}-function gltfReportFindings(report, profile) {- return report.issues.messages.filter((issue) => issue.severity === 0 || issue.severity === 1).filter((issue) => !isExpectedKtx2ValidatorLimitation(report, issue)).map((issue) => ({- code: `GLTF_${issue.code}`.replace(/[^A-Z0-9_]/g, "_"),- disposition: issue.severity === 0 ? "block" : "warn",- dimension: "exportIntegrity",- profile,- message: issue.message,- ...issue.pointer ? { affected: { nodePath: issue.pointer } } : {}- }));-}-function isExpectedKtx2ValidatorLimitation(report, issue) {- const required = report.info?.["extensionsRequired"];- if (!Array.isArray(required) || !required.includes("KHR_texture_basisu"))- return false;- if (issue.code === "VALUE_NOT_IN_LIST") {- return /^\/images\/\d+\/mimeType$/.test(issue.pointer ?? "") && issue.message === "Invalid value 'image/ktx2'. Valid values are ('image/jpeg', 'image/png').";- }- return issue.code === "IMAGE_UNRECOGNIZED_FORMAT" && /^\/images\/\d+$/.test(issue.pointer ?? "") && issue.message === "Image format not recognized.";-}-function appendFinalGltfQa(intent, sceneReport, gltfReport) {- const findings = Object.values(sceneReport.dimensions).flatMap((dimension) => dimension.findings);- const gltfFindings = gltfReportFindings(gltfReport, intent.qaProfile);- findings.push(...gltfFindings);- return createAssetQaReportV1(intent, {- findings,- evaluatedDimensions: ["exportIntegrity", "categoryReadiness"],- metrics: {- exportIntegrity: {- gltfErrors: gltfReport.issues.numErrors,- gltfWarnings: gltfFindings.filter((finding6) => finding6.disposition === "warn").length- }- }- });-}-function appendRuntimeCostQa(intent, report, instanceability, metricsError) {- const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);- if (metricsError) {- findings.push({- code: "RUNTIME_COST_METRICS_FAILED",- disposition: "warn",- dimension: "runtimeCost",- profile: intent.qaProfile,- message: `Runtime-cost metrics could not be computed: ${metricsError}`- });- }- const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);- evaluatedDimensions.push("runtimeCost");- const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));- if (instanceability) {- metrics.runtimeCost = {- instanceabilityGrade: instanceability.grade,- instanceabilitySummary: instanceability.summary,- uniqueGeometries: instanceability.metrics.uniqueGeometries,- uniqueMaterials: instanceability.metrics.uniqueMaterials,- drawCalls: instanceability.metrics.drawCalls,- textureCount: instanceability.metrics.textureCount,- transparentMaterials: instanceability.metrics.transparentMaterials,- triangles: instanceability.metrics.triangles,- skinned: instanceability.metrics.skinned- };- }- return createAssetQaReportV1(intent, {- findings,- evaluatedDimensions,- ...Object.keys(metrics).length > 0 ? { metrics } : {}- });-}-function appendMaterialMetricsQa(intent, report, materialMetrics, budgetWarnings = []) {- const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);- findings.push(...budgetWarnings.map((warning) => ({- code: warning.code,- disposition: "warn",- dimension: "runtimeCost",- profile: `${warning.profile}.${warning.tier}`,- message: `${warning.message} ${warning.advice}`,- measurement: warning.measurement- })));- const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);- if (!evaluatedDimensions.includes("runtimeCost"))- evaluatedDimensions.push("runtimeCost");- const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));- metrics.runtimeCost = {- ...metrics.runtimeCost ?? {},- materialCount: materialMetrics.materialCount,- opaqueMaterials: materialMetrics.opaqueMaterials,- maskedMaterials: materialMetrics.maskedMaterials,- blendedMaterials: materialMetrics.blendedMaterials,- singleSidedMaterials: materialMetrics.singleSidedMaterials,- doubleSidedMaterials: materialMetrics.doubleSidedMaterials,- texturedMaterials: materialMetrics.texturedMaterials,- materialExtensionCount: materialMetrics.materialExtensionCount,- materialExtensionsUsed: materialMetrics.materialExtensionsUsed.join(","),- imageCount: materialMetrics.imageCount,- maxImageDimension: materialMetrics.maxImageDimension,- decodedImageBytesRgba8: materialMetrics.decodedImageBytesRgba8,- estimatedGpuBytesWithMipmaps: materialMetrics.estimatedGpuBytesWithMipmaps,- blendedSurfaceAreaRatio: materialMetrics.blendedSurfaceAreaRatio- };- return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });-}-function appendReferenceComparisonQa(intent, report, evidence2) {- const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);- findings.push(...referenceComparisonFindings(evidence2, "reference.comparison"));- const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);- if (!evaluatedDimensions.includes("promptAlignment"))- evaluatedDimensions.push("promptAlignment");- const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));- metrics.promptAlignment = {- ...metrics.promptAlignment ?? {},- referenceSilhouetteIoU: evidence2.silhouetteIoU,- referenceColorAgreement: evidence2.colorAgreement,- referenceCoverageRatio: evidence2.coverageRatio,- referenceShadowPixels: evidence2.reference.shadowPixels- };- return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });-}-function qaPolicyFromEnv(env = process.env) {- const mode = env["KILN_QA_MODE"];- return mode === "observe" || mode === "off" ? { defaultMode: mode } : {};-}-function qaBlockingEnabled(env = process.env) {- const mode = env["KILN_QA_MODE"];- return mode !== "observe" && mode !== "off";-}-var DETERMINISTIC_QA_REGISTRY, MAX_DETAILED_BLOCKERS = 6, AssetQaBlockedError;-var init_run = __esm(() => {- init_material();- init_architecture();- init_character2();- init_character_advisory();- init_vehicle2();- init_vegetation();- init_prop();- init_part_connectivity();- init_reference_comparison();- init_self_intersection();- init_environment2();- init_breadth2();- init_breadth_evidence();- init_registry();- init_types();- init_universal();- DETERMINISTIC_QA_REGISTRY = new QaRegistry([- ...UNIVERSAL_QA_RULES,- MATERIAL_QA_RULE,- ...ARCHITECTURE_QA_RULES,- CHARACTER_QA_RULE,- CHARACTER_ADVISORY_QA_RULE,- ...VEHICLE_QA_RULES,- ...VEGETATION_QA_RULES,- ...PROP_QA_RULES,- ...ENVIRONMENT_QA_RULES,- ...W7_BREADTH_QA_RULES,- SELF_INTERSECTION_QA_RULE,- PART_CONNECTIVITY_QA_RULE,- REFERENCE_COMPARISON_QA_RULE- ]);- AssetQaBlockedError = class AssetQaBlockedError extends Error {- report;- stage;- gltfValidation;- constructor(report, stage, gltfValidation) {- const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding6) => finding6.disposition === "block");- const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding6) => `${finding6.code}: ${finding6.message}${finding6.repairText ? ` FIX: ${finding6.repairText}` : ""}`);- const overflow = blockers.length > MAX_DETAILED_BLOCKERS ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)` : "";- super(`Asset QA blocked at ${stage}: ${detailed.join(" | ") || "unknown blocker"}${overflow}`);- this.name = "AssetQaBlockedError";- this.report = report;- this.stage = stage;- this.gltfValidation = gltfValidation;- }- };-});--// src/geometry-export.ts-function geometryAttributeValues(attribute) {- const values = new Float32Array(attribute.count * attribute.itemSize);- for (let vertex = 0;vertex < attribute.count; vertex++) {- for (let component = 0;component < attribute.itemSize; component++) {- values[vertex * attribute.itemSize + component] = attribute.getComponent(vertex, component);- }- }- return values;-}-function inspectGeometryExport(root, policy = "warn") {- const warnings = [];- root.traverse((node) => {- const mesh = node;- if (!mesh.isMesh)- return;- const geometry = mesh.geometry;- const name = mesh.name || "<unnamed mesh>";- const unsupported = (feature) => {- const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.`;- if (policy === "strict")- throw new TypeError(message);- warnings.push(message);- };- const position = geometry.getAttribute("position");- if (!position || position.itemSize !== 3)- throw new TypeError(`${name}: position requires xyz vertices.`);- for (const [key, attribute] of Object.entries(geometry.attributes)) {- const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key];- if (expected === undefined) {- unsupported(key);- continue;- }- if (attribute.itemSize !== expected || attribute.count !== position.count) {- throw new TypeError(`${name}: ${key} requires ${position.count} vertices with ${expected} components each.`);- }- for (let vertex = 0;vertex < attribute.count; vertex++) {- for (let component = 0;component < attribute.itemSize; component++) {- if (!Number.isFinite(attribute.getComponent(vertex, component))) {- throw new TypeError(`${name}: ${key} contains a non-finite value at vertex ${vertex}.`);- }- }- }- }- const index = geometry.getIndex();- if ((index?.count ?? position.count) % 3 !== 0)- throw new TypeError(`${name}: triangle indices/vertices must be a multiple of three.`);- if (index) {- for (let i = 0;i < index.count; i++) {- const value = index.getX(i);- if (!Number.isInteger(value) || value < 0 || value >= position.count)- throw new TypeError(`${name}: index ${i} is outside the position attribute.`);- }- }- for (const key of Object.keys(geometry.morphAttributes))- unsupported(`morph ${key}`);- if (mesh.isSkinnedMesh)- unsupported("skinning");- for (const key of ["kilnAttributeWarnings", "kilnGeometryWarnings"]) {- const notes = geometry.userData[key];- if (!Array.isArray(notes))- continue;- for (const note of notes) {- if (typeof note === "string")- warnings.push(`${name}: ${note}`);- else if (note && typeof note === "object" && "code" in note)- warnings.push(`${name}: ${String(note.code)}${"message" in note ? ` ${String(note.message)}` : ""}`);- }- }- });- return warnings;-}-var EXPORTED_GEOMETRY_ATTRIBUTES;-var init_geometry_export = __esm(() => {- EXPORTED_GEOMETRY_ATTRIBUTES = {- position: 3,- normal: 3,- uv: 2,- tangent: 4- };-});--// src/palette-snap.ts-function srgbChannelToLinear(c) {- return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;-}-function hexToLinearRgb(hex) {- const h = hex.trim().replace(/^#/, "");- const full = h.length === 3 ? h[0] + h[0] + h[1] + h[1] + h[2] + h[2] : h;- const n = Number.parseInt(full.slice(0, 6).padEnd(6, "0"), 16);- const r = (n >> 16 & 255) / 255;- const g = (n >> 8 & 255) / 255;- const b = (n & 255) / 255;- return [srgbChannelToLinear(r), srgbChannelToLinear(g), srgbChannelToLinear(b)];-}-function linToOklab(r, g, b) {- const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;- const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;- const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;- const l_ = Math.cbrt(l), m_ = Math.cbrt(m), s_ = Math.cbrt(s);- return [- 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,- 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,- 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_- ];-}-function buildSlotIndex(slots) {- const opaque = [];- const neutral = [];- const chromatic = [];- const glass = [];- const glow = [];- slots.forEach((s, i) => {- const kind = s.kind ?? "opaque";- const [r, g, b] = hexToLinearRgb(s.color);- const lab = linToOklab(r, g, b);- if (kind === "glass") {- glass.push(i);- return;- }- if (kind === "glow") {- glow.push({ i, lab });- return;- }- opaque.push({ i, lab });- if (relChroma(lab) >= REL_CHROMA_GATE)- chromatic.push({ i, lab });- else- neutral.push({ i, lab });- });- return { slots, opaque, neutral, chromatic, glass, glow };-}-function nearestIn(cands, lab, dist) {- let best = cands[0].i, bd = Infinity;- for (const c of cands) {- const d = dist(c.lab, lab);- if (d < bd) {- bd = d;- best = c.i;- }- }- return best;-}-function nearestOpaqueSlot(idx, lin) {- if (idx.opaque.length === 0)- return;- const lab = linToOklab(lin[0], lin[1], lin[2]);- if (relChroma(lab) >= REL_CHROMA_GATE) {- return idx.chromatic.length ? nearestIn(idx.chromatic, lab, dE2Chroma) : nearestIn(idx.opaque, lab, dE2);- }- return idx.neutral.length ? nearestIn(idx.neutral, lab, dE2) : nearestIn(idx.opaque, lab, dE2);-}-function nearestGlowSlot(idx, emissiveLin) {- if (idx.glow.length === 0)- return;- return nearestIn(idx.glow, linToOklab(emissiveLin[0], emissiveLin[1], emissiveLin[2]), dE2);-}-function chooseSlot(idx, m) {- const emi = m.emissiveLinear;- const isEmissive = !!emi && (emi[0] > 0.0025 || emi[1] > 0.0025 || emi[2] > 0.0025);- if (isEmissive) {- const g = nearestGlowSlot(idx, emi);- if (g !== undefined)- return g;- }- if (m.transparent && idx.glass.length > 0) {- if (idx.glass.length === 1)- return idx.glass[0];- const lab = linToOklab(m.baseLinear[0], m.baseLinear[1], m.baseLinear[2]);- let best = idx.glass[0], bd = Infinity;- for (const gi of idx.glass) {- const [r, g, b] = hexToLinearRgb(idx.slots[gi].color);- const d = dE2(linToOklab(r, g, b), lab);- if (d < bd) {- bd = d;- best = gi;- }- }- return best;- }- return nearestOpaqueSlot(idx, m.baseLinear);-}-var dE2 = (a, b) => {- const dl = a[0] - b[0], da = a[1] - b[1], db = a[2] - b[2];- return dl * dl + da * da + db * db;-}, L_WEIGHT_CHROMA = 0.3, dE2Chroma = (a, b) => {- const dl = a[0] - b[0], da = a[1] - b[1], db = a[2] - b[2];- return L_WEIGHT_CHROMA * dl * dl + da * da + db * db;-}, chroma = (lab) => Math.hypot(lab[1], lab[2]), REL_CHROMA_GATE = 0.04, relChroma = (lab) => chroma(lab) / Math.max(lab[0], 0.25);--// src/architecture.ts-import * as THREE15 from "three";-function positive2(value, name) {- if (!Number.isFinite(value) || value <= 0)- throw new RangeError(`${name} must be finite and > 0`);- return value;-}-function nonNegative(value, name) {- if (!Number.isFinite(value) || value < 0)- throw new RangeError(`${name} must be finite and >= 0`);- return value;-}-function roleMetadata(roles2, relationships = [], frames = []) {- return { roles: roles2, relationships, frames, sockets: [] };-}-function relationship(kind, target) {- return { kind, target, targetType: "role" };-}-function setTransform(object, matrix) {- matrix.decompose(object.position, object.quaternion, object.scale);-}-function resolvePitch(halfRun, rise, pitchDegrees) {- positive2(halfRun, "roof half-run");- if (rise === undefined && pitchDegrees === undefined)- pitchDegrees = 30;- if (pitchDegrees !== undefined) {- if (!Number.isFinite(pitchDegrees) || pitchDegrees <= 0 || pitchDegrees >= 89) {- throw new RangeError("pitchDegrees must be finite, > 0, and < 89");- }- }- if (rise !== undefined)- positive2(rise, "rise");- const resolvedPitch = pitchDegrees ?? Math.atan2(rise, halfRun) / DEG;- const resolvedRise = rise ?? Math.tan(resolvedPitch * DEG) * halfRun;- const expected = Math.tan(resolvedPitch * DEG) * halfRun;- if (Math.abs(resolvedRise - expected) > Math.max(EPSILON3, expected * 0.000001)) {- throw new RangeError("rise and pitchDegrees disagree for the requested footprint");- }- return { rise: resolvedRise, pitchDegrees: resolvedPitch };-}-function resolveRoofProfile(options) {- const spanX = positive2(options.spanX, "spanX");- const spanZ = positive2(options.spanZ, "spanZ");- const ridgeAxis = options.ridgeAxis ?? "x";- const overhang = nonNegative(options.overhang ?? 0.3, "overhang");- const thickness = positive2(options.thickness ?? 0.08, "thickness");- const halfRun = (ridgeAxis === "x" ? spanZ : spanX) / 2;- const pitch = resolvePitch(halfRun, options.rise, options.pitchDegrees);- return {- spanX,- spanZ,- ridgeAxis,- overhang,- thickness,- ...pitch,- ridgeY: pitch.rise,- eaveY: -Math.tan(pitch.pitchDegrees * DEG) * overhang- };-}-function buildFace(roofRoot, profile, sideSign) {- const side = sideSign > 0 ? "positive" : "negative";- const halfFoot = (profile.ridgeAxis === "x" ? profile.spanZ : profile.spanX) / 2;- const horizontalRun = halfFoot + profile.overhang;- const verticalRun = profile.ridgeY - profile.eaveY;- const downhillLength = Math.hypot(horizontalRun, verticalRun);- const alongRidge = (profile.ridgeAxis === "x" ? profile.spanX : profile.spanZ) + profile.overhang * 2;- const downhill = profile.ridgeAxis === "x" ? new THREE15.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE15.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();- const tangent = profile.ridgeAxis === "x" ? new THREE15.Vector3(sideSign, 0, 0) : new THREE15.Vector3(0, 0, -sideSign);- const normal = downhill.clone().cross(tangent).normalize();- const localToRoof = new THREE15.Matrix4().makeBasis(tangent, normal, downhill);- localToRoof.setPosition(0, profile.ridgeY, 0);- const world = () => {- roofRoot.updateWorldMatrix(true, false);- return roofRoot.matrixWorld.clone().multiply(localToRoof);- };- const direction = (axis) => axis.clone().transformDirection(world());- const point = (x, z3) => new THREE15.Vector3(x, 0, z3).applyMatrix4(world());- return {- side,- ridgeAxis: profile.ridgeAxis,- roofRoot,- localToRoof,- get localToWorld() {- return world();- },- get ridgeTangent() {- return direction(new THREE15.Vector3(1, 0, 0));- },- get downhillDirection() {- return direction(new THREE15.Vector3(0, 0, 1));- },- get outwardNormal() {- return direction(new THREE15.Vector3(0, 1, 0));- },- get ridgeStart() {- return point(-alongRidge / 2, 0);- },- get ridgeEnd() {- return point(alongRidge / 2, 0);- },- get eaveStart() {- return point(-alongRidge / 2, downhillLength);- },- get eaveEnd() {- return point(alongRidge / 2, downhillLength);- },- dimensions: { alongRidge, downhill: downhillLength, thickness: profile.thickness }- };-}-function buildRoof(name, material, profile, parent) {- const root = new THREE15.Object3D;- root.name = name;- if (parent)- parent.add(root);- stampSemanticMetadataV1(root, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "assembly")], [relationship("separable-from", "architecture.shell.gable")]));- const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)];- const buildSlope = (face) => {- const geometry = new THREE15.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);- const mesh = new THREE15.Mesh(geometry, material);- mesh.name = `Mesh_${name}_${face.side}`;- const center = new THREE15.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);- setTransform(mesh, face.localToRoof.clone().multiply(center));- const coveredWall = profile.ridgeAxis === "x" ? face.side === "positive" ? "wall.right" : "wall.left" : face.side === "positive" ? "wall.front" : "wall.back";- stampSemanticMetadataV1(mesh, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side)], [- relationship("adjacent-to", semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side === "positive" ? "negative" : "positive")),- relationship("coverage-of", coveredWall),- relationship("separable-from", "architecture.shell.gable")- ], [- { id: "surface", translation: [0, profile.thickness / 2, 0], rotation: [0, 0, 0, 1] },- {- id: "ridge",- translation: [0, profile.thickness / 2, -face.dimensions.downhill / 2],- rotation: [0, 0, 0, 1]- },- {- id: "eave",- translation: [0, profile.thickness / 2, face.dimensions.downhill / 2],- rotation: [0, 0, 0, 1]- }- ]));- root.add(mesh);- return mesh;- };- const slopes = [buildSlope(faces[0]), buildSlope(faces[1])];- return {- root,- slopes,- faces: [faces[0], faces[1]],- rise: profile.rise,- pitchDegrees: profile.pitchDegrees- };-}-function createGableRoof(name, material, options) {- return buildRoof(name, material, resolveRoofProfile(options), options.parent);-}-function createRoofPlanes(name, material, options) {- const ridgeAxis = options.ridgeAxis ?? "x";- const overhang = nonNegative(options.overhang ?? 0.3, "overhang");- const halfFoot = (ridgeAxis === "x" ? positive2(options.width, "width") : positive2(options.depth, "depth")) / 2;- const totalRun = halfFoot + overhang;- const height = positive2(options.height, "height");- const pitchDegrees = Math.atan2(height, totalRun) / DEG;- const profile = resolveRoofProfile({- spanX: options.depth,- spanZ: options.width,- ridgeAxis,- overhang,- thickness: options.thickness,- rise: Math.tan(pitchDegrees * DEG) * halfFoot- });- profile.ridgeY = height;- profile.eaveY = 0;- profile.pitchDegrees = pitchDegrees;- return buildRoof(name, material, profile, options.parent);-}-function openingFitsTriangle(opening, span, rise) {- const half = span / 2;- const left = opening.offset - opening.width / 2;- const right = opening.offset + opening.width / 2;- const top = opening.bottom + opening.height;- const maxAt = (u) => rise * (1 - Math.abs(u) / half);- return left > -half && right < half && opening.bottom >= 0 && top < Math.min(maxAt(left), maxAt(right));-}-function createGableEndPanel(name, material, options) {- const span = positive2(options.span, "span");- const rise = positive2(options.rise, "rise");- const thickness = positive2(options.thickness ?? 0.15, "thickness");- const ridgeAxis = options.ridgeAxis ?? "x";- const side = options.side ?? "positive";- const half = span / 2;- const shape = new THREE15.Shape;- shape.moveTo(-half, 0);- shape.lineTo(half, 0);- shape.lineTo(0, rise);- shape.closePath();- const normalized = (options.openings ?? []).map((opening) => ({- id: opening.id,- offset: opening.offset ?? 0,- bottom: opening.bottom ?? 0.25,- width: positive2(opening.width, "opening.width"),- height: positive2(opening.height, "opening.height")- }));- for (const opening of normalized) {- if (!openingFitsTriangle(opening, span, rise))- throw new RangeError("gable opening must fit strictly inside the triangular boundary");- const left = opening.offset - opening.width / 2;- const right = opening.offset + opening.width / 2;- const bottom = opening.bottom;- const top = bottom + opening.height;- const hole = new THREE15.Path;- hole.moveTo(left, bottom);- hole.lineTo(left, top);- hole.lineTo(right, top);- hole.lineTo(right, bottom);- hole.closePath();- shape.holes.push(hole);- }- const geometry = new THREE15.ExtrudeGeometry(shape, {- depth: thickness,- bevelEnabled: false,- steps: 1- });- geometry.translate(0, 0, -thickness / 2);- if (ridgeAxis === "x")- geometry.rotateY(-Math.PI / 2);- geometry.computeVertexNormals();- const root = new THREE15.Mesh(geometry, material);- root.name = `Mesh_${name}`;- stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [- relationship("adjacent-to", "roof.slope.positive"),- relationship("adjacent-to", "roof.slope.negative"),- relationship("coverage-of", ridgeAxis === "x" ? side === "positive" ? "wall.front" : "wall.back" : side === "positive" ? "wall.right" : "wall.left"),- relationship("separable-from", "architecture.shell.gable")- ], [- { id: "base", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },- {- id: "apex",- translation: ridgeAxis === "x" ? [0, rise, 0] : [0, rise, 0],- rotation: [0, 0, 0, 1]- }- ]));- const markers = normalized.map((opening, index) => {- const marker = new THREE15.Object3D;- marker.name = `Opening_${name}_${opening.id ?? index + 1}`;- marker.position.set(ridgeAxis === "z" ? opening.offset : 0, opening.bottom + opening.height / 2, ridgeAxis === "x" ? opening.offset : 0);- marker.scale.set(ridgeAxis === "x" ? thickness : opening.width, opening.height, ridgeAxis === "x" ? opening.width : thickness);- stampSemanticMetadataV1(marker, roleMetadata([`opening.gable.${side}.${opening.id ?? index + 1}`], [relationship("cutout-of", `roof.gable.${side}`)]));- root.add(marker);- return marker;- });- if (options.parent)- options.parent.add(root);- return { root, geometry, openings: markers };-}-function wallRunAxis(wall) {- return wall === "front" || wall === "back" ? "z" : "x";-}-function wallNeighbors(wall) {- return wall === "front" || wall === "back" ? ["left", "right"] : ["front", "back"];-}-function createShellWall(name, wall, material, length3, height, thickness, openings) {- const axis = wallRunAxis(wall);- const root = new THREE15.Object3D;- root.name = `${name}_Wall_${wall}`;- const neighbors = wallNeighbors(wall);- stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [- relationship("adjacent-to", `wall.${neighbors[0]}`),- relationship("adjacent-to", `wall.${neighbors[1]}`),- relationship("adjacent-to", "floor")- ]));- const sorted = openings.map((opening2, index) => ({- ...opening2,- id: opening2.id ?? `${opening2.kind ?? "door"}-${index + 1}`,- kind: opening2.kind ?? "door",- offset: opening2.offset ?? 0,- width: positive2(opening2.width ?? (opening2.kind === "window" ? 1 : 1.1), "opening.width"),- height: positive2(opening2.height ?? (opening2.kind === "window" ? 1 : 2.1), "opening.height"),- sill: opening2.kind === "window" ? nonNegative(opening2.sill ?? 1, "opening.sill") : 0,- depth: positive2(opening2.depth ?? thickness, "opening.depth")- })).sort((a, b) => a.offset - b.offset);- if (sorted.length > 1)- throw new RangeError("the minimal gable shell supports at most one opening per wall");- const panel = (suffix, lo, hi, y0, y1) => {- if (hi - lo <= EPSILON3 || y1 - y0 <= EPSILON3)- return;- const geometry = axis === "x" ? new THREE15.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE15.BoxGeometry(thickness, y1 - y0, hi - lo);- const mesh = new THREE15.Mesh(geometry, material);- mesh.name = `Mesh_${name}_${wall}_${suffix}`;- mesh.position.set(axis === "x" ? (lo + hi) / 2 : 0, (y0 + y1) / 2, axis === "z" ? (lo + hi) / 2 : 0);- root.add(mesh);- };- const markers = [];- const opening = sorted[0];- if (!opening)- panel("solid", -length3 / 2, length3 / 2, 0, height);- else {- const left = opening.offset - opening.width / 2;- const right = opening.offset + opening.width / 2;- const top = opening.sill + opening.height;- if (left <= -length3 / 2 || right >= length3 / 2 || top >= height)- throw new RangeError(`opening on wall.${wall} must fit strictly inside the wall boundary`);- panel("left", -length3 / 2, left, 0, height);- panel("right", right, length3 / 2, 0, height);- panel("lintel", left, right, top, height);- if (opening.sill > 0)- panel("sill", left, right, 0, opening.sill);- const marker = new THREE15.Object3D;- marker.name = `Opening_${wall}_${opening.id}`;- marker.position.set(axis === "x" ? opening.offset : 0, opening.sill + opening.height / 2, axis === "z" ? opening.offset : 0);- marker.scale.set(axis === "x" ? opening.width : opening.depth, opening.height, axis === "z" ? opening.width : opening.depth);- stampSemanticMetadataV1(marker, roleMetadata([`opening.${wall}.${opening.kind}`], [- relationship("cutout-of", `wall.${wall}`),- relationship(opening.kind === "door" ? "portal-through" : "aperture-through", `wall.${wall}`)- ], [{ id: "clearance", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }]));- root.add(marker);- markers.push(marker);- }- return { root, openings: markers };-}-function createGableShell(name, materials, options) {- const spanX = positive2(options.spanX, "spanX");- const spanZ = positive2(options.spanZ, "spanZ");- const wallHeight = positive2(options.wallHeight ?? 2.8, "wallHeight");- const wallThickness = positive2(options.wallThickness ?? 0.15, "wallThickness");- const floorThickness = positive2(options.floorThickness ?? 0.1, "floorThickness");- const ridgeAxis = options.ridgeAxis ?? "x";- const closedEnds = options.closedEnds ?? true;- const enterable = options.enterable ?? true;- const shellOpenings = options.openings ?? (enterable ? [{ wall: "front", kind: "door" }] : []);- const root = new THREE15.Object3D;- root.name = name;- if (options.parent)- options.parent.add(root);- stampSemanticMetadataV1(root, roleMetadata(["architecture.shell.gable"], [relationship("contains", "floor"), relationship("contains", "roof.assembly")]));- const wallSpecs = {- front: { length: spanZ, position: [spanX / 2, 0, 0] },- back: { length: spanZ, position: [-spanX / 2, 0, 0] },- left: { length: spanX, position: [0, 0, -spanZ / 2] },- right: { length: spanX, position: [0, 0, spanZ / 2] }- };- const walls = {};- const openingMarkers = [];- for (const wall of ["front", "back", "left", "right"]) {- const built = createShellWall(name, wall, materials.wall, wallSpecs[wall].length, wallHeight, wallThickness, shellOpenings.filter((opening) => opening.wall === wall));- built.root.position.set(...wallSpecs[wall].position);- root.add(built.root);- walls[wall] = built.root;- openingMarkers.push(...built.openings);- }- const floor = new THREE15.Mesh(new THREE15.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);- floor.name = `Mesh_${name}_Floor`;- floor.position.y = -floorThickness / 2;- stampSemanticMetadataV1(floor, roleMetadata(["floor"], ["front", "back", "left", "right"].map((wall) => relationship("adjacent-to", `wall.${wall}`))));- root.add(floor);- const roof = createGableRoof("Roof", materials.roof, {- ...options,- spanX,- spanZ,- ridgeAxis,- parent: root- });- roof.root.position.y = wallHeight;- let gables = [];- if (closedEnds) {- const gableMaterial = materials.gable ?? materials.wall;- const span = ridgeAxis === "x" ? spanZ : spanX;- const ridgeSpan = ridgeAxis === "x" ? spanX : spanZ;- const positiveEnd = createGableEndPanel(`${name}_Gable_positive`, gableMaterial, {- span,- rise: roof.rise,- thickness: wallThickness,- ridgeAxis,- side: "positive",- openings: options.gableOpenings?.positive,- parent: roof.root- });- const negativeEnd = createGableEndPanel(`${name}_Gable_negative`, gableMaterial, {- span,- rise: roof.rise,- thickness: wallThickness,- ridgeAxis,- side: "negative",- openings: options.gableOpenings?.negative,- parent: roof.root- });- const coordinate = ridgeSpan / 2;- positiveEnd.root.position.set(ridgeAxis === "x" ? coordinate : 0, 0, ridgeAxis === "z" ? coordinate : 0);- negativeEnd.root.position.set(ridgeAxis === "x" ? -coordinate : 0, 0, ridgeAxis === "z" ? -coordinate : 0);- gables = [positiveEnd.root, negativeEnd.root];- openingMarkers.push(...positiveEnd.openings, ...negativeEnd.openings);- }- return { root, walls, floor, roof, gables, openings: openingMarkers };-}-function createRoofSurfaceLayout(name, material, options) {- const parent = options.parent ?? options.face.roofRoot;- const root = new THREE15.Object3D;- root.name = name;- parent.add(root);- stampSemanticMetadataV1(root, roleMetadata([`roof.surface.${options.kind}`], [relationship("coverage-of", `roof.slope.${options.face.side}`)]));- root.updateWorldMatrix(true, false);- const faceToRoot = root.matrixWorld.clone().invert().multiply(options.face.localToWorld);- const thickness = positive2(options.thickness ?? 0.025, "thickness");- const along = options.face.dimensions.alongRidge;- const downhill = options.face.dimensions.downhill;- const specs = [];- if (options.kind === "panels") {- const count = Math.max(1, Math.ceil(along / positive2(options.panelWidth ?? 0.9, "panelWidth")));- const width = along / count;- for (let i = 0;i < count; i++)- specs.push({- width: width * 0.98,- length: downhill,- x: -along / 2 + width * (i + 0.5),- z: downhill / 2- });- } else if (options.kind === "shingles") {- const rowHeight = positive2(options.rowHeight ?? 0.32, "rowHeight");- const tileWidth = positive2(options.panelWidth ?? 0.42, "panelWidth");- const rows = Math.max(1, Math.ceil(downhill / rowHeight));- const columns = Math.max(1, Math.ceil(along / tileWidth));- for (let row = 0;row < rows; row++) {- const length3 = Math.min(rowHeight * 1.08, downhill);- for (let column = 0;column < columns; column++) {- const offset = row % 2 === 0 ? 0 : tileWidth / 2;- const x = -along / 2 + tileWidth * (column + 0.5) + offset;- if (x + tileWidth / 2 <= along / 2 + EPSILON3)- specs.push({- width: tileWidth * 0.96,- length: length3,- x,- z: Math.min(downhill - length3 / 2, row * rowHeight + length3 / 2)- });- }- }- } else {- const spacing = positive2(options.spacing ?? (options.kind === "seams" ? 0.6 : 0.18), "spacing");- const count = Math.max(2, Math.floor(along / spacing) + 1);- const width = options.kind === "seams" ? 0.025 : 0.018;- for (let i = 0;i < count; i++)- specs.push({- width,- length: downhill,- x: -along / 2 + along * i / (count - 1),- z: downhill / 2- });- }- const items = specs.map((spec, index) => {- const mesh = new THREE15.Mesh(new THREE15.BoxGeometry(spec.width, thickness, spec.length), material);- mesh.name = `Mesh_${name}_${index + 1}`;- const local = new THREE15.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);- setTransform(mesh, faceToRoot.clone().multiply(local));- root.add(mesh);- return mesh;- });- return { root, items };-}-var DEG, EPSILON3 = 0.0000001;-var init_architecture2 = __esm(() => {- init_contracts();- DEG = Math.PI / 180;-});--// src/gears.ts-import * as THREE16 from "three";-function gearGeo(opts = {}) {- const {- teeth = 12,- rootRadius = 0.8,- tipRadius = 1,- boreRadius = 0.2,- height = 0.3,- toothWidthFrac = 0.5- } = opts;- if (teeth < 3)- throw new Error("gearGeo: teeth must be >= 3");- if (tipRadius <= rootRadius || boreRadius >= rootRadius) {- throw new AuthoringDiagnosticError("GEAR_RADII_ORDER");- }- const sector = Math.PI * 2 / teeth;- const alpha = (1 - toothWidthFrac) * (sector / 2);- const crown = [];- for (let i = 0;i < teeth; i++) {- const base = i * sector;- const a0 = base;- const a1 = base + alpha;- const a2 = base + sector - alpha;- crown.push([rootRadius * Math.cos(a0), rootRadius * Math.sin(a0)]);- crown.push([tipRadius * Math.cos(a1), tipRadius * Math.sin(a1)]);- crown.push([tipRadius * Math.cos(a2), tipRadius * Math.sin(a2)]);- }- const N = crown.length;- const bore = [];- for (let i = 0;i < N; i++) {- const t = Math.atan2(crown[i][1], crown[i][0]);- bore.push([boreRadius * Math.cos(t), boreRadius * Math.sin(t)]);- }- const halfH = height / 2;- const positions = [];- const indices = [];- for (let i = 0;i < N; i++) {- const p = crown[i];- positions.push(p[0], halfH, p[1]);- }- for (let i = 0;i < N; i++) {- const p = crown[i];- positions.push(p[0], -halfH, p[1]);- }- for (let i = 0;i < N; i++) {- const p = bore[i];- positions.push(p[0], halfH, p[1]);- }- for (let i = 0;i < N; i++) {- const p = bore[i];- positions.push(p[0], -halfH, p[1]);- }- const crownTop = 0;- const crownBot = N;- const boreTop = 2 * N;- const boreBot = 3 * N;- for (let i = 0;i < N; i++) {- const j = (i + 1) % N;- const cA = crownTop + i;- const cB = crownTop + j;- const bA = boreTop + i;- const bB = boreTop + j;- indices.push(bA, cB, cA);- if (boreRadius > 0)- indices.push(bA, bB, cB);- }- for (let i = 0;i < N; i++) {- const j = (i + 1) % N;- const cA = crownBot + i;- const cB = crownBot + j;- const bA = boreBot + i;- const bB = boreBot + j;- indices.push(bA, cA, cB);- if (boreRadius > 0)- indices.push(bA, cB, bB);- }- for (let i = 0;i < N; i++) {- const j = (i + 1) % N;- const tA = crownTop + i;- const tB = crownTop + j;- const bA = crownBot + i;- const bB = crownBot + j;- indices.push(tA, tB, bB);- indices.push(tA, bB, bA);- }- for (let i = 0;boreRadius > 0 && i < N; i++) {- const j = (i + 1) % N;- const tA = boreTop + i;- const tB = boreTop + j;- const bA = boreBot + i;- const bB = boreBot + j;- indices.push(tA, bA, bB);- indices.push(tA, bB, tB);- }- const geo = new THREE16.BufferGeometry;- geo.setAttribute("position", new THREE16.Float32BufferAttribute(positions, 3));- geo.setIndex(indices);- const nonIndexed = geo.toNonIndexed();- nonIndexed.computeVertexNormals();- return nonIndexed;-}-function bladeGeo(opts = {}) {- const {- length: length3 = 1.5,- baseWidth = 0.1,- thickness = 0.015,- tipLength = 0.25,- edgeBevel = 0- } = opts;- if (length3 <= 0 || baseWidth <= 0 || thickness <= 0) {- throw new Error("bladeGeo: length, baseWidth, thickness must all be > 0");- }- if (tipLength >= length3) {- throw new Error("bladeGeo: tipLength must be less than length");- }- const hw = baseWidth / 2;- const ht = thickness / 2;- const shoulderY = length3 - tipLength;- const outline = [- [-hw, 0],- [hw, 0],- [hw, shoulderY],- [0, length3],- [-hw, shoulderY]- ];- const n = outline.length;- const positions = [];- const indices = [];- if (edgeBevel <= 0) {- for (const [x, y] of outline)- positions.push(x, y, ht);- for (const [x, y] of outline)- positions.push(x, y, -ht);- for (let i = 1;i < n - 1; i++) {- indices.push(0, i, i + 1);- }- for (let i = 1;i < n - 1; i++) {- indices.push(n, n + i + 1, n + i);- }- for (let i = 0;i < n; i++) {- const j = (i + 1) % n;- const tA = i;- const tB = j;- const bA = n + i;- const bB = n + j;- indices.push(tA, bA, bB);- indices.push(tA, bB, tB);- }- } else {- const zFlat = ht;- const zRidge = ht * (1 - edgeBevel);- const vertsPerRing = 4;- for (const [x, y] of outline) {- positions.push(x, y, zFlat);- positions.push(x, y, zRidge);- positions.push(x, y, -zRidge);- positions.push(x, y, -zFlat);- }- const ringIdx = (i, k) => i * vertsPerRing + k;- for (let i = 1;i < n - 1; i++) {- indices.push(ringIdx(0, 0), ringIdx(i, 0), ringIdx(i + 1, 0));- }- for (let i = 1;i < n - 1; i++) {- indices.push(ringIdx(0, 3), ringIdx(i + 1, 3), ringIdx(i, 3));- }- const layerPairs = [- [0, 1],- [1, 2],- [2, 3],- [3, 0]- ];- for (const [kA, kB] of layerPairs) {- for (let i = 0;i < n; i++) {- const j = (i + 1) % n;- const a = ringIdx(i, kA);- const b = ringIdx(j, kA);- const c = ringIdx(j, kB);- const d = ringIdx(i, kB);- indices.push(a, d, c);- indices.push(a, c, b);- }- }- }- const geo = new THREE16.BufferGeometry;- geo.setAttribute("position", new THREE16.Float32BufferAttribute(positions, 3));- geo.setIndex(indices);- const nonIndexed = geo.toNonIndexed();- nonIndexed.computeVertexNormals();- return nonIndexed;-}-var init_gears = __esm(() => {- init_authoring_diagnostic();-});--// src/ops.ts-import * as THREE17 from "three";-import { LoopSubdivision } from "three-subdivide";-import { mergeVertices as threeMergeVertices } from "three/examples/jsm/utils/BufferGeometryUtils.js";-function arrayLinear(namePrefix, source, count, offset, parent) {- const out = [];- const base = source.position.toArray();- for (let i = 1;i < count; i++) {- const pos = [- base[0] + offset[0] * i,- base[1] + offset[1] * i,- base[2] + offset[2] * i- ];- out.push(createInstance(`${namePrefix}${i}`, source, { position: pos, parent }));- }- return out;-}-function arrayRadial(namePrefix, source, count, axis = "y", parent) {- const out = [];- const basePos = source.position.clone();- const axisVec = axis === "x" ? new THREE17.Vector3(1, 0, 0) : axis === "z" ? new THREE17.Vector3(0, 0, 1) : new THREE17.Vector3(0, 1, 0);- for (let i = 1;i < count; i++) {- const angle = i / count * Math.PI * 2;- const m = new THREE17.Matrix4().makeRotationAxis(axisVec, angle);- const rotated = basePos.clone().applyMatrix4(m);- const eulerDeg = axis === "y" ? [0, angle * 180 / Math.PI, 0] : axis === "x" ? [angle * 180 / Math.PI, 0, 0] : [0, 0, angle * 180 / Math.PI];- out.push(createInstance(`${namePrefix}${i}`, source, {- position: [rotated.x, rotated.y, rotated.z],- rotation: eulerDeg,- parent- }));- }- return out;-}-function mirror(name, source, axis, parent) {- const sourcePos = source.position.toArray();- const pos = [- axis === "x" ? -sourcePos[0] : sourcePos[0],- axis === "y" ? -sourcePos[1] : sourcePos[1],- axis === "z" ? -sourcePos[2] : sourcePos[2]- ];- const scale2 = [- axis === "x" ? -1 : 1,- axis === "y" ? -1 : 1,- axis === "z" ? -1 : 1- ];- return createInstance(name, source, { position: pos, scale: scale2, parent });-}-function mergeVertices(geometry, opts = {}) {- const { tolerance = 0.0001, positionOnly = false } = typeof opts === "number" ? { tolerance: opts } : opts;- if (!positionOnly)- return threeMergeVertices(geometry, tolerance);- const stripped = new THREE17.BufferGeometry;- const pos = geometry.getAttribute("position");- if (!pos)- return geometry;- stripped.setAttribute("position", new THREE17.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));- if (geometry.index) {- stripped.setIndex(new THREE17.BufferAttribute(new Uint32Array(geometry.index.array), 1));- }- return threeMergeVertices(stripped, tolerance);-}-function subdivide(geometry, iterations = 1, opts = {}) {- const { weld = true, preserveUV = false, ...subOpts } = opts;- const input = weld && !preserveUV ? mergeVertices(geometry, { positionOnly: true }) : geometry.clone();- const center = new THREE17.Vector3;- let normalizationScale = 1;- if (preserveUV) {- subOpts.uvSmooth = false;- input.computeBoundingBox();- const extent2 = input.boundingBox.getSize(new THREE17.Vector3);- input.boundingBox.getCenter(center);- const size = Math.max(extent2.x, extent2.y, extent2.z);- normalizationScale = size > 0 ? 1e4 / size : 1;- input.translate(-center.x, -center.y, -center.z).scale(normalizationScale, normalizationScale, normalizationScale);- }- const output = normalizeSurfaceNormals(LoopSubdivision.modify(input, iterations, subOpts));- if (preserveUV)- output.scale(1 / normalizationScale, 1 / normalizationScale, 1 / normalizationScale).translate(center.x, center.y, center.z);- output.deleteAttribute("tangent");- output.computeBoundingBox();- output.computeBoundingSphere();- if (geometry.getAttribute("uv") && !output.getAttribute("uv")) {- output.userData.kilnAttributeWarnings = [- {- code: "SUBDIVIDE_UV_DROPPED",- message: "Position-only subdivision discarded UVs. Use preserveUV: true or unwrap the output."- }- ];- }- if (geometry.userData.kilnCsgProvenance || geometry.userData.kilnRanges) {- delete output.userData.kilnCsgProvenance;- delete output.userData.kilnRanges;- output.userData.kilnAttributeWarnings = [- ...output.userData.kilnAttributeWarnings ?? [],- {- code: "SUBDIVIDE_PROVENANCE_DROPPED",- message: "Subdivision changed triangle topology. Source face/range provenance was discarded rather than guessed."- }- ];- }- return output;-}-function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {- const vectors = points.map((p) => new THREE17.Vector3(p[0], p[1], p[2]));- const curve = new THREE17.CatmullRomCurve3(vectors, closed);- return new THREE17.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);-}-function normalizeSurfaceNormals(geo) {- const normal = geo.getAttribute("normal");- if (!normal)- return geo;- let repaired = false;- for (let i = 0;i < normal.count; i++) {- const x = normal.getX(i);- const y = normal.getY(i);- const z3 = normal.getZ(i);- const len = Math.hypot(x, y, z3);- if (!Number.isFinite(len) || len < 0.000000000001) {- normal.setXYZ(i, 0, 1, 0);- repaired = true;- continue;- }- if (Math.abs(len - 1) <= 0.000001)- continue;- normal.setXYZ(i, x / len, y / len, z3 / len);- repaired = true;- }- if (repaired)- normal.needsUpdate = true;- return geo;-}-function lathe(profile, segments = 12) {- const points2d = profile.map((p) => new THREE17.Vector2(p[0], p[1]));- return normalizeSurfaceNormals(new THREE17.LatheGeometry(points2d, segments));-}-function revolveGeo(profile, options = {}) {- const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;- const points2d = profile.map((p) => new THREE17.Vector2(p[0], p[1]));- const geo = normalizeSurfaceNormals(new THREE17.LatheGeometry(points2d, segments, 0, angle));- const n = new THREE17.Vector3(axis[0], axis[1], axis[2]);- if (n.lengthSq() < 0.000000000001) {- throw new Error(`revolveGeo: axis must be a non-zero vector (got [${axis.join(",")}]).`);- }- n.normalize();- if (n.x !== 0 || n.y !== 1 || n.z !== 0) {- const q = new THREE17.Quaternion().setFromUnitVectors(new THREE17.Vector3(0, 1, 0), n);- geo.applyQuaternion(q);- }- return geo;-}-function pipeAlongPath(points, radius, options = {}) {- const { bendRadius = 0, closed = false, tubularSegments = 32, radialSegments = 8 } = options;- if (points.length < 2) {- throw new Error(`pipeAlongPath: need at least 2 points (got ${points.length}).`);- }- let pathPoints = points;- if (bendRadius > 0 && points.length >= 3) {- const smoothed = [];- smoothed.push(points[0]);- for (let i = 1;i < points.length - 1; i++) {- const prev = new THREE17.Vector3(...points[i - 1]);- const cur = new THREE17.Vector3(...points[i]);- const next = new THREE17.Vector3(...points[i + 1]);- const inDir = cur.clone().sub(prev);- const outDir = next.clone().sub(cur);- const inLen = inDir.length();- const outLen = outDir.length();- const inOffset = Math.min(bendRadius, inLen / 2);- const outOffset = Math.min(bendRadius, outLen / 2);- const before = cur.clone().sub(inDir.clone().normalize().multiplyScalar(inOffset));- const after = cur.clone().add(outDir.clone().normalize().multiplyScalar(outOffset));- smoothed.push([before.x, before.y, before.z]);- smoothed.push([after.x, after.y, after.z]);- }- smoothed.push(points[points.length - 1]);- pathPoints = smoothed;- }- const vectors = pathPoints.map((p) => new THREE17.Vector3(p[0], p[1], p[2]));- const curve = new THREE17.CatmullRomCurve3(vectors, closed);- return new THREE17.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);-}-function bezierCurve(controlPoints, samples = 32) {- const vecs = controlPoints.map((p) => new THREE17.Vector3(p[0], p[1], p[2]));- let curve;- if (vecs.length === 3) {- curve = new THREE17.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);- } else if (vecs.length === 4) {- curve = new THREE17.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);- } else {- throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);- }- return curve.getPoints(samples).map((v) => [v.x, v.y, v.z]);-}-var init_ops = __esm(() => {- init_primitives();-});--// src/geometry.ts-import * as THREE18 from "three";-function finiteArray(values, label, length3) {- const result = Array.from(values);- if (length3 !== undefined && result.length !== length3)- throw new Error(`${label}: expected ${length3} values, got ${result.length}`);- if (!result.every((n) => Number.isFinite(Math.fround(n))))- throw new Error(`${label}: all values must be finite Float32 values`);- return result;-}-function meshGeo(data) {- const positions = finiteArray(data.positions, "meshGeo positions");- if (positions.length < 9 || positions.length % 3)- throw new Error("meshGeo positions: need at least three xyz vertices");- const count = positions.length / 3;- const geometry = new THREE18.BufferGeometry;- geometry.setAttribute("position", new THREE18.Float32BufferAttribute(positions, 3));- if (data.indices) {- const indices = Array.from(data.indices);- if (!indices.length || indices.length % 3)- throw new Error("meshGeo indices: need complete triangles");- if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))- throw new Error("meshGeo index out of bounds or not an integer");- geometry.setIndex(indices);- } else if (count % 3)- throw new Error("meshGeo: non-indexed positions must form complete triangles");- if (data.normals) {- const normals = finiteArray(data.normals, "meshGeo normals", count * 3);- geometry.setAttribute("normal", new THREE18.Float32BufferAttribute(normals, 3));- for (let i = 0;i < count; i++)- if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)- throw new Error("meshGeo normals: zero-length normal");- geometry.normalizeNormals();- } else- geometry.computeVertexNormals();- if (data.uvs)- geometry.setAttribute("uv", new THREE18.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));- if (data.tangents) {- const tangents = finiteArray(data.tangents, "meshGeo tangents", count * 4);- for (let i = 0;i < count; i++) {- if (Math.abs(Math.hypot(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]) - 1) > 0.0001 || Math.abs(tangents[i * 4 + 3]) !== 1)- throw new Error("meshGeo tangents: expected unit xyz and handedness +1 or -1");- }- geometry.setAttribute("tangent", new THREE18.Float32BufferAttribute(tangents, 4));- }- geometry.computeBoundingBox();- geometry.computeBoundingSphere();- return geometry;-}-function geometryDiagnostics(geometry, tolerance = 0.000001) {- if (!Number.isFinite(tolerance) || tolerance <= 0)- throw new Error("geometryDiagnostics tolerance must be positive");- const p = geometry.getAttribute("position");- if (p?.itemSize !== 3)- throw new Error("geometryDiagnostics requires xyz positions");- const result = {- vertices: p.count,- triangles: 0,- boundaryEdges: 0,- nonManifoldEdges: 0,- orientationConflicts: 0,- degenerateTriangles: 0,- invalidIndices: 0,- nonFiniteVertices: 0- };- const ids = [];- const points = new Map;- for (let i = 0;i < p.count; i++) {- const xyz = [p.getX(i), p.getY(i), p.getZ(i)];- if (!xyz.every(Number.isFinite))- result.nonFiniteVertices++;- const key = xyz.map((x) => Math.round(x / tolerance)).join(",");- if (!points.has(key))- points.set(key, points.size);- ids.push(points.get(key));- }- const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);- const edges = new Map;- const a = new THREE18.Vector3, b = new THREE18.Vector3, c = new THREE18.Vector3;- for (let i = 0;i < indices.length; i += 3) {- result.triangles++;- const triangle = indices.slice(i, i + 3);- if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {- result.invalidIndices++;- continue;- }- const [ia, ib, ic] = triangle;- a.fromBufferAttribute(p, ia);- b.fromBufferAttribute(p, ib);- c.fromBufferAttribute(p, ic);- if (b.sub(a).cross(c.sub(a)).lengthSq() <= tolerance ** 4)- result.degenerateTriangles++;- for (const [start, end] of [- [ia, ib],- [ib, ic],- [ic, ia]- ]) {- const u = ids[start], v = ids[end];- if (u === v)- continue;- const key = u < v ? `${u}:${v}` : `${v}:${u}`;- const edge = edges.get(key) ?? { count: 0, direction: 0 };- edge.count++;- edge.direction += u < v ? 1 : -1;- edges.set(key, edge);- }- }- for (const edge of edges.values()) {- if (edge.count === 1)- result.boundaryEdges++;- else if (edge.count > 2)- result.nonManifoldEdges++;- else if (edge.direction !== 0)- result.orientationConflicts++;- }- return result;-}-function parametricSurface(sample, options = {}) {- const {- u = [0, 1],- v = [0, 1],- uSegments: nu = 24,- vSegments: nv = 24,- periodicU = false,- periodicV = false,- orientation = "uv"- } = options;- for (const [name, n] of [- ["uSegments", nu],- ["vSegments", nv]- ])- if (!Number.isSafeInteger(n) || n < 1)- throw new Error(`parametricSurface ${name} must be a positive integer`);- for (const [name, range] of [- ["u", u],- ["v", v]- ])- if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1])- throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);- if (orientation !== "uv" && orientation !== "vu")- throw new Error("parametricSurface orientation must be uv or vu");- const positions = [], uvs = [], indices = [];- for (let j = 0;j <= nv; j++)- for (let i = 0;i <= nu; i++) {- const point = sample(u[0] + (u[1] - u[0]) * i / nu, v[0] + (v[1] - v[0]) * j / nv);- if (point.length !== 3 || !point.every(Number.isFinite))- throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);- positions.push(...point);- uvs.push(i / nu, j / nv);- }- const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);- const find = (i) => {- while (groups[i] !== i)- i = groups[i];- return i;- };- const join2 = (a, b, label) => {- const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);- const scale2 = Math.max(1, ...pa.map(Math.abs), ...pb.map(Math.abs));- if (Math.hypot(...pa.map((x, k) => x - pb[k])) > scale2 * 0.000001)- throw new Error(`parametricSurface ${label}: endpoint positions do not match`);- groups[find(b)] = find(a);- for (let k = 0;k < 3; k++)- positions[b * 3 + k] = positions[a * 3 + k];- };- if (periodicU)- for (let j = 0;j <= nv; j++)- join2(j * (nu + 1), j * (nu + 1) + nu, "periodicU");- if (periodicV)- for (let i = 0;i <= nu; i++)- join2(i, nv * (nu + 1) + i, "periodicV");- for (let j = 0;j < nv; j++)- for (let i = 0;i < nu; i++) {- const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;- indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);- }- const out = meshGeo({ positions, indices, uvs });- if (periodicU || periodicV) {- const normal = out.getAttribute("normal");- const sums = new Map;- for (let i = 0;i < normal.count; i++) {- const id = find(i);- const sum = sums.get(id) ?? new THREE18.Vector3;- sum.add(new THREE18.Vector3().fromBufferAttribute(normal, i));- sums.set(id, sum);- }- for (let i = 0;i < normal.count; i++) {- const n = sums.get(find(i)).clone().normalize();- normal.setXYZ(i, n.x, n.y, n.z);- }- }- return out;-}-function creaseNormals(geometry, options = {}) {- const angle = options.angle ?? 60;- if (!Number.isFinite(angle) || angle < 0 || angle > 180)- throw new Error("creaseNormals angle must be between 0 and 180 degrees");- const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();- const position = out.getAttribute("position");- if (position?.itemSize !== 3 || position.count % 3 !== 0)- throw new Error("creaseNormals requires complete xyz triangles");- out.computeBoundingBox();- const diagonal = out.boundingBox.getSize(new THREE18.Vector3).length();- const tolerance = options.tolerance ?? Math.max(diagonal * 0.00000001, 0.000000000001);- if (!Number.isFinite(tolerance) || tolerance <= 0)- throw new Error("creaseNormals tolerance must be positive and finite");- const adjacent = new Map;- const keys = [];- const faces = [];- for (let i = 0;i < position.count; i += 3) {- const a = new THREE18.Vector3().fromBufferAttribute(position, i);- const b = new THREE18.Vector3().fromBufferAttribute(position, i + 1);- const c = new THREE18.Vector3().fromBufferAttribute(position, i + 2);- const face = b.sub(a).cross(c.sub(a)).normalize();- faces.push(face);- for (let j = i;j < i + 3; j++) {- const point = new THREE18.Vector3().fromBufferAttribute(position, j);- if (![point.x, point.y, point.z].every(Number.isFinite))- throw new Error("creaseNormals positions must be finite");- const key = point.toArray().map((n) => Math.round(n / tolerance)).join(",");- keys.push(key);- const neighbors = adjacent.get(key) ?? new Set;- neighbors.add(i / 3);- adjacent.set(key, neighbors);- }- }- const normals = new Float32Array(position.count * 3);- const threshold = Math.cos(THREE18.MathUtils.degToRad(angle));- for (let i = 0;i < position.count; i++) {- const face = faces[Math.floor(i / 3)], sum = new THREE18.Vector3;- for (const other of adjacent.get(keys[i]))- if (face.dot(faces[other]) >= threshold - 0.000000000001)- sum.add(faces[other]);- sum.normalize().toArray(normals, i * 3);- }- out.setAttribute("normal", new THREE18.BufferAttribute(normals, 3));- out.deleteAttribute("tangent");- out.computeBoundingSphere();- return out;-}-var init_geometry = () => {};--// src/deform.ts-import * as THREE19 from "three";-function geometryFrameMatrix(frame = {}) {- const origin = frame.origin ?? [0, 0, 0], rotation = frame.rotation ?? [0, 0, 0];- if (origin.length !== 3 || rotation.length !== 3 || ![...origin, ...rotation].every(Number.isFinite))- throw new Error("geometry frame requires finite xyz origin and rotation");- return new THREE19.Matrix4().compose(new THREE19.Vector3(...origin), new THREE19.Quaternion().setFromEuler(new THREE19.Euler(...rotation.map(THREE19.MathUtils.degToRad), "XYZ")), new THREE19.Vector3(1, 1, 1));-}-function deform(geometry, options, map) {- const source = geometry.getAttribute("position");- if (source?.itemSize !== 3 || source.count === 0)- throw new Error("deformation requires nonempty xyz positions");- const matrix = geometryFrameMatrix(options.frame), inverse = matrix.clone().invert();- const points = Array.from({ length: source.count }, (_, i) => new THREE19.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));- if (points.some((p) => ![p.x, p.y, p.z].every(Number.isFinite)))- throw new Error("deformation positions must be finite");- let low = Infinity, high = -Infinity;- for (const point of points) {- low = Math.min(low, point.y);- high = Math.max(high, point.y);- }- if (options.interval) {- if (options.interval.length !== 2 || !options.interval.every(Number.isFinite) || options.interval[1] <= options.interval[0])- throw new Error("deformation interval must be finite and increasing");- [low, high] = options.interval;- }- const length3 = high - low;- const out = geometry.clone();- const position = out.getAttribute("position");- for (let i = 0;i < points.length; i++) {- const point = points[i];- const epsilon = Math.max(1, Math.abs(low), Math.abs(high)) * 0.0000001;- if (point.y < low - epsilon || point.y > high + epsilon)- continue;- const t = length3 > epsilon ? THREE19.MathUtils.clamp((point.y - low) / length3, 0, 1) : 0;- const weight = options.falloff?.(t) ?? 1;- if (!Number.isFinite(weight) || weight < 0 || weight > 1)- throw new Error("deformation falloff must return a finite weight between 0 and 1");- const mapped = map(point.clone(), t, low, length3);- if (![mapped.x, mapped.y, mapped.z].every(Number.isFinite))- throw new Error("deformation callback must return finite coordinates");- point.lerp(mapped, weight).applyMatrix4(matrix);- if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))- throw new Error("deformation output must fit finite Float32 coordinates");- position.setXYZ(i, point.x, point.y, point.z);- }- position.needsUpdate = true;- out.deleteAttribute("tangent");- out.computeVertexNormals();- out.computeBoundingBox();- out.computeBoundingSphere();- return out;-}-function twist(geometry, options) {- if (!Number.isFinite(options.angle))- throw new Error("twist angle must be finite degrees");- return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE19.Vector3(0, 1, 0), THREE19.MathUtils.degToRad(options.angle) * t));-}-function bend(geometry, options) {- if (!Number.isFinite(options.angle))- throw new Error("bend angle must be finite degrees");- const angle = THREE19.MathUtils.degToRad(options.angle);- return deform(geometry, options, (p, t, low, length3) => {- if (Math.abs(angle) < 0.0000000001 || length3 === 0)- return p;- const radius = length3 / angle, theta = angle * t;- return new THREE19.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);- });-}-function taper(geometry, options) {- const start = options.startScale ?? [1, 1], end = options.endScale;- if (start.length !== 2 || end.length !== 2 || ![...start, ...end].every((n) => Number.isFinite(n) && n > 0))- throw new Error("taper scales must be two finite positive values");- return deform(geometry, options, (p, t) => p.set(p.x * THREE19.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE19.MathUtils.lerp(start[1], end[1], t)));-}-function displace(geometry, offset, options = {}) {- return deform(geometry, options, (p, t) => {- const delta = offset([p.x, p.y, p.z], t);- if (delta.length !== 3 || !delta.every(Number.isFinite))- throw new Error("displace callback must return three finite offsets");- return p.add(new THREE19.Vector3(...delta));- });-}-var init_deform = () => {};--// src/sweep.ts-import * as THREE20 from "three";-function profilePoints(profile) {- if (profile.length < 3 || profile.some((p) => p.length !== 2 || !p.every(Number.isFinite)))- throw new Error("profile requires at least three finite xy points");- const points = profile.map((p) => new THREE20.Vector2(...p));- if (points[0].distanceTo(points[points.length - 1]) < 0.0000000001)- points.pop();- if (points.length < 3)- throw new Error("profile requires three distinct points");- const cross3 = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);- for (let i = 0;i < points.length; i++) {- const a = points[i], b = points[(i + 1) % points.length];- if (a.distanceToSquared(b) < 0.00000000000000000001)- throw new Error("profile has duplicate adjacent points");- for (let j = i + 1;j < points.length; j++) {- if (j === i + 1 || i === 0 && j === points.length - 1)- continue;- const c = points[j], d = points[(j + 1) % points.length];- if (cross3(a, b, c) * cross3(a, b, d) <= 0 && cross3(c, d, a) * cross3(c, d, b) <= 0 && Math.max(Math.min(a.x, b.x), Math.min(c.x, d.x)) <= Math.min(Math.max(a.x, b.x), Math.max(c.x, d.x)) + 0.0000000001 && Math.max(Math.min(a.y, b.y), Math.min(c.y, d.y)) <= Math.min(Math.max(a.y, b.y), Math.max(c.y, d.y)) + 0.0000000001)- throw new Error("profile self-intersects or touches itself");- }- }- const area = THREE20.ShapeUtils.area(points);- if (Math.abs(area) < 0.000000000001)- throw new Error("profile area must be nonzero");- if (area < 0)- points.splice(1, points.length - 1, ...points.slice(1).reverse());- return points;-}-function buildLoft(rings, profiles, closed, cap) {- const n = rings[0].length, positions = [], uvs = [], indices = [];- const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE20.Vector3).multiplyScalar(1 / n));- const lengths = [0];- for (let i = 1;i < centers.length; i++)- lengths.push(lengths[i - 1] + centers[i].distanceTo(centers[i - 1]));- const total = lengths[lengths.length - 1];- if (total < 0.0000000001)- throw new Error("loft section centers must progress along a nonzero path");- for (let i = 0;i < rings.length; i++) {- const ring = rings[i], distance = [0];- for (let j = 1;j <= n; j++)- distance.push(distance[j - 1] + ring[j % n].distanceTo(ring[j - 1]));- for (let j = 0;j <= n; j++) {- positions.push(...ring[j % n].toArray());- uvs.push(distance[j] / distance[n], lengths[i] / total);- }- }- for (let i = 0;i < rings.length - 1; i++)- for (let j = 0;j < n; j++) {- const a = i * (n + 1) + j, b = a + 1, c = a + n + 1, d = c + 1;- indices.push(a, c, b, b, c, d);- }- if (cap && !closed)- for (const station of [0, rings.length - 1]) {- const ring = rings[station], profile = profiles[station];- const start = positions.length / 3;- const bounds = new THREE20.Box2().setFromPoints(profile);- const size = bounds.getSize(new THREE20.Vector2);- for (let j = 0;j < n; j++) {- positions.push(...ring[j].toArray());- uvs.push((profile[j].x - bounds.min.x) / (size.x || 1), (profile[j].y - bounds.min.y) / (size.y || 1));- }- for (const tri of THREE20.ShapeUtils.triangulateShape(profile, [])) {- if (station === 0)- indices.push(...tri.map((j) => start + j));- else- indices.push(...tri.toReversed().map((j) => start + j));- }- }- const out = meshGeo({ positions, indices, uvs });- const normal = out.getAttribute("normal");- for (let i = 0;i < rings.length; i++) {- const a = i * (n + 1), b = a + n;- const sum = new THREE20.Vector3().fromBufferAttribute(normal, a).add(new THREE20.Vector3().fromBufferAttribute(normal, b)).normalize();- normal.setXYZ(a, sum.x, sum.y, sum.z);- normal.setXYZ(b, sum.x, sum.y, sum.z);- }- if (closed)- for (let j = 0;j <= n; j++) {- const a = j, b = (rings.length - 1) * (n + 1) + j;- const sum = new THREE20.Vector3().fromBufferAttribute(normal, a).add(new THREE20.Vector3().fromBufferAttribute(normal, b)).normalize();- normal.setXYZ(a, sum.x, sum.y, sum.z);- normal.setXYZ(b, sum.x, sum.y, sum.z);- }- return out;-}-function loftProfiles(sections, options = {}) {- if (sections.length < 2)- throw new Error("loftProfiles needs at least two sections");- const profiles = sections.map((section) => profilePoints(section.profile));- if (profiles.some((p) => p.length !== profiles[0].length))- throw new Error("loftProfiles sections must have the same point count and correspondence");- const rings = sections.map((section, i) => {- const frame = geometryFrameMatrix(section.frame);- return profiles[i].map((p) => new THREE20.Vector3(p.x, 0, p.y).applyMatrix4(frame));- });- const out = buildLoft(rings, profiles, false, options.cap ?? true);- out.userData.kilnGeometryWarnings = [- {- code: "LOFT_SELF_INTERSECTION_UNCHECKED",- message: "Corresponding profiles are connected directly. Caps and closed boundaries do not prove the loft is free of self-intersections."- }- ];- return out;-}-function sweepProfile(profile, path, options = {}) {- const points = profilePoints(profile), closed = options.closed ?? false, twist2 = options.twist ?? 0;- if (!Number.isFinite(twist2))- throw new Error("sweepProfile twist must be finite degrees");- if (closed && Math.abs(twist2 / 360 - Math.round(twist2 / 360)) > 0.00000001)- throw new Error("closed sweep twist must be a multiple of 360 degrees");- if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))- throw new Error("sweepProfile requires finite path points (two open or three closed)");- const stations = path.map((p) => new THREE20.Vector3(...p));- if (closed && stations[0].distanceTo(stations[stations.length - 1]) < 0.0000000001)- throw new Error("closed sweep path should omit its repeated endpoint");- const segments = [];- for (let i = 0;i < stations.length - (closed ? 0 : 1); i++) {- const direction = stations[(i + 1) % stations.length].clone().sub(stations[i]);- if (direction.length() < 0.0000000001)- throw new Error("sweepProfile path stations must be distinct");- segments.push(direction.normalize());- }- const warnings = [];- const radius = Math.max(...points.map((p) => p.length()));- const tangents = stations.map((_, i) => {- if (!closed && i === 0)- return segments[0].clone();- if (!closed && i === stations.length - 1)- return segments[segments.length - 1].clone();- const incoming = segments[(i - 1 + segments.length) % segments.length], outgoing = segments[i];- if (incoming.dot(outgoing) < -0.9999)- throw new Error("sweepProfile path has a reversal; split it into separate sweeps");- const angle = incoming.angleTo(outgoing);- const distance = Math.min(stations[i].distanceTo(stations[(i - 1 + stations.length) % stations.length]), stations[i].distanceTo(stations[(i + 1) % stations.length]));- if (radius * Math.tan(angle / 2) >= distance * 0.5)- warnings.push({- code: "SWEEP_TIGHT_TURN",- message: `Path station ${i} turns tightly relative to the profile; reduce its size or widen the turn. Self-intersection is possible.`- });- return incoming.clone().add(outgoing).normalize();- });- const scales = stations.map((_, i) => {- const scale2 = typeof options.scale === "number" ? [options.scale, options.scale] : options.scale?.[i] ?? [1, 1];- if (scale2.length !== 2 || !scale2.every((n) => Number.isFinite(n) && n > 0))- throw new Error("sweepProfile scale requires positive finite pairs");- return scale2;- });- if (Array.isArray(options.scale) && options.scale.length !== stations.length)- throw new Error("sweepProfile scale needs one pair per path station");- const up = options.up ? new THREE20.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE20.Vector3(0, 0, 1) : new THREE20.Vector3(1, 0, 0);- if (![up.x, up.y, up.z].every(Number.isFinite) || up.lengthSq() < 0.00000000000000000001)- throw new Error("sweepProfile up must be a finite nonzero vector");- let z3 = up.clone().addScaledVector(tangents[0], -up.dot(tangents[0]));- if (z3.lengthSq() < 0.000000000001)- throw new Error("sweepProfile up must not be parallel to the first path tangent");- z3.normalize();- const normals = [z3.clone()];- if (closed) {- stations.push(stations[0].clone());- tangents.push(tangents[0].clone());- scales.push(scales[0]);- }- const distances = [0];- for (let i = 1;i < stations.length; i++) {- z3 = z3.clone().applyQuaternion(new THREE20.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));- normals.push(z3);- distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));- }- const total = distances[distances.length - 1];- let correction = 0;- if (closed)- correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));- const rings = stations.map((station, i) => {- const tangent = tangents[i], t = distances[i] / total;- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE20.MathUtils.degToRad(twist2)) * t);- const axisX = tangent.clone().cross(axisZ).normalize(), scale2 = scales[i];- return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale2[0]).addScaledVector(axisZ, p.y * scale2[1]));- });- if (closed)- rings[rings.length - 1] = rings[0].map((p) => p.clone());- const out = buildLoft(rings, rings.map(() => points), closed, options.cap ?? true);- warnings.push({- code: "SWEEP_SELF_INTERSECTION_UNCHECKED",- message: "Transported frames and caps do not prove a sweep is free of self-intersections. Review tight turns and nearby path segments."- });- out.userData.kilnGeometryWarnings = warnings;- return out;-}-var init_sweep = __esm(() => {- init_geometry();- init_deform();-});--// src/solids.ts-import * as THREE21 from "three";-async function getManifoldModule() {- if (_module)- return _module;- if (_initPromise)- return _initPromise;- _initPromise = (async () => {- const mod = await import("manifold-3d");- const m = await mod.default();- m.setup();- _module = m;- return m;- })();- return _initPromise;-}-function sourceSpans(mesh, count) {- const prior = mesh.geometry.userData.kilnCsgProvenance;- if (prior?.runs?.length)- return prior.runs.map((r) => ({- start: r.start * 3,- count: r.count * 3,- materialIndex: r.materialIndex,- name: r.sourceName- }));- const ranges = mesh.geometry.userData.kilnRanges;- const name = mesh.name || ranges?.[0]?.name || "unnamed";- return Array.isArray(mesh.material) ? mesh.geometry.groups.map((g) => ({- start: g.start,- count: g.count,- materialIndex: g.materialIndex ?? 0,- name- })) : [{ start: 0, count, materialIndex: 0, name }];-}-function threeToManifold(src, mod, label, context) {- src.updateWorldMatrix(true, true);- const properties = [], indices = [], runs = [], originals = [], faceIds = [];- let vertexOffset = 0, meshCount = 0;- const stride = context.preserve ? 5 : 3;- src.traverse((child) => {- const mesh2 = child;- if (!mesh2.isMesh)- return;- const geometry = mesh2.geometry, position = geometry.getAttribute("position");- if (!position)- return;- meshCount++;- const index = geometry.index, count = index?.count ?? position.count;- if (count % 3 !== 0)- throw new Error(`CSG ${label}: mesh "${mesh2.name || "(unnamed)"}" has ${count} ${index ? "indices" : "vertices"}, which is not a whole number of triangles. Every CSG input must be a triangle mesh.`);- if (position.itemSize !== 3)- throw new Error(`CSG ${label}: positions must have three components`);- const uv = geometry.getAttribute("uv");- if (context.preserve && uv && (uv.itemSize !== 2 || uv.count !== position.count))- throw new Error(`CSG ${label}: uv must have two components per vertex`);- if (context.preserve) {- if (uv)- context.anyUV = true;- else- context.missingUV.add(mesh2.name || label);- }- const point = new THREE21.Vector3;- for (let i = 0;i < position.count; i++) {- point.fromBufferAttribute(position, i).applyMatrix4(mesh2.matrixWorld);- if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))- throw new Error(`CSG ${label}: transformed positions must be finite Float32 coordinates`);- properties.push(point.x, point.y, point.z);- if (context.preserve) {- const u = uv?.getX(i) ?? 0, v = uv?.getY(i) ?? 0;- if (!Number.isFinite(u) || !Number.isFinite(v))- throw new Error(`CSG ${label}: UVs must be finite`);- properties.push(u, v);- }- }- const materials = Array.isArray(mesh2.material) ? mesh2.material : [mesh2.material];- const spans = sourceSpans(mesh2, count).sort((a, b) => a.start - b.start);- let covered = 0;- for (const span of spans) {- if (!Number.isInteger(span.start) || !Number.isInteger(span.count) || span.start !== covered || span.count <= 0 || span.count % 3 || span.start % 3 || span.start + span.count > count || !materials[span.materialIndex])- throw new Error(`CSG ${label}: material/source groups must cover triangles exactly once with valid materials`);- const id = mod.Manifold.reserveIDs(1);- context.sources.set(id, { name: span.name, material: materials[span.materialIndex] });- runs.push(indices.length);- originals.push(id);- for (let i = span.start;i < span.start + span.count; i += 3) {- const triangle = [- index?.getX(i) ?? i,- index?.getX(i + 1) ?? i + 1,- index?.getX(i + 2) ?? i + 2- ];- if (triangle.some((j) => !Number.isInteger(j) || j < 0 || j >= position.count))- throw new Error(`CSG ${label}: index outside positions`);- if (mesh2.matrixWorld.determinant() < 0)- [triangle[1], triangle[2]] = [triangle[2], triangle[1]];- indices.push(...triangle.map((j) => j + vertexOffset));- const prior = geometry.userData.kilnCsgProvenance;- faceIds.push(prior?.faceIds?.[i / 3] ?? i / 3);- }- covered += span.count;- }- if (covered !== count)- throw new Error(`CSG ${label}: material/source groups do not cover every triangle`);- vertexOffset += position.count;- });- if (!indices.length)- throw new Error(`CSG ${label}: contributes no triangles${meshCount === 0 ? " (nothing in it is a mesh — an empty Group, or a part that was never added to it)" : " (its meshes have no geometry)"}. Every CSG operand must be a solid with triangles.`);- runs.push(indices.length);- const mesh = new mod.Mesh({- numProp: stride,- vertProperties: new Float32Array(properties),- triVerts: new Uint32Array(indices),- runIndex: new Uint32Array(runs),- runOriginalID: new Uint32Array(originals),- ...context.preserve ? { faceID: new Uint32Array(faceIds) } : {}- });- mesh.merge();- return mod.Manifold.ofMesh(mesh);-}-function assertNonEmptyResult(m, op, hint) {- if (m.numTri() === 0)- throw new Error(`${op}: the result is empty (zero triangles). ${hint}`);-}-function manifoldToGeometry(m, opts = {}) {- const mesh = m.getMesh(), positions = new Float32Array(mesh.vertProperties.length / mesh.numProp * 3);- const uvs = opts.preserveUV && mesh.numProp >= 5 ? new Float32Array(positions.length / 3 * 2) : undefined;- for (let i = 0, v = 0;i < mesh.vertProperties.length; i += mesh.numProp, v++) {- positions.set(mesh.vertProperties.subarray(i, i + 3), v * 3);- if (uvs)- uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);- }- const geometry = new THREE21.BufferGeometry;- geometry.setAttribute("position", new THREE21.BufferAttribute(positions, 3));- geometry.setIndex(new THREE21.BufferAttribute(new Uint32Array(mesh.triVerts), 1));- if (uvs)- geometry.setAttribute("uv", new THREE21.BufferAttribute(uvs, 2));- const out = opts.smooth ? geometry : geometry.toNonIndexed();- out.computeVertexNormals();- if (opts.smooth && uvs) {- const cornerNormals = creaseNormals(out, { angle: 180 }).getAttribute("normal");- const normal = out.getAttribute("normal");- for (let corner = 0;corner < out.index.count; corner++) {- normal.setXYZ(out.index.getX(corner), cornerNormals.getX(corner), cornerNormals.getY(corner), cornerNormals.getZ(corner));- }- }- out.computeBoundingBox();- out.computeBoundingSphere();- return out;-}-function firstMaterial(src) {- let material;- src.traverse((child) => {- const mesh = child;- if (!material && mesh.isMesh)- material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;- });- return material ?? new THREE21.MeshStandardMaterial;-}-function outputMesh(result, name, parts, opts, context, isHull) {- const geometry = manifoldToGeometry(result, {- smooth: opts.smooth,- preserveUV: context.preserve && context.anyUV && !isHull- });- const native = result.getMesh(), materials = [], sourceRuns = [];- if (!isHull)- for (let i = 0;i < native.runOriginalID.length; i++) {- const source = context.sources.get(native.runOriginalID[i]);- const start = native.runIndex[i] / 3, count = (native.runIndex[i + 1] - native.runIndex[i]) / 3;- if (!count)- continue;- const material = source?.material ?? firstMaterial(parts[0]);- let materialIndex = context.preserve ? materials.indexOf(material) : 0;- if (context.preserve && materialIndex < 0) {- materialIndex = materials.length;- materials.push(material);- }- sourceRuns.push({- sourceName: source?.name ?? "unknown",- start,- count,- materialIndex,- backside: !!((native.runFlags?.[i] ?? 0) & 1)- });- if (context.preserve)- geometry.addGroup(start * 3, count * 3, materialIndex);- }- const total = (geometry.index?.count ?? geometry.getAttribute("position").count) / 3;- geometry.userData.kilnCsgProvenance = {- schemaVersion: 1,- runs: sourceRuns,- faceIds: isHull ? [] : Array.from(native.faceID),- unknownTriangles: isHull ? total : sourceRuns.filter((r) => r.sourceName === "unknown").reduce((sum, r) => sum + r.count, 0)- };- geometry.userData.kilnRanges = sourceRuns.length ? sourceRuns.map((r) => ({- name: r.sourceName,- start: r.start,- count: r.count,- certainty: r.sourceName === "unknown" ? "unknown" : "source-run"- })) : [{ name: "generated hull", start: 0, count: total, certainty: "unknown" }];- const warnings = [];- if (context.preserve && context.anyUV && context.missingUV.size)- warnings.push({- code: "CSG_UV_MISSING",- message: `UVs were absent on ${[...context.missingUV].join(", ")}; those surfaces use zero UVs. Unwrap the result if they need a texture.`- });- if (isHull && context.preserve)- warnings.push({- code: "HULL_ATTRIBUTES_GENERATED",- message: "A convex hull creates new faces. Source UVs and material boundaries cannot be assigned faithfully; output uses the first material and no UVs."- });- geometry.userData.kilnAttributeWarnings = warnings;- const output = new THREE21.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));- output.name = `Mesh_${name}`;- return output;-}-function splitPartsAndOpts(items) {- const last = items[items.length - 1];- if (last && !last.isObject3D)- return { parts: items.slice(0, -1), opts: last };- return { parts: items, opts: {} };-}-async function runBoolean(op, name, parts, opts) {- const mod = await getManifoldModule(), context = {- preserve: opts.preserveAttributes ?? false,- sources: new Map,- anyUV: false,- missingUV: new Set- };- const owned = new Set;- const track = (m) => {- owned.add(m);- return m;- };- try {- const operands = parts.map((p, i) => track(threeToManifold(p, mod, op === "boolDiff" ? i === 0 ? "boolDiff body" : `boolDiff cutter ${i}` : op === "boolIntersect" ? `boolIntersect operand ${i === 0 ? "a" : "b"}` : `${op} operand ${i + 1}`, context)));- let result;- if (op === "boolUnion")- result = track(mod.Manifold.union(operands));- else if (op === "boolDiff") {- const cutters = operands.length === 2 ? operands[1] : track(mod.Manifold.union(operands.slice(1)));- result = track(operands[0].subtract(cutters));- } else if (op === "boolIntersect")- result = track(operands[0].intersect(operands[1]));- else- result = track(operands.length === 1 ? operands[0].hull() : mod.Manifold.hull(operands));- const hint = op === "boolDiff" ? "The cutters removed the entire body — check their size and position, or subtract fewer of them." : op === "boolIntersect" ? "The two operands do not overlap — position them so their volumes actually intersect." : op === "hull" ? "The inputs are coplanar or collinear, so they enclose no volume." : "Every operand was empty after merging.";- assertNonEmptyResult(result, op, hint);- return outputMesh(result, name, parts, { ...opts, smooth: opts.smooth ?? op === "hull" }, context, op === "hull");- } finally {- for (const ownedManifold of owned)- ownedManifold.delete();- }-}-async function boolUnion(name, ...items) {- const { parts, opts } = splitPartsAndOpts(items);- if (parts.length < 2)- throw new Error("boolUnion requires at least two parts");- return runBoolean("boolUnion", name, parts, opts);-}-async function boolDiff(name, body, ...items) {- const { parts, opts } = splitPartsAndOpts(items);- if (parts.length < 1)- throw new Error("boolDiff requires at least one cutter");- return runBoolean("boolDiff", name, [body, ...parts], opts);-}-async function boolIntersect(name, a, b, opts = {}) {- return runBoolean("boolIntersect", name, [a, b], opts);-}-async function hull(name, ...items) {- const { parts, opts } = splitPartsAndOpts(items);- if (parts.length < 1)- throw new Error("hull requires at least one part");- return runBoolean("hull", name, parts, opts);-}-var _module = null, _initPromise = null;-var init_solids = __esm(() => {- init_geometry();-});--// src/implicit.ts-async function implicitSurface(sample, options) {- const {- bounds,- edgeLength,- maxCells = 1e6,- maxEvaluations = 8000000,- level = 0,- tolerance = -1,- smooth = true- } = options;- if (bounds?.min.length !== 3 || bounds.max.length !== 3 || ![...bounds.min, ...bounds.max].every(Number.isFinite) || bounds.min.some((v, i) => v >= bounds.max[i]))- throw new Error("implicitSurface bounds must be finite and increasing on every axis");- if (!Number.isFinite(edgeLength) || edgeLength <= 0)- throw new Error("implicitSurface edgeLength must be positive and finite");- if (!Number.isSafeInteger(maxCells) || maxCells < 1 || !Number.isSafeInteger(maxEvaluations) || maxEvaluations < 1)- throw new Error("implicitSurface maxCells and maxEvaluations must be positive safe integers");- if (!Number.isFinite(level) || !Number.isFinite(tolerance) || tolerance !== -1 && tolerance <= 0)- throw new Error("implicitSurface level must be finite; tolerance must be -1 or positive");- const estimatedGridCells = bounds.min.reduce((product, min, i) => product * Math.ceil((bounds.max[i] - min) / edgeLength), 1);- if (!Number.isSafeInteger(estimatedGridCells) || estimatedGridCells > maxCells)- throw new Error(`implicitSurface estimated grid ${estimatedGridCells} exceeds maxCells ${maxCells}; increase edgeLength or narrow bounds`);- const mod = await getManifoldModule();- let evaluations = 0;- const solid = mod.Manifold.levelSet((point) => {- evaluations++;- if (evaluations > maxEvaluations)- throw new Error(`implicitSurface exceeded maxEvaluations ${maxEvaluations}`);- const value = sample([point[0], point[1], point[2]]);- if (!Number.isFinite(value))- throw new Error("implicitSurface callback must return a finite number");- return value;- }, { min: [...bounds.min], max: [...bounds.max] }, edgeLength, level, tolerance);- try {- if (solid.numTri() === 0)- throw new Error("implicitSurface result is empty; the field does not enclose a positive-inside region in these bounds");- const out = manifoldToGeometry(solid, { smooth });- out.userData.kilnImplicit = {- schemaVersion: 1,- experimental: true,- edgeLength,- estimatedGridCells,- evaluations,- maxCells,- maxEvaluations- };- out.userData.kilnGeometryWarnings = [- {- code: "EXPERIMENTAL_IMPLICIT_SURFACE",- message: "Implicit sampling is resolution-dependent and produces geometry without UVs. Review thin features and bounds; closed topology is not a claim of CAD accuracy."- }- ];- return out;- } finally {- solid.delete();- }-}-var init_implicit = __esm(() => {- init_solids();-});--// src/profile.ts-function assertFiniteProfile(profile, label) {- if (!Array.isArray(profile) || profile.length < 3) {- throw new Error(`${label}: need at least 3 points to form a closed outline.`);- }- for (let i = 0;i < profile.length; i++) {- const p = profile[i];- if (!Array.isArray(p) || p.length < 2 || !Number.isFinite(p[0]) || !Number.isFinite(p[1])) {- throw new Error(`${label}: point ${i} is not a finite [x, y] pair (got ${JSON.stringify(p)}).`);- }- }-}-function assertPositive(value, label) {- if (!Number.isFinite(value) || value <= 0) {- throw new Error(`${label} must be a positive number (got ${value}).`);- }-}-function orientSweep(geo, axis) {- if (axis === "y")- geo.rotateX(-Math.PI / 2);- else if (axis === "x")- geo.rotateY(Math.PI / 2);- else if (axis !== "z")- throw new Error(`axis must be 'x', 'y', or 'z' (got ${String(axis)}).`);- return geo;-}-function bevelCrossSection(cs, bevel, style, segments, label) {- const join2 = JOIN_FOR_STYLE[style];- if (!join2) {- throw new Error(`${label}: bevelStyle must be 'round' or 'chamfer' (got ${String(style)}).`);- }- const eroded = cs.offset(-bevel, join2, 2, segments);- if (eroded.isEmpty()) {- eroded.delete();- throw new Error(`${label}: bevel ${bevel} is too large for this profile — eroding by it leaves nothing. ` + `Use a bevel smaller than half the narrowest part of the outline.`);- }- const dilated = eroded.offset(2 * bevel, join2, 2, segments);- const out = dilated.offset(-bevel, join2, 2, segments);- eroded.delete();- dilated.delete();- return out;-}-function normalizeTaper(taper2) {- if (taper2 === undefined)- return [1, 1];- if (typeof taper2 === "number") {- if (!Number.isFinite(taper2) || taper2 < 0) {- throw new Error(`taper must be a finite number >= 0 (got ${taper2}).`);- }- return [taper2, taper2];- }- if (!Array.isArray(taper2) || taper2.length !== 2 || !taper2.every((v) => Number.isFinite(v) && v >= 0)) {- throw new Error(`taper must be a number or [x, y] pair of numbers >= 0 (got ${JSON.stringify(taper2)}).`);- }- return [taper2[0], taper2[1]];-}-async function extrudeProfile(profile, options = {}) {- assertFiniteProfile(profile, "extrudeProfile");- const {- depth = 1,- holes = [],- bevel = 0,- bevelStyle = "round",- segments = 12,- twist: twist2 = 0,- taper: taper2,- divisions,- axis = "y",- center = true,- smooth = false- } = options;- assertPositive(depth, "extrudeProfile: depth");- if (bevel < 0)- throw new Error(`extrudeProfile: bevel must be >= 0 (got ${bevel}).`);- for (let i = 0;i < holes.length; i++) {- assertFiniteProfile(holes[i], `extrudeProfile: holes[${i}]`);- }- const mod = await getManifoldModule();- const { CrossSection: CS } = mod;- const disposable = [];- const track = (cs) => {- disposable.push(cs);- return cs;- };- try {- let section = track(new CS([profile], "NonZero"));- if (holes.length > 0) {- const holeSections = holes.map((h) => track(new CS([h], "NonZero")));- section = track(CS.difference(section, CS.union(holeSections)));- if (section.isEmpty()) {- throw new Error("extrudeProfile: the holes consume the whole profile — nothing left to extrude.");- }- }- if (bevel > 0) {- section = track(bevelCrossSection(section, bevel, bevelStyle, segments, "extrudeProfile"));- }- const nDivisions = divisions ?? (twist2 !== 0 ? 16 : 1);- const solid = section.extrude(depth, nDivisions, twist2, normalizeTaper(taper2), center);- try {- return orientSweep(manifoldToGeometry(solid, { smooth }), axis);- } finally {- solid.delete();- }- } finally {- for (const cs of disposable)- cs.delete();- }-}-async function revolveProfile(profile, options = {}) {- assertFiniteProfile(profile, "revolveProfile");- const {- segments = 24,- angle = 360,- bevel = 0,- bevelStyle = "round",- bevelSegments = 12,- axis = "y",- smooth = true- } = options;- if (bevel < 0)- throw new Error(`revolveProfile: bevel must be >= 0 (got ${bevel}).`);- if (!Number.isFinite(angle) || angle <= 0 || angle > 360) {- throw new Error(`revolveProfile: angle must be in (0, 360] degrees (got ${angle}).`);- }- const mod = await getManifoldModule();- const { CrossSection: CS } = mod;- const disposable = [];- try {- let section = new CS([profile], "NonZero");- disposable.push(section);- if (bevel > 0) {- section = bevelCrossSection(section, bevel, bevelStyle, bevelSegments, "revolveProfile");- disposable.push(section);- }- const solid = section.revolve(segments, angle);- try {- return orientSweep(manifoldToGeometry(solid, { smooth }), axis);- } finally {- solid.delete();- }- } finally {- for (const cs of disposable)- cs.delete();- }-}-async function roundedBoxGeo(width, height, depth, radius, options = {}) {- assertPositive(width, "roundedBoxGeo: width");- assertPositive(height, "roundedBoxGeo: height");- assertPositive(depth, "roundedBoxGeo: depth");- assertPositive(radius, "roundedBoxGeo: radius");- const { style = "round", segments = 12, smooth } = options;- const smallest = Math.min(width, height, depth);- if (radius >= smallest / 2) {- throw new AuthoringDiagnosticError("ROUNDED_BOX_RADIUS");- }- const mod = await getManifoldModule();- const ManifoldCls = mod.Manifold;- const parts = [];- try {- let solid;- if (style === "round") {- const corners = [];- for (const sx of [-1, 1]) {- for (const sy of [-1, 1]) {- for (const sz of [-1, 1]) {- const s = ManifoldCls.sphere(radius, segments).translate([- sx * (width - 2 * radius) / 2,- sy * (height - 2 * radius) / 2,- sz * (depth - 2 * radius) / 2- ]);- parts.push(s);- corners.push(s);- }- }- }- solid = ManifoldCls.hull(corners);- } else if (style === "chamfer") {- const boxes = [- ManifoldCls.cube([width, height - 2 * radius, depth - 2 * radius], true),- ManifoldCls.cube([width - 2 * radius, height, depth - 2 * radius], true),- ManifoldCls.cube([width - 2 * radius, height - 2 * radius, depth], true)- ];- parts.push(...boxes);- solid = ManifoldCls.hull(boxes);- } else {- throw new Error(`roundedBoxGeo: style must be 'round' or 'chamfer' (got ${String(style)}).`);- }- try {- return manifoldToGeometry(solid, { smooth: smooth ?? style === "round" });- } finally {- solid.delete();- }- } finally {- for (const p of parts)- p.delete();- }-}-function circleProfile(radius, segments = 24, center = [0, 0]) {- assertPositive(radius, "circleProfile: radius");- if (!Number.isInteger(segments) || segments < 3) {- throw new Error(`circleProfile: segments must be an integer >= 3 (got ${segments}).`);- }- const out = [];- for (let i = 0;i < segments; i++) {- const t = i / segments * Math.PI * 2;- out.push([center[0] + Math.cos(t) * radius, center[1] + Math.sin(t) * radius]);- }- return out;-}-var JOIN_FOR_STYLE;-var init_profile = __esm(() => {- init_solids();- init_authoring_diagnostic();- JOIN_FOR_STYLE = {- round: "Round",- chamfer: "Square"- };-});--// src/textures.ts-import * as THREE22 from "three";-async function loadTexture(source, opts = {}) {- let bytes;- if (typeof source === "string") {- const fs = await import("node:fs");- const path = await import("node:path");- const abs = path.isAbsolute(source) ? source : path.resolve(source);- bytes = new Uint8Array(fs.readFileSync(abs));- } else if (typeof Buffer !== "undefined" && Buffer.isBuffer(source)) {- bytes = new Uint8Array(source);- } else {- bytes = source;- }- const mime = sniffMime(bytes);- const sharp = (await import("sharp")).default;- const img = sharp(bytes);- const meta = await img.metadata();- const { data } = await img.ensureAlpha().raw({ depth: "uchar" }).toBuffer({ resolveWithObject: true });- if (!meta.width || !meta.height) {- throw new Error("loadTexture: could not read image dimensions");- }- const tex = new THREE22.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE22.RGBAFormat, THREE22.UnsignedByteType);- const usage = opts.usage ?? "albedo";- const colorSpace = usage === "albedo" || usage === "emissive" ? "srgb" : "linear";- let hasAlpha = false;- for (let offset = 3;offset < data.length; offset += 4) {- if ((data[offset] ?? 255) < 255) {- hasAlpha = true;- break;- }- }- tex.colorSpace = colorSpace === "srgb" ? THREE22.SRGBColorSpace : THREE22.NoColorSpace;- if (opts.name)- tex.name = opts.name;- tex.needsUpdate = true;- tex.wrapS = THREE22.RepeatWrapping;- tex.wrapT = THREE22.RepeatWrapping;- tex.minFilter = THREE22.LinearMipmapLinearFilter;- tex.magFilter = THREE22.LinearFilter;- tex.generateMipmaps = true;- tex.userData["encoded"] = {- mime,- bytes- };- tex.userData["kilnTexture"] = {- usage,- colorSpace,- width: meta.width,- height: meta.height,- hasAlpha- };- return tex;-}-function sniffMime(bytes) {- if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {- return "image/png";- }- if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {- return "image/jpeg";- }- if (bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80) {- return "image/webp";- }- return "image/png";-}-function textureMetadata(texture) {- return texture.userData["kilnTexture"];-}-function requireTextureUsage(texture, usage) {- const meta = textureMetadata(texture);- if (meta && meta.usage !== usage) {- throw new TypeError(`Texture ${JSON.stringify(texture.name || "(unnamed)")} was loaded for ${meta.usage}, not ${usage}.`);- }- texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE22.SRGBColorSpace : THREE22.NoColorSpace;-}-function pbrMaterial(opts = {}) {- const mat = new THREE22.MeshStandardMaterial;- const isTex = (v) => !!v?.isTexture;- if (isTex(opts.albedo)) {- requireTextureUsage(opts.albedo, "albedo");- mat.map = opts.albedo;- mat.color = new THREE22.Color(16777215);- } else if (opts.albedo !== undefined) {- mat.color = new THREE22.Color(opts.albedo);- }- if (opts.normal) {- requireTextureUsage(opts.normal, "normal");- mat.normalMap = opts.normal;- }- const roughnessTexture = isTex(opts.roughness) ? opts.roughness : undefined;- const metalnessTexture = isTex(opts.metalness) ? opts.metalness : undefined;- if (opts.metallicRoughness && (roughnessTexture || metalnessTexture)) {- throw new TypeError("Use metallicRoughness for the packed G/B map; do not also pass texture-valued roughness/metalness.");- }- if (roughnessTexture && metalnessTexture && roughnessTexture !== metalnessTexture) {- throw new TypeError("Separate roughness and metalness textures are ambiguous in glTF. Pack G=roughness/B=metalness and pass metallicRoughness.");- }- if (roughnessTexture && !metalnessTexture || !roughnessTexture && metalnessTexture) {- throw new TypeError("A texture-valued roughness or metalness must be the same packed G/B texture in both slots, or use metallicRoughness.");- }- const packedMr = opts.metallicRoughness ?? roughnessTexture;- if (packedMr) {- requireTextureUsage(packedMr, "metallicRoughness");- mat.roughnessMap = packedMr;- mat.metalnessMap = packedMr;- }- if (typeof opts.roughness === "number") {- mat.roughness = opts.roughness;- } else if (packedMr) {- mat.roughness = 1;- } else {- mat.roughness = 0.8;- }- if (typeof opts.metalness === "number") {- mat.metalness = opts.metalness;- } else if (packedMr) {- mat.metalness = 1;- }- if (isTex(opts.emissive)) {- requireTextureUsage(opts.emissive, "emissive");- mat.emissiveMap = opts.emissive;- mat.emissive = new THREE22.Color(16777215);- } else if (opts.emissive !== undefined) {- mat.emissive = new THREE22.Color(opts.emissive);- }- if (opts.emissiveIntensity !== undefined) {- mat.emissiveIntensity = opts.emissiveIntensity;- }- if (opts.aoMap) {- requireTextureUsage(opts.aoMap, "occlusion");- mat.aoMap = opts.aoMap;- }- if (opts.aoMapIntensity !== undefined)- mat.aoMapIntensity = opts.aoMapIntensity;- const alphaMode2 = opts.alphaMode ?? "opaque";- if (alphaMode2 !== "opaque" && alphaMode2 !== "mask" && alphaMode2 !== "blend") {- throw new TypeError('alphaMode must be one of "opaque", "mask", or "blend".');- }- if (opts.doubleSided !== undefined && typeof opts.doubleSided !== "boolean") {- throw new TypeError("doubleSided must be a boolean when provided.");- }- if (opts.alphaCutoff !== undefined && alphaMode2 !== "mask") {- throw new TypeError('alphaCutoff is valid only when alphaMode is "mask".');- }- if (opts.alphaCutoff !== undefined && (!Number.isFinite(opts.alphaCutoff) || opts.alphaCutoff < 0 || opts.alphaCutoff > 1)) {- throw new RangeError("alphaCutoff must be a finite number in [0,1].");- }- if (alphaMode2 === "mask") {- mat.alphaTest = opts.alphaCutoff ?? 0.5;- mat.transparent = false;- } else if (alphaMode2 === "blend") {- mat.alphaTest = 0;- mat.transparent = true;- }- if (opts.doubleSided)- mat.side = THREE22.DoubleSide;- mat.userData["kilnMaterial"] = {- alphaMode: alphaMode2,- ...alphaMode2 === "mask" ? { alphaCutoff: mat.alphaTest } : {},- doubleSided: opts.doubleSided === true- };- return mat;-}-function foliageMaterial(albedo, opts = {}) {- return pbrMaterial({- albedo,- roughness: opts.roughness ?? 0.9,- metalness: 0,- alphaMode: "mask",- alphaCutoff: opts.alphaCutoff ?? 0.5,- doubleSided: opts.doubleSided ?? true- });-}-var TEXTURE_USAGES;-var init_textures = __esm(() => {- TEXTURE_USAGES = [- "albedo",- "emissive",- "normal",- "roughness",- "metalness",- "metallicRoughness",- "occlusion"- ];-});--// src/procedural-material-v2.ts-function strictRecord(value, path) {- if (!value || typeof value !== "object" || Array.isArray(value)) {- throw new ProceduralTextureError(`${path} must be a plain JSON object.`);- }- const prototype = Object.getPrototypeOf(value);- if (prototype !== Object.prototype && prototype !== null) {- throw new ProceduralTextureError(`${path} must be a plain JSON object with no custom prototype.`);- }- for (const key of Reflect.ownKeys(value)) {- if (typeof key !== "string") {- throw new ProceduralTextureError(`${path} must not contain symbol keys.`);- }- if (FORBIDDEN_KEYS.has(key)) {- throw new ProceduralTextureError(`${path} contains forbidden key ${JSON.stringify(key)}.`);- }- if (!Object.prototype.propertyIsEnumerable.call(value, key)) {- throw new ProceduralTextureError(`${path}.${key} must be an enumerable JSON field.`);- }- const descriptor = Object.getOwnPropertyDescriptor(value, key);- if (!descriptor || !("value" in descriptor)) {- throw new ProceduralTextureError(`${path}.${key} must be a plain JSON data field.`);- }- }- return value;-}-function strictArray(value, path) {- if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) {- throw new ProceduralTextureError(`${path} must be a plain JSON array.`);- }- for (const key of Reflect.ownKeys(value)) {- if (typeof key !== "string") {- throw new ProceduralTextureError(`${path} must not contain symbol keys.`);- }- if (key === "length")- continue;- if (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length) {- throw new ProceduralTextureError(`${path} has non-index JSON array key ${JSON.stringify(key)}.`);- }- }- for (let index = 0;index < value.length; index++) {- if (!Object.hasOwn(value, index)) {- throw new ProceduralTextureError(`${path} must be a dense JSON array (missing index ${index}).`);- }- }- return value;-}-function assertKeys(record4, allowed, path) {- const allow = new Set(allowed);- for (const key of Object.keys(record4)) {- if (!allow.has(key)) {- throw new ProceduralTextureError(`${path} has unknown key ${JSON.stringify(key)}.`);- }- }-}-function color(value, path) {- if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 16777215) {- throw new ProceduralTextureError(`${path} must be a color integer between 0x000000 and 0xffffff, got ${JSON.stringify(value)}.`);- }- return value;-}-function integer(value, path, fallback, min, max) {- if (value === undefined)- return fallback;- if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {- throw new ProceduralTextureError(`${path} must be a whole number between ${min} and ${max}, got ${JSON.stringify(value)}.`);- }- return value;-}-function finite2(value, path, fallback, min, max) {- if (value === undefined)- return fallback;- if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {- throw new ProceduralTextureError(`${path} must be a finite number between ${min} and ${max}, got ${JSON.stringify(value)}.`);- }- return value;-}-function unit(value, path, fallback) {- return finite2(value, path, fallback, 0, 1);-}-function optionalName(value, path) {- if (value === undefined)- return;- const hasControlCharacter = typeof value === "string" && [...value].some((character) => {- const code = character.charCodeAt(0);- return code < 32 || code === 127;- });- if (typeof value !== "string" || value.length === 0 || value.length > MAX_PROCEDURAL_NAME_LENGTH || hasControlCharacter) {- throw new ProceduralTextureError(`${path} must be 1..${MAX_PROCEDURAL_NAME_LENGTH} visible characters.`);- }- return value;-}-function usage(value, path, fallback) {- if (value === undefined)- return fallback;- if (!TEXTURE_USAGES.includes(value)) {- throw new ProceduralTextureError(`${path} must be one of ${TEXTURE_USAGES.join(", ")}, got ${JSON.stringify(value)}.`);- }- return value;-}-function angle(value, path) {- const bounded = finite2(value, path, 0, -36000, 36000);- const normalized = (bounded % 360 + 360) % 360;- return Object.is(normalized, -0) ? 0 : normalized;-}-function blend(record4, path) {- const value = record4["blend"] ?? "normal";- if (!BLENDS.includes(value)) {- throw new ProceduralTextureError(`${path}.blend ${JSON.stringify(value)} is not one of ${BLENDS.join(", ")}.`);- }- return value;-}-function canonicalLayer(value, index) {- const path = `proceduralTexture.layers[${index}]`;- const record4 = strictRecord(value, path);- const op = record4["op"];- if (!OPS.includes(op)) {- throw new ProceduralTextureError(`${path}.op ${JSON.stringify(op)} is not one of ${OPS.join(", ")}.`);- }- const validatedBlend = blend(record4, path);- const validatedOpacity = unit(record4["opacity"], `${path}.opacity`, 1);- const common = {- blend: index === 0 ? "normal" : validatedBlend,- opacity: index === 0 ? 1 : validatedOpacity- };- switch (op) {- case "solid":- assertKeys(record4, ["op", "color", "blend", "opacity"], path);- return { op, color: color(record4["color"], `${path}.color`), ...common };- case "checker":- assertKeys(record4, ["op", "colorA", "colorB", "squares", "blend", "opacity"], path);- return {- op,- colorA: color(record4["colorA"], `${path}.colorA`),- colorB: color(record4["colorB"], `${path}.colorB`),- squares: integer(record4["squares"], `${path}.squares`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- ...common- };- case "stripes":- assertKeys(record4, ["op", "colorA", "colorB", "count", "angleDeg", "blend", "opacity"], path);- return {- op,- colorA: color(record4["colorA"], `${path}.colorA`),- colorB: color(record4["colorB"], `${path}.colorB`),- count: integer(record4["count"], `${path}.count`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- angleDeg: angle(record4["angleDeg"], `${path}.angleDeg`),- ...common- };- case "gradient":- assertKeys(record4, ["op", "from", "to", "angleDeg", "blend", "opacity"], path);- return {- op,- from: color(record4["from"], `${path}.from`),- to: color(record4["to"], `${path}.to`),- angleDeg: angle(record4["angleDeg"], `${path}.angleDeg`),- ...common- };- case "bricks":- assertKeys(record4, ["op", "brick", "mortar", "rows", "cols", "mortarWidth", "stagger", "blend", "opacity"], path);- return {- op,- brick: color(record4["brick"], `${path}.brick`),- mortar: color(record4["mortar"], `${path}.mortar`),- rows: integer(record4["rows"], `${path}.rows`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- cols: integer(record4["cols"], `${path}.cols`, 4, 1, MAX_PROCEDURAL_PATTERN_COUNT),- mortarWidth: unit(record4["mortarWidth"], `${path}.mortarWidth`, 0.06),- stagger: unit(record4["stagger"], `${path}.stagger`, 0.5),- ...common- };- case "noise":- assertKeys(record4, ["op", "colorA", "colorB", "scale", "octaves", "seed", "blend", "opacity"], path);- return {- op,- colorA: color(record4["colorA"], `${path}.colorA`),- colorB: color(record4["colorB"], `${path}.colorB`),- scale: integer(record4["scale"], `${path}.scale`, 8, 1, MAX_PROCEDURAL_PATTERN_COUNT),- octaves: integer(record4["octaves"], `${path}.octaves`, 3, 1, MAX_NOISE_OCTAVES),- seed: integer(record4["seed"], `${path}.seed`, 0, -2147483648, 2147483647),- ...common- };- default:- throw new ProceduralTextureError(`${path}.op is unsupported.`);- }-}-function migrateProceduralTextureSpecV1(input) {- const record4 = strictRecord(input, "proceduralTexture");- assertKeys(record4, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");- if (record4["schemaVersion"] !== undefined && record4["schemaVersion"] !== 1) {- throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(record4["schemaVersion"])}.`);- }- return {- schemaVersion: 2,- ...record4["size"] !== undefined ? { size: record4["size"] } : {},- ...record4["usage"] !== undefined ? { usage: record4["usage"] } : {},- ...record4["name"] !== undefined ? { name: record4["name"] } : {},- layers: record4["layers"]- };-}-function canonicalizeProceduralTextureSpecV2(input) {- const initial = strictRecord(input, "proceduralTexture");- const source = initial["schemaVersion"] === undefined || initial["schemaVersion"] === 1 ? strictRecord(migrateProceduralTextureSpecV1(initial), "proceduralTexture") : initial;- assertKeys(source, ["schemaVersion", "size", "usage", "name", "layers"], "proceduralTexture");- if (source["schemaVersion"] !== 2) {- throw new ProceduralTextureError(`proceduralTexture.schemaVersion must be 2, got ${JSON.stringify(source["schemaVersion"])}.`);- }- const size = source["size"] ?? 256;- if (typeof size !== "number" || !Number.isInteger(size) || size < MIN_PROCEDURAL_SIZE || size > MAX_PROCEDURAL_SIZE || (size & size - 1) !== 0) {- throw new ProceduralTextureError(`proceduralTexture.size must be a power of two between ${MIN_PROCEDURAL_SIZE} and ${MAX_PROCEDURAL_SIZE}, got ${JSON.stringify(source["size"])}.`);- }- const rawLayers = source["layers"];- if (!Array.isArray(rawLayers) || rawLayers.length === 0) {- throw new ProceduralTextureError("proceduralTexture.layers must be a non-empty array — the bottom layer is the base pattern.");- }- const layers = strictArray(rawLayers, "proceduralTexture.layers");- if (layers.length > MAX_PROCEDURAL_LAYERS) {- throw new ProceduralTextureError(`proceduralTexture: ${layers.length} layers exceeds the maximum of ${MAX_PROCEDURAL_LAYERS}.`);- }- const name = optionalName(source["name"], "proceduralTexture.name");- return {- schemaVersion: 2,- size,- usage: usage(source["usage"], "proceduralTexture.usage", "albedo"),- ...name !== undefined ? { name } : {},- layers: layers.map(canonicalLayer)- };-}-function canonicalJson(value) {- if (value === null || typeof value !== "object")- return JSON.stringify(value);- if (Array.isArray(value))- return `[${value.map(canonicalJson).join(",")}]`;- const record4 = value;- return `{${Object.keys(record4).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record4[key])}`).join(",")}}`;-}-function canonicalProceduralTextureJsonV2(input) {- return canonicalJson(canonicalizeProceduralTextureSpecV2(input));-}-function sha256Hex(text2) {- const source = new TextEncoder().encode(text2);- const bitLength = source.length * 8;- const paddedLength = Math.ceil((source.length + 9) / 64) * 64;- const bytes = new Uint8Array(paddedLength);- bytes.set(source);- bytes[source.length] = 128;- const view = new DataView(bytes.buffer);- view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296), false);- view.setUint32(paddedLength - 4, bitLength >>> 0, false);- const h = new Uint32Array([- 1779033703,- 3144134277,- 1013904242,- 2773480762,- 1359893119,- 2600822924,- 528734635,- 1541459225- ]);- const w = new Uint32Array(64);- for (let offset = 0;offset < bytes.length; offset += 64) {- for (let i = 0;i < 16; i++)- w[i] = view.getUint32(offset + i * 4, false);- for (let i = 16;i < 64; i++) {- const a2 = w[i - 15];- const b2 = w[i - 2];- const s0 = rotateRight(a2, 7) ^ rotateRight(a2, 18) ^ a2 >>> 3;- const s1 = rotateRight(b2, 17) ^ rotateRight(b2, 19) ^ b2 >>> 10;- w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;- }- let [a, b, c, d, e, f, g, hh] = h;- for (let i = 0;i < 64; i++) {- const s1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);- const choice = e & f ^ ~e & g;- const temp1 = hh + s1 + choice + SHA256_K[i] + w[i] >>> 0;- const s0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);- const majority = a & b ^ a & c ^ b & c;- const temp2 = s0 + majority >>> 0;- hh = g;- g = f;- f = e;- e = d + temp1 >>> 0;- d = c;- c = b;- b = a;- a = temp1 + temp2 >>> 0;- }- const next = [a, b, c, d, e, f, g, hh];- for (let i = 0;i < 8; i++)- h[i] = h[i] + next[i] >>> 0;- }- return [...h].map((value) => value.toString(16).padStart(8, "0")).join("");-}-function hashProceduralTextureSpecV2(input) {- return `sha256:${sha256Hex(canonicalProceduralTextureJsonV2(input))}`;-}-function canonicalTextureRef(value, slot) {- const path = `portableMaterial.textures.${slot}`;- const record4 = strictRecord(value, path);- if (record4["kind"] === "procedural") {- assertKeys(record4, ["kind", "spec"], path);- const spec = canonicalizeProceduralTextureSpecV2(record4["spec"]);- const expected = MATERIAL_TEXTURE_USAGE[slot];- if (spec.usage !== expected) {- throw new ProceduralTextureError(`${path} requires procedural usage ${JSON.stringify(expected)}, got ${JSON.stringify(spec.usage)}.`);- }- return { kind: "procedural", spec };- }- if (record4["kind"] === "resource") {- assertKeys(record4, ["kind", "resourceId"], path);- const resourceId = record4["resourceId"];- if (typeof resourceId !== "string" || resourceId.length > 128 || !/^kiln\.[a-z0-9][a-z0-9._-]+$/.test(resourceId)) {- throw new ProceduralTextureError(`${path}.resourceId must be a bounded kiln.* resource ID.`);- }- return { kind: "resource", resourceId };- }- throw new ProceduralTextureError(`${path}.kind must be "procedural" or "resource".`);-}-function canonicalizePortableMaterialSpecV2(input) {- const record4 = strictRecord(input, "portableMaterial");- assertKeys(record4, [- "schemaVersion",- "model",- "name",- "baseColor",- "roughness",- "metalness",- "emissive",- "emissiveIntensity",- "alphaMode",- "alphaCutoff",- "doubleSided",- "textures"- ], "portableMaterial");- if (record4["schemaVersion"] !== 2) {- throw new ProceduralTextureError("portableMaterial.schemaVersion must be 2.");- }- if (record4["model"] !== "pbrMetallicRoughness") {- throw new ProceduralTextureError('portableMaterial.model must be "pbrMetallicRoughness"; executable shader models are not portable.');- }- const textureInput = record4["textures"] ?? {};- const textureRecord = strictRecord(textureInput, "portableMaterial.textures");- const slots = Object.keys(MATERIAL_TEXTURE_USAGE);- assertKeys(textureRecord, slots, "portableMaterial.textures");- if (Object.keys(textureRecord).length > MAX_PORTABLE_MATERIAL_TEXTURES) {- throw new ProceduralTextureError(`portableMaterial has more than ${MAX_PORTABLE_MATERIAL_TEXTURES} texture slots.`);- }- const textures = {};- let proceduralTexels = 0;- for (const slot of slots) {- if (textureRecord[slot] === undefined)- continue;- const ref = canonicalTextureRef(textureRecord[slot], slot);- textures[slot] = ref;- if (ref.kind === "procedural")- proceduralTexels += ref.spec.size * ref.spec.size;- }- if (proceduralTexels > MAX_PORTABLE_MATERIAL_TEXELS) {- throw new ProceduralTextureError(`portableMaterial procedural texture budget is ${proceduralTexels} texels, above ${MAX_PORTABLE_MATERIAL_TEXELS}.`);- }- const alphaMode2 = record4["alphaMode"] ?? "opaque";- if (alphaMode2 !== "opaque" && alphaMode2 !== "mask" && alphaMode2 !== "blend") {- throw new ProceduralTextureError("portableMaterial.alphaMode must be opaque, mask, or blend.");- }- if (record4["doubleSided"] !== undefined && typeof record4["doubleSided"] !== "boolean") {- throw new ProceduralTextureError("portableMaterial.doubleSided must be boolean.");- }- const name = optionalName(record4["name"], "portableMaterial.name");- return {- schemaVersion: 2,- model: "pbrMetallicRoughness",- ...name !== undefined ? { name } : {},- ...record4["baseColor"] !== undefined ? { baseColor: color(record4["baseColor"], "portableMaterial.baseColor") } : {},- roughness: unit(record4["roughness"], "portableMaterial.roughness", 1),- metalness: unit(record4["metalness"], "portableMaterial.metalness", 0),- ...record4["emissive"] !== undefined ? { emissive: color(record4["emissive"], "portableMaterial.emissive") } : {},- emissiveIntensity: finite2(record4["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),- alphaMode: alphaMode2,- alphaCutoff: unit(record4["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),- doubleSided: record4["doubleSided"] === true,- textures- };-}-var MAX_PROCEDURAL_SIZE = 1024, MIN_PROCEDURAL_SIZE = 4, MAX_PROCEDURAL_LAYERS = 8, MAX_NOISE_OCTAVES = 6, MAX_PROCEDURAL_NAME_LENGTH = 80, MAX_PROCEDURAL_PATTERN_COUNT = 256, MAX_PORTABLE_MATERIAL_TEXTURES = 5, MAX_PORTABLE_MATERIAL_TEXELS, ProceduralTextureError, OPS, BLENDS, FORBIDDEN_KEYS, SHA256_K, rotateRight = (value, bits) => value >>> bits | value << 32 - bits, MATERIAL_TEXTURE_USAGE;-var init_procedural_material_v2 = __esm(() => {- init_textures();- MAX_PORTABLE_MATERIAL_TEXELS = 4 * 1024 * 1024;- ProceduralTextureError = class ProceduralTextureError extends Error {- constructor(message) {- super(message);- this.name = "ProceduralTextureError";- }- };- OPS = ["solid", "checker", "stripes", "gradient", "bricks", "noise"];- BLENDS = ["normal", "multiply", "screen", "overlay"];- FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);- SHA256_K = new Uint32Array([- 1116352408,- 1899447441,- 3049323471,- 3921009573,- 961987163,- 1508970993,- 2453635748,- 2870763221,- 3624381080,- 310598401,- 607225278,- 1426881987,- 1925078388,- 2162078206,- 2614888103,- 3248222580,- 3835390401,- 4022224774,- 264347078,- 604807628,- 770255983,- 1249150122,- 1555081692,- 1996064986,- 2554220882,- 2821834349,- 2952996808,- 3210313671,- 3336571891,- 3584528711,- 113926993,- 338241895,- 666307205,- 773529912,- 1294757372,- 1396182291,- 1695183700,- 1986661051,- 2177026350,- 2456956037,- 2730485921,- 2820302411,- 3259730800,- 3345764771,- 3516065817,- 3600352804,- 4094571909,- 275423344,- 430227734,- 506948616,- 659060556,- 883997877,- 958139571,- 1322822218,- 1537002063,- 1747873779,- 1955562222,- 2024104815,- 2227730452,- 2361852424,- 2428436474,- 2756734187,- 3204031479,- 3329325298- ]);- MATERIAL_TEXTURE_USAGE = {- baseColor: "albedo",- normal: "normal",- metallicRoughness: "metallicRoughness",- emissive: "emissive",- occlusion: "occlusion"- };-});--// src/procedural-texture.ts-import * as THREE23 from "three";-function hash2(x, y, seed) {- let h = Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0;- h = h ^ h >>> 13;- h = Math.imul(h, 1274126177) | 0;- h = h ^ h >>> 16;- return (h >>> 0) / 4294967296;-}-function valueNoise(u, v, period, seed) {- const x = u * period;- const y = v * period;- const xi = Math.floor(x);- const yi = Math.floor(y);- const xf = x - xi;- const yf = y - yi;- const wrap = (n) => (n % period + period) % period;- const x0 = wrap(xi);- const y0 = wrap(yi);- const x1 = wrap(xi + 1);- const y1 = wrap(yi + 1);- const sx = smoothstep(xf);- const sy = smoothstep(yf);- const n00 = hash2(x0, y0, seed);- const n10 = hash2(x1, y0, seed);- const n01 = hash2(x0, y1, seed);- const n11 = hash2(x1, y1, seed);- const top = n00 + sx * (n10 - n00);- const bottom = n01 + sx * (n11 - n01);- return top + sy * (bottom - top);-}-function fbm(u, v, period, octaves, seed) {- let sum = 0;- let amplitude = 1;- let total = 0;- let p = period;- for (let o = 0;o < octaves; o++) {- sum += valueNoise(u, v, p, seed + o * 101) * amplitude;- total += amplitude;- amplitude *= 0.5;- p *= 2;- }- return total > 0 ? sum / total : 0;-}-function project(u, v, angleDeg) {- const a = angleDeg * Math.PI / 180;- return (u - 0.5) * Math.cos(a) + (v - 0.5) * Math.sin(a) + 0.5;-}-function evalLayer(layer, u, v) {- switch (layer.op) {- case "solid":- return rgbOf(layer.color);- case "checker": {- const cx = Math.floor(u * layer.squares);- const cy = Math.floor(v * layer.squares);- return rgbOf((cx + cy) % 2 === 0 ? layer.colorA : layer.colorB);- }- case "stripes": {- const t = project(u, v, layer.angleDeg);- return rgbOf(Math.floor(t * layer.count) % 2 === 0 ? layer.colorA : layer.colorB);- }- case "gradient": {- const t = Math.min(1, Math.max(0, project(u, v, layer.angleDeg)));- const from = rgbOf(layer.from);- const to = rgbOf(layer.to);- return [lerp(from[0], to[0], t), lerp(from[1], to[1], t), lerp(from[2], to[2], t)];- }- case "bricks": {- const row = Math.floor(v * layer.rows);- const shifted = (u + (row % 2 === 0 ? 0 : layer.stagger / layer.cols) + 1) % 1;- const inCol = shifted * layer.cols % 1;- const inRow = v * layer.rows % 1;- const isMortar = inCol < layer.mortarWidth || inCol > 1 - layer.mortarWidth || inRow < layer.mortarWidth || inRow > 1 - layer.mortarWidth;- return rgbOf(isMortar ? layer.mortar : layer.brick);- }- case "noise": {- const n = fbm(u, v, layer.scale, layer.octaves, layer.seed);- const a = rgbOf(layer.colorA);- const b = rgbOf(layer.colorB);- return [lerp(a[0], b[0], n), lerp(a[1], b[1], n), lerp(a[2], b[2], n)];- }- }-}-function blendChannel(mode, base, top) {- const b = base / 255;- const t = top / 255;- let out;- switch (mode) {- case "multiply":- out = b * t;- break;- case "screen":- out = 1 - (1 - b) * (1 - t);- break;- case "overlay":- out = b < 0.5 ? 2 * b * t : 1 - 2 * (1 - b) * (1 - t);- break;- default:- out = t;- }- return out * 255;-}-function compileProceduralTextureSpecV2(input) {- const spec = canonicalizeProceduralTextureSpecV2(input);- const { size, layers } = spec;- const data = new Uint8Array(size * size * 4);- for (let y = 0;y < size; y++) {- const v = (y + 0.5) / size;- for (let x = 0;x < size; x++) {- const u = (x + 0.5) / size;- let r = 0;- let g = 0;- let b = 0;- for (const [i, layer] of layers.entries()) {- const [lr, lg, lb] = evalLayer(layer, u, v);- if (i === 0) {- r = lr;- g = lg;- b = lb;- continue;- }- r = lerp(r, blendChannel(layer.blend, r, lr), layer.opacity);- g = lerp(g, blendChannel(layer.blend, g, lg), layer.opacity);- b = lerp(b, blendChannel(layer.blend, b, lb), layer.opacity);- }- const o = (y * size + x) * 4;- data[o] = Math.max(0, Math.min(255, Math.round(r)));- data[o + 1] = Math.max(0, Math.min(255, Math.round(g)));- data[o + 2] = Math.max(0, Math.min(255, Math.round(b)));- data[o + 3] = 255;- }- }- return {- spec,- pixels: data,- canonicalJson: canonicalProceduralTextureJsonV2(spec),- recipeHash: hashProceduralTextureSpecV2(spec)- };-}-function proceduralTexture(spec) {- const compiled = compileProceduralTextureSpecV2(spec);- const { size, usage: usage2, name, layers } = compiled.spec;- const tex = new THREE23.DataTexture(compiled.pixels, size, size, THREE23.RGBAFormat, THREE23.UnsignedByteType);- if (name)- tex.name = name;- tex.colorSpace = usage2 === "albedo" || usage2 === "emissive" ? THREE23.SRGBColorSpace : THREE23.NoColorSpace;- tex.wrapS = THREE23.RepeatWrapping;- tex.wrapT = THREE23.RepeatWrapping;- tex.minFilter = THREE23.LinearMipmapLinearFilter;- tex.magFilter = THREE23.LinearFilter;- tex.generateMipmaps = true;- tex.needsUpdate = true;- tex.userData["kilnProcedural"] = {- schemaVersion: 2,- size,- usage: usage2,- ...name ? { name } : {},- layers,- canonicalJson: compiled.canonicalJson,- recipeHash: compiled.recipeHash- };- return tex;-}-function normalMapFromHeight(source, opts = {}) {- const image = source.image;- const data = image?.data;- const width = image?.width ?? 0;- const height = image?.height ?? 0;- if (!data || !width || !height) {- throw new ProceduralTextureError("normalMapFromHeight: the source texture has no readable pixels. Pass a proceduralTexture() result or a loadApprovedTexture() result, not a texture built from an image element.");- }- const channels = data.length / (width * height);- if (channels !== 3 && channels !== 4) {- throw new ProceduralTextureError(`normalMapFromHeight: the source has ${data.length} bytes for ${width}x${height}, which is neither RGB nor RGBA.`);- }- const strength = opts.strength ?? 2;- if (!Number.isFinite(strength) || strength <= 0) {- throw new ProceduralTextureError(`normalMapFromHeight: strength must be a positive number, got ${JSON.stringify(opts.strength)}.`);- }- const lum = (x, y) => {- const xw = (x % width + width) % width;- const yw = (y % height + height) % height;- const o = (yw * width + xw) * channels;- return (0.299 * (data[o] ?? 0) + 0.587 * (data[o + 1] ?? 0) + 0.114 * (data[o + 2] ?? 0)) / 255;- };- const out = new Uint8Array(width * height * 4);- for (let y = 0;y < height; y++) {- for (let x = 0;x < width; x++) {- const dx = (lum(x + 1, y) - lum(x - 1, y)) * strength;- const dy = (lum(x, y + 1) - lum(x, y - 1)) * strength;- let nx = -dx;- let ny = -dy;- const nz = 1;- const len = Math.hypot(nx, ny, nz) || 1;- nx /= len;- ny /= len;- const o = (y * width + x) * 4;- out[o] = Math.round((nx * 0.5 + 0.5) * 255);- out[o + 1] = Math.round((ny * 0.5 + 0.5) * 255);- out[o + 2] = Math.round(nz / len * 0.5 * 255 + 127.5);- out[o + 3] = 255;- }- }- const tex = new THREE23.DataTexture(out, width, height, THREE23.RGBAFormat, THREE23.UnsignedByteType);- tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : "");- tex.colorSpace = THREE23.NoColorSpace;- tex.wrapS = THREE23.RepeatWrapping;- tex.wrapT = THREE23.RepeatWrapping;- tex.minFilter = THREE23.LinearMipmapLinearFilter;- tex.magFilter = THREE23.LinearFilter;- tex.generateMipmaps = true;- tex.needsUpdate = true;- return tex;-}-var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color2) => [- color2 >> 16 & 255,- color2 >> 8 & 255,- color2 & 255+var smoothstep = (t) => t * t * (3 - 2 * t), rgbOf = (color) => [+ color >> 16 & 255,+ color >> 8 & 255,+ color & 255], lerp = (a, b, t) => a + (b - a) * t;var init_procedural_texture = __esm(() => {init_procedural_material_v2();@@ -17603,2357 +9653,10253 @@ var init_material_texture_library_generated = __esm(() => {sourceMd5: "d407c7adebb2d943107eb91a30a9f909",transform: "sharp 128x128 Lanczos3 PNG"}),- "kiln.texture.forest-leaves-normal.v1": Object.freeze({- sourceAsset: "forest_leaves_03",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/forest_leaves_03/forest_leaves_03_nor_gl_1k.jpg",- sourceMd5: "2ab6164e4eb8116e9209c5af261f22a6",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.texture.forest-leaves-normal.v1": Object.freeze({+ sourceAsset: "forest_leaves_03",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/forest_leaves_03/forest_leaves_03_nor_gl_1k.jpg",+ sourceMd5: "2ab6164e4eb8116e9209c5af261f22a6",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.forest-leaves-arm.v1": Object.freeze({+ sourceAsset: "forest_leaves_03",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/forest_leaves_03/forest_leaves_03_arm_1k.jpg",+ sourceMd5: "cee4ef6c48848ffa09f818ab86367eab",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.rubber-tiles-albedo.v1": Object.freeze({+ sourceAsset: "rubber_tiles",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/rubber_tiles/rubber_tiles_diff_1k.jpg",+ sourceMd5: "2a2cc9b5e06639c7fb6cc26c263c00ff",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.rubber-tiles-normal.v1": Object.freeze({+ sourceAsset: "rubber_tiles",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/rubber_tiles/rubber_tiles_nor_gl_1k.jpg",+ sourceMd5: "4ed5fac176252df9dde7d0fbf8a9b76d",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.rubber-tiles-arm.v1": Object.freeze({+ sourceAsset: "rubber_tiles",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/rubber_tiles/rubber_tiles_arm_1k.jpg",+ sourceMd5: "8b7e2c4a9851564b8e701b450df9abc9",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.metal-plate-albedo.v1": Object.freeze({+ sourceAsset: "metal_plate",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/metal_plate/metal_plate_diff_1k.jpg",+ sourceMd5: "bd9daf4c04046ca392a38b8df955ed26",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.metal-plate-normal.v1": Object.freeze({+ sourceAsset: "metal_plate",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/metal_plate/metal_plate_nor_gl_1k.jpg",+ sourceMd5: "d379e66130ad6ccff217ac9b13de935d",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.metal-plate-arm.v1": Object.freeze({+ sourceAsset: "metal_plate",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/metal_plate/metal_plate_arm_1k.jpg",+ sourceMd5: "13f064ffa4863a4170d902f675eb022e",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.clay-roof-tiles-albedo.v1": Object.freeze({+ sourceAsset: "clay_roof_tiles",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/clay_roof_tiles/clay_roof_tiles_diff_1k.jpg",+ sourceMd5: "d862ac9932b09b0918b5971ddb77099c",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.clay-roof-tiles-normal.v1": Object.freeze({+ sourceAsset: "clay_roof_tiles",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/clay_roof_tiles/clay_roof_tiles_nor_gl_1k.jpg",+ sourceMd5: "d861a708c94c824befc8aac668052776",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.clay-roof-tiles-arm.v1": Object.freeze({+ sourceAsset: "clay_roof_tiles",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/clay_roof_tiles/clay_roof_tiles_arm_1k.jpg",+ sourceMd5: "1c85df2500d6d9ae720cad193e3a4cec",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.cobblestone-floor-albedo.v1": Object.freeze({+ sourceAsset: "cobblestone_floor_01",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/cobblestone_floor_01/cobblestone_floor_01_diff_1k.jpg",+ sourceMd5: "ef7a4b9314ccd7f11ea07a06b81e515a",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.cobblestone-floor-normal.v1": Object.freeze({+ sourceAsset: "cobblestone_floor_01",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/cobblestone_floor_01/cobblestone_floor_01_nor_gl_1k.jpg",+ sourceMd5: "25994f0cbfefb6a4be0e0a349fa8c3ea",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.cobblestone-floor-arm.v1": Object.freeze({+ sourceAsset: "cobblestone_floor_01",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/cobblestone_floor_01/cobblestone_floor_01_arm_1k.jpg",+ sourceMd5: "80591b98c4d3126e006b32806424d541",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.oak-veneer-albedo.v1": Object.freeze({+ sourceAsset: "oak_veneer_01",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/oak_veneer_01/oak_veneer_01_diff_1k.jpg",+ sourceMd5: "39a99df4e328d62d74f3122722a64a95",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.oak-veneer-normal.v1": Object.freeze({+ sourceAsset: "oak_veneer_01",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/oak_veneer_01/oak_veneer_01_nor_gl_1k.jpg",+ sourceMd5: "d05406f5fdaf51f0d7b115b35d9af1b7",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.oak-veneer-arm.v1": Object.freeze({+ sourceAsset: "oak_veneer_01",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/oak_veneer_01/oak_veneer_01_arm_1k.jpg",+ sourceMd5: "dfba0f063663289248f4e887f836bdcc",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.polished-marble-albedo.v1": Object.freeze({+ sourceAsset: "marble_01",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/marble_01/marble_01_diff_1k.jpg",+ sourceMd5: "04325ced5018eb8a2e598a4ef69cb176",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.polished-marble-normal.v1": Object.freeze({+ sourceAsset: "marble_01",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/marble_01/marble_01_nor_gl_1k.jpg",+ sourceMd5: "fa073d722cde733c1bd6cc6e8897c8e3",+ transform: "sharp 128x128 Lanczos3 PNG"+ }),+ "kiln.texture.polished-marble-arm.v1": Object.freeze({+ sourceAsset: "marble_01",+ sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/marble_01/marble_01_arm_1k.jpg",+ sourceMd5: "51017a4e4f320c3b58763c66727d89c1",+ transform: "sharp 128x128 Lanczos3 PNG"+ })+ });+});++// src/material-recipes.ts+function validateMaterialRecipeRequestV1(value) {+ const issues = [];+ if (!isRecord5(value)) {+ return {+ valid: false,+ issues: [{ code: "EXPECTED_OBJECT", path: "", message: "materialRecipe must be an object." }]+ };+ }+ if (value.schemaVersion !== 1) {+ issues.push({+ code: "UNSUPPORTED_SCHEMA_VERSION",+ path: "schemaVersion",+ message: "materialRecipe.schemaVersion must be 1."+ });+ }+ if (!recipeId(value.id)) {+ issues.push({+ code: "UNSUPPORTED_RECIPE_ID",+ path: "id",+ message: `Unsupported material recipe ID ${JSON.stringify(value.id)}.`+ });+ }+ if (value.overrides !== undefined && !isRecord5(value.overrides)) {+ issues.push({+ code: "INVALID_OVERRIDES",+ path: "overrides",+ message: "materialRecipe.overrides must be an object."+ });+ }+ if (recipeId(value.id) && isRecord5(value.overrides)) {+ const allowed = new Set(MATERIAL_RECIPE_LIBRARY_V1[value.id].allowedOverrides);+ for (const [key, override] of Object.entries(value.overrides)) {+ if (!MATERIAL_RECIPE_OVERRIDE_KEYS.includes(key)) {+ issues.push({+ code: "UNSUPPORTED_OVERRIDE",+ path: `overrides.${key}`,+ message: `Unknown material recipe override ${JSON.stringify(key)}.`+ });+ continue;+ }+ if (!allowed.has(key)) {+ issues.push({+ code: "UNSUPPORTED_OVERRIDE",+ path: `overrides.${key}`,+ message: `${key} is not supported by ${value.id}.`+ });+ continue;+ }+ if ((key === "baseColor" || key === "emissiveColor") && !hexColor(override)) {+ issues.push({+ code: "INVALID_OVERRIDE_VALUE",+ path: `overrides.${key}`,+ message: `${key} must be a six-digit #RRGGBB color.`+ });+ } else if ((key === "roughness" || key === "metalness" || key === "opacity" || key === "alphaCutoff") && !finiteUnit(override)) {+ issues.push({+ code: "INVALID_OVERRIDE_VALUE",+ path: `overrides.${key}`,+ message: `${key} must be a finite number in [0,1].`+ });+ } else if (key === "doubleSided" && typeof override !== "boolean") {+ issues.push({+ code: "INVALID_OVERRIDE_VALUE",+ path: `overrides.${key}`,+ message: "doubleSided must be boolean."+ });+ } else if (key === "emissiveIntensity" && (typeof override !== "number" || !Number.isFinite(override) || override < 0 || override > 1)) {+ issues.push({+ code: "INVALID_OVERRIDE_VALUE",+ path: `overrides.${key}`,+ message: "emissiveIntensity must be a finite number in [0,1] for core glTF."+ });+ } else if (key === "textureResources") {+ if (!isRecord5(override)) {+ issues.push({+ code: "INVALID_OVERRIDE_VALUE",+ path: "overrides.textureResources",+ message: "textureResources must be an object keyed by portable material slot."+ });+ continue;+ }+ for (const [slot, selected] of Object.entries(override)) {+ if (!MATERIAL_TEXTURE_SLOTS.includes(slot)) {+ issues.push({+ code: "UNKNOWN_TEXTURE_SLOT",+ path: `overrides.textureResources.${slot}`,+ message: `Unknown portable texture slot ${JSON.stringify(slot)}.`+ });+ continue;+ }+ if (!resourceId(selected)) {+ issues.push({+ code: "UNSUPPORTED_RESOURCE_ID",+ path: `overrides.textureResources.${slot}`,+ message: `Unsupported approved texture resource ID ${JSON.stringify(selected)}.`+ });+ continue;+ }+ const resource = APPROVED_TEXTURE_RESOURCES_V1[selected];+ if (!resource.allowedSlots.includes(slot)) {+ issues.push({+ code: "RESOURCE_SLOT_MISMATCH",+ path: `overrides.textureResources.${slot}`,+ message: `${selected} cannot be used in ${slot}.`+ });+ }+ if (!resource.recipeIds.includes(value.id)) {+ issues.push({+ code: "RESOURCE_RECIPE_MISMATCH",+ path: `overrides.textureResources.${slot}`,+ message: `${selected} is not approved for ${value.id}.`+ });+ }+ }+ }+ }+ }+ if (issues.length > 0)+ return { valid: false, issues };+ return {+ valid: true,+ value: cloneMaterialRecipeRequestV1(value),+ issues+ };+}+function cloneMaterialRecipeRequestV1(value) {+ return {+ schemaVersion: 1,+ id: value.id,+ ...value.overrides ? {+ overrides: {+ ...value.overrides,+ ...value.overrides.textureResources ? { textureResources: { ...value.overrides.textureResources } } : {}+ }+ } : {}+ };+}+function createMaterialRecipeRequestV1(id, overrides) {+ const candidate = { schemaVersion: 1, id, ...overrides ? { overrides } : {} };+ const result = validateMaterialRecipeRequestV1(candidate);+ if (!result.valid || !result.value) {+ throw new TypeError(result.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; "));+ }+ return result.value;+}+function resolveMaterialRecipeV1(value) {+ const validation = validateMaterialRecipeRequestV1(value);+ if (!validation.valid || !validation.value) {+ throw new TypeError(validation.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; "));+ }+ const recipe = MATERIAL_RECIPE_LIBRARY_V1[validation.value.id];+ const over = validation.value.overrides ?? {};+ const baseAlpha = over.opacity ?? recipe.defaults.baseColorFactor[3];+ const baseColorFactor = over.baseColor ? rgba(over.baseColor, baseAlpha) : Object.freeze([+ recipe.defaults.baseColorFactor[0],+ recipe.defaults.baseColorFactor[1],+ recipe.defaults.baseColorFactor[2],+ baseAlpha+ ]);+ const emissiveIntensity = over.emissiveIntensity;+ const emissiveFactor = over.emissiveColor ? rgb(over.emissiveColor, over.emissiveIntensity ?? 1) : emissiveIntensity !== undefined ? Object.freeze(recipe.defaults.emissiveFactor.map((component) => component * emissiveIntensity)) : recipe.defaults.emissiveFactor;+ return Object.freeze({+ baseColorFactor,+ metallicFactor: over.metalness ?? recipe.defaults.metallicFactor,+ roughnessFactor: over.roughness ?? recipe.defaults.roughnessFactor,+ emissiveFactor,+ alphaMode: recipe.defaults.alphaMode,+ ...recipe.defaults.alphaMode === "MASK" ? { alphaCutoff: over.alphaCutoff ?? recipe.defaults.alphaCutoff ?? 0.5 } : {},+ doubleSided: over.doubleSided ?? recipe.defaults.doubleSided,+ textureResources: Object.freeze({+ ...recipe.defaults.textureResources,+ ...over.textureResources ?? {}+ })+ });+}+var MATERIAL_RECIPE_IDS, MATERIAL_RECIPE_OVERRIDE_KEYS, APPROVED_TEXTURE_RESOURCE_IDS, MATERIAL_TEXTURE_SLOTS, srgbChannelToLinear2 = (value) => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4, rgba = (hex, alpha = 1) => {+ const normalized = hex.replace(/^#/, "");+ return Object.freeze([+ srgbChannelToLinear2(Number.parseInt(normalized.slice(0, 2), 16) / 255),+ srgbChannelToLinear2(Number.parseInt(normalized.slice(2, 4), 16) / 255),+ srgbChannelToLinear2(Number.parseInt(normalized.slice(4, 6), 16) / 255),+ alpha+ ]);+}, rgb = (hex, intensity = 1) => {+ const color = rgba(hex);+ return Object.freeze([+ color[0] * intensity,+ color[1] * intensity,+ color[2] * intensity+ ]);+}, defaults = (baseColor, roughnessFactor, metallicFactor = 0, over = {}) => Object.freeze({+ baseColorFactor: rgba(baseColor),+ metallicFactor,+ roughnessFactor,+ emissiveFactor: Object.freeze([0, 0, 0]),+ alphaMode: "OPAQUE",+ doubleSided: false,+ textureResources: Object.freeze({}),+ ...over+}), commonSurface, descriptor = (value) => Object.freeze({+ schemaVersion: 1,+ version: 1,+ portable: true,+ gltfMaterialModel: "pbrMetallicRoughness",+ ...value+}), MATERIAL_RECIPE_LIBRARY_V1, APPROVED_TEXTURE_RESOURCES_V1, isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), recipeId = (value) => typeof value === "string" && MATERIAL_RECIPE_IDS.includes(value), resourceId = (value) => typeof value === "string" && APPROVED_TEXTURE_RESOURCE_IDS.includes(value), finiteUnit = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1, hexColor = (value) => typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value);+var init_material_recipes = __esm(() => {+ init_material_texture_library_generated();+ MATERIAL_RECIPE_IDS = [+ "kiln.material.bark.v1",+ "kiln.material.leaf.v1",+ "kiln.material.wood.v1",+ "kiln.material.stone.v1",+ "kiln.material.rubber.v1",+ "kiln.material.painted-metal.v1",+ "kiln.material.cloth.v1",+ "kiln.material.skin.v1",+ "kiln.material.glass.v1",+ "kiln.material.emissive.v1"+ ];+ MATERIAL_RECIPE_OVERRIDE_KEYS = [+ "baseColor",+ "roughness",+ "metalness",+ "opacity",+ "alphaCutoff",+ "doubleSided",+ "emissiveColor",+ "emissiveIntensity",+ "textureResources"+ ];+ APPROVED_TEXTURE_RESOURCE_IDS = [+ "kiln.texture.bark-albedo.v1",+ "kiln.texture.leaf-mask-albedo.v1",+ "kiln.texture.neutral-normal.v1",+ "kiln.texture.neutral-metallic-roughness.v1",+ "kiln.texture.emissive-grid.v1",+ ...PRODUCTION_TEXTURE_RESOURCE_IDS+ ];+ MATERIAL_TEXTURE_SLOTS = [+ "baseColor",+ "normal",+ "metallicRoughness",+ "emissive",+ "occlusion"+ ];+ commonSurface = Object.freeze([+ "baseColor",+ "roughness",+ "metalness",+ "doubleSided",+ "textureResources"+ ]);+ MATERIAL_RECIPE_LIBRARY_V1 = Object.freeze({+ "kiln.material.bark.v1": descriptor({+ id: "kiln.material.bark.v1",+ name: "Bark",+ description: "Rough, nonmetal tree bark with optional approved albedo and normal resources.",+ allowedOverrides: commonSurface,+ defaults: defaults("#6b4426", 0.93)+ }),+ "kiln.material.leaf.v1": descriptor({+ id: "kiln.material.leaf.v1",+ name: "Leaf",+ description: "Alpha-tested, double-sided foliage using glTF MASK rather than blending.",+ allowedOverrides: Object.freeze([+ "baseColor",+ "roughness",+ "alphaCutoff",+ "doubleSided",+ "textureResources"+ ]),+ defaults: defaults("#3f7f3a", 0.86, 0, {+ alphaMode: "MASK",+ alphaCutoff: 0.5,+ doubleSided: true+ })}),- "kiln.texture.forest-leaves-arm.v1": Object.freeze({- sourceAsset: "forest_leaves_03",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/forest_leaves_03/forest_leaves_03_arm_1k.jpg",- sourceMd5: "cee4ef6c48848ffa09f818ab86367eab",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.material.wood.v1": descriptor({+ id: "kiln.material.wood.v1",+ name: "Wood",+ description: "Portable nonmetal wood with a warm authored base color.",+ allowedOverrides: commonSurface,+ defaults: defaults("#9a6a3a", 0.78)}),- "kiln.texture.rubber-tiles-albedo.v1": Object.freeze({- sourceAsset: "rubber_tiles",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/rubber_tiles/rubber_tiles_diff_1k.jpg",- sourceMd5: "2a2cc9b5e06639c7fb6cc26c263c00ff",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.material.stone.v1": descriptor({+ id: "kiln.material.stone.v1",+ name: "Stone",+ description: "Dry rough stone with no runtime shader dependency.",+ allowedOverrides: commonSurface,+ defaults: defaults("#7d7a74", 0.95)}),- "kiln.texture.rubber-tiles-normal.v1": Object.freeze({- sourceAsset: "rubber_tiles",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/rubber_tiles/rubber_tiles_nor_gl_1k.jpg",- sourceMd5: "4ed5fac176252df9dde7d0fbf8a9b76d",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.material.rubber.v1": descriptor({+ id: "kiln.material.rubber.v1",+ name: "Rubber",+ description: "Dark, high-roughness rubber for tires, grips, and seals.",+ allowedOverrides: commonSurface,+ defaults: defaults("#202124", 0.88)}),- "kiln.texture.rubber-tiles-arm.v1": Object.freeze({- sourceAsset: "rubber_tiles",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/rubber_tiles/rubber_tiles_arm_1k.jpg",- sourceMd5: "8b7e2c4a9851564b8e701b450df9abc9",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.material.painted-metal.v1": descriptor({+ id: "kiln.material.painted-metal.v1",+ name: "Painted metal",+ description: "Coated metal with restrained metallic response and a durable painted finish.",+ allowedOverrides: commonSurface,+ defaults: defaults("#b33a32", 0.38, 0.18)}),- "kiln.texture.metal-plate-albedo.v1": Object.freeze({- sourceAsset: "metal_plate",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/metal_plate/metal_plate_diff_1k.jpg",- sourceMd5: "bd9daf4c04046ca392a38b8df955ed26",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.material.cloth.v1": descriptor({+ id: "kiln.material.cloth.v1",+ name: "Cloth",+ description: "Very rough, nonmetal woven cloth represented with core glTF PBR.",+ allowedOverrides: commonSurface,+ defaults: defaults("#6f7583", 1)}),- "kiln.texture.metal-plate-normal.v1": Object.freeze({- sourceAsset: "metal_plate",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/metal_plate/metal_plate_nor_gl_1k.jpg",- sourceMd5: "d379e66130ad6ccff217ac9b13de935d",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.material.skin.v1": descriptor({+ id: "kiln.material.skin.v1",+ name: "Skin",+ description: "Portable skin baseline without nonstandard subsurface extensions.",+ allowedOverrides: Object.freeze(["baseColor", "roughness", "doubleSided"]),+ defaults: defaults("#b87962", 0.62)}),- "kiln.texture.metal-plate-arm.v1": Object.freeze({- sourceAsset: "metal_plate",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/metal_plate/metal_plate_arm_1k.jpg",- sourceMd5: "13f064ffa4863a4170d902f675eb022e",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.material.glass.v1": descriptor({+ id: "kiln.material.glass.v1",+ name: "Glass",+ description: "Portable alpha-blended glass fallback using core glTF fields only.",+ allowedOverrides: Object.freeze(["baseColor", "roughness", "opacity", "doubleSided"]),+ defaults: defaults("#a9d8e8", 0.12, 0, {+ baseColorFactor: rgba("#a9d8e8", 0.32),+ alphaMode: "BLEND",+ doubleSided: true+ })}),- "kiln.texture.clay-roof-tiles-albedo.v1": Object.freeze({- sourceAsset: "clay_roof_tiles",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/clay_roof_tiles/clay_roof_tiles_diff_1k.jpg",- sourceMd5: "d862ac9932b09b0918b5971ddb77099c",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.material.emissive.v1": descriptor({+ id: "kiln.material.emissive.v1",+ name: "Emissive",+ description: "Core glTF emissive material with intensity baked into emissiveFactor.",+ allowedOverrides: Object.freeze([+ "baseColor",+ "roughness",+ "doubleSided",+ "emissiveColor",+ "emissiveIntensity",+ "textureResources"+ ]),+ defaults: defaults("#3a2410", 0.5, 0, {+ emissiveFactor: rgb("#ff8a22", 1)+ })+ })+ });+ APPROVED_TEXTURE_RESOURCES_V1 = Object.freeze({+ "kiln.texture.bark-albedo.v1": Object.freeze({+ schemaVersion: 1,+ id: "kiln.texture.bark-albedo.v1",+ version: 1,+ label: "Bark albedo reference",+ usage: "albedo",+ colorSpace: "srgb",+ mime: "image/png",+ contentHash: "ec74fd42fe317f578018a13a65d81a726e9baeade068ae016cff30c15507017f",+ delivery: "embedded",+ quality: "placeholder",+ byteLength: 100,+ license: Object.freeze({+ spdx: "CC0-1.0",+ attribution: "",+ source: "authored in-repo"+ }),+ allowedSlots: Object.freeze(["baseColor"]),+ recipeIds: Object.freeze(["kiln.material.bark.v1", "kiln.material.wood.v1"])}),- "kiln.texture.clay-roof-tiles-normal.v1": Object.freeze({- sourceAsset: "clay_roof_tiles",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/clay_roof_tiles/clay_roof_tiles_nor_gl_1k.jpg",- sourceMd5: "d861a708c94c824befc8aac668052776",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.texture.leaf-mask-albedo.v1": Object.freeze({+ schemaVersion: 1,+ id: "kiln.texture.leaf-mask-albedo.v1",+ version: 1,+ label: "Leaf alpha-mask albedo reference",+ usage: "albedo",+ colorSpace: "srgb",+ mime: "image/png",+ contentHash: "ae9ad7f5389529a42fd9e63cb16aa7dc2c803739953242422b0ccc8003bd827c",+ delivery: "embedded",+ quality: "placeholder",+ byteLength: 119,+ license: Object.freeze({+ spdx: "CC0-1.0",+ attribution: "",+ source: "authored in-repo"+ }),+ allowedSlots: Object.freeze(["baseColor"]),+ recipeIds: Object.freeze(["kiln.material.leaf.v1"])}),- "kiln.texture.clay-roof-tiles-arm.v1": Object.freeze({- sourceAsset: "clay_roof_tiles",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/clay_roof_tiles/clay_roof_tiles_arm_1k.jpg",- sourceMd5: "1c85df2500d6d9ae720cad193e3a4cec",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.texture.neutral-normal.v1": Object.freeze({+ schemaVersion: 1,+ id: "kiln.texture.neutral-normal.v1",+ version: 1,+ label: "Neutral tangent-space normal",+ usage: "normal",+ colorSpace: "linear",+ mime: "image/png",+ contentHash: "2be025139faed13fb12ac50101f7d91f8a758ce6a668104a7e8003eccdab7db7",+ delivery: "embedded",+ quality: "placeholder",+ byteLength: 95,+ license: Object.freeze({+ spdx: "CC0-1.0",+ attribution: "",+ source: "authored in-repo"+ }),+ allowedSlots: Object.freeze(["normal"]),+ recipeIds: Object.freeze([+ "kiln.material.bark.v1",+ "kiln.material.wood.v1",+ "kiln.material.stone.v1",+ "kiln.material.rubber.v1",+ "kiln.material.painted-metal.v1",+ "kiln.material.cloth.v1"+ ])}),- "kiln.texture.cobblestone-floor-albedo.v1": Object.freeze({- sourceAsset: "cobblestone_floor_01",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/cobblestone_floor_01/cobblestone_floor_01_diff_1k.jpg",- sourceMd5: "ef7a4b9314ccd7f11ea07a06b81e515a",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.texture.neutral-metallic-roughness.v1": Object.freeze({+ schemaVersion: 1,+ id: "kiln.texture.neutral-metallic-roughness.v1",+ version: 1,+ label: "Packed roughness-metalness reference",+ usage: "metallicRoughness",+ colorSpace: "linear",+ mime: "image/png",+ contentHash: "5e03d1e2863800c5f1a88411dd4447ccc0ec8470232129d8682db8f6ea76ad52",+ delivery: "embedded",+ quality: "placeholder",+ byteLength: 94,+ license: Object.freeze({+ spdx: "CC0-1.0",+ attribution: "",+ source: "authored in-repo"+ }),+ allowedSlots: Object.freeze(["metallicRoughness"]),+ recipeIds: Object.freeze([+ "kiln.material.rubber.v1",+ "kiln.material.painted-metal.v1"+ ])}),- "kiln.texture.cobblestone-floor-normal.v1": Object.freeze({- sourceAsset: "cobblestone_floor_01",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/cobblestone_floor_01/cobblestone_floor_01_nor_gl_1k.jpg",- sourceMd5: "25994f0cbfefb6a4be0e0a349fa8c3ea",- transform: "sharp 128x128 Lanczos3 PNG"+ "kiln.texture.emissive-grid.v1": Object.freeze({+ schemaVersion: 1,+ id: "kiln.texture.emissive-grid.v1",+ version: 1,+ label: "Emissive grid reference",+ usage: "emissive",+ colorSpace: "srgb",+ mime: "image/png",+ contentHash: "a0b2f4e243ec0ec914b80d4998cf4624ff68181aafc4b97a6bafa765a41e4814",+ delivery: "embedded",+ quality: "placeholder",+ byteLength: 100,+ license: Object.freeze({+ spdx: "CC0-1.0",+ attribution: "",+ source: "authored in-repo"+ }),+ allowedSlots: Object.freeze(["emissive"]),+ recipeIds: Object.freeze(["kiln.material.emissive.v1"])}),- "kiln.texture.cobblestone-floor-arm.v1": Object.freeze({- sourceAsset: "cobblestone_floor_01",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/cobblestone_floor_01/cobblestone_floor_01_arm_1k.jpg",- sourceMd5: "80591b98c4d3126e006b32806424d541",- transform: "sharp 128x128 Lanczos3 PNG"+ ...PRODUCTION_TEXTURE_RESOURCE_DESCRIPTORS_V1+ });+});++// src/material-resources.ts+import { createHash as createHash3 } from "node:crypto";+function provenance(descriptor, hash) {+ return {+ schemaVersion: 1,+ resourceId: descriptor.id,+ contentHash: hash,+ hashAlgorithm: "sha256",+ usage: descriptor.usage,+ colorSpace: descriptor.colorSpace,+ resourceVersion: descriptor.version,+ recipeVersion: 1,+ delivery: descriptor.delivery+ };+}+function readPngDimensions(descriptor, bytes) {+ const signature = [137, 80, 78, 71, 13, 10, 26, 10];+ if (bytes.byteLength < 24 || !signature.every((value, index) => bytes[index] === value) || String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR") {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "declared image/png bytes do not have a valid PNG signature and IHDR format");+ }+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ return { width: view.getUint32(16, false), height: view.getUint32(20, false) };+}+function verifyResourcePayload(descriptor, payload) {+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host payload must be { bytes, mime }");+ }+ const keys = Object.keys(payload).sort();+ if (keys.length !== 2 || keys[0] !== "bytes" || keys[1] !== "mime") {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host payload must contain only bytes and MIME");+ }+ if (!(payload.bytes instanceof Uint8Array)) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, "host bytes must be Uint8Array");+ }+ if (payload.mime !== descriptor.mime) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `host MIME ${String(payload.mime)} does not match approved ${descriptor.mime}`);+ }+ const bytes = payload.bytes;+ if (bytes.byteLength > TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `encoded-byte limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes}; received ${bytes.byteLength}`);+ }+ if (bytes.byteLength !== descriptor.byteLength) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `expected ${descriptor.byteLength} bytes, received ${bytes.byteLength}`);+ }+ const { width, height } = readPngDimensions(descriptor, bytes);+ if (width < 1 || height < 1 || width > TEXTURE_RESOLVER_LIMITS_V1.maxWidth || height > TEXTURE_RESOLVER_LIMITS_V1.maxHeight) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `dimension limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxWidth}x${TEXTURE_RESOLVER_LIMITS_V1.maxHeight}; received ${width}x${height}`);+ }+ const pixels = width * height;+ if (!Number.isSafeInteger(pixels) || pixels > TEXTURE_RESOLVER_LIMITS_V1.maxPixels) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`);+ }+ const hash = sha256(bytes);+ if (hash !== descriptor.contentHash) {+ throw new ApprovedTextureResourceUnavailableError(descriptor.id, `content hash ${hash} does not match the pinned ${descriptor.contentHash}`);+ }+ return hash;+}++class ApprovedTextureResourceCache {+ #bytesByHash = new Map;+ #hashById = new Map;+ #textureByVariant = new Map;+ #pendingById = new Map;+ #registry;+ #resolver;+ #resolverDeadlineMs;+ constructor(options = {}) {+ this.#resolver = options.resolver;+ this.#registry = options.registry ?? APPROVED_TEXTURE_RESOURCES_V1;+ const deadline = options.resolverDeadlineMs ?? TEXTURE_RESOLVER_LIMITS_V1.defaultDeadlineMs;+ if (!Number.isFinite(deadline) || deadline < 1 || deadline > TEXTURE_RESOLVER_LIMITS_V1.maxDeadlineMs) {+ throw new RangeError(`resolverDeadlineMs must be in [1,${TEXTURE_RESOLVER_LIMITS_V1.maxDeadlineMs}]`);+ }+ this.#resolverDeadlineMs = deadline;+ }+ setResolver(resolver) {+ const previous = this.#resolver;+ this.#resolver = resolver;+ return previous;+ }+ descriptor(id) {+ if (!isApprovedId(id))+ throw new RangeError(`Unsupported approved texture resource ID ${id}.`);+ return this.#registry[id];+ }+ available(id) {+ if (!isApprovedId(id))+ return false;+ return this.#registry[id].delivery === "embedded" || this.#resolver !== undefined;+ }+ #cacheBytes(id, hash, bytes) {+ let canonical = this.#bytesByHash.get(hash);+ if (!canonical) {+ canonical = bytes;+ this.#bytesByHash.set(hash, canonical);+ }+ this.#hashById.set(id, hash);+ return canonical;+ }+ #resolution(id, hash) {+ const canonical = this.#bytesByHash.get(hash);+ if (!canonical)+ throw new Error(`Approved resource cache lost content ${hash}.`);+ return {+ descriptor: this.#registry[id],+ bytes: canonical.slice(),+ provenance: provenance(this.#registry[id], hash)+ };+ }+ resolve(id) {+ if (!isApprovedId(id))+ throw new RangeError(`Unsupported approved texture resource ID ${id}.`);+ const hash = this.#hashById.get(id);+ if (hash)+ return this.#resolution(id, hash);+ const descriptor = this.#registry[id];+ if (descriptor.delivery !== "embedded") {+ throw new ApprovedTextureResourceUnavailableError(id, "it is delivered at runtime; use resolveAsync() or load()");+ }+ const decoded = bytesFromBase64(EMBEDDED_RESOURCE_BASE64[id]);+ this.#cacheBytes(id, verifyResourcePayload(descriptor, { bytes: decoded, mime: descriptor.mime }), decoded);+ return this.#resolution(id, this.#hashById.get(id));+ }+ async resolveAsync(id) {+ if (!isApprovedId(id))+ throw new RangeError(`Unsupported approved texture resource ID ${id}.`);+ const hash = this.#hashById.get(id);+ if (hash)+ return this.#resolution(id, hash);+ if (this.#registry[id].delivery === "embedded")+ return this.resolve(id);+ let pending = this.#pendingById.get(id);+ if (!pending) {+ const descriptor = this.#registry[id];+ const resolver = this.#resolver;+ pending = (async () => {+ if (!resolver) {+ throw new ApprovedTextureResourceUnavailableError(id, "no runtime texture resolver is registered in this environment");+ }+ const controller = new AbortController;+ let timer;+ const timeout = new Promise((_resolve, reject) => {+ timer = setTimeout(() => {+ controller.abort();+ reject(new ApprovedTextureResourceUnavailableError(id, `host resolver deadline exceeded after ${this.#resolverDeadlineMs}ms`));+ }, this.#resolverDeadlineMs);+ });+ let payload;+ try {+ payload = await Promise.race([+ Promise.resolve().then(() => resolver(descriptor, Object.freeze({+ signal: controller.signal,+ deadlineMs: this.#resolverDeadlineMs+ }))),+ timeout+ ]);+ } finally {+ if (timer !== undefined)+ clearTimeout(timer);+ }+ this.#cacheBytes(id, verifyResourcePayload(descriptor, payload), payload.bytes);+ return this.#resolution(id, this.#hashById.get(id));+ })().finally(() => {+ this.#pendingById.delete(id);+ });+ this.#pendingById.set(id, pending);+ }+ return pending;+ }+ async load(id) {+ const resolved = await this.resolveAsync(id);+ const variantKey = [+ resolved.provenance.contentHash,+ resolved.provenance.usage,+ resolved.provenance.colorSpace+ ].join(":");+ let pending = this.#textureByVariant.get(variantKey);+ if (!pending) {+ pending = loadTexture(resolved.bytes, {+ usage: resolved.provenance.usage,+ name: id+ }).then((texture) => {+ const metadata = texture.userData["kilnTexture"];+ texture.userData["kilnTexture"] = {+ ...metadata,+ approvedResource: resolved.provenance+ };+ return texture;+ });+ this.#textureByVariant.set(variantKey, pending);+ }+ return { ...resolved, texture: await pending };+ }+ stats() {+ return {+ approvedIdsResolved: this.#hashById.size,+ uniqueContentHashes: this.#bytesByHash.size,+ decodedTextureVariants: this.#textureByVariant.size,+ encodedBytes: [...this.#bytesByHash.values()].reduce((sum, bytes) => sum + bytes.byteLength, 0)+ };+ }+}+function readMaterialResourceProvenance(texture) {+ const metadata = texture.userData["kilnTexture"];+ return metadata?.approvedResource;+}+function sceneNeedsPbrShading(root) {+ let needs = false;+ root.traverse((node) => {+ if (needs)+ return;+ const material = node.material;+ const materials = Array.isArray(material) ? material : material ? [material] : [];+ for (const item of materials) {+ if (materialTextures(item).length > 0) {+ needs = true;+ return;+ }+ const metalness = item.metalness;+ if (typeof metalness === "number" && metalness > 0) {+ needs = true;+ return;+ }+ }+ });+ return needs;+}+function collectMaterialResourceProvenance(root) {+ const records = new Map;+ root.traverse((node) => {+ const material = node.material;+ const materials = Array.isArray(material) ? material : material ? [material] : [];+ for (const item of materials) {+ for (const texture of materialTextures(item)) {+ const record = readMaterialResourceProvenance(texture);+ if (record)+ records.set(`${record.resourceId}:${record.contentHash}:${record.usage}`, record);+ }+ }+ });+ return [...records.values()].sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));+}+var TEXTURE_RESOLVER_LIMITS_V1, ApprovedTextureResourceUnavailableError, EMBEDDED_RESOURCE_BASE64, isApprovedId = (value) => APPROVED_TEXTURE_RESOURCE_IDS.includes(value), bytesFromBase64 = (value) => new Uint8Array(Buffer.from(value, "base64")), sha256 = (bytes) => createHash3("sha256").update(bytes).digest("hex"), DEFAULT_APPROVED_TEXTURE_CACHE, materialTextures = (material) => {+ const standard = material;+ const candidates = [+ standard.map,+ standard.normalMap,+ standard.roughnessMap,+ standard.metalnessMap,+ standard.emissiveMap,+ standard.aoMap+ ];+ return [+ ...new Set(candidates.filter((value) => value?.isTexture === true))+ ];+};+var init_material_resources = __esm(() => {+ init_material_recipes();+ init_material_texture_library_generated();+ init_textures();+ TEXTURE_RESOLVER_LIMITS_V1 = Object.freeze({+ maxEncodedBytes: 8 * 1024 * 1024,+ maxWidth: 4096,+ maxHeight: 4096,+ maxPixels: 8 * 1024 * 1024,+ defaultDeadlineMs: 5000,+ maxDeadlineMs: 30000+ });+ ApprovedTextureResourceUnavailableError = class ApprovedTextureResourceUnavailableError extends Error {+ resourceId;+ constructor(id, reason) {+ super(`Approved texture resource ${id} is unavailable: ${reason}`);+ this.name = "ApprovedTextureResourceUnavailableError";+ this.resourceId = id;+ }+ };+ EMBEDDED_RESOURCE_BASE64 = Object.freeze({+ "kiln.texture.bark-albedo.v1": "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAFklEQVQImWMIMpT6X+Ch9h9GM5AuAACfBRvJB4zLLQAAAABJRU5ErkJggg==",+ "kiln.texture.leaf-mask-albedo.v1": "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAKUlEQVQImWMwaLFiMGixSjBosdoCYsM4/6E4ASQAkoEJbAEJwARBKhkACRMXLR+u+yUAAAAASUVORK5CYII=",+ "kiln.texture.neutral-normal.v1": "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEUlEQVQImWNoaPj/H4QZYAwAZ9IL+W19YCAAAAAASUVORK5CYII=",+ "kiln.texture.neutral-metallic-roughness.v1": "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEElEQVQImWNguCT0H4xhDAA/hAeNGSjqWAAAAABJRU5ErkJggg==",+ "kiln.texture.emissive-grid.v1": "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAFklEQVQImWP4P0Hhv4MEy38GEAHiAABG+wgTqOP6IAAAAABJRU5ErkJggg==",+ ...PRODUCTION_TEXTURE_RESOURCE_BASE64+ });+ DEFAULT_APPROVED_TEXTURE_CACHE = new ApprovedTextureResourceCache;+});++// src/portable-material-runtime.ts+async function compilePortableMaterialSpecV2(input) {+ const spec = canonicalizePortableMaterialSpecV2(input);+ const cache = DEFAULT_APPROVED_TEXTURE_CACHE;+ const entries = Object.entries(spec.textures);+ for (const [slot, ref] of entries) {+ if (ref.kind !== "resource")+ continue;+ if (!isApprovedResourceId(ref.resourceId)) {+ throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not an approved texture resource ID.`);+ }+ const descriptor = cache.descriptor(ref.resourceId);+ if (!descriptor.allowedSlots.includes(slot)) {+ throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not approved for that slot.`);+ }+ if (descriptor.usage !== SLOT_USAGE[slot]) {+ throw new ProceduralTextureError(`portableMaterial.textures.${slot} requires ${SLOT_USAGE[slot]} data, but ${JSON.stringify(ref.resourceId)} provides ${descriptor.usage}.`);+ }+ }+ const loaded = new Map;+ await Promise.all(entries.map(async ([slot, ref]) => {+ const texture = ref.kind === "procedural" ? proceduralTexture(ref.spec) : (await cache.load(ref.resourceId)).texture;+ loaded.set(slot, texture);+ }));+ const materialOptions = {+ roughness: spec.roughness,+ metalness: spec.metalness,+ emissiveIntensity: spec.emissiveIntensity,+ alphaMode: spec.alphaMode,+ ...spec.alphaMode === "mask" ? { alphaCutoff: spec.alphaCutoff } : {},+ doubleSided: spec.doubleSided,+ ...loaded.get("baseColor") ? { albedo: loaded.get("baseColor") } : spec.baseColor !== undefined ? { albedo: spec.baseColor } : {},+ ...loaded.get("normal") ? { normal: loaded.get("normal") } : {},+ ...loaded.get("metallicRoughness") ? { metallicRoughness: loaded.get("metallicRoughness") } : {},+ ...loaded.get("emissive") ? { emissive: loaded.get("emissive") } : spec.emissive !== undefined ? { emissive: spec.emissive } : {},+ ...loaded.get("occlusion") ? { aoMap: loaded.get("occlusion") } : {}+ };+ const material = pbrMaterial(materialOptions);+ if (spec.name)+ material.name = spec.name;+ if (loaded.has("baseColor") && spec.baseColor !== undefined)+ material.color.setHex(spec.baseColor);+ if (loaded.has("emissive") && spec.emissive !== undefined)+ material.emissive.setHex(spec.emissive);+ material.userData["kilnPortableMaterial"] = spec;+ return material;+}+var SLOT_USAGE, isApprovedResourceId = (value) => APPROVED_TEXTURE_RESOURCE_IDS.includes(value);+var init_portable_material_runtime = __esm(() => {+ init_material_recipes();+ init_material_resources();+ init_procedural_material_v2();+ init_procedural_texture();+ init_textures();+ SLOT_USAGE = {+ baseColor: "albedo",+ normal: "normal",+ metallicRoughness: "metallicRoughness",+ emissive: "emissive",+ occlusion: "occlusion"+ };+});++// src/vehicle.ts+import * as THREE11 from "three";+function assertId(value, name) {+ if (!ID_PATTERN.test(value))+ throw new TypeError(`${name} must be a stable identifier`);+ return value;+}+function positive2(value, name) {+ if (!Number.isFinite(value) || value <= 0)+ throw new RangeError(`${name} must be finite and > 0`);+ return value;+}+function normalizedQuaternion(value) {+ const source = value ?? [0, 0, 0, 1];+ const length = Math.hypot(source[0], source[1], source[2], source[3]);+ if (!Number.isFinite(length) || length <= 0.000000001)+ throw new TypeError("socket rotation must be a finite quaternion");+ return [source[0] / length, source[1] / length, source[2] / length, source[3] / length];+}+function semantic2(roles, options = {}) {+ return {+ roles,+ relationships: options.relationships ?? [],+ frames: options.frames ?? [],+ sockets: options.sockets ?? []+ };+}+function socketRole(kind, id) {+ if (kind === "chassis")+ return KILN_SEMANTIC_ROLES.chassisMain;+ return semanticRole(SOCKET_ROLE_BASE[kind], id);+}+function createTypedSocket(kind, input, parent) {+ const id = assertId(input.id, `${kind} socket id`);+ if (!input.position.every(Number.isFinite))+ throw new TypeError(`${kind}.${id} position must be finite`);+ const rotation = normalizedQuaternion(input.rotation);+ const node = new THREE11.Object3D;+ node.name = `Socket_${kind}_${id}`;+ node.position.set(...input.position);+ node.quaternion.set(...rotation);+ const socket = {+ id,+ type: `vehicle.${kind}`,+ frame: "socket",+ compatibleTypes: [...input.compatibleTypes ?? [`vehicle.${kind}`]]+ };+ stampSemanticMetadataV1(node, semantic2([semanticRole(KILN_SEMANTIC_ROLES.socket, kind, id), socketRole(kind, id)], {+ frames: [{ id: "socket", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ sockets: [socket],+ relationships: [+ { kind: "owned-by", target: KILN_SEMANTIC_ROLES.vehicleFrame, targetType: "role" }+ ]+ }));+ parent.add(node);+ return node;+}+function createVehicleFrame(name, options = {}) {+ const root = new THREE11.Object3D;+ root.name = name;+ stampSemanticMetadataV1(root, semantic2([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {+ frames: [+ { id: "origin", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: "forward.+x", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: "up.+y", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: "right.+z", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }+ ]+ }));+ if (options.parent)+ options.parent.add(root);+ const chassis = createTypedSocket("chassis", options.chassis ?? { id: "main", position: [0, 0, 0] }, root);+ const build = (kind, values) => (values ?? []).map((value) => createTypedSocket(kind, value, root));+ return {+ root,+ chassis,+ axles: build("axle", options.axles),+ seats: build("seat", options.seats),+ contacts: build("contact", options.contacts),+ steering: build("steering", options.steering),+ propulsion: build("propulsion", options.propulsion)+ };+}+function cylinderZ(radius, width, segments = 16) {+ const geometry = new THREE11.CylinderGeometry(radius, radius, width, segments);+ geometry.rotateX(Math.PI / 2);+ return geometry;+}+function createWheelGeometrySet(radius, width) {+ positive2(radius, "radius");+ positive2(width, "width");+ if (width >= radius * 2)+ throw new RangeError("wheel width must be less than its diameter");+ const tube = width / 2;+ return {+ tire: new THREE11.TorusGeometry(radius - tube, tube, 8, 20),+ rim: cylinderZ(radius * 0.68, width * 0.8),+ hub: cylinderZ(radius * 0.34, width * 0.94)+ };+}+function createWheelAssembly(name, materials, options) {+ const radius = positive2(options.radius, "radius");+ const width = positive2(options.width, "width");+ const rimRadius = positive2(options.rimRadius ?? radius * 0.68, "rimRadius");+ const hubRadius = positive2(options.hubRadius ?? radius * 0.34, "hubRadius");+ const rimWidth = positive2(options.rimWidth ?? width * 0.8, "rimWidth");+ const hubWidth = positive2(options.hubWidth ?? width * 0.94, "hubWidth");+ if (rimRadius >= radius || hubRadius >= rimRadius)+ throw new RangeError("wheel radii must satisfy hub < rim < tire");+ if (rimWidth > width || hubWidth > width)+ throw new RangeError("rim/hub width must not exceed tire width");+ const index = assertId(String(options.index), "wheel index");+ const key = `${options.side}.${index}`;+ const parent = options.parent;+ const root = new THREE11.Object3D;+ root.name = `${name}_Assembly_${options.side}_${index}`;+ let steeringPivot;+ if (options.steering) {+ steeringPivot = new THREE11.Object3D;+ steeringPivot.name = `SteeringPivot_${options.side}_${index}`;+ steeringPivot.position.set(...options.position ?? [0, 0, 0]);+ stampSemanticMetadataV1(steeringPivot, semantic2([semanticRole(ROLE.steeringPivot, key)], {+ frames: [{ id: "steering-axis.+y", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ relationships: [+ { kind: "steers", target: semanticRole(ROLE.wheelAssembly, key), targetType: "role" }+ ]+ }));+ root.add(steeringPivot);+ }+ const spinPivot = new THREE11.Object3D;+ spinPivot.name = `WheelPivot_${options.side}_${index}`;+ if (!steeringPivot)+ spinPivot.position.set(...options.position ?? [0, 0, 0]);+ stampSemanticMetadataV1(spinPivot, semantic2([+ semanticRole(ROLE.wheelAssembly, key),+ semanticRole(ROLE.wheelPivot, key),+ ...options.loadBearing === false ? [] : [semanticRole(ROLE.wheelLoadBearing, key)]+ ], {+ frames: [+ { id: "axle-center", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: "spin-axis.+z", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }+ ],+ relationships: [+ { kind: "mounted-on", target: semanticRole(ROLE.axle, index), targetType: "role" },+ { kind: "contains", target: semanticRole(ROLE.wheelTire, key), targetType: "role" },+ { kind: "contains", target: semanticRole(ROLE.wheelRim, key), targetType: "role" },+ { kind: "contains", target: semanticRole(ROLE.wheelHub, key), targetType: "role" }+ ]+ }));+ (steeringPivot ?? root).add(spinPivot);+ const defaults = createWheelGeometrySet(radius, width);+ const tire = new THREE11.Mesh(options.geometries?.tire ?? defaults.tire, materials.tire);+ const rim = new THREE11.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);+ const hub = new THREE11.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);+ tire.name = `Tire_${options.side}_${index}`;+ rim.name = `Rim_${options.side}_${index}`;+ hub.name = `Hub_${options.side}_${index}`;+ stampSemanticMetadataV1(tire, semantic2([semanticRole(ROLE.wheelTire, key)], {+ relationships: [+ { kind: "descends-from", target: semanticRole(ROLE.wheelPivot, key), targetType: "role" }+ ]+ }));+ stampSemanticMetadataV1(rim, semantic2([semanticRole(ROLE.wheelRim, key)], {+ relationships: [+ { kind: "contained-by", target: semanticRole(ROLE.wheelTire, key), targetType: "role" }+ ]+ }));+ stampSemanticMetadataV1(hub, semantic2([semanticRole(ROLE.wheelHub, key)], {+ relationships: [+ { kind: "contained-by", target: semanticRole(ROLE.wheelRim, key), targetType: "role" }+ ]+ }));+ spinPivot.add(tire, rim, hub);+ const contact = new THREE11.Object3D;+ contact.name = `Contact_${options.side}_${index}`;+ contact.position.y = -radius;+ stampSemanticMetadataV1(contact, semantic2([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {+ frames: [{ id: "contact", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ relationships: [{ kind: "supports", target: ROLE.vehicleFrame, targetType: "role" }]+ }));+ spinPivot.add(contact);+ if (parent)+ parent.add(root);+ return {+ root,+ ...steeringPivot ? { steeringPivot } : {},+ spinPivot,+ tire,+ rim,+ hub,+ contact,+ radius,+ width,+ side: options.side,+ index,+ spinAxis: VEHICLE_AXES.wheelAxle+ };+}+function roles(node) {+ return readSemanticMetadataV1(node)?.roles ?? [];+}+function descendantWithRole(root, prefix) {+ let found;+ root.traverse((node) => {+ if (!found && roles(node).some((role) => role.startsWith(prefix)))+ found = node;+ });+ return found;+}+function ancestorWithRole(node, prefix) {+ let current = node.parent;+ while (current) {+ if (roles(current).some((role) => role.startsWith(prefix)))+ return current;+ current = current.parent;+ }+ return;+}+function parseWheelRole(role) {+ const parts = role.split(".");+ const side = parts.at(-2);+ return {+ ...side === "left" || side === "right" ? { side } : {},+ ...parts.at(-1) ? { index: parts.at(-1) } : {}+ };+}+function objectBoundsInFrame(object, frame) {+ object.updateWorldMatrix(true, true);+ frame.updateWorldMatrix(true, false);+ const worldToFrame = frame.matrixWorld.clone().invert();+ const bounds = new THREE11.Box3;+ let found = false;+ object.traverse((node) => {+ if (!(node instanceof THREE11.Mesh) || !(node.geometry instanceof THREE11.BufferGeometry))+ return;+ node.geometry.computeBoundingBox();+ const local = node.geometry.boundingBox;+ if (!local)+ return;+ const matrix = worldToFrame.clone().multiply(node.matrixWorld);+ for (const x of [local.min.x, local.max.x])+ for (const y of [local.min.y, local.max.y])+ for (const z of [local.min.z, local.max.z]) {+ bounds.expandByPoint(new THREE11.Vector3(x, y, z).applyMatrix4(matrix));+ found = true;+ }+ });+ return found ? bounds : undefined;+}+function dimensions(object, frame) {+ if (!object)+ return;+ const bounds = objectBoundsInFrame(object, frame);+ if (!bounds)+ return;+ const size = bounds.getSize(new THREE11.Vector3);+ return {+ center: bounds.getCenter(new THREE11.Vector3),+ radius: Math.max(size.x, size.y) / 2,+ width: size.z+ };+}+function resolved(source, id, root, pivot, parts) {+ pivot.updateWorldMatrix(true, false);+ const tire = dimensions(parts.tire, pivot);+ const rim = dimensions(parts.rim, pivot);+ const hub = dimensions(parts.hub, pivot);+ const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE11.Vector3;+ const toWorld = (value) => value.clone().applyMatrix4(pivot.matrixWorld);+ return {+ id,+ source,+ ...parts.side ? { side: parts.side } : {},+ ...parts.index ? { index: parts.index } : {},+ root,+ pivot,+ ...parts.steeringPivot ? { steeringPivot: parts.steeringPivot } : {},+ ...parts.tire ? { tire: parts.tire } : {},+ ...parts.rim ? { rim: parts.rim } : {},+ ...parts.hub ? { hub: parts.hub } : {},+ ...parts.contact ? { contact: parts.contact } : {},+ centerWorld: toWorld(centerLocal),+ pivotCenterWorld: new THREE11.Vector3().setFromMatrixPosition(pivot.matrixWorld),+ ...tire ? { tireCenterWorld: toWorld(tire.center) } : {},+ ...rim ? { rimCenterWorld: toWorld(rim.center) } : {},+ ...hub ? { hubCenterWorld: toWorld(hub.center) } : {},+ spinAxisWorld: new THREE11.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),+ ...tire ? { radius: tire.radius, width: tire.width } : {},+ ...rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {},+ ...hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {},+ loadBearing: hasSemanticRole(roles(pivot), ROLE.wheelLoadBearing)+ };+}+function semanticAssemblies(root) {+ const result = [];+ root.traverse((node) => {+ const assemblyRole = roles(node).find((role) => semanticRoleMatches(role, ROLE.wheelAssembly));+ if (!assemblyRole)+ return;+ const parsed = parseWheelRole(assemblyRole);+ result.push(resolved("semantic", assemblyRole, node, node, {+ ...parsed,+ tire: descendantWithRole(node, `${ROLE.wheelTire}.`),+ rim: descendantWithRole(node, `${ROLE.wheelRim}.`),+ hub: descendantWithRole(node, `${ROLE.wheelHub}.`),+ contact: descendantWithRole(node, `${ROLE.wheelContact}.`),+ steeringPivot: ancestorWithRole(node, `${ROLE.steeringPivot}.`)+ }));+ });+ return result;+}+function legacyCorner(name) {+ const value = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");+ if (!/(wheel|tire|rim|hub)/.test(value))+ return;+ const side = /(?:left|(^|-)l($|-)|fl|rl)/.test(value) ? "left" : /(?:right|(^|-)r($|-)|fr|rr)/.test(value) ? "right" : undefined;+ const index = /(?:front|(^|-)f($|-)|fl|fr)/.test(value) ? "front" : /(?:rear|back|(^|-)r[lr]($|-)|rl|rr)/.test(value) ? "rear" : value.match(/\d+/)?.[0];+ return {+ key: `${side ?? "unknown"}.${index ?? value}`,+ ...side ? { side } : {},+ ...index ? { index } : {}+ };+}+function legacyAssemblies(root) {+ const groups = new Map;+ root.traverse((node) => {+ const corner = legacyCorner(node.name);+ if (!corner)+ return;+ const entry = groups.get(corner.key) ?? {+ ...corner.side ? { side: corner.side } : {},+ ...corner.index ? { index: corner.index } : {}+ };+ const lower = node.name.toLowerCase();+ if (lower.includes("pivot"))+ entry.pivot = node;+ else if (lower.includes("rim"))+ entry.rim = node;+ else if (lower.includes("hub"))+ entry.hub = node;+ else+ entry.tire = node;+ groups.set(corner.key, entry);+ });+ return [...groups.entries()].map(([key, parts]) => {+ const pivot = parts.pivot ?? parts.tire?.parent ?? parts.rim?.parent ?? parts.hub?.parent ?? root;+ return resolved("legacy", key, pivot, pivot, parts);+ });+}+function resolveVehicleWheelAssemblies(root) {+ const semantic = semanticAssemblies(root);+ return semantic.length > 0 ? semantic : legacyAssemblies(root);+}+function hasCanonicalVehicleFront(root) {+ let found = false;+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ if (metadata?.roles.includes(ROLE.vehicleFrame) && metadata.roles.includes(ROLE.vehicleForward) && metadata.frames.some((frame) => frame.id === "forward.+x")) {+ found = true;+ }+ });+ return found;+}+var ROLE, VEHICLE_AXES, ID_PATTERN, SOCKET_ROLE_BASE;+var init_vehicle = __esm(() => {+ init_contracts();+ ROLE = KILN_SEMANTIC_ROLES;+ VEHICLE_AXES = Object.freeze({+ forward: Object.freeze([1, 0, 0]),+ up: Object.freeze([0, 1, 0]),+ right: Object.freeze([0, 0, 1]),+ wheelAxle: Object.freeze([0, 0, 1])+ });+ ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;+ SOCKET_ROLE_BASE = Object.freeze({+ chassis: KILN_SEMANTIC_ROLES.chassis,+ axle: KILN_SEMANTIC_ROLES.axle,+ seat: KILN_SEMANTIC_ROLES.seat,+ contact: KILN_SEMANTIC_ROLES.contact,+ steering: KILN_SEMANTIC_ROLES.steering,+ propulsion: KILN_SEMANTIC_ROLES.propulsion+ });+});++// src/uv.ts+import * as THREE12 from "three";+async function getXatlas() {+ if (!_xatlasReady) {+ _xatlasReady = (async () => {+ const apiSpecifier = "xatlasjs/dist/node/api.mjs";+ const xatlasSpecifier = "xatlasjs/dist/node/xatlas.js";+ const apiMod = await import(apiSpecifier);+ const xatlasMod = await import(xatlasSpecifier);+ const create = xatlasMod.default ?? xatlasMod;+ const ApiCtor = apiMod.Api(create);+ return new Promise((resolve) => {+ const xa = new ApiCtor(() => resolve(xa), null, null);+ });+ })();+ }+ return _xatlasReady;+}+async function autoUnwrap(geometry, opts = {}) {+ const xa = await getXatlas();+ const src = geometry.index ? geometry : toIndexed(geometry);+ const posAttr = src.getAttribute("position");+ const normAttr = src.getAttribute("normal");+ const idxAttr = src.getIndex();+ if (!posAttr || !idxAttr) {+ throw new Error("autoUnwrap: geometry requires position attribute and an index");+ }+ if (idxAttr.count === 0 || posAttr.count === 0) {+ throw new Error("autoUnwrap: geometry has no triangles. Nothing can be unwrapped — check the operation that produced it (an empty CSG result is the usual cause).");+ }+ if (idxAttr.count % 3 !== 0) {+ throw new Error(`autoUnwrap: geometry has ${idxAttr.count} indices, which is not a whole number of triangles.`);+ }+ xa.createAtlas();+ const useNormals = Boolean(opts.useNormals && normAttr);+ const indexArray = idxAttr.array instanceof Uint32Array ? idxAttr.array : new Uint32Array(idxAttr.array);+ const addRes = xa.addMesh(indexArray, new Float32Array(posAttr.array), useNormals && normAttr ? new Float32Array(normAttr.array) : null, null, "kiln-mesh", useNormals, false, 1);+ if (!addRes) {+ xa.destroyAtlas();+ throw new Error("autoUnwrap: xatlas.addMesh failed (non-manifold or degenerate geometry?)");+ }+ const result = xa.generateAtlas({}, { resolution: opts.resolution ?? 1024, padding: opts.padding ?? 2 }, true);+ const mesh = result.meshes[0];+ if (!mesh) {+ xa.destroyAtlas();+ throw new Error("autoUnwrap: xatlas returned no meshes");+ }+ const out = new THREE12.BufferGeometry;+ out.setAttribute("position", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));+ if (mesh.vertex.normals) {+ out.setAttribute("normal", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));+ }+ if (mesh.vertex.coords1) {+ out.setAttribute("uv", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));+ }+ if (mesh.index) {+ out.setIndex(new THREE12.BufferAttribute(new Uint32Array(mesh.index), 1));+ }+ out.userData["atlas"] = {+ width: result.width,+ height: result.height,+ atlasCount: result.atlasCount+ };+ if (!out.getAttribute("normal"))+ out.computeVertexNormals();+ repairZeroNormals(out);+ if (!out.getAttribute("uv")) {+ xa.destroyAtlas();+ throw new Error("autoUnwrap: xatlas produced no UV coordinates for this geometry (degenerate or zero-area triangles?).");+ }+ xa.destroyAtlas();+ return out;+}+function toIndexed(geo) {+ const posAttr = geo.getAttribute("position");+ const indices = new Uint32Array(posAttr.count);+ for (let i = 0;i < posAttr.count; i++)+ indices[i] = i;+ const out = geo.clone();+ out.setIndex(new THREE12.BufferAttribute(indices, 1));+ return out;+}+function repairZeroNormals(geo) {+ const normal = geo.getAttribute("normal");+ const position = geo.getAttribute("position");+ const index = geo.getIndex();+ if (!normal || !position || !index)+ return;+ const broken = new Set;+ for (let i = 0;i < normal.count; i++) {+ const x = normal.getX(i);+ const y = normal.getY(i);+ const z = normal.getZ(i);+ if (!Number.isFinite(x + y + z) || Math.hypot(x, y, z) < 0.000001)+ broken.add(i);+ }+ if (broken.size === 0)+ return;+ const acc = new Float32Array(normal.count * 3);+ const a = new THREE12.Vector3;+ const b = new THREE12.Vector3;+ const c = new THREE12.Vector3;+ const face = new THREE12.Vector3;+ const edge = new THREE12.Vector3;+ for (let t = 0;t + 2 < index.count; t += 3) {+ const tri = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];+ if (!tri.some((i) => broken.has(i)))+ continue;+ a.fromBufferAttribute(position, tri[0]);+ b.fromBufferAttribute(position, tri[1]);+ c.fromBufferAttribute(position, tri[2]);+ face.subVectors(c, a);+ edge.subVectors(b, a);+ face.crossVectors(edge, face);+ for (const i of tri) {+ if (!broken.has(i))+ continue;+ const o = i * 3;+ acc[o] = acc[o] + face.x;+ acc[o + 1] = acc[o + 1] + face.y;+ acc[o + 2] = acc[o + 2] + face.z;+ }+ }+ for (const i of broken) {+ face.set(acc[i * 3], acc[i * 3 + 1], acc[i * 3 + 2]);+ if (face.lengthSq() < 0.00000000000000000001)+ face.set(0, 1, 0);+ else+ face.normalize();+ normal.setXYZ(i, face.x, face.y, face.z);+ }+ normal.needsUpdate = true;+}+var _xatlasReady = null;+var init_uv = () => {};++// src/uv-shapes.ts+import * as THREE13 from "three";+function boxUnwrap(geo) {+ const cloned = geo.clone();+ if (!cloned.getAttribute("uv")) {+ planarProjectToUVs(cloned);+ }+ return cloned;+}+function cylinderUnwrap(geo) {+ const cloned = geo.clone();+ if (!cloned.getAttribute("uv")) {+ cylindricalProjectToUVs(cloned);+ }+ return cloned;+}+function cylindricalProjectToUVs(geo) {+ const pos = geo.getAttribute("position");+ if (!pos)+ return;+ geo.computeBoundingBox();+ const bb = geo.boundingBox;+ if (!bb)+ return;+ const minY = bb.min.y;+ const height = bb.max.y - minY;+ const maxR = Math.max(Math.hypot(bb.min.x, bb.min.z), Math.hypot(bb.max.x, bb.max.z), 0.000001);+ if (!geo.getAttribute("normal"))+ geo.computeVertexNormals();+ const nrm = geo.getAttribute("normal");+ const spanX = Math.max(bb.max.x - bb.min.x, 0.000001);+ const spanZ = Math.max(bb.max.z - bb.min.z, 0.000001);+ let minA = Infinity;+ let maxA = -Infinity;+ for (let i = 0;i < pos.count; i++) {+ if (nrm && Math.abs(nrm.getY(i)) > 0.7)+ continue;+ const a = Math.atan2(pos.getZ(i), pos.getX(i));+ if (a < minA)+ minA = a;+ if (a > maxA)+ maxA = a;+ }+ const span = maxA - minA;+ const uv = new Float32Array(pos.count * 2);+ for (let i = 0;i < pos.count; i++) {+ const x = pos.getX(i);+ const y = pos.getY(i);+ const z = pos.getZ(i);+ if (nrm && Math.abs(nrm.getY(i)) > 0.7) {+ uv[i * 2] = (x - bb.min.x) / spanX;+ uv[i * 2 + 1] = (z - bb.min.z) / spanZ;+ continue;+ }+ const a = Math.atan2(z, x);+ uv[i * 2] = span > 0.000001 ? (a - minA) / span : 0.5;+ uv[i * 2 + 1] = height > 0.000001 ? (y - minY) / height : Math.hypot(x, z) / maxR;+ }+ geo.setAttribute("uv", new THREE13.BufferAttribute(uv, 2));+}+function planeUnwrap(geo) {+ const cloned = geo.clone();+ planarProjectToUVs(cloned);+ return cloned;+}+function panelRemapV(geo, vScale = 0.3, vOffset = 0, uScale = 1, uOffset = 0) {+ const cloned = geo.clone();+ const uvAttr = cloned.getAttribute("uv");+ if (!uvAttr)+ return cloned;+ const arr = uvAttr.array;+ for (let i = 0;i < arr.length; i += 2) {+ arr[i] = (arr[i] ?? 0) * uScale + uOffset;+ arr[i + 1] = (arr[i + 1] ?? 0) * vScale + vOffset;+ }+ uvAttr.needsUpdate = true;+ return cloned;+}+function planarProjectToUVs(geo) {+ geo.computeBoundingBox();+ const bb = geo.boundingBox;+ const size = new THREE13.Vector3;+ bb.getSize(size);+ const w = size.x || 1;+ const h = size.y || 1;+ const pos = geo.getAttribute("position");+ const uvs = new Float32Array(pos.count * 2);+ for (let i = 0;i < pos.count; i++) {+ uvs[i * 2] = (pos.getX(i) - bb.min.x) / w;+ uvs[i * 2 + 1] = (pos.getY(i) - bb.min.y) / h;+ }+ geo.setAttribute("uv", new THREE13.BufferAttribute(uvs, 2));+}+var init_uv_shapes = () => {};++// src/material-recipe-runtime.ts+import * as THREE14 from "three";+async function applyMaterialRecipeV1(request, options = {}) {+ const resolved = resolveMaterialRecipeV1(request);+ const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;+ const loaded = new Map;+ for (const [slot, id] of Object.entries(resolved.textureResources)) {+ if (id)+ loaded.set(slot, await cache.load(id));+ }+ const materialOptions = {+ roughness: resolved.roughnessFactor,+ metalness: resolved.metallicFactor,+ alphaMode: lowerAlphaMode(resolved.alphaMode),+ ...resolved.alphaMode === "MASK" ? { alphaCutoff: resolved.alphaCutoff ?? 0.5 } : {},+ doubleSided: resolved.doubleSided,+ ...loaded.get("baseColor") ? { albedo: loaded.get("baseColor").texture } : {},+ ...loaded.get("normal") ? { normal: loaded.get("normal").texture } : {},+ ...loaded.get("metallicRoughness") ? { metallicRoughness: loaded.get("metallicRoughness").texture } : {},+ ...loaded.get("emissive") ? { emissive: loaded.get("emissive").texture } : {},+ ...loaded.get("occlusion") ? { aoMap: loaded.get("occlusion").texture } : {}+ };+ const material = pbrMaterial(materialOptions);+ material.name = options.name ?? request.id;+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE14.LinearSRGBColorSpace);+ material.opacity = resolved.baseColorFactor[3];+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE14.LinearSRGBColorSpace);+ const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));+ const provenance = {+ schemaVersion: 1,+ recipeId: request.id,+ recipeVersion: 1,+ request: {+ schemaVersion: 1,+ id: request.id,+ ...request.overrides ? {+ overrides: {+ ...request.overrides,+ ...request.overrides.textureResources ? { textureResources: { ...request.overrides.textureResources } } : {}+ }+ } : {}+ },+ portableModel: "pbrMetallicRoughness",+ resources+ };+ material.userData["kilnMaterialRecipe"] = provenance;+ return { material, resolved, provenance };+}+async function materialRecipe(id, overrides, options = {}) {+ return (await applyMaterialRecipeV1(createMaterialRecipeRequestV1(id, overrides), options)).material;+}+function readMaterialRecipeApplication(material) {+ return material.userData["kilnMaterialRecipe"];+}+function collectMaterialRecipeApplications(root) {+ const applications = new Map;+ root.traverse((node) => {+ const value = node.material;+ const materials = Array.isArray(value) ? value : value ? [value] : [];+ for (const material of materials) {+ const application = readMaterialRecipeApplication(material);+ if (!application)+ continue;+ const resourceKey = application.resources.map((resource) => `${resource.resourceId}:${resource.contentHash}`).sort().join(",");+ applications.set(`${application.recipeId}:${JSON.stringify(application.request)}:${resourceKey}`, application);+ }+ });+ return [...applications.values()].sort((a, b) => a.recipeId.localeCompare(b.recipeId));+}+var lowerAlphaMode = (value) => value === "MASK" ? "mask" : value === "BLEND" ? "blend" : "opaque";+var init_material_recipe_runtime = __esm(() => {+ init_material_recipes();+ init_material_resources();+ init_textures();+});++// src/primitives.ts+import * as THREE15 from "three";+function vectorToTuple(v) {+ return [v.x, v.y, v.z];+}+function createRoot(name) {+ const root = new THREE15.Object3D;+ root.name = name;+ return root;+}+function createPivot(name, position = [0, 0, 0], parent) {+ const pivot = new THREE15.Object3D;+ pivot.name = `Joint_${name}`;+ pivot.position.set(...position);+ if (parent)+ parent.add(pivot);+ return pivot;+}+function assertPartArgs(name, geometry2, material) {+ const SIG = "Signature: createPart(name, geometry, material, options?) -- " + "e.g. createPart('Hull', boxGeo(1, 1, 1), gameMaterial(0x808080), { parent: root }).";+ if (typeof name !== "string") {+ const asObject = name;+ const got = asObject?.isObject3D === true ? `an Object3D ("${asObject.name || "unnamed"}"). The parent belongs in the options object as { parent }, not first` : `${name === null ? "null" : typeof name}`;+ throw new Error(`createPart: the first argument is the part NAME, a string, but got ${got}. ${SIG}`);+ }+ if (geometry2?.isBufferGeometry !== true) {+ let got;+ if (typeof geometry2 === "function") {+ got = "a function -- geometry helpers have to be CALLED, so boxGeo(1, 1, 1) rather than boxGeo";+ } else if (geometry2 instanceof Promise) {+ got = "a Promise -- roundedBoxGeo, extrudeProfile and revolveProfile are async, " + "so await the helper and mark build() async";+ } else {+ got = geometry2 === null ? "null" : geometry2 === undefined ? "undefined" : `a ${typeof geometry2}`;+ }+ throw new Error(`createPart("${name}"): the second argument must be a geometry, but got ${got}. ${SIG}`);+ }+ if (material?.isMaterial !== true) {+ const got = typeof material === "number" ? "a number -- a colour is not a material, so wrap it: gameMaterial(0x808080)" : material === null ? "null" : material === undefined ? "undefined" : `a ${typeof material}`;+ throw new Error(`createPart("${name}"): the third argument must be a material, but got ${got}. ${SIG}`);+ }+}+function createPart(name, geometry2, material, options = {}) {+ assertPartArgs(name, geometry2, material);+ const mesh = new THREE15.Mesh(geometry2, material);+ mesh.name = `Mesh_${name}`;+ if (options.position)+ mesh.position.set(...options.position);+ if (options.rotation)+ mesh.rotation.set(THREE15.MathUtils.degToRad(options.rotation[0]), THREE15.MathUtils.degToRad(options.rotation[1]), THREE15.MathUtils.degToRad(options.rotation[2]));+ if (options.scale)+ mesh.scale.set(...options.scale);+ if (options.pivot) {+ const pivot = new THREE15.Object3D;+ pivot.name = `Joint_${name}`;+ pivot.add(mesh);+ mesh.position.set(0, 0, 0);+ if (options.position)+ pivot.position.set(...options.position);+ if (options.parent)+ options.parent.add(pivot);+ if (options.semantic)+ stampSemanticMetadataV1(pivot, options.semantic);+ return pivot;+ }+ if (options.parent)+ options.parent.add(mesh);+ if (options.semantic)+ stampSemanticMetadataV1(mesh, options.semantic);+ return mesh;+}+function capsuleGeo(radius, height, segments = 6) {+ return new THREE15.CapsuleGeometry(radius, height, 2, segments);+}+function capsuleXGeo(radius, length, segments = 6) {+ const geo = capsuleGeo(radius, length, segments);+ geo.rotateZ(-Math.PI / 2);+ return geo;+}+function capsuleZGeo(radius, length, segments = 6) {+ const geo = capsuleGeo(radius, length, segments);+ geo.rotateX(Math.PI / 2);+ return geo;+}+function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {+ return new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);+}+function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {+ const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);+ geo.rotateZ(-Math.PI / 2);+ return geo;+}+function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {+ const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);+ geo.rotateX(Math.PI / 2);+ return geo;+}+function boxGeo(width, height, depth) {+ return new THREE15.BoxGeometry(width, height, depth);+}+function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {+ return new THREE15.SphereGeometry(radius, widthSegments, heightSegments);+}+function coneGeo(radius, height, segments = 8) {+ return new THREE15.ConeGeometry(radius, height, segments);+}+function coneXGeo(radius, length, segments = 8) {+ const geo = coneGeo(radius, length, segments);+ geo.rotateZ(-Math.PI / 2);+ return geo;+}+function coneZGeo(radius, length, segments = 8) {+ const geo = coneGeo(radius, length, segments);+ geo.rotateX(Math.PI / 2);+ return geo;+}+function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {+ const radiusTop = options.radiusTop ?? radiusBottom;+ const segments = options.segments ?? 8;+ const geo = new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);+ const n = new THREE15.Vector3(normal[0], normal[1], normal[2]);+ const len = n.length();+ if (len < 0.000001) {+ throw new Error(`cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(",")}]).`);+ }+ n.divideScalar(len);+ const q = new THREE15.Quaternion().setFromUnitVectors(new THREE15.Vector3(0, 1, 0), n);+ geo.applyQuaternion(q);+ geo.translate(center[0], center[1], center[2]);+ return geo;+}+function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8) {+ const geo = new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);+ if (axis === "x")+ geo.rotateZ(-Math.PI / 2);+ else if (axis === "z")+ geo.rotateX(Math.PI / 2);+ return geo;+}+function torusGeo(radius, tube, radialSegments = 8, tubularSegments = 12) {+ return new THREE15.TorusGeometry(radius, tube, radialSegments, tubularSegments);+}+function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {+ return new THREE15.PlaneGeometry(width, height, widthSegments, heightSegments);+}+function decalBox(width, height, depth = 0.01) {+ const d = Math.max(depth, 0.002);+ return new THREE15.BoxGeometry(width, height, d);+}+function foliageCardGeo(opts = {}) {+ const w = opts.width ?? 1;+ const h = opts.height ?? 1;+ const yPivot = opts.yPivot ?? 0;+ const geom = new THREE15.PlaneGeometry(w, h);+ geom.translate(0, h * (0.5 - yPivot), 0);+ geom.userData["kilnGeometryRole"] = "foliageCard";+ return geom;+}+function crossedQuadsGeo(opts = {}) {+ const w = opts.width ?? 1;+ const h = opts.height ?? 1;+ const planes = opts.planes ?? 2;+ const yPivot = opts.yPivot ?? 0;+ const geometries = [];+ for (let i = 0;i < planes; i++) {+ const angle = i / planes * Math.PI;+ const quad = new THREE15.PlaneGeometry(w, h);+ quad.translate(0, h * (0.5 - yPivot), 0);+ quad.rotateY(angle);+ geometries.push(quad);+ }+ const out = new THREE15.BufferGeometry;+ const posCount = geometries.reduce((sum, g) => sum + (g.attributes.position?.count ?? 0), 0);+ const positions = new Float32Array(posCount * 3);+ const normals = new Float32Array(posCount * 3);+ const uvs = new Float32Array(posCount * 2);+ const indices = [];+ let vOffset = 0;+ for (const g of geometries) {+ const p = g.attributes.position;+ const n = g.attributes.normal;+ const uv = g.attributes.uv;+ for (let i = 0;i < p.count; i++) {+ positions[(vOffset + i) * 3] = p.getX(i);+ positions[(vOffset + i) * 3 + 1] = p.getY(i);+ positions[(vOffset + i) * 3 + 2] = p.getZ(i);+ normals[(vOffset + i) * 3] = n.getX(i);+ normals[(vOffset + i) * 3 + 1] = n.getY(i);+ normals[(vOffset + i) * 3 + 2] = n.getZ(i);+ uvs[(vOffset + i) * 2] = uv.getX(i);+ uvs[(vOffset + i) * 2 + 1] = uv.getY(i);+ }+ const idx = g.index;+ for (let i = 0;i < idx.count; i++) {+ indices.push(idx.getX(i) + vOffset);+ }+ vOffset += p.count;+ }+ out.setAttribute("position", new THREE15.BufferAttribute(positions, 3));+ out.setAttribute("normal", new THREE15.BufferAttribute(normals, 3));+ out.setAttribute("uv", new THREE15.BufferAttribute(uvs, 2));+ out.setIndex(indices);+ out.userData["kilnGeometryRole"] = "foliageCard";+ return out;+}+function octaGridPlane(opts) {+ const w = opts.width ?? 1;+ const h = opts.height ?? 1;+ const yPivot = opts.yPivot ?? 0;+ const geom = new THREE15.PlaneGeometry(w, h);+ geom.translate(0, h * (0.5 - yPivot), 0);+ const uv = geom.attributes.uv;+ const du = 1 / opts.tilesX;+ const dv = 1 / opts.tilesY;+ for (let i = 0;i < uv.count; i++) {+ uv.setX(i, uv.getX(i) * du);+ uv.setY(i, 1 - dv + uv.getY(i) * dv);+ }+ uv.needsUpdate = true;+ return geom;+}+function wingGeo(options = {}) {+ const span = options.span ?? 1;+ const rootChord = options.rootChord ?? 0.6;+ const tipChord = options.tipChord ?? rootChord * 0.5;+ const sweep2 = options.sweep ?? 0;+ const thickness = options.thickness ?? 0.04;+ const dihedral = options.dihedral ?? 0;+ const rootLead = rootChord / 2;+ const rootTrail = -rootChord / 2;+ const tipLead = rootLead - sweep2;+ const tipTrail = tipLead - tipChord;+ const halfThickness = thickness / 2;+ const vertices = new Float32Array([+ rootLead,+ halfThickness,+ 0,+ rootTrail,+ halfThickness,+ 0,+ tipLead,+ dihedral + halfThickness,+ span,+ tipTrail,+ dihedral + halfThickness,+ span,+ rootLead,+ -halfThickness,+ 0,+ rootTrail,+ -halfThickness,+ 0,+ tipLead,+ dihedral - halfThickness,+ span,+ tipTrail,+ dihedral - halfThickness,+ span+ ]);+ const indices = [+ 0,+ 3,+ 2,+ 0,+ 1,+ 3,+ 4,+ 6,+ 7,+ 4,+ 7,+ 5,+ 0,+ 2,+ 6,+ 0,+ 6,+ 4,+ 1,+ 5,+ 7,+ 1,+ 7,+ 3,+ 0,+ 4,+ 5,+ 0,+ 5,+ 1,+ 2,+ 3,+ 7,+ 2,+ 7,+ 6+ ];+ const geo = new THREE15.BufferGeometry;+ geo.setAttribute("position", new THREE15.BufferAttribute(vertices, 3));+ geo.setIndex(indices);+ geo.computeVertexNormals();+ return geo;+}+function createWingPair(name, material, options) {+ const { parent, rootX = 0, rootY = 0, rootZ, ...wingOptions } = options;+ const rightGeo = wingGeo(wingOptions);+ const leftGeo = wingGeo(wingOptions);+ leftGeo.scale(1, 1, -1);+ leftGeo.computeVertexNormals();+ return {+ right: createPart(`${name}Right`, rightGeo, material, {+ position: [rootX, rootY, rootZ],+ parent}),- "kiln.texture.oak-veneer-albedo.v1": Object.freeze({- sourceAsset: "oak_veneer_01",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/oak_veneer_01/oak_veneer_01_diff_1k.jpg",- sourceMd5: "39a99df4e328d62d74f3122722a64a95",- transform: "sharp 128x128 Lanczos3 PNG"+ left: createPart(`${name}Left`, leftGeo, material, {+ position: [rootX, rootY, -rootZ],+ parent+ })+ };+}+function beamBetween(name, start, end, radius, material, options = {}) {+ const a = new THREE15.Vector3(...start);+ const b = new THREE15.Vector3(...end);+ const direction = b.clone().sub(a);+ const length = direction.length();+ if (length <= 0.0001) {+ throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);+ }+ const mesh = new THREE15.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);+ mesh.name = `Mesh_${name}`;+ mesh.position.copy(a.add(b).multiplyScalar(0.5));+ mesh.quaternion.setFromUnitVectors(new THREE15.Vector3(0, 1, 0), direction.normalize());+ if (options.parent)+ options.parent.add(mesh);+ return mesh;+}+function snapTo(part, host, options = {}) {+ const overlap = options.overlap ?? 0.02;+ part.updateMatrixWorld(true);+ host.updateMatrixWorld(true);+ const a = new THREE15.Box3().setFromObject(part);+ const b = new THREE15.Box3().setFromObject(host);+ if (a.isEmpty() || b.isEmpty())+ return part;+ const delta = new THREE15.Vector3;+ for (const axis of ["x", "y", "z"]) {+ if (a.min[axis] > b.max[axis])+ delta[axis] = b.max[axis] - a.min[axis];+ else if (a.max[axis] < b.min[axis])+ delta[axis] = b.min[axis] - a.max[axis];+ }+ if (delta.lengthSq() === 0)+ return part;+ const dominant = options.axis ?? ["x", "y", "z"].reduce((d, axis) => Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d, "x");+ if (delta[dominant] !== 0)+ delta[dominant] += Math.sign(delta[dominant]) * overlap;+ else+ delta[dominant] = -overlap;+ const parent = part.parent;+ if (parent) {+ const p0 = new THREE15.Vector3;+ part.getWorldPosition(p0);+ const p1 = p0.clone().add(delta);+ const l0 = parent.worldToLocal(p0.clone());+ const l1 = parent.worldToLocal(p1.clone());+ part.position.add(l1.sub(l0));+ } else {+ part.position.add(delta);+ }+ part.updateMatrixWorld(true);+ return part;+}+function createLadder(name, options) {+ const {+ bottom,+ top,+ material,+ width = 0.42,+ rungCount = 6,+ railRadius = 0.025,+ rungRadius = 0.02,+ segments = 6,+ widthAxis = "x",+ parent+ } = options;+ const bottomVec = new THREE15.Vector3(...bottom);+ const topVec = new THREE15.Vector3(...top);+ const offset = widthAxis === "x" ? new THREE15.Vector3(width / 2, 0, 0) : new THREE15.Vector3(0, 0, width / 2);+ const leftBottom = bottomVec.clone().sub(offset);+ const leftTop = topVec.clone().sub(offset);+ const rightBottom = bottomVec.clone().add(offset);+ const rightTop = topVec.clone().add(offset);+ const leftRail = beamBetween(`${name}LeftRail`, vectorToTuple(leftBottom), vectorToTuple(leftTop), railRadius, material, { parent, segments });+ const rightRail = beamBetween(`${name}RightRail`, vectorToTuple(rightBottom), vectorToTuple(rightTop), railRadius, material, { parent, segments });+ const rungs = [];+ for (let i = 0;i < rungCount; i++) {+ const t = (i + 1) / (rungCount + 1);+ const center = bottomVec.clone().lerp(topVec, t);+ rungs.push(beamBetween(`${name}Rung${i + 1}`, vectorToTuple(center.clone().sub(offset)), vectorToTuple(center.clone().add(offset)), rungRadius, material, { parent, segments }));+ }+ return { leftRail, rightRail, rungs };+}+function wallWithOpening(name, material, options) {+ const { length, height, thickness, axis = "z", opening, parent } = options;+ const group = new THREE15.Object3D;+ group.name = name;+ const overlap = 0.02;+ const panel = (suffix, lenStart, lenEnd, yLo, yHi) => {+ const segLen = lenEnd - lenStart;+ const segH = yHi - yLo;+ if (segLen <= 0.0001 || segH <= 0.0001)+ return;+ const lenC = (lenStart + lenEnd) / 2;+ const yC = (yLo + yHi) / 2;+ const geo = axis === "z" ? boxGeo(thickness, segH, segLen) : boxGeo(segLen, segH, thickness);+ const pos = axis === "z" ? [0, yC, lenC] : [lenC, yC, 0];+ createPart(`${name}${suffix}`, geo, material, { position: pos, parent: group });+ };+ if (!opening) {+ panel("", -length / 2, length / 2, 0, height);+ } else {+ const ow = opening.width ?? (opening.kind === "window" ? 1 : 1.1);+ const oh = opening.height ?? (opening.kind === "window" ? 1 : 2.1);+ const off = opening.offset ?? 0;+ const left = off - ow / 2;+ const right = off + ow / 2;+ const sill = opening.kind === "window" ? Math.max(opening.sill ?? 1, 0) : 0;+ const top = Math.min(sill + oh, height);+ panel("_L", -length / 2, left, 0, height);+ panel("_R", right, length / 2, 0, height);+ panel("_Lintel", left - overlap, right + overlap, top, height);+ if (sill > 0)+ panel("_Sill", left - overlap, right + overlap, 0, sill);+ }+ if (parent)+ parent.add(group);+ return group;+}+function room(name, material, options = {}) {+ const {+ width = 4,+ depth = 4,+ height = 2.8,+ wallThickness = 0.15,+ floor = true,+ floorThickness = 0.1,+ parent+ } = options;+ const openings = options.openings ?? [{ wall: "front", kind: "door" }];+ const root = new THREE15.Object3D;+ root.name = name;+ const openingFor = (wall) => {+ const found = openings.find((op) => op.wall === wall);+ if (!found)+ return;+ const { wall: _wall, ...rest } = found;+ return rest;+ };+ const wall = (suffix, len, axis, pos, which) => {+ const op = openingFor(which);+ const w = wallWithOpening(`${name}_Wall${suffix}`, material, {+ length: len,+ height,+ thickness: wallThickness,+ axis,+ ...op ? { opening: op } : {},+ parent: root+ });+ w.position.set(...pos);+ return w;+ };+ const walls = {+ front: wall("Front", width, "z", [depth / 2, 0, 0], "front"),+ back: wall("Back", width, "z", [-depth / 2, 0, 0], "back"),+ left: wall("Left", depth, "x", [0, 0, -width / 2], "left"),+ right: wall("Right", depth, "x", [0, 0, width / 2], "right")+ };+ let floorObj = null;+ if (floor) {+ floorObj = createPart(`${name}_Floor`, boxGeo(depth, floorThickness, width), material, {+ position: [0, floorThickness / 2, 0],+ parent: root+ });+ }+ if (parent)+ parent.add(root);+ return { root, walls, floor: floorObj };+}+function createRoofPlanes2(name, material, options) {+ const result = createRoofPlanes(name, material, options);+ result.slopes[0].name = `Mesh_${name}A`;+ result.slopes[1].name = `Mesh_${name}B`;+ for (let index = 0;index < result.slopes.length; index++) {+ const normal = new THREE15.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);+ result.slopes[index].position.addScaledVector(normal, (options.thickness ?? 0.08) / 2);+ }+ if ((options.ridgeAxis ?? "x") === "x") {+ const halfRun = options.width / 2 + (options.overhang ?? 0.3);+ const angle = Math.atan2(options.height, halfRun);+ result.slopes[1].rotation.set(-angle, Math.PI, 0);+ }+ return result;+}+function createStairs(name, material, options) {+ const {+ steps = 8,+ totalRise,+ totalRun,+ width,+ axis = "x",+ treadThickness = 0.08,+ riser = true,+ parent+ } = options;+ if (steps < 1) {+ throw new Error(`createStairs("${name}"): steps must be >= 1 (got ${steps}).`);+ }+ if (Math.abs(totalRise) < 0.0001 || Math.abs(totalRun) < 0.0001) {+ throw new Error(`createStairs("${name}"): totalRise and totalRun must be non-zero (got rise=${totalRise}, run=${totalRun}).`);+ }+ const root = new THREE15.Object3D;+ root.name = name;+ const stepRise = totalRise / steps;+ const stepRun = totalRun / steps;+ const stepList = [];+ for (let i = 0;i < steps; i++) {+ const topY = (i + 1) * stepRise;+ const alongC = (i + 0.5) * stepRun;+ const treadGeo = axis === "x" ? boxGeo(stepRun, treadThickness, width) : boxGeo(width, treadThickness, stepRun);+ const treadPos = axis === "x" ? [alongC, topY - treadThickness / 2, 0] : [0, topY - treadThickness / 2, alongC];+ stepList.push(createPart(`${name}Step${i + 1}`, treadGeo, material, { position: treadPos, parent: root }));+ if (riser) {+ const front = i * stepRun;+ const riserGeo = axis === "x" ? boxGeo(treadThickness, stepRise, width) : boxGeo(width, stepRise, treadThickness);+ const riserPos = axis === "x" ? [front + treadThickness / 2, topY - stepRise / 2, 0] : [0, topY - stepRise / 2, front + treadThickness / 2];+ createPart(`${name}Riser${i + 1}`, riserGeo, material, { position: riserPos, parent: root });+ }+ }+ if (parent)+ parent.add(root);+ return { root, steps: stepList };+}+function requireColor(color, fn) {+ if (typeof color === "number" || typeof color === "string")+ return;+ const got = color && typeof color === "object" ? `an object with keys [${Object.keys(color).join(", ")}]` : String(color);+ throw new Error(`${fn}(color, options?): color must be a hex number like 0x8c4a32 or a CSS string, got ${got}. ` + `Material settings go in the SECOND argument: ${fn}(0x8c4a32, { roughness: 0.5, metalness: 0.9 }).`);+}+function gameMaterial(color, options = {}) {+ requireColor(color, "gameMaterial");+ return new THREE15.MeshStandardMaterial({+ color,+ metalness: options.metalness ?? 0,+ roughness: options.roughness ?? 0.8,+ emissive: options.emissive ?? 0,+ emissiveIntensity: options.emissiveIntensity ?? 1,+ flatShading: options.flatShading ?? true+ });+}+function basicMaterial(color, options = {}) {+ requireColor(color, "basicMaterial");+ return new THREE15.MeshBasicMaterial({+ color,+ transparent: options.transparent ?? false,+ opacity: options.opacity ?? 1+ });+}+function glassMaterial(color, options = {}) {+ requireColor(color, "glassMaterial");+ return new THREE15.MeshStandardMaterial({+ color,+ transparent: true,+ opacity: options.opacity ?? 0.35,+ roughness: options.roughness ?? 0.1,+ metalness: options.metalness ?? 0,+ side: THREE15.DoubleSide+ });+}+function lambertMaterial(color, options = {}) {+ requireColor(color, "lambertMaterial");+ return new THREE15.MeshLambertMaterial({+ color,+ flatShading: options.flatShading ?? true,+ emissive: options.emissive ?? 0+ });+}+function threeInterpolation(mode) {+ return mode === "STEP" ? THREE15.InterpolateDiscrete : THREE15.InterpolateLinear;+}+function rotationTrack(jointName, keyframes, interpolation) {+ const times = [];+ const values = [];+ const euler = new THREE15.Euler;+ const quat = new THREE15.Quaternion;+ for (const kf of keyframes) {+ times.push(kf.time);+ euler.set(THREE15.MathUtils.degToRad(kf.rotation[0]), THREE15.MathUtils.degToRad(kf.rotation[1]), THREE15.MathUtils.degToRad(kf.rotation[2]));+ quat.setFromEuler(euler);+ values.push(quat.x, quat.y, quat.z, quat.w);+ }+ return new THREE15.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));+}+function positionTrack(jointName, keyframes, interpolation) {+ const times = [];+ const values = [];+ for (const kf of keyframes) {+ times.push(kf.time);+ values.push(...kf.position);+ }+ return new THREE15.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));+}+function scaleTrack(jointName, keyframes, interpolation) {+ const times = [];+ const values = [];+ for (const kf of keyframes) {+ times.push(kf.time);+ values.push(...kf.scale);+ }+ return new THREE15.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));+}+function createClip(name, duration, tracks) {+ return new THREE15.AnimationClip(name, duration, tracks);+}+function idleBreathing(bodyJoint, duration = 2, amount = 0.02) {+ const y = 0;+ return createClip("Idle", duration, [+ positionTrack(bodyJoint, [+ { time: 0, position: [0, y, 0] },+ { time: duration / 2, position: [0, y + amount, 0] },+ { time: duration, position: [0, y, 0] }+ ])+ ]);+}+function bobbingAnimation(rootName, duration = 2, height = 0.1) {+ return createClip("Bob", duration, [+ positionTrack(rootName, [+ { time: 0, position: [0, 0, 0] },+ { time: duration / 2, position: [0, height, 0] },+ { time: duration, position: [0, 0, 0] }+ ])+ ]);+}+function spinAnimation(jointName, duration = 2, axis = "y") {+ const rotation = [0, 0, 0];+ const idx = axis === "x" ? 0 : axis === "y" ? 1 : 2;+ const rotations = [];+ for (let i = 0;i <= 4; i++) {+ const r = [...rotation];+ r[idx] = i * 90 % 360;+ rotations.push({ time: i * duration / 4, rotation: r });+ }+ return createClip("Spin", duration, [rotationTrack(jointName, rotations)]);+}+function cloneGeometry(geo) {+ return geo;+}+function cloneMaterial(mat) {+ return mat;+}+function copyGeometry(geo) {+ return geo.clone();+}+function copyMaterial(mat) {+ return mat.clone();+}+function createInstance(name, source, options = {}) {+ const isMesh = (o) => !!o?.isMesh;+ const sourceMesh = isMesh(source) ? source : source.children.find(isMesh);+ if (!sourceMesh) {+ throw new Error(`createInstance("${name}"): source "${source.name}" has no Mesh to clone from`);+ }+ const mesh = new THREE15.Mesh(sourceMesh.geometry, sourceMesh.material);+ mesh.name = `Mesh_${name}`;+ if (options.position)+ mesh.position.set(...options.position);+ if (options.rotation)+ mesh.rotation.set(THREE15.MathUtils.degToRad(options.rotation[0]), THREE15.MathUtils.degToRad(options.rotation[1]), THREE15.MathUtils.degToRad(options.rotation[2]));+ if (options.scale)+ mesh.scale.set(...options.scale);+ if (options.parent)+ options.parent.add(mesh);+ return mesh;+}+function countTriangles(root) {+ let count = 0;+ root.traverse((child) => {+ if (child.isMesh) {+ const meshChild = child;+ const geometry2 = meshChild.geometry;+ if (geometry2.index) {+ count += geometry2.index.count / 3;+ } else {+ const position = geometry2.getAttribute("position");+ if (position)+ count += position.count / 3;+ }+ } else if (child.isSprite) {+ count += 2;+ }+ });+ return Math.floor(count);+}+function countMaterials(root) {+ const materials = new Set;+ root.traverse((child) => {+ if (child.isMesh) {+ const meshChild = child;+ if (Array.isArray(meshChild.material)) {+ meshChild.material.forEach((material) => {+ materials.add(material);+ });+ } else {+ materials.add(meshChild.material);+ }+ } else if (child.isSprite) {+ materials.add(child.material);+ }+ });+ return materials.size;+}+function getJointNames(root) {+ const joints = [];+ root.traverse((child) => {+ if (child.name.startsWith("Joint_")) {+ joints.push(child.name);+ }+ });+ return joints;+}+function validateAsset(root, category) {+ const errors = [];+ const warnings = [];+ const suggestedMats = {+ character: 8,+ prop: 6,+ vfx: 4,+ environment: 12,+ architecture: 12,+ vegetation: 8,+ vehicle: 10+ };+ const mats = countMaterials(root);+ const matLimit = suggestedMats[category];+ if (mats > matLimit) {+ warnings.push(`High material count: ${mats} (suggested: ${matLimit})`);+ }+ return { valid: true, errors, warnings };+}+function buildSandboxGlobals(usage, options = {}) {+ const wrap = (name, fn) => {+ if (!usage)+ return fn;+ const wrapped = (...args) => {+ usage[name] = (usage[name] ?? 0) + 1;+ return fn(...args);+ };+ return wrapped;+ };+ const geoCache = new Map;+ let _kilnCallSeq = 0;+ const stampKilnRange = (name, geo) => {+ const idx = geo.getIndex();+ const triCount = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;+ const callId = ++_kilnCallSeq;+ geo.userData = {+ ...geo.userData ?? {},+ kilnRanges: [+ {+ name: `${name}#${callId}`,+ start: 0,+ count: Math.floor(triCount)+ }+ ]+ };+ };+ const cacheGeo = (name, fn) => {+ const memoFn = (...args) => {+ let key;+ try {+ key = `${name}::${JSON.stringify(args)}`;+ } catch {+ const result = fn(...args);+ stampKilnRange(name, result);+ return result;+ }+ const hit = geoCache.get(key);+ if (hit)+ return hit;+ const result = fn(...args);+ stampKilnRange(name, result);+ geoCache.set(key, result);+ return result;+ };+ return memoFn;+ };+ const wrapGeo = (name, fn) => wrap(name, cacheGeo(name, fn));+ const loadApprovedTexture = (...args) => {+ if (args.length !== 1 || typeof args[0] !== "string") {+ return Promise.reject(new TypeError("loadApprovedTexture accepts exactly one approved resource ID string"));+ }+ if (!options.textureResolver) {+ return Promise.reject(new Error("loadApprovedTexture: no host TextureResolver is installed"));+ }+ return options.textureResolver.loadApprovedTexture(args[0]);+ };+ const sandboxMaterialRecipe = (...args) => {+ if (args.length < 1 || args.length > 2 || typeof args[0] !== "string") {+ return Promise.reject(new TypeError("materialRecipe accepts an approved recipe ID and optional bounded overrides"));+ }+ if (!options.textureResolver) {+ return Promise.reject(new Error("materialRecipe: no host TextureResolver is installed"));+ }+ return options.textureResolver.materialRecipe(args[0], args[1]);+ };+ return {+ createRoot: wrap("createRoot", createRoot),+ createPivot: wrap("createPivot", createPivot),+ createJointChain: wrap("createJointChain", createJointChain),+ createVehicleFrame: wrap("createVehicleFrame", createVehicleFrame),+ createWheelGeometrySet: wrap("createWheelGeometrySet", createWheelGeometrySet),+ createWheelAssembly: wrap("createWheelAssembly", createWheelAssembly),+ createPart: wrap("createPart", createPart),+ capsuleGeo: wrapGeo("capsuleGeo", capsuleGeo),+ capsuleXGeo: wrapGeo("capsuleXGeo", capsuleXGeo),+ capsuleYGeo: wrapGeo("capsuleYGeo", capsuleYGeo),+ capsuleZGeo: wrapGeo("capsuleZGeo", capsuleZGeo),+ cylinderGeo: wrapGeo("cylinderGeo", cylinderGeo),+ cylinderXGeo: wrapGeo("cylinderXGeo", cylinderXGeo),+ cylinderYGeo: wrapGeo("cylinderYGeo", cylinderYGeo),+ cylinderZGeo: wrapGeo("cylinderZGeo", cylinderZGeo),+ boxGeo: wrapGeo("boxGeo", boxGeo),+ sphereGeo: wrapGeo("sphereGeo", sphereGeo),+ coneGeo: wrapGeo("coneGeo", coneGeo),+ coneXGeo: wrapGeo("coneXGeo", coneXGeo),+ coneYGeo: wrapGeo("coneYGeo", coneYGeo),+ coneZGeo: wrapGeo("coneZGeo", coneZGeo),+ taperConeGeo: wrapGeo("taperConeGeo", taperConeGeo),+ cylinderOnAxis: wrapGeo("cylinderOnAxis", cylinderOnAxis),+ torusGeo: wrapGeo("torusGeo", torusGeo),+ planeGeo: wrapGeo("planeGeo", planeGeo),+ decalBox: wrapGeo("decalBox", decalBox),+ foliageCardGeo: wrapGeo("foliageCardGeo", foliageCardGeo),+ crossedQuadsGeo: wrapGeo("crossedQuadsGeo", crossedQuadsGeo),+ octaGridPlane: wrapGeo("octaGridPlane", octaGridPlane),+ wingGeo: wrapGeo("wingGeo", wingGeo),+ createWingPair: wrap("createWingPair", createWingPair),+ beamBetween: wrap("beamBetween", beamBetween),+ createLadder: wrap("createLadder", createLadder),+ snapTo: wrap("snapTo", snapTo),+ room: wrap("room", room),+ wallWithOpening: wrap("wallWithOpening", wallWithOpening),+ createRoofPlanes: wrap("createRoofPlanes", createRoofPlanes2),+ createGableRoof: wrap("createGableRoof", createGableRoof),+ createGableEndPanel: wrap("createGableEndPanel", createGableEndPanel),+ createGableShell: wrap("createGableShell", createGableShell),+ createRoofSurfaceLayout: wrap("createRoofSurfaceLayout", createRoofSurfaceLayout),+ createStairs: wrap("createStairs", createStairs),+ gameMaterial: wrap("gameMaterial", gameMaterial),+ materialRecipe: wrap("materialRecipe", sandboxMaterialRecipe),+ compilePortableMaterialSpecV2: wrap("compilePortableMaterialSpecV2", compilePortableMaterialSpecV2),+ basicMaterial: wrap("basicMaterial", basicMaterial),+ glassMaterial: wrap("glassMaterial", glassMaterial),+ lambertMaterial: wrap("lambertMaterial", lambertMaterial),+ rotationTrack: wrap("rotationTrack", rotationTrack),+ positionTrack: wrap("positionTrack", positionTrack),+ scaleTrack: wrap("scaleTrack", scaleTrack),+ createClip: wrap("createClip", createClip),+ spinAnimation: wrap("spinAnimation", spinAnimation),+ bobbingAnimation: wrap("bobbingAnimation", bobbingAnimation),+ idleBreathing: wrap("idleBreathing", idleBreathing),+ implicitSurface: wrap("implicitSurface", implicitSurface),+ sweepProfile: wrap("sweepProfile", sweepProfile),+ loftProfiles: wrap("loftProfiles", loftProfiles),+ bend: wrap("bend", bend),+ twist: wrap("twist", twist),+ taper: wrap("taper", taper),+ displace: wrap("displace", displace),+ copyGeometry: wrap("copyGeometry", copyGeometry),+ copyMaterial: wrap("copyMaterial", copyMaterial),+ meshGeo: wrap("meshGeo", meshGeo),+ parametricSurface: wrap("parametricSurface", parametricSurface),+ creaseNormals: wrap("creaseNormals", creaseNormals),+ geometryDiagnostics: wrap("geometryDiagnostics", geometryDiagnostics),+ cloneGeometry: wrap("cloneGeometry", cloneGeometry),+ cloneMaterial: wrap("cloneMaterial", cloneMaterial),+ createInstance: wrap("createInstance", createInstance),+ boolUnion: wrap("boolUnion", boolUnion),+ boolDiff: wrap("boolDiff", boolDiff),+ boolIntersect: wrap("boolIntersect", boolIntersect),+ hull: wrap("hull", hull),+ roundedBoxGeo: wrap("roundedBoxGeo", roundedBoxGeo),+ extrudeProfile: wrap("extrudeProfile", extrudeProfile),+ revolveProfile: wrap("revolveProfile", revolveProfile),+ circleProfile: wrap("circleProfile", circleProfile),+ arrayLinear: wrap("arrayLinear", arrayLinear),+ arrayRadial: wrap("arrayRadial", arrayRadial),+ mirror: wrap("mirror", mirror),+ subdivide: wrap("subdivide", subdivide),+ mergeVertices: wrap("mergeVertices", mergeVertices),+ curveToMesh: wrap("curveToMesh", curveToMesh),+ pipeAlongPath: wrap("pipeAlongPath", pipeAlongPath),+ lathe: wrap("lathe", lathe),+ revolveGeo: wrap("revolveGeo", revolveGeo),+ bezierCurve: wrap("bezierCurve", bezierCurve),+ autoUnwrap: wrap("autoUnwrap", autoUnwrap),+ boxUnwrap: wrap("boxUnwrap", boxUnwrap),+ cylinderUnwrap: wrap("cylinderUnwrap", cylinderUnwrap),+ planeUnwrap: wrap("planeUnwrap", planeUnwrap),+ panelRemapV: wrap("panelRemapV", panelRemapV),+ gearGeo: wrapGeo("gearGeo", gearGeo),+ bladeGeo: wrapGeo("bladeGeo", bladeGeo),+ loadApprovedTexture: wrap("loadApprovedTexture", loadApprovedTexture),+ proceduralTexture: wrap("proceduralTexture", proceduralTexture),+ normalMapFromHeight: wrap("normalMapFromHeight", normalMapFromHeight),+ pbrMaterial: wrap("pbrMaterial", pbrMaterial),+ foliageMaterial: wrap("foliageMaterial", foliageMaterial),+ countTriangles: wrap("countTriangles", countTriangles),+ countMaterials: wrap("countMaterials", countMaterials),+ getJointNames: wrap("getJointNames", getJointNames),+ validateAsset: wrap("validateAsset", validateAsset),+ THREE: THREE15,+ Math,+ console+ };+}+var cylinderYGeo, capsuleYGeo, coneYGeo;+var init_primitives = __esm(() => {+ init_character();+ init_architecture();+ init_gears();+ init_ops();+ init_geometry();+ init_deform();+ init_sweep();+ init_implicit();+ init_profile();+ init_solids();+ init_procedural_texture();+ init_textures();+ init_portable_material_runtime();+ init_vehicle();+ init_contracts();+ init_uv();+ init_uv_shapes();+ init_architecture();+ init_character();+ init_vehicle();+ init_material_recipe_runtime();+ init_portable_material_runtime();+ init_procedural_texture();+ init_implicit();+ init_sweep();+ init_deform();+ init_geometry();+ cylinderYGeo = cylinderGeo;+ capsuleYGeo = capsuleGeo;+ coneYGeo = coneGeo;+});++// src/metrics.ts+function collectGlbMetrics(doc, triangles) {+ const root = doc.getRoot();+ const geomSet = new Set;+ const matSet = new Set;+ let drawCalls = 0;+ let derivedTris = 0;+ const primTris = (prim) => {+ const idx = prim.getIndices();+ if (idx)+ return Math.floor(idx.getCount() / 3);+ const pos = prim.getAttribute("POSITION");+ return pos ? Math.floor(pos.getCount() / 3) : 0;+ };+ const instanceCopies = (node) => {+ const ext = node.getExtension("EXT_mesh_gpu_instancing");+ if (!ext)+ return 1;+ return ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 1;+ };+ const visit = (node) => {+ const mesh = node.getMesh();+ if (mesh) {+ const copies = instanceCopies(node);+ for (const prim of mesh.listPrimitives()) {+ drawCalls += 1;+ geomSet.add(prim);+ derivedTris += primTris(prim) * copies;+ const mat = prim.getMaterial();+ if (mat)+ matSet.add(mat);+ }+ }+ for (const child of node.listChildren())+ visit(child);+ };+ for (const scene of root.listScenes()) {+ for (const node of scene.listChildren())+ visit(node);+ }+ const transparentMaterials = root.listMaterials().filter((m) => m.getAlphaMode() === "BLEND").length;+ return {+ uniqueGeometries: geomSet.size,+ uniqueMaterials: matSet.size,+ drawCalls,+ textureCount: root.listTextures().length,+ skinned: root.listSkins().length > 0,+ transparentMaterials,+ triangles: triangles ?? derivedTris+ };+}+function gradeInstanceability(metrics, opts = {}) {+ const reasons = [];+ const m = metrics;+ let grade;+ if (m.uniqueMaterials <= 1)+ grade = "A";+ else if (m.uniqueMaterials <= 3)+ grade = "B";+ else if (m.uniqueMaterials <= 6)+ grade = "C";+ else if (m.uniqueMaterials <= 12)+ grade = "D";+ else+ grade = "F";+ const order = ["A", "B", "C", "D", "F"];+ const demote = (to, why) => {+ if (order.indexOf(to) > order.indexOf(grade)) {+ grade = to;+ reasons.push(why);+ } else {+ reasons.push(why);+ }+ };+ reasons.push(`${m.uniqueMaterials} material${m.uniqueMaterials === 1 ? "" : "s"}, ` + `${m.uniqueGeometries} geometr${m.uniqueGeometries === 1 ? "y" : "ies"}, ` + `${m.drawCalls} draw call${m.drawCalls === 1 ? "" : "s"}`);+ if (m.transparentMaterials > 0) {+ demote("C", `${m.transparentMaterials} transparent material(s) force per-object sort`);+ }+ if (m.textureCount > 4) {+ demote("C", `${m.textureCount} textures (consider atlasing) `.trim());+ }+ if (m.skinned) {+ reasons.push("skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts");+ }+ if (opts.category)+ reasons.push(`category: ${opts.category}`);+ const summary = `${grade} — ${m.uniqueMaterials} mat / ${m.uniqueGeometries} geo / ${m.drawCalls} draws` + (m.transparentMaterials > 0 ? ", transparent" : ", opaque") + (m.skinned ? ", skinned" : "");+ return { grade, summary, reasons, metrics: m };+}++// src/qa/gltf.ts+function finiteCount(value) {+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;+}+function normalizeIssue(value) {+ const issue = value ?? {};+ return {+ code: typeof issue.code === "string" ? issue.code : "GLTF_VALIDATOR_UNKNOWN",+ message: typeof issue.message === "string" ? issue.message : "Unknown glTF validation issue.",+ severity: finiteCount(issue.severity),+ ...typeof issue.pointer === "string" ? { pointer: issue.pointer } : {}+ };+}+function normalizeReport(value) {+ const report = value ?? {};+ const sourceIssues = report.issues ?? {};+ return {+ ...typeof report.uri === "string" ? { uri: report.uri } : {},+ ...typeof report.mimeType === "string" ? { mimeType: report.mimeType } : {},+ ...typeof report.validatorVersion === "string" ? { validatorVersion: report.validatorVersion } : {},+ ...typeof report.validatedAt === "string" ? { validatedAt: report.validatedAt } : {},+ issues: {+ numErrors: finiteCount(sourceIssues.numErrors),+ numWarnings: finiteCount(sourceIssues.numWarnings),+ numInfos: finiteCount(sourceIssues.numInfos),+ numHints: finiteCount(sourceIssues.numHints),+ messages: Array.isArray(sourceIssues.messages) ? sourceIssues.messages.map(normalizeIssue) : [],+ ...typeof sourceIssues.truncated === "boolean" ? { truncated: sourceIssues.truncated } : {}+ },+ ...report.info && typeof report.info === "object" ? { info: report.info } : {}+ };+}+async function validateFinalGlbBytes(bytes, uri = "model.glb") {+ const validator = await import("gltf-validator");+ const raw = await validator.validateBytes(bytes, {+ uri,+ maxIssues: 1000,+ externalResourceFunction: async (externalUri) => {+ throw new Error(`External glTF resource is forbidden in final GLB: ${externalUri}`);+ }+ });+ return normalizeReport(raw);+}+var init_gltf = () => {};++// src/qa/registry.ts+import { createHash as createHash4 } from "node:crypto";+function canonicalCalibrationReportEvidence(report) {+ return JSON.stringify({+ schemaVersion: report.schemaVersion,+ reportId: report.reportId,+ thresholdId: report.thresholdId,+ thresholdSha256: report.thresholdSha256,+ heldOutSetVersion: report.heldOutSetVersion,+ heldOutSetSha256: report.heldOutSetSha256,+ reviewAuthorityScheme: report.reviewAuthorityScheme,+ reviewAuthorityKeyId: report.reviewAuthorityKeyId,+ reviewAuthorityPublicKeySha256: report.reviewAuthorityPublicKeySha256,+ ruleCode: report.ruleCode,+ source: report.source,+ generatedAt: report.generatedAt,+ labeledCases: report.labeledCases,+ evaluatedCases: report.evaluatedCases,+ insufficientEvidenceCases: report.insufficientEvidenceCases,+ humanDisagreementCases: report.humanDisagreementCases,+ validExamples: report.validExamples,+ defectiveExamples: report.defectiveExamples,+ truePositive: report.truePositive,+ falsePositive: report.falsePositive,+ trueNegative: report.trueNegative,+ falseNegative: report.falseNegative,+ precision: report.precision,+ recall: report.recall,+ meanConfidence: report.meanConfidence,+ styles: report.styles,+ falseBlocks: report.falseBlocks+ });+}+function calibrationReportEvidenceSha256(report) {+ return createHash4("sha256").update(canonicalCalibrationReportEvidence(report)).digest("hex");+}+function conformancePromotionAuthorization(fixtureSetId, fixturePath, evidenceSha256, owner = KILN_ENGINE_QA_OWNER, frozenAt = "2026-07-09T00:00:00.000Z", authorizedMode = "enforce", rendererId = LEGACY_CPU_RASTER_RENDERER_ID) {+ return {+ basis: "conformance",+ authorizedMode,+ fixtureSetId,+ fixturePath,+ evidenceSha256,+ frozenAt,+ authorizedBy: owner.id,+ rendererId+ };+}+function evidenceId(promotion) {+ return promotion.basis === "conformance" ? promotion.fixtureSetId : promotion.packetId;+}+function assertOwner(owner, ruleId) {+ if (!owner || !OWNER_ID_PATTERN.test(owner.id) || owner.id === "unknown") {+ throw new TypeError(`QA rule ${ruleId} must name a stable rule owner`);+ }+ if (owner.authority !== "named" && owner.authority !== "delegated") {+ throw new TypeError(`QA rule ${ruleId} has an invalid owner authority`);+ }+}+function assertNonNegativeInteger(value, path, ruleId) {+ if (!Number.isInteger(value) || value < 0) {+ throw new TypeError(`QA rule ${ruleId} calibration ${path} must be a non-negative integer`);+ }+}+function assertCalibrationPromotion(rule, promotion) {+ const report = promotion.report;+ if (report.schemaVersion !== 1) {+ throw new TypeError(`QA rule ${rule.id} calibration report schemaVersion must be 1`);+ }+ if (!OWNER_ID_PATTERN.test(report.reportId) || promotion.packetId !== report.reportId) {+ throw new TypeError(`QA rule ${rule.id} calibration packet/report identity mismatch`);+ }+ if (report.thresholdId !== QA_026_CALIBRATION_THRESHOLD_ID || report.thresholdSha256 !== QA_026_CALIBRATION_THRESHOLD_SHA256) {+ throw new TypeError(`QA rule ${rule.id} calibration threshold identity mismatch`);+ }+ if (report.heldOutSetVersion !== QA_026_HELD_OUT_SET_VERSION || report.heldOutSetSha256 !== QA_026_HELD_OUT_SET_SHA256) {+ throw new TypeError(`QA rule ${rule.id} calibration held-out set identity mismatch`);+ }+ if (report.reviewAuthorityScheme !== QA_026_REVIEW_AUTHORITY_SCHEME || report.reviewAuthorityKeyId !== QA_026_REVIEW_AUTHORITY_KEY_ID || report.reviewAuthorityPublicKeySha256 !== QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256) {+ throw new TypeError(`QA rule ${rule.id} calibration review authority identity mismatch`);+ }+ if (report.ruleCode !== rule.id) {+ throw new TypeError(`QA rule ${rule.id} calibration report targets ${report.ruleCode}`);+ }+ const expectedSource = rule.ruleClass === "vlm" ? "vlm" : "deterministic-heuristic";+ if (report.source !== expectedSource) {+ throw new TypeError(`QA rule ${rule.id} calibration source must be ${expectedSource}`);+ }+ if (!Number.isFinite(Date.parse(report.generatedAt))) {+ throw new TypeError(`QA rule ${rule.id} calibration report generatedAt is invalid`);+ }+ if (Date.parse(promotion.frozenAt) < Date.parse(report.generatedAt)) {+ throw new TypeError(`QA rule ${rule.id} calibration cannot be frozen before its report`);+ }+ const actualReportSha256 = calibrationReportEvidenceSha256(report);+ if (promotion.evidenceSha256 !== actualReportSha256) {+ throw new TypeError(`QA rule ${rule.id} calibration report SHA-256 mismatch`);+ }+ for (const field of [+ "labeledCases",+ "evaluatedCases",+ "insufficientEvidenceCases",+ "humanDisagreementCases",+ "validExamples",+ "defectiveExamples",+ "truePositive",+ "falsePositive",+ "trueNegative",+ "falseNegative",+ "styles",+ "falseBlocks"+ ]) {+ assertNonNegativeInteger(report[field], field, rule.id);+ }+ if (!Number.isFinite(report.precision) || report.precision < 0 || report.precision > 1 || !Number.isFinite(report.recall) || report.recall < 0 || report.recall > 1) {+ throw new TypeError(`QA rule ${rule.id} calibration precision/recall must be within [0, 1]`);+ }+ if (report.validExamples !== report.trueNegative + report.falsePositive) {+ throw new TypeError(`QA rule ${rule.id} calibration valid-example confusion counts mismatch`);+ }+ if (report.defectiveExamples !== report.truePositive + report.falseNegative) {+ throw new TypeError(`QA rule ${rule.id} calibration defective-example confusion counts mismatch`);+ }+ if (report.evaluatedCases !== report.validExamples + report.defectiveExamples) {+ throw new TypeError(`QA rule ${rule.id} calibration evaluated-case count mismatch`);+ }+ if (report.labeledCases !== report.evaluatedCases + report.insufficientEvidenceCases + report.humanDisagreementCases) {+ throw new TypeError(`QA rule ${rule.id} calibration labeled-case count mismatch`);+ }+ const warn = QA_026_WARN_PROMOTION_MINIMUMS;+ if (report.evaluatedCases < warn.evaluatedCases || report.validExamples < warn.validExamples || report.defectiveExamples < warn.defectiveExamples || report.styles < warn.styles) {+ throw new Error(`QA rule ${rule.id} calibration does not meet the warn promotion minimums`);+ }+ const expectedPrecision = roundedRatio(report.truePositive, report.truePositive + report.falsePositive);+ const expectedRecall = roundedRatio(report.truePositive, report.truePositive + report.falseNegative);+ if (!Number.isFinite(expectedPrecision) || !Number.isFinite(expectedRecall) || report.precision !== expectedPrecision || report.recall !== expectedRecall) {+ throw new TypeError(`QA rule ${rule.id} calibration metrics do not match confusion counts`);+ }+ if (report.insufficientEvidenceCases !== 0 || report.humanDisagreementCases !== 0) {+ throw new Error(`QA rule ${rule.id} calibration has unresolved evidence or human disagreement`);+ }+ if (report.precision < warn.precision || report.recall < warn.recall) {+ throw new Error(`QA rule ${rule.id} calibration does not meet the warn promotion minimums`);+ }+ if (report.source === "vlm") {+ if (report.meanConfidence === null || !Number.isFinite(report.meanConfidence) || report.meanConfidence < warn.vlmMeanConfidence || report.meanConfidence > 1) {+ throw new Error(`QA rule ${rule.id} VLM calibration confidence is below the warn minimum`);+ }+ if (promotion.authorizedMode !== "warn") {+ throw new Error(`VLM QA rule ${rule.id} promotion is permanently capped at warn`);+ }+ } else if (report.meanConfidence !== null) {+ throw new TypeError(`QA rule ${rule.id} deterministic calibration meanConfidence must be null`);+ }+ if (promotion.authorizedMode === "warn") {+ if (report.falseBlocks !== 0) {+ throw new Error(`QA rule ${rule.id} warning calibration cannot report false blocks`);+ }+ return;+ }+ const enforce = QA_026_ENFORCE_PROMOTION_MINIMUMS;+ if (report.evaluatedCases < enforce.evaluatedCases || report.validExamples < enforce.validExamples || report.defectiveExamples < enforce.defectiveExamples || report.precision < enforce.precision || report.recall < enforce.recall || report.styles < enforce.styles || report.falsePositive !== 0 || report.falseBlocks !== enforce.falseBlocks) {+ throw new Error(`QA rule ${rule.id} calibration does not meet the enforce promotion minimums`);+ }+}+function assertPromotionShape(rule, promotion) {+ if (promotion.authorizedMode !== "warn" && promotion.authorizedMode !== "enforce") {+ throw new TypeError(`QA rule ${rule.id} promotion must explicitly authorize warn or enforce`);+ }+ if (!evidenceId(promotion).trim()) {+ throw new TypeError(`QA rule ${rule.id} promotion evidence must have a stable id`);+ }+ if (promotion.basis === "conformance" && (!promotion.fixturePath.startsWith("src/qa/") || !promotion.fixturePath.endsWith(".test.ts"))) {+ throw new TypeError(`QA rule ${rule.id} conformance evidence must name a repository-relative src/qa/*.test.ts fixture`);+ }+ if (!SHA256_PATTERN.test(promotion.evidenceSha256)) {+ throw new TypeError(`QA rule ${rule.id} promotion evidence must have a lowercase SHA-256`);+ }+ if (typeof promotion.rendererId !== "string" || !promotion.rendererId.trim()) {+ throw new TypeError(`QA rule ${rule.id} promotion evidence must name its producing rendererId ` + `(e.g. "cpu-raster:0.6.0"; pre-existing evidence uses "${LEGACY_CPU_RASTER_RENDERER_ID}")`);+ }+ if (!RENDERER_ID_PATTERN.test(promotion.rendererId)) {+ throw new TypeError(`QA rule ${rule.id} promotion rendererId "${promotion.rendererId}" must start with a ` + `renderer family prefix followed by ':' (e.g. "cpu-raster:", "dawn-vulkan:")`);+ }+ if (!Number.isFinite(Date.parse(promotion.frozenAt))) {+ throw new TypeError(`QA rule ${rule.id} promotion evidence must have a frozenAt timestamp`);+ }+ if (promotion.authorizedBy !== rule.owner.id) {+ throw new TypeError(`QA rule ${rule.id} promotion must be authorized by its named rule owner`);+ }+ if (promotion.basis === "conformance") {+ if (rule.ruleClass !== "exact") {+ throw new TypeError(`Non-exact QA rule ${rule.id} cannot use conformance promotion evidence`);+ }+ } else {+ if (rule.ruleClass === "exact") {+ throw new TypeError(`Exact QA rule ${rule.id} cannot use QA-026 calibration evidence`);+ }+ assertCalibrationPromotion(rule, promotion);+ }+}+function assertModeAuthorized(rule, mode) {+ assertOwner(rule.owner, rule.id);+ if (!QA_RULE_MODES.includes(mode)) {+ throw new TypeError(`QA rule ${rule.id} received unsupported rollout mode ${String(mode)}`);+ }+ if (mode === "off" || mode === "observe") {+ if (rule.promotion)+ assertPromotionShape(rule, rule.promotion);+ return;+ }+ if (rule.ruleClass === "appearance") {+ throw new Error(`Appearance QA rule ${rule.id} cannot exceed observe; appearance findings derive from rendered output and are never gates`);+ }+ const promotion = rule.promotion;+ if (!promotion) {+ throw new Error(`QA rule ${rule.id} cannot enter ${mode} without frozen promotion evidence and owner authorization`);+ }+ assertPromotionShape(rule, promotion);+ if (rule.ruleClass === "vlm" && mode === "enforce") {+ throw new Error(`VLM QA rule ${rule.id} cannot be enforced; VLM findings are never blockers`);+ }+ if (mode === "enforce" && promotion.authorizedMode !== "enforce") {+ throw new Error(`QA rule ${rule.id} promotion authorizes warn, not enforce; a new owner approval is required`);+ }+ if (rule.ruleClass === "exact" && promotion.basis !== "conformance") {+ throw new Error(`Exact QA rule ${rule.id} requires conformance-fixture promotion evidence`);+ }+ if (rule.ruleClass !== "exact" && promotion.basis !== "qa-026-calibration") {+ throw new Error(`QA rule ${rule.id} requires frozen QA-026 calibration evidence`);+ }+}+function policyDecision(rule, mode) {+ const promotion = rule.promotion;+ return {+ ruleId: rule.id,+ profile: rule.profile,+ mode,+ ruleClass: rule.ruleClass,+ owner: { ...rule.owner },+ ...promotion ? {+ promotionBasis: promotion.basis,+ authorizedMode: promotion.authorizedMode,+ evidenceId: evidenceId(promotion)+ } : {}+ };+}+function applies(rule, context) {+ const { scope } = rule;+ if (scope.kind === "universal")+ return true;+ if (scope.kind === "category")+ return context.intent.category === scope.category;+ if (scope.kind === "subtype") {+ return context.intent.category === scope.category && context.intent.subtype === scope.subtype;+ }+ return context.intent.capabilities.includes(scope.capability);+}+function effectiveMode(rule, policy) {+ return policy.byRule?.[rule.id] ?? policy.byProfile?.[rule.profile] ?? policy.defaultMode ?? rule.defaultMode;+}+function applyMode(finding, mode) {+ if (mode === "observe")+ return { ...finding, disposition: "observe" };+ if (mode === "warn")+ return { ...finding, disposition: "warn" };+ return finding;+}++class QaRegistry {+ #rules = [];+ #ids = new Set;+ constructor(rules = []) {+ for (const rule of rules)+ this.register(rule);+ }+ register(rule) {+ if (!/^[A-Z][A-Z0-9_]*$/.test(rule.id)) {+ throw new TypeError(`QA rule id must be a stable uppercase code: ${rule.id}`);+ }+ if (this.#ids.has(rule.id))+ throw new Error(`Duplicate QA rule id: ${rule.id}`);+ if (!QA_RULE_CLASSES.includes(rule.ruleClass)) {+ throw new TypeError(`QA rule ${rule.id} has an invalid rule class: ${rule.ruleClass}`);+ }+ assertModeAuthorized(rule, rule.defaultMode);+ this.#ids.add(rule.id);+ this.#rules.push(rule);+ return this;+ }+ list(context) {+ return context ? this.#rules.filter((rule) => applies(rule, context)) : [...this.#rules];+ }+ describePolicy(policy = {}) {+ return this.#rules.map((rule) => {+ const mode = effectiveMode(rule, policy);+ assertModeAuthorized(rule, mode);+ return policyDecision(rule, mode);+ });+ }+ run(context, policy = {}) {+ const findings = [];+ const executedRules = [];+ const skippedRules = [];+ const decisions = [];+ for (const rule of this.#rules) {+ if (!applies(rule, context))+ continue;+ const mode = effectiveMode(rule, policy);+ assertModeAuthorized(rule, mode);+ decisions.push(policyDecision(rule, mode));+ if (mode === "off") {+ skippedRules.push(rule.id);+ continue;+ }+ executedRules.push(rule.id);+ for (const finding of rule.evaluate(context))+ findings.push(applyMode(finding, mode));+ }+ return { findings, executedRules, skippedRules, decisions };+ }+}+var QA_RULE_MODES, QA_RULE_CLASSES, LEGACY_CPU_RASTER_RENDERER_ID = "cpu-raster:legacy", QA_026_CALIBRATION_THRESHOLD_ID = "kiln.asset-quality-calibration.thresholds.v1", QA_026_CALIBRATION_THRESHOLD_SHA256 = "054ce5088b6b0685bbc0492f8bed0121311cf18920c5697bd6dce66dcb7b2cf9", QA_026_HELD_OUT_SET_VERSION = "kiln.asset-quality.held-out.v1", QA_026_HELD_OUT_SET_SHA256 = "27c17e0e9dbcf22915550b46a94e6afaafe80584f30429e4eb97435163a176bd", QA_026_REVIEW_AUTHORITY_SCHEME = "ed25519", QA_026_REVIEW_AUTHORITY_KEY_ID = "kiln-studio.asset-quality-review.prod.v1", QA_026_REVIEW_AUTHORITY_PUBLIC_KEY_SHA256 = "08791ade50e377dfb3dc6bc1e852419515fbdaadabcd3880770507a2f192a528", QA_026_WARN_PROMOTION_MINIMUMS, QA_026_ENFORCE_PROMOTION_MINIMUMS, KILN_ENGINE_QA_OWNER, SHA256_PATTERN, OWNER_ID_PATTERN, RENDERER_ID_PATTERN, roundedRatio = (numerator, denominator) => Math.round(numerator / denominator * 1e6) / 1e6;+var init_registry = __esm(() => {+ QA_RULE_MODES = ["off", "observe", "warn", "enforce"];+ QA_RULE_CLASSES = ["exact", "heuristic", "vlm", "appearance"];+ QA_026_WARN_PROMOTION_MINIMUMS = Object.freeze({+ evaluatedCases: 20,+ validExamples: 5,+ defectiveExamples: 5,+ precision: 0.9,+ recall: 0.7,+ vlmMeanConfidence: 0.75,+ styles: 1+ });+ QA_026_ENFORCE_PROMOTION_MINIMUMS = Object.freeze({+ evaluatedCases: 60,+ validExamples: 30,+ defectiveExamples: 30,+ precision: 0.9,+ recall: 0.9,+ styles: 3,+ falseBlocks: 0+ });+ KILN_ENGINE_QA_OWNER = Object.freeze({+ id: "kiln-engine-maintainers",+ authority: "named"+ });+ SHA256_PATTERN = /^[a-f0-9]{64}$/;+ OWNER_ID_PATTERN = /^[a-z0-9][a-z0-9:._/-]*$/;+ RENDERER_ID_PATTERN = /^[a-z0-9-]+:/;+});++// src/qa/material.ts+import * as THREE16 from "three";+function textureMeta(texture) {+ return texture.userData["kilnTexture"];+}+function affected(mesh, material, texture, attribute) {+ return {+ node: mesh.name || "(unnamed mesh)",+ material: material.name || "(unnamed material)",+ ...texture ? { texture: texture.name || "(unnamed texture)" } : {},+ ...attribute ? { attribute } : {}+ };+}+function textureHasAlpha(texture) {+ const meta = textureMeta(texture);+ if (meta)+ return meta.hasAlpha;+ const image = texture.image;+ const data = image?.data;+ if (!data || data.length < 4)+ return false;+ for (let i = 3;i < data.length; i += 4) {+ if ((data[i] ?? 255) < 255)+ return true;+ }+ return false;+}+function encodedTextureIsExportable(texture) {+ const encoded = texture.userData["encoded"];+ if (!encoded || typeof encoded.mime !== "string")+ return false;+ const bytes = encoded.bytes;+ if (!bytes || typeof bytes.length !== "number" || bytes.length < 4)+ return false;+ if (encoded.mime === "image/png") {+ return bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71;+ }+ if (encoded.mime === "image/jpeg") {+ return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;+ }+ if (encoded.mime === "image/webp") {+ return bytes.length >= 12 && bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80;+ }+ return false;+}+function validateTextureSlot(findings, mesh, material, texture, slot, expected) {+ if (!texture)+ return;+ const meta = textureMeta(texture);+ const actual = texture.colorSpace === THREE16.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE16.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";+ if (!meta || !encodedTextureIsExportable(texture)) {+ findings.push({+ code: "MAT_TEXTURE_DECODE_FAILED",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "material.portablePbr",+ message: `${slot} texture has no verified decoded/exportable image payload.`,+ affected: affected(mesh, material, texture, slot),+ repairText: "Use loadApprovedTexture(resourceId) or proceduralTexture() before assigning it. A texture built in code is baked to PNG automatically, so reaching this means its pixels were unreadable — it must be a DataTexture holding 8-bit RGB or RGBA bytes, not float data or an image element."+ });+ }+ if (actual !== expected) {+ findings.push({+ code: "MAT_TEXTURE_COLOR_SPACE",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "material.portablePbr",+ message: `${slot} texture must use ${expected} data interpretation, not ${actual}.`,+ affected: affected(mesh, material, texture, slot),+ measurement: { name: "colorSpace", actual, expected },+ repairText: `Choose an approved resource whose declared usage matches '${slot === "map" ? "albedo" : slot}', or for a texture built in code set texture.colorSpace = ${expected === "srgb" ? "THREE.SRGBColorSpace" : "THREE.NoColorSpace"} — it is never set for you, because reinterpreting an author's pixels silently is exactly the failure this check exists to catch.`+ });+ }+ const image = texture.image;+ if (!image || !Number.isFinite(image.width) || !Number.isFinite(image.height) || (image.width ?? 0) <= 0 || (image.height ?? 0) <= 0) {+ findings.push({+ code: "MAT_TEXTURE_INVALID_DIMENSIONS",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "material.portablePbr",+ message: `${slot} texture has invalid or undecodable dimensions.`,+ affected: affected(mesh, material, texture, slot),+ repairText: "Use a decodable PNG, JPEG, or WebP with positive dimensions."+ });+ }+ if (!mesh.geometry.getAttribute("uv")) {+ findings.push({+ code: "MAT_TEXTURE_UV_MISSING",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "material.portablePbr",+ message: `${slot} texture is used on geometry without TEXCOORD_0 UVs.`,+ affected: affected(mesh, material, texture, slot),+ repairText: "Unwrap the geometry before assigning a texture-backed material."+ });+ }+}+function validateMaterial2(mesh, material, requiresPrecomputedTangents) {+ const findings = [];+ const standard = material;+ if (!standard.isMeshStandardMaterial)+ return findings;+ for (const [name, value] of [+ ["roughness", standard.roughness],+ ["metalness", standard.metalness],+ ["opacity", standard.opacity],+ ["emissiveIntensity", standard.emissiveIntensity]+ ]) {+ if (!Number.isFinite(value)) {+ findings.push({+ code: "MAT_NONFINITE_FACTOR",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "material.portablePbr",+ message: `Material factor ${name} is non-finite.`,+ affected: affected(mesh, material),+ measurement: { name, actual: String(value) }+ });+ }+ }+ validateTextureSlot(findings, mesh, standard, standard.map, "map", "srgb");+ validateTextureSlot(findings, mesh, standard, standard.emissiveMap, "emissive", "srgb");+ validateTextureSlot(findings, mesh, standard, standard.normalMap, "normal", "linear");+ validateTextureSlot(findings, mesh, standard, standard.roughnessMap, "metallicRoughness", "linear");+ validateTextureSlot(findings, mesh, standard, standard.metalnessMap, "metallicRoughness", "linear");+ validateTextureSlot(findings, mesh, standard, standard.aoMap, "occlusion", "linear");+ if (standard.normalMap && !mesh.geometry.getAttribute("tangent")) {+ findings.push({+ code: "MAT_NORMAL_TANGENTS_MISSING",+ disposition: requiresPrecomputedTangents ? "block" : "warn",+ dimension: "categoryReadiness",+ profile: "material.portablePbr",+ message: requiresPrecomputedTangents ? "The trusted consumer profile requires precomputed tangents for normal-mapped geometry." : "Normal-mapped geometry has no precomputed tangents; the consumer must derive them.",+ affected: affected(mesh, material, standard.normalMap, "normal"),+ repairText: "Generate and export TANGENT data for the normal-mapped geometry."+ });+ }+ if (standard.roughnessMap && standard.metalnessMap && standard.roughnessMap !== standard.metalnessMap) {+ findings.push({+ code: "MAT_SEPARATE_METALLIC_ROUGHNESS",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "material.portablePbr",+ message: "glTF requires one packed metallic-roughness texture (G=roughness, B=metalness).",+ affected: affected(mesh, material),+ repairText: "Pack both channels and pass the result as metallicRoughness."+ });+ }+ if (mesh.geometry.userData["kilnGeometryRole"] === "foliageCard") {+ const validMask = standard.alphaTest > 0 && !standard.transparent;+ if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE16.DoubleSide || !mesh.geometry.getAttribute("uv")) {+ findings.push({+ code: "MAT_FOLIAGE_CARD_CONTRACT",+ disposition: "block",+ dimension: "categoryReadiness",+ profile: "material.foliageCard",+ message: "Foliage cards require UVs, an alpha-bearing base-color texture, MASK cutoff, and double-sided output.",+ affected: affected(mesh, material, standard.map ?? undefined),+ repairText: "Use foliageMaterial() with an alpha-bearing albedo texture."+ });+ }+ }+ return findings;+}+function inspectSceneMaterials(context) {+ const root = context.scene;+ if (!root?.traverse)+ return [];+ const findings = [];+ const requiresPrecomputedTangents = context.intent.capabilities.includes("precomputedTangents");+ root.traverse((node) => {+ const mesh = node;+ if (!mesh.isMesh || !mesh.geometry)+ return;+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];+ for (const material of materials) {+ if (material) {+ findings.push(...validateMaterial2(mesh, material, requiresPrecomputedTangents));+ }+ }+ });+ return findings;+}+var MATERIAL_QA_RULE;+var init_material = __esm(() => {+ init_registry();+ MATERIAL_QA_RULE = {+ id: "MATERIAL_PORTABLE_PBR_RULE",+ profile: "material.portablePbr",+ scope: { kind: "universal" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("material-portable-pbr-v1", "src/qa/material.test.ts", "27f7469603ba986acfac2c6acbfb293ad787717aecdf4a3d03cae625f86f45e7"),+ defaultMode: "enforce",+ evaluate: inspectSceneMaterials+ };+});++// src/qa/architecture-repairs.ts+function architectureRepairRecipe(code) {+ return ARCHITECTURE_REPAIR_RECIPES[code];+}+function withArchitectureRepair(finding) {+ const recipe = architectureRepairRecipe(finding.code);+ if (!recipe)+ return finding;+ return {+ ...finding,+ repairText: finding.repairText ?? recipe.repairText,+ viewHints: [...new Set([...finding.viewHints ?? [], ...recipe.viewHints])]+ };+}+var ARCHITECTURE_REPAIR_RECIPES;+var init_architecture_repairs = __esm(() => {+ ARCHITECTURE_REPAIR_RECIPES = Object.freeze({+ ARCH_ROOF_AXIS: Object.freeze({+ code: "ARCH_ROOF_AXIS",+ repairText: "Edit only the reported roof slope or panel: keep the declared ridge axis fixed, mirror the two slope frames, and rotate panel span 90 degrees in roof-local space so it runs ridge-to-eave. Recheck both gable elevations and the top wireframe.",+ viewHints: Object.freeze([+ "architecture.gable.positive",+ "architecture.gable.negative",+ "generic.top.wireframe"+ ])}),- "kiln.texture.oak-veneer-normal.v1": Object.freeze({- sourceAsset: "oak_veneer_01",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/oak_veneer_01/oak_veneer_01_nor_gl_1k.jpg",- sourceMd5: "d05406f5fdaf51f0d7b115b35d9af1b7",- transform: "sharp 128x128 Lanczos3 PNG"+ ARCH_OPEN_GABLE: Object.freeze({+ code: "ARCH_OPEN_GABLE",+ repairText: "Add or complete only the reported roof.gable end panel. Its projected triangle must cover the full wall-top-to-ridge cross-section and meet both slopes; preserve intentional openings and the opposite end.",+ viewHints: Object.freeze([+ "architecture.gable.positive",+ "architecture.gable.negative",+ "generic.front.semantic-overlay"+ ])}),- "kiln.texture.oak-veneer-arm.v1": Object.freeze({- sourceAsset: "oak_veneer_01",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/oak_veneer_01/oak_veneer_01_arm_1k.jpg",- sourceMd5: "dfba0f063663289248f4e887f836bdcc",- transform: "sharp 128x128 Lanczos3 PNG"+ ARCH_RIDGE_GAP: Object.freeze({+ code: "ARCH_RIDGE_GAP",+ repairText: "Move only the reported slope high edge in its roof-local downhill direction until both high edges share the declared ridge line within tolerance. Do not change footprint, pitch, eaves, or overhang.",+ viewHints: Object.freeze([+ "architecture.gable.positive",+ "architecture.gable.negative",+ "generic.top.depth-contact"+ ])}),- "kiln.texture.polished-marble-albedo.v1": Object.freeze({- sourceAsset: "marble_01",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/marble_01/marble_01_diff_1k.jpg",- sourceMd5: "04325ced5018eb8a2e598a4ef69cb176",- transform: "sharp 128x128 Lanczos3 PNG"+ ARCH_ENVELOPE_GAP: Object.freeze({+ code: "ARCH_ENVELOPE_GAP",+ repairText: "At the reported wall-boundary samples, align the roof underside to the wall top plate within tolerance. Preserve the declared exterior overhang and do not close sides marked as an open pavilion.",+ viewHints: Object.freeze([+ "architecture.cutaway.dollhouse",+ "generic.front.depth-contact",+ "generic.right.depth-contact"+ ])}),- "kiln.texture.polished-marble-normal.v1": Object.freeze({- sourceAsset: "marble_01",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/marble_01/marble_01_nor_gl_1k.jpg",- sourceMd5: "fa073d722cde733c1bd6cc6e8897c8e3",- transform: "sharp 128x128 Lanczos3 PNG"+ ARCH_BLOCKED_PORTAL: Object.freeze({+ code: "ARCH_BLOCKED_PORTAL",+ repairText: "Remove or split only the reported blocker inside the opening clearance prism so the tagged exterior portal connects to the interior at the requested width, height, and depth. A painted door on a solid wall is not an opening.",+ viewHints: Object.freeze([+ "architecture.portal.eye",+ "architecture.cutaway.plan",+ "generic.front.depth-contact"+ ])+ })+ });+});++// src/qa/architecture.ts+import * as THREE17 from "three";+function semanticMetadata(node) {+ return readSemanticMetadataV1FromExtras(node.userData);+}+function markerBounds(matrix) {+ const bounds = emptyBounds();+ for (let corner = 0;corner < 8; corner++) {+ expandBounds(bounds, new THREE17.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));+ }+ return bounds;+}+function geometryPlaneNormal(geometry, relativeMatrix) {+ geometry.computeBoundingBox();+ const local = geometry.boundingBox;+ if (!local)+ return;+ const size = local.getSize(new THREE17.Vector3);+ const dimensions = [+ ["x", size.x],+ ["y", size.y],+ ["z", size.z]+ ];+ dimensions.sort((a, b) => a[1] - b[1]);+ const axis = dimensions[0]?.[0];+ if (!axis)+ return;+ const normal = new THREE17.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);+ if (normal.y < 0)+ normal.multiplyScalar(-1);+ return normal.normalize();+}+function geometryEvidence(geometry, relativeMatrix) {+ const position = geometry.getAttribute("position");+ const bounds = emptyBounds();+ const vertices = [];+ if (position?.itemSize !== 3)+ return { bounds, vertices, triangles: [] };+ for (let index = 0;index < position.count; index++) {+ const point = new THREE17.Vector3(position.getX(index), position.getY(index), position.getZ(index));+ point.applyMatrix4(relativeMatrix);+ vertices.push(point);+ expandBounds(bounds, point);+ }+ const triangles = [];+ const indices = geometry.getIndex();+ const addTriangle = (a, b, c) => {+ const va = vertices[a];+ const vb = vertices[b];+ const vc = vertices[c];+ if (va && vb && vc)+ triangles.push({ a: va, b: vb, c: vc });+ };+ if (indices) {+ for (let index = 0;index + 2 < indices.count; index += 3) {+ addTriangle(indices.getX(index), indices.getX(index + 1), indices.getX(index + 2));+ }+ } else {+ for (let index = 0;index + 2 < vertices.length; index += 3) {+ addTriangle(index, index + 1, index + 2);+ }+ }+ const planeNormal = geometryPlaneNormal(geometry, relativeMatrix);+ return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };+}+function collectArchitectureEvidence(scene) {+ if (!(scene instanceof THREE17.Object3D))+ return;+ scene.updateMatrixWorld(true);+ const rootInverse = scene.matrixWorld.clone().invert();+ const parts = [];+ const allRoles = new Set;+ const visit = (node, parentPath, siblingIndex, inheritedRoles) => {+ const metadata = semanticMetadata(node);+ const directRoles = metadata?.roles ?? [];+ const directRelationships = metadata?.relationships ?? [];+ directRoles.forEach((role) => {+ allRoles.add(role);+ });+ const roles = [...new Set([...inheritedRoles, ...directRoles])];+ const segment = `${node.name.trim() || node.type || "Object3D"}[${siblingIndex}]`;+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);+ const mesh = node;+ const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE17.BufferGeometry;+ const evidence = isMesh ? geometryEvidence(mesh.geometry, relativeMatrix) : {+ bounds: markerBounds(relativeMatrix),+ vertices: [],+ triangles: []+ };+ if (isMesh || directRoles.length > 0) {+ parts.push({+ node,+ nodeName: node.name || node.type,+ nodePath,+ directRoles,+ directRelationships,+ roles,+ isMesh,+ ...evidence+ });+ }+ node.children.forEach((child, index) => {+ visit(child, nodePath, index, roles);+ });+ };+ visit(scene, "", 0, []);+ return { root: scene, parts, semanticRoles: allRoles };+}+function aggregate(parts) {+ if (parts.length === 0)+ return;+ const bounds = emptyBounds();+ const vertices = [];+ const triangles = [];+ const normals = [];+ for (const part of parts) {+ if (boundsFinite(part.bounds)) {+ expandBounds(bounds, part.bounds.min);+ expandBounds(bounds, part.bounds.max);+ }+ vertices.push(...part.vertices);+ triangles.push(...part.triangles);+ if (part.planeNormal)+ normals.push(part.planeNormal);+ }+ if (!boundsFinite(bounds))+ return;+ return { parts: [...parts], bounds, vertices, triangles, normals };+}+function aggregateRole(evidence, role) {+ return aggregate(evidence.parts.filter((part) => hasRole(part, role)));+}+function architectureFinding(context, value) {+ return withArchitectureRepair({+ ...value,+ profile: context.intent.qaProfile,+ dimension: "categoryReadiness"+ });+}+function averageNormal(normals) {+ if (normals.length === 0)+ return;+ const result = normals.reduce((sum, normal) => sum.add(normal), new THREE17.Vector3);+ return result.lengthSq() > EPSILON2 ? result.normalize() : undefined;+}+function intervalCoverage(min, max, expectedMin, expectedMax) {+ const expected = expectedMax - expectedMin;+ if (expected <= EPSILON2)+ return 1;+ return Math.max(0, Math.min(max, expectedMax) - Math.max(min, expectedMin)) / expected;+}+function intervalSeparation(aMin, aMax, bMin, bMax) {+ if (aMax < bMin)+ return bMin - aMax;+ if (bMax < aMin)+ return aMin - bMax;+ return 0;+}+function requestedGable(architecture) {+ return architecture.roof.type === "gable";+}+function taggedGable(evidence) {+ return [...evidence.semanticRoles].some((role) => role === "architecture.shell.gable" || role.startsWith("roof.slope.") || role.startsWith("roof.gable."));+}+function isOpenPavilion(architecture, evidence) {+ return /(?:^|[. _-])(?:open[. _-])?pavilion(?:$|[. _-])/i.test(architecture.subtype) || evidence.semanticRoles.has("architecture.open-pavilion");+}+function highEdgeVertices(aggregateValue, rise) {+ const band = Math.max(0.006, rise * 0.02);+ const maximumY = aggregateValue.bounds.max.y;+ return aggregateValue.vertices.filter((point) => point.y >= maximumY - band);+}+function ridgeCrossSectionDistance(positive, negative, lateralAxis, rise) {+ const a = highEdgeVertices(positive, rise);+ const b = highEdgeVertices(negative, rise);+ let distance = Infinity;+ for (const pointA of a) {+ for (const pointB of b) {+ distance = Math.min(distance, Math.hypot(pointA[lateralAxis] - pointB[lateralAxis], pointA.y - pointB.y));+ }+ }+ return distance;+}+function roofFindings(context, architecture, evidence) {+ if (!requestedGable(architecture) && !taggedGable(evidence))+ return [];+ const positive = aggregateRole(evidence, "roof.slope.positive");+ const negative = aggregateRole(evidence, "roof.slope.negative");+ const tagged = taggedGable(evidence);+ const exactDisposition = tagged ? "block" : "warn";+ const findings = [];+ if (!positive || !negative) {+ findings.push(architectureFinding(context, {+ code: "ARCH_ROOF_AXIS",+ disposition: exactDisposition,+ message: `A gable requires exactly two semantic slope roles; found ${positive ? 1 : 0} positive and ${negative ? 1 : 0} negative slope surfaces.`,+ measurement: {+ name: "semanticSlopeRoleCount",+ actual: Number(Boolean(positive)) + Number(Boolean(negative)),+ expected: 2,+ threshold: 2+ },+ affected: { node: evidence.root.name || "architecture-root" }+ }));+ }+ const semanticRoofRoles = [...evidence.semanticRoles].filter((role) => role.startsWith("roof."));+ if (semanticRoofRoles.length === 0) {+ const inferredRoof = evidence.parts.find((part) => part.isMesh && /(?:^|[_ .-])roof(?:$|[_ .-])/i.test(part.nodeName));+ findings.push(architectureFinding(context, {+ code: "ARCH_MISSING_ROOF_ROLES",+ disposition: "warn",+ message: "The architecture has no portable roof.* semantic roles, so ridge, coverage, diagnostic cutaway, and separability checks cannot be exact.",+ affected: inferredRoof ? { node: inferredRoof.nodeName, nodePath: inferredRoof.nodePath } : { node: evidence.root.name || "architecture-root" },+ viewHints: ["generic.top.semantic-overlay", "architecture.cutaway.dollhouse"],+ repairText: "Build the roof with the gable shell helper or stamp roof.slope.positive/negative and roof.gable.positive/negative roles plus separable-from relationships."+ }));+ return findings;+ }+ if (!positive || !negative)+ return findings;+ const ridgeAxis = architecture.roof.ridgeAxis;+ const lateralAxis = ridgeAxis === "x" ? "z" : "x";+ const positiveNormal = averageNormal(positive.normals);+ const negativeNormal = averageNormal(negative.normals);+ const lateralProduct = positiveNormal && negativeNormal ? positiveNormal[lateralAxis] * negativeNormal[lateralAxis] : null;+ if (lateralProduct === null || lateralProduct >= -0.0025) {+ findings.push(architectureFinding(context, {+ code: "ARCH_ROOF_AXIS",+ disposition: exactDisposition,+ message: "The two semantic gable slopes do not face opposite downhill directions in the declared roof-local frame.",+ affected: { node: negative.parts[0]?.nodeName ?? "roof.slope.negative" },+ measurement: {+ name: "slopeLateralNormalProduct",+ actual: lateralProduct,+ expected: "< -0.0025",+ threshold: -0.0025+ }+ }));+ }+ const { spanX, spanZ } = architecture.footprint;+ const expectedRidgeSpan = (ridgeAxis === "x" ? spanX : spanZ) + architecture.roof.overhang * 2;+ const expectedLateralSpan = (lateralAxis === "x" ? spanX : spanZ) + architecture.roof.overhang * 2;+ const ridgeCoverage = Math.min(extent(positive.bounds, ridgeAxis) / expectedRidgeSpan, extent(negative.bounds, ridgeAxis) / expectedRidgeSpan);+ const roofMinLateral = Math.min(positive.bounds.min[lateralAxis], negative.bounds.min[lateralAxis]);+ const roofMaxLateral = Math.max(positive.bounds.max[lateralAxis], negative.bounds.max[lateralAxis]);+ const lateralCoverage = intervalCoverage(roofMinLateral, roofMaxLateral, -expectedLateralSpan / 2, expectedLateralSpan / 2);+ if (ridgeCoverage < 0.9 || lateralCoverage < 0.9) {+ const actual = Math.min(ridgeCoverage, lateralCoverage);+ findings.push(architectureFinding(context, {+ code: "ARCH_ROOF_AXIS",+ disposition: exactDisposition,+ message: `The semantic slopes cover ${(ridgeCoverage * 100).toFixed(1)}% of the ridge span and ${(lateralCoverage * 100).toFixed(1)}% of the ridge-to-eave span.`,+ measurement: {+ name: "minimumRoofFootprintCoverageRatio",+ actual,+ expected: ">= 0.9",+ threshold: 0.9+ },+ affected: { node: positive.parts[0]?.nodeName ?? "roof.slope.positive" }+ }));+ }+ const panels = evidence.parts.filter((part) => part.isMesh && (part.directRoles.some((role) => role.startsWith("roof.panel.")) || hasRole(part, "roof.surface.panels") || hasRolePrefix(part, "roof.") && /panel|sheet|shingle|seam|corrugat/i.test(part.nodeName)));+ const wrongPanel = panels.find((panel) => {+ const ridgeExtent = extent(panel.bounds, ridgeAxis);+ const downhillExtent = Math.hypot(extent(panel.bounds, lateralAxis), extent(panel.bounds, "y"));+ return ridgeExtent > downhillExtent * 1.05;+ });+ if (wrongPanel) {+ const ridgeExtent = extent(wrongPanel.bounds, ridgeAxis);+ const downhillExtent = Math.hypot(extent(wrongPanel.bounds, lateralAxis), extent(wrongPanel.bounds, "y"));+ findings.push(architectureFinding(context, {+ code: "ARCH_ROOF_AXIS",+ disposition: exactDisposition,+ message: `Roof panel ${wrongPanel.nodeName} runs along the ridge instead of ridge-to-eave.`,+ affected: { node: wrongPanel.nodeName, nodePath: wrongPanel.nodePath },+ measurement: {+ name: "panelRidgeToDownhillExtentRatio",+ actual: ridgeExtent / Math.max(EPSILON2, downhillExtent),+ expected: "<= 1.05",+ threshold: 1.05+ }+ }));+ }+ const ridgeDistance = ridgeCrossSectionDistance(positive, negative, lateralAxis, architecture.roof.rise);+ const ridgeTolerance = Math.max(0.04, expectedLateralSpan * 0.0125);+ if (!Number.isFinite(ridgeDistance) || ridgeDistance > ridgeTolerance) {+ findings.push(architectureFinding(context, {+ code: "ARCH_RIDGE_GAP",+ disposition: exactDisposition,+ message: `The two slope high edges miss the declared ridge by ${Number.isFinite(ridgeDistance) ? ridgeDistance.toFixed(3) : "an unmeasurable"} m.`,+ affected: { node: negative.parts[0]?.nodeName ?? "roof.slope.negative" },+ measurement: {+ name: "ridgeCrossSectionGap",+ actual: Number.isFinite(ridgeDistance) ? ridgeDistance : null,+ expected: `<= ${ridgeTolerance}`,+ threshold: ridgeTolerance,+ unit: "m"+ }+ }));+ }+ return findings;+}+function projectedGableArea(aggregateValue, lateralAxis) {+ let area = 0;+ for (const triangle of aggregateValue.triangles) {+ const abLateral = triangle.b[lateralAxis] - triangle.a[lateralAxis];+ const abY = triangle.b.y - triangle.a.y;+ const acLateral = triangle.c[lateralAxis] - triangle.a[lateralAxis];+ const acY = triangle.c.y - triangle.a.y;+ area += Math.abs(abLateral * acY - abY * acLateral) / 2;+ }+ return area;+}+function endFindings(context, architecture, evidence) {+ if (!requestedGable(architecture) || isOpenPavilion(architecture, evidence))+ return [];+ const closedEnds = architecture.roof.closedEnds;+ if (!closedEnds)+ return [];+ const positive = aggregateRole(evidence, "roof.gable.positive");+ const negative = aggregateRole(evidence, "roof.gable.negative");+ const hasTaggedRoof = taggedGable(evidence);+ const disposition = hasTaggedRoof ? "block" : "warn";+ const ridgeAxis = architecture.roof.ridgeAxis;+ const lateralAxis = ridgeAxis === "x" ? "z" : "x";+ const lateralSpan = lateralAxis === "x" ? architecture.footprint.spanX : architecture.footprint.spanZ;+ const ridgeSpan = ridgeAxis === "x" ? architecture.footprint.spanX : architecture.footprint.spanZ;+ const expectedArea = lateralSpan * architecture.roof.rise / 2;+ const findings = [];+ for (const [end, aggregateValue] of [+ ["positive", positive],+ ["negative", negative]+ ]) {+ if (!aggregateValue) {+ findings.push(architectureFinding(context, {+ code: "ARCH_OPEN_GABLE",+ disposition,+ message: `closedEnds=true but roof.gable.${end} is missing.`,+ affected: { node: `roof.gable.${end}` },+ measurement: {+ name: `${end}GableCoverageRatio`,+ actual: 0,+ expected: ">= 0.9 boundary coverage",+ threshold: 0.9+ }+ }));+ continue;+ }+ const wallRole = ridgeAxis === "x" ? end === "positive" ? "wall.front" : "wall.back" : end === "positive" ? "wall.right" : "wall.left";+ const endWall = aggregate(evidence.parts.filter((part) => part.isMesh && hasRole(part, wallRole)));+ const gableCenter = (aggregateValue.bounds.min[ridgeAxis] + aggregateValue.bounds.max[ridgeAxis]) / 2;+ const expectedCenter = (end === "positive" ? 1 : -1) * (ridgeSpan / 2);+ const endSeparation = endWall ? intervalSeparation(aggregateValue.bounds.min[ridgeAxis], aggregateValue.bounds.max[ridgeAxis], endWall.bounds.min[ridgeAxis], endWall.bounds.max[ridgeAxis]) : Math.abs(gableCenter - expectedCenter);+ const endTolerance = 0.05;+ if (endSeparation > endTolerance) {+ findings.push(architectureFinding(context, {+ code: "ARCH_OPEN_GABLE",+ disposition,+ message: `roof.gable.${end} is ${endSeparation.toFixed(3)} m away from its ${wallRole} end boundary, so it does not close the shell.`,+ affected: {+ node: aggregateValue.parts[0]?.nodeName ?? `roof.gable.${end}`,+ nodePath: aggregateValue.parts[0]?.nodePath+ },+ measurement: {+ name: `${end}GableEndSeparation`,+ actual: endSeparation,+ expected: `<= ${endTolerance}`,+ threshold: endTolerance,+ unit: "m"+ }+ }));+ continue;+ }+ const lateralCoverage = extent(aggregateValue.bounds, lateralAxis) / lateralSpan;+ const heightCoverage = extent(aggregateValue.bounds, "y") / architecture.roof.rise;+ const areaCoverage = expectedArea > EPSILON2 ? projectedGableArea(aggregateValue, lateralAxis) / expectedArea : 1;+ const boundaryCoverage = Math.min(lateralCoverage, heightCoverage);+ if (boundaryCoverage < 0.9 || areaCoverage < 0.45) {+ findings.push(architectureFinding(context, {+ code: "ARCH_OPEN_GABLE",+ disposition,+ message: `roof.gable.${end} is sparse: boundary coverage ${(boundaryCoverage * 100).toFixed(1)}%, projected filled area ${(areaCoverage * 100).toFixed(1)}%.`,+ affected: {+ node: aggregateValue.parts[0]?.nodeName ?? `roof.gable.${end}`,+ nodePath: aggregateValue.parts[0]?.nodePath+ },+ measurement: {+ name: `${end}GableMinimumCoverageRatio`,+ actual: Math.min(boundaryCoverage, areaCoverage / 0.5),+ expected: ">= 0.9 boundary and >= 0.45 area",+ threshold: 0.9+ }+ }));+ }+ }+ return findings;+}+function pointInProjectedTriangle(x, z, triangle) {+ const ax = triangle.a.x;+ const az = triangle.a.z;+ const bx = triangle.b.x;+ const bz = triangle.b.z;+ const cx = triangle.c.x;+ const cz = triangle.c.z;+ const denominator = (bz - cz) * (ax - cx) + (cx - bx) * (az - cz);+ if (Math.abs(denominator) <= EPSILON2)+ return { inside: false, weights: [0, 0, 0] };+ const wa = ((bz - cz) * (x - cx) + (cx - bx) * (z - cz)) / denominator;+ const wb = ((cz - az) * (x - cx) + (ax - cx) * (z - cz)) / denominator;+ const wc = 1 - wa - wb;+ const tolerance = 0.00001;+ return {+ inside: wa >= -tolerance && wb >= -tolerance && wc >= -tolerance,+ weights: [wa, wb, wc]+ };+}+function nearestRoofHeight(triangles, x, z, targetY) {+ const heights = [];+ for (const triangle of triangles) {+ const projected = pointInProjectedTriangle(x, z, triangle);+ if (!projected.inside)+ continue;+ const [wa, wb, wc] = projected.weights;+ heights.push(wa * triangle.a.y + wb * triangle.b.y + wc * triangle.c.y);+ }+ return heights.sort((a, b) => Math.abs(a - targetY) - Math.abs(b - targetY))[0];+}+function envelopeFindings(context, architecture, evidence) {+ if (!requestedGable(architecture) || isOpenPavilion(architecture, evidence))+ return [];+ const roof = aggregate(evidence.parts.filter((part) => part.isMesh && (hasRole(part, "roof.slope.positive") || hasRole(part, "roof.slope.negative"))));+ if (!roof || roof.triangles.length === 0)+ return [];+ const ridgeAxis = architecture.roof.ridgeAxis;+ const lateralAxis = ridgeAxis === "x" ? "z" : "x";+ const ridgeSpan = ridgeAxis === "x" ? architecture.footprint.spanX : architecture.footprint.spanZ;+ const lateralSpan = lateralAxis === "x" ? architecture.footprint.spanX : architecture.footprint.spanZ;+ const wallRoles = ridgeAxis === "x" ? ["wall.left", "wall.right"] : ["wall.front", "wall.back"];+ const findings = [];+ const gapTolerance = 0.05;+ const penetrationTolerance = 0.12;+ for (const [sideIndex, wallRole] of wallRoles.entries()) {+ const wall = aggregateRole(evidence, wallRole);+ if (!wall)+ continue;+ const sign = sideIndex === 0 ? -1 : 1;+ const lateral = sign * (lateralSpan / 2);+ const wallTop = wall.bounds.max.y;+ const offsets = [-0.4, 0, 0.4];+ const separations = [];+ for (const offset of offsets) {+ const ridge = offset * ridgeSpan;+ const x = ridgeAxis === "x" ? ridge : lateral;+ const z = ridgeAxis === "x" ? lateral : ridge;+ const roofY = nearestRoofHeight(roof.triangles, x, z, wallTop);+ if (roofY !== undefined)+ separations.push(roofY - wallTop);+ }+ if (separations.length === 0)+ continue;+ const worstGap = Math.max(...separations);+ const worstPenetration = -Math.min(...separations);+ if (worstGap > gapTolerance || worstPenetration > penetrationTolerance) {+ const daylight = worstGap > gapTolerance;+ findings.push(architectureFinding(context, {+ code: "ARCH_ENVELOPE_GAP",+ disposition: "warn",+ message: daylight ? `${wallRole} has a ${worstGap.toFixed(3)} m daylight gap to the roof underside at sampled bearing points.` : `${wallRole} penetrates the roof envelope by ${worstPenetration.toFixed(3)} m at sampled bearing points.`,+ affected: {+ node: wall.parts[0]?.nodeName ?? wallRole,+ nodePath: wall.parts[0]?.nodePath+ },+ measurement: {+ name: daylight ? "maximumWallRoofGap" : "maximumWallRoofPenetration",+ actual: daylight ? worstGap : worstPenetration,+ expected: daylight ? `<= ${gapTolerance}` : `<= ${penetrationTolerance}`,+ threshold: daylight ? gapTolerance : penetrationTolerance,+ unit: "m"+ }+ }));+ }+ }+ return findings;+}+function boundsOverlap(a, b, tolerance = 0) {+ return a.min.x < b.max.x - tolerance && a.max.x > b.min.x + tolerance && a.min.y < b.max.y - tolerance && a.max.y > b.min.y + tolerance && a.min.z < b.max.z - tolerance && a.max.z > b.min.z + tolerance;+}+function shrunkenPortalBounds(bounds, wall) {+ const result = { min: bounds.min.clone(), max: bounds.max.clone() };+ const widthAxis = wall === "front" || wall === "back" ? "z" : "x";+ const normalAxis = widthAxis === "x" ? "z" : "x";+ const widthInset = Math.min(0.04, extent(result, widthAxis) * 0.08);+ const heightInset = Math.min(0.04, extent(result, "y") * 0.04);+ result.min[widthAxis] += widthInset;+ result.max[widthAxis] -= widthInset;+ result.min.y += heightInset;+ result.max.y -= heightInset;+ if (extent(result, normalAxis) <= EPSILON2) {+ result.min[normalAxis] -= 0.01;+ result.max[normalAxis] += 0.01;+ }+ return result;+}+function portalRoleWall(roles) {+ for (const role of roles) {+ const match = /^opening\.(front|back|left|right)\.(?:door|portal|entry)(?:\.|$)/.exec(role);+ if (match)+ return match[1];+ }+ return;+}+function portalFindings(context, architecture, evidence) {+ if (!architecture.enterable && !context.intent.capabilities.includes("enterable"))+ return [];+ const requested = architecture.portal ?? { width: 1.1, height: 2.1, depth: 0.15 };+ const markers = evidence.parts.filter((part) => !part.isMesh && portalRoleWall(part.directRoles) !== undefined);+ if (markers.length === 0) {+ return [+ architectureFinding(context, {+ code: "ARCH_BLOCKED_PORTAL",+ disposition: "block",+ message: "enterable=true requires a non-rendered semantic opening.<wall>.door clearance node; no exterior-to-interior portal was found.",+ affected: { node: evidence.root.name || "architecture-root" },+ measurement: {+ name: "semanticPortalCount",+ actual: 0,+ expected: ">= 1",+ threshold: 1+ }+ })+ ];+ }+ const failures = [];+ for (const marker of markers) {+ const wall = portalRoleWall(marker.directRoles);+ const widthAxis = wall === "front" || wall === "back" ? "z" : "x";+ const depthAxis = widthAxis === "x" ? "z" : "x";+ const width = extent(marker.bounds, widthAxis);+ const height = extent(marker.bounds, "y");+ const depth = extent(marker.bounds, depthAxis);+ const claimedWall = aggregate(evidence.parts.filter((part) => part.isMesh && hasRole(part, `wall.${wall}`) && !hasRolePrefix(part, "opening.")));+ const placementCoverage = claimedWall ? Math.min(intervalCoverage(marker.bounds.min[depthAxis], marker.bounds.max[depthAxis], claimedWall.bounds.min[depthAxis], claimedWall.bounds.max[depthAxis]), intervalCoverage(claimedWall.bounds.min[widthAxis], claimedWall.bounds.max[widthAxis], marker.bounds.min[widthAxis], marker.bounds.max[widthAxis]), intervalCoverage(claimedWall.bounds.min.y, claimedWall.bounds.max.y, marker.bounds.min.y, marker.bounds.max.y)) : 0;+ const misplaced = placementCoverage < 0.9;+ const clearance = shrunkenPortalBounds(marker.bounds, wall);+ const blocker = evidence.parts.find((part) => {+ if (!part.isMesh)+ return false;+ if (hasRolePrefix(part, "roof.") || hasRole(part, "floor") || hasRolePrefix(part, "opening.")) {+ return false;+ }+ if (context.intent.capabilities.includes("openable") && part.roles.some((role) => role === "door.leaf" || role.startsWith("door.leaf."))) {+ return false;+ }+ return boundsOverlap(part.bounds, clearance, 0.004);+ });+ const undersized = width + 0.01 < requested.width || height + 0.01 < requested.height || depth + 0.01 < requested.depth;+ if (!blocker && !undersized && !misplaced)+ return [];+ failures.push({+ marker,+ wall,+ ...blocker ? { blocker } : {},+ width,+ height,+ depth,+ placementCoverage,+ undersized,+ misplaced+ });+ }+ const failure = failures[0];+ const undersizedBy = Math.max(0, requested.width - failure.width, requested.height - failure.height, requested.depth - failure.depth);+ return [+ architectureFinding(context, {+ code: "ARCH_BLOCKED_PORTAL",+ disposition: "block",+ message: failure.blocker ? `Portal ${failure.marker.nodeName} is blocked by ${failure.blocker.nodeName}; the semantic clearance does not connect exterior to interior.` : failure.undersized ? `Portal ${failure.marker.nodeName} is smaller than the requested ${requested.width.toFixed(2)} x ${requested.height.toFixed(2)} x ${requested.depth.toFixed(2)} m clearance.` : `Portal ${failure.marker.nodeName} overlaps only ${(failure.placementCoverage * 100).toFixed(1)}% of its claimed wall passage, so it does not connect exterior to interior through wall.${failure.wall}.`,+ affected: failure.blocker ? { node: failure.blocker.nodeName, nodePath: failure.blocker.nodePath } : { node: failure.marker.nodeName, nodePath: failure.marker.nodePath },+ measurement: failure.blocker ? {+ name: "portalBlockerCount",+ actual: 1,+ expected: 0,+ threshold: 0+ } : failure.undersized ? {+ name: "maximumPortalClearanceDeficit",+ actual: undersizedBy,+ expected: 0,+ threshold: 0.01,+ unit: "m"+ } : {+ name: "portalClaimedWallCoverageRatio",+ actual: failure.placementCoverage,+ expected: ">= 0.9",+ threshold: 0.9+ },+ viewHints: ["architecture.portal.eye"]+ })+ ];+}+function storeyFindings(context, architecture, evidence) {+ const requested = architecture.storeyCount ?? 1;+ const indexes = new Set;+ for (const role of evidence.semanticRoles) {+ const match = /^(?:architecture\.)?floor\.storey\.(\d+)$/.exec(role);+ if (match)+ indexes.add(Number(match[1]));+ }+ if (requested === 1 && indexes.size === 0)+ return [];+ const actual = indexes.size;+ if (actual === requested)+ return [];+ return [+ architectureFinding(context, {+ code: "ARCH_STOREY_COUNT",+ disposition: "block",+ message: `Requested ${requested} storeys but found ${actual} distinct portable floor.storey.<index> roles.`,+ affected: { node: evidence.root.name || "architecture-root" },+ measurement: {+ name: "semanticStoreyCount",+ actual,+ expected: requested,+ threshold: requested+ },+ viewHints: ["architecture.cutaway.dollhouse", "generic.top.semantic-overlay"],+ repairText: "Add or remove only the requested floor levels, stamp each level once as floor.storey.<1-5>, and keep stairs and clearances aligned between consecutive levels."+ })+ ];+}+function interiorModeFindings(context, architecture, evidence) {+ const mode = architecture.interiorMode ?? (architecture.enterable ? "navigable" : "none");+ const interiorEvidence = evidence.parts.filter((part) => part.roles.some((role) => role === "architecture.interior.shell" || role.startsWith("interior.")));+ const valid = mode === "shell" ? interiorEvidence.length > 0 : mode !== "none" || interiorEvidence.length === 0;+ if (valid)+ return [];+ return [+ architectureFinding(context, {+ code: "ARCH_INTERIOR_MODE",+ disposition: "block",+ message: mode === "shell" ? "interiorMode=shell requires a portable architecture.interior.shell semantic volume." : "interiorMode=none conflicts with semantic interior geometry.",+ affected: {+ node: interiorEvidence[0]?.nodeName ?? evidence.root.name ?? "architecture-root",+ nodePath: interiorEvidence[0]?.nodePath+ },+ measurement: {+ name: "semanticInteriorShellCount",+ actual: interiorEvidence.length,+ expected: mode === "shell" ? ">= 1" : 0,+ threshold: mode === "shell" ? 1 : 0+ },+ viewHints: ["architecture.cutaway.dollhouse", "architecture.floor-plan"],+ repairText: mode === "shell" ? "Add one non-rendering architecture.interior.shell volume matching the usable inner envelope; do not fake the interior with a painted exterior face." : "Remove the unrequested interior semantic volume or change trusted intent to shell/navigable before generation."+ })+ ];+}+function roofModeFindings(context, architecture, evidence) {+ const mode = architecture.roofMode ?? (architecture.roof.type === "none" ? "none" : "auto");+ if (mode === "auto")+ return [];+ const roofParts = evidence.parts.filter((part) => hasRolePrefix(part, "roof."));+ const removableRelationships = roofParts.flatMap((part) => part.directRelationships.filter((relationship) => relationship.kind === "separable-from"));+ const present = roofParts.length > 0;+ const valid = mode === "none" ? !present : mode === "fixed" ? present && removableRelationships.length === 0 : present && removableRelationships.length > 0;+ if (valid)+ return [];+ const measurement = mode === "removable" ? {+ name: "removableRoofRelationshipCount",+ actual: removableRelationships.length,+ expected: ">= 1",+ threshold: 1+ } : {+ name: "semanticRoofPartCount",+ actual: roofParts.length,+ expected: mode === "none" ? 0 : ">= 1",+ threshold: mode === "none" ? 0 : 1+ };+ return [+ architectureFinding(context, {+ code: "ARCH_ROOF_MODE",+ disposition: "block",+ message: `roofMode=${mode} conflicts with ${roofParts.length} semantic roof parts and ${removableRelationships.length} separable-from relationships.`,+ affected: {+ node: roofParts[0]?.nodeName ?? evidence.root.name ?? "architecture-root",+ nodePath: roofParts[0]?.nodePath+ },+ measurement,+ viewHints: ["generic.top.semantic-overlay", "architecture.cutaway.dollhouse"],+ repairText: "Match trusted roofMode exactly: omit all roof.* roles for none, keep fixed roofs attached, or stamp one roof assembly with a separable-from relationship for removable."+ })+ ];+}+function domeFindings(context, architecture, evidence) {+ const requested = architecture.roof.type === "dome" || /(?:^|[. _-])rotunda(?:$|[. _-])/i.test(architecture.subtype);+ if (!requested)+ return [];+ const dome = aggregate(evidence.parts.filter((part) => part.isMesh && (hasRole(part, "roof.dome") || hasRole(part, "roof.surface.dome"))));+ const spanXCoverage = dome ? extent(dome.bounds, "x") / architecture.footprint.spanX : 0;+ const spanZCoverage = dome ? extent(dome.bounds, "z") / architecture.footprint.spanZ : 0;+ const riseCoverage = dome ? extent(dome.bounds, "y") / architecture.roof.rise : 0;+ const minimumCoverage = Math.min(spanXCoverage, spanZCoverage, riseCoverage);+ if (minimumCoverage >= 0.9)+ return [];+ return [+ architectureFinding(context, {+ code: "ARCH_DOME_PROFILE",+ disposition: "block",+ message: `The semantic rotunda dome covers ${(spanXCoverage * 100).toFixed(1)}% X, ${(spanZCoverage * 100).toFixed(1)}% Z, and ${(riseCoverage * 100).toFixed(1)}% of declared rise.`,+ affected: {+ node: dome?.parts[0]?.nodeName ?? evidence.root.name ?? "architecture-root",+ nodePath: dome?.parts[0]?.nodePath+ },+ measurement: {+ name: "minimumDomeCoverageRatio",+ actual: minimumCoverage,+ expected: ">= 0.9",+ threshold: 0.9+ },+ viewHints: ["generic.top.semantic-overlay", "architecture.cutaway.dollhouse"],+ repairText: "Rebuild the roof.dome hemisphere to cover the declared circular rotunda footprint and rise; preserve any intentional oculus as a bounded opening rather than shrinking the whole dome."+ })+ ];+}+function scaleBandFinding(context, band) {+ if (band.actual >= band.minimum && band.actual <= band.maximum)+ return;+ return architectureFinding(context, {+ code: band.code,+ disposition: "warn",+ message: `${band.label} is ${band.actual.toFixed(3)} m; the realistic-scale observation band is ${band.minimum.toFixed(3)}–${band.maximum.toFixed(3)} m.`,+ ...band.affected ? { affected: { node: band.affected.nodeName, nodePath: band.affected.nodePath } } : {},+ measurement: {+ name: band.label,+ actual: band.actual,+ expected: `${band.minimum}..${band.maximum}`,+ threshold: band.actual < band.minimum ? band.minimum : band.maximum,+ unit: band.unit+ },+ viewHints: ["architecture.cutaway.dollhouse"],+ repairText: "Adjust only the reported architecture dimension into the realistic band, or explicitly select scaleMode=stylized to retain intentional exaggeration."+ });+}+function scaleFindings(context, architecture, evidence) {+ if (architecture.scaleMode === "stylized")+ return [];+ const scaleBands = ARCHITECTURE_REALISTIC_SCALE_BANDS;+ const bands = [+ {+ code: "ARCH_SCALE_CEILING_HEIGHT",+ label: "ceilingHeight",+ actual: architecture.wallHeight,+ minimum: scaleBands.ceilingHeight.minimum,+ maximum: scaleBands.ceilingHeight.maximum,+ unit: "m"+ },+ {+ code: "ARCH_SCALE_FOOTPRINT_X",+ label: "footprintSpanX",+ actual: architecture.footprint.spanX,+ minimum: scaleBands.footprint.minimum,+ maximum: scaleBands.footprint.maximum,+ unit: "m"+ },+ {+ code: "ARCH_SCALE_FOOTPRINT_Z",+ label: "footprintSpanZ",+ actual: architecture.footprint.spanZ,+ minimum: scaleBands.footprint.minimum,+ maximum: scaleBands.footprint.maximum,+ unit: "m"+ }+ ];+ const portal = evidence.parts.find((part) => !part.isMesh && portalRoleWall(part.directRoles) !== undefined);+ if (portal) {+ const wall = portalRoleWall(portal.directRoles);+ const widthAxis = wall === "front" || wall === "back" ? "z" : "x";+ bands.push({+ code: "ARCH_SCALE_DOOR_WIDTH",+ label: "doorClearWidth",+ actual: extent(portal.bounds, widthAxis),+ minimum: scaleBands.doorWidth.minimum,+ maximum: scaleBands.doorWidth.maximum,+ unit: "m",+ affected: portal+ }, {+ code: "ARCH_SCALE_DOOR_HEIGHT",+ label: "doorClearHeight",+ actual: extent(portal.bounds, "y"),+ minimum: scaleBands.doorHeight.minimum,+ maximum: scaleBands.doorHeight.maximum,+ unit: "m",+ affected: portal+ });+ }+ const wallParts = evidence.parts.filter((part) => part.isMesh && part.roles.some((role) => role.startsWith("wall.")));+ for (const wall of wallParts) {+ const thickness = Math.min(extent(wall.bounds, "x"), extent(wall.bounds, "z"));+ bands.push({+ code: "ARCH_SCALE_WALL_THICKNESS",+ label: "wallThickness",+ actual: thickness,+ minimum: scaleBands.wallThickness.minimum,+ maximum: scaleBands.wallThickness.maximum,+ unit: "m",+ affected: wall+ });+ }+ const steps = evidence.parts.filter((part) => part.isMesh && part.directRoles.some((role) => role.startsWith("stair.step")));+ for (const step of steps) {+ bands.push({+ code: "ARCH_SCALE_STAIR_RISER",+ label: "stairRiser",+ actual: extent(step.bounds, "y"),+ minimum: scaleBands.stairRiser.minimum,+ maximum: scaleBands.stairRiser.maximum,+ unit: "m",+ affected: step+ }, {+ code: "ARCH_SCALE_STAIR_TREAD",+ label: "stairTread",+ actual: Math.min(extent(step.bounds, "x"), extent(step.bounds, "z")),+ minimum: scaleBands.stairTread.minimum,+ maximum: scaleBands.stairTread.maximum,+ unit: "m",+ affected: step+ });+ }+ return bands.flatMap((band) => {+ const finding = scaleBandFinding(context, band);+ return finding ? [finding] : [];+ });+}+function evaluateArchitectureQa(context) {+ const architecture = context.intent.architecture;+ if (!architecture || context.intent.category !== "architecture")+ return [];+ const evidence = collectArchitectureEvidence(context.scene);+ if (!evidence)+ return [];+ return [+ ...storeyFindings(context, architecture, evidence),+ ...interiorModeFindings(context, architecture, evidence),+ ...roofModeFindings(context, architecture, evidence),+ ...domeFindings(context, architecture, evidence),+ ...roofFindings(context, architecture, evidence),+ ...endFindings(context, architecture, evidence),+ ...envelopeFindings(context, architecture, evidence),+ ...portalFindings(context, architecture, evidence),+ ...scaleFindings(context, architecture, evidence)+ ];+}+var PROFILE_RULE_ID = "ARCHITECTURE_PROFILE", EPSILON2 = 0.000001, ARCHITECTURE_REALISTIC_SCALE_BANDS, emptyBounds = () => ({+ min: new THREE17.Vector3(Infinity, Infinity, Infinity),+ max: new THREE17.Vector3(-Infinity, -Infinity, -Infinity)+}), expandBounds = (bounds, point) => {+ bounds.min.min(point);+ bounds.max.max(point);+}, boundsFinite = (bounds) => Number.isFinite(bounds.min.x), extent = (bounds, axis) => bounds.max[axis] - bounds.min[axis], hasRole = (part, role) => part.roles.includes(role), hasRolePrefix = (part, prefix) => part.roles.some((role) => role.startsWith(prefix)), ARCHITECTURE_QA_RULE, ARCHITECTURE_ADVISORY_QA_RULE, ARCHITECTURE_QA_RULES;+var init_architecture2 = __esm(() => {+ init_contracts();+ init_architecture_repairs();+ init_registry();+ ARCHITECTURE_REALISTIC_SCALE_BANDS = Object.freeze({+ doorWidth: Object.freeze({ minimum: 0.75, maximum: 2.5, unit: "m" }),+ doorHeight: Object.freeze({ minimum: 1.8, maximum: 3.2, unit: "m" }),+ ceilingHeight: Object.freeze({ minimum: 2.1, maximum: 6, unit: "m" }),+ stairRiser: Object.freeze({ minimum: 0.1, maximum: 0.25, unit: "m" }),+ stairTread: Object.freeze({ minimum: 0.2, maximum: 0.45, unit: "m" }),+ wallThickness: Object.freeze({ minimum: 0.05, maximum: 0.6, unit: "m" }),+ footprint: Object.freeze({ minimum: 1.5, maximum: 200, unit: "m" })+ });+ ARCHITECTURE_QA_RULE = {+ id: PROFILE_RULE_ID,+ profile: "architecture.default",+ scope: { kind: "category", category: "architecture" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("architecture-qa-v1", "src/qa/architecture.test.ts", "e5ad1245240f1244c592849df2977c74d26e535dffebc9ad5a2adf6db743d573"),+ defaultMode: "enforce",+ evaluate: (context) => evaluateArchitectureQa(context).filter((finding) => finding.disposition === "block")+ };+ ARCHITECTURE_ADVISORY_QA_RULE = {+ id: "ARCHITECTURE_ADVISORY_PROFILE",+ profile: "architecture.advisory",+ scope: { kind: "category", category: "architecture" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: (context) => evaluateArchitectureQa(context).filter((finding) => finding.disposition !== "block")+ };+ ARCHITECTURE_QA_RULES = [+ ARCHITECTURE_QA_RULE,+ ARCHITECTURE_ADVISORY_QA_RULE+ ];+});++// src/qa/character-repairs.ts+function characterRepairRecipe(code) {+ return CHARACTER_REPAIR_RECIPES[code];+}+function withCharacterRepair(finding) {+ const found = characterRepairRecipe(finding.code);+ if (!found)+ return finding;+ return {+ ...finding,+ repairText: finding.repairText ?? found.repairText,+ viewHints: [...new Set([...finding.viewHints ?? [], ...found.viewHints])]+ };+}+var skeletonViews, motionViews, recipe = (code, repairText, viewHints) => Object.freeze({ code, repairText, viewHints: Object.freeze([...viewHints]) }), CHARACTER_REPAIR_RECIPES;+var init_character_repairs = __esm(() => {+ skeletonViews = Object.freeze(["character.skeleton.front", "character.skeleton.right"]);+ motionViews = Object.freeze(["character.motion-strip.front", "character.motion-strip.right"]);+ CHARACTER_REPAIR_RECIPES = Object.freeze({+ CHAR_DUPLICATE_ANIMATED_NODE_NAME: recipe("CHAR_DUPLICATE_ANIMATED_NODE_NAME", "Rename only the reported duplicate Joint_* pivot and update its animation-track target so every animated node name is unique.", skeletonViews),+ CHAR_DUPLICATE_JOINT_ROLE: recipe("CHAR_DUPLICATE_JOINT_ROLE", "Give the reported joint its intended unique semantic role; do not remove or merge unrelated branches.", skeletonViews),+ CHAR_PARENT_EDGE: recipe("CHAR_PARENT_EDGE", "Reparent only the reported joint directly under its declared parent role while preserving its asset-local rest pose.", skeletonViews),+ CHAR_BIPED_REQUIRED_ROLE: recipe("CHAR_BIPED_REQUIRED_ROLE", "Add the reported missing biped joint role and declared parent edge without redesigning already-valid chains.", skeletonViews),+ CHAR_QUADRUPED_REQUIRED_ROLE: recipe("CHAR_QUADRUPED_REQUIRED_ROLE", "Add the reported missing quadruped joint role and declared parent edge without changing the other three limb chains.", skeletonViews),+ CHAR_CUSTOM_GRAPH_MISSING: recipe("CHAR_CUSTOM_GRAPH_MISSING", "Declare the requested custom rig graph before authoring animation; do not substitute biped assumptions.", skeletonViews),+ CHAR_CUSTOM_REQUIRED_ROLE: recipe("CHAR_CUSTOM_REQUIRED_ROLE", "Add only the reported role from the trusted custom graph and attach it to its declared parent.", skeletonViews),+ CHAR_HELD_ITEM_MISSING: recipe("CHAR_HELD_ITEM_MISSING", "Add the declared held item as its own node under the requested grip end effector.", skeletonViews),+ CHAR_HELD_ITEM_ATTACHMENT: recipe("CHAR_HELD_ITEM_ATTACHMENT", "Reparent only the held-item node under the reported hand, wrist, or grip end effector; never attach it to a shoulder or elbow.", skeletonViews),+ CHAR_HELD_ITEM_GRIP_BREAK: recipe("CHAR_HELD_ITEM_GRIP_BREAK", "Keep the reported held item under its declared grip end effector and remove only the item-local animation keys that change its grip distance.", motionViews),+ CHAR_CONTACT_MISSING: recipe("CHAR_CONTACT_MISSING", "Tag the requested foot, paw, or terminal support as a ground contact without changing body plan.", ["character.skeleton.front", "generic.front.depth-contact"]),+ CHAR_CONTACT_FLOATING: recipe("CHAR_CONTACT_FLOATING", "Move only the reported contact down to asset-local Y=0 while preserving its parent chain and lateral placement.", ["character.skeleton.front", "generic.front.depth-contact"]),+ CHAR_CONTACT_BURIED: recipe("CHAR_CONTACT_BURIED", "Move only the reported contact up to asset-local Y=0 while preserving its parent chain and lateral placement.", ["character.skeleton.front", "generic.front.depth-contact"]),+ CHAR_CLIP_MISSING: recipe("CHAR_CLIP_MISSING", "Author exactly the reported requested clip name using existing unique Joint_* targets.", motionViews),+ CHAR_CLIP_DUPLICATE: recipe("CHAR_CLIP_DUPLICATE", "Keep one clip with the requested name and remove or correctly rename the duplicate; preserve requested clip names exactly.", motionViews),+ CHAR_CLIP_UNEXPECTED: recipe("CHAR_CLIP_UNEXPECTED", "Remove the unrequested clip without changing any requested clip.", motionViews),+ CHAR_CLIP_DURATION: recipe("CHAR_CLIP_DURATION", "Set the reported clip to one finite positive duration and keep all keys inside it.", motionViews),+ CHAR_ANIMATION_NONFINITE: recipe("CHAR_ANIMATION_NONFINITE", "Replace only the reported non-finite key time or value with the intended finite value.", motionViews),+ CHAR_KEY_TIME_ORDER: recipe("CHAR_KEY_TIME_ORDER", "Sort the reported track keys into strictly increasing unique times without changing their poses.", motionViews),+ CHAR_KEY_OUT_OF_RANGE: recipe("CHAR_KEY_OUT_OF_RANGE", "Move only the reported key inside the inclusive [0, clip duration] interval.", motionViews),+ CHAR_TRACK_VALUE_COUNT: recipe("CHAR_TRACK_VALUE_COUNT", "Provide exactly one complete value tuple for every reported key time.", motionViews),+ CHAR_LOOP_ENDPOINT: recipe("CHAR_LOOP_ENDPOINT", "For the declared looping clip, make the reported track end pose equal its start pose; do not change one-shot clips.", motionViews),+ CHAR_ROOT_MOTION_BACKWARD: recipe("CHAR_ROOT_MOTION_BACKWARD", "Reverse only the declared locomotion root translation so net travel is toward canonical +X.", motionViews),+ CHAR_ROOT_MOTION_LATERAL: recipe("CHAR_ROOT_MOTION_LATERAL", "Rotate or rewrite only the declared locomotion root translation so +X travel dominates Z travel.", motionViews)+ });+});++// src/qa/character.ts+import * as THREE18 from "three";+function isClipLike(value) {+ if (typeof value !== "object" || value === null)+ return false;+ const clip = value;+ return typeof clip.name === "string" && Array.isArray(clip.tracks);+}+function collectNodes(root) {+ const nodes = [];+ const visit = (node, parentPath, siblingIndex) => {+ const segment = `${node.name.trim() || node.type || "Object3D"}[${siblingIndex}]`;+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ nodes.push({ node, nodePath });+ node.children.forEach((child, index) => {+ visit(child, nodePath, index);+ });+ };+ visit(root, "", 0);+ return nodes;+}+function characterIntent(intent) {+ return intent.character;+}+function block(intent, code, message, options) {+ return withCharacterRepair({+ code,+ disposition: "block",+ profile: intent.qaProfile,+ message,+ ...options+ });+}+function targetName(trackName) {+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(0, dot) : undefined;+}+function propertyName(trackName) {+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(dot + 1) : undefined;+}+function blockerKey(finding) {+ return [+ finding.code,+ finding.affected?.nodePath ?? "",+ finding.affected?.clip ?? "",+ finding.affected?.track ?? "",+ String(finding.measurement?.expected ?? "")+ ].join("|");+}+function dedupeFindings(findings) {+ const byKey = new Map;+ for (const finding of findings)+ byKey.set(blockerKey(finding), finding);+ return [...byKey.values()].sort((a, b) => blockerKey(a).localeCompare(blockerKey(b)));+}+function duplicateNameFindings(intent, nodes, clips) {+ const animatedTargets = new Set(clips.flatMap((clip) => clip.tracks.map((track) => targetName(track.name)).filter(Boolean)));+ const byName = new Map;+ for (const evidence of nodes) {+ if (!evidence.node.name)+ continue;+ if (!evidence.node.name.startsWith("Joint_") && !animatedTargets.has(evidence.node.name))+ continue;+ const values = byName.get(evidence.node.name) ?? [];+ values.push(evidence);+ byName.set(evidence.node.name, values);+ }+ const findings = [];+ for (const [name, matches] of [...byName.entries()].sort(([a], [b]) => a.localeCompare(b))) {+ if (matches.length < 2)+ continue;+ const paths = matches.map((match) => match.nodePath).sort();+ findings.push(block(intent, "CHAR_DUPLICATE_ANIMATED_NODE_NAME", `Animated node name ${JSON.stringify(name)} resolves to multiple exact paths: ${paths.join(", ")}.`, {+ dimension: "exportIntegrity",+ affected: { node: name, nodePath: paths[0] },+ measurement: {+ name: "animatedNodeNameCount",+ actual: matches.length,+ expected: 1+ },+ viewHints: ["character.skeleton.front", "character.skeleton.right"]+ }));+ }+ return findings;+}+function parentAndRoleFindings(intent, root) {+ const joints = collectCharacterJointNodes(root);+ const byRole = new Map;+ for (const joint of joints) {+ const values = byRole.get(joint.descriptor.role) ?? [];+ values.push(joint);+ byRole.set(joint.descriptor.role, values);+ }+ const findings = [];+ for (const [role, matches] of [...byRole.entries()].sort(([a], [b]) => a.localeCompare(b))) {+ if (matches.length < 2)+ continue;+ const paths = matches.map((match) => match.nodePath).sort();+ findings.push(block(intent, "CHAR_DUPLICATE_JOINT_ROLE", `Joint role ${role} is declared at ${paths.join(", ")}.`, {+ dimension: "categoryReadiness",+ affected: { node: role, nodePath: paths[0] },+ measurement: { name: "jointRoleCount", actual: matches.length, expected: 1 },+ viewHints: ["character.skeleton.front", "character.skeleton.right"]+ }));+ }+ for (const joint of joints) {+ const expected = joint.descriptor.parentRole;+ if (!expected)+ continue;+ const actualDescriptor = joint.node.parent ? readCharacterJointDescriptorV1(joint.node.parent) : undefined;+ const actual = actualDescriptor?.role ?? joint.node.parent?.name ?? "(none)";+ if (actualDescriptor?.role === expected)+ continue;+ findings.push(block(intent, "CHAR_PARENT_EDGE", `Broken joint edge ${expected} -> ${joint.descriptor.role}: actual direct parent is ${actual}.`, {+ dimension: "categoryReadiness",+ affected: { node: joint.node.name, nodePath: joint.nodePath },+ measurement: { name: "parentRole", actual, expected },+ viewHints: ["character.skeleton.front", "character.skeleton.right"]+ }));+ }+ return { findings, byRole };+}+function requiredGraphFindings(intent, graph, actualByRole, code) {+ const findings = [];+ for (const expected of graph.joints) {+ const actual = actualByRole.get(expected.role)?.[0];+ if (!actual) {+ findings.push(block(intent, code, `Explicit ${graph.bodyPlan} articulation is missing joint role ${expected.role}.`, {+ dimension: "categoryReadiness",+ affected: { node: expected.role },+ measurement: { name: "requiredJointRole", actual: false, expected: expected.role },+ viewHints: ["character.skeleton.front", "character.skeleton.right"]+ }));+ continue;+ }+ if (expected.parentRole && actual.descriptor.parentRole !== expected.parentRole) {+ findings.push(block(intent, "CHAR_PARENT_EDGE", `Role ${expected.role} declares parent ${actual.descriptor.parentRole ?? "(none)"}; ${expected.parentRole} is required by the ${graph.bodyPlan} graph.`, {+ dimension: "categoryReadiness",+ affected: { node: actual.node.name, nodePath: actual.nodePath },+ measurement: {+ name: "declaredParentRole",+ actual: actual.descriptor.parentRole ?? "(none)",+ expected: expected.parentRole+ },+ viewHints: ["character.skeleton.front", "character.skeleton.right"]+ }));+ }+ }+ return findings;+}+function rigProfileFindings(intent, root, byRole) {+ const trusted = characterIntent(intent);+ if (!trusted || !intent.capabilities.includes("articulated"))+ return [];+ if (trusted.bodyPlan === "biped") {+ return requiredGraphFindings(intent, BIPED_RIG_PRESET_V1, byRole, "CHAR_BIPED_REQUIRED_ROLE");+ }+ if (trusted.bodyPlan === "quadruped") {+ return requiredGraphFindings(intent, QUADRUPED_RIG_PRESET_V1, byRole, "CHAR_QUADRUPED_REQUIRED_ROLE");+ }+ const customGraph = trusted.rigGraph ?? readCharacterRigGraphV1(root);+ if (!customGraph) {+ return [+ block(intent, "CHAR_CUSTOM_GRAPH_MISSING", `Explicit articulated ${trusted.bodyPlan} character requires its declared semantic rig graph; no biped fallback is allowed.`, {+ dimension: "categoryReadiness",+ affected: { node: root.name },+ measurement: { name: "customRigGraphPresent", actual: false, expected: true },+ viewHints: ["character.skeleton.front", "character.skeleton.right"]+ })+ ];+ }+ return requiredGraphFindings(intent, customGraph, byRole, "CHAR_CUSTOM_REQUIRED_ROLE");+}+function heldItemFindings(intent, nodes) {+ const held = characterIntent(intent)?.heldItem;+ if (!held?.required)+ return [];+ const item = nodes.find((evidence) => {+ const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];+ return evidence.node.userData["kilnHeldItem"] === true || roles.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");+ });+ if (!item) {+ return [+ block(intent, "CHAR_HELD_ITEM_MISSING", "Trusted intent requires a held item, but none is declared.", {+ dimension: "categoryReadiness",+ affected: { node: held.attachmentRole },+ measurement: { name: "heldItemPresent", actual: false, expected: true },+ viewHints: ["character.skeleton.front", "character.skeleton.right"]+ })+ ];+ }+ let cursor = item.node.parent;+ let attachment;+ while (cursor) {+ attachment = readCharacterJointDescriptorV1(cursor);+ if (attachment)+ break;+ cursor = cursor.parent;+ }+ const roleMatches = (descriptor) => {+ const candidates = [descriptor.role, ...descriptor.aliases];+ return candidates.some((role) => role === held.attachmentRole || role.split(/[._-]/).includes(held.attachmentRole));+ };+ if (attachment?.endEffector && roleMatches(attachment))+ return [];+ return [+ block(intent, "CHAR_HELD_ITEM_ATTACHMENT", `Held item at ${item.nodePath} must be under ${held.attachmentRole} end effector; actual attachment is ${attachment?.role ?? "(non-joint)"}.`, {+ dimension: "categoryReadiness",+ affected: { node: item.node.name, nodePath: item.nodePath },+ measurement: {+ name: "heldItemAttachmentRole",+ actual: attachment?.role ?? "(non-joint)",+ expected: held.attachmentRole+ },+ viewHints: ["character.skeleton.front", "character.skeleton.right"]+ })+ ];+}+function contactFindings(intent, root) {+ const trusted = characterIntent(intent);+ if (!trusted?.grounded)+ return [];+ const contacts = collectCharacterJointNodes(root).filter((joint) => joint.descriptor.contact);+ if (contacts.length === 0) {+ return [+ block(intent, "CHAR_CONTACT_MISSING", "Grounded character declares no contact joint.", {+ dimension: "categoryReadiness",+ affected: { node: root.name },+ measurement: { name: "groundContactCount", actual: 0, expected: ">=1" },+ viewHints: ["character.skeleton.front", "generic.front.depth-contact"]+ })+ ];+ }+ root.updateMatrixWorld(true);+ const rootInverse = root.matrixWorld.clone().invert();+ const tolerance = Number.isFinite(trusted.contactTolerance) && (trusted.contactTolerance ?? 0) >= 0 ? trusted.contactTolerance : CONTACT_TOLERANCE;+ const findings = [];+ for (const contact of contacts) {+ const point = contact.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(rootInverse);+ if (point.y > tolerance) {+ findings.push(block(intent, "CHAR_CONTACT_FLOATING", `Ground contact ${contact.descriptor.role} is ${point.y.toFixed(6)} m above asset-local ground.`, {+ dimension: "categoryReadiness",+ affected: { node: contact.node.name, nodePath: contact.nodePath },+ measurement: {+ name: "contactY",+ actual: point.y,+ expected: 0,+ threshold: tolerance,+ unit: "m"+ },+ viewHints: ["character.skeleton.front", "generic.front.depth-contact"]+ }));+ } else if (point.y < -tolerance) {+ findings.push(block(intent, "CHAR_CONTACT_BURIED", `Ground contact ${contact.descriptor.role} is ${Math.abs(point.y).toFixed(6)} m below asset-local ground.`, {+ dimension: "categoryReadiness",+ affected: { node: contact.node.name, nodePath: contact.nodePath },+ measurement: {+ name: "contactY",+ actual: point.y,+ expected: 0,+ threshold: tolerance,+ unit: "m"+ },+ viewHints: ["character.skeleton.front", "generic.front.depth-contact"]+ }));+ }+ }+ return findings;+}+function requestedClipFindings(intent, clips, requested) {+ const findings = [];+ const requestedNames = new Set(requested.map((clip) => clip.name));+ const counts = new Map;+ for (const clip of clips)+ counts.set(clip.name, (counts.get(clip.name) ?? 0) + 1);+ for (const [name, count] of [...counts.entries()].sort(([a], [b]) => a.localeCompare(b))) {+ if (count < 2)+ continue;+ findings.push(block(intent, "CHAR_CLIP_DUPLICATE", `Clip ${name} appears ${count} times.`, {+ dimension: "exportIntegrity",+ affected: { clip: name },+ measurement: { name: "clipCount", actual: count, expected: 1 },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ for (const request of requested) {+ const count = counts.get(request.name) ?? 0;+ if (count === 0) {+ findings.push(block(intent, "CHAR_CLIP_MISSING", `Requested clip ${request.name} is missing.`, {+ dimension: "categoryReadiness",+ affected: { clip: request.name },+ measurement: { name: "clipCount", actual: 0, expected: 1 },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ }+ for (const name of [...counts.keys()].sort()) {+ if (requestedNames.has(name))+ continue;+ findings.push(block(intent, "CHAR_CLIP_UNEXPECTED", `Clip ${name} was not requested by trusted intent.`, {+ dimension: "categoryReadiness",+ affected: { clip: name },+ measurement: { name: "requestedClip", actual: name, expected: "absent" },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ return findings;+}+function valueSize(track) {+ const explicit = track.getValueSize?.();+ if (typeof explicit === "number" && Number.isInteger(explicit) && explicit > 0)+ return explicit;+ if (track.times.length > 0 && track.values.length % track.times.length === 0) {+ return track.values.length / track.times.length;+ }+ return;+}+function endpointDelta(track, size) {+ const first = Array.from({ length: size }, (_, index) => Number(track.values[index]));+ const lastOffset = track.values.length - size;+ const last = Array.from({ length: size }, (_, index) => Number(track.values[lastOffset + index]));+ if (track.name.endsWith(".quaternion") && size === 4) {+ const dot = Math.abs(first.reduce((sum, value, index) => sum + value * last[index], 0));+ return Math.abs(1 - Math.min(1, dot));+ }+ return Math.max(...first.map((value, index) => Math.abs(value - last[index])));+}+function animationDataFindings(intent, clips, requested, root) {+ const findings = [];+ const playback = new Map(requested.map((clip) => [clip.name, clip.playback]));+ const trusted = characterIntent(intent);+ const hipsName = root ? collectCharacterJointNodes(root).find((joint) => joint.descriptor.role === "hips")?.node.name : undefined;+ const rootMotionNames = new Set([trusted?.rootMotionNode, root?.name, hipsName].filter((name) => Boolean(name)));+ for (const clip of clips) {+ const durationValid = Number.isFinite(clip.duration) && clip.duration > 0;+ if (!durationValid) {+ findings.push(block(intent, "CHAR_CLIP_DURATION", `Clip ${clip.name} duration must be finite and positive.`, {+ dimension: "exportIntegrity",+ affected: { clip: clip.name },+ measurement: { name: "clipDuration", actual: clip.duration, expected: ">0", unit: "s" },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ for (const track of clip.tracks) {+ const times = Array.from(track.times, Number);+ const values = Array.from(track.values, Number);+ const nonFiniteTime = times.findIndex((value) => !Number.isFinite(value));+ const nonFiniteValue = values.findIndex((value) => !Number.isFinite(value));+ if (nonFiniteTime >= 0 || nonFiniteValue >= 0) {+ findings.push(block(intent, "CHAR_ANIMATION_NONFINITE", `Clip ${clip.name} track ${track.name} contains a non-finite ${nonFiniteTime >= 0 ? "time" : "value"}.`, {+ dimension: "exportIntegrity",+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: nonFiniteTime >= 0 ? "nonFiniteTimeIndex" : "nonFiniteValueIndex",+ actual: nonFiniteTime >= 0 ? nonFiniteTime : nonFiniteValue,+ expected: "none"+ },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ const badOrder = times.findIndex((time, index) => index > 0 && time <= times[index - 1]);+ if (badOrder >= 0) {+ findings.push(block(intent, "CHAR_KEY_TIME_ORDER", `Clip ${clip.name} track ${track.name} key times must be strictly increasing and unique.`, {+ dimension: "exportIntegrity",+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: "firstNonIncreasingKey",+ actual: badOrder,+ expected: "strictly increasing"+ },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ if (durationValid) {+ const outside = times.findIndex((time) => Number.isFinite(time) && (time < 0 || time > clip.duration));+ if (outside >= 0) {+ findings.push(block(intent, "CHAR_KEY_OUT_OF_RANGE", `Clip ${clip.name} track ${track.name} key ${outside} lies outside [0, ${clip.duration}].`, {+ dimension: "exportIntegrity",+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: "keyTime",+ actual: times[outside],+ expected: `0..${clip.duration}`,+ unit: "s"+ },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ }+ const size = valueSize(track);+ if (!size || values.length !== times.length * size) {+ findings.push(block(intent, "CHAR_TRACK_VALUE_COUNT", `Clip ${clip.name} track ${track.name} does not contain one complete value per key time.`, {+ dimension: "exportIntegrity",+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: "trackValueCount",+ actual: values.length,+ expected: size ? times.length * size : "integral tuple count"+ },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ } else if (playback.get(clip.name) === "loop" && !(trusted?.rootMotion === "forward" && track.name.endsWith(".position") && rootMotionNames.has(targetName(track.name) ?? "")) && times.length > 1 && nonFiniteValue < 0 && endpointDelta(track, size) > LOOP_TOLERANCE) {+ const delta = endpointDelta(track, size);+ findings.push(block(intent, "CHAR_LOOP_ENDPOINT", `Looping clip ${clip.name} track ${track.name} ends ${delta} away from its start pose.`, {+ dimension: "categoryReadiness",+ affected: { clip: clip.name, track: track.name },+ measurement: {+ name: "loopEndpointDelta",+ actual: delta,+ expected: 0,+ threshold: LOOP_TOLERANCE+ },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ }+ }+ return findings;+}+function applyTrackAt(root, track, time) {+ const nodeName = targetName(track.name);+ const property = propertyName(track.name);+ const node = nodeName ? root.getObjectByName(nodeName) : undefined;+ if (!node || !property || !track.createInterpolant)+ return;+ const value = track.createInterpolant().evaluate(time);+ if (property === "position")+ node.position.fromArray(value);+ else if (property === "scale")+ node.scale.fromArray(value);+ else if (property === "quaternion") {+ node.quaternion.fromArray(value).normalize();+ }+}+function locomotionClipNames(character) {+ const loopingMotion = character.clips.filter((clip) => clip.playback === "loop" && /(?:walk|run|fly|swim|slither|roll|locom)/i.test(clip.name)).map((clip) => clip.name);+ if (loopingMotion.length > 0)+ return loopingMotion;+ return character.clips.filter((clip) => clip.playback === "loop").map((clip) => clip.name);+}+function rootMotionFindings(intent, root, clips) {+ const trusted = characterIntent(intent);+ if (trusted?.rootMotion !== "forward")+ return [];+ const names = new Set(locomotionClipNames(trusted));+ const findings = [];+ const hips = collectCharacterJointNodes(root).find((joint) => joint.descriptor.role === "hips");+ for (const clip of clips.filter((candidate) => names.has(candidate.name))) {+ const positionTracks = clip.tracks.filter((track) => track.name.endsWith(".position"));+ const preferredName = trusted.rootMotionNode ?? root.name;+ const rootTrack = positionTracks.find((track) => targetName(track.name) === preferredName) ?? positionTracks.find((track) => targetName(track.name) === hips?.node.name) ?? positionTracks[0];+ if (!rootTrack || rootTrack.times.length === 0 || !rootTrack.createInterpolant)+ continue;+ const interpolant = rootTrack.createInterpolant();+ const first = Array.from(interpolant.evaluate(0), Number);+ const last = Array.from(interpolant.evaluate(clip.duration), Number);+ const dx = Number(last[0]) - Number(first[0]);+ const dz = Number(last[2]) - Number(first[2]);+ if (!Number.isFinite(dx) || !Number.isFinite(dz))+ continue;+ if (dx < -ROOT_MOTION_TOLERANCE) {+ findings.push(block(intent, "CHAR_ROOT_MOTION_BACKWARD", `Forward locomotion clip ${clip.name} travels ${dx.toFixed(6)} m along X.`, {+ dimension: "categoryReadiness",+ affected: { clip: clip.name, track: rootTrack.name },+ measurement: {+ name: "rootMotionDeltaX",+ actual: dx,+ expected: ">=0",+ threshold: ROOT_MOTION_TOLERANCE,+ unit: "m"+ },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ if (Math.abs(dz) > ROOT_MOTION_TOLERANCE && Math.abs(dz) > Math.max(Math.abs(dx) * 1.25, ROOT_MOTION_TOLERANCE)) {+ findings.push(block(intent, "CHAR_ROOT_MOTION_LATERAL", `Forward locomotion clip ${clip.name} is Z-dominant (dx=${dx.toFixed(6)}, dz=${dz.toFixed(6)}).`, {+ dimension: "categoryReadiness",+ affected: { clip: clip.name, track: rootTrack.name },+ measurement: {+ name: "rootMotionLateralToForward",+ actual: Math.abs(dz) / Math.max(Math.abs(dx), ROOT_MOTION_TOLERANCE),+ expected: "<=1.25",+ threshold: 1.25+ },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ }+ return findings;+}+function declaredHeldItem(nodes) {+ return nodes.find((evidence) => {+ const roles = readSemanticMetadataV1(evidence.node)?.roles ?? [];+ return evidence.node.userData["kilnHeldItem"] === true || roles.some((role) => role === "held-item" || role.startsWith("held-item.") || role === "character.held-item");+ });+}+function characterJointScale(root) {+ root.updateMatrixWorld(true);+ const inverse = root.matrixWorld.clone().invert();+ const bounds = new THREE18.Box3;+ for (const joint of collectCharacterJointNodes(root)) {+ bounds.expandByPoint(joint.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse));+ }+ if (bounds.isEmpty())+ return 1;+ const size = bounds.getSize(new THREE18.Vector3);+ return Math.max(size.x, size.y, size.z, 1);+}+function heldItemMotionFindings(intent, root, clips) {+ const held = characterIntent(intent)?.heldItem;+ if (!held?.required || clips.length === 0)+ return [];+ const item = declaredHeldItem(collectNodes(root));+ if (!item)+ return [];+ let attachmentNode = item.node.parent;+ let attachment = attachmentNode ? readCharacterJointDescriptorV1(attachmentNode) : undefined;+ while (attachmentNode && !attachment) {+ attachmentNode = attachmentNode.parent;+ attachment = attachmentNode ? readCharacterJointDescriptorV1(attachmentNode) : undefined;+ }+ if (!attachmentNode || !attachment?.endEffector)+ return [];+ const tolerance = Math.max(0.01, characterJointScale(root) * GRIP_MOTION_RATIO);+ const findings = [];+ for (const clip of clips) {+ if (!Number.isFinite(clip.duration) || clip.duration <= 0)+ continue;+ let baseline;+ let maximumDrift = 0;+ let maximumFraction = 0;+ for (const fraction of CHARACTER_SAMPLE_FRACTIONS) {+ const clone = root.clone(true);+ for (const track of clip.tracks)+ applyTrackAt(clone, track, fraction * clip.duration);+ clone.updateMatrixWorld(true);+ const cloneItem = clone.getObjectByName(item.node.name);+ const cloneAttachment = collectCharacterJointNodes(clone).find((joint) => joint.descriptor.role === attachment.role)?.node;+ if (!cloneItem || !cloneAttachment)+ continue;+ const inverse = clone.matrixWorld.clone().invert();+ const itemPoint = cloneItem.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);+ const gripPoint = cloneAttachment.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);+ const distance = itemPoint.distanceTo(gripPoint);+ baseline ??= distance;+ const drift = Math.abs(distance - baseline);+ if (drift > maximumDrift) {+ maximumDrift = drift;+ maximumFraction = fraction;+ }+ }+ if (maximumDrift <= tolerance)+ continue;+ findings.push(block(intent, "CHAR_HELD_ITEM_GRIP_BREAK", `Held item ${item.node.name} breaks its declared ${attachment.role} grip relationship in ${clip.name} at phase ${maximumFraction}.`, {+ dimension: "categoryReadiness",+ affected: {+ node: item.node.name,+ nodePath: item.nodePath,+ clip: clip.name+ },+ measurement: {+ name: "heldItemGripDistanceDrift",+ actual: maximumDrift,+ expected: 0,+ threshold: tolerance,+ unit: "m"+ },+ viewHints: ["character.motion-strip.front", "character.motion-strip.right"]+ }));+ }+ return findings;+}+function evaluateCharacterQa(context) {+ if (context.intent.category !== "character")+ return [];+ const root = context.scene instanceof THREE18.Object3D ? context.scene : undefined;+ const clips = (context.clips ?? []).filter(isClipLike);+ const findings = [];+ if (root) {+ const nodes = collectNodes(root);+ findings.push(...duplicateNameFindings(context.intent, nodes, clips));+ const rig = parentAndRoleFindings(context.intent, root);+ findings.push(...rig.findings);+ findings.push(...rigProfileFindings(context.intent, root, rig.byRole));+ findings.push(...heldItemFindings(context.intent, nodes));+ findings.push(...contactFindings(context.intent, root));+ findings.push(...rootMotionFindings(context.intent, root, clips));+ findings.push(...heldItemMotionFindings(context.intent, root, clips));+ }+ const requested = characterIntent(context.intent)?.clips ?? [];+ findings.push(...requestedClipFindings(context.intent, clips, requested));+ findings.push(...animationDataFindings(context.intent, clips, requested, root));+ return dedupeFindings(findings);+}+var PROFILE_RULE_ID2 = "CHARACTER_PROFILE", CONTACT_TOLERANCE = 0.02, LOOP_TOLERANCE = 0.00001, ROOT_MOTION_TOLERANCE = 0.01, GRIP_MOTION_RATIO = 0.02, CHARACTER_SAMPLE_FRACTIONS, CHARACTER_QA_RULE;+var init_character2 = __esm(() => {+ init_character();+ init_contracts();+ init_character_repairs();+ init_registry();+ CHARACTER_SAMPLE_FRACTIONS = Object.freeze([0, 0.25, 0.5, 0.75, 1]);+ CHARACTER_QA_RULE = Object.freeze({+ id: PROFILE_RULE_ID2,+ profile: "character",+ scope: { kind: "category", category: "character" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("character-qa-v1", "src/qa/character.test.ts", "53086f1350c61cb8ddd32a5a4a97d23256e5dbde2e5b9765e47a3c76045bd6ed"),+ defaultMode: "enforce",+ evaluate: evaluateCharacterQa+ });+});++// src/qa/character-advisory.ts+import * as THREE19 from "three";+function isClipLike2(value) {+ if (typeof value !== "object" || value === null)+ return false;+ const candidate = value;+ return typeof candidate.name === "string" && typeof candidate.duration === "number" && Array.isArray(candidate.tracks);+}+function characterIntent2(intent) {+ return intent.character;+}+function advisory(context, value) {+ return {+ ...value,+ disposition: "warn",+ dimension: "categoryReadiness",+ profile: context.intent.qaProfile+ };+}+function rootInverse(root) {+ root.updateMatrixWorld(true);+ return root.matrixWorld.clone().invert();+}+function jointPoints(root) {+ const inverse = rootInverse(root);+ return collectCharacterJointNodes(root).map((evidence) => ({+ evidence,+ local: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse)+ }));+}+function characterScale(points) {+ if (points.length === 0)+ return 1;+ const bounds = new THREE19.Box3;+ for (const point of points)+ bounds.expandByPoint(point.local);+ const size = bounds.getSize(new THREE19.Vector3);+ return Math.max(size.x, size.y, size.z, 1);+}+function pairKey(descriptor) {+ return descriptor.role.split(/[._-]/).filter((token) => token !== "left" && token !== "right").join(".");+}+function bilateralSymmetryFindings(context, root) {+ const points = jointPoints(root);+ const scale = characterScale(points);+ const threshold = Math.max(0.02, scale * REST_SYMMETRY_RATIO);+ const left = new Map(points.filter((point) => point.evidence.descriptor.side === "left").map((point) => [pairKey(point.evidence.descriptor), point]));+ const right = new Map(points.filter((point) => point.evidence.descriptor.side === "right").map((point) => [pairKey(point.evidence.descriptor), point]));+ const findings = [];+ for (const key of [...new Set([...left.keys(), ...right.keys()])].sort()) {+ const a = left.get(key);+ const b = right.get(key);+ if (!a || !b)+ continue;+ const mirrorDelta = Math.hypot(a.local.x - b.local.x, a.local.y - b.local.y, a.local.z + b.local.z);+ const sideSwapped = a.local.z > b.local.z;+ if (!sideSwapped && mirrorDelta <= threshold)+ continue;+ findings.push(advisory(context, {+ code: "CHAR_REST_BILATERAL_SYMMETRY",+ message: `Bilateral rest pair ${a.evidence.descriptor.role} / ${b.evidence.descriptor.role} ` + `${sideSwapped ? "appears left/right swapped" : "is grossly asymmetric"} ` + `(mirror delta ${mirrorDelta.toFixed(6)} m).`,+ affected: {+ node: b.evidence.node.name,+ nodePath: b.evidence.nodePath+ },+ measurement: {+ name: "bilateralMirrorDelta",+ actual: mirrorDelta,+ expected: 0,+ threshold,+ unit: "m"+ },+ viewHints: [...SKELETON_VIEWS]+ }));+ }+ return findings;+}+function restChainFindings(context, root) {+ const trusted = characterIntent2(context.intent);+ if (trusted?.bodyPlan !== "biped" && trusted?.bodyPlan !== "quadruped")+ return [];+ const points = jointPoints(root);+ const byRole = new Map(points.map((point) => [point.evidence.descriptor.role, point]));+ const scale = characterScale(points);+ const minimumSegment = Math.max(0.01, scale * REST_ORDER_RATIO);+ const chains = trusted.bodyPlan === "biped" ? BIPED_CHAINS : QUADRUPED_CHAINS;+ const findings = [];+ for (const roles of chains) {+ const chain = roles.map((role) => byRole.get(role)).filter((value) => !!value);+ if (chain.length !== roles.length)+ continue;+ for (let index = 1;index < chain.length; index++) {+ const parent = chain[index - 1];+ const child = chain[index];+ const verticalDrop = parent.local.y - child.local.y;+ if (verticalDrop >= minimumSegment)+ continue;+ findings.push(advisory(context, {+ code: "CHAR_REST_CHAIN_ORDER",+ message: `Rest chain ${roles.join(" -> ")} is vertically inverted or collapsed at ` + `${parent.evidence.descriptor.role} -> ${child.evidence.descriptor.role}.`,+ affected: { node: child.evidence.node.name, nodePath: child.evidence.nodePath },+ measurement: {+ name: "parentToChildVerticalDrop",+ actual: verticalDrop,+ expected: `>=${minimumSegment}`,+ threshold: minimumSegment,+ unit: "m"+ },+ viewHints: [...SKELETON_VIEWS]+ }));+ }+ const lengths = [+ chain[0].local.distanceTo(chain[1].local),+ chain[1].local.distanceTo(chain[2].local)+ ];+ const ratio = Math.max(...lengths) / Math.max(Math.min(...lengths), 0.000000001);+ if (Math.min(...lengths) >= minimumSegment && ratio <= 2.5)+ continue;+ findings.push(advisory(context, {+ code: "CHAR_REST_SEGMENT_LENGTH",+ message: `Rest chain ${roles.join(" -> ")} has collapsed or grossly unmatched segment lengths.`,+ affected: { node: chain[1].evidence.node.name, nodePath: chain[1].evidence.nodePath },+ measurement: {+ name: "chainSegmentLengthRatio",+ actual: ratio,+ expected: "<=2.5",+ threshold: 2.5+ },+ viewHints: [...SKELETON_VIEWS]+ }));+ }+ return findings;+}+function forwardMarkerFindings(context, root) {+ root.updateMatrixWorld(true);+ const expected = new THREE19.Vector3(1, 0, 0).transformDirection(root.matrixWorld);+ const markers = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:toe|muzzle|head)(?:$|[._-])/i.test(joint.descriptor.role));+ return markers.flatMap((marker) => {+ const quaternion = marker.node.getWorldQuaternion(new THREE19.Quaternion);+ const actual = new THREE19.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();+ const angle = THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(actual.dot(expected), -1, 1)));+ if (angle <= FORWARD_ANGLE_DEGREES)+ return [];+ return [+ advisory(context, {+ code: "CHAR_FORWARD_MARKER",+ message: `Declared forward marker ${marker.descriptor.role} differs from canonical +X by ` + `${angle.toFixed(3)} degrees.`,+ affected: { node: marker.node.name, nodePath: marker.nodePath },+ measurement: {+ name: "forwardMarkerAngle",+ actual: angle,+ expected: 0,+ threshold: FORWARD_ANGLE_DEGREES,+ unit: "degrees"+ },+ viewHints: [...SKELETON_VIEWS]+ })+ ];+ });+}+function trackTarget(trackName) {+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(0, dot) : undefined;+}+function trackProperty(trackName) {+ const dot = trackName.lastIndexOf(".");+ return dot > 0 ? trackName.slice(dot + 1) : undefined;+}+function applyTrack(root, track, time) {+ const target = trackTarget(track.name);+ const property = trackProperty(track.name);+ const node = target ? root.getObjectByName(target) : undefined;+ if (!node || !property || !track.createInterpolant)+ return;+ const value = track.createInterpolant().evaluate(time);+ if (property === "position")+ node.position.fromArray(value);+ else if (property === "scale")+ node.scale.fromArray(value);+ else if (property === "quaternion")+ node.quaternion.fromArray(value).normalize();+}+function sampleClip(root, clip) {+ const inverse = rootInverse(root);+ return SAMPLE_FRACTIONS.map((fraction) => {+ const clone = root.clone(true);+ for (const track of clip.tracks)+ applyTrack(clone, track, fraction * clip.duration);+ clone.updateMatrixWorld(true);+ return {+ fraction,+ byRole: new Map(collectCharacterJointNodes(clone).map((evidence) => [+ evidence.descriptor.role,+ {+ point: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse),+ evidence+ }+ ]))+ };+ });+}+function locomotionClips(context) {+ const trusted = characterIntent2(context.intent);+ if (!trusted || trusted.locomotion === "stationary")+ return [];+ const names = new Set(trusted.clips.filter((clip) => clip.playback === "loop").map((clip) => clip.name));+ return (context.clips ?? []).filter(isClipLike2).filter((clip) => names.size === 0 || names.has(clip.name));+}+function limbRole(role) {+ return /(?:shoulder|elbow|wrist|hip|knee|ankle|paw|toe|wing)/i.test(role);+}+function lateralEnergyFindings(context, root, clips) {+ const rest = jointPoints(root);+ const scale = characterScale(rest);+ const minimumEnergy = scale * scale * 0.0001;+ const findings = [];+ for (const clip of clips) {+ const samples = sampleClip(root, clip);+ const roles = [...samples[0].byRole.keys()].filter(limbRole).sort();+ for (const role of roles) {+ let sagittal = 0;+ let lateral = 0;+ let maximumLateral = 0;+ let maximumFraction = 0;+ for (let index = 1;index < samples.length; index++) {+ const before = samples[index - 1].byRole.get(role)?.point;+ const after = samples[index].byRole.get(role)?.point;+ if (!before || !after)+ continue;+ const delta = after.clone().sub(before);+ sagittal += delta.x * delta.x + delta.y * delta.y;+ lateral += delta.z * delta.z;+ if (Math.abs(delta.z) > maximumLateral) {+ maximumLateral = Math.abs(delta.z);+ maximumFraction = samples[index].fraction;+ }+ }+ if (lateral + sagittal < minimumEnergy || lateral <= sagittal * LATERAL_ENERGY_RATIO)+ continue;+ const evidence = samples[0].byRole.get(role).evidence;+ findings.push(advisory(context, {+ code: "CHAR_GAIT_LATERAL_ENERGY",+ message: `Locomotion chain ${role} in ${clip.name} is lateral-motion dominant; ` + `largest offending step ends at phase ${maximumFraction}.`,+ affected: { node: evidence.node.name, nodePath: evidence.nodePath, clip: clip.name },+ measurement: {+ name: "lateralToSagittalEnergy",+ actual: lateral / Math.max(sagittal, minimumEnergy),+ expected: `<=${LATERAL_ENERGY_RATIO}`,+ threshold: LATERAL_ENERGY_RATIO+ },+ viewHints: [...MOTION_VIEWS]+ }));+ }+ }+ return findings;+}+function correlation(a, b) {+ if (a.length !== b.length || a.length < 3)+ return;+ const meanA = a.reduce((sum, value) => sum + value, 0) / a.length;+ const meanB = b.reduce((sum, value) => sum + value, 0) / b.length;+ let numerator = 0;+ let varianceA = 0;+ let varianceB = 0;+ for (let index = 0;index < a.length; index++) {+ const da = a[index] - meanA;+ const db = b[index] - meanB;+ numerator += da * db;+ varianceA += da * da;+ varianceB += db * db;+ }+ const denominator = Math.sqrt(varianceA * varianceB);+ return denominator > 0.000000001 ? numerator / denominator : undefined;+}+function phaseOppositionFindings(context, root, clips) {+ const trusted = characterIntent2(context.intent);+ if (trusted?.bodyPlan !== "biped" || !/(?:walk|run)/i.test(trusted.locomotion))+ return [];+ const findings = [];+ for (const clip of clips) {+ const samples = sampleClip(root, clip);+ const left = samples.map((sample) => sample.byRole.get("ankle.left")?.point.x);+ const right = samples.map((sample) => sample.byRole.get("ankle.right")?.point.x);+ if (left.some((value) => value === undefined) || right.some((value) => value === undefined)) {+ continue;+ }+ const phaseCorrelation = correlation(left, right);+ if (phaseCorrelation === undefined || phaseCorrelation <= PHASE_CORRELATION_THRESHOLD)+ continue;+ const evidence = samples[0].byRole.get("ankle.right").evidence;+ findings.push(advisory(context, {+ code: "CHAR_GAIT_SAME_PHASE",+ message: `Biped ${clip.name} drives left and right legs in the same phase ` + `(correlation ${phaseCorrelation.toFixed(6)}).`,+ affected: { node: evidence.node.name, nodePath: evidence.nodePath, clip: clip.name },+ measurement: {+ name: "leftRightLegPhaseCorrelation",+ actual: phaseCorrelation,+ expected: "<=0.25",+ threshold: PHASE_CORRELATION_THRESHOLD+ },+ viewHints: [...MOTION_VIEWS]+ }));+ }+ return findings;+}+function signedBendDegrees(descriptor, quaternion) {+ const rest = new THREE19.Quaternion(...descriptor.rest.rotation);+ const delta = rest.invert().multiply(quaternion).normalize();+ const axis = new THREE19.Vector3(delta.x, delta.y, delta.z);+ const signedMagnitude = axis.dot(new THREE19.Vector3(...descriptor.localBendAxis));+ const angle = 2 * Math.atan2(signedMagnitude, delta.w);+ return THREE19.MathUtils.radToDeg(THREE19.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);+}+function bendDirectionFindings(context, root, clips) {+ const joints = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role));+ const findings = [];+ for (const clip of clips) {+ for (const joint of joints) {+ const track = clip.tracks.find((candidate) => trackTarget(candidate.name) === joint.node.name && trackProperty(candidate.name) === "quaternion" && candidate.createInterpolant);+ if (!track?.createInterpolant)+ continue;+ let maximum = 0;+ let maximumFraction = 0;+ for (const fraction of SAMPLE_FRACTIONS) {+ const value = track.createInterpolant().evaluate(fraction * clip.duration);+ const bend = signedBendDegrees(joint.descriptor, new THREE19.Quaternion().fromArray(value).normalize());+ if (Math.abs(bend) > Math.abs(maximum)) {+ maximum = bend;+ maximumFraction = fraction;+ }+ }+ if (maximum >= -REVERSE_BEND_DEGREES)+ continue;+ findings.push(advisory(context, {+ code: "CHAR_JOINT_REVERSE_BEND",+ message: `${joint.descriptor.role} bends opposite its declared local bend axis at ` + `${clip.name} phase ${maximumFraction}.`,+ affected: {+ node: joint.node.name,+ nodePath: joint.nodePath,+ clip: clip.name,+ track: track.name+ },+ measurement: {+ name: "signedMaximumFlexion",+ actual: maximum,+ expected: `>=-${REVERSE_BEND_DEGREES}`,+ threshold: REVERSE_BEND_DEGREES,+ unit: "degrees"+ },+ viewHints: [...MOTION_VIEWS]+ }));+ }+ }+ return findings;+}+function footSlideFindings(context, root, clips) {+ const trusted = characterIntent2(context.intent);+ if (!trusted?.grounded)+ return [];+ const rest = jointPoints(root);+ const threshold = Math.max(0.02, characterScale(rest) * FOOT_SLIDE_RATIO);+ const contactTolerance = Math.max(0.02, threshold * 0.4);+ const contacts = rest.filter((point) => point.evidence.descriptor.contact).map((point) => point.evidence.descriptor.role);+ const findings = [];+ for (const clip of clips) {+ const samples = sampleClip(root, clip);+ for (const role of contacts) {+ let anchor;+ let maximum = 0;+ let maximumFraction = 0;+ for (const sample of samples) {+ const entry = sample.byRole.get(role);+ if (!entry || entry.point.y > contactTolerance) {+ anchor = undefined;+ continue;+ }+ anchor ??= entry.point.clone();+ const slide = Math.hypot(entry.point.x - anchor.x, entry.point.z - anchor.z);+ if (slide > maximum) {+ maximum = slide;+ maximumFraction = sample.fraction;+ }+ }+ if (maximum <= threshold)+ continue;+ const evidence = samples[0].byRole.get(role)?.evidence;+ findings.push(advisory(context, {+ code: "CHAR_FOOT_SLIDE",+ message: `Planted contact ${role} slides ${maximum.toFixed(6)} m horizontally in ` + `${clip.name} by phase ${maximumFraction}.`,+ affected: {+ node: evidence?.node.name ?? role,+ ...evidence ? { nodePath: evidence.nodePath } : {},+ clip: clip.name+ },+ measurement: {+ name: "plantedContactHorizontalSlide",+ actual: maximum,+ expected: 0,+ threshold,+ unit: "m"+ },+ viewHints: [...MOTION_VIEWS, "generic.front.depth-contact"]+ }));+ }+ }+ return findings;+}+function evaluateCharacterAdvisoryQa(context) {+ if (context.intent.category !== "character" || !(context.scene instanceof THREE19.Object3D)) {+ return [];+ }+ const root = context.scene;+ const clips = locomotionClips(context);+ return [+ ...bilateralSymmetryFindings(context, root),+ ...restChainFindings(context, root),+ ...forwardMarkerFindings(context, root),+ ...lateralEnergyFindings(context, root, clips),+ ...phaseOppositionFindings(context, root, clips),+ ...bendDirectionFindings(context, root, clips),+ ...footSlideFindings(context, root, clips)+ ].sort((a, b) => `${a.code}:${a.affected?.nodePath ?? ""}:${a.affected?.clip ?? ""}`.localeCompare(`${b.code}:${b.affected?.nodePath ?? ""}:${b.affected?.clip ?? ""}`));+}+var SKELETON_VIEWS, MOTION_VIEWS, REST_SYMMETRY_RATIO = 0.08, REST_ORDER_RATIO = 0.01, FORWARD_ANGLE_DEGREES = 45, LATERAL_ENERGY_RATIO = 1.5, PHASE_CORRELATION_THRESHOLD = 0.25, REVERSE_BEND_DEGREES = 15, FOOT_SLIDE_RATIO = 0.05, SAMPLE_FRACTIONS, BIPED_CHAINS, QUADRUPED_CHAINS, CHARACTER_ADVISORY_QA_RULE;+var init_character_advisory = __esm(() => {+ init_character();+ init_registry();+ SKELETON_VIEWS = ["character.skeleton.front", "character.skeleton.right"];+ MOTION_VIEWS = ["character.motion-strip.front", "character.motion-strip.right"];+ SAMPLE_FRACTIONS = [0, 0.25, 0.5, 0.75, 1];+ BIPED_CHAINS = [+ ["shoulder.left", "elbow.left", "wrist.left"],+ ["shoulder.right", "elbow.right", "wrist.right"],+ ["hip.left", "knee.left", "ankle.left"],+ ["hip.right", "knee.right", "ankle.right"]+ ];+ QUADRUPED_CHAINS = [+ ["shoulder.fore.left", "elbow.fore.left", "paw.fore.left"],+ ["shoulder.fore.right", "elbow.fore.right", "paw.fore.right"],+ ["hip.hind.left", "knee.hind.left", "paw.hind.left"],+ ["hip.hind.right", "knee.hind.right", "paw.hind.right"]+ ];+ CHARACTER_ADVISORY_QA_RULE = Object.freeze({+ id: "CHARACTER_ADVISORY_PROFILE",+ profile: "character.advisory",+ scope: { kind: "category", category: "character" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: evaluateCharacterAdvisoryQa+ });+});++// src/qa/geometry-relations.ts+function createProbeLocalFrame3(input) {+ if (!input.id.trim())+ throw new TypeError("Probe frame ID must be non-empty.");+ if (!finiteVector(input.origin))+ throw new TypeError("Probe frame origin must be finite.");+ const basis = [input.xAxis, input.yAxis, input.zAxis];+ for (const [index, value] of basis.entries()) {+ if (!finiteVector(value) || Math.abs(length2(value) - 1) > 0.000001) {+ throw new TypeError(`Probe frame axis ${index} must be finite and normalized within 1e-6.`);+ }+ }+ if (Math.abs(dot3(input.xAxis, input.yAxis)) > 0.000001 || Math.abs(dot3(input.xAxis, input.zAxis)) > 0.000001 || Math.abs(dot3(input.yAxis, input.zAxis)) > 0.000001 || dot3(cross2(input.xAxis, input.yAxis), input.zAxis) < 1 - 0.000001) {+ throw new TypeError("Probe frame axes must be orthonormal and right-handed.");+ }+ return {+ id: input.id,+ origin: stableVector(input.origin),+ xAxis: stableVector(input.xAxis),+ yAxis: stableVector(input.yAxis),+ zAxis: stableVector(input.zAxis)+ };+}+function probeLocalFrameFromQuaternion(id, origin, quaternion) {+ if (!quaternion.every((component) => Number.isFinite(component))) {+ throw new TypeError("Probe frame quaternion must be finite.");+ }+ const quaternionLength = Math.hypot(...quaternion);+ if (Math.abs(quaternionLength - 1) > 0.000001) {+ throw new TypeError("Probe frame quaternion must be normalized within 1e-6.");+ }+ const [x, y, z, w] = quaternion;+ const xx = x * x;+ const yy = y * y;+ const zz = z * z;+ const xy = x * y;+ const xz = x * z;+ const yz = y * z;+ const wx = w * x;+ const wy = w * y;+ const wz = w * z;+ return createProbeLocalFrame3({+ id,+ origin,+ xAxis: [1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy)],+ yAxis: [2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx)],+ zAxis: [2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy)]+ });+}+function createOrientedProbeBox3(input) {+ if (!input.id.trim())+ throw new TypeError("Oriented probe box ID must be non-empty.");+ if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent) => extent <= 0)) {+ throw new TypeError("Oriented probe box half-extents must be finite and greater than zero.");+ }+ return {+ id: input.id,+ frame: createProbeLocalFrame3(input.frame),+ halfExtents: stableVector(input.halfExtents)+ };+}+function worldPointToProbeLocal(frame, worldPoint) {+ const offset = subtract2(worldPoint, frame.origin);+ return stableVector([+ dot3(offset, frame.xAxis),+ dot3(offset, frame.yAxis),+ dot3(offset, frame.zAxis)+ ]);+}+function worldVectorToProbeLocal(frame, worldVector) {+ return stableVector([+ dot3(worldVector, frame.xAxis),+ dot3(worldVector, frame.yAxis),+ dot3(worldVector, frame.zAxis)+ ]);+}+function projection(box, axisWorld) {+ const center = dot3(box.frame.origin, axisWorld);+ const radius = axes(box.frame).reduce((total, boxAxis, index) => total + Math.abs(dot3(boxAxis, axisWorld)) * box.halfExtents[index], 0);+ return { min: center - radius, max: center + radius };+}+function orientFromReferenceToSubject(axisWorld, subject, reference) {+ return dot3(subtract2(subject.frame.origin, reference.frame.origin), axisWorld) < 0 ? scale(axisWorld, -1) : axisWorld;+}+function candidateSatAxes(subject, reference) {+ const subjectAxes = axes(subject.frame);+ const referenceAxes = axes(reference.frame);+ const candidates = [];+ const pushUnique = (rawAxis, label) => {+ if (length2(rawAxis) <= EPSILON3)+ return;+ const axis = normalize2(rawAxis);+ if (candidates.some((candidate) => Math.abs(dot3(candidate.axis, axis)) > 1 - 0.000000001))+ return;+ candidates.push({ axis, label });+ };+ for (let index = 0;index < 3; index++) {+ pushUnique(referenceAxes[index], `reference.${["x", "y", "z"][index]}`);+ }+ for (let index = 0;index < 3; index++) {+ pushUnique(subjectAxes[index], `subject.${["x", "y", "z"][index]}`);+ }+ for (let subjectIndex = 0;subjectIndex < 3; subjectIndex++) {+ for (let referenceIndex = 0;referenceIndex < 3; referenceIndex++) {+ pushUnique(cross2(subjectAxes[subjectIndex], referenceAxes[referenceIndex]), `cross.subject.${["x", "y", "z"][subjectIndex]}.reference.${["x", "y", "z"][referenceIndex]}`);+ }+ }+ return candidates;+}+function sat(subject, reference) {+ let maximumSeparation = -Infinity;+ let separatingAxis = reference.frame.xAxis;+ let separatingLabel = "reference.x";+ let minimumOverlap = Infinity;+ let overlapAxis = reference.frame.xAxis;+ let overlapLabel = "reference.x";+ for (const candidate of candidateSatAxes(subject, reference)) {+ const subjectProjection = projection(subject, candidate.axis);+ const referenceProjection = projection(reference, candidate.axis);+ const gap = Math.max(subjectProjection.min - referenceProjection.max, referenceProjection.min - subjectProjection.max);+ if (gap > maximumSeparation) {+ maximumSeparation = gap;+ separatingAxis = candidate.axis;+ separatingLabel = candidate.label;+ }+ const overlap = Math.min(subjectProjection.max, referenceProjection.max) - Math.max(subjectProjection.min, referenceProjection.min);+ if (overlap < minimumOverlap) {+ minimumOverlap = overlap;+ overlapAxis = candidate.axis;+ overlapLabel = candidate.label;+ }+ }+ if (maximumSeparation > 0) {+ return {+ separation: stable2(maximumSeparation),+ penetration: 0,+ axisWorld: orientFromReferenceToSubject(separatingAxis, subject, reference),+ axisLabel: separatingLabel+ };+ }+ return {+ separation: 0,+ penetration: stable2(Math.max(0, minimumOverlap)),+ axisWorld: orientFromReferenceToSubject(overlapAxis, subject, reference),+ axisLabel: overlapLabel+ };+}+function supportPoint(box, direction) {+ let point = [...box.frame.origin];+ axes(box.frame).forEach((boxAxis, index) => {+ const projectionValue = dot3(boxAxis, direction);+ if (Math.abs(projectionValue) <= EPSILON3)+ return;+ point = add(point, scale(boxAxis, Math.sign(projectionValue) * box.halfExtents[index]));+ });+ return stableVector(point);+}+function evidence(subject, reference, points, axisWorld, axisLabel) {+ return {+ subjectId: subject.id,+ referenceId: reference.id,+ coordinateSpace: "reference-local",+ referenceFrameId: reference.frame.id,+ ...axisWorld ? { axis: worldVectorToProbeLocal(reference.frame, axisWorld) } : {},+ ...axisLabel ? { axisLabel } : {},+ points+ };+}+function satEvidencePoints(subject, reference, axisWorld) {+ return [+ {+ label: `${reference.id}.support`,+ position: worldPointToProbeLocal(reference.frame, supportPoint(reference, axisWorld))+ },+ {+ label: `${subject.id}.support`,+ position: worldPointToProbeLocal(reference.frame, supportPoint(subject, scale(axisWorld, -1)))+ }+ ];+}+function probeOrientedPenetration(subject, reference, options = {}) {+ const maxDepth = options.maxDepth ?? 0;+ const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;+ assertNonNegative(maxDepth, "maxDepth");+ assertNonNegative(tolerance, "tolerance");+ const relation = sat(subject, reference);+ return {+ relation: "penetration",+ pass: relation.penetration <= maxDepth + tolerance,+ measurements: {+ penetrationDepth: relation.penetration,+ separation: relation.separation,+ maxDepth,+ tolerance+ },+ evidence: evidence(subject, reference, satEvidencePoints(subject, reference, relation.axisWorld), relation.axisWorld, relation.axisLabel)+ };+}+var EPSILON3 = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value) => value.length === 3 && value.every((component) => Number.isFinite(component)), add = (a, b) => [+ a[0] + b[0],+ a[1] + b[1],+ a[2] + b[2]+], subtract2 = (a, b) => [+ a[0] - b[0],+ a[1] - b[1],+ a[2] - b[2]+], scale = (value, amount) => [+ value[0] * amount,+ value[1] * amount,+ value[2] * amount+], dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], cross2 = (a, b) => [+ a[1] * b[2] - a[2] * b[1],+ a[2] * b[0] - a[0] * b[2],+ a[0] * b[1] - a[1] * b[0]+], length2 = (value) => Math.hypot(value[0], value[1], value[2]), normalize2 = (value) => {+ const magnitude = length2(value);+ if (magnitude <= EPSILON3)+ throw new TypeError("Cannot normalize a zero-length probe axis.");+ return scale(value, 1 / magnitude);+}, stable2 = (value) => {+ if (Math.abs(value) < 0.0000000001)+ return 0;+ return Number(value.toFixed(9));+}, stableVector = (value) => [+ stable2(value[0]),+ stable2(value[1]),+ stable2(value[2])+], assertNonNegative = (value, name) => {+ if (!Number.isFinite(value) || value < 0) {+ throw new TypeError(`${name} must be a finite non-negative number.`);+ }+}, axes = (frame) => [+ frame.xAxis,+ frame.yAxis,+ frame.zAxis+];++// src/qa/vehicle-advisory.ts+import * as THREE20 from "three";+function advisory2(context, value) {+ return {+ ...value,+ disposition: "warn",+ dimension: "categoryReadiness",+ profile: context.intent.qaProfile,+ viewHints: value.viewHints ?? [...VEHICLE_VIEWS]+ };+}+function localPoint(inverse, point) {+ return point.clone().applyMatrix4(inverse);+}+function wheelPairs(wheels) {+ const groups = new Map;+ for (const wheel of wheels) {+ if (!wheel.index)+ continue;+ const group = groups.get(wheel.index) ?? [];+ group.push(wheel);+ groups.set(wheel.index, group);+ }+ return [...groups.entries()].flatMap(([index, group]) => {+ const left = group.find((wheel) => wheel.side === "left");+ const right = group.find((wheel) => wheel.side === "right");+ return left && right ? [[index, left, right]] : [];+ });+}+function bilateralSymmetryFindings2(context, root, wheels) {+ root.updateMatrixWorld(true);+ const inverse = root.matrixWorld.clone().invert();+ const findings = [];+ for (const [index, left, right] of wheelPairs(wheels)) {+ const a = localPoint(inverse, left.centerWorld);+ const b = localPoint(inverse, right.centerWorld);+ const centerDelta = Math.hypot(a.x - b.x, a.y - b.y, a.z + b.z);+ const radiusDelta = Math.abs((left.radius ?? 0) - (right.radius ?? 0));+ const widthDelta = Math.abs((left.width ?? 0) - (right.width ?? 0));+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(0.01, scale * SYMMETRY_RATIO);+ const maximum = Math.max(centerDelta, radiusDelta, widthDelta);+ if (maximum <= threshold)+ continue;+ const measurementName = maximum === centerDelta ? "bilateralCenterMirrorDelta" : maximum === radiusDelta ? "bilateralRadiusDelta" : "bilateralWidthDelta";+ findings.push(advisory2(context, {+ code: "VEH_BILATERAL_SYMMETRY",+ message: `Axle ${index} left/right assemblies differ in center, radius, or width ` + `(center=${centerDelta.toFixed(6)}, radius=${radiusDelta.toFixed(6)}, width=${widthDelta.toFixed(6)} m).`,+ affected: { node: right.root.name },+ measurement: {+ name: measurementName,+ actual: maximum,+ expected: 0,+ threshold,+ unit: "m"+ }+ }));+ }+ return findings;+}+function semanticRoles(node) {+ return readSemanticMetadataV1(node)?.roles ?? [];+}+function trackSide(node) {+ for (const role of semanticRoles(node)) {+ const match = role.match(/(?:track\.loop|support\.track|track\.road-wheel)\.(left|right)(?:\.|$)/);+ if (match?.[1] === "left" || match?.[1] === "right")+ return match[1];+ }+ return;+}+function isFender(node) {+ return semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) || /fender|wheel[ _.-]?arch/i.test(node.name);+}+function isChassisMesh(node) {+ if (!(node instanceof THREE20.Mesh) || isFender(node))+ return false;+ return semanticRoles(node).some((role) => /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role)) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name);+}+function objectBoundsInFrame2(object, frame) {+ object.updateWorldMatrix(true, true);+ frame.updateWorldMatrix(true, false);+ const worldToFrame = frame.matrixWorld.clone().invert();+ const bounds = new THREE20.Box3;+ let found = false;+ object.traverse((part) => {+ if (!(part instanceof THREE20.Mesh) || !(part.geometry instanceof THREE20.BufferGeometry))+ return;+ part.geometry.computeBoundingBox();+ const box = part.geometry.boundingBox;+ if (!box)+ return;+ const matrix = worldToFrame.clone().multiply(part.matrixWorld);+ for (const x of [box.min.x, box.max.x])+ for (const y of [box.min.y, box.max.y])+ for (const z of [box.min.z, box.max.z]) {+ bounds.expandByPoint(new THREE20.Vector3(x, y, z).applyMatrix4(matrix));+ found = true;+ }+ });+ return found ? bounds : undefined;+}+function tuple2(value) {+ return [value.x, value.y, value.z];+}+function probeBox(id, root, bounds) {+ root.updateWorldMatrix(true, false);+ const center = bounds.getCenter(new THREE20.Vector3).applyMatrix4(root.matrixWorld);+ const size = bounds.getSize(new THREE20.Vector3);+ const position = new THREE20.Vector3;+ const quaternion = new THREE20.Quaternion;+ const scale = new THREE20.Vector3;+ root.matrixWorld.decompose(position, quaternion, scale);+ const xAxis = new THREE20.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();+ const yAxis = new THREE20.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();+ const zAxis = new THREE20.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();+ return createOrientedProbeBox3({+ id,+ frame: createProbeLocalFrame3({+ id: `${id}.frame`,+ origin: tuple2(center),+ xAxis: tuple2(xAxis),+ yAxis: tuple2(yAxis),+ zAxis: tuple2(zAxis)}),- "kiln.texture.polished-marble-arm.v1": Object.freeze({- sourceAsset: "marble_01",- sourceUrl: "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/1k/marble_01/marble_01_arm_1k.jpg",- sourceMd5: "51017a4e4f320c3b58763c66727d89c1",- transform: "sharp 128x128 Lanczos3 PNG"+ halfExtents: [+ size.x * Math.abs(scale.x) / 2,+ size.y * Math.abs(scale.y) / 2,+ size.z * Math.abs(scale.z) / 2+ ]+ });+}+function chassisMeshes(root) {+ const meshes = [];+ root.traverse((node) => {+ if (isChassisMesh(node))+ meshes.push(node);+ });+ return meshes;+}+function penetrationFindings(context, root, wheels) {+ const chassis = chassisMeshes(root);+ const findings = [];+ for (const wheel of wheels) {+ if (!wheel.tire || wheel.radius === undefined)+ continue;+ const tireBounds = objectBoundsInFrame2(wheel.tire, root);+ if (!tireBounds)+ continue;+ const threshold = Math.max(0.02, wheel.radius * PENETRATION_RATIO);+ for (const body of chassis) {+ const bodyBounds = objectBoundsInFrame2(body, root);+ if (!bodyBounds)+ continue;+ const result = probeOrientedPenetration(probeBox(`${wheel.id}.tire`, root, tireBounds), probeBox(body.name || "vehicle.chassis", root, bodyBounds), { maxDepth: threshold });+ if (result.pass)+ continue;+ findings.push(advisory2(context, {+ code: "VEH_WHEEL_CHASSIS_PENETRATION",+ message: `Wheel ${wheel.id} penetrates chassis ${body.name || "(unnamed)"} by ` + `${result.measurements.penetrationDepth?.toFixed(6)} m beyond the allowed non-fender overlap.`,+ affected: { node: wheel.tire.name || wheel.root.name },+ measurement: {+ name: "tireChassisPenetrationDepth",+ actual: result.measurements.penetrationDepth ?? 0,+ expected: 0,+ threshold,+ unit: "m"+ },+ viewHints: ["vehicle.underbody", "vehicle.wheel-section.right"]+ }));+ }+ }+ return findings;+}+function wholeAssetBounds(root) {+ return objectBoundsInFrame2(root, root);+}+function orientationFindings(context, root, intent) {+ if (intent.subtype === "fixed-wing" || intent.subtype === "rotorcraft" || intent.subtype === "walking" || intent.subtype === "custom") {+ return [];+ }+ const bounds = wholeAssetBounds(root);+ if (!bounds)+ return [];+ const size = bounds.getSize(new THREE20.Vector3);+ const ratio = size.z / Math.max(size.x, 0.000000001);+ if (ratio <= ORIENTATION_RATIO)+ return [];+ return [+ advisory2(context, {+ code: "VEH_ORIENTATION_SIDEWAYS",+ message: `${intent.subtype} bounds are Z-dominant despite canonical +X travel ` + `(spanX=${size.x.toFixed(6)}, spanZ=${size.z.toFixed(6)} m).`,+ affected: { node: root.name || "vehicle-root" },+ measurement: {+ name: "boundsSpanZToSpanX",+ actual: ratio,+ expected: `<=${ORIENTATION_RATIO}`,+ threshold: ORIENTATION_RATIO+ },+ viewHints: ["generic.top.semantic-overlay", "vehicle.underbody"]})+ ];+}+function nodePath(root, target) {+ let found = "";+ const visit = (node, parent, index) => {+ if (found)+ return;+ const segment = `${node.name.trim() || node.type || "Object3D"}[${index}]`;+ const path = parent ? `${parent}/${segment}` : segment;+ if (node === target) {+ found = path;+ return;+ }+ node.children.forEach((child, childIndex) => {+ visit(child, path, childIndex);+ });+ };+ visit(root, "", 0);+ return found;+}+function weldedBoundaryEdges(root, loop) {+ root.updateMatrixWorld(true);+ const inverse = loop.matrixWorld.clone().invert();+ const edges = new Map;+ let triangleCount = 0;+ const vertexKey = (point) => [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(",");+ loop.traverse((node) => {+ if (!(node instanceof THREE20.Mesh) || !(node.geometry instanceof THREE20.BufferGeometry))+ return;+ const positions = node.geometry.getAttribute("position");+ if (!positions)+ return;+ const matrix = inverse.clone().multiply(node.matrixWorld);+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE20.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));+ const index = node.geometry.getIndex();+ const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);+ for (let offset = 0;offset + 2 < indices.length; offset += 3) {+ triangleCount++;+ const triangle = [indices[offset], indices[offset + 1], indices[offset + 2]];+ for (let edge = 0;edge < 3; edge++) {+ const a = keys[triangle[edge]];+ const b = keys[triangle[(edge + 1) % 3]];+ const id = a < b ? `${a}|${b}` : `${b}|${a}`;+ edges.set(id, (edges.get(id) ?? 0) + 1);+ }+ }+ });+ if (triangleCount === 0)+ return;+ return [...edges.values()].filter((count) => count === 1).length;+}+function trackProfileFindings(context, root, intent) {+ if (intent.subtype !== "tracked")+ return [];+ const loops = [];+ const roadWheels = [];+ root.traverse((node) => {+ const roles = semanticRoles(node);+ if (roles.some((role) => role.startsWith("track.loop.")) || roles.some((role) => role.startsWith("support.track."))) {+ loops.push(node);+ }+ if (roles.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {+ roadWheels.push(node);+ }+ });+ if (loops.length === 0) {+ return [+ advisory2(context, {+ code: "VEH_TRACK_LOOP_MISSING",+ message: "Tracked vehicle exposes no semantic track.loop.* assembly to inspect.",+ affected: { node: root.name || "vehicle-root" },+ measurement: { name: "trackLoopCount", actual: 0, expected: ">=1", threshold: 1 },+ viewHints: ["vehicle.underbody", "generic.right.semantic-overlay"]+ })+ ];+ }+ const findings = [];+ for (const loop of loops) {+ const loopSide = trackSide(loop);+ const declaredClosed = loop.userData["kilnTrackLoopClosed"];+ const boundaryEdges = weldedBoundaryEdges(root, loop);+ if (declaredClosed === false || boundaryEdges !== undefined && boundaryEdges > 0) {+ findings.push(advisory2(context, {+ code: "VEH_TRACK_LOOP_OPEN",+ message: `Track loop ${loop.name || "(unnamed)"} is open ` + `(boundary edges ${boundaryEdges ?? "declared"}).`,+ affected: { node: loop.name || "track-loop", nodePath: nodePath(root, loop) },+ measurement: {+ name: "trackLoopBoundaryEdgeCount",+ actual: boundaryEdges ?? 1,+ expected: 0,+ threshold: 0+ },+ viewHints: ["vehicle.underbody", "generic.right.wireframe"]+ }));+ }+ const loopBounds = objectBoundsInFrame2(loop, root);+ if (!loopBounds)+ continue;+ const expanded = loopBounds.clone().expandByScalar(TRACK_CONTAINMENT_TOLERANCE);+ for (const roadWheel of roadWheels.filter((candidate) => !loopSide || !trackSide(candidate) || trackSide(candidate) === loopSide)) {+ const wheelBounds = objectBoundsInFrame2(roadWheel, root);+ if (!wheelBounds)+ continue;+ const center = wheelBounds.getCenter(new THREE20.Vector3);+ if (expanded.containsPoint(center))+ continue;+ const clamped = center.clone().clamp(expanded.min, expanded.max);+ const overflow = center.distanceTo(clamped);+ findings.push(advisory2(context, {+ code: "VEH_TRACK_ROAD_WHEEL_ESCAPED",+ message: `Road wheel ${roadWheel.name || "(unnamed)"} escapes track loop ` + `${loop.name || "(unnamed)"} by ${overflow.toFixed(6)} m.`,+ affected: {+ node: roadWheel.name || "track-road-wheel",+ nodePath: nodePath(root, roadWheel)+ },+ measurement: {+ name: "roadWheelTrackContainmentOverflow",+ actual: overflow,+ expected: 0,+ threshold: TRACK_CONTAINMENT_TOLERANCE,+ unit: "m"+ },+ viewHints: ["vehicle.underbody", "generic.right.semantic-overlay"]+ }));+ }+ }+ return findings;+}+function evaluateVehicleAdvisoryQa(context) {+ if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE20.Object3D)) {+ return [];+ }+ const intent = context.intent.vehicle;+ if (!intent)+ return [];+ const root = context.scene;+ root.updateMatrixWorld(true);+ const wheels = resolveVehicleWheelAssemblies(root);+ return [+ ...bilateralSymmetryFindings2(context, root, wheels),+ ...penetrationFindings(context, root, wheels),+ ...orientationFindings(context, root, intent),+ ...trackProfileFindings(context, root, intent)+ ].sort((a, b) => `${a.code}:${a.affected?.nodePath ?? a.affected?.node ?? ""}`.localeCompare(`${b.code}:${b.affected?.nodePath ?? b.affected?.node ?? ""}`));+}+var SYMMETRY_RATIO = 0.08, PENETRATION_RATIO = 0.25, ORIENTATION_RATIO = 1.15, TRACK_CONTAINMENT_TOLERANCE = 0.02, VEHICLE_VIEWS, VEHICLE_W6_ADVISORY_QA_RULE;+var init_vehicle_advisory = __esm(() => {+ init_contracts();+ init_vehicle();+ init_registry();+ VEHICLE_VIEWS = [+ "vehicle.underbody",+ "vehicle.wheel-section.right",+ "generic.top.semantic-overlay"+ ];+ VEHICLE_W6_ADVISORY_QA_RULE = Object.freeze({+ id: "VEHICLE_W6_ADVISORY_PROFILE",+ profile: "vehicle.w6-advisory",+ scope: { kind: "category", category: "vehicle" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: evaluateVehicleAdvisoryQa+ });+});++// src/qa/vehicle.ts+import * as THREE21 from "three";+function finding(context, value) {+ return {+ ...value,+ profile: context.intent.qaProfile || PROFILE,+ dimension: "categoryReadiness",+ viewHints: value.viewHints ?? ["vehicle.underbody", "vehicle.wheel-section"]+ };+}+function localPoint2(rootInverse, value) {+ return value.clone().applyMatrix4(rootInverse);+}+function rootAxis(root, axis) {+ root.updateWorldMatrix(true, false);+ return axis.clone().transformDirection(root.matrixWorld);+}+function angleDegrees(a, b) {+ return THREE21.MathUtils.radToDeg(Math.acos(THREE21.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));+}+function isDescendant(node, ancestor) {+ let current = node;+ while (current) {+ if (current === ancestor)+ return true;+ current = current.parent ?? undefined;+ }+ return false;+}+function componentDisposition(wheel) {+ return wheel.source === "semantic" ? "block" : "warn";+}+function wheelCountFindings(context, intent, wheels) {+ const findings = [];+ if (wheels.length !== intent.wheelCount) {+ findings.push(finding(context, {+ code: "VEH_WHEEL_COUNT",+ disposition: "block",+ message: `Trusted vehicle intent requires ${intent.wheelCount} wheel assemblies; resolved ${wheels.length}.`,+ measurement: {+ name: "wheelAssemblyCount",+ actual: wheels.length,+ expected: intent.wheelCount,+ threshold: intent.wheelCount+ },+ repairText: "Create exactly the requested number of axle-centered wheel assemblies and remove duplicate or ungrouped wheel parts."+ }));+ }+ const axleIds = new Set(wheels.map((wheel) => wheel.index).filter(Boolean));+ if (intent.axleCount > 0 && axleIds.size !== intent.axleCount) {+ findings.push(finding(context, {+ code: "VEH_AXLE_COUNT",+ disposition: "block",+ message: `Trusted vehicle intent requires ${intent.axleCount} axles; wheel grouping resolved ${axleIds.size}.`,+ measurement: {+ name: "wheelAxleCount",+ actual: axleIds.size,+ expected: intent.axleCount,+ threshold: intent.axleCount+ }+ }));+ }+ return findings;+}+function wheelGeometryFindings(context, root, wheels) {+ const findings = [];+ const expectedAxle = rootAxis(root, new THREE21.Vector3(0, 0, 1));+ for (const wheel of wheels) {+ const disposition = componentDisposition(wheel);+ const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);+ const pivotInverse = wheel.pivot.matrixWorld.clone().invert();+ const componentCenters = [wheel.tireCenterWorld, wheel.rimCenterWorld, wheel.hubCenterWorld].filter((center) => !!center).map((center) => localPoint2(pivotInverse, center));+ let centerDelta = 0;+ for (let a = 0;a < componentCenters.length; a++) {+ for (let b = a + 1;b < componentCenters.length; b++) {+ centerDelta = Math.max(centerDelta, componentCenters[a].distanceTo(componentCenters[b]));+ }+ }+ if (!wheel.tire || !wheel.rim || !wheel.hub || centerDelta > centerTolerance) {+ findings.push(finding(context, {+ code: "VEH_WHEEL_CONCENTRICITY",+ disposition,+ message: `Wheel ${wheel.id} tire, rim, and hub must share one axle center.`,+ affected: { node: wheel.root.name },+ measurement: {+ name: "maximumComponentCenterDelta",+ actual: Number.isFinite(centerDelta) ? centerDelta : null,+ expected: 0,+ threshold: centerTolerance,+ unit: "m"+ },+ repairText: `Move the tire, rim, and hub of ${wheel.id} to its axle-centered wheel pivot.`+ }));+ }+ const nested = wheel.radius !== undefined && wheel.rimRadius !== undefined && wheel.hubRadius !== undefined && wheel.hubRadius < wheel.rimRadius && wheel.rimRadius < wheel.radius && wheel.rimWidth !== undefined && wheel.hubWidth !== undefined && wheel.width !== undefined && wheel.rimWidth <= wheel.width + 0.000001 && wheel.hubWidth <= wheel.width + 0.000001;+ if (!nested) {+ findings.push(finding(context, {+ code: "VEH_WHEEL_RADIUS",+ disposition,+ message: `Wheel ${wheel.id} must satisfy hub radius < rim radius < tire radius and keep rim/hub widths inside the tire envelope.`,+ affected: { node: wheel.root.name },+ measurement: {+ name: "nestedRadii",+ actual: false,+ expected: true+ },+ repairText: `Resize ${wheel.id} so its hub is nested inside its rim and its rim is nested inside its tire.`+ }));+ }+ const axleAngle = angleDegrees(wheel.spinAxisWorld, expectedAxle);+ if (axleAngle > AXIS_TOLERANCE_DEGREES) {+ findings.push(finding(context, {+ code: "VEH_WHEEL_AXLE_AXIS",+ disposition,+ message: `Wheel ${wheel.id} spin axis must align with vehicle-local +Z.`,+ affected: { node: wheel.pivot.name },+ measurement: {+ name: "axleAxisAngle",+ actual: axleAngle,+ expected: 0,+ threshold: AXIS_TOLERANCE_DEGREES,+ unit: "degrees"+ },+ repairText: `Orient ${wheel.pivot.name} so its local +Z is the axle/spin axis.`+ }));+ }+ const pivotDelta = localPoint2(pivotInverse, wheel.pivotCenterWorld).distanceTo(localPoint2(pivotInverse, wheel.centerWorld));+ const descendants = [wheel.tire, wheel.rim, wheel.hub].every((part) => isDescendant(part, wheel.pivot));+ if (!descendants || pivotDelta > centerTolerance) {+ findings.push(finding(context, {+ code: "VEH_WHEEL_PIVOT",+ disposition,+ message: `Wheel ${wheel.id} pivot must be at the axle center and own every moving component.`,+ affected: { node: wheel.pivot.name },+ measurement: {+ name: "pivotCenterDelta",+ actual: pivotDelta,+ expected: 0,+ threshold: centerTolerance,+ unit: "m"+ },+ repairText: `Place ${wheel.pivot.name} at the axle center and parent tire, rim, and hub beneath it.`+ }));+ }+ }+ return findings;+}+function axlePairFindings(context, root, wheels) {+ root.updateWorldMatrix(true, false);+ const inverse = root.matrixWorld.clone().invert();+ const groups = new Map;+ for (const wheel of wheels) {+ if (!wheel.index)+ continue;+ const group = groups.get(wheel.index) ?? [];+ group.push(wheel);+ groups.set(wheel.index, group);+ }+ const findings = [];+ for (const [index, pair] of groups) {+ const left = pair.find((wheel) => wheel.side === "left");+ const right = pair.find((wheel) => wheel.side === "right");+ if (!left || !right)+ continue;+ const leftCenter = localPoint2(inverse, left.centerWorld);+ const rightCenter = localPoint2(inverse, right.centerWorld);+ const delta = Math.hypot(leftCenter.x - rightCenter.x, leftCenter.y - rightCenter.y);+ if (delta > PAIR_TOLERANCE) {+ findings.push(finding(context, {+ code: "VEH_AXLE_PAIR",+ disposition: left.source === "semantic" && right.source === "semantic" ? "block" : "warn",+ message: `Axle ${index} left/right wheel centers disagree in vehicle-local X/Y.`,+ affected: { node: right.root.name },+ measurement: {+ name: "pairedCenterXYDelta",+ actual: delta,+ expected: 0,+ threshold: PAIR_TOLERANCE,+ unit: "m"+ },+ repairText: `Align both wheels on axle ${index} to the same local X and Y coordinates.`+ }));+ }+ }+ return findings;+}+function duplicateAssemblyFindings(context, root, wheels) {+ root.updateMatrixWorld(true);+ const inverse = root.matrixWorld.clone().invert();+ const findings = [];+ for (let a = 0;a < wheels.length; a++) {+ for (let b = a + 1;b < wheels.length; b++) {+ const left = wheels[a];+ const right = wheels[b];+ const sameDeclaredCorner = left.side !== undefined && left.side === right.side && left.index !== undefined && left.index === right.index;+ const centerDelta = localPoint2(inverse, left.centerWorld).distanceTo(localPoint2(inverse, right.centerWorld));+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(CENTER_MINIMUM, scale * CENTER_RATIO);+ if (!sameDeclaredCorner && centerDelta > threshold)+ continue;+ const semantic = left.source === "semantic" && right.source === "semantic";+ findings.push(finding(context, {+ code: "VEH_DUPLICATE_ASSEMBLY",+ disposition: semantic ? "block" : "warn",+ message: `Wheel assemblies ${left.id} and ${right.id} resolve to the same ` + `${sameDeclaredCorner ? `${left.side}-${left.index} corner` : "scale-relative center"}.`,+ affected: { node: right.root.name },+ measurement: {+ name: "duplicateAssemblyCenterDelta",+ actual: centerDelta,+ expected: `>${threshold}`,+ threshold,+ unit: "m"+ },+ viewHints: [+ "vehicle.underbody",+ "vehicle.wheel-section.right",+ "generic.top.semantic-overlay"+ ],+ repairText: `Remove only duplicate assembly ${right.id} at the reported center; preserve ${left.id} and rebuild the actually missing corner from trusted wheel/axle intent.`+ }));+ }+ }+ return findings;+}+function contactFindings2(context, root, intent, wheels) {+ if (intent.supportPolicy !== "grounded")+ return [];+ root.updateWorldMatrix(true, false);+ const inverse = root.matrixWorld.clone().invert();+ const findings = [];+ for (const wheel of wheels.filter((value) => value.loadBearing)) {+ const center = localPoint2(inverse, wheel.centerWorld);+ const contactY = center.y - (wheel.radius ?? 0);+ if (wheel.radius === undefined || Math.abs(contactY) > CONTACT_TOLERANCE2) {+ findings.push(finding(context, {+ code: "VEH_CONTACT_PLANE",+ disposition: componentDisposition(wheel),+ message: `Load-bearing wheel ${wheel.id} must touch the shared ground plane Y=0 without floating or burial.`,+ affected: { node: wheel.tire?.name ?? wheel.root.name },+ measurement: {+ name: "tireContactY",+ actual: wheel.radius === undefined ? null : contactY,+ expected: 0,+ threshold: CONTACT_TOLERANCE2,+ unit: "m"+ },+ repairText: `Set ${wheel.id} axle-center Y to its tire radius so its contact point is Y=0.`+ }));+ }+ }+ return findings;+}+function renderableMinYInRoot(rootInverse, node) {+ let minimum = Infinity;+ node.traverse((part) => {+ if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))+ return;+ part.geometry.computeBoundingBox();+ const bounds = part.geometry.boundingBox;+ if (!bounds)+ return;+ const matrix = rootInverse.clone().multiply(part.matrixWorld);+ for (const x of [bounds.min.x, bounds.max.x]) {+ for (const y of [bounds.min.y, bounds.max.y]) {+ for (const z of [bounds.min.z, bounds.max.z]) {+ minimum = Math.min(minimum, new THREE21.Vector3(x, y, z).applyMatrix4(matrix).y);+ }+ }+ }+ });+ return Number.isFinite(minimum) ? minimum : undefined;+}+function supportContactFindings(context, root, intent) {+ if (intent.supportPolicy !== "grounded")+ return [];+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const explicitContacts = [];+ const supports = [];+ root.traverse((node) => {+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ const isWheelContact = roles.some((role) => role.startsWith("wheel.contact."));+ if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {+ explicitContacts.push({+ node,+ contactY: localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(node.matrixWorld)).y,+ source: "contact"+ });+ }+ if (roles.some((role) => role.startsWith("support."))) {+ const contactY = renderableMinYInRoot(inverse, node);+ if (contactY !== undefined)+ supports.push({ node, contactY, source: "support" });+ }+ });+ const measurements = explicitContacts.length > 0 ? explicitContacts : supports;+ const findings = measurements.flatMap((measurement) => {+ if (Math.abs(measurement.contactY) <= CONTACT_TOLERANCE2)+ return [];+ return [+ finding(context, {+ code: "VEH_CONTACT_PLANE",+ disposition: "block",+ message: `Load-bearing ${measurement.source} ${measurement.node.name || "(unnamed)"} must touch the shared ground plane Y=0 without floating or burial.`,+ affected: { node: measurement.node.name || "vehicle-support" },+ measurement: {+ name: "supportContactY",+ actual: measurement.contactY,+ expected: 0,+ threshold: CONTACT_TOLERANCE2,+ unit: "m"+ },+ repairText: `Move ${measurement.node.name || "the support"} so its declared contact rests at vehicle-local Y=0.`+ })+ ];+ });+ if (intent.wheelCount === 0) {+ for (const expected of intent.supportAssemblies) {+ const matches = [...explicitContacts, ...supports].filter((measurement) => (readSemanticMetadataV1(measurement.node)?.roles ?? []).some((role) => role === `support.${expected}` || role.startsWith(`support.${expected}.`) || role === `contact.${expected}` || role.startsWith(`contact.${expected}.`)));+ if (matches.length > 0)+ continue;+ findings.push(finding(context, {+ code: "VEH_SUPPORT_SET_MISSING",+ disposition: "block",+ message: `Trusted grounded ${intent.subtype} intent requires semantic ${expected} supports or contacts.`,+ affected: { node: root.name || "vehicle-root" },+ measurement: {+ name: `${expected}SupportCount`,+ actual: 0,+ expected: ">=1",+ threshold: 1+ },+ viewHints: ["vehicle.underbody", "generic.front.depth-contact"],+ repairText: `Add only the declared ${expected} support set, tag each load-bearing part/contact semantically, and place every contact on vehicle-local Y=0.`+ }));+ }+ if (measurements.length > 1) {+ const values = measurements.map((measurement) => measurement.contactY);+ const range = Math.max(...values) - Math.min(...values);+ if (range > CONTACT_TOLERANCE2) {+ findings.push(finding(context, {+ code: "VEH_SUPPORT_PLANE",+ disposition: "block",+ message: `Declared non-wheel supports do not share one stable vehicle-local contact plane.`,+ affected: { node: root.name || "vehicle-root" },+ measurement: {+ name: "supportContactPlaneRange",+ actual: range,+ expected: 0,+ threshold: CONTACT_TOLERANCE2,+ unit: "m"+ },+ viewHints: ["vehicle.underbody", "generic.front.depth-contact"],+ repairText: "Move only the reported skid, landing-gear, track, or other support contacts onto one vehicle-local Y=0 plane while preserving their stance."+ }));+ }+ }+ }+ return findings;+}+function steeringFindings(context, root, intent, wheels) {+ if (intent.steering === "none" || wheels.length === 0)+ return [];+ root.updateWorldMatrix(true, false);+ const inverse = root.matrixWorld.clone().invert();+ const expectedAxis = rootAxis(root, new THREE21.Vector3(0, 1, 0));+ const localCenters = wheels.map((wheel) => ({+ wheel,+ center: localPoint2(inverse, wheel.centerWorld)+ }));+ const extreme = intent.steering === "rear" ? Math.min(...localCenters.map((entry) => entry.center.x)) : Math.max(...localCenters.map((entry) => entry.center.x));+ const targets = intent.steering === "all" ? localCenters : localCenters.filter((entry) => Math.abs(entry.center.x - extreme) <= PAIR_TOLERANCE);+ const findings = [];+ for (const { wheel } of targets) {+ const steering = wheel.steeringPivot;+ const centerDelta = steering ? localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;+ const axisAngle = steering ? angleDegrees(new THREE21.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;+ if (!steering || !isDescendant(wheel.pivot, steering) || centerDelta > CENTER_MINIMUM || axisAngle > AXIS_TOLERANCE_DEGREES) {+ const axisInvalid = axisAngle > AXIS_TOLERANCE_DEGREES;+ findings.push(finding(context, {+ code: "VEH_STEERING_PIVOT",+ disposition: componentDisposition(wheel),+ message: `Declared steering wheel ${wheel.id} requires a centered +Y steering pivot owning its spin pivot.`,+ affected: { node: steering?.name ?? wheel.pivot.name },+ measurement: {+ name: axisInvalid ? "steeringAxisAngle" : "steeringPivotCenterDelta",+ actual: axisInvalid ? Number.isFinite(axisAngle) ? axisAngle : null : Number.isFinite(centerDelta) ? centerDelta : null,+ expected: 0,+ threshold: axisInvalid ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,+ unit: axisInvalid ? "degrees" : "m"+ },+ repairText: `Move the steering pivot for ${wheel.id} to the axle center, orient local +Y as steering axis, and parent the wheel spin pivot beneath it.`+ }));+ }+ }+ return findings;+}+function propulsionFindings(context, root, intent) {+ const expectedKinds = intent.propulsionAssemblies.filter((value) => value === "rotor" || value === "propeller");+ if (expectedKinds.length === 0)+ return [];+ const pivots = new Map;+ const components = [];+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ for (const role of metadata?.roles ?? []) {+ if (role.startsWith("propulsion.pivot."))+ pivots.set(role.slice("propulsion.pivot.".length), node);+ for (const kind of ["rotor", "propeller"]) {+ if (role.startsWith(`propulsion.${kind}.`)) {+ components.push({ id: role.slice(`propulsion.${kind}.`.length), kind, node });+ }+ }+ }});+ const findings = [];+ root.updateWorldMatrix(true, false);+ const rootInverse = root.matrixWorld.clone().invert();+ for (const kind of expectedKinds) {+ const candidates = components.filter((part) => part.kind === kind);+ if (candidates.length === 0) {+ findings.push(finding(context, {+ code: "VEH_ROTOR_PIVOT",+ disposition: "block",+ message: `Trusted vehicle intent requires a semantic ${kind} assembly and centered pivot.`,+ measurement: { name: `${kind}AssemblyCount`, actual: 0, expected: 1, threshold: 1 }+ }));+ continue;+ }+ for (const component of candidates) {+ const pivot = pivots.get(component.id);+ const box = new THREE21.Box3().setFromObject(component.node);+ const center = box.isEmpty() ? undefined : box.getCenter(new THREE21.Vector3);+ const pivotCenter = pivot ? new THREE21.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;+ const delta = center && pivotCenter ? localPoint2(rootInverse, center).distanceTo(localPoint2(rootInverse, pivotCenter)) : Infinity;+ const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";+ const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);+ const canonicalAxis = kind === "rotor" ? new THREE21.Vector3(0, 1, 0) : new THREE21.Vector3(1, 0, 0);+ const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE21.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;+ if (!pivot || !isDescendant(component.node, pivot) || delta > CENTER_MINIMUM || !axisFrame || axisAngle > AXIS_TOLERANCE_DEGREES) {+ findings.push(finding(context, {+ code: "VEH_ROTOR_PIVOT",+ disposition: "block",+ message: `${kind} ${component.id} requires a centered owning pivot with ${frameId}.`,+ affected: { node: pivot?.name ?? component.node.name },+ measurement: {+ name: axisAngle > AXIS_TOLERANCE_DEGREES ? "propulsionAxisAngle" : "propulsionPivotCenterDelta",+ actual: axisAngle > AXIS_TOLERANCE_DEGREES ? Number.isFinite(axisAngle) ? axisAngle : null : Number.isFinite(delta) ? delta : null,+ expected: 0,+ threshold: axisAngle > AXIS_TOLERANCE_DEGREES ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,+ unit: axisAngle > AXIS_TOLERANCE_DEGREES ? "degrees" : "m"+ },+ repairText: `Place the ${kind} pivot at the mast/shaft center, parent the moving geometry beneath it, and declare ${frameId}.`+ }));+ }+ }+ }+ return findings;+}+function evaluateVehicleQa(context) {+ if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE21.Object3D))+ return [];+ const intent = context.intent.vehicle;+ if (!intent)+ return [];+ const root = context.scene;+ root.updateMatrixWorld(true);+ const wheels = resolveVehicleWheelAssemblies(root);+ const findings = [];+ if (!hasCanonicalVehicleFront(root)) {+ findings.push(finding(context, {+ code: "VEH_FRONT_AXIS",+ disposition: "block",+ message: "Generated vehicles must declare the trusted semantic +X front frame.",+ affected: { node: root.name || "vehicle-root" },+ measurement: { name: "canonicalFrontDeclared", actual: false, expected: true },+ repairText: "Author the vehicle beneath createVehicleFrame() and preserve vehicle.front.+x semantics."+ }));+ }+ if (intent.wheelCount > 0 || intent.subtype === "wheeled") {+ findings.push(...wheelCountFindings(context, intent, wheels));+ findings.push(...wheelGeometryFindings(context, root, wheels));+ findings.push(...axlePairFindings(context, root, wheels));+ findings.push(...duplicateAssemblyFindings(context, root, wheels));+ findings.push(...contactFindings2(context, root, intent, wheels));+ findings.push(...steeringFindings(context, root, intent, wheels));+ }+ findings.push(...supportContactFindings(context, root, intent));+ findings.push(...propulsionFindings(context, root, intent));+ return findings;+}+var PROFILE = "vehicle.semantic", CENTER_RATIO = 0.03, CENTER_MINIMUM = 0.01, AXIS_TOLERANCE_DEGREES = 1, PAIR_TOLERANCE = 0.015, CONTACT_TOLERANCE2 = 0.02, VEHICLE_QA_RULE, VEHICLE_ADVISORY_QA_RULE, VEHICLE_QA_RULES;+var init_vehicle2 = __esm(() => {+ init_contracts();+ init_vehicle();+ init_registry();+ init_vehicle_advisory();+ VEHICLE_QA_RULE = {+ id: "VEHICLE_PROFILE",+ profile: PROFILE,+ scope: { kind: "category", category: "vehicle" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("vehicle-qa-v1", "src/qa/vehicle.test.ts", "4bffa0dff0ed33be2ce7003ee36ac33efc5b4900e57d390898e43551912e626b"),+ defaultMode: "enforce",+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition === "block")+ };+ VEHICLE_ADVISORY_QA_RULE = {+ id: "VEHICLE_ADVISORY_PROFILE",+ profile: "vehicle.advisory",+ scope: { kind: "category", category: "vehicle" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition !== "block")+ };+ VEHICLE_QA_RULES = [+ VEHICLE_QA_RULE,+ VEHICLE_ADVISORY_QA_RULE,+ VEHICLE_W6_ADVISORY_QA_RULE+ ];});-// src/material-recipes.ts-function validateMaterialRecipeRequestV1(value) {- const issues = [];- if (!isRecord5(value)) {- return {- valid: false,- issues: [{ code: "EXPECTED_OBJECT", path: "", message: "materialRecipe must be an object." }]- };+// src/qa/vegetation.ts+import * as THREE22 from "three";+function rolesOf(node) {+ return readSemanticMetadataV1(node)?.roles ?? [];+}+function pathOf(node, root) {+ const names = [];+ let cursor = node;+ while (cursor) {+ names.push(cursor.name || cursor.type);+ if (cursor === root)+ break;+ cursor = cursor.parent;+ }+ return names.reverse().join("/");+}+function localPoint3(rootInverse, node) {+ return node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse);+}+function meshLocalBox(mesh, rootInverse) {+ if (!(mesh.geometry instanceof THREE22.BufferGeometry))+ return;+ mesh.geometry.computeBoundingBox();+ const source = mesh.geometry.boundingBox;+ if (!source || source.isEmpty())+ return;+ const transform = rootInverse.clone().multiply(mesh.matrixWorld);+ const result = new THREE22.Box3;+ for (const x of [source.min.x, source.max.x]) {+ for (const y of [source.min.y, source.max.y]) {+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE22.Vector3(x, y, z).applyMatrix4(transform));+ }+ }+ }+ return result;+}+function collectRenderableBounds(root) {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const values = [];+ root.traverse((node) => {+ if (!(node instanceof THREE22.Mesh))+ return;+ const box = meshLocalBox(node, inverse);+ if (!box)+ return;+ const roles = rolesOf(node);+ values.push({ node, box, roles, source: roles.length > 0 ? "semantic" : "fallback" });+ });+ return values;+}+function finding2(context, value) {+ return { ...value, profile: context.intent.qaProfile || PROFILE2 };+}+function vegetationIntent(intent) {+ return intent.category === "vegetation" ? intent.vegetation : undefined;+}+function evaluateVegetationContactQa(context) {+ const trusted = vegetationIntent(context.intent);+ if (!trusted?.grounded || !(context.scene instanceof THREE22.Object3D))+ return [];+ const root = context.scene;+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const contacts = [];+ const semanticSupports = [];+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ const roles = metadata?.roles ?? [];+ if (roles.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {+ const frame = metadata?.frames.find((value) => value.id === "ground-contact" || value.id === "vegetation-ground-contact");+ contacts.push({+ node,+ ...frame ? { frameTranslation: frame.translation } : {}+ });+ }+ if (roles.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {+ semanticSupports.push(node);+ }+ });+ if (contacts.length === 0) {+ return [+ finding2(context, {+ code: "VEG_CONTACT_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "Standalone grounded vegetation requires one semantic ground-contact marker.",+ affected: { node: root.name || "vegetation-root" },+ measurement: { name: "groundContactCount", actual: 0, expected: ">=1" },+ viewHints: ["right", "vegetation.base-contact"],+ repairText: "Add a vegetation.contact.ground semantic marker at asset-local Y=0 and seat the plant base on it."+ })+ ];+ }+ const findings = [];+ for (const contact of contacts) {+ const contactPoint = contact.frameTranslation ? new THREE22.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);+ const y = contactPoint.y;+ if (Math.abs(y) <= VEGETATION_CONTACT_TOLERANCE_METERS)+ continue;+ const floating = y > 0;+ findings.push(finding2(context, {+ code: floating ? "VEG_CONTACT_FLOATING" : "VEG_CONTACT_BURIED",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `${contact.node.name || "Vegetation contact"} is ${Math.abs(y).toFixed(6)} m ${floating ? "above" : "below"} asset-local ground.`,+ affected: {+ node: contact.node.name || "vegetation-contact",+ nodePath: pathOf(contact.node, root)+ },+ measurement: {+ name: "contactY",+ actual: stable3(y),+ expected: 0,+ threshold: VEGETATION_CONTACT_TOLERANCE_METERS,+ unit: "m"+ },+ viewHints: ["right", "vegetation.base-contact"],+ repairText: `Move ${contact.node.name || "the contact marker"} or its ground-contact frame to asset-local Y=0 without moving unrelated canopy parts.`+ }));+ }+ for (const support of semanticSupports) {+ let minimumY = Infinity;+ support.traverse((node) => {+ if (!(node instanceof THREE22.Mesh))+ return;+ const box = meshLocalBox(node, inverse);+ if (box)+ minimumY = Math.min(minimumY, box.min.y);+ });+ if (!Number.isFinite(minimumY) || minimumY >= -VEGETATION_CONTACT_TOLERANCE_METERS)+ continue;+ findings.push(finding2(context, {+ code: "VEG_MATERIAL_BURIED",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `${support.name || "Vegetation support"} extends materially below the standalone ground plane.`,+ affected: { node: support.name || "vegetation-support", nodePath: pathOf(support, root) },+ measurement: {+ name: "supportMinimumY",+ actual: stable3(minimumY),+ expected: 0,+ threshold: VEGETATION_CONTACT_TOLERANCE_METERS,+ unit: "m"+ },+ viewHints: ["right", "vegetation.base-contact"],+ repairText: "Raise or trim the declared trunk/stem/root support so its visible material stops at Y=0."+ }));+ }+ return findings;+}+function materialNames(node) {+ if (!(node instanceof THREE22.Mesh))+ return [];+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ return materials.filter(Boolean).map((material) => material.name ?? "");+}+function evaluateVegetationScopeQa(context) {+ const trusted = vegetationIntent(context.intent);+ if (!trusted?.standalone || !(context.scene instanceof THREE22.Object3D))+ return [];+ const root = context.scene;+ const renderables = collectRenderableBounds(root);+ if (renderables.length === 0)+ return [];+ const overall = renderables.reduce((box, value) => box.union(value.box), new THREE22.Box3);+ const overallSize = overall.getSize(new THREE22.Vector3);+ const findings = [];+ for (const value of renderables) {+ const size = value.box.getSize(new THREE22.Vector3);+ const center = value.box.getCenter(new THREE22.Vector3);+ const names = [value.node.name, ...value.roles];+ const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));+ const roleEvidence = value.roles.some((role) => /(?:terrain|soil|rock|pot|planter|base)/i.test(role));+ const materialEvidence = materialNames(value.node).some((name) => CLUTTER_NAME.test(name));+ const footprintRatio = size.x * size.z / Math.max(0.000000001, overallSize.x * overallSize.z);+ const flatEvidence = footprintRatio >= 0.35 && size.y <= Math.max(0.08, overallSize.y * 0.08) && center.y <= VEGETATION_CONTACT_TOLERANCE_METERS + size.y;+ const evidence = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);+ if (evidence.length < 2)+ continue;+ findings.push(finding2(context, {+ code: "VEG_SCOPE_EXTRA",+ disposition: "warn",+ dimension: "promptAlignment",+ message: `${value.node.name || "Renderable"} is likely unrequested standalone-vegetation base clutter; review before removal.`,+ affected: {+ node: value.node.name || "vegetation-extra",+ nodePath: pathOf(value.node, root)+ },+ measurement: {+ name: "scopeEvidence",+ actual: [+ nameEvidence ? "name" : "",+ roleEvidence ? "role" : "",+ materialEvidence ? "material" : "",+ flatEvidence ? "flat-footprint" : ""+ ].filter(Boolean).join(","),+ expected: "standalone plant/fungus only"+ },+ viewHints: ["top", "three-quarter", "vegetation.base-contact"]+ }));+ }+ return findings;+}+function unionVolume(boxes) {+ if (boxes.length === 0)+ return 0;+ const union = boxes.reduce((result, box) => result.union(box), new THREE22.Box3);+ const size = union.getSize(new THREE22.Vector3);+ return size.x * size.y * size.z;+}+function projectedOccupancy(boxes, axes) {+ if (boxes.length === 0)+ return 0;+ const minimum = [Infinity, Infinity];+ const maximum = [-Infinity, -Infinity];+ for (const box of boxes) {+ const min = [box.min.x, box.min.y, box.min.z];+ const max = [box.max.x, box.max.y, box.max.z];+ for (const dimension of [0, 1]) {+ minimum[dimension] = Math.min(minimum[dimension], min[axes[dimension]]);+ maximum[dimension] = Math.max(maximum[dimension], max[axes[dimension]]);+ }}- if (value.schemaVersion !== 1) {- issues.push({- code: "UNSUPPORTED_SCHEMA_VERSION",- path: "schemaVersion",- message: "materialRecipe.schemaVersion must be 1."- });+ const spans = [maximum[0] - minimum[0], maximum[1] - minimum[1]];+ if (spans[0] <= 0.000000001 || spans[1] <= 0.000000001)+ return 0;+ const occupied = new Uint8Array(RASTER_SIZE * RASTER_SIZE);+ for (const box of boxes) {+ const min = [box.min.x, box.min.y, box.min.z];+ const max = [box.max.x, box.max.y, box.max.z];+ const x0 = Math.max(0, Math.floor((min[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const y0 = Math.max(0, Math.floor((min[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ for (let y = y0;y <= y1; y++) {+ for (let x = x0;x <= x1; x++)+ occupied[y * RASTER_SIZE + x] = 1;+ }}- if (!recipeId(value.id)) {- issues.push({- code: "UNSUPPORTED_RECIPE_ID",- path: "id",- message: `Unsupported material recipe ID ${JSON.stringify(value.id)}.`- });+ return stable3(occupied.reduce((sum, value) => sum + value, 0) / occupied.length);+}+function matchesAny(value, patterns) {+ const candidates = [value.node.name, ...value.roles];+ return candidates.some((candidate) => patterns.some((pattern) => pattern.test(candidate)));+}+function measurementSource(values) {+ if (values.length === 0)+ return "none";+ const semantic = values.some((value) => value.source === "semantic");+ const fallback = values.some((value) => value.source === "fallback");+ return semantic && fallback ? "mixed" : semantic ? "semantic" : "fallback";+}+function roleOrNameSource(value, patterns) {+ if (value.roles.some((role) => patterns.some((pattern) => pattern.test(role))))+ return "semantic";+ if (patterns.some((pattern) => pattern.test(value.node.name)))+ return "fallback";+ return;+}+function growthCandidates(root) {+ const result = [];+ for (const value of collectRenderableBounds(root)) {+ const branchSource = roleOrNameSource(value, BRANCH_PATTERNS);+ const trunkSource = roleOrNameSource(value, TRUNK_PATTERNS);+ if (branchSource)+ result.push({ ...value, kind: "branch", growthSource: branchSource });+ else if (trunkSource)+ result.push({ ...value, kind: "trunk", growthSource: trunkSource });}- if (value.overrides !== undefined && !isRecord5(value.overrides)) {- issues.push({- code: "INVALID_OVERRIDES",- path: "overrides",- message: "materialRecipe.overrides must be an object."- });+ return result;+}+function boxDistanceToPoint(box, point) {+ return box.distanceToPoint(point);+}+function endpointRadius(position, axis, axisValue, tolerance, scale) {+ const radialAxes = [0, 1, 2].filter((value) => value !== axis);+ const points = [];+ const point = new THREE22.Vector3;+ for (let index = 0;index < position.count; index++) {+ point.fromBufferAttribute(position, index);+ if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)+ points.push(point.clone());}- if (recipeId(value.id) && isRecord5(value.overrides)) {- const allowed = new Set(MATERIAL_RECIPE_LIBRARY_V1[value.id].allowedOverrides);- for (const [key, override] of Object.entries(value.overrides)) {- if (!MATERIAL_RECIPE_OVERRIDE_KEYS.includes(key)) {- issues.push({- code: "UNSUPPORTED_OVERRIDE",- path: `overrides.${key}`,- message: `Unknown material recipe override ${JSON.stringify(key)}.`- });- continue;- }- if (!allowed.has(key)) {- issues.push({- code: "UNSUPPORTED_OVERRIDE",- path: `overrides.${key}`,- message: `${key} is not supported by ${value.id}.`- });- continue;- }- if ((key === "baseColor" || key === "emissiveColor") && !hexColor(override)) {- issues.push({- code: "INVALID_OVERRIDE_VALUE",- path: `overrides.${key}`,- message: `${key} must be a six-digit #RRGGBB color.`- });- } else if ((key === "roughness" || key === "metalness" || key === "opacity" || key === "alphaCutoff") && !finiteUnit(override)) {- issues.push({- code: "INVALID_OVERRIDE_VALUE",- path: `overrides.${key}`,- message: `${key} must be a finite number in [0,1].`- });- } else if (key === "doubleSided" && typeof override !== "boolean") {- issues.push({- code: "INVALID_OVERRIDE_VALUE",- path: `overrides.${key}`,- message: "doubleSided must be boolean."- });- } else if (key === "emissiveIntensity" && (typeof override !== "number" || !Number.isFinite(override) || override < 0 || override > 1)) {- issues.push({- code: "INVALID_OVERRIDE_VALUE",- path: `overrides.${key}`,- message: "emissiveIntensity must be a finite number in [0,1] for core glTF."- });- } else if (key === "textureResources") {- if (!isRecord5(override)) {- issues.push({- code: "INVALID_OVERRIDE_VALUE",- path: "overrides.textureResources",- message: "textureResources must be an object keyed by portable material slot."- });- continue;- }- for (const [slot, selected] of Object.entries(override)) {- if (!MATERIAL_TEXTURE_SLOTS.includes(slot)) {- issues.push({- code: "UNKNOWN_TEXTURE_SLOT",- path: `overrides.textureResources.${slot}`,- message: `Unknown portable texture slot ${JSON.stringify(slot)}.`- });- continue;- }- if (!resourceId(selected)) {- issues.push({- code: "UNSUPPORTED_RESOURCE_ID",- path: `overrides.textureResources.${slot}`,- message: `Unsupported approved texture resource ID ${JSON.stringify(selected)}.`- });- continue;- }- const resource = APPROVED_TEXTURE_RESOURCES_V1[selected];- if (!resource.allowedSlots.includes(slot)) {- issues.push({- code: "RESOURCE_SLOT_MISMATCH",- path: `overrides.textureResources.${slot}`,- message: `${selected} cannot be used in ${slot}.`- });- }- if (!resource.recipeIds.includes(value.id)) {- issues.push({- code: "RESOURCE_RECIPE_MISMATCH",- path: `overrides.textureResources.${slot}`,- message: `${selected} is not approved for ${value.id}.`- });- }- }- }+ if (points.length === 0)+ return;+ const center = new THREE22.Vector3;+ center.setComponent(axis, axisValue);+ for (const radialAxis of radialAxes) {+ center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);+ }+ let radius = 0;+ for (const value of points) {+ const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale.getComponent(radialAxes[0]));+ const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale.getComponent(radialAxes[1]));+ radius = Math.max(radius, Math.hypot(a, b));+ }+ return { center, radius };+}+function growthNodeMeasurement(root, candidate, allCandidates, band) {+ if (!(candidate.node instanceof THREE22.Mesh))+ return;+ const geometry = candidate.node.geometry;+ const position = geometry.getAttribute("position");+ if (!position || position.count < 2)+ return;+ geometry.computeBoundingBox();+ const geometryBox = geometry.boundingBox;+ if (!geometryBox || geometryBox.isEmpty())+ return;+ root.updateWorldMatrix(true, true);+ const relative = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);+ const relativeScale = new THREE22.Vector3;+ relative.decompose(new THREE22.Vector3, new THREE22.Quaternion, relativeScale);+ const size = geometryBox.getSize(new THREE22.Vector3);+ const scaledSizes = [+ Math.abs(size.x * relativeScale.x),+ Math.abs(size.y * relativeScale.y),+ Math.abs(size.z * relativeScale.z)+ ];+ const axis = scaledSizes.indexOf(Math.max(...scaledSizes));+ const minimum = geometryBox.min.getComponent(axis);+ const maximum = geometryBox.max.getComponent(axis);+ const tolerance = Math.max(0.000001, (maximum - minimum) * 0.0001);+ const first = endpointRadius(position, axis, minimum, tolerance, relativeScale);+ const second = endpointRadius(position, axis, maximum, tolerance, relativeScale);+ if (!first || !second)+ return;+ const firstPoint = first.center.clone().applyMatrix4(relative);+ const secondPoint = second.center.clone().applyMatrix4(relative);+ const supportBoxes = allCandidates.filter((value) => value !== candidate).map((value) => value.box);+ let firstIsBase;+ if (candidate.kind === "trunk") {+ firstIsBase = firstPoint.y <= secondPoint.y;+ } else if (supportBoxes.length > 0) {+ const firstGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, firstPoint)));+ const secondGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, secondPoint)));+ firstIsBase = Math.abs(firstGap - secondGap) > 0.000001 ? firstGap < secondGap : first.radius >= second.radius;+ } else {+ firstIsBase = first.radius >= second.radius;+ }+ const baseRadius = firstIsBase ? first.radius : second.radius;+ const tipRadius = firstIsBase ? second.radius : first.radius;+ const length = firstPoint.distanceTo(secondPoint);+ const averageRadius = (baseRadius + tipRadius) / 2;+ const taperRatio = baseRadius > 0.000000001 ? tipRadius / baseRadius : null;+ const lengthRadiusRatio = averageRadius > 0.000000001 ? length / averageRadius : null;+ const selected = band[candidate.kind];+ const taperOutlier = taperRatio !== null && (taperRatio < selected.taper[0] || taperRatio > selected.taper[1]);+ const lengthRadiusOutlier = lengthRadiusRatio !== null && (lengthRadiusRatio < selected.lengthRadius[0] || lengthRadiusRatio > selected.lengthRadius[1]);+ return {+ node: candidate.node.name || candidate.kind,+ nodePath: pathOf(candidate.node, root),+ kind: candidate.kind,+ source: candidate.growthSource,+ lengthMeters: stable3(length),+ baseRadiusMeters: stable3(baseRadius),+ tipRadiusMeters: stable3(tipRadius),+ taperRatio: taperRatio === null ? null : stable3(taperRatio),+ lengthRadiusRatio: lengthRadiusRatio === null ? null : stable3(lengthRadiusRatio),+ expectedTaperRatio: `${selected.taper[0]}..${selected.taper[1]}`,+ expectedLengthRadiusRatio: `${selected.lengthRadius[0]}..${selected.lengthRadius[1]}`,+ taperOutlier,+ lengthRadiusOutlier+ };+}+function measureVegetationGrowth(intent, root) {+ const trusted = vegetationIntent(intent);+ const subtype = trusted?.subtype ?? "custom";+ const candidates = growthCandidates(root);+ const nodes = candidates.map((candidate) => growthNodeMeasurement(root, candidate, candidates, VEGETATION_GROWTH_BANDS_V1[subtype])).filter((value) => Boolean(value));+ return {+ schemaVersion: 1,+ subtype,+ source: measurementSource(nodes),+ trunkCount: nodes.filter((value) => value.kind === "trunk").length,+ branchCount: nodes.filter((value) => value.kind === "branch").length,+ nodes+ };+}+function evaluateVegetationGrowthQa(context) {+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))+ return [];+ const measured = measureVegetationGrowth(context.intent, context.scene);+ const findings = [];+ for (const node of measured.nodes) {+ if (node.taperOutlier) {+ findings.push(finding2(context, {+ code: "VEG_GROWTH_TAPER_OUTLIER",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${node.kind} taper measurement is outside the ${measured.subtype} measurement band.`,+ affected: { node: node.node, nodePath: node.nodePath },+ measurement: {+ name: "tipToBaseRadiusRatio",+ actual: node.taperRatio ?? "unmeasurable",+ expected: node.expectedTaperRatio,+ unit: "ratio"+ },+ viewHints: ["front", "right", "three-quarter"]+ }));+ }+ if (node.lengthRadiusOutlier) {+ findings.push(finding2(context, {+ code: "VEG_GROWTH_LENGTH_RADIUS_OUTLIER",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${node.kind} length/radius measurement is outside the ${measured.subtype} measurement band.`,+ affected: { node: node.node, nodePath: node.nodePath },+ measurement: {+ name: "lengthToAverageRadiusRatio",+ actual: node.lengthRadiusRatio ?? "unmeasurable",+ expected: node.expectedLengthRadiusRatio,+ unit: "ratio"+ },+ viewHints: ["front", "right", "three-quarter"]+ }));}}- if (issues.length > 0)- return { valid: false, issues };- return {- valid: true,- value: cloneMaterialRecipeRequestV1(value),- issues- };+ return findings;}-function cloneMaterialRecipeRequestV1(value) {+function distanceBetweenBoxes(a, b) {+ const dx = Math.max(0, a.min.x - b.max.x, b.min.x - a.max.x);+ const dy = Math.max(0, a.min.y - b.max.y, b.min.y - a.max.y);+ const dz = Math.max(0, a.min.z - b.max.z, b.min.z - a.max.z);+ return Math.hypot(dx, dy, dz);+}+function measureVegetationFoliageAttachment(root) {+ const renderables = collectRenderableBounds(root);+ const support = renderables.filter((value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS));+ const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));+ const clusters = foliage.map((value) => {+ const size = value.box.getSize(new THREE22.Vector3);+ const threshold = stable3(Math.max(0.03, Math.min(0.18, size.length() * 0.12)));+ const nearest = support.map((candidate) => ({ candidate, gap: distanceBetweenBoxes(value.box, candidate.box) })).sort((a, b) => a.gap - b.gap || (a.candidate.node.name || "").localeCompare(b.candidate.node.name || ""))[0];+ const source = roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback";+ return {+ node: value.node.name || "foliage-cluster",+ nodePath: pathOf(value.node, root),+ source,+ nearestSupport: nearest?.candidate.node.name || null,+ gapMeters: nearest ? stable3(nearest.gap) : null,+ thresholdMeters: threshold,+ detached: !nearest || nearest.gap > threshold+ };+ });return {schemaVersion: 1,- id: value.id,- ...value.overrides ? {- overrides: {- ...value.overrides,- ...value.overrides.textureResources ? { textureResources: { ...value.overrides.textureResources } } : {}- }- } : {}+ source: measurementSource(clusters),+ supportNodeCount: support.length,+ foliageClusterCount: foliage.length,+ clusters};}-function createMaterialRecipeRequestV1(id, overrides) {- const candidate = { schemaVersion: 1, id, ...overrides ? { overrides } : {} };- const result = validateMaterialRecipeRequestV1(candidate);- if (!result.valid || !result.value) {- throw new TypeError(result.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; "));- }- return result.value;+function evaluateVegetationFoliageAttachmentQa(context) {+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))+ return [];+ return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding2(context, {+ code: "VEG_FOLIAGE_DETACHED",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${cluster.node} is detached from the nearest inferred or semantic branch/twig support.`,+ affected: { node: cluster.node, nodePath: cluster.nodePath },+ measurement: {+ name: "foliageSupportGap",+ actual: cluster.gapMeters ?? "no support found",+ expected: `<=${cluster.thresholdMeters}`,+ threshold: cluster.thresholdMeters,+ unit: "m"+ },+ viewHints: ["front", "right", "three-quarter"]+ }));}-function resolveMaterialRecipeV1(value) {- const validation = validateMaterialRecipeRequestV1(value);- if (!validation.valid || !validation.value) {- throw new TypeError(validation.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; "));+function relativeTransformSignature(root, node) {+ const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);+ const scale = new THREE22.Vector3;+ const quaternion = new THREE22.Quaternion;+ matrix.decompose(new THREE22.Vector3, quaternion, scale);+ if (quaternion.w < 0)+ quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);+ const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable3(value));+ return values.join(",");+}+function measureVegetationRepetition(intent, root) {+ root.updateWorldMatrix(true, true);+ const foliage = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));+ const bySignature = new Map;+ for (const value of foliage) {+ const signature = relativeTransformSignature(root, value.node);+ const entries = bySignature.get(signature) ?? [];+ entries.push(value);+ bySignature.set(signature, entries);}- const recipe2 = MATERIAL_RECIPE_LIBRARY_V1[validation.value.id];- const over = validation.value.overrides ?? {};- const baseAlpha = over.opacity ?? recipe2.defaults.baseColorFactor[3];- const baseColorFactor = over.baseColor ? rgba(over.baseColor, baseAlpha) : Object.freeze([- recipe2.defaults.baseColorFactor[0],- recipe2.defaults.baseColorFactor[1],- recipe2.defaults.baseColorFactor[2],- baseAlpha- ]);- const emissiveIntensity = over.emissiveIntensity;- const emissiveFactor = over.emissiveColor ? rgb(over.emissiveColor, over.emissiveIntensity ?? 1) : emissiveIntensity !== undefined ? Object.freeze(recipe2.defaults.emissiveFactor.map((component) => component * emissiveIntensity)) : recipe2.defaults.emissiveFactor;- return Object.freeze({- baseColorFactor,- metallicFactor: over.metalness ?? recipe2.defaults.metallicFactor,- roughnessFactor: over.roughness ?? recipe2.defaults.roughnessFactor,- emissiveFactor,- alphaMode: recipe2.defaults.alphaMode,- ...recipe2.defaults.alphaMode === "MASK" ? { alphaCutoff: over.alphaCutoff ?? recipe2.defaults.alphaCutoff ?? 0.5 } : {},- doubleSided: over.doubleSided ?? recipe2.defaults.doubleSided,- textureResources: Object.freeze({- ...recipe2.defaults.textureResources,- ...over.textureResources ?? {}- })- });+ const identicalTransformGroups = [...bySignature.entries()].filter(([, values]) => values.length >= 3).map(([signature, values]) => ({+ signature,+ nodes: values.map((value) => value.node.name || "foliage-cluster").sort()+ })).sort((a, b) => a.signature.localeCompare(b.signature));+ const supports = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, TRUNK_PATTERNS));+ const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE22.Box3);+ const centers = foliage.map((value) => value.box.getCenter(new THREE22.Vector3));+ const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE22.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE22.Vector3);+ const radial = centers.map((value) => ({+ angle: Math.atan2(value.z - center.z, value.x - center.x),+ radius: Math.hypot(value.x - center.x, value.z - center.z)+ })).filter((value) => value.radius > 0.000001).sort((a, b) => a.angle - b.angle);+ let radialGapRangeRadians = null;+ let radialRadiusSpreadRatio = null;+ let perfectRadialLockstep = false;+ if (radial.length >= 4) {+ const gaps = radial.map((value, index) => {+ const next = radial[(index + 1) % radial.length];+ const raw = next.angle - value.angle;+ return raw > 0 ? raw : raw + Math.PI * 2;+ });+ radialGapRangeRadians = stable3(Math.max(...gaps) - Math.min(...gaps));+ const radii = radial.map((value) => value.radius);+ const meanRadius = radii.reduce((sum, value) => sum + value, 0) / radii.length;+ radialRadiusSpreadRatio = stable3((Math.max(...radii) - Math.min(...radii)) / meanRadius);+ perfectRadialLockstep = radialGapRangeRadians <= 0.02 && radialRadiusSpreadRatio <= 0.02;+ }+ const suppressedForTopiary = vegetationIntent(intent)?.canopyProfile === "topiary";+ return {+ schemaVersion: 1,+ source: measurementSource(foliage.map((value) => ({+ source: roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback"+ }))),+ clusterCount: foliage.length,+ identicalTransformGroups,+ radialGapRangeRadians,+ radialRadiusSpreadRatio,+ perfectRadialLockstep,+ suppressedForTopiary+ };}-var MATERIAL_RECIPE_IDS, MATERIAL_RECIPE_OVERRIDE_KEYS, APPROVED_TEXTURE_RESOURCE_IDS, MATERIAL_TEXTURE_SLOTS, srgbChannelToLinear2 = (value) => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4, rgba = (hex, alpha = 1) => {- const normalized = hex.replace(/^#/, "");- return Object.freeze([- srgbChannelToLinear2(Number.parseInt(normalized.slice(0, 2), 16) / 255),- srgbChannelToLinear2(Number.parseInt(normalized.slice(2, 4), 16) / 255),- srgbChannelToLinear2(Number.parseInt(normalized.slice(4, 6), 16) / 255),- alpha- ]);-}, rgb = (hex, intensity = 1) => {- const color2 = rgba(hex);- return Object.freeze([- color2[0] * intensity,- color2[1] * intensity,- color2[2] * intensity- ]);-}, defaults = (baseColor, roughnessFactor, metallicFactor = 0, over = {}) => Object.freeze({- baseColorFactor: rgba(baseColor),- metallicFactor,- roughnessFactor,- emissiveFactor: Object.freeze([0, 0, 0]),- alphaMode: "OPAQUE",- doubleSided: false,- textureResources: Object.freeze({}),- ...over-}), commonSurface, descriptor = (value) => Object.freeze({- schemaVersion: 1,- version: 1,- portable: true,- gltfMaterialModel: "pbrMetallicRoughness",- ...value-}), MATERIAL_RECIPE_LIBRARY_V1, APPROVED_TEXTURE_RESOURCES_V1, isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), recipeId = (value) => typeof value === "string" && MATERIAL_RECIPE_IDS.includes(value), resourceId = (value) => typeof value === "string" && APPROVED_TEXTURE_RESOURCE_IDS.includes(value), finiteUnit = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1, hexColor = (value) => typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value);-var init_material_recipes = __esm(() => {- init_material_texture_library_generated();- MATERIAL_RECIPE_IDS = [- "kiln.material.bark.v1",- "kiln.material.leaf.v1",- "kiln.material.wood.v1",- "kiln.material.stone.v1",- "kiln.material.rubber.v1",- "kiln.material.painted-metal.v1",- "kiln.material.cloth.v1",- "kiln.material.skin.v1",- "kiln.material.glass.v1",- "kiln.material.emissive.v1"- ];- MATERIAL_RECIPE_OVERRIDE_KEYS = [- "baseColor",- "roughness",- "metalness",- "opacity",- "alphaCutoff",- "doubleSided",- "emissiveColor",- "emissiveIntensity",- "textureResources"- ];- APPROVED_TEXTURE_RESOURCE_IDS = [- "kiln.texture.bark-albedo.v1",- "kiln.texture.leaf-mask-albedo.v1",- "kiln.texture.neutral-normal.v1",- "kiln.texture.neutral-metallic-roughness.v1",- "kiln.texture.emissive-grid.v1",- ...PRODUCTION_TEXTURE_RESOURCE_IDS- ];- MATERIAL_TEXTURE_SLOTS = [- "baseColor",- "normal",- "metallicRoughness",- "emissive",- "occlusion"+function evaluateVegetationRepetitionQa(context) {+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))+ return [];+ const measured = measureVegetationRepetition(context.intent, context.scene);+ if (measured.suppressedForTopiary)+ return [];+ const findings = measured.identicalTransformGroups.map((group) => finding2(context, {+ code: "VEG_CLUSTER_TRANSFORM_REPEAT",+ disposition: "warn",+ dimension: "visualQuality",+ message: `${group.nodes.length} foliage clusters use an identical scale/rotation signature.`,+ affected: { node: group.nodes[0], nodePath: group.nodes.join(",") },+ measurement: {+ name: "identicalClusterTransformCount",+ actual: group.nodes.length,+ expected: "<3 outside formal topiary intent"+ },+ viewHints: ["front", "right", "top", "three-quarter"]+ }));+ if (measured.perfectRadialLockstep) {+ findings.push(finding2(context, {+ code: "VEG_CLUSTER_RADIAL_LOCKSTEP",+ disposition: "warn",+ dimension: "visualQuality",+ message: "Foliage clusters form a perfect equal-radius, equal-angle radial sequence.",+ measurement: {+ name: "radialGapAndRadiusSpread",+ actual: `${measured.radialGapRangeRadians},${measured.radialRadiusSpreadRatio}`,+ expected: "angle gap range >0.02 or radius spread ratio >0.02",+ unit: "ratio"+ },+ viewHints: ["top", "three-quarter"]+ }));+ }+ return findings;+}+function measureVegetationCanopy(intent, root) {+ const profile = vegetationIntent(intent)?.canopyProfile ?? "broadleaf";+ const renderables = collectRenderableBounds(root);+ const canopy = renderables.filter((value) => matchesAny(value, CANOPY_PATTERNS));+ const trunk = renderables.filter((value) => matchesAny(value, TRUNK_PATTERNS));+ const semanticCanopy = canopy.some((value) => value.roles.length > 0);+ const source = canopy.length === 0 ? "none" : semanticCanopy ? "semantic" : "fallback";+ const canopyBoxes = canopy.map((value) => value.box);+ const trunkVolume = unionVolume(trunk.map((value) => value.box));+ const ratio = trunkVolume > 0.000000001 ? unionVolume(canopyBoxes) / trunkVolume : null;+ return {+ schemaVersion: 1,+ profile,+ source,+ canopyNodeCount: canopy.length,+ trunkNodeCount: trunk.length,+ frontOccupancy: projectedOccupancy(canopyBoxes, [2, 1]),+ sideOccupancy: projectedOccupancy(canopyBoxes, [0, 1]),+ topOccupancy: projectedOccupancy(canopyBoxes, [0, 2]),+ canopyToTrunkVolumeRatio: ratio === null ? null : stable3(ratio)+ };+}+function evaluateVegetationCanopyQa(context) {+ const trusted = vegetationIntent(context.intent);+ if (!trusted || !(context.scene instanceof THREE22.Object3D))+ return [];+ const measurements = measureVegetationCanopy(context.intent, context.scene);+ const bands = PROFILE_BANDS[measurements.profile];+ const sparseFactor = trusted.growthState === "sparse" ? 0.55 : 1;+ const values = [+ ["FRONT", "frontOccupancy", measurements.frontOccupancy, bands.occupancy.front, "front"],+ ["SIDE", "sideOccupancy", measurements.sideOccupancy, bands.occupancy.side, "right"],+ ["TOP", "topOccupancy", measurements.topOccupancy, bands.occupancy.top, "top"]];- commonSurface = Object.freeze([- "baseColor",- "roughness",- "metalness",- "doubleSided",- "textureResources"- ]);- MATERIAL_RECIPE_LIBRARY_V1 = Object.freeze({- "kiln.material.bark.v1": descriptor({- id: "kiln.material.bark.v1",- name: "Bark",- description: "Rough, nonmetal tree bark with optional approved albedo and normal resources.",- allowedOverrides: commonSurface,- defaults: defaults("#6b4426", 0.93)- }),- "kiln.material.leaf.v1": descriptor({- id: "kiln.material.leaf.v1",- name: "Leaf",- description: "Alpha-tested, double-sided foliage using glTF MASK rather than blending.",- allowedOverrides: Object.freeze([- "baseColor",- "roughness",- "alphaCutoff",- "doubleSided",- "textureResources"- ]),- defaults: defaults("#3f7f3a", 0.86, 0, {- alphaMode: "MASK",- alphaCutoff: 0.5,- doubleSided: true- })- }),- "kiln.material.wood.v1": descriptor({- id: "kiln.material.wood.v1",- name: "Wood",- description: "Portable nonmetal wood with a warm authored base color.",- allowedOverrides: commonSurface,- defaults: defaults("#9a6a3a", 0.78)- }),- "kiln.material.stone.v1": descriptor({- id: "kiln.material.stone.v1",- name: "Stone",- description: "Dry rough stone with no runtime shader dependency.",- allowedOverrides: commonSurface,- defaults: defaults("#7d7a74", 0.95)- }),- "kiln.material.rubber.v1": descriptor({- id: "kiln.material.rubber.v1",- name: "Rubber",- description: "Dark, high-roughness rubber for tires, grips, and seals.",- allowedOverrides: commonSurface,- defaults: defaults("#202124", 0.88)- }),- "kiln.material.painted-metal.v1": descriptor({- id: "kiln.material.painted-metal.v1",- name: "Painted metal",- description: "Coated metal with restrained metallic response and a durable painted finish.",- allowedOverrides: commonSurface,- defaults: defaults("#b33a32", 0.38, 0.18)- }),- "kiln.material.cloth.v1": descriptor({- id: "kiln.material.cloth.v1",- name: "Cloth",- description: "Very rough, nonmetal woven cloth represented with core glTF PBR.",- allowedOverrides: commonSurface,- defaults: defaults("#6f7583", 1)- }),- "kiln.material.skin.v1": descriptor({- id: "kiln.material.skin.v1",- name: "Skin",- description: "Portable skin baseline without nonstandard subsurface extensions.",- allowedOverrides: Object.freeze(["baseColor", "roughness", "doubleSided"]),- defaults: defaults("#b87962", 0.62)- }),- "kiln.material.glass.v1": descriptor({- id: "kiln.material.glass.v1",- name: "Glass",- description: "Portable alpha-blended glass fallback using core glTF fields only.",- allowedOverrides: Object.freeze(["baseColor", "roughness", "opacity", "doubleSided"]),- defaults: defaults("#a9d8e8", 0.12, 0, {- baseColorFactor: rgba("#a9d8e8", 0.32),- alphaMode: "BLEND",- doubleSided: true- })- }),- "kiln.material.emissive.v1": descriptor({- id: "kiln.material.emissive.v1",- name: "Emissive",- description: "Core glTF emissive material with intensity baked into emissiveFactor.",- allowedOverrides: Object.freeze([- "baseColor",- "roughness",- "doubleSided",- "emissiveColor",- "emissiveIntensity",- "textureResources"- ]),- defaults: defaults("#3a2410", 0.5, 0, {- emissiveFactor: rgb("#ff8a22", 1)- })- })- });- APPROVED_TEXTURE_RESOURCES_V1 = Object.freeze({- "kiln.texture.bark-albedo.v1": Object.freeze({- schemaVersion: 1,- id: "kiln.texture.bark-albedo.v1",- version: 1,- label: "Bark albedo reference",- usage: "albedo",- colorSpace: "srgb",- mime: "image/png",- contentHash: "ec74fd42fe317f578018a13a65d81a726e9baeade068ae016cff30c15507017f",- delivery: "embedded",- quality: "placeholder",- byteLength: 100,- license: Object.freeze({- spdx: "CC0-1.0",- attribution: "",- source: "authored in-repo"- }),- allowedSlots: Object.freeze(["baseColor"]),- recipeIds: Object.freeze(["kiln.material.bark.v1", "kiln.material.wood.v1"])- }),- "kiln.texture.leaf-mask-albedo.v1": Object.freeze({- schemaVersion: 1,- id: "kiln.texture.leaf-mask-albedo.v1",- version: 1,- label: "Leaf alpha-mask albedo reference",- usage: "albedo",- colorSpace: "srgb",- mime: "image/png",- contentHash: "ae9ad7f5389529a42fd9e63cb16aa7dc2c803739953242422b0ccc8003bd827c",- delivery: "embedded",- quality: "placeholder",- byteLength: 119,- license: Object.freeze({- spdx: "CC0-1.0",- attribution: "",- source: "authored in-repo"- }),- allowedSlots: Object.freeze(["baseColor"]),- recipeIds: Object.freeze(["kiln.material.leaf.v1"])- }),- "kiln.texture.neutral-normal.v1": Object.freeze({- schemaVersion: 1,- id: "kiln.texture.neutral-normal.v1",- version: 1,- label: "Neutral tangent-space normal",- usage: "normal",- colorSpace: "linear",- mime: "image/png",- contentHash: "2be025139faed13fb12ac50101f7d91f8a758ce6a668104a7e8003eccdab7db7",- delivery: "embedded",- quality: "placeholder",- byteLength: 95,- license: Object.freeze({- spdx: "CC0-1.0",- attribution: "",- source: "authored in-repo"- }),- allowedSlots: Object.freeze(["normal"]),- recipeIds: Object.freeze([- "kiln.material.bark.v1",- "kiln.material.wood.v1",- "kiln.material.stone.v1",- "kiln.material.rubber.v1",- "kiln.material.painted-metal.v1",- "kiln.material.cloth.v1"- ])- }),- "kiln.texture.neutral-metallic-roughness.v1": Object.freeze({- schemaVersion: 1,- id: "kiln.texture.neutral-metallic-roughness.v1",- version: 1,- label: "Packed roughness-metalness reference",- usage: "metallicRoughness",- colorSpace: "linear",- mime: "image/png",- contentHash: "5e03d1e2863800c5f1a88411dd4447ccc0ec8470232129d8682db8f6ea76ad52",- delivery: "embedded",- quality: "placeholder",- byteLength: 94,- license: Object.freeze({- spdx: "CC0-1.0",- attribution: "",- source: "authored in-repo"- }),- allowedSlots: Object.freeze(["metallicRoughness"]),- recipeIds: Object.freeze([- "kiln.material.rubber.v1",- "kiln.material.painted-metal.v1"- ])- }),- "kiln.texture.emissive-grid.v1": Object.freeze({- schemaVersion: 1,- id: "kiln.texture.emissive-grid.v1",- version: 1,- label: "Emissive grid reference",- usage: "emissive",- colorSpace: "srgb",- mime: "image/png",- contentHash: "a0b2f4e243ec0ec914b80d4998cf4624ff68181aafc4b97a6bafa765a41e4814",- delivery: "embedded",- quality: "placeholder",- byteLength: 100,- license: Object.freeze({- spdx: "CC0-1.0",- attribution: "",- source: "authored in-repo"- }),- allowedSlots: Object.freeze(["emissive"]),- recipeIds: Object.freeze(["kiln.material.emissive.v1"])- }),- ...PRODUCTION_TEXTURE_RESOURCE_DESCRIPTORS_V1+ const findings = [];+ if (measurements.canopyNodeCount === 0 && measurements.profile !== "bare/dead") {+ findings.push(finding2(context, {+ code: "VEG_CANOPY_MISSING",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `The ${trusted.subtype} profile resolved no semantic or inferred canopy renderables.`,+ measurement: { name: "canopyNodeCount", actual: 0, expected: ">=1" },+ viewHints: ["front", "right", "top"]+ }));+ return findings;+ }+ for (const [suffix, name, actual, [minimum, maximum], view] of values) {+ const adjustedMinimum = minimum * sparseFactor;+ if (actual >= adjustedMinimum && actual <= maximum)+ continue;+ findings.push(finding2(context, {+ code: `VEG_CANOPY_OCCUPANCY_${suffix}`,+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${measurements.profile} ${name} is outside its measured ${trusted.growthState} profile band.`,+ measurement: {+ name,+ actual,+ expected: `${stable3(adjustedMinimum)}..${maximum}`,+ threshold: adjustedMinimum,+ unit: "ratio"+ },+ viewHints: [view, "three-quarter"]+ }));+ }+ const ratio = measurements.canopyToTrunkVolumeRatio;+ if (ratio !== null && (ratio < bands.ratio[0] || ratio > bands.ratio[1])) {+ findings.push(finding2(context, {+ code: "VEG_CANOPY_TRUNK_RATIO",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${measurements.profile} canopy-to-trunk volume ratio is outside its subtype band.`,+ measurement: {+ name: "canopyToTrunkVolumeRatio",+ actual: ratio,+ expected: `${bands.ratio[0]}..${bands.ratio[1]}`,+ threshold: bands.ratio[0],+ unit: "ratio"+ },+ viewHints: ["front", "right", "top"]+ }));+ }+ return findings;+}+function materialValue(material) {+ if (!(material instanceof THREE22.MeshStandardMaterial) && !(material instanceof THREE22.MeshBasicMaterial)) {+ return;+ }+ const color = material.color;+ return 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;+}+function measureVegetationFoliageMaterials(intent, root) {+ const values = [];+ let foliageNodeCount = 0;+ root.traverse((node) => {+ if (!(node instanceof THREE22.Mesh))+ return;+ const bounds = {+ node,+ box: new THREE22.Box3,+ roles: rolesOf(node),+ source: rolesOf(node).length > 0 ? "semantic" : "fallback"+ };+ if (!matchesAny(bounds, CANOPY_PATTERNS))+ return;+ foliageNodeCount++;+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ for (const material of materials) {+ const value = materialValue(material);+ if (value !== undefined)+ values.push(value);+ }});-});--// src/material-resources.ts-import { createHash as createHash4 } from "node:crypto";-function provenance(descriptor2, hash3) {+ const buckets = new Set(values.map((value) => Math.round(value * 20) / 20));+ const valueRange = values.length > 0 ? Math.max(...values) - Math.min(...values) : 0;+ const optimized = intent.material.mode === "flatOptimized";return {schemaVersion: 1,- resourceId: descriptor2.id,- contentHash: hash3,- hashAlgorithm: "sha256",- usage: descriptor2.usage,- colorSpace: descriptor2.colorSpace,- resourceVersion: descriptor2.version,- recipeVersion: 1,- delivery: descriptor2.delivery+ mode: intent.material.mode,+ foliageNodeCount,+ valueRoleCount: buckets.size,+ valueRange: stable3(valueRange),+ coherent: optimized ? buckets.size <= 1 : buckets.size >= 2 && buckets.size <= 6 && valueRange >= 0.03};}-function readPngDimensions(descriptor2, bytes) {- const signature = [137, 80, 78, 71, 13, 10, 26, 10];- if (bytes.byteLength < 24 || !signature.every((value, index) => bytes[index] === value) || String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR") {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "declared image/png bytes do not have a valid PNG signature and IHDR format");- }- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);- return { width: view.getUint32(16, false), height: view.getUint32(20, false) };+function evaluateVegetationMaterialQa(context) {+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))+ return [];+ const measured = measureVegetationFoliageMaterials(context.intent, context.scene);+ if (measured.foliageNodeCount === 0 || measured.coherent)+ return [];+ const optimized = measured.mode === "flatOptimized";+ return [+ finding2(context, {+ code: "VEG_FOLIAGE_VALUE_ROLES",+ disposition: "warn",+ dimension: "visualQuality",+ message: optimized ? "Optimized vegetation should retain one coherent foliage value role." : "Rich organic vegetation should use two to six restrained foliage value roles with visible value separation.",+ measurement: {+ name: "foliageValueRoles",+ actual: `${measured.valueRoleCount} roles; range ${measured.valueRange}`,+ expected: optimized ? "1 role" : "2..6 roles; range >=0.03"+ },+ viewHints: ["front", "three-quarter"]+ })+ ];}-function verifyResourcePayload(descriptor2, payload) {- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host payload must be { bytes, mime }");- }- const keys = Object.keys(payload).sort();- if (keys.length !== 2 || keys[0] !== "bytes" || keys[1] !== "mime") {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host payload must contain only bytes and MIME");- }- if (!(payload.bytes instanceof Uint8Array)) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, "host bytes must be Uint8Array");- }- if (payload.mime !== descriptor2.mime) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `host MIME ${String(payload.mime)} does not match approved ${descriptor2.mime}`);- }- const bytes = payload.bytes;- if (bytes.byteLength > TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `encoded-byte limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxEncodedBytes}; received ${bytes.byteLength}`);- }- if (bytes.byteLength !== descriptor2.byteLength) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `expected ${descriptor2.byteLength} bytes, received ${bytes.byteLength}`);- }- const { width, height } = readPngDimensions(descriptor2, bytes);- if (width < 1 || height < 1 || width > TEXTURE_RESOLVER_LIMITS_V1.maxWidth || height > TEXTURE_RESOLVER_LIMITS_V1.maxHeight) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `dimension limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxWidth}x${TEXTURE_RESOLVER_LIMITS_V1.maxHeight}; received ${width}x${height}`);- }- const pixels = width * height;- if (!Number.isSafeInteger(pixels) || pixels > TEXTURE_RESOLVER_LIMITS_V1.maxPixels) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`);- }- const hash3 = sha256(bytes);- if (hash3 !== descriptor2.contentHash) {- throw new ApprovedTextureResourceUnavailableError(descriptor2.id, `content hash ${hash3} does not match the pinned ${descriptor2.contentHash}`);+function evaluateVegetationAdvisoryQa(context) {+ return [+ ...evaluateVegetationScopeQa(context),+ ...evaluateVegetationGrowthQa(context),+ ...evaluateVegetationCanopyQa(context),+ ...evaluateVegetationFoliageAttachmentQa(context),+ ...evaluateVegetationRepetitionQa(context),+ ...evaluateVegetationMaterialQa(context)+ ];+}+var PROFILE2 = "vegetation.semantic", VEGETATION_CONTACT_TOLERANCE_METERS = 0.02, RASTER_SIZE = 48, stable3 = (value) => Math.round(value * 1e6) / 1e6, CLUTTER_NAME, CANOPY_PATTERNS, TRUNK_PATTERNS, BRANCH_PATTERNS, VEGETATION_GROWTH_BANDS_V1, PROFILE_BANDS, VEGETATION_CONTACT_QA_RULE, VEGETATION_ADVISORY_QA_RULE, VEGETATION_QA_RULES;+var init_vegetation = __esm(() => {+ init_contracts();+ init_registry();+ CLUTTER_NAME = /(?:^|[._ -])(?:terrain|soil|dirt|mound|rock|stone|pot|planter|grass[._ -]?skirt|base[._ -]?(?:disk|plate))(?:$|[._ -])/i;+ CANOPY_PATTERNS = [/(?:^|[._ -])(?:canopy|foliage|leaf|leaves|needle|frond)(?:$|[._ -])/i];+ TRUNK_PATTERNS = [/(?:^|[._ -])(?:trunk|stem|stalk|branch-primary)(?:$|[._ -])/i];+ BRANCH_PATTERNS = [+ /(?:^|[._ -])(?:branch|twig|bough|limb)(?:$|[._ -])/i,+ /^vegetation\.branch(?:\.|$)/i+ ];+ VEGETATION_GROWTH_BANDS_V1 = Object.freeze({+ tree: {+ trunk: { taper: [0.35, 1.05], lengthRadius: [4, 80] },+ branch: { taper: [0.12, 1.05], lengthRadius: [4, 100] }+ },+ conifer: {+ trunk: { taper: [0.25, 1.05], lengthRadius: [6, 110] },+ branch: { taper: [0.1, 1.05], lengthRadius: [5, 140] }+ },+ shrub: {+ trunk: { taper: [0.25, 1.1], lengthRadius: [2, 65] },+ branch: { taper: [0.1, 1.1], lengthRadius: [2, 80] }+ },+ grass: {+ trunk: { taper: [0.05, 1.15], lengthRadius: [6, 260] },+ branch: { taper: [0.05, 1.15], lengthRadius: [5, 260] }+ },+ "frond/palm": {+ trunk: { taper: [0.35, 1.05], lengthRadius: [6, 140] },+ branch: { taper: [0.04, 1.1], lengthRadius: [8, 300] }+ },+ vine: {+ trunk: { taper: [0.1, 1.15], lengthRadius: [8, 320] },+ branch: { taper: [0.04, 1.15], lengthRadius: [8, 360] }+ },+ "crop/flower": {+ trunk: { taper: [0.15, 1.1], lengthRadius: [5, 220] },+ branch: { taper: [0.05, 1.15], lengthRadius: [4, 240] }+ },+ succulent: {+ trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },+ branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] }+ },+ fungus: {+ trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },+ branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] }+ },+ aquatic: {+ trunk: { taper: [0.08, 1.15], lengthRadius: [4, 260] },+ branch: { taper: [0.04, 1.15], lengthRadius: [4, 300] }+ },+ "bare/dead": {+ trunk: { taper: [0.25, 1.05], lengthRadius: [4, 100] },+ branch: { taper: [0.08, 1.05], lengthRadius: [3, 140] }+ },+ custom: {+ trunk: { taper: [0.05, 1.25], lengthRadius: [1.2, 320] },+ branch: { taper: [0.03, 1.25], lengthRadius: [1.2, 360] }+ }+ });+ PROFILE_BANDS = Object.freeze({+ broadleaf: {+ occupancy: { front: [0.4, 0.99], side: [0.4, 0.99], top: [0.32, 0.99] },+ ratio: [1.5, 120]+ },+ conifer: {+ occupancy: { front: [0.32, 0.97], side: [0.32, 0.97], top: [0.2, 0.95] },+ ratio: [1, 100]+ },+ topiary: {+ occupancy: { front: [0.62, 1], side: [0.62, 1], top: [0.58, 1] },+ ratio: [1, 120]+ },+ "bare/dead": {+ occupancy: { front: [0, 0.08], side: [0, 0.08], top: [0, 0.08] },+ ratio: [0, 0.2]+ }+ });+ VEGETATION_CONTACT_QA_RULE = {+ id: "VEGETATION_CONTACT_PROFILE",+ profile: PROFILE2,+ scope: { kind: "category", category: "vegetation" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("vegetation-contact-v1", "src/qa/vegetation.test.ts", "8ad8f1753fc76e5e1b0114ad7d7f2c6c02c6f1c60953727027219424422a8ac4"),+ defaultMode: "enforce",+ evaluate: evaluateVegetationContactQa+ };+ VEGETATION_ADVISORY_QA_RULE = {+ id: "VEGETATION_ADVISORY_PROFILE",+ profile: "vegetation.advisory",+ scope: { kind: "category", category: "vegetation" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: evaluateVegetationAdvisoryQa+ };+ VEGETATION_QA_RULES = [+ VEGETATION_CONTACT_QA_RULE,+ VEGETATION_ADVISORY_QA_RULE+ ];+});++// src/qa/prop.ts+import * as THREE23 from "three";+function finding3(context, value) {+ return { ...value, profile: context.intent.qaProfile || PROFILE3 };+}+function rolesOf2(node) {+ return readSemanticMetadataV1(node)?.roles ?? [];+}+function nodePath2(root, node) {+ const names = [];+ let cursor = node;+ while (cursor) {+ names.push(cursor.name || cursor.type);+ if (cursor === root)+ break;+ cursor = cursor.parent;}- return hash3;+ return names.reverse().join("/");}--class ApprovedTextureResourceCache {- #bytesByHash = new Map;- #hashById = new Map;- #textureByVariant = new Map;- #pendingById = new Map;- #registry;- #resolver;- #resolverDeadlineMs;- constructor(options = {}) {- this.#resolver = options.resolver;- this.#registry = options.registry ?? APPROVED_TEXTURE_RESOURCES_V1;- const deadline = options.resolverDeadlineMs ?? TEXTURE_RESOLVER_LIMITS_V1.defaultDeadlineMs;- if (!Number.isFinite(deadline) || deadline < 1 || deadline > TEXTURE_RESOLVER_LIMITS_V1.maxDeadlineMs) {- throw new RangeError(`resolverDeadlineMs must be in [1,${TEXTURE_RESOLVER_LIMITS_V1.maxDeadlineMs}]`);+function transformedBox(source, transform) {+ const result = new THREE23.Box3;+ for (const x of [source.min.x, source.max.x]) {+ for (const y of [source.min.y, source.max.y]) {+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE23.Vector3(x, y, z).applyMatrix4(transform));+ }}- this.#resolverDeadlineMs = deadline;- }- setResolver(resolver) {- const previous = this.#resolver;- this.#resolver = resolver;- return previous;- }- descriptor(id) {- if (!isApprovedId(id))- throw new RangeError(`Unsupported approved texture resource ID ${id}.`);- return this.#registry[id];- }- available(id) {- if (!isApprovedId(id))- return false;- return this.#registry[id].delivery === "embedded" || this.#resolver !== undefined;}- #cacheBytes(id, hash3, bytes) {- let canonical2 = this.#bytesByHash.get(hash3);- if (!canonical2) {- canonical2 = bytes;- this.#bytesByHash.set(hash3, canonical2);+ return result;+}+function collectParts(root) {+ root.updateWorldMatrix(true, true);+ const rootInverse = root.matrixWorld.clone().invert();+ const result = [];+ root.traverse((node) => {+ const roles = rolesOf2(node);+ const renderable = node instanceof THREE23.Mesh;+ let box;+ if (renderable && node.geometry instanceof THREE23.BufferGeometry) {+ node.geometry.computeBoundingBox();+ if (node.geometry.boundingBox) {+ box = transformedBox(node.geometry.boundingBox, rootInverse.clone().multiply(node.matrixWorld));+ }+ } else if (roles.length > 0) {+ box = transformedBox(new THREE23.Box3(new THREE23.Vector3(-0.5, -0.5, -0.5), new THREE23.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));}- this.#hashById.set(id, hash3);- return canonical2;- }- #resolution(id, hash3) {- const canonical2 = this.#bytesByHash.get(hash3);- if (!canonical2)- throw new Error(`Approved resource cache lost content ${hash3}.`);- return {- descriptor: this.#registry[id],- bytes: canonical2.slice(),- provenance: provenance(this.#registry[id], hash3)- };+ if (box?.isEmpty())+ box = undefined;+ result.push({ node, roles, ...box ? { box } : {}, renderable });+ });+ return result;+}+function descendantOf(node, ancestor) {+ let cursor = node;+ while (cursor) {+ if (cursor === ancestor)+ return true;+ cursor = cursor.parent;}- resolve(id) {- if (!isApprovedId(id))- throw new RangeError(`Unsupported approved texture resource ID ${id}.`);- const hash3 = this.#hashById.get(id);- if (hash3)- return this.#resolution(id, hash3);- const descriptor2 = this.#registry[id];- if (descriptor2.delivery !== "embedded") {- throw new ApprovedTextureResourceUnavailableError(id, "it is delivered at runtime; use resolveAsync() or load()");+ return false;+}+function boxesOverlap(a, b, inset = 0) {+ return a.min.x < b.max.x - inset && a.max.x > b.min.x + inset && a.min.y < b.max.y - inset && a.max.y > b.min.y + inset && a.min.z < b.max.z - inset && a.max.z > b.min.z + inset;+}+function motionAssemblies(parts) {+ const values = new Map;+ const get = (kind, id) => {+ const key = `${kind}:${id}`;+ let value = values.get(key);+ if (!value) {+ value = { kind, id };+ values.set(key, value);}- const decoded = bytesFromBase64(EMBEDDED_RESOURCE_BASE64[id]);- this.#cacheBytes(id, verifyResourcePayload(descriptor2, { bytes: decoded, mime: descriptor2.mime }), decoded);- return this.#resolution(id, this.#hashById.get(id));- }- async resolveAsync(id) {- if (!isApprovedId(id))- throw new RangeError(`Unsupported approved texture resource ID ${id}.`);- const hash3 = this.#hashById.get(id);- if (hash3)- return this.#resolution(id, hash3);- if (this.#registry[id].delivery === "embedded")- return this.resolve(id);- let pending = this.#pendingById.get(id);- if (!pending) {- const descriptor2 = this.#registry[id];- const resolver = this.#resolver;- pending = (async () => {- if (!resolver) {- throw new ApprovedTextureResourceUnavailableError(id, "no runtime texture resolver is registered in this environment");- }- const controller = new AbortController;- let timer;- const timeout = new Promise((_resolve, reject) => {- timer = setTimeout(() => {- controller.abort();- reject(new ApprovedTextureResourceUnavailableError(id, `host resolver deadline exceeded after ${this.#resolverDeadlineMs}ms`));- }, this.#resolverDeadlineMs);- });- let payload;- try {- payload = await Promise.race([- Promise.resolve().then(() => resolver(descriptor2, Object.freeze({- signal: controller.signal,- deadlineMs: this.#resolverDeadlineMs- }))),- timeout- ]);- } finally {- if (timer !== undefined)- clearTimeout(timer);- }- this.#cacheBytes(id, verifyResourcePayload(descriptor2, payload), payload.bytes);- return this.#resolution(id, this.#hashById.get(id));- })().finally(() => {- this.#pendingById.delete(id);- });- this.#pendingById.set(id, pending);+ return value;+ };+ for (const part of parts) {+ for (const role of part.roles) {+ const pivot = /^prop\.pivot\.(hinge|slider|spinner)\.([^.]+)$/.exec(role);+ if (pivot)+ get(pivot[1], pivot[2]).pivot = part;+ const moving = /^prop\.motion\.(hinge|slider|spinner)\.([^.]+)$/.exec(role);+ if (moving)+ get(moving[1], moving[2]).moving = part;+ const clearance = /^prop\.clearance\.(?:hinge\.|slider\.|spinner\.)?([^.]+)$/.exec(role);+ if (clearance) {+ const direct = Array.from(values.values()).find((value) => value.id === clearance[1]);+ if (direct)+ direct.clearance = part;+ }}- return pending;}- async load(id) {- const resolved2 = await this.resolveAsync(id);- const variantKey = [- resolved2.provenance.contentHash,- resolved2.provenance.usage,- resolved2.provenance.colorSpace- ].join(":");- let pending = this.#textureByVariant.get(variantKey);- if (!pending) {- pending = loadTexture(resolved2.bytes, {- usage: resolved2.provenance.usage,- name: id- }).then((texture) => {- const metadata = texture.userData["kilnTexture"];- texture.userData["kilnTexture"] = {- ...metadata,- approvedResource: resolved2.provenance- };- return texture;- });- this.#textureByVariant.set(variantKey, pending);+ for (const part of parts) {+ for (const role of part.roles) {+ const match = /^prop\.clearance\.(?:(hinge|slider|spinner)\.)?([^.]+)$/.exec(role);+ if (!match)+ continue;+ if (match[1])+ get(match[1], match[2]).clearance = part;+ else {+ const candidates = Array.from(values.values()).filter((value) => value.id === match[2]);+ if (candidates.length === 1)+ candidates[0].clearance = part;+ }}- return { ...resolved2, texture: await pending };- }- stats() {- return {- approvedIdsResolved: this.#hashById.size,- uniqueContentHashes: this.#bytesByHash.size,- decodedTextureVariants: this.#textureByVariant.size,- encodedBytes: [...this.#bytesByHash.values()].reduce((sum, bytes) => sum + bytes.byteLength, 0)- };}+ return Array.from(values.values()).sort((a, b) => `${a.kind}:${a.id}`.localeCompare(`${b.kind}:${b.id}`));}-function readMaterialResourceProvenance(texture) {- const metadata = texture.userData["kilnTexture"];- return metadata?.approvedResource;+function hasMotionAxis(part) {+ const frames = readSemanticMetadataV1(part.node)?.frames ?? [];+ return frames.some((frame) => /^(?:prop\.)?(?:motion-)?axis\.[+-]?[xyz]$/.test(frame.id));}-function sceneNeedsPbrShading(root) {- let needs = false;- root.traverse((node) => {- if (needs)- return;- const material = node.material;- const materials = Array.isArray(material) ? material : material ? [material] : [];- for (const item of materials) {- if (materialTextures2(item).length > 0) {- needs = true;- return;- }- const metalness = item.metalness;- if (typeof metalness === "number" && metalness > 0) {- needs = true;- return;+function usesExplicitLegacyProfile(context) {+ return context.intent.qaProfile === "prop.legacy" || context.intent.qaProfile === "prop.legacy-control";+}+function allowedClearanceContactRoles(assembly) {+ const result = new Set;+ for (const part of [assembly.pivot, assembly.clearance]) {+ const metadata = part ? readSemanticMetadataV1(part.node) : undefined;+ for (const relationship of metadata?.relationships ?? []) {+ if (relationship.targetType === "role" && /^(?:mountedTo|allowsContact|allowsClearanceContact)$/.test(relationship.kind) && /^prop\.articulation\.support\.[^.]+$/.test(relationship.target)) {+ result.add(relationship.target);}}- });- return needs;-}-function collectMaterialResourceProvenance(root) {- const records = new Map;- root.traverse((node) => {- const material = node.material;- const materials = Array.isArray(material) ? material : material ? [material] : [];- for (const item of materials) {- for (const texture of materialTextures2(item)) {- const record4 = readMaterialResourceProvenance(texture);- if (record4)- records.set(`${record4.resourceId}:${record4.contentHash}:${record4.usage}`, record4);- }+ }+ return result;+}+function legacyArticulationEvidence(context, root) {+ const joints = [];+ root.traverse((node) => {+ if (/^(?:Joint|Pivot)[_.-]/i.test(node.name))+ joints.push(node.name);+ });+ if (joints.length === 0)+ return false;+ const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE23.AnimationClip);+ if ((context.intent.animation?.clips.length ?? 0) === 0 && clips.length === 0)+ return true;+ const targets = new Set(clips.flatMap((clip) => clip.tracks.map((track) => track.name.split(".")[0] ?? "")));+ return joints.some((joint) => targets.has(joint));+}+function evaluatePropArticulationQa(context) {+ if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE23.Object3D)) {+ return [];+ }+ const root = context.scene;+ const parts = collectParts(root);+ const assemblies = motionAssemblies(parts);+ if (assemblies.length === 0) {+ if (usesExplicitLegacyProfile(context) && legacyArticulationEvidence(context, root))+ return [];+ return [+ finding3(context, {+ code: "PROP_ARTICULATION_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "articulated=true requires a semantic hinge, slider, or spinner assembly with a real pivot and moving subtree.",+ affected: { node: root.name || "prop-root" },+ measurement: { name: "motionAssemblyCount", actual: 0, expected: ">=1", threshold: 1 },+ viewHints: ["front", "right", "top"],+ repairText: "Create prop.pivot.<hinge|slider|spinner>.<id>, parent only prop.motion.<kind>.<id> beneath it, and add an axis frame plus prop.clearance.<id>."+ })+ ];+ }+ const findings = [];+ for (const assembly of assemblies) {+ const label = `${assembly.kind}.${assembly.id}`;+ if (!assembly.pivot) {+ findings.push(finding3(context, {+ code: "PROP_ARTICULATION_PIVOT_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Motion assembly ${label} has no semantic pivot.`,+ affected: { node: assembly.moving?.node.name || label },+ measurement: { name: "pivotCount", actual: 0, expected: 1, threshold: 1 },+ viewHints: ["right", "top"],+ repairText: `Add prop.pivot.${label} at the physical hinge/rail/axle origin.`+ }));+ continue;+ }+ if (!hasMotionAxis(assembly.pivot)) {+ findings.push(finding3(context, {+ code: "PROP_ARTICULATION_AXIS_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Motion pivot ${label} has no declared local axis frame.`,+ affected: {+ node: assembly.pivot.node.name || label,+ nodePath: nodePath2(root, assembly.pivot.node)+ },+ measurement: { name: "motionAxisFrameCount", actual: 0, expected: 1, threshold: 1 },+ viewHints: ["right", "top"],+ repairText: `Add a normalized axis.+x, axis.+y, or axis.+z frame to prop.pivot.${label}.`+ }));}- });- return [...records.values()].sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));-}-var TEXTURE_RESOLVER_LIMITS_V1, ApprovedTextureResourceUnavailableError, EMBEDDED_RESOURCE_BASE64, isApprovedId = (value) => APPROVED_TEXTURE_RESOURCE_IDS.includes(value), bytesFromBase64 = (value) => new Uint8Array(Buffer.from(value, "base64")), sha256 = (bytes) => createHash4("sha256").update(bytes).digest("hex"), DEFAULT_APPROVED_TEXTURE_CACHE, materialTextures2 = (material) => {- const standard = material;- const candidates = [- standard.map,- standard.normalMap,- standard.roughnessMap,- standard.metalnessMap,- standard.emissiveMap,- standard.aoMap- ];- return [- ...new Set(candidates.filter((value) => value?.isTexture === true))- ];-};-var init_material_resources = __esm(() => {- init_material_recipes();- init_material_texture_library_generated();- init_textures();- TEXTURE_RESOLVER_LIMITS_V1 = Object.freeze({- maxEncodedBytes: 8 * 1024 * 1024,- maxWidth: 4096,- maxHeight: 4096,- maxPixels: 8 * 1024 * 1024,- defaultDeadlineMs: 5000,- maxDeadlineMs: 30000- });- ApprovedTextureResourceUnavailableError = class ApprovedTextureResourceUnavailableError extends Error {- resourceId;- constructor(id, reason) {- super(`Approved texture resource ${id} is unavailable: ${reason}`);- this.name = "ApprovedTextureResourceUnavailableError";- this.resourceId = id;+ if (!assembly.moving || !descendantOf(assembly.moving.node, assembly.pivot.node)) {+ findings.push(finding3(context, {+ code: "PROP_ARTICULATION_SUBTREE_INVALID",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Motion assembly ${label} does not own exactly its declared moving subtree beneath the pivot.`,+ affected: {+ node: assembly.moving?.node.name || assembly.pivot.node.name || label,+ nodePath: assembly.moving ? nodePath2(root, assembly.moving.node) : undefined+ },+ measurement: {+ name: "movingSubtreeParentedToPivot",+ actual: assembly.moving ? descendantOf(assembly.moving.node, assembly.pivot.node) : false,+ expected: true+ },+ viewHints: ["front", "right"],+ repairText: `Parent only prop.motion.${label} beneath prop.pivot.${label}; keep the static body outside that subtree.`+ }));}- };- EMBEDDED_RESOURCE_BASE64 = Object.freeze({- "kiln.texture.bark-albedo.v1": "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAFklEQVQImWMIMpT6X+Ch9h9GM5AuAACfBRvJB4zLLQAAAABJRU5ErkJggg==",- "kiln.texture.leaf-mask-albedo.v1": "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAKUlEQVQImWMwaLFiMGixSjBosdoCYsM4/6E4ASQAkoEJbAEJwARBKhkACRMXLR+u+yUAAAAASUVORK5CYII=",- "kiln.texture.neutral-normal.v1": "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEUlEQVQImWNoaPj/H4QZYAwAZ9IL+W19YCAAAAAASUVORK5CYII=",- "kiln.texture.neutral-metallic-roughness.v1": "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEElEQVQImWNguCT0H4xhDAA/hAeNGSjqWAAAAABJRU5ErkJggg==",- "kiln.texture.emissive-grid.v1": "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAFklEQVQImWP4P0Hhv4MEy38GEAHiAABG+wgTqOP6IAAAAABJRU5ErkJggg==",- ...PRODUCTION_TEXTURE_RESOURCE_BASE64- });- DEFAULT_APPROVED_TEXTURE_CACHE = new ApprovedTextureResourceCache;-});--// src/portable-material-runtime.ts-async function compilePortableMaterialSpecV2(input) {- const spec = canonicalizePortableMaterialSpecV2(input);- const cache = DEFAULT_APPROVED_TEXTURE_CACHE;- const entries = Object.entries(spec.textures);- for (const [slot, ref] of entries) {- if (ref.kind !== "resource")+ if (!assembly.clearance?.box) {+ findings.push(finding3(context, {+ code: "PROP_ARTICULATION_CLEARANCE_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Motion assembly ${label} has no measurable semantic sweep/clearance prism.`,+ affected: { node: assembly.pivot.node.name || label },+ measurement: { name: "clearanceMarkerCount", actual: 0, expected: 1, threshold: 1 },+ viewHints: ["front", "right", "top"],+ repairText: `Add a non-rendered scaled prop.clearance.${label} marker covering the requested motion sweep.`+ }));continue;- if (!isApprovedResourceId(ref.resourceId)) {- throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not an approved texture resource ID.`);- }- const descriptor2 = cache.descriptor(ref.resourceId);- if (!descriptor2.allowedSlots.includes(slot)) {- throw new ProceduralTextureError(`portableMaterial.textures.${slot} resource ${JSON.stringify(ref.resourceId)} is not approved for that slot.`);}- if (descriptor2.usage !== SLOT_USAGE[slot]) {- throw new ProceduralTextureError(`portableMaterial.textures.${slot} requires ${SLOT_USAGE[slot]} data, but ${JSON.stringify(ref.resourceId)} provides ${descriptor2.usage}.`);+ const allowedStationaryRoles = allowedClearanceContactRoles(assembly);+ const blocker = parts.find((part) => part.renderable && part.box && !descendantOf(part.node, assembly.pivot.node) && !part.roles.some((role) => allowedStationaryRoles.has(role)) && boxesOverlap(part.box, assembly.clearance.box, CLEARANCE_TOLERANCE_METERS));+ if (blocker) {+ findings.push(finding3(context, {+ code: "PROP_ARTICULATION_CLEARANCE_BLOCKED",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Motion sweep ${label} is blocked by ${blocker.node.name || "an unnamed mesh"}.`,+ affected: {+ node: blocker.node.name || "prop-motion-blocker",+ nodePath: nodePath2(root, blocker.node)+ },+ measurement: {+ name: "motionClearanceBlockerCount",+ actual: 1,+ expected: 0,+ threshold: 0+ },+ viewHints: ["front", "right", "top"],+ repairText: `Remove only the reported blocker from prop.clearance.${label}; do not move unrelated geometry.`+ }));}}- const loaded = new Map;- await Promise.all(entries.map(async ([slot, ref]) => {- const texture = ref.kind === "procedural" ? proceduralTexture(ref.spec) : (await cache.load(ref.resourceId)).texture;- loaded.set(slot, texture);- }));- const materialOptions = {- roughness: spec.roughness,- metalness: spec.metalness,- emissiveIntensity: spec.emissiveIntensity,- alphaMode: spec.alphaMode,- ...spec.alphaMode === "mask" ? { alphaCutoff: spec.alphaCutoff } : {},- doubleSided: spec.doubleSided,- ...loaded.get("baseColor") ? { albedo: loaded.get("baseColor") } : spec.baseColor !== undefined ? { albedo: spec.baseColor } : {},- ...loaded.get("normal") ? { normal: loaded.get("normal") } : {},- ...loaded.get("metallicRoughness") ? { metallicRoughness: loaded.get("metallicRoughness") } : {},- ...loaded.get("emissive") ? { emissive: loaded.get("emissive") } : spec.emissive !== undefined ? { emissive: spec.emissive } : {},- ...loaded.get("occlusion") ? { aoMap: loaded.get("occlusion") } : {}- };- const material = pbrMaterial(materialOptions);- if (spec.name)- material.name = spec.name;- if (loaded.has("baseColor") && spec.baseColor !== undefined)- material.color.setHex(spec.baseColor);- if (loaded.has("emissive") && spec.emissive !== undefined)- material.emissive.setHex(spec.emissive);- material.userData["kilnPortableMaterial"] = spec;- return material;+ return findings;}-var SLOT_USAGE, isApprovedResourceId = (value) => APPROVED_TEXTURE_RESOURCE_IDS.includes(value);-var init_portable_material_runtime = __esm(() => {- init_material_recipes();- init_material_resources();- init_procedural_material_v2();- init_procedural_texture();- init_textures();- SLOT_USAGE = {- baseColor: "albedo",- normal: "normal",- metallicRoughness: "metallicRoughness",- emissive: "emissive",- occlusion: "occlusion"- };-});--// src/uv.ts-import * as THREE24 from "three";-async function getXatlas() {- if (!_xatlasReady) {- _xatlasReady = (async () => {- const apiSpecifier = "xatlasjs/dist/node/api.mjs";- const xatlasSpecifier = "xatlasjs/dist/node/xatlas.js";- const apiMod = await import(apiSpecifier);- const xatlasMod = await import(xatlasSpecifier);- const create = xatlasMod.default ?? xatlasMod;- const ApiCtor = apiMod.Api(create);- return new Promise((resolve2) => {- const xa = new ApiCtor(() => resolve2(xa), null, null);- });- })();- }- return _xatlasReady;+function rolePart(parts, expression) {+ return parts.find((part) => part.roles.some((role) => expression.test(role)));}-async function autoUnwrap(geometry, opts = {}) {- const xa = await getXatlas();- const src = geometry.index ? geometry : toIndexed(geometry);- const posAttr = src.getAttribute("position");- const normAttr = src.getAttribute("normal");- const idxAttr = src.getIndex();- if (!posAttr || !idxAttr) {- throw new Error("autoUnwrap: geometry requires position attribute and an index");+function interiorUsable(box) {+ const size = box.getSize(new THREE23.Vector3);+ return size.x >= 0.08 && size.y >= 0.08 && size.z >= 0.08;+}+function evaluatePropContainerQa(context) {+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))+ return [];+ const explicitlyOpen = context.intent.capabilities.includes("openable");+ const explicitContainment = /^(?:open-)?(?:container|chest|case|box)$/i.test(context.intent.subtype ?? "");+ if (!explicitlyOpen && !explicitContainment)+ return [];+ const root = context.scene;+ const parts = collectParts(root);+ const interior = rolePart(parts, /^prop\.container\.interior(?:\.|$)/);+ const opening = rolePart(parts, /^prop\.container\.opening(?:\.|$)/);+ const hasSemanticContainerEvidence = Boolean(interior || opening);+ if (!hasSemanticContainerEvidence) {+ const names = [];+ root.traverse((node) => names.push(node.name));+ if (usesExplicitLegacyProfile(context) && names.some((name) => /^(?:Joint|Pivot)[_.-].*(?:lid|door|hatch)/i.test(name)) && names.some((name) => /(?:Mesh[_.-])?(?:lid|door|hatch)/i.test(name))) {+ return [];+ }+ if (!explicitlyOpen)+ return [];+ return [+ finding3(context, {+ code: "PROP_CONTAINER_OPENING_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "openable=true has no semantic opening/interior markers or canonical jointed lid.",+ affected: { node: root.name || "prop-root" },+ measurement: {+ name: "containerOpeningEvidenceCount",+ actual: 0,+ expected: ">=1",+ threshold: 1+ },+ viewHints: ["front", "right", "top"],+ repairText: "Author distinct prop.container.opening.main and prop.container.interior.main clearance markers; do not fill the interior with a solid mesh."+ })+ ];}- if (idxAttr.count === 0 || posAttr.count === 0) {- throw new Error("autoUnwrap: geometry has no triangles. Nothing can be unwrapped — check the operation that produced it (an empty CSG result is the usual cause).");+ const findings = [];+ if (!interior?.box) {+ findings.push(finding3(context, {+ code: "PROP_CONTAINER_INTERIOR_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "The semantic container profile has no measurable interior negative-space prism.",+ affected: { node: root.name || "prop-root" },+ measurement: { name: "containerInteriorMarkerCount", actual: 0, expected: 1, threshold: 1 },+ viewHints: ["front", "top"],+ repairText: "Add a non-rendered scaled prop.container.interior.main marker inside the shell."+ }));+ } else if (!interiorUsable(interior.box)) {+ const size = interior.box.getSize(new THREE23.Vector3);+ findings.push(finding3(context, {+ code: "PROP_CONTAINER_INTERIOR_UNUSABLE",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "The declared container interior has no usable three-dimensional negative space.",+ affected: {+ node: interior.node.name || "container-interior",+ nodePath: nodePath2(root, interior.node)+ },+ measurement: {+ name: "minimumInteriorExtent",+ actual: stable4(Math.min(size.x, size.y, size.z)),+ expected: ">=0.08",+ threshold: 0.08,+ unit: "m"+ },+ viewHints: ["front", "top"],+ repairText: "Enlarge the interior marker and remove solid filler so all three clear extents are at least 0.08 m."+ }));}- if (idxAttr.count % 3 !== 0) {- throw new Error(`autoUnwrap: geometry has ${idxAttr.count} indices, which is not a whole number of triangles.`);+ if (!opening?.box) {+ findings.push(finding3(context, {+ code: "PROP_CONTAINER_OPENING_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "The semantic container profile has no measurable opening into its interior.",+ affected: { node: root.name || "prop-root" },+ measurement: { name: "containerOpeningMarkerCount", actual: 0, expected: 1, threshold: 1 },+ viewHints: ["front", "top"],+ repairText: "Add a non-rendered scaled prop.container.opening.main marker connecting outside to the interior."+ }));+ } else {+ const blocker = parts.find((part) => part.renderable && part.box && !part.roles.some((role) => role.startsWith("prop.container.shell") || role.startsWith("prop.container.lid") || role.startsWith("prop.motion.")) && boxesOverlap(part.box, opening.box, CLEARANCE_TOLERANCE_METERS));+ if (blocker) {+ findings.push(finding3(context, {+ code: "PROP_CONTAINER_OPENING_BLOCKED",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Container opening is blocked by ${blocker.node.name || "an unnamed solid filler"}.`,+ affected: {+ node: blocker.node.name || "container-blocker",+ nodePath: nodePath2(root, blocker.node)+ },+ measurement: {+ name: "containerOpeningBlockerCount",+ actual: 1,+ expected: 0,+ threshold: 0+ },+ viewHints: ["front", "top"],+ repairText: "Remove or split only the reported filler so the opening connects to the interior negative space."+ }));+ }}- xa.createAtlas();- const useNormals = Boolean(opts.useNormals && normAttr);- const indexArray = idxAttr.array instanceof Uint32Array ? idxAttr.array : new Uint32Array(idxAttr.array);- const addRes = xa.addMesh(indexArray, new Float32Array(posAttr.array), useNormals && normAttr ? new Float32Array(normAttr.array) : null, null, "kiln-mesh", useNormals, false, 1);- if (!addRes) {- xa.destroyAtlas();- throw new Error("autoUnwrap: xatlas.addMesh failed (non-manifold or degenerate geometry?)");+ return findings;+}+function horizontalDirection(part, root) {+ if (!(part.node instanceof THREE23.Mesh) || !(part.node.geometry instanceof THREE23.BufferGeometry)) {+ return;}- const result = xa.generateAtlas({}, { resolution: opts.resolution ?? 1024, padding: opts.padding ?? 2 }, true);- const mesh = result.meshes[0];- if (!mesh) {- xa.destroyAtlas();- throw new Error("autoUnwrap: xatlas returned no meshes");+ part.node.geometry.computeBoundingBox();+ const box = part.node.geometry.boundingBox;+ if (!box)+ return;+ const size = box.getSize(new THREE23.Vector3);+ const axis = size.x >= size.z ? new THREE23.Vector3(1, 0, 0) : new THREE23.Vector3(0, 0, 1);+ root.updateWorldMatrix(true, true);+ const rootQuaternion = root.getWorldQuaternion(new THREE23.Quaternion).invert();+ return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE23.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();+}+function evaluatePropCircularAssemblyQa(context) {+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))+ return [];+ const root = context.scene;+ const parts = collectParts(root);+ const tagged = parts.some((part) => part.roles.some((role) => role === "prop.circular.assembly" || role.startsWith("prop.circular.member.")));+ const namedProfile = /(?:barrel|drum)/i.test(context.intent.subtype ?? "");+ if (!tagged && !namedProfile)+ return [];+ const memberParts = parts.filter((part) => part.box && (part.roles.some((role) => role.startsWith("prop.circular.member.")) || namedProfile && /(?:stave|ring[_.-]?segment)/i.test(part.node.name)));+ if (memberParts.length < 3)+ return [];+ const centers = memberParts.map((part) => part.box.getCenter(new THREE23.Vector3));+ const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE23.Vector3).multiplyScalar(1 / centers.length);+ const members = memberParts.map((part, index) => {+ const center = centers[index];+ return {+ part,+ center,+ angle: Math.atan2(center.z - ringCenter.z, center.x - ringCenter.x),+ horizontalDirection: horizontalDirection(part, root)+ };+ });+ members.sort((a, b) => a.angle - b.angle);+ const gaps = members.map((member, index) => {+ const next = members[(index + 1) % members.length];+ return (next.angle - member.angle + Math.PI * 2) % (Math.PI * 2);+ });+ const expectedGap = Math.PI * 2 / members.length;+ const maximumGap = Math.max(...gaps);+ const findings = [];+ if (maximumGap > Math.max(Math.PI / 3, expectedGap * 1.5)) {+ findings.push(finding3(context, {+ code: "PROP_CIRCULAR_RING_INCOMPLETE",+ disposition: "warn",+ dimension: "visualQuality",+ message: `Circular assembly has a likely missing sector of ${(maximumGap * 180 / Math.PI).toFixed(2)} degrees.`,+ affected: { node: root.name || "prop-root" },+ measurement: {+ name: "maximumAngularGap",+ actual: stable4(maximumGap * 180 / Math.PI),+ expected: `<=${stable4(Math.max(60, expectedGap * 1.5 * 180 / Math.PI))}`,+ unit: "deg"+ },+ viewHints: ["top", "three-quarter"]+ }));}- const out = new THREE24.BufferGeometry;- out.setAttribute("position", new THREE24.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));- if (mesh.vertex.normals) {- out.setAttribute("normal", new THREE24.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));+ const expectedOrientation = parts.some((part) => part.roles.includes("prop.circular.expected.radial")) ? "radial" : "tangent";+ const wrong = members.filter((member) => {+ if (!member.horizontalDirection)+ return false;+ const radial = member.center.clone().sub(ringCenter).setY(0).normalize();+ const tangent = new THREE23.Vector3(-radial.z, 0, radial.x);+ const radialScore = Math.abs(member.horizontalDirection.dot(radial));+ const tangentScore = Math.abs(member.horizontalDirection.dot(tangent));+ return expectedOrientation === "tangent" ? tangentScore + 0.1 < radialScore : radialScore + 0.1 < tangentScore;+ });+ if (wrong.length > 0) {+ findings.push(finding3(context, {+ code: "PROP_CIRCULAR_MEMBER_ORIENTATION",+ disposition: "warn",+ dimension: "visualQuality",+ message: `${wrong.length} circular members appear ${expectedOrientation === "tangent" ? "radial" : "tangent"} instead of ${expectedOrientation}.`,+ affected: {+ node: wrong[0].part.node.name || "circular-member",+ nodePath: nodePath2(root, wrong[0].part.node)+ },+ measurement: {+ name: "misorientedCircularMemberCount",+ actual: wrong.length,+ expected: 0,+ threshold: 0+ },+ viewHints: ["top", "three-quarter"]+ }));}- if (mesh.vertex.coords1) {- out.setAttribute("uv", new THREE24.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));+ return findings;+}+function evaluatePropScalePivotQa(context) {+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))+ return [];+ const root = context.scene;+ const parts = collectParts(root);+ const renderable = parts.filter((part) => part.renderable && part.box);+ if (renderable.length === 0)+ return [];+ const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE23.Box3);+ const size = bounds.getSize(new THREE23.Vector3);+ const findings = [];+ for (const axis of ["x", "y", "z"]) {+ const expected = context.intent.bounds?.[axis];+ if (expected === undefined)+ continue;+ const actual = size[axis];+ const tolerance = Math.max(0.05, expected * 0.2);+ if (Math.abs(actual - expected) <= tolerance)+ continue;+ findings.push(finding3(context, {+ code: "PROP_SCALE_BOUNDS_MISMATCH",+ disposition: "warn",+ dimension: "promptAlignment",+ message: `Prop ${axis.toUpperCase()} extent is ${actual.toFixed(4)} m, outside the declared ${expected.toFixed(4)} m scale band.`,+ affected: { node: root.name || "prop-root", attribute: `bounds.${axis}` },+ measurement: {+ name: `bounds.${axis}`,+ actual: stable4(actual),+ expected: stable4(expected),+ threshold: stable4(tolerance),+ unit: "m"+ },+ viewHints: ["front", "right", "top"]+ }));}- if (mesh.index) {- out.setIndex(new THREE24.BufferAttribute(new Uint32Array(mesh.index), 1));+ if (context.intent.capabilities.includes("grounded")) {+ if (Math.abs(bounds.min.y) > GROUND_TOLERANCE_METERS) {+ findings.push(finding3(context, {+ code: "PROP_GROUND_MISMATCH",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `Grounded prop base is ${Math.abs(bounds.min.y).toFixed(6)} m ${bounds.min.y > 0 ? "above" : "below"} asset-local Y=0.`,+ affected: { node: root.name || "prop-root" },+ measurement: {+ name: "minimumY",+ actual: stable4(bounds.min.y),+ expected: 0,+ threshold: GROUND_TOLERANCE_METERS,+ unit: "m"+ },+ viewHints: ["right", "three-quarter"]+ }));+ }}- out.userData["atlas"] = {- width: result.width,- height: result.height,- atlasCount: result.atlasCount- };- if (!out.getAttribute("normal"))- out.computeVertexNormals();- repairZeroNormals(out);- if (!out.getAttribute("uv")) {- xa.destroyAtlas();- throw new Error("autoUnwrap: xatlas produced no UV coordinates for this geometry (degenerate or zero-area triangles?).");+ const placement = parts.find((part) => part.roles.includes("prop.pivot.placement"));+ if (placement) {+ const point = placement.node.getWorldPosition(new THREE23.Vector3);+ point.applyMatrix4(root.matrixWorld.clone().invert());+ const horizontalOutside = point.x < bounds.min.x - GROUND_TOLERANCE_METERS || point.x > bounds.max.x + GROUND_TOLERANCE_METERS || point.z < bounds.min.z - GROUND_TOLERANCE_METERS || point.z > bounds.max.z + GROUND_TOLERANCE_METERS;+ const verticalDelta = Math.abs(point.y - bounds.min.y);+ if (horizontalOutside || verticalDelta > GROUND_TOLERANCE_METERS) {+ findings.push(finding3(context, {+ code: "PROP_PLACEMENT_PIVOT_OFF_BASE",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: "Declared placement pivot is not on the prop support base.",+ affected: {+ node: placement.node.name || "placement-pivot",+ nodePath: nodePath2(root, placement.node)+ },+ measurement: {+ name: "placementPivotBaseDelta",+ actual: stable4(verticalDelta),+ expected: 0,+ threshold: GROUND_TOLERANCE_METERS,+ unit: "m"+ },+ viewHints: ["right", "top"]+ }));+ }}- xa.destroyAtlas();- return out;+ return findings;+}+var PROFILE3 = "prop.capability", GROUND_TOLERANCE_METERS = 0.02, CLEARANCE_TOLERANCE_METERS = 0.004, stable4 = (value) => Math.round(value * 1e6) / 1e6, PROP_EXACT_QA_RULE, PROP_ADVISORY_QA_RULE, PROP_QA_RULES;+var init_prop = __esm(() => {+ init_contracts();+ init_registry();+ PROP_EXACT_QA_RULE = Object.freeze({+ id: "PROP_CAPABILITY_EXACT_PROFILE",+ profile: PROFILE3,+ scope: { kind: "category", category: "prop" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("prop-capability-v1", "src/qa/prop.test.ts", "a152104990fa6b92eea3c201ce39497a5d165ee19080a29e42b96ebe450d936c"),+ defaultMode: "enforce",+ evaluate: (context) => [+ ...evaluatePropArticulationQa(context),+ ...evaluatePropContainerQa(context)+ ]+ });+ PROP_ADVISORY_QA_RULE = Object.freeze({+ id: "PROP_ADVISORY_PROFILE",+ profile: "prop.advisory",+ scope: { kind: "category", category: "prop" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: (context) => [+ ...evaluatePropCircularAssemblyQa(context),+ ...evaluatePropScalePivotQa(context)+ ]+ });+ PROP_QA_RULES = [+ PROP_EXACT_QA_RULE,+ PROP_ADVISORY_QA_RULE+ ];+});++// src/qa/part-connectivity.ts+import * as THREE24 from "three";+function collectParts2(root, exempt) {+ const parts = [];+ root.updateWorldMatrix(true, true);+ root.traverse((node) => {+ const mesh = node;+ if (!mesh.isMesh || !mesh.geometry)+ return;+ const name = mesh.name || "(unnamed mesh)";+ if (EXEMPT_NAME.test(name)) {+ exempt.push(name);+ return;+ }+ const box = new THREE24.Box3().setFromObject(mesh);+ if (box.isEmpty())+ return;+ parts.push({ name, box });+ });+ return parts;}-function toIndexed(geo) {- const posAttr = geo.getAttribute("position");- const indices = new Uint32Array(posAttr.count);- for (let i = 0;i < posAttr.count; i++)- indices[i] = i;- const out = geo.clone();- out.setIndex(new THREE24.BufferAttribute(indices, 1));- return out;+function boxGap(a, b) {+ const dx = Math.max(0, Math.max(a.min.x - b.max.x, b.min.x - a.max.x));+ const dy = Math.max(0, Math.max(a.min.y - b.max.y, b.min.y - a.max.y));+ const dz = Math.max(0, Math.max(a.min.z - b.max.z, b.min.z - a.max.z));+ return Math.hypot(dx, dy, dz);}-function repairZeroNormals(geo) {- const normal = geo.getAttribute("normal");- const position = geo.getAttribute("position");- const index = geo.getIndex();- if (!normal || !position || !index)- return;- const broken = new Set;- for (let i = 0;i < normal.count; i++) {- const x = normal.getX(i);- const y = normal.getY(i);- const z3 = normal.getZ(i);- if (!Number.isFinite(x + y + z3) || Math.hypot(x, y, z3) < 0.000001)- broken.add(i);+function analyzePartConnectivity(root) {+ const exempt = [];+ const parts = collectParts2(root, exempt);+ const report = {+ partsAnalyzed: parts.length,+ mainComponentSize: parts.length,+ exempt,+ groups: []+ };+ if (parts.length < 2)+ return report;+ const adjacency = parts.map(() => []);+ for (let i = 0;i < parts.length; i++) {+ for (let j = i + 1;j < parts.length; j++) {+ if (boxGap(parts[i].box, parts[j].box) <= CONNECTIVITY_TOLERANCE) {+ adjacency[i].push(j);+ adjacency[j].push(i);+ }+ }}- if (broken.size === 0)- return;- const acc = new Float32Array(normal.count * 3);- const a = new THREE24.Vector3;- const b = new THREE24.Vector3;- const c = new THREE24.Vector3;- const face = new THREE24.Vector3;- const edge = new THREE24.Vector3;- for (let t = 0;t + 2 < index.count; t += 3) {- const tri = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];- if (!tri.some((i) => broken.has(i)))+ const component = new Int32Array(parts.length).fill(-1);+ const components = [];+ for (let seed = 0;seed < parts.length; seed++) {+ if (component[seed] !== -1)continue;- a.fromBufferAttribute(position, tri[0]);- b.fromBufferAttribute(position, tri[1]);- c.fromBufferAttribute(position, tri[2]);- face.subVectors(c, a);- edge.subVectors(b, a);- face.crossVectors(edge, face);- for (const i of tri) {- if (!broken.has(i))- continue;- const o = i * 3;- acc[o] = acc[o] + face.x;- acc[o + 1] = acc[o + 1] + face.y;- acc[o + 2] = acc[o + 2] + face.z;+ const id = components.length;+ const members = [];+ const stack = [seed];+ component[seed] = id;+ while (stack.length > 0) {+ const current = stack.pop();+ members.push(current);+ for (const next of adjacency[current]) {+ if (component[next] === -1) {+ component[next] = id;+ stack.push(next);+ }+ }}+ members.sort((x, y) => x - y);+ components.push(members);}- for (const i of broken) {- face.set(acc[i * 3], acc[i * 3 + 1], acc[i * 3 + 2]);- if (face.lengthSq() < 0.00000000000000000001)- face.set(0, 1, 0);- else- face.normalize();- normal.setXYZ(i, face.x, face.y, face.z);+ if (components.length < 2)+ return report;+ let mainIndex = 0;+ for (let i = 1;i < components.length; i++) {+ const bigger = components[i].length > components[mainIndex].length;+ const tie = components[i].length === components[mainIndex].length && components[i][0] < components[mainIndex][0];+ if (bigger || tie)+ mainIndex = i;}- normal.needsUpdate = true;+ const main = components[mainIndex];+ report.mainComponentSize = main.length;+ for (const [index, members] of components.entries()) {+ if (index === mainIndex)+ continue;+ let gap = Number.POSITIVE_INFINITY;+ for (const m of members) {+ for (const b of main) {+ gap = Math.min(gap, boxGap(parts[m].box, parts[b].box));+ }+ }+ report.groups.push({+ parts: members.map((m) => parts[m].name),+ gap: Math.round(gap * 1e6) / 1e6+ });+ }+ report.groups.sort((a, b) => b.parts.length - a.parts.length || a.gap - b.gap);+ return report;}-var _xatlasReady = null;-var init_uv = () => {};+var CONNECTIVITY_TOLERANCE = 0.02, EXEMPT_NAME, PART_CONNECTIVITY_QA_RULE;+var init_part_connectivity = __esm(() => {+ init_registry();+ EXEMPT_NAME = /(?:^|_)(?:leaf|leaves|foliage|frond|card|decal|billboard|petal)/i;+ PART_CONNECTIVITY_QA_RULE = Object.freeze({+ id: "GEO_PART_CONNECTIVITY",+ profile: "geometry.partConnectivity",+ scope: { kind: "universal" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate(context) {+ if (!(context.scene instanceof THREE24.Object3D))+ return [];+ const report = analyzePartConnectivity(context.scene);+ if (report.groups.length === 0)+ return [];+ return report.groups.map((group) => {+ const listed = group.parts.map((p) => JSON.stringify(p)).join(", ");+ const subject = group.parts.length === 1 ? `Part ${listed} is` : `A group of ${group.parts.length} parts (${listed}) is`;+ return {+ code: "GEO_PART_CONNECTIVITY",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.partConnectivity",+ message: `${subject} not attached to the main body — the nearest gap is ${group.gap.toFixed(3)} m. ${group.parts.length === 1 ? "It floats on its own." : "These parts touch each other but nothing else, so one join is missing rather than several parts being misplaced."}`,+ affected: { node: group.parts[0] },+ measurement: {+ name: "gapToMainComponent",+ actual: group.gap,+ expected: CONNECTIVITY_TOLERANCE+ },+ repairText: `Attach it with snapTo(${JSON.stringify(group.parts[0])}Part, hostPart), or reposition the group so it contacts the body. If it is meant to stand apart, say so in the part name (foliage, card, decal) so this check skips it.`+ };+ });+ }+ });+});-// src/uv-shapes.ts-import * as THREE25 from "three";-function boxUnwrap(geo) {- const cloned = geo.clone();- if (!cloned.getAttribute("uv")) {- planarProjectToUVs(cloned);- }- return cloned;+// src/qa/reference-comparison.ts+function isEvidence(value) {+ if (typeof value !== "object" || value === null)+ return false;+ const candidate = value;+ return candidate.schemaVersion === 1 && typeof candidate.silhouetteIoU === "number" && typeof candidate.colorAgreement === "number" && typeof candidate.reference === "object" && typeof candidate.rendered === "object";}-function cylinderUnwrap(geo) {- const cloned = geo.clone();- if (!cloned.getAttribute("uv")) {- cylindricalProjectToUVs(cloned);+function referenceComparisonFindings(evidence, profile) {+ if (evidence.reference.coverage <= 0 || evidence.rendered.coverage <= 0)+ return [];+ const findings = [];+ if (evidence.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {+ findings.push({+ code: "REF_SILHOUETTE_AGREEMENT",+ disposition: "observe",+ dimension: "promptAlignment",+ profile,+ message: `The asset's outline agrees with the reference image on ${(evidence.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,+ measurement: {+ name: "silhouetteIoU",+ actual: evidence.silhouetteIoU,+ threshold: SILHOUETTE_IOU_OBSERVE+ },+ repairText: "Compare the reference against the rendered views and adjust the overall proportions — the outline is the part that disagrees, not the detail."+ });}- return cloned;-}-function cylindricalProjectToUVs(geo) {- const pos = geo.getAttribute("position");- if (!pos)- return;- geo.computeBoundingBox();- const bb = geo.boundingBox;- if (!bb)- return;- const minY = bb.min.y;- const height = bb.max.y - minY;- const maxR = Math.max(Math.hypot(bb.min.x, bb.min.z), Math.hypot(bb.max.x, bb.max.z), 0.000001);- if (!geo.getAttribute("normal"))- geo.computeVertexNormals();- const nrm = geo.getAttribute("normal");- const spanX = Math.max(bb.max.x - bb.min.x, 0.000001);- const spanZ = Math.max(bb.max.z - bb.min.z, 0.000001);- let minA = Infinity;- let maxA = -Infinity;- for (let i = 0;i < pos.count; i++) {- if (nrm && Math.abs(nrm.getY(i)) > 0.7)- continue;- const a = Math.atan2(pos.getZ(i), pos.getX(i));- if (a < minA)- minA = a;- if (a > maxA)- maxA = a;+ if (evidence.colorAgreement < COLOR_AGREEMENT_OBSERVE) {+ findings.push({+ code: "REF_COLOR_AGREEMENT",+ disposition: "observe",+ dimension: "promptAlignment",+ profile,+ message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,+ measurement: {+ name: "colorAgreement",+ actual: evidence.colorAgreement,+ threshold: COLOR_AGREEMENT_OBSERVE+ },+ repairText: "Set the base colours from the reference image rather than from the prompt wording, then re-render."+ });}- const span = maxA - minA;- const uv = new Float32Array(pos.count * 2);- for (let i = 0;i < pos.count; i++) {- const x = pos.getX(i);- const y = pos.getY(i);- const z3 = pos.getZ(i);- if (nrm && Math.abs(nrm.getY(i)) > 0.7) {- uv[i * 2] = (x - bb.min.x) / spanX;- uv[i * 2 + 1] = (z3 - bb.min.z) / spanZ;- continue;+ return findings;+}+var SILHOUETTE_IOU_OBSERVE = 0.55, COLOR_AGREEMENT_OBSERVE = 0.5, REFERENCE_COMPARISON_QA_RULE;+var init_reference_comparison = __esm(() => {+ init_registry();+ REFERENCE_COMPARISON_QA_RULE = Object.freeze({+ id: "REF_COMPARISON",+ profile: "reference.comparison",+ scope: { kind: "universal" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate(context) {+ const evidence = context.derivedEvidence?.["referenceComparison"];+ if (!isEvidence(evidence))+ return [];+ return referenceComparisonFindings(evidence, "reference.comparison");}- const a = Math.atan2(z3, x);- uv[i * 2] = span > 0.000001 ? (a - minA) / span : 0.5;- uv[i * 2 + 1] = height > 0.000001 ? (y - minY) / height : Math.hypot(x, z3) / maxR;- }- geo.setAttribute("uv", new THREE25.BufferAttribute(uv, 2));+ });+});++// src/qa/self-intersection.ts+import * as THREE25 from "three";+function triangleCount(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");+ if (!position)+ return 0;+ return Math.floor((index ? index.count : position.count) / 3);}-function planeUnwrap(geo) {- const cloned = geo.clone();- planarProjectToUVs(cloned);- return cloned;+function collectParts3(root, skipped) {+ const parts = [];+ root.updateWorldMatrix(true, true);+ root.traverse((node) => {+ const mesh = node;+ if (!mesh.isMesh || !mesh.geometry)+ return;+ const name = mesh.name || "(unnamed mesh)";+ const triangles = triangleCount(mesh.geometry);+ if (triangles === 0)+ return;+ if (triangles > MAX_PART_TRIANGLES) {+ skipped.push({+ part: name,+ reason: `${triangles} triangles exceeds the ${MAX_PART_TRIANGLES}-triangle analysis budget`+ });+ return;+ }+ const box = new THREE25.Box3().setFromObject(mesh);+ if (box.isEmpty())+ return;+ parts.push({ name, mesh, box, triangles });+ });+ return parts;}-function panelRemapV(geo, vScale = 0.3, vOffset = 0, uScale = 1, uOffset = 0) {- const cloned = geo.clone();- const uvAttr = cloned.getAttribute("uv");- if (!uvAttr)- return cloned;- const arr = uvAttr.array;- for (let i = 0;i < arr.length; i += 2) {- arr[i] = (arr[i] ?? 0) * uScale + uOffset;- arr[i + 1] = (arr[i + 1] ?? 0) * vScale + vOffset;+function meshToArrays(mesh) {+ const geometry = mesh.geometry;+ const position = geometry.getAttribute("position");+ if (!position)+ return null;+ const matrix = mesh.matrixWorld;+ const v = new THREE25.Vector3;+ const verts = new Float32Array(position.count * 3);+ for (let i = 0;i < position.count; i++) {+ v.set(position.getX(i), position.getY(i), position.getZ(i)).applyMatrix4(matrix);+ verts[i * 3] = v.x;+ verts[i * 3 + 1] = v.y;+ verts[i * 3 + 2] = v.z;}- uvAttr.needsUpdate = true;- return cloned;-}-function planarProjectToUVs(geo) {- geo.computeBoundingBox();- const bb = geo.boundingBox;- const size = new THREE25.Vector3;- bb.getSize(size);- const w = size.x || 1;- const h = size.y || 1;- const pos = geo.getAttribute("position");- const uvs = new Float32Array(pos.count * 2);- for (let i = 0;i < pos.count; i++) {- uvs[i * 2] = (pos.getX(i) - bb.min.x) / w;- uvs[i * 2 + 1] = (pos.getY(i) - bb.min.y) / h;+ const index = geometry.getIndex();+ let tris;+ if (index) {+ if (index.count % 3 !== 0)+ return null;+ tris = new Uint32Array(index.count);+ for (let i = 0;i < index.count; i++)+ tris[i] = index.getX(i);+ } else {+ if (position.count % 3 !== 0)+ return null;+ tris = new Uint32Array(position.count);+ for (let i = 0;i < position.count; i++)+ tris[i] = i;}- geo.setAttribute("uv", new THREE25.BufferAttribute(uvs, 2));+ return { vertProperties: verts, triVerts: tris };}-var init_uv_shapes = () => {};--// src/material-recipe-runtime.ts-import * as THREE26 from "three";-async function applyMaterialRecipeV1(request, options = {}) {- const resolved2 = resolveMaterialRecipeV1(request);- const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;- const loaded = new Map;- for (const [slot, id] of Object.entries(resolved2.textureResources)) {- if (id)- loaded.set(slot, await cache.load(id));+async function analyzePartPenetration(root) {+ const skipped = [];+ const parts = collectParts3(root, skipped);+ const base = {+ schemaVersion: 1,+ source: "engine-scene-analysis",+ partsAnalyzed: parts.length,+ candidatePairs: 0,+ pairsTested: 0,+ truncated: false,+ skipped,+ penetrations: []+ };+ if (parts.length < 2)+ return base;+ const candidates = [];+ for (let i = 0;i < parts.length; i++) {+ for (let j = i + 1;j < parts.length; j++) {+ if (parts[i].box.intersectsBox(parts[j].box))+ candidates.push([parts[i], parts[j]]);+ }}- const materialOptions = {- roughness: resolved2.roughnessFactor,- metalness: resolved2.metallicFactor,- alphaMode: lowerAlphaMode(resolved2.alphaMode),- ...resolved2.alphaMode === "MASK" ? { alphaCutoff: resolved2.alphaCutoff ?? 0.5 } : {},- doubleSided: resolved2.doubleSided,- ...loaded.get("baseColor") ? { albedo: loaded.get("baseColor").texture } : {},- ...loaded.get("normal") ? { normal: loaded.get("normal").texture } : {},- ...loaded.get("metallicRoughness") ? { metallicRoughness: loaded.get("metallicRoughness").texture } : {},- ...loaded.get("emissive") ? { emissive: loaded.get("emissive").texture } : {},- ...loaded.get("occlusion") ? { aoMap: loaded.get("occlusion").texture } : {}+ base.candidatePairs = candidates.length;+ if (candidates.length === 0)+ return base;+ const tested = candidates.slice(0, MAX_NARROW_PHASE_PAIRS);+ base.truncated = candidates.length > tested.length;+ const Module = await import("manifold-3d");+ const wasm = await Module.default();+ wasm.setup();+ const { Manifold, Mesh } = wasm;+ const cache = new Map;+ const build = (part) => {+ if (cache.has(part.mesh))+ return cache.get(part.mesh);+ let solid = null;+ try {+ const arrays = meshToArrays(part.mesh);+ if (arrays) {+ const mesh = new Mesh({ numProp: 3, ...arrays });+ mesh.merge();+ solid = new Manifold(mesh);+ } else {+ skipped.push({ part: part.name, reason: "its triangle list is malformed" });+ }+ } catch (err) {+ skipped.push({+ part: part.name,+ reason: `it is not a closed solid, so it encloses no volume (${err instanceof Error ? err.message : String(err)})`+ });+ solid = null;+ }+ cache.set(part.mesh, solid);+ return solid;};- const material = pbrMaterial(materialOptions);- material.name = options.name ?? request.id;- material.color.setRGB(resolved2.baseColorFactor[0], resolved2.baseColorFactor[1], resolved2.baseColorFactor[2], THREE26.LinearSRGBColorSpace);- material.opacity = resolved2.baseColorFactor[3];- material.emissive.setRGB(resolved2.emissiveFactor[0], resolved2.emissiveFactor[1], resolved2.emissiveFactor[2], THREE26.LinearSRGBColorSpace);- const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));- const provenance2 = {- schemaVersion: 1,- recipeId: request.id,- recipeVersion: 1,- request: {- schemaVersion: 1,- id: request.id,- ...request.overrides ? {- overrides: {- ...request.overrides,- ...request.overrides.textureResources ? { textureResources: { ...request.overrides.textureResources } } : {}+ const penetrations = [];+ try {+ for (const [a, b] of tested) {+ const sa = build(a);+ const sb = build(b);+ if (!sa || !sb)+ continue;+ base.pairsTested++;+ let overlap = null;+ try {+ overlap = Manifold.intersection(sa, sb);+ const volume = overlap.volume();+ if (volume > 0) {+ const smaller = Math.min(Math.abs(sa.volume()), Math.abs(sb.volume()));+ const fraction = smaller > 0 ? volume / smaller : 0;+ if (fraction > CONTACT_VOLUME_FRACTION) {+ penetrations.push({+ a: a.name,+ b: b.name,+ volume: round(volume),+ fraction: round(fraction)+ });+ }}- } : {}- },- portableModel: "pbrMetallicRoughness",- resources- };- material.userData["kilnMaterialRecipe"] = provenance2;- return { material, resolved: resolved2, provenance: provenance2 };-}-async function materialRecipe(id, overrides, options = {}) {- return (await applyMaterialRecipeV1(createMaterialRecipeRequestV1(id, overrides), options)).material;+ } finally {+ overlap?.delete();+ }+ }+ } finally {+ for (const solid of cache.values())+ solid?.delete();+ }+ penetrations.sort((x, y) => y.fraction - x.fraction || `${x.a}:${x.b}`.localeCompare(`${y.a}:${y.b}`));+ base.penetrations = penetrations;+ return base;}-function readMaterialRecipeApplication(material) {- return material.userData["kilnMaterialRecipe"];+function readEvidence(context) {+ const evidence = context.derivedEvidence?.["partPenetration"];+ return evidence?.schemaVersion === 1 ? evidence : undefined;}-function collectMaterialRecipeApplications(root) {- const applications = new Map;- root.traverse((node) => {- const value = node.material;- const materials = Array.isArray(value) ? value : value ? [value] : [];- for (const material of materials) {- const application = readMaterialRecipeApplication(material);- if (!application)- continue;- const resourceKey = application.resources.map((resource) => `${resource.resourceId}:${resource.contentHash}`).sort().join(",");- applications.set(`${application.recipeId}:${JSON.stringify(application.request)}:${resourceKey}`, application);+var MAX_PART_TRIANGLES = 20000, MAX_NARROW_PHASE_PAIRS = 64, CONTACT_VOLUME_FRACTION = 0.001, round = (n) => Math.round(n * 1e9) / 1e9, SELF_INTERSECTION_QA_RULE;+var init_self_intersection = __esm(() => {+ init_registry();+ SELF_INTERSECTION_QA_RULE = Object.freeze({+ id: "GEO_PART_SELF_INTERSECTION",+ profile: "geometry.selfIntersection",+ scope: { kind: "universal" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate(context) {+ const evidence = readEvidence(context);+ if (!evidence)+ return [];+ const findings = evidence.penetrations.map((pair) => ({+ code: "GEO_PART_SELF_INTERSECTION",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.selfIntersection",+ message: `Parts ${JSON.stringify(pair.a)} and ${JSON.stringify(pair.b)} occupy the same space: they share ${pair.volume.toPrecision(3)} m³, which is ${(pair.fraction * 100).toFixed(1)}% of the smaller part.`,+ affected: { node: pair.a },+ measurement: {+ name: "intersectionVolumeFraction",+ actual: pair.fraction,+ expected: CONTACT_VOLUME_FRACTION+ },+ repairText: "Move one part clear of the other, or subtract it with boolDiff so the overlap becomes a real cut instead of two solids in the same place."+ }));+ if (evidence.truncated) {+ findings.push({+ code: "GEO_PART_SELF_INTERSECTION_TRUNCATED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.selfIntersection",+ message: `Only ${evidence.pairsTested} of ${evidence.candidatePairs} overlapping part pairs were checked (analysis budget). Parts beyond that were not examined.`+ });+ }+ return findings;}});- return [...applications.values()].sort((a, b) => a.recipeId.localeCompare(b.recipeId));-}-var lowerAlphaMode = (value) => value === "MASK" ? "mask" : value === "BLEND" ? "blend" : "opaque";-var init_material_recipe_runtime = __esm(() => {- init_material_recipes();- init_material_resources();- init_textures();});-// src/primitives.ts-import * as THREE27 from "three";-function vectorToTuple(v) {- return [v.x, v.y, v.z];-}-function createRoot(name) {- const root = new THREE27.Object3D;- root.name = name;- return root;+// src/qa/environment.ts+import * as THREE26 from "three";+function finding4(context, value) {+ return { ...value, profile: context.intent.qaProfile || PROFILE4 };}-function createPivot(name, position = [0, 0, 0], parent) {- const pivot = new THREE27.Object3D;- pivot.name = `Joint_${name}`;- pivot.position.set(...position);- if (parent)- parent.add(pivot);- return pivot;+function rolesOf3(node) {+ return readSemanticMetadataV1(node)?.roles ?? [];}-function assertPartArgs(name, geometry2, material) {- const SIG = "Signature: createPart(name, geometry, material, options?) -- " + "e.g. createPart('Hull', boxGeo(1, 1, 1), gameMaterial(0x808080), { parent: root }).";- if (typeof name !== "string") {- const asObject = name;- const got = asObject?.isObject3D === true ? `an Object3D ("${asObject.name || "unnamed"}"). The parent belongs in the options object as { parent }, not first` : `${name === null ? "null" : typeof name}`;- throw new Error(`createPart: the first argument is the part NAME, a string, but got ${got}. ${SIG}`);- }- if (geometry2?.isBufferGeometry !== true) {- let got;- if (typeof geometry2 === "function") {- got = "a function -- geometry helpers have to be CALLED, so boxGeo(1, 1, 1) rather than boxGeo";- } else if (geometry2 instanceof Promise) {- got = "a Promise -- roundedBoxGeo, extrudeProfile and revolveProfile are async, " + "so await the helper and mark build() async";- } else {- got = geometry2 === null ? "null" : geometry2 === undefined ? "undefined" : `a ${typeof geometry2}`;- }- throw new Error(`createPart("${name}"): the second argument must be a geometry, but got ${got}. ${SIG}`);- }- if (material?.isMaterial !== true) {- const got = typeof material === "number" ? "a number -- a colour is not a material, so wrap it: gameMaterial(0x808080)" : material === null ? "null" : material === undefined ? "undefined" : `a ${typeof material}`;- throw new Error(`createPart("${name}"): the third argument must be a material, but got ${got}. ${SIG}`);+function nodePath3(root, node) {+ const names = [];+ let cursor = node;+ while (cursor) {+ names.push(cursor.name || cursor.type);+ if (cursor === root)+ break;+ cursor = cursor.parent;}+ return names.reverse().join("/");}-function createPart(name, geometry2, material, options = {}) {- assertPartArgs(name, geometry2, material);- const mesh = new THREE27.Mesh(geometry2, material);- mesh.name = `Mesh_${name}`;- if (options.position)- mesh.position.set(...options.position);- if (options.rotation)- mesh.rotation.set(THREE27.MathUtils.degToRad(options.rotation[0]), THREE27.MathUtils.degToRad(options.rotation[1]), THREE27.MathUtils.degToRad(options.rotation[2]));- if (options.scale)- mesh.scale.set(...options.scale);- if (options.pivot) {- const pivot = new THREE27.Object3D;- pivot.name = `Joint_${name}`;- pivot.add(mesh);- mesh.position.set(0, 0, 0);- if (options.position)- pivot.position.set(...options.position);- if (options.parent)- options.parent.add(pivot);- if (options.semantic)- stampSemanticMetadataV1(pivot, options.semantic);- return pivot;+function transformedBox2(source, transform) {+ const result = new THREE26.Box3;+ for (const x of [source.min.x, source.max.x]) {+ for (const y of [source.min.y, source.max.y]) {+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE26.Vector3(x, y, z).applyMatrix4(transform));+ }+ }}- if (options.parent)- options.parent.add(mesh);- if (options.semantic)- stampSemanticMetadataV1(mesh, options.semantic);- return mesh;-}-function capsuleGeo(radius, height, segments = 6) {- return new THREE27.CapsuleGeometry(radius, height, 2, segments);+ return result;}-function capsuleXGeo(radius, length3, segments = 6) {- const geo = capsuleGeo(radius, length3, segments);- geo.rotateZ(-Math.PI / 2);- return geo;+function orientedBoxFromLocalBounds(root, node, source) {+ const relative = root.matrixWorld.clone().invert().multiply(node.matrixWorld);+ if (!relative.elements.every(Number.isFinite))+ return;+ const position = new THREE26.Vector3;+ const rotation = new THREE26.Quaternion;+ const scale = new THREE26.Vector3;+ relative.decompose(position, rotation, scale);+ const recomposed = new THREE26.Matrix4().compose(position, rotation, scale);+ const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));+ if (residual > 0.00001)+ return;+ const center = source.getCenter(new THREE26.Vector3).applyMatrix4(relative);+ const sourceHalf = source.getSize(new THREE26.Vector3).multiplyScalar(0.5);+ const halfExtents = [+ Math.abs(sourceHalf.x * scale.x),+ Math.abs(sourceHalf.y * scale.y),+ Math.abs(sourceHalf.z * scale.z)+ ];+ if (halfExtents.some((extent) => !Number.isFinite(extent) || extent <= 0.000000001))+ return;+ rotation.normalize();+ return createOrientedProbeBox3({+ id: `${node.name || node.type}:${node.uuid}`,+ frame: probeLocalFrameFromQuaternion(`${node.name || node.type}:asset-local`, [stable5(center.x), stable5(center.y), stable5(center.z)], [rotation.x, rotation.y, rotation.z, rotation.w]),+ halfExtents+ });}-function capsuleZGeo(radius, length3, segments = 6) {- const geo = capsuleGeo(radius, length3, segments);- geo.rotateX(Math.PI / 2);- return geo;+function collectParts4(root) {+ root.updateWorldMatrix(true, true);+ const rootInverse = root.matrixWorld.clone().invert();+ const result = [];+ root.traverse((node) => {+ const roles = rolesOf3(node);+ const renderable = node instanceof THREE26.Mesh;+ let box;+ let orientedBox;+ let source;+ if (renderable && node.geometry instanceof THREE26.BufferGeometry) {+ node.geometry.computeBoundingBox();+ if (node.geometry.boundingBox) {+ source = node.geometry.boundingBox;+ }+ } else if (roles.length > 0) {+ source = new THREE26.Box3(new THREE26.Vector3(-0.5, -0.5, -0.5), new THREE26.Vector3(0.5, 0.5, 0.5));+ }+ if (source) {+ box = transformedBox2(source, rootInverse.clone().multiply(node.matrixWorld));+ orientedBox = orientedBoxFromLocalBounds(root, node, source);+ }+ if (box?.isEmpty())+ box = undefined;+ result.push({+ node,+ roles,+ ...box ? { box } : {},+ ...orientedBox ? { orientedBox } : {},+ renderable+ });+ });+ return result;}-function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {- return new THREE27.CylinderGeometry(radiusTop, radiusBottom, height, segments);+function quaternionTuple(value) {+ return [stable5(value.x), stable5(value.y), stable5(value.z), stable5(value.w)];}-function cylinderXGeo(radiusTop, radiusBottom, length3, segments = 8) {- const geo = cylinderGeo(radiusTop, radiusBottom, length3, segments);- geo.rotateZ(-Math.PI / 2);- return geo;+function resolveSocket(root, node, socket) {+ const metadata = readSemanticMetadataV1(node);+ const frame = metadata?.frames.find((candidate) => candidate.id === socket.frame);+ if (!frame)+ return;+ root.updateWorldMatrix(true, true);+ const rootInverse = root.matrixWorld.clone().invert();+ const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE26.Quaternion).invert();+ const rotation = node.getWorldQuaternion(new THREE26.Quaternion).multiply(new THREE26.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();+ return {+ id: socket.id,+ type: socket.type,+ node: node.name || node.type,+ translation: [stable5(point.x), stable5(point.y), stable5(point.z)],+ rotation: quaternionTuple(rotation),+ compatibleTypes: [...socket.compatibleTypes],+ ...socket.allowedRotationsDegrees ? { allowedRotationsDegrees: [...socket.allowedRotationsDegrees] } : {}+ };}-function cylinderZGeo(radiusTop, radiusBottom, length3, segments = 8) {- const geo = cylinderGeo(radiusTop, radiusBottom, length3, segments);- geo.rotateX(Math.PI / 2);- return geo;+function resolveEnvironmentSockets(root) {+ const result = [];+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ for (const socket of metadata?.sockets ?? []) {+ if (!socket.type.startsWith("environment."))+ continue;+ const resolved = resolveSocket(root, node, socket);+ if (resolved)+ result.push(resolved);+ }+ });+ return result.sort((a, b) => `${a.type}:${a.id}`.localeCompare(`${b.type}:${b.id}`));}-function boxGeo(width, height, depth) {- return new THREE27.BoxGeometry(width, height, depth);+function socketByType(sockets, type) {+ return sockets.find((socket) => socket.type === type);}-function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {- return new THREE27.SphereGeometry(radius, widthSegments, heightSegments);+function evaluateEnvironmentSocketQa(context) {+ if (context.intent.category !== "environment" || !(context.scene instanceof THREE26.Object3D)) {+ return [];+ }+ const root = context.scene;+ const sockets = resolveEnvironmentSockets(root);+ const findings = [];+ for (const pair of SOCKET_PAIR_CONTRACTS) {+ const declared = [...pair.negative, ...pair.positive].some((type) => sockets.some((socket) => socket.type === type));+ if (!declared)+ continue;+ for (const side of [pair.negative, pair.positive]) {+ if (side.some((type) => sockets.some((socket) => socket.type === type)))+ continue;+ findings.push(finding4(context, {+ code: "ENV_SOCKET_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Declared ${pair.label} is incomplete; its opposite socket is missing.`,+ affected: { node: root.name || "environment-root" },+ measurement: { name: "declaredPairSocketCount", actual: 0, expected: 1, threshold: 1 },+ viewHints: ["top", "generic.top.semantic-overlay"],+ repairText: `Complete the declared ${pair.label} with ${side.join(" or ")} without inventing unrelated axes or joins.`+ }));+ }+ }+ for (const axis of ["x", "z"]) {+ const negative = socketByType(sockets, `environment.tile.${axis}-negative`);+ const positive = socketByType(sockets, `environment.tile.${axis}-positive`);+ if (!negative || !positive)+ continue;+ const cross = axis === "x" ? 2 : 0;+ const crossDelta = Math.hypot(negative.translation[1] - positive.translation[1], negative.translation[cross] - positive.translation[cross]);+ if (crossDelta <= SOCKET_ALIGNMENT_TOLERANCE_METERS)+ continue;+ findings.push(finding4(context, {+ code: "ENV_SOCKET_PAIR_MISALIGNED",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Opposing ${axis.toUpperCase()} tile sockets differ by ${crossDelta.toFixed(6)} m in their paired height/cross-axis frame.`,+ affected: { node: positive.node, attribute: positive.id },+ measurement: {+ name: "socketCrossAxisDelta",+ actual: stable5(crossDelta),+ expected: 0,+ threshold: SOCKET_ALIGNMENT_TOLERANCE_METERS,+ unit: "m"+ },+ viewHints: ["top", "generic.top.semantic-overlay"],+ repairText: `Align the ${axis}-negative/${axis}-positive socket frames in height and cross-axis offset.`+ }));+ }+ return findings;}-function coneGeo(radius, height, segments = 8) {- return new THREE27.ConeGeometry(radius, height, segments);+function materialSignature(material) {+ const values = Array.isArray(material) ? material : [material];+ return values.map((value) => {+ const standard = value;+ const color = standard.color?.getHexString?.() ?? "none";+ return `${value.type}:${value.name}:${color}`;+ }).sort().join("|");}-function coneXGeo(radius, length3, segments = 8) {- const geo = coneGeo(radius, length3, segments);- geo.rotateZ(-Math.PI / 2);- return geo;+function boundarySamples(root, axis, side, bins = 12) {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const bounds = new THREE26.Box3().setFromObject(root);+ const localBounds = transformedBox2(bounds, root.matrixWorld.clone().invert());+ const edge = side === "negative" ? localBounds.min[axis] : localBounds.max[axis];+ const axisExtent = localBounds.max[axis] - localBounds.min[axis];+ const band = Math.max(0.002, axisExtent * 0.005);+ const crossAxis = axis === "x" ? "z" : "x";+ const crossMin = localBounds.min[crossAxis];+ const crossExtent = Math.max(0.000000001, localBounds.max[crossAxis] - crossMin);+ const byBin = new Map;+ root.traverse((node) => {+ if (!(node instanceof THREE26.Mesh) || !(node.geometry instanceof THREE26.BufferGeometry))+ return;+ const positions = node.geometry.getAttribute("position");+ if (positions?.itemSize !== 3)+ return;+ const normals = node.geometry.getAttribute("normal");+ const transform = inverse.clone().multiply(node.matrixWorld);+ const normalMatrix = new THREE26.Matrix3().getNormalMatrix(transform);+ const material = materialSignature(node.material);+ for (let index = 0;index < positions.count; index++) {+ const point = new THREE26.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);+ if (Math.abs(point[axis] - edge) > band)+ continue;+ const t = THREE26.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);+ const bin = Math.min(bins - 1, Math.floor(t * bins));+ const normal = normals ? new THREE26.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE26.Vector3(0, 1, 0);+ const current = byBin.get(bin);+ if (!current || point.y > current.height || point.y === current.height && normal.y > current.normal.y) {+ byBin.set(bin, { bin, height: point.y, normal, material });+ }+ }+ });+ return Array.from(byBin.values()).sort((a, b) => a.bin - b.bin);}-function coneZGeo(radius, length3, segments = 8) {- const geo = coneGeo(radius, length3, segments);- geo.rotateX(Math.PI / 2);- return geo;+function edgePairMeasurements(root, axis, sockets) {+ const negative = boundarySamples(root, axis, "negative");+ const positive = boundarySamples(root, axis, "positive");+ const negativeByBin = new Map(negative.map((sample) => [sample.bin, sample]));+ const pairs = positive.flatMap((sample) => {+ const other = negativeByBin.get(sample.bin);+ return other ? [[other, sample]] : [];+ });+ const unionBins = new Set([+ ...negative.map((sample) => sample.bin),+ ...positive.map((sample) => sample.bin)+ ]);+ const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;+ const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE26.MathUtils.radToDeg(Math.acos(THREE26.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;+ const materialMismatch = pairs.some(([a, b]) => a.material !== b.material);+ const negativeSocket = socketByType(sockets, `environment.tile.${axis}-negative`);+ const positiveSocket = socketByType(sockets, `environment.tile.${axis}-positive`);+ const crossIndex = axis === "x" ? 2 : 0;+ const socketCrossAxisDelta = negativeSocket && positiveSocket ? Math.hypot(negativeSocket.translation[1] - positiveSocket.translation[1], negativeSocket.translation[crossIndex] - positiveSocket.translation[crossIndex]) : null;+ return {+ axis,+ source: negativeSocket && positiveSocket ? "semantic" : "fallback",+ sampleCoverage: unionBins.size === 0 ? 0 : pairs.length / unionBins.size,+ maximumHeightDelta: stable5(maximumHeightDelta),+ maximumNormalDeltaDegrees: stable5(maximumNormalDeltaDegrees),+ materialMismatch,+ socketCrossAxisDelta: socketCrossAxisDelta === null ? null : stable5(socketCrossAxisDelta)+ };}-function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {- const radiusTop = options.radiusTop ?? radiusBottom;- const segments = options.segments ?? 8;- const geo = new THREE27.CylinderGeometry(radiusTop, radiusBottom, height, segments);- const n = new THREE27.Vector3(normal[0], normal[1], normal[2]);- const len = n.length();- if (len < 0.000001) {- throw new Error(`cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(",")}]).`);+function evaluateEnvironmentTileEdgeQa(context) {+ if (context.intent.category !== "environment" || !context.intent.capabilities.includes("tileable") || !(context.scene instanceof THREE26.Object3D)) {+ return [];}- n.divideScalar(len);- const q = new THREE27.Quaternion().setFromUnitVectors(new THREE27.Vector3(0, 1, 0), n);- geo.applyQuaternion(q);- geo.translate(center[0], center[1], center[2]);- return geo;+ const root = context.scene;+ const sockets = resolveEnvironmentSockets(root);+ const findings = [];+ for (const axis of ["x", "z"]) {+ const measured = edgePairMeasurements(root, axis, sockets);+ const disposition = measured.source === "semantic" ? "block" : "warn";+ if (measured.sampleCoverage < 0.5) {+ findings.push(finding4(context, {+ code: "ENV_TILE_EDGE_EVIDENCE_SPARSE",+ disposition,+ dimension: "categoryReadiness",+ message: `${axis.toUpperCase()} tile edges share only ${(measured.sampleCoverage * 100).toFixed(1)}% sampled boundary coverage.`,+ affected: { node: root.name || "environment-root", attribute: `${axis}-edge` },+ measurement: {+ name: "pairedBoundarySampleCoverage",+ actual: measured.sampleCoverage,+ expected: ">=0.5",+ threshold: 0.5,+ unit: "ratio"+ },+ viewHints: ["top", "right"],+ repairText: `Author matching ${axis}-negative/${axis}-positive boundary vertices and semantic tile sockets.`+ }));+ continue;+ }+ if (measured.maximumHeightDelta > EDGE_HEIGHT_TOLERANCE_METERS) {+ findings.push(finding4(context, {+ code: "ENV_TILE_EDGE_HEIGHT_SEAM",+ disposition,+ dimension: "categoryReadiness",+ message: `${axis.toUpperCase()} tile boundaries differ by ${measured.maximumHeightDelta.toFixed(6)} m.`,+ affected: { node: root.name || "environment-root", attribute: `${axis}-edge-height` },+ measurement: {+ name: "maximumBoundaryHeightDelta",+ actual: measured.maximumHeightDelta,+ expected: 0,+ threshold: EDGE_HEIGHT_TOLERANCE_METERS,+ unit: "m"+ },+ viewHints: ["top", "right"],+ repairText: `Match the sampled ${axis}-negative/${axis}-positive boundary heights without flattening the tile interior.`+ }));+ }+ if (measured.maximumNormalDeltaDegrees > EDGE_NORMAL_TOLERANCE_DEGREES) {+ findings.push(finding4(context, {+ code: "ENV_TILE_EDGE_NORMAL_SEAM",+ disposition,+ dimension: "categoryReadiness",+ message: `${axis.toUpperCase()} tile boundary normals differ by ${measured.maximumNormalDeltaDegrees.toFixed(3)} degrees.`,+ affected: { node: root.name || "environment-root", attribute: `${axis}-edge-normal` },+ measurement: {+ name: "maximumBoundaryNormalDelta",+ actual: measured.maximumNormalDeltaDegrees,+ expected: 0,+ threshold: EDGE_NORMAL_TOLERANCE_DEGREES,+ unit: "deg"+ },+ viewHints: ["top", "three-quarter"],+ repairText: `Align the ${axis}-edge vertex normals while preserving intentional interior shading.`+ }));+ }+ if (measured.materialMismatch) {+ findings.push(finding4(context, {+ code: "ENV_TILE_EDGE_MATERIAL_SEAM",+ disposition,+ dimension: "visualQuality",+ message: `${axis.toUpperCase()} tile boundaries use different material signatures.`,+ affected: { node: root.name || "environment-root", attribute: `${axis}-edge-material` },+ measurement: { name: "boundaryMaterialMismatch", actual: true, expected: false },+ viewHints: ["top", "three-quarter"],+ repairText: `Use the same portable PBR material role on both ${axis} boundary samples.`+ }));+ }+ }+ return findings;}-function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8) {- const geo = new THREE27.CylinderGeometry(radiusTop, radiusBottom, height, segments);- if (axis === "x")- geo.rotateZ(-Math.PI / 2);- else if (axis === "z")- geo.rotateX(Math.PI / 2);- return geo;+function isCorridor(part) {+ return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));}-function torusGeo(radius, tube, radialSegments = 8, tubularSegments = 12) {- return new THREE27.TorusGeometry(radius, tube, radialSegments, tubularSegments);+function evaluateEnvironmentNavigabilityQa(context) {+ if (context.intent.category !== "environment" || !context.intent.capabilities.includes("navigable") || !(context.scene instanceof THREE26.Object3D)) {+ return [];+ }+ const root = context.scene;+ const parts = collectParts4(root);+ const corridors = parts.filter((part) => isCorridor(part));+ if (corridors.length === 0) {+ return [+ finding4(context, {+ code: "ENV_NAV_CLEARANCE_UNASSESSED",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: "navigable=true has no measurable semantic corridor prism; geometry inference cannot hard-gate traversal.",+ affected: { node: root.name || "environment-root" },+ measurement: { name: "semanticCorridorCount", actual: 0, expected: ">=1", threshold: 1 },+ viewHints: ["top", "right"],+ repairText: "Add a scaled non-rendered environment.navigation.corridor.<id> marker through the intended route."+ })+ ];+ }+ const findings = [];+ for (const corridor of corridors) {+ if (!corridor.orientedBox) {+ findings.push(finding4(context, {+ code: "ENV_NAV_CLEARANCE_UNASSESSED",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `Traversal corridor ${corridor.node.name || "(unnamed)"} has a sheared or degenerate transform that cannot be measured safely.`,+ affected: {+ node: corridor.node.name || "navigation-corridor",+ nodePath: nodePath3(root, corridor.node)+ },+ measurement: { name: "orientedCorridorEvidence", actual: false, expected: true },+ viewHints: ["top", "right"],+ repairText: "Author the corridor marker with a finite non-sheared local transform."+ }));+ continue;+ }+ const width = Math.min(corridor.orientedBox.halfExtents[0] * 2, corridor.orientedBox.halfExtents[2] * 2);+ const height = corridor.orientedBox.halfExtents[1] * 2;+ if (width + 0.000001 < 0.8) {+ findings.push(finding4(context, {+ code: "ENV_NAV_CORRIDOR_TOO_NARROW",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `Traversal corridor ${corridor.node.name || "(unnamed)"} is only ${width.toFixed(4)} m wide.`,+ affected: {+ node: corridor.node.name || "navigation-corridor",+ nodePath: nodePath3(root, corridor.node)+ },+ measurement: {+ name: "minimumCorridorWidth",+ actual: stable5(width),+ expected: ">=0.8",+ threshold: 0.8,+ unit: "m"+ },+ viewHints: ["top", "right"],+ repairText: "Widen only the declared corridor to at least 0.8 m while preserving surrounding structure."+ }));+ }+ if (height + 0.000001 < 1.8) {+ findings.push(finding4(context, {+ code: "ENV_NAV_HEADROOM_TOO_LOW",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `Traversal corridor ${corridor.node.name || "(unnamed)"} has only ${height.toFixed(4)} m headroom.`,+ affected: {+ node: corridor.node.name || "navigation-corridor",+ nodePath: nodePath3(root, corridor.node)+ },+ measurement: {+ name: "minimumCorridorHeadroom",+ actual: stable5(height),+ expected: ">=1.8",+ threshold: 1.8,+ unit: "m"+ },+ viewHints: ["right", "three-quarter"],+ repairText: "Raise or clear only the corridor ceiling to provide at least 1.8 m headroom."+ }));+ }+ const blocker = parts.find((part) => part.renderable && part.orientedBox && part.node !== corridor.node && !part.roles.some((role) => role.startsWith("environment.ground") || role.startsWith("environment.surface") || role.startsWith("environment.path.surface") || role.startsWith("environment.bridge.deck")) && !probeOrientedPenetration(part.orientedBox, corridor.orientedBox, {+ maxDepth: 0,+ tolerance: 0.004+ }).pass);+ if (blocker) {+ findings.push(finding4(context, {+ code: "ENV_NAV_CORRIDOR_BLOCKED",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Traversal corridor ${corridor.node.name || "(unnamed)"} is blocked by ${blocker.node.name || "an unnamed mesh"}.`,+ affected: {+ node: blocker.node.name || "navigation-blocker",+ nodePath: nodePath3(root, blocker.node)+ },+ measurement: { name: "corridorBlockerCount", actual: 1, expected: 0, threshold: 0 },+ viewHints: ["top", "right"],+ repairText: "Remove or split only the reported blocker from the declared navigation corridor."+ }));+ }+ }+ return findings;}-function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {- return new THREE27.PlaneGeometry(width, height, widthSegments, heightSegments);+function horizontalOverlap(a, b) {+ return a.min.x < b.max.x && a.max.x > b.min.x && a.min.z < b.max.z && a.max.z > b.min.z;}-function decalBox(width, height, depth = 0.01) {- const d = Math.max(depth, 0.002);- return new THREE27.BoxGeometry(width, height, d);+function intentionalGround(part) {+ return part.roles.some((role) => role.startsWith("environment.ground") || role.startsWith("environment.terrain.volume") || role.startsWith("environment.cliff.volume"));}-function foliageCardGeo(opts = {}) {- const w = opts.width ?? 1;- const h = opts.height ?? 1;- const yPivot = opts.yPivot ?? 0;- const geom = new THREE27.PlaneGeometry(w, h);- geom.translate(0, h * (0.5 - yPivot), 0);- geom.userData["kilnGeometryRole"] = "foliageCard";- return geom;+function functionalLayer(part) {+ return part.roles.some((role) => role.startsWith("environment.functional") || role.startsWith("environment.layer") || role.startsWith("environment.path") || role.startsWith("environment.road") || role.startsWith("environment.bridge") || role.startsWith("environment.gate"));}-function crossedQuadsGeo(opts = {}) {- const w = opts.width ?? 1;- const h = opts.height ?? 1;- const planes = opts.planes ?? 2;- const yPivot = opts.yPivot ?? 0;- const geometries = [];- for (let i = 0;i < planes; i++) {- const angle2 = i / planes * Math.PI;- const quad = new THREE27.PlaneGeometry(w, h);- quad.translate(0, h * (0.5 - yPivot), 0);- quad.rotateY(angle2);- geometries.push(quad);+function evaluateEnvironmentGroundQa(context) {+ if (context.intent.category !== "environment" || !(context.scene instanceof THREE26.Object3D)) {+ return [];}- const out = new THREE27.BufferGeometry;- const posCount = geometries.reduce((sum, g) => sum + (g.attributes.position?.count ?? 0), 0);- const positions = new Float32Array(posCount * 3);- const normals = new Float32Array(posCount * 3);- const uvs = new Float32Array(posCount * 2);- const indices = [];- let vOffset = 0;- for (const g of geometries) {- const p = g.attributes.position;- const n = g.attributes.normal;- const uv = g.attributes.uv;- for (let i = 0;i < p.count; i++) {- positions[(vOffset + i) * 3] = p.getX(i);- positions[(vOffset + i) * 3 + 1] = p.getY(i);- positions[(vOffset + i) * 3 + 2] = p.getZ(i);- normals[(vOffset + i) * 3] = n.getX(i);- normals[(vOffset + i) * 3 + 1] = n.getY(i);- normals[(vOffset + i) * 3 + 2] = n.getZ(i);- uvs[(vOffset + i) * 2] = uv.getX(i);- uvs[(vOffset + i) * 2 + 1] = uv.getY(i);+ const root = context.scene;+ const parts = collectParts4(root).filter((part) => part.renderable && part.box);+ const findings = [];+ for (const part of parts) {+ const box = part.box;+ if (intentionalGround(part))+ continue;+ if (functionalLayer(part) && box.min.y < -GROUND_TOLERANCE_METERS2) {+ findings.push(finding4(context, {+ code: "ENV_FUNCTIONAL_PART_BURIED",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${part.node.name || "Functional environment part"} is buried ${Math.abs(box.min.y).toFixed(6)} m below asset-local ground.`,+ affected: {+ node: part.node.name || "environment-part",+ nodePath: nodePath3(root, part.node)+ },+ measurement: {+ name: "minimumY",+ actual: stable5(box.min.y),+ expected: ">=-0.02",+ threshold: GROUND_TOLERANCE_METERS2,+ unit: "m"+ },+ viewHints: ["right", "three-quarter"]+ }));}- const idx = g.index;- for (let i = 0;i < idx.count; i++) {- indices.push(idx.getX(i) + vOffset);+ if (functionalLayer(part) && box.min.y > GROUND_TOLERANCE_METERS2) {+ const supported = parts.some((support) => support !== part && support.box && horizontalOverlap(box, support.box) && Math.abs(support.box.max.y - box.min.y) <= 0.04);+ if (!supported) {+ findings.push(finding4(context, {+ code: "ENV_LAYER_UNSUPPORTED",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${part.node.name || "Environment layer"} floats without a contacting support.`,+ affected: {+ node: part.node.name || "environment-layer",+ nodePath: nodePath3(root, part.node)+ },+ measurement: { name: "supportContactCount", actual: 0, expected: ">=1", threshold: 1 },+ viewHints: ["right", "three-quarter"]+ }));+ }+ }+ const size = box.getSize(new THREE26.Vector3);+ if (box.min.y < -0.05 && size.y <= Math.max(0.05, Math.min(size.x, size.z) * 0.03) && Math.max(size.x, size.z) >= 1) {+ findings.push(finding4(context, {+ code: "ENV_GROUND_UNDECLARED_SKIRT",+ disposition: "warn",+ dimension: "promptAlignment",+ message: `${part.node.name || "Environment layer"} resembles an undeclared below-ground skirt rather than intentional terrain volume.`,+ affected: {+ node: part.node.name || "environment-skirt",+ nodePath: nodePath3(root, part.node)+ },+ measurement: {+ name: "skirtThickness",+ actual: stable5(size.y),+ expected: "declared terrain volume or supported layer",+ unit: "m"+ },+ viewHints: ["right", "three-quarter"]+ }));}- vOffset += p.count;- }- out.setAttribute("position", new THREE27.BufferAttribute(positions, 3));- out.setAttribute("normal", new THREE27.BufferAttribute(normals, 3));- out.setAttribute("uv", new THREE27.BufferAttribute(uvs, 2));- out.setIndex(indices);- out.userData["kilnGeometryRole"] = "foliageCard";- return out;-}-function octaGridPlane(opts) {- const w = opts.width ?? 1;- const h = opts.height ?? 1;- const yPivot = opts.yPivot ?? 0;- const geom = new THREE27.PlaneGeometry(w, h);- geom.translate(0, h * (0.5 - yPivot), 0);- const uv = geom.attributes.uv;- const du = 1 / opts.tilesX;- const dv = 1 / opts.tilesY;- for (let i = 0;i < uv.count; i++) {- uv.setX(i, uv.getX(i) * du);- uv.setY(i, 1 - dv + uv.getY(i) * dv);}- uv.needsUpdate = true;- return geom;+ return findings;}-function wingGeo(options = {}) {- const span = options.span ?? 1;- const rootChord = options.rootChord ?? 0.6;- const tipChord = options.tipChord ?? rootChord * 0.5;- const sweep2 = options.sweep ?? 0;- const thickness = options.thickness ?? 0.04;- const dihedral = options.dihedral ?? 0;- const rootLead = rootChord / 2;- const rootTrail = -rootChord / 2;- const tipLead = rootLead - sweep2;- const tipTrail = tipLead - tipChord;- const halfThickness = thickness / 2;- const vertices = new Float32Array([- rootLead,- halfThickness,- 0,- rootTrail,- halfThickness,- 0,- tipLead,- dihedral + halfThickness,- span,- tipTrail,- dihedral + halfThickness,- span,- rootLead,- -halfThickness,- 0,- rootTrail,- -halfThickness,- 0,- tipLead,- dihedral - halfThickness,- span,- tipTrail,- dihedral - halfThickness,- span- ]);- const indices = [- 0,- 3,- 2,- 0,- 1,- 3,- 4,- 6,- 7,- 4,- 7,- 5,- 0,- 2,- 6,- 0,- 6,- 4,- 1,- 5,- 7,- 1,- 7,- 3,- 0,- 4,- 5,- 0,- 5,- 1,- 2,- 3,- 7,- 2,- 7,- 6+var PROFILE4 = "environment.semantic", EDGE_HEIGHT_TOLERANCE_METERS = 0.02, EDGE_NORMAL_TOLERANCE_DEGREES = 8, SOCKET_ALIGNMENT_TOLERANCE_METERS = 0.02, GROUND_TOLERANCE_METERS2 = 0.02, stable5 = (value) => Math.round(value * 1e6) / 1e6, SOCKET_PAIR_CONTRACTS, ENVIRONMENT_EXACT_QA_RULE, ENVIRONMENT_ADVISORY_QA_RULE, ENVIRONMENT_QA_RULES;+var init_environment2 = __esm(() => {+ init_contracts();+ init_registry();+ init_environment();+ SOCKET_PAIR_CONTRACTS = [+ {+ label: "X tile axis",+ negative: ["environment.tile.x-negative"],+ positive: ["environment.tile.x-positive"]+ },+ {+ label: "Z tile axis",+ negative: ["environment.tile.z-negative"],+ positive: ["environment.tile.z-positive"]+ },+ {+ label: "road join",+ negative: ["environment.road.start"],+ positive: ["environment.road.end"]+ },+ {+ label: "bridge join",+ negative: ["environment.bridge.start"],+ positive: ["environment.bridge.end"]+ },+ {+ label: "wall/gate join",+ negative: ["environment.wall.left", "environment.gate.left"],+ positive: ["environment.wall.right", "environment.gate.right"]+ }+ ];+ ENVIRONMENT_EXACT_QA_RULE = Object.freeze({+ id: "ENVIRONMENT_EXACT_PROFILE",+ profile: PROFILE4,+ scope: { kind: "category", category: "environment" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("environment-semantic-v1", "src/qa/environment.test.ts", "13b0c50894074bf93a5dd9eb1c93e519b030312e030e5123493a4833a1438b28"),+ defaultMode: "enforce",+ evaluate: (context) => [+ ...evaluateEnvironmentSocketQa(context),+ ...evaluateEnvironmentTileEdgeQa(context).filter((value) => value.disposition === "block"),+ ...evaluateEnvironmentNavigabilityQa(context).filter((value) => value.disposition === "block")+ ]+ });+ ENVIRONMENT_ADVISORY_QA_RULE = Object.freeze({+ id: "ENVIRONMENT_ADVISORY_PROFILE",+ profile: "environment.advisory",+ scope: { kind: "category", category: "environment" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: (context) => [+ ...evaluateEnvironmentTileEdgeQa(context).filter((value) => value.disposition !== "block"),+ ...evaluateEnvironmentNavigabilityQa(context).filter((value) => value.disposition !== "block"),+ ...evaluateEnvironmentGroundQa(context)+ ]+ });+ ENVIRONMENT_QA_RULES = [+ ENVIRONMENT_EXACT_QA_RULE,+ ENVIRONMENT_ADVISORY_QA_RULE];- const geo = new THREE27.BufferGeometry;- geo.setAttribute("position", new THREE27.BufferAttribute(vertices, 3));- geo.setIndex(indices);- geo.computeVertexNormals();- return geo;+});++// src/qa/breadth.ts+function validModularJoinObservation(value) {+ if (!record2(value))+ return false;+ return typeof value.aSocketId === "string" && value.aSocketId.length > 0 && typeof value.bSocketId === "string" && value.bSocketId.length > 0 && finiteTuple2(value.aWorldPosition, 3) && finiteTuple2(value.bWorldPosition, 3) && finiteTuple2(value.aWorldNormal, 3) && finiteTuple2(value.bWorldNormal, 3) && typeof value.relativeRotationDegrees === "number" && Number.isFinite(value.relativeRotationDegrees) && (value.toleranceMeters === undefined || typeof value.toleranceMeters === "number" && Number.isFinite(value.toleranceMeters) && value.toleranceMeters >= 0) && (value.normalToleranceDegrees === undefined || typeof value.normalToleranceDegrees === "number" && Number.isFinite(value.normalToleranceDegrees) && value.normalToleranceDegrees >= 0);}-function createWingPair(name, material, options) {- const { parent, rootX = 0, rootY = 0, rootZ, ...wingOptions } = options;- const rightGeo = wingGeo(wingOptions);- const leftGeo = wingGeo(wingOptions);- leftGeo.scale(1, 1, -1);- leftGeo.computeVertexNormals();+function validVfxArtifactEvidence(value) {+ if (!record2(value) || value.schemaVersion !== 1)+ return false;+ if (!record2(value.facing) || !record2(value.animation))+ return false;+ if (!Array.isArray(value.materials))+ return false;+ if (!Array.isArray(value.clips) || !Array.isArray(value.uniforms))+ return false;+ if (!value.uniforms.every((name) => typeof name === "string" && name.length > 0))+ return false;+ if (!value.clips.every((clip) => record2(clip) && typeof clip.name === "string" && clip.name.length > 0 && typeof clip.durationSeconds === "number" && Number.isFinite(clip.durationSeconds) && clip.durationSeconds >= 0)) {+ return false;+ }+ return value.materials.every((material) => record2(material) && typeof material.id === "string" && material.id.length > 0 && ["card", "beam", "trail", "volume", "core"].includes(String(material.surfaceRole)) && ["opaque", "mask", "blend"].includes(String(material.alphaMode)) && (material.effectSurface === undefined || typeof material.effectSurface === "boolean") && typeof material.alphaData === "boolean" && typeof material.doubleSided === "boolean" && typeof material.screenAreaRatio === "number" && Number.isFinite(material.screenAreaRatio) && material.screenAreaRatio >= 0 && typeof material.transparentLayers === "number" && Number.isInteger(material.transparentLayers) && material.transparentLayers >= 0 && typeof material.textureMemoryBytes === "number" && Number.isInteger(material.textureMemoryBytes) && material.textureMemoryBytes >= 0);+}+function artifactEvidence(context) {+ if (context.derivedEvidence?.source !== "engine-scene-analysis")+ return;+ const candidate = context.derivedEvidence.vfxArtifact;+ return validVfxArtifactEvidence(candidate) ? candidate : undefined;+}+function finding5(context, value, profile = "vfx.w7") {+ return { ...value, profile: context.intent.qaProfile || profile };+}+function measureVfxRuntimeCostV1(evidence) {+ let blendedScreenAreaRatio = 0;+ let transparentLayerCount = 0;+ let overdrawProxy = 0;+ let textureMemoryBytes = 0;+ for (const material of evidence.materials) {+ textureMemoryBytes += material.textureMemoryBytes;+ if (material.alphaMode !== "blend")+ continue;+ blendedScreenAreaRatio += material.screenAreaRatio;+ transparentLayerCount += material.transparentLayers;+ overdrawProxy += material.screenAreaRatio * Math.max(1, material.transparentLayers);+ }return {- right: createPart(`${name}Right`, rightGeo, material, {- position: [rootX, rootY, rootZ],- parent- }),- left: createPart(`${name}Left`, leftGeo, material, {- position: [rootX, rootY, -rootZ],- parent- })+ schemaVersion: 1,+ blendedScreenAreaRatio: stable6(blendedScreenAreaRatio),+ transparentLayerCount,+ overdrawProxy: stable6(overdrawProxy),+ textureMemoryBytes,+ shaderSidecarRequired: evidence.sidecar !== undefined};}-function beamBetween(name, start, end, radius, material, options = {}) {- const a = new THREE27.Vector3(...start);- const b = new THREE27.Vector3(...end);- const direction = b.clone().sub(a);- const length3 = direction.length();- if (length3 <= 0.0001) {- throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length3.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);+function exactVfxIntent(context) {+ const candidate = context.intent.vfx;+ const validated = validateVfxIntentV1(candidate);+ if (!validated.valid || !validated.value) {+ return {+ findings: [+ finding5(context, {+ code: "VFX_INTENT_INVALID",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Trusted VFX intent is missing or invalid: ${validated.issues.map((issue) => `${issue.path || "<root>"}:${issue.code}`).join(", ")}`,+ measurement: {+ name: "vfxIntentIssueCount",+ actual: validated.issues.length,+ expected: 0+ },+ repairText: "Return to request normalization; model-authored source cannot repair trusted intent."+ })+ ]+ };+ }+ const evidence = artifactEvidence(context);+ if (!evidence) {+ return {+ findings: [+ finding5(context, {+ code: "VFX_RUNTIME_CONTRACT_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "VFX output is missing its versioned facing/material/animation runtime evidence.",+ measurement: { name: "vfxEvidencePresent", actual: false, expected: true },+ repairText: "Return a renderable Three.js scene so the engine can analyze actual materials, facing behavior, clips/uniforms, and sidecar availability."+ })+ ]+ };+ }+ return { intent: validated.value, evidence };+}+function evaluateVfxExactQa(context) {+ if (context.intent.category !== "vfx")+ return [];+ const resolved = exactVfxIntent(context);+ if ("findings" in resolved)+ return resolved.findings;+ const { intent, evidence } = resolved;+ const findings = [];+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface !== false);+ if (effectMaterials.length === 0) {+ findings.push(finding5(context, {+ code: "VFX_EFFECT_SURFACE_MISSING",+ disposition: "block",+ dimension: "exportIntegrity",+ message: "VFX output has no explicitly analyzed effect-surface material.",+ measurement: { name: "effectMaterialCount", actual: 0, expected: ">=1" },+ repairText: "Stamp effect-rendering nodes with vfx.effect.surface.* and keep opaque support geometry in vfx.support.* roles."+ }));+ }+ for (const material of effectMaterials) {+ if (material.alphaMode !== intent.transparency) {+ findings.push(finding5(context, {+ code: "VFX_TRANSPARENCY_MODE_MISMATCH",+ disposition: "block",+ dimension: "exportIntegrity",+ message: `${material.id} exported ${material.alphaMode} but trusted VFX intent requires ${intent.transparency}.`,+ affected: { material: material.id },+ measurement: {+ name: "alphaMode",+ actual: material.alphaMode,+ expected: intent.transparency+ },+ repairText: `Set ${material.id} to the declared ${intent.transparency} alpha mode without changing unrelated materials.`+ }));+ }+ if (intent.transparency !== "opaque" && !material.alphaData) {+ findings.push(finding5(context, {+ code: "VFX_ALPHA_DATA_MISSING",+ disposition: "block",+ dimension: "exportIntegrity",+ message: `${material.id} declares ${intent.transparency} but has no alpha-bearing factor or texture data.`,+ affected: { material: material.id },+ measurement: { name: "alphaData", actual: false, expected: true },+ repairText: `Add alpha-bearing data to ${material.id}; do not leave an opaque effect-card rectangle.`+ }));+ }+ if (material.doubleSided !== intent.doubleSided) {+ findings.push(finding5(context, {+ code: "VFX_SIDEDNESS_MISMATCH",+ disposition: "block",+ dimension: "exportIntegrity",+ message: `${material.id} sidedness does not match trusted VFX intent.`,+ affected: { material: material.id },+ measurement: {+ name: "doubleSided",+ actual: material.doubleSided,+ expected: intent.doubleSided+ },+ repairText: `Set ${material.id} doubleSided=${intent.doubleSided}.`+ }));+ }+ if (intent.transparency === "mask" && (material.alphaCutoff === undefined || !Number.isFinite(material.alphaCutoff) || material.alphaCutoff <= 0 || material.alphaCutoff > 1)) {+ findings.push(finding5(context, {+ code: "VFX_ALPHA_CUTOFF_INVALID",+ disposition: "block",+ dimension: "exportIntegrity",+ message: `${material.id} uses MASK without a finite cutoff in (0, 1].`,+ affected: { material: material.id },+ measurement: {+ name: "alphaCutoff",+ actual: material.alphaCutoff ?? null,+ expected: "0 < cutoff <= 1"+ },+ repairText: `Set a valid alpha cutoff on ${material.id}.`+ }));+ }+ }+ const facingFields = ["mode", "normalAxis", "directionAxis"];+ for (const field of facingFields) {+ if (intent.facing[field] === evidence.facing[field])+ continue;+ if (intent.facing.source !== "explicit")+ continue;+ findings.push(finding5(context, {+ code: "VFX_FACING_CONTRACT_MISMATCH",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Explicit VFX facing ${field} does not match the emitted runtime contract.`,+ measurement: {+ name: `facing.${field}`,+ actual: evidence.facing[field] ?? null,+ expected: intent.facing[field] ?? null+ },+ repairText: `Stamp and implement the requested ${field}; preserve the canonical Kiln frame.`+ }));+ }+ const requestedAnimation = intent.animation;+ const actualAnimation = evidence.animation;+ for (const field of ["playback", "endpointBehavior", "driver"]) {+ if (requestedAnimation[field] === actualAnimation[field])+ continue;+ findings.push(finding5(context, {+ code: "VFX_ANIMATION_POLICY_MISMATCH",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `VFX animation ${field} does not match trusted intent.`,+ measurement: {+ name: `animation.${field}`,+ actual: actualAnimation[field],+ expected: requestedAnimation[field]+ },+ repairText: `Implement the declared ${field} without changing the effect subtype.`+ }));+ }+ if (Math.abs(requestedAnimation.durationSeconds - actualAnimation.durationSeconds) > 0.000001) {+ findings.push(finding5(context, {+ code: "VFX_ANIMATION_DURATION_MISMATCH",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "VFX animation duration does not match trusted intent.",+ measurement: {+ name: "animation.durationSeconds",+ actual: actualAnimation.durationSeconds,+ expected: requestedAnimation.durationSeconds,+ threshold: 0.000001,+ unit: "s"+ },+ repairText: "Use the declared duration and resample endpoint keys deterministically."+ }));+ }+ if (requestedAnimation.playback === "loop" && !actualAnimation.endpointMatches) {+ findings.push(finding5(context, {+ code: "VFX_LOOP_ENDPOINT_MISMATCH",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "Looping VFX does not return to its start state at the declared endpoint.",+ measurement: { name: "endpointMatches", actual: false, expected: true },+ repairText: "Make the final loop sample equal the initial sample for every driven channel."+ }));+ }+ if (requestedAnimation.driver === "clip" && !evidence.clips.some((clip) => clip.name === requestedAnimation.clipName && Math.abs(clip.durationSeconds - requestedAnimation.durationSeconds) <= 0.000001)) {+ findings.push(finding5(context, {+ code: "VFX_REQUIRED_CLIP_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "The declared VFX clip name/duration is absent from the artifact evidence.",+ affected: { clip: requestedAnimation.clipName ?? "<missing>" },+ repairText: `Emit clip ${requestedAnimation.clipName ?? "<declared clip>"} with the requested duration.`+ }));+ }+ if (requestedAnimation.driver === "timeUniform" && !evidence.uniforms.includes(requestedAnimation.timeUniformName ?? "")) {+ findings.push(finding5(context, {+ code: "VFX_REQUIRED_TIME_UNIFORM_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "The declared runtime time uniform is absent from the sidecar evidence.",+ measurement: {+ name: "timeUniformName",+ actual: evidence.uniforms.join(","),+ expected: requestedAnimation.timeUniformName ?? null+ },+ repairText: `Expose ${requestedAnimation.timeUniformName ?? "the declared uniform"} in the runtime sidecar.`+ }));}- const mesh = new THREE27.Mesh(cylinderGeo(radius, radius, length3, options.segments ?? 8), material);- mesh.name = `Mesh_${name}`;- mesh.position.copy(a.add(b).multiplyScalar(0.5));- mesh.quaternion.setFromUnitVectors(new THREE27.Vector3(0, 1, 0), direction.normalize());- if (options.parent)- options.parent.add(mesh);- return mesh;+ if (intent.portability === "portable" && evidence.sidecar !== undefined) {+ findings.push(finding5(context, {+ code: "VFX_UNDECLARED_SIDECAR",+ disposition: "block",+ dimension: "exportIntegrity",+ message: "Portable VFX unexpectedly requires a runtime shader sidecar.",+ repairText: "Bake the portable appearance into standard glTF materials or update trusted intent before spend."+ }));+ }+ if (intent.portability === "sidecar" && (evidence.sidecar?.id !== intent.sidecar?.id || evidence.sidecar?.version !== intent.sidecar?.version)) {+ findings.push(finding5(context, {+ code: "VFX_SIDECAR_IDENTITY_MISMATCH",+ disposition: "block",+ dimension: "exportIntegrity",+ message: "Runtime VFX sidecar identity/version does not match trusted intent.",+ measurement: {+ name: "sidecarIdentity",+ actual: evidence.sidecar ? `${evidence.sidecar.id}@${evidence.sidecar.version}` : null,+ expected: intent.sidecar ? `${intent.sidecar.id}@${intent.sidecar.version}` : null+ },+ repairText: "Attach the exact declared sidecar identity and keep the GLB fallback honest."+ }));+ }+ return findings;}-function snapTo(part, host, options = {}) {- const overlap = options.overlap ?? 0.02;- part.updateMatrixWorld(true);- host.updateMatrixWorld(true);- const a = new THREE27.Box3().setFromObject(part);- const b = new THREE27.Box3().setFromObject(host);- if (a.isEmpty() || b.isEmpty())- return part;- const delta = new THREE27.Vector3;- for (const axis of ["x", "y", "z"]) {- if (a.min[axis] > b.max[axis])- delta[axis] = b.max[axis] - a.min[axis];- else if (a.max[axis] < b.min[axis])- delta[axis] = b.min[axis] - a.max[axis];+function evaluateVfxAdvisoryQa(context) {+ if (context.intent.category !== "vfx")+ return [];+ const intent = context.intent.vfx;+ const validated = validateVfxIntentV1(intent);+ const evidence = artifactEvidence(context);+ if (!validated.valid || !validated.value || !evidence)+ return [];+ const findings = [];+ if (validated.value.facing.source === "inferred") {+ const mismatch = ["mode", "normalAxis", "directionAxis"].some((field) => validated.value?.facing[field] !== evidence.facing[field]);+ if (mismatch) {+ findings.push(finding5(context, {+ code: "VFX_FACING_INFERRED_DRIFT",+ disposition: "observe",+ dimension: "categoryReadiness",+ message: "Inferred VFX facing differs from emitted metadata; review the named views.",+ viewHints: ["front", "right", "three-quarter"]+ }));+ }}- if (delta.lengthSq() === 0)- return part;- const dominant = options.axis ?? ["x", "y", "z"].reduce((d, axis) => Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d, "x");- if (delta[dominant] !== 0)- delta[dominant] += Math.sign(delta[dominant]) * overlap;- else- delta[dominant] = -overlap;- const parent = part.parent;- if (parent) {- const p0 = new THREE27.Vector3;- part.getWorldPosition(p0);- const p1 = p0.clone().add(delta);- const l0 = parent.worldToLocal(p0.clone());- const l1 = parent.worldToLocal(p1.clone());- part.position.add(l1.sub(l0));- } else {- part.position.add(delta);+ const cost = measureVfxRuntimeCostV1(evidence);+ findings.push(finding5(context, {+ code: "VFX_RUNTIME_COST_REPORT",+ disposition: "observe",+ dimension: "runtimeCost",+ message: "VFX transparency/runtime cost is reported separately from instanceability.",+ measurement: {+ name: "vfxRuntimeCost",+ actual: `blendArea=${cost.blendedScreenAreaRatio};layers=${cost.transparentLayerCount};overdraw=${cost.overdrawProxy};textureBytes=${cost.textureMemoryBytes};sidecar=${cost.shaderSidecarRequired}`+ },+ viewHints: ["front", "right", "three-quarter"]+ }));+ if (cost.overdrawProxy > 2 || cost.textureMemoryBytes > 32 * 1024 * 1024) {+ findings.push(finding5(context, {+ code: "VFX_RUNTIME_PRESSURE",+ disposition: "observe",+ dimension: "runtimeCost",+ message: "VFX exceeds the observe-mode overdraw or texture-memory review threshold.",+ measurement: {+ name: "overdrawProxy",+ actual: cost.overdrawProxy,+ threshold: 2,+ unit: "screen-layers"+ }+ }));}- part.updateMatrixWorld(true);- return part;+ return findings;}-function createLadder(name, options) {- const {- bottom,- top,- material,- width = 0.42,- rungCount = 6,- railRadius = 0.025,- rungRadius = 0.02,- segments = 6,- widthAxis = "x",- parent- } = options;- const bottomVec = new THREE27.Vector3(...bottom);- const topVec = new THREE27.Vector3(...top);- const offset = widthAxis === "x" ? new THREE27.Vector3(width / 2, 0, 0) : new THREE27.Vector3(0, 0, width / 2);- const leftBottom = bottomVec.clone().sub(offset);- const leftTop = topVec.clone().sub(offset);- const rightBottom = bottomVec.clone().add(offset);- const rightTop = topVec.clone().add(offset);- const leftRail = beamBetween(`${name}LeftRail`, vectorToTuple(leftBottom), vectorToTuple(leftTop), railRadius, material, { parent, segments });- const rightRail = beamBetween(`${name}RightRail`, vectorToTuple(rightBottom), vectorToTuple(rightTop), railRadius, material, { parent, segments });- const rungs = [];- for (let i = 0;i < rungCount; i++) {- const t = (i + 1) / (rungCount + 1);- const center = bottomVec.clone().lerp(topVec, t);- rungs.push(beamBetween(`${name}Rung${i + 1}`, vectorToTuple(center.clone().sub(offset)), vectorToTuple(center.clone().add(offset)), rungRadius, material, { parent, segments }));+function evaluateModularJoinQa(context) {+ if (context.intent.scope.scope !== "modularSet" || !context.intent.scope.explicit)+ return [];+ const modularKit = context.derivedEvidence?.modularKit;+ const modularJoin = context.derivedEvidence?.modularJoin;+ const validation = validateModularKitContractV1(modularKit);+ if (!validation.valid || !validation.value || !validModularJoinObservation(modularJoin)) {+ return [+ finding5(context, {+ code: "MODULAR_CONTRACT_INVALID",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Explicit modular-set intent requires a valid grid/units/socket contract and join observation: ${validation.issues.map((issue) => issue.code).join(", ")}`,+ repairText: "Emit the requested modular socket metadata; do not infer a noun-specific primitive."+ }, "modular.w7")+ ];}- return { leftRail, rightRail, rungs };+ const result = evaluateModularJoinV1(validation.value, modularJoin);+ if (result.pass)+ return [];+ return result.codes.map((code) => finding5(context, {+ code,+ disposition: "block",+ dimension: "categoryReadiness",+ message: `Explicit modular join failed ${code}: seam=${result.seamMeters} m, overlap=${result.overlapMeters} m, lateral=${result.lateralOffsetMeters} m.`,+ measurement: {+ name: "modularJoinError",+ actual: Math.max(result.seamMeters, result.overlapMeters, result.lateralOffsetMeters),+ expected: 0,+ threshold: result.toleranceMeters,+ unit: "m"+ },+ repairText: "Snap the named compatible sockets on the declared meter grid using an allowed rotation."+ }, "modular.w7"));}-function wallWithOpening(name, material, options) {- const { length: length3, height, thickness, axis = "z", opening, parent } = options;- const group = new THREE27.Object3D;- group.name = name;- const overlap = 0.02;- const panel = (suffix, lenStart, lenEnd, yLo, yHi) => {- const segLen = lenEnd - lenStart;- const segH = yHi - yLo;- if (segLen <= 0.0001 || segH <= 0.0001)- return;- const lenC = (lenStart + lenEnd) / 2;- const yC = (yLo + yHi) / 2;- const geo = axis === "z" ? boxGeo(thickness, segH, segLen) : boxGeo(segLen, segH, thickness);- const pos = axis === "z" ? [0, yC, lenC] : [lenC, yC, 0];- createPart(`${name}${suffix}`, geo, material, { position: pos, parent: group });- };- if (!opening) {- panel("", -length3 / 2, length3 / 2, 0, height);- } else {- const ow = opening.width ?? (opening.kind === "window" ? 1 : 1.1);- const oh = opening.height ?? (opening.kind === "window" ? 1 : 2.1);- const off = opening.offset ?? 0;- const left = off - ow / 2;- const right = off + ow / 2;- const sill = opening.kind === "window" ? Math.max(opening.sill ?? 1, 0) : 0;- const top = Math.min(sill + oh, height);- panel("_L", -length3 / 2, left, 0, height);- panel("_R", right, length3 / 2, 0, height);- panel("_Lintel", left - overlap, right + overlap, top, height);- if (sill > 0)- panel("_Sill", left - overlap, right + overlap, 0, sill);+function evaluateAssetScopeQa(context) {+ const scope = context.intent.scope;+ const scopeObservation = context.derivedEvidence?.assetScope;+ if (context.derivedEvidence?.source !== "engine-scene-analysis" || !record2(scopeObservation) || typeof scopeObservation.topLevelAssetRoots !== "number" || typeof scopeObservation.reusableMemberCount !== "number" || !Array.isArray(scopeObservation.sceneDressingRoles)) {+ return [];}- if (parent)- parent.add(group);- return group;+ const result = assessAssetScopeV1(scope, scopeObservation);+ if (result.status === "pass" || !result.code)+ return [];+ return [+ finding5(context, {+ code: result.code,+ disposition: "observe",+ dimension: "promptAlignment",+ message: `Requested ${result.requested} scope produced ${result.observed} evidence: ${result.evidence.join("; ")}.`,+ measurement: {+ name: "explicitSingleViolation",+ actual: result.explicitSingleViolation,+ expected: false+ },+ viewHints: ["top", "three-quarter"]+ }, "scope.w7")+ ];}-function room(name, material, options = {}) {- const {- width = 4,- depth = 4,- height = 2.8,- wallThickness = 0.15,- floor = true,- floorThickness = 0.1,- parent- } = options;- const openings = options.openings ?? [{ wall: "front", kind: "door" }];- const root = new THREE27.Object3D;- root.name = name;- const openingFor = (wall2) => {- const found = openings.find((op) => op.wall === wall2);- if (!found)- return;- const { wall: _wall, ...rest } = found;- return rest;+var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), stable6 = (value) => Math.round(value * 1e6) / 1e6, finiteTuple2 = (value, length) => Array.isArray(value) && value.length === length && value.every((component) => typeof component === "number" && Number.isFinite(component)), VFX_EXACT_QA_RULE, VFX_ADVISORY_QA_RULE, MODULAR_JOIN_QA_RULE, ASSET_SCOPE_QA_RULE, W7_BREADTH_QA_RULES;+var init_breadth2 = __esm(() => {+ init_breadth();+ init_registry();+ VFX_EXACT_QA_RULE = {+ id: "VFX_EXACT_PROFILE",+ profile: "vfx.w7.exact",+ scope: { kind: "category", category: "vfx" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("vfx-w7-conformance-v1", "src/qa/breadth-corpus.test.ts", "58837182f467de6757194d54c8b42682d21d3d9355daecab694888cd742d2405"),+ defaultMode: "enforce",+ evaluate: evaluateVfxExactQa};- const wall = (suffix, len, axis, pos, which) => {- const op = openingFor(which);- const w = wallWithOpening(`${name}_Wall${suffix}`, material, {- length: len,- height,- thickness: wallThickness,- axis,- ...op ? { opening: op } : {},- parent: root- });- w.position.set(...pos);- return w;+ VFX_ADVISORY_QA_RULE = {+ id: "VFX_ADVISORY_PROFILE",+ profile: "vfx.w7.advisory",+ scope: { kind: "category", category: "vfx" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: evaluateVfxAdvisoryQa};- const walls = {- front: wall("Front", width, "z", [depth / 2, 0, 0], "front"),- back: wall("Back", width, "z", [-depth / 2, 0, 0], "back"),- left: wall("Left", depth, "x", [0, 0, -width / 2], "left"),- right: wall("Right", depth, "x", [0, 0, width / 2], "right")+ MODULAR_JOIN_QA_RULE = {+ id: "MODULAR_JOIN_PROFILE",+ profile: "modular.w7.exact",+ scope: { kind: "universal" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("modular-w7-conformance-v1", "src/qa/breadth-corpus.test.ts", "58837182f467de6757194d54c8b42682d21d3d9355daecab694888cd742d2405"),+ defaultMode: "enforce",+ evaluate: evaluateModularJoinQa};- let floorObj = null;- if (floor) {- floorObj = createPart(`${name}_Floor`, boxGeo(depth, floorThickness, width), material, {- position: [0, floorThickness / 2, 0],- parent: root- });- }- if (parent)- parent.add(root);- return { root, walls, floor: floorObj };-}-function createRoofPlanes2(name, material, options) {- const result = createRoofPlanes(name, material, options);- result.slopes[0].name = `Mesh_${name}A`;- result.slopes[1].name = `Mesh_${name}B`;- for (let index = 0;index < result.slopes.length; index++) {- const normal = new THREE27.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);- result.slopes[index].position.addScaledVector(normal, (options.thickness ?? 0.08) / 2);- }- if ((options.ridgeAxis ?? "x") === "x") {- const halfRun = options.width / 2 + (options.overhang ?? 0.3);- const angle2 = Math.atan2(options.height, halfRun);- result.slopes[1].rotation.set(-angle2, Math.PI, 0);- }- return result;+ ASSET_SCOPE_QA_RULE = {+ id: "ASSET_SCOPE_PROFILE",+ profile: "scope.w7.advisory",+ scope: { kind: "universal" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: evaluateAssetScopeQa+ };+ W7_BREADTH_QA_RULES = [+ VFX_EXACT_QA_RULE,+ VFX_ADVISORY_QA_RULE,+ MODULAR_JOIN_QA_RULE,+ ASSET_SCOPE_QA_RULE+ ];+});++// src/qa/breadth-evidence.ts+import * as THREE27 from "three";+function record3(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);}-function createStairs(name, material, options) {- const {- steps = 8,- totalRise,- totalRun,- width,- axis = "x",- treadThickness = 0.08,- riser = true,- parent- } = options;- if (steps < 1) {- throw new Error(`createStairs("${name}"): steps must be >= 1 (got ${steps}).`);- }- if (Math.abs(totalRise) < 0.0001 || Math.abs(totalRun) < 0.0001) {- throw new Error(`createStairs("${name}"): totalRise and totalRun must be non-zero (got rise=${totalRise}, run=${totalRun}).`);- }- const root = new THREE27.Object3D;- root.name = name;- const stepRise = totalRise / steps;- const stepRun = totalRun / steps;- const stepList = [];- for (let i = 0;i < steps; i++) {- const topY = (i + 1) * stepRise;- const alongC = (i + 0.5) * stepRun;- const treadGeo = axis === "x" ? boxGeo(stepRun, treadThickness, width) : boxGeo(width, treadThickness, stepRun);- const treadPos = axis === "x" ? [alongC, topY - treadThickness / 2, 0] : [0, topY - treadThickness / 2, alongC];- stepList.push(createPart(`${name}Step${i + 1}`, treadGeo, material, { position: treadPos, parent: root }));- if (riser) {- const front = i * stepRun;- const riserGeo = axis === "x" ? boxGeo(treadThickness, stepRise, width) : boxGeo(width, stepRise, treadThickness);- const riserPos = axis === "x" ? [front + treadThickness / 2, topY - stepRise / 2, 0] : [0, topY - stepRise / 2, front + treadThickness / 2];- createPart(`${name}Riser${i + 1}`, riserGeo, material, { position: riserPos, parent: root });- }- }- if (parent)- parent.add(root);- return { root, steps: stepList };+function isObject3D(value) {+ return record3(value) && value.isObject3D === true && typeof value.traverse === "function";}-function requireColor(color2, fn) {- if (typeof color2 === "number" || typeof color2 === "string")- return;- const got = color2 && typeof color2 === "object" ? `an object with keys [${Object.keys(color2).join(", ")}]` : String(color2);- throw new Error(`${fn}(color, options?): color must be a hex number like 0x8c4a32 or a CSS string, got ${got}. ` + `Material settings go in the SECOND argument: ${fn}(0x8c4a32, { roughness: 0.5, metalness: 0.9 }).`);+function isMeshNode(value) {+ return value.isMesh === true;}-function gameMaterial(color2, options = {}) {- requireColor(color2, "gameMaterial");- return new THREE27.MeshStandardMaterial({- color: color2,- metalness: options.metalness ?? 0,- roughness: options.roughness ?? 0.8,- emissive: options.emissive ?? 0,- emissiveIntensity: options.emissiveIntensity ?? 1,- flatShading: options.flatShading ?? true- });+function isSpriteNode(value) {+ return value.isSprite === true;}-function basicMaterial(color2, options = {}) {- requireColor(color2, "basicMaterial");- return new THREE27.MeshBasicMaterial({- color: color2,- transparent: options.transparent ?? false,- opacity: options.opacity ?? 1- });+function isTexture(value) {+ return record3(value) && value.isTexture === true;}-function glassMaterial(color2, options = {}) {- requireColor(color2, "glassMaterial");- return new THREE27.MeshStandardMaterial({- color: color2,- transparent: true,- opacity: options.opacity ?? 0.35,- roughness: options.roughness ?? 0.1,- metalness: options.metalness ?? 0,- side: THREE27.DoubleSide- });+function isAnimationClip(value) {+ return record3(value) && typeof value.name === "string" && typeof value.duration === "number" && Number.isFinite(value.duration) && Array.isArray(value.tracks);}-function lambertMaterial(color2, options = {}) {- requireColor(color2, "lambertMaterial");- return new THREE27.MeshLambertMaterial({- color: color2,- flatShading: options.flatShading ?? true,- emissive: options.emissive ?? 0- });+function localRenderableBox(rootInverse, node) {+ if (isSpriteNode(node)) {+ const transform = rootInverse.clone().multiply(node.matrixWorld);+ return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);+ }+ if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)+ return;+ node.geometry.computeBoundingBox();+ const source = node.geometry.boundingBox;+ if (!source || source.isEmpty())+ return;+ const transform = rootInverse.clone().multiply(node.matrixWorld);+ const result = new THREE27.Box3;+ for (const x of [source.min.x, source.max.x]) {+ for (const y of [source.min.y, source.max.y]) {+ for (const z of [source.min.z, source.max.z]) {+ result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));+ }+ }+ }+ return result;}-function threeInterpolation(mode) {- return mode === "STEP" ? THREE27.InterpolateDiscrete : THREE27.InterpolateLinear;+function textureDimensions(texture) {+ const image = texture.image;+ return image && typeof image.width === "number" && Number.isFinite(image.width) && image.width > 0 && typeof image.height === "number" && Number.isFinite(image.height) && image.height > 0 ? [image.width, image.height] : undefined;}-function rotationTrack(jointName, keyframes, interpolation) {- const times = [];- const values = [];- const euler = new THREE27.Euler;- const quat = new THREE27.Quaternion;- for (const kf of keyframes) {- times.push(kf.time);- euler.set(THREE27.MathUtils.degToRad(kf.rotation[0]), THREE27.MathUtils.degToRad(kf.rotation[1]), THREE27.MathUtils.degToRad(kf.rotation[2]));- quat.setFromEuler(euler);- values.push(quat.x, quat.y, quat.z, quat.w);+function textureHasAlpha2(texture) {+ if (!texture)+ return false;+ const image = texture.image;+ if (!image?.data || !image.width || !image.height)+ return false;+ const pixelCount = image.width * image.height;+ if (pixelCount <= 0 || image.data.length < pixelCount * 4)+ return false;+ for (let index = 3;index < pixelCount * 4; index += 4) {+ if ((image.data[index] ?? 255) < 255)+ return true;}- return new THREE27.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));+ return false;}-function positionTrack(jointName, keyframes, interpolation) {- const times = [];- const values = [];- for (const kf of keyframes) {- times.push(kf.time);- values.push(...kf.position);+function materialTextures2(material) {+ const candidate = material;+ const textures = new Set;+ for (const key of [+ "map",+ "alphaMap",+ "emissiveMap",+ "normalMap",+ "roughnessMap",+ "metalnessMap",+ "aoMap"+ ]) {+ const value = candidate[key];+ if (isTexture(value))+ textures.add(value);}- return new THREE27.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));+ return [...textures];}-function scaleTrack(jointName, keyframes, interpolation) {- const times = [];- const values = [];- for (const kf of keyframes) {- times.push(kf.time);- values.push(...kf.scale);- }- return new THREE27.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));+function materialTextureBytes(material) {+ return materialTextures2(material).reduce((sum, texture) => {+ const dimensions = textureDimensions(texture);+ return sum + (dimensions ? Math.ceil(dimensions[0] * dimensions[1] * 4 * (4 / 3)) : 0);+ }, 0);}-function createClip(name, duration, tracks) {- return new THREE27.AnimationClip(name, duration, tracks);+function alphaMode(material) {+ const standard = material;+ if ((standard.alphaTest ?? 0) > 0)+ return "mask";+ if (standard.transparent || (standard.opacity ?? 1) < 1 || standard.alphaMap)+ return "blend";+ return "opaque";}-function idleBreathing(bodyJoint, duration = 2, amount = 0.02) {- const y = 0;- return createClip("Idle", duration, [- positionTrack(bodyJoint, [- { time: 0, position: [0, y, 0] },- { time: duration / 2, position: [0, y + amount, 0] },- { time: duration, position: [0, y, 0] }- ])- ]);+function alphaData(material) {+ const standard = material;+ return (standard.opacity ?? 1) < 1 || standard.alphaMap !== undefined && standard.alphaMap !== null || textureHasAlpha2(standard.alphaMap) || textureHasAlpha2(standard.map) || (standard.alphaTest ?? 0) > 0 && standard.alphaMap !== undefined && standard.alphaMap !== null;}-function bobbingAnimation(rootName, duration = 2, height = 0.1) {- return createClip("Bob", duration, [- positionTrack(rootName, [- { time: 0, position: [0, 0, 0] },- { time: duration / 2, position: [0, height, 0] },- { time: duration, position: [0, 0, 0] }- ])+function surfaceRole(nodes, intent) {+ const evidence = nodes.flatMap((node) => [+ node.name,+ ...readSemanticMetadataV1(node)?.roles ?? []]);-}-function spinAnimation(jointName, duration = 2, axis = "y") {- const rotation = [0, 0, 0];- const idx = axis === "x" ? 0 : axis === "y" ? 1 : 2;- const rotations = [];- for (let i = 0;i <= 4; i++) {- const r = [...rotation];- r[idx] = i * 90 % 360;- rotations.push({ time: i * duration / 4, rotation: r });+ if (evidence.some((value) => /(?:^|[._ -])beam(?:$|[._ -])/i.test(value)))+ return "beam";+ if (evidence.some((value) => /(?:^|[._ -])trail(?:$|[._ -])/i.test(value)))+ return "trail";+ if (evidence.some((value) => /(?:^|[._ -])(?:volume|aura|portal)(?:$|[._ -])/i.test(value))) {+ return "volume";}- return createClip("Spin", duration, [rotationTrack(jointName, rotations)]);-}-function cloneGeometry(geo) {- return geo;+ if (intent.subtype === "beam")+ return "beam";+ if (intent.subtype === "trail")+ return "trail";+ if (intent.subtype === "volume-like" || intent.subtype === "aura" || intent.subtype === "portal") {+ return "volume";+ }+ return "card";}-function cloneMaterial(mat) {- return mat;+function isEffectSurface(nodes) {+ return nodes.some((node) => isSpriteNode(node) || (readSemanticMetadataV1(node)?.roles ?? []).some((role) => EFFECT_SURFACE_ROLE.test(role)));}-function copyGeometry(geo) {- return geo.clone();+function coverageRatio(boxes, overall) {+ if (boxes.length === 0 || overall.isEmpty())+ return 0;+ const overallSize = overall.getSize(new THREE27.Vector3);+ const denominator = Math.max(0.000000001, overallSize.x * overallSize.y, overallSize.z * overallSize.y, overallSize.x * overallSize.z);+ const area = boxes.reduce((sum, box) => {+ const size = box.getSize(new THREE27.Vector3);+ return sum + Math.max(size.x * size.y, size.z * size.y, size.x * size.z);+ }, 0);+ return stable7(Math.min(1, area / denominator));}-function copyMaterial(mat) {- return mat.clone();+function collectMaterialEvidence(root, intent) {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const byMaterial = new Map;+ const overall = new THREE27.Box3;+ root.traverse((node) => {+ const box = localRenderableBox(inverse, node);+ if (!box || !isMeshNode(node) && !isSpriteNode(node))+ return;+ overall.union(box);+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ for (const material of materials) {+ if (!material)+ continue;+ const value = byMaterial.get(material) ?? { nodes: [], boxes: [] };+ value.nodes.push(node);+ value.boxes.push(box);+ byMaterial.set(material, value);+ }+ });+ return [...byMaterial.entries()].map(([material, value], index) => {+ const mode = alphaMode(material);+ const standard = material;+ return {+ id: material.name || `material.${index}`,+ surfaceRole: surfaceRole(value.nodes, intent),+ effectSurface: isEffectSurface(value.nodes),+ alphaMode: mode,+ alphaData: alphaData(material),+ doubleSided: material.side === THREE27.DoubleSide,+ ...mode === "mask" ? { alphaCutoff: standard.alphaTest ?? 0 } : {},+ screenAreaRatio: coverageRatio(value.boxes, overall),+ transparentLayers: mode === "blend" ? value.nodes.length : 0,+ textureMemoryBytes: materialTextureBytes(material)+ };+ }).sort((a, b) => a.id.localeCompare(b.id));}-function createInstance(name, source, options = {}) {- const isMesh = (o) => !!o?.isMesh;- const sourceMesh = isMesh(source) ? source : source.children.find(isMesh);- if (!sourceMesh) {- throw new Error(`createInstance("${name}"): source "${source.name}" has no Mesh to clone from`);- }- const mesh = new THREE27.Mesh(sourceMesh.geometry, sourceMesh.material);- mesh.name = `Mesh_${name}`;- if (options.position)- mesh.position.set(...options.position);- if (options.rotation)- mesh.rotation.set(THREE27.MathUtils.degToRad(options.rotation[0]), THREE27.MathUtils.degToRad(options.rotation[1]), THREE27.MathUtils.degToRad(options.rotation[2]));- if (options.scale)- mesh.scale.set(...options.scale);- if (options.parent)- options.parent.add(mesh);- return mesh;+function signedAxis(vector) {+ const values = [+ { axis: "X", value: vector.x },+ { axis: "Y", value: vector.y },+ { axis: "Z", value: vector.z }+ ];+ const dominant = [...values].sort((a, b) => Math.abs(b.value) - Math.abs(a.value))[0];+ return `${dominant.value < 0 ? "-" : "+"}${dominant.axis}`;}-function countTriangles(root) {- let count = 0;- root.traverse((child) => {- if (child.isMesh) {- const meshChild = child;- const geometry2 = meshChild.geometry;- if (geometry2.index) {- count += geometry2.index.count / 3;- } else {- const position = geometry2.getAttribute("position");- if (position)- count += position.count / 3;- }- } else if (child.isSprite) {- count += 2;+function dominantGeometryAxis(root, mode) {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ let best;+ root.traverse((node) => {+ if (!isMeshNode(node) || !node.geometry?.isBufferGeometry || !isEffectSurface([node]))+ return;+ node.geometry.computeBoundingBox();+ const bounds = node.geometry.boundingBox;+ if (!bounds || bounds.isEmpty())+ return;+ const size = bounds.getSize(new THREE27.Vector3);+ const axes = [+ { score: size.x, direction: new THREE27.Vector3(1, 0, 0) },+ { score: size.y, direction: new THREE27.Vector3(0, 1, 0) },+ { score: size.z, direction: new THREE27.Vector3(0, 0, 1) }+ ];+ const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);+ const relative = inverse.clone().multiply(node.matrixWorld);+ const direction = selected.direction.transformDirection(relative);+ const score = selected.score * node.getWorldScale(new THREE27.Vector3).length();+ if (!best || (mode === "length" ? score > best.score : score < best.score)) {+ best = { score, direction };}});- return Math.floor(count);+ if (best)+ return signedAxis(best.direction);+ const overall = new THREE27.Box3;+ root.traverse((node) => {+ const box = localRenderableBox(inverse, node);+ if (box)+ overall.union(box);+ });+ if (overall.isEmpty())+ return "+X";+ const size = overall.getSize(new THREE27.Vector3);+ const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE27.Vector3(1, 0, 0) : size.y >= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE27.Vector3(1, 0, 0) : size.y <= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1);+ return signedAxis(vector);}-function countMaterials(root) {- const materials = new Set;- root.traverse((child) => {- if (child.isMesh) {- const meshChild = child;- if (Array.isArray(meshChild.material)) {- meshChild.material.forEach((material) => {- materials.add(material);- });- } else {- materials.add(meshChild.material);+function analyzedFacing(root, intent) {+ let cameraFacing = false;+ root.traverse((node) => {+ if (isSpriteNode(node))+ cameraFacing = true;+ });+ return {+ source: cameraFacing ? "explicit" : "inferred",+ mode: cameraFacing ? "camera-spherical" : "fixed",+ normalAxis: cameraFacing ? "+X" : dominantGeometryAxis(root, "normal"),+ ...(intent.subtype === "beam" || intent.subtype === "trail") && {+ directionAxis: dominantGeometryAxis(root, "length")+ }+ };+}+function clipEndpointMatches(clip) {+ if (!clip || clip.tracks.length === 0)+ return false;+ return clip.tracks.every((track) => {+ const stride = track.getValueSize();+ if (stride <= 0 || track.values.length < stride * 2)+ return false;+ for (let index = 0;index < stride; index++) {+ const first = Number(track.values[index]);+ const last = Number(track.values[track.values.length - stride + index]);+ if (!Number.isFinite(first) || !Number.isFinite(last) || Math.abs(first - last) > 0.000001) {+ return false;}- } else if (child.isSprite) {- materials.add(child.material);}+ return true;});- return materials.size;}-function getJointNames(root) {- const joints = [];- root.traverse((child) => {- if (child.name.startsWith("Joint_")) {- joints.push(child.name);+function shaderMaterials(root) {+ const values = new Set;+ root.traverse((node) => {+ if (!isMeshNode(node) && !isSpriteNode(node))+ return;+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ for (const material of materials) {+ if (material.isShaderMaterial || material.isNodeMaterial) {+ values.add(material);+ }}});- return joints;+ return [...values];}-function validateAsset(root, category) {- const errors = [];- const warnings = [];- const suggestedMats = {- character: 8,- prop: 6,- vfx: 4,- environment: 12,- architecture: 12,- vegetation: 8,- vehicle: 10- };- const mats = countMaterials(root);- const matLimit = suggestedMats[category];- if (mats > matLimit) {- warnings.push(`High material count: ${mats} (suggested: ${matLimit})`);+function shaderUniforms(materials) {+ const values = new Set;+ for (const material of materials) {+ const uniforms = material.uniforms;+ if (record3(uniforms))+ for (const key of Object.keys(uniforms))+ values.add(key);}- return { valid: true, errors, warnings };+ return [...values].sort();}-function buildSandboxGlobals(usage2, options = {}) {- const wrap = (name, fn) => {- if (!usage2)- return fn;- const wrapped = (...args) => {- usage2[name] = (usage2[name] ?? 0) + 1;- return fn(...args);- };- return wrapped;- };- const geoCache = new Map;- let _kilnCallSeq = 0;- const stampKilnRange = (name, geo) => {- const idx = geo.getIndex();- const triCount = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;- const callId = ++_kilnCallSeq;- geo.userData = {- ...geo.userData ?? {},- kilnRanges: [- {- name: `${name}#${callId}`,- start: 0,- count: Math.floor(triCount)- }- ]- };- };- const cacheGeo = (name, fn) => {- const memoFn = (...args) => {- let key;- try {- key = `${name}::${JSON.stringify(args)}`;- } catch {- const result2 = fn(...args);- stampKilnRange(name, result2);- return result2;- }- const hit = geoCache.get(key);- if (hit)- return hit;- const result = fn(...args);- stampKilnRange(name, result);- geoCache.set(key, result);- return result;- };- return memoFn;+function analyzeVfxArtifactEvidenceV1(intent, root, clips = []) {+ const actualClips = clips.filter(isAnimationClip);+ const selectedClip = actualClips.find((clip) => clip.name === intent.animation.clipName) ?? actualClips[0];+ const shaders = shaderMaterials(root);+ const uniforms = shaderUniforms(shaders);+ const actualDriver = selectedClip ? "clip" : uniforms.length > 0 ? "timeUniform" : "none";+ const endpointMatches = selectedClip ? clipEndpointMatches(selectedClip) : false;+ const playback = actualDriver === "none" ? "static" : actualDriver === "clip" ? endpointMatches ? "loop" : "oneShot" : endpointMatches ? "loop" : "oneShot";+ const durationSeconds = selectedClip?.duration ?? 0;+ return {+ schemaVersion: 1,+ facing: analyzedFacing(root, intent),+ animation: {+ playback,+ durationSeconds: stable7(durationSeconds),+ endpointBehavior: playback === "static" ? "none" : playback === "loop" ? "matchStart" : "holdLast",+ driver: actualDriver,+ ...selectedClip ? { clipName: selectedClip.name } : {},+ ...actualDriver === "timeUniform" && intent.animation.timeUniformName ? { timeUniformName: intent.animation.timeUniformName } : {},+ endpointMatches+ },+ materials: collectMaterialEvidence(root, intent),+ clips: actualClips.map((clip) => ({ name: clip.name, durationSeconds: stable7(clip.duration) })),+ uniforms};- const wrapGeo = (name, fn) => wrap(name, cacheGeo(name, fn));- const loadApprovedTexture = (...args) => {- if (args.length !== 1 || typeof args[0] !== "string") {- return Promise.reject(new TypeError("loadApprovedTexture accepts exactly one approved resource ID string"));- }- if (!options.textureResolver) {- return Promise.reject(new Error("loadApprovedTexture: no host TextureResolver is installed"));- }- return options.textureResolver.loadApprovedTexture(args[0]);+}+function analyzeAssetScopeObservationV1(root) {+ let renderableCount = 0;+ const members = new Set;+ const dressing = new Set;+ root.traverse((node) => {+ if ((isMeshNode(node) || isSpriteNode(node)) && node.visible)+ renderableCount++;+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ if (roles.some((role) => MEMBER_ROLE.test(role)))+ members.add(node);+ for (const role of roles)+ if (DRESSING_ROLE.test(role))+ dressing.add(role);+ if (node !== root && DRESSING_NAME.test(node.name))+ dressing.add(`name:${node.name}`);+ });+ const memberCount = members.size > 0 ? members.size : renderableCount > 0 ? 1 : 0;+ return {+ topLevelAssetRoots: memberCount,+ reusableMemberCount: memberCount,+ sceneDressingRoles: [...dressing].sort()};- const sandboxMaterialRecipe = (...args) => {- if (args.length < 1 || args.length > 2 || typeof args[0] !== "string") {- return Promise.reject(new TypeError("materialRecipe accepts an approved recipe ID and optional bounded overrides"));- }- if (!options.textureResolver) {- return Promise.reject(new Error("materialRecipe: no host TextureResolver is installed"));+}+function pathOf2(root, node) {+ const values = [];+ let cursor = node;+ while (cursor) {+ values.push(cursor.name || cursor.type);+ if (cursor === root)+ break;+ cursor = cursor.parent;+ }+ return values.reverse().join("/");+}+function analyzeSockets(root) {+ root.updateWorldMatrix(true, true);+ const rootInverse = root.matrixWorld.clone().invert();+ const rootWorldRotation = root.getWorldQuaternion(new THREE27.Quaternion).invert();+ const values = [];+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ if (!metadata)+ return;+ const nodeWorldRotation = node.getWorldQuaternion(new THREE27.Quaternion);+ for (const socket of metadata.sockets) {+ const frame = metadata.frames.find((candidate) => candidate.id === socket.frame);+ if (!frame)+ continue;+ const frameRotation = new THREE27.Quaternion(...frame.rotation);+ const worldRotation = rootWorldRotation.clone().multiply(nodeWorldRotation).multiply(frameRotation);+ const position = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);+ const normal = new THREE27.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();+ values.push({+ contract: {+ id: socket.id,+ pieceId: pathOf2(root, node),+ type: socket.type,+ compatibleTypes: [...socket.compatibleTypes],+ frame: {+ translation: [...frame.translation],+ rotation: [...frame.rotation]+ },+ allowedRotationsDegrees: [...socket.allowedRotationsDegrees ?? []]+ },+ worldPosition: [stable7(position.x), stable7(position.y), stable7(position.z)],+ worldNormal: [stable7(normal.x), stable7(normal.y), stable7(normal.z)],+ worldRotation+ });}- return options.textureResolver.materialRecipe(args[0], args[1]);+ });+ return values.sort((a, b) => a.contract.id.localeCompare(b.contract.id));+}+function analyzeModularEvidenceV1(root, trustedGrid) {+ const sockets = analyzeSockets(root);+ const kit = {+ schemaVersion: 1,+ units: "m",+ grid: [trustedGrid[0], trustedGrid[1], trustedGrid[2]],+ sockets: sockets.map((value) => value.contract)};+ const pair = sockets.flatMap((a, index) => sockets.slice(index + 1).map((b) => [a, b])).find(([a, b]) => a.contract.pieceId !== b.contract.pieceId && a.contract.compatibleTypes.includes(b.contract.type) && b.contract.compatibleTypes.includes(a.contract.type));+ if (!pair)+ return { kit };+ const relative = pair[0].worldRotation.clone().invert().multiply(pair[1].worldRotation);+ const euler = new THREE27.Euler().setFromQuaternion(relative, "YXZ");+ const rotation = THREE27.MathUtils.euclideanModulo(THREE27.MathUtils.radToDeg(euler.y), 360);return {- createRoot: wrap("createRoot", createRoot),- createPivot: wrap("createPivot", createPivot),- createJointChain: wrap("createJointChain", createJointChain),- createVehicleFrame: wrap("createVehicleFrame", createVehicleFrame),- createWheelGeometrySet: wrap("createWheelGeometrySet", createWheelGeometrySet),- createWheelAssembly: wrap("createWheelAssembly", createWheelAssembly),- createPart: wrap("createPart", createPart),- capsuleGeo: wrapGeo("capsuleGeo", capsuleGeo),- capsuleXGeo: wrapGeo("capsuleXGeo", capsuleXGeo),- capsuleYGeo: wrapGeo("capsuleYGeo", capsuleYGeo),- capsuleZGeo: wrapGeo("capsuleZGeo", capsuleZGeo),- cylinderGeo: wrapGeo("cylinderGeo", cylinderGeo),- cylinderXGeo: wrapGeo("cylinderXGeo", cylinderXGeo),- cylinderYGeo: wrapGeo("cylinderYGeo", cylinderYGeo),- cylinderZGeo: wrapGeo("cylinderZGeo", cylinderZGeo),- boxGeo: wrapGeo("boxGeo", boxGeo),- sphereGeo: wrapGeo("sphereGeo", sphereGeo),- coneGeo: wrapGeo("coneGeo", coneGeo),- coneXGeo: wrapGeo("coneXGeo", coneXGeo),- coneYGeo: wrapGeo("coneYGeo", coneYGeo),- coneZGeo: wrapGeo("coneZGeo", coneZGeo),- taperConeGeo: wrapGeo("taperConeGeo", taperConeGeo),- cylinderOnAxis: wrapGeo("cylinderOnAxis", cylinderOnAxis),- torusGeo: wrapGeo("torusGeo", torusGeo),- planeGeo: wrapGeo("planeGeo", planeGeo),- decalBox: wrapGeo("decalBox", decalBox),- foliageCardGeo: wrapGeo("foliageCardGeo", foliageCardGeo),- crossedQuadsGeo: wrapGeo("crossedQuadsGeo", crossedQuadsGeo),- octaGridPlane: wrapGeo("octaGridPlane", octaGridPlane),- wingGeo: wrapGeo("wingGeo", wingGeo),- createWingPair: wrap("createWingPair", createWingPair),- beamBetween: wrap("beamBetween", beamBetween),- createLadder: wrap("createLadder", createLadder),- snapTo: wrap("snapTo", snapTo),- room: wrap("room", room),- wallWithOpening: wrap("wallWithOpening", wallWithOpening),- createRoofPlanes: wrap("createRoofPlanes", createRoofPlanes2),- createGableRoof: wrap("createGableRoof", createGableRoof),- createGableEndPanel: wrap("createGableEndPanel", createGableEndPanel),- createGableShell: wrap("createGableShell", createGableShell),- createRoofSurfaceLayout: wrap("createRoofSurfaceLayout", createRoofSurfaceLayout),- createStairs: wrap("createStairs", createStairs),- gameMaterial: wrap("gameMaterial", gameMaterial),- materialRecipe: wrap("materialRecipe", sandboxMaterialRecipe),- compilePortableMaterialSpecV2: wrap("compilePortableMaterialSpecV2", compilePortableMaterialSpecV2),- basicMaterial: wrap("basicMaterial", basicMaterial),- glassMaterial: wrap("glassMaterial", glassMaterial),- lambertMaterial: wrap("lambertMaterial", lambertMaterial),- rotationTrack: wrap("rotationTrack", rotationTrack),- positionTrack: wrap("positionTrack", positionTrack),- scaleTrack: wrap("scaleTrack", scaleTrack),- createClip: wrap("createClip", createClip),- spinAnimation: wrap("spinAnimation", spinAnimation),- bobbingAnimation: wrap("bobbingAnimation", bobbingAnimation),- idleBreathing: wrap("idleBreathing", idleBreathing),- implicitSurface: wrap("implicitSurface", implicitSurface),- sweepProfile: wrap("sweepProfile", sweepProfile),- loftProfiles: wrap("loftProfiles", loftProfiles),- bend: wrap("bend", bend),- twist: wrap("twist", twist),- taper: wrap("taper", taper),- displace: wrap("displace", displace),- copyGeometry: wrap("copyGeometry", copyGeometry),- copyMaterial: wrap("copyMaterial", copyMaterial),- meshGeo: wrap("meshGeo", meshGeo),- parametricSurface: wrap("parametricSurface", parametricSurface),- creaseNormals: wrap("creaseNormals", creaseNormals),- geometryDiagnostics: wrap("geometryDiagnostics", geometryDiagnostics),- cloneGeometry: wrap("cloneGeometry", cloneGeometry),- cloneMaterial: wrap("cloneMaterial", cloneMaterial),- createInstance: wrap("createInstance", createInstance),- boolUnion: wrap("boolUnion", boolUnion),- boolDiff: wrap("boolDiff", boolDiff),- boolIntersect: wrap("boolIntersect", boolIntersect),- hull: wrap("hull", hull),- roundedBoxGeo: wrap("roundedBoxGeo", roundedBoxGeo),- extrudeProfile: wrap("extrudeProfile", extrudeProfile),- revolveProfile: wrap("revolveProfile", revolveProfile),- circleProfile: wrap("circleProfile", circleProfile),- arrayLinear: wrap("arrayLinear", arrayLinear),- arrayRadial: wrap("arrayRadial", arrayRadial),- mirror: wrap("mirror", mirror),- subdivide: wrap("subdivide", subdivide),- mergeVertices: wrap("mergeVertices", mergeVertices),- curveToMesh: wrap("curveToMesh", curveToMesh),- pipeAlongPath: wrap("pipeAlongPath", pipeAlongPath),- lathe: wrap("lathe", lathe),- revolveGeo: wrap("revolveGeo", revolveGeo),- bezierCurve: wrap("bezierCurve", bezierCurve),- autoUnwrap: wrap("autoUnwrap", autoUnwrap),- boxUnwrap: wrap("boxUnwrap", boxUnwrap),- cylinderUnwrap: wrap("cylinderUnwrap", cylinderUnwrap),- planeUnwrap: wrap("planeUnwrap", planeUnwrap),- panelRemapV: wrap("panelRemapV", panelRemapV),- gearGeo: wrapGeo("gearGeo", gearGeo),- bladeGeo: wrapGeo("bladeGeo", bladeGeo),- loadApprovedTexture: wrap("loadApprovedTexture", loadApprovedTexture),- proceduralTexture: wrap("proceduralTexture", proceduralTexture),- normalMapFromHeight: wrap("normalMapFromHeight", normalMapFromHeight),- pbrMaterial: wrap("pbrMaterial", pbrMaterial),- foliageMaterial: wrap("foliageMaterial", foliageMaterial),- countTriangles: wrap("countTriangles", countTriangles),- countMaterials: wrap("countMaterials", countMaterials),- getJointNames: wrap("getJointNames", getJointNames),- validateAsset: wrap("validateAsset", validateAsset),- THREE: THREE27,- Math,- console+ kit,+ join: {+ aSocketId: pair[0].contract.id,+ bSocketId: pair[1].contract.id,+ aWorldPosition: pair[0].worldPosition,+ bWorldPosition: pair[1].worldPosition,+ aWorldNormal: pair[0].worldNormal,+ bWorldNormal: pair[1].worldNormal,+ relativeRotationDegrees: stable7(rotation)+ }};}-var cylinderYGeo, capsuleYGeo, coneYGeo;-var init_primitives = __esm(() => {- init_character();- init_architecture2();- init_gears();- init_ops();- init_geometry();- init_deform();- init_sweep();- init_implicit();- init_profile();- init_solids();- init_procedural_texture();- init_textures();- init_portable_material_runtime();- init_vehicle();- init_contracts();- init_uv();- init_uv_shapes();- init_architecture2();- init_character();- init_vehicle();- init_material_recipe_runtime();- init_portable_material_runtime();- init_procedural_texture();- init_implicit();- init_sweep();- init_deform();- init_geometry();- cylinderYGeo = cylinderGeo;- capsuleYGeo = capsuleGeo;- coneYGeo = coneGeo;+function deriveW7BreadthEvidence(context) {+ if (!isObject3D(context.scene))+ return context.derivedEvidence;+ const derived = {+ source: "engine-scene-analysis",+ assetScope: analyzeAssetScopeObservationV1(context.scene)+ };+ if (context.intent.category === "vfx" && context.intent.vfx) {+ derived.vfxArtifact = analyzeVfxArtifactEvidenceV1(context.intent.vfx, context.scene, context.clips);+ }+ if (context.intent.scope.scope === "modularSet") {+ const modular = analyzeModularEvidenceV1(context.scene, context.intent.modular?.grid ?? [1, 1, 1]);+ if (modular.kit)+ derived.modularKit = modular.kit;+ if (modular.join)+ derived.modularJoin = modular.join;+ }+ return derived;+}+function withDerivedW7BreadthEvidence(context) {+ const derivedEvidence = deriveW7BreadthEvidence(context);+ return derivedEvidence ? { ...context, derivedEvidence } : context;+}+var stable7 = (value) => Math.round(value * 1e6) / 1e6, EFFECT_SURFACE_ROLE, MEMBER_ROLE, DRESSING_ROLE, DRESSING_NAME;+var init_breadth_evidence = __esm(() => {+ init_contracts();+ EFFECT_SURFACE_ROLE = /^vfx\.effect\.surface(?:\.|$)/;+ MEMBER_ROLE = /^(?:asset|scope|cluster|modular)\.member(?:\.|$)|^modular\.piece(?:\.|$)/;+ DRESSING_ROLE = /^(?:scene\.dressing|scope\.extra|environment\.dressing)(?:\.|$)/;+ DRESSING_NAME = /(?:diorama|display[-_ ]?plate|terrain[-_ ]?base|backdrop)/i;});-// src/metrics.ts-function collectGlbMetrics(doc, triangles) {- const root = doc.getRoot();- const geomSet = new Set;- const matSet = new Set;- let drawCalls = 0;- let derivedTris = 0;- const primTris = (prim) => {- const idx = prim.getIndices();- if (idx)- return Math.floor(idx.getCount() / 3);- const pos = prim.getAttribute("POSITION");- return pos ? Math.floor(pos.getCount() / 3) : 0;- };- const instanceCopies = (node) => {- const ext = node.getExtension("EXT_mesh_gpu_instancing");- if (!ext)- return 1;- return ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 1;+// src/qa/universal.ts+function isSceneNode(value) {+ return typeof value === "object" && value !== null;+}+function sceneNodes(context) {+ if (!isSceneNode(context.scene))+ return [];+ const nodes = [];+ const seen = new Set;+ const add = (node) => {+ if (!seen.has(node)) {+ seen.add(node);+ nodes.push(node);+ }};- const visit = (node) => {- const mesh = node.getMesh();- if (mesh) {- const copies = instanceCopies(node);- for (const prim of mesh.listPrimitives()) {- drawCalls += 1;- geomSet.add(prim);- derivedTris += primTris(prim) * copies;- const mat = prim.getMaterial();- if (mat)- matSet.add(mat);+ if (typeof context.scene.traverse === "function") {+ context.scene.traverse(add);+ return nodes;+ }+ const pending = [context.scene];+ while (pending.length > 0) {+ const node = pending.shift();+ add(node);+ for (const child of node.children ?? [])+ pending.push(child);+ }+ return nodes;+}+function nodeName(node) {+ return node.name?.trim() || "(unnamed)";+}+function nodePath4(node) {+ const names = [];+ const seen = new Set;+ let cursor = node;+ while (cursor && !seen.has(cursor)) {+ seen.add(cursor);+ names.unshift(nodeName(cursor));+ cursor = cursor.parent;+ }+ return names.join("/");+}+function affectedNode(node, extra = {}) {+ return { node: nodeName(node), nodePath: nodePath4(node), ...extra };+}+function isRenderable(node) {+ if (node.isSprite)+ return true;+ if (!(node.isMesh || node.isLine || node.isPoints))+ return false;+ const position = node.geometry?.attributes?.position;+ return typeof position?.count === "number" ? position.count > 0 : Boolean(position?.array?.length);+}+function descendantsContainRenderable(node) {+ const pending = [...node.children ?? []];+ while (pending.length > 0) {+ const child = pending.shift();+ if (isRenderable(child))+ return true;+ pending.push(...child.children ?? []);+ }+ return false;+}+function finiteComponents(value) {+ if (!value)+ return true;+ const values = "w" in value ? [value.x, value.y, value.z, value.w] : [value.x, value.y, value.z];+ return values.every(Number.isFinite);+}+function iterableValues(value) {+ if (!value)+ return [];+ const out = [];+ for (let i = 0;i < value.length; i++)+ out.push(value[i]);+ return out;+}+function emptyOutputFindings(context) {+ const nodes = sceneNodes(context);+ if (nodes.some(isRenderable))+ return [];+ return [+ {+ code: "UNIVERSAL_EMPTY_OUTPUT",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "universal",+ message: "The generated scene contains no renderable geometry.",+ measurement: { name: "renderableNodeCount", actual: 0, expected: 1 },+ repairText: "Return at least one non-empty renderable mesh or Sprite from build()."+ }+ ];+}+function finiteDataFindings(context) {+ const findings = [];+ for (const node of sceneNodes(context)) {+ const badTransform = !finiteComponents(node.position) || !finiteComponents(node.quaternion) || !finiteComponents(node.scale) || iterableValues(node.matrix?.elements).some((value) => !Number.isFinite(value));+ if (badTransform) {+ findings.push({+ code: "UNIVERSAL_NONFINITE_TRANSFORM",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "universal",+ message: `Node ${JSON.stringify(nodeName(node))} contains a non-finite transform value.`,+ affected: affectedNode(node),+ repairText: "Replace NaN/Infinity transform components with finite numbers."+ });+ }+ for (const [attributeName, attribute] of Object.entries(node.geometry?.attributes ?? {})) {+ const values = iterableValues(attribute.array);+ const badIndex = values.findIndex((value) => !Number.isFinite(value));+ if (badIndex >= 0) {+ findings.push({+ code: "UNIVERSAL_NONFINITE_ATTRIBUTE",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "universal",+ message: `Geometry attribute ${attributeName} on ${JSON.stringify(nodeName(node))} contains a non-finite value.`,+ affected: affectedNode(node, { attribute: attributeName }),+ measurement: { name: "arrayIndex", actual: badIndex },+ repairText: `Rebuild the ${attributeName} attribute with finite numeric data.`+ });}}- for (const child of node.listChildren())- visit(child);- };- for (const scene of root.listScenes()) {- for (const node of scene.listChildren())- visit(node);}- const transparentMaterials = root.listMaterials().filter((m) => m.getAlphaMode() === "BLEND").length;- return {- uniqueGeometries: geomSet.size,- uniqueMaterials: matSet.size,- drawCalls,- textureCount: root.listTextures().length,- skinned: root.listSkins().length > 0,- transparentMaterials,- triangles: triangles ?? derivedTris- };+ return findings;}-function gradeInstanceability(metrics, opts = {}) {- const reasons = [];- const m = metrics;- let grade;- if (m.uniqueMaterials <= 1)- grade = "A";- else if (m.uniqueMaterials <= 3)- grade = "B";- else if (m.uniqueMaterials <= 6)- grade = "C";- else if (m.uniqueMaterials <= 12)- grade = "D";- else- grade = "F";- const order = ["A", "B", "C", "D", "F"];- const demote = (to, why) => {- if (order.indexOf(to) > order.indexOf(grade)) {- grade = to;- reasons.push(why);- } else {- reasons.push(why);+function invalidIndexFindings(context) {+ const findings = [];+ for (const node of sceneNodes(context)) {+ const index = node.geometry?.index;+ if (!index?.array)+ continue;+ const vertexCount = node.geometry?.attributes?.position?.count ?? 0;+ const values = iterableValues(index.array);+ const badPosition = values.findIndex((value) => !Number.isInteger(value) || value < 0 || value >= vertexCount);+ if (badPosition >= 0) {+ findings.push({+ code: "UNIVERSAL_INVALID_INDEX",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "universal",+ message: `Geometry index on ${JSON.stringify(nodeName(node))} references an invalid vertex.`,+ affected: affectedNode(node, { attribute: "index" }),+ measurement: {+ name: "indexValue",+ actual: values[badPosition] ?? null,+ threshold: vertexCount - 1+ },+ repairText: "Rebuild the index so every value is an integer within the POSITION accessor."+ });+ }+ }+ return findings;+}+function zeroScaleFindings(context) {+ const required = new Set(context.intent.requiredParts);+ const findings = [];+ for (const node of sceneNodes(context)) {+ const scale = node.scale;+ if (!scale)+ continue;+ const zeroAxes = ["x", "y", "z"].filter((axis) => Number.isFinite(scale[axis]) && Math.abs(scale[axis]) <= ZERO_SCALE_EPSILON);+ if (zeroAxes.length === 0)+ continue;+ const outputBearing = isRenderable(node) || descendantsContainRenderable(node) || required.has(nodeName(node));+ findings.push({+ code: outputBearing ? "UNIVERSAL_ZERO_SCALE_RENDERABLE" : "UNIVERSAL_ZERO_SCALE_ORGANIZATIONAL",+ disposition: outputBearing ? "block" : "warn",+ dimension: outputBearing ? "exportIntegrity" : "categoryReadiness",+ profile: "universal",+ message: outputBearing ? `Renderable or required node ${JSON.stringify(nodeName(node))} has zero scale.` : `Organizational node ${JSON.stringify(nodeName(node))} has zero scale.`,+ affected: affectedNode(node),+ measurement: { name: "zeroScaleAxes", actual: zeroAxes.join(",") },+ repairText: outputBearing ? "Use a finite non-zero scale for geometry and required semantic nodes." : "Remove the zero scale unless the organizational node is intentionally disabled."+ });+ }+ return findings;+}+function clipList(context) {+ return (context.clips ?? []).filter((clip) => typeof clip === "object" && clip !== null);+}+function trackTarget2(trackName) {+ const dot = trackName.indexOf(".");+ if (dot <= 0)+ return;+ const path = trackName.slice(0, dot);+ const slash = path.lastIndexOf("/");+ return path.slice(slash + 1) || undefined;+}+function requiredTrackTargets(context) {+ const requested = new Set(context.intent.animation?.clips ?? []);+ const targets = new Set;+ for (const clip of clipList(context)) {+ if (!clip.name || !requested.has(clip.name))+ continue;+ for (const track of clip.tracks ?? []) {+ if (track.name) {+ const target = trackTarget2(track.name);+ if (target)+ targets.add(target);+ }}- };- reasons.push(`${m.uniqueMaterials} material${m.uniqueMaterials === 1 ? "" : "s"}, ` + `${m.uniqueGeometries} geometr${m.uniqueGeometries === 1 ? "y" : "ies"}, ` + `${m.drawCalls} draw call${m.drawCalls === 1 ? "" : "s"}`);- if (m.transparentMaterials > 0) {- demote("C", `${m.transparentMaterials} transparent material(s) force per-object sort`);}- if (m.textureCount > 4) {- demote("C", `${m.textureCount} textures (consider atlasing) `.trim());+ return targets;+}+function duplicateNameFindings2(context) {+ const byName = new Map;+ for (const node of sceneNodes(context)) {+ const name = node.name?.trim();+ if (!name)+ continue;+ const nodes = byName.get(name) ?? [];+ nodes.push(node);+ byName.set(name, nodes);}- if (m.skinned) {- reasons.push("skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts");+ const required = new Set([...context.intent.requiredParts, ...requiredTrackTargets(context)]);+ const findings = [];+ for (const [name, nodes] of byName) {+ if (nodes.length < 2)+ continue;+ const contractCritical = required.has(name);+ findings.push({+ code: contractCritical ? "UNIVERSAL_DUPLICATE_REQUIRED_NODE_NAME" : "UNIVERSAL_DUPLICATE_NODE_NAME",+ disposition: contractCritical ? "block" : "warn",+ dimension: "categoryReadiness",+ profile: "universal",+ message: `${nodes.length} scene nodes share the name ${JSON.stringify(name)}.`,+ affected: { node: name, nodePath: nodes.map(nodePath4).join(" | ") },+ measurement: { name: "duplicateCount", actual: nodes.length, expected: 1 },+ repairText: contractCritical ? "Give every required or animated target a unique name." : "Use unique names when nodes must be addressed independently."+ });}- if (opts.category)- reasons.push(`category: ${opts.category}`);- const summary = `${grade} — ${m.uniqueMaterials} mat / ${m.uniqueGeometries} geo / ${m.drawCalls} draws` + (m.transparentMaterials > 0 ? ", transparent" : ", opaque") + (m.skinned ? ", skinned" : "");- return { grade, summary, reasons, metrics: m };+ return findings;+}+function animationTargetFindings(context) {+ const animation = context.intent.animation;+ if (!animation || animation.clips.length === 0)+ return [];+ const nodes = sceneNodes(context);+ const names = new Set(nodes.map((node) => node.name?.trim()).filter(Boolean));+ const clips = clipList(context);+ const byName = new Map(clips.map((clip) => [clip.name, clip]));+ const findings = [];+ for (const requiredClip of animation.clips) {+ const clip = byName.get(requiredClip);+ if (!clip) {+ findings.push({+ code: "UNIVERSAL_REQUIRED_CLIP_MISSING",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "universal",+ message: `Required animation clip ${JSON.stringify(requiredClip)} is missing.`,+ affected: { clip: requiredClip },+ repairText: `Create and return the required ${requiredClip} clip from animate().`+ });+ continue;+ }+ for (const track of clip.tracks ?? []) {+ const trackName = track.name ?? "";+ const target = trackTarget2(trackName);+ if (!target || !names.has(target)) {+ findings.push({+ code: "UNIVERSAL_REQUIRED_ANIMATION_TARGET_UNRESOLVED",+ disposition: "block",+ dimension: "exportIntegrity",+ profile: "universal",+ message: `Required clip ${JSON.stringify(requiredClip)} has an unresolved track target.`,+ affected: { clip: requiredClip, track: trackName, ...target ? { node: target } : {} },+ repairText: "Rename the track target to exactly match one unique scene node."+ });+ }+ }+ }+ return findings;}+var ZERO_SCALE_EPSILON = 0.00000001, UNIVERSAL_QA_RULES;+var init_universal = __esm(() => {+ init_registry();+ UNIVERSAL_QA_RULES = [+ {+ id: "UNIVERSAL_SCENE_CONTENT_RULE",+ profile: "universal",+ scope: { kind: "universal" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),+ defaultMode: "enforce",+ evaluate: emptyOutputFindings+ },+ {+ id: "UNIVERSAL_FINITE_DATA_RULE",+ profile: "universal",+ scope: { kind: "universal" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),+ defaultMode: "enforce",+ evaluate: finiteDataFindings+ },+ {+ id: "UNIVERSAL_INDEX_RULE",+ profile: "universal",+ scope: { kind: "universal" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),+ defaultMode: "enforce",+ evaluate: invalidIndexFindings+ },+ {+ id: "UNIVERSAL_ZERO_SCALE_RULE",+ profile: "universal",+ scope: { kind: "universal" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),+ defaultMode: "enforce",+ evaluate: zeroScaleFindings+ },+ {+ id: "UNIVERSAL_NODE_NAME_RULE",+ profile: "universal",+ scope: { kind: "universal" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),+ defaultMode: "enforce",+ evaluate: duplicateNameFindings2+ },+ {+ id: "UNIVERSAL_ANIMATION_TARGET_RULE",+ profile: "universal",+ scope: { kind: "universal" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("universal-qa-v1", "src/qa/universal.test.ts", "82c1b26db0a7900141aa44fd40e90fb858e80c51347dc6975ef1691f62730c78"),+ defaultMode: "enforce",+ evaluate: animationTargetFindings+ }+ ];+});-// src/qa/gltf.ts-function finiteCount(value) {- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;+// src/qa/run.ts+function runDeterministicSceneQa(context, policy = {}) {+ const result = DETERMINISTIC_QA_REGISTRY.run(withDerivedW7BreadthEvidence(context), policy);+ return createAssetQaReportV1(context.intent, {+ findings: result.findings,+ evaluatedDimensions: ["exportIntegrity", "categoryReadiness"]+ });}-function normalizeIssue(value) {- const issue = value ?? {};- return {- code: typeof issue.code === "string" ? issue.code : "GLTF_VALIDATOR_UNKNOWN",- message: typeof issue.message === "string" ? issue.message : "Unknown glTF validation issue.",- severity: finiteCount(issue.severity),- ...typeof issue.pointer === "string" ? { pointer: issue.pointer } : {}- };+function gltfReportFindings(report, profile) {+ return report.issues.messages.filter((issue) => issue.severity === 0 || issue.severity === 1).filter((issue) => !isExpectedKtx2ValidatorLimitation(report, issue)).map((issue) => ({+ code: `GLTF_${issue.code}`.replace(/[^A-Z0-9_]/g, "_"),+ disposition: issue.severity === 0 ? "block" : "warn",+ dimension: "exportIntegrity",+ profile,+ message: issue.message,+ ...issue.pointer ? { affected: { nodePath: issue.pointer } } : {}+ }));}-function normalizeReport(value) {- const report = value ?? {};- const sourceIssues = report.issues ?? {};- return {- ...typeof report.uri === "string" ? { uri: report.uri } : {},- ...typeof report.mimeType === "string" ? { mimeType: report.mimeType } : {},- ...typeof report.validatorVersion === "string" ? { validatorVersion: report.validatorVersion } : {},- ...typeof report.validatedAt === "string" ? { validatedAt: report.validatedAt } : {},- issues: {- numErrors: finiteCount(sourceIssues.numErrors),- numWarnings: finiteCount(sourceIssues.numWarnings),- numInfos: finiteCount(sourceIssues.numInfos),- numHints: finiteCount(sourceIssues.numHints),- messages: Array.isArray(sourceIssues.messages) ? sourceIssues.messages.map(normalizeIssue) : [],- ...typeof sourceIssues.truncated === "boolean" ? { truncated: sourceIssues.truncated } : {}- },- ...report.info && typeof report.info === "object" ? { info: report.info } : {}+function isExpectedKtx2ValidatorLimitation(report, issue) {+ const required = report.info?.["extensionsRequired"];+ if (!Array.isArray(required) || !required.includes("KHR_texture_basisu"))+ return false;+ if (issue.code === "VALUE_NOT_IN_LIST") {+ return /^\/images\/\d+\/mimeType$/.test(issue.pointer ?? "") && issue.message === "Invalid value 'image/ktx2'. Valid values are ('image/jpeg', 'image/png').";+ }+ return issue.code === "IMAGE_UNRECOGNIZED_FORMAT" && /^\/images\/\d+$/.test(issue.pointer ?? "") && issue.message === "Image format not recognized.";+}+function appendFinalGltfQa(intent, sceneReport, gltfReport) {+ const findings = Object.values(sceneReport.dimensions).flatMap((dimension) => dimension.findings);+ const gltfFindings = gltfReportFindings(gltfReport, intent.qaProfile);+ findings.push(...gltfFindings);+ return createAssetQaReportV1(intent, {+ findings,+ evaluatedDimensions: ["exportIntegrity", "categoryReadiness"],+ metrics: {+ exportIntegrity: {+ gltfErrors: gltfReport.issues.numErrors,+ gltfWarnings: gltfFindings.filter((finding) => finding.disposition === "warn").length+ }+ }+ });+}+function appendRuntimeCostQa(intent, report, instanceability, metricsError) {+ const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);+ if (metricsError) {+ findings.push({+ code: "RUNTIME_COST_METRICS_FAILED",+ disposition: "warn",+ dimension: "runtimeCost",+ profile: intent.qaProfile,+ message: `Runtime-cost metrics could not be computed: ${metricsError}`+ });+ }+ const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);+ evaluatedDimensions.push("runtimeCost");+ const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));+ if (instanceability) {+ metrics.runtimeCost = {+ instanceabilityGrade: instanceability.grade,+ instanceabilitySummary: instanceability.summary,+ uniqueGeometries: instanceability.metrics.uniqueGeometries,+ uniqueMaterials: instanceability.metrics.uniqueMaterials,+ drawCalls: instanceability.metrics.drawCalls,+ textureCount: instanceability.metrics.textureCount,+ transparentMaterials: instanceability.metrics.transparentMaterials,+ triangles: instanceability.metrics.triangles,+ skinned: instanceability.metrics.skinned+ };+ }+ return createAssetQaReportV1(intent, {+ findings,+ evaluatedDimensions,+ ...Object.keys(metrics).length > 0 ? { metrics } : {}+ });+}+function appendMaterialMetricsQa(intent, report, materialMetrics, budgetWarnings = []) {+ const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);+ findings.push(...budgetWarnings.map((warning) => ({+ code: warning.code,+ disposition: "warn",+ dimension: "runtimeCost",+ profile: `${warning.profile}.${warning.tier}`,+ message: `${warning.message} ${warning.advice}`,+ measurement: warning.measurement+ })));+ const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);+ if (!evaluatedDimensions.includes("runtimeCost"))+ evaluatedDimensions.push("runtimeCost");+ const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));+ metrics.runtimeCost = {+ ...metrics.runtimeCost ?? {},+ materialCount: materialMetrics.materialCount,+ opaqueMaterials: materialMetrics.opaqueMaterials,+ maskedMaterials: materialMetrics.maskedMaterials,+ blendedMaterials: materialMetrics.blendedMaterials,+ singleSidedMaterials: materialMetrics.singleSidedMaterials,+ doubleSidedMaterials: materialMetrics.doubleSidedMaterials,+ texturedMaterials: materialMetrics.texturedMaterials,+ materialExtensionCount: materialMetrics.materialExtensionCount,+ materialExtensionsUsed: materialMetrics.materialExtensionsUsed.join(","),+ imageCount: materialMetrics.imageCount,+ maxImageDimension: materialMetrics.maxImageDimension,+ decodedImageBytesRgba8: materialMetrics.decodedImageBytesRgba8,+ estimatedGpuBytesWithMipmaps: materialMetrics.estimatedGpuBytesWithMipmaps,+ blendedSurfaceAreaRatio: materialMetrics.blendedSurfaceAreaRatio};+ return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });}-async function validateFinalGlbBytes(bytes, uri = "model.glb") {- const validator = await import("gltf-validator");- const raw = await validator.validateBytes(bytes, {- uri,- maxIssues: 1000,- externalResourceFunction: async (externalUri) => {- throw new Error(`External glTF resource is forbidden in final GLB: ${externalUri}`);- }- });- return normalizeReport(raw);+function qaPolicyFromEnv(env = process.env) {+ const mode = env["KILN_QA_MODE"];+ return mode === "observe" || mode === "off" ? { defaultMode: mode } : {};}-async function assertFinalGlbValid(bytes, uri = "model.glb") {- const report = await validateFinalGlbBytes(bytes, uri);- if (report.issues.numErrors > 0)- throw new GltfValidationError(report);- return report;+function qaBlockingEnabled(env = process.env) {+ const mode = env["KILN_QA_MODE"];+ return mode !== "observe" && mode !== "off";}-var GltfValidationError;-var init_gltf = __esm(() => {- GltfValidationError = class GltfValidationError extends Error {+var DETERMINISTIC_QA_REGISTRY, MAX_DETAILED_BLOCKERS = 6, AssetQaBlockedError;+var init_run = __esm(() => {+ init_material();+ init_architecture2();+ init_character2();+ init_character_advisory();+ init_vehicle2();+ init_vegetation();+ init_prop();+ init_part_connectivity();+ init_reference_comparison();+ init_self_intersection();+ init_environment2();+ init_breadth2();+ init_breadth_evidence();+ init_registry();+ init_types();+ init_universal();+ DETERMINISTIC_QA_REGISTRY = new QaRegistry([+ ...UNIVERSAL_QA_RULES,+ MATERIAL_QA_RULE,+ ...ARCHITECTURE_QA_RULES,+ CHARACTER_QA_RULE,+ CHARACTER_ADVISORY_QA_RULE,+ ...VEHICLE_QA_RULES,+ ...VEGETATION_QA_RULES,+ ...PROP_QA_RULES,+ ...ENVIRONMENT_QA_RULES,+ ...W7_BREADTH_QA_RULES,+ SELF_INTERSECTION_QA_RULE,+ PART_CONNECTIVITY_QA_RULE,+ REFERENCE_COMPARISON_QA_RULE+ ]);+ AssetQaBlockedError = class AssetQaBlockedError extends Error {report;- constructor(report) {- const first = report.issues.messages.find((issue) => issue.severity === 0);- super(`Final GLB failed Khronos validation with ${report.issues.numErrors} error(s)` + (first ? `: ${first.code} — ${first.message}` : "."));- this.name = "GltfValidationError";+ stage;+ gltfValidation;+ constructor(report, stage, gltfValidation) {+ const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding) => finding.disposition === "block");+ const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding) => `${finding.code}: ${finding.message}${finding.repairText ? ` FIX: ${finding.repairText}` : ""}`);+ const overflow = blockers.length > MAX_DETAILED_BLOCKERS ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)` : "";+ super(`Asset QA blocked at ${stage}: ${detailed.join(" | ") || "unknown blocker"}${overflow}`);+ this.name = "AssetQaBlockedError";this.report = report;+ this.stage = stage;+ this.gltfValidation = gltfValidation;}};});@@ -20016,25 +19962,25 @@ function signedAxis2(vector) {function finalEffectAxis(nodes, mode) {let best;for (const node of nodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic3?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());- const scale2 = node.getWorldScale();- const scaleMagnitude = Math.hypot(scale2[0], scale2[1], scale2[2]);+ const scale = node.getWorldScale();+ const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);for (const primitive of node.getMesh()?.listPrimitives() ?? []) {const position = primitive.getAttribute("POSITION");if (!position)continue;const min = position.getMin([]);const max = position.getMax([]);- const axes2 = [+ const axes = [{ score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },{ score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },{ score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }];- const selected = axes2.reduce((candidate2, value) => mode === "length" ? value.score > candidate2.score ? value : candidate2 : value.score < candidate2.score ? value : candidate2);+ const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const candidate = {score: selected.score * scaleMagnitude,direction: selected.direction.transformDirection(matrix)@@ -20053,16 +19999,16 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);const meshes = [...new Set(renderableNodes.map((node) => node.getMesh()).filter(Boolean))];const primitives = meshes.flatMap((mesh) => mesh?.listPrimitives() ?? []);- let triangleCount2 = 0;+ let triangleCount = 0;for (const primitive of primitives) {const indices = primitive.getIndices();const position = primitive.getAttribute("POSITION");- triangleCount2 += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;+ triangleCount += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;}const effectSurfaceMaterials = new Set;for (const node of renderableNodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic3?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}for (const primitive of node.getMesh()?.listPrimitives() ?? []) {@@ -20090,8 +20036,8 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {});const facingSemantics = new Set;for (const node of renderableNodes) {- const semantic3 = readSemanticMetadataV1FromExtras(node.getExtras());- for (const role of semantic3?.roles ?? []) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ for (const role of semantic?.roles ?? []) {const match = /^vfx\.facing\.(fixed|camera-spherical|camera-y-axis)$/.exec(role);if (match)facingSemantics.add(match[1]);@@ -20103,7 +20049,7 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {schemaVersion: 1,meshCount: meshes.length,primitiveCount: primitives.length,- triangleCount: Math.floor(triangleCount2),+ triangleCount: Math.floor(triangleCount),materials,facingSemantics: [...facingSemantics].sort(),...normalAxis ? { normalAxis } : {},@@ -20117,12 +20063,12 @@ async function analyzeFinalVfxGlbBytesV1(bytes) {function finalFinding(intent, value) {return { ...value, profile: intent.qaProfile || "vfx.w7.final-glb" };}-function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {+function evaluateFinalVfxGlbEvidenceV1(intent, evidence) {if (intent.category !== "vfx" || !intent.vfx)return [];const contract = intent.vfx;const findings = [];- if (evidence2.meshCount === 0 || evidence2.primitiveCount === 0 || evidence2.triangleCount === 0) {+ if (evidence.meshCount === 0 || evidence.primitiveCount === 0 || evidence.triangleCount === 0) {findings.push(finalFinding(intent, {code: "VFX_GLTF_RENDERABLE_MISSING",disposition: "block",@@ -20130,13 +20076,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB contains no renderable VFX geometry.",measurement: {name: "finalVfxTriangles",- actual: evidence2.triangleCount,+ actual: evidence.triangleCount,expected: ">=1"},repairText: "Export the effect surface as portable geometry before final-byte approval."}));}- const effectMaterials = evidence2.materials.filter((material) => material.effectSurface);+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface);if (effectMaterials.length === 0) {findings.push(finalFinding(intent, {code: "VFX_GLTF_EFFECT_SURFACE_MISSING",@@ -20196,7 +20142,7 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {}));}}- if (contract.facing.mode !== "fixed" && !evidence2.facingSemantics.includes(contract.facing.mode)) {+ if (contract.facing.mode !== "fixed" && !evidence.facingSemantics.includes(contract.facing.mode)) {findings.push(finalFinding(intent, {code: "VFX_GLTF_FACING_SEMANTIC_MISSING",disposition: "block",@@ -20204,13 +20150,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: `Final GLB does not carry the ${contract.facing.mode} runtime-facing semantic.`,measurement: {name: "finalFacingSemantics",- actual: evidence2.facingSemantics.join(",") || null,+ actual: evidence.facingSemantics.join(",") || null,expected: contract.facing.mode},repairText: "Preserve the exporter-derived billboard semantic on the renderable quad node."}));}- if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence2.normalAxis) {+ if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence.normalAxis) {findings.push(finalFinding(intent, {code: "VFX_GLTF_NORMAL_AXIS_MISMATCH",disposition: "block",@@ -20218,12 +20164,12 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB effect-surface normal axis differs from explicit VFX intent.",measurement: {name: "finalNormalAxis",- actual: evidence2.normalAxis ?? null,+ actual: evidence.normalAxis ?? null,expected: contract.facing.normalAxis ?? null}}));}- if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence2.directionAxis) {+ if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence.directionAxis) {findings.push(finalFinding(intent, {code: "VFX_GLTF_DIRECTION_AXIS_MISMATCH",disposition: "block",@@ -20231,13 +20177,13 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {message: "Final GLB effect-surface direction axis differs from explicit VFX intent.",measurement: {name: "finalDirectionAxis",- actual: evidence2.directionAxis ?? null,+ actual: evidence.directionAxis ?? null,expected: contract.facing.directionAxis}}));}if (contract.animation.driver === "clip") {- const clip = evidence2.clips.find((candidate) => candidate.name === contract.animation.clipName);+ const clip = evidence.clips.find((candidate) => candidate.name === contract.animation.clipName);if (!clip || Math.abs(clip.durationSeconds - contract.animation.durationSeconds) > 0.000001) {findings.push(finalFinding(intent, {code: "VFX_GLTF_REQUIRED_CLIP_MISSING",@@ -20260,24 +20206,24 @@ function evaluateFinalVfxGlbEvidenceV1(intent, evidence2) {async function appendFinalVfxGlbQa(intent, report, bytes) {if (intent.category !== "vfx")return report;- const evidence2 = await analyzeFinalVfxGlbBytesV1(bytes);+ const evidence = await analyzeFinalVfxGlbBytesV1(bytes);const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);- findings.push(...evaluateFinalVfxGlbEvidenceV1(intent, evidence2));+ findings.push(...evaluateFinalVfxGlbEvidenceV1(intent, evidence));const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== "notEvaluated").map(([dimension]) => dimension);if (!evaluatedDimensions.includes("exportIntegrity"))evaluatedDimensions.push("exportIntegrity");const metrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, result]) => result.metrics ? [[dimension, result.metrics]] : []));metrics.exportIntegrity = {...metrics.exportIntegrity ?? {},- finalVfxMeshCount: evidence2.meshCount,- finalVfxPrimitiveCount: evidence2.primitiveCount,- finalVfxTriangles: evidence2.triangleCount,- finalVfxMaterialCount: evidence2.materials.length,- finalVfxEffectMaterialCount: evidence2.materials.filter((material) => material.effectSurface).length,- finalVfxFacingSemantics: evidence2.facingSemantics.join(","),- finalVfxNormalAxis: evidence2.normalAxis ?? null,- finalVfxDirectionAxis: evidence2.directionAxis ?? null,- finalVfxClipCount: evidence2.clips.length+ finalVfxMeshCount: evidence.meshCount,+ finalVfxPrimitiveCount: evidence.primitiveCount,+ finalVfxTriangles: evidence.triangleCount,+ finalVfxMaterialCount: evidence.materials.length,+ finalVfxEffectMaterialCount: evidence.materials.filter((material) => material.effectSurface).length,+ finalVfxFacingSemantics: evidence.facingSemantics.join(","),+ finalVfxNormalAxis: evidence.normalAxis ?? null,+ finalVfxDirectionAxis: evidence.directionAxis ?? null,+ finalVfxClipCount: evidence.clips.length};return createAssetQaReportV1(intent, { findings, evaluatedDimensions, metrics });}@@ -20411,7 +20357,7 @@ function evaluateMaterialBudgetV1(metrics, options) {});}if (metrics.decodedImageBytesRgba8 > limits.maxDecodedBytesRgba8) {- const scale2 = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);+ const scale = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);warnings.push({code: "MATERIAL_DECODED_MEMORY_BUDGET",disposition: "warn",@@ -20424,7 +20370,7 @@ function evaluateMaterialBudgetV1(metrics, options) {threshold: limits.maxDecodedBytesRgba8,unit: "bytes"},- advice: `Downscale image width and height by approximately ${(Math.min(1, scale2) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`+ advice: `Downscale image width and height by approximately ${(Math.min(1, scale) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`});}if (metrics.blendedSurfaceAreaRatio > limits.maxBlendedSurfaceAreaRatio) {@@ -20451,13 +20397,13 @@ var MATERIAL_BUDGET_PROFILES_V1, materialTextures3 = (material) => [material.getNormalTexture(),material.getOcclusionTexture(),material.getEmissiveTexture()-], hasTexture = (material) => materialTextures3(material).some(Boolean), transformPoint = (matrix, x, y, z3) => {- const w = matrix[3] * x + matrix[7] * y + matrix[11] * z3 + matrix[15];+], hasTexture = (material) => materialTextures3(material).some(Boolean), transformPoint = (matrix, x, y, z) => {+ const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];const reciprocal = w === 0 ? 1 : 1 / w;return [- (matrix[0] * x + matrix[4] * y + matrix[8] * z3 + matrix[12]) * reciprocal,- (matrix[1] * x + matrix[5] * y + matrix[9] * z3 + matrix[13]) * reciprocal,- (matrix[2] * x + matrix[6] * y + matrix[10] * z3 + matrix[14]) * reciprocal+ (matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12]) * reciprocal,+ (matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13]) * reciprocal,+ (matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]) * reciprocal];}, accessorPoint = (accessor, index, matrix) => {const array = accessor.getArray();@@ -20526,11 +20472,11 @@ var init_material_metrics = __esm(() => {// src/texture-resolver.tsfunction createTextureResolver(cache = DEFAULT_APPROVED_TEXTURE_CACHE) {return Object.freeze({- async loadApprovedTexture(resourceId2) {- if (typeof resourceId2 !== "string") {+ async loadApprovedTexture(resourceId) {+ if (typeof resourceId !== "string") {throw new RangeError("Unsupported approved texture resource ID.");}- return (await cache.load(resourceId2)).texture;+ return (await cache.load(resourceId)).texture;},async materialRecipe(id, overrides) {if (typeof id !== "string")@@ -20829,32 +20775,32 @@ function analyzeGeneratedSourceSafety(ast) {const issues = [];const seen = new Set;const staticStrings = collectStaticStringBindings(ast);- const add2 = (issue) => {+ const add = (issue) => {const key = issueKey(issue);if (seen.has(key))return;seen.add(key);issues.push(issue);};- const ambient = (name, line) => add2({+ const ambient = (name, line) => add({code: "UNSAFE_GLOBAL_ACCESS",message: `Generated code cannot access ambient capability \`${name}\`.`,fixHint: "Use only the documented sandbox globals and approved resource helpers.",line});- const dynamicCode = (line) => add2({+ const dynamicCode = (line) => add({code: "DYNAMIC_CODE_ACCESS",message: "Generated code cannot access constructor chains or dynamic-code constructors.",fixHint: "Call documented sandbox helpers directly; do not derive constructors at runtime.",line});- const unsafeThree = (name, line) => add2({+ const unsafeThree = (name, line) => add({code: "UNSAFE_THREE_CONSTRUCTOR",message: `Generated code cannot access raw THREE constructor \`${name}\`.`,fixHint: "Use approved texture loading, proceduralTexture, pbrMaterial, or materialRecipe instead.",line});- const unsafeThreeNamespace = (code, line) => add2({+ const unsafeThreeNamespace = (code, line) => add({code,message: code === "UNSAFE_THREE_ALIAS" ? "Generated code cannot alias the THREE namespace." : "Generated code cannot use non-static computed access on the THREE namespace.",fixHint: "Use a documented direct THREE constructor or a sandbox material/texture helper.",@@ -20873,7 +20819,7 @@ function analyzeGeneratedSourceSafety(ast) {ambient("this", node.loc?.start.line);},ImportExpression(node) {- add2({+ add({code: "DYNAMIC_IMPORT",message: "Generated code cannot use dynamic import.",fixHint: "Remove import(); all supported helpers are already sandbox globals.",@@ -21096,8 +21042,8 @@ function analyzeRotationUnits(ast, source) {}function classifyRotationArray(arr, fn, source) {const rendered = () => {- const text2 = source.slice(arr.start, arr.end).replace(/\s+/g, " ");- return text2.length > 64 ? `${text2.slice(0, 61)}...` : text2;+ const text = source.slice(arr.start, arr.end).replace(/\s+/g, " ");+ return text.length > 64 ? `${text.slice(0, 61)}...` : text;};let sawPI = false;let onlyConversions = true;@@ -21394,234 +21340,9 @@ var init_validation = __esm(() => {// src/kit.tsimport { execFile } from "node:child_process";-import { mkdtemp, readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join as join2 } from "node:path";import { promisify } from "node:util";import { KHRMaterialsVariants, KHRTextureBasisu } from "@gltf-transform/extensions";-async function findKtxEncoder() {- if (cachedEncoder !== undefined)- return cachedEncoder ?? undefined;- for (const candidate of KTX_ENCODER_CANDIDATES) {- try {- await run(candidate, ["--version"], { timeout: 1e4 });- cachedEncoder = candidate;- return candidate;- } catch {}- }- cachedEncoder = null;- return;-}-function disposeIfOrphaned(texture) {- const stillUsed = texture.listParents().some((parent) => parent.propertyType !== "Root");- if (!stillUsed)- texture.dispose();-}-async function packOcclusionIntoMetallicRoughness(doc) {- const sharp = (await import("sharp")).default;- let packed = 0;- for (const material of doc.getRoot().listMaterials()) {- const occlusion = material.getOcclusionTexture();- const metallicRoughness = material.getMetallicRoughnessTexture();- if (!occlusion || !metallicRoughness || occlusion === metallicRoughness)- continue;- if (!isPng(occlusion) || !isPng(metallicRoughness))- continue;- const occlusionBytes = occlusion.getImage();- const mrBytes = metallicRoughness.getImage();- if (!occlusionBytes || !mrBytes)- continue;- try {- const [occImage, mrImage] = await Promise.all([- sharp(Buffer.from(occlusionBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true }),- sharp(Buffer.from(mrBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true })- ]);- if (occImage.info.width !== mrImage.info.width || occImage.info.height !== mrImage.info.height) {- continue;- }- const { width, height } = mrImage.info;- const merged = Buffer.allocUnsafe(width * height * 3);- for (let i = 0, o = 0;o < merged.length; i += 4, o += 3) {- merged[o] = occImage.data[i] ?? 255;- merged[o + 1] = mrImage.data[i + 1] ?? 255;- merged[o + 2] = mrImage.data[i + 2] ?? 255;- }- const png = await sharp(merged, { raw: { width, height, channels: 3 } }).png({ compressionLevel: 9 }).toBuffer();- metallicRoughness.setImage(new Uint8Array(png));- material.setOcclusionTexture(metallicRoughness);- const info = material.getOcclusionTextureInfo();- const mrInfo = material.getMetallicRoughnessTextureInfo();- if (info && mrInfo)- info.setTexCoord(mrInfo.getTexCoord());- disposeIfOrphaned(occlusion);- packed += 1;- } catch {}- }- return packed;-}-function recolorForPalette(doc, material, slots, variantName) {- const clone2 = doc.createMaterial(`${material.getName()}__${variantName}`).copy(material);- if (material.getBaseColorTexture())- return { material: clone2, changed: false };- const index = buildSlotIndex(slots);- const base = material.getBaseColorFactor();- const emissive = material.getEmissiveFactor();- const slot = chooseSlot(index, {- baseLinear: [base[0], base[1], base[2]],- emissiveLinear: [emissive[0], emissive[1], emissive[2]],- transparent: material.getAlphaMode() === "BLEND" || material.getAlpha() < 0.98- });- if (slot === undefined)- return { material: clone2, changed: false };- const chosen = slots[slot];- if (!chosen)- return { material: clone2, changed: false };- const [r, g, b] = hexToLinearRgb(chosen.color);- if (chosen.kind === "glow") {- clone2.setEmissiveFactor([r, g, b]);- } else {- clone2.setBaseColorFactor([r, g, b, base[3]]);- if (typeof chosen.roughness === "number")- clone2.setRoughnessFactor(chosen.roughness);- if (typeof chosen.metalness === "number")- clone2.setMetallicFactor(chosen.metalness);- if (chosen.kind === "glass" && typeof chosen.opacity === "number") {- clone2.setBaseColorFactor([r, g, b, chosen.opacity]);- }- }- return { material: clone2, changed: true };-}-function addPaletteVariants(doc, specs) {- const extension = doc.createExtension(KHRMaterialsVariants);- const names = [];- let materialsCreated = 0;- const variants = specs.map((spec) => {- names.push(spec.name);- return { spec, variant: extension.createVariant(spec.name) };- });- for (const mesh of doc.getRoot().listMeshes()) {- for (const primitive of mesh.listPrimitives()) {- const base = primitive.getMaterial();- if (!base)- continue;- const mappings = variants.map(({ spec, variant }) => {- const { material, changed } = recolorForPalette(doc, base, spec.slots, spec.name);- if (!changed) {- material.dispose();- return;- }- materialsCreated += 1;- return extension.createMapping().addVariant(variant).setMaterial(material);- }).filter((value) => value !== undefined);- if (mappings.length === 0)- continue;- const list = extension.createMappingList();- for (const mapping of mappings)- list.addMapping(mapping);- primitive.setExtension("KHR_materials_variants", list);- }- }- if (names.length === 0 || materialsCreated === 0)- extension.dispose();- return { names: materialsCreated > 0 ? names : [], materialsCreated };-}-async function encodeTexturesToKtx2(doc, encoder) {- const textures = doc.getRoot().listTextures().filter(isPng);- if (textures.length === 0)- return { encoded: 0, before: 0, after: 0 };- const dir = await mkdtemp(join2(tmpdir(), "kiln-ktx2-"));- const staged = [];- let encoded = 0;- let before = 0;- let after = 0;- try {- for (const [index, texture] of textures.entries()) {- const bytes = texture.getImage();- if (!bytes)- continue;- const src = join2(dir, `t${index}.png`);- const dst = join2(dir, `t${index}.ktx2`);- await writeFile2(src, bytes);- const srgb = doc.getRoot().listMaterials().some((material) => material.getBaseColorTexture() === texture || material.getEmissiveTexture() === texture);- await run(encoder, [- "create",- "--format",- srgb ? "R8G8B8A8_SRGB" : "R8G8B8A8_UNORM",- "--encode",- KTX_ENCODE_MODE,- "--generate-mipmap",- src,- dst- ], { timeout: 120000 });- const out = await readFile2(dst);- before += bytes.byteLength;- after += out.byteLength;- staged.push({ texture, original: bytes, encodedBytes: new Uint8Array(out) });- }- } finally {- await rm2(dir, { recursive: true, force: true });- }- if (staged.length === 0)- return { encoded: 0, before, after };- if (after >= before * KTX2_SIZE_ACCEPT_RATIO) {- return { encoded: 0, before, after };- }- for (const entry of staged) {- entry.texture.setImage(entry.encodedBytes).setMimeType("image/ktx2");- encoded += 1;- }- doc.createExtension(KHRTextureBasisu).setRequired(true);- return { encoded, before, after };-}-async function applyKitContract(doc, options = {}) {- const ormPacked = options.packOrm === false ? 0 : await packOcclusionIntoMetallicRoughness(doc);- const specs = options.variants ?? [];- const { names, materialsCreated } = specs.length ? addPaletteVariants(doc, specs) : { names: [], materialsCreated: 0 };- let ktx2 = {- applied: false,- skipped: "disabled by caller",- texturesEncoded: 0,- bytesBefore: 0,- bytesAfter: 0- };- if (options.ktx2 !== false) {- const encoder = await findKtxEncoder();- if (!encoder) {- ktx2 = {- applied: false,- skipped: "no KTX-Software encoder on PATH (set KILN_KTX_BIN to override)",- texturesEncoded: 0,- bytesBefore: 0,- bytesAfter: 0- };- } else {- try {- const result = await encodeTexturesToKtx2(doc, encoder);- ktx2 = {- applied: result.encoded > 0,- ...result.encoded > 0 ? {} : {- skipped: result.before === 0 ? "no PNG textures to encode" : `KTX2 was not smaller (${result.after} vs ${result.before} bytes); kept PNG`- },- encoder,- texturesEncoded: result.encoded,- bytesBefore: result.before,- bytesAfter: result.after- };- } catch (error) {- ktx2 = {- applied: false,- skipped: `encoder failed: ${error instanceof Error ? error.message : String(error)}`,- encoder,- texturesEncoded: 0,- bytesBefore: 0,- bytesAfter: 0- };- }- }- }- return { ormPacked, variantsAdded: names, variantMaterialsCreated: materialsCreated, ktx2 };-}-var run, KTX_ENCODER_CANDIDATES, KTX_ENCODE_MODE = "basis-lz", KTX2_SIZE_ACCEPT_RATIO = 0.9, cachedEncoder, isPng = (texture) => texture.getMimeType() === "image/png";+var run, KTX_ENCODER_CANDIDATES;var init_kit = __esm(() => {run = promisify(execFile);KTX_ENCODER_CANDIDATES = Object.freeze([@@ -21689,7 +21410,7 @@ async function bakeSceneTextures(root, warnings) {const materials = Array.isArray(material) ? material : material ? [material] : [];for (const item of materials) {const bag = item;- for (const [slot, usage2] of SLOT_USAGE2) {+ for (const [slot, usage] of SLOT_USAGE2) {const texture = bag[slot];if (!isTexture2(texture))continue;@@ -21700,7 +21421,7 @@ async function bakeSceneTextures(root, warnings) {node: node.name || "(unnamed node)",material: item.name || "(unnamed material)",slot,- usage: usage2+ usage});pending.set(texture, existing);}@@ -21728,8 +21449,8 @@ async function bakeSceneTextures(root, warnings) {bytes};const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";- const recipe2 = entry.texture.userData["kilnProcedural"];- const primaryUsage = recipe2?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");+ const recipe = entry.texture.userData["kilnProcedural"];+ const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");entry.texture.userData["kilnTexture"] = {usage: primaryUsage,colorSpace,@@ -21755,16 +21476,16 @@ async function bakeSceneTextures(root, warnings) {colorSpace,imageSha256,sha1,- ...recipe2 ? { procedural: recipe2 } : {}+ ...recipe ? { procedural: recipe } : {}});}return baked.sort((a, b) => `${a.node}:${a.material}:${a.texture}:${a.slot}`.localeCompare(`${b.node}:${b.material}:${b.texture}:${b.slot}`));}-function computeTangentBasis(geometry2) {- const index = geometry2.getIndex();- const position = geometry2.getAttribute("position");- const normal = geometry2.getAttribute("normal");- const uv = geometry2.getAttribute("uv");+function computeTangentBasis(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");+ const normal = geometry.getAttribute("normal");+ const uv = geometry.getAttribute("uv");if (!position || !normal || !uv) {throw new Error("position, normal, and uv are all required");}@@ -21782,7 +21503,7 @@ function computeTangentBasis(geometry2) {const z1 = position.getZ(b) - position.getZ(a);const x2 = position.getX(c) - position.getX(a);const y2 = position.getY(c) - position.getY(a);- const z22 = position.getZ(c) - position.getZ(a);+ const z2 = position.getZ(c) - position.getZ(a);const s1 = uv.getX(b) - uv.getX(a);const t1 = uv.getY(b) - uv.getY(a);const s2 = uv.getX(c) - uv.getX(a);@@ -21793,10 +21514,10 @@ function computeTangentBasis(geometry2) {const r = 1 / det;const sdx = (t2 * x1 - t1 * x2) * r;const sdy = (t2 * y1 - t1 * y2) * r;- const sdz = (t2 * z1 - t1 * z22) * r;+ const sdz = (t2 * z1 - t1 * z2) * r;const tdx = (s1 * x2 - s2 * x1) * r;const tdy = (s1 * y2 - s2 * y1) * r;- const tdz = (s1 * z22 - s2 * z1) * r;+ const tdz = (s1 * z2 - s2 * z1) * r;for (const v of [a, b, c]) {const o = v * 3;tan1[o] = (tan1[o] ?? 0) + sdx;@@ -21831,7 +21552,7 @@ function computeTangentBasis(geometry2) {out[v * 4 + 2] = tmp.z;out[v * 4 + 3] = w;}- geometry2.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));+ geometry.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));}function ensureNormalMapTangents(root, warnings) {let count = 0;@@ -21844,19 +21565,19 @@ function ensureNormalMapTangents(root, warnings) {const needsTangents = materials.some((m) => m?.normalMap);if (!needsTangents)return;- const geometry2 = mesh.geometry;- if (!geometry2 || done.has(geometry2) || geometry2.getAttribute("tangent"))+ const geometry = mesh.geometry;+ if (!geometry || done.has(geometry) || geometry.getAttribute("tangent"))return;- done.add(geometry2);+ done.add(geometry);const name = mesh.name || "(unnamed mesh)";- if (!geometry2.getAttribute("uv")) {+ if (!geometry.getAttribute("uv")) {warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but has no UV coordinates, so tangents could not be computed — and the normal map cannot be sampled either. Unwrap it first: mesh.geometry = await autoUnwrap(mesh.geometry).`);return;}- if (!geometry2.getAttribute("normal"))- geometry2.computeVertexNormals();+ if (!geometry.getAttribute("normal"))+ geometry.computeVertexNormals();try {- computeTangentBasis(geometry2);+ computeTangentBasis(geometry);count++;} catch (err) {warnings.push(`Mesh ${JSON.stringify(name)} uses a normal map but tangents could not be computed (${err instanceof Error ? err.message : String(err)}). Each runtime will generate its own tangent basis.`);@@ -21885,10 +21606,10 @@ function rounded(value) {function tuple5(vector) {return [rounded(vector.x), rounded(vector.y), rounded(vector.z)];}-function chainIdFor(descriptor2, byRole) {- if (AXIAL_ROLES.has(descriptor2.role))+function chainIdFor(descriptor, byRole) {+ if (AXIAL_ROLES.has(descriptor.role))return "axial";- let current = descriptor2;+ let current = descriptor;const seen = new Set([current.role]);while (current.parentRole && !AXIAL_ROLES.has(current.parentRole)) {const parent = byRole.get(current.parentRole);@@ -21900,28 +21621,28 @@ function chainIdFor(descriptor2, byRole) {return current.role;}function colorFor(value) {- let hash3 = 2166136261;+ let hash = 2166136261;for (let index = 0;index < value.length; index++) {- hash3 ^= value.charCodeAt(index);- hash3 = Math.imul(hash3, 16777619);+ hash ^= value.charCodeAt(index);+ hash = Math.imul(hash, 16777619);}- return CHAIN_COLORS[Math.abs(hash3) % CHAIN_COLORS.length];+ return CHAIN_COLORS[Math.abs(hash) % CHAIN_COLORS.length];}function buildCharacterDiagnosticDescriptor(root, findings = []) {root.updateMatrixWorld(true);- const rootInverse2 = root.matrixWorld.clone().invert();- const evidence2 = collectCharacterJointNodes(root);- const descriptorByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint.descriptor]));- const evidenceByRole = new Map(evidence2.map((joint) => [joint.descriptor.role, joint]));+ const rootInverse = root.matrixWorld.clone().invert();+ const evidence = collectCharacterJointNodes(root);+ const descriptorByRole = new Map(evidence.map((joint) => [joint.descriptor.role, joint.descriptor]));+ const evidenceByRole = new Map(evidence.map((joint) => [joint.descriptor.role, joint]));const invalidFindingNodePaths = [- ...new Set(findings.filter((finding6) => finding6.code === "CHAR_PARENT_EDGE").map((finding6) => finding6.affected?.nodePath).filter((path) => Boolean(path)))+ ...new Set(findings.filter((finding) => finding.code === "CHAR_PARENT_EDGE").map((finding) => finding.affected?.nodePath).filter((path) => Boolean(path)))].sort();const invalidPaths = new Set(invalidFindingNodePaths);- const joints = evidence2.map((joint) => {- const relative2 = rootInverse2.clone().multiply(joint.node.matrixWorld);- const position = new THREE30.Vector3().setFromMatrixPosition(relative2);- const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative2).multiplyScalar(0.2).add(position);- const bend2 = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative2).multiplyScalar(0.2).add(position);+ const joints = evidence.map((joint) => {+ const relative = rootInverse.clone().multiply(joint.node.matrixWorld);+ const position = new THREE30.Vector3().setFromMatrixPosition(relative);+ const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -21934,12 +21655,12 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {color: colorFor(chainId),assetPosition: tuple5(position),forwardAxisEnd: tuple5(forward),- bendAxisEnd: tuple5(bend2),+ bendAxisEnd: tuple5(bend),endEffector: joint.descriptor.endEffector,contact: joint.descriptor.contact};});- const edges = evidence2.filter((joint) => joint.descriptor.parentRole).map((joint) => {+ const edges = evidence.filter((joint) => joint.descriptor.parentRole).map((joint) => {const parentRole = joint.descriptor.parentRole;const parent = evidenceByRole.get(parentRole);const chainId = chainIdFor(joint.descriptor, descriptorByRole);@@ -22138,16 +21859,16 @@ function composeLocalMatrix(node) {}const x2 = q.x + q.x;const y2 = q.y + q.y;- const z22 = q.z + q.z;+ const z2 = q.z + q.z;const xx = q.x * x2;const xy = q.x * y2;- const xz = q.x * z22;+ const xz = q.x * z2;const yy = q.y * y2;- const yz = q.y * z22;- const zz = q.z * z22;+ const yz = q.y * z2;+ const zz = q.z * z2;const wx = q.w * x2;const wy = q.w * y2;- const wz = q.w * z22;+ const wz = q.w * z2;return new Float64Array([(1 - (yy + zz)) * s.x,(xy + wz) * s.x,@@ -22167,15 +21888,15 @@ function composeLocalMatrix(node) {1]);}-function transformPoint2(matrix, x, y, z3) {+function transformPoint2(matrix, x, y, z) {return [- matrix[0] * x + matrix[4] * y + matrix[8] * z3 + matrix[12],- matrix[1] * x + matrix[5] * y + matrix[9] * z3 + matrix[13],- matrix[2] * x + matrix[6] * y + matrix[10] * z3 + matrix[14]+ matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],+ matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],+ matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]];}-function matchesRole(roles2, prefixes) {- return Boolean(prefixes?.some((prefix) => roles2.some((role) => role.startsWith(prefix))));+function matchesRole(roles, prefixes) {+ return Boolean(prefixes?.some((prefix) => roles.some((role) => role.startsWith(prefix))));}function semanticRoles2(node) {const metadata = readSemanticMetadataV1FromExtras(node.userData ?? {});@@ -22198,9 +21919,9 @@ function collectScene(root, requestValue) {const world = multiplyMatrices(parentMatrix, local);const visible = ancestorVisible && node.visible !== false;const segment = `${node.name?.trim() || node.type || "Node"}[${siblingIndex}]`;- const nodePath5 = parentPath ? `${parentPath}/${segment}` : segment;- const roles2 = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];- const omitted = matchesRole(roles2, requestValue.omitRolePrefixes);+ const nodePath = parentPath ? `${parentPath}/${segment}` : segment;+ const roles = [...new Set([...inheritedRoles, ...semanticRoles2(node)])];+ const omitted = matchesRole(roles, requestValue.omitRolePrefixes);if (visible && !omitted && node.isMesh && node.geometry) {const materials = Array.isArray(node.material) ? node.material : [node.material];const material = materials[0];@@ -22208,13 +21929,13 @@ function collectScene(root, requestValue) {const position = node.geometry.getAttribute?.("position");if (position?.itemSize === 3) {const worldPositions = [];- for (let index2 = 0;index2 < position.count; index2++) {- const point = transformPoint2(world, position.array[index2 * 3], position.array[index2 * 3 + 1], position.array[index2 * 3 + 2]);+ for (let index = 0;index < position.count; index++) {+ const point = transformPoint2(world, position.array[index * 3], position.array[index * 3 + 1], position.array[index * 3 + 2]);worldPositions.push(point);}const materialColor = material?.color;- const color2 = materialColor ? [clamp012(materialColor.r), clamp012(materialColor.g), clamp012(materialColor.b)] : [0.7, 0.7, 0.7];- const focused = matchesRole(roles2, requestValue.focusRolePrefixes);+ const color = materialColor ? [clamp012(materialColor.r), clamp012(materialColor.g), clamp012(materialColor.b)] : [0.7, 0.7, 0.7];+ const focused = matchesRole(roles, requestValue.focusRolePrefixes);const addTriangle = (a, b, c) => {const points = [worldPositions[a], worldPositions[b], worldPositions[c]];if (points.some((point) => !point || point.some((value) => !Number.isFinite(value)))) {@@ -22235,10 +21956,10 @@ function collectScene(root, requestValue) {});triangles.push({vertices,- color: color2,+ color,nodeName: node.name ?? "",- nodePath: nodePath5,- semanticRoles: roles2+ nodePath,+ semanticRoles: roles});};const index = node.geometry.index;@@ -22254,7 +21975,7 @@ function collectScene(root, requestValue) {}}(node.children ?? []).forEach((child, index) => {- visit(child, world, nodePath5, index, visible && !omitted, roles2);+ visit(child, world, nodePath, index, visible && !omitted, roles);});};visit(root, IDENTITY, "", 0, true, []);@@ -22267,8 +21988,8 @@ function collectScene(root, requestValue) {};}function normalize3(vector) {- const length3 = Math.hypot(...vector) || 1;- return [vector[0] / length3, vector[1] / length3, vector[2] / length3];+ const length = Math.hypot(...vector) || 1;+ return [vector[0] / length, vector[1] / length, vector[2] / length];}function cross3(a, b) {return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];@@ -22277,12 +21998,12 @@ function dot4(a, b) {return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];}function stableColor(key) {- let hash3 = 2166136261;+ let hash = 2166136261;for (let index = 0;index < key.length; index++) {- hash3 ^= key.charCodeAt(index);- hash3 = Math.imul(hash3, 16777619);+ hash ^= key.charCodeAt(index);+ hash = Math.imul(hash, 16777619);}- return [96 + (hash3 & 127), 96 + (hash3 >>> 8 & 127), 96 + (hash3 >>> 16 & 127)];+ return [96 + (hash & 127), 96 + (hash >>> 8 & 127), 96 + (hash >>> 16 & 127)];}function projectScene(scene, camera, size) {const zAxis = normalize3(camera.dir);@@ -22295,26 +22016,26 @@ function projectScene(scene, camera, size) {(frame.min[1] + frame.max[1]) / 2,(frame.min[2] + frame.max[2]) / 2];- let extent2 = 0.000001;+ let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {const point = [(corner & 1 ? frame.max[0] : frame.min[0]) - center[0],(corner & 2 ? frame.max[1] : frame.min[1]) - center[1],(corner & 4 ? frame.max[2] : frame.min[2]) - center[2]];- extent2 = Math.max(extent2, Math.abs(dot4(point, xAxis)), Math.abs(dot4(point, yAxis)));+ extent = Math.max(extent, Math.abs(dot4(point, xAxis)), Math.abs(dot4(point, yAxis)));}- const scale2 = size * 0.45 / extent2;+ const scale = size * 0.45 / extent;const half = size / 2;return scene.triangles.flatMap((triangle) => {const v = triangle.vertices;const edgeA = [v[3] - v[0], v[4] - v[1], v[5] - v[2]];const edgeB = [v[6] - v[0], v[7] - v[1], v[8] - v[2]];const normalRaw = cross3(edgeA, edgeB);- const length3 = Math.hypot(...normalRaw);- if (length3 < 0.000000000001)+ const length = Math.hypot(...normalRaw);+ if (length < 0.000000000001)return [];- const normal = normalRaw.map((component) => component / length3);+ const normal = normalRaw.map((component) => component / length);const xs = [];const ys = [];const zs = [];@@ -22325,8 +22046,8 @@ function projectScene(scene, camera, size) {v[index * 3 + 1] - center[1],v[index * 3 + 2] - center[2]];- xs.push(half + dot4(point, xAxis) * scale2);- ys.push(half - dot4(point, yAxis) * scale2);+ xs.push(half + dot4(point, xAxis) * scale);+ ys.push(half - dot4(point, yAxis) * scale);zs.push(dot4(point, zAxis));worldY.push(v[index * 3 + 1]);}@@ -22343,7 +22064,7 @@ function projectScene(scene, camera, size) {];});}-function drawLine(rgb2, size, from, to, color2) {+function drawLine(rgb, size, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);const x1 = Math.round(to[0]);@@ -22356,9 +22077,9 @@ function drawLine(rgb2, size, from, to, color2) {while (true) {if (x0 >= 0 && x0 < size && y0 >= 0 && y0 < size) {const offset = (y0 * size + x0) * 3;- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}if (x0 === x1 && y0 === y1)break;@@ -22373,12 +22094,12 @@ function drawLine(rgb2, size, from, to, color2) {}}}-function drawRegionBox(rgb2, size, region) {+function drawRegionBox(rgb, size, region) {const [minX, minY, maxX, maxY] = region.pixelBounds;- drawLine(rgb2, size, [minX, minY], [maxX, minY], region.color);- drawLine(rgb2, size, [maxX, minY], [maxX, maxY], region.color);- drawLine(rgb2, size, [maxX, maxY], [minX, maxY], region.color);- drawLine(rgb2, size, [minX, maxY], [minX, minY], region.color);+ drawLine(rgb, size, [minX, minY], [maxX, minY], region.color);+ drawLine(rgb, size, [maxX, minY], [maxX, maxY], region.color);+ drawLine(rgb, size, [maxX, maxY], [minX, maxY], region.color);+ drawLine(rgb, size, [minX, maxY], [minX, minY], region.color);}function renderDiagnosticView(root, requestValue, options = {}) {const camera = cameraById.get(requestValue.cameraId);@@ -22389,11 +22110,11 @@ function renderDiagnosticView(root, requestValue, options = {}) {const scene = collectScene(root, requestValue);const triangles = projectScene(scene, camera, size);const background = [18, 20, 24];- const rgb2 = new Uint8Array(size * size * 3);+ const rgb = new Uint8Array(size * size * 3);for (let pixel = 0;pixel < size * size; pixel++) {- rgb2[pixel * 3] = background[0];- rgb2[pixel * 3 + 1] = background[1];- rgb2[pixel * 3 + 2] = background[2];+ rgb[pixel * 3] = background[0];+ rgb[pixel * 3 + 1] = background[1];+ rgb[pixel * 3 + 2] = background[2];}const depth = new Float64Array(size * size).fill(-Infinity);const depths = triangles.flatMap((triangle) => triangle.z);@@ -22455,50 +22176,50 @@ function renderDiagnosticView(root, requestValue, options = {}) {continue;depth[pixel] = pixelDepth;const offset = pixel * 3;- let color2;+ let color;if (requestValue.variant === "material-grazing-light") {const grazingDirection = normalize3([0.25, 0.08, 1]);const light = 0.08 + 0.92 * Math.max(0, dot4(triangle.normal, grazingDirection));- color2 = triangle.source.color.map((value) => Math.round(clamp012(value * light) * 255));+ color = triangle.source.color.map((value) => Math.round(clamp012(value * light) * 255));} else if (requestValue.buffer === "silhouette-unlit") {- color2 = [235, 238, 242];+ color = [235, 238, 242];} else if (requestValue.buffer === "normals-backface") {- color2 = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];+ color = triangle.frontFacing ? triangle.normal.map((value) => Math.round((value * 0.5 + 0.5) * 255)) : [238, 48, 64];} else if (requestValue.buffer === "depth-contact") {const worldY = w1 * triangle.worldY[0] + w2 * triangle.worldY[1] + w0 * triangle.worldY[2];if (Math.abs(worldY - groundY) <= contactTolerance)- color2 = [58, 220, 126];+ color = [58, 220, 126];else if (worldY < groundY - contactTolerance)- color2 = [245, 94, 72];+ color = [245, 94, 72];else {const value = Math.round(48 + 190 * ((pixelDepth - minDepth) / depthRange));- color2 = [value, value, value];+ color = [value, value, value];}} else {- color2 = regionColor;+ color = regionColor;}- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}}}if (requestValue.buffer === "wireframe") {for (const triangle of triangles) {- const color2 = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];+ const color = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];for (const [a, b] of [[0, 1],[1, 2],[2, 0]]) {- drawLine(rgb2, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color2);+ drawLine(rgb, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color);}}}const regions = [...regionMap.values()].sort((a, b) => a.nodePath.localeCompare(b.nodePath));if (requestValue.buffer === "semantic-overlay") {for (const region of regions)- drawRegionBox(rgb2, size, region);+ drawRegionBox(rgb, size, region);}return {id: requestValue.id,@@ -22508,15 +22229,12 @@ function renderDiagnosticView(root, requestValue, options = {}) {...requestValue.variant ? { variant: requestValue.variant } : {},width: size,height: size,- rgb: rgb2,- png: encodePng(rgb2, size, size),+ rgb,+ png: encodePng(rgb, size, size),regions,...requestValue.phaseFractions ? { phaseFractions: requestValue.phaseFractions } : {}};}-function renderDiagnosticViews(root, requests, options = {}) {- return requests.map((viewRequest) => renderDiagnosticView(root, viewRequest, options));-}var GENERIC_DIAGNOSTIC_BUFFER_IDS, frozenCamera = (id, name, dir) => Object.freeze({ id, name, dir: Object.freeze([...dir]) }), GENERIC_DIAGNOSTIC_CAMERAS, EXTRA_CAMERAS, cameraById, request = (value) => Object.freeze({...value,...value.omitRolePrefixes ? { omitRolePrefixes: Object.freeze([...value.omitRolePrefixes]) } : {},@@ -22614,11 +22332,6 @@ var init_diagnostic = __esm(() => {});// src/views/camera-capture.ts-var exports_camera_capture = {};-__export(exports_camera_capture, {- validateAdvancedCapture: () => validateAdvancedCapture,- renderCaptureGrid: () => renderCaptureGrid-});function validateAdvancedCapture(config) {for (const key of Object.keys(config))if (!["version", "shots", "cols", "size", "output"].includes(key))@@ -22646,7 +22359,7 @@ async function renderCaptureGrid(root, config, render, limits) {for (const shot of shots) {const dir = shot.camera.position.map((n, i) => n - shot.camera.target[i]);const view = { name: shot.name, dir };- const png2 = await withCameraVisibility(root, shot, async () => {+ const png = await withCameraVisibility(root, shot, async () => {if (render) {const result = await render({ root, label: shot.name, view, size, camera: shot.camera });derivativeReceipts.push(result.receipt);@@ -22654,15 +22367,15 @@ async function renderCaptureGrid(root, config, render, limits) {}return encodePng(rasterizeCamera(root, shot.camera, size), size, size);});- const decoded = decodePng(png2);+ const decoded = decodePng(png);if (decoded.width !== size || decoded.height !== size)throw new Error("capture cell dimensions do not match request");annotateViewCell(decoded.rgb, size, view);cells.push(decoded.rgb);perFramePngs.push(encodePng(decoded.rgb, size, size));}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);- const png = encodePng(rgb2, width, height);+ const { rgb, width, height } = compositeCellGrid(cells, size, cols);+ const png = encodePng(rgb, width, height);enforceCaptureBytes(config.output === "separate" ? perFramePngs : [png], limits);return {png,@@ -22691,17 +22404,6 @@ var init_camera_capture = __esm(() => {});// src/views/capture.ts-var exports_capture = {};-__export(exports_capture, {- resolveGridCapture: () => resolveGridCapture,- resolveCapture: () => resolveCapture,- describeCapture: () => describeCapture,- captureCellLabel: () => captureCellLabel,- MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,- DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,- CaptureConfigError: () => CaptureConfigError,- CAPTURE_PRESETS: () => CAPTURE_PRESETS-});function captureCellLabel(azimuthDeg, elevationDeg) {const az = Math.round((azimuthDeg % 360 + 360) % 360);const el = Math.round(elevationDeg);@@ -22764,18 +22466,11 @@ function resolveCapture(config) {};}function resolveGridCapture(config, envVariant) {- const resolved2 = resolveCapture(config);+ const resolved = resolveCapture(config);if (config)- return resolved2;+ return resolved;const views = resolveGridViews(envVariant);- return views === resolved2.views ? resolved2 : { ...resolved2, views };-}-function describeCapture(resolved2) {- const angles = resolved2.views.map((v) => {- const { azimuthDeg, elevationDeg } = orbitAnglesOf(v.dir);- return `${v.name} (az ${azimuthDeg}, el ${elevationDeg})`;- }).join("; ");- return `${resolved2.preset} grid, ${resolved2.views.length} cell${resolved2.views.length === 1 ? "" : "s"}: ${angles}`;+ return views === resolved.views ? resolved : { ...resolved, views };}var CAPTURE_PRESETS, DEFAULT_CAPTURE_PRESET = "3x2", MAX_CAPTURE_CELLS = 9, PRESET_COLS, PRESET_CAPACITY, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW, PRESET_VIEWS, CaptureConfigError;var init_capture = __esm(() => {@@ -22849,9 +22544,9 @@ function minimalMatches(root, predicate) {}function selectArchitectureRoofNodes(root) {const candidate = root;- const semantic3 = minimalMatches(candidate, hasArchitectureRoofRole);- if (semantic3.length > 0)- return { mode: "semantic", nodes: semantic3 };+ const semantic = minimalMatches(candidate, hasArchitectureRoofRole);+ if (semantic.length > 0)+ return { mode: "semantic", nodes: semantic };const legacy = minimalMatches(candidate, (node) => legacyRoofName(node.name));return legacy.length > 0 ? { mode: "legacy-name", nodes: legacy } : { mode: "none", nodes: [] };}@@ -22984,20 +22679,20 @@ function flatMaterial(material) {};}const [r, g, b, factorAlpha] = material.getBaseColorFactor();- const alphaMode2 = material.getAlphaMode();- const opacity = alphaMode2 === "BLEND" ? factorAlpha : alphaMode2 === "MASK" && factorAlpha < material.getAlphaCutoff() ? 0 : 1;+ const alphaMode = material.getAlphaMode();+ const opacity = alphaMode === "BLEND" ? factorAlpha : alphaMode === "MASK" && factorAlpha < material.getAlphaCutoff() ? 0 : 1;return {color: { r, g, b },opacity,doubleSided: material.getDoubleSided(),metalness: material.getMetallicFactor(),roughness: material.getRoughnessFactor(),- alphaMode: alphaMode2,+ alphaMode,alphaCutoff: material.getAlphaCutoff(),emissive: material.getEmissiveFactor()};}-function preserveTexture(source, usage2, cache) {+function preserveTexture(source, usage, cache) {if (!source)return null;const encoded = source.getImage();@@ -23009,14 +22704,14 @@ function preserveTexture(source, usage2, cache) {byUsage = new Map;cache.set(source, byUsage);}- const existing = byUsage.get(usage2);+ const existing = byUsage.get(usage);if (existing)return existing;const texture = new Texture;texture.name = source.getName();- texture.colorSpace = usage2 === "color" ? SRGBColorSpace5 : NoColorSpace4;+ texture.colorSpace = usage === "color" ? SRGBColorSpace5 : NoColorSpace4;texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };- byUsage.set(usage2, texture);+ byUsage.set(usage, texture);return texture;}function noteMaterialTextures(material, reasons) {@@ -23052,13 +22747,13 @@ function instanceMatrices(node) {const scales = extension.getAttribute("SCALE");const translation = [];const rotation = [];- const scale2 = [];+ const scale = [];const matrices = [];for (let index = 0;index < count; index++) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);- scales?.getElement(index, scale2);- const local = new Matrix47().compose(new Vector326(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion14(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector326(scales ? scale2[0] : 1, scales ? scale2[1] : 1, scales ? scale2[2] : 1));+ scales?.getElement(index, scale);+ const local = new Matrix47().compose(new Vector326(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion14(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector326(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));matrices.push(world.clone().multiply(local));}return { matrices, count };@@ -23076,17 +22771,17 @@ async function loadGlbGeometryFlatScene(bytes) {const reasons = new Set;const meshes = [];let instanceCount = 0;- const sceneNodes2 = new Set;+ const sceneNodes = new Set;const visit = (node) => {- if (sceneNodes2.has(node))+ if (sceneNodes.has(node))return;- sceneNodes2.add(node);+ sceneNodes.add(node);for (const child of node.listChildren())visit(child);};for (const child of scene.listChildren())visit(child);- for (const node of sceneNodes2) {+ for (const node of sceneNodes) {const mesh = node.getMesh();if (!mesh)continue;@@ -23109,7 +22804,7 @@ async function loadGlbGeometryFlatScene(bytes) {}const material = primitive.getMaterial();noteMaterialTextures(material, reasons);- const geometry2 = {+ const geometry = {getAttribute(name) {return name === "position" ? { array: positions, itemSize: 3, count: positionAccessor.getCount() } : undefined;},@@ -23119,7 +22814,7 @@ async function loadGlbGeometryFlatScene(bytes) {meshes.push({isMesh: true,visible: true,- geometry: geometry2,+ geometry,material: flatMaterial(material),matrixWorld: { elements: [...matrix.elements] }});@@ -23160,12 +22855,12 @@ function localInstanceMatrices(node) {const scales = extension.getAttribute("SCALE");const translation = [];const rotation = [];- const scale2 = [];+ const scale = [];return Array.from({ length: count }, (_, index) => {translations?.getElement(index, translation);rotations?.getElement(index, rotation);- scales?.getElement(index, scale2);- return new Matrix47().compose(new Vector326(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion14(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector326(...scales ? scale2.slice(0, 3) : [1, 1, 1]));+ scales?.getElement(index, scale);+ return new Matrix47().compose(new Vector326(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion14(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector326(...scales ? scale.slice(0, 3) : [1, 1, 1]));});}async function loadGlbReviewScene(bytes) {@@ -23217,21 +22912,21 @@ async function loadGlbReviewScene(bytes) {const material = primitive.getMaterial();noteMaterialTextures(material, reasons);const flat = flatMaterial(material);- const geometry2 = new BufferGeometry14;- geometry2.setAttribute("position", new BufferAttribute8(Float32Array.from(decodedAccessor(position)), 3));+ const geometry = new BufferGeometry14;+ geometry.setAttribute("position", new BufferAttribute8(Float32Array.from(decodedAccessor(position)), 3));const normal = primitive.getAttribute("NORMAL");if (normal) {- geometry2.setAttribute("normal", new BufferAttribute8(Float32Array.from(decodedAccessor(normal)), 3));+ geometry.setAttribute("normal", new BufferAttribute8(Float32Array.from(decodedAccessor(normal)), 3));}const uv = primitive.getAttribute("TEXCOORD_0");if (uv) {- geometry2.setAttribute("uv", new BufferAttribute8(Float32Array.from(decodedAccessor(uv)), 2));+ geometry.setAttribute("uv", new BufferAttribute8(Float32Array.from(decodedAccessor(uv)), 2));}const tangent = primitive.getAttribute("TANGENT");if (tangent) {- geometry2.setAttribute("tangent", new BufferAttribute8(Float32Array.from(decodedAccessor(tangent)), 4));+ geometry.setAttribute("tangent", new BufferAttribute8(Float32Array.from(decodedAccessor(tangent)), 4));}- geometry2.setIndex(new BufferAttribute8(indices, 1));+ geometry.setIndex(new BufferAttribute8(indices, 1));const threeMaterial = new MeshStandardMaterial5({opacity: flat.opacity,transparent: flat.alphaMode === "BLEND",@@ -23254,7 +22949,7 @@ async function loadGlbReviewScene(bytes) {threeMaterial.aoMapIntensity = material.getOcclusionStrength();}for (const [index, matrix] of matrices.entries()) {- const mesh = new Mesh10(geometry2, threeMaterial);+ const mesh = new Mesh10(geometry, threeMaterial);const baseName = source.getName() || sourceMesh.getName() || "Mesh";mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;mesh.matrixAutoUpdate = false;@@ -23335,13 +23030,6 @@ var init_handler = __esm(() => {});// src/evaluator/subprocess.ts-var exports_subprocess = {};-__export(exports_subprocess, {- sanitizedEvaluatorEnv: () => sanitizedEvaluatorEnv,- renderGLBViaSubprocess: () => renderGLBViaSubprocess,- renderGLBViaProcessLaunch: () => renderGLBViaProcessLaunch,- EvaluatorSubprocessError: () => EvaluatorSubprocessError-});import { spawn } from "node:child_process";import { fileURLToPath } from "node:url";function sanitizedEvaluatorEnv(source = process.env) {@@ -23353,11 +23041,11 @@ function sanitizedEvaluatorEnv(source = process.env) {return env;}function boundedInteger(value, fallback, max) {- const resolved2 = value ?? fallback;- if (!Number.isInteger(resolved2) || resolved2 < 1 || resolved2 > max) {+ const resolved = value ?? fallback;+ if (!Number.isInteger(resolved) || resolved < 1 || resolved > max) {throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator controls are invalid.");}- return resolved2;+ return resolved;}function terminateProcess(child, detached) {if (!child.pid || child.killed)@@ -23382,7 +23070,7 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launconst deadlineMs = boundedInteger(controls.deadlineMs, DEFAULT_DEADLINE_MS, 120000);const maxGlbBytes = boundedInteger(controls.maxGlbBytes, DEFAULT_MAX_GLB_BYTES, 64 * 1024 * 1024);const maxResponseBytes = boundedInteger(controls.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);- const request2 = {+ const request = {version: EVALUATOR_REQUEST_VERSION,requestId: "render-1",operation: "execute-export-glb",@@ -23390,7 +23078,7 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launoptions,limits: { maxGlbBytes }};- const requestJson = JSON.stringify(request2);+ const requestJson = JSON.stringify(request);if (Buffer.byteLength(requestJson, "utf8") > MAX_EVALUATOR_REQUEST_BYTES) {throw new EvaluatorSubprocessError("INPUT_INVALID", "Evaluator request exceeds its size limit.");}@@ -23407,7 +23095,7 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, laun};const resolvedLaunch = launch ?? defaultLaunch;const detached = resolvedLaunch.detached === true;- return await new Promise((resolve2, reject) => {+ return await new Promise((resolve, reject) => {const spawnOptions = {env: resolvedLaunch.env,windowsHide: true,@@ -23434,7 +23122,7 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launif (error)reject(error);else- resolve2(result);+ resolve(result);};const timer = setTimeout(() => {finish(new EvaluatorSubprocessError("DEADLINE_EXCEEDED", "Evaluator deadline exceeded."));@@ -23462,17 +23150,17 @@ async function renderGLBViaProcessLaunch(code, options = {}, controls = {}, launcontrols.signal?.addEventListener("abort", abort, { once: true });if (controls.signal?.aborted)abort();- protocol.on("data", (chunk2) => {- responseBytes += chunk2.byteLength;+ protocol.on("data", (chunk) => {+ responseBytes += chunk.byteLength;if (responseBytes > maxResponseBytes) {finish(new EvaluatorSubprocessError("OUTPUT_LIMIT_EXCEEDED", "Evaluator output limit exceeded."));terminateProcess(child, detached);return;}- chunks.push(Buffer.from(chunk2));+ chunks.push(Buffer.from(chunk));});- child.stderr?.on("data", (chunk2) => {- stderrBytes = Math.min(MAX_STDERR_BYTES, stderrBytes + chunk2.byteLength);+ child.stderr?.on("data", (chunk) => {+ stderrBytes = Math.min(MAX_STDERR_BYTES, stderrBytes + chunk.byteLength);});child.on("error", () => {finish(new EvaluatorSubprocessError("WORKER_FAILED", "Evaluator worker failed to start."));@@ -23527,25 +23215,9 @@ var init_subprocess = __esm(() => {});// src/evaluator/isolation.ts-var exports_isolation = {};-__export(exports_isolation, {- renderGLBViaIsolatedEvaluator: () => renderGLBViaIsolatedEvaluator,- isolationReadinessFailureCode: () => isolationReadinessFailureCode,- isolatedEvaluatorLaunch: () => isolatedEvaluatorLaunch,- decodeEvaluatorIsolationTransport: () => decodeEvaluatorIsolationTransport,- decodeEvaluatorIsolationReadiness: () => decodeEvaluatorIsolationReadiness,- assertIsolatedEvaluatorReady: () => assertIsolatedEvaluatorReady,- EvaluatorIsolationReadinessError: () => EvaluatorIsolationReadinessError-});-import { spawn as spawn2 } from "node:child_process";import { existsSync } from "node:fs";import { posix } from "node:path";import { fileURLToPath as fileURLToPath2 } from "node:url";-function isolationReadinessFailureCode(error) {- if (!(error instanceof EvaluatorIsolationReadinessError))- return;- return READINESS_FAILURE_CODES.includes(error.readinessCode) ? error.readinessCode : undefined;-}function isolationUnavailable() {throw new EvaluatorSubprocessError("ISOLATION_UNAVAILABLE", "Isolated evaluator is unavailable.");}@@ -23584,8 +23256,8 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"const bwrapPath = requiredAbsolutePath(host.bwrapPath ?? DEFAULT_BWRAP_PATH);const setprivPath = requiredAbsolutePath(host.setprivPath ?? DEFAULT_SETPRIV_PATH);const prlimitPath = requiredAbsolutePath(host.prlimitPath ?? DEFAULT_PRLIMIT_PATH);- const nodePath5 = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);- for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath5]) {+ const nodePath = requiredAbsolutePath(host.nodePath ?? DEFAULT_NODE_PATH);+ for (const executable of [bwrapPath, setprivPath, prlimitPath, nodePath]) {if (!pathExists(executable))isolationUnavailable();}@@ -23620,7 +23292,7 @@ function isolatedEvaluatorLaunchWithLoader(workerPath, host = {}, loader = "tsx"for (const mount of runtimeMounts(runtimeRoot, pathExists)) {bwrapArgs.push("--ro-bind", mount, mount);}- const nodeArgs = [nodePath5, "--max-old-space-size=512", "--disable-proto=throw"];+ const nodeArgs = [nodePath, "--max-old-space-size=512", "--disable-proto=throw"];if (loader === "tsx")nodeArgs.push("--import", "tsx");nodeArgs.push(resolvedWorkerPath);@@ -23648,219 +23320,10 @@ async function renderGLBViaIsolatedEvaluator(code, options = {}, controls = {})const { host: _, ...processControls } = controls;return renderGLBViaProcessLaunch(code, options, processControls, launch);}-function decodeEvaluatorIsolationReadiness(value) {- if (typeof value !== "object" || value === null || Array.isArray(value))- isolationUnavailable();- const record5 = value;- if (Object.keys(record5).sort().join(",") === "failure,mode,version" && record5.version === READINESS_VERSION && record5.mode === "isolated" && [- "loader-probe-boot",- "invariant-namespace",- "invariant-environment",- "invariant-filesystem",- "invariant-network",- "invariant-generated-policy"- ].includes(String(record5.failure))) {- return record5;- }- if (Object.keys(record5).sort().join(",") !== "checks,mode,version" || record5.version !== READINESS_VERSION || record5.mode !== "isolated" || !Array.isArray(record5.checks) || record5.checks.length !== READINESS_CHECKS.length || record5.checks.join(",") !== READINESS_CHECKS.join(",")) {- isolationUnavailable();- }- return record5;-}-function decodeEvaluatorIsolationTransport(value) {- if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).sort().join(",") !== "transport,version") {- isolationUnavailable();- }- const record5 = value;- if (record5.version !== TRANSPORT_VERSION || record5.transport !== "fd3")- isolationUnavailable();- return record5;-}-function terminateReadinessChild(child) {- try {- if (child.pid)- process.kill(-child.pid, "SIGKILL");- } catch {}-}-async function assertIsolationTransport(launch) {- return await new Promise((resolve2, reject) => {- const child = spawn2(launch.command, launch.args, {- env: launch.env,- windowsHide: true,- detached: true,- stdio: ["ignore", "pipe", "ignore", "pipe"]- });- const stdoutChunks = [];- const protocolChunks = [];- let stdoutBytes = 0;- let protocolBytes = 0;- let settled = false;- const fail = (readinessCode) => {- if (settled)- return;- settled = true;- clearTimeout(timer);- reject(new EvaluatorIsolationReadinessError(readinessCode));- };- const timer = setTimeout(() => {- terminateReadinessChild(child);- fail("deadline");- }, PROBE_DEADLINE_MS);- child.stdout?.on("data", (chunk2) => {- stdoutBytes += chunk2.byteLength;- if (stdoutBytes > MAX_TRANSPORT_STDOUT_BYTES) {- terminateReadinessChild(child);- fail("wrapper-launch");- return;- }- stdoutChunks.push(Buffer.from(chunk2));- });- const protocol = child.stdio[3];- if (!protocol) {- terminateReadinessChild(child);- fail("fd3-transport");- return;- }- protocol.on("data", (chunk2) => {- protocolBytes += chunk2.byteLength;- if (protocolBytes > MAX_READINESS_PROTOCOL_BYTES) {- terminateReadinessChild(child);- fail("fd3-transport");- return;- }- protocolChunks.push(Buffer.from(chunk2));- });- child.once("error", () => fail("wrapper-launch"));- child.once("close", (code) => {- if (settled)- return;- const stdout = Buffer.concat(stdoutChunks).toString("utf8");- if (stdout !== TRANSPORT_STDOUT_MARKER)- return fail("wrapper-launch");- if (code !== 0 || protocolChunks.length === 0)- return fail("fd3-transport");- try {- decodeEvaluatorIsolationTransport(JSON.parse(Buffer.concat(protocolChunks).toString("utf8")));- settled = true;- clearTimeout(timer);- resolve2();- } catch {- fail("fd3-transport");- }- });- });-}-async function runIsolationProbe(launch) {- return await new Promise((resolve2, reject) => {- const child = spawn2(launch.command, launch.args, {- env: launch.env,- windowsHide: true,- detached: true,- stdio: ["ignore", "ignore", "ignore", "pipe"]- });- const protocol = child.stdio[3];- const chunks = [];- let bytes = 0;- let settled = false;- const fail = (readinessCode) => {- if (settled)- return;- settled = true;- clearTimeout(timer);- reject(new EvaluatorIsolationReadinessError(readinessCode));- };- const timer = setTimeout(() => {- terminateReadinessChild(child);- fail("deadline");- }, PROBE_DEADLINE_MS);- if (!protocol) {- terminateReadinessChild(child);- fail("fd3-transport");- return;- }- protocol.on("data", (chunk2) => {- bytes += chunk2.byteLength;- if (bytes > MAX_READINESS_PROTOCOL_BYTES) {- terminateReadinessChild(child);- fail("loader-probe-boot");- return;- }- chunks.push(Buffer.from(chunk2));- });- child.once("error", () => fail("wrapper-launch"));- child.once("close", (code) => {- if (settled)- return;- if (chunks.length === 0)- return fail("loader-probe-boot");- try {- const result = decodeEvaluatorIsolationReadiness(JSON.parse(Buffer.concat(chunks).toString("utf8")));- if ("failure" in result)- return fail(result.failure);- if (code !== 0)- return fail("loader-probe-boot");- settled = true;- clearTimeout(timer);- resolve2(result);- } catch {- fail("loader-probe-boot");- }- });- });-}-async function assertIsolatedEvaluatorReady(host = {}) {- if (typeof process.getuid !== "function" || process.getuid() === 0) {- throw new EvaluatorIsolationReadinessError("invariant-namespace");- }- const transportPath = fileURLToPath2(new URL("./transport-worker.mjs", import.meta.url));- const probePath = fileURLToPath2(new URL("./probe-worker.ts", import.meta.url));- let transportLaunch;- let probeLaunch;- try {- transportLaunch = isolatedEvaluatorLaunchWithLoader(transportPath, host, "module");- probeLaunch = isolatedEvaluatorLaunch(probePath, host);- } catch {- throw new EvaluatorIsolationReadinessError("wrapper-launch");- }- await assertIsolationTransport(transportLaunch);- return await runIsolationProbe(probeLaunch);-}-var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", READINESS_VERSION = "kiln.evaluator.isolation-readiness.v1", TRANSPORT_VERSION = "kiln.evaluator.isolation-transport.v1", TRANSPORT_STDOUT_MARKER = `kiln-evaluator-transport-boot-v1-`, PROBE_DEADLINE_MS = 8000, MAX_READINESS_PROTOCOL_BYTES, MAX_TRANSPORT_STDOUT_BYTES = 256, READINESS_FAILURE_CODES, READINESS_CHECKS, EvaluatorIsolationReadinessError;+var DEFAULT_RUNTIME_ROOT = "/app", DEFAULT_BWRAP_PATH = "/usr/local/bin/bwrap", DEFAULT_SETPRIV_PATH = "/usr/bin/setpriv", DEFAULT_PRLIMIT_PATH = "/usr/bin/prlimit", DEFAULT_NODE_PATH = "/usr/local/bin/node", MAX_READINESS_PROTOCOL_BYTES;var init_isolation = __esm(() => {init_subprocess();MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;- READINESS_FAILURE_CODES = [- "wrapper-launch",- "fd3-transport",- "loader-probe-boot",- "invariant-namespace",- "invariant-environment",- "invariant-filesystem",- "invariant-network",- "invariant-generated-policy",- "deadline"- ];- READINESS_CHECKS = [- "user-namespace",- "no-new-privileges",- "capabilities-empty",- "environment-exact",- "product-filesystem-denied",- "host-filesystem-denied",- "runtime-filesystem-read-only",- "network-namespace-empty",- "metadata-and-local-network-denied",- "generated-capabilities-denied"- ];- EvaluatorIsolationReadinessError = class EvaluatorIsolationReadinessError extends EvaluatorSubprocessError {- readinessCode;- constructor(readinessCode) {- super("ISOLATION_UNAVAILABLE", "Isolated evaluator readiness check failed.");- this.name = "EvaluatorIsolationReadinessError";- this.readinessCode = readinessCode;- }- };});// src/evaluator/index.ts@@ -23884,8 +23347,8 @@ function cloneReference(reference) {}function currentEvidence(sequence, surface, fidelity) {if (fidelity.version === "kiln.view-fidelity.v1") {- const valid2 = SHA256.test(fidelity.inputGlbSha256) && fidelity.rendererId.trim().length > 0 && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded);- if (!valid2) {+ const valid = SHA256.test(fidelity.inputGlbSha256) && fidelity.rendererId.trim().length > 0 && (!fidelity.materialFaithful || fidelity.delivered === "full-material" && !fidelity.degraded);+ if (!valid) {return {sequence,surface,@@ -23990,10 +23453,6 @@ var init_evidence_history = __esm(() => {});// src/views/renderer-id.ts-var exports_renderer_id = {};-__export(exports_renderer_id, {- CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID-});import { readFileSync as readFileSync2 } from "node:fs";function engineVersion() {for (const path of ["../package.json", "../../package.json"]) {@@ -24014,66 +23473,13 @@ var init_renderer_id = __esm(() => {// src/views/scene-raster.tsimport * as THREE31 from "three";-async function rasterizeComposedScene(parts, opts = {}) {- const views = opts.views?.length ? opts.views : SCENE_VIEWS;- const size = opts.size ?? 320;- const group = new THREE31.Group;- const baseByInput = new Map;- for (const part of parts) {- if (part.code === undefined === (part.glb === undefined)) {- throw new TypeError("Composed part must provide exactly one of code or glb.");- }- const key = part.glb ?? part.code;- let base = baseByInput.get(key);- if (!base) {- const glb = part.glb ? Uint8Array.from(part.glb) : (await resolveEvaluatorPortV1(opts.evaluatorPort, opts.evaluatorProfile ?? "trusted-local").render(part.code)).glb;- base = (await loadGlbReviewScene(glb)).root;- baseByInput.set(key, base);- }- const inst = base.clone(true);- inst.position.set(part.pos[0], part.pos[1], part.pos[2]);- inst.rotation.set(0, part.rotYDeg * DEG2, 0);- inst.scale.setScalar(part.scale);- group.add(inst);- }- group.updateMatrixWorld(true);- const cols = Math.min(Math.max(views.length, 1), 3);- const rows = Math.ceil(views.length / cols);- const width = cols * size + (cols + 1) * PAD2;- const height = rows * size + (rows + 1) * PAD2;- const grid = new Uint8Array(width * height * 3);- for (let i = 0;i < width * height; i++) {- grid[i * 3] = PAD_COLOR2[0];- grid[i * 3 + 1] = PAD_COLOR2[1];- grid[i * 3 + 2] = PAD_COLOR2[2];- }- for (let vi = 0;vi < views.length; vi++) {- const cell = rasterizeView(group, views[vi].dir, { size });- const col = vi % cols;- const row = Math.floor(vi / cols);- const x0 = PAD2 + col * (size + PAD2);- const y0 = PAD2 + row * (size + PAD2);- for (let y = 0;y < size; y++) {- const src = y * size * 3;- const dst = ((y0 + y) * width + x0) * 3;- grid.set(cell.subarray(src, src + size * 3), dst);- }- }- return { png: encodePng(grid, width, height), width, height, views: views.map((v) => v.name) };-}-var DEG2, PAD2 = 4, PAD_COLOR2, SCENE_VIEWS;+var DEG2;var init_scene_raster = __esm(() => {init_evaluator();init_glb();init_png();init_raster();DEG2 = Math.PI / 180;- PAD_COLOR2 = [10, 11, 13];- SCENE_VIEWS = [- { name: "Hero 3/4", dir: [0.7, 0.45, 0.7] },- { name: "Reverse 3/4", dir: [-0.7, 0.45, -0.7] },- { name: "Top", dir: [0, 1, 0.0001] }- ];});// src/views/vehicle.ts@@ -24097,8 +23503,8 @@ function chassisBounds(root, inverse) {const matrix = inverse.clone().multiply(part.matrixWorld);for (const x of [box.min.x, box.max.x])for (const y of [box.min.y, box.max.y])- for (const z3 of [box.min.z, box.max.z]) {- bounds.expandByPoint(new THREE32.Vector3(x, y, z3).applyMatrix4(matrix));+ for (const z of [box.min.z, box.max.z]) {+ bounds.expandByPoint(new THREE32.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -24111,10 +23517,10 @@ function describeVehicleDiagnostics(root) {const assemblies = resolveVehicleWheelAssemblies(root);const wheels = assemblies.map((wheel) => ({id: wheel.id,- center: tuple7(wheel.centerWorld.clone().applyMatrix4(inverse)),+ center: tuple6(wheel.centerWorld.clone().applyMatrix4(inverse)),radius: wheel.radius ?? 0,width: wheel.width ?? 0,- axle: tuple7(wheel.spinAxisWorld.clone().transformDirection(inverse)),+ axle: tuple6(wheel.spinAxisWorld.clone().transformDirection(inverse)),loadBearing: wheel.loadBearing}));const byAxle = new Map;@@ -24155,7 +23561,7 @@ function describeVehicleDiagnostics(root) {return {schemaVersion: 1,forwardArrow: { start: [0, 0, 0], end: [1, 0, 0] },- ...chassis ? { chassisBox: { min: tuple7(chassis.min), max: tuple7(chassis.max) } } : {},+ ...chassis ? { chassisBox: { min: tuple6(chassis.min), max: tuple6(chassis.max) } } : {},axles,wheels,...supportPlaneY !== undefined ? { supportPlaneY } : {},@@ -24165,41 +23571,41 @@ function describeVehicleDiagnostics(root) {function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}-function rod(name, start, end, radius, color2, role) {+function rod(name, start, end, radius, color, role) {const from = new THREE32.Vector3(...start);const to = new THREE32.Vector3(...end);const direction = to.clone().sub(from);- const length3 = direction.length();- const geometry2 = length3 > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length3, 8) : new THREE32.SphereGeometry(radius, 8, 6);- const result = new THREE32.Mesh(geometry2, new THREE32.MeshBasicMaterial({ color: color2 }));+ const length = direction.length();+ const geometry = length > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length, 8) : new THREE32.SphereGeometry(radius, 8, 6);+ const result = new THREE32.Mesh(geometry, new THREE32.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);- if (length3 > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length3));+ if (length > 0.000000001) {+ result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}-function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagnostics(root)) {+function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {const overlay = new THREE32.Group;overlay.name = "VehicleDiagnosticOverlay";- const chassisSpan = descriptor2.chassisBox ? Math.max(descriptor2.chassisBox.max[0] - descriptor2.chassisBox.min[0], descriptor2.chassisBox.max[1] - descriptor2.chassisBox.min[1], descriptor2.chassisBox.max[2] - descriptor2.chassisBox.min[2]) : 1;+ const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;const thickness = Math.max(0.01, chassisSpan * 0.008);const arrow = new THREE32.Group;arrow.name = "Diagnostic_Forward_+X";tagDiagnostic(arrow, "diagnostic.vehicle.forward");- arrow.add(rod("Diagnostic_Forward_Shaft", descriptor2.forwardArrow.start, [descriptor2.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));+ arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";- arrowHead.position.set(descriptor2.forwardArrow.end[0] - 0.12, 0, 0);+ arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);- for (const axle of descriptor2.axles) {+ for (const axle of descriptor.axles) {overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));}- for (const wheel of descriptor2.wheels) {+ for (const wheel of descriptor.wheels) {const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);@@ -24210,11 +23616,11 @@ function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagntagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}- if (descriptor2.chassisBox) {+ if (descriptor.chassisBox) {const chassis = new THREE32.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");- const { min, max } = descriptor2.chassisBox;+ const { min, max } = descriptor.chassisBox;const corners = [[min[0], min[1], min[2]],[max[0], min[1], min[2]],@@ -24244,13 +23650,13 @@ function createVehicleDiagnosticOverlay(root, descriptor2 = describeVehicleDiagn}overlay.add(chassis);}- if (descriptor2.supportPlaneY !== undefined) {+ if (descriptor.supportPlaneY !== undefined) {const plane = new THREE32.Group;plane.name = "Diagnostic_SupportPlane";tagDiagnostic(plane, "diagnostic.vehicle.support-plane");- const halfX = Math.max(1, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[0]), Math.abs(descriptor2.chassisBox.max[0])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;- const halfZ = Math.max(0.8, ...descriptor2.chassisBox ? [Math.abs(descriptor2.chassisBox.min[2]), Math.abs(descriptor2.chassisBox.max[2])] : [], ...descriptor2.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;- const y = descriptor2.supportPlaneY;+ const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;+ const halfZ = Math.max(0.8, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[2]), Math.abs(descriptor.chassisBox.max[2])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[2]) + wheel.width / 2)) + 0.2;+ const y = descriptor.supportPlaneY;const planeLines = [[[-halfX, y, -halfZ],@@ -24303,8 +23709,8 @@ function compositeForCapture(root, overlay) {children: [root, overlay]};}-function selectWheelSectionRequest(requestValue, descriptor2) {- const target = descriptor2.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor2.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor2.wheels[0];+function selectWheelSectionRequest(requestValue, descriptor) {+ const target = descriptor.wheels.find((wheel) => /right.*front|front.*right/i.test(wheel.id)) ?? descriptor.wheels.find((wheel) => /right/i.test(wheel.id)) ?? descriptor.wheels[0];if (!target?.id.startsWith("wheel.assembly."))return requestValue;const suffix = target.id.replace(/[^a-zA-Z0-9.-]/g, "-");@@ -24318,12 +23724,12 @@ function selectWheelSectionRequest(requestValue, descriptor2) {function captureVehicleDiagnosticViews(root, intent, size = 256) {if (intent.category !== "vehicle")return [];- const descriptor2 = describeVehicleDiagnostics(root);- const overlay = createVehicleDiagnosticOverlay(root, descriptor2);+ const descriptor = describeVehicleDiagnostics(root);+ const overlay = createVehicleDiagnosticOverlay(root, descriptor);const composite = compositeForCapture(root, overlay);const requests = planDiagnosticViews(intent).extra.filter((value) => value.variant === "vehicle-underbody" || value.variant === "vehicle-wheel-section");return requests.map((baseRequest) => {- const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor2) : baseRequest;+ const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor) : baseRequest;const frame = renderDiagnosticView(composite, requestValue, { size });return {id: frame.id,@@ -24335,11 +23741,11 @@ function captureVehicleDiagnosticViews(root, intent, size = 256) {height: frame.height,png: frame.png,regions: frame.regions,- descriptor: descriptor2+ descriptor};});}-var tuple7 = (value) => [value.x, value.y, value.z];+var tuple6 = (value) => [value.x, value.y, value.z];var init_vehicle3 = __esm(() => {init_contracts();init_vehicle();@@ -24349,93 +23755,24 @@ var init_vehicle3 = __esm(() => {// src/views/index.tsvar exports_views = {};__export(exports_views, {- withCameraVisibility: () => withCameraVisibility,- validateResolvedAssetCamera: () => validateResolvedAssetCamera,- validateAdvancedCapture: () => validateAdvancedCapture,- stampAxisGnomon: () => stampAxisGnomon,- snapSceneToPalette: () => snapSceneToPalette,- selectCameraSubject: () => selectCameraSubject,- selectArchitectureRoofNodes: () => selectArchitectureRoofNodes,- resolveGridViews: () => resolveGridViews,- resolveGridCapture: () => resolveGridCapture,- resolveCaptureLimits: () => resolveCaptureLimits,- resolveCapture: () => resolveCapture,- resolveAssetCamera: () => resolveAssetCamera,- renderViewGrid: () => renderViewGrid,- renderInteriorGrid: () => renderInteriorGrid,- renderGlbViewGrid: () => renderGlbViewGrid,- renderGlbViewCell: () => renderGlbViewCell,- renderDiagnosticViews: () => renderDiagnosticViews,- renderDiagnosticView: () => renderDiagnosticView,- renderCodeViewGrid: () => renderCodeViewGrid,- renderClipAnimation: () => renderClipAnimation,- renderCaptureGrid: () => renderCaptureGrid,- rasterizeView: () => rasterizeView,- rasterizeComposedScene: () => rasterizeComposedScene,- rasterizeCamera: () => rasterizeCamera,- prepareClip: () => prepareClip,- poseSceneAtTime: () => poseSceneAtTime,- planFrameTimes: () => planFrameTimes,- planDiagnosticViews: () => planDiagnosticViews,- planCharacterDiagnosticRequests: () => planCharacterDiagnosticRequests,- orbitDir: () => orbitDir,- orbitAnglesOf: () => orbitAnglesOf,- measureBounds: () => measureBounds,- loadGlbReviewScene: () => loadGlbReviewScene,- loadGlbGeometryFlatScene: () => loadGlbGeometryFlatScene,- listCameraSubjects: () => listCameraSubjects,- hideNodeInScene: () => hideNodeInScene,- hideArchitectureRoofInScene: () => hideArchitectureRoofInScene,- hasArchitectureRoofRole: () => hasArchitectureRoofRole,- geometryFlatTextureReasonCode: () => geometryFlatTextureReasonCode,- findClip: () => findClip,- encodePng: () => encodePng,- describeVehicleDiagnostics: () => describeVehicleDiagnostics,- describeCapture: () => describeCapture,- decodePng: () => decodePng,- createVehicleDiagnosticOverlay: () => createVehicleDiagnosticOverlay,- createCachedRenderPort: () => createCachedRenderPort,- coverage: () => coverage,- compositeViewPngGrid: () => compositeViewPngGrid,- compositeCellGrid: () => compositeCellGrid,- clipNames: () => clipNames,- captureVehicleDiagnosticViews: () => captureVehicleDiagnosticViews,- captureCpuCell: () => captureCpuCell,- captureCellLabel: () => captureCellLabel,- cameraFromBounds: () => cameraFromBounds,- buildCharacterDiagnosticDescriptor: () => buildCharacterDiagnosticDescriptor,- annotateViewCell: () => annotateViewCell,- ViewEvidenceHistoryStore: () => ViewEvidenceHistoryStore,- SIX_VIEWS_REAR_QUARTER: () => SIX_VIEWS_REAR_QUARTER,- SIX_VIEWS: () => SIX_VIEWS,- SCENE_VIEWS: () => SCENE_VIEWS,- MemoryCaptureCache: () => MemoryCaptureCache,- MIN_ELEVATION_DEG: () => MIN_ELEVATION_DEG,- MAX_ELEVATION_DEG: () => MAX_ELEVATION_DEG,- MAX_CAPTURE_CELLS: () => MAX_CAPTURE_CELLS,- INTERIOR_VIEWS: () => INTERIOR_VIEWS,- GlbGeometryFlatError: () => GlbGeometryFlatError,- GRID_COLS: () => GRID_COLS,- GRID_BACKGROUND_RGB: () => GRID_BACKGROUND_RGB,- GRID_BACKGROUND_HEX: () => GRID_BACKGROUND_HEX,- GLB_GEOMETRY_FLAT_REASON: () => GLB_GEOMETRY_FLAT_REASON,- GENERIC_DIAGNOSTIC_REQUESTS: () => GENERIC_DIAGNOSTIC_REQUESTS,- GENERIC_DIAGNOSTIC_CAMERAS: () => GENERIC_DIAGNOSTIC_CAMERAS,- GENERIC_DIAGNOSTIC_BUFFER_IDS: () => GENERIC_DIAGNOSTIC_BUFFER_IDS,- DEFAULT_CAPTURE_PRESET: () => DEFAULT_CAPTURE_PRESET,- DEFAULT_CAPTURE_LIMITS: () => DEFAULT_CAPTURE_LIMITS,- CaptureConfigError: () => CaptureConfigError,CPU_RASTER_RENDERER_ID: () => CPU_RASTER_RENDERER_ID,- CHARACTER_MOTION_DIAGNOSTIC_PHASES: () => CHARACTER_MOTION_DIAGNOSTIC_PHASES,- CAPTURE_PRESETS: () => CAPTURE_PRESETS,- ARCHITECTURE_ROOF_ROLE_PREFIXES: () => ARCHITECTURE_ROOF_ROLE_PREFIXES+ cameraFromBounds: () => cameraFromBounds,+ listCameraSubjects: () => listCameraSubjects,+ loadGlbReviewScene: () => loadGlbReviewScene,+ measureBounds: () => measureBounds,+ renderCaptureGrid: () => renderCaptureGrid,+ renderClipAnimation: () => renderClipAnimation,+ renderGlbViewCell: () => renderGlbViewCell,+ renderGlbViewGrid: () => renderGlbViewGrid,+ renderInteriorGrid: () => renderInteriorGrid,+ resolveGridCapture: () => resolveGridCapture});-function setLinearColor(color2, rgb2) {- if (!color2)+function setLinearColor(color, rgb) {+ if (!color)return;- color2.r = rgb2[0];- color2.g = rgb2[1];- color2.b = rgb2[2];+ color.r = rgb[0];+ color.g = rgb[1];+ color.b = rgb[2];}function snapMaterialToPalette(mat, slots, idx) {if (!mat.color)@@ -24456,8 +23793,8 @@ function snapMaterialToPalette(mat, slots, idx) {return false;const slot = slots[slotI];const kind = slot.kind ?? "opaque";- const rgb2 = hexToLinearRgb(slot.color);- setLinearColor(mat.color, rgb2);+ const rgb = hexToLinearRgb(slot.color);+ setLinearColor(mat.color, rgb);if (mat.metalness !== undefined)mat.metalness = slot.metalness ?? 0;if (mat.roughness !== undefined)@@ -24473,7 +23810,7 @@ function snapMaterialToPalette(mat, slots, idx) {}if (mat.emissive) {if (kind === "glow") {- setLinearColor(mat.emissive, rgb2);+ setLinearColor(mat.emissive, rgb);mat.emissiveIntensity = Math.max(mat.emissiveIntensity ?? 1, 1);} else {setLinearColor(mat.emissive, [0, 0, 0]);@@ -24510,19 +23847,19 @@ async function renderViewGrid(root, opts = {}) {if (opts.capture?.shots || opts.capture?.version)return renderCaptureGrid(root, opts.capture, undefined, opts.captureLimits);const size = opts.size ?? 384;- const resolved2 = resolveGridCapture(opts.capture, process.env["KILN_GRID_VARIANT"]);- const views = opts.views ?? resolved2.views;- const cols = opts.cols ?? resolved2.cols;+ const resolved = resolveGridCapture(opts.capture, process.env["KILN_GRID_VARIANT"]);+ const views = opts.views ?? resolved.views;+ const cols = opts.cols ?? resolved.cols;enforceCapturePixels(views.length, size, cols, opts.captureLimits);if (opts.snapPalette?.length)snapSceneToPalette(root, opts.snapPalette);- const wantsZoom = resolved2.zooms.some((z3) => z3 !== undefined);+ const wantsZoom = resolved.zooms.some((z) => z !== undefined);const sceneBounds = wantsZoom ? measureBounds(root) : undefined;const cache = opts.snapPalette?.length ? undefined : opts.captureCache;let reused = 0;const cells = [];for (let vi = 0;vi < views.length; vi++) {- const zoom = resolved2.zooms[vi];+ const zoom = resolved.zooms[vi];const rasterOptions = {size,backfaceCull: opts.backfaceCull,@@ -24531,11 +23868,11 @@ async function renderViewGrid(root, opts = {}) {};let cell;if (cache && opts.artifactGlbSha256) {- const { CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2 } = await Promise.resolve().then(() => (init_renderer_id(), exports_renderer_id));+ await Promise.resolve().then(() => init_renderer_id());const camera2 = cameraFromBounds(rasterOptions.frameBounds ?? measureBounds(root), views[vi].dir);const result = await captureCpuCell(cache, {artifactGlbSha256: opts.artifactGlbSha256,- rendererId: `${CPU_RASTER_RENDERER_ID2}/legacy-fit`,+ rendererId: `${CPU_RASTER_RENDERER_ID}/legacy-fit`,camera: camera2,size,backfaceCull: opts.backfaceCull ?? true@@ -24556,34 +23893,34 @@ async function renderViewGrid(root, opts = {}) {annotateViewCell(cell, size, views[vi]);cells.push(cell);}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, cols);- const png = encodePng(rgb2, width, height);+ const { rgb, width, height } = compositeCellGrid(cells, size, cols);+ const png = encodePng(rgb, width, height);enforceCaptureBytes([png], opts.captureLimits);return {png,width,height,views: views.map((v) => v.name),- capture: { preset: resolved2.preset, cols, cells: views.length },+ capture: { preset: resolved.preset, cols, cells: views.length },...cache && opts.artifactGlbSha256 ? { captureCache: { hit: reused === views.length, reused, total: views.length } } : {}};}async function hashGlbViewInput(bytes) {const copy = Uint8Array.from(bytes);- const digest3 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));- return `sha256:${[...digest3].map((value) => value.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));+ return `sha256:${[...digest].map((value) => value.toString(16).padStart(2, "0")).join("")}`;}async function renderGlbViewCell(bytes, view, options = {}) {const exactBytes = Uint8Array.from(bytes);const loaded = await loadGlbGeometryFlatScene(exactBytes);const size = options.size ?? 256;- const rgb2 = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull) : rasterizeView(loaded.root, view.dir, {+ const rgb = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull) : rasterizeView(loaded.root, view.dir, {size,...options.backfaceCull !== undefined ? { backfaceCull: options.backfaceCull } : {},...options.frameBounds ? { frameBounds: options.frameBounds } : {}});return {- png: encodePng(rgb2, size, size),+ png: encodePng(rgb, size, size),width: size,height: size,inputGlbSha256: await hashGlbViewInput(exactBytes),@@ -24616,11 +23953,6 @@ function expandFrameBounds(b, factor) {}return { min, max };}-async function renderCodeViewGrid(code, opts = {}) {- const { evaluatorPort, evaluatorProfile, ...viewOptions } = opts;- const rendered = await resolveEvaluatorPortV1(evaluatorPort, evaluatorProfile ?? "trusted-local").render(code);- return renderGlbViewGrid(rendered.glb, viewOptions);-}function resolveCamera(name) {const key = (name ?? "right").trim().toLowerCase().replace(/[_\s]+/g, "-");return ANIM_CAMERAS[key] ?? ANIM_CAMERAS[ANIM_CAMERA_ALIASES[key] ?? ""] ?? ANIM_CAMERAS["right"];@@ -24740,8 +24072,8 @@ async function renderClipAnimation(root, clips, opts = {}) {pngs: cells.map((c) => encodePng(c, size, size))};}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size);- return { ...baseMeta, width, height, png: encodePng(rgb2, width, height) };+ const { rgb, width, height } = compositeCellGrid(cells, size);+ return { ...baseMeta, width, height, png: encodePng(rgb, width, height) };}function normalizeVec(v) {const len = Math.hypot(v[0], v[1], v[2]) || 1;@@ -24794,9 +24126,9 @@ async function renderInteriorGrid(root, opts = {}) {stampLabel(cell, size, size, labelScale, labelScale, view.name, labelScale);cells.push(cell);}- const { rgb: rgb2, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);+ const { rgb, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);return {- png: encodePng(rgb2, width, height),+ png: encodePng(rgb, width, height),width,height,views: INTERIOR_VIEWS.map((v) => v.name),@@ -24872,7 +24204,7 @@ var init_views = __esm(() => {// src/views/character-capture.tsimport * as THREE33 from "three";-function drawLine2(rgb2, width, height, from, to, color2) {+function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);const x1 = Math.round(to[0]);@@ -24885,9 +24217,9 @@ function drawLine2(rgb2, width, height, from, to, color2) {while (true) {if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {const offset = (y0 * width + x0) * 3;- rgb2[offset] = color2[0];- rgb2[offset + 1] = color2[1];- rgb2[offset + 2] = color2[2];+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}if (x0 === x1 && y0 === y1)break;@@ -24902,9 +24234,9 @@ function drawLine2(rgb2, width, height, from, to, color2) {}}}-function drawCross(rgb2, width, height, point, color2, radius = 3) {- drawLine2(rgb2, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color2);- drawLine2(rgb2, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color2);+function drawCross(rgb, width, height, point, color, radius = 3) {+ drawLine2(rgb, width, height, [point[0] - radius, point[1]], [point[0] + radius, point[1]], color);+ drawLine2(rgb, width, height, [point[0], point[1] - radius], [point[0], point[1] + radius], color);}function projector(root, cameraId, size) {root.updateMatrixWorld(true);@@ -24912,48 +24244,48 @@ function projector(root, cameraId, size) {if (bounds.isEmpty())bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));const center = bounds.getCenter(new THREE33.Vector3);- const camera2 = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);+ const camera = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);const upHint = new THREE33.Vector3(0, 1, 0);- const xAxis = new THREE33.Vector3().crossVectors(upHint, camera2).normalize();- const yAxis = new THREE33.Vector3().crossVectors(camera2, xAxis).normalize();- let extent2 = 0.000001;+ const xAxis = new THREE33.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE33.Vector3().crossVectors(camera, xAxis).normalize();+ let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);- extent2 = Math.max(extent2, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));+ extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));}- const scale2 = size * 0.45 / extent2;+ const scale = size * 0.45 / extent;return (assetPoint) => {const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);- return [size / 2 + world.dot(xAxis) * scale2, size / 2 - world.dot(yAxis) * scale2];+ return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}-function skeletonCapture(root, request2, findings, size) {+function skeletonCapture(root, request, findings, size) {const baseRequest = {- id: request2.id,- label: request2.label,- cameraId: request2.cameraId,+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,buffer: "semantic-overlay",scope: "category",variant: "character-skeleton",- focusRolePrefixes: request2.focusRolePrefixes+ focusRolePrefixes: request.focusRolePrefixes};const frame = renderDiagnosticView(root, baseRequest, { size });- const descriptor2 = buildCharacterDiagnosticDescriptor(root, findings);- const project2 = projector(root, request2.cameraId, size);- const byRole = new Map(descriptor2.joints.map((joint) => [joint.role, joint]));- for (const edge of descriptor2.edges) {+ const descriptor = buildCharacterDiagnosticDescriptor(root, findings);+ const project = projector(root, request.cameraId, size);+ const byRole = new Map(descriptor.joints.map((joint) => [joint.role, joint]));+ for (const edge of descriptor.edges) {const parent = byRole.get(edge.parentRole);const child = byRole.get(edge.childRole);if (!parent || !child)continue;- drawLine2(frame.rgb, frame.width, frame.height, project2(parent.assetPosition), project2(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);- }- for (const joint of descriptor2.joints) {- const point = project2(joint.assetPosition);- const color2 = rgbFromHex(joint.color);- drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color2);- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.forwardAxisEnd), [64, 220, 255]);- drawLine2(frame.rgb, frame.width, frame.height, point, project2(joint.bendAxisEnd), [255, 105, 210]);+ drawLine2(frame.rgb, frame.width, frame.height, project(parent.assetPosition), project(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);+ }+ for (const joint of descriptor.joints) {+ const point = project(joint.assetPosition);+ const color = rgbFromHex(joint.color);+ drawCross(frame.rgb, frame.width, frame.height, point, joint.contact ? [55, 235, 130] : color);+ drawLine2(frame.rgb, frame.width, frame.height, point, project(joint.forwardAxisEnd), [64, 220, 255]);+ drawLine2(frame.rgb, frame.width, frame.height, point, project(joint.bendAxisEnd), [255, 105, 210]);stampLabel(frame.rgb, frame.width, frame.height, Math.max(0, Math.min(frame.width - 2, Math.round(point[0] + 3))), Math.max(0, Math.min(frame.height - 7, Math.round(point[1] - 6))), joint.label.toUpperCase().replace(/[^A-Z0-9]+/g, " ").slice(0, 18), 1);frame.regions.push({nodeName: joint.nodeName,@@ -24965,17 +24297,17 @@ function skeletonCapture(root, request2, findings, size) {Math.min(frame.width - 1, Math.round(point[0]) + 4),Math.min(frame.height - 1, Math.round(point[1]) + 4)],- color: color2,+ color,triangleCount: 0});}- const arrow = descriptor2.canonicalForwardArrow;- drawLine2(frame.rgb, frame.width, frame.height, project2(arrow.start), project2(arrow.end), [255, 220, 64]);+ const arrow = descriptor.canonicalForwardArrow;+ drawLine2(frame.rgb, frame.width, frame.height, project(arrow.start), project(arrow.end), [255, 220, 64]);frame.regions.sort((a, b) => a.nodePath.localeCompare(b.nodePath));return {id: frame.id,label: frame.label,- cameraId: request2.cameraId,+ cameraId: request.cameraId,kind: "skeleton",width: frame.width,height: frame.height,@@ -24996,32 +24328,32 @@ async function captureCharacterDiagnosticViews(root, clips, intent, findings = [const requests = planCharacterDiagnosticRequests(intent);const captures = [];try {- for (const request2 of requests) {- if (request2.variant === "character-skeleton") {- captures.push(skeletonCapture(root, request2, findings, size));+ for (const request of requests) {+ if (request.variant === "character-skeleton") {+ captures.push(skeletonCapture(root, request, findings, size));continue;}- if (!request2.clipName)+ if (!request.clipName)continue;const strip = await renderClipAnimation(root, clips, {- clip: request2.clipName,- camera: request2.cameraId,- frames: request2.phaseFractions?.length ?? 6,+ clip: request.clipName,+ camera: request.cameraId,+ frames: request.phaseFractions?.length ?? 6,size});if (!strip.ok || !strip.png || !strip.width || !strip.height)continue;captures.push({- id: request2.id,- label: request2.label,- cameraId: request2.cameraId,+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,kind: "motion-strip",width: strip.width,height: strip.height,png: strip.png,regions: [],- clipName: request2.clipName,- phaseFractions: request2.phaseFractions+ clipName: request.clipName,+ phaseFractions: request.phaseFractions});}} finally {@@ -25047,27 +24379,7 @@ var init_character_capture = __esm(() => {});// src/render.ts-var exports_render = {};-__export(exports_render, {- snapGlbToPalette: () => snapGlbToPalette,- settleContacts: () => settleContacts,- resolveEvaluatorMode: () => resolveEvaluatorMode,- renderSceneToGLB: () => renderSceneToGLB,- renderGLBInProcess: () => renderGLBInProcess,- renderGLB: () => renderGLB,- packKitGlb: () => packKitGlb,- optimizeGlbBytes: () => optimizeGlbBytes,- measureGlbBounds: () => measureGlbBounds,- inspectSceneStructure: () => inspectSceneStructure,- inspectGlbIntegration: () => inspectGlbIntegration,- inspectGeneratedAnimation: () => inspectGeneratedAnimation,- gradeGlbBytes: () => gradeGlbBytes,- executeKilnCode: () => executeKilnCode,- composeSceneGLB: () => composeSceneGLB,- bindBakedTextureProvenanceToFinalGlb: () => bindBakedTextureProvenanceToFinalGlb-});import * as THREE34 from "three";-import { createHash as createHash6 } from "node:crypto";import { Document, WebIO as WebIO3, getBounds } from "@gltf-transform/core";import {EXTMeshGPUInstancing as EXTMeshGPUInstancing3,@@ -25079,25 +24391,11 @@ import {instance,palette,flatten,- join as join3,+ join as join2,weld,prune,mergeDocuments} from "@gltf-transform/functions";-async function measureGlbBounds(bytes) {- const doc = await engineIO().readBinary(bytes);- const root = doc.getRoot();- const scene = root.getDefaultScene() ?? root.listScenes()[0];- if (!scene)- return;- const { min, max } = getBounds(scene);- if (!min.every(Number.isFinite) || !max.every(Number.isFinite))- return;- return {- min: [min[0], min[1], min[2]],- max: [max[0], max[1], max[2]]- };-}function ensureDefaultScene(doc) {const root = doc.getRoot();const scene = root.getDefaultScene() ?? root.listScenes()[0];@@ -25106,8 +24404,8 @@ function ensureDefaultScene(doc) {return scene;}async function sha256Hex2(bytes) {- const digest3 = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer);- return [...new Uint8Array(digest3)].map((value) => value.toString(16).padStart(2, "0")).join("");+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer);+ return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");}async function inspectGlbIntegration(bytes, opts = {}) {const doc = await engineIO().readBinary(bytes);@@ -25313,28 +24611,28 @@ function bridgeTexture(doc, threeTex, cache) {cache.set(threeTex, t);return t;}-function bridgeGeometry(doc, buf, geometry2, material, meshName) {- if (!geometry2.getAttribute("normal")) {- geometry2.computeVertexNormals();+function bridgeGeometry(doc, buf, geometry, material, meshName) {+ if (!geometry.getAttribute("normal")) {+ geometry.computeVertexNormals();}const prim = doc.createPrimitive().setMaterial(Array.isArray(material) ? material[0] : material);- const posAttr = geometry2.getAttribute("position");+ const posAttr = geometry.getAttribute("position");if (posAttr) {prim.setAttribute("POSITION", doc.createAccessor(meshName + "_pos").setArray(geometryAttributeValues(posAttr)).setType(TYPE_VEC3).setBuffer(buf));}- const normAttr = geometry2.getAttribute("normal");+ const normAttr = geometry.getAttribute("normal");if (normAttr) {prim.setAttribute("NORMAL", doc.createAccessor(meshName + "_norm").setArray(geometryAttributeValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));}- const uvAttr = geometry2.getAttribute("uv");+ const uvAttr = geometry.getAttribute("uv");if (uvAttr) {prim.setAttribute("TEXCOORD_0", doc.createAccessor(meshName + "_uv").setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));}- const tangentAttr = geometry2.getAttribute("tangent");+ const tangentAttr = geometry.getAttribute("tangent");if (tangentAttr?.itemSize === 4) {prim.setAttribute("TANGENT", doc.createAccessor(meshName + "_tangent").setArray(geometryAttributeValues(tangentAttr)).setType(TYPE_VEC4).setBuffer(buf));}- const indexAttr = geometry2.getIndex();+ const indexAttr = geometry.getIndex();if (indexAttr) {const IndexArray = posAttr && posAttr.count > 65535 ? Uint32Array : Uint16Array;prim.setIndices(doc.createAccessor(meshName + "_idx").setArray(new IndexArray(indexAttr.array)).setType(TYPE_SCALAR).setBuffer(buf));@@ -25343,15 +24641,15 @@ function bridgeGeometry(doc, buf, geometry2, material, meshName) {if (!Array.isArray(material))return mesh.addPrimitive(prim);const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);- const groups = [...geometry2.groups].sort((a, b) => a.start - b.start);+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);let covered = 0;for (const group of groups) {if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);}const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);- for (const semantic3 of prim.listSemantics())- part.setAttribute(semantic3, prim.getAttribute(semantic3));+ for (const semantic of prim.listSemantics())+ part.setAttribute(semantic, prim.getAttribute(semantic));const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;part.setIndices(doc.createAccessor(meshName + "_group_indices").setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));mesh.addPrimitive(part);@@ -25386,13 +24684,13 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)}}if (semanticForExport !== undefined) {- const semantic3 = validateSemanticMetadataV1(semanticForExport);- if (!semantic3.valid || !semantic3.value) {- const detail = semantic3.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");+ const semantic = validateSemanticMetadataV1(semanticForExport);+ if (!semantic.valid || !semantic.value) {+ const detail = semantic.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ");throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on node ${threeObj.name || "<unnamed>"}: ${detail}`);}gtNode.setExtras({- [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic3.value)+ [KILN_SEMANTIC_EXTRAS_KEY]: cloneSemanticMetadataV1(semantic.value)});}gtNode.setTranslation([threeObj.position.x, threeObj.position.y, threeObj.position.z]);@@ -25425,13 +24723,13 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;let gtMesh = meshCache.get(cacheKey);if (!gtMesh) {- const geometry2 = new THREE34.PlaneGeometry(1, 1);+ const geometry = new THREE34.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {- geometry2.translate(0.5 - centerX, 0.5 - centerY, 0);+ geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}if (rotation !== 0)- geometry2.rotateZ(rotation);- gtMesh = bridgeGeometry(doc, buf, geometry2, gtMat, sprite.name || "sprite-quad");+ geometry.rotateZ(rotation);+ gtMesh = bridgeGeometry(doc, buf, geometry, gtMat, sprite.name || "sprite-quad");meshCache.set(cacheKey, gtMesh);}gtNode.setMesh(gtMesh);@@ -25450,11 +24748,11 @@ function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {const anim = doc.createAnimation(clip.name);for (const track of clip.tracks) {const dotIdx = track.name.lastIndexOf(".");- const nodeName2 = track.name.substring(0, dotIdx);+ const nodeName = track.name.substring(0, dotIdx);const property = track.name.substring(dotIdx + 1);- const targetNode = nodeMap.get(nodeName2);+ const targetNode = nodeMap.get(nodeName);if (!targetNode) {- warnings.push(`Animation target "${nodeName2}" not found - skipped`);+ warnings.push(`Animation target "${nodeName}" not found - skipped`);continue;}let targetPath;@@ -25469,11 +24767,11 @@ function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {targetPath = "scale";valueType = TYPE_VEC3;} else {- warnings.push(`Unsupported animation property "${property}" on "${nodeName2}" - skipped`);+ warnings.push(`Unsupported animation property "${property}" on "${nodeName}" - skipped`);continue;}- const inputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);- const outputAcc = doc.createAccessor(clip.name + "_" + nodeName2 + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);+ const inputAcc = doc.createAccessor(clip.name + "_" + nodeName + "_input").setArray(new Float32Array(track.times)).setType(TYPE_SCALAR).setBuffer(buf);+ const outputAcc = doc.createAccessor(clip.name + "_" + nodeName + "_output").setArray(new Float32Array(track.values)).setType(valueType).setBuffer(buf);const sampler = doc.createAnimationSampler().setInput(inputAcc).setOutput(outputAcc).setInterpolation("LINEAR");const channel = doc.createAnimationChannel().setTargetNode(targetNode).setTargetPath(targetPath).setSampler(sampler);anim.addSampler(sampler);@@ -25511,80 +24809,6 @@ function reviewClipExtras(clips) {}))};}-function finalTextureForSlot(material, slot) {- switch (slot) {- case "map":- return material.getBaseColorTexture();- case "normalMap":- return material.getNormalTexture();- case "roughnessMap":- case "metalnessMap":- return material.getMetallicRoughnessTexture();- case "emissiveMap":- return material.getEmissiveTexture();- case "aoMap":- return material.getOcclusionTexture();- default:- return null;- }-}-async function bindBakedTextureProvenanceToFinalGlb(baked, finalGlb) {- if (baked.length === 0)- return [];- const doc = await engineIO().readBinary(finalGlb);- const root = doc.getRoot();- const byMaterialName = new Map;- for (const material of root.listMaterials()) {- const name = material.getName() || "(unnamed material)";- const list = byMaterialName.get(name) ?? [];- list.push(material);- byMaterialName.set(name, list);- }- const nodesByName = new Map;- for (const node of root.listNodes()) {- const list = nodesByName.get(node.getName()) ?? [];- list.push(node);- nodesByName.set(node.getName(), list);- }- const artifactGlbSha256 = `sha256:${await sha256Hex2(finalGlb)}`;- return baked.flatMap((entry) => {- const resolved2 = new Set;- for (const binding of entry.bindings) {- const nodeMaterials = (nodesByName.get(binding.node) ?? []).flatMap((node) => node.getMesh()?.listPrimitives().flatMap((primitive) => {- const material = primitive.getMaterial();- return material ? [material] : [];- }) ?? []);- const materials = nodeMaterials.filter((material) => (material.getName() || "(unnamed material)") === binding.material);- const candidates = materials.length ? materials : byMaterialName.get(binding.material) ?? [];- for (const material of candidates) {- const texture2 = finalTextureForSlot(material, binding.slot);- if (texture2)- resolved2.add(texture2);- }- }- if (resolved2.size === 0 && entry.texture !== "(unnamed texture)") {- for (const texture2 of root.listTextures()) {- if (texture2.getName() === entry.texture)- resolved2.add(texture2);- }- }- if (resolved2.size !== 1)- return [];- const texture = [...resolved2][0];- const image = texture.getImage();- const mime = texture.getMimeType();- if (!image || !mime)- return [];- return [- {- ...entry,- artifactGlbSha256,- finalMime: mime,- finalImageSha256: `sha256:${createHash6("sha256").update(image).digest("hex")}`- }- ];- });-}function resolveOptimize(opt) {if (opt)return opt;@@ -25634,7 +24858,7 @@ async function consolidateMaterials(doc, mode) {const effective = mode === "full" && (animatedOrSkinned || semanticGraph) ? "palette" : mode;const steps = [palette({ min: PALETTE_MIN })];if (effective === "full") {- steps.push(flatten(), join3({ keepNamed: true }));+ steps.push(flatten(), join2({ keepNamed: true }));}steps.push(weld(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));await doc.transform(...steps);@@ -25862,240 +25086,6 @@ function resolveEvaluatorMode(env = process.env) {return "isolated";throw new Error("Invalid KILN_EVALUATOR_MODE.");}-async function renderGLB(code, opts = {}) {- const mode = resolveEvaluatorMode();- if (mode === "in-process")- return renderGLBInProcess(code, opts);- if (mode === "subprocess") {- const { renderGLBViaSubprocess: renderGLBViaSubprocess2 } = await Promise.resolve().then(() => (init_subprocess(), exports_subprocess));- return renderGLBViaSubprocess2(code, opts);- }- const { renderGLBViaIsolatedEvaluator: renderGLBViaIsolatedEvaluator2 } = await Promise.resolve().then(() => (init_isolation(), exports_isolation));- return renderGLBViaIsolatedEvaluator2(code, opts);-}-async function gradeGlbBytes(bytes, opts = {}) {- try {- const doc = await engineIO().readBinary(bytes);- return gradeInstanceability(collectGlbMetrics(doc), opts);- } catch {- return;- }-}-async function optimizeGlbBytes(bytes, opts = {}) {- const requested = opts.mode ?? "palette";- try {- const io = engineIO();- const doc = await io.readBinary(bytes);- let instancing;- if (opts.instance && opts.instance !== "off") {- instancing = await applyGpuInstancing(doc, opts.instance, opts.role);- }- let summary;- let mode;- if (requested !== "off") {- if (requested === "auto") {- if (collectGlbMetrics(doc).uniqueMaterials >= PALETTE_MIN)- mode = "palette";- } else {- mode = requested;- }- }- if (mode)- summary = await consolidateMaterials(doc, mode);- if (!summary && !instancing)- return;- ensureDefaultScene(doc);- const outBytes = await io.writeBinary(doc);- const gltfValidation = await assertFinalGlbValid(outBytes);- let report;- try {- report = gradeInstanceability(collectGlbMetrics(doc), { category: opts.category });- } catch {- report = undefined;- }- return {- bytes: outBytes,- gltfValidation,- ...report ? { report } : {},- ...summary ? { summary } : {},- ...instancing ? { instancing } : {}- };- } catch (error) {- if (error instanceof GltfValidationError)- throw error;- return;- }-}-async function packKitGlb(bytes, opts = {}) {- let doc;- try {- doc = await engineIO().readBinary(bytes);- } catch {- return;- }- const summary = await applyKitContract(doc, opts);- const changed = summary.ormPacked > 0 || summary.variantsAdded.length > 0 || summary.ktx2.applied;- if (!changed)- return;- ensureDefaultScene(doc);- const outBytes = await engineIO().writeBinary(doc);- const gltfValidation = await assertFinalGlbValid(outBytes);- return { bytes: outBytes, summary, gltfValidation };-}-async function snapGlbToPalette(bytes, slots, opts = {}) {- if (slots.length === 0)- return;- try {- const io = engineIO();- const doc = await io.readBinary(bytes);- const before = collectGlbMetrics(doc);- const idx = buildSlotIndex(slots);- let snapped = 0;- let skipped = 0;- for (const mat of doc.getRoot().listMaterials()) {- if (mat.getBaseColorTexture()) {- skipped++;- continue;- }- const base = mat.getBaseColorFactor();- const emissive = mat.getEmissiveFactor();- const transparent = mat.getAlphaMode() === "BLEND" || mat.getAlpha() < 0.98;- const slotI = chooseSlot(idx, {- baseLinear: [base[0], base[1], base[2]],- emissiveLinear: [emissive[0], emissive[1], emissive[2]],- transparent- });- if (slotI === undefined) {- skipped++;- continue;- }- const slot = slots[slotI];- const kind = slot.kind ?? "opaque";- const [lr, lg, lb] = hexToLinearRgb(slot.color);- const alpha = kind === "glass" ? slot.opacity ?? 0.4 : 1;- mat.setBaseColorFactor([lr, lg, lb, alpha]);- mat.setMetallicFactor(slot.metalness ?? 0);- mat.setRoughnessFactor(slot.roughness ?? (kind === "glass" ? 0.1 : 0.85));- if (kind === "glass")- mat.setAlphaMode("BLEND");- else if (mat.getAlphaMode() === "BLEND")- mat.setAlphaMode("OPAQUE");- mat.setEmissiveFactor(kind === "glow" ? [lr, lg, lb] : [0, 0, 0]);- snapped++;- }- await doc.transform(dedup());- await consolidateMaterials(doc, "palette");- const after = collectGlbMetrics(doc);- const summary = {- mode: "palette",- materialsBefore: before.uniqueMaterials,- materialsAfter: after.uniqueMaterials,- drawsBefore: before.drawCalls,- drawsAfter: after.drawCalls- };- ensureDefaultScene(doc);- const outBytes = await io.writeBinary(doc);- const gltfValidation = await assertFinalGlbValid(outBytes);- let report;- try {- report = gradeInstanceability(after, { category: opts.category });- } catch {- report = undefined;- }- return {- bytes: outBytes,- ...report ? { report } : {},- summary,- snapped,- skipped,- gltfValidation- };- } catch (error) {- if (error instanceof GltfValidationError)- throw error;- return;- }-}-function eulerDegToQuat(deg) {- const e = new THREE34.Euler(THREE34.MathUtils.degToRad(deg[0]), THREE34.MathUtils.degToRad(deg[1]), THREE34.MathUtils.degToRad(deg[2]), "XYZ");- const q = new THREE34.Quaternion().setFromEuler(e);- return [q.x, q.y, q.z, q.w];-}-async function composeSceneGLB(parts, opts = {}) {- const warnings = [];- const io = engineIO();- const master = new Document;- const masterScene = master.createScene(opts.sceneName ?? "Scene");- master.getRoot().setDefaultScene(masterScene);- let composed = 0;- for (let i = 0;i < parts.length; i++) {- const part = parts[i];- try {- const src = await io.readBinary(part.bytes);- const srcScene = src.getRoot().listScenes()[0];- const map = mergeDocuments(master, src);- const wrap = master.createNode(part.name ?? `part_${i}`).setTranslation([part.transform.pos[0], part.transform.pos[1], part.transform.pos[2]]).setRotation(eulerDegToQuat(part.transform.rotDeg)).setScale([part.transform.scale[0], part.transform.scale[1], part.transform.scale[2]]);- const mergedScene = srcScene ? map.get(srcScene) : undefined;- if (mergedScene) {- for (const child of mergedScene.listChildren())- wrap.addChild(child);- mergedScene.dispose();- }- masterScene.addChild(wrap);- composed++;- } catch (err) {- warnings.push(`part ${i} (${part.name ?? ""}) skipped: ${err instanceof Error ? err.message : String(err)}`);- }- }- if (composed === 0)- throw new Error("composeSceneGLB: no parts could be merged");- if (!opts.keepAnimations) {- for (const anim of master.getRoot().listAnimations())- anim.dispose();- }- try {- await master.transform(dedup());- } catch (err) {- warnings.push(`dedup failed: ${err instanceof Error ? err.message : String(err)}`);- }- const optimizeMode = opts.optimize ?? "palette";- let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;- if (optimizeMode === "auto" && collectGlbMetrics(master).uniqueMaterials >= PALETTE_MIN) {- effectiveOptimize = "palette";- }- if (effectiveOptimize !== "off") {- try {- await consolidateMaterials(master, effectiveOptimize);- } catch (err) {- warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);- }- }- const rootBuffers = master.getRoot().listBuffers();- if (rootBuffers.length > 1) {- const main = rootBuffers[0];- for (const acc of master.getRoot().listAccessors())- acc.setBuffer(main);- for (let i = 1;i < rootBuffers.length; i++)- rootBuffers[i].dispose();- }- const metrics = collectGlbMetrics(master);- ensureDefaultScene(master);- const bytes = await io.writeBinary(master);- const gltfValidation = await assertFinalGlbValid(bytes, "scene.glb");- for (const issue of gltfValidation.issues.messages) {- if (issue.severity !== 1)- continue;- warnings.push(`glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ""}: ${issue.message}`);- }- return {- bytes,- tris: metrics.triangles,- draws: metrics.drawCalls,- materials: metrics.uniqueMaterials,- warnings,- gltfValidation- };-}function inspectGeneratedAnimation(root, clips) {const warnings = [];if (clips.length === 0)@@ -26112,10 +25102,10 @@ function inspectGeneratedAnimation(root, clips) {warnings.push(`Track "${track.name}" is missing a node.property separator`);continue;}- const nodeName2 = track.name.substring(0, dotIdx);+ const nodeName = track.name.substring(0, dotIdx);const property = track.name.substring(dotIdx + 1);- if (!nodeNames.has(nodeName2)) {- warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName2}" — rename the pivot or fix the track`);+ if (!nodeNames.has(nodeName)) {+ warnings.push(`Animation track "${clip.name}:${track.name}" targets unknown node "${nodeName}" — rename the pivot or fix the track`);}if (!["position", "quaternion", "scale"].includes(property)) {warnings.push(`Animation track "${clip.name}:${track.name}" uses unsupported property "${property}"`);@@ -26238,58 +25228,6 @@ function inspectSceneStructure(root, opts = {}) {}return warnings;}-function settleContacts(root, opts = {}) {- const maxGap = opts.maxGap ?? 0.05;- const overlap = opts.overlap ?? 0.01;- const settled = [];- for (let pass = 0;pass < 8; pass++) {- const meshes = collectMeshStats(root);- if (meshes.length < 2)- return settled;- let pick;- for (let i = 0;i < meshes.length; i++) {- const a = meshes[i];- const ax = a.box.clone().expandByScalar(0.02);- if (meshes.some((b, j) => j !== i && ax.intersectsBox(b.box)))- continue;- let nearestGap;- for (let j = 0;j < meshes.length; j++) {- if (i === j)- continue;- const gap = minimalGapVector(a.box, meshes[j].box);- if (!nearestGap || gap.length() < nearestGap.length())- nearestGap = gap;- }- if (!nearestGap || nearestGap.length() === 0 || nearestGap.length() > maxGap)- continue;- const volume = a.size.x * a.size.y * a.size.z;- if (!pick || volume < pick.volume)- pick = { stats: a, gap: nearestGap, volume };- }- if (!pick)- break;- const delta = pick.gap.clone();- const dominant = ["x", "y", "z"].reduce((d, axis) => Math.abs(delta[axis]) > Math.abs(delta[d]) ? axis : d, "x");- delta[dominant] += Math.sign(delta[dominant]) * overlap;- let target;- root.traverse((obj) => {- if (!target && obj.name === pick.stats.name && obj.isMesh)- target = obj;- });- if (!target)- break;- const parent = target.parent ?? root;- const p0 = new THREE34.Vector3;- target.getWorldPosition(p0);- const p1 = p0.clone().add(delta);- const l0 = parent.worldToLocal(p0.clone());- const l1 = parent.worldToLocal(p1.clone());- target.position.add(l1.sub(l0));- target.updateMatrixWorld(true);- settled.push(pick.stats.name);- }- return settled;-}var engineIO = () => new WebIO3().registerExtensions([EXTMeshGPUInstancing3, KHRMaterialsVariants3, KHRTextureBasisu3]), TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;var init_render = __esm(() => {init_authoring_diagnostic();@@ -26318,26 +25256,7 @@ var init_render = __esm(() => {});// src/evaluator/protocol.ts-var exports_protocol = {};-__export(exports_protocol, {- trustedInProcessEvaluatorPortV1: () => trustedInProcessEvaluatorPortV1,- resolveEvaluatorPortV1: () => resolveEvaluatorPortV1,- evaluatorOutcomeMessage: () => evaluatorOutcomeMessage,- encodeRenderResultV1: () => encodeRenderResultV1,- decodeEvaluatorResultV1: () => decodeEvaluatorResultV1,- decodeEvaluatorRequestV1: () => decodeEvaluatorRequestV1,- createEvaluatorRequestV1: () => createEvaluatorRequestV1,- createEvaluatorPortV1: () => createEvaluatorPortV1,- MAX_EVALUATOR_REQUEST_BYTES: () => MAX_EVALUATOR_REQUEST_BYTES,- MAX_EVALUATOR_CODE_BYTES: () => MAX_EVALUATOR_CODE_BYTES,- EvaluatorPortError: () => EvaluatorPortError,- EVALUATOR_RESULT_VERSION: () => EVALUATOR_RESULT_VERSION,- EVALUATOR_REQUEST_VERSION: () => EVALUATOR_REQUEST_VERSION,- DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES: () => DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES,- DEFAULT_EVALUATOR_MAX_GLB_BYTES: () => DEFAULT_EVALUATOR_MAX_GLB_BYTES,- DEFAULT_EVALUATOR_DEADLINE_MS: () => DEFAULT_EVALUATOR_DEADLINE_MS-});-import { createHash as createHash7 } from "node:crypto";+import { createHash as createHash6 } from "node:crypto";function evaluatorOutcomeMessage(code) {return EVALUATOR_OUTCOME_MESSAGES[code];}@@ -26365,12 +25284,12 @@ function validInteger(value, min, max) {return Number.isInteger(value) && Number(value) >= min && Number(value) <= max;}function validQaReport(value) {- const dimensions2 = isRecord6(value) && isRecord6(value.dimensions) ? value.dimensions : undefined;- if (!isRecord6(value) || !hasExactKeys(value, ["schemaVersion", "category", "qaProfile", "disposition", "dimensions"]) || value.schemaVersion !== 1 || !isAssetCategory(value.category) || typeof value.qaProfile !== "string" || value.qaProfile.length < 1 || value.qaProfile.length > 128 || !["pass", "warn", "block", "notEvaluated", "legacy-unassessed"].includes(String(value.disposition)) || !dimensions2 || !hasExactKeys(dimensions2, QA_DIMENSIONS) || !QA_DIMENSIONS.every((dimension) => (dimension in dimensions2))) {+ const dimensions = isRecord6(value) && isRecord6(value.dimensions) ? value.dimensions : undefined;+ if (!isRecord6(value) || !hasExactKeys(value, ["schemaVersion", "category", "qaProfile", "disposition", "dimensions"]) || value.schemaVersion !== 1 || !isAssetCategory(value.category) || typeof value.qaProfile !== "string" || value.qaProfile.length < 1 || value.qaProfile.length > 128 || !["pass", "warn", "block", "notEvaluated", "legacy-unassessed"].includes(String(value.disposition)) || !dimensions || !hasExactKeys(dimensions, QA_DIMENSIONS) || !QA_DIMENSIONS.every((dimension) => (dimension in dimensions))) {return false;}return QA_DIMENSIONS.every((dimension) => {- const result = dimensions2[dimension];+ const result = dimensions[dimension];return isRecord6(result) && hasExactKeys(result, ["status", "findings", "metrics"]) && ["pass", "warn", "block", "notEvaluated"].includes(String(result.status)) && Array.isArray(result.findings) && result.findings.length <= 1000 && result.findings.every(isQaFinding) && (result.metrics === undefined || isRecord6(result.metrics));});}@@ -26381,85 +25300,6 @@ function validGltfValidation(value) {}return ["numErrors", "numWarnings", "numInfos", "numHints"].every((key) => validInteger(issues[key], 0, Number.MAX_SAFE_INTEGER)) && issues.messages.length <= 1000 && issues.messages.every((issue) => isRecord6(issue) && typeof issue.code === "string" && typeof issue.message === "string" && typeof issue.severity === "number" && Number.isFinite(issue.severity));}-function boundedControl(value, fallback, max) {- const resolved2 = value ?? fallback;- if (!validInteger(resolved2, 1, max)) {- throw new EvaluatorPortError("INPUT_INVALID");- }- return resolved2;-}-function createEvaluatorRequestV1(input) {- if (input.options?.textureResolver) {- throw new EvaluatorPortError("INPUT_INVALID", "Evaluator requests do not accept a host resolver capability.");- }- const maxGlbBytes = boundedControl(input.maxGlbBytes, DEFAULT_EVALUATOR_MAX_GLB_BYTES, 64 * 1024 * 1024);- const { textureResolver: _, ...options } = input.options ?? {};- const request2 = {- version: EVALUATOR_REQUEST_VERSION,- requestId: input.requestId,- operation: "execute-export-glb",- code: input.code,- options,- limits: { maxGlbBytes }- };- const json = JSON.stringify(request2);- const decoded = decodeEvaluatorRequestV1(json);- return { request: decoded, json };-}-function parseOptions(value) {- if (!isRecord6(value) || !hasExactKeys(value, ["optimize", "instance", "intent", "category", "geometryPolicy"])) {- return fail("request");- }- const options = {};- if (value.geometryPolicy !== undefined) {- if (!["warn", "strict"].includes(String(value.geometryPolicy)))- fail("request");- options.geometryPolicy = value.geometryPolicy;- }- if (value.optimize !== undefined) {- if (!["off", "auto", "palette", "full"].includes(String(value.optimize)))- fail("request");- options.optimize = value.optimize;- }- if (value.instance !== undefined) {- if (!["off", "auto", "on"].includes(String(value.instance)))- fail("request");- options.instance = value.instance;- }- if (value.category !== undefined) {- if (!isAssetCategory(value.category))- fail("request");- options.category = value.category;- }- if (value.intent !== undefined) {- const result = validateAssetIntentV1(value.intent);- if (!result.valid)- fail("request");- options.intent = result.value;- }- return options;-}-function decodeEvaluatorRequestV1(json) {- if (Buffer.byteLength(json, "utf8") > MAX_EVALUATOR_REQUEST_BYTES)- fail("request");- let value;- try {- value = JSON.parse(json);- } catch {- return fail("request");- }- if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "operation", "code", "options", "limits"]) || value.version !== EVALUATOR_REQUEST_VERSION || !validRequestId(value.requestId) || value.operation !== "execute-export-glb" || typeof value.code !== "string" || Buffer.byteLength(value.code, "utf8") > MAX_EVALUATOR_CODE_BYTES || !isRecord6(value.limits) || !hasExactKeys(value.limits, ["maxGlbBytes"]) || !validInteger(value.limits.maxGlbBytes, 1, 64 * 1024 * 1024)) {- return fail("request");- }- return {- version: EVALUATOR_REQUEST_VERSION,- requestId: value.requestId,- operation: "execute-export-glb",- code: value.code,- options: parseOptions(value.options),- limits: { maxGlbBytes: value.limits.maxGlbBytes }- };-}function encodeRenderResultV1(requestId, render) {const { glb, diagnosticViews, buildCache: _hostCacheReceipt, ...rest } = render;return {@@ -26547,7 +25387,7 @@ function decodeEvaluatorResultV1(json, maxGlbBytes, expectedRequestId) {fail("result");if (!isSha256(value.render.artifactGlbSha256))fail("result");- const actualHash = `sha256:${createHash7("sha256").update(glb).digest("hex")}`;+ const actualHash = `sha256:${createHash6("sha256").update(glb).digest("hex")}`;if (actualHash !== value.render.artifactGlbSha256)fail("result");const diagnosticViews = value.render.diagnosticViews;@@ -26559,7 +25399,7 @@ function decodeEvaluatorResultV1(json, maxGlbBytes, expectedRequestId) {const png = Buffer.from(candidate.pngBase64, "base64");if (png.toString("base64") !== candidate.pngBase64)return fail("result");- const { pngBase64: _2, ...view } = candidate;+ const { pngBase64: _, ...view } = candidate;return { ...view, png };});const { glbBase64: _, diagnosticViews: __, ...rest } = value.render;@@ -26574,78 +25414,7 @@ function decodeEvaluatorResultV1(json, maxGlbBytes, expectedRequestId) {}};}-function createEvaluatorPortV1(transport, defaults2 = {}) {- let sequence = 0;- return {- async render(code, options = {}, controls = {}) {- const signal = controls.signal ?? defaults2.signal;- if (signal?.aborted)- throw new EvaluatorPortError("CANCELLED");- const deadlineMs = boundedControl(controls.deadlineMs ?? defaults2.deadlineMs, DEFAULT_EVALUATOR_DEADLINE_MS, 120000);- const maxGlbBytes = boundedControl(controls.maxGlbBytes ?? defaults2.maxGlbBytes, DEFAULT_EVALUATOR_MAX_GLB_BYTES, 64 * 1024 * 1024);- const maxResponseBytes = boundedControl(controls.maxResponseBytes ?? defaults2.maxResponseBytes, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, 96 * 1024 * 1024);- const requestId = `eval-${++sequence}`;- const built = createEvaluatorRequestV1({ requestId, code, options, maxGlbBytes });- let timer;- let response;- const transportController = new AbortController;- let abort;- try {- const cancelled = new Promise((_, reject) => {- abort = () => {- reject(new EvaluatorPortError("CANCELLED"));- transportController.abort();- };- signal?.addEventListener("abort", abort, { once: true });- });- response = await Promise.race([- transport(built.json, {- deadlineMs,- maxResponseBytes,- signal: transportController.signal- }),- cancelled,- new Promise((_, reject) => {- timer = setTimeout(() => {- reject(new EvaluatorPortError("DEADLINE_EXCEEDED"));- transportController.abort();- }, deadlineMs);- })- ]);- } catch (error) {- if (error instanceof EvaluatorPortError)- throw error;- throw new EvaluatorPortError("WORKER_FAILED");- } finally {- clearTimeout(timer);- if (abort)- signal?.removeEventListener("abort", abort);- }- if (signal?.aborted)- throw new EvaluatorPortError("CANCELLED");- if (typeof response !== "string")- throw new EvaluatorPortError("PROTOCOL_ERROR");- if (Buffer.byteLength(response, "utf8") > maxResponseBytes) {- throw new EvaluatorPortError("OUTPUT_LIMIT_EXCEEDED");- }- let result;- try {- result = decodeEvaluatorResultV1(response, maxGlbBytes, requestId);- } catch {- throw new EvaluatorPortError("PROTOCOL_ERROR");- }- if (!result.ok) {- if (result.error.code === "QA_BLOCKED" && result.error.qa) {- const { AssetQaBlockedError: AssetQaBlockedError2 } = await Promise.resolve().then(() => (init_run(), exports_run));- throw new AssetQaBlockedError2(result.error.qa.report, result.error.qa.stage, result.error.qa.gltfValidation);- }- throw new EvaluatorPortError(result.error.code, undefined, result.error.diagnostic);- }- return result.render;- }- };-}-var EVALUATOR_REQUEST_VERSION = "kiln.evaluator.request.v1", EVALUATOR_RESULT_VERSION = "kiln.evaluator.result.v1", MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_DEADLINE_MS = 60000, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV1;+var EVALUATOR_REQUEST_VERSION = "kiln.evaluator.request.v1", EVALUATOR_RESULT_VERSION = "kiln.evaluator.result.v1", MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV1;var init_protocol = __esm(() => {init_authoring_diagnostic();init_contracts();@@ -26679,8 +25448,8 @@ var init_protocol = __esm(() => {async render(code, options = {}, controls = {}) {if (controls.signal?.aborted)throw new EvaluatorPortError("CANCELLED");- const { renderGLBInProcess: renderGLBInProcess2 } = await Promise.resolve().then(() => (init_render(), exports_render));- const result = await renderGLBInProcess2(code, options);+ await Promise.resolve().then(() => init_render());+ const result = await renderGLBInProcess(code, options);if (controls.signal?.aborted)throw new EvaluatorPortError("CANCELLED");return result;@@ -26689,18 +25458,11 @@ var init_protocol = __esm(() => {});// src/views/port.ts-var exports_port = {};-__export(exports_port, {- sha256Bytes: () => sha256Bytes,- captureViewsViaPort: () => captureViewsViaPort,- captureViewPngsViaPort: () => captureViewPngsViaPort,- DEFAULT_VIEW_RENDER_TIMEOUT_MS: () => DEFAULT_VIEW_RENDER_TIMEOUT_MS-});async function sha256Bytes(bytes) {const input = new Uint8Array(bytes.byteLength);input.set(bytes);- const digest3 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", input));- return `sha256:${[...digest3].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", input));+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;}async function captureViewPngsViaPort(port, glb, timeoutMs, viewDirs, size, cameras, limits) {let timer;@@ -26779,38 +25541,38 @@ async function captureViewPngsViaPort(port, glb, timeoutMs, viewDirs, size, cameasync function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIMEOUT_MS, capture, limits) {if (capture?.shots || capture?.version) {try {- const { loadGlbReviewScene: loadGlbReviewScene2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const { renderCaptureGrid: renderCaptureGrid2 } = await Promise.resolve().then(() => (init_camera_capture(), exports_camera_capture));- const { renderSceneToGLB: renderSceneToGLB2 } = await Promise.resolve().then(() => (init_render(), exports_render));- const loaded = await loadGlbReviewScene2(Uint8Array.from(glb));+ await Promise.resolve().then(() => init_views());+ await Promise.resolve().then(() => init_camera_capture());+ await Promise.resolve().then(() => init_render());+ const loaded = await loadGlbReviewScene(Uint8Array.from(glb));let rendererId = "";- const grid = await renderCaptureGrid2(loaded.root, capture, async (input) => {- const derivative = await renderSceneToGLB2(input.root, {+ const grid = await renderCaptureGrid(loaded.root, capture, async (input) => {+ const derivative = await renderSceneToGLB(input.root, {derivative: true});- const result2 = await captureViewPngsViaPort(port, derivative.bytes, timeoutMs, [input.view.dir], input.size, [input.camera], limits);- if (!result2.ok)- throw new Error(result2.reason);- if (!result2.derivativeFidelityAttested || !result2.inputGlbSha256)+ const result = await captureViewPngsViaPort(port, derivative.bytes, timeoutMs, [input.view.dir], input.size, [input.camera], limits);+ if (!result.ok)+ throw new Error(result.reason);+ if (!result.derivativeFidelityAttested || !result.inputGlbSha256)throw new Error("advanced capture requires derivative material receipt");- if (rendererId && rendererId !== result2.rendererId)+ if (rendererId && rendererId !== result.rendererId)throw new Error("capture renderer changed between cells");- rendererId = result2.rendererId;+ rendererId = result.rendererId;return {- png: Buffer.from(result2.pngs[0]),+ png: Buffer.from(result.pngs[0]),receipt: {version: "kiln.view-fidelity.v1",derivativeLabel: input.label,requested: "full-preferred",delivered: "full-material",exactArtifact: false,- rendererId: result2.rendererId,+ rendererId: result.rendererId,materialFaithful: true,degraded: false,- inputGlbSha256: result2.inputGlbSha256,+ inputGlbSha256: result.inputGlbSha256,camera: input.camera,cameraFidelity: "echo-validated",- ...result2.captureCache ? { captureCache: result2.captureCache } : {}+ ...result.captureCache ? { captureCache: result.captureCache } : {}}};}, limits);@@ -26830,22 +25592,22 @@ async function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIreturn { ok: false, reason: error instanceof Error ? error.message : String(error) };}}- let resolved2;+ let resolved;try {- resolved2 = resolveGridCapture(capture, process.env["KILN_GRID_VARIANT"]);- enforceCapturePixels(resolved2.views.length, 384, resolved2.cols, limits);+ resolved = resolveGridCapture(capture, process.env["KILN_GRID_VARIANT"]);+ enforceCapturePixels(resolved.views.length, 384, resolved.cols, limits);} catch (err) {return { ok: false, reason: err instanceof Error ? err.message : String(err) };}- const views = resolved2.views;- const shape = { preset: resolved2.preset, cols: resolved2.cols, cells: views.length };+ const views = resolved.views;+ const shape = { preset: resolved.preset, cols: resolved.cols, cells: views.length };let cameras;- if (resolved2.zooms.some((z4) => z4 !== undefined)) {+ if (resolved.zooms.some((z) => z !== undefined)) {try {- const { loadGlbReviewScene: loadGlbReviewScene2, measureBounds: measureBounds2, cameraFromBounds: cameraFromBounds2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const loaded = await loadGlbReviewScene2(Uint8Array.from(glb));- const bounds = measureBounds2(loaded.root);- cameras = views.map((view, i) => cameraFromBounds2(bounds, view.dir, resolved2.zooms[i] ?? 1));+ await Promise.resolve().then(() => init_views());+ const loaded = await loadGlbReviewScene(Uint8Array.from(glb));+ const bounds = measureBounds(loaded.root);+ cameras = views.map((view, i) => cameraFromBounds(bounds, view.dir, resolved.zooms[i] ?? 1));} catch (error) {return { ok: false, reason: error instanceof Error ? error.message : String(error) };}@@ -26854,7 +25616,7 @@ async function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIif (!result.ok)return result;try {- const grid = compositeViewPngGrid(result.pngs, resolved2.cols, views);+ const grid = compositeViewPngGrid(result.pngs, resolved.cols, views);enforceCaptureBytes([grid.png], limits);return {ok: true,@@ -26879,18 +25641,6 @@ var init_port = __esm(() => {});// src/views/inspect.ts-var exports_inspect = {};-__export(exports_inspect, {- renderInspectView: () => renderInspectView,- prepareInspectView: () => prepareInspectView,- listPartNames: () => listPartNames,- INSPECT_SIZE: () => INSPECT_SIZE,- INSPECT_MIN_ZOOM: () => INSPECT_MIN_ZOOM,- INSPECT_MAX_ZOOM: () => INSPECT_MAX_ZOOM,- INSPECT_MAX_PART_NAMES: () => INSPECT_MAX_PART_NAMES,- INSPECT_DEFAULT_ZOOM: () => INSPECT_DEFAULT_ZOOM,- INSPECT_CAMERAS: () => INSPECT_CAMERAS-});function listPartNames(root, cap = INSPECT_MAX_PART_NAMES) {const names = [];const seen = new Set;@@ -27002,27 +25752,6 @@ function prepareInspectView(root, opts = {}) {frameBounds: expandBounds2(bounds, zoom)};}-function renderInspectView(root, opts = {}) {- const prepared = prepareInspectView(root, opts);- if (!prepared.ok)- return prepared;- const rgb2 = rasterizeView(prepared.root, prepared.viewSpec.dir, {- size: prepared.size,- frameBounds: prepared.frameBounds- });- return {- ok: true,- ...prepared.part ? { part: prepared.part } : {},- view: prepared.view,- azimuthDeg: prepared.azimuthDeg,- elevationDeg: prepared.elevationDeg,- zoom: prepared.zoom,- isolated: prepared.isolated,- width: prepared.size,- height: prepared.size,- png: encodePng(rgb2, prepared.size, prepared.size)- };-}var INSPECT_SIZE = 512, INSPECT_DEFAULT_ZOOM = 1.2, INSPECT_MIN_ZOOM = 1, INSPECT_MAX_ZOOM = 4, INSPECT_MAX_PART_NAMES = 40, INSPECT_CAMERAS;var init_inspect = __esm(() => {init_raster();@@ -27038,11 +25767,6 @@ var init_inspect = __esm(() => {});// src/views/measurement.ts-var exports_measurement = {};-__export(exports_measurement, {- measureAttachment: () => measureAttachment,- describeSubjectFrame: () => describeSubjectFrame-});import { Box3 as Box316, Vector3 as Vector330 } from "three";function describeSubjectFrame(root, subject) {const selected = selectCameraSubject(root, subject);@@ -27077,9 +25801,9 @@ function describeSubjectFrame(root, subject) {};}function measureAttachment(root, input) {- const endpoint = (request2) => {- const selected = selectCameraSubject(root, request2.subject);- const local = request2.point ?? [0, 0, 0];+ const endpoint = (request) => {+ const selected = selectCameraSubject(root, request.subject);+ const local = request.point ?? [0, 0, 0];if (local.length !== 3 || local.some((n) => !Number.isFinite(n)))throw new Error("attachment point must be three finite subject-local coordinates");selected.node.updateWorldMatrix(true, false);@@ -27106,8 +25830,6 @@ var init_measurement = __esm(() => {// src/assets-resources.tsvar exports_assets_resources = {};__export(exports_assets_resources, {- readAssetResource: () => readAssetResource2,- assetMime: () => assetMime2,assetLinks: () => assetLinks});function assetLinks(collection, manifest) {@@ -27121,20 +25843,6 @@ function assetLinks(collection, manifest) {function assetMime2(name) {return name.endsWith(".glb") ? "model/gltf-binary" : name.endsWith(".png") ? "image/png" : name.endsWith(".zip") ? "application/zip" : name.endsWith(".json") ? "application/json" : "text/javascript";}-async function readAssetResource2(library, uri) {- const match = /^kiln:\/\/assets\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/(asset\.glb|source\.kiln\.js|preview\.png|manifest\.json|editable\.zip)$/.exec(uri);- if (!match)- throw new Error("Unknown asset resource");- const collection = match[1];- const asset2 = match[2];- const revision = match[3];- const name = match[4];- const record5 = await library.read(collection, asset2, revision);- const bytes = name === "editable.zip" ? encodeAssetBundle([record5]) : name === "manifest.json" ? new TextEncoder().encode(JSON.stringify(record5.manifest, null, 2)) : record5.files[name];- if (!bytes)- throw new Error("Asset file unavailable");- return { bytes, mimeType: assetMime2(name), name };-}var init_assets_resources = __esm(() => {init_assets();});@@ -27171,13 +25879,11 @@ var init_widget_transfer = __esm(() => {// src/asset-widget.tsvar exports_asset_widget = {};__export(exports_asset_widget, {- readAssetWidgetHtml: () => readAssetWidgetHtml,assetWidgetData: () => assetWidgetData});-import { readFile as readFile3 } from "node:fs/promises";async function assetWidgetData(library, selector) {- const record5 = await library.read(selector.collection, selector.asset.assetId, selector.asset.revisionId);- if (Object.values(record5.files).reduce((sum, bytes) => sum + bytes.length, 0) > WIDGET_TRANSFER_LIMIT)+ const record = await library.read(selector.collection, selector.asset.assetId, selector.asset.revisionId);+ if (Object.values(record.files).reduce((sum, bytes) => sum + bytes.length, 0) > WIDGET_TRANSFER_LIMIT)return {kilnAsset: {error: "This asset exceeds the 16 MiB chat preview limit. Open it with kiln view."@@ -27185,15 +25891,12 @@ async function assetWidgetData(library, selector) {};return {kilnAsset: {- manifest: record5.manifest,+ manifest: record.manifest,downloadUrls: selector.downloadUrls,- files: encodeWidgetFiles(record5.files)+ files: encodeWidgetFiles(record.files)}};}-async function readAssetWidgetHtml() {- return readFile3(new URL("../dist/viewer/chat.html", import.meta.url), "utf8");-}var init_asset_widget = __esm(() => {init_widget_transfer();});@@ -27201,28 +25904,11 @@ var init_asset_widget = __esm(() => {// src/asset-widget.tsvar exports_asset_widget2 = {};__export(exports_asset_widget2, {- readAssetWidgetHtml: () => readAssetWidgetHtml2,- assetWidgetData: () => assetWidgetData2+ readAssetWidgetHtml: () => readAssetWidgetHtml});-import { readFile as readFile8 } from "node:fs/promises";-async function assetWidgetData2(library, selector) {- const record5 = await library.read(selector.collection, selector.asset.assetId, selector.asset.revisionId);- if (Object.values(record5.files).reduce((sum, bytes) => sum + bytes.length, 0) > WIDGET_TRANSFER_LIMIT)- return {- kilnAsset: {- error: "This asset exceeds the 16 MiB chat preview limit. Open it with kiln view."- }- };- return {- kilnAsset: {- manifest: record5.manifest,- downloadUrls: selector.downloadUrls,- files: encodeWidgetFiles(record5.files)- }- };-}-async function readAssetWidgetHtml2() {- return readFile8(new URL("../dist/viewer/chat.html", import.meta.url), "utf8");+import { readFile as readFile6 } from "node:fs/promises";+async function readAssetWidgetHtml() {+ return readFile6(new URL("../dist/viewer/chat.html", import.meta.url), "utf8");}var init_asset_widget2 = __esm(() => {init_widget_transfer();@@ -27450,7 +26136,7 @@ async function readAssetResource(library, uri) {// src/mcp-server.tsimport { serveStdio } from "@modelcontextprotocol/server/stdio";import { AsyncLocalStorage } from "async_hooks";-import { fileURLToPath as fileURLToPath4 } from "url";+import { fileURLToPath as fileURLToPath5 } from "url";// src/tools/registry.tsinit_capture_cache();@@ -27466,14 +26152,14 @@ function assertProgramRef(ref) {throw new Error("Invalid program reference; use a p_ handle or full sha256 reference returned by Kiln.");}async function retainProgram(store, code) {- const canonical2 = await store.put(code);- return store.shortRef ? store.shortRef(canonical2) : canonical2;+ const canonical = await store.put(code);+ return store.shortRef ? store.shortRef(canonical) : canonical;}-function* shortProgramRefCandidates(canonical2) {- if (!canonicalProgramRefPattern.test(canonical2) || canonical2.length !== 71)+function* shortProgramRefCandidates(canonical) {+ if (!canonicalProgramRefPattern.test(canonical) || canonical.length !== 71)throw new Error("Invalid canonical program reference.");for (let length = 12;length <= 64; length += 4)- yield `p_${canonical2.slice(7, 7 + length)}`;+ yield `p_${canonical.slice(7, 7 + length)}`;}async function programReference(code) {const bytes = new TextEncoder().encode(code);@@ -27481,8 +26167,8 @@ async function programReference(code) {throw new Error("Program exceeds the 1 MiB source limit.");if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== code)throw new Error("Program must be valid Unicode.");- const hash2 = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));- return `sha256:${Array.from(hash2, (b) => b.toString(16).padStart(2, "0")).join("")}`;+ const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));+ return `sha256:${Array.from(hash, (b) => b.toString(16).padStart(2, "0")).join("")}`;}class MemoryProgramStore {@@ -27515,8 +26201,8 @@ class MemoryProgramStore {}async get(ref) {assertProgramRef(ref);- const canonical2 = ref.startsWith("p_") ? this.handles.get(ref) : ref;- const code = canonical2 === undefined ? undefined : this.programs.get(canonical2);+ const canonical = ref.startsWith("p_") ? this.handles.get(ref) : ref;+ const code = canonical === undefined ? undefined : this.programs.get(canonical);if (code === undefined)throw new Error(`Program not found: ${ref}. Import the source into this store again.`);return code;@@ -27719,13 +26405,13 @@ Note: ${entry.promptNotes}` : ""}`;const unknown = requested.filter((_, index) => !selected[index]);if (unknown.length)return missing(`Unknown helpers: ${unknown.join(", ")}.`);- const primitives2 = selected.filter((entry) => Boolean(entry));+ const primitives = selected.filter((entry) => Boolean(entry));return {- primitives: primitives2,- total: primitives2.length,+ primitives,+ total: primitives.length,nextOffset: null,categories,- text: [`${primitives2.length} requested helpers.`, ...primitives2.map(detail)].join(`+ text: [`${primitives.length} requested helpers.`, ...primitives.map(detail)].join(``)};@@ -27745,7 +26431,7 @@ Note: ${entry.promptNotes}` : ""}`;return missing(`No helper matches ${input.name ? `name "${input.name}"` : `query "${input.query ?? input.category}"`}.`);const overview = input.overview ?? !(input.name || input.query || input.category || input.offset || input.limit);if (overview) {- const text3 = [+ const text = ['Kiln helper overview. Use {names:["boxGeo","createPart"]} for up to six signatures/examples together, {name:"boxGeo"} for one, {query:"holes"} for an operation, or {category:"geometry"} to browse.',...categories.map((group) => `${group}: ${matches.filter((entry) => entry.category === group).map((entry) => entry.name).join(", ")}`).filter((line) => !line.endsWith(": ")),"Custom geometry: THREE.BufferGeometry, indexed triangles and ordinary functions are available. GLB exports position, normal, UV0, tangent, indices and material groups. Query meshGeo, parametricSurface, sweepProfile, loftProfiles or twist for focused examples.",@@ -27762,20 +26448,20 @@ Note: ${entry.promptNotes}` : ""}`;nextOffset: null,categories,capabilities,- text: text3+ text};}const offset = input.offset ?? 0;const primitives = matches.slice(offset, offset + (input.limit ?? 6));const nextOffset = offset + primitives.length < matches.length ? offset + primitives.length : null;- const text2 = [+ const text = [`${matches.length} matching helpers. Showing ${primitives.length ? offset + 1 : 0}–${offset + primitives.length}.`,...primitives.map(detail),...nextOffset === null ? [] : [`More results: repeat this query with offset:${nextOffset}.`]].join(``);- return { primitives, total: matches.length, nextOffset, categories, text: text2 };+ return { primitives, total: matches.length, nextOffset, categories, text };},text: (output) => output.text};@@ -27783,7 +26469,7 @@ Note: ${entry.promptNotes}` : ""}`;// src/build-cache.tsinit_protocol();-import { createHash as createHash8 } from "node:crypto";+import { createHash as createHash7 } from "node:crypto";import * as acorn2 from "acorn";import * as walk2 from "acorn-walk";function sourceHasAmbientInputs(code) {@@ -27903,7 +26589,7 @@ function createCachedEvaluatorPort(evaluator, options) {} catch {return evaluator.render(code, renderOptions, controls);}- const key = `sha256:${createHash8("sha256").update(serialized).digest("hex")}`;+ const key = `sha256:${createHash7("sha256").update(serialized).digest("hex")}`;const cached = await options.cache.get(key).catch(() => {return;});@@ -28018,9 +26704,9 @@ function diffLines(a, b) {const n = a.length;const m = b.length;const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));- for (let i2 = n - 1;i2 >= 0; i2--) {- for (let j2 = m - 1;j2 >= 0; j2--) {- lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);+ for (let i = n - 1;i >= 0; i--) {+ for (let j = m - 1;j >= 0; j--) {+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);}}const ops = [];@@ -28160,20 +26846,20 @@ function resolveViewRenderTimeoutMs(input) {...remainingGenerationBudgetMs !== undefined ? { remainingGenerationBudgetMs } : {},...rendererDeadlineMs !== undefined ? { rendererDeadlineMs } : {}});- let resolved2 = timeoutMs;+ let resolved = timeoutMs;if (input.resolver && hostContextAvailable) {try {- resolved2 = boundedTimeout(input.resolver(resolverContext), timeoutMs);+ resolved = boundedTimeout(input.resolver(resolverContext), timeoutMs);} catch {- resolved2 = timeoutMs;+ resolved = timeoutMs;}}if (rendererDeadlineMs !== undefined)- resolved2 = Math.min(resolved2, rendererDeadlineMs);+ resolved = Math.min(resolved, rendererDeadlineMs);if (remainingGenerationBudgetMs !== undefined) {- resolved2 = Math.min(resolved2, remainingGenerationBudgetMs);+ resolved = Math.min(resolved, remainingGenerationBudgetMs);}- return boundedTimeout(resolved2, timeoutMs);+ return boundedTimeout(resolved, timeoutMs);}// src/tools/registry.ts@@ -28184,8 +26870,8 @@ function proceduralTextureMaterialContract(rendered, context) {if (required.length === 0)return;const available = new Set((rendered.bakedTextures ?? []).map((entry) => entry.usage));- const present = required.filter((usage2) => available.has(usage2));- const missing = required.filter((usage2) => !available.has(usage2));+ const present = required.filter((usage) => available.has(usage));+ const missing = required.filter((usage) => !available.has(usage));return { required, present, missing };}function missingProceduralTextureResult(rendered, context) {@@ -28224,8 +26910,8 @@ async function evaluateGeneratedSource(code, context, optimize = "off") {}async function loadEvaluatedReviewScene(code, context) {const rendered = await evaluateGeneratedSource(code, context);- const { loadGlbReviewScene: loadGlbReviewScene2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const scene = await loadGlbReviewScene2(rendered.glb);+ await Promise.resolve().then(() => init_views());+ const scene = await loadGlbReviewScene(rendered.glb);return { rendered, ...scene };}var viewEvidenceHistoryByContext = new WeakMap;@@ -28241,8 +26927,8 @@ function withViewEvidenceHistory(context) {return { ...context, viewEvidenceHistory: history };}async function sha256Glb(bytes) {- const digest3 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));- return `sha256:${[...digest3].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;}async function renderDerivativeCell(input, context) {let derivativeRoot = input.root;@@ -28253,9 +26939,9 @@ async function renderDerivativeCell(input, context) {if (!mesh.isMesh)return;const prepare = (material) => {- const copy2 = material.clone();- copy2.side = THREE35.DoubleSide;- return copy2;+ const copy = material.clone();+ copy.side = THREE35.DoubleSide;+ return copy;};mesh.material = Array.isArray(mesh.material) ? mesh.material.map(prepare) : prepare(mesh.material);});@@ -28283,23 +26969,23 @@ async function renderDerivativeCell(input, context) {...trustedCategory(context) ? { category: trustedCategory(context) } : {},...context.intent ? { intent: context.intent } : {}});- const { cameraFromBounds: cameraFromBounds2, measureBounds: measureBounds2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const camera2 = input.camera ?? cameraFromBounds2(input.frameBounds ?? measureBounds2(input.root), input.view.dir, 1, undefined, measureBounds2(input.root));+ await Promise.resolve().then(() => init_views());+ const camera = input.camera ?? cameraFromBounds(input.frameBounds ?? measureBounds(input.root), input.view.dir, 1, undefined, measureBounds(input.root));const derivativeGlb = Uint8Array.from(rendered.bytes);const inputGlbSha256 = await sha256Glb(derivativeGlb);let degradeReason;const derivativeReasonCodes = [];if (context.viewRenderPort) {- const { captureViewPngsViaPort: captureViewPngsViaPort2 } = await Promise.resolve().then(() => (init_port(), exports_port));- const ported = await captureViewPngsViaPort2(context.viewRenderPort, derivativeGlb, resolveInLoopViewRenderTimeoutMs(context, "derivative-cell"), [input.view.dir], input.size, [camera2], context.captureLimits);+ await Promise.resolve().then(() => init_port());+ const ported = await captureViewPngsViaPort(context.viewRenderPort, derivativeGlb, resolveInLoopViewRenderTimeoutMs(context, "derivative-cell"), [input.view.dir], input.size, [camera], context.captureLimits);if (ported.ok && ported.derivativeFidelityAttested) {if (ported.inputGlbSha256 !== inputGlbSha256) {throw new Error(`validated derivative receipt hash mismatch (${ported.inputGlbSha256} != ${inputGlbSha256})`);}- const receipt2 = {+ const receipt = {version: "kiln.view-fidelity.v1",derivativeLabel: input.label,- camera: camera2,+ camera,cameraFidelity: "echo-validated",...ported.captureCache ? { captureCache: ported.captureCache } : {},requested: "full-preferred",@@ -28317,7 +27003,7 @@ async function renderDerivativeCell(input, context) {neededPbr: true});} catch {}- return { png: Buffer.from(ported.pngs[0]), receipt: receipt2 };+ return { png: Buffer.from(ported.pngs[0]), receipt };}if (ported.ok) {degradeReason = "view render port returned no derivative material/hash receipt";@@ -28335,17 +27021,17 @@ async function renderDerivativeCell(input, context) {}if (context.viewRenderRequired)throw new Error(`Required GPU render failed: ${degradeReason}`);- const { renderGlbViewCell: renderGlbViewCell2, CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const produceFlat = async () => renderGlbViewCell2(derivativeGlb, input.view, {+ await Promise.resolve().then(() => init_views());+ const produceFlat = async () => renderGlbViewCell(derivativeGlb, input.view, {size: input.size,- camera: camera2,+ camera,...input.backfaceCull !== undefined ? { backfaceCull: input.backfaceCull } : {},...input.frameBounds ? { frameBounds: input.frameBounds } : {}});const flat = context.captureCache ? await (await Promise.resolve().then(() => (init_capture_cache(), exports_capture_cache))).captureCpuCell(context.captureCache, {artifactGlbSha256: inputGlbSha256,- rendererId: CPU_RASTER_RENDERER_ID2,- camera: camera2,+ rendererId: CPU_RASTER_RENDERER_ID,+ camera,size: input.size,backfaceCull: input.backfaceCull ?? true}, produceFlat) : await produceFlat();@@ -28361,7 +27047,7 @@ async function renderDerivativeCell(input, context) {const receipt = {version: "kiln.view-fidelity.v1",derivativeLabel: input.label,- camera: camera2,+ camera,cameraFidelity: "engine-resolved",...flat.captureCache ? {captureCache: {@@ -28374,7 +27060,7 @@ async function renderDerivativeCell(input, context) {delivered: "geometry-flat",materialFaithful: false,exactArtifact: false,- rendererId: CPU_RASTER_RENDERER_ID2,+ rendererId: CPU_RASTER_RENDERER_ID,inputGlbSha256,degraded: true,degradeReason,@@ -28382,7 +27068,7 @@ async function renderDerivativeCell(input, context) {};try {context.onViewsRendered?.({- renderer: CPU_RASTER_RENDERER_ID2,+ renderer: CPU_RASTER_RENDERER_ID,degraded: true,degradedReason: degradeReason,neededPbr: true@@ -28510,12 +27196,12 @@ function runListPrimitives(input) {const all = listPrimitives();const category = input.category?.trim().toLowerCase();const primitives = category ? all.filter((p) => p.category.toLowerCase() === category) : all;- const text2 = primitives.map((p) => `${p.signature} -> ${p.returns}+ const text = primitives.map((p) => `${p.signature} -> ${p.returns}${p.description}e.g. ${p.example}`).join(``);- return { primitives, text: text2 };+ return { primitives, text };}function runValidate(input, context) {const category = trustedCategory(context);@@ -28611,12 +27297,12 @@ async function runRender(input, context) {}async function runScreenshot(input, context) {try {- const { renderGlbViewGrid: renderGlbViewGrid2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root, rendered } = await loadEvaluatedReviewScene(input.code, context);const warnings = inspectSceneStructure(root, {category: trustedCategory(context)});- const grid = await renderGlbViewGrid2(rendered.glb);+ const grid = await renderGlbViewGrid(rendered.glb);return {ok: true,views: grid.views,@@ -28642,7 +27328,7 @@ function screenshotMedia(output) {}async function runRenderViews(input, context) {try {- const { renderGlbViewGrid: renderGlbViewGrid2, CPU_RASTER_RENDERER_ID: CPU_RASTER_RENDERER_ID2, resolveGridCapture: resolveGridCapture2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root, rendered, reasonCodes } = await loadEvaluatedReviewScene(input.code, context);const materialContractFailure = missingProceduralTextureResult(rendered, context);if (materialContractFailure)@@ -28651,10 +27337,10 @@ async function runRenderViews(input, context) {const structuralWarnings = inspectSceneStructure(root, { category });const metrics = collectSceneMetrics(root);if ("shots" in (input.capture ?? {})) {- const { renderCaptureGrid: renderCaptureGrid2, listCameraSubjects: listCameraSubjects2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const grid2 = await renderCaptureGrid2(root, input.capture, (cell) => renderDerivativeCell(cell, context));- const receipts = grid2.derivativeReceipts;- const materialFaithful2 = receipts.every((r) => r.materialFaithful);+ await Promise.resolve().then(() => init_views());+ const grid = await renderCaptureGrid(root, input.capture, (cell) => renderDerivativeCell(cell, context));+ const receipts = grid.derivativeReceipts;+ const materialFaithful = receipts.every((r) => r.materialFaithful);return {ok: true,...rendered.buildCache ? { buildCache: rendered.buildCache } : {},@@ -28664,24 +27350,24 @@ async function runRenderViews(input, context) {...rendered.meta.instanceability ? { distinctMaterials: rendered.meta.instanceability.metrics.uniqueMaterials } : {},bbox: metrics.bbox,lowestPart: metrics.lowestPart,- views: grid2.views,- capture: grid2.capture,- ...grid2.captureCache ? { captureCache: grid2.captureCache } : {},- gridWidth: grid2.width,- gridHeight: grid2.height,- cameraShots: grid2.cameraShots,- parts: listCameraSubjects2(root).slice(0, 80).map(({ path, name }) => ({ path, name })),+ views: grid.views,+ capture: grid.capture,+ ...grid.captureCache ? { captureCache: grid.captureCache } : {},+ gridWidth: grid.width,+ gridHeight: grid.height,+ cameraShots: grid.cameraShots,+ parts: listCameraSubjects(root).slice(0, 80).map(({ path, name }) => ({ path, name })),derivativeReceipts: receipts,- ..."output" in input.capture && input.capture.output === "separate" ? { framesBase64: grid2.perFramePngs.map((p) => p.toString("base64")) } : { pngBase64: grid2.png.toString("base64") },+ ..."output" in input.capture && input.capture.output === "separate" ? { framesBase64: grid.perFramePngs.map((p) => p.toString("base64")) } : { pngBase64: grid.png.toString("base64") },viewFidelity: {version: "kiln.view-fidelity.v1",requested: "full-preferred",- delivered: materialFaithful2 ? "full-material" : "geometry-flat",- materialFaithful: materialFaithful2,+ delivered: materialFaithful ? "full-material" : "geometry-flat",+ materialFaithful,exactArtifact: false,rendererId: [...new Set(receipts.map((r) => r.rendererId))].join(", "),inputGlbSha256: await sha256Glb(Uint8Array.from(rendered.glb)),- degraded: !materialFaithful2+ degraded: !materialFaithful},warnings: [...structuralWarnings, ...rendered.warnings]};@@ -28691,10 +27377,10 @@ async function runRenderViews(input, context) {let drawnBy;let materialFaithful = false;if (context.viewRenderPort && (neededPbr || context.viewRenderRequired)) {- const { captureViewsViaPort: captureViewsViaPort2 } = await Promise.resolve().then(() => (init_port(), exports_port));- const ported = await captureViewsViaPort2(context.viewRenderPort, rendered.glb, resolveInLoopViewRenderTimeoutMs(context, "in-loop-grid"), input.capture);+ await Promise.resolve().then(() => init_port());+ const ported = await captureViewsViaPort(context.viewRenderPort, rendered.glb, resolveInLoopViewRenderTimeoutMs(context, "in-loop-grid"), input.capture);if (ported.ok) {- const resolvedViews = resolveGridCapture2(input.capture, process.env["KILN_GRID_VARIANT"]);+ const resolvedViews = resolveGridCapture(input.capture, process.env["KILN_GRID_VARIANT"]);grid = {png: ported.png,views: resolvedViews.views.map((v) => v.name),@@ -28707,7 +27393,7 @@ async function runRenderViews(input, context) {drawnBy = { renderer: ported.rendererId, degraded: false, neededPbr };} else {drawnBy = {- renderer: CPU_RASTER_RENDERER_ID2,+ renderer: CPU_RASTER_RENDERER_ID,degraded: true,degradedReason: ported.reason,neededPbr@@ -28717,13 +27403,13 @@ async function runRenderViews(input, context) {if (!grid && context.viewRenderRequired)throw new Error(`Required GPU render failed: ${drawnBy?.degradedReason ?? "renderer unavailable"}`);if (!grid) {- grid = await renderGlbViewGrid2(rendered.glb, {+ grid = await renderGlbViewGrid(rendered.glb, {...input.capture ? { capture: input.capture } : {},...context.captureCache ? { captureCache: context.captureCache } : {}});}- drawnBy ??= context.viewRenderPort ? { renderer: CPU_RASTER_RENDERER_ID2, degraded: false, neededPbr } : {- renderer: CPU_RASTER_RENDERER_ID2,+ drawnBy ??= context.viewRenderPort ? { renderer: CPU_RASTER_RENDERER_ID, degraded: false, neededPbr } : {+ renderer: CPU_RASTER_RENDERER_ID,degraded: neededPbr,...neededPbr ? {degradedReason: "material-faithful view render port unavailable"@@ -28732,8 +27418,8 @@ async function runRenderViews(input, context) {};const hashInput = new Uint8Array(rendered.glb.byteLength);hashInput.set(rendered.glb);- const digest3 = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", hashInput));- const inputGlbSha256 = `sha256:${[...digest3].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", hashInput));+ const inputGlbSha256 = `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;const viewFidelity = {version: "kiln.view-fidelity.v1",requested: "full-preferred",@@ -28802,12 +27488,12 @@ function createKilnRenderViewsDef(context = {}) {var kilnRenderViewsDef = createKilnRenderViewsDef();async function runScreenshotAnimation(input, context) {try {- const { renderClipAnimation: renderClipAnimation2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root, clips } = await loadEvaluatedReviewScene(input.code, context);const warnings = inspectSceneStructure(root, {category: trustedCategory(context)});- const r = await renderClipAnimation2(root, clips, {+ const r = await renderClipAnimation(root, clips, {clip: input.clip,...input.shot ? { shot: input.shot } : {},...input.frames !== undefined ? { frames: input.frames } : {},@@ -28888,19 +27574,19 @@ function createKilnScreenshotAnimationDef(context = {}) {var kilnScreenshotAnimationDef = createKilnScreenshotAnimationDef();async function runViewInterior(input, context) {try {- const { renderInteriorGrid: renderInteriorGrid2 } = await Promise.resolve().then(() => (init_views(), exports_views));+ await Promise.resolve().then(() => init_views());const { root } = await loadEvaluatedReviewScene(input.code, context);- const nodeName2 = input.nodeName?.trim() ? input.nodeName : undefined;- const grid = await renderInteriorGrid2(root, {+ const nodeName = input.nodeName?.trim() ? input.nodeName : undefined;+ const grid = await renderInteriorGrid(root, {...input.capture ? { capture: input.capture } : {},- ...nodeName2 ? { nodeName: nodeName2 } : {},+ ...nodeName ? { nodeName } : {},renderDerivativeCell: (cell) => renderDerivativeCell(cell, context)});const warnings = inspectSceneStructure(root, {category: trustedCategory(context)});if (grid.roofsHidden === 0) {- warnings.push(nodeName2 ? `No node named "${nodeName2}" was found, so the roof could not be lifted and the interior is still occluded. Check that name, or omit nodeName so the roof is found by its semantic role instead.` : 'No roof was found, so nothing could be lifted and the interior is still occluded. Build the roof with createRoofPlanes/createGableRoof (which tag it as a roof), or name the roof group "Roof".');+ warnings.push(nodeName ? `No node named "${nodeName}" was found, so the roof could not be lifted and the interior is still occluded. Check that name, or omit nodeName so the roof is found by its semantic role instead.` : 'No roof was found, so nothing could be lifted and the interior is still occluded. Build the roof with createRoofPlanes/createGableRoof (which tag it as a roof), or name the roof group "Roof".');}const viewFidelity = derivativeReviewFidelity(grid.derivativeReceipts);const viewEvidence = viewFidelity ? context.viewEvidenceHistory?.record("kiln_view_interior", viewFidelity) : undefined;@@ -28956,10 +27642,10 @@ var inspectInput = z4.object({var inspectBufferInput = inspectInput.omit({ code: true });async function runInspect(input, context) {try {- const { prepareInspectView: prepareInspectView2 } = await Promise.resolve().then(() => (init_inspect(), exports_inspect));+ await Promise.resolve().then(() => init_inspect());const { root } = await loadEvaluatedReviewScene(input.code, context);- const { measureAttachment: measureAttachment2, describeSubjectFrame: describeSubjectFrame2 } = await Promise.resolve().then(() => (init_measurement(), exports_measurement));- const measurement = input.measure ? measureAttachment2(root, input.measure) : undefined;+ await Promise.resolve().then(() => init_measurement());+ const measurement = input.measure ? measureAttachment(root, input.measure) : undefined;if (input.shot) {if ([input.part,@@ -28970,12 +27656,12 @@ async function runInspect(input, context) {input.isolate].some((v) => v !== undefined))throw new Error("shot cannot be combined with legacy inspection controls");- const { renderCaptureGrid: renderCaptureGrid2 } = await Promise.resolve().then(() => (init_views(), exports_views));- const grid = await renderCaptureGrid2(root, { version: "kiln.capture.v1", shots: [input.shot], size: 512 }, (cell) => renderDerivativeCell(cell, context));+ await Promise.resolve().then(() => init_views());+ const grid = await renderCaptureGrid(root, { version: "kiln.capture.v1", shots: [input.shot], size: 512 }, (cell) => renderDerivativeCell(cell, context));return {ok: true,cameraShot: grid.cameraShots[0],- subjectFrame: describeSubjectFrame2(root, input.shot.subject),+ subjectFrame: describeSubjectFrame(root, input.shot.subject),...measurement ? { measurement } : {},pngBase64: grid.perFramePngs[0].toString("base64"),width: 512,@@ -28983,7 +27669,7 @@ async function runInspect(input, context) {viewFidelity: derivativeReviewFidelity(grid.derivativeReceipts)};}- const r = prepareInspectView2(root, {+ const r = prepareInspectView(root, {...input.part !== undefined ? { part: input.part } : {},...input.view !== undefined ? { view: input.view } : {},...input.azimuthDeg !== undefined ? { azimuthDeg: input.azimuthDeg } : {},@@ -29168,12 +27854,12 @@ function withBuildCache(context) {})};}-async function guardCaptureBudget(name, input, context, run2) {+async function guardCaptureBudget(name, input, context, run) {try {- const { enforceCapturePixels: enforceCapturePixels2, enforceCaptureBytes: enforceCaptureBytes2 } = await Promise.resolve().then(() => (init_capture_limits(), exports_capture_limits));+ await Promise.resolve().then(() => init_capture_limits());const args = input;if (name === "kiln_edit" && args.render === false)- return await run2();+ return await run();let cells = 6, size = 384, cols = 3, compose = true;if (name === "kiln_inspect") {cells = 1;@@ -29193,18 +27879,18 @@ async function guardCaptureBudget(name, input, context, run2) {size = args.capture.size ?? 384;cols = args.capture.cols ?? Math.min(3, cells);} else {- const { resolveGridCapture: resolveGridCapture2 } = await Promise.resolve().then(() => (init_capture(), exports_capture));- const resolved2 = resolveGridCapture2(args.capture);- cells = resolved2.views.length;- cols = resolved2.cols;+ await Promise.resolve().then(() => init_capture());+ const resolved = resolveGridCapture(args.capture);+ cells = resolved.views.length;+ cols = resolved.cols;}}- enforceCapturePixels2(cells, size, cols, context.captureLimits, compose);- const out = await run2();+ enforceCapturePixels(cells, size, cols, context.captureLimits, compose);+ const out = await run();if (out && typeof out === "object") {const media = out;const encoded = media.framesBase64 ?? (media.pngBase64 ? [media.pngBase64] : []);- enforceCaptureBytes2(encoded.map((value) => Buffer.from(value, "base64")), context.captureLimits);+ enforceCaptureBytes(encoded.map((value) => Buffer.from(value, "base64")), context.captureLimits);}return out;} catch (error) {@@ -29267,27 +27953,27 @@ function createKilnAssetDefs(context) {throw new Error("No asset library configured. The local CLI/MCP host supplies workspace collections; embedded hosts must inject assetLibrary.");return context.assetLibrary;};- const links = async (collection, asset2) => ({+ const links = async (collection, asset) => ({ok: true,collection,asset: {- assetId: asset2.assetId,- revisionId: asset2.revisionId,- parentRevision: asset2.parentRevision,- name: asset2.name,- tags: asset2.tags,- createdAt: asset2.createdAt,- editable: asset2.editable,- files: asset2.files,- build: asset2.build && {- engine: asset2.build.engine,- rebuild: asset2.build.rebuild,- warningCount: asset2.build.warnings.length,- warnings: asset2.build.warnings.slice(0, 3).map((warning) => warning.slice(0, 200))+ assetId: asset.assetId,+ revisionId: asset.revisionId,+ parentRevision: asset.parentRevision,+ name: asset.name,+ tags: asset.tags,+ createdAt: asset.createdAt,+ editable: asset.editable,+ files: asset.files,+ build: asset.build && {+ engine: asset.build.engine,+ rebuild: asset.build.rebuild,+ warningCount: asset.build.warnings.length,+ warnings: asset.build.warnings.slice(0, 3).map((warning) => warning.slice(0, 200))}},- resources: (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).assetLinks(collection, asset2),- downloadUrls: await context.assetDownloadUrls?.(collection, asset2.assetId, asset2.revisionId)+ resources: (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).assetLinks(collection, asset),+ downloadUrls: await context.assetDownloadUrls?.(collection, asset.assetId, asset.revisionId)});const saveInput = z4.object({collection: assetSelector.collection,@@ -29345,7 +28031,7 @@ function createKilnAssetDefs(context) {};}const dependencies = rendered.materialResourceProvenance ?? [];- const asset2 = await target.save(input.collection, {+ const asset = await target.save(input.collection, {...input,code,glb: rendered.glb,@@ -29368,7 +28054,7 @@ function createKilnAssetDefs(context) {rebuild: dependencies.some((d) => d.delivery === "runtime") ? "external-dependencies-required" : "engine-required"}});- return links(input.collection, asset2);+ return links(input.collection, asset);}},{@@ -29400,14 +28086,14 @@ function createKilnAssetDefs(context) {}if (!input.assetId || !input.revisionId)throw new Error("get/restore requires assetId and revisionId");- const record5 = await target.read(input.collection, input.assetId, input.revisionId);+ const record = await target.read(input.collection, input.assetId, input.revisionId);if (input.action === "get")- return links(input.collection, record5.manifest);- const code = record5.files["source.kiln.js"];+ return links(input.collection, record.manifest);+ const code = record.files["source.kiln.js"];if (!code)throw new Error("Source unavailable: this asset contains only a GLB");return {- ...await links(input.collection, record5.manifest),+ ...await links(input.collection, record.manifest),programRef: await retainProgram(context.programStore, new TextDecoder().decode(code))};}@@ -29469,16 +28155,16 @@ function createKilnAssetDefs(context) {run: async (raw) => {const input = importInput.parse(raw);const target = library();- const record5 = await target.read(input.sourceCollection, input.assetId, input.revisionId);- await target.import(input.collection, [record5]);- return links(input.collection, record5.manifest);+ const record = await target.read(input.sourceCollection, input.assetId, input.revisionId);+ await target.import(input.collection, [record]);+ return links(input.collection, record.manifest);}}];}// src/cli-render-mode.ts-import { createHash as createHash9 } from "node:crypto";+import { createHash as createHash8 } from "node:crypto";var DEFAULT_LOCAL_PORT_URL = "http://127.0.0.1:8000";var HEALTH_PROBE_TIMEOUT_MS = 1500;var HEALTH_PROBE_BUSY_TIMEOUT_MS = 8000;@@ -29493,7 +28179,7 @@ function makeRemoteRenderPort(url, token) {const body = {glb_base64: Buffer.from(req.glb).toString("base64")};- const inputGlbSha256 = `sha256:${createHash9("sha256").update(req.glb).digest("hex")}`;+ const inputGlbSha256 = `sha256:${createHash8("sha256").update(req.glb).digest("hex")}`;body["input_glb_sha256"] = inputGlbSha256;if (req.cameras) {body["cameras"] = req.cameras;@@ -29610,9 +28296,9 @@ async function buildRenderPort(mode, portUrl) {}// src/program-store-node.ts-import { link, lstat as lstat2, mkdir as mkdir2, readFile as readFile4, readdir as readdir2, stat, unlink, writeFile as writeFile3 } from "node:fs/promises";+import { link, lstat as lstat2, mkdir as mkdir2, readFile as readFile2, readdir as readdir2, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";import { randomUUID as randomUUID2 } from "node:crypto";-import { join as join4, resolve as resolve2 } from "node:path";+import { join as join3, resolve as resolve2 } from "node:path";class FileProgramStore {directory;constructor(directory) {@@ -29626,7 +28312,7 @@ class FileProgramStore {if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))continue;try {- bytes += (await stat(join4(this.directory, entry.name))).size;+ bytes += (await stat(join3(this.directory, entry.name))).size;entries++;} catch (error) {if (error.code !== "ENOENT")@@ -29641,21 +28327,21 @@ class FileProgramStore {}async get(ref) {assertProgramRef(ref);- const canonical3 = ref.startsWith("p_") ? await this.readHandle(ref) : ref;- if (canonical3 === undefined)+ const canonical = ref.startsWith("p_") ? await this.readHandle(ref) : ref;+ if (canonical === undefined)throw this.notFound(ref);- const path = join4(this.directory, `${canonical3.slice(7)}.js`);+ const path = join3(this.directory, `${canonical.slice(7)}.js`);let code;try {if ((await stat(path)).size > MAX_PROGRAM_BYTES)throw new Error("Stored program exceeds the 1 MiB source limit.");- code = await readFile4(path, "utf8");+ code = await readFile2(path, "utf8");} catch (error) {if (error.code === "ENOENT")throw this.notFound(ref);throw error;}- if (await programReference(code) !== canonical3)+ if (await programReference(code) !== canonical)throw new Error(`Program integrity check failed: ${ref}`);return code;}@@ -29663,15 +28349,15 @@ class FileProgramStore {return new Error(`Program not found: ${ref}. Use the same KILN_PROGRAM_STORE or import the source again.`);}async readHandle(handle) {- const path = join4(this.directory, "refs", `${handle}.ref`);+ const path = join3(this.directory, "refs", `${handle}.ref`);try {const info = await lstat2(path);if (!info.isFile() || info.size !== 71)throw new Error(`Program handle integrity check failed: ${handle}`);- const canonical3 = await readFile4(path, "utf8");- if (!canonicalProgramRefPattern.test(canonical3) || !canonical3.slice(7).startsWith(handle.slice(2)))+ const canonical = await readFile2(path, "utf8");+ if (!canonicalProgramRefPattern.test(canonical) || !canonical.slice(7).startsWith(handle.slice(2)))throw new Error(`Program handle integrity check failed: ${handle}`);- return canonical3;+ return canonical;} catch (error) {if (error.code === "ENOENT")return;@@ -29682,7 +28368,7 @@ class FileProgramStore {await this.get(ref);if (ref.startsWith("p_"))return ref;- const directory = join4(this.directory, "refs");+ const directory = join3(this.directory, "refs");await mkdir2(directory, { recursive: true });for (const handle of shortProgramRefCandidates(ref)) {const owner = await this.readHandle(handle);@@ -29690,11 +28376,11 @@ class FileProgramStore {return handle;if (owner !== undefined)continue;- const temporary = join4(directory, `.write-${randomUUID2()}`);- await writeFile3(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });+ const temporary = join3(directory, `.write-${randomUUID2()}`);+ await writeFile2(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link(temporary, join4(directory, `${handle}.ref`));+ await link(temporary, join3(directory, `${handle}.ref`));return handle;} catch (error) {if (error.code !== "EEXIST")@@ -29711,9 +28397,9 @@ class FileProgramStore {async put(code) {const ref = await programReference(code);await mkdir2(this.directory, { recursive: true });- const target = join4(this.directory, `${ref.slice(7)}.js`);- const temporary = join4(this.directory, `.write-${randomUUID2()}`);- await writeFile3(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });+ const target = join3(this.directory, `${ref.slice(7)}.js`);+ const temporary = join3(this.directory, `.write-${randomUUID2()}`);+ await writeFile2(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });try {try {await link(temporary, target);@@ -29732,15 +28418,29 @@ function localProgramStore() {return new FileProgramStore(resolve2(process.env["KILN_PROGRAM_STORE"] ?? ".kiln/programs"));}+// src/direct-entry.ts+import { realpathSync } from "node:fs";+import { resolve as resolve3 } from "node:path";+import { fileURLToPath as fileURLToPath3 } from "node:url";+function isDirectEntry(moduleUrl) {+ if (!process.argv[1])+ return false;+ try {+ return realpathSync(resolve3(process.argv[1])) === realpathSync(fileURLToPath3(moduleUrl));+ } catch {+ return false;+ }+}+// src/local-runtime.tsinit_subprocess();init_isolation();init_render();// src/program-store-node.ts-import { link as link2, lstat as lstat3, mkdir as mkdir3, readFile as readFile5, readdir as readdir3, stat as stat2, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";+import { link as link2, lstat as lstat3, mkdir as mkdir3, readFile as readFile3, readdir as readdir3, stat as stat2, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";import { randomUUID as randomUUID3 } from "node:crypto";-import { join as join5, resolve as resolve3 } from "node:path";+import { join as join4, resolve as resolve4 } from "node:path";class FileProgramStore2 {directory;constructor(directory) {@@ -29754,7 +28454,7 @@ class FileProgramStore2 {if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))continue;try {- bytes += (await stat2(join5(this.directory, entry.name))).size;+ bytes += (await stat2(join4(this.directory, entry.name))).size;entries++;} catch (error) {if (error.code !== "ENOENT")@@ -29769,21 +28469,21 @@ class FileProgramStore2 {}async get(ref) {assertProgramRef(ref);- const canonical3 = ref.startsWith("p_") ? await this.readHandle(ref) : ref;- if (canonical3 === undefined)+ const canonical = ref.startsWith("p_") ? await this.readHandle(ref) : ref;+ if (canonical === undefined)throw this.notFound(ref);- const path = join5(this.directory, `${canonical3.slice(7)}.js`);+ const path = join4(this.directory, `${canonical.slice(7)}.js`);let code;try {if ((await stat2(path)).size > MAX_PROGRAM_BYTES)throw new Error("Stored program exceeds the 1 MiB source limit.");- code = await readFile5(path, "utf8");+ code = await readFile3(path, "utf8");} catch (error) {if (error.code === "ENOENT")throw this.notFound(ref);throw error;}- if (await programReference(code) !== canonical3)+ if (await programReference(code) !== canonical)throw new Error(`Program integrity check failed: ${ref}`);return code;}@@ -29791,15 +28491,15 @@ class FileProgramStore2 {return new Error(`Program not found: ${ref}. Use the same KILN_PROGRAM_STORE or import the source again.`);}async readHandle(handle) {- const path = join5(this.directory, "refs", `${handle}.ref`);+ const path = join4(this.directory, "refs", `${handle}.ref`);try {const info = await lstat3(path);if (!info.isFile() || info.size !== 71)throw new Error(`Program handle integrity check failed: ${handle}`);- const canonical3 = await readFile5(path, "utf8");- if (!canonicalProgramRefPattern.test(canonical3) || !canonical3.slice(7).startsWith(handle.slice(2)))+ const canonical = await readFile3(path, "utf8");+ if (!canonicalProgramRefPattern.test(canonical) || !canonical.slice(7).startsWith(handle.slice(2)))throw new Error(`Program handle integrity check failed: ${handle}`);- return canonical3;+ return canonical;} catch (error) {if (error.code === "ENOENT")return;@@ -29810,7 +28510,7 @@ class FileProgramStore2 {await this.get(ref);if (ref.startsWith("p_"))return ref;- const directory = join5(this.directory, "refs");+ const directory = join4(this.directory, "refs");await mkdir3(directory, { recursive: true });for (const handle of shortProgramRefCandidates(ref)) {const owner = await this.readHandle(handle);@@ -29818,11 +28518,11 @@ class FileProgramStore2 {return handle;if (owner !== undefined)continue;- const temporary = join5(directory, `.write-${randomUUID3()}`);- await writeFile4(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });+ const temporary = join4(directory, `.write-${randomUUID3()}`);+ await writeFile3(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link2(temporary, join5(directory, `${handle}.ref`));+ await link2(temporary, join4(directory, `${handle}.ref`));return handle;} catch (error) {if (error.code !== "EEXIST")@@ -29839,9 +28539,9 @@ class FileProgramStore2 {async put(code) {const ref = await programReference(code);await mkdir3(this.directory, { recursive: true });- const target = join5(this.directory, `${ref.slice(7)}.js`);- const temporary = join5(this.directory, `.write-${randomUUID3()}`);- await writeFile4(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });+ const target = join4(this.directory, `${ref.slice(7)}.js`);+ const temporary = join4(this.directory, `.write-${randomUUID3()}`);+ await writeFile3(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });try {try {await link2(temporary, target);@@ -29859,35 +28559,35 @@ class FileProgramStore2 {// src/build-cache-node.tsinit_protocol();-import { createHash as createHash10, randomUUID as randomUUID4 } from "node:crypto";+import { createHash as createHash9, randomUUID as randomUUID4 } from "node:crypto";import {mkdir as mkdir4,- readFile as readFile6,+ readFile as readFile4,readdir as readdir4,rename as rename2,stat as stat3,unlink as unlink3,utimes,- writeFile as writeFile5+ writeFile as writeFile4} from "node:fs/promises";-import { join as join6, resolve as resolve4 } from "node:path";+import { join as join5, resolve as resolve5 } from "node:path";var keyPattern = /^sha256:[a-f0-9]{64}$/;var filePattern = /^[a-f0-9]{64}\.json$/;-var digest3 = (text2) => createHash10("sha256").update(text2).digest("hex");+var digest3 = (text) => createHash9("sha256").update(text).digest("hex");class FileBuildCache {maxBytes;directory;constructor(directory, maxBytes = 128 * 1024 * 1024) {this.maxBytes = maxBytes;- this.directory = resolve4(directory);+ this.directory = resolve5(directory);if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 1024 * 1024 * 1024)throw new Error("File build cache size must be 0..1 GiB.");}path(key) {if (!keyPattern.test(key))throw new Error("Invalid build cache key.");- return join6(this.directory, `${key.slice(7)}.json`);+ return join5(this.directory, `${key.slice(7)}.json`);}async get(key) {const path = this.path(key);@@ -29895,7 +28595,7 @@ class FileBuildCache {const entry = await stat3(path);if (entry.size > this.maxBytes || entry.size > 96 * 1024 * 1024)return;- const envelope = JSON.parse(await readFile6(path, "utf8"));+ const envelope = JSON.parse(await readFile4(path, "utf8"));if (envelope.version !== 1 || envelope.key !== key || typeof envelope.payload !== "string" || envelope.checksum !== digest3(envelope.payload))return;const decoded = decodeEvaluatorResultV1(envelope.payload, 64 * 1024 * 1024);@@ -29915,8 +28615,8 @@ class FileBuildCache {if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))return;await mkdir4(this.directory, { recursive: true });- const temporary = join6(this.directory, `.write-${randomUUID4()}`);- await writeFile5(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });+ const temporary = join5(this.directory, `.write-${randomUUID4()}`);+ await writeFile4(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });try {await rename2(temporary, path);} finally {@@ -29929,7 +28629,7 @@ class FileBuildCache {for (const name of await readdir4(this.directory)) {if (!filePattern.test(name))continue;- const path = join6(this.directory, name);+ const path = join5(this.directory, name);try {const item = await stat3(path);entries.push({ path, size: item.size, used: item.mtimeMs });@@ -29947,23 +28647,23 @@ class FileBuildCache {}// src/runtime-identity.ts-import { createHash as createHash11 } from "node:crypto";-import { readFile as readFile7, readdir as readdir5, realpath as realpath2, stat as stat4 } from "node:fs/promises";-import { createRequire as createRequire2 } from "node:module";-import { dirname as dirname2, join as join7, relative as relative2 } from "node:path";-var digest4 = (bytes) => createHash11("sha256").update(bytes).digest("hex");+import { createHash as createHash10 } from "node:crypto";+import { readFile as readFile5, readdir as readdir5, realpath as realpath2, stat as stat4 } from "node:fs/promises";+import { createRequire } from "node:module";+import { dirname as dirname2, join as join6, relative as relative2 } from "node:path";+var digest4 = (bytes) => createHash10("sha256").update(bytes).digest("hex");var compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;async function installedRuntimeIdentity(root, limits = {}) {let bytes = 0;let files = 0;const maxBytes = limits.maxBytes ?? 512 * 1024 * 1024;const maxFiles = limits.maxFiles ?? 40000;- const manifest = async (directory) => JSON.parse(await readFile7(join7(directory, "package.json"), "utf8"));+ const manifest = async (directory) => JSON.parse(await readFile5(join6(directory, "package.json"), "utf8"));let readers = 0;const waiting = [];const read = async (path) => {if (readers >= 24)- await new Promise((resolve5) => waiting.push(resolve5));+ await new Promise((resolve) => waiting.push(resolve));elsereaders++;try {@@ -29971,7 +28671,7 @@ async function installedRuntimeIdentity(root, limits = {}) {if (++files > maxFiles || bytes + info.size > maxBytes)throw new Error("Installed runtime fingerprint exceeds its scan budget.");bytes += info.size;- return await readFile7(path);+ return await readFile5(path);} finally {const next = waiting.shift();if (next)@@ -29984,17 +28684,17 @@ async function installedRuntimeIdentity(root, limits = {}) {const pkg = await manifest(root);if (pkg.name !== "@kiln/engine")throw new Error("Not a Kiln installation.");- const build = JSON.parse(await readFile7(join7(root, "dist", "build.json"), "utf8"));+ const build = JSON.parse(await readFile5(join6(root, "dist", "build.json"), "utf8"));const worker = build.entries?.worker;if (build.schemaVersion !== 1 || worker?.file !== "evaluator-worker.mjs" || !/^sha256:[a-f0-9]{64}$/.test(worker.identity))throw new Error("No valid packaged worker identity.");- const workerHash = `sha256:${digest4(await read(join7(root, "dist", worker.file)))}`;+ const workerHash = `sha256:${digest4(await read(join6(root, "dist", worker.file)))}`;if (worker.bundleHash !== workerHash)throw new Error("Packaged worker differs from its build manifest.");const records = [];const visited = new Map;async function resolvePackage(parent, name) {- const require2 = createRequire2(join7(parent, "package.json"));+ const require2 = createRequire(join6(parent, "package.json"));let found;try {found = require2.resolve(`${name}/package.json`);@@ -30003,7 +28703,7 @@ async function installedRuntimeIdentity(root, limits = {}) {found = require2.resolve(name);} catch {for (const modules of require2.resolve.paths(name) ?? []) {- const candidate = join7(modules, name);+ const candidate = join6(modules, name);try {if ((await manifest(candidate)).name === name)return await realpath2(candidate);@@ -30029,7 +28729,7 @@ async function installedRuntimeIdentity(root, limits = {}) {return (await Promise.all(entries.map(async (entry) => {if (entry.name === "node_modules" || entry.name === ".git")return [];- const path = join7(directory, entry.name);+ const path = join6(directory, entry.name);if (entry.isSymbolicLink())throw new Error("Dependency contains an untracked internal symlink.");if (entry.isDirectory())@@ -30040,16 +28740,16 @@ async function installedRuntimeIdentity(root, limits = {}) {}))).flat();}async function visit(directory, path) {- const canonical3 = await realpath2(directory);- const previous = visited.get(canonical3);+ const canonical = await realpath2(directory);+ const previous = visited.get(canonical);if (previous) {records.push([path, `same-package:${previous}`]);return;}- visited.set(canonical3, path);- const metadata = await manifest(canonical3);- records.push([path, digest4(JSON.stringify(await tree(canonical3, canonical3)))]);- await dependencies(canonical3, metadata, path);+ visited.set(canonical, path);+ const metadata = await manifest(canonical);+ records.push([path, digest4(JSON.stringify(await tree(canonical, canonical)))]);+ await dependencies(canonical, metadata, path);}async function dependencies(directory, metadata, prefix) {const names = [@@ -30095,8 +28795,8 @@ async function installedRuntimeIdentity(root, limits = {}) {}// src/local-runtime.ts-import { dirname as dirname3, join as join8, resolve as resolve5 } from "node:path";-import { fileURLToPath as fileURLToPath3 } from "node:url";+import { dirname as dirname3, join as join7, resolve as resolve6 } from "node:path";+import { fileURLToPath as fileURLToPath4 } from "node:url";var scope = 0;function integer2(env, name, fallback, min, max) {const value = env[name] === undefined ? fallback : Number(env[name]);@@ -30120,35 +28820,35 @@ function createLocalToolContext(base = {}, env = process.env) {throw new Error("KILN_QA_MODE overrides are not transported to the local worker. Remove the override or explicitly select trusted KILN_EVALUATOR_MODE=in-process.");}const optimize = ["auto", "palette", "full"].includes(env.KILN_BAKE_OPTIMIZE ?? "") ? env.KILN_BAKE_OPTIMIZE : "off";- const instance2 = ["off", "auto", "on"].includes(env.KILN_BAKE_INSTANCE ?? "") ? env.KILN_BAKE_INSTANCE : "auto";+ const instance = ["off", "auto", "on"].includes(env.KILN_BAKE_INSTANCE ?? "") ? env.KILN_BAKE_INSTANCE : "auto";const maxGlbBytes = 16 * 1024 * 1024;const maxResponseBytes = 32 * 1024 * 1024;const evaluatorPort = {async render(code, options = {}, controls = {}) {if (controls.signal?.aborted) {- const { EvaluatorPortError: EvaluatorPortError2 } = await Promise.resolve().then(() => (init_protocol(), exports_protocol));- throw new EvaluatorPortError2("CANCELLED");+ await Promise.resolve().then(() => init_protocol());+ throw new EvaluatorPortError("CANCELLED");}if (options.geometryPolicy !== undefined && !["warn", "strict"].includes(options.geometryPolicy))throw new Error("geometryPolicy must be warn or strict");- const resolved2 = {+ const resolved = {optimize,- instance: instance2,+ instance,...options,geometryPolicy: geometryPolicy === "strict" ? "strict" : options.geometryPolicy ?? "warn"};if (mode === "in-process") {- const result = await renderGLBInProcess(code, resolved2);+ const result = await renderGLBInProcess(code, resolved);if (controls.signal?.aborted) {- const { EvaluatorPortError: EvaluatorPortError2 } = await Promise.resolve().then(() => (init_protocol(), exports_protocol));- throw new EvaluatorPortError2("CANCELLED");+ await Promise.resolve().then(() => init_protocol());+ throw new EvaluatorPortError("CANCELLED");}return result;}const limits = { deadlineMs, maxGlbBytes, maxResponseBytes, ...controls };if (mode === "isolated")- return renderGLBViaIsolatedEvaluator(code, resolved2, limits);- return renderGLBViaSubprocess(code, resolved2, {+ return renderGLBViaIsolatedEvaluator(code, resolved, limits);+ return renderGLBViaSubprocess(code, resolved, {...limits,...!process.versions.bun ? { maxHeapMb: heapMb } : {}});@@ -30166,27 +28866,27 @@ function createLocalToolContext(base = {}, env = process.env) {return {...base,geometryPolicy,- programStore: base.programStore ?? new FileProgramStore2(resolve5(env.KILN_PROGRAM_STORE ?? ".kiln/programs")),+ programStore: base.programStore ?? new FileProgramStore2(resolve6(env.KILN_PROGRAM_STORE ?? ".kiln/programs")),evaluatorPort,assetBuildOptions: {optimize,- instance: instance2,+ instance,geometryPolicy,qaMode: env.KILN_QA_MODE ?? "enforce",evaluatorMode: mode},buildCache: new MemoryBuildCache,- evaluatorCacheIdentity: `kiln-local-${process.pid}-${++scope}:${JSON.stringify({ mode, optimize, instance: instance2, geometryPolicy, qa: env.KILN_QA_MODE, deadlineMs, heapMb })}`,+ evaluatorCacheIdentity: `kiln-local-${process.pid}-${++scope}:${JSON.stringify({ mode, optimize, instance, geometryPolicy, qa: env.KILN_QA_MODE, deadlineMs, heapMb })}`,localExecution};}-async function createPackagedLocalToolContext(base = {}, env = process.env, installationRoot = fileURLToPath3(new URL("../", import.meta.url))) {+async function createPackagedLocalToolContext(base = {}, env = process.env, installationRoot = fileURLToPath4(new URL("../", import.meta.url))) {const context = createLocalToolContext(base, env);const managed = () => {- const identity2 = context.evaluatorCacheIdentity;+ const identity = context.evaluatorCacheIdentity;const cached = createCachedEvaluatorPort(context.evaluatorPort, {cache: context.buildCache,- identity: () => typeof identity2 === "function" ? identity2() : identity2+ identity: () => typeof identity === "function" ? identity() : identity});context.evaluatorPort = {render: (code, options, controls) => cached.render(code, {@@ -30218,7 +28918,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst}const cacheBytes = integer2(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;const store = context.programStore;- const directory = resolve5(env.KILN_BUILD_CACHE_DIR ?? join8(store instanceof FileProgramStore2 ? dirname3(store.directory) : ".kiln", "cache", "builds"));+ const directory = resolve6(env.KILN_BUILD_CACHE_DIR ?? join7(store instanceof FileProgramStore2 ? dirname3(store.directory) : ".kiln", "cache", "builds"));context.buildCache = new FileBuildCache(directory, cacheBytes);context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({execution: context.localExecution,@@ -30240,7 +28940,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst// src/mcp-server.tsvar MCP_SERVER_NAME = "kiln";var MCP_SERVER_VERSION = "0.6.0";-var packagedSkillsDir = fileURLToPath4(new URL("../skills", import.meta.url));+var packagedSkillsDir = fileURLToPath5(new URL("../skills", import.meta.url));var MCP_SERVER_INSTRUCTIONS = `Kiln turns JavaScript you write into GLB 3D assets and returns rendered views for review.Work by reference. Send a program once to kiln_validate or kiln_render; the result carries a programRef. Keep it exactly as returned, including a short p_ handle, and use it for every later view and edit. kiln_source with that ref and a literal query returns exact edit anchors, and kiln_edit with that ref plus edits returns a new ref and renders by default. Do not resend a whole program to change part of it.@@ -30372,9 +29072,9 @@ function createKilnMcpServer(context = {}) {} : {},inputSchema: def.inputSchema,...def.outputSchema ? { outputSchema: def.outputSchema } : {}- }, async (args, request2) => {+ }, async (args, request) => {try {- return await requests.run(request2.mcpReq.signal, () => runTool(def, args));+ return await requests.run(request.mcpReq.signal, () => runTool(def, args));} catch (err) {return {isError: true,@@ -30390,7 +29090,7 @@ function createKilnMcpServer(context = {}) {}return server;}-if (__require.main == __require.module) {+if (isDirectEntry(import.meta.url)) {const mode = resolveRenderMode(process.env["KILN_RENDER"] ?? "auto");const context = await createPackagedLocalToolContext(await buildRenderPort(mode, process.env["KILN_RENDER_PORT_URL"]));context.programStore = localProgramStore();@@ -30409,10 +29109,10 @@ if (__require.main == __require.module) {serveStdio(() => createKilnMcpServer(context));}export {- runTool,- kilnMcpToolDefs,- createKilnMcpServer,- MCP_SERVER_VERSION,+ MCP_SERVER_INSTRUCTIONS,MCP_SERVER_NAME,- MCP_SERVER_INSTRUCTIONS+ MCP_SERVER_VERSION,+ createKilnMcpServer,+ kilnMcpToolDefs,+ runTool};diff --git a/dist/viewer/app.js b/dist/viewer/app.jsindex b75c35cc..b58eea1c 100644--- a/dist/viewer/app.js+++ b/dist/viewer/app.js@@ -1,79 +1,78 @@-var kF=Object.defineProperty;var FF=($)=>$;function LF($,U){this[$]=FF.bind(null,U)}var RJ=($,U)=>{for(var J in U)kF($,J,{get:U[J],enumerable:!0,configurable:!0,set:LF.bind(U,J)})};var W6={};RJ(W6,{xor:()=>Nq,xid:()=>SI,void:()=>Uq,uuidv7:()=>wI,uuidv6:()=>VI,uuidv4:()=>RI,uuid:()=>LI,util:()=>Q$,url:()=>MI,uppercase:()=>OW,unknown:()=>C0,union:()=>LK,undefined:()=>eI,ulid:()=>CI,uint64:()=>sI,uint32:()=>oI,tuple:()=>YG,trim:()=>kW,treeifyError:()=>$X,transform:()=>VK,toUpperCase:()=>LW,toLowerCase:()=>FW,toJSONSchema:()=>n9,templateLiteral:()=>Vq,symbol:()=>tI,superRefine:()=>yG,success:()=>kq,stringbool:()=>Cq,stringFormat:()=>lI,string:()=>f8,strictObject:()=>Kq,startsWith:()=>ZW,slugify:()=>RW,size:()=>z0,setErrorMap:()=>eL,set:()=>Eq,safeParseAsync:()=>y1,safeParse:()=>x1,safeEncodeAsync:()=>d1,safeEncode:()=>m1,safeDecodeAsync:()=>c1,safeDecode:()=>p1,registry:()=>k9,regexes:()=>LU,regex:()=>YW,refine:()=>xG,record:()=>GG,readonly:()=>SG,property:()=>m9,promise:()=>wq,prettifyError:()=>UX,preprocess:()=>Tq,prefault:()=>wG,positive:()=>h9,pipe:()=>e9,partialRecord:()=>Yq,parseAsync:()=>b1,parse:()=>g1,overwrite:()=>fU,optional:()=>l8,object:()=>Qq,number:()=>i1,nullish:()=>Dq,nullable:()=>m8,null:()=>t1,normalize:()=>DW,nonpositive:()=>u9,nonoptional:()=>MG,nonnegative:()=>l9,never:()=>FK,negative:()=>f9,nativeEnum:()=>Zq,nanoid:()=>zI,nan:()=>Fq,multipleOf:()=>cJ,minSize:()=>WJ,minLength:()=>wJ,mime:()=>qW,meta:()=>_q,maxSize:()=>nJ,maxLength:()=>_0,map:()=>Oq,mac:()=>jI,lte:()=>RU,lt:()=>UJ,lowercase:()=>GW,looseRecord:()=>Gq,looseObject:()=>Xq,locales:()=>b8,literal:()=>Iq,length:()=>A0,lazy:()=>jG,ksuid:()=>TI,keyof:()=>Wq,jwt:()=>uI,json:()=>Sq,iso:()=>MW,ipv6:()=>gI,ipv4:()=>vI,invertCodec:()=>Rq,intersection:()=>NG,int64:()=>aI,int32:()=>iI,int:()=>t9,instanceof:()=>Aq,includes:()=>EW,httpUrl:()=>BI,hostname:()=>mI,hex:()=>pI,hash:()=>dI,guid:()=>FI,gte:()=>XU,gt:()=>JJ,globalRegistry:()=>a6,getErrorMap:()=>$R,function:()=>Mq,fromJSONSchema:()=>jq,formatError:()=>B8,float64:()=>nI,float32:()=>cI,flattenError:()=>M8,file:()=>qq,exactOptional:()=>kG,enum:()=>RK,endsWith:()=>IW,encodeAsync:()=>u1,encode:()=>h1,emoji:()=>PI,email:()=>kI,e164:()=>fI,discriminatedUnion:()=>Hq,describe:()=>zq,decodeAsync:()=>l1,decode:()=>f1,date:()=>Jq,custom:()=>Pq,cuid2:()=>AI,cuid:()=>_I,core:()=>MJ,config:()=>T6,coerce:()=>fG,codec:()=>Lq,clone:()=>QU,cidrv6:()=>xI,cidrv4:()=>bI,check:()=>Bq,catch:()=>zG,boolean:()=>o1,bigint:()=>rI,base64url:()=>hI,base64:()=>yI,array:()=>n8,any:()=>$q,_function:()=>Mq,_default:()=>RG,_ZodString:()=>$K,ZodXor:()=>QG,ZodXID:()=>NK,ZodVoid:()=>JG,ZodUnknown:()=>$G,ZodUnion:()=>o8,ZodUndefined:()=>a1,ZodUUID:()=>QJ,ZodURL:()=>d8,ZodULID:()=>XK,ZodType:()=>n$,ZodTuple:()=>HG,ZodTransform:()=>qG,ZodTemplateLiteral:()=>TG,ZodSymbol:()=>r1,ZodSuccess:()=>BG,ZodStringFormat:()=>D6,ZodString:()=>zW,ZodSet:()=>EG,ZodRecord:()=>BW,ZodRealError:()=>IU,ZodReadonly:()=>CG,ZodPromise:()=>gG,ZodPreprocess:()=>AG,ZodPrefault:()=>VG,ZodPipe:()=>r8,ZodOptional:()=>wK,ZodObject:()=>i8,ZodNumberFormat:()=>S0,ZodNumber:()=>AW,ZodNullable:()=>FG,ZodNull:()=>s1,ZodNonOptional:()=>MK,ZodNever:()=>UG,ZodNanoID:()=>WK,ZodNaN:()=>_G,ZodMap:()=>OG,ZodMAC:()=>n1,ZodLiteral:()=>ZG,ZodLazy:()=>vG,ZodKSUID:()=>HK,ZodJWT:()=>DK,ZodIssueCode:()=>tL,ZodIntersection:()=>XG,ZodISOTime:()=>a9,ZodISODuration:()=>s9,ZodISODateTime:()=>o9,ZodISODate:()=>r9,ZodIPv6:()=>GK,ZodIPv4:()=>YK,ZodGUID:()=>u8,ZodFunction:()=>bG,ZodFirstPartyTypeKind:()=>hG,ZodFile:()=>IG,ZodExactOptional:()=>DG,ZodError:()=>aL,ZodEnum:()=>PW,ZodEmoji:()=>JK,ZodEmail:()=>UK,ZodE164:()=>qK,ZodDiscriminatedUnion:()=>KG,ZodDefault:()=>LG,ZodDate:()=>c8,ZodCustomStringFormat:()=>_W,ZodCustom:()=>s8,ZodCodec:()=>a8,ZodCatch:()=>PG,ZodCUID2:()=>KK,ZodCUID:()=>QK,ZodCIDRv6:()=>EK,ZodCIDRv4:()=>OK,ZodBoolean:()=>CW,ZodBigIntFormat:()=>kK,ZodBigInt:()=>SW,ZodBase64URL:()=>IK,ZodBase64:()=>ZK,ZodArray:()=>WG,ZodAny:()=>e1,TimePrecision:()=>YY,NEVER:()=>m7,$output:()=>WY,$input:()=>QY,$brand:()=>p7});var MJ={};RJ(MJ,{version:()=>sX,util:()=>Q$,treeifyError:()=>$X,toJSONSchema:()=>n9,toDotPath:()=>xZ,safeParseAsync:()=>WX,safeParse:()=>JX,safeEncodeAsync:()=>tF,safeEncode:()=>aF,safeDecodeAsync:()=>eF,safeDecode:()=>sF,registry:()=>k9,regexes:()=>LU,process:()=>O6,prettifyError:()=>UX,parseAsync:()=>rQ,parse:()=>oQ,meta:()=>pY,locales:()=>b8,isValidJWT:()=>QI,isValidBase64URL:()=>WI,isValidBase64:()=>LN,initializeContext:()=>iJ,globalRegistry:()=>a6,globalConfig:()=>V0,formatError:()=>B8,flattenError:()=>M8,finalize:()=>rJ,extractDefs:()=>oJ,encodeAsync:()=>oF,encode:()=>nF,describe:()=>mY,decodeAsync:()=>rF,decode:()=>iF,createToJSONSchemaMethod:()=>cY,createStandardJSONSchemaMethod:()=>wW,config:()=>T6,clone:()=>QU,_xor:()=>zL,_xid:()=>A9,_void:()=>jY,_uuidv7:()=>w9,_uuidv6:()=>V9,_uuidv4:()=>R9,_uuid:()=>L9,_url:()=>y8,_uppercase:()=>OW,_unknown:()=>TY,_union:()=>PL,_undefined:()=>AY,_ulid:()=>_9,_uint64:()=>zY,_uint32:()=>RY,_tuple:()=>CL,_trim:()=>kW,_transform:()=>xL,_toUpperCase:()=>LW,_toLowerCase:()=>FW,_templateLiteral:()=>cL,_symbol:()=>_Y,_superRefine:()=>lY,_success:()=>lL,_stringbool:()=>dY,_stringFormat:()=>VW,_string:()=>XY,_startsWith:()=>ZW,_slugify:()=>RW,_size:()=>z0,_set:()=>vL,_safeParseAsync:()=>XW,_safeParse:()=>KW,_safeEncodeAsync:()=>J9,_safeEncode:()=>$9,_safeDecodeAsync:()=>W9,_safeDecode:()=>U9,_regex:()=>YW,_refine:()=>uY,_record:()=>SL,_readonly:()=>dL,_property:()=>m9,_promise:()=>iL,_positive:()=>h9,_pipe:()=>pL,_parseAsync:()=>QW,_parse:()=>WW,_overwrite:()=>fU,_optional:()=>yL,_number:()=>IY,_nullable:()=>hL,_null:()=>CY,_normalize:()=>DW,_nonpositive:()=>u9,_nonoptional:()=>uL,_nonnegative:()=>l9,_never:()=>vY,_negative:()=>f9,_nativeEnum:()=>gL,_nanoid:()=>B9,_nan:()=>xY,_multipleOf:()=>cJ,_minSize:()=>WJ,_minLength:()=>wJ,_min:()=>XU,_mime:()=>qW,_maxSize:()=>nJ,_maxLength:()=>_0,_max:()=>RU,_map:()=>TL,_mac:()=>HY,_lte:()=>RU,_lt:()=>UJ,_lowercase:()=>GW,_literal:()=>bL,_length:()=>A0,_lazy:()=>nL,_ksuid:()=>C9,_jwt:()=>y9,_isoTime:()=>EY,_isoDuration:()=>ZY,_isoDateTime:()=>GY,_isoDate:()=>OY,_ipv6:()=>T9,_ipv4:()=>S9,_intersection:()=>AL,_int64:()=>PY,_int32:()=>LY,_int:()=>DY,_includes:()=>EW,_guid:()=>x8,_gte:()=>XU,_gt:()=>JJ,_float64:()=>FY,_float32:()=>kY,_file:()=>hY,_enum:()=>jL,_endsWith:()=>IW,_encodeAsync:()=>tQ,_encode:()=>aQ,_emoji:()=>M9,_email:()=>F9,_e164:()=>x9,_discriminatedUnion:()=>_L,_default:()=>fL,_decodeAsync:()=>eQ,_decode:()=>sQ,_date:()=>gY,_custom:()=>fY,_cuid2:()=>z9,_cuid:()=>P9,_coercedString:()=>NY,_coercedNumber:()=>qY,_coercedDate:()=>bY,_coercedBoolean:()=>wY,_coercedBigint:()=>BY,_cidrv6:()=>j9,_cidrv4:()=>v9,_check:()=>ZI,_catch:()=>mL,_boolean:()=>VY,_bigint:()=>MY,_base64url:()=>b9,_base64:()=>g9,_array:()=>yY,_any:()=>SY,TimePrecision:()=>YY,NEVER:()=>m7,JSONSchemaGenerator:()=>C1,JSONSchema:()=>II,Doc:()=>N9,$output:()=>WY,$input:()=>QY,$constructor:()=>g,$brand:()=>p7,$ZodXor:()=>yN,$ZodXID:()=>HN,$ZodVoid:()=>jN,$ZodUnknown:()=>TN,$ZodUnion:()=>C8,$ZodUndefined:()=>AN,$ZodUUID:()=>$N,$ZodURL:()=>JN,$ZodULID:()=>NN,$ZodType:()=>h$,$ZodTuple:()=>I9,$ZodTransform:()=>nN,$ZodTemplateLiteral:()=>WH,$ZodSymbol:()=>_N,$ZodSuccess:()=>tN,$ZodStringFormat:()=>q6,$ZodString:()=>P0,$ZodSet:()=>mN,$ZodRegistry:()=>KY,$ZodRecord:()=>uN,$ZodRealError:()=>ZU,$ZodReadonly:()=>JH,$ZodPromise:()=>KH,$ZodPreprocess:()=>UH,$ZodPrefault:()=>aN,$ZodPipe:()=>D9,$ZodOptional:()=>q9,$ZodObjectJIT:()=>xN,$ZodObject:()=>NI,$ZodNumberFormat:()=>PN,$ZodNumber:()=>E9,$ZodNullable:()=>oN,$ZodNull:()=>CN,$ZodNonOptional:()=>sN,$ZodNever:()=>vN,$ZodNanoID:()=>QN,$ZodNaN:()=>$H,$ZodMap:()=>lN,$ZodMAC:()=>DN,$ZodLiteral:()=>dN,$ZodLazy:()=>XH,$ZodKSUID:()=>YN,$ZodJWT:()=>MN,$ZodIntersection:()=>fN,$ZodISOTime:()=>EN,$ZodISODuration:()=>ZN,$ZodISODateTime:()=>GN,$ZodISODate:()=>ON,$ZodIPv6:()=>qN,$ZodIPv4:()=>IN,$ZodGUID:()=>eX,$ZodFunction:()=>QH,$ZodFile:()=>cN,$ZodExactOptional:()=>iN,$ZodError:()=>w8,$ZodEnum:()=>pN,$ZodEncodeError:()=>w0,$ZodEmoji:()=>WN,$ZodEmail:()=>UN,$ZodE164:()=>wN,$ZodDiscriminatedUnion:()=>hN,$ZodDefault:()=>rN,$ZodDate:()=>gN,$ZodCustomStringFormat:()=>BN,$ZodCustom:()=>NH,$ZodCodec:()=>S8,$ZodCheckUpperCase:()=>dX,$ZodCheckStringFormat:()=>NW,$ZodCheckStartsWith:()=>nX,$ZodCheckSizeEquals:()=>hX,$ZodCheckRegex:()=>mX,$ZodCheckProperty:()=>oX,$ZodCheckOverwrite:()=>aX,$ZodCheckNumberFormat:()=>gX,$ZodCheckMultipleOf:()=>jX,$ZodCheckMinSize:()=>yX,$ZodCheckMinLength:()=>uX,$ZodCheckMimeType:()=>rX,$ZodCheckMaxSize:()=>xX,$ZodCheckMaxLength:()=>fX,$ZodCheckLowerCase:()=>pX,$ZodCheckLessThan:()=>K9,$ZodCheckLengthEquals:()=>lX,$ZodCheckIncludes:()=>cX,$ZodCheckGreaterThan:()=>X9,$ZodCheckEndsWith:()=>iX,$ZodCheckBigIntFormat:()=>bX,$ZodCheck:()=>V6,$ZodCatch:()=>eN,$ZodCUID2:()=>XN,$ZodCUID:()=>KN,$ZodCIDRv6:()=>FN,$ZodCIDRv4:()=>kN,$ZodBoolean:()=>A8,$ZodBigIntFormat:()=>zN,$ZodBigInt:()=>Z9,$ZodBase64URL:()=>VN,$ZodBase64:()=>RN,$ZodAsyncError:()=>$J,$ZodArray:()=>bN,$ZodAny:()=>SN});var SZ,m7=Object.freeze({status:"aborted"});function g($,U,J){function Q(N,H){if(!N._zod)Object.defineProperty(N,"_zod",{value:{def:H,constr:X,traits:new Set},enumerable:!1});if(N._zod.traits.has($))return;N._zod.traits.add($),U(N,H);let Y=X.prototype,G=Object.keys(Y);for(let O=0;O<G.length;O++){let E=G[O];if(!(E in N))N[E]=Y[E].bind(N)}}let W=J?.Parent??Object;class K extends W{}Object.defineProperty(K,"name",{value:$});function X(N){var H;let Y=J?.Parent?new K:this;Q(Y,N),(H=Y._zod).deferred??(H.deferred=[]);for(let G of Y._zod.deferred)G();return Y}return Object.defineProperty(X,"init",{value:Q}),Object.defineProperty(X,Symbol.hasInstance,{value:(N)=>{if(J?.Parent&&N instanceof J.Parent)return!0;return N?._zod?.traits?.has($)}}),Object.defineProperty(X,"name",{value:$}),X}var p7=Symbol("zod_brand");class $J extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class w0 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}(SZ=globalThis).__zod_globalConfig??(SZ.__zod_globalConfig={});var V0=globalThis.__zod_globalConfig;function T6($){if($)Object.assign(V0,$);return V0}var Q$={};RJ(Q$,{unwrapMessage:()=>D8,uint8ArrayToHex:()=>dF,uint8ArrayToBase64url:()=>mF,uint8ArrayToBase64:()=>jZ,stringifyPrimitive:()=>U$,slugify:()=>n7,shallowClone:()=>o7,safeExtend:()=>xF,required:()=>fF,randomString:()=>CF,propertyKeyTypes:()=>L8,promiseAllObject:()=>AF,primitiveTypes:()=>r7,prefixIssues:()=>EU,pick:()=>jF,partial:()=>hF,parsedType:()=>W$,optionalKeys:()=>a7,omit:()=>gF,objectClone:()=>PF,numKeys:()=>SF,nullish:()=>lJ,normalizeParams:()=>K$,mergeDefs:()=>VJ,merge:()=>yF,jsonStringifyReplacer:()=>$W,joinValues:()=>m,issue:()=>JW,isPlainObject:()=>pJ,isObject:()=>M0,hexToUint8Array:()=>pF,getSizableOrigin:()=>R8,getParsedType:()=>TF,getLengthableOrigin:()=>V8,getEnumValues:()=>k8,getElementAtPath:()=>_F,floatSafeRemainder:()=>c7,finalizeIssue:()=>KU,extend:()=>bF,explicitlyAborted:()=>e7,escapeRegex:()=>vU,esc:()=>nQ,defineLazy:()=>a$,createTransparentProxy:()=>vF,cloneDef:()=>zF,clone:()=>QU,cleanRegex:()=>F8,cleanEnum:()=>uF,captureStackTrace:()=>iQ,cached:()=>UW,base64urlToUint8Array:()=>lF,base64ToUint8Array:()=>vZ,assignProp:()=>mJ,assertNotEqual:()=>VF,assertNever:()=>MF,assertIs:()=>wF,assertEqual:()=>RF,assert:()=>BF,allowsEval:()=>i7,aborted:()=>dJ,NUMBER_FORMAT_RANGES:()=>s7,Class:()=>gZ,BIGINT_FORMAT_RANGES:()=>t7});function RF($){return $}function VF($){return $}function wF($){}function MF($){throw Error("Unexpected value in exhaustive check")}function BF($){}function k8($){let U=Object.values($).filter((Q)=>typeof Q==="number");return Object.entries($).filter(([Q,W])=>U.indexOf(+Q)===-1).map(([Q,W])=>W)}function m($,U="|"){return $.map((J)=>U$(J)).join(U)}function $W($,U){if(typeof U==="bigint")return U.toString();return U}function UW($){return{get value(){{let J=$();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function lJ($){return $===null||$===void 0}function F8($){let U=$.startsWith("^")?1:0,J=$.endsWith("$")?$.length-1:$.length;return $.slice(U,J)}function c7($,U){let J=$/U,Q=Math.round(J),W=Number.EPSILON*Math.max(Math.abs(J),1);if(Math.abs(J-Q)<W)return 0;return J-Q}var TZ=Symbol("evaluating");function a$($,U,J){let Q=void 0;Object.defineProperty($,U,{get(){if(Q===TZ)return;if(Q===void 0)Q=TZ,Q=J();return Q},set(W){Object.defineProperty($,U,{value:W})},configurable:!0})}function PF($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function mJ($,U,J){Object.defineProperty($,U,{value:J,writable:!0,enumerable:!0,configurable:!0})}function VJ(...$){let U={};for(let J of $){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(U,Q)}return Object.defineProperties({},U)}function zF($){return VJ($._zod.def)}function _F($,U){if(!U)return $;return U.reduce((J,Q)=>J?.[Q],$)}function AF($){let U=Object.keys($),J=U.map((Q)=>$[Q]);return Promise.all(J).then((Q)=>{let W={};for(let K=0;K<U.length;K++)W[U[K]]=Q[K];return W})}function CF($=10){let J="";for(let Q=0;Q<$;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function nQ($){return JSON.stringify($)}function n7($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var iQ="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function M0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var i7=UW(()=>{if(V0.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function pJ($){if(M0($)===!1)return!1;let U=$.constructor;if(U===void 0)return!0;if(typeof U!=="function")return!0;let J=U.prototype;if(M0(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function o7($){if(pJ($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function SF($){let U=0;for(let J in $)if(Object.prototype.hasOwnProperty.call($,J))U++;return U}var TF=($)=>{let U=typeof $;switch(U){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${U}`)}},L8=new Set(["string","number","symbol"]),r7=new Set(["string","number","bigint","boolean","symbol","undefined"]);function vU($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function QU($,U,J){let Q=new $._zod.constr(U??$._zod.def);if(!U||J?.parent)Q._zod.parent=$;return Q}function K$($){let U=$;if(!U)return{};if(typeof U==="string")return{error:()=>U};if(U?.message!==void 0){if(U?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");U.error=U.message}if(delete U.message,typeof U.error==="string")return{...U,error:()=>U.error};return U}function vF($){let U;return new Proxy({},{get(J,Q,W){return U??(U=$()),Reflect.get(U,Q,W)},set(J,Q,W,K){return U??(U=$()),Reflect.set(U,Q,W,K)},has(J,Q){return U??(U=$()),Reflect.has(U,Q)},deleteProperty(J,Q){return U??(U=$()),Reflect.deleteProperty(U,Q)},ownKeys(J){return U??(U=$()),Reflect.ownKeys(U)},getOwnPropertyDescriptor(J,Q){return U??(U=$()),Reflect.getOwnPropertyDescriptor(U,Q)},defineProperty(J,Q,W){return U??(U=$()),Reflect.defineProperty(U,Q,W)}})}function U$($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function a7($){return Object.keys($).filter((U)=>{return $[U]._zod.optin==="optional"&&$[U]._zod.optout==="optional"})}var s7={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},t7={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function jF($,U){let J=$._zod.def,Q=J.checks;if(Q&&Q.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let K=VJ($._zod.def,{get shape(){let X={};for(let N in U){if(!(N in J.shape))throw Error(`Unrecognized key: "${N}"`);if(!U[N])continue;X[N]=J.shape[N]}return mJ(this,"shape",X),X},checks:[]});return QU($,K)}function gF($,U){let J=$._zod.def,Q=J.checks;if(Q&&Q.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let K=VJ($._zod.def,{get shape(){let X={...$._zod.def.shape};for(let N in U){if(!(N in J.shape))throw Error(`Unrecognized key: "${N}"`);if(!U[N])continue;delete X[N]}return mJ(this,"shape",X),X},checks:[]});return QU($,K)}function bF($,U){if(!pJ(U))throw Error("Invalid input to extend: expected a plain object");let J=$._zod.def.checks;if(J&&J.length>0){let K=$._zod.def.shape;for(let X in U)if(Object.getOwnPropertyDescriptor(K,X)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let W=VJ($._zod.def,{get shape(){let K={...$._zod.def.shape,...U};return mJ(this,"shape",K),K}});return QU($,W)}function xF($,U){if(!pJ(U))throw Error("Invalid input to safeExtend: expected a plain object");let J=VJ($._zod.def,{get shape(){let Q={...$._zod.def.shape,...U};return mJ(this,"shape",Q),Q}});return QU($,J)}function yF($,U){if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let J=VJ($._zod.def,{get shape(){let Q={...$._zod.def.shape,...U._zod.def.shape};return mJ(this,"shape",Q),Q},get catchall(){return U._zod.def.catchall},checks:U._zod.def.checks??[]});return QU($,J)}function hF($,U,J){let W=U._zod.def.checks;if(W&&W.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let X=VJ(U._zod.def,{get shape(){let N=U._zod.def.shape,H={...N};if(J)for(let Y in J){if(!(Y in N))throw Error(`Unrecognized key: "${Y}"`);if(!J[Y])continue;H[Y]=$?new $({type:"optional",innerType:N[Y]}):N[Y]}else for(let Y in N)H[Y]=$?new $({type:"optional",innerType:N[Y]}):N[Y];return mJ(this,"shape",H),H},checks:[]});return QU(U,X)}function fF($,U,J){let Q=VJ(U._zod.def,{get shape(){let W=U._zod.def.shape,K={...W};if(J)for(let X in J){if(!(X in K))throw Error(`Unrecognized key: "${X}"`);if(!J[X])continue;K[X]=new $({type:"nonoptional",innerType:W[X]})}else for(let X in W)K[X]=new $({type:"nonoptional",innerType:W[X]});return mJ(this,"shape",K),K}});return QU(U,Q)}function dJ($,U=0){if($.aborted===!0)return!0;for(let J=U;J<$.issues.length;J++)if($.issues[J]?.continue!==!0)return!0;return!1}function e7($,U=0){if($.aborted===!0)return!0;for(let J=U;J<$.issues.length;J++)if($.issues[J]?.continue===!1)return!0;return!1}function EU($,U){return U.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift($),J})}function D8($){return typeof $==="string"?$:$?.message}function KU($,U,J){let Q=$.message?$.message:D8($.inst?._zod.def?.error?.($))??D8(U?.error?.($))??D8(J.customError?.($))??D8(J.localeError?.($))??"Invalid input",{inst:W,continue:K,input:X,...N}=$;if(N.path??(N.path=[]),N.message=Q,U?.reportInput)N.input=X;return N}function R8($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function V8($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function W$($){let U=typeof $;switch(U){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let J=$;if(J&&Object.getPrototypeOf(J)!==Object.prototype&&"constructor"in J&&J.constructor)return J.constructor.name}}return U}function JW(...$){let[U,J,Q]=$;if(typeof U==="string")return{message:U,code:"custom",input:J,inst:Q};return{...U}}function uF($){return Object.entries($).filter(([U,J])=>{return Number.isNaN(Number.parseInt(U,10))}).map((U)=>U[1])}function vZ($){let U=atob($),J=new Uint8Array(U.length);for(let Q=0;Q<U.length;Q++)J[Q]=U.charCodeAt(Q);return J}function jZ($){let U="";for(let J=0;J<$.length;J++)U+=String.fromCharCode($[J]);return btoa(U)}function lF($){let U=$.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-U.length%4)%4);return vZ(U+J)}function mF($){return jZ($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function pF($){let U=$.replace(/^0x/,"");if(U.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(U.length/2);for(let Q=0;Q<U.length;Q+=2)J[Q/2]=Number.parseInt(U.slice(Q,Q+2),16);return J}function dF($){return Array.from($).map((U)=>U.toString(16).padStart(2,"0")).join("")}class gZ{constructor(...$){}}var bZ=($,U)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:U,enumerable:!1}),$.message=JSON.stringify(U,$W,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},w8=g("$ZodError",bZ),ZU=g("$ZodError",bZ,{Parent:Error});function M8($,U=(J)=>J.message){let J={},Q=[];for(let W of $.issues)if(W.path.length>0)J[W.path[0]]=J[W.path[0]]||[],J[W.path[0]].push(U(W));else Q.push(U(W));return{formErrors:Q,fieldErrors:J}}function B8($,U=(J)=>J.message){let J={_errors:[]},Q=(W,K=[])=>{for(let X of W.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((N)=>Q({issues:N},[...K,...X.path]));else if(X.code==="invalid_key")Q({issues:X.issues},[...K,...X.path]);else if(X.code==="invalid_element")Q({issues:X.issues},[...K,...X.path]);else{let N=[...K,...X.path];if(N.length===0)J._errors.push(U(X));else{let H=J,Y=0;while(Y<N.length){let G=N[Y];if(Y!==N.length-1)H[G]=H[G]||{_errors:[]};else H[G]=H[G]||{_errors:[]},H[G]._errors.push(U(X));H=H[G],Y++}}}};return Q($),J}function $X($,U=(J)=>J.message){let J={errors:[]},Q=(W,K=[])=>{var X,N;for(let H of W.issues)if(H.code==="invalid_union"&&H.errors.length)H.errors.map((Y)=>Q({issues:Y},[...K,...H.path]));else if(H.code==="invalid_key")Q({issues:H.issues},[...K,...H.path]);else if(H.code==="invalid_element")Q({issues:H.issues},[...K,...H.path]);else{let Y=[...K,...H.path];if(Y.length===0){J.errors.push(U(H));continue}let G=J,O=0;while(O<Y.length){let E=Y[O],Z=O===Y.length-1;if(typeof E==="string")G.properties??(G.properties={}),(X=G.properties)[E]??(X[E]={errors:[]}),G=G.properties[E];else G.items??(G.items=[]),(N=G.items)[E]??(N[E]={errors:[]}),G=G.items[E];if(Z)G.errors.push(U(H));O++}}};return Q($),J}function xZ($){let U=[],J=$.map((Q)=>typeof Q==="object"?Q.key:Q);for(let Q of J)if(typeof Q==="number")U.push(`[${Q}]`);else if(typeof Q==="symbol")U.push(`[${JSON.stringify(String(Q))}]`);else if(/[^\w$]/.test(Q))U.push(`[${JSON.stringify(Q)}]`);else{if(U.length)U.push(".");U.push(Q)}return U.join("")}function UX($){let U=[],J=[...$.issues].sort((Q,W)=>(Q.path??[]).length-(W.path??[]).length);for(let Q of J)if(U.push(`✖ ${Q.message}`),Q.path?.length)U.push(` → at ${xZ(Q.path)}`);return U.join(`-`)}var WW=($)=>(U,J,Q,W)=>{let K=Q?{...Q,async:!1}:{async:!1},X=U._zod.run({value:J,issues:[]},K);if(X instanceof Promise)throw new $J;if(X.issues.length){let N=new(W?.Err??$)(X.issues.map((H)=>KU(H,K,T6())));throw iQ(N,W?.callee),N}return X.value},oQ=WW(ZU),QW=($)=>async(U,J,Q,W)=>{let K=Q?{...Q,async:!0}:{async:!0},X=U._zod.run({value:J,issues:[]},K);if(X instanceof Promise)X=await X;if(X.issues.length){let N=new(W?.Err??$)(X.issues.map((H)=>KU(H,K,T6())));throw iQ(N,W?.callee),N}return X.value},rQ=QW(ZU),KW=($)=>(U,J,Q)=>{let W=Q?{...Q,async:!1}:{async:!1},K=U._zod.run({value:J,issues:[]},W);if(K instanceof Promise)throw new $J;return K.issues.length?{success:!1,error:new($??w8)(K.issues.map((X)=>KU(X,W,T6())))}:{success:!0,data:K.value}},JX=KW(ZU),XW=($)=>async(U,J,Q)=>{let W=Q?{...Q,async:!0}:{async:!0},K=U._zod.run({value:J,issues:[]},W);if(K instanceof Promise)K=await K;return K.issues.length?{success:!1,error:new $(K.issues.map((X)=>KU(X,W,T6())))}:{success:!0,data:K.value}},WX=XW(ZU),aQ=($)=>(U,J,Q)=>{let W=Q?{...Q,direction:"backward"}:{direction:"backward"};return WW($)(U,J,W)},nF=aQ(ZU),sQ=($)=>(U,J,Q)=>{return WW($)(U,J,Q)},iF=sQ(ZU),tQ=($)=>async(U,J,Q)=>{let W=Q?{...Q,direction:"backward"}:{direction:"backward"};return QW($)(U,J,W)},oF=tQ(ZU),eQ=($)=>async(U,J,Q)=>{return QW($)(U,J,Q)},rF=eQ(ZU),$9=($)=>(U,J,Q)=>{let W=Q?{...Q,direction:"backward"}:{direction:"backward"};return KW($)(U,J,W)},aF=$9(ZU),U9=($)=>(U,J,Q)=>{return KW($)(U,J,Q)},sF=U9(ZU),J9=($)=>async(U,J,Q)=>{let W=Q?{...Q,direction:"backward"}:{direction:"backward"};return XW($)(U,J,W)},tF=J9(ZU),W9=($)=>async(U,J,Q)=>{return XW($)(U,J,Q)},eF=W9(ZU);var LU={};RJ(LU,{xid:()=>NX,uuid7:()=>W4,uuid6:()=>J4,uuid4:()=>U4,uuid:()=>B0,uppercase:()=>vX,unicodeEmail:()=>yZ,undefined:()=>SX,ulid:()=>XX,time:()=>MX,string:()=>PX,sha512_hex:()=>B4,sha512_base64url:()=>z4,sha512_base64:()=>P4,sha384_hex:()=>V4,sha384_base64url:()=>M4,sha384_base64:()=>w4,sha256_hex:()=>F4,sha256_base64url:()=>R4,sha256_base64:()=>L4,sha1_hex:()=>q4,sha1_base64url:()=>k4,sha1_base64:()=>D4,rfc5322Email:()=>K4,number:()=>P8,null:()=>CX,nanoid:()=>YX,md5_hex:()=>E4,md5_base64url:()=>I4,md5_base64:()=>Z4,mac:()=>DX,lowercase:()=>TX,ksuid:()=>HX,ipv6:()=>qX,ipv4:()=>IX,integer:()=>_X,idnEmail:()=>X4,httpProtocol:()=>RX,html5Email:()=>Q4,hostname:()=>Y4,hex:()=>O4,guid:()=>OX,extendedDuration:()=>$4,emoji:()=>ZX,email:()=>EX,e164:()=>VX,duration:()=>GX,domain:()=>G4,datetime:()=>BX,date:()=>wX,cuid2:()=>KX,cuid:()=>QX,cidrv6:()=>FX,cidrv4:()=>kX,browserEmail:()=>N4,boolean:()=>AX,bigint:()=>zX,base64url:()=>Q9,base64:()=>LX});var QX=/^[cC][0-9a-z]{6,}$/,KX=/^[0-9a-z]+$/,XX=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,NX=/^[0-9a-vA-V]{20}$/,HX=/^[A-Za-z0-9]{27}$/,YX=/^[a-zA-Z0-9_-]{21}$/,GX=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,$4=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,OX=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,B0=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},U4=B0(4),J4=B0(6),W4=B0(7),EX=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Q4=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,K4=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,yZ=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,X4=yZ,N4=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,H4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ZX(){return new RegExp(H4,"u")}var IX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qX=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,DX=($)=>{let U=vU($??":");return new RegExp(`^(?:[0-9A-F]{2}${U}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${U}){5}[0-9a-f]{2}$`)},kX=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,FX=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,LX=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Q9=/^[A-Za-z0-9_-]*$/,Y4=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,G4=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,RX=/^https?$/,VX=/^\+[1-9]\d{6,14}$/,hZ="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",wX=new RegExp(`^${hZ}$`);function fZ($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function MX($){return new RegExp(`^${fZ($)}$`)}function BX($){let U=fZ({precision:$.precision}),J=["Z"];if($.local)J.push("");if($.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${U}(?:${J.join("|")})`;return new RegExp(`^${hZ}T(?:${Q})$`)}var PX=($)=>{let U=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${U}$`)},zX=/^-?\d+n?$/,_X=/^-?\d+$/,P8=/^-?\d+(?:\.\d+)?$/,AX=/^(?:true|false)$/i,CX=/^null$/i;var SX=/^undefined$/i;var TX=/^[^A-Z]*$/,vX=/^[^a-z]*$/,O4=/^[0-9a-fA-F]*$/;function z8($,U){return new RegExp(`^[A-Za-z0-9+/]{${$}}${U}$`)}function _8($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var E4=/^[0-9a-fA-F]{32}$/,Z4=z8(22,"=="),I4=_8(22),q4=/^[0-9a-fA-F]{40}$/,D4=z8(27,"="),k4=_8(27),F4=/^[0-9a-fA-F]{64}$/,L4=z8(43,"="),R4=_8(43),V4=/^[0-9a-fA-F]{96}$/,w4=z8(64,""),M4=_8(64),B4=/^[0-9a-fA-F]{128}$/,P4=z8(86,"=="),z4=_8(86);var V6=g("$ZodCheck",($,U)=>{var J;$._zod??($._zod={}),$._zod.def=U,(J=$._zod).onattach??(J.onattach=[])}),lZ={number:"number",bigint:"bigint",object:"date"},K9=g("$ZodCheckLessThan",($,U)=>{V6.init($,U);let J=lZ[typeof U.value];$._zod.onattach.push((Q)=>{let W=Q._zod.bag,K=(U.inclusive?W.maximum:W.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(U.value<K)if(U.inclusive)W.maximum=U.value;else W.exclusiveMaximum=U.value}),$._zod.check=(Q)=>{if(U.inclusive?Q.value<=U.value:Q.value<U.value)return;Q.issues.push({origin:J,code:"too_big",maximum:typeof U.value==="object"?U.value.getTime():U.value,input:Q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),X9=g("$ZodCheckGreaterThan",($,U)=>{V6.init($,U);let J=lZ[typeof U.value];$._zod.onattach.push((Q)=>{let W=Q._zod.bag,K=(U.inclusive?W.minimum:W.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(U.value>K)if(U.inclusive)W.minimum=U.value;else W.exclusiveMinimum=U.value}),$._zod.check=(Q)=>{if(U.inclusive?Q.value>=U.value:Q.value>U.value)return;Q.issues.push({origin:J,code:"too_small",minimum:typeof U.value==="object"?U.value.getTime():U.value,input:Q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),jX=g("$ZodCheckMultipleOf",($,U)=>{V6.init($,U),$._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=U.value)}),$._zod.check=(J)=>{if(typeof J.value!==typeof U.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%U.value===BigInt(0):c7(J.value,U.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:U.value,input:J.value,inst:$,continue:!U.abort})}}),gX=g("$ZodCheckNumberFormat",($,U)=>{V6.init($,U),U.format=U.format||"float64";let J=U.format?.includes("int"),Q=J?"int":"number",[W,K]=s7[U.format];$._zod.onattach.push((X)=>{let N=X._zod.bag;if(N.format=U.format,N.minimum=W,N.maximum=K,J)N.pattern=_X}),$._zod.check=(X)=>{let N=X.value;if(J){if(!Number.isInteger(N)){X.issues.push({expected:Q,format:U.format,code:"invalid_type",continue:!1,input:N,inst:$});return}if(!Number.isSafeInteger(N)){if(N>0)X.issues.push({input:N,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:Q,inclusive:!0,continue:!U.abort});else X.issues.push({input:N,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:Q,inclusive:!0,continue:!U.abort});return}}if(N<W)X.issues.push({origin:"number",input:N,code:"too_small",minimum:W,inclusive:!0,inst:$,continue:!U.abort});if(N>K)X.issues.push({origin:"number",input:N,code:"too_big",maximum:K,inclusive:!0,inst:$,continue:!U.abort})}}),bX=g("$ZodCheckBigIntFormat",($,U)=>{V6.init($,U);let[J,Q]=t7[U.format];$._zod.onattach.push((W)=>{let K=W._zod.bag;K.format=U.format,K.minimum=J,K.maximum=Q}),$._zod.check=(W)=>{let K=W.value;if(K<J)W.issues.push({origin:"bigint",input:K,code:"too_small",minimum:J,inclusive:!0,inst:$,continue:!U.abort});if(K>Q)W.issues.push({origin:"bigint",input:K,code:"too_big",maximum:Q,inclusive:!0,inst:$,continue:!U.abort})}}),xX=g("$ZodCheckMaxSize",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!lJ(W)&&W.size!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<W)Q._zod.bag.maximum=U.maximum}),$._zod.check=(Q)=>{let W=Q.value;if(W.size<=U.maximum)return;Q.issues.push({origin:R8(W),code:"too_big",maximum:U.maximum,inclusive:!0,input:W,inst:$,continue:!U.abort})}}),yX=g("$ZodCheckMinSize",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!lJ(W)&&W.size!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>W)Q._zod.bag.minimum=U.minimum}),$._zod.check=(Q)=>{let W=Q.value;if(W.size>=U.minimum)return;Q.issues.push({origin:R8(W),code:"too_small",minimum:U.minimum,inclusive:!0,input:W,inst:$,continue:!U.abort})}}),hX=g("$ZodCheckSizeEquals",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!lJ(W)&&W.size!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.minimum=U.size,W.maximum=U.size,W.size=U.size}),$._zod.check=(Q)=>{let W=Q.value,K=W.size;if(K===U.size)return;let X=K>U.size;Q.issues.push({origin:R8(W),...X?{code:"too_big",maximum:U.size}:{code:"too_small",minimum:U.size},inclusive:!0,exact:!0,input:Q.value,inst:$,continue:!U.abort})}}),fX=g("$ZodCheckMaxLength",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!lJ(W)&&W.length!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<W)Q._zod.bag.maximum=U.maximum}),$._zod.check=(Q)=>{let W=Q.value;if(W.length<=U.maximum)return;let X=V8(W);Q.issues.push({origin:X,code:"too_big",maximum:U.maximum,inclusive:!0,input:W,inst:$,continue:!U.abort})}}),uX=g("$ZodCheckMinLength",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!lJ(W)&&W.length!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>W)Q._zod.bag.minimum=U.minimum}),$._zod.check=(Q)=>{let W=Q.value;if(W.length>=U.minimum)return;let X=V8(W);Q.issues.push({origin:X,code:"too_small",minimum:U.minimum,inclusive:!0,input:W,inst:$,continue:!U.abort})}}),lX=g("$ZodCheckLengthEquals",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!lJ(W)&&W.length!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.minimum=U.length,W.maximum=U.length,W.length=U.length}),$._zod.check=(Q)=>{let W=Q.value,K=W.length;if(K===U.length)return;let X=V8(W),N=K>U.length;Q.issues.push({origin:X,...N?{code:"too_big",maximum:U.length}:{code:"too_small",minimum:U.length},inclusive:!0,exact:!0,input:Q.value,inst:$,continue:!U.abort})}}),NW=g("$ZodCheckStringFormat",($,U)=>{var J,Q;if(V6.init($,U),$._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=U.format,U.pattern)K.patterns??(K.patterns=new Set),K.patterns.add(U.pattern)}),U.pattern)(J=$._zod).check??(J.check=(W)=>{if(U.pattern.lastIndex=0,U.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:U.format,input:W.value,...U.pattern?{pattern:U.pattern.toString()}:{},inst:$,continue:!U.abort})});else(Q=$._zod).check??(Q.check=()=>{})}),mX=g("$ZodCheckRegex",($,U)=>{NW.init($,U),$._zod.check=(J)=>{if(U.pattern.lastIndex=0,U.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:U.pattern.toString(),inst:$,continue:!U.abort})}}),pX=g("$ZodCheckLowerCase",($,U)=>{U.pattern??(U.pattern=TX),NW.init($,U)}),dX=g("$ZodCheckUpperCase",($,U)=>{U.pattern??(U.pattern=vX),NW.init($,U)}),cX=g("$ZodCheckIncludes",($,U)=>{V6.init($,U);let J=vU(U.includes),Q=new RegExp(typeof U.position==="number"?`^.{${U.position}}${J}`:J);U.pattern=Q,$._zod.onattach.push((W)=>{let K=W._zod.bag;K.patterns??(K.patterns=new Set),K.patterns.add(Q)}),$._zod.check=(W)=>{if(W.value.includes(U.includes,U.position))return;W.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:U.includes,input:W.value,inst:$,continue:!U.abort})}}),nX=g("$ZodCheckStartsWith",($,U)=>{V6.init($,U);let J=new RegExp(`^${vU(U.prefix)}.*`);U.pattern??(U.pattern=J),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(Q)=>{if(Q.value.startsWith(U.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:U.prefix,input:Q.value,inst:$,continue:!U.abort})}}),iX=g("$ZodCheckEndsWith",($,U)=>{V6.init($,U);let J=new RegExp(`.*${vU(U.suffix)}$`);U.pattern??(U.pattern=J),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(Q)=>{if(Q.value.endsWith(U.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:U.suffix,input:Q.value,inst:$,continue:!U.abort})}});function uZ($,U,J){if($.issues.length)U.issues.push(...EU(J,$.issues))}var oX=g("$ZodCheckProperty",($,U)=>{V6.init($,U),$._zod.check=(J)=>{let Q=U.schema._zod.run({value:J.value[U.property],issues:[]},{});if(Q instanceof Promise)return Q.then((W)=>uZ(W,J,U.property));uZ(Q,J,U.property);return}}),rX=g("$ZodCheckMimeType",($,U)=>{V6.init($,U);let J=new Set(U.mime);$._zod.onattach.push((Q)=>{Q._zod.bag.mime=U.mime}),$._zod.check=(Q)=>{if(J.has(Q.value.type))return;Q.issues.push({code:"invalid_value",values:U.mime,input:Q.value.type,inst:$,continue:!U.abort})}}),aX=g("$ZodCheckOverwrite",($,U)=>{V6.init($,U),$._zod.check=(J)=>{J.value=U.tx(J.value)}});class N9{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let J=$.split(`-`).filter((K)=>K),Q=Math.min(...J.map((K)=>K.length-K.trimStart().length)),W=J.map((K)=>K.slice(Q)).map((K)=>" ".repeat(this.indent*2)+K);for(let K of W)this.content.push(K)}compile(){let $=Function,U=this?.args,Q=[...(this?.content??[""]).map((W)=>` ${W}`)];return new $(...U,Q.join(`-`))}}var sX={major:4,minor:4,patch:3};var h$=g("$ZodType",($,U)=>{var J;$??($={}),$._zod.def=U,$._zod.bag=$._zod.bag||{},$._zod.version=sX;let Q=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))Q.unshift($);for(let W of Q)for(let K of W._zod.onattach)K($);if(Q.length===0)(J=$._zod).deferred??(J.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let W=(X,N,H)=>{let Y=dJ(X),G;for(let O of N){if(O._zod.def.when){if(e7(X))continue;if(!O._zod.def.when(X))continue}else if(Y)continue;let E=X.issues.length,Z=O._zod.check(X);if(Z instanceof Promise&&H?.async===!1)throw new $J;if(G||Z instanceof Promise)G=(G??Promise.resolve()).then(async()=>{if(await Z,X.issues.length===E)return;if(!Y)Y=dJ(X,E)});else{if(X.issues.length===E)continue;if(!Y)Y=dJ(X,E)}}if(G)return G.then(()=>{return X});return X},K=(X,N,H)=>{if(dJ(X))return X.aborted=!0,X;let Y=W(N,Q,H);if(Y instanceof Promise){if(H.async===!1)throw new $J;return Y.then((G)=>$._zod.parse(G,H))}return $._zod.parse(Y,H)};$._zod.run=(X,N)=>{if(N.skipChecks)return $._zod.parse(X,N);if(N.direction==="backward"){let Y=$._zod.parse({value:X.value,issues:[]},{...N,skipChecks:!0});if(Y instanceof Promise)return Y.then((G)=>{return K(G,X,N)});return K(Y,X,N)}let H=$._zod.parse(X,N);if(H instanceof Promise){if(N.async===!1)throw new $J;return H.then((Y)=>W(Y,Q,N))}return W(H,Q,N)}}a$($,"~standard",()=>({validate:(W)=>{try{let K=JX($,W);return K.success?{value:K.data}:{issues:K.error?.issues}}catch(K){return WX($,W).then((X)=>X.success?{value:X.data}:{issues:X.error?.issues})}},vendor:"zod",version:1}))}),P0=g("$ZodString",($,U)=>{h$.init($,U),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??PX($._zod.bag),$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=String(J.value)}catch(W){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:$}),J}}),q6=g("$ZodStringFormat",($,U)=>{NW.init($,U),P0.init($,U)}),eX=g("$ZodGUID",($,U)=>{U.pattern??(U.pattern=OX),q6.init($,U)}),$N=g("$ZodUUID",($,U)=>{if(U.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[U.version];if(Q===void 0)throw Error(`Invalid UUID version: "${U.version}"`);U.pattern??(U.pattern=B0(Q))}else U.pattern??(U.pattern=B0());q6.init($,U)}),UN=g("$ZodEmail",($,U)=>{U.pattern??(U.pattern=EX),q6.init($,U)}),JN=g("$ZodURL",($,U)=>{q6.init($,U),$._zod.check=(J)=>{try{let Q=J.value.trim();if(!U.normalize&&U.protocol?.source===RX.source){if(!/^https?:\/\//i.test(Q)){J.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:J.value,inst:$,continue:!U.abort});return}}let W=new URL(Q);if(U.hostname){if(U.hostname.lastIndex=0,!U.hostname.test(W.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:U.hostname.source,input:J.value,inst:$,continue:!U.abort})}if(U.protocol){if(U.protocol.lastIndex=0,!U.protocol.test(W.protocol.endsWith(":")?W.protocol.slice(0,-1):W.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:U.protocol.source,input:J.value,inst:$,continue:!U.abort})}if(U.normalize)J.value=W.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:$,continue:!U.abort})}}}),WN=g("$ZodEmoji",($,U)=>{U.pattern??(U.pattern=ZX()),q6.init($,U)}),QN=g("$ZodNanoID",($,U)=>{U.pattern??(U.pattern=YX),q6.init($,U)}),KN=g("$ZodCUID",($,U)=>{U.pattern??(U.pattern=QX),q6.init($,U)}),XN=g("$ZodCUID2",($,U)=>{U.pattern??(U.pattern=KX),q6.init($,U)}),NN=g("$ZodULID",($,U)=>{U.pattern??(U.pattern=XX),q6.init($,U)}),HN=g("$ZodXID",($,U)=>{U.pattern??(U.pattern=NX),q6.init($,U)}),YN=g("$ZodKSUID",($,U)=>{U.pattern??(U.pattern=HX),q6.init($,U)}),GN=g("$ZodISODateTime",($,U)=>{U.pattern??(U.pattern=BX(U)),q6.init($,U)}),ON=g("$ZodISODate",($,U)=>{U.pattern??(U.pattern=wX),q6.init($,U)}),EN=g("$ZodISOTime",($,U)=>{U.pattern??(U.pattern=MX(U)),q6.init($,U)}),ZN=g("$ZodISODuration",($,U)=>{U.pattern??(U.pattern=GX),q6.init($,U)}),IN=g("$ZodIPv4",($,U)=>{U.pattern??(U.pattern=IX),q6.init($,U),$._zod.bag.format="ipv4"}),qN=g("$ZodIPv6",($,U)=>{U.pattern??(U.pattern=qX),q6.init($,U),$._zod.bag.format="ipv6",$._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:$,continue:!U.abort})}}}),DN=g("$ZodMAC",($,U)=>{U.pattern??(U.pattern=DX(U.delimiter)),q6.init($,U),$._zod.bag.format="mac"}),kN=g("$ZodCIDRv4",($,U)=>{U.pattern??(U.pattern=kX),q6.init($,U)}),FN=g("$ZodCIDRv6",($,U)=>{U.pattern??(U.pattern=FX),q6.init($,U),$._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[W,K]=Q;if(!K)throw Error();let X=Number(K);if(`${X}`!==K)throw Error();if(X<0||X>128)throw Error();new URL(`http://[${W}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:$,continue:!U.abort})}}});function LN($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var RN=g("$ZodBase64",($,U)=>{U.pattern??(U.pattern=LX),q6.init($,U),$._zod.bag.contentEncoding="base64",$._zod.check=(J)=>{if(LN(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:$,continue:!U.abort})}});function WI($){if(!Q9.test($))return!1;let U=$.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=U.padEnd(Math.ceil(U.length/4)*4,"=");return LN(J)}var VN=g("$ZodBase64URL",($,U)=>{U.pattern??(U.pattern=Q9),q6.init($,U),$._zod.bag.contentEncoding="base64url",$._zod.check=(J)=>{if(WI(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:$,continue:!U.abort})}}),wN=g("$ZodE164",($,U)=>{U.pattern??(U.pattern=VX),q6.init($,U)});function QI($,U=null){try{let J=$.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let W=JSON.parse(atob(Q));if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(U&&(!("alg"in W)||W.alg!==U))return!1;return!0}catch{return!1}}var MN=g("$ZodJWT",($,U)=>{q6.init($,U),$._zod.check=(J)=>{if(QI(J.value,U.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:$,continue:!U.abort})}}),BN=g("$ZodCustomStringFormat",($,U)=>{q6.init($,U),$._zod.check=(J)=>{if(U.fn(J.value))return;J.issues.push({code:"invalid_format",format:U.format,input:J.value,inst:$,continue:!U.abort})}}),E9=g("$ZodNumber",($,U)=>{h$.init($,U),$._zod.pattern=$._zod.bag.pattern??P8,$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=Number(J.value)}catch(X){}let W=J.value;if(typeof W==="number"&&!Number.isNaN(W)&&Number.isFinite(W))return J;let K=typeof W==="number"?Number.isNaN(W)?"NaN":!Number.isFinite(W)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:W,inst:$,...K?{received:K}:{}}),J}}),PN=g("$ZodNumberFormat",($,U)=>{gX.init($,U),E9.init($,U)}),A8=g("$ZodBoolean",($,U)=>{h$.init($,U),$._zod.pattern=AX,$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=Boolean(J.value)}catch(K){}let W=J.value;if(typeof W==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:W,inst:$}),J}}),Z9=g("$ZodBigInt",($,U)=>{h$.init($,U),$._zod.pattern=zX,$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=BigInt(J.value)}catch(W){}if(typeof J.value==="bigint")return J;return J.issues.push({expected:"bigint",code:"invalid_type",input:J.value,inst:$}),J}}),zN=g("$ZodBigIntFormat",($,U)=>{bX.init($,U),Z9.init($,U)}),_N=g("$ZodSymbol",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(typeof W==="symbol")return J;return J.issues.push({expected:"symbol",code:"invalid_type",input:W,inst:$}),J}}),AN=g("$ZodUndefined",($,U)=>{h$.init($,U),$._zod.pattern=SX,$._zod.values=new Set([void 0]),$._zod.parse=(J,Q)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"undefined",code:"invalid_type",input:W,inst:$}),J}}),CN=g("$ZodNull",($,U)=>{h$.init($,U),$._zod.pattern=CX,$._zod.values=new Set([null]),$._zod.parse=(J,Q)=>{let W=J.value;if(W===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:W,inst:$}),J}}),SN=g("$ZodAny",($,U)=>{h$.init($,U),$._zod.parse=(J)=>J}),TN=g("$ZodUnknown",($,U)=>{h$.init($,U),$._zod.parse=(J)=>J}),vN=g("$ZodNever",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:$}),J}}),jN=g("$ZodVoid",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"void",code:"invalid_type",input:W,inst:$}),J}}),gN=g("$ZodDate",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=new Date(J.value)}catch(N){}let W=J.value,K=W instanceof Date;if(K&&!Number.isNaN(W.getTime()))return J;return J.issues.push({expected:"date",code:"invalid_type",input:W,...K?{received:"Invalid Date"}:{},inst:$}),J}});function pZ($,U,J){if($.issues.length)U.issues.push(...EU(J,$.issues));U.value[J]=$.value}var bN=g("$ZodArray",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(!Array.isArray(W))return J.issues.push({expected:"array",code:"invalid_type",input:W,inst:$}),J;J.value=Array(W.length);let K=[];for(let X=0;X<W.length;X++){let N=W[X],H=U.element._zod.run({value:N,issues:[]},Q);if(H instanceof Promise)K.push(H.then((Y)=>pZ(Y,J,X)));else pZ(H,J,X)}if(K.length)return Promise.all(K).then(()=>J);return J}});function O9($,U,J,Q,W,K){let X=J in Q;if($.issues.length){if(W&&K&&!X)return;U.issues.push(...EU(J,$.issues))}if(!X&&!W){if(!$.issues.length)U.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[J]});return}if($.value===void 0){if(X)U.value[J]=void 0}else U.value[J]=$.value}function KI($){let U=Object.keys($.shape);for(let Q of U)if(!$.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let J=a7($.shape);return{...$,keys:U,keySet:new Set(U),numKeys:U.length,optionalKeys:new Set(J)}}function XI($,U,J,Q,W,K){let X=[],N=W.keySet,H=W.catchall._zod,Y=H.def.type,G=H.optin==="optional",O=H.optout==="optional";for(let E in U){if(E==="__proto__")continue;if(N.has(E))continue;if(Y==="never"){X.push(E);continue}let Z=H.run({value:U[E],issues:[]},Q);if(Z instanceof Promise)$.push(Z.then((D)=>O9(D,J,E,U,G,O)));else O9(Z,J,E,U,G,O)}if(X.length)J.issues.push({code:"unrecognized_keys",keys:X,input:U,inst:K});if(!$.length)return J;return Promise.all($).then(()=>{return J})}var NI=g("$ZodObject",($,U)=>{if(h$.init($,U),!Object.getOwnPropertyDescriptor(U,"shape")?.get){let N=U.shape;Object.defineProperty(U,"shape",{get:()=>{let H={...N};return Object.defineProperty(U,"shape",{value:H}),H}})}let Q=UW(()=>KI(U));a$($._zod,"propValues",()=>{let N=U.shape,H={};for(let Y in N){let G=N[Y]._zod;if(G.values){H[Y]??(H[Y]=new Set);for(let O of G.values)H[Y].add(O)}}return H});let W=M0,K=U.catchall,X;$._zod.parse=(N,H)=>{X??(X=Q.value);let Y=N.value;if(!W(Y))return N.issues.push({expected:"object",code:"invalid_type",input:Y,inst:$}),N;N.value={};let G=[],O=X.shape;for(let E of X.keys){let Z=O[E],D=Z._zod.optin==="optional",R=Z._zod.optout==="optional",I=Z._zod.run({value:Y[E],issues:[]},H);if(I instanceof Promise)G.push(I.then((q)=>O9(q,N,E,Y,D,R)));else O9(I,N,E,Y,D,R)}if(!K)return G.length?Promise.all(G).then(()=>N):N;return XI(G,Y,N,H,Q.value,$)}}),xN=g("$ZodObjectJIT",($,U)=>{NI.init($,U);let J=$._zod.parse,Q=UW(()=>KI(U)),W=(E)=>{let Z=new N9(["shape","payload","ctx"]),D=Q.value,R=(P)=>{let L=nQ(P);return`shape[${L}]._zod.run({ value: input[${L}], issues: [] }, ctx)`};Z.write("const input = payload.value;");let I=Object.create(null),q=0;for(let P of D.keys)I[P]=`key_${q++}`;Z.write("const newResult = {};");for(let P of D.keys){let L=I[P],B=nQ(P),z=E[P],A=z?._zod?.optin==="optional",k=z?._zod?.optout==="optional";if(Z.write(`const ${L} = ${R(P)};`),A&&k)Z.write(`- if (${L}.issues.length) {- if (${B} in input) {- payload.issues = payload.issues.concat(${L}.issues.map(iss => ({+var Th;function q(e,t,n){function i(a,c){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=o.prototype,u=Object.keys(l);for(let f=0;f<u.length;f++){let h=u[f];if(!(h in a))a[h]=l[h].bind(a)}}let r=n?.Parent??Object;class s extends r{}Object.defineProperty(s,"name",{value:e});function o(a){var c;let l=n?.Parent?new s:this;i(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(o,"init",{value:i}),Object.defineProperty(o,Symbol.hasInstance,{value:(a)=>{if(n?.Parent&&a instanceof n.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(o,"name",{value:e}),o}var dE=Symbol("zod_brand");class ii extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ds extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Th=globalThis).__zod_globalConfig??(Th.__zod_globalConfig={});var Er=globalThis.__zod_globalConfig;function Tn(e){if(e)Object.assign(Er,e);return Er}function yo(e){let t=Object.values(e).filter((i)=>typeof i==="number");return Object.entries(e).filter(([i,r])=>t.indexOf(+i)===-1).map(([i,r])=>r)}function ms(e,t){if(typeof t==="bigint")return t.toString();return t}function bo(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function So(e){return e===null||e===void 0}function Mo(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Ah(e,t){let n=e/t,i=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-i)<r)return 0;return n-i}var Eh=Symbol("evaluating");function it(e,t,n){let i=void 0;Object.defineProperty(e,t,{get(){if(i===Eh)return;if(i===void 0)i=Eh,i=n();return i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Ji(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function bi(...e){let t={};for(let n of e){let i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function sc(e){return JSON.stringify(e)}function Rh(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var oc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ps(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Ch=bo(()=>{if(Er.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ki(e){if(ps(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(ps(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function ac(e){if(Ki(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Ih=new Set(["string","number","symbol"]);function Si(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gn(e,t,n){let i=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)i._zod.parent=e;return i}function Te(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Ph(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Lh={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Q0(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=bi(e._zod.def,{get shape(){let o={};for(let a in t){if(!(a in n.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;o[a]=n.shape[a]}return Ji(this,"shape",o),o},checks:[]});return Gn(e,s)}function ex(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=bi(e._zod.def,{get shape(){let o={...e._zod.def.shape};for(let a in t){if(!(a in n.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete o[a]}return Ji(this,"shape",o),o},checks:[]});return Gn(e,s)}function tx(e,t){if(!Ki(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let s=e._zod.def.shape;for(let o in t)if(Object.getOwnPropertyDescriptor(s,o)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=bi(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return Ji(this,"shape",s),s}});return Gn(e,r)}function nx(e,t){if(!Ki(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=bi(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Ji(this,"shape",i),i}});return Gn(e,n)}function ix(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=bi(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t._zod.def.shape};return Ji(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Gn(e,n)}function rx(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let o=bi(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(n)for(let l in n){if(!(l in a))throw Error(`Unrecognized key: "${l}"`);if(!n[l])continue;c[l]=e?new e({type:"optional",innerType:a[l]}):a[l]}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Ji(this,"shape",c),c},checks:[]});return Gn(t,o)}function sx(e,t,n){let i=bi(t._zod.def,{get shape(){let r=t._zod.def.shape,s={...r};if(n)for(let o in n){if(!(o in s))throw Error(`Unrecognized key: "${o}"`);if(!n[o])continue;s[o]=new e({type:"nonoptional",innerType:r[o]})}else for(let o in r)s[o]=new e({type:"nonoptional",innerType:r[o]});return Ji(this,"shape",s),s}});return Gn(t,i)}function Qi(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Nh(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Mi(e,t){return t.map((n)=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function vo(e){return typeof e==="string"?e:e?.message}function En(e,t,n){let i=e.message?e.message:vo(e.inst?._zod.def?.error?.(e))??vo(t?.error?.(e))??vo(n.customError?.(e))??vo(n.localeError?.(e))??"Invalid input",{inst:r,continue:s,input:o,...a}=e;if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=o;return a}function wo(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function er(...e){let[t,n,i]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:i};return{...t}}var Dh=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ms,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},To=q("$ZodError",Dh),cc=q("$ZodError",Dh,{Parent:Error});function Uh(e,t=(n)=>n.message){let n={},i=[];for(let r of e.issues)if(r.path.length>0)n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r));else i.push(t(r));return{formErrors:i,fieldErrors:n}}function Oh(e,t=(n)=>n.message){let n={_errors:[]},i=(r,s=[])=>{for(let o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map((a)=>i({issues:a},[...s,...o.path]));else if(o.code==="invalid_key")i({issues:o.issues},[...s,...o.path]);else if(o.code==="invalid_element")i({issues:o.issues},[...s,...o.path]);else{let a=[...s,...o.path];if(a.length===0)n._errors.push(t(o));else{let c=n,l=0;while(l<a.length){let u=a[l];if(l!==a.length-1)c[u]=c[u]||{_errors:[]};else c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(o));c=c[u],l++}}}};return i(e),n}var Eo=(e)=>(t,n,i,r)=>{let s=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise)throw new ii;if(o.issues.length){let a=new(r?.Err??e)(o.issues.map((c)=>En(c,s,Tn())));throw oc(a,r?.callee),a}return o.value};var Ao=(e)=>async(t,n,i,r)=>{let s=i?{...i,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise)o=await o;if(o.issues.length){let a=new(r?.Err??e)(o.issues.map((c)=>En(c,s,Tn())));throw oc(a,r?.callee),a}return o.value};var gs=(e)=>(t,n,i)=>{let r=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new ii;return s.issues.length?{success:!1,error:new(e??To)(s.issues.map((o)=>En(o,r,Tn())))}:{success:!0,data:s.value}},Fh=gs(cc),_s=(e)=>async(t,n,i)=>{let r=i?{...i,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((o)=>En(o,r,Tn())))}:{success:!0,data:s.value}},zh=_s(cc),kh=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return Eo(e)(t,n,r)};var Bh=(e)=>(t,n,i)=>Eo(e)(t,n,i);var Gh=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return Ao(e)(t,n,r)};var Hh=(e)=>async(t,n,i)=>Ao(e)(t,n,i);var Vh=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return gs(e)(t,n,r)};var Wh=(e)=>(t,n,i)=>gs(e)(t,n,i);var $h=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return _s(e)(t,n,r)};var Zh=(e)=>async(t,n,i)=>_s(e)(t,n,i);var Xh=/^[cC][0-9a-z]{6,}$/,qh=/^[0-9a-z]+$/,Yh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jh=/^[0-9a-vA-V]{20}$/,Jh=/^[A-Za-z0-9]{27}$/,Kh=/^[a-zA-Z0-9_-]{21}$/,Qh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ef=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,lc=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var tf=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var ax="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function nf(){return new RegExp(ax,"u")}var rf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sf=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var of=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,af=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cf=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,uc=/^[A-Za-z0-9_-]*$/;var lf=/^https?$/,uf=/^\+[1-9]\d{6,14}$/,hf="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ff=new RegExp(`^${hf}$`);function df(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function pf(e){return new RegExp(`^${df(e)}$`)}function mf(e){let t=df({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${t}(?:${n.join("|")})`;return new RegExp(`^${hf}T(?:${i})$`)}var gf=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var _f=/^-?\d+$/,hc=/^-?\d+(?:\.\d+)?$/,xf=/^(?:true|false)$/i;var vf=/^[^A-Z]*$/,yf=/^[^a-z]*$/;var Vt=q("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),bf={number:"number",bigint:"bigint",object:"date"},fc=q("$ZodCheckLessThan",(e,t)=>{Vt.init(e,t);let n=bf[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,s=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)r.maximum=t.value;else r.exclusiveMaximum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value<=t.value:i.value<t.value)return;i.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),dc=q("$ZodCheckGreaterThan",(e,t)=>{Vt.init(e,t);let n=bf[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,s=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)r.minimum=t.value;else r.exclusiveMinimum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value>=t.value:i.value>t.value)return;i.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Sf=q("$ZodCheckMultipleOf",(e,t)=>{Vt.init(e,t),e._zod.onattach.push((n)=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):Ah(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Mf=q("$ZodCheckNumberFormat",(e,t)=>{Vt.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),i=n?"int":"number",[r,s]=Lh[t.format];e._zod.onattach.push((o)=>{let a=o._zod.bag;if(a.format=t.format,a.minimum=r,a.maximum=s,n)a.pattern=_f}),e._zod.check=(o)=>{let a=o.value;if(n){if(!Number.isInteger(a)){o.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});else o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}if(a<r)o.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(a>s)o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var wf=q("$ZodCheckMaxLength",(e,t)=>{var n;Vt.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!So(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<r)i._zod.bag.maximum=t.maximum}),e._zod.check=(i)=>{let r=i.value;if(r.length<=t.maximum)return;let o=wo(r);i.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Tf=q("$ZodCheckMinLength",(e,t)=>{var n;Vt.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!So(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>r)i._zod.bag.minimum=t.minimum}),e._zod.check=(i)=>{let r=i.value;if(r.length>=t.minimum)return;let o=wo(r);i.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ef=q("$ZodCheckLengthEquals",(e,t)=>{var n;Vt.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!So(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=(i)=>{let r=i.value,s=r.length;if(s===t.length)return;let o=wo(r),a=s>t.length;i.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),xs=q("$ZodCheckStringFormat",(e,t)=>{var n,i;if(Vt.init(e,t),e._zod.onattach.push((r)=>{let s=r._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(i=e._zod).check??(i.check=()=>{})}),Af=q("$ZodCheckRegex",(e,t)=>{xs.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Rf=q("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vf),xs.init(e,t)}),Cf=q("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yf),xs.init(e,t)}),If=q("$ZodCheckIncludes",(e,t)=>{Vt.init(e,t);let n=Si(t.includes),i=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push((r)=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(i)}),e._zod.check=(r)=>{if(r.value.includes(t.includes,t.position))return;r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),Pf=q("$ZodCheckStartsWith",(e,t)=>{Vt.init(e,t);let n=new RegExp(`^${Si(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.startsWith(t.prefix))return;i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),Lf=q("$ZodCheckEndsWith",(e,t)=>{Vt.init(e,t);let n=new RegExp(`.*${Si(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.endsWith(t.suffix))return;i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}});var Nf=q("$ZodCheckOverwrite",(e,t)=>{Vt.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class pc{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`+`).filter((s)=>s),i=Math.min(...n.map((s)=>s.length-s.trimStart().length)),r=n.map((s)=>s.slice(i)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of r)this.content.push(s)}compile(){let e=Function,t=this?.args,i=[...(this?.content??[""]).map((r)=>` ${r}`)];return new e(...t,i.join(`+`))}}var Uf={major:4,minor:4,patch:3};var xt=q("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Uf;let i=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))i.unshift(e);for(let r of i)for(let s of r._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let r=(o,a,c)=>{let l=Qi(o),u;for(let f of a){if(f._zod.def.when){if(Nh(o))continue;if(!f._zod.def.when(o))continue}else if(l)continue;let h=o.issues.length,d=f._zod.check(o);if(d instanceof Promise&&c?.async===!1)throw new ii;if(u||d instanceof Promise)u=(u??Promise.resolve()).then(async()=>{if(await d,o.issues.length===h)return;if(!l)l=Qi(o,h)});else{if(o.issues.length===h)continue;if(!l)l=Qi(o,h)}}if(u)return u.then(()=>o);return o},s=(o,a,c)=>{if(Qi(o))return o.aborted=!0,o;let l=r(a,i,c);if(l instanceof Promise){if(c.async===!1)throw new ii;return l.then((u)=>e._zod.parse(u,c))}return e._zod.parse(l,c)};e._zod.run=(o,a)=>{if(a.skipChecks)return e._zod.parse(o,a);if(a.direction==="backward"){let l=e._zod.parse({value:o.value,issues:[]},{...a,skipChecks:!0});if(l instanceof Promise)return l.then((u)=>s(u,o,a));return s(l,o,a)}let c=e._zod.parse(o,a);if(c instanceof Promise){if(a.async===!1)throw new ii;return c.then((l)=>r(l,i,a))}return r(c,i,a)}}it(e,"~standard",()=>({validate:(r)=>{try{let s=Fh(e,r);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return zh(e,r).then((o)=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),Po=q("$ZodString",(e,t)=>{xt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??gf(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),_t=q("$ZodStringFormat",(e,t)=>{xs.init(e,t),Po.init(e,t)}),Wf=q("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ef),_t.init(e,t)}),$f=q("$ZodUUID",(e,t)=>{if(t.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=lc(i))}else t.pattern??(t.pattern=lc());_t.init(e,t)}),Zf=q("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=tf),_t.init(e,t)}),Xf=q("$ZodURL",(e,t)=>{_t.init(e,t),e._zod.check=(n)=>{try{let i=n.value.trim();if(!t.normalize&&t.protocol?.source===lf.source){if(!/^https?:\/\//i.test(i)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}}let r=new URL(i);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(r.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=r.href;else n.value=i;return}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),qf=q("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=nf()),_t.init(e,t)}),Yf=q("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Kh),_t.init(e,t)}),jf=q("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Xh),_t.init(e,t)}),Jf=q("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=qh),_t.init(e,t)}),Kf=q("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Yh),_t.init(e,t)}),Qf=q("$ZodXID",(e,t)=>{t.pattern??(t.pattern=jh),_t.init(e,t)}),ed=q("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Jh),_t.init(e,t)}),td=q("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=mf(t)),_t.init(e,t)}),nd=q("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ff),_t.init(e,t)}),id=q("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=pf(t)),_t.init(e,t)}),rd=q("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qh),_t.init(e,t)}),sd=q("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=rf),_t.init(e,t),e._zod.bag.format="ipv4"}),od=q("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=sf),_t.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(n)=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}});var ad=q("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=of),_t.init(e,t)}),cd=q("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=af),_t.init(e,t),e._zod.check=(n)=>{let i=n.value.split("/");try{if(i.length!==2)throw Error();let[r,s]=i;if(!s)throw Error();let o=Number(s);if(`${o}`!==s)throw Error();if(o<0||o>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ld(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var ud=q("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cf),_t.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(ld(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function cx(e){if(!uc.test(e))return!1;let t=e.replace(/[-_]/g,(i)=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return ld(n)}var hd=q("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=uc),_t.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(cx(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),fd=q("$ZodE164",(e,t)=>{t.pattern??(t.pattern=uf),_t.init(e,t)});function lx(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let r=JSON.parse(atob(i));if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&(!("alg"in r)||r.alg!==t))return!1;return!0}catch{return!1}}var dd=q("$ZodJWT",(e,t)=>{_t.init(e,t),e._zod.check=(n)=>{if(lx(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var gc=q("$ZodNumber",(e,t)=>{xt.init(e,t),e._zod.pattern=e._zod.bag.pattern??hc,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch(o){}let r=n.value;if(typeof r==="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let s=typeof r==="number"?Number.isNaN(r)?"NaN":!Number.isFinite(r)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),n}}),pd=q("$ZodNumberFormat",(e,t)=>{Mf.init(e,t),gc.init(e,t)}),md=q("$ZodBoolean",(e,t)=>{xt.init(e,t),e._zod.pattern=xf,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}let r=n.value;if(typeof r==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}});var gd=q("$ZodUnknown",(e,t)=>{xt.init(e,t),e._zod.parse=(n)=>n}),_d=q("$ZodNever",(e,t)=>{xt.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Of(e,t,n){if(e.issues.length)t.issues.push(...Mi(n,e.issues));t.value[n]=e.value}var xd=q("$ZodArray",(e,t)=>{xt.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);let s=[];for(let o=0;o<r.length;o++){let a=r[o],c=t.element._zod.run({value:a,issues:[]},i);if(c instanceof Promise)s.push(c.then((l)=>Of(l,n,o)));else Of(c,n,o)}if(s.length)return Promise.all(s).then(()=>n);return n}});function Io(e,t,n,i,r,s){let o=n in i;if(e.issues.length){if(r&&s&&!o)return;t.issues.push(...Mi(n,e.issues))}if(!o&&!r){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(o)t.value[n]=void 0}else t.value[n]=e.value}function vd(e){let t=Object.keys(e.shape);for(let i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${i}": expected a Zod schema`);let n=Ph(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function yd(e,t,n,i,r,s){let o=[],a=r.keySet,c=r.catchall._zod,l=c.def.type,u=c.optin==="optional",f=c.optout==="optional";for(let h in t){if(h==="__proto__")continue;if(a.has(h))continue;if(l==="never"){o.push(h);continue}let d=c.run({value:t[h],issues:[]},i);if(d instanceof Promise)e.push(d.then((g)=>Io(g,n,h,t,u,f)));else Io(d,n,h,t,u,f)}if(o.length)n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s});if(!e.length)return n;return Promise.all(e).then(()=>n)}var ux=q("$ZodObject",(e,t)=>{if(xt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let i=bo(()=>vd(t));it(e._zod,"propValues",()=>{let a=t.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let f of u.values)c[l].add(f)}}return c});let r=ps,s=t.catchall,o;e._zod.parse=(a,c)=>{o??(o=i.value);let l=a.value;if(!r(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};let u=[],f=o.shape;for(let h of o.keys){let d=f[h],g=d._zod.optin==="optional",y=d._zod.optout==="optional",p=d._zod.run({value:l[h],issues:[]},c);if(p instanceof Promise)u.push(p.then((m)=>Io(m,a,h,l,g,y)));else Io(p,a,h,l,g,y)}if(!s)return u.length?Promise.all(u).then(()=>a):a;return yd(u,l,a,c,i.value,e)}}),bd=q("$ZodObjectJIT",(e,t)=>{ux.init(e,t);let n=e._zod.parse,i=bo(()=>vd(t)),r=(h)=>{let d=new pc(["shape","payload","ctx"]),g=i.value,y=(T)=>{let v=sc(T);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};d.write("const input = payload.value;");let p=Object.create(null),m=0;for(let T of g.keys)p[T]=`key_${m++}`;d.write("const newResult = {};");for(let T of g.keys){let v=p[T],w=sc(T),E=h[T],R=E?._zod?.optin==="optional",_=E?._zod?.optout==="optional";if(d.write(`const ${v} = ${y(T)};`),R&&_)d.write(`+ if (${v}.issues.length) {+ if (${w} in input) {+ payload.issues = payload.issues.concat(${v}.issues.map(iss => ({...iss,- path: iss.path ? [${B}, ...iss.path] : [${B}]+ path: iss.path ? [${w}, ...iss.path] : [${w}]})));}}- if (${L}.value === undefined) {- if (${B} in input) {- newResult[${B}] = undefined;+ if (${v}.value === undefined) {+ if (${w} in input) {+ newResult[${w}] = undefined;}} else {- newResult[${B}] = ${L}.value;+ newResult[${w}] = ${v}.value;}- `);else if(!A)Z.write(`- const ${L}_present = ${B} in input;- if (${L}.issues.length) {- payload.issues = payload.issues.concat(${L}.issues.map(iss => ({+ `);else if(!R)d.write(`+ const ${v}_present = ${w} in input;+ if (${v}.issues.length) {+ payload.issues = payload.issues.concat(${v}.issues.map(iss => ({...iss,- path: iss.path ? [${B}, ...iss.path] : [${B}]+ path: iss.path ? [${w}, ...iss.path] : [${w}]})));}- if (!${L}_present && !${L}.issues.length) {+ if (!${v}_present && !${v}.issues.length) {payload.issues.push({code: "invalid_type",expected: "nonoptional",input: undefined,- path: [${B}]+ path: [${w}]});}- if (${L}_present) {- if (${L}.value === undefined) {- newResult[${B}] = undefined;+ if (${v}_present) {+ if (${v}.value === undefined) {+ newResult[${w}] = undefined;} else {- newResult[${B}] = ${L}.value;+ newResult[${w}] = ${v}.value;}}- `);else Z.write(`- if (${L}.issues.length) {- payload.issues = payload.issues.concat(${L}.issues.map(iss => ({+ `);else d.write(`+ if (${v}.issues.length) {+ payload.issues = payload.issues.concat(${v}.issues.map(iss => ({...iss,- path: iss.path ? [${B}, ...iss.path] : [${B}]+ path: iss.path ? [${w}, ...iss.path] : [${w}]})));}- if (${L}.value === undefined) {- if (${B} in input) {- newResult[${B}] = undefined;+ if (${v}.value === undefined) {+ if (${w} in input) {+ newResult[${w}] = undefined;}} else {- newResult[${B}] = ${L}.value;+ newResult[${w}] = ${v}.value;}- `)}Z.write("payload.value = newResult;"),Z.write("return payload;");let _=Z.compile();return(P,L)=>_(E,P,L)},K,X=M0,N=!V0.jitless,Y=N&&i7.value,G=U.catchall,O;$._zod.parse=(E,Z)=>{O??(O=Q.value);let D=E.value;if(!X(D))return E.issues.push({expected:"object",code:"invalid_type",input:D,inst:$}),E;if(N&&Y&&Z?.async===!1&&Z.jitless!==!0){if(!K)K=W(U.shape);if(E=K(E,Z),!G)return E;return XI([],D,E,Z,O,$)}return J(E,Z)}});function dZ($,U,J,Q){for(let K of $)if(K.issues.length===0)return U.value=K.value,U;let W=$.filter((K)=>!dJ(K));if(W.length===1)return U.value=W[0].value,W[0];return U.issues.push({code:"invalid_union",input:U.value,inst:J,errors:$.map((K)=>K.issues.map((X)=>KU(X,Q,T6())))}),U}var C8=g("$ZodUnion",($,U)=>{h$.init($,U),a$($._zod,"optin",()=>U.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),a$($._zod,"optout",()=>U.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),a$($._zod,"values",()=>{if(U.options.every((Q)=>Q._zod.values))return new Set(U.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),a$($._zod,"pattern",()=>{if(U.options.every((Q)=>Q._zod.pattern)){let Q=U.options.map((W)=>W._zod.pattern);return new RegExp(`^(${Q.map((W)=>F8(W.source)).join("|")})$`)}return});let J=U.options.length===1?U.options[0]._zod.run:null;$._zod.parse=(Q,W)=>{if(J)return J(Q,W);let K=!1,X=[];for(let N of U.options){let H=N._zod.run({value:Q.value,issues:[]},W);if(H instanceof Promise)X.push(H),K=!0;else{if(H.issues.length===0)return H;X.push(H)}}if(!K)return dZ(X,Q,$,W);return Promise.all(X).then((N)=>{return dZ(N,Q,$,W)})}});function cZ($,U,J,Q){let W=$.filter((K)=>K.issues.length===0);if(W.length===1)return U.value=W[0].value,U;if(W.length===0)U.issues.push({code:"invalid_union",input:U.value,inst:J,errors:$.map((K)=>K.issues.map((X)=>KU(X,Q,T6())))});else U.issues.push({code:"invalid_union",input:U.value,inst:J,errors:[],inclusive:!1});return U}var yN=g("$ZodXor",($,U)=>{C8.init($,U),U.inclusive=!1;let J=U.options.length===1?U.options[0]._zod.run:null;$._zod.parse=(Q,W)=>{if(J)return J(Q,W);let K=!1,X=[];for(let N of U.options){let H=N._zod.run({value:Q.value,issues:[]},W);if(H instanceof Promise)X.push(H),K=!0;else X.push(H)}if(!K)return cZ(X,Q,$,W);return Promise.all(X).then((N)=>{return cZ(N,Q,$,W)})}}),hN=g("$ZodDiscriminatedUnion",($,U)=>{U.inclusive=!1,C8.init($,U);let J=$._zod.parse;a$($._zod,"propValues",()=>{let W={};for(let K of U.options){let X=K._zod.propValues;if(!X||Object.keys(X).length===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(K)}"`);for(let[N,H]of Object.entries(X)){if(!W[N])W[N]=new Set;for(let Y of H)W[N].add(Y)}}return W});let Q=UW(()=>{let W=U.options,K=new Map;for(let X of W){let N=X._zod.propValues?.[U.discriminator];if(!N||N.size===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(X)}"`);for(let H of N){if(K.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);K.set(H,X)}}return K});$._zod.parse=(W,K)=>{let X=W.value;if(!M0(X))return W.issues.push({code:"invalid_type",expected:"object",input:X,inst:$}),W;let N=Q.value.get(X?.[U.discriminator]);if(N)return N._zod.run(W,K);if(U.unionFallback||K.direction==="backward")return J(W,K);return W.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:U.discriminator,options:Array.from(Q.value.keys()),input:X,path:[U.discriminator],inst:$}),W}}),fN=g("$ZodIntersection",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value,K=U.left._zod.run({value:W,issues:[]},Q),X=U.right._zod.run({value:W,issues:[]},Q);if(K instanceof Promise||X instanceof Promise)return Promise.all([K,X]).then(([H,Y])=>{return nZ(J,H,Y)});return nZ(J,K,X)}});function tX($,U){if($===U)return{valid:!0,data:$};if($ instanceof Date&&U instanceof Date&&+$===+U)return{valid:!0,data:$};if(pJ($)&&pJ(U)){let J=Object.keys(U),Q=Object.keys($).filter((K)=>J.indexOf(K)!==-1),W={...$,...U};for(let K of Q){let X=tX($[K],U[K]);if(!X.valid)return{valid:!1,mergeErrorPath:[K,...X.mergeErrorPath]};W[K]=X.data}return{valid:!0,data:W}}if(Array.isArray($)&&Array.isArray(U)){if($.length!==U.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<$.length;Q++){let W=$[Q],K=U[Q],X=tX(W,K);if(!X.valid)return{valid:!1,mergeErrorPath:[Q,...X.mergeErrorPath]};J.push(X.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function nZ($,U,J){let Q=new Map,W;for(let N of U.issues)if(N.code==="unrecognized_keys"){W??(W=N);for(let H of N.keys){if(!Q.has(H))Q.set(H,{});Q.get(H).l=!0}}else $.issues.push(N);for(let N of J.issues)if(N.code==="unrecognized_keys")for(let H of N.keys){if(!Q.has(H))Q.set(H,{});Q.get(H).r=!0}else $.issues.push(N);let K=[...Q].filter(([,N])=>N.l&&N.r).map(([N])=>N);if(K.length&&W)$.issues.push({...W,keys:K});if(dJ($))return $;let X=tX(U.value,J.value);if(!X.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}var I9=g("$ZodTuple",($,U)=>{h$.init($,U);let J=U.items;$._zod.parse=(Q,W)=>{let K=Q.value;if(!Array.isArray(K))return Q.issues.push({input:K,inst:$,expected:"tuple",code:"invalid_type"}),Q;Q.value=[];let X=[],N=iZ(J,"optin"),H=iZ(J,"optout");if(!U.rest){if(K.length<N)return Q.issues.push({code:"too_small",minimum:N,inclusive:!0,input:K,inst:$,origin:"array"}),Q;if(K.length>J.length)Q.issues.push({code:"too_big",maximum:J.length,inclusive:!0,input:K,inst:$,origin:"array"})}let Y=Array(J.length);for(let G=0;G<J.length;G++){let O=J[G]._zod.run({value:K[G],issues:[]},W);if(O instanceof Promise)X.push(O.then((E)=>{Y[G]=E}));else Y[G]=O}if(U.rest){let G=J.length-1,O=K.slice(J.length);for(let E of O){G++;let Z=U.rest._zod.run({value:E,issues:[]},W);if(Z instanceof Promise)X.push(Z.then((D)=>oZ(D,Q,G)));else oZ(Z,Q,G)}}if(X.length)return Promise.all(X).then(()=>rZ(Y,Q,J,K,H));return rZ(Y,Q,J,K,H)}});function iZ($,U){for(let J=$.length-1;J>=0;J--)if($[J]._zod[U]!=="optional")return J+1;return 0}function oZ($,U,J){if($.issues.length)U.issues.push(...EU(J,$.issues));U.value[J]=$.value}function rZ($,U,J,Q,W){for(let K=0;K<J.length;K++){let X=$[K],N=K<Q.length;if(X.issues.length){if(!N&&K>=W){U.value.length=K;break}U.issues.push(...EU(K,X.issues))}U.value[K]=X.value}for(let K=U.value.length-1;K>=Q.length;K--)if(J[K]._zod.optout==="optional"&&U.value[K]===void 0)U.value.length=K;else break;return U}var uN=g("$ZodRecord",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(!pJ(W))return J.issues.push({expected:"record",code:"invalid_type",input:W,inst:$}),J;let K=[],X=U.keyType._zod.values;if(X){J.value={};let N=new Set;for(let Y of X)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){N.add(typeof Y==="number"?Y.toString():Y);let G=U.keyType._zod.run({value:Y,issues:[]},Q);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(G.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((Z)=>KU(Z,Q,T6())),input:Y,path:[Y],inst:$});continue}let O=G.value,E=U.valueType._zod.run({value:W[Y],issues:[]},Q);if(E instanceof Promise)K.push(E.then((Z)=>{if(Z.issues.length)J.issues.push(...EU(Y,Z.issues));J.value[O]=Z.value}));else{if(E.issues.length)J.issues.push(...EU(Y,E.issues));J.value[O]=E.value}}let H;for(let Y in W)if(!N.has(Y))H=H??[],H.push(Y);if(H&&H.length>0)J.issues.push({code:"unrecognized_keys",input:W,inst:$,keys:H})}else{J.value={};for(let N of Reflect.ownKeys(W)){if(N==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(W,N))continue;let H=U.keyType._zod.run({value:N,issues:[]},Q);if(H instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof N==="string"&&P8.test(N)&&H.issues.length){let O=U.keyType._zod.run({value:Number(N),issues:[]},Q);if(O instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(O.issues.length===0)H=O}if(H.issues.length){if(U.mode==="loose")J.value[N]=W[N];else J.issues.push({code:"invalid_key",origin:"record",issues:H.issues.map((O)=>KU(O,Q,T6())),input:N,path:[N],inst:$});continue}let G=U.valueType._zod.run({value:W[N],issues:[]},Q);if(G instanceof Promise)K.push(G.then((O)=>{if(O.issues.length)J.issues.push(...EU(N,O.issues));J.value[H.value]=O.value}));else{if(G.issues.length)J.issues.push(...EU(N,G.issues));J.value[H.value]=G.value}}}if(K.length)return Promise.all(K).then(()=>J);return J}}),lN=g("$ZodMap",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(!(W instanceof Map))return J.issues.push({expected:"map",code:"invalid_type",input:W,inst:$}),J;let K=[];J.value=new Map;for(let[X,N]of W){let H=U.keyType._zod.run({value:X,issues:[]},Q),Y=U.valueType._zod.run({value:N,issues:[]},Q);if(H instanceof Promise||Y instanceof Promise)K.push(Promise.all([H,Y]).then(([G,O])=>{aZ(G,O,J,X,W,$,Q)}));else aZ(H,Y,J,X,W,$,Q)}if(K.length)return Promise.all(K).then(()=>J);return J}});function aZ($,U,J,Q,W,K,X){if($.issues.length)if(L8.has(typeof Q))J.issues.push(...EU(Q,$.issues));else J.issues.push({code:"invalid_key",origin:"map",input:W,inst:K,issues:$.issues.map((N)=>KU(N,X,T6()))});if(U.issues.length)if(L8.has(typeof Q))J.issues.push(...EU(Q,U.issues));else J.issues.push({origin:"map",code:"invalid_element",input:W,inst:K,key:Q,issues:U.issues.map((N)=>KU(N,X,T6()))});J.value.set($.value,U.value)}var mN=g("$ZodSet",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(!(W instanceof Set))return J.issues.push({input:W,inst:$,expected:"set",code:"invalid_type"}),J;let K=[];J.value=new Set;for(let X of W){let N=U.valueType._zod.run({value:X,issues:[]},Q);if(N instanceof Promise)K.push(N.then((H)=>sZ(H,J)));else sZ(N,J)}if(K.length)return Promise.all(K).then(()=>J);return J}});function sZ($,U){if($.issues.length)U.issues.push(...$.issues);U.value.add($.value)}var pN=g("$ZodEnum",($,U)=>{h$.init($,U);let J=k8(U.entries),Q=new Set(J);$._zod.values=Q,$._zod.pattern=new RegExp(`^(${J.filter((W)=>L8.has(typeof W)).map((W)=>typeof W==="string"?vU(W):W.toString()).join("|")})$`),$._zod.parse=(W,K)=>{let X=W.value;if(Q.has(X))return W;return W.issues.push({code:"invalid_value",values:J,input:X,inst:$}),W}}),dN=g("$ZodLiteral",($,U)=>{if(h$.init($,U),U.values.length===0)throw Error("Cannot create literal schema with no valid values");let J=new Set(U.values);$._zod.values=J,$._zod.pattern=new RegExp(`^(${U.values.map((Q)=>typeof Q==="string"?vU(Q):Q?vU(Q.toString()):String(Q)).join("|")})$`),$._zod.parse=(Q,W)=>{let K=Q.value;if(J.has(K))return Q;return Q.issues.push({code:"invalid_value",values:U.values,input:K,inst:$}),Q}}),cN=g("$ZodFile",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(W instanceof File)return J;return J.issues.push({expected:"file",code:"invalid_type",input:W,inst:$}),J}}),nN=g("$ZodTransform",($,U)=>{h$.init($,U),$._zod.optin="optional",$._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new w0($.constructor.name);let W=U.transform(J.value,J);if(Q.async)return(W instanceof Promise?W:Promise.resolve(W)).then((X)=>{return J.value=X,J.fallback=!0,J});if(W instanceof Promise)throw new $J;return J.value=W,J.fallback=!0,J}});function tZ($,U){if(U===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}var q9=g("$ZodOptional",($,U)=>{h$.init($,U),$._zod.optin="optional",$._zod.optout="optional",a$($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,void 0]):void 0}),a$($._zod,"pattern",()=>{let J=U.innerType._zod.pattern;return J?new RegExp(`^(${F8(J.source)})?$`):void 0}),$._zod.parse=(J,Q)=>{if(U.innerType._zod.optin==="optional"){let W=J.value,K=U.innerType._zod.run(J,Q);if(K instanceof Promise)return K.then((X)=>tZ(X,W));return tZ(K,W)}if(J.value===void 0)return J;return U.innerType._zod.run(J,Q)}}),iN=g("$ZodExactOptional",($,U)=>{q9.init($,U),a$($._zod,"values",()=>U.innerType._zod.values),a$($._zod,"pattern",()=>U.innerType._zod.pattern),$._zod.parse=(J,Q)=>{return U.innerType._zod.run(J,Q)}}),oN=g("$ZodNullable",($,U)=>{h$.init($,U),a$($._zod,"optin",()=>U.innerType._zod.optin),a$($._zod,"optout",()=>U.innerType._zod.optout),a$($._zod,"pattern",()=>{let J=U.innerType._zod.pattern;return J?new RegExp(`^(${F8(J.source)}|null)$`):void 0}),a$($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,null]):void 0}),$._zod.parse=(J,Q)=>{if(J.value===null)return J;return U.innerType._zod.run(J,Q)}}),rN=g("$ZodDefault",($,U)=>{h$.init($,U),$._zod.optin="optional",a$($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")return U.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=U.defaultValue,J;let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>eZ(K,U));return eZ(W,U)}});function eZ($,U){if($.value===void 0)$.value=U.defaultValue;return $}var aN=g("$ZodPrefault",($,U)=>{h$.init($,U),$._zod.optin="optional",a$($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")return U.innerType._zod.run(J,Q);if(J.value===void 0)J.value=U.defaultValue;return U.innerType._zod.run(J,Q)}}),sN=g("$ZodNonOptional",($,U)=>{h$.init($,U),a$($._zod,"values",()=>{let J=U.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),$._zod.parse=(J,Q)=>{let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>$I(K,$));return $I(W,$)}});function $I($,U){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:U});return $}var tN=g("$ZodSuccess",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new w0("ZodSuccess");let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>{return J.value=K.issues.length===0,J});return J.value=W.issues.length===0,J}}),eN=g("$ZodCatch",($,U)=>{h$.init($,U),$._zod.optin="optional",a$($._zod,"optout",()=>U.innerType._zod.optout),a$($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")return U.innerType._zod.run(J,Q);let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>{if(J.value=K.value,K.issues.length)J.value=U.catchValue({...J,error:{issues:K.issues.map((X)=>KU(X,Q,T6()))},input:J.value}),J.issues=[],J.fallback=!0;return J});if(J.value=W.value,W.issues.length)J.value=U.catchValue({...J,error:{issues:W.issues.map((K)=>KU(K,Q,T6()))},input:J.value}),J.issues=[],J.fallback=!0;return J}}),$H=g("$ZodNaN",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{if(typeof J.value!=="number"||!Number.isNaN(J.value))return J.issues.push({input:J.value,inst:$,expected:"nan",code:"invalid_type"}),J;return J}}),D9=g("$ZodPipe",($,U)=>{h$.init($,U),a$($._zod,"values",()=>U.in._zod.values),a$($._zod,"optin",()=>U.in._zod.optin),a$($._zod,"optout",()=>U.out._zod.optout),a$($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let K=U.out._zod.run(J,Q);if(K instanceof Promise)return K.then((X)=>H9(X,U.in,Q));return H9(K,U.in,Q)}let W=U.in._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>H9(K,U.out,Q));return H9(W,U.out,Q)}});function H9($,U,J){if($.issues.length)return $.aborted=!0,$;return U._zod.run({value:$.value,issues:$.issues,fallback:$.fallback},J)}var S8=g("$ZodCodec",($,U)=>{h$.init($,U),a$($._zod,"values",()=>U.in._zod.values),a$($._zod,"optin",()=>U.in._zod.optin),a$($._zod,"optout",()=>U.out._zod.optout),a$($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(J,Q)=>{if((Q.direction||"forward")==="forward"){let K=U.in._zod.run(J,Q);if(K instanceof Promise)return K.then((X)=>Y9(X,U,Q));return Y9(K,U,Q)}else{let K=U.out._zod.run(J,Q);if(K instanceof Promise)return K.then((X)=>Y9(X,U,Q));return Y9(K,U,Q)}}});function Y9($,U,J){if($.issues.length)return $.aborted=!0,$;if((J.direction||"forward")==="forward"){let W=U.transform($.value,$);if(W instanceof Promise)return W.then((K)=>G9($,K,U.out,J));return G9($,W,U.out,J)}else{let W=U.reverseTransform($.value,$);if(W instanceof Promise)return W.then((K)=>G9($,K,U.in,J));return G9($,W,U.in,J)}}function G9($,U,J,Q){if($.issues.length)return $.aborted=!0,$;return J._zod.run({value:U,issues:$.issues},Q)}var UH=g("$ZodPreprocess",($,U)=>{D9.init($,U)}),JH=g("$ZodReadonly",($,U)=>{h$.init($,U),a$($._zod,"propValues",()=>U.innerType._zod.propValues),a$($._zod,"values",()=>U.innerType._zod.values),a$($._zod,"optin",()=>U.innerType?._zod?.optin),a$($._zod,"optout",()=>U.innerType?._zod?.optout),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")return U.innerType._zod.run(J,Q);let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then(UI);return UI(W)}});function UI($){return $.value=Object.freeze($.value),$}var WH=g("$ZodTemplateLiteral",($,U)=>{h$.init($,U);let J=[];for(let Q of U.parts)if(typeof Q==="object"&&Q!==null){if(!Q._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...Q._zod.traits].shift()}`);let W=Q._zod.pattern instanceof RegExp?Q._zod.pattern.source:Q._zod.pattern;if(!W)throw Error(`Invalid template literal part: ${Q._zod.traits}`);let K=W.startsWith("^")?1:0,X=W.endsWith("$")?W.length-1:W.length;J.push(W.slice(K,X))}else if(Q===null||r7.has(typeof Q))J.push(vU(`${Q}`));else throw Error(`Invalid template literal part: ${Q}`);$._zod.pattern=new RegExp(`^${J.join("")}$`),$._zod.parse=(Q,W)=>{if(typeof Q.value!=="string")return Q.issues.push({input:Q.value,inst:$,expected:"string",code:"invalid_type"}),Q;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(Q.value))return Q.issues.push({input:Q.value,inst:$,code:"invalid_format",format:U.format??"template_literal",pattern:$._zod.pattern.source}),Q;return Q}}),QH=g("$ZodFunction",($,U)=>{return h$.init($,U),$._def=U,$._zod.def=U,$.implement=(J)=>{if(typeof J!=="function")throw Error("implement() must be called with a function");return function(...Q){let W=$._def.input?oQ($._def.input,Q):Q,K=Reflect.apply(J,this,W);if($._def.output)return oQ($._def.output,K);return K}},$.implementAsync=(J)=>{if(typeof J!=="function")throw Error("implementAsync() must be called with a function");return async function(...Q){let W=$._def.input?await rQ($._def.input,Q):Q,K=await Reflect.apply(J,this,W);if($._def.output)return await rQ($._def.output,K);return K}},$._zod.parse=(J,Q)=>{if(typeof J.value!=="function")return J.issues.push({code:"invalid_type",expected:"function",input:J.value,inst:$}),J;if($._def.output&&$._def.output._zod.def.type==="promise")J.value=$.implementAsync(J.value);else J.value=$.implement(J.value);return J},$.input=(...J)=>{let Q=$.constructor;if(Array.isArray(J[0]))return new Q({type:"function",input:new I9({type:"tuple",items:J[0],rest:J[1]}),output:$._def.output});return new Q({type:"function",input:J[0],output:$._def.output})},$.output=(J)=>{return new $.constructor({type:"function",input:$._def.input,output:J})},$}),KH=g("$ZodPromise",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{return Promise.resolve(J.value).then((W)=>U.innerType._zod.run({value:W,issues:[]},Q))}}),XH=g("$ZodLazy",($,U)=>{h$.init($,U),a$($._zod,"innerType",()=>{let J=U;if(!J._cachedInner)J._cachedInner=U.getter();return J._cachedInner}),a$($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),a$($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),a$($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),a$($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(J,Q)=>{return $._zod.innerType._zod.run(J,Q)}}),NH=g("$ZodCustom",($,U)=>{V6.init($,U),h$.init($,U),$._zod.parse=(J,Q)=>{return J},$._zod.check=(J)=>{let Q=J.value,W=U.fn(Q);if(W instanceof Promise)return W.then((K)=>JI(K,J,Q,$));JI(W,J,Q,$);return}});function JI($,U,J,Q){if(!$){let W={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)W.params=Q._zod.def.params;U.issues.push(JW(W))}}var b8={};RJ(b8,{zhTW:()=>UY,zhCN:()=>$Y,yo:()=>JY,vi:()=>eH,uz:()=>tH,ur:()=>sH,uk:()=>g8,ua:()=>aH,tr:()=>rH,th:()=>oH,ta:()=>iH,sv:()=>nH,sl:()=>cH,ru:()=>dH,ro:()=>pH,pt:()=>mH,ps:()=>uH,pl:()=>lH,ota:()=>fH,no:()=>hH,nl:()=>yH,ms:()=>xH,mk:()=>bH,lt:()=>gH,ko:()=>jH,km:()=>v8,kh:()=>vH,ka:()=>TH,ja:()=>SH,it:()=>CH,is:()=>AH,id:()=>_H,hy:()=>zH,hu:()=>PH,hr:()=>BH,he:()=>MH,frCA:()=>wH,fr:()=>VH,fi:()=>RH,fa:()=>LH,es:()=>FH,eo:()=>kH,en:()=>T8,el:()=>DH,de:()=>qH,da:()=>IH,cs:()=>ZH,ca:()=>EH,bg:()=>OH,be:()=>GH,az:()=>YH,ar:()=>HH});var A4=()=>{let $={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function U(W){return $[W]??null}let J={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${W.expected}، ولكن تم إدخال ${N}`;return`مدخلات غير مقبولة: يفترض إدخال ${K}، ولكن تم إدخال ${N}`}case"invalid_value":if(W.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${U$(W.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return` أكبر من اللازم: يفترض أن تكون ${W.origin??"القيمة"} ${K} ${W.maximum.toString()} ${X.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${W.origin??"القيمة"} ${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`أصغر من اللازم: يفترض لـ ${W.origin} أن يكون ${K} ${W.minimum.toString()} ${X.unit}`;return`أصغر من اللازم: يفترض لـ ${W.origin} أن يكون ${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${W.prefix}"`;if(K.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${K.suffix}"`;if(K.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${K.includes}"`;if(K.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${K.pattern}`;return`${J[K.format]??W.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${W.divisor}`;case"unrecognized_keys":return`معرف${W.keys.length>1?"ات":""} غريب${W.keys.length>1?"ة":""}: ${m(W.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${W.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${W.origin}`;default:return"مدخل غير مقبول"}}};function HH(){return{localeError:A4()}}var C4=()=>{let $={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function U(W){return $[W]??null}let J={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Yanlış dəyər: gözlənilən instanceof ${W.expected}, daxil olan ${N}`;return`Yanlış dəyər: gözlənilən ${K}, daxil olan ${N}`}case"invalid_value":if(W.values.length===1)return`Yanlış dəyər: gözlənilən ${U$(W.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Çox böyük: gözlənilən ${W.origin??"dəyər"} ${K}${W.maximum.toString()} ${X.unit??"element"}`;return`Çox böyük: gözlənilən ${W.origin??"dəyər"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Çox kiçik: gözlənilən ${W.origin} ${K}${W.minimum.toString()} ${X.unit}`;return`Çox kiçik: gözlənilən ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Yanlış mətn: "${K.prefix}" ilə başlamalıdır`;if(K.format==="ends_with")return`Yanlış mətn: "${K.suffix}" ilə bitməlidir`;if(K.format==="includes")return`Yanlış mətn: "${K.includes}" daxil olmalıdır`;if(K.format==="regex")return`Yanlış mətn: ${K.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${J[K.format]??W.format}`}case"not_multiple_of":return`Yanlış ədəd: ${W.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${W.keys.length>1?"lar":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${W.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function YH(){return{localeError:C4()}}function HI($,U,J,Q){let W=Math.abs($),K=W%10,X=W%100;if(X>=11&&X<=19)return Q;if(K===1)return U;if(K>=2&&K<=4)return J;return Q}var S4=()=>{let $={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function U(W){return $[W]??null}let J={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},Q={nan:"NaN",number:"лік",array:"масіў"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Няправільны ўвод: чакаўся instanceof ${W.expected}, атрымана ${N}`;return`Няправільны ўвод: чакаўся ${K}, атрымана ${N}`}case"invalid_value":if(W.values.length===1)return`Няправільны ўвод: чакалася ${U$(W.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X){let N=Number(W.maximum),H=HI(N,X.unit.one,X.unit.few,X.unit.many);return`Занадта вялікі: чакалася, што ${W.origin??"значэнне"} павінна ${X.verb} ${K}${W.maximum.toString()} ${H}`}return`Занадта вялікі: чакалася, што ${W.origin??"значэнне"} павінна быць ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X){let N=Number(W.minimum),H=HI(N,X.unit.one,X.unit.few,X.unit.many);return`Занадта малы: чакалася, што ${W.origin} павінна ${X.verb} ${K}${W.minimum.toString()} ${H}`}return`Занадта малы: чакалася, што ${W.origin} павінна быць ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${K.prefix}"`;if(K.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${K.suffix}"`;if(K.format==="includes")return`Няправільны радок: павінен змяшчаць "${K.includes}"`;if(K.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${K.pattern}`;return`Няправільны ${J[K.format]??W.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${W.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${W.keys.length>1?"ключы":"ключ"}: ${m(W.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${W.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${W.origin}`;default:return"Няправільны ўвод"}}};function GH(){return{localeError:S4()}}var T4=()=>{let $={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function U(W){return $[W]??null}let J={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},Q={nan:"NaN",number:"число",array:"масив"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Невалиден вход: очакван instanceof ${W.expected}, получен ${N}`;return`Невалиден вход: очакван ${K}, получен ${N}`}case"invalid_value":if(W.values.length===1)return`Невалиден вход: очакван ${U$(W.values[0])}`;return`Невалидна опция: очаквано едно от ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Твърде голямо: очаква се ${W.origin??"стойност"} да съдържа ${K}${W.maximum.toString()} ${X.unit??"елемента"}`;return`Твърде голямо: очаква се ${W.origin??"стойност"} да бъде ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Твърде малко: очаква се ${W.origin} да съдържа ${K}${W.minimum.toString()} ${X.unit}`;return`Твърде малко: очаква се ${W.origin} да бъде ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Невалиден низ: трябва да започва с "${K.prefix}"`;if(K.format==="ends_with")return`Невалиден низ: трябва да завършва с "${K.suffix}"`;if(K.format==="includes")return`Невалиден низ: трябва да включва "${K.includes}"`;if(K.format==="regex")return`Невалиден низ: трябва да съвпада с ${K.pattern}`;let X="Невалиден";if(K.format==="emoji")X="Невалидно";if(K.format==="datetime")X="Невалидно";if(K.format==="date")X="Невалидна";if(K.format==="time")X="Невалидно";if(K.format==="duration")X="Невалидна";return`${X} ${J[K.format]??W.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${W.divisor}`;case"unrecognized_keys":return`Неразпознат${W.keys.length>1?"и":""} ключ${W.keys.length>1?"ове":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${W.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${W.origin}`;default:return"Невалиден вход"}}};function OH(){return{localeError:T4()}}var v4=()=>{let $={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function U(W){return $[W]??null}let J={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Tipus invàlid: s'esperava instanceof ${W.expected}, s'ha rebut ${N}`;return`Tipus invàlid: s'esperava ${K}, s'ha rebut ${N}`}case"invalid_value":if(W.values.length===1)return`Valor invàlid: s'esperava ${U$(W.values[0])}`;return`Opció invàlida: s'esperava una de ${m(W.values," o ")}`;case"too_big":{let K=W.inclusive?"com a màxim":"menys de",X=U(W.origin);if(X)return`Massa gran: s'esperava que ${W.origin??"el valor"} contingués ${K} ${W.maximum.toString()} ${X.unit??"elements"}`;return`Massa gran: s'esperava que ${W.origin??"el valor"} fos ${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?"com a mínim":"més de",X=U(W.origin);if(X)return`Massa petit: s'esperava que ${W.origin} contingués ${K} ${W.minimum.toString()} ${X.unit}`;return`Massa petit: s'esperava que ${W.origin} fos ${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Format invàlid: ha de començar amb "${K.prefix}"`;if(K.format==="ends_with")return`Format invàlid: ha d'acabar amb "${K.suffix}"`;if(K.format==="includes")return`Format invàlid: ha d'incloure "${K.includes}"`;if(K.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${K.pattern}`;return`Format invàlid per a ${J[K.format]??W.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${W.divisor}`;case"unrecognized_keys":return`Clau${W.keys.length>1?"s":""} no reconeguda${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${W.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${W.origin}`;default:return"Entrada invàlida"}}};function EH(){return{localeError:v4()}}var j4=()=>{let $={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function U(W){return $[W]??null}let J={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},Q={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Neplatný vstup: očekáváno instanceof ${W.expected}, obdrženo ${N}`;return`Neplatný vstup: očekáváno ${K}, obdrženo ${N}`}case"invalid_value":if(W.values.length===1)return`Neplatný vstup: očekáváno ${U$(W.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Hodnota je příliš velká: ${W.origin??"hodnota"} musí mít ${K}${W.maximum.toString()} ${X.unit??"prvků"}`;return`Hodnota je příliš velká: ${W.origin??"hodnota"} musí být ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Hodnota je příliš malá: ${W.origin??"hodnota"} musí mít ${K}${W.minimum.toString()} ${X.unit??"prvků"}`;return`Hodnota je příliš malá: ${W.origin??"hodnota"} musí být ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Neplatný řetězec: musí začínat na "${K.prefix}"`;if(K.format==="ends_with")return`Neplatný řetězec: musí končit na "${K.suffix}"`;if(K.format==="includes")return`Neplatný řetězec: musí obsahovat "${K.includes}"`;if(K.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${K.pattern}`;return`Neplatný formát ${J[K.format]??W.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${W.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${m(W.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${W.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${W.origin}`;default:return"Neplatný vstup"}}};function ZH(){return{localeError:j4()}}var g4=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function U(W){return $[W]??null}let J={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ugyldigt input: forventede instanceof ${W.expected}, fik ${N}`;return`Ugyldigt input: forventede ${K}, fik ${N}`}case"invalid_value":if(W.values.length===1)return`Ugyldig værdi: forventede ${U$(W.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin),N=Q[W.origin]??W.origin;if(X)return`For stor: forventede ${N??"value"} ${X.verb} ${K} ${W.maximum.toString()} ${X.unit??"elementer"}`;return`For stor: forventede ${N??"value"} havde ${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin),N=Q[W.origin]??W.origin;if(X)return`For lille: forventede ${N} ${X.verb} ${K} ${W.minimum.toString()} ${X.unit}`;return`For lille: forventede ${N} havde ${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ugyldig streng: skal starte med "${K.prefix}"`;if(K.format==="ends_with")return`Ugyldig streng: skal ende med "${K.suffix}"`;if(K.format==="includes")return`Ugyldig streng: skal indeholde "${K.includes}"`;if(K.format==="regex")return`Ugyldig streng: skal matche mønsteret ${K.pattern}`;return`Ugyldig ${J[K.format]??W.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${m(W.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${W.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${W.origin}`;default:return"Ugyldigt input"}}};function IH(){return{localeError:g4()}}var b4=()=>{let $={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function U(W){return $[W]??null}let J={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},Q={nan:"NaN",number:"Zahl",array:"Array"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ungültige Eingabe: erwartet instanceof ${W.expected}, erhalten ${N}`;return`Ungültige Eingabe: erwartet ${K}, erhalten ${N}`}case"invalid_value":if(W.values.length===1)return`Ungültige Eingabe: erwartet ${U$(W.values[0])}`;return`Ungültige Option: erwartet eine von ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Zu groß: erwartet, dass ${W.origin??"Wert"} ${K}${W.maximum.toString()} ${X.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${W.origin??"Wert"} ${K}${W.maximum.toString()} ist`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Zu klein: erwartet, dass ${W.origin} ${K}${W.minimum.toString()} ${X.unit} hat`;return`Zu klein: erwartet, dass ${W.origin} ${K}${W.minimum.toString()} ist`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ungültiger String: muss mit "${K.prefix}" beginnen`;if(K.format==="ends_with")return`Ungültiger String: muss mit "${K.suffix}" enden`;if(K.format==="includes")return`Ungültiger String: muss "${K.includes}" enthalten`;if(K.format==="regex")return`Ungültiger String: muss dem Muster ${K.pattern} entsprechen`;return`Ungültig: ${J[K.format]??W.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${W.divisor} sein`;case"unrecognized_keys":return`${W.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${m(W.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${W.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${W.origin}`;default:return"Ungültige Eingabe"}}};function qH(){return{localeError:b4()}}var x4=()=>{let $={string:{unit:"χαρακτήρες",verb:"να έχει"},file:{unit:"bytes",verb:"να έχει"},array:{unit:"στοιχεία",verb:"να έχει"},set:{unit:"στοιχεία",verb:"να έχει"},map:{unit:"καταχωρήσεις",verb:"να έχει"}};function U(W){return $[W]??null}let J={regex:"είσοδος",email:"διεύθυνση email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ημερομηνία και ώρα",date:"ISO ημερομηνία",time:"ISO ώρα",duration:"ISO διάρκεια",ipv4:"διεύθυνση IPv4",ipv6:"διεύθυνση IPv6",mac:"διεύθυνση MAC",cidrv4:"εύρος IPv4",cidrv6:"εύρος IPv6",base64:"συμβολοσειρά κωδικοποιημένη σε base64",base64url:"συμβολοσειρά κωδικοποιημένη σε base64url",json_string:"συμβολοσειρά JSON",e164:"αριθμός E.164",jwt:"JWT",template_literal:"είσοδος"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(typeof W.expected==="string"&&/^[A-Z]/.test(W.expected))return`Μη έγκυρη είσοδος: αναμενόταν instanceof ${W.expected}, λήφθηκε ${N}`;return`Μη έγκυρη είσοδος: αναμενόταν ${K}, λήφθηκε ${N}`}case"invalid_value":if(W.values.length===1)return`Μη έγκυρη είσοδος: αναμενόταν ${U$(W.values[0])}`;return`Μη έγκυρη επιλογή: αναμενόταν ένα από ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Πολύ μεγάλο: αναμενόταν ${W.origin??"τιμή"} να έχει ${K}${W.maximum.toString()} ${X.unit??"στοιχεία"}`;return`Πολύ μεγάλο: αναμενόταν ${W.origin??"τιμή"} να είναι ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Πολύ μικρό: αναμενόταν ${W.origin} να έχει ${K}${W.minimum.toString()} ${X.unit}`;return`Πολύ μικρό: αναμενόταν ${W.origin} να είναι ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${K.prefix}"`;if(K.format==="ends_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${K.suffix}"`;if(K.format==="includes")return`Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${K.includes}"`;if(K.format==="regex")return`Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${K.pattern}`;return`Μη έγκυρο: ${J[K.format]??W.format}`}case"not_multiple_of":return`Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${W.divisor}`;case"unrecognized_keys":return`Άγνωστ${W.keys.length>1?"α":"ο"} κλειδ${W.keys.length>1?"ιά":"ί"}: ${m(W.keys,", ")}`;case"invalid_key":return`Μη έγκυρο κλειδί στο ${W.origin}`;case"invalid_union":return"Μη έγκυρη είσοδος";case"invalid_element":return`Μη έγκυρη τιμή στο ${W.origin}`;default:return"Μη έγκυρη είσοδος"}}};function DH(){return{localeError:x4()}}var y4=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function U(W){return $[W]??null}let J={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;return`Invalid input: expected ${K}, received ${N}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${U$(W.values[0])}`;return`Invalid option: expected one of ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Too big: expected ${W.origin??"value"} to have ${K}${W.maximum.toString()} ${X.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Too small: expected ${W.origin} to have ${K}${W.minimum.toString()} ${X.unit}`;return`Too small: expected ${W.origin} to be ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Invalid string: must start with "${K.prefix}"`;if(K.format==="ends_with")return`Invalid string: must end with "${K.suffix}"`;if(K.format==="includes")return`Invalid string: must include "${K.includes}"`;if(K.format==="regex")return`Invalid string: must match pattern ${K.pattern}`;return`Invalid ${J[K.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":if(W.options&&Array.isArray(W.options)&&W.options.length>0)return`Invalid discriminator value. Expected ${W.options.map((X)=>`'${X}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function T8(){return{localeError:y4()}}var h4=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function U(W){return $[W]??null}let J={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},Q={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Nevalida enigo: atendiĝis instanceof ${W.expected}, riceviĝis ${N}`;return`Nevalida enigo: atendiĝis ${K}, riceviĝis ${N}`}case"invalid_value":if(W.values.length===1)return`Nevalida enigo: atendiĝis ${U$(W.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Tro granda: atendiĝis ke ${W.origin??"valoro"} havu ${K}${W.maximum.toString()} ${X.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${W.origin??"valoro"} havu ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Tro malgranda: atendiĝis ke ${W.origin} havu ${K}${W.minimum.toString()} ${X.unit}`;return`Tro malgranda: atendiĝis ke ${W.origin} estu ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${K.prefix}"`;if(K.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${K.suffix}"`;if(K.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${K.includes}"`;if(K.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${K.pattern}`;return`Nevalida ${J[K.format]??W.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${W.divisor}`;case"unrecognized_keys":return`Nekonata${W.keys.length>1?"j":""} ŝlosilo${W.keys.length>1?"j":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${W.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${W.origin}`;default:return"Nevalida enigo"}}};function kH(){return{localeError:h4()}}var f4=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function U(W){return $[W]??null}let J={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},Q={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Entrada inválida: se esperaba instanceof ${W.expected}, recibido ${N}`;return`Entrada inválida: se esperaba ${K}, recibido ${N}`}case"invalid_value":if(W.values.length===1)return`Entrada inválida: se esperaba ${U$(W.values[0])}`;return`Opción inválida: se esperaba una de ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin),N=Q[W.origin]??W.origin;if(X)return`Demasiado grande: se esperaba que ${N??"valor"} tuviera ${K}${W.maximum.toString()} ${X.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${N??"valor"} fuera ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin),N=Q[W.origin]??W.origin;if(X)return`Demasiado pequeño: se esperaba que ${N} tuviera ${K}${W.minimum.toString()} ${X.unit}`;return`Demasiado pequeño: se esperaba que ${N} fuera ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Cadena inválida: debe comenzar con "${K.prefix}"`;if(K.format==="ends_with")return`Cadena inválida: debe terminar en "${K.suffix}"`;if(K.format==="includes")return`Cadena inválida: debe incluir "${K.includes}"`;if(K.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${K.pattern}`;return`Inválido ${J[K.format]??W.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${W.divisor}`;case"unrecognized_keys":return`Llave${W.keys.length>1?"s":""} desconocida${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Llave inválida en ${Q[W.origin]??W.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${Q[W.origin]??W.origin}`;default:return"Entrada inválida"}}};function FH(){return{localeError:f4()}}var u4=()=>{let $={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function U(W){return $[W]??null}let J={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},Q={nan:"NaN",number:"عدد",array:"آرایه"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`ورودی نامعتبر: میبایست instanceof ${W.expected} میبود، ${N} دریافت شد`;return`ورودی نامعتبر: میبایست ${K} میبود، ${N} دریافت شد`}case"invalid_value":if(W.values.length===1)return`ورودی نامعتبر: میبایست ${U$(W.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${m(W.values,"|")} میبود`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`خیلی بزرگ: ${W.origin??"مقدار"} باید ${K}${W.maximum.toString()} ${X.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${W.origin??"مقدار"} باید ${K}${W.maximum.toString()} باشد`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`خیلی کوچک: ${W.origin} باید ${K}${W.minimum.toString()} ${X.unit} باشد`;return`خیلی کوچک: ${W.origin} باید ${K}${W.minimum.toString()} باشد`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`رشته نامعتبر: باید با "${K.prefix}" شروع شود`;if(K.format==="ends_with")return`رشته نامعتبر: باید با "${K.suffix}" تمام شود`;if(K.format==="includes")return`رشته نامعتبر: باید شامل "${K.includes}" باشد`;if(K.format==="regex")return`رشته نامعتبر: باید با الگوی ${K.pattern} مطابقت داشته باشد`;return`${J[K.format]??W.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${W.divisor} باشد`;case"unrecognized_keys":return`کلید${W.keys.length>1?"های":""} ناشناس: ${m(W.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${W.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${W.origin}`;default:return"ورودی نامعتبر"}}};function LH(){return{localeError:u4()}}var l4=()=>{let $={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function U(W){return $[W]??null}let J={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Virheellinen tyyppi: odotettiin instanceof ${W.expected}, oli ${N}`;return`Virheellinen tyyppi: odotettiin ${K}, oli ${N}`}case"invalid_value":if(W.values.length===1)return`Virheellinen syöte: täytyy olla ${U$(W.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Liian suuri: ${X.subject} täytyy olla ${K}${W.maximum.toString()} ${X.unit}`.trim();return`Liian suuri: arvon täytyy olla ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Liian pieni: ${X.subject} täytyy olla ${K}${W.minimum.toString()} ${X.unit}`.trim();return`Liian pieni: arvon täytyy olla ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${K.prefix}"`;if(K.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${K.suffix}"`;if(K.format==="includes")return`Virheellinen syöte: täytyy sisältää "${K.includes}"`;if(K.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${K.pattern}`;return`Virheellinen ${J[K.format]??W.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${W.divisor} monikerta`;case"unrecognized_keys":return`${W.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${m(W.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function RH(){return{localeError:l4()}}var m4=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(W){return $[W]??null}let J={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},Q={string:"chaîne",number:"nombre",int:"entier",boolean:"booléen",bigint:"grand entier",symbol:"symbole",undefined:"indéfini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Entrée invalide : instanceof ${W.expected} attendu, ${N} reçu`;return`Entrée invalide : ${K} attendu, ${N} reçu`}case"invalid_value":if(W.values.length===1)return`Entrée invalide : ${U$(W.values[0])} attendu`;return`Option invalide : une valeur parmi ${m(W.values,"|")} attendue`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Trop grand : ${Q[W.origin]??"valeur"} doit ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"élément(s)"}`;return`Trop grand : ${Q[W.origin]??"valeur"} doit être ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Trop petit : ${Q[W.origin]??"valeur"} doit ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Trop petit : ${Q[W.origin]??"valeur"} doit être ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Chaîne invalide : doit commencer par "${K.prefix}"`;if(K.format==="ends_with")return`Chaîne invalide : doit se terminer par "${K.suffix}"`;if(K.format==="includes")return`Chaîne invalide : doit inclure "${K.includes}"`;if(K.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${K.pattern}`;return`${J[K.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${W.divisor}`;case"unrecognized_keys":return`Clé${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${m(W.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${W.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entrée invalide"}}};function VH(){return{localeError:m4()}}var p4=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(W){return $[W]??null}let J={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Entrée invalide : attendu instanceof ${W.expected}, reçu ${N}`;return`Entrée invalide : attendu ${K}, reçu ${N}`}case"invalid_value":if(W.values.length===1)return`Entrée invalide : attendu ${U$(W.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"≤":"<",X=U(W.origin);if(X)return`Trop grand : attendu que ${W.origin??"la valeur"} ait ${K}${W.maximum.toString()} ${X.unit}`;return`Trop grand : attendu que ${W.origin??"la valeur"} soit ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?"≥":">",X=U(W.origin);if(X)return`Trop petit : attendu que ${W.origin} ait ${K}${W.minimum.toString()} ${X.unit}`;return`Trop petit : attendu que ${W.origin} soit ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Chaîne invalide : doit commencer par "${K.prefix}"`;if(K.format==="ends_with")return`Chaîne invalide : doit se terminer par "${K.suffix}"`;if(K.format==="includes")return`Chaîne invalide : doit inclure "${K.includes}"`;if(K.format==="regex")return`Chaîne invalide : doit correspondre au motif ${K.pattern}`;return`${J[K.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${W.divisor}`;case"unrecognized_keys":return`Clé${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${m(W.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${W.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entrée invalide"}}};function wH(){return{localeError:p4()}}var d4=()=>{let $={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},U={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},J=(Y)=>Y?$[Y]:void 0,Q=(Y)=>{let G=J(Y);if(G)return G.label;return Y??$.unknown.label},W=(Y)=>`ה${Q(Y)}`,K=(Y)=>{return(J(Y)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},X=(Y)=>{if(!Y)return null;return U[Y]??null},N={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},H={nan:"NaN"};return(Y)=>{switch(Y.code){case"invalid_type":{let G=Y.expected,O=H[G??""]??Q(G),E=W$(Y.input),Z=H[E]??$[E]?.label??E;if(/^[A-Z]/.test(Y.expected))return`קלט לא תקין: צריך להיות instanceof ${Y.expected}, התקבל ${Z}`;return`קלט לא תקין: צריך להיות ${O}, התקבל ${Z}`}case"invalid_value":{if(Y.values.length===1)return`ערך לא תקין: הערך חייב להיות ${U$(Y.values[0])}`;let G=Y.values.map((Z)=>U$(Z));if(Y.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${G[0]} או ${G[1]}`;let O=G[G.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${G.slice(0,-1).join(", ")} או ${O}`}case"too_big":{let G=X(Y.origin),O=W(Y.origin??"value");if(Y.origin==="string")return`${G?.longLabel??"ארוך"} מדי: ${O} צריכה להכיל ${Y.maximum.toString()} ${G?.unit??""} ${Y.inclusive?"או פחות":"לכל היותר"}`.trim();if(Y.origin==="number"){let D=Y.inclusive?`קטן או שווה ל-${Y.maximum}`:`קטן מ-${Y.maximum}`;return`גדול מדי: ${O} צריך להיות ${D}`}if(Y.origin==="array"||Y.origin==="set"){let D=Y.origin==="set"?"צריכה":"צריך",R=Y.inclusive?`${Y.maximum} ${G?.unit??""} או פחות`:`פחות מ-${Y.maximum} ${G?.unit??""}`;return`גדול מדי: ${O} ${D} להכיל ${R}`.trim()}let E=Y.inclusive?"<=":"<",Z=K(Y.origin??"value");if(G?.unit)return`${G.longLabel} מדי: ${O} ${Z} ${E}${Y.maximum.toString()} ${G.unit}`;return`${G?.longLabel??"גדול"} מדי: ${O} ${Z} ${E}${Y.maximum.toString()}`}case"too_small":{let G=X(Y.origin),O=W(Y.origin??"value");if(Y.origin==="string")return`${G?.shortLabel??"קצר"} מדי: ${O} צריכה להכיל ${Y.minimum.toString()} ${G?.unit??""} ${Y.inclusive?"או יותר":"לפחות"}`.trim();if(Y.origin==="number"){let D=Y.inclusive?`גדול או שווה ל-${Y.minimum}`:`גדול מ-${Y.minimum}`;return`קטן מדי: ${O} צריך להיות ${D}`}if(Y.origin==="array"||Y.origin==="set"){let D=Y.origin==="set"?"צריכה":"צריך";if(Y.minimum===1&&Y.inclusive){let I=Y.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${O} ${D} להכיל ${I}`}let R=Y.inclusive?`${Y.minimum} ${G?.unit??""} או יותר`:`יותר מ-${Y.minimum} ${G?.unit??""}`;return`קטן מדי: ${O} ${D} להכיל ${R}`.trim()}let E=Y.inclusive?">=":">",Z=K(Y.origin??"value");if(G?.unit)return`${G.shortLabel} מדי: ${O} ${Z} ${E}${Y.minimum.toString()} ${G.unit}`;return`${G?.shortLabel??"קטן"} מדי: ${O} ${Z} ${E}${Y.minimum.toString()}`}case"invalid_format":{let G=Y;if(G.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${G.prefix}"`;if(G.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${G.suffix}"`;if(G.format==="includes")return`המחרוזת חייבת לכלול "${G.includes}"`;if(G.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${G.pattern}`;let O=N[G.format],E=O?.label??G.format,D=(O?.gender??"m")==="f"?"תקינה":"תקין";return`${E} לא ${D}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${Y.divisor}`;case"unrecognized_keys":return`מפתח${Y.keys.length>1?"ות":""} לא מזוה${Y.keys.length>1?"ים":"ה"}: ${m(Y.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${W(Y.origin??"array")}`;default:return"קלט לא תקין"}}};function MH(){return{localeError:d4()}}var c4=()=>{let $={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function U(W){return $[W]??null}let J={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},Q={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Neispravan unos: očekuje se instanceof ${W.expected}, a primljeno je ${N}`;return`Neispravan unos: očekuje se ${K}, a primljeno je ${N}`}case"invalid_value":if(W.values.length===1)return`Neispravna vrijednost: očekivano ${U$(W.values[0])}`;return`Neispravna opcija: očekivano jedno od ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin),N=Q[W.origin]??W.origin;if(X)return`Preveliko: očekivano da ${N??"vrijednost"} ima ${K}${W.maximum.toString()} ${X.unit??"elemenata"}`;return`Preveliko: očekivano da ${N??"vrijednost"} bude ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin),N=Q[W.origin]??W.origin;if(X)return`Premalo: očekivano da ${N} ima ${K}${W.minimum.toString()} ${X.unit}`;return`Premalo: očekivano da ${N} bude ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Neispravan tekst: mora započinjati s "${K.prefix}"`;if(K.format==="ends_with")return`Neispravan tekst: mora završavati s "${K.suffix}"`;if(K.format==="includes")return`Neispravan tekst: mora sadržavati "${K.includes}"`;if(K.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${K.pattern}`;return`Neispravna ${J[K.format]??W.format}`}case"not_multiple_of":return`Neispravan broj: mora biti višekratnik od ${W.divisor}`;case"unrecognized_keys":return`Neprepoznat${W.keys.length>1?"i ključevi":" ključ"}: ${m(W.keys,", ")}`;case"invalid_key":return`Neispravan ključ u ${Q[W.origin]??W.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${Q[W.origin]??W.origin}`;default:return"Neispravan unos"}}};function BH(){return{localeError:c4()}}var n4=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function U(W){return $[W]??null}let J={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},Q={nan:"NaN",number:"szám",array:"tömb"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Érvénytelen bemenet: a várt érték instanceof ${W.expected}, a kapott érték ${N}`;return`Érvénytelen bemenet: a várt érték ${K}, a kapott érték ${N}`}case"invalid_value":if(W.values.length===1)return`Érvénytelen bemenet: a várt érték ${U$(W.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Túl nagy: ${W.origin??"érték"} mérete túl nagy ${K}${W.maximum.toString()} ${X.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${W.origin??"érték"} túl nagy: ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Túl kicsi: a bemeneti érték ${W.origin} mérete túl kicsi ${K}${W.minimum.toString()} ${X.unit}`;return`Túl kicsi: a bemeneti érték ${W.origin} túl kicsi ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Érvénytelen string: "${K.prefix}" értékkel kell kezdődnie`;if(K.format==="ends_with")return`Érvénytelen string: "${K.suffix}" értékkel kell végződnie`;if(K.format==="includes")return`Érvénytelen string: "${K.includes}" értéket kell tartalmaznia`;if(K.format==="regex")return`Érvénytelen string: ${K.pattern} mintának kell megfelelnie`;return`Érvénytelen ${J[K.format]??W.format}`}case"not_multiple_of":return`Érvénytelen szám: ${W.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${W.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${W.origin}`;default:return"Érvénytelen bemenet"}}};function PH(){return{localeError:n4()}}function YI($,U,J){return Math.abs($)===1?U:J}function HW($){if(!$)return"";let U=["ա","ե","ը","ի","ո","ու","օ"],J=$[$.length-1];return $+(U.includes(J)?"ն":"ը")}var i4=()=>{let $={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function U(W){return $[W]??null}let J={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},Q={nan:"NaN",number:"թիվ",array:"զանգված"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${W.expected}, ստացվել է ${N}`;return`Սխալ մուտքագրում․ սպասվում էր ${K}, ստացվել է ${N}`}case"invalid_value":if(W.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${U$(W.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X){let N=Number(W.maximum),H=YI(N,X.unit.one,X.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${HW(W.origin??"արժեք")} կունենա ${K}${W.maximum.toString()} ${H}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${HW(W.origin??"արժեք")} լինի ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X){let N=Number(W.minimum),H=YI(N,X.unit.one,X.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${HW(W.origin)} կունենա ${K}${W.minimum.toString()} ${H}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${HW(W.origin)} լինի ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${K.prefix}"-ով`;if(K.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${K.suffix}"-ով`;if(K.format==="includes")return`Սխալ տող․ պետք է պարունակի "${K.includes}"`;if(K.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${K.pattern} ձևաչափին`;return`Սխալ ${J[K.format]??W.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${W.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${W.keys.length>1?"ներ":""}. ${m(W.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${HW(W.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${HW(W.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function zH(){return{localeError:i4()}}var o4=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function U(W){return $[W]??null}let J={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Input tidak valid: diharapkan instanceof ${W.expected}, diterima ${N}`;return`Input tidak valid: diharapkan ${K}, diterima ${N}`}case"invalid_value":if(W.values.length===1)return`Input tidak valid: diharapkan ${U$(W.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Terlalu besar: diharapkan ${W.origin??"value"} memiliki ${K}${W.maximum.toString()} ${X.unit??"elemen"}`;return`Terlalu besar: diharapkan ${W.origin??"value"} menjadi ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Terlalu kecil: diharapkan ${W.origin} memiliki ${K}${W.minimum.toString()} ${X.unit}`;return`Terlalu kecil: diharapkan ${W.origin} menjadi ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`String tidak valid: harus dimulai dengan "${K.prefix}"`;if(K.format==="ends_with")return`String tidak valid: harus berakhir dengan "${K.suffix}"`;if(K.format==="includes")return`String tidak valid: harus menyertakan "${K.includes}"`;if(K.format==="regex")return`String tidak valid: harus sesuai pola ${K.pattern}`;return`${J[K.format]??W.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${W.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${W.origin}`;default:return"Input tidak valid"}}};function _H(){return{localeError:o4()}}var r4=()=>{let $={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function U(W){return $[W]??null}let J={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},Q={nan:"NaN",number:"númer",array:"fylki"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Rangt gildi: Þú slóst inn ${N} þar sem á að vera instanceof ${W.expected}`;return`Rangt gildi: Þú slóst inn ${N} þar sem á að vera ${K}`}case"invalid_value":if(W.values.length===1)return`Rangt gildi: gert ráð fyrir ${U$(W.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Of stórt: gert er ráð fyrir að ${W.origin??"gildi"} hafi ${K}${W.maximum.toString()} ${X.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${W.origin??"gildi"} sé ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Of lítið: gert er ráð fyrir að ${W.origin} hafi ${K}${W.minimum.toString()} ${X.unit}`;return`Of lítið: gert er ráð fyrir að ${W.origin} sé ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ógildur strengur: verður að byrja á "${K.prefix}"`;if(K.format==="ends_with")return`Ógildur strengur: verður að enda á "${K.suffix}"`;if(K.format==="includes")return`Ógildur strengur: verður að innihalda "${K.includes}"`;if(K.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${K.pattern}`;return`Rangt ${J[K.format]??W.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${W.divisor}`;case"unrecognized_keys":return`Óþekkt ${W.keys.length>1?"ir lyklar":"ur lykill"}: ${m(W.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${W.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${W.origin}`;default:return"Rangt gildi"}}};function AH(){return{localeError:r4()}}var a4=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function U(W){return $[W]??null}let J={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"numero",array:"vettore"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Input non valido: atteso instanceof ${W.expected}, ricevuto ${N}`;return`Input non valido: atteso ${K}, ricevuto ${N}`}case"invalid_value":if(W.values.length===1)return`Input non valido: atteso ${U$(W.values[0])}`;return`Opzione non valida: atteso uno tra ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Troppo grande: ${W.origin??"valore"} deve avere ${K}${W.maximum.toString()} ${X.unit??"elementi"}`;return`Troppo grande: ${W.origin??"valore"} deve essere ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Troppo piccolo: ${W.origin} deve avere ${K}${W.minimum.toString()} ${X.unit}`;return`Troppo piccolo: ${W.origin} deve essere ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Stringa non valida: deve iniziare con "${K.prefix}"`;if(K.format==="ends_with")return`Stringa non valida: deve terminare con "${K.suffix}"`;if(K.format==="includes")return`Stringa non valida: deve includere "${K.includes}"`;if(K.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${K.pattern}`;return`Input non valido: ${J[K.format]??W.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${W.divisor}`;case"unrecognized_keys":return`Chiav${W.keys.length>1?"i":"e"} non riconosciut${W.keys.length>1?"e":"a"}: ${m(W.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${W.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${W.origin}`;default:return"Input non valido"}}};function CH(){return{localeError:a4()}}var s4=()=>{let $={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function U(W){return $[W]??null}let J={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},Q={nan:"NaN",number:"数値",array:"配列"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`無効な入力: instanceof ${W.expected}が期待されましたが、${N}が入力されました`;return`無効な入力: ${K}が期待されましたが、${N}が入力されました`}case"invalid_value":if(W.values.length===1)return`無効な入力: ${U$(W.values[0])}が期待されました`;return`無効な選択: ${m(W.values,"、")}のいずれかである必要があります`;case"too_big":{let K=W.inclusive?"以下である":"より小さい",X=U(W.origin);if(X)return`大きすぎる値: ${W.origin??"値"}は${W.maximum.toString()}${X.unit??"要素"}${K}必要があります`;return`大きすぎる値: ${W.origin??"値"}は${W.maximum.toString()}${K}必要があります`}case"too_small":{let K=W.inclusive?"以上である":"より大きい",X=U(W.origin);if(X)return`小さすぎる値: ${W.origin}は${W.minimum.toString()}${X.unit}${K}必要があります`;return`小さすぎる値: ${W.origin}は${W.minimum.toString()}${K}必要があります`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`無効な文字列: "${K.prefix}"で始まる必要があります`;if(K.format==="ends_with")return`無効な文字列: "${K.suffix}"で終わる必要があります`;if(K.format==="includes")return`無効な文字列: "${K.includes}"を含む必要があります`;if(K.format==="regex")return`無効な文字列: パターン${K.pattern}に一致する必要があります`;return`無効な${J[K.format]??W.format}`}case"not_multiple_of":return`無効な数値: ${W.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${W.keys.length>1?"群":""}: ${m(W.keys,"、")}`;case"invalid_key":return`${W.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${W.origin}内の無効な値`;default:return"無効な入力"}}};function SH(){return{localeError:s4()}}var t4=()=>{let $={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function U(W){return $[W]??null}let J={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული ველი",base64url:"base64url-კოდირებული ველი",json_string:"JSON ველი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},Q={nan:"NaN",number:"რიცხვი",string:"ველი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${W.expected}, მიღებული ${N}`;return`არასწორი შეყვანა: მოსალოდნელი ${K}, მიღებული ${N}`}case"invalid_value":if(W.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${U$(W.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${m(W.values,"|")}-დან`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`ზედმეტად დიდი: მოსალოდნელი ${W.origin??"მნიშვნელობა"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${W.origin??"მნიშვნელობა"} იყოს ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`ზედმეტად პატარა: მოსალოდნელი ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${W.origin} იყოს ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`არასწორი ველი: უნდა იწყებოდეს "${K.prefix}"-ით`;if(K.format==="ends_with")return`არასწორი ველი: უნდა მთავრდებოდეს "${K.suffix}"-ით`;if(K.format==="includes")return`არასწორი ველი: უნდა შეიცავდეს "${K.includes}"-ს`;if(K.format==="regex")return`არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${K.pattern}`;return`არასწორი ${J[K.format]??W.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${W.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${W.keys.length>1?"ები":"ი"}: ${m(W.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${W.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${W.origin}-ში`;default:return"არასწორი შეყვანა"}}};function TH(){return{localeError:t4()}}var e4=()=>{let $={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function U(W){return $[W]??null}let J={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},Q={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${W.expected} ប៉ុន្តែទទួលបាន ${N}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${K} ប៉ុន្តែទទួលបាន ${N}`}case"invalid_value":if(W.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${U$(W.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`ធំពេក៖ ត្រូវការ ${W.origin??"តម្លៃ"} ${K} ${W.maximum.toString()} ${X.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${W.origin??"តម្លៃ"} ${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`តូចពេក៖ ត្រូវការ ${W.origin} ${K} ${W.minimum.toString()} ${X.unit}`;return`តូចពេក៖ ត្រូវការ ${W.origin} ${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${K.prefix}"`;if(K.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${K.suffix}"`;if(K.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${K.includes}"`;if(K.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${K.pattern}`;return`មិនត្រឹមត្រូវ៖ ${J[K.format]??W.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${W.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${m(W.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${W.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${W.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function v8(){return{localeError:e4()}}function vH(){return v8()}var $L=()=>{let $={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function U(W){return $[W]??null}let J={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`잘못된 입력: 예상 타입은 instanceof ${W.expected}, 받은 타입은 ${N}입니다`;return`잘못된 입력: 예상 타입은 ${K}, 받은 타입은 ${N}입니다`}case"invalid_value":if(W.values.length===1)return`잘못된 입력: 값은 ${U$(W.values[0])} 이어야 합니다`;return`잘못된 옵션: ${m(W.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let K=W.inclusive?"이하":"미만",X=K==="미만"?"이어야 합니다":"여야 합니다",N=U(W.origin),H=N?.unit??"요소";if(N)return`${W.origin??"값"}이 너무 큽니다: ${W.maximum.toString()}${H} ${K}${X}`;return`${W.origin??"값"}이 너무 큽니다: ${W.maximum.toString()} ${K}${X}`}case"too_small":{let K=W.inclusive?"이상":"초과",X=K==="이상"?"이어야 합니다":"여야 합니다",N=U(W.origin),H=N?.unit??"요소";if(N)return`${W.origin??"값"}이 너무 작습니다: ${W.minimum.toString()}${H} ${K}${X}`;return`${W.origin??"값"}이 너무 작습니다: ${W.minimum.toString()} ${K}${X}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`잘못된 문자열: "${K.prefix}"(으)로 시작해야 합니다`;if(K.format==="ends_with")return`잘못된 문자열: "${K.suffix}"(으)로 끝나야 합니다`;if(K.format==="includes")return`잘못된 문자열: "${K.includes}"을(를) 포함해야 합니다`;if(K.format==="regex")return`잘못된 문자열: 정규식 ${K.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${J[K.format]??W.format}`}case"not_multiple_of":return`잘못된 숫자: ${W.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${m(W.keys,", ")}`;case"invalid_key":return`잘못된 키: ${W.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${W.origin}`;default:return"잘못된 입력"}}};function jH(){return{localeError:$L()}}var j8=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function GI($){let U=Math.abs($),J=U%10,Q=U%100;if(Q>=11&&Q<=19||J===0)return"many";if(J===1)return"one";return"few"}var UL=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function U(W,K,X,N){let H=$[W]??null;if(H===null)return H;return{unit:H.unit[K],verb:H.verb[N][X?"inclusive":"notInclusive"]}}let J={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},Q={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Gautas tipas ${N}, o tikėtasi - instanceof ${W.expected}`;return`Gautas tipas ${N}, o tikėtasi - ${K}`}case"invalid_value":if(W.values.length===1)return`Privalo būti ${U$(W.values[0])}`;return`Privalo būti vienas iš ${m(W.values,"|")} pasirinkimų`;case"too_big":{let K=Q[W.origin]??W.origin,X=U(W.origin,GI(Number(W.maximum)),W.inclusive??!1,"smaller");if(X?.verb)return`${j8(K??W.origin??"reikšmė")} ${X.verb} ${W.maximum.toString()} ${X.unit??"elementų"}`;let N=W.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${j8(K??W.origin??"reikšmė")} turi būti ${N} ${W.maximum.toString()} ${X?.unit}`}case"too_small":{let K=Q[W.origin]??W.origin,X=U(W.origin,GI(Number(W.minimum)),W.inclusive??!1,"bigger");if(X?.verb)return`${j8(K??W.origin??"reikšmė")} ${X.verb} ${W.minimum.toString()} ${X.unit??"elementų"}`;let N=W.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${j8(K??W.origin??"reikšmė")} turi būti ${N} ${W.minimum.toString()} ${X?.unit}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Eilutė privalo prasidėti "${K.prefix}"`;if(K.format==="ends_with")return`Eilutė privalo pasibaigti "${K.suffix}"`;if(K.format==="includes")return`Eilutė privalo įtraukti "${K.includes}"`;if(K.format==="regex")return`Eilutė privalo atitikti ${K.pattern}`;return`Neteisingas ${J[K.format]??W.format}`}case"not_multiple_of":return`Skaičius privalo būti ${W.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${W.keys.length>1?"i":"as"} rakt${W.keys.length>1?"ai":"as"}: ${m(W.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let K=Q[W.origin]??W.origin;return`${j8(K??W.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function gH(){return{localeError:UL()}}var JL=()=>{let $={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function U(W){return $[W]??null}let J={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},Q={nan:"NaN",number:"број",array:"низа"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Грешен внес: се очекува instanceof ${W.expected}, примено ${N}`;return`Грешен внес: се очекува ${K}, примено ${N}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${U$(W.values[0])}`;return`Грешана опција: се очекува една ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Премногу голем: се очекува ${W.origin??"вредноста"} да има ${K}${W.maximum.toString()} ${X.unit??"елементи"}`;return`Премногу голем: се очекува ${W.origin??"вредноста"} да биде ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Премногу мал: се очекува ${W.origin} да има ${K}${W.minimum.toString()} ${X.unit}`;return`Премногу мал: се очекува ${W.origin} да биде ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Неважечка низа: мора да започнува со "${K.prefix}"`;if(K.format==="ends_with")return`Неважечка низа: мора да завршува со "${K.suffix}"`;if(K.format==="includes")return`Неважечка низа: мора да вклучува "${K.includes}"`;if(K.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${K.pattern}`;return`Invalid ${J[K.format]??W.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${m(W.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${W.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${W.origin}`;default:return"Грешен внес"}}};function bH(){return{localeError:JL()}}var WL=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function U(W){return $[W]??null}let J={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"nombor"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Input tidak sah: dijangka instanceof ${W.expected}, diterima ${N}`;return`Input tidak sah: dijangka ${K}, diterima ${N}`}case"invalid_value":if(W.values.length===1)return`Input tidak sah: dijangka ${U$(W.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Terlalu besar: dijangka ${W.origin??"nilai"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"elemen"}`;return`Terlalu besar: dijangka ${W.origin??"nilai"} adalah ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Terlalu kecil: dijangka ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Terlalu kecil: dijangka ${W.origin} adalah ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`String tidak sah: mesti bermula dengan "${K.prefix}"`;if(K.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${K.suffix}"`;if(K.format==="includes")return`String tidak sah: mesti mengandungi "${K.includes}"`;if(K.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${K.pattern}`;return`${J[K.format]??W.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${m(W.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${W.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${W.origin}`;default:return"Input tidak sah"}}};function xH(){return{localeError:WL()}}var QL=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function U(W){return $[W]??null}let J={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},Q={nan:"NaN",number:"getal"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ongeldige invoer: verwacht instanceof ${W.expected}, ontving ${N}`;return`Ongeldige invoer: verwacht ${K}, ontving ${N}`}case"invalid_value":if(W.values.length===1)return`Ongeldige invoer: verwacht ${U$(W.values[0])}`;return`Ongeldige optie: verwacht één van ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin),N=W.origin==="date"?"laat":W.origin==="string"?"lang":"groot";if(X)return`Te ${N}: verwacht dat ${W.origin??"waarde"} ${K}${W.maximum.toString()} ${X.unit??"elementen"} ${X.verb}`;return`Te ${N}: verwacht dat ${W.origin??"waarde"} ${K}${W.maximum.toString()} is`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin),N=W.origin==="date"?"vroeg":W.origin==="string"?"kort":"klein";if(X)return`Te ${N}: verwacht dat ${W.origin} ${K}${W.minimum.toString()} ${X.unit} ${X.verb}`;return`Te ${N}: verwacht dat ${W.origin} ${K}${W.minimum.toString()} is`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ongeldige tekst: moet met "${K.prefix}" beginnen`;if(K.format==="ends_with")return`Ongeldige tekst: moet op "${K.suffix}" eindigen`;if(K.format==="includes")return`Ongeldige tekst: moet "${K.includes}" bevatten`;if(K.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${K.pattern}`;return`Ongeldig: ${J[K.format]??W.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${W.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${W.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${W.origin}`;default:return"Ongeldige invoer"}}};function yH(){return{localeError:QL()}}var KL=()=>{let $={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function U(W){return $[W]??null}let J={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"tall",array:"liste"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ugyldig input: forventet instanceof ${W.expected}, fikk ${N}`;return`Ugyldig input: forventet ${K}, fikk ${N}`}case"invalid_value":if(W.values.length===1)return`Ugyldig verdi: forventet ${U$(W.values[0])}`;return`Ugyldig valg: forventet en av ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`For stor(t): forventet ${W.origin??"value"} til å ha ${K}${W.maximum.toString()} ${X.unit??"elementer"}`;return`For stor(t): forventet ${W.origin??"value"} til å ha ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`For lite(n): forventet ${W.origin} til å ha ${K}${W.minimum.toString()} ${X.unit}`;return`For lite(n): forventet ${W.origin} til å ha ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ugyldig streng: må starte med "${K.prefix}"`;if(K.format==="ends_with")return`Ugyldig streng: må ende med "${K.suffix}"`;if(K.format==="includes")return`Ugyldig streng: må inneholde "${K.includes}"`;if(K.format==="regex")return`Ugyldig streng: må matche mønsteret ${K.pattern}`;return`Ugyldig ${J[K.format]??W.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${m(W.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${W.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${W.origin}`;default:return"Ugyldig input"}}};function hH(){return{localeError:KL()}}var XL=()=>{let $={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function U(W){return $[W]??null}let J={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},Q={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Fâsit giren: umulan instanceof ${W.expected}, alınan ${N}`;return`Fâsit giren: umulan ${K}, alınan ${N}`}case"invalid_value":if(W.values.length===1)return`Fâsit giren: umulan ${U$(W.values[0])}`;return`Fâsit tercih: mûteberler ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Fazla büyük: ${W.origin??"value"}, ${K}${W.maximum.toString()} ${X.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${W.origin??"value"}, ${K}${W.maximum.toString()} olmalıydı.`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Fazla küçük: ${W.origin}, ${K}${W.minimum.toString()} ${X.unit} sahip olmalıydı.`;return`Fazla küçük: ${W.origin}, ${K}${W.minimum.toString()} olmalıydı.`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Fâsit metin: "${K.prefix}" ile başlamalı.`;if(K.format==="ends_with")return`Fâsit metin: "${K.suffix}" ile bitmeli.`;if(K.format==="includes")return`Fâsit metin: "${K.includes}" ihtivâ etmeli.`;if(K.format==="regex")return`Fâsit metin: ${K.pattern} nakşına uymalı.`;return`Fâsit ${J[K.format]??W.format}`}case"not_multiple_of":return`Fâsit sayı: ${W.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${W.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function fH(){return{localeError:XL()}}var NL=()=>{let $={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function U(W){return $[W]??null}let J={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},Q={nan:"NaN",number:"عدد",array:"ارې"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`ناسم ورودي: باید instanceof ${W.expected} وای, مګر ${N} ترلاسه شو`;return`ناسم ورودي: باید ${K} وای, مګر ${N} ترلاسه شو`}case"invalid_value":if(W.values.length===1)return`ناسم ورودي: باید ${U$(W.values[0])} وای`;return`ناسم انتخاب: باید یو له ${m(W.values,"|")} څخه وای`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`ډیر لوی: ${W.origin??"ارزښت"} باید ${K}${W.maximum.toString()} ${X.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${W.origin??"ارزښت"} باید ${K}${W.maximum.toString()} وي`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`ډیر کوچنی: ${W.origin} باید ${K}${W.minimum.toString()} ${X.unit} ولري`;return`ډیر کوچنی: ${W.origin} باید ${K}${W.minimum.toString()} وي`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`ناسم متن: باید د "${K.prefix}" سره پیل شي`;if(K.format==="ends_with")return`ناسم متن: باید د "${K.suffix}" سره پای ته ورسيږي`;if(K.format==="includes")return`ناسم متن: باید "${K.includes}" ولري`;if(K.format==="regex")return`ناسم متن: باید د ${K.pattern} سره مطابقت ولري`;return`${J[K.format]??W.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${W.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${W.keys.length>1?"کلیډونه":"کلیډ"}: ${m(W.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${W.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${W.origin} کې`;default:return"ناسمه ورودي"}}};function uH(){return{localeError:NL()}}var HL=()=>{let $={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function U(W){return $[W]??null}let J={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},Q={nan:"NaN",number:"liczba",array:"tablica"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${W.expected}, otrzymano ${N}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${K}, otrzymano ${N}`}case"invalid_value":if(W.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${U$(W.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Za duża wartość: oczekiwano, że ${W.origin??"wartość"} będzie mieć ${K}${W.maximum.toString()} ${X.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${W.origin??"wartość"} będzie wynosić ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Za mała wartość: oczekiwano, że ${W.origin??"wartość"} będzie mieć ${K}${W.minimum.toString()} ${X.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${W.origin??"wartość"} będzie wynosić ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${K.prefix}"`;if(K.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${K.suffix}"`;if(K.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${K.includes}"`;if(K.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${K.pattern}`;return`Nieprawidłow(y/a/e) ${J[K.format]??W.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${W.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${W.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${W.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function lH(){return{localeError:HL()}}var YL=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function U(W){return $[W]??null}let J={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},Q={nan:"NaN",number:"número",null:"nulo"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Tipo inválido: esperado instanceof ${W.expected}, recebido ${N}`;return`Tipo inválido: esperado ${K}, recebido ${N}`}case"invalid_value":if(W.values.length===1)return`Entrada inválida: esperado ${U$(W.values[0])}`;return`Opção inválida: esperada uma das ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Muito grande: esperado que ${W.origin??"valor"} tivesse ${K}${W.maximum.toString()} ${X.unit??"elementos"}`;return`Muito grande: esperado que ${W.origin??"valor"} fosse ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Muito pequeno: esperado que ${W.origin} tivesse ${K}${W.minimum.toString()} ${X.unit}`;return`Muito pequeno: esperado que ${W.origin} fosse ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Texto inválido: deve começar com "${K.prefix}"`;if(K.format==="ends_with")return`Texto inválido: deve terminar com "${K.suffix}"`;if(K.format==="includes")return`Texto inválido: deve incluir "${K.includes}"`;if(K.format==="regex")return`Texto inválido: deve corresponder ao padrão ${K.pattern}`;return`${J[K.format]??W.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${W.divisor}`;case"unrecognized_keys":return`Chave${W.keys.length>1?"s":""} desconhecida${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Chave inválida em ${W.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${W.origin}`;default:return"Campo inválido"}}};function mH(){return{localeError:YL()}}var GL=()=>{let $={string:{unit:"caractere",verb:"să aibă"},file:{unit:"octeți",verb:"să aibă"},array:{unit:"elemente",verb:"să aibă"},set:{unit:"elemente",verb:"să aibă"},map:{unit:"intrări",verb:"să aibă"}};function U(W){return $[W]??null}let J={regex:"intrare",email:"adresă de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dată și oră ISO",date:"dată ISO",time:"oră ISO",duration:"durată ISO",ipv4:"adresă IPv4",ipv6:"adresă IPv6",mac:"adresă MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"șir codat base64",base64url:"șir codat base64url",json_string:"șir JSON",e164:"număr E.164",jwt:"JWT",template_literal:"intrare"},Q={nan:"NaN",string:"șir",number:"număr",boolean:"boolean",function:"funcție",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"număr mare",void:"void",never:"never",map:"hartă",set:"set"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;return`Intrare invalidă: așteptat ${K}, primit ${N}`}case"invalid_value":if(W.values.length===1)return`Intrare invalidă: așteptat ${U$(W.values[0])}`;return`Opțiune invalidă: așteptat una dintre ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Prea mare: așteptat ca ${W.origin??"valoarea"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"elemente"}`;return`Prea mare: așteptat ca ${W.origin??"valoarea"} să fie ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Prea mic: așteptat ca ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Prea mic: așteptat ca ${W.origin} să fie ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Șir invalid: trebuie să înceapă cu "${K.prefix}"`;if(K.format==="ends_with")return`Șir invalid: trebuie să se termine cu "${K.suffix}"`;if(K.format==="includes")return`Șir invalid: trebuie să includă "${K.includes}"`;if(K.format==="regex")return`Șir invalid: trebuie să se potrivească cu modelul ${K.pattern}`;return`Format invalid: ${J[K.format]??W.format}`}case"not_multiple_of":return`Număr invalid: trebuie să fie multiplu de ${W.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${m(W.keys,", ")}`;case"invalid_key":return`Cheie invalidă în ${W.origin}`;case"invalid_union":return"Intrare invalidă";case"invalid_element":return`Valoare invalidă în ${W.origin}`;default:return"Intrare invalidă"}}};function pH(){return{localeError:GL()}}function OI($,U,J,Q){let W=Math.abs($),K=W%10,X=W%100;if(X>=11&&X<=19)return Q;if(K===1)return U;if(K>=2&&K<=4)return J;return Q}var OL=()=>{let $={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function U(W){return $[W]??null}let J={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},Q={nan:"NaN",number:"число",array:"массив"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Неверный ввод: ожидалось instanceof ${W.expected}, получено ${N}`;return`Неверный ввод: ожидалось ${K}, получено ${N}`}case"invalid_value":if(W.values.length===1)return`Неверный ввод: ожидалось ${U$(W.values[0])}`;return`Неверный вариант: ожидалось одно из ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X){let N=Number(W.maximum),H=OI(N,X.unit.one,X.unit.few,X.unit.many);return`Слишком большое значение: ожидалось, что ${W.origin??"значение"} будет иметь ${K}${W.maximum.toString()} ${H}`}return`Слишком большое значение: ожидалось, что ${W.origin??"значение"} будет ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X){let N=Number(W.minimum),H=OI(N,X.unit.one,X.unit.few,X.unit.many);return`Слишком маленькое значение: ожидалось, что ${W.origin} будет иметь ${K}${W.minimum.toString()} ${H}`}return`Слишком маленькое значение: ожидалось, что ${W.origin} будет ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Неверная строка: должна начинаться с "${K.prefix}"`;if(K.format==="ends_with")return`Неверная строка: должна заканчиваться на "${K.suffix}"`;if(K.format==="includes")return`Неверная строка: должна содержать "${K.includes}"`;if(K.format==="regex")return`Неверная строка: должна соответствовать шаблону ${K.pattern}`;return`Неверный ${J[K.format]??W.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${W.divisor}`;case"unrecognized_keys":return`Нераспознанн${W.keys.length>1?"ые":"ый"} ключ${W.keys.length>1?"и":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${W.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${W.origin}`;default:return"Неверные входные данные"}}};function dH(){return{localeError:OL()}}var EL=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function U(W){return $[W]??null}let J={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},Q={nan:"NaN",number:"število",array:"tabela"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Neveljaven vnos: pričakovano instanceof ${W.expected}, prejeto ${N}`;return`Neveljaven vnos: pričakovano ${K}, prejeto ${N}`}case"invalid_value":if(W.values.length===1)return`Neveljaven vnos: pričakovano ${U$(W.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Preveliko: pričakovano, da bo ${W.origin??"vrednost"} imelo ${K}${W.maximum.toString()} ${X.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${W.origin??"vrednost"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Premajhno: pričakovano, da bo ${W.origin} imelo ${K}${W.minimum.toString()} ${X.unit}`;return`Premajhno: pričakovano, da bo ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Neveljaven niz: mora se začeti z "${K.prefix}"`;if(K.format==="ends_with")return`Neveljaven niz: mora se končati z "${K.suffix}"`;if(K.format==="includes")return`Neveljaven niz: mora vsebovati "${K.includes}"`;if(K.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${K.pattern}`;return`Neveljaven ${J[K.format]??W.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${W.divisor}`;case"unrecognized_keys":return`Neprepoznan${W.keys.length>1?"i ključi":" ključ"}: ${m(W.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${W.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${W.origin}`;default:return"Neveljaven vnos"}}};function cH(){return{localeError:EL()}}var ZL=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function U(W){return $[W]??null}let J={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},Q={nan:"NaN",number:"antal",array:"lista"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ogiltig inmatning: förväntat instanceof ${W.expected}, fick ${N}`;return`Ogiltig inmatning: förväntat ${K}, fick ${N}`}case"invalid_value":if(W.values.length===1)return`Ogiltig inmatning: förväntat ${U$(W.values[0])}`;return`Ogiltigt val: förväntade en av ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`För stor(t): förväntade ${W.origin??"värdet"} att ha ${K}${W.maximum.toString()} ${X.unit??"element"}`;return`För stor(t): förväntat ${W.origin??"värdet"} att ha ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`För lite(t): förväntade ${W.origin??"värdet"} att ha ${K}${W.minimum.toString()} ${X.unit}`;return`För lite(t): förväntade ${W.origin??"värdet"} att ha ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ogiltig sträng: måste börja med "${K.prefix}"`;if(K.format==="ends_with")return`Ogiltig sträng: måste sluta med "${K.suffix}"`;if(K.format==="includes")return`Ogiltig sträng: måste innehålla "${K.includes}"`;if(K.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${K.pattern}"`;return`Ogiltig(t) ${J[K.format]??W.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${m(W.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${W.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${W.origin??"värdet"}`;default:return"Ogiltig input"}}};function nH(){return{localeError:ZL()}}var IL=()=>{let $={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function U(W){return $[W]??null}let J={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${W.expected}, பெறப்பட்டது ${N}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${K}, பெறப்பட்டது ${N}`}case"invalid_value":if(W.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${U$(W.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${m(W.values,"|")} இல் ஒன்று`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${W.origin??"மதிப்பு"} ${K}${W.maximum.toString()} ${X.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${W.origin??"மதிப்பு"} ${K}${W.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${W.origin} ${K}${W.minimum.toString()} ${X.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${W.origin} ${K}${W.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`தவறான சரம்: "${K.prefix}" இல் தொடங்க வேண்டும்`;if(K.format==="ends_with")return`தவறான சரம்: "${K.suffix}" இல் முடிவடைய வேண்டும்`;if(K.format==="includes")return`தவறான சரம்: "${K.includes}" ஐ உள்ளடக்க வேண்டும்`;if(K.format==="regex")return`தவறான சரம்: ${K.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${J[K.format]??W.format}`}case"not_multiple_of":return`தவறான எண்: ${W.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${W.keys.length>1?"கள்":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${W.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function iH(){return{localeError:IL()}}var qL=()=>{let $={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function U(W){return $[W]??null}let J={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},Q={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${W.expected} แต่ได้รับ ${N}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${K} แต่ได้รับ ${N}`}case"invalid_value":if(W.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${U$(W.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"ไม่เกิน":"น้อยกว่า",X=U(W.origin);if(X)return`เกินกำหนด: ${W.origin??"ค่า"} ควรมี${K} ${W.maximum.toString()} ${X.unit??"รายการ"}`;return`เกินกำหนด: ${W.origin??"ค่า"} ควรมี${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?"อย่างน้อย":"มากกว่า",X=U(W.origin);if(X)return`น้อยกว่ากำหนด: ${W.origin} ควรมี${K} ${W.minimum.toString()} ${X.unit}`;return`น้อยกว่ากำหนด: ${W.origin} ควรมี${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${K.prefix}"`;if(K.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${K.suffix}"`;if(K.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${K.includes}" อยู่ในข้อความ`;if(K.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${K.pattern}`;return`รูปแบบไม่ถูกต้อง: ${J[K.format]??W.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${W.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${m(W.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${W.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${W.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function oH(){return{localeError:qL()}}var DL=()=>{let $={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function U(W){return $[W]??null}let J={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Geçersiz değer: beklenen instanceof ${W.expected}, alınan ${N}`;return`Geçersiz değer: beklenen ${K}, alınan ${N}`}case"invalid_value":if(W.values.length===1)return`Geçersiz değer: beklenen ${U$(W.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Çok büyük: beklenen ${W.origin??"değer"} ${K}${W.maximum.toString()} ${X.unit??"öğe"}`;return`Çok büyük: beklenen ${W.origin??"değer"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Çok küçük: beklenen ${W.origin} ${K}${W.minimum.toString()} ${X.unit}`;return`Çok küçük: beklenen ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Geçersiz metin: "${K.prefix}" ile başlamalı`;if(K.format==="ends_with")return`Geçersiz metin: "${K.suffix}" ile bitmeli`;if(K.format==="includes")return`Geçersiz metin: "${K.includes}" içermeli`;if(K.format==="regex")return`Geçersiz metin: ${K.pattern} desenine uymalı`;return`Geçersiz ${J[K.format]??W.format}`}case"not_multiple_of":return`Geçersiz sayı: ${W.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${W.keys.length>1?"lar":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${W.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function rH(){return{localeError:DL()}}var kL=()=>{let $={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function U(W){return $[W]??null}let J={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},Q={nan:"NaN",number:"число",array:"масив"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Неправильні вхідні дані: очікується instanceof ${W.expected}, отримано ${N}`;return`Неправильні вхідні дані: очікується ${K}, отримано ${N}`}case"invalid_value":if(W.values.length===1)return`Неправильні вхідні дані: очікується ${U$(W.values[0])}`;return`Неправильна опція: очікується одне з ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Занадто велике: очікується, що ${W.origin??"значення"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"елементів"}`;return`Занадто велике: очікується, що ${W.origin??"значення"} буде ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Занадто мале: очікується, що ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Занадто мале: очікується, що ${W.origin} буде ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Неправильний рядок: повинен починатися з "${K.prefix}"`;if(K.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${K.suffix}"`;if(K.format==="includes")return`Неправильний рядок: повинен містити "${K.includes}"`;if(K.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${K.pattern}`;return`Неправильний ${J[K.format]??W.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${W.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${W.keys.length>1?"і":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${W.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${W.origin}`;default:return"Неправильні вхідні дані"}}};function g8(){return{localeError:kL()}}function aH(){return g8()}var FL=()=>{let $={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function U(W){return $[W]??null}let J={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},Q={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`غلط ان پٹ: instanceof ${W.expected} متوقع تھا، ${N} موصول ہوا`;return`غلط ان پٹ: ${K} متوقع تھا، ${N} موصول ہوا`}case"invalid_value":if(W.values.length===1)return`غلط ان پٹ: ${U$(W.values[0])} متوقع تھا`;return`غلط آپشن: ${m(W.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`بہت بڑا: ${W.origin??"ویلیو"} کے ${K}${W.maximum.toString()} ${X.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${W.origin??"ویلیو"} کا ${K}${W.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`بہت چھوٹا: ${W.origin} کے ${K}${W.minimum.toString()} ${X.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${W.origin} کا ${K}${W.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`غلط سٹرنگ: "${K.prefix}" سے شروع ہونا چاہیے`;if(K.format==="ends_with")return`غلط سٹرنگ: "${K.suffix}" پر ختم ہونا چاہیے`;if(K.format==="includes")return`غلط سٹرنگ: "${K.includes}" شامل ہونا چاہیے`;if(K.format==="regex")return`غلط سٹرنگ: پیٹرن ${K.pattern} سے میچ ہونا چاہیے`;return`غلط ${J[K.format]??W.format}`}case"not_multiple_of":return`غلط نمبر: ${W.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${W.keys.length>1?"ز":""}: ${m(W.keys,"، ")}`;case"invalid_key":return`${W.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${W.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function sH(){return{localeError:FL()}}var LL=()=>{let $={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"},map:{unit:"yozuv",verb:"bo‘lishi kerak"}};function U(W){return $[W]??null}let J={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},Q={nan:"NaN",number:"raqam",array:"massiv"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${W.expected}, qabul qilingan ${N}`;return`Noto‘g‘ri kirish: kutilgan ${K}, qabul qilingan ${N}`}case"invalid_value":if(W.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${U$(W.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Juda katta: kutilgan ${W.origin??"qiymat"} ${K}${W.maximum.toString()} ${X.unit} ${X.verb}`;return`Juda katta: kutilgan ${W.origin??"qiymat"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Juda kichik: kutilgan ${W.origin} ${K}${W.minimum.toString()} ${X.unit} ${X.verb}`;return`Juda kichik: kutilgan ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Noto‘g‘ri satr: "${K.prefix}" bilan boshlanishi kerak`;if(K.format==="ends_with")return`Noto‘g‘ri satr: "${K.suffix}" bilan tugashi kerak`;if(K.format==="includes")return`Noto‘g‘ri satr: "${K.includes}" ni o‘z ichiga olishi kerak`;if(K.format==="regex")return`Noto‘g‘ri satr: ${K.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${J[K.format]??W.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${W.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${W.keys.length>1?"lar":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${W.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function tH(){return{localeError:LL()}}var RL=()=>{let $={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function U(W){return $[W]??null}let J={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},Q={nan:"NaN",number:"số",array:"mảng"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${W.expected}, nhận được ${N}`;return`Đầu vào không hợp lệ: mong đợi ${K}, nhận được ${N}`}case"invalid_value":if(W.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${U$(W.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Quá lớn: mong đợi ${W.origin??"giá trị"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"phần tử"}`;return`Quá lớn: mong đợi ${W.origin??"giá trị"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Quá nhỏ: mong đợi ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Quá nhỏ: mong đợi ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${K.prefix}"`;if(K.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${K.suffix}"`;if(K.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${K.includes}"`;if(K.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${K.pattern}`;return`${J[K.format]??W.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${W.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${m(W.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${W.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${W.origin}`;default:return"Đầu vào không hợp lệ"}}};function eH(){return{localeError:RL()}}var VL=()=>{let $={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function U(W){return $[W]??null}let J={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},Q={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`无效输入:期望 instanceof ${W.expected},实际接收 ${N}`;return`无效输入:期望 ${K},实际接收 ${N}`}case"invalid_value":if(W.values.length===1)return`无效输入:期望 ${U$(W.values[0])}`;return`无效选项:期望以下之一 ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`数值过大:期望 ${W.origin??"值"} ${K}${W.maximum.toString()} ${X.unit??"个元素"}`;return`数值过大:期望 ${W.origin??"值"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`数值过小:期望 ${W.origin} ${K}${W.minimum.toString()} ${X.unit}`;return`数值过小:期望 ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`无效字符串:必须以 "${K.prefix}" 开头`;if(K.format==="ends_with")return`无效字符串:必须以 "${K.suffix}" 结尾`;if(K.format==="includes")return`无效字符串:必须包含 "${K.includes}"`;if(K.format==="regex")return`无效字符串:必须满足正则表达式 ${K.pattern}`;return`无效${J[K.format]??W.format}`}case"not_multiple_of":return`无效数字:必须是 ${W.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${W.origin} 中包含无效值(value)`;default:return"无效输入"}}};function $Y(){return{localeError:VL()}}var wL=()=>{let $={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function U(W){return $[W]??null}let J={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`無效的輸入值:預期為 instanceof ${W.expected},但收到 ${N}`;return`無效的輸入值:預期為 ${K},但收到 ${N}`}case"invalid_value":if(W.values.length===1)return`無效的輸入值:預期為 ${U$(W.values[0])}`;return`無效的選項:預期為以下其中之一 ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`數值過大:預期 ${W.origin??"值"} 應為 ${K}${W.maximum.toString()} ${X.unit??"個元素"}`;return`數值過大:預期 ${W.origin??"值"} 應為 ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`數值過小:預期 ${W.origin} 應為 ${K}${W.minimum.toString()} ${X.unit}`;return`數值過小:預期 ${W.origin} 應為 ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`無效的字串:必須以 "${K.prefix}" 開頭`;if(K.format==="ends_with")return`無效的字串:必須以 "${K.suffix}" 結尾`;if(K.format==="includes")return`無效的字串:必須包含 "${K.includes}"`;if(K.format==="regex")return`無效的字串:必須符合格式 ${K.pattern}`;return`無效的 ${J[K.format]??W.format}`}case"not_multiple_of":return`無效的數字:必須為 ${W.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${W.keys.length>1?"們":""}:${m(W.keys,"、")}`;case"invalid_key":return`${W.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${W.origin} 中有無效的值`;default:return"無效的輸入值"}}};function UY(){return{localeError:wL()}}var ML=()=>{let $={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function U(W){return $[W]??null}let J={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},Q={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),N=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${W.expected}, àmọ̀ a rí ${N}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${K}, àmọ̀ a rí ${N}`}case"invalid_value":if(W.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${U$(W.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${W.origin??"iye"} ${X.verb} ${K}${W.maximum} ${X.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${K}${W.maximum}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Kéré ju: a ní láti jẹ́ pé ${W.origin} ${X.verb} ${K}${W.minimum} ${X.unit}`;return`Kéré ju: a ní láti jẹ́ ${K}${W.minimum}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${K.prefix}"`;if(K.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${K.suffix}"`;if(K.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${K.includes}"`;if(K.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${K.pattern}`;return`Aṣìṣe: ${J[K.format]??W.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${W.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${m(W.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${W.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${W.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function JY(){return{localeError:ML()}}var EI,WY=Symbol("ZodOutput"),QY=Symbol("ZodInput");class KY{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...U){let J=U[0];if(this._map.set($,J),J&&typeof J==="object"&&"id"in J)this._idmap.set(J.id,$);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let U=this._map.get($);if(U&&typeof U==="object"&&"id"in U)this._idmap.delete(U.id);return this._map.delete($),this}get($){let U=$._zod.parent;if(U){let J={...this.get(U)??{}};delete J.id;let Q={...J,...this._map.get($)};return Object.keys(Q).length?Q:void 0}return this._map.get($)}has($){return this._map.has($)}}function k9(){return new KY}(EI=globalThis).__zod_globalRegistry??(EI.__zod_globalRegistry=k9());var a6=globalThis.__zod_globalRegistry;function XY($,U){return new $({type:"string",...K$(U)})}function NY($,U){return new $({type:"string",coerce:!0,...K$(U)})}function F9($,U){return new $({type:"string",format:"email",check:"string_format",abort:!1,...K$(U)})}function x8($,U){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...K$(U)})}function L9($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...K$(U)})}function R9($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...K$(U)})}function V9($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...K$(U)})}function w9($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...K$(U)})}function y8($,U){return new $({type:"string",format:"url",check:"string_format",abort:!1,...K$(U)})}function M9($,U){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...K$(U)})}function B9($,U){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...K$(U)})}function P9($,U){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...K$(U)})}function z9($,U){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...K$(U)})}function _9($,U){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...K$(U)})}function A9($,U){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...K$(U)})}function C9($,U){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...K$(U)})}function S9($,U){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...K$(U)})}function T9($,U){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...K$(U)})}function HY($,U){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...K$(U)})}function v9($,U){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...K$(U)})}function j9($,U){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...K$(U)})}function g9($,U){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...K$(U)})}function b9($,U){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...K$(U)})}function x9($,U){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...K$(U)})}function y9($,U){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...K$(U)})}var YY={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function GY($,U){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...K$(U)})}function OY($,U){return new $({type:"string",format:"date",check:"string_format",...K$(U)})}function EY($,U){return new $({type:"string",format:"time",check:"string_format",precision:null,...K$(U)})}function ZY($,U){return new $({type:"string",format:"duration",check:"string_format",...K$(U)})}function IY($,U){return new $({type:"number",checks:[],...K$(U)})}function qY($,U){return new $({type:"number",coerce:!0,checks:[],...K$(U)})}function DY($,U){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...K$(U)})}function kY($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...K$(U)})}function FY($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...K$(U)})}function LY($,U){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...K$(U)})}function RY($,U){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...K$(U)})}function VY($,U){return new $({type:"boolean",...K$(U)})}function wY($,U){return new $({type:"boolean",coerce:!0,...K$(U)})}function MY($,U){return new $({type:"bigint",...K$(U)})}function BY($,U){return new $({type:"bigint",coerce:!0,...K$(U)})}function PY($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...K$(U)})}function zY($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...K$(U)})}function _Y($,U){return new $({type:"symbol",...K$(U)})}function AY($,U){return new $({type:"undefined",...K$(U)})}function CY($,U){return new $({type:"null",...K$(U)})}function SY($){return new $({type:"any"})}function TY($){return new $({type:"unknown"})}function vY($,U){return new $({type:"never",...K$(U)})}function jY($,U){return new $({type:"void",...K$(U)})}function gY($,U){return new $({type:"date",...K$(U)})}function bY($,U){return new $({type:"date",coerce:!0,...K$(U)})}function xY($,U){return new $({type:"nan",...K$(U)})}function UJ($,U){return new K9({check:"less_than",...K$(U),value:$,inclusive:!1})}function RU($,U){return new K9({check:"less_than",...K$(U),value:$,inclusive:!0})}function JJ($,U){return new X9({check:"greater_than",...K$(U),value:$,inclusive:!1})}function XU($,U){return new X9({check:"greater_than",...K$(U),value:$,inclusive:!0})}function h9($){return JJ(0,$)}function f9($){return UJ(0,$)}function u9($){return RU(0,$)}function l9($){return XU(0,$)}function cJ($,U){return new jX({check:"multiple_of",...K$(U),value:$})}function nJ($,U){return new xX({check:"max_size",...K$(U),maximum:$})}function WJ($,U){return new yX({check:"min_size",...K$(U),minimum:$})}function z0($,U){return new hX({check:"size_equals",...K$(U),size:$})}function _0($,U){return new fX({check:"max_length",...K$(U),maximum:$})}function wJ($,U){return new uX({check:"min_length",...K$(U),minimum:$})}function A0($,U){return new lX({check:"length_equals",...K$(U),length:$})}function YW($,U){return new mX({check:"string_format",format:"regex",...K$(U),pattern:$})}function GW($){return new pX({check:"string_format",format:"lowercase",...K$($)})}function OW($){return new dX({check:"string_format",format:"uppercase",...K$($)})}function EW($,U){return new cX({check:"string_format",format:"includes",...K$(U),includes:$})}function ZW($,U){return new nX({check:"string_format",format:"starts_with",...K$(U),prefix:$})}function IW($,U){return new iX({check:"string_format",format:"ends_with",...K$(U),suffix:$})}function m9($,U,J){return new oX({check:"property",property:$,schema:U,...K$(J)})}function qW($,U){return new rX({check:"mime_type",mime:$,...K$(U)})}function fU($){return new aX({check:"overwrite",tx:$})}function DW($){return fU((U)=>U.normalize($))}function kW(){return fU(($)=>$.trim())}function FW(){return fU(($)=>$.toLowerCase())}function LW(){return fU(($)=>$.toUpperCase())}function RW(){return fU(($)=>n7($))}function yY($,U,J){return new $({type:"array",element:U,...K$(J)})}function PL($,U,J){return new $({type:"union",options:U,...K$(J)})}function zL($,U,J){return new $({type:"union",options:U,inclusive:!1,...K$(J)})}function _L($,U,J,Q){return new $({type:"union",options:J,discriminator:U,...K$(Q)})}function AL($,U,J){return new $({type:"intersection",left:U,right:J})}function CL($,U,J,Q){let W=J instanceof h$;return new $({type:"tuple",items:U,rest:W?J:null,...K$(W?Q:J)})}function SL($,U,J,Q){return new $({type:"record",keyType:U,valueType:J,...K$(Q)})}function TL($,U,J,Q){return new $({type:"map",keyType:U,valueType:J,...K$(Q)})}function vL($,U,J){return new $({type:"set",valueType:U,...K$(J)})}function jL($,U,J){let Q=Array.isArray(U)?Object.fromEntries(U.map((W)=>[W,W])):U;return new $({type:"enum",entries:Q,...K$(J)})}function gL($,U,J){return new $({type:"enum",entries:U,...K$(J)})}function bL($,U,J){return new $({type:"literal",values:Array.isArray(U)?U:[U],...K$(J)})}function hY($,U){return new $({type:"file",...K$(U)})}function xL($,U){return new $({type:"transform",transform:U})}function yL($,U){return new $({type:"optional",innerType:U})}function hL($,U){return new $({type:"nullable",innerType:U})}function fL($,U,J){return new $({type:"default",innerType:U,get defaultValue(){return typeof J==="function"?J():o7(J)}})}function uL($,U,J){return new $({type:"nonoptional",innerType:U,...K$(J)})}function lL($,U){return new $({type:"success",innerType:U})}function mL($,U,J){return new $({type:"catch",innerType:U,catchValue:typeof J==="function"?J:()=>J})}function pL($,U,J){return new $({type:"pipe",in:U,out:J})}function dL($,U){return new $({type:"readonly",innerType:U})}function cL($,U,J){return new $({type:"template_literal",parts:U,...K$(J)})}function nL($,U){return new $({type:"lazy",getter:U})}function iL($,U){return new $({type:"promise",innerType:U})}function fY($,U,J){let Q=K$(J);return Q.abort??(Q.abort=!0),new $({type:"custom",check:"custom",fn:U,...Q})}function uY($,U,J){return new $({type:"custom",check:"custom",fn:U,...K$(J)})}function lY($,U){let J=ZI((Q)=>{return Q.addIssue=(W)=>{if(typeof W==="string")Q.issues.push(JW(W,Q.value,J._zod.def));else{let K=W;if(K.fatal)K.continue=!1;K.code??(K.code="custom"),K.input??(K.input=Q.value),K.inst??(K.inst=J),K.continue??(K.continue=!J._zod.def.abort),Q.issues.push(JW(K))}},$(Q.value,Q)},U);return J}function ZI($,U){let J=new V6({check:"custom",...K$(U)});return J._zod.check=$,J}function mY($){let U=new V6({check:"describe"});return U._zod.onattach=[(J)=>{let Q=a6.get(J)??{};a6.add(J,{...Q,description:$})}],U._zod.check=()=>{},U}function pY($){let U=new V6({check:"meta"});return U._zod.onattach=[(J)=>{let Q=a6.get(J)??{};a6.add(J,{...Q,...$})}],U._zod.check=()=>{},U}function dY($,U){let J=K$(U),Q=J.truthy??["true","1","yes","on","y","enabled"],W=J.falsy??["false","0","no","off","n","disabled"];if(J.case!=="sensitive")Q=Q.map((Z)=>typeof Z==="string"?Z.toLowerCase():Z),W=W.map((Z)=>typeof Z==="string"?Z.toLowerCase():Z);let K=new Set(Q),X=new Set(W),N=$.Codec??S8,H=$.Boolean??A8,G=new($.String??P0)({type:"string",error:J.error}),O=new H({type:"boolean",error:J.error}),E=new N({type:"pipe",in:G,out:O,transform:(Z,D)=>{let R=Z;if(J.case!=="sensitive")R=R.toLowerCase();if(K.has(R))return!0;else if(X.has(R))return!1;else return D.issues.push({code:"invalid_value",expected:"stringbool",values:[...K,...X],input:D.value,inst:E,continue:!1}),{}},reverseTransform:(Z,D)=>{if(Z===!0)return Q[0]||"true";else return W[0]||"false"},error:J.error});return E}function VW($,U,J,Q={}){let W=K$(Q),K={...K$(Q),check:"string_format",type:"string",format:U,fn:typeof J==="function"?J:(N)=>J.test(N),...W};if(J instanceof RegExp)K.pattern=J;return new $(K)}function iJ($){let U=$?.target??"draft-2020-12";if(U==="draft-4")U="draft-04";if(U==="draft-7")U="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??a6,target:U,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,cycles:$?.cycles??"ref",reused:$?.reused??"inline",external:$?.external??void 0}}function O6($,U,J={path:[],schemaPath:[]}){var Q;let W=$._zod.def,K=U.seen.get($);if(K){if(K.count++,J.schemaPath.includes($))K.cycle=J.path;return K.schema}let X={schema:{},count:1,cycle:void 0,path:J.path};U.seen.set($,X);let N=$._zod.toJSONSchema?.();if(N)X.schema=N;else{let G={...J,schemaPath:[...J.schemaPath,$],path:J.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(U,X.schema,G);else{let E=X.schema,Z=U.processors[W.type];if(!Z)throw Error(`[toJSONSchema]: Non-representable type encountered: ${W.type}`);Z($,U,E,G)}let O=$._zod.parent;if(O){if(!X.ref)X.ref=O;O6(O,U,G),U.seen.get(O).isParent=!0}}let H=U.metadataRegistry.get($);if(H)Object.assign(X.schema,H);if(U.io==="input"&&NU($))delete X.schema.examples,delete X.schema.default;if(U.io==="input"&&"_prefault"in X.schema)(Q=X.schema).default??(Q.default=X.schema._prefault);return delete X.schema._prefault,U.seen.get($).schema}function oJ($,U){let J=$.seen.get(U);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let Q=new Map;for(let X of $.seen.entries()){let N=$.metadataRegistry.get(X[0])?.id;if(N){let H=Q.get(N);if(H&&H!==X[0])throw Error(`Duplicate schema id "${N}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);Q.set(N,X[0])}}let W=(X)=>{let N=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let O=$.external.registry.get(X[0])?.id,E=$.external.uri??((D)=>D);if(O)return{ref:E(O)};let Z=X[1].defId??X[1].schema.id??`schema${$.counter++}`;return X[1].defId=Z,{defId:Z,ref:`${E("__shared")}#/${N}/${Z}`}}if(X[1]===J)return{ref:"#"};let Y=`${"#"}/${N}/`,G=X[1].schema.id??`__schema${$.counter++}`;return{defId:G,ref:Y+G}},K=(X)=>{if(X[1].schema.$ref)return;let N=X[1],{ref:H,defId:Y}=W(X);if(N.def={...N.schema},Y)N.defId=Y;let G=N.schema;for(let O in G)delete G[O];G.$ref=H};if($.cycles==="throw")for(let X of $.seen.entries()){let N=X[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/<root>+ `)}d.write("payload.value = newResult;"),d.write("return payload;");let A=d.compile();return(T,v)=>A(h,T,v)},s,o=ps,a=!Er.jitless,l=a&&Ch.value,u=t.catchall,f;e._zod.parse=(h,d)=>{f??(f=i.value);let g=h.value;if(!o(g))return h.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),h;if(a&&l&&d?.async===!1&&d.jitless!==!0){if(!s)s=r(t.shape);if(h=s(h,d),!u)return h;return yd([],g,h,d,f,e)}return n(h,d)}});function Ff(e,t,n,i){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let r=e.filter((s)=>!Qi(s));if(r.length===1)return t.value=r[0].value,r[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((s)=>s.issues.map((o)=>En(o,i,Tn())))}),t}var Sd=q("$ZodUnion",(e,t)=>{xt.init(e,t),it(e._zod,"optin",()=>t.options.some((i)=>i._zod.optin==="optional")?"optional":void 0),it(e._zod,"optout",()=>t.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),it(e._zod,"values",()=>{if(t.options.every((i)=>i._zod.values))return new Set(t.options.flatMap((i)=>Array.from(i._zod.values)));return}),it(e._zod,"pattern",()=>{if(t.options.every((i)=>i._zod.pattern)){let i=t.options.map((r)=>r._zod.pattern);return new RegExp(`^(${i.map((r)=>Mo(r.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(i,r)=>{if(n)return n(i,r);let s=!1,o=[];for(let a of t.options){let c=a._zod.run({value:i.value,issues:[]},r);if(c instanceof Promise)o.push(c),s=!0;else{if(c.issues.length===0)return c;o.push(c)}}if(!s)return Ff(o,i,e,r);return Promise.all(o).then((a)=>Ff(a,i,e,r))}});var Md=q("$ZodIntersection",(e,t)=>{xt.init(e,t),e._zod.parse=(n,i)=>{let r=n.value,s=t.left._zod.run({value:r,issues:[]},i),o=t.right._zod.run({value:r,issues:[]},i);if(s instanceof Promise||o instanceof Promise)return Promise.all([s,o]).then(([c,l])=>zf(n,c,l));return zf(n,s,o)}});function mc(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Ki(e)&&Ki(t)){let n=Object.keys(t),i=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),r={...e,...t};for(let s of i){let o=mc(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};r[s]=o.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<e.length;i++){let r=e[i],s=t[i],o=mc(r,s);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function zf(e,t,n){let i=new Map,r;for(let a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(let c of a.keys){if(!i.has(c))i.set(c,{});i.get(c).l=!0}}else e.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys){if(!i.has(c))i.set(c,{});i.get(c).r=!0}else e.issues.push(a);let s=[...i].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&r)e.issues.push({...r,keys:s});if(Qi(e))return e;let o=mc(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var wd=q("$ZodRecord",(e,t)=>{xt.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Ki(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;let s=[],o=t.keyType._zod.values;if(o){n.value={};let a=new Set;for(let l of o)if(typeof l==="string"||typeof l==="number"||typeof l==="symbol"){a.add(typeof l==="number"?l.toString():l);let u=t.keyType._zod.run({value:l,issues:[]},i);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((d)=>En(d,i,Tn())),input:l,path:[l],inst:e});continue}let f=u.value,h=t.valueType._zod.run({value:r[l],issues:[]},i);if(h instanceof Promise)s.push(h.then((d)=>{if(d.issues.length)n.issues.push(...Mi(l,d.issues));n.value[f]=d.value}));else{if(h.issues.length)n.issues.push(...Mi(l,h.issues));n.value[f]=h.value}}let c;for(let l in r)if(!a.has(l))c=c??[],c.push(l);if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(r)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(r,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},i);if(c instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&hc.test(a)&&c.issues.length){let f=t.keyType._zod.run({value:Number(a),issues:[]},i);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length===0)c=f}if(c.issues.length){if(t.mode==="loose")n.value[a]=r[a];else n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map((f)=>En(f,i,Tn())),input:a,path:[a],inst:e});continue}let u=t.valueType._zod.run({value:r[a],issues:[]},i);if(u instanceof Promise)s.push(u.then((f)=>{if(f.issues.length)n.issues.push(...Mi(a,f.issues));n.value[c.value]=f.value}));else{if(u.issues.length)n.issues.push(...Mi(a,u.issues));n.value[c.value]=u.value}}}if(s.length)return Promise.all(s).then(()=>n);return n}});var Td=q("$ZodEnum",(e,t)=>{xt.init(e,t);let n=yo(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter((r)=>Ih.has(typeof r)).map((r)=>typeof r==="string"?Si(r):r.toString()).join("|")})$`),e._zod.parse=(r,s)=>{let o=r.value;if(i.has(o))return r;return r.issues.push({code:"invalid_value",values:n,input:o,inst:e}),r}}),Ed=q("$ZodLiteral",(e,t)=>{if(xt.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((i)=>typeof i==="string"?Si(i):i?Si(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,r)=>{let s=i.value;if(n.has(s))return i;return i.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),i}});var Ad=q("$ZodTransform",(e,t)=>{xt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new ds(e.constructor.name);let r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then((o)=>(n.value=o,n.fallback=!0,n));if(r instanceof Promise)throw new ii;return n.value=r,n.fallback=!0,n}});function kf(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var _c=q("$ZodOptional",(e,t)=>{xt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",it(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),it(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Mo(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){let r=n.value,s=t.innerType._zod.run(n,i);if(s instanceof Promise)return s.then((o)=>kf(o,r));return kf(s,r)}if(n.value===void 0)return n;return t.innerType._zod.run(n,i)}}),Rd=q("$ZodExactOptional",(e,t)=>{_c.init(e,t),it(e._zod,"values",()=>t.innerType._zod.values),it(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),Cd=q("$ZodNullable",(e,t)=>{xt.init(e,t),it(e._zod,"optin",()=>t.innerType._zod.optin),it(e._zod,"optout",()=>t.innerType._zod.optout),it(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Mo(n.source)}|null)$`):void 0}),it(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>{if(n.value===null)return n;return t.innerType._zod.run(n,i)}}),Id=q("$ZodDefault",(e,t)=>{xt.init(e,t),e._zod.optin="optional",it(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>Bf(s,t));return Bf(r,t)}});function Bf(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Pd=q("$ZodPrefault",(e,t)=>{xt.init(e,t),e._zod.optin="optional",it(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,i)}}),Ld=q("$ZodNonOptional",(e,t)=>{xt.init(e,t),it(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((i)=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>Gf(s,e));return Gf(r,e)}});function Gf(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var Nd=q("$ZodCatch",(e,t)=>{xt.init(e,t),e._zod.optin="optional",it(e._zod,"optout",()=>t.innerType._zod.optout),it(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>{if(n.value=s.value,s.issues.length)n.value=t.catchValue({...n,error:{issues:s.issues.map((o)=>En(o,i,Tn()))},input:n.value}),n.issues=[],n.fallback=!0;return n});if(n.value=r.value,r.issues.length)n.value=t.catchValue({...n,error:{issues:r.issues.map((s)=>En(s,i,Tn()))},input:n.value}),n.issues=[],n.fallback=!0;return n}});var Dd=q("$ZodPipe",(e,t)=>{xt.init(e,t),it(e._zod,"values",()=>t.in._zod.values),it(e._zod,"optin",()=>t.in._zod.optin),it(e._zod,"optout",()=>t.out._zod.optout),it(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){let s=t.out._zod.run(n,i);if(s instanceof Promise)return s.then((o)=>Co(o,t.in,i));return Co(s,t.in,i)}let r=t.in._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>Co(s,t.out,i));return Co(r,t.out,i)}});function Co(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Ud=q("$ZodReadonly",(e,t)=>{xt.init(e,t),it(e._zod,"propValues",()=>t.innerType._zod.propValues),it(e._zod,"values",()=>t.innerType._zod.values),it(e._zod,"optin",()=>t.innerType?._zod?.optin),it(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then(Hf);return Hf(r)}});function Hf(e){return e.value=Object.freeze(e.value),e}var Od=q("$ZodCustom",(e,t)=>{Vt.init(e,t),xt.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=(n)=>{let i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then((s)=>Vf(s,n,i,e));Vf(r,n,i,e);return}});function Vf(e,t,n,i){if(!e){let r={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};if(i._zod.def.params)r.params=i._zod.def.params;t.issues.push(er(r))}}var Fd,DE=Symbol("ZodOutput"),UE=Symbol("ZodInput");class zd{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function hx(){return new zd}(Fd=globalThis).__zod_globalRegistry??(Fd.__zod_globalRegistry=hx());var tr=globalThis.__zod_globalRegistry;function kd(e,t){return new e({type:"string",...Te(t)})}function Bd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Te(t)})}function xc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Te(t)})}function Gd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Te(t)})}function Hd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Te(t)})}function Vd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Te(t)})}function Wd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Te(t)})}function $d(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Te(t)})}function Zd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Te(t)})}function Xd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Te(t)})}function qd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Te(t)})}function Yd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Te(t)})}function jd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Te(t)})}function Jd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Te(t)})}function Kd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Te(t)})}function Qd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Te(t)})}function ep(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Te(t)})}function tp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Te(t)})}function np(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Te(t)})}function ip(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Te(t)})}function rp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Te(t)})}function sp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Te(t)})}function op(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Te(t)})}function ap(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Te(t)})}function cp(e,t){return new e({type:"string",format:"date",check:"string_format",...Te(t)})}function lp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Te(t)})}function up(e,t){return new e({type:"string",format:"duration",check:"string_format",...Te(t)})}function hp(e,t){return new e({type:"number",checks:[],...Te(t)})}function fp(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Te(t)})}function dp(e,t){return new e({type:"boolean",...Te(t)})}function pp(e){return new e({type:"unknown"})}function mp(e,t){return new e({type:"never",...Te(t)})}function Lo(e,t){return new fc({check:"less_than",...Te(t),value:e,inclusive:!1})}function vs(e,t){return new fc({check:"less_than",...Te(t),value:e,inclusive:!0})}function No(e,t){return new dc({check:"greater_than",...Te(t),value:e,inclusive:!1})}function ys(e,t){return new dc({check:"greater_than",...Te(t),value:e,inclusive:!0})}function Do(e,t){return new Sf({check:"multiple_of",...Te(t),value:e})}function Uo(e,t){return new wf({check:"max_length",...Te(t),maximum:e})}function Ar(e,t){return new Tf({check:"min_length",...Te(t),minimum:e})}function Oo(e,t){return new Ef({check:"length_equals",...Te(t),length:e})}function vc(e,t){return new Af({check:"string_format",format:"regex",...Te(t),pattern:e})}function yc(e){return new Rf({check:"string_format",format:"lowercase",...Te(e)})}function bc(e){return new Cf({check:"string_format",format:"uppercase",...Te(e)})}function Sc(e,t){return new If({check:"string_format",format:"includes",...Te(t),includes:e})}function Mc(e,t){return new Pf({check:"string_format",format:"starts_with",...Te(t),prefix:e})}function wc(e,t){return new Lf({check:"string_format",format:"ends_with",...Te(t),suffix:e})}function Ti(e){return new Nf({check:"overwrite",tx:e})}function Tc(e){return Ti((t)=>t.normalize(e))}function Ec(){return Ti((e)=>e.trim())}function Ac(){return Ti((e)=>e.toLowerCase())}function Rc(){return Ti((e)=>e.toUpperCase())}function Cc(){return Ti((e)=>Rh(e))}function gp(e,t,n){return new e({type:"array",element:t,...Te(n)})}function _p(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Te(n)})}function xp(e,t){let n=fx((i)=>(i.addIssue=(r)=>{if(typeof r==="string")i.issues.push(er(r,i.value,n._zod.def));else{let s=r;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=i.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),i.issues.push(er(s))}},e(i.value,i)),t);return n}function fx(e,t){let n=new Vt({check:"custom",...Te(t)});return n._zod.check=e,n}function Ic(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??tr,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function At(e,t,n={path:[],schemaPath:[]}){var i;let r=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,n.schemaPath.includes(e))s.cycle=n.path;return s.schema}let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let a=e._zod.toJSONSchema?.();if(a)o.schema=a;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,u);else{let h=o.schema,d=t.processors[r.type];if(!d)throw Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);d(e,t,h,u)}let f=e._zod.parent;if(f){if(!o.ref)o.ref=f;At(f,t,u),t.seen.get(f).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Object.assign(o.schema,c);if(t.io==="input"&&Jt(e))delete o.schema.examples,delete o.schema.default;if(t.io==="input"&&"_prefault"in o.schema)(i=o.schema).default??(i.default=o.schema._prefault);return delete o.schema._prefault,t.seen.get(e).schema}function Pc(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=new Map;for(let o of e.seen.entries()){let a=e.metadataRegistry.get(o[0])?.id;if(a){let c=i.get(a);if(c&&c!==o[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(a,o[0])}}let r=(o)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(o[0])?.id,h=e.external.uri??((g)=>g);if(f)return{ref:h(f)};let d=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=d,{defId:d,ref:`${h("__shared")}#/${a}/${d}`}}if(o[1]===n)return{ref:"#"};let l=`${"#"}/${a}/`,u=o[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+u}},s=(o)=>{if(o[1].schema.$ref)return;let a=o[1],{ref:c,defId:l}=r(o);if(a.def={...a.schema},l)a.defId=l;let u=a.schema;for(let f in u)delete u[f];u.$ref=c};if(e.cycles==="throw")for(let o of e.seen.entries()){let a=o[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let X of $.seen.entries()){let N=X[1];if(U===X[0]){K(X);continue}if($.external){let Y=$.external.registry.get(X[0])?.id;if(U!==X[0]&&Y){K(X);continue}}if($.metadataRegistry.get(X[0])?.id){K(X);continue}if(N.cycle){K(X);continue}if(N.count>1){if($.reused==="ref"){K(X);continue}}}}function rJ($,U){let J=$.seen.get(U);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let Q=(N)=>{let H=$.seen.get(N);if(H.ref===null)return;let Y=H.def??H.schema,G={...Y},O=H.ref;if(H.ref=null,O){Q(O);let Z=$.seen.get(O),D=Z.schema;if(D.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))Y.allOf=Y.allOf??[],Y.allOf.push(D);else Object.assign(Y,D);if(Object.assign(Y,G),N._zod.parent===O)for(let I in Y){if(I==="$ref"||I==="allOf")continue;if(!(I in G))delete Y[I]}if(D.$ref&&Z.def)for(let I in Y){if(I==="$ref"||I==="allOf")continue;if(I in Z.def&&JSON.stringify(Y[I])===JSON.stringify(Z.def[I]))delete Y[I]}}let E=N._zod.parent;if(E&&E!==O){Q(E);let Z=$.seen.get(E);if(Z?.schema.$ref){if(Y.$ref=Z.schema.$ref,Z.def)for(let D in Y){if(D==="$ref"||D==="allOf")continue;if(D in Z.def&&JSON.stringify(Y[D])===JSON.stringify(Z.def[D]))delete Y[D]}}}$.override({zodSchema:N,jsonSchema:Y,path:H.path??[]})};for(let N of[...$.seen.entries()].reverse())Q(N[0]);let W={};if($.target==="draft-2020-12")W.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")W.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let N=$.external.registry.get(U)?.id;if(!N)throw Error("Schema is missing an `id` property");W.$id=$.external.uri(N)}Object.assign(W,J.def??J.schema);let K=$.metadataRegistry.get(U)?.id;if(K!==void 0&&W.id===K)delete W.id;let X=$.external?.defs??{};for(let N of $.seen.entries()){let H=N[1];if(H.def&&H.defId){if(H.def.id===H.defId)delete H.def.id;X[H.defId]=H.def}}if($.external);else if(Object.keys(X).length>0)if($.target==="draft-2020-12")W.$defs=X;else W.definitions=X;try{let N=JSON.parse(JSON.stringify(W));return Object.defineProperty(N,"~standard",{value:{...U["~standard"],jsonSchema:{input:wW(U,"input",$.processors),output:wW(U,"output",$.processors)}},enumerable:!1,writable:!1}),N}catch(N){throw Error("Error converting schema to JSON.")}}function NU($,U){let J=U??{seen:new Set};if(J.seen.has($))return!1;J.seen.add($);let Q=$._zod.def;if(Q.type==="transform")return!0;if(Q.type==="array")return NU(Q.element,J);if(Q.type==="set")return NU(Q.valueType,J);if(Q.type==="lazy")return NU(Q.getter(),J);if(Q.type==="promise"||Q.type==="optional"||Q.type==="nonoptional"||Q.type==="nullable"||Q.type==="readonly"||Q.type==="default"||Q.type==="prefault")return NU(Q.innerType,J);if(Q.type==="intersection")return NU(Q.left,J)||NU(Q.right,J);if(Q.type==="record"||Q.type==="map")return NU(Q.keyType,J)||NU(Q.valueType,J);if(Q.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return NU(Q.in,J)||NU(Q.out,J)}if(Q.type==="object"){for(let W in Q.shape)if(NU(Q.shape[W],J))return!0;return!1}if(Q.type==="union"){for(let W of Q.options)if(NU(W,J))return!0;return!1}if(Q.type==="tuple"){for(let W of Q.items)if(NU(W,J))return!0;if(Q.rest&&NU(Q.rest,J))return!0;return!1}return!1}var cY=($,U={})=>(J)=>{let Q=iJ({...J,processors:U});return O6($,Q),oJ(Q,$),rJ(Q,$)},wW=($,U,J={})=>(Q)=>{let{libraryOptions:W,target:K}=Q??{},X=iJ({...W??{},target:K,io:U,processors:J});return O6($,X),oJ(X,$),rJ(X,$)};var oL={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},nY=($,U,J,Q)=>{let W=J;W.type="string";let{minimum:K,maximum:X,format:N,patterns:H,contentEncoding:Y}=$._zod.bag;if(typeof K==="number")W.minLength=K;if(typeof X==="number")W.maxLength=X;if(N){if(W.format=oL[N]??N,W.format==="")delete W.format;if(N==="time")delete W.format}if(Y)W.contentEncoding=Y;if(H&&H.size>0){let G=[...H];if(G.length===1)W.pattern=G[0].source;else if(G.length>1)W.allOf=[...G.map((O)=>({...U.target==="draft-07"||U.target==="draft-04"||U.target==="openapi-3.0"?{type:"string"}:{},pattern:O.source}))]}},iY=($,U,J,Q)=>{let W=J,{minimum:K,maximum:X,format:N,multipleOf:H,exclusiveMaximum:Y,exclusiveMinimum:G}=$._zod.bag;if(typeof N==="string"&&N.includes("int"))W.type="integer";else W.type="number";let O=typeof G==="number"&&G>=(K??Number.NEGATIVE_INFINITY),E=typeof Y==="number"&&Y<=(X??Number.POSITIVE_INFINITY),Z=U.target==="draft-04"||U.target==="openapi-3.0";if(O)if(Z)W.minimum=G,W.exclusiveMinimum=!0;else W.exclusiveMinimum=G;else if(typeof K==="number")W.minimum=K;if(E)if(Z)W.maximum=Y,W.exclusiveMaximum=!0;else W.exclusiveMaximum=Y;else if(typeof X==="number")W.maximum=X;if(typeof H==="number")W.multipleOf=H},oY=($,U,J,Q)=>{J.type="boolean"},rY=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},aY=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},sY=($,U,J,Q)=>{if(U.target==="openapi-3.0")J.type="string",J.nullable=!0,J.enum=[null];else J.type="null"},tY=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},eY=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},$1=($,U,J,Q)=>{J.not={}},U1=($,U,J,Q)=>{},J1=($,U,J,Q)=>{},W1=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Q1=($,U,J,Q)=>{let W=$._zod.def,K=k8(W.entries);if(K.every((X)=>typeof X==="number"))J.type="number";if(K.every((X)=>typeof X==="string"))J.type="string";J.enum=K},K1=($,U,J,Q)=>{let W=$._zod.def,K=[];for(let X of W.values)if(X===void 0){if(U.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof X==="bigint")if(U.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else K.push(Number(X));else K.push(X);if(K.length===0);else if(K.length===1){let X=K[0];if(J.type=X===null?"null":typeof X,U.target==="draft-04"||U.target==="openapi-3.0")J.enum=[X];else J.const=X}else{if(K.every((X)=>typeof X==="number"))J.type="number";if(K.every((X)=>typeof X==="string"))J.type="string";if(K.every((X)=>typeof X==="boolean"))J.type="boolean";if(K.every((X)=>X===null))J.type="null";J.enum=K}},X1=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},N1=($,U,J,Q)=>{let W=J,K=$._zod.pattern;if(!K)throw Error("Pattern not found in template literal");W.type="string",W.pattern=K.source},H1=($,U,J,Q)=>{let W=J,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:X,maximum:N,mime:H}=$._zod.bag;if(X!==void 0)K.minLength=X;if(N!==void 0)K.maxLength=N;if(H)if(H.length===1)K.contentMediaType=H[0],Object.assign(W,K);else Object.assign(W,K),W.anyOf=H.map((Y)=>({contentMediaType:Y}));else Object.assign(W,K)},Y1=($,U,J,Q)=>{J.type="boolean"},G1=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},O1=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},E1=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Z1=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},I1=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},q1=($,U,J,Q)=>{let W=J,K=$._zod.def,{minimum:X,maximum:N}=$._zod.bag;if(typeof X==="number")W.minItems=X;if(typeof N==="number")W.maxItems=N;W.type="array",W.items=O6(K.element,U,{...Q,path:[...Q.path,"items"]})},D1=($,U,J,Q)=>{let W=J,K=$._zod.def;W.type="object",W.properties={};let X=K.shape;for(let Y in X)W.properties[Y]=O6(X[Y],U,{...Q,path:[...Q.path,"properties",Y]});let N=new Set(Object.keys(X)),H=new Set([...N].filter((Y)=>{let G=K.shape[Y]._zod;if(U.io==="input")return G.optin===void 0;else return G.optout===void 0}));if(H.size>0)W.required=Array.from(H);if(K.catchall?._zod.def.type==="never")W.additionalProperties=!1;else if(!K.catchall){if(U.io==="output")W.additionalProperties=!1}else if(K.catchall)W.additionalProperties=O6(K.catchall,U,{...Q,path:[...Q.path,"additionalProperties"]})},d9=($,U,J,Q)=>{let W=$._zod.def,K=W.inclusive===!1,X=W.options.map((N,H)=>O6(N,U,{...Q,path:[...Q.path,K?"oneOf":"anyOf",H]}));if(K)J.oneOf=X;else J.anyOf=X},k1=($,U,J,Q)=>{let W=$._zod.def,K=O6(W.left,U,{...Q,path:[...Q.path,"allOf",0]}),X=O6(W.right,U,{...Q,path:[...Q.path,"allOf",1]}),N=(Y)=>("allOf"in Y)&&Object.keys(Y).length===1,H=[...N(K)?K.allOf:[K],...N(X)?X.allOf:[X]];J.allOf=H},F1=($,U,J,Q)=>{let W=J,K=$._zod.def;W.type="array";let X=U.target==="draft-2020-12"?"prefixItems":"items",N=U.target==="draft-2020-12"?"items":U.target==="openapi-3.0"?"items":"additionalItems",H=K.items.map((E,Z)=>O6(E,U,{...Q,path:[...Q.path,X,Z]})),Y=K.rest?O6(K.rest,U,{...Q,path:[...Q.path,N,...U.target==="openapi-3.0"?[K.items.length]:[]]}):null;if(U.target==="draft-2020-12"){if(W.prefixItems=H,Y)W.items=Y}else if(U.target==="openapi-3.0"){if(W.items={anyOf:H},Y)W.items.anyOf.push(Y);if(W.minItems=H.length,!Y)W.maxItems=H.length}else if(W.items=H,Y)W.additionalItems=Y;let{minimum:G,maximum:O}=$._zod.bag;if(typeof G==="number")W.minItems=G;if(typeof O==="number")W.maxItems=O},L1=($,U,J,Q)=>{let W=J,K=$._zod.def;W.type="object";let X=K.keyType,H=X._zod.bag?.patterns;if(K.mode==="loose"&&H&&H.size>0){let G=O6(K.valueType,U,{...Q,path:[...Q.path,"patternProperties","*"]});W.patternProperties={};for(let O of H)W.patternProperties[O.source]=G}else{if(U.target==="draft-07"||U.target==="draft-2020-12")W.propertyNames=O6(K.keyType,U,{...Q,path:[...Q.path,"propertyNames"]});W.additionalProperties=O6(K.valueType,U,{...Q,path:[...Q.path,"additionalProperties"]})}let Y=X._zod.values;if(Y){let G=[...Y].filter((O)=>typeof O==="string"||typeof O==="number");if(G.length>0)W.required=G}},R1=($,U,J,Q)=>{let W=$._zod.def,K=O6(W.innerType,U,Q),X=U.seen.get($);if(U.target==="openapi-3.0")X.ref=W.innerType,J.nullable=!0;else J.anyOf=[K,{type:"null"}]},V1=($,U,J,Q)=>{let W=$._zod.def;O6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType},w1=($,U,J,Q)=>{let W=$._zod.def;O6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType,J.default=JSON.parse(JSON.stringify(W.defaultValue))},M1=($,U,J,Q)=>{let W=$._zod.def;O6(W.innerType,U,Q);let K=U.seen.get($);if(K.ref=W.innerType,U.io==="input")J._prefault=JSON.parse(JSON.stringify(W.defaultValue))},B1=($,U,J,Q)=>{let W=$._zod.def;O6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType;let X;try{X=W.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}J.default=X},P1=($,U,J,Q)=>{let W=$._zod.def,K=W.in._zod.traits.has("$ZodTransform"),X=U.io==="input"?K?W.out:W.in:W.out;O6(X,U,Q);let N=U.seen.get($);N.ref=X},z1=($,U,J,Q)=>{let W=$._zod.def;O6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType,J.readOnly=!0},_1=($,U,J,Q)=>{let W=$._zod.def;O6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType},c9=($,U,J,Q)=>{let W=$._zod.def;O6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType},A1=($,U,J,Q)=>{let W=$._zod.innerType;O6(W,U,Q);let K=U.seen.get($);K.ref=W},p9={string:nY,number:iY,boolean:oY,bigint:rY,symbol:aY,null:sY,undefined:tY,void:eY,never:$1,any:U1,unknown:J1,date:W1,enum:Q1,literal:K1,nan:X1,template_literal:N1,file:H1,success:Y1,custom:G1,function:O1,transform:E1,map:Z1,set:I1,array:q1,object:D1,union:d9,intersection:k1,tuple:F1,record:L1,nullable:R1,nonoptional:V1,default:w1,prefault:M1,catch:B1,pipe:P1,readonly:z1,promise:_1,optional:c9,lazy:A1};function n9($,U){if("_idmap"in $){let Q=$,W=iJ({...U,processors:p9}),K={};for(let H of Q._idmap.entries()){let[Y,G]=H;O6(G,W)}let X={},N={registry:Q,uri:U?.uri,defs:K};W.external=N;for(let H of Q._idmap.entries()){let[Y,G]=H;oJ(W,G),X[Y]=rJ(W,G)}if(Object.keys(K).length>0){let H=W.target==="draft-2020-12"?"$defs":"definitions";X.__shared={[H]:K}}return{schemas:X}}let J=iJ({...U,processors:p9});return O6($,J),oJ(J,$),rJ(J,$)}class C1{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter($){this.ctx.counter=$}get seen(){return this.ctx.seen}constructor($){let U=$?.target??"draft-2020-12";if(U==="draft-4")U="draft-04";if(U==="draft-7")U="draft-07";this.ctx=iJ({processors:p9,target:U,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,U={path:[],schemaPath:[]}){return O6($,this.ctx,U)}emit($,U){if(U){if(U.cycles)this.ctx.cycles=U.cycles;if(U.reused)this.ctx.reused=U.reused;if(U.external)this.ctx.external=U.external}oJ(this.ctx,$);let J=rJ(this.ctx,$),{"~standard":Q,...W}=J;return W}}var II={};var h8={};RJ(h8,{xor:()=>Nq,xid:()=>SI,void:()=>Uq,uuidv7:()=>wI,uuidv6:()=>VI,uuidv4:()=>RI,uuid:()=>LI,url:()=>MI,unknown:()=>C0,union:()=>LK,undefined:()=>eI,ulid:()=>CI,uint64:()=>sI,uint32:()=>oI,tuple:()=>YG,transform:()=>VK,templateLiteral:()=>Vq,symbol:()=>tI,superRefine:()=>yG,success:()=>kq,stringbool:()=>Cq,stringFormat:()=>lI,string:()=>f8,strictObject:()=>Kq,set:()=>Eq,refine:()=>xG,record:()=>GG,readonly:()=>SG,promise:()=>wq,preprocess:()=>Tq,prefault:()=>wG,pipe:()=>e9,partialRecord:()=>Yq,optional:()=>l8,object:()=>Qq,number:()=>i1,nullish:()=>Dq,nullable:()=>m8,null:()=>t1,nonoptional:()=>MG,never:()=>FK,nativeEnum:()=>Zq,nanoid:()=>zI,nan:()=>Fq,meta:()=>_q,map:()=>Oq,mac:()=>jI,looseRecord:()=>Gq,looseObject:()=>Xq,literal:()=>Iq,lazy:()=>jG,ksuid:()=>TI,keyof:()=>Wq,jwt:()=>uI,json:()=>Sq,ipv6:()=>gI,ipv4:()=>vI,invertCodec:()=>Rq,intersection:()=>NG,int64:()=>aI,int32:()=>iI,int:()=>t9,instanceof:()=>Aq,httpUrl:()=>BI,hostname:()=>mI,hex:()=>pI,hash:()=>dI,guid:()=>FI,function:()=>Mq,float64:()=>nI,float32:()=>cI,file:()=>qq,exactOptional:()=>kG,enum:()=>RK,emoji:()=>PI,email:()=>kI,e164:()=>fI,discriminatedUnion:()=>Hq,describe:()=>zq,date:()=>Jq,custom:()=>Pq,cuid2:()=>AI,cuid:()=>_I,codec:()=>Lq,cidrv6:()=>xI,cidrv4:()=>bI,check:()=>Bq,catch:()=>zG,boolean:()=>o1,bigint:()=>rI,base64url:()=>hI,base64:()=>yI,array:()=>n8,any:()=>$q,_function:()=>Mq,_default:()=>RG,_ZodString:()=>$K,ZodXor:()=>QG,ZodXID:()=>NK,ZodVoid:()=>JG,ZodUnknown:()=>$G,ZodUnion:()=>o8,ZodUndefined:()=>a1,ZodUUID:()=>QJ,ZodURL:()=>d8,ZodULID:()=>XK,ZodType:()=>n$,ZodTuple:()=>HG,ZodTransform:()=>qG,ZodTemplateLiteral:()=>TG,ZodSymbol:()=>r1,ZodSuccess:()=>BG,ZodStringFormat:()=>D6,ZodString:()=>zW,ZodSet:()=>EG,ZodRecord:()=>BW,ZodReadonly:()=>CG,ZodPromise:()=>gG,ZodPreprocess:()=>AG,ZodPrefault:()=>VG,ZodPipe:()=>r8,ZodOptional:()=>wK,ZodObject:()=>i8,ZodNumberFormat:()=>S0,ZodNumber:()=>AW,ZodNullable:()=>FG,ZodNull:()=>s1,ZodNonOptional:()=>MK,ZodNever:()=>UG,ZodNanoID:()=>WK,ZodNaN:()=>_G,ZodMap:()=>OG,ZodMAC:()=>n1,ZodLiteral:()=>ZG,ZodLazy:()=>vG,ZodKSUID:()=>HK,ZodJWT:()=>DK,ZodIntersection:()=>XG,ZodIPv6:()=>GK,ZodIPv4:()=>YK,ZodGUID:()=>u8,ZodFunction:()=>bG,ZodFile:()=>IG,ZodExactOptional:()=>DG,ZodEnum:()=>PW,ZodEmoji:()=>JK,ZodEmail:()=>UK,ZodE164:()=>qK,ZodDiscriminatedUnion:()=>KG,ZodDefault:()=>LG,ZodDate:()=>c8,ZodCustomStringFormat:()=>_W,ZodCustom:()=>s8,ZodCodec:()=>a8,ZodCatch:()=>PG,ZodCUID2:()=>KK,ZodCUID:()=>QK,ZodCIDRv6:()=>EK,ZodCIDRv4:()=>OK,ZodBoolean:()=>CW,ZodBigIntFormat:()=>kK,ZodBigInt:()=>SW,ZodBase64URL:()=>IK,ZodBase64:()=>ZK,ZodArray:()=>WG,ZodAny:()=>e1});var i9={};RJ(i9,{uppercase:()=>OW,trim:()=>kW,toUpperCase:()=>LW,toLowerCase:()=>FW,startsWith:()=>ZW,slugify:()=>RW,size:()=>z0,regex:()=>YW,property:()=>m9,positive:()=>h9,overwrite:()=>fU,normalize:()=>DW,nonpositive:()=>u9,nonnegative:()=>l9,negative:()=>f9,multipleOf:()=>cJ,minSize:()=>WJ,minLength:()=>wJ,mime:()=>qW,maxSize:()=>nJ,maxLength:()=>_0,lte:()=>RU,lt:()=>UJ,lowercase:()=>GW,length:()=>A0,includes:()=>EW,gte:()=>XU,gt:()=>JJ,endsWith:()=>IW});var MW={};RJ(MW,{time:()=>v1,duration:()=>j1,datetime:()=>S1,date:()=>T1,ZodISOTime:()=>a9,ZodISODuration:()=>s9,ZodISODateTime:()=>o9,ZodISODate:()=>r9});var o9=g("ZodISODateTime",($,U)=>{GN.init($,U),D6.init($,U)});function S1($){return GY(o9,$)}var r9=g("ZodISODate",($,U)=>{ON.init($,U),D6.init($,U)});function T1($){return OY(r9,$)}var a9=g("ZodISOTime",($,U)=>{EN.init($,U),D6.init($,U)});function v1($){return EY(a9,$)}var s9=g("ZodISODuration",($,U)=>{ZN.init($,U),D6.init($,U)});function j1($){return ZY(s9,$)}var qI=($,U)=>{w8.init($,U),$.name="ZodError",Object.defineProperties($,{format:{value:(J)=>B8($,J)},flatten:{value:(J)=>M8($,J)},addIssue:{value:(J)=>{$.issues.push(J),$.message=JSON.stringify($.issues,$W,2)}},addIssues:{value:(J)=>{$.issues.push(...J),$.message=JSON.stringify($.issues,$W,2)}},isEmpty:{get(){return $.issues.length===0}}})},aL=g("ZodError",qI),IU=g("ZodError",qI,{Parent:Error});var g1=WW(IU),b1=QW(IU),x1=KW(IU),y1=XW(IU),h1=aQ(IU),f1=sQ(IU),u1=tQ(IU),l1=eQ(IU),m1=$9(IU),p1=U9(IU),d1=J9(IU),c1=W9(IU);var DI=new WeakMap;function p8($,U,J){let Q=Object.getPrototypeOf($),W=DI.get(Q);if(!W)W=new Set,DI.set(Q,W);if(W.has(U))return;W.add(U);for(let K in J){let X=J[K];Object.defineProperty(Q,K,{configurable:!0,enumerable:!1,get(){let N=X.bind(this);return Object.defineProperty(this,K,{configurable:!0,writable:!0,enumerable:!0,value:N}),N},set(N){Object.defineProperty(this,K,{configurable:!0,writable:!0,enumerable:!0,value:N})}})}}var n$=g("ZodType",($,U)=>{return h$.init($,U),Object.assign($["~standard"],{jsonSchema:{input:wW($,"input"),output:wW($,"output")}}),$.toJSONSchema=cY($,{}),$.def=U,$.type=U.type,Object.defineProperty($,"_def",{value:U}),$.parse=(J,Q)=>g1($,J,Q,{callee:$.parse}),$.safeParse=(J,Q)=>x1($,J,Q),$.parseAsync=async(J,Q)=>b1($,J,Q,{callee:$.parseAsync}),$.safeParseAsync=async(J,Q)=>y1($,J,Q),$.spa=$.safeParseAsync,$.encode=(J,Q)=>h1($,J,Q),$.decode=(J,Q)=>f1($,J,Q),$.encodeAsync=async(J,Q)=>u1($,J,Q),$.decodeAsync=async(J,Q)=>l1($,J,Q),$.safeEncode=(J,Q)=>m1($,J,Q),$.safeDecode=(J,Q)=>p1($,J,Q),$.safeEncodeAsync=async(J,Q)=>d1($,J,Q),$.safeDecodeAsync=async(J,Q)=>c1($,J,Q),p8($,"ZodType",{check(...J){let Q=this.def;return this.clone(Q$.mergeDefs(Q,{checks:[...Q.checks??[],...J.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}),{parent:!0})},with(...J){return this.check(...J)},clone(J,Q){return QU(this,J,Q)},brand(){return this},register(J,Q){return J.add(this,Q),this},refine(J,Q){return this.check(xG(J,Q))},superRefine(J,Q){return this.check(yG(J,Q))},overwrite(J){return this.check(fU(J))},optional(){return l8(this)},exactOptional(){return kG(this)},nullable(){return m8(this)},nullish(){return l8(m8(this))},nonoptional(J){return MG(this,J)},array(){return n8(this)},or(J){return LK([this,J])},and(J){return NG(this,J)},transform(J){return e9(this,VK(J))},default(J){return RG(this,J)},prefault(J){return wG(this,J)},catch(J){return zG(this,J)},pipe(J){return e9(this,J)},readonly(){return SG(this)},describe(J){let Q=this.clone();return a6.add(Q,{description:J}),Q},meta(...J){if(J.length===0)return a6.get(this);let Q=this.clone();return a6.add(Q,J[0]),Q},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(J){return J(this)}}),Object.defineProperty($,"description",{get(){return a6.get($)?.description},configurable:!0}),$}),$K=g("_ZodString",($,U)=>{P0.init($,U),n$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>nY($,Q,W,K);let J=$._zod.bag;$.format=J.format??null,$.minLength=J.minimum??null,$.maxLength=J.maximum??null,p8($,"_ZodString",{regex(...Q){return this.check(YW(...Q))},includes(...Q){return this.check(EW(...Q))},startsWith(...Q){return this.check(ZW(...Q))},endsWith(...Q){return this.check(IW(...Q))},min(...Q){return this.check(wJ(...Q))},max(...Q){return this.check(_0(...Q))},length(...Q){return this.check(A0(...Q))},nonempty(...Q){return this.check(wJ(1,...Q))},lowercase(Q){return this.check(GW(Q))},uppercase(Q){return this.check(OW(Q))},trim(){return this.check(kW())},normalize(...Q){return this.check(DW(...Q))},toLowerCase(){return this.check(FW())},toUpperCase(){return this.check(LW())},slugify(){return this.check(RW())}})}),zW=g("ZodString",($,U)=>{P0.init($,U),$K.init($,U),$.email=(J)=>$.check(F9(UK,J)),$.url=(J)=>$.check(y8(d8,J)),$.jwt=(J)=>$.check(y9(DK,J)),$.emoji=(J)=>$.check(M9(JK,J)),$.guid=(J)=>$.check(x8(u8,J)),$.uuid=(J)=>$.check(L9(QJ,J)),$.uuidv4=(J)=>$.check(R9(QJ,J)),$.uuidv6=(J)=>$.check(V9(QJ,J)),$.uuidv7=(J)=>$.check(w9(QJ,J)),$.nanoid=(J)=>$.check(B9(WK,J)),$.guid=(J)=>$.check(x8(u8,J)),$.cuid=(J)=>$.check(P9(QK,J)),$.cuid2=(J)=>$.check(z9(KK,J)),$.ulid=(J)=>$.check(_9(XK,J)),$.base64=(J)=>$.check(g9(ZK,J)),$.base64url=(J)=>$.check(b9(IK,J)),$.xid=(J)=>$.check(A9(NK,J)),$.ksuid=(J)=>$.check(C9(HK,J)),$.ipv4=(J)=>$.check(S9(YK,J)),$.ipv6=(J)=>$.check(T9(GK,J)),$.cidrv4=(J)=>$.check(v9(OK,J)),$.cidrv6=(J)=>$.check(j9(EK,J)),$.e164=(J)=>$.check(x9(qK,J)),$.datetime=(J)=>$.check(S1(J)),$.date=(J)=>$.check(T1(J)),$.time=(J)=>$.check(v1(J)),$.duration=(J)=>$.check(j1(J))});function f8($){return XY(zW,$)}var D6=g("ZodStringFormat",($,U)=>{q6.init($,U),$K.init($,U)}),UK=g("ZodEmail",($,U)=>{UN.init($,U),D6.init($,U)});function kI($){return F9(UK,$)}var u8=g("ZodGUID",($,U)=>{eX.init($,U),D6.init($,U)});function FI($){return x8(u8,$)}var QJ=g("ZodUUID",($,U)=>{$N.init($,U),D6.init($,U)});function LI($){return L9(QJ,$)}function RI($){return R9(QJ,$)}function VI($){return V9(QJ,$)}function wI($){return w9(QJ,$)}var d8=g("ZodURL",($,U)=>{JN.init($,U),D6.init($,U)});function MI($){return y8(d8,$)}function BI($){return y8(d8,{protocol:LU.httpProtocol,hostname:LU.domain,...Q$.normalizeParams($)})}var JK=g("ZodEmoji",($,U)=>{WN.init($,U),D6.init($,U)});function PI($){return M9(JK,$)}var WK=g("ZodNanoID",($,U)=>{QN.init($,U),D6.init($,U)});function zI($){return B9(WK,$)}var QK=g("ZodCUID",($,U)=>{KN.init($,U),D6.init($,U)});function _I($){return P9(QK,$)}var KK=g("ZodCUID2",($,U)=>{XN.init($,U),D6.init($,U)});function AI($){return z9(KK,$)}var XK=g("ZodULID",($,U)=>{NN.init($,U),D6.init($,U)});function CI($){return _9(XK,$)}var NK=g("ZodXID",($,U)=>{HN.init($,U),D6.init($,U)});function SI($){return A9(NK,$)}var HK=g("ZodKSUID",($,U)=>{YN.init($,U),D6.init($,U)});function TI($){return C9(HK,$)}var YK=g("ZodIPv4",($,U)=>{IN.init($,U),D6.init($,U)});function vI($){return S9(YK,$)}var n1=g("ZodMAC",($,U)=>{DN.init($,U),D6.init($,U)});function jI($){return HY(n1,$)}var GK=g("ZodIPv6",($,U)=>{qN.init($,U),D6.init($,U)});function gI($){return T9(GK,$)}var OK=g("ZodCIDRv4",($,U)=>{kN.init($,U),D6.init($,U)});function bI($){return v9(OK,$)}var EK=g("ZodCIDRv6",($,U)=>{FN.init($,U),D6.init($,U)});function xI($){return j9(EK,$)}var ZK=g("ZodBase64",($,U)=>{RN.init($,U),D6.init($,U)});function yI($){return g9(ZK,$)}var IK=g("ZodBase64URL",($,U)=>{VN.init($,U),D6.init($,U)});function hI($){return b9(IK,$)}var qK=g("ZodE164",($,U)=>{wN.init($,U),D6.init($,U)});function fI($){return x9(qK,$)}var DK=g("ZodJWT",($,U)=>{MN.init($,U),D6.init($,U)});function uI($){return y9(DK,$)}var _W=g("ZodCustomStringFormat",($,U)=>{BN.init($,U),D6.init($,U)});function lI($,U,J={}){return VW(_W,$,U,J)}function mI($){return VW(_W,"hostname",LU.hostname,$)}function pI($){return VW(_W,"hex",LU.hex,$)}function dI($,U){let J=U?.enc??"hex",Q=`${$}_${J}`,W=LU[Q];if(!W)throw Error(`Unrecognized hash format: ${Q}`);return VW(_W,Q,W,U)}var AW=g("ZodNumber",($,U)=>{E9.init($,U),n$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>iY($,Q,W,K),p8($,"ZodNumber",{gt(Q,W){return this.check(JJ(Q,W))},gte(Q,W){return this.check(XU(Q,W))},min(Q,W){return this.check(XU(Q,W))},lt(Q,W){return this.check(UJ(Q,W))},lte(Q,W){return this.check(RU(Q,W))},max(Q,W){return this.check(RU(Q,W))},int(Q){return this.check(t9(Q))},safe(Q){return this.check(t9(Q))},positive(Q){return this.check(JJ(0,Q))},nonnegative(Q){return this.check(XU(0,Q))},negative(Q){return this.check(UJ(0,Q))},nonpositive(Q){return this.check(RU(0,Q))},multipleOf(Q,W){return this.check(cJ(Q,W))},step(Q,W){return this.check(cJ(Q,W))},finite(){return this}});let J=$._zod.bag;$.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),$.isFinite=!0,$.format=J.format??null});function i1($){return IY(AW,$)}var S0=g("ZodNumberFormat",($,U)=>{PN.init($,U),AW.init($,U)});function t9($){return DY(S0,$)}function cI($){return kY(S0,$)}function nI($){return FY(S0,$)}function iI($){return LY(S0,$)}function oI($){return RY(S0,$)}var CW=g("ZodBoolean",($,U)=>{A8.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>oY($,J,Q,W)});function o1($){return VY(CW,$)}var SW=g("ZodBigInt",($,U)=>{Z9.init($,U),n$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>rY($,Q,W,K),$.gte=(Q,W)=>$.check(XU(Q,W)),$.min=(Q,W)=>$.check(XU(Q,W)),$.gt=(Q,W)=>$.check(JJ(Q,W)),$.gte=(Q,W)=>$.check(XU(Q,W)),$.min=(Q,W)=>$.check(XU(Q,W)),$.lt=(Q,W)=>$.check(UJ(Q,W)),$.lte=(Q,W)=>$.check(RU(Q,W)),$.max=(Q,W)=>$.check(RU(Q,W)),$.positive=(Q)=>$.check(JJ(BigInt(0),Q)),$.negative=(Q)=>$.check(UJ(BigInt(0),Q)),$.nonpositive=(Q)=>$.check(RU(BigInt(0),Q)),$.nonnegative=(Q)=>$.check(XU(BigInt(0),Q)),$.multipleOf=(Q,W)=>$.check(cJ(Q,W));let J=$._zod.bag;$.minValue=J.minimum??null,$.maxValue=J.maximum??null,$.format=J.format??null});function rI($){return MY(SW,$)}var kK=g("ZodBigIntFormat",($,U)=>{zN.init($,U),SW.init($,U)});function aI($){return PY(kK,$)}function sI($){return zY(kK,$)}var r1=g("ZodSymbol",($,U)=>{_N.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>aY($,J,Q,W)});function tI($){return _Y(r1,$)}var a1=g("ZodUndefined",($,U)=>{AN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>tY($,J,Q,W)});function eI($){return AY(a1,$)}var s1=g("ZodNull",($,U)=>{CN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>sY($,J,Q,W)});function t1($){return CY(s1,$)}var e1=g("ZodAny",($,U)=>{SN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>U1($,J,Q,W)});function $q(){return SY(e1)}var $G=g("ZodUnknown",($,U)=>{TN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>J1($,J,Q,W)});function C0(){return TY($G)}var UG=g("ZodNever",($,U)=>{vN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>$1($,J,Q,W)});function FK($){return vY(UG,$)}var JG=g("ZodVoid",($,U)=>{jN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>eY($,J,Q,W)});function Uq($){return jY(JG,$)}var c8=g("ZodDate",($,U)=>{gN.init($,U),n$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>W1($,Q,W,K),$.min=(Q,W)=>$.check(XU(Q,W)),$.max=(Q,W)=>$.check(RU(Q,W));let J=$._zod.bag;$.minDate=J.minimum?new Date(J.minimum):null,$.maxDate=J.maximum?new Date(J.maximum):null});function Jq($){return gY(c8,$)}var WG=g("ZodArray",($,U)=>{bN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>q1($,J,Q,W),$.element=U.element,p8($,"ZodArray",{min(J,Q){return this.check(wJ(J,Q))},nonempty(J){return this.check(wJ(1,J))},max(J,Q){return this.check(_0(J,Q))},length(J,Q){return this.check(A0(J,Q))},unwrap(){return this.element}})});function n8($,U){return yY(WG,$,U)}function Wq($){let U=$._zod.def.shape;return RK(Object.keys(U))}var i8=g("ZodObject",($,U)=>{xN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>D1($,J,Q,W),Q$.defineLazy($,"shape",()=>{return U.shape}),p8($,"ZodObject",{keyof(){return RK(Object.keys(this._zod.def.shape))},catchall(J){return this.clone({...this._zod.def,catchall:J})},passthrough(){return this.clone({...this._zod.def,catchall:C0()})},loose(){return this.clone({...this._zod.def,catchall:C0()})},strict(){return this.clone({...this._zod.def,catchall:FK()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(J){return Q$.extend(this,J)},safeExtend(J){return Q$.safeExtend(this,J)},merge(J){return Q$.merge(this,J)},pick(J){return Q$.pick(this,J)},omit(J){return Q$.omit(this,J)},partial(...J){return Q$.partial(wK,this,J[0])},required(...J){return Q$.required(MK,this,J[0])}})});function Qq($,U){let J={type:"object",shape:$??{},...Q$.normalizeParams(U)};return new i8(J)}function Kq($,U){return new i8({type:"object",shape:$,catchall:FK(),...Q$.normalizeParams(U)})}function Xq($,U){return new i8({type:"object",shape:$,catchall:C0(),...Q$.normalizeParams(U)})}var o8=g("ZodUnion",($,U)=>{C8.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>d9($,J,Q,W),$.options=U.options});function LK($,U){return new o8({type:"union",options:$,...Q$.normalizeParams(U)})}var QG=g("ZodXor",($,U)=>{o8.init($,U),yN.init($,U),$._zod.processJSONSchema=(J,Q,W)=>d9($,J,Q,W),$.options=U.options});function Nq($,U){return new QG({type:"union",options:$,inclusive:!1,...Q$.normalizeParams(U)})}var KG=g("ZodDiscriminatedUnion",($,U)=>{o8.init($,U),hN.init($,U)});function Hq($,U,J){return new KG({type:"union",options:U,discriminator:$,...Q$.normalizeParams(J)})}var XG=g("ZodIntersection",($,U)=>{fN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>k1($,J,Q,W)});function NG($,U){return new XG({type:"intersection",left:$,right:U})}var HG=g("ZodTuple",($,U)=>{I9.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>F1($,J,Q,W),$.rest=(J)=>$.clone({...$._zod.def,rest:J})});function YG($,U,J){let Q=U instanceof h$,W=Q?J:U;return new HG({type:"tuple",items:$,rest:Q?U:null,...Q$.normalizeParams(W)})}var BW=g("ZodRecord",($,U)=>{uN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>L1($,J,Q,W),$.keyType=U.keyType,$.valueType=U.valueType});function GG($,U,J){if(!U||!U._zod)return new BW({type:"record",keyType:f8(),valueType:$,...Q$.normalizeParams(U)});return new BW({type:"record",keyType:$,valueType:U,...Q$.normalizeParams(J)})}function Yq($,U,J){let Q=QU($);return Q._zod.values=void 0,new BW({type:"record",keyType:Q,valueType:U,...Q$.normalizeParams(J)})}function Gq($,U,J){return new BW({type:"record",keyType:$,valueType:U,mode:"loose",...Q$.normalizeParams(J)})}var OG=g("ZodMap",($,U)=>{lN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>Z1($,J,Q,W),$.keyType=U.keyType,$.valueType=U.valueType,$.min=(...J)=>$.check(WJ(...J)),$.nonempty=(J)=>$.check(WJ(1,J)),$.max=(...J)=>$.check(nJ(...J)),$.size=(...J)=>$.check(z0(...J))});function Oq($,U,J){return new OG({type:"map",keyType:$,valueType:U,...Q$.normalizeParams(J)})}var EG=g("ZodSet",($,U)=>{mN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>I1($,J,Q,W),$.min=(...J)=>$.check(WJ(...J)),$.nonempty=(J)=>$.check(WJ(1,J)),$.max=(...J)=>$.check(nJ(...J)),$.size=(...J)=>$.check(z0(...J))});function Eq($,U){return new EG({type:"set",valueType:$,...Q$.normalizeParams(U)})}var PW=g("ZodEnum",($,U)=>{pN.init($,U),n$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>Q1($,Q,W,K),$.enum=U.entries,$.options=Object.values(U.entries);let J=new Set(Object.keys(U.entries));$.extract=(Q,W)=>{let K={};for(let X of Q)if(J.has(X))K[X]=U.entries[X];else throw Error(`Key ${X} not found in enum`);return new PW({...U,checks:[],...Q$.normalizeParams(W),entries:K})},$.exclude=(Q,W)=>{let K={...U.entries};for(let X of Q)if(J.has(X))delete K[X];else throw Error(`Key ${X} not found in enum`);return new PW({...U,checks:[],...Q$.normalizeParams(W),entries:K})}});function RK($,U){let J=Array.isArray($)?Object.fromEntries($.map((Q)=>[Q,Q])):$;return new PW({type:"enum",entries:J,...Q$.normalizeParams(U)})}function Zq($,U){return new PW({type:"enum",entries:$,...Q$.normalizeParams(U)})}var ZG=g("ZodLiteral",($,U)=>{dN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>K1($,J,Q,W),$.values=new Set(U.values),Object.defineProperty($,"value",{get(){if(U.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return U.values[0]}})});function Iq($,U){return new ZG({type:"literal",values:Array.isArray($)?$:[$],...Q$.normalizeParams(U)})}var IG=g("ZodFile",($,U)=>{cN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>H1($,J,Q,W),$.min=(J,Q)=>$.check(WJ(J,Q)),$.max=(J,Q)=>$.check(nJ(J,Q)),$.mime=(J,Q)=>$.check(qW(Array.isArray(J)?J:[J],Q))});function qq($){return hY(IG,$)}var qG=g("ZodTransform",($,U)=>{nN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>E1($,J,Q,W),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new w0($.constructor.name);J.addIssue=(K)=>{if(typeof K==="string")J.issues.push(Q$.issue(K,J.value,U));else{let X=K;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=J.value),X.inst??(X.inst=$),J.issues.push(Q$.issue(X))}};let W=U.transform(J.value,J);if(W instanceof Promise)return W.then((K)=>{return J.value=K,J.fallback=!0,J});return J.value=W,J.fallback=!0,J}});function VK($){return new qG({type:"transform",transform:$})}var wK=g("ZodOptional",($,U)=>{q9.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>c9($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function l8($){return new wK({type:"optional",innerType:$})}var DG=g("ZodExactOptional",($,U)=>{iN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>c9($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function kG($){return new DG({type:"optional",innerType:$})}var FG=g("ZodNullable",($,U)=>{oN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>R1($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function m8($){return new FG({type:"nullable",innerType:$})}function Dq($){return l8(m8($))}var LG=g("ZodDefault",($,U)=>{rN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>w1($,J,Q,W),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function RG($,U){return new LG({type:"default",innerType:$,get defaultValue(){return typeof U==="function"?U():Q$.shallowClone(U)}})}var VG=g("ZodPrefault",($,U)=>{aN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>M1($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function wG($,U){return new VG({type:"prefault",innerType:$,get defaultValue(){return typeof U==="function"?U():Q$.shallowClone(U)}})}var MK=g("ZodNonOptional",($,U)=>{sN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>V1($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function MG($,U){return new MK({type:"nonoptional",innerType:$,...Q$.normalizeParams(U)})}var BG=g("ZodSuccess",($,U)=>{tN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>Y1($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function kq($){return new BG({type:"success",innerType:$})}var PG=g("ZodCatch",($,U)=>{eN.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>B1($,J,Q,W),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function zG($,U){return new PG({type:"catch",innerType:$,catchValue:typeof U==="function"?U:()=>U})}var _G=g("ZodNaN",($,U)=>{$H.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>X1($,J,Q,W)});function Fq($){return xY(_G,$)}var r8=g("ZodPipe",($,U)=>{D9.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>P1($,J,Q,W),$.in=U.in,$.out=U.out});function e9($,U){return new r8({type:"pipe",in:$,out:U})}var a8=g("ZodCodec",($,U)=>{r8.init($,U),S8.init($,U)});function Lq($,U,J){return new a8({type:"pipe",in:$,out:U,transform:J.decode,reverseTransform:J.encode})}function Rq($){let U=$._zod.def;return new a8({type:"pipe",in:U.out,out:U.in,transform:U.reverseTransform,reverseTransform:U.transform})}var AG=g("ZodPreprocess",($,U)=>{r8.init($,U),UH.init($,U)}),CG=g("ZodReadonly",($,U)=>{JH.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>z1($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function SG($){return new CG({type:"readonly",innerType:$})}var TG=g("ZodTemplateLiteral",($,U)=>{WH.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>N1($,J,Q,W)});function Vq($,U){return new TG({type:"template_literal",parts:$,...Q$.normalizeParams(U)})}var vG=g("ZodLazy",($,U)=>{XH.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>A1($,J,Q,W),$.unwrap=()=>$._zod.def.getter()});function jG($){return new vG({type:"lazy",getter:$})}var gG=g("ZodPromise",($,U)=>{KH.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>_1($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function wq($){return new gG({type:"promise",innerType:$})}var bG=g("ZodFunction",($,U)=>{QH.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>O1($,J,Q,W)});function Mq($){return new bG({type:"function",input:Array.isArray($?.input)?YG($?.input):$?.input??n8(C0()),output:$?.output??C0()})}var s8=g("ZodCustom",($,U)=>{NH.init($,U),n$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>G1($,J,Q,W)});function Bq($){let U=new V6({check:"custom"});return U._zod.check=$,U}function Pq($,U){return fY(s8,$??(()=>!0),U)}function xG($,U={}){return uY(s8,$,U)}function yG($,U){return lY($,U)}var zq=mY,_q=pY;function Aq($,U={}){let J=new s8({type:"custom",check:"custom",fn:(Q)=>Q instanceof $,abort:!0,...Q$.normalizeParams(U)});return J._zod.bag.Class=$,J._zod.check=(Q)=>{if(!(Q.value instanceof $))Q.issues.push({code:"invalid_type",expected:$.name,input:Q.value,inst:J,path:[...J._zod.def.path??[]]})},J}var Cq=(...$)=>dY({Codec:a8,Boolean:CW,String:zW},...$);function Sq($){let U=jG(()=>{return LK([f8($),i1(),o1(),t1(),n8(U),GG(f8(),U)])});return U}function Tq($,U){return new AG({type:"pipe",in:VK($),out:U})}var tL={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function eL($){T6({customError:$})}function $R(){return T6().customError}var hG;(function($){})(hG||(hG={}));var q$={...h8,...i9,iso:MW},UR=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function JR($,U){let J=$.$schema;if(J==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(J==="http://json-schema.org/draft-07/schema#")return"draft-7";if(J==="http://json-schema.org/draft-04/schema#")return"draft-4";return U??"draft-2020-12"}function WR($,U){if(!$.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let J=$.slice(1).split("/").filter(Boolean);if(J.length===0)return U.rootSchema;let Q=U.version==="draft-2020-12"?"$defs":"definitions";if(J[0]===Q){let W=J[1];if(!W||!U.defs[W])throw Error(`Reference not found: ${$}`);return U.defs[W]}throw Error(`Reference not found: ${$}`)}function vq($,U){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return q$.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if($.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if($.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if($.if!==void 0||$.then!==void 0||$.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if($.dependentSchemas!==void 0||$.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if($.$ref){let W=$.$ref;if(U.refs.has(W))return U.refs.get(W);if(U.processing.has(W))return q$.lazy(()=>{if(!U.refs.has(W))throw Error(`Circular reference not resolved: ${W}`);return U.refs.get(W)});U.processing.add(W);let K=WR(W,U),X=e6(K,U);return U.refs.set(W,X),U.processing.delete(W),X}if($.enum!==void 0){let W=$.enum;if(U.version==="openapi-3.0"&&$.nullable===!0&&W.length===1&&W[0]===null)return q$.null();if(W.length===0)return q$.never();if(W.length===1)return q$.literal(W[0]);if(W.every((X)=>typeof X==="string"))return q$.enum(W);let K=W.map((X)=>q$.literal(X));if(K.length<2)return K[0];return q$.union([K[0],K[1],...K.slice(2)])}if($.const!==void 0)return q$.literal($.const);let J=$.type;if(Array.isArray(J)){let W=J.map((K)=>{let X={...$,type:K};return vq(X,U)});if(W.length===0)return q$.never();if(W.length===1)return W[0];return q$.union(W)}if(!J)return q$.any();let Q;switch(J){case"string":{let W=q$.string();if($.format){let K=$.format;if(K==="email")W=W.check(q$.email());else if(K==="uri"||K==="uri-reference")W=W.check(q$.url());else if(K==="uuid"||K==="guid")W=W.check(q$.uuid());else if(K==="date-time")W=W.check(q$.iso.datetime());else if(K==="date")W=W.check(q$.iso.date());else if(K==="time")W=W.check(q$.iso.time());else if(K==="duration")W=W.check(q$.iso.duration());else if(K==="ipv4")W=W.check(q$.ipv4());else if(K==="ipv6")W=W.check(q$.ipv6());else if(K==="mac")W=W.check(q$.mac());else if(K==="cidr")W=W.check(q$.cidrv4());else if(K==="cidr-v6")W=W.check(q$.cidrv6());else if(K==="base64")W=W.check(q$.base64());else if(K==="base64url")W=W.check(q$.base64url());else if(K==="e164")W=W.check(q$.e164());else if(K==="jwt")W=W.check(q$.jwt());else if(K==="emoji")W=W.check(q$.emoji());else if(K==="nanoid")W=W.check(q$.nanoid());else if(K==="cuid")W=W.check(q$.cuid());else if(K==="cuid2")W=W.check(q$.cuid2());else if(K==="ulid")W=W.check(q$.ulid());else if(K==="xid")W=W.check(q$.xid());else if(K==="ksuid")W=W.check(q$.ksuid())}if(typeof $.minLength==="number")W=W.min($.minLength);if(typeof $.maxLength==="number")W=W.max($.maxLength);if($.pattern)W=W.regex(new RegExp($.pattern));Q=W;break}case"number":case"integer":{let W=J==="integer"?q$.number().int():q$.number();if(typeof $.minimum==="number")W=W.min($.minimum);if(typeof $.maximum==="number")W=W.max($.maximum);if(typeof $.exclusiveMinimum==="number")W=W.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")W=W.gt($.minimum);if(typeof $.exclusiveMaximum==="number")W=W.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")W=W.lt($.maximum);if(typeof $.multipleOf==="number")W=W.multipleOf($.multipleOf);Q=W;break}case"boolean":{Q=q$.boolean();break}case"null":{Q=q$.null();break}case"object":{let W={},K=$.properties||{},X=new Set($.required||[]);for(let[H,Y]of Object.entries(K)){let G=e6(Y,U);W[H]=X.has(H)?G:G.optional()}if($.propertyNames){let H=e6($.propertyNames,U),Y=$.additionalProperties&&typeof $.additionalProperties==="object"?e6($.additionalProperties,U):q$.any();if(Object.keys(W).length===0){Q=q$.record(H,Y);break}let G=q$.object(W).passthrough(),O=q$.looseRecord(H,Y);Q=q$.intersection(G,O);break}if($.patternProperties){let H=$.patternProperties,Y=Object.keys(H),G=[];for(let E of Y){let Z=e6(H[E],U),D=q$.string().regex(new RegExp(E));G.push(q$.looseRecord(D,Z))}let O=[];if(Object.keys(W).length>0)O.push(q$.object(W).passthrough());if(O.push(...G),O.length===0)Q=q$.object({}).passthrough();else if(O.length===1)Q=O[0];else{let E=q$.intersection(O[0],O[1]);for(let Z=2;Z<O.length;Z++)E=q$.intersection(E,O[Z]);Q=E}break}let N=q$.object(W);if($.additionalProperties===!1)Q=N.strict();else if(typeof $.additionalProperties==="object")Q=N.catchall(e6($.additionalProperties,U));else Q=N.passthrough();break}case"array":{let{prefixItems:W,items:K}=$;if(W&&Array.isArray(W)){let X=W.map((H)=>e6(H,U)),N=K&&typeof K==="object"&&!Array.isArray(K)?e6(K,U):void 0;if(N)Q=q$.tuple(X).rest(N);else Q=q$.tuple(X);if(typeof $.minItems==="number")Q=Q.check(q$.minLength($.minItems));if(typeof $.maxItems==="number")Q=Q.check(q$.maxLength($.maxItems))}else if(Array.isArray(K)){let X=K.map((H)=>e6(H,U)),N=$.additionalItems&&typeof $.additionalItems==="object"?e6($.additionalItems,U):void 0;if(N)Q=q$.tuple(X).rest(N);else Q=q$.tuple(X);if(typeof $.minItems==="number")Q=Q.check(q$.minLength($.minItems));if(typeof $.maxItems==="number")Q=Q.check(q$.maxLength($.maxItems))}else if(K!==void 0){let X=e6(K,U),N=q$.array(X);if(typeof $.minItems==="number")N=N.min($.minItems);if(typeof $.maxItems==="number")N=N.max($.maxItems);Q=N}else Q=q$.array(q$.any());break}default:throw Error(`Unsupported type: ${J}`)}return Q}function e6($,U){if(typeof $==="boolean")return $?q$.any():q$.never();let J=vq($,U),Q=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let N=$.anyOf.map((Y)=>e6(Y,U)),H=q$.union(N);J=Q?q$.intersection(J,H):H}if($.oneOf&&Array.isArray($.oneOf)){let N=$.oneOf.map((Y)=>e6(Y,U)),H=q$.xor(N);J=Q?q$.intersection(J,H):H}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)J=Q?J:q$.any();else{let N=Q?J:e6($.allOf[0],U),H=Q?0:1;for(let Y=H;Y<$.allOf.length;Y++)N=q$.intersection(N,e6($.allOf[Y],U));J=N}if($.nullable===!0&&U.version==="openapi-3.0")J=q$.nullable(J);if($.readOnly===!0)J=q$.readonly(J);if($.default!==void 0)J=J.default($.default);let W={},K=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let N of K)if(N in $)W[N]=$[N];let X=["contentEncoding","contentMediaType","contentSchema"];for(let N of X)if(N in $)W[N]=$[N];for(let N of Object.keys($))if(!UR.has(N))W[N]=$[N];if(Object.keys(W).length>0)U.registry.add(J,W);if($.description)J=J.describe($.description);return J}function jq($,U){if(typeof $==="boolean")return $?q$.any():q$.never();let J;try{J=JSON.parse(JSON.stringify($))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let Q=JR(J,U?.defaultTarget),W=J.$defs||J.definitions||{},K={version:Q,defs:W,refs:new Map,processing:new Set,rootSchema:J,registry:U?.registry??a6};return e6(J,K)}var fG={};RJ(fG,{string:()=>QR,number:()=>KR,date:()=>HR,boolean:()=>XR,bigint:()=>NR});function QR($){return NY(zW,$)}function KR($){return qY(AW,$)}function XR($){return wY(CW,$)}function NR($){return BY(SW,$)}function HR($){return bY(c8,$)}T6(T8());/*!+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of e.seen.entries()){let a=o[1];if(t===o[0]){s(o);continue}if(e.external){let l=e.external.registry.get(o[0])?.id;if(t!==o[0]&&l){s(o);continue}}if(e.metadataRegistry.get(o[0])?.id){s(o);continue}if(a.cycle){s(o);continue}if(a.count>1){if(e.reused==="ref"){s(o);continue}}}}function Lc(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},f=c.ref;if(c.ref=null,f){i(f);let d=e.seen.get(f),g=d.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(g);else Object.assign(l,g);if(Object.assign(l,u),a._zod.parent===f)for(let p in l){if(p==="$ref"||p==="allOf")continue;if(!(p in u))delete l[p]}if(g.$ref&&d.def)for(let p in l){if(p==="$ref"||p==="allOf")continue;if(p in d.def&&JSON.stringify(l[p])===JSON.stringify(d.def[p]))delete l[p]}}let h=a._zod.parent;if(h&&h!==f){i(h);let d=e.seen.get(h);if(d?.schema.$ref){if(l.$ref=d.schema.$ref,d.def)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(g in d.def&&JSON.stringify(l[g])===JSON.stringify(d.def[g]))delete l[g]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())i(a[0]);let r={};if(e.target==="draft-2020-12")r.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")r.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")r.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&r.id===s)delete r.id;let o=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;o[c.defId]=c.def}}if(e.external);else if(Object.keys(o).length>0)if(e.target==="draft-2020-12")r.$defs=o;else r.definitions=o;try{let a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:bs(t,"input",e.processors),output:bs(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Jt(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return Jt(i.element,n);if(i.type==="set")return Jt(i.valueType,n);if(i.type==="lazy")return Jt(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return Jt(i.innerType,n);if(i.type==="intersection")return Jt(i.left,n)||Jt(i.right,n);if(i.type==="record"||i.type==="map")return Jt(i.keyType,n)||Jt(i.valueType,n);if(i.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Jt(i.in,n)||Jt(i.out,n)}if(i.type==="object"){for(let r in i.shape)if(Jt(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(let r of i.options)if(Jt(r,n))return!0;return!1}if(i.type==="tuple"){for(let r of i.items)if(Jt(r,n))return!0;if(i.rest&&Jt(i.rest,n))return!0;return!1}return!1}var vp=(e,t={})=>(n)=>{let i=Ic({...n,processors:t});return At(e,i),Pc(i,e),Lc(i,e)},bs=(e,t,n={})=>(i)=>{let{libraryOptions:r,target:s}=i??{},o=Ic({...r??{},target:s,io:t,processors:n});return At(e,o),Pc(o,e),Lc(o,e)};var dx={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yp=(e,t,n,i)=>{let r=n;r.type="string";let{minimum:s,maximum:o,format:a,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof s==="number")r.minLength=s;if(typeof o==="number")r.maxLength=o;if(a){if(r.format=dx[a]??a,r.format==="")delete r.format;if(a==="time")delete r.format}if(l)r.contentEncoding=l;if(c&&c.size>0){let u=[...c];if(u.length===1)r.pattern=u[0].source;else if(u.length>1)r.allOf=[...u.map((f)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}},bp=(e,t,n,i)=>{let r=n,{minimum:s,maximum:o,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))r.type="integer";else r.type="number";let f=typeof u==="number"&&u>=(s??Number.NEGATIVE_INFINITY),h=typeof l==="number"&&l<=(o??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(d)r.minimum=u,r.exclusiveMinimum=!0;else r.exclusiveMinimum=u;else if(typeof s==="number")r.minimum=s;if(h)if(d)r.maximum=l,r.exclusiveMaximum=!0;else r.exclusiveMaximum=l;else if(typeof o==="number")r.maximum=o;if(typeof c==="number")r.multipleOf=c},Sp=(e,t,n,i)=>{n.type="boolean"};var Mp=(e,t,n,i)=>{n.not={}};var wp=(e,t,n,i)=>{};var Tp=(e,t,n,i)=>{let r=e._zod.def,s=yo(r.entries);if(s.every((o)=>typeof o==="number"))n.type="number";if(s.every((o)=>typeof o==="string"))n.type="string";n.enum=s},Ep=(e,t,n,i)=>{let r=e._zod.def,s=[];for(let o of r.values)if(o===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(o));else s.push(o);if(s.length===0);else if(s.length===1){let o=s[0];if(n.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[o];else n.const=o}else{if(s.every((o)=>typeof o==="number"))n.type="number";if(s.every((o)=>typeof o==="string"))n.type="string";if(s.every((o)=>typeof o==="boolean"))n.type="boolean";if(s.every((o)=>o===null))n.type="null";n.enum=s}};var Ap=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")};var Rp=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")};var Cp=(e,t,n,i)=>{let r=n,s=e._zod.def,{minimum:o,maximum:a}=e._zod.bag;if(typeof o==="number")r.minItems=o;if(typeof a==="number")r.maxItems=a;r.type="array",r.items=At(s.element,t,{...i,path:[...i.path,"items"]})},Ip=(e,t,n,i)=>{let r=n,s=e._zod.def;r.type="object",r.properties={};let o=s.shape;for(let l in o)r.properties[l]=At(o[l],t,{...i,path:[...i.path,"properties",l]});let a=new Set(Object.keys(o)),c=new Set([...a].filter((l)=>{let u=s.shape[l]._zod;if(t.io==="input")return u.optin===void 0;else return u.optout===void 0}));if(c.size>0)r.required=Array.from(c);if(s.catchall?._zod.def.type==="never")r.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")r.additionalProperties=!1}else if(s.catchall)r.additionalProperties=At(s.catchall,t,{...i,path:[...i.path,"additionalProperties"]})},Pp=(e,t,n,i)=>{let r=e._zod.def,s=r.inclusive===!1,o=r.options.map((a,c)=>At(a,t,{...i,path:[...i.path,s?"oneOf":"anyOf",c]}));if(s)n.oneOf=o;else n.anyOf=o},Lp=(e,t,n,i)=>{let r=e._zod.def,s=At(r.left,t,{...i,path:[...i.path,"allOf",0]}),o=At(r.right,t,{...i,path:[...i.path,"allOf",1]}),a=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...a(s)?s.allOf:[s],...a(o)?o.allOf:[o]];n.allOf=c};var Np=(e,t,n,i)=>{let r=n,s=e._zod.def;r.type="object";let o=s.keyType,c=o._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let u=At(s.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(let f of c)r.patternProperties[f.source]=u}else{if(t.target==="draft-07"||t.target==="draft-2020-12")r.propertyNames=At(s.keyType,t,{...i,path:[...i.path,"propertyNames"]});r.additionalProperties=At(s.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let l=o._zod.values;if(l){let u=[...l].filter((f)=>typeof f==="string"||typeof f==="number");if(u.length>0)r.required=u}},Dp=(e,t,n,i)=>{let r=e._zod.def,s=At(r.innerType,t,i),o=t.seen.get(e);if(t.target==="openapi-3.0")o.ref=r.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},Up=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType},Op=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},Fp=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);if(s.ref=r.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(r.defaultValue))},zp=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},kp=(e,t,n,i)=>{let r=e._zod.def,s=r.in._zod.traits.has("$ZodTransform"),o=t.io==="input"?s?r.out:r.in:r.out;At(o,t,i);let a=t.seen.get(e);a.ref=o},Bp=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0};var Nc=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType};var yx=q("ZodISODateTime",(e,t)=>{td.init(e,t),vt.init(e,t)});function Gp(e){return ap(yx,e)}var bx=q("ZodISODate",(e,t)=>{nd.init(e,t),vt.init(e,t)});function Hp(e){return cp(bx,e)}var Sx=q("ZodISOTime",(e,t)=>{id.init(e,t),vt.init(e,t)});function Vp(e){return lp(Sx,e)}var Mx=q("ZodISODuration",(e,t)=>{rd.init(e,t),vt.init(e,t)});function Wp(e){return up(Mx,e)}var Ex=(e,t)=>{To.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Oh(e,n)},flatten:{value:(n)=>Uh(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ms,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ms,2)}},isEmpty:{get(){return e.issues.length===0}}})};var an=q("ZodError",Ex,{Parent:Error});var $p=Eo(an),Zp=Ao(an),Xp=gs(an),qp=_s(an),Yp=kh(an),jp=Bh(an),Jp=Gh(an),Kp=Hh(an),Qp=Vh(an),em=Wh(an),tm=$h(an),nm=Zh(an);var im=new WeakMap;function Ss(e,t,n){let i=Object.getPrototypeOf(e),r=im.get(i);if(!r)r=new Set,im.set(i,r);if(r.has(t))return;r.add(t);for(let s in n){let o=n[s];Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get(){let a=o.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var yt=q("ZodType",(e,t)=>(xt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:bs(e,"input"),output:bs(e,"output")}}),e.toJSONSchema=vp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,i)=>$p(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>Xp(e,n,i),e.parseAsync=async(n,i)=>Zp(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>qp(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>Yp(e,n,i),e.decode=(n,i)=>jp(e,n,i),e.encodeAsync=async(n,i)=>Jp(e,n,i),e.decodeAsync=async(n,i)=>Kp(e,n,i),e.safeEncode=(n,i)=>Qp(e,n,i),e.safeDecode=(n,i)=>em(e,n,i),e.safeEncodeAsync=async(n,i)=>tm(e,n,i),e.safeDecodeAsync=async(n,i)=>nm(e,n,i),Ss(e,"ZodType",{check(...n){let i=this.def;return this.clone(bi(i,{checks:[...i.checks??[],...n.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,i){return Gn(this,n,i)},brand(){return this},register(n,i){return n.add(this,i),this},refine(n,i){return this.check(Mv(n,i))},superRefine(n,i){return this.check(wv(n,i))},overwrite(n){return this.check(Ti(n))},optional(){return am(this)},exactOptional(){return uv(this)},nullable(){return cm(this)},nullish(){return am(cm(this))},nonoptional(n){return gv(this,n)},array(){return ko(this)},or(n){return nv([this,n])},and(n){return rv(this,n)},transform(n){return lm(this,cv(n))},default(n){return dv(this,n)},prefault(n){return mv(this,n)},catch(n){return xv(this,n)},pipe(n){return lm(this,n)},readonly(){return bv(this)},describe(n){let i=this.clone();return tr.add(i,{description:n}),i},meta(...n){if(n.length===0)return tr.get(this);let i=this.clone();return tr.add(i,n[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return tr.get(e)?.description},configurable:!0}),e)),um=q("_ZodString",(e,t)=>{Po.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(i,r,s)=>yp(e,i,r,s);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ss(e,"_ZodString",{regex(...i){return this.check(vc(...i))},includes(...i){return this.check(Sc(...i))},startsWith(...i){return this.check(Mc(...i))},endsWith(...i){return this.check(wc(...i))},min(...i){return this.check(Ar(...i))},max(...i){return this.check(Uo(...i))},length(...i){return this.check(Oo(...i))},nonempty(...i){return this.check(Ar(1,...i))},lowercase(i){return this.check(yc(i))},uppercase(i){return this.check(bc(i))},trim(){return this.check(Ec())},normalize(...i){return this.check(Tc(...i))},toLowerCase(){return this.check(Ac())},toUpperCase(){return this.check(Rc())},slugify(){return this.check(Cc())}})}),Rx=q("ZodString",(e,t)=>{Po.init(e,t),um.init(e,t),e.email=(n)=>e.check(Bd(Cx,n)),e.url=(n)=>e.check($d(Ix,n)),e.jwt=(n)=>e.check(op($x,n)),e.emoji=(n)=>e.check(Zd(Px,n)),e.guid=(n)=>e.check(xc(rm,n)),e.uuid=(n)=>e.check(Gd(zo,n)),e.uuidv4=(n)=>e.check(Hd(zo,n)),e.uuidv6=(n)=>e.check(Vd(zo,n)),e.uuidv7=(n)=>e.check(Wd(zo,n)),e.nanoid=(n)=>e.check(Xd(Lx,n)),e.guid=(n)=>e.check(xc(rm,n)),e.cuid=(n)=>e.check(qd(Nx,n)),e.cuid2=(n)=>e.check(Yd(Dx,n)),e.ulid=(n)=>e.check(jd(Ux,n)),e.base64=(n)=>e.check(ip(Hx,n)),e.base64url=(n)=>e.check(rp(Vx,n)),e.xid=(n)=>e.check(Jd(Ox,n)),e.ksuid=(n)=>e.check(Kd(Fx,n)),e.ipv4=(n)=>e.check(Qd(zx,n)),e.ipv6=(n)=>e.check(ep(kx,n)),e.cidrv4=(n)=>e.check(tp(Bx,n)),e.cidrv6=(n)=>e.check(np(Gx,n)),e.e164=(n)=>e.check(sp(Wx,n)),e.datetime=(n)=>e.check(Gp(n)),e.date=(n)=>e.check(Hp(n)),e.time=(n)=>e.check(Vp(n)),e.duration=(n)=>e.check(Wp(n))});function Zt(e){return kd(Rx,e)}var vt=q("ZodStringFormat",(e,t)=>{_t.init(e,t),um.init(e,t)}),Cx=q("ZodEmail",(e,t)=>{Zf.init(e,t),vt.init(e,t)});var rm=q("ZodGUID",(e,t)=>{Wf.init(e,t),vt.init(e,t)});var zo=q("ZodUUID",(e,t)=>{$f.init(e,t),vt.init(e,t)});var Ix=q("ZodURL",(e,t)=>{Xf.init(e,t),vt.init(e,t)});var Px=q("ZodEmoji",(e,t)=>{qf.init(e,t),vt.init(e,t)});var Lx=q("ZodNanoID",(e,t)=>{Yf.init(e,t),vt.init(e,t)});var Nx=q("ZodCUID",(e,t)=>{jf.init(e,t),vt.init(e,t)});var Dx=q("ZodCUID2",(e,t)=>{Jf.init(e,t),vt.init(e,t)});var Ux=q("ZodULID",(e,t)=>{Kf.init(e,t),vt.init(e,t)});var Ox=q("ZodXID",(e,t)=>{Qf.init(e,t),vt.init(e,t)});var Fx=q("ZodKSUID",(e,t)=>{ed.init(e,t),vt.init(e,t)});var zx=q("ZodIPv4",(e,t)=>{sd.init(e,t),vt.init(e,t)});var kx=q("ZodIPv6",(e,t)=>{od.init(e,t),vt.init(e,t)});var Bx=q("ZodCIDRv4",(e,t)=>{ad.init(e,t),vt.init(e,t)});var Gx=q("ZodCIDRv6",(e,t)=>{cd.init(e,t),vt.init(e,t)});var Hx=q("ZodBase64",(e,t)=>{ud.init(e,t),vt.init(e,t)});var Vx=q("ZodBase64URL",(e,t)=>{hd.init(e,t),vt.init(e,t)});var Wx=q("ZodE164",(e,t)=>{fd.init(e,t),vt.init(e,t)});var $x=q("ZodJWT",(e,t)=>{dd.init(e,t),vt.init(e,t)});var hm=q("ZodNumber",(e,t)=>{gc.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(i,r,s)=>bp(e,i,r,s),Ss(e,"ZodNumber",{gt(i,r){return this.check(No(i,r))},gte(i,r){return this.check(ys(i,r))},min(i,r){return this.check(ys(i,r))},lt(i,r){return this.check(Lo(i,r))},lte(i,r){return this.check(vs(i,r))},max(i,r){return this.check(vs(i,r))},int(i){return this.check(sm(i))},safe(i){return this.check(sm(i))},positive(i){return this.check(No(0,i))},nonnegative(i){return this.check(ys(0,i))},negative(i){return this.check(Lo(0,i))},nonpositive(i){return this.check(vs(0,i))},multipleOf(i,r){return this.check(Do(i,r))},step(i,r){return this.check(Do(i,r))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??0.5),e.isFinite=!0,e.format=n.format??null});function Zx(e){return hp(hm,e)}var Xx=q("ZodNumberFormat",(e,t)=>{pd.init(e,t),hm.init(e,t)});function sm(e){return fp(Xx,e)}var qx=q("ZodBoolean",(e,t)=>{md.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Sp(e,n,i,r)});function Yx(e){return dp(qx,e)}var jx=q("ZodUnknown",(e,t)=>{gd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>wp(e,n,i,r)});function nr(){return pp(jx)}var Jx=q("ZodNever",(e,t)=>{_d.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Mp(e,n,i,r)});function Kx(e){return mp(Jx,e)}var Qx=q("ZodArray",(e,t)=>{xd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Cp(e,n,i,r),e.element=t.element,Ss(e,"ZodArray",{min(n,i){return this.check(Ar(n,i))},nonempty(n){return this.check(Ar(1,n))},max(n,i){return this.check(Uo(n,i))},length(n,i){return this.check(Oo(n,i))},unwrap(){return this.element}})});function ko(e,t){return gp(Qx,e,t)}var ev=q("ZodObject",(e,t)=>{bd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ip(e,n,i,r),it(e,"shape",()=>t.shape),Ss(e,"ZodObject",{keyof(){return dm(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:nr()})},loose(){return this.clone({...this._zod.def,catchall:nr()})},strict(){return this.clone({...this._zod.def,catchall:Kx()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return tx(this,n)},safeExtend(n){return nx(this,n)},merge(n){return ix(this,n)},pick(n){return Q0(this,n)},omit(n){return ex(this,n)},partial(...n){return rx(pm,this,n[0])},required(...n){return sx(mm,this,n[0])}})});function Ms(e,t){let n={type:"object",shape:e??{},...Te(t)};return new ev(n)}var tv=q("ZodUnion",(e,t)=>{Sd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Pp(e,n,i,r),e.options=t.options});function nv(e,t){return new tv({type:"union",options:e,...Te(t)})}var iv=q("ZodIntersection",(e,t)=>{Md.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Lp(e,n,i,r)});function rv(e,t){return new iv({type:"intersection",left:e,right:t})}var om=q("ZodRecord",(e,t)=>{wd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Np(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function fm(e,t,n){if(!t||!t._zod)return new om({type:"record",keyType:Zt(),valueType:e,...Te(t)});return new om({type:"record",keyType:e,valueType:t,...Te(n)})}var Dc=q("ZodEnum",(e,t)=>{Td.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(i,r,s)=>Tp(e,i,r,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{let s={};for(let o of i)if(n.has(o))s[o]=t.entries[o];else throw Error(`Key ${o} not found in enum`);return new Dc({...t,checks:[],...Te(r),entries:s})},e.exclude=(i,r)=>{let s={...t.entries};for(let o of i)if(n.has(o))delete s[o];else throw Error(`Key ${o} not found in enum`);return new Dc({...t,checks:[],...Te(r),entries:s})}});function dm(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((i)=>[i,i])):e;return new Dc({type:"enum",entries:n,...Te(t)})}var sv=q("ZodLiteral",(e,t)=>{Ed.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ep(e,n,i,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function ov(e,t){return new sv({type:"literal",values:Array.isArray(e)?e:[e],...Te(t)})}var av=q("ZodTransform",(e,t)=>{Ad.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Rp(e,n,i,r),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new ds(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(er(s,n.value,t));else{let o=s;if(o.fatal)o.continue=!1;o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),n.issues.push(er(o))}};let r=t.transform(n.value,n);if(r instanceof Promise)return r.then((s)=>(n.value=s,n.fallback=!0,n));return n.value=r,n.fallback=!0,n}});function cv(e){return new av({type:"transform",transform:e})}var pm=q("ZodOptional",(e,t)=>{_c.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Nc(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function am(e){return new pm({type:"optional",innerType:e})}var lv=q("ZodExactOptional",(e,t)=>{Rd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Nc(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function uv(e){return new lv({type:"optional",innerType:e})}var hv=q("ZodNullable",(e,t)=>{Cd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Dp(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function cm(e){return new hv({type:"nullable",innerType:e})}var fv=q("ZodDefault",(e,t)=>{Id.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Op(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function dv(e,t){return new fv({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():ac(t)}})}var pv=q("ZodPrefault",(e,t)=>{Pd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Fp(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function mv(e,t){return new pv({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():ac(t)}})}var mm=q("ZodNonOptional",(e,t)=>{Ld.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Up(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function gv(e,t){return new mm({type:"nonoptional",innerType:e,...Te(t)})}var _v=q("ZodCatch",(e,t)=>{Nd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>zp(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function xv(e,t){return new _v({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var vv=q("ZodPipe",(e,t)=>{Dd.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>kp(e,n,i,r),e.in=t.in,e.out=t.out});function lm(e,t){return new vv({type:"pipe",in:e,out:t})}var yv=q("ZodReadonly",(e,t)=>{Ud.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Bp(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function bv(e){return new yv({type:"readonly",innerType:e})}var Sv=q("ZodCustom",(e,t)=>{Od.init(e,t),yt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ap(e,n,i,r)});function Mv(e,t={}){return _p(Sv,e,t)}function wv(e,t){return xp(e,t)}/*!fflate - fast JavaScript compression/decompression<https://101arrowz.github.io/fflate>Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSEversion 0.8.2-*/var A6=Uint8Array,VU=Uint16Array,aG=Int32Array,BK=new A6([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]),PK=new A6([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]),dG=new A6([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),uq=function($,U){var J=new VU(31);for(var Q=0;Q<31;++Q)J[Q]=U+=1<<$[Q-1];var W=new aG(J[30]);for(var Q=1;Q<30;++Q)for(var K=J[Q];K<J[Q+1];++K)W[K]=K-J[Q]<<5|Q;return{b:J,r:W}},lq=uq(BK,2),mq=lq.b,cG=lq.r;mq[28]=258,cG[258]=28;var pq=uq(PK,0),YR=pq.b,gq=pq.r,nG=new VU(32768);for(Q6=0;Q6<32768;++Q6)KJ=(Q6&43690)>>1|(Q6&21845)<<1,KJ=(KJ&52428)>>2|(KJ&13107)<<2,KJ=(KJ&61680)>>4|(KJ&3855)<<4,nG[Q6]=((KJ&65280)>>8|(KJ&255)<<8)>>1;var KJ,Q6,NJ=function($,U,J){var Q=$.length,W=0,K=new VU(U);for(;W<Q;++W)if($[W])++K[$[W]-1];var X=new VU(U);for(W=1;W<U;++W)X[W]=X[W-1]+K[W-1]<<1;var N;if(J){N=new VU(1<<U);var H=15-U;for(W=0;W<Q;++W)if($[W]){var Y=W<<4|$[W],G=U-$[W],O=X[$[W]-1]++<<G;for(var E=O|(1<<G)-1;O<=E;++O)N[nG[O]>>H]=Y}}else{N=new VU(Q);for(W=0;W<Q;++W)if($[W])N[W]=nG[X[$[W]-1]++]>>15-$[W]}return N},aJ=new A6(288);for(Q6=0;Q6<144;++Q6)aJ[Q6]=8;var Q6;for(Q6=144;Q6<256;++Q6)aJ[Q6]=9;var Q6;for(Q6=256;Q6<280;++Q6)aJ[Q6]=7;var Q6;for(Q6=280;Q6<288;++Q6)aJ[Q6]=8;var Q6,$Q=new A6(32);for(Q6=0;Q6<32;++Q6)$Q[Q6]=5;var Q6,GR=NJ(aJ,9,0),OR=NJ(aJ,9,1),ER=NJ($Q,5,0),ZR=NJ($Q,5,1),uG=function($){var U=$[0];for(var J=1;J<$.length;++J)if($[J]>U)U=$[J];return U},uU=function($,U,J){var Q=U/8|0;return($[Q]|$[Q+1]<<8)>>(U&7)&J},lG=function($,U){var J=U/8|0;return($[J]|$[J+1]<<8|$[J+2]<<16)>>(U&7)},sG=function($){return($+7)/8|0},UQ=function($,U,J){if(U==null||U<0)U=0;if(J==null||J>$.length)J=$.length;return new A6($.subarray(U,J))};var IR=["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"],HU=function($,U,J){var Q=Error(U||IR[$]);if(Q.code=$,Error.captureStackTrace)Error.captureStackTrace(Q,HU);if(!J)throw Q;return Q},qR=function($,U,J,Q){var W=$.length,K=Q?Q.length:0;if(!W||U.f&&!U.l)return J||new A6(0);var X=!J,N=X||U.i!=2,H=U.i;if(X)J=new A6(W*3);var Y=function(l$){var d$=J.length;if(l$>d$){var X6=new A6(Math.max(d$*2,l$));X6.set(J),J=X6}},G=U.f||0,O=U.p||0,E=U.b||0,Z=U.l,D=U.d,R=U.m,I=U.n,q=W*8;do{if(!Z){G=uU($,O,1);var _=uU($,O+1,3);if(O+=3,!_){var P=sG(O)+4,L=$[P-4]|$[P-3]<<8,B=P+L;if(B>W){if(H)HU(0);break}if(N)Y(E+L);J.set($.subarray(P,B),E),U.b=E+=L,U.p=O=B*8,U.f=G;continue}else if(_==1)Z=OR,D=ZR,R=9,I=5;else if(_==2){var z=uU($,O,31)+257,A=uU($,O+10,15)+4,k=z+uU($,O+5,31)+1;O+=14;var w=new A6(k),h=new A6(19);for(var C=0;C<A;++C)h[dG[C]]=uU($,O+C*3,7);O+=A*3;var f=uG(h),s=(1<<f)-1,y=NJ(h,f,1);for(var C=0;C<k;){var d=y[uU($,O,s)];O+=d&15;var P=d>>4;if(P<16)w[C++]=P;else{var c=0,x=0;if(P==16)x=3+uU($,O,3),O+=2,c=w[C-1];else if(P==17)x=3+uU($,O,7),O+=3;else if(P==18)x=11+uU($,O,127),O+=7;while(x--)w[C++]=c}}var t=w.subarray(0,z),e=w.subarray(z);R=uG(t),I=uG(e),Z=NJ(t,R,1),D=NJ(e,I,1)}else HU(1);if(O>q){if(H)HU(0);break}}if(N)Y(E+131072);var Y$=(1<<R)-1,R$=(1<<I)-1,w$=O;for(;;w$=O){var c=Z[lG($,O)&Y$],U6=c>>4;if(O+=c&15,O>q){if(H)HU(0);break}if(!c)HU(2);if(U6<256)J[E++]=U6;else if(U6==256){w$=O,Z=null;break}else{var i$=U6-254;if(U6>264){var C=U6-257,i=BK[C];i$=uU($,O,(1<<i)-1)+mq[C],O+=i}var X$=D[lG($,O)&R$],k$=X$>>4;if(!X$)HU(3);O+=X$&15;var e=YR[k$];if(k$>3){var i=PK[k$];e+=lG($,O)&(1<<i)-1,O+=i}if(O>q){if(H)HU(0);break}if(N)Y(E+131072);var F$=E+i$;if(E<e){var v$=K-e,e$=Math.min(e,F$);if(v$+E<0)HU(3);for(;E<e$;++E)J[E]=Q[v$+E]}for(;E<F$;++E)J[E]=J[E-e]}}if(U.l=Z,U.p=w$,U.b=E,U.f=G,Z)G=1,U.m=R,U.d=D,U.n=I}while(!G);return E!=J.length&&X?UQ(J,0,E):J.subarray(0,E)},BJ=function($,U,J){J<<=U&7;var Q=U/8|0;$[Q]|=J,$[Q+1]|=J>>8},t8=function($,U,J){J<<=U&7;var Q=U/8|0;$[Q]|=J,$[Q+1]|=J>>8,$[Q+2]|=J>>16},mG=function($,U){var J=[];for(var Q=0;Q<$.length;++Q)if($[Q])J.push({s:Q,f:$[Q]});var W=J.length,K=J.slice();if(!W)return{t:cq,l:0};if(W==1){var X=new A6(J[0].s+1);return X[J[0].s]=1,{t:X,l:1}}J.sort(function(B,z){return B.f-z.f}),J.push({s:-1,f:25001});var N=J[0],H=J[1],Y=0,G=1,O=2;J[0]={s:-1,f:N.f+H.f,l:N,r:H};while(G!=W-1)N=J[J[Y].f<J[O].f?Y++:O++],H=J[Y!=G&&J[Y].f<J[O].f?Y++:O++],J[G++]={s:-1,f:N.f+H.f,l:N,r:H};var E=K[0].s;for(var Q=1;Q<W;++Q)if(K[Q].s>E)E=K[Q].s;var Z=new VU(E+1),D=iG(J[G-1],Z,0);if(D>U){var Q=0,R=0,I=D-U,q=1<<I;K.sort(function(z,A){return Z[A.s]-Z[z.s]||z.f-A.f});for(;Q<W;++Q){var _=K[Q].s;if(Z[_]>U)R+=q-(1<<D-Z[_]),Z[_]=U;else break}R>>=I;while(R>0){var P=K[Q].s;if(Z[P]<U)R-=1<<U-Z[P]++-1;else++Q}for(;Q>=0&&R;--Q){var L=K[Q].s;if(Z[L]==U)--Z[L],++R}D=U}return{t:new A6(Z),l:D}},iG=function($,U,J){return $.s==-1?Math.max(iG($.l,U,J+1),iG($.r,U,J+1)):U[$.s]=J},bq=function($){var U=$.length;while(U&&!$[--U]);var J=new VU(++U),Q=0,W=$[0],K=1,X=function(H){J[Q++]=H};for(var N=1;N<=U;++N)if($[N]==W&&N!=U)++K;else{if(!W&&K>2){for(;K>138;K-=138)X(32754);if(K>2)X(K>10?K-11<<5|28690:K-3<<5|12305),K=0}else if(K>3){X(W),--K;for(;K>6;K-=6)X(8304);if(K>2)X(K-3<<5|8208),K=0}while(K--)X(W);K=1,W=$[N]}return{c:J.subarray(0,Q),n:U}},e8=function($,U){var J=0;for(var Q=0;Q<U.length;++Q)J+=$[Q]*U[Q];return J},dq=function($,U,J){var Q=J.length,W=sG(U+2);$[W]=Q&255,$[W+1]=Q>>8,$[W+2]=$[W]^255,$[W+3]=$[W+1]^255;for(var K=0;K<Q;++K)$[W+K+4]=J[K];return(W+4+Q)*8},xq=function($,U,J,Q,W,K,X,N,H,Y,G){BJ(U,G++,J),++W[256];var O=mG(W,15),E=O.t,Z=O.l,D=mG(K,15),R=D.t,I=D.l,q=bq(E),_=q.c,P=q.n,L=bq(R),B=L.c,z=L.n,A=new VU(19);for(var k=0;k<_.length;++k)++A[_[k]&31];for(var k=0;k<B.length;++k)++A[B[k]&31];var w=mG(A,7),h=w.t,C=w.l,f=19;for(;f>4&&!h[dG[f-1]];--f);var s=Y+5<<3,y=e8(W,aJ)+e8(K,$Q)+X,d=e8(W,E)+e8(K,R)+X+14+3*f+e8(A,h)+2*A[16]+3*A[17]+7*A[18];if(H>=0&&s<=y&&s<=d)return dq(U,G,$.subarray(H,H+Y));var c,x,t,e;if(BJ(U,G,1+(d<y)),G+=2,d<y){c=NJ(E,Z,0),x=E,t=NJ(R,I,0),e=R;var Y$=NJ(h,C,0);BJ(U,G,P-257),BJ(U,G+5,z-1),BJ(U,G+10,f-4),G+=14;for(var k=0;k<f;++k)BJ(U,G+3*k,h[dG[k]]);G+=3*f;var R$=[_,B];for(var w$=0;w$<2;++w$){var U6=R$[w$];for(var k=0;k<U6.length;++k){var i$=U6[k]&31;if(BJ(U,G,Y$[i$]),G+=h[i$],i$>15)BJ(U,G,U6[k]>>5&127),G+=U6[k]>>12}}}else c=GR,x=aJ,t=ER,e=$Q;for(var k=0;k<N;++k){var i=Q[k];if(i>255){var i$=i>>18&31;if(t8(U,G,c[i$+257]),G+=x[i$+257],i$>7)BJ(U,G,i>>23&31),G+=BK[i$];var X$=i&31;if(t8(U,G,t[X$]),G+=e[X$],X$>3)t8(U,G,i>>5&8191),G+=PK[X$]}else t8(U,G,c[i]),G+=x[i]}return t8(U,G,c[256]),G+x[256]},DR=new aG([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),cq=new A6(0),kR=function($,U,J,Q,W,K){var X=K.z||$.length,N=new A6(Q+X+5*(1+Math.ceil(X/7000))+W),H=N.subarray(Q,N.length-W),Y=K.l,G=(K.r||0)&7;if(U){if(G)H[0]=K.r>>3;var O=DR[U-1],E=O>>13,Z=O&8191,D=(1<<J)-1,R=K.p||new VU(32768),I=K.h||new VU(D+1),q=Math.ceil(J/3),_=2*q,P=function(J6){return($[J6]^$[J6+1]<<q^$[J6+2]<<_)&D},L=new aG(25000),B=new VU(288),z=new VU(32),A=0,k=0,w=K.i||0,h=0,C=K.w||0,f=0;for(;w+2<X;++w){var s=P(w),y=w&32767,d=I[s];if(R[y]=d,I[s]=y,C<=w){var c=X-w;if((A>7000||h>24576)&&(c>423||!Y)){G=xq($,H,0,L,B,z,k,h,f,w-f,G),h=A=k=0,f=w;for(var x=0;x<286;++x)B[x]=0;for(var x=0;x<30;++x)z[x]=0}var t=2,e=0,Y$=Z,R$=y-d&32767;if(c>2&&s==P(w-R$)){var w$=Math.min(E,c)-1,U6=Math.min(32767,w),i$=Math.min(258,c);while(R$<=U6&&--Y$&&y!=d){if($[w+t]==$[w+t-R$]){var i=0;for(;i<i$&&$[w+i]==$[w+i-R$];++i);if(i>t){if(t=i,e=R$,i>w$)break;var X$=Math.min(R$,i-2),k$=0;for(var x=0;x<X$;++x){var F$=w-R$+x&32767,v$=R[F$],e$=F$-v$&32767;if(e$>k$)k$=e$,d=F$}}}y=d,d=R[y],R$+=y-d&32767}}if(e){L[h++]=268435456|cG[t]<<18|gq[e];var l$=cG[t]&31,d$=gq[e]&31;k+=BK[l$]+PK[d$],++B[257+l$],++z[d$],C=w+t,++A}else L[h++]=$[w],++B[$[w]]}}for(w=Math.max(w,C);w<X;++w)L[h++]=$[w],++B[$[w]];if(G=xq($,H,Y,L,B,z,k,h,f,w-f,G),!Y)K.r=G&7|H[G/8|0]<<3,G-=7,K.h=I,K.p=R,K.i=w,K.w=C}else{for(var w=K.w||0;w<X+Y;w+=65535){var X6=w+65535;if(X6>=X)H[G/8|0]=Y,X6=X;G=dq(H,G+1,$.subarray(w,X6))}K.i=X}return UQ(N,0,Q+sG(G)+W)},FR=function(){var $=new Int32Array(256);for(var U=0;U<256;++U){var J=U,Q=9;while(--Q)J=(J&1&&-306674912)^J>>>1;$[U]=J}return $}(),LR=function(){var $=-1;return{p:function(U){var J=$;for(var Q=0;Q<U.length;++Q)J=FR[J&255^U[Q]]^J>>>8;$=J},d:function(){return~$}}};var RR=function($,U,J,Q,W){if(!W){if(W={l:1},U.dictionary){var K=U.dictionary.subarray(-32768),X=new A6(K.length+$.length);X.set(K),X.set($,K.length),$=X,W.w=K.length}}return kR($,U.level==null?6:U.level,U.mem==null?W.l?Math.ceil(Math.max(8,Math.min(13,Math.log($.length)))*1.5):20:12+U.mem,J,Q,W)},nq=function($,U){var J={};for(var Q in $)J[Q]=$[Q];for(var Q in U)J[Q]=U[Q];return J};var XJ=function($,U){return $[U]|$[U+1]<<8},lU=function($,U){return($[U]|$[U+1]<<8|$[U+2]<<16|$[U+3]<<24)>>>0},pG=function($,U){return lU($,U)+lU($,U+4)*4294967296},s6=function($,U,J){for(;J;++U)$[U]=J,J>>>=8};function VR($,U){return RR($,U||{},0,0)}function wR($,U){return qR($,{i:2},U&&U.out,U&&U.dictionary)}var iq=function($,U,J,Q){for(var W in $){var K=$[W],X=U+W,N=Q;if(Array.isArray(K))N=nq(Q,K[1]),K=K[0];if(K instanceof A6)J[X]=[K,N];else J[X+="/"]=[new A6(0),N],iq(K,X,J,Q)}},yq=typeof TextEncoder<"u"&&new TextEncoder,oG=typeof TextDecoder<"u"&&new TextDecoder,MR=0;try{oG.decode(cq,{stream:!0}),MR=1}catch($){}var BR=function($){for(var U="",J=0;;){var Q=$[J++],W=(Q>127)+(Q>223)+(Q>239);if(J+W>$.length)return{s:U,r:UQ($,J-1)};if(!W)U+=String.fromCharCode(Q);else if(W==3)Q=((Q&15)<<18|($[J++]&63)<<12|($[J++]&63)<<6|$[J++]&63)-65536,U+=String.fromCharCode(55296|Q>>10,56320|Q&1023);else if(W&1)U+=String.fromCharCode((Q&31)<<6|$[J++]&63);else U+=String.fromCharCode((Q&15)<<12|($[J++]&63)<<6|$[J++]&63)}};function hq($,U){if(U){var J=new A6($.length);for(var Q=0;Q<$.length;++Q)J[Q]=$.charCodeAt(Q);return J}if(yq)return yq.encode($);var W=$.length,K=new A6($.length+($.length>>1)),X=0,N=function(G){K[X++]=G};for(var Q=0;Q<W;++Q){if(X+5>K.length){var H=new A6(X+8+(W-Q<<1));H.set(K),K=H}var Y=$.charCodeAt(Q);if(Y<128||U)N(Y);else if(Y<2048)N(192|Y>>6),N(128|Y&63);else if(Y>55295&&Y<57344)Y=65536+(Y&1047552)|$.charCodeAt(++Q)&1023,N(240|Y>>18),N(128|Y>>12&63),N(128|Y>>6&63),N(128|Y&63);else N(224|Y>>12),N(128|Y>>6&63),N(128|Y&63)}return UQ(K,0,X)}function PR($,U){if(U){var J="";for(var Q=0;Q<$.length;Q+=16384)J+=String.fromCharCode.apply(null,$.subarray(Q,Q+16384));return J}else if(oG)return oG.decode($);else{var W=BR($),K=W.s,J=W.r;if(J.length)HU(8);return K}}var zR=function($,U){return U+30+XJ($,U+26)+XJ($,U+28)},_R=function($,U,J){var Q=XJ($,U+28),W=PR($.subarray(U+46,U+46+Q),!(XJ($,U+8)&2048)),K=U+46+Q,X=lU($,U+20),N=J&&X==4294967295?AR($,K):[X,lU($,U+24),lU($,U+42)],H=N[0],Y=N[1],G=N[2];return[XJ($,U+10),H,Y,W,K+XJ($,U+30)+XJ($,U+32),G]},AR=function($,U){for(;XJ($,U)!=1;U+=4+XJ($,U+2));return[pG($,U+12),pG($,U+4),pG($,U+20)]},rG=function($){var U=0;if($)for(var J in $){var Q=$[J].length;if(Q>65535)HU(9);U+=Q+4}return U},fq=function($,U,J,Q,W,K,X,N){var H=Q.length,Y=J.extra,G=N&&N.length,O=rG(Y);if(s6($,U,X!=null?33639248:67324752),U+=4,X!=null)$[U++]=20,$[U++]=J.os;$[U]=20,U+=2,$[U++]=J.flag<<1|(K<0&&8),$[U++]=W&&8,$[U++]=J.compression&255,$[U++]=J.compression>>8;var E=new Date(J.mtime==null?Date.now():J.mtime),Z=E.getFullYear()-1980;if(Z<0||Z>119)HU(10);if(s6($,U,Z<<25|E.getMonth()+1<<21|E.getDate()<<16|E.getHours()<<11|E.getMinutes()<<5|E.getSeconds()>>1),U+=4,K!=-1)s6($,U,J.crc),s6($,U+4,K<0?-K-2:K),s6($,U+8,J.size);if(s6($,U+12,H),s6($,U+14,O),U+=16,X!=null)s6($,U,G),s6($,U+6,J.attrs),s6($,U+10,X),U+=14;if($.set(Q,U),U+=H,O)for(var D in Y){var R=Y[D],I=R.length;s6($,U,+D),s6($,U+2,I),$.set(R,U+4),U+=4+I}if(G)$.set(N,U),U+=G;return U},CR=function($,U,J,Q,W){s6($,U,101010256),s6($,U+8,J),s6($,U+10,J),s6($,U+12,Q),s6($,U+16,W)};function oq($,U){if(!U)U={};var J={},Q=[];iq($,"",J,U);var W=0,K=0;for(var X in J){var N=J[X],H=N[0],Y=N[1],G=Y.level==0?0:8,O=hq(X),E=O.length,Z=Y.comment,D=Z&&hq(Z),R=D&&D.length,I=rG(Y.extra);if(E>65535)HU(11);var q=G?VR(H,Y):H,_=q.length,P=LR();P.p(H),Q.push(nq(Y,{size:H.length,crc:P.d(),c:q,f:O,m:D,u:E!=X.length||D&&Z.length!=R,o:W,compression:G})),W+=30+E+I+_,K+=76+2*(E+I)+(R||0)+_}var L=new A6(K+22),B=W,z=K-W;for(var A=0;A<Q.length;++A){var O=Q[A];fq(L,O.o,O,O.f,O.u,O.c.length);var k=30+O.f.length+rG(O.extra);L.set(O.c,O.o+k),fq(L,W,O,O.f,O.u,O.c.length,O.o,O.m),W+=16+k+(O.m?O.m.length:0)}return CR(L,W,Q.length,z,B),L}function rq($,U){var J={},Q=$.length-22;for(;lU($,Q)!=101010256;--Q)if(!Q||$.length-Q>65558)HU(13);var W=XJ($,Q+8);if(!W)return{};var K=lU($,Q+16),X=K==4294967295||W==65535;if(X){var N=lU($,Q-12);if(X=lU($,N)==101075792,X)W=lU($,N+32),K=lU($,N+48)}var H=U&&U.filter;for(var Y=0;Y<W;++Y){var G=_R($,K,X),O=G[0],E=G[1],Z=G[2],D=G[3],R=G[4],I=G[5],q=zR($,I);if(K=R,!H||H({name:D,size:E,originalSize:Z,compression:O}))if(!O)J[D]=UQ($,q,q+E);else if(O==8)J[D]=wR($.subarray(q,q+E),{out:new A6(Z)});else HU(14,"unknown compression type "+O)}return J}var PJ=67108864,tG=W6.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),SR=W6.string().regex(/^sha256:[a-f0-9]{64}$/),aq=W6.object({version:W6.literal("kiln.asset.v1"),assetId:tG,revisionId:tG,parentRevision:tG.optional(),name:W6.string().min(1).max(200),tags:W6.array(W6.string().max(80)).max(30),createdAt:W6.string().datetime(),description:W6.string().max(4000).optional(),brief:W6.string().max(8000).optional(),attribution:W6.object({model:W6.string().max(200).optional(),harness:W6.string().max(200).optional(),author:W6.string().max(200).optional()}).optional(),editable:W6.boolean(),files:W6.record(W6.string(),W6.object({sha256:SR,bytes:W6.number().int().nonnegative().max(PJ)})),build:W6.object({engine:W6.string(),options:W6.record(W6.string(),W6.unknown()),warnings:W6.array(W6.string()),integration:W6.unknown().optional(),qa:W6.unknown().optional(),dependencies:W6.array(W6.unknown()).optional(),rebuild:W6.enum(["engine-required","external-dependencies-required"])}).optional(),preview:W6.object({fidelity:W6.unknown().optional(),error:W6.string().optional()}).optional()}),TR=new Set(["asset.glb","source.kiln.js","preview.png"]);function sq($){let U=aq.parse($.manifest),J=Object.keys($.files);if(J.length!==Object.keys(U.files).length||!J.includes("asset.glb"))throw Error("Asset file inventory mismatch");let Q=0;for(let W of J){if(!TR.has(W)||!U.files[W]||U.files[W].bytes!==$.files[W].length)throw Error("Invalid asset file inventory");Q+=$.files[W].length}if(Q>PJ||U.editable!==J.includes("source.kiln.js"))throw Error("Invalid asset size or source inventory");if(($.files["source.kiln.js"]?.length??0)>1048576)throw Error("Source exceeds 1 MiB");eG($.files["asset.glb"])}function eG($){if($.length<20||$.length>PJ)throw Error("Invalid GLB size");let U=new DataView($.buffer,$.byteOffset,$.byteLength);if(U.getUint32(0,!0)!==1179937895||U.getUint32(4,!0)!==2||U.getUint32(8,!0)!==$.length||U.getUint32(16,!0)!==1313821514)throw Error("Invalid GLB header");let J=20+U.getUint32(12,!0);if(J>$.length)throw Error("Invalid GLB JSON length");let Q=JSON.parse(new TextDecoder().decode($.subarray(20,J)));for(let W of[...Q.buffers??[],...Q.images??[]])if(W.uri&&!String(W.uri).startsWith("data:"))throw Error("GLB must embed its resources")}function $O($){if(!$.length||$.length>100)throw Error("Bundle requires 1..100 revisions");let U={},J=0;for(let Q of $){sq(Q);let W=`${Q.manifest.assetId}/${Q.manifest.revisionId}/`;if(U[`${W}manifest.json`])throw Error("Duplicate bundle revision");U[`${W}manifest.json`]=new TextEncoder().encode(JSON.stringify(Q.manifest,null,2));for(let[K,X]of Object.entries(Q.files))U[W+K]=X}for(let Q of Object.values(U))J+=Q.length;if(J>PJ)throw Error("Bundle exceeds 64 MiB");return oq(U,{level:0})}function tq($){if($.length>PJ+1048576)throw Error("Bundle exceeds 64 MiB");let U=0,J=0,Q=rq($,{filter:(X)=>{if(U+=X.originalSize,J++,U>PJ||J>400||!/^[a-z][a-z0-9_-]{0,79}\/[a-z][a-z0-9_-]{0,79}\/(manifest\.json|asset\.glb|source\.kiln\.js|preview\.png)$/.test(X.name))throw Error("Unsafe or oversized asset bundle");return!0}}),W=[],K=new Set;for(let[X,N]of Object.entries(Q)){if(!X.endsWith("/manifest.json"))continue;if(N.length>1048576)throw Error("Manifest exceeds 1 MiB");let H=aq.parse(JSON.parse(new TextDecoder().decode(N))),Y=`${H.assetId}/${H.revisionId}/`;if(X!==`${Y}manifest.json`)throw Error("Bundle identity mismatch");let G={manifest:H,files:{}};K.add(X);for(let O of Object.keys(H.files)){if(!Q[Y+O])throw Error("Bundle file missing");G.files[O]=Q[Y+O],K.add(Y+O)}sq(G),W.push(G)}if(!W.length||K.size!==Object.keys(Q).length)throw Error("Incomplete asset bundle");return W}var bD="185",W0={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Q0={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},xD=0,AO=1,yD=2;var ZQ=1,hD=2,rW=3,K0=0,JU=1,bU=2,EJ=0,IQ=1,CO=2,SO=3,TO=4,fD=5;var aW=100,uD=101,lD=102,mD=103,pD=104,dD=200,cD=201,nD=202,iD=203,oD=204,rD=205,aD=206,sD=207,tD=208,eD=209,$k=210,Uk=211,Jk=212,Wk=213,Qk=214,Kk=0,Xk=1,Nk=2,vO=3,Hk=4,Yk=5,Gk=6,Ok=7,Ek=0,Zk=1,Ik=2,oU=0,jO=1,gO=2,bO=3,qQ=4,xO=5,yO=6,hO=7;var sW=301,h0=302,$7=303,U7=304,DQ=306,tW=1000,eW=1001,J7=1002,rU=1003,W7=1004;var f0=1005;var o6=1006,$8=1007;var ZJ=1008;var aU=1009,qk=1010,Dk=1011,kQ=1012,fO=1013,X0=1014,jJ=1015,gJ=1016,uO=1017,lO=1018,U8=1020,kk=35902,Fk=35899,Lk=1021,Rk=1022,IJ=1023,u0=1026,l0=1027,Vk=1028,mO=1029,m0=1030,pO=1031;var dO=1033,Q7=33776,K7=33777,X7=33778,N7=33779,cO=35840,nO=35841,iO=35842,oO=35843,rO=36196,aO=37492,sO=37496,tO=37488,eO=37489,H7=37490,$E=37491,UE=37808,JE=37809,WE=37810,QE=37811,KE=37812,XE=37813,NE=37814,HE=37815,YE=37816,GE=37817,OE=37818,EE=37819,ZE=37820,IE=37821,qE=36492,DE=36494,kE=36495,FE=36283,LE=36284,Y7=36285,RE=36286;var VE=2300,G7=2301;var wE=0,FQ=1,J8=2;var ME=0,wk=1,p0="",N0="srgb",BU="srgb-linear",BE="linear",w6="srgb";var Mk=512,Bk=513,Pk=514,O7=515,zk=516,_k=517,E7=518,Ak=519;var PE="300 es",zE=2000;function vR($){for(let U=$.length-1;U>=0;--U)if($[U]>=65535)return!0;return!1}function jR($){return ArrayBuffer.isView($)&&!($ instanceof DataView)}function nW($){return document.createElementNS("http://www.w3.org/1999/xhtml",$)}function Ck(){let $=nW("canvas");return $.style.display="block",$}var eq={},iW=null;function EQ(...$){let U="THREE."+$.shift();if(iW)iW("log",U,...$);else console.log(U,...$)}function Sk($){let U=$[0];if(typeof U==="string"&&U.startsWith("TSL:")){let J=$[1];if(J&&J.isStackTrace)$[0]+=" "+J.getLocation();else $[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return $}function A$(...$){$=Sk($);let U="THREE."+$.shift();if(iW)iW("warn",U,...$);else{let J=$[0];if(J&&J.isStackTrace)console.warn(J.getError(U));else console.warn(U,...$)}}function y$(...$){$=Sk($);let U="THREE."+$.shift();if(iW)iW("error",U,...$);else{let J=$[0];if(J&&J.isStackTrace)console.error(J.getError(U));else console.error(U,...$)}}function b0(...$){let U=$.join(" ");if(U in eq)return;eq[U]=!0,A$(...$)}function Tk($,U,J){return new Promise(function(Q,W){function K(){switch($.clientWaitSync(U,$.SYNC_FLUSH_COMMANDS_BIT,0)){case $.WAIT_FAILED:W();break;case $.TIMEOUT_EXPIRED:setTimeout(K,J);break;default:Q()}}setTimeout(K,J)})}var vk={[0]:1,[2]:6,[4]:7,[3]:5,[1]:0,[6]:2,[7]:4,[5]:3};class sU{addEventListener($,U){if(this._listeners===void 0)this._listeners={};let J=this._listeners;if(J[$]===void 0)J[$]=[];if(J[$].indexOf(U)===-1)J[$].push(U)}hasEventListener($,U){let J=this._listeners;if(J===void 0)return!1;return J[$]!==void 0&&J[$].indexOf(U)!==-1}removeEventListener($,U){let J=this._listeners;if(J===void 0)return;let Q=J[$];if(Q!==void 0){let W=Q.indexOf(U);if(W!==-1)Q.splice(W,1)}}dispatchEvent($){let U=this._listeners;if(U===void 0)return;let J=U[$.type];if(J!==void 0){$.target=this;let Q=J.slice(0);for(let W=0,K=Q.length;W<K;W++)Q[W].call(this,$);$.target=null}}}var $U=["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"],$D=1234567,GQ=Math.PI/180,x0=180/Math.PI;function iU(){let $=Math.random()*4294967295|0,U=Math.random()*4294967295|0,J=Math.random()*4294967295|0,Q=Math.random()*4294967295|0;return($U[$&255]+$U[$>>8&255]+$U[$>>16&255]+$U[$>>24&255]+"-"+$U[U&255]+$U[U>>8&255]+"-"+$U[U>>16&15|64]+$U[U>>24&255]+"-"+$U[J&63|128]+$U[J>>8&255]+"-"+$U[J>>16&255]+$U[J>>24&255]+$U[Q&255]+$U[Q>>8&255]+$U[Q>>16&255]+$U[Q>>24&255]).toLowerCase()}function t$($,U,J){return Math.max(U,Math.min(J,$))}function _E($,U){return($%U+U)%U}function gR($,U,J,Q,W){return Q+($-U)*(W-Q)/(J-U)}function bR($,U,J){if($!==U)return(J-$)/(U-$);else return 0}function OQ($,U,J){return(1-J)*$+J*U}function xR($,U,J,Q){return OQ($,U,1-Math.exp(-J*Q))}function yR($,U=1){return U-Math.abs(_E($,U*2)-U)}function hR($,U,J){if($<=U)return 0;if($>=J)return 1;return $=($-U)/(J-U),$*$*(3-2*$)}function fR($,U,J){if($<=U)return 0;if($>=J)return 1;return $=($-U)/(J-U),$*$*$*($*($*6-15)+10)}function uR($,U){return $+Math.floor(Math.random()*(U-$+1))}function lR($,U){return $+Math.random()*(U-$)}function mR($){return $*(0.5-Math.random())}function pR($){if($!==void 0)$D=$;let U=$D+=1831565813;return U=Math.imul(U^U>>>15,U|1),U^=U+Math.imul(U^U>>>7,U|61),((U^U>>>14)>>>0)/4294967296}function dR($){return $*GQ}function cR($){return $*x0}function nR($){return($&$-1)===0&&$!==0}function iR($){return Math.pow(2,Math.ceil(Math.log($)/Math.LN2))}function oR($){return Math.pow(2,Math.floor(Math.log($)/Math.LN2))}function rR($,U,J,Q,W){let{cos:K,sin:X}=Math,N=K(J/2),H=X(J/2),Y=K((U+Q)/2),G=X((U+Q)/2),O=K((U-Q)/2),E=X((U-Q)/2),Z=K((Q-U)/2),D=X((Q-U)/2);switch(W){case"XYX":$.set(N*G,H*O,H*E,N*Y);break;case"YZY":$.set(H*E,N*G,H*O,N*Y);break;case"ZXZ":$.set(H*O,H*E,N*G,N*Y);break;case"XZX":$.set(N*G,H*D,H*Z,N*Y);break;case"YXY":$.set(H*Z,N*G,H*D,N*Y);break;case"ZYZ":$.set(H*D,H*Z,N*G,N*Y);break;default:A$("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+W)}}function nU($,U){switch(U.constructor){case Float32Array:return $;case Uint32Array:return $/4294967295;case Uint16Array:return $/65535;case Uint8Array:return $/255;case Int32Array:return Math.max($/2147483647,-1);case Int16Array:return Math.max($/32767,-1);case Int8Array:return Math.max($/127,-1);default:throw Error("THREE.MathUtils: Invalid component type.")}}function E6($,U){switch(U.constructor){case Float32Array:return $;case Uint32Array:return Math.round($*4294967295);case Uint16Array:return Math.round($*65535);case Uint8Array:return Math.round($*255);case Int32Array:return Math.round($*2147483647);case Int16Array:return Math.round($*32767);case Int8Array:return Math.round($*127);default:throw Error("THREE.MathUtils: Invalid component type.")}}var LQ={DEG2RAD:GQ,RAD2DEG:x0,generateUUID:iU,clamp:t$,euclideanModulo:_E,mapLinear:gR,inverseLerp:bR,lerp:OQ,damp:xR,pingpong:yR,smoothstep:hR,smootherstep:fR,randInt:uR,randFloat:lR,randFloatSpread:mR,seededRandom:pR,degToRad:dR,radToDeg:cR,isPowerOfTwo:nR,ceilPowerOfTwo:iR,floorPowerOfTwo:oR,setQuaternionFromProperEuler:rR,normalize:E6,denormalize:nU};class g${static{g$.prototype.isVector2=!0}constructor($=0,U=0){this.x=$,this.y=U}get width(){return this.x}set width($){this.x=$}get height(){return this.y}set height($){this.y=$}set($,U){return this.x=$,this.y=U,this}setScalar($){return this.x=$,this.y=$,this}setX($){return this.x=$,this}setY($){return this.y=$,this}setComponent($,U){switch($){case 0:this.x=U;break;case 1:this.y=U;break;default:throw Error("THREE.Vector2: index is out of range: "+$)}return this}getComponent($){switch($){case 0:return this.x;case 1:return this.y;default:throw Error("THREE.Vector2: index is out of range: "+$)}}clone(){return new this.constructor(this.x,this.y)}copy($){return this.x=$.x,this.y=$.y,this}add($){return this.x+=$.x,this.y+=$.y,this}addScalar($){return this.x+=$,this.y+=$,this}addVectors($,U){return this.x=$.x+U.x,this.y=$.y+U.y,this}addScaledVector($,U){return this.x+=$.x*U,this.y+=$.y*U,this}sub($){return this.x-=$.x,this.y-=$.y,this}subScalar($){return this.x-=$,this.y-=$,this}subVectors($,U){return this.x=$.x-U.x,this.y=$.y-U.y,this}multiply($){return this.x*=$.x,this.y*=$.y,this}multiplyScalar($){return this.x*=$,this.y*=$,this}divide($){return this.x/=$.x,this.y/=$.y,this}divideScalar($){return this.multiplyScalar(1/$)}applyMatrix3($){let U=this.x,J=this.y,Q=$.elements;return this.x=Q[0]*U+Q[3]*J+Q[6],this.y=Q[1]*U+Q[4]*J+Q[7],this}min($){return this.x=Math.min(this.x,$.x),this.y=Math.min(this.y,$.y),this}max($){return this.x=Math.max(this.x,$.x),this.y=Math.max(this.y,$.y),this}clamp($,U){return this.x=t$(this.x,$.x,U.x),this.y=t$(this.y,$.y,U.y),this}clampScalar($,U){return this.x=t$(this.x,$,U),this.y=t$(this.y,$,U),this}clampLength($,U){let J=this.length();return this.divideScalar(J||1).multiplyScalar(t$(J,$,U))}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($){return this.x*$.x+this.y*$.y}cross($){return this.x*$.y-this.y*$.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($){let U=Math.sqrt(this.lengthSq()*$.lengthSq());if(U===0)return Math.PI/2;let J=this.dot($)/U;return Math.acos(t$(J,-1,1))}distanceTo($){return Math.sqrt(this.distanceToSquared($))}distanceToSquared($){let U=this.x-$.x,J=this.y-$.y;return U*U+J*J}manhattanDistanceTo($){return Math.abs(this.x-$.x)+Math.abs(this.y-$.y)}setLength($){return this.normalize().multiplyScalar($)}lerp($,U){return this.x+=($.x-this.x)*U,this.y+=($.y-this.y)*U,this}lerpVectors($,U,J){return this.x=$.x+(U.x-$.x)*J,this.y=$.y+(U.y-$.y)*J,this}equals($){return $.x===this.x&&$.y===this.y}fromArray($,U=0){return this.x=$[U],this.y=$[U+1],this}toArray($=[],U=0){return $[U]=this.x,$[U+1]=this.y,$}fromBufferAttribute($,U){return this.x=$.getX(U),this.y=$.getY(U),this}rotateAround($,U){let J=Math.cos(U),Q=Math.sin(U),W=this.x-$.x,K=this.y-$.y;return this.x=W*J-K*Q+$.x,this.y=W*Q+K*J+$.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class i6{constructor($=0,U=0,J=0,Q=1){this.isQuaternion=!0,this._x=$,this._y=U,this._z=J,this._w=Q}static slerpFlat($,U,J,Q,W,K,X){let N=J[Q+0],H=J[Q+1],Y=J[Q+2],G=J[Q+3],O=W[K+0],E=W[K+1],Z=W[K+2],D=W[K+3];if(G!==D||N!==O||H!==E||Y!==Z){let R=N*O+H*E+Y*Z+G*D;if(R<0)O=-O,E=-E,Z=-Z,D=-D,R=-R;let I=1-X;if(R<0.9995){let q=Math.acos(R),_=Math.sin(q);I=Math.sin(I*q)/_,X=Math.sin(X*q)/_,N=N*I+O*X,H=H*I+E*X,Y=Y*I+Z*X,G=G*I+D*X}else{N=N*I+O*X,H=H*I+E*X,Y=Y*I+Z*X,G=G*I+D*X;let q=1/Math.sqrt(N*N+H*H+Y*Y+G*G);N*=q,H*=q,Y*=q,G*=q}}$[U]=N,$[U+1]=H,$[U+2]=Y,$[U+3]=G}static multiplyQuaternionsFlat($,U,J,Q,W,K){let X=J[Q],N=J[Q+1],H=J[Q+2],Y=J[Q+3],G=W[K],O=W[K+1],E=W[K+2],Z=W[K+3];return $[U]=X*Z+Y*G+N*E-H*O,$[U+1]=N*Z+Y*O+H*G-X*E,$[U+2]=H*Z+Y*E+X*O-N*G,$[U+3]=Y*Z-X*G-N*O-H*E,$}get x(){return this._x}set x($){this._x=$,this._onChangeCallback()}get y(){return this._y}set y($){this._y=$,this._onChangeCallback()}get z(){return this._z}set z($){this._z=$,this._onChangeCallback()}get w(){return this._w}set w($){this._w=$,this._onChangeCallback()}set($,U,J,Q){return this._x=$,this._y=U,this._z=J,this._w=Q,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy($){return this._x=$.x,this._y=$.y,this._z=$.z,this._w=$.w,this._onChangeCallback(),this}setFromEuler($,U=!0){let{_x:J,_y:Q,_z:W,_order:K}=$,X=Math.cos,N=Math.sin,H=X(J/2),Y=X(Q/2),G=X(W/2),O=N(J/2),E=N(Q/2),Z=N(W/2);switch(K){case"XYZ":this._x=O*Y*G+H*E*Z,this._y=H*E*G-O*Y*Z,this._z=H*Y*Z+O*E*G,this._w=H*Y*G-O*E*Z;break;case"YXZ":this._x=O*Y*G+H*E*Z,this._y=H*E*G-O*Y*Z,this._z=H*Y*Z-O*E*G,this._w=H*Y*G+O*E*Z;break;case"ZXY":this._x=O*Y*G-H*E*Z,this._y=H*E*G+O*Y*Z,this._z=H*Y*Z+O*E*G,this._w=H*Y*G-O*E*Z;break;case"ZYX":this._x=O*Y*G-H*E*Z,this._y=H*E*G+O*Y*Z,this._z=H*Y*Z-O*E*G,this._w=H*Y*G+O*E*Z;break;case"YZX":this._x=O*Y*G+H*E*Z,this._y=H*E*G+O*Y*Z,this._z=H*Y*Z-O*E*G,this._w=H*Y*G-O*E*Z;break;case"XZY":this._x=O*Y*G-H*E*Z,this._y=H*E*G-O*Y*Z,this._z=H*Y*Z+O*E*G,this._w=H*Y*G+O*E*Z;break;default:A$("Quaternion: .setFromEuler() encountered an unknown order: "+K)}if(U===!0)this._onChangeCallback();return this}setFromAxisAngle($,U){let J=U/2,Q=Math.sin(J);return this._x=$.x*Q,this._y=$.y*Q,this._z=$.z*Q,this._w=Math.cos(J),this._onChangeCallback(),this}setFromRotationMatrix($){let U=$.elements,J=U[0],Q=U[4],W=U[8],K=U[1],X=U[5],N=U[9],H=U[2],Y=U[6],G=U[10],O=J+X+G;if(O>0){let E=0.5/Math.sqrt(O+1);this._w=0.25/E,this._x=(Y-N)*E,this._y=(W-H)*E,this._z=(K-Q)*E}else if(J>X&&J>G){let E=2*Math.sqrt(1+J-X-G);this._w=(Y-N)/E,this._x=0.25*E,this._y=(Q+K)/E,this._z=(W+H)/E}else if(X>G){let E=2*Math.sqrt(1+X-J-G);this._w=(W-H)/E,this._x=(Q+K)/E,this._y=0.25*E,this._z=(N+Y)/E}else{let E=2*Math.sqrt(1+G-J-X);this._w=(K-Q)/E,this._x=(W+H)/E,this._y=(N+Y)/E,this._z=0.25*E}return this._onChangeCallback(),this}setFromUnitVectors($,U){let J=$.dot(U)+1;if(J<0.00000001)if(J=0,Math.abs($.x)>Math.abs($.z))this._x=-$.y,this._y=$.x,this._z=0,this._w=J;else this._x=0,this._y=-$.z,this._z=$.y,this._w=J;else this._x=$.y*U.z-$.z*U.y,this._y=$.z*U.x-$.x*U.z,this._z=$.x*U.y-$.y*U.x,this._w=J;return this.normalize()}angleTo($){return 2*Math.acos(Math.abs(t$(this.dot($),-1,1)))}rotateTowards($,U){let J=this.angleTo($);if(J===0)return this;let Q=Math.min(1,U/J);return this.slerp($,Q),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($){return this._x*$._x+this._y*$._y+this._z*$._z+this._w*$._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 $=this.length();if($===0)this._x=0,this._y=0,this._z=0,this._w=1;else $=1/$,this._x=this._x*$,this._y=this._y*$,this._z=this._z*$,this._w=this._w*$;return this._onChangeCallback(),this}multiply($){return this.multiplyQuaternions(this,$)}premultiply($){return this.multiplyQuaternions($,this)}multiplyQuaternions($,U){let{_x:J,_y:Q,_z:W,_w:K}=$,X=U._x,N=U._y,H=U._z,Y=U._w;return this._x=J*Y+K*X+Q*H-W*N,this._y=Q*Y+K*N+W*X-J*H,this._z=W*Y+K*H+J*N-Q*X,this._w=K*Y-J*X-Q*N-W*H,this._onChangeCallback(),this}slerp($,U){let{_x:J,_y:Q,_z:W,_w:K}=$,X=this.dot($);if(X<0)J=-J,Q=-Q,W=-W,K=-K,X=-X;let N=1-U;if(X<0.9995){let H=Math.acos(X),Y=Math.sin(H);N=Math.sin(N*H)/Y,U=Math.sin(U*H)/Y,this._x=this._x*N+J*U,this._y=this._y*N+Q*U,this._z=this._z*N+W*U,this._w=this._w*N+K*U,this._onChangeCallback()}else this._x=this._x*N+J*U,this._y=this._y*N+Q*U,this._z=this._z*N+W*U,this._w=this._w*N+K*U,this.normalize();return this}slerpQuaternions($,U,J){return this.copy($).slerp(U,J)}random(){let $=2*Math.PI*Math.random(),U=2*Math.PI*Math.random(),J=Math.random(),Q=Math.sqrt(1-J),W=Math.sqrt(J);return this.set(Q*Math.sin($),Q*Math.cos($),W*Math.sin(U),W*Math.cos(U))}equals($){return $._x===this._x&&$._y===this._y&&$._z===this._z&&$._w===this._w}fromArray($,U=0){return this._x=$[U],this._y=$[U+1],this._z=$[U+2],this._w=$[U+3],this._onChangeCallback(),this}toArray($=[],U=0){return $[U]=this._x,$[U+1]=this._y,$[U+2]=this._z,$[U+3]=this._w,$}fromBufferAttribute($,U){return this._x=$.getX(U),this._y=$.getY(U),this._z=$.getZ(U),this._w=$.getW(U),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange($){return this._onChangeCallback=$,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class j{static{j.prototype.isVector3=!0}constructor($=0,U=0,J=0){this.x=$,this.y=U,this.z=J}set($,U,J){if(J===void 0)J=this.z;return this.x=$,this.y=U,this.z=J,this}setScalar($){return this.x=$,this.y=$,this.z=$,this}setX($){return this.x=$,this}setY($){return this.y=$,this}setZ($){return this.z=$,this}setComponent($,U){switch($){case 0:this.x=U;break;case 1:this.y=U;break;case 2:this.z=U;break;default:throw Error("THREE.Vector3: index is out of range: "+$)}return this}getComponent($){switch($){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("THREE.Vector3: index is out of range: "+$)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy($){return this.x=$.x,this.y=$.y,this.z=$.z,this}add($){return this.x+=$.x,this.y+=$.y,this.z+=$.z,this}addScalar($){return this.x+=$,this.y+=$,this.z+=$,this}addVectors($,U){return this.x=$.x+U.x,this.y=$.y+U.y,this.z=$.z+U.z,this}addScaledVector($,U){return this.x+=$.x*U,this.y+=$.y*U,this.z+=$.z*U,this}sub($){return this.x-=$.x,this.y-=$.y,this.z-=$.z,this}subScalar($){return this.x-=$,this.y-=$,this.z-=$,this}subVectors($,U){return this.x=$.x-U.x,this.y=$.y-U.y,this.z=$.z-U.z,this}multiply($){return this.x*=$.x,this.y*=$.y,this.z*=$.z,this}multiplyScalar($){return this.x*=$,this.y*=$,this.z*=$,this}multiplyVectors($,U){return this.x=$.x*U.x,this.y=$.y*U.y,this.z=$.z*U.z,this}applyEuler($){return this.applyQuaternion(UD.setFromEuler($))}applyAxisAngle($,U){return this.applyQuaternion(UD.setFromAxisAngle($,U))}applyMatrix3($){let U=this.x,J=this.y,Q=this.z,W=$.elements;return this.x=W[0]*U+W[3]*J+W[6]*Q,this.y=W[1]*U+W[4]*J+W[7]*Q,this.z=W[2]*U+W[5]*J+W[8]*Q,this}applyNormalMatrix($){return this.applyMatrix3($).normalize()}applyMatrix4($){let U=this.x,J=this.y,Q=this.z,W=$.elements,K=1/(W[3]*U+W[7]*J+W[11]*Q+W[15]);return this.x=(W[0]*U+W[4]*J+W[8]*Q+W[12])*K,this.y=(W[1]*U+W[5]*J+W[9]*Q+W[13])*K,this.z=(W[2]*U+W[6]*J+W[10]*Q+W[14])*K,this}applyQuaternion($){let U=this.x,J=this.y,Q=this.z,W=$.x,K=$.y,X=$.z,N=$.w,H=2*(K*Q-X*J),Y=2*(X*U-W*Q),G=2*(W*J-K*U);return this.x=U+N*H+K*G-X*Y,this.y=J+N*Y+X*H-W*G,this.z=Q+N*G+W*Y-K*H,this}project($){return this.applyMatrix4($.matrixWorldInverse).applyMatrix4($.projectionMatrix)}unproject($){return this.applyMatrix4($.projectionMatrixInverse).applyMatrix4($.matrixWorld)}transformDirection($){let U=this.x,J=this.y,Q=this.z,W=$.elements;return this.x=W[0]*U+W[4]*J+W[8]*Q,this.y=W[1]*U+W[5]*J+W[9]*Q,this.z=W[2]*U+W[6]*J+W[10]*Q,this.normalize()}divide($){return this.x/=$.x,this.y/=$.y,this.z/=$.z,this}divideScalar($){return this.multiplyScalar(1/$)}min($){return this.x=Math.min(this.x,$.x),this.y=Math.min(this.y,$.y),this.z=Math.min(this.z,$.z),this}max($){return this.x=Math.max(this.x,$.x),this.y=Math.max(this.y,$.y),this.z=Math.max(this.z,$.z),this}clamp($,U){return this.x=t$(this.x,$.x,U.x),this.y=t$(this.y,$.y,U.y),this.z=t$(this.z,$.z,U.z),this}clampScalar($,U){return this.x=t$(this.x,$,U),this.y=t$(this.y,$,U),this.z=t$(this.z,$,U),this}clampLength($,U){let J=this.length();return this.divideScalar(J||1).multiplyScalar(t$(J,$,U))}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($){return this.x*$.x+this.y*$.y+this.z*$.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($){return this.normalize().multiplyScalar($)}lerp($,U){return this.x+=($.x-this.x)*U,this.y+=($.y-this.y)*U,this.z+=($.z-this.z)*U,this}lerpVectors($,U,J){return this.x=$.x+(U.x-$.x)*J,this.y=$.y+(U.y-$.y)*J,this.z=$.z+(U.z-$.z)*J,this}cross($){return this.crossVectors(this,$)}crossVectors($,U){let{x:J,y:Q,z:W}=$,K=U.x,X=U.y,N=U.z;return this.x=Q*N-W*X,this.y=W*K-J*N,this.z=J*X-Q*K,this}projectOnVector($){let U=$.lengthSq();if(U===0)return this.set(0,0,0);let J=$.dot(this)/U;return this.copy($).multiplyScalar(J)}projectOnPlane($){return UO.copy(this).projectOnVector($),this.sub(UO)}reflect($){return this.sub(UO.copy($).multiplyScalar(2*this.dot($)))}angleTo($){let U=Math.sqrt(this.lengthSq()*$.lengthSq());if(U===0)return Math.PI/2;let J=this.dot($)/U;return Math.acos(t$(J,-1,1))}distanceTo($){return Math.sqrt(this.distanceToSquared($))}distanceToSquared($){let U=this.x-$.x,J=this.y-$.y,Q=this.z-$.z;return U*U+J*J+Q*Q}manhattanDistanceTo($){return Math.abs(this.x-$.x)+Math.abs(this.y-$.y)+Math.abs(this.z-$.z)}setFromSpherical($){return this.setFromSphericalCoords($.radius,$.phi,$.theta)}setFromSphericalCoords($,U,J){let Q=Math.sin(U)*$;return this.x=Q*Math.sin(J),this.y=Math.cos(U)*$,this.z=Q*Math.cos(J),this}setFromCylindrical($){return this.setFromCylindricalCoords($.radius,$.theta,$.y)}setFromCylindricalCoords($,U,J){return this.x=$*Math.sin(U),this.y=J,this.z=$*Math.cos(U),this}setFromMatrixPosition($){let U=$.elements;return this.x=U[12],this.y=U[13],this.z=U[14],this}setFromMatrixScale($){let U=this.setFromMatrixColumn($,0).length(),J=this.setFromMatrixColumn($,1).length(),Q=this.setFromMatrixColumn($,2).length();return this.x=U,this.y=J,this.z=Q,this}setFromMatrixColumn($,U){return this.fromArray($.elements,U*4)}setFromMatrix3Column($,U){return this.fromArray($.elements,U*3)}setFromEuler($){return this.x=$._x,this.y=$._y,this.z=$._z,this}setFromColor($){return this.x=$.r,this.y=$.g,this.z=$.b,this}equals($){return $.x===this.x&&$.y===this.y&&$.z===this.z}fromArray($,U=0){return this.x=$[U],this.y=$[U+1],this.z=$[U+2],this}toArray($=[],U=0){return $[U]=this.x,$[U+1]=this.y,$[U+2]=this.z,$}fromBufferAttribute($,U){return this.x=$.getX(U),this.y=$.getY(U),this.z=$.getZ(U),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let $=Math.random()*Math.PI*2,U=Math.random()*2-1,J=Math.sqrt(1-U*U);return this.x=J*Math.cos($),this.y=U,this.z=J*Math.sin($),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}var UO=new j,UD=new i6;class u${static{u$.prototype.isMatrix3=!0}constructor($,U,J,Q,W,K,X,N,H){if(this.elements=[1,0,0,0,1,0,0,0,1],$!==void 0)this.set($,U,J,Q,W,K,X,N,H)}set($,U,J,Q,W,K,X,N,H){let Y=this.elements;return Y[0]=$,Y[1]=Q,Y[2]=X,Y[3]=U,Y[4]=W,Y[5]=N,Y[6]=J,Y[7]=K,Y[8]=H,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy($){let U=this.elements,J=$.elements;return U[0]=J[0],U[1]=J[1],U[2]=J[2],U[3]=J[3],U[4]=J[4],U[5]=J[5],U[6]=J[6],U[7]=J[7],U[8]=J[8],this}extractBasis($,U,J){return $.setFromMatrix3Column(this,0),U.setFromMatrix3Column(this,1),J.setFromMatrix3Column(this,2),this}setFromMatrix4($){let U=$.elements;return this.set(U[0],U[4],U[8],U[1],U[5],U[9],U[2],U[6],U[10]),this}multiply($){return this.multiplyMatrices(this,$)}premultiply($){return this.multiplyMatrices($,this)}multiplyMatrices($,U){let J=$.elements,Q=U.elements,W=this.elements,K=J[0],X=J[3],N=J[6],H=J[1],Y=J[4],G=J[7],O=J[2],E=J[5],Z=J[8],D=Q[0],R=Q[3],I=Q[6],q=Q[1],_=Q[4],P=Q[7],L=Q[2],B=Q[5],z=Q[8];return W[0]=K*D+X*q+N*L,W[3]=K*R+X*_+N*B,W[6]=K*I+X*P+N*z,W[1]=H*D+Y*q+G*L,W[4]=H*R+Y*_+G*B,W[7]=H*I+Y*P+G*z,W[2]=O*D+E*q+Z*L,W[5]=O*R+E*_+Z*B,W[8]=O*I+E*P+Z*z,this}multiplyScalar($){let U=this.elements;return U[0]*=$,U[3]*=$,U[6]*=$,U[1]*=$,U[4]*=$,U[7]*=$,U[2]*=$,U[5]*=$,U[8]*=$,this}determinant(){let $=this.elements,U=$[0],J=$[1],Q=$[2],W=$[3],K=$[4],X=$[5],N=$[6],H=$[7],Y=$[8];return U*K*Y-U*X*H-J*W*Y+J*X*N+Q*W*H-Q*K*N}invert(){let $=this.elements,U=$[0],J=$[1],Q=$[2],W=$[3],K=$[4],X=$[5],N=$[6],H=$[7],Y=$[8],G=Y*K-X*H,O=X*N-Y*W,E=H*W-K*N,Z=U*G+J*O+Q*E;if(Z===0)return this.set(0,0,0,0,0,0,0,0,0);let D=1/Z;return $[0]=G*D,$[1]=(Q*H-Y*J)*D,$[2]=(X*J-Q*K)*D,$[3]=O*D,$[4]=(Y*U-Q*N)*D,$[5]=(Q*W-X*U)*D,$[6]=E*D,$[7]=(J*N-H*U)*D,$[8]=(K*U-J*W)*D,this}transpose(){let $,U=this.elements;return $=U[1],U[1]=U[3],U[3]=$,$=U[2],U[2]=U[6],U[6]=$,$=U[5],U[5]=U[7],U[7]=$,this}getNormalMatrix($){return this.setFromMatrix4($).invert().transpose()}transposeIntoArray($){let U=this.elements;return $[0]=U[0],$[1]=U[3],$[2]=U[6],$[3]=U[1],$[4]=U[4],$[5]=U[7],$[6]=U[2],$[7]=U[5],$[8]=U[8],this}setUvTransform($,U,J,Q,W,K,X){let N=Math.cos(W),H=Math.sin(W);return this.set(J*N,J*H,-J*(N*K+H*X)+K+$,-Q*H,Q*N,-Q*(-H*K+N*X)+X+U,0,0,1),this}scale($,U){return b0("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(JO.makeScale($,U)),this}rotate($){return b0("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(JO.makeRotation(-$)),this}translate($,U){return b0("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(JO.makeTranslation($,U)),this}makeTranslation($,U){if($.isVector2)this.set(1,0,$.x,0,1,$.y,0,0,1);else this.set(1,0,$,0,1,U,0,0,1);return this}makeRotation($){let U=Math.cos($),J=Math.sin($);return this.set(U,-J,0,J,U,0,0,0,1),this}makeScale($,U){return this.set($,0,0,0,U,0,0,0,1),this}equals($){let U=this.elements,J=$.elements;for(let Q=0;Q<9;Q++)if(U[Q]!==J[Q])return!1;return!0}fromArray($,U=0){for(let J=0;J<9;J++)this.elements[J]=$[J+U];return this}toArray($=[],U=0){let J=this.elements;return $[U]=J[0],$[U+1]=J[1],$[U+2]=J[2],$[U+3]=J[3],$[U+4]=J[4],$[U+5]=J[5],$[U+6]=J[6],$[U+7]=J[7],$[U+8]=J[8],$}clone(){return new this.constructor().fromArray(this.elements)}}var JO=new u$,JD=new u$().set(0.4123908,0.3575843,0.1804808,0.212639,0.7151687,0.0721923,0.0193308,0.1191948,0.9505322),WD=new u$().set(3.2409699,-1.5373832,-0.4986108,-0.9692436,1.8759675,0.0415551,0.0556301,-0.203977,1.0569715);function aR(){let $={enabled:!0,workingColorSpace:"srgb-linear",spaces:{},convert:function(W,K,X){if(this.enabled===!1||K===X||!K||!X)return W;if(this.spaces[K].transfer==="srgb")W.r=vJ(W.r),W.g=vJ(W.g),W.b=vJ(W.b);if(this.spaces[K].primaries!==this.spaces[X].primaries)W.applyMatrix3(this.spaces[K].toXYZ),W.applyMatrix3(this.spaces[X].fromXYZ);if(this.spaces[X].transfer==="srgb")W.r=cW(W.r),W.g=cW(W.g),W.b=cW(W.b);return W},workingToColorSpace:function(W,K){return this.convert(W,this.workingColorSpace,K)},colorSpaceToWorking:function(W,K){return this.convert(W,K,this.workingColorSpace)},getPrimaries:function(W){return this.spaces[W].primaries},getTransfer:function(W){if(W==="")return"linear";return this.spaces[W].transfer},getToneMappingMode:function(W){return this.spaces[W].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(W,K=this.workingColorSpace){return W.fromArray(this.spaces[K].luminanceCoefficients)},define:function(W){Object.assign(this.spaces,W)},_getMatrix:function(W,K,X){return W.copy(this.spaces[K].toXYZ).multiply(this.spaces[X].fromXYZ)},_getDrawingBufferColorSpace:function(W){return this.spaces[W].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(W=this.workingColorSpace){return this.spaces[W].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(W,K){return b0("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),$.workingToColorSpace(W,K)},toWorkingColorSpace:function(W,K){return b0("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),$.colorSpaceToWorking(W,K)}},U=[0.64,0.33,0.3,0.6,0.15,0.06],J=[0.2126,0.7152,0.0722],Q=[0.3127,0.329];return $.define({["srgb-linear"]:{primaries:U,whitePoint:Q,transfer:"linear",toXYZ:JD,fromXYZ:WD,luminanceCoefficients:J,workingColorSpaceConfig:{unpackColorSpace:"srgb"},outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}},["srgb"]:{primaries:U,whitePoint:Q,transfer:"srgb",toXYZ:JD,fromXYZ:WD,luminanceCoefficients:J,outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}}}),$}var s$=aR();function vJ($){return $<0.04045?$*0.0773993808:Math.pow($*0.9478672986+0.0521327014,2.4)}function cW($){return $<0.0031308?$*12.92:1.055*Math.pow($,0.41666)-0.055}var TW;class AE{static getDataURL($,U="image/png"){if(/^data:/i.test($.src))return $.src;if(typeof HTMLCanvasElement>"u")return $.src;let J;if($ instanceof HTMLCanvasElement)J=$;else{if(TW===void 0)TW=nW("canvas");TW.width=$.width,TW.height=$.height;let Q=TW.getContext("2d");if($ instanceof ImageData)Q.putImageData($,0,0);else Q.drawImage($,0,0,$.width,$.height);J=TW}return J.toDataURL(U)}static sRGBToLinear($){if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap){let U=nW("canvas");U.width=$.width,U.height=$.height;let J=U.getContext("2d");J.drawImage($,0,0,$.width,$.height);let Q=J.getImageData(0,0,$.width,$.height),W=Q.data;for(let K=0;K<W.length;K++)W[K]=vJ(W[K]/255)*255;return J.putImageData(Q,0,0),U}else if($.data){let U=$.data.slice(0);for(let J=0;J<U.length;J++)if(U instanceof Uint8Array||U instanceof Uint8ClampedArray)U[J]=Math.floor(vJ(U[J]/255)*255);else U[J]=vJ(U[J]);return{data:U,width:$.width,height:$.height}}else return A$("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),$}}var sR=0;class RQ{constructor($=null){this.isSource=!0,Object.defineProperty(this,"id",{value:sR++}),this.uuid=iU(),this.data=$,this.dataReady=!0,this.version=0}getSize($){let U=this.data;if(typeof HTMLVideoElement<"u"&&U instanceof HTMLVideoElement)$.set(U.videoWidth,U.videoHeight,0);else if(typeof VideoFrame<"u"&&U instanceof VideoFrame)$.set(U.displayWidth,U.displayHeight,0);else if(U!==null)$.set(U.width,U.height,U.depth||0);else $.set(0,0,0);return $}set needsUpdate($){if($===!0)this.version++}toJSON($){let U=$===void 0||typeof $==="string";if(!U&&$.images[this.uuid]!==void 0)return $.images[this.uuid];let J={uuid:this.uuid,url:""},Q=this.data;if(Q!==null){let W;if(Array.isArray(Q)){W=[];for(let K=0,X=Q.length;K<X;K++)if(Q[K].isDataTexture)W.push(WO(Q[K].image));else W.push(WO(Q[K]))}else W=WO(Q);J.url=W}if(!U)$.images[this.uuid]=J;return J}}function WO($){if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap)return AE.getDataURL($);else if($.data)return{data:Array.from($.data),width:$.width,height:$.height,type:$.data.constructor.name};else return A$("Texture: Unable to serialize Texture."),{}}var tR=0,QO=new j;class v6 extends sU{constructor($=v6.DEFAULT_IMAGE,U=v6.DEFAULT_MAPPING,J=1001,Q=1001,W=1006,K=1008,X=1023,N=1009,H=v6.DEFAULT_ANISOTROPY,Y=""){super();this.isTexture=!0,Object.defineProperty(this,"id",{value:tR++}),this.uuid=iU(),this.name="",this.source=new RQ($),this.mipmaps=[],this.mapping=U,this.channel=0,this.wrapS=J,this.wrapT=Q,this.magFilter=W,this.minFilter=K,this.anisotropy=H,this.format=X,this.internalFormat=null,this.type=N,this.offset=new g$(0,0),this.repeat=new g$(1,1),this.center=new g$(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new u$,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=Y,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=$&&$.depth&&$.depth>1?!0:!1,this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(QO).x}get height(){return this.source.getSize(QO).y}get depth(){return this.source.getSize(QO).z}get image(){return this.source.data}set image($){this.source.data=$}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($,U){this.updateRanges.push({start:$,count:U})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy($){return this.name=$.name,this.source=$.source,this.mipmaps=$.mipmaps.slice(0),this.mapping=$.mapping,this.channel=$.channel,this.wrapS=$.wrapS,this.wrapT=$.wrapT,this.magFilter=$.magFilter,this.minFilter=$.minFilter,this.anisotropy=$.anisotropy,this.format=$.format,this.internalFormat=$.internalFormat,this.type=$.type,this.normalized=$.normalized,this.offset.copy($.offset),this.repeat.copy($.repeat),this.center.copy($.center),this.rotation=$.rotation,this.matrixAutoUpdate=$.matrixAutoUpdate,this.matrix.copy($.matrix),this.generateMipmaps=$.generateMipmaps,this.premultiplyAlpha=$.premultiplyAlpha,this.flipY=$.flipY,this.unpackAlignment=$.unpackAlignment,this.colorSpace=$.colorSpace,this.renderTarget=$.renderTarget,this.isRenderTargetTexture=$.isRenderTargetTexture,this.isArrayTexture=$.isArrayTexture,this.userData=JSON.parse(JSON.stringify($.userData)),this.needsUpdate=!0,this}setValues($){for(let U in $){let J=$[U];if(J===void 0){A$(`Texture.setValues(): parameter '${U}' has value of undefined.`);continue}let Q=this[U];if(Q===void 0){A$(`Texture.setValues(): property '${U}' does not exist.`);continue}if(Q&&J&&(Q.isVector2&&J.isVector2))Q.copy(J);else if(Q&&J&&(Q.isVector3&&J.isVector3))Q.copy(J);else if(Q&&J&&(Q.isMatrix3&&J.isMatrix3))Q.copy(J);else this[U]=J}}toJSON($){let U=$===void 0||typeof $==="string";if(!U&&$.textures[this.uuid]!==void 0)return $.textures[this.uuid];let J={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON($).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};if(Object.keys(this.userData).length>0)J.userData=this.userData;if(!U)$.textures[this.uuid]=J;return J}dispose(){this.dispatchEvent({type:"dispose"})}transformUv($){if(this.mapping!==300)return $;if($.applyMatrix3(this.matrix),$.x<0||$.x>1)switch(this.wrapS){case 1000:$.x=$.x-Math.floor($.x);break;case 1001:$.x=$.x<0?0:1;break;case 1002:if(Math.abs(Math.floor($.x)%2)===1)$.x=Math.ceil($.x)-$.x;else $.x=$.x-Math.floor($.x);break}if($.y<0||$.y>1)switch(this.wrapT){case 1000:$.y=$.y-Math.floor($.y);break;case 1001:$.y=$.y<0?0:1;break;case 1002:if(Math.abs(Math.floor($.y)%2)===1)$.y=Math.ceil($.y)-$.y;else $.y=$.y-Math.floor($.y);break}if(this.flipY)$.y=1-$.y;return $}set needsUpdate($){if($===!0)this.version++,this.source.needsUpdate=!0}set needsPMREMUpdate($){if($===!0)this.pmremVersion++}}v6.DEFAULT_IMAGE=null;v6.DEFAULT_MAPPING=300;v6.DEFAULT_ANISOTROPY=1;class Z6{static{Z6.prototype.isVector4=!0}constructor($=0,U=0,J=0,Q=1){this.x=$,this.y=U,this.z=J,this.w=Q}get width(){return this.z}set width($){this.z=$}get height(){return this.w}set height($){this.w=$}set($,U,J,Q){return this.x=$,this.y=U,this.z=J,this.w=Q,this}setScalar($){return this.x=$,this.y=$,this.z=$,this.w=$,this}setX($){return this.x=$,this}setY($){return this.y=$,this}setZ($){return this.z=$,this}setW($){return this.w=$,this}setComponent($,U){switch($){case 0:this.x=U;break;case 1:this.y=U;break;case 2:this.z=U;break;case 3:this.w=U;break;default:throw Error("THREE.Vector4: index is out of range: "+$)}return this}getComponent($){switch($){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("THREE.Vector4: index is out of range: "+$)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy($){return this.x=$.x,this.y=$.y,this.z=$.z,this.w=$.w!==void 0?$.w:1,this}add($){return this.x+=$.x,this.y+=$.y,this.z+=$.z,this.w+=$.w,this}addScalar($){return this.x+=$,this.y+=$,this.z+=$,this.w+=$,this}addVectors($,U){return this.x=$.x+U.x,this.y=$.y+U.y,this.z=$.z+U.z,this.w=$.w+U.w,this}addScaledVector($,U){return this.x+=$.x*U,this.y+=$.y*U,this.z+=$.z*U,this.w+=$.w*U,this}sub($){return this.x-=$.x,this.y-=$.y,this.z-=$.z,this.w-=$.w,this}subScalar($){return this.x-=$,this.y-=$,this.z-=$,this.w-=$,this}subVectors($,U){return this.x=$.x-U.x,this.y=$.y-U.y,this.z=$.z-U.z,this.w=$.w-U.w,this}multiply($){return this.x*=$.x,this.y*=$.y,this.z*=$.z,this.w*=$.w,this}multiplyScalar($){return this.x*=$,this.y*=$,this.z*=$,this.w*=$,this}applyMatrix4($){let U=this.x,J=this.y,Q=this.z,W=this.w,K=$.elements;return this.x=K[0]*U+K[4]*J+K[8]*Q+K[12]*W,this.y=K[1]*U+K[5]*J+K[9]*Q+K[13]*W,this.z=K[2]*U+K[6]*J+K[10]*Q+K[14]*W,this.w=K[3]*U+K[7]*J+K[11]*Q+K[15]*W,this}divide($){return this.x/=$.x,this.y/=$.y,this.z/=$.z,this.w/=$.w,this}divideScalar($){return this.multiplyScalar(1/$)}setAxisAngleFromQuaternion($){this.w=2*Math.acos($.w);let U=Math.sqrt(1-$.w*$.w);if(U<0.0001)this.x=1,this.y=0,this.z=0;else this.x=$.x/U,this.y=$.y/U,this.z=$.z/U;return this}setAxisAngleFromRotationMatrix($){let U,J,Q,W,K=0.01,X=0.1,N=$.elements,H=N[0],Y=N[4],G=N[8],O=N[1],E=N[5],Z=N[9],D=N[2],R=N[6],I=N[10];if(Math.abs(Y-O)<0.01&&Math.abs(G-D)<0.01&&Math.abs(Z-R)<0.01){if(Math.abs(Y+O)<0.1&&Math.abs(G+D)<0.1&&Math.abs(Z+R)<0.1&&Math.abs(H+E+I-3)<0.1)return this.set(1,0,0,0),this;U=Math.PI;let _=(H+1)/2,P=(E+1)/2,L=(I+1)/2,B=(Y+O)/4,z=(G+D)/4,A=(Z+R)/4;if(_>P&&_>L)if(_<0.01)J=0,Q=0.707106781,W=0.707106781;else J=Math.sqrt(_),Q=B/J,W=z/J;else if(P>L)if(P<0.01)J=0.707106781,Q=0,W=0.707106781;else Q=Math.sqrt(P),J=B/Q,W=A/Q;else if(L<0.01)J=0.707106781,Q=0.707106781,W=0;else W=Math.sqrt(L),J=z/W,Q=A/W;return this.set(J,Q,W,U),this}let q=Math.sqrt((R-Z)*(R-Z)+(G-D)*(G-D)+(O-Y)*(O-Y));if(Math.abs(q)<0.001)q=1;return this.x=(R-Z)/q,this.y=(G-D)/q,this.z=(O-Y)/q,this.w=Math.acos((H+E+I-1)/2),this}setFromMatrixPosition($){let U=$.elements;return this.x=U[12],this.y=U[13],this.z=U[14],this.w=U[15],this}min($){return this.x=Math.min(this.x,$.x),this.y=Math.min(this.y,$.y),this.z=Math.min(this.z,$.z),this.w=Math.min(this.w,$.w),this}max($){return this.x=Math.max(this.x,$.x),this.y=Math.max(this.y,$.y),this.z=Math.max(this.z,$.z),this.w=Math.max(this.w,$.w),this}clamp($,U){return this.x=t$(this.x,$.x,U.x),this.y=t$(this.y,$.y,U.y),this.z=t$(this.z,$.z,U.z),this.w=t$(this.w,$.w,U.w),this}clampScalar($,U){return this.x=t$(this.x,$,U),this.y=t$(this.y,$,U),this.z=t$(this.z,$,U),this.w=t$(this.w,$,U),this}clampLength($,U){let J=this.length();return this.divideScalar(J||1).multiplyScalar(t$(J,$,U))}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($){return this.x*$.x+this.y*$.y+this.z*$.z+this.w*$.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($){return this.normalize().multiplyScalar($)}lerp($,U){return this.x+=($.x-this.x)*U,this.y+=($.y-this.y)*U,this.z+=($.z-this.z)*U,this.w+=($.w-this.w)*U,this}lerpVectors($,U,J){return this.x=$.x+(U.x-$.x)*J,this.y=$.y+(U.y-$.y)*J,this.z=$.z+(U.z-$.z)*J,this.w=$.w+(U.w-$.w)*J,this}equals($){return $.x===this.x&&$.y===this.y&&$.z===this.z&&$.w===this.w}fromArray($,U=0){return this.x=$[U],this.y=$[U+1],this.z=$[U+2],this.w=$[U+3],this}toArray($=[],U=0){return $[U]=this.x,$[U+1]=this.y,$[U+2]=this.z,$[U+3]=this.w,$}fromBufferAttribute($,U){return this.x=$.getX(U),this.y=$.getY(U),this.z=$.getZ(U),this.w=$.getW(U),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}}class CE extends sU{constructor($=1,U=1,J={}){super();J=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},J),this.isRenderTarget=!0,this.width=$,this.height=U,this.depth=J.depth,this.scissor=new Z6(0,0,$,U),this.scissorTest=!1,this.viewport=new Z6(0,0,$,U),this.textures=[];let Q={width:$,height:U,depth:J.depth},W=new v6(Q),K=J.count;for(let X=0;X<K;X++)this.textures[X]=W.clone(),this.textures[X].isRenderTargetTexture=!0,this.textures[X].renderTarget=this;this._setTextureOptions(J),this.depthBuffer=J.depthBuffer,this.stencilBuffer=J.stencilBuffer,this.resolveDepthBuffer=J.resolveDepthBuffer,this.resolveStencilBuffer=J.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=J.depthTexture,this.samples=J.samples,this.multiview=J.multiview,this.useArrayDepthTexture=J.useArrayDepthTexture}_setTextureOptions($={}){let U={minFilter:1006,generateMipmaps:!1,flipY:!1,internalFormat:null};if($.mapping!==void 0)U.mapping=$.mapping;if($.wrapS!==void 0)U.wrapS=$.wrapS;if($.wrapT!==void 0)U.wrapT=$.wrapT;if($.wrapR!==void 0)U.wrapR=$.wrapR;if($.magFilter!==void 0)U.magFilter=$.magFilter;if($.minFilter!==void 0)U.minFilter=$.minFilter;if($.format!==void 0)U.format=$.format;if($.type!==void 0)U.type=$.type;if($.anisotropy!==void 0)U.anisotropy=$.anisotropy;if($.colorSpace!==void 0)U.colorSpace=$.colorSpace;if($.flipY!==void 0)U.flipY=$.flipY;if($.generateMipmaps!==void 0)U.generateMipmaps=$.generateMipmaps;if($.internalFormat!==void 0)U.internalFormat=$.internalFormat;for(let J=0;J<this.textures.length;J++)this.textures[J].setValues(U)}get texture(){return this.textures[0]}set texture($){this.textures[0]=$}set depthTexture($){if(this._depthTexture!==null)this._depthTexture.renderTarget=null;if($!==null)$.renderTarget=this;this._depthTexture=$}get depthTexture(){return this._depthTexture}setSize($,U,J=1){if(this.width!==$||this.height!==U||this.depth!==J){this.width=$,this.height=U,this.depth=J;for(let Q=0,W=this.textures.length;Q<W;Q++)if(this.textures[Q].image.width=$,this.textures[Q].image.height=U,this.textures[Q].image.depth=J,this.textures[Q].isData3DTexture!==!0)this.textures[Q].isArrayTexture=this.textures[Q].image.depth>1;this.dispose()}this.viewport.set(0,0,$,U),this.scissor.set(0,0,$,U)}clone(){return new this.constructor().copy(this)}copy($){this.width=$.width,this.height=$.height,this.depth=$.depth,this.scissor.copy($.scissor),this.scissorTest=$.scissorTest,this.viewport.copy($.viewport),this.textures.length=0;for(let U=0,J=$.textures.length;U<J;U++){this.textures[U]=$.textures[U].clone(),this.textures[U].isRenderTargetTexture=!0,this.textures[U].renderTarget=this;let Q=Object.assign({},$.textures[U].image);this.textures[U].source=new RQ(Q)}if(this.depthBuffer=$.depthBuffer,this.stencilBuffer=$.stencilBuffer,this.resolveDepthBuffer=$.resolveDepthBuffer,this.resolveStencilBuffer=$.resolveStencilBuffer,$.depthTexture!==null)this.depthTexture=$.depthTexture.clone();return this.samples=$.samples,this.multiview=$.multiview,this.useArrayDepthTexture=$.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class xU extends CE{constructor($=1,U=1,J={}){super($,U,J);this.isWebGLRenderTarget=!0}}class Z7 extends v6{constructor($=null,U=1,J=1,Q=1){super(null);this.isDataArrayTexture=!0,this.image={data:$,width:U,height:J,depth:Q},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate($){this.layerUpdates.add($)}clearLayerUpdates(){this.layerUpdates.clear()}}class SE extends v6{constructor($=null,U=1,J=1,Q=1){super(null);this.isData3DTexture=!0,this.image={data:$,width:U,height:J,depth:Q},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class p${static{p$.prototype.isMatrix4=!0}constructor($,U,J,Q,W,K,X,N,H,Y,G,O,E,Z,D,R){if(this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],$!==void 0)this.set($,U,J,Q,W,K,X,N,H,Y,G,O,E,Z,D,R)}set($,U,J,Q,W,K,X,N,H,Y,G,O,E,Z,D,R){let I=this.elements;return I[0]=$,I[4]=U,I[8]=J,I[12]=Q,I[1]=W,I[5]=K,I[9]=X,I[13]=N,I[2]=H,I[6]=Y,I[10]=G,I[14]=O,I[3]=E,I[7]=Z,I[11]=D,I[15]=R,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 p$().fromArray(this.elements)}copy($){let U=this.elements,J=$.elements;return U[0]=J[0],U[1]=J[1],U[2]=J[2],U[3]=J[3],U[4]=J[4],U[5]=J[5],U[6]=J[6],U[7]=J[7],U[8]=J[8],U[9]=J[9],U[10]=J[10],U[11]=J[11],U[12]=J[12],U[13]=J[13],U[14]=J[14],U[15]=J[15],this}copyPosition($){let U=this.elements,J=$.elements;return U[12]=J[12],U[13]=J[13],U[14]=J[14],this}setFromMatrix3($){let U=$.elements;return this.set(U[0],U[3],U[6],0,U[1],U[4],U[7],0,U[2],U[5],U[8],0,0,0,0,1),this}extractBasis($,U,J){if(this.determinantAffine()===0)return $.set(1,0,0),U.set(0,1,0),J.set(0,0,1),this;return $.setFromMatrixColumn(this,0),U.setFromMatrixColumn(this,1),J.setFromMatrixColumn(this,2),this}makeBasis($,U,J){return this.set($.x,U.x,J.x,0,$.y,U.y,J.y,0,$.z,U.z,J.z,0,0,0,0,1),this}extractRotation($){if($.determinantAffine()===0)return this.identity();let U=this.elements,J=$.elements,Q=1/vW.setFromMatrixColumn($,0).length(),W=1/vW.setFromMatrixColumn($,1).length(),K=1/vW.setFromMatrixColumn($,2).length();return U[0]=J[0]*Q,U[1]=J[1]*Q,U[2]=J[2]*Q,U[3]=0,U[4]=J[4]*W,U[5]=J[5]*W,U[6]=J[6]*W,U[7]=0,U[8]=J[8]*K,U[9]=J[9]*K,U[10]=J[10]*K,U[11]=0,U[12]=0,U[13]=0,U[14]=0,U[15]=1,this}makeRotationFromEuler($){let U=this.elements,J=$.x,Q=$.y,W=$.z,K=Math.cos(J),X=Math.sin(J),N=Math.cos(Q),H=Math.sin(Q),Y=Math.cos(W),G=Math.sin(W);if($.order==="XYZ"){let O=K*Y,E=K*G,Z=X*Y,D=X*G;U[0]=N*Y,U[4]=-N*G,U[8]=H,U[1]=E+Z*H,U[5]=O-D*H,U[9]=-X*N,U[2]=D-O*H,U[6]=Z+E*H,U[10]=K*N}else if($.order==="YXZ"){let O=N*Y,E=N*G,Z=H*Y,D=H*G;U[0]=O+D*X,U[4]=Z*X-E,U[8]=K*H,U[1]=K*G,U[5]=K*Y,U[9]=-X,U[2]=E*X-Z,U[6]=D+O*X,U[10]=K*N}else if($.order==="ZXY"){let O=N*Y,E=N*G,Z=H*Y,D=H*G;U[0]=O-D*X,U[4]=-K*G,U[8]=Z+E*X,U[1]=E+Z*X,U[5]=K*Y,U[9]=D-O*X,U[2]=-K*H,U[6]=X,U[10]=K*N}else if($.order==="ZYX"){let O=K*Y,E=K*G,Z=X*Y,D=X*G;U[0]=N*Y,U[4]=Z*H-E,U[8]=O*H+D,U[1]=N*G,U[5]=D*H+O,U[9]=E*H-Z,U[2]=-H,U[6]=X*N,U[10]=K*N}else if($.order==="YZX"){let O=K*N,E=K*H,Z=X*N,D=X*H;U[0]=N*Y,U[4]=D-O*G,U[8]=Z*G+E,U[1]=G,U[5]=K*Y,U[9]=-X*Y,U[2]=-H*Y,U[6]=E*G+Z,U[10]=O-D*G}else if($.order==="XZY"){let O=K*N,E=K*H,Z=X*N,D=X*H;U[0]=N*Y,U[4]=-G,U[8]=H*Y,U[1]=O*G+D,U[5]=K*Y,U[9]=E*G-Z,U[2]=Z*G-E,U[6]=X*Y,U[10]=D*G+O}return U[3]=0,U[7]=0,U[11]=0,U[12]=0,U[13]=0,U[14]=0,U[15]=1,this}makeRotationFromQuaternion($){return this.compose(eR,$,$V)}lookAt($,U,J){let Q=this.elements;if(wU.subVectors($,U),wU.lengthSq()===0)wU.z=1;if(wU.normalize(),sJ.crossVectors(J,wU),sJ.lengthSq()===0){if(Math.abs(J.z)===1)wU.x+=0.0001;else wU.z+=0.0001;wU.normalize(),sJ.crossVectors(J,wU)}return sJ.normalize(),zK.crossVectors(wU,sJ),Q[0]=sJ.x,Q[4]=zK.x,Q[8]=wU.x,Q[1]=sJ.y,Q[5]=zK.y,Q[9]=wU.y,Q[2]=sJ.z,Q[6]=zK.z,Q[10]=wU.z,this}multiply($){return this.multiplyMatrices(this,$)}premultiply($){return this.multiplyMatrices($,this)}multiplyMatrices($,U){let J=$.elements,Q=U.elements,W=this.elements,K=J[0],X=J[4],N=J[8],H=J[12],Y=J[1],G=J[5],O=J[9],E=J[13],Z=J[2],D=J[6],R=J[10],I=J[14],q=J[3],_=J[7],P=J[11],L=J[15],B=Q[0],z=Q[4],A=Q[8],k=Q[12],w=Q[1],h=Q[5],C=Q[9],f=Q[13],s=Q[2],y=Q[6],d=Q[10],c=Q[14],x=Q[3],t=Q[7],e=Q[11],Y$=Q[15];return W[0]=K*B+X*w+N*s+H*x,W[4]=K*z+X*h+N*y+H*t,W[8]=K*A+X*C+N*d+H*e,W[12]=K*k+X*f+N*c+H*Y$,W[1]=Y*B+G*w+O*s+E*x,W[5]=Y*z+G*h+O*y+E*t,W[9]=Y*A+G*C+O*d+E*e,W[13]=Y*k+G*f+O*c+E*Y$,W[2]=Z*B+D*w+R*s+I*x,W[6]=Z*z+D*h+R*y+I*t,W[10]=Z*A+D*C+R*d+I*e,W[14]=Z*k+D*f+R*c+I*Y$,W[3]=q*B+_*w+P*s+L*x,W[7]=q*z+_*h+P*y+L*t,W[11]=q*A+_*C+P*d+L*e,W[15]=q*k+_*f+P*c+L*Y$,this}multiplyScalar($){let U=this.elements;return U[0]*=$,U[4]*=$,U[8]*=$,U[12]*=$,U[1]*=$,U[5]*=$,U[9]*=$,U[13]*=$,U[2]*=$,U[6]*=$,U[10]*=$,U[14]*=$,U[3]*=$,U[7]*=$,U[11]*=$,U[15]*=$,this}determinant(){let $=this.elements,U=$[0],J=$[4],Q=$[8],W=$[12],K=$[1],X=$[5],N=$[9],H=$[13],Y=$[2],G=$[6],O=$[10],E=$[14],Z=$[3],D=$[7],R=$[11],I=$[15],q=N*E-H*O,_=X*E-H*G,P=X*O-N*G,L=K*E-H*Y,B=K*O-N*Y,z=K*G-X*Y;return U*(D*q-R*_+I*P)-J*(Z*q-R*L+I*B)+Q*(Z*_-D*L+I*z)-W*(Z*P-D*B+R*z)}determinantAffine(){let $=this.elements,U=$[0],J=$[4],Q=$[8],W=$[1],K=$[5],X=$[9],N=$[2],H=$[6],Y=$[10];return U*(K*Y-X*H)-J*(W*Y-X*N)+Q*(W*H-K*N)}transpose(){let $=this.elements,U;return U=$[1],$[1]=$[4],$[4]=U,U=$[2],$[2]=$[8],$[8]=U,U=$[6],$[6]=$[9],$[9]=U,U=$[3],$[3]=$[12],$[12]=U,U=$[7],$[7]=$[13],$[13]=U,U=$[11],$[11]=$[14],$[14]=U,this}setPosition($,U,J){let Q=this.elements;if($.isVector3)Q[12]=$.x,Q[13]=$.y,Q[14]=$.z;else Q[12]=$,Q[13]=U,Q[14]=J;return this}invert(){let $=this.elements,U=$[0],J=$[1],Q=$[2],W=$[3],K=$[4],X=$[5],N=$[6],H=$[7],Y=$[8],G=$[9],O=$[10],E=$[11],Z=$[12],D=$[13],R=$[14],I=$[15],q=U*X-J*K,_=U*N-Q*K,P=U*H-W*K,L=J*N-Q*X,B=J*H-W*X,z=Q*H-W*N,A=Y*D-G*Z,k=Y*R-O*Z,w=Y*I-E*Z,h=G*R-O*D,C=G*I-E*D,f=O*I-E*R,s=q*f-_*C+P*h+L*w-B*k+z*A;if(s===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let y=1/s;return $[0]=(X*f-N*C+H*h)*y,$[1]=(Q*C-J*f-W*h)*y,$[2]=(D*z-R*B+I*L)*y,$[3]=(O*B-G*z-E*L)*y,$[4]=(N*w-K*f-H*k)*y,$[5]=(U*f-Q*w+W*k)*y,$[6]=(R*P-Z*z-I*_)*y,$[7]=(Y*z-O*P+E*_)*y,$[8]=(K*C-X*w+H*A)*y,$[9]=(J*w-U*C-W*A)*y,$[10]=(Z*B-D*P+I*q)*y,$[11]=(G*P-Y*B-E*q)*y,$[12]=(X*k-K*h-N*A)*y,$[13]=(U*h-J*k+Q*A)*y,$[14]=(D*_-Z*L-R*q)*y,$[15]=(Y*L-G*_+O*q)*y,this}scale($){let U=this.elements,J=$.x,Q=$.y,W=$.z;return U[0]*=J,U[4]*=Q,U[8]*=W,U[1]*=J,U[5]*=Q,U[9]*=W,U[2]*=J,U[6]*=Q,U[10]*=W,U[3]*=J,U[7]*=Q,U[11]*=W,this}getMaxScaleOnAxis(){let $=this.elements,U=$[0]*$[0]+$[1]*$[1]+$[2]*$[2],J=$[4]*$[4]+$[5]*$[5]+$[6]*$[6],Q=$[8]*$[8]+$[9]*$[9]+$[10]*$[10];return Math.sqrt(Math.max(U,J,Q))}makeTranslation($,U,J){if($.isVector3)this.set(1,0,0,$.x,0,1,0,$.y,0,0,1,$.z,0,0,0,1);else this.set(1,0,0,$,0,1,0,U,0,0,1,J,0,0,0,1);return this}makeRotationX($){let U=Math.cos($),J=Math.sin($);return this.set(1,0,0,0,0,U,-J,0,0,J,U,0,0,0,0,1),this}makeRotationY($){let U=Math.cos($),J=Math.sin($);return this.set(U,0,J,0,0,1,0,0,-J,0,U,0,0,0,0,1),this}makeRotationZ($){let U=Math.cos($),J=Math.sin($);return this.set(U,-J,0,0,J,U,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis($,U){let J=Math.cos(U),Q=Math.sin(U),W=1-J,K=$.x,X=$.y,N=$.z,H=W*K,Y=W*X;return this.set(H*K+J,H*X-Q*N,H*N+Q*X,0,H*X+Q*N,Y*X+J,Y*N-Q*K,0,H*N-Q*X,Y*N+Q*K,W*N*N+J,0,0,0,0,1),this}makeScale($,U,J){return this.set($,0,0,0,0,U,0,0,0,0,J,0,0,0,0,1),this}makeShear($,U,J,Q,W,K){return this.set(1,J,W,0,$,1,K,0,U,Q,1,0,0,0,0,1),this}compose($,U,J){let Q=this.elements,W=U._x,K=U._y,X=U._z,N=U._w,H=W+W,Y=K+K,G=X+X,O=W*H,E=W*Y,Z=W*G,D=K*Y,R=K*G,I=X*G,q=N*H,_=N*Y,P=N*G,L=J.x,B=J.y,z=J.z;return Q[0]=(1-(D+I))*L,Q[1]=(E+P)*L,Q[2]=(Z-_)*L,Q[3]=0,Q[4]=(E-P)*B,Q[5]=(1-(O+I))*B,Q[6]=(R+q)*B,Q[7]=0,Q[8]=(Z+_)*z,Q[9]=(R-q)*z,Q[10]=(1-(O+D))*z,Q[11]=0,Q[12]=$.x,Q[13]=$.y,Q[14]=$.z,Q[15]=1,this}decompose($,U,J){let Q=this.elements;$.x=Q[12],$.y=Q[13],$.z=Q[14];let W=this.determinantAffine();if(W===0)return J.set(1,1,1),U.identity(),this;let K=vW.set(Q[0],Q[1],Q[2]).length(),X=vW.set(Q[4],Q[5],Q[6]).length(),N=vW.set(Q[8],Q[9],Q[10]).length();if(W<0)K=-K;mU.copy(this);let H=1/K,Y=1/X,G=1/N;return mU.elements[0]*=H,mU.elements[1]*=H,mU.elements[2]*=H,mU.elements[4]*=Y,mU.elements[5]*=Y,mU.elements[6]*=Y,mU.elements[8]*=G,mU.elements[9]*=G,mU.elements[10]*=G,U.setFromRotationMatrix(mU),J.x=K,J.y=X,J.z=N,this}makePerspective($,U,J,Q,W,K,X=2000,N=!1){let H=this.elements,Y=2*W/(U-$),G=2*W/(J-Q),O=(U+$)/(U-$),E=(J+Q)/(J-Q),Z,D;if(N)Z=W/(K-W),D=K*W/(K-W);else if(X===2000)Z=-(K+W)/(K-W),D=-2*K*W/(K-W);else if(X===2001)Z=-K/(K-W),D=-K*W/(K-W);else throw Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+X);return H[0]=Y,H[4]=0,H[8]=O,H[12]=0,H[1]=0,H[5]=G,H[9]=E,H[13]=0,H[2]=0,H[6]=0,H[10]=Z,H[14]=D,H[3]=0,H[7]=0,H[11]=-1,H[15]=0,this}makeOrthographic($,U,J,Q,W,K,X=2000,N=!1){let H=this.elements,Y=2/(U-$),G=2/(J-Q),O=-(U+$)/(U-$),E=-(J+Q)/(J-Q),Z,D;if(N)Z=1/(K-W),D=K/(K-W);else if(X===2000)Z=-2/(K-W),D=-(K+W)/(K-W);else if(X===2001)Z=-1/(K-W),D=-W/(K-W);else throw Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+X);return H[0]=Y,H[4]=0,H[8]=0,H[12]=O,H[1]=0,H[5]=G,H[9]=0,H[13]=E,H[2]=0,H[6]=0,H[10]=Z,H[14]=D,H[3]=0,H[7]=0,H[11]=0,H[15]=1,this}equals($){let U=this.elements,J=$.elements;for(let Q=0;Q<16;Q++)if(U[Q]!==J[Q])return!1;return!0}fromArray($,U=0){for(let J=0;J<16;J++)this.elements[J]=$[J+U];return this}toArray($=[],U=0){let J=this.elements;return $[U]=J[0],$[U+1]=J[1],$[U+2]=J[2],$[U+3]=J[3],$[U+4]=J[4],$[U+5]=J[5],$[U+6]=J[6],$[U+7]=J[7],$[U+8]=J[8],$[U+9]=J[9],$[U+10]=J[10],$[U+11]=J[11],$[U+12]=J[12],$[U+13]=J[13],$[U+14]=J[14],$[U+15]=J[15],$}}var vW=new j,mU=new p$,eR=new j(0,0,0),$V=new j(1,1,1),sJ=new j,zK=new j,wU=new j,QD=new p$,KD=new i6;class OJ{constructor($=0,U=0,J=0,Q=OJ.DEFAULT_ORDER){this.isEuler=!0,this._x=$,this._y=U,this._z=J,this._order=Q}get x(){return this._x}set x($){this._x=$,this._onChangeCallback()}get y(){return this._y}set y($){this._y=$,this._onChangeCallback()}get z(){return this._z}set z($){this._z=$,this._onChangeCallback()}get order(){return this._order}set order($){this._order=$,this._onChangeCallback()}set($,U,J,Q=this._order){return this._x=$,this._y=U,this._z=J,this._order=Q,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy($){return this._x=$._x,this._y=$._y,this._z=$._z,this._order=$._order,this._onChangeCallback(),this}setFromRotationMatrix($,U=this._order,J=!0){let Q=$.elements,W=Q[0],K=Q[4],X=Q[8],N=Q[1],H=Q[5],Y=Q[9],G=Q[2],O=Q[6],E=Q[10];switch(U){case"XYZ":if(this._y=Math.asin(t$(X,-1,1)),Math.abs(X)<0.9999999)this._x=Math.atan2(-Y,E),this._z=Math.atan2(-K,W);else this._x=Math.atan2(O,H),this._z=0;break;case"YXZ":if(this._x=Math.asin(-t$(Y,-1,1)),Math.abs(Y)<0.9999999)this._y=Math.atan2(X,E),this._z=Math.atan2(N,H);else this._y=Math.atan2(-G,W),this._z=0;break;case"ZXY":if(this._x=Math.asin(t$(O,-1,1)),Math.abs(O)<0.9999999)this._y=Math.atan2(-G,E),this._z=Math.atan2(-K,H);else this._y=0,this._z=Math.atan2(N,W);break;case"ZYX":if(this._y=Math.asin(-t$(G,-1,1)),Math.abs(G)<0.9999999)this._x=Math.atan2(O,E),this._z=Math.atan2(N,W);else this._x=0,this._z=Math.atan2(-K,H);break;case"YZX":if(this._z=Math.asin(t$(N,-1,1)),Math.abs(N)<0.9999999)this._x=Math.atan2(-Y,H),this._y=Math.atan2(-G,W);else this._x=0,this._y=Math.atan2(X,E);break;case"XZY":if(this._z=Math.asin(-t$(K,-1,1)),Math.abs(K)<0.9999999)this._x=Math.atan2(O,H),this._y=Math.atan2(X,W);else this._x=Math.atan2(-Y,E),this._y=0;break;default:A$("Euler: .setFromRotationMatrix() encountered an unknown order: "+U)}if(this._order=U,J===!0)this._onChangeCallback();return this}setFromQuaternion($,U,J){return QD.makeRotationFromQuaternion($),this.setFromRotationMatrix(QD,U,J)}setFromVector3($,U=this._order){return this.set($.x,$.y,$.z,U)}reorder($){return KD.setFromEuler(this),this.setFromQuaternion(KD,$)}equals($){return $._x===this._x&&$._y===this._y&&$._z===this._z&&$._order===this._order}fromArray($){if(this._x=$[0],this._y=$[1],this._z=$[2],$[3]!==void 0)this._order=$[3];return this._onChangeCallback(),this}toArray($=[],U=0){return $[U]=this._x,$[U+1]=this._y,$[U+2]=this._z,$[U+3]=this._order,$}_onChange($){return this._onChangeCallback=$,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}OJ.DEFAULT_ORDER="XYZ";class I7{constructor(){this.mask=1}set($){this.mask=(1<<$|0)>>>0}enable($){this.mask|=1<<$|0}enableAll(){this.mask=-1}toggle($){this.mask^=1<<$|0}disable($){this.mask&=~(1<<$|0)}disableAll(){this.mask=0}test($){return(this.mask&$.mask)!==0}isEnabled($){return(this.mask&(1<<$|0))!==0}}var UV=0,XD=new j,jW=new i6,zJ=new p$,_K=new j,JQ=new j,JV=new j,WV=new i6,ND=new j(1,0,0),HD=new j(0,1,0),YD=new j(0,0,1),GD={type:"added"},QV={type:"removed"},gW={type:"childadded",child:null},KO={type:"childremoved",child:null};class k6 extends sU{constructor(){super();this.isObject3D=!0,Object.defineProperty(this,"id",{value:UV++}),this.uuid=iU(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=k6.DEFAULT_UP.clone();let $=new j,U=new OJ,J=new i6,Q=new j(1,1,1);function W(){J.setFromEuler(U,!1)}function K(){U.setFromQuaternion(J,void 0,!1)}U._onChange(W),J._onChange(K),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:$},rotation:{configurable:!0,enumerable:!0,value:U},quaternion:{configurable:!0,enumerable:!0,value:J},scale:{configurable:!0,enumerable:!0,value:Q},modelViewMatrix:{value:new p$},normalMatrix:{value:new u$}}),this.matrix=new p$,this.matrixWorld=new p$,this.matrixAutoUpdate=k6.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=k6.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new I7,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($){if(this.matrixAutoUpdate)this.updateMatrix();this.matrix.premultiply($),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion($){return this.quaternion.premultiply($),this}setRotationFromAxisAngle($,U){this.quaternion.setFromAxisAngle($,U)}setRotationFromEuler($){this.quaternion.setFromEuler($,!0)}setRotationFromMatrix($){this.quaternion.setFromRotationMatrix($)}setRotationFromQuaternion($){this.quaternion.copy($)}rotateOnAxis($,U){return jW.setFromAxisAngle($,U),this.quaternion.multiply(jW),this}rotateOnWorldAxis($,U){return jW.setFromAxisAngle($,U),this.quaternion.premultiply(jW),this}rotateX($){return this.rotateOnAxis(ND,$)}rotateY($){return this.rotateOnAxis(HD,$)}rotateZ($){return this.rotateOnAxis(YD,$)}translateOnAxis($,U){return XD.copy($).applyQuaternion(this.quaternion),this.position.add(XD.multiplyScalar(U)),this}translateX($){return this.translateOnAxis(ND,$)}translateY($){return this.translateOnAxis(HD,$)}translateZ($){return this.translateOnAxis(YD,$)}localToWorld($){return this.updateWorldMatrix(!0,!1),$.applyMatrix4(this.matrixWorld)}worldToLocal($){return this.updateWorldMatrix(!0,!1),$.applyMatrix4(zJ.copy(this.matrixWorld).invert())}lookAt($,U,J){if($.isVector3)_K.copy($);else _K.set($,U,J);let Q=this.parent;if(this.updateWorldMatrix(!0,!1),JQ.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight)zJ.lookAt(JQ,_K,this.up);else zJ.lookAt(_K,JQ,this.up);if(this.quaternion.setFromRotationMatrix(zJ),Q)zJ.extractRotation(Q.matrixWorld),jW.setFromRotationMatrix(zJ),this.quaternion.premultiply(jW.invert())}add($){if(arguments.length>1){for(let U=0;U<arguments.length;U++)this.add(arguments[U]);return this}if($===this)return y$("Object3D.add: object can't be added as a child of itself.",$),this;if($&&$.isObject3D)$.removeFromParent(),$.parent=this,this.children.push($),$.dispatchEvent(GD),gW.child=$,this.dispatchEvent(gW),gW.child=null;else y$("Object3D.add: object not an instance of THREE.Object3D.",$);return this}remove($){if(arguments.length>1){for(let J=0;J<arguments.length;J++)this.remove(arguments[J]);return this}let U=this.children.indexOf($);if(U!==-1)$.parent=null,this.children.splice(U,1),$.dispatchEvent(QV),KO.child=$,this.dispatchEvent(KO),KO.child=null;return this}removeFromParent(){let $=this.parent;if($!==null)$.remove(this);return this}clear(){return this.remove(...this.children)}attach($){if(this.updateWorldMatrix(!0,!1),zJ.copy(this.matrixWorld).invert(),$.parent!==null)$.parent.updateWorldMatrix(!0,!1),zJ.multiply($.parent.matrixWorld);return $.applyMatrix4(zJ),$.removeFromParent(),$.parent=this,this.children.push($),$.updateWorldMatrix(!1,!0),$.dispatchEvent(GD),gW.child=$,this.dispatchEvent(gW),gW.child=null,this}getObjectById($){return this.getObjectByProperty("id",$)}getObjectByName($){return this.getObjectByProperty("name",$)}getObjectByProperty($,U){if(this[$]===U)return this;for(let J=0,Q=this.children.length;J<Q;J++){let K=this.children[J].getObjectByProperty($,U);if(K!==void 0)return K}return}getObjectsByProperty($,U,J=[]){if(this[$]===U)J.push(this);let Q=this.children;for(let W=0,K=Q.length;W<K;W++)Q[W].getObjectsByProperty($,U,J);return J}getWorldPosition($){return this.updateWorldMatrix(!0,!1),$.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion($){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(JQ,$,JV),$}getWorldScale($){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(JQ,WV,$),$}getWorldDirection($){this.updateWorldMatrix(!0,!1);let U=this.matrixWorld.elements;return $.set(U[8],U[9],U[10]).normalize()}raycast(){}traverse($){$(this);let U=this.children;for(let J=0,Q=U.length;J<Q;J++)U[J].traverse($)}traverseVisible($){if(this.visible===!1)return;$(this);let U=this.children;for(let J=0,Q=U.length;J<Q;J++)U[J].traverseVisible($)}traverseAncestors($){let U=this.parent;if(U!==null)$(U),U.traverseAncestors($)}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let $=this.pivot;if($!==null){let{x:U,y:J,z:Q}=$,W=this.matrix.elements;W[12]+=U-W[0]*U-W[4]*J-W[8]*Q,W[13]+=J-W[1]*U-W[5]*J-W[9]*Q,W[14]+=Q-W[2]*U-W[6]*J-W[10]*Q}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld($){if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||$){if(this.matrixWorldAutoUpdate===!0)if(this.parent===null)this.matrixWorld.copy(this.matrix);else this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);this.matrixWorldNeedsUpdate=!1,$=!0}let U=this.children;for(let J=0,Q=U.length;J<Q;J++)U[J].updateMatrixWorld($)}updateWorldMatrix($,U,J=!1){let Q=this.parent;if($===!0&&Q!==null)Q.updateWorldMatrix(!0,!1);if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||J){if(this.matrixWorldAutoUpdate===!0)if(this.parent===null)this.matrixWorld.copy(this.matrix);else this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);this.matrixWorldNeedsUpdate=!1,J=!0}if(U===!0){let W=this.children;for(let K=0,X=W.length;K<X;K++)W[K].updateWorldMatrix(!1,!0,J)}}toJSON($){let U=$===void 0||typeof $==="string",J={};if(U)$={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},J.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"};let Q={};if(Q.uuid=this.uuid,Q.type=this.type,this.name!=="")Q.name=this.name;if(this.castShadow===!0)Q.castShadow=!0;if(this.receiveShadow===!0)Q.receiveShadow=!0;if(this.visible===!1)Q.visible=!1;if(this.frustumCulled===!1)Q.frustumCulled=!1;if(this.renderOrder!==0)Q.renderOrder=this.renderOrder;if(this.static!==!1)Q.static=this.static;if(Object.keys(this.userData).length>0)Q.userData=this.userData;if(Q.layers=this.layers.mask,Q.matrix=this.matrix.toArray(),Q.up=this.up.toArray(),this.pivot!==null)Q.pivot=this.pivot.toArray();if(this.matrixAutoUpdate===!1)Q.matrixAutoUpdate=!1;if(this.morphTargetDictionary!==void 0)Q.morphTargetDictionary=Object.assign({},this.morphTargetDictionary);if(this.morphTargetInfluences!==void 0)Q.morphTargetInfluences=this.morphTargetInfluences.slice();if(this.isInstancedMesh){if(Q.type="InstancedMesh",Q.count=this.count,Q.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null)Q.instanceColor=this.instanceColor.toJSON()}if(this.isBatchedMesh){if(Q.type="BatchedMesh",Q.perObjectFrustumCulled=this.perObjectFrustumCulled,Q.sortObjects=this.sortObjects,Q.drawRanges=this._drawRanges,Q.reservedRanges=this._reservedRanges,Q.geometryInfo=this._geometryInfo.map((X)=>({...X,boundingBox:X.boundingBox?X.boundingBox.toJSON():void 0,boundingSphere:X.boundingSphere?X.boundingSphere.toJSON():void 0})),Q.instanceInfo=this._instanceInfo.map((X)=>({...X})),Q.availableInstanceIds=this._availableInstanceIds.slice(),Q.availableGeometryIds=this._availableGeometryIds.slice(),Q.nextIndexStart=this._nextIndexStart,Q.nextVertexStart=this._nextVertexStart,Q.geometryCount=this._geometryCount,Q.maxInstanceCount=this._maxInstanceCount,Q.maxVertexCount=this._maxVertexCount,Q.maxIndexCount=this._maxIndexCount,Q.geometryInitialized=this._geometryInitialized,Q.matricesTexture=this._matricesTexture.toJSON($),Q.indirectTexture=this._indirectTexture.toJSON($),this._colorsTexture!==null)Q.colorsTexture=this._colorsTexture.toJSON($);if(this.boundingSphere!==null)Q.boundingSphere=this.boundingSphere.toJSON();if(this.boundingBox!==null)Q.boundingBox=this.boundingBox.toJSON()}function W(X,N){if(X[N.uuid]===void 0)X[N.uuid]=N.toJSON($);return N.uuid}if(this.isScene){if(this.background){if(this.background.isColor)Q.background=this.background.toJSON();else if(this.background.isTexture)Q.background=this.background.toJSON($).uuid}if(this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0)Q.environment=this.environment.toJSON($).uuid}else if(this.isMesh||this.isLine||this.isPoints){Q.geometry=W($.geometries,this.geometry);let X=this.geometry.parameters;if(X!==void 0&&X.shapes!==void 0){let N=X.shapes;if(Array.isArray(N))for(let H=0,Y=N.length;H<Y;H++){let G=N[H];W($.shapes,G)}else W($.shapes,N)}}if(this.isSkinnedMesh){if(Q.bindMode=this.bindMode,Q.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0)W($.skeletons,this.skeleton),Q.skeleton=this.skeleton.uuid}if(this.material!==void 0)if(Array.isArray(this.material)){let X=[];for(let N=0,H=this.material.length;N<H;N++)X.push(W($.materials,this.material[N]));Q.material=X}else Q.material=W($.materials,this.material);if(this.children.length>0){Q.children=[];for(let X=0;X<this.children.length;X++)Q.children.push(this.children[X].toJSON($).object)}if(this.animations.length>0){Q.animations=[];for(let X=0;X<this.animations.length;X++){let N=this.animations[X];Q.animations.push(W($.animations,N))}}if(U){let X=K($.geometries),N=K($.materials),H=K($.textures),Y=K($.images),G=K($.shapes),O=K($.skeletons),E=K($.animations),Z=K($.nodes);if(X.length>0)J.geometries=X;if(N.length>0)J.materials=N;if(H.length>0)J.textures=H;if(Y.length>0)J.images=Y;if(G.length>0)J.shapes=G;if(O.length>0)J.skeletons=O;if(E.length>0)J.animations=E;if(Z.length>0)J.nodes=Z}return J.object=Q,J;function K(X){let N=[];for(let H in X){let Y=X[H];delete Y.metadata,N.push(Y)}return N}}clone($){return new this.constructor().copy(this,$)}copy($,U=!0){if(this.name=$.name,this.up.copy($.up),this.position.copy($.position),this.rotation.order=$.rotation.order,this.quaternion.copy($.quaternion),this.scale.copy($.scale),this.pivot=$.pivot!==null?$.pivot.clone():null,this.matrix.copy($.matrix),this.matrixWorld.copy($.matrixWorld),this.matrixAutoUpdate=$.matrixAutoUpdate,this.matrixWorldAutoUpdate=$.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=$.matrixWorldNeedsUpdate,this.layers.mask=$.layers.mask,this.visible=$.visible,this.castShadow=$.castShadow,this.receiveShadow=$.receiveShadow,this.frustumCulled=$.frustumCulled,this.renderOrder=$.renderOrder,this.static=$.static,this.animations=$.animations.slice(),this.userData=JSON.parse(JSON.stringify($.userData)),U===!0)for(let J=0;J<$.children.length;J++){let Q=$.children[J];this.add(Q.clone())}return this}}k6.DEFAULT_UP=new j(0,1,0);k6.DEFAULT_MATRIX_AUTO_UPDATE=!0;k6.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class YJ extends k6{constructor(){super();this.isGroup=!0,this.type="Group"}}var KV={type:"move"};class VQ{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){if(this._hand===null)this._hand=new YJ,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1};return this._hand}getTargetRaySpace(){if(this._targetRay===null)this._targetRay=new YJ,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new j,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new j;return this._targetRay}getGripSpace(){if(this._grip===null)this._grip=new YJ,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new j,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new j,this._grip.eventsEnabled=!1;return this._grip}dispatchEvent($){if(this._targetRay!==null)this._targetRay.dispatchEvent($);if(this._grip!==null)this._grip.dispatchEvent($);if(this._hand!==null)this._hand.dispatchEvent($);return this}connect($){if($&&$.hand){let U=this._hand;if(U)for(let J of $.hand.values())this._getHandJoint(U,J)}return this.dispatchEvent({type:"connected",data:$}),this}disconnect($){if(this.dispatchEvent({type:"disconnected",data:$}),this._targetRay!==null)this._targetRay.visible=!1;if(this._grip!==null)this._grip.visible=!1;if(this._hand!==null)this._hand.visible=!1;return this}update($,U,J){let Q=null,W=null,K=null,X=this._targetRay,N=this._grip,H=this._hand;if($&&U.session.visibilityState!=="visible-blurred"){if(H&&$.hand){K=!0;for(let D of $.hand.values()){let R=U.getJointPose(D,J),I=this._getHandJoint(H,D);if(R!==null)I.matrix.fromArray(R.transform.matrix),I.matrix.decompose(I.position,I.rotation,I.scale),I.matrixWorldNeedsUpdate=!0,I.jointRadius=R.radius;I.visible=R!==null}let Y=H.joints["index-finger-tip"],G=H.joints["thumb-tip"],O=Y.position.distanceTo(G.position),E=0.02,Z=0.005;if(H.inputState.pinching&&O>E+Z)H.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:$.handedness,target:this});else if(!H.inputState.pinching&&O<=E-Z)H.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:$.handedness,target:this})}else if(N!==null&&$.gripSpace){if(W=U.getPose($.gripSpace,J),W!==null){if(N.matrix.fromArray(W.transform.matrix),N.matrix.decompose(N.position,N.rotation,N.scale),N.matrixWorldNeedsUpdate=!0,W.linearVelocity)N.hasLinearVelocity=!0,N.linearVelocity.copy(W.linearVelocity);else N.hasLinearVelocity=!1;if(W.angularVelocity)N.hasAngularVelocity=!0,N.angularVelocity.copy(W.angularVelocity);else N.hasAngularVelocity=!1;if(N.eventsEnabled)N.dispatchEvent({type:"gripUpdated",data:$,target:this})}}if(X!==null){if(Q=U.getPose($.targetRaySpace,J),Q===null&&W!==null)Q=W;if(Q!==null){if(X.matrix.fromArray(Q.transform.matrix),X.matrix.decompose(X.position,X.rotation,X.scale),X.matrixWorldNeedsUpdate=!0,Q.linearVelocity)X.hasLinearVelocity=!0,X.linearVelocity.copy(Q.linearVelocity);else X.hasLinearVelocity=!1;if(Q.angularVelocity)X.hasAngularVelocity=!0,X.angularVelocity.copy(Q.angularVelocity);else X.hasAngularVelocity=!1;this.dispatchEvent(KV)}}}if(X!==null)X.visible=Q!==null;if(N!==null)N.visible=W!==null;if(H!==null)H.visible=K!==null;return this}_getHandJoint($,U){if($.joints[U.jointName]===void 0){let J=new YJ;J.matrixAutoUpdate=!1,J.visible=!1,$.joints[U.jointName]=J,$.add(J)}return $.joints[U.jointName]}}var jk={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},tJ={h:0,s:0,l:0},AK={h:0,s:0,l:0};function XO($,U,J){if(J<0)J+=1;if(J>1)J-=1;if(J<0.16666666666666666)return $+(U-$)*6*J;if(J<0.5)return U;if(J<0.6666666666666666)return $+(U-$)*6*(0.6666666666666666-J);return $}class x${constructor($,U,J){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set($,U,J)}set($,U,J){if(U===void 0&&J===void 0){let Q=$;if(Q&&Q.isColor)this.copy(Q);else if(typeof Q==="number")this.setHex(Q);else if(typeof Q==="string")this.setStyle(Q)}else this.setRGB($,U,J);return this}setScalar($){return this.r=$,this.g=$,this.b=$,this}setHex($,U="srgb"){return $=Math.floor($),this.r=($>>16&255)/255,this.g=($>>8&255)/255,this.b=($&255)/255,s$.colorSpaceToWorking(this,U),this}setRGB($,U,J,Q=s$.workingColorSpace){return this.r=$,this.g=U,this.b=J,s$.colorSpaceToWorking(this,Q),this}setHSL($,U,J,Q=s$.workingColorSpace){if($=_E($,1),U=t$(U,0,1),J=t$(J,0,1),U===0)this.r=this.g=this.b=J;else{let W=J<=0.5?J*(1+U):J+U-J*U,K=2*J-W;this.r=XO(K,W,$+0.3333333333333333),this.g=XO(K,W,$),this.b=XO(K,W,$-0.3333333333333333)}return s$.colorSpaceToWorking(this,Q),this}setStyle($,U="srgb"){function J(W){if(W===void 0)return;if(parseFloat(W)<1)A$("Color: Alpha component of "+$+" will be ignored.")}let Q;if(Q=/^(\w+)\(([^\)]*)\)/.exec($)){let W,K=Q[1],X=Q[2];switch(K){case"rgb":case"rgba":if(W=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(X))return J(W[4]),this.setRGB(Math.min(255,parseInt(W[1],10))/255,Math.min(255,parseInt(W[2],10))/255,Math.min(255,parseInt(W[3],10))/255,U);if(W=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(X))return J(W[4]),this.setRGB(Math.min(100,parseInt(W[1],10))/100,Math.min(100,parseInt(W[2],10))/100,Math.min(100,parseInt(W[3],10))/100,U);break;case"hsl":case"hsla":if(W=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(X))return J(W[4]),this.setHSL(parseFloat(W[1])/360,parseFloat(W[2])/100,parseFloat(W[3])/100,U);break;default:A$("Color: Unknown color model "+$)}}else if(Q=/^\#([A-Fa-f\d]+)$/.exec($)){let W=Q[1],K=W.length;if(K===3)return this.setRGB(parseInt(W.charAt(0),16)/15,parseInt(W.charAt(1),16)/15,parseInt(W.charAt(2),16)/15,U);else if(K===6)return this.setHex(parseInt(W,16),U);else A$("Color: Invalid hex color "+$)}else if($&&$.length>0)return this.setColorName($,U);return this}setColorName($,U="srgb"){let J=jk[$.toLowerCase()];if(J!==void 0)this.setHex(J,U);else A$("Color: Unknown color "+$);return this}clone(){return new this.constructor(this.r,this.g,this.b)}copy($){return this.r=$.r,this.g=$.g,this.b=$.b,this}copySRGBToLinear($){return this.r=vJ($.r),this.g=vJ($.g),this.b=vJ($.b),this}copyLinearToSRGB($){return this.r=cW($.r),this.g=cW($.g),this.b=cW($.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex($="srgb"){return s$.workingToColorSpace(UU.copy(this),$),Math.round(t$(UU.r*255,0,255))*65536+Math.round(t$(UU.g*255,0,255))*256+Math.round(t$(UU.b*255,0,255))}getHexString($="srgb"){return("000000"+this.getHex($).toString(16)).slice(-6)}getHSL($,U=s$.workingColorSpace){s$.workingToColorSpace(UU.copy(this),U);let{r:J,g:Q,b:W}=UU,K=Math.max(J,Q,W),X=Math.min(J,Q,W),N,H,Y=(X+K)/2;if(X===K)N=0,H=0;else{let G=K-X;switch(H=Y<=0.5?G/(K+X):G/(2-K-X),K){case J:N=(Q-W)/G+(Q<W?6:0);break;case Q:N=(W-J)/G+2;break;case W:N=(J-Q)/G+4;break}N/=6}return $.h=N,$.s=H,$.l=Y,$}getRGB($,U=s$.workingColorSpace){return s$.workingToColorSpace(UU.copy(this),U),$.r=UU.r,$.g=UU.g,$.b=UU.b,$}getStyle($="srgb"){s$.workingToColorSpace(UU.copy(this),$);let{r:U,g:J,b:Q}=UU;if($!=="srgb")return`color(${$} ${U.toFixed(3)} ${J.toFixed(3)} ${Q.toFixed(3)})`;return`rgb(${Math.round(U*255)},${Math.round(J*255)},${Math.round(Q*255)})`}offsetHSL($,U,J){return this.getHSL(tJ),this.setHSL(tJ.h+$,tJ.s+U,tJ.l+J)}add($){return this.r+=$.r,this.g+=$.g,this.b+=$.b,this}addColors($,U){return this.r=$.r+U.r,this.g=$.g+U.g,this.b=$.b+U.b,this}addScalar($){return this.r+=$,this.g+=$,this.b+=$,this}sub($){return this.r=Math.max(0,this.r-$.r),this.g=Math.max(0,this.g-$.g),this.b=Math.max(0,this.b-$.b),this}multiply($){return this.r*=$.r,this.g*=$.g,this.b*=$.b,this}multiplyScalar($){return this.r*=$,this.g*=$,this.b*=$,this}lerp($,U){return this.r+=($.r-this.r)*U,this.g+=($.g-this.g)*U,this.b+=($.b-this.b)*U,this}lerpColors($,U,J){return this.r=$.r+(U.r-$.r)*J,this.g=$.g+(U.g-$.g)*J,this.b=$.b+(U.b-$.b)*J,this}lerpHSL($,U){this.getHSL(tJ),$.getHSL(AK);let J=OQ(tJ.h,AK.h,U),Q=OQ(tJ.s,AK.s,U),W=OQ(tJ.l,AK.l,U);return this.setHSL(J,Q,W),this}setFromVector3($){return this.r=$.x,this.g=$.y,this.b=$.z,this}applyMatrix3($){let U=this.r,J=this.g,Q=this.b,W=$.elements;return this.r=W[0]*U+W[3]*J+W[6]*Q,this.g=W[1]*U+W[4]*J+W[7]*Q,this.b=W[2]*U+W[5]*J+W[8]*Q,this}equals($){return $.r===this.r&&$.g===this.g&&$.b===this.b}fromArray($,U=0){return this.r=$[U],this.g=$[U+1],this.b=$[U+2],this}toArray($=[],U=0){return $[U]=this.r,$[U+1]=this.g,$[U+2]=this.b,$}fromBufferAttribute($,U){return this.r=$.getX(U),this.g=$.getY(U),this.b=$.getZ(U),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}var UU=new x$;x$.NAMES=jk;class W8 extends k6{constructor(){super();if(this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new OJ,this.environmentIntensity=1,this.environmentRotation=new OJ,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy($,U){if(super.copy($,U),$.background!==null)this.background=$.background.clone();if($.environment!==null)this.environment=$.environment.clone();if($.fog!==null)this.fog=$.fog.clone();if(this.backgroundBlurriness=$.backgroundBlurriness,this.backgroundIntensity=$.backgroundIntensity,this.backgroundRotation.copy($.backgroundRotation),this.environmentIntensity=$.environmentIntensity,this.environmentRotation.copy($.environmentRotation),$.overrideMaterial!==null)this.overrideMaterial=$.overrideMaterial.clone();return this.matrixAutoUpdate=$.matrixAutoUpdate,this}toJSON($){let U=super.toJSON($);if(this.fog!==null)U.object.fog=this.fog.toJSON();if(this.backgroundBlurriness>0)U.object.backgroundBlurriness=this.backgroundBlurriness;if(this.backgroundIntensity!==1)U.object.backgroundIntensity=this.backgroundIntensity;if(U.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1)U.object.environmentIntensity=this.environmentIntensity;return U.object.environmentRotation=this.environmentRotation.toArray(),U}}var pU=new j,_J=new j,NO=new j,AJ=new j,bW=new j,xW=new j,OD=new j,HO=new j,YO=new j,GO=new j,OO=new Z6,EO=new Z6,ZO=new Z6;class gU{constructor($=new j,U=new j,J=new j){this.a=$,this.b=U,this.c=J}static getNormal($,U,J,Q){Q.subVectors(J,U),pU.subVectors($,U),Q.cross(pU);let W=Q.lengthSq();if(W>0)return Q.multiplyScalar(1/Math.sqrt(W));return Q.set(0,0,0)}static getBarycoord($,U,J,Q,W){pU.subVectors(Q,U),_J.subVectors(J,U),NO.subVectors($,U);let K=pU.dot(pU),X=pU.dot(_J),N=pU.dot(NO),H=_J.dot(_J),Y=_J.dot(NO),G=K*H-X*X;if(G===0)return W.set(0,0,0),null;let O=1/G,E=(H*N-X*Y)*O,Z=(K*Y-X*N)*O;return W.set(1-E-Z,Z,E)}static containsPoint($,U,J,Q){if(this.getBarycoord($,U,J,Q,AJ)===null)return!1;return AJ.x>=0&&AJ.y>=0&&AJ.x+AJ.y<=1}static getInterpolation($,U,J,Q,W,K,X,N){if(this.getBarycoord($,U,J,Q,AJ)===null){if(N.x=0,N.y=0,"z"in N)N.z=0;if("w"in N)N.w=0;return null}return N.setScalar(0),N.addScaledVector(W,AJ.x),N.addScaledVector(K,AJ.y),N.addScaledVector(X,AJ.z),N}static getInterpolatedAttribute($,U,J,Q,W,K){return OO.setScalar(0),EO.setScalar(0),ZO.setScalar(0),OO.fromBufferAttribute($,U),EO.fromBufferAttribute($,J),ZO.fromBufferAttribute($,Q),K.setScalar(0),K.addScaledVector(OO,W.x),K.addScaledVector(EO,W.y),K.addScaledVector(ZO,W.z),K}static isFrontFacing($,U,J,Q){return pU.subVectors(J,U),_J.subVectors($,U),pU.cross(_J).dot(Q)<0}set($,U,J){return this.a.copy($),this.b.copy(U),this.c.copy(J),this}setFromPointsAndIndices($,U,J,Q){return this.a.copy($[U]),this.b.copy($[J]),this.c.copy($[Q]),this}setFromAttributeAndIndices($,U,J,Q){return this.a.fromBufferAttribute($,U),this.b.fromBufferAttribute($,J),this.c.fromBufferAttribute($,Q),this}clone(){return new this.constructor().copy(this)}copy($){return this.a.copy($.a),this.b.copy($.b),this.c.copy($.c),this}getArea(){return pU.subVectors(this.c,this.b),_J.subVectors(this.a,this.b),pU.cross(_J).length()*0.5}getMidpoint($){return $.addVectors(this.a,this.b).add(this.c).multiplyScalar(0.3333333333333333)}getNormal($){return gU.getNormal(this.a,this.b,this.c,$)}getPlane($){return $.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord($,U){return gU.getBarycoord($,this.a,this.b,this.c,U)}getInterpolation($,U,J,Q,W){return gU.getInterpolation($,this.a,this.b,this.c,U,J,Q,W)}containsPoint($){return gU.containsPoint($,this.a,this.b,this.c)}isFrontFacing($){return gU.isFrontFacing(this.a,this.b,this.c,$)}intersectsBox($){return $.intersectsTriangle(this)}closestPointToPoint($,U){let J=this.a,Q=this.b,W=this.c,K,X;bW.subVectors(Q,J),xW.subVectors(W,J),HO.subVectors($,J);let N=bW.dot(HO),H=xW.dot(HO);if(N<=0&&H<=0)return U.copy(J);YO.subVectors($,Q);let Y=bW.dot(YO),G=xW.dot(YO);if(Y>=0&&G<=Y)return U.copy(Q);let O=N*G-Y*H;if(O<=0&&N>=0&&Y<=0)return K=N/(N-Y),U.copy(J).addScaledVector(bW,K);GO.subVectors($,W);let E=bW.dot(GO),Z=xW.dot(GO);if(Z>=0&&E<=Z)return U.copy(W);let D=E*H-N*Z;if(D<=0&&H>=0&&Z<=0)return X=H/(H-Z),U.copy(J).addScaledVector(xW,X);let R=Y*Z-E*G;if(R<=0&&G-Y>=0&&E-Z>=0)return OD.subVectors(W,Q),X=(G-Y)/(G-Y+(E-Z)),U.copy(Q).addScaledVector(OD,X);let I=1/(R+D+O);return K=D*I,X=O*I,U.copy(J).addScaledVector(bW,K).addScaledVector(xW,X)}equals($){return $.a.equals(this.a)&&$.b.equals(this.b)&&$.c.equals(this.c)}}class GU{constructor($=new j(1/0,1/0,1/0),U=new j(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=$,this.max=U}set($,U){return this.min.copy($),this.max.copy(U),this}setFromArray($){this.makeEmpty();for(let U=0,J=$.length;U<J;U+=3)this.expandByPoint(dU.fromArray($,U));return this}setFromBufferAttribute($){this.makeEmpty();for(let U=0,J=$.count;U<J;U++)this.expandByPoint(dU.fromBufferAttribute($,U));return this}setFromPoints($){this.makeEmpty();for(let U=0,J=$.length;U<J;U++)this.expandByPoint($[U]);return this}setFromCenterAndSize($,U){let J=dU.copy(U).multiplyScalar(0.5);return this.min.copy($).sub(J),this.max.copy($).add(J),this}setFromObject($,U=!1){return this.makeEmpty(),this.expandByObject($,U)}clone(){return new this.constructor().copy(this)}copy($){return this.min.copy($.min),this.max.copy($.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($){return this.isEmpty()?$.set(0,0,0):$.addVectors(this.min,this.max).multiplyScalar(0.5)}getSize($){return this.isEmpty()?$.set(0,0,0):$.subVectors(this.max,this.min)}expandByPoint($){return this.min.min($),this.max.max($),this}expandByVector($){return this.min.sub($),this.max.add($),this}expandByScalar($){return this.min.addScalar(-$),this.max.addScalar($),this}expandByObject($,U=!1){$.updateWorldMatrix(!1,!1);let J=$.geometry;if(J!==void 0){let W=J.getAttribute("position");if(U===!0&&W!==void 0&&$.isInstancedMesh!==!0)for(let K=0,X=W.count;K<X;K++){if($.isMesh===!0)$.getVertexPosition(K,dU);else dU.fromBufferAttribute(W,K);dU.applyMatrix4($.matrixWorld),this.expandByPoint(dU)}else{if($.boundingBox!==void 0){if($.boundingBox===null)$.computeBoundingBox();CK.copy($.boundingBox)}else{if(J.boundingBox===null)J.computeBoundingBox();CK.copy(J.boundingBox)}CK.applyMatrix4($.matrixWorld),this.union(CK)}}let Q=$.children;for(let W=0,K=Q.length;W<K;W++)this.expandByObject(Q[W],U);return this}containsPoint($){return $.x>=this.min.x&&$.x<=this.max.x&&$.y>=this.min.y&&$.y<=this.max.y&&$.z>=this.min.z&&$.z<=this.max.z}containsBox($){return this.min.x<=$.min.x&&$.max.x<=this.max.x&&this.min.y<=$.min.y&&$.max.y<=this.max.y&&this.min.z<=$.min.z&&$.max.z<=this.max.z}getParameter($,U){return U.set(($.x-this.min.x)/(this.max.x-this.min.x),($.y-this.min.y)/(this.max.y-this.min.y),($.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox($){return $.max.x>=this.min.x&&$.min.x<=this.max.x&&$.max.y>=this.min.y&&$.min.y<=this.max.y&&$.max.z>=this.min.z&&$.min.z<=this.max.z}intersectsSphere($){return this.clampPoint($.center,dU),dU.distanceToSquared($.center)<=$.radius*$.radius}intersectsPlane($){let U,J;if($.normal.x>0)U=$.normal.x*this.min.x,J=$.normal.x*this.max.x;else U=$.normal.x*this.max.x,J=$.normal.x*this.min.x;if($.normal.y>0)U+=$.normal.y*this.min.y,J+=$.normal.y*this.max.y;else U+=$.normal.y*this.max.y,J+=$.normal.y*this.min.y;if($.normal.z>0)U+=$.normal.z*this.min.z,J+=$.normal.z*this.max.z;else U+=$.normal.z*this.max.z,J+=$.normal.z*this.min.z;return U<=-$.constant&&J>=-$.constant}intersectsTriangle($){if(this.isEmpty())return!1;this.getCenter(WQ),SK.subVectors(this.max,WQ),yW.subVectors($.a,WQ),hW.subVectors($.b,WQ),fW.subVectors($.c,WQ),eJ.subVectors(hW,yW),$0.subVectors(fW,hW),T0.subVectors(yW,fW);let U=[0,-eJ.z,eJ.y,0,-$0.z,$0.y,0,-T0.z,T0.y,eJ.z,0,-eJ.x,$0.z,0,-$0.x,T0.z,0,-T0.x,-eJ.y,eJ.x,0,-$0.y,$0.x,0,-T0.y,T0.x,0];if(!IO(U,yW,hW,fW,SK))return!1;if(U=[1,0,0,0,1,0,0,0,1],!IO(U,yW,hW,fW,SK))return!1;return TK.crossVectors(eJ,$0),U=[TK.x,TK.y,TK.z],IO(U,yW,hW,fW,SK)}clampPoint($,U){return U.copy($).clamp(this.min,this.max)}distanceToPoint($){return this.clampPoint($,dU).distanceTo($)}getBoundingSphere($){if(this.isEmpty())$.makeEmpty();else this.getCenter($.center),$.radius=this.getSize(dU).length()*0.5;return $}intersect($){if(this.min.max($.min),this.max.min($.max),this.isEmpty())this.makeEmpty();return this}union($){return this.min.min($.min),this.max.max($.max),this}applyMatrix4($){if(this.isEmpty())return this;return CJ[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4($),CJ[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4($),CJ[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4($),CJ[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4($),CJ[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4($),CJ[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4($),CJ[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4($),CJ[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4($),this.setFromPoints(CJ),this}translate($){return this.min.add($),this.max.add($),this}equals($){return $.min.equals(this.min)&&$.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON($){return this.min.fromArray($.min),this.max.fromArray($.max),this}}var CJ=[new j,new j,new j,new j,new j,new j,new j,new j],dU=new j,CK=new GU,yW=new j,hW=new j,fW=new j,eJ=new j,$0=new j,T0=new j,WQ=new j,SK=new j,TK=new j,v0=new j;function IO($,U,J,Q,W){for(let K=0,X=$.length-3;K<=X;K+=3){v0.fromArray($,K);let N=W.x*Math.abs(v0.x)+W.y*Math.abs(v0.y)+W.z*Math.abs(v0.z),H=U.dot(v0),Y=J.dot(v0),G=Q.dot(v0);if(Math.max(-Math.max(H,Y,G),Math.min(H,Y,G))>N)return!1}return!0}var y6=new j,vK=new g$,XV=0;class u6 extends sU{constructor($,U,J=!1){super();if(Array.isArray($))throw TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:XV++}),this.name="",this.array=$,this.itemSize=U,this.count=$!==void 0?$.length/U:0,this.normalized=J,this.usage=35044,this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate($){if($===!0)this.version++}setUsage($){return this.usage=$,this}addUpdateRange($,U){this.updateRanges.push({start:$,count:U})}clearUpdateRanges(){this.updateRanges.length=0}copy($){return this.name=$.name,this.array=new $.array.constructor($.array),this.itemSize=$.itemSize,this.count=$.count,this.normalized=$.normalized,this.usage=$.usage,this.gpuType=$.gpuType,this}copyAt($,U,J){$*=this.itemSize,J*=U.itemSize;for(let Q=0,W=this.itemSize;Q<W;Q++)this.array[$+Q]=U.array[J+Q];return this}copyArray($){return this.array.set($),this}applyMatrix3($){if(this.itemSize===2)for(let U=0,J=this.count;U<J;U++)vK.fromBufferAttribute(this,U),vK.applyMatrix3($),this.setXY(U,vK.x,vK.y);else if(this.itemSize===3)for(let U=0,J=this.count;U<J;U++)y6.fromBufferAttribute(this,U),y6.applyMatrix3($),this.setXYZ(U,y6.x,y6.y,y6.z);return this}applyMatrix4($){for(let U=0,J=this.count;U<J;U++)y6.fromBufferAttribute(this,U),y6.applyMatrix4($),this.setXYZ(U,y6.x,y6.y,y6.z);return this}applyNormalMatrix($){for(let U=0,J=this.count;U<J;U++)y6.fromBufferAttribute(this,U),y6.applyNormalMatrix($),this.setXYZ(U,y6.x,y6.y,y6.z);return this}transformDirection($){for(let U=0,J=this.count;U<J;U++)y6.fromBufferAttribute(this,U),y6.transformDirection($),this.setXYZ(U,y6.x,y6.y,y6.z);return this}set($,U=0){return this.array.set($,U),this}getComponent($,U){let J=this.array[$*this.itemSize+U];if(this.normalized)J=nU(J,this.array);return J}setComponent($,U,J){if(this.normalized)J=E6(J,this.array);return this.array[$*this.itemSize+U]=J,this}getX($){let U=this.array[$*this.itemSize];if(this.normalized)U=nU(U,this.array);return U}setX($,U){if(this.normalized)U=E6(U,this.array);return this.array[$*this.itemSize]=U,this}getY($){let U=this.array[$*this.itemSize+1];if(this.normalized)U=nU(U,this.array);return U}setY($,U){if(this.normalized)U=E6(U,this.array);return this.array[$*this.itemSize+1]=U,this}getZ($){let U=this.array[$*this.itemSize+2];if(this.normalized)U=nU(U,this.array);return U}setZ($,U){if(this.normalized)U=E6(U,this.array);return this.array[$*this.itemSize+2]=U,this}getW($){let U=this.array[$*this.itemSize+3];if(this.normalized)U=nU(U,this.array);return U}setW($,U){if(this.normalized)U=E6(U,this.array);return this.array[$*this.itemSize+3]=U,this}setXY($,U,J){if($*=this.itemSize,this.normalized)U=E6(U,this.array),J=E6(J,this.array);return this.array[$+0]=U,this.array[$+1]=J,this}setXYZ($,U,J,Q){if($*=this.itemSize,this.normalized)U=E6(U,this.array),J=E6(J,this.array),Q=E6(Q,this.array);return this.array[$+0]=U,this.array[$+1]=J,this.array[$+2]=Q,this}setXYZW($,U,J,Q,W){if($*=this.itemSize,this.normalized)U=E6(U,this.array),J=E6(J,this.array),Q=E6(Q,this.array),W=E6(W,this.array);return this.array[$+0]=U,this.array[$+1]=J,this.array[$+2]=Q,this.array[$+3]=W,this}onUpload($){return this.onUploadCallback=$,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let $={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};if(this.name!=="")$.name=this.name;if(this.usage!==35044)$.usage=this.usage;return $}dispose(){this.dispatchEvent({type:"dispose"})}}class q7 extends u6{constructor($,U,J){super(new Uint16Array($),U,J)}}class D7 extends u6{constructor($,U,J){super(new Uint32Array($),U,J)}}class qU extends u6{constructor($,U,J){super(new Float32Array($),U,J)}}var NV=new GU,QQ=new j,qO=new j;class PU{constructor($=new j,U=-1){this.isSphere=!0,this.center=$,this.radius=U}set($,U){return this.center.copy($),this.radius=U,this}setFromPoints($,U){let J=this.center;if(U!==void 0)J.copy(U);else NV.setFromPoints($).getCenter(J);let Q=0;for(let W=0,K=$.length;W<K;W++)Q=Math.max(Q,J.distanceToSquared($[W]));return this.radius=Math.sqrt(Q),this}copy($){return this.center.copy($.center),this.radius=$.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint($){return $.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint($){return $.distanceTo(this.center)-this.radius}intersectsSphere($){let U=this.radius+$.radius;return $.center.distanceToSquared(this.center)<=U*U}intersectsBox($){return $.intersectsSphere(this)}intersectsPlane($){return Math.abs($.distanceToPoint(this.center))<=this.radius}clampPoint($,U){let J=this.center.distanceToSquared($);if(U.copy($),J>this.radius*this.radius)U.sub(this.center).normalize(),U.multiplyScalar(this.radius).add(this.center);return U}getBoundingBox($){if(this.isEmpty())return $.makeEmpty(),$;return $.set(this.center,this.center),$.expandByScalar(this.radius),$}applyMatrix4($){return this.center.applyMatrix4($),this.radius=this.radius*$.getMaxScaleOnAxis(),this}translate($){return this.center.add($),this}expandByPoint($){if(this.isEmpty())return this.center.copy($),this.radius=0,this;QQ.subVectors($,this.center);let U=QQ.lengthSq();if(U>this.radius*this.radius){let J=Math.sqrt(U),Q=(J-this.radius)*0.5;this.center.addScaledVector(QQ,Q/J),this.radius+=Q}return this}union($){if($.isEmpty())return this;if(this.isEmpty())return this.copy($),this;if(this.center.equals($.center)===!0)this.radius=Math.max(this.radius,$.radius);else qO.subVectors($.center,this.center).setLength($.radius),this.expandByPoint(QQ.copy($.center).add(qO)),this.expandByPoint(QQ.copy($.center).sub(qO));return this}equals($){return $.center.equals(this.center)&&$.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON($){return this.radius=$.radius,this.center.fromArray($.center),this}}var HV=0,jU=new p$,DO=new k6,uW=new j,MU=new GU,KQ=new GU,n6=new j;class OU extends sU{constructor(){super();this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:HV++}),this.uuid=iU(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex($){if(Array.isArray($))this.index=new((vR($))?D7:q7)($,1);else this.index=$;return this}setIndirect($,U=0){return this.indirect=$,this.indirectOffset=U,this}getIndirect(){return this.indirect}getAttribute($){return this.attributes[$]}setAttribute($,U){return this.attributes[$]=U,this}deleteAttribute($){return delete this.attributes[$],this}hasAttribute($){return this.attributes[$]!==void 0}addGroup($,U,J=0){this.groups.push({start:$,count:U,materialIndex:J})}clearGroups(){this.groups=[]}setDrawRange($,U){this.drawRange.start=$,this.drawRange.count=U}applyMatrix4($){let U=this.attributes.position;if(U!==void 0)U.applyMatrix4($),U.needsUpdate=!0;let J=this.attributes.normal;if(J!==void 0){let W=new u$().getNormalMatrix($);J.applyNormalMatrix(W),J.needsUpdate=!0}let Q=this.attributes.tangent;if(Q!==void 0)Q.transformDirection($),Q.needsUpdate=!0;if(this.boundingBox!==null)this.computeBoundingBox();if(this.boundingSphere!==null)this.computeBoundingSphere();return this._transformed=!0,this}applyQuaternion($){return jU.makeRotationFromQuaternion($),this.applyMatrix4(jU),this}rotateX($){return jU.makeRotationX($),this.applyMatrix4(jU),this}rotateY($){return jU.makeRotationY($),this.applyMatrix4(jU),this}rotateZ($){return jU.makeRotationZ($),this.applyMatrix4(jU),this}translate($,U,J){return jU.makeTranslation($,U,J),this.applyMatrix4(jU),this}scale($,U,J){return jU.makeScale($,U,J),this.applyMatrix4(jU),this}lookAt($){return DO.lookAt($),DO.updateMatrix(),this.applyMatrix4(DO.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(uW).negate(),this.translate(uW.x,uW.y,uW.z),this}setFromPoints($){let U=this.getAttribute("position");if(U===void 0){let J=[];for(let Q=0,W=$.length;Q<W;Q++){let K=$[Q];J.push(K.x,K.y,K.z||0)}this.setAttribute("position",new qU(J,3))}else{let J=Math.min($.length,U.count);for(let Q=0;Q<J;Q++){let W=$[Q];U.setXYZ(Q,W.x,W.y,W.z||0)}if($.length>U.count)A$("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.");U.needsUpdate=!0}return this}computeBoundingBox(){if(this.boundingBox===null)this.boundingBox=new GU;let $=this.attributes.position,U=this.morphAttributes.position;if($&&$.isGLBufferAttribute){y$("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new j(-1/0,-1/0,-1/0),new j(1/0,1/0,1/0));return}if($!==void 0){if(this.boundingBox.setFromBufferAttribute($),U)for(let J=0,Q=U.length;J<Q;J++){let W=U[J];if(MU.setFromBufferAttribute(W),this.morphTargetsRelative)n6.addVectors(this.boundingBox.min,MU.min),this.boundingBox.expandByPoint(n6),n6.addVectors(this.boundingBox.max,MU.max),this.boundingBox.expandByPoint(n6);else this.boundingBox.expandByPoint(MU.min),this.boundingBox.expandByPoint(MU.max)}}else this.boundingBox.makeEmpty();if(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))y$('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){if(this.boundingSphere===null)this.boundingSphere=new PU;let $=this.attributes.position,U=this.morphAttributes.position;if($&&$.isGLBufferAttribute){y$("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new j,1/0);return}if($){let J=this.boundingSphere.center;if(MU.setFromBufferAttribute($),U)for(let W=0,K=U.length;W<K;W++){let X=U[W];if(KQ.setFromBufferAttribute(X),this.morphTargetsRelative)n6.addVectors(MU.min,KQ.min),MU.expandByPoint(n6),n6.addVectors(MU.max,KQ.max),MU.expandByPoint(n6);else MU.expandByPoint(KQ.min),MU.expandByPoint(KQ.max)}MU.getCenter(J);let Q=0;for(let W=0,K=$.count;W<K;W++)n6.fromBufferAttribute($,W),Q=Math.max(Q,J.distanceToSquared(n6));if(U)for(let W=0,K=U.length;W<K;W++){let X=U[W],N=this.morphTargetsRelative;for(let H=0,Y=X.count;H<Y;H++){if(n6.fromBufferAttribute(X,H),N)uW.fromBufferAttribute($,H),n6.add(uW);Q=Math.max(Q,J.distanceToSquared(n6))}}if(this.boundingSphere.radius=Math.sqrt(Q),isNaN(this.boundingSphere.radius))y$('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){let $=this.index,U=this.attributes;if($===null||U.position===void 0||U.normal===void 0||U.uv===void 0){y$("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let{position:J,normal:Q,uv:W}=U,K=this.getAttribute("tangent");if(K===void 0||K.count!==J.count)K=new u6(new Float32Array(4*J.count),4),this.setAttribute("tangent",K);let X=[],N=[];for(let A=0;A<J.count;A++)X[A]=new j,N[A]=new j;let H=new j,Y=new j,G=new j,O=new g$,E=new g$,Z=new g$,D=new j,R=new j;function I(A,k,w){H.fromBufferAttribute(J,A),Y.fromBufferAttribute(J,k),G.fromBufferAttribute(J,w),O.fromBufferAttribute(W,A),E.fromBufferAttribute(W,k),Z.fromBufferAttribute(W,w),Y.sub(H),G.sub(H),E.sub(O),Z.sub(O);let h=1/(E.x*Z.y-Z.x*E.y);if(!isFinite(h))return;D.copy(Y).multiplyScalar(Z.y).addScaledVector(G,-E.y).multiplyScalar(h),R.copy(G).multiplyScalar(E.x).addScaledVector(Y,-Z.x).multiplyScalar(h),X[A].add(D),X[k].add(D),X[w].add(D),N[A].add(R),N[k].add(R),N[w].add(R)}let q=this.groups;if(q.length===0)q=[{start:0,count:$.count}];for(let A=0,k=q.length;A<k;++A){let w=q[A],h=w.start,C=w.count;for(let f=h,s=h+C;f<s;f+=3)I($.getX(f+0),$.getX(f+1),$.getX(f+2))}let _=new j,P=new j,L=new j,B=new j;function z(A){L.fromBufferAttribute(Q,A),B.copy(L);let k=X[A];_.copy(k),_.sub(L.multiplyScalar(L.dot(k))).normalize(),P.crossVectors(B,k);let h=P.dot(N[A])<0?-1:1;K.setXYZW(A,_.x,_.y,_.z,h)}for(let A=0,k=q.length;A<k;++A){let w=q[A],h=w.start,C=w.count;for(let f=h,s=h+C;f<s;f+=3)z($.getX(f+0)),z($.getX(f+1)),z($.getX(f+2))}this._transformed=!0}computeVertexNormals(){let $=this.index,U=this.getAttribute("position");if(U!==void 0){let J=this.getAttribute("normal");if(J===void 0||J.count!==U.count)J=new u6(new Float32Array(U.count*3),3),this.setAttribute("normal",J);else for(let O=0,E=J.count;O<E;O++)J.setXYZ(O,0,0,0);let Q=new j,W=new j,K=new j,X=new j,N=new j,H=new j,Y=new j,G=new j;if($)for(let O=0,E=$.count;O<E;O+=3){let Z=$.getX(O+0),D=$.getX(O+1),R=$.getX(O+2);Q.fromBufferAttribute(U,Z),W.fromBufferAttribute(U,D),K.fromBufferAttribute(U,R),Y.subVectors(K,W),G.subVectors(Q,W),Y.cross(G),X.fromBufferAttribute(J,Z),N.fromBufferAttribute(J,D),H.fromBufferAttribute(J,R),X.add(Y),N.add(Y),H.add(Y),J.setXYZ(Z,X.x,X.y,X.z),J.setXYZ(D,N.x,N.y,N.z),J.setXYZ(R,H.x,H.y,H.z)}else for(let O=0,E=U.count;O<E;O+=3)Q.fromBufferAttribute(U,O+0),W.fromBufferAttribute(U,O+1),K.fromBufferAttribute(U,O+2),Y.subVectors(K,W),G.subVectors(Q,W),Y.cross(G),J.setXYZ(O+0,Y.x,Y.y,Y.z),J.setXYZ(O+1,Y.x,Y.y,Y.z),J.setXYZ(O+2,Y.x,Y.y,Y.z);this.normalizeNormals(),J.needsUpdate=!0}}normalizeNormals(){let $=this.attributes.normal;for(let U=0,J=$.count;U<J;U++)n6.fromBufferAttribute($,U),n6.normalize(),$.setXYZ(U,n6.x,n6.y,n6.z)}toNonIndexed(){function $(X,N){let{array:H,itemSize:Y,normalized:G}=X,O=new H.constructor(N.length*Y),E=0,Z=0;for(let D=0,R=N.length;D<R;D++){if(X.isInterleavedBufferAttribute)E=N[D]*X.data.stride+X.offset;else E=N[D]*Y;for(let I=0;I<Y;I++)O[Z++]=H[E++]}return new u6(O,Y,G)}if(this.index===null)return A$("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let U=new OU,J=this.index.array,Q=this.attributes;for(let X in Q){let N=Q[X],H=$(N,J);U.setAttribute(X,H)}let W=this.morphAttributes;for(let X in W){let N=[],H=W[X];for(let Y=0,G=H.length;Y<G;Y++){let O=H[Y],E=$(O,J);N.push(E)}U.morphAttributes[X]=N}U.morphTargetsRelative=this.morphTargetsRelative;let K=this.groups;for(let X=0,N=K.length;X<N;X++){let H=K[X];U.addGroup(H.start,H.count,H.materialIndex)}return U}toJSON(){let $={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if($.uuid=this.uuid,$.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!=="")$.name=this.name;if(Object.keys(this.userData).length>0)$.userData=this.userData;if(this.parameters!==void 0&&this._transformed!==!0){let N=this.parameters;for(let H in N)if(N[H]!==void 0)$[H]=N[H];return $}$.data={attributes:{}};let U=this.index;if(U!==null)$.data.index={type:U.array.constructor.name,array:Array.prototype.slice.call(U.array)};let J=this.attributes;for(let N in J){let H=J[N];$.data.attributes[N]=H.toJSON($.data)}let Q={},W=!1;for(let N in this.morphAttributes){let H=this.morphAttributes[N],Y=[];for(let G=0,O=H.length;G<O;G++){let E=H[G];Y.push(E.toJSON($.data))}if(Y.length>0)Q[N]=Y,W=!0}if(W)$.data.morphAttributes=Q,$.data.morphTargetsRelative=this.morphTargetsRelative;let K=this.groups;if(K.length>0)$.data.groups=JSON.parse(JSON.stringify(K));let X=this.boundingSphere;if(X!==null)$.data.boundingSphere=X.toJSON();return $}clone(){return new this.constructor().copy(this)}copy($){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let U={};this.name=$.name;let J=$.index;if(J!==null)this.setIndex(J.clone());let Q=$.attributes;for(let H in Q){let Y=Q[H];this.setAttribute(H,Y.clone(U))}let W=$.morphAttributes;for(let H in W){let Y=[],G=W[H];for(let O=0,E=G.length;O<E;O++)Y.push(G[O].clone(U));this.morphAttributes[H]=Y}this.morphTargetsRelative=$.morphTargetsRelative;let K=$.groups;for(let H=0,Y=K.length;H<Y;H++){let G=K[H];this.addGroup(G.start,G.count,G.materialIndex)}let X=$.boundingBox;if(X!==null)this.boundingBox=X.clone();let N=$.boundingSphere;if(N!==null)this.boundingSphere=N.clone();return this.drawRange.start=$.drawRange.start,this.drawRange.count=$.drawRange.count,this.userData=$.userData,this._transformed=$._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class wQ{constructor($,U){this.isInterleavedBuffer=!0,this.array=$,this.stride=U,this.count=$!==void 0?$.length/U:0,this.usage=35044,this.updateRanges=[],this.version=0,this.uuid=iU()}onUploadCallback(){}set needsUpdate($){if($===!0)this.version++}setUsage($){return this.usage=$,this}addUpdateRange($,U){this.updateRanges.push({start:$,count:U})}clearUpdateRanges(){this.updateRanges.length=0}copy($){return this.array=new $.array.constructor($.array),this.count=$.count,this.stride=$.stride,this.usage=$.usage,this}copyAt($,U,J){$*=this.stride,J*=U.stride;for(let Q=0,W=this.stride;Q<W;Q++)this.array[$+Q]=U.array[J+Q];return this}set($,U=0){return this.array.set($,U),this}clone($){if($.arrayBuffers===void 0)$.arrayBuffers={};if(this.array.buffer._uuid===void 0)this.array.buffer._uuid=iU();if($.arrayBuffers[this.array.buffer._uuid]===void 0)$.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer;let U=new this.array.constructor($.arrayBuffers[this.array.buffer._uuid]),J=new this.constructor(U,this.stride);return J.setUsage(this.usage),J}onUpload($){return this.onUploadCallback=$,this}toJSON($){if($.arrayBuffers===void 0)$.arrayBuffers={};if(this.array.buffer._uuid===void 0)this.array.buffer._uuid=iU();if($.arrayBuffers[this.array.buffer._uuid]===void 0)$.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer));return{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}var YU=new j;class Q8{constructor($,U,J,Q=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=$,this.itemSize=U,this.offset=J,this.normalized=Q}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate($){this.data.needsUpdate=$}applyMatrix4($){for(let U=0,J=this.data.count;U<J;U++)YU.fromBufferAttribute(this,U),YU.applyMatrix4($),this.setXYZ(U,YU.x,YU.y,YU.z);return this}applyNormalMatrix($){for(let U=0,J=this.count;U<J;U++)YU.fromBufferAttribute(this,U),YU.applyNormalMatrix($),this.setXYZ(U,YU.x,YU.y,YU.z);return this}transformDirection($){for(let U=0,J=this.count;U<J;U++)YU.fromBufferAttribute(this,U),YU.transformDirection($),this.setXYZ(U,YU.x,YU.y,YU.z);return this}getComponent($,U){let J=this.array[$*this.data.stride+this.offset+U];if(this.normalized)J=nU(J,this.array);return J}setComponent($,U,J){if(this.normalized)J=E6(J,this.array);return this.data.array[$*this.data.stride+this.offset+U]=J,this}setX($,U){if(this.normalized)U=E6(U,this.array);return this.data.array[$*this.data.stride+this.offset]=U,this}setY($,U){if(this.normalized)U=E6(U,this.array);return this.data.array[$*this.data.stride+this.offset+1]=U,this}setZ($,U){if(this.normalized)U=E6(U,this.array);return this.data.array[$*this.data.stride+this.offset+2]=U,this}setW($,U){if(this.normalized)U=E6(U,this.array);return this.data.array[$*this.data.stride+this.offset+3]=U,this}getX($){let U=this.data.array[$*this.data.stride+this.offset];if(this.normalized)U=nU(U,this.array);return U}getY($){let U=this.data.array[$*this.data.stride+this.offset+1];if(this.normalized)U=nU(U,this.array);return U}getZ($){let U=this.data.array[$*this.data.stride+this.offset+2];if(this.normalized)U=nU(U,this.array);return U}getW($){let U=this.data.array[$*this.data.stride+this.offset+3];if(this.normalized)U=nU(U,this.array);return U}setXY($,U,J){if($=$*this.data.stride+this.offset,this.normalized)U=E6(U,this.array),J=E6(J,this.array);return this.data.array[$+0]=U,this.data.array[$+1]=J,this}setXYZ($,U,J,Q){if($=$*this.data.stride+this.offset,this.normalized)U=E6(U,this.array),J=E6(J,this.array),Q=E6(Q,this.array);return this.data.array[$+0]=U,this.data.array[$+1]=J,this.data.array[$+2]=Q,this}setXYZW($,U,J,Q,W){if($=$*this.data.stride+this.offset,this.normalized)U=E6(U,this.array),J=E6(J,this.array),Q=E6(Q,this.array),W=E6(W,this.array);return this.data.array[$+0]=U,this.data.array[$+1]=J,this.data.array[$+2]=Q,this.data.array[$+3]=W,this}clone($){if($===void 0){EQ("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");let U=[];for(let J=0;J<this.count;J++){let Q=J*this.data.stride+this.offset;for(let W=0;W<this.itemSize;W++)U.push(this.data.array[Q+W])}return new u6(new this.array.constructor(U),this.itemSize,this.normalized)}else{if($.interleavedBuffers===void 0)$.interleavedBuffers={};if($.interleavedBuffers[this.data.uuid]===void 0)$.interleavedBuffers[this.data.uuid]=this.data.clone($);return new Q8($.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}}toJSON($){if($===void 0){EQ("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");let U=[];for(let J=0;J<this.count;J++){let Q=J*this.data.stride+this.offset;for(let W=0;W<this.itemSize;W++)U.push(this.data.array[Q+W])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:U,normalized:this.normalized}}else{if($.interleavedBuffers===void 0)$.interleavedBuffers={};if($.interleavedBuffers[this.data.uuid]===void 0)$.interleavedBuffers[this.data.uuid]=this.data.toJSON($);return{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}}var YV=0;class DU extends sU{constructor(){super();this.isMaterial=!0,Object.defineProperty(this,"id",{value:YV++}),this.uuid=iU(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new x$(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=7680,this.stencilZFail=7680,this.stencilZPass=7680,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($){if(this._alphaTest>0!==$>0)this.version++;this._alphaTest=$}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues($){if($===void 0)return;for(let U in $){let J=$[U];if(J===void 0){A$(`Material: parameter '${U}' has value of undefined.`);continue}let Q=this[U];if(Q===void 0){A$(`Material: '${U}' is not a property of THREE.${this.type}.`);continue}if(Q&&Q.isColor)Q.set(J);else if(Q&&Q.isVector2&&(J&&J.isVector2)||Q&&Q.isEuler&&(J&&J.isEuler)||Q&&Q.isVector3&&(J&&J.isVector3))Q.copy(J);else this[U]=J}}toJSON($){let U=$===void 0||typeof $==="string";if(U)$={textures:{},images:{}};let J={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};if(J.uuid=this.uuid,J.type=this.type,this.name!=="")J.name=this.name;if(this.color&&this.color.isColor)J.color=this.color.getHex();if(this.roughness!==void 0)J.roughness=this.roughness;if(this.metalness!==void 0)J.metalness=this.metalness;if(this.sheen!==void 0)J.sheen=this.sheen;if(this.sheenColor&&this.sheenColor.isColor)J.sheenColor=this.sheenColor.getHex();if(this.sheenRoughness!==void 0)J.sheenRoughness=this.sheenRoughness;if(this.emissive&&this.emissive.isColor)J.emissive=this.emissive.getHex();if(this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1)J.emissiveIntensity=this.emissiveIntensity;if(this.specular&&this.specular.isColor)J.specular=this.specular.getHex();if(this.specularIntensity!==void 0)J.specularIntensity=this.specularIntensity;if(this.specularColor&&this.specularColor.isColor)J.specularColor=this.specularColor.getHex();if(this.shininess!==void 0)J.shininess=this.shininess;if(this.clearcoat!==void 0)J.clearcoat=this.clearcoat;if(this.clearcoatRoughness!==void 0)J.clearcoatRoughness=this.clearcoatRoughness;if(this.clearcoatMap&&this.clearcoatMap.isTexture)J.clearcoatMap=this.clearcoatMap.toJSON($).uuid;if(this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture)J.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON($).uuid;if(this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture)J.clearcoatNormalMap=this.clearcoatNormalMap.toJSON($).uuid,J.clearcoatNormalScale=this.clearcoatNormalScale.toArray();if(this.sheenColorMap&&this.sheenColorMap.isTexture)J.sheenColorMap=this.sheenColorMap.toJSON($).uuid;if(this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture)J.sheenRoughnessMap=this.sheenRoughnessMap.toJSON($).uuid;if(this.dispersion!==void 0)J.dispersion=this.dispersion;if(this.iridescence!==void 0)J.iridescence=this.iridescence;if(this.iridescenceIOR!==void 0)J.iridescenceIOR=this.iridescenceIOR;if(this.iridescenceThicknessRange!==void 0)J.iridescenceThicknessRange=this.iridescenceThicknessRange;if(this.iridescenceMap&&this.iridescenceMap.isTexture)J.iridescenceMap=this.iridescenceMap.toJSON($).uuid;if(this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture)J.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON($).uuid;if(this.anisotropy!==void 0)J.anisotropy=this.anisotropy;if(this.anisotropyRotation!==void 0)J.anisotropyRotation=this.anisotropyRotation;if(this.anisotropyMap&&this.anisotropyMap.isTexture)J.anisotropyMap=this.anisotropyMap.toJSON($).uuid;if(this.map&&this.map.isTexture)J.map=this.map.toJSON($).uuid;if(this.matcap&&this.matcap.isTexture)J.matcap=this.matcap.toJSON($).uuid;if(this.alphaMap&&this.alphaMap.isTexture)J.alphaMap=this.alphaMap.toJSON($).uuid;if(this.lightMap&&this.lightMap.isTexture)J.lightMap=this.lightMap.toJSON($).uuid,J.lightMapIntensity=this.lightMapIntensity;if(this.aoMap&&this.aoMap.isTexture)J.aoMap=this.aoMap.toJSON($).uuid,J.aoMapIntensity=this.aoMapIntensity;if(this.bumpMap&&this.bumpMap.isTexture)J.bumpMap=this.bumpMap.toJSON($).uuid,J.bumpScale=this.bumpScale;if(this.normalMap&&this.normalMap.isTexture)J.normalMap=this.normalMap.toJSON($).uuid,J.normalMapType=this.normalMapType,J.normalScale=this.normalScale.toArray();if(this.displacementMap&&this.displacementMap.isTexture)J.displacementMap=this.displacementMap.toJSON($).uuid,J.displacementScale=this.displacementScale,J.displacementBias=this.displacementBias;if(this.roughnessMap&&this.roughnessMap.isTexture)J.roughnessMap=this.roughnessMap.toJSON($).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)J.metalnessMap=this.metalnessMap.toJSON($).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)J.emissiveMap=this.emissiveMap.toJSON($).uuid;if(this.specularMap&&this.specularMap.isTexture)J.specularMap=this.specularMap.toJSON($).uuid;if(this.specularIntensityMap&&this.specularIntensityMap.isTexture)J.specularIntensityMap=this.specularIntensityMap.toJSON($).uuid;if(this.specularColorMap&&this.specularColorMap.isTexture)J.specularColorMap=this.specularColorMap.toJSON($).uuid;if(this.envMap&&this.envMap.isTexture){if(J.envMap=this.envMap.toJSON($).uuid,this.combine!==void 0)J.combine=this.combine}if(this.envMapRotation!==void 0)J.envMapRotation=this.envMapRotation.toArray();if(this.envMapIntensity!==void 0)J.envMapIntensity=this.envMapIntensity;if(this.reflectivity!==void 0)J.reflectivity=this.reflectivity;if(this.refractionRatio!==void 0)J.refractionRatio=this.refractionRatio;if(this.gradientMap&&this.gradientMap.isTexture)J.gradientMap=this.gradientMap.toJSON($).uuid;if(this.transmission!==void 0)J.transmission=this.transmission;if(this.transmissionMap&&this.transmissionMap.isTexture)J.transmissionMap=this.transmissionMap.toJSON($).uuid;if(this.thickness!==void 0)J.thickness=this.thickness;if(this.thicknessMap&&this.thicknessMap.isTexture)J.thicknessMap=this.thicknessMap.toJSON($).uuid;if(this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0)J.attenuationDistance=this.attenuationDistance;if(this.attenuationColor!==void 0)J.attenuationColor=this.attenuationColor.getHex();if(this.size!==void 0)J.size=this.size;if(this.shadowSide!==null)J.shadowSide=this.shadowSide;if(this.sizeAttenuation!==void 0)J.sizeAttenuation=this.sizeAttenuation;if(this.blending!==1)J.blending=this.blending;if(this.side!==0)J.side=this.side;if(this.vertexColors===!0)J.vertexColors=!0;if(this.opacity<1)J.opacity=this.opacity;if(this.transparent===!0)J.transparent=!0;if(this.blendSrc!==204)J.blendSrc=this.blendSrc;if(this.blendDst!==205)J.blendDst=this.blendDst;if(this.blendEquation!==100)J.blendEquation=this.blendEquation;if(this.blendSrcAlpha!==null)J.blendSrcAlpha=this.blendSrcAlpha;if(this.blendDstAlpha!==null)J.blendDstAlpha=this.blendDstAlpha;if(this.blendEquationAlpha!==null)J.blendEquationAlpha=this.blendEquationAlpha;if(this.blendColor&&this.blendColor.isColor)J.blendColor=this.blendColor.getHex();if(this.blendAlpha!==0)J.blendAlpha=this.blendAlpha;if(this.depthFunc!==3)J.depthFunc=this.depthFunc;if(this.depthTest===!1)J.depthTest=this.depthTest;if(this.depthWrite===!1)J.depthWrite=this.depthWrite;if(this.colorWrite===!1)J.colorWrite=this.colorWrite;if(this.stencilWriteMask!==255)J.stencilWriteMask=this.stencilWriteMask;if(this.stencilFunc!==519)J.stencilFunc=this.stencilFunc;if(this.stencilRef!==0)J.stencilRef=this.stencilRef;if(this.stencilFuncMask!==255)J.stencilFuncMask=this.stencilFuncMask;if(this.stencilFail!==7680)J.stencilFail=this.stencilFail;if(this.stencilZFail!==7680)J.stencilZFail=this.stencilZFail;if(this.stencilZPass!==7680)J.stencilZPass=this.stencilZPass;if(this.stencilWrite===!0)J.stencilWrite=this.stencilWrite;if(this.rotation!==void 0&&this.rotation!==0)J.rotation=this.rotation;if(this.polygonOffset===!0)J.polygonOffset=!0;if(this.polygonOffsetFactor!==0)J.polygonOffsetFactor=this.polygonOffsetFactor;if(this.polygonOffsetUnits!==0)J.polygonOffsetUnits=this.polygonOffsetUnits;if(this.linewidth!==void 0&&this.linewidth!==1)J.linewidth=this.linewidth;if(this.dashSize!==void 0)J.dashSize=this.dashSize;if(this.gapSize!==void 0)J.gapSize=this.gapSize;if(this.scale!==void 0)J.scale=this.scale;if(this.dithering===!0)J.dithering=!0;if(this.alphaTest>0)J.alphaTest=this.alphaTest;if(this.alphaHash===!0)J.alphaHash=!0;if(this.alphaToCoverage===!0)J.alphaToCoverage=!0;if(this.premultipliedAlpha===!0)J.premultipliedAlpha=!0;if(this.forceSinglePass===!0)J.forceSinglePass=!0;if(this.allowOverride===!1)J.allowOverride=!1;if(this.wireframe===!0)J.wireframe=!0;if(this.wireframeLinewidth>1)J.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=="round")J.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=="round")J.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading===!0)J.flatShading=!0;if(this.visible===!1)J.visible=!1;if(this.toneMapped===!1)J.toneMapped=!1;if(this.fog===!1)J.fog=!1;if(Object.keys(this.userData).length>0)J.userData=this.userData;function Q(W){let K=[];for(let X in W){let N=W[X];delete N.metadata,K.push(N)}return K}if(U){let W=Q($.textures),K=Q($.images);if(W.length>0)J.textures=W;if(K.length>0)J.images=K}return J}fromJSON($,U){if($.uuid!==void 0)this.uuid=$.uuid;if($.name!==void 0)this.name=$.name;if($.color!==void 0&&this.color!==void 0)this.color.setHex($.color);if($.roughness!==void 0)this.roughness=$.roughness;if($.metalness!==void 0)this.metalness=$.metalness;if($.sheen!==void 0)this.sheen=$.sheen;if($.sheenColor!==void 0)this.sheenColor=new x$().setHex($.sheenColor);if($.sheenRoughness!==void 0)this.sheenRoughness=$.sheenRoughness;if($.emissive!==void 0&&this.emissive!==void 0)this.emissive.setHex($.emissive);if($.specular!==void 0&&this.specular!==void 0)this.specular.setHex($.specular);if($.specularIntensity!==void 0)this.specularIntensity=$.specularIntensity;if($.specularColor!==void 0&&this.specularColor!==void 0)this.specularColor.setHex($.specularColor);if($.shininess!==void 0)this.shininess=$.shininess;if($.clearcoat!==void 0)this.clearcoat=$.clearcoat;if($.clearcoatRoughness!==void 0)this.clearcoatRoughness=$.clearcoatRoughness;if($.dispersion!==void 0)this.dispersion=$.dispersion;if($.iridescence!==void 0)this.iridescence=$.iridescence;if($.iridescenceIOR!==void 0)this.iridescenceIOR=$.iridescenceIOR;if($.iridescenceThicknessRange!==void 0)this.iridescenceThicknessRange=$.iridescenceThicknessRange;if($.transmission!==void 0)this.transmission=$.transmission;if($.thickness!==void 0)this.thickness=$.thickness;if($.attenuationDistance!==void 0)this.attenuationDistance=$.attenuationDistance;if($.attenuationColor!==void 0&&this.attenuationColor!==void 0)this.attenuationColor.setHex($.attenuationColor);if($.anisotropy!==void 0)this.anisotropy=$.anisotropy;if($.anisotropyRotation!==void 0)this.anisotropyRotation=$.anisotropyRotation;if($.fog!==void 0)this.fog=$.fog;if($.flatShading!==void 0)this.flatShading=$.flatShading;if($.blending!==void 0)this.blending=$.blending;if($.combine!==void 0)this.combine=$.combine;if($.side!==void 0)this.side=$.side;if($.shadowSide!==void 0)this.shadowSide=$.shadowSide;if($.opacity!==void 0)this.opacity=$.opacity;if($.transparent!==void 0)this.transparent=$.transparent;if($.alphaTest!==void 0)this.alphaTest=$.alphaTest;if($.alphaHash!==void 0)this.alphaHash=$.alphaHash;if($.depthFunc!==void 0)this.depthFunc=$.depthFunc;if($.depthTest!==void 0)this.depthTest=$.depthTest;if($.depthWrite!==void 0)this.depthWrite=$.depthWrite;if($.colorWrite!==void 0)this.colorWrite=$.colorWrite;if($.blendSrc!==void 0)this.blendSrc=$.blendSrc;if($.blendDst!==void 0)this.blendDst=$.blendDst;if($.blendEquation!==void 0)this.blendEquation=$.blendEquation;if($.blendSrcAlpha!==void 0)this.blendSrcAlpha=$.blendSrcAlpha;if($.blendDstAlpha!==void 0)this.blendDstAlpha=$.blendDstAlpha;if($.blendEquationAlpha!==void 0)this.blendEquationAlpha=$.blendEquationAlpha;if($.blendColor!==void 0&&this.blendColor!==void 0)this.blendColor.setHex($.blendColor);if($.blendAlpha!==void 0)this.blendAlpha=$.blendAlpha;if($.stencilWriteMask!==void 0)this.stencilWriteMask=$.stencilWriteMask;if($.stencilFunc!==void 0)this.stencilFunc=$.stencilFunc;if($.stencilRef!==void 0)this.stencilRef=$.stencilRef;if($.stencilFuncMask!==void 0)this.stencilFuncMask=$.stencilFuncMask;if($.stencilFail!==void 0)this.stencilFail=$.stencilFail;if($.stencilZFail!==void 0)this.stencilZFail=$.stencilZFail;if($.stencilZPass!==void 0)this.stencilZPass=$.stencilZPass;if($.stencilWrite!==void 0)this.stencilWrite=$.stencilWrite;if($.wireframe!==void 0)this.wireframe=$.wireframe;if($.wireframeLinewidth!==void 0)this.wireframeLinewidth=$.wireframeLinewidth;if($.wireframeLinecap!==void 0)this.wireframeLinecap=$.wireframeLinecap;if($.wireframeLinejoin!==void 0)this.wireframeLinejoin=$.wireframeLinejoin;if($.rotation!==void 0)this.rotation=$.rotation;if($.linewidth!==void 0)this.linewidth=$.linewidth;if($.dashSize!==void 0)this.dashSize=$.dashSize;if($.gapSize!==void 0)this.gapSize=$.gapSize;if($.scale!==void 0)this.scale=$.scale;if($.polygonOffset!==void 0)this.polygonOffset=$.polygonOffset;if($.polygonOffsetFactor!==void 0)this.polygonOffsetFactor=$.polygonOffsetFactor;if($.polygonOffsetUnits!==void 0)this.polygonOffsetUnits=$.polygonOffsetUnits;if($.dithering!==void 0)this.dithering=$.dithering;if($.alphaToCoverage!==void 0)this.alphaToCoverage=$.alphaToCoverage;if($.premultipliedAlpha!==void 0)this.premultipliedAlpha=$.premultipliedAlpha;if($.forceSinglePass!==void 0)this.forceSinglePass=$.forceSinglePass;if($.allowOverride!==void 0)this.allowOverride=$.allowOverride;if($.visible!==void 0)this.visible=$.visible;if($.toneMapped!==void 0)this.toneMapped=$.toneMapped;if($.userData!==void 0)this.userData=$.userData;if($.vertexColors!==void 0)if(typeof $.vertexColors==="number")this.vertexColors=$.vertexColors>0;else this.vertexColors=$.vertexColors;if($.size!==void 0)this.size=$.size;if($.sizeAttenuation!==void 0)this.sizeAttenuation=$.sizeAttenuation;if($.map!==void 0)this.map=U[$.map]||null;if($.matcap!==void 0)this.matcap=U[$.matcap]||null;if($.alphaMap!==void 0)this.alphaMap=U[$.alphaMap]||null;if($.bumpMap!==void 0)this.bumpMap=U[$.bumpMap]||null;if($.bumpScale!==void 0)this.bumpScale=$.bumpScale;if($.normalMap!==void 0)this.normalMap=U[$.normalMap]||null;if($.normalMapType!==void 0)this.normalMapType=$.normalMapType;if($.normalScale!==void 0){let J=$.normalScale;if(Array.isArray(J)===!1)J=[J,J];this.normalScale=new g$().fromArray(J)}if($.displacementMap!==void 0)this.displacementMap=U[$.displacementMap]||null;if($.displacementScale!==void 0)this.displacementScale=$.displacementScale;if($.displacementBias!==void 0)this.displacementBias=$.displacementBias;if($.roughnessMap!==void 0)this.roughnessMap=U[$.roughnessMap]||null;if($.metalnessMap!==void 0)this.metalnessMap=U[$.metalnessMap]||null;if($.emissiveMap!==void 0)this.emissiveMap=U[$.emissiveMap]||null;if($.emissiveIntensity!==void 0)this.emissiveIntensity=$.emissiveIntensity;if($.specularMap!==void 0)this.specularMap=U[$.specularMap]||null;if($.specularIntensityMap!==void 0)this.specularIntensityMap=U[$.specularIntensityMap]||null;if($.specularColorMap!==void 0)this.specularColorMap=U[$.specularColorMap]||null;if($.envMap!==void 0)this.envMap=U[$.envMap]||null;if($.envMapRotation!==void 0)this.envMapRotation.fromArray($.envMapRotation);if($.envMapIntensity!==void 0)this.envMapIntensity=$.envMapIntensity;if($.reflectivity!==void 0)this.reflectivity=$.reflectivity;if($.refractionRatio!==void 0)this.refractionRatio=$.refractionRatio;if($.lightMap!==void 0)this.lightMap=U[$.lightMap]||null;if($.lightMapIntensity!==void 0)this.lightMapIntensity=$.lightMapIntensity;if($.aoMap!==void 0)this.aoMap=U[$.aoMap]||null;if($.aoMapIntensity!==void 0)this.aoMapIntensity=$.aoMapIntensity;if($.gradientMap!==void 0)this.gradientMap=U[$.gradientMap]||null;if($.clearcoatMap!==void 0)this.clearcoatMap=U[$.clearcoatMap]||null;if($.clearcoatRoughnessMap!==void 0)this.clearcoatRoughnessMap=U[$.clearcoatRoughnessMap]||null;if($.clearcoatNormalMap!==void 0)this.clearcoatNormalMap=U[$.clearcoatNormalMap]||null;if($.clearcoatNormalScale!==void 0)this.clearcoatNormalScale=new g$().fromArray($.clearcoatNormalScale);if($.iridescenceMap!==void 0)this.iridescenceMap=U[$.iridescenceMap]||null;if($.iridescenceThicknessMap!==void 0)this.iridescenceThicknessMap=U[$.iridescenceThicknessMap]||null;if($.transmissionMap!==void 0)this.transmissionMap=U[$.transmissionMap]||null;if($.thicknessMap!==void 0)this.thicknessMap=U[$.thicknessMap]||null;if($.anisotropyMap!==void 0)this.anisotropyMap=U[$.anisotropyMap]||null;if($.sheenColorMap!==void 0)this.sheenColorMap=U[$.sheenColorMap]||null;if($.sheenRoughnessMap!==void 0)this.sheenRoughnessMap=U[$.sheenRoughnessMap]||null;return this}clone(){return new this.constructor().copy(this)}copy($){this.name=$.name,this.blending=$.blending,this.side=$.side,this.vertexColors=$.vertexColors,this.opacity=$.opacity,this.transparent=$.transparent,this.blendSrc=$.blendSrc,this.blendDst=$.blendDst,this.blendEquation=$.blendEquation,this.blendSrcAlpha=$.blendSrcAlpha,this.blendDstAlpha=$.blendDstAlpha,this.blendEquationAlpha=$.blendEquationAlpha,this.blendColor.copy($.blendColor),this.blendAlpha=$.blendAlpha,this.depthFunc=$.depthFunc,this.depthTest=$.depthTest,this.depthWrite=$.depthWrite,this.stencilWriteMask=$.stencilWriteMask,this.stencilFunc=$.stencilFunc,this.stencilRef=$.stencilRef,this.stencilFuncMask=$.stencilFuncMask,this.stencilFail=$.stencilFail,this.stencilZFail=$.stencilZFail,this.stencilZPass=$.stencilZPass,this.stencilWrite=$.stencilWrite;let U=$.clippingPlanes,J=null;if(U!==null){let Q=U.length;J=Array(Q);for(let W=0;W!==Q;++W)J[W]=U[W].clone()}return this.clippingPlanes=J,this.clipIntersection=$.clipIntersection,this.clipShadows=$.clipShadows,this.shadowSide=$.shadowSide,this.colorWrite=$.colorWrite,this.precision=$.precision,this.polygonOffset=$.polygonOffset,this.polygonOffsetFactor=$.polygonOffsetFactor,this.polygonOffsetUnits=$.polygonOffsetUnits,this.dithering=$.dithering,this.alphaTest=$.alphaTest,this.alphaHash=$.alphaHash,this.alphaToCoverage=$.alphaToCoverage,this.premultipliedAlpha=$.premultipliedAlpha,this.forceSinglePass=$.forceSinglePass,this.allowOverride=$.allowOverride,this.visible=$.visible,this.toneMapped=$.toneMapped,this.userData=JSON.parse(JSON.stringify($.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate($){if($===!0)this.version++}}var SJ=new j,kO=new j,jK=new j,U0=new j,FO=new j,gK=new j,LO=new j;class H0{constructor($=new j,U=new j(0,0,-1)){this.origin=$,this.direction=U}set($,U){return this.origin.copy($),this.direction.copy(U),this}copy($){return this.origin.copy($.origin),this.direction.copy($.direction),this}at($,U){return U.copy(this.origin).addScaledVector(this.direction,$)}lookAt($){return this.direction.copy($).sub(this.origin).normalize(),this}recast($){return this.origin.copy(this.at($,SJ)),this}closestPointToPoint($,U){U.subVectors($,this.origin);let J=U.dot(this.direction);if(J<0)return U.copy(this.origin);return U.copy(this.origin).addScaledVector(this.direction,J)}distanceToPoint($){return Math.sqrt(this.distanceSqToPoint($))}distanceSqToPoint($){let U=SJ.subVectors($,this.origin).dot(this.direction);if(U<0)return this.origin.distanceToSquared($);return SJ.copy(this.origin).addScaledVector(this.direction,U),SJ.distanceToSquared($)}distanceSqToSegment($,U,J,Q){kO.copy($).add(U).multiplyScalar(0.5),jK.copy(U).sub($).normalize(),U0.copy(this.origin).sub(kO);let W=$.distanceTo(U)*0.5,K=-this.direction.dot(jK),X=U0.dot(this.direction),N=-U0.dot(jK),H=U0.lengthSq(),Y=Math.abs(1-K*K),G,O,E,Z;if(Y>0)if(G=K*N-X,O=K*X-N,Z=W*Y,G>=0)if(O>=-Z)if(O<=Z){let D=1/Y;G*=D,O*=D,E=G*(G+K*O+2*X)+O*(K*G+O+2*N)+H}else O=W,G=Math.max(0,-(K*O+X)),E=-G*G+O*(O+2*N)+H;else O=-W,G=Math.max(0,-(K*O+X)),E=-G*G+O*(O+2*N)+H;else if(O<=-Z)G=Math.max(0,-(-K*W+X)),O=G>0?-W:Math.min(Math.max(-W,-N),W),E=-G*G+O*(O+2*N)+H;else if(O<=Z)G=0,O=Math.min(Math.max(-W,-N),W),E=O*(O+2*N)+H;else G=Math.max(0,-(K*W+X)),O=G>0?W:Math.min(Math.max(-W,-N),W),E=-G*G+O*(O+2*N)+H;else O=K>0?-W:W,G=Math.max(0,-(K*O+X)),E=-G*G+O*(O+2*N)+H;if(J)J.copy(this.origin).addScaledVector(this.direction,G);if(Q)Q.copy(kO).addScaledVector(jK,O);return E}intersectSphere($,U){SJ.subVectors($.center,this.origin);let J=SJ.dot(this.direction),Q=SJ.dot(SJ)-J*J,W=$.radius*$.radius;if(Q>W)return null;let K=Math.sqrt(W-Q),X=J-K,N=J+K;if(N<0)return null;if(X<0)return this.at(N,U);return this.at(X,U)}intersectsSphere($){if($.radius<0)return!1;return this.distanceSqToPoint($.center)<=$.radius*$.radius}distanceToPlane($){let U=$.normal.dot(this.direction);if(U===0){if($.distanceToPoint(this.origin)===0)return 0;return null}let J=-(this.origin.dot($.normal)+$.constant)/U;return J>=0?J:null}intersectPlane($,U){let J=this.distanceToPlane($);if(J===null)return null;return this.at(J,U)}intersectsPlane($){let U=$.distanceToPoint(this.origin);if(U===0)return!0;if($.normal.dot(this.direction)*U<0)return!0;return!1}intersectBox($,U){let J,Q,W,K,X,N,H=1/this.direction.x,Y=1/this.direction.y,G=1/this.direction.z,O=this.origin;if(H>=0)J=($.min.x-O.x)*H,Q=($.max.x-O.x)*H;else J=($.max.x-O.x)*H,Q=($.min.x-O.x)*H;if(Y>=0)W=($.min.y-O.y)*Y,K=($.max.y-O.y)*Y;else W=($.max.y-O.y)*Y,K=($.min.y-O.y)*Y;if(J>K||W>Q)return null;if(W>J||isNaN(J))J=W;if(K<Q||isNaN(Q))Q=K;if(G>=0)X=($.min.z-O.z)*G,N=($.max.z-O.z)*G;else X=($.max.z-O.z)*G,N=($.min.z-O.z)*G;if(J>N||X>Q)return null;if(X>J||J!==J)J=X;if(N<Q||Q!==Q)Q=N;if(Q<0)return null;return this.at(J>=0?J:Q,U)}intersectsBox($){return this.intersectBox($,SJ)!==null}intersectTriangle($,U,J,Q,W){FO.subVectors(U,$),gK.subVectors(J,$),LO.crossVectors(FO,gK);let K=this.direction.dot(LO),X;if(K>0){if(Q)return null;X=1}else if(K<0)X=-1,K=-K;else return null;U0.subVectors(this.origin,$);let N=X*this.direction.dot(gK.crossVectors(U0,gK));if(N<0)return null;let H=X*this.direction.dot(FO.cross(U0));if(H<0)return null;if(N+H>K)return null;let Y=-X*U0.dot(LO);if(Y<0)return null;return this.at(Y/K,W)}applyMatrix4($){return this.origin.applyMatrix4($),this.direction.transformDirection($),this}equals($){return $.origin.equals(this.origin)&&$.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class qJ extends DU{constructor($){super();this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new x$(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 OJ,this.combine=0,this.reflectivity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues($)}copy($){return super.copy($),this.color.copy($.color),this.map=$.map,this.lightMap=$.lightMap,this.lightMapIntensity=$.lightMapIntensity,this.aoMap=$.aoMap,this.aoMapIntensity=$.aoMapIntensity,this.specularMap=$.specularMap,this.alphaMap=$.alphaMap,this.envMap=$.envMap,this.envMapRotation.copy($.envMapRotation),this.combine=$.combine,this.reflectivity=$.reflectivity,this.refractionRatio=$.refractionRatio,this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this.wireframeLinecap=$.wireframeLinecap,this.wireframeLinejoin=$.wireframeLinejoin,this.fog=$.fog,this}}var ED=new p$,j0=new H0,bK=new PU,ZD=new j,xK=new j,yK=new j,hK=new j,RO=new j,fK=new j,ID=new j,uK=new j;class P6 extends k6{constructor($=new OU,U=new qJ){super();this.isMesh=!0,this.type="Mesh",this.geometry=$,this.material=U,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy($,U){if(super.copy($,U),$.morphTargetInfluences!==void 0)this.morphTargetInfluences=$.morphTargetInfluences.slice();if($.morphTargetDictionary!==void 0)this.morphTargetDictionary=Object.assign({},$.morphTargetDictionary);return this.material=Array.isArray($.material)?$.material.slice():$.material,this.geometry=$.geometry,this}updateMorphTargets(){let U=this.geometry.morphAttributes,J=Object.keys(U);if(J.length>0){let Q=U[J[0]];if(Q!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let W=0,K=Q.length;W<K;W++){let X=Q[W].name||String(W);this.morphTargetInfluences.push(0),this.morphTargetDictionary[X]=W}}}}getVertexPosition($,U){let J=this.geometry,Q=J.attributes.position,W=J.morphAttributes.position,K=J.morphTargetsRelative;U.fromBufferAttribute(Q,$);let X=this.morphTargetInfluences;if(W&&X){fK.set(0,0,0);for(let N=0,H=W.length;N<H;N++){let Y=X[N],G=W[N];if(Y===0)continue;if(RO.fromBufferAttribute(G,$),K)fK.addScaledVector(RO,Y);else fK.addScaledVector(RO.sub(U),Y)}U.add(fK)}return U}raycast($,U){let J=this.geometry,Q=this.material,W=this.matrixWorld;if(Q===void 0)return;if(J.boundingSphere===null)J.computeBoundingSphere();if(bK.copy(J.boundingSphere),bK.applyMatrix4(W),j0.copy($.ray).recast($.near),bK.containsPoint(j0.origin)===!1){if(j0.intersectSphere(bK,ZD)===null)return;if(j0.origin.distanceToSquared(ZD)>($.far-$.near)**2)return}if(ED.copy(W).invert(),j0.copy($.ray).applyMatrix4(ED),J.boundingBox!==null){if(j0.intersectsBox(J.boundingBox)===!1)return}this._computeIntersections($,U,j0)}_computeIntersections($,U,J){let Q,W=this.geometry,K=this.material,X=W.index,N=W.attributes.position,H=W.attributes.uv,Y=W.attributes.uv1,G=W.attributes.normal,O=W.groups,E=W.drawRange;if(X!==null)if(Array.isArray(K))for(let Z=0,D=O.length;Z<D;Z++){let R=O[Z],I=K[R.materialIndex],q=Math.max(R.start,E.start),_=Math.min(X.count,Math.min(R.start+R.count,E.start+E.count));for(let P=q,L=_;P<L;P+=3){let B=X.getX(P),z=X.getX(P+1),A=X.getX(P+2);if(Q=lK(this,I,$,J,H,Y,G,B,z,A),Q)Q.faceIndex=Math.floor(P/3),Q.face.materialIndex=R.materialIndex,U.push(Q)}}else{let Z=Math.max(0,E.start),D=Math.min(X.count,E.start+E.count);for(let R=Z,I=D;R<I;R+=3){let q=X.getX(R),_=X.getX(R+1),P=X.getX(R+2);if(Q=lK(this,K,$,J,H,Y,G,q,_,P),Q)Q.faceIndex=Math.floor(R/3),U.push(Q)}}else if(N!==void 0)if(Array.isArray(K))for(let Z=0,D=O.length;Z<D;Z++){let R=O[Z],I=K[R.materialIndex],q=Math.max(R.start,E.start),_=Math.min(N.count,Math.min(R.start+R.count,E.start+E.count));for(let P=q,L=_;P<L;P+=3){let B=P,z=P+1,A=P+2;if(Q=lK(this,I,$,J,H,Y,G,B,z,A),Q)Q.faceIndex=Math.floor(P/3),Q.face.materialIndex=R.materialIndex,U.push(Q)}}else{let Z=Math.max(0,E.start),D=Math.min(N.count,E.start+E.count);for(let R=Z,I=D;R<I;R+=3){let q=R,_=R+1,P=R+2;if(Q=lK(this,K,$,J,H,Y,G,q,_,P),Q)Q.faceIndex=Math.floor(R/3),U.push(Q)}}}}function GV($,U,J,Q,W,K,X,N){let H;if(U.side===1)H=Q.intersectTriangle(X,K,W,!0,N);else H=Q.intersectTriangle(W,K,X,U.side===0,N);if(H===null)return null;uK.copy(N),uK.applyMatrix4($.matrixWorld);let Y=J.ray.origin.distanceTo(uK);if(Y<J.near||Y>J.far)return null;return{distance:Y,point:uK.clone(),object:$}}function lK($,U,J,Q,W,K,X,N,H,Y){$.getVertexPosition(N,xK),$.getVertexPosition(H,yK),$.getVertexPosition(Y,hK);let G=GV($,U,J,Q,xK,yK,hK,ID);if(G){let O=new j;if(gU.getBarycoord(ID,xK,yK,hK,O),W)G.uv=gU.getInterpolatedAttribute(W,N,H,Y,O,new g$);if(K)G.uv1=gU.getInterpolatedAttribute(K,N,H,Y,O,new g$);if(X){if(G.normal=gU.getInterpolatedAttribute(X,N,H,Y,O,new j),G.normal.dot(Q.direction)>0)G.normal.multiplyScalar(-1)}let E={a:N,b:H,c:Y,normal:new j,materialIndex:0};gU.getNormal(xK,yK,hK,E.normal),G.face=E,G.barycoord=O}return G}var XQ=new Z6,qD=new Z6,DD=new Z6,OV=new Z6,kD=new p$,mK=new j,VO=new PU,FD=new p$,wO=new H0;class k7 extends P6{constructor($,U){super($,U);this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new p$,this.bindMatrixInverse=new p$,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let $=this.geometry;if(this.boundingBox===null)this.boundingBox=new GU;this.boundingBox.makeEmpty();let U=$.getAttribute("position");for(let J=0;J<U.count;J++)this.getVertexPosition(J,mK),this.boundingBox.expandByPoint(mK)}computeBoundingSphere(){let $=this.geometry;if(this.boundingSphere===null)this.boundingSphere=new PU;this.boundingSphere.makeEmpty();let U=$.getAttribute("position");for(let J=0;J<U.count;J++)this.getVertexPosition(J,mK),this.boundingSphere.expandByPoint(mK)}copy($,U){if(super.copy($,U),this.bindMode=$.bindMode,this.bindMatrix.copy($.bindMatrix),this.bindMatrixInverse.copy($.bindMatrixInverse),this.skeleton=$.skeleton,$.boundingBox!==null)this.boundingBox=$.boundingBox.clone();if($.boundingSphere!==null)this.boundingSphere=$.boundingSphere.clone();return this}raycast($,U){let J=this.material,Q=this.matrixWorld;if(J===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(VO.copy(this.boundingSphere),VO.applyMatrix4(Q),$.ray.intersectsSphere(VO)===!1)return;if(FD.copy(Q).invert(),wO.copy($.ray).applyMatrix4(FD),this.boundingBox!==null){if(wO.intersectsBox(this.boundingBox)===!1)return}this._computeIntersections($,U,wO)}getVertexPosition($,U){return super.getVertexPosition($,U),this.applyBoneTransform($,U),U}bind($,U){if(this.skeleton=$,U===void 0)this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),U=this.matrixWorld;this.bindMatrix.copy(U),this.bindMatrixInverse.copy(U).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let $=new Z6,U=this.geometry.attributes.skinWeight;for(let J=0,Q=U.count;J<Q;J++){$.fromBufferAttribute(U,J);let W=1/$.manhattanLength();if(W!==1/0)$.multiplyScalar(W);else $.set(1,0,0,0);U.setXYZW(J,$.x,$.y,$.z,$.w)}}updateMatrixWorld($){if(super.updateMatrixWorld($),this.bindMode==="attached")this.bindMatrixInverse.copy(this.matrixWorld).invert();else if(this.bindMode==="detached")this.bindMatrixInverse.copy(this.bindMatrix).invert();else A$("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform($,U){let J=this.skeleton,Q=this.geometry;if(qD.fromBufferAttribute(Q.attributes.skinIndex,$),DD.fromBufferAttribute(Q.attributes.skinWeight,$),U.isVector4)XQ.copy(U),U.set(0,0,0,0);else XQ.set(...U,1),U.set(0,0,0);XQ.applyMatrix4(this.bindMatrix);for(let W=0;W<4;W++){let K=DD.getComponent(W);if(K!==0){let X=qD.getComponent(W);kD.multiplyMatrices(J.bones[X].matrixWorld,J.boneInverses[X]),U.addScaledVector(OV.copy(XQ).applyMatrix4(kD),K)}}if(U.isVector4)U.w=XQ.w;return U.applyMatrix4(this.bindMatrixInverse)}}class MQ extends k6{constructor(){super();this.isBone=!0,this.type="Bone"}}class BQ extends v6{constructor($=null,U=1,J=1,Q,W,K,X,N,H=1003,Y=1003,G,O){super(null,K,X,N,H,Y,Q,W,G,O);this.isDataTexture=!0,this.image={data:$,width:U,height:J},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}var LD=new p$,EV=new p$;class PQ{constructor($=[],U=[]){this.uuid=iU(),this.bones=$.slice(0),this.boneInverses=U,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){let $=this.bones,U=this.boneInverses;if(this.boneMatrices=new Float32Array($.length*16),U.length===0)this.calculateInverses();else if($.length!==U.length){A$("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let J=0,Q=this.bones.length;J<Q;J++)this.boneInverses.push(new p$)}}calculateInverses(){this.boneInverses.length=0;for(let $=0,U=this.bones.length;$<U;$++){let J=new p$;if(this.bones[$])J.copy(this.bones[$].matrixWorld).invert();this.boneInverses.push(J)}}pose(){for(let $=0,U=this.bones.length;$<U;$++){let J=this.bones[$];if(J)J.matrixWorld.copy(this.boneInverses[$]).invert()}for(let $=0,U=this.bones.length;$<U;$++){let J=this.bones[$];if(J){if(J.parent&&J.parent.isBone)J.matrix.copy(J.parent.matrixWorld).invert(),J.matrix.multiply(J.matrixWorld);else J.matrix.copy(J.matrixWorld);J.matrix.decompose(J.position,J.quaternion,J.scale)}}}update(){let $=this.bones,U=this.boneInverses,J=this.boneMatrices,Q=this.boneTexture;for(let W=0,K=$.length;W<K;W++){let X=$[W]?$[W].matrixWorld:EV;LD.multiplyMatrices(X,U[W]),LD.toArray(J,W*16)}if(Q!==null)Q.needsUpdate=!0}clone(){return new PQ(this.bones,this.boneInverses)}computeBoneTexture(){let $=Math.sqrt(this.bones.length*4);$=Math.ceil($/4)*4,$=Math.max($,4);let U=new Float32Array($*$*4);U.set(this.boneMatrices);let J=new BQ(U,$,$,1023,1015);return J.needsUpdate=!0,this.boneMatrices=U,this.boneTexture=J,this}getBoneByName($){for(let U=0,J=this.bones.length;U<J;U++){let Q=this.bones[U];if(Q.name===$)return Q}return}dispose(){if(this.boneTexture!==null)this.boneTexture.dispose(),this.boneTexture=null}fromJSON($,U){this.uuid=$.uuid;for(let J=0,Q=$.bones.length;J<Q;J++){let W=$.bones[J],K=U[W];if(K===void 0)A$("Skeleton: No bone found with UUID:",W),K=new MQ;this.bones.push(K),this.boneInverses.push(new p$().fromArray($.boneInverses[J]))}return this.init(),this}toJSON(){let $={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};$.uuid=this.uuid;let U=this.bones,J=this.boneInverses;for(let Q=0,W=U.length;Q<W;Q++){let K=U[Q];$.bones.push(K.uuid);let X=J[Q];$.boneInverses.push(X.toArray())}return $}}class y0 extends u6{constructor($,U,J,Q=1){super($,U,J);this.isInstancedBufferAttribute=!0,this.meshPerAttribute=Q}copy($){return super.copy($),this.meshPerAttribute=$.meshPerAttribute,this}toJSON(){let $=super.toJSON();return $.meshPerAttribute=this.meshPerAttribute,$.isInstancedBufferAttribute=!0,$}}var lW=new p$,RD=new p$,pK=[],VD=new GU,ZV=new p$,NQ=new P6,HQ=new PU;class K8 extends P6{constructor($,U,J){super($,U);this.isInstancedMesh=!0,this.instanceMatrix=new y0(new Float32Array(J*16),16),this.instanceColor=null,this.morphTexture=null,this.count=J,this.boundingBox=null,this.boundingSphere=null;for(let Q=0;Q<J;Q++)this.setMatrixAt(Q,ZV)}computeBoundingBox(){let $=this.geometry,U=this.count;if(this.boundingBox===null)this.boundingBox=new GU;if($.boundingBox===null)$.computeBoundingBox();this.boundingBox.makeEmpty();for(let J=0;J<U;J++)this.getMatrixAt(J,lW),VD.copy($.boundingBox).applyMatrix4(lW),this.boundingBox.union(VD)}computeBoundingSphere(){let $=this.geometry,U=this.count;if(this.boundingSphere===null)this.boundingSphere=new PU;if($.boundingSphere===null)$.computeBoundingSphere();this.boundingSphere.makeEmpty();for(let J=0;J<U;J++)this.getMatrixAt(J,lW),HQ.copy($.boundingSphere).applyMatrix4(lW),this.boundingSphere.union(HQ)}copy($,U){if(super.copy($,U),this.instanceMatrix.copy($.instanceMatrix),$.morphTexture!==null)this.morphTexture=$.morphTexture.clone();if($.instanceColor!==null)this.instanceColor=$.instanceColor.clone();if(this.count=$.count,$.boundingBox!==null)this.boundingBox=$.boundingBox.clone();if($.boundingSphere!==null)this.boundingSphere=$.boundingSphere.clone();return this}getColorAt($,U){if(this.instanceColor===null)return U.setRGB(1,1,1);else return U.fromArray(this.instanceColor.array,$*3)}getMatrixAt($,U){return U.fromArray(this.instanceMatrix.array,$*16)}getMorphAt($,U){let J=U.morphTargetInfluences,Q=this.morphTexture.source.data.data,W=J.length+1,K=$*W+1;for(let X=0;X<J.length;X++)J[X]=Q[K+X]}raycast($,U){let J=this.matrixWorld,Q=this.count;if(NQ.geometry=this.geometry,NQ.material=this.material,NQ.material===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(HQ.copy(this.boundingSphere),HQ.applyMatrix4(J),$.ray.intersectsSphere(HQ)===!1)return;for(let W=0;W<Q;W++){this.getMatrixAt(W,lW),RD.multiplyMatrices(J,lW),NQ.matrixWorld=RD,NQ.raycast($,pK);for(let K=0,X=pK.length;K<X;K++){let N=pK[K];N.instanceId=W,N.object=this,U.push(N)}pK.length=0}}setColorAt($,U){if(this.instanceColor===null)this.instanceColor=new y0(new Float32Array(this.instanceMatrix.count*3).fill(1),3);return U.toArray(this.instanceColor.array,$*3),this}setMatrixAt($,U){return U.toArray(this.instanceMatrix.array,$*16),this}setMorphAt($,U){let J=U.morphTargetInfluences,Q=J.length+1;if(this.morphTexture===null)this.morphTexture=new BQ(new Float32Array(Q*this.count),Q,this.count,1028,1015);let W=this.morphTexture.source.data.data,K=0;for(let H=0;H<J.length;H++)K+=J[H];let X=this.geometry.morphTargetsRelative?1:1-K,N=Q*$;return W[N]=X,W.set(J,N+1),this}updateMorphTargets(){}dispose(){if(this.dispatchEvent({type:"dispose"}),this.morphTexture!==null)this.morphTexture.dispose(),this.morphTexture=null}}var MO=new j,IV=new j,qV=new u$;class cU{constructor($=new j(1,0,0),U=0){this.isPlane=!0,this.normal=$,this.constant=U}set($,U){return this.normal.copy($),this.constant=U,this}setComponents($,U,J,Q){return this.normal.set($,U,J),this.constant=Q,this}setFromNormalAndCoplanarPoint($,U){return this.normal.copy($),this.constant=-U.dot(this.normal),this}setFromCoplanarPoints($,U,J){let Q=MO.subVectors(J,U).cross(IV.subVectors($,U)).normalize();return this.setFromNormalAndCoplanarPoint(Q,$),this}copy($){return this.normal.copy($.normal),this.constant=$.constant,this}normalize(){let $=1/this.normal.length();return this.normal.multiplyScalar($),this.constant*=$,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint($){return this.normal.dot($)+this.constant}distanceToSphere($){return this.distanceToPoint($.center)-$.radius}projectPoint($,U){return U.copy($).addScaledVector(this.normal,-this.distanceToPoint($))}intersectLine($,U,J=!0){let Q=$.delta(MO),W=this.normal.dot(Q);if(W===0){if(this.distanceToPoint($.start)===0)return U.copy($.start);return null}let K=-($.start.dot(this.normal)+this.constant)/W;if(J===!0&&(K<0||K>1))return null;return U.copy($.start).addScaledVector(Q,K)}intersectsLine($){let U=this.distanceToPoint($.start),J=this.distanceToPoint($.end);return U<0&&J>0||J<0&&U>0}intersectsBox($){return $.intersectsPlane(this)}intersectsSphere($){return $.intersectsPlane(this)}coplanarPoint($){return $.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4($,U){let J=U||qV.getNormalMatrix($),Q=this.coplanarPoint(MO).applyMatrix4($),W=this.normal.applyMatrix3(J).normalize();return this.constant=-Q.dot(W),this}translate($){return this.constant-=$.dot(this.normal),this}equals($){return $.normal.equals(this.normal)&&$.constant===this.constant}clone(){return new this.constructor().copy(this)}}var g0=new PU,DV=new g$(0.5,0.5),dK=new j;class zQ{constructor($=new cU,U=new cU,J=new cU,Q=new cU,W=new cU,K=new cU){this.planes=[$,U,J,Q,W,K]}set($,U,J,Q,W,K){let X=this.planes;return X[0].copy($),X[1].copy(U),X[2].copy(J),X[3].copy(Q),X[4].copy(W),X[5].copy(K),this}copy($){let U=this.planes;for(let J=0;J<6;J++)U[J].copy($.planes[J]);return this}setFromProjectionMatrix($,U=2000,J=!1){let Q=this.planes,W=$.elements,K=W[0],X=W[1],N=W[2],H=W[3],Y=W[4],G=W[5],O=W[6],E=W[7],Z=W[8],D=W[9],R=W[10],I=W[11],q=W[12],_=W[13],P=W[14],L=W[15];if(Q[0].setComponents(H-K,E-Y,I-Z,L-q).normalize(),Q[1].setComponents(H+K,E+Y,I+Z,L+q).normalize(),Q[2].setComponents(H+X,E+G,I+D,L+_).normalize(),Q[3].setComponents(H-X,E-G,I-D,L-_).normalize(),J)Q[4].setComponents(N,O,R,P).normalize(),Q[5].setComponents(H-N,E-O,I-R,L-P).normalize();else if(Q[4].setComponents(H-N,E-O,I-R,L-P).normalize(),U===2000)Q[5].setComponents(H+N,E+O,I+R,L+P).normalize();else if(U===2001)Q[5].setComponents(N,O,R,P).normalize();else throw Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+U);return this}intersectsObject($){if($.boundingSphere!==void 0){if($.boundingSphere===null)$.computeBoundingSphere();g0.copy($.boundingSphere).applyMatrix4($.matrixWorld)}else{let U=$.geometry;if(U.boundingSphere===null)U.computeBoundingSphere();g0.copy(U.boundingSphere).applyMatrix4($.matrixWorld)}return this.intersectsSphere(g0)}intersectsSprite($){g0.center.set(0,0,0);let U=DV.distanceTo($.center);return g0.radius=0.7071067811865476+U,g0.applyMatrix4($.matrixWorld),this.intersectsSphere(g0)}intersectsSphere($){let U=this.planes,J=$.center,Q=-$.radius;for(let W=0;W<6;W++)if(U[W].distanceToPoint(J)<Q)return!1;return!0}intersectsBox($){let U=this.planes;for(let J=0;J<6;J++){let Q=U[J];if(dK.x=Q.normal.x>0?$.max.x:$.min.x,dK.y=Q.normal.y>0?$.max.y:$.min.y,dK.z=Q.normal.z>0?$.max.z:$.min.z,Q.distanceToPoint(dK)<0)return!1}return!0}containsPoint($){let U=this.planes;for(let J=0;J<6;J++)if(U[J].distanceToPoint($)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class _Q extends DU{constructor($){super();this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new x$(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues($)}copy($){return super.copy($),this.color.copy($.color),this.map=$.map,this.linewidth=$.linewidth,this.linecap=$.linecap,this.linejoin=$.linejoin,this.fog=$.fog,this}}var tK=new j,eK=new j,wD=new p$,YQ=new H0,cK=new PU,BO=new j,MD=new j;class Y0 extends k6{constructor($=new OU,U=new _Q){super();this.isLine=!0,this.type="Line",this.geometry=$,this.material=U,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy($,U){return super.copy($,U),this.material=Array.isArray($.material)?$.material.slice():$.material,this.geometry=$.geometry,this}computeLineDistances(){let $=this.geometry;if($.index===null){let U=$.attributes.position,J=[0];for(let Q=1,W=U.count;Q<W;Q++)tK.fromBufferAttribute(U,Q-1),eK.fromBufferAttribute(U,Q),J[Q]=J[Q-1],J[Q]+=tK.distanceTo(eK);$.setAttribute("lineDistance",new qU(J,1))}else A$("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast($,U){let J=this.geometry,Q=this.matrixWorld,W=$.params.Line.threshold,K=J.drawRange;if(J.boundingSphere===null)J.computeBoundingSphere();if(cK.copy(J.boundingSphere),cK.applyMatrix4(Q),cK.radius+=W,$.ray.intersectsSphere(cK)===!1)return;wD.copy(Q).invert(),YQ.copy($.ray).applyMatrix4(wD);let X=W/((this.scale.x+this.scale.y+this.scale.z)/3),N=X*X,H=this.isLineSegments?2:1,Y=J.index,O=J.attributes.position;if(Y!==null){let E=Math.max(0,K.start),Z=Math.min(Y.count,K.start+K.count);for(let D=E,R=Z-1;D<R;D+=H){let I=Y.getX(D),q=Y.getX(D+1),_=nK(this,$,YQ,N,I,q,D);if(_)U.push(_)}if(this.isLineLoop){let D=Y.getX(Z-1),R=Y.getX(E),I=nK(this,$,YQ,N,D,R,Z-1);if(I)U.push(I)}}else{let E=Math.max(0,K.start),Z=Math.min(O.count,K.start+K.count);for(let D=E,R=Z-1;D<R;D+=H){let I=nK(this,$,YQ,N,D,D+1,D);if(I)U.push(I)}if(this.isLineLoop){let D=nK(this,$,YQ,N,Z-1,E,Z-1);if(D)U.push(D)}}}updateMorphTargets(){let U=this.geometry.morphAttributes,J=Object.keys(U);if(J.length>0){let Q=U[J[0]];if(Q!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let W=0,K=Q.length;W<K;W++){let X=Q[W].name||String(W);this.morphTargetInfluences.push(0),this.morphTargetDictionary[X]=W}}}}}function nK($,U,J,Q,W,K,X){let N=$.geometry.attributes.position;if(tK.fromBufferAttribute(N,W),eK.fromBufferAttribute(N,K),J.distanceSqToSegment(tK,eK,BO,MD)>Q)return;BO.applyMatrix4($.matrixWorld);let Y=U.ray.origin.distanceTo(BO);if(Y<U.near||Y>U.far)return;return{distance:Y,point:MD.clone().applyMatrix4($.matrixWorld),index:X,face:null,faceIndex:null,barycoord:null,object:$}}var BD=new j,PD=new j;class F7 extends Y0{constructor($,U){super($,U);this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let $=this.geometry;if($.index===null){let U=$.attributes.position,J=[];for(let Q=0,W=U.count;Q<W;Q+=2)BD.fromBufferAttribute(U,Q),PD.fromBufferAttribute(U,Q+1),J[Q]=Q===0?0:J[Q-1],J[Q+1]=J[Q]+BD.distanceTo(PD);$.setAttribute("lineDistance",new qU(J,1))}else A$("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class L7 extends Y0{constructor($,U){super($,U);this.isLineLoop=!0,this.type="LineLoop"}}class AQ extends DU{constructor($){super();this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new x$(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues($)}copy($){return super.copy($),this.color.copy($.color),this.map=$.map,this.alphaMap=$.alphaMap,this.size=$.size,this.sizeAttenuation=$.sizeAttenuation,this.fog=$.fog,this}}var zD=new p$,_O=new H0,iK=new PU,oK=new j;class X8 extends k6{constructor($=new OU,U=new AQ){super();this.isPoints=!0,this.type="Points",this.geometry=$,this.material=U,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy($,U){return super.copy($,U),this.material=Array.isArray($.material)?$.material.slice():$.material,this.geometry=$.geometry,this}raycast($,U){let J=this.geometry,Q=this.matrixWorld,W=$.params.Points.threshold,K=J.drawRange;if(J.boundingSphere===null)J.computeBoundingSphere();if(iK.copy(J.boundingSphere),iK.applyMatrix4(Q),iK.radius+=W,$.ray.intersectsSphere(iK)===!1)return;zD.copy(Q).invert(),_O.copy($.ray).applyMatrix4(zD);let X=W/((this.scale.x+this.scale.y+this.scale.z)/3),N=X*X,H=J.index,G=J.attributes.position;if(H!==null){let O=Math.max(0,K.start),E=Math.min(H.count,K.start+K.count);for(let Z=O,D=E;Z<D;Z++){let R=H.getX(Z);oK.fromBufferAttribute(G,R),_D(oK,R,N,Q,$,U,this)}}else{let O=Math.max(0,K.start),E=Math.min(G.count,K.start+K.count);for(let Z=O,D=E;Z<D;Z++)oK.fromBufferAttribute(G,Z),_D(oK,Z,N,Q,$,U,this)}}updateMorphTargets(){let U=this.geometry.morphAttributes,J=Object.keys(U);if(J.length>0){let Q=U[J[0]];if(Q!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let W=0,K=Q.length;W<K;W++){let X=Q[W].name||String(W);this.morphTargetInfluences.push(0),this.morphTargetDictionary[X]=W}}}}}function _D($,U,J,Q,W,K,X){let N=_O.distanceSqToPoint($);if(N<J){let H=new j;_O.closestPointToPoint($,H),H.applyMatrix4(Q);let Y=W.ray.origin.distanceTo(H);if(Y<W.near||Y>W.far)return;K.push({distance:Y,distanceToRay:Math.sqrt(N),point:H,index:U,face:null,faceIndex:null,barycoord:null,object:X})}}class R7 extends v6{constructor($=[],U=301,J,Q,W,K,X,N,H,Y){super($,U,J,Q,W,K,X,N,H,Y);this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images($){this.image=$}}class G0 extends v6{constructor($,U,J=1014,Q,W,K,X=1003,N=1003,H,Y=1026,G=1){if(Y!==1026&&Y!==1027)throw Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let O={width:$,height:U,depth:G};super(O,Q,W,K,X,N,Y,J,H);this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy($){return super.copy($),this.source=new RQ(Object.assign({},$.image)),this.compareFunction=$.compareFunction,this}toJSON($){let U=super.toJSON($);if(this.compareFunction!==null)U.compareFunction=this.compareFunction;return U}}class TE extends G0{constructor($,U=1014,J=301,Q,W,K=1003,X=1003,N,H=1026){let Y={width:$,height:$,depth:1},G=[Y,Y,Y,Y,Y,Y];super($,$,U,J,Q,W,K,X,N,H);this.image=G,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images($){this.image=$}}class V7 extends v6{constructor($=null){super();this.sourceTexture=$,this.isExternalTexture=!0}copy($){return super.copy($),this.sourceTexture=$.sourceTexture,this}}class O0 extends OU{constructor($=1,U=1,J=1,Q=1,W=1,K=1){super();this.type="BoxGeometry",this.parameters={width:$,height:U,depth:J,widthSegments:Q,heightSegments:W,depthSegments:K};let X=this;Q=Math.floor(Q),W=Math.floor(W),K=Math.floor(K);let N=[],H=[],Y=[],G=[],O=0,E=0;Z("z","y","x",-1,-1,J,U,$,K,W,0),Z("z","y","x",1,-1,J,U,-$,K,W,1),Z("x","z","y",1,1,$,J,U,Q,K,2),Z("x","z","y",1,-1,$,J,-U,Q,K,3),Z("x","y","z",1,-1,$,U,J,Q,W,4),Z("x","y","z",-1,-1,$,U,-J,Q,W,5),this.setIndex(N),this.setAttribute("position",new qU(H,3)),this.setAttribute("normal",new qU(Y,3)),this.setAttribute("uv",new qU(G,2));function Z(D,R,I,q,_,P,L,B,z,A,k){let w=P/z,h=L/A,C=P/2,f=L/2,s=B/2,y=z+1,d=A+1,c=0,x=0,t=new j;for(let e=0;e<d;e++){let Y$=e*h-f;for(let R$=0;R$<y;R$++){let w$=R$*w-C;t[D]=w$*q,t[R]=Y$*_,t[I]=s,H.push(t.x,t.y,t.z),t[D]=0,t[R]=0,t[I]=B>0?1:-1,Y.push(t.x,t.y,t.z),G.push(R$/z),G.push(1-e/A),c+=1}}for(let e=0;e<A;e++)for(let Y$=0;Y$<z;Y$++){let R$=O+Y$+y*e,w$=O+Y$+y*(e+1),U6=O+(Y$+1)+y*(e+1),i$=O+(Y$+1)+y*e;N.push(R$,w$,i$),N.push(w$,U6,i$),x+=6}X.addGroup(E,x,k),E+=x,O+=c}}copy($){return super.copy($),this.parameters=Object.assign({},$.parameters),this}static fromJSON($){return new O0($.width,$.height,$.depth,$.widthSegments,$.heightSegments,$.depthSegments)}}class CQ extends OU{constructor($=1,U=1,J=1,Q=1){super();this.type="PlaneGeometry",this.parameters={width:$,height:U,widthSegments:J,heightSegments:Q};let W=$/2,K=U/2,X=Math.floor(J),N=Math.floor(Q),H=X+1,Y=N+1,G=$/X,O=U/N,E=[],Z=[],D=[],R=[];for(let I=0;I<Y;I++){let q=I*O-K;for(let _=0;_<H;_++){let P=_*G-W;Z.push(P,-q,0),D.push(0,0,1),R.push(_/X),R.push(1-I/N)}}for(let I=0;I<N;I++)for(let q=0;q<X;q++){let _=q+H*I,P=q+H*(I+1),L=q+1+H*(I+1),B=q+1+H*I;E.push(_,P,B),E.push(P,L,B)}this.setIndex(E),this.setAttribute("position",new qU(Z,3)),this.setAttribute("normal",new qU(D,3)),this.setAttribute("uv",new qU(R,2))}copy($){return super.copy($),this.parameters=Object.assign({},$.parameters),this}static fromJSON($){return new CQ($.width,$.height,$.widthSegments,$.heightSegments)}}function d0($){let U={};for(let J in $){U[J]={};for(let Q in $[J]){let W=$[J][Q];if(AD(W))if(W.isRenderTargetTexture)A$("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),U[J][Q]=null;else U[J][Q]=W.clone();else if(Array.isArray(W))if(AD(W[0])){let K=[];for(let X=0,N=W.length;X<N;X++)K[X]=W[X].clone();U[J][Q]=K}else U[J][Q]=W.slice();else U[J][Q]=W}}return U}function WU($){let U={};for(let J=0;J<$.length;J++){let Q=d0($[J]);for(let W in Q)U[W]=Q[W]}return U}function AD($){return $&&($.isColor||$.isMatrix3||$.isMatrix4||$.isVector2||$.isVector3||$.isVector4||$.isTexture||$.isQuaternion)}function kV($){let U=[];for(let J=0;J<$.length;J++)U.push($[J].clone());return U}function vE($){let U=$.getRenderTarget();if(U===null)return $.outputColorSpace;if(U.isXRRenderTarget===!0)return U.texture.colorSpace;return s$.workingColorSpace}var gk={clone:d0,merge:WU},FV=`void main() {+*/var bt=Uint8Array,cn=Uint16Array,$c=Int32Array,Bo=new bt([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]),Go=new bt([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]),kc=new bt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Sm=function(e,t){var n=new cn(31);for(var i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new $c(n[30]);for(var i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)r[s]=s-n[i]<<5|i;return{b:n,r}},Mm=Sm(Bo,2),{b:wm,r:Bc}=Mm;wm[28]=258,Bc[258]=28;var Tm=Sm(Go,0),{b:Ev,r:gm}=Tm,Gc=new cn(32768);for(je=0;je<32768;++je)Hn=(je&43690)>>1|(je&21845)<<1,Hn=(Hn&52428)>>2|(Hn&13107)<<2,Hn=(Hn&61680)>>4|(Hn&3855)<<4,Gc[je]=((Hn&65280)>>8|(Hn&255)<<8)>>1;var Hn,je,Wn=function(e,t,n){var i=e.length,r=0,s=new cn(t);for(;r<i;++r)if(e[r])++s[e[r]-1];var o=new cn(t);for(r=1;r<t;++r)o[r]=o[r-1]+s[r-1]<<1;var a;if(n){a=new cn(1<<t);var c=15-t;for(r=0;r<i;++r)if(e[r]){var l=r<<4|e[r],u=t-e[r],f=o[e[r]-1]++<<u;for(var h=f|(1<<u)-1;f<=h;++f)a[Gc[f]>>c]=l}}else{a=new cn(i);for(r=0;r<i;++r)if(e[r])a[r]=Gc[o[e[r]-1]++]>>15-e[r]}return a},Ei=new bt(288);for(je=0;je<144;++je)Ei[je]=8;var je;for(je=144;je<256;++je)Ei[je]=9;var je;for(je=256;je<280;++je)Ei[je]=7;var je;for(je=280;je<288;++je)Ei[je]=8;var je,Es=new bt(32);for(je=0;je<32;++je)Es[je]=5;var je,Av=Wn(Ei,9,0),Rv=Wn(Ei,9,1),Cv=Wn(Es,5,0),Iv=Wn(Es,5,1),Uc=function(e){var t=e[0];for(var n=1;n<e.length;++n)if(e[n]>t)t=e[n];return t},An=function(e,t,n){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(t&7)&n},Oc=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Zc=function(e){return(e+7)/8|0},As=function(e,t,n){if(t==null||t<0)t=0;if(n==null||n>e.length)n=e.length;return new bt(e.subarray(t,n))};var Pv=["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"],Kt=function(e,t,n){var i=Error(t||Pv[e]);if(i.code=e,Error.captureStackTrace)Error.captureStackTrace(i,Kt);if(!n)throw i;return i},Lv=function(e,t,n,i){var r=e.length,s=i?i.length:0;if(!r||t.f&&!t.l)return n||new bt(0);var o=!n,a=o||t.i!=2,c=t.i;if(o)n=new bt(r*3);var l=function(Oe){var ke=n.length;if(Oe>ke){var Ke=new bt(Math.max(ke*2,Oe));Ke.set(n),n=Ke}},u=t.f||0,f=t.p||0,h=t.b||0,{l:d,d:g,m:y,n:p}=t,m=r*8;do{if(!d){u=An(e,f,1);var A=An(e,f+1,3);if(f+=3,!A){var T=Zc(f)+4,v=e[T-4]|e[T-3]<<8,w=T+v;if(w>r){if(c)Kt(0);break}if(a)l(h+v);n.set(e.subarray(T,w),h),t.b=h+=v,t.p=f=w*8,t.f=u;continue}else if(A==1)d=Rv,g=Iv,y=9,p=5;else if(A==2){var E=An(e,f,31)+257,R=An(e,f+10,15)+4,_=E+An(e,f+5,31)+1;f+=14;var S=new bt(_),F=new bt(19);for(var C=0;C<R;++C)F[kc[C]]=An(e,f+C*3,7);f+=R*3;var z=Uc(F),J=(1<<z)-1,O=Wn(F,z,1);for(var C=0;C<_;){var H=O[An(e,f,J)];f+=H&15;var T=H>>4;if(T<16)S[C++]=T;else{var V=0,U=0;if(T==16)U=3+An(e,f,3),f+=2,V=S[C-1];else if(T==17)U=3+An(e,f,7),f+=3;else if(T==18)U=11+An(e,f,127),f+=7;while(U--)S[C++]=V}}var K=S.subarray(0,E),Q=S.subarray(E);y=Uc(K),p=Uc(Q),d=Wn(K,y,1),g=Wn(Q,p,1)}else Kt(1);if(f>m){if(c)Kt(0);break}}if(a)l(h+131072);var se=(1<<y)-1,me=(1<<p)-1,_e=f;for(;;_e=f){var V=d[Oc(e,f)&se],qe=V>>4;if(f+=V&15,f>m){if(c)Kt(0);break}if(!V)Kt(2);if(qe<256)n[h++]=qe;else if(qe==256){_e=f,d=null;break}else{var Ge=qe-254;if(qe>264){var C=qe-257,Z=Bo[C];Ge=An(e,f,(1<<Z)-1)+wm[C],f+=Z}var ne=g[Oc(e,f)&me],fe=ne>>4;if(!ne)Kt(3);f+=ne&15;var Q=Ev[fe];if(fe>3){var Z=Go[fe];Q+=Oc(e,f)&(1<<Z)-1,f+=Z}if(f>m){if(c)Kt(0);break}if(a)l(h+131072);var de=h+Ge;if(h<Q){var Re=s-Q,Ze=Math.min(Q,de);if(Re+h<0)Kt(3);for(;h<Ze;++h)n[h]=i[Re+h]}for(;h<de;++h)n[h]=n[h-Q]}}if(t.l=d,t.p=_e,t.b=h,t.f=u,d)u=1,t.m=y,t.d=g,t.n=p}while(!u);return h!=n.length&&o?As(n,0,h):n.subarray(0,h)},ri=function(e,t,n){n<<=t&7;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8},ws=function(e,t,n){n<<=t&7;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8,e[i+2]|=n>>16},Fc=function(e,t){var n=[];for(var i=0;i<e.length;++i)if(e[i])n.push({s:i,f:e[i]});var r=n.length,s=n.slice();if(!r)return{t:Am,l:0};if(r==1){var o=new bt(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(w,E){return w.f-E.f}),n.push({s:-1,f:25001});var a=n[0],c=n[1],l=0,u=1,f=2;n[0]={s:-1,f:a.f+c.f,l:a,r:c};while(u!=r-1)a=n[n[l].f<n[f].f?l++:f++],c=n[l!=u&&n[l].f<n[f].f?l++:f++],n[u++]={s:-1,f:a.f+c.f,l:a,r:c};var h=s[0].s;for(var i=1;i<r;++i)if(s[i].s>h)h=s[i].s;var d=new cn(h+1),g=Hc(n[u-1],d,0);if(g>t){var i=0,y=0,p=g-t,m=1<<p;s.sort(function(E,R){return d[R.s]-d[E.s]||E.f-R.f});for(;i<r;++i){var A=s[i].s;if(d[A]>t)y+=m-(1<<g-d[A]),d[A]=t;else break}y>>=p;while(y>0){var T=s[i].s;if(d[T]<t)y-=1<<t-d[T]++-1;else++i}for(;i>=0&&y;--i){var v=s[i].s;if(d[v]==t)--d[v],++y}g=t}return{t:new bt(d),l:g}},Hc=function(e,t,n){return e.s==-1?Math.max(Hc(e.l,t,n+1),Hc(e.r,t,n+1)):t[e.s]=n},_m=function(e){var t=e.length;while(t&&!e[--t]);var n=new cn(++t),i=0,r=e[0],s=1,o=function(c){n[i++]=c};for(var a=1;a<=t;++a)if(e[a]==r&&a!=t)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);if(s>2)o(s>10?s-11<<5|28690:s-3<<5|12305),s=0}else if(s>3){o(r),--s;for(;s>6;s-=6)o(8304);if(s>2)o(s-3<<5|8208),s=0}while(s--)o(r);s=1,r=e[a]}return{c:n.subarray(0,i),n:t}},Ts=function(e,t){var n=0;for(var i=0;i<t.length;++i)n+=e[i]*t[i];return n},Em=function(e,t,n){var i=n.length,r=Zc(t+2);e[r]=i&255,e[r+1]=i>>8,e[r+2]=e[r]^255,e[r+3]=e[r+1]^255;for(var s=0;s<i;++s)e[r+s+4]=n[s];return(r+4+i)*8},xm=function(e,t,n,i,r,s,o,a,c,l,u){ri(t,u++,n),++r[256];var f=Fc(r,15),{t:h,l:d}=f,g=Fc(s,15),{t:y,l:p}=g,m=_m(h),{c:A,n:T}=m,v=_m(y),{c:w,n:E}=v,R=new cn(19);for(var _=0;_<A.length;++_)++R[A[_]&31];for(var _=0;_<w.length;++_)++R[w[_]&31];var S=Fc(R,7),{t:F,l:C}=S,z=19;for(;z>4&&!F[kc[z-1]];--z);var J=l+5<<3,O=Ts(r,Ei)+Ts(s,Es)+o,H=Ts(r,h)+Ts(s,y)+o+14+3*z+Ts(R,F)+2*R[16]+3*R[17]+7*R[18];if(c>=0&&J<=O&&J<=H)return Em(t,u,e.subarray(c,c+l));var V,U,K,Q;if(ri(t,u,1+(H<O)),u+=2,H<O){V=Wn(h,d,0),U=h,K=Wn(y,p,0),Q=y;var se=Wn(F,C,0);ri(t,u,T-257),ri(t,u+5,E-1),ri(t,u+10,z-4),u+=14;for(var _=0;_<z;++_)ri(t,u+3*_,F[kc[_]]);u+=3*z;var me=[A,w];for(var _e=0;_e<2;++_e){var qe=me[_e];for(var _=0;_<qe.length;++_){var Ge=qe[_]&31;if(ri(t,u,se[Ge]),u+=F[Ge],Ge>15)ri(t,u,qe[_]>>5&127),u+=qe[_]>>12}}}else V=Av,U=Ei,K=Cv,Q=Es;for(var _=0;_<a;++_){var Z=i[_];if(Z>255){var Ge=Z>>18&31;if(ws(t,u,V[Ge+257]),u+=U[Ge+257],Ge>7)ri(t,u,Z>>23&31),u+=Bo[Ge];var ne=Z&31;if(ws(t,u,K[ne]),u+=Q[ne],ne>3)ws(t,u,Z>>5&8191),u+=Go[ne]}else ws(t,u,V[Z]),u+=U[Z]}return ws(t,u,V[256]),u+U[256]},Nv=new $c([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Am=new bt(0),Dv=function(e,t,n,i,r,s){var o=s.z||e.length,a=new bt(i+o+5*(1+Math.ceil(o/7000))+r),c=a.subarray(i,a.length-r),l=s.l,u=(s.r||0)&7;if(t){if(u)c[0]=s.r>>3;var f=Nv[t-1],h=f>>13,d=f&8191,g=(1<<n)-1,y=s.p||new cn(32768),p=s.h||new cn(g+1),m=Math.ceil(n/3),A=2*m,T=function(Ye){return(e[Ye]^e[Ye+1]<<m^e[Ye+2]<<A)&g},v=new $c(25000),w=new cn(288),E=new cn(32),R=0,_=0,S=s.i||0,F=0,C=s.w||0,z=0;for(;S+2<o;++S){var J=T(S),O=S&32767,H=p[J];if(y[O]=H,p[J]=O,C<=S){var V=o-S;if((R>7000||F>24576)&&(V>423||!l)){u=xm(e,c,0,v,w,E,_,F,z,S-z,u),F=R=_=0,z=S;for(var U=0;U<286;++U)w[U]=0;for(var U=0;U<30;++U)E[U]=0}var K=2,Q=0,se=d,me=O-H&32767;if(V>2&&J==T(S-me)){var _e=Math.min(h,V)-1,qe=Math.min(32767,S),Ge=Math.min(258,V);while(me<=qe&&--se&&O!=H){if(e[S+K]==e[S+K-me]){var Z=0;for(;Z<Ge&&e[S+Z]==e[S+Z-me];++Z);if(Z>K){if(K=Z,Q=me,Z>_e)break;var ne=Math.min(me,Z-2),fe=0;for(var U=0;U<ne;++U){var de=S-me+U&32767,Re=y[de],Ze=de-Re&32767;if(Ze>fe)fe=Ze,H=de}}}O=H,H=y[O],me+=O-H&32767}}if(Q){v[F++]=268435456|Bc[K]<<18|gm[Q];var Oe=Bc[K]&31,ke=gm[Q]&31;_+=Bo[Oe]+Go[ke],++w[257+Oe],++E[ke],C=S+K,++R}else v[F++]=e[S],++w[e[S]]}}for(S=Math.max(S,C);S<o;++S)v[F++]=e[S],++w[e[S]];if(u=xm(e,c,l,v,w,E,_,F,z,S-z,u),!l)s.r=u&7|c[u/8|0]<<3,u-=7,s.h=p,s.p=y,s.i=S,s.w=C}else{for(var S=s.w||0;S<o+l;S+=65535){var Ke=S+65535;if(Ke>=o)c[u/8|0]=l,Ke=o;u=Em(c,u+1,e.subarray(S,Ke))}s.i=o}return As(a,0,i+Zc(u)+r)},Uv=function(){var e=new Int32Array(256);for(var t=0;t<256;++t){var n=t,i=9;while(--i)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e}(),Ov=function(){var e=-1;return{p:function(t){var n=e;for(var i=0;i<t.length;++i)n=Uv[n&255^t[i]]^n>>>8;e=n},d:function(){return~e}}};var Fv=function(e,t,n,i,r){if(!r){if(r={l:1},t.dictionary){var s=t.dictionary.subarray(-32768),o=new bt(s.length+e.length);o.set(s),o.set(e,s.length),e=o,r.w=s.length}}return Dv(e,t.level==null?6:t.level,t.mem==null?r.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,i,r)},Rm=function(e,t){var n={};for(var i in e)n[i]=e[i];for(var i in t)n[i]=t[i];return n};var Vn=function(e,t){return e[t]|e[t+1]<<8},Rn=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},zc=function(e,t){return Rn(e,t)+Rn(e,t+4)*4294967296},Wt=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function zv(e,t){return Fv(e,t||{},0,0)}function kv(e,t){return Lv(e,{i:2},t&&t.out,t&&t.dictionary)}var Cm=function(e,t,n,i){for(var r in e){var s=e[r],o=t+r,a=i;if(Array.isArray(s))a=Rm(i,s[1]),s=s[0];if(s instanceof bt)n[o]=[s,a];else n[o+="/"]=[new bt(0),a],Cm(s,o,n,i)}},vm=typeof TextEncoder<"u"&&new TextEncoder,Vc=typeof TextDecoder<"u"&&new TextDecoder,Bv=0;try{Vc.decode(Am,{stream:!0}),Bv=1}catch(e){}var Gv=function(e){for(var t="",n=0;;){var i=e[n++],r=(i>127)+(i>223)+(i>239);if(n+r>e.length)return{s:t,r:As(e,n-1)};if(!r)t+=String.fromCharCode(i);else if(r==3)i=((i&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|i>>10,56320|i&1023);else if(r&1)t+=String.fromCharCode((i&31)<<6|e[n++]&63);else t+=String.fromCharCode((i&15)<<12|(e[n++]&63)<<6|e[n++]&63)}};function ym(e,t){if(t){var n=new bt(e.length);for(var i=0;i<e.length;++i)n[i]=e.charCodeAt(i);return n}if(vm)return vm.encode(e);var r=e.length,s=new bt(e.length+(e.length>>1)),o=0,a=function(u){s[o++]=u};for(var i=0;i<r;++i){if(o+5>s.length){var c=new bt(o+8+(r-i<<1));c.set(s),s=c}var l=e.charCodeAt(i);if(l<128||t)a(l);else if(l<2048)a(192|l>>6),a(128|l&63);else if(l>55295&&l<57344)l=65536+(l&1047552)|e.charCodeAt(++i)&1023,a(240|l>>18),a(128|l>>12&63),a(128|l>>6&63),a(128|l&63);else a(224|l>>12),a(128|l>>6&63),a(128|l&63)}return As(s,0,o)}function Hv(e,t){if(t){var n="";for(var i=0;i<e.length;i+=16384)n+=String.fromCharCode.apply(null,e.subarray(i,i+16384));return n}else if(Vc)return Vc.decode(e);else{var r=Gv(e),{s,r:n}=r;if(n.length)Kt(8);return s}}var Vv=function(e,t){return t+30+Vn(e,t+26)+Vn(e,t+28)},Wv=function(e,t,n){var i=Vn(e,t+28),r=Hv(e.subarray(t+46,t+46+i),!(Vn(e,t+8)&2048)),s=t+46+i,o=Rn(e,t+20),a=n&&o==4294967295?$v(e,s):[o,Rn(e,t+24),Rn(e,t+42)],c=a[0],l=a[1],u=a[2];return[Vn(e,t+10),c,l,r,s+Vn(e,t+30)+Vn(e,t+32),u]},$v=function(e,t){for(;Vn(e,t)!=1;t+=4+Vn(e,t+2));return[zc(e,t+12),zc(e,t+4),zc(e,t+20)]},Wc=function(e){var t=0;if(e)for(var n in e){var i=e[n].length;if(i>65535)Kt(9);t+=i+4}return t},bm=function(e,t,n,i,r,s,o,a){var c=i.length,l=n.extra,u=a&&a.length,f=Wc(l);if(Wt(e,t,o!=null?33639248:67324752),t+=4,o!=null)e[t++]=20,e[t++]=n.os;e[t]=20,t+=2,e[t++]=n.flag<<1|(s<0&&8),e[t++]=r&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var h=new Date(n.mtime==null?Date.now():n.mtime),d=h.getFullYear()-1980;if(d<0||d>119)Kt(10);if(Wt(e,t,d<<25|h.getMonth()+1<<21|h.getDate()<<16|h.getHours()<<11|h.getMinutes()<<5|h.getSeconds()>>1),t+=4,s!=-1)Wt(e,t,n.crc),Wt(e,t+4,s<0?-s-2:s),Wt(e,t+8,n.size);if(Wt(e,t+12,c),Wt(e,t+14,f),t+=16,o!=null)Wt(e,t,u),Wt(e,t+6,n.attrs),Wt(e,t+10,o),t+=14;if(e.set(i,t),t+=c,f)for(var g in l){var y=l[g],p=y.length;Wt(e,t,+g),Wt(e,t+2,p),e.set(y,t+4),t+=4+p}if(u)e.set(a,t),t+=u;return t},Zv=function(e,t,n,i,r){Wt(e,t,101010256),Wt(e,t+8,n),Wt(e,t+10,n),Wt(e,t+12,i),Wt(e,t+16,r)};function Im(e,t){if(!t)t={};var n={},i=[];Cm(e,"",n,t);var r=0,s=0;for(var o in n){var a=n[o],c=a[0],l=a[1],u=l.level==0?0:8,f=ym(o),h=f.length,d=l.comment,g=d&&ym(d),y=g&&g.length,p=Wc(l.extra);if(h>65535)Kt(11);var m=u?zv(c,l):c,A=m.length,T=Ov();T.p(c),i.push(Rm(l,{size:c.length,crc:T.d(),c:m,f,m:g,u:h!=o.length||g&&d.length!=y,o:r,compression:u})),r+=30+h+p+A,s+=76+2*(h+p)+(y||0)+A}var v=new bt(s+22),w=r,E=s-r;for(var R=0;R<i.length;++R){var f=i[R];bm(v,f.o,f,f.f,f.u,f.c.length);var _=30+f.f.length+Wc(f.extra);v.set(f.c,f.o+_),bm(v,r,f,f.f,f.u,f.c.length,f.o,f.m),r+=16+_+(f.m?f.m.length:0)}return Zv(v,r,i.length,E,w),v}function Pm(e,t){var n={},i=e.length-22;for(;Rn(e,i)!=101010256;--i)if(!i||e.length-i>65558)Kt(13);var r=Vn(e,i+8);if(!r)return{};var s=Rn(e,i+16),o=s==4294967295||r==65535;if(o){var a=Rn(e,i-12);if(o=Rn(e,a)==101075792,o)r=Rn(e,a+32),s=Rn(e,a+48)}var c=t&&t.filter;for(var l=0;l<r;++l){var u=Wv(e,s,o),f=u[0],h=u[1],d=u[2],g=u[3],y=u[4],p=u[5],m=Vv(e,p);if(s=y,!c||c({name:g,size:h,originalSize:d,compression:f}))if(!f)n[g]=As(e,m,m+h);else if(f==8)n[g]=kv(e.subarray(m,m+h),{out:new bt(d)});else Kt(14,"unknown compression type "+f)}return n}var si=67108864,Xc=Zt().regex(/^[a-z][a-z0-9_-]{0,79}$/),Xv=Zt().regex(/^sha256:[a-f0-9]{64}$/),Lm=Ms({version:ov("kiln.asset.v1"),assetId:Xc,revisionId:Xc,parentRevision:Xc.optional(),name:Zt().min(1).max(200),tags:ko(Zt().max(80)).max(30),createdAt:Zt().datetime(),description:Zt().max(4000).optional(),brief:Zt().max(8000).optional(),attribution:Ms({model:Zt().max(200).optional(),harness:Zt().max(200).optional(),author:Zt().max(200).optional()}).optional(),editable:Yx(),files:fm(Zt(),Ms({sha256:Xv,bytes:Zx().int().nonnegative().max(si)})),build:Ms({engine:Zt(),options:fm(Zt(),nr()),warnings:ko(Zt()),integration:nr().optional(),qa:nr().optional(),dependencies:ko(nr()).optional(),rebuild:dm(["engine-required","external-dependencies-required"])}).optional(),preview:Ms({fidelity:nr().optional(),error:Zt().optional()}).optional()}),qv=new Set(["asset.glb","source.kiln.js","preview.png"]);function Nm(e){let t=Lm.parse(e.manifest),n=Object.keys(e.files);if(n.length!==Object.keys(t.files).length||!n.includes("asset.glb"))throw Error("Asset file inventory mismatch");let i=0;for(let r of n){if(!qv.has(r)||!t.files[r]||t.files[r].bytes!==e.files[r].length)throw Error("Invalid asset file inventory");i+=e.files[r].length}if(i>si||t.editable!==n.includes("source.kiln.js"))throw Error("Invalid asset size or source inventory");if((e.files["source.kiln.js"]?.length??0)>1048576)throw Error("Source exceeds 1 MiB");qc(e.files["asset.glb"])}function qc(e){if(e.length<20||e.length>si)throw Error("Invalid GLB size");let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t.getUint32(0,!0)!==1179937895||t.getUint32(4,!0)!==2||t.getUint32(8,!0)!==e.length||t.getUint32(16,!0)!==1313821514)throw Error("Invalid GLB header");let n=20+t.getUint32(12,!0);if(n>e.length)throw Error("Invalid GLB JSON length");let i=JSON.parse(new TextDecoder().decode(e.subarray(20,n)));for(let r of[...i.buffers??[],...i.images??[]])if(r.uri&&!String(r.uri).startsWith("data:"))throw Error("GLB must embed its resources")}function Yc(e){if(!e.length||e.length>100)throw Error("Bundle requires 1..100 revisions");let t={},n=0;for(let i of e){Nm(i);let r=`${i.manifest.assetId}/${i.manifest.revisionId}/`;if(t[`${r}manifest.json`])throw Error("Duplicate bundle revision");t[`${r}manifest.json`]=new TextEncoder().encode(JSON.stringify(i.manifest,null,2));for(let[s,o]of Object.entries(i.files))t[r+s]=o}for(let i of Object.values(t))n+=i.length;if(n>si)throw Error("Bundle exceeds 64 MiB");return Im(t,{level:0})}function Dm(e){if(e.length>si+1048576)throw Error("Bundle exceeds 64 MiB");let t=0,n=0,i=Pm(e,{filter:(o)=>{if(t+=o.originalSize,n++,t>si||n>400||!/^[a-z][a-z0-9_-]{0,79}\/[a-z][a-z0-9_-]{0,79}\/(manifest\.json|asset\.glb|source\.kiln\.js|preview\.png)$/.test(o.name))throw Error("Unsafe or oversized asset bundle");return!0}}),r=[],s=new Set;for(let[o,a]of Object.entries(i)){if(!o.endsWith("/manifest.json"))continue;if(a.length>1048576)throw Error("Manifest exceeds 1 MiB");let c=Lm.parse(JSON.parse(new TextDecoder().decode(a))),l=`${c.assetId}/${c.revisionId}/`;if(o!==`${l}manifest.json`)throw Error("Bundle identity mismatch");let u={manifest:c,files:{}};s.add(o);for(let f of Object.keys(c.files)){if(!i[l+f])throw Error("Bundle file missing");u.files[f]=i[l+f],s.add(l+f)}Nm(u),r.push(u)}if(!r.length||s.size!==Object.keys(i).length)throw Error("Incomplete asset bundle");return r}var _g="185",Ni={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Di={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},xg=0,Ml=1,vg=2;var ks=1,yg=2,Zr=3,Ui=0,Yt=1,bn=2,Yn=0,Bs=1,wl=2,Tl=3,El=4,bg=5;var Xr=100,Sg=101,Mg=102,wg=103,Tg=104,Eg=200,Ag=201,Rg=202,Cg=203,Ig=204,Pg=205,Lg=206,Ng=207,Dg=208,Ug=209,Og=210,Fg=211,zg=212,kg=213,Bg=214,Gg=0,Hg=1,Vg=2,Al=3,Wg=4,$g=5,Zg=6,Xg=7,qg=0,Yg=1,jg=2,Un=0,Rl=1,Cl=2,Il=3,Gs=4,Pl=5,Ll=6,Nl=7;var qr=301,ur=302,ga=303,_a=304,Hs=306,Yr=1000,jr=1001,xa=1002,On=1003,va=1004;var hr=1005;var Gt=1006,Jr=1007;var jn=1008;var Fn=1009,Jg=1010,Kg=1011,Vs=1012,Dl=1013,Oi=1014,di=1015,pi=1016,Ul=1017,Ol=1018,Kr=1020,Qg=35902,e_=35899,t_=1021,n_=1022,Jn=1023,fr=1026,dr=1027,i_=1028,Fl=1029,pr=1030,zl=1031;var kl=1033,ya=33776,ba=33777,Sa=33778,Ma=33779,Bl=35840,Gl=35841,Hl=35842,Vl=35843,Wl=36196,$l=37492,Zl=37496,Xl=37488,ql=37489,wa=37490,Yl=37491,jl=37808,Jl=37809,Kl=37810,Ql=37811,eu=37812,tu=37813,nu=37814,iu=37815,ru=37816,su=37817,ou=37818,au=37819,cu=37820,lu=37821,uu=36492,hu=36494,fu=36495,du=36283,pu=36284,Ta=36285,mu=36286;var gu=2300,Ea=2301;var _u=0,Ws=1,Qr=2;var xu=0,r_=1,mr="",Fi="srgb",hn="srgb-linear",vu="linear",ht="srgb";var s_=512,o_=513,a_=514,Aa=515,c_=516,l_=517,Ra=518,u_=519;var yu="300 es",bu=2000;function Yv(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function jv(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Vr(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function h_(){let e=Vr("canvas");return e.style.display="block",e}var Um={},Wr=null;function zs(...e){let t="THREE."+e.shift();if(Wr)Wr("log",t,...e);else console.log(t,...e)}function f_(e){let t=e[0];if(typeof t==="string"&&t.startsWith("TSL:")){let n=e[1];if(n&&n.isStackTrace)e[0]+=" "+n.getLocation();else e[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return e}function Me(...e){e=f_(e);let t="THREE."+e.shift();if(Wr)Wr("warn",t,...e);else{let n=e[0];if(n&&n.isStackTrace)console.warn(n.getError(t));else console.warn(t,...e)}}function Ne(...e){e=f_(e);let t="THREE."+e.shift();if(Wr)Wr("error",t,...e);else{let n=e[0];if(n&&n.isStackTrace)console.error(n.getError(t));else console.error(t,...e)}}function ar(...e){let t=e.join(" ");if(t in Um)return;Um[t]=!0,Me(...e)}function d_(e,t,n){return new Promise(function(i,r){function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}}setTimeout(s,n)})}var p_={[0]:1,[2]:6,[4]:7,[3]:5,[1]:0,[6]:2,[7]:4,[5]:3};class zn{addEventListener(e,t){if(this._listeners===void 0)this._listeners={};let n=this._listeners;if(n[e]===void 0)n[e]=[];if(n[e].indexOf(t)===-1)n[e].push(t)}hasEventListener(e,t){let n=this._listeners;if(n===void 0)return!1;return n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let i=n[e];if(i!==void 0){let r=i.indexOf(t);if(r!==-1)i.splice(r,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 i=n.slice(0);for(let r=0,s=i.length;r<s;r++)i[r].call(this,e);e.target=null}}}var Xt=["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"],Om=1234567,Os=Math.PI/180,cr=180/Math.PI;function Dn(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Xt[e&255]+Xt[e>>8&255]+Xt[e>>16&255]+Xt[e>>24&255]+"-"+Xt[t&255]+Xt[t>>8&255]+"-"+Xt[t>>16&15|64]+Xt[t>>24&255]+"-"+Xt[n&63|128]+Xt[n>>8&255]+"-"+Xt[n>>16&255]+Xt[n>>24&255]+Xt[i&255]+Xt[i>>8&255]+Xt[i>>16&255]+Xt[i>>24&255]).toLowerCase()}function $e(e,t,n){return Math.max(t,Math.min(n,e))}function Su(e,t){return(e%t+t)%t}function Jv(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)}function Kv(e,t,n){if(e!==t)return(n-e)/(t-e);else return 0}function Fs(e,t,n){return(1-n)*e+n*t}function Qv(e,t,n,i){return Fs(e,t,1-Math.exp(-n*i))}function ey(e,t=1){return t-Math.abs(Su(e,t*2)-t)}function ty(e,t,n){if(e<=t)return 0;if(e>=n)return 1;return e=(e-t)/(n-t),e*e*(3-2*e)}function ny(e,t,n){if(e<=t)return 0;if(e>=n)return 1;return e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10)}function iy(e,t){return e+Math.floor(Math.random()*(t-e+1))}function ry(e,t){return e+Math.random()*(t-e)}function sy(e){return e*(0.5-Math.random())}function oy(e){if(e!==void 0)Om=e;let t=Om+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function ay(e){return e*Os}function cy(e){return e*cr}function ly(e){return(e&e-1)===0&&e!==0}function uy(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))}function hy(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function fy(e,t,n,i,r){let{cos:s,sin:o}=Math,a=s(n/2),c=o(n/2),l=s((t+i)/2),u=o((t+i)/2),f=s((t-i)/2),h=o((t-i)/2),d=s((i-t)/2),g=o((i-t)/2);switch(r){case"XYX":e.set(a*u,c*f,c*h,a*l);break;case"YZY":e.set(c*h,a*u,c*f,a*l);break;case"ZXZ":e.set(c*f,c*h,a*u,a*l);break;case"XZX":e.set(a*u,c*g,c*d,a*l);break;case"YXY":e.set(c*d,a*u,c*g,a*l);break;case"ZYZ":e.set(c*g,c*d,a*u,a*l);break;default:Me("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function Nn(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error("THREE.MathUtils: Invalid component type.")}}function rt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error("THREE.MathUtils: Invalid component type.")}}var $s={DEG2RAD:Os,RAD2DEG:cr,generateUUID:Dn,clamp:$e,euclideanModulo:Su,mapLinear:Jv,inverseLerp:Kv,lerp:Fs,damp:Qv,pingpong:ey,smoothstep:ty,smootherstep:ny,randInt:iy,randFloat:ry,randFloatSpread:sy,seededRandom:oy,degToRad:ay,radToDeg:cy,isPowerOfTwo:ly,ceilPowerOfTwo:uy,floorPowerOfTwo:hy,setQuaternionFromProperEuler:fy,normalize:rt,denormalize:Nn};class Ie{static{Ie.prototype.isVector2=!0}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 Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error("THREE.Vector2: 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,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[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=$e(this.x,e.x,t.x),this.y=$e(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=$e(this.x,e,t),this.y=$e(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar($e(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($e(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),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Bt{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,r,s,o){let a=n[i+0],c=n[i+1],l=n[i+2],u=n[i+3],f=r[s+0],h=r[s+1],d=r[s+2],g=r[s+3];if(u!==g||a!==f||c!==h||l!==d){let y=a*f+c*h+l*d+u*g;if(y<0)f=-f,h=-h,d=-d,g=-g,y=-y;let p=1-o;if(y<0.9995){let m=Math.acos(y),A=Math.sin(m);p=Math.sin(p*m)/A,o=Math.sin(o*m)/A,a=a*p+f*o,c=c*p+h*o,l=l*p+d*o,u=u*p+g*o}else{a=a*p+f*o,c=c*p+h*o,l=l*p+d*o,u=u*p+g*o;let m=1/Math.sqrt(a*a+c*c+l*l+u*u);a*=m,c*=m,l*=m,u*=m}}e[t]=a,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,s){let o=n[i],a=n[i+1],c=n[i+2],l=n[i+3],u=r[s],f=r[s+1],h=r[s+2],d=r[s+3];return e[t]=o*d+l*u+a*h-c*f,e[t+1]=a*d+l*f+c*u-o*h,e[t+2]=c*d+l*h+o*f-a*u,e[t+3]=l*d-o*u-a*f-c*h,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,i){return this._x=e,this._y=t,this._z=n,this._w=i,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{_x:n,_y:i,_z:r,_order:s}=e,{cos:o,sin:a}=Math,c=o(n/2),l=o(i/2),u=o(r/2),f=a(n/2),h=a(i/2),d=a(r/2);switch(s){case"XYZ":this._x=f*l*u+c*h*d,this._y=c*h*u-f*l*d,this._z=c*l*d+f*h*u,this._w=c*l*u-f*h*d;break;case"YXZ":this._x=f*l*u+c*h*d,this._y=c*h*u-f*l*d,this._z=c*l*d-f*h*u,this._w=c*l*u+f*h*d;break;case"ZXY":this._x=f*l*u-c*h*d,this._y=c*h*u+f*l*d,this._z=c*l*d+f*h*u,this._w=c*l*u-f*h*d;break;case"ZYX":this._x=f*l*u-c*h*d,this._y=c*h*u+f*l*d,this._z=c*l*d-f*h*u,this._w=c*l*u+f*h*d;break;case"YZX":this._x=f*l*u+c*h*d,this._y=c*h*u+f*l*d,this._z=c*l*d-f*h*u,this._w=c*l*u-f*h*d;break;case"XZY":this._x=f*l*u-c*h*d,this._y=c*h*u-f*l*d,this._z=c*l*d+f*h*u,this._w=c*l*u+f*h*d;break;default:Me("Quaternion: .setFromEuler() encountered an unknown order: "+s)}if(t===!0)this._onChangeCallback();return this}setFromAxisAngle(e,t){let n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],o=t[5],a=t[9],c=t[2],l=t[6],u=t[10],f=n+o+u;if(f>0){let h=0.5/Math.sqrt(f+1);this._w=0.25/h,this._x=(l-a)*h,this._y=(r-c)*h,this._z=(s-i)*h}else if(n>o&&n>u){let h=2*Math.sqrt(1+n-o-u);this._w=(l-a)/h,this._x=0.25*h,this._y=(i+s)/h,this._z=(r+c)/h}else if(o>u){let h=2*Math.sqrt(1+o-n-u);this._w=(r-c)/h,this._x=(i+s)/h,this._y=0.25*h,this._z=(a+l)/h}else{let h=2*Math.sqrt(1+u-n-o);this._w=(s-i)/h,this._x=(r+c)/h,this._y=(a+l)/h,this._z=0.25*h}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;if(n<0.00000001)if(n=0,Math.abs(e.x)>Math.abs(e.z))this._x=-e.y,this._y=e.x,this._z=0,this._w=n;else this._x=0,this._y=-e.z,this._z=e.y,this._w=n;else 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;return this.normalize()}angleTo(e){return 2*Math.acos(Math.abs($e(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let i=Math.min(1,t/n);return this.slerp(e,i),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();if(e===0)this._x=0,this._y=0,this._z=0,this._w=1;else e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e;return this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let{_x:n,_y:i,_z:r,_w:s}=e,{_x:o,_y:a,_z:c,_w:l}=t;return this._x=n*l+s*o+i*c-r*a,this._y=i*l+s*a+r*o-n*c,this._z=r*l+s*c+n*a-i*o,this._w=s*l-n*o-i*a-r*c,this._onChangeCallback(),this}slerp(e,t){let{_x:n,_y:i,_z:r,_w:s}=e,o=this.dot(e);if(o<0)n=-n,i=-i,r=-r,s=-s,o=-o;let a=1-t;if(o<0.9995){let c=Math.acos(o),l=Math.sin(c);a=Math.sin(a*c)/l,t=Math.sin(t*c)/l,this._x=this._x*a+n*t,this._y=this._y*a+i*t,this._z=this._z*a+r*t,this._w=this._w*a+s*t,this._onChangeCallback()}else this._x=this._x*a+n*t,this._y=this._y*a+i*t,this._z=this._z*a+r*t,this._w=this._w*a+s*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(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*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}}class N{static{N.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){if(n===void 0)n=this.z;return 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 Error("THREE.Vector3: 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 Error("THREE.Vector3: 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(Fm.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Fm.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){let t=this.x,n=this.y,i=this.z,{x:r,y:s,z:o,w:a}=e,c=2*(s*i-o*n),l=2*(o*t-r*i),u=2*(r*n-s*t);return this.x=t+a*c+s*u-o*l,this.y=n+a*l+o*c-r*u,this.z=i+a*u+r*l-s*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,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,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=$e(this.x,e.x,t.x),this.y=$e(this.y,e.y,t.y),this.z=$e(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=$e(this.x,e,t),this.y=$e(this.y,e,t),this.z=$e(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar($e(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{x:n,y:i,z:r}=e,{x:s,y:o,z:a}=t;return this.x=i*a-r*o,this.y=r*s-n*a,this.z=n*o-i*s,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 jc.copy(this).projectOnVector(e),this.sub(jc)}reflect(e){return this.sub(jc.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($e(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}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 i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*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(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,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}}var jc=new N,Fm=new Bt;class Ue{static{Ue.prototype.isMatrix3=!0}constructor(e,t,n,i,r,s,o,a,c){if(this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0)this.set(e,t,n,i,r,s,o,a,c)}set(e,t,n,i,r,s,o,a,c){let l=this.elements;return l[0]=e,l[1]=i,l[2]=o,l[3]=t,l[4]=r,l[5]=a,l[6]=n,l[7]=s,l[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,i=t.elements,r=this.elements,s=n[0],o=n[3],a=n[6],c=n[1],l=n[4],u=n[7],f=n[2],h=n[5],d=n[8],g=i[0],y=i[3],p=i[6],m=i[1],A=i[4],T=i[7],v=i[2],w=i[5],E=i[8];return r[0]=s*g+o*m+a*v,r[3]=s*y+o*A+a*w,r[6]=s*p+o*T+a*E,r[1]=c*g+l*m+u*v,r[4]=c*y+l*A+u*w,r[7]=c*p+l*T+u*E,r[2]=f*g+h*m+d*v,r[5]=f*y+h*A+d*w,r[8]=f*p+h*T+d*E,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],i=e[2],r=e[3],s=e[4],o=e[5],a=e[6],c=e[7],l=e[8];return t*s*l-t*o*c-n*r*l+n*o*a+i*r*c-i*s*a}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],o=e[5],a=e[6],c=e[7],l=e[8],u=l*s-o*c,f=o*a-l*r,h=c*r-s*a,d=t*u+n*f+i*h;if(d===0)return this.set(0,0,0,0,0,0,0,0,0);let g=1/d;return e[0]=u*g,e[1]=(i*c-l*n)*g,e[2]=(o*n-i*s)*g,e[3]=f*g,e[4]=(l*t-i*a)*g,e[5]=(i*r-o*t)*g,e[6]=h*g,e[7]=(n*a-c*t)*g,e[8]=(s*t-n*r)*g,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,i,r,s,o){let a=Math.cos(r),c=Math.sin(r);return this.set(n*a,n*c,-n*(a*s+c*o)+s+e,-i*c,i*a,-i*(-c*s+a*o)+o+t,0,0,1),this}scale(e,t){return ar("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(Jc.makeScale(e,t)),this}rotate(e){return ar("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(Jc.makeRotation(-e)),this}translate(e,t){return ar("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(Jc.makeTranslation(e,t)),this}makeTranslation(e,t){if(e.isVector2)this.set(1,0,e.x,0,1,e.y,0,0,1);else this.set(1,0,e,0,1,t,0,0,1);return 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 i=0;i<9;i++)if(t[i]!==n[i])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)}}var Jc=new Ue,zm=new Ue().set(0.4123908,0.3575843,0.1804808,0.212639,0.7151687,0.0721923,0.0193308,0.1191948,0.9505322),km=new Ue().set(3.2409699,-1.5373832,-0.4986108,-0.9692436,1.8759675,0.0415551,0.0556301,-0.203977,1.0569715);function dy(){let e={enabled:!0,workingColorSpace:"srgb-linear",spaces:{},convert:function(r,s,o){if(this.enabled===!1||s===o||!s||!o)return r;if(this.spaces[s].transfer==="srgb")r.r=fi(r.r),r.g=fi(r.g),r.b=fi(r.b);if(this.spaces[s].primaries!==this.spaces[o].primaries)r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[o].fromXYZ);if(this.spaces[o].transfer==="srgb")r.r=Hr(r.r),r.g=Hr(r.g),r.b=Hr(r.b);return 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){if(r==="")return"linear";return 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,o){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[o].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 ar("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return ar("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(r,s)}},t=[0.64,0.33,0.3,0.6,0.15,0.06],n=[0.2126,0.7152,0.0722],i=[0.3127,0.329];return e.define({["srgb-linear"]:{primaries:t,whitePoint:i,transfer:"linear",toXYZ:zm,fromXYZ:km,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:"srgb"},outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}},["srgb"]:{primaries:t,whitePoint:i,transfer:"srgb",toXYZ:zm,fromXYZ:km,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}}}),e}var We=dy();function fi(e){return e<0.04045?e*0.0773993808:Math.pow(e*0.9478672986+0.0521327014,2.4)}function Hr(e){return e<0.0031308?e*12.92:1.055*Math.pow(e,0.41666)-0.055}var Rr;class Mu{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if(typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{if(Rr===void 0)Rr=Vr("canvas");Rr.width=e.width,Rr.height=e.height;let i=Rr.getContext("2d");if(e instanceof ImageData)i.putImageData(e,0,0);else i.drawImage(e,0,0,e.width,e.height);n=Rr}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=Vr("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let s=0;s<r.length;s++)r[s]=fi(r[s]/255)*255;return n.putImageData(i,0,0),t}else if(e.data){let t=e.data.slice(0);for(let n=0;n<t.length;n++)if(t instanceof Uint8Array||t instanceof Uint8ClampedArray)t[n]=Math.floor(fi(t[n]/255)*255);else t[n]=fi(t[n]);return{data:t,width:e.width,height:e.height}}else return Me("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}var py=0;class Zs{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:py++}),this.uuid=Dn(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)e.set(t.videoWidth,t.videoHeight,0);else if(typeof VideoFrame<"u"&&t instanceof VideoFrame)e.set(t.displayWidth,t.displayHeight,0);else if(t!==null)e.set(t.width,t.height,t.depth||0);else e.set(0,0,0);return e}set needsUpdate(e){if(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:""},i=this.data;if(i!==null){let r;if(Array.isArray(i)){r=[];for(let s=0,o=i.length;s<o;s++)if(i[s].isDataTexture)r.push(Kc(i[s].image));else r.push(Kc(i[s]))}else r=Kc(i);n.url=r}if(!t)e.images[this.uuid]=n;return n}}function Kc(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap)return Mu.getDataURL(e);else if(e.data)return{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name};else return Me("Texture: Unable to serialize Texture."),{}}var my=0,Qc=new N;class wt extends zn{constructor(e=wt.DEFAULT_IMAGE,t=wt.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,o=1023,a=1009,c=wt.DEFAULT_ANISOTROPY,l=""){super();this.isTexture=!0,Object.defineProperty(this,"id",{value:my++}),this.uuid=Dn(),this.name="",this.source=new Zs(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=a,this.offset=new Ie(0,0),this.repeat=new Ie(1,1),this.center=new Ie(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ue,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=l,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=e&&e.depth&&e.depth>1?!0:!1,this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Qc).x}get height(){return this.source.getSize(Qc).y}get depth(){return this.source.getSize(Qc).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){Me(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){Me(`Texture.setValues(): property '${t}' does not exist.`);continue}if(i&&n&&(i.isVector2&&n.isVector2))i.copy(n);else if(i&&n&&(i.isVector3&&n.isVector3))i.copy(n);else if(i&&n&&(i.isMatrix3&&n.isMatrix3))i.copy(n);else 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};if(Object.keys(this.userData).length>0)n.userData=this.userData;if(!t)e.textures[this.uuid]=n;return n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case 1000:e.x=e.x-Math.floor(e.x);break;case 1001:e.x=e.x<0?0:1;break;case 1002:if(Math.abs(Math.floor(e.x)%2)===1)e.x=Math.ceil(e.x)-e.x;else e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case 1000:e.y=e.y-Math.floor(e.y);break;case 1001:e.y=e.y<0?0:1;break;case 1002:if(Math.abs(Math.floor(e.y)%2)===1)e.y=Math.ceil(e.y)-e.y;else e.y=e.y-Math.floor(e.y);break}if(this.flipY)e.y=1-e.y;return e}set needsUpdate(e){if(e===!0)this.version++,this.source.needsUpdate=!0}set needsPMREMUpdate(e){if(e===!0)this.pmremVersion++}}wt.DEFAULT_IMAGE=null;wt.DEFAULT_MAPPING=300;wt.DEFAULT_ANISOTROPY=1;class st{static{st.prototype.isVector4=!0}constructor(e=0,t=0,n=0,i=1){this.x=e,this.y=t,this.z=n,this.w=i}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,i){return this.x=e,this.y=t,this.z=n,this.w=i,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 Error("THREE.Vector4: 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 Error("THREE.Vector4: 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,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,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);if(t<0.0001)this.x=1,this.y=0,this.z=0;else this.x=e.x/t,this.y=e.y/t,this.z=e.z/t;return this}setAxisAngleFromRotationMatrix(e){let t,n,i,r,s=0.01,o=0.1,a=e.elements,c=a[0],l=a[4],u=a[8],f=a[1],h=a[5],d=a[9],g=a[2],y=a[6],p=a[10];if(Math.abs(l-f)<0.01&&Math.abs(u-g)<0.01&&Math.abs(d-y)<0.01){if(Math.abs(l+f)<0.1&&Math.abs(u+g)<0.1&&Math.abs(d+y)<0.1&&Math.abs(c+h+p-3)<0.1)return this.set(1,0,0,0),this;t=Math.PI;let A=(c+1)/2,T=(h+1)/2,v=(p+1)/2,w=(l+f)/4,E=(u+g)/4,R=(d+y)/4;if(A>T&&A>v)if(A<0.01)n=0,i=0.707106781,r=0.707106781;else n=Math.sqrt(A),i=w/n,r=E/n;else if(T>v)if(T<0.01)n=0.707106781,i=0,r=0.707106781;else i=Math.sqrt(T),n=w/i,r=R/i;else if(v<0.01)n=0.707106781,i=0.707106781,r=0;else r=Math.sqrt(v),n=E/r,i=R/r;return this.set(n,i,r,t),this}let m=Math.sqrt((y-d)*(y-d)+(u-g)*(u-g)+(f-l)*(f-l));if(Math.abs(m)<0.001)m=1;return this.x=(y-d)/m,this.y=(u-g)/m,this.z=(f-l)/m,this.w=Math.acos((c+h+p-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=$e(this.x,e.x,t.x),this.y=$e(this.y,e.y,t.y),this.z=$e(this.z,e.z,t.z),this.w=$e(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=$e(this.x,e,t),this.y=$e(this.y,e,t),this.z=$e(this.z,e,t),this.w=$e(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar($e(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}}class wu extends zn{constructor(e=1,t=1,n={}){super();n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new st(0,0,e,t),this.scissorTest=!1,this.viewport=new st(0,0,e,t),this.textures=[];let i={width:e,height:t,depth:n.depth},r=new wt(i),s=n.count;for(let o=0;o<s;o++)this.textures[o]=r.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,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){let t={minFilter:1006,generateMipmaps:!1,flipY:!1,internalFormat:null};if(e.mapping!==void 0)t.mapping=e.mapping;if(e.wrapS!==void 0)t.wrapS=e.wrapS;if(e.wrapT!==void 0)t.wrapT=e.wrapT;if(e.wrapR!==void 0)t.wrapR=e.wrapR;if(e.magFilter!==void 0)t.magFilter=e.magFilter;if(e.minFilter!==void 0)t.minFilter=e.minFilter;if(e.format!==void 0)t.format=e.format;if(e.type!==void 0)t.type=e.type;if(e.anisotropy!==void 0)t.anisotropy=e.anisotropy;if(e.colorSpace!==void 0)t.colorSpace=e.colorSpace;if(e.flipY!==void 0)t.flipY=e.flipY;if(e.generateMipmaps!==void 0)t.generateMipmaps=e.generateMipmaps;if(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){if(this._depthTexture!==null)this._depthTexture.renderTarget=null;if(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 i=0,r=this.textures.length;i<r;i++)if(this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=n,this.textures[i].isData3DTexture!==!0)this.textures[i].isArrayTexture=this.textures[i].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 i=Object.assign({},e.textures[t].image);this.textures[t].source=new Zs(i)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null)this.depthTexture=e.depthTexture.clone();return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Sn extends wu{constructor(e=1,t=1,n={}){super(e,t,n);this.isWebGLRenderTarget=!0}}class Ca extends wt{constructor(e=null,t=1,n=1,i=1){super(null);this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class Tu extends wt{constructor(e=null,t=1,n=1,i=1){super(null);this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class ze{static{ze.prototype.isMatrix4=!0}constructor(e,t,n,i,r,s,o,a,c,l,u,f,h,d,g,y){if(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,i,r,s,o,a,c,l,u,f,h,d,g,y)}set(e,t,n,i,r,s,o,a,c,l,u,f,h,d,g,y){let p=this.elements;return p[0]=e,p[4]=t,p[8]=n,p[12]=i,p[1]=r,p[5]=s,p[9]=o,p[13]=a,p[2]=c,p[6]=l,p[10]=u,p[14]=f,p[3]=h,p[7]=d,p[11]=g,p[15]=y,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 ze().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){if(this.determinantAffine()===0)return e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this;return 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.determinantAffine()===0)return this.identity();let t=this.elements,n=e.elements,i=1/Cr.setFromMatrixColumn(e,0).length(),r=1/Cr.setFromMatrixColumn(e,1).length(),s=1/Cr.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,{x:n,y:i,z:r}=e,s=Math.cos(n),o=Math.sin(n),a=Math.cos(i),c=Math.sin(i),l=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){let f=s*l,h=s*u,d=o*l,g=o*u;t[0]=a*l,t[4]=-a*u,t[8]=c,t[1]=h+d*c,t[5]=f-g*c,t[9]=-o*a,t[2]=g-f*c,t[6]=d+h*c,t[10]=s*a}else if(e.order==="YXZ"){let f=a*l,h=a*u,d=c*l,g=c*u;t[0]=f+g*o,t[4]=d*o-h,t[8]=s*c,t[1]=s*u,t[5]=s*l,t[9]=-o,t[2]=h*o-d,t[6]=g+f*o,t[10]=s*a}else if(e.order==="ZXY"){let f=a*l,h=a*u,d=c*l,g=c*u;t[0]=f-g*o,t[4]=-s*u,t[8]=d+h*o,t[1]=h+d*o,t[5]=s*l,t[9]=g-f*o,t[2]=-s*c,t[6]=o,t[10]=s*a}else if(e.order==="ZYX"){let f=s*l,h=s*u,d=o*l,g=o*u;t[0]=a*l,t[4]=d*c-h,t[8]=f*c+g,t[1]=a*u,t[5]=g*c+f,t[9]=h*c-d,t[2]=-c,t[6]=o*a,t[10]=s*a}else if(e.order==="YZX"){let f=s*a,h=s*c,d=o*a,g=o*c;t[0]=a*l,t[4]=g-f*u,t[8]=d*u+h,t[1]=u,t[5]=s*l,t[9]=-o*l,t[2]=-c*l,t[6]=h*u+d,t[10]=f-g*u}else if(e.order==="XZY"){let f=s*a,h=s*c,d=o*a,g=o*c;t[0]=a*l,t[4]=-u,t[8]=c*l,t[1]=f*u+g,t[5]=s*l,t[9]=h*u-d,t[2]=d*u-h,t[6]=o*l,t[10]=g*u+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(gy,e,_y)}lookAt(e,t,n){let i=this.elements;if(ln.subVectors(e,t),ln.lengthSq()===0)ln.z=1;if(ln.normalize(),Ai.crossVectors(n,ln),Ai.lengthSq()===0){if(Math.abs(n.z)===1)ln.x+=0.0001;else ln.z+=0.0001;ln.normalize(),Ai.crossVectors(n,ln)}return Ai.normalize(),Ho.crossVectors(ln,Ai),i[0]=Ai.x,i[4]=Ho.x,i[8]=ln.x,i[1]=Ai.y,i[5]=Ho.y,i[9]=ln.y,i[2]=Ai.z,i[6]=Ho.z,i[10]=ln.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,r=this.elements,s=n[0],o=n[4],a=n[8],c=n[12],l=n[1],u=n[5],f=n[9],h=n[13],d=n[2],g=n[6],y=n[10],p=n[14],m=n[3],A=n[7],T=n[11],v=n[15],w=i[0],E=i[4],R=i[8],_=i[12],S=i[1],F=i[5],C=i[9],z=i[13],J=i[2],O=i[6],H=i[10],V=i[14],U=i[3],K=i[7],Q=i[11],se=i[15];return r[0]=s*w+o*S+a*J+c*U,r[4]=s*E+o*F+a*O+c*K,r[8]=s*R+o*C+a*H+c*Q,r[12]=s*_+o*z+a*V+c*se,r[1]=l*w+u*S+f*J+h*U,r[5]=l*E+u*F+f*O+h*K,r[9]=l*R+u*C+f*H+h*Q,r[13]=l*_+u*z+f*V+h*se,r[2]=d*w+g*S+y*J+p*U,r[6]=d*E+g*F+y*O+p*K,r[10]=d*R+g*C+y*H+p*Q,r[14]=d*_+g*z+y*V+p*se,r[3]=m*w+A*S+T*J+v*U,r[7]=m*E+A*F+T*O+v*K,r[11]=m*R+A*C+T*H+v*Q,r[15]=m*_+A*z+T*V+v*se,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],i=e[8],r=e[12],s=e[1],o=e[5],a=e[9],c=e[13],l=e[2],u=e[6],f=e[10],h=e[14],d=e[3],g=e[7],y=e[11],p=e[15],m=a*h-c*f,A=o*h-c*u,T=o*f-a*u,v=s*h-c*l,w=s*f-a*l,E=s*u-o*l;return t*(g*m-y*A+p*T)-n*(d*m-y*v+p*w)+i*(d*A-g*v+p*E)-r*(d*T-g*w+y*E)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],i=e[8],r=e[1],s=e[5],o=e[9],a=e[2],c=e[6],l=e[10];return t*(s*l-o*c)-n*(r*l-o*a)+i*(r*c-s*a)}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 i=this.elements;if(e.isVector3)i[12]=e.x,i[13]=e.y,i[14]=e.z;else i[12]=e,i[13]=t,i[14]=n;return this}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],o=e[5],a=e[6],c=e[7],l=e[8],u=e[9],f=e[10],h=e[11],d=e[12],g=e[13],y=e[14],p=e[15],m=t*o-n*s,A=t*a-i*s,T=t*c-r*s,v=n*a-i*o,w=n*c-r*o,E=i*c-r*a,R=l*g-u*d,_=l*y-f*d,S=l*p-h*d,F=u*y-f*g,C=u*p-h*g,z=f*p-h*y,J=m*z-A*C+T*F+v*S-w*_+E*R;if(J===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let O=1/J;return e[0]=(o*z-a*C+c*F)*O,e[1]=(i*C-n*z-r*F)*O,e[2]=(g*E-y*w+p*v)*O,e[3]=(f*w-u*E-h*v)*O,e[4]=(a*S-s*z-c*_)*O,e[5]=(t*z-i*S+r*_)*O,e[6]=(y*T-d*E-p*A)*O,e[7]=(l*E-f*T+h*A)*O,e[8]=(s*C-o*S+c*R)*O,e[9]=(n*S-t*C-r*R)*O,e[10]=(d*w-g*T+p*m)*O,e[11]=(u*T-l*w-h*m)*O,e[12]=(o*_-s*F-a*R)*O,e[13]=(t*F-n*_+i*R)*O,e[14]=(g*A-d*v-y*m)*O,e[15]=(l*v-u*A+f*m)*O,this}scale(e){let t=this.elements,{x:n,y:i,z:r}=e;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,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],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){if(e.isVector3)this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1);else this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1);return 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),i=Math.sin(t),r=1-n,{x:s,y:o,z:a}=e,c=r*s,l=r*o;return this.set(c*s+n,c*o-i*a,c*a+i*o,0,c*o+i*a,l*o+n,l*a-i*s,0,c*a-i*o,l*a+i*s,r*a*a+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,i,r,s){return this.set(1,n,r,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){let i=this.elements,{_x:r,_y:s,_z:o,_w:a}=t,c=r+r,l=s+s,u=o+o,f=r*c,h=r*l,d=r*u,g=s*l,y=s*u,p=o*u,m=a*c,A=a*l,T=a*u,{x:v,y:w,z:E}=n;return i[0]=(1-(g+p))*v,i[1]=(h+T)*v,i[2]=(d-A)*v,i[3]=0,i[4]=(h-T)*w,i[5]=(1-(f+p))*w,i[6]=(y+m)*w,i[7]=0,i[8]=(d+A)*E,i[9]=(y-m)*E,i[10]=(1-(f+g))*E,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){let i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];let r=this.determinantAffine();if(r===0)return n.set(1,1,1),t.identity(),this;let s=Cr.set(i[0],i[1],i[2]).length(),o=Cr.set(i[4],i[5],i[6]).length(),a=Cr.set(i[8],i[9],i[10]).length();if(r<0)s=-s;Cn.copy(this);let c=1/s,l=1/o,u=1/a;return Cn.elements[0]*=c,Cn.elements[1]*=c,Cn.elements[2]*=c,Cn.elements[4]*=l,Cn.elements[5]*=l,Cn.elements[6]*=l,Cn.elements[8]*=u,Cn.elements[9]*=u,Cn.elements[10]*=u,t.setFromRotationMatrix(Cn),n.x=s,n.y=o,n.z=a,this}makePerspective(e,t,n,i,r,s,o=2000,a=!1){let c=this.elements,l=2*r/(t-e),u=2*r/(n-i),f=(t+e)/(t-e),h=(n+i)/(n-i),d,g;if(a)d=r/(s-r),g=s*r/(s-r);else if(o===2000)d=-(s+r)/(s-r),g=-2*s*r/(s-r);else if(o===2001)d=-s/(s-r),g=-s*r/(s-r);else throw Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=l,c[4]=0,c[8]=f,c[12]=0,c[1]=0,c[5]=u,c[9]=h,c[13]=0,c[2]=0,c[6]=0,c[10]=d,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,i,r,s,o=2000,a=!1){let c=this.elements,l=2/(t-e),u=2/(n-i),f=-(t+e)/(t-e),h=-(n+i)/(n-i),d,g;if(a)d=1/(s-r),g=s/(s-r);else if(o===2000)d=-2/(s-r),g=-(s+r)/(s-r);else if(o===2001)d=-1/(s-r),g=-r/(s-r);else throw Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=f,c[1]=0,c[5]=u,c[9]=0,c[13]=h,c[2]=0,c[6]=0,c[10]=d,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])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}}var Cr=new N,Cn=new ze,gy=new N(0,0,0),_y=new N(1,1,1),Ai=new N,Ho=new N,ln=new N,Bm=new ze,Gm=new Bt;class qn{constructor(e=0,t=0,n=0,i=qn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}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,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,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 i=e.elements,r=i[0],s=i[4],o=i[8],a=i[1],c=i[5],l=i[9],u=i[2],f=i[6],h=i[10];switch(t){case"XYZ":if(this._y=Math.asin($e(o,-1,1)),Math.abs(o)<0.9999999)this._x=Math.atan2(-l,h),this._z=Math.atan2(-s,r);else this._x=Math.atan2(f,c),this._z=0;break;case"YXZ":if(this._x=Math.asin(-$e(l,-1,1)),Math.abs(l)<0.9999999)this._y=Math.atan2(o,h),this._z=Math.atan2(a,c);else this._y=Math.atan2(-u,r),this._z=0;break;case"ZXY":if(this._x=Math.asin($e(f,-1,1)),Math.abs(f)<0.9999999)this._y=Math.atan2(-u,h),this._z=Math.atan2(-s,c);else this._y=0,this._z=Math.atan2(a,r);break;case"ZYX":if(this._y=Math.asin(-$e(u,-1,1)),Math.abs(u)<0.9999999)this._x=Math.atan2(f,h),this._z=Math.atan2(a,r);else this._x=0,this._z=Math.atan2(-s,c);break;case"YZX":if(this._z=Math.asin($e(a,-1,1)),Math.abs(a)<0.9999999)this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,r);else this._x=0,this._y=Math.atan2(o,h);break;case"XZY":if(this._z=Math.asin(-$e(s,-1,1)),Math.abs(s)<0.9999999)this._x=Math.atan2(f,c),this._y=Math.atan2(o,r);else this._x=Math.atan2(-l,h),this._y=0;break;default:Me("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}if(this._order=t,n===!0)this._onChangeCallback();return this}setFromQuaternion(e,t,n){return Bm.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Bm,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Gm.setFromEuler(this),this.setFromQuaternion(Gm,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){if(this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0)this._order=e[3];return 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}}qn.DEFAULT_ORDER="XYZ";class Ia{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}}var xy=0,Hm=new N,Ir=new Bt,oi=new ze,Vo=new N,Rs=new N,vy=new N,yy=new Bt,Vm=new N(1,0,0),Wm=new N(0,1,0),$m=new N(0,0,1),Zm={type:"added"},by={type:"removed"},Pr={type:"childadded",child:null},el={type:"childremoved",child:null};class at extends zn{constructor(){super();this.isObject3D=!0,Object.defineProperty(this,"id",{value:xy++}),this.uuid=Dn(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=at.DEFAULT_UP.clone();let e=new N,t=new qn,n=new Bt,i=new N(1,1,1);function r(){n.setFromEuler(t,!1)}function s(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(s),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:i},modelViewMatrix:{value:new ze},normalMatrix:{value:new Ue}}),this.matrix=new ze,this.matrixWorld=new ze,this.matrixAutoUpdate=at.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=at.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Ia,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){if(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 Ir.setFromAxisAngle(e,t),this.quaternion.multiply(Ir),this}rotateOnWorldAxis(e,t){return Ir.setFromAxisAngle(e,t),this.quaternion.premultiply(Ir),this}rotateX(e){return this.rotateOnAxis(Vm,e)}rotateY(e){return this.rotateOnAxis(Wm,e)}rotateZ(e){return this.rotateOnAxis($m,e)}translateOnAxis(e,t){return Hm.copy(e).applyQuaternion(this.quaternion),this.position.add(Hm.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Vm,e)}translateY(e){return this.translateOnAxis(Wm,e)}translateZ(e){return this.translateOnAxis($m,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(oi.copy(this.matrixWorld).invert())}lookAt(e,t,n){if(e.isVector3)Vo.copy(e);else Vo.set(e,t,n);let i=this.parent;if(this.updateWorldMatrix(!0,!1),Rs.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight)oi.lookAt(Rs,Vo,this.up);else oi.lookAt(Vo,Rs,this.up);if(this.quaternion.setFromRotationMatrix(oi),i)oi.extractRotation(i.matrixWorld),Ir.setFromRotationMatrix(oi),this.quaternion.premultiply(Ir.invert())}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}if(e===this)return Ne("Object3D.add: object can't be added as a child of itself.",e),this;if(e&&e.isObject3D)e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Zm),Pr.child=e,this.dispatchEvent(Pr),Pr.child=null;else Ne("Object3D.add: object not an instance of THREE.Object3D.",e);return 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);if(t!==-1)e.parent=null,this.children.splice(t,1),e.dispatchEvent(by),el.child=e,this.dispatchEvent(el),el.child=null;return this}removeFromParent(){let e=this.parent;if(e!==null)e.remove(this);return this}clear(){return this.remove(...this.children)}attach(e){if(this.updateWorldMatrix(!0,!1),oi.copy(this.matrixWorld).invert(),e.parent!==null)e.parent.updateWorldMatrix(!0,!1),oi.multiply(e.parent.matrixWorld);return e.applyMatrix4(oi),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Zm),Pr.child=e,this.dispatchEvent(Pr),Pr.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,i=this.children.length;n<i;n++){let s=this.children[n].getObjectByProperty(e,t);if(s!==void 0)return s}return}getObjectsByProperty(e,t,n=[]){if(this[e]===t)n.push(this);let i=this.children;for(let r=0,s=i.length;r<s;r++)i[r].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(Rs,e,vy),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Rs,yy,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,i=t.length;n<i;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;if(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{x:t,y:n,z:i}=e,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*n-r[8]*i,r[13]+=n-r[1]*t-r[5]*n-r[9]*i,r[14]+=i-r[2]*t-r[6]*n-r[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||e){if(this.matrixWorldAutoUpdate===!0)if(this.parent===null)this.matrixWorld.copy(this.matrix);else this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);this.matrixWorldNeedsUpdate=!1,e=!0}let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t,n=!1){let i=this.parent;if(e===!0&&i!==null)i.updateWorldMatrix(!0,!1);if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||n){if(this.matrixWorldAutoUpdate===!0)if(this.parent===null)this.matrixWorld.copy(this.matrix);else this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);this.matrixWorldNeedsUpdate=!1,n=!0}if(t===!0){let r=this.children;for(let s=0,o=r.length;s<o;s++)r[s].updateWorldMatrix(!1,!0,n)}}toJSON(e){let t=e===void 0||typeof e==="string",n={};if(t)e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"};let i={};if(i.uuid=this.uuid,i.type=this.type,this.name!=="")i.name=this.name;if(this.castShadow===!0)i.castShadow=!0;if(this.receiveShadow===!0)i.receiveShadow=!0;if(this.visible===!1)i.visible=!1;if(this.frustumCulled===!1)i.frustumCulled=!1;if(this.renderOrder!==0)i.renderOrder=this.renderOrder;if(this.static!==!1)i.static=this.static;if(Object.keys(this.userData).length>0)i.userData=this.userData;if(i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.pivot!==null)i.pivot=this.pivot.toArray();if(this.matrixAutoUpdate===!1)i.matrixAutoUpdate=!1;if(this.morphTargetDictionary!==void 0)i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary);if(this.morphTargetInfluences!==void 0)i.morphTargetInfluences=this.morphTargetInfluences.slice();if(this.isInstancedMesh){if(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null)i.instanceColor=this.instanceColor.toJSON()}if(this.isBatchedMesh){if(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map((o)=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map((o)=>({...o})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null)i.colorsTexture=this._colorsTexture.toJSON(e);if(this.boundingSphere!==null)i.boundingSphere=this.boundingSphere.toJSON();if(this.boundingBox!==null)i.boundingBox=this.boundingBox.toJSON()}function r(o,a){if(o[a.uuid]===void 0)o[a.uuid]=a.toJSON(e);return a.uuid}if(this.isScene){if(this.background){if(this.background.isColor)i.background=this.background.toJSON();else if(this.background.isTexture)i.background=this.background.toJSON(e).uuid}if(this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0)i.environment=this.environment.toJSON(e).uuid}else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let a=o.shapes;if(Array.isArray(a))for(let c=0,l=a.length;c<l;c++){let u=a[c];r(e.shapes,u)}else r(e.shapes,a)}}if(this.isSkinnedMesh){if(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0)r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid}if(this.material!==void 0)if(Array.isArray(this.material)){let o=[];for(let a=0,c=this.material.length;a<c;a++)o.push(r(e.materials,this.material[a]));i.material=o}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let o=0;o<this.children.length;o++)i.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let o=0;o<this.animations.length;o++){let a=this.animations[o];i.animations.push(r(e.animations,a))}}if(t){let o=s(e.geometries),a=s(e.materials),c=s(e.textures),l=s(e.images),u=s(e.shapes),f=s(e.skeletons),h=s(e.animations),d=s(e.nodes);if(o.length>0)n.geometries=o;if(a.length>0)n.materials=a;if(c.length>0)n.textures=c;if(l.length>0)n.images=l;if(u.length>0)n.shapes=u;if(f.length>0)n.skeletons=f;if(h.length>0)n.animations=h;if(d.length>0)n.nodes=d}return n.object=i,n;function s(o){let a=[];for(let c in o){let l=o[c];delete l.metadata,a.push(l)}return a}}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 i=e.children[n];this.add(i.clone())}return this}}at.DEFAULT_UP=new N(0,1,0);at.DEFAULT_MATRIX_AUTO_UPDATE=!0;at.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class Zn extends at{constructor(){super();this.isGroup=!0,this.type="Group"}}var Sy={type:"move"};class Xs{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){if(this._hand===null)this._hand=new Zn,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1};return this._hand}getTargetRaySpace(){if(this._targetRay===null)this._targetRay=new Zn,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new N,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new N;return this._targetRay}getGripSpace(){if(this._grip===null)this._grip=new Zn,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new N,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new N,this._grip.eventsEnabled=!1;return this._grip}dispatchEvent(e){if(this._targetRay!==null)this._targetRay.dispatchEvent(e);if(this._grip!==null)this._grip.dispatchEvent(e);if(this._hand!==null)this._hand.dispatchEvent(e);return 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){if(this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null)this._targetRay.visible=!1;if(this._grip!==null)this._grip.visible=!1;if(this._hand!==null)this._hand.visible=!1;return this}update(e,t,n){let i=null,r=null,s=null,o=this._targetRay,a=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){s=!0;for(let g of e.hand.values()){let y=t.getJointPose(g,n),p=this._getHandJoint(c,g);if(y!==null)p.matrix.fromArray(y.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=y.radius;p.visible=y!==null}let l=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],f=l.position.distanceTo(u.position),h=0.02,d=0.005;if(c.inputState.pinching&&f>h+d)c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this});else if(!c.inputState.pinching&&f<=h-d)c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this})}else if(a!==null&&e.gripSpace){if(r=t.getPose(e.gripSpace,n),r!==null){if(a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,r.linearVelocity)a.hasLinearVelocity=!0,a.linearVelocity.copy(r.linearVelocity);else a.hasLinearVelocity=!1;if(r.angularVelocity)a.hasAngularVelocity=!0,a.angularVelocity.copy(r.angularVelocity);else a.hasAngularVelocity=!1;if(a.eventsEnabled)a.dispatchEvent({type:"gripUpdated",data:e,target:this})}}if(o!==null){if(i=t.getPose(e.targetRaySpace,n),i===null&&r!==null)i=r;if(i!==null){if(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity)o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity);else o.hasLinearVelocity=!1;if(i.angularVelocity)o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity);else o.hasAngularVelocity=!1;this.dispatchEvent(Sy)}}}if(o!==null)o.visible=i!==null;if(a!==null)a.visible=r!==null;if(c!==null)c.visible=s!==null;return this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new Zn;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}var m_={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ri={h:0,s:0,l:0},Wo={h:0,s:0,l:0};function tl(e,t,n){if(n<0)n+=1;if(n>1)n-=1;if(n<0.16666666666666666)return e+(t-e)*6*n;if(n<0.5)return t;if(n<0.6666666666666666)return e+(t-e)*6*(0.6666666666666666-n);return e}class Le{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 i=e;if(i&&i.isColor)this.copy(i);else if(typeof i==="number")this.setHex(i);else if(typeof i==="string")this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t="srgb"){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,We.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=We.workingColorSpace){return this.r=e,this.g=t,this.b=n,We.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=We.workingColorSpace){if(e=Su(e,1),t=$e(t,0,1),n=$e(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=0.5?n*(1+t):n+t-n*t,s=2*n-r;this.r=tl(s,r,e+0.3333333333333333),this.g=tl(s,r,e),this.b=tl(s,r,e-0.3333333333333333)}return We.colorSpaceToWorking(this,i),this}setStyle(e,t="srgb"){function n(r){if(r===void 0)return;if(parseFloat(r)<1)Me("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r,s=i[1],o=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Me("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){let r=i[1],s=r.length;if(s===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);else if(s===6)return this.setHex(parseInt(r,16),t);else Me("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t="srgb"){let n=m_[e.toLowerCase()];if(n!==void 0)this.setHex(n,t);else Me("Color: Unknown color "+e);return 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=fi(e.r),this.g=fi(e.g),this.b=fi(e.b),this}copyLinearToSRGB(e){return this.r=Hr(e.r),this.g=Hr(e.g),this.b=Hr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e="srgb"){return We.workingToColorSpace(qt.copy(this),e),Math.round($e(qt.r*255,0,255))*65536+Math.round($e(qt.g*255,0,255))*256+Math.round($e(qt.b*255,0,255))}getHexString(e="srgb"){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=We.workingColorSpace){We.workingToColorSpace(qt.copy(this),t);let{r:n,g:i,b:r}=qt,s=Math.max(n,i,r),o=Math.min(n,i,r),a,c,l=(o+s)/2;if(o===s)a=0,c=0;else{let u=s-o;switch(c=l<=0.5?u/(s+o):u/(2-s-o),s){case n:a=(i-r)/u+(i<r?6:0);break;case i:a=(r-n)/u+2;break;case r:a=(n-i)/u+4;break}a/=6}return e.h=a,e.s=c,e.l=l,e}getRGB(e,t=We.workingColorSpace){return We.workingToColorSpace(qt.copy(this),t),e.r=qt.r,e.g=qt.g,e.b=qt.b,e}getStyle(e="srgb"){We.workingToColorSpace(qt.copy(this),e);let{r:t,g:n,b:i}=qt;if(e!=="srgb")return`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`;return`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(i*255)})`}offsetHSL(e,t,n){return this.getHSL(Ri),this.setHSL(Ri.h+e,Ri.s+t,Ri.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(Ri),e.getHSL(Wo);let n=Fs(Ri.h,Wo.h,t),i=Fs(Ri.s,Wo.s,t),r=Fs(Ri.l,Wo.l,t);return this.setHSL(n,i,r),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,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*i,this.g=r[1]*t+r[4]*n+r[7]*i,this.b=r[2]*t+r[5]*n+r[8]*i,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}}var qt=new Le;Le.NAMES=m_;class es extends at{constructor(){super();if(this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new qn,this.environmentIntensity=1,this.environmentRotation=new qn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){if(super.copy(e,t),e.background!==null)this.background=e.background.clone();if(e.environment!==null)this.environment=e.environment.clone();if(e.fog!==null)this.fog=e.fog.clone();if(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();return this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);if(this.fog!==null)t.object.fog=this.fog.toJSON();if(this.backgroundBlurriness>0)t.object.backgroundBlurriness=this.backgroundBlurriness;if(this.backgroundIntensity!==1)t.object.backgroundIntensity=this.backgroundIntensity;if(t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1)t.object.environmentIntensity=this.environmentIntensity;return t.object.environmentRotation=this.environmentRotation.toArray(),t}}var In=new N,ai=new N,nl=new N,ci=new N,Lr=new N,Nr=new N,Xm=new N,il=new N,rl=new N,sl=new N,ol=new st,al=new st,cl=new st;class yn{constructor(e=new N,t=new N,n=new N){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),In.subVectors(e,t),i.cross(In);let r=i.lengthSq();if(r>0)return i.multiplyScalar(1/Math.sqrt(r));return i.set(0,0,0)}static getBarycoord(e,t,n,i,r){In.subVectors(i,t),ai.subVectors(n,t),nl.subVectors(e,t);let s=In.dot(In),o=In.dot(ai),a=In.dot(nl),c=ai.dot(ai),l=ai.dot(nl),u=s*c-o*o;if(u===0)return r.set(0,0,0),null;let f=1/u,h=(c*a-o*l)*f,d=(s*l-o*a)*f;return r.set(1-h-d,d,h)}static containsPoint(e,t,n,i){if(this.getBarycoord(e,t,n,i,ci)===null)return!1;return ci.x>=0&&ci.y>=0&&ci.x+ci.y<=1}static getInterpolation(e,t,n,i,r,s,o,a){if(this.getBarycoord(e,t,n,i,ci)===null){if(a.x=0,a.y=0,"z"in a)a.z=0;if("w"in a)a.w=0;return null}return a.setScalar(0),a.addScaledVector(r,ci.x),a.addScaledVector(s,ci.y),a.addScaledVector(o,ci.z),a}static getInterpolatedAttribute(e,t,n,i,r,s){return ol.setScalar(0),al.setScalar(0),cl.setScalar(0),ol.fromBufferAttribute(e,t),al.fromBufferAttribute(e,n),cl.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(ol,r.x),s.addScaledVector(al,r.y),s.addScaledVector(cl,r.z),s}static isFrontFacing(e,t,n,i){return In.subVectors(n,t),ai.subVectors(e,t),In.cross(ai).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),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 In.subVectors(this.c,this.b),ai.subVectors(this.a,this.b),In.cross(ai).length()*0.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(0.3333333333333333)}getNormal(e){return yn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return yn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return yn.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return yn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return yn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,r=this.c,s,o;Lr.subVectors(i,n),Nr.subVectors(r,n),il.subVectors(e,n);let a=Lr.dot(il),c=Nr.dot(il);if(a<=0&&c<=0)return t.copy(n);rl.subVectors(e,i);let l=Lr.dot(rl),u=Nr.dot(rl);if(l>=0&&u<=l)return t.copy(i);let f=a*u-l*c;if(f<=0&&a>=0&&l<=0)return s=a/(a-l),t.copy(n).addScaledVector(Lr,s);sl.subVectors(e,r);let h=Lr.dot(sl),d=Nr.dot(sl);if(d>=0&&h<=d)return t.copy(r);let g=h*c-a*d;if(g<=0&&c>=0&&d<=0)return o=c/(c-d),t.copy(n).addScaledVector(Nr,o);let y=l*d-h*u;if(y<=0&&u-l>=0&&h-d>=0)return Xm.subVectors(r,i),o=(u-l)/(u-l+(h-d)),t.copy(i).addScaledVector(Xm,o);let p=1/(y+g+f);return s=g*p,o=f*p,t.copy(n).addScaledVector(Lr,s).addScaledVector(Nr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class en{constructor(e=new N(1/0,1/0,1/0),t=new N(-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(Pn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Pn.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=Pn.copy(t).multiplyScalar(0.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(0.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 r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let s=0,o=r.count;s<o;s++){if(e.isMesh===!0)e.getVertexPosition(s,Pn);else Pn.fromBufferAttribute(r,s);Pn.applyMatrix4(e.matrixWorld),this.expandByPoint(Pn)}else{if(e.boundingBox!==void 0){if(e.boundingBox===null)e.computeBoundingBox();$o.copy(e.boundingBox)}else{if(n.boundingBox===null)n.computeBoundingBox();$o.copy(n.boundingBox)}$o.applyMatrix4(e.matrixWorld),this.union($o)}}let i=e.children;for(let r=0,s=i.length;r<s;r++)this.expandByObject(i[r],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,Pn),Pn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;if(e.normal.x>0)t=e.normal.x*this.min.x,n=e.normal.x*this.max.x;else t=e.normal.x*this.max.x,n=e.normal.x*this.min.x;if(e.normal.y>0)t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y;else t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y;if(e.normal.z>0)t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z;else t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z;return t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Cs),Zo.subVectors(this.max,Cs),Dr.subVectors(e.a,Cs),Ur.subVectors(e.b,Cs),Or.subVectors(e.c,Cs),Ci.subVectors(Ur,Dr),Ii.subVectors(Or,Ur),ir.subVectors(Dr,Or);let t=[0,-Ci.z,Ci.y,0,-Ii.z,Ii.y,0,-ir.z,ir.y,Ci.z,0,-Ci.x,Ii.z,0,-Ii.x,ir.z,0,-ir.x,-Ci.y,Ci.x,0,-Ii.y,Ii.x,0,-ir.y,ir.x,0];if(!ll(t,Dr,Ur,Or,Zo))return!1;if(t=[1,0,0,0,1,0,0,0,1],!ll(t,Dr,Ur,Or,Zo))return!1;return Xo.crossVectors(Ci,Ii),t=[Xo.x,Xo.y,Xo.z],ll(t,Dr,Ur,Or,Zo)}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Pn).distanceTo(e)}getBoundingSphere(e){if(this.isEmpty())e.makeEmpty();else this.getCenter(e.center),e.radius=this.getSize(Pn).length()*0.5;return e}intersect(e){if(this.min.max(e.min),this.max.min(e.max),this.isEmpty())this.makeEmpty();return this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){if(this.isEmpty())return this;return li[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),li[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),li[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),li[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),li[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),li[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),li[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),li[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(li),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}}var li=[new N,new N,new N,new N,new N,new N,new N,new N],Pn=new N,$o=new en,Dr=new N,Ur=new N,Or=new N,Ci=new N,Ii=new N,ir=new N,Cs=new N,Zo=new N,Xo=new N,rr=new N;function ll(e,t,n,i,r){for(let s=0,o=e.length-3;s<=o;s+=3){rr.fromArray(e,s);let a=r.x*Math.abs(rr.x)+r.y*Math.abs(rr.y)+r.z*Math.abs(rr.z),c=t.dot(rr),l=n.dot(rr),u=i.dot(rr);if(Math.max(-Math.max(c,l,u),Math.min(c,l,u))>a)return!1}return!0}var It=new N,qo=new Ie,My=0;class Nt extends zn{constructor(e,t,n=!1){super();if(Array.isArray(e))throw TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:My++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=35044,this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate(e){if(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 i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[n+i];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++)qo.fromBufferAttribute(this,t),qo.applyMatrix3(e),this.setXY(t,qo.x,qo.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)It.fromBufferAttribute(this,t),It.applyMatrix3(e),this.setXYZ(t,It.x,It.y,It.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)It.fromBufferAttribute(this,t),It.applyMatrix4(e),this.setXYZ(t,It.x,It.y,It.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)It.fromBufferAttribute(this,t),It.applyNormalMatrix(e),this.setXYZ(t,It.x,It.y,It.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)It.fromBufferAttribute(this,t),It.transformDirection(e),this.setXYZ(t,It.x,It.y,It.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];if(this.normalized)n=Nn(n,this.array);return n}setComponent(e,t,n){if(this.normalized)n=rt(n,this.array);return this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];if(this.normalized)t=Nn(t,this.array);return t}setX(e,t){if(this.normalized)t=rt(t,this.array);return this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];if(this.normalized)t=Nn(t,this.array);return t}setY(e,t){if(this.normalized)t=rt(t,this.array);return this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];if(this.normalized)t=Nn(t,this.array);return t}setZ(e,t){if(this.normalized)t=rt(t,this.array);return this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];if(this.normalized)t=Nn(t,this.array);return t}setW(e,t){if(this.normalized)t=rt(t,this.array);return this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){if(e*=this.itemSize,this.normalized)t=rt(t,this.array),n=rt(n,this.array);return this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,i){if(e*=this.itemSize,this.normalized)t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array);return this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,r){if(e*=this.itemSize,this.normalized)t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array),r=rt(r,this.array);return this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this.array[e+3]=r,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};if(this.name!=="")e.name=this.name;if(this.usage!==35044)e.usage=this.usage;return e}dispose(){this.dispatchEvent({type:"dispose"})}}class Pa extends Nt{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class La extends Nt{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class nn extends Nt{constructor(e,t,n){super(new Float32Array(e),t,n)}}var wy=new en,Is=new N,ul=new N;class fn{constructor(e=new N,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;if(t!==void 0)n.copy(t);else wy.setFromPoints(e).getCenter(n);let i=0;for(let r=0,s=e.length;r<s;r++)i=Math.max(i,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(i),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);if(t.copy(e),n>this.radius*this.radius)t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center);return t}getBoundingBox(e){if(this.isEmpty())return e.makeEmpty(),e;return 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;Is.subVectors(e,this.center);let t=Is.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=(n-this.radius)*0.5;this.center.addScaledVector(Is,i/n),this.radius+=i}return this}union(e){if(e.isEmpty())return this;if(this.isEmpty())return this.copy(e),this;if(this.center.equals(e.center)===!0)this.radius=Math.max(this.radius,e.radius);else ul.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Is.copy(e.center).add(ul)),this.expandByPoint(Is.copy(e.center).sub(ul));return 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}}var Ty=0,vn=new ze,hl=new at,Fr=new N,un=new en,Ps=new en,kt=new N;class tn extends zn{constructor(){super();this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Ty++}),this.uuid=Dn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){if(Array.isArray(e))this.index=new((Yv(e))?La:Pa)(e,1);else this.index=e;return 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;if(t!==void 0)t.applyMatrix4(e),t.needsUpdate=!0;let n=this.attributes.normal;if(n!==void 0){let r=new Ue().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}let i=this.attributes.tangent;if(i!==void 0)i.transformDirection(e),i.needsUpdate=!0;if(this.boundingBox!==null)this.computeBoundingBox();if(this.boundingSphere!==null)this.computeBoundingSphere();return this._transformed=!0,this}applyQuaternion(e){return vn.makeRotationFromQuaternion(e),this.applyMatrix4(vn),this}rotateX(e){return vn.makeRotationX(e),this.applyMatrix4(vn),this}rotateY(e){return vn.makeRotationY(e),this.applyMatrix4(vn),this}rotateZ(e){return vn.makeRotationZ(e),this.applyMatrix4(vn),this}translate(e,t,n){return vn.makeTranslation(e,t,n),this.applyMatrix4(vn),this}scale(e,t,n){return vn.makeScale(e,t,n),this.applyMatrix4(vn),this}lookAt(e){return hl.lookAt(e),hl.updateMatrix(),this.applyMatrix4(hl.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Fr).negate(),this.translate(Fr.x,Fr.y,Fr.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let n=[];for(let i=0,r=e.length;i<r;i++){let s=e[i];n.push(s.x,s.y,s.z||0)}this.setAttribute("position",new nn(n,3))}else{let n=Math.min(e.length,t.count);for(let i=0;i<n;i++){let r=e[i];t.setXYZ(i,r.x,r.y,r.z||0)}if(e.length>t.count)Me("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.");t.needsUpdate=!0}return this}computeBoundingBox(){if(this.boundingBox===null)this.boundingBox=new en;let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ne("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new N(-1/0,-1/0,-1/0),new N(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n<i;n++){let r=t[n];if(un.setFromBufferAttribute(r),this.morphTargetsRelative)kt.addVectors(this.boundingBox.min,un.min),this.boundingBox.expandByPoint(kt),kt.addVectors(this.boundingBox.max,un.max),this.boundingBox.expandByPoint(kt);else this.boundingBox.expandByPoint(un.min),this.boundingBox.expandByPoint(un.max)}}else this.boundingBox.makeEmpty();if(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))Ne('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){if(this.boundingSphere===null)this.boundingSphere=new fn;let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ne("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new N,1/0);return}if(e){let n=this.boundingSphere.center;if(un.setFromBufferAttribute(e),t)for(let r=0,s=t.length;r<s;r++){let o=t[r];if(Ps.setFromBufferAttribute(o),this.morphTargetsRelative)kt.addVectors(un.min,Ps.min),un.expandByPoint(kt),kt.addVectors(un.max,Ps.max),un.expandByPoint(kt);else un.expandByPoint(Ps.min),un.expandByPoint(Ps.max)}un.getCenter(n);let i=0;for(let r=0,s=e.count;r<s;r++)kt.fromBufferAttribute(e,r),i=Math.max(i,n.distanceToSquared(kt));if(t)for(let r=0,s=t.length;r<s;r++){let o=t[r],a=this.morphTargetsRelative;for(let c=0,l=o.count;c<l;c++){if(kt.fromBufferAttribute(o,c),a)Fr.fromBufferAttribute(e,c),kt.add(Fr);i=Math.max(i,n.distanceToSquared(kt))}}if(this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius))Ne('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){Ne("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let{position:n,normal:i,uv:r}=t,s=this.getAttribute("tangent");if(s===void 0||s.count!==n.count)s=new Nt(new Float32Array(4*n.count),4),this.setAttribute("tangent",s);let o=[],a=[];for(let R=0;R<n.count;R++)o[R]=new N,a[R]=new N;let c=new N,l=new N,u=new N,f=new Ie,h=new Ie,d=new Ie,g=new N,y=new N;function p(R,_,S){c.fromBufferAttribute(n,R),l.fromBufferAttribute(n,_),u.fromBufferAttribute(n,S),f.fromBufferAttribute(r,R),h.fromBufferAttribute(r,_),d.fromBufferAttribute(r,S),l.sub(c),u.sub(c),h.sub(f),d.sub(f);let F=1/(h.x*d.y-d.x*h.y);if(!isFinite(F))return;g.copy(l).multiplyScalar(d.y).addScaledVector(u,-h.y).multiplyScalar(F),y.copy(u).multiplyScalar(h.x).addScaledVector(l,-d.x).multiplyScalar(F),o[R].add(g),o[_].add(g),o[S].add(g),a[R].add(y),a[_].add(y),a[S].add(y)}let m=this.groups;if(m.length===0)m=[{start:0,count:e.count}];for(let R=0,_=m.length;R<_;++R){let S=m[R],{start:F,count:C}=S;for(let z=F,J=F+C;z<J;z+=3)p(e.getX(z+0),e.getX(z+1),e.getX(z+2))}let A=new N,T=new N,v=new N,w=new N;function E(R){v.fromBufferAttribute(i,R),w.copy(v);let _=o[R];A.copy(_),A.sub(v.multiplyScalar(v.dot(_))).normalize(),T.crossVectors(w,_);let F=T.dot(a[R])<0?-1:1;s.setXYZW(R,A.x,A.y,A.z,F)}for(let R=0,_=m.length;R<_;++R){let S=m[R],{start:F,count:C}=S;for(let z=F,J=F+C;z<J;z+=3)E(e.getX(z+0)),E(e.getX(z+1)),E(e.getX(z+2))}this._transformed=!0}computeVertexNormals(){let e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0||n.count!==t.count)n=new Nt(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let f=0,h=n.count;f<h;f++)n.setXYZ(f,0,0,0);let i=new N,r=new N,s=new N,o=new N,a=new N,c=new N,l=new N,u=new N;if(e)for(let f=0,h=e.count;f<h;f+=3){let d=e.getX(f+0),g=e.getX(f+1),y=e.getX(f+2);i.fromBufferAttribute(t,d),r.fromBufferAttribute(t,g),s.fromBufferAttribute(t,y),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),o.fromBufferAttribute(n,d),a.fromBufferAttribute(n,g),c.fromBufferAttribute(n,y),o.add(l),a.add(l),c.add(l),n.setXYZ(d,o.x,o.y,o.z),n.setXYZ(g,a.x,a.y,a.z),n.setXYZ(y,c.x,c.y,c.z)}else for(let f=0,h=t.count;f<h;f+=3)i.fromBufferAttribute(t,f+0),r.fromBufferAttribute(t,f+1),s.fromBufferAttribute(t,f+2),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),n.setXYZ(f+0,l.x,l.y,l.z),n.setXYZ(f+1,l.x,l.y,l.z),n.setXYZ(f+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)kt.fromBufferAttribute(e,t),kt.normalize(),e.setXYZ(t,kt.x,kt.y,kt.z)}toNonIndexed(){function e(o,a){let{array:c,itemSize:l,normalized:u}=o,f=new c.constructor(a.length*l),h=0,d=0;for(let g=0,y=a.length;g<y;g++){if(o.isInterleavedBufferAttribute)h=a[g]*o.data.stride+o.offset;else h=a[g]*l;for(let p=0;p<l;p++)f[d++]=c[h++]}return new Nt(f,l,u)}if(this.index===null)return Me("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let t=new tn,n=this.index.array,i=this.attributes;for(let o in i){let a=i[o],c=e(a,n);t.setAttribute(o,c)}let r=this.morphAttributes;for(let o in r){let a=[],c=r[o];for(let l=0,u=c.length;l<u;l++){let f=c[l],h=e(f,n);a.push(h)}t.morphAttributes[o]=a}t.morphTargetsRelative=this.morphTargetsRelative;let s=this.groups;for(let o=0,a=s.length;o<a;o++){let c=s[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.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!=="")e.name=this.name;if(Object.keys(this.userData).length>0)e.userData=this.userData;if(this.parameters!==void 0&&this._transformed!==!0){let a=this.parameters;for(let c in a)if(a[c]!==void 0)e[c]=a[c];return e}e.data={attributes:{}};let t=this.index;if(t!==null)e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)};let n=this.attributes;for(let a in n){let c=n[a];e.data.attributes[a]=c.toJSON(e.data)}let i={},r=!1;for(let a in this.morphAttributes){let c=this.morphAttributes[a],l=[];for(let u=0,f=c.length;u<f;u++){let h=c[u];l.push(h.toJSON(e.data))}if(l.length>0)i[a]=l,r=!0}if(r)e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative;let s=this.groups;if(s.length>0)e.data.groups=JSON.parse(JSON.stringify(s));let o=this.boundingSphere;if(o!==null)e.data.boundingSphere=o.toJSON();return 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;if(n!==null)this.setIndex(n.clone());let i=e.attributes;for(let c in i){let l=i[c];this.setAttribute(c,l.clone(t))}let r=e.morphAttributes;for(let c in r){let l=[],u=r[c];for(let f=0,h=u.length;f<h;f++)l.push(u[f].clone(t));this.morphAttributes[c]=l}this.morphTargetsRelative=e.morphTargetsRelative;let s=e.groups;for(let c=0,l=s.length;c<l;c++){let u=s[c];this.addGroup(u.start,u.count,u.materialIndex)}let o=e.boundingBox;if(o!==null)this.boundingBox=o.clone();let a=e.boundingSphere;if(a!==null)this.boundingSphere=a.clone();return this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class qs{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=35044,this.updateRanges=[],this.version=0,this.uuid=Dn()}onUploadCallback(){}set needsUpdate(e){if(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 i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[n+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){if(e.arrayBuffers===void 0)e.arrayBuffers={};if(this.array.buffer._uuid===void 0)this.array.buffer._uuid=Dn();if(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){if(e.arrayBuffers===void 0)e.arrayBuffers={};if(this.array.buffer._uuid===void 0)this.array.buffer._uuid=Dn();if(e.arrayBuffers[this.array.buffer._uuid]===void 0)e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer));return{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}var Qt=new N;class ts{constructor(e,t,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=i}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++)Qt.fromBufferAttribute(this,t),Qt.applyMatrix4(e),this.setXYZ(t,Qt.x,Qt.y,Qt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Qt.fromBufferAttribute(this,t),Qt.applyNormalMatrix(e),this.setXYZ(t,Qt.x,Qt.y,Qt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Qt.fromBufferAttribute(this,t),Qt.transformDirection(e),this.setXYZ(t,Qt.x,Qt.y,Qt.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];if(this.normalized)n=Nn(n,this.array);return n}setComponent(e,t,n){if(this.normalized)n=rt(n,this.array);return this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){if(this.normalized)t=rt(t,this.array);return this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){if(this.normalized)t=rt(t,this.array);return this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){if(this.normalized)t=rt(t,this.array);return this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){if(this.normalized)t=rt(t,this.array);return 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];if(this.normalized)t=Nn(t,this.array);return t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];if(this.normalized)t=Nn(t,this.array);return t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];if(this.normalized)t=Nn(t,this.array);return t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];if(this.normalized)t=Nn(t,this.array);return t}setXY(e,t,n){if(e=e*this.data.stride+this.offset,this.normalized)t=rt(t,this.array),n=rt(n,this.array);return this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,i){if(e=e*this.data.stride+this.offset,this.normalized)t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array);return this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this}setXYZW(e,t,n,i,r){if(e=e*this.data.stride+this.offset,this.normalized)t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array),r=rt(r,this.array);return this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(e===void 0){zs("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[i+r])}return new Nt(new this.array.constructor(t),this.itemSize,this.normalized)}else{if(e.interleavedBuffers===void 0)e.interleavedBuffers={};if(e.interleavedBuffers[this.data.uuid]===void 0)e.interleavedBuffers[this.data.uuid]=this.data.clone(e);return new ts(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}}toJSON(e){if(e===void 0){zs("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[i+r])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else{if(e.interleavedBuffers===void 0)e.interleavedBuffers={};if(e.interleavedBuffers[this.data.uuid]===void 0)e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e);return{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}}var Ey=0;class rn extends zn{constructor(){super();this.isMaterial=!0,Object.defineProperty(this,"id",{value:Ey++}),this.uuid=Dn(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Le(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=7680,this.stencilZFail=7680,this.stencilZPass=7680,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){if(this._alphaTest>0!==e>0)this.version++;this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e===void 0)return;for(let t in e){let n=e[t];if(n===void 0){Me(`Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){Me(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}if(i&&i.isColor)i.set(n);else if(i&&i.isVector2&&(n&&n.isVector2)||i&&i.isEuler&&(n&&n.isEuler)||i&&i.isVector3&&(n&&n.isVector3))i.copy(n);else this[t]=n}}toJSON(e){let t=e===void 0||typeof e==="string";if(t)e={textures:{},images:{}};let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};if(n.uuid=this.uuid,n.type=this.type,this.name!=="")n.name=this.name;if(this.color&&this.color.isColor)n.color=this.color.getHex();if(this.roughness!==void 0)n.roughness=this.roughness;if(this.metalness!==void 0)n.metalness=this.metalness;if(this.sheen!==void 0)n.sheen=this.sheen;if(this.sheenColor&&this.sheenColor.isColor)n.sheenColor=this.sheenColor.getHex();if(this.sheenRoughness!==void 0)n.sheenRoughness=this.sheenRoughness;if(this.emissive&&this.emissive.isColor)n.emissive=this.emissive.getHex();if(this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1)n.emissiveIntensity=this.emissiveIntensity;if(this.specular&&this.specular.isColor)n.specular=this.specular.getHex();if(this.specularIntensity!==void 0)n.specularIntensity=this.specularIntensity;if(this.specularColor&&this.specularColor.isColor)n.specularColor=this.specularColor.getHex();if(this.shininess!==void 0)n.shininess=this.shininess;if(this.clearcoat!==void 0)n.clearcoat=this.clearcoat;if(this.clearcoatRoughness!==void 0)n.clearcoatRoughness=this.clearcoatRoughness;if(this.clearcoatMap&&this.clearcoatMap.isTexture)n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid;if(this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture)n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid;if(this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture)n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray();if(this.sheenColorMap&&this.sheenColorMap.isTexture)n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid;if(this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture)n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid;if(this.dispersion!==void 0)n.dispersion=this.dispersion;if(this.iridescence!==void 0)n.iridescence=this.iridescence;if(this.iridescenceIOR!==void 0)n.iridescenceIOR=this.iridescenceIOR;if(this.iridescenceThicknessRange!==void 0)n.iridescenceThicknessRange=this.iridescenceThicknessRange;if(this.iridescenceMap&&this.iridescenceMap.isTexture)n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid;if(this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture)n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid;if(this.anisotropy!==void 0)n.anisotropy=this.anisotropy;if(this.anisotropyRotation!==void 0)n.anisotropyRotation=this.anisotropyRotation;if(this.anisotropyMap&&this.anisotropyMap.isTexture)n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid;if(this.map&&this.map.isTexture)n.map=this.map.toJSON(e).uuid;if(this.matcap&&this.matcap.isTexture)n.matcap=this.matcap.toJSON(e).uuid;if(this.alphaMap&&this.alphaMap.isTexture)n.alphaMap=this.alphaMap.toJSON(e).uuid;if(this.lightMap&&this.lightMap.isTexture)n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity;if(this.aoMap&&this.aoMap.isTexture)n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity;if(this.bumpMap&&this.bumpMap.isTexture)n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale;if(this.normalMap&&this.normalMap.isTexture)n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray();if(this.displacementMap&&this.displacementMap.isTexture)n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias;if(this.roughnessMap&&this.roughnessMap.isTexture)n.roughnessMap=this.roughnessMap.toJSON(e).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)n.metalnessMap=this.metalnessMap.toJSON(e).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)n.emissiveMap=this.emissiveMap.toJSON(e).uuid;if(this.specularMap&&this.specularMap.isTexture)n.specularMap=this.specularMap.toJSON(e).uuid;if(this.specularIntensityMap&&this.specularIntensityMap.isTexture)n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid;if(this.specularColorMap&&this.specularColorMap.isTexture)n.specularColorMap=this.specularColorMap.toJSON(e).uuid;if(this.envMap&&this.envMap.isTexture){if(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0)n.combine=this.combine}if(this.envMapRotation!==void 0)n.envMapRotation=this.envMapRotation.toArray();if(this.envMapIntensity!==void 0)n.envMapIntensity=this.envMapIntensity;if(this.reflectivity!==void 0)n.reflectivity=this.reflectivity;if(this.refractionRatio!==void 0)n.refractionRatio=this.refractionRatio;if(this.gradientMap&&this.gradientMap.isTexture)n.gradientMap=this.gradientMap.toJSON(e).uuid;if(this.transmission!==void 0)n.transmission=this.transmission;if(this.transmissionMap&&this.transmissionMap.isTexture)n.transmissionMap=this.transmissionMap.toJSON(e).uuid;if(this.thickness!==void 0)n.thickness=this.thickness;if(this.thicknessMap&&this.thicknessMap.isTexture)n.thicknessMap=this.thicknessMap.toJSON(e).uuid;if(this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0)n.attenuationDistance=this.attenuationDistance;if(this.attenuationColor!==void 0)n.attenuationColor=this.attenuationColor.getHex();if(this.size!==void 0)n.size=this.size;if(this.shadowSide!==null)n.shadowSide=this.shadowSide;if(this.sizeAttenuation!==void 0)n.sizeAttenuation=this.sizeAttenuation;if(this.blending!==1)n.blending=this.blending;if(this.side!==0)n.side=this.side;if(this.vertexColors===!0)n.vertexColors=!0;if(this.opacity<1)n.opacity=this.opacity;if(this.transparent===!0)n.transparent=!0;if(this.blendSrc!==204)n.blendSrc=this.blendSrc;if(this.blendDst!==205)n.blendDst=this.blendDst;if(this.blendEquation!==100)n.blendEquation=this.blendEquation;if(this.blendSrcAlpha!==null)n.blendSrcAlpha=this.blendSrcAlpha;if(this.blendDstAlpha!==null)n.blendDstAlpha=this.blendDstAlpha;if(this.blendEquationAlpha!==null)n.blendEquationAlpha=this.blendEquationAlpha;if(this.blendColor&&this.blendColor.isColor)n.blendColor=this.blendColor.getHex();if(this.blendAlpha!==0)n.blendAlpha=this.blendAlpha;if(this.depthFunc!==3)n.depthFunc=this.depthFunc;if(this.depthTest===!1)n.depthTest=this.depthTest;if(this.depthWrite===!1)n.depthWrite=this.depthWrite;if(this.colorWrite===!1)n.colorWrite=this.colorWrite;if(this.stencilWriteMask!==255)n.stencilWriteMask=this.stencilWriteMask;if(this.stencilFunc!==519)n.stencilFunc=this.stencilFunc;if(this.stencilRef!==0)n.stencilRef=this.stencilRef;if(this.stencilFuncMask!==255)n.stencilFuncMask=this.stencilFuncMask;if(this.stencilFail!==7680)n.stencilFail=this.stencilFail;if(this.stencilZFail!==7680)n.stencilZFail=this.stencilZFail;if(this.stencilZPass!==7680)n.stencilZPass=this.stencilZPass;if(this.stencilWrite===!0)n.stencilWrite=this.stencilWrite;if(this.rotation!==void 0&&this.rotation!==0)n.rotation=this.rotation;if(this.polygonOffset===!0)n.polygonOffset=!0;if(this.polygonOffsetFactor!==0)n.polygonOffsetFactor=this.polygonOffsetFactor;if(this.polygonOffsetUnits!==0)n.polygonOffsetUnits=this.polygonOffsetUnits;if(this.linewidth!==void 0&&this.linewidth!==1)n.linewidth=this.linewidth;if(this.dashSize!==void 0)n.dashSize=this.dashSize;if(this.gapSize!==void 0)n.gapSize=this.gapSize;if(this.scale!==void 0)n.scale=this.scale;if(this.dithering===!0)n.dithering=!0;if(this.alphaTest>0)n.alphaTest=this.alphaTest;if(this.alphaHash===!0)n.alphaHash=!0;if(this.alphaToCoverage===!0)n.alphaToCoverage=!0;if(this.premultipliedAlpha===!0)n.premultipliedAlpha=!0;if(this.forceSinglePass===!0)n.forceSinglePass=!0;if(this.allowOverride===!1)n.allowOverride=!1;if(this.wireframe===!0)n.wireframe=!0;if(this.wireframeLinewidth>1)n.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=="round")n.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=="round")n.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading===!0)n.flatShading=!0;if(this.visible===!1)n.visible=!1;if(this.toneMapped===!1)n.toneMapped=!1;if(this.fog===!1)n.fog=!1;if(Object.keys(this.userData).length>0)n.userData=this.userData;function i(r){let s=[];for(let o in r){let a=r[o];delete a.metadata,s.push(a)}return s}if(t){let r=i(e.textures),s=i(e.images);if(r.length>0)n.textures=r;if(s.length>0)n.images=s}return n}fromJSON(e,t){if(e.uuid!==void 0)this.uuid=e.uuid;if(e.name!==void 0)this.name=e.name;if(e.color!==void 0&&this.color!==void 0)this.color.setHex(e.color);if(e.roughness!==void 0)this.roughness=e.roughness;if(e.metalness!==void 0)this.metalness=e.metalness;if(e.sheen!==void 0)this.sheen=e.sheen;if(e.sheenColor!==void 0)this.sheenColor=new Le().setHex(e.sheenColor);if(e.sheenRoughness!==void 0)this.sheenRoughness=e.sheenRoughness;if(e.emissive!==void 0&&this.emissive!==void 0)this.emissive.setHex(e.emissive);if(e.specular!==void 0&&this.specular!==void 0)this.specular.setHex(e.specular);if(e.specularIntensity!==void 0)this.specularIntensity=e.specularIntensity;if(e.specularColor!==void 0&&this.specularColor!==void 0)this.specularColor.setHex(e.specularColor);if(e.shininess!==void 0)this.shininess=e.shininess;if(e.clearcoat!==void 0)this.clearcoat=e.clearcoat;if(e.clearcoatRoughness!==void 0)this.clearcoatRoughness=e.clearcoatRoughness;if(e.dispersion!==void 0)this.dispersion=e.dispersion;if(e.iridescence!==void 0)this.iridescence=e.iridescence;if(e.iridescenceIOR!==void 0)this.iridescenceIOR=e.iridescenceIOR;if(e.iridescenceThicknessRange!==void 0)this.iridescenceThicknessRange=e.iridescenceThicknessRange;if(e.transmission!==void 0)this.transmission=e.transmission;if(e.thickness!==void 0)this.thickness=e.thickness;if(e.attenuationDistance!==void 0)this.attenuationDistance=e.attenuationDistance;if(e.attenuationColor!==void 0&&this.attenuationColor!==void 0)this.attenuationColor.setHex(e.attenuationColor);if(e.anisotropy!==void 0)this.anisotropy=e.anisotropy;if(e.anisotropyRotation!==void 0)this.anisotropyRotation=e.anisotropyRotation;if(e.fog!==void 0)this.fog=e.fog;if(e.flatShading!==void 0)this.flatShading=e.flatShading;if(e.blending!==void 0)this.blending=e.blending;if(e.combine!==void 0)this.combine=e.combine;if(e.side!==void 0)this.side=e.side;if(e.shadowSide!==void 0)this.shadowSide=e.shadowSide;if(e.opacity!==void 0)this.opacity=e.opacity;if(e.transparent!==void 0)this.transparent=e.transparent;if(e.alphaTest!==void 0)this.alphaTest=e.alphaTest;if(e.alphaHash!==void 0)this.alphaHash=e.alphaHash;if(e.depthFunc!==void 0)this.depthFunc=e.depthFunc;if(e.depthTest!==void 0)this.depthTest=e.depthTest;if(e.depthWrite!==void 0)this.depthWrite=e.depthWrite;if(e.colorWrite!==void 0)this.colorWrite=e.colorWrite;if(e.blendSrc!==void 0)this.blendSrc=e.blendSrc;if(e.blendDst!==void 0)this.blendDst=e.blendDst;if(e.blendEquation!==void 0)this.blendEquation=e.blendEquation;if(e.blendSrcAlpha!==void 0)this.blendSrcAlpha=e.blendSrcAlpha;if(e.blendDstAlpha!==void 0)this.blendDstAlpha=e.blendDstAlpha;if(e.blendEquationAlpha!==void 0)this.blendEquationAlpha=e.blendEquationAlpha;if(e.blendColor!==void 0&&this.blendColor!==void 0)this.blendColor.setHex(e.blendColor);if(e.blendAlpha!==void 0)this.blendAlpha=e.blendAlpha;if(e.stencilWriteMask!==void 0)this.stencilWriteMask=e.stencilWriteMask;if(e.stencilFunc!==void 0)this.stencilFunc=e.stencilFunc;if(e.stencilRef!==void 0)this.stencilRef=e.stencilRef;if(e.stencilFuncMask!==void 0)this.stencilFuncMask=e.stencilFuncMask;if(e.stencilFail!==void 0)this.stencilFail=e.stencilFail;if(e.stencilZFail!==void 0)this.stencilZFail=e.stencilZFail;if(e.stencilZPass!==void 0)this.stencilZPass=e.stencilZPass;if(e.stencilWrite!==void 0)this.stencilWrite=e.stencilWrite;if(e.wireframe!==void 0)this.wireframe=e.wireframe;if(e.wireframeLinewidth!==void 0)this.wireframeLinewidth=e.wireframeLinewidth;if(e.wireframeLinecap!==void 0)this.wireframeLinecap=e.wireframeLinecap;if(e.wireframeLinejoin!==void 0)this.wireframeLinejoin=e.wireframeLinejoin;if(e.rotation!==void 0)this.rotation=e.rotation;if(e.linewidth!==void 0)this.linewidth=e.linewidth;if(e.dashSize!==void 0)this.dashSize=e.dashSize;if(e.gapSize!==void 0)this.gapSize=e.gapSize;if(e.scale!==void 0)this.scale=e.scale;if(e.polygonOffset!==void 0)this.polygonOffset=e.polygonOffset;if(e.polygonOffsetFactor!==void 0)this.polygonOffsetFactor=e.polygonOffsetFactor;if(e.polygonOffsetUnits!==void 0)this.polygonOffsetUnits=e.polygonOffsetUnits;if(e.dithering!==void 0)this.dithering=e.dithering;if(e.alphaToCoverage!==void 0)this.alphaToCoverage=e.alphaToCoverage;if(e.premultipliedAlpha!==void 0)this.premultipliedAlpha=e.premultipliedAlpha;if(e.forceSinglePass!==void 0)this.forceSinglePass=e.forceSinglePass;if(e.allowOverride!==void 0)this.allowOverride=e.allowOverride;if(e.visible!==void 0)this.visible=e.visible;if(e.toneMapped!==void 0)this.toneMapped=e.toneMapped;if(e.userData!==void 0)this.userData=e.userData;if(e.vertexColors!==void 0)if(typeof e.vertexColors==="number")this.vertexColors=e.vertexColors>0;else this.vertexColors=e.vertexColors;if(e.size!==void 0)this.size=e.size;if(e.sizeAttenuation!==void 0)this.sizeAttenuation=e.sizeAttenuation;if(e.map!==void 0)this.map=t[e.map]||null;if(e.matcap!==void 0)this.matcap=t[e.matcap]||null;if(e.alphaMap!==void 0)this.alphaMap=t[e.alphaMap]||null;if(e.bumpMap!==void 0)this.bumpMap=t[e.bumpMap]||null;if(e.bumpScale!==void 0)this.bumpScale=e.bumpScale;if(e.normalMap!==void 0)this.normalMap=t[e.normalMap]||null;if(e.normalMapType!==void 0)this.normalMapType=e.normalMapType;if(e.normalScale!==void 0){let n=e.normalScale;if(Array.isArray(n)===!1)n=[n,n];this.normalScale=new Ie().fromArray(n)}if(e.displacementMap!==void 0)this.displacementMap=t[e.displacementMap]||null;if(e.displacementScale!==void 0)this.displacementScale=e.displacementScale;if(e.displacementBias!==void 0)this.displacementBias=e.displacementBias;if(e.roughnessMap!==void 0)this.roughnessMap=t[e.roughnessMap]||null;if(e.metalnessMap!==void 0)this.metalnessMap=t[e.metalnessMap]||null;if(e.emissiveMap!==void 0)this.emissiveMap=t[e.emissiveMap]||null;if(e.emissiveIntensity!==void 0)this.emissiveIntensity=e.emissiveIntensity;if(e.specularMap!==void 0)this.specularMap=t[e.specularMap]||null;if(e.specularIntensityMap!==void 0)this.specularIntensityMap=t[e.specularIntensityMap]||null;if(e.specularColorMap!==void 0)this.specularColorMap=t[e.specularColorMap]||null;if(e.envMap!==void 0)this.envMap=t[e.envMap]||null;if(e.envMapRotation!==void 0)this.envMapRotation.fromArray(e.envMapRotation);if(e.envMapIntensity!==void 0)this.envMapIntensity=e.envMapIntensity;if(e.reflectivity!==void 0)this.reflectivity=e.reflectivity;if(e.refractionRatio!==void 0)this.refractionRatio=e.refractionRatio;if(e.lightMap!==void 0)this.lightMap=t[e.lightMap]||null;if(e.lightMapIntensity!==void 0)this.lightMapIntensity=e.lightMapIntensity;if(e.aoMap!==void 0)this.aoMap=t[e.aoMap]||null;if(e.aoMapIntensity!==void 0)this.aoMapIntensity=e.aoMapIntensity;if(e.gradientMap!==void 0)this.gradientMap=t[e.gradientMap]||null;if(e.clearcoatMap!==void 0)this.clearcoatMap=t[e.clearcoatMap]||null;if(e.clearcoatRoughnessMap!==void 0)this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null;if(e.clearcoatNormalMap!==void 0)this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null;if(e.clearcoatNormalScale!==void 0)this.clearcoatNormalScale=new Ie().fromArray(e.clearcoatNormalScale);if(e.iridescenceMap!==void 0)this.iridescenceMap=t[e.iridescenceMap]||null;if(e.iridescenceThicknessMap!==void 0)this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null;if(e.transmissionMap!==void 0)this.transmissionMap=t[e.transmissionMap]||null;if(e.thicknessMap!==void 0)this.thicknessMap=t[e.thicknessMap]||null;if(e.anisotropyMap!==void 0)this.anisotropyMap=t[e.anisotropyMap]||null;if(e.sheenColorMap!==void 0)this.sheenColorMap=t[e.sheenColorMap]||null;if(e.sheenRoughnessMap!==void 0)this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null;return this}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 i=t.length;n=Array(i);for(let r=0;r!==i;++r)n[r]=t[r].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){if(e===!0)this.version++}}var ui=new N,fl=new N,Yo=new N,Pi=new N,dl=new N,jo=new N,pl=new N;class zi{constructor(e=new N,t=new N(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,ui)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);if(n<0)return t.copy(this.origin);return t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=ui.subVectors(e,this.origin).dot(this.direction);if(t<0)return this.origin.distanceToSquared(e);return ui.copy(this.origin).addScaledVector(this.direction,t),ui.distanceToSquared(e)}distanceSqToSegment(e,t,n,i){fl.copy(e).add(t).multiplyScalar(0.5),Yo.copy(t).sub(e).normalize(),Pi.copy(this.origin).sub(fl);let r=e.distanceTo(t)*0.5,s=-this.direction.dot(Yo),o=Pi.dot(this.direction),a=-Pi.dot(Yo),c=Pi.lengthSq(),l=Math.abs(1-s*s),u,f,h,d;if(l>0)if(u=s*a-o,f=s*o-a,d=r*l,u>=0)if(f>=-d)if(f<=d){let g=1/l;u*=g,f*=g,h=u*(u+s*f+2*o)+f*(s*u+f+2*a)+c}else f=r,u=Math.max(0,-(s*f+o)),h=-u*u+f*(f+2*a)+c;else f=-r,u=Math.max(0,-(s*f+o)),h=-u*u+f*(f+2*a)+c;else if(f<=-d)u=Math.max(0,-(-s*r+o)),f=u>0?-r:Math.min(Math.max(-r,-a),r),h=-u*u+f*(f+2*a)+c;else if(f<=d)u=0,f=Math.min(Math.max(-r,-a),r),h=f*(f+2*a)+c;else u=Math.max(0,-(s*r+o)),f=u>0?r:Math.min(Math.max(-r,-a),r),h=-u*u+f*(f+2*a)+c;else f=s>0?-r:r,u=Math.max(0,-(s*f+o)),h=-u*u+f*(f+2*a)+c;if(n)n.copy(this.origin).addScaledVector(this.direction,u);if(i)i.copy(fl).addScaledVector(Yo,f);return h}intersectSphere(e,t){ui.subVectors(e.center,this.origin);let n=ui.dot(this.direction),i=ui.dot(ui)-n*n,r=e.radius*e.radius;if(i>r)return null;let s=Math.sqrt(r-i),o=n-s,a=n+s;if(a<0)return null;if(o<0)return this.at(a,t);return this.at(o,t)}intersectsSphere(e){if(e.radius<0)return!1;return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0){if(e.distanceToPoint(this.origin)===0)return 0;return null}let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);if(n===null)return null;return this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);if(t===0)return!0;if(e.normal.dot(this.direction)*t<0)return!0;return!1}intersectBox(e,t){let n,i,r,s,o,a,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,f=this.origin;if(c>=0)n=(e.min.x-f.x)*c,i=(e.max.x-f.x)*c;else n=(e.max.x-f.x)*c,i=(e.min.x-f.x)*c;if(l>=0)r=(e.min.y-f.y)*l,s=(e.max.y-f.y)*l;else r=(e.max.y-f.y)*l,s=(e.min.y-f.y)*l;if(n>s||r>i)return null;if(r>n||isNaN(n))n=r;if(s<i||isNaN(i))i=s;if(u>=0)o=(e.min.z-f.z)*u,a=(e.max.z-f.z)*u;else o=(e.max.z-f.z)*u,a=(e.min.z-f.z)*u;if(n>a||o>i)return null;if(o>n||n!==n)n=o;if(a<i||i!==i)i=a;if(i<0)return null;return this.at(n>=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,ui)!==null}intersectTriangle(e,t,n,i,r){dl.subVectors(t,e),jo.subVectors(n,e),pl.crossVectors(dl,jo);let s=this.direction.dot(pl),o;if(s>0){if(i)return null;o=1}else if(s<0)o=-1,s=-s;else return null;Pi.subVectors(this.origin,e);let a=o*this.direction.dot(jo.crossVectors(Pi,jo));if(a<0)return null;let c=o*this.direction.dot(dl.cross(Pi));if(c<0)return null;if(a+c>s)return null;let l=-o*Pi.dot(pl);if(l<0)return null;return this.at(l/s,r)}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)}}class Kn extends rn{constructor(e){super();this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Le(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 qn,this.combine=0,this.reflectivity=1,this.refractionRatio=0.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}}var qm=new ze,sr=new zi,Jo=new fn,Ym=new N,Ko=new N,Qo=new N,ea=new N,ml=new N,ta=new N,jm=new N,na=new N;class pt extends at{constructor(e=new tn,t=new Kn){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){if(super.copy(e,t),e.morphTargetInfluences!==void 0)this.morphTargetInfluences=e.morphTargetInfluences.slice();if(e.morphTargetDictionary!==void 0)this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary);return 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 i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=i.length;r<s;r++){let o=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}getVertexPosition(e,t){let n=this.geometry,i=n.attributes.position,r=n.morphAttributes.position,s=n.morphTargetsRelative;t.fromBufferAttribute(i,e);let o=this.morphTargetInfluences;if(r&&o){ta.set(0,0,0);for(let a=0,c=r.length;a<c;a++){let l=o[a],u=r[a];if(l===0)continue;if(ml.fromBufferAttribute(u,e),s)ta.addScaledVector(ml,l);else ta.addScaledVector(ml.sub(t),l)}t.add(ta)}return t}raycast(e,t){let n=this.geometry,i=this.material,r=this.matrixWorld;if(i===void 0)return;if(n.boundingSphere===null)n.computeBoundingSphere();if(Jo.copy(n.boundingSphere),Jo.applyMatrix4(r),sr.copy(e.ray).recast(e.near),Jo.containsPoint(sr.origin)===!1){if(sr.intersectSphere(Jo,Ym)===null)return;if(sr.origin.distanceToSquared(Ym)>(e.far-e.near)**2)return}if(qm.copy(r).invert(),sr.copy(e.ray).applyMatrix4(qm),n.boundingBox!==null){if(sr.intersectsBox(n.boundingBox)===!1)return}this._computeIntersections(e,t,sr)}_computeIntersections(e,t,n){let i,r=this.geometry,s=this.material,o=r.index,a=r.attributes.position,c=r.attributes.uv,l=r.attributes.uv1,u=r.attributes.normal,{groups:f,drawRange:h}=r;if(o!==null)if(Array.isArray(s))for(let d=0,g=f.length;d<g;d++){let y=f[d],p=s[y.materialIndex],m=Math.max(y.start,h.start),A=Math.min(o.count,Math.min(y.start+y.count,h.start+h.count));for(let T=m,v=A;T<v;T+=3){let w=o.getX(T),E=o.getX(T+1),R=o.getX(T+2);if(i=ia(this,p,e,n,c,l,u,w,E,R),i)i.faceIndex=Math.floor(T/3),i.face.materialIndex=y.materialIndex,t.push(i)}}else{let d=Math.max(0,h.start),g=Math.min(o.count,h.start+h.count);for(let y=d,p=g;y<p;y+=3){let m=o.getX(y),A=o.getX(y+1),T=o.getX(y+2);if(i=ia(this,s,e,n,c,l,u,m,A,T),i)i.faceIndex=Math.floor(y/3),t.push(i)}}else if(a!==void 0)if(Array.isArray(s))for(let d=0,g=f.length;d<g;d++){let y=f[d],p=s[y.materialIndex],m=Math.max(y.start,h.start),A=Math.min(a.count,Math.min(y.start+y.count,h.start+h.count));for(let T=m,v=A;T<v;T+=3){let w=T,E=T+1,R=T+2;if(i=ia(this,p,e,n,c,l,u,w,E,R),i)i.faceIndex=Math.floor(T/3),i.face.materialIndex=y.materialIndex,t.push(i)}}else{let d=Math.max(0,h.start),g=Math.min(a.count,h.start+h.count);for(let y=d,p=g;y<p;y+=3){let m=y,A=y+1,T=y+2;if(i=ia(this,s,e,n,c,l,u,m,A,T),i)i.faceIndex=Math.floor(y/3),t.push(i)}}}}function Ay(e,t,n,i,r,s,o,a){let c;if(t.side===1)c=i.intersectTriangle(o,s,r,!0,a);else c=i.intersectTriangle(r,s,o,t.side===0,a);if(c===null)return null;na.copy(a),na.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(na);if(l<n.near||l>n.far)return null;return{distance:l,point:na.clone(),object:e}}function ia(e,t,n,i,r,s,o,a,c,l){e.getVertexPosition(a,Ko),e.getVertexPosition(c,Qo),e.getVertexPosition(l,ea);let u=Ay(e,t,n,i,Ko,Qo,ea,jm);if(u){let f=new N;if(yn.getBarycoord(jm,Ko,Qo,ea,f),r)u.uv=yn.getInterpolatedAttribute(r,a,c,l,f,new Ie);if(s)u.uv1=yn.getInterpolatedAttribute(s,a,c,l,f,new Ie);if(o){if(u.normal=yn.getInterpolatedAttribute(o,a,c,l,f,new N),u.normal.dot(i.direction)>0)u.normal.multiplyScalar(-1)}let h={a,b:c,c:l,normal:new N,materialIndex:0};yn.getNormal(Ko,Qo,ea,h.normal),u.face=h,u.barycoord=f}return u}var Ls=new st,Jm=new st,Km=new st,Ry=new st,Qm=new ze,ra=new N,gl=new fn,eg=new ze,_l=new zi;class Na extends pt{constructor(e,t){super(e,t);this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new ze,this.bindMatrixInverse=new ze,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;if(this.boundingBox===null)this.boundingBox=new en;this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,ra),this.boundingBox.expandByPoint(ra)}computeBoundingSphere(){let e=this.geometry;if(this.boundingSphere===null)this.boundingSphere=new fn;this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,ra),this.boundingSphere.expandByPoint(ra)}copy(e,t){if(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();if(e.boundingSphere!==null)this.boundingSphere=e.boundingSphere.clone();return this}raycast(e,t){let n=this.material,i=this.matrixWorld;if(n===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(gl.copy(this.boundingSphere),gl.applyMatrix4(i),e.ray.intersectsSphere(gl)===!1)return;if(eg.copy(i).invert(),_l.copy(e.ray).applyMatrix4(eg),this.boundingBox!==null){if(_l.intersectsBox(this.boundingBox)===!1)return}this._computeIntersections(e,t,_l)}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){if(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 st,t=this.geometry.attributes.skinWeight;for(let n=0,i=t.count;n<i;n++){e.fromBufferAttribute(t,n);let r=1/e.manhattanLength();if(r!==1/0)e.multiplyScalar(r);else e.set(1,0,0,0);t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){if(super.updateMatrixWorld(e),this.bindMode==="attached")this.bindMatrixInverse.copy(this.matrixWorld).invert();else if(this.bindMode==="detached")this.bindMatrixInverse.copy(this.bindMatrix).invert();else Me("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,i=this.geometry;if(Jm.fromBufferAttribute(i.attributes.skinIndex,e),Km.fromBufferAttribute(i.attributes.skinWeight,e),t.isVector4)Ls.copy(t),t.set(0,0,0,0);else Ls.set(...t,1),t.set(0,0,0);Ls.applyMatrix4(this.bindMatrix);for(let r=0;r<4;r++){let s=Km.getComponent(r);if(s!==0){let o=Jm.getComponent(r);Qm.multiplyMatrices(n.bones[o].matrixWorld,n.boneInverses[o]),t.addScaledVector(Ry.copy(Ls).applyMatrix4(Qm),s)}}if(t.isVector4)t.w=Ls.w;return t.applyMatrix4(this.bindMatrixInverse)}}class Ys extends at{constructor(){super();this.isBone=!0,this.type="Bone"}}class js extends wt{constructor(e=null,t=1,n=1,i,r,s,o,a,c=1003,l=1003,u,f){super(null,s,o,a,c,l,i,r,u,f);this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}var tg=new ze,Cy=new ze;class Js{constructor(e=[],t=[]){this.uuid=Dn(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=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){Me("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let n=0,i=this.bones.length;n<i;n++)this.boneInverses.push(new ze)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let n=new ze;if(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];if(n)n.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){let n=this.bones[e];if(n){if(n.parent&&n.parent.isBone)n.matrix.copy(n.parent.matrixWorld).invert(),n.matrix.multiply(n.matrixWorld);else 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,i=this.boneTexture;for(let r=0,s=e.length;r<s;r++){let o=e[r]?e[r].matrixWorld:Cy;tg.multiplyMatrices(o,t[r]),tg.toArray(n,r*16)}if(i!==null)i.needsUpdate=!0}clone(){return new Js(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 js(t,e,e,1023,1015);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 i=this.bones[t];if(i.name===e)return i}return}dispose(){if(this.boneTexture!==null)this.boneTexture.dispose(),this.boneTexture=null}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,i=e.bones.length;n<i;n++){let r=e.bones[n],s=t[r];if(s===void 0)Me("Skeleton: No bone found with UUID:",r),s=new Ys;this.bones.push(s),this.boneInverses.push(new ze().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 i=0,r=t.length;i<r;i++){let s=t[i];e.bones.push(s.uuid);let o=n[i];e.boneInverses.push(o.toArray())}return e}}class lr extends Nt{constructor(e,t,n,i=1){super(e,t,n);this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}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}}var zr=new ze,ng=new ze,sa=[],ig=new en,Iy=new ze,Ns=new pt,Ds=new fn;class ns extends pt{constructor(e,t,n){super(e,t);this.isInstancedMesh=!0,this.instanceMatrix=new lr(new Float32Array(n*16),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let i=0;i<n;i++)this.setMatrixAt(i,Iy)}computeBoundingBox(){let e=this.geometry,t=this.count;if(this.boundingBox===null)this.boundingBox=new en;if(e.boundingBox===null)e.computeBoundingBox();this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,zr),ig.copy(e.boundingBox).applyMatrix4(zr),this.boundingBox.union(ig)}computeBoundingSphere(){let e=this.geometry,t=this.count;if(this.boundingSphere===null)this.boundingSphere=new fn;if(e.boundingSphere===null)e.computeBoundingSphere();this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,zr),Ds.copy(e.boundingSphere).applyMatrix4(zr),this.boundingSphere.union(Ds)}copy(e,t){if(super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null)this.morphTexture=e.morphTexture.clone();if(e.instanceColor!==null)this.instanceColor=e.instanceColor.clone();if(this.count=e.count,e.boundingBox!==null)this.boundingBox=e.boundingBox.clone();if(e.boundingSphere!==null)this.boundingSphere=e.boundingSphere.clone();return this}getColorAt(e,t){if(this.instanceColor===null)return t.setRGB(1,1,1);else return 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,i=this.morphTexture.source.data.data,r=n.length+1,s=e*r+1;for(let o=0;o<n.length;o++)n[o]=i[s+o]}raycast(e,t){let n=this.matrixWorld,i=this.count;if(Ns.geometry=this.geometry,Ns.material=this.material,Ns.material===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(Ds.copy(this.boundingSphere),Ds.applyMatrix4(n),e.ray.intersectsSphere(Ds)===!1)return;for(let r=0;r<i;r++){this.getMatrixAt(r,zr),ng.multiplyMatrices(n,zr),Ns.matrixWorld=ng,Ns.raycast(e,sa);for(let s=0,o=sa.length;s<o;s++){let a=sa[s];a.instanceId=r,a.object=this,t.push(a)}sa.length=0}}setColorAt(e,t){if(this.instanceColor===null)this.instanceColor=new lr(new Float32Array(this.instanceMatrix.count*3).fill(1),3);return 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,i=n.length+1;if(this.morphTexture===null)this.morphTexture=new js(new Float32Array(i*this.count),i,this.count,1028,1015);let r=this.morphTexture.source.data.data,s=0;for(let c=0;c<n.length;c++)s+=n[c];let o=this.geometry.morphTargetsRelative?1:1-s,a=i*e;return r[a]=o,r.set(n,a+1),this}updateMorphTargets(){}dispose(){if(this.dispatchEvent({type:"dispose"}),this.morphTexture!==null)this.morphTexture.dispose(),this.morphTexture=null}}var xl=new N,Py=new N,Ly=new Ue;class Ln{constructor(e=new N(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,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let i=xl.subVectors(n,t).cross(Py.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,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 i=e.delta(xl),r=this.normal.dot(i);if(r===0){if(this.distanceToPoint(e.start)===0)return t.copy(e.start);return null}let s=-(e.start.dot(this.normal)+this.constant)/r;if(n===!0&&(s<0||s>1))return null;return t.copy(e.start).addScaledVector(i,s)}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||Ly.getNormalMatrix(e),i=this.coplanarPoint(xl).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),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)}}var or=new fn,Ny=new Ie(0.5,0.5),oa=new N;class Ks{constructor(e=new Ln,t=new Ln,n=new Ln,i=new Ln,r=new Ln,s=new Ln){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(i),o[4].copy(r),o[5].copy(s),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=2000,n=!1){let i=this.planes,r=e.elements,s=r[0],o=r[1],a=r[2],c=r[3],l=r[4],u=r[5],f=r[6],h=r[7],d=r[8],g=r[9],y=r[10],p=r[11],m=r[12],A=r[13],T=r[14],v=r[15];if(i[0].setComponents(c-s,h-l,p-d,v-m).normalize(),i[1].setComponents(c+s,h+l,p+d,v+m).normalize(),i[2].setComponents(c+o,h+u,p+g,v+A).normalize(),i[3].setComponents(c-o,h-u,p-g,v-A).normalize(),n)i[4].setComponents(a,f,y,T).normalize(),i[5].setComponents(c-a,h-f,p-y,v-T).normalize();else if(i[4].setComponents(c-a,h-f,p-y,v-T).normalize(),t===2000)i[5].setComponents(c+a,h+f,p+y,v+T).normalize();else if(t===2001)i[5].setComponents(a,f,y,T).normalize();else throw Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0){if(e.boundingSphere===null)e.computeBoundingSphere();or.copy(e.boundingSphere).applyMatrix4(e.matrixWorld)}else{let t=e.geometry;if(t.boundingSphere===null)t.computeBoundingSphere();or.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(or)}intersectsSprite(e){or.center.set(0,0,0);let t=Ny.distanceTo(e.center);return or.radius=0.7071067811865476+t,or.applyMatrix4(e.matrixWorld),this.intersectsSphere(or)}intersectsSphere(e){let t=this.planes,n=e.center,i=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<i)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let i=t[n];if(oa.x=i.normal.x>0?e.max.x:e.min.x,oa.y=i.normal.y>0?e.max.y:e.min.y,oa.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(oa)<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)}}class Qs extends rn{constructor(e){super();this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Le(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}}var pa=new N,ma=new N,rg=new ze,Us=new zi,aa=new fn,vl=new N,sg=new N;class ki extends at{constructor(e=new tn,t=new Qs){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 i=1,r=t.count;i<r;i++)pa.fromBufferAttribute(t,i-1),ma.fromBufferAttribute(t,i),n[i]=n[i-1],n[i]+=pa.distanceTo(ma);e.setAttribute("lineDistance",new nn(n,1))}else Me("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){let n=this.geometry,i=this.matrixWorld,r=e.params.Line.threshold,s=n.drawRange;if(n.boundingSphere===null)n.computeBoundingSphere();if(aa.copy(n.boundingSphere),aa.applyMatrix4(i),aa.radius+=r,e.ray.intersectsSphere(aa)===!1)return;rg.copy(i).invert(),Us.copy(e.ray).applyMatrix4(rg);let o=r/((this.scale.x+this.scale.y+this.scale.z)/3),a=o*o,c=this.isLineSegments?2:1,l=n.index,f=n.attributes.position;if(l!==null){let h=Math.max(0,s.start),d=Math.min(l.count,s.start+s.count);for(let g=h,y=d-1;g<y;g+=c){let p=l.getX(g),m=l.getX(g+1),A=ca(this,e,Us,a,p,m,g);if(A)t.push(A)}if(this.isLineLoop){let g=l.getX(d-1),y=l.getX(h),p=ca(this,e,Us,a,g,y,d-1);if(p)t.push(p)}}else{let h=Math.max(0,s.start),d=Math.min(f.count,s.start+s.count);for(let g=h,y=d-1;g<y;g+=c){let p=ca(this,e,Us,a,g,g+1,g);if(p)t.push(p)}if(this.isLineLoop){let g=ca(this,e,Us,a,d-1,h,d-1);if(g)t.push(g)}}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=i.length;r<s;r++){let o=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function ca(e,t,n,i,r,s,o){let a=e.geometry.attributes.position;if(pa.fromBufferAttribute(a,r),ma.fromBufferAttribute(a,s),n.distanceSqToSegment(pa,ma,vl,sg)>i)return;vl.applyMatrix4(e.matrixWorld);let l=t.ray.origin.distanceTo(vl);if(l<t.near||l>t.far)return;return{distance:l,point:sg.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var og=new N,ag=new N;class Da extends ki{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 i=0,r=t.count;i<r;i+=2)og.fromBufferAttribute(t,i),ag.fromBufferAttribute(t,i+1),n[i]=i===0?0:n[i-1],n[i+1]=n[i]+og.distanceTo(ag);e.setAttribute("lineDistance",new nn(n,1))}else Me("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class Ua extends ki{constructor(e,t){super(e,t);this.isLineLoop=!0,this.type="LineLoop"}}class eo extends rn{constructor(e){super();this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Le(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}}var cg=new ze,Sl=new zi,la=new fn,ua=new N;class is extends at{constructor(e=new tn,t=new eo){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,i=this.matrixWorld,r=e.params.Points.threshold,s=n.drawRange;if(n.boundingSphere===null)n.computeBoundingSphere();if(la.copy(n.boundingSphere),la.applyMatrix4(i),la.radius+=r,e.ray.intersectsSphere(la)===!1)return;cg.copy(i).invert(),Sl.copy(e.ray).applyMatrix4(cg);let o=r/((this.scale.x+this.scale.y+this.scale.z)/3),a=o*o,c=n.index,u=n.attributes.position;if(c!==null){let f=Math.max(0,s.start),h=Math.min(c.count,s.start+s.count);for(let d=f,g=h;d<g;d++){let y=c.getX(d);ua.fromBufferAttribute(u,y),lg(ua,y,a,i,e,t,this)}}else{let f=Math.max(0,s.start),h=Math.min(u.count,s.start+s.count);for(let d=f,g=h;d<g;d++)ua.fromBufferAttribute(u,d),lg(ua,d,a,i,e,t,this)}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=i.length;r<s;r++){let o=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function lg(e,t,n,i,r,s,o){let a=Sl.distanceSqToPoint(e);if(a<n){let c=new N;Sl.closestPointToPoint(e,c),c.applyMatrix4(i);let l=r.ray.origin.distanceTo(c);if(l<r.near||l>r.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}class Oa extends wt{constructor(e=[],t=301,n,i,r,s,o,a,c,l){super(e,t,n,i,r,s,o,a,c,l);this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Bi extends wt{constructor(e,t,n=1014,i,r,s,o=1003,a=1003,c,l=1026,u=1){if(l!==1026&&l!==1027)throw Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let f={width:e,height:t,depth:u};super(f,i,r,s,o,a,l,n,c);this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Zs(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);if(this.compareFunction!==null)t.compareFunction=this.compareFunction;return t}}class Eu extends Bi{constructor(e,t=1014,n=301,i,r,s=1003,o=1003,a,c=1026){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,i,r,s,o,a,c);this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class Fa extends wt{constructor(e=null){super();this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Gi extends tn{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super();this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};let o=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);let a=[],c=[],l=[],u=[],f=0,h=0;d("z","y","x",-1,-1,n,t,e,s,r,0),d("z","y","x",1,-1,n,t,-e,s,r,1),d("x","z","y",1,1,e,n,t,i,s,2),d("x","z","y",1,-1,e,n,-t,i,s,3),d("x","y","z",1,-1,e,t,n,i,r,4),d("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(a),this.setAttribute("position",new nn(c,3)),this.setAttribute("normal",new nn(l,3)),this.setAttribute("uv",new nn(u,2));function d(g,y,p,m,A,T,v,w,E,R,_){let S=T/E,F=v/R,C=T/2,z=v/2,J=w/2,O=E+1,H=R+1,V=0,U=0,K=new N;for(let Q=0;Q<H;Q++){let se=Q*F-z;for(let me=0;me<O;me++){let _e=me*S-C;K[g]=_e*m,K[y]=se*A,K[p]=J,c.push(K.x,K.y,K.z),K[g]=0,K[y]=0,K[p]=w>0?1:-1,l.push(K.x,K.y,K.z),u.push(me/E),u.push(1-Q/R),V+=1}}for(let Q=0;Q<R;Q++)for(let se=0;se<E;se++){let me=f+se+O*Q,_e=f+se+O*(Q+1),qe=f+(se+1)+O*(Q+1),Ge=f+(se+1)+O*Q;a.push(me,_e,Ge),a.push(_e,qe,Ge),U+=6}o.addGroup(h,U,_),h+=U,f+=V}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Gi(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class to extends tn{constructor(e=1,t=1,n=1,i=1){super();this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};let r=e/2,s=t/2,o=Math.floor(n),a=Math.floor(i),c=o+1,l=a+1,u=e/o,f=t/a,h=[],d=[],g=[],y=[];for(let p=0;p<l;p++){let m=p*f-s;for(let A=0;A<c;A++){let T=A*u-r;d.push(T,-m,0),g.push(0,0,1),y.push(A/o),y.push(1-p/a)}}for(let p=0;p<a;p++)for(let m=0;m<o;m++){let A=m+c*p,T=m+c*(p+1),v=m+1+c*(p+1),w=m+1+c*p;h.push(A,T,w),h.push(T,v,w)}this.setIndex(h),this.setAttribute("position",new nn(d,3)),this.setAttribute("normal",new nn(g,3)),this.setAttribute("uv",new nn(y,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new to(e.width,e.height,e.widthSegments,e.heightSegments)}}function gr(e){let t={};for(let n in e){t[n]={};for(let i in e[n]){let r=e[n][i];if(ug(r))if(r.isRenderTargetTexture)Me("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[n][i]=null;else t[n][i]=r.clone();else if(Array.isArray(r))if(ug(r[0])){let s=[];for(let o=0,a=r.length;o<a;o++)s[o]=r[o].clone();t[n][i]=s}else t[n][i]=r.slice();else t[n][i]=r}}return t}function jt(e){let t={};for(let n=0;n<e.length;n++){let i=gr(e[n]);for(let r in i)t[r]=i[r]}return t}function ug(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function Dy(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function Au(e){let t=e.getRenderTarget();if(t===null)return e.outputColorSpace;if(t.isXRRenderTarget===!0)return t.texture.colorSpace;return We.workingColorSpace}var g_={clone:gr,merge:jt},Uy=`void main() {gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );-}`,LV=`void main() {+}`,Oy=`void main() {gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );-}`;class yU extends DU{constructor($){super();if(this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=FV,this.fragmentShader=LV,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,$!==void 0)this.setValues($)}copy($){return super.copy($),this.fragmentShader=$.fragmentShader,this.vertexShader=$.vertexShader,this.uniforms=d0($.uniforms),this.uniformsGroups=kV($.uniformsGroups),this.defines=Object.assign({},$.defines),this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this.fog=$.fog,this.lights=$.lights,this.clipping=$.clipping,this.extensions=Object.assign({},$.extensions),this.glslVersion=$.glslVersion,this.defaultAttributeValues=Object.assign({},$.defaultAttributeValues),this.index0AttributeName=$.index0AttributeName,this.uniformsNeedUpdate=$.uniformsNeedUpdate,this}toJSON($){let U=super.toJSON($);U.glslVersion=this.glslVersion,U.uniforms={};for(let Q in this.uniforms){let K=this.uniforms[Q].value;if(K&&K.isTexture)U.uniforms[Q]={type:"t",value:K.toJSON($).uuid};else if(K&&K.isColor)U.uniforms[Q]={type:"c",value:K.getHex()};else if(K&&K.isVector2)U.uniforms[Q]={type:"v2",value:K.toArray()};else if(K&&K.isVector3)U.uniforms[Q]={type:"v3",value:K.toArray()};else if(K&&K.isVector4)U.uniforms[Q]={type:"v4",value:K.toArray()};else if(K&&K.isMatrix3)U.uniforms[Q]={type:"m3",value:K.toArray()};else if(K&&K.isMatrix4)U.uniforms[Q]={type:"m4",value:K.toArray()};else U.uniforms[Q]={value:K}}if(Object.keys(this.defines).length>0)U.defines=this.defines;U.vertexShader=this.vertexShader,U.fragmentShader=this.fragmentShader,U.lights=this.lights,U.clipping=this.clipping;let J={};for(let Q in this.extensions)if(this.extensions[Q]===!0)J[Q]=!0;if(Object.keys(J).length>0)U.extensions=J;return U}fromJSON($,U){if(super.fromJSON($,U),$.uniforms!==void 0)for(let J in $.uniforms){let Q=$.uniforms[J];switch(this.uniforms[J]={},Q.type){case"t":this.uniforms[J].value=U[Q.value]||null;break;case"c":this.uniforms[J].value=new x$().setHex(Q.value);break;case"v2":this.uniforms[J].value=new g$().fromArray(Q.value);break;case"v3":this.uniforms[J].value=new j().fromArray(Q.value);break;case"v4":this.uniforms[J].value=new Z6().fromArray(Q.value);break;case"m3":this.uniforms[J].value=new u$().fromArray(Q.value);break;case"m4":this.uniforms[J].value=new p$().fromArray(Q.value);break;default:this.uniforms[J].value=Q.value}}if($.defines!==void 0)this.defines=$.defines;if($.vertexShader!==void 0)this.vertexShader=$.vertexShader;if($.fragmentShader!==void 0)this.fragmentShader=$.fragmentShader;if($.glslVersion!==void 0)this.glslVersion=$.glslVersion;if($.extensions!==void 0)for(let J in $.extensions)this.extensions[J]=$.extensions[J];if($.lights!==void 0)this.lights=$.lights;if($.clipping!==void 0)this.clipping=$.clipping;return this}}class jE extends yU{constructor($){super($);this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class bJ extends DU{constructor($){super();this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new x$(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 x$(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new g$(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 OJ,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues($)}copy($){return super.copy($),this.defines={STANDARD:""},this.color.copy($.color),this.roughness=$.roughness,this.metalness=$.metalness,this.map=$.map,this.lightMap=$.lightMap,this.lightMapIntensity=$.lightMapIntensity,this.aoMap=$.aoMap,this.aoMapIntensity=$.aoMapIntensity,this.emissive.copy($.emissive),this.emissiveMap=$.emissiveMap,this.emissiveIntensity=$.emissiveIntensity,this.bumpMap=$.bumpMap,this.bumpScale=$.bumpScale,this.normalMap=$.normalMap,this.normalMapType=$.normalMapType,this.normalScale.copy($.normalScale),this.displacementMap=$.displacementMap,this.displacementScale=$.displacementScale,this.displacementBias=$.displacementBias,this.roughnessMap=$.roughnessMap,this.metalnessMap=$.metalnessMap,this.alphaMap=$.alphaMap,this.envMap=$.envMap,this.envMapRotation.copy($.envMapRotation),this.envMapIntensity=$.envMapIntensity,this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this.wireframeLinecap=$.wireframeLinecap,this.wireframeLinejoin=$.wireframeLinejoin,this.flatShading=$.flatShading,this.fog=$.fog,this}}class zU extends bJ{constructor($){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 g$(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return t$(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(U){this.ior=(1+0.4*U)/(1-0.4*U)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new x$(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 x$(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new x$(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($)}get anisotropy(){return this._anisotropy}set anisotropy($){if(this._anisotropy>0!==$>0)this.version++;this._anisotropy=$}get clearcoat(){return this._clearcoat}set clearcoat($){if(this._clearcoat>0!==$>0)this.version++;this._clearcoat=$}get iridescence(){return this._iridescence}set iridescence($){if(this._iridescence>0!==$>0)this.version++;this._iridescence=$}get dispersion(){return this._dispersion}set dispersion($){if(this._dispersion>0!==$>0)this.version++;this._dispersion=$}get sheen(){return this._sheen}set sheen($){if(this._sheen>0!==$>0)this.version++;this._sheen=$}get transmission(){return this._transmission}set transmission($){if(this._transmission>0!==$>0)this.version++;this._transmission=$}copy($){return super.copy($),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=$.anisotropy,this.anisotropyRotation=$.anisotropyRotation,this.anisotropyMap=$.anisotropyMap,this.clearcoat=$.clearcoat,this.clearcoatMap=$.clearcoatMap,this.clearcoatRoughness=$.clearcoatRoughness,this.clearcoatRoughnessMap=$.clearcoatRoughnessMap,this.clearcoatNormalMap=$.clearcoatNormalMap,this.clearcoatNormalScale.copy($.clearcoatNormalScale),this.dispersion=$.dispersion,this.ior=$.ior,this.iridescence=$.iridescence,this.iridescenceMap=$.iridescenceMap,this.iridescenceIOR=$.iridescenceIOR,this.iridescenceThicknessRange=[...$.iridescenceThicknessRange],this.iridescenceThicknessMap=$.iridescenceThicknessMap,this.sheen=$.sheen,this.sheenColor.copy($.sheenColor),this.sheenColorMap=$.sheenColorMap,this.sheenRoughness=$.sheenRoughness,this.sheenRoughnessMap=$.sheenRoughnessMap,this.transmission=$.transmission,this.transmissionMap=$.transmissionMap,this.thickness=$.thickness,this.thicknessMap=$.thicknessMap,this.attenuationDistance=$.attenuationDistance,this.attenuationColor.copy($.attenuationColor),this.specularIntensity=$.specularIntensity,this.specularIntensityMap=$.specularIntensityMap,this.specularColor.copy($.specularColor),this.specularColorMap=$.specularColorMap,this}}class w7 extends DU{constructor($){super();this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new x$(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new x$(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new g$(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new OJ,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues($)}copy($){return super.copy($),this.color.copy($.color),this.map=$.map,this.lightMap=$.lightMap,this.lightMapIntensity=$.lightMapIntensity,this.aoMap=$.aoMap,this.aoMapIntensity=$.aoMapIntensity,this.emissive.copy($.emissive),this.emissiveMap=$.emissiveMap,this.emissiveIntensity=$.emissiveIntensity,this.bumpMap=$.bumpMap,this.bumpScale=$.bumpScale,this.normalMap=$.normalMap,this.normalMapType=$.normalMapType,this.normalScale.copy($.normalScale),this.displacementMap=$.displacementMap,this.displacementScale=$.displacementScale,this.displacementBias=$.displacementBias,this.specularMap=$.specularMap,this.alphaMap=$.alphaMap,this.envMap=$.envMap,this.envMapRotation.copy($.envMapRotation),this.combine=$.combine,this.reflectivity=$.reflectivity,this.envMapIntensity=$.envMapIntensity,this.refractionRatio=$.refractionRatio,this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this.wireframeLinecap=$.wireframeLinecap,this.wireframeLinejoin=$.wireframeLinejoin,this.flatShading=$.flatShading,this.fog=$.fog,this}}class gE extends DU{constructor($){super();this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues($)}copy($){return super.copy($),this.depthPacking=$.depthPacking,this.map=$.map,this.alphaMap=$.alphaMap,this.displacementMap=$.displacementMap,this.displacementScale=$.displacementScale,this.displacementBias=$.displacementBias,this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this}}class bE extends DU{constructor($){super();this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues($)}copy($){return super.copy($),this.map=$.map,this.alphaMap=$.alphaMap,this.displacementMap=$.displacementMap,this.displacementScale=$.displacementScale,this.displacementBias=$.displacementBias,this}}function rK($,U){if(!$||$.constructor===U)return $;if(typeof U.BYTES_PER_ELEMENT==="number")return new U($);return Array.prototype.slice.call($)}function RV($){function U(W,K){return $[W]-$[K]}let J=$.length,Q=Array(J);for(let W=0;W!==J;++W)Q[W]=W;return Q.sort(U),Q}function CD($,U,J){let Q=$.length,W=new $.constructor(Q);for(let K=0,X=0;X!==Q;++K){let N=J[K]*U;for(let H=0;H!==U;++H)W[X++]=$[N+H]}return W}function VV($,U,J,Q){let W=1,K=$[0];while(K!==void 0&&K[Q]===void 0)K=$[W++];if(K===void 0)return;let X=K[Q];if(X===void 0)return;if(Array.isArray(X))do{if(X=K[Q],X!==void 0)U.push(K.time),J.push(...X);K=$[W++]}while(K!==void 0);else if(X.toArray!==void 0)do{if(X=K[Q],X!==void 0)U.push(K.time),X.toArray(J,J.length);K=$[W++]}while(K!==void 0);else do{if(X=K[Q],X!==void 0)U.push(K.time),J.push(X);K=$[W++]}while(K!==void 0)}class xJ{constructor($,U,J,Q){this.parameterPositions=$,this._cachedIndex=0,this.resultBuffer=Q!==void 0?Q:new U.constructor(J),this.sampleValues=U,this.valueSize=J,this.settings=null,this.DefaultSettings_={}}evaluate($){let U=this.parameterPositions,J=this._cachedIndex,Q=U[J],W=U[J-1];$:{U:{let K;J:{W:if(!($<Q)){for(let X=J+2;;){if(Q===void 0){if($<W)break W;return J=U.length,this._cachedIndex=J,this.copySampleValue_(J-1)}if(J===X)break;if(W=Q,Q=U[++J],$<Q)break U}K=U.length;break J}if(!($>=W)){let X=U[1];if($<X)J=2,W=X;for(let N=J-2;;){if(W===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(J===N)break;if(Q=W,W=U[--J-1],$>=W)break U}K=J,J=0;break J}break $}while(J<K){let X=J+K>>>1;if($<U[X])K=X;else J=X+1}if(Q=U[J],W=U[J-1],W===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(Q===void 0)return J=U.length,this._cachedIndex=J,this.copySampleValue_(J-1)}this._cachedIndex=J,this.intervalChanged_(J,W,Q)}return this.interpolate_(J,W,$,Q)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_($){let U=this.resultBuffer,J=this.sampleValues,Q=this.valueSize,W=$*Q;for(let K=0;K!==Q;++K)U[K]=J[W+K];return U}interpolate_(){throw Error("THREE.Interpolant: Call to abstract method.")}intervalChanged_(){}}class xE extends xJ{constructor($,U,J,Q){super($,U,J,Q);this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:2400,endingEnd:2400}}intervalChanged_($,U,J){let Q=this.parameterPositions,W=$-2,K=$+1,X=Q[W],N=Q[K];if(X===void 0)switch(this.getSettings_().endingStart){case 2401:W=$,X=2*U-J;break;case 2402:W=Q.length-2,X=U+Q[W]-Q[W+1];break;default:W=$,X=J}if(N===void 0)switch(this.getSettings_().endingEnd){case 2401:K=$,N=2*J-U;break;case 2402:K=1,N=J+Q[1]-Q[0];break;default:K=$-1,N=U}let H=(J-U)*0.5,Y=this.valueSize;this._weightPrev=H/(U-X),this._weightNext=H/(N-J),this._offsetPrev=W*Y,this._offsetNext=K*Y}interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,N=$*X,H=N-X,Y=this._offsetPrev,G=this._offsetNext,O=this._weightPrev,E=this._weightNext,Z=(J-U)/(Q-U),D=Z*Z,R=D*Z,I=-O*R+2*O*D-O*Z,q=(1+O)*R+(-1.5-2*O)*D+(-0.5+O)*Z+1,_=(-1-E)*R+(1.5+E)*D+0.5*Z,P=E*R-E*D;for(let L=0;L!==X;++L)W[L]=I*K[Y+L]+q*K[H+L]+_*K[N+L]+P*K[G+L];return W}}class M7 extends xJ{constructor($,U,J,Q){super($,U,J,Q)}interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,N=$*X,H=N-X,Y=(J-U)/(Q-U),G=1-Y;for(let O=0;O!==X;++O)W[O]=K[H+O]*G+K[N+O]*Y;return W}}class yE extends xJ{constructor($,U,J,Q){super($,U,J,Q)}interpolate_($){return this.copySampleValue_($-1)}}class hE extends xJ{interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,N=$*X,H=N-X,Y=this.inTangents,G=this.outTangents;if(!Y||!G){let Z=(J-U)/(Q-U),D=1-Z;for(let R=0;R!==X;++R)W[R]=K[H+R]*D+K[N+R]*Z;return W}let O=X*2,E=$-1;for(let Z=0;Z!==X;++Z){let D=K[H+Z],R=K[N+Z],I=E*O+Z*2,q=G[I],_=G[I+1],P=$*O+Z*2,L=Y[P],B=Y[P+1],z=(J-U)/(Q-U),A,k,w,h,C;for(let f=0;f<8;f++){A=z*z,k=A*z,w=1-z,h=w*w,C=h*w;let y=C*U+3*h*z*q+3*w*A*L+k*Q-J;if(Math.abs(y)<0.0000000001)break;let d=3*h*(q-U)+6*w*z*(L-q)+3*A*(Q-L);if(Math.abs(d)<0.0000000001)break;z=z-y/d,z=Math.max(0,Math.min(1,z))}W[Z]=C*D+3*h*z*_+3*w*A*B+k*R}return W}}class _U{constructor($,U,J,Q){if($===void 0)throw Error("THREE.KeyframeTrack: track name is undefined");if(U===void 0||U.length===0)throw Error("THREE.KeyframeTrack: no keyframes in track named "+$);this.name=$,this.times=rK(U,this.TimeBufferType),this.values=rK(J,this.ValueBufferType),this.setInterpolation(Q||this.DefaultInterpolation)}static toJSON($){let U=$.constructor,J;if(U.toJSON!==this.toJSON)J=U.toJSON($);else{J={name:$.name,times:rK($.times,Array),values:rK($.values,Array)};let Q=$.getInterpolation();if(Q!==$.DefaultInterpolation)J.interpolation=Q}return J.type=$.ValueTypeName,J}InterpolantFactoryMethodDiscrete($){return new yE(this.times,this.values,this.getValueSize(),$)}InterpolantFactoryMethodLinear($){return new M7(this.times,this.values,this.getValueSize(),$)}InterpolantFactoryMethodSmooth($){return new xE(this.times,this.values,this.getValueSize(),$)}InterpolantFactoryMethodBezier($){let U=new hE(this.times,this.values,this.getValueSize(),$);if(this.settings)U.inTangents=this.settings.inTangents,U.outTangents=this.settings.outTangents;return U}setInterpolation($){let U;switch($){case 2300:U=this.InterpolantFactoryMethodDiscrete;break;case 2301:U=this.InterpolantFactoryMethodLinear;break;case 2302:U=this.InterpolantFactoryMethodSmooth;break;case 2303:U=this.InterpolantFactoryMethodBezier;break}if(U===void 0){let J="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if($!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(J);return A$("KeyframeTrack:",J),this}return this.createInterpolant=U,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;case this.InterpolantFactoryMethodLinear:return 2301;case this.InterpolantFactoryMethodSmooth:return 2302;case this.InterpolantFactoryMethodBezier:return 2303}}getValueSize(){return this.values.length/this.times.length}shift($){if($!==0){let U=this.times;for(let J=0,Q=U.length;J!==Q;++J)U[J]+=$}return this}scale($){if($!==1){let U=this.times;for(let J=0,Q=U.length;J!==Q;++J)U[J]*=$}return this}trim($,U){let J=this.times,Q=J.length,W=0,K=Q-1;while(W!==Q&&J[W]<$)++W;while(K!==-1&&J[K]>U)--K;if(++K,W!==0||K!==Q){if(W>=K)K=Math.max(K,1),W=K-1;let X=this.getValueSize();this.times=J.slice(W,K),this.values=this.values.slice(W*X,K*X)}return this}validate(){let $=!0,U=this.getValueSize();if(U-Math.floor(U)!==0)y$("KeyframeTrack: Invalid value size in track.",this),$=!1;let J=this.times,Q=this.values,W=J.length;if(W===0)y$("KeyframeTrack: Track is empty.",this),$=!1;let K=null;for(let X=0;X!==W;X++){let N=J[X];if(typeof N==="number"&&isNaN(N)){y$("KeyframeTrack: Time is not a valid number.",this,X,N),$=!1;break}if(K!==null&&K>N){y$("KeyframeTrack: Out of order keys.",this,X,N,K),$=!1;break}K=N}if(Q!==void 0){if(jR(Q))for(let X=0,N=Q.length;X!==N;++X){let H=Q[X];if(isNaN(H)){y$("KeyframeTrack: Value is not a valid number.",this,X,H),$=!1;break}}}return $}optimize(){let $=this.times.slice(),U=this.values.slice(),J=this.getValueSize(),Q=this.getInterpolation()===2302,W=$.length-1,K=1;for(let X=1;X<W;++X){let N=!1,H=$[X],Y=$[X+1];if(H!==Y&&(X!==1||H!==$[0]))if(!Q){let G=X*J,O=G-J,E=G+J;for(let Z=0;Z!==J;++Z){let D=U[G+Z];if(D!==U[O+Z]||D!==U[E+Z]){N=!0;break}}}else N=!0;if(N){if(X!==K){$[K]=$[X];let G=X*J,O=K*J;for(let E=0;E!==J;++E)U[O+E]=U[G+E]}++K}}if(W>0){$[K]=$[W];for(let X=W*J,N=K*J,H=0;H!==J;++H)U[N+H]=U[X+H];++K}if(K!==$.length)this.times=$.slice(0,K),this.values=U.slice(0,K*J);else this.times=$,this.values=U;return this}clone(){let $=this.times.slice(),U=this.values.slice(),Q=new this.constructor(this.name,$,U);return Q.createInterpolant=this.createInterpolant,Q}}_U.prototype.ValueTypeName="";_U.prototype.TimeBufferType=Float32Array;_U.prototype.ValueBufferType=Float32Array;_U.prototype.DefaultInterpolation=2301;class E0 extends _U{constructor($,U,J){super($,U,J)}}E0.prototype.ValueTypeName="bool";E0.prototype.ValueBufferType=Array;E0.prototype.DefaultInterpolation=2300;E0.prototype.InterpolantFactoryMethodLinear=void 0;E0.prototype.InterpolantFactoryMethodSmooth=void 0;class B7 extends _U{constructor($,U,J,Q){super($,U,J,Q)}}B7.prototype.ValueTypeName="color";class Z0 extends _U{constructor($,U,J,Q){super($,U,J,Q)}}Z0.prototype.ValueTypeName="number";class fE extends xJ{constructor($,U,J,Q){super($,U,J,Q)}interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,N=(J-U)/(Q-U),H=$*X;for(let Y=H+X;H!==Y;H+=4)i6.slerpFlat(W,0,K,H-X,K,H,N);return W}}class I0 extends _U{constructor($,U,J,Q){super($,U,J,Q)}InterpolantFactoryMethodLinear($){return new fE(this.times,this.values,this.getValueSize(),$)}}I0.prototype.ValueTypeName="quaternion";I0.prototype.InterpolantFactoryMethodSmooth=void 0;class q0 extends _U{constructor($,U,J){super($,U,J)}}q0.prototype.ValueTypeName="string";q0.prototype.ValueBufferType=Array;q0.prototype.DefaultInterpolation=2300;q0.prototype.InterpolantFactoryMethodLinear=void 0;q0.prototype.InterpolantFactoryMethodSmooth=void 0;class c0 extends _U{constructor($,U,J,Q){super($,U,J,Q)}}c0.prototype.ValueTypeName="vector";class oW{constructor($="",U=-1,J=[],Q=2500){if(this.name=$,this.tracks=J,this.duration=U,this.blendMode=Q,this.uuid=iU(),this.userData={},this.duration<0)this.resetDuration()}static parse($){let U=[],J=$.tracks,Q=1/($.fps||1);for(let K=0,X=J.length;K!==X;++K)U.push(MV(J[K]).scale(Q));let W=new this($.name,$.duration,U,$.blendMode);return W.uuid=$.uuid,W.userData=JSON.parse($.userData||"{}"),W}static toJSON($){let U=[],J=$.tracks,Q={name:$.name,duration:$.duration,tracks:U,uuid:$.uuid,blendMode:$.blendMode,userData:JSON.stringify($.userData)};for(let W=0,K=J.length;W!==K;++W)U.push(_U.toJSON(J[W]));return Q}static CreateFromMorphTargetSequence($,U,J,Q){let W=U.length,K=[];for(let X=0;X<W;X++){let N=[],H=[];N.push((X+W-1)%W,X,(X+1)%W),H.push(0,1,0);let Y=RV(N);if(N=CD(N,1,Y),H=CD(H,1,Y),!Q&&N[0]===0)N.push(W),H.push(H[0]);K.push(new Z0(".morphTargetInfluences["+U[X].name+"]",N,H).scale(1/J))}return new this($,-1,K)}static findByName($,U){let J=$;if(!Array.isArray($)){let Q=$;J=Q.geometry&&Q.geometry.animations||Q.animations}for(let Q=0;Q<J.length;Q++)if(J[Q].name===U)return J[Q];return null}static CreateClipsFromMorphTargetSequences($,U,J){let Q={},W=/^([\w-]*?)([\d]+)$/;for(let X=0,N=$.length;X<N;X++){let H=$[X],Y=H.name.match(W);if(Y&&Y.length>1){let G=Y[1],O=Q[G];if(!O)Q[G]=O=[];O.push(H)}}let K=[];for(let X in Q)K.push(this.CreateFromMorphTargetSequence(X,Q[X],U,J));return K}resetDuration(){let $=this.tracks,U=0;for(let J=0,Q=$.length;J!==Q;++J){let W=this.tracks[J];U=Math.max(U,W.times[W.times.length-1])}return this.duration=U,this}trim(){for(let $=0;$<this.tracks.length;$++)this.tracks[$].trim(0,this.duration);return this}validate(){let $=!0;for(let U=0;U<this.tracks.length;U++)$=$&&this.tracks[U].validate();return $}optimize(){for(let $=0;$<this.tracks.length;$++)this.tracks[$].optimize();return this}clone(){let $=[];for(let J=0;J<this.tracks.length;J++)$.push(this.tracks[J].clone());let U=new this.constructor(this.name,this.duration,$,this.blendMode);return U.userData=JSON.parse(JSON.stringify(this.userData)),U}toJSON(){return this.constructor.toJSON(this)}}function wV($){switch($.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return Z0;case"vector":case"vector2":case"vector3":case"vector4":return c0;case"color":return B7;case"quaternion":return I0;case"bool":case"boolean":return E0;case"string":return q0}throw Error("THREE.KeyframeTrack: Unsupported typeName: "+$)}function MV($){if($.type===void 0)throw Error("THREE.KeyframeTrack: track type undefined, can not parse");let U=wV($.type);if($.times===void 0){let J=[],Q=[];VV($.keys,J,Q,"value"),$.times=J,$.values=Q}if(U.parse!==void 0)return U.parse($);else return new U($.name,$.times,$.values,$.interpolation)}var GJ={enabled:!1,files:{},add:function($,U){if(this.enabled===!1)return;if(SD($))return;this.files[$]=U},get:function($){if(this.enabled===!1)return;if(SD($))return;return this.files[$]},remove:function($){delete this.files[$]},clear:function(){this.files={}}};function SD($){try{let U=$.slice($.indexOf(":")+1);return new URL(U).protocol==="blob:"}catch(U){return!1}}class SQ{constructor($,U,J){let Q=this,W=!1,K=0,X=0,N=void 0,H=[];this.onStart=void 0,this.onLoad=$,this.onProgress=U,this.onError=J,this._abortController=null,this.itemStart=function(Y){if(X++,W===!1){if(Q.onStart!==void 0)Q.onStart(Y,K,X)}W=!0},this.itemEnd=function(Y){if(K++,Q.onProgress!==void 0)Q.onProgress(Y,K,X);if(K===X){if(W=!1,Q.onLoad!==void 0)Q.onLoad()}},this.itemError=function(Y){if(Q.onError!==void 0)Q.onError(Y)},this.resolveURL=function(Y){if(Y=Y.normalize("NFC"),N)return N(Y);return Y},this.setURLModifier=function(Y){return N=Y,this},this.addHandler=function(Y,G){return H.push(Y,G),this},this.removeHandler=function(Y){let G=H.indexOf(Y);if(G!==-1)H.splice(G,2);return this},this.getHandler=function(Y){for(let G=0,O=H.length;G<O;G+=2){let E=H[G],Z=H[G+1];if(E.global)E.lastIndex=0;if(E.test(Y))return Z}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){if(!this._abortController)this._abortController=new AbortController;return this._abortController}}var bk=new SQ;class yJ{constructor($){if(this.manager=$!==void 0?$:bk,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($,U){let J=this;return new Promise(function(Q,W){J.load($,Q,U,W)})}parse(){}setCrossOrigin($){return this.crossOrigin=$,this}setWithCredentials($){return this.withCredentials=$,this}setPath($){return this.path=$,this}setResourcePath($){return this.resourcePath=$,this}setRequestHeader($){return this.requestHeader=$,this}abort(){return this}}yJ.DEFAULT_MATERIAL_NAME="__DEFAULT";var TJ={};class xk extends Error{constructor($,U){super($);this.response=U}}class TQ extends yJ{constructor($){super($);this.mimeType="",this.responseType="",this._abortController=new AbortController}load($,U,J,Q){if($===void 0)$="";if(this.path!==void 0)$=this.path+$;$=this.manager.resolveURL($);let W=GJ.get(`file:${$}`);if(W!==void 0){this.manager.itemStart($),setTimeout(()=>{if(U)U(W);this.manager.itemEnd($)},0);return}if(TJ[$]!==void 0){TJ[$].push({onLoad:U,onProgress:J,onError:Q});return}TJ[$]=[],TJ[$].push({onLoad:U,onProgress:J,onError:Q});let K=new Request($,{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}),X=this.mimeType,N=this.responseType;fetch(K).then((H)=>{if(H.status===200||H.status===0){if(H.status===0)A$("FileLoader: HTTP Status 0 received.");if(typeof ReadableStream>"u"||H.body===void 0||H.body.getReader===void 0)return H;let Y=TJ[$],G=H.body.getReader(),O=H.headers.get("X-File-Size")||H.headers.get("Content-Length"),E=O?parseInt(O):0,Z=E!==0,D=0,R=new ReadableStream({start(I){q();function q(){G.read().then(({done:_,value:P})=>{if(_)I.close();else{D+=P.byteLength;let L=new ProgressEvent("progress",{lengthComputable:Z,loaded:D,total:E});for(let B=0,z=Y.length;B<z;B++){let A=Y[B];if(A.onProgress)A.onProgress(L)}I.enqueue(P),q()}},(_)=>{I.error(_)})}}});return new Response(R)}else throw new xk(`fetch for "${H.url}" responded with ${H.status}: ${H.statusText}`,H)}).then((H)=>{switch(N){case"arraybuffer":return H.arrayBuffer();case"blob":return H.blob();case"document":return H.text().then((Y)=>{return new DOMParser().parseFromString(Y,X)});case"json":return H.json();default:if(X==="")return H.text();else{let G=/charset="?([^;"\s]*)"?/i.exec(X),O=G&&G[1]?G[1].toLowerCase():void 0,E=new TextDecoder(O);return H.arrayBuffer().then((Z)=>E.decode(Z))}}}).then((H)=>{GJ.add(`file:${$}`,H);let Y=TJ[$];delete TJ[$];for(let G=0,O=Y.length;G<O;G++){let E=Y[G];if(E.onLoad)E.onLoad(H)}}).catch((H)=>{let Y=TJ[$];if(Y===void 0)throw this.manager.itemError($),H;delete TJ[$];for(let G=0,O=Y.length;G<O;G++){let E=Y[G];if(E.onError)E.onError(H)}this.manager.itemError($)}).finally(()=>{this.manager.itemEnd($)}),this.manager.itemStart($)}setResponseType($){return this.responseType=$,this}setMimeType($){return this.mimeType=$,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}var mW=new WeakMap;class uE extends yJ{constructor($){super($)}load($,U,J,Q){if(this.path!==void 0)$=this.path+$;$=this.manager.resolveURL($);let W=this,K=GJ.get(`image:${$}`);if(K!==void 0){if(K.complete===!0)W.manager.itemStart($),setTimeout(function(){if(U)U(K);W.manager.itemEnd($)},0);else{let G=mW.get(K);if(G===void 0)G=[],mW.set(K,G);G.push({onLoad:U,onError:Q})}return K}let X=nW("img");function N(){if(Y(),U)U(this);let G=mW.get(this)||[];for(let O=0;O<G.length;O++){let E=G[O];if(E.onLoad)E.onLoad(this)}mW.delete(this),W.manager.itemEnd($)}function H(G){if(Y(),Q)Q(G);GJ.remove(`image:${$}`);let O=mW.get(this)||[];for(let E=0;E<O.length;E++){let Z=O[E];if(Z.onError)Z.onError(G)}mW.delete(this),W.manager.itemError($),W.manager.itemEnd($)}function Y(){X.removeEventListener("load",N,!1),X.removeEventListener("error",H,!1)}if(X.addEventListener("load",N,!1),X.addEventListener("error",H,!1),$.slice(0,5)!=="data:"){if(this.crossOrigin!==void 0)X.crossOrigin=this.crossOrigin}return GJ.add(`image:${$}`,X),W.manager.itemStart($),X.src=$,X}}class P7 extends yJ{constructor($){super($)}load($,U,J,Q){let W=new v6,K=new uE(this.manager);return K.setCrossOrigin(this.crossOrigin),K.setPath(this.path),K.load($,function(X){if(W.image=X,W.needsUpdate=!0,U!==void 0)U(W)},J,Q),W}}class N8 extends k6{constructor($,U=1){super();this.isLight=!0,this.type="Light",this.color=new x$($),this.intensity=U}dispose(){this.dispatchEvent({type:"dispose"})}copy($,U){return super.copy($,U),this.color.copy($.color),this.intensity=$.intensity,this}toJSON($){let U=super.toJSON($);return U.object.color=this.color.getHex(),U.object.intensity=this.intensity,U}}class z7 extends N8{constructor($,U,J){super($,J);this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(k6.DEFAULT_UP),this.updateMatrix(),this.groundColor=new x$(U)}copy($,U){return super.copy($,U),this.groundColor.copy($.groundColor),this}toJSON($){let U=super.toJSON($);return U.object.groundColor=this.groundColor.getHex(),U}}var PO=new p$,TD=new j,vD=new j;class _7{constructor($){this.camera=$,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new g$(512,512),this.mapType=1009,this.map=null,this.mapPass=null,this.matrix=new p$,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new zQ,this._frameExtents=new g$(1,1),this._viewportCount=1,this._viewports=[new Z6(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices($){let U=this.camera,J=this.matrix;if(TD.setFromMatrixPosition($.matrixWorld),U.position.copy(TD),vD.setFromMatrixPosition($.target.matrixWorld),U.lookAt(vD),U.updateMatrixWorld(),PO.multiplyMatrices(U.projectionMatrix,U.matrixWorldInverse),this._frustum.setFromProjectionMatrix(PO,U.coordinateSystem,U.reversedDepth),U.coordinateSystem===2001||U.reversedDepth)J.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,1,0,0,0,0,1);else J.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1);J.multiply(PO)}getViewport($){return this._viewports[$]}getFrameExtents(){return this._frameExtents}dispose(){if(this.map)this.map.dispose();if(this.mapPass)this.mapPass.dispose()}copy($){return this.camera=$.camera.clone(),this.intensity=$.intensity,this.bias=$.bias,this.radius=$.radius,this.autoUpdate=$.autoUpdate,this.needsUpdate=$.needsUpdate,this.normalBias=$.normalBias,this.blurSamples=$.blurSamples,this.mapSize.copy($.mapSize),this.biasNode=$.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let $={};if(this.intensity!==1)$.intensity=this.intensity;if(this.bias!==0)$.bias=this.bias;if(this.normalBias!==0)$.normalBias=this.normalBias;if(this.radius!==1)$.radius=this.radius;if(this.mapSize.x!==512||this.mapSize.y!==512)$.mapSize=this.mapSize.toArray();return $.camera=this.camera.toJSON(!1).object,delete $.camera.matrix,$}}var aK=new j,sK=new i6,HJ=new j;class A7 extends k6{constructor(){super();this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new p$,this.projectionMatrix=new p$,this.projectionMatrixInverse=new p$,this.coordinateSystem=2000,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy($,U){return super.copy($,U),this.matrixWorldInverse.copy($.matrixWorldInverse),this.projectionMatrix.copy($.projectionMatrix),this.projectionMatrixInverse.copy($.projectionMatrixInverse),this.coordinateSystem=$.coordinateSystem,this}getWorldDirection($){return super.getWorldDirection($).negate()}updateMatrixWorld($){if(super.updateMatrixWorld($),this.matrixWorld.decompose(aK,sK,HJ),HJ.x===1&&HJ.y===1&&HJ.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(aK,sK,HJ.set(1,1,1)).invert()}updateWorldMatrix($,U,J=!1){if(super.updateWorldMatrix($,U,J),this.matrixWorld.decompose(aK,sK,HJ),HJ.x===1&&HJ.y===1&&HJ.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(aK,sK,HJ.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}var J0=new j,jD=new g$,gD=new g$;class f6 extends A7{constructor($=50,U=1,J=0.1,Q=2000){super();this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=$,this.zoom=1,this.near=J,this.far=Q,this.focus=10,this.aspect=U,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy($,U){return super.copy($,U),this.fov=$.fov,this.zoom=$.zoom,this.near=$.near,this.far=$.far,this.focus=$.focus,this.aspect=$.aspect,this.view=$.view===null?null:Object.assign({},$.view),this.filmGauge=$.filmGauge,this.filmOffset=$.filmOffset,this}setFocalLength($){let U=0.5*this.getFilmHeight()/$;this.fov=x0*2*Math.atan(U),this.updateProjectionMatrix()}getFocalLength(){let $=Math.tan(GQ*0.5*this.fov);return 0.5*this.getFilmHeight()/$}getEffectiveFOV(){return x0*2*Math.atan(Math.tan(GQ*0.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds($,U,J){J0.set(-1,-1,0.5).applyMatrix4(this.projectionMatrixInverse),U.set(J0.x,J0.y).multiplyScalar(-$/J0.z),J0.set(1,1,0.5).applyMatrix4(this.projectionMatrixInverse),J.set(J0.x,J0.y).multiplyScalar(-$/J0.z)}getViewSize($,U){return this.getViewBounds($,jD,gD),U.subVectors(gD,jD)}setViewOffset($,U,J,Q,W,K){if(this.aspect=$/U,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=$,this.view.fullHeight=U,this.view.offsetX=J,this.view.offsetY=Q,this.view.width=W,this.view.height=K,this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null)this.view.enabled=!1;this.updateProjectionMatrix()}updateProjectionMatrix(){let $=this.near,U=$*Math.tan(GQ*0.5*this.fov)/this.zoom,J=2*U,Q=this.aspect*J,W=-0.5*Q,K=this.view;if(this.view!==null&&this.view.enabled){let{fullWidth:N,fullHeight:H}=K;W+=K.offsetX*Q/N,U-=K.offsetY*J/H,Q*=K.width/N,J*=K.height/H}let X=this.filmOffset;if(X!==0)W+=$*X/this.getFilmWidth();this.projectionMatrix.makePerspective(W,W+Q,U,U-J,$,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON($){let U=super.toJSON($);if(U.object.fov=this.fov,U.object.zoom=this.zoom,U.object.near=this.near,U.object.far=this.far,U.object.focus=this.focus,U.object.aspect=this.aspect,this.view!==null)U.object.view=Object.assign({},this.view);return U.object.filmGauge=this.filmGauge,U.object.filmOffset=this.filmOffset,U}}class yk extends _7{constructor(){super(new f6(50,1,0.5,500));this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices($){let U=this.camera,J=x0*2*$.angle*this.focus,Q=this.mapSize.width/this.mapSize.height*this.aspect,W=$.distance||U.far;if(J!==U.fov||Q!==U.aspect||W!==U.far)U.fov=J,U.aspect=Q,U.far=W,U.updateProjectionMatrix();super.updateMatrices($)}copy($){return super.copy($),this.focus=$.focus,this}}class C7 extends N8{constructor($,U,J=0,Q=Math.PI/3,W=0,K=2){super($,U);this.isSpotLight=!0,this.type="SpotLight",this.position.copy(k6.DEFAULT_UP),this.updateMatrix(),this.target=new k6,this.distance=J,this.angle=Q,this.penumbra=W,this.decay=K,this.map=null,this.shadow=new yk}get power(){return this.intensity*Math.PI}set power($){this.intensity=$/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy($,U){return super.copy($,U),this.distance=$.distance,this.angle=$.angle,this.penumbra=$.penumbra,this.decay=$.decay,this.target=$.target.clone(),this.map=$.map,this.shadow=$.shadow.clone(),this}toJSON($){let U=super.toJSON($);if(U.object.distance=this.distance,U.object.angle=this.angle,U.object.decay=this.decay,U.object.penumbra=this.penumbra,U.object.target=this.target.uuid,this.map&&this.map.isTexture)U.object.map=this.map.toJSON($).uuid;return U.object.shadow=this.shadow.toJSON(),U}}class hk extends _7{constructor(){super(new f6(90,1,0.5,500));this.isPointLightShadow=!0}}class H8 extends N8{constructor($,U,J=0,Q=2){super($,U);this.isPointLight=!0,this.type="PointLight",this.distance=J,this.decay=Q,this.shadow=new hk}get power(){return this.intensity*4*Math.PI}set power($){this.intensity=$/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy($,U){return super.copy($,U),this.distance=$.distance,this.decay=$.decay,this.shadow=$.shadow.clone(),this}toJSON($){let U=super.toJSON($);return U.object.distance=this.distance,U.object.decay=this.decay,U.object.shadow=this.shadow.toJSON(),U}}class n0 extends A7{constructor($=-1,U=1,J=1,Q=-1,W=0.1,K=2000){super();this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=$,this.right=U,this.top=J,this.bottom=Q,this.near=W,this.far=K,this.updateProjectionMatrix()}copy($,U){return super.copy($,U),this.left=$.left,this.right=$.right,this.top=$.top,this.bottom=$.bottom,this.near=$.near,this.far=$.far,this.zoom=$.zoom,this.view=$.view===null?null:Object.assign({},$.view),this}setViewOffset($,U,J,Q,W,K){if(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=$,this.view.fullHeight=U,this.view.offsetX=J,this.view.offsetY=Q,this.view.width=W,this.view.height=K,this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null)this.view.enabled=!1;this.updateProjectionMatrix()}updateProjectionMatrix(){let $=(this.right-this.left)/(2*this.zoom),U=(this.top-this.bottom)/(2*this.zoom),J=(this.right+this.left)/2,Q=(this.top+this.bottom)/2,W=J-$,K=J+$,X=Q+U,N=Q-U;if(this.view!==null&&this.view.enabled){let H=(this.right-this.left)/this.view.fullWidth/this.zoom,Y=(this.top-this.bottom)/this.view.fullHeight/this.zoom;W+=H*this.view.offsetX,K=W+H*this.view.width,X-=Y*this.view.offsetY,N=X-Y*this.view.height}this.projectionMatrix.makeOrthographic(W,K,X,N,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON($){let U=super.toJSON($);if(U.object.zoom=this.zoom,U.object.left=this.left,U.object.right=this.right,U.object.top=this.top,U.object.bottom=this.bottom,U.object.near=this.near,U.object.far=this.far,this.view!==null)U.object.view=Object.assign({},this.view);return U}}class fk extends _7{constructor(){super(new n0(-5,5,5,-5,0.5,500));this.isDirectionalLightShadow=!0}}class Y8 extends N8{constructor($,U){super($,U);this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(k6.DEFAULT_UP),this.updateMatrix(),this.target=new k6,this.shadow=new fk}dispose(){super.dispose(),this.shadow.dispose()}copy($){return super.copy($),this.target=$.target.clone(),this.shadow=$.shadow.clone(),this}toJSON($){let U=super.toJSON($);return U.object.shadow=this.shadow.toJSON(),U.object.target=this.target.uuid,U}}class D0{static extractUrlBase($){let U=$.lastIndexOf("/");if(U===-1)return"./";return $.slice(0,U+1)}static resolveURL($,U){if(typeof $!=="string"||$==="")return"";if(/^https?:\/\//i.test(U)&&/^\//.test($))U=U.replace(/(^https?:\/\/[^\/]+).*/i,"$1");if(/^(https?:)?\/\//i.test($))return $;if(/^data:.*,.*$/i.test($))return $;if(/^blob:.*$/i.test($))return $;return U+$}}var zO=new WeakMap;class S7 extends yJ{constructor($){super($);if(this.isImageBitmapLoader=!0,typeof createImageBitmap>"u")A$("ImageBitmapLoader: createImageBitmap() not supported.");if(typeof fetch>"u")A$("ImageBitmapLoader: fetch() not supported.");this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions($){return this.options=$,this}load($,U,J,Q){if($===void 0)$="";if(this.path!==void 0)$=this.path+$;$=this.manager.resolveURL($);let W=this,K=GJ.get(`image-bitmap:${$}`);if(K!==void 0){if(W.manager.itemStart($),K.then){K.then((H)=>{if(zO.has(K)===!0){if(Q)Q(zO.get(K));W.manager.itemError($),W.manager.itemEnd($)}else{if(U)U(H);W.manager.itemEnd($)}});return}setTimeout(function(){if(U)U(K);W.manager.itemEnd($)},0);return}let X={};X.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",X.headers=this.requestHeader,X.signal=typeof AbortSignal.any==="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let N=fetch($,X).then(function(H){return H.blob()}).then(function(H){return createImageBitmap(H,Object.assign(W.options,{colorSpaceConversion:"none"}))}).then(function(H){if(GJ.add(`image-bitmap:${$}`,H),U)U(H);W.manager.itemEnd($)}).catch(function(H){if(Q)Q(H);zO.set(N,H),GJ.remove(`image-bitmap:${$}`),W.manager.itemError($),W.manager.itemEnd($)});GJ.add(`image-bitmap:${$}`,N),W.manager.itemStart($)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}var pW=-90,dW=1;class lE extends k6{constructor($,U,J){super();this.type="CubeCamera",this.renderTarget=J,this.coordinateSystem=null,this.activeMipmapLevel=0;let Q=new f6(pW,dW,$,U);Q.layers=this.layers,this.add(Q);let W=new f6(pW,dW,$,U);W.layers=this.layers,this.add(W);let K=new f6(pW,dW,$,U);K.layers=this.layers,this.add(K);let X=new f6(pW,dW,$,U);X.layers=this.layers,this.add(X);let N=new f6(pW,dW,$,U);N.layers=this.layers,this.add(N);let H=new f6(pW,dW,$,U);H.layers=this.layers,this.add(H)}updateCoordinateSystem(){let $=this.coordinateSystem,U=this.children.concat(),[J,Q,W,K,X,N]=U;for(let H of U)this.remove(H);if($===2000)J.up.set(0,1,0),J.lookAt(1,0,0),Q.up.set(0,1,0),Q.lookAt(-1,0,0),W.up.set(0,0,-1),W.lookAt(0,1,0),K.up.set(0,0,1),K.lookAt(0,-1,0),X.up.set(0,1,0),X.lookAt(0,0,1),N.up.set(0,1,0),N.lookAt(0,0,-1);else if($===2001)J.up.set(0,-1,0),J.lookAt(-1,0,0),Q.up.set(0,-1,0),Q.lookAt(1,0,0),W.up.set(0,0,1),W.lookAt(0,1,0),K.up.set(0,0,-1),K.lookAt(0,-1,0),X.up.set(0,-1,0),X.lookAt(0,0,1),N.up.set(0,-1,0),N.lookAt(0,0,-1);else throw Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+$);for(let H of U)this.add(H),H.updateMatrixWorld()}update($,U){if(this.parent===null)this.updateMatrixWorld();let{renderTarget:J,activeMipmapLevel:Q}=this;if(this.coordinateSystem!==$.coordinateSystem)this.coordinateSystem=$.coordinateSystem,this.updateCoordinateSystem();let[W,K,X,N,H,Y]=this.children,G=$.getRenderTarget(),O=$.getActiveCubeFace(),E=$.getActiveMipmapLevel(),Z=$.xr.enabled;$.xr.enabled=!1;let D=J.texture.generateMipmaps;J.texture.generateMipmaps=!1;let R=!1;if($.isWebGLRenderer===!0)R=$.state.buffers.depth.getReversed();else R=$.reversedDepthBuffer;if($.setRenderTarget(J,0,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,W),$.setRenderTarget(J,1,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,K),$.setRenderTarget(J,2,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,X),$.setRenderTarget(J,3,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,N),$.setRenderTarget(J,4,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,H),J.texture.generateMipmaps=D,$.setRenderTarget(J,5,Q),R&&$.autoClear===!1)$.clearDepth();$.render(U,Y),$.setRenderTarget(G,O,E),$.xr.enabled=Z,J.texture.needsPMREMUpdate=!0}}class mE extends f6{constructor($=[]){super();this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=$}}class pE{constructor($,U,J){this.binding=$,this.valueSize=J;let Q,W,K;switch(U){case"quaternion":Q=this._slerp,W=this._slerpAdditive,K=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(J*6),this._workIndex=5;break;case"string":case"bool":Q=this._select,W=this._select,K=this._setAdditiveIdentityOther,this.buffer=Array(J*5);break;default:Q=this._lerp,W=this._lerpAdditive,K=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(J*5)}this._mixBufferRegion=Q,this._mixBufferRegionAdditive=W,this._setIdentity=K,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate($,U){let J=this.buffer,Q=this.valueSize,W=$*Q+Q,K=this.cumulativeWeight;if(K===0){for(let X=0;X!==Q;++X)J[W+X]=J[X];K=U}else{K+=U;let X=U/K;this._mixBufferRegion(J,W,0,X,Q)}this.cumulativeWeight=K}accumulateAdditive($){let U=this.buffer,J=this.valueSize,Q=J*this._addIndex;if(this.cumulativeWeightAdditive===0)this._setIdentity();this._mixBufferRegionAdditive(U,Q,0,$,J),this.cumulativeWeightAdditive+=$}apply($){let U=this.valueSize,J=this.buffer,Q=$*U+U,W=this.cumulativeWeight,K=this.cumulativeWeightAdditive,X=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,W<1){let N=U*this._origIndex;this._mixBufferRegion(J,Q,N,1-W,U)}if(K>0)this._mixBufferRegionAdditive(J,Q,this._addIndex*U,1,U);for(let N=U,H=U+U;N!==H;++N)if(J[N]!==J[N+U]){X.setValue(J,Q);break}}saveOriginalState(){let $=this.binding,U=this.buffer,J=this.valueSize,Q=J*this._origIndex;$.getValue(U,Q);for(let W=J,K=Q;W!==K;++W)U[W]=U[Q+W%J];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let $=this.valueSize*3;this.binding.setValue(this.buffer,$)}_setAdditiveIdentityNumeric(){let $=this._addIndex*this.valueSize,U=$+this.valueSize;for(let J=$;J<U;J++)this.buffer[J]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let $=this._origIndex*this.valueSize,U=this._addIndex*this.valueSize;for(let J=0;J<this.valueSize;J++)this.buffer[U+J]=this.buffer[$+J]}_select($,U,J,Q,W){if(Q>=0.5)for(let K=0;K!==W;++K)$[U+K]=$[J+K]}_slerp($,U,J,Q){i6.slerpFlat($,U,$,U,$,J,Q)}_slerpAdditive($,U,J,Q,W){let K=this._workIndex*W;i6.multiplyQuaternionsFlat($,K,$,U,$,J),i6.slerpFlat($,U,$,U,$,K,Q)}_lerp($,U,J,Q,W){let K=1-Q;for(let X=0;X!==W;++X){let N=U+X;$[N]=$[N]*K+$[J+X]*Q}}_lerpAdditive($,U,J,Q,W){for(let K=0;K!==W;++K){let X=U+K;$[X]=$[X]+$[J+K]*Q}}}var dE="\\[\\]\\.:\\/",BV=new RegExp("["+dE+"]","g"),cE="[^"+dE+"]",PV="[^"+dE.replace("\\.","")+"]",zV=/((?:WC+[\/:])*)/.source.replace("WC",cE),_V=/(WCOD+)?/.source.replace("WCOD",PV),AV=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",cE),CV=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",cE),SV=new RegExp("^"+zV+_V+AV+CV+"$"),TV=["material","materials","bones","map"];class uk{constructor($,U,J){let Q=J||Y6.parseTrackName(U);this._targetGroup=$,this._bindings=$.subscribe_(U,Q)}getValue($,U){this.bind();let J=this._targetGroup.nCachedObjects_,Q=this._bindings[J];if(Q!==void 0)Q.getValue($,U)}setValue($,U){let J=this._bindings;for(let Q=this._targetGroup.nCachedObjects_,W=J.length;Q!==W;++Q)J[Q].setValue($,U)}bind(){let $=this._bindings;for(let U=this._targetGroup.nCachedObjects_,J=$.length;U!==J;++U)$[U].bind()}unbind(){let $=this._bindings;for(let U=this._targetGroup.nCachedObjects_,J=$.length;U!==J;++U)$[U].unbind()}}class Y6{constructor($,U,J){this.path=U,this.parsedPath=J||Y6.parseTrackName(U),this.node=Y6.findNode($,this.parsedPath.nodeName),this.rootNode=$,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create($,U,J){if(!($&&$.isAnimationObjectGroup))return new Y6($,U,J);else return new Y6.Composite($,U,J)}static sanitizeNodeName($){return $.replace(/\s/g,"_").replace(BV,"")}static parseTrackName($){let U=SV.exec($);if(U===null)throw Error("THREE.PropertyBinding: Cannot parse trackName: "+$);let J={nodeName:U[2],objectName:U[3],objectIndex:U[4],propertyName:U[5],propertyIndex:U[6]},Q=J.nodeName&&J.nodeName.lastIndexOf(".");if(Q!==void 0&&Q!==-1){let W=J.nodeName.substring(Q+1);if(TV.indexOf(W)!==-1)J.nodeName=J.nodeName.substring(0,Q),J.objectName=W}if(J.propertyName===null||J.propertyName.length===0)throw Error("THREE.PropertyBinding: can not parse propertyName from trackName: "+$);return J}static findNode($,U){if(U===void 0||U===""||U==="."||U===-1||U===$.name||U===$.uuid)return $;if($.skeleton){let J=$.skeleton.getBoneByName(U);if(J!==void 0)return J}if($.children){let J=function(W){for(let K=0;K<W.length;K++){let X=W[K];if(X.name===U||X.uuid===U)return X;let N=J(X.children);if(N)return N}return null},Q=J($.children);if(Q)return Q}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct($,U){$[U]=this.targetObject[this.propertyName]}_getValue_array($,U){let J=this.resolvedProperty;for(let Q=0,W=J.length;Q!==W;++Q)$[U++]=J[Q]}_getValue_arrayElement($,U){$[U]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray($,U){this.resolvedProperty.toArray($,U)}_setValue_direct($,U){this.targetObject[this.propertyName]=$[U]}_setValue_direct_setNeedsUpdate($,U){this.targetObject[this.propertyName]=$[U],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate($,U){this.targetObject[this.propertyName]=$[U],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array($,U){let J=this.resolvedProperty;for(let Q=0,W=J.length;Q!==W;++Q)J[Q]=$[U++]}_setValue_array_setNeedsUpdate($,U){let J=this.resolvedProperty;for(let Q=0,W=J.length;Q!==W;++Q)J[Q]=$[U++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate($,U){let J=this.resolvedProperty;for(let Q=0,W=J.length;Q!==W;++Q)J[Q]=$[U++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement($,U){this.resolvedProperty[this.propertyIndex]=$[U]}_setValue_arrayElement_setNeedsUpdate($,U){this.resolvedProperty[this.propertyIndex]=$[U],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate($,U){this.resolvedProperty[this.propertyIndex]=$[U],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray($,U){this.resolvedProperty.fromArray($,U)}_setValue_fromArray_setNeedsUpdate($,U){this.resolvedProperty.fromArray($,U),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate($,U){this.resolvedProperty.fromArray($,U),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound($,U){this.bind(),this.getValue($,U)}_setValue_unbound($,U){this.bind(),this.setValue($,U)}bind(){let $=this.node,U=this.parsedPath,J=U.objectName,Q=U.propertyName,W=U.propertyIndex;if(!$)$=Y6.findNode(this.rootNode,U.nodeName),this.node=$;if(this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!$){A$("PropertyBinding: No target node found for track: "+this.path+".");return}if(J){let H=U.objectIndex;switch(J){case"materials":if(!$.material){y$("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!$.material.materials){y$("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}$=$.material.materials;break;case"bones":if(!$.skeleton){y$("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}$=$.skeleton.bones;for(let Y=0;Y<$.length;Y++)if($[Y].name===H){H=Y;break}break;case"map":if("map"in $){$=$.map;break}if(!$.material){y$("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!$.material.map){y$("PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}$=$.material.map;break;default:if($[J]===void 0){y$("PropertyBinding: Can not bind to objectName of node undefined.",this);return}$=$[J]}if(H!==void 0){if($[H]===void 0){y$("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,$);return}$=$[H]}}let K=$[Q];if(K===void 0){let H=U.nodeName;y$("PropertyBinding: Trying to update property for track: "+H+"."+Q+" but it wasn't found.",$);return}let X=this.Versioning.None;if(this.targetObject=$,$.isMaterial===!0)X=this.Versioning.NeedsUpdate;else if($.isObject3D===!0)X=this.Versioning.MatrixWorldNeedsUpdate;let N=this.BindingType.Direct;if(W!==void 0){if(Q==="morphTargetInfluences"){if(!$.geometry){y$("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!$.geometry.morphAttributes){y$("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}if($.morphTargetDictionary[W]!==void 0)W=$.morphTargetDictionary[W]}N=this.BindingType.ArrayElement,this.resolvedProperty=K,this.propertyIndex=W}else if(K.fromArray!==void 0&&K.toArray!==void 0)N=this.BindingType.HasFromToArray,this.resolvedProperty=K;else if(Array.isArray(K))N=this.BindingType.EntireArray,this.resolvedProperty=K;else this.propertyName=Q;this.getValue=this.GetterByBindingType[N],this.setValue=this.SetterByBindingTypeAndVersioning[N][X]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}Y6.Composite=uk;Y6.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};Y6.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};Y6.prototype.GetterByBindingType=[Y6.prototype._getValue_direct,Y6.prototype._getValue_array,Y6.prototype._getValue_arrayElement,Y6.prototype._getValue_toArray];Y6.prototype.SetterByBindingTypeAndVersioning=[[Y6.prototype._setValue_direct,Y6.prototype._setValue_direct_setNeedsUpdate,Y6.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Y6.prototype._setValue_array,Y6.prototype._setValue_array_setNeedsUpdate,Y6.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Y6.prototype._setValue_arrayElement,Y6.prototype._setValue_arrayElement_setNeedsUpdate,Y6.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Y6.prototype._setValue_fromArray,Y6.prototype._setValue_fromArray_setNeedsUpdate,Y6.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class nE{constructor($,U,J=null,Q=U.blendMode){this._mixer=$,this._clip=U,this._localRoot=J,this.blendMode=Q;let W=U.tracks,K=W.length,X=Array(K),N={endingStart:2400,endingEnd:2400};for(let H=0;H!==K;++H){let Y=W[H].createInterpolant(null);X[H]=Y,Y.settings=N}this._interpolantSettings=N,this._interpolants=X,this._propertyBindings=Array(K),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._restoreTimeScale=null,this._weightInterpolant=null,this.loop=2201,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($){return this._startTime=$,this}setLoop($,U){return this.loop=$,this.repetitions=U,this}setEffectiveWeight($){return this.weight=$,this._effectiveWeight=this.enabled?$:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn($){return this._scheduleFading($,0,1)}fadeOut($){return this._scheduleFading($,1,0)}crossFadeFrom($,U,J=!1){if($.fadeOut(U),this.fadeIn(U),J===!0){let Q=this._clip.duration,W=$._clip.duration,K=W/Q,X=Q/W;$._restoreTimeScale=$.timeScale,this._restoreTimeScale=this.timeScale,$.warp(1,K,U),this.warp(X,1,U)}return this}crossFadeTo($,U,J=!1){return $.crossFadeFrom(this,U,J)}stopFading(){let $=this._weightInterpolant;if($!==null)this._weightInterpolant=null,this._mixer._takeBackControlInterpolant($);return this}setEffectiveTimeScale($){return this.timeScale=$,this._effectiveTimeScale=this.paused?0:$,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration($){return this.timeScale=this._clip.duration/$,this.stopWarping()}syncWith($){return this.time=$.time,this.timeScale=$.timeScale,this.stopWarping()}halt($){return this.warp(this._effectiveTimeScale,0,$)}warp($,U,J){let Q=this._mixer,W=Q.time,K=this.timeScale,X=this._timeScaleInterpolant;if(X===null)X=Q._lendControlInterpolant(),this._timeScaleInterpolant=X;let{parameterPositions:N,sampleValues:H}=X;return N[0]=W,N[1]=W+J,H[0]=$/K,H[1]=U/K,this}stopWarping(){let $=this._timeScaleInterpolant;if($!==null)this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant($);return this._restoreTimeScale=null,this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update($,U,J,Q){if(!this.enabled){this._updateWeight($);return}let W=this._startTime;if(W!==null){let N=($-W)*J;if(N<0||J===0)U=0;else this._startTime=null,U=J*N}U*=this._updateTimeScale($);let K=this._updateTime(U),X=this._updateWeight($);if(X>0){let N=this._interpolants,H=this._propertyBindings;switch(this.blendMode){case 2501:for(let Y=0,G=N.length;Y!==G;++Y)N[Y].evaluate(K),H[Y].accumulateAdditive(X);break;case 2500:default:for(let Y=0,G=N.length;Y!==G;++Y)N[Y].evaluate(K),H[Y].accumulate(Q,X)}}}_updateWeight($){let U=0;if(this.enabled){U=this.weight;let J=this._weightInterpolant;if(J!==null){let Q=J.evaluate($)[0];if(U*=Q,$>J.parameterPositions[1]){if(this.stopFading(),Q===0)this.enabled=!1}}}return this._effectiveWeight=U,U}_updateTimeScale($){let U=0;if(!this.paused){U=this.timeScale;let J=this._timeScaleInterpolant;if(J!==null){let Q=J.evaluate($)[0];if(U*=Q,$>J.parameterPositions[1]){if(U===0)this.paused=!0;else{if(this._restoreTimeScale!==null)U=this._restoreTimeScale;this.timeScale=U}this.stopWarping()}}}return this._effectiveTimeScale=U,U}_updateTime($){let U=this._clip.duration,J=this.loop,Q=this.time+$,W=this._loopCount,K=J===2202;if($===0){if(W===-1)return Q;return K&&(W&1)===1?U-Q:Q}if(J===2200){if(W===-1)this._loopCount=0,this._setEndings(!0,!0,!1);$:{if(Q>=U)Q=U;else if(Q<0)Q=0;else{this.time=Q;break $}if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;this.time=Q,this._mixer.dispatchEvent({type:"finished",action:this,direction:$<0?-1:1})}}else{if(W===-1)if($>=0)W=0,this._setEndings(!0,this.repetitions===0,K);else this._setEndings(this.repetitions===0,!0,K);if(Q>=U||Q<0){let X=Math.floor(Q/U);Q-=U*X,W+=Math.abs(X);let N=this.repetitions-W;if(N<=0){if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;Q=$>0?U:0,this.time=Q,this._mixer.dispatchEvent({type:"finished",action:this,direction:$>0?1:-1})}else{if(N===1){let H=$<0;this._setEndings(H,!H,K)}else this._setEndings(!1,!1,K);this._loopCount=W,this.time=Q,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:X})}}else this._loopCount=W,this.time=Q;if(K&&(W&1)===1)return U-Q}return Q}_setEndings($,U,J){let Q=this._interpolantSettings;if(J)Q.endingStart=2401,Q.endingEnd=2401;else{if($)Q.endingStart=this.zeroSlopeAtStart?2401:2400;else Q.endingStart=2402;if(U)Q.endingEnd=this.zeroSlopeAtEnd?2401:2400;else Q.endingEnd=2402}}_scheduleFading($,U,J){let Q=this._mixer,W=Q.time,K=this._weightInterpolant;if(K===null)K=Q._lendControlInterpolant(),this._weightInterpolant=K;let{parameterPositions:X,sampleValues:N}=K;return X[0]=W,N[0]=U,X[1]=W+$,N[1]=J,this}}var vV=new Float32Array(1);class T7 extends sU{constructor($){super();if(this._root=$,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction($,U){let J=$._localRoot||this._root,Q=$._clip.tracks,W=Q.length,K=$._propertyBindings,X=$._interpolants,N=J.uuid,H=this._bindingsByRootAndName,Y=H[N];if(Y===void 0)Y={},H[N]=Y;for(let G=0;G!==W;++G){let O=Q[G],E=O.name,Z=Y[E];if(Z!==void 0)++Z.referenceCount,K[G]=Z;else{if(Z=K[G],Z!==void 0){if(Z._cacheIndex===null)++Z.referenceCount,this._addInactiveBinding(Z,N,E);continue}let D=U&&U._propertyBindings[G].binding.parsedPath;Z=new pE(Y6.create(J,E,D),O.ValueTypeName,O.getValueSize()),++Z.referenceCount,this._addInactiveBinding(Z,N,E),K[G]=Z}X[G].resultBuffer=Z.buffer}}_activateAction($){if(!this._isActiveAction($)){if($._cacheIndex===null){let J=($._localRoot||this._root).uuid,Q=$._clip.uuid,W=this._actionsByClip[Q];this._bindAction($,W&&W.knownActions[0]),this._addInactiveAction($,Q,J)}let U=$._propertyBindings;for(let J=0,Q=U.length;J!==Q;++J){let W=U[J];if(W.useCount++===0)this._lendBinding(W),W.saveOriginalState()}this._lendAction($)}}_deactivateAction($){if(this._isActiveAction($)){let U=$._propertyBindings;for(let J=0,Q=U.length;J!==Q;++J){let W=U[J];if(--W.useCount===0)W.restoreOriginalState(),this._takeBackBinding(W)}this._takeBackAction($)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let $=this;this.stats={actions:{get total(){return $._actions.length},get inUse(){return $._nActiveActions}},bindings:{get total(){return $._bindings.length},get inUse(){return $._nActiveBindings}},controlInterpolants:{get total(){return $._controlInterpolants.length},get inUse(){return $._nActiveControlInterpolants}}}}_isActiveAction($){let U=$._cacheIndex;return U!==null&&U<this._nActiveActions}_addInactiveAction($,U,J){let Q=this._actions,W=this._actionsByClip,K=W[U];if(K===void 0)K={knownActions:[$],actionByRoot:{}},$._byClipCacheIndex=0,W[U]=K;else{let X=K.knownActions;$._byClipCacheIndex=X.length,X.push($)}$._cacheIndex=Q.length,Q.push($),K.actionByRoot[J]=$}_removeInactiveAction($){let U=this._actions,J=U[U.length-1],Q=$._cacheIndex;J._cacheIndex=Q,U[Q]=J,U.pop(),$._cacheIndex=null;let W=$._clip.uuid,K=this._actionsByClip,X=K[W],N=X.knownActions,H=N[N.length-1],Y=$._byClipCacheIndex;H._byClipCacheIndex=Y,N[Y]=H,N.pop(),$._byClipCacheIndex=null;let G=X.actionByRoot,O=($._localRoot||this._root).uuid;if(delete G[O],N.length===0)delete K[W];this._removeInactiveBindingsForAction($)}_removeInactiveBindingsForAction($){let U=$._propertyBindings;for(let J=0,Q=U.length;J!==Q;++J){let W=U[J];if(--W.referenceCount===0)this._removeInactiveBinding(W)}}_lendAction($){let U=this._actions,J=$._cacheIndex,Q=this._nActiveActions++,W=U[Q];$._cacheIndex=Q,U[Q]=$,W._cacheIndex=J,U[J]=W}_takeBackAction($){let U=this._actions,J=$._cacheIndex,Q=--this._nActiveActions,W=U[Q];$._cacheIndex=Q,U[Q]=$,W._cacheIndex=J,U[J]=W}_addInactiveBinding($,U,J){let Q=this._bindingsByRootAndName,W=this._bindings,K=Q[U];if(K===void 0)K={},Q[U]=K;K[J]=$,$._cacheIndex=W.length,W.push($)}_removeInactiveBinding($){let U=this._bindings,J=$.binding,Q=J.rootNode.uuid,W=J.path,K=this._bindingsByRootAndName,X=K[Q],N=U[U.length-1],H=$._cacheIndex;if(N._cacheIndex=H,U[H]=N,U.pop(),delete X[W],Object.keys(X).length===0)delete K[Q]}_lendBinding($){let U=this._bindings,J=$._cacheIndex,Q=this._nActiveBindings++,W=U[Q];$._cacheIndex=Q,U[Q]=$,W._cacheIndex=J,U[J]=W}_takeBackBinding($){let U=this._bindings,J=$._cacheIndex,Q=--this._nActiveBindings,W=U[Q];$._cacheIndex=Q,U[Q]=$,W._cacheIndex=J,U[J]=W}_lendControlInterpolant(){let $=this._controlInterpolants,U=this._nActiveControlInterpolants++,J=$[U];if(J===void 0)J=new M7(new Float32Array(2),new Float32Array(2),1,vV),J.__cacheIndex=U,$[U]=J;return J}_takeBackControlInterpolant($){let U=this._controlInterpolants,J=$.__cacheIndex,Q=--this._nActiveControlInterpolants,W=U[Q];$.__cacheIndex=Q,U[Q]=$,W.__cacheIndex=J,U[J]=W}clipAction($,U,J){let Q=U||this._root,W=Q.uuid,K=typeof $==="string"?oW.findByName(Q,$):$,X=K!==null?K.uuid:$,N=this._actionsByClip[X],H=null;if(J===void 0)if(K!==null)J=K.blendMode;else J=2500;if(N!==void 0){let G=N.actionByRoot[W];if(G!==void 0&&G.blendMode===J)return G;if(H=N.knownActions[0],K===null)K=H._clip}if(K===null)return null;let Y=new nE(this,K,U,J);return this._bindAction(Y,H),this._addInactiveAction(Y,X,W),Y}existingAction($,U){let J=U||this._root,Q=J.uuid,W=typeof $==="string"?oW.findByName(J,$):$,K=W?W.uuid:$,X=this._actionsByClip[K];if(X!==void 0)return X.actionByRoot[Q]||null;return null}stopAllAction(){let $=this._actions,U=this._nActiveActions;for(let J=U-1;J>=0;--J)$[J].stop();return this}update($){$*=this.timeScale;let U=this._actions,J=this._nActiveActions,Q=this.time+=$,W=Math.sign($),K=this._accuIndex^=1;for(let H=0;H!==J;++H)U[H]._update(Q,$,W,K);let X=this._bindings,N=this._nActiveBindings;for(let H=0;H!==N;++H)X[H].apply(K);return this}setTime($){this.time=0;for(let U=0;U<this._actions.length;U++)this._actions[U].time=0;return this.update($)}getRoot(){return this._root}uncacheClip($){let U=this._actions,J=$.uuid,Q=this._actionsByClip,W=Q[J];if(W!==void 0){let K=W.knownActions;for(let X=0,N=K.length;X!==N;++X){let H=K[X];this._deactivateAction(H);let Y=H._cacheIndex,G=U[U.length-1];H._cacheIndex=null,H._byClipCacheIndex=null,G._cacheIndex=Y,U[Y]=G,U.pop(),this._removeInactiveBindingsForAction(H)}delete Q[J]}}uncacheRoot($){let U=$.uuid,J=this._actionsByClip;for(let K in J){let X=J[K].actionByRoot,N=X[U];if(N!==void 0)this._deactivateAction(N),this._removeInactiveAction(N)}let Q=this._bindingsByRootAndName,W=Q[U];if(W!==void 0)for(let K in W){let X=W[K];X.restoreOriginalState(),this._removeInactiveBinding(X)}}uncacheAction($,U){let J=this.existingAction($,U);if(J!==null)this._deactivateAction(J),this._removeInactiveAction(J)}}class vQ{constructor($=1,U=0,J=0){this.radius=$,this.phi=U,this.theta=J}set($,U,J){return this.radius=$,this.phi=U,this.theta=J,this}copy($){return this.radius=$.radius,this.phi=$.phi,this.theta=$.theta,this}makeSafe(){return this.phi=t$(this.phi,0.000001,Math.PI-0.000001),this}setFromVector3($){return this.setFromCartesianCoords($.x,$.y,$.z)}setFromCartesianCoords($,U,J){if(this.radius=Math.sqrt($*$+U*U+J*J),this.radius===0)this.theta=0,this.phi=0;else this.theta=Math.atan2($,J),this.phi=Math.acos(t$(U/this.radius,-1,1));return this}clone(){return new this.constructor().copy(this)}}class iE{static{iE.prototype.isMatrix2=!0}constructor($,U,J,Q){if(this.elements=[1,0,0,1],$!==void 0)this.set($,U,J,Q)}identity(){return this.set(1,0,0,1),this}fromArray($,U=0){for(let J=0;J<4;J++)this.elements[J]=$[J+U];return this}set($,U,J,Q){let W=this.elements;return W[0]=$,W[2]=U,W[1]=J,W[3]=Q,this}}class v7 extends sU{constructor($,U=null){super();this.object=$,this.domElement=U,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect($){if($===void 0){A$("Controls: connect() now requires an element.");return}if(this.domElement!==null)this.disconnect();this.domElement=$}disconnect(){}dispose(){}update(){}}function oE($,U,J,Q){let W=jV(Q);switch(J){case 1021:return $*U;case 1028:return $*U/W.components*W.byteLength;case 1029:return $*U/W.components*W.byteLength;case 1030:return $*U*2/W.components*W.byteLength;case 1031:return $*U*2/W.components*W.byteLength;case 1022:return $*U*3/W.components*W.byteLength;case 1023:return $*U*4/W.components*W.byteLength;case 1033:return $*U*4/W.components*W.byteLength;case 33776:case 33777:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*8;case 33778:case 33779:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*16;case 35841:case 35843:return Math.max($,16)*Math.max(U,8)/4;case 35840:case 35842:return Math.max($,8)*Math.max(U,8)/2;case 36196:case 37492:case 37488:case 37489:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*8;case 37496:case 37490:case 37491:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*16;case 37808:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*16;case 37809:return Math.floor(($+4)/5)*Math.floor((U+3)/4)*16;case 37810:return Math.floor(($+4)/5)*Math.floor((U+4)/5)*16;case 37811:return Math.floor(($+5)/6)*Math.floor((U+4)/5)*16;case 37812:return Math.floor(($+5)/6)*Math.floor((U+5)/6)*16;case 37813:return Math.floor(($+7)/8)*Math.floor((U+4)/5)*16;case 37814:return Math.floor(($+7)/8)*Math.floor((U+5)/6)*16;case 37815:return Math.floor(($+7)/8)*Math.floor((U+7)/8)*16;case 37816:return Math.floor(($+9)/10)*Math.floor((U+4)/5)*16;case 37817:return Math.floor(($+9)/10)*Math.floor((U+5)/6)*16;case 37818:return Math.floor(($+9)/10)*Math.floor((U+7)/8)*16;case 37819:return Math.floor(($+9)/10)*Math.floor((U+9)/10)*16;case 37820:return Math.floor(($+11)/12)*Math.floor((U+9)/10)*16;case 37821:return Math.floor(($+11)/12)*Math.floor((U+11)/12)*16;case 36492:case 36494:case 36495:return Math.ceil($/4)*Math.ceil(U/4)*16;case 36283:case 36284:return Math.ceil($/4)*Math.ceil(U/4)*8;case 36285:case 36286:return Math.ceil($/4)*Math.ceil(U/4)*16}throw Error(`Unable to determine texture byte length for ${J} format.`)}function jV($){switch($){case 1009:case 1010:return{byteLength:1,components:1};case 1012:case 1011:case 1016:return{byteLength:2,components:1};case 1017:case 1018:return{byteLength:2,components:4};case 1014:case 1013:case 1015:return{byteLength:4,components:1};case 35902:case 35899:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${$}.`)}if(typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"185"}}));if(typeof window<"u")if(window.__THREE__)A$("WARNING: Multiple instances of Three.js being imported.");else window.__THREE__="185";function Y5(){let $=null,U=!1,J=null,Q=null;function W(K,X){J(K,X),Q=$.requestAnimationFrame(W)}return{start:function(){if(U===!0)return;if(J===null)return;if($===null)return;Q=$.requestAnimationFrame(W),U=!0},stop:function(){if($!==null)$.cancelAnimationFrame(Q);U=!1},setAnimationLoop:function(K){J=K},setContext:function(K){$=K}}}function gV($){let U=new WeakMap;function J(N,H){let{array:Y,usage:G}=N,O=Y.byteLength,E=$.createBuffer();$.bindBuffer(H,E),$.bufferData(H,Y,G),N.onUploadCallback();let Z;if(Y instanceof Float32Array)Z=$.FLOAT;else if(typeof Float16Array<"u"&&Y instanceof Float16Array)Z=$.HALF_FLOAT;else if(Y instanceof Uint16Array)if(N.isFloat16BufferAttribute)Z=$.HALF_FLOAT;else Z=$.UNSIGNED_SHORT;else if(Y instanceof Int16Array)Z=$.SHORT;else if(Y instanceof Uint32Array)Z=$.UNSIGNED_INT;else if(Y instanceof Int32Array)Z=$.INT;else if(Y instanceof Int8Array)Z=$.BYTE;else if(Y instanceof Uint8Array)Z=$.UNSIGNED_BYTE;else if(Y instanceof Uint8ClampedArray)Z=$.UNSIGNED_BYTE;else throw Error("THREE.WebGLAttributes: Unsupported buffer data format: "+Y);return{buffer:E,type:Z,bytesPerElement:Y.BYTES_PER_ELEMENT,version:N.version,size:O}}function Q(N,H,Y){let{array:G,updateRanges:O}=H;if($.bindBuffer(Y,N),O.length===0)$.bufferSubData(Y,0,G);else{O.sort((Z,D)=>Z.start-D.start);let E=0;for(let Z=1;Z<O.length;Z++){let D=O[E],R=O[Z];if(R.start<=D.start+D.count+1)D.count=Math.max(D.count,R.start+R.count-D.start);else++E,O[E]=R}O.length=E+1;for(let Z=0,D=O.length;Z<D;Z++){let R=O[Z];$.bufferSubData(Y,R.start*G.BYTES_PER_ELEMENT,G,R.start,R.count)}H.clearUpdateRanges()}H.onUploadCallback()}function W(N){if(N.isInterleavedBufferAttribute)N=N.data;return U.get(N)}function K(N){if(N.isInterleavedBufferAttribute)N=N.data;let H=U.get(N);if(H)$.deleteBuffer(H.buffer),U.delete(N)}function X(N,H){if(N.isInterleavedBufferAttribute)N=N.data;if(N.isGLBufferAttribute){let G=U.get(N);if(!G||G.version<N.version)U.set(N,{buffer:N.buffer,type:N.type,bytesPerElement:N.elementSize,version:N.version});return}let Y=U.get(N);if(Y===void 0)U.set(N,J(N,H));else if(Y.version<N.version){if(Y.size!==N.array.byteLength)throw Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");Q(Y.buffer,N,H),Y.version=N.version}}return{get:W,remove:K,update:X}}var bV=`#ifdef USE_ALPHAHASH+}`;class Mn extends rn{constructor(e){super();if(this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Uy,this.fragmentShader=Oy,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=gr(e.uniforms),this.uniformsGroups=Dy(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 i in this.uniforms){let s=this.uniforms[i].value;if(s&&s.isTexture)t.uniforms[i]={type:"t",value:s.toJSON(e).uuid};else if(s&&s.isColor)t.uniforms[i]={type:"c",value:s.getHex()};else if(s&&s.isVector2)t.uniforms[i]={type:"v2",value:s.toArray()};else if(s&&s.isVector3)t.uniforms[i]={type:"v3",value:s.toArray()};else if(s&&s.isVector4)t.uniforms[i]={type:"v4",value:s.toArray()};else if(s&&s.isMatrix3)t.uniforms[i]={type:"m3",value:s.toArray()};else if(s&&s.isMatrix4)t.uniforms[i]={type:"m4",value:s.toArray()};else t.uniforms[i]={value:s}}if(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 i in this.extensions)if(this.extensions[i]===!0)n[i]=!0;if(Object.keys(n).length>0)t.extensions=n;return t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let i=e.uniforms[n];switch(this.uniforms[n]={},i.type){case"t":this.uniforms[n].value=t[i.value]||null;break;case"c":this.uniforms[n].value=new Le().setHex(i.value);break;case"v2":this.uniforms[n].value=new Ie().fromArray(i.value);break;case"v3":this.uniforms[n].value=new N().fromArray(i.value);break;case"v4":this.uniforms[n].value=new st().fromArray(i.value);break;case"m3":this.uniforms[n].value=new Ue().fromArray(i.value);break;case"m4":this.uniforms[n].value=new ze().fromArray(i.value);break;default:this.uniforms[n].value=i.value}}if(e.defines!==void 0)this.defines=e.defines;if(e.vertexShader!==void 0)this.vertexShader=e.vertexShader;if(e.fragmentShader!==void 0)this.fragmentShader=e.fragmentShader;if(e.glslVersion!==void 0)this.glslVersion=e.glslVersion;if(e.extensions!==void 0)for(let n in e.extensions)this.extensions[n]=e.extensions[n];if(e.lights!==void 0)this.lights=e.lights;if(e.clipping!==void 0)this.clipping=e.clipping;return this}}class Ru extends Mn{constructor(e){super(e);this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class mi extends rn{constructor(e){super();this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Le(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 Le(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ie(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 qn,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}}class dn extends mi{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 Ie(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return $e(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+0.4*t)/(1-0.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Le(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 Le(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Le(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){if(this._anisotropy>0!==e>0)this.version++;this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){if(this._clearcoat>0!==e>0)this.version++;this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){if(this._iridescence>0!==e>0)this.version++;this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){if(this._dispersion>0!==e>0)this.version++;this._dispersion=e}get sheen(){return this._sheen}set sheen(e){if(this._sheen>0!==e>0)this.version++;this._sheen=e}get transmission(){return this._transmission}set transmission(e){if(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}}class za extends rn{constructor(e){super();this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Le(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Le(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ie(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new qn,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=0.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}}class Cu extends rn{constructor(e){super();this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,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}}class Iu extends rn{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}}function ha(e,t){if(!e||e.constructor===t)return e;if(typeof t.BYTES_PER_ELEMENT==="number")return new t(e);return Array.prototype.slice.call(e)}function Fy(e){function t(r,s){return e[r]-e[s]}let n=e.length,i=Array(n);for(let r=0;r!==n;++r)i[r]=r;return i.sort(t),i}function hg(e,t,n){let i=e.length,r=new e.constructor(i);for(let s=0,o=0;o!==i;++s){let a=n[s]*t;for(let c=0;c!==t;++c)r[o++]=e[a+c]}return r}function zy(e,t,n,i){let r=1,s=e[0];while(s!==void 0&&s[i]===void 0)s=e[r++];if(s===void 0)return;let o=s[i];if(o===void 0)return;if(Array.isArray(o))do{if(o=s[i],o!==void 0)t.push(s.time),n.push(...o);s=e[r++]}while(s!==void 0);else if(o.toArray!==void 0)do{if(o=s[i],o!==void 0)t.push(s.time),o.toArray(n,n.length);s=e[r++]}while(s!==void 0);else do{if(o=s[i],o!==void 0)t.push(s.time),n.push(o);s=e[r++]}while(s!==void 0)}class gi{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,i=t[n],r=t[n-1];e:{t:{let s;n:{i:if(!(e<i)){for(let o=n+2;;){if(i===void 0){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===o)break;if(r=i,i=t[++n],e<i)break t}s=t.length;break n}if(!(e>=r)){let o=t[1];if(e<o)n=2,r=o;for(let a=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(i=r,r=t[--n-1],e>=r)break t}s=n,n=0;break n}break e}while(n<s){let o=n+s>>>1;if(e<t[o])s=o;else n=o+1}if(i=t[n],r=t[n-1],r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,r,i)}return this.interpolate_(n,r,e,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=e*i;for(let s=0;s!==i;++s)t[s]=n[r+s];return t}interpolate_(){throw Error("THREE.Interpolant: Call to abstract method.")}intervalChanged_(){}}class Pu extends gi{constructor(e,t,n,i){super(e,t,n,i);this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:2400,endingEnd:2400}}intervalChanged_(e,t,n){let i=this.parameterPositions,r=e-2,s=e+1,o=i[r],a=i[s];if(o===void 0)switch(this.getSettings_().endingStart){case 2401:r=e,o=2*t-n;break;case 2402:r=i.length-2,o=t+i[r]-i[r+1];break;default:r=e,o=n}if(a===void 0)switch(this.getSettings_().endingEnd){case 2401:s=e,a=2*n-t;break;case 2402:s=1,a=n+i[1]-i[0];break;default:s=e-1,a=t}let c=(n-t)*0.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(a-n),this._offsetPrev=r*l,this._offsetNext=s*l}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=e*o,c=a-o,l=this._offsetPrev,u=this._offsetNext,f=this._weightPrev,h=this._weightNext,d=(n-t)/(i-t),g=d*d,y=g*d,p=-f*y+2*f*g-f*d,m=(1+f)*y+(-1.5-2*f)*g+(-0.5+f)*d+1,A=(-1-h)*y+(1.5+h)*g+0.5*d,T=h*y-h*g;for(let v=0;v!==o;++v)r[v]=p*s[l+v]+m*s[c+v]+A*s[a+v]+T*s[u+v];return r}}class ka extends gi{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=e*o,c=a-o,l=(n-t)/(i-t),u=1-l;for(let f=0;f!==o;++f)r[f]=s[c+f]*u+s[a+f]*l;return r}}class Lu extends gi{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e){return this.copySampleValue_(e-1)}}class Nu extends gi{interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=e*o,c=a-o,l=this.inTangents,u=this.outTangents;if(!l||!u){let d=(n-t)/(i-t),g=1-d;for(let y=0;y!==o;++y)r[y]=s[c+y]*g+s[a+y]*d;return r}let f=o*2,h=e-1;for(let d=0;d!==o;++d){let g=s[c+d],y=s[a+d],p=h*f+d*2,m=u[p],A=u[p+1],T=e*f+d*2,v=l[T],w=l[T+1],E=(n-t)/(i-t),R,_,S,F,C;for(let z=0;z<8;z++){R=E*E,_=R*E,S=1-E,F=S*S,C=F*S;let O=C*t+3*F*E*m+3*S*R*v+_*i-n;if(Math.abs(O)<0.0000000001)break;let H=3*F*(m-t)+6*S*E*(v-m)+3*R*(i-v);if(Math.abs(H)<0.0000000001)break;E=E-O/H,E=Math.max(0,Math.min(1,E))}r[d]=C*g+3*F*E*A+3*S*R*w+_*y}return r}}class pn{constructor(e,t,n,i){if(e===void 0)throw Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=ha(t,this.TimeBufferType),this.values=ha(n,this.ValueBufferType),this.setInterpolation(i||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:ha(e.times,Array),values:ha(e.values,Array)};let i=e.getInterpolation();if(i!==e.DefaultInterpolation)n.interpolation=i}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Lu(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new ka(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Pu(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new Nu(this.times,this.values,this.getValueSize(),e);if(this.settings)t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents;return t}setInterpolation(e){let t;switch(e){case 2300:t=this.InterpolantFactoryMethodDiscrete;break;case 2301:t=this.InterpolantFactoryMethodLinear;break;case 2302:t=this.InterpolantFactoryMethodSmooth;break;case 2303: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 Error(n);return Me("KeyframeTrack:",n),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;case this.InterpolantFactoryMethodLinear:return 2301;case this.InterpolantFactoryMethodSmooth:return 2302;case this.InterpolantFactoryMethodBezier:return 2303}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]*=e}return this}trim(e,t){let n=this.times,i=n.length,r=0,s=i-1;while(r!==i&&n[r]<e)++r;while(s!==-1&&n[s]>t)--s;if(++s,r!==0||s!==i){if(r>=s)s=Math.max(s,1),r=s-1;let o=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*o,s*o)}return this}validate(){let e=!0,t=this.getValueSize();if(t-Math.floor(t)!==0)Ne("KeyframeTrack: Invalid value size in track.",this),e=!1;let n=this.times,i=this.values,r=n.length;if(r===0)Ne("KeyframeTrack: Track is empty.",this),e=!1;let s=null;for(let o=0;o!==r;o++){let a=n[o];if(typeof a==="number"&&isNaN(a)){Ne("KeyframeTrack: Time is not a valid number.",this,o,a),e=!1;break}if(s!==null&&s>a){Ne("KeyframeTrack: Out of order keys.",this,o,a,s),e=!1;break}s=a}if(i!==void 0){if(jv(i))for(let o=0,a=i.length;o!==a;++o){let c=i[o];if(isNaN(c)){Ne("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(),i=this.getInterpolation()===2302,r=e.length-1,s=1;for(let o=1;o<r;++o){let a=!1,c=e[o],l=e[o+1];if(c!==l&&(o!==1||c!==e[0]))if(!i){let u=o*n,f=u-n,h=u+n;for(let d=0;d!==n;++d){let g=t[u+d];if(g!==t[f+d]||g!==t[h+d]){a=!0;break}}}else a=!0;if(a){if(o!==s){e[s]=e[o];let u=o*n,f=s*n;for(let h=0;h!==n;++h)t[f+h]=t[u+h]}++s}}if(r>0){e[s]=e[r];for(let o=r*n,a=s*n,c=0;c!==n;++c)t[a+c]=t[o+c];++s}if(s!==e.length)this.times=e.slice(0,s),this.values=t.slice(0,s*n);else this.times=e,this.values=t;return this}clone(){let e=this.times.slice(),t=this.values.slice(),i=new this.constructor(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}}pn.prototype.ValueTypeName="";pn.prototype.TimeBufferType=Float32Array;pn.prototype.ValueBufferType=Float32Array;pn.prototype.DefaultInterpolation=2301;class Hi extends pn{constructor(e,t,n){super(e,t,n)}}Hi.prototype.ValueTypeName="bool";Hi.prototype.ValueBufferType=Array;Hi.prototype.DefaultInterpolation=2300;Hi.prototype.InterpolantFactoryMethodLinear=void 0;Hi.prototype.InterpolantFactoryMethodSmooth=void 0;class Ba extends pn{constructor(e,t,n,i){super(e,t,n,i)}}Ba.prototype.ValueTypeName="color";class Vi extends pn{constructor(e,t,n,i){super(e,t,n,i)}}Vi.prototype.ValueTypeName="number";class Du extends gi{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=(n-t)/(i-t),c=e*o;for(let l=c+o;c!==l;c+=4)Bt.slerpFlat(r,0,s,c-o,s,c,a);return r}}class Wi extends pn{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new Du(this.times,this.values,this.getValueSize(),e)}}Wi.prototype.ValueTypeName="quaternion";Wi.prototype.InterpolantFactoryMethodSmooth=void 0;class $i extends pn{constructor(e,t,n){super(e,t,n)}}$i.prototype.ValueTypeName="string";$i.prototype.ValueBufferType=Array;$i.prototype.DefaultInterpolation=2300;$i.prototype.InterpolantFactoryMethodLinear=void 0;$i.prototype.InterpolantFactoryMethodSmooth=void 0;class _r extends pn{constructor(e,t,n,i){super(e,t,n,i)}}_r.prototype.ValueTypeName="vector";class $r{constructor(e="",t=-1,n=[],i=2500){if(this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=Dn(),this.userData={},this.duration<0)this.resetDuration()}static parse(e){let t=[],n=e.tracks,i=1/(e.fps||1);for(let s=0,o=n.length;s!==o;++s)t.push(By(n[s]).scale(i));let r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r.userData=JSON.parse(e.userData||"{}"),r}static toJSON(e){let t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let r=0,s=n.length;r!==s;++r)t.push(pn.toJSON(n[r]));return i}static CreateFromMorphTargetSequence(e,t,n,i){let r=t.length,s=[];for(let o=0;o<r;o++){let a=[],c=[];a.push((o+r-1)%r,o,(o+1)%r),c.push(0,1,0);let l=Fy(a);if(a=hg(a,1,l),c=hg(c,1,l),!i&&a[0]===0)a.push(r),c.push(c[0]);s.push(new Vi(".morphTargetInfluences["+t[o].name+"]",a,c).scale(1/n))}return new this(e,-1,s)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let i=e;n=i.geometry&&i.geometry.animations||i.animations}for(let i=0;i<n.length;i++)if(n[i].name===t)return n[i];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let i={},r=/^([\w-]*?)([\d]+)$/;for(let o=0,a=e.length;o<a;o++){let c=e[o],l=c.name.match(r);if(l&&l.length>1){let u=l[1],f=i[u];if(!f)i[u]=f=[];f.push(c)}}let s=[];for(let o in i)s.push(this.CreateFromMorphTargetSequence(o,i[o],t,n));return s}resetDuration(){let e=this.tracks,t=0;for(let n=0,i=e.length;n!==i;++n){let r=this.tracks[n];t=Math.max(t,r.times[r.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)}}function ky(e){switch(e.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return Vi;case"vector":case"vector2":case"vector3":case"vector4":return _r;case"color":return Ba;case"quaternion":return Wi;case"bool":case"boolean":return Hi;case"string":return $i}throw Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}function By(e){if(e.type===void 0)throw Error("THREE.KeyframeTrack: track type undefined, can not parse");let t=ky(e.type);if(e.times===void 0){let n=[],i=[];zy(e.keys,n,i,"value"),e.times=n,e.values=i}if(t.parse!==void 0)return t.parse(e);else return new t(e.name,e.times,e.values,e.interpolation)}var Xn={enabled:!1,files:{},add:function(e,t){if(this.enabled===!1)return;if(fg(e))return;this.files[e]=t},get:function(e){if(this.enabled===!1)return;if(fg(e))return;return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function fg(e){try{let t=e.slice(e.indexOf(":")+1);return new URL(t).protocol==="blob:"}catch(t){return!1}}class no{constructor(e,t,n){let i=this,r=!1,s=0,o=0,a=void 0,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(l){if(o++,r===!1){if(i.onStart!==void 0)i.onStart(l,s,o)}r=!0},this.itemEnd=function(l){if(s++,i.onProgress!==void 0)i.onProgress(l,s,o);if(s===o){if(r=!1,i.onLoad!==void 0)i.onLoad()}},this.itemError=function(l){if(i.onError!==void 0)i.onError(l)},this.resolveURL=function(l){if(l=l.normalize("NFC"),a)return a(l);return l},this.setURLModifier=function(l){return a=l,this},this.addHandler=function(l,u){return c.push(l,u),this},this.removeHandler=function(l){let u=c.indexOf(l);if(u!==-1)c.splice(u,2);return this},this.getHandler=function(l){for(let u=0,f=c.length;u<f;u+=2){let h=c[u],d=c[u+1];if(h.global)h.lastIndex=0;if(h.test(l))return d}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){if(!this._abortController)this._abortController=new AbortController;return this._abortController}}var __=new no;class _i{constructor(e){if(this.manager=e!==void 0?e:__,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(i,r){n.load(e,i,t,r)})}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}}_i.DEFAULT_MATERIAL_NAME="__DEFAULT";var hi={};class x_ extends Error{constructor(e,t){super(e);this.response=t}}class io extends _i{constructor(e){super(e);this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,t,n,i){if(e===void 0)e="";if(this.path!==void 0)e=this.path+e;e=this.manager.resolveURL(e);let r=Xn.get(`file:${e}`);if(r!==void 0){this.manager.itemStart(e),setTimeout(()=>{if(t)t(r);this.manager.itemEnd(e)},0);return}if(hi[e]!==void 0){hi[e].push({onLoad:t,onProgress:n,onError:i});return}hi[e]=[],hi[e].push({onLoad:t,onProgress:n,onError:i});let s=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,a=this.responseType;fetch(s).then((c)=>{if(c.status===200||c.status===0){if(c.status===0)Me("FileLoader: HTTP Status 0 received.");if(typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;let l=hi[e],u=c.body.getReader(),f=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),h=f?parseInt(f):0,d=h!==0,g=0,y=new ReadableStream({start(p){m();function m(){u.read().then(({done:A,value:T})=>{if(A)p.close();else{g+=T.byteLength;let v=new ProgressEvent("progress",{lengthComputable:d,loaded:g,total:h});for(let w=0,E=l.length;w<E;w++){let R=l[w];if(R.onProgress)R.onProgress(v)}p.enqueue(T),m()}},(A)=>{p.error(A)})}}});return new Response(y)}else throw new x_(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then((c)=>{switch(a){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then((l)=>new DOMParser().parseFromString(l,o));case"json":return c.json();default:if(o==="")return c.text();else{let u=/charset="?([^;"\s]*)"?/i.exec(o),f=u&&u[1]?u[1].toLowerCase():void 0,h=new TextDecoder(f);return c.arrayBuffer().then((d)=>h.decode(d))}}}).then((c)=>{Xn.add(`file:${e}`,c);let l=hi[e];delete hi[e];for(let u=0,f=l.length;u<f;u++){let h=l[u];if(h.onLoad)h.onLoad(c)}}).catch((c)=>{let l=hi[e];if(l===void 0)throw this.manager.itemError(e),c;delete hi[e];for(let u=0,f=l.length;u<f;u++){let h=l[u];if(h.onError)h.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}}var kr=new WeakMap;class Uu extends _i{constructor(e){super(e)}load(e,t,n,i){if(this.path!==void 0)e=this.path+e;e=this.manager.resolveURL(e);let r=this,s=Xn.get(`image:${e}`);if(s!==void 0){if(s.complete===!0)r.manager.itemStart(e),setTimeout(function(){if(t)t(s);r.manager.itemEnd(e)},0);else{let u=kr.get(s);if(u===void 0)u=[],kr.set(s,u);u.push({onLoad:t,onError:i})}return s}let o=Vr("img");function a(){if(l(),t)t(this);let u=kr.get(this)||[];for(let f=0;f<u.length;f++){let h=u[f];if(h.onLoad)h.onLoad(this)}kr.delete(this),r.manager.itemEnd(e)}function c(u){if(l(),i)i(u);Xn.remove(`image:${e}`);let f=kr.get(this)||[];for(let h=0;h<f.length;h++){let d=f[h];if(d.onError)d.onError(u)}kr.delete(this),r.manager.itemError(e),r.manager.itemEnd(e)}function l(){o.removeEventListener("load",a,!1),o.removeEventListener("error",c,!1)}if(o.addEventListener("load",a,!1),o.addEventListener("error",c,!1),e.slice(0,5)!=="data:"){if(this.crossOrigin!==void 0)o.crossOrigin=this.crossOrigin}return Xn.add(`image:${e}`,o),r.manager.itemStart(e),o.src=e,o}}class Ga extends _i{constructor(e){super(e)}load(e,t,n,i){let r=new wt,s=new Uu(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(o){if(r.image=o,r.needsUpdate=!0,t!==void 0)t(r)},n,i),r}}class rs extends at{constructor(e,t=1){super();this.isLight=!0,this.type="Light",this.color=new Le(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}}class Ha extends rs{constructor(e,t,n){super(e,n);this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(at.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Le(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}}var yl=new ze,dg=new N,pg=new N;class Va{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 Ie(512,512),this.mapType=1009,this.map=null,this.mapPass=null,this.matrix=new ze,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Ks,this._frameExtents=new Ie(1,1),this._viewportCount=1,this._viewports=[new st(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;if(dg.setFromMatrixPosition(e.matrixWorld),t.position.copy(dg),pg.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(pg),t.updateMatrixWorld(),yl.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(yl,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===2001||t.reversedDepth)n.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,1,0,0,0,0,1);else n.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1);n.multiply(yl)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){if(this.map)this.map.dispose();if(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={};if(this.intensity!==1)e.intensity=this.intensity;if(this.bias!==0)e.bias=this.bias;if(this.normalBias!==0)e.normalBias=this.normalBias;if(this.radius!==1)e.radius=this.radius;if(this.mapSize.x!==512||this.mapSize.y!==512)e.mapSize=this.mapSize.toArray();return e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}var fa=new N,da=new Bt,$n=new N;class Wa extends at{constructor(){super();this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ze,this.projectionMatrix=new ze,this.projectionMatrixInverse=new ze,this.coordinateSystem=2000,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){if(super.updateMatrixWorld(e),this.matrixWorld.decompose(fa,da,$n),$n.x===1&&$n.y===1&&$n.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(fa,da,$n.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){if(super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(fa,da,$n),$n.x===1&&$n.y===1&&$n.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(fa,da,$n.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}var Li=new N,mg=new Ie,gg=new Ie;class Lt extends Wa{constructor(e=50,t=1,n=0.1,i=2000){super();this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,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=0.5*this.getFilmHeight()/e;this.fov=cr*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Os*0.5*this.fov);return 0.5*this.getFilmHeight()/e}getEffectiveFOV(){return cr*2*Math.atan(Math.tan(Os*0.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){Li.set(-1,-1,0.5).applyMatrix4(this.projectionMatrixInverse),t.set(Li.x,Li.y).multiplyScalar(-e/Li.z),Li.set(1,1,0.5).applyMatrix4(this.projectionMatrixInverse),n.set(Li.x,Li.y).multiplyScalar(-e/Li.z)}getViewSize(e,t){return this.getViewBounds(e,mg,gg),t.subVectors(gg,mg)}setViewOffset(e,t,n,i,r,s){if(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=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null)this.view.enabled=!1;this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(Os*0.5*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-0.5*i,s=this.view;if(this.view!==null&&this.view.enabled){let{fullWidth:a,fullHeight:c}=s;r+=s.offsetX*i/a,t-=s.offsetY*n/c,i*=s.width/a,n*=s.height/c}let o=this.filmOffset;if(o!==0)r+=e*o/this.getFilmWidth();this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);if(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);return t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class v_ extends Va{constructor(){super(new Lt(50,1,0.5,500));this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=cr*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;if(n!==t.fov||i!==t.aspect||r!==t.far)t.fov=n,t.aspect=i,t.far=r,t.updateProjectionMatrix();super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class $a extends rs{constructor(e,t,n=0,i=Math.PI/3,r=0,s=2){super(e,t);this.isSpotLight=!0,this.type="SpotLight",this.position.copy(at.DEFAULT_UP),this.updateMatrix(),this.target=new at,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new v_}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);if(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;return t.object.shadow=this.shadow.toJSON(),t}}class y_ extends Va{constructor(){super(new Lt(90,1,0.5,500));this.isPointLightShadow=!0}}class ss extends rs{constructor(e,t,n=0,i=2){super(e,t);this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new y_}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}}class xr extends Wa{constructor(e=-1,t=1,n=1,i=-1,r=0.1,s=2000){super();this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=r,this.far=s,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,i,r,s){if(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=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){if(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,i=(this.top+this.bottom)/2,r=n-e,s=n+e,o=i+t,a=i-t;if(this.view!==null&&this.view.enabled){let c=(this.right-this.left)/this.view.fullWidth/this.zoom,l=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=c*this.view.offsetX,s=r+c*this.view.width,o-=l*this.view.offsetY,a=o-l*this.view.height}this.projectionMatrix.makeOrthographic(r,s,o,a,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);if(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);return t}}class b_ extends Va{constructor(){super(new xr(-5,5,5,-5,0.5,500));this.isDirectionalLightShadow=!0}}class os extends rs{constructor(e,t){super(e,t);this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(at.DEFAULT_UP),this.updateMatrix(),this.target=new at,this.shadow=new b_}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}}class Zi{static extractUrlBase(e){let t=e.lastIndexOf("/");if(t===-1)return"./";return e.slice(0,t+1)}static resolveURL(e,t){if(typeof e!=="string"||e==="")return"";if(/^https?:\/\//i.test(t)&&/^\//.test(e))t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1");if(/^(https?:)?\/\//i.test(e))return e;if(/^data:.*,.*$/i.test(e))return e;if(/^blob:.*$/i.test(e))return e;return t+e}}var bl=new WeakMap;class Za extends _i{constructor(e){super(e);if(this.isImageBitmapLoader=!0,typeof createImageBitmap>"u")Me("ImageBitmapLoader: createImageBitmap() not supported.");if(typeof fetch>"u")Me("ImageBitmapLoader: fetch() not supported.");this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,i){if(e===void 0)e="";if(this.path!==void 0)e=this.path+e;e=this.manager.resolveURL(e);let r=this,s=Xn.get(`image-bitmap:${e}`);if(s!==void 0){if(r.manager.itemStart(e),s.then){s.then((c)=>{if(bl.has(s)===!0){if(i)i(bl.get(s));r.manager.itemError(e),r.manager.itemEnd(e)}else{if(t)t(c);r.manager.itemEnd(e)}});return}setTimeout(function(){if(t)t(s);r.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 a=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(c){if(Xn.add(`image-bitmap:${e}`,c),t)t(c);r.manager.itemEnd(e)}).catch(function(c){if(i)i(c);bl.set(a,c),Xn.remove(`image-bitmap:${e}`),r.manager.itemError(e),r.manager.itemEnd(e)});Xn.add(`image-bitmap:${e}`,a),r.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}var Br=-90,Gr=1;class Ou extends at{constructor(e,t,n){super();this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new Lt(Br,Gr,e,t);i.layers=this.layers,this.add(i);let r=new Lt(Br,Gr,e,t);r.layers=this.layers,this.add(r);let s=new Lt(Br,Gr,e,t);s.layers=this.layers,this.add(s);let o=new Lt(Br,Gr,e,t);o.layers=this.layers,this.add(o);let a=new Lt(Br,Gr,e,t);a.layers=this.layers,this.add(a);let c=new Lt(Br,Gr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,o,a]=t;for(let c of t)this.remove(c);if(e===2000)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1);else throw Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let c of t)this.add(c),c.updateMatrixWorld()}update(e,t){if(this.parent===null)this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:i}=this;if(this.coordinateSystem!==e.coordinateSystem)this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem();let[r,s,o,a,c,l]=this.children,u=e.getRenderTarget(),f=e.getActiveCubeFace(),h=e.getActiveMipmapLevel(),d=e.xr.enabled;e.xr.enabled=!1;let g=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let y=!1;if(e.isWebGLRenderer===!0)y=e.state.buffers.depth.getReversed();else y=e.reversedDepthBuffer;if(e.setRenderTarget(n,0,i),y&&e.autoClear===!1)e.clearDepth();if(e.render(t,r),e.setRenderTarget(n,1,i),y&&e.autoClear===!1)e.clearDepth();if(e.render(t,s),e.setRenderTarget(n,2,i),y&&e.autoClear===!1)e.clearDepth();if(e.render(t,o),e.setRenderTarget(n,3,i),y&&e.autoClear===!1)e.clearDepth();if(e.render(t,a),e.setRenderTarget(n,4,i),y&&e.autoClear===!1)e.clearDepth();if(e.render(t,c),n.texture.generateMipmaps=g,e.setRenderTarget(n,5,i),y&&e.autoClear===!1)e.clearDepth();e.render(t,l),e.setRenderTarget(u,f,h),e.xr.enabled=d,n.texture.needsPMREMUpdate=!0}}class Fu extends Lt{constructor(e=[]){super();this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class zu{constructor(e,t,n){this.binding=e,this.valueSize=n;let i,r,s;switch(t){case"quaternion":i=this._slerp,r=this._slerpAdditive,s=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case"string":case"bool":i=this._select,r=this._select,s=this._setAdditiveIdentityOther,this.buffer=Array(n*5);break;default:i=this._lerp,r=this._lerpAdditive,s=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=r,this._setIdentity=s,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,i=this.valueSize,r=e*i+i,s=this.cumulativeWeight;if(s===0){for(let o=0;o!==i;++o)n[r+o]=n[o];s=t}else{s+=t;let o=t/s;this._mixBufferRegion(n,r,0,o,i)}this.cumulativeWeight=s}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,i=n*this._addIndex;if(this.cumulativeWeightAdditive===0)this._setIdentity();this._mixBufferRegionAdditive(t,i,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,i=e*t+t,r=this.cumulativeWeight,s=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){let a=t*this._origIndex;this._mixBufferRegion(n,i,a,1-r,t)}if(s>0)this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let a=t,c=t+t;a!==c;++a)if(n[a]!==n[a+t]){o.setValue(n,i);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,i=n*this._origIndex;e.getValue(t,i);for(let r=n,s=i;r!==s;++r)t[r]=t[i+r%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,i,r){if(i>=0.5)for(let s=0;s!==r;++s)e[t+s]=e[n+s]}_slerp(e,t,n,i){Bt.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,r){let s=this._workIndex*r;Bt.multiplyQuaternionsFlat(e,s,e,t,e,n),Bt.slerpFlat(e,t,e,t,e,s,i)}_lerp(e,t,n,i,r){let s=1-i;for(let o=0;o!==r;++o){let a=t+o;e[a]=e[a]*s+e[n+o]*i}}_lerpAdditive(e,t,n,i,r){for(let s=0;s!==r;++s){let o=t+s;e[o]=e[o]+e[n+s]*i}}}var ku="\\[\\]\\.:\\/",Gy=new RegExp("["+ku+"]","g"),Bu="[^"+ku+"]",Hy="[^"+ku.replace("\\.","")+"]",Vy=/((?:WC+[\/:])*)/.source.replace("WC",Bu),Wy=/(WCOD+)?/.source.replace("WCOD",Hy),$y=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Bu),Zy=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Bu),Xy=new RegExp("^"+Vy+Wy+$y+Zy+"$"),qy=["material","materials","bones","map"];class S_{constructor(e,t,n){let i=n||tt.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,i=this._bindings[n];if(i!==void 0)i.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++i)n[i].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()}}class tt{constructor(e,t,n){this.path=t,this.parsedPath=n||tt.parseTrackName(t),this.node=tt.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){if(!(e&&e.isAnimationObjectGroup))return new tt(e,t,n);else return new tt.Composite(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Gy,"")}static parseTrackName(e){let t=Xy.exec(e);if(t===null)throw Error("THREE.PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){let r=n.nodeName.substring(i+1);if(qy.indexOf(r)!==-1)n.nodeName=n.nodeName.substring(0,i),n.objectName=r}if(n.propertyName===null||n.propertyName.length===0)throw Error("THREE.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(r){for(let s=0;s<r.length;s++){let o=r[s];if(o.name===t||o.uuid===t)return o;let a=n(o.children);if(a)return a}return null},i=n(e.children);if(i)return i}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 i=0,r=n.length;i!==r;++i)e[t++]=n[i]}_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 i=0,r=n.length;i!==r;++i)n[i]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=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,{objectName:n,propertyName:i,propertyIndex:r}=t;if(!e)e=tt.findNode(this.rootNode,t.nodeName),this.node=e;if(this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){Me("PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let c=t.objectIndex;switch(n){case"materials":if(!e.material){Ne("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){Ne("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){Ne("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let l=0;l<e.length;l++)if(e[l].name===c){c=l;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){Ne("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){Ne("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){Ne("PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(c!==void 0){if(e[c]===void 0){Ne("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[c]}}let s=e[i];if(s===void 0){let c=t.nodeName;Ne("PropertyBinding: Trying to update property for track: "+c+"."+i+" but it wasn't found.",e);return}let o=this.Versioning.None;if(this.targetObject=e,e.isMaterial===!0)o=this.Versioning.NeedsUpdate;else if(e.isObject3D===!0)o=this.Versioning.MatrixWorldNeedsUpdate;let a=this.BindingType.Direct;if(r!==void 0){if(i==="morphTargetInfluences"){if(!e.geometry){Ne("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){Ne("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}if(e.morphTargetDictionary[r]!==void 0)r=e.morphTargetDictionary[r]}a=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=r}else if(s.fromArray!==void 0&&s.toArray!==void 0)a=this.BindingType.HasFromToArray,this.resolvedProperty=s;else if(Array.isArray(s))a=this.BindingType.EntireArray,this.resolvedProperty=s;else this.propertyName=i;this.getValue=this.GetterByBindingType[a],this.setValue=this.SetterByBindingTypeAndVersioning[a][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}tt.Composite=S_;tt.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};tt.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};tt.prototype.GetterByBindingType=[tt.prototype._getValue_direct,tt.prototype._getValue_array,tt.prototype._getValue_arrayElement,tt.prototype._getValue_toArray];tt.prototype.SetterByBindingTypeAndVersioning=[[tt.prototype._setValue_direct,tt.prototype._setValue_direct_setNeedsUpdate,tt.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[tt.prototype._setValue_array,tt.prototype._setValue_array_setNeedsUpdate,tt.prototype._setValue_array_setMatrixWorldNeedsUpdate],[tt.prototype._setValue_arrayElement,tt.prototype._setValue_arrayElement_setNeedsUpdate,tt.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[tt.prototype._setValue_fromArray,tt.prototype._setValue_fromArray_setNeedsUpdate,tt.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class Gu{constructor(e,t,n=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=i;let r=t.tracks,s=r.length,o=Array(s),a={endingStart:2400,endingEnd:2400};for(let c=0;c!==s;++c){let l=r[c].createInterpolant(null);o[c]=l,l.settings=a}this._interpolantSettings=a,this._interpolants=o,this._propertyBindings=Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._restoreTimeScale=null,this._weightInterpolant=null,this.loop=2201,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 i=this._clip.duration,r=e._clip.duration,s=r/i,o=i/r;e._restoreTimeScale=e.timeScale,this._restoreTimeScale=this.timeScale,e.warp(1,s,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;if(e!==null)this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e);return 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 i=this._mixer,r=i.time,s=this.timeScale,o=this._timeScaleInterpolant;if(o===null)o=i._lendControlInterpolant(),this._timeScaleInterpolant=o;let a=o.parameterPositions,c=o.sampleValues;return a[0]=r,a[1]=r+n,c[0]=e/s,c[1]=t/s,this}stopWarping(){let e=this._timeScaleInterpolant;if(e!==null)this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e);return this._restoreTimeScale=null,this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,i){if(!this.enabled){this._updateWeight(e);return}let r=this._startTime;if(r!==null){let a=(e-r)*n;if(a<0||n===0)t=0;else this._startTime=null,t=n*a}t*=this._updateTimeScale(e);let s=this._updateTime(t),o=this._updateWeight(e);if(o>0){let a=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case 2501:for(let l=0,u=a.length;l!==u;++l)a[l].evaluate(s),c[l].accumulateAdditive(o);break;case 2500:default:for(let l=0,u=a.length;l!==u;++l)a[l].evaluate(s),c[l].accumulate(i,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let i=n.evaluate(e)[0];if(t*=i,e>n.parameterPositions[1]){if(this.stopFading(),i===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 i=n.evaluate(e)[0];if(t*=i,e>n.parameterPositions[1]){if(t===0)this.paused=!0;else{if(this._restoreTimeScale!==null)t=this._restoreTimeScale;this.timeScale=t}this.stopWarping()}}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,i=this.time+e,r=this._loopCount,s=n===2202;if(e===0){if(r===-1)return i;return s&&(r&1)===1?t-i:i}if(n===2200){if(r===-1)this._loopCount=0,this._setEndings(!0,!0,!1);e:{if(i>=t)i=t;else if(i<0)i=0;else{this.time=i;break e}if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(r===-1)if(e>=0)r=0,this._setEndings(!0,this.repetitions===0,s);else this._setEndings(this.repetitions===0,!0,s);if(i>=t||i<0){let o=Math.floor(i/t);i-=t*o,r+=Math.abs(o);let a=this.repetitions-r;if(a<=0){if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1})}else{if(a===1){let c=e<0;this._setEndings(c,!c,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this._loopCount=r,this.time=i;if(s&&(r&1)===1)return t-i}return i}_setEndings(e,t,n){let i=this._interpolantSettings;if(n)i.endingStart=2401,i.endingEnd=2401;else{if(e)i.endingStart=this.zeroSlopeAtStart?2401:2400;else i.endingStart=2402;if(t)i.endingEnd=this.zeroSlopeAtEnd?2401:2400;else i.endingEnd=2402}}_scheduleFading(e,t,n){let i=this._mixer,r=i.time,s=this._weightInterpolant;if(s===null)s=i._lendControlInterpolant(),this._weightInterpolant=s;let o=s.parameterPositions,a=s.sampleValues;return o[0]=r,a[0]=t,o[1]=r+e,a[1]=n,this}}var Yy=new Float32Array(1);class Xa extends zn{constructor(e){super();if(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,i=e._clip.tracks,r=i.length,{_propertyBindings:s,_interpolants:o}=e,a=n.uuid,c=this._bindingsByRootAndName,l=c[a];if(l===void 0)l={},c[a]=l;for(let u=0;u!==r;++u){let f=i[u],h=f.name,d=l[h];if(d!==void 0)++d.referenceCount,s[u]=d;else{if(d=s[u],d!==void 0){if(d._cacheIndex===null)++d.referenceCount,this._addInactiveBinding(d,a,h);continue}let g=t&&t._propertyBindings[u].binding.parsedPath;d=new zu(tt.create(n,h,g),f.ValueTypeName,f.getValueSize()),++d.referenceCount,this._addInactiveBinding(d,a,h),s[u]=d}o[u].resultBuffer=d.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let n=(e._localRoot||this._root).uuid,i=e._clip.uuid,r=this._actionsByClip[i];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,i,n)}let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let r=t[n];if(r.useCount++===0)this._lendBinding(r),r.saveOriginalState()}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let r=t[n];if(--r.useCount===0)r.restoreOriginalState(),this._takeBackBinding(r)}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 i=this._actions,r=this._actionsByClip,s=r[t];if(s===void 0)s={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,r[t]=s;else{let o=s.knownActions;e._byClipCacheIndex=o.length,o.push(e)}e._cacheIndex=i.length,i.push(e),s.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],i=e._cacheIndex;n._cacheIndex=i,t[i]=n,t.pop(),e._cacheIndex=null;let r=e._clip.uuid,s=this._actionsByClip,o=s[r],a=o.knownActions,c=a[a.length-1],l=e._byClipCacheIndex;c._byClipCacheIndex=l,a[l]=c,a.pop(),e._byClipCacheIndex=null;let u=o.actionByRoot,f=(e._localRoot||this._root).uuid;if(delete u[f],a.length===0)delete s[r];this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let r=t[n];if(--r.referenceCount===0)this._removeInactiveBinding(r)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,i=this._nActiveActions++,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,i=--this._nActiveActions,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_addInactiveBinding(e,t,n){let i=this._bindingsByRootAndName,r=this._bindings,s=i[t];if(s===void 0)s={},i[t]=s;s[n]=e,e._cacheIndex=r.length,r.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,i=n.rootNode.uuid,r=n.path,s=this._bindingsByRootAndName,o=s[i],a=t[t.length-1],c=e._cacheIndex;if(a._cacheIndex=c,t[c]=a,t.pop(),delete o[r],Object.keys(o).length===0)delete s[i]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,i=this._nActiveBindings++,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,i=--this._nActiveBindings,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];if(n===void 0)n=new ka(new Float32Array(2),new Float32Array(2),1,Yy),n.__cacheIndex=t,e[t]=n;return n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,i=--this._nActiveControlInterpolants,r=t[i];e.__cacheIndex=i,t[i]=e,r.__cacheIndex=n,t[n]=r}clipAction(e,t,n){let i=t||this._root,r=i.uuid,s=typeof e==="string"?$r.findByName(i,e):e,o=s!==null?s.uuid:e,a=this._actionsByClip[o],c=null;if(n===void 0)if(s!==null)n=s.blendMode;else n=2500;if(a!==void 0){let u=a.actionByRoot[r];if(u!==void 0&&u.blendMode===n)return u;if(c=a.knownActions[0],s===null)s=c._clip}if(s===null)return null;let l=new Gu(this,s,t,n);return this._bindAction(l,c),this._addInactiveAction(l,o,r),l}existingAction(e,t){let n=t||this._root,i=n.uuid,r=typeof e==="string"?$r.findByName(n,e):e,s=r?r.uuid:e,o=this._actionsByClip[s];if(o!==void 0)return o.actionByRoot[i]||null;return 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,i=this.time+=e,r=Math.sign(e),s=this._accuIndex^=1;for(let c=0;c!==n;++c)t[c]._update(i,e,r,s);let o=this._bindings,a=this._nActiveBindings;for(let c=0;c!==a;++c)o[c].apply(s);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,i=this._actionsByClip,r=i[n];if(r!==void 0){let s=r.knownActions;for(let o=0,a=s.length;o!==a;++o){let c=s[o];this._deactivateAction(c);let l=c._cacheIndex,u=t[t.length-1];c._cacheIndex=null,c._byClipCacheIndex=null,u._cacheIndex=l,t[l]=u,t.pop(),this._removeInactiveBindingsForAction(c)}delete i[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let s in n){let o=n[s].actionByRoot,a=o[t];if(a!==void 0)this._deactivateAction(a),this._removeInactiveAction(a)}let i=this._bindingsByRootAndName,r=i[t];if(r!==void 0)for(let s in r){let o=r[s];o.restoreOriginalState(),this._removeInactiveBinding(o)}}uncacheAction(e,t){let n=this.existingAction(e,t);if(n!==null)this._deactivateAction(n),this._removeInactiveAction(n)}}class ro{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=$e(this.phi,0.000001,Math.PI-0.000001),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){if(this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0)this.theta=0,this.phi=0;else this.theta=Math.atan2(e,n),this.phi=Math.acos($e(t/this.radius,-1,1));return this}clone(){return new this.constructor().copy(this)}}class Hu{static{Hu.prototype.isMatrix2=!0}constructor(e,t,n,i){if(this.elements=[1,0,0,1],e!==void 0)this.set(e,t,n,i)}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,i){let r=this.elements;return r[0]=e,r[2]=t,r[1]=n,r[3]=i,this}}class qa extends zn{constructor(e,t=null){super();this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){Me("Controls: connect() now requires an element.");return}if(this.domElement!==null)this.disconnect();this.domElement=e}disconnect(){}dispose(){}update(){}}function Vu(e,t,n,i){let r=jy(i);switch(n){case 1021:return e*t;case 1028:return e*t/r.components*r.byteLength;case 1029:return e*t/r.components*r.byteLength;case 1030:return e*t*2/r.components*r.byteLength;case 1031:return e*t*2/r.components*r.byteLength;case 1022:return e*t*3/r.components*r.byteLength;case 1023:return e*t*4/r.components*r.byteLength;case 1033:return e*t*4/r.components*r.byteLength;case 33776:case 33777:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case 33778:case 33779:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case 35841:case 35843:return Math.max(e,16)*Math.max(t,8)/4;case 35840:case 35842:return Math.max(e,8)*Math.max(t,8)/2;case 36196:case 37492:case 37488:case 37489:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case 37496:case 37490:case 37491:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case 37808:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case 37809:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case 37810:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case 37811:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case 37812:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case 37813:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case 37814:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case 37815:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case 37816:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case 37817:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case 37818:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case 37819:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case 37820:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case 37821:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case 36492:case 36494:case 36495:return Math.ceil(e/4)*Math.ceil(t/4)*16;case 36283:case 36284:return Math.ceil(e/4)*Math.ceil(t/4)*8;case 36285:case 36286:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function jy(e){switch(e){case 1009:case 1010:return{byteLength:1,components:1};case 1012:case 1011:case 1016:return{byteLength:2,components:1};case 1017:case 1018:return{byteLength:2,components:4};case 1014:case 1013:case 1015:return{byteLength:4,components:1};case 35902:case 35899:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}if(typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"185"}}));if(typeof window<"u")if(window.__THREE__)Me("WARNING: Multiple instances of Three.js being imported.");else window.__THREE__="185";function $_(){let e=null,t=!1,n=null,i=null;function r(s,o){n(s,o),i=e.requestAnimationFrame(r)}return{start:function(){if(t===!0)return;if(n===null)return;if(e===null)return;i=e.requestAnimationFrame(r),t=!0},stop:function(){if(e!==null)e.cancelAnimationFrame(i);t=!1},setAnimationLoop:function(s){n=s},setContext:function(s){e=s}}}function Jy(e){let t=new WeakMap;function n(a,c){let{array:l,usage:u}=a,f=l.byteLength,h=e.createBuffer();e.bindBuffer(c,h),e.bufferData(c,l,u),a.onUploadCallback();let d;if(l instanceof Float32Array)d=e.FLOAT;else if(typeof Float16Array<"u"&&l instanceof Float16Array)d=e.HALF_FLOAT;else if(l instanceof Uint16Array)if(a.isFloat16BufferAttribute)d=e.HALF_FLOAT;else d=e.UNSIGNED_SHORT;else if(l instanceof Int16Array)d=e.SHORT;else if(l instanceof Uint32Array)d=e.UNSIGNED_INT;else if(l instanceof Int32Array)d=e.INT;else if(l instanceof Int8Array)d=e.BYTE;else if(l instanceof Uint8Array)d=e.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)d=e.UNSIGNED_BYTE;else throw Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:h,type:d,bytesPerElement:l.BYTES_PER_ELEMENT,version:a.version,size:f}}function i(a,c,l){let{array:u,updateRanges:f}=c;if(e.bindBuffer(l,a),f.length===0)e.bufferSubData(l,0,u);else{f.sort((d,g)=>d.start-g.start);let h=0;for(let d=1;d<f.length;d++){let g=f[h],y=f[d];if(y.start<=g.start+g.count+1)g.count=Math.max(g.count,y.start+y.count-g.start);else++h,f[h]=y}f.length=h+1;for(let d=0,g=f.length;d<g;d++){let y=f[d];e.bufferSubData(l,y.start*u.BYTES_PER_ELEMENT,u,y.start,y.count)}c.clearUpdateRanges()}c.onUploadCallback()}function r(a){if(a.isInterleavedBufferAttribute)a=a.data;return t.get(a)}function s(a){if(a.isInterleavedBufferAttribute)a=a.data;let c=t.get(a);if(c)e.deleteBuffer(c.buffer),t.delete(a)}function o(a,c){if(a.isInterleavedBufferAttribute)a=a.data;if(a.isGLBufferAttribute){let u=t.get(a);if(!u||u.version<a.version)t.set(a,{buffer:a.buffer,type:a.type,bytesPerElement:a.elementSize,version:a.version});return}let l=t.get(a);if(l===void 0)t.set(a,n(a,c));else if(l.version<a.version){if(l.size!==a.array.byteLength)throw Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");i(l.buffer,a,c),l.version=a.version}}return{get:r,remove:s,update:o}}var Ky=`#ifdef USE_ALPHAHASHif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;-#endif`,xV=`#ifdef USE_ALPHAHASH+#endif`,Qy=`#ifdef USE_ALPHAHASHconst 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 ) ) ) );@@ -108,20 +107,20 @@ version 0.8.2: cases.z;return clamp( threshold , 1.0e-6, 1.0 );}-#endif`,yV=`#ifdef USE_ALPHAMAP+#endif`,eb=`#ifdef USE_ALPHAMAPdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;-#endif`,hV=`#ifdef USE_ALPHAMAP+#endif`,tb=`#ifdef USE_ALPHAMAPuniform sampler2D alphaMap;-#endif`,fV=`#ifdef USE_ALPHATEST+#endif`,nb=`#ifdef USE_ALPHATEST#ifdef ALPHA_TO_COVERAGEdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );if ( diffuseColor.a == 0.0 ) discard;#elseif ( diffuseColor.a < alphaTest ) discard;#endif-#endif`,uV=`#ifdef USE_ALPHATEST+#endif`,ib=`#ifdef USE_ALPHATESTuniform float alphaTest;-#endif`,lV=`#ifdef USE_AOMAP+#endif`,rb=`#ifdef USE_AOMAPfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;reflectedLight.indirectDiffuse *= ambientOcclusion;#if defined( USE_CLEARCOAT )@@ -134,10 +133,10 @@ version 0.8.2float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );#endif-#endif`,mV=`#ifdef USE_AOMAP+#endif`,sb=`#ifdef USE_AOMAPuniform sampler2D aoMap;uniform float aoMapIntensity;-#endif`,pV=`#ifdef USE_BATCHING+#endif`,ob=`#ifdef USE_BATCHING#if ! defined( GL_ANGLE_multi_draw )#define gl_DrawID _gl_DrawIDuniform int _gl_DrawID;@@ -171,15 +170,15 @@ version 0.8.2int y = j / size;return texelFetch( batchingColorTexture, ivec2( x, y ), 0 );}-#endif`,dV=`#ifdef USE_BATCHING+#endif`,ab=`#ifdef USE_BATCHINGmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );-#endif`,cV=`vec3 transformed = vec3( position );+#endif`,cb=`vec3 transformed = vec3( position );#ifdef USE_ALPHAHASHvPosition = vec3( position );-#endif`,nV=`vec3 objectNormal = vec3( normal );+#endif`,lb=`vec3 objectNormal = vec3( normal );#ifdef USE_TANGENTvec3 objectTangent = vec3( tangent.xyz );-#endif`,iV=`float G_BlinnPhong_Implicit( ) {+#endif`,ub=`float G_BlinnPhong_Implicit( ) {return 0.25;}float D_BlinnPhong( const in float shininess, const in float dotNH ) {@@ -193,7 +192,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vefloat G = G_BlinnPhong_Implicit( );float D = D_BlinnPhong( shininess, dotNH );return F * ( G * D );-} // validated`,oV=`#ifdef USE_IRIDESCENCE+} // validated`,hb=`#ifdef USE_IRIDESCENCEconst mat3 XYZ_TO_REC709 = mat3(3.2404542, -0.9692660, 0.0556434,-1.5371385, 1.8760108, -0.2040259,@@ -256,7 +255,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve}return max( I, vec3( 0.0 ) );}-#endif`,rV=`#ifdef USE_BUMPMAP+#endif`,fb=`#ifdef USE_BUMPMAPuniform sampler2D bumpMap;uniform float bumpScale;vec2 dHdxy_fwd() {@@ -277,7 +276,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vevec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );return normalize( abs( fDet ) * surf_norm - vGrad );}-#endif`,aV=`#if NUM_CLIPPING_PLANES > 0+#endif`,db=`#if NUM_CLIPPING_PLANES > 0vec4 plane;#ifdef ALPHA_TO_COVERAGEfloat distanceToPlane, distanceGradient;@@ -323,20 +322,20 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in veif ( clipped ) discard;#endif#endif-#endif`,sV=`#if NUM_CLIPPING_PLANES > 0+#endif`,pb=`#if NUM_CLIPPING_PLANES > 0varying vec3 vClipPosition;uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];-#endif`,tV=`#if NUM_CLIPPING_PLANES > 0+#endif`,mb=`#if NUM_CLIPPING_PLANES > 0varying vec3 vClipPosition;-#endif`,eV=`#if NUM_CLIPPING_PLANES > 0+#endif`,gb=`#if NUM_CLIPPING_PLANES > 0vClipPosition = - mvPosition.xyz;-#endif`,$w=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )+#endif`,_b=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )diffuseColor *= vColor;-#endif`,Uw=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )+#endif`,xb=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )varying vec4 vColor;-#endif`,Jw=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+#endif`,vb=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )varying vec4 vColor;-#endif`,Ww=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+#endif`,yb=`#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@@ -349,7 +348,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve#endif#ifdef USE_BATCHING_COLORvColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );-#endif`,Qw=`#define PI 3.141592653589793+#endif`,bb=`#define PI 3.141592653589793#define PI2 6.283185307179586#define PI_HALF 1.5707963267948966#define RECIPROCAL_PI 0.3183098861837907@@ -420,7 +419,7 @@ vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {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`,Kw=`#ifdef ENVMAP_TYPE_CUBE_UV+} // validated`,Sb=`#ifdef ENVMAP_TYPE_CUBE_UV#define cubeUV_minMipLevel 4.0#define cubeUV_minTileSize 16.0float getFace( vec3 direction ) {@@ -513,7 +512,7 @@ float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {return vec4( mix( color0, color1, mipF ), 1.0 );}}-#endif`,Xw=`vec3 transformedNormal = objectNormal;+#endif`,Mb=`vec3 transformedNormal = objectNormal;#ifdef USE_TANGENTvec3 transformedTangent = objectTangent;#endif@@ -539,21 +538,21 @@ transformedNormal = normalMatrix * transformedNormal;#endif#ifdef USE_TANGENTtransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;-#endif`,Nw=`#ifdef USE_DISPLACEMENTMAP+#endif`,wb=`#ifdef USE_DISPLACEMENTMAPuniform sampler2D displacementMap;uniform float displacementScale;uniform float displacementBias;-#endif`,Hw=`#ifdef USE_DISPLACEMENTMAP+#endif`,Tb=`#ifdef USE_DISPLACEMENTMAPtransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );-#endif`,Yw=`#ifdef USE_EMISSIVEMAP+#endif`,Eb=`#ifdef USE_EMISSIVEMAPvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );#ifdef DECODE_VIDEO_TEXTURE_EMISSIVEemissiveColor = sRGBTransferEOTF( emissiveColor );#endiftotalEmissiveRadiance *= emissiveColor.rgb;-#endif`,Gw=`#ifdef USE_EMISSIVEMAP+#endif`,Ab=`#ifdef USE_EMISSIVEMAPuniform sampler2D emissiveMap;-#endif`,Ow="gl_FragColor = linearToOutputTexel( gl_FragColor );",Ew=`vec4 LinearTransferOETF( in vec4 value ) {+#endif`,Rb="gl_FragColor = linearToOutputTexel( gl_FragColor );",Cb=`vec4 LinearTransferOETF( in vec4 value ) {return value;}vec4 sRGBTransferEOTF( in vec4 value ) {@@ -561,7 +560,7 @@ vec4 sRGBTransferEOTF( in vec4 value ) {}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 );-}`,Zw=`#ifdef USE_ENVMAP+}`,Ib=`#ifdef USE_ENVMAP#ifdef ENV_WORLDPOSvec3 cameraToFrag;if ( isOrthographic ) {@@ -588,7 +587,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {outgoingLight += envColor.xyz * specularStrength * reflectivity;#endif#endif-#endif`,Iw=`#ifdef USE_ENVMAP+#endif`,Pb=`#ifdef USE_ENVMAPuniform float envMapIntensity;uniform mat3 envMapRotation;#ifdef ENVMAP_TYPE_CUBE@@ -596,7 +595,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {#elseuniform sampler2D envMap;#endif-#endif`,qw=`#ifdef USE_ENVMAP+#endif`,Lb=`#ifdef USE_ENVMAPuniform float reflectivity;#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )#define ENV_WORLDPOS@@ -607,7 +606,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {#elsevarying vec3 vReflect;#endif-#endif`,Dw=`#ifdef USE_ENVMAP+#endif`,Nb=`#ifdef USE_ENVMAP#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )#define ENV_WORLDPOS#endif@@ -618,7 +617,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {varying vec3 vReflect;uniform float refractionRatio;#endif-#endif`,kw=`#ifdef USE_ENVMAP+#endif`,Db=`#ifdef USE_ENVMAP#ifdef ENV_WORLDPOSvWorldPosition = worldPosition.xyz;#else@@ -635,18 +634,18 @@ vec4 sRGBTransferOETF( in vec4 value ) {vReflect = refract( cameraToVertex, worldNormal, refractionRatio );#endif#endif-#endif`,Fw=`#ifdef USE_FOG+#endif`,Ub=`#ifdef USE_FOGvFogDepth = - mvPosition.z;-#endif`,Lw=`#ifdef USE_FOG+#endif`,Ob=`#ifdef USE_FOGvarying float vFogDepth;-#endif`,Rw=`#ifdef USE_FOG+#endif`,Fb=`#ifdef USE_FOG#ifdef FOG_EXP2float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );#elsefloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );#endifgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );-#endif`,Vw=`#ifdef USE_FOG+#endif`,zb=`#ifdef USE_FOGuniform vec3 fogColor;varying float vFogDepth;#ifdef FOG_EXP2@@ -655,7 +654,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {uniform float fogNear;uniform float fogFar;#endif-#endif`,ww=`#ifdef USE_GRADIENTMAP+#endif`,kb=`#ifdef USE_GRADIENTMAPuniform sampler2D gradientMap;#endifvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {@@ -667,12 +666,12 @@ vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {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-}`,Mw=`#ifdef USE_LIGHTMAP+}`,Bb=`#ifdef USE_LIGHTMAPuniform sampler2D lightMap;uniform float lightMapIntensity;-#endif`,Bw=`LambertMaterial material;+#endif`,Gb=`LambertMaterial material;material.diffuseColor = diffuseColor.rgb;-material.specularStrength = specularStrength;`,Pw=`varying vec3 vViewPosition;+material.specularStrength = specularStrength;`,Hb=`varying vec3 vViewPosition;struct LambertMaterial {vec3 diffuseColor;float specularStrength;@@ -686,7 +685,7 @@ void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometrreflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );}#define RE_Direct RE_Direct_Lambert-#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,zw=`uniform bool receiveShadow;+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Vb=`uniform bool receiveShadow;uniform vec3 ambientLightColor;#if defined( USE_LIGHT_PROBES )uniform vec3 lightProbe[ 9 ];@@ -803,7 +802,7 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosireturn irradiance;}#endif-#include <lightprobes_pars_fragment>`,_w=`#ifdef USE_ENVMAP+#include <lightprobes_pars_fragment>`,Wb=`#ifdef USE_ENVMAPvec3 getIBLIrradiance( const in vec3 normal ) {#ifdef ENVMAP_TYPE_CUBE_UVvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );@@ -836,8 +835,8 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi#endif}#endif-#endif`,Aw=`ToonMaterial material;-material.diffuseColor = diffuseColor.rgb;`,Cw=`varying vec3 vViewPosition;+#endif`,$b=`ToonMaterial material;+material.diffuseColor = diffuseColor.rgb;`,Zb=`varying vec3 vViewPosition;struct ToonMaterial {vec3 diffuseColor;};@@ -849,11 +848,11 @@ void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPoreflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );}#define RE_Direct RE_Direct_Toon-#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Sw=`BlinnPhongMaterial material;+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Xb=`BlinnPhongMaterial material;material.diffuseColor = diffuseColor.rgb;material.specularColor = specular;material.specularShininess = shininess;-material.specularStrength = specularStrength;`,Tw=`varying vec3 vViewPosition;+material.specularStrength = specularStrength;`,qb=`varying vec3 vViewPosition;struct BlinnPhongMaterial {vec3 diffuseColor;vec3 specularColor;@@ -870,7 +869,7 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geomreflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );}#define RE_Direct RE_Direct_BlinnPhong-#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,vw=`PhysicalMaterial material;+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,Yb=`PhysicalMaterial material;material.diffuseColor = diffuseColor.rgb;material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );material.metalness = metalnessFactor;@@ -960,7 +959,7 @@ material.roughness = min( material.roughness, 1.0 );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`,jw=`uniform sampler2D dfgLUT;+#endif`,jb=`uniform sampler2D dfgLUT;struct PhysicalMaterial {vec3 diffuseColor;vec3 diffuseContribution;@@ -1320,7 +1319,7 @@ void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradia#define RE_IndirectSpecular RE_IndirectSpecular_Physicalfloat 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 );-}`,gw=`+}`,Jb=`vec3 geometryPosition = - vViewPosition;vec3 geometryNormal = normal;vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );@@ -1442,7 +1441,7 @@ IncidentLight directLight;#if defined( RE_IndirectSpecular )vec3 radiance = vec3( 0.0 );vec3 clearcoatRadiance = vec3( 0.0 );-#endif`,bw=`#if defined( RE_IndirectDiffuse )+#endif`,Kb=`#if defined( RE_IndirectDiffuse )#ifdef USE_LIGHTMAPvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;@@ -1463,7 +1462,7 @@ IncidentLight directLight;#ifdef USE_CLEARCOATclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );#endif-#endif`,xw=`#if defined( RE_IndirectDiffuse )+#endif`,Qb=`#if defined( RE_IndirectDiffuse )#if defined( LAMBERT ) || defined( PHONG )irradiance += iblIrradiance;#endif@@ -1471,7 +1470,7 @@ IncidentLight directLight;#endif#if defined( RE_IndirectSpecular )RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );-#endif`,yw=`#ifdef USE_LIGHT_PROBES_GRID+#endif`,eS=`#ifdef USE_LIGHT_PROBES_GRIDuniform highp sampler3D probesSH;uniform vec3 probesMin;uniform vec3 probesMax;@@ -1516,27 +1515,27 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {result += c8 * 0.429043 * ( x * x - y * y );return max( result, vec3( 0.0 ) );}-#endif`,hw=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+#endif`,tS=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;-#endif`,fw=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+#endif`,nS=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )uniform float logDepthBufFC;varying float vFragDepth;varying float vIsPerspective;-#endif`,uw=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+#endif`,iS=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFERvarying float vFragDepth;varying float vIsPerspective;-#endif`,lw=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+#endif`,rS=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFERvFragDepth = 1.0 + gl_Position.w;vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );-#endif`,mw=`#ifdef USE_MAP+#endif`,sS=`#ifdef USE_MAPvec4 sampledDiffuseColor = texture2D( map, vMapUv );#ifdef DECODE_VIDEO_TEXTUREsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );#endifdiffuseColor *= sampledDiffuseColor;-#endif`,pw=`#ifdef USE_MAP+#endif`,oS=`#ifdef USE_MAPuniform sampler2D map;-#endif`,dw=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )+#endif`,aS=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )#if defined( USE_POINTS_UV )vec2 uv = vUv;#else@@ -1548,7 +1547,7 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {#endif#ifdef USE_ALPHAMAPdiffuseColor.a *= texture2D( alphaMap, uv ).g;-#endif`,cw=`#if defined( USE_POINTS_UV )+#endif`,cS=`#if defined( USE_POINTS_UV )varying vec2 vUv;#else#if defined( USE_MAP ) || defined( USE_ALPHAMAP )@@ -1560,19 +1559,19 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {#endif#ifdef USE_ALPHAMAPuniform sampler2D alphaMap;-#endif`,nw=`float metalnessFactor = metalness;+#endif`,lS=`float metalnessFactor = metalness;#ifdef USE_METALNESSMAPvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );metalnessFactor *= texelMetalness.b;-#endif`,iw=`#ifdef USE_METALNESSMAP+#endif`,uS=`#ifdef USE_METALNESSMAPuniform sampler2D metalnessMap;-#endif`,ow=`#ifdef USE_INSTANCING_MORPH+#endif`,hS=`#ifdef USE_INSTANCING_MORPHfloat 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`,rw=`#if defined( USE_MORPHCOLORS )+#endif`,fS=`#if defined( USE_MORPHCOLORS )vColor *= morphTargetBaseInfluence;for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {#if defined( USE_COLOR_ALPHA )@@ -1581,12 +1580,12 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];#endif}-#endif`,aw=`#ifdef USE_MORPHNORMALS+#endif`,dS=`#ifdef USE_MORPHNORMALSobjectNormal *= morphTargetBaseInfluence;for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];}-#endif`,sw=`#ifdef USE_MORPHTARGETS+#endif`,pS=`#ifdef USE_MORPHTARGETS#ifndef USE_INSTANCING_MORPHuniform float morphTargetBaseInfluence;uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];@@ -1600,12 +1599,12 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {ivec3 morphUV = ivec3( x, y, morphTargetIndex );return texelFetch( morphTargetsTexture, morphUV, 0 );}-#endif`,tw=`#ifdef USE_MORPHTARGETS+#endif`,mS=`#ifdef USE_MORPHTARGETStransformed *= morphTargetBaseInfluence;for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];}-#endif`,ew=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;+#endif`,gS=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;#ifdef FLAT_SHADEDvec3 fdx = dFdx( vViewPosition );vec3 fdy = dFdy( vViewPosition );@@ -1646,7 +1645,7 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {tbn2[1] *= faceDirection;#endif#endif-vec3 nonPerturbedNormal = normal;`,$M=`#ifdef USE_NORMALMAP_OBJECTSPACE+vec3 nonPerturbedNormal = normal;`,_S=`#ifdef USE_NORMALMAP_OBJECTSPACEnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;#ifdef FLIP_SIDEDnormal = - normal;@@ -1664,19 +1663,19 @@ vec3 nonPerturbedNormal = normal;`,$M=`#ifdef USE_NORMALMAP_OBJECTSPACEnormal = normalize( tbn * mapN );#elif defined( USE_BUMPMAP )normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );-#endif`,UM=`#ifndef FLAT_SHADED+#endif`,xS=`#ifndef FLAT_SHADEDvarying vec3 vNormal;#ifdef USE_TANGENTvarying vec3 vTangent;varying vec3 vBitangent;#endif-#endif`,JM=`#ifndef FLAT_SHADED+#endif`,vS=`#ifndef FLAT_SHADEDvarying vec3 vNormal;#ifdef USE_TANGENTvarying vec3 vTangent;varying vec3 vBitangent;#endif-#endif`,WM=`#ifndef FLAT_SHADED+#endif`,yS=`#ifndef FLAT_SHADEDvNormal = normalize( transformedNormal );#ifdef USE_TANGENTvTangent = normalize( transformedTangent );@@ -1685,7 +1684,7 @@ vec3 nonPerturbedNormal = normal;`,$M=`#ifdef USE_NORMALMAP_OBJECTSPACEvBitangent = - vBitangent;#endif#endif-#endif`,QM=`#ifdef USE_NORMALMAP+#endif`,bS=`#ifdef USE_NORMALMAPuniform sampler2D normalMap;uniform vec2 normalScale;#endif@@ -1707,13 +1706,13 @@ vec3 nonPerturbedNormal = normal;`,$M=`#ifdef USE_NORMALMAP_OBJECTSPACEfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );return mat3( T * scale, B * scale, N );}-#endif`,KM=`#ifdef USE_CLEARCOAT+#endif`,SS=`#ifdef USE_CLEARCOATvec3 clearcoatNormal = nonPerturbedNormal;-#endif`,XM=`#ifdef USE_CLEARCOAT_NORMALMAP+#endif`,MS=`#ifdef USE_CLEARCOAT_NORMALMAPvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;clearcoatMapN.xy *= clearcoatNormalScale;clearcoatNormal = normalize( tbn2 * clearcoatMapN );-#endif`,NM=`#ifdef USE_CLEARCOATMAP+#endif`,wS=`#ifdef USE_CLEARCOATMAPuniform sampler2D clearcoatMap;#endif#ifdef USE_CLEARCOAT_NORMALMAP@@ -1722,18 +1721,18 @@ vec3 nonPerturbedNormal = normal;`,$M=`#ifdef USE_NORMALMAP_OBJECTSPACE#endif#ifdef USE_CLEARCOAT_ROUGHNESSMAPuniform sampler2D clearcoatRoughnessMap;-#endif`,HM=`#ifdef USE_IRIDESCENCEMAP+#endif`,TS=`#ifdef USE_IRIDESCENCEMAPuniform sampler2D iridescenceMap;#endif#ifdef USE_IRIDESCENCE_THICKNESSMAPuniform sampler2D iridescenceThicknessMap;-#endif`,YM=`#ifdef OPAQUE+#endif`,ES=`#ifdef OPAQUEdiffuseColor.a = 1.0;#endif#ifdef USE_TRANSMISSIONdiffuseColor.a *= material.transmissionAlpha;#endif-gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,GM=`vec3 packNormalToRGB( const in vec3 normal ) {+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,AS=`vec3 packNormalToRGB( const in vec3 normal ) {return normalize( normal ) * 0.5 + 0.5;}vec3 unpackRGBToNormal( const in vec3 rgb ) {@@ -1812,9 +1811,9 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const#elsereturn ( near * far ) / ( ( far - near ) * depth - far );#endif-}`,OM=`#ifdef PREMULTIPLIED_ALPHA+}`,RS=`#ifdef PREMULTIPLIED_ALPHAgl_FragColor.rgb *= gl_FragColor.a;-#endif`,EM=`vec4 mvPosition = vec4( transformed, 1.0 );+#endif`,CS=`vec4 mvPosition = vec4( transformed, 1.0 );#ifdef USE_BATCHINGmvPosition = batchingMatrix * mvPosition;#endif@@ -1822,22 +1821,22 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, constmvPosition = instanceMatrix * mvPosition;#endifmvPosition = modelViewMatrix * mvPosition;-gl_Position = projectionMatrix * mvPosition;`,ZM=`#ifdef DITHERING+gl_Position = projectionMatrix * mvPosition;`,IS=`#ifdef DITHERINGgl_FragColor.rgb = dithering( gl_FragColor.rgb );-#endif`,IM=`#ifdef DITHERING+#endif`,PS=`#ifdef DITHERINGvec3 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`,qM=`float roughnessFactor = roughness;+#endif`,LS=`float roughnessFactor = roughness;#ifdef USE_ROUGHNESSMAPvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );roughnessFactor *= texelRoughness.g;-#endif`,DM=`#ifdef USE_ROUGHNESSMAP+#endif`,NS=`#ifdef USE_ROUGHNESSMAPuniform sampler2D roughnessMap;-#endif`,kM=`#if NUM_SPOT_LIGHT_COORDS > 0+#endif`,DS=`#if NUM_SPOT_LIGHT_COORDS > 0varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];#endif#if NUM_SPOT_LIGHT_MAPS > 0@@ -2037,7 +2036,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZM=`#ifdef DITHERING}#endif#endif-#endif`,FM=`#if NUM_SPOT_LIGHT_COORDS > 0+#endif`,US=`#if NUM_SPOT_LIGHT_COORDS > 0uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];#endif@@ -2078,7 +2077,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZM=`#ifdef DITHERING};uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];#endif-#endif`,LM=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )+#endif`,OS=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )#ifdef HAS_NORMALvec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );#else@@ -2114,7 +2113,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZM=`#ifdef DITHERINGvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;}#pragma unroll_loop_end-#endif`,RM=`float getShadowMask() {+#endif`,FS=`float getShadowMask() {float shadow = 1.0;#ifdef USE_SHADOWMAP#if NUM_DIR_LIGHT_SHADOWS > 0@@ -2146,12 +2145,12 @@ gl_Position = projectionMatrix * mvPosition;`,ZM=`#ifdef DITHERING#endif#endifreturn shadow;-}`,VM=`#ifdef USE_SKINNING+}`,zS=`#ifdef USE_SKINNINGmat4 boneMatX = getBoneMatrix( skinIndex.x );mat4 boneMatY = getBoneMatrix( skinIndex.y );mat4 boneMatZ = getBoneMatrix( skinIndex.z );mat4 boneMatW = getBoneMatrix( skinIndex.w );-#endif`,wM=`#ifdef USE_SKINNING+#endif`,kS=`#ifdef USE_SKINNINGuniform mat4 bindMatrix;uniform mat4 bindMatrixInverse;uniform highp sampler2D boneTexture;@@ -2166,7 +2165,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZM=`#ifdef DITHERINGvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );return mat4( v1, v2, v3, v4 );}-#endif`,MM=`#ifdef USE_SKINNING+#endif`,BS=`#ifdef USE_SKINNINGvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );vec4 skinned = vec4( 0.0 );skinned += boneMatX * skinVertex * skinWeight.x;@@ -2174,7 +2173,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZM=`#ifdef DITHERINGskinned += boneMatZ * skinVertex * skinWeight.z;skinned += boneMatW * skinVertex * skinWeight.w;transformed = ( bindMatrixInverse * skinned ).xyz;-#endif`,BM=`#ifdef USE_SKINNING+#endif`,GS=`#ifdef USE_SKINNINGmat4 skinMatrix = mat4( 0.0 );skinMatrix += skinWeight.x * boneMatX;skinMatrix += skinWeight.y * boneMatY;@@ -2185,17 +2184,17 @@ gl_Position = projectionMatrix * mvPosition;`,ZM=`#ifdef DITHERING#ifdef USE_TANGENTobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;#endif-#endif`,PM=`float specularStrength;+#endif`,HS=`float specularStrength;#ifdef USE_SPECULARMAPvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );specularStrength = texelSpecular.r;#elsespecularStrength = 1.0;-#endif`,zM=`#ifdef USE_SPECULARMAP+#endif`,VS=`#ifdef USE_SPECULARMAPuniform sampler2D specularMap;-#endif`,_M=`#if defined( TONE_MAPPING )+#endif`,WS=`#if defined( TONE_MAPPING )gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );-#endif`,AM=`#ifndef saturate+#endif`,$S=`#ifndef saturate#define saturate( a ) clamp( a, 0.0, 1.0 )#endifuniform float toneMappingExposure;@@ -2292,7 +2291,7 @@ vec3 NeutralToneMapping( vec3 color ) {float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );return mix( color, vec3( newPeak ), g );}-vec3 CustomToneMapping( vec3 color ) { return color; }`,CM=`#ifdef USE_TRANSMISSION+vec3 CustomToneMapping( vec3 color ) { return color; }`,ZS=`#ifdef USE_TRANSMISSIONmaterial.transmission = transmission;material.transmissionAlpha = 1.0;material.thickness = thickness;@@ -2313,7 +2312,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,CM=`#ifdef USE_TRANSMISSmaterial.attenuationColor, material.attenuationDistance );material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );-#endif`,SM=`#ifdef USE_TRANSMISSION+#endif`,XS=`#ifdef USE_TRANSMISSIONuniform float transmission;uniform float thickness;uniform float attenuationDistance;@@ -2439,7 +2438,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,CM=`#ifdef USE_TRANSMISSfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );}-#endif`,TM=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+#endif`,qS=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )varying vec2 vUv;#endif#ifdef USE_MAP@@ -2509,7 +2508,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,CM=`#ifdef USE_TRANSMISS#ifdef USE_THICKNESSMAPuniform mat3 thicknessMapTransform;varying vec2 vThicknessMapUv;-#endif`,vM=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+#endif`,YS=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )varying vec2 vUv;#endif#ifdef USE_MAP@@ -2603,7 +2602,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,CM=`#ifdef USE_TRANSMISS#ifdef USE_THICKNESSMAPuniform mat3 thicknessMapTransform;varying vec2 vThicknessMapUv;-#endif`,jM=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+#endif`,jS=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )vUv = vec3( uv, 1 ).xy;#endif#ifdef USE_MAP@@ -2674,7 +2673,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,CM=`#ifdef USE_TRANSMISS#endif#ifdef USE_THICKNESSMAPvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;-#endif`,gM=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0+#endif`,JS=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0vec4 worldPosition = vec4( transformed, 1.0 );#ifdef USE_BATCHINGworldPosition = batchingMatrix * worldPosition;@@ -2683,12 +2682,12 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,CM=`#ifdef USE_TRANSMISSworldPosition = instanceMatrix * worldPosition;#endifworldPosition = modelMatrix * worldPosition;-#endif`,bM=`varying vec2 vUv;+#endif`,KS=`varying vec2 vUv;uniform mat3 uvTransform;void main() {vUv = ( uvTransform * vec3( uv, 1 ) ).xy;gl_Position = vec4( position.xy, 1.0, 1.0 );-}`,xM=`uniform sampler2D t2D;+}`,QS=`uniform sampler2D t2D;uniform float backgroundIntensity;varying vec2 vUv;void main() {@@ -2700,14 +2699,14 @@ void main() {gl_FragColor = texColor;#include <tonemapping_fragment>#include <colorspace_fragment>-}`,yM=`varying vec3 vWorldDirection;+}`,eM=`varying vec3 vWorldDirection;#include <common>void main() {vWorldDirection = transformDirection( position, modelMatrix );#include <begin_vertex>#include <project_vertex>gl_Position.z = gl_Position.w;-}`,hM=`#ifdef ENVMAP_TYPE_CUBE+}`,tM=`#ifdef ENVMAP_TYPE_CUBEuniform samplerCube envMap;#elif defined( ENVMAP_TYPE_CUBE_UV )uniform sampler2D envMap;@@ -2729,14 +2728,14 @@ void main() {gl_FragColor = texColor;#include <tonemapping_fragment>#include <colorspace_fragment>-}`,fM=`varying vec3 vWorldDirection;+}`,nM=`varying vec3 vWorldDirection;#include <common>void main() {vWorldDirection = transformDirection( position, modelMatrix );#include <begin_vertex>#include <project_vertex>gl_Position.z = gl_Position.w;-}`,uM=`uniform samplerCube tCube;+}`,iM=`uniform samplerCube tCube;uniform float tFlip;uniform float opacity;varying vec3 vWorldDirection;@@ -2746,7 +2745,7 @@ void main() {gl_FragColor.a *= opacity;#include <tonemapping_fragment>#include <colorspace_fragment>-}`,lM=`#include <common>+}`,rM=`#include <common>#include <batching_pars_vertex>#include <uv_pars_vertex>#include <displacementmap_pars_vertex>@@ -2773,7 +2772,7 @@ void main() {#include <logdepthbuf_vertex>#include <clipping_planes_vertex>vHighPrecisionZW = gl_Position.zw;-}`,mM=`#if DEPTH_PACKING == 3200+}`,sM=`#if DEPTH_PACKING == 3200uniform float opacity;#endif#include <common>@@ -2811,7 +2810,7 @@ void main() {#elif DEPTH_PACKING == 3203gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );#endif-}`,pM=`#define DISTANCE+}`,oM=`#define DISTANCEvarying vec3 vWorldPosition;#include <common>#include <batching_pars_vertex>@@ -2838,7 +2837,7 @@ void main() {#include <worldpos_vertex>#include <clipping_planes_vertex>vWorldPosition = worldPosition.xyz;-}`,dM=`#define DISTANCE+}`;var aM=`#define DISTANCEuniform vec3 referencePosition;uniform float nearDistance;uniform float farDistance;@@ -2867,7 +2866,7 @@ void main() {vWorldDirection = transformDirection( position, modelMatrix );#include <begin_vertex>#include <project_vertex>-}`,nM=`uniform sampler2D tEquirect;+}`,lM=`uniform sampler2D tEquirect;varying vec3 vWorldDirection;#include <common>void main() {@@ -2876,7 +2875,7 @@ void main() {gl_FragColor = texture2D( tEquirect, sampleUV );#include <tonemapping_fragment>#include <colorspace_fragment>-}`,iM=`uniform float scale;+}`,uM=`uniform float scale;attribute float lineDistance;varying float vLineDistance;#include <common>@@ -2898,7 +2897,7 @@ void main() {#include <logdepthbuf_vertex>#include <clipping_planes_vertex>#include <fog_vertex>-}`,oM=`uniform vec3 diffuse;+}`,hM=`uniform vec3 diffuse;uniform float opacity;uniform float dashSize;uniform float totalSize;@@ -2926,7 +2925,7 @@ void main() {#include <colorspace_fragment>#include <fog_fragment>#include <premultiplied_alpha_fragment>-}`,rM=`#include <common>+}`,fM=`#include <common>#include <batching_pars_vertex>#include <uv_pars_vertex>#include <envmap_pars_vertex>@@ -2958,7 +2957,7 @@ void main() {#include <worldpos_vertex>#include <envmap_vertex>#include <fog_vertex>-}`,aM=`uniform vec3 diffuse;+}`,dM=`uniform vec3 diffuse;uniform float opacity;#ifndef FLAT_SHADEDvarying vec3 vNormal;@@ -3006,7 +3005,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,sM=`#define LAMBERT+}`,pM=`#define LAMBERTvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3045,7 +3044,7 @@ void main() {#include <envmap_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,tM=`#define LAMBERT+}`,mM=`#define LAMBERTuniform vec3 diffuse;uniform vec3 emissive;uniform float opacity;@@ -3103,7 +3102,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,eM=`#define MATCAP+}`,gM=`#define MATCAPvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3137,7 +3136,7 @@ void main() {#include <clipping_planes_vertex>#include <fog_vertex>vViewPosition = - mvPosition.xyz;-}`,$B=`#define MATCAP+}`,_M=`#define MATCAPuniform vec3 diffuse;uniform float opacity;uniform sampler2D matcap;@@ -3183,7 +3182,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,UB=`#define NORMAL+}`,xM=`#define NORMAL#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )varying vec3 vViewPosition;#endif@@ -3216,7 +3215,7 @@ void main() {#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )vViewPosition = - mvPosition.xyz;#endif-}`,JB=`#define NORMAL+}`,vM=`#define NORMALuniform float opacity;#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )varying vec3 vViewPosition;@@ -3237,7 +3236,7 @@ void main() {#ifdef OPAQUEgl_FragColor.a = 1.0;#endif-}`,WB=`#define PHONG+}`,yM=`#define PHONGvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3276,7 +3275,7 @@ void main() {#include <envmap_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,QB=`#define PHONG+}`,bM=`#define PHONGuniform vec3 diffuse;uniform vec3 emissive;uniform vec3 specular;@@ -3336,7 +3335,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,KB=`#define STANDARD+}`,SM=`#define STANDARDvarying vec3 vViewPosition;#ifdef USE_TRANSMISSIONvarying vec3 vWorldPosition;@@ -3379,7 +3378,7 @@ void main() {#ifdef USE_TRANSMISSIONvWorldPosition = worldPosition.xyz;#endif-}`,XB=`#define STANDARD+}`,MM=`#define STANDARD#ifdef PHYSICAL#define IOR#define USE_SPECULAR@@ -3504,7 +3503,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,NB=`#define TOON+}`,wM=`#define TOONvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3541,7 +3540,7 @@ void main() {#include <worldpos_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,HB=`#define TOON+}`,TM=`#define TOONuniform vec3 diffuse;uniform vec3 emissive;uniform float opacity;@@ -3593,7 +3592,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,YB=`uniform float size;+}`,EM=`uniform float size;uniform float scale;#include <common>#include <color_pars_vertex>@@ -3624,7 +3623,7 @@ void main() {#include <clipping_planes_vertex>#include <worldpos_vertex>#include <fog_vertex>-}`,GB=`uniform vec3 diffuse;+}`,AM=`uniform vec3 diffuse;uniform float opacity;#include <common>#include <color_pars_fragment>@@ -3649,7 +3648,7 @@ void main() {#include <colorspace_fragment>#include <fog_fragment>#include <premultiplied_alpha_fragment>-}`,OB=`#include <common>+}`,RM=`#include <common>#include <batching_pars_vertex>#include <fog_pars_vertex>#include <morphtarget_pars_vertex>@@ -3672,7 +3671,7 @@ void main() {#include <worldpos_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,EB=`uniform vec3 color;+}`,CM=`uniform vec3 color;uniform float opacity;#include <common>#include <fog_pars_fragment>@@ -3688,7 +3687,7 @@ void main() {#include <colorspace_fragment>#include <fog_fragment>#include <premultiplied_alpha_fragment>-}`,ZB=`uniform float rotation;+}`,IM=`uniform float rotation;uniform vec2 center;#include <common>#include <uv_pars_vertex>@@ -3712,7 +3711,7 @@ void main() {#include <logdepthbuf_vertex>#include <clipping_planes_vertex>#include <fog_vertex>-}`,IB=`uniform vec3 diffuse;+}`,PM=`uniform vec3 diffuse;uniform float opacity;#include <common>#include <uv_pars_fragment>@@ -3737,7 +3736,7 @@ void main() {#include <tonemapping_fragment>#include <colorspace_fragment>#include <fog_fragment>-}`,o$={alphahash_fragment:bV,alphahash_pars_fragment:xV,alphamap_fragment:yV,alphamap_pars_fragment:hV,alphatest_fragment:fV,alphatest_pars_fragment:uV,aomap_fragment:lV,aomap_pars_fragment:mV,batching_pars_vertex:pV,batching_vertex:dV,begin_vertex:cV,beginnormal_vertex:nV,bsdfs:iV,iridescence_fragment:oV,bumpmap_pars_fragment:rV,clipping_planes_fragment:aV,clipping_planes_pars_fragment:sV,clipping_planes_pars_vertex:tV,clipping_planes_vertex:eV,color_fragment:$w,color_pars_fragment:Uw,color_pars_vertex:Jw,color_vertex:Ww,common:Qw,cube_uv_reflection_fragment:Kw,defaultnormal_vertex:Xw,displacementmap_pars_vertex:Nw,displacementmap_vertex:Hw,emissivemap_fragment:Yw,emissivemap_pars_fragment:Gw,colorspace_fragment:Ow,colorspace_pars_fragment:Ew,envmap_fragment:Zw,envmap_common_pars_fragment:Iw,envmap_pars_fragment:qw,envmap_pars_vertex:Dw,envmap_physical_pars_fragment:_w,envmap_vertex:kw,fog_vertex:Fw,fog_pars_vertex:Lw,fog_fragment:Rw,fog_pars_fragment:Vw,gradientmap_pars_fragment:ww,lightmap_pars_fragment:Mw,lights_lambert_fragment:Bw,lights_lambert_pars_fragment:Pw,lights_pars_begin:zw,lights_toon_fragment:Aw,lights_toon_pars_fragment:Cw,lights_phong_fragment:Sw,lights_phong_pars_fragment:Tw,lights_physical_fragment:vw,lights_physical_pars_fragment:jw,lights_fragment_begin:gw,lights_fragment_maps:bw,lights_fragment_end:xw,lightprobes_pars_fragment:yw,logdepthbuf_fragment:hw,logdepthbuf_pars_fragment:fw,logdepthbuf_pars_vertex:uw,logdepthbuf_vertex:lw,map_fragment:mw,map_pars_fragment:pw,map_particle_fragment:dw,map_particle_pars_fragment:cw,metalnessmap_fragment:nw,metalnessmap_pars_fragment:iw,morphinstance_vertex:ow,morphcolor_vertex:rw,morphnormal_vertex:aw,morphtarget_pars_vertex:sw,morphtarget_vertex:tw,normal_fragment_begin:ew,normal_fragment_maps:$M,normal_pars_fragment:UM,normal_pars_vertex:JM,normal_vertex:WM,normalmap_pars_fragment:QM,clearcoat_normal_fragment_begin:KM,clearcoat_normal_fragment_maps:XM,clearcoat_pars_fragment:NM,iridescence_pars_fragment:HM,opaque_fragment:YM,packing:GM,premultiplied_alpha_fragment:OM,project_vertex:EM,dithering_fragment:ZM,dithering_pars_fragment:IM,roughnessmap_fragment:qM,roughnessmap_pars_fragment:DM,shadowmap_pars_fragment:kM,shadowmap_pars_vertex:FM,shadowmap_vertex:LM,shadowmask_pars_fragment:RM,skinbase_vertex:VM,skinning_pars_vertex:wM,skinning_vertex:MM,skinnormal_vertex:BM,specularmap_fragment:PM,specularmap_pars_fragment:zM,tonemapping_fragment:_M,tonemapping_pars_fragment:AM,transmission_fragment:CM,transmission_pars_fragment:SM,uv_pars_fragment:TM,uv_pars_vertex:vM,uv_vertex:jM,worldpos_vertex:gM,background_vert:bM,background_frag:xM,backgroundCube_vert:yM,backgroundCube_frag:hM,cube_vert:fM,cube_frag:uM,depth_vert:lM,depth_frag:mM,distance_vert:pM,distance_frag:dM,equirect_vert:cM,equirect_frag:nM,linedashed_vert:iM,linedashed_frag:oM,meshbasic_vert:rM,meshbasic_frag:aM,meshlambert_vert:sM,meshlambert_frag:tM,meshmatcap_vert:eM,meshmatcap_frag:$B,meshnormal_vert:UB,meshnormal_frag:JB,meshphong_vert:WB,meshphong_frag:QB,meshphysical_vert:KB,meshphysical_frag:XB,meshtoon_vert:NB,meshtoon_frag:HB,points_vert:YB,points_frag:GB,shadow_vert:OB,shadow_frag:EB,sprite_vert:ZB,sprite_frag:IB},D$={common:{diffuse:{value:new x$(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new u$},alphaMap:{value:null},alphaMapTransform:{value:new u$},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new u$}},envmap:{envMap:{value:null},envMapRotation:{value:new u$},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:0.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new u$}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new u$}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new u$},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new u$},normalScale:{value:new g$(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new u$},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new u$}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new u$}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new u$}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:0.00025},fogNear:{value:1},fogFar:{value:2000},fogColor:{value:new x$(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 j},probesMax:{value:new j},probesResolution:{value:new j}},points:{diffuse:{value:new x$(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new u$},alphaTest:{value:0},uvTransform:{value:new u$}},sprite:{diffuse:{value:new x$(16777215)},opacity:{value:1},center:{value:new g$(0.5,0.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new u$},alphaMap:{value:null},alphaMapTransform:{value:new u$},alphaTest:{value:0}}},kJ={basic:{uniforms:WU([D$.common,D$.specularmap,D$.envmap,D$.aomap,D$.lightmap,D$.fog]),vertexShader:o$.meshbasic_vert,fragmentShader:o$.meshbasic_frag},lambert:{uniforms:WU([D$.common,D$.specularmap,D$.envmap,D$.aomap,D$.lightmap,D$.emissivemap,D$.bumpmap,D$.normalmap,D$.displacementmap,D$.fog,D$.lights,{emissive:{value:new x$(0)},envMapIntensity:{value:1}}]),vertexShader:o$.meshlambert_vert,fragmentShader:o$.meshlambert_frag},phong:{uniforms:WU([D$.common,D$.specularmap,D$.envmap,D$.aomap,D$.lightmap,D$.emissivemap,D$.bumpmap,D$.normalmap,D$.displacementmap,D$.fog,D$.lights,{emissive:{value:new x$(0)},specular:{value:new x$(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:o$.meshphong_vert,fragmentShader:o$.meshphong_frag},standard:{uniforms:WU([D$.common,D$.envmap,D$.aomap,D$.lightmap,D$.emissivemap,D$.bumpmap,D$.normalmap,D$.displacementmap,D$.roughnessmap,D$.metalnessmap,D$.fog,D$.lights,{emissive:{value:new x$(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:o$.meshphysical_vert,fragmentShader:o$.meshphysical_frag},toon:{uniforms:WU([D$.common,D$.aomap,D$.lightmap,D$.emissivemap,D$.bumpmap,D$.normalmap,D$.displacementmap,D$.gradientmap,D$.fog,D$.lights,{emissive:{value:new x$(0)}}]),vertexShader:o$.meshtoon_vert,fragmentShader:o$.meshtoon_frag},matcap:{uniforms:WU([D$.common,D$.bumpmap,D$.normalmap,D$.displacementmap,D$.fog,{matcap:{value:null}}]),vertexShader:o$.meshmatcap_vert,fragmentShader:o$.meshmatcap_frag},points:{uniforms:WU([D$.points,D$.fog]),vertexShader:o$.points_vert,fragmentShader:o$.points_frag},dashed:{uniforms:WU([D$.common,D$.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:o$.linedashed_vert,fragmentShader:o$.linedashed_frag},depth:{uniforms:WU([D$.common,D$.displacementmap]),vertexShader:o$.depth_vert,fragmentShader:o$.depth_frag},normal:{uniforms:WU([D$.common,D$.bumpmap,D$.normalmap,D$.displacementmap,{opacity:{value:1}}]),vertexShader:o$.meshnormal_vert,fragmentShader:o$.meshnormal_frag},sprite:{uniforms:WU([D$.sprite,D$.fog]),vertexShader:o$.sprite_vert,fragmentShader:o$.sprite_frag},background:{uniforms:{uvTransform:{value:new u$},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:o$.background_vert,fragmentShader:o$.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new u$}},vertexShader:o$.backgroundCube_vert,fragmentShader:o$.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:o$.cube_vert,fragmentShader:o$.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:o$.equirect_vert,fragmentShader:o$.equirect_frag},distance:{uniforms:WU([D$.common,D$.displacementmap,{referencePosition:{value:new j},nearDistance:{value:1},farDistance:{value:1000}}]),vertexShader:o$.distance_vert,fragmentShader:o$.distance_frag},shadow:{uniforms:WU([D$.lights,D$.fog,{color:{value:new x$(0)},opacity:{value:1}}]),vertexShader:o$.shadow_vert,fragmentShader:o$.shadow_frag}};kJ.physical={uniforms:WU([kJ.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new u$},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new u$},clearcoatNormalScale:{value:new g$(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new u$},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new u$},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new u$},sheen:{value:0},sheenColor:{value:new x$(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new u$},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new u$},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new u$},transmissionSamplerSize:{value:new g$},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new u$},attenuationDistance:{value:0},attenuationColor:{value:new x$(0)},specularColor:{value:new x$(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new u$},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new u$},anisotropyVector:{value:new g$},anisotropyMap:{value:null},anisotropyMapTransform:{value:new u$}}]),vertexShader:o$.meshphysical_vert,fragmentShader:o$.meshphysical_frag};var j7={r:0,b:0,g:0},qB=new p$,G5=new u$;G5.set(-1,0,0,0,1,0,0,0,1);function DB($,U,J,Q,W,K){let X=new x$(0),N=W===!0?0:1,H,Y,G=null,O=0,E=null;function Z(_){let P=_.isScene===!0?_.background:null;if(P&&P.isTexture){let L=_.backgroundBlurriness>0;P=U.get(P,L)}return P}function D(_){let P=!1,L=Z(_);if(L===null)I(X,N);else if(L&&L.isColor)I(L,1),P=!0;let B=$.xr.getEnvironmentBlendMode();if(B==="additive")J.buffers.color.setClear(0,0,0,1,K);else if(B==="alpha-blend")J.buffers.color.setClear(0,0,0,0,K);if($.autoClear||P)J.buffers.depth.setTest(!0),J.buffers.depth.setMask(!0),J.buffers.color.setMask(!0),$.clear($.autoClearColor,$.autoClearDepth,$.autoClearStencil)}function R(_,P){let L=Z(P);if(L&&(L.isCubeTexture||L.mapping===DQ)){if(Y===void 0)Y=new P6(new O0(1,1,1),new yU({name:"BackgroundCubeMaterial",uniforms:d0(kJ.backgroundCube.uniforms),vertexShader:kJ.backgroundCube.vertexShader,fragmentShader:kJ.backgroundCube.fragmentShader,side:JU,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),Y.geometry.deleteAttribute("normal"),Y.geometry.deleteAttribute("uv"),Y.onBeforeRender=function(B,z,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(Y.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),Q.update(Y);if(Y.material.uniforms.envMap.value=L,Y.material.uniforms.backgroundBlurriness.value=P.backgroundBlurriness,Y.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,Y.material.uniforms.backgroundRotation.value.setFromMatrix4(qB.makeRotationFromEuler(P.backgroundRotation)).transpose(),L.isCubeTexture&&L.isRenderTargetTexture===!1)Y.material.uniforms.backgroundRotation.value.premultiply(G5);if(Y.material.toneMapped=s$.getTransfer(L.colorSpace)!==w6,G!==L||O!==L.version||E!==$.toneMapping)Y.material.needsUpdate=!0,G=L,O=L.version,E=$.toneMapping;Y.layers.enableAll(),_.unshift(Y,Y.geometry,Y.material,0,0,null)}else if(L&&L.isTexture){if(H===void 0)H=new P6(new CQ(2,2),new yU({name:"BackgroundMaterial",uniforms:d0(kJ.background.uniforms),vertexShader:kJ.background.vertexShader,fragmentShader:kJ.background.fragmentShader,side:K0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),H.geometry.deleteAttribute("normal"),Object.defineProperty(H.material,"map",{get:function(){return this.uniforms.t2D.value}}),Q.update(H);if(H.material.uniforms.t2D.value=L,H.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,H.material.toneMapped=s$.getTransfer(L.colorSpace)!==w6,L.matrixAutoUpdate===!0)L.updateMatrix();if(H.material.uniforms.uvTransform.value.copy(L.matrix),G!==L||O!==L.version||E!==$.toneMapping)H.material.needsUpdate=!0,G=L,O=L.version,E=$.toneMapping;H.layers.enableAll(),_.unshift(H,H.geometry,H.material,0,0,null)}}function I(_,P){_.getRGB(j7,vE($)),J.buffers.color.setClear(j7.r,j7.g,j7.b,P,K)}function q(){if(Y!==void 0)Y.geometry.dispose(),Y.material.dispose(),Y=void 0;if(H!==void 0)H.geometry.dispose(),H.material.dispose(),H=void 0}return{getClearColor:function(){return X},setClearColor:function(_,P=1){X.set(_),N=P,I(X,N)},getClearAlpha:function(){return N},setClearAlpha:function(_){N=_,I(X,N)},render:D,addToRenderList:R,dispose:q}}function kB($,U){let J=$.getParameter($.MAX_VERTEX_ATTRIBS),Q={},W=E(null),K=W,X=!1;function N(C,f,s,y,d){let c=!1,x=O(C,y,s,f);if(K!==x)K=x,Y(K.object);if(c=Z(C,y,s,d),c)D(C,y,s,d);if(d!==null)U.update(d,$.ELEMENT_ARRAY_BUFFER);if(c||X){if(X=!1,L(C,f,s,y),d!==null)$.bindBuffer($.ELEMENT_ARRAY_BUFFER,U.get(d).buffer)}}function H(){return $.createVertexArray()}function Y(C){return $.bindVertexArray(C)}function G(C){return $.deleteVertexArray(C)}function O(C,f,s,y){let d=y.wireframe===!0,c=Q[f.id];if(c===void 0)c={},Q[f.id]=c;let x=C.isInstancedMesh===!0?C.id:0,t=c[x];if(t===void 0)t={},c[x]=t;let e=t[s.id];if(e===void 0)e={},t[s.id]=e;let Y$=e[d];if(Y$===void 0)Y$=E(H()),e[d]=Y$;return Y$}function E(C){let f=[],s=[],y=[];for(let d=0;d<J;d++)f[d]=0,s[d]=0,y[d]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:f,enabledAttributes:s,attributeDivisors:y,object:C,attributes:{},index:null}}function Z(C,f,s,y){let d=K.attributes,c=f.attributes,x=0,t=s.getAttributes();for(let e in t)if(t[e].location>=0){let R$=d[e],w$=c[e];if(w$===void 0){if(e==="instanceMatrix"&&C.instanceMatrix)w$=C.instanceMatrix;if(e==="instanceColor"&&C.instanceColor)w$=C.instanceColor}if(R$===void 0)return!0;if(R$.attribute!==w$)return!0;if(w$&&R$.data!==w$.data)return!0;x++}if(K.attributesNum!==x)return!0;if(K.index!==y)return!0;return!1}function D(C,f,s,y){let d={},c=f.attributes,x=0,t=s.getAttributes();for(let e in t)if(t[e].location>=0){let R$=c[e];if(R$===void 0){if(e==="instanceMatrix"&&C.instanceMatrix)R$=C.instanceMatrix;if(e==="instanceColor"&&C.instanceColor)R$=C.instanceColor}let w$={};if(w$.attribute=R$,R$&&R$.data)w$.data=R$.data;d[e]=w$,x++}K.attributes=d,K.attributesNum=x,K.index=y}function R(){let C=K.newAttributes;for(let f=0,s=C.length;f<s;f++)C[f]=0}function I(C){q(C,0)}function q(C,f){let{newAttributes:s,enabledAttributes:y,attributeDivisors:d}=K;if(s[C]=1,y[C]===0)$.enableVertexAttribArray(C),y[C]=1;if(d[C]!==f)$.vertexAttribDivisor(C,f),d[C]=f}function _(){let{newAttributes:C,enabledAttributes:f}=K;for(let s=0,y=f.length;s<y;s++)if(f[s]!==C[s])$.disableVertexAttribArray(s),f[s]=0}function P(C,f,s,y,d,c,x){if(x===!0)$.vertexAttribIPointer(C,f,s,d,c);else $.vertexAttribPointer(C,f,s,y,d,c)}function L(C,f,s,y){R();let d=y.attributes,c=s.getAttributes(),x=f.defaultAttributeValues;for(let t in c){let e=c[t];if(e.location>=0){let Y$=d[t];if(Y$===void 0){if(t==="instanceMatrix"&&C.instanceMatrix)Y$=C.instanceMatrix;if(t==="instanceColor"&&C.instanceColor)Y$=C.instanceColor}if(Y$!==void 0){let{normalized:R$,itemSize:w$}=Y$,U6=U.get(Y$);if(U6===void 0)continue;let{buffer:i$,type:i,bytesPerElement:X$}=U6,k$=i===$.INT||i===$.UNSIGNED_INT||Y$.gpuType===fO;if(Y$.isInterleavedBufferAttribute){let F$=Y$.data,v$=F$.stride,e$=Y$.offset;if(F$.isInstancedInterleavedBuffer){for(let l$=0;l$<e.locationSize;l$++)q(e.location+l$,F$.meshPerAttribute);if(C.isInstancedMesh!==!0&&y._maxInstanceCount===void 0)y._maxInstanceCount=F$.meshPerAttribute*F$.count}else for(let l$=0;l$<e.locationSize;l$++)I(e.location+l$);$.bindBuffer($.ARRAY_BUFFER,i$);for(let l$=0;l$<e.locationSize;l$++)P(e.location+l$,w$/e.locationSize,i,R$,v$*X$,(e$+w$/e.locationSize*l$)*X$,k$)}else{if(Y$.isInstancedBufferAttribute){for(let F$=0;F$<e.locationSize;F$++)q(e.location+F$,Y$.meshPerAttribute);if(C.isInstancedMesh!==!0&&y._maxInstanceCount===void 0)y._maxInstanceCount=Y$.meshPerAttribute*Y$.count}else for(let F$=0;F$<e.locationSize;F$++)I(e.location+F$);$.bindBuffer($.ARRAY_BUFFER,i$);for(let F$=0;F$<e.locationSize;F$++)P(e.location+F$,w$/e.locationSize,i,R$,w$*X$,w$/e.locationSize*F$*X$,k$)}}else if(x!==void 0){let R$=x[t];if(R$!==void 0)switch(R$.length){case 2:$.vertexAttrib2fv(e.location,R$);break;case 3:$.vertexAttrib3fv(e.location,R$);break;case 4:$.vertexAttrib4fv(e.location,R$);break;default:$.vertexAttrib1fv(e.location,R$)}}}}_()}function B(){w();for(let C in Q){let f=Q[C];for(let s in f){let y=f[s];for(let d in y){let c=y[d];for(let x in c)G(c[x].object),delete c[x];delete y[d]}}delete Q[C]}}function z(C){if(Q[C.id]===void 0)return;let f=Q[C.id];for(let s in f){let y=f[s];for(let d in y){let c=y[d];for(let x in c)G(c[x].object),delete c[x];delete y[d]}}delete Q[C.id]}function A(C){for(let f in Q){let s=Q[f];for(let y in s){let d=s[y];if(d[C.id]===void 0)continue;let c=d[C.id];for(let x in c)G(c[x].object),delete c[x];delete d[C.id]}}}function k(C){for(let f in Q){let s=Q[f],y=C.isInstancedMesh===!0?C.id:0,d=s[y];if(d===void 0)continue;for(let c in d){let x=d[c];for(let t in x)G(x[t].object),delete x[t];delete d[c]}if(delete s[y],Object.keys(s).length===0)delete Q[f]}}function w(){if(h(),X=!0,K===W)return;K=W,Y(K.object)}function h(){W.geometry=null,W.program=null,W.wireframe=!1}return{setup:N,reset:w,resetDefaultState:h,dispose:B,releaseStatesOfGeometry:z,releaseStatesOfObject:k,releaseStatesOfProgram:A,initAttributes:R,enableAttribute:I,disableUnusedAttributes:_}}function FB($,U,J){let Q;function W(H){Q=H}function K(H,Y){$.drawArrays(Q,H,Y),J.update(Y,Q,1)}function X(H,Y,G){if(G===0)return;$.drawArraysInstanced(Q,H,Y,G),J.update(Y,Q,G)}function N(H,Y,G){if(G===0)return;U.get("WEBGL_multi_draw").multiDrawArraysWEBGL(Q,H,0,Y,0,G);let E=0;for(let Z=0;Z<G;Z++)E+=Y[Z];J.update(E,Q,1)}this.setMode=W,this.render=K,this.renderInstances=X,this.renderMultiDraw=N}function LB($,U,J,Q){let W;function K(){if(W!==void 0)return W;if(U.has("EXT_texture_filter_anisotropic")===!0){let A=U.get("EXT_texture_filter_anisotropic");W=$.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else W=0;return W}function X(A){if(A!==IJ&&Q.convert(A)!==$.getParameter($.IMPLEMENTATION_COLOR_READ_FORMAT))return!1;return!0}function N(A){let k=A===gJ&&(U.has("EXT_color_buffer_half_float")||U.has("EXT_color_buffer_float"));if(A!==aU&&Q.convert(A)!==$.getParameter($.IMPLEMENTATION_COLOR_READ_TYPE)&&A!==jJ&&!k)return!1;return!0}function H(A){if(A==="highp"){if($.getShaderPrecisionFormat($.VERTEX_SHADER,$.HIGH_FLOAT).precision>0&&$.getShaderPrecisionFormat($.FRAGMENT_SHADER,$.HIGH_FLOAT).precision>0)return"highp";A="mediump"}if(A==="mediump"){if($.getShaderPrecisionFormat($.VERTEX_SHADER,$.MEDIUM_FLOAT).precision>0&&$.getShaderPrecisionFormat($.FRAGMENT_SHADER,$.MEDIUM_FLOAT).precision>0)return"mediump"}return"lowp"}let Y=J.precision!==void 0?J.precision:"highp",G=H(Y);if(G!==Y)A$("WebGLRenderer:",Y,"not supported, using",G,"instead."),Y=G;let O=J.logarithmicDepthBuffer===!0,E=J.reversedDepthBuffer===!0&&U.has("EXT_clip_control");if(J.reversedDepthBuffer===!0&&E===!1)A$("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let Z=$.getParameter($.MAX_TEXTURE_IMAGE_UNITS),D=$.getParameter($.MAX_VERTEX_TEXTURE_IMAGE_UNITS),R=$.getParameter($.MAX_TEXTURE_SIZE),I=$.getParameter($.MAX_CUBE_MAP_TEXTURE_SIZE),q=$.getParameter($.MAX_VERTEX_ATTRIBS),_=$.getParameter($.MAX_VERTEX_UNIFORM_VECTORS),P=$.getParameter($.MAX_VARYING_VECTORS),L=$.getParameter($.MAX_FRAGMENT_UNIFORM_VECTORS),B=$.getParameter($.MAX_SAMPLES),z=$.getParameter($.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:K,getMaxPrecision:H,textureFormatReadable:X,textureTypeReadable:N,precision:Y,logarithmicDepthBuffer:O,reversedDepthBuffer:E,maxTextures:Z,maxVertexTextures:D,maxTextureSize:R,maxCubemapSize:I,maxAttributes:q,maxVertexUniforms:_,maxVaryings:P,maxFragmentUniforms:L,maxSamples:B,samples:z}}function RB($){let U=this,J=null,Q=0,W=!1,K=!1,X=new cU,N=new u$,H={value:null,needsUpdate:!1};this.uniform=H,this.numPlanes=0,this.numIntersection=0,this.init=function(O,E){let Z=O.length!==0||E||Q!==0||W;return W=E,Q=O.length,Z},this.beginShadows=function(){K=!0,G(null)},this.endShadows=function(){K=!1},this.setGlobalState=function(O,E){J=G(O,E,0)},this.setState=function(O,E,Z){let{clippingPlanes:D,clipIntersection:R,clipShadows:I}=O,q=$.get(O);if(!W||D===null||D.length===0||K&&!I)if(K)G(null);else Y();else{let _=K?0:Q,P=_*4,L=q.clippingState||null;H.value=L,L=G(D,E,P,Z);for(let B=0;B!==P;++B)L[B]=J[B];q.clippingState=L,this.numIntersection=R?this.numPlanes:0,this.numPlanes+=_}};function Y(){if(H.value!==J)H.value=J,H.needsUpdate=Q>0;U.numPlanes=Q,U.numIntersection=0}function G(O,E,Z,D){let R=O!==null?O.length:0,I=null;if(R!==0){if(I=H.value,D!==!0||I===null){let q=Z+R*4,_=E.matrixWorldInverse;if(N.getNormalMatrix(_),I===null||I.length<q)I=new Float32Array(q);for(let P=0,L=Z;P!==R;++P,L+=4)X.copy(O[P]).applyMatrix4(_,N),X.normal.toArray(I,L),I[L+3]=X.constant}H.value=I,H.needsUpdate=!0}return U.numPlanes=R,U.numIntersection=0,I}}var k0=4,lk=[0.125,0.215,0.35,0.446,0.526,0.582],i0=20,VB=256,jQ=new n0,mk=new x$,rE=null,aE=0,sE=0,tE=!1,wB=new j;class yQ{constructor($){this._renderer=$,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($,U=0,J=0.1,Q=100,W={}){let{size:K=256,position:X=wB}=W;rE=this._renderer.getRenderTarget(),aE=this._renderer.getActiveCubeFace(),sE=this._renderer.getActiveMipmapLevel(),tE=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(K);let N=this._allocateTargets();if(N.depthBuffer=!0,this._sceneToCubeUV($,J,Q,N,X),U>0)this._blur(N,0,0,U);return this._applyPMREM(N),this._cleanup(N),N}fromEquirectangular($,U=null){return this._fromTexture($,U)}fromCubemap($,U=null){return this._fromTexture($,U)}compileCubemapShader(){if(this._cubemapMaterial===null)this._cubemapMaterial=ck(),this._compileMaterial(this._cubemapMaterial)}compileEquirectangularShader(){if(this._equirectMaterial===null)this._equirectMaterial=dk(),this._compileMaterial(this._equirectMaterial)}dispose(){if(this._dispose(),this._cubemapMaterial!==null)this._cubemapMaterial.dispose();if(this._equirectMaterial!==null)this._equirectMaterial.dispose();if(this._backgroundBox!==null)this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose()}_setSize($){this._lodMax=Math.floor(Math.log2($)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){if(this._blurMaterial!==null)this._blurMaterial.dispose();if(this._ggxMaterial!==null)this._ggxMaterial.dispose();if(this._pingPongRenderTarget!==null)this._pingPongRenderTarget.dispose();for(let $=0;$<this._lodMeshes.length;$++)this._lodMeshes[$].geometry.dispose()}_cleanup($){this._renderer.setRenderTarget(rE,aE,sE),this._renderer.xr.enabled=tE,$.scissorTest=!1,G8($,0,0,$.width,$.height)}_fromTexture($,U){if($.mapping===sW||$.mapping===h0)this._setSize($.image.length===0?16:$.image[0].width||$.image[0].image.width);else this._setSize($.image.width/4);rE=this._renderer.getRenderTarget(),aE=this._renderer.getActiveCubeFace(),sE=this._renderer.getActiveMipmapLevel(),tE=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let J=U||this._allocateTargets();return this._textureToCubeUV($,J),this._applyPMREM(J),this._cleanup(J),J}_allocateTargets(){let $=3*Math.max(this._cubeSize,112),U=4*this._cubeSize,J={magFilter:o6,minFilter:o6,generateMipmaps:!1,type:gJ,format:IJ,colorSpace:BU,depthBuffer:!1},Q=pk($,U,J);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==$||this._pingPongRenderTarget.height!==U){if(this._pingPongRenderTarget!==null)this._dispose();this._pingPongRenderTarget=pk($,U,J);let{_lodMax:W}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=MB(W)),this._blurMaterial=PB(W,$,U),this._ggxMaterial=BB(W,$,U)}return Q}_compileMaterial($){let U=new P6(new OU,$);this._renderer.compile(U,jQ)}_sceneToCubeUV($,U,J,Q,W){let N=new f6(90,1,U,J),H=[1,-1,1,1,1,1],Y=[1,1,1,-1,-1,-1],G=this._renderer,O=G.autoClear,E=G.toneMapping;if(G.getClearColor(mk),G.toneMapping=oU,G.autoClear=!1,G.state.buffers.depth.getReversed())G.setRenderTarget(Q),G.clearDepth(),G.setRenderTarget(null);if(this._backgroundBox===null)this._backgroundBox=new P6(new O0,new qJ({name:"PMREM.Background",side:JU,depthWrite:!1,depthTest:!1}));let D=this._backgroundBox,R=D.material,I=!1,q=$.background;if(q){if(q.isColor)R.color.copy(q),$.background=null,I=!0}else R.color.copy(mk),I=!0;for(let _=0;_<6;_++){let P=_%3;if(P===0)N.up.set(0,H[_],0),N.position.set(W.x,W.y,W.z),N.lookAt(W.x+Y[_],W.y,W.z);else if(P===1)N.up.set(0,0,H[_]),N.position.set(W.x,W.y,W.z),N.lookAt(W.x,W.y+Y[_],W.z);else N.up.set(0,H[_],0),N.position.set(W.x,W.y,W.z),N.lookAt(W.x,W.y,W.z+Y[_]);let L=this._cubeSize;if(G8(Q,P*L,_>2?L:0,L,L),G.setRenderTarget(Q),I)G.render(D,N);G.render($,N)}G.toneMapping=E,G.autoClear=O,$.background=q}_textureToCubeUV($,U){let J=this._renderer,Q=$.mapping===sW||$.mapping===h0;if(Q){if(this._cubemapMaterial===null)this._cubemapMaterial=ck();this._cubemapMaterial.uniforms.flipEnvMap.value=$.isRenderTargetTexture===!1?-1:1}else if(this._equirectMaterial===null)this._equirectMaterial=dk();let W=Q?this._cubemapMaterial:this._equirectMaterial,K=this._lodMeshes[0];K.material=W;let X=W.uniforms;X.envMap.value=$;let N=this._cubeSize;G8(U,0,0,3*N,2*N),J.setRenderTarget(U),J.render(K,jQ)}_applyPMREM($){let U=this._renderer,J=U.autoClear;U.autoClear=!1;let Q=this._lodMeshes.length;for(let W=1;W<Q;W++)this._applyGGXFilter($,W-1,W);U.autoClear=J}_applyGGXFilter($,U,J){let Q=this._renderer,W=this._pingPongRenderTarget,K=this._ggxMaterial,X=this._lodMeshes[J];X.material=K;let N=K.uniforms,H=J/(this._lodMeshes.length-1),Y=U/(this._lodMeshes.length-1),G=Math.sqrt(H*H-Y*Y),O=0+H*1.25,E=G*O,{_lodMax:Z}=this,D=this._sizeLods[J],R=3*D*(J>Z-k0?J-Z+k0:0),I=4*(this._cubeSize-D);N.envMap.value=$.texture,N.roughness.value=E,N.mipInt.value=Z-U,G8(W,R,I,3*D,2*D),Q.setRenderTarget(W),Q.render(X,jQ),N.envMap.value=W.texture,N.roughness.value=0,N.mipInt.value=Z-J,G8($,R,I,3*D,2*D),Q.setRenderTarget($),Q.render(X,jQ)}_blur($,U,J,Q,W){let K=this._pingPongRenderTarget;this._halfBlur($,K,U,J,Q,"latitudinal",W),this._halfBlur(K,$,J,J,Q,"longitudinal",W)}_halfBlur($,U,J,Q,W,K,X){let N=this._renderer,H=this._blurMaterial;if(K!=="latitudinal"&&K!=="longitudinal")y$("blur direction must be either latitudinal or longitudinal!");let Y=3,G=this._lodMeshes[Q];G.material=H;let O=H.uniforms,E=this._sizeLods[J]-1,Z=isFinite(W)?Math.PI/(2*E):2*Math.PI/(2*i0-1),D=W/Z,R=isFinite(W)?1+Math.floor(Y*D):i0;if(R>i0)A$(`sigmaRadians, ${W}, is too large and will clip, as it requested ${R} samples when the maximum is set to ${i0}`);let I=[],q=0;for(let z=0;z<i0;++z){let A=z/D,k=Math.exp(-A*A/2);if(I.push(k),z===0)q+=k;else if(z<R)q+=2*k}for(let z=0;z<I.length;z++)I[z]=I[z]/q;if(O.envMap.value=$.texture,O.samples.value=R,O.weights.value=I,O.latitudinal.value=K==="latitudinal",X)O.poleAxis.value=X;let{_lodMax:_}=this;O.dTheta.value=Z,O.mipInt.value=_-J;let P=this._sizeLods[Q],L=3*P*(Q>_-k0?Q-_+k0:0),B=4*(this._cubeSize-P);G8(U,L,B,3*P,2*P),N.setRenderTarget(U),N.render(G,jQ)}}function MB($){let U=[],J=[],Q=[],W=$,K=$-k0+1+lk.length;for(let X=0;X<K;X++){let N=Math.pow(2,W);U.push(N);let H=1/N;if(X>$-k0)H=lk[X-$+k0-1];else if(X===0)H=0;J.push(H);let Y=1/(N-2),G=-Y,O=1+Y,E=[G,G,O,G,O,O,G,G,O,O,G,O],Z=6,D=6,R=3,I=2,q=1,_=new Float32Array(R*D*Z),P=new Float32Array(I*D*Z),L=new Float32Array(q*D*Z);for(let z=0;z<Z;z++){let A=z%3*2/3-1,k=z>2?0:-1,w=[A,k,0,A+0.6666666666666666,k,0,A+0.6666666666666666,k+1,0,A,k,0,A+0.6666666666666666,k+1,0,A,k+1,0];_.set(w,R*D*z),P.set(E,I*D*z);let h=[z,z,z,z,z,z];L.set(h,q*D*z)}let B=new OU;if(B.setAttribute("position",new u6(_,R)),B.setAttribute("uv",new u6(P,I)),B.setAttribute("faceIndex",new u6(L,q)),Q.push(new P6(B,null)),W>k0)W--}return{lodMeshes:Q,sizeLods:U,sigmas:J}}function pk($,U,J){let Q=new xU($,U,J);return Q.texture.mapping=DQ,Q.texture.name="PMREM.cubeUv",Q.scissorTest=!0,Q}function G8($,U,J,Q,W){$.viewport.set(U,J,Q,W),$.scissor.set(U,J,Q,W)}function BB($,U,J){return new yU({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:VB,CUBEUV_TEXEL_WIDTH:1/U,CUBEUV_TEXEL_HEIGHT:1/J,CUBEUV_MAX_MIP:`${$}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:b7(),fragmentShader:`+}`,He={alphahash_fragment:Ky,alphahash_pars_fragment:Qy,alphamap_fragment:eb,alphamap_pars_fragment:tb,alphatest_fragment:nb,alphatest_pars_fragment:ib,aomap_fragment:rb,aomap_pars_fragment:sb,batching_pars_vertex:ob,batching_vertex:ab,begin_vertex:cb,beginnormal_vertex:lb,bsdfs:ub,iridescence_fragment:hb,bumpmap_pars_fragment:fb,clipping_planes_fragment:db,clipping_planes_pars_fragment:pb,clipping_planes_pars_vertex:mb,clipping_planes_vertex:gb,color_fragment:_b,color_pars_fragment:xb,color_pars_vertex:vb,color_vertex:yb,common:bb,cube_uv_reflection_fragment:Sb,defaultnormal_vertex:Mb,displacementmap_pars_vertex:wb,displacementmap_vertex:Tb,emissivemap_fragment:Eb,emissivemap_pars_fragment:Ab,colorspace_fragment:Rb,colorspace_pars_fragment:Cb,envmap_fragment:Ib,envmap_common_pars_fragment:Pb,envmap_pars_fragment:Lb,envmap_pars_vertex:Nb,envmap_physical_pars_fragment:Wb,envmap_vertex:Db,fog_vertex:Ub,fog_pars_vertex:Ob,fog_fragment:Fb,fog_pars_fragment:zb,gradientmap_pars_fragment:kb,lightmap_pars_fragment:Bb,lights_lambert_fragment:Gb,lights_lambert_pars_fragment:Hb,lights_pars_begin:Vb,lights_toon_fragment:$b,lights_toon_pars_fragment:Zb,lights_phong_fragment:Xb,lights_phong_pars_fragment:qb,lights_physical_fragment:Yb,lights_physical_pars_fragment:jb,lights_fragment_begin:Jb,lights_fragment_maps:Kb,lights_fragment_end:Qb,lightprobes_pars_fragment:eS,logdepthbuf_fragment:tS,logdepthbuf_pars_fragment:nS,logdepthbuf_pars_vertex:iS,logdepthbuf_vertex:rS,map_fragment:sS,map_pars_fragment:oS,map_particle_fragment:aS,map_particle_pars_fragment:cS,metalnessmap_fragment:lS,metalnessmap_pars_fragment:uS,morphinstance_vertex:hS,morphcolor_vertex:fS,morphnormal_vertex:dS,morphtarget_pars_vertex:pS,morphtarget_vertex:mS,normal_fragment_begin:gS,normal_fragment_maps:_S,normal_pars_fragment:xS,normal_pars_vertex:vS,normal_vertex:yS,normalmap_pars_fragment:bS,clearcoat_normal_fragment_begin:SS,clearcoat_normal_fragment_maps:MS,clearcoat_pars_fragment:wS,iridescence_pars_fragment:TS,opaque_fragment:ES,packing:AS,premultiplied_alpha_fragment:RS,project_vertex:CS,dithering_fragment:IS,dithering_pars_fragment:PS,roughnessmap_fragment:LS,roughnessmap_pars_fragment:NS,shadowmap_pars_fragment:DS,shadowmap_pars_vertex:US,shadowmap_vertex:OS,shadowmask_pars_fragment:FS,skinbase_vertex:zS,skinning_pars_vertex:kS,skinning_vertex:BS,skinnormal_vertex:GS,specularmap_fragment:HS,specularmap_pars_fragment:VS,tonemapping_fragment:WS,tonemapping_pars_fragment:$S,transmission_fragment:ZS,transmission_pars_fragment:XS,uv_pars_fragment:qS,uv_pars_vertex:YS,uv_vertex:jS,worldpos_vertex:JS,background_vert:KS,background_frag:QS,backgroundCube_vert:eM,backgroundCube_frag:tM,cube_vert:nM,cube_frag:iM,depth_vert:rM,depth_frag:sM,distance_vert:oM,distance_frag:aM,equirect_vert:cM,equirect_frag:lM,linedashed_vert:uM,linedashed_frag:hM,meshbasic_vert:fM,meshbasic_frag:dM,meshlambert_vert:pM,meshlambert_frag:mM,meshmatcap_vert:gM,meshmatcap_frag:_M,meshnormal_vert:xM,meshnormal_frag:vM,meshphong_vert:yM,meshphong_frag:bM,meshphysical_vert:SM,meshphysical_frag:MM,meshtoon_vert:wM,meshtoon_frag:TM,points_vert:EM,points_frag:AM,shadow_vert:RM,shadow_frag:CM,sprite_vert:IM,sprite_frag:PM},he={common:{diffuse:{value:new Le(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ue},alphaMap:{value:null},alphaMapTransform:{value:new Ue},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ue}},envmap:{envMap:{value:null},envMapRotation:{value:new Ue},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:0.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ue}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ue}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ue},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ue},normalScale:{value:new Ie(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ue},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ue}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ue}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ue}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:0.00025},fogNear:{value:1},fogFar:{value:2000},fogColor:{value:new Le(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 N},probesMax:{value:new N},probesResolution:{value:new N}},points:{diffuse:{value:new Le(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ue},alphaTest:{value:0},uvTransform:{value:new Ue}},sprite:{diffuse:{value:new Le(16777215)},opacity:{value:1},center:{value:new Ie(0.5,0.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ue},alphaMap:{value:null},alphaMapTransform:{value:new Ue},alphaTest:{value:0}}},ei={basic:{uniforms:jt([he.common,he.specularmap,he.envmap,he.aomap,he.lightmap,he.fog]),vertexShader:He.meshbasic_vert,fragmentShader:He.meshbasic_frag},lambert:{uniforms:jt([he.common,he.specularmap,he.envmap,he.aomap,he.lightmap,he.emissivemap,he.bumpmap,he.normalmap,he.displacementmap,he.fog,he.lights,{emissive:{value:new Le(0)},envMapIntensity:{value:1}}]),vertexShader:He.meshlambert_vert,fragmentShader:He.meshlambert_frag},phong:{uniforms:jt([he.common,he.specularmap,he.envmap,he.aomap,he.lightmap,he.emissivemap,he.bumpmap,he.normalmap,he.displacementmap,he.fog,he.lights,{emissive:{value:new Le(0)},specular:{value:new Le(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:He.meshphong_vert,fragmentShader:He.meshphong_frag},standard:{uniforms:jt([he.common,he.envmap,he.aomap,he.lightmap,he.emissivemap,he.bumpmap,he.normalmap,he.displacementmap,he.roughnessmap,he.metalnessmap,he.fog,he.lights,{emissive:{value:new Le(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag},toon:{uniforms:jt([he.common,he.aomap,he.lightmap,he.emissivemap,he.bumpmap,he.normalmap,he.displacementmap,he.gradientmap,he.fog,he.lights,{emissive:{value:new Le(0)}}]),vertexShader:He.meshtoon_vert,fragmentShader:He.meshtoon_frag},matcap:{uniforms:jt([he.common,he.bumpmap,he.normalmap,he.displacementmap,he.fog,{matcap:{value:null}}]),vertexShader:He.meshmatcap_vert,fragmentShader:He.meshmatcap_frag},points:{uniforms:jt([he.points,he.fog]),vertexShader:He.points_vert,fragmentShader:He.points_frag},dashed:{uniforms:jt([he.common,he.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:He.linedashed_vert,fragmentShader:He.linedashed_frag},depth:{uniforms:jt([he.common,he.displacementmap]),vertexShader:He.depth_vert,fragmentShader:He.depth_frag},normal:{uniforms:jt([he.common,he.bumpmap,he.normalmap,he.displacementmap,{opacity:{value:1}}]),vertexShader:He.meshnormal_vert,fragmentShader:He.meshnormal_frag},sprite:{uniforms:jt([he.sprite,he.fog]),vertexShader:He.sprite_vert,fragmentShader:He.sprite_frag},background:{uniforms:{uvTransform:{value:new Ue},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:He.background_vert,fragmentShader:He.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ue}},vertexShader:He.backgroundCube_vert,fragmentShader:He.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:He.cube_vert,fragmentShader:He.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:He.equirect_vert,fragmentShader:He.equirect_frag},distance:{uniforms:jt([he.common,he.displacementmap,{referencePosition:{value:new N},nearDistance:{value:1},farDistance:{value:1000}}]),vertexShader:He.distance_vert,fragmentShader:He.distance_frag},shadow:{uniforms:jt([he.lights,he.fog,{color:{value:new Le(0)},opacity:{value:1}}]),vertexShader:He.shadow_vert,fragmentShader:He.shadow_frag}};ei.physical={uniforms:jt([ei.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ue},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ue},clearcoatNormalScale:{value:new Ie(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ue},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ue},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ue},sheen:{value:0},sheenColor:{value:new Le(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ue},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ue},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ue},transmissionSamplerSize:{value:new Ie},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ue},attenuationDistance:{value:0},attenuationColor:{value:new Le(0)},specularColor:{value:new Le(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ue},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ue},anisotropyVector:{value:new Ie},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ue}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag};var Ya={r:0,b:0,g:0},LM=new ze,Z_=new Ue;Z_.set(-1,0,0,0,1,0,0,0,1);function NM(e,t,n,i,r,s){let o=new Le(0),a=r===!0?0:1,c,l,u=null,f=0,h=null;function d(A){let T=A.isScene===!0?A.background:null;if(T&&T.isTexture){let v=A.backgroundBlurriness>0;T=t.get(T,v)}return T}function g(A){let T=!1,v=d(A);if(v===null)p(o,a);else if(v&&v.isColor)p(v,1),T=!0;let w=e.xr.getEnvironmentBlendMode();if(w==="additive")n.buffers.color.setClear(0,0,0,1,s);else if(w==="alpha-blend")n.buffers.color.setClear(0,0,0,0,s);if(e.autoClear||T)n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil)}function y(A,T){let v=d(T);if(v&&(v.isCubeTexture||v.mapping===Hs)){if(l===void 0)l=new pt(new Gi(1,1,1),new Mn({name:"BackgroundCubeMaterial",uniforms:gr(ei.backgroundCube.uniforms),vertexShader:ei.backgroundCube.vertexShader,fragmentShader:ei.backgroundCube.fragmentShader,side:Yt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(w,E,R){this.matrixWorld.copyPosition(R.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(l);if(l.material.uniforms.envMap.value=v,l.material.uniforms.backgroundBlurriness.value=T.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=T.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(LM.makeRotationFromEuler(T.backgroundRotation)).transpose(),v.isCubeTexture&&v.isRenderTargetTexture===!1)l.material.uniforms.backgroundRotation.value.premultiply(Z_);if(l.material.toneMapped=We.getTransfer(v.colorSpace)!==ht,u!==v||f!==v.version||h!==e.toneMapping)l.material.needsUpdate=!0,u=v,f=v.version,h=e.toneMapping;l.layers.enableAll(),A.unshift(l,l.geometry,l.material,0,0,null)}else if(v&&v.isTexture){if(c===void 0)c=new pt(new to(2,2),new Mn({name:"BackgroundMaterial",uniforms:gr(ei.background.uniforms),vertexShader:ei.background.vertexShader,fragmentShader:ei.background.fragmentShader,side:Ui,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(c);if(c.material.uniforms.t2D.value=v,c.material.uniforms.backgroundIntensity.value=T.backgroundIntensity,c.material.toneMapped=We.getTransfer(v.colorSpace)!==ht,v.matrixAutoUpdate===!0)v.updateMatrix();if(c.material.uniforms.uvTransform.value.copy(v.matrix),u!==v||f!==v.version||h!==e.toneMapping)c.material.needsUpdate=!0,u=v,f=v.version,h=e.toneMapping;c.layers.enableAll(),A.unshift(c,c.geometry,c.material,0,0,null)}}function p(A,T){A.getRGB(Ya,Au(e)),n.buffers.color.setClear(Ya.r,Ya.g,Ya.b,T,s)}function m(){if(l!==void 0)l.geometry.dispose(),l.material.dispose(),l=void 0;if(c!==void 0)c.geometry.dispose(),c.material.dispose(),c=void 0}return{getClearColor:function(){return o},setClearColor:function(A,T=1){o.set(A),a=T,p(o,a)},getClearAlpha:function(){return a},setClearAlpha:function(A){a=A,p(o,a)},render:g,addToRenderList:y,dispose:m}}function DM(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=h(null),s=r,o=!1;function a(C,z,J,O,H){let V=!1,U=f(C,O,J,z);if(s!==U)s=U,l(s.object);if(V=d(C,O,J,H),V)g(C,O,J,H);if(H!==null)t.update(H,e.ELEMENT_ARRAY_BUFFER);if(V||o){if(o=!1,v(C,z,J,O),H!==null)e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(H).buffer)}}function c(){return e.createVertexArray()}function l(C){return e.bindVertexArray(C)}function u(C){return e.deleteVertexArray(C)}function f(C,z,J,O){let H=O.wireframe===!0,V=i[z.id];if(V===void 0)V={},i[z.id]=V;let U=C.isInstancedMesh===!0?C.id:0,K=V[U];if(K===void 0)K={},V[U]=K;let Q=K[J.id];if(Q===void 0)Q={},K[J.id]=Q;let se=Q[H];if(se===void 0)se=h(c()),Q[H]=se;return se}function h(C){let z=[],J=[],O=[];for(let H=0;H<n;H++)z[H]=0,J[H]=0,O[H]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:z,enabledAttributes:J,attributeDivisors:O,object:C,attributes:{},index:null}}function d(C,z,J,O){let H=s.attributes,V=z.attributes,U=0,K=J.getAttributes();for(let Q in K)if(K[Q].location>=0){let me=H[Q],_e=V[Q];if(_e===void 0){if(Q==="instanceMatrix"&&C.instanceMatrix)_e=C.instanceMatrix;if(Q==="instanceColor"&&C.instanceColor)_e=C.instanceColor}if(me===void 0)return!0;if(me.attribute!==_e)return!0;if(_e&&me.data!==_e.data)return!0;U++}if(s.attributesNum!==U)return!0;if(s.index!==O)return!0;return!1}function g(C,z,J,O){let H={},V=z.attributes,U=0,K=J.getAttributes();for(let Q in K)if(K[Q].location>=0){let me=V[Q];if(me===void 0){if(Q==="instanceMatrix"&&C.instanceMatrix)me=C.instanceMatrix;if(Q==="instanceColor"&&C.instanceColor)me=C.instanceColor}let _e={};if(_e.attribute=me,me&&me.data)_e.data=me.data;H[Q]=_e,U++}s.attributes=H,s.attributesNum=U,s.index=O}function y(){let C=s.newAttributes;for(let z=0,J=C.length;z<J;z++)C[z]=0}function p(C){m(C,0)}function m(C,z){let J=s.newAttributes,O=s.enabledAttributes,H=s.attributeDivisors;if(J[C]=1,O[C]===0)e.enableVertexAttribArray(C),O[C]=1;if(H[C]!==z)e.vertexAttribDivisor(C,z),H[C]=z}function A(){let C=s.newAttributes,z=s.enabledAttributes;for(let J=0,O=z.length;J<O;J++)if(z[J]!==C[J])e.disableVertexAttribArray(J),z[J]=0}function T(C,z,J,O,H,V,U){if(U===!0)e.vertexAttribIPointer(C,z,J,H,V);else e.vertexAttribPointer(C,z,J,O,H,V)}function v(C,z,J,O){y();let H=O.attributes,V=J.getAttributes(),U=z.defaultAttributeValues;for(let K in V){let Q=V[K];if(Q.location>=0){let se=H[K];if(se===void 0){if(K==="instanceMatrix"&&C.instanceMatrix)se=C.instanceMatrix;if(K==="instanceColor"&&C.instanceColor)se=C.instanceColor}if(se!==void 0){let me=se.normalized,_e=se.itemSize,qe=t.get(se);if(qe===void 0)continue;let{buffer:Ge,type:Z,bytesPerElement:ne}=qe,fe=Z===e.INT||Z===e.UNSIGNED_INT||se.gpuType===Dl;if(se.isInterleavedBufferAttribute){let de=se.data,Re=de.stride,Ze=se.offset;if(de.isInstancedInterleavedBuffer){for(let Oe=0;Oe<Q.locationSize;Oe++)m(Q.location+Oe,de.meshPerAttribute);if(C.isInstancedMesh!==!0&&O._maxInstanceCount===void 0)O._maxInstanceCount=de.meshPerAttribute*de.count}else for(let Oe=0;Oe<Q.locationSize;Oe++)p(Q.location+Oe);e.bindBuffer(e.ARRAY_BUFFER,Ge);for(let Oe=0;Oe<Q.locationSize;Oe++)T(Q.location+Oe,_e/Q.locationSize,Z,me,Re*ne,(Ze+_e/Q.locationSize*Oe)*ne,fe)}else{if(se.isInstancedBufferAttribute){for(let de=0;de<Q.locationSize;de++)m(Q.location+de,se.meshPerAttribute);if(C.isInstancedMesh!==!0&&O._maxInstanceCount===void 0)O._maxInstanceCount=se.meshPerAttribute*se.count}else for(let de=0;de<Q.locationSize;de++)p(Q.location+de);e.bindBuffer(e.ARRAY_BUFFER,Ge);for(let de=0;de<Q.locationSize;de++)T(Q.location+de,_e/Q.locationSize,Z,me,_e*ne,_e/Q.locationSize*de*ne,fe)}}else if(U!==void 0){let me=U[K];if(me!==void 0)switch(me.length){case 2:e.vertexAttrib2fv(Q.location,me);break;case 3:e.vertexAttrib3fv(Q.location,me);break;case 4:e.vertexAttrib4fv(Q.location,me);break;default:e.vertexAttrib1fv(Q.location,me)}}}}A()}function w(){S();for(let C in i){let z=i[C];for(let J in z){let O=z[J];for(let H in O){let V=O[H];for(let U in V)u(V[U].object),delete V[U];delete O[H]}}delete i[C]}}function E(C){if(i[C.id]===void 0)return;let z=i[C.id];for(let J in z){let O=z[J];for(let H in O){let V=O[H];for(let U in V)u(V[U].object),delete V[U];delete O[H]}}delete i[C.id]}function R(C){for(let z in i){let J=i[z];for(let O in J){let H=J[O];if(H[C.id]===void 0)continue;let V=H[C.id];for(let U in V)u(V[U].object),delete V[U];delete H[C.id]}}}function _(C){for(let z in i){let J=i[z],O=C.isInstancedMesh===!0?C.id:0,H=J[O];if(H===void 0)continue;for(let V in H){let U=H[V];for(let K in U)u(U[K].object),delete U[K];delete H[V]}if(delete J[O],Object.keys(J).length===0)delete i[z]}}function S(){if(F(),o=!0,s===r)return;s=r,l(s.object)}function F(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:a,reset:S,resetDefaultState:F,dispose:w,releaseStatesOfGeometry:E,releaseStatesOfObject:_,releaseStatesOfProgram:R,initAttributes:y,enableAttribute:p,disableUnusedAttributes:A}}function UM(e,t,n){let i;function r(c){i=c}function s(c,l){e.drawArrays(i,c,l),n.update(l,i,1)}function o(c,l,u){if(u===0)return;e.drawArraysInstanced(i,c,l,u),n.update(l,i,u)}function a(c,l,u){if(u===0)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,c,0,l,0,u);let h=0;for(let d=0;d<u;d++)h+=l[d];n.update(h,i,1)}this.setMode=r,this.render=s,this.renderInstances=o,this.renderMultiDraw=a}function OM(e,t,n,i){let r;function s(){if(r!==void 0)return r;if(t.has("EXT_texture_filter_anisotropic")===!0){let R=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(R.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}function o(R){if(R!==Jn&&i.convert(R)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))return!1;return!0}function a(R){let _=R===pi&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));if(R!==Fn&&i.convert(R)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&R!==di&&!_)return!1;return!0}function c(R){if(R==="highp"){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";R="mediump"}if(R==="mediump"){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0)return"mediump"}return"lowp"}let l=n.precision!==void 0?n.precision:"highp",u=c(l);if(u!==l)Me("WebGLRenderer:",l,"not supported, using",u,"instead."),l=u;let f=n.logarithmicDepthBuffer===!0,h=n.reversedDepthBuffer===!0&&t.has("EXT_clip_control");if(n.reversedDepthBuffer===!0&&h===!1)Me("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let d=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),g=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),y=e.getParameter(e.MAX_TEXTURE_SIZE),p=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),m=e.getParameter(e.MAX_VERTEX_ATTRIBS),A=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),T=e.getParameter(e.MAX_VARYING_VECTORS),v=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),w=e.getParameter(e.MAX_SAMPLES),E=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:f,reversedDepthBuffer:h,maxTextures:d,maxVertexTextures:g,maxTextureSize:y,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:A,maxVaryings:T,maxFragmentUniforms:v,maxSamples:w,samples:E}}function FM(e){let t=this,n=null,i=0,r=!1,s=!1,o=new Ln,a=new Ue,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(f,h){let d=f.length!==0||h||i!==0||r;return r=h,i=f.length,d},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(f,h){n=u(f,h,0)},this.setState=function(f,h,d){let{clippingPlanes:g,clipIntersection:y,clipShadows:p}=f,m=e.get(f);if(!r||g===null||g.length===0||s&&!p)if(s)u(null);else l();else{let A=s?0:i,T=A*4,v=m.clippingState||null;c.value=v,v=u(g,h,T,d);for(let w=0;w!==T;++w)v[w]=n[w];m.clippingState=v,this.numIntersection=y?this.numPlanes:0,this.numPlanes+=A}};function l(){if(c.value!==n)c.value=n,c.needsUpdate=i>0;t.numPlanes=i,t.numIntersection=0}function u(f,h,d,g){let y=f!==null?f.length:0,p=null;if(y!==0){if(p=c.value,g!==!0||p===null){let m=d+y*4,A=h.matrixWorldInverse;if(a.getNormalMatrix(A),p===null||p.length<m)p=new Float32Array(m);for(let T=0,v=d;T!==y;++T,v+=4)o.copy(f[T]).applyMatrix4(A,a),o.normal.toArray(p,v),p[v+3]=o.constant}c.value=p,c.needsUpdate=!0}return t.numPlanes=y,t.numIntersection=0,p}}var Xi=4,M_=[0.125,0.215,0.35,0.446,0.526,0.582],vr=20,zM=256,so=new xr,w_=new Le,Wu=null,$u=0,Zu=0,Xu=!1,kM=new N;class lo{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=0.1,i=100,r={}){let{size:s=256,position:o=kM}=r;Wu=this._renderer.getRenderTarget(),$u=this._renderer.getActiveCubeFace(),Zu=this._renderer.getActiveMipmapLevel(),Xu=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);let a=this._allocateTargets();if(a.depthBuffer=!0,this._sceneToCubeUV(e,n,i,a,o),t>0)this._blur(a,0,0,t);return this._applyPMREM(a),this._cleanup(a),a}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){if(this._cubemapMaterial===null)this._cubemapMaterial=A_(),this._compileMaterial(this._cubemapMaterial)}compileEquirectangularShader(){if(this._equirectMaterial===null)this._equirectMaterial=E_(),this._compileMaterial(this._equirectMaterial)}dispose(){if(this._dispose(),this._cubemapMaterial!==null)this._cubemapMaterial.dispose();if(this._equirectMaterial!==null)this._equirectMaterial.dispose();if(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(){if(this._blurMaterial!==null)this._blurMaterial.dispose();if(this._ggxMaterial!==null)this._ggxMaterial.dispose();if(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(Wu,$u,Zu),this._renderer.xr.enabled=Xu,e.scissorTest=!1,as(e,0,0,e.width,e.height)}_fromTexture(e,t){if(e.mapping===qr||e.mapping===ur)this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width);else this._setSize(e.image.width/4);Wu=this._renderer.getRenderTarget(),$u=this._renderer.getActiveCubeFace(),Zu=this._renderer.getActiveMipmapLevel(),Xu=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:Gt,minFilter:Gt,generateMipmaps:!1,type:pi,format:Jn,colorSpace:hn,depthBuffer:!1},i=T_(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){if(this._pingPongRenderTarget!==null)this._dispose();this._pingPongRenderTarget=T_(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=BM(r)),this._blurMaterial=HM(r,e,t),this._ggxMaterial=GM(r,e,t)}return i}_compileMaterial(e){let t=new pt(new tn,e);this._renderer.compile(t,so)}_sceneToCubeUV(e,t,n,i,r){let a=new Lt(90,1,t,n),c=[1,-1,1,1,1,1],l=[1,1,1,-1,-1,-1],u=this._renderer,{autoClear:f,toneMapping:h}=u;if(u.getClearColor(w_),u.toneMapping=Un,u.autoClear=!1,u.state.buffers.depth.getReversed())u.setRenderTarget(i),u.clearDepth(),u.setRenderTarget(null);if(this._backgroundBox===null)this._backgroundBox=new pt(new Gi,new Kn({name:"PMREM.Background",side:Yt,depthWrite:!1,depthTest:!1}));let g=this._backgroundBox,y=g.material,p=!1,m=e.background;if(m){if(m.isColor)y.color.copy(m),e.background=null,p=!0}else y.color.copy(w_),p=!0;for(let A=0;A<6;A++){let T=A%3;if(T===0)a.up.set(0,c[A],0),a.position.set(r.x,r.y,r.z),a.lookAt(r.x+l[A],r.y,r.z);else if(T===1)a.up.set(0,0,c[A]),a.position.set(r.x,r.y,r.z),a.lookAt(r.x,r.y+l[A],r.z);else a.up.set(0,c[A],0),a.position.set(r.x,r.y,r.z),a.lookAt(r.x,r.y,r.z+l[A]);let v=this._cubeSize;if(as(i,T*v,A>2?v:0,v,v),u.setRenderTarget(i),p)u.render(g,a);u.render(e,a)}u.toneMapping=h,u.autoClear=f,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===qr||e.mapping===ur;if(i){if(this._cubemapMaterial===null)this._cubemapMaterial=A_();this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1}else if(this._equirectMaterial===null)this._equirectMaterial=E_();let r=i?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=r;let o=r.uniforms;o.envMap.value=e;let a=this._cubeSize;as(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,so)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let i=this._lodMeshes.length;for(let r=1;r<i;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){let i=this._renderer,r=this._pingPongRenderTarget,s=this._ggxMaterial,o=this._lodMeshes[n];o.material=s;let a=s.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l),f=0+c*1.25,h=u*f,{_lodMax:d}=this,g=this._sizeLods[n],y=3*g*(n>d-Xi?n-d+Xi:0),p=4*(this._cubeSize-g);a.envMap.value=e.texture,a.roughness.value=h,a.mipInt.value=d-t,as(r,y,p,3*g,2*g),i.setRenderTarget(r),i.render(o,so),a.envMap.value=r.texture,a.roughness.value=0,a.mipInt.value=d-n,as(e,y,p,3*g,2*g),i.setRenderTarget(e),i.render(o,so)}_blur(e,t,n,i,r){let s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,i,"latitudinal",r),this._halfBlur(s,e,n,n,i,"longitudinal",r)}_halfBlur(e,t,n,i,r,s,o){let a=this._renderer,c=this._blurMaterial;if(s!=="latitudinal"&&s!=="longitudinal")Ne("blur direction must be either latitudinal or longitudinal!");let l=3,u=this._lodMeshes[i];u.material=c;let f=c.uniforms,h=this._sizeLods[n]-1,d=isFinite(r)?Math.PI/(2*h):2*Math.PI/(2*vr-1),g=r/d,y=isFinite(r)?1+Math.floor(l*g):vr;if(y>vr)Me(`sigmaRadians, ${r}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${vr}`);let p=[],m=0;for(let E=0;E<vr;++E){let R=E/g,_=Math.exp(-R*R/2);if(p.push(_),E===0)m+=_;else if(E<y)m+=2*_}for(let E=0;E<p.length;E++)p[E]=p[E]/m;if(f.envMap.value=e.texture,f.samples.value=y,f.weights.value=p,f.latitudinal.value=s==="latitudinal",o)f.poleAxis.value=o;let{_lodMax:A}=this;f.dTheta.value=d,f.mipInt.value=A-n;let T=this._sizeLods[i],v=3*T*(i>A-Xi?i-A+Xi:0),w=4*(this._cubeSize-T);as(t,v,w,3*T,2*T),a.setRenderTarget(t),a.render(u,so)}}function BM(e){let t=[],n=[],i=[],r=e,s=e-Xi+1+M_.length;for(let o=0;o<s;o++){let a=Math.pow(2,r);t.push(a);let c=1/a;if(o>e-Xi)c=M_[o-e+Xi-1];else if(o===0)c=0;n.push(c);let l=1/(a-2),u=-l,f=1+l,h=[u,u,f,u,f,f,u,u,f,f,u,f],d=6,g=6,y=3,p=2,m=1,A=new Float32Array(y*g*d),T=new Float32Array(p*g*d),v=new Float32Array(m*g*d);for(let E=0;E<d;E++){let R=E%3*2/3-1,_=E>2?0:-1,S=[R,_,0,R+0.6666666666666666,_,0,R+0.6666666666666666,_+1,0,R,_,0,R+0.6666666666666666,_+1,0,R,_+1,0];A.set(S,y*g*E),T.set(h,p*g*E);let F=[E,E,E,E,E,E];v.set(F,m*g*E)}let w=new tn;if(w.setAttribute("position",new Nt(A,y)),w.setAttribute("uv",new Nt(T,p)),w.setAttribute("faceIndex",new Nt(v,m)),i.push(new pt(w,null)),r>Xi)r--}return{lodMeshes:i,sizeLods:t,sigmas:n}}function T_(e,t,n){let i=new Sn(e,t,n);return i.texture.mapping=Hs,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function as(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function GM(e,t,n){return new Mn({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:zM,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Ja(),fragmentShader:`precision highp float;precision highp int;@@ -3841,7 +3840,7 @@ void main() {gl_FragColor = vec4(prefilteredColor, 1.0);}- `,blending:EJ,depthTest:!1,depthWrite:!1})}function PB($,U,J){let Q=new Float32Array(i0),W=new j(0,1,0);return new yU({name:"SphericalGaussianBlur",defines:{n:i0,CUBEUV_TEXEL_WIDTH:1/U,CUBEUV_TEXEL_HEIGHT:1/J,CUBEUV_MAX_MIP:`${$}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:Q},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:W}},vertexShader:b7(),fragmentShader:`+ `,blending:Yn,depthTest:!1,depthWrite:!1})}function HM(e,t,n){let i=new Float32Array(vr),r=new N(0,1,0);return new Mn({name:"SphericalGaussianBlur",defines:{n:vr,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:Ja(),fragmentShader:`precision mediump float;precision mediump int;@@ -3901,7 +3900,7 @@ void main() {}}- `,blending:EJ,depthTest:!1,depthWrite:!1})}function dk(){return new yU({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:b7(),fragmentShader:`+ `,blending:Yn,depthTest:!1,depthWrite:!1})}function E_(){return new Mn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ja(),fragmentShader:`precision mediump float;precision mediump int;@@ -3920,7 +3919,7 @@ void main() {gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );}- `,blending:EJ,depthTest:!1,depthWrite:!1})}function ck(){return new yU({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:b7(),fragmentShader:`+ `,blending:Yn,depthTest:!1,depthWrite:!1})}function A_(){return new Mn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ja(),fragmentShader:`precision mediump float;precision mediump int;@@ -3936,7 +3935,7 @@ void main() {gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );}- `,blending:EJ,depthTest:!1,depthWrite:!1})}function b7(){return`+ `,blending:Yn,depthTest:!1,depthWrite:!1})}function Ja(){return`precision mediump float;precision mediump int;@@ -3991,7 +3990,7 @@ void main() {gl_Position = vec4( position, 1.0 );}- `}class WZ extends xU{constructor($=1,U={}){super($,$,U);this.isWebGLCubeRenderTarget=!0;let J={width:$,height:$,depth:1},Q=[J,J,J,J,J,J];this.texture=new R7(Q),this._setTextureOptions(U),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture($,U){this.texture.type=U.type,this.texture.colorSpace=U.colorSpace,this.texture.generateMipmaps=U.generateMipmaps,this.texture.minFilter=U.minFilter,this.texture.magFilter=U.magFilter;let J={uniforms:{tEquirect:{value:null}},vertexShader:`+ `}class Ku extends Sn{constructor(e=1,t={}){super(e,e,t);this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new Oa(i),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;@@ -4026,7 +4025,7 @@ void main() {gl_FragColor = texture2D( tEquirect, sampleUV );}- `},Q=new O0(5,5,5),W=new yU({name:"CubemapFromEquirect",uniforms:d0(J.uniforms),vertexShader:J.vertexShader,fragmentShader:J.fragmentShader,side:JU,blending:EJ});W.uniforms.tEquirect.value=U;let K=new P6(Q,W),X=U.minFilter;if(U.minFilter===ZJ)U.minFilter=o6;return new lE(1,10,this).update($,K),U.minFilter=X,K.geometry.dispose(),K.material.dispose(),this}clear($,U=!0,J=!0,Q=!0){let W=$.getRenderTarget();for(let K=0;K<6;K++)$.setRenderTarget(this,K),$.clear(U,J,Q);$.setRenderTarget(W)}}function zB($){let U=new WeakMap,J=new WeakMap,Q=null;function W(E,Z=!1){if(E===null||E===void 0)return null;if(Z)return X(E);return K(E)}function K(E){if(E&&E.isTexture){let Z=E.mapping;if(Z===$7||Z===U7)if(U.has(E)){let D=U.get(E).texture;return N(D,E.mapping)}else{let D=E.image;if(D&&D.height>0){let R=new WZ(D.height);return R.fromEquirectangularTexture($,E),U.set(E,R),E.addEventListener("dispose",Y),N(R.texture,E.mapping)}else return null}}return E}function X(E){if(E&&E.isTexture){let Z=E.mapping,D=Z===$7||Z===U7,R=Z===sW||Z===h0;if(D||R){let I=J.get(E),q=I!==void 0?I.texture.pmremVersion:0;if(E.isRenderTargetTexture&&E.pmremVersion!==q){if(Q===null)Q=new yQ($);return I=D?Q.fromEquirectangular(E,I):Q.fromCubemap(E,I),I.texture.pmremVersion=E.pmremVersion,J.set(E,I),I.texture}else if(I!==void 0)return I.texture;else{let _=E.image;if(D&&_&&_.height>0||R&&_&&H(_)){if(Q===null)Q=new yQ($);return I=D?Q.fromEquirectangular(E):Q.fromCubemap(E),I.texture.pmremVersion=E.pmremVersion,J.set(E,I),E.addEventListener("dispose",G),I.texture}else return null}}}return E}function N(E,Z){if(Z===$7)E.mapping=sW;else if(Z===U7)E.mapping=h0;return E}function H(E){let Z=0,D=6;for(let R=0;R<D;R++)if(E[R]!==void 0)Z++;return Z===D}function Y(E){let Z=E.target;Z.removeEventListener("dispose",Y);let D=U.get(Z);if(D!==void 0)U.delete(Z),D.dispose()}function G(E){let Z=E.target;Z.removeEventListener("dispose",G);let D=J.get(Z);if(D!==void 0)J.delete(Z),D.dispose()}function O(){if(U=new WeakMap,J=new WeakMap,Q!==null)Q.dispose(),Q=null}return{get:W,dispose:O}}function _B($){let U={};function J(Q){if(U[Q]!==void 0)return U[Q];let W=$.getExtension(Q);return U[Q]=W,W}return{has:function(Q){return J(Q)!==null},init:function(){J("EXT_color_buffer_float"),J("WEBGL_clip_cull_distance"),J("OES_texture_float_linear"),J("EXT_color_buffer_half_float"),J("WEBGL_multisampled_render_to_texture"),J("WEBGL_render_shared_exponent")},get:function(Q){let W=J(Q);if(W===null)b0("WebGLRenderer: "+Q+" extension not supported.");return W}}}function AB($,U,J,Q){let W={},K=new WeakMap;function X(O){let E=O.target;if(E.index!==null)U.remove(E.index);for(let D in E.attributes)U.remove(E.attributes[D]);E.removeEventListener("dispose",X),delete W[E.id];let Z=K.get(E);if(Z)U.remove(Z),K.delete(E);if(Q.releaseStatesOfGeometry(E),E.isInstancedBufferGeometry===!0)delete E._maxInstanceCount;J.memory.geometries--}function N(O,E){if(W[E.id]===!0)return E;return E.addEventListener("dispose",X),W[E.id]=!0,J.memory.geometries++,E}function H(O){let E=O.attributes;for(let Z in E)U.update(E[Z],$.ARRAY_BUFFER)}function Y(O){let E=[],Z=O.index,D=O.attributes.position,R=0;if(D===void 0)return;if(Z!==null){let _=Z.array;R=Z.version;for(let P=0,L=_.length;P<L;P+=3){let B=_[P+0],z=_[P+1],A=_[P+2];E.push(B,z,z,A,A,B)}}else{let _=D.array;R=D.version;for(let P=0,L=_.length/3-1;P<L;P+=3){let B=P+0,z=P+1,A=P+2;E.push(B,z,z,A,A,B)}}let I=new(D.count>=65535?D7:q7)(E,1);I.version=R;let q=K.get(O);if(q)U.remove(q);K.set(O,I)}function G(O){let E=K.get(O);if(E){let Z=O.index;if(Z!==null){if(E.version<Z.version)Y(O)}}else Y(O);return K.get(O)}return{get:N,update:H,getWireframeAttribute:G}}function CB($,U,J){let Q;function W(O){Q=O}let K,X;function N(O){K=O.type,X=O.bytesPerElement}function H(O,E){$.drawElements(Q,E,K,O*X),J.update(E,Q,1)}function Y(O,E,Z){if(Z===0)return;$.drawElementsInstanced(Q,E,K,O*X,Z),J.update(E,Q,Z)}function G(O,E,Z){if(Z===0)return;U.get("WEBGL_multi_draw").multiDrawElementsWEBGL(Q,E,0,K,O,0,Z);let R=0;for(let I=0;I<Z;I++)R+=E[I];J.update(R,Q,1)}this.setMode=W,this.setIndex=N,this.render=H,this.renderInstances=Y,this.renderMultiDraw=G}function SB($){let U={geometries:0,textures:0},J={frame:0,calls:0,triangles:0,points:0,lines:0};function Q(K,X,N){switch(J.calls++,X){case $.TRIANGLES:J.triangles+=N*(K/3);break;case $.LINES:J.lines+=N*(K/2);break;case $.LINE_STRIP:J.lines+=N*(K-1);break;case $.LINE_LOOP:J.lines+=N*K;break;case $.POINTS:J.points+=N*K;break;default:y$("WebGLInfo: Unknown draw mode:",X);break}}function W(){J.calls=0,J.triangles=0,J.points=0,J.lines=0}return{memory:U,render:J,programs:null,autoReset:!0,reset:W,update:Q}}function TB($,U,J){let Q=new WeakMap,W=new Z6;function K(X,N,H){let Y=X.morphTargetInfluences,G=N.morphAttributes.position||N.morphAttributes.normal||N.morphAttributes.color,O=G!==void 0?G.length:0,E=Q.get(N);if(E===void 0||E.count!==O){let w=function(){A.dispose(),Q.delete(N),N.removeEventListener("dispose",w)};if(E!==void 0)E.texture.dispose();let Z=N.morphAttributes.position!==void 0,D=N.morphAttributes.normal!==void 0,R=N.morphAttributes.color!==void 0,I=N.morphAttributes.position||[],q=N.morphAttributes.normal||[],_=N.morphAttributes.color||[],P=0;if(Z===!0)P=1;if(D===!0)P=2;if(R===!0)P=3;let L=N.attributes.position.count*P,B=1;if(L>U.maxTextureSize)B=Math.ceil(L/U.maxTextureSize),L=U.maxTextureSize;let z=new Float32Array(L*B*4*O),A=new Z7(z,L,B,O);A.type=jJ,A.needsUpdate=!0;let k=P*4;for(let h=0;h<O;h++){let C=I[h],f=q[h],s=_[h],y=L*B*4*h;for(let d=0;d<C.count;d++){let c=d*k;if(Z===!0)W.fromBufferAttribute(C,d),z[y+c+0]=W.x,z[y+c+1]=W.y,z[y+c+2]=W.z,z[y+c+3]=0;if(D===!0)W.fromBufferAttribute(f,d),z[y+c+4]=W.x,z[y+c+5]=W.y,z[y+c+6]=W.z,z[y+c+7]=0;if(R===!0)W.fromBufferAttribute(s,d),z[y+c+8]=W.x,z[y+c+9]=W.y,z[y+c+10]=W.z,z[y+c+11]=s.itemSize===4?W.w:1}}E={count:O,texture:A,size:new g$(L,B)},Q.set(N,E),N.addEventListener("dispose",w)}if(X.isInstancedMesh===!0&&X.morphTexture!==null)H.getUniforms().setValue($,"morphTexture",X.morphTexture,J);else{let Z=0;for(let R=0;R<Y.length;R++)Z+=Y[R];let D=N.morphTargetsRelative?1:1-Z;H.getUniforms().setValue($,"morphTargetBaseInfluence",D),H.getUniforms().setValue($,"morphTargetInfluences",Y)}H.getUniforms().setValue($,"morphTargetsTexture",E.texture,J),H.getUniforms().setValue($,"morphTargetsTextureSize",E.size)}return{update:K}}function vB($,U,J,Q,W){let K=new WeakMap;function X(Y){let G=W.render.frame,O=Y.geometry,E=U.get(Y,O);if(K.get(E)!==G)U.update(E),K.set(E,G);if(Y.isInstancedMesh){if(Y.hasEventListener("dispose",H)===!1)Y.addEventListener("dispose",H);if(K.get(Y)!==G){if(J.update(Y.instanceMatrix,$.ARRAY_BUFFER),Y.instanceColor!==null)J.update(Y.instanceColor,$.ARRAY_BUFFER);K.set(Y,G)}}if(Y.isSkinnedMesh){let Z=Y.skeleton;if(K.get(Z)!==G)Z.update(),K.set(Z,G)}return E}function N(){K=new WeakMap}function H(Y){let G=Y.target;if(G.removeEventListener("dispose",H),Q.releaseStatesOfObject(G),J.remove(G.instanceMatrix),G.instanceColor!==null)J.remove(G.instanceColor)}return{update:X,dispose:N}}var jB={[jO]:"LINEAR_TONE_MAPPING",[gO]:"REINHARD_TONE_MAPPING",[bO]:"CINEON_TONE_MAPPING",[qQ]:"ACES_FILMIC_TONE_MAPPING",[yO]:"AGX_TONE_MAPPING",[hO]:"NEUTRAL_TONE_MAPPING",[xO]:"CUSTOM_TONE_MAPPING"};function gB($,U,J,Q,W,K){let X=new xU(U,J,{type:$,depthBuffer:W,stencilBuffer:K,samples:Q?4:0,depthTexture:W?new G0(U,J):void 0}),N=new xU(U,J,{type:gJ,depthBuffer:!1,stencilBuffer:!1}),H=new OU;H.setAttribute("position",new qU([-1,3,0,-1,-1,0,3,-1,0],3)),H.setAttribute("uv",new qU([0,2,0,0,2,0],2));let Y=new jE({uniforms:{tDiffuse:{value:null}},vertexShader:`+ `},i=new Gi(5,5,5),r=new Mn({name:"CubemapFromEquirect",uniforms:gr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Yt,blending:Yn});r.uniforms.tEquirect.value=t;let s=new pt(i,r),o=t.minFilter;if(t.minFilter===jn)t.minFilter=Gt;return new Ou(1,10,this).update(e,s),t.minFilter=o,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){let r=e.getRenderTarget();for(let s=0;s<6;s++)e.setRenderTarget(this,s),e.clear(t,n,i);e.setRenderTarget(r)}}function VM(e){let t=new WeakMap,n=new WeakMap,i=null;function r(h,d=!1){if(h===null||h===void 0)return null;if(d)return o(h);return s(h)}function s(h){if(h&&h.isTexture){let d=h.mapping;if(d===ga||d===_a)if(t.has(h)){let g=t.get(h).texture;return a(g,h.mapping)}else{let g=h.image;if(g&&g.height>0){let y=new Ku(g.height);return y.fromEquirectangularTexture(e,h),t.set(h,y),h.addEventListener("dispose",l),a(y.texture,h.mapping)}else return null}}return h}function o(h){if(h&&h.isTexture){let d=h.mapping,g=d===ga||d===_a,y=d===qr||d===ur;if(g||y){let p=n.get(h),m=p!==void 0?p.texture.pmremVersion:0;if(h.isRenderTargetTexture&&h.pmremVersion!==m){if(i===null)i=new lo(e);return p=g?i.fromEquirectangular(h,p):i.fromCubemap(h,p),p.texture.pmremVersion=h.pmremVersion,n.set(h,p),p.texture}else if(p!==void 0)return p.texture;else{let A=h.image;if(g&&A&&A.height>0||y&&A&&c(A)){if(i===null)i=new lo(e);return p=g?i.fromEquirectangular(h):i.fromCubemap(h),p.texture.pmremVersion=h.pmremVersion,n.set(h,p),h.addEventListener("dispose",u),p.texture}else return null}}}return h}function a(h,d){if(d===ga)h.mapping=qr;else if(d===_a)h.mapping=ur;return h}function c(h){let d=0,g=6;for(let y=0;y<g;y++)if(h[y]!==void 0)d++;return d===g}function l(h){let d=h.target;d.removeEventListener("dispose",l);let g=t.get(d);if(g!==void 0)t.delete(d),g.dispose()}function u(h){let d=h.target;d.removeEventListener("dispose",u);let g=n.get(d);if(g!==void 0)n.delete(d),g.dispose()}function f(){if(t=new WeakMap,n=new WeakMap,i!==null)i.dispose(),i=null}return{get:r,dispose:f}}function WM(e){let t={};function n(i){if(t[i]!==void 0)return t[i];let r=e.getExtension(i);return t[i]=r,r}return{has:function(i){return n(i)!==null},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(i){let r=n(i);if(r===null)ar("WebGLRenderer: "+i+" extension not supported.");return r}}}function $M(e,t,n,i){let r={},s=new WeakMap;function o(f){let h=f.target;if(h.index!==null)t.remove(h.index);for(let g in h.attributes)t.remove(h.attributes[g]);h.removeEventListener("dispose",o),delete r[h.id];let d=s.get(h);if(d)t.remove(d),s.delete(h);if(i.releaseStatesOfGeometry(h),h.isInstancedBufferGeometry===!0)delete h._maxInstanceCount;n.memory.geometries--}function a(f,h){if(r[h.id]===!0)return h;return h.addEventListener("dispose",o),r[h.id]=!0,n.memory.geometries++,h}function c(f){let h=f.attributes;for(let d in h)t.update(h[d],e.ARRAY_BUFFER)}function l(f){let h=[],d=f.index,g=f.attributes.position,y=0;if(g===void 0)return;if(d!==null){let A=d.array;y=d.version;for(let T=0,v=A.length;T<v;T+=3){let w=A[T+0],E=A[T+1],R=A[T+2];h.push(w,E,E,R,R,w)}}else{let A=g.array;y=g.version;for(let T=0,v=A.length/3-1;T<v;T+=3){let w=T+0,E=T+1,R=T+2;h.push(w,E,E,R,R,w)}}let p=new(g.count>=65535?La:Pa)(h,1);p.version=y;let m=s.get(f);if(m)t.remove(m);s.set(f,p)}function u(f){let h=s.get(f);if(h){let d=f.index;if(d!==null){if(h.version<d.version)l(f)}}else l(f);return s.get(f)}return{get:a,update:c,getWireframeAttribute:u}}function ZM(e,t,n){let i;function r(f){i=f}let s,o;function a(f){s=f.type,o=f.bytesPerElement}function c(f,h){e.drawElements(i,h,s,f*o),n.update(h,i,1)}function l(f,h,d){if(d===0)return;e.drawElementsInstanced(i,h,s,f*o,d),n.update(h,i,d)}function u(f,h,d){if(d===0)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,h,0,s,f,0,d);let y=0;for(let p=0;p<d;p++)y+=h[p];n.update(y,i,1)}this.setMode=r,this.setIndex=a,this.render=c,this.renderInstances=l,this.renderMultiDraw=u}function XM(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function i(s,o,a){switch(n.calls++,o){case e.TRIANGLES:n.triangles+=a*(s/3);break;case e.LINES:n.lines+=a*(s/2);break;case e.LINE_STRIP:n.lines+=a*(s-1);break;case e.LINE_LOOP:n.lines+=a*s;break;case e.POINTS:n.points+=a*s;break;default:Ne("WebGLInfo: Unknown draw mode:",o);break}}function r(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:t,render:n,programs:null,autoReset:!0,reset:r,update:i}}function qM(e,t,n){let i=new WeakMap,r=new st;function s(o,a,c){let l=o.morphTargetInfluences,u=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,f=u!==void 0?u.length:0,h=i.get(a);if(h===void 0||h.count!==f){let S=function(){R.dispose(),i.delete(a),a.removeEventListener("dispose",S)};if(h!==void 0)h.texture.dispose();let d=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,y=a.morphAttributes.color!==void 0,p=a.morphAttributes.position||[],m=a.morphAttributes.normal||[],A=a.morphAttributes.color||[],T=0;if(d===!0)T=1;if(g===!0)T=2;if(y===!0)T=3;let v=a.attributes.position.count*T,w=1;if(v>t.maxTextureSize)w=Math.ceil(v/t.maxTextureSize),v=t.maxTextureSize;let E=new Float32Array(v*w*4*f),R=new Ca(E,v,w,f);R.type=di,R.needsUpdate=!0;let _=T*4;for(let F=0;F<f;F++){let C=p[F],z=m[F],J=A[F],O=v*w*4*F;for(let H=0;H<C.count;H++){let V=H*_;if(d===!0)r.fromBufferAttribute(C,H),E[O+V+0]=r.x,E[O+V+1]=r.y,E[O+V+2]=r.z,E[O+V+3]=0;if(g===!0)r.fromBufferAttribute(z,H),E[O+V+4]=r.x,E[O+V+5]=r.y,E[O+V+6]=r.z,E[O+V+7]=0;if(y===!0)r.fromBufferAttribute(J,H),E[O+V+8]=r.x,E[O+V+9]=r.y,E[O+V+10]=r.z,E[O+V+11]=J.itemSize===4?r.w:1}}h={count:f,texture:R,size:new Ie(v,w)},i.set(a,h),a.addEventListener("dispose",S)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(e,"morphTexture",o.morphTexture,n);else{let d=0;for(let y=0;y<l.length;y++)d+=l[y];let g=a.morphTargetsRelative?1:1-d;c.getUniforms().setValue(e,"morphTargetBaseInfluence",g),c.getUniforms().setValue(e,"morphTargetInfluences",l)}c.getUniforms().setValue(e,"morphTargetsTexture",h.texture,n),c.getUniforms().setValue(e,"morphTargetsTextureSize",h.size)}return{update:s}}function YM(e,t,n,i,r){let s=new WeakMap;function o(l){let u=r.render.frame,f=l.geometry,h=t.get(l,f);if(s.get(h)!==u)t.update(h),s.set(h,u);if(l.isInstancedMesh){if(l.hasEventListener("dispose",c)===!1)l.addEventListener("dispose",c);if(s.get(l)!==u){if(n.update(l.instanceMatrix,e.ARRAY_BUFFER),l.instanceColor!==null)n.update(l.instanceColor,e.ARRAY_BUFFER);s.set(l,u)}}if(l.isSkinnedMesh){let d=l.skeleton;if(s.get(d)!==u)d.update(),s.set(d,u)}return h}function a(){s=new WeakMap}function c(l){let u=l.target;if(u.removeEventListener("dispose",c),i.releaseStatesOfObject(u),n.remove(u.instanceMatrix),u.instanceColor!==null)n.remove(u.instanceColor)}return{update:o,dispose:a}}var jM={[Rl]:"LINEAR_TONE_MAPPING",[Cl]:"REINHARD_TONE_MAPPING",[Il]:"CINEON_TONE_MAPPING",[Gs]:"ACES_FILMIC_TONE_MAPPING",[Ll]:"AGX_TONE_MAPPING",[Nl]:"NEUTRAL_TONE_MAPPING",[Pl]:"CUSTOM_TONE_MAPPING"};function JM(e,t,n,i,r,s){let o=new Sn(t,n,{type:e,depthBuffer:r,stencilBuffer:s,samples:i?4:0,depthTexture:r?new Bi(t,n):void 0}),a=new Sn(t,n,{type:pi,depthBuffer:!1,stencilBuffer:!1}),c=new tn;c.setAttribute("position",new nn([-1,3,0,-1,-1,0,3,-1,0],3)),c.setAttribute("uv",new nn([0,2,0,0,2,0],2));let l=new Ru({uniforms:{tDiffuse:{value:null}},vertexShader:`precision highp float;uniform mat4 modelViewMatrix;@@ -4072,60 +4071,60 @@ void main() {#ifdef SRGB_TRANSFERgl_FragColor = sRGBTransferOETF( gl_FragColor );#endif- }`,depthTest:!1,depthWrite:!1}),G=new P6(H,Y),O=new n0(-1,1,1,-1,0,1),E=null,Z=null,D=!1,R,I=null,q=[],_=!1;this.setSize=function(P,L){X.setSize(P,L),N.setSize(P,L);for(let B=0;B<q.length;B++){let z=q[B];if(z.setSize)z.setSize(P,L)}},this.setEffects=function(P){q=P,_=q.length>0&&q[0].isRenderPass===!0;let{width:L,height:B}=X;for(let z=0;z<q.length;z++){let A=q[z];if(A.setSize)A.setSize(L,B)}},this.begin=function(P,L){if(D)return!1;if(P.toneMapping===oU&&q.length===0)return!1;if(I=L,L!==null){let{width:B,height:z}=L;if(X.width!==B||X.height!==z)this.setSize(B,z)}if(_===!1)P.setRenderTarget(X);return R=P.toneMapping,P.toneMapping=oU,!0},this.hasRenderPass=function(){return _},this.end=function(P,L){P.toneMapping=R,D=!0;let B=X,z=N;for(let A=0;A<q.length;A++){let k=q[A];if(k.enabled===!1)continue;if(k.render(P,z,B,L),k.needsSwap!==!1){let w=B;B=z,z=w}}if(E!==P.outputColorSpace||Z!==P.toneMapping){if(E=P.outputColorSpace,Z=P.toneMapping,Y.defines={},s$.getTransfer(E)===w6)Y.defines.SRGB_TRANSFER="";let A=jB[Z];if(A)Y.defines[A]="";Y.needsUpdate=!0}Y.uniforms.tDiffuse.value=B.texture,P.setRenderTarget(I),P.render(G,O),I=null,D=!1},this.isCompositing=function(){return D},this.dispose=function(){if(X.depthTexture)X.depthTexture.dispose();X.dispose(),N.dispose(),H.dispose(),Y.dispose()}}var O5=new v6,UZ=new G0(1,1),E5=new Z7,Z5=new SE,I5=new R7,nk=[],ik=[],ok=new Float32Array(16),rk=new Float32Array(9),ak=new Float32Array(4);function O8($,U,J){let Q=$[0];if(Q<=0||Q>0)return $;let W=U*J,K=nk[W];if(K===void 0)K=new Float32Array(W),nk[W]=K;if(U!==0){Q.toArray(K,0);for(let X=1,N=0;X!==U;++X)N+=J,$[X].toArray(K,N)}return K}function l6($,U){if($.length!==U.length)return!1;for(let J=0,Q=$.length;J<Q;J++)if($[J]!==U[J])return!1;return!0}function m6($,U){for(let J=0,Q=U.length;J<Q;J++)$[J]=U[J]}function x7($,U){let J=ik[U];if(J===void 0)J=new Int32Array(U),ik[U]=J;for(let Q=0;Q!==U;++Q)J[Q]=$.allocateTextureUnit();return J}function bB($,U){let J=this.cache;if(J[0]===U)return;$.uniform1f(this.addr,U),J[0]=U}function xB($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y)$.uniform2f(this.addr,U.x,U.y),J[0]=U.x,J[1]=U.y}else{if(l6(J,U))return;$.uniform2fv(this.addr,U),m6(J,U)}}function yB($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z)$.uniform3f(this.addr,U.x,U.y,U.z),J[0]=U.x,J[1]=U.y,J[2]=U.z}else if(U.r!==void 0){if(J[0]!==U.r||J[1]!==U.g||J[2]!==U.b)$.uniform3f(this.addr,U.r,U.g,U.b),J[0]=U.r,J[1]=U.g,J[2]=U.b}else{if(l6(J,U))return;$.uniform3fv(this.addr,U),m6(J,U)}}function hB($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z||J[3]!==U.w)$.uniform4f(this.addr,U.x,U.y,U.z,U.w),J[0]=U.x,J[1]=U.y,J[2]=U.z,J[3]=U.w}else{if(l6(J,U))return;$.uniform4fv(this.addr,U),m6(J,U)}}function fB($,U){let J=this.cache,Q=U.elements;if(Q===void 0){if(l6(J,U))return;$.uniformMatrix2fv(this.addr,!1,U),m6(J,U)}else{if(l6(J,Q))return;ak.set(Q),$.uniformMatrix2fv(this.addr,!1,ak),m6(J,Q)}}function uB($,U){let J=this.cache,Q=U.elements;if(Q===void 0){if(l6(J,U))return;$.uniformMatrix3fv(this.addr,!1,U),m6(J,U)}else{if(l6(J,Q))return;rk.set(Q),$.uniformMatrix3fv(this.addr,!1,rk),m6(J,Q)}}function lB($,U){let J=this.cache,Q=U.elements;if(Q===void 0){if(l6(J,U))return;$.uniformMatrix4fv(this.addr,!1,U),m6(J,U)}else{if(l6(J,Q))return;ok.set(Q),$.uniformMatrix4fv(this.addr,!1,ok),m6(J,Q)}}function mB($,U){let J=this.cache;if(J[0]===U)return;$.uniform1i(this.addr,U),J[0]=U}function pB($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y)$.uniform2i(this.addr,U.x,U.y),J[0]=U.x,J[1]=U.y}else{if(l6(J,U))return;$.uniform2iv(this.addr,U),m6(J,U)}}function dB($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z)$.uniform3i(this.addr,U.x,U.y,U.z),J[0]=U.x,J[1]=U.y,J[2]=U.z}else{if(l6(J,U))return;$.uniform3iv(this.addr,U),m6(J,U)}}function cB($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z||J[3]!==U.w)$.uniform4i(this.addr,U.x,U.y,U.z,U.w),J[0]=U.x,J[1]=U.y,J[2]=U.z,J[3]=U.w}else{if(l6(J,U))return;$.uniform4iv(this.addr,U),m6(J,U)}}function nB($,U){let J=this.cache;if(J[0]===U)return;$.uniform1ui(this.addr,U),J[0]=U}function iB($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y)$.uniform2ui(this.addr,U.x,U.y),J[0]=U.x,J[1]=U.y}else{if(l6(J,U))return;$.uniform2uiv(this.addr,U),m6(J,U)}}function oB($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z)$.uniform3ui(this.addr,U.x,U.y,U.z),J[0]=U.x,J[1]=U.y,J[2]=U.z}else{if(l6(J,U))return;$.uniform3uiv(this.addr,U),m6(J,U)}}function rB($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z||J[3]!==U.w)$.uniform4ui(this.addr,U.x,U.y,U.z,U.w),J[0]=U.x,J[1]=U.y,J[2]=U.z,J[3]=U.w}else{if(l6(J,U))return;$.uniform4uiv(this.addr,U),m6(J,U)}}function aB($,U,J){let Q=this.cache,W=J.allocateTextureUnit();if(Q[0]!==W)$.uniform1i(this.addr,W),Q[0]=W;let K;if(this.type===$.SAMPLER_2D_SHADOW)UZ.compareFunction=J.isReversedDepthBuffer()?E7:O7,K=UZ;else K=O5;J.setTexture2D(U||K,W)}function sB($,U,J){let Q=this.cache,W=J.allocateTextureUnit();if(Q[0]!==W)$.uniform1i(this.addr,W),Q[0]=W;J.setTexture3D(U||Z5,W)}function tB($,U,J){let Q=this.cache,W=J.allocateTextureUnit();if(Q[0]!==W)$.uniform1i(this.addr,W),Q[0]=W;J.setTextureCube(U||I5,W)}function eB($,U,J){let Q=this.cache,W=J.allocateTextureUnit();if(Q[0]!==W)$.uniform1i(this.addr,W),Q[0]=W;J.setTexture2DArray(U||E5,W)}function $P($){switch($){case 5126:return bB;case 35664:return xB;case 35665:return yB;case 35666:return hB;case 35674:return fB;case 35675:return uB;case 35676:return lB;case 5124:case 35670:return mB;case 35667:case 35671:return pB;case 35668:case 35672:return dB;case 35669:case 35673:return cB;case 5125:return nB;case 36294:return iB;case 36295:return oB;case 36296:return rB;case 35678:case 36198:case 36298:case 36306:case 35682:return aB;case 35679:case 36299:case 36307:return sB;case 35680:case 36300:case 36308:case 36293:return tB;case 36289:case 36303:case 36311:case 36292:return eB}}function UP($,U){$.uniform1fv(this.addr,U)}function JP($,U){let J=O8(U,this.size,2);$.uniform2fv(this.addr,J)}function WP($,U){let J=O8(U,this.size,3);$.uniform3fv(this.addr,J)}function QP($,U){let J=O8(U,this.size,4);$.uniform4fv(this.addr,J)}function KP($,U){let J=O8(U,this.size,4);$.uniformMatrix2fv(this.addr,!1,J)}function XP($,U){let J=O8(U,this.size,9);$.uniformMatrix3fv(this.addr,!1,J)}function NP($,U){let J=O8(U,this.size,16);$.uniformMatrix4fv(this.addr,!1,J)}function HP($,U){$.uniform1iv(this.addr,U)}function YP($,U){$.uniform2iv(this.addr,U)}function GP($,U){$.uniform3iv(this.addr,U)}function OP($,U){$.uniform4iv(this.addr,U)}function EP($,U){$.uniform1uiv(this.addr,U)}function ZP($,U){$.uniform2uiv(this.addr,U)}function IP($,U){$.uniform3uiv(this.addr,U)}function qP($,U){$.uniform4uiv(this.addr,U)}function DP($,U,J){let Q=this.cache,W=U.length,K=x7(J,W);if(!l6(Q,K))$.uniform1iv(this.addr,K),m6(Q,K);let X;if(this.type===$.SAMPLER_2D_SHADOW)X=UZ;else X=O5;for(let N=0;N!==W;++N)J.setTexture2D(U[N]||X,K[N])}function kP($,U,J){let Q=this.cache,W=U.length,K=x7(J,W);if(!l6(Q,K))$.uniform1iv(this.addr,K),m6(Q,K);for(let X=0;X!==W;++X)J.setTexture3D(U[X]||Z5,K[X])}function FP($,U,J){let Q=this.cache,W=U.length,K=x7(J,W);if(!l6(Q,K))$.uniform1iv(this.addr,K),m6(Q,K);for(let X=0;X!==W;++X)J.setTextureCube(U[X]||I5,K[X])}function LP($,U,J){let Q=this.cache,W=U.length,K=x7(J,W);if(!l6(Q,K))$.uniform1iv(this.addr,K),m6(Q,K);for(let X=0;X!==W;++X)J.setTexture2DArray(U[X]||E5,K[X])}function RP($){switch($){case 5126:return UP;case 35664:return JP;case 35665:return WP;case 35666:return QP;case 35674:return KP;case 35675:return XP;case 35676:return NP;case 5124:case 35670:return HP;case 35667:case 35671:return YP;case 35668:case 35672:return GP;case 35669:case 35673:return OP;case 5125:return EP;case 36294:return ZP;case 36295:return IP;case 36296:return qP;case 35678:case 36198:case 36298:case 36306:case 35682:return DP;case 35679:case 36299:case 36307:return kP;case 35680:case 36300:case 36308:case 36293:return FP;case 36289:case 36303:case 36311:case 36292:return LP}}class q5{constructor($,U,J){this.id=$,this.addr=J,this.cache=[],this.type=U.type,this.setValue=$P(U.type)}}class D5{constructor($,U,J){this.id=$,this.addr=J,this.cache=[],this.type=U.type,this.size=U.size,this.setValue=RP(U.type)}}class k5{constructor($){this.id=$,this.seq=[],this.map={}}setValue($,U,J){let Q=this.seq;for(let W=0,K=Q.length;W!==K;++W){let X=Q[W];X.setValue($,U[X.id],J)}}}var eE=/(\w+)(\])?(\[|\.)?/g;function sk($,U){$.seq.push(U),$.map[U.id]=U}function VP($,U,J){let Q=$.name,W=Q.length;eE.lastIndex=0;while(!0){let K=eE.exec(Q),X=eE.lastIndex,N=K[1],H=K[2]==="]",Y=K[3];if(H)N=N|0;if(Y===void 0||Y==="["&&X+2===W){sk(J,Y===void 0?new q5(N,$,U):new D5(N,$,U));break}else{let O=J.map[N];if(O===void 0)O=new k5(N),sk(J,O);J=O}}}class xQ{constructor($,U){this.seq=[],this.map={};let J=$.getProgramParameter(U,$.ACTIVE_UNIFORMS);for(let K=0;K<J;++K){let X=$.getActiveUniform(U,K),N=$.getUniformLocation(U,X.name);VP(X,N,this)}let Q=[],W=[];for(let K of this.seq)if(K.type===$.SAMPLER_2D_SHADOW||K.type===$.SAMPLER_CUBE_SHADOW||K.type===$.SAMPLER_2D_ARRAY_SHADOW)Q.push(K);else W.push(K);if(Q.length>0)this.seq=Q.concat(W)}setValue($,U,J,Q){let W=this.map[U];if(W!==void 0)W.setValue($,J,Q)}setOptional($,U,J){let Q=U[J];if(Q!==void 0)this.setValue($,J,Q)}static upload($,U,J,Q){for(let W=0,K=U.length;W!==K;++W){let X=U[W],N=J[X.id];if(N.needsUpdate!==!1)X.setValue($,N.value,Q)}}static seqWithValue($,U){let J=[];for(let Q=0,W=$.length;Q!==W;++Q){let K=$[Q];if(K.id in U)J.push(K)}return J}}function tk($,U,J){let Q=$.createShader(U);return $.shaderSource(Q,J),$.compileShader(Q),Q}var wP=37297,MP=0;function BP($,U){let J=$.split(`-`),Q=[],W=Math.max(U-6,0),K=Math.min(U+6,J.length);for(let X=W;X<K;X++){let N=X+1;Q.push(`${N===U?">":" "} ${N}: ${J[X]}`)}return Q.join(`-`)}var ek=new u$;function PP($){s$._getMatrix(ek,s$.workingColorSpace,$);let U=`mat3( ${ek.elements.map((J)=>J.toFixed(4))} )`;switch(s$.getTransfer($)){case BE:return[U,"LinearTransferOETF"];case w6:return[U,"sRGBTransferOETF"];default:return A$("WebGLProgram: Unsupported color space: ",$),[U,"LinearTransferOETF"]}}function $5($,U,J){let Q=$.getShaderParameter(U,$.COMPILE_STATUS),K=($.getShaderInfoLog(U)||"").trim();if(Q&&K==="")return"";let X=/ERROR: 0:(\d+)/.exec(K);if(X){let N=parseInt(X[1]);return J.toUpperCase()+`--`+K+`--`+BP($.getShaderSource(U),N)}else return K}function zP($,U){let J=PP(U);return[`vec4 ${$}( vec4 value ) {`,` return ${J[1]}( vec4( value.rgb * ${J[0]}, value.a ) );`,"}"].join(`-`)}var _P={[jO]:"Linear",[gO]:"Reinhard",[bO]:"Cineon",[qQ]:"ACESFilmic",[yO]:"AgX",[hO]:"Neutral",[xO]:"Custom"};function AP($,U){let J=_P[U];if(J===void 0)return A$("WebGLProgram: Unsupported toneMapping:",U),"vec3 "+$+"( vec3 color ) { return LinearToneMapping( color ); }";return"vec3 "+$+"( vec3 color ) { return "+J+"ToneMapping( color ); }"}var g7=new j;function CP(){s$.getLuminanceCoefficients(g7);let $=g7.x.toFixed(4),U=g7.y.toFixed(4),J=g7.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${$}, ${U}, ${J} );`,"\treturn dot( weights, rgb );","}"].join(`-`)}function SP($){return[$.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",$.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(bQ).join(`-`)}function TP($){let U=[];for(let J in $){let Q=$[J];if(Q===!1)continue;U.push("#define "+J+" "+Q)}return U.join(`-`)}function vP($,U){let J={},Q=$.getProgramParameter(U,$.ACTIVE_ATTRIBUTES);for(let W=0;W<Q;W++){let K=$.getActiveAttrib(U,W),X=K.name,N=1;if(K.type===$.FLOAT_MAT2)N=2;if(K.type===$.FLOAT_MAT3)N=3;if(K.type===$.FLOAT_MAT4)N=4;J[X]={type:K.type,location:$.getAttribLocation(U,X),locationSize:N}}return J}function bQ($){return $!==""}function U5($,U){let J=U.numSpotLightShadows+U.numSpotLightMaps-U.numSpotLightShadowsWithMaps;return $.replace(/NUM_DIR_LIGHTS/g,U.numDirLights).replace(/NUM_SPOT_LIGHTS/g,U.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,U.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,J).replace(/NUM_RECT_AREA_LIGHTS/g,U.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,U.numPointLights).replace(/NUM_HEMI_LIGHTS/g,U.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,U.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,U.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,U.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,U.numPointLightShadows)}function J5($,U){return $.replace(/NUM_CLIPPING_PLANES/g,U.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,U.numClippingPlanes-U.numClipIntersection)}var jP=/^[ \t]*#include +<([\w\d./]+)>/gm;function JZ($){return $.replace(jP,bP)}var gP=new Map;function bP($,U){let J=o$[U];if(J===void 0){let Q=gP.get(U);if(Q!==void 0)J=o$[Q],A$('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',U,Q);else throw Error("THREE.WebGLProgram: Can not resolve #include <"+U+">")}return JZ(J)}var xP=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function W5($){return $.replace(xP,yP)}function yP($,U,J,Q){let W="";for(let K=parseInt(U);K<parseInt(J);K++)W+=Q.replace(/\[\s*i\s*\]/g,"[ "+K+" ]").replace(/UNROLLED_LOOP_INDEX/g,K);return W}function Q5($){let U=`precision ${$.precision} float;- precision ${$.precision} int;- precision ${$.precision} sampler2D;- precision ${$.precision} samplerCube;- precision ${$.precision} sampler3D;- precision ${$.precision} sampler2DArray;- precision ${$.precision} sampler2DShadow;- precision ${$.precision} samplerCubeShadow;- precision ${$.precision} sampler2DArrayShadow;- precision ${$.precision} isampler2D;- precision ${$.precision} isampler3D;- precision ${$.precision} isamplerCube;- precision ${$.precision} isampler2DArray;- precision ${$.precision} usampler2D;- precision ${$.precision} usampler3D;- precision ${$.precision} usamplerCube;- precision ${$.precision} usampler2DArray;- `;if($.precision==="highp")U+=`-#define HIGH_PRECISION`;else if($.precision==="mediump")U+=`-#define MEDIUM_PRECISION`;else if($.precision==="lowp")U+=`-#define LOW_PRECISION`;return U}var hP={[ZQ]:"SHADOWMAP_TYPE_PCF",[rW]:"SHADOWMAP_TYPE_VSM"};function fP($){return hP[$.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}var uP={[sW]:"ENVMAP_TYPE_CUBE",[h0]:"ENVMAP_TYPE_CUBE",[DQ]:"ENVMAP_TYPE_CUBE_UV"};function lP($){if($.envMap===!1)return"ENVMAP_TYPE_CUBE";return uP[$.envMapMode]||"ENVMAP_TYPE_CUBE"}var mP={[h0]:"ENVMAP_MODE_REFRACTION"};function pP($){if($.envMap===!1)return"ENVMAP_MODE_REFLECTION";return mP[$.envMapMode]||"ENVMAP_MODE_REFLECTION"}var dP={[Ek]:"ENVMAP_BLENDING_MULTIPLY",[Zk]:"ENVMAP_BLENDING_MIX",[Ik]:"ENVMAP_BLENDING_ADD"};function cP($){if($.envMap===!1)return"ENVMAP_BLENDING_NONE";return dP[$.combine]||"ENVMAP_BLENDING_NONE"}function nP($){let U=$.envMapCubeUVHeight;if(U===null)return null;let J=Math.log2(U)-2,Q=1/U;return{texelWidth:1/(3*Math.max(Math.pow(2,J),112)),texelHeight:Q,maxMip:J}}function iP($,U,J,Q){let W=$.getContext(),K=J.defines,X=J.vertexShader,N=J.fragmentShader,H=fP(J),Y=lP(J),G=pP(J),O=cP(J),E=nP(J),Z=SP(J),D=TP(K),R=W.createProgram(),I,q,_=J.glslVersion?"#version "+J.glslVersion+`-`:"";if(J.isRawShaderMaterial){if(I=["#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,D].filter(bQ).join(`-`),I.length>0)I+=`-`;if(q=["#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,D].filter(bQ).join(`-`),q.length>0)q+=`-`}else I=[Q5(J),"#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,D,J.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",J.batching?"#define USE_BATCHING":"",J.batchingColor?"#define USE_BATCHING_COLOR":"",J.instancing?"#define USE_INSTANCING":"",J.instancingColor?"#define USE_INSTANCING_COLOR":"",J.instancingMorph?"#define USE_INSTANCING_MORPH":"",J.useFog&&J.fog?"#define USE_FOG":"",J.useFog&&J.fogExp2?"#define FOG_EXP2":"",J.map?"#define USE_MAP":"",J.envMap?"#define USE_ENVMAP":"",J.envMap?"#define "+G:"",J.lightMap?"#define USE_LIGHTMAP":"",J.aoMap?"#define USE_AOMAP":"",J.bumpMap?"#define USE_BUMPMAP":"",J.normalMap?"#define USE_NORMALMAP":"",J.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",J.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",J.displacementMap?"#define USE_DISPLACEMENTMAP":"",J.emissiveMap?"#define USE_EMISSIVEMAP":"",J.anisotropy?"#define USE_ANISOTROPY":"",J.anisotropyMap?"#define USE_ANISOTROPYMAP":"",J.clearcoatMap?"#define USE_CLEARCOATMAP":"",J.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",J.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",J.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",J.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",J.specularMap?"#define USE_SPECULARMAP":"",J.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",J.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",J.roughnessMap?"#define USE_ROUGHNESSMAP":"",J.metalnessMap?"#define USE_METALNESSMAP":"",J.alphaMap?"#define USE_ALPHAMAP":"",J.alphaHash?"#define USE_ALPHAHASH":"",J.transmission?"#define USE_TRANSMISSION":"",J.transmissionMap?"#define USE_TRANSMISSIONMAP":"",J.thicknessMap?"#define USE_THICKNESSMAP":"",J.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",J.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",J.mapUv?"#define MAP_UV "+J.mapUv:"",J.alphaMapUv?"#define ALPHAMAP_UV "+J.alphaMapUv:"",J.lightMapUv?"#define LIGHTMAP_UV "+J.lightMapUv:"",J.aoMapUv?"#define AOMAP_UV "+J.aoMapUv:"",J.emissiveMapUv?"#define EMISSIVEMAP_UV "+J.emissiveMapUv:"",J.bumpMapUv?"#define BUMPMAP_UV "+J.bumpMapUv:"",J.normalMapUv?"#define NORMALMAP_UV "+J.normalMapUv:"",J.displacementMapUv?"#define DISPLACEMENTMAP_UV "+J.displacementMapUv:"",J.metalnessMapUv?"#define METALNESSMAP_UV "+J.metalnessMapUv:"",J.roughnessMapUv?"#define ROUGHNESSMAP_UV "+J.roughnessMapUv:"",J.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+J.anisotropyMapUv:"",J.clearcoatMapUv?"#define CLEARCOATMAP_UV "+J.clearcoatMapUv:"",J.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+J.clearcoatNormalMapUv:"",J.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+J.clearcoatRoughnessMapUv:"",J.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+J.iridescenceMapUv:"",J.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+J.iridescenceThicknessMapUv:"",J.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+J.sheenColorMapUv:"",J.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+J.sheenRoughnessMapUv:"",J.specularMapUv?"#define SPECULARMAP_UV "+J.specularMapUv:"",J.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+J.specularColorMapUv:"",J.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+J.specularIntensityMapUv:"",J.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+J.transmissionMapUv:"",J.thicknessMapUv?"#define THICKNESSMAP_UV "+J.thicknessMapUv:"",J.vertexTangents&&J.flatShading===!1?"#define USE_TANGENT":"",J.vertexNormals?"#define HAS_NORMAL":"",J.vertexColors?"#define USE_COLOR":"",J.vertexAlphas?"#define USE_COLOR_ALPHA":"",J.vertexUv1s?"#define USE_UV1":"",J.vertexUv2s?"#define USE_UV2":"",J.vertexUv3s?"#define USE_UV3":"",J.pointsUvs?"#define USE_POINTS_UV":"",J.flatShading?"#define FLAT_SHADED":"",J.skinning?"#define USE_SKINNING":"",J.morphTargets?"#define USE_MORPHTARGETS":"",J.morphNormals&&J.flatShading===!1?"#define USE_MORPHNORMALS":"",J.morphColors?"#define USE_MORPHCOLORS":"",J.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+J.morphTextureStride:"",J.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+J.morphTargetsCount:"",J.doubleSided?"#define DOUBLE_SIDED":"",J.flipSided?"#define FLIP_SIDED":"",J.shadowMapEnabled?"#define USE_SHADOWMAP":"",J.shadowMapEnabled?"#define "+H:"",J.sizeAttenuation?"#define USE_SIZEATTENUATION":"",J.numLightProbes>0?"#define USE_LIGHT_PROBES":"",J.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",J.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","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif",`-`].filter(bQ).join(`-`),q=[Q5(J),"#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,D,J.useFog&&J.fog?"#define USE_FOG":"",J.useFog&&J.fogExp2?"#define FOG_EXP2":"",J.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",J.map?"#define USE_MAP":"",J.matcap?"#define USE_MATCAP":"",J.envMap?"#define USE_ENVMAP":"",J.envMap?"#define "+Y:"",J.envMap?"#define "+G:"",J.envMap?"#define "+O:"",E?"#define CUBEUV_TEXEL_WIDTH "+E.texelWidth:"",E?"#define CUBEUV_TEXEL_HEIGHT "+E.texelHeight:"",E?"#define CUBEUV_MAX_MIP "+E.maxMip+".0":"",J.lightMap?"#define USE_LIGHTMAP":"",J.aoMap?"#define USE_AOMAP":"",J.bumpMap?"#define USE_BUMPMAP":"",J.normalMap?"#define USE_NORMALMAP":"",J.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",J.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",J.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",J.emissiveMap?"#define USE_EMISSIVEMAP":"",J.anisotropy?"#define USE_ANISOTROPY":"",J.anisotropyMap?"#define USE_ANISOTROPYMAP":"",J.clearcoat?"#define USE_CLEARCOAT":"",J.clearcoatMap?"#define USE_CLEARCOATMAP":"",J.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",J.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",J.dispersion?"#define USE_DISPERSION":"",J.iridescence?"#define USE_IRIDESCENCE":"",J.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",J.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",J.specularMap?"#define USE_SPECULARMAP":"",J.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",J.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",J.roughnessMap?"#define USE_ROUGHNESSMAP":"",J.metalnessMap?"#define USE_METALNESSMAP":"",J.alphaMap?"#define USE_ALPHAMAP":"",J.alphaTest?"#define USE_ALPHATEST":"",J.alphaHash?"#define USE_ALPHAHASH":"",J.sheen?"#define USE_SHEEN":"",J.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",J.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",J.transmission?"#define USE_TRANSMISSION":"",J.transmissionMap?"#define USE_TRANSMISSIONMAP":"",J.thicknessMap?"#define USE_THICKNESSMAP":"",J.vertexTangents&&J.flatShading===!1?"#define USE_TANGENT":"",J.vertexColors||J.instancingColor?"#define USE_COLOR":"",J.vertexAlphas||J.batchingColor?"#define USE_COLOR_ALPHA":"",J.vertexUv1s?"#define USE_UV1":"",J.vertexUv2s?"#define USE_UV2":"",J.vertexUv3s?"#define USE_UV3":"",J.pointsUvs?"#define USE_POINTS_UV":"",J.gradientMap?"#define USE_GRADIENTMAP":"",J.flatShading?"#define FLAT_SHADED":"",J.doubleSided?"#define DOUBLE_SIDED":"",J.flipSided?"#define FLIP_SIDED":"",J.shadowMapEnabled?"#define USE_SHADOWMAP":"",J.shadowMapEnabled?"#define "+H:"",J.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",J.numLightProbes>0?"#define USE_LIGHT_PROBES":"",J.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",J.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",J.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",J.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",J.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",J.toneMapping!==oU?"#define TONE_MAPPING":"",J.toneMapping!==oU?o$.tonemapping_pars_fragment:"",J.toneMapping!==oU?AP("toneMapping",J.toneMapping):"",J.dithering?"#define DITHERING":"",J.opaque?"#define OPAQUE":"",o$.colorspace_pars_fragment,zP("linearToOutputTexel",J.outputColorSpace),CP(),J.useDepthPacking?"#define DEPTH_PACKING "+J.depthPacking:"",`-`].filter(bQ).join(`-`);if(X=JZ(X),X=U5(X,J),X=J5(X,J),N=JZ(N),N=U5(N,J),N=J5(N,J),X=W5(X),N=W5(N),J.isRawShaderMaterial!==!0)_=`#version 300 es-`,I=[Z,"#define attribute in","#define varying out","#define texture2D texture"].join(`+ }`,depthTest:!1,depthWrite:!1}),u=new pt(c,l),f=new xr(-1,1,1,-1,0,1),h=null,d=null,g=!1,y,p=null,m=[],A=!1;this.setSize=function(T,v){o.setSize(T,v),a.setSize(T,v);for(let w=0;w<m.length;w++){let E=m[w];if(E.setSize)E.setSize(T,v)}},this.setEffects=function(T){m=T,A=m.length>0&&m[0].isRenderPass===!0;let{width:v,height:w}=o;for(let E=0;E<m.length;E++){let R=m[E];if(R.setSize)R.setSize(v,w)}},this.begin=function(T,v){if(g)return!1;if(T.toneMapping===Un&&m.length===0)return!1;if(p=v,v!==null){let{width:w,height:E}=v;if(o.width!==w||o.height!==E)this.setSize(w,E)}if(A===!1)T.setRenderTarget(o);return y=T.toneMapping,T.toneMapping=Un,!0},this.hasRenderPass=function(){return A},this.end=function(T,v){T.toneMapping=y,g=!0;let w=o,E=a;for(let R=0;R<m.length;R++){let _=m[R];if(_.enabled===!1)continue;if(_.render(T,E,w,v),_.needsSwap!==!1){let S=w;w=E,E=S}}if(h!==T.outputColorSpace||d!==T.toneMapping){if(h=T.outputColorSpace,d=T.toneMapping,l.defines={},We.getTransfer(h)===ht)l.defines.SRGB_TRANSFER="";let R=jM[d];if(R)l.defines[R]="";l.needsUpdate=!0}l.uniforms.tDiffuse.value=w.texture,T.setRenderTarget(p),T.render(u,f),p=null,g=!1},this.isCompositing=function(){return g},this.dispose=function(){if(o.depthTexture)o.depthTexture.dispose();o.dispose(),a.dispose(),c.dispose(),l.dispose()}}var X_=new wt,ju=new Bi(1,1),q_=new Ca,Y_=new Tu,j_=new Oa,R_=[],C_=[],I_=new Float32Array(16),P_=new Float32Array(9),L_=new Float32Array(4);function cs(e,t,n){let i=e[0];if(i<=0||i>0)return e;let r=t*n,s=R_[r];if(s===void 0)s=new Float32Array(r),R_[r]=s;if(t!==0){i.toArray(s,0);for(let o=1,a=0;o!==t;++o)a+=n,e[o].toArray(s,a)}return s}function Dt(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n<i;n++)if(e[n]!==t[n])return!1;return!0}function Ut(e,t){for(let n=0,i=t.length;n<i;n++)e[n]=t[n]}function Ka(e,t){let n=C_[t];if(n===void 0)n=new Int32Array(t),C_[t]=n;for(let i=0;i!==t;++i)n[i]=e.allocateTextureUnit();return n}function KM(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1f(this.addr,t),n[0]=t}function QM(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y)e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y}else{if(Dt(n,t))return;e.uniform2fv(this.addr,t),Ut(n,t)}}function ew(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z}else if(t.r!==void 0){if(n[0]!==t.r||n[1]!==t.g||n[2]!==t.b)e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b}else{if(Dt(n,t))return;e.uniform3fv(this.addr,t),Ut(n,t)}}function tw(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w}else{if(Dt(n,t))return;e.uniform4fv(this.addr,t),Ut(n,t)}}function nw(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(Dt(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),Ut(n,t)}else{if(Dt(n,i))return;L_.set(i),e.uniformMatrix2fv(this.addr,!1,L_),Ut(n,i)}}function iw(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(Dt(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),Ut(n,t)}else{if(Dt(n,i))return;P_.set(i),e.uniformMatrix3fv(this.addr,!1,P_),Ut(n,i)}}function rw(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(Dt(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),Ut(n,t)}else{if(Dt(n,i))return;I_.set(i),e.uniformMatrix4fv(this.addr,!1,I_),Ut(n,i)}}function sw(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1i(this.addr,t),n[0]=t}function ow(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y)e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y}else{if(Dt(n,t))return;e.uniform2iv(this.addr,t),Ut(n,t)}}function aw(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z}else{if(Dt(n,t))return;e.uniform3iv(this.addr,t),Ut(n,t)}}function cw(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w}else{if(Dt(n,t))return;e.uniform4iv(this.addr,t),Ut(n,t)}}function lw(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1ui(this.addr,t),n[0]=t}function uw(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y)e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y}else{if(Dt(n,t))return;e.uniform2uiv(this.addr,t),Ut(n,t)}}function hw(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z}else{if(Dt(n,t))return;e.uniform3uiv(this.addr,t),Ut(n,t)}}function fw(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w}else{if(Dt(n,t))return;e.uniform4uiv(this.addr,t),Ut(n,t)}}function dw(e,t,n){let i=this.cache,r=n.allocateTextureUnit();if(i[0]!==r)e.uniform1i(this.addr,r),i[0]=r;let s;if(this.type===e.SAMPLER_2D_SHADOW)ju.compareFunction=n.isReversedDepthBuffer()?Ra:Aa,s=ju;else s=X_;n.setTexture2D(t||s,r)}function pw(e,t,n){let i=this.cache,r=n.allocateTextureUnit();if(i[0]!==r)e.uniform1i(this.addr,r),i[0]=r;n.setTexture3D(t||Y_,r)}function mw(e,t,n){let i=this.cache,r=n.allocateTextureUnit();if(i[0]!==r)e.uniform1i(this.addr,r),i[0]=r;n.setTextureCube(t||j_,r)}function gw(e,t,n){let i=this.cache,r=n.allocateTextureUnit();if(i[0]!==r)e.uniform1i(this.addr,r),i[0]=r;n.setTexture2DArray(t||q_,r)}function _w(e){switch(e){case 5126:return KM;case 35664:return QM;case 35665:return ew;case 35666:return tw;case 35674:return nw;case 35675:return iw;case 35676:return rw;case 5124:case 35670:return sw;case 35667:case 35671:return ow;case 35668:case 35672:return aw;case 35669:case 35673:return cw;case 5125:return lw;case 36294:return uw;case 36295:return hw;case 36296:return fw;case 35678:case 36198:case 36298:case 36306:case 35682:return dw;case 35679:case 36299:case 36307:return pw;case 35680:case 36300:case 36308:case 36293:return mw;case 36289:case 36303:case 36311:case 36292:return gw}}function xw(e,t){e.uniform1fv(this.addr,t)}function vw(e,t){let n=cs(t,this.size,2);e.uniform2fv(this.addr,n)}function yw(e,t){let n=cs(t,this.size,3);e.uniform3fv(this.addr,n)}function bw(e,t){let n=cs(t,this.size,4);e.uniform4fv(this.addr,n)}function Sw(e,t){let n=cs(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function Mw(e,t){let n=cs(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function ww(e,t){let n=cs(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function Tw(e,t){e.uniform1iv(this.addr,t)}function Ew(e,t){e.uniform2iv(this.addr,t)}function Aw(e,t){e.uniform3iv(this.addr,t)}function Rw(e,t){e.uniform4iv(this.addr,t)}function Cw(e,t){e.uniform1uiv(this.addr,t)}function Iw(e,t){e.uniform2uiv(this.addr,t)}function Pw(e,t){e.uniform3uiv(this.addr,t)}function Lw(e,t){e.uniform4uiv(this.addr,t)}function Nw(e,t,n){let i=this.cache,r=t.length,s=Ka(n,r);if(!Dt(i,s))e.uniform1iv(this.addr,s),Ut(i,s);let o;if(this.type===e.SAMPLER_2D_SHADOW)o=ju;else o=X_;for(let a=0;a!==r;++a)n.setTexture2D(t[a]||o,s[a])}function Dw(e,t,n){let i=this.cache,r=t.length,s=Ka(n,r);if(!Dt(i,s))e.uniform1iv(this.addr,s),Ut(i,s);for(let o=0;o!==r;++o)n.setTexture3D(t[o]||Y_,s[o])}function Uw(e,t,n){let i=this.cache,r=t.length,s=Ka(n,r);if(!Dt(i,s))e.uniform1iv(this.addr,s),Ut(i,s);for(let o=0;o!==r;++o)n.setTextureCube(t[o]||j_,s[o])}function Ow(e,t,n){let i=this.cache,r=t.length,s=Ka(n,r);if(!Dt(i,s))e.uniform1iv(this.addr,s),Ut(i,s);for(let o=0;o!==r;++o)n.setTexture2DArray(t[o]||q_,s[o])}function Fw(e){switch(e){case 5126:return xw;case 35664:return vw;case 35665:return yw;case 35666:return bw;case 35674:return Sw;case 35675:return Mw;case 35676:return ww;case 5124:case 35670:return Tw;case 35667:case 35671:return Ew;case 35668:case 35672:return Aw;case 35669:case 35673:return Rw;case 5125:return Cw;case 36294:return Iw;case 36295:return Pw;case 36296:return Lw;case 35678:case 36198:case 36298:case 36306:case 35682:return Nw;case 35679:case 36299:case 36307:return Dw;case 35680:case 36300:case 36308:case 36293:return Uw;case 36289:case 36303:case 36311:case 36292:return Ow}}class J_{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=_w(t.type)}}class K_{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=Fw(t.type)}}class Q_{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let i=this.seq;for(let r=0,s=i.length;r!==s;++r){let o=i[r];o.setValue(e,t[o.id],n)}}}var qu=/(\w+)(\])?(\[|\.)?/g;function N_(e,t){e.seq.push(t),e.map[t.id]=t}function zw(e,t,n){let i=e.name,r=i.length;qu.lastIndex=0;while(!0){let s=qu.exec(i),o=qu.lastIndex,a=s[1],c=s[2]==="]",l=s[3];if(c)a=a|0;if(l===void 0||l==="["&&o+2===r){N_(n,l===void 0?new J_(a,e,t):new K_(a,e,t));break}else{let f=n.map[a];if(f===void 0)f=new Q_(a),N_(n,f);n=f}}}class co{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let s=0;s<n;++s){let o=e.getActiveUniform(t,s),a=e.getUniformLocation(t,o.name);zw(o,a,this)}let i=[],r=[];for(let s of this.seq)if(s.type===e.SAMPLER_2D_SHADOW||s.type===e.SAMPLER_CUBE_SHADOW||s.type===e.SAMPLER_2D_ARRAY_SHADOW)i.push(s);else r.push(s);if(i.length>0)this.seq=i.concat(r)}setValue(e,t,n,i){let r=this.map[t];if(r!==void 0)r.setValue(e,n,i)}setOptional(e,t,n){let i=t[n];if(i!==void 0)this.setValue(e,n,i)}static upload(e,t,n,i){for(let r=0,s=t.length;r!==s;++r){let o=t[r],a=n[o.id];if(a.needsUpdate!==!1)o.setValue(e,a.value,i)}}static seqWithValue(e,t){let n=[];for(let i=0,r=e.length;i!==r;++i){let s=e[i];if(s.id in t)n.push(s)}return n}}function D_(e,t,n){let i=e.createShader(t);return e.shaderSource(i,n),e.compileShader(i),i}var kw=37297,Bw=0;function Gw(e,t){let n=e.split(`+`),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let o=r;o<s;o++){let a=o+1;i.push(`${a===t?">":" "} ${a}: ${n[o]}`)}return i.join(`+`)}var U_=new Ue;function Hw(e){We._getMatrix(U_,We.workingColorSpace,e);let t=`mat3( ${U_.elements.map((n)=>n.toFixed(4))} )`;switch(We.getTransfer(e)){case vu:return[t,"LinearTransferOETF"];case ht:return[t,"sRGBTransferOETF"];default:return Me("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}function O_(e,t,n){let i=e.getShaderParameter(t,e.COMPILE_STATUS),s=(e.getShaderInfoLog(t)||"").trim();if(i&&s==="")return"";let o=/ERROR: 0:(\d+)/.exec(s);if(o){let a=parseInt(o[1]);return n.toUpperCase()+`++`+s+`++`+Gw(e.getShaderSource(t),a)}else return s}function Vw(e,t){let n=Hw(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(`+`)}var Ww={[Rl]:"Linear",[Cl]:"Reinhard",[Il]:"Cineon",[Gs]:"ACESFilmic",[Ll]:"AgX",[Nl]:"Neutral",[Pl]:"Custom"};function $w(e,t){let n=Ww[t];if(n===void 0)return Me("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }";return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}var ja=new N;function Zw(){We.getLuminanceCoefficients(ja);let e=ja.x.toFixed(4),t=ja.y.toFixed(4),n=ja.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${e}, ${t}, ${n} );`,"\treturn dot( weights, rgb );","}"].join(`+`)}function Xw(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(ao).join(`+`)}function qw(e){let t=[];for(let n in e){let i=e[n];if(i===!1)continue;t.push("#define "+n+" "+i)}return t.join(`+`)}function Yw(e,t){let n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<i;r++){let s=e.getActiveAttrib(t,r),o=s.name,a=1;if(s.type===e.FLOAT_MAT2)a=2;if(s.type===e.FLOAT_MAT3)a=3;if(s.type===e.FLOAT_MAT4)a=4;n[o]={type:s.type,location:e.getAttribLocation(t,o),locationSize:a}}return n}function ao(e){return e!==""}function F_(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function z_(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var jw=/^[ \t]*#include +<([\w\d./]+)>/gm;function Ju(e){return e.replace(jw,Kw)}var Jw=new Map;function Kw(e,t){let n=He[t];if(n===void 0){let i=Jw.get(t);if(i!==void 0)n=He[i],Me('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,i);else throw Error("THREE.WebGLProgram: Can not resolve #include <"+t+">")}return Ju(n)}var Qw=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function k_(e){return e.replace(Qw,eT)}function eT(e,t,n,i){let r="";for(let s=parseInt(t);s<parseInt(n);s++)r+=i.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return r}function B_(e){let t=`precision ${e.precision} float;+ precision ${e.precision} int;+ precision ${e.precision} sampler2D;+ precision ${e.precision} samplerCube;+ precision ${e.precision} sampler3D;+ precision ${e.precision} sampler2DArray;+ precision ${e.precision} sampler2DShadow;+ precision ${e.precision} samplerCubeShadow;+ precision ${e.precision} sampler2DArrayShadow;+ precision ${e.precision} isampler2D;+ precision ${e.precision} isampler3D;+ precision ${e.precision} isamplerCube;+ precision ${e.precision} isampler2DArray;+ precision ${e.precision} usampler2D;+ precision ${e.precision} usampler3D;+ precision ${e.precision} usamplerCube;+ precision ${e.precision} usampler2DArray;+ `;if(e.precision==="highp")t+=`+#define HIGH_PRECISION`;else if(e.precision==="mediump")t+=`+#define MEDIUM_PRECISION`;else if(e.precision==="lowp")t+=`+#define LOW_PRECISION`;return t}var tT={[ks]:"SHADOWMAP_TYPE_PCF",[Zr]:"SHADOWMAP_TYPE_VSM"};function nT(e){return tT[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}var iT={[qr]:"ENVMAP_TYPE_CUBE",[ur]:"ENVMAP_TYPE_CUBE",[Hs]:"ENVMAP_TYPE_CUBE_UV"};function rT(e){if(e.envMap===!1)return"ENVMAP_TYPE_CUBE";return iT[e.envMapMode]||"ENVMAP_TYPE_CUBE"}var sT={[ur]:"ENVMAP_MODE_REFRACTION"};function oT(e){if(e.envMap===!1)return"ENVMAP_MODE_REFLECTION";return sT[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}var aT={[qg]:"ENVMAP_BLENDING_MULTIPLY",[Yg]:"ENVMAP_BLENDING_MIX",[jg]:"ENVMAP_BLENDING_ADD"};function cT(e){if(e.envMap===!1)return"ENVMAP_BLENDING_NONE";return aT[e.combine]||"ENVMAP_BLENDING_NONE"}function lT(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let n=Math.log2(t)-2,i=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:i,maxMip:n}}function uT(e,t,n,i){let r=e.getContext(),{defines:s,vertexShader:o,fragmentShader:a}=n,c=nT(n),l=rT(n),u=oT(n),f=cT(n),h=lT(n),d=Xw(n),g=qw(s),y=r.createProgram(),p,m,A=n.glslVersion?"#version "+n.glslVersion+`+`:"";if(n.isRawShaderMaterial){if(p=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(ao).join(`+`),p.length>0)p+=`+`;if(m=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(ao).join(`+`),m.length>0)m+=`+`}else p=[B_(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexNormals?"#define HAS_NORMAL":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&n.flatShading===!1?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.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","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif",`+`].filter(ao).join(`+`),m=[B_(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+l:"",n.envMap?"#define "+u:"",n.envMap?"#define "+f:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas||n.batchingColor?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==Un?"#define TONE_MAPPING":"",n.toneMapping!==Un?He.tonemapping_pars_fragment:"",n.toneMapping!==Un?$w("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",He.colorspace_pars_fragment,Vw("linearToOutputTexel",n.outputColorSpace),Zw(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`+`].filter(ao).join(`+`);if(o=Ju(o),o=F_(o,n),o=z_(o,n),a=Ju(a),a=F_(a,n),a=z_(a,n),o=k_(o),a=k_(a),n.isRawShaderMaterial!==!0)A=`#version 300 es+`,p=[d,"#define attribute in","#define varying out","#define texture2D texture"].join(``)+`-`+I,q=["#define varying in",J.glslVersion===PE?"":"layout(location = 0) out highp vec4 pc_fragColor;",J.glslVersion===PE?"":"#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(`+`+p,m=["#define varying in",n.glslVersion===yu?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===yu?"":"#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(``)+`-`+q;let P=_+I+X,L=_+q+N,B=tk(W,W.VERTEX_SHADER,P),z=tk(W,W.FRAGMENT_SHADER,L);if(W.attachShader(R,B),W.attachShader(R,z),J.index0AttributeName!==void 0)W.bindAttribLocation(R,0,J.index0AttributeName);else if(J.hasPositionAttribute===!0)W.bindAttribLocation(R,0,"position");W.linkProgram(R);function A(C){if($.debug.checkShaderErrors){let f=W.getProgramInfoLog(R)||"",s=W.getShaderInfoLog(B)||"",y=W.getShaderInfoLog(z)||"",d=f.trim(),c=s.trim(),x=y.trim(),t=!0,e=!0;if(W.getProgramParameter(R,W.LINK_STATUS)===!1)if(t=!1,typeof $.debug.onShaderError==="function")$.debug.onShaderError(W,R,B,z);else{let Y$=$5(W,B,"vertex"),R$=$5(W,z,"fragment");y$("WebGLProgram: Shader Error "+W.getError()+" - VALIDATE_STATUS "+W.getProgramParameter(R,W.VALIDATE_STATUS)+`+`+m;let T=A+p+o,v=A+m+a,w=D_(r,r.VERTEX_SHADER,T),E=D_(r,r.FRAGMENT_SHADER,v);if(r.attachShader(y,w),r.attachShader(y,E),n.index0AttributeName!==void 0)r.bindAttribLocation(y,0,n.index0AttributeName);else if(n.hasPositionAttribute===!0)r.bindAttribLocation(y,0,"position");r.linkProgram(y);function R(C){if(e.debug.checkShaderErrors){let z=r.getProgramInfoLog(y)||"",J=r.getShaderInfoLog(w)||"",O=r.getShaderInfoLog(E)||"",H=z.trim(),V=J.trim(),U=O.trim(),K=!0,Q=!0;if(r.getProgramParameter(y,r.LINK_STATUS)===!1)if(K=!1,typeof e.debug.onShaderError==="function")e.debug.onShaderError(r,y,w,E);else{let se=O_(r,w,"vertex"),me=O_(r,E,"fragment");Ne("WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(y,r.VALIDATE_STATUS)+`Material Name: `+C.name+`Material Type: `+C.type+`-Program Info Log: `+d+`-`+Y$+`-`+R$)}else if(d!=="")A$("WebGLProgram: Program Info Log:",d);else if(c===""||x==="")e=!1;if(e)C.diagnostics={runnable:t,programLog:d,vertexShader:{log:c,prefix:I},fragmentShader:{log:x,prefix:q}}}W.deleteShader(B),W.deleteShader(z),k=new xQ(W,R),w=vP(W,R)}let k;this.getUniforms=function(){if(k===void 0)A(this);return k};let w;this.getAttributes=function(){if(w===void 0)A(this);return w};let h=J.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){if(h===!1)h=W.getProgramParameter(R,wP);return h},this.destroy=function(){Q.releaseStatesOfProgram(this),W.deleteProgram(R),this.program=void 0},this.type=J.shaderType,this.name=J.shaderName,this.id=MP++,this.cacheKey=U,this.usedTimes=1,this.program=R,this.vertexShader=B,this.fragmentShader=z,this}var oP=0;class F5{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update($,U,J){let Q=this._getShaderCacheForMaterial($);if(Q.has(U)===!1)Q.add(U),U.usedTimes++;if(Q.has(J)===!1)Q.add(J),J.usedTimes++;return this}remove($){let U=this.materialCache.get($);for(let J of U)if(J.usedTimes--,J.usedTimes===0)this.shaderCache.delete(J.code);return this.materialCache.delete($),this}getVertexShaderStage($){return this._getShaderStage($.vertexShader)}getFragmentShaderStage($){return this._getShaderStage($.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial($){let U=this.materialCache,J=U.get($);if(J===void 0)J=new Set,U.set($,J);return J}_getShaderStage($){let U=this.shaderCache,J=U.get($);if(J===void 0)J=new L5($),U.set($,J);return J}}class L5{constructor($){this.id=oP++,this.code=$,this.usedTimes=0}}function rP($){return $===m0||$===H7||$===Y7}function aP($,U,J,Q,W,K){let X=new I7,N=new F5,H=new Set,Y=[],G=new Map,O=Q.logarithmicDepthBuffer,E=Q.precision,Z={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 D(k){if(H.add(k),k===0)return"uv";return`uv${k}`}function R(k,w,h,C,f,s){let y=C.fog,d=f.geometry,c=k.isMeshStandardMaterial||k.isMeshLambertMaterial||k.isMeshPhongMaterial?C.environment:null,x=k.isMeshStandardMaterial||k.isMeshLambertMaterial&&!k.envMap||k.isMeshPhongMaterial&&!k.envMap,t=U.get(k.envMap||c,x),e=!!t&&t.mapping===DQ?t.image.height:null,Y$=Z[k.type];if(k.precision!==null){if(E=Q.getMaxPrecision(k.precision),E!==k.precision)A$("WebGLProgram.getParameters:",k.precision,"not supported, using",E,"instead.")}let R$=d.morphAttributes.position||d.morphAttributes.normal||d.morphAttributes.color,w$=R$!==void 0?R$.length:0,U6=0;if(d.morphAttributes.position!==void 0)U6=1;if(d.morphAttributes.normal!==void 0)U6=2;if(d.morphAttributes.color!==void 0)U6=3;let i$,i,X$,k$;if(Y$){let m$=kJ[Y$];i$=m$.vertexShader,i=m$.fragmentShader}else{i$=k.vertexShader,i=k.fragmentShader;let m$=N.getVertexShaderStage(k),C6=N.getFragmentShaderStage(k);N.update(k,m$,C6),X$=m$.id,k$=C6.id}let F$=$.getRenderTarget(),v$=$.state.buffers.depth.getReversed(),e$=f.isInstancedMesh===!0,l$=f.isBatchedMesh===!0,d$=!!k.map,X6=!!k.matcap,J6=!!t,K6=!!k.aoMap,d6=!!k.lightMap,CU=!!k.bumpMap&&k.wireframe===!1,z6=!!k.normalMap,r6=!!k.displacementMap,c6=!!k.emissiveMap,h6=!!k.metalnessMap,v=!!k.roughnessMap,SU=k.anisotropy>0,G6=k.clearcoat>0,_6=k.dispersion>0,M=k.iridescence>0,F=k.sheen>0,S=k.transmission>0,n=SU&&!!k.anisotropyMap,J$=G6&&!!k.clearcoatMap,N$=G6&&!!k.clearcoatNormalMap,Z$=G6&&!!k.clearcoatRoughnessMap,o=M&&!!k.iridescenceMap,a=M&&!!k.iridescenceThicknessMap,M$=F&&!!k.sheenColorMap,C$=F&&!!k.sheenRoughnessMap,I$=!!k.specularMap,H$=!!k.specularColorMap,j$=!!k.specularIntensityMap,b$=S&&!!k.transmissionMap,H6=S&&!!k.thicknessMap,T=!!k.gradientMap,G$=!!k.alphaMap,r=k.alphaTest>0,O$=!!k.alphaHash,B$=!!k.extensions,$$=oU;if(k.toneMapped){if(F$===null||F$.isXRRenderTarget===!0)$$=$.toneMapping}let E$={shaderID:Y$,shaderType:k.type,shaderName:k.name,vertexShader:i$,fragmentShader:i,defines:k.defines,customVertexShaderID:X$,customFragmentShaderID:k$,isRawShaderMaterial:k.isRawShaderMaterial===!0,glslVersion:k.glslVersion,precision:E,batching:l$,batchingColor:l$&&f._colorsTexture!==null,instancing:e$,instancingColor:e$&&f.instanceColor!==null,instancingMorph:e$&&f.morphTexture!==null,outputColorSpace:F$===null?$.outputColorSpace:F$.isXRRenderTarget===!0?F$.texture.colorSpace:s$.workingColorSpace,alphaToCoverage:!!k.alphaToCoverage,map:d$,matcap:X6,envMap:J6,envMapMode:J6&&t.mapping,envMapCubeUVHeight:e,aoMap:K6,lightMap:d6,bumpMap:CU,normalMap:z6,displacementMap:r6,emissiveMap:c6,normalMapObjectSpace:z6&&k.normalMapType===wk,normalMapTangentSpace:z6&&k.normalMapType===ME,packedNormalMap:z6&&k.normalMapType===ME&&rP(k.normalMap.format),metalnessMap:h6,roughnessMap:v,anisotropy:SU,anisotropyMap:n,clearcoat:G6,clearcoatMap:J$,clearcoatNormalMap:N$,clearcoatRoughnessMap:Z$,dispersion:_6,iridescence:M,iridescenceMap:o,iridescenceThicknessMap:a,sheen:F,sheenColorMap:M$,sheenRoughnessMap:C$,specularMap:I$,specularColorMap:H$,specularIntensityMap:j$,transmission:S,transmissionMap:b$,thicknessMap:H6,gradientMap:T,opaque:k.transparent===!1&&k.blending===IQ&&k.alphaToCoverage===!1,alphaMap:G$,alphaTest:r,alphaHash:O$,combine:k.combine,mapUv:d$&&D(k.map.channel),aoMapUv:K6&&D(k.aoMap.channel),lightMapUv:d6&&D(k.lightMap.channel),bumpMapUv:CU&&D(k.bumpMap.channel),normalMapUv:z6&&D(k.normalMap.channel),displacementMapUv:r6&&D(k.displacementMap.channel),emissiveMapUv:c6&&D(k.emissiveMap.channel),metalnessMapUv:h6&&D(k.metalnessMap.channel),roughnessMapUv:v&&D(k.roughnessMap.channel),anisotropyMapUv:n&&D(k.anisotropyMap.channel),clearcoatMapUv:J$&&D(k.clearcoatMap.channel),clearcoatNormalMapUv:N$&&D(k.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Z$&&D(k.clearcoatRoughnessMap.channel),iridescenceMapUv:o&&D(k.iridescenceMap.channel),iridescenceThicknessMapUv:a&&D(k.iridescenceThicknessMap.channel),sheenColorMapUv:M$&&D(k.sheenColorMap.channel),sheenRoughnessMapUv:C$&&D(k.sheenRoughnessMap.channel),specularMapUv:I$&&D(k.specularMap.channel),specularColorMapUv:H$&&D(k.specularColorMap.channel),specularIntensityMapUv:j$&&D(k.specularIntensityMap.channel),transmissionMapUv:b$&&D(k.transmissionMap.channel),thicknessMapUv:H6&&D(k.thicknessMap.channel),alphaMapUv:G$&&D(k.alphaMap.channel),vertexTangents:!!d.attributes.tangent&&(z6||SU),vertexNormals:!!d.attributes.normal,vertexColors:k.vertexColors,vertexAlphas:k.vertexColors===!0&&!!d.attributes.color&&d.attributes.color.itemSize===4,pointsUvs:f.isPoints===!0&&!!d.attributes.uv&&(d$||G$),fog:!!y,useFog:k.fog===!0,fogExp2:!!y&&y.isFogExp2,flatShading:k.wireframe===!1&&(k.flatShading===!0||d.attributes.normal===void 0&&z6===!1&&(k.isMeshLambertMaterial||k.isMeshPhongMaterial||k.isMeshStandardMaterial||k.isMeshPhysicalMaterial)),sizeAttenuation:k.sizeAttenuation===!0,logarithmicDepthBuffer:O,reversedDepthBuffer:v$,skinning:f.isSkinnedMesh===!0,hasPositionAttribute:d.attributes.position!==void 0,morphTargets:d.morphAttributes.position!==void 0,morphNormals:d.morphAttributes.normal!==void 0,morphColors:d.morphAttributes.color!==void 0,morphTargetsCount:w$,morphTextureStride:U6,numDirLights:w.directional.length,numPointLights:w.point.length,numSpotLights:w.spot.length,numSpotLightMaps:w.spotLightMap.length,numRectAreaLights:w.rectArea.length,numHemiLights:w.hemi.length,numDirLightShadows:w.directionalShadowMap.length,numPointLightShadows:w.pointShadowMap.length,numSpotLightShadows:w.spotShadowMap.length,numSpotLightShadowsWithMaps:w.numSpotLightShadowsWithMaps,numLightProbes:w.numLightProbes,numLightProbeGrids:s.length,numClippingPlanes:K.numPlanes,numClipIntersection:K.numIntersection,dithering:k.dithering,shadowMapEnabled:$.shadowMap.enabled&&h.length>0,shadowMapType:$.shadowMap.type,toneMapping:$$,decodeVideoTexture:d$&&k.map.isVideoTexture===!0&&s$.getTransfer(k.map.colorSpace)===w6,decodeVideoTextureEmissive:c6&&k.emissiveMap.isVideoTexture===!0&&s$.getTransfer(k.emissiveMap.colorSpace)===w6,premultipliedAlpha:k.premultipliedAlpha,doubleSided:k.side===bU,flipSided:k.side===JU,useDepthPacking:k.depthPacking>=0,depthPacking:k.depthPacking||0,index0AttributeName:k.index0AttributeName,extensionClipCullDistance:B$&&k.extensions.clipCullDistance===!0&&J.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(B$&&k.extensions.multiDraw===!0||l$)&&J.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:J.has("KHR_parallel_shader_compile"),customProgramCacheKey:k.customProgramCacheKey()};return E$.vertexUv1s=H.has(1),E$.vertexUv2s=H.has(2),E$.vertexUv3s=H.has(3),H.clear(),E$}function I(k){let w=[];if(k.shaderID)w.push(k.shaderID);else w.push(k.customVertexShaderID),w.push(k.customFragmentShaderID);if(k.defines!==void 0)for(let h in k.defines)w.push(h),w.push(k.defines[h]);if(k.isRawShaderMaterial===!1)q(w,k),_(w,k),w.push($.outputColorSpace);return w.push(k.customProgramCacheKey),w.join()}function q(k,w){k.push(w.precision),k.push(w.outputColorSpace),k.push(w.envMapMode),k.push(w.envMapCubeUVHeight),k.push(w.mapUv),k.push(w.alphaMapUv),k.push(w.lightMapUv),k.push(w.aoMapUv),k.push(w.bumpMapUv),k.push(w.normalMapUv),k.push(w.displacementMapUv),k.push(w.emissiveMapUv),k.push(w.metalnessMapUv),k.push(w.roughnessMapUv),k.push(w.anisotropyMapUv),k.push(w.clearcoatMapUv),k.push(w.clearcoatNormalMapUv),k.push(w.clearcoatRoughnessMapUv),k.push(w.iridescenceMapUv),k.push(w.iridescenceThicknessMapUv),k.push(w.sheenColorMapUv),k.push(w.sheenRoughnessMapUv),k.push(w.specularMapUv),k.push(w.specularColorMapUv),k.push(w.specularIntensityMapUv),k.push(w.transmissionMapUv),k.push(w.thicknessMapUv),k.push(w.combine),k.push(w.fogExp2),k.push(w.sizeAttenuation),k.push(w.morphTargetsCount),k.push(w.morphAttributeCount),k.push(w.numDirLights),k.push(w.numPointLights),k.push(w.numSpotLights),k.push(w.numSpotLightMaps),k.push(w.numHemiLights),k.push(w.numRectAreaLights),k.push(w.numDirLightShadows),k.push(w.numPointLightShadows),k.push(w.numSpotLightShadows),k.push(w.numSpotLightShadowsWithMaps),k.push(w.numLightProbes),k.push(w.shadowMapType),k.push(w.toneMapping),k.push(w.numClippingPlanes),k.push(w.numClipIntersection),k.push(w.depthPacking)}function _(k,w){if(X.disableAll(),w.instancing)X.enable(0);if(w.instancingColor)X.enable(1);if(w.instancingMorph)X.enable(2);if(w.matcap)X.enable(3);if(w.envMap)X.enable(4);if(w.normalMapObjectSpace)X.enable(5);if(w.normalMapTangentSpace)X.enable(6);if(w.clearcoat)X.enable(7);if(w.iridescence)X.enable(8);if(w.alphaTest)X.enable(9);if(w.vertexColors)X.enable(10);if(w.vertexAlphas)X.enable(11);if(w.vertexUv1s)X.enable(12);if(w.vertexUv2s)X.enable(13);if(w.vertexUv3s)X.enable(14);if(w.vertexTangents)X.enable(15);if(w.anisotropy)X.enable(16);if(w.alphaHash)X.enable(17);if(w.batching)X.enable(18);if(w.dispersion)X.enable(19);if(w.batchingColor)X.enable(20);if(w.gradientMap)X.enable(21);if(w.packedNormalMap)X.enable(22);if(w.vertexNormals)X.enable(23);if(k.push(X.mask),X.disableAll(),w.fog)X.enable(0);if(w.useFog)X.enable(1);if(w.flatShading)X.enable(2);if(w.logarithmicDepthBuffer)X.enable(3);if(w.reversedDepthBuffer)X.enable(4);if(w.skinning)X.enable(5);if(w.morphTargets)X.enable(6);if(w.morphNormals)X.enable(7);if(w.morphColors)X.enable(8);if(w.premultipliedAlpha)X.enable(9);if(w.shadowMapEnabled)X.enable(10);if(w.doubleSided)X.enable(11);if(w.flipSided)X.enable(12);if(w.useDepthPacking)X.enable(13);if(w.dithering)X.enable(14);if(w.transmission)X.enable(15);if(w.sheen)X.enable(16);if(w.opaque)X.enable(17);if(w.pointsUvs)X.enable(18);if(w.decodeVideoTexture)X.enable(19);if(w.decodeVideoTextureEmissive)X.enable(20);if(w.alphaToCoverage)X.enable(21);if(w.numLightProbeGrids>0)X.enable(22);if(w.hasPositionAttribute)X.enable(23);k.push(X.mask)}function P(k){let w=Z[k.type],h;if(w){let C=kJ[w];h=gk.clone(C.uniforms)}else h=k.uniforms;return h}function L(k,w){let h=G.get(w);if(h!==void 0)++h.usedTimes;else h=new iP($,w,k,W),Y.push(h),G.set(w,h);return h}function B(k){if(--k.usedTimes===0){let w=Y.indexOf(k);Y[w]=Y[Y.length-1],Y.pop(),G.delete(k.cacheKey),k.destroy()}}function z(k){N.remove(k)}function A(){N.dispose()}return{getParameters:R,getProgramCacheKey:I,getUniforms:P,acquireProgram:L,releaseProgram:B,releaseShaderCache:z,programs:Y,dispose:A}}function sP(){let $=new WeakMap;function U(X){return $.has(X)}function J(X){let N=$.get(X);if(N===void 0)N={},$.set(X,N);return N}function Q(X){$.delete(X)}function W(X,N,H){$.get(X)[N]=H}function K(){$=new WeakMap}return{has:U,get:J,remove:Q,update:W,dispose:K}}function tP($,U){if($.groupOrder!==U.groupOrder)return $.groupOrder-U.groupOrder;else if($.renderOrder!==U.renderOrder)return $.renderOrder-U.renderOrder;else if($.material.id!==U.material.id)return $.material.id-U.material.id;else if($.materialVariant!==U.materialVariant)return $.materialVariant-U.materialVariant;else if($.z!==U.z)return $.z-U.z;else return $.id-U.id}function K5($,U){if($.groupOrder!==U.groupOrder)return $.groupOrder-U.groupOrder;else if($.renderOrder!==U.renderOrder)return $.renderOrder-U.renderOrder;else if($.z!==U.z)return U.z-$.z;else return $.id-U.id}function X5(){let $=[],U=0,J=[],Q=[],W=[];function K(){U=0,J.length=0,Q.length=0,W.length=0}function X(E){let Z=0;if(E.isInstancedMesh)Z+=2;if(E.isSkinnedMesh)Z+=1;return Z}function N(E,Z,D,R,I,q){let _=$[U];if(_===void 0)_={id:E.id,object:E,geometry:Z,material:D,materialVariant:X(E),groupOrder:R,renderOrder:E.renderOrder,z:I,group:q},$[U]=_;else _.id=E.id,_.object=E,_.geometry=Z,_.material=D,_.materialVariant=X(E),_.groupOrder=R,_.renderOrder=E.renderOrder,_.z=I,_.group=q;return U++,_}function H(E,Z,D,R,I,q){let _=N(E,Z,D,R,I,q);if(D.transmission>0)Q.push(_);else if(D.transparent===!0)W.push(_);else J.push(_)}function Y(E,Z,D,R,I,q){let _=N(E,Z,D,R,I,q);if(D.transmission>0)Q.unshift(_);else if(D.transparent===!0)W.unshift(_);else J.unshift(_)}function G(E,Z,D){if(J.length>1)J.sort(E||tP);if(Q.length>1)Q.sort(Z||K5);if(W.length>1)W.sort(Z||K5);if(D)J.reverse(),Q.reverse(),W.reverse()}function O(){for(let E=U,Z=$.length;E<Z;E++){let D=$[E];if(D.id===null)break;D.id=null,D.object=null,D.geometry=null,D.material=null,D.group=null}}return{opaque:J,transmissive:Q,transparent:W,init:K,push:H,unshift:Y,finish:O,sort:G}}function eP(){let $=new WeakMap;function U(Q,W){let K=$.get(Q),X;if(K===void 0)X=new X5,$.set(Q,[X]);else if(W>=K.length)X=new X5,K.push(X);else X=K[W];return X}function J(){$=new WeakMap}return{get:U,dispose:J}}function $z(){let $={};return{get:function(U){if($[U.id]!==void 0)return $[U.id];let J;switch(U.type){case"DirectionalLight":J={direction:new j,color:new x$};break;case"SpotLight":J={position:new j,direction:new j,color:new x$,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":J={position:new j,color:new x$,distance:0,decay:0};break;case"HemisphereLight":J={direction:new j,skyColor:new x$,groundColor:new x$};break;case"RectAreaLight":J={color:new x$,position:new j,halfWidth:new j,halfHeight:new j};break}return $[U.id]=J,J}}}function Uz(){let $={};return{get:function(U){if($[U.id]!==void 0)return $[U.id];let J;switch(U.type){case"DirectionalLight":J={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new g$};break;case"SpotLight":J={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new g$};break;case"PointLight":J={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new g$,shadowCameraNear:1,shadowCameraFar:1000};break}return $[U.id]=J,J}}}var Jz=0;function Wz($,U){return(U.castShadow?2:0)-($.castShadow?2:0)+(U.map?1:0)-($.map?1:0)}function Qz($){let U=new $z,J=Uz(),Q={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 Y=0;Y<9;Y++)Q.probe.push(new j);let W=new j,K=new p$,X=new p$;function N(Y){let G=0,O=0,E=0;for(let w=0;w<9;w++)Q.probe[w].set(0,0,0);let Z=0,D=0,R=0,I=0,q=0,_=0,P=0,L=0,B=0,z=0,A=0;Y.sort(Wz);for(let w=0,h=Y.length;w<h;w++){let C=Y[w],f=C.color,s=C.intensity,y=C.distance,d=null;if(C.shadow&&C.shadow.map)if(C.shadow.map.texture.format===m0)d=C.shadow.map.texture;else d=C.shadow.map.depthTexture||C.shadow.map.texture;if(C.isAmbientLight)G+=f.r*s,O+=f.g*s,E+=f.b*s;else if(C.isLightProbe){for(let c=0;c<9;c++)Q.probe[c].addScaledVector(C.sh.coefficients[c],s);A++}else if(C.isDirectionalLight){let c=U.get(C);if(c.color.copy(C.color).multiplyScalar(C.intensity),C.castShadow){let x=C.shadow,t=J.get(C);t.shadowIntensity=x.intensity,t.shadowBias=x.bias,t.shadowNormalBias=x.normalBias,t.shadowRadius=x.radius,t.shadowMapSize=x.mapSize,Q.directionalShadow[Z]=t,Q.directionalShadowMap[Z]=d,Q.directionalShadowMatrix[Z]=C.shadow.matrix,_++}Q.directional[Z]=c,Z++}else if(C.isSpotLight){let c=U.get(C);c.position.setFromMatrixPosition(C.matrixWorld),c.color.copy(f).multiplyScalar(s),c.distance=y,c.coneCos=Math.cos(C.angle),c.penumbraCos=Math.cos(C.angle*(1-C.penumbra)),c.decay=C.decay,Q.spot[R]=c;let x=C.shadow;if(C.map){if(Q.spotLightMap[B]=C.map,B++,x.updateMatrices(C),C.castShadow)z++}if(Q.spotLightMatrix[R]=x.matrix,C.castShadow){let t=J.get(C);t.shadowIntensity=x.intensity,t.shadowBias=x.bias,t.shadowNormalBias=x.normalBias,t.shadowRadius=x.radius,t.shadowMapSize=x.mapSize,Q.spotShadow[R]=t,Q.spotShadowMap[R]=d,L++}R++}else if(C.isRectAreaLight){let c=U.get(C);c.color.copy(f).multiplyScalar(s),c.halfWidth.set(C.width*0.5,0,0),c.halfHeight.set(0,C.height*0.5,0),Q.rectArea[I]=c,I++}else if(C.isPointLight){let c=U.get(C);if(c.color.copy(C.color).multiplyScalar(C.intensity),c.distance=C.distance,c.decay=C.decay,C.castShadow){let x=C.shadow,t=J.get(C);t.shadowIntensity=x.intensity,t.shadowBias=x.bias,t.shadowNormalBias=x.normalBias,t.shadowRadius=x.radius,t.shadowMapSize=x.mapSize,t.shadowCameraNear=x.camera.near,t.shadowCameraFar=x.camera.far,Q.pointShadow[D]=t,Q.pointShadowMap[D]=d,Q.pointShadowMatrix[D]=C.shadow.matrix,P++}Q.point[D]=c,D++}else if(C.isHemisphereLight){let c=U.get(C);c.skyColor.copy(C.color).multiplyScalar(s),c.groundColor.copy(C.groundColor).multiplyScalar(s),Q.hemi[q]=c,q++}}if(I>0)if($.has("OES_texture_float_linear")===!0)Q.rectAreaLTC1=D$.LTC_FLOAT_1,Q.rectAreaLTC2=D$.LTC_FLOAT_2;else Q.rectAreaLTC1=D$.LTC_HALF_1,Q.rectAreaLTC2=D$.LTC_HALF_2;Q.ambient[0]=G,Q.ambient[1]=O,Q.ambient[2]=E;let k=Q.hash;if(k.directionalLength!==Z||k.pointLength!==D||k.spotLength!==R||k.rectAreaLength!==I||k.hemiLength!==q||k.numDirectionalShadows!==_||k.numPointShadows!==P||k.numSpotShadows!==L||k.numSpotMaps!==B||k.numLightProbes!==A)Q.directional.length=Z,Q.spot.length=R,Q.rectArea.length=I,Q.point.length=D,Q.hemi.length=q,Q.directionalShadow.length=_,Q.directionalShadowMap.length=_,Q.pointShadow.length=P,Q.pointShadowMap.length=P,Q.spotShadow.length=L,Q.spotShadowMap.length=L,Q.directionalShadowMatrix.length=_,Q.pointShadowMatrix.length=P,Q.spotLightMatrix.length=L+B-z,Q.spotLightMap.length=B,Q.numSpotLightShadowsWithMaps=z,Q.numLightProbes=A,k.directionalLength=Z,k.pointLength=D,k.spotLength=R,k.rectAreaLength=I,k.hemiLength=q,k.numDirectionalShadows=_,k.numPointShadows=P,k.numSpotShadows=L,k.numSpotMaps=B,k.numLightProbes=A,Q.version=Jz++}function H(Y,G){let O=0,E=0,Z=0,D=0,R=0,I=G.matrixWorldInverse;for(let q=0,_=Y.length;q<_;q++){let P=Y[q];if(P.isDirectionalLight){let L=Q.directional[O];L.direction.setFromMatrixPosition(P.matrixWorld),W.setFromMatrixPosition(P.target.matrixWorld),L.direction.sub(W),L.direction.transformDirection(I),O++}else if(P.isSpotLight){let L=Q.spot[Z];L.position.setFromMatrixPosition(P.matrixWorld),L.position.applyMatrix4(I),L.direction.setFromMatrixPosition(P.matrixWorld),W.setFromMatrixPosition(P.target.matrixWorld),L.direction.sub(W),L.direction.transformDirection(I),Z++}else if(P.isRectAreaLight){let L=Q.rectArea[D];L.position.setFromMatrixPosition(P.matrixWorld),L.position.applyMatrix4(I),X.identity(),K.copy(P.matrixWorld),K.premultiply(I),X.extractRotation(K),L.halfWidth.set(P.width*0.5,0,0),L.halfHeight.set(0,P.height*0.5,0),L.halfWidth.applyMatrix4(X),L.halfHeight.applyMatrix4(X),D++}else if(P.isPointLight){let L=Q.point[E];L.position.setFromMatrixPosition(P.matrixWorld),L.position.applyMatrix4(I),E++}else if(P.isHemisphereLight){let L=Q.hemi[R];L.direction.setFromMatrixPosition(P.matrixWorld),L.direction.transformDirection(I),R++}}}return{setup:N,setupView:H,state:Q}}function N5($){let U=new Qz($),J=[],Q=[],W=[];function K(E){O.camera=E,J.length=0,Q.length=0,W.length=0}function X(E){J.push(E)}function N(E){Q.push(E)}function H(E){W.push(E)}function Y(){U.setup(J)}function G(E){U.setupView(J,E)}let O={lightsArray:J,shadowsArray:Q,lightProbeGridArray:W,camera:null,lights:U,transmissionRenderTarget:{},textureUnits:0};return{init:K,state:O,setupLights:Y,setupLightsView:G,pushLight:X,pushShadow:N,pushLightProbeGrid:H}}function Kz($){let U=new WeakMap;function J(W,K=0){let X=U.get(W),N;if(X===void 0)N=new N5($),U.set(W,[N]);else if(K>=X.length)N=new N5($),X.push(N);else N=X[K];return N}function Q(){U=new WeakMap}return{get:J,dispose:Q}}var Xz=`void main() {+Program Info Log: `+H+`+`+se+`+`+me)}else if(H!=="")Me("WebGLProgram: Program Info Log:",H);else if(V===""||U==="")Q=!1;if(Q)C.diagnostics={runnable:K,programLog:H,vertexShader:{log:V,prefix:p},fragmentShader:{log:U,prefix:m}}}r.deleteShader(w),r.deleteShader(E),_=new co(r,y),S=Yw(r,y)}let _;this.getUniforms=function(){if(_===void 0)R(this);return _};let S;this.getAttributes=function(){if(S===void 0)R(this);return S};let F=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){if(F===!1)F=r.getProgramParameter(y,kw);return F},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(y),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=Bw++,this.cacheKey=t,this.usedTimes=1,this.program=y,this.vertexShader=w,this.fragmentShader=E,this}var hT=0;class e0{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,n){let i=this._getShaderCacheForMaterial(e);if(i.has(t)===!1)i.add(t),t.usedTimes++;if(i.has(n)===!1)i.add(n),n.usedTimes++;return this}remove(e){let t=this.materialCache.get(e);for(let n of t)if(n.usedTimes--,n.usedTimes===0)this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);if(n===void 0)n=new Set,t.set(e,n);return n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);if(n===void 0)n=new t0(e),t.set(e,n);return n}}class t0{constructor(e){this.id=hT++,this.code=e,this.usedTimes=0}}function fT(e){return e===pr||e===wa||e===Ta}function dT(e,t,n,i,r,s){let o=new Ia,a=new e0,c=new Set,l=[],u=new Map,{logarithmicDepthBuffer:f,precision:h}=i,d={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(_){if(c.add(_),_===0)return"uv";return`uv${_}`}function y(_,S,F,C,z,J){let O=C.fog,H=z.geometry,V=_.isMeshStandardMaterial||_.isMeshLambertMaterial||_.isMeshPhongMaterial?C.environment:null,U=_.isMeshStandardMaterial||_.isMeshLambertMaterial&&!_.envMap||_.isMeshPhongMaterial&&!_.envMap,K=t.get(_.envMap||V,U),Q=!!K&&K.mapping===Hs?K.image.height:null,se=d[_.type];if(_.precision!==null){if(h=i.getMaxPrecision(_.precision),h!==_.precision)Me("WebGLProgram.getParameters:",_.precision,"not supported, using",h,"instead.")}let me=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,_e=me!==void 0?me.length:0,qe=0;if(H.morphAttributes.position!==void 0)qe=1;if(H.morphAttributes.normal!==void 0)qe=2;if(H.morphAttributes.color!==void 0)qe=3;let Ge,Z,ne,fe;if(se){let Fe=ei[se];Ge=Fe.vertexShader,Z=Fe.fragmentShader}else{Ge=_.vertexShader,Z=_.fragmentShader;let Fe=a.getVertexShaderStage(_),St=a.getFragmentShaderStage(_);a.update(_,Fe,St),ne=Fe.id,fe=St.id}let de=e.getRenderTarget(),Re=e.state.buffers.depth.getReversed(),Ze=z.isInstancedMesh===!0,Oe=z.isBatchedMesh===!0,ke=!!_.map,Ke=!!_.matcap,Ye=!!K,Je=!!_.aoMap,Ft=!!_.lightMap,gn=!!_.bumpMap&&_.wireframe===!1,mt=!!_.normalMap,Ht=!!_.displacementMap,zt=!!_.emissiveMap,Pt=!!_.metalnessMap,L=!!_.roughnessMap,_n=_.anisotropy>0,nt=_.clearcoat>0,gt=_.dispersion>0,M=_.iridescence>0,x=_.sheen>0,I=_.transmission>0,W=_n&&!!_.anisotropyMap,te=nt&&!!_.clearcoatMap,ie=nt&&!!_.clearcoatNormalMap,le=nt&&!!_.clearcoatRoughnessMap,X=M&&!!_.iridescenceMap,j=M&&!!_.iridescenceThicknessMap,xe=x&&!!_.sheenColorMap,we=x&&!!_.sheenRoughnessMap,ue=!!_.specularMap,re=!!_.specularColorMap,Ce=!!_.specularIntensityMap,Pe=I&&!!_.transmissionMap,et=I&&!!_.thicknessMap,P=!!_.gradientMap,oe=!!_.alphaMap,Y=_.alphaTest>0,ae=!!_.alphaHash,ve=!!_.extensions,ee=Un;if(_.toneMapped){if(de===null||de.isXRRenderTarget===!0)ee=e.toneMapping}let ce={shaderID:se,shaderType:_.type,shaderName:_.name,vertexShader:Ge,fragmentShader:Z,defines:_.defines,customVertexShaderID:ne,customFragmentShaderID:fe,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:h,batching:Oe,batchingColor:Oe&&z._colorsTexture!==null,instancing:Ze,instancingColor:Ze&&z.instanceColor!==null,instancingMorph:Ze&&z.morphTexture!==null,outputColorSpace:de===null?e.outputColorSpace:de.isXRRenderTarget===!0?de.texture.colorSpace:We.workingColorSpace,alphaToCoverage:!!_.alphaToCoverage,map:ke,matcap:Ke,envMap:Ye,envMapMode:Ye&&K.mapping,envMapCubeUVHeight:Q,aoMap:Je,lightMap:Ft,bumpMap:gn,normalMap:mt,displacementMap:Ht,emissiveMap:zt,normalMapObjectSpace:mt&&_.normalMapType===r_,normalMapTangentSpace:mt&&_.normalMapType===xu,packedNormalMap:mt&&_.normalMapType===xu&&fT(_.normalMap.format),metalnessMap:Pt,roughnessMap:L,anisotropy:_n,anisotropyMap:W,clearcoat:nt,clearcoatMap:te,clearcoatNormalMap:ie,clearcoatRoughnessMap:le,dispersion:gt,iridescence:M,iridescenceMap:X,iridescenceThicknessMap:j,sheen:x,sheenColorMap:xe,sheenRoughnessMap:we,specularMap:ue,specularColorMap:re,specularIntensityMap:Ce,transmission:I,transmissionMap:Pe,thicknessMap:et,gradientMap:P,opaque:_.transparent===!1&&_.blending===Bs&&_.alphaToCoverage===!1,alphaMap:oe,alphaTest:Y,alphaHash:ae,combine:_.combine,mapUv:ke&&g(_.map.channel),aoMapUv:Je&&g(_.aoMap.channel),lightMapUv:Ft&&g(_.lightMap.channel),bumpMapUv:gn&&g(_.bumpMap.channel),normalMapUv:mt&&g(_.normalMap.channel),displacementMapUv:Ht&&g(_.displacementMap.channel),emissiveMapUv:zt&&g(_.emissiveMap.channel),metalnessMapUv:Pt&&g(_.metalnessMap.channel),roughnessMapUv:L&&g(_.roughnessMap.channel),anisotropyMapUv:W&&g(_.anisotropyMap.channel),clearcoatMapUv:te&&g(_.clearcoatMap.channel),clearcoatNormalMapUv:ie&&g(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:le&&g(_.clearcoatRoughnessMap.channel),iridescenceMapUv:X&&g(_.iridescenceMap.channel),iridescenceThicknessMapUv:j&&g(_.iridescenceThicknessMap.channel),sheenColorMapUv:xe&&g(_.sheenColorMap.channel),sheenRoughnessMapUv:we&&g(_.sheenRoughnessMap.channel),specularMapUv:ue&&g(_.specularMap.channel),specularColorMapUv:re&&g(_.specularColorMap.channel),specularIntensityMapUv:Ce&&g(_.specularIntensityMap.channel),transmissionMapUv:Pe&&g(_.transmissionMap.channel),thicknessMapUv:et&&g(_.thicknessMap.channel),alphaMapUv:oe&&g(_.alphaMap.channel),vertexTangents:!!H.attributes.tangent&&(mt||_n),vertexNormals:!!H.attributes.normal,vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,pointsUvs:z.isPoints===!0&&!!H.attributes.uv&&(ke||oe),fog:!!O,useFog:_.fog===!0,fogExp2:!!O&&O.isFogExp2,flatShading:_.wireframe===!1&&(_.flatShading===!0||H.attributes.normal===void 0&&mt===!1&&(_.isMeshLambertMaterial||_.isMeshPhongMaterial||_.isMeshStandardMaterial||_.isMeshPhysicalMaterial)),sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:f,reversedDepthBuffer:Re,skinning:z.isSkinnedMesh===!0,hasPositionAttribute:H.attributes.position!==void 0,morphTargets:H.morphAttributes.position!==void 0,morphNormals:H.morphAttributes.normal!==void 0,morphColors:H.morphAttributes.color!==void 0,morphTargetsCount:_e,morphTextureStride:qe,numDirLights:S.directional.length,numPointLights:S.point.length,numSpotLights:S.spot.length,numSpotLightMaps:S.spotLightMap.length,numRectAreaLights:S.rectArea.length,numHemiLights:S.hemi.length,numDirLightShadows:S.directionalShadowMap.length,numPointLightShadows:S.pointShadowMap.length,numSpotLightShadows:S.spotShadowMap.length,numSpotLightShadowsWithMaps:S.numSpotLightShadowsWithMaps,numLightProbes:S.numLightProbes,numLightProbeGrids:J.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:_.dithering,shadowMapEnabled:e.shadowMap.enabled&&F.length>0,shadowMapType:e.shadowMap.type,toneMapping:ee,decodeVideoTexture:ke&&_.map.isVideoTexture===!0&&We.getTransfer(_.map.colorSpace)===ht,decodeVideoTextureEmissive:zt&&_.emissiveMap.isVideoTexture===!0&&We.getTransfer(_.emissiveMap.colorSpace)===ht,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===bn,flipSided:_.side===Yt,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionClipCullDistance:ve&&_.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ve&&_.extensions.multiDraw===!0||Oe)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()};return ce.vertexUv1s=c.has(1),ce.vertexUv2s=c.has(2),ce.vertexUv3s=c.has(3),c.clear(),ce}function p(_){let S=[];if(_.shaderID)S.push(_.shaderID);else S.push(_.customVertexShaderID),S.push(_.customFragmentShaderID);if(_.defines!==void 0)for(let F in _.defines)S.push(F),S.push(_.defines[F]);if(_.isRawShaderMaterial===!1)m(S,_),A(S,_),S.push(e.outputColorSpace);return S.push(_.customProgramCacheKey),S.join()}function m(_,S){_.push(S.precision),_.push(S.outputColorSpace),_.push(S.envMapMode),_.push(S.envMapCubeUVHeight),_.push(S.mapUv),_.push(S.alphaMapUv),_.push(S.lightMapUv),_.push(S.aoMapUv),_.push(S.bumpMapUv),_.push(S.normalMapUv),_.push(S.displacementMapUv),_.push(S.emissiveMapUv),_.push(S.metalnessMapUv),_.push(S.roughnessMapUv),_.push(S.anisotropyMapUv),_.push(S.clearcoatMapUv),_.push(S.clearcoatNormalMapUv),_.push(S.clearcoatRoughnessMapUv),_.push(S.iridescenceMapUv),_.push(S.iridescenceThicknessMapUv),_.push(S.sheenColorMapUv),_.push(S.sheenRoughnessMapUv),_.push(S.specularMapUv),_.push(S.specularColorMapUv),_.push(S.specularIntensityMapUv),_.push(S.transmissionMapUv),_.push(S.thicknessMapUv),_.push(S.combine),_.push(S.fogExp2),_.push(S.sizeAttenuation),_.push(S.morphTargetsCount),_.push(S.morphAttributeCount),_.push(S.numDirLights),_.push(S.numPointLights),_.push(S.numSpotLights),_.push(S.numSpotLightMaps),_.push(S.numHemiLights),_.push(S.numRectAreaLights),_.push(S.numDirLightShadows),_.push(S.numPointLightShadows),_.push(S.numSpotLightShadows),_.push(S.numSpotLightShadowsWithMaps),_.push(S.numLightProbes),_.push(S.shadowMapType),_.push(S.toneMapping),_.push(S.numClippingPlanes),_.push(S.numClipIntersection),_.push(S.depthPacking)}function A(_,S){if(o.disableAll(),S.instancing)o.enable(0);if(S.instancingColor)o.enable(1);if(S.instancingMorph)o.enable(2);if(S.matcap)o.enable(3);if(S.envMap)o.enable(4);if(S.normalMapObjectSpace)o.enable(5);if(S.normalMapTangentSpace)o.enable(6);if(S.clearcoat)o.enable(7);if(S.iridescence)o.enable(8);if(S.alphaTest)o.enable(9);if(S.vertexColors)o.enable(10);if(S.vertexAlphas)o.enable(11);if(S.vertexUv1s)o.enable(12);if(S.vertexUv2s)o.enable(13);if(S.vertexUv3s)o.enable(14);if(S.vertexTangents)o.enable(15);if(S.anisotropy)o.enable(16);if(S.alphaHash)o.enable(17);if(S.batching)o.enable(18);if(S.dispersion)o.enable(19);if(S.batchingColor)o.enable(20);if(S.gradientMap)o.enable(21);if(S.packedNormalMap)o.enable(22);if(S.vertexNormals)o.enable(23);if(_.push(o.mask),o.disableAll(),S.fog)o.enable(0);if(S.useFog)o.enable(1);if(S.flatShading)o.enable(2);if(S.logarithmicDepthBuffer)o.enable(3);if(S.reversedDepthBuffer)o.enable(4);if(S.skinning)o.enable(5);if(S.morphTargets)o.enable(6);if(S.morphNormals)o.enable(7);if(S.morphColors)o.enable(8);if(S.premultipliedAlpha)o.enable(9);if(S.shadowMapEnabled)o.enable(10);if(S.doubleSided)o.enable(11);if(S.flipSided)o.enable(12);if(S.useDepthPacking)o.enable(13);if(S.dithering)o.enable(14);if(S.transmission)o.enable(15);if(S.sheen)o.enable(16);if(S.opaque)o.enable(17);if(S.pointsUvs)o.enable(18);if(S.decodeVideoTexture)o.enable(19);if(S.decodeVideoTextureEmissive)o.enable(20);if(S.alphaToCoverage)o.enable(21);if(S.numLightProbeGrids>0)o.enable(22);if(S.hasPositionAttribute)o.enable(23);_.push(o.mask)}function T(_){let S=d[_.type],F;if(S){let C=ei[S];F=g_.clone(C.uniforms)}else F=_.uniforms;return F}function v(_,S){let F=u.get(S);if(F!==void 0)++F.usedTimes;else F=new uT(e,S,_,r),l.push(F),u.set(S,F);return F}function w(_){if(--_.usedTimes===0){let S=l.indexOf(_);l[S]=l[l.length-1],l.pop(),u.delete(_.cacheKey),_.destroy()}}function E(_){a.remove(_)}function R(){a.dispose()}return{getParameters:y,getProgramCacheKey:p,getUniforms:T,acquireProgram:v,releaseProgram:w,releaseShaderCache:E,programs:l,dispose:R}}function pT(){let e=new WeakMap;function t(o){return e.has(o)}function n(o){let a=e.get(o);if(a===void 0)a={},e.set(o,a);return a}function i(o){e.delete(o)}function r(o,a,c){e.get(o)[a]=c}function s(){e=new WeakMap}return{has:t,get:n,remove:i,update:r,dispose:s}}function mT(e,t){if(e.groupOrder!==t.groupOrder)return e.groupOrder-t.groupOrder;else if(e.renderOrder!==t.renderOrder)return e.renderOrder-t.renderOrder;else if(e.material.id!==t.material.id)return e.material.id-t.material.id;else if(e.materialVariant!==t.materialVariant)return e.materialVariant-t.materialVariant;else if(e.z!==t.z)return e.z-t.z;else return e.id-t.id}function G_(e,t){if(e.groupOrder!==t.groupOrder)return e.groupOrder-t.groupOrder;else if(e.renderOrder!==t.renderOrder)return e.renderOrder-t.renderOrder;else if(e.z!==t.z)return t.z-e.z;else return e.id-t.id}function H_(){let e=[],t=0,n=[],i=[],r=[];function s(){t=0,n.length=0,i.length=0,r.length=0}function o(h){let d=0;if(h.isInstancedMesh)d+=2;if(h.isSkinnedMesh)d+=1;return d}function a(h,d,g,y,p,m){let A=e[t];if(A===void 0)A={id:h.id,object:h,geometry:d,material:g,materialVariant:o(h),groupOrder:y,renderOrder:h.renderOrder,z:p,group:m},e[t]=A;else A.id=h.id,A.object=h,A.geometry=d,A.material=g,A.materialVariant=o(h),A.groupOrder=y,A.renderOrder=h.renderOrder,A.z=p,A.group=m;return t++,A}function c(h,d,g,y,p,m){let A=a(h,d,g,y,p,m);if(g.transmission>0)i.push(A);else if(g.transparent===!0)r.push(A);else n.push(A)}function l(h,d,g,y,p,m){let A=a(h,d,g,y,p,m);if(g.transmission>0)i.unshift(A);else if(g.transparent===!0)r.unshift(A);else n.unshift(A)}function u(h,d,g){if(n.length>1)n.sort(h||mT);if(i.length>1)i.sort(d||G_);if(r.length>1)r.sort(d||G_);if(g)n.reverse(),i.reverse(),r.reverse()}function f(){for(let h=t,d=e.length;h<d;h++){let g=e[h];if(g.id===null)break;g.id=null,g.object=null,g.geometry=null,g.material=null,g.group=null}}return{opaque:n,transmissive:i,transparent:r,init:s,push:c,unshift:l,finish:f,sort:u}}function gT(){let e=new WeakMap;function t(i,r){let s=e.get(i),o;if(s===void 0)o=new H_,e.set(i,[o]);else if(r>=s.length)o=new H_,s.push(o);else o=s[r];return o}function n(){e=new WeakMap}return{get:t,dispose:n}}function _T(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new N,color:new Le};break;case"SpotLight":n={position:new N,direction:new N,color:new Le,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new N,color:new Le,distance:0,decay:0};break;case"HemisphereLight":n={direction:new N,skyColor:new Le,groundColor:new Le};break;case"RectAreaLight":n={color:new Le,position:new N,halfWidth:new N,halfHeight:new N};break}return e[t.id]=n,n}}}function xT(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ie};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ie};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ie,shadowCameraNear:1,shadowCameraFar:1000};break}return e[t.id]=n,n}}}var vT=0;function yT(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function bT(e){let t=new _T,n=xT(),i={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 l=0;l<9;l++)i.probe.push(new N);let r=new N,s=new ze,o=new ze;function a(l){let u=0,f=0,h=0;for(let S=0;S<9;S++)i.probe[S].set(0,0,0);let d=0,g=0,y=0,p=0,m=0,A=0,T=0,v=0,w=0,E=0,R=0;l.sort(yT);for(let S=0,F=l.length;S<F;S++){let C=l[S],{color:z,intensity:J,distance:O}=C,H=null;if(C.shadow&&C.shadow.map)if(C.shadow.map.texture.format===pr)H=C.shadow.map.texture;else H=C.shadow.map.depthTexture||C.shadow.map.texture;if(C.isAmbientLight)u+=z.r*J,f+=z.g*J,h+=z.b*J;else if(C.isLightProbe){for(let V=0;V<9;V++)i.probe[V].addScaledVector(C.sh.coefficients[V],J);R++}else if(C.isDirectionalLight){let V=t.get(C);if(V.color.copy(C.color).multiplyScalar(C.intensity),C.castShadow){let U=C.shadow,K=n.get(C);K.shadowIntensity=U.intensity,K.shadowBias=U.bias,K.shadowNormalBias=U.normalBias,K.shadowRadius=U.radius,K.shadowMapSize=U.mapSize,i.directionalShadow[d]=K,i.directionalShadowMap[d]=H,i.directionalShadowMatrix[d]=C.shadow.matrix,A++}i.directional[d]=V,d++}else if(C.isSpotLight){let V=t.get(C);V.position.setFromMatrixPosition(C.matrixWorld),V.color.copy(z).multiplyScalar(J),V.distance=O,V.coneCos=Math.cos(C.angle),V.penumbraCos=Math.cos(C.angle*(1-C.penumbra)),V.decay=C.decay,i.spot[y]=V;let U=C.shadow;if(C.map){if(i.spotLightMap[w]=C.map,w++,U.updateMatrices(C),C.castShadow)E++}if(i.spotLightMatrix[y]=U.matrix,C.castShadow){let K=n.get(C);K.shadowIntensity=U.intensity,K.shadowBias=U.bias,K.shadowNormalBias=U.normalBias,K.shadowRadius=U.radius,K.shadowMapSize=U.mapSize,i.spotShadow[y]=K,i.spotShadowMap[y]=H,v++}y++}else if(C.isRectAreaLight){let V=t.get(C);V.color.copy(z).multiplyScalar(J),V.halfWidth.set(C.width*0.5,0,0),V.halfHeight.set(0,C.height*0.5,0),i.rectArea[p]=V,p++}else if(C.isPointLight){let V=t.get(C);if(V.color.copy(C.color).multiplyScalar(C.intensity),V.distance=C.distance,V.decay=C.decay,C.castShadow){let U=C.shadow,K=n.get(C);K.shadowIntensity=U.intensity,K.shadowBias=U.bias,K.shadowNormalBias=U.normalBias,K.shadowRadius=U.radius,K.shadowMapSize=U.mapSize,K.shadowCameraNear=U.camera.near,K.shadowCameraFar=U.camera.far,i.pointShadow[g]=K,i.pointShadowMap[g]=H,i.pointShadowMatrix[g]=C.shadow.matrix,T++}i.point[g]=V,g++}else if(C.isHemisphereLight){let V=t.get(C);V.skyColor.copy(C.color).multiplyScalar(J),V.groundColor.copy(C.groundColor).multiplyScalar(J),i.hemi[m]=V,m++}}if(p>0)if(e.has("OES_texture_float_linear")===!0)i.rectAreaLTC1=he.LTC_FLOAT_1,i.rectAreaLTC2=he.LTC_FLOAT_2;else i.rectAreaLTC1=he.LTC_HALF_1,i.rectAreaLTC2=he.LTC_HALF_2;i.ambient[0]=u,i.ambient[1]=f,i.ambient[2]=h;let _=i.hash;if(_.directionalLength!==d||_.pointLength!==g||_.spotLength!==y||_.rectAreaLength!==p||_.hemiLength!==m||_.numDirectionalShadows!==A||_.numPointShadows!==T||_.numSpotShadows!==v||_.numSpotMaps!==w||_.numLightProbes!==R)i.directional.length=d,i.spot.length=y,i.rectArea.length=p,i.point.length=g,i.hemi.length=m,i.directionalShadow.length=A,i.directionalShadowMap.length=A,i.pointShadow.length=T,i.pointShadowMap.length=T,i.spotShadow.length=v,i.spotShadowMap.length=v,i.directionalShadowMatrix.length=A,i.pointShadowMatrix.length=T,i.spotLightMatrix.length=v+w-E,i.spotLightMap.length=w,i.numSpotLightShadowsWithMaps=E,i.numLightProbes=R,_.directionalLength=d,_.pointLength=g,_.spotLength=y,_.rectAreaLength=p,_.hemiLength=m,_.numDirectionalShadows=A,_.numPointShadows=T,_.numSpotShadows=v,_.numSpotMaps=w,_.numLightProbes=R,i.version=vT++}function c(l,u){let f=0,h=0,d=0,g=0,y=0,p=u.matrixWorldInverse;for(let m=0,A=l.length;m<A;m++){let T=l[m];if(T.isDirectionalLight){let v=i.directional[f];v.direction.setFromMatrixPosition(T.matrixWorld),r.setFromMatrixPosition(T.target.matrixWorld),v.direction.sub(r),v.direction.transformDirection(p),f++}else if(T.isSpotLight){let v=i.spot[d];v.position.setFromMatrixPosition(T.matrixWorld),v.position.applyMatrix4(p),v.direction.setFromMatrixPosition(T.matrixWorld),r.setFromMatrixPosition(T.target.matrixWorld),v.direction.sub(r),v.direction.transformDirection(p),d++}else if(T.isRectAreaLight){let v=i.rectArea[g];v.position.setFromMatrixPosition(T.matrixWorld),v.position.applyMatrix4(p),o.identity(),s.copy(T.matrixWorld),s.premultiply(p),o.extractRotation(s),v.halfWidth.set(T.width*0.5,0,0),v.halfHeight.set(0,T.height*0.5,0),v.halfWidth.applyMatrix4(o),v.halfHeight.applyMatrix4(o),g++}else if(T.isPointLight){let v=i.point[h];v.position.setFromMatrixPosition(T.matrixWorld),v.position.applyMatrix4(p),h++}else if(T.isHemisphereLight){let v=i.hemi[y];v.direction.setFromMatrixPosition(T.matrixWorld),v.direction.transformDirection(p),y++}}}return{setup:a,setupView:c,state:i}}function V_(e){let t=new bT(e),n=[],i=[],r=[];function s(h){f.camera=h,n.length=0,i.length=0,r.length=0}function o(h){n.push(h)}function a(h){i.push(h)}function c(h){r.push(h)}function l(){t.setup(n)}function u(h){t.setupView(n,h)}let f={lightsArray:n,shadowsArray:i,lightProbeGridArray:r,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:f,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:a,pushLightProbeGrid:c}}function ST(e){let t=new WeakMap;function n(r,s=0){let o=t.get(r),a;if(o===void 0)a=new V_(e),t.set(r,[a]);else if(s>=o.length)a=new V_(e),o.push(a);else a=o[s];return a}function i(){t=new WeakMap}return{get:n,dispose:i}}var MT=`void main() {gl_Position = vec4( position, 1.0 );-}`,Nz=`uniform sampler2D shadow_pass;+}`,wT=`uniform sampler2D shadow_pass;uniform vec2 resolution;uniform float radius;void main() {@@ -4150,12 +4149,12 @@ void main() {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 );-}`,Hz=[new j(1,0,0),new j(-1,0,0),new j(0,1,0),new j(0,-1,0),new j(0,0,1),new j(0,0,-1)],Yz=[new j(0,-1,0),new j(0,-1,0),new j(0,0,1),new j(0,0,-1),new j(0,-1,0),new j(0,-1,0)],H5=new p$,gQ=new j,$Z=new j;function Gz($,U,J){let Q=new zQ,W=new g$,K=new g$,X=new Z6,N=new gE,H=new bE,Y={},G=J.maxTextureSize,O={[K0]:JU,[JU]:K0,[bU]:bU},E=new yU({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new g$},radius:{value:4}},vertexShader:Xz,fragmentShader:Nz}),Z=E.clone();Z.defines.HORIZONTAL_PASS=1;let D=new OU;D.setAttribute("position",new u6(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));let R=new P6(D,E),I=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=ZQ;let q=this.type;this.render=function(z,A,k){if(I.enabled===!1)return;if(I.autoUpdate===!1&&I.needsUpdate===!1)return;if(z.length===0)return;if(this.type===hD)A$("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=ZQ;let w=$.getRenderTarget(),h=$.getActiveCubeFace(),C=$.getActiveMipmapLevel(),f=$.state;if(f.setBlending(EJ),f.buffers.depth.getReversed()===!0)f.buffers.color.setClear(0,0,0,0);else f.buffers.color.setClear(1,1,1,1);f.buffers.depth.setTest(!0),f.setScissorTest(!1);let s=q!==this.type;if(s)A.traverse(function(y){if(y.material)if(Array.isArray(y.material))y.material.forEach((d)=>d.needsUpdate=!0);else y.material.needsUpdate=!0});for(let y=0,d=z.length;y<d;y++){let c=z[y],x=c.shadow;if(x===void 0){A$("WebGLShadowMap:",c,"has no shadow.");continue}if(x.autoUpdate===!1&&x.needsUpdate===!1)continue;W.copy(x.mapSize);let t=x.getFrameExtents();if(W.multiply(t),K.copy(x.mapSize),W.x>G||W.y>G){if(W.x>G)K.x=Math.floor(G/t.x),W.x=K.x*t.x,x.mapSize.x=K.x;if(W.y>G)K.y=Math.floor(G/t.y),W.y=K.y*t.y,x.mapSize.y=K.y}let e=$.state.buffers.depth.getReversed();if(x.camera._reversedDepth=e,x.map===null||s===!0){if(x.map!==null){if(x.map.depthTexture!==null)x.map.depthTexture.dispose(),x.map.depthTexture=null;x.map.dispose()}if(this.type===rW){if(c.isPointLight){A$("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}x.map=new xU(W.x,W.y,{format:m0,type:gJ,minFilter:o6,magFilter:o6,generateMipmaps:!1}),x.map.texture.name=c.name+".shadowMap",x.map.depthTexture=new G0(W.x,W.y,jJ),x.map.depthTexture.name=c.name+".shadowMapDepth",x.map.depthTexture.format=u0,x.map.depthTexture.compareFunction=null,x.map.depthTexture.minFilter=rU,x.map.depthTexture.magFilter=rU}else{if(c.isPointLight)x.map=new WZ(W.x),x.map.depthTexture=new TE(W.x,X0);else x.map=new xU(W.x,W.y),x.map.depthTexture=new G0(W.x,W.y,X0);if(x.map.depthTexture.name=c.name+".shadowMap",x.map.depthTexture.format=u0,this.type===ZQ)x.map.depthTexture.compareFunction=e?E7:O7,x.map.depthTexture.minFilter=o6,x.map.depthTexture.magFilter=o6;else x.map.depthTexture.compareFunction=null,x.map.depthTexture.minFilter=rU,x.map.depthTexture.magFilter=rU}x.camera.updateProjectionMatrix()}let Y$=x.map.isWebGLCubeRenderTarget?6:1;for(let R$=0;R$<Y$;R$++){if(x.map.isWebGLCubeRenderTarget)$.setRenderTarget(x.map,R$),$.clear();else{if(R$===0)$.setRenderTarget(x.map),$.clear();let w$=x.getViewport(R$);X.set(K.x*w$.x,K.y*w$.y,K.x*w$.z,K.y*w$.w),f.viewport(X)}if(c.isPointLight){let{camera:w$,matrix:U6}=x,i$=c.distance||w$.far;if(i$!==w$.far)w$.far=i$,w$.updateProjectionMatrix();gQ.setFromMatrixPosition(c.matrixWorld),w$.position.copy(gQ),$Z.copy(w$.position),$Z.add(Hz[R$]),w$.up.copy(Yz[R$]),w$.lookAt($Z),w$.updateMatrixWorld(),U6.makeTranslation(-gQ.x,-gQ.y,-gQ.z),H5.multiplyMatrices(w$.projectionMatrix,w$.matrixWorldInverse),x._frustum.setFromProjectionMatrix(H5,w$.coordinateSystem,w$.reversedDepth)}else x.updateMatrices(c);Q=x.getFrustum(),L(A,k,x.camera,c,this.type)}if(x.isPointLightShadow!==!0&&this.type===rW)_(x,k);x.needsUpdate=!1}q=this.type,I.needsUpdate=!1,$.setRenderTarget(w,h,C)};function _(z,A){let k=U.update(R);if(E.defines.VSM_SAMPLES!==z.blurSamples)E.defines.VSM_SAMPLES=z.blurSamples,Z.defines.VSM_SAMPLES=z.blurSamples,E.needsUpdate=!0,Z.needsUpdate=!0;if(z.mapPass===null)z.mapPass=new xU(W.x,W.y,{format:m0,type:gJ});E.uniforms.shadow_pass.value=z.map.depthTexture,E.uniforms.resolution.value=z.mapSize,E.uniforms.radius.value=z.radius,$.setRenderTarget(z.mapPass),$.clear(),$.renderBufferDirect(A,null,k,E,R,null),Z.uniforms.shadow_pass.value=z.mapPass.texture,Z.uniforms.resolution.value=z.mapSize,Z.uniforms.radius.value=z.radius,$.setRenderTarget(z.map),$.clear(),$.renderBufferDirect(A,null,k,Z,R,null)}function P(z,A,k,w){let h=null,C=k.isPointLight===!0?z.customDistanceMaterial:z.customDepthMaterial;if(C!==void 0)h=C;else if(h=k.isPointLight===!0?H:N,$.localClippingEnabled&&A.clipShadows===!0&&Array.isArray(A.clippingPlanes)&&A.clippingPlanes.length!==0||A.displacementMap&&A.displacementScale!==0||A.alphaMap&&A.alphaTest>0||A.map&&A.alphaTest>0||A.alphaToCoverage===!0){let f=h.uuid,s=A.uuid,y=Y[f];if(y===void 0)y={},Y[f]=y;let d=y[s];if(d===void 0)d=h.clone(),y[s]=d,A.addEventListener("dispose",B);h=d}if(h.visible=A.visible,h.wireframe=A.wireframe,w===rW)h.side=A.shadowSide!==null?A.shadowSide:A.side;else h.side=A.shadowSide!==null?A.shadowSide:O[A.side];if(h.alphaMap=A.alphaMap,h.alphaTest=A.alphaToCoverage===!0?0.5:A.alphaTest,h.map=A.map,h.clipShadows=A.clipShadows,h.clippingPlanes=A.clippingPlanes,h.clipIntersection=A.clipIntersection,h.displacementMap=A.displacementMap,h.displacementScale=A.displacementScale,h.displacementBias=A.displacementBias,h.wireframeLinewidth=A.wireframeLinewidth,h.linewidth=A.linewidth,k.isPointLight===!0&&h.isMeshDistanceMaterial===!0){let f=$.properties.get(h);f.light=k}return h}function L(z,A,k,w,h){if(z.visible===!1)return;if(z.layers.test(A.layers)&&(z.isMesh||z.isLine||z.isPoints)){if((z.castShadow||z.receiveShadow&&h===rW)&&(!z.frustumCulled||Q.intersectsObject(z))){z.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,z.matrixWorld);let s=U.update(z),y=z.material;if(Array.isArray(y)){let d=s.groups;for(let c=0,x=d.length;c<x;c++){let t=d[c],e=y[t.materialIndex];if(e&&e.visible){let Y$=P(z,e,w,h);z.onBeforeShadow($,z,A,k,s,Y$,t),$.renderBufferDirect(k,null,s,Y$,z,t),z.onAfterShadow($,z,A,k,s,Y$,t)}}}else if(y.visible){let d=P(z,y,w,h);z.onBeforeShadow($,z,A,k,s,d,null),$.renderBufferDirect(k,null,s,d,z,null),z.onAfterShadow($,z,A,k,s,d,null)}}}let f=z.children;for(let s=0,y=f.length;s<y;s++)L(f[s],A,k,w,h)}function B(z){z.target.removeEventListener("dispose",B);for(let k in Y){let w=Y[k],h=z.target.uuid;if(h in w)w[h].dispose(),delete w[h]}}}function Oz($,U){function J(){let T=!1,G$=new Z6,r=null,O$=new Z6(0,0,0,0);return{setMask:function(B$){if(r!==B$&&!T)$.colorMask(B$,B$,B$,B$),r=B$},setLocked:function(B$){T=B$},setClear:function(B$,$$,E$,m$,C6){if(C6===!0)B$*=m$,$$*=m$,E$*=m$;if(G$.set(B$,$$,E$,m$),O$.equals(G$)===!1)$.clearColor(B$,$$,E$,m$),O$.copy(G$)},reset:function(){T=!1,r=null,O$.set(-1,0,0,0)}}}function Q(){let T=!1,G$=!1,r=null,O$=null,B$=null;return{setReversed:function($$){if(G$!==$$){let E$=U.get("EXT_clip_control");if($$)E$.clipControlEXT(E$.LOWER_LEFT_EXT,E$.ZERO_TO_ONE_EXT);else E$.clipControlEXT(E$.LOWER_LEFT_EXT,E$.NEGATIVE_ONE_TO_ONE_EXT);G$=$$;let m$=B$;B$=null,this.setClear(m$)}},getReversed:function(){return G$},setTest:function($$){if($$)F$($.DEPTH_TEST);else v$($.DEPTH_TEST)},setMask:function($$){if(r!==$$&&!T)$.depthMask($$),r=$$},setFunc:function($$){if(G$)$$=vk[$$];if(O$!==$$){switch($$){case Kk:$.depthFunc($.NEVER);break;case Xk:$.depthFunc($.ALWAYS);break;case Nk:$.depthFunc($.LESS);break;case vO:$.depthFunc($.LEQUAL);break;case Hk:$.depthFunc($.EQUAL);break;case Yk:$.depthFunc($.GEQUAL);break;case Gk:$.depthFunc($.GREATER);break;case Ok:$.depthFunc($.NOTEQUAL);break;default:$.depthFunc($.LEQUAL)}O$=$$}},setLocked:function($$){T=$$},setClear:function($$){if(B$!==$$){if(B$=$$,G$)$$=1-$$;$.clearDepth($$)}},reset:function(){T=!1,r=null,O$=null,B$=null,G$=!1}}}function W(){let T=!1,G$=null,r=null,O$=null,B$=null,$$=null,E$=null,m$=null,C6=null;return{setTest:function(M6){if(!T)if(M6)F$($.STENCIL_TEST);else v$($.STENCIL_TEST)},setMask:function(M6){if(G$!==M6&&!T)$.stencilMask(M6),G$=M6},setFunc:function(M6,tU,LJ){if(r!==M6||O$!==tU||B$!==LJ)$.stencilFunc(M6,tU,LJ),r=M6,O$=tU,B$=LJ},setOp:function(M6,tU,LJ){if($$!==M6||E$!==tU||m$!==LJ)$.stencilOp(M6,tU,LJ),$$=M6,E$=tU,m$=LJ},setLocked:function(M6){T=M6},setClear:function(M6){if(C6!==M6)$.clearStencil(M6),C6=M6},reset:function(){T=!1,G$=null,r=null,O$=null,B$=null,$$=null,E$=null,m$=null,C6=null}}}let K=new J,X=new Q,N=new W,H=new WeakMap,Y=new WeakMap,G={},O={},E={},Z=new WeakMap,D=[],R=null,I=!1,q=null,_=null,P=null,L=null,B=null,z=null,A=null,k=new x$(0,0,0),w=0,h=!1,C=null,f=null,s=null,y=null,d=null,c=$.getParameter($.MAX_COMBINED_TEXTURE_IMAGE_UNITS),x=!1,t=0,e=$.getParameter($.VERSION);if(e.indexOf("WebGL")!==-1)t=parseFloat(/^WebGL (\d)/.exec(e)[1]),x=t>=1;else if(e.indexOf("OpenGL ES")!==-1)t=parseFloat(/^OpenGL ES (\d)/.exec(e)[1]),x=t>=2;let Y$=null,R$={},w$=$.getParameter($.SCISSOR_BOX),U6=$.getParameter($.VIEWPORT),i$=new Z6().fromArray(w$),i=new Z6().fromArray(U6);function X$(T,G$,r,O$){let B$=new Uint8Array(4),$$=$.createTexture();$.bindTexture(T,$$),$.texParameteri(T,$.TEXTURE_MIN_FILTER,$.NEAREST),$.texParameteri(T,$.TEXTURE_MAG_FILTER,$.NEAREST);for(let E$=0;E$<r;E$++)if(T===$.TEXTURE_3D||T===$.TEXTURE_2D_ARRAY)$.texImage3D(G$,0,$.RGBA,1,1,O$,0,$.RGBA,$.UNSIGNED_BYTE,B$);else $.texImage2D(G$+E$,0,$.RGBA,1,1,0,$.RGBA,$.UNSIGNED_BYTE,B$);return $$}let k$={};k$[$.TEXTURE_2D]=X$($.TEXTURE_2D,$.TEXTURE_2D,1),k$[$.TEXTURE_CUBE_MAP]=X$($.TEXTURE_CUBE_MAP,$.TEXTURE_CUBE_MAP_POSITIVE_X,6),k$[$.TEXTURE_2D_ARRAY]=X$($.TEXTURE_2D_ARRAY,$.TEXTURE_2D_ARRAY,1,1),k$[$.TEXTURE_3D]=X$($.TEXTURE_3D,$.TEXTURE_3D,1,1),K.setClear(0,0,0,1),X.setClear(1),N.setClear(0),F$($.DEPTH_TEST),X.setFunc(vO),CU(!1),z6(AO),F$($.CULL_FACE),K6(EJ);function F$(T){if(G[T]!==!0)$.enable(T),G[T]=!0}function v$(T){if(G[T]!==!1)$.disable(T),G[T]=!1}function e$(T,G$){if(E[T]!==G$){if($.bindFramebuffer(T,G$),E[T]=G$,T===$.DRAW_FRAMEBUFFER)E[$.FRAMEBUFFER]=G$;if(T===$.FRAMEBUFFER)E[$.DRAW_FRAMEBUFFER]=G$;return!0}return!1}function l$(T,G$){let r=D,O$=!1;if(T){if(r=Z.get(G$),r===void 0)r=[],Z.set(G$,r);let B$=T.textures;if(r.length!==B$.length||r[0]!==$.COLOR_ATTACHMENT0){for(let $$=0,E$=B$.length;$$<E$;$$++)r[$$]=$.COLOR_ATTACHMENT0+$$;r.length=B$.length,O$=!0}}else if(r[0]!==$.BACK)r[0]=$.BACK,O$=!0;if(O$)$.drawBuffers(r)}function d$(T){if(R!==T)return $.useProgram(T),R=T,!0;return!1}let X6={[aW]:$.FUNC_ADD,[uD]:$.FUNC_SUBTRACT,[lD]:$.FUNC_REVERSE_SUBTRACT};X6[mD]=$.MIN,X6[pD]=$.MAX;let J6={[dD]:$.ZERO,[cD]:$.ONE,[nD]:$.SRC_COLOR,[oD]:$.SRC_ALPHA,[$k]:$.SRC_ALPHA_SATURATE,[tD]:$.DST_COLOR,[aD]:$.DST_ALPHA,[iD]:$.ONE_MINUS_SRC_COLOR,[rD]:$.ONE_MINUS_SRC_ALPHA,[eD]:$.ONE_MINUS_DST_COLOR,[sD]:$.ONE_MINUS_DST_ALPHA,[Uk]:$.CONSTANT_COLOR,[Jk]:$.ONE_MINUS_CONSTANT_COLOR,[Wk]:$.CONSTANT_ALPHA,[Qk]:$.ONE_MINUS_CONSTANT_ALPHA};function K6(T,G$,r,O$,B$,$$,E$,m$,C6,M6){if(T===EJ){if(I===!0)v$($.BLEND),I=!1;return}if(I===!1)F$($.BLEND),I=!0;if(T!==fD){if(T!==q||M6!==h){if(_!==aW||B!==aW)$.blendEquation($.FUNC_ADD),_=aW,B=aW;if(M6)switch(T){case IQ:$.blendFuncSeparate($.ONE,$.ONE_MINUS_SRC_ALPHA,$.ONE,$.ONE_MINUS_SRC_ALPHA);break;case CO:$.blendFunc($.ONE,$.ONE);break;case SO:$.blendFuncSeparate($.ZERO,$.ONE_MINUS_SRC_COLOR,$.ZERO,$.ONE);break;case TO:$.blendFuncSeparate($.DST_COLOR,$.ONE_MINUS_SRC_ALPHA,$.ZERO,$.ONE);break;default:y$("WebGLState: Invalid blending: ",T);break}else switch(T){case IQ:$.blendFuncSeparate($.SRC_ALPHA,$.ONE_MINUS_SRC_ALPHA,$.ONE,$.ONE_MINUS_SRC_ALPHA);break;case CO:$.blendFuncSeparate($.SRC_ALPHA,$.ONE,$.ONE,$.ONE);break;case SO:y$("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case TO:y$("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:y$("WebGLState: Invalid blending: ",T);break}P=null,L=null,z=null,A=null,k.set(0,0,0),w=0,q=T,h=M6}return}if(B$=B$||G$,$$=$$||r,E$=E$||O$,G$!==_||B$!==B)$.blendEquationSeparate(X6[G$],X6[B$]),_=G$,B=B$;if(r!==P||O$!==L||$$!==z||E$!==A)$.blendFuncSeparate(J6[r],J6[O$],J6[$$],J6[E$]),P=r,L=O$,z=$$,A=E$;if(m$.equals(k)===!1||C6!==w)$.blendColor(m$.r,m$.g,m$.b,C6),k.copy(m$),w=C6;q=T,h=!1}function d6(T,G$){T.side===bU?v$($.CULL_FACE):F$($.CULL_FACE);let r=T.side===JU;if(G$)r=!r;CU(r),T.blending===IQ&&T.transparent===!1?K6(EJ):K6(T.blending,T.blendEquation,T.blendSrc,T.blendDst,T.blendEquationAlpha,T.blendSrcAlpha,T.blendDstAlpha,T.blendColor,T.blendAlpha,T.premultipliedAlpha),X.setFunc(T.depthFunc),X.setTest(T.depthTest),X.setMask(T.depthWrite),K.setMask(T.colorWrite);let O$=T.stencilWrite;if(N.setTest(O$),O$)N.setMask(T.stencilWriteMask),N.setFunc(T.stencilFunc,T.stencilRef,T.stencilFuncMask),N.setOp(T.stencilFail,T.stencilZFail,T.stencilZPass);c6(T.polygonOffset,T.polygonOffsetFactor,T.polygonOffsetUnits),T.alphaToCoverage===!0?F$($.SAMPLE_ALPHA_TO_COVERAGE):v$($.SAMPLE_ALPHA_TO_COVERAGE)}function CU(T){if(C!==T){if(T)$.frontFace($.CW);else $.frontFace($.CCW);C=T}}function z6(T){if(T!==xD){if(F$($.CULL_FACE),T!==f)if(T===AO)$.cullFace($.BACK);else if(T===yD)$.cullFace($.FRONT);else $.cullFace($.FRONT_AND_BACK)}else v$($.CULL_FACE);f=T}function r6(T){if(T!==s){if(x)$.lineWidth(T);s=T}}function c6(T,G$,r){if(T){if(F$($.POLYGON_OFFSET_FILL),y!==G$||d!==r){if(y=G$,d=r,X.getReversed())G$=-G$;$.polygonOffset(G$,r)}}else v$($.POLYGON_OFFSET_FILL)}function h6(T){if(T)F$($.SCISSOR_TEST);else v$($.SCISSOR_TEST)}function v(T){if(T===void 0)T=$.TEXTURE0+c-1;if(Y$!==T)$.activeTexture(T),Y$=T}function SU(T,G$,r){if(r===void 0)if(Y$===null)r=$.TEXTURE0+c-1;else r=Y$;let O$=R$[r];if(O$===void 0)O$={type:void 0,texture:void 0},R$[r]=O$;if(O$.type!==T||O$.texture!==G$){if(Y$!==r)$.activeTexture(r),Y$=r;$.bindTexture(T,G$||k$[T]),O$.type=T,O$.texture=G$}}function G6(){let T=R$[Y$];if(T!==void 0&&T.type!==void 0)$.bindTexture(T.type,null),T.type=void 0,T.texture=void 0}function _6(){try{$.compressedTexImage2D(...arguments)}catch(T){y$("WebGLState:",T)}}function M(){try{$.compressedTexImage3D(...arguments)}catch(T){y$("WebGLState:",T)}}function F(){try{$.texSubImage2D(...arguments)}catch(T){y$("WebGLState:",T)}}function S(){try{$.texSubImage3D(...arguments)}catch(T){y$("WebGLState:",T)}}function n(){try{$.compressedTexSubImage2D(...arguments)}catch(T){y$("WebGLState:",T)}}function J$(){try{$.compressedTexSubImage3D(...arguments)}catch(T){y$("WebGLState:",T)}}function N$(){try{$.texStorage2D(...arguments)}catch(T){y$("WebGLState:",T)}}function Z$(){try{$.texStorage3D(...arguments)}catch(T){y$("WebGLState:",T)}}function o(){try{$.texImage2D(...arguments)}catch(T){y$("WebGLState:",T)}}function a(){try{$.texImage3D(...arguments)}catch(T){y$("WebGLState:",T)}}function M$(T){if(O[T]!==void 0)return O[T];else return $.getParameter(T)}function C$(T,G$){if(O[T]!==G$)$.pixelStorei(T,G$),O[T]=G$}function I$(T){if(i$.equals(T)===!1)$.scissor(T.x,T.y,T.z,T.w),i$.copy(T)}function H$(T){if(i.equals(T)===!1)$.viewport(T.x,T.y,T.z,T.w),i.copy(T)}function j$(T,G$){let r=Y.get(G$);if(r===void 0)r=new WeakMap,Y.set(G$,r);let O$=r.get(T);if(O$===void 0)O$=$.getUniformBlockIndex(G$,T.name),r.set(T,O$)}function b$(T,G$){let O$=Y.get(G$).get(T);if(H.get(G$)!==O$)$.uniformBlockBinding(G$,O$,T.__bindingPointIndex),H.set(G$,O$)}function H6(){$.disable($.BLEND),$.disable($.CULL_FACE),$.disable($.DEPTH_TEST),$.disable($.POLYGON_OFFSET_FILL),$.disable($.SCISSOR_TEST),$.disable($.STENCIL_TEST),$.disable($.SAMPLE_ALPHA_TO_COVERAGE),$.blendEquation($.FUNC_ADD),$.blendFunc($.ONE,$.ZERO),$.blendFuncSeparate($.ONE,$.ZERO,$.ONE,$.ZERO),$.blendColor(0,0,0,0),$.colorMask(!0,!0,!0,!0),$.clearColor(0,0,0,0),$.depthMask(!0),$.depthFunc($.LESS),X.setReversed(!1),$.clearDepth(1),$.stencilMask(4294967295),$.stencilFunc($.ALWAYS,0,4294967295),$.stencilOp($.KEEP,$.KEEP,$.KEEP),$.clearStencil(0),$.cullFace($.BACK),$.frontFace($.CCW),$.polygonOffset(0,0),$.activeTexture($.TEXTURE0),$.bindFramebuffer($.FRAMEBUFFER,null),$.bindFramebuffer($.DRAW_FRAMEBUFFER,null),$.bindFramebuffer($.READ_FRAMEBUFFER,null),$.useProgram(null),$.lineWidth(1),$.scissor(0,0,$.canvas.width,$.canvas.height),$.viewport(0,0,$.canvas.width,$.canvas.height),$.pixelStorei($.PACK_ALIGNMENT,4),$.pixelStorei($.UNPACK_ALIGNMENT,4),$.pixelStorei($.UNPACK_FLIP_Y_WEBGL,!1),$.pixelStorei($.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),$.pixelStorei($.UNPACK_COLORSPACE_CONVERSION_WEBGL,$.BROWSER_DEFAULT_WEBGL),$.pixelStorei($.PACK_ROW_LENGTH,0),$.pixelStorei($.PACK_SKIP_PIXELS,0),$.pixelStorei($.PACK_SKIP_ROWS,0),$.pixelStorei($.UNPACK_ROW_LENGTH,0),$.pixelStorei($.UNPACK_IMAGE_HEIGHT,0),$.pixelStorei($.UNPACK_SKIP_PIXELS,0),$.pixelStorei($.UNPACK_SKIP_ROWS,0),$.pixelStorei($.UNPACK_SKIP_IMAGES,0),G={},O={},Y$=null,R$={},E={},Z=new WeakMap,D=[],R=null,I=!1,q=null,_=null,P=null,L=null,B=null,z=null,A=null,k=new x$(0,0,0),w=0,h=!1,C=null,f=null,s=null,y=null,d=null,i$.set(0,0,$.canvas.width,$.canvas.height),i.set(0,0,$.canvas.width,$.canvas.height),K.reset(),X.reset(),N.reset()}return{buffers:{color:K,depth:X,stencil:N},enable:F$,disable:v$,bindFramebuffer:e$,drawBuffers:l$,useProgram:d$,setBlending:K6,setMaterial:d6,setFlipSided:CU,setCullFace:z6,setLineWidth:r6,setPolygonOffset:c6,setScissorTest:h6,activeTexture:v,bindTexture:SU,unbindTexture:G6,compressedTexImage2D:_6,compressedTexImage3D:M,texImage2D:o,texImage3D:a,pixelStorei:C$,getParameter:M$,updateUBOMapping:j$,uniformBlockBinding:b$,texStorage2D:N$,texStorage3D:Z$,texSubImage2D:F,texSubImage3D:S,compressedTexSubImage2D:n,compressedTexSubImage3D:J$,scissor:I$,viewport:H$,reset:H6}}function Ez($,U,J,Q,W,K,X){let N=U.has("WEBGL_multisampled_render_to_texture")?U.get("WEBGL_multisampled_render_to_texture"):null,H=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),Y=new g$,G=new WeakMap,O=new Set,E,Z=new WeakMap,D=!1;try{D=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch(M){}function R(M,F){return D?new OffscreenCanvas(M,F):nW("canvas")}function I(M,F,S){let n=1,J$=_6(M);if(J$.width>S||J$.height>S)n=S/Math.max(J$.width,J$.height);if(n<1)if(typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&M instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&M instanceof ImageBitmap||typeof VideoFrame<"u"&&M instanceof VideoFrame){let N$=Math.floor(n*J$.width),Z$=Math.floor(n*J$.height);if(E===void 0)E=R(N$,Z$);let o=F?R(N$,Z$):E;return o.width=N$,o.height=Z$,o.getContext("2d").drawImage(M,0,0,N$,Z$),A$("WebGLRenderer: Texture has been resized from ("+J$.width+"x"+J$.height+") to ("+N$+"x"+Z$+")."),o}else{if("data"in M)A$("WebGLRenderer: Image in DataTexture is too big ("+J$.width+"x"+J$.height+").");return M}return M}function q(M){return M.generateMipmaps}function _(M){$.generateMipmap(M)}function P(M){if(M.isWebGLCubeRenderTarget)return $.TEXTURE_CUBE_MAP;if(M.isWebGL3DRenderTarget)return $.TEXTURE_3D;if(M.isWebGLArrayRenderTarget||M.isCompressedArrayTexture)return $.TEXTURE_2D_ARRAY;return $.TEXTURE_2D}function L(M,F,S,n,J$,N$=!1){if(M!==null){if($[M]!==void 0)return $[M];A$("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+M+"'")}let Z$;if(n){if(Z$=U.get("EXT_texture_norm16"),!Z$)A$("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension")}let o=F;if(F===$.RED){if(S===$.FLOAT)o=$.R32F;if(S===$.HALF_FLOAT)o=$.R16F;if(S===$.UNSIGNED_BYTE)o=$.R8;if(S===$.UNSIGNED_SHORT&&Z$)o=Z$.R16_EXT;if(S===$.SHORT&&Z$)o=Z$.R16_SNORM_EXT}if(F===$.RED_INTEGER){if(S===$.UNSIGNED_BYTE)o=$.R8UI;if(S===$.UNSIGNED_SHORT)o=$.R16UI;if(S===$.UNSIGNED_INT)o=$.R32UI;if(S===$.BYTE)o=$.R8I;if(S===$.SHORT)o=$.R16I;if(S===$.INT)o=$.R32I}if(F===$.RG){if(S===$.FLOAT)o=$.RG32F;if(S===$.HALF_FLOAT)o=$.RG16F;if(S===$.UNSIGNED_BYTE)o=$.RG8;if(S===$.UNSIGNED_SHORT&&Z$)o=Z$.RG16_EXT;if(S===$.SHORT&&Z$)o=Z$.RG16_SNORM_EXT}if(F===$.RG_INTEGER){if(S===$.UNSIGNED_BYTE)o=$.RG8UI;if(S===$.UNSIGNED_SHORT)o=$.RG16UI;if(S===$.UNSIGNED_INT)o=$.RG32UI;if(S===$.BYTE)o=$.RG8I;if(S===$.SHORT)o=$.RG16I;if(S===$.INT)o=$.RG32I}if(F===$.RGB_INTEGER){if(S===$.UNSIGNED_BYTE)o=$.RGB8UI;if(S===$.UNSIGNED_SHORT)o=$.RGB16UI;if(S===$.UNSIGNED_INT)o=$.RGB32UI;if(S===$.BYTE)o=$.RGB8I;if(S===$.SHORT)o=$.RGB16I;if(S===$.INT)o=$.RGB32I}if(F===$.RGBA_INTEGER){if(S===$.UNSIGNED_BYTE)o=$.RGBA8UI;if(S===$.UNSIGNED_SHORT)o=$.RGBA16UI;if(S===$.UNSIGNED_INT)o=$.RGBA32UI;if(S===$.BYTE)o=$.RGBA8I;if(S===$.SHORT)o=$.RGBA16I;if(S===$.INT)o=$.RGBA32I}if(F===$.RGB){if(S===$.UNSIGNED_SHORT&&Z$)o=Z$.RGB16_EXT;if(S===$.SHORT&&Z$)o=Z$.RGB16_SNORM_EXT;if(S===$.UNSIGNED_INT_5_9_9_9_REV)o=$.RGB9_E5;if(S===$.UNSIGNED_INT_10F_11F_11F_REV)o=$.R11F_G11F_B10F}if(F===$.RGBA){let a=N$?BE:s$.getTransfer(J$);if(S===$.FLOAT)o=$.RGBA32F;if(S===$.HALF_FLOAT)o=$.RGBA16F;if(S===$.UNSIGNED_BYTE)o=a===w6?$.SRGB8_ALPHA8:$.RGBA8;if(S===$.UNSIGNED_SHORT&&Z$)o=Z$.RGBA16_EXT;if(S===$.SHORT&&Z$)o=Z$.RGBA16_SNORM_EXT;if(S===$.UNSIGNED_SHORT_4_4_4_4)o=$.RGBA4;if(S===$.UNSIGNED_SHORT_5_5_5_1)o=$.RGB5_A1}if(o===$.R16F||o===$.R32F||o===$.RG16F||o===$.RG32F||o===$.RGBA16F||o===$.RGBA32F)U.get("EXT_color_buffer_float");return o}function B(M,F){let S;if(M){if(F===null||F===X0||F===U8)S=$.DEPTH24_STENCIL8;else if(F===jJ)S=$.DEPTH32F_STENCIL8;else if(F===kQ)S=$.DEPTH24_STENCIL8,A$("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")}else if(F===null||F===X0||F===U8)S=$.DEPTH_COMPONENT24;else if(F===jJ)S=$.DEPTH_COMPONENT32F;else if(F===kQ)S=$.DEPTH_COMPONENT16;return S}function z(M,F){if(q(M)===!0||M.isFramebufferTexture&&M.minFilter!==rU&&M.minFilter!==o6)return Math.log2(Math.max(F.width,F.height))+1;else if(M.mipmaps!==void 0&&M.mipmaps.length>0)return M.mipmaps.length;else if(M.isCompressedTexture&&Array.isArray(M.image))return F.mipmaps.length;else return 1}function A(M){let F=M.target;if(F.removeEventListener("dispose",A),w(F),F.isVideoTexture)G.delete(F);if(F.isHTMLTexture)O.delete(F)}function k(M){let F=M.target;F.removeEventListener("dispose",k),C(F)}function w(M){let F=Q.get(M);if(F.__webglInit===void 0)return;let S=M.source,n=Z.get(S);if(n){let J$=n[F.__cacheKey];if(J$.usedTimes--,J$.usedTimes===0)h(M);if(Object.keys(n).length===0)Z.delete(S)}Q.remove(M)}function h(M){let F=Q.get(M);$.deleteTexture(F.__webglTexture);let S=M.source,n=Z.get(S);delete n[F.__cacheKey],X.memory.textures--}function C(M){let F=Q.get(M);if(M.depthTexture)M.depthTexture.dispose(),Q.remove(M.depthTexture);if(M.isWebGLCubeRenderTarget)for(let n=0;n<6;n++){if(Array.isArray(F.__webglFramebuffer[n]))for(let J$=0;J$<F.__webglFramebuffer[n].length;J$++)$.deleteFramebuffer(F.__webglFramebuffer[n][J$]);else $.deleteFramebuffer(F.__webglFramebuffer[n]);if(F.__webglDepthbuffer)$.deleteRenderbuffer(F.__webglDepthbuffer[n])}else{if(Array.isArray(F.__webglFramebuffer))for(let n=0;n<F.__webglFramebuffer.length;n++)$.deleteFramebuffer(F.__webglFramebuffer[n]);else $.deleteFramebuffer(F.__webglFramebuffer);if(F.__webglDepthbuffer)$.deleteRenderbuffer(F.__webglDepthbuffer);if(F.__webglMultisampledFramebuffer)$.deleteFramebuffer(F.__webglMultisampledFramebuffer);if(F.__webglColorRenderbuffer){for(let n=0;n<F.__webglColorRenderbuffer.length;n++)if(F.__webglColorRenderbuffer[n])$.deleteRenderbuffer(F.__webglColorRenderbuffer[n])}if(F.__webglDepthRenderbuffer)$.deleteRenderbuffer(F.__webglDepthRenderbuffer)}let S=M.textures;for(let n=0,J$=S.length;n<J$;n++){let N$=Q.get(S[n]);if(N$.__webglTexture)$.deleteTexture(N$.__webglTexture),X.memory.textures--;Q.remove(S[n])}Q.remove(M)}let f=0;function s(){f=0}function y(){return f}function d(M){f=M}function c(){let M=f;if(M>=W.maxTextures)A$("WebGLTextures: Trying to use "+M+" texture units while this GPU supports only "+W.maxTextures);return f+=1,M}function x(M){let F=[];return F.push(M.wrapS),F.push(M.wrapT),F.push(M.wrapR||0),F.push(M.magFilter),F.push(M.minFilter),F.push(M.anisotropy),F.push(M.internalFormat),F.push(M.format),F.push(M.type),F.push(M.generateMipmaps),F.push(M.premultiplyAlpha),F.push(M.flipY),F.push(M.unpackAlignment),F.push(M.colorSpace),F.join()}function t(M,F){let S=Q.get(M);if(M.isVideoTexture)SU(M);if(M.isRenderTargetTexture===!1&&M.isExternalTexture!==!0&&M.version>0&&S.__version!==M.version){let n=M.image;if(n===null)A$("WebGLRenderer: Texture marked for update but no image data found.");else if(n.complete===!1)A$("WebGLRenderer: Texture marked for update but image is incomplete");else{v$(S,M,F);return}}else if(M.isExternalTexture)S.__webglTexture=M.sourceTexture?M.sourceTexture:null;J.bindTexture($.TEXTURE_2D,S.__webglTexture,$.TEXTURE0+F)}function e(M,F){let S=Q.get(M);if(M.isRenderTargetTexture===!1&&M.version>0&&S.__version!==M.version){v$(S,M,F);return}else if(M.isExternalTexture)S.__webglTexture=M.sourceTexture?M.sourceTexture:null;J.bindTexture($.TEXTURE_2D_ARRAY,S.__webglTexture,$.TEXTURE0+F)}function Y$(M,F){let S=Q.get(M);if(M.isRenderTargetTexture===!1&&M.version>0&&S.__version!==M.version){v$(S,M,F);return}J.bindTexture($.TEXTURE_3D,S.__webglTexture,$.TEXTURE0+F)}function R$(M,F){let S=Q.get(M);if(M.isCubeDepthTexture!==!0&&M.version>0&&S.__version!==M.version){e$(S,M,F);return}J.bindTexture($.TEXTURE_CUBE_MAP,S.__webglTexture,$.TEXTURE0+F)}let w$={[tW]:$.REPEAT,[eW]:$.CLAMP_TO_EDGE,[J7]:$.MIRRORED_REPEAT},U6={[rU]:$.NEAREST,[W7]:$.NEAREST_MIPMAP_NEAREST,[f0]:$.NEAREST_MIPMAP_LINEAR,[o6]:$.LINEAR,[$8]:$.LINEAR_MIPMAP_NEAREST,[ZJ]:$.LINEAR_MIPMAP_LINEAR},i$={[Mk]:$.NEVER,[Ak]:$.ALWAYS,[Bk]:$.LESS,[O7]:$.LEQUAL,[Pk]:$.EQUAL,[E7]:$.GEQUAL,[zk]:$.GREATER,[_k]:$.NOTEQUAL};function i(M,F){if(F.type===jJ&&U.has("OES_texture_float_linear")===!1&&(F.magFilter===o6||F.magFilter===$8||F.magFilter===f0||F.magFilter===ZJ||F.minFilter===o6||F.minFilter===$8||F.minFilter===f0||F.minFilter===ZJ))A$("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.");if($.texParameteri(M,$.TEXTURE_WRAP_S,w$[F.wrapS]),$.texParameteri(M,$.TEXTURE_WRAP_T,w$[F.wrapT]),M===$.TEXTURE_3D||M===$.TEXTURE_2D_ARRAY)$.texParameteri(M,$.TEXTURE_WRAP_R,w$[F.wrapR]);if($.texParameteri(M,$.TEXTURE_MAG_FILTER,U6[F.magFilter]),$.texParameteri(M,$.TEXTURE_MIN_FILTER,U6[F.minFilter]),F.compareFunction)$.texParameteri(M,$.TEXTURE_COMPARE_MODE,$.COMPARE_REF_TO_TEXTURE),$.texParameteri(M,$.TEXTURE_COMPARE_FUNC,i$[F.compareFunction]);if(U.has("EXT_texture_filter_anisotropic")===!0){if(F.magFilter===rU)return;if(F.minFilter!==f0&&F.minFilter!==ZJ)return;if(F.type===jJ&&U.has("OES_texture_float_linear")===!1)return;if(F.anisotropy>1||Q.get(F).__currentAnisotropy){let S=U.get("EXT_texture_filter_anisotropic");$.texParameterf(M,S.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(F.anisotropy,W.getMaxAnisotropy())),Q.get(F).__currentAnisotropy=F.anisotropy}}}function X$(M,F){let S=!1;if(M.__webglInit===void 0)M.__webglInit=!0,F.addEventListener("dispose",A);let n=F.source,J$=Z.get(n);if(J$===void 0)J$={},Z.set(n,J$);let N$=x(F);if(N$!==M.__cacheKey){if(J$[N$]===void 0)J$[N$]={texture:$.createTexture(),usedTimes:0},X.memory.textures++,S=!0;J$[N$].usedTimes++;let Z$=J$[M.__cacheKey];if(Z$!==void 0){if(J$[M.__cacheKey].usedTimes--,Z$.usedTimes===0)h(F)}M.__cacheKey=N$,M.__webglTexture=J$[N$].texture}return S}function k$(M,F,S){return Math.floor(Math.floor(M/S)/F)}function F$(M,F,S,n){let N$=M.updateRanges;if(N$.length===0)J.texSubImage2D($.TEXTURE_2D,0,0,0,F.width,F.height,S,n,F.data);else{N$.sort((C$,I$)=>C$.start-I$.start);let Z$=0;for(let C$=1;C$<N$.length;C$++){let I$=N$[Z$],H$=N$[C$],j$=I$.start+I$.count,b$=k$(H$.start,F.width,4),H6=k$(I$.start,F.width,4);if(H$.start<=j$+1&&b$===H6&&k$(H$.start+H$.count-1,F.width,4)===b$)I$.count=Math.max(I$.count,H$.start+H$.count-I$.start);else++Z$,N$[Z$]=H$}N$.length=Z$+1;let o=J.getParameter($.UNPACK_ROW_LENGTH),a=J.getParameter($.UNPACK_SKIP_PIXELS),M$=J.getParameter($.UNPACK_SKIP_ROWS);J.pixelStorei($.UNPACK_ROW_LENGTH,F.width);for(let C$=0,I$=N$.length;C$<I$;C$++){let H$=N$[C$],j$=Math.floor(H$.start/4),b$=Math.ceil(H$.count/4),H6=j$%F.width,T=Math.floor(j$/F.width),G$=b$,r=1;J.pixelStorei($.UNPACK_SKIP_PIXELS,H6),J.pixelStorei($.UNPACK_SKIP_ROWS,T),J.texSubImage2D($.TEXTURE_2D,0,H6,T,G$,1,S,n,F.data)}M.clearUpdateRanges(),J.pixelStorei($.UNPACK_ROW_LENGTH,o),J.pixelStorei($.UNPACK_SKIP_PIXELS,a),J.pixelStorei($.UNPACK_SKIP_ROWS,M$)}}function v$(M,F,S){let n=$.TEXTURE_2D;if(F.isDataArrayTexture||F.isCompressedArrayTexture)n=$.TEXTURE_2D_ARRAY;if(F.isData3DTexture)n=$.TEXTURE_3D;let J$=X$(M,F),N$=F.source;J.bindTexture(n,M.__webglTexture,$.TEXTURE0+S);let Z$=Q.get(N$);if(N$.version!==Z$.__version||J$===!0){if(J.activeTexture($.TEXTURE0+S),(typeof ImageBitmap<"u"&&F.image instanceof ImageBitmap)===!1){let r=s$.getPrimaries(s$.workingColorSpace),O$=F.colorSpace===p0?null:s$.getPrimaries(F.colorSpace),B$=F.colorSpace===p0||r===O$?$.NONE:$.BROWSER_DEFAULT_WEBGL;J.pixelStorei($.UNPACK_FLIP_Y_WEBGL,F.flipY),J.pixelStorei($.UNPACK_PREMULTIPLY_ALPHA_WEBGL,F.premultiplyAlpha),J.pixelStorei($.UNPACK_COLORSPACE_CONVERSION_WEBGL,B$)}J.pixelStorei($.UNPACK_ALIGNMENT,F.unpackAlignment);let a=I(F.image,!1,W.maxTextureSize);a=G6(F,a);let M$=K.convert(F.format,F.colorSpace),C$=K.convert(F.type),I$=L(F.internalFormat,M$,C$,F.normalized,F.colorSpace,F.isVideoTexture);i(n,F);let H$,j$=F.mipmaps,b$=F.isVideoTexture!==!0,H6=Z$.__version===void 0||J$===!0,T=N$.dataReady,G$=z(F,a);if(F.isDepthTexture){if(I$=B(F.format===l0,F.type),H6)if(b$)J.texStorage2D($.TEXTURE_2D,1,I$,a.width,a.height);else J.texImage2D($.TEXTURE_2D,0,I$,a.width,a.height,0,M$,C$,null)}else if(F.isDataTexture)if(j$.length>0){if(b$&&H6)J.texStorage2D($.TEXTURE_2D,G$,I$,j$[0].width,j$[0].height);for(let r=0,O$=j$.length;r<O$;r++)if(H$=j$[r],b$){if(T)J.texSubImage2D($.TEXTURE_2D,r,0,0,H$.width,H$.height,M$,C$,H$.data)}else J.texImage2D($.TEXTURE_2D,r,I$,H$.width,H$.height,0,M$,C$,H$.data);F.generateMipmaps=!1}else if(b$){if(H6)J.texStorage2D($.TEXTURE_2D,G$,I$,a.width,a.height);if(T)F$(F,a,M$,C$)}else J.texImage2D($.TEXTURE_2D,0,I$,a.width,a.height,0,M$,C$,a.data);else if(F.isCompressedTexture)if(F.isCompressedArrayTexture){if(b$&&H6)J.texStorage3D($.TEXTURE_2D_ARRAY,G$,I$,j$[0].width,j$[0].height,a.depth);for(let r=0,O$=j$.length;r<O$;r++)if(H$=j$[r],F.format!==IJ)if(M$!==null)if(b$){if(T)if(F.layerUpdates.size>0){let B$=oE(H$.width,H$.height,F.format,F.type);for(let $$ of F.layerUpdates){let E$=H$.data.subarray($$*B$/H$.data.BYTES_PER_ELEMENT,($$+1)*B$/H$.data.BYTES_PER_ELEMENT);J.compressedTexSubImage3D($.TEXTURE_2D_ARRAY,r,0,0,$$,H$.width,H$.height,1,M$,E$)}F.clearLayerUpdates()}else J.compressedTexSubImage3D($.TEXTURE_2D_ARRAY,r,0,0,0,H$.width,H$.height,a.depth,M$,H$.data)}else J.compressedTexImage3D($.TEXTURE_2D_ARRAY,r,I$,H$.width,H$.height,a.depth,0,H$.data,0,0);else A$("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(b$){if(T)J.texSubImage3D($.TEXTURE_2D_ARRAY,r,0,0,0,H$.width,H$.height,a.depth,M$,C$,H$.data)}else J.texImage3D($.TEXTURE_2D_ARRAY,r,I$,H$.width,H$.height,a.depth,0,M$,C$,H$.data)}else{if(b$&&H6)J.texStorage2D($.TEXTURE_2D,G$,I$,j$[0].width,j$[0].height);for(let r=0,O$=j$.length;r<O$;r++)if(H$=j$[r],F.format!==IJ)if(M$!==null)if(b$){if(T)J.compressedTexSubImage2D($.TEXTURE_2D,r,0,0,H$.width,H$.height,M$,H$.data)}else J.compressedTexImage2D($.TEXTURE_2D,r,I$,H$.width,H$.height,0,H$.data);else A$("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(b$){if(T)J.texSubImage2D($.TEXTURE_2D,r,0,0,H$.width,H$.height,M$,C$,H$.data)}else J.texImage2D($.TEXTURE_2D,r,I$,H$.width,H$.height,0,M$,C$,H$.data)}else if(F.isDataArrayTexture)if(b$){if(H6)J.texStorage3D($.TEXTURE_2D_ARRAY,G$,I$,a.width,a.height,a.depth);if(T)if(F.layerUpdates.size>0){let r=oE(a.width,a.height,F.format,F.type);for(let O$ of F.layerUpdates){let B$=a.data.subarray(O$*r/a.data.BYTES_PER_ELEMENT,(O$+1)*r/a.data.BYTES_PER_ELEMENT);J.texSubImage3D($.TEXTURE_2D_ARRAY,0,0,0,O$,a.width,a.height,1,M$,C$,B$)}F.clearLayerUpdates()}else J.texSubImage3D($.TEXTURE_2D_ARRAY,0,0,0,0,a.width,a.height,a.depth,M$,C$,a.data)}else J.texImage3D($.TEXTURE_2D_ARRAY,0,I$,a.width,a.height,a.depth,0,M$,C$,a.data);else if(F.isData3DTexture)if(b$){if(H6)J.texStorage3D($.TEXTURE_3D,G$,I$,a.width,a.height,a.depth);if(T)J.texSubImage3D($.TEXTURE_3D,0,0,0,0,a.width,a.height,a.depth,M$,C$,a.data)}else J.texImage3D($.TEXTURE_3D,0,I$,a.width,a.height,a.depth,0,M$,C$,a.data);else if(F.isFramebufferTexture){if(H6)if(b$)J.texStorage2D($.TEXTURE_2D,G$,I$,a.width,a.height);else{let{width:r,height:O$}=a;for(let B$=0;B$<G$;B$++)J.texImage2D($.TEXTURE_2D,B$,I$,r,O$,0,M$,C$,null),r>>=1,O$>>=1}}else if(F.isHTMLTexture){if("texElementImage2D"in $){let r=$.canvas;if(!r.hasAttribute("layoutsubtree"))r.setAttribute("layoutsubtree","true");if(a.parentNode!==r){r.appendChild(a),O.add(F),r.onpaint=(O$)=>{let B$=O$.changedElements;for(let $$ of O)if(B$.includes($$.image))$$.needsUpdate=!0},r.requestPaint();return}if($.texElementImage2D.length===3)$.texElementImage2D($.TEXTURE_2D,$.RGBA8,a);else{let{RGBA:B$,RGBA:$$,UNSIGNED_BYTE:E$}=$;$.texElementImage2D($.TEXTURE_2D,0,B$,$$,E$,a)}$.texParameteri($.TEXTURE_2D,$.TEXTURE_MIN_FILTER,$.LINEAR),$.texParameteri($.TEXTURE_2D,$.TEXTURE_WRAP_S,$.CLAMP_TO_EDGE),$.texParameteri($.TEXTURE_2D,$.TEXTURE_WRAP_T,$.CLAMP_TO_EDGE)}}else if(j$.length>0){if(b$&&H6){let r=_6(j$[0]);J.texStorage2D($.TEXTURE_2D,G$,I$,r.width,r.height)}for(let r=0,O$=j$.length;r<O$;r++)if(H$=j$[r],b$){if(T)J.texSubImage2D($.TEXTURE_2D,r,0,0,M$,C$,H$)}else J.texImage2D($.TEXTURE_2D,r,I$,M$,C$,H$);F.generateMipmaps=!1}else if(b$){if(H6){let r=_6(a);J.texStorage2D($.TEXTURE_2D,G$,I$,r.width,r.height)}if(T)J.texSubImage2D($.TEXTURE_2D,0,0,0,M$,C$,a)}else J.texImage2D($.TEXTURE_2D,0,I$,M$,C$,a);if(q(F))_(n);if(Z$.__version=N$.version,F.onUpdate)F.onUpdate(F)}M.__version=F.version}function e$(M,F,S){if(F.image.length!==6)return;let n=X$(M,F),J$=F.source;J.bindTexture($.TEXTURE_CUBE_MAP,M.__webglTexture,$.TEXTURE0+S);let N$=Q.get(J$);if(J$.version!==N$.__version||n===!0){J.activeTexture($.TEXTURE0+S);let Z$=s$.getPrimaries(s$.workingColorSpace),o=F.colorSpace===p0?null:s$.getPrimaries(F.colorSpace),a=F.colorSpace===p0||Z$===o?$.NONE:$.BROWSER_DEFAULT_WEBGL;J.pixelStorei($.UNPACK_FLIP_Y_WEBGL,F.flipY),J.pixelStorei($.UNPACK_PREMULTIPLY_ALPHA_WEBGL,F.premultiplyAlpha),J.pixelStorei($.UNPACK_ALIGNMENT,F.unpackAlignment),J.pixelStorei($.UNPACK_COLORSPACE_CONVERSION_WEBGL,a);let M$=F.isCompressedTexture||F.image[0].isCompressedTexture,C$=F.image[0]&&F.image[0].isDataTexture,I$=[];for(let $$=0;$$<6;$$++){if(!M$&&!C$)I$[$$]=I(F.image[$$],!0,W.maxCubemapSize);else I$[$$]=C$?F.image[$$].image:F.image[$$];I$[$$]=G6(F,I$[$$])}let H$=I$[0],j$=K.convert(F.format,F.colorSpace),b$=K.convert(F.type),H6=L(F.internalFormat,j$,b$,F.normalized,F.colorSpace),T=F.isVideoTexture!==!0,G$=N$.__version===void 0||n===!0,r=J$.dataReady,O$=z(F,H$);i($.TEXTURE_CUBE_MAP,F);let B$;if(M$){if(T&&G$)J.texStorage2D($.TEXTURE_CUBE_MAP,O$,H6,H$.width,H$.height);for(let $$=0;$$<6;$$++){B$=I$[$$].mipmaps;for(let E$=0;E$<B$.length;E$++){let m$=B$[E$];if(F.format!==IJ)if(j$!==null)if(T){if(r)J.compressedTexSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$,0,0,m$.width,m$.height,j$,m$.data)}else J.compressedTexImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$,H6,m$.width,m$.height,0,m$.data);else A$("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()");else if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$,0,0,m$.width,m$.height,j$,b$,m$.data)}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$,H6,m$.width,m$.height,0,j$,b$,m$.data)}}}else{if(B$=F.mipmaps,T&&G$){if(B$.length>0)O$++;let $$=_6(I$[0]);J.texStorage2D($.TEXTURE_CUBE_MAP,O$,H6,$$.width,$$.height)}for(let $$=0;$$<6;$$++)if(C$){if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,0,0,0,I$[$$].width,I$[$$].height,j$,b$,I$[$$].data)}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,0,H6,I$[$$].width,I$[$$].height,0,j$,b$,I$[$$].data);for(let E$=0;E$<B$.length;E$++){let C6=B$[E$].image[$$].image;if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$+1,0,0,C6.width,C6.height,j$,b$,C6.data)}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$+1,H6,C6.width,C6.height,0,j$,b$,C6.data)}}else{if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,0,0,0,j$,b$,I$[$$])}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,0,H6,j$,b$,I$[$$]);for(let E$=0;E$<B$.length;E$++){let m$=B$[E$];if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$+1,0,0,j$,b$,m$.image[$$])}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$+1,H6,j$,b$,m$.image[$$])}}}if(q(F))_($.TEXTURE_CUBE_MAP);if(N$.__version=J$.version,F.onUpdate)F.onUpdate(F)}M.__version=F.version}function l$(M,F,S,n,J$,N$){let Z$=K.convert(S.format,S.colorSpace),o=K.convert(S.type),a=L(S.internalFormat,Z$,o,S.normalized,S.colorSpace),M$=Q.get(F),C$=Q.get(S);if(C$.__renderTarget=F,!M$.__hasExternalTextures){let I$=Math.max(1,F.width>>N$),H$=Math.max(1,F.height>>N$);if(J$===$.TEXTURE_3D||J$===$.TEXTURE_2D_ARRAY)J.texImage3D(J$,N$,a,I$,H$,F.depth,0,Z$,o,null);else J.texImage2D(J$,N$,a,I$,H$,0,Z$,o,null)}if(J.bindFramebuffer($.FRAMEBUFFER,M),v(F))N.framebufferTexture2DMultisampleEXT($.FRAMEBUFFER,n,J$,C$.__webglTexture,0,h6(F));else if(J$===$.TEXTURE_2D||J$>=$.TEXTURE_CUBE_MAP_POSITIVE_X&&J$<=$.TEXTURE_CUBE_MAP_NEGATIVE_Z)$.framebufferTexture2D($.FRAMEBUFFER,n,J$,C$.__webglTexture,N$);J.bindFramebuffer($.FRAMEBUFFER,null)}function d$(M,F,S){if($.bindRenderbuffer($.RENDERBUFFER,M),F.depthBuffer){let n=F.depthTexture,J$=n&&n.isDepthTexture?n.type:null,N$=B(F.stencilBuffer,J$),Z$=F.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT;if(v(F))N.renderbufferStorageMultisampleEXT($.RENDERBUFFER,h6(F),N$,F.width,F.height);else if(S)$.renderbufferStorageMultisample($.RENDERBUFFER,h6(F),N$,F.width,F.height);else $.renderbufferStorage($.RENDERBUFFER,N$,F.width,F.height);$.framebufferRenderbuffer($.FRAMEBUFFER,Z$,$.RENDERBUFFER,M)}else{let n=F.textures;for(let J$=0;J$<n.length;J$++){let N$=n[J$],Z$=K.convert(N$.format,N$.colorSpace),o=K.convert(N$.type),a=L(N$.internalFormat,Z$,o,N$.normalized,N$.colorSpace);if(v(F))N.renderbufferStorageMultisampleEXT($.RENDERBUFFER,h6(F),a,F.width,F.height);else if(S)$.renderbufferStorageMultisample($.RENDERBUFFER,h6(F),a,F.width,F.height);else $.renderbufferStorage($.RENDERBUFFER,a,F.width,F.height)}}$.bindRenderbuffer($.RENDERBUFFER,null)}function X6(M,F,S){let n=F.isWebGLCubeRenderTarget===!0;if(J.bindFramebuffer($.FRAMEBUFFER,M),!(F.depthTexture&&F.depthTexture.isDepthTexture))throw Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");let J$=Q.get(F.depthTexture);if(J$.__renderTarget=F,!J$.__webglTexture||F.depthTexture.image.width!==F.width||F.depthTexture.image.height!==F.height)F.depthTexture.image.width=F.width,F.depthTexture.image.height=F.height,F.depthTexture.needsUpdate=!0;if(n){if(J$.__webglInit===void 0)J$.__webglInit=!0,F.depthTexture.addEventListener("dispose",A);if(J$.__webglTexture===void 0){J$.__webglTexture=$.createTexture(),J.bindTexture($.TEXTURE_CUBE_MAP,J$.__webglTexture),i($.TEXTURE_CUBE_MAP,F.depthTexture);let M$=K.convert(F.depthTexture.format),C$=K.convert(F.depthTexture.type),I$;if(F.depthTexture.format===u0)I$=$.DEPTH_COMPONENT24;else if(F.depthTexture.format===l0)I$=$.DEPTH24_STENCIL8;for(let H$=0;H$<6;H$++)$.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+H$,0,I$,F.width,F.height,0,M$,C$,null)}}else t(F.depthTexture,0);let N$=J$.__webglTexture,Z$=h6(F),o=n?$.TEXTURE_CUBE_MAP_POSITIVE_X+S:$.TEXTURE_2D,a=F.depthTexture.format===l0?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT;if(F.depthTexture.format===u0)if(v(F))N.framebufferTexture2DMultisampleEXT($.FRAMEBUFFER,a,o,N$,0,Z$);else $.framebufferTexture2D($.FRAMEBUFFER,a,o,N$,0);else if(F.depthTexture.format===l0)if(v(F))N.framebufferTexture2DMultisampleEXT($.FRAMEBUFFER,a,o,N$,0,Z$);else $.framebufferTexture2D($.FRAMEBUFFER,a,o,N$,0);else throw Error("THREE.WebGLTextures: Unknown depthTexture format.")}function J6(M){let F=Q.get(M),S=M.isWebGLCubeRenderTarget===!0;if(F.__boundDepthTexture!==M.depthTexture){let n=M.depthTexture;if(F.__depthDisposeCallback)F.__depthDisposeCallback();if(n){let J$=()=>{delete F.__boundDepthTexture,delete F.__depthDisposeCallback,n.removeEventListener("dispose",J$)};n.addEventListener("dispose",J$),F.__depthDisposeCallback=J$}F.__boundDepthTexture=n}if(M.depthTexture&&!F.__autoAllocateDepthBuffer)if(S)for(let n=0;n<6;n++)X6(F.__webglFramebuffer[n],M,n);else{let n=M.texture.mipmaps;if(n&&n.length>0)X6(F.__webglFramebuffer[0],M,0);else X6(F.__webglFramebuffer,M,0)}else if(S){F.__webglDepthbuffer=[];for(let n=0;n<6;n++)if(J.bindFramebuffer($.FRAMEBUFFER,F.__webglFramebuffer[n]),F.__webglDepthbuffer[n]===void 0)F.__webglDepthbuffer[n]=$.createRenderbuffer(),d$(F.__webglDepthbuffer[n],M,!1);else{let J$=M.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT,N$=F.__webglDepthbuffer[n];$.bindRenderbuffer($.RENDERBUFFER,N$),$.framebufferRenderbuffer($.FRAMEBUFFER,J$,$.RENDERBUFFER,N$)}}else{let n=M.texture.mipmaps;if(n&&n.length>0)J.bindFramebuffer($.FRAMEBUFFER,F.__webglFramebuffer[0]);else J.bindFramebuffer($.FRAMEBUFFER,F.__webglFramebuffer);if(F.__webglDepthbuffer===void 0)F.__webglDepthbuffer=$.createRenderbuffer(),d$(F.__webglDepthbuffer,M,!1);else{let J$=M.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT,N$=F.__webglDepthbuffer;$.bindRenderbuffer($.RENDERBUFFER,N$),$.framebufferRenderbuffer($.FRAMEBUFFER,J$,$.RENDERBUFFER,N$)}}J.bindFramebuffer($.FRAMEBUFFER,null)}function K6(M,F,S){let n=Q.get(M);if(F!==void 0)l$(n.__webglFramebuffer,M,M.texture,$.COLOR_ATTACHMENT0,$.TEXTURE_2D,0);if(S!==void 0)J6(M)}function d6(M){let F=M.texture,S=Q.get(M),n=Q.get(F);M.addEventListener("dispose",k);let J$=M.textures,N$=M.isWebGLCubeRenderTarget===!0,Z$=J$.length>1;if(!Z$){if(n.__webglTexture===void 0)n.__webglTexture=$.createTexture();n.__version=F.version,X.memory.textures++}if(N$){S.__webglFramebuffer=[];for(let o=0;o<6;o++)if(F.mipmaps&&F.mipmaps.length>0){S.__webglFramebuffer[o]=[];for(let a=0;a<F.mipmaps.length;a++)S.__webglFramebuffer[o][a]=$.createFramebuffer()}else S.__webglFramebuffer[o]=$.createFramebuffer()}else{if(F.mipmaps&&F.mipmaps.length>0){S.__webglFramebuffer=[];for(let o=0;o<F.mipmaps.length;o++)S.__webglFramebuffer[o]=$.createFramebuffer()}else S.__webglFramebuffer=$.createFramebuffer();if(Z$)for(let o=0,a=J$.length;o<a;o++){let M$=Q.get(J$[o]);if(M$.__webglTexture===void 0)M$.__webglTexture=$.createTexture(),X.memory.textures++}if(M.samples>0&&v(M)===!1){S.__webglMultisampledFramebuffer=$.createFramebuffer(),S.__webglColorRenderbuffer=[],J.bindFramebuffer($.FRAMEBUFFER,S.__webglMultisampledFramebuffer);for(let o=0;o<J$.length;o++){let a=J$[o];S.__webglColorRenderbuffer[o]=$.createRenderbuffer(),$.bindRenderbuffer($.RENDERBUFFER,S.__webglColorRenderbuffer[o]);let M$=K.convert(a.format,a.colorSpace),C$=K.convert(a.type),I$=L(a.internalFormat,M$,C$,a.normalized,a.colorSpace,M.isXRRenderTarget===!0),H$=h6(M);$.renderbufferStorageMultisample($.RENDERBUFFER,H$,I$,M.width,M.height),$.framebufferRenderbuffer($.FRAMEBUFFER,$.COLOR_ATTACHMENT0+o,$.RENDERBUFFER,S.__webglColorRenderbuffer[o])}if($.bindRenderbuffer($.RENDERBUFFER,null),M.depthBuffer)S.__webglDepthRenderbuffer=$.createRenderbuffer(),d$(S.__webglDepthRenderbuffer,M,!0);J.bindFramebuffer($.FRAMEBUFFER,null)}}if(N$){J.bindTexture($.TEXTURE_CUBE_MAP,n.__webglTexture),i($.TEXTURE_CUBE_MAP,F);for(let o=0;o<6;o++)if(F.mipmaps&&F.mipmaps.length>0)for(let a=0;a<F.mipmaps.length;a++)l$(S.__webglFramebuffer[o][a],M,F,$.COLOR_ATTACHMENT0,$.TEXTURE_CUBE_MAP_POSITIVE_X+o,a);else l$(S.__webglFramebuffer[o],M,F,$.COLOR_ATTACHMENT0,$.TEXTURE_CUBE_MAP_POSITIVE_X+o,0);if(q(F))_($.TEXTURE_CUBE_MAP);J.unbindTexture()}else if(Z$){for(let o=0,a=J$.length;o<a;o++){let M$=J$[o],C$=Q.get(M$),I$=$.TEXTURE_2D;if(M.isWebGL3DRenderTarget||M.isWebGLArrayRenderTarget)I$=M.isWebGL3DRenderTarget?$.TEXTURE_3D:$.TEXTURE_2D_ARRAY;if(J.bindTexture(I$,C$.__webglTexture),i(I$,M$),l$(S.__webglFramebuffer,M,M$,$.COLOR_ATTACHMENT0+o,I$,0),q(M$))_(I$)}J.unbindTexture()}else{let o=$.TEXTURE_2D;if(M.isWebGL3DRenderTarget||M.isWebGLArrayRenderTarget)o=M.isWebGL3DRenderTarget?$.TEXTURE_3D:$.TEXTURE_2D_ARRAY;if(J.bindTexture(o,n.__webglTexture),i(o,F),F.mipmaps&&F.mipmaps.length>0)for(let a=0;a<F.mipmaps.length;a++)l$(S.__webglFramebuffer[a],M,F,$.COLOR_ATTACHMENT0,o,a);else l$(S.__webglFramebuffer,M,F,$.COLOR_ATTACHMENT0,o,0);if(q(F))_(o);J.unbindTexture()}if(M.depthBuffer)J6(M)}function CU(M){let F=M.textures;for(let S=0,n=F.length;S<n;S++){let J$=F[S];if(q(J$)){let N$=P(M),Z$=Q.get(J$).__webglTexture;J.bindTexture(N$,Z$),_(N$),J.unbindTexture()}}}let z6=[],r6=[];function c6(M){if(M.samples>0){if(v(M)===!1){let{textures:F,width:S,height:n}=M,J$=$.COLOR_BUFFER_BIT,N$=M.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT,Z$=Q.get(M),o=F.length>1;if(o)for(let M$=0;M$<F.length;M$++)J.bindFramebuffer($.FRAMEBUFFER,Z$.__webglMultisampledFramebuffer),$.framebufferRenderbuffer($.FRAMEBUFFER,$.COLOR_ATTACHMENT0+M$,$.RENDERBUFFER,null),J.bindFramebuffer($.FRAMEBUFFER,Z$.__webglFramebuffer),$.framebufferTexture2D($.DRAW_FRAMEBUFFER,$.COLOR_ATTACHMENT0+M$,$.TEXTURE_2D,null,0);J.bindFramebuffer($.READ_FRAMEBUFFER,Z$.__webglMultisampledFramebuffer);let a=M.texture.mipmaps;if(a&&a.length>0)J.bindFramebuffer($.DRAW_FRAMEBUFFER,Z$.__webglFramebuffer[0]);else J.bindFramebuffer($.DRAW_FRAMEBUFFER,Z$.__webglFramebuffer);for(let M$=0;M$<F.length;M$++){if(M.resolveDepthBuffer){if(M.depthBuffer)J$|=$.DEPTH_BUFFER_BIT;if(M.stencilBuffer&&M.resolveStencilBuffer)J$|=$.STENCIL_BUFFER_BIT}if(o){$.framebufferRenderbuffer($.READ_FRAMEBUFFER,$.COLOR_ATTACHMENT0,$.RENDERBUFFER,Z$.__webglColorRenderbuffer[M$]);let C$=Q.get(F[M$]).__webglTexture;$.framebufferTexture2D($.DRAW_FRAMEBUFFER,$.COLOR_ATTACHMENT0,$.TEXTURE_2D,C$,0)}if($.blitFramebuffer(0,0,S,n,0,0,S,n,J$,$.NEAREST),H===!0){if(z6.length=0,r6.length=0,z6.push($.COLOR_ATTACHMENT0+M$),M.depthBuffer&&M.resolveDepthBuffer===!1)z6.push(N$),r6.push(N$),$.invalidateFramebuffer($.DRAW_FRAMEBUFFER,r6);$.invalidateFramebuffer($.READ_FRAMEBUFFER,z6)}}if(J.bindFramebuffer($.READ_FRAMEBUFFER,null),J.bindFramebuffer($.DRAW_FRAMEBUFFER,null),o)for(let M$=0;M$<F.length;M$++){J.bindFramebuffer($.FRAMEBUFFER,Z$.__webglMultisampledFramebuffer),$.framebufferRenderbuffer($.FRAMEBUFFER,$.COLOR_ATTACHMENT0+M$,$.RENDERBUFFER,Z$.__webglColorRenderbuffer[M$]);let C$=Q.get(F[M$]).__webglTexture;J.bindFramebuffer($.FRAMEBUFFER,Z$.__webglFramebuffer),$.framebufferTexture2D($.DRAW_FRAMEBUFFER,$.COLOR_ATTACHMENT0+M$,$.TEXTURE_2D,C$,0)}J.bindFramebuffer($.DRAW_FRAMEBUFFER,Z$.__webglMultisampledFramebuffer)}else if(M.depthBuffer&&M.resolveDepthBuffer===!1&&H){let F=M.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT;$.invalidateFramebuffer($.DRAW_FRAMEBUFFER,[F])}}}function h6(M){return Math.min(W.maxSamples,M.samples)}function v(M){let F=Q.get(M);return M.samples>0&&U.has("WEBGL_multisampled_render_to_texture")===!0&&F.__useRenderToTexture!==!1}function SU(M){let F=X.render.frame;if(G.get(M)!==F)G.set(M,F),M.update()}function G6(M,F){let{colorSpace:S,format:n,type:J$}=M;if(M.isCompressedTexture===!0||M.isVideoTexture===!0)return F;if(S!==BU&&S!==p0)if(s$.getTransfer(S)===w6){if(n!==IJ||J$!==aU)A$("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}else y$("WebGLTextures: Unsupported texture color space:",S);return F}function _6(M){if(typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement)Y.width=M.naturalWidth||M.width,Y.height=M.naturalHeight||M.height;else if(typeof VideoFrame<"u"&&M instanceof VideoFrame)Y.width=M.displayWidth,Y.height=M.displayHeight;else Y.width=M.width,Y.height=M.height;return Y}this.allocateTextureUnit=c,this.resetTextureUnits=s,this.getTextureUnits=y,this.setTextureUnits=d,this.setTexture2D=t,this.setTexture2DArray=e,this.setTexture3D=Y$,this.setTextureCube=R$,this.rebindTextures=K6,this.setupRenderTarget=d6,this.updateRenderTargetMipmap=CU,this.updateMultisampleRenderTarget=c6,this.setupDepthRenderbuffer=J6,this.setupFrameBufferTexture=l$,this.useMultisampledRTT=v,this.isReversedDepthBuffer=function(){return J.buffers.depth.getReversed()}}function Zz($,U){function J(Q,W=p0){let K,X=s$.getTransfer(W);if(Q===aU)return $.UNSIGNED_BYTE;if(Q===uO)return $.UNSIGNED_SHORT_4_4_4_4;if(Q===lO)return $.UNSIGNED_SHORT_5_5_5_1;if(Q===kk)return $.UNSIGNED_INT_5_9_9_9_REV;if(Q===Fk)return $.UNSIGNED_INT_10F_11F_11F_REV;if(Q===qk)return $.BYTE;if(Q===Dk)return $.SHORT;if(Q===kQ)return $.UNSIGNED_SHORT;if(Q===fO)return $.INT;if(Q===X0)return $.UNSIGNED_INT;if(Q===jJ)return $.FLOAT;if(Q===gJ)return $.HALF_FLOAT;if(Q===Lk)return $.ALPHA;if(Q===Rk)return $.RGB;if(Q===IJ)return $.RGBA;if(Q===u0)return $.DEPTH_COMPONENT;if(Q===l0)return $.DEPTH_STENCIL;if(Q===Vk)return $.RED;if(Q===mO)return $.RED_INTEGER;if(Q===m0)return $.RG;if(Q===pO)return $.RG_INTEGER;if(Q===dO)return $.RGBA_INTEGER;if(Q===Q7||Q===K7||Q===X7||Q===N7)if(X===w6)if(K=U.get("WEBGL_compressed_texture_s3tc_srgb"),K!==null){if(Q===Q7)return K.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(Q===K7)return K.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(Q===X7)return K.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(Q===N7)return K.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(K=U.get("WEBGL_compressed_texture_s3tc"),K!==null){if(Q===Q7)return K.COMPRESSED_RGB_S3TC_DXT1_EXT;if(Q===K7)return K.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(Q===X7)return K.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(Q===N7)return K.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(Q===cO||Q===nO||Q===iO||Q===oO)if(K=U.get("WEBGL_compressed_texture_pvrtc"),K!==null){if(Q===cO)return K.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(Q===nO)return K.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(Q===iO)return K.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(Q===oO)return K.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(Q===rO||Q===aO||Q===sO||Q===tO||Q===eO||Q===H7||Q===$E)if(K=U.get("WEBGL_compressed_texture_etc"),K!==null){if(Q===rO||Q===aO)return X===w6?K.COMPRESSED_SRGB8_ETC2:K.COMPRESSED_RGB8_ETC2;if(Q===sO)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:K.COMPRESSED_RGBA8_ETC2_EAC;if(Q===tO)return K.COMPRESSED_R11_EAC;if(Q===eO)return K.COMPRESSED_SIGNED_R11_EAC;if(Q===H7)return K.COMPRESSED_RG11_EAC;if(Q===$E)return K.COMPRESSED_SIGNED_RG11_EAC}else return null;if(Q===UE||Q===JE||Q===WE||Q===QE||Q===KE||Q===XE||Q===NE||Q===HE||Q===YE||Q===GE||Q===OE||Q===EE||Q===ZE||Q===IE)if(K=U.get("WEBGL_compressed_texture_astc"),K!==null){if(Q===UE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:K.COMPRESSED_RGBA_ASTC_4x4_KHR;if(Q===JE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:K.COMPRESSED_RGBA_ASTC_5x4_KHR;if(Q===WE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:K.COMPRESSED_RGBA_ASTC_5x5_KHR;if(Q===QE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:K.COMPRESSED_RGBA_ASTC_6x5_KHR;if(Q===KE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:K.COMPRESSED_RGBA_ASTC_6x6_KHR;if(Q===XE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:K.COMPRESSED_RGBA_ASTC_8x5_KHR;if(Q===NE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:K.COMPRESSED_RGBA_ASTC_8x6_KHR;if(Q===HE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:K.COMPRESSED_RGBA_ASTC_8x8_KHR;if(Q===YE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:K.COMPRESSED_RGBA_ASTC_10x5_KHR;if(Q===GE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:K.COMPRESSED_RGBA_ASTC_10x6_KHR;if(Q===OE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:K.COMPRESSED_RGBA_ASTC_10x8_KHR;if(Q===EE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:K.COMPRESSED_RGBA_ASTC_10x10_KHR;if(Q===ZE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:K.COMPRESSED_RGBA_ASTC_12x10_KHR;if(Q===IE)return X===w6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:K.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(Q===qE||Q===DE||Q===kE)if(K=U.get("EXT_texture_compression_bptc"),K!==null){if(Q===qE)return X===w6?K.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:K.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(Q===DE)return K.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(Q===kE)return K.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(Q===FE||Q===LE||Q===Y7||Q===RE)if(K=U.get("EXT_texture_compression_rgtc"),K!==null){if(Q===FE)return K.COMPRESSED_RED_RGTC1_EXT;if(Q===LE)return K.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(Q===Y7)return K.COMPRESSED_RED_GREEN_RGTC2_EXT;if(Q===RE)return K.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;if(Q===U8)return $.UNSIGNED_INT_24_8;return $[Q]!==void 0?$[Q]:null}return{convert:J}}var Iz=`+}`,TT=[new N(1,0,0),new N(-1,0,0),new N(0,1,0),new N(0,-1,0),new N(0,0,1),new N(0,0,-1)],ET=[new N(0,-1,0),new N(0,-1,0),new N(0,0,1),new N(0,0,-1),new N(0,-1,0),new N(0,-1,0)],W_=new ze,oo=new N,Yu=new N;function AT(e,t,n){let i=new Ks,r=new Ie,s=new Ie,o=new st,a=new Cu,c=new Iu,l={},u=n.maxTextureSize,f={[Ui]:Yt,[Yt]:Ui,[bn]:bn},h=new Mn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Ie},radius:{value:4}},vertexShader:MT,fragmentShader:wT}),d=h.clone();d.defines.HORIZONTAL_PASS=1;let g=new tn;g.setAttribute("position",new Nt(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));let y=new pt(g,h),p=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=ks;let m=this.type;this.render=function(E,R,_){if(p.enabled===!1)return;if(p.autoUpdate===!1&&p.needsUpdate===!1)return;if(E.length===0)return;if(this.type===yg)Me("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=ks;let S=e.getRenderTarget(),F=e.getActiveCubeFace(),C=e.getActiveMipmapLevel(),z=e.state;if(z.setBlending(Yn),z.buffers.depth.getReversed()===!0)z.buffers.color.setClear(0,0,0,0);else z.buffers.color.setClear(1,1,1,1);z.buffers.depth.setTest(!0),z.setScissorTest(!1);let J=m!==this.type;if(J)R.traverse(function(O){if(O.material)if(Array.isArray(O.material))O.material.forEach((H)=>H.needsUpdate=!0);else O.material.needsUpdate=!0});for(let O=0,H=E.length;O<H;O++){let V=E[O],U=V.shadow;if(U===void 0){Me("WebGLShadowMap:",V,"has no shadow.");continue}if(U.autoUpdate===!1&&U.needsUpdate===!1)continue;r.copy(U.mapSize);let K=U.getFrameExtents();if(r.multiply(K),s.copy(U.mapSize),r.x>u||r.y>u){if(r.x>u)s.x=Math.floor(u/K.x),r.x=s.x*K.x,U.mapSize.x=s.x;if(r.y>u)s.y=Math.floor(u/K.y),r.y=s.y*K.y,U.mapSize.y=s.y}let Q=e.state.buffers.depth.getReversed();if(U.camera._reversedDepth=Q,U.map===null||J===!0){if(U.map!==null){if(U.map.depthTexture!==null)U.map.depthTexture.dispose(),U.map.depthTexture=null;U.map.dispose()}if(this.type===Zr){if(V.isPointLight){Me("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}U.map=new Sn(r.x,r.y,{format:pr,type:pi,minFilter:Gt,magFilter:Gt,generateMipmaps:!1}),U.map.texture.name=V.name+".shadowMap",U.map.depthTexture=new Bi(r.x,r.y,di),U.map.depthTexture.name=V.name+".shadowMapDepth",U.map.depthTexture.format=fr,U.map.depthTexture.compareFunction=null,U.map.depthTexture.minFilter=On,U.map.depthTexture.magFilter=On}else{if(V.isPointLight)U.map=new Ku(r.x),U.map.depthTexture=new Eu(r.x,Oi);else U.map=new Sn(r.x,r.y),U.map.depthTexture=new Bi(r.x,r.y,Oi);if(U.map.depthTexture.name=V.name+".shadowMap",U.map.depthTexture.format=fr,this.type===ks)U.map.depthTexture.compareFunction=Q?Ra:Aa,U.map.depthTexture.minFilter=Gt,U.map.depthTexture.magFilter=Gt;else U.map.depthTexture.compareFunction=null,U.map.depthTexture.minFilter=On,U.map.depthTexture.magFilter=On}U.camera.updateProjectionMatrix()}let se=U.map.isWebGLCubeRenderTarget?6:1;for(let me=0;me<se;me++){if(U.map.isWebGLCubeRenderTarget)e.setRenderTarget(U.map,me),e.clear();else{if(me===0)e.setRenderTarget(U.map),e.clear();let _e=U.getViewport(me);o.set(s.x*_e.x,s.y*_e.y,s.x*_e.z,s.y*_e.w),z.viewport(o)}if(V.isPointLight){let{camera:_e,matrix:qe}=U,Ge=V.distance||_e.far;if(Ge!==_e.far)_e.far=Ge,_e.updateProjectionMatrix();oo.setFromMatrixPosition(V.matrixWorld),_e.position.copy(oo),Yu.copy(_e.position),Yu.add(TT[me]),_e.up.copy(ET[me]),_e.lookAt(Yu),_e.updateMatrixWorld(),qe.makeTranslation(-oo.x,-oo.y,-oo.z),W_.multiplyMatrices(_e.projectionMatrix,_e.matrixWorldInverse),U._frustum.setFromProjectionMatrix(W_,_e.coordinateSystem,_e.reversedDepth)}else U.updateMatrices(V);i=U.getFrustum(),v(R,_,U.camera,V,this.type)}if(U.isPointLightShadow!==!0&&this.type===Zr)A(U,_);U.needsUpdate=!1}m=this.type,p.needsUpdate=!1,e.setRenderTarget(S,F,C)};function A(E,R){let _=t.update(y);if(h.defines.VSM_SAMPLES!==E.blurSamples)h.defines.VSM_SAMPLES=E.blurSamples,d.defines.VSM_SAMPLES=E.blurSamples,h.needsUpdate=!0,d.needsUpdate=!0;if(E.mapPass===null)E.mapPass=new Sn(r.x,r.y,{format:pr,type:pi});h.uniforms.shadow_pass.value=E.map.depthTexture,h.uniforms.resolution.value=E.mapSize,h.uniforms.radius.value=E.radius,e.setRenderTarget(E.mapPass),e.clear(),e.renderBufferDirect(R,null,_,h,y,null),d.uniforms.shadow_pass.value=E.mapPass.texture,d.uniforms.resolution.value=E.mapSize,d.uniforms.radius.value=E.radius,e.setRenderTarget(E.map),e.clear(),e.renderBufferDirect(R,null,_,d,y,null)}function T(E,R,_,S){let F=null,C=_.isPointLight===!0?E.customDistanceMaterial:E.customDepthMaterial;if(C!==void 0)F=C;else if(F=_.isPointLight===!0?c:a,e.localClippingEnabled&&R.clipShadows===!0&&Array.isArray(R.clippingPlanes)&&R.clippingPlanes.length!==0||R.displacementMap&&R.displacementScale!==0||R.alphaMap&&R.alphaTest>0||R.map&&R.alphaTest>0||R.alphaToCoverage===!0){let z=F.uuid,J=R.uuid,O=l[z];if(O===void 0)O={},l[z]=O;let H=O[J];if(H===void 0)H=F.clone(),O[J]=H,R.addEventListener("dispose",w);F=H}if(F.visible=R.visible,F.wireframe=R.wireframe,S===Zr)F.side=R.shadowSide!==null?R.shadowSide:R.side;else F.side=R.shadowSide!==null?R.shadowSide:f[R.side];if(F.alphaMap=R.alphaMap,F.alphaTest=R.alphaToCoverage===!0?0.5:R.alphaTest,F.map=R.map,F.clipShadows=R.clipShadows,F.clippingPlanes=R.clippingPlanes,F.clipIntersection=R.clipIntersection,F.displacementMap=R.displacementMap,F.displacementScale=R.displacementScale,F.displacementBias=R.displacementBias,F.wireframeLinewidth=R.wireframeLinewidth,F.linewidth=R.linewidth,_.isPointLight===!0&&F.isMeshDistanceMaterial===!0){let z=e.properties.get(F);z.light=_}return F}function v(E,R,_,S,F){if(E.visible===!1)return;if(E.layers.test(R.layers)&&(E.isMesh||E.isLine||E.isPoints)){if((E.castShadow||E.receiveShadow&&F===Zr)&&(!E.frustumCulled||i.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(_.matrixWorldInverse,E.matrixWorld);let J=t.update(E),O=E.material;if(Array.isArray(O)){let H=J.groups;for(let V=0,U=H.length;V<U;V++){let K=H[V],Q=O[K.materialIndex];if(Q&&Q.visible){let se=T(E,Q,S,F);E.onBeforeShadow(e,E,R,_,J,se,K),e.renderBufferDirect(_,null,J,se,E,K),E.onAfterShadow(e,E,R,_,J,se,K)}}}else if(O.visible){let H=T(E,O,S,F);E.onBeforeShadow(e,E,R,_,J,H,null),e.renderBufferDirect(_,null,J,H,E,null),E.onAfterShadow(e,E,R,_,J,H,null)}}}let z=E.children;for(let J=0,O=z.length;J<O;J++)v(z[J],R,_,S,F)}function w(E){E.target.removeEventListener("dispose",w);for(let _ in l){let S=l[_],F=E.target.uuid;if(F in S)S[F].dispose(),delete S[F]}}}function RT(e,t){function n(){let P=!1,oe=new st,Y=null,ae=new st(0,0,0,0);return{setMask:function(ve){if(Y!==ve&&!P)e.colorMask(ve,ve,ve,ve),Y=ve},setLocked:function(ve){P=ve},setClear:function(ve,ee,ce,Fe,St){if(St===!0)ve*=Fe,ee*=Fe,ce*=Fe;if(oe.set(ve,ee,ce,Fe),ae.equals(oe)===!1)e.clearColor(ve,ee,ce,Fe),ae.copy(oe)},reset:function(){P=!1,Y=null,ae.set(-1,0,0,0)}}}function i(){let P=!1,oe=!1,Y=null,ae=null,ve=null;return{setReversed:function(ee){if(oe!==ee){let ce=t.get("EXT_clip_control");if(ee)ce.clipControlEXT(ce.LOWER_LEFT_EXT,ce.ZERO_TO_ONE_EXT);else ce.clipControlEXT(ce.LOWER_LEFT_EXT,ce.NEGATIVE_ONE_TO_ONE_EXT);oe=ee;let Fe=ve;ve=null,this.setClear(Fe)}},getReversed:function(){return oe},setTest:function(ee){if(ee)de(e.DEPTH_TEST);else Re(e.DEPTH_TEST)},setMask:function(ee){if(Y!==ee&&!P)e.depthMask(ee),Y=ee},setFunc:function(ee){if(oe)ee=p_[ee];if(ae!==ee){switch(ee){case Gg:e.depthFunc(e.NEVER);break;case Hg:e.depthFunc(e.ALWAYS);break;case Vg:e.depthFunc(e.LESS);break;case Al:e.depthFunc(e.LEQUAL);break;case Wg:e.depthFunc(e.EQUAL);break;case $g:e.depthFunc(e.GEQUAL);break;case Zg:e.depthFunc(e.GREATER);break;case Xg:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}ae=ee}},setLocked:function(ee){P=ee},setClear:function(ee){if(ve!==ee){if(ve=ee,oe)ee=1-ee;e.clearDepth(ee)}},reset:function(){P=!1,Y=null,ae=null,ve=null,oe=!1}}}function r(){let P=!1,oe=null,Y=null,ae=null,ve=null,ee=null,ce=null,Fe=null,St=null;return{setTest:function(ft){if(!P)if(ft)de(e.STENCIL_TEST);else Re(e.STENCIL_TEST)},setMask:function(ft){if(oe!==ft&&!P)e.stencilMask(ft),oe=ft},setFunc:function(ft,kn,ni){if(Y!==ft||ae!==kn||ve!==ni)e.stencilFunc(ft,kn,ni),Y=ft,ae=kn,ve=ni},setOp:function(ft,kn,ni){if(ee!==ft||ce!==kn||Fe!==ni)e.stencilOp(ft,kn,ni),ee=ft,ce=kn,Fe=ni},setLocked:function(ft){P=ft},setClear:function(ft){if(St!==ft)e.clearStencil(ft),St=ft},reset:function(){P=!1,oe=null,Y=null,ae=null,ve=null,ee=null,ce=null,Fe=null,St=null}}}let s=new n,o=new i,a=new r,c=new WeakMap,l=new WeakMap,u={},f={},h={},d=new WeakMap,g=[],y=null,p=!1,m=null,A=null,T=null,v=null,w=null,E=null,R=null,_=new Le(0,0,0),S=0,F=!1,C=null,z=null,J=null,O=null,H=null,V=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),U=!1,K=0,Q=e.getParameter(e.VERSION);if(Q.indexOf("WebGL")!==-1)K=parseFloat(/^WebGL (\d)/.exec(Q)[1]),U=K>=1;else if(Q.indexOf("OpenGL ES")!==-1)K=parseFloat(/^OpenGL ES (\d)/.exec(Q)[1]),U=K>=2;let se=null,me={},_e=e.getParameter(e.SCISSOR_BOX),qe=e.getParameter(e.VIEWPORT),Ge=new st().fromArray(_e),Z=new st().fromArray(qe);function ne(P,oe,Y,ae){let ve=new Uint8Array(4),ee=e.createTexture();e.bindTexture(P,ee),e.texParameteri(P,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(P,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let ce=0;ce<Y;ce++)if(P===e.TEXTURE_3D||P===e.TEXTURE_2D_ARRAY)e.texImage3D(oe,0,e.RGBA,1,1,ae,0,e.RGBA,e.UNSIGNED_BYTE,ve);else e.texImage2D(oe+ce,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,ve);return ee}let fe={};fe[e.TEXTURE_2D]=ne(e.TEXTURE_2D,e.TEXTURE_2D,1),fe[e.TEXTURE_CUBE_MAP]=ne(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),fe[e.TEXTURE_2D_ARRAY]=ne(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),fe[e.TEXTURE_3D]=ne(e.TEXTURE_3D,e.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),a.setClear(0),de(e.DEPTH_TEST),o.setFunc(Al),gn(!1),mt(Ml),de(e.CULL_FACE),Je(Yn);function de(P){if(u[P]!==!0)e.enable(P),u[P]=!0}function Re(P){if(u[P]!==!1)e.disable(P),u[P]=!1}function Ze(P,oe){if(h[P]!==oe){if(e.bindFramebuffer(P,oe),h[P]=oe,P===e.DRAW_FRAMEBUFFER)h[e.FRAMEBUFFER]=oe;if(P===e.FRAMEBUFFER)h[e.DRAW_FRAMEBUFFER]=oe;return!0}return!1}function Oe(P,oe){let Y=g,ae=!1;if(P){if(Y=d.get(oe),Y===void 0)Y=[],d.set(oe,Y);let ve=P.textures;if(Y.length!==ve.length||Y[0]!==e.COLOR_ATTACHMENT0){for(let ee=0,ce=ve.length;ee<ce;ee++)Y[ee]=e.COLOR_ATTACHMENT0+ee;Y.length=ve.length,ae=!0}}else if(Y[0]!==e.BACK)Y[0]=e.BACK,ae=!0;if(ae)e.drawBuffers(Y)}function ke(P){if(y!==P)return e.useProgram(P),y=P,!0;return!1}let Ke={[Xr]:e.FUNC_ADD,[Sg]:e.FUNC_SUBTRACT,[Mg]:e.FUNC_REVERSE_SUBTRACT};Ke[wg]=e.MIN,Ke[Tg]=e.MAX;let Ye={[Eg]:e.ZERO,[Ag]:e.ONE,[Rg]:e.SRC_COLOR,[Ig]:e.SRC_ALPHA,[Og]:e.SRC_ALPHA_SATURATE,[Dg]:e.DST_COLOR,[Lg]:e.DST_ALPHA,[Cg]:e.ONE_MINUS_SRC_COLOR,[Pg]:e.ONE_MINUS_SRC_ALPHA,[Ug]:e.ONE_MINUS_DST_COLOR,[Ng]:e.ONE_MINUS_DST_ALPHA,[Fg]:e.CONSTANT_COLOR,[zg]:e.ONE_MINUS_CONSTANT_COLOR,[kg]:e.CONSTANT_ALPHA,[Bg]:e.ONE_MINUS_CONSTANT_ALPHA};function Je(P,oe,Y,ae,ve,ee,ce,Fe,St,ft){if(P===Yn){if(p===!0)Re(e.BLEND),p=!1;return}if(p===!1)de(e.BLEND),p=!0;if(P!==bg){if(P!==m||ft!==F){if(A!==Xr||w!==Xr)e.blendEquation(e.FUNC_ADD),A=Xr,w=Xr;if(ft)switch(P){case Bs:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case wl:e.blendFunc(e.ONE,e.ONE);break;case Tl:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case El:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:Ne("WebGLState: Invalid blending: ",P);break}else switch(P){case Bs:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case wl:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case Tl:Ne("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case El:Ne("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Ne("WebGLState: Invalid blending: ",P);break}T=null,v=null,E=null,R=null,_.set(0,0,0),S=0,m=P,F=ft}return}if(ve=ve||oe,ee=ee||Y,ce=ce||ae,oe!==A||ve!==w)e.blendEquationSeparate(Ke[oe],Ke[ve]),A=oe,w=ve;if(Y!==T||ae!==v||ee!==E||ce!==R)e.blendFuncSeparate(Ye[Y],Ye[ae],Ye[ee],Ye[ce]),T=Y,v=ae,E=ee,R=ce;if(Fe.equals(_)===!1||St!==S)e.blendColor(Fe.r,Fe.g,Fe.b,St),_.copy(Fe),S=St;m=P,F=!1}function Ft(P,oe){P.side===bn?Re(e.CULL_FACE):de(e.CULL_FACE);let Y=P.side===Yt;if(oe)Y=!Y;gn(Y),P.blending===Bs&&P.transparent===!1?Je(Yn):Je(P.blending,P.blendEquation,P.blendSrc,P.blendDst,P.blendEquationAlpha,P.blendSrcAlpha,P.blendDstAlpha,P.blendColor,P.blendAlpha,P.premultipliedAlpha),o.setFunc(P.depthFunc),o.setTest(P.depthTest),o.setMask(P.depthWrite),s.setMask(P.colorWrite);let ae=P.stencilWrite;if(a.setTest(ae),ae)a.setMask(P.stencilWriteMask),a.setFunc(P.stencilFunc,P.stencilRef,P.stencilFuncMask),a.setOp(P.stencilFail,P.stencilZFail,P.stencilZPass);zt(P.polygonOffset,P.polygonOffsetFactor,P.polygonOffsetUnits),P.alphaToCoverage===!0?de(e.SAMPLE_ALPHA_TO_COVERAGE):Re(e.SAMPLE_ALPHA_TO_COVERAGE)}function gn(P){if(C!==P){if(P)e.frontFace(e.CW);else e.frontFace(e.CCW);C=P}}function mt(P){if(P!==xg){if(de(e.CULL_FACE),P!==z)if(P===Ml)e.cullFace(e.BACK);else if(P===vg)e.cullFace(e.FRONT);else e.cullFace(e.FRONT_AND_BACK)}else Re(e.CULL_FACE);z=P}function Ht(P){if(P!==J){if(U)e.lineWidth(P);J=P}}function zt(P,oe,Y){if(P){if(de(e.POLYGON_OFFSET_FILL),O!==oe||H!==Y){if(O=oe,H=Y,o.getReversed())oe=-oe;e.polygonOffset(oe,Y)}}else Re(e.POLYGON_OFFSET_FILL)}function Pt(P){if(P)de(e.SCISSOR_TEST);else Re(e.SCISSOR_TEST)}function L(P){if(P===void 0)P=e.TEXTURE0+V-1;if(se!==P)e.activeTexture(P),se=P}function _n(P,oe,Y){if(Y===void 0)if(se===null)Y=e.TEXTURE0+V-1;else Y=se;let ae=me[Y];if(ae===void 0)ae={type:void 0,texture:void 0},me[Y]=ae;if(ae.type!==P||ae.texture!==oe){if(se!==Y)e.activeTexture(Y),se=Y;e.bindTexture(P,oe||fe[P]),ae.type=P,ae.texture=oe}}function nt(){let P=me[se];if(P!==void 0&&P.type!==void 0)e.bindTexture(P.type,null),P.type=void 0,P.texture=void 0}function gt(){try{e.compressedTexImage2D(...arguments)}catch(P){Ne("WebGLState:",P)}}function M(){try{e.compressedTexImage3D(...arguments)}catch(P){Ne("WebGLState:",P)}}function x(){try{e.texSubImage2D(...arguments)}catch(P){Ne("WebGLState:",P)}}function I(){try{e.texSubImage3D(...arguments)}catch(P){Ne("WebGLState:",P)}}function W(){try{e.compressedTexSubImage2D(...arguments)}catch(P){Ne("WebGLState:",P)}}function te(){try{e.compressedTexSubImage3D(...arguments)}catch(P){Ne("WebGLState:",P)}}function ie(){try{e.texStorage2D(...arguments)}catch(P){Ne("WebGLState:",P)}}function le(){try{e.texStorage3D(...arguments)}catch(P){Ne("WebGLState:",P)}}function X(){try{e.texImage2D(...arguments)}catch(P){Ne("WebGLState:",P)}}function j(){try{e.texImage3D(...arguments)}catch(P){Ne("WebGLState:",P)}}function xe(P){if(f[P]!==void 0)return f[P];else return e.getParameter(P)}function we(P,oe){if(f[P]!==oe)e.pixelStorei(P,oe),f[P]=oe}function ue(P){if(Ge.equals(P)===!1)e.scissor(P.x,P.y,P.z,P.w),Ge.copy(P)}function re(P){if(Z.equals(P)===!1)e.viewport(P.x,P.y,P.z,P.w),Z.copy(P)}function Ce(P,oe){let Y=l.get(oe);if(Y===void 0)Y=new WeakMap,l.set(oe,Y);let ae=Y.get(P);if(ae===void 0)ae=e.getUniformBlockIndex(oe,P.name),Y.set(P,ae)}function Pe(P,oe){let ae=l.get(oe).get(P);if(c.get(oe)!==ae)e.uniformBlockBinding(oe,ae,P.__bindingPointIndex),c.set(oe,ae)}function et(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},f={},se=null,me={},h={},d=new WeakMap,g=[],y=null,p=!1,m=null,A=null,T=null,v=null,w=null,E=null,R=null,_=new Le(0,0,0),S=0,F=!1,C=null,z=null,J=null,O=null,H=null,Ge.set(0,0,e.canvas.width,e.canvas.height),Z.set(0,0,e.canvas.width,e.canvas.height),s.reset(),o.reset(),a.reset()}return{buffers:{color:s,depth:o,stencil:a},enable:de,disable:Re,bindFramebuffer:Ze,drawBuffers:Oe,useProgram:ke,setBlending:Je,setMaterial:Ft,setFlipSided:gn,setCullFace:mt,setLineWidth:Ht,setPolygonOffset:zt,setScissorTest:Pt,activeTexture:L,bindTexture:_n,unbindTexture:nt,compressedTexImage2D:gt,compressedTexImage3D:M,texImage2D:X,texImage3D:j,pixelStorei:we,getParameter:xe,updateUBOMapping:Ce,uniformBlockBinding:Pe,texStorage2D:ie,texStorage3D:le,texSubImage2D:x,texSubImage3D:I,compressedTexSubImage2D:W,compressedTexSubImage3D:te,scissor:ue,viewport:re,reset:et}}function CT(e,t,n,i,r,s,o){let a=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Ie,u=new WeakMap,f=new Set,h,d=new WeakMap,g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch(M){}function y(M,x){return g?new OffscreenCanvas(M,x):Vr("canvas")}function p(M,x,I){let W=1,te=gt(M);if(te.width>I||te.height>I)W=I/Math.max(te.width,te.height);if(W<1)if(typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&M instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&M instanceof ImageBitmap||typeof VideoFrame<"u"&&M instanceof VideoFrame){let ie=Math.floor(W*te.width),le=Math.floor(W*te.height);if(h===void 0)h=y(ie,le);let X=x?y(ie,le):h;return X.width=ie,X.height=le,X.getContext("2d").drawImage(M,0,0,ie,le),Me("WebGLRenderer: Texture has been resized from ("+te.width+"x"+te.height+") to ("+ie+"x"+le+")."),X}else{if("data"in M)Me("WebGLRenderer: Image in DataTexture is too big ("+te.width+"x"+te.height+").");return M}return M}function m(M){return M.generateMipmaps}function A(M){e.generateMipmap(M)}function T(M){if(M.isWebGLCubeRenderTarget)return e.TEXTURE_CUBE_MAP;if(M.isWebGL3DRenderTarget)return e.TEXTURE_3D;if(M.isWebGLArrayRenderTarget||M.isCompressedArrayTexture)return e.TEXTURE_2D_ARRAY;return e.TEXTURE_2D}function v(M,x,I,W,te,ie=!1){if(M!==null){if(e[M]!==void 0)return e[M];Me("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+M+"'")}let le;if(W){if(le=t.get("EXT_texture_norm16"),!le)Me("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension")}let X=x;if(x===e.RED){if(I===e.FLOAT)X=e.R32F;if(I===e.HALF_FLOAT)X=e.R16F;if(I===e.UNSIGNED_BYTE)X=e.R8;if(I===e.UNSIGNED_SHORT&&le)X=le.R16_EXT;if(I===e.SHORT&&le)X=le.R16_SNORM_EXT}if(x===e.RED_INTEGER){if(I===e.UNSIGNED_BYTE)X=e.R8UI;if(I===e.UNSIGNED_SHORT)X=e.R16UI;if(I===e.UNSIGNED_INT)X=e.R32UI;if(I===e.BYTE)X=e.R8I;if(I===e.SHORT)X=e.R16I;if(I===e.INT)X=e.R32I}if(x===e.RG){if(I===e.FLOAT)X=e.RG32F;if(I===e.HALF_FLOAT)X=e.RG16F;if(I===e.UNSIGNED_BYTE)X=e.RG8;if(I===e.UNSIGNED_SHORT&&le)X=le.RG16_EXT;if(I===e.SHORT&&le)X=le.RG16_SNORM_EXT}if(x===e.RG_INTEGER){if(I===e.UNSIGNED_BYTE)X=e.RG8UI;if(I===e.UNSIGNED_SHORT)X=e.RG16UI;if(I===e.UNSIGNED_INT)X=e.RG32UI;if(I===e.BYTE)X=e.RG8I;if(I===e.SHORT)X=e.RG16I;if(I===e.INT)X=e.RG32I}if(x===e.RGB_INTEGER){if(I===e.UNSIGNED_BYTE)X=e.RGB8UI;if(I===e.UNSIGNED_SHORT)X=e.RGB16UI;if(I===e.UNSIGNED_INT)X=e.RGB32UI;if(I===e.BYTE)X=e.RGB8I;if(I===e.SHORT)X=e.RGB16I;if(I===e.INT)X=e.RGB32I}if(x===e.RGBA_INTEGER){if(I===e.UNSIGNED_BYTE)X=e.RGBA8UI;if(I===e.UNSIGNED_SHORT)X=e.RGBA16UI;if(I===e.UNSIGNED_INT)X=e.RGBA32UI;if(I===e.BYTE)X=e.RGBA8I;if(I===e.SHORT)X=e.RGBA16I;if(I===e.INT)X=e.RGBA32I}if(x===e.RGB){if(I===e.UNSIGNED_SHORT&&le)X=le.RGB16_EXT;if(I===e.SHORT&&le)X=le.RGB16_SNORM_EXT;if(I===e.UNSIGNED_INT_5_9_9_9_REV)X=e.RGB9_E5;if(I===e.UNSIGNED_INT_10F_11F_11F_REV)X=e.R11F_G11F_B10F}if(x===e.RGBA){let j=ie?vu:We.getTransfer(te);if(I===e.FLOAT)X=e.RGBA32F;if(I===e.HALF_FLOAT)X=e.RGBA16F;if(I===e.UNSIGNED_BYTE)X=j===ht?e.SRGB8_ALPHA8:e.RGBA8;if(I===e.UNSIGNED_SHORT&&le)X=le.RGBA16_EXT;if(I===e.SHORT&&le)X=le.RGBA16_SNORM_EXT;if(I===e.UNSIGNED_SHORT_4_4_4_4)X=e.RGBA4;if(I===e.UNSIGNED_SHORT_5_5_5_1)X=e.RGB5_A1}if(X===e.R16F||X===e.R32F||X===e.RG16F||X===e.RG32F||X===e.RGBA16F||X===e.RGBA32F)t.get("EXT_color_buffer_float");return X}function w(M,x){let I;if(M){if(x===null||x===Oi||x===Kr)I=e.DEPTH24_STENCIL8;else if(x===di)I=e.DEPTH32F_STENCIL8;else if(x===Vs)I=e.DEPTH24_STENCIL8,Me("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")}else if(x===null||x===Oi||x===Kr)I=e.DEPTH_COMPONENT24;else if(x===di)I=e.DEPTH_COMPONENT32F;else if(x===Vs)I=e.DEPTH_COMPONENT16;return I}function E(M,x){if(m(M)===!0||M.isFramebufferTexture&&M.minFilter!==On&&M.minFilter!==Gt)return Math.log2(Math.max(x.width,x.height))+1;else if(M.mipmaps!==void 0&&M.mipmaps.length>0)return M.mipmaps.length;else if(M.isCompressedTexture&&Array.isArray(M.image))return x.mipmaps.length;else return 1}function R(M){let x=M.target;if(x.removeEventListener("dispose",R),S(x),x.isVideoTexture)u.delete(x);if(x.isHTMLTexture)f.delete(x)}function _(M){let x=M.target;x.removeEventListener("dispose",_),C(x)}function S(M){let x=i.get(M);if(x.__webglInit===void 0)return;let I=M.source,W=d.get(I);if(W){let te=W[x.__cacheKey];if(te.usedTimes--,te.usedTimes===0)F(M);if(Object.keys(W).length===0)d.delete(I)}i.remove(M)}function F(M){let x=i.get(M);e.deleteTexture(x.__webglTexture);let I=M.source,W=d.get(I);delete W[x.__cacheKey],o.memory.textures--}function C(M){let x=i.get(M);if(M.depthTexture)M.depthTexture.dispose(),i.remove(M.depthTexture);if(M.isWebGLCubeRenderTarget)for(let W=0;W<6;W++){if(Array.isArray(x.__webglFramebuffer[W]))for(let te=0;te<x.__webglFramebuffer[W].length;te++)e.deleteFramebuffer(x.__webglFramebuffer[W][te]);else e.deleteFramebuffer(x.__webglFramebuffer[W]);if(x.__webglDepthbuffer)e.deleteRenderbuffer(x.__webglDepthbuffer[W])}else{if(Array.isArray(x.__webglFramebuffer))for(let W=0;W<x.__webglFramebuffer.length;W++)e.deleteFramebuffer(x.__webglFramebuffer[W]);else e.deleteFramebuffer(x.__webglFramebuffer);if(x.__webglDepthbuffer)e.deleteRenderbuffer(x.__webglDepthbuffer);if(x.__webglMultisampledFramebuffer)e.deleteFramebuffer(x.__webglMultisampledFramebuffer);if(x.__webglColorRenderbuffer){for(let W=0;W<x.__webglColorRenderbuffer.length;W++)if(x.__webglColorRenderbuffer[W])e.deleteRenderbuffer(x.__webglColorRenderbuffer[W])}if(x.__webglDepthRenderbuffer)e.deleteRenderbuffer(x.__webglDepthRenderbuffer)}let I=M.textures;for(let W=0,te=I.length;W<te;W++){let ie=i.get(I[W]);if(ie.__webglTexture)e.deleteTexture(ie.__webglTexture),o.memory.textures--;i.remove(I[W])}i.remove(M)}let z=0;function J(){z=0}function O(){return z}function H(M){z=M}function V(){let M=z;if(M>=r.maxTextures)Me("WebGLTextures: Trying to use "+M+" texture units while this GPU supports only "+r.maxTextures);return z+=1,M}function U(M){let x=[];return x.push(M.wrapS),x.push(M.wrapT),x.push(M.wrapR||0),x.push(M.magFilter),x.push(M.minFilter),x.push(M.anisotropy),x.push(M.internalFormat),x.push(M.format),x.push(M.type),x.push(M.generateMipmaps),x.push(M.premultiplyAlpha),x.push(M.flipY),x.push(M.unpackAlignment),x.push(M.colorSpace),x.join()}function K(M,x){let I=i.get(M);if(M.isVideoTexture)_n(M);if(M.isRenderTargetTexture===!1&&M.isExternalTexture!==!0&&M.version>0&&I.__version!==M.version){let W=M.image;if(W===null)Me("WebGLRenderer: Texture marked for update but no image data found.");else if(W.complete===!1)Me("WebGLRenderer: Texture marked for update but image is incomplete");else{Re(I,M,x);return}}else if(M.isExternalTexture)I.__webglTexture=M.sourceTexture?M.sourceTexture:null;n.bindTexture(e.TEXTURE_2D,I.__webglTexture,e.TEXTURE0+x)}function Q(M,x){let I=i.get(M);if(M.isRenderTargetTexture===!1&&M.version>0&&I.__version!==M.version){Re(I,M,x);return}else if(M.isExternalTexture)I.__webglTexture=M.sourceTexture?M.sourceTexture:null;n.bindTexture(e.TEXTURE_2D_ARRAY,I.__webglTexture,e.TEXTURE0+x)}function se(M,x){let I=i.get(M);if(M.isRenderTargetTexture===!1&&M.version>0&&I.__version!==M.version){Re(I,M,x);return}n.bindTexture(e.TEXTURE_3D,I.__webglTexture,e.TEXTURE0+x)}function me(M,x){let I=i.get(M);if(M.isCubeDepthTexture!==!0&&M.version>0&&I.__version!==M.version){Ze(I,M,x);return}n.bindTexture(e.TEXTURE_CUBE_MAP,I.__webglTexture,e.TEXTURE0+x)}let _e={[Yr]:e.REPEAT,[jr]:e.CLAMP_TO_EDGE,[xa]:e.MIRRORED_REPEAT},qe={[On]:e.NEAREST,[va]:e.NEAREST_MIPMAP_NEAREST,[hr]:e.NEAREST_MIPMAP_LINEAR,[Gt]:e.LINEAR,[Jr]:e.LINEAR_MIPMAP_NEAREST,[jn]:e.LINEAR_MIPMAP_LINEAR},Ge={[s_]:e.NEVER,[u_]:e.ALWAYS,[o_]:e.LESS,[Aa]:e.LEQUAL,[a_]:e.EQUAL,[Ra]:e.GEQUAL,[c_]:e.GREATER,[l_]:e.NOTEQUAL};function Z(M,x){if(x.type===di&&t.has("OES_texture_float_linear")===!1&&(x.magFilter===Gt||x.magFilter===Jr||x.magFilter===hr||x.magFilter===jn||x.minFilter===Gt||x.minFilter===Jr||x.minFilter===hr||x.minFilter===jn))Me("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.");if(e.texParameteri(M,e.TEXTURE_WRAP_S,_e[x.wrapS]),e.texParameteri(M,e.TEXTURE_WRAP_T,_e[x.wrapT]),M===e.TEXTURE_3D||M===e.TEXTURE_2D_ARRAY)e.texParameteri(M,e.TEXTURE_WRAP_R,_e[x.wrapR]);if(e.texParameteri(M,e.TEXTURE_MAG_FILTER,qe[x.magFilter]),e.texParameteri(M,e.TEXTURE_MIN_FILTER,qe[x.minFilter]),x.compareFunction)e.texParameteri(M,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(M,e.TEXTURE_COMPARE_FUNC,Ge[x.compareFunction]);if(t.has("EXT_texture_filter_anisotropic")===!0){if(x.magFilter===On)return;if(x.minFilter!==hr&&x.minFilter!==jn)return;if(x.type===di&&t.has("OES_texture_float_linear")===!1)return;if(x.anisotropy>1||i.get(x).__currentAnisotropy){let I=t.get("EXT_texture_filter_anisotropic");e.texParameterf(M,I.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(x.anisotropy,r.getMaxAnisotropy())),i.get(x).__currentAnisotropy=x.anisotropy}}}function ne(M,x){let I=!1;if(M.__webglInit===void 0)M.__webglInit=!0,x.addEventListener("dispose",R);let W=x.source,te=d.get(W);if(te===void 0)te={},d.set(W,te);let ie=U(x);if(ie!==M.__cacheKey){if(te[ie]===void 0)te[ie]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,I=!0;te[ie].usedTimes++;let le=te[M.__cacheKey];if(le!==void 0){if(te[M.__cacheKey].usedTimes--,le.usedTimes===0)F(x)}M.__cacheKey=ie,M.__webglTexture=te[ie].texture}return I}function fe(M,x,I){return Math.floor(Math.floor(M/I)/x)}function de(M,x,I,W){let ie=M.updateRanges;if(ie.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,x.width,x.height,I,W,x.data);else{ie.sort((we,ue)=>we.start-ue.start);let le=0;for(let we=1;we<ie.length;we++){let ue=ie[le],re=ie[we],Ce=ue.start+ue.count,Pe=fe(re.start,x.width,4),et=fe(ue.start,x.width,4);if(re.start<=Ce+1&&Pe===et&&fe(re.start+re.count-1,x.width,4)===Pe)ue.count=Math.max(ue.count,re.start+re.count-ue.start);else++le,ie[le]=re}ie.length=le+1;let X=n.getParameter(e.UNPACK_ROW_LENGTH),j=n.getParameter(e.UNPACK_SKIP_PIXELS),xe=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,x.width);for(let we=0,ue=ie.length;we<ue;we++){let re=ie[we],Ce=Math.floor(re.start/4),Pe=Math.ceil(re.count/4),et=Ce%x.width,P=Math.floor(Ce/x.width),oe=Pe,Y=1;n.pixelStorei(e.UNPACK_SKIP_PIXELS,et),n.pixelStorei(e.UNPACK_SKIP_ROWS,P),n.texSubImage2D(e.TEXTURE_2D,0,et,P,oe,1,I,W,x.data)}M.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,X),n.pixelStorei(e.UNPACK_SKIP_PIXELS,j),n.pixelStorei(e.UNPACK_SKIP_ROWS,xe)}}function Re(M,x,I){let W=e.TEXTURE_2D;if(x.isDataArrayTexture||x.isCompressedArrayTexture)W=e.TEXTURE_2D_ARRAY;if(x.isData3DTexture)W=e.TEXTURE_3D;let te=ne(M,x),ie=x.source;n.bindTexture(W,M.__webglTexture,e.TEXTURE0+I);let le=i.get(ie);if(ie.version!==le.__version||te===!0){if(n.activeTexture(e.TEXTURE0+I),(typeof ImageBitmap<"u"&&x.image instanceof ImageBitmap)===!1){let Y=We.getPrimaries(We.workingColorSpace),ae=x.colorSpace===mr?null:We.getPrimaries(x.colorSpace),ve=x.colorSpace===mr||Y===ae?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,x.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,ve)}n.pixelStorei(e.UNPACK_ALIGNMENT,x.unpackAlignment);let j=p(x.image,!1,r.maxTextureSize);j=nt(x,j);let xe=s.convert(x.format,x.colorSpace),we=s.convert(x.type),ue=v(x.internalFormat,xe,we,x.normalized,x.colorSpace,x.isVideoTexture);Z(W,x);let re,Ce=x.mipmaps,Pe=x.isVideoTexture!==!0,et=le.__version===void 0||te===!0,P=ie.dataReady,oe=E(x,j);if(x.isDepthTexture){if(ue=w(x.format===dr,x.type),et)if(Pe)n.texStorage2D(e.TEXTURE_2D,1,ue,j.width,j.height);else n.texImage2D(e.TEXTURE_2D,0,ue,j.width,j.height,0,xe,we,null)}else if(x.isDataTexture)if(Ce.length>0){if(Pe&&et)n.texStorage2D(e.TEXTURE_2D,oe,ue,Ce[0].width,Ce[0].height);for(let Y=0,ae=Ce.length;Y<ae;Y++)if(re=Ce[Y],Pe){if(P)n.texSubImage2D(e.TEXTURE_2D,Y,0,0,re.width,re.height,xe,we,re.data)}else n.texImage2D(e.TEXTURE_2D,Y,ue,re.width,re.height,0,xe,we,re.data);x.generateMipmaps=!1}else if(Pe){if(et)n.texStorage2D(e.TEXTURE_2D,oe,ue,j.width,j.height);if(P)de(x,j,xe,we)}else n.texImage2D(e.TEXTURE_2D,0,ue,j.width,j.height,0,xe,we,j.data);else if(x.isCompressedTexture)if(x.isCompressedArrayTexture){if(Pe&&et)n.texStorage3D(e.TEXTURE_2D_ARRAY,oe,ue,Ce[0].width,Ce[0].height,j.depth);for(let Y=0,ae=Ce.length;Y<ae;Y++)if(re=Ce[Y],x.format!==Jn)if(xe!==null)if(Pe){if(P)if(x.layerUpdates.size>0){let ve=Vu(re.width,re.height,x.format,x.type);for(let ee of x.layerUpdates){let ce=re.data.subarray(ee*ve/re.data.BYTES_PER_ELEMENT,(ee+1)*ve/re.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,Y,0,0,ee,re.width,re.height,1,xe,ce)}x.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,Y,0,0,0,re.width,re.height,j.depth,xe,re.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,Y,ue,re.width,re.height,j.depth,0,re.data,0,0);else Me("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(Pe){if(P)n.texSubImage3D(e.TEXTURE_2D_ARRAY,Y,0,0,0,re.width,re.height,j.depth,xe,we,re.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,Y,ue,re.width,re.height,j.depth,0,xe,we,re.data)}else{if(Pe&&et)n.texStorage2D(e.TEXTURE_2D,oe,ue,Ce[0].width,Ce[0].height);for(let Y=0,ae=Ce.length;Y<ae;Y++)if(re=Ce[Y],x.format!==Jn)if(xe!==null)if(Pe){if(P)n.compressedTexSubImage2D(e.TEXTURE_2D,Y,0,0,re.width,re.height,xe,re.data)}else n.compressedTexImage2D(e.TEXTURE_2D,Y,ue,re.width,re.height,0,re.data);else Me("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(Pe){if(P)n.texSubImage2D(e.TEXTURE_2D,Y,0,0,re.width,re.height,xe,we,re.data)}else n.texImage2D(e.TEXTURE_2D,Y,ue,re.width,re.height,0,xe,we,re.data)}else if(x.isDataArrayTexture)if(Pe){if(et)n.texStorage3D(e.TEXTURE_2D_ARRAY,oe,ue,j.width,j.height,j.depth);if(P)if(x.layerUpdates.size>0){let Y=Vu(j.width,j.height,x.format,x.type);for(let ae of x.layerUpdates){let ve=j.data.subarray(ae*Y/j.data.BYTES_PER_ELEMENT,(ae+1)*Y/j.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,ae,j.width,j.height,1,xe,we,ve)}x.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,j.width,j.height,j.depth,xe,we,j.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,ue,j.width,j.height,j.depth,0,xe,we,j.data);else if(x.isData3DTexture)if(Pe){if(et)n.texStorage3D(e.TEXTURE_3D,oe,ue,j.width,j.height,j.depth);if(P)n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,j.width,j.height,j.depth,xe,we,j.data)}else n.texImage3D(e.TEXTURE_3D,0,ue,j.width,j.height,j.depth,0,xe,we,j.data);else if(x.isFramebufferTexture){if(et)if(Pe)n.texStorage2D(e.TEXTURE_2D,oe,ue,j.width,j.height);else{let Y=j.width,ae=j.height;for(let ve=0;ve<oe;ve++)n.texImage2D(e.TEXTURE_2D,ve,ue,Y,ae,0,xe,we,null),Y>>=1,ae>>=1}}else if(x.isHTMLTexture){if("texElementImage2D"in e){let Y=e.canvas;if(!Y.hasAttribute("layoutsubtree"))Y.setAttribute("layoutsubtree","true");if(j.parentNode!==Y){Y.appendChild(j),f.add(x),Y.onpaint=(ae)=>{let ve=ae.changedElements;for(let ee of f)if(ve.includes(ee.image))ee.needsUpdate=!0},Y.requestPaint();return}if(e.texElementImage2D.length===3)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,j);else{let{RGBA:ve,RGBA:ee,UNSIGNED_BYTE:ce}=e;e.texElementImage2D(e.TEXTURE_2D,0,ve,ee,ce,j)}e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(Ce.length>0){if(Pe&&et){let Y=gt(Ce[0]);n.texStorage2D(e.TEXTURE_2D,oe,ue,Y.width,Y.height)}for(let Y=0,ae=Ce.length;Y<ae;Y++)if(re=Ce[Y],Pe){if(P)n.texSubImage2D(e.TEXTURE_2D,Y,0,0,xe,we,re)}else n.texImage2D(e.TEXTURE_2D,Y,ue,xe,we,re);x.generateMipmaps=!1}else if(Pe){if(et){let Y=gt(j);n.texStorage2D(e.TEXTURE_2D,oe,ue,Y.width,Y.height)}if(P)n.texSubImage2D(e.TEXTURE_2D,0,0,0,xe,we,j)}else n.texImage2D(e.TEXTURE_2D,0,ue,xe,we,j);if(m(x))A(W);if(le.__version=ie.version,x.onUpdate)x.onUpdate(x)}M.__version=x.version}function Ze(M,x,I){if(x.image.length!==6)return;let W=ne(M,x),te=x.source;n.bindTexture(e.TEXTURE_CUBE_MAP,M.__webglTexture,e.TEXTURE0+I);let ie=i.get(te);if(te.version!==ie.__version||W===!0){n.activeTexture(e.TEXTURE0+I);let le=We.getPrimaries(We.workingColorSpace),X=x.colorSpace===mr?null:We.getPrimaries(x.colorSpace),j=x.colorSpace===mr||le===X?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,x.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,x.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,j);let xe=x.isCompressedTexture||x.image[0].isCompressedTexture,we=x.image[0]&&x.image[0].isDataTexture,ue=[];for(let ee=0;ee<6;ee++){if(!xe&&!we)ue[ee]=p(x.image[ee],!0,r.maxCubemapSize);else ue[ee]=we?x.image[ee].image:x.image[ee];ue[ee]=nt(x,ue[ee])}let re=ue[0],Ce=s.convert(x.format,x.colorSpace),Pe=s.convert(x.type),et=v(x.internalFormat,Ce,Pe,x.normalized,x.colorSpace),P=x.isVideoTexture!==!0,oe=ie.__version===void 0||W===!0,Y=te.dataReady,ae=E(x,re);Z(e.TEXTURE_CUBE_MAP,x);let ve;if(xe){if(P&&oe)n.texStorage2D(e.TEXTURE_CUBE_MAP,ae,et,re.width,re.height);for(let ee=0;ee<6;ee++){ve=ue[ee].mipmaps;for(let ce=0;ce<ve.length;ce++){let Fe=ve[ce];if(x.format!==Jn)if(Ce!==null)if(P){if(Y)n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce,0,0,Fe.width,Fe.height,Ce,Fe.data)}else n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce,et,Fe.width,Fe.height,0,Fe.data);else Me("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()");else if(P){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce,0,0,Fe.width,Fe.height,Ce,Pe,Fe.data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce,et,Fe.width,Fe.height,0,Ce,Pe,Fe.data)}}}else{if(ve=x.mipmaps,P&&oe){if(ve.length>0)ae++;let ee=gt(ue[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,ae,et,ee.width,ee.height)}for(let ee=0;ee<6;ee++)if(we){if(P){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,0,0,0,ue[ee].width,ue[ee].height,Ce,Pe,ue[ee].data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,0,et,ue[ee].width,ue[ee].height,0,Ce,Pe,ue[ee].data);for(let ce=0;ce<ve.length;ce++){let St=ve[ce].image[ee].image;if(P){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce+1,0,0,St.width,St.height,Ce,Pe,St.data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce+1,et,St.width,St.height,0,Ce,Pe,St.data)}}else{if(P){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,0,0,0,Ce,Pe,ue[ee])}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,0,et,Ce,Pe,ue[ee]);for(let ce=0;ce<ve.length;ce++){let Fe=ve[ce];if(P){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce+1,0,0,Ce,Pe,Fe.image[ee])}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce+1,et,Ce,Pe,Fe.image[ee])}}}if(m(x))A(e.TEXTURE_CUBE_MAP);if(ie.__version=te.version,x.onUpdate)x.onUpdate(x)}M.__version=x.version}function Oe(M,x,I,W,te,ie){let le=s.convert(I.format,I.colorSpace),X=s.convert(I.type),j=v(I.internalFormat,le,X,I.normalized,I.colorSpace),xe=i.get(x),we=i.get(I);if(we.__renderTarget=x,!xe.__hasExternalTextures){let ue=Math.max(1,x.width>>ie),re=Math.max(1,x.height>>ie);if(te===e.TEXTURE_3D||te===e.TEXTURE_2D_ARRAY)n.texImage3D(te,ie,j,ue,re,x.depth,0,le,X,null);else n.texImage2D(te,ie,j,ue,re,0,le,X,null)}if(n.bindFramebuffer(e.FRAMEBUFFER,M),L(x))a.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,W,te,we.__webglTexture,0,Pt(x));else if(te===e.TEXTURE_2D||te>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&te<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)e.framebufferTexture2D(e.FRAMEBUFFER,W,te,we.__webglTexture,ie);n.bindFramebuffer(e.FRAMEBUFFER,null)}function ke(M,x,I){if(e.bindRenderbuffer(e.RENDERBUFFER,M),x.depthBuffer){let W=x.depthTexture,te=W&&W.isDepthTexture?W.type:null,ie=w(x.stencilBuffer,te),le=x.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(L(x))a.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Pt(x),ie,x.width,x.height);else if(I)e.renderbufferStorageMultisample(e.RENDERBUFFER,Pt(x),ie,x.width,x.height);else e.renderbufferStorage(e.RENDERBUFFER,ie,x.width,x.height);e.framebufferRenderbuffer(e.FRAMEBUFFER,le,e.RENDERBUFFER,M)}else{let W=x.textures;for(let te=0;te<W.length;te++){let ie=W[te],le=s.convert(ie.format,ie.colorSpace),X=s.convert(ie.type),j=v(ie.internalFormat,le,X,ie.normalized,ie.colorSpace);if(L(x))a.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Pt(x),j,x.width,x.height);else if(I)e.renderbufferStorageMultisample(e.RENDERBUFFER,Pt(x),j,x.width,x.height);else e.renderbufferStorage(e.RENDERBUFFER,j,x.width,x.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function Ke(M,x,I){let W=x.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,M),!(x.depthTexture&&x.depthTexture.isDepthTexture))throw Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");let te=i.get(x.depthTexture);if(te.__renderTarget=x,!te.__webglTexture||x.depthTexture.image.width!==x.width||x.depthTexture.image.height!==x.height)x.depthTexture.image.width=x.width,x.depthTexture.image.height=x.height,x.depthTexture.needsUpdate=!0;if(W){if(te.__webglInit===void 0)te.__webglInit=!0,x.depthTexture.addEventListener("dispose",R);if(te.__webglTexture===void 0){te.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,te.__webglTexture),Z(e.TEXTURE_CUBE_MAP,x.depthTexture);let xe=s.convert(x.depthTexture.format),we=s.convert(x.depthTexture.type),ue;if(x.depthTexture.format===fr)ue=e.DEPTH_COMPONENT24;else if(x.depthTexture.format===dr)ue=e.DEPTH24_STENCIL8;for(let re=0;re<6;re++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,ue,x.width,x.height,0,xe,we,null)}}else K(x.depthTexture,0);let ie=te.__webglTexture,le=Pt(x),X=W?e.TEXTURE_CUBE_MAP_POSITIVE_X+I:e.TEXTURE_2D,j=x.depthTexture.format===dr?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(x.depthTexture.format===fr)if(L(x))a.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,j,X,ie,0,le);else e.framebufferTexture2D(e.FRAMEBUFFER,j,X,ie,0);else if(x.depthTexture.format===dr)if(L(x))a.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,j,X,ie,0,le);else e.framebufferTexture2D(e.FRAMEBUFFER,j,X,ie,0);else throw Error("THREE.WebGLTextures: Unknown depthTexture format.")}function Ye(M){let x=i.get(M),I=M.isWebGLCubeRenderTarget===!0;if(x.__boundDepthTexture!==M.depthTexture){let W=M.depthTexture;if(x.__depthDisposeCallback)x.__depthDisposeCallback();if(W){let te=()=>{delete x.__boundDepthTexture,delete x.__depthDisposeCallback,W.removeEventListener("dispose",te)};W.addEventListener("dispose",te),x.__depthDisposeCallback=te}x.__boundDepthTexture=W}if(M.depthTexture&&!x.__autoAllocateDepthBuffer)if(I)for(let W=0;W<6;W++)Ke(x.__webglFramebuffer[W],M,W);else{let W=M.texture.mipmaps;if(W&&W.length>0)Ke(x.__webglFramebuffer[0],M,0);else Ke(x.__webglFramebuffer,M,0)}else if(I){x.__webglDepthbuffer=[];for(let W=0;W<6;W++)if(n.bindFramebuffer(e.FRAMEBUFFER,x.__webglFramebuffer[W]),x.__webglDepthbuffer[W]===void 0)x.__webglDepthbuffer[W]=e.createRenderbuffer(),ke(x.__webglDepthbuffer[W],M,!1);else{let te=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ie=x.__webglDepthbuffer[W];e.bindRenderbuffer(e.RENDERBUFFER,ie),e.framebufferRenderbuffer(e.FRAMEBUFFER,te,e.RENDERBUFFER,ie)}}else{let W=M.texture.mipmaps;if(W&&W.length>0)n.bindFramebuffer(e.FRAMEBUFFER,x.__webglFramebuffer[0]);else n.bindFramebuffer(e.FRAMEBUFFER,x.__webglFramebuffer);if(x.__webglDepthbuffer===void 0)x.__webglDepthbuffer=e.createRenderbuffer(),ke(x.__webglDepthbuffer,M,!1);else{let te=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ie=x.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,ie),e.framebufferRenderbuffer(e.FRAMEBUFFER,te,e.RENDERBUFFER,ie)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function Je(M,x,I){let W=i.get(M);if(x!==void 0)Oe(W.__webglFramebuffer,M,M.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0);if(I!==void 0)Ye(M)}function Ft(M){let x=M.texture,I=i.get(M),W=i.get(x);M.addEventListener("dispose",_);let te=M.textures,ie=M.isWebGLCubeRenderTarget===!0,le=te.length>1;if(!le){if(W.__webglTexture===void 0)W.__webglTexture=e.createTexture();W.__version=x.version,o.memory.textures++}if(ie){I.__webglFramebuffer=[];for(let X=0;X<6;X++)if(x.mipmaps&&x.mipmaps.length>0){I.__webglFramebuffer[X]=[];for(let j=0;j<x.mipmaps.length;j++)I.__webglFramebuffer[X][j]=e.createFramebuffer()}else I.__webglFramebuffer[X]=e.createFramebuffer()}else{if(x.mipmaps&&x.mipmaps.length>0){I.__webglFramebuffer=[];for(let X=0;X<x.mipmaps.length;X++)I.__webglFramebuffer[X]=e.createFramebuffer()}else I.__webglFramebuffer=e.createFramebuffer();if(le)for(let X=0,j=te.length;X<j;X++){let xe=i.get(te[X]);if(xe.__webglTexture===void 0)xe.__webglTexture=e.createTexture(),o.memory.textures++}if(M.samples>0&&L(M)===!1){I.__webglMultisampledFramebuffer=e.createFramebuffer(),I.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,I.__webglMultisampledFramebuffer);for(let X=0;X<te.length;X++){let j=te[X];I.__webglColorRenderbuffer[X]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,I.__webglColorRenderbuffer[X]);let xe=s.convert(j.format,j.colorSpace),we=s.convert(j.type),ue=v(j.internalFormat,xe,we,j.normalized,j.colorSpace,M.isXRRenderTarget===!0),re=Pt(M);e.renderbufferStorageMultisample(e.RENDERBUFFER,re,ue,M.width,M.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+X,e.RENDERBUFFER,I.__webglColorRenderbuffer[X])}if(e.bindRenderbuffer(e.RENDERBUFFER,null),M.depthBuffer)I.__webglDepthRenderbuffer=e.createRenderbuffer(),ke(I.__webglDepthRenderbuffer,M,!0);n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(ie){n.bindTexture(e.TEXTURE_CUBE_MAP,W.__webglTexture),Z(e.TEXTURE_CUBE_MAP,x);for(let X=0;X<6;X++)if(x.mipmaps&&x.mipmaps.length>0)for(let j=0;j<x.mipmaps.length;j++)Oe(I.__webglFramebuffer[X][j],M,x,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+X,j);else Oe(I.__webglFramebuffer[X],M,x,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+X,0);if(m(x))A(e.TEXTURE_CUBE_MAP);n.unbindTexture()}else if(le){for(let X=0,j=te.length;X<j;X++){let xe=te[X],we=i.get(xe),ue=e.TEXTURE_2D;if(M.isWebGL3DRenderTarget||M.isWebGLArrayRenderTarget)ue=M.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY;if(n.bindTexture(ue,we.__webglTexture),Z(ue,xe),Oe(I.__webglFramebuffer,M,xe,e.COLOR_ATTACHMENT0+X,ue,0),m(xe))A(ue)}n.unbindTexture()}else{let X=e.TEXTURE_2D;if(M.isWebGL3DRenderTarget||M.isWebGLArrayRenderTarget)X=M.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY;if(n.bindTexture(X,W.__webglTexture),Z(X,x),x.mipmaps&&x.mipmaps.length>0)for(let j=0;j<x.mipmaps.length;j++)Oe(I.__webglFramebuffer[j],M,x,e.COLOR_ATTACHMENT0,X,j);else Oe(I.__webglFramebuffer,M,x,e.COLOR_ATTACHMENT0,X,0);if(m(x))A(X);n.unbindTexture()}if(M.depthBuffer)Ye(M)}function gn(M){let x=M.textures;for(let I=0,W=x.length;I<W;I++){let te=x[I];if(m(te)){let ie=T(M),le=i.get(te).__webglTexture;n.bindTexture(ie,le),A(ie),n.unbindTexture()}}}let mt=[],Ht=[];function zt(M){if(M.samples>0){if(L(M)===!1){let{textures:x,width:I,height:W}=M,te=e.COLOR_BUFFER_BIT,ie=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,le=i.get(M),X=x.length>1;if(X)for(let xe=0;xe<x.length;xe++)n.bindFramebuffer(e.FRAMEBUFFER,le.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+xe,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,le.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+xe,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,le.__webglMultisampledFramebuffer);let j=M.texture.mipmaps;if(j&&j.length>0)n.bindFramebuffer(e.DRAW_FRAMEBUFFER,le.__webglFramebuffer[0]);else n.bindFramebuffer(e.DRAW_FRAMEBUFFER,le.__webglFramebuffer);for(let xe=0;xe<x.length;xe++){if(M.resolveDepthBuffer){if(M.depthBuffer)te|=e.DEPTH_BUFFER_BIT;if(M.stencilBuffer&&M.resolveStencilBuffer)te|=e.STENCIL_BUFFER_BIT}if(X){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,le.__webglColorRenderbuffer[xe]);let we=i.get(x[xe]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,we,0)}if(e.blitFramebuffer(0,0,I,W,0,0,I,W,te,e.NEAREST),c===!0){if(mt.length=0,Ht.length=0,mt.push(e.COLOR_ATTACHMENT0+xe),M.depthBuffer&&M.resolveDepthBuffer===!1)mt.push(ie),Ht.push(ie),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,Ht);e.invalidateFramebuffer(e.READ_FRAMEBUFFER,mt)}}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),X)for(let xe=0;xe<x.length;xe++){n.bindFramebuffer(e.FRAMEBUFFER,le.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+xe,e.RENDERBUFFER,le.__webglColorRenderbuffer[xe]);let we=i.get(x[xe]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,le.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+xe,e.TEXTURE_2D,we,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,le.__webglMultisampledFramebuffer)}else if(M.depthBuffer&&M.resolveDepthBuffer===!1&&c){let x=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[x])}}}function Pt(M){return Math.min(r.maxSamples,M.samples)}function L(M){let x=i.get(M);return M.samples>0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&x.__useRenderToTexture!==!1}function _n(M){let x=o.render.frame;if(u.get(M)!==x)u.set(M,x),M.update()}function nt(M,x){let{colorSpace:I,format:W,type:te}=M;if(M.isCompressedTexture===!0||M.isVideoTexture===!0)return x;if(I!==hn&&I!==mr)if(We.getTransfer(I)===ht){if(W!==Jn||te!==Fn)Me("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}else Ne("WebGLTextures: Unsupported texture color space:",I);return x}function gt(M){if(typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement)l.width=M.naturalWidth||M.width,l.height=M.naturalHeight||M.height;else if(typeof VideoFrame<"u"&&M instanceof VideoFrame)l.width=M.displayWidth,l.height=M.displayHeight;else l.width=M.width,l.height=M.height;return l}this.allocateTextureUnit=V,this.resetTextureUnits=J,this.getTextureUnits=O,this.setTextureUnits=H,this.setTexture2D=K,this.setTexture2DArray=Q,this.setTexture3D=se,this.setTextureCube=me,this.rebindTextures=Je,this.setupRenderTarget=Ft,this.updateRenderTargetMipmap=gn,this.updateMultisampleRenderTarget=zt,this.setupDepthRenderbuffer=Ye,this.setupFrameBufferTexture=Oe,this.useMultisampledRTT=L,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function IT(e,t){function n(i,r=mr){let s,o=We.getTransfer(r);if(i===Fn)return e.UNSIGNED_BYTE;if(i===Ul)return e.UNSIGNED_SHORT_4_4_4_4;if(i===Ol)return e.UNSIGNED_SHORT_5_5_5_1;if(i===Qg)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===e_)return e.UNSIGNED_INT_10F_11F_11F_REV;if(i===Jg)return e.BYTE;if(i===Kg)return e.SHORT;if(i===Vs)return e.UNSIGNED_SHORT;if(i===Dl)return e.INT;if(i===Oi)return e.UNSIGNED_INT;if(i===di)return e.FLOAT;if(i===pi)return e.HALF_FLOAT;if(i===t_)return e.ALPHA;if(i===n_)return e.RGB;if(i===Jn)return e.RGBA;if(i===fr)return e.DEPTH_COMPONENT;if(i===dr)return e.DEPTH_STENCIL;if(i===i_)return e.RED;if(i===Fl)return e.RED_INTEGER;if(i===pr)return e.RG;if(i===zl)return e.RG_INTEGER;if(i===kl)return e.RGBA_INTEGER;if(i===ya||i===ba||i===Sa||i===Ma)if(o===ht)if(s=t.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===ya)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===ba)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Sa)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Ma)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=t.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===ya)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===ba)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Sa)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Ma)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Bl||i===Gl||i===Hl||i===Vl)if(s=t.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===Bl)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Gl)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Hl)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Vl)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Wl||i===$l||i===Zl||i===Xl||i===ql||i===wa||i===Yl)if(s=t.get("WEBGL_compressed_texture_etc"),s!==null){if(i===Wl||i===$l)return o===ht?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===Zl)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===Xl)return s.COMPRESSED_R11_EAC;if(i===ql)return s.COMPRESSED_SIGNED_R11_EAC;if(i===wa)return s.COMPRESSED_RG11_EAC;if(i===Yl)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===jl||i===Jl||i===Kl||i===Ql||i===eu||i===tu||i===nu||i===iu||i===ru||i===su||i===ou||i===au||i===cu||i===lu)if(s=t.get("WEBGL_compressed_texture_astc"),s!==null){if(i===jl)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Jl)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Kl)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Ql)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===eu)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===tu)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===nu)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===iu)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===ru)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===su)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===ou)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===au)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===cu)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===lu)return o===ht?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===uu||i===hu||i===fu)if(s=t.get("EXT_texture_compression_bptc"),s!==null){if(i===uu)return o===ht?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===hu)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===fu)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===du||i===pu||i===Ta||i===mu)if(s=t.get("EXT_texture_compression_rgtc"),s!==null){if(i===du)return s.COMPRESSED_RED_RGTC1_EXT;if(i===pu)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===Ta)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===mu)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;if(i===Kr)return e.UNSIGNED_INT_24_8;return e[i]!==void 0?e[i]:null}return{convert:n}}var PT=`void main() {gl_Position = vec4( position, 1.0 );-}`,qz=`+}`,LT=`uniform sampler2DArray depthColor;uniform float depthWidth;uniform float depthHeight;@@ -4174,4 +4173,4 @@ void main() {}-}`;class R5{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init($,U){if(this.texture===null){let J=new V7($.texture);if($.depthNear!==U.depthNear||$.depthFar!==U.depthFar)this.depthNear=$.depthNear,this.depthFar=$.depthFar;this.texture=J}}getMesh($){if(this.texture!==null){if(this.mesh===null){let U=$.cameras[0].viewport,J=new yU({vertexShader:Iz,fragmentShader:qz,uniforms:{depthColor:{value:this.texture},depthWidth:{value:U.z},depthHeight:{value:U.w}}});this.mesh=new P6(new CQ(20,20),J)}}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class V5 extends sU{constructor($,U){super();let J=this,Q=null,W=1,K=null,X="local-floor",N=1,H=null,Y=null,G=null,O=null,E=null,Z=null,D=typeof XRWebGLBinding<"u",R=new R5,I={},q=U.getContextAttributes(),_=null,P=null,L=[],B=[],z=new g$,A=null,k=new f6;k.viewport=new Z6;let w=new f6;w.viewport=new Z6;let h=[k,w],C=new mE,f=null,s=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(i){let X$=L[i];if(X$===void 0)X$=new VQ,L[i]=X$;return X$.getTargetRaySpace()},this.getControllerGrip=function(i){let X$=L[i];if(X$===void 0)X$=new VQ,L[i]=X$;return X$.getGripSpace()},this.getHand=function(i){let X$=L[i];if(X$===void 0)X$=new VQ,L[i]=X$;return X$.getHandSpace()};function y(i){let X$=B.indexOf(i.inputSource);if(X$===-1)return;let k$=L[X$];if(k$!==void 0)k$.update(i.inputSource,i.frame,H||K),k$.dispatchEvent({type:i.type,data:i.inputSource})}function d(){Q.removeEventListener("select",y),Q.removeEventListener("selectstart",y),Q.removeEventListener("selectend",y),Q.removeEventListener("squeeze",y),Q.removeEventListener("squeezestart",y),Q.removeEventListener("squeezeend",y),Q.removeEventListener("end",d),Q.removeEventListener("inputsourceschange",c);for(let i=0;i<L.length;i++){let X$=B[i];if(X$===null)continue;B[i]=null,L[i].disconnect(X$)}f=null,s=null,R.reset();for(let i in I)delete I[i];$.setRenderTarget(_),E=null,O=null,G=null,Q=null,P=null,i$.stop(),J.isPresenting=!1,$.setPixelRatio(A),$.setSize(z.width,z.height,!1),J.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(i){if(W=i,J.isPresenting===!0)A$("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(i){if(X=i,J.isPresenting===!0)A$("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return H||K},this.setReferenceSpace=function(i){H=i},this.getBaseLayer=function(){return O!==null?O:E},this.getBinding=function(){if(G===null&&D)G=new XRWebGLBinding(Q,U);return G},this.getFrame=function(){return Z},this.getSession=function(){return Q},this.setSession=async function(i){if(Q=i,Q!==null){if(_=$.getRenderTarget(),Q.addEventListener("select",y),Q.addEventListener("selectstart",y),Q.addEventListener("selectend",y),Q.addEventListener("squeeze",y),Q.addEventListener("squeezestart",y),Q.addEventListener("squeezeend",y),Q.addEventListener("end",d),Q.addEventListener("inputsourceschange",c),q.xrCompatible!==!0)await U.makeXRCompatible();if(A=$.getPixelRatio(),$.getSize(z),!(D&&("createProjectionLayer"in XRWebGLBinding.prototype))){let k$={antialias:q.antialias,alpha:!0,depth:q.depth,stencil:q.stencil,framebufferScaleFactor:W};E=new XRWebGLLayer(Q,U,k$),Q.updateRenderState({baseLayer:E}),$.setPixelRatio(1),$.setSize(E.framebufferWidth,E.framebufferHeight,!1),P=new xU(E.framebufferWidth,E.framebufferHeight,{format:IJ,type:aU,colorSpace:$.outputColorSpace,stencilBuffer:q.stencil,resolveDepthBuffer:E.ignoreDepthValues===!1,resolveStencilBuffer:E.ignoreDepthValues===!1})}else{let k$=null,F$=null,v$=null;if(q.depth)v$=q.stencil?U.DEPTH24_STENCIL8:U.DEPTH_COMPONENT24,k$=q.stencil?l0:u0,F$=q.stencil?U8:X0;let e$={colorFormat:U.RGBA8,depthFormat:v$,scaleFactor:W};G=this.getBinding(),O=G.createProjectionLayer(e$),Q.updateRenderState({layers:[O]}),$.setPixelRatio(1),$.setSize(O.textureWidth,O.textureHeight,!1),P=new xU(O.textureWidth,O.textureHeight,{format:IJ,type:aU,depthTexture:new G0(O.textureWidth,O.textureHeight,F$,void 0,void 0,void 0,void 0,void 0,void 0,k$),stencilBuffer:q.stencil,colorSpace:$.outputColorSpace,samples:q.antialias?4:0,resolveDepthBuffer:O.ignoreDepthValues===!1,resolveStencilBuffer:O.ignoreDepthValues===!1})}P.isXRRenderTarget=!0,this.setFoveation(N),H=null,K=await Q.requestReferenceSpace(X),i$.setContext(Q),i$.start(),J.isPresenting=!0,J.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(Q!==null)return Q.environmentBlendMode},this.getDepthTexture=function(){return R.getDepthTexture()};function c(i){for(let X$=0;X$<i.removed.length;X$++){let k$=i.removed[X$],F$=B.indexOf(k$);if(F$>=0)B[F$]=null,L[F$].disconnect(k$)}for(let X$=0;X$<i.added.length;X$++){let k$=i.added[X$],F$=B.indexOf(k$);if(F$===-1){for(let e$=0;e$<L.length;e$++)if(e$>=B.length){B.push(k$),F$=e$;break}else if(B[e$]===null){B[e$]=k$,F$=e$;break}if(F$===-1)break}let v$=L[F$];if(v$)v$.connect(k$)}}let x=new j,t=new j;function e(i,X$,k$){x.setFromMatrixPosition(X$.matrixWorld),t.setFromMatrixPosition(k$.matrixWorld);let F$=x.distanceTo(t),v$=X$.projectionMatrix.elements,e$=k$.projectionMatrix.elements,l$=v$[14]/(v$[10]-1),d$=v$[14]/(v$[10]+1),X6=(v$[9]+1)/v$[5],J6=(v$[9]-1)/v$[5],K6=(v$[8]-1)/v$[0],d6=(e$[8]+1)/e$[0],CU=l$*K6,z6=l$*d6,r6=F$/(-K6+d6),c6=r6*-K6;if(X$.matrixWorld.decompose(i.position,i.quaternion,i.scale),i.translateX(c6),i.translateZ(r6),i.matrixWorld.compose(i.position,i.quaternion,i.scale),i.matrixWorldInverse.copy(i.matrixWorld).invert(),v$[10]===-1)i.projectionMatrix.copy(X$.projectionMatrix),i.projectionMatrixInverse.copy(X$.projectionMatrixInverse);else{let h6=l$+r6,v=d$+r6,SU=CU-c6,G6=z6+(F$-c6),_6=X6*d$/v*h6,M=J6*d$/v*h6;i.projectionMatrix.makePerspective(SU,G6,_6,M,h6,v),i.projectionMatrixInverse.copy(i.projectionMatrix).invert()}}function Y$(i,X$){if(X$===null)i.matrixWorld.copy(i.matrix);else i.matrixWorld.multiplyMatrices(X$.matrixWorld,i.matrix);i.matrixWorldInverse.copy(i.matrixWorld).invert()}this.updateCamera=function(i){if(Q===null)return;let{near:X$,far:k$}=i;if(R.texture!==null){if(R.depthNear>0)X$=R.depthNear;if(R.depthFar>0)k$=R.depthFar}if(C.near=w.near=k.near=X$,C.far=w.far=k.far=k$,f!==C.near||s!==C.far)Q.updateRenderState({depthNear:C.near,depthFar:C.far}),f=C.near,s=C.far;C.layers.mask=i.layers.mask|6,k.layers.mask=C.layers.mask&-5,w.layers.mask=C.layers.mask&-3;let F$=i.parent,v$=C.cameras;Y$(C,F$);for(let e$=0;e$<v$.length;e$++)Y$(v$[e$],F$);if(v$.length===2)e(C,k,w);else C.projectionMatrix.copy(k.projectionMatrix);R$(i,C,F$)};function R$(i,X$,k$){if(k$===null)i.matrix.copy(X$.matrixWorld);else i.matrix.copy(k$.matrixWorld),i.matrix.invert(),i.matrix.multiply(X$.matrixWorld);if(i.matrix.decompose(i.position,i.quaternion,i.scale),i.updateMatrixWorld(!0),i.projectionMatrix.copy(X$.projectionMatrix),i.projectionMatrixInverse.copy(X$.projectionMatrixInverse),i.isPerspectiveCamera)i.fov=x0*2*Math.atan(1/i.projectionMatrix.elements[5]),i.zoom=1}this.getCamera=function(){return C},this.getFoveation=function(){if(O===null&&E===null)return;return N},this.setFoveation=function(i){if(N=i,O!==null)O.fixedFoveation=i;if(E!==null&&E.fixedFoveation!==void 0)E.fixedFoveation=i},this.hasDepthSensing=function(){return R.texture!==null},this.getDepthSensingMesh=function(){return R.getMesh(C)},this.getCameraTexture=function(i){return I[i]};let w$=null;function U6(i,X$){if(Y=X$.getViewerPose(H||K),Z=X$,Y!==null){let k$=Y.views;if(E!==null)$.setRenderTargetFramebuffer(P,E.framebuffer),$.setRenderTarget(P);let F$=!1;if(k$.length!==C.cameras.length)C.cameras.length=0,F$=!0;for(let d$=0;d$<k$.length;d$++){let X6=k$[d$],J6=null;if(E!==null)J6=E.getViewport(X6);else{let d6=G.getViewSubImage(O,X6);if(J6=d6.viewport,d$===0)$.setRenderTargetTextures(P,d6.colorTexture,d6.depthStencilTexture),$.setRenderTarget(P)}let K6=h[d$];if(K6===void 0)K6=new f6,K6.layers.enable(d$),K6.viewport=new Z6,h[d$]=K6;if(K6.matrix.fromArray(X6.transform.matrix),K6.matrix.decompose(K6.position,K6.quaternion,K6.scale),K6.projectionMatrix.fromArray(X6.projectionMatrix),K6.projectionMatrixInverse.copy(K6.projectionMatrix).invert(),K6.viewport.set(J6.x,J6.y,J6.width,J6.height),d$===0)C.matrix.copy(K6.matrix),C.matrix.decompose(C.position,C.quaternion,C.scale);if(F$===!0)C.cameras.push(K6)}let v$=Q.enabledFeatures;if(v$&&v$.includes("depth-sensing")&&Q.depthUsage=="gpu-optimized"&&D){G=J.getBinding();let d$=G.getDepthInformation(k$[0]);if(d$&&d$.isValid&&d$.texture)R.init(d$,Q.renderState)}if(v$&&v$.includes("camera-access")&&D){$.state.unbindTexture(),G=J.getBinding();for(let d$=0;d$<k$.length;d$++){let X6=k$[d$].camera;if(X6){let J6=I[X6];if(!J6)J6=new V7,I[X6]=J6;let K6=G.getCameraImage(X6);J6.sourceTexture=K6}}}}for(let k$=0;k$<L.length;k$++){let F$=B[k$],v$=L[k$];if(F$!==null&&v$!==void 0)v$.update(F$,X$,H||K)}if(w$)w$(i,X$);if(X$.detectedPlanes)J.dispatchEvent({type:"planesdetected",data:X$});Z=null}let i$=new Y5;i$.setAnimationLoop(U6),this.setAnimationLoop=function(i){w$=i},this.dispose=function(){}}}var Dz=new p$,w5=new u$;w5.set(-1,0,0,0,1,0,0,0,1);function kz($,U){function J(I,q){if(I.matrixAutoUpdate===!0)I.updateMatrix();q.value.copy(I.matrix)}function Q(I,q){if(q.color.getRGB(I.fogColor.value,vE($)),q.isFog)I.fogNear.value=q.near,I.fogFar.value=q.far;else if(q.isFogExp2)I.fogDensity.value=q.density}function W(I,q,_,P,L){if(q.isNodeMaterial)q.uniformsNeedUpdate=!1;else if(q.isMeshBasicMaterial)K(I,q);else if(q.isMeshLambertMaterial){if(K(I,q),q.envMap)I.envMapIntensity.value=q.envMapIntensity}else if(q.isMeshToonMaterial)K(I,q),O(I,q);else if(q.isMeshPhongMaterial){if(K(I,q),G(I,q),q.envMap)I.envMapIntensity.value=q.envMapIntensity}else if(q.isMeshStandardMaterial){if(K(I,q),E(I,q),q.isMeshPhysicalMaterial)Z(I,q,L)}else if(q.isMeshMatcapMaterial)K(I,q),D(I,q);else if(q.isMeshDepthMaterial)K(I,q);else if(q.isMeshDistanceMaterial)K(I,q),R(I,q);else if(q.isMeshNormalMaterial)K(I,q);else if(q.isLineBasicMaterial){if(X(I,q),q.isLineDashedMaterial)N(I,q)}else if(q.isPointsMaterial)H(I,q,_,P);else if(q.isSpriteMaterial)Y(I,q);else if(q.isShadowMaterial)I.color.value.copy(q.color),I.opacity.value=q.opacity;else if(q.isShaderMaterial)q.uniformsNeedUpdate=!1}function K(I,q){if(I.opacity.value=q.opacity,q.color)I.diffuse.value.copy(q.color);if(q.emissive)I.emissive.value.copy(q.emissive).multiplyScalar(q.emissiveIntensity);if(q.map)I.map.value=q.map,J(q.map,I.mapTransform);if(q.alphaMap)I.alphaMap.value=q.alphaMap,J(q.alphaMap,I.alphaMapTransform);if(q.bumpMap){if(I.bumpMap.value=q.bumpMap,J(q.bumpMap,I.bumpMapTransform),I.bumpScale.value=q.bumpScale,q.side===JU)I.bumpScale.value*=-1}if(q.normalMap){if(I.normalMap.value=q.normalMap,J(q.normalMap,I.normalMapTransform),I.normalScale.value.copy(q.normalScale),q.side===JU)I.normalScale.value.negate()}if(q.displacementMap)I.displacementMap.value=q.displacementMap,J(q.displacementMap,I.displacementMapTransform),I.displacementScale.value=q.displacementScale,I.displacementBias.value=q.displacementBias;if(q.emissiveMap)I.emissiveMap.value=q.emissiveMap,J(q.emissiveMap,I.emissiveMapTransform);if(q.specularMap)I.specularMap.value=q.specularMap,J(q.specularMap,I.specularMapTransform);if(q.alphaTest>0)I.alphaTest.value=q.alphaTest;let _=U.get(q),P=_.envMap,L=_.envMapRotation;if(P){if(I.envMap.value=P,I.envMapRotation.value.setFromMatrix4(Dz.makeRotationFromEuler(L)).transpose(),P.isCubeTexture&&P.isRenderTargetTexture===!1)I.envMapRotation.value.premultiply(w5);I.reflectivity.value=q.reflectivity,I.ior.value=q.ior,I.refractionRatio.value=q.refractionRatio}if(q.lightMap)I.lightMap.value=q.lightMap,I.lightMapIntensity.value=q.lightMapIntensity,J(q.lightMap,I.lightMapTransform);if(q.aoMap)I.aoMap.value=q.aoMap,I.aoMapIntensity.value=q.aoMapIntensity,J(q.aoMap,I.aoMapTransform)}function X(I,q){if(I.diffuse.value.copy(q.color),I.opacity.value=q.opacity,q.map)I.map.value=q.map,J(q.map,I.mapTransform)}function N(I,q){I.dashSize.value=q.dashSize,I.totalSize.value=q.dashSize+q.gapSize,I.scale.value=q.scale}function H(I,q,_,P){if(I.diffuse.value.copy(q.color),I.opacity.value=q.opacity,I.size.value=q.size*_,I.scale.value=P*0.5,q.map)I.map.value=q.map,J(q.map,I.uvTransform);if(q.alphaMap)I.alphaMap.value=q.alphaMap,J(q.alphaMap,I.alphaMapTransform);if(q.alphaTest>0)I.alphaTest.value=q.alphaTest}function Y(I,q){if(I.diffuse.value.copy(q.color),I.opacity.value=q.opacity,I.rotation.value=q.rotation,q.map)I.map.value=q.map,J(q.map,I.mapTransform);if(q.alphaMap)I.alphaMap.value=q.alphaMap,J(q.alphaMap,I.alphaMapTransform);if(q.alphaTest>0)I.alphaTest.value=q.alphaTest}function G(I,q){I.specular.value.copy(q.specular),I.shininess.value=Math.max(q.shininess,0.0001)}function O(I,q){if(q.gradientMap)I.gradientMap.value=q.gradientMap}function E(I,q){if(I.metalness.value=q.metalness,q.metalnessMap)I.metalnessMap.value=q.metalnessMap,J(q.metalnessMap,I.metalnessMapTransform);if(I.roughness.value=q.roughness,q.roughnessMap)I.roughnessMap.value=q.roughnessMap,J(q.roughnessMap,I.roughnessMapTransform);if(q.envMap)I.envMapIntensity.value=q.envMapIntensity}function Z(I,q,_){if(I.ior.value=q.ior,q.sheen>0){if(I.sheenColor.value.copy(q.sheenColor).multiplyScalar(q.sheen),I.sheenRoughness.value=q.sheenRoughness,q.sheenColorMap)I.sheenColorMap.value=q.sheenColorMap,J(q.sheenColorMap,I.sheenColorMapTransform);if(q.sheenRoughnessMap)I.sheenRoughnessMap.value=q.sheenRoughnessMap,J(q.sheenRoughnessMap,I.sheenRoughnessMapTransform)}if(q.clearcoat>0){if(I.clearcoat.value=q.clearcoat,I.clearcoatRoughness.value=q.clearcoatRoughness,q.clearcoatMap)I.clearcoatMap.value=q.clearcoatMap,J(q.clearcoatMap,I.clearcoatMapTransform);if(q.clearcoatRoughnessMap)I.clearcoatRoughnessMap.value=q.clearcoatRoughnessMap,J(q.clearcoatRoughnessMap,I.clearcoatRoughnessMapTransform);if(q.clearcoatNormalMap){if(I.clearcoatNormalMap.value=q.clearcoatNormalMap,J(q.clearcoatNormalMap,I.clearcoatNormalMapTransform),I.clearcoatNormalScale.value.copy(q.clearcoatNormalScale),q.side===JU)I.clearcoatNormalScale.value.negate()}}if(q.dispersion>0)I.dispersion.value=q.dispersion;if(q.iridescence>0){if(I.iridescence.value=q.iridescence,I.iridescenceIOR.value=q.iridescenceIOR,I.iridescenceThicknessMinimum.value=q.iridescenceThicknessRange[0],I.iridescenceThicknessMaximum.value=q.iridescenceThicknessRange[1],q.iridescenceMap)I.iridescenceMap.value=q.iridescenceMap,J(q.iridescenceMap,I.iridescenceMapTransform);if(q.iridescenceThicknessMap)I.iridescenceThicknessMap.value=q.iridescenceThicknessMap,J(q.iridescenceThicknessMap,I.iridescenceThicknessMapTransform)}if(q.transmission>0){if(I.transmission.value=q.transmission,I.transmissionSamplerMap.value=_.texture,I.transmissionSamplerSize.value.set(_.width,_.height),q.transmissionMap)I.transmissionMap.value=q.transmissionMap,J(q.transmissionMap,I.transmissionMapTransform);if(I.thickness.value=q.thickness,q.thicknessMap)I.thicknessMap.value=q.thicknessMap,J(q.thicknessMap,I.thicknessMapTransform);I.attenuationDistance.value=q.attenuationDistance,I.attenuationColor.value.copy(q.attenuationColor)}if(q.anisotropy>0){if(I.anisotropyVector.value.set(q.anisotropy*Math.cos(q.anisotropyRotation),q.anisotropy*Math.sin(q.anisotropyRotation)),q.anisotropyMap)I.anisotropyMap.value=q.anisotropyMap,J(q.anisotropyMap,I.anisotropyMapTransform)}if(I.specularIntensity.value=q.specularIntensity,I.specularColor.value.copy(q.specularColor),q.specularColorMap)I.specularColorMap.value=q.specularColorMap,J(q.specularColorMap,I.specularColorMapTransform);if(q.specularIntensityMap)I.specularIntensityMap.value=q.specularIntensityMap,J(q.specularIntensityMap,I.specularIntensityMapTransform)}function D(I,q){if(q.matcap)I.matcap.value=q.matcap}function R(I,q){let _=U.get(q).light;I.referencePosition.value.setFromMatrixPosition(_.matrixWorld),I.nearDistance.value=_.shadow.camera.near,I.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:Q,refreshMaterialUniforms:W}}function Fz($,U,J,Q){let W={},K={},X=[],N=$.getParameter($.MAX_UNIFORM_BUFFER_BINDINGS);function H(L,B){let z=B.program;Q.uniformBlockBinding(L,z)}function Y(L,B){let z=W[L.id];if(z===void 0)I(L),z=G(L),W[L.id]=z,L.addEventListener("dispose",_);let A=B.program;Q.updateUBOMapping(L,A);let k=U.render.frame;if(K[L.id]!==k)E(L),K[L.id]=k}function G(L){let B=O();L.__bindingPointIndex=B;let z=$.createBuffer(),A=L.__size,k=L.usage;return $.bindBuffer($.UNIFORM_BUFFER,z),$.bufferData($.UNIFORM_BUFFER,A,k),$.bindBuffer($.UNIFORM_BUFFER,null),$.bindBufferBase($.UNIFORM_BUFFER,B,z),z}function O(){for(let L=0;L<N;L++)if(X.indexOf(L)===-1)return X.push(L),L;return y$("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function E(L){let B=W[L.id],z=L.uniforms,A=L.__cache;$.bindBuffer($.UNIFORM_BUFFER,B);for(let k=0,w=z.length;k<w;k++){let h=z[k];if(Array.isArray(h))for(let C=0,f=h.length;C<f;C++)Z(h[C],k,C,A);else Z(h,k,0,A)}$.bindBuffer($.UNIFORM_BUFFER,null)}function Z(L,B,z,A){if(R(L,B,z,A)===!0){let{__offset:k,value:w}=L;if(Array.isArray(w)){let h=0;for(let C=0;C<w.length;C++){let f=w[C],s=q(f);if(D(f,L.__data,h),typeof f!=="number"&&typeof f!=="boolean"&&!f.isMatrix3&&!ArrayBuffer.isView(f))h+=s.storage/Float32Array.BYTES_PER_ELEMENT}}else D(w,L.__data,0);$.bufferSubData($.UNIFORM_BUFFER,k,L.__data)}}function D(L,B,z){if(typeof L==="number"||typeof L==="boolean")B[0]=L;else if(L.isMatrix3)B[0]=L.elements[0],B[1]=L.elements[1],B[2]=L.elements[2],B[3]=0,B[4]=L.elements[3],B[5]=L.elements[4],B[6]=L.elements[5],B[7]=0,B[8]=L.elements[6],B[9]=L.elements[7],B[10]=L.elements[8],B[11]=0;else if(ArrayBuffer.isView(L))B.set(new L.constructor(L.buffer,L.byteOffset,B.length));else L.toArray(B,z)}function R(L,B,z,A){let k=L.value,w=B+"_"+z;if(A[w]===void 0){if(typeof k==="number"||typeof k==="boolean")A[w]=k;else if(ArrayBuffer.isView(k))A[w]=k.slice();else A[w]=k.clone();return!0}else{let h=A[w];if(typeof k==="number"||typeof k==="boolean"){if(h!==k)return A[w]=k,!0}else if(ArrayBuffer.isView(k))return!0;else if(h.equals(k)===!1)return h.copy(k),!0}return!1}function I(L){let B=L.uniforms,z=0,A=16;for(let w=0,h=B.length;w<h;w++){let C=Array.isArray(B[w])?B[w]:[B[w]];for(let f=0,s=C.length;f<s;f++){let y=C[f],d=Array.isArray(y.value)?y.value:[y.value];for(let c=0,x=d.length;c<x;c++){let t=d[c],e=q(t),Y$=z%A,R$=Y$%e.boundary,w$=Y$+R$;if(z+=R$,w$!==0&&A-w$<e.storage)z+=A-w$;y.__data=new Float32Array(e.storage/Float32Array.BYTES_PER_ELEMENT),y.__offset=z,z+=e.storage}}}let k=z%A;if(k>0)z+=A-k;return L.__size=z,L.__cache={},this}function q(L){let B={boundary:0,storage:0};if(typeof L==="number"||typeof L==="boolean")B.boundary=4,B.storage=4;else if(L.isVector2)B.boundary=8,B.storage=8;else if(L.isVector3||L.isColor)B.boundary=16,B.storage=12;else if(L.isVector4)B.boundary=16,B.storage=16;else if(L.isMatrix3)B.boundary=48,B.storage=48;else if(L.isMatrix4)B.boundary=64,B.storage=64;else if(L.isTexture)A$("WebGLRenderer: Texture samplers can not be part of an uniforms group.");else if(ArrayBuffer.isView(L))B.boundary=16,B.storage=L.byteLength;else A$("WebGLRenderer: Unsupported uniform value type.",L);return B}function _(L){let B=L.target;B.removeEventListener("dispose",_);let z=X.indexOf(B.__bindingPointIndex);X.splice(z,1),$.deleteBuffer(W[B.id]),delete W[B.id],delete K[B.id]}function P(){for(let L in W)$.deleteBuffer(W[L]);X=[],W={},K={}}return{bind:H,update:Y,dispose:P}}var Lz=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]),DJ=null;function Rz(){if(DJ===null)DJ=new BQ(Lz,16,16,m0,gJ),DJ.name="DFG_LUT",DJ.minFilter=o6,DJ.magFilter=o6,DJ.wrapS=eW,DJ.wrapT=eW,DJ.generateMipmaps=!1,DJ.needsUpdate=!0;return DJ}class QZ{constructor($={}){let{canvas:U=Ck(),context:J=null,depth:Q=!0,stencil:W=!1,alpha:K=!1,antialias:X=!1,premultipliedAlpha:N=!0,preserveDrawingBuffer:H=!1,powerPreference:Y="default",failIfMajorPerformanceCaveat:G=!1,reversedDepthBuffer:O=!1,outputBufferType:E=aU}=$;this.isWebGLRenderer=!0;let Z;if(J!==null){if(typeof WebGLRenderingContext<"u"&&J instanceof WebGLRenderingContext)throw Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");Z=J.getContextAttributes().alpha}else Z=K;let D=E,R=new Set([dO,pO,mO]),I=new Set([aU,X0,kQ,U8,uO,lO]),q=new Uint32Array(4),_=new Int32Array(4),P=new j,L=null,B=null,z=[],A=[],k=null;this.domElement=U,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=oU,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let w=this,h=!1,C=null,f=null,s=null,y=null;this._outputColorSpace=N0;let d=0,c=0,x=null,t=-1,e=null,Y$=new Z6,R$=new Z6,w$=null,U6=new x$(0),i$=0,i=U.width,X$=U.height,k$=1,F$=null,v$=null,e$=new Z6(0,0,i,X$),l$=new Z6(0,0,i,X$),d$=!1,X6=new zQ,J6=!1,K6=!1,d6=new p$,CU=new j,z6=new Z6,r6={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},c6=!1;function h6(){return x===null?k$:1}let v=J;function SU(V,b){return U.getContext(V,b)}try{let V={alpha:!0,depth:Q,stencil:W,antialias:X,premultipliedAlpha:N,preserveDrawingBuffer:H,powerPreference:Y,failIfMajorPerformanceCaveat:G};if("setAttribute"in U)U.setAttribute("data-engine",`three.js r${bD}`);if(U.addEventListener("webglcontextlost",m$,!1),U.addEventListener("webglcontextrestored",C6,!1),U.addEventListener("webglcontextcreationerror",M6,!1),v===null){if(v=SU("webgl2",V),v===null)if(SU("webgl2"))throw Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.");else throw Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(V){throw y$("WebGLRenderer: "+V.message),V}let G6,_6,M,F,S,n,J$,N$,Z$,o,a,M$,C$,I$,H$,j$,b$,H6,T,G$,r,O$,B$;function $$(){if(G6=new _B(v),G6.init(),r=new Zz(v,G6),_6=new LB(v,G6,$,r),M=new Oz(v,G6),_6.reversedDepthBuffer&&O)M.buffers.depth.setReversed(!0);f=v.createFramebuffer(),s=v.createFramebuffer(),y=v.createFramebuffer(),F=new SB(v),S=new sP,n=new Ez(v,G6,M,S,_6,r,F),J$=new zB(w),N$=new gV(v),O$=new kB(v,N$),Z$=new AB(v,N$,F,O$),o=new vB(v,Z$,N$,O$,F),H6=new TB(v,_6,n),H$=new RB(S),a=new aP(w,J$,G6,_6,O$,H$),M$=new kz(w,S),C$=new eP,I$=new Kz(G6),b$=new DB(w,J$,M,o,Z,N),j$=new Gz(w,o,_6),B$=new Fz(v,F,_6,M),T=new FB(v,G6,F),G$=new CB(v,G6,F),F.programs=a.programs,w.capabilities=_6,w.extensions=G6,w.properties=S,w.renderLists=C$,w.shadowMap=j$,w.state=M,w.info=F}if($$(),D!==aU)k=new gB(D,U.width,U.height,X,Q,W);let E$=new V5(w,v);this.xr=E$,this.getContext=function(){return v},this.getContextAttributes=function(){return v.getContextAttributes()},this.forceContextLoss=function(){let V=G6.get("WEBGL_lose_context");if(V)V.loseContext()},this.forceContextRestore=function(){let V=G6.get("WEBGL_lose_context");if(V)V.restoreContext()},this.getPixelRatio=function(){return k$},this.setPixelRatio=function(V){if(V===void 0)return;k$=V,this.setSize(i,X$,!1)},this.getSize=function(V){return V.set(i,X$)},this.setSize=function(V,b,p=!0){if(E$.isPresenting){A$("WebGLRenderer: Can't change size while VR device is presenting.");return}if(i=V,X$=b,U.width=Math.floor(V*k$),U.height=Math.floor(b*k$),p===!0)U.style.width=V+"px",U.style.height=b+"px";if(k!==null)k.setSize(U.width,U.height);this.setViewport(0,0,V,b)},this.getDrawingBufferSize=function(V){return V.set(i*k$,X$*k$).floor()},this.setDrawingBufferSize=function(V,b,p){i=V,X$=b,k$=p,U.width=Math.floor(V*p),U.height=Math.floor(b*p),this.setViewport(0,0,V,b)},this.setEffects=function(V){if(D===aU){y$("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(V){for(let b=0;b<V.length;b++)if(V[b].isOutputPass===!0){A$("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}k.setEffects(V||[])},this.getCurrentViewport=function(V){return V.copy(Y$)},this.getViewport=function(V){return V.copy(e$)},this.setViewport=function(V,b,p,u){if(V.isVector4)e$.set(V.x,V.y,V.z,V.w);else e$.set(V,b,p,u);M.viewport(Y$.copy(e$).multiplyScalar(k$).round())},this.getScissor=function(V){return V.copy(l$)},this.setScissor=function(V,b,p,u){if(V.isVector4)l$.set(V.x,V.y,V.z,V.w);else l$.set(V,b,p,u);M.scissor(R$.copy(l$).multiplyScalar(k$).round())},this.getScissorTest=function(){return d$},this.setScissorTest=function(V){M.setScissorTest(d$=V)},this.setOpaqueSort=function(V){F$=V},this.setTransparentSort=function(V){v$=V},this.getClearColor=function(V){return V.copy(b$.getClearColor())},this.setClearColor=function(){b$.setClearColor(...arguments)},this.getClearAlpha=function(){return b$.getClearAlpha()},this.setClearAlpha=function(){b$.setClearAlpha(...arguments)},this.clear=function(V=!0,b=!0,p=!0){let u=0;if(V){let l=!1;if(x!==null){let V$=x.texture.format;l=R.has(V$)}if(l){let V$=x.texture.type,z$=I.has(V$),L$=b$.getClearColor(),_$=b$.getClearAlpha(),S$=L$.r,c$=L$.g,r$=L$.b;if(z$)q[0]=S$,q[1]=c$,q[2]=r$,q[3]=_$,v.clearBufferuiv(v.COLOR,0,q);else _[0]=S$,_[1]=c$,_[2]=r$,_[3]=_$,v.clearBufferiv(v.COLOR,0,_)}else u|=v.COLOR_BUFFER_BIT}if(b)u|=v.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0);if(p)u|=v.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295);if(u!==0)v.clear(u)},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(V){V.setRenderer(this),C=V},this.dispose=function(){U.removeEventListener("webglcontextlost",m$,!1),U.removeEventListener("webglcontextrestored",C6,!1),U.removeEventListener("webglcontextcreationerror",M6,!1),b$.dispose(),C$.dispose(),I$.dispose(),S.dispose(),J$.dispose(),o.dispose(),O$.dispose(),B$.dispose(),a.dispose(),E$.dispose(),E$.removeEventListener("sessionstart",wZ),E$.removeEventListener("sessionend",MZ),R0.stop()};function m$(V){V.preventDefault(),EQ("WebGLRenderer: Context Lost."),h=!0}function C6(){EQ("WebGLRenderer: Context Restored."),h=!1;let V=F.autoReset,b=j$.enabled,p=j$.autoUpdate,u=j$.needsUpdate,l=j$.type;$$(),F.autoReset=V,j$.enabled=b,j$.autoUpdate=p,j$.needsUpdate=u,j$.type=l}function M6(V){y$("WebGLRenderer: A WebGL context could not be created. Reason: ",V.statusMessage)}function tU(V){let b=V.target;b.removeEventListener("dispose",tU),LJ(b)}function LJ(V){OF(V),S.remove(V)}function OF(V){let b=S.get(V).programs;if(b!==void 0){if(b.forEach(function(p){a.releaseProgram(p)}),V.isShaderMaterial)a.releaseShaderCache(V)}}this.renderBufferDirect=function(V,b,p,u,l,V$){if(b===null)b=r6;let z$=l.isMesh&&l.matrixWorld.determinantAffine()<0,L$=IF(V,b,p,u,l);M.setMaterial(u,z$);let _$=p.index,S$=1;if(u.wireframe===!0){if(_$=Z$.getWireframeAttribute(p),_$===void 0)return;S$=2}let c$=p.drawRange,r$=p.attributes.position,T$=c$.start*S$,I6=(c$.start+c$.count)*S$;if(V$!==null)T$=Math.max(T$,V$.start*S$),I6=Math.min(I6,(V$.start+V$.count)*S$);if(_$!==null)T$=Math.max(T$,0),I6=Math.min(I6,_$.count);else if(r$!==void 0&&r$!==null)T$=Math.max(T$,0),I6=Math.min(I6,r$.count);let j6=I6-T$;if(j6<0||j6===1/0)return;O$.setup(l,u,L$,p,_$);let S6,L6=T;if(_$!==null)S6=N$.get(_$),L6=G$,L6.setIndex(S6);if(l.isMesh)if(u.wireframe===!0)M.setLineWidth(u.wireframeLinewidth*h6()),L6.setMode(v.LINES);else L6.setMode(v.TRIANGLES);else if(l.isLine){let t6=u.linewidth;if(t6===void 0)t6=1;if(M.setLineWidth(t6*h6()),l.isLineSegments)L6.setMode(v.LINES);else if(l.isLineLoop)L6.setMode(v.LINE_LOOP);else L6.setMode(v.LINE_STRIP)}else if(l.isPoints)L6.setMode(v.POINTS);else if(l.isSprite)L6.setMode(v.TRIANGLES);if(l.isBatchedMesh)if(!G6.get("WEBGL_multi_draw")){let{_multiDrawStarts:t6,_multiDrawCounts:P$,_multiDrawCount:FU}=l,N6=_$?N$.get(_$).bytesPerElement:1,TU=S.get(u).currentProgram.getUniforms();for(let eU=0;eU<FU;eU++)TU.setValue(v,"_gl_DrawID",eU),L6.render(t6[eU]/N6,P$[eU])}else L6.renderMultiDraw(l._multiDrawStarts,l._multiDrawCounts,l._multiDrawCount);else if(l.isInstancedMesh)L6.renderInstances(T$,j6,l.count);else if(p.isInstancedBufferGeometry){let t6=p._maxInstanceCount!==void 0?p._maxInstanceCount:1/0,P$=Math.min(p.instanceCount,t6);L6.renderInstances(T$,j6,P$)}else L6.render(T$,j6)};function VZ(V,b,p){if(V.transparent===!0&&V.side===bU&&V.forceSinglePass===!1)V.side=JU,V.needsUpdate=!0,cQ(V,b,p),V.side=K0,V.needsUpdate=!0,cQ(V,b,p),V.side=bU;else cQ(V,b,p)}this.compile=function(V,b,p=null){if(p===null)p=V;if(B=I$.get(p),B.init(b),A.push(B),p.traverseVisible(function(l){if(l.isLight&&l.layers.test(b.layers)){if(B.pushLight(l),l.castShadow)B.pushShadow(l)}}),V!==p)V.traverseVisible(function(l){if(l.isLight&&l.layers.test(b.layers)){if(B.pushLight(l),l.castShadow)B.pushShadow(l)}});B.setupLights();let u=new Set;return V.traverse(function(l){if(!(l.isMesh||l.isPoints||l.isLine||l.isSprite))return;let V$=l.material;if(V$)if(Array.isArray(V$))for(let z$=0;z$<V$.length;z$++){let L$=V$[z$];VZ(L$,p,l),u.add(L$)}else VZ(V$,p,l),u.add(V$)}),B=A.pop(),u},this.compileAsync=function(V,b,p=null){let u=this.compile(V,b,p);return new Promise((l)=>{function V$(){if(u.forEach(function(z$){if(S.get(z$).currentProgram.isReady())u.delete(z$)}),u.size===0){l(V);return}setTimeout(V$,10)}if(G6.get("KHR_parallel_shader_compile")!==null)V$();else setTimeout(V$,10)})};let u7=null;function EF(V){if(u7)u7(V)}function wZ(){R0.stop()}function MZ(){R0.start()}let R0=new Y5;if(R0.setAnimationLoop(EF),typeof self<"u")R0.setContext(self);this.setAnimationLoop=function(V){u7=V,E$.setAnimationLoop(V),V===null?R0.stop():R0.start()},E$.addEventListener("sessionstart",wZ),E$.addEventListener("sessionend",MZ),this.render=function(V,b){if(b!==void 0&&b.isCamera!==!0){y$("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(h===!0)return;if(C!==null)C.renderStart(V,b);let p=E$.enabled===!0&&E$.isPresenting===!0,u=k!==null&&(x===null||p)&&k.begin(w,x);if(V.matrixWorldAutoUpdate===!0)V.updateMatrixWorld();if(b.parent===null&&b.matrixWorldAutoUpdate===!0)b.updateMatrixWorld();if(E$.enabled===!0&&E$.isPresenting===!0&&(k===null||k.isCompositing()===!1)){if(E$.cameraAutoUpdate===!0)E$.updateCamera(b);b=E$.getCamera()}if(V.isScene===!0)V.onBeforeRender(w,V,b,x);if(B=I$.get(V,A.length),B.init(b),B.state.textureUnits=n.getTextureUnits(),A.push(B),d6.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse),X6.setFromProjectionMatrix(d6,zE,b.reversedDepth),K6=this.localClippingEnabled,J6=H$.init(this.clippingPlanes,K6),L=C$.get(V,z.length),L.init(),z.push(L),E$.enabled===!0&&E$.isPresenting===!0){let z$=w.xr.getDepthSensingMesh();if(z$!==null)l7(z$,b,-1/0,w.sortObjects)}if(l7(V,b,0,w.sortObjects),L.finish(),w.sortObjects===!0)L.sort(F$,v$,b.reversedDepth);if(c6=E$.enabled===!1||E$.isPresenting===!1||E$.hasDepthSensing()===!1,c6)b$.addToRenderList(L,V);if(this.info.render.frame++,this.info.autoReset===!0)this.info.reset();if(J6===!0)H$.beginShadows();let l=B.state.shadowsArray;if(j$.render(l,V,b),J6===!0)H$.endShadows();if((u&&k.hasRenderPass())===!1){let{opaque:z$,transmissive:L$}=L;if(B.setupLights(),b.isArrayCamera){let _$=b.cameras;if(L$.length>0)for(let S$=0,c$=_$.length;S$<c$;S$++){let r$=_$[S$];PZ(z$,L$,V,r$)}if(c6)b$.render(V);for(let S$=0,c$=_$.length;S$<c$;S$++){let r$=_$[S$];BZ(L,V,r$,r$.viewport)}}else{if(L$.length>0)PZ(z$,L$,V,b);if(c6)b$.render(V);BZ(L,V,b)}}if(x!==null&&c===0)n.updateMultisampleRenderTarget(x),n.updateRenderTargetMipmap(x);if(u)k.end(w);if(V.isScene===!0)V.onAfterRender(w,V,b);if(O$.resetDefaultState(),t=-1,e=null,A.pop(),A.length>0){if(B=A[A.length-1],n.setTextureUnits(B.state.textureUnits),J6===!0)H$.setGlobalState(w.clippingPlanes,B.state.camera)}else B=null;if(z.pop(),z.length>0)L=z[z.length-1];else L=null;if(C!==null)C.renderEnd()};function l7(V,b,p,u){if(V.visible===!1)return;if(V.layers.test(b.layers)){if(V.isGroup)p=V.renderOrder;else if(V.isLOD){if(V.autoUpdate===!0)V.update(b)}else if(V.isLightProbeGrid)B.pushLightProbeGrid(V);else if(V.isLight){if(B.pushLight(V),V.castShadow)B.pushShadow(V)}else if(V.isSprite){if(!V.frustumCulled||X6.intersectsSprite(V)){if(u)z6.setFromMatrixPosition(V.matrixWorld).applyMatrix4(d6);let z$=o.update(V),L$=V.material;if(L$.visible)L.push(V,z$,L$,p,z6.z,null)}}else if(V.isMesh||V.isLine||V.isPoints){if(!V.frustumCulled||X6.intersectsObject(V)){let z$=o.update(V),L$=V.material;if(u){if(V.boundingSphere!==void 0){if(V.boundingSphere===null)V.computeBoundingSphere();z6.copy(V.boundingSphere.center)}else{if(z$.boundingSphere===null)z$.computeBoundingSphere();z6.copy(z$.boundingSphere.center)}z6.applyMatrix4(V.matrixWorld).applyMatrix4(d6)}if(Array.isArray(L$)){let _$=z$.groups;for(let S$=0,c$=_$.length;S$<c$;S$++){let r$=_$[S$],T$=L$[r$.materialIndex];if(T$&&T$.visible)L.push(V,z$,T$,p,z6.z,r$)}}else if(L$.visible)L.push(V,z$,L$,p,z6.z,null)}}}let V$=V.children;for(let z$=0,L$=V$.length;z$<L$;z$++)l7(V$[z$],b,p,u)}function BZ(V,b,p,u){let{opaque:l,transmissive:V$,transparent:z$}=V;if(B.setupLightsView(p),J6===!0)H$.setGlobalState(w.clippingPlanes,p);if(u)M.viewport(Y$.copy(u));if(l.length>0)dQ(l,b,p);if(V$.length>0)dQ(V$,b,p);if(z$.length>0)dQ(z$,b,p);M.buffers.depth.setTest(!0),M.buffers.depth.setMask(!0),M.buffers.color.setMask(!0),M.setPolygonOffset(!1)}function PZ(V,b,p,u){if((p.isScene===!0?p.overrideMaterial:null)!==null)return;if(B.state.transmissionRenderTarget[u.id]===void 0){let T$=G6.has("EXT_color_buffer_half_float")||G6.has("EXT_color_buffer_float");B.state.transmissionRenderTarget[u.id]=new xU(1,1,{generateMipmaps:!0,type:T$?gJ:aU,minFilter:ZJ,samples:Math.max(4,_6.samples),stencilBuffer:W,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:s$.workingColorSpace})}let V$=B.state.transmissionRenderTarget[u.id],z$=u.viewport||Y$;V$.setSize(z$.z*w.transmissionResolutionScale,z$.w*w.transmissionResolutionScale);let L$=w.getRenderTarget(),_$=w.getActiveCubeFace(),S$=w.getActiveMipmapLevel();if(w.setRenderTarget(V$),w.getClearColor(U6),i$=w.getClearAlpha(),i$<1)w.setClearColor(16777215,0.5);if(w.clear(),c6)b$.render(p);let c$=w.toneMapping;w.toneMapping=oU;let r$=u.viewport;if(u.viewport!==void 0)u.viewport=void 0;if(B.setupLightsView(u),J6===!0)H$.setGlobalState(w.clippingPlanes,u);if(dQ(V,p,u),n.updateMultisampleRenderTarget(V$),n.updateRenderTargetMipmap(V$),G6.has("WEBGL_multisampled_render_to_texture")===!1){let T$=!1;for(let I6=0,j6=b.length;I6<j6;I6++){let S6=b[I6],{object:L6,geometry:t6,material:P$,group:FU}=S6;if(P$.side===bU&&L6.layers.test(u.layers)){let N6=P$.side;P$.side=JU,P$.needsUpdate=!0,zZ(L6,p,u,t6,P$,FU),P$.side=N6,P$.needsUpdate=!0,T$=!0}}if(T$===!0)n.updateMultisampleRenderTarget(V$),n.updateRenderTargetMipmap(V$)}if(w.setRenderTarget(L$,_$,S$),w.setClearColor(U6,i$),r$!==void 0)u.viewport=r$;w.toneMapping=c$}function dQ(V,b,p){let u=b.isScene===!0?b.overrideMaterial:null;for(let l=0,V$=V.length;l<V$;l++){let z$=V[l],{object:L$,geometry:_$,group:S$}=z$,c$=z$.material;if(c$.allowOverride===!0&&u!==null)c$=u;if(L$.layers.test(p.layers))zZ(L$,b,p,_$,c$,S$)}}function zZ(V,b,p,u,l,V$){if(V.onBeforeRender(w,b,p,u,l,V$),V.modelViewMatrix.multiplyMatrices(p.matrixWorldInverse,V.matrixWorld),V.normalMatrix.getNormalMatrix(V.modelViewMatrix),l.onBeforeRender(w,b,p,u,V,V$),l.transparent===!0&&l.side===bU&&l.forceSinglePass===!1)l.side=JU,l.needsUpdate=!0,w.renderBufferDirect(p,b,u,l,V,V$),l.side=K0,l.needsUpdate=!0,w.renderBufferDirect(p,b,u,l,V,V$),l.side=bU;else w.renderBufferDirect(p,b,u,l,V,V$);V.onAfterRender(w,b,p,u,l,V$)}function cQ(V,b,p){if(b.isScene!==!0)b=r6;let u=S.get(V),l=B.state.lights,V$=B.state.shadowsArray,z$=l.state.version,L$=a.getParameters(V,l.state,V$,b,p,B.state.lightProbeGridArray),_$=a.getProgramCacheKey(L$),S$=u.programs;u.environment=V.isMeshStandardMaterial||V.isMeshLambertMaterial||V.isMeshPhongMaterial?b.environment:null,u.fog=b.fog;let c$=V.isMeshStandardMaterial||V.isMeshLambertMaterial&&!V.envMap||V.isMeshPhongMaterial&&!V.envMap;if(u.envMap=J$.get(V.envMap||u.environment,c$),u.envMapRotation=u.environment!==null&&V.envMap===null?b.environmentRotation:V.envMapRotation,S$===void 0)V.addEventListener("dispose",tU),S$=new Map,u.programs=S$;let r$=S$.get(_$);if(r$!==void 0){if(u.currentProgram===r$&&u.lightsStateVersion===z$)return AZ(V,L$),r$}else{if(L$.uniforms=a.getUniforms(V),C!==null&&V.isNodeMaterial)C.build(V,p,L$);V.onBeforeCompile(L$,w),r$=a.acquireProgram(L$,_$),S$.set(_$,r$),u.uniforms=L$.uniforms}let T$=u.uniforms;if(!V.isShaderMaterial&&!V.isRawShaderMaterial||V.clipping===!0)T$.clippingPlanes=H$.uniform;if(AZ(V,L$),u.needsLights=DF(V),u.lightsStateVersion=z$,u.needsLights)T$.ambientLightColor.value=l.state.ambient,T$.lightProbe.value=l.state.probe,T$.directionalLights.value=l.state.directional,T$.directionalLightShadows.value=l.state.directionalShadow,T$.spotLights.value=l.state.spot,T$.spotLightShadows.value=l.state.spotShadow,T$.rectAreaLights.value=l.state.rectArea,T$.ltc_1.value=l.state.rectAreaLTC1,T$.ltc_2.value=l.state.rectAreaLTC2,T$.pointLights.value=l.state.point,T$.pointLightShadows.value=l.state.pointShadow,T$.hemisphereLights.value=l.state.hemi,T$.directionalShadowMatrix.value=l.state.directionalShadowMatrix,T$.spotLightMatrix.value=l.state.spotLightMatrix,T$.spotLightMap.value=l.state.spotLightMap,T$.pointShadowMatrix.value=l.state.pointShadowMatrix;return u.lightProbeGrid=B.state.lightProbeGridArray.length>0,u.currentProgram=r$,u.uniformsList=null,r$}function _Z(V){if(V.uniformsList===null){let b=V.currentProgram.getUniforms();V.uniformsList=xQ.seqWithValue(b.seq,V.uniforms)}return V.uniformsList}function AZ(V,b){let p=S.get(V);p.outputColorSpace=b.outputColorSpace,p.batching=b.batching,p.batchingColor=b.batchingColor,p.instancing=b.instancing,p.instancingColor=b.instancingColor,p.instancingMorph=b.instancingMorph,p.skinning=b.skinning,p.morphTargets=b.morphTargets,p.morphNormals=b.morphNormals,p.morphColors=b.morphColors,p.morphTargetsCount=b.morphTargetsCount,p.numClippingPlanes=b.numClippingPlanes,p.numIntersection=b.numClipIntersection,p.vertexAlphas=b.vertexAlphas,p.vertexTangents=b.vertexTangents,p.toneMapping=b.toneMapping}function ZF(V,b){if(V.length===0)return null;if(V.length===1)return V[0].texture!==null?V[0]:null;P.setFromMatrixPosition(b.matrixWorld);for(let p=0,u=V.length;p<u;p++){let l=V[p];if(l.texture!==null&&l.boundingBox.containsPoint(P))return l}return null}function IF(V,b,p,u,l){if(b.isScene!==!0)b=r6;n.resetTextureUnits();let V$=b.fog,z$=u.isMeshStandardMaterial||u.isMeshLambertMaterial||u.isMeshPhongMaterial?b.environment:null,L$=x===null?w.outputColorSpace:x.isXRRenderTarget===!0?x.texture.colorSpace:s$.workingColorSpace,_$=u.isMeshStandardMaterial||u.isMeshLambertMaterial&&!u.envMap||u.isMeshPhongMaterial&&!u.envMap,S$=J$.get(u.envMap||z$,_$),c$=u.vertexColors===!0&&!!p.attributes.color&&p.attributes.color.itemSize===4,r$=!!p.attributes.tangent&&(!!u.normalMap||u.anisotropy>0),T$=!!p.morphAttributes.position,I6=!!p.morphAttributes.normal,j6=!!p.morphAttributes.color,S6=oU;if(u.toneMapped){if(x===null||x.isXRRenderTarget===!0)S6=w.toneMapping}let L6=p.morphAttributes.position||p.morphAttributes.normal||p.morphAttributes.color,t6=L6!==void 0?L6.length:0,P$=S.get(u),FU=B.state.lights;if(J6===!0){if(K6===!0||V!==e){let B6=V===e&&u.id===t;H$.setState(u,V,B6)}}let N6=!1;if(u.version===P$.__version){if(P$.needsLights&&P$.lightsStateVersion!==FU.state.version)N6=!0;else if(P$.outputColorSpace!==L$)N6=!0;else if(l.isBatchedMesh&&P$.batching===!1)N6=!0;else if(!l.isBatchedMesh&&P$.batching===!0)N6=!0;else if(l.isBatchedMesh&&P$.batchingColor===!0&&l.colorTexture===null)N6=!0;else if(l.isBatchedMesh&&P$.batchingColor===!1&&l.colorTexture!==null)N6=!0;else if(l.isInstancedMesh&&P$.instancing===!1)N6=!0;else if(!l.isInstancedMesh&&P$.instancing===!0)N6=!0;else if(l.isSkinnedMesh&&P$.skinning===!1)N6=!0;else if(!l.isSkinnedMesh&&P$.skinning===!0)N6=!0;else if(l.isInstancedMesh&&P$.instancingColor===!0&&l.instanceColor===null)N6=!0;else if(l.isInstancedMesh&&P$.instancingColor===!1&&l.instanceColor!==null)N6=!0;else if(l.isInstancedMesh&&P$.instancingMorph===!0&&l.morphTexture===null)N6=!0;else if(l.isInstancedMesh&&P$.instancingMorph===!1&&l.morphTexture!==null)N6=!0;else if(P$.envMap!==S$)N6=!0;else if(u.fog===!0&&P$.fog!==V$)N6=!0;else if(P$.numClippingPlanes!==void 0&&(P$.numClippingPlanes!==H$.numPlanes||P$.numIntersection!==H$.numIntersection))N6=!0;else if(P$.vertexAlphas!==c$)N6=!0;else if(P$.vertexTangents!==r$)N6=!0;else if(P$.morphTargets!==T$)N6=!0;else if(P$.morphNormals!==I6)N6=!0;else if(P$.morphColors!==j6)N6=!0;else if(P$.toneMapping!==S6)N6=!0;else if(P$.morphTargetsCount!==t6)N6=!0;else if(!!P$.lightProbeGrid!==B.state.lightProbeGridArray.length>0)N6=!0}else N6=!0,P$.__version=u.version;let TU=P$.currentProgram;if(N6===!0){if(TU=cQ(u,b,l),C&&u.isNodeMaterial)C.onUpdateProgram(u,TU,P$)}let eU=!1,hJ=!1,t0=!1,R6=TU.getUniforms(),g6=P$.uniforms;if(M.useProgram(TU.program))eU=!0,hJ=!0,t0=!0;if(u.id!==t)t=u.id,hJ=!0;if(P$.needsLights){let B6=ZF(B.state.lightProbeGridArray,l);if(P$.lightProbeGrid!==B6)P$.lightProbeGrid=B6,hJ=!0}if(eU||e!==V){if(M.buffers.depth.getReversed()&&V.reversedDepth!==!0)V._reversedDepth=!0,V.updateProjectionMatrix();R6.setValue(v,"projectionMatrix",V.projectionMatrix),R6.setValue(v,"viewMatrix",V.matrixWorldInverse);let uJ=R6.map.cameraPosition;if(uJ!==void 0)uJ.setValue(v,CU.setFromMatrixPosition(V.matrixWorld));if(_6.logarithmicDepthBuffer)R6.setValue(v,"logDepthBufFC",2/(Math.log(V.far+1)/Math.LN2));if(u.isMeshPhongMaterial||u.isMeshToonMaterial||u.isMeshLambertMaterial||u.isMeshBasicMaterial||u.isMeshStandardMaterial||u.isShaderMaterial)R6.setValue(v,"isOrthographic",V.isOrthographicCamera===!0);if(e!==V)e=V,hJ=!0,t0=!0}if(P$.needsLights){if(FU.state.directionalShadowMap.length>0)R6.setValue(v,"directionalShadowMap",FU.state.directionalShadowMap,n);if(FU.state.spotShadowMap.length>0)R6.setValue(v,"spotShadowMap",FU.state.spotShadowMap,n);if(FU.state.pointShadowMap.length>0)R6.setValue(v,"pointShadowMap",FU.state.pointShadowMap,n)}if(l.isSkinnedMesh){R6.setOptional(v,l,"bindMatrix"),R6.setOptional(v,l,"bindMatrixInverse");let B6=l.skeleton;if(B6){if(B6.boneTexture===null)B6.computeBoneTexture();R6.setValue(v,"boneTexture",B6.boneTexture,n)}}if(l.isBatchedMesh){if(R6.setOptional(v,l,"batchingTexture"),R6.setValue(v,"batchingTexture",l._matricesTexture,n),R6.setOptional(v,l,"batchingIdTexture"),R6.setValue(v,"batchingIdTexture",l._indirectTexture,n),R6.setOptional(v,l,"batchingColorTexture"),l._colorsTexture!==null)R6.setValue(v,"batchingColorTexture",l._colorsTexture,n)}let fJ=p.morphAttributes;if(fJ.position!==void 0||fJ.normal!==void 0||fJ.color!==void 0)H6.update(l,p,TU);if(hJ||P$.receiveShadow!==l.receiveShadow)P$.receiveShadow=l.receiveShadow,R6.setValue(v,"receiveShadow",l.receiveShadow);if((u.isMeshStandardMaterial||u.isMeshLambertMaterial||u.isMeshPhongMaterial)&&u.envMap===null&&b.environment!==null)g6.envMapIntensity.value=b.environmentIntensity;if(g6.dfgLUT!==void 0)g6.dfgLUT.value=Rz();if(hJ){if(R6.setValue(v,"toneMappingExposure",w.toneMappingExposure),P$.needsLights)qF(g6,t0);if(V$&&u.fog===!0)M$.refreshFogUniforms(g6,V$);if(M$.refreshMaterialUniforms(g6,u,k$,X$,B.state.transmissionRenderTarget[V.id]),P$.needsLights&&P$.lightProbeGrid){let B6=P$.lightProbeGrid;g6.probesSH.value=B6.texture,g6.probesMin.value.copy(B6.boundingBox.min),g6.probesMax.value.copy(B6.boundingBox.max),g6.probesResolution.value.copy(B6.resolution)}xQ.upload(v,_Z(P$),g6,n)}if(u.isShaderMaterial&&u.uniformsNeedUpdate===!0)xQ.upload(v,_Z(P$),g6,n),u.uniformsNeedUpdate=!1;if(u.isSpriteMaterial)R6.setValue(v,"center",l.center);if(R6.setValue(v,"modelViewMatrix",l.modelViewMatrix),R6.setValue(v,"normalMatrix",l.normalMatrix),R6.setValue(v,"modelMatrix",l.matrixWorld),u.uniformsGroups!==void 0){let B6=u.uniformsGroups;for(let uJ=0,e0=B6.length;uJ<e0;uJ++){let CZ=B6[uJ];B$.update(CZ,TU),B$.bind(CZ,TU)}}return TU}function qF(V,b){V.ambientLightColor.needsUpdate=b,V.lightProbe.needsUpdate=b,V.directionalLights.needsUpdate=b,V.directionalLightShadows.needsUpdate=b,V.pointLights.needsUpdate=b,V.pointLightShadows.needsUpdate=b,V.spotLights.needsUpdate=b,V.spotLightShadows.needsUpdate=b,V.rectAreaLights.needsUpdate=b,V.hemisphereLights.needsUpdate=b}function DF(V){return V.isMeshLambertMaterial||V.isMeshToonMaterial||V.isMeshPhongMaterial||V.isMeshStandardMaterial||V.isShadowMaterial||V.isShaderMaterial&&V.lights===!0}if(this.getActiveCubeFace=function(){return d},this.getActiveMipmapLevel=function(){return c},this.getRenderTarget=function(){return x},this.setRenderTargetTextures=function(V,b,p){let u=S.get(V);if(u.__autoAllocateDepthBuffer=V.resolveDepthBuffer===!1,u.__autoAllocateDepthBuffer===!1)u.__useRenderToTexture=!1;S.get(V.texture).__webglTexture=b,S.get(V.depthTexture).__webglTexture=u.__autoAllocateDepthBuffer?void 0:p,u.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(V,b){let p=S.get(V);p.__webglFramebuffer=b,p.__useDefaultFramebuffer=b===void 0},this.setRenderTarget=function(V,b=0,p=0){x=V,d=b,c=p;let u=null,l=!1,V$=!1;if(V){let L$=S.get(V);if(L$.__useDefaultFramebuffer!==void 0){M.bindFramebuffer(v.FRAMEBUFFER,L$.__webglFramebuffer),Y$.copy(V.viewport),R$.copy(V.scissor),w$=V.scissorTest,M.viewport(Y$),M.scissor(R$),M.setScissorTest(w$),t=-1;return}else if(L$.__webglFramebuffer===void 0)n.setupRenderTarget(V);else if(L$.__hasExternalTextures)n.rebindTextures(V,S.get(V.texture).__webglTexture,S.get(V.depthTexture).__webglTexture);else if(V.depthBuffer){let c$=V.depthTexture;if(L$.__boundDepthTexture!==c$){if(c$!==null&&S.has(c$)&&(V.width!==c$.image.width||V.height!==c$.image.height))throw Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");n.setupDepthRenderbuffer(V)}}let _$=V.texture;if(_$.isData3DTexture||_$.isDataArrayTexture||_$.isCompressedArrayTexture)V$=!0;let S$=S.get(V).__webglFramebuffer;if(V.isWebGLCubeRenderTarget){if(Array.isArray(S$[b]))u=S$[b][p];else u=S$[b];l=!0}else if(V.samples>0&&n.useMultisampledRTT(V)===!1)u=S.get(V).__webglMultisampledFramebuffer;else if(Array.isArray(S$))u=S$[p];else u=S$;Y$.copy(V.viewport),R$.copy(V.scissor),w$=V.scissorTest}else Y$.copy(e$).multiplyScalar(k$).floor(),R$.copy(l$).multiplyScalar(k$).floor(),w$=d$;if(p!==0)u=f;if(M.bindFramebuffer(v.FRAMEBUFFER,u))M.drawBuffers(V,u);if(M.viewport(Y$),M.scissor(R$),M.setScissorTest(w$),l){let L$=S.get(V.texture);v.framebufferTexture2D(v.FRAMEBUFFER,v.COLOR_ATTACHMENT0,v.TEXTURE_CUBE_MAP_POSITIVE_X+b,L$.__webglTexture,p)}else if(V$){let L$=b;for(let _$=0;_$<V.textures.length;_$++){let S$=S.get(V.textures[_$]);v.framebufferTextureLayer(v.FRAMEBUFFER,v.COLOR_ATTACHMENT0+_$,S$.__webglTexture,p,L$)}}else if(V!==null&&p!==0){let L$=S.get(V.texture);v.framebufferTexture2D(v.FRAMEBUFFER,v.COLOR_ATTACHMENT0,v.TEXTURE_2D,L$.__webglTexture,p)}t=-1},this.readRenderTargetPixels=function(V,b,p,u,l,V$,z$,L$=0){if(!(V&&V.isWebGLRenderTarget)){y$("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let _$=S.get(V).__webglFramebuffer;if(V.isWebGLCubeRenderTarget&&z$!==void 0)_$=_$[z$];if(_$){M.bindFramebuffer(v.FRAMEBUFFER,_$);try{let S$=V.textures[L$],c$=S$.format,r$=S$.type;if(V.textures.length>1)v.readBuffer(v.COLOR_ATTACHMENT0+L$);if(!_6.textureFormatReadable(c$)){y$("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!_6.textureTypeReadable(r$)){y$("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(b>=0&&b<=V.width-u&&(p>=0&&p<=V.height-l))v.readPixels(b,p,u,l,r.convert(c$),r.convert(r$),V$)}finally{let S$=x!==null?S.get(x).__webglFramebuffer:null;M.bindFramebuffer(v.FRAMEBUFFER,S$)}}},this.readRenderTargetPixelsAsync=async function(V,b,p,u,l,V$,z$,L$=0){if(!(V&&V.isWebGLRenderTarget))throw Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let _$=S.get(V).__webglFramebuffer;if(V.isWebGLCubeRenderTarget&&z$!==void 0)_$=_$[z$];if(_$)if(b>=0&&b<=V.width-u&&(p>=0&&p<=V.height-l)){M.bindFramebuffer(v.FRAMEBUFFER,_$);let S$=V.textures[L$],c$=S$.format,r$=S$.type;if(V.textures.length>1)v.readBuffer(v.COLOR_ATTACHMENT0+L$);if(!_6.textureFormatReadable(c$))throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!_6.textureTypeReadable(r$))throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let T$=v.createBuffer();v.bindBuffer(v.PIXEL_PACK_BUFFER,T$),v.bufferData(v.PIXEL_PACK_BUFFER,V$.byteLength,v.STREAM_READ),v.readPixels(b,p,u,l,r.convert(c$),r.convert(r$),0);let I6=x!==null?S.get(x).__webglFramebuffer:null;M.bindFramebuffer(v.FRAMEBUFFER,I6);let j6=v.fenceSync(v.SYNC_GPU_COMMANDS_COMPLETE,0);return v.flush(),await Tk(v,j6,4),v.bindBuffer(v.PIXEL_PACK_BUFFER,T$),v.getBufferSubData(v.PIXEL_PACK_BUFFER,0,V$),v.deleteBuffer(T$),v.deleteSync(j6),V$}else throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(V,b=null,p=0){let u=Math.pow(2,-p),l=Math.floor(V.image.width*u),V$=Math.floor(V.image.height*u),z$=b!==null?b.x:0,L$=b!==null?b.y:0;n.setTexture2D(V,0),v.copyTexSubImage2D(v.TEXTURE_2D,p,0,0,z$,L$,l,V$),M.unbindTexture()},this.copyTextureToTexture=function(V,b,p=null,u=null,l=0,V$=0){let z$,L$,_$,S$,c$,r$,T$,I6,j6,S6=V.isCompressedTexture?V.mipmaps[V$]:V.image;if(p!==null)z$=p.max.x-p.min.x,L$=p.max.y-p.min.y,_$=p.isBox3?p.max.z-p.min.z:1,S$=p.min.x,c$=p.min.y,r$=p.isBox3?p.min.z:0;else{let g6=Math.pow(2,-l);if(z$=Math.floor(S6.width*g6),L$=Math.floor(S6.height*g6),V.isDataArrayTexture)_$=S6.depth;else if(V.isData3DTexture)_$=Math.floor(S6.depth*g6);else _$=1;S$=0,c$=0,r$=0}if(u!==null)T$=u.x,I6=u.y,j6=u.z;else T$=0,I6=0,j6=0;let L6=r.convert(b.format),t6=r.convert(b.type),P$;if(b.isData3DTexture)n.setTexture3D(b,0),P$=v.TEXTURE_3D;else if(b.isDataArrayTexture||b.isCompressedArrayTexture)n.setTexture2DArray(b,0),P$=v.TEXTURE_2D_ARRAY;else n.setTexture2D(b,0),P$=v.TEXTURE_2D;M.activeTexture(v.TEXTURE0),M.pixelStorei(v.UNPACK_FLIP_Y_WEBGL,b.flipY),M.pixelStorei(v.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),M.pixelStorei(v.UNPACK_ALIGNMENT,b.unpackAlignment);let FU=M.getParameter(v.UNPACK_ROW_LENGTH),N6=M.getParameter(v.UNPACK_IMAGE_HEIGHT),TU=M.getParameter(v.UNPACK_SKIP_PIXELS),eU=M.getParameter(v.UNPACK_SKIP_ROWS),hJ=M.getParameter(v.UNPACK_SKIP_IMAGES);M.pixelStorei(v.UNPACK_ROW_LENGTH,S6.width),M.pixelStorei(v.UNPACK_IMAGE_HEIGHT,S6.height),M.pixelStorei(v.UNPACK_SKIP_PIXELS,S$),M.pixelStorei(v.UNPACK_SKIP_ROWS,c$),M.pixelStorei(v.UNPACK_SKIP_IMAGES,r$);let t0=V.isDataArrayTexture||V.isData3DTexture,R6=b.isDataArrayTexture||b.isData3DTexture;if(V.isDepthTexture){let g6=S.get(V),fJ=S.get(b),B6=S.get(g6.__renderTarget),uJ=S.get(fJ.__renderTarget);M.bindFramebuffer(v.READ_FRAMEBUFFER,B6.__webglFramebuffer),M.bindFramebuffer(v.DRAW_FRAMEBUFFER,uJ.__webglFramebuffer);for(let e0=0;e0<_$;e0++){if(t0)v.framebufferTextureLayer(v.READ_FRAMEBUFFER,v.COLOR_ATTACHMENT0,S.get(V).__webglTexture,l,r$+e0),v.framebufferTextureLayer(v.DRAW_FRAMEBUFFER,v.COLOR_ATTACHMENT0,S.get(b).__webglTexture,V$,j6+e0);v.blitFramebuffer(S$,c$,z$,L$,T$,I6,z$,L$,v.DEPTH_BUFFER_BIT,v.NEAREST)}M.bindFramebuffer(v.READ_FRAMEBUFFER,null),M.bindFramebuffer(v.DRAW_FRAMEBUFFER,null)}else if(l!==0||V.isRenderTargetTexture||S.has(V)){let g6=S.get(V),fJ=S.get(b);M.bindFramebuffer(v.READ_FRAMEBUFFER,s),M.bindFramebuffer(v.DRAW_FRAMEBUFFER,y);for(let B6=0;B6<_$;B6++){if(t0)v.framebufferTextureLayer(v.READ_FRAMEBUFFER,v.COLOR_ATTACHMENT0,g6.__webglTexture,l,r$+B6);else v.framebufferTexture2D(v.READ_FRAMEBUFFER,v.COLOR_ATTACHMENT0,v.TEXTURE_2D,g6.__webglTexture,l);if(R6)v.framebufferTextureLayer(v.DRAW_FRAMEBUFFER,v.COLOR_ATTACHMENT0,fJ.__webglTexture,V$,j6+B6);else v.framebufferTexture2D(v.DRAW_FRAMEBUFFER,v.COLOR_ATTACHMENT0,v.TEXTURE_2D,fJ.__webglTexture,V$);if(l!==0)v.blitFramebuffer(S$,c$,z$,L$,T$,I6,z$,L$,v.COLOR_BUFFER_BIT,v.NEAREST);else if(R6)v.copyTexSubImage3D(P$,V$,T$,I6,j6+B6,S$,c$,z$,L$);else v.copyTexSubImage2D(P$,V$,T$,I6,S$,c$,z$,L$)}M.bindFramebuffer(v.READ_FRAMEBUFFER,null),M.bindFramebuffer(v.DRAW_FRAMEBUFFER,null)}else if(R6)if(V.isDataTexture||V.isData3DTexture)v.texSubImage3D(P$,V$,T$,I6,j6,z$,L$,_$,L6,t6,S6.data);else if(b.isCompressedArrayTexture)v.compressedTexSubImage3D(P$,V$,T$,I6,j6,z$,L$,_$,L6,S6.data);else v.texSubImage3D(P$,V$,T$,I6,j6,z$,L$,_$,L6,t6,S6);else if(V.isDataTexture)v.texSubImage2D(v.TEXTURE_2D,V$,T$,I6,z$,L$,L6,t6,S6.data);else if(V.isCompressedTexture)v.compressedTexSubImage2D(v.TEXTURE_2D,V$,T$,I6,S6.width,S6.height,L6,S6.data);else v.texSubImage2D(v.TEXTURE_2D,V$,T$,I6,z$,L$,L6,t6,S6);if(M.pixelStorei(v.UNPACK_ROW_LENGTH,FU),M.pixelStorei(v.UNPACK_IMAGE_HEIGHT,N6),M.pixelStorei(v.UNPACK_SKIP_PIXELS,TU),M.pixelStorei(v.UNPACK_SKIP_ROWS,eU),M.pixelStorei(v.UNPACK_SKIP_IMAGES,hJ),V$===0&&b.generateMipmaps)v.generateMipmap(P$);M.unbindTexture()},this.initRenderTarget=function(V){if(S.get(V).__webglFramebuffer===void 0)n.setupRenderTarget(V)},this.initTexture=function(V){if(V.isCubeTexture)n.setTextureCube(V,0);else if(V.isData3DTexture)n.setTexture3D(V,0);else if(V.isDataArrayTexture||V.isCompressedArrayTexture)n.setTexture2DArray(V,0);else n.setTexture2D(V,0);M.unbindTexture()},this.resetState=function(){d=0,c=0,x=null,M.reset(),O$.reset()},typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return zE}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace($){this._outputColorSpace=$;let U=this.getContext();U.drawingBufferColorSpace=s$._getDrawingBufferColorSpace($),U.unpackColorSpace=s$._getUnpackColorSpace()}}function KZ($,U){if(U===wE)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),$;if(U===J8||U===FQ){let J=$.getIndex();if(J===null){let X=[],N=$.getAttribute("position");if(N!==void 0){for(let H=0;H<N.count;H++)X.push(H);$.setIndex(X),J=$.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),$}let Q=J.count-2,W=[];if(U===J8)for(let X=1;X<=Q;X++)W.push(J.getX(0)),W.push(J.getX(X)),W.push(J.getX(X+1));else for(let X=0;X<Q;X++)if(X%2===0)W.push(J.getX(X)),W.push(J.getX(X+1)),W.push(J.getX(X+2));else W.push(J.getX(X+2)),W.push(J.getX(X+1)),W.push(J.getX(X));if(W.length/3!==Q)console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let K=$.clone();return K.setIndex(W),K.clearGroups(),K}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",U),$}function M5($){let U=new Map,J=new Map,Q=$.clone();return B5($,Q,function(W,K){U.set(K,W),J.set(W,K)}),Q.traverse(function(W){if(!W.isSkinnedMesh)return;let K=W,X=U.get(W),N=X.skeleton.bones;K.skeleton=X.skeleton.clone(),K.bindMatrix.copy(X.bindMatrix),K.skeleton.bones=N.map(function(H){return J.get(H)}),K.bind(K.skeleton,K.bindMatrix)}),Q}function B5($,U,J){J($,U);for(let Q=0;Q<$.children.length;Q++)B5($.children[Q],U.children[Q],J)}class EZ extends yJ{constructor($){super($);this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(U){return new v5(U)}),this.register(function(U){return new j5(U)}),this.register(function(U){return new m5(U)}),this.register(function(U){return new p5(U)}),this.register(function(U){return new d5(U)}),this.register(function(U){return new b5(U)}),this.register(function(U){return new x5(U)}),this.register(function(U){return new y5(U)}),this.register(function(U){return new h5(U)}),this.register(function(U){return new T5(U)}),this.register(function(U){return new f5(U)}),this.register(function(U){return new g5(U)}),this.register(function(U){return new l5(U)}),this.register(function(U){return new u5(U)}),this.register(function(U){return new C5(U)}),this.register(function(U){return new YZ(U,$6.EXT_MESHOPT_COMPRESSION)}),this.register(function(U){return new YZ(U,$6.KHR_MESHOPT_COMPRESSION)}),this.register(function(U){return new c5(U)})}load($,U,J,Q){let W=this,K;if(this.resourcePath!=="")K=this.resourcePath;else if(this.path!==""){let H=D0.extractUrlBase($);K=D0.resolveURL(H,this.path)}else K=D0.extractUrlBase($);this.manager.itemStart($);let X=function(H){if(Q)Q(H);else console.error(H);W.manager.itemError($),W.manager.itemEnd($)},N=new TQ(this.manager);N.setPath(this.path),N.setResponseType("arraybuffer"),N.setRequestHeader(this.requestHeader),N.setWithCredentials(this.withCredentials),N.load($,function(H){try{W.parse(H,K,function(Y){U(Y),W.manager.itemEnd($)},X)}catch(Y){X(Y)}},J,X)}setDRACOLoader($){return this.dracoLoader=$,this}setKTX2Loader($){return this.ktx2Loader=$,this}setMeshoptDecoder($){return this.meshoptDecoder=$,this}register($){if(this.pluginCallbacks.indexOf($)===-1)this.pluginCallbacks.push($);return this}unregister($){if(this.pluginCallbacks.indexOf($)!==-1)this.pluginCallbacks.splice(this.pluginCallbacks.indexOf($),1);return this}parse($,U,J,Q){let W,K={},X={},N=new TextDecoder;if(typeof $==="string")W=JSON.parse($);else if($ instanceof ArrayBuffer)if(N.decode(new Uint8Array($,0,4))===n5){try{K[$6.KHR_BINARY_GLTF]=new i5($)}catch(G){if(Q)Q(G);return}W=JSON.parse(K[$6.KHR_BINARY_GLTF].content)}else W=JSON.parse(N.decode($));else W=$;if(W.asset===void 0||W.asset.version[0]<2){if(Q)Q(Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let H=new t5(W,{path:U||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});H.fileLoader.setRequestHeader(this.requestHeader);for(let Y=0;Y<this.pluginCallbacks.length;Y++){let G=this.pluginCallbacks[Y](H);if(!G.name)console.error("THREE.GLTFLoader: Invalid plugin found: missing name");X[G.name]=G,K[G.name]=!0}if(W.extensionsUsed)for(let Y=0;Y<W.extensionsUsed.length;++Y){let G=W.extensionsUsed[Y],O=W.extensionsRequired||[];switch(G){case $6.KHR_MATERIALS_UNLIT:K[G]=new S5;break;case $6.KHR_DRACO_MESH_COMPRESSION:K[G]=new o5(W,this.dracoLoader);break;case $6.KHR_TEXTURE_TRANSFORM:K[G]=new r5;break;case $6.KHR_MESH_QUANTIZATION:K[G]=new a5;break;default:if(O.indexOf(G)>=0&&X[G]===void 0)console.warn('THREE.GLTFLoader: Unknown extension "'+G+'".')}}H.setExtensions(K),H.setPlugins(X),H.parse(J,Q)}parseAsync($,U){let J=this;return new Promise(function(Q,W){J.parse($,U,Q,W)})}}function wz(){let $={};return{get:function(U){return $[U]},add:function(U,J){$[U]=J},remove:function(U){delete $[U]},removeAll:function(){$={}}}}function b6($,U,J){let Q=$.json.materials[U];if(Q.extensions&&Q.extensions[J])return Q.extensions[J];return null}var $6={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"};class C5{constructor($){this.parser=$,this.name=$6.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let $=this.parser,U=this.parser.json.nodes||[];for(let J=0,Q=U.length;J<Q;J++){let W=U[J];if(W.extensions&&W.extensions[this.name]&&W.extensions[this.name].light!==void 0)$._addNodeRef(this.cache,W.extensions[this.name].light)}}_loadLight($){let U=this.parser,J="light:"+$,Q=U.cache.get(J);if(Q)return Q;let W=U.json,N=((W.extensions&&W.extensions[this.name]||{}).lights||[])[$],H,Y=new x$(16777215);if(N.color!==void 0)Y.setRGB(N.color[0],N.color[1],N.color[2],BU);let G=N.range!==void 0?N.range:0;switch(N.type){case"directional":H=new Y8(Y),H.target.position.set(0,0,-1),H.add(H.target);break;case"point":H=new H8(Y),H.distance=G;break;case"spot":H=new C7(Y),H.distance=G,N.spot=N.spot||{},N.spot.innerConeAngle=N.spot.innerConeAngle!==void 0?N.spot.innerConeAngle:0,N.spot.outerConeAngle=N.spot.outerConeAngle!==void 0?N.spot.outerConeAngle:Math.PI/4,H.angle=N.spot.outerConeAngle,H.penumbra=1-N.spot.innerConeAngle/N.spot.outerConeAngle,H.target.position.set(0,0,-1),H.add(H.target);break;default:throw Error("THREE.GLTFLoader: Unexpected light type: "+N.type)}if(H.position.set(0,0,0),FJ(H,N),N.intensity!==void 0)H.intensity=N.intensity;return H.name=U.createUniqueName(N.name||"light_"+$),Q=Promise.resolve(H),U.cache.add(J,Q),Q}getDependency($,U){if($!=="light")return;return this._loadLight(U)}createNodeAttachment($){let U=this,J=this.parser,W=J.json.nodes[$],X=(W.extensions&&W.extensions[this.name]||{}).light;if(X===void 0)return null;return this._loadLight(X).then(function(N){return J._getNodeRef(U.cache,X,N)})}}class S5{constructor(){this.name=$6.KHR_MATERIALS_UNLIT}getMaterialType(){return qJ}extendParams($,U,J){let Q=[];$.color=new x$(1,1,1),$.opacity=1;let W=U.pbrMetallicRoughness;if(W){if(Array.isArray(W.baseColorFactor)){let K=W.baseColorFactor;$.color.setRGB(K[0],K[1],K[2],BU),$.opacity=K[3]}if(W.baseColorTexture!==void 0)Q.push(J.assignTexture($,"map",W.baseColorTexture,N0))}return Promise.all(Q)}}class T5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();if(J.emissiveStrength!==void 0)U.emissiveIntensity=J.emissiveStrength;return Promise.resolve()}}class v5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_CLEARCOAT}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(J.clearcoatFactor!==void 0)U.clearcoat=J.clearcoatFactor;if(J.clearcoatTexture!==void 0)Q.push(this.parser.assignTexture(U,"clearcoatMap",J.clearcoatTexture));if(J.clearcoatRoughnessFactor!==void 0)U.clearcoatRoughness=J.clearcoatRoughnessFactor;if(J.clearcoatRoughnessTexture!==void 0)Q.push(this.parser.assignTexture(U,"clearcoatRoughnessMap",J.clearcoatRoughnessTexture));if(J.clearcoatNormalTexture!==void 0){if(Q.push(this.parser.assignTexture(U,"clearcoatNormalMap",J.clearcoatNormalTexture)),J.clearcoatNormalTexture.scale!==void 0){let W=J.clearcoatNormalTexture.scale;U.clearcoatNormalScale=new g$(W,W)}}return Promise.all(Q)}}class j5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_DISPERSION}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();return U.dispersion=J.dispersion!==void 0?J.dispersion:0,Promise.resolve()}}class g5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_IRIDESCENCE}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(J.iridescenceFactor!==void 0)U.iridescence=J.iridescenceFactor;if(J.iridescenceTexture!==void 0)Q.push(this.parser.assignTexture(U,"iridescenceMap",J.iridescenceTexture));if(J.iridescenceIor!==void 0)U.iridescenceIOR=J.iridescenceIor;if(U.iridescenceThicknessRange===void 0)U.iridescenceThicknessRange=[100,400];if(J.iridescenceThicknessMinimum!==void 0)U.iridescenceThicknessRange[0]=J.iridescenceThicknessMinimum;if(J.iridescenceThicknessMaximum!==void 0)U.iridescenceThicknessRange[1]=J.iridescenceThicknessMaximum;if(J.iridescenceThicknessTexture!==void 0)Q.push(this.parser.assignTexture(U,"iridescenceThicknessMap",J.iridescenceThicknessTexture));return Promise.all(Q)}}class b5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_SHEEN}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(U.sheenColor=new x$(0,0,0),U.sheenRoughness=0,U.sheen=1,J.sheenColorFactor!==void 0){let W=J.sheenColorFactor;U.sheenColor.setRGB(W[0],W[1],W[2],BU)}if(J.sheenRoughnessFactor!==void 0)U.sheenRoughness=J.sheenRoughnessFactor;if(J.sheenColorTexture!==void 0)Q.push(this.parser.assignTexture(U,"sheenColorMap",J.sheenColorTexture,N0));if(J.sheenRoughnessTexture!==void 0)Q.push(this.parser.assignTexture(U,"sheenRoughnessMap",J.sheenRoughnessTexture));return Promise.all(Q)}}class x5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_TRANSMISSION}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(J.transmissionFactor!==void 0)U.transmission=J.transmissionFactor;if(J.transmissionTexture!==void 0)Q.push(this.parser.assignTexture(U,"transmissionMap",J.transmissionTexture));return Promise.all(Q)}}class y5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_VOLUME}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(U.thickness=J.thicknessFactor!==void 0?J.thicknessFactor:0,J.thicknessTexture!==void 0)Q.push(this.parser.assignTexture(U,"thicknessMap",J.thicknessTexture));U.attenuationDistance=J.attenuationDistance||1/0;let W=J.attenuationColor||[1,1,1];return U.attenuationColor=new x$().setRGB(W[0],W[1],W[2],BU),Promise.all(Q)}}class h5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_IOR}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();if(U.ior=J.ior!==void 0?J.ior:1.5,U.ior===0)U.ior=1000;return Promise.resolve()}}class f5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_SPECULAR}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(U.specularIntensity=J.specularFactor!==void 0?J.specularFactor:1,J.specularTexture!==void 0)Q.push(this.parser.assignTexture(U,"specularIntensityMap",J.specularTexture));let W=J.specularColorFactor||[1,1,1];if(U.specularColor=new x$().setRGB(W[0],W[1],W[2],BU),J.specularColorTexture!==void 0)Q.push(this.parser.assignTexture(U,"specularColorMap",J.specularColorTexture,N0));return Promise.all(Q)}}class u5{constructor($){this.parser=$,this.name=$6.EXT_MATERIALS_BUMP}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(U.bumpScale=J.bumpFactor!==void 0?J.bumpFactor:1,J.bumpTexture!==void 0)Q.push(this.parser.assignTexture(U,"bumpMap",J.bumpTexture));return Promise.all(Q)}}class l5{constructor($){this.parser=$,this.name=$6.KHR_MATERIALS_ANISOTROPY}getMaterialType($){return b6(this.parser,$,this.name)!==null?zU:null}extendMaterialParams($,U){let J=b6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(J.anisotropyStrength!==void 0)U.anisotropy=J.anisotropyStrength;if(J.anisotropyRotation!==void 0)U.anisotropyRotation=J.anisotropyRotation;if(J.anisotropyTexture!==void 0)Q.push(this.parser.assignTexture(U,"anisotropyMap",J.anisotropyTexture));return Promise.all(Q)}}class m5{constructor($){this.parser=$,this.name=$6.KHR_TEXTURE_BASISU}loadTexture($){let U=this.parser,J=U.json,Q=J.textures[$];if(!Q.extensions||!Q.extensions[this.name])return null;let W=Q.extensions[this.name],K=U.options.ktx2Loader;if(!K)if(J.extensionsRequired&&J.extensionsRequired.indexOf(this.name)>=0)throw Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");else return null;return U.loadTextureImage($,W.source,K)}}class p5{constructor($){this.parser=$,this.name=$6.EXT_TEXTURE_WEBP}loadTexture($){let U=this.name,J=this.parser,Q=J.json,W=Q.textures[$];if(!W.extensions||!W.extensions[U])return null;let K=W.extensions[U],X=Q.images[K.source],N=J.textureLoader;if(X.uri){let H=J.options.manager.getHandler(X.uri);if(H!==null)N=H}return J.loadTextureImage($,K.source,N)}}class d5{constructor($){this.parser=$,this.name=$6.EXT_TEXTURE_AVIF}loadTexture($){let U=this.name,J=this.parser,Q=J.json,W=Q.textures[$];if(!W.extensions||!W.extensions[U])return null;let K=W.extensions[U],X=Q.images[K.source],N=J.textureLoader;if(X.uri){let H=J.options.manager.getHandler(X.uri);if(H!==null)N=H}return J.loadTextureImage($,K.source,N)}}class YZ{constructor($,U){this.name=U,this.parser=$}loadBufferView($){let U=this.parser.json,J=U.bufferViews[$];if(J.extensions&&J.extensions[this.name]){let Q=J.extensions[this.name],W=this.parser.getDependency("buffer",Q.buffer),K=this.parser.options.meshoptDecoder;if(!K||!K.supported)if(U.extensionsRequired&&U.extensionsRequired.indexOf(this.name)>=0)throw Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");else return null;return W.then(function(X){let N=Q.byteOffset||0,H=Q.byteLength||0,Y=Q.count,G=Q.byteStride,O=new Uint8Array(X,N,H);if(K.decodeGltfBufferAsync)return K.decodeGltfBufferAsync(Y,G,O,Q.mode,Q.filter).then(function(E){return E.buffer});else return K.ready.then(function(){let E=new ArrayBuffer(Y*G);return K.decodeGltfBuffer(new Uint8Array(E),Y,G,O,Q.mode,Q.filter),E})})}else return null}}class c5{constructor($){this.name=$6.EXT_MESH_GPU_INSTANCING,this.parser=$}createNodeMesh($){let U=this.parser.json,J=U.nodes[$];if(!J.extensions||!J.extensions[this.name]||J.mesh===void 0)return null;let Q=U.meshes[J.mesh];for(let H of Q.primitives)if(H.mode!==hU.TRIANGLES&&H.mode!==hU.TRIANGLE_STRIP&&H.mode!==hU.TRIANGLE_FAN&&H.mode!==void 0)return null;let K=J.extensions[this.name].attributes,X=[],N={};for(let H in K)X.push(this.parser.getDependency("accessor",K[H]).then((Y)=>{return N[H]=Y,N[H]}));if(X.length<1)return null;return X.push(this.parser.createNodeMesh($)),Promise.all(X).then((H)=>{let Y=H.pop(),G=Y.isGroup?Y.children:[Y],O=H[0].count,E=[];for(let Z of G){let D=new p$,R=new j,I=new i6,q=new j(1,1,1),_=new K8(Z.geometry,Z.material,O);for(let P=0;P<O;P++){if(N.TRANSLATION)R.fromBufferAttribute(N.TRANSLATION,P);if(N.ROTATION)I.fromBufferAttribute(N.ROTATION,P);if(N.SCALE)q.fromBufferAttribute(N.SCALE,P);_.setMatrixAt(P,D.compose(R,I,q))}for(let P in N)if(P==="_COLOR_0"){let L=N[P];_.instanceColor=new y0(L.array,L.itemSize,L.normalized)}else if(P!=="TRANSLATION"&&P!=="ROTATION"&&P!=="SCALE")Z.geometry.setAttribute(P,N[P]);k6.prototype.copy.call(_,Z),this.parser.assignFinalMaterial(_),E.push(_)}if(Y.isGroup)return Y.clear(),Y.add(...E),Y;return E[0]})}}var n5="glTF",hQ=12,P5={JSON:1313821514,BIN:5130562};class i5{constructor($){this.name=$6.KHR_BINARY_GLTF,this.content=null,this.body=null;let U=new DataView($,0,hQ),J=new TextDecoder;if(this.header={magic:J.decode(new Uint8Array($.slice(0,4))),version:U.getUint32(4,!0),length:U.getUint32(8,!0)},this.header.magic!==n5)throw Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");else if(this.header.version<2)throw Error("THREE.GLTFLoader: Legacy binary file detected.");let Q=this.header.length-hQ,W=new DataView($,hQ),K=0;while(K<Q){let X=W.getUint32(K,!0);K+=4;let N=W.getUint32(K,!0);if(K+=4,N===P5.JSON){let H=new Uint8Array($,hQ+K,X);this.content=J.decode(H)}else if(N===P5.BIN){let H=hQ+K;this.body=$.slice(H,H+X)}K+=X}if(this.content===null)throw Error("THREE.GLTFLoader: JSON content not found.")}}class o5{constructor($,U){if(!U)throw Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=$6.KHR_DRACO_MESH_COMPRESSION,this.json=$,this.dracoLoader=U,this.dracoLoader.preload()}decodePrimitive($,U){let J=this.json,Q=this.dracoLoader,W=$.extensions[this.name].bufferView,K=$.extensions[this.name].attributes,X={},N={},H={};for(let Y in K){let G=GZ[Y]||Y.toLowerCase();X[G]=K[Y]}for(let Y in $.attributes){let G=GZ[Y]||Y.toLowerCase();if(K[Y]!==void 0){let O=J.accessors[$.attributes[Y]],E=E8[O.componentType];H[G]=E.name,N[G]=O.normalized===!0}}return U.getDependency("bufferView",W).then(function(Y){return new Promise(function(G,O){Q.decodeDracoFile(Y,function(E){for(let Z in E.attributes){let D=E.attributes[Z],R=N[Z];if(R!==void 0)D.normalized=R}G(E)},X,H,BU,O)})})}}class r5{constructor(){this.name=$6.KHR_TEXTURE_TRANSFORM}extendTexture($,U){if((U.texCoord===void 0||U.texCoord===$.channel)&&U.offset===void 0&&U.rotation===void 0&&U.scale===void 0)return $;if($=$.clone(),U.texCoord!==void 0)$.channel=U.texCoord;if(U.offset!==void 0)$.offset.fromArray(U.offset);if(U.rotation!==void 0)$.rotation=U.rotation;if(U.scale!==void 0)$.repeat.fromArray(U.scale);return $.needsUpdate=!0,$}}class a5{constructor(){this.name=$6.KHR_MESH_QUANTIZATION}}class ZZ extends xJ{constructor($,U,J,Q){super($,U,J,Q)}copySampleValue_($){let U=this.resultBuffer,J=this.sampleValues,Q=this.valueSize,W=$*Q*3+Q;for(let K=0;K!==Q;K++)U[K]=J[W+K];return U}interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,N=X*2,H=X*3,Y=Q-U,G=(J-U)/Y,O=G*G,E=O*G,Z=$*H,D=Z-H,R=-2*E+3*O,I=E-O,q=1-R,_=I-O+G;for(let P=0;P!==X;P++){let L=K[D+P+X],B=K[D+P+N]*Y,z=K[Z+P+X],A=K[Z+P]*Y;W[P]=q*L+_*B+R*z+I*A}return W}}var Mz=new i6;class s5 extends ZZ{interpolate_($,U,J,Q){let W=super.interpolate_($,U,J,Q);return Mz.fromArray(W).normalize().toArray(W),W}}var hU={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},E8={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},z5={9728:rU,9729:o6,9984:W7,9985:$8,9986:f0,9987:ZJ},_5={33071:eW,33648:J7,10497:tW},XZ={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},GZ={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"},F0={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Bz={CUBICSPLINE:void 0,LINEAR:G7,STEP:VE},NZ={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Pz($){if($.DefaultMaterial===void 0)$.DefaultMaterial=new bJ({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:K0});return $.DefaultMaterial}function o0($,U,J){for(let Q in J.extensions)if($[Q]===void 0)U.userData.gltfExtensions=U.userData.gltfExtensions||{},U.userData.gltfExtensions[Q]=J.extensions[Q]}function FJ($,U){if(U.extras!==void 0)if(typeof U.extras==="object")Object.assign($.userData,U.extras);else console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+U.extras)}function zz($,U,J){let Q=!1,W=!1,K=!1;for(let Y=0,G=U.length;Y<G;Y++){let O=U[Y];if(O.POSITION!==void 0)Q=!0;if(O.NORMAL!==void 0)W=!0;if(O.COLOR_0!==void 0)K=!0;if(Q&&W&&K)break}if(!Q&&!W&&!K)return Promise.resolve($);let X=[],N=[],H=[];for(let Y=0,G=U.length;Y<G;Y++){let O=U[Y];if(Q){let E=O.POSITION!==void 0?J.getDependency("accessor",O.POSITION):$.attributes.position;X.push(E)}if(W){let E=O.NORMAL!==void 0?J.getDependency("accessor",O.NORMAL):$.attributes.normal;N.push(E)}if(K){let E=O.COLOR_0!==void 0?J.getDependency("accessor",O.COLOR_0):$.attributes.color;H.push(E)}}return Promise.all([Promise.all(X),Promise.all(N),Promise.all(H)]).then(function(Y){let G=Y[0],O=Y[1],E=Y[2];if(Q)$.morphAttributes.position=G;if(W)$.morphAttributes.normal=O;if(K)$.morphAttributes.color=E;return $.morphTargetsRelative=!0,$})}function _z($,U){if($.updateMorphTargets(),U.weights!==void 0)for(let J=0,Q=U.weights.length;J<Q;J++)$.morphTargetInfluences[J]=U.weights[J];if(U.extras&&Array.isArray(U.extras.targetNames)){let J=U.extras.targetNames;if($.morphTargetInfluences.length===J.length){$.morphTargetDictionary={};for(let Q=0,W=J.length;Q<W;Q++)$.morphTargetDictionary[J[Q]]=Q}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Az($){let U,J=$.extensions&&$.extensions[$6.KHR_DRACO_MESH_COMPRESSION];if(J)U="draco:"+J.bufferView+":"+J.indices+":"+HZ(J.attributes);else U=$.indices+":"+HZ($.attributes)+":"+$.mode;if($.targets!==void 0)for(let Q=0,W=$.targets.length;Q<W;Q++)U+=":"+HZ($.targets[Q]);return U}function HZ($){let U="",J=Object.keys($).sort();for(let Q=0,W=J.length;Q<W;Q++)U+=J[Q]+":"+$[J[Q]]+";";return U}function OZ($){switch($){case Int8Array:return 0.007874015748031496;case Uint8Array:return 0.00392156862745098;case Int16Array:return 0.00003051850947599719;case Uint16Array:return 0.000015259021896696422;default:throw Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function Cz($){if($.search(/\.jpe?g($|\?)/i)>0||$.search(/^data\:image\/jpeg/)===0)return"image/jpeg";if($.search(/\.webp($|\?)/i)>0||$.search(/^data\:image\/webp/)===0)return"image/webp";if($.search(/\.ktx2($|\?)/i)>0||$.search(/^data\:image\/ktx2/)===0)return"image/ktx2";return"image/png"}var Sz=new p$;class t5{constructor($={},U={}){this.json=$,this.extensions={},this.plugins={},this.options=U,this.cache=new wz,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 J=!1,Q=-1,W=!1,K=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){let X=navigator.userAgent;J=/^((?!chrome|android).)*safari/i.test(X)===!0;let N=X.match(/Version\/(\d+)/);Q=J&&N?parseInt(N[1],10):-1,W=X.indexOf("Firefox")>-1,K=W?X.match(/Firefox\/([0-9]+)\./)[1]:-1}if(typeof createImageBitmap>"u"||J&&Q<17||W&&K<98)this.textureLoader=new P7(this.options.manager);else this.textureLoader=new S7(this.options.manager);if(this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new TQ(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials")this.fileLoader.setWithCredentials(!0)}setExtensions($){this.extensions=$}setPlugins($){this.plugins=$}parse($,U){let J=this,Q=this.json,W=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(K){return K._markDefs&&K._markDefs()}),Promise.all(this._invokeAll(function(K){return K.beforeRoot&&K.beforeRoot()})).then(function(){return Promise.all([J.getDependencies("scene"),J.getDependencies("animation"),J.getDependencies("camera")])}).then(function(K){let X={scene:K[0][Q.scene||0],scenes:K[0],animations:K[1],cameras:K[2],asset:Q.asset,parser:J,userData:{}};return o0(W,X,Q),FJ(X,Q),Promise.all(J._invokeAll(function(N){return N.afterRoot&&N.afterRoot(X)})).then(function(){for(let N of X.scenes)N.updateMatrixWorld();$(X)})}).catch(U)}_markDefs(){let $=this.json.nodes||[],U=this.json.skins||[],J=this.json.meshes||[];for(let Q=0,W=U.length;Q<W;Q++){let K=U[Q].joints;for(let X=0,N=K.length;X<N;X++)$[K[X]].isBone=!0}for(let Q=0,W=$.length;Q<W;Q++){let K=$[Q];if(K.mesh!==void 0){if(this._addNodeRef(this.meshCache,K.mesh),K.skin!==void 0)J[K.mesh].isSkinnedMesh=!0}if(K.camera!==void 0)this._addNodeRef(this.cameraCache,K.camera)}}_addNodeRef($,U){if(U===void 0)return;if($.refs[U]===void 0)$.refs[U]=$.uses[U]=0;$.refs[U]++}_getNodeRef($,U,J){if($.refs[U]<=1)return J;let Q=J.clone(),W=(K,X)=>{let N=this.associations.get(K);if(N!=null)this.associations.set(X,N);for(let[H,Y]of K.children.entries())W(Y,X.children[H])};return W(J,Q),Q.name+="_instance_"+$.uses[U]++,Q}_invokeOne($){let U=Object.values(this.plugins);U.push(this);for(let J=0;J<U.length;J++){let Q=$(U[J]);if(Q)return Q}return null}_invokeAll($){let U=Object.values(this.plugins);U.unshift(this);let J=[];for(let Q=0;Q<U.length;Q++){let W=$(U[Q]);if(W)J.push(W)}return J}getDependency($,U){let J=$+":"+U,Q=this.cache.get(J);if(!Q){switch($){case"scene":Q=this.loadScene(U);break;case"node":Q=this._invokeOne(function(W){return W.loadNode&&W.loadNode(U)});break;case"mesh":Q=this._invokeOne(function(W){return W.loadMesh&&W.loadMesh(U)});break;case"accessor":Q=this.loadAccessor(U);break;case"bufferView":Q=this._invokeOne(function(W){return W.loadBufferView&&W.loadBufferView(U)});break;case"buffer":Q=this.loadBuffer(U);break;case"material":Q=this._invokeOne(function(W){return W.loadMaterial&&W.loadMaterial(U)});break;case"texture":Q=this._invokeOne(function(W){return W.loadTexture&&W.loadTexture(U)});break;case"skin":Q=this.loadSkin(U);break;case"animation":Q=this._invokeOne(function(W){return W.loadAnimation&&W.loadAnimation(U)});break;case"camera":Q=this.loadCamera(U);break;default:if(Q=this._invokeOne(function(W){return W!=this&&W.getDependency&&W.getDependency($,U)}),!Q)throw Error("Unknown type: "+$);break}this.cache.add(J,Q)}return Q}getDependencies($){let U=this.cache.get($);if(!U){let J=this,Q=this.json[$+($==="mesh"?"es":"s")]||[];U=Promise.all(Q.map(function(W,K){return J.getDependency($,K)})),this.cache.add($,U)}return U}loadBuffer($){let U=this.json.buffers[$],J=this.fileLoader;if(U.type&&U.type!=="arraybuffer")throw Error("THREE.GLTFLoader: "+U.type+" buffer type is not supported.");if(U.uri===void 0&&$===0)return Promise.resolve(this.extensions[$6.KHR_BINARY_GLTF].body);let Q=this.options;return new Promise(function(W,K){J.load(D0.resolveURL(U.uri,Q.path),W,void 0,function(){K(Error('THREE.GLTFLoader: Failed to load buffer "'+U.uri+'".'))})})}loadBufferView($){let U=this.json.bufferViews[$];return this.getDependency("buffer",U.buffer).then(function(J){let Q=U.byteLength||0,W=U.byteOffset||0;return J.slice(W,W+Q)})}loadAccessor($){let U=this,J=this.json,Q=this.json.accessors[$];if(Q.bufferView===void 0&&Q.sparse===void 0){let K=XZ[Q.type],X=E8[Q.componentType],N=Q.normalized===!0,H=new X(Q.count*K);return Promise.resolve(new u6(H,K,N))}let W=[];if(Q.bufferView!==void 0)W.push(this.getDependency("bufferView",Q.bufferView));else W.push(null);if(Q.sparse!==void 0)W.push(this.getDependency("bufferView",Q.sparse.indices.bufferView)),W.push(this.getDependency("bufferView",Q.sparse.values.bufferView));return Promise.all(W).then(function(K){let X=K[0],N=XZ[Q.type],H=E8[Q.componentType],Y=H.BYTES_PER_ELEMENT,G=Y*N,O=Q.byteOffset||0,E=Q.bufferView!==void 0?J.bufferViews[Q.bufferView].byteStride:void 0,Z=Q.normalized===!0,D,R;if(E&&E!==G){let I=Math.floor(O/E),q="InterleavedBuffer:"+Q.bufferView+":"+Q.componentType+":"+I+":"+Q.count,_=U.cache.get(q);if(!_)D=new H(X,I*E,Q.count*E/Y),_=new wQ(D,E/Y),U.cache.add(q,_);R=new Q8(_,N,O%E/Y,Z)}else{if(X===null)D=new H(Q.count*N);else D=new H(X,O,Q.count*N);R=new u6(D,N,Z)}if(Q.sparse!==void 0){let I=XZ.SCALAR,q=E8[Q.sparse.indices.componentType],_=Q.sparse.indices.byteOffset||0,P=Q.sparse.values.byteOffset||0,L=new q(K[1],_,Q.sparse.count*I),B=new H(K[2],P,Q.sparse.count*N);if(X!==null)R=new u6(R.array.slice(),R.itemSize,R.normalized);R.normalized=!1;for(let z=0,A=L.length;z<A;z++){let k=L[z];if(R.setX(k,B[z*N]),N>=2)R.setY(k,B[z*N+1]);if(N>=3)R.setZ(k,B[z*N+2]);if(N>=4)R.setW(k,B[z*N+3]);if(N>=5)throw Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}R.normalized=Z}return R})}loadTexture($){let U=this.json,J=this.options,W=U.textures[$].source,K=U.images[W],X=this.textureLoader;if(K.uri){let N=J.manager.getHandler(K.uri);if(N!==null)X=N}return this.loadTextureImage($,W,X)}loadTextureImage($,U,J){let Q=this,W=this.json,K=W.textures[$],X=W.images[U],N=(X.uri||X.bufferView)+":"+K.sampler;if(this.textureCache[N])return this.textureCache[N];let H=this.loadImageSource(U,J).then(function(Y){if(Y.flipY=!1,Y.name=K.name||X.name||"",Y.name===""&&typeof X.uri==="string"&&X.uri.startsWith("data:image/")===!1)Y.name=X.uri;let O=(W.samplers||{})[K.sampler]||{};return Y.magFilter=z5[O.magFilter]||o6,Y.minFilter=z5[O.minFilter]||ZJ,Y.wrapS=_5[O.wrapS]||tW,Y.wrapT=_5[O.wrapT]||tW,Y.generateMipmaps=!Y.isCompressedTexture&&Y.minFilter!==rU&&Y.minFilter!==o6,Q.associations.set(Y,{textures:$}),Y}).catch(function(){return null});return this.textureCache[N]=H,H}loadImageSource($,U){let J=this,Q=this.json,W=this.options;if(this.sourceCache[$]!==void 0)return this.sourceCache[$].then((G)=>G.clone());let K=Q.images[$],X=self.URL||self.webkitURL,N=K.uri||"",H=!1;if(K.bufferView!==void 0)N=J.getDependency("bufferView",K.bufferView).then(function(G){H=!0;let O=new Blob([G],{type:K.mimeType});return N=X.createObjectURL(O),N});else if(K.uri===void 0)throw Error("THREE.GLTFLoader: Image "+$+" is missing URI and bufferView");let Y=Promise.resolve(N).then(function(G){return new Promise(function(O,E){let Z=O;if(U.isImageBitmapLoader===!0)Z=function(D){let R=new v6(D);R.needsUpdate=!0,O(R)};U.load(D0.resolveURL(G,W.path),Z,void 0,E)})}).then(function(G){if(H===!0)X.revokeObjectURL(N);return FJ(G,K),G.userData.mimeType=K.mimeType||Cz(K.uri),G}).catch(function(G){throw console.error("THREE.GLTFLoader: Couldn't load texture",N),G});return this.sourceCache[$]=Y,Y}assignTexture($,U,J,Q){let W=this;return this.getDependency("texture",J.index).then(function(K){if(!K)return null;if(J.texCoord!==void 0&&J.texCoord>0)K=K.clone(),K.channel=J.texCoord;if(W.extensions[$6.KHR_TEXTURE_TRANSFORM]){let X=J.extensions!==void 0?J.extensions[$6.KHR_TEXTURE_TRANSFORM]:void 0;if(X){let N=W.associations.get(K);K=W.extensions[$6.KHR_TEXTURE_TRANSFORM].extendTexture(K,X),W.associations.set(K,N)}}if(Q!==void 0)K.colorSpace=Q;return $[U]=K,K})}assignFinalMaterial($){let{geometry:U,material:J}=$,Q=U.attributes.tangent===void 0,W=U.attributes.color!==void 0,K=U.attributes.normal===void 0;if($.isPoints){let X="PointsMaterial:"+J.uuid,N=this.cache.get(X);if(!N)N=new AQ,DU.prototype.copy.call(N,J),N.color.copy(J.color),N.map=J.map,N.sizeAttenuation=!1,this.cache.add(X,N);J=N}else if($.isLine){let X="LineBasicMaterial:"+J.uuid,N=this.cache.get(X);if(!N)N=new _Q,DU.prototype.copy.call(N,J),N.color.copy(J.color),N.map=J.map,this.cache.add(X,N);J=N}if(Q||W||K){let X="ClonedMaterial:"+J.uuid+":";if(Q)X+="derivative-tangents:";if(W)X+="vertex-colors:";if(K)X+="flat-shading:";let N=this.cache.get(X);if(!N){if(N=J.clone(),W)N.vertexColors=!0;if(K)N.flatShading=!0;if(Q){if(N.normalScale)N.normalScale.y*=-1;if(N.clearcoatNormalScale)N.clearcoatNormalScale.y*=-1}this.cache.add(X,N),this.associations.set(N,this.associations.get(J))}J=N}$.material=J}getMaterialType(){return bJ}loadMaterial($){let U=this,J=this.json,Q=this.extensions,W=J.materials[$],K,X={},N=W.extensions||{},H=[];if(N[$6.KHR_MATERIALS_UNLIT]){let G=Q[$6.KHR_MATERIALS_UNLIT];K=G.getMaterialType(),H.push(G.extendParams(X,W,U))}else{let G=W.pbrMetallicRoughness||{};if(X.color=new x$(1,1,1),X.opacity=1,Array.isArray(G.baseColorFactor)){let O=G.baseColorFactor;X.color.setRGB(O[0],O[1],O[2],BU),X.opacity=O[3]}if(G.baseColorTexture!==void 0)H.push(U.assignTexture(X,"map",G.baseColorTexture,N0));if(X.metalness=G.metallicFactor!==void 0?G.metallicFactor:1,X.roughness=G.roughnessFactor!==void 0?G.roughnessFactor:1,G.metallicRoughnessTexture!==void 0)H.push(U.assignTexture(X,"metalnessMap",G.metallicRoughnessTexture)),H.push(U.assignTexture(X,"roughnessMap",G.metallicRoughnessTexture));K=this._invokeOne(function(O){return O.getMaterialType&&O.getMaterialType($)}),H.push(Promise.all(this._invokeAll(function(O){return O.extendMaterialParams&&O.extendMaterialParams($,X)})))}if(W.doubleSided===!0)X.side=bU;let Y=W.alphaMode||NZ.OPAQUE;if(Y===NZ.BLEND)X.transparent=!0,X.depthWrite=!1;else if(X.transparent=!1,Y===NZ.MASK)X.alphaTest=W.alphaCutoff!==void 0?W.alphaCutoff:0.5;if(W.normalTexture!==void 0&&K!==qJ){if(H.push(U.assignTexture(X,"normalMap",W.normalTexture)),X.normalScale=new g$(1,1),W.normalTexture.scale!==void 0){let G=W.normalTexture.scale;X.normalScale.set(G,G)}}if(W.occlusionTexture!==void 0&&K!==qJ){if(H.push(U.assignTexture(X,"aoMap",W.occlusionTexture)),W.occlusionTexture.strength!==void 0)X.aoMapIntensity=W.occlusionTexture.strength}if(W.emissiveFactor!==void 0&&K!==qJ){let G=W.emissiveFactor;X.emissive=new x$().setRGB(G[0],G[1],G[2],BU)}if(W.emissiveTexture!==void 0&&K!==qJ)H.push(U.assignTexture(X,"emissiveMap",W.emissiveTexture,N0));return Promise.all(H).then(function(){let G=new K(X);if(W.name)G.name=W.name;if(FJ(G,W),U.associations.set(G,{materials:$}),W.extensions)o0(Q,G,W);return G})}createUniqueName($){let U=Y6.sanitizeNodeName($||"");if(U in this.nodeNamesUsed)return U+"_"+ ++this.nodeNamesUsed[U];else return this.nodeNamesUsed[U]=0,U}loadGeometries($){let U=this,J=this.extensions,Q=this.primitiveCache;function W(X){return J[$6.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(X,U).then(function(N){return A5(N,X,U)})}let K=[];for(let X=0,N=$.length;X<N;X++){let H=$[X],Y=Az(H),G=Q[Y];if(G)K.push(G.promise);else{let O;if(H.extensions&&H.extensions[$6.KHR_DRACO_MESH_COMPRESSION])O=W(H);else O=A5(new OU,H,U);Q[Y]={primitive:H,promise:O},K.push(O)}}return Promise.all(K)}loadMesh($){let U=this,J=this.json,Q=this.extensions,W=J.meshes[$],K=W.primitives,X=[];for(let N=0,H=K.length;N<H;N++){let Y=K[N].material===void 0?Pz(this.cache):this.getDependency("material",K[N].material);X.push(Y)}return X.push(U.loadGeometries(K)),Promise.all(X).then(function(N){let H=N.slice(0,N.length-1),Y=N[N.length-1],G=[];for(let E=0,Z=Y.length;E<Z;E++){let D=Y[E],R=K[E],I,q=H[E];if(R.mode===hU.TRIANGLES||R.mode===hU.TRIANGLE_STRIP||R.mode===hU.TRIANGLE_FAN||R.mode===void 0){if(I=W.isSkinnedMesh===!0?new k7(D,q):new P6(D,q),I.isSkinnedMesh===!0)I.normalizeSkinWeights();if(R.mode===hU.TRIANGLE_STRIP)I.geometry=KZ(I.geometry,FQ);else if(R.mode===hU.TRIANGLE_FAN)I.geometry=KZ(I.geometry,J8)}else if(R.mode===hU.LINES)I=new F7(D,q);else if(R.mode===hU.LINE_STRIP)I=new Y0(D,q);else if(R.mode===hU.LINE_LOOP)I=new L7(D,q);else if(R.mode===hU.POINTS)I=new X8(D,q);else throw Error("THREE.GLTFLoader: Primitive mode unsupported: "+R.mode);if(Object.keys(I.geometry.morphAttributes).length>0)_z(I,W);if(I.name=U.createUniqueName(W.name||"mesh_"+$),FJ(I,W),R.extensions)o0(Q,I,R);U.assignFinalMaterial(I),G.push(I)}for(let E=0,Z=G.length;E<Z;E++)U.associations.set(G[E],{meshes:$,primitives:E});if(G.length===1){if(W.extensions)o0(Q,G[0],W);return G[0]}let O=new YJ;if(W.extensions)o0(Q,O,W);U.associations.set(O,{meshes:$});for(let E=0,Z=G.length;E<Z;E++)O.add(G[E]);return O})}loadCamera($){let U,J=this.json.cameras[$],Q=J[J.type];if(!Q){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}if(J.type==="perspective")U=new f6(LQ.radToDeg(Q.yfov),Q.aspectRatio||1,Q.znear||1,Q.zfar||2000000);else if(J.type==="orthographic")U=new n0(-Q.xmag,Q.xmag,Q.ymag,-Q.ymag,Q.znear,Q.zfar);if(J.name)U.name=this.createUniqueName(J.name);return FJ(U,J),Promise.resolve(U)}loadSkin($){let U=this.json.skins[$],J=[];for(let Q=0,W=U.joints.length;Q<W;Q++)J.push(this._loadNodeShallow(U.joints[Q]));if(U.inverseBindMatrices!==void 0)J.push(this.getDependency("accessor",U.inverseBindMatrices));else J.push(null);return Promise.all(J).then(function(Q){let W=Q.pop(),K=Q,X=[],N=[];for(let H=0,Y=K.length;H<Y;H++){let G=K[H];if(G){X.push(G);let O=new p$;if(W!==null)O.fromArray(W.array,H*16);N.push(O)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',U.joints[H])}return new PQ(X,N)})}loadAnimation($){let U=this.json,J=this,Q=U.animations[$],W=Q.name?Q.name:"animation_"+$,K=[],X=[],N=[],H=[],Y=[];for(let G=0,O=Q.channels.length;G<O;G++){let E=Q.channels[G],Z=Q.samplers[E.sampler],D=E.target,R=D.node,I=Q.parameters!==void 0?Q.parameters[Z.input]:Z.input,q=Q.parameters!==void 0?Q.parameters[Z.output]:Z.output;if(D.node===void 0)continue;K.push(this.getDependency("node",R)),X.push(this.getDependency("accessor",I)),N.push(this.getDependency("accessor",q)),H.push(Z),Y.push(D)}return Promise.all([Promise.all(K),Promise.all(X),Promise.all(N),Promise.all(H),Promise.all(Y)]).then(function(G){let O=G[0],E=G[1],Z=G[2],D=G[3],R=G[4],I=[];for(let _=0,P=O.length;_<P;_++){let L=O[_],B=E[_],z=Z[_],A=D[_],k=R[_];if(L===void 0)continue;if(L.updateMatrix)L.updateMatrix();let w=J._createAnimationTracks(L,B,z,A,k);if(w)for(let h=0;h<w.length;h++)I.push(w[h])}let q=new oW(W,void 0,I);return FJ(q,Q),q})}createNodeMesh($){let U=this.json,J=this,Q=U.nodes[$];if(Q.mesh===void 0)return null;return J.getDependency("mesh",Q.mesh).then(function(W){let K=J._getNodeRef(J.meshCache,Q.mesh,W);if(Q.weights!==void 0)K.traverse(function(X){if(!X.isMesh)return;for(let N=0,H=Q.weights.length;N<H;N++)X.morphTargetInfluences[N]=Q.weights[N]});return K})}loadNode($){let U=this.json,J=this,Q=U.nodes[$],W=J._loadNodeShallow($),K=[],X=Q.children||[];for(let H=0,Y=X.length;H<Y;H++)K.push(J.getDependency("node",X[H]));let N=Q.skin===void 0?Promise.resolve(null):J.getDependency("skin",Q.skin);return Promise.all([W,Promise.all(K),N]).then(function(H){let Y=H[0],G=H[1],O=H[2];if(O!==null)Y.traverse(function(E){if(!E.isSkinnedMesh)return;E.bind(O,Sz)});for(let E=0,Z=G.length;E<Z;E++)Y.add(G[E]);if(Y.userData.pivot!==void 0&&G.length>0){let E=Y.userData.pivot,Z=G[0];Y.pivot=new j().fromArray(E),Y.position.x-=E[0],Y.position.y-=E[1],Y.position.z-=E[2],Z.position.set(0,0,0),delete Y.userData.pivot}return Y})}_loadNodeShallow($){let U=this.json,J=this.extensions,Q=this;if(this.nodeCache[$]!==void 0)return this.nodeCache[$];let W=U.nodes[$],K=W.name?Q.createUniqueName(W.name):"",X=[],N=Q._invokeOne(function(H){return H.createNodeMesh&&H.createNodeMesh($)});if(N)X.push(N);if(W.camera!==void 0)X.push(Q.getDependency("camera",W.camera).then(function(H){return Q._getNodeRef(Q.cameraCache,W.camera,H)}));return Q._invokeAll(function(H){return H.createNodeAttachment&&H.createNodeAttachment($)}).forEach(function(H){X.push(H)}),this.nodeCache[$]=Promise.all(X).then(function(H){let Y;if(W.isBone===!0)Y=new MQ;else if(H.length>1)Y=new YJ;else if(H.length===1)Y=H[0];else Y=new k6;if(Y!==H[0])for(let G=0,O=H.length;G<O;G++)Y.add(H[G]);if(W.name)Y.userData.name=W.name,Y.name=K;if(FJ(Y,W),W.extensions)o0(J,Y,W);if(W.matrix!==void 0){let G=new p$;G.fromArray(W.matrix),Y.applyMatrix4(G)}else{if(W.translation!==void 0)Y.position.fromArray(W.translation);if(W.rotation!==void 0)Y.quaternion.fromArray(W.rotation);if(W.scale!==void 0)Y.scale.fromArray(W.scale)}if(!Q.associations.has(Y))Q.associations.set(Y,{});else if(W.mesh!==void 0&&Q.meshCache.refs[W.mesh]>1){let G=Q.associations.get(Y);Q.associations.set(Y,{...G})}return Q.associations.get(Y).nodes=$,Y}),this.nodeCache[$]}loadScene($){let U=this.extensions,J=this.json.scenes[$],Q=this,W=new YJ;if(J.name)W.name=Q.createUniqueName(J.name);if(FJ(W,J),J.extensions)o0(U,W,J);let K=J.nodes||[],X=[];for(let N=0,H=K.length;N<H;N++)X.push(Q.getDependency("node",K[N]));return Promise.all(X).then(function(N){for(let Y=0,G=N.length;Y<G;Y++){let O=N[Y];if(O.parent!==null)W.add(M5(O));else W.add(O)}let H=(Y)=>{let G=new Map;for(let[O,E]of Q.associations)if(O instanceof DU||O instanceof v6)G.set(O,E);return Y.traverse((O)=>{let E=Q.associations.get(O);if(E!=null)G.set(O,E)}),G};return Q.associations=H(W),W})}_createAnimationTracks($,U,J,Q,W){let K=[],X=$.name?$.name:$.uuid,N=[];function H(E){if(E.morphTargetInfluences)N.push(E.name?E.name:E.uuid)}if(F0[W.path]===F0.weights){if(H($),$.isGroup)$.children.forEach(H)}else N.push(X);let Y;switch(F0[W.path]){case F0.weights:Y=Z0;break;case F0.rotation:Y=I0;break;case F0.translation:case F0.scale:Y=c0;break;default:switch(J.itemSize){case 1:Y=Z0;break;case 2:case 3:default:Y=c0;break}break}let G=Q.interpolation!==void 0?Bz[Q.interpolation]:G7,O=this._getArrayFromAccessor(J);for(let E=0,Z=N.length;E<Z;E++){let D=new Y(N[E]+"."+F0[W.path],U.array,O,G);if(Q.interpolation==="CUBICSPLINE")this._createCubicSplineTrackInterpolant(D);K.push(D)}return K}_getArrayFromAccessor($){let U=$.array;if($.normalized){let J=OZ(U.constructor),Q=new Float32Array(U.length);for(let W=0,K=U.length;W<K;W++)Q[W]=U[W]*J;U=Q}return U}_createCubicSplineTrackInterpolant($){$.createInterpolant=function(J){return new(this instanceof I0?s5:ZZ)(this.times,this.values,this.getValueSize()/3,J)},$.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Tz($,U,J){let Q=U.attributes,W=new GU;if(Q.POSITION!==void 0){let N=J.json.accessors[Q.POSITION],H=N.min,Y=N.max;if(H!==void 0&&Y!==void 0){if(W.set(new j(H[0],H[1],H[2]),new j(Y[0],Y[1],Y[2])),N.normalized){let G=OZ(E8[N.componentType]);W.min.multiplyScalar(G),W.max.multiplyScalar(G)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let K=U.targets;if(K!==void 0){let N=new j,H=new j;for(let Y=0,G=K.length;Y<G;Y++){let O=K[Y];if(O.POSITION!==void 0){let E=J.json.accessors[O.POSITION],Z=E.min,D=E.max;if(Z!==void 0&&D!==void 0){if(H.setX(Math.max(Math.abs(Z[0]),Math.abs(D[0]))),H.setY(Math.max(Math.abs(Z[1]),Math.abs(D[1]))),H.setZ(Math.max(Math.abs(Z[2]),Math.abs(D[2]))),E.normalized){let R=OZ(E8[E.componentType]);H.multiplyScalar(R)}N.max(H)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}W.expandByVector(N)}$.boundingBox=W;let X=new PU;W.getCenter(X.center),X.radius=W.min.distanceTo(W.max)/2,$.boundingSphere=X}function A5($,U,J){let Q=U.attributes,W=[];function K(X,N){return J.getDependency("accessor",X).then(function(H){$.setAttribute(N,H)})}for(let X in Q){let N=GZ[X]||X.toLowerCase();if(N in $.attributes)continue;W.push(K(Q[X],N))}if(U.indices!==void 0&&!$.index){let X=J.getDependency("accessor",U.indices).then(function(N){$.setIndex(N)});W.push(X)}if(s$.workingColorSpace!==BU&&"COLOR_0"in Q)console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${s$.workingColorSpace}" not supported.`);return FJ($,U),Tz($,U,J),Promise.all(W).then(function(){return U.targets!==void 0?zz($,U.targets,J):$})}var e5={type:"change"},qZ={type:"start"},UF={type:"end"},y7=new H0,$F=new cU,vz=Math.cos(70*LQ.DEG2RAD),p6=new j,kU=2*Math.PI,F6={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},IZ=0.000001;class DZ extends v7{constructor($,U=null){super($,U);if(this.state=F6.NONE,this.target=new j,this.cursor=new j,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=0.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:W0.ROTATE,MIDDLE:W0.DOLLY,RIGHT:W0.PAN},this.touches={ONE:Q0.ROTATE,TWO:Q0.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new j,this._lastQuaternion=new i6,this._lastTargetPosition=new j,this._quat=new i6().setFromUnitVectors($.up,new j(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new vQ,this._sphericalDelta=new vQ,this._scale=1,this._panOffset=new j,this._rotateStart=new g$,this._rotateEnd=new g$,this._rotateDelta=new g$,this._panStart=new g$,this._panEnd=new g$,this._panDelta=new g$,this._dollyStart=new g$,this._dollyEnd=new g$,this._dollyDelta=new g$,this._dollyDirection=new j,this._mouse=new g$,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=gz.bind(this),this._onPointerDown=jz.bind(this),this._onPointerUp=bz.bind(this),this._onContextMenu=mz.bind(this),this._onMouseWheel=hz.bind(this),this._onKeyDown=fz.bind(this),this._onTouchStart=uz.bind(this),this._onTouchMove=lz.bind(this),this._onMouseDown=xz.bind(this),this._onMouseMove=yz.bind(this),this._interceptControlDown=pz.bind(this),this._interceptControlUp=dz.bind(this),this.domElement!==null)this.connect(this.domElement);this.update()}set cursorStyle($){if(this._cursorStyle=$,$==="grab")this.domElement.style.cursor="grab";else this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect($){super.connect($),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents($){$.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=$}stopListenToKeyEvents(){if(this._domElementKeyEvents!==null)this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(e5),this.update(),this.state=F6.NONE}pan($,U){this._pan($,U),this.update()}dollyIn($){this._dollyIn($),this.update()}dollyOut($){this._dollyOut($),this.update()}rotateLeft($){this._rotateLeft($),this.update()}rotateUp($){this._rotateUp($),this.update()}update($=null){let U=this.object.position;if(p6.copy(U).sub(this.target),p6.applyQuaternion(this._quat),this._spherical.setFromVector3(p6),this.autoRotate&&this.state===F6.NONE)this._rotateLeft(this._getAutoRotationAngle($));if(this.enableDamping)this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor;else this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi;let J=this.minAzimuthAngle,Q=this.maxAzimuthAngle;if(isFinite(J)&&isFinite(Q)){if(J<-Math.PI)J+=kU;else if(J>Math.PI)J-=kU;if(Q<-Math.PI)Q+=kU;else if(Q>Math.PI)Q-=kU;if(J<=Q)this._spherical.theta=Math.max(J,Math.min(Q,this._spherical.theta));else this._spherical.theta=this._spherical.theta>(J+Q)/2?Math.max(J,this._spherical.theta):Math.min(Q,this._spherical.theta)}if(this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0)this.target.addScaledVector(this._panOffset,this.dampingFactor);else this.target.add(this._panOffset);this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let W=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let K=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),W=K!=this._spherical.radius}if(p6.setFromSpherical(this._spherical),p6.applyQuaternion(this._quatInverse),U.copy(this.target).add(p6),this.object.lookAt(this.target),this.enableDamping===!0)this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor);else this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0);if(this.zoomToCursor&&this._performCursorZoom){let K=null;if(this.object.isPerspectiveCamera){let X=p6.length();K=this._clampDistance(X*this._scale);let N=X-K;this.object.position.addScaledVector(this._dollyDirection,N),this.object.updateMatrixWorld(),W=!!N}else if(this.object.isOrthographicCamera){let X=new j(this._mouse.x,this._mouse.y,0);X.unproject(this.object);let N=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),W=N!==this.object.zoom;let H=new j(this._mouse.x,this._mouse.y,0);H.unproject(this.object),this.object.position.sub(H).add(X),this.object.updateMatrixWorld(),K=p6.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;if(K!==null)if(this.screenSpacePanning)this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(K).add(this.object.position);else if(y7.origin.copy(this.object.position),y7.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(y7.direction))<vz)this.object.lookAt(this.target);else $F.setFromNormalAndCoplanarPoint(this.object.up,this.target),y7.intersectPlane($F,this.target)}else if(this.object.isOrthographicCamera){let K=this.object.zoom;if(this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),K!==this.object.zoom)this.object.updateProjectionMatrix(),W=!0}if(this._scale=1,this._performCursorZoom=!1,W||this._lastPosition.distanceToSquared(this.object.position)>IZ||8*(1-this._lastQuaternion.dot(this.object.quaternion))>IZ||this._lastTargetPosition.distanceToSquared(this.target)>IZ)return this.dispatchEvent(e5),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0;return!1}_getAutoRotationAngle($){if($!==null)return kU/60*this.autoRotateSpeed*$;else return kU/60/60*this.autoRotateSpeed}_getZoomScale($){let U=Math.abs($*0.01);return Math.pow(0.95,this.zoomSpeed*U)}_rotateLeft($){this._sphericalDelta.theta-=$}_rotateUp($){this._sphericalDelta.phi-=$}_panLeft($,U){p6.setFromMatrixColumn(U,0),p6.multiplyScalar(-$),this._panOffset.add(p6)}_panUp($,U){if(this.screenSpacePanning===!0)p6.setFromMatrixColumn(U,1);else p6.setFromMatrixColumn(U,0),p6.crossVectors(this.object.up,p6);p6.multiplyScalar($),this._panOffset.add(p6)}_pan($,U){let J=this.domElement;if(this.object.isPerspectiveCamera){let Q=this.object.position;p6.copy(Q).sub(this.target);let W=p6.length();W*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*$*W/J.clientHeight,this.object.matrix),this._panUp(2*U*W/J.clientHeight,this.object.matrix)}else if(this.object.isOrthographicCamera)this._panLeft($*(this.object.right-this.object.left)/this.object.zoom/J.clientWidth,this.object.matrix),this._panUp(U*(this.object.top-this.object.bottom)/this.object.zoom/J.clientHeight,this.object.matrix);else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1}_dollyOut($){if(this.object.isPerspectiveCamera||this.object.isOrthographicCamera)this._scale/=$;else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1}_dollyIn($){if(this.object.isPerspectiveCamera||this.object.isOrthographicCamera)this._scale*=$;else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1}_updateZoomParameters($,U){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let J=this.domElement.getBoundingClientRect(),Q=$-J.left,W=U-J.top,K=J.width,X=J.height;this._mouse.x=Q/K*2-1,this._mouse.y=-(W/X)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance($){return Math.max(this.minDistance,Math.min(this.maxDistance,$))}_handleMouseDownRotate($){this._rotateStart.set($.clientX,$.clientY)}_handleMouseDownDolly($){this._updateZoomParameters($.clientX,$.clientX),this._dollyStart.set($.clientX,$.clientY)}_handleMouseDownPan($){this._panStart.set($.clientX,$.clientY)}_handleMouseMoveRotate($){this._rotateEnd.set($.clientX,$.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let U=this.domElement;this._rotateLeft(kU*this._rotateDelta.x/U.clientHeight),this._rotateUp(kU*this._rotateDelta.y/U.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly($){if(this._dollyEnd.set($.clientX,$.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0)this._dollyOut(this._getZoomScale(this._dollyDelta.y));else if(this._dollyDelta.y<0)this._dollyIn(this._getZoomScale(this._dollyDelta.y));this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan($){this._panEnd.set($.clientX,$.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel($){if(this._updateZoomParameters($.clientX,$.clientY),$.deltaY<0)this._dollyIn(this._getZoomScale($.deltaY));else if($.deltaY>0)this._dollyOut(this._getZoomScale($.deltaY));this.update()}_handleKeyDown($){let U=!1;switch($.code){case this.keys.UP:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate)this._rotateUp(kU*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(0,this.keyPanSpeed);U=!0;break;case this.keys.BOTTOM:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate)this._rotateUp(-kU*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(0,-this.keyPanSpeed);U=!0;break;case this.keys.LEFT:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate)this._rotateLeft(kU*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(this.keyPanSpeed,0);U=!0;break;case this.keys.RIGHT:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate)this._rotateLeft(-kU*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(-this.keyPanSpeed,0);U=!0;break}if(U)$.preventDefault(),this.update()}_handleTouchStartRotate($){if(this._pointers.length===1)this._rotateStart.set($.pageX,$.pageY);else{let U=this._getSecondPointerPosition($),J=0.5*($.pageX+U.x),Q=0.5*($.pageY+U.y);this._rotateStart.set(J,Q)}}_handleTouchStartPan($){if(this._pointers.length===1)this._panStart.set($.pageX,$.pageY);else{let U=this._getSecondPointerPosition($),J=0.5*($.pageX+U.x),Q=0.5*($.pageY+U.y);this._panStart.set(J,Q)}}_handleTouchStartDolly($){let U=this._getSecondPointerPosition($),J=$.pageX-U.x,Q=$.pageY-U.y,W=Math.sqrt(J*J+Q*Q);this._dollyStart.set(0,W)}_handleTouchStartDollyPan($){if(this.enableZoom)this._handleTouchStartDolly($);if(this.enablePan)this._handleTouchStartPan($)}_handleTouchStartDollyRotate($){if(this.enableZoom)this._handleTouchStartDolly($);if(this.enableRotate)this._handleTouchStartRotate($)}_handleTouchMoveRotate($){if(this._pointers.length==1)this._rotateEnd.set($.pageX,$.pageY);else{let J=this._getSecondPointerPosition($),Q=0.5*($.pageX+J.x),W=0.5*($.pageY+J.y);this._rotateEnd.set(Q,W)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let U=this.domElement;this._rotateLeft(kU*this._rotateDelta.x/U.clientHeight),this._rotateUp(kU*this._rotateDelta.y/U.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan($){if(this._pointers.length===1)this._panEnd.set($.pageX,$.pageY);else{let U=this._getSecondPointerPosition($),J=0.5*($.pageX+U.x),Q=0.5*($.pageY+U.y);this._panEnd.set(J,Q)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly($){let U=this._getSecondPointerPosition($),J=$.pageX-U.x,Q=$.pageY-U.y,W=Math.sqrt(J*J+Q*Q);this._dollyEnd.set(0,W),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let K=($.pageX+U.x)*0.5,X=($.pageY+U.y)*0.5;this._updateZoomParameters(K,X)}_handleTouchMoveDollyPan($){if(this.enableZoom)this._handleTouchMoveDolly($);if(this.enablePan)this._handleTouchMovePan($)}_handleTouchMoveDollyRotate($){if(this.enableZoom)this._handleTouchMoveDolly($);if(this.enableRotate)this._handleTouchMoveRotate($)}_addPointer($){this._pointers.push($.pointerId)}_removePointer($){delete this._pointerPositions[$.pointerId];for(let U=0;U<this._pointers.length;U++)if(this._pointers[U]==$.pointerId){this._pointers.splice(U,1);return}}_isTrackingPointer($){for(let U=0;U<this._pointers.length;U++)if(this._pointers[U]==$.pointerId)return!0;return!1}_trackPointer($){let U=this._pointerPositions[$.pointerId];if(U===void 0)U=new g$,this._pointerPositions[$.pointerId]=U;U.set($.pageX,$.pageY)}_getSecondPointerPosition($){let U=$.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[U]}_customWheelEvent($){let U=$.deltaMode,J={clientX:$.clientX,clientY:$.clientY,deltaY:$.deltaY};switch(U){case 1:J.deltaY*=16;break;case 2:J.deltaY*=100;break}if($.ctrlKey&&!this._controlActive)J.deltaY*=10;return J}}function jz($){if(this.enabled===!1)return;if(this._pointers.length===0)this.domElement.setPointerCapture($.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp);if(this._isTrackingPointer($))return;if(this._addPointer($),$.pointerType==="touch")this._onTouchStart($);else this._onMouseDown($);if(this._cursorStyle==="grab")this.domElement.style.cursor="grabbing"}function gz($){if(this.enabled===!1)return;if($.pointerType==="touch")this._onTouchMove($);else this._onMouseMove($)}function bz($){switch(this._removePointer($),this._pointers.length){case 0:if(this.domElement.releasePointerCapture($.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(UF),this.state=F6.NONE,this._cursorStyle==="grab")this.domElement.style.cursor="grab";break;case 1:let U=this._pointers[0],J=this._pointerPositions[U];this._onTouchStart({pointerId:U,pageX:J.x,pageY:J.y});break}}function xz($){let U;switch($.button){case 0:U=this.mouseButtons.LEFT;break;case 1:U=this.mouseButtons.MIDDLE;break;case 2:U=this.mouseButtons.RIGHT;break;default:U=-1}switch(U){case W0.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly($),this.state=F6.DOLLY;break;case W0.ROTATE:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan($),this.state=F6.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate($),this.state=F6.ROTATE}break;case W0.PAN:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate($),this.state=F6.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan($),this.state=F6.PAN}break;default:this.state=F6.NONE}if(this.state!==F6.NONE)this.dispatchEvent(qZ)}function yz($){switch(this.state){case F6.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate($);break;case F6.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly($);break;case F6.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan($);break}}function hz($){if(this.enabled===!1||this.enableZoom===!1||this.state!==F6.NONE)return;$.preventDefault(),this.dispatchEvent(qZ),this._handleMouseWheel(this._customWheelEvent($)),this.dispatchEvent(UF)}function fz($){if(this.enabled===!1)return;this._handleKeyDown($)}function uz($){switch(this._trackPointer($),this._pointers.length){case 1:switch(this.touches.ONE){case Q0.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate($),this.state=F6.TOUCH_ROTATE;break;case Q0.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan($),this.state=F6.TOUCH_PAN;break;default:this.state=F6.NONE}break;case 2:switch(this.touches.TWO){case Q0.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan($),this.state=F6.TOUCH_DOLLY_PAN;break;case Q0.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate($),this.state=F6.TOUCH_DOLLY_ROTATE;break;default:this.state=F6.NONE}break;default:this.state=F6.NONE}if(this.state!==F6.NONE)this.dispatchEvent(qZ)}function lz($){switch(this._trackPointer($),this.state){case F6.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate($),this.update();break;case F6.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan($),this.update();break;case F6.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan($),this.update();break;case F6.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate($),this.update();break;default:this.state=F6.NONE}}function mz($){if(this.enabled===!1)return;$.preventDefault()}function pz($){if($.key==="Control")this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}function dz($){if($.key==="Control")this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}class kZ extends W8{constructor(){super();this.name="RoomEnvironment",this.position.y=-3.5;let $=new O0;$.deleteAttribute("uv");let U=new bJ({side:JU}),J=new bJ,Q=new H8(16777215,900,28,2);Q.position.set(0.418,16.199,0.3),this.add(Q);let W=new P6($,U);W.position.set(-0.757,13.219,0.717),W.scale.set(31.713,28.305,28.591),this.add(W);let K=new K8($,J,6),X=new k6;X.position.set(-10.906,2.009,1.846),X.rotation.set(0,-0.195,0),X.scale.set(2.328,7.905,4.651),X.updateMatrix(),K.setMatrixAt(0,X.matrix),X.position.set(-5.607,-0.754,-0.758),X.rotation.set(0,0.994,0),X.scale.set(1.97,1.534,3.955),X.updateMatrix(),K.setMatrixAt(1,X.matrix),X.position.set(6.167,0.857,7.803),X.rotation.set(0,0.561,0),X.scale.set(3.927,6.285,3.687),X.updateMatrix(),K.setMatrixAt(2,X.matrix),X.position.set(-2.017,0.018,6.124),X.rotation.set(0,0.333,0),X.scale.set(2.002,4.566,2.064),X.updateMatrix(),K.setMatrixAt(3,X.matrix),X.position.set(2.291,-0.756,-2.621),X.rotation.set(0,-0.286,0),X.scale.set(1.546,1.552,1.496),X.updateMatrix(),K.setMatrixAt(4,X.matrix),X.position.set(-2.193,-0.369,-5.547),X.rotation.set(0,0.516,0),X.scale.set(3.875,3.487,2.986),X.updateMatrix(),K.setMatrixAt(5,X.matrix),this.add(K);let N=new P6($,Z8(50));N.position.set(-16.116,14.37,8.208),N.scale.set(0.1,2.428,2.739),this.add(N);let H=new P6($,Z8(50));H.position.set(-16.109,18.021,-8.207),H.scale.set(0.1,2.425,2.751),this.add(H);let Y=new P6($,Z8(17));Y.position.set(14.904,12.198,-1.832),Y.scale.set(0.15,4.265,6.331),this.add(Y);let G=new P6($,Z8(43));G.position.set(-0.462,8.89,14.52),G.scale.set(4.38,5.441,0.088),this.add(G);let O=new P6($,Z8(20));O.position.set(3.235,11.486,-12.541),O.scale.set(2.5,2,0.1),this.add(O);let E=new P6($,Z8(100));E.position.set(0,20,0),E.scale.set(1,0.1,1),this.add(E)}dispose(){let $=new Set;this.traverse((U)=>{if(U.isMesh)$.add(U.geometry),$.add(U.material)});for(let U of $)U.dispose()}}function Z8($){return new w7({color:0,emissive:16777215,emissiveIntensity:$})}function JF($,U,J=40,Q=[$]){let W=$.getCenter(new j),K=Math.max($.getSize(new j).length()/2,0.01),X=new j(1,0.65,1.25).normalize(),N=new j().crossVectors(new j(0,1,0),X).normalize(),H=new j().crossVectors(X,N),Y=[];for(let _ of Q.length?Q:[$])for(let P of[_.min.x,_.max.x])for(let L of[_.min.y,_.max.y])for(let B of[_.min.z,_.max.z])Y.push(new j(P,L,B));let G=1/0,O=-1/0,E=1/0,Z=-1/0;for(let _ of Y){let P=_.clone().sub(W),L=P.dot(N),B=P.dot(H);G=Math.min(G,L),O=Math.max(O,L),E=Math.min(E,B),Z=Math.max(Z,B)}W.addScaledVector(N,(G+O)/2),W.addScaledVector(H,(E+Z)/2);let D=Math.tan(J*Math.PI/360),R=D*U,I=K;for(let _ of Y){let P=_.clone().sub(W),L=P.dot(X);I=Math.max(I,L+Math.abs(P.dot(N))*1.12/R,L+Math.abs(P.dot(H))*1.12/D)}let q=W.clone().addScaledVector(X,I);return{center:W,radius:K,distance:I,position:q}}function WF($){let U=new QZ({antialias:!0,alpha:!1});U.setPixelRatio(Math.min(devicePixelRatio,2)),U.setClearColor(1382930),U.toneMapping=qQ,U.toneMappingExposure=1.15,$.replaceChildren(U.domElement);let J=new W8,Q=new f6(40,1,0.01,1000),W=new DZ(Q,U.domElement);W.enableDamping=!0;let K=new yQ(U),X=new kZ,N=K.fromScene(X,0.04);J.environment=N.texture,X.dispose(),K.dispose();let H=new Y8(16773591,2.4);H.position.set(4,8,5),J.add(H),J.add(new z7(14806490,5065021,1.7));let Y,G,O=[],E=!0,Z=performance.now(),D=0,R=0,I=!1,q=(B)=>{let z=new Set,A=new Set,k=new Set;B.traverse((w)=>{let h=w;if(!h.isMesh)return;z.add(h.geometry);for(let C of Array.isArray(h.material)?h.material:[h.material]){A.add(C);for(let f of Object.values(C))if(f instanceof v6)k.add(f)}});for(let w of[...z,...A,...k])w.dispose()},_=()=>{if(!Y)return;let B=new GU().setFromObject(Y,!0),z=[];Y.traverse((C)=>{if(C instanceof P6||C instanceof Y0||C instanceof X8){let f=new GU().setFromObject(C,!0);if(!f.isEmpty())z.push(f)}});let{center:A,radius:k,distance:w,position:h}=JF(B,Q.aspect,Q.fov,z);W.target.copy(A),Q.position.copy(h),Q.near=Math.max(k/1000,0.0001),Q.far=w+k*100,W.minDistance=k*0.1,W.maxDistance=k*80,Q.updateProjectionMatrix(),W.update()},P=new ResizeObserver(()=>{let{clientWidth:B,clientHeight:z}=$;if(!B||!z)return;U.setSize(B,z),Q.aspect=B/z,Q.updateProjectionMatrix()});P.observe($);let L=(B)=>{if(I)return;let z=Math.min((B-Z)/1000,0.1);if(Z=B,E)G?.update(z);W.update(),U.render(J,Q),D=requestAnimationFrame(L)};return D=requestAnimationFrame(L),{async load(B){let z=++R;eG(B);let A=new SQ;A.setURLModifier((y)=>{if(!y.startsWith("blob:")&&!y.startsWith("data:"))throw Error("External model resources are not loaded");return y});let k=await new EZ(A).parseAsync(Uint8Array.from(B).buffer,"");if(I||z!==R){q(k.scene);return}if(Y)G?.stopAllAction(),G?.uncacheRoot(Y),J.remove(Y),q(Y);Y=k.scene,J.add(Y),O=k.animations,G=new T7(Y),E=!0;let{clientWidth:w,clientHeight:h}=$;U.setSize(w,h),Q.aspect=w/h,_();let C=0,f=0,s=new Set;return Y.traverse((y)=>{let d=y;if(!d.isMesh)return;f++,C+=(d.geometry.index?.count??d.geometry.attributes.position?.count??0)/3*(d.isInstancedMesh?d.count:1);for(let c of Array.isArray(d.material)?d.material:[d.material])s.add(c)}),{triangles:C,meshes:f,materials:s.size,clips:O.map((y)=>y.name)}},reset:_,wire(B){Y?.traverse((z)=>{let A=z;if(A.isMesh){for(let k of Array.isArray(A.material)?A.material:[A.material])if("wireframe"in k)k.wireframe=B}})},lighting(B){U.toneMappingExposure=B==="bright"?1.65:B==="soft"?0.85:1.15,H.intensity=B==="soft"?0.8:2.4},clip(B){if(G?.stopAllAction(),O[B])G?.clipAction(O[B]).play()},pause(B){E=!B},dispose(){if(I=!0,R++,cancelAnimationFrame(D),P.disconnect(),W.dispose(),Y)q(Y);N.dispose(),U.dispose(),$.replaceChildren()}}}var f$=($)=>document.getElementById($),x6=($,U,J)=>{let Q=document.createElement($);if(U!==void 0)Q.textContent=U;if(J)Q.className=J;return Q},mQ=[],q8=[],a0=[],h7="",I8,AU,fQ=0,QF=0,uQ=!1,lQ=!1,L0=new Set,FZ=[],KF=[],r0=($)=>`${$.collection}/${$.manifest.assetId}/${$.manifest.revisionId}`,XF=($)=>{f$("status").textContent=$},s0=($)=>XF($ instanceof Error?$.message:String($)),pQ=($,U,J=FZ)=>{let Q=URL.createObjectURL(new Blob([Uint8Array.from($)],{type:U}));return J.push(Q),Q};async function NF($){let U=await fetch($),J=await U.json();if(!U.ok)throw Error(J.error??"Request failed");return J}async function cz($,U){if($.local){let Q=$.local.files[U];if(!Q)throw Error("File unavailable");return Q}if($.loose&&U==="asset.glb")return $.loose;let J=await fetch(`/files/${r0($)}/${U}`);if(!J.ok)throw Error((await J.json()).error??"File unavailable");return new Uint8Array(await J.arrayBuffer())}function nz($,U){if($.local){if(U==="editable.zip")return pQ($O([$.local]),"application/zip");return pQ($.local.files[U],U.endsWith(".js")?"text/javascript":"model/gltf-binary")}if($.loose)return pQ($.loose,"model/gltf-binary");return`/files/${r0($)}/${U}?download`}function HF($,U){try{localStorage.setItem($,U)}catch{}}function YF($){try{return localStorage.getItem($)}catch{return null}}function iz(){let $=f$("collections");$.replaceChildren();for(let U of[...mQ,...a0.length?[{id:"opened-files",label:"Opened files"}]:[]]){let J=x6("button",U.label,h7===U.id?"active":"");J.onclick=()=>void f7(U.id).catch(s0),$.append(J)}}async function f7($){let U=++QF;h7=$,L0.clear(),iz(),XF("");let J=$==="opened-files"?a0:(await NF(`/api/assets?collection=${encodeURIComponent($)}`)).assets.map((Q)=>({collection:$,manifest:Q}));if(U!==QF)return;q8=J,HF("kiln.collection",$),f$("collection-title").textContent=$==="opened-files"?"Opened files":mQ.find((Q)=>Q.id===$)?.label??$,f$("collection-caption").textContent=$==="opened-files"?"Previewed in your browser. Your original files stay untouched.":"Saved revisions, editable source, and everything ready to use.",LZ()}function oz(){let $=new Map;for(let U of q8){let J=U.manifest.assetId;$.set(J,[...$.get(J)??[],U])}return[...$.values()].map((U)=>{return U.sort((J,Q)=>Q.manifest.createdAt.localeCompare(J.manifest.createdAt)||Q.manifest.revisionId.localeCompare(J.manifest.revisionId)),U.find((J)=>J.manifest.revisionId===YF(`kiln.revision.${J.collection}.${J.manifest.assetId}`))??U[0]})}function LZ(){for(let Q of KF.splice(0))URL.revokeObjectURL(Q);let $=f$("cards");$.replaceChildren();let U=f$("search").value.toLowerCase(),J=oz().filter((Q)=>`${Q.manifest.name} ${Q.manifest.tags.join(" ")}`.toLowerCase().includes(U));if(f$("count").textContent=`${J.length} asset${J.length===1?"":"s"}`,f$("export-selection").disabled=!L0.size,!J.length){let Q=x6("div",void 0,"empty");if(Q.append(x6("b",U?"No matching assets":"Your next idea belongs here."),x6("p",U?"Try another name or tag.":"Save an asset with your agent, or open a GLB or editable bundle.")),!U)Q.append(x6("code",'kiln save asset.kiln.js --name "My asset"'));$.append(Q);return}for(let Q of J){let W=Q.manifest,K=x6("article",void 0,"card"),X=x6("button",void 0,"card-open");X.setAttribute("aria-label",`View ${W.name}`),X.onclick=()=>void RZ(Q).catch(s0);let N=x6("div",void 0,"thumb");if(W.files["preview.png"]){let Z=x6("img");Z.loading="lazy",Z.alt=W.name,Z.src=Q.local?pQ(Q.local.files["preview.png"],"image/png",KF):`/files/${r0(Q)}/preview.png`,Z.onerror=()=>{Z.remove(),N.textContent="◇"},N.append(Z)}else N.textContent="◇";let H=x6("div",void 0,"card-content");H.append(x6("span",W.name,"card-title"));let Y=q8.filter((Z)=>Z.manifest.assetId===W.assetId),G=new Set(Y.map((Z)=>Z.manifest.parentRevision)),O=Y.filter((Z)=>!G.has(Z.manifest.revisionId));H.append(x6("span",`${W.editable?"Editable source":"Source unavailable"} · ${Y.length} revision${Y.length===1?"":"s"}${O.length>1?` · ${O.length} branches`:""}`,"card-meta"));let E=x6("div",void 0,"tags");for(let Z of W.tags)E.append(x6("span",Z,"tag"));if(H.append(E),X.append(N,H),K.append(X),!Q.loose){let Z=x6("input");Z.type="checkbox",Z.className="selection",Z.checked=L0.has(r0(Q)),Z.setAttribute("aria-label",`Select ${W.name}`),Z.onchange=()=>{if(Z.checked)L0.add(r0(Q));else L0.delete(r0(Q));f$("export-selection").disabled=!L0.size},K.append(Z)}$.append(K)}}async function RZ($){let U=++fQ;I8=$,HF(`kiln.revision.${$.collection}.${$.manifest.assetId}`,$.manifest.revisionId);for(let X of FZ.splice(0))URL.revokeObjectURL(X);let J=f$("detail");if(!J.open)J.showModal();f$("asset-name").textContent=$.manifest.name;let Q=f$("revisions");Q.replaceChildren();for(let X of q8.filter((N)=>N.manifest.assetId===$.manifest.assetId)){let N=x6("option",`${new Date(X.manifest.createdAt).toLocaleString()} · ${X.manifest.description||X.manifest.revisionId.slice(0,10)}`);N.value=X.manifest.revisionId,N.selected=X.manifest.revisionId===$.manifest.revisionId,Q.append(N)}Q.onchange=()=>{let X=q8.find((N)=>N.manifest.assetId===$.manifest.assetId&&N.manifest.revisionId===Q.value);if(X)RZ(X).catch(s0)},f$("asset-description").textContent=$.manifest.description??$.manifest.brief??($.manifest.editable?"Source travels with this revision. Download the editable bundle to continue elsewhere.":"This GLB has no saved Kiln source. You can view and use the model."),f$("provenance").textContent=$.loose?"Standalone GLB. No source or build provenance supplied.":JSON.stringify($.manifest,null,2);let W=f$("downloads");W.replaceChildren();for(let[X,N]of[["asset.glb","Download GLB"],...$.manifest.editable?[["source.kiln.js","Download source"]]:[],...!$.loose?[["editable.zip",$.manifest.editable?"Download editable bundle":"Download asset bundle"]]:[]]){let H=x6("a",N);H.href=nz($,X),H.download=`${$.manifest.name.replace(/[^a-z0-9_-]/gi,"-")}${X==="asset.glb"?".glb":X==="source.kiln.js"?".kiln.js":".zip"}`,W.append(H)}f$("refine").disabled=!$.manifest.editable,f$("asset-stats").replaceChildren(),f$("stage-status").textContent="Loading saved GLB…",uQ=!1,lQ=!1,f$("wire").setAttribute("aria-pressed","false"),f$("play").textContent="Pause";let K=f$("animation");K.replaceChildren(new Option("Rest pose","")),f$("play").disabled=!0;try{AU??=WF(f$("stage"));let X=await cz($,"asset.glb");if(U!==fQ)return;let N=await AU.load(X);if(!N||U!==fQ)return;AU.wire(!1),AU.lighting(f$("lighting").value);for(let[H,Y]of[[N.triangles.toLocaleString(),"triangles"],[N.meshes,"meshes"],[N.materials,"materials"],[`${(X.length/1024).toFixed(0)} KB`,"GLB"]]){let G=x6("div");G.append(x6("strong",String(H)),x6("span",String(Y))),f$("asset-stats").append(G)}for(let H=0;H<N.clips.length;H++)K.append(new Option(N.clips[H],String(H)));f$("stage-status").textContent=""}catch(X){if(U===fQ)AU?.dispose(),AU=void 0,f$("stage-status").textContent=`3D preview unavailable: ${X instanceof Error?X.message:X}. Downloads remain available.`}}async function GF($){for(let U of $){if(U.bytes.length>PJ)throw Error("File exceeds 64 MiB");if(U.name.toLowerCase().endsWith(".zip"))for(let J of tq(U.bytes)){for(let[Q,W]of Object.entries(J.files))if(`sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(W)))).map((X)=>X.toString(16).padStart(2,"0")).join("")}`!==J.manifest.files[Q]?.sha256)throw Error(`Bundle integrity failure: ${Q}`);if(!a0.some((Q)=>Q.manifest.revisionId===J.manifest.revisionId&&Q.manifest.assetId===J.manifest.assetId))a0.push({collection:"opened-files",manifest:J.manifest,local:J})}else{let J=`a_${crypto.randomUUID().replaceAll("-","")}`;a0.push({collection:"opened-files",loose:U.bytes,manifest:{version:"kiln.asset.v1",assetId:J,revisionId:`r_${J}`,name:U.name.replace(/\.glb$/i,""),tags:[],createdAt:new Date().toISOString(),editable:!1,files:{}}})}}await f7("opened-files")}f$("open").onchange=async($)=>{try{let U=Array.from($.target.files??[]);if(U.some((J)=>J.size>PJ))throw Error("File exceeds 64 MiB");await GF(await Promise.all(U.map(async(J)=>({name:J.name,bytes:new Uint8Array(await J.arrayBuffer())}))))}catch(U){s0(U)}};f$("refresh").onclick=()=>void f7(h7).catch(s0);f$("search").oninput=LZ;f$("close-detail").onclick=()=>f$("detail").close();f$("detail").addEventListener("close",()=>{fQ++,AU?.dispose(),AU=void 0;for(let $ of FZ.splice(0))URL.revokeObjectURL($);LZ()});f$("frame").onclick=()=>AU?.reset();f$("wire").onclick=()=>{uQ=!uQ,AU?.wire(uQ),f$("wire").setAttribute("aria-pressed",String(uQ))};f$("lighting").onchange=($)=>AU?.lighting($.target.value);f$("animation").onchange=($)=>{let U=$.target.value;AU?.clip(U===""?-1:Number(U)),f$("play").disabled=U===""};f$("play").onclick=()=>{lQ=!lQ,AU?.pause(lQ),f$("play").textContent=lQ?"Play":"Pause"};f$("refine").onclick=async()=>{if(!I8)return;let $=I8.manifest,U=I8.local?`Import the downloaded editable bundle using kiln import <bundle.zip>. Restore asset ${$.assetId}, revision ${$.revisionId}, using kiln_assets action=restore. Read its source with kiln_source, refine it with kiln_edit, review the result, and save a child revision with kiln_save. Requested change: `:`Use kiln_assets with action=restore, collection=${I8.collection}, assetId=${$.assetId}, revisionId=${$.revisionId}. Read the returned programRef with kiln_source, refine it with kiln_edit, review the result, and save with kiln_save using assetId=${$.assetId}, parentRevision=${$.revisionId}, collection=${I8.collection}. Requested change: `;try{await navigator.clipboard.writeText(U),f$("refine").textContent="Instructions copied"}catch{f$("provenance").textContent=U,f$("provenance").parentElement?.setAttribute("open","")}};f$("export-selection").onclick=()=>{try{let $=x6("a");if(h7==="opened-files")$.href=pQ($O(q8.filter((U)=>L0.has(r0(U))).map((U)=>U.local)),"application/zip");else{let U=new URLSearchParams;for(let J of L0)U.append("revision",J);$.href=`/api/bundle?${U}`}$.download="kiln-assets.zip",$.click()}catch($){s0($)}};async function rz(){mQ=(await NF("/api/collections")).collections;let $=YF("kiln.collection");if(await f7(mQ.find((U)=>U.id===$)?.id??mQ[0]?.id??"project"),new URLSearchParams(location.search).has("open")){let U=await fetch("/api/standalone");if(!U.ok)throw Error("File unavailable");if(await GF([{name:U.headers.get("Content-Type")?.includes("zip")?"asset.zip":"asset.glb",bytes:new Uint8Array(await U.arrayBuffer())}]),a0.length===1)await RZ(a0[0])}}rz().catch(s0);+}`;class n0{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new Fa(e.texture);if(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){if(this.mesh===null){let t=e.cameras[0].viewport,n=new Mn({vertexShader:PT,fragmentShader:LT,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new pt(new to(20,20),n)}}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class i0 extends zn{constructor(e,t){super();let n=this,i=null,r=1,s=null,o="local-floor",a=1,c=null,l=null,u=null,f=null,h=null,d=null,g=typeof XRWebGLBinding<"u",y=new n0,p={},m=t.getContextAttributes(),A=null,T=null,v=[],w=[],E=new Ie,R=null,_=new Lt;_.viewport=new st;let S=new Lt;S.viewport=new st;let F=[_,S],C=new Fu,z=null,J=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let ne=v[Z];if(ne===void 0)ne=new Xs,v[Z]=ne;return ne.getTargetRaySpace()},this.getControllerGrip=function(Z){let ne=v[Z];if(ne===void 0)ne=new Xs,v[Z]=ne;return ne.getGripSpace()},this.getHand=function(Z){let ne=v[Z];if(ne===void 0)ne=new Xs,v[Z]=ne;return ne.getHandSpace()};function O(Z){let ne=w.indexOf(Z.inputSource);if(ne===-1)return;let fe=v[ne];if(fe!==void 0)fe.update(Z.inputSource,Z.frame,c||s),fe.dispatchEvent({type:Z.type,data:Z.inputSource})}function H(){i.removeEventListener("select",O),i.removeEventListener("selectstart",O),i.removeEventListener("selectend",O),i.removeEventListener("squeeze",O),i.removeEventListener("squeezestart",O),i.removeEventListener("squeezeend",O),i.removeEventListener("end",H),i.removeEventListener("inputsourceschange",V);for(let Z=0;Z<v.length;Z++){let ne=w[Z];if(ne===null)continue;w[Z]=null,v[Z].disconnect(ne)}z=null,J=null,y.reset();for(let Z in p)delete p[Z];e.setRenderTarget(A),h=null,f=null,u=null,i=null,T=null,Ge.stop(),n.isPresenting=!1,e.setPixelRatio(R),e.setSize(E.width,E.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){if(r=Z,n.isPresenting===!0)Me("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){if(o=Z,n.isPresenting===!0)Me("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||s},this.setReferenceSpace=function(Z){c=Z},this.getBaseLayer=function(){return f!==null?f:h},this.getBinding=function(){if(u===null&&g)u=new XRWebGLBinding(i,t);return u},this.getFrame=function(){return d},this.getSession=function(){return i},this.setSession=async function(Z){if(i=Z,i!==null){if(A=e.getRenderTarget(),i.addEventListener("select",O),i.addEventListener("selectstart",O),i.addEventListener("selectend",O),i.addEventListener("squeeze",O),i.addEventListener("squeezestart",O),i.addEventListener("squeezeend",O),i.addEventListener("end",H),i.addEventListener("inputsourceschange",V),m.xrCompatible!==!0)await t.makeXRCompatible();if(R=e.getPixelRatio(),e.getSize(E),!(g&&("createProjectionLayer"in XRWebGLBinding.prototype))){let fe={antialias:m.antialias,alpha:!0,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:r};h=new XRWebGLLayer(i,t,fe),i.updateRenderState({baseLayer:h}),e.setPixelRatio(1),e.setSize(h.framebufferWidth,h.framebufferHeight,!1),T=new Sn(h.framebufferWidth,h.framebufferHeight,{format:Jn,type:Fn,colorSpace:e.outputColorSpace,stencilBuffer:m.stencil,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1})}else{let fe=null,de=null,Re=null;if(m.depth)Re=m.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,fe=m.stencil?dr:fr,de=m.stencil?Kr:Oi;let Ze={colorFormat:t.RGBA8,depthFormat:Re,scaleFactor:r};u=this.getBinding(),f=u.createProjectionLayer(Ze),i.updateRenderState({layers:[f]}),e.setPixelRatio(1),e.setSize(f.textureWidth,f.textureHeight,!1),T=new Sn(f.textureWidth,f.textureHeight,{format:Jn,type:Fn,depthTexture:new Bi(f.textureWidth,f.textureHeight,de,void 0,void 0,void 0,void 0,void 0,void 0,fe),stencilBuffer:m.stencil,colorSpace:e.outputColorSpace,samples:m.antialias?4:0,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}T.isXRRenderTarget=!0,this.setFoveation(a),c=null,s=await i.requestReferenceSpace(o),Ge.setContext(i),Ge.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return y.getDepthTexture()};function V(Z){for(let ne=0;ne<Z.removed.length;ne++){let fe=Z.removed[ne],de=w.indexOf(fe);if(de>=0)w[de]=null,v[de].disconnect(fe)}for(let ne=0;ne<Z.added.length;ne++){let fe=Z.added[ne],de=w.indexOf(fe);if(de===-1){for(let Ze=0;Ze<v.length;Ze++)if(Ze>=w.length){w.push(fe),de=Ze;break}else if(w[Ze]===null){w[Ze]=fe,de=Ze;break}if(de===-1)break}let Re=v[de];if(Re)Re.connect(fe)}}let U=new N,K=new N;function Q(Z,ne,fe){U.setFromMatrixPosition(ne.matrixWorld),K.setFromMatrixPosition(fe.matrixWorld);let de=U.distanceTo(K),Re=ne.projectionMatrix.elements,Ze=fe.projectionMatrix.elements,Oe=Re[14]/(Re[10]-1),ke=Re[14]/(Re[10]+1),Ke=(Re[9]+1)/Re[5],Ye=(Re[9]-1)/Re[5],Je=(Re[8]-1)/Re[0],Ft=(Ze[8]+1)/Ze[0],gn=Oe*Je,mt=Oe*Ft,Ht=de/(-Je+Ft),zt=Ht*-Je;if(ne.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(zt),Z.translateZ(Ht),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),Re[10]===-1)Z.projectionMatrix.copy(ne.projectionMatrix),Z.projectionMatrixInverse.copy(ne.projectionMatrixInverse);else{let Pt=Oe+Ht,L=ke+Ht,_n=gn-zt,nt=mt+(de-zt),gt=Ke*ke/L*Pt,M=Ye*ke/L*Pt;Z.projectionMatrix.makePerspective(_n,nt,gt,M,Pt,L),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function se(Z,ne){if(ne===null)Z.matrixWorld.copy(Z.matrix);else Z.matrixWorld.multiplyMatrices(ne.matrixWorld,Z.matrix);Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(i===null)return;let{near:ne,far:fe}=Z;if(y.texture!==null){if(y.depthNear>0)ne=y.depthNear;if(y.depthFar>0)fe=y.depthFar}if(C.near=S.near=_.near=ne,C.far=S.far=_.far=fe,z!==C.near||J!==C.far)i.updateRenderState({depthNear:C.near,depthFar:C.far}),z=C.near,J=C.far;C.layers.mask=Z.layers.mask|6,_.layers.mask=C.layers.mask&-5,S.layers.mask=C.layers.mask&-3;let de=Z.parent,Re=C.cameras;se(C,de);for(let Ze=0;Ze<Re.length;Ze++)se(Re[Ze],de);if(Re.length===2)Q(C,_,S);else C.projectionMatrix.copy(_.projectionMatrix);me(Z,C,de)};function me(Z,ne,fe){if(fe===null)Z.matrix.copy(ne.matrixWorld);else Z.matrix.copy(fe.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(ne.matrixWorld);if(Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(ne.projectionMatrix),Z.projectionMatrixInverse.copy(ne.projectionMatrixInverse),Z.isPerspectiveCamera)Z.fov=cr*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1}this.getCamera=function(){return C},this.getFoveation=function(){if(f===null&&h===null)return;return a},this.setFoveation=function(Z){if(a=Z,f!==null)f.fixedFoveation=Z;if(h!==null&&h.fixedFoveation!==void 0)h.fixedFoveation=Z},this.hasDepthSensing=function(){return y.texture!==null},this.getDepthSensingMesh=function(){return y.getMesh(C)},this.getCameraTexture=function(Z){return p[Z]};let _e=null;function qe(Z,ne){if(l=ne.getViewerPose(c||s),d=ne,l!==null){let fe=l.views;if(h!==null)e.setRenderTargetFramebuffer(T,h.framebuffer),e.setRenderTarget(T);let de=!1;if(fe.length!==C.cameras.length)C.cameras.length=0,de=!0;for(let ke=0;ke<fe.length;ke++){let Ke=fe[ke],Ye=null;if(h!==null)Ye=h.getViewport(Ke);else{let Ft=u.getViewSubImage(f,Ke);if(Ye=Ft.viewport,ke===0)e.setRenderTargetTextures(T,Ft.colorTexture,Ft.depthStencilTexture),e.setRenderTarget(T)}let Je=F[ke];if(Je===void 0)Je=new Lt,Je.layers.enable(ke),Je.viewport=new st,F[ke]=Je;if(Je.matrix.fromArray(Ke.transform.matrix),Je.matrix.decompose(Je.position,Je.quaternion,Je.scale),Je.projectionMatrix.fromArray(Ke.projectionMatrix),Je.projectionMatrixInverse.copy(Je.projectionMatrix).invert(),Je.viewport.set(Ye.x,Ye.y,Ye.width,Ye.height),ke===0)C.matrix.copy(Je.matrix),C.matrix.decompose(C.position,C.quaternion,C.scale);if(de===!0)C.cameras.push(Je)}let Re=i.enabledFeatures;if(Re&&Re.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&g){u=n.getBinding();let ke=u.getDepthInformation(fe[0]);if(ke&&ke.isValid&&ke.texture)y.init(ke,i.renderState)}if(Re&&Re.includes("camera-access")&&g){e.state.unbindTexture(),u=n.getBinding();for(let ke=0;ke<fe.length;ke++){let Ke=fe[ke].camera;if(Ke){let Ye=p[Ke];if(!Ye)Ye=new Fa,p[Ke]=Ye;let Je=u.getCameraImage(Ke);Ye.sourceTexture=Je}}}}for(let fe=0;fe<v.length;fe++){let de=w[fe],Re=v[fe];if(de!==null&&Re!==void 0)Re.update(de,ne,c||s)}if(_e)_e(Z,ne);if(ne.detectedPlanes)n.dispatchEvent({type:"planesdetected",data:ne});d=null}let Ge=new $_;Ge.setAnimationLoop(qe),this.setAnimationLoop=function(Z){_e=Z},this.dispose=function(){}}}var NT=new ze,r0=new Ue;r0.set(-1,0,0,0,1,0,0,0,1);function DT(e,t){function n(p,m){if(p.matrixAutoUpdate===!0)p.updateMatrix();m.value.copy(p.matrix)}function i(p,m){if(m.color.getRGB(p.fogColor.value,Au(e)),m.isFog)p.fogNear.value=m.near,p.fogFar.value=m.far;else if(m.isFogExp2)p.fogDensity.value=m.density}function r(p,m,A,T,v){if(m.isNodeMaterial)m.uniformsNeedUpdate=!1;else if(m.isMeshBasicMaterial)s(p,m);else if(m.isMeshLambertMaterial){if(s(p,m),m.envMap)p.envMapIntensity.value=m.envMapIntensity}else if(m.isMeshToonMaterial)s(p,m),f(p,m);else if(m.isMeshPhongMaterial){if(s(p,m),u(p,m),m.envMap)p.envMapIntensity.value=m.envMapIntensity}else if(m.isMeshStandardMaterial){if(s(p,m),h(p,m),m.isMeshPhysicalMaterial)d(p,m,v)}else if(m.isMeshMatcapMaterial)s(p,m),g(p,m);else if(m.isMeshDepthMaterial)s(p,m);else if(m.isMeshDistanceMaterial)s(p,m),y(p,m);else if(m.isMeshNormalMaterial)s(p,m);else if(m.isLineBasicMaterial){if(o(p,m),m.isLineDashedMaterial)a(p,m)}else if(m.isPointsMaterial)c(p,m,A,T);else if(m.isSpriteMaterial)l(p,m);else if(m.isShadowMaterial)p.color.value.copy(m.color),p.opacity.value=m.opacity;else if(m.isShaderMaterial)m.uniformsNeedUpdate=!1}function s(p,m){if(p.opacity.value=m.opacity,m.color)p.diffuse.value.copy(m.color);if(m.emissive)p.emissive.value.copy(m.emissive).multiplyScalar(m.emissiveIntensity);if(m.map)p.map.value=m.map,n(m.map,p.mapTransform);if(m.alphaMap)p.alphaMap.value=m.alphaMap,n(m.alphaMap,p.alphaMapTransform);if(m.bumpMap){if(p.bumpMap.value=m.bumpMap,n(m.bumpMap,p.bumpMapTransform),p.bumpScale.value=m.bumpScale,m.side===Yt)p.bumpScale.value*=-1}if(m.normalMap){if(p.normalMap.value=m.normalMap,n(m.normalMap,p.normalMapTransform),p.normalScale.value.copy(m.normalScale),m.side===Yt)p.normalScale.value.negate()}if(m.displacementMap)p.displacementMap.value=m.displacementMap,n(m.displacementMap,p.displacementMapTransform),p.displacementScale.value=m.displacementScale,p.displacementBias.value=m.displacementBias;if(m.emissiveMap)p.emissiveMap.value=m.emissiveMap,n(m.emissiveMap,p.emissiveMapTransform);if(m.specularMap)p.specularMap.value=m.specularMap,n(m.specularMap,p.specularMapTransform);if(m.alphaTest>0)p.alphaTest.value=m.alphaTest;let A=t.get(m),{envMap:T,envMapRotation:v}=A;if(T){if(p.envMap.value=T,p.envMapRotation.value.setFromMatrix4(NT.makeRotationFromEuler(v)).transpose(),T.isCubeTexture&&T.isRenderTargetTexture===!1)p.envMapRotation.value.premultiply(r0);p.reflectivity.value=m.reflectivity,p.ior.value=m.ior,p.refractionRatio.value=m.refractionRatio}if(m.lightMap)p.lightMap.value=m.lightMap,p.lightMapIntensity.value=m.lightMapIntensity,n(m.lightMap,p.lightMapTransform);if(m.aoMap)p.aoMap.value=m.aoMap,p.aoMapIntensity.value=m.aoMapIntensity,n(m.aoMap,p.aoMapTransform)}function o(p,m){if(p.diffuse.value.copy(m.color),p.opacity.value=m.opacity,m.map)p.map.value=m.map,n(m.map,p.mapTransform)}function a(p,m){p.dashSize.value=m.dashSize,p.totalSize.value=m.dashSize+m.gapSize,p.scale.value=m.scale}function c(p,m,A,T){if(p.diffuse.value.copy(m.color),p.opacity.value=m.opacity,p.size.value=m.size*A,p.scale.value=T*0.5,m.map)p.map.value=m.map,n(m.map,p.uvTransform);if(m.alphaMap)p.alphaMap.value=m.alphaMap,n(m.alphaMap,p.alphaMapTransform);if(m.alphaTest>0)p.alphaTest.value=m.alphaTest}function l(p,m){if(p.diffuse.value.copy(m.color),p.opacity.value=m.opacity,p.rotation.value=m.rotation,m.map)p.map.value=m.map,n(m.map,p.mapTransform);if(m.alphaMap)p.alphaMap.value=m.alphaMap,n(m.alphaMap,p.alphaMapTransform);if(m.alphaTest>0)p.alphaTest.value=m.alphaTest}function u(p,m){p.specular.value.copy(m.specular),p.shininess.value=Math.max(m.shininess,0.0001)}function f(p,m){if(m.gradientMap)p.gradientMap.value=m.gradientMap}function h(p,m){if(p.metalness.value=m.metalness,m.metalnessMap)p.metalnessMap.value=m.metalnessMap,n(m.metalnessMap,p.metalnessMapTransform);if(p.roughness.value=m.roughness,m.roughnessMap)p.roughnessMap.value=m.roughnessMap,n(m.roughnessMap,p.roughnessMapTransform);if(m.envMap)p.envMapIntensity.value=m.envMapIntensity}function d(p,m,A){if(p.ior.value=m.ior,m.sheen>0){if(p.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),p.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap)p.sheenColorMap.value=m.sheenColorMap,n(m.sheenColorMap,p.sheenColorMapTransform);if(m.sheenRoughnessMap)p.sheenRoughnessMap.value=m.sheenRoughnessMap,n(m.sheenRoughnessMap,p.sheenRoughnessMapTransform)}if(m.clearcoat>0){if(p.clearcoat.value=m.clearcoat,p.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap)p.clearcoatMap.value=m.clearcoatMap,n(m.clearcoatMap,p.clearcoatMapTransform);if(m.clearcoatRoughnessMap)p.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,n(m.clearcoatRoughnessMap,p.clearcoatRoughnessMapTransform);if(m.clearcoatNormalMap){if(p.clearcoatNormalMap.value=m.clearcoatNormalMap,n(m.clearcoatNormalMap,p.clearcoatNormalMapTransform),p.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===Yt)p.clearcoatNormalScale.value.negate()}}if(m.dispersion>0)p.dispersion.value=m.dispersion;if(m.iridescence>0){if(p.iridescence.value=m.iridescence,p.iridescenceIOR.value=m.iridescenceIOR,p.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],p.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap)p.iridescenceMap.value=m.iridescenceMap,n(m.iridescenceMap,p.iridescenceMapTransform);if(m.iridescenceThicknessMap)p.iridescenceThicknessMap.value=m.iridescenceThicknessMap,n(m.iridescenceThicknessMap,p.iridescenceThicknessMapTransform)}if(m.transmission>0){if(p.transmission.value=m.transmission,p.transmissionSamplerMap.value=A.texture,p.transmissionSamplerSize.value.set(A.width,A.height),m.transmissionMap)p.transmissionMap.value=m.transmissionMap,n(m.transmissionMap,p.transmissionMapTransform);if(p.thickness.value=m.thickness,m.thicknessMap)p.thicknessMap.value=m.thicknessMap,n(m.thicknessMap,p.thicknessMapTransform);p.attenuationDistance.value=m.attenuationDistance,p.attenuationColor.value.copy(m.attenuationColor)}if(m.anisotropy>0){if(p.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap)p.anisotropyMap.value=m.anisotropyMap,n(m.anisotropyMap,p.anisotropyMapTransform)}if(p.specularIntensity.value=m.specularIntensity,p.specularColor.value.copy(m.specularColor),m.specularColorMap)p.specularColorMap.value=m.specularColorMap,n(m.specularColorMap,p.specularColorMapTransform);if(m.specularIntensityMap)p.specularIntensityMap.value=m.specularIntensityMap,n(m.specularIntensityMap,p.specularIntensityMapTransform)}function g(p,m){if(m.matcap)p.matcap.value=m.matcap}function y(p,m){let A=t.get(m).light;p.referencePosition.value.setFromMatrixPosition(A.matrixWorld),p.nearDistance.value=A.shadow.camera.near,p.farDistance.value=A.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:r}}function UT(e,t,n,i){let r={},s={},o=[],a=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(v,w){let E=w.program;i.uniformBlockBinding(v,E)}function l(v,w){let E=r[v.id];if(E===void 0)p(v),E=u(v),r[v.id]=E,v.addEventListener("dispose",A);let R=w.program;i.updateUBOMapping(v,R);let _=t.render.frame;if(s[v.id]!==_)h(v),s[v.id]=_}function u(v){let w=f();v.__bindingPointIndex=w;let E=e.createBuffer(),{__size:R,usage:_}=v;return e.bindBuffer(e.UNIFORM_BUFFER,E),e.bufferData(e.UNIFORM_BUFFER,R,_),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,w,E),E}function f(){for(let v=0;v<a;v++)if(o.indexOf(v)===-1)return o.push(v),v;return Ne("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(v){let w=r[v.id],{uniforms:E,__cache:R}=v;e.bindBuffer(e.UNIFORM_BUFFER,w);for(let _=0,S=E.length;_<S;_++){let F=E[_];if(Array.isArray(F))for(let C=0,z=F.length;C<z;C++)d(F[C],_,C,R);else d(F,_,0,R)}e.bindBuffer(e.UNIFORM_BUFFER,null)}function d(v,w,E,R){if(y(v,w,E,R)===!0){let{__offset:_,value:S}=v;if(Array.isArray(S)){let F=0;for(let C=0;C<S.length;C++){let z=S[C],J=m(z);if(g(z,v.__data,F),typeof z!=="number"&&typeof z!=="boolean"&&!z.isMatrix3&&!ArrayBuffer.isView(z))F+=J.storage/Float32Array.BYTES_PER_ELEMENT}}else g(S,v.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,_,v.__data)}}function g(v,w,E){if(typeof v==="number"||typeof v==="boolean")w[0]=v;else if(v.isMatrix3)w[0]=v.elements[0],w[1]=v.elements[1],w[2]=v.elements[2],w[3]=0,w[4]=v.elements[3],w[5]=v.elements[4],w[6]=v.elements[5],w[7]=0,w[8]=v.elements[6],w[9]=v.elements[7],w[10]=v.elements[8],w[11]=0;else if(ArrayBuffer.isView(v))w.set(new v.constructor(v.buffer,v.byteOffset,w.length));else v.toArray(w,E)}function y(v,w,E,R){let _=v.value,S=w+"_"+E;if(R[S]===void 0){if(typeof _==="number"||typeof _==="boolean")R[S]=_;else if(ArrayBuffer.isView(_))R[S]=_.slice();else R[S]=_.clone();return!0}else{let F=R[S];if(typeof _==="number"||typeof _==="boolean"){if(F!==_)return R[S]=_,!0}else if(ArrayBuffer.isView(_))return!0;else if(F.equals(_)===!1)return F.copy(_),!0}return!1}function p(v){let w=v.uniforms,E=0,R=16;for(let S=0,F=w.length;S<F;S++){let C=Array.isArray(w[S])?w[S]:[w[S]];for(let z=0,J=C.length;z<J;z++){let O=C[z],H=Array.isArray(O.value)?O.value:[O.value];for(let V=0,U=H.length;V<U;V++){let K=H[V],Q=m(K),se=E%R,me=se%Q.boundary,_e=se+me;if(E+=me,_e!==0&&R-_e<Q.storage)E+=R-_e;O.__data=new Float32Array(Q.storage/Float32Array.BYTES_PER_ELEMENT),O.__offset=E,E+=Q.storage}}}let _=E%R;if(_>0)E+=R-_;return v.__size=E,v.__cache={},this}function m(v){let w={boundary:0,storage:0};if(typeof v==="number"||typeof v==="boolean")w.boundary=4,w.storage=4;else if(v.isVector2)w.boundary=8,w.storage=8;else if(v.isVector3||v.isColor)w.boundary=16,w.storage=12;else if(v.isVector4)w.boundary=16,w.storage=16;else if(v.isMatrix3)w.boundary=48,w.storage=48;else if(v.isMatrix4)w.boundary=64,w.storage=64;else if(v.isTexture)Me("WebGLRenderer: Texture samplers can not be part of an uniforms group.");else if(ArrayBuffer.isView(v))w.boundary=16,w.storage=v.byteLength;else Me("WebGLRenderer: Unsupported uniform value type.",v);return w}function A(v){let w=v.target;w.removeEventListener("dispose",A);let E=o.indexOf(w.__bindingPointIndex);o.splice(E,1),e.deleteBuffer(r[w.id]),delete r[w.id],delete s[w.id]}function T(){for(let v in r)e.deleteBuffer(r[v]);o=[],r={},s={}}return{bind:c,update:l,dispose:T}}var OT=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]),Qn=null;function FT(){if(Qn===null)Qn=new js(OT,16,16,pr,pi),Qn.name="DFG_LUT",Qn.minFilter=Gt,Qn.magFilter=Gt,Qn.wrapS=jr,Qn.wrapT=jr,Qn.generateMipmaps=!1,Qn.needsUpdate=!0;return Qn}class Qu{constructor(e={}){let{canvas:t=h_(),context:n=null,depth:i=!0,stencil:r=!1,alpha:s=!1,antialias:o=!1,premultipliedAlpha:a=!0,preserveDrawingBuffer:c=!1,powerPreference:l="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:f=!1,outputBufferType:h=Fn}=e;this.isWebGLRenderer=!0;let d;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=n.getContextAttributes().alpha}else d=s;let g=h,y=new Set([kl,zl,Fl]),p=new Set([Fn,Oi,Vs,Kr,Ul,Ol]),m=new Uint32Array(4),A=new Int32Array(4),T=new N,v=null,w=null,E=[],R=[],_=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=Un,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let S=this,F=!1,C=null,z=null,J=null,O=null;this._outputColorSpace=Fi;let H=0,V=0,U=null,K=-1,Q=null,se=new st,me=new st,_e=null,qe=new Le(0),Ge=0,{width:Z,height:ne}=t,fe=1,de=null,Re=null,Ze=new st(0,0,Z,ne),Oe=new st(0,0,Z,ne),ke=!1,Ke=new Ks,Ye=!1,Je=!1,Ft=new ze,gn=new N,mt=new st,Ht={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},zt=!1;function Pt(){return U===null?fe:1}let L=n;function _n(b,D){return t.getContext(b,D)}try{let b={alpha:!0,depth:i,stencil:r,antialias:o,premultipliedAlpha:a,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if("setAttribute"in t)t.setAttribute("data-engine",`three.js r${_g}`);if(t.addEventListener("webglcontextlost",Fe,!1),t.addEventListener("webglcontextrestored",St,!1),t.addEventListener("webglcontextcreationerror",ft,!1),L===null){if(L=_n("webgl2",b),L===null)if(_n("webgl2"))throw Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.");else throw Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(b){throw Ne("WebGLRenderer: "+b.message),b}let nt,gt,M,x,I,W,te,ie,le,X,j,xe,we,ue,re,Ce,Pe,et,P,oe,Y,ae,ve;function ee(){if(nt=new WM(L),nt.init(),Y=new IT(L,nt),gt=new OM(L,nt,e,Y),M=new RT(L,nt),gt.reversedDepthBuffer&&f)M.buffers.depth.setReversed(!0);z=L.createFramebuffer(),J=L.createFramebuffer(),O=L.createFramebuffer(),x=new XM(L),I=new pT,W=new CT(L,nt,M,I,gt,Y,x),te=new VM(S),ie=new Jy(L),ae=new DM(L,ie),le=new $M(L,ie,x,ae),X=new YM(L,le,ie,ae,x),et=new qM(L,gt,W),re=new FM(I),j=new dT(S,te,nt,gt,ae,re),xe=new DT(S,I),we=new gT,ue=new ST(nt),Pe=new NM(S,te,M,X,d,a),Ce=new AT(S,X,gt),ve=new UT(L,x,gt,M),P=new UM(L,nt,x),oe=new ZM(L,nt,x),x.programs=j.programs,S.capabilities=gt,S.extensions=nt,S.properties=I,S.renderLists=we,S.shadowMap=Ce,S.state=M,S.info=x}if(ee(),g!==Fn)_=new JM(g,t.width,t.height,o,i,r);let ce=new i0(S,L);this.xr=ce,this.getContext=function(){return L},this.getContextAttributes=function(){return L.getContextAttributes()},this.forceContextLoss=function(){let b=nt.get("WEBGL_lose_context");if(b)b.loseContext()},this.forceContextRestore=function(){let b=nt.get("WEBGL_lose_context");if(b)b.restoreContext()},this.getPixelRatio=function(){return fe},this.setPixelRatio=function(b){if(b===void 0)return;fe=b,this.setSize(Z,ne,!1)},this.getSize=function(b){return b.set(Z,ne)},this.setSize=function(b,D,G=!0){if(ce.isPresenting){Me("WebGLRenderer: Can't change size while VR device is presenting.");return}if(Z=b,ne=D,t.width=Math.floor(b*fe),t.height=Math.floor(D*fe),G===!0)t.style.width=b+"px",t.style.height=D+"px";if(_!==null)_.setSize(t.width,t.height);this.setViewport(0,0,b,D)},this.getDrawingBufferSize=function(b){return b.set(Z*fe,ne*fe).floor()},this.setDrawingBufferSize=function(b,D,G){Z=b,ne=D,fe=G,t.width=Math.floor(b*G),t.height=Math.floor(D*G),this.setViewport(0,0,b,D)},this.setEffects=function(b){if(g===Fn){Ne("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(b){for(let D=0;D<b.length;D++)if(b[D].isOutputPass===!0){Me("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}_.setEffects(b||[])},this.getCurrentViewport=function(b){return b.copy(se)},this.getViewport=function(b){return b.copy(Ze)},this.setViewport=function(b,D,G,k){if(b.isVector4)Ze.set(b.x,b.y,b.z,b.w);else Ze.set(b,D,G,k);M.viewport(se.copy(Ze).multiplyScalar(fe).round())},this.getScissor=function(b){return b.copy(Oe)},this.setScissor=function(b,D,G,k){if(b.isVector4)Oe.set(b.x,b.y,b.z,b.w);else Oe.set(b,D,G,k);M.scissor(me.copy(Oe).multiplyScalar(fe).round())},this.getScissorTest=function(){return ke},this.setScissorTest=function(b){M.setScissorTest(ke=b)},this.setOpaqueSort=function(b){de=b},this.setTransparentSort=function(b){Re=b},this.getClearColor=function(b){return b.copy(Pe.getClearColor())},this.setClearColor=function(){Pe.setClearColor(...arguments)},this.getClearAlpha=function(){return Pe.getClearAlpha()},this.setClearAlpha=function(){Pe.setClearAlpha(...arguments)},this.clear=function(b=!0,D=!0,G=!0){let k=0;if(b){let B=!1;if(U!==null){let ge=U.texture.format;B=y.has(ge)}if(B){let ge=U.texture.type,be=p.has(ge),pe=Pe.getClearColor(),Se=Pe.getClearAlpha(),{r:Ee,g:Be,b:Ve}=pe;if(be)m[0]=Ee,m[1]=Be,m[2]=Ve,m[3]=Se,L.clearBufferuiv(L.COLOR,0,m);else A[0]=Ee,A[1]=Be,A[2]=Ve,A[3]=Se,L.clearBufferiv(L.COLOR,0,A)}else k|=L.COLOR_BUFFER_BIT}if(D)k|=L.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0);if(G)k|=L.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295);if(k!==0)L.clear(k)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(b){b.setRenderer(this),C=b},this.dispose=function(){t.removeEventListener("webglcontextlost",Fe,!1),t.removeEventListener("webglcontextrestored",St,!1),t.removeEventListener("webglcontextcreationerror",ft,!1),Pe.dispose(),we.dispose(),ue.dispose(),I.dispose(),te.dispose(),X.dispose(),ae.dispose(),ve.dispose(),j.dispose(),ce.dispose(),ce.removeEventListener("sessionstart",_h),ce.removeEventListener("sessionend",xh),ji.stop()};function Fe(b){b.preventDefault(),zs("WebGLRenderer: Context Lost."),F=!0}function St(){zs("WebGLRenderer: Context Restored."),F=!1;let b=x.autoReset,D=Ce.enabled,G=Ce.autoUpdate,k=Ce.needsUpdate,B=Ce.type;ee(),x.autoReset=b,Ce.enabled=D,Ce.autoUpdate=G,Ce.needsUpdate=k,Ce.type=B}function ft(b){Ne("WebGLRenderer: A WebGL context could not be created. Reason: ",b.statusMessage)}function kn(b){let D=b.target;D.removeEventListener("dispose",kn),ni(D)}function ni(b){X0(b),I.remove(b)}function X0(b){let D=I.get(b).programs;if(D!==void 0){if(D.forEach(function(G){j.releaseProgram(G)}),b.isShaderMaterial)j.releaseShaderCache(b)}}this.renderBufferDirect=function(b,D,G,k,B,ge){if(D===null)D=Ht;let be=B.isMesh&&B.matrixWorld.determinantAffine()<0,pe=j0(b,D,G,k,B);M.setMaterial(k,be);let Se=G.index,Ee=1;if(k.wireframe===!0){if(Se=le.getWireframeAttribute(G),Se===void 0)return;Ee=2}let Be=G.drawRange,Ve=G.attributes.position,Ae=Be.start*Ee,ot=(Be.start+Be.count)*Ee;if(ge!==null)Ae=Math.max(Ae,ge.start*Ee),ot=Math.min(ot,(ge.start+ge.count)*Ee);if(Se!==null)Ae=Math.max(Ae,0),ot=Math.min(ot,Se.count);else if(Ve!==void 0&&Ve!==null)Ae=Math.max(Ae,0),ot=Math.min(ot,Ve.count);let Tt=ot-Ae;if(Tt<0||Tt===1/0)return;ae.setup(B,k,pe,G,Se);let Mt,lt=P;if(Se!==null)Mt=ie.get(Se),lt=oe,lt.setIndex(Mt);if(B.isMesh)if(k.wireframe===!0)M.setLineWidth(k.wireframeLinewidth*Pt()),lt.setMode(L.LINES);else lt.setMode(L.TRIANGLES);else if(B.isLine){let $t=k.linewidth;if($t===void 0)$t=1;if(M.setLineWidth($t*Pt()),B.isLineSegments)lt.setMode(L.LINES);else if(B.isLineLoop)lt.setMode(L.LINE_LOOP);else lt.setMode(L.LINE_STRIP)}else if(B.isPoints)lt.setMode(L.POINTS);else if(B.isSprite)lt.setMode(L.TRIANGLES);if(B.isBatchedMesh)if(!nt.get("WEBGL_multi_draw")){let{_multiDrawStarts:$t,_multiDrawCounts:ye,_multiDrawCount:on}=B,Qe=Se?ie.get(Se).bytesPerElement:1,xn=I.get(k).currentProgram.getUniforms();for(let Bn=0;Bn<on;Bn++)xn.setValue(L,"_gl_DrawID",Bn),lt.render($t[Bn]/Qe,ye[Bn])}else lt.renderMultiDraw(B._multiDrawStarts,B._multiDrawCounts,B._multiDrawCount);else if(B.isInstancedMesh)lt.renderInstances(Ae,Tt,B.count);else if(G.isInstancedBufferGeometry){let $t=G._maxInstanceCount!==void 0?G._maxInstanceCount:1/0,ye=Math.min(G.instanceCount,$t);lt.renderInstances(Ae,Tt,ye)}else lt.render(Ae,Tt)};function gh(b,D,G){if(b.transparent===!0&&b.side===bn&&b.forceSinglePass===!1)b.side=Yt,b.needsUpdate=!0,xo(b,D,G),b.side=Ui,b.needsUpdate=!0,xo(b,D,G),b.side=bn;else xo(b,D,G)}this.compile=function(b,D,G=null){if(G===null)G=b;if(w=ue.get(G),w.init(D),R.push(w),G.traverseVisible(function(B){if(B.isLight&&B.layers.test(D.layers)){if(w.pushLight(B),B.castShadow)w.pushShadow(B)}}),b!==G)b.traverseVisible(function(B){if(B.isLight&&B.layers.test(D.layers)){if(w.pushLight(B),B.castShadow)w.pushShadow(B)}});w.setupLights();let k=new Set;return b.traverse(function(B){if(!(B.isMesh||B.isPoints||B.isLine||B.isSprite))return;let ge=B.material;if(ge)if(Array.isArray(ge))for(let be=0;be<ge.length;be++){let pe=ge[be];gh(pe,G,B),k.add(pe)}else gh(ge,G,B),k.add(ge)}),w=R.pop(),k},this.compileAsync=function(b,D,G=null){let k=this.compile(b,D,G);return new Promise((B)=>{function ge(){if(k.forEach(function(be){if(I.get(be).currentProgram.isReady())k.delete(be)}),k.size===0){B(b);return}setTimeout(ge,10)}if(nt.get("KHR_parallel_shader_compile")!==null)ge();else setTimeout(ge,10)})};let nc=null;function q0(b){if(nc)nc(b)}function _h(){ji.stop()}function xh(){ji.start()}let ji=new $_;if(ji.setAnimationLoop(q0),typeof self<"u")ji.setContext(self);this.setAnimationLoop=function(b){nc=b,ce.setAnimationLoop(b),b===null?ji.stop():ji.start()},ce.addEventListener("sessionstart",_h),ce.addEventListener("sessionend",xh),this.render=function(b,D){if(D!==void 0&&D.isCamera!==!0){Ne("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(F===!0)return;if(C!==null)C.renderStart(b,D);let G=ce.enabled===!0&&ce.isPresenting===!0,k=_!==null&&(U===null||G)&&_.begin(S,U);if(b.matrixWorldAutoUpdate===!0)b.updateMatrixWorld();if(D.parent===null&&D.matrixWorldAutoUpdate===!0)D.updateMatrixWorld();if(ce.enabled===!0&&ce.isPresenting===!0&&(_===null||_.isCompositing()===!1)){if(ce.cameraAutoUpdate===!0)ce.updateCamera(D);D=ce.getCamera()}if(b.isScene===!0)b.onBeforeRender(S,b,D,U);if(w=ue.get(b,R.length),w.init(D),w.state.textureUnits=W.getTextureUnits(),R.push(w),Ft.multiplyMatrices(D.projectionMatrix,D.matrixWorldInverse),Ke.setFromProjectionMatrix(Ft,bu,D.reversedDepth),Je=this.localClippingEnabled,Ye=re.init(this.clippingPlanes,Je),v=we.get(b,E.length),v.init(),E.push(v),ce.enabled===!0&&ce.isPresenting===!0){let be=S.xr.getDepthSensingMesh();if(be!==null)ic(be,D,-1/0,S.sortObjects)}if(ic(b,D,0,S.sortObjects),v.finish(),S.sortObjects===!0)v.sort(de,Re,D.reversedDepth);if(zt=ce.enabled===!1||ce.isPresenting===!1||ce.hasDepthSensing()===!1,zt)Pe.addToRenderList(v,b);if(this.info.render.frame++,this.info.autoReset===!0)this.info.reset();if(Ye===!0)re.beginShadows();let B=w.state.shadowsArray;if(Ce.render(B,b,D),Ye===!0)re.endShadows();if((k&&_.hasRenderPass())===!1){let be=v.opaque,pe=v.transmissive;if(w.setupLights(),D.isArrayCamera){let Se=D.cameras;if(pe.length>0)for(let Ee=0,Be=Se.length;Ee<Be;Ee++){let Ve=Se[Ee];yh(be,pe,b,Ve)}if(zt)Pe.render(b);for(let Ee=0,Be=Se.length;Ee<Be;Ee++){let Ve=Se[Ee];vh(v,b,Ve,Ve.viewport)}}else{if(pe.length>0)yh(be,pe,b,D);if(zt)Pe.render(b);vh(v,b,D)}}if(U!==null&&V===0)W.updateMultisampleRenderTarget(U),W.updateRenderTargetMipmap(U);if(k)_.end(S);if(b.isScene===!0)b.onAfterRender(S,b,D);if(ae.resetDefaultState(),K=-1,Q=null,R.pop(),R.length>0){if(w=R[R.length-1],W.setTextureUnits(w.state.textureUnits),Ye===!0)re.setGlobalState(S.clippingPlanes,w.state.camera)}else w=null;if(E.pop(),E.length>0)v=E[E.length-1];else v=null;if(C!==null)C.renderEnd()};function ic(b,D,G,k){if(b.visible===!1)return;if(b.layers.test(D.layers)){if(b.isGroup)G=b.renderOrder;else if(b.isLOD){if(b.autoUpdate===!0)b.update(D)}else if(b.isLightProbeGrid)w.pushLightProbeGrid(b);else if(b.isLight){if(w.pushLight(b),b.castShadow)w.pushShadow(b)}else if(b.isSprite){if(!b.frustumCulled||Ke.intersectsSprite(b)){if(k)mt.setFromMatrixPosition(b.matrixWorld).applyMatrix4(Ft);let be=X.update(b),pe=b.material;if(pe.visible)v.push(b,be,pe,G,mt.z,null)}}else if(b.isMesh||b.isLine||b.isPoints){if(!b.frustumCulled||Ke.intersectsObject(b)){let be=X.update(b),pe=b.material;if(k){if(b.boundingSphere!==void 0){if(b.boundingSphere===null)b.computeBoundingSphere();mt.copy(b.boundingSphere.center)}else{if(be.boundingSphere===null)be.computeBoundingSphere();mt.copy(be.boundingSphere.center)}mt.applyMatrix4(b.matrixWorld).applyMatrix4(Ft)}if(Array.isArray(pe)){let Se=be.groups;for(let Ee=0,Be=Se.length;Ee<Be;Ee++){let Ve=Se[Ee],Ae=pe[Ve.materialIndex];if(Ae&&Ae.visible)v.push(b,be,Ae,G,mt.z,Ve)}}else if(pe.visible)v.push(b,be,pe,G,mt.z,null)}}}let ge=b.children;for(let be=0,pe=ge.length;be<pe;be++)ic(ge[be],D,G,k)}function vh(b,D,G,k){let{opaque:B,transmissive:ge,transparent:be}=b;if(w.setupLightsView(G),Ye===!0)re.setGlobalState(S.clippingPlanes,G);if(k)M.viewport(se.copy(k));if(B.length>0)_o(B,D,G);if(ge.length>0)_o(ge,D,G);if(be.length>0)_o(be,D,G);M.buffers.depth.setTest(!0),M.buffers.depth.setMask(!0),M.buffers.color.setMask(!0),M.setPolygonOffset(!1)}function yh(b,D,G,k){if((G.isScene===!0?G.overrideMaterial:null)!==null)return;if(w.state.transmissionRenderTarget[k.id]===void 0){let Ae=nt.has("EXT_color_buffer_half_float")||nt.has("EXT_color_buffer_float");w.state.transmissionRenderTarget[k.id]=new Sn(1,1,{generateMipmaps:!0,type:Ae?pi:Fn,minFilter:jn,samples:Math.max(4,gt.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:We.workingColorSpace})}let ge=w.state.transmissionRenderTarget[k.id],be=k.viewport||se;ge.setSize(be.z*S.transmissionResolutionScale,be.w*S.transmissionResolutionScale);let pe=S.getRenderTarget(),Se=S.getActiveCubeFace(),Ee=S.getActiveMipmapLevel();if(S.setRenderTarget(ge),S.getClearColor(qe),Ge=S.getClearAlpha(),Ge<1)S.setClearColor(16777215,0.5);if(S.clear(),zt)Pe.render(G);let Be=S.toneMapping;S.toneMapping=Un;let Ve=k.viewport;if(k.viewport!==void 0)k.viewport=void 0;if(w.setupLightsView(k),Ye===!0)re.setGlobalState(S.clippingPlanes,k);if(_o(b,G,k),W.updateMultisampleRenderTarget(ge),W.updateRenderTargetMipmap(ge),nt.has("WEBGL_multisampled_render_to_texture")===!1){let Ae=!1;for(let ot=0,Tt=D.length;ot<Tt;ot++){let Mt=D[ot],{object:lt,geometry:$t,material:ye,group:on}=Mt;if(ye.side===bn&<.layers.test(k.layers)){let Qe=ye.side;ye.side=Yt,ye.needsUpdate=!0,bh(lt,G,k,$t,ye,on),ye.side=Qe,ye.needsUpdate=!0,Ae=!0}}if(Ae===!0)W.updateMultisampleRenderTarget(ge),W.updateRenderTargetMipmap(ge)}if(S.setRenderTarget(pe,Se,Ee),S.setClearColor(qe,Ge),Ve!==void 0)k.viewport=Ve;S.toneMapping=Be}function _o(b,D,G){let k=D.isScene===!0?D.overrideMaterial:null;for(let B=0,ge=b.length;B<ge;B++){let be=b[B],{object:pe,geometry:Se,group:Ee}=be,Be=be.material;if(Be.allowOverride===!0&&k!==null)Be=k;if(pe.layers.test(G.layers))bh(pe,D,G,Se,Be,Ee)}}function bh(b,D,G,k,B,ge){if(b.onBeforeRender(S,D,G,k,B,ge),b.modelViewMatrix.multiplyMatrices(G.matrixWorldInverse,b.matrixWorld),b.normalMatrix.getNormalMatrix(b.modelViewMatrix),B.onBeforeRender(S,D,G,k,b,ge),B.transparent===!0&&B.side===bn&&B.forceSinglePass===!1)B.side=Yt,B.needsUpdate=!0,S.renderBufferDirect(G,D,k,B,b,ge),B.side=Ui,B.needsUpdate=!0,S.renderBufferDirect(G,D,k,B,b,ge),B.side=bn;else S.renderBufferDirect(G,D,k,B,b,ge);b.onAfterRender(S,D,G,k,B,ge)}function xo(b,D,G){if(D.isScene!==!0)D=Ht;let k=I.get(b),B=w.state.lights,ge=w.state.shadowsArray,be=B.state.version,pe=j.getParameters(b,B.state,ge,D,G,w.state.lightProbeGridArray),Se=j.getProgramCacheKey(pe),Ee=k.programs;k.environment=b.isMeshStandardMaterial||b.isMeshLambertMaterial||b.isMeshPhongMaterial?D.environment:null,k.fog=D.fog;let Be=b.isMeshStandardMaterial||b.isMeshLambertMaterial&&!b.envMap||b.isMeshPhongMaterial&&!b.envMap;if(k.envMap=te.get(b.envMap||k.environment,Be),k.envMapRotation=k.environment!==null&&b.envMap===null?D.environmentRotation:b.envMapRotation,Ee===void 0)b.addEventListener("dispose",kn),Ee=new Map,k.programs=Ee;let Ve=Ee.get(Se);if(Ve!==void 0){if(k.currentProgram===Ve&&k.lightsStateVersion===be)return Mh(b,pe),Ve}else{if(pe.uniforms=j.getUniforms(b),C!==null&&b.isNodeMaterial)C.build(b,G,pe);b.onBeforeCompile(pe,S),Ve=j.acquireProgram(pe,Se),Ee.set(Se,Ve),k.uniforms=pe.uniforms}let Ae=k.uniforms;if(!b.isShaderMaterial&&!b.isRawShaderMaterial||b.clipping===!0)Ae.clippingPlanes=re.uniform;if(Mh(b,pe),k.needsLights=K0(b),k.lightsStateVersion=be,k.needsLights)Ae.ambientLightColor.value=B.state.ambient,Ae.lightProbe.value=B.state.probe,Ae.directionalLights.value=B.state.directional,Ae.directionalLightShadows.value=B.state.directionalShadow,Ae.spotLights.value=B.state.spot,Ae.spotLightShadows.value=B.state.spotShadow,Ae.rectAreaLights.value=B.state.rectArea,Ae.ltc_1.value=B.state.rectAreaLTC1,Ae.ltc_2.value=B.state.rectAreaLTC2,Ae.pointLights.value=B.state.point,Ae.pointLightShadows.value=B.state.pointShadow,Ae.hemisphereLights.value=B.state.hemi,Ae.directionalShadowMatrix.value=B.state.directionalShadowMatrix,Ae.spotLightMatrix.value=B.state.spotLightMatrix,Ae.spotLightMap.value=B.state.spotLightMap,Ae.pointShadowMatrix.value=B.state.pointShadowMatrix;return k.lightProbeGrid=w.state.lightProbeGridArray.length>0,k.currentProgram=Ve,k.uniformsList=null,Ve}function Sh(b){if(b.uniformsList===null){let D=b.currentProgram.getUniforms();b.uniformsList=co.seqWithValue(D.seq,b.uniforms)}return b.uniformsList}function Mh(b,D){let G=I.get(b);G.outputColorSpace=D.outputColorSpace,G.batching=D.batching,G.batchingColor=D.batchingColor,G.instancing=D.instancing,G.instancingColor=D.instancingColor,G.instancingMorph=D.instancingMorph,G.skinning=D.skinning,G.morphTargets=D.morphTargets,G.morphNormals=D.morphNormals,G.morphColors=D.morphColors,G.morphTargetsCount=D.morphTargetsCount,G.numClippingPlanes=D.numClippingPlanes,G.numIntersection=D.numClipIntersection,G.vertexAlphas=D.vertexAlphas,G.vertexTangents=D.vertexTangents,G.toneMapping=D.toneMapping}function Y0(b,D){if(b.length===0)return null;if(b.length===1)return b[0].texture!==null?b[0]:null;T.setFromMatrixPosition(D.matrixWorld);for(let G=0,k=b.length;G<k;G++){let B=b[G];if(B.texture!==null&&B.boundingBox.containsPoint(T))return B}return null}function j0(b,D,G,k,B){if(D.isScene!==!0)D=Ht;W.resetTextureUnits();let ge=D.fog,be=k.isMeshStandardMaterial||k.isMeshLambertMaterial||k.isMeshPhongMaterial?D.environment:null,pe=U===null?S.outputColorSpace:U.isXRRenderTarget===!0?U.texture.colorSpace:We.workingColorSpace,Se=k.isMeshStandardMaterial||k.isMeshLambertMaterial&&!k.envMap||k.isMeshPhongMaterial&&!k.envMap,Ee=te.get(k.envMap||be,Se),Be=k.vertexColors===!0&&!!G.attributes.color&&G.attributes.color.itemSize===4,Ve=!!G.attributes.tangent&&(!!k.normalMap||k.anisotropy>0),Ae=!!G.morphAttributes.position,ot=!!G.morphAttributes.normal,Tt=!!G.morphAttributes.color,Mt=Un;if(k.toneMapped){if(U===null||U.isXRRenderTarget===!0)Mt=S.toneMapping}let lt=G.morphAttributes.position||G.morphAttributes.normal||G.morphAttributes.color,$t=lt!==void 0?lt.length:0,ye=I.get(k),on=w.state.lights;if(Ye===!0){if(Je===!0||b!==Q){let dt=b===Q&&k.id===K;re.setState(k,b,dt)}}let Qe=!1;if(k.version===ye.__version){if(ye.needsLights&&ye.lightsStateVersion!==on.state.version)Qe=!0;else if(ye.outputColorSpace!==pe)Qe=!0;else if(B.isBatchedMesh&&ye.batching===!1)Qe=!0;else if(!B.isBatchedMesh&&ye.batching===!0)Qe=!0;else if(B.isBatchedMesh&&ye.batchingColor===!0&&B.colorTexture===null)Qe=!0;else if(B.isBatchedMesh&&ye.batchingColor===!1&&B.colorTexture!==null)Qe=!0;else if(B.isInstancedMesh&&ye.instancing===!1)Qe=!0;else if(!B.isInstancedMesh&&ye.instancing===!0)Qe=!0;else if(B.isSkinnedMesh&&ye.skinning===!1)Qe=!0;else if(!B.isSkinnedMesh&&ye.skinning===!0)Qe=!0;else if(B.isInstancedMesh&&ye.instancingColor===!0&&B.instanceColor===null)Qe=!0;else if(B.isInstancedMesh&&ye.instancingColor===!1&&B.instanceColor!==null)Qe=!0;else if(B.isInstancedMesh&&ye.instancingMorph===!0&&B.morphTexture===null)Qe=!0;else if(B.isInstancedMesh&&ye.instancingMorph===!1&&B.morphTexture!==null)Qe=!0;else if(ye.envMap!==Ee)Qe=!0;else if(k.fog===!0&&ye.fog!==ge)Qe=!0;else if(ye.numClippingPlanes!==void 0&&(ye.numClippingPlanes!==re.numPlanes||ye.numIntersection!==re.numIntersection))Qe=!0;else if(ye.vertexAlphas!==Be)Qe=!0;else if(ye.vertexTangents!==Ve)Qe=!0;else if(ye.morphTargets!==Ae)Qe=!0;else if(ye.morphNormals!==ot)Qe=!0;else if(ye.morphColors!==Tt)Qe=!0;else if(ye.toneMapping!==Mt)Qe=!0;else if(ye.morphTargetsCount!==$t)Qe=!0;else if(!!ye.lightProbeGrid!==w.state.lightProbeGridArray.length>0)Qe=!0}else Qe=!0,ye.__version=k.version;let xn=ye.currentProgram;if(Qe===!0){if(xn=xo(k,D,B),C&&k.isNodeMaterial)C.onUpdateProgram(k,xn,ye)}let Bn=!1,xi=!1,wr=!1,ut=xn.getUniforms(),Et=ye.uniforms;if(M.useProgram(xn.program))Bn=!0,xi=!0,wr=!0;if(k.id!==K)K=k.id,xi=!0;if(ye.needsLights){let dt=Y0(w.state.lightProbeGridArray,B);if(ye.lightProbeGrid!==dt)ye.lightProbeGrid=dt,xi=!0}if(Bn||Q!==b){if(M.buffers.depth.getReversed()&&b.reversedDepth!==!0)b._reversedDepth=!0,b.updateProjectionMatrix();ut.setValue(L,"projectionMatrix",b.projectionMatrix),ut.setValue(L,"viewMatrix",b.matrixWorldInverse);let yi=ut.map.cameraPosition;if(yi!==void 0)yi.setValue(L,gn.setFromMatrixPosition(b.matrixWorld));if(gt.logarithmicDepthBuffer)ut.setValue(L,"logDepthBufFC",2/(Math.log(b.far+1)/Math.LN2));if(k.isMeshPhongMaterial||k.isMeshToonMaterial||k.isMeshLambertMaterial||k.isMeshBasicMaterial||k.isMeshStandardMaterial||k.isShaderMaterial)ut.setValue(L,"isOrthographic",b.isOrthographicCamera===!0);if(Q!==b)Q=b,xi=!0,wr=!0}if(ye.needsLights){if(on.state.directionalShadowMap.length>0)ut.setValue(L,"directionalShadowMap",on.state.directionalShadowMap,W);if(on.state.spotShadowMap.length>0)ut.setValue(L,"spotShadowMap",on.state.spotShadowMap,W);if(on.state.pointShadowMap.length>0)ut.setValue(L,"pointShadowMap",on.state.pointShadowMap,W)}if(B.isSkinnedMesh){ut.setOptional(L,B,"bindMatrix"),ut.setOptional(L,B,"bindMatrixInverse");let dt=B.skeleton;if(dt){if(dt.boneTexture===null)dt.computeBoneTexture();ut.setValue(L,"boneTexture",dt.boneTexture,W)}}if(B.isBatchedMesh){if(ut.setOptional(L,B,"batchingTexture"),ut.setValue(L,"batchingTexture",B._matricesTexture,W),ut.setOptional(L,B,"batchingIdTexture"),ut.setValue(L,"batchingIdTexture",B._indirectTexture,W),ut.setOptional(L,B,"batchingColorTexture"),B._colorsTexture!==null)ut.setValue(L,"batchingColorTexture",B._colorsTexture,W)}let vi=G.morphAttributes;if(vi.position!==void 0||vi.normal!==void 0||vi.color!==void 0)et.update(B,G,xn);if(xi||ye.receiveShadow!==B.receiveShadow)ye.receiveShadow=B.receiveShadow,ut.setValue(L,"receiveShadow",B.receiveShadow);if((k.isMeshStandardMaterial||k.isMeshLambertMaterial||k.isMeshPhongMaterial)&&k.envMap===null&&D.environment!==null)Et.envMapIntensity.value=D.environmentIntensity;if(Et.dfgLUT!==void 0)Et.dfgLUT.value=FT();if(xi){if(ut.setValue(L,"toneMappingExposure",S.toneMappingExposure),ye.needsLights)J0(Et,wr);if(ge&&k.fog===!0)xe.refreshFogUniforms(Et,ge);if(xe.refreshMaterialUniforms(Et,k,fe,ne,w.state.transmissionRenderTarget[b.id]),ye.needsLights&&ye.lightProbeGrid){let dt=ye.lightProbeGrid;Et.probesSH.value=dt.texture,Et.probesMin.value.copy(dt.boundingBox.min),Et.probesMax.value.copy(dt.boundingBox.max),Et.probesResolution.value.copy(dt.resolution)}co.upload(L,Sh(ye),Et,W)}if(k.isShaderMaterial&&k.uniformsNeedUpdate===!0)co.upload(L,Sh(ye),Et,W),k.uniformsNeedUpdate=!1;if(k.isSpriteMaterial)ut.setValue(L,"center",B.center);if(ut.setValue(L,"modelViewMatrix",B.modelViewMatrix),ut.setValue(L,"normalMatrix",B.normalMatrix),ut.setValue(L,"modelMatrix",B.matrixWorld),k.uniformsGroups!==void 0){let dt=k.uniformsGroups;for(let yi=0,Tr=dt.length;yi<Tr;yi++){let wh=dt[yi];ve.update(wh,xn),ve.bind(wh,xn)}}return xn}function J0(b,D){b.ambientLightColor.needsUpdate=D,b.lightProbe.needsUpdate=D,b.directionalLights.needsUpdate=D,b.directionalLightShadows.needsUpdate=D,b.pointLights.needsUpdate=D,b.pointLightShadows.needsUpdate=D,b.spotLights.needsUpdate=D,b.spotLightShadows.needsUpdate=D,b.rectAreaLights.needsUpdate=D,b.hemisphereLights.needsUpdate=D}function K0(b){return b.isMeshLambertMaterial||b.isMeshToonMaterial||b.isMeshPhongMaterial||b.isMeshStandardMaterial||b.isShadowMaterial||b.isShaderMaterial&&b.lights===!0}if(this.getActiveCubeFace=function(){return H},this.getActiveMipmapLevel=function(){return V},this.getRenderTarget=function(){return U},this.setRenderTargetTextures=function(b,D,G){let k=I.get(b);if(k.__autoAllocateDepthBuffer=b.resolveDepthBuffer===!1,k.__autoAllocateDepthBuffer===!1)k.__useRenderToTexture=!1;I.get(b.texture).__webglTexture=D,I.get(b.depthTexture).__webglTexture=k.__autoAllocateDepthBuffer?void 0:G,k.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(b,D){let G=I.get(b);G.__webglFramebuffer=D,G.__useDefaultFramebuffer=D===void 0},this.setRenderTarget=function(b,D=0,G=0){U=b,H=D,V=G;let k=null,B=!1,ge=!1;if(b){let pe=I.get(b);if(pe.__useDefaultFramebuffer!==void 0){M.bindFramebuffer(L.FRAMEBUFFER,pe.__webglFramebuffer),se.copy(b.viewport),me.copy(b.scissor),_e=b.scissorTest,M.viewport(se),M.scissor(me),M.setScissorTest(_e),K=-1;return}else if(pe.__webglFramebuffer===void 0)W.setupRenderTarget(b);else if(pe.__hasExternalTextures)W.rebindTextures(b,I.get(b.texture).__webglTexture,I.get(b.depthTexture).__webglTexture);else if(b.depthBuffer){let Be=b.depthTexture;if(pe.__boundDepthTexture!==Be){if(Be!==null&&I.has(Be)&&(b.width!==Be.image.width||b.height!==Be.image.height))throw Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");W.setupDepthRenderbuffer(b)}}let Se=b.texture;if(Se.isData3DTexture||Se.isDataArrayTexture||Se.isCompressedArrayTexture)ge=!0;let Ee=I.get(b).__webglFramebuffer;if(b.isWebGLCubeRenderTarget){if(Array.isArray(Ee[D]))k=Ee[D][G];else k=Ee[D];B=!0}else if(b.samples>0&&W.useMultisampledRTT(b)===!1)k=I.get(b).__webglMultisampledFramebuffer;else if(Array.isArray(Ee))k=Ee[G];else k=Ee;se.copy(b.viewport),me.copy(b.scissor),_e=b.scissorTest}else se.copy(Ze).multiplyScalar(fe).floor(),me.copy(Oe).multiplyScalar(fe).floor(),_e=ke;if(G!==0)k=z;if(M.bindFramebuffer(L.FRAMEBUFFER,k))M.drawBuffers(b,k);if(M.viewport(se),M.scissor(me),M.setScissorTest(_e),B){let pe=I.get(b.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+D,pe.__webglTexture,G)}else if(ge){let pe=D;for(let Se=0;Se<b.textures.length;Se++){let Ee=I.get(b.textures[Se]);L.framebufferTextureLayer(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0+Se,Ee.__webglTexture,G,pe)}}else if(b!==null&&G!==0){let pe=I.get(b.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,pe.__webglTexture,G)}K=-1},this.readRenderTargetPixels=function(b,D,G,k,B,ge,be,pe=0){if(!(b&&b.isWebGLRenderTarget)){Ne("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Se=I.get(b).__webglFramebuffer;if(b.isWebGLCubeRenderTarget&&be!==void 0)Se=Se[be];if(Se){M.bindFramebuffer(L.FRAMEBUFFER,Se);try{let Ee=b.textures[pe],{format:Be,type:Ve}=Ee;if(b.textures.length>1)L.readBuffer(L.COLOR_ATTACHMENT0+pe);if(!gt.textureFormatReadable(Be)){Ne("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!gt.textureTypeReadable(Ve)){Ne("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(D>=0&&D<=b.width-k&&(G>=0&&G<=b.height-B))L.readPixels(D,G,k,B,Y.convert(Be),Y.convert(Ve),ge)}finally{let Ee=U!==null?I.get(U).__webglFramebuffer:null;M.bindFramebuffer(L.FRAMEBUFFER,Ee)}}},this.readRenderTargetPixelsAsync=async function(b,D,G,k,B,ge,be,pe=0){if(!(b&&b.isWebGLRenderTarget))throw Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Se=I.get(b).__webglFramebuffer;if(b.isWebGLCubeRenderTarget&&be!==void 0)Se=Se[be];if(Se)if(D>=0&&D<=b.width-k&&(G>=0&&G<=b.height-B)){M.bindFramebuffer(L.FRAMEBUFFER,Se);let Ee=b.textures[pe],{format:Be,type:Ve}=Ee;if(b.textures.length>1)L.readBuffer(L.COLOR_ATTACHMENT0+pe);if(!gt.textureFormatReadable(Be))throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!gt.textureTypeReadable(Ve))throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Ae=L.createBuffer();L.bindBuffer(L.PIXEL_PACK_BUFFER,Ae),L.bufferData(L.PIXEL_PACK_BUFFER,ge.byteLength,L.STREAM_READ),L.readPixels(D,G,k,B,Y.convert(Be),Y.convert(Ve),0);let ot=U!==null?I.get(U).__webglFramebuffer:null;M.bindFramebuffer(L.FRAMEBUFFER,ot);let Tt=L.fenceSync(L.SYNC_GPU_COMMANDS_COMPLETE,0);return L.flush(),await d_(L,Tt,4),L.bindBuffer(L.PIXEL_PACK_BUFFER,Ae),L.getBufferSubData(L.PIXEL_PACK_BUFFER,0,ge),L.deleteBuffer(Ae),L.deleteSync(Tt),ge}else throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(b,D=null,G=0){let k=Math.pow(2,-G),B=Math.floor(b.image.width*k),ge=Math.floor(b.image.height*k),be=D!==null?D.x:0,pe=D!==null?D.y:0;W.setTexture2D(b,0),L.copyTexSubImage2D(L.TEXTURE_2D,G,0,0,be,pe,B,ge),M.unbindTexture()},this.copyTextureToTexture=function(b,D,G=null,k=null,B=0,ge=0){let be,pe,Se,Ee,Be,Ve,Ae,ot,Tt,Mt=b.isCompressedTexture?b.mipmaps[ge]:b.image;if(G!==null)be=G.max.x-G.min.x,pe=G.max.y-G.min.y,Se=G.isBox3?G.max.z-G.min.z:1,Ee=G.min.x,Be=G.min.y,Ve=G.isBox3?G.min.z:0;else{let Et=Math.pow(2,-B);if(be=Math.floor(Mt.width*Et),pe=Math.floor(Mt.height*Et),b.isDataArrayTexture)Se=Mt.depth;else if(b.isData3DTexture)Se=Math.floor(Mt.depth*Et);else Se=1;Ee=0,Be=0,Ve=0}if(k!==null)Ae=k.x,ot=k.y,Tt=k.z;else Ae=0,ot=0,Tt=0;let lt=Y.convert(D.format),$t=Y.convert(D.type),ye;if(D.isData3DTexture)W.setTexture3D(D,0),ye=L.TEXTURE_3D;else if(D.isDataArrayTexture||D.isCompressedArrayTexture)W.setTexture2DArray(D,0),ye=L.TEXTURE_2D_ARRAY;else W.setTexture2D(D,0),ye=L.TEXTURE_2D;M.activeTexture(L.TEXTURE0),M.pixelStorei(L.UNPACK_FLIP_Y_WEBGL,D.flipY),M.pixelStorei(L.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),M.pixelStorei(L.UNPACK_ALIGNMENT,D.unpackAlignment);let on=M.getParameter(L.UNPACK_ROW_LENGTH),Qe=M.getParameter(L.UNPACK_IMAGE_HEIGHT),xn=M.getParameter(L.UNPACK_SKIP_PIXELS),Bn=M.getParameter(L.UNPACK_SKIP_ROWS),xi=M.getParameter(L.UNPACK_SKIP_IMAGES);M.pixelStorei(L.UNPACK_ROW_LENGTH,Mt.width),M.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Mt.height),M.pixelStorei(L.UNPACK_SKIP_PIXELS,Ee),M.pixelStorei(L.UNPACK_SKIP_ROWS,Be),M.pixelStorei(L.UNPACK_SKIP_IMAGES,Ve);let wr=b.isDataArrayTexture||b.isData3DTexture,ut=D.isDataArrayTexture||D.isData3DTexture;if(b.isDepthTexture){let Et=I.get(b),vi=I.get(D),dt=I.get(Et.__renderTarget),yi=I.get(vi.__renderTarget);M.bindFramebuffer(L.READ_FRAMEBUFFER,dt.__webglFramebuffer),M.bindFramebuffer(L.DRAW_FRAMEBUFFER,yi.__webglFramebuffer);for(let Tr=0;Tr<Se;Tr++){if(wr)L.framebufferTextureLayer(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,I.get(b).__webglTexture,B,Ve+Tr),L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,I.get(D).__webglTexture,ge,Tt+Tr);L.blitFramebuffer(Ee,Be,be,pe,Ae,ot,be,pe,L.DEPTH_BUFFER_BIT,L.NEAREST)}M.bindFramebuffer(L.READ_FRAMEBUFFER,null),M.bindFramebuffer(L.DRAW_FRAMEBUFFER,null)}else if(B!==0||b.isRenderTargetTexture||I.has(b)){let Et=I.get(b),vi=I.get(D);M.bindFramebuffer(L.READ_FRAMEBUFFER,J),M.bindFramebuffer(L.DRAW_FRAMEBUFFER,O);for(let dt=0;dt<Se;dt++){if(wr)L.framebufferTextureLayer(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,Et.__webglTexture,B,Ve+dt);else L.framebufferTexture2D(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,Et.__webglTexture,B);if(ut)L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,vi.__webglTexture,ge,Tt+dt);else L.framebufferTexture2D(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,vi.__webglTexture,ge);if(B!==0)L.blitFramebuffer(Ee,Be,be,pe,Ae,ot,be,pe,L.COLOR_BUFFER_BIT,L.NEAREST);else if(ut)L.copyTexSubImage3D(ye,ge,Ae,ot,Tt+dt,Ee,Be,be,pe);else L.copyTexSubImage2D(ye,ge,Ae,ot,Ee,Be,be,pe)}M.bindFramebuffer(L.READ_FRAMEBUFFER,null),M.bindFramebuffer(L.DRAW_FRAMEBUFFER,null)}else if(ut)if(b.isDataTexture||b.isData3DTexture)L.texSubImage3D(ye,ge,Ae,ot,Tt,be,pe,Se,lt,$t,Mt.data);else if(D.isCompressedArrayTexture)L.compressedTexSubImage3D(ye,ge,Ae,ot,Tt,be,pe,Se,lt,Mt.data);else L.texSubImage3D(ye,ge,Ae,ot,Tt,be,pe,Se,lt,$t,Mt);else if(b.isDataTexture)L.texSubImage2D(L.TEXTURE_2D,ge,Ae,ot,be,pe,lt,$t,Mt.data);else if(b.isCompressedTexture)L.compressedTexSubImage2D(L.TEXTURE_2D,ge,Ae,ot,Mt.width,Mt.height,lt,Mt.data);else L.texSubImage2D(L.TEXTURE_2D,ge,Ae,ot,be,pe,lt,$t,Mt);if(M.pixelStorei(L.UNPACK_ROW_LENGTH,on),M.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Qe),M.pixelStorei(L.UNPACK_SKIP_PIXELS,xn),M.pixelStorei(L.UNPACK_SKIP_ROWS,Bn),M.pixelStorei(L.UNPACK_SKIP_IMAGES,xi),ge===0&&D.generateMipmaps)L.generateMipmap(ye);M.unbindTexture()},this.initRenderTarget=function(b){if(I.get(b).__webglFramebuffer===void 0)W.setupRenderTarget(b)},this.initTexture=function(b){if(b.isCubeTexture)W.setTextureCube(b,0);else if(b.isData3DTexture)W.setTexture3D(b,0);else if(b.isDataArrayTexture||b.isCompressedArrayTexture)W.setTexture2DArray(b,0);else W.setTexture2D(b,0);M.unbindTexture()},this.resetState=function(){H=0,V=0,U=null,M.reset(),ae.reset()},typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return bu}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=We._getDrawingBufferColorSpace(e),t.unpackColorSpace=We._getUnpackColorSpace()}}function eh(e,t){if(t===_u)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(t===Qr||t===Ws){let n=e.getIndex();if(n===null){let o=[],a=e.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)o.push(c);e.setIndex(o),n=e.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),e}let i=n.count-2,r=[];if(t===Qr)for(let o=1;o<=i;o++)r.push(n.getX(0)),r.push(n.getX(o)),r.push(n.getX(o+1));else for(let o=0;o<i;o++)if(o%2===0)r.push(n.getX(o)),r.push(n.getX(o+1)),r.push(n.getX(o+2));else r.push(n.getX(o+2)),r.push(n.getX(o+1)),r.push(n.getX(o));if(r.length/3!==i)console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let s=e.clone();return s.setIndex(r),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}function s0(e){let t=new Map,n=new Map,i=e.clone();return o0(e,i,function(r,s){t.set(s,r),n.set(r,s)}),i.traverse(function(r){if(!r.isSkinnedMesh)return;let s=r,o=t.get(r),a=o.skeleton.bones;s.skeleton=o.skeleton.clone(),s.bindMatrix.copy(o.bindMatrix),s.skeleton.bones=a.map(function(c){return n.get(c)}),s.bind(s.skeleton,s.bindMatrix)}),i}function o0(e,t,n){n(e,t);for(let i=0;i<e.children.length;i++)o0(e.children[i],t.children[i],n)}class ah extends _i{constructor(e){super(e);this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new p0(t)}),this.register(function(t){return new m0(t)}),this.register(function(t){return new w0(t)}),this.register(function(t){return new T0(t)}),this.register(function(t){return new E0(t)}),this.register(function(t){return new _0(t)}),this.register(function(t){return new x0(t)}),this.register(function(t){return new v0(t)}),this.register(function(t){return new y0(t)}),this.register(function(t){return new d0(t)}),this.register(function(t){return new b0(t)}),this.register(function(t){return new g0(t)}),this.register(function(t){return new M0(t)}),this.register(function(t){return new S0(t)}),this.register(function(t){return new h0(t)}),this.register(function(t){return new rh(t,Xe.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new rh(t,Xe.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new A0(t)})}load(e,t,n,i){let r=this,s;if(this.resourcePath!=="")s=this.resourcePath;else if(this.path!==""){let c=Zi.extractUrlBase(e);s=Zi.resolveURL(c,this.path)}else s=Zi.extractUrlBase(e);this.manager.itemStart(e);let o=function(c){if(i)i(c);else console.error(c);r.manager.itemError(e),r.manager.itemEnd(e)},a=new io(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(c){try{r.parse(c,s,function(l){t(l),r.manager.itemEnd(e)},o)}catch(l){o(l)}},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){if(this.pluginCallbacks.indexOf(e)===-1)this.pluginCallbacks.push(e);return this}unregister(e){if(this.pluginCallbacks.indexOf(e)!==-1)this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1);return this}parse(e,t,n,i){let r,s={},o={},a=new TextDecoder;if(typeof e==="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(a.decode(new Uint8Array(e,0,4))===R0){try{s[Xe.KHR_BINARY_GLTF]=new C0(e)}catch(u){if(i)i(u);return}r=JSON.parse(s[Xe.KHR_BINARY_GLTF].content)}else r=JSON.parse(a.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){if(i)i(Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let c=new D0(r,{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 l=0;l<this.pluginCallbacks.length;l++){let u=this.pluginCallbacks[l](c);if(!u.name)console.error("THREE.GLTFLoader: Invalid plugin found: missing name");o[u.name]=u,s[u.name]=!0}if(r.extensionsUsed)for(let l=0;l<r.extensionsUsed.length;++l){let u=r.extensionsUsed[l],f=r.extensionsRequired||[];switch(u){case Xe.KHR_MATERIALS_UNLIT:s[u]=new f0;break;case Xe.KHR_DRACO_MESH_COMPRESSION:s[u]=new I0(r,this.dracoLoader);break;case Xe.KHR_TEXTURE_TRANSFORM:s[u]=new P0;break;case Xe.KHR_MESH_QUANTIZATION:s[u]=new L0;break;default:if(f.indexOf(u)>=0&&o[u]===void 0)console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}c.setExtensions(s),c.setPlugins(o),c.parse(n,i)}parseAsync(e,t){let n=this;return new Promise(function(i,r){n.parse(e,t,i,r)})}}function kT(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function Rt(e,t,n){let i=e.json.materials[t];if(i.extensions&&i.extensions[n])return i.extensions[n];return null}var Xe={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"};class h0{constructor(e){this.parser=e,this.name=Xe.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){let r=t[n];if(r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0)e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n="light:"+e,i=t.cache.get(n);if(i)return i;let r=t.json,a=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e],c,l=new Le(16777215);if(a.color!==void 0)l.setRGB(a.color[0],a.color[1],a.color[2],hn);let u=a.range!==void 0?a.range:0;switch(a.type){case"directional":c=new os(l),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new ss(l),c.distance=u;break;case"spot":c=new $a(l),c.distance=u,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,c.angle=a.spot.outerConeAngle,c.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}if(c.position.set(0,0,0),ti(c,a),a.intensity!==void 0)c.intensity=a.intensity;return c.name=t.createUniqueName(a.name||"light_"+e),i=Promise.resolve(c),t.cache.add(n,i),i}getDependency(e,t){if(e!=="light")return;return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],o=(r.extensions&&r.extensions[this.name]||{}).light;if(o===void 0)return null;return this._loadLight(o).then(function(a){return n._getNodeRef(t.cache,o,a)})}}class f0{constructor(){this.name=Xe.KHR_MATERIALS_UNLIT}getMaterialType(){return Kn}extendParams(e,t,n){let i=[];e.color=new Le(1,1,1),e.opacity=1;let r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){let s=r.baseColorFactor;e.color.setRGB(s[0],s[1],s[2],hn),e.opacity=s[3]}if(r.baseColorTexture!==void 0)i.push(n.assignTexture(e,"map",r.baseColorTexture,Fi))}return Promise.all(i)}}class d0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();if(n.emissiveStrength!==void 0)t.emissiveIntensity=n.emissiveStrength;return Promise.resolve()}}class p0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(n.clearcoatFactor!==void 0)t.clearcoat=n.clearcoatFactor;if(n.clearcoatTexture!==void 0)i.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture));if(n.clearcoatRoughnessFactor!==void 0)t.clearcoatRoughness=n.clearcoatRoughnessFactor;if(n.clearcoatRoughnessTexture!==void 0)i.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture));if(n.clearcoatNormalTexture!==void 0){if(i.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0){let r=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Ie(r,r)}}return Promise.all(i)}}class m0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();return t.dispersion=n.dispersion!==void 0?n.dispersion:0,Promise.resolve()}}class g0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(n.iridescenceFactor!==void 0)t.iridescence=n.iridescenceFactor;if(n.iridescenceTexture!==void 0)i.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture));if(n.iridescenceIor!==void 0)t.iridescenceIOR=n.iridescenceIor;if(t.iridescenceThicknessRange===void 0)t.iridescenceThicknessRange=[100,400];if(n.iridescenceThicknessMinimum!==void 0)t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum;if(n.iridescenceThicknessMaximum!==void 0)t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum;if(n.iridescenceThicknessTexture!==void 0)i.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture));return Promise.all(i)}}class _0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_SHEEN}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.sheenColor=new Le(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){let r=n.sheenColorFactor;t.sheenColor.setRGB(r[0],r[1],r[2],hn)}if(n.sheenRoughnessFactor!==void 0)t.sheenRoughness=n.sheenRoughnessFactor;if(n.sheenColorTexture!==void 0)i.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,Fi));if(n.sheenRoughnessTexture!==void 0)i.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture));return Promise.all(i)}}class x0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(n.transmissionFactor!==void 0)t.transmission=n.transmissionFactor;if(n.transmissionTexture!==void 0)i.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture));return Promise.all(i)}}class v0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_VOLUME}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0)i.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture));t.attenuationDistance=n.attenuationDistance||1/0;let r=n.attenuationColor||[1,1,1];return t.attenuationColor=new Le().setRGB(r[0],r[1],r[2],hn),Promise.all(i)}}class y0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_IOR}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();if(t.ior=n.ior!==void 0?n.ior:1.5,t.ior===0)t.ior=1000;return Promise.resolve()}}class b0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0)i.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));let r=n.specularColorFactor||[1,1,1];if(t.specularColor=new Le().setRGB(r[0],r[1],r[2],hn),n.specularColorTexture!==void 0)i.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,Fi));return Promise.all(i)}}class S0{constructor(e){this.parser=e,this.name=Xe.EXT_MATERIALS_BUMP}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0)i.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture));return Promise.all(i)}}class M0{constructor(e){this.parser=e,this.name=Xe.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Rt(this.parser,e,this.name)!==null?dn:null}extendMaterialParams(e,t){let n=Rt(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(n.anisotropyStrength!==void 0)t.anisotropy=n.anisotropyStrength;if(n.anisotropyRotation!==void 0)t.anisotropyRotation=n.anisotropyRotation;if(n.anisotropyTexture!==void 0)i.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture));return Promise.all(i)}}class w0{constructor(e){this.parser=e,this.name=Xe.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;let r=i.extensions[this.name],s=t.options.ktx2Loader;if(!s)if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");else return null;return t.loadTextureImage(e,r.source,s)}}class T0{constructor(e){this.parser=e,this.name=Xe.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],o=i.images[s.source],a=n.textureLoader;if(o.uri){let c=n.options.manager.getHandler(o.uri);if(c!==null)a=c}return n.loadTextureImage(e,s.source,a)}}class E0{constructor(e){this.parser=e,this.name=Xe.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],o=i.images[s.source],a=n.textureLoader;if(o.uri){let c=n.options.manager.getHandler(o.uri);if(c!==null)a=c}return n.loadTextureImage(e,s.source,a)}}class rh{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 i=n.extensions[this.name],r=this.parser.getDependency("buffer",i.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.supported)if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");else return null;return r.then(function(o){let a=i.byteOffset||0,c=i.byteLength||0,{count:l,byteStride:u}=i,f=new Uint8Array(o,a,c);if(s.decodeGltfBufferAsync)return s.decodeGltfBufferAsync(l,u,f,i.mode,i.filter).then(function(h){return h.buffer});else return s.ready.then(function(){let h=new ArrayBuffer(l*u);return s.decodeGltfBuffer(new Uint8Array(h),l,u,f,i.mode,i.filter),h})})}else return null}}class A0{constructor(e){this.name=Xe.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 i=t.meshes[n.mesh];for(let c of i.primitives)if(c.mode!==wn.TRIANGLES&&c.mode!==wn.TRIANGLE_STRIP&&c.mode!==wn.TRIANGLE_FAN&&c.mode!==void 0)return null;let s=n.extensions[this.name].attributes,o=[],a={};for(let c in s)o.push(this.parser.getDependency("accessor",s[c]).then((l)=>(a[c]=l,a[c])));if(o.length<1)return null;return o.push(this.parser.createNodeMesh(e)),Promise.all(o).then((c)=>{let l=c.pop(),u=l.isGroup?l.children:[l],f=c[0].count,h=[];for(let d of u){let g=new ze,y=new N,p=new Bt,m=new N(1,1,1),A=new ns(d.geometry,d.material,f);for(let T=0;T<f;T++){if(a.TRANSLATION)y.fromBufferAttribute(a.TRANSLATION,T);if(a.ROTATION)p.fromBufferAttribute(a.ROTATION,T);if(a.SCALE)m.fromBufferAttribute(a.SCALE,T);A.setMatrixAt(T,g.compose(y,p,m))}for(let T in a)if(T==="_COLOR_0"){let v=a[T];A.instanceColor=new lr(v.array,v.itemSize,v.normalized)}else if(T!=="TRANSLATION"&&T!=="ROTATION"&&T!=="SCALE")d.geometry.setAttribute(T,a[T]);at.prototype.copy.call(A,d),this.parser.assignFinalMaterial(A),h.push(A)}if(l.isGroup)return l.clear(),l.add(...h),l;return h[0]})}}var R0="glTF",uo=12,a0={JSON:1313821514,BIN:5130562};class C0{constructor(e){this.name=Xe.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,uo),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!==R0)throw Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");else if(this.header.version<2)throw Error("THREE.GLTFLoader: Legacy binary file detected.");let i=this.header.length-uo,r=new DataView(e,uo),s=0;while(s<i){let o=r.getUint32(s,!0);s+=4;let a=r.getUint32(s,!0);if(s+=4,a===a0.JSON){let c=new Uint8Array(e,uo+s,o);this.content=n.decode(c)}else if(a===a0.BIN){let c=uo+s;this.body=e.slice(c,c+o)}s+=o}if(this.content===null)throw Error("THREE.GLTFLoader: JSON content not found.")}}class I0{constructor(e,t){if(!t)throw Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Xe.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,i=this.dracoLoader,r=e.extensions[this.name].bufferView,s=e.extensions[this.name].attributes,o={},a={},c={};for(let l in s){let u=sh[l]||l.toLowerCase();o[u]=s[l]}for(let l in e.attributes){let u=sh[l]||l.toLowerCase();if(s[l]!==void 0){let f=n.accessors[e.attributes[l]],h=ls[f.componentType];c[u]=h.name,a[u]=f.normalized===!0}}return t.getDependency("bufferView",r).then(function(l){return new Promise(function(u,f){i.decodeDracoFile(l,function(h){for(let d in h.attributes){let g=h.attributes[d],y=a[d];if(y!==void 0)g.normalized=y}u(h)},o,c,hn,f)})})}}class P0{constructor(){this.name=Xe.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){if((t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0)return e;if(e=e.clone(),t.texCoord!==void 0)e.channel=t.texCoord;if(t.offset!==void 0)e.offset.fromArray(t.offset);if(t.rotation!==void 0)e.rotation=t.rotation;if(t.scale!==void 0)e.repeat.fromArray(t.scale);return e.needsUpdate=!0,e}}class L0{constructor(){this.name=Xe.KHR_MESH_QUANTIZATION}}class ch extends gi{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=e*i*3+i;for(let s=0;s!==i;s++)t[s]=n[r+s];return t}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=o*2,c=o*3,l=i-t,u=(n-t)/l,f=u*u,h=f*u,d=e*c,g=d-c,y=-2*h+3*f,p=h-f,m=1-y,A=p-f+u;for(let T=0;T!==o;T++){let v=s[g+T+o],w=s[g+T+a]*l,E=s[d+T+o],R=s[d+T]*l;r[T]=m*v+A*w+y*E+p*R}return r}}var BT=new Bt;class N0 extends ch{interpolate_(e,t,n,i){let r=super.interpolate_(e,t,n,i);return BT.fromArray(r).normalize().toArray(r),r}}var wn={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},ls={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},c0={9728:On,9729:Gt,9984:va,9985:Jr,9986:hr,9987:jn},l0={33071:jr,33648:xa,10497:Yr},th={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},sh={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"},qi={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},GT={CUBICSPLINE:void 0,LINEAR:Ea,STEP:gu},nh={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function HT(e){if(e.DefaultMaterial===void 0)e.DefaultMaterial=new mi({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Ui});return e.DefaultMaterial}function yr(e,t,n){for(let i in n.extensions)if(e[i]===void 0)t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[i]=n.extensions[i]}function ti(e,t){if(t.extras!==void 0)if(typeof t.extras==="object")Object.assign(e.userData,t.extras);else console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras)}function VT(e,t,n){let i=!1,r=!1,s=!1;for(let l=0,u=t.length;l<u;l++){let f=t[l];if(f.POSITION!==void 0)i=!0;if(f.NORMAL!==void 0)r=!0;if(f.COLOR_0!==void 0)s=!0;if(i&&r&&s)break}if(!i&&!r&&!s)return Promise.resolve(e);let o=[],a=[],c=[];for(let l=0,u=t.length;l<u;l++){let f=t[l];if(i){let h=f.POSITION!==void 0?n.getDependency("accessor",f.POSITION):e.attributes.position;o.push(h)}if(r){let h=f.NORMAL!==void 0?n.getDependency("accessor",f.NORMAL):e.attributes.normal;a.push(h)}if(s){let h=f.COLOR_0!==void 0?n.getDependency("accessor",f.COLOR_0):e.attributes.color;c.push(h)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c)]).then(function(l){let u=l[0],f=l[1],h=l[2];if(i)e.morphAttributes.position=u;if(r)e.morphAttributes.normal=f;if(s)e.morphAttributes.color=h;return e.morphTargetsRelative=!0,e})}function WT(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let n=0,i=t.weights.length;n<i;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){let n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let i=0,r=n.length;i<r;i++)e.morphTargetDictionary[n[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function $T(e){let t,n=e.extensions&&e.extensions[Xe.KHR_DRACO_MESH_COMPRESSION];if(n)t="draco:"+n.bufferView+":"+n.indices+":"+ih(n.attributes);else t=e.indices+":"+ih(e.attributes)+":"+e.mode;if(e.targets!==void 0)for(let i=0,r=e.targets.length;i<r;i++)t+=":"+ih(e.targets[i]);return t}function ih(e){let t="",n=Object.keys(e).sort();for(let i=0,r=n.length;i<r;i++)t+=n[i]+":"+e[n[i]]+";";return t}function oh(e){switch(e){case Int8Array:return 0.007874015748031496;case Uint8Array:return 0.00392156862745098;case Int16Array:return 0.00003051850947599719;case Uint16Array:return 0.000015259021896696422;default:throw Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function ZT(e){if(e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0)return"image/jpeg";if(e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0)return"image/webp";if(e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0)return"image/ktx2";return"image/png"}var XT=new ze;class D0{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new kT,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,i=-1,r=!1,s=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){let o=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(o)===!0;let a=o.match(/Version\/(\d+)/);i=n&&a?parseInt(a[1],10):-1,r=o.indexOf("Firefox")>-1,s=r?o.match(/Firefox\/([0-9]+)\./)[1]:-1}if(typeof createImageBitmap>"u"||n&&i<17||r&&s<98)this.textureLoader=new Ga(this.options.manager);else this.textureLoader=new Za(this.options.manager);if(this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new io(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,i=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(s){let o={scene:s[0][i.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:i.asset,parser:n,userData:{}};return yr(r,o,i),ti(o,i),Promise.all(n._invokeAll(function(a){return a.afterRoot&&a.afterRoot(o)})).then(function(){for(let a of o.scenes)a.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,r=t.length;i<r;i++){let s=t[i].joints;for(let o=0,a=s.length;o<a;o++)e[s[o]].isBone=!0}for(let i=0,r=e.length;i<r;i++){let s=e[i];if(s.mesh!==void 0){if(this._addNodeRef(this.meshCache,s.mesh),s.skin!==void 0)n[s.mesh].isSkinnedMesh=!0}if(s.camera!==void 0)this._addNodeRef(this.cameraCache,s.camera)}}_addNodeRef(e,t){if(t===void 0)return;if(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 i=n.clone(),r=(s,o)=>{let a=this.associations.get(s);if(a!=null)this.associations.set(o,a);for(let[c,l]of s.children.entries())r(l,o.children[c])};return r(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let i=e(t[n]);if(i)return i}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let i=0;i<t.length;i++){let r=e(t[i]);if(r)n.push(r)}return n}getDependency(e,t){let n=e+":"+t,i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":i=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!i)throw Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(r,s){return n.getDependency(e,s)})),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 Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Xe.KHR_BINARY_GLTF].body);let i=this.options;return new Promise(function(r,s){n.load(Zi.resolveURL(t.uri,i.path),r,void 0,function(){s(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 i=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+i)})}loadAccessor(e){let t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){let s=th[i.type],o=ls[i.componentType],a=i.normalized===!0,c=new o(i.count*s);return Promise.resolve(new Nt(c,s,a))}let r=[];if(i.bufferView!==void 0)r.push(this.getDependency("bufferView",i.bufferView));else r.push(null);if(i.sparse!==void 0)r.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",i.sparse.values.bufferView));return Promise.all(r).then(function(s){let o=s[0],a=th[i.type],c=ls[i.componentType],l=c.BYTES_PER_ELEMENT,u=l*a,f=i.byteOffset||0,h=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,d=i.normalized===!0,g,y;if(h&&h!==u){let p=Math.floor(f/h),m="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+p+":"+i.count,A=t.cache.get(m);if(!A)g=new c(o,p*h,i.count*h/l),A=new qs(g,h/l),t.cache.add(m,A);y=new ts(A,a,f%h/l,d)}else{if(o===null)g=new c(i.count*a);else g=new c(o,f,i.count*a);y=new Nt(g,a,d)}if(i.sparse!==void 0){let p=th.SCALAR,m=ls[i.sparse.indices.componentType],A=i.sparse.indices.byteOffset||0,T=i.sparse.values.byteOffset||0,v=new m(s[1],A,i.sparse.count*p),w=new c(s[2],T,i.sparse.count*a);if(o!==null)y=new Nt(y.array.slice(),y.itemSize,y.normalized);y.normalized=!1;for(let E=0,R=v.length;E<R;E++){let _=v[E];if(y.setX(_,w[E*a]),a>=2)y.setY(_,w[E*a+1]);if(a>=3)y.setZ(_,w[E*a+2]);if(a>=4)y.setW(_,w[E*a+3]);if(a>=5)throw Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}y.normalized=d}return y})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,s=t.images[r],o=this.textureLoader;if(s.uri){let a=n.manager.getHandler(s.uri);if(a!==null)o=a}return this.loadTextureImage(e,r,o)}loadTextureImage(e,t,n){let i=this,r=this.json,s=r.textures[e],o=r.images[t],a=(o.uri||o.bufferView)+":"+s.sampler;if(this.textureCache[a])return this.textureCache[a];let c=this.loadImageSource(t,n).then(function(l){if(l.flipY=!1,l.name=s.name||o.name||"",l.name===""&&typeof o.uri==="string"&&o.uri.startsWith("data:image/")===!1)l.name=o.uri;let f=(r.samplers||{})[s.sampler]||{};return l.magFilter=c0[f.magFilter]||Gt,l.minFilter=c0[f.minFilter]||jn,l.wrapS=l0[f.wrapS]||Yr,l.wrapT=l0[f.wrapT]||Yr,l.generateMipmaps=!l.isCompressedTexture&&l.minFilter!==On&&l.minFilter!==Gt,i.associations.set(l,{textures:e}),l}).catch(function(){return null});return this.textureCache[a]=c,c}loadImageSource(e,t){let n=this,i=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then((u)=>u.clone());let s=i.images[e],o=self.URL||self.webkitURL,a=s.uri||"",c=!1;if(s.bufferView!==void 0)a=n.getDependency("bufferView",s.bufferView).then(function(u){c=!0;let f=new Blob([u],{type:s.mimeType});return a=o.createObjectURL(f),a});else if(s.uri===void 0)throw Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let l=Promise.resolve(a).then(function(u){return new Promise(function(f,h){let d=f;if(t.isImageBitmapLoader===!0)d=function(g){let y=new wt(g);y.needsUpdate=!0,f(y)};t.load(Zi.resolveURL(u,r.path),d,void 0,h)})}).then(function(u){if(c===!0)o.revokeObjectURL(a);return ti(u,s),u.userData.mimeType=s.mimeType||ZT(s.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),u});return this.sourceCache[e]=l,l}assignTexture(e,t,n,i){let r=this;return this.getDependency("texture",n.index).then(function(s){if(!s)return null;if(n.texCoord!==void 0&&n.texCoord>0)s=s.clone(),s.channel=n.texCoord;if(r.extensions[Xe.KHR_TEXTURE_TRANSFORM]){let o=n.extensions!==void 0?n.extensions[Xe.KHR_TEXTURE_TRANSFORM]:void 0;if(o){let a=r.associations.get(s);s=r.extensions[Xe.KHR_TEXTURE_TRANSFORM].extendTexture(s,o),r.associations.set(s,a)}}if(i!==void 0)s.colorSpace=i;return e[t]=s,s})}assignFinalMaterial(e){let{geometry:t,material:n}=e,i=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,s=t.attributes.normal===void 0;if(e.isPoints){let o="PointsMaterial:"+n.uuid,a=this.cache.get(o);if(!a)a=new eo,rn.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,a.sizeAttenuation=!1,this.cache.add(o,a);n=a}else if(e.isLine){let o="LineBasicMaterial:"+n.uuid,a=this.cache.get(o);if(!a)a=new Qs,rn.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,this.cache.add(o,a);n=a}if(i||r||s){let o="ClonedMaterial:"+n.uuid+":";if(i)o+="derivative-tangents:";if(r)o+="vertex-colors:";if(s)o+="flat-shading:";let a=this.cache.get(o);if(!a){if(a=n.clone(),r)a.vertexColors=!0;if(s)a.flatShading=!0;if(i){if(a.normalScale)a.normalScale.y*=-1;if(a.clearcoatNormalScale)a.clearcoatNormalScale.y*=-1}this.cache.add(o,a),this.associations.set(a,this.associations.get(n))}n=a}e.material=n}getMaterialType(){return mi}loadMaterial(e){let t=this,n=this.json,i=this.extensions,r=n.materials[e],s,o={},a=r.extensions||{},c=[];if(a[Xe.KHR_MATERIALS_UNLIT]){let u=i[Xe.KHR_MATERIALS_UNLIT];s=u.getMaterialType(),c.push(u.extendParams(o,r,t))}else{let u=r.pbrMetallicRoughness||{};if(o.color=new Le(1,1,1),o.opacity=1,Array.isArray(u.baseColorFactor)){let f=u.baseColorFactor;o.color.setRGB(f[0],f[1],f[2],hn),o.opacity=f[3]}if(u.baseColorTexture!==void 0)c.push(t.assignTexture(o,"map",u.baseColorTexture,Fi));if(o.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,o.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0)c.push(t.assignTexture(o,"metalnessMap",u.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",u.metallicRoughnessTexture));s=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)})))}if(r.doubleSided===!0)o.side=bn;let l=r.alphaMode||nh.OPAQUE;if(l===nh.BLEND)o.transparent=!0,o.depthWrite=!1;else if(o.transparent=!1,l===nh.MASK)o.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:0.5;if(r.normalTexture!==void 0&&s!==Kn){if(c.push(t.assignTexture(o,"normalMap",r.normalTexture)),o.normalScale=new Ie(1,1),r.normalTexture.scale!==void 0){let u=r.normalTexture.scale;o.normalScale.set(u,u)}}if(r.occlusionTexture!==void 0&&s!==Kn){if(c.push(t.assignTexture(o,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0)o.aoMapIntensity=r.occlusionTexture.strength}if(r.emissiveFactor!==void 0&&s!==Kn){let u=r.emissiveFactor;o.emissive=new Le().setRGB(u[0],u[1],u[2],hn)}if(r.emissiveTexture!==void 0&&s!==Kn)c.push(t.assignTexture(o,"emissiveMap",r.emissiveTexture,Fi));return Promise.all(c).then(function(){let u=new s(o);if(r.name)u.name=r.name;if(ti(u,r),t.associations.set(u,{materials:e}),r.extensions)yr(i,u,r);return u})}createUniqueName(e){let t=tt.sanitizeNodeName(e||"");if(t in this.nodeNamesUsed)return t+"_"+ ++this.nodeNamesUsed[t];else return this.nodeNamesUsed[t]=0,t}loadGeometries(e){let t=this,n=this.extensions,i=this.primitiveCache;function r(o){return n[Xe.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(a){return u0(a,o,t)})}let s=[];for(let o=0,a=e.length;o<a;o++){let c=e[o],l=$T(c),u=i[l];if(u)s.push(u.promise);else{let f;if(c.extensions&&c.extensions[Xe.KHR_DRACO_MESH_COMPRESSION])f=r(c);else f=u0(new tn,c,t);i[l]={primitive:c,promise:f},s.push(f)}}return Promise.all(s)}loadMesh(e){let t=this,n=this.json,i=this.extensions,r=n.meshes[e],s=r.primitives,o=[];for(let a=0,c=s.length;a<c;a++){let l=s[a].material===void 0?HT(this.cache):this.getDependency("material",s[a].material);o.push(l)}return o.push(t.loadGeometries(s)),Promise.all(o).then(function(a){let c=a.slice(0,a.length-1),l=a[a.length-1],u=[];for(let h=0,d=l.length;h<d;h++){let g=l[h],y=s[h],p,m=c[h];if(y.mode===wn.TRIANGLES||y.mode===wn.TRIANGLE_STRIP||y.mode===wn.TRIANGLE_FAN||y.mode===void 0){if(p=r.isSkinnedMesh===!0?new Na(g,m):new pt(g,m),p.isSkinnedMesh===!0)p.normalizeSkinWeights();if(y.mode===wn.TRIANGLE_STRIP)p.geometry=eh(p.geometry,Ws);else if(y.mode===wn.TRIANGLE_FAN)p.geometry=eh(p.geometry,Qr)}else if(y.mode===wn.LINES)p=new Da(g,m);else if(y.mode===wn.LINE_STRIP)p=new ki(g,m);else if(y.mode===wn.LINE_LOOP)p=new Ua(g,m);else if(y.mode===wn.POINTS)p=new is(g,m);else throw Error("THREE.GLTFLoader: Primitive mode unsupported: "+y.mode);if(Object.keys(p.geometry.morphAttributes).length>0)WT(p,r);if(p.name=t.createUniqueName(r.name||"mesh_"+e),ti(p,r),y.extensions)yr(i,p,y);t.assignFinalMaterial(p),u.push(p)}for(let h=0,d=u.length;h<d;h++)t.associations.set(u[h],{meshes:e,primitives:h});if(u.length===1){if(r.extensions)yr(i,u[0],r);return u[0]}let f=new Zn;if(r.extensions)yr(i,f,r);t.associations.set(f,{meshes:e});for(let h=0,d=u.length;h<d;h++)f.add(u[h]);return f})}loadCamera(e){let t,n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}if(n.type==="perspective")t=new Lt($s.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2000000);else if(n.type==="orthographic")t=new xr(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar);if(n.name)t.name=this.createUniqueName(n.name);return ti(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let i=0,r=t.joints.length;i<r;i++)n.push(this._loadNodeShallow(t.joints[i]));if(t.inverseBindMatrices!==void 0)n.push(this.getDependency("accessor",t.inverseBindMatrices));else n.push(null);return Promise.all(n).then(function(i){let r=i.pop(),s=i,o=[],a=[];for(let c=0,l=s.length;c<l;c++){let u=s[c];if(u){o.push(u);let f=new ze;if(r!==null)f.fromArray(r.array,c*16);a.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new Js(o,a)})}loadAnimation(e){let t=this.json,n=this,i=t.animations[e],r=i.name?i.name:"animation_"+e,s=[],o=[],a=[],c=[],l=[];for(let u=0,f=i.channels.length;u<f;u++){let h=i.channels[u],d=i.samplers[h.sampler],g=h.target,y=g.node,p=i.parameters!==void 0?i.parameters[d.input]:d.input,m=i.parameters!==void 0?i.parameters[d.output]:d.output;if(g.node===void 0)continue;s.push(this.getDependency("node",y)),o.push(this.getDependency("accessor",p)),a.push(this.getDependency("accessor",m)),c.push(d),l.push(g)}return Promise.all([Promise.all(s),Promise.all(o),Promise.all(a),Promise.all(c),Promise.all(l)]).then(function(u){let f=u[0],h=u[1],d=u[2],g=u[3],y=u[4],p=[];for(let A=0,T=f.length;A<T;A++){let v=f[A],w=h[A],E=d[A],R=g[A],_=y[A];if(v===void 0)continue;if(v.updateMatrix)v.updateMatrix();let S=n._createAnimationTracks(v,w,E,R,_);if(S)for(let F=0;F<S.length;F++)p.push(S[F])}let m=new $r(r,void 0,p);return ti(m,i),m})}createNodeMesh(e){let t=this.json,n=this,i=t.nodes[e];if(i.mesh===void 0)return null;return n.getDependency("mesh",i.mesh).then(function(r){let s=n._getNodeRef(n.meshCache,i.mesh,r);if(i.weights!==void 0)s.traverse(function(o){if(!o.isMesh)return;for(let a=0,c=i.weights.length;a<c;a++)o.morphTargetInfluences[a]=i.weights[a]});return s})}loadNode(e){let t=this.json,n=this,i=t.nodes[e],r=n._loadNodeShallow(e),s=[],o=i.children||[];for(let c=0,l=o.length;c<l;c++)s.push(n.getDependency("node",o[c]));let a=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([r,Promise.all(s),a]).then(function(c){let l=c[0],u=c[1],f=c[2];if(f!==null)l.traverse(function(h){if(!h.isSkinnedMesh)return;h.bind(f,XT)});for(let h=0,d=u.length;h<d;h++)l.add(u[h]);if(l.userData.pivot!==void 0&&u.length>0){let h=l.userData.pivot,d=u[0];l.pivot=new N().fromArray(h),l.position.x-=h[0],l.position.y-=h[1],l.position.z-=h[2],d.position.set(0,0,0),delete l.userData.pivot}return l})}_loadNodeShallow(e){let t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let r=t.nodes[e],s=r.name?i.createUniqueName(r.name):"",o=[],a=i._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});if(a)o.push(a);if(r.camera!==void 0)o.push(i.getDependency("camera",r.camera).then(function(c){return i._getNodeRef(i.cameraCache,r.camera,c)}));return i._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 l;if(r.isBone===!0)l=new Ys;else if(c.length>1)l=new Zn;else if(c.length===1)l=c[0];else l=new at;if(l!==c[0])for(let u=0,f=c.length;u<f;u++)l.add(c[u]);if(r.name)l.userData.name=r.name,l.name=s;if(ti(l,r),r.extensions)yr(n,l,r);if(r.matrix!==void 0){let u=new ze;u.fromArray(r.matrix),l.applyMatrix4(u)}else{if(r.translation!==void 0)l.position.fromArray(r.translation);if(r.rotation!==void 0)l.quaternion.fromArray(r.rotation);if(r.scale!==void 0)l.scale.fromArray(r.scale)}if(!i.associations.has(l))i.associations.set(l,{});else if(r.mesh!==void 0&&i.meshCache.refs[r.mesh]>1){let u=i.associations.get(l);i.associations.set(l,{...u})}return i.associations.get(l).nodes=e,l}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],i=this,r=new Zn;if(n.name)r.name=i.createUniqueName(n.name);if(ti(r,n),n.extensions)yr(t,r,n);let s=n.nodes||[],o=[];for(let a=0,c=s.length;a<c;a++)o.push(i.getDependency("node",s[a]));return Promise.all(o).then(function(a){for(let l=0,u=a.length;l<u;l++){let f=a[l];if(f.parent!==null)r.add(s0(f));else r.add(f)}let c=(l)=>{let u=new Map;for(let[f,h]of i.associations)if(f instanceof rn||f instanceof wt)u.set(f,h);return l.traverse((f)=>{let h=i.associations.get(f);if(h!=null)u.set(f,h)}),u};return i.associations=c(r),r})}_createAnimationTracks(e,t,n,i,r){let s=[],o=e.name?e.name:e.uuid,a=[];function c(h){if(h.morphTargetInfluences)a.push(h.name?h.name:h.uuid)}if(qi[r.path]===qi.weights){if(c(e),e.isGroup)e.children.forEach(c)}else a.push(o);let l;switch(qi[r.path]){case qi.weights:l=Vi;break;case qi.rotation:l=Wi;break;case qi.translation:case qi.scale:l=_r;break;default:switch(n.itemSize){case 1:l=Vi;break;case 2:case 3:default:l=_r;break}break}let u=i.interpolation!==void 0?GT[i.interpolation]:Ea,f=this._getArrayFromAccessor(n);for(let h=0,d=a.length;h<d;h++){let g=new l(a[h]+"."+qi[r.path],t.array,f,u);if(i.interpolation==="CUBICSPLINE")this._createCubicSplineTrackInterpolant(g);s.push(g)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let n=oh(t.constructor),i=new Float32Array(t.length);for(let r=0,s=t.length;r<s;r++)i[r]=t[r]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){return new(this instanceof Wi?N0:ch)(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function qT(e,t,n){let i=t.attributes,r=new en;if(i.POSITION!==void 0){let a=n.json.accessors[i.POSITION],{min:c,max:l}=a;if(c!==void 0&&l!==void 0){if(r.set(new N(c[0],c[1],c[2]),new N(l[0],l[1],l[2])),a.normalized){let u=oh(ls[a.componentType]);r.min.multiplyScalar(u),r.max.multiplyScalar(u)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let s=t.targets;if(s!==void 0){let a=new N,c=new N;for(let l=0,u=s.length;l<u;l++){let f=s[l];if(f.POSITION!==void 0){let h=n.json.accessors[f.POSITION],{min:d,max:g}=h;if(d!==void 0&&g!==void 0){if(c.setX(Math.max(Math.abs(d[0]),Math.abs(g[0]))),c.setY(Math.max(Math.abs(d[1]),Math.abs(g[1]))),c.setZ(Math.max(Math.abs(d[2]),Math.abs(g[2]))),h.normalized){let y=oh(ls[h.componentType]);c.multiplyScalar(y)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(a)}e.boundingBox=r;let o=new fn;r.getCenter(o.center),o.radius=r.min.distanceTo(r.max)/2,e.boundingSphere=o}function u0(e,t,n){let i=t.attributes,r=[];function s(o,a){return n.getDependency("accessor",o).then(function(c){e.setAttribute(a,c)})}for(let o in i){let a=sh[o]||o.toLowerCase();if(a in e.attributes)continue;r.push(s(i[o],a))}if(t.indices!==void 0&&!e.index){let o=n.getDependency("accessor",t.indices).then(function(a){e.setIndex(a)});r.push(o)}if(We.workingColorSpace!==hn&&"COLOR_0"in i)console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${We.workingColorSpace}" not supported.`);return ti(e,t),qT(e,t,n),Promise.all(r).then(function(){return t.targets!==void 0?VT(e,t.targets,n):e})}var U0={type:"change"},uh={type:"start"},F0={type:"end"},Qa=new zi,O0=new Ln,YT=Math.cos(70*$s.DEG2RAD),Ot=new N,sn=2*Math.PI,ct={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},lh=0.000001;class hh extends qa{constructor(e,t=null){super(e,t);if(this.state=ct.NONE,this.target=new N,this.cursor=new N,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=0.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Ni.ROTATE,MIDDLE:Ni.DOLLY,RIGHT:Ni.PAN},this.touches={ONE:Di.ROTATE,TWO:Di.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new N,this._lastQuaternion=new Bt,this._lastTargetPosition=new N,this._quat=new Bt().setFromUnitVectors(e.up,new N(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new ro,this._sphericalDelta=new ro,this._scale=1,this._panOffset=new N,this._rotateStart=new Ie,this._rotateEnd=new Ie,this._rotateDelta=new Ie,this._panStart=new Ie,this._panEnd=new Ie,this._panDelta=new Ie,this._dollyStart=new Ie,this._dollyEnd=new Ie,this._dollyDelta=new Ie,this._dollyDirection=new N,this._mouse=new Ie,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=JT.bind(this),this._onPointerDown=jT.bind(this),this._onPointerUp=KT.bind(this),this._onContextMenu=sE.bind(this),this._onMouseWheel=tE.bind(this),this._onKeyDown=nE.bind(this),this._onTouchStart=iE.bind(this),this._onTouchMove=rE.bind(this),this._onMouseDown=QT.bind(this),this._onMouseMove=eE.bind(this),this._interceptControlDown=oE.bind(this),this._interceptControlUp=aE.bind(this),this.domElement!==null)this.connect(this.domElement);this.update()}set cursorStyle(e){if(this._cursorStyle=e,e==="grab")this.domElement.style.cursor="grab";else this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){if(this._domElementKeyEvents!==null)this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(U0),this.update(),this.state=ct.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){let t=this.object.position;if(Ot.copy(t).sub(this.target),Ot.applyQuaternion(this._quat),this._spherical.setFromVector3(Ot),this.autoRotate&&this.state===ct.NONE)this._rotateLeft(this._getAutoRotationAngle(e));if(this.enableDamping)this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor;else this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi;let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;if(isFinite(n)&&isFinite(i)){if(n<-Math.PI)n+=sn;else if(n>Math.PI)n-=sn;if(i<-Math.PI)i+=sn;else if(i>Math.PI)i-=sn;if(n<=i)this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta));else this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)}if(this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0)this.target.addScaledVector(this._panOffset,this.dampingFactor);else this.target.add(this._panOffset);this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let s=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=s!=this._spherical.radius}if(Ot.setFromSpherical(this._spherical),Ot.applyQuaternion(this._quatInverse),t.copy(this.target).add(Ot),this.object.lookAt(this.target),this.enableDamping===!0)this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor);else this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0);if(this.zoomToCursor&&this._performCursorZoom){let s=null;if(this.object.isPerspectiveCamera){let o=Ot.length();s=this._clampDistance(o*this._scale);let a=o-s;this.object.position.addScaledVector(this._dollyDirection,a),this.object.updateMatrixWorld(),r=!!a}else if(this.object.isOrthographicCamera){let o=new N(this._mouse.x,this._mouse.y,0);o.unproject(this.object);let a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=a!==this.object.zoom;let c=new N(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),s=Ot.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;if(s!==null)if(this.screenSpacePanning)this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(s).add(this.object.position);else if(Qa.origin.copy(this.object.position),Qa.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Qa.direction))<YT)this.object.lookAt(this.target);else O0.setFromNormalAndCoplanarPoint(this.object.up,this.target),Qa.intersectPlane(O0,this.target)}else if(this.object.isOrthographicCamera){let s=this.object.zoom;if(this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),s!==this.object.zoom)this.object.updateProjectionMatrix(),r=!0}if(this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>lh||8*(1-this._lastQuaternion.dot(this.object.quaternion))>lh||this._lastTargetPosition.distanceToSquared(this.target)>lh)return this.dispatchEvent(U0),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0;return!1}_getAutoRotationAngle(e){if(e!==null)return sn/60*this.autoRotateSpeed*e;else return sn/60/60*this.autoRotateSpeed}_getZoomScale(e){let t=Math.abs(e*0.01);return Math.pow(0.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Ot.setFromMatrixColumn(t,0),Ot.multiplyScalar(-e),this._panOffset.add(Ot)}_panUp(e,t){if(this.screenSpacePanning===!0)Ot.setFromMatrixColumn(t,1);else Ot.setFromMatrixColumn(t,0),Ot.crossVectors(this.object.up,Ot);Ot.multiplyScalar(e),this._panOffset.add(Ot)}_pan(e,t){let n=this.domElement;if(this.object.isPerspectiveCamera){let i=this.object.position;Ot.copy(i).sub(this.target);let r=Ot.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else if(this.object.isOrthographicCamera)this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix);else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1}_dollyOut(e){if(this.object.isPerspectiveCamera||this.object.isOrthographicCamera)this._scale/=e;else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1}_dollyIn(e){if(this.object.isPerspectiveCamera||this.object.isOrthographicCamera)this._scale*=e;else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let n=this.domElement.getBoundingClientRect(),i=e-n.left,r=t-n.top,{width:s,height:o}=n;this._mouse.x=i/s*2-1,this._mouse.y=-(r/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(sn*this._rotateDelta.x/t.clientHeight),this._rotateUp(sn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){if(this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0)this._dollyOut(this._getZoomScale(this._dollyDelta.y));else if(this._dollyDelta.y<0)this._dollyIn(this._getZoomScale(this._dollyDelta.y));this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){if(this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0)this._dollyIn(this._getZoomScale(e.deltaY));else if(e.deltaY>0)this._dollyOut(this._getZoomScale(e.deltaY));this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate)this._rotateUp(sn*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(0,this.keyPanSpeed);t=!0;break;case this.keys.BOTTOM:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate)this._rotateUp(-sn*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(0,-this.keyPanSpeed);t=!0;break;case this.keys.LEFT:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate)this._rotateLeft(sn*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(this.keyPanSpeed,0);t=!0;break;case this.keys.RIGHT:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate)this._rotateLeft(-sn*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(-this.keyPanSpeed,0);t=!0;break}if(t)e.preventDefault(),this.update()}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=0.5*(e.pageX+t.x),i=0.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=0.5*(e.pageX+t.x),i=0.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){if(this.enableZoom)this._handleTouchStartDolly(e);if(this.enablePan)this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){if(this.enableZoom)this._handleTouchStartDolly(e);if(this.enableRotate)this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let n=this._getSecondPointerPosition(e),i=0.5*(e.pageX+n.x),r=0.5*(e.pageY+n.y);this._rotateEnd.set(i,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(sn*this._rotateDelta.x/t.clientHeight),this._rotateUp(sn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=0.5*(e.pageX+t.x),i=0.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let s=(e.pageX+t.x)*0.5,o=(e.pageY+t.y)*0.5;this._updateZoomParameters(s,o)}_handleTouchMoveDollyPan(e){if(this.enableZoom)this._handleTouchMoveDolly(e);if(this.enablePan)this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){if(this.enableZoom)this._handleTouchMoveDolly(e);if(this.enableRotate)this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];if(t===void 0)t=new Ie,this._pointerPositions[e.pointerId]=t;t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){let t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){let t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}if(e.ctrlKey&&!this._controlActive)n.deltaY*=10;return n}}function jT(e){if(this.enabled===!1)return;if(this._pointers.length===0)this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp);if(this._isTrackingPointer(e))return;if(this._addPointer(e),e.pointerType==="touch")this._onTouchStart(e);else this._onMouseDown(e);if(this._cursorStyle==="grab")this.domElement.style.cursor="grabbing"}function JT(e){if(this.enabled===!1)return;if(e.pointerType==="touch")this._onTouchMove(e);else this._onMouseMove(e)}function KT(e){switch(this._removePointer(e),this._pointers.length){case 0:if(this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(F0),this.state=ct.NONE,this._cursorStyle==="grab")this.domElement.style.cursor="grab";break;case 1:let t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y});break}}function QT(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case Ni.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(e),this.state=ct.DOLLY;break;case Ni.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=ct.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=ct.ROTATE}break;case Ni.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=ct.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=ct.PAN}break;default:this.state=ct.NONE}if(this.state!==ct.NONE)this.dispatchEvent(uh)}function eE(e){switch(this.state){case ct.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(e);break;case ct.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(e);break;case ct.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(e);break}}function tE(e){if(this.enabled===!1||this.enableZoom===!1||this.state!==ct.NONE)return;e.preventDefault(),this.dispatchEvent(uh),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(F0)}function nE(e){if(this.enabled===!1)return;this._handleKeyDown(e)}function iE(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case Di.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(e),this.state=ct.TOUCH_ROTATE;break;case Di.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(e),this.state=ct.TOUCH_PAN;break;default:this.state=ct.NONE}break;case 2:switch(this.touches.TWO){case Di.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(e),this.state=ct.TOUCH_DOLLY_PAN;break;case Di.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(e),this.state=ct.TOUCH_DOLLY_ROTATE;break;default:this.state=ct.NONE}break;default:this.state=ct.NONE}if(this.state!==ct.NONE)this.dispatchEvent(uh)}function rE(e){switch(this._trackPointer(e),this.state){case ct.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(e),this.update();break;case ct.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(e),this.update();break;case ct.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(e),this.update();break;case ct.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=ct.NONE}}function sE(e){if(this.enabled===!1)return;e.preventDefault()}function oE(e){if(e.key==="Control")this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}function aE(e){if(e.key==="Control")this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}class fh extends es{constructor(){super();this.name="RoomEnvironment",this.position.y=-3.5;let e=new Gi;e.deleteAttribute("uv");let t=new mi({side:Yt}),n=new mi,i=new ss(16777215,900,28,2);i.position.set(0.418,16.199,0.3),this.add(i);let r=new pt(e,t);r.position.set(-0.757,13.219,0.717),r.scale.set(31.713,28.305,28.591),this.add(r);let s=new ns(e,n,6),o=new at;o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-0.195,0),o.scale.set(2.328,7.905,4.651),o.updateMatrix(),s.setMatrixAt(0,o.matrix),o.position.set(-5.607,-0.754,-0.758),o.rotation.set(0,0.994,0),o.scale.set(1.97,1.534,3.955),o.updateMatrix(),s.setMatrixAt(1,o.matrix),o.position.set(6.167,0.857,7.803),o.rotation.set(0,0.561,0),o.scale.set(3.927,6.285,3.687),o.updateMatrix(),s.setMatrixAt(2,o.matrix),o.position.set(-2.017,0.018,6.124),o.rotation.set(0,0.333,0),o.scale.set(2.002,4.566,2.064),o.updateMatrix(),s.setMatrixAt(3,o.matrix),o.position.set(2.291,-0.756,-2.621),o.rotation.set(0,-0.286,0),o.scale.set(1.546,1.552,1.496),o.updateMatrix(),s.setMatrixAt(4,o.matrix),o.position.set(-2.193,-0.369,-5.547),o.rotation.set(0,0.516,0),o.scale.set(3.875,3.487,2.986),o.updateMatrix(),s.setMatrixAt(5,o.matrix),this.add(s);let a=new pt(e,us(50));a.position.set(-16.116,14.37,8.208),a.scale.set(0.1,2.428,2.739),this.add(a);let c=new pt(e,us(50));c.position.set(-16.109,18.021,-8.207),c.scale.set(0.1,2.425,2.751),this.add(c);let l=new pt(e,us(17));l.position.set(14.904,12.198,-1.832),l.scale.set(0.15,4.265,6.331),this.add(l);let u=new pt(e,us(43));u.position.set(-0.462,8.89,14.52),u.scale.set(4.38,5.441,0.088),this.add(u);let f=new pt(e,us(20));f.position.set(3.235,11.486,-12.541),f.scale.set(2.5,2,0.1),this.add(f);let h=new pt(e,us(100));h.position.set(0,20,0),h.scale.set(1,0.1,1),this.add(h)}dispose(){let e=new Set;this.traverse((t)=>{if(t.isMesh)e.add(t.geometry),e.add(t.material)});for(let t of e)t.dispose()}}function us(e){return new za({color:0,emissive:16777215,emissiveIntensity:e})}function z0(e,t,n=40,i=[e]){let r=e.getCenter(new N),s=Math.max(e.getSize(new N).length()/2,0.01),o=new N(1,0.65,1.25).normalize(),a=new N().crossVectors(new N(0,1,0),o).normalize(),c=new N().crossVectors(o,a),l=[];for(let A of i.length?i:[e])for(let T of[A.min.x,A.max.x])for(let v of[A.min.y,A.max.y])for(let w of[A.min.z,A.max.z])l.push(new N(T,v,w));let u=1/0,f=-1/0,h=1/0,d=-1/0;for(let A of l){let T=A.clone().sub(r),v=T.dot(a),w=T.dot(c);u=Math.min(u,v),f=Math.max(f,v),h=Math.min(h,w),d=Math.max(d,w)}r.addScaledVector(a,(u+f)/2),r.addScaledVector(c,(h+d)/2);let g=Math.tan(n*Math.PI/360),y=g*t,p=s;for(let A of l){let T=A.clone().sub(r),v=T.dot(o);p=Math.max(p,v+Math.abs(T.dot(a))*1.12/y,v+Math.abs(T.dot(c))*1.12/g)}let m=r.clone().addScaledVector(o,p);return{center:r,radius:s,distance:p,position:m}}function k0(e){let t=new Qu({antialias:!0,alpha:!1});t.setPixelRatio(Math.min(devicePixelRatio,2)),t.setClearColor(1382930),t.toneMapping=Gs,t.toneMappingExposure=1.15,e.replaceChildren(t.domElement);let n=new es,i=new Lt(40,1,0.01,1000),r=new hh(i,t.domElement);r.enableDamping=!0;let s=new lo(t),o=new fh,a=s.fromScene(o,0.04);n.environment=a.texture,o.dispose(),s.dispose();let c=new os(16773591,2.4);c.position.set(4,8,5),n.add(c),n.add(new Ha(14806490,5065021,1.7));let l,u,f=[],h=!0,d=performance.now(),g=0,y=0,p=!1,m=(w)=>{let E=new Set,R=new Set,_=new Set;w.traverse((S)=>{let F=S;if(!F.isMesh)return;E.add(F.geometry);for(let C of Array.isArray(F.material)?F.material:[F.material]){R.add(C);for(let z of Object.values(C))if(z instanceof wt)_.add(z)}});for(let S of[...E,...R,..._])S.dispose()},A=()=>{if(!l)return;let w=new en().setFromObject(l,!0),E=[];l.traverse((C)=>{if(C instanceof pt||C instanceof ki||C instanceof is){let z=new en().setFromObject(C,!0);if(!z.isEmpty())E.push(z)}});let{center:R,radius:_,distance:S,position:F}=z0(w,i.aspect,i.fov,E);r.target.copy(R),i.position.copy(F),i.near=Math.max(_/1000,0.0001),i.far=S+_*100,r.minDistance=_*0.1,r.maxDistance=_*80,i.updateProjectionMatrix(),r.update()},T=new ResizeObserver(()=>{let{clientWidth:w,clientHeight:E}=e;if(!w||!E)return;t.setSize(w,E),i.aspect=w/E,i.updateProjectionMatrix()});T.observe(e);let v=(w)=>{if(p)return;let E=Math.min((w-d)/1000,0.1);if(d=w,h)u?.update(E);r.update(),t.render(n,i),g=requestAnimationFrame(v)};return g=requestAnimationFrame(v),{async load(w){let E=++y;qc(w);let R=new no;R.setURLModifier((O)=>{if(!O.startsWith("blob:")&&!O.startsWith("data:"))throw Error("External model resources are not loaded");return O});let _=await new ah(R).parseAsync(Uint8Array.from(w).buffer,"");if(p||E!==y){m(_.scene);return}if(l)u?.stopAllAction(),u?.uncacheRoot(l),n.remove(l),m(l);l=_.scene,n.add(l),f=_.animations,u=new Xa(l),h=!0;let{clientWidth:S,clientHeight:F}=e;t.setSize(S,F),i.aspect=S/F,A();let C=0,z=0,J=new Set;return l.traverse((O)=>{let H=O;if(!H.isMesh)return;z++,C+=(H.geometry.index?.count??H.geometry.attributes.position?.count??0)/3*(H.isInstancedMesh?H.count:1);for(let V of Array.isArray(H.material)?H.material:[H.material])J.add(V)}),{triangles:C,meshes:z,materials:J.size,clips:f.map((O)=>O.name)}},reset:A,wire(w){l?.traverse((E)=>{let R=E;if(R.isMesh){for(let _ of Array.isArray(R.material)?R.material:[R.material])if("wireframe"in _)_.wireframe=w}})},lighting(w){t.toneMappingExposure=w==="bright"?1.65:w==="soft"?0.85:1.15,c.intensity=w==="soft"?0.8:2.4},clip(w){if(u?.stopAllAction(),f[w])u?.clipAction(f[w]).play()},pause(w){h=!w},dispose(){if(p=!0,y++,cancelAnimationFrame(g),T.disconnect(),r.dispose(),l)m(l);a.dispose(),t.dispose(),e.replaceChildren()}}}var De=(e)=>document.getElementById(e),Ct=(e,t,n)=>{let i=document.createElement(e);if(t!==void 0)i.textContent=t;if(n)i.className=n;return i},mo=[],fs=[],Sr=[],ec="",hs,mn,ho=0,B0=0,fo=!1,po=!1,Yi=new Set,dh=[],G0=[],br=(e)=>`${e.collection}/${e.manifest.assetId}/${e.manifest.revisionId}`,H0=(e)=>{De("status").textContent=e},Mr=(e)=>H0(e instanceof Error?e.message:String(e)),go=(e,t,n=dh)=>{let i=URL.createObjectURL(new Blob([Uint8Array.from(e)],{type:t}));return n.push(i),i};async function V0(e){let t=await fetch(e),n=await t.json();if(!t.ok)throw Error(n.error??"Request failed");return n}async function cE(e,t){if(e.local){let i=e.local.files[t];if(!i)throw Error("File unavailable");return i}if(e.loose&&t==="asset.glb")return e.loose;let n=await fetch(`/files/${br(e)}/${t}`);if(!n.ok)throw Error((await n.json()).error??"File unavailable");return new Uint8Array(await n.arrayBuffer())}function lE(e,t){if(e.local){if(t==="editable.zip")return go(Yc([e.local]),"application/zip");return go(e.local.files[t],t.endsWith(".js")?"text/javascript":"model/gltf-binary")}if(e.loose)return go(e.loose,"model/gltf-binary");return`/files/${br(e)}/${t}?download`}function W0(e,t){try{localStorage.setItem(e,t)}catch{}}function $0(e){try{return localStorage.getItem(e)}catch{return null}}function uE(){let e=De("collections");e.replaceChildren();for(let t of[...mo,...Sr.length?[{id:"opened-files",label:"Opened files"}]:[]]){let n=Ct("button",t.label,ec===t.id?"active":"");n.onclick=()=>void tc(t.id).catch(Mr),e.append(n)}}async function tc(e){let t=++B0;ec=e,Yi.clear(),uE(),H0("");let n=e==="opened-files"?Sr:(await V0(`/api/assets?collection=${encodeURIComponent(e)}`)).assets.map((i)=>({collection:e,manifest:i}));if(t!==B0)return;fs=n,W0("kiln.collection",e),De("collection-title").textContent=e==="opened-files"?"Opened files":mo.find((i)=>i.id===e)?.label??e,De("collection-caption").textContent=e==="opened-files"?"Previewed in your browser. Your original files stay untouched.":"Saved revisions, editable source, and everything ready to use.",ph()}function hE(){let e=new Map;for(let t of fs){let n=t.manifest.assetId;e.set(n,[...e.get(n)??[],t])}return[...e.values()].map((t)=>(t.sort((n,i)=>i.manifest.createdAt.localeCompare(n.manifest.createdAt)||i.manifest.revisionId.localeCompare(n.manifest.revisionId)),t.find((n)=>n.manifest.revisionId===$0(`kiln.revision.${n.collection}.${n.manifest.assetId}`))??t[0]))}function ph(){for(let i of G0.splice(0))URL.revokeObjectURL(i);let e=De("cards");e.replaceChildren();let t=De("search").value.toLowerCase(),n=hE().filter((i)=>`${i.manifest.name} ${i.manifest.tags.join(" ")}`.toLowerCase().includes(t));if(De("count").textContent=`${n.length} asset${n.length===1?"":"s"}`,De("export-selection").disabled=!Yi.size,!n.length){let i=Ct("div",void 0,"empty");if(i.append(Ct("b",t?"No matching assets":"Your next idea belongs here."),Ct("p",t?"Try another name or tag.":"Save an asset with your agent, or open a GLB or editable bundle.")),!t)i.append(Ct("code",'kiln save asset.kiln.js --name "My asset"'));e.append(i);return}for(let i of n){let r=i.manifest,s=Ct("article",void 0,"card"),o=Ct("button",void 0,"card-open");o.setAttribute("aria-label",`View ${r.name}`),o.onclick=()=>void mh(i).catch(Mr);let a=Ct("div",void 0,"thumb");if(r.files["preview.png"]){let d=Ct("img");d.loading="lazy",d.alt=r.name,d.src=i.local?go(i.local.files["preview.png"],"image/png",G0):`/files/${br(i)}/preview.png`,d.onerror=()=>{d.remove(),a.textContent="◇"},a.append(d)}else a.textContent="◇";let c=Ct("div",void 0,"card-content");c.append(Ct("span",r.name,"card-title"));let l=fs.filter((d)=>d.manifest.assetId===r.assetId),u=new Set(l.map((d)=>d.manifest.parentRevision)),f=l.filter((d)=>!u.has(d.manifest.revisionId));c.append(Ct("span",`${r.editable?"Editable source":"Source unavailable"} · ${l.length} revision${l.length===1?"":"s"}${f.length>1?` · ${f.length} branches`:""}`,"card-meta"));let h=Ct("div",void 0,"tags");for(let d of r.tags)h.append(Ct("span",d,"tag"));if(c.append(h),o.append(a,c),s.append(o),!i.loose){let d=Ct("input");d.type="checkbox",d.className="selection",d.checked=Yi.has(br(i)),d.setAttribute("aria-label",`Select ${r.name}`),d.onchange=()=>{if(d.checked)Yi.add(br(i));else Yi.delete(br(i));De("export-selection").disabled=!Yi.size},s.append(d)}e.append(s)}}async function mh(e){let t=++ho;hs=e,W0(`kiln.revision.${e.collection}.${e.manifest.assetId}`,e.manifest.revisionId);for(let o of dh.splice(0))URL.revokeObjectURL(o);let n=De("detail");if(!n.open)n.showModal();De("asset-name").textContent=e.manifest.name;let i=De("revisions");i.replaceChildren();for(let o of fs.filter((a)=>a.manifest.assetId===e.manifest.assetId)){let a=Ct("option",`${new Date(o.manifest.createdAt).toLocaleString()} · ${o.manifest.description||o.manifest.revisionId.slice(0,10)}`);a.value=o.manifest.revisionId,a.selected=o.manifest.revisionId===e.manifest.revisionId,i.append(a)}i.onchange=()=>{let o=fs.find((a)=>a.manifest.assetId===e.manifest.assetId&&a.manifest.revisionId===i.value);if(o)mh(o).catch(Mr)},De("asset-description").textContent=e.manifest.description??e.manifest.brief??(e.manifest.editable?"Source travels with this revision. Download the editable bundle to continue elsewhere.":"This GLB has no saved Kiln source. You can view and use the model."),De("provenance").textContent=e.loose?"Standalone GLB. No source or build provenance supplied.":JSON.stringify(e.manifest,null,2);let r=De("downloads");r.replaceChildren();for(let[o,a]of[["asset.glb","Download GLB"],...e.manifest.editable?[["source.kiln.js","Download source"]]:[],...!e.loose?[["editable.zip",e.manifest.editable?"Download editable bundle":"Download asset bundle"]]:[]]){let c=Ct("a",a);c.href=lE(e,o),c.download=`${e.manifest.name.replace(/[^a-z0-9_-]/gi,"-")}${o==="asset.glb"?".glb":o==="source.kiln.js"?".kiln.js":".zip"}`,r.append(c)}De("refine").disabled=!e.manifest.editable,De("asset-stats").replaceChildren(),De("stage-status").textContent="Loading saved GLB…",fo=!1,po=!1,De("wire").setAttribute("aria-pressed","false"),De("play").textContent="Pause";let s=De("animation");s.replaceChildren(new Option("Rest pose","")),De("play").disabled=!0;try{mn??=k0(De("stage"));let o=await cE(e,"asset.glb");if(t!==ho)return;let a=await mn.load(o);if(!a||t!==ho)return;mn.wire(!1),mn.lighting(De("lighting").value);for(let[c,l]of[[a.triangles.toLocaleString(),"triangles"],[a.meshes,"meshes"],[a.materials,"materials"],[`${(o.length/1024).toFixed(0)} KB`,"GLB"]]){let u=Ct("div");u.append(Ct("strong",String(c)),Ct("span",String(l))),De("asset-stats").append(u)}for(let c=0;c<a.clips.length;c++)s.append(new Option(a.clips[c],String(c)));De("stage-status").textContent=""}catch(o){if(t===ho)mn?.dispose(),mn=void 0,De("stage-status").textContent=`3D preview unavailable: ${o instanceof Error?o.message:o}. Downloads remain available.`}}async function Z0(e){for(let t of e){if(t.bytes.length>si)throw Error("File exceeds 64 MiB");if(t.name.toLowerCase().endsWith(".zip"))for(let n of Dm(t.bytes)){for(let[i,r]of Object.entries(n.files))if(`sha256:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(r)))).map((o)=>o.toString(16).padStart(2,"0")).join("")}`!==n.manifest.files[i]?.sha256)throw Error(`Bundle integrity failure: ${i}`);if(!Sr.some((i)=>i.manifest.revisionId===n.manifest.revisionId&&i.manifest.assetId===n.manifest.assetId))Sr.push({collection:"opened-files",manifest:n.manifest,local:n})}else{let n=`a_${crypto.randomUUID().replaceAll("-","")}`;Sr.push({collection:"opened-files",loose:t.bytes,manifest:{version:"kiln.asset.v1",assetId:n,revisionId:`r_${n}`,name:t.name.replace(/\.glb$/i,""),tags:[],createdAt:new Date().toISOString(),editable:!1,files:{}}})}}await tc("opened-files")}De("open").onchange=async(e)=>{try{let t=Array.from(e.target.files??[]);if(t.some((n)=>n.size>si))throw Error("File exceeds 64 MiB");await Z0(await Promise.all(t.map(async(n)=>({name:n.name,bytes:new Uint8Array(await n.arrayBuffer())}))))}catch(t){Mr(t)}};De("refresh").onclick=()=>void tc(ec).catch(Mr);De("search").oninput=ph;De("close-detail").onclick=()=>De("detail").close();De("detail").addEventListener("close",()=>{ho++,mn?.dispose(),mn=void 0;for(let e of dh.splice(0))URL.revokeObjectURL(e);ph()});De("frame").onclick=()=>mn?.reset();De("wire").onclick=()=>{fo=!fo,mn?.wire(fo),De("wire").setAttribute("aria-pressed",String(fo))};De("lighting").onchange=(e)=>mn?.lighting(e.target.value);De("animation").onchange=(e)=>{let t=e.target.value;mn?.clip(t===""?-1:Number(t)),De("play").disabled=t===""};De("play").onclick=()=>{po=!po,mn?.pause(po),De("play").textContent=po?"Play":"Pause"};De("refine").onclick=async()=>{if(!hs)return;let e=hs.manifest,t=hs.local?`Import the downloaded editable bundle using kiln import <bundle.zip>. Restore asset ${e.assetId}, revision ${e.revisionId}, using kiln_assets action=restore. Read its source with kiln_source, refine it with kiln_edit, review the result, and save a child revision with kiln_save. Requested change: `:`Use kiln_assets with action=restore, collection=${hs.collection}, assetId=${e.assetId}, revisionId=${e.revisionId}. Read the returned programRef with kiln_source, refine it with kiln_edit, review the result, and save with kiln_save using assetId=${e.assetId}, parentRevision=${e.revisionId}, collection=${hs.collection}. Requested change: `;try{await navigator.clipboard.writeText(t),De("refine").textContent="Instructions copied"}catch{De("provenance").textContent=t,De("provenance").parentElement?.setAttribute("open","")}};De("export-selection").onclick=()=>{try{let e=Ct("a");if(ec==="opened-files")e.href=go(Yc(fs.filter((t)=>Yi.has(br(t))).map((t)=>t.local)),"application/zip");else{let t=new URLSearchParams;for(let n of Yi)t.append("revision",n);e.href=`/api/bundle?${t}`}e.download="kiln-assets.zip",e.click()}catch(e){Mr(e)}};async function fE(){mo=(await V0("/api/collections")).collections;let e=$0("kiln.collection");if(await tc(mo.find((t)=>t.id===e)?.id??mo[0]?.id??"project"),new URLSearchParams(location.search).has("open")){let t=await fetch("/api/standalone");if(!t.ok)throw Error("File unavailable");if(await Z0([{name:t.headers.get("Content-Type")?.includes("zip")?"asset.zip":"asset.glb",bytes:new Uint8Array(await t.arrayBuffer())}]),Sr.length===1)await mh(Sr[0])}}fE().catch(Mr);diff --git a/dist/viewer/chat.html b/dist/viewer/chat.htmlindex a8566bad..6a5ee702 100644--- a/dist/viewer/chat.html+++ b/dist/viewer/chat.html@@ -116,13 +116,13 @@</div><p id="status" role="status">Loading asset from Kiln…</p><script type="module">- var JF=Object.defineProperty;var WF=($)=>$;function QF($,U){this[$]=WF.bind(null,U)}var RJ=($,U)=>{for(var J in U)JF($,J,{get:U[J],enumerable:!0,configurable:!0,set:QF.bind(U,J)})};var sk="185",nJ={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},iJ={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},tk=0,QX=1,ek=2;var RW=1,$q=2,k8=3,oJ=0,$U=1,vU=2,JJ=0,VW=1,KX=2,XX=3,HX=4,Uq=5;var q8=100,Jq=101,Wq=102,Qq=103,Kq=104,Xq=200,Hq=201,Nq=202,Yq=203,Gq=204,Oq=205,Eq=206,kq=207,qq=208,Zq=209,Iq=210,Dq=211,Fq=212,Lq=213,Rq=214,Vq=0,wq=1,Mq=2,NX=3,Bq=4,Pq=5,zq=6,_q=7,Aq=0,Cq=1,Sq=2,dU=0,YX=1,GX=2,OX=3,wW=4,EX=5,kX=6,qX=7;var Z8=301,z0=302,Y9=303,G9=304,MW=306,I8=1000,D8=1001,O9=1002,cU=1003,E9=1004;var _0=1005;var n6=1006,F8=1007;var WJ=1008;var nU=1009,Tq=1010,vq=1011,BW=1012,ZX=1013,rJ=1014,AJ=1015,CJ=1016,IX=1017,DX=1018,L8=1020,jq=35902,gq=35899,bq=1021,yq=1022,QJ=1023,A0=1026,C0=1027,xq=1028,FX=1029,S0=1030,LX=1031;var RX=1033,k9=33776,q9=33777,Z9=33778,I9=33779,VX=35840,wX=35841,MX=35842,BX=35843,PX=36196,zX=37492,_X=37496,AX=37488,CX=37489,D9=37490,SX=37491,TX=37808,vX=37809,jX=37810,gX=37811,bX=37812,yX=37813,xX=37814,hX=37815,fX=37816,uX=37817,lX=37818,mX=37819,pX=37820,dX=37821,cX=36492,nX=36494,iX=36495,oX=36283,rX=36284,F9=36285,aX=36286;var sX=2300,L9=2301;var tX=0,PW=1,R8=2;var eX=0,hq=1,T0="",aJ="srgb",RU="srgb-linear",$H="linear",R6="srgb";var fq=512,uq=513,lq=514,R9=515,mq=516,pq=517,V9=518,dq=519;var UH="300 es",JH=2000;function KF($){for(let U=$.length-1;U>=0;--U)if($[U]>=65535)return!0;return!1}function XF($){return ArrayBuffer.isView($)&&!($ instanceof DataView)}function G8($){return document.createElementNS("http://www.w3.org/1999/xhtml",$)}function cq(){let $=G8("canvas");return $.style.display="block",$}var Zk={},O8=null;function LW(...$){let U="THREE."+$.shift();if(O8)O8("log",U,...$);else console.log(U,...$)}function nq($){let U=$[0];if(typeof U==="string"&&U.startsWith("TSL:")){let J=$[1];if(J&&J.isStackTrace)$[0]+=" "+J.getLocation();else $[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return $}function A$(...$){$=nq($);let U="THREE."+$.shift();if(O8)O8("warn",U,...$);else{let J=$[0];if(J&&J.isStackTrace)console.warn(J.getError(U));else console.warn(U,...$)}}function x$(...$){$=nq($);let U="THREE."+$.shift();if(O8)O8("error",U,...$);else{let J=$[0];if(J&&J.isStackTrace)console.error(J.getError(U));else console.error(U,...$)}}function M0(...$){let U=$.join(" ");if(U in Zk)return;Zk[U]=!0,A$(...$)}function iq($,U,J){return new Promise(function(Q,W){function K(){switch($.clientWaitSync(U,$.SYNC_FLUSH_COMMANDS_BIT,0)){case $.WAIT_FAILED:W();break;case $.TIMEOUT_EXPIRED:setTimeout(K,J);break;default:Q()}}setTimeout(K,J)})}var oq={[0]:1,[2]:6,[4]:7,[3]:5,[1]:0,[6]:2,[7]:4,[5]:3};class iU{addEventListener($,U){if(this._listeners===void 0)this._listeners={};let J=this._listeners;if(J[$]===void 0)J[$]=[];if(J[$].indexOf(U)===-1)J[$].push(U)}hasEventListener($,U){let J=this._listeners;if(J===void 0)return!1;return J[$]!==void 0&&J[$].indexOf(U)!==-1}removeEventListener($,U){let J=this._listeners;if(J===void 0)return;let Q=J[$];if(Q!==void 0){let W=Q.indexOf(U);if(W!==-1)Q.splice(W,1)}}dispatchEvent($){let U=this._listeners;if(U===void 0)return;let J=U[$.type];if(J!==void 0){$.target=this;let Q=J.slice(0);for(let W=0,K=Q.length;W<K;W++)Q[W].call(this,$);$.target=null}}}var t6=["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"],Ik=1234567,DW=Math.PI/180,B0=180/Math.PI;function pU(){let $=Math.random()*4294967295|0,U=Math.random()*4294967295|0,J=Math.random()*4294967295|0,Q=Math.random()*4294967295|0;return(t6[$&255]+t6[$>>8&255]+t6[$>>16&255]+t6[$>>24&255]+"-"+t6[U&255]+t6[U>>8&255]+"-"+t6[U>>16&15|64]+t6[U>>24&255]+"-"+t6[J&63|128]+t6[J>>8&255]+"-"+t6[J>>16&255]+t6[J>>24&255]+t6[Q&255]+t6[Q>>8&255]+t6[Q>>16&255]+t6[Q>>24&255]).toLowerCase()}function a$($,U,J){return Math.max(U,Math.min(J,$))}function WH($,U){return($%U+U)%U}function HF($,U,J,Q,W){return Q+($-U)*(W-Q)/(J-U)}function NF($,U,J){if($!==U)return(J-$)/(U-$);else return 0}function FW($,U,J){return(1-J)*$+J*U}function YF($,U,J,Q){return FW($,U,1-Math.exp(-J*Q))}function GF($,U=1){return U-Math.abs(WH($,U*2)-U)}function OF($,U,J){if($<=U)return 0;if($>=J)return 1;return $=($-U)/(J-U),$*$*(3-2*$)}function EF($,U,J){if($<=U)return 0;if($>=J)return 1;return $=($-U)/(J-U),$*$*$*($*($*6-15)+10)}function kF($,U){return $+Math.floor(Math.random()*(U-$+1))}function qF($,U){return $+Math.random()*(U-$)}function ZF($){return $*(0.5-Math.random())}function IF($){if($!==void 0)Ik=$;let U=Ik+=1831565813;return U=Math.imul(U^U>>>15,U|1),U^=U+Math.imul(U^U>>>7,U|61),((U^U>>>14)>>>0)/4294967296}function DF($){return $*DW}function FF($){return $*B0}function LF($){return($&$-1)===0&&$!==0}function RF($){return Math.pow(2,Math.ceil(Math.log($)/Math.LN2))}function VF($){return Math.pow(2,Math.floor(Math.log($)/Math.LN2))}function wF($,U,J,Q,W){let{cos:K,sin:X}=Math,H=K(J/2),N=X(J/2),Y=K((U+Q)/2),G=X((U+Q)/2),O=K((U-Q)/2),E=X((U-Q)/2),k=K((Q-U)/2),I=X((Q-U)/2);switch(W){case"XYX":$.set(H*G,N*O,N*E,H*Y);break;case"YZY":$.set(N*E,H*G,N*O,H*Y);break;case"ZXZ":$.set(N*O,N*E,H*G,H*Y);break;case"XZX":$.set(H*G,N*I,N*k,H*Y);break;case"YXY":$.set(N*k,H*G,N*I,H*Y);break;case"ZYZ":$.set(N*I,N*k,H*G,H*Y);break;default:A$("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+W)}}function mU($,U){switch(U.constructor){case Float32Array:return $;case Uint32Array:return $/4294967295;case Uint16Array:return $/65535;case Uint8Array:return $/255;case Int32Array:return Math.max($/2147483647,-1);case Int16Array:return Math.max($/32767,-1);case Int8Array:return Math.max($/127,-1);default:throw Error("THREE.MathUtils: Invalid component type.")}}function O6($,U){switch(U.constructor){case Float32Array:return $;case Uint32Array:return Math.round($*4294967295);case Uint16Array:return Math.round($*65535);case Uint8Array:return Math.round($*255);case Int32Array:return Math.round($*2147483647);case Int16Array:return Math.round($*32767);case Int8Array:return Math.round($*127);default:throw Error("THREE.MathUtils: Invalid component type.")}}var zW={DEG2RAD:DW,RAD2DEG:B0,generateUUID:pU,clamp:a$,euclideanModulo:WH,mapLinear:HF,inverseLerp:NF,lerp:FW,damp:YF,pingpong:GF,smoothstep:OF,smootherstep:EF,randInt:kF,randFloat:qF,randFloatSpread:ZF,seededRandom:IF,degToRad:DF,radToDeg:FF,isPowerOfTwo:LF,ceilPowerOfTwo:RF,floorPowerOfTwo:VF,setQuaternionFromProperEuler:wF,normalize:O6,denormalize:mU};class g${static{g$.prototype.isVector2=!0}constructor($=0,U=0){this.x=$,this.y=U}get width(){return this.x}set width($){this.x=$}get height(){return this.y}set height($){this.y=$}set($,U){return this.x=$,this.y=U,this}setScalar($){return this.x=$,this.y=$,this}setX($){return this.x=$,this}setY($){return this.y=$,this}setComponent($,U){switch($){case 0:this.x=U;break;case 1:this.y=U;break;default:throw Error("THREE.Vector2: index is out of range: "+$)}return this}getComponent($){switch($){case 0:return this.x;case 1:return this.y;default:throw Error("THREE.Vector2: index is out of range: "+$)}}clone(){return new this.constructor(this.x,this.y)}copy($){return this.x=$.x,this.y=$.y,this}add($){return this.x+=$.x,this.y+=$.y,this}addScalar($){return this.x+=$,this.y+=$,this}addVectors($,U){return this.x=$.x+U.x,this.y=$.y+U.y,this}addScaledVector($,U){return this.x+=$.x*U,this.y+=$.y*U,this}sub($){return this.x-=$.x,this.y-=$.y,this}subScalar($){return this.x-=$,this.y-=$,this}subVectors($,U){return this.x=$.x-U.x,this.y=$.y-U.y,this}multiply($){return this.x*=$.x,this.y*=$.y,this}multiplyScalar($){return this.x*=$,this.y*=$,this}divide($){return this.x/=$.x,this.y/=$.y,this}divideScalar($){return this.multiplyScalar(1/$)}applyMatrix3($){let U=this.x,J=this.y,Q=$.elements;return this.x=Q[0]*U+Q[3]*J+Q[6],this.y=Q[1]*U+Q[4]*J+Q[7],this}min($){return this.x=Math.min(this.x,$.x),this.y=Math.min(this.y,$.y),this}max($){return this.x=Math.max(this.x,$.x),this.y=Math.max(this.y,$.y),this}clamp($,U){return this.x=a$(this.x,$.x,U.x),this.y=a$(this.y,$.y,U.y),this}clampScalar($,U){return this.x=a$(this.x,$,U),this.y=a$(this.y,$,U),this}clampLength($,U){let J=this.length();return this.divideScalar(J||1).multiplyScalar(a$(J,$,U))}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($){return this.x*$.x+this.y*$.y}cross($){return this.x*$.y-this.y*$.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($){let U=Math.sqrt(this.lengthSq()*$.lengthSq());if(U===0)return Math.PI/2;let J=this.dot($)/U;return Math.acos(a$(J,-1,1))}distanceTo($){return Math.sqrt(this.distanceToSquared($))}distanceToSquared($){let U=this.x-$.x,J=this.y-$.y;return U*U+J*J}manhattanDistanceTo($){return Math.abs(this.x-$.x)+Math.abs(this.y-$.y)}setLength($){return this.normalize().multiplyScalar($)}lerp($,U){return this.x+=($.x-this.x)*U,this.y+=($.y-this.y)*U,this}lerpVectors($,U,J){return this.x=$.x+(U.x-$.x)*J,this.y=$.y+(U.y-$.y)*J,this}equals($){return $.x===this.x&&$.y===this.y}fromArray($,U=0){return this.x=$[U],this.y=$[U+1],this}toArray($=[],U=0){return $[U]=this.x,$[U+1]=this.y,$}fromBufferAttribute($,U){return this.x=$.getX(U),this.y=$.getY(U),this}rotateAround($,U){let J=Math.cos(U),Q=Math.sin(U),W=this.x-$.x,K=this.y-$.y;return this.x=W*J-K*Q+$.x,this.y=W*Q+K*J+$.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class c6{constructor($=0,U=0,J=0,Q=1){this.isQuaternion=!0,this._x=$,this._y=U,this._z=J,this._w=Q}static slerpFlat($,U,J,Q,W,K,X){let H=J[Q+0],N=J[Q+1],Y=J[Q+2],G=J[Q+3],O=W[K+0],E=W[K+1],k=W[K+2],I=W[K+3];if(G!==I||H!==O||N!==E||Y!==k){let R=H*O+N*E+Y*k+G*I;if(R<0)O=-O,E=-E,k=-k,I=-I,R=-R;let q=1-X;if(R<0.9995){let Z=Math.acos(R),_=Math.sin(Z);q=Math.sin(q*Z)/_,X=Math.sin(X*Z)/_,H=H*q+O*X,N=N*q+E*X,Y=Y*q+k*X,G=G*q+I*X}else{H=H*q+O*X,N=N*q+E*X,Y=Y*q+k*X,G=G*q+I*X;let Z=1/Math.sqrt(H*H+N*N+Y*Y+G*G);H*=Z,N*=Z,Y*=Z,G*=Z}}$[U]=H,$[U+1]=N,$[U+2]=Y,$[U+3]=G}static multiplyQuaternionsFlat($,U,J,Q,W,K){let X=J[Q],H=J[Q+1],N=J[Q+2],Y=J[Q+3],G=W[K],O=W[K+1],E=W[K+2],k=W[K+3];return $[U]=X*k+Y*G+H*E-N*O,$[U+1]=H*k+Y*O+N*G-X*E,$[U+2]=N*k+Y*E+X*O-H*G,$[U+3]=Y*k-X*G-H*O-N*E,$}get x(){return this._x}set x($){this._x=$,this._onChangeCallback()}get y(){return this._y}set y($){this._y=$,this._onChangeCallback()}get z(){return this._z}set z($){this._z=$,this._onChangeCallback()}get w(){return this._w}set w($){this._w=$,this._onChangeCallback()}set($,U,J,Q){return this._x=$,this._y=U,this._z=J,this._w=Q,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy($){return this._x=$.x,this._y=$.y,this._z=$.z,this._w=$.w,this._onChangeCallback(),this}setFromEuler($,U=!0){let{_x:J,_y:Q,_z:W,_order:K}=$,X=Math.cos,H=Math.sin,N=X(J/2),Y=X(Q/2),G=X(W/2),O=H(J/2),E=H(Q/2),k=H(W/2);switch(K){case"XYZ":this._x=O*Y*G+N*E*k,this._y=N*E*G-O*Y*k,this._z=N*Y*k+O*E*G,this._w=N*Y*G-O*E*k;break;case"YXZ":this._x=O*Y*G+N*E*k,this._y=N*E*G-O*Y*k,this._z=N*Y*k-O*E*G,this._w=N*Y*G+O*E*k;break;case"ZXY":this._x=O*Y*G-N*E*k,this._y=N*E*G+O*Y*k,this._z=N*Y*k+O*E*G,this._w=N*Y*G-O*E*k;break;case"ZYX":this._x=O*Y*G-N*E*k,this._y=N*E*G+O*Y*k,this._z=N*Y*k-O*E*G,this._w=N*Y*G+O*E*k;break;case"YZX":this._x=O*Y*G+N*E*k,this._y=N*E*G+O*Y*k,this._z=N*Y*k-O*E*G,this._w=N*Y*G-O*E*k;break;case"XZY":this._x=O*Y*G-N*E*k,this._y=N*E*G-O*Y*k,this._z=N*Y*k+O*E*G,this._w=N*Y*G+O*E*k;break;default:A$("Quaternion: .setFromEuler() encountered an unknown order: "+K)}if(U===!0)this._onChangeCallback();return this}setFromAxisAngle($,U){let J=U/2,Q=Math.sin(J);return this._x=$.x*Q,this._y=$.y*Q,this._z=$.z*Q,this._w=Math.cos(J),this._onChangeCallback(),this}setFromRotationMatrix($){let U=$.elements,J=U[0],Q=U[4],W=U[8],K=U[1],X=U[5],H=U[9],N=U[2],Y=U[6],G=U[10],O=J+X+G;if(O>0){let E=0.5/Math.sqrt(O+1);this._w=0.25/E,this._x=(Y-H)*E,this._y=(W-N)*E,this._z=(K-Q)*E}else if(J>X&&J>G){let E=2*Math.sqrt(1+J-X-G);this._w=(Y-H)/E,this._x=0.25*E,this._y=(Q+K)/E,this._z=(W+N)/E}else if(X>G){let E=2*Math.sqrt(1+X-J-G);this._w=(W-N)/E,this._x=(Q+K)/E,this._y=0.25*E,this._z=(H+Y)/E}else{let E=2*Math.sqrt(1+G-J-X);this._w=(K-Q)/E,this._x=(W+N)/E,this._y=(H+Y)/E,this._z=0.25*E}return this._onChangeCallback(),this}setFromUnitVectors($,U){let J=$.dot(U)+1;if(J<0.00000001)if(J=0,Math.abs($.x)>Math.abs($.z))this._x=-$.y,this._y=$.x,this._z=0,this._w=J;else this._x=0,this._y=-$.z,this._z=$.y,this._w=J;else this._x=$.y*U.z-$.z*U.y,this._y=$.z*U.x-$.x*U.z,this._z=$.x*U.y-$.y*U.x,this._w=J;return this.normalize()}angleTo($){return 2*Math.acos(Math.abs(a$(this.dot($),-1,1)))}rotateTowards($,U){let J=this.angleTo($);if(J===0)return this;let Q=Math.min(1,U/J);return this.slerp($,Q),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($){return this._x*$._x+this._y*$._y+this._z*$._z+this._w*$._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 $=this.length();if($===0)this._x=0,this._y=0,this._z=0,this._w=1;else $=1/$,this._x=this._x*$,this._y=this._y*$,this._z=this._z*$,this._w=this._w*$;return this._onChangeCallback(),this}multiply($){return this.multiplyQuaternions(this,$)}premultiply($){return this.multiplyQuaternions($,this)}multiplyQuaternions($,U){let{_x:J,_y:Q,_z:W,_w:K}=$,X=U._x,H=U._y,N=U._z,Y=U._w;return this._x=J*Y+K*X+Q*N-W*H,this._y=Q*Y+K*H+W*X-J*N,this._z=W*Y+K*N+J*H-Q*X,this._w=K*Y-J*X-Q*H-W*N,this._onChangeCallback(),this}slerp($,U){let{_x:J,_y:Q,_z:W,_w:K}=$,X=this.dot($);if(X<0)J=-J,Q=-Q,W=-W,K=-K,X=-X;let H=1-U;if(X<0.9995){let N=Math.acos(X),Y=Math.sin(N);H=Math.sin(H*N)/Y,U=Math.sin(U*N)/Y,this._x=this._x*H+J*U,this._y=this._y*H+Q*U,this._z=this._z*H+W*U,this._w=this._w*H+K*U,this._onChangeCallback()}else this._x=this._x*H+J*U,this._y=this._y*H+Q*U,this._z=this._z*H+W*U,this._w=this._w*H+K*U,this.normalize();return this}slerpQuaternions($,U,J){return this.copy($).slerp(U,J)}random(){let $=2*Math.PI*Math.random(),U=2*Math.PI*Math.random(),J=Math.random(),Q=Math.sqrt(1-J),W=Math.sqrt(J);return this.set(Q*Math.sin($),Q*Math.cos($),W*Math.sin(U),W*Math.cos(U))}equals($){return $._x===this._x&&$._y===this._y&&$._z===this._z&&$._w===this._w}fromArray($,U=0){return this._x=$[U],this._y=$[U+1],this._z=$[U+2],this._w=$[U+3],this._onChangeCallback(),this}toArray($=[],U=0){return $[U]=this._x,$[U+1]=this._y,$[U+2]=this._z,$[U+3]=this._w,$}fromBufferAttribute($,U){return this._x=$.getX(U),this._y=$.getY(U),this._z=$.getZ(U),this._w=$.getW(U),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange($){return this._onChangeCallback=$,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class j{static{j.prototype.isVector3=!0}constructor($=0,U=0,J=0){this.x=$,this.y=U,this.z=J}set($,U,J){if(J===void 0)J=this.z;return this.x=$,this.y=U,this.z=J,this}setScalar($){return this.x=$,this.y=$,this.z=$,this}setX($){return this.x=$,this}setY($){return this.y=$,this}setZ($){return this.z=$,this}setComponent($,U){switch($){case 0:this.x=U;break;case 1:this.y=U;break;case 2:this.z=U;break;default:throw Error("THREE.Vector3: index is out of range: "+$)}return this}getComponent($){switch($){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("THREE.Vector3: index is out of range: "+$)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy($){return this.x=$.x,this.y=$.y,this.z=$.z,this}add($){return this.x+=$.x,this.y+=$.y,this.z+=$.z,this}addScalar($){return this.x+=$,this.y+=$,this.z+=$,this}addVectors($,U){return this.x=$.x+U.x,this.y=$.y+U.y,this.z=$.z+U.z,this}addScaledVector($,U){return this.x+=$.x*U,this.y+=$.y*U,this.z+=$.z*U,this}sub($){return this.x-=$.x,this.y-=$.y,this.z-=$.z,this}subScalar($){return this.x-=$,this.y-=$,this.z-=$,this}subVectors($,U){return this.x=$.x-U.x,this.y=$.y-U.y,this.z=$.z-U.z,this}multiply($){return this.x*=$.x,this.y*=$.y,this.z*=$.z,this}multiplyScalar($){return this.x*=$,this.y*=$,this.z*=$,this}multiplyVectors($,U){return this.x=$.x*U.x,this.y=$.y*U.y,this.z=$.z*U.z,this}applyEuler($){return this.applyQuaternion(Dk.setFromEuler($))}applyAxisAngle($,U){return this.applyQuaternion(Dk.setFromAxisAngle($,U))}applyMatrix3($){let U=this.x,J=this.y,Q=this.z,W=$.elements;return this.x=W[0]*U+W[3]*J+W[6]*Q,this.y=W[1]*U+W[4]*J+W[7]*Q,this.z=W[2]*U+W[5]*J+W[8]*Q,this}applyNormalMatrix($){return this.applyMatrix3($).normalize()}applyMatrix4($){let U=this.x,J=this.y,Q=this.z,W=$.elements,K=1/(W[3]*U+W[7]*J+W[11]*Q+W[15]);return this.x=(W[0]*U+W[4]*J+W[8]*Q+W[12])*K,this.y=(W[1]*U+W[5]*J+W[9]*Q+W[13])*K,this.z=(W[2]*U+W[6]*J+W[10]*Q+W[14])*K,this}applyQuaternion($){let U=this.x,J=this.y,Q=this.z,W=$.x,K=$.y,X=$.z,H=$.w,N=2*(K*Q-X*J),Y=2*(X*U-W*Q),G=2*(W*J-K*U);return this.x=U+H*N+K*G-X*Y,this.y=J+H*Y+X*N-W*G,this.z=Q+H*G+W*Y-K*N,this}project($){return this.applyMatrix4($.matrixWorldInverse).applyMatrix4($.projectionMatrix)}unproject($){return this.applyMatrix4($.projectionMatrixInverse).applyMatrix4($.matrixWorld)}transformDirection($){let U=this.x,J=this.y,Q=this.z,W=$.elements;return this.x=W[0]*U+W[4]*J+W[8]*Q,this.y=W[1]*U+W[5]*J+W[9]*Q,this.z=W[2]*U+W[6]*J+W[10]*Q,this.normalize()}divide($){return this.x/=$.x,this.y/=$.y,this.z/=$.z,this}divideScalar($){return this.multiplyScalar(1/$)}min($){return this.x=Math.min(this.x,$.x),this.y=Math.min(this.y,$.y),this.z=Math.min(this.z,$.z),this}max($){return this.x=Math.max(this.x,$.x),this.y=Math.max(this.y,$.y),this.z=Math.max(this.z,$.z),this}clamp($,U){return this.x=a$(this.x,$.x,U.x),this.y=a$(this.y,$.y,U.y),this.z=a$(this.z,$.z,U.z),this}clampScalar($,U){return this.x=a$(this.x,$,U),this.y=a$(this.y,$,U),this.z=a$(this.z,$,U),this}clampLength($,U){let J=this.length();return this.divideScalar(J||1).multiplyScalar(a$(J,$,U))}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($){return this.x*$.x+this.y*$.y+this.z*$.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($){return this.normalize().multiplyScalar($)}lerp($,U){return this.x+=($.x-this.x)*U,this.y+=($.y-this.y)*U,this.z+=($.z-this.z)*U,this}lerpVectors($,U,J){return this.x=$.x+(U.x-$.x)*J,this.y=$.y+(U.y-$.y)*J,this.z=$.z+(U.z-$.z)*J,this}cross($){return this.crossVectors(this,$)}crossVectors($,U){let{x:J,y:Q,z:W}=$,K=U.x,X=U.y,H=U.z;return this.x=Q*H-W*X,this.y=W*K-J*H,this.z=J*X-Q*K,this}projectOnVector($){let U=$.lengthSq();if(U===0)return this.set(0,0,0);let J=$.dot(this)/U;return this.copy($).multiplyScalar(J)}projectOnPlane($){return T7.copy(this).projectOnVector($),this.sub(T7)}reflect($){return this.sub(T7.copy($).multiplyScalar(2*this.dot($)))}angleTo($){let U=Math.sqrt(this.lengthSq()*$.lengthSq());if(U===0)return Math.PI/2;let J=this.dot($)/U;return Math.acos(a$(J,-1,1))}distanceTo($){return Math.sqrt(this.distanceToSquared($))}distanceToSquared($){let U=this.x-$.x,J=this.y-$.y,Q=this.z-$.z;return U*U+J*J+Q*Q}manhattanDistanceTo($){return Math.abs(this.x-$.x)+Math.abs(this.y-$.y)+Math.abs(this.z-$.z)}setFromSpherical($){return this.setFromSphericalCoords($.radius,$.phi,$.theta)}setFromSphericalCoords($,U,J){let Q=Math.sin(U)*$;return this.x=Q*Math.sin(J),this.y=Math.cos(U)*$,this.z=Q*Math.cos(J),this}setFromCylindrical($){return this.setFromCylindricalCoords($.radius,$.theta,$.y)}setFromCylindricalCoords($,U,J){return this.x=$*Math.sin(U),this.y=J,this.z=$*Math.cos(U),this}setFromMatrixPosition($){let U=$.elements;return this.x=U[12],this.y=U[13],this.z=U[14],this}setFromMatrixScale($){let U=this.setFromMatrixColumn($,0).length(),J=this.setFromMatrixColumn($,1).length(),Q=this.setFromMatrixColumn($,2).length();return this.x=U,this.y=J,this.z=Q,this}setFromMatrixColumn($,U){return this.fromArray($.elements,U*4)}setFromMatrix3Column($,U){return this.fromArray($.elements,U*3)}setFromEuler($){return this.x=$._x,this.y=$._y,this.z=$._z,this}setFromColor($){return this.x=$.r,this.y=$.g,this.z=$.b,this}equals($){return $.x===this.x&&$.y===this.y&&$.z===this.z}fromArray($,U=0){return this.x=$[U],this.y=$[U+1],this.z=$[U+2],this}toArray($=[],U=0){return $[U]=this.x,$[U+1]=this.y,$[U+2]=this.z,$}fromBufferAttribute($,U){return this.x=$.getX(U),this.y=$.getY(U),this.z=$.getZ(U),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let $=Math.random()*Math.PI*2,U=Math.random()*2-1,J=Math.sqrt(1-U*U);return this.x=J*Math.cos($),this.y=U,this.z=J*Math.sin($),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}var T7=new j,Dk=new c6;class f${static{f$.prototype.isMatrix3=!0}constructor($,U,J,Q,W,K,X,H,N){if(this.elements=[1,0,0,0,1,0,0,0,1],$!==void 0)this.set($,U,J,Q,W,K,X,H,N)}set($,U,J,Q,W,K,X,H,N){let Y=this.elements;return Y[0]=$,Y[1]=Q,Y[2]=X,Y[3]=U,Y[4]=W,Y[5]=H,Y[6]=J,Y[7]=K,Y[8]=N,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy($){let U=this.elements,J=$.elements;return U[0]=J[0],U[1]=J[1],U[2]=J[2],U[3]=J[3],U[4]=J[4],U[5]=J[5],U[6]=J[6],U[7]=J[7],U[8]=J[8],this}extractBasis($,U,J){return $.setFromMatrix3Column(this,0),U.setFromMatrix3Column(this,1),J.setFromMatrix3Column(this,2),this}setFromMatrix4($){let U=$.elements;return this.set(U[0],U[4],U[8],U[1],U[5],U[9],U[2],U[6],U[10]),this}multiply($){return this.multiplyMatrices(this,$)}premultiply($){return this.multiplyMatrices($,this)}multiplyMatrices($,U){let J=$.elements,Q=U.elements,W=this.elements,K=J[0],X=J[3],H=J[6],N=J[1],Y=J[4],G=J[7],O=J[2],E=J[5],k=J[8],I=Q[0],R=Q[3],q=Q[6],Z=Q[1],_=Q[4],P=Q[7],L=Q[2],B=Q[5],z=Q[8];return W[0]=K*I+X*Z+H*L,W[3]=K*R+X*_+H*B,W[6]=K*q+X*P+H*z,W[1]=N*I+Y*Z+G*L,W[4]=N*R+Y*_+G*B,W[7]=N*q+Y*P+G*z,W[2]=O*I+E*Z+k*L,W[5]=O*R+E*_+k*B,W[8]=O*q+E*P+k*z,this}multiplyScalar($){let U=this.elements;return U[0]*=$,U[3]*=$,U[6]*=$,U[1]*=$,U[4]*=$,U[7]*=$,U[2]*=$,U[5]*=$,U[8]*=$,this}determinant(){let $=this.elements,U=$[0],J=$[1],Q=$[2],W=$[3],K=$[4],X=$[5],H=$[6],N=$[7],Y=$[8];return U*K*Y-U*X*N-J*W*Y+J*X*H+Q*W*N-Q*K*H}invert(){let $=this.elements,U=$[0],J=$[1],Q=$[2],W=$[3],K=$[4],X=$[5],H=$[6],N=$[7],Y=$[8],G=Y*K-X*N,O=X*H-Y*W,E=N*W-K*H,k=U*G+J*O+Q*E;if(k===0)return this.set(0,0,0,0,0,0,0,0,0);let I=1/k;return $[0]=G*I,$[1]=(Q*N-Y*J)*I,$[2]=(X*J-Q*K)*I,$[3]=O*I,$[4]=(Y*U-Q*H)*I,$[5]=(Q*W-X*U)*I,$[6]=E*I,$[7]=(J*H-N*U)*I,$[8]=(K*U-J*W)*I,this}transpose(){let $,U=this.elements;return $=U[1],U[1]=U[3],U[3]=$,$=U[2],U[2]=U[6],U[6]=$,$=U[5],U[5]=U[7],U[7]=$,this}getNormalMatrix($){return this.setFromMatrix4($).invert().transpose()}transposeIntoArray($){let U=this.elements;return $[0]=U[0],$[1]=U[3],$[2]=U[6],$[3]=U[1],$[4]=U[4],$[5]=U[7],$[6]=U[2],$[7]=U[5],$[8]=U[8],this}setUvTransform($,U,J,Q,W,K,X){let H=Math.cos(W),N=Math.sin(W);return this.set(J*H,J*N,-J*(H*K+N*X)+K+$,-Q*N,Q*H,-Q*(-N*K+H*X)+X+U,0,0,1),this}scale($,U){return M0("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(v7.makeScale($,U)),this}rotate($){return M0("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(v7.makeRotation(-$)),this}translate($,U){return M0("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(v7.makeTranslation($,U)),this}makeTranslation($,U){if($.isVector2)this.set(1,0,$.x,0,1,$.y,0,0,1);else this.set(1,0,$,0,1,U,0,0,1);return this}makeRotation($){let U=Math.cos($),J=Math.sin($);return this.set(U,-J,0,J,U,0,0,0,1),this}makeScale($,U){return this.set($,0,0,0,U,0,0,0,1),this}equals($){let U=this.elements,J=$.elements;for(let Q=0;Q<9;Q++)if(U[Q]!==J[Q])return!1;return!0}fromArray($,U=0){for(let J=0;J<9;J++)this.elements[J]=$[J+U];return this}toArray($=[],U=0){let J=this.elements;return $[U]=J[0],$[U+1]=J[1],$[U+2]=J[2],$[U+3]=J[3],$[U+4]=J[4],$[U+5]=J[5],$[U+6]=J[6],$[U+7]=J[7],$[U+8]=J[8],$}clone(){return new this.constructor().fromArray(this.elements)}}var v7=new f$,Fk=new f$().set(0.4123908,0.3575843,0.1804808,0.212639,0.7151687,0.0721923,0.0193308,0.1191948,0.9505322),Lk=new f$().set(3.2409699,-1.5373832,-0.4986108,-0.9692436,1.8759675,0.0415551,0.0556301,-0.203977,1.0569715);function MF(){let $={enabled:!0,workingColorSpace:"srgb-linear",spaces:{},convert:function(W,K,X){if(this.enabled===!1||K===X||!K||!X)return W;if(this.spaces[K].transfer==="srgb")W.r=_J(W.r),W.g=_J(W.g),W.b=_J(W.b);if(this.spaces[K].primaries!==this.spaces[X].primaries)W.applyMatrix3(this.spaces[K].toXYZ),W.applyMatrix3(this.spaces[X].fromXYZ);if(this.spaces[X].transfer==="srgb")W.r=Y8(W.r),W.g=Y8(W.g),W.b=Y8(W.b);return W},workingToColorSpace:function(W,K){return this.convert(W,this.workingColorSpace,K)},colorSpaceToWorking:function(W,K){return this.convert(W,K,this.workingColorSpace)},getPrimaries:function(W){return this.spaces[W].primaries},getTransfer:function(W){if(W==="")return"linear";return this.spaces[W].transfer},getToneMappingMode:function(W){return this.spaces[W].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(W,K=this.workingColorSpace){return W.fromArray(this.spaces[K].luminanceCoefficients)},define:function(W){Object.assign(this.spaces,W)},_getMatrix:function(W,K,X){return W.copy(this.spaces[K].toXYZ).multiply(this.spaces[X].fromXYZ)},_getDrawingBufferColorSpace:function(W){return this.spaces[W].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(W=this.workingColorSpace){return this.spaces[W].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(W,K){return M0("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),$.workingToColorSpace(W,K)},toWorkingColorSpace:function(W,K){return M0("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),$.colorSpaceToWorking(W,K)}},U=[0.64,0.33,0.3,0.6,0.15,0.06],J=[0.2126,0.7152,0.0722],Q=[0.3127,0.329];return $.define({["srgb-linear"]:{primaries:U,whitePoint:Q,transfer:"linear",toXYZ:Fk,fromXYZ:Lk,luminanceCoefficients:J,workingColorSpaceConfig:{unpackColorSpace:"srgb"},outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}},["srgb"]:{primaries:U,whitePoint:Q,transfer:"srgb",toXYZ:Fk,fromXYZ:Lk,luminanceCoefficients:J,outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}}}),$}var r$=MF();function _J($){return $<0.04045?$*0.0773993808:Math.pow($*0.9478672986+0.0521327014,2.4)}function Y8($){return $<0.0031308?$*12.92:1.055*Math.pow($,0.41666)-0.055}var r0;class QH{static getDataURL($,U="image/png"){if(/^data:/i.test($.src))return $.src;if(typeof HTMLCanvasElement>"u")return $.src;let J;if($ instanceof HTMLCanvasElement)J=$;else{if(r0===void 0)r0=G8("canvas");r0.width=$.width,r0.height=$.height;let Q=r0.getContext("2d");if($ instanceof ImageData)Q.putImageData($,0,0);else Q.drawImage($,0,0,$.width,$.height);J=r0}return J.toDataURL(U)}static sRGBToLinear($){if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap){let U=G8("canvas");U.width=$.width,U.height=$.height;let J=U.getContext("2d");J.drawImage($,0,0,$.width,$.height);let Q=J.getImageData(0,0,$.width,$.height),W=Q.data;for(let K=0;K<W.length;K++)W[K]=_J(W[K]/255)*255;return J.putImageData(Q,0,0),U}else if($.data){let U=$.data.slice(0);for(let J=0;J<U.length;J++)if(U instanceof Uint8Array||U instanceof Uint8ClampedArray)U[J]=Math.floor(_J(U[J]/255)*255);else U[J]=_J(U[J]);return{data:U,width:$.width,height:$.height}}else return A$("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),$}}var BF=0;class _W{constructor($=null){this.isSource=!0,Object.defineProperty(this,"id",{value:BF++}),this.uuid=pU(),this.data=$,this.dataReady=!0,this.version=0}getSize($){let U=this.data;if(typeof HTMLVideoElement<"u"&&U instanceof HTMLVideoElement)$.set(U.videoWidth,U.videoHeight,0);else if(typeof VideoFrame<"u"&&U instanceof VideoFrame)$.set(U.displayWidth,U.displayHeight,0);else if(U!==null)$.set(U.width,U.height,U.depth||0);else $.set(0,0,0);return $}set needsUpdate($){if($===!0)this.version++}toJSON($){let U=$===void 0||typeof $==="string";if(!U&&$.images[this.uuid]!==void 0)return $.images[this.uuid];let J={uuid:this.uuid,url:""},Q=this.data;if(Q!==null){let W;if(Array.isArray(Q)){W=[];for(let K=0,X=Q.length;K<X;K++)if(Q[K].isDataTexture)W.push(j7(Q[K].image));else W.push(j7(Q[K]))}else W=j7(Q);J.url=W}if(!U)$.images[this.uuid]=J;return J}}function j7($){if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap)return QH.getDataURL($);else if($.data)return{data:Array.from($.data),width:$.width,height:$.height,type:$.data.constructor.name};else return A$("Texture: Unable to serialize Texture."),{}}var PF=0,g7=new j;class C6 extends iU{constructor($=C6.DEFAULT_IMAGE,U=C6.DEFAULT_MAPPING,J=1001,Q=1001,W=1006,K=1008,X=1023,H=1009,N=C6.DEFAULT_ANISOTROPY,Y=""){super();this.isTexture=!0,Object.defineProperty(this,"id",{value:PF++}),this.uuid=pU(),this.name="",this.source=new _W($),this.mipmaps=[],this.mapping=U,this.channel=0,this.wrapS=J,this.wrapT=Q,this.magFilter=W,this.minFilter=K,this.anisotropy=N,this.format=X,this.internalFormat=null,this.type=H,this.offset=new g$(0,0),this.repeat=new g$(1,1),this.center=new g$(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new f$,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=Y,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=$&&$.depth&&$.depth>1?!0:!1,this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(g7).x}get height(){return this.source.getSize(g7).y}get depth(){return this.source.getSize(g7).z}get image(){return this.source.data}set image($){this.source.data=$}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($,U){this.updateRanges.push({start:$,count:U})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy($){return this.name=$.name,this.source=$.source,this.mipmaps=$.mipmaps.slice(0),this.mapping=$.mapping,this.channel=$.channel,this.wrapS=$.wrapS,this.wrapT=$.wrapT,this.magFilter=$.magFilter,this.minFilter=$.minFilter,this.anisotropy=$.anisotropy,this.format=$.format,this.internalFormat=$.internalFormat,this.type=$.type,this.normalized=$.normalized,this.offset.copy($.offset),this.repeat.copy($.repeat),this.center.copy($.center),this.rotation=$.rotation,this.matrixAutoUpdate=$.matrixAutoUpdate,this.matrix.copy($.matrix),this.generateMipmaps=$.generateMipmaps,this.premultiplyAlpha=$.premultiplyAlpha,this.flipY=$.flipY,this.unpackAlignment=$.unpackAlignment,this.colorSpace=$.colorSpace,this.renderTarget=$.renderTarget,this.isRenderTargetTexture=$.isRenderTargetTexture,this.isArrayTexture=$.isArrayTexture,this.userData=JSON.parse(JSON.stringify($.userData)),this.needsUpdate=!0,this}setValues($){for(let U in $){let J=$[U];if(J===void 0){A$(`Texture.setValues(): parameter '${U}' has value of undefined.`);continue}let Q=this[U];if(Q===void 0){A$(`Texture.setValues(): property '${U}' does not exist.`);continue}if(Q&&J&&(Q.isVector2&&J.isVector2))Q.copy(J);else if(Q&&J&&(Q.isVector3&&J.isVector3))Q.copy(J);else if(Q&&J&&(Q.isMatrix3&&J.isMatrix3))Q.copy(J);else this[U]=J}}toJSON($){let U=$===void 0||typeof $==="string";if(!U&&$.textures[this.uuid]!==void 0)return $.textures[this.uuid];let J={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON($).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};if(Object.keys(this.userData).length>0)J.userData=this.userData;if(!U)$.textures[this.uuid]=J;return J}dispose(){this.dispatchEvent({type:"dispose"})}transformUv($){if(this.mapping!==300)return $;if($.applyMatrix3(this.matrix),$.x<0||$.x>1)switch(this.wrapS){case 1000:$.x=$.x-Math.floor($.x);break;case 1001:$.x=$.x<0?0:1;break;case 1002:if(Math.abs(Math.floor($.x)%2)===1)$.x=Math.ceil($.x)-$.x;else $.x=$.x-Math.floor($.x);break}if($.y<0||$.y>1)switch(this.wrapT){case 1000:$.y=$.y-Math.floor($.y);break;case 1001:$.y=$.y<0?0:1;break;case 1002:if(Math.abs(Math.floor($.y)%2)===1)$.y=Math.ceil($.y)-$.y;else $.y=$.y-Math.floor($.y);break}if(this.flipY)$.y=1-$.y;return $}set needsUpdate($){if($===!0)this.version++,this.source.needsUpdate=!0}set needsPMREMUpdate($){if($===!0)this.pmremVersion++}}C6.DEFAULT_IMAGE=null;C6.DEFAULT_MAPPING=300;C6.DEFAULT_ANISOTROPY=1;class E6{static{E6.prototype.isVector4=!0}constructor($=0,U=0,J=0,Q=1){this.x=$,this.y=U,this.z=J,this.w=Q}get width(){return this.z}set width($){this.z=$}get height(){return this.w}set height($){this.w=$}set($,U,J,Q){return this.x=$,this.y=U,this.z=J,this.w=Q,this}setScalar($){return this.x=$,this.y=$,this.z=$,this.w=$,this}setX($){return this.x=$,this}setY($){return this.y=$,this}setZ($){return this.z=$,this}setW($){return this.w=$,this}setComponent($,U){switch($){case 0:this.x=U;break;case 1:this.y=U;break;case 2:this.z=U;break;case 3:this.w=U;break;default:throw Error("THREE.Vector4: index is out of range: "+$)}return this}getComponent($){switch($){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("THREE.Vector4: index is out of range: "+$)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy($){return this.x=$.x,this.y=$.y,this.z=$.z,this.w=$.w!==void 0?$.w:1,this}add($){return this.x+=$.x,this.y+=$.y,this.z+=$.z,this.w+=$.w,this}addScalar($){return this.x+=$,this.y+=$,this.z+=$,this.w+=$,this}addVectors($,U){return this.x=$.x+U.x,this.y=$.y+U.y,this.z=$.z+U.z,this.w=$.w+U.w,this}addScaledVector($,U){return this.x+=$.x*U,this.y+=$.y*U,this.z+=$.z*U,this.w+=$.w*U,this}sub($){return this.x-=$.x,this.y-=$.y,this.z-=$.z,this.w-=$.w,this}subScalar($){return this.x-=$,this.y-=$,this.z-=$,this.w-=$,this}subVectors($,U){return this.x=$.x-U.x,this.y=$.y-U.y,this.z=$.z-U.z,this.w=$.w-U.w,this}multiply($){return this.x*=$.x,this.y*=$.y,this.z*=$.z,this.w*=$.w,this}multiplyScalar($){return this.x*=$,this.y*=$,this.z*=$,this.w*=$,this}applyMatrix4($){let U=this.x,J=this.y,Q=this.z,W=this.w,K=$.elements;return this.x=K[0]*U+K[4]*J+K[8]*Q+K[12]*W,this.y=K[1]*U+K[5]*J+K[9]*Q+K[13]*W,this.z=K[2]*U+K[6]*J+K[10]*Q+K[14]*W,this.w=K[3]*U+K[7]*J+K[11]*Q+K[15]*W,this}divide($){return this.x/=$.x,this.y/=$.y,this.z/=$.z,this.w/=$.w,this}divideScalar($){return this.multiplyScalar(1/$)}setAxisAngleFromQuaternion($){this.w=2*Math.acos($.w);let U=Math.sqrt(1-$.w*$.w);if(U<0.0001)this.x=1,this.y=0,this.z=0;else this.x=$.x/U,this.y=$.y/U,this.z=$.z/U;return this}setAxisAngleFromRotationMatrix($){let U,J,Q,W,K=0.01,X=0.1,H=$.elements,N=H[0],Y=H[4],G=H[8],O=H[1],E=H[5],k=H[9],I=H[2],R=H[6],q=H[10];if(Math.abs(Y-O)<0.01&&Math.abs(G-I)<0.01&&Math.abs(k-R)<0.01){if(Math.abs(Y+O)<0.1&&Math.abs(G+I)<0.1&&Math.abs(k+R)<0.1&&Math.abs(N+E+q-3)<0.1)return this.set(1,0,0,0),this;U=Math.PI;let _=(N+1)/2,P=(E+1)/2,L=(q+1)/2,B=(Y+O)/4,z=(G+I)/4,A=(k+R)/4;if(_>P&&_>L)if(_<0.01)J=0,Q=0.707106781,W=0.707106781;else J=Math.sqrt(_),Q=B/J,W=z/J;else if(P>L)if(P<0.01)J=0.707106781,Q=0,W=0.707106781;else Q=Math.sqrt(P),J=B/Q,W=A/Q;else if(L<0.01)J=0.707106781,Q=0.707106781,W=0;else W=Math.sqrt(L),J=z/W,Q=A/W;return this.set(J,Q,W,U),this}let Z=Math.sqrt((R-k)*(R-k)+(G-I)*(G-I)+(O-Y)*(O-Y));if(Math.abs(Z)<0.001)Z=1;return this.x=(R-k)/Z,this.y=(G-I)/Z,this.z=(O-Y)/Z,this.w=Math.acos((N+E+q-1)/2),this}setFromMatrixPosition($){let U=$.elements;return this.x=U[12],this.y=U[13],this.z=U[14],this.w=U[15],this}min($){return this.x=Math.min(this.x,$.x),this.y=Math.min(this.y,$.y),this.z=Math.min(this.z,$.z),this.w=Math.min(this.w,$.w),this}max($){return this.x=Math.max(this.x,$.x),this.y=Math.max(this.y,$.y),this.z=Math.max(this.z,$.z),this.w=Math.max(this.w,$.w),this}clamp($,U){return this.x=a$(this.x,$.x,U.x),this.y=a$(this.y,$.y,U.y),this.z=a$(this.z,$.z,U.z),this.w=a$(this.w,$.w,U.w),this}clampScalar($,U){return this.x=a$(this.x,$,U),this.y=a$(this.y,$,U),this.z=a$(this.z,$,U),this.w=a$(this.w,$,U),this}clampLength($,U){let J=this.length();return this.divideScalar(J||1).multiplyScalar(a$(J,$,U))}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($){return this.x*$.x+this.y*$.y+this.z*$.z+this.w*$.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($){return this.normalize().multiplyScalar($)}lerp($,U){return this.x+=($.x-this.x)*U,this.y+=($.y-this.y)*U,this.z+=($.z-this.z)*U,this.w+=($.w-this.w)*U,this}lerpVectors($,U,J){return this.x=$.x+(U.x-$.x)*J,this.y=$.y+(U.y-$.y)*J,this.z=$.z+(U.z-$.z)*J,this.w=$.w+(U.w-$.w)*J,this}equals($){return $.x===this.x&&$.y===this.y&&$.z===this.z&&$.w===this.w}fromArray($,U=0){return this.x=$[U],this.y=$[U+1],this.z=$[U+2],this.w=$[U+3],this}toArray($=[],U=0){return $[U]=this.x,$[U+1]=this.y,$[U+2]=this.z,$[U+3]=this.w,$}fromBufferAttribute($,U){return this.x=$.getX(U),this.y=$.getY(U),this.z=$.getZ(U),this.w=$.getW(U),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}}class KH extends iU{constructor($=1,U=1,J={}){super();J=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},J),this.isRenderTarget=!0,this.width=$,this.height=U,this.depth=J.depth,this.scissor=new E6(0,0,$,U),this.scissorTest=!1,this.viewport=new E6(0,0,$,U),this.textures=[];let Q={width:$,height:U,depth:J.depth},W=new C6(Q),K=J.count;for(let X=0;X<K;X++)this.textures[X]=W.clone(),this.textures[X].isRenderTargetTexture=!0,this.textures[X].renderTarget=this;this._setTextureOptions(J),this.depthBuffer=J.depthBuffer,this.stencilBuffer=J.stencilBuffer,this.resolveDepthBuffer=J.resolveDepthBuffer,this.resolveStencilBuffer=J.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=J.depthTexture,this.samples=J.samples,this.multiview=J.multiview,this.useArrayDepthTexture=J.useArrayDepthTexture}_setTextureOptions($={}){let U={minFilter:1006,generateMipmaps:!1,flipY:!1,internalFormat:null};if($.mapping!==void 0)U.mapping=$.mapping;if($.wrapS!==void 0)U.wrapS=$.wrapS;if($.wrapT!==void 0)U.wrapT=$.wrapT;if($.wrapR!==void 0)U.wrapR=$.wrapR;if($.magFilter!==void 0)U.magFilter=$.magFilter;if($.minFilter!==void 0)U.minFilter=$.minFilter;if($.format!==void 0)U.format=$.format;if($.type!==void 0)U.type=$.type;if($.anisotropy!==void 0)U.anisotropy=$.anisotropy;if($.colorSpace!==void 0)U.colorSpace=$.colorSpace;if($.flipY!==void 0)U.flipY=$.flipY;if($.generateMipmaps!==void 0)U.generateMipmaps=$.generateMipmaps;if($.internalFormat!==void 0)U.internalFormat=$.internalFormat;for(let J=0;J<this.textures.length;J++)this.textures[J].setValues(U)}get texture(){return this.textures[0]}set texture($){this.textures[0]=$}set depthTexture($){if(this._depthTexture!==null)this._depthTexture.renderTarget=null;if($!==null)$.renderTarget=this;this._depthTexture=$}get depthTexture(){return this._depthTexture}setSize($,U,J=1){if(this.width!==$||this.height!==U||this.depth!==J){this.width=$,this.height=U,this.depth=J;for(let Q=0,W=this.textures.length;Q<W;Q++)if(this.textures[Q].image.width=$,this.textures[Q].image.height=U,this.textures[Q].image.depth=J,this.textures[Q].isData3DTexture!==!0)this.textures[Q].isArrayTexture=this.textures[Q].image.depth>1;this.dispose()}this.viewport.set(0,0,$,U),this.scissor.set(0,0,$,U)}clone(){return new this.constructor().copy(this)}copy($){this.width=$.width,this.height=$.height,this.depth=$.depth,this.scissor.copy($.scissor),this.scissorTest=$.scissorTest,this.viewport.copy($.viewport),this.textures.length=0;for(let U=0,J=$.textures.length;U<J;U++){this.textures[U]=$.textures[U].clone(),this.textures[U].isRenderTargetTexture=!0,this.textures[U].renderTarget=this;let Q=Object.assign({},$.textures[U].image);this.textures[U].source=new _W(Q)}if(this.depthBuffer=$.depthBuffer,this.stencilBuffer=$.stencilBuffer,this.resolveDepthBuffer=$.resolveDepthBuffer,this.resolveStencilBuffer=$.resolveStencilBuffer,$.depthTexture!==null)this.depthTexture=$.depthTexture.clone();return this.samples=$.samples,this.multiview=$.multiview,this.useArrayDepthTexture=$.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class jU extends KH{constructor($=1,U=1,J={}){super($,U,J);this.isWebGLRenderTarget=!0}}class w9 extends C6{constructor($=null,U=1,J=1,Q=1){super(null);this.isDataArrayTexture=!0,this.image={data:$,width:U,height:J,depth:Q},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate($){this.layerUpdates.add($)}clearLayerUpdates(){this.layerUpdates.clear()}}class XH extends C6{constructor($=null,U=1,J=1,Q=1){super(null);this.isData3DTexture=!0,this.image={data:$,width:U,height:J,depth:Q},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class m${static{m$.prototype.isMatrix4=!0}constructor($,U,J,Q,W,K,X,H,N,Y,G,O,E,k,I,R){if(this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],$!==void 0)this.set($,U,J,Q,W,K,X,H,N,Y,G,O,E,k,I,R)}set($,U,J,Q,W,K,X,H,N,Y,G,O,E,k,I,R){let q=this.elements;return q[0]=$,q[4]=U,q[8]=J,q[12]=Q,q[1]=W,q[5]=K,q[9]=X,q[13]=H,q[2]=N,q[6]=Y,q[10]=G,q[14]=O,q[3]=E,q[7]=k,q[11]=I,q[15]=R,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 m$().fromArray(this.elements)}copy($){let U=this.elements,J=$.elements;return U[0]=J[0],U[1]=J[1],U[2]=J[2],U[3]=J[3],U[4]=J[4],U[5]=J[5],U[6]=J[6],U[7]=J[7],U[8]=J[8],U[9]=J[9],U[10]=J[10],U[11]=J[11],U[12]=J[12],U[13]=J[13],U[14]=J[14],U[15]=J[15],this}copyPosition($){let U=this.elements,J=$.elements;return U[12]=J[12],U[13]=J[13],U[14]=J[14],this}setFromMatrix3($){let U=$.elements;return this.set(U[0],U[3],U[6],0,U[1],U[4],U[7],0,U[2],U[5],U[8],0,0,0,0,1),this}extractBasis($,U,J){if(this.determinantAffine()===0)return $.set(1,0,0),U.set(0,1,0),J.set(0,0,1),this;return $.setFromMatrixColumn(this,0),U.setFromMatrixColumn(this,1),J.setFromMatrixColumn(this,2),this}makeBasis($,U,J){return this.set($.x,U.x,J.x,0,$.y,U.y,J.y,0,$.z,U.z,J.z,0,0,0,0,1),this}extractRotation($){if($.determinantAffine()===0)return this.identity();let U=this.elements,J=$.elements,Q=1/a0.setFromMatrixColumn($,0).length(),W=1/a0.setFromMatrixColumn($,1).length(),K=1/a0.setFromMatrixColumn($,2).length();return U[0]=J[0]*Q,U[1]=J[1]*Q,U[2]=J[2]*Q,U[3]=0,U[4]=J[4]*W,U[5]=J[5]*W,U[6]=J[6]*W,U[7]=0,U[8]=J[8]*K,U[9]=J[9]*K,U[10]=J[10]*K,U[11]=0,U[12]=0,U[13]=0,U[14]=0,U[15]=1,this}makeRotationFromEuler($){let U=this.elements,J=$.x,Q=$.y,W=$.z,K=Math.cos(J),X=Math.sin(J),H=Math.cos(Q),N=Math.sin(Q),Y=Math.cos(W),G=Math.sin(W);if($.order==="XYZ"){let O=K*Y,E=K*G,k=X*Y,I=X*G;U[0]=H*Y,U[4]=-H*G,U[8]=N,U[1]=E+k*N,U[5]=O-I*N,U[9]=-X*H,U[2]=I-O*N,U[6]=k+E*N,U[10]=K*H}else if($.order==="YXZ"){let O=H*Y,E=H*G,k=N*Y,I=N*G;U[0]=O+I*X,U[4]=k*X-E,U[8]=K*N,U[1]=K*G,U[5]=K*Y,U[9]=-X,U[2]=E*X-k,U[6]=I+O*X,U[10]=K*H}else if($.order==="ZXY"){let O=H*Y,E=H*G,k=N*Y,I=N*G;U[0]=O-I*X,U[4]=-K*G,U[8]=k+E*X,U[1]=E+k*X,U[5]=K*Y,U[9]=I-O*X,U[2]=-K*N,U[6]=X,U[10]=K*H}else if($.order==="ZYX"){let O=K*Y,E=K*G,k=X*Y,I=X*G;U[0]=H*Y,U[4]=k*N-E,U[8]=O*N+I,U[1]=H*G,U[5]=I*N+O,U[9]=E*N-k,U[2]=-N,U[6]=X*H,U[10]=K*H}else if($.order==="YZX"){let O=K*H,E=K*N,k=X*H,I=X*N;U[0]=H*Y,U[4]=I-O*G,U[8]=k*G+E,U[1]=G,U[5]=K*Y,U[9]=-X*Y,U[2]=-N*Y,U[6]=E*G+k,U[10]=O-I*G}else if($.order==="XZY"){let O=K*H,E=K*N,k=X*H,I=X*N;U[0]=H*Y,U[4]=-G,U[8]=N*Y,U[1]=O*G+I,U[5]=K*Y,U[9]=E*G-k,U[2]=k*G-E,U[6]=X*Y,U[10]=I*G+O}return U[3]=0,U[7]=0,U[11]=0,U[12]=0,U[13]=0,U[14]=0,U[15]=1,this}makeRotationFromQuaternion($){return this.compose(zF,$,_F)}lookAt($,U,J){let Q=this.elements;if(FU.subVectors($,U),FU.lengthSq()===0)FU.z=1;if(FU.normalize(),uJ.crossVectors(J,FU),uJ.lengthSq()===0){if(Math.abs(J.z)===1)FU.x+=0.0001;else FU.z+=0.0001;FU.normalize(),uJ.crossVectors(J,FU)}return uJ.normalize(),bQ.crossVectors(FU,uJ),Q[0]=uJ.x,Q[4]=bQ.x,Q[8]=FU.x,Q[1]=uJ.y,Q[5]=bQ.y,Q[9]=FU.y,Q[2]=uJ.z,Q[6]=bQ.z,Q[10]=FU.z,this}multiply($){return this.multiplyMatrices(this,$)}premultiply($){return this.multiplyMatrices($,this)}multiplyMatrices($,U){let J=$.elements,Q=U.elements,W=this.elements,K=J[0],X=J[4],H=J[8],N=J[12],Y=J[1],G=J[5],O=J[9],E=J[13],k=J[2],I=J[6],R=J[10],q=J[14],Z=J[3],_=J[7],P=J[11],L=J[15],B=Q[0],z=Q[4],A=Q[8],D=Q[12],w=Q[1],h=Q[5],C=Q[9],f=Q[13],s=Q[2],x=Q[6],d=Q[10],c=Q[14],y=Q[3],t=Q[7],e=Q[11],Y$=Q[15];return W[0]=K*B+X*w+H*s+N*y,W[4]=K*z+X*h+H*x+N*t,W[8]=K*A+X*C+H*d+N*e,W[12]=K*D+X*f+H*c+N*Y$,W[1]=Y*B+G*w+O*s+E*y,W[5]=Y*z+G*h+O*x+E*t,W[9]=Y*A+G*C+O*d+E*e,W[13]=Y*D+G*f+O*c+E*Y$,W[2]=k*B+I*w+R*s+q*y,W[6]=k*z+I*h+R*x+q*t,W[10]=k*A+I*C+R*d+q*e,W[14]=k*D+I*f+R*c+q*Y$,W[3]=Z*B+_*w+P*s+L*y,W[7]=Z*z+_*h+P*x+L*t,W[11]=Z*A+_*C+P*d+L*e,W[15]=Z*D+_*f+P*c+L*Y$,this}multiplyScalar($){let U=this.elements;return U[0]*=$,U[4]*=$,U[8]*=$,U[12]*=$,U[1]*=$,U[5]*=$,U[9]*=$,U[13]*=$,U[2]*=$,U[6]*=$,U[10]*=$,U[14]*=$,U[3]*=$,U[7]*=$,U[11]*=$,U[15]*=$,this}determinant(){let $=this.elements,U=$[0],J=$[4],Q=$[8],W=$[12],K=$[1],X=$[5],H=$[9],N=$[13],Y=$[2],G=$[6],O=$[10],E=$[14],k=$[3],I=$[7],R=$[11],q=$[15],Z=H*E-N*O,_=X*E-N*G,P=X*O-H*G,L=K*E-N*Y,B=K*O-H*Y,z=K*G-X*Y;return U*(I*Z-R*_+q*P)-J*(k*Z-R*L+q*B)+Q*(k*_-I*L+q*z)-W*(k*P-I*B+R*z)}determinantAffine(){let $=this.elements,U=$[0],J=$[4],Q=$[8],W=$[1],K=$[5],X=$[9],H=$[2],N=$[6],Y=$[10];return U*(K*Y-X*N)-J*(W*Y-X*H)+Q*(W*N-K*H)}transpose(){let $=this.elements,U;return U=$[1],$[1]=$[4],$[4]=U,U=$[2],$[2]=$[8],$[8]=U,U=$[6],$[6]=$[9],$[9]=U,U=$[3],$[3]=$[12],$[12]=U,U=$[7],$[7]=$[13],$[13]=U,U=$[11],$[11]=$[14],$[14]=U,this}setPosition($,U,J){let Q=this.elements;if($.isVector3)Q[12]=$.x,Q[13]=$.y,Q[14]=$.z;else Q[12]=$,Q[13]=U,Q[14]=J;return this}invert(){let $=this.elements,U=$[0],J=$[1],Q=$[2],W=$[3],K=$[4],X=$[5],H=$[6],N=$[7],Y=$[8],G=$[9],O=$[10],E=$[11],k=$[12],I=$[13],R=$[14],q=$[15],Z=U*X-J*K,_=U*H-Q*K,P=U*N-W*K,L=J*H-Q*X,B=J*N-W*X,z=Q*N-W*H,A=Y*I-G*k,D=Y*R-O*k,w=Y*q-E*k,h=G*R-O*I,C=G*q-E*I,f=O*q-E*R,s=Z*f-_*C+P*h+L*w-B*D+z*A;if(s===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let x=1/s;return $[0]=(X*f-H*C+N*h)*x,$[1]=(Q*C-J*f-W*h)*x,$[2]=(I*z-R*B+q*L)*x,$[3]=(O*B-G*z-E*L)*x,$[4]=(H*w-K*f-N*D)*x,$[5]=(U*f-Q*w+W*D)*x,$[6]=(R*P-k*z-q*_)*x,$[7]=(Y*z-O*P+E*_)*x,$[8]=(K*C-X*w+N*A)*x,$[9]=(J*w-U*C-W*A)*x,$[10]=(k*B-I*P+q*Z)*x,$[11]=(G*P-Y*B-E*Z)*x,$[12]=(X*D-K*h-H*A)*x,$[13]=(U*h-J*D+Q*A)*x,$[14]=(I*_-k*L-R*Z)*x,$[15]=(Y*L-G*_+O*Z)*x,this}scale($){let U=this.elements,J=$.x,Q=$.y,W=$.z;return U[0]*=J,U[4]*=Q,U[8]*=W,U[1]*=J,U[5]*=Q,U[9]*=W,U[2]*=J,U[6]*=Q,U[10]*=W,U[3]*=J,U[7]*=Q,U[11]*=W,this}getMaxScaleOnAxis(){let $=this.elements,U=$[0]*$[0]+$[1]*$[1]+$[2]*$[2],J=$[4]*$[4]+$[5]*$[5]+$[6]*$[6],Q=$[8]*$[8]+$[9]*$[9]+$[10]*$[10];return Math.sqrt(Math.max(U,J,Q))}makeTranslation($,U,J){if($.isVector3)this.set(1,0,0,$.x,0,1,0,$.y,0,0,1,$.z,0,0,0,1);else this.set(1,0,0,$,0,1,0,U,0,0,1,J,0,0,0,1);return this}makeRotationX($){let U=Math.cos($),J=Math.sin($);return this.set(1,0,0,0,0,U,-J,0,0,J,U,0,0,0,0,1),this}makeRotationY($){let U=Math.cos($),J=Math.sin($);return this.set(U,0,J,0,0,1,0,0,-J,0,U,0,0,0,0,1),this}makeRotationZ($){let U=Math.cos($),J=Math.sin($);return this.set(U,-J,0,0,J,U,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis($,U){let J=Math.cos(U),Q=Math.sin(U),W=1-J,K=$.x,X=$.y,H=$.z,N=W*K,Y=W*X;return this.set(N*K+J,N*X-Q*H,N*H+Q*X,0,N*X+Q*H,Y*X+J,Y*H-Q*K,0,N*H-Q*X,Y*H+Q*K,W*H*H+J,0,0,0,0,1),this}makeScale($,U,J){return this.set($,0,0,0,0,U,0,0,0,0,J,0,0,0,0,1),this}makeShear($,U,J,Q,W,K){return this.set(1,J,W,0,$,1,K,0,U,Q,1,0,0,0,0,1),this}compose($,U,J){let Q=this.elements,W=U._x,K=U._y,X=U._z,H=U._w,N=W+W,Y=K+K,G=X+X,O=W*N,E=W*Y,k=W*G,I=K*Y,R=K*G,q=X*G,Z=H*N,_=H*Y,P=H*G,L=J.x,B=J.y,z=J.z;return Q[0]=(1-(I+q))*L,Q[1]=(E+P)*L,Q[2]=(k-_)*L,Q[3]=0,Q[4]=(E-P)*B,Q[5]=(1-(O+q))*B,Q[6]=(R+Z)*B,Q[7]=0,Q[8]=(k+_)*z,Q[9]=(R-Z)*z,Q[10]=(1-(O+I))*z,Q[11]=0,Q[12]=$.x,Q[13]=$.y,Q[14]=$.z,Q[15]=1,this}decompose($,U,J){let Q=this.elements;$.x=Q[12],$.y=Q[13],$.z=Q[14];let W=this.determinantAffine();if(W===0)return J.set(1,1,1),U.identity(),this;let K=a0.set(Q[0],Q[1],Q[2]).length(),X=a0.set(Q[4],Q[5],Q[6]).length(),H=a0.set(Q[8],Q[9],Q[10]).length();if(W<0)K=-K;hU.copy(this);let N=1/K,Y=1/X,G=1/H;return hU.elements[0]*=N,hU.elements[1]*=N,hU.elements[2]*=N,hU.elements[4]*=Y,hU.elements[5]*=Y,hU.elements[6]*=Y,hU.elements[8]*=G,hU.elements[9]*=G,hU.elements[10]*=G,U.setFromRotationMatrix(hU),J.x=K,J.y=X,J.z=H,this}makePerspective($,U,J,Q,W,K,X=2000,H=!1){let N=this.elements,Y=2*W/(U-$),G=2*W/(J-Q),O=(U+$)/(U-$),E=(J+Q)/(J-Q),k,I;if(H)k=W/(K-W),I=K*W/(K-W);else if(X===2000)k=-(K+W)/(K-W),I=-2*K*W/(K-W);else if(X===2001)k=-K/(K-W),I=-K*W/(K-W);else throw Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+X);return N[0]=Y,N[4]=0,N[8]=O,N[12]=0,N[1]=0,N[5]=G,N[9]=E,N[13]=0,N[2]=0,N[6]=0,N[10]=k,N[14]=I,N[3]=0,N[7]=0,N[11]=-1,N[15]=0,this}makeOrthographic($,U,J,Q,W,K,X=2000,H=!1){let N=this.elements,Y=2/(U-$),G=2/(J-Q),O=-(U+$)/(U-$),E=-(J+Q)/(J-Q),k,I;if(H)k=1/(K-W),I=K/(K-W);else if(X===2000)k=-2/(K-W),I=-(K+W)/(K-W);else if(X===2001)k=-1/(K-W),I=-W/(K-W);else throw Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+X);return N[0]=Y,N[4]=0,N[8]=0,N[12]=O,N[1]=0,N[5]=G,N[9]=0,N[13]=E,N[2]=0,N[6]=0,N[10]=k,N[14]=I,N[3]=0,N[7]=0,N[11]=0,N[15]=1,this}equals($){let U=this.elements,J=$.elements;for(let Q=0;Q<16;Q++)if(U[Q]!==J[Q])return!1;return!0}fromArray($,U=0){for(let J=0;J<16;J++)this.elements[J]=$[J+U];return this}toArray($=[],U=0){let J=this.elements;return $[U]=J[0],$[U+1]=J[1],$[U+2]=J[2],$[U+3]=J[3],$[U+4]=J[4],$[U+5]=J[5],$[U+6]=J[6],$[U+7]=J[7],$[U+8]=J[8],$[U+9]=J[9],$[U+10]=J[10],$[U+11]=J[11],$[U+12]=J[12],$[U+13]=J[13],$[U+14]=J[14],$[U+15]=J[15],$}}var a0=new j,hU=new m$,zF=new j(0,0,0),_F=new j(1,1,1),uJ=new j,bQ=new j,FU=new j,Rk=new m$,Vk=new c6;class UJ{constructor($=0,U=0,J=0,Q=UJ.DEFAULT_ORDER){this.isEuler=!0,this._x=$,this._y=U,this._z=J,this._order=Q}get x(){return this._x}set x($){this._x=$,this._onChangeCallback()}get y(){return this._y}set y($){this._y=$,this._onChangeCallback()}get z(){return this._z}set z($){this._z=$,this._onChangeCallback()}get order(){return this._order}set order($){this._order=$,this._onChangeCallback()}set($,U,J,Q=this._order){return this._x=$,this._y=U,this._z=J,this._order=Q,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy($){return this._x=$._x,this._y=$._y,this._z=$._z,this._order=$._order,this._onChangeCallback(),this}setFromRotationMatrix($,U=this._order,J=!0){let Q=$.elements,W=Q[0],K=Q[4],X=Q[8],H=Q[1],N=Q[5],Y=Q[9],G=Q[2],O=Q[6],E=Q[10];switch(U){case"XYZ":if(this._y=Math.asin(a$(X,-1,1)),Math.abs(X)<0.9999999)this._x=Math.atan2(-Y,E),this._z=Math.atan2(-K,W);else this._x=Math.atan2(O,N),this._z=0;break;case"YXZ":if(this._x=Math.asin(-a$(Y,-1,1)),Math.abs(Y)<0.9999999)this._y=Math.atan2(X,E),this._z=Math.atan2(H,N);else this._y=Math.atan2(-G,W),this._z=0;break;case"ZXY":if(this._x=Math.asin(a$(O,-1,1)),Math.abs(O)<0.9999999)this._y=Math.atan2(-G,E),this._z=Math.atan2(-K,N);else this._y=0,this._z=Math.atan2(H,W);break;case"ZYX":if(this._y=Math.asin(-a$(G,-1,1)),Math.abs(G)<0.9999999)this._x=Math.atan2(O,E),this._z=Math.atan2(H,W);else this._x=0,this._z=Math.atan2(-K,N);break;case"YZX":if(this._z=Math.asin(a$(H,-1,1)),Math.abs(H)<0.9999999)this._x=Math.atan2(-Y,N),this._y=Math.atan2(-G,W);else this._x=0,this._y=Math.atan2(X,E);break;case"XZY":if(this._z=Math.asin(-a$(K,-1,1)),Math.abs(K)<0.9999999)this._x=Math.atan2(O,N),this._y=Math.atan2(X,W);else this._x=Math.atan2(-Y,E),this._y=0;break;default:A$("Euler: .setFromRotationMatrix() encountered an unknown order: "+U)}if(this._order=U,J===!0)this._onChangeCallback();return this}setFromQuaternion($,U,J){return Rk.makeRotationFromQuaternion($),this.setFromRotationMatrix(Rk,U,J)}setFromVector3($,U=this._order){return this.set($.x,$.y,$.z,U)}reorder($){return Vk.setFromEuler(this),this.setFromQuaternion(Vk,$)}equals($){return $._x===this._x&&$._y===this._y&&$._z===this._z&&$._order===this._order}fromArray($){if(this._x=$[0],this._y=$[1],this._z=$[2],$[3]!==void 0)this._order=$[3];return this._onChangeCallback(),this}toArray($=[],U=0){return $[U]=this._x,$[U+1]=this._y,$[U+2]=this._z,$[U+3]=this._order,$}_onChange($){return this._onChangeCallback=$,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}UJ.DEFAULT_ORDER="XYZ";class M9{constructor(){this.mask=1}set($){this.mask=(1<<$|0)>>>0}enable($){this.mask|=1<<$|0}enableAll(){this.mask=-1}toggle($){this.mask^=1<<$|0}disable($){this.mask&=~(1<<$|0)}disableAll(){this.mask=0}test($){return(this.mask&$.mask)!==0}isEnabled($){return(this.mask&(1<<$|0))!==0}}var AF=0,wk=new j,s0=new c6,VJ=new m$,yQ=new j,YW=new j,CF=new j,SF=new c6,Mk=new j(1,0,0),Bk=new j(0,1,0),Pk=new j(0,0,1),zk={type:"added"},TF={type:"removed"},t0={type:"childadded",child:null},b7={type:"childremoved",child:null};class q6 extends iU{constructor(){super();this.isObject3D=!0,Object.defineProperty(this,"id",{value:AF++}),this.uuid=pU(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=q6.DEFAULT_UP.clone();let $=new j,U=new UJ,J=new c6,Q=new j(1,1,1);function W(){J.setFromEuler(U,!1)}function K(){U.setFromQuaternion(J,void 0,!1)}U._onChange(W),J._onChange(K),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:$},rotation:{configurable:!0,enumerable:!0,value:U},quaternion:{configurable:!0,enumerable:!0,value:J},scale:{configurable:!0,enumerable:!0,value:Q},modelViewMatrix:{value:new m$},normalMatrix:{value:new f$}}),this.matrix=new m$,this.matrixWorld=new m$,this.matrixAutoUpdate=q6.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=q6.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new M9,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($){if(this.matrixAutoUpdate)this.updateMatrix();this.matrix.premultiply($),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion($){return this.quaternion.premultiply($),this}setRotationFromAxisAngle($,U){this.quaternion.setFromAxisAngle($,U)}setRotationFromEuler($){this.quaternion.setFromEuler($,!0)}setRotationFromMatrix($){this.quaternion.setFromRotationMatrix($)}setRotationFromQuaternion($){this.quaternion.copy($)}rotateOnAxis($,U){return s0.setFromAxisAngle($,U),this.quaternion.multiply(s0),this}rotateOnWorldAxis($,U){return s0.setFromAxisAngle($,U),this.quaternion.premultiply(s0),this}rotateX($){return this.rotateOnAxis(Mk,$)}rotateY($){return this.rotateOnAxis(Bk,$)}rotateZ($){return this.rotateOnAxis(Pk,$)}translateOnAxis($,U){return wk.copy($).applyQuaternion(this.quaternion),this.position.add(wk.multiplyScalar(U)),this}translateX($){return this.translateOnAxis(Mk,$)}translateY($){return this.translateOnAxis(Bk,$)}translateZ($){return this.translateOnAxis(Pk,$)}localToWorld($){return this.updateWorldMatrix(!0,!1),$.applyMatrix4(this.matrixWorld)}worldToLocal($){return this.updateWorldMatrix(!0,!1),$.applyMatrix4(VJ.copy(this.matrixWorld).invert())}lookAt($,U,J){if($.isVector3)yQ.copy($);else yQ.set($,U,J);let Q=this.parent;if(this.updateWorldMatrix(!0,!1),YW.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight)VJ.lookAt(YW,yQ,this.up);else VJ.lookAt(yQ,YW,this.up);if(this.quaternion.setFromRotationMatrix(VJ),Q)VJ.extractRotation(Q.matrixWorld),s0.setFromRotationMatrix(VJ),this.quaternion.premultiply(s0.invert())}add($){if(arguments.length>1){for(let U=0;U<arguments.length;U++)this.add(arguments[U]);return this}if($===this)return x$("Object3D.add: object can't be added as a child of itself.",$),this;if($&&$.isObject3D)$.removeFromParent(),$.parent=this,this.children.push($),$.dispatchEvent(zk),t0.child=$,this.dispatchEvent(t0),t0.child=null;else x$("Object3D.add: object not an instance of THREE.Object3D.",$);return this}remove($){if(arguments.length>1){for(let J=0;J<arguments.length;J++)this.remove(arguments[J]);return this}let U=this.children.indexOf($);if(U!==-1)$.parent=null,this.children.splice(U,1),$.dispatchEvent(TF),b7.child=$,this.dispatchEvent(b7),b7.child=null;return this}removeFromParent(){let $=this.parent;if($!==null)$.remove(this);return this}clear(){return this.remove(...this.children)}attach($){if(this.updateWorldMatrix(!0,!1),VJ.copy(this.matrixWorld).invert(),$.parent!==null)$.parent.updateWorldMatrix(!0,!1),VJ.multiply($.parent.matrixWorld);return $.applyMatrix4(VJ),$.removeFromParent(),$.parent=this,this.children.push($),$.updateWorldMatrix(!1,!0),$.dispatchEvent(zk),t0.child=$,this.dispatchEvent(t0),t0.child=null,this}getObjectById($){return this.getObjectByProperty("id",$)}getObjectByName($){return this.getObjectByProperty("name",$)}getObjectByProperty($,U){if(this[$]===U)return this;for(let J=0,Q=this.children.length;J<Q;J++){let K=this.children[J].getObjectByProperty($,U);if(K!==void 0)return K}return}getObjectsByProperty($,U,J=[]){if(this[$]===U)J.push(this);let Q=this.children;for(let W=0,K=Q.length;W<K;W++)Q[W].getObjectsByProperty($,U,J);return J}getWorldPosition($){return this.updateWorldMatrix(!0,!1),$.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion($){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(YW,$,CF),$}getWorldScale($){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(YW,SF,$),$}getWorldDirection($){this.updateWorldMatrix(!0,!1);let U=this.matrixWorld.elements;return $.set(U[8],U[9],U[10]).normalize()}raycast(){}traverse($){$(this);let U=this.children;for(let J=0,Q=U.length;J<Q;J++)U[J].traverse($)}traverseVisible($){if(this.visible===!1)return;$(this);let U=this.children;for(let J=0,Q=U.length;J<Q;J++)U[J].traverseVisible($)}traverseAncestors($){let U=this.parent;if(U!==null)$(U),U.traverseAncestors($)}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let $=this.pivot;if($!==null){let{x:U,y:J,z:Q}=$,W=this.matrix.elements;W[12]+=U-W[0]*U-W[4]*J-W[8]*Q,W[13]+=J-W[1]*U-W[5]*J-W[9]*Q,W[14]+=Q-W[2]*U-W[6]*J-W[10]*Q}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld($){if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||$){if(this.matrixWorldAutoUpdate===!0)if(this.parent===null)this.matrixWorld.copy(this.matrix);else this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);this.matrixWorldNeedsUpdate=!1,$=!0}let U=this.children;for(let J=0,Q=U.length;J<Q;J++)U[J].updateMatrixWorld($)}updateWorldMatrix($,U,J=!1){let Q=this.parent;if($===!0&&Q!==null)Q.updateWorldMatrix(!0,!1);if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||J){if(this.matrixWorldAutoUpdate===!0)if(this.parent===null)this.matrixWorld.copy(this.matrix);else this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);this.matrixWorldNeedsUpdate=!1,J=!0}if(U===!0){let W=this.children;for(let K=0,X=W.length;K<X;K++)W[K].updateWorldMatrix(!1,!0,J)}}toJSON($){let U=$===void 0||typeof $==="string",J={};if(U)$={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},J.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"};let Q={};if(Q.uuid=this.uuid,Q.type=this.type,this.name!=="")Q.name=this.name;if(this.castShadow===!0)Q.castShadow=!0;if(this.receiveShadow===!0)Q.receiveShadow=!0;if(this.visible===!1)Q.visible=!1;if(this.frustumCulled===!1)Q.frustumCulled=!1;if(this.renderOrder!==0)Q.renderOrder=this.renderOrder;if(this.static!==!1)Q.static=this.static;if(Object.keys(this.userData).length>0)Q.userData=this.userData;if(Q.layers=this.layers.mask,Q.matrix=this.matrix.toArray(),Q.up=this.up.toArray(),this.pivot!==null)Q.pivot=this.pivot.toArray();if(this.matrixAutoUpdate===!1)Q.matrixAutoUpdate=!1;if(this.morphTargetDictionary!==void 0)Q.morphTargetDictionary=Object.assign({},this.morphTargetDictionary);if(this.morphTargetInfluences!==void 0)Q.morphTargetInfluences=this.morphTargetInfluences.slice();if(this.isInstancedMesh){if(Q.type="InstancedMesh",Q.count=this.count,Q.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null)Q.instanceColor=this.instanceColor.toJSON()}if(this.isBatchedMesh){if(Q.type="BatchedMesh",Q.perObjectFrustumCulled=this.perObjectFrustumCulled,Q.sortObjects=this.sortObjects,Q.drawRanges=this._drawRanges,Q.reservedRanges=this._reservedRanges,Q.geometryInfo=this._geometryInfo.map((X)=>({...X,boundingBox:X.boundingBox?X.boundingBox.toJSON():void 0,boundingSphere:X.boundingSphere?X.boundingSphere.toJSON():void 0})),Q.instanceInfo=this._instanceInfo.map((X)=>({...X})),Q.availableInstanceIds=this._availableInstanceIds.slice(),Q.availableGeometryIds=this._availableGeometryIds.slice(),Q.nextIndexStart=this._nextIndexStart,Q.nextVertexStart=this._nextVertexStart,Q.geometryCount=this._geometryCount,Q.maxInstanceCount=this._maxInstanceCount,Q.maxVertexCount=this._maxVertexCount,Q.maxIndexCount=this._maxIndexCount,Q.geometryInitialized=this._geometryInitialized,Q.matricesTexture=this._matricesTexture.toJSON($),Q.indirectTexture=this._indirectTexture.toJSON($),this._colorsTexture!==null)Q.colorsTexture=this._colorsTexture.toJSON($);if(this.boundingSphere!==null)Q.boundingSphere=this.boundingSphere.toJSON();if(this.boundingBox!==null)Q.boundingBox=this.boundingBox.toJSON()}function W(X,H){if(X[H.uuid]===void 0)X[H.uuid]=H.toJSON($);return H.uuid}if(this.isScene){if(this.background){if(this.background.isColor)Q.background=this.background.toJSON();else if(this.background.isTexture)Q.background=this.background.toJSON($).uuid}if(this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0)Q.environment=this.environment.toJSON($).uuid}else if(this.isMesh||this.isLine||this.isPoints){Q.geometry=W($.geometries,this.geometry);let X=this.geometry.parameters;if(X!==void 0&&X.shapes!==void 0){let H=X.shapes;if(Array.isArray(H))for(let N=0,Y=H.length;N<Y;N++){let G=H[N];W($.shapes,G)}else W($.shapes,H)}}if(this.isSkinnedMesh){if(Q.bindMode=this.bindMode,Q.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0)W($.skeletons,this.skeleton),Q.skeleton=this.skeleton.uuid}if(this.material!==void 0)if(Array.isArray(this.material)){let X=[];for(let H=0,N=this.material.length;H<N;H++)X.push(W($.materials,this.material[H]));Q.material=X}else Q.material=W($.materials,this.material);if(this.children.length>0){Q.children=[];for(let X=0;X<this.children.length;X++)Q.children.push(this.children[X].toJSON($).object)}if(this.animations.length>0){Q.animations=[];for(let X=0;X<this.animations.length;X++){let H=this.animations[X];Q.animations.push(W($.animations,H))}}if(U){let X=K($.geometries),H=K($.materials),N=K($.textures),Y=K($.images),G=K($.shapes),O=K($.skeletons),E=K($.animations),k=K($.nodes);if(X.length>0)J.geometries=X;if(H.length>0)J.materials=H;if(N.length>0)J.textures=N;if(Y.length>0)J.images=Y;if(G.length>0)J.shapes=G;if(O.length>0)J.skeletons=O;if(E.length>0)J.animations=E;if(k.length>0)J.nodes=k}return J.object=Q,J;function K(X){let H=[];for(let N in X){let Y=X[N];delete Y.metadata,H.push(Y)}return H}}clone($){return new this.constructor().copy(this,$)}copy($,U=!0){if(this.name=$.name,this.up.copy($.up),this.position.copy($.position),this.rotation.order=$.rotation.order,this.quaternion.copy($.quaternion),this.scale.copy($.scale),this.pivot=$.pivot!==null?$.pivot.clone():null,this.matrix.copy($.matrix),this.matrixWorld.copy($.matrixWorld),this.matrixAutoUpdate=$.matrixAutoUpdate,this.matrixWorldAutoUpdate=$.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=$.matrixWorldNeedsUpdate,this.layers.mask=$.layers.mask,this.visible=$.visible,this.castShadow=$.castShadow,this.receiveShadow=$.receiveShadow,this.frustumCulled=$.frustumCulled,this.renderOrder=$.renderOrder,this.static=$.static,this.animations=$.animations.slice(),this.userData=JSON.parse(JSON.stringify($.userData)),U===!0)for(let J=0;J<$.children.length;J++){let Q=$.children[J];this.add(Q.clone())}return this}}q6.DEFAULT_UP=new j(0,1,0);q6.DEFAULT_MATRIX_AUTO_UPDATE=!0;q6.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class eU extends q6{constructor(){super();this.isGroup=!0,this.type="Group"}}var vF={type:"move"};class AW{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){if(this._hand===null)this._hand=new eU,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1};return this._hand}getTargetRaySpace(){if(this._targetRay===null)this._targetRay=new eU,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new j,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new j;return this._targetRay}getGripSpace(){if(this._grip===null)this._grip=new eU,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new j,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new j,this._grip.eventsEnabled=!1;return this._grip}dispatchEvent($){if(this._targetRay!==null)this._targetRay.dispatchEvent($);if(this._grip!==null)this._grip.dispatchEvent($);if(this._hand!==null)this._hand.dispatchEvent($);return this}connect($){if($&&$.hand){let U=this._hand;if(U)for(let J of $.hand.values())this._getHandJoint(U,J)}return this.dispatchEvent({type:"connected",data:$}),this}disconnect($){if(this.dispatchEvent({type:"disconnected",data:$}),this._targetRay!==null)this._targetRay.visible=!1;if(this._grip!==null)this._grip.visible=!1;if(this._hand!==null)this._hand.visible=!1;return this}update($,U,J){let Q=null,W=null,K=null,X=this._targetRay,H=this._grip,N=this._hand;if($&&U.session.visibilityState!=="visible-blurred"){if(N&&$.hand){K=!0;for(let I of $.hand.values()){let R=U.getJointPose(I,J),q=this._getHandJoint(N,I);if(R!==null)q.matrix.fromArray(R.transform.matrix),q.matrix.decompose(q.position,q.rotation,q.scale),q.matrixWorldNeedsUpdate=!0,q.jointRadius=R.radius;q.visible=R!==null}let Y=N.joints["index-finger-tip"],G=N.joints["thumb-tip"],O=Y.position.distanceTo(G.position),E=0.02,k=0.005;if(N.inputState.pinching&&O>E+k)N.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:$.handedness,target:this});else if(!N.inputState.pinching&&O<=E-k)N.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:$.handedness,target:this})}else if(H!==null&&$.gripSpace){if(W=U.getPose($.gripSpace,J),W!==null){if(H.matrix.fromArray(W.transform.matrix),H.matrix.decompose(H.position,H.rotation,H.scale),H.matrixWorldNeedsUpdate=!0,W.linearVelocity)H.hasLinearVelocity=!0,H.linearVelocity.copy(W.linearVelocity);else H.hasLinearVelocity=!1;if(W.angularVelocity)H.hasAngularVelocity=!0,H.angularVelocity.copy(W.angularVelocity);else H.hasAngularVelocity=!1;if(H.eventsEnabled)H.dispatchEvent({type:"gripUpdated",data:$,target:this})}}if(X!==null){if(Q=U.getPose($.targetRaySpace,J),Q===null&&W!==null)Q=W;if(Q!==null){if(X.matrix.fromArray(Q.transform.matrix),X.matrix.decompose(X.position,X.rotation,X.scale),X.matrixWorldNeedsUpdate=!0,Q.linearVelocity)X.hasLinearVelocity=!0,X.linearVelocity.copy(Q.linearVelocity);else X.hasLinearVelocity=!1;if(Q.angularVelocity)X.hasAngularVelocity=!0,X.angularVelocity.copy(Q.angularVelocity);else X.hasAngularVelocity=!1;this.dispatchEvent(vF)}}}if(X!==null)X.visible=Q!==null;if(H!==null)H.visible=W!==null;if(N!==null)N.visible=K!==null;return this}_getHandJoint($,U){if($.joints[U.jointName]===void 0){let J=new eU;J.matrixAutoUpdate=!1,J.visible=!1,$.joints[U.jointName]=J,$.add(J)}return $.joints[U.jointName]}}var rq={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},lJ={h:0,s:0,l:0},xQ={h:0,s:0,l:0};function y7($,U,J){if(J<0)J+=1;if(J>1)J-=1;if(J<0.16666666666666666)return $+(U-$)*6*J;if(J<0.5)return U;if(J<0.6666666666666666)return $+(U-$)*6*(0.6666666666666666-J);return $}class y${constructor($,U,J){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set($,U,J)}set($,U,J){if(U===void 0&&J===void 0){let Q=$;if(Q&&Q.isColor)this.copy(Q);else if(typeof Q==="number")this.setHex(Q);else if(typeof Q==="string")this.setStyle(Q)}else this.setRGB($,U,J);return this}setScalar($){return this.r=$,this.g=$,this.b=$,this}setHex($,U="srgb"){return $=Math.floor($),this.r=($>>16&255)/255,this.g=($>>8&255)/255,this.b=($&255)/255,r$.colorSpaceToWorking(this,U),this}setRGB($,U,J,Q=r$.workingColorSpace){return this.r=$,this.g=U,this.b=J,r$.colorSpaceToWorking(this,Q),this}setHSL($,U,J,Q=r$.workingColorSpace){if($=WH($,1),U=a$(U,0,1),J=a$(J,0,1),U===0)this.r=this.g=this.b=J;else{let W=J<=0.5?J*(1+U):J+U-J*U,K=2*J-W;this.r=y7(K,W,$+0.3333333333333333),this.g=y7(K,W,$),this.b=y7(K,W,$-0.3333333333333333)}return r$.colorSpaceToWorking(this,Q),this}setStyle($,U="srgb"){function J(W){if(W===void 0)return;if(parseFloat(W)<1)A$("Color: Alpha component of "+$+" will be ignored.")}let Q;if(Q=/^(\w+)\(([^\)]*)\)/.exec($)){let W,K=Q[1],X=Q[2];switch(K){case"rgb":case"rgba":if(W=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(X))return J(W[4]),this.setRGB(Math.min(255,parseInt(W[1],10))/255,Math.min(255,parseInt(W[2],10))/255,Math.min(255,parseInt(W[3],10))/255,U);if(W=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(X))return J(W[4]),this.setRGB(Math.min(100,parseInt(W[1],10))/100,Math.min(100,parseInt(W[2],10))/100,Math.min(100,parseInt(W[3],10))/100,U);break;case"hsl":case"hsla":if(W=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(X))return J(W[4]),this.setHSL(parseFloat(W[1])/360,parseFloat(W[2])/100,parseFloat(W[3])/100,U);break;default:A$("Color: Unknown color model "+$)}}else if(Q=/^\#([A-Fa-f\d]+)$/.exec($)){let W=Q[1],K=W.length;if(K===3)return this.setRGB(parseInt(W.charAt(0),16)/15,parseInt(W.charAt(1),16)/15,parseInt(W.charAt(2),16)/15,U);else if(K===6)return this.setHex(parseInt(W,16),U);else A$("Color: Invalid hex color "+$)}else if($&&$.length>0)return this.setColorName($,U);return this}setColorName($,U="srgb"){let J=rq[$.toLowerCase()];if(J!==void 0)this.setHex(J,U);else A$("Color: Unknown color "+$);return this}clone(){return new this.constructor(this.r,this.g,this.b)}copy($){return this.r=$.r,this.g=$.g,this.b=$.b,this}copySRGBToLinear($){return this.r=_J($.r),this.g=_J($.g),this.b=_J($.b),this}copyLinearToSRGB($){return this.r=Y8($.r),this.g=Y8($.g),this.b=Y8($.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex($="srgb"){return r$.workingToColorSpace(e6.copy(this),$),Math.round(a$(e6.r*255,0,255))*65536+Math.round(a$(e6.g*255,0,255))*256+Math.round(a$(e6.b*255,0,255))}getHexString($="srgb"){return("000000"+this.getHex($).toString(16)).slice(-6)}getHSL($,U=r$.workingColorSpace){r$.workingToColorSpace(e6.copy(this),U);let{r:J,g:Q,b:W}=e6,K=Math.max(J,Q,W),X=Math.min(J,Q,W),H,N,Y=(X+K)/2;if(X===K)H=0,N=0;else{let G=K-X;switch(N=Y<=0.5?G/(K+X):G/(2-K-X),K){case J:H=(Q-W)/G+(Q<W?6:0);break;case Q:H=(W-J)/G+2;break;case W:H=(J-Q)/G+4;break}H/=6}return $.h=H,$.s=N,$.l=Y,$}getRGB($,U=r$.workingColorSpace){return r$.workingToColorSpace(e6.copy(this),U),$.r=e6.r,$.g=e6.g,$.b=e6.b,$}getStyle($="srgb"){r$.workingToColorSpace(e6.copy(this),$);let{r:U,g:J,b:Q}=e6;if($!=="srgb")return`color(${$} ${U.toFixed(3)} ${J.toFixed(3)} ${Q.toFixed(3)})`;return`rgb(${Math.round(U*255)},${Math.round(J*255)},${Math.round(Q*255)})`}offsetHSL($,U,J){return this.getHSL(lJ),this.setHSL(lJ.h+$,lJ.s+U,lJ.l+J)}add($){return this.r+=$.r,this.g+=$.g,this.b+=$.b,this}addColors($,U){return this.r=$.r+U.r,this.g=$.g+U.g,this.b=$.b+U.b,this}addScalar($){return this.r+=$,this.g+=$,this.b+=$,this}sub($){return this.r=Math.max(0,this.r-$.r),this.g=Math.max(0,this.g-$.g),this.b=Math.max(0,this.b-$.b),this}multiply($){return this.r*=$.r,this.g*=$.g,this.b*=$.b,this}multiplyScalar($){return this.r*=$,this.g*=$,this.b*=$,this}lerp($,U){return this.r+=($.r-this.r)*U,this.g+=($.g-this.g)*U,this.b+=($.b-this.b)*U,this}lerpColors($,U,J){return this.r=$.r+(U.r-$.r)*J,this.g=$.g+(U.g-$.g)*J,this.b=$.b+(U.b-$.b)*J,this}lerpHSL($,U){this.getHSL(lJ),$.getHSL(xQ);let J=FW(lJ.h,xQ.h,U),Q=FW(lJ.s,xQ.s,U),W=FW(lJ.l,xQ.l,U);return this.setHSL(J,Q,W),this}setFromVector3($){return this.r=$.x,this.g=$.y,this.b=$.z,this}applyMatrix3($){let U=this.r,J=this.g,Q=this.b,W=$.elements;return this.r=W[0]*U+W[3]*J+W[6]*Q,this.g=W[1]*U+W[4]*J+W[7]*Q,this.b=W[2]*U+W[5]*J+W[8]*Q,this}equals($){return $.r===this.r&&$.g===this.g&&$.b===this.b}fromArray($,U=0){return this.r=$[U],this.g=$[U+1],this.b=$[U+2],this}toArray($=[],U=0){return $[U]=this.r,$[U+1]=this.g,$[U+2]=this.b,$}fromBufferAttribute($,U){return this.r=$.getX(U),this.g=$.getY(U),this.b=$.getZ(U),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}var e6=new y$;y$.NAMES=rq;class V8 extends q6{constructor(){super();if(this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new UJ,this.environmentIntensity=1,this.environmentRotation=new UJ,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy($,U){if(super.copy($,U),$.background!==null)this.background=$.background.clone();if($.environment!==null)this.environment=$.environment.clone();if($.fog!==null)this.fog=$.fog.clone();if(this.backgroundBlurriness=$.backgroundBlurriness,this.backgroundIntensity=$.backgroundIntensity,this.backgroundRotation.copy($.backgroundRotation),this.environmentIntensity=$.environmentIntensity,this.environmentRotation.copy($.environmentRotation),$.overrideMaterial!==null)this.overrideMaterial=$.overrideMaterial.clone();return this.matrixAutoUpdate=$.matrixAutoUpdate,this}toJSON($){let U=super.toJSON($);if(this.fog!==null)U.object.fog=this.fog.toJSON();if(this.backgroundBlurriness>0)U.object.backgroundBlurriness=this.backgroundBlurriness;if(this.backgroundIntensity!==1)U.object.backgroundIntensity=this.backgroundIntensity;if(U.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1)U.object.environmentIntensity=this.environmentIntensity;return U.object.environmentRotation=this.environmentRotation.toArray(),U}}var fU=new j,wJ=new j,x7=new j,MJ=new j,e0=new j,$8=new j,_k=new j,h7=new j,f7=new j,u7=new j,l7=new E6,m7=new E6,p7=new E6;class TU{constructor($=new j,U=new j,J=new j){this.a=$,this.b=U,this.c=J}static getNormal($,U,J,Q){Q.subVectors(J,U),fU.subVectors($,U),Q.cross(fU);let W=Q.lengthSq();if(W>0)return Q.multiplyScalar(1/Math.sqrt(W));return Q.set(0,0,0)}static getBarycoord($,U,J,Q,W){fU.subVectors(Q,U),wJ.subVectors(J,U),x7.subVectors($,U);let K=fU.dot(fU),X=fU.dot(wJ),H=fU.dot(x7),N=wJ.dot(wJ),Y=wJ.dot(x7),G=K*N-X*X;if(G===0)return W.set(0,0,0),null;let O=1/G,E=(N*H-X*Y)*O,k=(K*Y-X*H)*O;return W.set(1-E-k,k,E)}static containsPoint($,U,J,Q){if(this.getBarycoord($,U,J,Q,MJ)===null)return!1;return MJ.x>=0&&MJ.y>=0&&MJ.x+MJ.y<=1}static getInterpolation($,U,J,Q,W,K,X,H){if(this.getBarycoord($,U,J,Q,MJ)===null){if(H.x=0,H.y=0,"z"in H)H.z=0;if("w"in H)H.w=0;return null}return H.setScalar(0),H.addScaledVector(W,MJ.x),H.addScaledVector(K,MJ.y),H.addScaledVector(X,MJ.z),H}static getInterpolatedAttribute($,U,J,Q,W,K){return l7.setScalar(0),m7.setScalar(0),p7.setScalar(0),l7.fromBufferAttribute($,U),m7.fromBufferAttribute($,J),p7.fromBufferAttribute($,Q),K.setScalar(0),K.addScaledVector(l7,W.x),K.addScaledVector(m7,W.y),K.addScaledVector(p7,W.z),K}static isFrontFacing($,U,J,Q){return fU.subVectors(J,U),wJ.subVectors($,U),fU.cross(wJ).dot(Q)<0}set($,U,J){return this.a.copy($),this.b.copy(U),this.c.copy(J),this}setFromPointsAndIndices($,U,J,Q){return this.a.copy($[U]),this.b.copy($[J]),this.c.copy($[Q]),this}setFromAttributeAndIndices($,U,J,Q){return this.a.fromBufferAttribute($,U),this.b.fromBufferAttribute($,J),this.c.fromBufferAttribute($,Q),this}clone(){return new this.constructor().copy(this)}copy($){return this.a.copy($.a),this.b.copy($.b),this.c.copy($.c),this}getArea(){return fU.subVectors(this.c,this.b),wJ.subVectors(this.a,this.b),fU.cross(wJ).length()*0.5}getMidpoint($){return $.addVectors(this.a,this.b).add(this.c).multiplyScalar(0.3333333333333333)}getNormal($){return TU.getNormal(this.a,this.b,this.c,$)}getPlane($){return $.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord($,U){return TU.getBarycoord($,this.a,this.b,this.c,U)}getInterpolation($,U,J,Q,W){return TU.getInterpolation($,this.a,this.b,this.c,U,J,Q,W)}containsPoint($){return TU.containsPoint($,this.a,this.b,this.c)}isFrontFacing($){return TU.isFrontFacing(this.a,this.b,this.c,$)}intersectsBox($){return $.intersectsTriangle(this)}closestPointToPoint($,U){let J=this.a,Q=this.b,W=this.c,K,X;e0.subVectors(Q,J),$8.subVectors(W,J),h7.subVectors($,J);let H=e0.dot(h7),N=$8.dot(h7);if(H<=0&&N<=0)return U.copy(J);f7.subVectors($,Q);let Y=e0.dot(f7),G=$8.dot(f7);if(Y>=0&&G<=Y)return U.copy(Q);let O=H*G-Y*N;if(O<=0&&H>=0&&Y<=0)return K=H/(H-Y),U.copy(J).addScaledVector(e0,K);u7.subVectors($,W);let E=e0.dot(u7),k=$8.dot(u7);if(k>=0&&E<=k)return U.copy(W);let I=E*N-H*k;if(I<=0&&N>=0&&k<=0)return X=N/(N-k),U.copy(J).addScaledVector($8,X);let R=Y*k-E*G;if(R<=0&&G-Y>=0&&E-k>=0)return _k.subVectors(W,Q),X=(G-Y)/(G-Y+(E-k)),U.copy(Q).addScaledVector(_k,X);let q=1/(R+I+O);return K=I*q,X=O*q,U.copy(J).addScaledVector(e0,K).addScaledVector($8,X)}equals($){return $.a.equals(this.a)&&$.b.equals(this.b)&&$.c.equals(this.c)}}class QU{constructor($=new j(1/0,1/0,1/0),U=new j(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=$,this.max=U}set($,U){return this.min.copy($),this.max.copy(U),this}setFromArray($){this.makeEmpty();for(let U=0,J=$.length;U<J;U+=3)this.expandByPoint(uU.fromArray($,U));return this}setFromBufferAttribute($){this.makeEmpty();for(let U=0,J=$.count;U<J;U++)this.expandByPoint(uU.fromBufferAttribute($,U));return this}setFromPoints($){this.makeEmpty();for(let U=0,J=$.length;U<J;U++)this.expandByPoint($[U]);return this}setFromCenterAndSize($,U){let J=uU.copy(U).multiplyScalar(0.5);return this.min.copy($).sub(J),this.max.copy($).add(J),this}setFromObject($,U=!1){return this.makeEmpty(),this.expandByObject($,U)}clone(){return new this.constructor().copy(this)}copy($){return this.min.copy($.min),this.max.copy($.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($){return this.isEmpty()?$.set(0,0,0):$.addVectors(this.min,this.max).multiplyScalar(0.5)}getSize($){return this.isEmpty()?$.set(0,0,0):$.subVectors(this.max,this.min)}expandByPoint($){return this.min.min($),this.max.max($),this}expandByVector($){return this.min.sub($),this.max.add($),this}expandByScalar($){return this.min.addScalar(-$),this.max.addScalar($),this}expandByObject($,U=!1){$.updateWorldMatrix(!1,!1);let J=$.geometry;if(J!==void 0){let W=J.getAttribute("position");if(U===!0&&W!==void 0&&$.isInstancedMesh!==!0)for(let K=0,X=W.count;K<X;K++){if($.isMesh===!0)$.getVertexPosition(K,uU);else uU.fromBufferAttribute(W,K);uU.applyMatrix4($.matrixWorld),this.expandByPoint(uU)}else{if($.boundingBox!==void 0){if($.boundingBox===null)$.computeBoundingBox();hQ.copy($.boundingBox)}else{if(J.boundingBox===null)J.computeBoundingBox();hQ.copy(J.boundingBox)}hQ.applyMatrix4($.matrixWorld),this.union(hQ)}}let Q=$.children;for(let W=0,K=Q.length;W<K;W++)this.expandByObject(Q[W],U);return this}containsPoint($){return $.x>=this.min.x&&$.x<=this.max.x&&$.y>=this.min.y&&$.y<=this.max.y&&$.z>=this.min.z&&$.z<=this.max.z}containsBox($){return this.min.x<=$.min.x&&$.max.x<=this.max.x&&this.min.y<=$.min.y&&$.max.y<=this.max.y&&this.min.z<=$.min.z&&$.max.z<=this.max.z}getParameter($,U){return U.set(($.x-this.min.x)/(this.max.x-this.min.x),($.y-this.min.y)/(this.max.y-this.min.y),($.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox($){return $.max.x>=this.min.x&&$.min.x<=this.max.x&&$.max.y>=this.min.y&&$.min.y<=this.max.y&&$.max.z>=this.min.z&&$.min.z<=this.max.z}intersectsSphere($){return this.clampPoint($.center,uU),uU.distanceToSquared($.center)<=$.radius*$.radius}intersectsPlane($){let U,J;if($.normal.x>0)U=$.normal.x*this.min.x,J=$.normal.x*this.max.x;else U=$.normal.x*this.max.x,J=$.normal.x*this.min.x;if($.normal.y>0)U+=$.normal.y*this.min.y,J+=$.normal.y*this.max.y;else U+=$.normal.y*this.max.y,J+=$.normal.y*this.min.y;if($.normal.z>0)U+=$.normal.z*this.min.z,J+=$.normal.z*this.max.z;else U+=$.normal.z*this.max.z,J+=$.normal.z*this.min.z;return U<=-$.constant&&J>=-$.constant}intersectsTriangle($){if(this.isEmpty())return!1;this.getCenter(GW),fQ.subVectors(this.max,GW),U8.subVectors($.a,GW),J8.subVectors($.b,GW),W8.subVectors($.c,GW),mJ.subVectors(J8,U8),pJ.subVectors(W8,J8),L0.subVectors(U8,W8);let U=[0,-mJ.z,mJ.y,0,-pJ.z,pJ.y,0,-L0.z,L0.y,mJ.z,0,-mJ.x,pJ.z,0,-pJ.x,L0.z,0,-L0.x,-mJ.y,mJ.x,0,-pJ.y,pJ.x,0,-L0.y,L0.x,0];if(!d7(U,U8,J8,W8,fQ))return!1;if(U=[1,0,0,0,1,0,0,0,1],!d7(U,U8,J8,W8,fQ))return!1;return uQ.crossVectors(mJ,pJ),U=[uQ.x,uQ.y,uQ.z],d7(U,U8,J8,W8,fQ)}clampPoint($,U){return U.copy($).clamp(this.min,this.max)}distanceToPoint($){return this.clampPoint($,uU).distanceTo($)}getBoundingSphere($){if(this.isEmpty())$.makeEmpty();else this.getCenter($.center),$.radius=this.getSize(uU).length()*0.5;return $}intersect($){if(this.min.max($.min),this.max.min($.max),this.isEmpty())this.makeEmpty();return this}union($){return this.min.min($.min),this.max.max($.max),this}applyMatrix4($){if(this.isEmpty())return this;return BJ[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4($),BJ[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4($),BJ[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4($),BJ[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4($),BJ[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4($),BJ[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4($),BJ[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4($),BJ[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4($),this.setFromPoints(BJ),this}translate($){return this.min.add($),this.max.add($),this}equals($){return $.min.equals(this.min)&&$.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON($){return this.min.fromArray($.min),this.max.fromArray($.max),this}}var BJ=[new j,new j,new j,new j,new j,new j,new j,new j],uU=new j,hQ=new QU,U8=new j,J8=new j,W8=new j,mJ=new j,pJ=new j,L0=new j,GW=new j,fQ=new j,uQ=new j,R0=new j;function d7($,U,J,Q,W){for(let K=0,X=$.length-3;K<=X;K+=3){R0.fromArray($,K);let H=W.x*Math.abs(R0.x)+W.y*Math.abs(R0.y)+W.z*Math.abs(R0.z),N=U.dot(R0),Y=J.dot(R0),G=Q.dot(R0);if(Math.max(-Math.max(N,Y,G),Math.min(N,Y,G))>H)return!1}return!0}var b6=new j,lQ=new g$,jF=0;class h6 extends iU{constructor($,U,J=!1){super();if(Array.isArray($))throw TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:jF++}),this.name="",this.array=$,this.itemSize=U,this.count=$!==void 0?$.length/U:0,this.normalized=J,this.usage=35044,this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate($){if($===!0)this.version++}setUsage($){return this.usage=$,this}addUpdateRange($,U){this.updateRanges.push({start:$,count:U})}clearUpdateRanges(){this.updateRanges.length=0}copy($){return this.name=$.name,this.array=new $.array.constructor($.array),this.itemSize=$.itemSize,this.count=$.count,this.normalized=$.normalized,this.usage=$.usage,this.gpuType=$.gpuType,this}copyAt($,U,J){$*=this.itemSize,J*=U.itemSize;for(let Q=0,W=this.itemSize;Q<W;Q++)this.array[$+Q]=U.array[J+Q];return this}copyArray($){return this.array.set($),this}applyMatrix3($){if(this.itemSize===2)for(let U=0,J=this.count;U<J;U++)lQ.fromBufferAttribute(this,U),lQ.applyMatrix3($),this.setXY(U,lQ.x,lQ.y);else if(this.itemSize===3)for(let U=0,J=this.count;U<J;U++)b6.fromBufferAttribute(this,U),b6.applyMatrix3($),this.setXYZ(U,b6.x,b6.y,b6.z);return this}applyMatrix4($){for(let U=0,J=this.count;U<J;U++)b6.fromBufferAttribute(this,U),b6.applyMatrix4($),this.setXYZ(U,b6.x,b6.y,b6.z);return this}applyNormalMatrix($){for(let U=0,J=this.count;U<J;U++)b6.fromBufferAttribute(this,U),b6.applyNormalMatrix($),this.setXYZ(U,b6.x,b6.y,b6.z);return this}transformDirection($){for(let U=0,J=this.count;U<J;U++)b6.fromBufferAttribute(this,U),b6.transformDirection($),this.setXYZ(U,b6.x,b6.y,b6.z);return this}set($,U=0){return this.array.set($,U),this}getComponent($,U){let J=this.array[$*this.itemSize+U];if(this.normalized)J=mU(J,this.array);return J}setComponent($,U,J){if(this.normalized)J=O6(J,this.array);return this.array[$*this.itemSize+U]=J,this}getX($){let U=this.array[$*this.itemSize];if(this.normalized)U=mU(U,this.array);return U}setX($,U){if(this.normalized)U=O6(U,this.array);return this.array[$*this.itemSize]=U,this}getY($){let U=this.array[$*this.itemSize+1];if(this.normalized)U=mU(U,this.array);return U}setY($,U){if(this.normalized)U=O6(U,this.array);return this.array[$*this.itemSize+1]=U,this}getZ($){let U=this.array[$*this.itemSize+2];if(this.normalized)U=mU(U,this.array);return U}setZ($,U){if(this.normalized)U=O6(U,this.array);return this.array[$*this.itemSize+2]=U,this}getW($){let U=this.array[$*this.itemSize+3];if(this.normalized)U=mU(U,this.array);return U}setW($,U){if(this.normalized)U=O6(U,this.array);return this.array[$*this.itemSize+3]=U,this}setXY($,U,J){if($*=this.itemSize,this.normalized)U=O6(U,this.array),J=O6(J,this.array);return this.array[$+0]=U,this.array[$+1]=J,this}setXYZ($,U,J,Q){if($*=this.itemSize,this.normalized)U=O6(U,this.array),J=O6(J,this.array),Q=O6(Q,this.array);return this.array[$+0]=U,this.array[$+1]=J,this.array[$+2]=Q,this}setXYZW($,U,J,Q,W){if($*=this.itemSize,this.normalized)U=O6(U,this.array),J=O6(J,this.array),Q=O6(Q,this.array),W=O6(W,this.array);return this.array[$+0]=U,this.array[$+1]=J,this.array[$+2]=Q,this.array[$+3]=W,this}onUpload($){return this.onUploadCallback=$,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let $={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};if(this.name!=="")$.name=this.name;if(this.usage!==35044)$.usage=this.usage;return $}dispose(){this.dispatchEvent({type:"dispose"})}}class B9 extends h6{constructor($,U,J){super(new Uint16Array($),U,J)}}class P9 extends h6{constructor($,U,J){super(new Uint32Array($),U,J)}}class OU extends h6{constructor($,U,J){super(new Float32Array($),U,J)}}var gF=new QU,OW=new j,c7=new j;class VU{constructor($=new j,U=-1){this.isSphere=!0,this.center=$,this.radius=U}set($,U){return this.center.copy($),this.radius=U,this}setFromPoints($,U){let J=this.center;if(U!==void 0)J.copy(U);else gF.setFromPoints($).getCenter(J);let Q=0;for(let W=0,K=$.length;W<K;W++)Q=Math.max(Q,J.distanceToSquared($[W]));return this.radius=Math.sqrt(Q),this}copy($){return this.center.copy($.center),this.radius=$.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint($){return $.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint($){return $.distanceTo(this.center)-this.radius}intersectsSphere($){let U=this.radius+$.radius;return $.center.distanceToSquared(this.center)<=U*U}intersectsBox($){return $.intersectsSphere(this)}intersectsPlane($){return Math.abs($.distanceToPoint(this.center))<=this.radius}clampPoint($,U){let J=this.center.distanceToSquared($);if(U.copy($),J>this.radius*this.radius)U.sub(this.center).normalize(),U.multiplyScalar(this.radius).add(this.center);return U}getBoundingBox($){if(this.isEmpty())return $.makeEmpty(),$;return $.set(this.center,this.center),$.expandByScalar(this.radius),$}applyMatrix4($){return this.center.applyMatrix4($),this.radius=this.radius*$.getMaxScaleOnAxis(),this}translate($){return this.center.add($),this}expandByPoint($){if(this.isEmpty())return this.center.copy($),this.radius=0,this;OW.subVectors($,this.center);let U=OW.lengthSq();if(U>this.radius*this.radius){let J=Math.sqrt(U),Q=(J-this.radius)*0.5;this.center.addScaledVector(OW,Q/J),this.radius+=Q}return this}union($){if($.isEmpty())return this;if(this.isEmpty())return this.copy($),this;if(this.center.equals($.center)===!0)this.radius=Math.max(this.radius,$.radius);else c7.subVectors($.center,this.center).setLength($.radius),this.expandByPoint(OW.copy($.center).add(c7)),this.expandByPoint(OW.copy($.center).sub(c7));return this}equals($){return $.center.equals(this.center)&&$.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON($){return this.radius=$.radius,this.center.fromArray($.center),this}}var bF=0,SU=new m$,n7=new q6,Q8=new j,LU=new QU,EW=new QU,d6=new j;class KU extends iU{constructor(){super();this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:bF++}),this.uuid=pU(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex($){if(Array.isArray($))this.index=new((KF($))?P9:B9)($,1);else this.index=$;return this}setIndirect($,U=0){return this.indirect=$,this.indirectOffset=U,this}getIndirect(){return this.indirect}getAttribute($){return this.attributes[$]}setAttribute($,U){return this.attributes[$]=U,this}deleteAttribute($){return delete this.attributes[$],this}hasAttribute($){return this.attributes[$]!==void 0}addGroup($,U,J=0){this.groups.push({start:$,count:U,materialIndex:J})}clearGroups(){this.groups=[]}setDrawRange($,U){this.drawRange.start=$,this.drawRange.count=U}applyMatrix4($){let U=this.attributes.position;if(U!==void 0)U.applyMatrix4($),U.needsUpdate=!0;let J=this.attributes.normal;if(J!==void 0){let W=new f$().getNormalMatrix($);J.applyNormalMatrix(W),J.needsUpdate=!0}let Q=this.attributes.tangent;if(Q!==void 0)Q.transformDirection($),Q.needsUpdate=!0;if(this.boundingBox!==null)this.computeBoundingBox();if(this.boundingSphere!==null)this.computeBoundingSphere();return this._transformed=!0,this}applyQuaternion($){return SU.makeRotationFromQuaternion($),this.applyMatrix4(SU),this}rotateX($){return SU.makeRotationX($),this.applyMatrix4(SU),this}rotateY($){return SU.makeRotationY($),this.applyMatrix4(SU),this}rotateZ($){return SU.makeRotationZ($),this.applyMatrix4(SU),this}translate($,U,J){return SU.makeTranslation($,U,J),this.applyMatrix4(SU),this}scale($,U,J){return SU.makeScale($,U,J),this.applyMatrix4(SU),this}lookAt($){return n7.lookAt($),n7.updateMatrix(),this.applyMatrix4(n7.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Q8).negate(),this.translate(Q8.x,Q8.y,Q8.z),this}setFromPoints($){let U=this.getAttribute("position");if(U===void 0){let J=[];for(let Q=0,W=$.length;Q<W;Q++){let K=$[Q];J.push(K.x,K.y,K.z||0)}this.setAttribute("position",new OU(J,3))}else{let J=Math.min($.length,U.count);for(let Q=0;Q<J;Q++){let W=$[Q];U.setXYZ(Q,W.x,W.y,W.z||0)}if($.length>U.count)A$("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.");U.needsUpdate=!0}return this}computeBoundingBox(){if(this.boundingBox===null)this.boundingBox=new QU;let $=this.attributes.position,U=this.morphAttributes.position;if($&&$.isGLBufferAttribute){x$("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new j(-1/0,-1/0,-1/0),new j(1/0,1/0,1/0));return}if($!==void 0){if(this.boundingBox.setFromBufferAttribute($),U)for(let J=0,Q=U.length;J<Q;J++){let W=U[J];if(LU.setFromBufferAttribute(W),this.morphTargetsRelative)d6.addVectors(this.boundingBox.min,LU.min),this.boundingBox.expandByPoint(d6),d6.addVectors(this.boundingBox.max,LU.max),this.boundingBox.expandByPoint(d6);else this.boundingBox.expandByPoint(LU.min),this.boundingBox.expandByPoint(LU.max)}}else this.boundingBox.makeEmpty();if(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))x$('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){if(this.boundingSphere===null)this.boundingSphere=new VU;let $=this.attributes.position,U=this.morphAttributes.position;if($&&$.isGLBufferAttribute){x$("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new j,1/0);return}if($){let J=this.boundingSphere.center;if(LU.setFromBufferAttribute($),U)for(let W=0,K=U.length;W<K;W++){let X=U[W];if(EW.setFromBufferAttribute(X),this.morphTargetsRelative)d6.addVectors(LU.min,EW.min),LU.expandByPoint(d6),d6.addVectors(LU.max,EW.max),LU.expandByPoint(d6);else LU.expandByPoint(EW.min),LU.expandByPoint(EW.max)}LU.getCenter(J);let Q=0;for(let W=0,K=$.count;W<K;W++)d6.fromBufferAttribute($,W),Q=Math.max(Q,J.distanceToSquared(d6));if(U)for(let W=0,K=U.length;W<K;W++){let X=U[W],H=this.morphTargetsRelative;for(let N=0,Y=X.count;N<Y;N++){if(d6.fromBufferAttribute(X,N),H)Q8.fromBufferAttribute($,N),d6.add(Q8);Q=Math.max(Q,J.distanceToSquared(d6))}}if(this.boundingSphere.radius=Math.sqrt(Q),isNaN(this.boundingSphere.radius))x$('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){let $=this.index,U=this.attributes;if($===null||U.position===void 0||U.normal===void 0||U.uv===void 0){x$("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let{position:J,normal:Q,uv:W}=U,K=this.getAttribute("tangent");if(K===void 0||K.count!==J.count)K=new h6(new Float32Array(4*J.count),4),this.setAttribute("tangent",K);let X=[],H=[];for(let A=0;A<J.count;A++)X[A]=new j,H[A]=new j;let N=new j,Y=new j,G=new j,O=new g$,E=new g$,k=new g$,I=new j,R=new j;function q(A,D,w){N.fromBufferAttribute(J,A),Y.fromBufferAttribute(J,D),G.fromBufferAttribute(J,w),O.fromBufferAttribute(W,A),E.fromBufferAttribute(W,D),k.fromBufferAttribute(W,w),Y.sub(N),G.sub(N),E.sub(O),k.sub(O);let h=1/(E.x*k.y-k.x*E.y);if(!isFinite(h))return;I.copy(Y).multiplyScalar(k.y).addScaledVector(G,-E.y).multiplyScalar(h),R.copy(G).multiplyScalar(E.x).addScaledVector(Y,-k.x).multiplyScalar(h),X[A].add(I),X[D].add(I),X[w].add(I),H[A].add(R),H[D].add(R),H[w].add(R)}let Z=this.groups;if(Z.length===0)Z=[{start:0,count:$.count}];for(let A=0,D=Z.length;A<D;++A){let w=Z[A],h=w.start,C=w.count;for(let f=h,s=h+C;f<s;f+=3)q($.getX(f+0),$.getX(f+1),$.getX(f+2))}let _=new j,P=new j,L=new j,B=new j;function z(A){L.fromBufferAttribute(Q,A),B.copy(L);let D=X[A];_.copy(D),_.sub(L.multiplyScalar(L.dot(D))).normalize(),P.crossVectors(B,D);let h=P.dot(H[A])<0?-1:1;K.setXYZW(A,_.x,_.y,_.z,h)}for(let A=0,D=Z.length;A<D;++A){let w=Z[A],h=w.start,C=w.count;for(let f=h,s=h+C;f<s;f+=3)z($.getX(f+0)),z($.getX(f+1)),z($.getX(f+2))}this._transformed=!0}computeVertexNormals(){let $=this.index,U=this.getAttribute("position");if(U!==void 0){let J=this.getAttribute("normal");if(J===void 0||J.count!==U.count)J=new h6(new Float32Array(U.count*3),3),this.setAttribute("normal",J);else for(let O=0,E=J.count;O<E;O++)J.setXYZ(O,0,0,0);let Q=new j,W=new j,K=new j,X=new j,H=new j,N=new j,Y=new j,G=new j;if($)for(let O=0,E=$.count;O<E;O+=3){let k=$.getX(O+0),I=$.getX(O+1),R=$.getX(O+2);Q.fromBufferAttribute(U,k),W.fromBufferAttribute(U,I),K.fromBufferAttribute(U,R),Y.subVectors(K,W),G.subVectors(Q,W),Y.cross(G),X.fromBufferAttribute(J,k),H.fromBufferAttribute(J,I),N.fromBufferAttribute(J,R),X.add(Y),H.add(Y),N.add(Y),J.setXYZ(k,X.x,X.y,X.z),J.setXYZ(I,H.x,H.y,H.z),J.setXYZ(R,N.x,N.y,N.z)}else for(let O=0,E=U.count;O<E;O+=3)Q.fromBufferAttribute(U,O+0),W.fromBufferAttribute(U,O+1),K.fromBufferAttribute(U,O+2),Y.subVectors(K,W),G.subVectors(Q,W),Y.cross(G),J.setXYZ(O+0,Y.x,Y.y,Y.z),J.setXYZ(O+1,Y.x,Y.y,Y.z),J.setXYZ(O+2,Y.x,Y.y,Y.z);this.normalizeNormals(),J.needsUpdate=!0}}normalizeNormals(){let $=this.attributes.normal;for(let U=0,J=$.count;U<J;U++)d6.fromBufferAttribute($,U),d6.normalize(),$.setXYZ(U,d6.x,d6.y,d6.z)}toNonIndexed(){function $(X,H){let{array:N,itemSize:Y,normalized:G}=X,O=new N.constructor(H.length*Y),E=0,k=0;for(let I=0,R=H.length;I<R;I++){if(X.isInterleavedBufferAttribute)E=H[I]*X.data.stride+X.offset;else E=H[I]*Y;for(let q=0;q<Y;q++)O[k++]=N[E++]}return new h6(O,Y,G)}if(this.index===null)return A$("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let U=new KU,J=this.index.array,Q=this.attributes;for(let X in Q){let H=Q[X],N=$(H,J);U.setAttribute(X,N)}let W=this.morphAttributes;for(let X in W){let H=[],N=W[X];for(let Y=0,G=N.length;Y<G;Y++){let O=N[Y],E=$(O,J);H.push(E)}U.morphAttributes[X]=H}U.morphTargetsRelative=this.morphTargetsRelative;let K=this.groups;for(let X=0,H=K.length;X<H;X++){let N=K[X];U.addGroup(N.start,N.count,N.materialIndex)}return U}toJSON(){let $={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if($.uuid=this.uuid,$.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!=="")$.name=this.name;if(Object.keys(this.userData).length>0)$.userData=this.userData;if(this.parameters!==void 0&&this._transformed!==!0){let H=this.parameters;for(let N in H)if(H[N]!==void 0)$[N]=H[N];return $}$.data={attributes:{}};let U=this.index;if(U!==null)$.data.index={type:U.array.constructor.name,array:Array.prototype.slice.call(U.array)};let J=this.attributes;for(let H in J){let N=J[H];$.data.attributes[H]=N.toJSON($.data)}let Q={},W=!1;for(let H in this.morphAttributes){let N=this.morphAttributes[H],Y=[];for(let G=0,O=N.length;G<O;G++){let E=N[G];Y.push(E.toJSON($.data))}if(Y.length>0)Q[H]=Y,W=!0}if(W)$.data.morphAttributes=Q,$.data.morphTargetsRelative=this.morphTargetsRelative;let K=this.groups;if(K.length>0)$.data.groups=JSON.parse(JSON.stringify(K));let X=this.boundingSphere;if(X!==null)$.data.boundingSphere=X.toJSON();return $}clone(){return new this.constructor().copy(this)}copy($){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let U={};this.name=$.name;let J=$.index;if(J!==null)this.setIndex(J.clone());let Q=$.attributes;for(let N in Q){let Y=Q[N];this.setAttribute(N,Y.clone(U))}let W=$.morphAttributes;for(let N in W){let Y=[],G=W[N];for(let O=0,E=G.length;O<E;O++)Y.push(G[O].clone(U));this.morphAttributes[N]=Y}this.morphTargetsRelative=$.morphTargetsRelative;let K=$.groups;for(let N=0,Y=K.length;N<Y;N++){let G=K[N];this.addGroup(G.start,G.count,G.materialIndex)}let X=$.boundingBox;if(X!==null)this.boundingBox=X.clone();let H=$.boundingSphere;if(H!==null)this.boundingSphere=H.clone();return this.drawRange.start=$.drawRange.start,this.drawRange.count=$.drawRange.count,this.userData=$.userData,this._transformed=$._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class CW{constructor($,U){this.isInterleavedBuffer=!0,this.array=$,this.stride=U,this.count=$!==void 0?$.length/U:0,this.usage=35044,this.updateRanges=[],this.version=0,this.uuid=pU()}onUploadCallback(){}set needsUpdate($){if($===!0)this.version++}setUsage($){return this.usage=$,this}addUpdateRange($,U){this.updateRanges.push({start:$,count:U})}clearUpdateRanges(){this.updateRanges.length=0}copy($){return this.array=new $.array.constructor($.array),this.count=$.count,this.stride=$.stride,this.usage=$.usage,this}copyAt($,U,J){$*=this.stride,J*=U.stride;for(let Q=0,W=this.stride;Q<W;Q++)this.array[$+Q]=U.array[J+Q];return this}set($,U=0){return this.array.set($,U),this}clone($){if($.arrayBuffers===void 0)$.arrayBuffers={};if(this.array.buffer._uuid===void 0)this.array.buffer._uuid=pU();if($.arrayBuffers[this.array.buffer._uuid]===void 0)$.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer;let U=new this.array.constructor($.arrayBuffers[this.array.buffer._uuid]),J=new this.constructor(U,this.stride);return J.setUsage(this.usage),J}onUpload($){return this.onUploadCallback=$,this}toJSON($){if($.arrayBuffers===void 0)$.arrayBuffers={};if(this.array.buffer._uuid===void 0)this.array.buffer._uuid=pU();if($.arrayBuffers[this.array.buffer._uuid]===void 0)$.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer));return{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}var WU=new j;class w8{constructor($,U,J,Q=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=$,this.itemSize=U,this.offset=J,this.normalized=Q}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate($){this.data.needsUpdate=$}applyMatrix4($){for(let U=0,J=this.data.count;U<J;U++)WU.fromBufferAttribute(this,U),WU.applyMatrix4($),this.setXYZ(U,WU.x,WU.y,WU.z);return this}applyNormalMatrix($){for(let U=0,J=this.count;U<J;U++)WU.fromBufferAttribute(this,U),WU.applyNormalMatrix($),this.setXYZ(U,WU.x,WU.y,WU.z);return this}transformDirection($){for(let U=0,J=this.count;U<J;U++)WU.fromBufferAttribute(this,U),WU.transformDirection($),this.setXYZ(U,WU.x,WU.y,WU.z);return this}getComponent($,U){let J=this.array[$*this.data.stride+this.offset+U];if(this.normalized)J=mU(J,this.array);return J}setComponent($,U,J){if(this.normalized)J=O6(J,this.array);return this.data.array[$*this.data.stride+this.offset+U]=J,this}setX($,U){if(this.normalized)U=O6(U,this.array);return this.data.array[$*this.data.stride+this.offset]=U,this}setY($,U){if(this.normalized)U=O6(U,this.array);return this.data.array[$*this.data.stride+this.offset+1]=U,this}setZ($,U){if(this.normalized)U=O6(U,this.array);return this.data.array[$*this.data.stride+this.offset+2]=U,this}setW($,U){if(this.normalized)U=O6(U,this.array);return this.data.array[$*this.data.stride+this.offset+3]=U,this}getX($){let U=this.data.array[$*this.data.stride+this.offset];if(this.normalized)U=mU(U,this.array);return U}getY($){let U=this.data.array[$*this.data.stride+this.offset+1];if(this.normalized)U=mU(U,this.array);return U}getZ($){let U=this.data.array[$*this.data.stride+this.offset+2];if(this.normalized)U=mU(U,this.array);return U}getW($){let U=this.data.array[$*this.data.stride+this.offset+3];if(this.normalized)U=mU(U,this.array);return U}setXY($,U,J){if($=$*this.data.stride+this.offset,this.normalized)U=O6(U,this.array),J=O6(J,this.array);return this.data.array[$+0]=U,this.data.array[$+1]=J,this}setXYZ($,U,J,Q){if($=$*this.data.stride+this.offset,this.normalized)U=O6(U,this.array),J=O6(J,this.array),Q=O6(Q,this.array);return this.data.array[$+0]=U,this.data.array[$+1]=J,this.data.array[$+2]=Q,this}setXYZW($,U,J,Q,W){if($=$*this.data.stride+this.offset,this.normalized)U=O6(U,this.array),J=O6(J,this.array),Q=O6(Q,this.array),W=O6(W,this.array);return this.data.array[$+0]=U,this.data.array[$+1]=J,this.data.array[$+2]=Q,this.data.array[$+3]=W,this}clone($){if($===void 0){LW("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");let U=[];for(let J=0;J<this.count;J++){let Q=J*this.data.stride+this.offset;for(let W=0;W<this.itemSize;W++)U.push(this.data.array[Q+W])}return new h6(new this.array.constructor(U),this.itemSize,this.normalized)}else{if($.interleavedBuffers===void 0)$.interleavedBuffers={};if($.interleavedBuffers[this.data.uuid]===void 0)$.interleavedBuffers[this.data.uuid]=this.data.clone($);return new w8($.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}}toJSON($){if($===void 0){LW("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");let U=[];for(let J=0;J<this.count;J++){let Q=J*this.data.stride+this.offset;for(let W=0;W<this.itemSize;W++)U.push(this.data.array[Q+W])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:U,normalized:this.normalized}}else{if($.interleavedBuffers===void 0)$.interleavedBuffers={};if($.interleavedBuffers[this.data.uuid]===void 0)$.interleavedBuffers[this.data.uuid]=this.data.toJSON($);return{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}}var yF=0;class EU extends iU{constructor(){super();this.isMaterial=!0,Object.defineProperty(this,"id",{value:yF++}),this.uuid=pU(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new y$(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=7680,this.stencilZFail=7680,this.stencilZPass=7680,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($){if(this._alphaTest>0!==$>0)this.version++;this._alphaTest=$}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues($){if($===void 0)return;for(let U in $){let J=$[U];if(J===void 0){A$(`Material: parameter '${U}' has value of undefined.`);continue}let Q=this[U];if(Q===void 0){A$(`Material: '${U}' is not a property of THREE.${this.type}.`);continue}if(Q&&Q.isColor)Q.set(J);else if(Q&&Q.isVector2&&(J&&J.isVector2)||Q&&Q.isEuler&&(J&&J.isEuler)||Q&&Q.isVector3&&(J&&J.isVector3))Q.copy(J);else this[U]=J}}toJSON($){let U=$===void 0||typeof $==="string";if(U)$={textures:{},images:{}};let J={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};if(J.uuid=this.uuid,J.type=this.type,this.name!=="")J.name=this.name;if(this.color&&this.color.isColor)J.color=this.color.getHex();if(this.roughness!==void 0)J.roughness=this.roughness;if(this.metalness!==void 0)J.metalness=this.metalness;if(this.sheen!==void 0)J.sheen=this.sheen;if(this.sheenColor&&this.sheenColor.isColor)J.sheenColor=this.sheenColor.getHex();if(this.sheenRoughness!==void 0)J.sheenRoughness=this.sheenRoughness;if(this.emissive&&this.emissive.isColor)J.emissive=this.emissive.getHex();if(this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1)J.emissiveIntensity=this.emissiveIntensity;if(this.specular&&this.specular.isColor)J.specular=this.specular.getHex();if(this.specularIntensity!==void 0)J.specularIntensity=this.specularIntensity;if(this.specularColor&&this.specularColor.isColor)J.specularColor=this.specularColor.getHex();if(this.shininess!==void 0)J.shininess=this.shininess;if(this.clearcoat!==void 0)J.clearcoat=this.clearcoat;if(this.clearcoatRoughness!==void 0)J.clearcoatRoughness=this.clearcoatRoughness;if(this.clearcoatMap&&this.clearcoatMap.isTexture)J.clearcoatMap=this.clearcoatMap.toJSON($).uuid;if(this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture)J.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON($).uuid;if(this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture)J.clearcoatNormalMap=this.clearcoatNormalMap.toJSON($).uuid,J.clearcoatNormalScale=this.clearcoatNormalScale.toArray();if(this.sheenColorMap&&this.sheenColorMap.isTexture)J.sheenColorMap=this.sheenColorMap.toJSON($).uuid;if(this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture)J.sheenRoughnessMap=this.sheenRoughnessMap.toJSON($).uuid;if(this.dispersion!==void 0)J.dispersion=this.dispersion;if(this.iridescence!==void 0)J.iridescence=this.iridescence;if(this.iridescenceIOR!==void 0)J.iridescenceIOR=this.iridescenceIOR;if(this.iridescenceThicknessRange!==void 0)J.iridescenceThicknessRange=this.iridescenceThicknessRange;if(this.iridescenceMap&&this.iridescenceMap.isTexture)J.iridescenceMap=this.iridescenceMap.toJSON($).uuid;if(this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture)J.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON($).uuid;if(this.anisotropy!==void 0)J.anisotropy=this.anisotropy;if(this.anisotropyRotation!==void 0)J.anisotropyRotation=this.anisotropyRotation;if(this.anisotropyMap&&this.anisotropyMap.isTexture)J.anisotropyMap=this.anisotropyMap.toJSON($).uuid;if(this.map&&this.map.isTexture)J.map=this.map.toJSON($).uuid;if(this.matcap&&this.matcap.isTexture)J.matcap=this.matcap.toJSON($).uuid;if(this.alphaMap&&this.alphaMap.isTexture)J.alphaMap=this.alphaMap.toJSON($).uuid;if(this.lightMap&&this.lightMap.isTexture)J.lightMap=this.lightMap.toJSON($).uuid,J.lightMapIntensity=this.lightMapIntensity;if(this.aoMap&&this.aoMap.isTexture)J.aoMap=this.aoMap.toJSON($).uuid,J.aoMapIntensity=this.aoMapIntensity;if(this.bumpMap&&this.bumpMap.isTexture)J.bumpMap=this.bumpMap.toJSON($).uuid,J.bumpScale=this.bumpScale;if(this.normalMap&&this.normalMap.isTexture)J.normalMap=this.normalMap.toJSON($).uuid,J.normalMapType=this.normalMapType,J.normalScale=this.normalScale.toArray();if(this.displacementMap&&this.displacementMap.isTexture)J.displacementMap=this.displacementMap.toJSON($).uuid,J.displacementScale=this.displacementScale,J.displacementBias=this.displacementBias;if(this.roughnessMap&&this.roughnessMap.isTexture)J.roughnessMap=this.roughnessMap.toJSON($).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)J.metalnessMap=this.metalnessMap.toJSON($).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)J.emissiveMap=this.emissiveMap.toJSON($).uuid;if(this.specularMap&&this.specularMap.isTexture)J.specularMap=this.specularMap.toJSON($).uuid;if(this.specularIntensityMap&&this.specularIntensityMap.isTexture)J.specularIntensityMap=this.specularIntensityMap.toJSON($).uuid;if(this.specularColorMap&&this.specularColorMap.isTexture)J.specularColorMap=this.specularColorMap.toJSON($).uuid;if(this.envMap&&this.envMap.isTexture){if(J.envMap=this.envMap.toJSON($).uuid,this.combine!==void 0)J.combine=this.combine}if(this.envMapRotation!==void 0)J.envMapRotation=this.envMapRotation.toArray();if(this.envMapIntensity!==void 0)J.envMapIntensity=this.envMapIntensity;if(this.reflectivity!==void 0)J.reflectivity=this.reflectivity;if(this.refractionRatio!==void 0)J.refractionRatio=this.refractionRatio;if(this.gradientMap&&this.gradientMap.isTexture)J.gradientMap=this.gradientMap.toJSON($).uuid;if(this.transmission!==void 0)J.transmission=this.transmission;if(this.transmissionMap&&this.transmissionMap.isTexture)J.transmissionMap=this.transmissionMap.toJSON($).uuid;if(this.thickness!==void 0)J.thickness=this.thickness;if(this.thicknessMap&&this.thicknessMap.isTexture)J.thicknessMap=this.thicknessMap.toJSON($).uuid;if(this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0)J.attenuationDistance=this.attenuationDistance;if(this.attenuationColor!==void 0)J.attenuationColor=this.attenuationColor.getHex();if(this.size!==void 0)J.size=this.size;if(this.shadowSide!==null)J.shadowSide=this.shadowSide;if(this.sizeAttenuation!==void 0)J.sizeAttenuation=this.sizeAttenuation;if(this.blending!==1)J.blending=this.blending;if(this.side!==0)J.side=this.side;if(this.vertexColors===!0)J.vertexColors=!0;if(this.opacity<1)J.opacity=this.opacity;if(this.transparent===!0)J.transparent=!0;if(this.blendSrc!==204)J.blendSrc=this.blendSrc;if(this.blendDst!==205)J.blendDst=this.blendDst;if(this.blendEquation!==100)J.blendEquation=this.blendEquation;if(this.blendSrcAlpha!==null)J.blendSrcAlpha=this.blendSrcAlpha;if(this.blendDstAlpha!==null)J.blendDstAlpha=this.blendDstAlpha;if(this.blendEquationAlpha!==null)J.blendEquationAlpha=this.blendEquationAlpha;if(this.blendColor&&this.blendColor.isColor)J.blendColor=this.blendColor.getHex();if(this.blendAlpha!==0)J.blendAlpha=this.blendAlpha;if(this.depthFunc!==3)J.depthFunc=this.depthFunc;if(this.depthTest===!1)J.depthTest=this.depthTest;if(this.depthWrite===!1)J.depthWrite=this.depthWrite;if(this.colorWrite===!1)J.colorWrite=this.colorWrite;if(this.stencilWriteMask!==255)J.stencilWriteMask=this.stencilWriteMask;if(this.stencilFunc!==519)J.stencilFunc=this.stencilFunc;if(this.stencilRef!==0)J.stencilRef=this.stencilRef;if(this.stencilFuncMask!==255)J.stencilFuncMask=this.stencilFuncMask;if(this.stencilFail!==7680)J.stencilFail=this.stencilFail;if(this.stencilZFail!==7680)J.stencilZFail=this.stencilZFail;if(this.stencilZPass!==7680)J.stencilZPass=this.stencilZPass;if(this.stencilWrite===!0)J.stencilWrite=this.stencilWrite;if(this.rotation!==void 0&&this.rotation!==0)J.rotation=this.rotation;if(this.polygonOffset===!0)J.polygonOffset=!0;if(this.polygonOffsetFactor!==0)J.polygonOffsetFactor=this.polygonOffsetFactor;if(this.polygonOffsetUnits!==0)J.polygonOffsetUnits=this.polygonOffsetUnits;if(this.linewidth!==void 0&&this.linewidth!==1)J.linewidth=this.linewidth;if(this.dashSize!==void 0)J.dashSize=this.dashSize;if(this.gapSize!==void 0)J.gapSize=this.gapSize;if(this.scale!==void 0)J.scale=this.scale;if(this.dithering===!0)J.dithering=!0;if(this.alphaTest>0)J.alphaTest=this.alphaTest;if(this.alphaHash===!0)J.alphaHash=!0;if(this.alphaToCoverage===!0)J.alphaToCoverage=!0;if(this.premultipliedAlpha===!0)J.premultipliedAlpha=!0;if(this.forceSinglePass===!0)J.forceSinglePass=!0;if(this.allowOverride===!1)J.allowOverride=!1;if(this.wireframe===!0)J.wireframe=!0;if(this.wireframeLinewidth>1)J.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=="round")J.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=="round")J.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading===!0)J.flatShading=!0;if(this.visible===!1)J.visible=!1;if(this.toneMapped===!1)J.toneMapped=!1;if(this.fog===!1)J.fog=!1;if(Object.keys(this.userData).length>0)J.userData=this.userData;function Q(W){let K=[];for(let X in W){let H=W[X];delete H.metadata,K.push(H)}return K}if(U){let W=Q($.textures),K=Q($.images);if(W.length>0)J.textures=W;if(K.length>0)J.images=K}return J}fromJSON($,U){if($.uuid!==void 0)this.uuid=$.uuid;if($.name!==void 0)this.name=$.name;if($.color!==void 0&&this.color!==void 0)this.color.setHex($.color);if($.roughness!==void 0)this.roughness=$.roughness;if($.metalness!==void 0)this.metalness=$.metalness;if($.sheen!==void 0)this.sheen=$.sheen;if($.sheenColor!==void 0)this.sheenColor=new y$().setHex($.sheenColor);if($.sheenRoughness!==void 0)this.sheenRoughness=$.sheenRoughness;if($.emissive!==void 0&&this.emissive!==void 0)this.emissive.setHex($.emissive);if($.specular!==void 0&&this.specular!==void 0)this.specular.setHex($.specular);if($.specularIntensity!==void 0)this.specularIntensity=$.specularIntensity;if($.specularColor!==void 0&&this.specularColor!==void 0)this.specularColor.setHex($.specularColor);if($.shininess!==void 0)this.shininess=$.shininess;if($.clearcoat!==void 0)this.clearcoat=$.clearcoat;if($.clearcoatRoughness!==void 0)this.clearcoatRoughness=$.clearcoatRoughness;if($.dispersion!==void 0)this.dispersion=$.dispersion;if($.iridescence!==void 0)this.iridescence=$.iridescence;if($.iridescenceIOR!==void 0)this.iridescenceIOR=$.iridescenceIOR;if($.iridescenceThicknessRange!==void 0)this.iridescenceThicknessRange=$.iridescenceThicknessRange;if($.transmission!==void 0)this.transmission=$.transmission;if($.thickness!==void 0)this.thickness=$.thickness;if($.attenuationDistance!==void 0)this.attenuationDistance=$.attenuationDistance;if($.attenuationColor!==void 0&&this.attenuationColor!==void 0)this.attenuationColor.setHex($.attenuationColor);if($.anisotropy!==void 0)this.anisotropy=$.anisotropy;if($.anisotropyRotation!==void 0)this.anisotropyRotation=$.anisotropyRotation;if($.fog!==void 0)this.fog=$.fog;if($.flatShading!==void 0)this.flatShading=$.flatShading;if($.blending!==void 0)this.blending=$.blending;if($.combine!==void 0)this.combine=$.combine;if($.side!==void 0)this.side=$.side;if($.shadowSide!==void 0)this.shadowSide=$.shadowSide;if($.opacity!==void 0)this.opacity=$.opacity;if($.transparent!==void 0)this.transparent=$.transparent;if($.alphaTest!==void 0)this.alphaTest=$.alphaTest;if($.alphaHash!==void 0)this.alphaHash=$.alphaHash;if($.depthFunc!==void 0)this.depthFunc=$.depthFunc;if($.depthTest!==void 0)this.depthTest=$.depthTest;if($.depthWrite!==void 0)this.depthWrite=$.depthWrite;if($.colorWrite!==void 0)this.colorWrite=$.colorWrite;if($.blendSrc!==void 0)this.blendSrc=$.blendSrc;if($.blendDst!==void 0)this.blendDst=$.blendDst;if($.blendEquation!==void 0)this.blendEquation=$.blendEquation;if($.blendSrcAlpha!==void 0)this.blendSrcAlpha=$.blendSrcAlpha;if($.blendDstAlpha!==void 0)this.blendDstAlpha=$.blendDstAlpha;if($.blendEquationAlpha!==void 0)this.blendEquationAlpha=$.blendEquationAlpha;if($.blendColor!==void 0&&this.blendColor!==void 0)this.blendColor.setHex($.blendColor);if($.blendAlpha!==void 0)this.blendAlpha=$.blendAlpha;if($.stencilWriteMask!==void 0)this.stencilWriteMask=$.stencilWriteMask;if($.stencilFunc!==void 0)this.stencilFunc=$.stencilFunc;if($.stencilRef!==void 0)this.stencilRef=$.stencilRef;if($.stencilFuncMask!==void 0)this.stencilFuncMask=$.stencilFuncMask;if($.stencilFail!==void 0)this.stencilFail=$.stencilFail;if($.stencilZFail!==void 0)this.stencilZFail=$.stencilZFail;if($.stencilZPass!==void 0)this.stencilZPass=$.stencilZPass;if($.stencilWrite!==void 0)this.stencilWrite=$.stencilWrite;if($.wireframe!==void 0)this.wireframe=$.wireframe;if($.wireframeLinewidth!==void 0)this.wireframeLinewidth=$.wireframeLinewidth;if($.wireframeLinecap!==void 0)this.wireframeLinecap=$.wireframeLinecap;if($.wireframeLinejoin!==void 0)this.wireframeLinejoin=$.wireframeLinejoin;if($.rotation!==void 0)this.rotation=$.rotation;if($.linewidth!==void 0)this.linewidth=$.linewidth;if($.dashSize!==void 0)this.dashSize=$.dashSize;if($.gapSize!==void 0)this.gapSize=$.gapSize;if($.scale!==void 0)this.scale=$.scale;if($.polygonOffset!==void 0)this.polygonOffset=$.polygonOffset;if($.polygonOffsetFactor!==void 0)this.polygonOffsetFactor=$.polygonOffsetFactor;if($.polygonOffsetUnits!==void 0)this.polygonOffsetUnits=$.polygonOffsetUnits;if($.dithering!==void 0)this.dithering=$.dithering;if($.alphaToCoverage!==void 0)this.alphaToCoverage=$.alphaToCoverage;if($.premultipliedAlpha!==void 0)this.premultipliedAlpha=$.premultipliedAlpha;if($.forceSinglePass!==void 0)this.forceSinglePass=$.forceSinglePass;if($.allowOverride!==void 0)this.allowOverride=$.allowOverride;if($.visible!==void 0)this.visible=$.visible;if($.toneMapped!==void 0)this.toneMapped=$.toneMapped;if($.userData!==void 0)this.userData=$.userData;if($.vertexColors!==void 0)if(typeof $.vertexColors==="number")this.vertexColors=$.vertexColors>0;else this.vertexColors=$.vertexColors;if($.size!==void 0)this.size=$.size;if($.sizeAttenuation!==void 0)this.sizeAttenuation=$.sizeAttenuation;if($.map!==void 0)this.map=U[$.map]||null;if($.matcap!==void 0)this.matcap=U[$.matcap]||null;if($.alphaMap!==void 0)this.alphaMap=U[$.alphaMap]||null;if($.bumpMap!==void 0)this.bumpMap=U[$.bumpMap]||null;if($.bumpScale!==void 0)this.bumpScale=$.bumpScale;if($.normalMap!==void 0)this.normalMap=U[$.normalMap]||null;if($.normalMapType!==void 0)this.normalMapType=$.normalMapType;if($.normalScale!==void 0){let J=$.normalScale;if(Array.isArray(J)===!1)J=[J,J];this.normalScale=new g$().fromArray(J)}if($.displacementMap!==void 0)this.displacementMap=U[$.displacementMap]||null;if($.displacementScale!==void 0)this.displacementScale=$.displacementScale;if($.displacementBias!==void 0)this.displacementBias=$.displacementBias;if($.roughnessMap!==void 0)this.roughnessMap=U[$.roughnessMap]||null;if($.metalnessMap!==void 0)this.metalnessMap=U[$.metalnessMap]||null;if($.emissiveMap!==void 0)this.emissiveMap=U[$.emissiveMap]||null;if($.emissiveIntensity!==void 0)this.emissiveIntensity=$.emissiveIntensity;if($.specularMap!==void 0)this.specularMap=U[$.specularMap]||null;if($.specularIntensityMap!==void 0)this.specularIntensityMap=U[$.specularIntensityMap]||null;if($.specularColorMap!==void 0)this.specularColorMap=U[$.specularColorMap]||null;if($.envMap!==void 0)this.envMap=U[$.envMap]||null;if($.envMapRotation!==void 0)this.envMapRotation.fromArray($.envMapRotation);if($.envMapIntensity!==void 0)this.envMapIntensity=$.envMapIntensity;if($.reflectivity!==void 0)this.reflectivity=$.reflectivity;if($.refractionRatio!==void 0)this.refractionRatio=$.refractionRatio;if($.lightMap!==void 0)this.lightMap=U[$.lightMap]||null;if($.lightMapIntensity!==void 0)this.lightMapIntensity=$.lightMapIntensity;if($.aoMap!==void 0)this.aoMap=U[$.aoMap]||null;if($.aoMapIntensity!==void 0)this.aoMapIntensity=$.aoMapIntensity;if($.gradientMap!==void 0)this.gradientMap=U[$.gradientMap]||null;if($.clearcoatMap!==void 0)this.clearcoatMap=U[$.clearcoatMap]||null;if($.clearcoatRoughnessMap!==void 0)this.clearcoatRoughnessMap=U[$.clearcoatRoughnessMap]||null;if($.clearcoatNormalMap!==void 0)this.clearcoatNormalMap=U[$.clearcoatNormalMap]||null;if($.clearcoatNormalScale!==void 0)this.clearcoatNormalScale=new g$().fromArray($.clearcoatNormalScale);if($.iridescenceMap!==void 0)this.iridescenceMap=U[$.iridescenceMap]||null;if($.iridescenceThicknessMap!==void 0)this.iridescenceThicknessMap=U[$.iridescenceThicknessMap]||null;if($.transmissionMap!==void 0)this.transmissionMap=U[$.transmissionMap]||null;if($.thicknessMap!==void 0)this.thicknessMap=U[$.thicknessMap]||null;if($.anisotropyMap!==void 0)this.anisotropyMap=U[$.anisotropyMap]||null;if($.sheenColorMap!==void 0)this.sheenColorMap=U[$.sheenColorMap]||null;if($.sheenRoughnessMap!==void 0)this.sheenRoughnessMap=U[$.sheenRoughnessMap]||null;return this}clone(){return new this.constructor().copy(this)}copy($){this.name=$.name,this.blending=$.blending,this.side=$.side,this.vertexColors=$.vertexColors,this.opacity=$.opacity,this.transparent=$.transparent,this.blendSrc=$.blendSrc,this.blendDst=$.blendDst,this.blendEquation=$.blendEquation,this.blendSrcAlpha=$.blendSrcAlpha,this.blendDstAlpha=$.blendDstAlpha,this.blendEquationAlpha=$.blendEquationAlpha,this.blendColor.copy($.blendColor),this.blendAlpha=$.blendAlpha,this.depthFunc=$.depthFunc,this.depthTest=$.depthTest,this.depthWrite=$.depthWrite,this.stencilWriteMask=$.stencilWriteMask,this.stencilFunc=$.stencilFunc,this.stencilRef=$.stencilRef,this.stencilFuncMask=$.stencilFuncMask,this.stencilFail=$.stencilFail,this.stencilZFail=$.stencilZFail,this.stencilZPass=$.stencilZPass,this.stencilWrite=$.stencilWrite;let U=$.clippingPlanes,J=null;if(U!==null){let Q=U.length;J=Array(Q);for(let W=0;W!==Q;++W)J[W]=U[W].clone()}return this.clippingPlanes=J,this.clipIntersection=$.clipIntersection,this.clipShadows=$.clipShadows,this.shadowSide=$.shadowSide,this.colorWrite=$.colorWrite,this.precision=$.precision,this.polygonOffset=$.polygonOffset,this.polygonOffsetFactor=$.polygonOffsetFactor,this.polygonOffsetUnits=$.polygonOffsetUnits,this.dithering=$.dithering,this.alphaTest=$.alphaTest,this.alphaHash=$.alphaHash,this.alphaToCoverage=$.alphaToCoverage,this.premultipliedAlpha=$.premultipliedAlpha,this.forceSinglePass=$.forceSinglePass,this.allowOverride=$.allowOverride,this.visible=$.visible,this.toneMapped=$.toneMapped,this.userData=JSON.parse(JSON.stringify($.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate($){if($===!0)this.version++}}var PJ=new j,i7=new j,mQ=new j,dJ=new j,o7=new j,pQ=new j,r7=new j;class sJ{constructor($=new j,U=new j(0,0,-1)){this.origin=$,this.direction=U}set($,U){return this.origin.copy($),this.direction.copy(U),this}copy($){return this.origin.copy($.origin),this.direction.copy($.direction),this}at($,U){return U.copy(this.origin).addScaledVector(this.direction,$)}lookAt($){return this.direction.copy($).sub(this.origin).normalize(),this}recast($){return this.origin.copy(this.at($,PJ)),this}closestPointToPoint($,U){U.subVectors($,this.origin);let J=U.dot(this.direction);if(J<0)return U.copy(this.origin);return U.copy(this.origin).addScaledVector(this.direction,J)}distanceToPoint($){return Math.sqrt(this.distanceSqToPoint($))}distanceSqToPoint($){let U=PJ.subVectors($,this.origin).dot(this.direction);if(U<0)return this.origin.distanceToSquared($);return PJ.copy(this.origin).addScaledVector(this.direction,U),PJ.distanceToSquared($)}distanceSqToSegment($,U,J,Q){i7.copy($).add(U).multiplyScalar(0.5),mQ.copy(U).sub($).normalize(),dJ.copy(this.origin).sub(i7);let W=$.distanceTo(U)*0.5,K=-this.direction.dot(mQ),X=dJ.dot(this.direction),H=-dJ.dot(mQ),N=dJ.lengthSq(),Y=Math.abs(1-K*K),G,O,E,k;if(Y>0)if(G=K*H-X,O=K*X-H,k=W*Y,G>=0)if(O>=-k)if(O<=k){let I=1/Y;G*=I,O*=I,E=G*(G+K*O+2*X)+O*(K*G+O+2*H)+N}else O=W,G=Math.max(0,-(K*O+X)),E=-G*G+O*(O+2*H)+N;else O=-W,G=Math.max(0,-(K*O+X)),E=-G*G+O*(O+2*H)+N;else if(O<=-k)G=Math.max(0,-(-K*W+X)),O=G>0?-W:Math.min(Math.max(-W,-H),W),E=-G*G+O*(O+2*H)+N;else if(O<=k)G=0,O=Math.min(Math.max(-W,-H),W),E=O*(O+2*H)+N;else G=Math.max(0,-(K*W+X)),O=G>0?W:Math.min(Math.max(-W,-H),W),E=-G*G+O*(O+2*H)+N;else O=K>0?-W:W,G=Math.max(0,-(K*O+X)),E=-G*G+O*(O+2*H)+N;if(J)J.copy(this.origin).addScaledVector(this.direction,G);if(Q)Q.copy(i7).addScaledVector(mQ,O);return E}intersectSphere($,U){PJ.subVectors($.center,this.origin);let J=PJ.dot(this.direction),Q=PJ.dot(PJ)-J*J,W=$.radius*$.radius;if(Q>W)return null;let K=Math.sqrt(W-Q),X=J-K,H=J+K;if(H<0)return null;if(X<0)return this.at(H,U);return this.at(X,U)}intersectsSphere($){if($.radius<0)return!1;return this.distanceSqToPoint($.center)<=$.radius*$.radius}distanceToPlane($){let U=$.normal.dot(this.direction);if(U===0){if($.distanceToPoint(this.origin)===0)return 0;return null}let J=-(this.origin.dot($.normal)+$.constant)/U;return J>=0?J:null}intersectPlane($,U){let J=this.distanceToPlane($);if(J===null)return null;return this.at(J,U)}intersectsPlane($){let U=$.distanceToPoint(this.origin);if(U===0)return!0;if($.normal.dot(this.direction)*U<0)return!0;return!1}intersectBox($,U){let J,Q,W,K,X,H,N=1/this.direction.x,Y=1/this.direction.y,G=1/this.direction.z,O=this.origin;if(N>=0)J=($.min.x-O.x)*N,Q=($.max.x-O.x)*N;else J=($.max.x-O.x)*N,Q=($.min.x-O.x)*N;if(Y>=0)W=($.min.y-O.y)*Y,K=($.max.y-O.y)*Y;else W=($.max.y-O.y)*Y,K=($.min.y-O.y)*Y;if(J>K||W>Q)return null;if(W>J||isNaN(J))J=W;if(K<Q||isNaN(Q))Q=K;if(G>=0)X=($.min.z-O.z)*G,H=($.max.z-O.z)*G;else X=($.max.z-O.z)*G,H=($.min.z-O.z)*G;if(J>H||X>Q)return null;if(X>J||J!==J)J=X;if(H<Q||Q!==Q)Q=H;if(Q<0)return null;return this.at(J>=0?J:Q,U)}intersectsBox($){return this.intersectBox($,PJ)!==null}intersectTriangle($,U,J,Q,W){o7.subVectors(U,$),pQ.subVectors(J,$),r7.crossVectors(o7,pQ);let K=this.direction.dot(r7),X;if(K>0){if(Q)return null;X=1}else if(K<0)X=-1,K=-K;else return null;dJ.subVectors(this.origin,$);let H=X*this.direction.dot(pQ.crossVectors(dJ,pQ));if(H<0)return null;let N=X*this.direction.dot(o7.cross(dJ));if(N<0)return null;if(H+N>K)return null;let Y=-X*dJ.dot(r7);if(Y<0)return null;return this.at(Y/K,W)}applyMatrix4($){return this.origin.applyMatrix4($),this.direction.transformDirection($),this}equals($){return $.origin.equals(this.origin)&&$.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class KJ extends EU{constructor($){super();this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new y$(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 UJ,this.combine=0,this.reflectivity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues($)}copy($){return super.copy($),this.color.copy($.color),this.map=$.map,this.lightMap=$.lightMap,this.lightMapIntensity=$.lightMapIntensity,this.aoMap=$.aoMap,this.aoMapIntensity=$.aoMapIntensity,this.specularMap=$.specularMap,this.alphaMap=$.alphaMap,this.envMap=$.envMap,this.envMapRotation.copy($.envMapRotation),this.combine=$.combine,this.reflectivity=$.reflectivity,this.refractionRatio=$.refractionRatio,this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this.wireframeLinecap=$.wireframeLinecap,this.wireframeLinejoin=$.wireframeLinejoin,this.fog=$.fog,this}}var Ak=new m$,V0=new sJ,dQ=new VU,Ck=new j,cQ=new j,nQ=new j,iQ=new j,a7=new j,oQ=new j,Sk=new j,rQ=new j;class B6 extends q6{constructor($=new KU,U=new KJ){super();this.isMesh=!0,this.type="Mesh",this.geometry=$,this.material=U,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy($,U){if(super.copy($,U),$.morphTargetInfluences!==void 0)this.morphTargetInfluences=$.morphTargetInfluences.slice();if($.morphTargetDictionary!==void 0)this.morphTargetDictionary=Object.assign({},$.morphTargetDictionary);return this.material=Array.isArray($.material)?$.material.slice():$.material,this.geometry=$.geometry,this}updateMorphTargets(){let U=this.geometry.morphAttributes,J=Object.keys(U);if(J.length>0){let Q=U[J[0]];if(Q!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let W=0,K=Q.length;W<K;W++){let X=Q[W].name||String(W);this.morphTargetInfluences.push(0),this.morphTargetDictionary[X]=W}}}}getVertexPosition($,U){let J=this.geometry,Q=J.attributes.position,W=J.morphAttributes.position,K=J.morphTargetsRelative;U.fromBufferAttribute(Q,$);let X=this.morphTargetInfluences;if(W&&X){oQ.set(0,0,0);for(let H=0,N=W.length;H<N;H++){let Y=X[H],G=W[H];if(Y===0)continue;if(a7.fromBufferAttribute(G,$),K)oQ.addScaledVector(a7,Y);else oQ.addScaledVector(a7.sub(U),Y)}U.add(oQ)}return U}raycast($,U){let J=this.geometry,Q=this.material,W=this.matrixWorld;if(Q===void 0)return;if(J.boundingSphere===null)J.computeBoundingSphere();if(dQ.copy(J.boundingSphere),dQ.applyMatrix4(W),V0.copy($.ray).recast($.near),dQ.containsPoint(V0.origin)===!1){if(V0.intersectSphere(dQ,Ck)===null)return;if(V0.origin.distanceToSquared(Ck)>($.far-$.near)**2)return}if(Ak.copy(W).invert(),V0.copy($.ray).applyMatrix4(Ak),J.boundingBox!==null){if(V0.intersectsBox(J.boundingBox)===!1)return}this._computeIntersections($,U,V0)}_computeIntersections($,U,J){let Q,W=this.geometry,K=this.material,X=W.index,H=W.attributes.position,N=W.attributes.uv,Y=W.attributes.uv1,G=W.attributes.normal,O=W.groups,E=W.drawRange;if(X!==null)if(Array.isArray(K))for(let k=0,I=O.length;k<I;k++){let R=O[k],q=K[R.materialIndex],Z=Math.max(R.start,E.start),_=Math.min(X.count,Math.min(R.start+R.count,E.start+E.count));for(let P=Z,L=_;P<L;P+=3){let B=X.getX(P),z=X.getX(P+1),A=X.getX(P+2);if(Q=aQ(this,q,$,J,N,Y,G,B,z,A),Q)Q.faceIndex=Math.floor(P/3),Q.face.materialIndex=R.materialIndex,U.push(Q)}}else{let k=Math.max(0,E.start),I=Math.min(X.count,E.start+E.count);for(let R=k,q=I;R<q;R+=3){let Z=X.getX(R),_=X.getX(R+1),P=X.getX(R+2);if(Q=aQ(this,K,$,J,N,Y,G,Z,_,P),Q)Q.faceIndex=Math.floor(R/3),U.push(Q)}}else if(H!==void 0)if(Array.isArray(K))for(let k=0,I=O.length;k<I;k++){let R=O[k],q=K[R.materialIndex],Z=Math.max(R.start,E.start),_=Math.min(H.count,Math.min(R.start+R.count,E.start+E.count));for(let P=Z,L=_;P<L;P+=3){let B=P,z=P+1,A=P+2;if(Q=aQ(this,q,$,J,N,Y,G,B,z,A),Q)Q.faceIndex=Math.floor(P/3),Q.face.materialIndex=R.materialIndex,U.push(Q)}}else{let k=Math.max(0,E.start),I=Math.min(H.count,E.start+E.count);for(let R=k,q=I;R<q;R+=3){let Z=R,_=R+1,P=R+2;if(Q=aQ(this,K,$,J,N,Y,G,Z,_,P),Q)Q.faceIndex=Math.floor(R/3),U.push(Q)}}}}function xF($,U,J,Q,W,K,X,H){let N;if(U.side===1)N=Q.intersectTriangle(X,K,W,!0,H);else N=Q.intersectTriangle(W,K,X,U.side===0,H);if(N===null)return null;rQ.copy(H),rQ.applyMatrix4($.matrixWorld);let Y=J.ray.origin.distanceTo(rQ);if(Y<J.near||Y>J.far)return null;return{distance:Y,point:rQ.clone(),object:$}}function aQ($,U,J,Q,W,K,X,H,N,Y){$.getVertexPosition(H,cQ),$.getVertexPosition(N,nQ),$.getVertexPosition(Y,iQ);let G=xF($,U,J,Q,cQ,nQ,iQ,Sk);if(G){let O=new j;if(TU.getBarycoord(Sk,cQ,nQ,iQ,O),W)G.uv=TU.getInterpolatedAttribute(W,H,N,Y,O,new g$);if(K)G.uv1=TU.getInterpolatedAttribute(K,H,N,Y,O,new g$);if(X){if(G.normal=TU.getInterpolatedAttribute(X,H,N,Y,O,new j),G.normal.dot(Q.direction)>0)G.normal.multiplyScalar(-1)}let E={a:H,b:N,c:Y,normal:new j,materialIndex:0};TU.getNormal(cQ,nQ,iQ,E.normal),G.face=E,G.barycoord=O}return G}var kW=new E6,Tk=new E6,vk=new E6,hF=new E6,jk=new m$,sQ=new j,s7=new VU,gk=new m$,t7=new sJ;class z9 extends B6{constructor($,U){super($,U);this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new m$,this.bindMatrixInverse=new m$,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let $=this.geometry;if(this.boundingBox===null)this.boundingBox=new QU;this.boundingBox.makeEmpty();let U=$.getAttribute("position");for(let J=0;J<U.count;J++)this.getVertexPosition(J,sQ),this.boundingBox.expandByPoint(sQ)}computeBoundingSphere(){let $=this.geometry;if(this.boundingSphere===null)this.boundingSphere=new VU;this.boundingSphere.makeEmpty();let U=$.getAttribute("position");for(let J=0;J<U.count;J++)this.getVertexPosition(J,sQ),this.boundingSphere.expandByPoint(sQ)}copy($,U){if(super.copy($,U),this.bindMode=$.bindMode,this.bindMatrix.copy($.bindMatrix),this.bindMatrixInverse.copy($.bindMatrixInverse),this.skeleton=$.skeleton,$.boundingBox!==null)this.boundingBox=$.boundingBox.clone();if($.boundingSphere!==null)this.boundingSphere=$.boundingSphere.clone();return this}raycast($,U){let J=this.material,Q=this.matrixWorld;if(J===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(s7.copy(this.boundingSphere),s7.applyMatrix4(Q),$.ray.intersectsSphere(s7)===!1)return;if(gk.copy(Q).invert(),t7.copy($.ray).applyMatrix4(gk),this.boundingBox!==null){if(t7.intersectsBox(this.boundingBox)===!1)return}this._computeIntersections($,U,t7)}getVertexPosition($,U){return super.getVertexPosition($,U),this.applyBoneTransform($,U),U}bind($,U){if(this.skeleton=$,U===void 0)this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),U=this.matrixWorld;this.bindMatrix.copy(U),this.bindMatrixInverse.copy(U).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let $=new E6,U=this.geometry.attributes.skinWeight;for(let J=0,Q=U.count;J<Q;J++){$.fromBufferAttribute(U,J);let W=1/$.manhattanLength();if(W!==1/0)$.multiplyScalar(W);else $.set(1,0,0,0);U.setXYZW(J,$.x,$.y,$.z,$.w)}}updateMatrixWorld($){if(super.updateMatrixWorld($),this.bindMode==="attached")this.bindMatrixInverse.copy(this.matrixWorld).invert();else if(this.bindMode==="detached")this.bindMatrixInverse.copy(this.bindMatrix).invert();else A$("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform($,U){let J=this.skeleton,Q=this.geometry;if(Tk.fromBufferAttribute(Q.attributes.skinIndex,$),vk.fromBufferAttribute(Q.attributes.skinWeight,$),U.isVector4)kW.copy(U),U.set(0,0,0,0);else kW.set(...U,1),U.set(0,0,0);kW.applyMatrix4(this.bindMatrix);for(let W=0;W<4;W++){let K=vk.getComponent(W);if(K!==0){let X=Tk.getComponent(W);jk.multiplyMatrices(J.bones[X].matrixWorld,J.boneInverses[X]),U.addScaledVector(hF.copy(kW).applyMatrix4(jk),K)}}if(U.isVector4)U.w=kW.w;return U.applyMatrix4(this.bindMatrixInverse)}}class SW extends q6{constructor(){super();this.isBone=!0,this.type="Bone"}}class TW extends C6{constructor($=null,U=1,J=1,Q,W,K,X,H,N=1003,Y=1003,G,O){super(null,K,X,H,N,Y,Q,W,G,O);this.isDataTexture=!0,this.image={data:$,width:U,height:J},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}var bk=new m$,fF=new m$;class vW{constructor($=[],U=[]){this.uuid=pU(),this.bones=$.slice(0),this.boneInverses=U,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){let $=this.bones,U=this.boneInverses;if(this.boneMatrices=new Float32Array($.length*16),U.length===0)this.calculateInverses();else if($.length!==U.length){A$("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let J=0,Q=this.bones.length;J<Q;J++)this.boneInverses.push(new m$)}}calculateInverses(){this.boneInverses.length=0;for(let $=0,U=this.bones.length;$<U;$++){let J=new m$;if(this.bones[$])J.copy(this.bones[$].matrixWorld).invert();this.boneInverses.push(J)}}pose(){for(let $=0,U=this.bones.length;$<U;$++){let J=this.bones[$];if(J)J.matrixWorld.copy(this.boneInverses[$]).invert()}for(let $=0,U=this.bones.length;$<U;$++){let J=this.bones[$];if(J){if(J.parent&&J.parent.isBone)J.matrix.copy(J.parent.matrixWorld).invert(),J.matrix.multiply(J.matrixWorld);else J.matrix.copy(J.matrixWorld);J.matrix.decompose(J.position,J.quaternion,J.scale)}}}update(){let $=this.bones,U=this.boneInverses,J=this.boneMatrices,Q=this.boneTexture;for(let W=0,K=$.length;W<K;W++){let X=$[W]?$[W].matrixWorld:fF;bk.multiplyMatrices(X,U[W]),bk.toArray(J,W*16)}if(Q!==null)Q.needsUpdate=!0}clone(){return new vW(this.bones,this.boneInverses)}computeBoneTexture(){let $=Math.sqrt(this.bones.length*4);$=Math.ceil($/4)*4,$=Math.max($,4);let U=new Float32Array($*$*4);U.set(this.boneMatrices);let J=new TW(U,$,$,1023,1015);return J.needsUpdate=!0,this.boneMatrices=U,this.boneTexture=J,this}getBoneByName($){for(let U=0,J=this.bones.length;U<J;U++){let Q=this.bones[U];if(Q.name===$)return Q}return}dispose(){if(this.boneTexture!==null)this.boneTexture.dispose(),this.boneTexture=null}fromJSON($,U){this.uuid=$.uuid;for(let J=0,Q=$.bones.length;J<Q;J++){let W=$.bones[J],K=U[W];if(K===void 0)A$("Skeleton: No bone found with UUID:",W),K=new SW;this.bones.push(K),this.boneInverses.push(new m$().fromArray($.boneInverses[J]))}return this.init(),this}toJSON(){let $={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};$.uuid=this.uuid;let U=this.bones,J=this.boneInverses;for(let Q=0,W=U.length;Q<W;Q++){let K=U[Q];$.bones.push(K.uuid);let X=J[Q];$.boneInverses.push(X.toArray())}return $}}class P0 extends h6{constructor($,U,J,Q=1){super($,U,J);this.isInstancedBufferAttribute=!0,this.meshPerAttribute=Q}copy($){return super.copy($),this.meshPerAttribute=$.meshPerAttribute,this}toJSON(){let $=super.toJSON();return $.meshPerAttribute=this.meshPerAttribute,$.isInstancedBufferAttribute=!0,$}}var K8=new m$,yk=new m$,tQ=[],xk=new QU,uF=new m$,qW=new B6,ZW=new VU;class M8 extends B6{constructor($,U,J){super($,U);this.isInstancedMesh=!0,this.instanceMatrix=new P0(new Float32Array(J*16),16),this.instanceColor=null,this.morphTexture=null,this.count=J,this.boundingBox=null,this.boundingSphere=null;for(let Q=0;Q<J;Q++)this.setMatrixAt(Q,uF)}computeBoundingBox(){let $=this.geometry,U=this.count;if(this.boundingBox===null)this.boundingBox=new QU;if($.boundingBox===null)$.computeBoundingBox();this.boundingBox.makeEmpty();for(let J=0;J<U;J++)this.getMatrixAt(J,K8),xk.copy($.boundingBox).applyMatrix4(K8),this.boundingBox.union(xk)}computeBoundingSphere(){let $=this.geometry,U=this.count;if(this.boundingSphere===null)this.boundingSphere=new VU;if($.boundingSphere===null)$.computeBoundingSphere();this.boundingSphere.makeEmpty();for(let J=0;J<U;J++)this.getMatrixAt(J,K8),ZW.copy($.boundingSphere).applyMatrix4(K8),this.boundingSphere.union(ZW)}copy($,U){if(super.copy($,U),this.instanceMatrix.copy($.instanceMatrix),$.morphTexture!==null)this.morphTexture=$.morphTexture.clone();if($.instanceColor!==null)this.instanceColor=$.instanceColor.clone();if(this.count=$.count,$.boundingBox!==null)this.boundingBox=$.boundingBox.clone();if($.boundingSphere!==null)this.boundingSphere=$.boundingSphere.clone();return this}getColorAt($,U){if(this.instanceColor===null)return U.setRGB(1,1,1);else return U.fromArray(this.instanceColor.array,$*3)}getMatrixAt($,U){return U.fromArray(this.instanceMatrix.array,$*16)}getMorphAt($,U){let J=U.morphTargetInfluences,Q=this.morphTexture.source.data.data,W=J.length+1,K=$*W+1;for(let X=0;X<J.length;X++)J[X]=Q[K+X]}raycast($,U){let J=this.matrixWorld,Q=this.count;if(qW.geometry=this.geometry,qW.material=this.material,qW.material===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(ZW.copy(this.boundingSphere),ZW.applyMatrix4(J),$.ray.intersectsSphere(ZW)===!1)return;for(let W=0;W<Q;W++){this.getMatrixAt(W,K8),yk.multiplyMatrices(J,K8),qW.matrixWorld=yk,qW.raycast($,tQ);for(let K=0,X=tQ.length;K<X;K++){let H=tQ[K];H.instanceId=W,H.object=this,U.push(H)}tQ.length=0}}setColorAt($,U){if(this.instanceColor===null)this.instanceColor=new P0(new Float32Array(this.instanceMatrix.count*3).fill(1),3);return U.toArray(this.instanceColor.array,$*3),this}setMatrixAt($,U){return U.toArray(this.instanceMatrix.array,$*16),this}setMorphAt($,U){let J=U.morphTargetInfluences,Q=J.length+1;if(this.morphTexture===null)this.morphTexture=new TW(new Float32Array(Q*this.count),Q,this.count,1028,1015);let W=this.morphTexture.source.data.data,K=0;for(let N=0;N<J.length;N++)K+=J[N];let X=this.geometry.morphTargetsRelative?1:1-K,H=Q*$;return W[H]=X,W.set(J,H+1),this}updateMorphTargets(){}dispose(){if(this.dispatchEvent({type:"dispose"}),this.morphTexture!==null)this.morphTexture.dispose(),this.morphTexture=null}}var e7=new j,lF=new j,mF=new f$;class lU{constructor($=new j(1,0,0),U=0){this.isPlane=!0,this.normal=$,this.constant=U}set($,U){return this.normal.copy($),this.constant=U,this}setComponents($,U,J,Q){return this.normal.set($,U,J),this.constant=Q,this}setFromNormalAndCoplanarPoint($,U){return this.normal.copy($),this.constant=-U.dot(this.normal),this}setFromCoplanarPoints($,U,J){let Q=e7.subVectors(J,U).cross(lF.subVectors($,U)).normalize();return this.setFromNormalAndCoplanarPoint(Q,$),this}copy($){return this.normal.copy($.normal),this.constant=$.constant,this}normalize(){let $=1/this.normal.length();return this.normal.multiplyScalar($),this.constant*=$,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint($){return this.normal.dot($)+this.constant}distanceToSphere($){return this.distanceToPoint($.center)-$.radius}projectPoint($,U){return U.copy($).addScaledVector(this.normal,-this.distanceToPoint($))}intersectLine($,U,J=!0){let Q=$.delta(e7),W=this.normal.dot(Q);if(W===0){if(this.distanceToPoint($.start)===0)return U.copy($.start);return null}let K=-($.start.dot(this.normal)+this.constant)/W;if(J===!0&&(K<0||K>1))return null;return U.copy($.start).addScaledVector(Q,K)}intersectsLine($){let U=this.distanceToPoint($.start),J=this.distanceToPoint($.end);return U<0&&J>0||J<0&&U>0}intersectsBox($){return $.intersectsPlane(this)}intersectsSphere($){return $.intersectsPlane(this)}coplanarPoint($){return $.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4($,U){let J=U||mF.getNormalMatrix($),Q=this.coplanarPoint(e7).applyMatrix4($),W=this.normal.applyMatrix3(J).normalize();return this.constant=-Q.dot(W),this}translate($){return this.constant-=$.dot(this.normal),this}equals($){return $.normal.equals(this.normal)&&$.constant===this.constant}clone(){return new this.constructor().copy(this)}}var w0=new VU,pF=new g$(0.5,0.5),eQ=new j;class jW{constructor($=new lU,U=new lU,J=new lU,Q=new lU,W=new lU,K=new lU){this.planes=[$,U,J,Q,W,K]}set($,U,J,Q,W,K){let X=this.planes;return X[0].copy($),X[1].copy(U),X[2].copy(J),X[3].copy(Q),X[4].copy(W),X[5].copy(K),this}copy($){let U=this.planes;for(let J=0;J<6;J++)U[J].copy($.planes[J]);return this}setFromProjectionMatrix($,U=2000,J=!1){let Q=this.planes,W=$.elements,K=W[0],X=W[1],H=W[2],N=W[3],Y=W[4],G=W[5],O=W[6],E=W[7],k=W[8],I=W[9],R=W[10],q=W[11],Z=W[12],_=W[13],P=W[14],L=W[15];if(Q[0].setComponents(N-K,E-Y,q-k,L-Z).normalize(),Q[1].setComponents(N+K,E+Y,q+k,L+Z).normalize(),Q[2].setComponents(N+X,E+G,q+I,L+_).normalize(),Q[3].setComponents(N-X,E-G,q-I,L-_).normalize(),J)Q[4].setComponents(H,O,R,P).normalize(),Q[5].setComponents(N-H,E-O,q-R,L-P).normalize();else if(Q[4].setComponents(N-H,E-O,q-R,L-P).normalize(),U===2000)Q[5].setComponents(N+H,E+O,q+R,L+P).normalize();else if(U===2001)Q[5].setComponents(H,O,R,P).normalize();else throw Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+U);return this}intersectsObject($){if($.boundingSphere!==void 0){if($.boundingSphere===null)$.computeBoundingSphere();w0.copy($.boundingSphere).applyMatrix4($.matrixWorld)}else{let U=$.geometry;if(U.boundingSphere===null)U.computeBoundingSphere();w0.copy(U.boundingSphere).applyMatrix4($.matrixWorld)}return this.intersectsSphere(w0)}intersectsSprite($){w0.center.set(0,0,0);let U=pF.distanceTo($.center);return w0.radius=0.7071067811865476+U,w0.applyMatrix4($.matrixWorld),this.intersectsSphere(w0)}intersectsSphere($){let U=this.planes,J=$.center,Q=-$.radius;for(let W=0;W<6;W++)if(U[W].distanceToPoint(J)<Q)return!1;return!0}intersectsBox($){let U=this.planes;for(let J=0;J<6;J++){let Q=U[J];if(eQ.x=Q.normal.x>0?$.max.x:$.min.x,eQ.y=Q.normal.y>0?$.max.y:$.min.y,eQ.z=Q.normal.z>0?$.max.z:$.min.z,Q.distanceToPoint(eQ)<0)return!1}return!0}containsPoint($){let U=this.planes;for(let J=0;J<6;J++)if(U[J].distanceToPoint($)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class gW extends EU{constructor($){super();this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new y$(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues($)}copy($){return super.copy($),this.color.copy($.color),this.map=$.map,this.linewidth=$.linewidth,this.linecap=$.linecap,this.linejoin=$.linejoin,this.fog=$.fog,this}}var H9=new j,N9=new j,hk=new m$,IW=new sJ,$9=new VU,$X=new j,fk=new j;class tJ extends q6{constructor($=new KU,U=new gW){super();this.isLine=!0,this.type="Line",this.geometry=$,this.material=U,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy($,U){return super.copy($,U),this.material=Array.isArray($.material)?$.material.slice():$.material,this.geometry=$.geometry,this}computeLineDistances(){let $=this.geometry;if($.index===null){let U=$.attributes.position,J=[0];for(let Q=1,W=U.count;Q<W;Q++)H9.fromBufferAttribute(U,Q-1),N9.fromBufferAttribute(U,Q),J[Q]=J[Q-1],J[Q]+=H9.distanceTo(N9);$.setAttribute("lineDistance",new OU(J,1))}else A$("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast($,U){let J=this.geometry,Q=this.matrixWorld,W=$.params.Line.threshold,K=J.drawRange;if(J.boundingSphere===null)J.computeBoundingSphere();if($9.copy(J.boundingSphere),$9.applyMatrix4(Q),$9.radius+=W,$.ray.intersectsSphere($9)===!1)return;hk.copy(Q).invert(),IW.copy($.ray).applyMatrix4(hk);let X=W/((this.scale.x+this.scale.y+this.scale.z)/3),H=X*X,N=this.isLineSegments?2:1,Y=J.index,O=J.attributes.position;if(Y!==null){let E=Math.max(0,K.start),k=Math.min(Y.count,K.start+K.count);for(let I=E,R=k-1;I<R;I+=N){let q=Y.getX(I),Z=Y.getX(I+1),_=U9(this,$,IW,H,q,Z,I);if(_)U.push(_)}if(this.isLineLoop){let I=Y.getX(k-1),R=Y.getX(E),q=U9(this,$,IW,H,I,R,k-1);if(q)U.push(q)}}else{let E=Math.max(0,K.start),k=Math.min(O.count,K.start+K.count);for(let I=E,R=k-1;I<R;I+=N){let q=U9(this,$,IW,H,I,I+1,I);if(q)U.push(q)}if(this.isLineLoop){let I=U9(this,$,IW,H,k-1,E,k-1);if(I)U.push(I)}}}updateMorphTargets(){let U=this.geometry.morphAttributes,J=Object.keys(U);if(J.length>0){let Q=U[J[0]];if(Q!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let W=0,K=Q.length;W<K;W++){let X=Q[W].name||String(W);this.morphTargetInfluences.push(0),this.morphTargetDictionary[X]=W}}}}}function U9($,U,J,Q,W,K,X){let H=$.geometry.attributes.position;if(H9.fromBufferAttribute(H,W),N9.fromBufferAttribute(H,K),J.distanceSqToSegment(H9,N9,$X,fk)>Q)return;$X.applyMatrix4($.matrixWorld);let Y=U.ray.origin.distanceTo($X);if(Y<U.near||Y>U.far)return;return{distance:Y,point:fk.clone().applyMatrix4($.matrixWorld),index:X,face:null,faceIndex:null,barycoord:null,object:$}}var uk=new j,lk=new j;class _9 extends tJ{constructor($,U){super($,U);this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let $=this.geometry;if($.index===null){let U=$.attributes.position,J=[];for(let Q=0,W=U.count;Q<W;Q+=2)uk.fromBufferAttribute(U,Q),lk.fromBufferAttribute(U,Q+1),J[Q]=Q===0?0:J[Q-1],J[Q+1]=J[Q]+uk.distanceTo(lk);$.setAttribute("lineDistance",new OU(J,1))}else A$("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class A9 extends tJ{constructor($,U){super($,U);this.isLineLoop=!0,this.type="LineLoop"}}class bW extends EU{constructor($){super();this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new y$(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues($)}copy($){return super.copy($),this.color.copy($.color),this.map=$.map,this.alphaMap=$.alphaMap,this.size=$.size,this.sizeAttenuation=$.sizeAttenuation,this.fog=$.fog,this}}var mk=new m$,WX=new sJ,J9=new VU,W9=new j;class B8 extends q6{constructor($=new KU,U=new bW){super();this.isPoints=!0,this.type="Points",this.geometry=$,this.material=U,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy($,U){return super.copy($,U),this.material=Array.isArray($.material)?$.material.slice():$.material,this.geometry=$.geometry,this}raycast($,U){let J=this.geometry,Q=this.matrixWorld,W=$.params.Points.threshold,K=J.drawRange;if(J.boundingSphere===null)J.computeBoundingSphere();if(J9.copy(J.boundingSphere),J9.applyMatrix4(Q),J9.radius+=W,$.ray.intersectsSphere(J9)===!1)return;mk.copy(Q).invert(),WX.copy($.ray).applyMatrix4(mk);let X=W/((this.scale.x+this.scale.y+this.scale.z)/3),H=X*X,N=J.index,G=J.attributes.position;if(N!==null){let O=Math.max(0,K.start),E=Math.min(N.count,K.start+K.count);for(let k=O,I=E;k<I;k++){let R=N.getX(k);W9.fromBufferAttribute(G,R),pk(W9,R,H,Q,$,U,this)}}else{let O=Math.max(0,K.start),E=Math.min(G.count,K.start+K.count);for(let k=O,I=E;k<I;k++)W9.fromBufferAttribute(G,k),pk(W9,k,H,Q,$,U,this)}}updateMorphTargets(){let U=this.geometry.morphAttributes,J=Object.keys(U);if(J.length>0){let Q=U[J[0]];if(Q!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let W=0,K=Q.length;W<K;W++){let X=Q[W].name||String(W);this.morphTargetInfluences.push(0),this.morphTargetDictionary[X]=W}}}}}function pk($,U,J,Q,W,K,X){let H=WX.distanceSqToPoint($);if(H<J){let N=new j;WX.closestPointToPoint($,N),N.applyMatrix4(Q);let Y=W.ray.origin.distanceTo(N);if(Y<W.near||Y>W.far)return;K.push({distance:Y,distanceToRay:Math.sqrt(H),point:N,index:U,face:null,faceIndex:null,barycoord:null,object:X})}}class C9 extends C6{constructor($=[],U=301,J,Q,W,K,X,H,N,Y){super($,U,J,Q,W,K,X,H,N,Y);this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images($){this.image=$}}class eJ extends C6{constructor($,U,J=1014,Q,W,K,X=1003,H=1003,N,Y=1026,G=1){if(Y!==1026&&Y!==1027)throw Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let O={width:$,height:U,depth:G};super(O,Q,W,K,X,H,Y,J,N);this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy($){return super.copy($),this.source=new _W(Object.assign({},$.image)),this.compareFunction=$.compareFunction,this}toJSON($){let U=super.toJSON($);if(this.compareFunction!==null)U.compareFunction=this.compareFunction;return U}}class HH extends eJ{constructor($,U=1014,J=301,Q,W,K=1003,X=1003,H,N=1026){let Y={width:$,height:$,depth:1},G=[Y,Y,Y,Y,Y,Y];super($,$,U,J,Q,W,K,X,H,N);this.image=G,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images($){this.image=$}}class S9 extends C6{constructor($=null){super();this.sourceTexture=$,this.isExternalTexture=!0}copy($){return super.copy($),this.sourceTexture=$.sourceTexture,this}}class $0 extends KU{constructor($=1,U=1,J=1,Q=1,W=1,K=1){super();this.type="BoxGeometry",this.parameters={width:$,height:U,depth:J,widthSegments:Q,heightSegments:W,depthSegments:K};let X=this;Q=Math.floor(Q),W=Math.floor(W),K=Math.floor(K);let H=[],N=[],Y=[],G=[],O=0,E=0;k("z","y","x",-1,-1,J,U,$,K,W,0),k("z","y","x",1,-1,J,U,-$,K,W,1),k("x","z","y",1,1,$,J,U,Q,K,2),k("x","z","y",1,-1,$,J,-U,Q,K,3),k("x","y","z",1,-1,$,U,J,Q,W,4),k("x","y","z",-1,-1,$,U,-J,Q,W,5),this.setIndex(H),this.setAttribute("position",new OU(N,3)),this.setAttribute("normal",new OU(Y,3)),this.setAttribute("uv",new OU(G,2));function k(I,R,q,Z,_,P,L,B,z,A,D){let w=P/z,h=L/A,C=P/2,f=L/2,s=B/2,x=z+1,d=A+1,c=0,y=0,t=new j;for(let e=0;e<d;e++){let Y$=e*h-f;for(let R$=0;R$<x;R$++){let w$=R$*w-C;t[I]=w$*Z,t[R]=Y$*_,t[q]=s,N.push(t.x,t.y,t.z),t[I]=0,t[R]=0,t[q]=B>0?1:-1,Y.push(t.x,t.y,t.z),G.push(R$/z),G.push(1-e/A),c+=1}}for(let e=0;e<A;e++)for(let Y$=0;Y$<z;Y$++){let R$=O+Y$+x*e,w$=O+Y$+x*(e+1),$6=O+(Y$+1)+x*(e+1),n$=O+(Y$+1)+x*e;H.push(R$,w$,n$),H.push(w$,$6,n$),y+=6}X.addGroup(E,y,D),E+=y,O+=c}}copy($){return super.copy($),this.parameters=Object.assign({},$.parameters),this}static fromJSON($){return new $0($.width,$.height,$.depth,$.widthSegments,$.heightSegments,$.depthSegments)}}class yW extends KU{constructor($=1,U=1,J=1,Q=1){super();this.type="PlaneGeometry",this.parameters={width:$,height:U,widthSegments:J,heightSegments:Q};let W=$/2,K=U/2,X=Math.floor(J),H=Math.floor(Q),N=X+1,Y=H+1,G=$/X,O=U/H,E=[],k=[],I=[],R=[];for(let q=0;q<Y;q++){let Z=q*O-K;for(let _=0;_<N;_++){let P=_*G-W;k.push(P,-Z,0),I.push(0,0,1),R.push(_/X),R.push(1-q/H)}}for(let q=0;q<H;q++)for(let Z=0;Z<X;Z++){let _=Z+N*q,P=Z+N*(q+1),L=Z+1+N*(q+1),B=Z+1+N*q;E.push(_,P,B),E.push(P,L,B)}this.setIndex(E),this.setAttribute("position",new OU(k,3)),this.setAttribute("normal",new OU(I,3)),this.setAttribute("uv",new OU(R,2))}copy($){return super.copy($),this.parameters=Object.assign({},$.parameters),this}static fromJSON($){return new yW($.width,$.height,$.widthSegments,$.heightSegments)}}function v0($){let U={};for(let J in $){U[J]={};for(let Q in $[J]){let W=$[J][Q];if(dk(W))if(W.isRenderTargetTexture)A$("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),U[J][Q]=null;else U[J][Q]=W.clone();else if(Array.isArray(W))if(dk(W[0])){let K=[];for(let X=0,H=W.length;X<H;X++)K[X]=W[X].clone();U[J][Q]=K}else U[J][Q]=W.slice();else U[J][Q]=W}}return U}function UU($){let U={};for(let J=0;J<$.length;J++){let Q=v0($[J]);for(let W in Q)U[W]=Q[W]}return U}function dk($){return $&&($.isColor||$.isMatrix3||$.isMatrix4||$.isVector2||$.isVector3||$.isVector4||$.isTexture||$.isQuaternion)}function dF($){let U=[];for(let J=0;J<$.length;J++)U.push($[J].clone());return U}function NH($){let U=$.getRenderTarget();if(U===null)return $.outputColorSpace;if(U.isXRRenderTarget===!0)return U.texture.colorSpace;return r$.workingColorSpace}var aq={clone:v0,merge:UU},cF=`void main() {+ var Zh="185",Ei={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Ai={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},Xh=0,yc=1,qh=2;var _s=1,Yh=2,kr=3,Ri=0,Xt=1,vn=2,Vn=0,xs=1,bc=2,Sc=3,Mc=4,jh=5;var Br=100,Jh=101,Kh=102,Qh=103,ef=104,tf=200,nf=201,rf=202,sf=203,of=204,af=205,cf=206,lf=207,uf=208,hf=209,ff=210,df=211,pf=212,mf=213,gf=214,_f=0,xf=1,vf=2,wc=3,yf=4,bf=5,Sf=6,Mf=7,wf=0,Tf=1,Ef=2,Pn=0,Tc=1,Ec=2,Ac=3,vs=4,Rc=5,Cc=6,Pc=7;var Gr=301,nr=302,Oo=303,Fo=304,ys=306,Hr=1000,Vr=1001,zo=1002,In=1003,ko=1004;var ir=1005;var kt=1006,Wr=1007;var Wn=1008;var Ln=1009,Af=1010,Rf=1011,bs=1012,Ic=1013,Ci=1014,ui=1015,hi=1016,Lc=1017,Nc=1018,$r=1020,Cf=35902,Pf=35899,If=1021,Lf=1022,$n=1023,rr=1026,sr=1027,Nf=1028,Dc=1029,or=1030,Uc=1031;var Oc=1033,Bo=33776,Go=33777,Ho=33778,Vo=33779,Fc=35840,zc=35841,kc=35842,Bc=35843,Gc=36196,Hc=37492,Vc=37496,Wc=37488,$c=37489,Wo=37490,Zc=37491,Xc=37808,qc=37809,Yc=37810,jc=37811,Jc=37812,Kc=37813,Qc=37814,el=37815,tl=37816,nl=37817,il=37818,rl=37819,sl=37820,ol=37821,al=36492,cl=36494,ll=36495,ul=36283,hl=36284,$o=36285,fl=36286;var dl=2300,Zo=2301;var pl=0,Ss=1,Zr=2;var ml=0,Df=1,ar="",Pi="srgb",cn="srgb-linear",gl="linear",ut="srgb";var Uf=512,Of=513,Ff=514,Xo=515,zf=516,kf=517,qo=518,Bf=519;var _l="300 es",xl=2000;function z0(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function k0(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Or(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function Gf(){let e=Or("canvas");return e.style.display="block",e}var uh={},Fr=null;function gs(...e){let t="THREE."+e.shift();if(Fr)Fr("log",t,...e);else console.log(t,...e)}function Hf(e){let t=e[0];if(typeof t==="string"&&t.startsWith("TSL:")){let n=e[1];if(n&&n.isStackTrace)e[0]+=" "+n.getLocation();else e[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return e}function Me(...e){e=Hf(e);let t="THREE."+e.shift();if(Fr)Fr("warn",t,...e);else{let n=e[0];if(n&&n.isStackTrace)console.warn(n.getError(t));else console.warn(t,...e)}}function Ne(...e){e=Hf(e);let t="THREE."+e.shift();if(Fr)Fr("error",t,...e);else{let n=e[0];if(n&&n.isStackTrace)console.error(n.getError(t));else console.error(t,...e)}}function Qi(...e){let t=e.join(" ");if(t in uh)return;uh[t]=!0,Me(...e)}function Vf(e,t,n){return new Promise(function(i,r){function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}}setTimeout(s,n)})}var Wf={[0]:1,[2]:6,[4]:7,[3]:5,[1]:0,[6]:2,[7]:4,[5]:3};class Nn{addEventListener(e,t){if(this._listeners===void 0)this._listeners={};let n=this._listeners;if(n[e]===void 0)n[e]=[];if(n[e].indexOf(t)===-1)n[e].push(t)}hasEventListener(e,t){let n=this._listeners;if(n===void 0)return!1;return n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let i=n[e];if(i!==void 0){let r=i.indexOf(t);if(r!==-1)i.splice(r,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 i=n.slice(0);for(let r=0,s=i.length;r<s;r++)i[r].call(this,e);e.target=null}}}var $t=["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"],hh=1234567,ps=Math.PI/180,er=180/Math.PI;function Cn(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return($t[e&255]+$t[e>>8&255]+$t[e>>16&255]+$t[e>>24&255]+"-"+$t[t&255]+$t[t>>8&255]+"-"+$t[t>>16&15|64]+$t[t>>24&255]+"-"+$t[n&63|128]+$t[n>>8&255]+"-"+$t[n>>16&255]+$t[n>>24&255]+$t[i&255]+$t[i>>8&255]+$t[i>>16&255]+$t[i>>24&255]).toLowerCase()}function We(e,t,n){return Math.max(t,Math.min(n,e))}function vl(e,t){return(e%t+t)%t}function B0(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)}function G0(e,t,n){if(e!==t)return(n-e)/(t-e);else return 0}function ms(e,t,n){return(1-n)*e+n*t}function H0(e,t,n,i){return ms(e,t,1-Math.exp(-n*i))}function V0(e,t=1){return t-Math.abs(vl(e,t*2)-t)}function W0(e,t,n){if(e<=t)return 0;if(e>=n)return 1;return e=(e-t)/(n-t),e*e*(3-2*e)}function $0(e,t,n){if(e<=t)return 0;if(e>=n)return 1;return e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10)}function Z0(e,t){return e+Math.floor(Math.random()*(t-e+1))}function X0(e,t){return e+Math.random()*(t-e)}function q0(e){return e*(0.5-Math.random())}function Y0(e){if(e!==void 0)hh=e;let t=hh+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function j0(e){return e*ps}function J0(e){return e*er}function K0(e){return(e&e-1)===0&&e!==0}function Q0(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))}function ex(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function tx(e,t,n,i,r){let{cos:s,sin:o}=Math,a=s(n/2),c=o(n/2),l=s((t+i)/2),u=o((t+i)/2),f=s((t-i)/2),h=o((t-i)/2),d=s((i-t)/2),g=o((i-t)/2);switch(r){case"XYX":e.set(a*u,c*f,c*h,a*l);break;case"YZY":e.set(c*h,a*u,c*f,a*l);break;case"ZXZ":e.set(c*f,c*h,a*u,a*l);break;case"XZX":e.set(a*u,c*g,c*d,a*l);break;case"YXY":e.set(c*d,a*u,c*g,a*l);break;case"ZYZ":e.set(c*g,c*d,a*u,a*l);break;default:Me("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function Rn(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error("THREE.MathUtils: Invalid component type.")}}function nt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error("THREE.MathUtils: Invalid component type.")}}var Ms={DEG2RAD:ps,RAD2DEG:er,generateUUID:Cn,clamp:We,euclideanModulo:vl,mapLinear:B0,inverseLerp:G0,lerp:ms,damp:H0,pingpong:V0,smoothstep:W0,smootherstep:$0,randInt:Z0,randFloat:X0,randFloatSpread:q0,seededRandom:Y0,degToRad:j0,radToDeg:J0,isPowerOfTwo:K0,ceilPowerOfTwo:Q0,floorPowerOfTwo:ex,setQuaternionFromProperEuler:tx,normalize:nt,denormalize:Rn};class Pe{static{Pe.prototype.isVector2=!0}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 Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error("THREE.Vector2: 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,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[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=We(this.x,e.x,t.x),this.y=We(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=We(this.x,e,t),this.y=We(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(We(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(We(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),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class zt{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,r,s,o){let a=n[i+0],c=n[i+1],l=n[i+2],u=n[i+3],f=r[s+0],h=r[s+1],d=r[s+2],g=r[s+3];if(u!==g||a!==f||c!==h||l!==d){let b=a*f+c*h+l*d+u*g;if(b<0)f=-f,h=-h,d=-d,g=-g,b=-b;let p=1-o;if(b<0.9995){let m=Math.acos(b),A=Math.sin(m);p=Math.sin(p*m)/A,o=Math.sin(o*m)/A,a=a*p+f*o,c=c*p+h*o,l=l*p+d*o,u=u*p+g*o}else{a=a*p+f*o,c=c*p+h*o,l=l*p+d*o,u=u*p+g*o;let m=1/Math.sqrt(a*a+c*c+l*l+u*u);a*=m,c*=m,l*=m,u*=m}}e[t]=a,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,s){let o=n[i],a=n[i+1],c=n[i+2],l=n[i+3],u=r[s],f=r[s+1],h=r[s+2],d=r[s+3];return e[t]=o*d+l*u+a*h-c*f,e[t+1]=a*d+l*f+c*u-o*h,e[t+2]=c*d+l*h+o*f-a*u,e[t+3]=l*d-o*u-a*f-c*h,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,i){return this._x=e,this._y=t,this._z=n,this._w=i,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{_x:n,_y:i,_z:r,_order:s}=e,{cos:o,sin:a}=Math,c=o(n/2),l=o(i/2),u=o(r/2),f=a(n/2),h=a(i/2),d=a(r/2);switch(s){case"XYZ":this._x=f*l*u+c*h*d,this._y=c*h*u-f*l*d,this._z=c*l*d+f*h*u,this._w=c*l*u-f*h*d;break;case"YXZ":this._x=f*l*u+c*h*d,this._y=c*h*u-f*l*d,this._z=c*l*d-f*h*u,this._w=c*l*u+f*h*d;break;case"ZXY":this._x=f*l*u-c*h*d,this._y=c*h*u+f*l*d,this._z=c*l*d+f*h*u,this._w=c*l*u-f*h*d;break;case"ZYX":this._x=f*l*u-c*h*d,this._y=c*h*u+f*l*d,this._z=c*l*d-f*h*u,this._w=c*l*u+f*h*d;break;case"YZX":this._x=f*l*u+c*h*d,this._y=c*h*u+f*l*d,this._z=c*l*d-f*h*u,this._w=c*l*u-f*h*d;break;case"XZY":this._x=f*l*u-c*h*d,this._y=c*h*u-f*l*d,this._z=c*l*d+f*h*u,this._w=c*l*u+f*h*d;break;default:Me("Quaternion: .setFromEuler() encountered an unknown order: "+s)}if(t===!0)this._onChangeCallback();return this}setFromAxisAngle(e,t){let n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],o=t[5],a=t[9],c=t[2],l=t[6],u=t[10],f=n+o+u;if(f>0){let h=0.5/Math.sqrt(f+1);this._w=0.25/h,this._x=(l-a)*h,this._y=(r-c)*h,this._z=(s-i)*h}else if(n>o&&n>u){let h=2*Math.sqrt(1+n-o-u);this._w=(l-a)/h,this._x=0.25*h,this._y=(i+s)/h,this._z=(r+c)/h}else if(o>u){let h=2*Math.sqrt(1+o-n-u);this._w=(r-c)/h,this._x=(i+s)/h,this._y=0.25*h,this._z=(a+l)/h}else{let h=2*Math.sqrt(1+u-n-o);this._w=(s-i)/h,this._x=(r+c)/h,this._y=(a+l)/h,this._z=0.25*h}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;if(n<0.00000001)if(n=0,Math.abs(e.x)>Math.abs(e.z))this._x=-e.y,this._y=e.x,this._z=0,this._w=n;else this._x=0,this._y=-e.z,this._z=e.y,this._w=n;else 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;return this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(We(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let i=Math.min(1,t/n);return this.slerp(e,i),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();if(e===0)this._x=0,this._y=0,this._z=0,this._w=1;else e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e;return this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let{_x:n,_y:i,_z:r,_w:s}=e,{_x:o,_y:a,_z:c,_w:l}=t;return this._x=n*l+s*o+i*c-r*a,this._y=i*l+s*a+r*o-n*c,this._z=r*l+s*c+n*a-i*o,this._w=s*l-n*o-i*a-r*c,this._onChangeCallback(),this}slerp(e,t){let{_x:n,_y:i,_z:r,_w:s}=e,o=this.dot(e);if(o<0)n=-n,i=-i,r=-r,s=-s,o=-o;let a=1-t;if(o<0.9995){let c=Math.acos(o),l=Math.sin(c);a=Math.sin(a*c)/l,t=Math.sin(t*c)/l,this._x=this._x*a+n*t,this._y=this._y*a+i*t,this._z=this._z*a+r*t,this._w=this._w*a+s*t,this._onChangeCallback()}else this._x=this._x*a+n*t,this._y=this._y*a+i*t,this._z=this._z*a+r*t,this._w=this._w*a+s*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(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*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}}class N{static{N.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){if(n===void 0)n=this.z;return 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 Error("THREE.Vector3: 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 Error("THREE.Vector3: 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(fh.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(fh.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){let t=this.x,n=this.y,i=this.z,{x:r,y:s,z:o,w:a}=e,c=2*(s*i-o*n),l=2*(o*t-r*i),u=2*(r*n-s*t);return this.x=t+a*c+s*u-o*l,this.y=n+a*l+o*c-r*u,this.z=i+a*u+r*l-s*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,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,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=We(this.x,e.x,t.x),this.y=We(this.y,e.y,t.y),this.z=We(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=We(this.x,e,t),this.y=We(this.y,e,t),this.z=We(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(We(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{x:n,y:i,z:r}=e,{x:s,y:o,z:a}=t;return this.x=i*a-r*o,this.y=r*s-n*a,this.z=n*o-i*s,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 Xa.copy(this).projectOnVector(e),this.sub(Xa)}reflect(e){return this.sub(Xa.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(We(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}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 i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*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(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,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}}var Xa=new N,fh=new zt;class De{static{De.prototype.isMatrix3=!0}constructor(e,t,n,i,r,s,o,a,c){if(this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0)this.set(e,t,n,i,r,s,o,a,c)}set(e,t,n,i,r,s,o,a,c){let l=this.elements;return l[0]=e,l[1]=i,l[2]=o,l[3]=t,l[4]=r,l[5]=a,l[6]=n,l[7]=s,l[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,i=t.elements,r=this.elements,s=n[0],o=n[3],a=n[6],c=n[1],l=n[4],u=n[7],f=n[2],h=n[5],d=n[8],g=i[0],b=i[3],p=i[6],m=i[1],A=i[4],T=i[7],v=i[2],w=i[5],E=i[8];return r[0]=s*g+o*m+a*v,r[3]=s*b+o*A+a*w,r[6]=s*p+o*T+a*E,r[1]=c*g+l*m+u*v,r[4]=c*b+l*A+u*w,r[7]=c*p+l*T+u*E,r[2]=f*g+h*m+d*v,r[5]=f*b+h*A+d*w,r[8]=f*p+h*T+d*E,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],i=e[2],r=e[3],s=e[4],o=e[5],a=e[6],c=e[7],l=e[8];return t*s*l-t*o*c-n*r*l+n*o*a+i*r*c-i*s*a}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],o=e[5],a=e[6],c=e[7],l=e[8],u=l*s-o*c,f=o*a-l*r,h=c*r-s*a,d=t*u+n*f+i*h;if(d===0)return this.set(0,0,0,0,0,0,0,0,0);let g=1/d;return e[0]=u*g,e[1]=(i*c-l*n)*g,e[2]=(o*n-i*s)*g,e[3]=f*g,e[4]=(l*t-i*a)*g,e[5]=(i*r-o*t)*g,e[6]=h*g,e[7]=(n*a-c*t)*g,e[8]=(s*t-n*r)*g,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,i,r,s,o){let a=Math.cos(r),c=Math.sin(r);return this.set(n*a,n*c,-n*(a*s+c*o)+s+e,-i*c,i*a,-i*(-c*s+a*o)+o+t,0,0,1),this}scale(e,t){return Qi("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(qa.makeScale(e,t)),this}rotate(e){return Qi("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(qa.makeRotation(-e)),this}translate(e,t){return Qi("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(qa.makeTranslation(e,t)),this}makeTranslation(e,t){if(e.isVector2)this.set(1,0,e.x,0,1,e.y,0,0,1);else this.set(1,0,e,0,1,t,0,0,1);return 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 i=0;i<9;i++)if(t[i]!==n[i])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)}}var qa=new De,dh=new De().set(0.4123908,0.3575843,0.1804808,0.212639,0.7151687,0.0721923,0.0193308,0.1191948,0.9505322),ph=new De().set(3.2409699,-1.5373832,-0.4986108,-0.9692436,1.8759675,0.0415551,0.0556301,-0.203977,1.0569715);function nx(){let e={enabled:!0,workingColorSpace:"srgb-linear",spaces:{},convert:function(r,s,o){if(this.enabled===!1||s===o||!s||!o)return r;if(this.spaces[s].transfer==="srgb")r.r=li(r.r),r.g=li(r.g),r.b=li(r.b);if(this.spaces[s].primaries!==this.spaces[o].primaries)r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[o].fromXYZ);if(this.spaces[o].transfer==="srgb")r.r=Ur(r.r),r.g=Ur(r.g),r.b=Ur(r.b);return 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){if(r==="")return"linear";return 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,o){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[o].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 Qi("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return Qi("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(r,s)}},t=[0.64,0.33,0.3,0.6,0.15,0.06],n=[0.2126,0.7152,0.0722],i=[0.3127,0.329];return e.define({["srgb-linear"]:{primaries:t,whitePoint:i,transfer:"linear",toXYZ:dh,fromXYZ:ph,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:"srgb"},outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}},["srgb"]:{primaries:t,whitePoint:i,transfer:"srgb",toXYZ:dh,fromXYZ:ph,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}}}),e}var Ve=nx();function li(e){return e<0.04045?e*0.0773993808:Math.pow(e*0.9478672986+0.0521327014,2.4)}function Ur(e){return e<0.0031308?e*12.92:1.055*Math.pow(e,0.41666)-0.055}var br;class yl{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if(typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{if(br===void 0)br=Or("canvas");br.width=e.width,br.height=e.height;let i=br.getContext("2d");if(e instanceof ImageData)i.putImageData(e,0,0);else i.drawImage(e,0,0,e.width,e.height);n=br}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=Or("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let s=0;s<r.length;s++)r[s]=li(r[s]/255)*255;return n.putImageData(i,0,0),t}else if(e.data){let t=e.data.slice(0);for(let n=0;n<t.length;n++)if(t instanceof Uint8Array||t instanceof Uint8ClampedArray)t[n]=Math.floor(li(t[n]/255)*255);else t[n]=li(t[n]);return{data:t,width:e.width,height:e.height}}else return Me("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}var ix=0;class ws{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ix++}),this.uuid=Cn(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)e.set(t.videoWidth,t.videoHeight,0);else if(typeof VideoFrame<"u"&&t instanceof VideoFrame)e.set(t.displayWidth,t.displayHeight,0);else if(t!==null)e.set(t.width,t.height,t.depth||0);else e.set(0,0,0);return e}set needsUpdate(e){if(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:""},i=this.data;if(i!==null){let r;if(Array.isArray(i)){r=[];for(let s=0,o=i.length;s<o;s++)if(i[s].isDataTexture)r.push(Ya(i[s].image));else r.push(Ya(i[s]))}else r=Ya(i);n.url=r}if(!t)e.images[this.uuid]=n;return n}}function Ya(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap)return yl.getDataURL(e);else if(e.data)return{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name};else return Me("Texture: Unable to serialize Texture."),{}}var rx=0,ja=new N;class St extends Nn{constructor(e=St.DEFAULT_IMAGE,t=St.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,o=1023,a=1009,c=St.DEFAULT_ANISOTROPY,l=""){super();this.isTexture=!0,Object.defineProperty(this,"id",{value:rx++}),this.uuid=Cn(),this.name="",this.source=new ws(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=a,this.offset=new Pe(0,0),this.repeat=new Pe(1,1),this.center=new Pe(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new De,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=l,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=e&&e.depth&&e.depth>1?!0:!1,this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(ja).x}get height(){return this.source.getSize(ja).y}get depth(){return this.source.getSize(ja).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){Me(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){Me(`Texture.setValues(): property '${t}' does not exist.`);continue}if(i&&n&&(i.isVector2&&n.isVector2))i.copy(n);else if(i&&n&&(i.isVector3&&n.isVector3))i.copy(n);else if(i&&n&&(i.isMatrix3&&n.isMatrix3))i.copy(n);else 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};if(Object.keys(this.userData).length>0)n.userData=this.userData;if(!t)e.textures[this.uuid]=n;return n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case 1000:e.x=e.x-Math.floor(e.x);break;case 1001:e.x=e.x<0?0:1;break;case 1002:if(Math.abs(Math.floor(e.x)%2)===1)e.x=Math.ceil(e.x)-e.x;else e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case 1000:e.y=e.y-Math.floor(e.y);break;case 1001:e.y=e.y<0?0:1;break;case 1002:if(Math.abs(Math.floor(e.y)%2)===1)e.y=Math.ceil(e.y)-e.y;else e.y=e.y-Math.floor(e.y);break}if(this.flipY)e.y=1-e.y;return e}set needsUpdate(e){if(e===!0)this.version++,this.source.needsUpdate=!0}set needsPMREMUpdate(e){if(e===!0)this.pmremVersion++}}St.DEFAULT_IMAGE=null;St.DEFAULT_MAPPING=300;St.DEFAULT_ANISOTROPY=1;class it{static{it.prototype.isVector4=!0}constructor(e=0,t=0,n=0,i=1){this.x=e,this.y=t,this.z=n,this.w=i}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,i){return this.x=e,this.y=t,this.z=n,this.w=i,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 Error("THREE.Vector4: 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 Error("THREE.Vector4: 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,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,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);if(t<0.0001)this.x=1,this.y=0,this.z=0;else this.x=e.x/t,this.y=e.y/t,this.z=e.z/t;return this}setAxisAngleFromRotationMatrix(e){let t,n,i,r,s=0.01,o=0.1,a=e.elements,c=a[0],l=a[4],u=a[8],f=a[1],h=a[5],d=a[9],g=a[2],b=a[6],p=a[10];if(Math.abs(l-f)<0.01&&Math.abs(u-g)<0.01&&Math.abs(d-b)<0.01){if(Math.abs(l+f)<0.1&&Math.abs(u+g)<0.1&&Math.abs(d+b)<0.1&&Math.abs(c+h+p-3)<0.1)return this.set(1,0,0,0),this;t=Math.PI;let A=(c+1)/2,T=(h+1)/2,v=(p+1)/2,w=(l+f)/4,E=(u+g)/4,R=(d+b)/4;if(A>T&&A>v)if(A<0.01)n=0,i=0.707106781,r=0.707106781;else n=Math.sqrt(A),i=w/n,r=E/n;else if(T>v)if(T<0.01)n=0.707106781,i=0,r=0.707106781;else i=Math.sqrt(T),n=w/i,r=R/i;else if(v<0.01)n=0.707106781,i=0.707106781,r=0;else r=Math.sqrt(v),n=E/r,i=R/r;return this.set(n,i,r,t),this}let m=Math.sqrt((b-d)*(b-d)+(u-g)*(u-g)+(f-l)*(f-l));if(Math.abs(m)<0.001)m=1;return this.x=(b-d)/m,this.y=(u-g)/m,this.z=(f-l)/m,this.w=Math.acos((c+h+p-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=We(this.x,e.x,t.x),this.y=We(this.y,e.y,t.y),this.z=We(this.z,e.z,t.z),this.w=We(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=We(this.x,e,t),this.y=We(this.y,e,t),this.z=We(this.z,e,t),this.w=We(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(We(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}}class bl extends Nn{constructor(e=1,t=1,n={}){super();n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new it(0,0,e,t),this.scissorTest=!1,this.viewport=new it(0,0,e,t),this.textures=[];let i={width:e,height:t,depth:n.depth},r=new St(i),s=n.count;for(let o=0;o<s;o++)this.textures[o]=r.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,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){let t={minFilter:1006,generateMipmaps:!1,flipY:!1,internalFormat:null};if(e.mapping!==void 0)t.mapping=e.mapping;if(e.wrapS!==void 0)t.wrapS=e.wrapS;if(e.wrapT!==void 0)t.wrapT=e.wrapT;if(e.wrapR!==void 0)t.wrapR=e.wrapR;if(e.magFilter!==void 0)t.magFilter=e.magFilter;if(e.minFilter!==void 0)t.minFilter=e.minFilter;if(e.format!==void 0)t.format=e.format;if(e.type!==void 0)t.type=e.type;if(e.anisotropy!==void 0)t.anisotropy=e.anisotropy;if(e.colorSpace!==void 0)t.colorSpace=e.colorSpace;if(e.flipY!==void 0)t.flipY=e.flipY;if(e.generateMipmaps!==void 0)t.generateMipmaps=e.generateMipmaps;if(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){if(this._depthTexture!==null)this._depthTexture.renderTarget=null;if(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 i=0,r=this.textures.length;i<r;i++)if(this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=n,this.textures[i].isData3DTexture!==!0)this.textures[i].isArrayTexture=this.textures[i].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 i=Object.assign({},e.textures[t].image);this.textures[t].source=new ws(i)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null)this.depthTexture=e.depthTexture.clone();return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class yn extends bl{constructor(e=1,t=1,n={}){super(e,t,n);this.isWebGLRenderTarget=!0}}class Yo extends St{constructor(e=null,t=1,n=1,i=1){super(null);this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class Sl extends St{constructor(e=null,t=1,n=1,i=1){super(null);this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=1003,this.minFilter=1003,this.wrapR=1001,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Fe{static{Fe.prototype.isMatrix4=!0}constructor(e,t,n,i,r,s,o,a,c,l,u,f,h,d,g,b){if(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,i,r,s,o,a,c,l,u,f,h,d,g,b)}set(e,t,n,i,r,s,o,a,c,l,u,f,h,d,g,b){let p=this.elements;return p[0]=e,p[4]=t,p[8]=n,p[12]=i,p[1]=r,p[5]=s,p[9]=o,p[13]=a,p[2]=c,p[6]=l,p[10]=u,p[14]=f,p[3]=h,p[7]=d,p[11]=g,p[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 Fe().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){if(this.determinantAffine()===0)return e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this;return 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.determinantAffine()===0)return this.identity();let t=this.elements,n=e.elements,i=1/Sr.setFromMatrixColumn(e,0).length(),r=1/Sr.setFromMatrixColumn(e,1).length(),s=1/Sr.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,{x:n,y:i,z:r}=e,s=Math.cos(n),o=Math.sin(n),a=Math.cos(i),c=Math.sin(i),l=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){let f=s*l,h=s*u,d=o*l,g=o*u;t[0]=a*l,t[4]=-a*u,t[8]=c,t[1]=h+d*c,t[5]=f-g*c,t[9]=-o*a,t[2]=g-f*c,t[6]=d+h*c,t[10]=s*a}else if(e.order==="YXZ"){let f=a*l,h=a*u,d=c*l,g=c*u;t[0]=f+g*o,t[4]=d*o-h,t[8]=s*c,t[1]=s*u,t[5]=s*l,t[9]=-o,t[2]=h*o-d,t[6]=g+f*o,t[10]=s*a}else if(e.order==="ZXY"){let f=a*l,h=a*u,d=c*l,g=c*u;t[0]=f-g*o,t[4]=-s*u,t[8]=d+h*o,t[1]=h+d*o,t[5]=s*l,t[9]=g-f*o,t[2]=-s*c,t[6]=o,t[10]=s*a}else if(e.order==="ZYX"){let f=s*l,h=s*u,d=o*l,g=o*u;t[0]=a*l,t[4]=d*c-h,t[8]=f*c+g,t[1]=a*u,t[5]=g*c+f,t[9]=h*c-d,t[2]=-c,t[6]=o*a,t[10]=s*a}else if(e.order==="YZX"){let f=s*a,h=s*c,d=o*a,g=o*c;t[0]=a*l,t[4]=g-f*u,t[8]=d*u+h,t[1]=u,t[5]=s*l,t[9]=-o*l,t[2]=-c*l,t[6]=h*u+d,t[10]=f-g*u}else if(e.order==="XZY"){let f=s*a,h=s*c,d=o*a,g=o*c;t[0]=a*l,t[4]=-u,t[8]=c*l,t[1]=f*u+g,t[5]=s*l,t[9]=h*u-d,t[2]=d*u-h,t[6]=o*l,t[10]=g*u+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(sx,e,ox)}lookAt(e,t,n){let i=this.elements;if(on.subVectors(e,t),on.lengthSq()===0)on.z=1;if(on.normalize(),yi.crossVectors(n,on),yi.lengthSq()===0){if(Math.abs(n.z)===1)on.x+=0.0001;else on.z+=0.0001;on.normalize(),yi.crossVectors(n,on)}return yi.normalize(),ao.crossVectors(on,yi),i[0]=yi.x,i[4]=ao.x,i[8]=on.x,i[1]=yi.y,i[5]=ao.y,i[9]=on.y,i[2]=yi.z,i[6]=ao.z,i[10]=on.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,r=this.elements,s=n[0],o=n[4],a=n[8],c=n[12],l=n[1],u=n[5],f=n[9],h=n[13],d=n[2],g=n[6],b=n[10],p=n[14],m=n[3],A=n[7],T=n[11],v=n[15],w=i[0],E=i[4],R=i[8],_=i[12],S=i[1],F=i[5],C=i[9],z=i[13],J=i[2],O=i[6],H=i[10],V=i[14],U=i[3],K=i[7],Q=i[11],se=i[15];return r[0]=s*w+o*S+a*J+c*U,r[4]=s*E+o*F+a*O+c*K,r[8]=s*R+o*C+a*H+c*Q,r[12]=s*_+o*z+a*V+c*se,r[1]=l*w+u*S+f*J+h*U,r[5]=l*E+u*F+f*O+h*K,r[9]=l*R+u*C+f*H+h*Q,r[13]=l*_+u*z+f*V+h*se,r[2]=d*w+g*S+b*J+p*U,r[6]=d*E+g*F+b*O+p*K,r[10]=d*R+g*C+b*H+p*Q,r[14]=d*_+g*z+b*V+p*se,r[3]=m*w+A*S+T*J+v*U,r[7]=m*E+A*F+T*O+v*K,r[11]=m*R+A*C+T*H+v*Q,r[15]=m*_+A*z+T*V+v*se,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],i=e[8],r=e[12],s=e[1],o=e[5],a=e[9],c=e[13],l=e[2],u=e[6],f=e[10],h=e[14],d=e[3],g=e[7],b=e[11],p=e[15],m=a*h-c*f,A=o*h-c*u,T=o*f-a*u,v=s*h-c*l,w=s*f-a*l,E=s*u-o*l;return t*(g*m-b*A+p*T)-n*(d*m-b*v+p*w)+i*(d*A-g*v+p*E)-r*(d*T-g*w+b*E)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],i=e[8],r=e[1],s=e[5],o=e[9],a=e[2],c=e[6],l=e[10];return t*(s*l-o*c)-n*(r*l-o*a)+i*(r*c-s*a)}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 i=this.elements;if(e.isVector3)i[12]=e.x,i[13]=e.y,i[14]=e.z;else i[12]=e,i[13]=t,i[14]=n;return this}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],o=e[5],a=e[6],c=e[7],l=e[8],u=e[9],f=e[10],h=e[11],d=e[12],g=e[13],b=e[14],p=e[15],m=t*o-n*s,A=t*a-i*s,T=t*c-r*s,v=n*a-i*o,w=n*c-r*o,E=i*c-r*a,R=l*g-u*d,_=l*b-f*d,S=l*p-h*d,F=u*b-f*g,C=u*p-h*g,z=f*p-h*b,J=m*z-A*C+T*F+v*S-w*_+E*R;if(J===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let O=1/J;return e[0]=(o*z-a*C+c*F)*O,e[1]=(i*C-n*z-r*F)*O,e[2]=(g*E-b*w+p*v)*O,e[3]=(f*w-u*E-h*v)*O,e[4]=(a*S-s*z-c*_)*O,e[5]=(t*z-i*S+r*_)*O,e[6]=(b*T-d*E-p*A)*O,e[7]=(l*E-f*T+h*A)*O,e[8]=(s*C-o*S+c*R)*O,e[9]=(n*S-t*C-r*R)*O,e[10]=(d*w-g*T+p*m)*O,e[11]=(u*T-l*w-h*m)*O,e[12]=(o*_-s*F-a*R)*O,e[13]=(t*F-n*_+i*R)*O,e[14]=(g*A-d*v-b*m)*O,e[15]=(l*v-u*A+f*m)*O,this}scale(e){let t=this.elements,{x:n,y:i,z:r}=e;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,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],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){if(e.isVector3)this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1);else this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1);return 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),i=Math.sin(t),r=1-n,{x:s,y:o,z:a}=e,c=r*s,l=r*o;return this.set(c*s+n,c*o-i*a,c*a+i*o,0,c*o+i*a,l*o+n,l*a-i*s,0,c*a-i*o,l*a+i*s,r*a*a+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,i,r,s){return this.set(1,n,r,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){let i=this.elements,{_x:r,_y:s,_z:o,_w:a}=t,c=r+r,l=s+s,u=o+o,f=r*c,h=r*l,d=r*u,g=s*l,b=s*u,p=o*u,m=a*c,A=a*l,T=a*u,{x:v,y:w,z:E}=n;return i[0]=(1-(g+p))*v,i[1]=(h+T)*v,i[2]=(d-A)*v,i[3]=0,i[4]=(h-T)*w,i[5]=(1-(f+p))*w,i[6]=(b+m)*w,i[7]=0,i[8]=(d+A)*E,i[9]=(b-m)*E,i[10]=(1-(f+g))*E,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){let i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];let r=this.determinantAffine();if(r===0)return n.set(1,1,1),t.identity(),this;let s=Sr.set(i[0],i[1],i[2]).length(),o=Sr.set(i[4],i[5],i[6]).length(),a=Sr.set(i[8],i[9],i[10]).length();if(r<0)s=-s;wn.copy(this);let c=1/s,l=1/o,u=1/a;return wn.elements[0]*=c,wn.elements[1]*=c,wn.elements[2]*=c,wn.elements[4]*=l,wn.elements[5]*=l,wn.elements[6]*=l,wn.elements[8]*=u,wn.elements[9]*=u,wn.elements[10]*=u,t.setFromRotationMatrix(wn),n.x=s,n.y=o,n.z=a,this}makePerspective(e,t,n,i,r,s,o=2000,a=!1){let c=this.elements,l=2*r/(t-e),u=2*r/(n-i),f=(t+e)/(t-e),h=(n+i)/(n-i),d,g;if(a)d=r/(s-r),g=s*r/(s-r);else if(o===2000)d=-(s+r)/(s-r),g=-2*s*r/(s-r);else if(o===2001)d=-s/(s-r),g=-s*r/(s-r);else throw Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return c[0]=l,c[4]=0,c[8]=f,c[12]=0,c[1]=0,c[5]=u,c[9]=h,c[13]=0,c[2]=0,c[6]=0,c[10]=d,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,i,r,s,o=2000,a=!1){let c=this.elements,l=2/(t-e),u=2/(n-i),f=-(t+e)/(t-e),h=-(n+i)/(n-i),d,g;if(a)d=1/(s-r),g=s/(s-r);else if(o===2000)d=-2/(s-r),g=-(s+r)/(s-r);else if(o===2001)d=-1/(s-r),g=-r/(s-r);else throw Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=f,c[1]=0,c[5]=u,c[9]=0,c[13]=h,c[2]=0,c[6]=0,c[10]=d,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])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}}var Sr=new N,wn=new Fe,sx=new N(0,0,0),ox=new N(1,1,1),yi=new N,ao=new N,on=new N,mh=new Fe,gh=new zt;class Hn{constructor(e=0,t=0,n=0,i=Hn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}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,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,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 i=e.elements,r=i[0],s=i[4],o=i[8],a=i[1],c=i[5],l=i[9],u=i[2],f=i[6],h=i[10];switch(t){case"XYZ":if(this._y=Math.asin(We(o,-1,1)),Math.abs(o)<0.9999999)this._x=Math.atan2(-l,h),this._z=Math.atan2(-s,r);else this._x=Math.atan2(f,c),this._z=0;break;case"YXZ":if(this._x=Math.asin(-We(l,-1,1)),Math.abs(l)<0.9999999)this._y=Math.atan2(o,h),this._z=Math.atan2(a,c);else this._y=Math.atan2(-u,r),this._z=0;break;case"ZXY":if(this._x=Math.asin(We(f,-1,1)),Math.abs(f)<0.9999999)this._y=Math.atan2(-u,h),this._z=Math.atan2(-s,c);else this._y=0,this._z=Math.atan2(a,r);break;case"ZYX":if(this._y=Math.asin(-We(u,-1,1)),Math.abs(u)<0.9999999)this._x=Math.atan2(f,h),this._z=Math.atan2(a,r);else this._x=0,this._z=Math.atan2(-s,c);break;case"YZX":if(this._z=Math.asin(We(a,-1,1)),Math.abs(a)<0.9999999)this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,r);else this._x=0,this._y=Math.atan2(o,h);break;case"XZY":if(this._z=Math.asin(-We(s,-1,1)),Math.abs(s)<0.9999999)this._x=Math.atan2(f,c),this._y=Math.atan2(o,r);else this._x=Math.atan2(-l,h),this._y=0;break;default:Me("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}if(this._order=t,n===!0)this._onChangeCallback();return this}setFromQuaternion(e,t,n){return mh.makeRotationFromQuaternion(e),this.setFromRotationMatrix(mh,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return gh.setFromEuler(this),this.setFromQuaternion(gh,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){if(this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0)this._order=e[3];return 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}}Hn.DEFAULT_ORDER="XYZ";class jo{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}}var ax=0,_h=new N,Mr=new zt,ii=new Fe,co=new N,os=new N,cx=new N,lx=new zt,xh=new N(1,0,0),vh=new N(0,1,0),yh=new N(0,0,1),bh={type:"added"},ux={type:"removed"},wr={type:"childadded",child:null},Ja={type:"childremoved",child:null};class ot extends Nn{constructor(){super();this.isObject3D=!0,Object.defineProperty(this,"id",{value:ax++}),this.uuid=Cn(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ot.DEFAULT_UP.clone();let e=new N,t=new Hn,n=new zt,i=new N(1,1,1);function r(){n.setFromEuler(t,!1)}function s(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(s),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:i},modelViewMatrix:{value:new Fe},normalMatrix:{value:new De}}),this.matrix=new Fe,this.matrixWorld=new Fe,this.matrixAutoUpdate=ot.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ot.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new jo,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){if(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 Mr.setFromAxisAngle(e,t),this.quaternion.multiply(Mr),this}rotateOnWorldAxis(e,t){return Mr.setFromAxisAngle(e,t),this.quaternion.premultiply(Mr),this}rotateX(e){return this.rotateOnAxis(xh,e)}rotateY(e){return this.rotateOnAxis(vh,e)}rotateZ(e){return this.rotateOnAxis(yh,e)}translateOnAxis(e,t){return _h.copy(e).applyQuaternion(this.quaternion),this.position.add(_h.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(xh,e)}translateY(e){return this.translateOnAxis(vh,e)}translateZ(e){return this.translateOnAxis(yh,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(ii.copy(this.matrixWorld).invert())}lookAt(e,t,n){if(e.isVector3)co.copy(e);else co.set(e,t,n);let i=this.parent;if(this.updateWorldMatrix(!0,!1),os.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight)ii.lookAt(os,co,this.up);else ii.lookAt(co,os,this.up);if(this.quaternion.setFromRotationMatrix(ii),i)ii.extractRotation(i.matrixWorld),Mr.setFromRotationMatrix(ii),this.quaternion.premultiply(Mr.invert())}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}if(e===this)return Ne("Object3D.add: object can't be added as a child of itself.",e),this;if(e&&e.isObject3D)e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(bh),wr.child=e,this.dispatchEvent(wr),wr.child=null;else Ne("Object3D.add: object not an instance of THREE.Object3D.",e);return 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);if(t!==-1)e.parent=null,this.children.splice(t,1),e.dispatchEvent(ux),Ja.child=e,this.dispatchEvent(Ja),Ja.child=null;return this}removeFromParent(){let e=this.parent;if(e!==null)e.remove(this);return this}clear(){return this.remove(...this.children)}attach(e){if(this.updateWorldMatrix(!0,!1),ii.copy(this.matrixWorld).invert(),e.parent!==null)e.parent.updateWorldMatrix(!0,!1),ii.multiply(e.parent.matrixWorld);return e.applyMatrix4(ii),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(bh),wr.child=e,this.dispatchEvent(wr),wr.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,i=this.children.length;n<i;n++){let s=this.children[n].getObjectByProperty(e,t);if(s!==void 0)return s}return}getObjectsByProperty(e,t,n=[]){if(this[e]===t)n.push(this);let i=this.children;for(let r=0,s=i.length;r<s;r++)i[r].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(os,e,cx),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(os,lx,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,i=t.length;n<i;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;if(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{x:t,y:n,z:i}=e,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*n-r[8]*i,r[13]+=n-r[1]*t-r[5]*n-r[9]*i,r[14]+=i-r[2]*t-r[6]*n-r[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||e){if(this.matrixWorldAutoUpdate===!0)if(this.parent===null)this.matrixWorld.copy(this.matrix);else this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);this.matrixWorldNeedsUpdate=!1,e=!0}let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t,n=!1){let i=this.parent;if(e===!0&&i!==null)i.updateWorldMatrix(!0,!1);if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||n){if(this.matrixWorldAutoUpdate===!0)if(this.parent===null)this.matrixWorld.copy(this.matrix);else this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);this.matrixWorldNeedsUpdate=!1,n=!0}if(t===!0){let r=this.children;for(let s=0,o=r.length;s<o;s++)r[s].updateWorldMatrix(!1,!0,n)}}toJSON(e){let t=e===void 0||typeof e==="string",n={};if(t)e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"};let i={};if(i.uuid=this.uuid,i.type=this.type,this.name!=="")i.name=this.name;if(this.castShadow===!0)i.castShadow=!0;if(this.receiveShadow===!0)i.receiveShadow=!0;if(this.visible===!1)i.visible=!1;if(this.frustumCulled===!1)i.frustumCulled=!1;if(this.renderOrder!==0)i.renderOrder=this.renderOrder;if(this.static!==!1)i.static=this.static;if(Object.keys(this.userData).length>0)i.userData=this.userData;if(i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.pivot!==null)i.pivot=this.pivot.toArray();if(this.matrixAutoUpdate===!1)i.matrixAutoUpdate=!1;if(this.morphTargetDictionary!==void 0)i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary);if(this.morphTargetInfluences!==void 0)i.morphTargetInfluences=this.morphTargetInfluences.slice();if(this.isInstancedMesh){if(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null)i.instanceColor=this.instanceColor.toJSON()}if(this.isBatchedMesh){if(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map((o)=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map((o)=>({...o})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null)i.colorsTexture=this._colorsTexture.toJSON(e);if(this.boundingSphere!==null)i.boundingSphere=this.boundingSphere.toJSON();if(this.boundingBox!==null)i.boundingBox=this.boundingBox.toJSON()}function r(o,a){if(o[a.uuid]===void 0)o[a.uuid]=a.toJSON(e);return a.uuid}if(this.isScene){if(this.background){if(this.background.isColor)i.background=this.background.toJSON();else if(this.background.isTexture)i.background=this.background.toJSON(e).uuid}if(this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0)i.environment=this.environment.toJSON(e).uuid}else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let a=o.shapes;if(Array.isArray(a))for(let c=0,l=a.length;c<l;c++){let u=a[c];r(e.shapes,u)}else r(e.shapes,a)}}if(this.isSkinnedMesh){if(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0)r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid}if(this.material!==void 0)if(Array.isArray(this.material)){let o=[];for(let a=0,c=this.material.length;a<c;a++)o.push(r(e.materials,this.material[a]));i.material=o}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let o=0;o<this.children.length;o++)i.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let o=0;o<this.animations.length;o++){let a=this.animations[o];i.animations.push(r(e.animations,a))}}if(t){let o=s(e.geometries),a=s(e.materials),c=s(e.textures),l=s(e.images),u=s(e.shapes),f=s(e.skeletons),h=s(e.animations),d=s(e.nodes);if(o.length>0)n.geometries=o;if(a.length>0)n.materials=a;if(c.length>0)n.textures=c;if(l.length>0)n.images=l;if(u.length>0)n.shapes=u;if(f.length>0)n.skeletons=f;if(h.length>0)n.animations=h;if(d.length>0)n.nodes=d}return n.object=i,n;function s(o){let a=[];for(let c in o){let l=o[c];delete l.metadata,a.push(l)}return a}}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 i=e.children[n];this.add(i.clone())}return this}}ot.DEFAULT_UP=new N(0,1,0);ot.DEFAULT_MATRIX_AUTO_UPDATE=!0;ot.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class Bn extends ot{constructor(){super();this.isGroup=!0,this.type="Group"}}var hx={type:"move"};class Ts{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){if(this._hand===null)this._hand=new Bn,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1};return this._hand}getTargetRaySpace(){if(this._targetRay===null)this._targetRay=new Bn,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new N,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new N;return this._targetRay}getGripSpace(){if(this._grip===null)this._grip=new Bn,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new N,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new N,this._grip.eventsEnabled=!1;return this._grip}dispatchEvent(e){if(this._targetRay!==null)this._targetRay.dispatchEvent(e);if(this._grip!==null)this._grip.dispatchEvent(e);if(this._hand!==null)this._hand.dispatchEvent(e);return 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){if(this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null)this._targetRay.visible=!1;if(this._grip!==null)this._grip.visible=!1;if(this._hand!==null)this._hand.visible=!1;return this}update(e,t,n){let i=null,r=null,s=null,o=this._targetRay,a=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){s=!0;for(let g of e.hand.values()){let b=t.getJointPose(g,n),p=this._getHandJoint(c,g);if(b!==null)p.matrix.fromArray(b.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=b.radius;p.visible=b!==null}let l=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],f=l.position.distanceTo(u.position),h=0.02,d=0.005;if(c.inputState.pinching&&f>h+d)c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this});else if(!c.inputState.pinching&&f<=h-d)c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this})}else if(a!==null&&e.gripSpace){if(r=t.getPose(e.gripSpace,n),r!==null){if(a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,r.linearVelocity)a.hasLinearVelocity=!0,a.linearVelocity.copy(r.linearVelocity);else a.hasLinearVelocity=!1;if(r.angularVelocity)a.hasAngularVelocity=!0,a.angularVelocity.copy(r.angularVelocity);else a.hasAngularVelocity=!1;if(a.eventsEnabled)a.dispatchEvent({type:"gripUpdated",data:e,target:this})}}if(o!==null){if(i=t.getPose(e.targetRaySpace,n),i===null&&r!==null)i=r;if(i!==null){if(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity)o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity);else o.hasLinearVelocity=!1;if(i.angularVelocity)o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity);else o.hasAngularVelocity=!1;this.dispatchEvent(hx)}}}if(o!==null)o.visible=i!==null;if(a!==null)a.visible=r!==null;if(c!==null)c.visible=s!==null;return this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new Bn;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}var $f={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},bi={h:0,s:0,l:0},lo={h:0,s:0,l:0};function Ka(e,t,n){if(n<0)n+=1;if(n>1)n-=1;if(n<0.16666666666666666)return e+(t-e)*6*n;if(n<0.5)return t;if(n<0.6666666666666666)return e+(t-e)*6*(0.6666666666666666-n);return e}class Le{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 i=e;if(i&&i.isColor)this.copy(i);else if(typeof i==="number")this.setHex(i);else if(typeof i==="string")this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t="srgb"){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ve.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=Ve.workingColorSpace){return this.r=e,this.g=t,this.b=n,Ve.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=Ve.workingColorSpace){if(e=vl(e,1),t=We(t,0,1),n=We(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=0.5?n*(1+t):n+t-n*t,s=2*n-r;this.r=Ka(s,r,e+0.3333333333333333),this.g=Ka(s,r,e),this.b=Ka(s,r,e-0.3333333333333333)}return Ve.colorSpaceToWorking(this,i),this}setStyle(e,t="srgb"){function n(r){if(r===void 0)return;if(parseFloat(r)<1)Me("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r,s=i[1],o=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Me("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){let r=i[1],s=r.length;if(s===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);else if(s===6)return this.setHex(parseInt(r,16),t);else Me("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t="srgb"){let n=$f[e.toLowerCase()];if(n!==void 0)this.setHex(n,t);else Me("Color: Unknown color "+e);return 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=li(e.r),this.g=li(e.g),this.b=li(e.b),this}copyLinearToSRGB(e){return this.r=Ur(e.r),this.g=Ur(e.g),this.b=Ur(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e="srgb"){return Ve.workingToColorSpace(Zt.copy(this),e),Math.round(We(Zt.r*255,0,255))*65536+Math.round(We(Zt.g*255,0,255))*256+Math.round(We(Zt.b*255,0,255))}getHexString(e="srgb"){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ve.workingColorSpace){Ve.workingToColorSpace(Zt.copy(this),t);let{r:n,g:i,b:r}=Zt,s=Math.max(n,i,r),o=Math.min(n,i,r),a,c,l=(o+s)/2;if(o===s)a=0,c=0;else{let u=s-o;switch(c=l<=0.5?u/(s+o):u/(2-s-o),s){case n:a=(i-r)/u+(i<r?6:0);break;case i:a=(r-n)/u+2;break;case r:a=(n-i)/u+4;break}a/=6}return e.h=a,e.s=c,e.l=l,e}getRGB(e,t=Ve.workingColorSpace){return Ve.workingToColorSpace(Zt.copy(this),t),e.r=Zt.r,e.g=Zt.g,e.b=Zt.b,e}getStyle(e="srgb"){Ve.workingToColorSpace(Zt.copy(this),e);let{r:t,g:n,b:i}=Zt;if(e!=="srgb")return`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`;return`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(i*255)})`}offsetHSL(e,t,n){return this.getHSL(bi),this.setHSL(bi.h+e,bi.s+t,bi.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(bi),e.getHSL(lo);let n=ms(bi.h,lo.h,t),i=ms(bi.s,lo.s,t),r=ms(bi.l,lo.l,t);return this.setHSL(n,i,r),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,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*i,this.g=r[1]*t+r[4]*n+r[7]*i,this.b=r[2]*t+r[5]*n+r[8]*i,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}}var Zt=new Le;Le.NAMES=$f;class Xr extends ot{constructor(){super();if(this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Hn,this.environmentIntensity=1,this.environmentRotation=new Hn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){if(super.copy(e,t),e.background!==null)this.background=e.background.clone();if(e.environment!==null)this.environment=e.environment.clone();if(e.fog!==null)this.fog=e.fog.clone();if(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();return this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);if(this.fog!==null)t.object.fog=this.fog.toJSON();if(this.backgroundBlurriness>0)t.object.backgroundBlurriness=this.backgroundBlurriness;if(this.backgroundIntensity!==1)t.object.backgroundIntensity=this.backgroundIntensity;if(t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1)t.object.environmentIntensity=this.environmentIntensity;return t.object.environmentRotation=this.environmentRotation.toArray(),t}}var Tn=new N,ri=new N,Qa=new N,si=new N,Tr=new N,Er=new N,Sh=new N,ec=new N,tc=new N,nc=new N,ic=new it,rc=new it,sc=new it;class xn{constructor(e=new N,t=new N,n=new N){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),Tn.subVectors(e,t),i.cross(Tn);let r=i.lengthSq();if(r>0)return i.multiplyScalar(1/Math.sqrt(r));return i.set(0,0,0)}static getBarycoord(e,t,n,i,r){Tn.subVectors(i,t),ri.subVectors(n,t),Qa.subVectors(e,t);let s=Tn.dot(Tn),o=Tn.dot(ri),a=Tn.dot(Qa),c=ri.dot(ri),l=ri.dot(Qa),u=s*c-o*o;if(u===0)return r.set(0,0,0),null;let f=1/u,h=(c*a-o*l)*f,d=(s*l-o*a)*f;return r.set(1-h-d,d,h)}static containsPoint(e,t,n,i){if(this.getBarycoord(e,t,n,i,si)===null)return!1;return si.x>=0&&si.y>=0&&si.x+si.y<=1}static getInterpolation(e,t,n,i,r,s,o,a){if(this.getBarycoord(e,t,n,i,si)===null){if(a.x=0,a.y=0,"z"in a)a.z=0;if("w"in a)a.w=0;return null}return a.setScalar(0),a.addScaledVector(r,si.x),a.addScaledVector(s,si.y),a.addScaledVector(o,si.z),a}static getInterpolatedAttribute(e,t,n,i,r,s){return ic.setScalar(0),rc.setScalar(0),sc.setScalar(0),ic.fromBufferAttribute(e,t),rc.fromBufferAttribute(e,n),sc.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(ic,r.x),s.addScaledVector(rc,r.y),s.addScaledVector(sc,r.z),s}static isFrontFacing(e,t,n,i){return Tn.subVectors(n,t),ri.subVectors(e,t),Tn.cross(ri).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),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 Tn.subVectors(this.c,this.b),ri.subVectors(this.a,this.b),Tn.cross(ri).length()*0.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(0.3333333333333333)}getNormal(e){return xn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return xn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return xn.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return xn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return xn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,r=this.c,s,o;Tr.subVectors(i,n),Er.subVectors(r,n),ec.subVectors(e,n);let a=Tr.dot(ec),c=Er.dot(ec);if(a<=0&&c<=0)return t.copy(n);tc.subVectors(e,i);let l=Tr.dot(tc),u=Er.dot(tc);if(l>=0&&u<=l)return t.copy(i);let f=a*u-l*c;if(f<=0&&a>=0&&l<=0)return s=a/(a-l),t.copy(n).addScaledVector(Tr,s);nc.subVectors(e,r);let h=Tr.dot(nc),d=Er.dot(nc);if(d>=0&&h<=d)return t.copy(r);let g=h*c-a*d;if(g<=0&&c>=0&&d<=0)return o=c/(c-d),t.copy(n).addScaledVector(Er,o);let b=l*d-h*u;if(b<=0&&u-l>=0&&h-d>=0)return Sh.subVectors(r,i),o=(u-l)/(u-l+(h-d)),t.copy(i).addScaledVector(Sh,o);let p=1/(b+g+f);return s=g*p,o=f*p,t.copy(n).addScaledVector(Tr,s).addScaledVector(Er,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Jt{constructor(e=new N(1/0,1/0,1/0),t=new N(-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(En.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(En.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=En.copy(t).multiplyScalar(0.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(0.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 r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let s=0,o=r.count;s<o;s++){if(e.isMesh===!0)e.getVertexPosition(s,En);else En.fromBufferAttribute(r,s);En.applyMatrix4(e.matrixWorld),this.expandByPoint(En)}else{if(e.boundingBox!==void 0){if(e.boundingBox===null)e.computeBoundingBox();uo.copy(e.boundingBox)}else{if(n.boundingBox===null)n.computeBoundingBox();uo.copy(n.boundingBox)}uo.applyMatrix4(e.matrixWorld),this.union(uo)}}let i=e.children;for(let r=0,s=i.length;r<s;r++)this.expandByObject(i[r],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,En),En.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;if(e.normal.x>0)t=e.normal.x*this.min.x,n=e.normal.x*this.max.x;else t=e.normal.x*this.max.x,n=e.normal.x*this.min.x;if(e.normal.y>0)t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y;else t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y;if(e.normal.z>0)t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z;else t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z;return t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(as),ho.subVectors(this.max,as),Ar.subVectors(e.a,as),Rr.subVectors(e.b,as),Cr.subVectors(e.c,as),Si.subVectors(Rr,Ar),Mi.subVectors(Cr,Rr),Yi.subVectors(Ar,Cr);let t=[0,-Si.z,Si.y,0,-Mi.z,Mi.y,0,-Yi.z,Yi.y,Si.z,0,-Si.x,Mi.z,0,-Mi.x,Yi.z,0,-Yi.x,-Si.y,Si.x,0,-Mi.y,Mi.x,0,-Yi.y,Yi.x,0];if(!oc(t,Ar,Rr,Cr,ho))return!1;if(t=[1,0,0,0,1,0,0,0,1],!oc(t,Ar,Rr,Cr,ho))return!1;return fo.crossVectors(Si,Mi),t=[fo.x,fo.y,fo.z],oc(t,Ar,Rr,Cr,ho)}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,En).distanceTo(e)}getBoundingSphere(e){if(this.isEmpty())e.makeEmpty();else this.getCenter(e.center),e.radius=this.getSize(En).length()*0.5;return e}intersect(e){if(this.min.max(e.min),this.max.min(e.max),this.isEmpty())this.makeEmpty();return this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){if(this.isEmpty())return this;return oi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),oi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),oi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),oi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),oi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),oi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),oi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),oi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(oi),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}}var oi=[new N,new N,new N,new N,new N,new N,new N,new N],En=new N,uo=new Jt,Ar=new N,Rr=new N,Cr=new N,Si=new N,Mi=new N,Yi=new N,as=new N,ho=new N,fo=new N,ji=new N;function oc(e,t,n,i,r){for(let s=0,o=e.length-3;s<=o;s+=3){ji.fromArray(e,s);let a=r.x*Math.abs(ji.x)+r.y*Math.abs(ji.y)+r.z*Math.abs(ji.z),c=t.dot(ji),l=n.dot(ji),u=i.dot(ji);if(Math.max(-Math.max(c,l,u),Math.min(c,l,u))>a)return!1}return!0}var Rt=new N,po=new Pe,fx=0;class It extends Nn{constructor(e,t,n=!1){super();if(Array.isArray(e))throw TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:fx++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=35044,this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate(e){if(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 i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[n+i];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++)po.fromBufferAttribute(this,t),po.applyMatrix3(e),this.setXY(t,po.x,po.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Rt.fromBufferAttribute(this,t),Rt.applyMatrix3(e),this.setXYZ(t,Rt.x,Rt.y,Rt.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Rt.fromBufferAttribute(this,t),Rt.applyMatrix4(e),this.setXYZ(t,Rt.x,Rt.y,Rt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Rt.fromBufferAttribute(this,t),Rt.applyNormalMatrix(e),this.setXYZ(t,Rt.x,Rt.y,Rt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Rt.fromBufferAttribute(this,t),Rt.transformDirection(e),this.setXYZ(t,Rt.x,Rt.y,Rt.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];if(this.normalized)n=Rn(n,this.array);return n}setComponent(e,t,n){if(this.normalized)n=nt(n,this.array);return this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];if(this.normalized)t=Rn(t,this.array);return t}setX(e,t){if(this.normalized)t=nt(t,this.array);return this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];if(this.normalized)t=Rn(t,this.array);return t}setY(e,t){if(this.normalized)t=nt(t,this.array);return this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];if(this.normalized)t=Rn(t,this.array);return t}setZ(e,t){if(this.normalized)t=nt(t,this.array);return this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];if(this.normalized)t=Rn(t,this.array);return t}setW(e,t){if(this.normalized)t=nt(t,this.array);return this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){if(e*=this.itemSize,this.normalized)t=nt(t,this.array),n=nt(n,this.array);return this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,i){if(e*=this.itemSize,this.normalized)t=nt(t,this.array),n=nt(n,this.array),i=nt(i,this.array);return this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,r){if(e*=this.itemSize,this.normalized)t=nt(t,this.array),n=nt(n,this.array),i=nt(i,this.array),r=nt(r,this.array);return this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this.array[e+3]=r,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};if(this.name!=="")e.name=this.name;if(this.usage!==35044)e.usage=this.usage;return e}dispose(){this.dispatchEvent({type:"dispose"})}}class Jo extends It{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class Ko extends It{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class tn extends It{constructor(e,t,n){super(new Float32Array(e),t,n)}}var dx=new Jt,cs=new N,ac=new N;class ln{constructor(e=new N,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;if(t!==void 0)n.copy(t);else dx.setFromPoints(e).getCenter(n);let i=0;for(let r=0,s=e.length;r<s;r++)i=Math.max(i,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(i),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);if(t.copy(e),n>this.radius*this.radius)t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center);return t}getBoundingBox(e){if(this.isEmpty())return e.makeEmpty(),e;return 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;cs.subVectors(e,this.center);let t=cs.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=(n-this.radius)*0.5;this.center.addScaledVector(cs,i/n),this.radius+=i}return this}union(e){if(e.isEmpty())return this;if(this.isEmpty())return this.copy(e),this;if(this.center.equals(e.center)===!0)this.radius=Math.max(this.radius,e.radius);else ac.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(cs.copy(e.center).add(ac)),this.expandByPoint(cs.copy(e.center).sub(ac));return 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}}var px=0,_n=new Fe,cc=new ot,Pr=new N,an=new Jt,ls=new Jt,Ft=new N;class Kt extends Nn{constructor(){super();this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:px++}),this.uuid=Cn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){if(Array.isArray(e))this.index=new((z0(e))?Ko:Jo)(e,1);else this.index=e;return 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;if(t!==void 0)t.applyMatrix4(e),t.needsUpdate=!0;let n=this.attributes.normal;if(n!==void 0){let r=new De().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}let i=this.attributes.tangent;if(i!==void 0)i.transformDirection(e),i.needsUpdate=!0;if(this.boundingBox!==null)this.computeBoundingBox();if(this.boundingSphere!==null)this.computeBoundingSphere();return this._transformed=!0,this}applyQuaternion(e){return _n.makeRotationFromQuaternion(e),this.applyMatrix4(_n),this}rotateX(e){return _n.makeRotationX(e),this.applyMatrix4(_n),this}rotateY(e){return _n.makeRotationY(e),this.applyMatrix4(_n),this}rotateZ(e){return _n.makeRotationZ(e),this.applyMatrix4(_n),this}translate(e,t,n){return _n.makeTranslation(e,t,n),this.applyMatrix4(_n),this}scale(e,t,n){return _n.makeScale(e,t,n),this.applyMatrix4(_n),this}lookAt(e){return cc.lookAt(e),cc.updateMatrix(),this.applyMatrix4(cc.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Pr).negate(),this.translate(Pr.x,Pr.y,Pr.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let n=[];for(let i=0,r=e.length;i<r;i++){let s=e[i];n.push(s.x,s.y,s.z||0)}this.setAttribute("position",new tn(n,3))}else{let n=Math.min(e.length,t.count);for(let i=0;i<n;i++){let r=e[i];t.setXYZ(i,r.x,r.y,r.z||0)}if(e.length>t.count)Me("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.");t.needsUpdate=!0}return this}computeBoundingBox(){if(this.boundingBox===null)this.boundingBox=new Jt;let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ne("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new N(-1/0,-1/0,-1/0),new N(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n<i;n++){let r=t[n];if(an.setFromBufferAttribute(r),this.morphTargetsRelative)Ft.addVectors(this.boundingBox.min,an.min),this.boundingBox.expandByPoint(Ft),Ft.addVectors(this.boundingBox.max,an.max),this.boundingBox.expandByPoint(Ft);else this.boundingBox.expandByPoint(an.min),this.boundingBox.expandByPoint(an.max)}}else this.boundingBox.makeEmpty();if(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))Ne('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){if(this.boundingSphere===null)this.boundingSphere=new ln;let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ne("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new N,1/0);return}if(e){let n=this.boundingSphere.center;if(an.setFromBufferAttribute(e),t)for(let r=0,s=t.length;r<s;r++){let o=t[r];if(ls.setFromBufferAttribute(o),this.morphTargetsRelative)Ft.addVectors(an.min,ls.min),an.expandByPoint(Ft),Ft.addVectors(an.max,ls.max),an.expandByPoint(Ft);else an.expandByPoint(ls.min),an.expandByPoint(ls.max)}an.getCenter(n);let i=0;for(let r=0,s=e.count;r<s;r++)Ft.fromBufferAttribute(e,r),i=Math.max(i,n.distanceToSquared(Ft));if(t)for(let r=0,s=t.length;r<s;r++){let o=t[r],a=this.morphTargetsRelative;for(let c=0,l=o.count;c<l;c++){if(Ft.fromBufferAttribute(o,c),a)Pr.fromBufferAttribute(e,c),Ft.add(Pr);i=Math.max(i,n.distanceToSquared(Ft))}}if(this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius))Ne('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){Ne("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let{position:n,normal:i,uv:r}=t,s=this.getAttribute("tangent");if(s===void 0||s.count!==n.count)s=new It(new Float32Array(4*n.count),4),this.setAttribute("tangent",s);let o=[],a=[];for(let R=0;R<n.count;R++)o[R]=new N,a[R]=new N;let c=new N,l=new N,u=new N,f=new Pe,h=new Pe,d=new Pe,g=new N,b=new N;function p(R,_,S){c.fromBufferAttribute(n,R),l.fromBufferAttribute(n,_),u.fromBufferAttribute(n,S),f.fromBufferAttribute(r,R),h.fromBufferAttribute(r,_),d.fromBufferAttribute(r,S),l.sub(c),u.sub(c),h.sub(f),d.sub(f);let F=1/(h.x*d.y-d.x*h.y);if(!isFinite(F))return;g.copy(l).multiplyScalar(d.y).addScaledVector(u,-h.y).multiplyScalar(F),b.copy(u).multiplyScalar(h.x).addScaledVector(l,-d.x).multiplyScalar(F),o[R].add(g),o[_].add(g),o[S].add(g),a[R].add(b),a[_].add(b),a[S].add(b)}let m=this.groups;if(m.length===0)m=[{start:0,count:e.count}];for(let R=0,_=m.length;R<_;++R){let S=m[R],{start:F,count:C}=S;for(let z=F,J=F+C;z<J;z+=3)p(e.getX(z+0),e.getX(z+1),e.getX(z+2))}let A=new N,T=new N,v=new N,w=new N;function E(R){v.fromBufferAttribute(i,R),w.copy(v);let _=o[R];A.copy(_),A.sub(v.multiplyScalar(v.dot(_))).normalize(),T.crossVectors(w,_);let F=T.dot(a[R])<0?-1:1;s.setXYZW(R,A.x,A.y,A.z,F)}for(let R=0,_=m.length;R<_;++R){let S=m[R],{start:F,count:C}=S;for(let z=F,J=F+C;z<J;z+=3)E(e.getX(z+0)),E(e.getX(z+1)),E(e.getX(z+2))}this._transformed=!0}computeVertexNormals(){let e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0||n.count!==t.count)n=new It(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let f=0,h=n.count;f<h;f++)n.setXYZ(f,0,0,0);let i=new N,r=new N,s=new N,o=new N,a=new N,c=new N,l=new N,u=new N;if(e)for(let f=0,h=e.count;f<h;f+=3){let d=e.getX(f+0),g=e.getX(f+1),b=e.getX(f+2);i.fromBufferAttribute(t,d),r.fromBufferAttribute(t,g),s.fromBufferAttribute(t,b),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),o.fromBufferAttribute(n,d),a.fromBufferAttribute(n,g),c.fromBufferAttribute(n,b),o.add(l),a.add(l),c.add(l),n.setXYZ(d,o.x,o.y,o.z),n.setXYZ(g,a.x,a.y,a.z),n.setXYZ(b,c.x,c.y,c.z)}else for(let f=0,h=t.count;f<h;f+=3)i.fromBufferAttribute(t,f+0),r.fromBufferAttribute(t,f+1),s.fromBufferAttribute(t,f+2),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),n.setXYZ(f+0,l.x,l.y,l.z),n.setXYZ(f+1,l.x,l.y,l.z),n.setXYZ(f+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Ft.fromBufferAttribute(e,t),Ft.normalize(),e.setXYZ(t,Ft.x,Ft.y,Ft.z)}toNonIndexed(){function e(o,a){let{array:c,itemSize:l,normalized:u}=o,f=new c.constructor(a.length*l),h=0,d=0;for(let g=0,b=a.length;g<b;g++){if(o.isInterleavedBufferAttribute)h=a[g]*o.data.stride+o.offset;else h=a[g]*l;for(let p=0;p<l;p++)f[d++]=c[h++]}return new It(f,l,u)}if(this.index===null)return Me("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let t=new Kt,n=this.index.array,i=this.attributes;for(let o in i){let a=i[o],c=e(a,n);t.setAttribute(o,c)}let r=this.morphAttributes;for(let o in r){let a=[],c=r[o];for(let l=0,u=c.length;l<u;l++){let f=c[l],h=e(f,n);a.push(h)}t.morphAttributes[o]=a}t.morphTargetsRelative=this.morphTargetsRelative;let s=this.groups;for(let o=0,a=s.length;o<a;o++){let c=s[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.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!=="")e.name=this.name;if(Object.keys(this.userData).length>0)e.userData=this.userData;if(this.parameters!==void 0&&this._transformed!==!0){let a=this.parameters;for(let c in a)if(a[c]!==void 0)e[c]=a[c];return e}e.data={attributes:{}};let t=this.index;if(t!==null)e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)};let n=this.attributes;for(let a in n){let c=n[a];e.data.attributes[a]=c.toJSON(e.data)}let i={},r=!1;for(let a in this.morphAttributes){let c=this.morphAttributes[a],l=[];for(let u=0,f=c.length;u<f;u++){let h=c[u];l.push(h.toJSON(e.data))}if(l.length>0)i[a]=l,r=!0}if(r)e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative;let s=this.groups;if(s.length>0)e.data.groups=JSON.parse(JSON.stringify(s));let o=this.boundingSphere;if(o!==null)e.data.boundingSphere=o.toJSON();return 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;if(n!==null)this.setIndex(n.clone());let i=e.attributes;for(let c in i){let l=i[c];this.setAttribute(c,l.clone(t))}let r=e.morphAttributes;for(let c in r){let l=[],u=r[c];for(let f=0,h=u.length;f<h;f++)l.push(u[f].clone(t));this.morphAttributes[c]=l}this.morphTargetsRelative=e.morphTargetsRelative;let s=e.groups;for(let c=0,l=s.length;c<l;c++){let u=s[c];this.addGroup(u.start,u.count,u.materialIndex)}let o=e.boundingBox;if(o!==null)this.boundingBox=o.clone();let a=e.boundingSphere;if(a!==null)this.boundingSphere=a.clone();return this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Es{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=35044,this.updateRanges=[],this.version=0,this.uuid=Cn()}onUploadCallback(){}set needsUpdate(e){if(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 i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[n+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){if(e.arrayBuffers===void 0)e.arrayBuffers={};if(this.array.buffer._uuid===void 0)this.array.buffer._uuid=Cn();if(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){if(e.arrayBuffers===void 0)e.arrayBuffers={};if(this.array.buffer._uuid===void 0)this.array.buffer._uuid=Cn();if(e.arrayBuffers[this.array.buffer._uuid]===void 0)e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer));return{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}var jt=new N;class qr{constructor(e,t,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=i}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++)jt.fromBufferAttribute(this,t),jt.applyMatrix4(e),this.setXYZ(t,jt.x,jt.y,jt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)jt.fromBufferAttribute(this,t),jt.applyNormalMatrix(e),this.setXYZ(t,jt.x,jt.y,jt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)jt.fromBufferAttribute(this,t),jt.transformDirection(e),this.setXYZ(t,jt.x,jt.y,jt.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];if(this.normalized)n=Rn(n,this.array);return n}setComponent(e,t,n){if(this.normalized)n=nt(n,this.array);return this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){if(this.normalized)t=nt(t,this.array);return this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){if(this.normalized)t=nt(t,this.array);return this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){if(this.normalized)t=nt(t,this.array);return this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){if(this.normalized)t=nt(t,this.array);return 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];if(this.normalized)t=Rn(t,this.array);return t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];if(this.normalized)t=Rn(t,this.array);return t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];if(this.normalized)t=Rn(t,this.array);return t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];if(this.normalized)t=Rn(t,this.array);return t}setXY(e,t,n){if(e=e*this.data.stride+this.offset,this.normalized)t=nt(t,this.array),n=nt(n,this.array);return this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,i){if(e=e*this.data.stride+this.offset,this.normalized)t=nt(t,this.array),n=nt(n,this.array),i=nt(i,this.array);return this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this}setXYZW(e,t,n,i,r){if(e=e*this.data.stride+this.offset,this.normalized)t=nt(t,this.array),n=nt(n,this.array),i=nt(i,this.array),r=nt(r,this.array);return this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(e===void 0){gs("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[i+r])}return new It(new this.array.constructor(t),this.itemSize,this.normalized)}else{if(e.interleavedBuffers===void 0)e.interleavedBuffers={};if(e.interleavedBuffers[this.data.uuid]===void 0)e.interleavedBuffers[this.data.uuid]=this.data.clone(e);return new qr(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}}toJSON(e){if(e===void 0){gs("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let r=0;r<this.itemSize;r++)t.push(this.data.array[i+r])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else{if(e.interleavedBuffers===void 0)e.interleavedBuffers={};if(e.interleavedBuffers[this.data.uuid]===void 0)e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e);return{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}}var mx=0;class nn extends Nn{constructor(){super();this.isMaterial=!0,Object.defineProperty(this,"id",{value:mx++}),this.uuid=Cn(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Le(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=7680,this.stencilZFail=7680,this.stencilZPass=7680,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){if(this._alphaTest>0!==e>0)this.version++;this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e===void 0)return;for(let t in e){let n=e[t];if(n===void 0){Me(`Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){Me(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}if(i&&i.isColor)i.set(n);else if(i&&i.isVector2&&(n&&n.isVector2)||i&&i.isEuler&&(n&&n.isEuler)||i&&i.isVector3&&(n&&n.isVector3))i.copy(n);else this[t]=n}}toJSON(e){let t=e===void 0||typeof e==="string";if(t)e={textures:{},images:{}};let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};if(n.uuid=this.uuid,n.type=this.type,this.name!=="")n.name=this.name;if(this.color&&this.color.isColor)n.color=this.color.getHex();if(this.roughness!==void 0)n.roughness=this.roughness;if(this.metalness!==void 0)n.metalness=this.metalness;if(this.sheen!==void 0)n.sheen=this.sheen;if(this.sheenColor&&this.sheenColor.isColor)n.sheenColor=this.sheenColor.getHex();if(this.sheenRoughness!==void 0)n.sheenRoughness=this.sheenRoughness;if(this.emissive&&this.emissive.isColor)n.emissive=this.emissive.getHex();if(this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1)n.emissiveIntensity=this.emissiveIntensity;if(this.specular&&this.specular.isColor)n.specular=this.specular.getHex();if(this.specularIntensity!==void 0)n.specularIntensity=this.specularIntensity;if(this.specularColor&&this.specularColor.isColor)n.specularColor=this.specularColor.getHex();if(this.shininess!==void 0)n.shininess=this.shininess;if(this.clearcoat!==void 0)n.clearcoat=this.clearcoat;if(this.clearcoatRoughness!==void 0)n.clearcoatRoughness=this.clearcoatRoughness;if(this.clearcoatMap&&this.clearcoatMap.isTexture)n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid;if(this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture)n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid;if(this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture)n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray();if(this.sheenColorMap&&this.sheenColorMap.isTexture)n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid;if(this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture)n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid;if(this.dispersion!==void 0)n.dispersion=this.dispersion;if(this.iridescence!==void 0)n.iridescence=this.iridescence;if(this.iridescenceIOR!==void 0)n.iridescenceIOR=this.iridescenceIOR;if(this.iridescenceThicknessRange!==void 0)n.iridescenceThicknessRange=this.iridescenceThicknessRange;if(this.iridescenceMap&&this.iridescenceMap.isTexture)n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid;if(this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture)n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid;if(this.anisotropy!==void 0)n.anisotropy=this.anisotropy;if(this.anisotropyRotation!==void 0)n.anisotropyRotation=this.anisotropyRotation;if(this.anisotropyMap&&this.anisotropyMap.isTexture)n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid;if(this.map&&this.map.isTexture)n.map=this.map.toJSON(e).uuid;if(this.matcap&&this.matcap.isTexture)n.matcap=this.matcap.toJSON(e).uuid;if(this.alphaMap&&this.alphaMap.isTexture)n.alphaMap=this.alphaMap.toJSON(e).uuid;if(this.lightMap&&this.lightMap.isTexture)n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity;if(this.aoMap&&this.aoMap.isTexture)n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity;if(this.bumpMap&&this.bumpMap.isTexture)n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale;if(this.normalMap&&this.normalMap.isTexture)n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray();if(this.displacementMap&&this.displacementMap.isTexture)n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias;if(this.roughnessMap&&this.roughnessMap.isTexture)n.roughnessMap=this.roughnessMap.toJSON(e).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)n.metalnessMap=this.metalnessMap.toJSON(e).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)n.emissiveMap=this.emissiveMap.toJSON(e).uuid;if(this.specularMap&&this.specularMap.isTexture)n.specularMap=this.specularMap.toJSON(e).uuid;if(this.specularIntensityMap&&this.specularIntensityMap.isTexture)n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid;if(this.specularColorMap&&this.specularColorMap.isTexture)n.specularColorMap=this.specularColorMap.toJSON(e).uuid;if(this.envMap&&this.envMap.isTexture){if(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0)n.combine=this.combine}if(this.envMapRotation!==void 0)n.envMapRotation=this.envMapRotation.toArray();if(this.envMapIntensity!==void 0)n.envMapIntensity=this.envMapIntensity;if(this.reflectivity!==void 0)n.reflectivity=this.reflectivity;if(this.refractionRatio!==void 0)n.refractionRatio=this.refractionRatio;if(this.gradientMap&&this.gradientMap.isTexture)n.gradientMap=this.gradientMap.toJSON(e).uuid;if(this.transmission!==void 0)n.transmission=this.transmission;if(this.transmissionMap&&this.transmissionMap.isTexture)n.transmissionMap=this.transmissionMap.toJSON(e).uuid;if(this.thickness!==void 0)n.thickness=this.thickness;if(this.thicknessMap&&this.thicknessMap.isTexture)n.thicknessMap=this.thicknessMap.toJSON(e).uuid;if(this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0)n.attenuationDistance=this.attenuationDistance;if(this.attenuationColor!==void 0)n.attenuationColor=this.attenuationColor.getHex();if(this.size!==void 0)n.size=this.size;if(this.shadowSide!==null)n.shadowSide=this.shadowSide;if(this.sizeAttenuation!==void 0)n.sizeAttenuation=this.sizeAttenuation;if(this.blending!==1)n.blending=this.blending;if(this.side!==0)n.side=this.side;if(this.vertexColors===!0)n.vertexColors=!0;if(this.opacity<1)n.opacity=this.opacity;if(this.transparent===!0)n.transparent=!0;if(this.blendSrc!==204)n.blendSrc=this.blendSrc;if(this.blendDst!==205)n.blendDst=this.blendDst;if(this.blendEquation!==100)n.blendEquation=this.blendEquation;if(this.blendSrcAlpha!==null)n.blendSrcAlpha=this.blendSrcAlpha;if(this.blendDstAlpha!==null)n.blendDstAlpha=this.blendDstAlpha;if(this.blendEquationAlpha!==null)n.blendEquationAlpha=this.blendEquationAlpha;if(this.blendColor&&this.blendColor.isColor)n.blendColor=this.blendColor.getHex();if(this.blendAlpha!==0)n.blendAlpha=this.blendAlpha;if(this.depthFunc!==3)n.depthFunc=this.depthFunc;if(this.depthTest===!1)n.depthTest=this.depthTest;if(this.depthWrite===!1)n.depthWrite=this.depthWrite;if(this.colorWrite===!1)n.colorWrite=this.colorWrite;if(this.stencilWriteMask!==255)n.stencilWriteMask=this.stencilWriteMask;if(this.stencilFunc!==519)n.stencilFunc=this.stencilFunc;if(this.stencilRef!==0)n.stencilRef=this.stencilRef;if(this.stencilFuncMask!==255)n.stencilFuncMask=this.stencilFuncMask;if(this.stencilFail!==7680)n.stencilFail=this.stencilFail;if(this.stencilZFail!==7680)n.stencilZFail=this.stencilZFail;if(this.stencilZPass!==7680)n.stencilZPass=this.stencilZPass;if(this.stencilWrite===!0)n.stencilWrite=this.stencilWrite;if(this.rotation!==void 0&&this.rotation!==0)n.rotation=this.rotation;if(this.polygonOffset===!0)n.polygonOffset=!0;if(this.polygonOffsetFactor!==0)n.polygonOffsetFactor=this.polygonOffsetFactor;if(this.polygonOffsetUnits!==0)n.polygonOffsetUnits=this.polygonOffsetUnits;if(this.linewidth!==void 0&&this.linewidth!==1)n.linewidth=this.linewidth;if(this.dashSize!==void 0)n.dashSize=this.dashSize;if(this.gapSize!==void 0)n.gapSize=this.gapSize;if(this.scale!==void 0)n.scale=this.scale;if(this.dithering===!0)n.dithering=!0;if(this.alphaTest>0)n.alphaTest=this.alphaTest;if(this.alphaHash===!0)n.alphaHash=!0;if(this.alphaToCoverage===!0)n.alphaToCoverage=!0;if(this.premultipliedAlpha===!0)n.premultipliedAlpha=!0;if(this.forceSinglePass===!0)n.forceSinglePass=!0;if(this.allowOverride===!1)n.allowOverride=!1;if(this.wireframe===!0)n.wireframe=!0;if(this.wireframeLinewidth>1)n.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=="round")n.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=="round")n.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading===!0)n.flatShading=!0;if(this.visible===!1)n.visible=!1;if(this.toneMapped===!1)n.toneMapped=!1;if(this.fog===!1)n.fog=!1;if(Object.keys(this.userData).length>0)n.userData=this.userData;function i(r){let s=[];for(let o in r){let a=r[o];delete a.metadata,s.push(a)}return s}if(t){let r=i(e.textures),s=i(e.images);if(r.length>0)n.textures=r;if(s.length>0)n.images=s}return n}fromJSON(e,t){if(e.uuid!==void 0)this.uuid=e.uuid;if(e.name!==void 0)this.name=e.name;if(e.color!==void 0&&this.color!==void 0)this.color.setHex(e.color);if(e.roughness!==void 0)this.roughness=e.roughness;if(e.metalness!==void 0)this.metalness=e.metalness;if(e.sheen!==void 0)this.sheen=e.sheen;if(e.sheenColor!==void 0)this.sheenColor=new Le().setHex(e.sheenColor);if(e.sheenRoughness!==void 0)this.sheenRoughness=e.sheenRoughness;if(e.emissive!==void 0&&this.emissive!==void 0)this.emissive.setHex(e.emissive);if(e.specular!==void 0&&this.specular!==void 0)this.specular.setHex(e.specular);if(e.specularIntensity!==void 0)this.specularIntensity=e.specularIntensity;if(e.specularColor!==void 0&&this.specularColor!==void 0)this.specularColor.setHex(e.specularColor);if(e.shininess!==void 0)this.shininess=e.shininess;if(e.clearcoat!==void 0)this.clearcoat=e.clearcoat;if(e.clearcoatRoughness!==void 0)this.clearcoatRoughness=e.clearcoatRoughness;if(e.dispersion!==void 0)this.dispersion=e.dispersion;if(e.iridescence!==void 0)this.iridescence=e.iridescence;if(e.iridescenceIOR!==void 0)this.iridescenceIOR=e.iridescenceIOR;if(e.iridescenceThicknessRange!==void 0)this.iridescenceThicknessRange=e.iridescenceThicknessRange;if(e.transmission!==void 0)this.transmission=e.transmission;if(e.thickness!==void 0)this.thickness=e.thickness;if(e.attenuationDistance!==void 0)this.attenuationDistance=e.attenuationDistance;if(e.attenuationColor!==void 0&&this.attenuationColor!==void 0)this.attenuationColor.setHex(e.attenuationColor);if(e.anisotropy!==void 0)this.anisotropy=e.anisotropy;if(e.anisotropyRotation!==void 0)this.anisotropyRotation=e.anisotropyRotation;if(e.fog!==void 0)this.fog=e.fog;if(e.flatShading!==void 0)this.flatShading=e.flatShading;if(e.blending!==void 0)this.blending=e.blending;if(e.combine!==void 0)this.combine=e.combine;if(e.side!==void 0)this.side=e.side;if(e.shadowSide!==void 0)this.shadowSide=e.shadowSide;if(e.opacity!==void 0)this.opacity=e.opacity;if(e.transparent!==void 0)this.transparent=e.transparent;if(e.alphaTest!==void 0)this.alphaTest=e.alphaTest;if(e.alphaHash!==void 0)this.alphaHash=e.alphaHash;if(e.depthFunc!==void 0)this.depthFunc=e.depthFunc;if(e.depthTest!==void 0)this.depthTest=e.depthTest;if(e.depthWrite!==void 0)this.depthWrite=e.depthWrite;if(e.colorWrite!==void 0)this.colorWrite=e.colorWrite;if(e.blendSrc!==void 0)this.blendSrc=e.blendSrc;if(e.blendDst!==void 0)this.blendDst=e.blendDst;if(e.blendEquation!==void 0)this.blendEquation=e.blendEquation;if(e.blendSrcAlpha!==void 0)this.blendSrcAlpha=e.blendSrcAlpha;if(e.blendDstAlpha!==void 0)this.blendDstAlpha=e.blendDstAlpha;if(e.blendEquationAlpha!==void 0)this.blendEquationAlpha=e.blendEquationAlpha;if(e.blendColor!==void 0&&this.blendColor!==void 0)this.blendColor.setHex(e.blendColor);if(e.blendAlpha!==void 0)this.blendAlpha=e.blendAlpha;if(e.stencilWriteMask!==void 0)this.stencilWriteMask=e.stencilWriteMask;if(e.stencilFunc!==void 0)this.stencilFunc=e.stencilFunc;if(e.stencilRef!==void 0)this.stencilRef=e.stencilRef;if(e.stencilFuncMask!==void 0)this.stencilFuncMask=e.stencilFuncMask;if(e.stencilFail!==void 0)this.stencilFail=e.stencilFail;if(e.stencilZFail!==void 0)this.stencilZFail=e.stencilZFail;if(e.stencilZPass!==void 0)this.stencilZPass=e.stencilZPass;if(e.stencilWrite!==void 0)this.stencilWrite=e.stencilWrite;if(e.wireframe!==void 0)this.wireframe=e.wireframe;if(e.wireframeLinewidth!==void 0)this.wireframeLinewidth=e.wireframeLinewidth;if(e.wireframeLinecap!==void 0)this.wireframeLinecap=e.wireframeLinecap;if(e.wireframeLinejoin!==void 0)this.wireframeLinejoin=e.wireframeLinejoin;if(e.rotation!==void 0)this.rotation=e.rotation;if(e.linewidth!==void 0)this.linewidth=e.linewidth;if(e.dashSize!==void 0)this.dashSize=e.dashSize;if(e.gapSize!==void 0)this.gapSize=e.gapSize;if(e.scale!==void 0)this.scale=e.scale;if(e.polygonOffset!==void 0)this.polygonOffset=e.polygonOffset;if(e.polygonOffsetFactor!==void 0)this.polygonOffsetFactor=e.polygonOffsetFactor;if(e.polygonOffsetUnits!==void 0)this.polygonOffsetUnits=e.polygonOffsetUnits;if(e.dithering!==void 0)this.dithering=e.dithering;if(e.alphaToCoverage!==void 0)this.alphaToCoverage=e.alphaToCoverage;if(e.premultipliedAlpha!==void 0)this.premultipliedAlpha=e.premultipliedAlpha;if(e.forceSinglePass!==void 0)this.forceSinglePass=e.forceSinglePass;if(e.allowOverride!==void 0)this.allowOverride=e.allowOverride;if(e.visible!==void 0)this.visible=e.visible;if(e.toneMapped!==void 0)this.toneMapped=e.toneMapped;if(e.userData!==void 0)this.userData=e.userData;if(e.vertexColors!==void 0)if(typeof e.vertexColors==="number")this.vertexColors=e.vertexColors>0;else this.vertexColors=e.vertexColors;if(e.size!==void 0)this.size=e.size;if(e.sizeAttenuation!==void 0)this.sizeAttenuation=e.sizeAttenuation;if(e.map!==void 0)this.map=t[e.map]||null;if(e.matcap!==void 0)this.matcap=t[e.matcap]||null;if(e.alphaMap!==void 0)this.alphaMap=t[e.alphaMap]||null;if(e.bumpMap!==void 0)this.bumpMap=t[e.bumpMap]||null;if(e.bumpScale!==void 0)this.bumpScale=e.bumpScale;if(e.normalMap!==void 0)this.normalMap=t[e.normalMap]||null;if(e.normalMapType!==void 0)this.normalMapType=e.normalMapType;if(e.normalScale!==void 0){let n=e.normalScale;if(Array.isArray(n)===!1)n=[n,n];this.normalScale=new Pe().fromArray(n)}if(e.displacementMap!==void 0)this.displacementMap=t[e.displacementMap]||null;if(e.displacementScale!==void 0)this.displacementScale=e.displacementScale;if(e.displacementBias!==void 0)this.displacementBias=e.displacementBias;if(e.roughnessMap!==void 0)this.roughnessMap=t[e.roughnessMap]||null;if(e.metalnessMap!==void 0)this.metalnessMap=t[e.metalnessMap]||null;if(e.emissiveMap!==void 0)this.emissiveMap=t[e.emissiveMap]||null;if(e.emissiveIntensity!==void 0)this.emissiveIntensity=e.emissiveIntensity;if(e.specularMap!==void 0)this.specularMap=t[e.specularMap]||null;if(e.specularIntensityMap!==void 0)this.specularIntensityMap=t[e.specularIntensityMap]||null;if(e.specularColorMap!==void 0)this.specularColorMap=t[e.specularColorMap]||null;if(e.envMap!==void 0)this.envMap=t[e.envMap]||null;if(e.envMapRotation!==void 0)this.envMapRotation.fromArray(e.envMapRotation);if(e.envMapIntensity!==void 0)this.envMapIntensity=e.envMapIntensity;if(e.reflectivity!==void 0)this.reflectivity=e.reflectivity;if(e.refractionRatio!==void 0)this.refractionRatio=e.refractionRatio;if(e.lightMap!==void 0)this.lightMap=t[e.lightMap]||null;if(e.lightMapIntensity!==void 0)this.lightMapIntensity=e.lightMapIntensity;if(e.aoMap!==void 0)this.aoMap=t[e.aoMap]||null;if(e.aoMapIntensity!==void 0)this.aoMapIntensity=e.aoMapIntensity;if(e.gradientMap!==void 0)this.gradientMap=t[e.gradientMap]||null;if(e.clearcoatMap!==void 0)this.clearcoatMap=t[e.clearcoatMap]||null;if(e.clearcoatRoughnessMap!==void 0)this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null;if(e.clearcoatNormalMap!==void 0)this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null;if(e.clearcoatNormalScale!==void 0)this.clearcoatNormalScale=new Pe().fromArray(e.clearcoatNormalScale);if(e.iridescenceMap!==void 0)this.iridescenceMap=t[e.iridescenceMap]||null;if(e.iridescenceThicknessMap!==void 0)this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null;if(e.transmissionMap!==void 0)this.transmissionMap=t[e.transmissionMap]||null;if(e.thicknessMap!==void 0)this.thicknessMap=t[e.thicknessMap]||null;if(e.anisotropyMap!==void 0)this.anisotropyMap=t[e.anisotropyMap]||null;if(e.sheenColorMap!==void 0)this.sheenColorMap=t[e.sheenColorMap]||null;if(e.sheenRoughnessMap!==void 0)this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null;return this}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 i=t.length;n=Array(i);for(let r=0;r!==i;++r)n[r]=t[r].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){if(e===!0)this.version++}}var ai=new N,lc=new N,mo=new N,wi=new N,uc=new N,go=new N,hc=new N;class Ii{constructor(e=new N,t=new N(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,ai)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);if(n<0)return t.copy(this.origin);return t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=ai.subVectors(e,this.origin).dot(this.direction);if(t<0)return this.origin.distanceToSquared(e);return ai.copy(this.origin).addScaledVector(this.direction,t),ai.distanceToSquared(e)}distanceSqToSegment(e,t,n,i){lc.copy(e).add(t).multiplyScalar(0.5),mo.copy(t).sub(e).normalize(),wi.copy(this.origin).sub(lc);let r=e.distanceTo(t)*0.5,s=-this.direction.dot(mo),o=wi.dot(this.direction),a=-wi.dot(mo),c=wi.lengthSq(),l=Math.abs(1-s*s),u,f,h,d;if(l>0)if(u=s*a-o,f=s*o-a,d=r*l,u>=0)if(f>=-d)if(f<=d){let g=1/l;u*=g,f*=g,h=u*(u+s*f+2*o)+f*(s*u+f+2*a)+c}else f=r,u=Math.max(0,-(s*f+o)),h=-u*u+f*(f+2*a)+c;else f=-r,u=Math.max(0,-(s*f+o)),h=-u*u+f*(f+2*a)+c;else if(f<=-d)u=Math.max(0,-(-s*r+o)),f=u>0?-r:Math.min(Math.max(-r,-a),r),h=-u*u+f*(f+2*a)+c;else if(f<=d)u=0,f=Math.min(Math.max(-r,-a),r),h=f*(f+2*a)+c;else u=Math.max(0,-(s*r+o)),f=u>0?r:Math.min(Math.max(-r,-a),r),h=-u*u+f*(f+2*a)+c;else f=s>0?-r:r,u=Math.max(0,-(s*f+o)),h=-u*u+f*(f+2*a)+c;if(n)n.copy(this.origin).addScaledVector(this.direction,u);if(i)i.copy(lc).addScaledVector(mo,f);return h}intersectSphere(e,t){ai.subVectors(e.center,this.origin);let n=ai.dot(this.direction),i=ai.dot(ai)-n*n,r=e.radius*e.radius;if(i>r)return null;let s=Math.sqrt(r-i),o=n-s,a=n+s;if(a<0)return null;if(o<0)return this.at(a,t);return this.at(o,t)}intersectsSphere(e){if(e.radius<0)return!1;return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0){if(e.distanceToPoint(this.origin)===0)return 0;return null}let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);if(n===null)return null;return this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);if(t===0)return!0;if(e.normal.dot(this.direction)*t<0)return!0;return!1}intersectBox(e,t){let n,i,r,s,o,a,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,f=this.origin;if(c>=0)n=(e.min.x-f.x)*c,i=(e.max.x-f.x)*c;else n=(e.max.x-f.x)*c,i=(e.min.x-f.x)*c;if(l>=0)r=(e.min.y-f.y)*l,s=(e.max.y-f.y)*l;else r=(e.max.y-f.y)*l,s=(e.min.y-f.y)*l;if(n>s||r>i)return null;if(r>n||isNaN(n))n=r;if(s<i||isNaN(i))i=s;if(u>=0)o=(e.min.z-f.z)*u,a=(e.max.z-f.z)*u;else o=(e.max.z-f.z)*u,a=(e.min.z-f.z)*u;if(n>a||o>i)return null;if(o>n||n!==n)n=o;if(a<i||i!==i)i=a;if(i<0)return null;return this.at(n>=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,ai)!==null}intersectTriangle(e,t,n,i,r){uc.subVectors(t,e),go.subVectors(n,e),hc.crossVectors(uc,go);let s=this.direction.dot(hc),o;if(s>0){if(i)return null;o=1}else if(s<0)o=-1,s=-s;else return null;wi.subVectors(this.origin,e);let a=o*this.direction.dot(go.crossVectors(wi,go));if(a<0)return null;let c=o*this.direction.dot(uc.cross(wi));if(c<0)return null;if(a+c>s)return null;let l=-o*wi.dot(hc);if(l<0)return null;return this.at(l/s,r)}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)}}class Zn extends nn{constructor(e){super();this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Le(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 Hn,this.combine=0,this.reflectivity=1,this.refractionRatio=0.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}}var Mh=new Fe,Ji=new Ii,_o=new ln,wh=new N,xo=new N,vo=new N,yo=new N,fc=new N,bo=new N,Th=new N,So=new N;class dt extends ot{constructor(e=new Kt,t=new Zn){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){if(super.copy(e,t),e.morphTargetInfluences!==void 0)this.morphTargetInfluences=e.morphTargetInfluences.slice();if(e.morphTargetDictionary!==void 0)this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary);return 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 i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=i.length;r<s;r++){let o=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}getVertexPosition(e,t){let n=this.geometry,i=n.attributes.position,r=n.morphAttributes.position,s=n.morphTargetsRelative;t.fromBufferAttribute(i,e);let o=this.morphTargetInfluences;if(r&&o){bo.set(0,0,0);for(let a=0,c=r.length;a<c;a++){let l=o[a],u=r[a];if(l===0)continue;if(fc.fromBufferAttribute(u,e),s)bo.addScaledVector(fc,l);else bo.addScaledVector(fc.sub(t),l)}t.add(bo)}return t}raycast(e,t){let n=this.geometry,i=this.material,r=this.matrixWorld;if(i===void 0)return;if(n.boundingSphere===null)n.computeBoundingSphere();if(_o.copy(n.boundingSphere),_o.applyMatrix4(r),Ji.copy(e.ray).recast(e.near),_o.containsPoint(Ji.origin)===!1){if(Ji.intersectSphere(_o,wh)===null)return;if(Ji.origin.distanceToSquared(wh)>(e.far-e.near)**2)return}if(Mh.copy(r).invert(),Ji.copy(e.ray).applyMatrix4(Mh),n.boundingBox!==null){if(Ji.intersectsBox(n.boundingBox)===!1)return}this._computeIntersections(e,t,Ji)}_computeIntersections(e,t,n){let i,r=this.geometry,s=this.material,o=r.index,a=r.attributes.position,c=r.attributes.uv,l=r.attributes.uv1,u=r.attributes.normal,{groups:f,drawRange:h}=r;if(o!==null)if(Array.isArray(s))for(let d=0,g=f.length;d<g;d++){let b=f[d],p=s[b.materialIndex],m=Math.max(b.start,h.start),A=Math.min(o.count,Math.min(b.start+b.count,h.start+h.count));for(let T=m,v=A;T<v;T+=3){let w=o.getX(T),E=o.getX(T+1),R=o.getX(T+2);if(i=Mo(this,p,e,n,c,l,u,w,E,R),i)i.faceIndex=Math.floor(T/3),i.face.materialIndex=b.materialIndex,t.push(i)}}else{let d=Math.max(0,h.start),g=Math.min(o.count,h.start+h.count);for(let b=d,p=g;b<p;b+=3){let m=o.getX(b),A=o.getX(b+1),T=o.getX(b+2);if(i=Mo(this,s,e,n,c,l,u,m,A,T),i)i.faceIndex=Math.floor(b/3),t.push(i)}}else if(a!==void 0)if(Array.isArray(s))for(let d=0,g=f.length;d<g;d++){let b=f[d],p=s[b.materialIndex],m=Math.max(b.start,h.start),A=Math.min(a.count,Math.min(b.start+b.count,h.start+h.count));for(let T=m,v=A;T<v;T+=3){let w=T,E=T+1,R=T+2;if(i=Mo(this,p,e,n,c,l,u,w,E,R),i)i.faceIndex=Math.floor(T/3),i.face.materialIndex=b.materialIndex,t.push(i)}}else{let d=Math.max(0,h.start),g=Math.min(a.count,h.start+h.count);for(let b=d,p=g;b<p;b+=3){let m=b,A=b+1,T=b+2;if(i=Mo(this,s,e,n,c,l,u,m,A,T),i)i.faceIndex=Math.floor(b/3),t.push(i)}}}}function gx(e,t,n,i,r,s,o,a){let c;if(t.side===1)c=i.intersectTriangle(o,s,r,!0,a);else c=i.intersectTriangle(r,s,o,t.side===0,a);if(c===null)return null;So.copy(a),So.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(So);if(l<n.near||l>n.far)return null;return{distance:l,point:So.clone(),object:e}}function Mo(e,t,n,i,r,s,o,a,c,l){e.getVertexPosition(a,xo),e.getVertexPosition(c,vo),e.getVertexPosition(l,yo);let u=gx(e,t,n,i,xo,vo,yo,Th);if(u){let f=new N;if(xn.getBarycoord(Th,xo,vo,yo,f),r)u.uv=xn.getInterpolatedAttribute(r,a,c,l,f,new Pe);if(s)u.uv1=xn.getInterpolatedAttribute(s,a,c,l,f,new Pe);if(o){if(u.normal=xn.getInterpolatedAttribute(o,a,c,l,f,new N),u.normal.dot(i.direction)>0)u.normal.multiplyScalar(-1)}let h={a,b:c,c:l,normal:new N,materialIndex:0};xn.getNormal(xo,vo,yo,h.normal),u.face=h,u.barycoord=f}return u}var us=new it,Eh=new it,Ah=new it,_x=new it,Rh=new Fe,wo=new N,dc=new ln,Ch=new Fe,pc=new Ii;class Qo extends dt{constructor(e,t){super(e,t);this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new Fe,this.bindMatrixInverse=new Fe,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;if(this.boundingBox===null)this.boundingBox=new Jt;this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,wo),this.boundingBox.expandByPoint(wo)}computeBoundingSphere(){let e=this.geometry;if(this.boundingSphere===null)this.boundingSphere=new ln;this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,wo),this.boundingSphere.expandByPoint(wo)}copy(e,t){if(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();if(e.boundingSphere!==null)this.boundingSphere=e.boundingSphere.clone();return this}raycast(e,t){let n=this.material,i=this.matrixWorld;if(n===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(dc.copy(this.boundingSphere),dc.applyMatrix4(i),e.ray.intersectsSphere(dc)===!1)return;if(Ch.copy(i).invert(),pc.copy(e.ray).applyMatrix4(Ch),this.boundingBox!==null){if(pc.intersectsBox(this.boundingBox)===!1)return}this._computeIntersections(e,t,pc)}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){if(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 it,t=this.geometry.attributes.skinWeight;for(let n=0,i=t.count;n<i;n++){e.fromBufferAttribute(t,n);let r=1/e.manhattanLength();if(r!==1/0)e.multiplyScalar(r);else e.set(1,0,0,0);t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){if(super.updateMatrixWorld(e),this.bindMode==="attached")this.bindMatrixInverse.copy(this.matrixWorld).invert();else if(this.bindMode==="detached")this.bindMatrixInverse.copy(this.bindMatrix).invert();else Me("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,i=this.geometry;if(Eh.fromBufferAttribute(i.attributes.skinIndex,e),Ah.fromBufferAttribute(i.attributes.skinWeight,e),t.isVector4)us.copy(t),t.set(0,0,0,0);else us.set(...t,1),t.set(0,0,0);us.applyMatrix4(this.bindMatrix);for(let r=0;r<4;r++){let s=Ah.getComponent(r);if(s!==0){let o=Eh.getComponent(r);Rh.multiplyMatrices(n.bones[o].matrixWorld,n.boneInverses[o]),t.addScaledVector(_x.copy(us).applyMatrix4(Rh),s)}}if(t.isVector4)t.w=us.w;return t.applyMatrix4(this.bindMatrixInverse)}}class As extends ot{constructor(){super();this.isBone=!0,this.type="Bone"}}class Rs extends St{constructor(e=null,t=1,n=1,i,r,s,o,a,c=1003,l=1003,u,f){super(null,s,o,a,c,l,i,r,u,f);this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}var Ph=new Fe,xx=new Fe;class Cs{constructor(e=[],t=[]){this.uuid=Cn(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=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){Me("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let n=0,i=this.bones.length;n<i;n++)this.boneInverses.push(new Fe)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let n=new Fe;if(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];if(n)n.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){let n=this.bones[e];if(n){if(n.parent&&n.parent.isBone)n.matrix.copy(n.parent.matrixWorld).invert(),n.matrix.multiply(n.matrixWorld);else 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,i=this.boneTexture;for(let r=0,s=e.length;r<s;r++){let o=e[r]?e[r].matrixWorld:xx;Ph.multiplyMatrices(o,t[r]),Ph.toArray(n,r*16)}if(i!==null)i.needsUpdate=!0}clone(){return new Cs(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 Rs(t,e,e,1023,1015);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 i=this.bones[t];if(i.name===e)return i}return}dispose(){if(this.boneTexture!==null)this.boneTexture.dispose(),this.boneTexture=null}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,i=e.bones.length;n<i;n++){let r=e.bones[n],s=t[r];if(s===void 0)Me("Skeleton: No bone found with UUID:",r),s=new As;this.bones.push(s),this.boneInverses.push(new Fe().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 i=0,r=t.length;i<r;i++){let s=t[i];e.bones.push(s.uuid);let o=n[i];e.boneInverses.push(o.toArray())}return e}}class tr extends It{constructor(e,t,n,i=1){super(e,t,n);this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}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}}var Ir=new Fe,Ih=new Fe,To=[],Lh=new Jt,vx=new Fe,hs=new dt,fs=new ln;class Yr extends dt{constructor(e,t,n){super(e,t);this.isInstancedMesh=!0,this.instanceMatrix=new tr(new Float32Array(n*16),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let i=0;i<n;i++)this.setMatrixAt(i,vx)}computeBoundingBox(){let e=this.geometry,t=this.count;if(this.boundingBox===null)this.boundingBox=new Jt;if(e.boundingBox===null)e.computeBoundingBox();this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Ir),Lh.copy(e.boundingBox).applyMatrix4(Ir),this.boundingBox.union(Lh)}computeBoundingSphere(){let e=this.geometry,t=this.count;if(this.boundingSphere===null)this.boundingSphere=new ln;if(e.boundingSphere===null)e.computeBoundingSphere();this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Ir),fs.copy(e.boundingSphere).applyMatrix4(Ir),this.boundingSphere.union(fs)}copy(e,t){if(super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null)this.morphTexture=e.morphTexture.clone();if(e.instanceColor!==null)this.instanceColor=e.instanceColor.clone();if(this.count=e.count,e.boundingBox!==null)this.boundingBox=e.boundingBox.clone();if(e.boundingSphere!==null)this.boundingSphere=e.boundingSphere.clone();return this}getColorAt(e,t){if(this.instanceColor===null)return t.setRGB(1,1,1);else return 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,i=this.morphTexture.source.data.data,r=n.length+1,s=e*r+1;for(let o=0;o<n.length;o++)n[o]=i[s+o]}raycast(e,t){let n=this.matrixWorld,i=this.count;if(hs.geometry=this.geometry,hs.material=this.material,hs.material===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(fs.copy(this.boundingSphere),fs.applyMatrix4(n),e.ray.intersectsSphere(fs)===!1)return;for(let r=0;r<i;r++){this.getMatrixAt(r,Ir),Ih.multiplyMatrices(n,Ir),hs.matrixWorld=Ih,hs.raycast(e,To);for(let s=0,o=To.length;s<o;s++){let a=To[s];a.instanceId=r,a.object=this,t.push(a)}To.length=0}}setColorAt(e,t){if(this.instanceColor===null)this.instanceColor=new tr(new Float32Array(this.instanceMatrix.count*3).fill(1),3);return 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,i=n.length+1;if(this.morphTexture===null)this.morphTexture=new Rs(new Float32Array(i*this.count),i,this.count,1028,1015);let r=this.morphTexture.source.data.data,s=0;for(let c=0;c<n.length;c++)s+=n[c];let o=this.geometry.morphTargetsRelative?1:1-s,a=i*e;return r[a]=o,r.set(n,a+1),this}updateMorphTargets(){}dispose(){if(this.dispatchEvent({type:"dispose"}),this.morphTexture!==null)this.morphTexture.dispose(),this.morphTexture=null}}var mc=new N,yx=new N,bx=new De;class An{constructor(e=new N(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,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let i=mc.subVectors(n,t).cross(yx.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,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 i=e.delta(mc),r=this.normal.dot(i);if(r===0){if(this.distanceToPoint(e.start)===0)return t.copy(e.start);return null}let s=-(e.start.dot(this.normal)+this.constant)/r;if(n===!0&&(s<0||s>1))return null;return t.copy(e.start).addScaledVector(i,s)}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||bx.getNormalMatrix(e),i=this.coplanarPoint(mc).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),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)}}var Ki=new ln,Sx=new Pe(0.5,0.5),Eo=new N;class Ps{constructor(e=new An,t=new An,n=new An,i=new An,r=new An,s=new An){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(i),o[4].copy(r),o[5].copy(s),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=2000,n=!1){let i=this.planes,r=e.elements,s=r[0],o=r[1],a=r[2],c=r[3],l=r[4],u=r[5],f=r[6],h=r[7],d=r[8],g=r[9],b=r[10],p=r[11],m=r[12],A=r[13],T=r[14],v=r[15];if(i[0].setComponents(c-s,h-l,p-d,v-m).normalize(),i[1].setComponents(c+s,h+l,p+d,v+m).normalize(),i[2].setComponents(c+o,h+u,p+g,v+A).normalize(),i[3].setComponents(c-o,h-u,p-g,v-A).normalize(),n)i[4].setComponents(a,f,b,T).normalize(),i[5].setComponents(c-a,h-f,p-b,v-T).normalize();else if(i[4].setComponents(c-a,h-f,p-b,v-T).normalize(),t===2000)i[5].setComponents(c+a,h+f,p+b,v+T).normalize();else if(t===2001)i[5].setComponents(a,f,b,T).normalize();else throw Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0){if(e.boundingSphere===null)e.computeBoundingSphere();Ki.copy(e.boundingSphere).applyMatrix4(e.matrixWorld)}else{let t=e.geometry;if(t.boundingSphere===null)t.computeBoundingSphere();Ki.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ki)}intersectsSprite(e){Ki.center.set(0,0,0);let t=Sx.distanceTo(e.center);return Ki.radius=0.7071067811865476+t,Ki.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ki)}intersectsSphere(e){let t=this.planes,n=e.center,i=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<i)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let i=t[n];if(Eo.x=i.normal.x>0?e.max.x:e.min.x,Eo.y=i.normal.y>0?e.max.y:e.min.y,Eo.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Eo)<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)}}class Is extends nn{constructor(e){super();this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Le(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}}var Do=new N,Uo=new N,Nh=new Fe,ds=new Ii,Ao=new ln,gc=new N,Dh=new N;class Li extends ot{constructor(e=new Kt,t=new Is){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 i=1,r=t.count;i<r;i++)Do.fromBufferAttribute(t,i-1),Uo.fromBufferAttribute(t,i),n[i]=n[i-1],n[i]+=Do.distanceTo(Uo);e.setAttribute("lineDistance",new tn(n,1))}else Me("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){let n=this.geometry,i=this.matrixWorld,r=e.params.Line.threshold,s=n.drawRange;if(n.boundingSphere===null)n.computeBoundingSphere();if(Ao.copy(n.boundingSphere),Ao.applyMatrix4(i),Ao.radius+=r,e.ray.intersectsSphere(Ao)===!1)return;Nh.copy(i).invert(),ds.copy(e.ray).applyMatrix4(Nh);let o=r/((this.scale.x+this.scale.y+this.scale.z)/3),a=o*o,c=this.isLineSegments?2:1,l=n.index,f=n.attributes.position;if(l!==null){let h=Math.max(0,s.start),d=Math.min(l.count,s.start+s.count);for(let g=h,b=d-1;g<b;g+=c){let p=l.getX(g),m=l.getX(g+1),A=Ro(this,e,ds,a,p,m,g);if(A)t.push(A)}if(this.isLineLoop){let g=l.getX(d-1),b=l.getX(h),p=Ro(this,e,ds,a,g,b,d-1);if(p)t.push(p)}}else{let h=Math.max(0,s.start),d=Math.min(f.count,s.start+s.count);for(let g=h,b=d-1;g<b;g+=c){let p=Ro(this,e,ds,a,g,g+1,g);if(p)t.push(p)}if(this.isLineLoop){let g=Ro(this,e,ds,a,d-1,h,d-1);if(g)t.push(g)}}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=i.length;r<s;r++){let o=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function Ro(e,t,n,i,r,s,o){let a=e.geometry.attributes.position;if(Do.fromBufferAttribute(a,r),Uo.fromBufferAttribute(a,s),n.distanceSqToSegment(Do,Uo,gc,Dh)>i)return;gc.applyMatrix4(e.matrixWorld);let l=t.ray.origin.distanceTo(gc);if(l<t.near||l>t.far)return;return{distance:l,point:Dh.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var Uh=new N,Oh=new N;class ea extends Li{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 i=0,r=t.count;i<r;i+=2)Uh.fromBufferAttribute(t,i),Oh.fromBufferAttribute(t,i+1),n[i]=i===0?0:n[i-1],n[i+1]=n[i]+Uh.distanceTo(Oh);e.setAttribute("lineDistance",new tn(n,1))}else Me("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class ta extends Li{constructor(e,t){super(e,t);this.isLineLoop=!0,this.type="LineLoop"}}class Ls extends nn{constructor(e){super();this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Le(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}}var Fh=new Fe,vc=new Ii,Co=new ln,Po=new N;class jr extends ot{constructor(e=new Kt,t=new Ls){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,i=this.matrixWorld,r=e.params.Points.threshold,s=n.drawRange;if(n.boundingSphere===null)n.computeBoundingSphere();if(Co.copy(n.boundingSphere),Co.applyMatrix4(i),Co.radius+=r,e.ray.intersectsSphere(Co)===!1)return;Fh.copy(i).invert(),vc.copy(e.ray).applyMatrix4(Fh);let o=r/((this.scale.x+this.scale.y+this.scale.z)/3),a=o*o,c=n.index,u=n.attributes.position;if(c!==null){let f=Math.max(0,s.start),h=Math.min(c.count,s.start+s.count);for(let d=f,g=h;d<g;d++){let b=c.getX(d);Po.fromBufferAttribute(u,b),zh(Po,b,a,i,e,t,this)}}else{let f=Math.max(0,s.start),h=Math.min(u.count,s.start+s.count);for(let d=f,g=h;d<g;d++)Po.fromBufferAttribute(u,d),zh(Po,d,a,i,e,t,this)}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,s=i.length;r<s;r++){let o=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}}function zh(e,t,n,i,r,s,o){let a=vc.distanceSqToPoint(e);if(a<n){let c=new N;vc.closestPointToPoint(e,c),c.applyMatrix4(i);let l=r.ray.origin.distanceTo(c);if(l<r.near||l>r.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}class na extends St{constructor(e=[],t=301,n,i,r,s,o,a,c,l){super(e,t,n,i,r,s,o,a,c,l);this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Ni extends St{constructor(e,t,n=1014,i,r,s,o=1003,a=1003,c,l=1026,u=1){if(l!==1026&&l!==1027)throw Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let f={width:e,height:t,depth:u};super(f,i,r,s,o,a,l,n,c);this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ws(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);if(this.compareFunction!==null)t.compareFunction=this.compareFunction;return t}}class Ml extends Ni{constructor(e,t=1014,n=301,i,r,s=1003,o=1003,a,c=1026){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,i,r,s,o,a,c);this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class ia extends St{constructor(e=null){super();this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Di extends Kt{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super();this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};let o=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);let a=[],c=[],l=[],u=[],f=0,h=0;d("z","y","x",-1,-1,n,t,e,s,r,0),d("z","y","x",1,-1,n,t,-e,s,r,1),d("x","z","y",1,1,e,n,t,i,s,2),d("x","z","y",1,-1,e,n,-t,i,s,3),d("x","y","z",1,-1,e,t,n,i,r,4),d("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(a),this.setAttribute("position",new tn(c,3)),this.setAttribute("normal",new tn(l,3)),this.setAttribute("uv",new tn(u,2));function d(g,b,p,m,A,T,v,w,E,R,_){let S=T/E,F=v/R,C=T/2,z=v/2,J=w/2,O=E+1,H=R+1,V=0,U=0,K=new N;for(let Q=0;Q<H;Q++){let se=Q*F-z;for(let me=0;me<O;me++){let _e=me*S-C;K[g]=_e*m,K[b]=se*A,K[p]=J,c.push(K.x,K.y,K.z),K[g]=0,K[b]=0,K[p]=w>0?1:-1,l.push(K.x,K.y,K.z),u.push(me/E),u.push(1-Q/R),V+=1}}for(let Q=0;Q<R;Q++)for(let se=0;se<E;se++){let me=f+se+O*Q,_e=f+se+O*(Q+1),Xe=f+(se+1)+O*(Q+1),Be=f+(se+1)+O*Q;a.push(me,_e,Be),a.push(_e,Xe,Be),U+=6}o.addGroup(h,U,_),h+=U,f+=V}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Di(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Ns extends Kt{constructor(e=1,t=1,n=1,i=1){super();this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};let r=e/2,s=t/2,o=Math.floor(n),a=Math.floor(i),c=o+1,l=a+1,u=e/o,f=t/a,h=[],d=[],g=[],b=[];for(let p=0;p<l;p++){let m=p*f-s;for(let A=0;A<c;A++){let T=A*u-r;d.push(T,-m,0),g.push(0,0,1),b.push(A/o),b.push(1-p/a)}}for(let p=0;p<a;p++)for(let m=0;m<o;m++){let A=m+c*p,T=m+c*(p+1),v=m+1+c*(p+1),w=m+1+c*p;h.push(A,T,w),h.push(T,v,w)}this.setIndex(h),this.setAttribute("position",new tn(d,3)),this.setAttribute("normal",new tn(g,3)),this.setAttribute("uv",new tn(b,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ns(e.width,e.height,e.widthSegments,e.heightSegments)}}function cr(e){let t={};for(let n in e){t[n]={};for(let i in e[n]){let r=e[n][i];if(kh(r))if(r.isRenderTargetTexture)Me("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[n][i]=null;else t[n][i]=r.clone();else if(Array.isArray(r))if(kh(r[0])){let s=[];for(let o=0,a=r.length;o<a;o++)s[o]=r[o].clone();t[n][i]=s}else t[n][i]=r.slice();else t[n][i]=r}}return t}function qt(e){let t={};for(let n=0;n<e.length;n++){let i=cr(e[n]);for(let r in i)t[r]=i[r]}return t}function kh(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function Mx(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function wl(e){let t=e.getRenderTarget();if(t===null)return e.outputColorSpace;if(t.isXRRenderTarget===!0)return t.texture.colorSpace;return Ve.workingColorSpace}var Zf={clone:cr,merge:qt},wx=`void main() {gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );-}`,nF=`void main() {+}`,Tx=`void main() {gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );-}`;class gU extends EU{constructor($){super();if(this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=cF,this.fragmentShader=nF,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,$!==void 0)this.setValues($)}copy($){return super.copy($),this.fragmentShader=$.fragmentShader,this.vertexShader=$.vertexShader,this.uniforms=v0($.uniforms),this.uniformsGroups=dF($.uniformsGroups),this.defines=Object.assign({},$.defines),this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this.fog=$.fog,this.lights=$.lights,this.clipping=$.clipping,this.extensions=Object.assign({},$.extensions),this.glslVersion=$.glslVersion,this.defaultAttributeValues=Object.assign({},$.defaultAttributeValues),this.index0AttributeName=$.index0AttributeName,this.uniformsNeedUpdate=$.uniformsNeedUpdate,this}toJSON($){let U=super.toJSON($);U.glslVersion=this.glslVersion,U.uniforms={};for(let Q in this.uniforms){let K=this.uniforms[Q].value;if(K&&K.isTexture)U.uniforms[Q]={type:"t",value:K.toJSON($).uuid};else if(K&&K.isColor)U.uniforms[Q]={type:"c",value:K.getHex()};else if(K&&K.isVector2)U.uniforms[Q]={type:"v2",value:K.toArray()};else if(K&&K.isVector3)U.uniforms[Q]={type:"v3",value:K.toArray()};else if(K&&K.isVector4)U.uniforms[Q]={type:"v4",value:K.toArray()};else if(K&&K.isMatrix3)U.uniforms[Q]={type:"m3",value:K.toArray()};else if(K&&K.isMatrix4)U.uniforms[Q]={type:"m4",value:K.toArray()};else U.uniforms[Q]={value:K}}if(Object.keys(this.defines).length>0)U.defines=this.defines;U.vertexShader=this.vertexShader,U.fragmentShader=this.fragmentShader,U.lights=this.lights,U.clipping=this.clipping;let J={};for(let Q in this.extensions)if(this.extensions[Q]===!0)J[Q]=!0;if(Object.keys(J).length>0)U.extensions=J;return U}fromJSON($,U){if(super.fromJSON($,U),$.uniforms!==void 0)for(let J in $.uniforms){let Q=$.uniforms[J];switch(this.uniforms[J]={},Q.type){case"t":this.uniforms[J].value=U[Q.value]||null;break;case"c":this.uniforms[J].value=new y$().setHex(Q.value);break;case"v2":this.uniforms[J].value=new g$().fromArray(Q.value);break;case"v3":this.uniforms[J].value=new j().fromArray(Q.value);break;case"v4":this.uniforms[J].value=new E6().fromArray(Q.value);break;case"m3":this.uniforms[J].value=new f$().fromArray(Q.value);break;case"m4":this.uniforms[J].value=new m$().fromArray(Q.value);break;default:this.uniforms[J].value=Q.value}}if($.defines!==void 0)this.defines=$.defines;if($.vertexShader!==void 0)this.vertexShader=$.vertexShader;if($.fragmentShader!==void 0)this.fragmentShader=$.fragmentShader;if($.glslVersion!==void 0)this.glslVersion=$.glslVersion;if($.extensions!==void 0)for(let J in $.extensions)this.extensions[J]=$.extensions[J];if($.lights!==void 0)this.lights=$.lights;if($.clipping!==void 0)this.clipping=$.clipping;return this}}class YH extends gU{constructor($){super($);this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class SJ extends EU{constructor($){super();this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new y$(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 y$(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new g$(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 UJ,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues($)}copy($){return super.copy($),this.defines={STANDARD:""},this.color.copy($.color),this.roughness=$.roughness,this.metalness=$.metalness,this.map=$.map,this.lightMap=$.lightMap,this.lightMapIntensity=$.lightMapIntensity,this.aoMap=$.aoMap,this.aoMapIntensity=$.aoMapIntensity,this.emissive.copy($.emissive),this.emissiveMap=$.emissiveMap,this.emissiveIntensity=$.emissiveIntensity,this.bumpMap=$.bumpMap,this.bumpScale=$.bumpScale,this.normalMap=$.normalMap,this.normalMapType=$.normalMapType,this.normalScale.copy($.normalScale),this.displacementMap=$.displacementMap,this.displacementScale=$.displacementScale,this.displacementBias=$.displacementBias,this.roughnessMap=$.roughnessMap,this.metalnessMap=$.metalnessMap,this.alphaMap=$.alphaMap,this.envMap=$.envMap,this.envMapRotation.copy($.envMapRotation),this.envMapIntensity=$.envMapIntensity,this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this.wireframeLinecap=$.wireframeLinecap,this.wireframeLinejoin=$.wireframeLinejoin,this.flatShading=$.flatShading,this.fog=$.fog,this}}class wU extends SJ{constructor($){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 g$(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return a$(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(U){this.ior=(1+0.4*U)/(1-0.4*U)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new y$(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 y$(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new y$(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($)}get anisotropy(){return this._anisotropy}set anisotropy($){if(this._anisotropy>0!==$>0)this.version++;this._anisotropy=$}get clearcoat(){return this._clearcoat}set clearcoat($){if(this._clearcoat>0!==$>0)this.version++;this._clearcoat=$}get iridescence(){return this._iridescence}set iridescence($){if(this._iridescence>0!==$>0)this.version++;this._iridescence=$}get dispersion(){return this._dispersion}set dispersion($){if(this._dispersion>0!==$>0)this.version++;this._dispersion=$}get sheen(){return this._sheen}set sheen($){if(this._sheen>0!==$>0)this.version++;this._sheen=$}get transmission(){return this._transmission}set transmission($){if(this._transmission>0!==$>0)this.version++;this._transmission=$}copy($){return super.copy($),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=$.anisotropy,this.anisotropyRotation=$.anisotropyRotation,this.anisotropyMap=$.anisotropyMap,this.clearcoat=$.clearcoat,this.clearcoatMap=$.clearcoatMap,this.clearcoatRoughness=$.clearcoatRoughness,this.clearcoatRoughnessMap=$.clearcoatRoughnessMap,this.clearcoatNormalMap=$.clearcoatNormalMap,this.clearcoatNormalScale.copy($.clearcoatNormalScale),this.dispersion=$.dispersion,this.ior=$.ior,this.iridescence=$.iridescence,this.iridescenceMap=$.iridescenceMap,this.iridescenceIOR=$.iridescenceIOR,this.iridescenceThicknessRange=[...$.iridescenceThicknessRange],this.iridescenceThicknessMap=$.iridescenceThicknessMap,this.sheen=$.sheen,this.sheenColor.copy($.sheenColor),this.sheenColorMap=$.sheenColorMap,this.sheenRoughness=$.sheenRoughness,this.sheenRoughnessMap=$.sheenRoughnessMap,this.transmission=$.transmission,this.transmissionMap=$.transmissionMap,this.thickness=$.thickness,this.thicknessMap=$.thicknessMap,this.attenuationDistance=$.attenuationDistance,this.attenuationColor.copy($.attenuationColor),this.specularIntensity=$.specularIntensity,this.specularIntensityMap=$.specularIntensityMap,this.specularColor.copy($.specularColor),this.specularColorMap=$.specularColorMap,this}}class T9 extends EU{constructor($){super();this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new y$(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new y$(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new g$(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new UJ,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues($)}copy($){return super.copy($),this.color.copy($.color),this.map=$.map,this.lightMap=$.lightMap,this.lightMapIntensity=$.lightMapIntensity,this.aoMap=$.aoMap,this.aoMapIntensity=$.aoMapIntensity,this.emissive.copy($.emissive),this.emissiveMap=$.emissiveMap,this.emissiveIntensity=$.emissiveIntensity,this.bumpMap=$.bumpMap,this.bumpScale=$.bumpScale,this.normalMap=$.normalMap,this.normalMapType=$.normalMapType,this.normalScale.copy($.normalScale),this.displacementMap=$.displacementMap,this.displacementScale=$.displacementScale,this.displacementBias=$.displacementBias,this.specularMap=$.specularMap,this.alphaMap=$.alphaMap,this.envMap=$.envMap,this.envMapRotation.copy($.envMapRotation),this.combine=$.combine,this.reflectivity=$.reflectivity,this.envMapIntensity=$.envMapIntensity,this.refractionRatio=$.refractionRatio,this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this.wireframeLinecap=$.wireframeLinecap,this.wireframeLinejoin=$.wireframeLinejoin,this.flatShading=$.flatShading,this.fog=$.fog,this}}class GH extends EU{constructor($){super();this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues($)}copy($){return super.copy($),this.depthPacking=$.depthPacking,this.map=$.map,this.alphaMap=$.alphaMap,this.displacementMap=$.displacementMap,this.displacementScale=$.displacementScale,this.displacementBias=$.displacementBias,this.wireframe=$.wireframe,this.wireframeLinewidth=$.wireframeLinewidth,this}}class OH extends EU{constructor($){super();this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues($)}copy($){return super.copy($),this.map=$.map,this.alphaMap=$.alphaMap,this.displacementMap=$.displacementMap,this.displacementScale=$.displacementScale,this.displacementBias=$.displacementBias,this}}function Q9($,U){if(!$||$.constructor===U)return $;if(typeof U.BYTES_PER_ELEMENT==="number")return new U($);return Array.prototype.slice.call($)}function iF($){function U(W,K){return $[W]-$[K]}let J=$.length,Q=Array(J);for(let W=0;W!==J;++W)Q[W]=W;return Q.sort(U),Q}function ck($,U,J){let Q=$.length,W=new $.constructor(Q);for(let K=0,X=0;X!==Q;++K){let H=J[K]*U;for(let N=0;N!==U;++N)W[X++]=$[H+N]}return W}function oF($,U,J,Q){let W=1,K=$[0];while(K!==void 0&&K[Q]===void 0)K=$[W++];if(K===void 0)return;let X=K[Q];if(X===void 0)return;if(Array.isArray(X))do{if(X=K[Q],X!==void 0)U.push(K.time),J.push(...X);K=$[W++]}while(K!==void 0);else if(X.toArray!==void 0)do{if(X=K[Q],X!==void 0)U.push(K.time),X.toArray(J,J.length);K=$[W++]}while(K!==void 0);else do{if(X=K[Q],X!==void 0)U.push(K.time),J.push(X);K=$[W++]}while(K!==void 0)}class TJ{constructor($,U,J,Q){this.parameterPositions=$,this._cachedIndex=0,this.resultBuffer=Q!==void 0?Q:new U.constructor(J),this.sampleValues=U,this.valueSize=J,this.settings=null,this.DefaultSettings_={}}evaluate($){let U=this.parameterPositions,J=this._cachedIndex,Q=U[J],W=U[J-1];$:{U:{let K;J:{W:if(!($<Q)){for(let X=J+2;;){if(Q===void 0){if($<W)break W;return J=U.length,this._cachedIndex=J,this.copySampleValue_(J-1)}if(J===X)break;if(W=Q,Q=U[++J],$<Q)break U}K=U.length;break J}if(!($>=W)){let X=U[1];if($<X)J=2,W=X;for(let H=J-2;;){if(W===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(J===H)break;if(Q=W,W=U[--J-1],$>=W)break U}K=J,J=0;break J}break $}while(J<K){let X=J+K>>>1;if($<U[X])K=X;else J=X+1}if(Q=U[J],W=U[J-1],W===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(Q===void 0)return J=U.length,this._cachedIndex=J,this.copySampleValue_(J-1)}this._cachedIndex=J,this.intervalChanged_(J,W,Q)}return this.interpolate_(J,W,$,Q)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_($){let U=this.resultBuffer,J=this.sampleValues,Q=this.valueSize,W=$*Q;for(let K=0;K!==Q;++K)U[K]=J[W+K];return U}interpolate_(){throw Error("THREE.Interpolant: Call to abstract method.")}intervalChanged_(){}}class EH extends TJ{constructor($,U,J,Q){super($,U,J,Q);this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:2400,endingEnd:2400}}intervalChanged_($,U,J){let Q=this.parameterPositions,W=$-2,K=$+1,X=Q[W],H=Q[K];if(X===void 0)switch(this.getSettings_().endingStart){case 2401:W=$,X=2*U-J;break;case 2402:W=Q.length-2,X=U+Q[W]-Q[W+1];break;default:W=$,X=J}if(H===void 0)switch(this.getSettings_().endingEnd){case 2401:K=$,H=2*J-U;break;case 2402:K=1,H=J+Q[1]-Q[0];break;default:K=$-1,H=U}let N=(J-U)*0.5,Y=this.valueSize;this._weightPrev=N/(U-X),this._weightNext=N/(H-J),this._offsetPrev=W*Y,this._offsetNext=K*Y}interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,H=$*X,N=H-X,Y=this._offsetPrev,G=this._offsetNext,O=this._weightPrev,E=this._weightNext,k=(J-U)/(Q-U),I=k*k,R=I*k,q=-O*R+2*O*I-O*k,Z=(1+O)*R+(-1.5-2*O)*I+(-0.5+O)*k+1,_=(-1-E)*R+(1.5+E)*I+0.5*k,P=E*R-E*I;for(let L=0;L!==X;++L)W[L]=q*K[Y+L]+Z*K[N+L]+_*K[H+L]+P*K[G+L];return W}}class v9 extends TJ{constructor($,U,J,Q){super($,U,J,Q)}interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,H=$*X,N=H-X,Y=(J-U)/(Q-U),G=1-Y;for(let O=0;O!==X;++O)W[O]=K[N+O]*G+K[H+O]*Y;return W}}class kH extends TJ{constructor($,U,J,Q){super($,U,J,Q)}interpolate_($){return this.copySampleValue_($-1)}}class qH extends TJ{interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,H=$*X,N=H-X,Y=this.inTangents,G=this.outTangents;if(!Y||!G){let k=(J-U)/(Q-U),I=1-k;for(let R=0;R!==X;++R)W[R]=K[N+R]*I+K[H+R]*k;return W}let O=X*2,E=$-1;for(let k=0;k!==X;++k){let I=K[N+k],R=K[H+k],q=E*O+k*2,Z=G[q],_=G[q+1],P=$*O+k*2,L=Y[P],B=Y[P+1],z=(J-U)/(Q-U),A,D,w,h,C;for(let f=0;f<8;f++){A=z*z,D=A*z,w=1-z,h=w*w,C=h*w;let x=C*U+3*h*z*Z+3*w*A*L+D*Q-J;if(Math.abs(x)<0.0000000001)break;let d=3*h*(Z-U)+6*w*z*(L-Z)+3*A*(Q-L);if(Math.abs(d)<0.0000000001)break;z=z-x/d,z=Math.max(0,Math.min(1,z))}W[k]=C*I+3*h*z*_+3*w*A*B+D*R}return W}}class MU{constructor($,U,J,Q){if($===void 0)throw Error("THREE.KeyframeTrack: track name is undefined");if(U===void 0||U.length===0)throw Error("THREE.KeyframeTrack: no keyframes in track named "+$);this.name=$,this.times=Q9(U,this.TimeBufferType),this.values=Q9(J,this.ValueBufferType),this.setInterpolation(Q||this.DefaultInterpolation)}static toJSON($){let U=$.constructor,J;if(U.toJSON!==this.toJSON)J=U.toJSON($);else{J={name:$.name,times:Q9($.times,Array),values:Q9($.values,Array)};let Q=$.getInterpolation();if(Q!==$.DefaultInterpolation)J.interpolation=Q}return J.type=$.ValueTypeName,J}InterpolantFactoryMethodDiscrete($){return new kH(this.times,this.values,this.getValueSize(),$)}InterpolantFactoryMethodLinear($){return new v9(this.times,this.values,this.getValueSize(),$)}InterpolantFactoryMethodSmooth($){return new EH(this.times,this.values,this.getValueSize(),$)}InterpolantFactoryMethodBezier($){let U=new qH(this.times,this.values,this.getValueSize(),$);if(this.settings)U.inTangents=this.settings.inTangents,U.outTangents=this.settings.outTangents;return U}setInterpolation($){let U;switch($){case 2300:U=this.InterpolantFactoryMethodDiscrete;break;case 2301:U=this.InterpolantFactoryMethodLinear;break;case 2302:U=this.InterpolantFactoryMethodSmooth;break;case 2303:U=this.InterpolantFactoryMethodBezier;break}if(U===void 0){let J="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if($!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(J);return A$("KeyframeTrack:",J),this}return this.createInterpolant=U,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;case this.InterpolantFactoryMethodLinear:return 2301;case this.InterpolantFactoryMethodSmooth:return 2302;case this.InterpolantFactoryMethodBezier:return 2303}}getValueSize(){return this.values.length/this.times.length}shift($){if($!==0){let U=this.times;for(let J=0,Q=U.length;J!==Q;++J)U[J]+=$}return this}scale($){if($!==1){let U=this.times;for(let J=0,Q=U.length;J!==Q;++J)U[J]*=$}return this}trim($,U){let J=this.times,Q=J.length,W=0,K=Q-1;while(W!==Q&&J[W]<$)++W;while(K!==-1&&J[K]>U)--K;if(++K,W!==0||K!==Q){if(W>=K)K=Math.max(K,1),W=K-1;let X=this.getValueSize();this.times=J.slice(W,K),this.values=this.values.slice(W*X,K*X)}return this}validate(){let $=!0,U=this.getValueSize();if(U-Math.floor(U)!==0)x$("KeyframeTrack: Invalid value size in track.",this),$=!1;let J=this.times,Q=this.values,W=J.length;if(W===0)x$("KeyframeTrack: Track is empty.",this),$=!1;let K=null;for(let X=0;X!==W;X++){let H=J[X];if(typeof H==="number"&&isNaN(H)){x$("KeyframeTrack: Time is not a valid number.",this,X,H),$=!1;break}if(K!==null&&K>H){x$("KeyframeTrack: Out of order keys.",this,X,H,K),$=!1;break}K=H}if(Q!==void 0){if(XF(Q))for(let X=0,H=Q.length;X!==H;++X){let N=Q[X];if(isNaN(N)){x$("KeyframeTrack: Value is not a valid number.",this,X,N),$=!1;break}}}return $}optimize(){let $=this.times.slice(),U=this.values.slice(),J=this.getValueSize(),Q=this.getInterpolation()===2302,W=$.length-1,K=1;for(let X=1;X<W;++X){let H=!1,N=$[X],Y=$[X+1];if(N!==Y&&(X!==1||N!==$[0]))if(!Q){let G=X*J,O=G-J,E=G+J;for(let k=0;k!==J;++k){let I=U[G+k];if(I!==U[O+k]||I!==U[E+k]){H=!0;break}}}else H=!0;if(H){if(X!==K){$[K]=$[X];let G=X*J,O=K*J;for(let E=0;E!==J;++E)U[O+E]=U[G+E]}++K}}if(W>0){$[K]=$[W];for(let X=W*J,H=K*J,N=0;N!==J;++N)U[H+N]=U[X+N];++K}if(K!==$.length)this.times=$.slice(0,K),this.values=U.slice(0,K*J);else this.times=$,this.values=U;return this}clone(){let $=this.times.slice(),U=this.values.slice(),Q=new this.constructor(this.name,$,U);return Q.createInterpolant=this.createInterpolant,Q}}MU.prototype.ValueTypeName="";MU.prototype.TimeBufferType=Float32Array;MU.prototype.ValueBufferType=Float32Array;MU.prototype.DefaultInterpolation=2301;class U0 extends MU{constructor($,U,J){super($,U,J)}}U0.prototype.ValueTypeName="bool";U0.prototype.ValueBufferType=Array;U0.prototype.DefaultInterpolation=2300;U0.prototype.InterpolantFactoryMethodLinear=void 0;U0.prototype.InterpolantFactoryMethodSmooth=void 0;class j9 extends MU{constructor($,U,J,Q){super($,U,J,Q)}}j9.prototype.ValueTypeName="color";class J0 extends MU{constructor($,U,J,Q){super($,U,J,Q)}}J0.prototype.ValueTypeName="number";class ZH extends TJ{constructor($,U,J,Q){super($,U,J,Q)}interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,H=(J-U)/(Q-U),N=$*X;for(let Y=N+X;N!==Y;N+=4)c6.slerpFlat(W,0,K,N-X,K,N,H);return W}}class W0 extends MU{constructor($,U,J,Q){super($,U,J,Q)}InterpolantFactoryMethodLinear($){return new ZH(this.times,this.values,this.getValueSize(),$)}}W0.prototype.ValueTypeName="quaternion";W0.prototype.InterpolantFactoryMethodSmooth=void 0;class Q0 extends MU{constructor($,U,J){super($,U,J)}}Q0.prototype.ValueTypeName="string";Q0.prototype.ValueBufferType=Array;Q0.prototype.DefaultInterpolation=2300;Q0.prototype.InterpolantFactoryMethodLinear=void 0;Q0.prototype.InterpolantFactoryMethodSmooth=void 0;class j0 extends MU{constructor($,U,J,Q){super($,U,J,Q)}}j0.prototype.ValueTypeName="vector";class E8{constructor($="",U=-1,J=[],Q=2500){if(this.name=$,this.tracks=J,this.duration=U,this.blendMode=Q,this.uuid=pU(),this.userData={},this.duration<0)this.resetDuration()}static parse($){let U=[],J=$.tracks,Q=1/($.fps||1);for(let K=0,X=J.length;K!==X;++K)U.push(aF(J[K]).scale(Q));let W=new this($.name,$.duration,U,$.blendMode);return W.uuid=$.uuid,W.userData=JSON.parse($.userData||"{}"),W}static toJSON($){let U=[],J=$.tracks,Q={name:$.name,duration:$.duration,tracks:U,uuid:$.uuid,blendMode:$.blendMode,userData:JSON.stringify($.userData)};for(let W=0,K=J.length;W!==K;++W)U.push(MU.toJSON(J[W]));return Q}static CreateFromMorphTargetSequence($,U,J,Q){let W=U.length,K=[];for(let X=0;X<W;X++){let H=[],N=[];H.push((X+W-1)%W,X,(X+1)%W),N.push(0,1,0);let Y=iF(H);if(H=ck(H,1,Y),N=ck(N,1,Y),!Q&&H[0]===0)H.push(W),N.push(N[0]);K.push(new J0(".morphTargetInfluences["+U[X].name+"]",H,N).scale(1/J))}return new this($,-1,K)}static findByName($,U){let J=$;if(!Array.isArray($)){let Q=$;J=Q.geometry&&Q.geometry.animations||Q.animations}for(let Q=0;Q<J.length;Q++)if(J[Q].name===U)return J[Q];return null}static CreateClipsFromMorphTargetSequences($,U,J){let Q={},W=/^([\w-]*?)([\d]+)$/;for(let X=0,H=$.length;X<H;X++){let N=$[X],Y=N.name.match(W);if(Y&&Y.length>1){let G=Y[1],O=Q[G];if(!O)Q[G]=O=[];O.push(N)}}let K=[];for(let X in Q)K.push(this.CreateFromMorphTargetSequence(X,Q[X],U,J));return K}resetDuration(){let $=this.tracks,U=0;for(let J=0,Q=$.length;J!==Q;++J){let W=this.tracks[J];U=Math.max(U,W.times[W.times.length-1])}return this.duration=U,this}trim(){for(let $=0;$<this.tracks.length;$++)this.tracks[$].trim(0,this.duration);return this}validate(){let $=!0;for(let U=0;U<this.tracks.length;U++)$=$&&this.tracks[U].validate();return $}optimize(){for(let $=0;$<this.tracks.length;$++)this.tracks[$].optimize();return this}clone(){let $=[];for(let J=0;J<this.tracks.length;J++)$.push(this.tracks[J].clone());let U=new this.constructor(this.name,this.duration,$,this.blendMode);return U.userData=JSON.parse(JSON.stringify(this.userData)),U}toJSON(){return this.constructor.toJSON(this)}}function rF($){switch($.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return J0;case"vector":case"vector2":case"vector3":case"vector4":return j0;case"color":return j9;case"quaternion":return W0;case"bool":case"boolean":return U0;case"string":return Q0}throw Error("THREE.KeyframeTrack: Unsupported typeName: "+$)}function aF($){if($.type===void 0)throw Error("THREE.KeyframeTrack: track type undefined, can not parse");let U=rF($.type);if($.times===void 0){let J=[],Q=[];oF($.keys,J,Q,"value"),$.times=J,$.values=Q}if(U.parse!==void 0)return U.parse($);else return new U($.name,$.times,$.values,$.interpolation)}var $J={enabled:!1,files:{},add:function($,U){if(this.enabled===!1)return;if(nk($))return;this.files[$]=U},get:function($){if(this.enabled===!1)return;if(nk($))return;return this.files[$]},remove:function($){delete this.files[$]},clear:function(){this.files={}}};function nk($){try{let U=$.slice($.indexOf(":")+1);return new URL(U).protocol==="blob:"}catch(U){return!1}}class xW{constructor($,U,J){let Q=this,W=!1,K=0,X=0,H=void 0,N=[];this.onStart=void 0,this.onLoad=$,this.onProgress=U,this.onError=J,this._abortController=null,this.itemStart=function(Y){if(X++,W===!1){if(Q.onStart!==void 0)Q.onStart(Y,K,X)}W=!0},this.itemEnd=function(Y){if(K++,Q.onProgress!==void 0)Q.onProgress(Y,K,X);if(K===X){if(W=!1,Q.onLoad!==void 0)Q.onLoad()}},this.itemError=function(Y){if(Q.onError!==void 0)Q.onError(Y)},this.resolveURL=function(Y){if(Y=Y.normalize("NFC"),H)return H(Y);return Y},this.setURLModifier=function(Y){return H=Y,this},this.addHandler=function(Y,G){return N.push(Y,G),this},this.removeHandler=function(Y){let G=N.indexOf(Y);if(G!==-1)N.splice(G,2);return this},this.getHandler=function(Y){for(let G=0,O=N.length;G<O;G+=2){let E=N[G],k=N[G+1];if(E.global)E.lastIndex=0;if(E.test(Y))return k}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){if(!this._abortController)this._abortController=new AbortController;return this._abortController}}var sq=new xW;class vJ{constructor($){if(this.manager=$!==void 0?$:sq,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($,U){let J=this;return new Promise(function(Q,W){J.load($,Q,U,W)})}parse(){}setCrossOrigin($){return this.crossOrigin=$,this}setWithCredentials($){return this.withCredentials=$,this}setPath($){return this.path=$,this}setResourcePath($){return this.resourcePath=$,this}setRequestHeader($){return this.requestHeader=$,this}abort(){return this}}vJ.DEFAULT_MATERIAL_NAME="__DEFAULT";var zJ={};class tq extends Error{constructor($,U){super($);this.response=U}}class hW extends vJ{constructor($){super($);this.mimeType="",this.responseType="",this._abortController=new AbortController}load($,U,J,Q){if($===void 0)$="";if(this.path!==void 0)$=this.path+$;$=this.manager.resolveURL($);let W=$J.get(`file:${$}`);if(W!==void 0){this.manager.itemStart($),setTimeout(()=>{if(U)U(W);this.manager.itemEnd($)},0);return}if(zJ[$]!==void 0){zJ[$].push({onLoad:U,onProgress:J,onError:Q});return}zJ[$]=[],zJ[$].push({onLoad:U,onProgress:J,onError:Q});let K=new Request($,{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}),X=this.mimeType,H=this.responseType;fetch(K).then((N)=>{if(N.status===200||N.status===0){if(N.status===0)A$("FileLoader: HTTP Status 0 received.");if(typeof ReadableStream>"u"||N.body===void 0||N.body.getReader===void 0)return N;let Y=zJ[$],G=N.body.getReader(),O=N.headers.get("X-File-Size")||N.headers.get("Content-Length"),E=O?parseInt(O):0,k=E!==0,I=0,R=new ReadableStream({start(q){Z();function Z(){G.read().then(({done:_,value:P})=>{if(_)q.close();else{I+=P.byteLength;let L=new ProgressEvent("progress",{lengthComputable:k,loaded:I,total:E});for(let B=0,z=Y.length;B<z;B++){let A=Y[B];if(A.onProgress)A.onProgress(L)}q.enqueue(P),Z()}},(_)=>{q.error(_)})}}});return new Response(R)}else throw new tq(`fetch for "${N.url}" responded with ${N.status}: ${N.statusText}`,N)}).then((N)=>{switch(H){case"arraybuffer":return N.arrayBuffer();case"blob":return N.blob();case"document":return N.text().then((Y)=>{return new DOMParser().parseFromString(Y,X)});case"json":return N.json();default:if(X==="")return N.text();else{let G=/charset="?([^;"\s]*)"?/i.exec(X),O=G&&G[1]?G[1].toLowerCase():void 0,E=new TextDecoder(O);return N.arrayBuffer().then((k)=>E.decode(k))}}}).then((N)=>{$J.add(`file:${$}`,N);let Y=zJ[$];delete zJ[$];for(let G=0,O=Y.length;G<O;G++){let E=Y[G];if(E.onLoad)E.onLoad(N)}}).catch((N)=>{let Y=zJ[$];if(Y===void 0)throw this.manager.itemError($),N;delete zJ[$];for(let G=0,O=Y.length;G<O;G++){let E=Y[G];if(E.onError)E.onError(N)}this.manager.itemError($)}).finally(()=>{this.manager.itemEnd($)}),this.manager.itemStart($)}setResponseType($){return this.responseType=$,this}setMimeType($){return this.mimeType=$,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}var X8=new WeakMap;class IH extends vJ{constructor($){super($)}load($,U,J,Q){if(this.path!==void 0)$=this.path+$;$=this.manager.resolveURL($);let W=this,K=$J.get(`image:${$}`);if(K!==void 0){if(K.complete===!0)W.manager.itemStart($),setTimeout(function(){if(U)U(K);W.manager.itemEnd($)},0);else{let G=X8.get(K);if(G===void 0)G=[],X8.set(K,G);G.push({onLoad:U,onError:Q})}return K}let X=G8("img");function H(){if(Y(),U)U(this);let G=X8.get(this)||[];for(let O=0;O<G.length;O++){let E=G[O];if(E.onLoad)E.onLoad(this)}X8.delete(this),W.manager.itemEnd($)}function N(G){if(Y(),Q)Q(G);$J.remove(`image:${$}`);let O=X8.get(this)||[];for(let E=0;E<O.length;E++){let k=O[E];if(k.onError)k.onError(G)}X8.delete(this),W.manager.itemError($),W.manager.itemEnd($)}function Y(){X.removeEventListener("load",H,!1),X.removeEventListener("error",N,!1)}if(X.addEventListener("load",H,!1),X.addEventListener("error",N,!1),$.slice(0,5)!=="data:"){if(this.crossOrigin!==void 0)X.crossOrigin=this.crossOrigin}return $J.add(`image:${$}`,X),W.manager.itemStart($),X.src=$,X}}class g9 extends vJ{constructor($){super($)}load($,U,J,Q){let W=new C6,K=new IH(this.manager);return K.setCrossOrigin(this.crossOrigin),K.setPath(this.path),K.load($,function(X){if(W.image=X,W.needsUpdate=!0,U!==void 0)U(W)},J,Q),W}}class P8 extends q6{constructor($,U=1){super();this.isLight=!0,this.type="Light",this.color=new y$($),this.intensity=U}dispose(){this.dispatchEvent({type:"dispose"})}copy($,U){return super.copy($,U),this.color.copy($.color),this.intensity=$.intensity,this}toJSON($){let U=super.toJSON($);return U.object.color=this.color.getHex(),U.object.intensity=this.intensity,U}}class b9 extends P8{constructor($,U,J){super($,J);this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(q6.DEFAULT_UP),this.updateMatrix(),this.groundColor=new y$(U)}copy($,U){return super.copy($,U),this.groundColor.copy($.groundColor),this}toJSON($){let U=super.toJSON($);return U.object.groundColor=this.groundColor.getHex(),U}}var UX=new m$,ik=new j,ok=new j;class y9{constructor($){this.camera=$,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new g$(512,512),this.mapType=1009,this.map=null,this.mapPass=null,this.matrix=new m$,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new jW,this._frameExtents=new g$(1,1),this._viewportCount=1,this._viewports=[new E6(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices($){let U=this.camera,J=this.matrix;if(ik.setFromMatrixPosition($.matrixWorld),U.position.copy(ik),ok.setFromMatrixPosition($.target.matrixWorld),U.lookAt(ok),U.updateMatrixWorld(),UX.multiplyMatrices(U.projectionMatrix,U.matrixWorldInverse),this._frustum.setFromProjectionMatrix(UX,U.coordinateSystem,U.reversedDepth),U.coordinateSystem===2001||U.reversedDepth)J.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,1,0,0,0,0,1);else J.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1);J.multiply(UX)}getViewport($){return this._viewports[$]}getFrameExtents(){return this._frameExtents}dispose(){if(this.map)this.map.dispose();if(this.mapPass)this.mapPass.dispose()}copy($){return this.camera=$.camera.clone(),this.intensity=$.intensity,this.bias=$.bias,this.radius=$.radius,this.autoUpdate=$.autoUpdate,this.needsUpdate=$.needsUpdate,this.normalBias=$.normalBias,this.blurSamples=$.blurSamples,this.mapSize.copy($.mapSize),this.biasNode=$.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let $={};if(this.intensity!==1)$.intensity=this.intensity;if(this.bias!==0)$.bias=this.bias;if(this.normalBias!==0)$.normalBias=this.normalBias;if(this.radius!==1)$.radius=this.radius;if(this.mapSize.x!==512||this.mapSize.y!==512)$.mapSize=this.mapSize.toArray();return $.camera=this.camera.toJSON(!1).object,delete $.camera.matrix,$}}var K9=new j,X9=new c6,tU=new j;class x9 extends q6{constructor(){super();this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new m$,this.projectionMatrix=new m$,this.projectionMatrixInverse=new m$,this.coordinateSystem=2000,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy($,U){return super.copy($,U),this.matrixWorldInverse.copy($.matrixWorldInverse),this.projectionMatrix.copy($.projectionMatrix),this.projectionMatrixInverse.copy($.projectionMatrixInverse),this.coordinateSystem=$.coordinateSystem,this}getWorldDirection($){return super.getWorldDirection($).negate()}updateMatrixWorld($){if(super.updateMatrixWorld($),this.matrixWorld.decompose(K9,X9,tU),tU.x===1&&tU.y===1&&tU.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(K9,X9,tU.set(1,1,1)).invert()}updateWorldMatrix($,U,J=!1){if(super.updateWorldMatrix($,U,J),this.matrixWorld.decompose(K9,X9,tU),tU.x===1&&tU.y===1&&tU.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(K9,X9,tU.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}var cJ=new j,rk=new g$,ak=new g$;class x6 extends x9{constructor($=50,U=1,J=0.1,Q=2000){super();this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=$,this.zoom=1,this.near=J,this.far=Q,this.focus=10,this.aspect=U,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy($,U){return super.copy($,U),this.fov=$.fov,this.zoom=$.zoom,this.near=$.near,this.far=$.far,this.focus=$.focus,this.aspect=$.aspect,this.view=$.view===null?null:Object.assign({},$.view),this.filmGauge=$.filmGauge,this.filmOffset=$.filmOffset,this}setFocalLength($){let U=0.5*this.getFilmHeight()/$;this.fov=B0*2*Math.atan(U),this.updateProjectionMatrix()}getFocalLength(){let $=Math.tan(DW*0.5*this.fov);return 0.5*this.getFilmHeight()/$}getEffectiveFOV(){return B0*2*Math.atan(Math.tan(DW*0.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds($,U,J){cJ.set(-1,-1,0.5).applyMatrix4(this.projectionMatrixInverse),U.set(cJ.x,cJ.y).multiplyScalar(-$/cJ.z),cJ.set(1,1,0.5).applyMatrix4(this.projectionMatrixInverse),J.set(cJ.x,cJ.y).multiplyScalar(-$/cJ.z)}getViewSize($,U){return this.getViewBounds($,rk,ak),U.subVectors(ak,rk)}setViewOffset($,U,J,Q,W,K){if(this.aspect=$/U,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=$,this.view.fullHeight=U,this.view.offsetX=J,this.view.offsetY=Q,this.view.width=W,this.view.height=K,this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null)this.view.enabled=!1;this.updateProjectionMatrix()}updateProjectionMatrix(){let $=this.near,U=$*Math.tan(DW*0.5*this.fov)/this.zoom,J=2*U,Q=this.aspect*J,W=-0.5*Q,K=this.view;if(this.view!==null&&this.view.enabled){let{fullWidth:H,fullHeight:N}=K;W+=K.offsetX*Q/H,U-=K.offsetY*J/N,Q*=K.width/H,J*=K.height/N}let X=this.filmOffset;if(X!==0)W+=$*X/this.getFilmWidth();this.projectionMatrix.makePerspective(W,W+Q,U,U-J,$,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON($){let U=super.toJSON($);if(U.object.fov=this.fov,U.object.zoom=this.zoom,U.object.near=this.near,U.object.far=this.far,U.object.focus=this.focus,U.object.aspect=this.aspect,this.view!==null)U.object.view=Object.assign({},this.view);return U.object.filmGauge=this.filmGauge,U.object.filmOffset=this.filmOffset,U}}class eq extends y9{constructor(){super(new x6(50,1,0.5,500));this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices($){let U=this.camera,J=B0*2*$.angle*this.focus,Q=this.mapSize.width/this.mapSize.height*this.aspect,W=$.distance||U.far;if(J!==U.fov||Q!==U.aspect||W!==U.far)U.fov=J,U.aspect=Q,U.far=W,U.updateProjectionMatrix();super.updateMatrices($)}copy($){return super.copy($),this.focus=$.focus,this}}class h9 extends P8{constructor($,U,J=0,Q=Math.PI/3,W=0,K=2){super($,U);this.isSpotLight=!0,this.type="SpotLight",this.position.copy(q6.DEFAULT_UP),this.updateMatrix(),this.target=new q6,this.distance=J,this.angle=Q,this.penumbra=W,this.decay=K,this.map=null,this.shadow=new eq}get power(){return this.intensity*Math.PI}set power($){this.intensity=$/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy($,U){return super.copy($,U),this.distance=$.distance,this.angle=$.angle,this.penumbra=$.penumbra,this.decay=$.decay,this.target=$.target.clone(),this.map=$.map,this.shadow=$.shadow.clone(),this}toJSON($){let U=super.toJSON($);if(U.object.distance=this.distance,U.object.angle=this.angle,U.object.decay=this.decay,U.object.penumbra=this.penumbra,U.object.target=this.target.uuid,this.map&&this.map.isTexture)U.object.map=this.map.toJSON($).uuid;return U.object.shadow=this.shadow.toJSON(),U}}class $Z extends y9{constructor(){super(new x6(90,1,0.5,500));this.isPointLightShadow=!0}}class z8 extends P8{constructor($,U,J=0,Q=2){super($,U);this.isPointLight=!0,this.type="PointLight",this.distance=J,this.decay=Q,this.shadow=new $Z}get power(){return this.intensity*4*Math.PI}set power($){this.intensity=$/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy($,U){return super.copy($,U),this.distance=$.distance,this.decay=$.decay,this.shadow=$.shadow.clone(),this}toJSON($){let U=super.toJSON($);return U.object.distance=this.distance,U.object.decay=this.decay,U.object.shadow=this.shadow.toJSON(),U}}class g0 extends x9{constructor($=-1,U=1,J=1,Q=-1,W=0.1,K=2000){super();this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=$,this.right=U,this.top=J,this.bottom=Q,this.near=W,this.far=K,this.updateProjectionMatrix()}copy($,U){return super.copy($,U),this.left=$.left,this.right=$.right,this.top=$.top,this.bottom=$.bottom,this.near=$.near,this.far=$.far,this.zoom=$.zoom,this.view=$.view===null?null:Object.assign({},$.view),this}setViewOffset($,U,J,Q,W,K){if(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=$,this.view.fullHeight=U,this.view.offsetX=J,this.view.offsetY=Q,this.view.width=W,this.view.height=K,this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null)this.view.enabled=!1;this.updateProjectionMatrix()}updateProjectionMatrix(){let $=(this.right-this.left)/(2*this.zoom),U=(this.top-this.bottom)/(2*this.zoom),J=(this.right+this.left)/2,Q=(this.top+this.bottom)/2,W=J-$,K=J+$,X=Q+U,H=Q-U;if(this.view!==null&&this.view.enabled){let N=(this.right-this.left)/this.view.fullWidth/this.zoom,Y=(this.top-this.bottom)/this.view.fullHeight/this.zoom;W+=N*this.view.offsetX,K=W+N*this.view.width,X-=Y*this.view.offsetY,H=X-Y*this.view.height}this.projectionMatrix.makeOrthographic(W,K,X,H,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON($){let U=super.toJSON($);if(U.object.zoom=this.zoom,U.object.left=this.left,U.object.right=this.right,U.object.top=this.top,U.object.bottom=this.bottom,U.object.near=this.near,U.object.far=this.far,this.view!==null)U.object.view=Object.assign({},this.view);return U}}class UZ extends y9{constructor(){super(new g0(-5,5,5,-5,0.5,500));this.isDirectionalLightShadow=!0}}class _8 extends P8{constructor($,U){super($,U);this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(q6.DEFAULT_UP),this.updateMatrix(),this.target=new q6,this.shadow=new UZ}dispose(){super.dispose(),this.shadow.dispose()}copy($){return super.copy($),this.target=$.target.clone(),this.shadow=$.shadow.clone(),this}toJSON($){let U=super.toJSON($);return U.object.shadow=this.shadow.toJSON(),U.object.target=this.target.uuid,U}}class K0{static extractUrlBase($){let U=$.lastIndexOf("/");if(U===-1)return"./";return $.slice(0,U+1)}static resolveURL($,U){if(typeof $!=="string"||$==="")return"";if(/^https?:\/\//i.test(U)&&/^\//.test($))U=U.replace(/(^https?:\/\/[^\/]+).*/i,"$1");if(/^(https?:)?\/\//i.test($))return $;if(/^data:.*,.*$/i.test($))return $;if(/^blob:.*$/i.test($))return $;return U+$}}var JX=new WeakMap;class f9 extends vJ{constructor($){super($);if(this.isImageBitmapLoader=!0,typeof createImageBitmap>"u")A$("ImageBitmapLoader: createImageBitmap() not supported.");if(typeof fetch>"u")A$("ImageBitmapLoader: fetch() not supported.");this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions($){return this.options=$,this}load($,U,J,Q){if($===void 0)$="";if(this.path!==void 0)$=this.path+$;$=this.manager.resolveURL($);let W=this,K=$J.get(`image-bitmap:${$}`);if(K!==void 0){if(W.manager.itemStart($),K.then){K.then((N)=>{if(JX.has(K)===!0){if(Q)Q(JX.get(K));W.manager.itemError($),W.manager.itemEnd($)}else{if(U)U(N);W.manager.itemEnd($)}});return}setTimeout(function(){if(U)U(K);W.manager.itemEnd($)},0);return}let X={};X.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",X.headers=this.requestHeader,X.signal=typeof AbortSignal.any==="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let H=fetch($,X).then(function(N){return N.blob()}).then(function(N){return createImageBitmap(N,Object.assign(W.options,{colorSpaceConversion:"none"}))}).then(function(N){if($J.add(`image-bitmap:${$}`,N),U)U(N);W.manager.itemEnd($)}).catch(function(N){if(Q)Q(N);JX.set(H,N),$J.remove(`image-bitmap:${$}`),W.manager.itemError($),W.manager.itemEnd($)});$J.add(`image-bitmap:${$}`,H),W.manager.itemStart($)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}var H8=-90,N8=1;class DH extends q6{constructor($,U,J){super();this.type="CubeCamera",this.renderTarget=J,this.coordinateSystem=null,this.activeMipmapLevel=0;let Q=new x6(H8,N8,$,U);Q.layers=this.layers,this.add(Q);let W=new x6(H8,N8,$,U);W.layers=this.layers,this.add(W);let K=new x6(H8,N8,$,U);K.layers=this.layers,this.add(K);let X=new x6(H8,N8,$,U);X.layers=this.layers,this.add(X);let H=new x6(H8,N8,$,U);H.layers=this.layers,this.add(H);let N=new x6(H8,N8,$,U);N.layers=this.layers,this.add(N)}updateCoordinateSystem(){let $=this.coordinateSystem,U=this.children.concat(),[J,Q,W,K,X,H]=U;for(let N of U)this.remove(N);if($===2000)J.up.set(0,1,0),J.lookAt(1,0,0),Q.up.set(0,1,0),Q.lookAt(-1,0,0),W.up.set(0,0,-1),W.lookAt(0,1,0),K.up.set(0,0,1),K.lookAt(0,-1,0),X.up.set(0,1,0),X.lookAt(0,0,1),H.up.set(0,1,0),H.lookAt(0,0,-1);else if($===2001)J.up.set(0,-1,0),J.lookAt(-1,0,0),Q.up.set(0,-1,0),Q.lookAt(1,0,0),W.up.set(0,0,1),W.lookAt(0,1,0),K.up.set(0,0,-1),K.lookAt(0,-1,0),X.up.set(0,-1,0),X.lookAt(0,0,1),H.up.set(0,-1,0),H.lookAt(0,0,-1);else throw Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+$);for(let N of U)this.add(N),N.updateMatrixWorld()}update($,U){if(this.parent===null)this.updateMatrixWorld();let{renderTarget:J,activeMipmapLevel:Q}=this;if(this.coordinateSystem!==$.coordinateSystem)this.coordinateSystem=$.coordinateSystem,this.updateCoordinateSystem();let[W,K,X,H,N,Y]=this.children,G=$.getRenderTarget(),O=$.getActiveCubeFace(),E=$.getActiveMipmapLevel(),k=$.xr.enabled;$.xr.enabled=!1;let I=J.texture.generateMipmaps;J.texture.generateMipmaps=!1;let R=!1;if($.isWebGLRenderer===!0)R=$.state.buffers.depth.getReversed();else R=$.reversedDepthBuffer;if($.setRenderTarget(J,0,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,W),$.setRenderTarget(J,1,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,K),$.setRenderTarget(J,2,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,X),$.setRenderTarget(J,3,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,H),$.setRenderTarget(J,4,Q),R&&$.autoClear===!1)$.clearDepth();if($.render(U,N),J.texture.generateMipmaps=I,$.setRenderTarget(J,5,Q),R&&$.autoClear===!1)$.clearDepth();$.render(U,Y),$.setRenderTarget(G,O,E),$.xr.enabled=k,J.texture.needsPMREMUpdate=!0}}class FH extends x6{constructor($=[]){super();this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=$}}class LH{constructor($,U,J){this.binding=$,this.valueSize=J;let Q,W,K;switch(U){case"quaternion":Q=this._slerp,W=this._slerpAdditive,K=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(J*6),this._workIndex=5;break;case"string":case"bool":Q=this._select,W=this._select,K=this._setAdditiveIdentityOther,this.buffer=Array(J*5);break;default:Q=this._lerp,W=this._lerpAdditive,K=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(J*5)}this._mixBufferRegion=Q,this._mixBufferRegionAdditive=W,this._setIdentity=K,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate($,U){let J=this.buffer,Q=this.valueSize,W=$*Q+Q,K=this.cumulativeWeight;if(K===0){for(let X=0;X!==Q;++X)J[W+X]=J[X];K=U}else{K+=U;let X=U/K;this._mixBufferRegion(J,W,0,X,Q)}this.cumulativeWeight=K}accumulateAdditive($){let U=this.buffer,J=this.valueSize,Q=J*this._addIndex;if(this.cumulativeWeightAdditive===0)this._setIdentity();this._mixBufferRegionAdditive(U,Q,0,$,J),this.cumulativeWeightAdditive+=$}apply($){let U=this.valueSize,J=this.buffer,Q=$*U+U,W=this.cumulativeWeight,K=this.cumulativeWeightAdditive,X=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,W<1){let H=U*this._origIndex;this._mixBufferRegion(J,Q,H,1-W,U)}if(K>0)this._mixBufferRegionAdditive(J,Q,this._addIndex*U,1,U);for(let H=U,N=U+U;H!==N;++H)if(J[H]!==J[H+U]){X.setValue(J,Q);break}}saveOriginalState(){let $=this.binding,U=this.buffer,J=this.valueSize,Q=J*this._origIndex;$.getValue(U,Q);for(let W=J,K=Q;W!==K;++W)U[W]=U[Q+W%J];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let $=this.valueSize*3;this.binding.setValue(this.buffer,$)}_setAdditiveIdentityNumeric(){let $=this._addIndex*this.valueSize,U=$+this.valueSize;for(let J=$;J<U;J++)this.buffer[J]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let $=this._origIndex*this.valueSize,U=this._addIndex*this.valueSize;for(let J=0;J<this.valueSize;J++)this.buffer[U+J]=this.buffer[$+J]}_select($,U,J,Q,W){if(Q>=0.5)for(let K=0;K!==W;++K)$[U+K]=$[J+K]}_slerp($,U,J,Q){c6.slerpFlat($,U,$,U,$,J,Q)}_slerpAdditive($,U,J,Q,W){let K=this._workIndex*W;c6.multiplyQuaternionsFlat($,K,$,U,$,J),c6.slerpFlat($,U,$,U,$,K,Q)}_lerp($,U,J,Q,W){let K=1-Q;for(let X=0;X!==W;++X){let H=U+X;$[H]=$[H]*K+$[J+X]*Q}}_lerpAdditive($,U,J,Q,W){for(let K=0;K!==W;++K){let X=U+K;$[X]=$[X]+$[J+K]*Q}}}var RH="\\[\\]\\.:\\/",sF=new RegExp("["+RH+"]","g"),VH="[^"+RH+"]",tF="[^"+RH.replace("\\.","")+"]",eF=/((?:WC+[\/:])*)/.source.replace("WC",VH),$4=/(WCOD+)?/.source.replace("WCOD",tF),U4=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",VH),J4=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",VH),W4=new RegExp("^"+eF+$4+U4+J4+"$"),Q4=["material","materials","bones","map"];class JZ{constructor($,U,J){let Q=J||N6.parseTrackName(U);this._targetGroup=$,this._bindings=$.subscribe_(U,Q)}getValue($,U){this.bind();let J=this._targetGroup.nCachedObjects_,Q=this._bindings[J];if(Q!==void 0)Q.getValue($,U)}setValue($,U){let J=this._bindings;for(let Q=this._targetGroup.nCachedObjects_,W=J.length;Q!==W;++Q)J[Q].setValue($,U)}bind(){let $=this._bindings;for(let U=this._targetGroup.nCachedObjects_,J=$.length;U!==J;++U)$[U].bind()}unbind(){let $=this._bindings;for(let U=this._targetGroup.nCachedObjects_,J=$.length;U!==J;++U)$[U].unbind()}}class N6{constructor($,U,J){this.path=U,this.parsedPath=J||N6.parseTrackName(U),this.node=N6.findNode($,this.parsedPath.nodeName),this.rootNode=$,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create($,U,J){if(!($&&$.isAnimationObjectGroup))return new N6($,U,J);else return new N6.Composite($,U,J)}static sanitizeNodeName($){return $.replace(/\s/g,"_").replace(sF,"")}static parseTrackName($){let U=W4.exec($);if(U===null)throw Error("THREE.PropertyBinding: Cannot parse trackName: "+$);let J={nodeName:U[2],objectName:U[3],objectIndex:U[4],propertyName:U[5],propertyIndex:U[6]},Q=J.nodeName&&J.nodeName.lastIndexOf(".");if(Q!==void 0&&Q!==-1){let W=J.nodeName.substring(Q+1);if(Q4.indexOf(W)!==-1)J.nodeName=J.nodeName.substring(0,Q),J.objectName=W}if(J.propertyName===null||J.propertyName.length===0)throw Error("THREE.PropertyBinding: can not parse propertyName from trackName: "+$);return J}static findNode($,U){if(U===void 0||U===""||U==="."||U===-1||U===$.name||U===$.uuid)return $;if($.skeleton){let J=$.skeleton.getBoneByName(U);if(J!==void 0)return J}if($.children){let J=function(W){for(let K=0;K<W.length;K++){let X=W[K];if(X.name===U||X.uuid===U)return X;let H=J(X.children);if(H)return H}return null},Q=J($.children);if(Q)return Q}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct($,U){$[U]=this.targetObject[this.propertyName]}_getValue_array($,U){let J=this.resolvedProperty;for(let Q=0,W=J.length;Q!==W;++Q)$[U++]=J[Q]}_getValue_arrayElement($,U){$[U]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray($,U){this.resolvedProperty.toArray($,U)}_setValue_direct($,U){this.targetObject[this.propertyName]=$[U]}_setValue_direct_setNeedsUpdate($,U){this.targetObject[this.propertyName]=$[U],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate($,U){this.targetObject[this.propertyName]=$[U],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array($,U){let J=this.resolvedProperty;for(let Q=0,W=J.length;Q!==W;++Q)J[Q]=$[U++]}_setValue_array_setNeedsUpdate($,U){let J=this.resolvedProperty;for(let Q=0,W=J.length;Q!==W;++Q)J[Q]=$[U++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate($,U){let J=this.resolvedProperty;for(let Q=0,W=J.length;Q!==W;++Q)J[Q]=$[U++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement($,U){this.resolvedProperty[this.propertyIndex]=$[U]}_setValue_arrayElement_setNeedsUpdate($,U){this.resolvedProperty[this.propertyIndex]=$[U],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate($,U){this.resolvedProperty[this.propertyIndex]=$[U],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray($,U){this.resolvedProperty.fromArray($,U)}_setValue_fromArray_setNeedsUpdate($,U){this.resolvedProperty.fromArray($,U),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate($,U){this.resolvedProperty.fromArray($,U),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound($,U){this.bind(),this.getValue($,U)}_setValue_unbound($,U){this.bind(),this.setValue($,U)}bind(){let $=this.node,U=this.parsedPath,J=U.objectName,Q=U.propertyName,W=U.propertyIndex;if(!$)$=N6.findNode(this.rootNode,U.nodeName),this.node=$;if(this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!$){A$("PropertyBinding: No target node found for track: "+this.path+".");return}if(J){let N=U.objectIndex;switch(J){case"materials":if(!$.material){x$("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!$.material.materials){x$("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}$=$.material.materials;break;case"bones":if(!$.skeleton){x$("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}$=$.skeleton.bones;for(let Y=0;Y<$.length;Y++)if($[Y].name===N){N=Y;break}break;case"map":if("map"in $){$=$.map;break}if(!$.material){x$("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!$.material.map){x$("PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}$=$.material.map;break;default:if($[J]===void 0){x$("PropertyBinding: Can not bind to objectName of node undefined.",this);return}$=$[J]}if(N!==void 0){if($[N]===void 0){x$("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,$);return}$=$[N]}}let K=$[Q];if(K===void 0){let N=U.nodeName;x$("PropertyBinding: Trying to update property for track: "+N+"."+Q+" but it wasn't found.",$);return}let X=this.Versioning.None;if(this.targetObject=$,$.isMaterial===!0)X=this.Versioning.NeedsUpdate;else if($.isObject3D===!0)X=this.Versioning.MatrixWorldNeedsUpdate;let H=this.BindingType.Direct;if(W!==void 0){if(Q==="morphTargetInfluences"){if(!$.geometry){x$("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!$.geometry.morphAttributes){x$("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}if($.morphTargetDictionary[W]!==void 0)W=$.morphTargetDictionary[W]}H=this.BindingType.ArrayElement,this.resolvedProperty=K,this.propertyIndex=W}else if(K.fromArray!==void 0&&K.toArray!==void 0)H=this.BindingType.HasFromToArray,this.resolvedProperty=K;else if(Array.isArray(K))H=this.BindingType.EntireArray,this.resolvedProperty=K;else this.propertyName=Q;this.getValue=this.GetterByBindingType[H],this.setValue=this.SetterByBindingTypeAndVersioning[H][X]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}N6.Composite=JZ;N6.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};N6.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};N6.prototype.GetterByBindingType=[N6.prototype._getValue_direct,N6.prototype._getValue_array,N6.prototype._getValue_arrayElement,N6.prototype._getValue_toArray];N6.prototype.SetterByBindingTypeAndVersioning=[[N6.prototype._setValue_direct,N6.prototype._setValue_direct_setNeedsUpdate,N6.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[N6.prototype._setValue_array,N6.prototype._setValue_array_setNeedsUpdate,N6.prototype._setValue_array_setMatrixWorldNeedsUpdate],[N6.prototype._setValue_arrayElement,N6.prototype._setValue_arrayElement_setNeedsUpdate,N6.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[N6.prototype._setValue_fromArray,N6.prototype._setValue_fromArray_setNeedsUpdate,N6.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class wH{constructor($,U,J=null,Q=U.blendMode){this._mixer=$,this._clip=U,this._localRoot=J,this.blendMode=Q;let W=U.tracks,K=W.length,X=Array(K),H={endingStart:2400,endingEnd:2400};for(let N=0;N!==K;++N){let Y=W[N].createInterpolant(null);X[N]=Y,Y.settings=H}this._interpolantSettings=H,this._interpolants=X,this._propertyBindings=Array(K),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._restoreTimeScale=null,this._weightInterpolant=null,this.loop=2201,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($){return this._startTime=$,this}setLoop($,U){return this.loop=$,this.repetitions=U,this}setEffectiveWeight($){return this.weight=$,this._effectiveWeight=this.enabled?$:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn($){return this._scheduleFading($,0,1)}fadeOut($){return this._scheduleFading($,1,0)}crossFadeFrom($,U,J=!1){if($.fadeOut(U),this.fadeIn(U),J===!0){let Q=this._clip.duration,W=$._clip.duration,K=W/Q,X=Q/W;$._restoreTimeScale=$.timeScale,this._restoreTimeScale=this.timeScale,$.warp(1,K,U),this.warp(X,1,U)}return this}crossFadeTo($,U,J=!1){return $.crossFadeFrom(this,U,J)}stopFading(){let $=this._weightInterpolant;if($!==null)this._weightInterpolant=null,this._mixer._takeBackControlInterpolant($);return this}setEffectiveTimeScale($){return this.timeScale=$,this._effectiveTimeScale=this.paused?0:$,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration($){return this.timeScale=this._clip.duration/$,this.stopWarping()}syncWith($){return this.time=$.time,this.timeScale=$.timeScale,this.stopWarping()}halt($){return this.warp(this._effectiveTimeScale,0,$)}warp($,U,J){let Q=this._mixer,W=Q.time,K=this.timeScale,X=this._timeScaleInterpolant;if(X===null)X=Q._lendControlInterpolant(),this._timeScaleInterpolant=X;let{parameterPositions:H,sampleValues:N}=X;return H[0]=W,H[1]=W+J,N[0]=$/K,N[1]=U/K,this}stopWarping(){let $=this._timeScaleInterpolant;if($!==null)this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant($);return this._restoreTimeScale=null,this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update($,U,J,Q){if(!this.enabled){this._updateWeight($);return}let W=this._startTime;if(W!==null){let H=($-W)*J;if(H<0||J===0)U=0;else this._startTime=null,U=J*H}U*=this._updateTimeScale($);let K=this._updateTime(U),X=this._updateWeight($);if(X>0){let H=this._interpolants,N=this._propertyBindings;switch(this.blendMode){case 2501:for(let Y=0,G=H.length;Y!==G;++Y)H[Y].evaluate(K),N[Y].accumulateAdditive(X);break;case 2500:default:for(let Y=0,G=H.length;Y!==G;++Y)H[Y].evaluate(K),N[Y].accumulate(Q,X)}}}_updateWeight($){let U=0;if(this.enabled){U=this.weight;let J=this._weightInterpolant;if(J!==null){let Q=J.evaluate($)[0];if(U*=Q,$>J.parameterPositions[1]){if(this.stopFading(),Q===0)this.enabled=!1}}}return this._effectiveWeight=U,U}_updateTimeScale($){let U=0;if(!this.paused){U=this.timeScale;let J=this._timeScaleInterpolant;if(J!==null){let Q=J.evaluate($)[0];if(U*=Q,$>J.parameterPositions[1]){if(U===0)this.paused=!0;else{if(this._restoreTimeScale!==null)U=this._restoreTimeScale;this.timeScale=U}this.stopWarping()}}}return this._effectiveTimeScale=U,U}_updateTime($){let U=this._clip.duration,J=this.loop,Q=this.time+$,W=this._loopCount,K=J===2202;if($===0){if(W===-1)return Q;return K&&(W&1)===1?U-Q:Q}if(J===2200){if(W===-1)this._loopCount=0,this._setEndings(!0,!0,!1);$:{if(Q>=U)Q=U;else if(Q<0)Q=0;else{this.time=Q;break $}if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;this.time=Q,this._mixer.dispatchEvent({type:"finished",action:this,direction:$<0?-1:1})}}else{if(W===-1)if($>=0)W=0,this._setEndings(!0,this.repetitions===0,K);else this._setEndings(this.repetitions===0,!0,K);if(Q>=U||Q<0){let X=Math.floor(Q/U);Q-=U*X,W+=Math.abs(X);let H=this.repetitions-W;if(H<=0){if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;Q=$>0?U:0,this.time=Q,this._mixer.dispatchEvent({type:"finished",action:this,direction:$>0?1:-1})}else{if(H===1){let N=$<0;this._setEndings(N,!N,K)}else this._setEndings(!1,!1,K);this._loopCount=W,this.time=Q,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:X})}}else this._loopCount=W,this.time=Q;if(K&&(W&1)===1)return U-Q}return Q}_setEndings($,U,J){let Q=this._interpolantSettings;if(J)Q.endingStart=2401,Q.endingEnd=2401;else{if($)Q.endingStart=this.zeroSlopeAtStart?2401:2400;else Q.endingStart=2402;if(U)Q.endingEnd=this.zeroSlopeAtEnd?2401:2400;else Q.endingEnd=2402}}_scheduleFading($,U,J){let Q=this._mixer,W=Q.time,K=this._weightInterpolant;if(K===null)K=Q._lendControlInterpolant(),this._weightInterpolant=K;let{parameterPositions:X,sampleValues:H}=K;return X[0]=W,H[0]=U,X[1]=W+$,H[1]=J,this}}var K4=new Float32Array(1);class u9 extends iU{constructor($){super();if(this._root=$,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction($,U){let J=$._localRoot||this._root,Q=$._clip.tracks,W=Q.length,K=$._propertyBindings,X=$._interpolants,H=J.uuid,N=this._bindingsByRootAndName,Y=N[H];if(Y===void 0)Y={},N[H]=Y;for(let G=0;G!==W;++G){let O=Q[G],E=O.name,k=Y[E];if(k!==void 0)++k.referenceCount,K[G]=k;else{if(k=K[G],k!==void 0){if(k._cacheIndex===null)++k.referenceCount,this._addInactiveBinding(k,H,E);continue}let I=U&&U._propertyBindings[G].binding.parsedPath;k=new LH(N6.create(J,E,I),O.ValueTypeName,O.getValueSize()),++k.referenceCount,this._addInactiveBinding(k,H,E),K[G]=k}X[G].resultBuffer=k.buffer}}_activateAction($){if(!this._isActiveAction($)){if($._cacheIndex===null){let J=($._localRoot||this._root).uuid,Q=$._clip.uuid,W=this._actionsByClip[Q];this._bindAction($,W&&W.knownActions[0]),this._addInactiveAction($,Q,J)}let U=$._propertyBindings;for(let J=0,Q=U.length;J!==Q;++J){let W=U[J];if(W.useCount++===0)this._lendBinding(W),W.saveOriginalState()}this._lendAction($)}}_deactivateAction($){if(this._isActiveAction($)){let U=$._propertyBindings;for(let J=0,Q=U.length;J!==Q;++J){let W=U[J];if(--W.useCount===0)W.restoreOriginalState(),this._takeBackBinding(W)}this._takeBackAction($)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let $=this;this.stats={actions:{get total(){return $._actions.length},get inUse(){return $._nActiveActions}},bindings:{get total(){return $._bindings.length},get inUse(){return $._nActiveBindings}},controlInterpolants:{get total(){return $._controlInterpolants.length},get inUse(){return $._nActiveControlInterpolants}}}}_isActiveAction($){let U=$._cacheIndex;return U!==null&&U<this._nActiveActions}_addInactiveAction($,U,J){let Q=this._actions,W=this._actionsByClip,K=W[U];if(K===void 0)K={knownActions:[$],actionByRoot:{}},$._byClipCacheIndex=0,W[U]=K;else{let X=K.knownActions;$._byClipCacheIndex=X.length,X.push($)}$._cacheIndex=Q.length,Q.push($),K.actionByRoot[J]=$}_removeInactiveAction($){let U=this._actions,J=U[U.length-1],Q=$._cacheIndex;J._cacheIndex=Q,U[Q]=J,U.pop(),$._cacheIndex=null;let W=$._clip.uuid,K=this._actionsByClip,X=K[W],H=X.knownActions,N=H[H.length-1],Y=$._byClipCacheIndex;N._byClipCacheIndex=Y,H[Y]=N,H.pop(),$._byClipCacheIndex=null;let G=X.actionByRoot,O=($._localRoot||this._root).uuid;if(delete G[O],H.length===0)delete K[W];this._removeInactiveBindingsForAction($)}_removeInactiveBindingsForAction($){let U=$._propertyBindings;for(let J=0,Q=U.length;J!==Q;++J){let W=U[J];if(--W.referenceCount===0)this._removeInactiveBinding(W)}}_lendAction($){let U=this._actions,J=$._cacheIndex,Q=this._nActiveActions++,W=U[Q];$._cacheIndex=Q,U[Q]=$,W._cacheIndex=J,U[J]=W}_takeBackAction($){let U=this._actions,J=$._cacheIndex,Q=--this._nActiveActions,W=U[Q];$._cacheIndex=Q,U[Q]=$,W._cacheIndex=J,U[J]=W}_addInactiveBinding($,U,J){let Q=this._bindingsByRootAndName,W=this._bindings,K=Q[U];if(K===void 0)K={},Q[U]=K;K[J]=$,$._cacheIndex=W.length,W.push($)}_removeInactiveBinding($){let U=this._bindings,J=$.binding,Q=J.rootNode.uuid,W=J.path,K=this._bindingsByRootAndName,X=K[Q],H=U[U.length-1],N=$._cacheIndex;if(H._cacheIndex=N,U[N]=H,U.pop(),delete X[W],Object.keys(X).length===0)delete K[Q]}_lendBinding($){let U=this._bindings,J=$._cacheIndex,Q=this._nActiveBindings++,W=U[Q];$._cacheIndex=Q,U[Q]=$,W._cacheIndex=J,U[J]=W}_takeBackBinding($){let U=this._bindings,J=$._cacheIndex,Q=--this._nActiveBindings,W=U[Q];$._cacheIndex=Q,U[Q]=$,W._cacheIndex=J,U[J]=W}_lendControlInterpolant(){let $=this._controlInterpolants,U=this._nActiveControlInterpolants++,J=$[U];if(J===void 0)J=new v9(new Float32Array(2),new Float32Array(2),1,K4),J.__cacheIndex=U,$[U]=J;return J}_takeBackControlInterpolant($){let U=this._controlInterpolants,J=$.__cacheIndex,Q=--this._nActiveControlInterpolants,W=U[Q];$.__cacheIndex=Q,U[Q]=$,W.__cacheIndex=J,U[J]=W}clipAction($,U,J){let Q=U||this._root,W=Q.uuid,K=typeof $==="string"?E8.findByName(Q,$):$,X=K!==null?K.uuid:$,H=this._actionsByClip[X],N=null;if(J===void 0)if(K!==null)J=K.blendMode;else J=2500;if(H!==void 0){let G=H.actionByRoot[W];if(G!==void 0&&G.blendMode===J)return G;if(N=H.knownActions[0],K===null)K=N._clip}if(K===null)return null;let Y=new wH(this,K,U,J);return this._bindAction(Y,N),this._addInactiveAction(Y,X,W),Y}existingAction($,U){let J=U||this._root,Q=J.uuid,W=typeof $==="string"?E8.findByName(J,$):$,K=W?W.uuid:$,X=this._actionsByClip[K];if(X!==void 0)return X.actionByRoot[Q]||null;return null}stopAllAction(){let $=this._actions,U=this._nActiveActions;for(let J=U-1;J>=0;--J)$[J].stop();return this}update($){$*=this.timeScale;let U=this._actions,J=this._nActiveActions,Q=this.time+=$,W=Math.sign($),K=this._accuIndex^=1;for(let N=0;N!==J;++N)U[N]._update(Q,$,W,K);let X=this._bindings,H=this._nActiveBindings;for(let N=0;N!==H;++N)X[N].apply(K);return this}setTime($){this.time=0;for(let U=0;U<this._actions.length;U++)this._actions[U].time=0;return this.update($)}getRoot(){return this._root}uncacheClip($){let U=this._actions,J=$.uuid,Q=this._actionsByClip,W=Q[J];if(W!==void 0){let K=W.knownActions;for(let X=0,H=K.length;X!==H;++X){let N=K[X];this._deactivateAction(N);let Y=N._cacheIndex,G=U[U.length-1];N._cacheIndex=null,N._byClipCacheIndex=null,G._cacheIndex=Y,U[Y]=G,U.pop(),this._removeInactiveBindingsForAction(N)}delete Q[J]}}uncacheRoot($){let U=$.uuid,J=this._actionsByClip;for(let K in J){let X=J[K].actionByRoot,H=X[U];if(H!==void 0)this._deactivateAction(H),this._removeInactiveAction(H)}let Q=this._bindingsByRootAndName,W=Q[U];if(W!==void 0)for(let K in W){let X=W[K];X.restoreOriginalState(),this._removeInactiveBinding(X)}}uncacheAction($,U){let J=this.existingAction($,U);if(J!==null)this._deactivateAction(J),this._removeInactiveAction(J)}}class fW{constructor($=1,U=0,J=0){this.radius=$,this.phi=U,this.theta=J}set($,U,J){return this.radius=$,this.phi=U,this.theta=J,this}copy($){return this.radius=$.radius,this.phi=$.phi,this.theta=$.theta,this}makeSafe(){return this.phi=a$(this.phi,0.000001,Math.PI-0.000001),this}setFromVector3($){return this.setFromCartesianCoords($.x,$.y,$.z)}setFromCartesianCoords($,U,J){if(this.radius=Math.sqrt($*$+U*U+J*J),this.radius===0)this.theta=0,this.phi=0;else this.theta=Math.atan2($,J),this.phi=Math.acos(a$(U/this.radius,-1,1));return this}clone(){return new this.constructor().copy(this)}}class MH{static{MH.prototype.isMatrix2=!0}constructor($,U,J,Q){if(this.elements=[1,0,0,1],$!==void 0)this.set($,U,J,Q)}identity(){return this.set(1,0,0,1),this}fromArray($,U=0){for(let J=0;J<4;J++)this.elements[J]=$[J+U];return this}set($,U,J,Q){let W=this.elements;return W[0]=$,W[2]=U,W[1]=J,W[3]=Q,this}}class l9 extends iU{constructor($,U=null){super();this.object=$,this.domElement=U,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect($){if($===void 0){A$("Controls: connect() now requires an element.");return}if(this.domElement!==null)this.disconnect();this.domElement=$}disconnect(){}dispose(){}update(){}}function BH($,U,J,Q){let W=X4(Q);switch(J){case 1021:return $*U;case 1028:return $*U/W.components*W.byteLength;case 1029:return $*U/W.components*W.byteLength;case 1030:return $*U*2/W.components*W.byteLength;case 1031:return $*U*2/W.components*W.byteLength;case 1022:return $*U*3/W.components*W.byteLength;case 1023:return $*U*4/W.components*W.byteLength;case 1033:return $*U*4/W.components*W.byteLength;case 33776:case 33777:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*8;case 33778:case 33779:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*16;case 35841:case 35843:return Math.max($,16)*Math.max(U,8)/4;case 35840:case 35842:return Math.max($,8)*Math.max(U,8)/2;case 36196:case 37492:case 37488:case 37489:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*8;case 37496:case 37490:case 37491:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*16;case 37808:return Math.floor(($+3)/4)*Math.floor((U+3)/4)*16;case 37809:return Math.floor(($+4)/5)*Math.floor((U+3)/4)*16;case 37810:return Math.floor(($+4)/5)*Math.floor((U+4)/5)*16;case 37811:return Math.floor(($+5)/6)*Math.floor((U+4)/5)*16;case 37812:return Math.floor(($+5)/6)*Math.floor((U+5)/6)*16;case 37813:return Math.floor(($+7)/8)*Math.floor((U+4)/5)*16;case 37814:return Math.floor(($+7)/8)*Math.floor((U+5)/6)*16;case 37815:return Math.floor(($+7)/8)*Math.floor((U+7)/8)*16;case 37816:return Math.floor(($+9)/10)*Math.floor((U+4)/5)*16;case 37817:return Math.floor(($+9)/10)*Math.floor((U+5)/6)*16;case 37818:return Math.floor(($+9)/10)*Math.floor((U+7)/8)*16;case 37819:return Math.floor(($+9)/10)*Math.floor((U+9)/10)*16;case 37820:return Math.floor(($+11)/12)*Math.floor((U+9)/10)*16;case 37821:return Math.floor(($+11)/12)*Math.floor((U+11)/12)*16;case 36492:case 36494:case 36495:return Math.ceil($/4)*Math.ceil(U/4)*16;case 36283:case 36284:return Math.ceil($/4)*Math.ceil(U/4)*8;case 36285:case 36286:return Math.ceil($/4)*Math.ceil(U/4)*16}throw Error(`Unable to determine texture byte length for ${J} format.`)}function X4($){switch($){case 1009:case 1010:return{byteLength:1,components:1};case 1012:case 1011:case 1016:return{byteLength:2,components:1};case 1017:case 1018:return{byteLength:2,components:4};case 1014:case 1013:case 1015:return{byteLength:4,components:1};case 35902:case 35899:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${$}.`)}if(typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"185"}}));if(typeof window<"u")if(window.__THREE__)A$("WARNING: Multiple instances of Three.js being imported.");else window.__THREE__="185";function PZ(){let $=null,U=!1,J=null,Q=null;function W(K,X){J(K,X),Q=$.requestAnimationFrame(W)}return{start:function(){if(U===!0)return;if(J===null)return;if($===null)return;Q=$.requestAnimationFrame(W),U=!0},stop:function(){if($!==null)$.cancelAnimationFrame(Q);U=!1},setAnimationLoop:function(K){J=K},setContext:function(K){$=K}}}function H4($){let U=new WeakMap;function J(H,N){let{array:Y,usage:G}=H,O=Y.byteLength,E=$.createBuffer();$.bindBuffer(N,E),$.bufferData(N,Y,G),H.onUploadCallback();let k;if(Y instanceof Float32Array)k=$.FLOAT;else if(typeof Float16Array<"u"&&Y instanceof Float16Array)k=$.HALF_FLOAT;else if(Y instanceof Uint16Array)if(H.isFloat16BufferAttribute)k=$.HALF_FLOAT;else k=$.UNSIGNED_SHORT;else if(Y instanceof Int16Array)k=$.SHORT;else if(Y instanceof Uint32Array)k=$.UNSIGNED_INT;else if(Y instanceof Int32Array)k=$.INT;else if(Y instanceof Int8Array)k=$.BYTE;else if(Y instanceof Uint8Array)k=$.UNSIGNED_BYTE;else if(Y instanceof Uint8ClampedArray)k=$.UNSIGNED_BYTE;else throw Error("THREE.WebGLAttributes: Unsupported buffer data format: "+Y);return{buffer:E,type:k,bytesPerElement:Y.BYTES_PER_ELEMENT,version:H.version,size:O}}function Q(H,N,Y){let{array:G,updateRanges:O}=N;if($.bindBuffer(Y,H),O.length===0)$.bufferSubData(Y,0,G);else{O.sort((k,I)=>k.start-I.start);let E=0;for(let k=1;k<O.length;k++){let I=O[E],R=O[k];if(R.start<=I.start+I.count+1)I.count=Math.max(I.count,R.start+R.count-I.start);else++E,O[E]=R}O.length=E+1;for(let k=0,I=O.length;k<I;k++){let R=O[k];$.bufferSubData(Y,R.start*G.BYTES_PER_ELEMENT,G,R.start,R.count)}N.clearUpdateRanges()}N.onUploadCallback()}function W(H){if(H.isInterleavedBufferAttribute)H=H.data;return U.get(H)}function K(H){if(H.isInterleavedBufferAttribute)H=H.data;let N=U.get(H);if(N)$.deleteBuffer(N.buffer),U.delete(H)}function X(H,N){if(H.isInterleavedBufferAttribute)H=H.data;if(H.isGLBufferAttribute){let G=U.get(H);if(!G||G.version<H.version)U.set(H,{buffer:H.buffer,type:H.type,bytesPerElement:H.elementSize,version:H.version});return}let Y=U.get(H);if(Y===void 0)U.set(H,J(H,N));else if(Y.version<H.version){if(Y.size!==H.array.byteLength)throw Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");Q(Y.buffer,H,N),Y.version=H.version}}return{get:W,remove:K,update:X}}var N4=`#ifdef USE_ALPHAHASH+}`;class bn extends nn{constructor(e){super();if(this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=wx,this.fragmentShader=Tx,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=cr(e.uniforms),this.uniformsGroups=Mx(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 i in this.uniforms){let s=this.uniforms[i].value;if(s&&s.isTexture)t.uniforms[i]={type:"t",value:s.toJSON(e).uuid};else if(s&&s.isColor)t.uniforms[i]={type:"c",value:s.getHex()};else if(s&&s.isVector2)t.uniforms[i]={type:"v2",value:s.toArray()};else if(s&&s.isVector3)t.uniforms[i]={type:"v3",value:s.toArray()};else if(s&&s.isVector4)t.uniforms[i]={type:"v4",value:s.toArray()};else if(s&&s.isMatrix3)t.uniforms[i]={type:"m3",value:s.toArray()};else if(s&&s.isMatrix4)t.uniforms[i]={type:"m4",value:s.toArray()};else t.uniforms[i]={value:s}}if(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 i in this.extensions)if(this.extensions[i]===!0)n[i]=!0;if(Object.keys(n).length>0)t.extensions=n;return t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let i=e.uniforms[n];switch(this.uniforms[n]={},i.type){case"t":this.uniforms[n].value=t[i.value]||null;break;case"c":this.uniforms[n].value=new Le().setHex(i.value);break;case"v2":this.uniforms[n].value=new Pe().fromArray(i.value);break;case"v3":this.uniforms[n].value=new N().fromArray(i.value);break;case"v4":this.uniforms[n].value=new it().fromArray(i.value);break;case"m3":this.uniforms[n].value=new De().fromArray(i.value);break;case"m4":this.uniforms[n].value=new Fe().fromArray(i.value);break;default:this.uniforms[n].value=i.value}}if(e.defines!==void 0)this.defines=e.defines;if(e.vertexShader!==void 0)this.vertexShader=e.vertexShader;if(e.fragmentShader!==void 0)this.fragmentShader=e.fragmentShader;if(e.glslVersion!==void 0)this.glslVersion=e.glslVersion;if(e.extensions!==void 0)for(let n in e.extensions)this.extensions[n]=e.extensions[n];if(e.lights!==void 0)this.lights=e.lights;if(e.clipping!==void 0)this.clipping=e.clipping;return this}}class Tl extends bn{constructor(e){super(e);this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class fi extends nn{constructor(e){super();this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Le(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 Le(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Pe(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 Hn,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}}class un extends fi{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 Pe(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return We(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+0.4*t)/(1-0.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Le(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 Le(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Le(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){if(this._anisotropy>0!==e>0)this.version++;this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){if(this._clearcoat>0!==e>0)this.version++;this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){if(this._iridescence>0!==e>0)this.version++;this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){if(this._dispersion>0!==e>0)this.version++;this._dispersion=e}get sheen(){return this._sheen}set sheen(e){if(this._sheen>0!==e>0)this.version++;this._sheen=e}get transmission(){return this._transmission}set transmission(e){if(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}}class ra extends nn{constructor(e){super();this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Le(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Le(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Pe(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Hn,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=0.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}}class El extends nn{constructor(e){super();this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,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}}class Al extends nn{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}}function Io(e,t){if(!e||e.constructor===t)return e;if(typeof t.BYTES_PER_ELEMENT==="number")return new t(e);return Array.prototype.slice.call(e)}function Ex(e){function t(r,s){return e[r]-e[s]}let n=e.length,i=Array(n);for(let r=0;r!==n;++r)i[r]=r;return i.sort(t),i}function Bh(e,t,n){let i=e.length,r=new e.constructor(i);for(let s=0,o=0;o!==i;++s){let a=n[s]*t;for(let c=0;c!==t;++c)r[o++]=e[a+c]}return r}function Ax(e,t,n,i){let r=1,s=e[0];while(s!==void 0&&s[i]===void 0)s=e[r++];if(s===void 0)return;let o=s[i];if(o===void 0)return;if(Array.isArray(o))do{if(o=s[i],o!==void 0)t.push(s.time),n.push(...o);s=e[r++]}while(s!==void 0);else if(o.toArray!==void 0)do{if(o=s[i],o!==void 0)t.push(s.time),o.toArray(n,n.length);s=e[r++]}while(s!==void 0);else do{if(o=s[i],o!==void 0)t.push(s.time),n.push(o);s=e[r++]}while(s!==void 0)}class di{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,i=t[n],r=t[n-1];e:{t:{let s;n:{i:if(!(e<i)){for(let o=n+2;;){if(i===void 0){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===o)break;if(r=i,i=t[++n],e<i)break t}s=t.length;break n}if(!(e>=r)){let o=t[1];if(e<o)n=2,r=o;for(let a=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(i=r,r=t[--n-1],e>=r)break t}s=n,n=0;break n}break e}while(n<s){let o=n+s>>>1;if(e<t[o])s=o;else n=o+1}if(i=t[n],r=t[n-1],r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,r,i)}return this.interpolate_(n,r,e,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=e*i;for(let s=0;s!==i;++s)t[s]=n[r+s];return t}interpolate_(){throw Error("THREE.Interpolant: Call to abstract method.")}intervalChanged_(){}}class Rl extends di{constructor(e,t,n,i){super(e,t,n,i);this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:2400,endingEnd:2400}}intervalChanged_(e,t,n){let i=this.parameterPositions,r=e-2,s=e+1,o=i[r],a=i[s];if(o===void 0)switch(this.getSettings_().endingStart){case 2401:r=e,o=2*t-n;break;case 2402:r=i.length-2,o=t+i[r]-i[r+1];break;default:r=e,o=n}if(a===void 0)switch(this.getSettings_().endingEnd){case 2401:s=e,a=2*n-t;break;case 2402:s=1,a=n+i[1]-i[0];break;default:s=e-1,a=t}let c=(n-t)*0.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(a-n),this._offsetPrev=r*l,this._offsetNext=s*l}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=e*o,c=a-o,l=this._offsetPrev,u=this._offsetNext,f=this._weightPrev,h=this._weightNext,d=(n-t)/(i-t),g=d*d,b=g*d,p=-f*b+2*f*g-f*d,m=(1+f)*b+(-1.5-2*f)*g+(-0.5+f)*d+1,A=(-1-h)*b+(1.5+h)*g+0.5*d,T=h*b-h*g;for(let v=0;v!==o;++v)r[v]=p*s[l+v]+m*s[c+v]+A*s[a+v]+T*s[u+v];return r}}class sa extends di{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=e*o,c=a-o,l=(n-t)/(i-t),u=1-l;for(let f=0;f!==o;++f)r[f]=s[c+f]*u+s[a+f]*l;return r}}class Cl extends di{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e){return this.copySampleValue_(e-1)}}class Pl extends di{interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=e*o,c=a-o,l=this.inTangents,u=this.outTangents;if(!l||!u){let d=(n-t)/(i-t),g=1-d;for(let b=0;b!==o;++b)r[b]=s[c+b]*g+s[a+b]*d;return r}let f=o*2,h=e-1;for(let d=0;d!==o;++d){let g=s[c+d],b=s[a+d],p=h*f+d*2,m=u[p],A=u[p+1],T=e*f+d*2,v=l[T],w=l[T+1],E=(n-t)/(i-t),R,_,S,F,C;for(let z=0;z<8;z++){R=E*E,_=R*E,S=1-E,F=S*S,C=F*S;let O=C*t+3*F*E*m+3*S*R*v+_*i-n;if(Math.abs(O)<0.0000000001)break;let H=3*F*(m-t)+6*S*E*(v-m)+3*R*(i-v);if(Math.abs(H)<0.0000000001)break;E=E-O/H,E=Math.max(0,Math.min(1,E))}r[d]=C*g+3*F*E*A+3*S*R*w+_*b}return r}}class hn{constructor(e,t,n,i){if(e===void 0)throw Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=Io(t,this.TimeBufferType),this.values=Io(n,this.ValueBufferType),this.setInterpolation(i||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:Io(e.times,Array),values:Io(e.values,Array)};let i=e.getInterpolation();if(i!==e.DefaultInterpolation)n.interpolation=i}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Cl(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new sa(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Rl(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new Pl(this.times,this.values,this.getValueSize(),e);if(this.settings)t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents;return t}setInterpolation(e){let t;switch(e){case 2300:t=this.InterpolantFactoryMethodDiscrete;break;case 2301:t=this.InterpolantFactoryMethodLinear;break;case 2302:t=this.InterpolantFactoryMethodSmooth;break;case 2303: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 Error(n);return Me("KeyframeTrack:",n),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;case this.InterpolantFactoryMethodLinear:return 2301;case this.InterpolantFactoryMethodSmooth:return 2302;case this.InterpolantFactoryMethodBezier:return 2303}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]*=e}return this}trim(e,t){let n=this.times,i=n.length,r=0,s=i-1;while(r!==i&&n[r]<e)++r;while(s!==-1&&n[s]>t)--s;if(++s,r!==0||s!==i){if(r>=s)s=Math.max(s,1),r=s-1;let o=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*o,s*o)}return this}validate(){let e=!0,t=this.getValueSize();if(t-Math.floor(t)!==0)Ne("KeyframeTrack: Invalid value size in track.",this),e=!1;let n=this.times,i=this.values,r=n.length;if(r===0)Ne("KeyframeTrack: Track is empty.",this),e=!1;let s=null;for(let o=0;o!==r;o++){let a=n[o];if(typeof a==="number"&&isNaN(a)){Ne("KeyframeTrack: Time is not a valid number.",this,o,a),e=!1;break}if(s!==null&&s>a){Ne("KeyframeTrack: Out of order keys.",this,o,a,s),e=!1;break}s=a}if(i!==void 0){if(k0(i))for(let o=0,a=i.length;o!==a;++o){let c=i[o];if(isNaN(c)){Ne("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(),i=this.getInterpolation()===2302,r=e.length-1,s=1;for(let o=1;o<r;++o){let a=!1,c=e[o],l=e[o+1];if(c!==l&&(o!==1||c!==e[0]))if(!i){let u=o*n,f=u-n,h=u+n;for(let d=0;d!==n;++d){let g=t[u+d];if(g!==t[f+d]||g!==t[h+d]){a=!0;break}}}else a=!0;if(a){if(o!==s){e[s]=e[o];let u=o*n,f=s*n;for(let h=0;h!==n;++h)t[f+h]=t[u+h]}++s}}if(r>0){e[s]=e[r];for(let o=r*n,a=s*n,c=0;c!==n;++c)t[a+c]=t[o+c];++s}if(s!==e.length)this.times=e.slice(0,s),this.values=t.slice(0,s*n);else this.times=e,this.values=t;return this}clone(){let e=this.times.slice(),t=this.values.slice(),i=new this.constructor(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}}hn.prototype.ValueTypeName="";hn.prototype.TimeBufferType=Float32Array;hn.prototype.ValueBufferType=Float32Array;hn.prototype.DefaultInterpolation=2301;class Ui extends hn{constructor(e,t,n){super(e,t,n)}}Ui.prototype.ValueTypeName="bool";Ui.prototype.ValueBufferType=Array;Ui.prototype.DefaultInterpolation=2300;Ui.prototype.InterpolantFactoryMethodLinear=void 0;Ui.prototype.InterpolantFactoryMethodSmooth=void 0;class oa extends hn{constructor(e,t,n,i){super(e,t,n,i)}}oa.prototype.ValueTypeName="color";class Oi extends hn{constructor(e,t,n,i){super(e,t,n,i)}}Oi.prototype.ValueTypeName="number";class Il extends di{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=(n-t)/(i-t),c=e*o;for(let l=c+o;c!==l;c+=4)zt.slerpFlat(r,0,s,c-o,s,c,a);return r}}class Fi extends hn{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new Il(this.times,this.values,this.getValueSize(),e)}}Fi.prototype.ValueTypeName="quaternion";Fi.prototype.InterpolantFactoryMethodSmooth=void 0;class zi extends hn{constructor(e,t,n){super(e,t,n)}}zi.prototype.ValueTypeName="string";zi.prototype.ValueBufferType=Array;zi.prototype.DefaultInterpolation=2300;zi.prototype.InterpolantFactoryMethodLinear=void 0;zi.prototype.InterpolantFactoryMethodSmooth=void 0;class lr extends hn{constructor(e,t,n,i){super(e,t,n,i)}}lr.prototype.ValueTypeName="vector";class zr{constructor(e="",t=-1,n=[],i=2500){if(this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=Cn(),this.userData={},this.duration<0)this.resetDuration()}static parse(e){let t=[],n=e.tracks,i=1/(e.fps||1);for(let s=0,o=n.length;s!==o;++s)t.push(Cx(n[s]).scale(i));let r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r.userData=JSON.parse(e.userData||"{}"),r}static toJSON(e){let t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let r=0,s=n.length;r!==s;++r)t.push(hn.toJSON(n[r]));return i}static CreateFromMorphTargetSequence(e,t,n,i){let r=t.length,s=[];for(let o=0;o<r;o++){let a=[],c=[];a.push((o+r-1)%r,o,(o+1)%r),c.push(0,1,0);let l=Ex(a);if(a=Bh(a,1,l),c=Bh(c,1,l),!i&&a[0]===0)a.push(r),c.push(c[0]);s.push(new Oi(".morphTargetInfluences["+t[o].name+"]",a,c).scale(1/n))}return new this(e,-1,s)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let i=e;n=i.geometry&&i.geometry.animations||i.animations}for(let i=0;i<n.length;i++)if(n[i].name===t)return n[i];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let i={},r=/^([\w-]*?)([\d]+)$/;for(let o=0,a=e.length;o<a;o++){let c=e[o],l=c.name.match(r);if(l&&l.length>1){let u=l[1],f=i[u];if(!f)i[u]=f=[];f.push(c)}}let s=[];for(let o in i)s.push(this.CreateFromMorphTargetSequence(o,i[o],t,n));return s}resetDuration(){let e=this.tracks,t=0;for(let n=0,i=e.length;n!==i;++n){let r=this.tracks[n];t=Math.max(t,r.times[r.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)}}function Rx(e){switch(e.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return Oi;case"vector":case"vector2":case"vector3":case"vector4":return lr;case"color":return oa;case"quaternion":return Fi;case"bool":case"boolean":return Ui;case"string":return zi}throw Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}function Cx(e){if(e.type===void 0)throw Error("THREE.KeyframeTrack: track type undefined, can not parse");let t=Rx(e.type);if(e.times===void 0){let n=[],i=[];Ax(e.keys,n,i,"value"),e.times=n,e.values=i}if(t.parse!==void 0)return t.parse(e);else return new t(e.name,e.times,e.values,e.interpolation)}var Gn={enabled:!1,files:{},add:function(e,t){if(this.enabled===!1)return;if(Gh(e))return;this.files[e]=t},get:function(e){if(this.enabled===!1)return;if(Gh(e))return;return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function Gh(e){try{let t=e.slice(e.indexOf(":")+1);return new URL(t).protocol==="blob:"}catch(t){return!1}}class Ds{constructor(e,t,n){let i=this,r=!1,s=0,o=0,a=void 0,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(l){if(o++,r===!1){if(i.onStart!==void 0)i.onStart(l,s,o)}r=!0},this.itemEnd=function(l){if(s++,i.onProgress!==void 0)i.onProgress(l,s,o);if(s===o){if(r=!1,i.onLoad!==void 0)i.onLoad()}},this.itemError=function(l){if(i.onError!==void 0)i.onError(l)},this.resolveURL=function(l){if(l=l.normalize("NFC"),a)return a(l);return l},this.setURLModifier=function(l){return a=l,this},this.addHandler=function(l,u){return c.push(l,u),this},this.removeHandler=function(l){let u=c.indexOf(l);if(u!==-1)c.splice(u,2);return this},this.getHandler=function(l){for(let u=0,f=c.length;u<f;u+=2){let h=c[u],d=c[u+1];if(h.global)h.lastIndex=0;if(h.test(l))return d}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){if(!this._abortController)this._abortController=new AbortController;return this._abortController}}var Xf=new Ds;class pi{constructor(e){if(this.manager=e!==void 0?e:Xf,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(i,r){n.load(e,i,t,r)})}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}}pi.DEFAULT_MATERIAL_NAME="__DEFAULT";var ci={};class qf extends Error{constructor(e,t){super(e);this.response=t}}class Us extends pi{constructor(e){super(e);this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,t,n,i){if(e===void 0)e="";if(this.path!==void 0)e=this.path+e;e=this.manager.resolveURL(e);let r=Gn.get(`file:${e}`);if(r!==void 0){this.manager.itemStart(e),setTimeout(()=>{if(t)t(r);this.manager.itemEnd(e)},0);return}if(ci[e]!==void 0){ci[e].push({onLoad:t,onProgress:n,onError:i});return}ci[e]=[],ci[e].push({onLoad:t,onProgress:n,onError:i});let s=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,a=this.responseType;fetch(s).then((c)=>{if(c.status===200||c.status===0){if(c.status===0)Me("FileLoader: HTTP Status 0 received.");if(typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;let l=ci[e],u=c.body.getReader(),f=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),h=f?parseInt(f):0,d=h!==0,g=0,b=new ReadableStream({start(p){m();function m(){u.read().then(({done:A,value:T})=>{if(A)p.close();else{g+=T.byteLength;let v=new ProgressEvent("progress",{lengthComputable:d,loaded:g,total:h});for(let w=0,E=l.length;w<E;w++){let R=l[w];if(R.onProgress)R.onProgress(v)}p.enqueue(T),m()}},(A)=>{p.error(A)})}}});return new Response(b)}else throw new qf(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then((c)=>{switch(a){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then((l)=>new DOMParser().parseFromString(l,o));case"json":return c.json();default:if(o==="")return c.text();else{let u=/charset="?([^;"\s]*)"?/i.exec(o),f=u&&u[1]?u[1].toLowerCase():void 0,h=new TextDecoder(f);return c.arrayBuffer().then((d)=>h.decode(d))}}}).then((c)=>{Gn.add(`file:${e}`,c);let l=ci[e];delete ci[e];for(let u=0,f=l.length;u<f;u++){let h=l[u];if(h.onLoad)h.onLoad(c)}}).catch((c)=>{let l=ci[e];if(l===void 0)throw this.manager.itemError(e),c;delete ci[e];for(let u=0,f=l.length;u<f;u++){let h=l[u];if(h.onError)h.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}}var Lr=new WeakMap;class Ll extends pi{constructor(e){super(e)}load(e,t,n,i){if(this.path!==void 0)e=this.path+e;e=this.manager.resolveURL(e);let r=this,s=Gn.get(`image:${e}`);if(s!==void 0){if(s.complete===!0)r.manager.itemStart(e),setTimeout(function(){if(t)t(s);r.manager.itemEnd(e)},0);else{let u=Lr.get(s);if(u===void 0)u=[],Lr.set(s,u);u.push({onLoad:t,onError:i})}return s}let o=Or("img");function a(){if(l(),t)t(this);let u=Lr.get(this)||[];for(let f=0;f<u.length;f++){let h=u[f];if(h.onLoad)h.onLoad(this)}Lr.delete(this),r.manager.itemEnd(e)}function c(u){if(l(),i)i(u);Gn.remove(`image:${e}`);let f=Lr.get(this)||[];for(let h=0;h<f.length;h++){let d=f[h];if(d.onError)d.onError(u)}Lr.delete(this),r.manager.itemError(e),r.manager.itemEnd(e)}function l(){o.removeEventListener("load",a,!1),o.removeEventListener("error",c,!1)}if(o.addEventListener("load",a,!1),o.addEventListener("error",c,!1),e.slice(0,5)!=="data:"){if(this.crossOrigin!==void 0)o.crossOrigin=this.crossOrigin}return Gn.add(`image:${e}`,o),r.manager.itemStart(e),o.src=e,o}}class aa extends pi{constructor(e){super(e)}load(e,t,n,i){let r=new St,s=new Ll(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(o){if(r.image=o,r.needsUpdate=!0,t!==void 0)t(r)},n,i),r}}class Jr extends ot{constructor(e,t=1){super();this.isLight=!0,this.type="Light",this.color=new Le(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}}class ca extends Jr{constructor(e,t,n){super(e,n);this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(ot.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Le(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}}var _c=new Fe,Hh=new N,Vh=new N;class la{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 Pe(512,512),this.mapType=1009,this.map=null,this.mapPass=null,this.matrix=new Fe,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Ps,this._frameExtents=new Pe(1,1),this._viewportCount=1,this._viewports=[new it(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;if(Hh.setFromMatrixPosition(e.matrixWorld),t.position.copy(Hh),Vh.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Vh),t.updateMatrixWorld(),_c.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(_c,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===2001||t.reversedDepth)n.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,1,0,0,0,0,1);else n.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1);n.multiply(_c)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){if(this.map)this.map.dispose();if(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={};if(this.intensity!==1)e.intensity=this.intensity;if(this.bias!==0)e.bias=this.bias;if(this.normalBias!==0)e.normalBias=this.normalBias;if(this.radius!==1)e.radius=this.radius;if(this.mapSize.x!==512||this.mapSize.y!==512)e.mapSize=this.mapSize.toArray();return e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}var Lo=new N,No=new zt,kn=new N;class ua extends ot{constructor(){super();this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Fe,this.projectionMatrix=new Fe,this.projectionMatrixInverse=new Fe,this.coordinateSystem=2000,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){if(super.updateMatrixWorld(e),this.matrixWorld.decompose(Lo,No,kn),kn.x===1&&kn.y===1&&kn.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(Lo,No,kn.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){if(super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(Lo,No,kn),kn.x===1&&kn.y===1&&kn.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(Lo,No,kn.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}var Ti=new N,Wh=new Pe,$h=new Pe;class Pt extends ua{constructor(e=50,t=1,n=0.1,i=2000){super();this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,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=0.5*this.getFilmHeight()/e;this.fov=er*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(ps*0.5*this.fov);return 0.5*this.getFilmHeight()/e}getEffectiveFOV(){return er*2*Math.atan(Math.tan(ps*0.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){Ti.set(-1,-1,0.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ti.x,Ti.y).multiplyScalar(-e/Ti.z),Ti.set(1,1,0.5).applyMatrix4(this.projectionMatrixInverse),n.set(Ti.x,Ti.y).multiplyScalar(-e/Ti.z)}getViewSize(e,t){return this.getViewBounds(e,Wh,$h),t.subVectors($h,Wh)}setViewOffset(e,t,n,i,r,s){if(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=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null)this.view.enabled=!1;this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(ps*0.5*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-0.5*i,s=this.view;if(this.view!==null&&this.view.enabled){let{fullWidth:a,fullHeight:c}=s;r+=s.offsetX*i/a,t-=s.offsetY*n/c,i*=s.width/a,n*=s.height/c}let o=this.filmOffset;if(o!==0)r+=e*o/this.getFilmWidth();this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);if(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);return t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class Yf extends la{constructor(){super(new Pt(50,1,0.5,500));this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=er*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;if(n!==t.fov||i!==t.aspect||r!==t.far)t.fov=n,t.aspect=i,t.far=r,t.updateProjectionMatrix();super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class ha extends Jr{constructor(e,t,n=0,i=Math.PI/3,r=0,s=2){super(e,t);this.isSpotLight=!0,this.type="SpotLight",this.position.copy(ot.DEFAULT_UP),this.updateMatrix(),this.target=new ot,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new Yf}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);if(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;return t.object.shadow=this.shadow.toJSON(),t}}class jf extends la{constructor(){super(new Pt(90,1,0.5,500));this.isPointLightShadow=!0}}class Kr extends Jr{constructor(e,t,n=0,i=2){super(e,t);this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new jf}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}}class ur extends ua{constructor(e=-1,t=1,n=1,i=-1,r=0.1,s=2000){super();this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=r,this.far=s,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,i,r,s){if(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=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){if(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,i=(this.top+this.bottom)/2,r=n-e,s=n+e,o=i+t,a=i-t;if(this.view!==null&&this.view.enabled){let c=(this.right-this.left)/this.view.fullWidth/this.zoom,l=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=c*this.view.offsetX,s=r+c*this.view.width,o-=l*this.view.offsetY,a=o-l*this.view.height}this.projectionMatrix.makeOrthographic(r,s,o,a,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);if(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);return t}}class Jf extends la{constructor(){super(new ur(-5,5,5,-5,0.5,500));this.isDirectionalLightShadow=!0}}class Qr extends Jr{constructor(e,t){super(e,t);this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ot.DEFAULT_UP),this.updateMatrix(),this.target=new ot,this.shadow=new Jf}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}}class ki{static extractUrlBase(e){let t=e.lastIndexOf("/");if(t===-1)return"./";return e.slice(0,t+1)}static resolveURL(e,t){if(typeof e!=="string"||e==="")return"";if(/^https?:\/\//i.test(t)&&/^\//.test(e))t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1");if(/^(https?:)?\/\//i.test(e))return e;if(/^data:.*,.*$/i.test(e))return e;if(/^blob:.*$/i.test(e))return e;return t+e}}var xc=new WeakMap;class fa extends pi{constructor(e){super(e);if(this.isImageBitmapLoader=!0,typeof createImageBitmap>"u")Me("ImageBitmapLoader: createImageBitmap() not supported.");if(typeof fetch>"u")Me("ImageBitmapLoader: fetch() not supported.");this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,i){if(e===void 0)e="";if(this.path!==void 0)e=this.path+e;e=this.manager.resolveURL(e);let r=this,s=Gn.get(`image-bitmap:${e}`);if(s!==void 0){if(r.manager.itemStart(e),s.then){s.then((c)=>{if(xc.has(s)===!0){if(i)i(xc.get(s));r.manager.itemError(e),r.manager.itemEnd(e)}else{if(t)t(c);r.manager.itemEnd(e)}});return}setTimeout(function(){if(t)t(s);r.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 a=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(c){if(Gn.add(`image-bitmap:${e}`,c),t)t(c);r.manager.itemEnd(e)}).catch(function(c){if(i)i(c);xc.set(a,c),Gn.remove(`image-bitmap:${e}`),r.manager.itemError(e),r.manager.itemEnd(e)});Gn.add(`image-bitmap:${e}`,a),r.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}var Nr=-90,Dr=1;class Nl extends ot{constructor(e,t,n){super();this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new Pt(Nr,Dr,e,t);i.layers=this.layers,this.add(i);let r=new Pt(Nr,Dr,e,t);r.layers=this.layers,this.add(r);let s=new Pt(Nr,Dr,e,t);s.layers=this.layers,this.add(s);let o=new Pt(Nr,Dr,e,t);o.layers=this.layers,this.add(o);let a=new Pt(Nr,Dr,e,t);a.layers=this.layers,this.add(a);let c=new Pt(Nr,Dr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,o,a]=t;for(let c of t)this.remove(c);if(e===2000)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1);else throw Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let c of t)this.add(c),c.updateMatrixWorld()}update(e,t){if(this.parent===null)this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:i}=this;if(this.coordinateSystem!==e.coordinateSystem)this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem();let[r,s,o,a,c,l]=this.children,u=e.getRenderTarget(),f=e.getActiveCubeFace(),h=e.getActiveMipmapLevel(),d=e.xr.enabled;e.xr.enabled=!1;let g=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let b=!1;if(e.isWebGLRenderer===!0)b=e.state.buffers.depth.getReversed();else b=e.reversedDepthBuffer;if(e.setRenderTarget(n,0,i),b&&e.autoClear===!1)e.clearDepth();if(e.render(t,r),e.setRenderTarget(n,1,i),b&&e.autoClear===!1)e.clearDepth();if(e.render(t,s),e.setRenderTarget(n,2,i),b&&e.autoClear===!1)e.clearDepth();if(e.render(t,o),e.setRenderTarget(n,3,i),b&&e.autoClear===!1)e.clearDepth();if(e.render(t,a),e.setRenderTarget(n,4,i),b&&e.autoClear===!1)e.clearDepth();if(e.render(t,c),n.texture.generateMipmaps=g,e.setRenderTarget(n,5,i),b&&e.autoClear===!1)e.clearDepth();e.render(t,l),e.setRenderTarget(u,f,h),e.xr.enabled=d,n.texture.needsPMREMUpdate=!0}}class Dl extends Pt{constructor(e=[]){super();this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Ul{constructor(e,t,n){this.binding=e,this.valueSize=n;let i,r,s;switch(t){case"quaternion":i=this._slerp,r=this._slerpAdditive,s=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case"string":case"bool":i=this._select,r=this._select,s=this._setAdditiveIdentityOther,this.buffer=Array(n*5);break;default:i=this._lerp,r=this._lerpAdditive,s=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=r,this._setIdentity=s,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,i=this.valueSize,r=e*i+i,s=this.cumulativeWeight;if(s===0){for(let o=0;o!==i;++o)n[r+o]=n[o];s=t}else{s+=t;let o=t/s;this._mixBufferRegion(n,r,0,o,i)}this.cumulativeWeight=s}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,i=n*this._addIndex;if(this.cumulativeWeightAdditive===0)this._setIdentity();this._mixBufferRegionAdditive(t,i,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,i=e*t+t,r=this.cumulativeWeight,s=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){let a=t*this._origIndex;this._mixBufferRegion(n,i,a,1-r,t)}if(s>0)this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let a=t,c=t+t;a!==c;++a)if(n[a]!==n[a+t]){o.setValue(n,i);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,i=n*this._origIndex;e.getValue(t,i);for(let r=n,s=i;r!==s;++r)t[r]=t[i+r%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,i,r){if(i>=0.5)for(let s=0;s!==r;++s)e[t+s]=e[n+s]}_slerp(e,t,n,i){zt.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,r){let s=this._workIndex*r;zt.multiplyQuaternionsFlat(e,s,e,t,e,n),zt.slerpFlat(e,t,e,t,e,s,i)}_lerp(e,t,n,i,r){let s=1-i;for(let o=0;o!==r;++o){let a=t+o;e[a]=e[a]*s+e[n+o]*i}}_lerpAdditive(e,t,n,i,r){for(let s=0;s!==r;++s){let o=t+s;e[o]=e[o]+e[n+s]*i}}}var Ol="\\[\\]\\.:\\/",Px=new RegExp("["+Ol+"]","g"),Fl="[^"+Ol+"]",Ix="[^"+Ol.replace("\\.","")+"]",Lx=/((?:WC+[\/:])*)/.source.replace("WC",Fl),Nx=/(WCOD+)?/.source.replace("WCOD",Ix),Dx=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Fl),Ux=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Fl),Ox=new RegExp("^"+Lx+Nx+Dx+Ux+"$"),Fx=["material","materials","bones","map"];class Kf{constructor(e,t,n){let i=n||et.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,i=this._bindings[n];if(i!==void 0)i.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++i)n[i].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()}}class et{constructor(e,t,n){this.path=t,this.parsedPath=n||et.parseTrackName(t),this.node=et.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){if(!(e&&e.isAnimationObjectGroup))return new et(e,t,n);else return new et.Composite(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Px,"")}static parseTrackName(e){let t=Ox.exec(e);if(t===null)throw Error("THREE.PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){let r=n.nodeName.substring(i+1);if(Fx.indexOf(r)!==-1)n.nodeName=n.nodeName.substring(0,i),n.objectName=r}if(n.propertyName===null||n.propertyName.length===0)throw Error("THREE.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(r){for(let s=0;s<r.length;s++){let o=r[s];if(o.name===t||o.uuid===t)return o;let a=n(o.children);if(a)return a}return null},i=n(e.children);if(i)return i}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 i=0,r=n.length;i!==r;++i)e[t++]=n[i]}_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 i=0,r=n.length;i!==r;++i)n[i]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,r=n.length;i!==r;++i)n[i]=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,{objectName:n,propertyName:i,propertyIndex:r}=t;if(!e)e=et.findNode(this.rootNode,t.nodeName),this.node=e;if(this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){Me("PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let c=t.objectIndex;switch(n){case"materials":if(!e.material){Ne("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){Ne("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){Ne("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let l=0;l<e.length;l++)if(e[l].name===c){c=l;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){Ne("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){Ne("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){Ne("PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(c!==void 0){if(e[c]===void 0){Ne("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[c]}}let s=e[i];if(s===void 0){let c=t.nodeName;Ne("PropertyBinding: Trying to update property for track: "+c+"."+i+" but it wasn't found.",e);return}let o=this.Versioning.None;if(this.targetObject=e,e.isMaterial===!0)o=this.Versioning.NeedsUpdate;else if(e.isObject3D===!0)o=this.Versioning.MatrixWorldNeedsUpdate;let a=this.BindingType.Direct;if(r!==void 0){if(i==="morphTargetInfluences"){if(!e.geometry){Ne("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){Ne("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}if(e.morphTargetDictionary[r]!==void 0)r=e.morphTargetDictionary[r]}a=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=r}else if(s.fromArray!==void 0&&s.toArray!==void 0)a=this.BindingType.HasFromToArray,this.resolvedProperty=s;else if(Array.isArray(s))a=this.BindingType.EntireArray,this.resolvedProperty=s;else this.propertyName=i;this.getValue=this.GetterByBindingType[a],this.setValue=this.SetterByBindingTypeAndVersioning[a][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}et.Composite=Kf;et.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};et.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};et.prototype.GetterByBindingType=[et.prototype._getValue_direct,et.prototype._getValue_array,et.prototype._getValue_arrayElement,et.prototype._getValue_toArray];et.prototype.SetterByBindingTypeAndVersioning=[[et.prototype._setValue_direct,et.prototype._setValue_direct_setNeedsUpdate,et.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[et.prototype._setValue_array,et.prototype._setValue_array_setNeedsUpdate,et.prototype._setValue_array_setMatrixWorldNeedsUpdate],[et.prototype._setValue_arrayElement,et.prototype._setValue_arrayElement_setNeedsUpdate,et.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[et.prototype._setValue_fromArray,et.prototype._setValue_fromArray_setNeedsUpdate,et.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class zl{constructor(e,t,n=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=i;let r=t.tracks,s=r.length,o=Array(s),a={endingStart:2400,endingEnd:2400};for(let c=0;c!==s;++c){let l=r[c].createInterpolant(null);o[c]=l,l.settings=a}this._interpolantSettings=a,this._interpolants=o,this._propertyBindings=Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._restoreTimeScale=null,this._weightInterpolant=null,this.loop=2201,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 i=this._clip.duration,r=e._clip.duration,s=r/i,o=i/r;e._restoreTimeScale=e.timeScale,this._restoreTimeScale=this.timeScale,e.warp(1,s,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;if(e!==null)this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e);return 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 i=this._mixer,r=i.time,s=this.timeScale,o=this._timeScaleInterpolant;if(o===null)o=i._lendControlInterpolant(),this._timeScaleInterpolant=o;let a=o.parameterPositions,c=o.sampleValues;return a[0]=r,a[1]=r+n,c[0]=e/s,c[1]=t/s,this}stopWarping(){let e=this._timeScaleInterpolant;if(e!==null)this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e);return this._restoreTimeScale=null,this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,i){if(!this.enabled){this._updateWeight(e);return}let r=this._startTime;if(r!==null){let a=(e-r)*n;if(a<0||n===0)t=0;else this._startTime=null,t=n*a}t*=this._updateTimeScale(e);let s=this._updateTime(t),o=this._updateWeight(e);if(o>0){let a=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case 2501:for(let l=0,u=a.length;l!==u;++l)a[l].evaluate(s),c[l].accumulateAdditive(o);break;case 2500:default:for(let l=0,u=a.length;l!==u;++l)a[l].evaluate(s),c[l].accumulate(i,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let i=n.evaluate(e)[0];if(t*=i,e>n.parameterPositions[1]){if(this.stopFading(),i===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 i=n.evaluate(e)[0];if(t*=i,e>n.parameterPositions[1]){if(t===0)this.paused=!0;else{if(this._restoreTimeScale!==null)t=this._restoreTimeScale;this.timeScale=t}this.stopWarping()}}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,i=this.time+e,r=this._loopCount,s=n===2202;if(e===0){if(r===-1)return i;return s&&(r&1)===1?t-i:i}if(n===2200){if(r===-1)this._loopCount=0,this._setEndings(!0,!0,!1);e:{if(i>=t)i=t;else if(i<0)i=0;else{this.time=i;break e}if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(r===-1)if(e>=0)r=0,this._setEndings(!0,this.repetitions===0,s);else this._setEndings(this.repetitions===0,!0,s);if(i>=t||i<0){let o=Math.floor(i/t);i-=t*o,r+=Math.abs(o);let a=this.repetitions-r;if(a<=0){if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1})}else{if(a===1){let c=e<0;this._setEndings(c,!c,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this._loopCount=r,this.time=i;if(s&&(r&1)===1)return t-i}return i}_setEndings(e,t,n){let i=this._interpolantSettings;if(n)i.endingStart=2401,i.endingEnd=2401;else{if(e)i.endingStart=this.zeroSlopeAtStart?2401:2400;else i.endingStart=2402;if(t)i.endingEnd=this.zeroSlopeAtEnd?2401:2400;else i.endingEnd=2402}}_scheduleFading(e,t,n){let i=this._mixer,r=i.time,s=this._weightInterpolant;if(s===null)s=i._lendControlInterpolant(),this._weightInterpolant=s;let o=s.parameterPositions,a=s.sampleValues;return o[0]=r,a[0]=t,o[1]=r+e,a[1]=n,this}}var zx=new Float32Array(1);class da extends Nn{constructor(e){super();if(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,i=e._clip.tracks,r=i.length,{_propertyBindings:s,_interpolants:o}=e,a=n.uuid,c=this._bindingsByRootAndName,l=c[a];if(l===void 0)l={},c[a]=l;for(let u=0;u!==r;++u){let f=i[u],h=f.name,d=l[h];if(d!==void 0)++d.referenceCount,s[u]=d;else{if(d=s[u],d!==void 0){if(d._cacheIndex===null)++d.referenceCount,this._addInactiveBinding(d,a,h);continue}let g=t&&t._propertyBindings[u].binding.parsedPath;d=new Ul(et.create(n,h,g),f.ValueTypeName,f.getValueSize()),++d.referenceCount,this._addInactiveBinding(d,a,h),s[u]=d}o[u].resultBuffer=d.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let n=(e._localRoot||this._root).uuid,i=e._clip.uuid,r=this._actionsByClip[i];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,i,n)}let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let r=t[n];if(r.useCount++===0)this._lendBinding(r),r.saveOriginalState()}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let r=t[n];if(--r.useCount===0)r.restoreOriginalState(),this._takeBackBinding(r)}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 i=this._actions,r=this._actionsByClip,s=r[t];if(s===void 0)s={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,r[t]=s;else{let o=s.knownActions;e._byClipCacheIndex=o.length,o.push(e)}e._cacheIndex=i.length,i.push(e),s.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],i=e._cacheIndex;n._cacheIndex=i,t[i]=n,t.pop(),e._cacheIndex=null;let r=e._clip.uuid,s=this._actionsByClip,o=s[r],a=o.knownActions,c=a[a.length-1],l=e._byClipCacheIndex;c._byClipCacheIndex=l,a[l]=c,a.pop(),e._byClipCacheIndex=null;let u=o.actionByRoot,f=(e._localRoot||this._root).uuid;if(delete u[f],a.length===0)delete s[r];this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let r=t[n];if(--r.referenceCount===0)this._removeInactiveBinding(r)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,i=this._nActiveActions++,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,i=--this._nActiveActions,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_addInactiveBinding(e,t,n){let i=this._bindingsByRootAndName,r=this._bindings,s=i[t];if(s===void 0)s={},i[t]=s;s[n]=e,e._cacheIndex=r.length,r.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,i=n.rootNode.uuid,r=n.path,s=this._bindingsByRootAndName,o=s[i],a=t[t.length-1],c=e._cacheIndex;if(a._cacheIndex=c,t[c]=a,t.pop(),delete o[r],Object.keys(o).length===0)delete s[i]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,i=this._nActiveBindings++,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,i=--this._nActiveBindings,r=t[i];e._cacheIndex=i,t[i]=e,r._cacheIndex=n,t[n]=r}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];if(n===void 0)n=new sa(new Float32Array(2),new Float32Array(2),1,zx),n.__cacheIndex=t,e[t]=n;return n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,i=--this._nActiveControlInterpolants,r=t[i];e.__cacheIndex=i,t[i]=e,r.__cacheIndex=n,t[n]=r}clipAction(e,t,n){let i=t||this._root,r=i.uuid,s=typeof e==="string"?zr.findByName(i,e):e,o=s!==null?s.uuid:e,a=this._actionsByClip[o],c=null;if(n===void 0)if(s!==null)n=s.blendMode;else n=2500;if(a!==void 0){let u=a.actionByRoot[r];if(u!==void 0&&u.blendMode===n)return u;if(c=a.knownActions[0],s===null)s=c._clip}if(s===null)return null;let l=new zl(this,s,t,n);return this._bindAction(l,c),this._addInactiveAction(l,o,r),l}existingAction(e,t){let n=t||this._root,i=n.uuid,r=typeof e==="string"?zr.findByName(n,e):e,s=r?r.uuid:e,o=this._actionsByClip[s];if(o!==void 0)return o.actionByRoot[i]||null;return 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,i=this.time+=e,r=Math.sign(e),s=this._accuIndex^=1;for(let c=0;c!==n;++c)t[c]._update(i,e,r,s);let o=this._bindings,a=this._nActiveBindings;for(let c=0;c!==a;++c)o[c].apply(s);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,i=this._actionsByClip,r=i[n];if(r!==void 0){let s=r.knownActions;for(let o=0,a=s.length;o!==a;++o){let c=s[o];this._deactivateAction(c);let l=c._cacheIndex,u=t[t.length-1];c._cacheIndex=null,c._byClipCacheIndex=null,u._cacheIndex=l,t[l]=u,t.pop(),this._removeInactiveBindingsForAction(c)}delete i[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let s in n){let o=n[s].actionByRoot,a=o[t];if(a!==void 0)this._deactivateAction(a),this._removeInactiveAction(a)}let i=this._bindingsByRootAndName,r=i[t];if(r!==void 0)for(let s in r){let o=r[s];o.restoreOriginalState(),this._removeInactiveBinding(o)}}uncacheAction(e,t){let n=this.existingAction(e,t);if(n!==null)this._deactivateAction(n),this._removeInactiveAction(n)}}class Os{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=We(this.phi,0.000001,Math.PI-0.000001),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){if(this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0)this.theta=0,this.phi=0;else this.theta=Math.atan2(e,n),this.phi=Math.acos(We(t/this.radius,-1,1));return this}clone(){return new this.constructor().copy(this)}}class kl{static{kl.prototype.isMatrix2=!0}constructor(e,t,n,i){if(this.elements=[1,0,0,1],e!==void 0)this.set(e,t,n,i)}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,i){let r=this.elements;return r[0]=e,r[2]=t,r[1]=n,r[3]=i,this}}class pa extends Nn{constructor(e,t=null){super();this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){Me("Controls: connect() now requires an element.");return}if(this.domElement!==null)this.disconnect();this.domElement=e}disconnect(){}dispose(){}update(){}}function Bl(e,t,n,i){let r=kx(i);switch(n){case 1021:return e*t;case 1028:return e*t/r.components*r.byteLength;case 1029:return e*t/r.components*r.byteLength;case 1030:return e*t*2/r.components*r.byteLength;case 1031:return e*t*2/r.components*r.byteLength;case 1022:return e*t*3/r.components*r.byteLength;case 1023:return e*t*4/r.components*r.byteLength;case 1033:return e*t*4/r.components*r.byteLength;case 33776:case 33777:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case 33778:case 33779:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case 35841:case 35843:return Math.max(e,16)*Math.max(t,8)/4;case 35840:case 35842:return Math.max(e,8)*Math.max(t,8)/2;case 36196:case 37492:case 37488:case 37489:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case 37496:case 37490:case 37491:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case 37808:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case 37809:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case 37810:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case 37811:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case 37812:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case 37813:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case 37814:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case 37815:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case 37816:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case 37817:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case 37818:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case 37819:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case 37820:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case 37821:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case 36492:case 36494:case 36495:return Math.ceil(e/4)*Math.ceil(t/4)*16;case 36283:case 36284:return Math.ceil(e/4)*Math.ceil(t/4)*8;case 36285:case 36286:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function kx(e){switch(e){case 1009:case 1010:return{byteLength:1,components:1};case 1012:case 1011:case 1016:return{byteLength:2,components:1};case 1017:case 1018:return{byteLength:2,components:4};case 1014:case 1013:case 1015:return{byteLength:4,components:1};case 35902:case 35899:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}if(typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"185"}}));if(typeof window<"u")if(window.__THREE__)Me("WARNING: Multiple instances of Three.js being imported.");else window.__THREE__="185";function bd(){let e=null,t=!1,n=null,i=null;function r(s,o){n(s,o),i=e.requestAnimationFrame(r)}return{start:function(){if(t===!0)return;if(n===null)return;if(e===null)return;i=e.requestAnimationFrame(r),t=!0},stop:function(){if(e!==null)e.cancelAnimationFrame(i);t=!1},setAnimationLoop:function(s){n=s},setContext:function(s){e=s}}}function Bx(e){let t=new WeakMap;function n(a,c){let{array:l,usage:u}=a,f=l.byteLength,h=e.createBuffer();e.bindBuffer(c,h),e.bufferData(c,l,u),a.onUploadCallback();let d;if(l instanceof Float32Array)d=e.FLOAT;else if(typeof Float16Array<"u"&&l instanceof Float16Array)d=e.HALF_FLOAT;else if(l instanceof Uint16Array)if(a.isFloat16BufferAttribute)d=e.HALF_FLOAT;else d=e.UNSIGNED_SHORT;else if(l instanceof Int16Array)d=e.SHORT;else if(l instanceof Uint32Array)d=e.UNSIGNED_INT;else if(l instanceof Int32Array)d=e.INT;else if(l instanceof Int8Array)d=e.BYTE;else if(l instanceof Uint8Array)d=e.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)d=e.UNSIGNED_BYTE;else throw Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:h,type:d,bytesPerElement:l.BYTES_PER_ELEMENT,version:a.version,size:f}}function i(a,c,l){let{array:u,updateRanges:f}=c;if(e.bindBuffer(l,a),f.length===0)e.bufferSubData(l,0,u);else{f.sort((d,g)=>d.start-g.start);let h=0;for(let d=1;d<f.length;d++){let g=f[h],b=f[d];if(b.start<=g.start+g.count+1)g.count=Math.max(g.count,b.start+b.count-g.start);else++h,f[h]=b}f.length=h+1;for(let d=0,g=f.length;d<g;d++){let b=f[d];e.bufferSubData(l,b.start*u.BYTES_PER_ELEMENT,u,b.start,b.count)}c.clearUpdateRanges()}c.onUploadCallback()}function r(a){if(a.isInterleavedBufferAttribute)a=a.data;return t.get(a)}function s(a){if(a.isInterleavedBufferAttribute)a=a.data;let c=t.get(a);if(c)e.deleteBuffer(c.buffer),t.delete(a)}function o(a,c){if(a.isInterleavedBufferAttribute)a=a.data;if(a.isGLBufferAttribute){let u=t.get(a);if(!u||u.version<a.version)t.set(a,{buffer:a.buffer,type:a.type,bytesPerElement:a.elementSize,version:a.version});return}let l=t.get(a);if(l===void 0)t.set(a,n(a,c));else if(l.version<a.version){if(l.size!==a.array.byteLength)throw Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");i(l.buffer,a,c),l.version=a.version}}return{get:r,remove:s,update:o}}var Gx=`#ifdef USE_ALPHAHASHif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;-#endif`,Y4=`#ifdef USE_ALPHAHASH+#endif`,Hx=`#ifdef USE_ALPHAHASHconst 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 ) ) ) );@@ -157,20 +157,20 @@: cases.z;return clamp( threshold , 1.0e-6, 1.0 );}-#endif`,G4=`#ifdef USE_ALPHAMAP+#endif`,Vx=`#ifdef USE_ALPHAMAPdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;-#endif`,O4=`#ifdef USE_ALPHAMAP+#endif`,Wx=`#ifdef USE_ALPHAMAPuniform sampler2D alphaMap;-#endif`,E4=`#ifdef USE_ALPHATEST+#endif`,$x=`#ifdef USE_ALPHATEST#ifdef ALPHA_TO_COVERAGEdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );if ( diffuseColor.a == 0.0 ) discard;#elseif ( diffuseColor.a < alphaTest ) discard;#endif-#endif`,k4=`#ifdef USE_ALPHATEST+#endif`,Zx=`#ifdef USE_ALPHATESTuniform float alphaTest;-#endif`,q4=`#ifdef USE_AOMAP+#endif`,Xx=`#ifdef USE_AOMAPfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;reflectedLight.indirectDiffuse *= ambientOcclusion;#if defined( USE_CLEARCOAT )@@ -183,10 +183,10 @@float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );#endif-#endif`,Z4=`#ifdef USE_AOMAP+#endif`,qx=`#ifdef USE_AOMAPuniform sampler2D aoMap;uniform float aoMapIntensity;-#endif`,I4=`#ifdef USE_BATCHING+#endif`,Yx=`#ifdef USE_BATCHING#if ! defined( GL_ANGLE_multi_draw )#define gl_DrawID _gl_DrawIDuniform int _gl_DrawID;@@ -220,15 +220,15 @@int y = j / size;return texelFetch( batchingColorTexture, ivec2( x, y ), 0 );}-#endif`,D4=`#ifdef USE_BATCHING+#endif`,jx=`#ifdef USE_BATCHINGmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );-#endif`,F4=`vec3 transformed = vec3( position );+#endif`,Jx=`vec3 transformed = vec3( position );#ifdef USE_ALPHAHASHvPosition = vec3( position );-#endif`,L4=`vec3 objectNormal = vec3( normal );+#endif`,Kx=`vec3 objectNormal = vec3( normal );#ifdef USE_TANGENTvec3 objectTangent = vec3( tangent.xyz );-#endif`,R4=`float G_BlinnPhong_Implicit( ) {+#endif`,Qx=`float G_BlinnPhong_Implicit( ) {return 0.25;}float D_BlinnPhong( const in float shininess, const in float dotNH ) {@@ -242,7 +242,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vefloat G = G_BlinnPhong_Implicit( );float D = D_BlinnPhong( shininess, dotNH );return F * ( G * D );-} // validated`,V4=`#ifdef USE_IRIDESCENCE+} // validated`,ev=`#ifdef USE_IRIDESCENCEconst mat3 XYZ_TO_REC709 = mat3(3.2404542, -0.9692660, 0.0556434,-1.5371385, 1.8760108, -0.2040259,@@ -305,7 +305,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve}return max( I, vec3( 0.0 ) );}-#endif`,w4=`#ifdef USE_BUMPMAP+#endif`,tv=`#ifdef USE_BUMPMAPuniform sampler2D bumpMap;uniform float bumpScale;vec2 dHdxy_fwd() {@@ -326,7 +326,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vevec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );return normalize( abs( fDet ) * surf_norm - vGrad );}-#endif`,M4=`#if NUM_CLIPPING_PLANES > 0+#endif`,nv=`#if NUM_CLIPPING_PLANES > 0vec4 plane;#ifdef ALPHA_TO_COVERAGEfloat distanceToPlane, distanceGradient;@@ -372,20 +372,20 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in veif ( clipped ) discard;#endif#endif-#endif`,B4=`#if NUM_CLIPPING_PLANES > 0+#endif`,iv=`#if NUM_CLIPPING_PLANES > 0varying vec3 vClipPosition;uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];-#endif`,P4=`#if NUM_CLIPPING_PLANES > 0+#endif`,rv=`#if NUM_CLIPPING_PLANES > 0varying vec3 vClipPosition;-#endif`,z4=`#if NUM_CLIPPING_PLANES > 0+#endif`,sv=`#if NUM_CLIPPING_PLANES > 0vClipPosition = - mvPosition.xyz;-#endif`,_4=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )+#endif`,ov=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )diffuseColor *= vColor;-#endif`,A4=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )+#endif`,av=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )varying vec4 vColor;-#endif`,C4=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+#endif`,cv=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )varying vec4 vColor;-#endif`,S4=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+#endif`,lv=`#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@@ -398,7 +398,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve#endif#ifdef USE_BATCHING_COLORvColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );-#endif`,T4=`#define PI 3.141592653589793+#endif`,uv=`#define PI 3.141592653589793#define PI2 6.283185307179586#define PI_HALF 1.5707963267948966#define RECIPROCAL_PI 0.3183098861837907@@ -469,7 +469,7 @@ vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {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`,v4=`#ifdef ENVMAP_TYPE_CUBE_UV+} // validated`,hv=`#ifdef ENVMAP_TYPE_CUBE_UV#define cubeUV_minMipLevel 4.0#define cubeUV_minTileSize 16.0float getFace( vec3 direction ) {@@ -562,7 +562,7 @@ float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {return vec4( mix( color0, color1, mipF ), 1.0 );}}-#endif`,j4=`vec3 transformedNormal = objectNormal;+#endif`,fv=`vec3 transformedNormal = objectNormal;#ifdef USE_TANGENTvec3 transformedTangent = objectTangent;#endif@@ -588,21 +588,21 @@ transformedNormal = normalMatrix * transformedNormal;#endif#ifdef USE_TANGENTtransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;-#endif`,g4=`#ifdef USE_DISPLACEMENTMAP+#endif`,dv=`#ifdef USE_DISPLACEMENTMAPuniform sampler2D displacementMap;uniform float displacementScale;uniform float displacementBias;-#endif`,b4=`#ifdef USE_DISPLACEMENTMAP+#endif`,pv=`#ifdef USE_DISPLACEMENTMAPtransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );-#endif`,y4=`#ifdef USE_EMISSIVEMAP+#endif`,mv=`#ifdef USE_EMISSIVEMAPvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );#ifdef DECODE_VIDEO_TEXTURE_EMISSIVEemissiveColor = sRGBTransferEOTF( emissiveColor );#endiftotalEmissiveRadiance *= emissiveColor.rgb;-#endif`,x4=`#ifdef USE_EMISSIVEMAP+#endif`,gv=`#ifdef USE_EMISSIVEMAPuniform sampler2D emissiveMap;-#endif`,h4="gl_FragColor = linearToOutputTexel( gl_FragColor );",f4=`vec4 LinearTransferOETF( in vec4 value ) {+#endif`,_v="gl_FragColor = linearToOutputTexel( gl_FragColor );",xv=`vec4 LinearTransferOETF( in vec4 value ) {return value;}vec4 sRGBTransferEOTF( in vec4 value ) {@@ -610,7 +610,7 @@ vec4 sRGBTransferEOTF( in vec4 value ) {}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 );-}`,u4=`#ifdef USE_ENVMAP+}`,vv=`#ifdef USE_ENVMAP#ifdef ENV_WORLDPOSvec3 cameraToFrag;if ( isOrthographic ) {@@ -637,7 +637,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {outgoingLight += envColor.xyz * specularStrength * reflectivity;#endif#endif-#endif`,l4=`#ifdef USE_ENVMAP+#endif`,yv=`#ifdef USE_ENVMAPuniform float envMapIntensity;uniform mat3 envMapRotation;#ifdef ENVMAP_TYPE_CUBE@@ -645,7 +645,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {#elseuniform sampler2D envMap;#endif-#endif`,m4=`#ifdef USE_ENVMAP+#endif`,bv=`#ifdef USE_ENVMAPuniform float reflectivity;#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )#define ENV_WORLDPOS@@ -656,7 +656,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {#elsevarying vec3 vReflect;#endif-#endif`,p4=`#ifdef USE_ENVMAP+#endif`,Sv=`#ifdef USE_ENVMAP#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )#define ENV_WORLDPOS#endif@@ -667,7 +667,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {varying vec3 vReflect;uniform float refractionRatio;#endif-#endif`,d4=`#ifdef USE_ENVMAP+#endif`,Mv=`#ifdef USE_ENVMAP#ifdef ENV_WORLDPOSvWorldPosition = worldPosition.xyz;#else@@ -684,18 +684,18 @@ vec4 sRGBTransferOETF( in vec4 value ) {vReflect = refract( cameraToVertex, worldNormal, refractionRatio );#endif#endif-#endif`,c4=`#ifdef USE_FOG+#endif`,wv=`#ifdef USE_FOGvFogDepth = - mvPosition.z;-#endif`,n4=`#ifdef USE_FOG+#endif`,Tv=`#ifdef USE_FOGvarying float vFogDepth;-#endif`,i4=`#ifdef USE_FOG+#endif`,Ev=`#ifdef USE_FOG#ifdef FOG_EXP2float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );#elsefloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );#endifgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );-#endif`,o4=`#ifdef USE_FOG+#endif`,Av=`#ifdef USE_FOGuniform vec3 fogColor;varying float vFogDepth;#ifdef FOG_EXP2@@ -704,7 +704,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {uniform float fogNear;uniform float fogFar;#endif-#endif`,r4=`#ifdef USE_GRADIENTMAP+#endif`,Rv=`#ifdef USE_GRADIENTMAPuniform sampler2D gradientMap;#endifvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {@@ -716,12 +716,12 @@ vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {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-}`,a4=`#ifdef USE_LIGHTMAP+}`,Cv=`#ifdef USE_LIGHTMAPuniform sampler2D lightMap;uniform float lightMapIntensity;-#endif`,s4=`LambertMaterial material;+#endif`,Pv=`LambertMaterial material;material.diffuseColor = diffuseColor.rgb;-material.specularStrength = specularStrength;`,t4=`varying vec3 vViewPosition;+material.specularStrength = specularStrength;`,Iv=`varying vec3 vViewPosition;struct LambertMaterial {vec3 diffuseColor;float specularStrength;@@ -735,7 +735,7 @@ void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometrreflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );}#define RE_Direct RE_Direct_Lambert-#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,e4=`uniform bool receiveShadow;+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Lv=`uniform bool receiveShadow;uniform vec3 ambientLightColor;#if defined( USE_LIGHT_PROBES )uniform vec3 lightProbe[ 9 ];@@ -852,7 +852,7 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosireturn irradiance;}#endif-#include <lightprobes_pars_fragment>`,$L=`#ifdef USE_ENVMAP+#include <lightprobes_pars_fragment>`,Nv=`#ifdef USE_ENVMAPvec3 getIBLIrradiance( const in vec3 normal ) {#ifdef ENVMAP_TYPE_CUBE_UVvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );@@ -885,8 +885,8 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi#endif}#endif-#endif`,UL=`ToonMaterial material;-material.diffuseColor = diffuseColor.rgb;`,JL=`varying vec3 vViewPosition;+#endif`,Dv=`ToonMaterial material;+material.diffuseColor = diffuseColor.rgb;`,Uv=`varying vec3 vViewPosition;struct ToonMaterial {vec3 diffuseColor;};@@ -898,11 +898,11 @@ void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPoreflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );}#define RE_Direct RE_Direct_Toon-#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,WL=`BlinnPhongMaterial material;+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Ov=`BlinnPhongMaterial material;material.diffuseColor = diffuseColor.rgb;material.specularColor = specular;material.specularShininess = shininess;-material.specularStrength = specularStrength;`,QL=`varying vec3 vViewPosition;+material.specularStrength = specularStrength;`,Fv=`varying vec3 vViewPosition;struct BlinnPhongMaterial {vec3 diffuseColor;vec3 specularColor;@@ -919,7 +919,7 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geomreflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );}#define RE_Direct RE_Direct_BlinnPhong-#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,KL=`PhysicalMaterial material;+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,zv=`PhysicalMaterial material;material.diffuseColor = diffuseColor.rgb;material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );material.metalness = metalnessFactor;@@ -1009,7 +1009,7 @@ material.roughness = min( material.roughness, 1.0 );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`,XL=`uniform sampler2D dfgLUT;+#endif`,kv=`uniform sampler2D dfgLUT;struct PhysicalMaterial {vec3 diffuseColor;vec3 diffuseContribution;@@ -1369,7 +1369,7 @@ void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradia#define RE_IndirectSpecular RE_IndirectSpecular_Physicalfloat 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 );-}`,HL=`+}`,Bv=`vec3 geometryPosition = - vViewPosition;vec3 geometryNormal = normal;vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );@@ -1491,7 +1491,7 @@ IncidentLight directLight;#if defined( RE_IndirectSpecular )vec3 radiance = vec3( 0.0 );vec3 clearcoatRadiance = vec3( 0.0 );-#endif`,NL=`#if defined( RE_IndirectDiffuse )+#endif`,Gv=`#if defined( RE_IndirectDiffuse )#ifdef USE_LIGHTMAPvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;@@ -1512,7 +1512,7 @@ IncidentLight directLight;#ifdef USE_CLEARCOATclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );#endif-#endif`,YL=`#if defined( RE_IndirectDiffuse )+#endif`,Hv=`#if defined( RE_IndirectDiffuse )#if defined( LAMBERT ) || defined( PHONG )irradiance += iblIrradiance;#endif@@ -1520,7 +1520,7 @@ IncidentLight directLight;#endif#if defined( RE_IndirectSpecular )RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );-#endif`,GL=`#ifdef USE_LIGHT_PROBES_GRID+#endif`,Vv=`#ifdef USE_LIGHT_PROBES_GRIDuniform highp sampler3D probesSH;uniform vec3 probesMin;uniform vec3 probesMax;@@ -1565,27 +1565,27 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {result += c8 * 0.429043 * ( x * x - y * y );return max( result, vec3( 0.0 ) );}-#endif`,OL=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+#endif`,Wv=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;-#endif`,EL=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+#endif`,$v=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )uniform float logDepthBufFC;varying float vFragDepth;varying float vIsPerspective;-#endif`,kL=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+#endif`,Zv=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFERvarying float vFragDepth;varying float vIsPerspective;-#endif`,qL=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+#endif`,Xv=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFERvFragDepth = 1.0 + gl_Position.w;vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );-#endif`,ZL=`#ifdef USE_MAP+#endif`,qv=`#ifdef USE_MAPvec4 sampledDiffuseColor = texture2D( map, vMapUv );#ifdef DECODE_VIDEO_TEXTUREsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );#endifdiffuseColor *= sampledDiffuseColor;-#endif`,IL=`#ifdef USE_MAP+#endif`,Yv=`#ifdef USE_MAPuniform sampler2D map;-#endif`,DL=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )+#endif`,jv=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )#if defined( USE_POINTS_UV )vec2 uv = vUv;#else@@ -1597,7 +1597,7 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {#endif#ifdef USE_ALPHAMAPdiffuseColor.a *= texture2D( alphaMap, uv ).g;-#endif`,FL=`#if defined( USE_POINTS_UV )+#endif`,Jv=`#if defined( USE_POINTS_UV )varying vec2 vUv;#else#if defined( USE_MAP ) || defined( USE_ALPHAMAP )@@ -1609,19 +1609,19 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {#endif#ifdef USE_ALPHAMAPuniform sampler2D alphaMap;-#endif`,LL=`float metalnessFactor = metalness;+#endif`,Kv=`float metalnessFactor = metalness;#ifdef USE_METALNESSMAPvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );metalnessFactor *= texelMetalness.b;-#endif`,RL=`#ifdef USE_METALNESSMAP+#endif`,Qv=`#ifdef USE_METALNESSMAPuniform sampler2D metalnessMap;-#endif`,VL=`#ifdef USE_INSTANCING_MORPH+#endif`,ey=`#ifdef USE_INSTANCING_MORPHfloat 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`,wL=`#if defined( USE_MORPHCOLORS )+#endif`,ty=`#if defined( USE_MORPHCOLORS )vColor *= morphTargetBaseInfluence;for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {#if defined( USE_COLOR_ALPHA )@@ -1630,12 +1630,12 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];#endif}-#endif`,ML=`#ifdef USE_MORPHNORMALS+#endif`,ny=`#ifdef USE_MORPHNORMALSobjectNormal *= morphTargetBaseInfluence;for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];}-#endif`,BL=`#ifdef USE_MORPHTARGETS+#endif`,iy=`#ifdef USE_MORPHTARGETS#ifndef USE_INSTANCING_MORPHuniform float morphTargetBaseInfluence;uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];@@ -1649,12 +1649,12 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {ivec3 morphUV = ivec3( x, y, morphTargetIndex );return texelFetch( morphTargetsTexture, morphUV, 0 );}-#endif`,PL=`#ifdef USE_MORPHTARGETS+#endif`,ry=`#ifdef USE_MORPHTARGETStransformed *= morphTargetBaseInfluence;for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];}-#endif`,zL=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;+#endif`,sy=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;#ifdef FLAT_SHADEDvec3 fdx = dFdx( vViewPosition );vec3 fdy = dFdy( vViewPosition );@@ -1695,7 +1695,7 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {tbn2[1] *= faceDirection;#endif#endif-vec3 nonPerturbedNormal = normal;`,_L=`#ifdef USE_NORMALMAP_OBJECTSPACE+vec3 nonPerturbedNormal = normal;`,oy=`#ifdef USE_NORMALMAP_OBJECTSPACEnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;#ifdef FLIP_SIDEDnormal = - normal;@@ -1713,19 +1713,19 @@ vec3 nonPerturbedNormal = normal;`,_L=`#ifdef USE_NORMALMAP_OBJECTSPACEnormal = normalize( tbn * mapN );#elif defined( USE_BUMPMAP )normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );-#endif`,AL=`#ifndef FLAT_SHADED+#endif`,ay=`#ifndef FLAT_SHADEDvarying vec3 vNormal;#ifdef USE_TANGENTvarying vec3 vTangent;varying vec3 vBitangent;#endif-#endif`,CL=`#ifndef FLAT_SHADED+#endif`,cy=`#ifndef FLAT_SHADEDvarying vec3 vNormal;#ifdef USE_TANGENTvarying vec3 vTangent;varying vec3 vBitangent;#endif-#endif`,SL=`#ifndef FLAT_SHADED+#endif`,ly=`#ifndef FLAT_SHADEDvNormal = normalize( transformedNormal );#ifdef USE_TANGENTvTangent = normalize( transformedTangent );@@ -1734,7 +1734,7 @@ vec3 nonPerturbedNormal = normal;`,_L=`#ifdef USE_NORMALMAP_OBJECTSPACEvBitangent = - vBitangent;#endif#endif-#endif`,TL=`#ifdef USE_NORMALMAP+#endif`,uy=`#ifdef USE_NORMALMAPuniform sampler2D normalMap;uniform vec2 normalScale;#endif@@ -1756,13 +1756,13 @@ vec3 nonPerturbedNormal = normal;`,_L=`#ifdef USE_NORMALMAP_OBJECTSPACEfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );return mat3( T * scale, B * scale, N );}-#endif`,vL=`#ifdef USE_CLEARCOAT+#endif`,hy=`#ifdef USE_CLEARCOATvec3 clearcoatNormal = nonPerturbedNormal;-#endif`,jL=`#ifdef USE_CLEARCOAT_NORMALMAP+#endif`,fy=`#ifdef USE_CLEARCOAT_NORMALMAPvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;clearcoatMapN.xy *= clearcoatNormalScale;clearcoatNormal = normalize( tbn2 * clearcoatMapN );-#endif`,gL=`#ifdef USE_CLEARCOATMAP+#endif`,dy=`#ifdef USE_CLEARCOATMAPuniform sampler2D clearcoatMap;#endif#ifdef USE_CLEARCOAT_NORMALMAP@@ -1771,18 +1771,18 @@ vec3 nonPerturbedNormal = normal;`,_L=`#ifdef USE_NORMALMAP_OBJECTSPACE#endif#ifdef USE_CLEARCOAT_ROUGHNESSMAPuniform sampler2D clearcoatRoughnessMap;-#endif`,bL=`#ifdef USE_IRIDESCENCEMAP+#endif`,py=`#ifdef USE_IRIDESCENCEMAPuniform sampler2D iridescenceMap;#endif#ifdef USE_IRIDESCENCE_THICKNESSMAPuniform sampler2D iridescenceThicknessMap;-#endif`,yL=`#ifdef OPAQUE+#endif`,my=`#ifdef OPAQUEdiffuseColor.a = 1.0;#endif#ifdef USE_TRANSMISSIONdiffuseColor.a *= material.transmissionAlpha;#endif-gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,xL=`vec3 packNormalToRGB( const in vec3 normal ) {+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,gy=`vec3 packNormalToRGB( const in vec3 normal ) {return normalize( normal ) * 0.5 + 0.5;}vec3 unpackRGBToNormal( const in vec3 rgb ) {@@ -1861,9 +1861,9 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const#elsereturn ( near * far ) / ( ( far - near ) * depth - far );#endif-}`,hL=`#ifdef PREMULTIPLIED_ALPHA+}`,_y=`#ifdef PREMULTIPLIED_ALPHAgl_FragColor.rgb *= gl_FragColor.a;-#endif`,fL=`vec4 mvPosition = vec4( transformed, 1.0 );+#endif`,xy=`vec4 mvPosition = vec4( transformed, 1.0 );#ifdef USE_BATCHINGmvPosition = batchingMatrix * mvPosition;#endif@@ -1871,22 +1871,22 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, constmvPosition = instanceMatrix * mvPosition;#endifmvPosition = modelViewMatrix * mvPosition;-gl_Position = projectionMatrix * mvPosition;`,uL=`#ifdef DITHERING+gl_Position = projectionMatrix * mvPosition;`,vy=`#ifdef DITHERINGgl_FragColor.rgb = dithering( gl_FragColor.rgb );-#endif`,lL=`#ifdef DITHERING+#endif`,yy=`#ifdef DITHERINGvec3 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`,mL=`float roughnessFactor = roughness;+#endif`,by=`float roughnessFactor = roughness;#ifdef USE_ROUGHNESSMAPvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );roughnessFactor *= texelRoughness.g;-#endif`,pL=`#ifdef USE_ROUGHNESSMAP+#endif`,Sy=`#ifdef USE_ROUGHNESSMAPuniform sampler2D roughnessMap;-#endif`,dL=`#if NUM_SPOT_LIGHT_COORDS > 0+#endif`,My=`#if NUM_SPOT_LIGHT_COORDS > 0varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];#endif#if NUM_SPOT_LIGHT_MAPS > 0@@ -2086,7 +2086,7 @@ gl_Position = projectionMatrix * mvPosition;`,uL=`#ifdef DITHERING}#endif#endif-#endif`,cL=`#if NUM_SPOT_LIGHT_COORDS > 0+#endif`,wy=`#if NUM_SPOT_LIGHT_COORDS > 0uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];#endif@@ -2127,7 +2127,7 @@ gl_Position = projectionMatrix * mvPosition;`,uL=`#ifdef DITHERING};uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];#endif-#endif`,nL=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )+#endif`,Ty=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )#ifdef HAS_NORMALvec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );#else@@ -2163,7 +2163,7 @@ gl_Position = projectionMatrix * mvPosition;`,uL=`#ifdef DITHERINGvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;}#pragma unroll_loop_end-#endif`,iL=`float getShadowMask() {+#endif`,Ey=`float getShadowMask() {float shadow = 1.0;#ifdef USE_SHADOWMAP#if NUM_DIR_LIGHT_SHADOWS > 0@@ -2195,12 +2195,12 @@ gl_Position = projectionMatrix * mvPosition;`,uL=`#ifdef DITHERING#endif#endifreturn shadow;-}`,oL=`#ifdef USE_SKINNING+}`,Ay=`#ifdef USE_SKINNINGmat4 boneMatX = getBoneMatrix( skinIndex.x );mat4 boneMatY = getBoneMatrix( skinIndex.y );mat4 boneMatZ = getBoneMatrix( skinIndex.z );mat4 boneMatW = getBoneMatrix( skinIndex.w );-#endif`,rL=`#ifdef USE_SKINNING+#endif`,Ry=`#ifdef USE_SKINNINGuniform mat4 bindMatrix;uniform mat4 bindMatrixInverse;uniform highp sampler2D boneTexture;@@ -2215,7 +2215,7 @@ gl_Position = projectionMatrix * mvPosition;`,uL=`#ifdef DITHERINGvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );return mat4( v1, v2, v3, v4 );}-#endif`,aL=`#ifdef USE_SKINNING+#endif`,Cy=`#ifdef USE_SKINNINGvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );vec4 skinned = vec4( 0.0 );skinned += boneMatX * skinVertex * skinWeight.x;@@ -2223,7 +2223,7 @@ gl_Position = projectionMatrix * mvPosition;`,uL=`#ifdef DITHERINGskinned += boneMatZ * skinVertex * skinWeight.z;skinned += boneMatW * skinVertex * skinWeight.w;transformed = ( bindMatrixInverse * skinned ).xyz;-#endif`,sL=`#ifdef USE_SKINNING+#endif`,Py=`#ifdef USE_SKINNINGmat4 skinMatrix = mat4( 0.0 );skinMatrix += skinWeight.x * boneMatX;skinMatrix += skinWeight.y * boneMatY;@@ -2234,17 +2234,17 @@ gl_Position = projectionMatrix * mvPosition;`,uL=`#ifdef DITHERING#ifdef USE_TANGENTobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;#endif-#endif`,tL=`float specularStrength;+#endif`,Iy=`float specularStrength;#ifdef USE_SPECULARMAPvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );specularStrength = texelSpecular.r;#elsespecularStrength = 1.0;-#endif`,eL=`#ifdef USE_SPECULARMAP+#endif`,Ly=`#ifdef USE_SPECULARMAPuniform sampler2D specularMap;-#endif`,$R=`#if defined( TONE_MAPPING )+#endif`,Ny=`#if defined( TONE_MAPPING )gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );-#endif`,UR=`#ifndef saturate+#endif`,Dy=`#ifndef saturate#define saturate( a ) clamp( a, 0.0, 1.0 )#endifuniform float toneMappingExposure;@@ -2341,7 +2341,7 @@ vec3 NeutralToneMapping( vec3 color ) {float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );return mix( color, vec3( newPeak ), g );}-vec3 CustomToneMapping( vec3 color ) { return color; }`,JR=`#ifdef USE_TRANSMISSION+vec3 CustomToneMapping( vec3 color ) { return color; }`,Uy=`#ifdef USE_TRANSMISSIONmaterial.transmission = transmission;material.transmissionAlpha = 1.0;material.thickness = thickness;@@ -2362,7 +2362,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,JR=`#ifdef USE_TRANSMISSmaterial.attenuationColor, material.attenuationDistance );material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );-#endif`,WR=`#ifdef USE_TRANSMISSION+#endif`,Oy=`#ifdef USE_TRANSMISSIONuniform float transmission;uniform float thickness;uniform float attenuationDistance;@@ -2488,7 +2488,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,JR=`#ifdef USE_TRANSMISSfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );}-#endif`,QR=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+#endif`,Fy=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )varying vec2 vUv;#endif#ifdef USE_MAP@@ -2558,7 +2558,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,JR=`#ifdef USE_TRANSMISS#ifdef USE_THICKNESSMAPuniform mat3 thicknessMapTransform;varying vec2 vThicknessMapUv;-#endif`,KR=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+#endif`,zy=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )varying vec2 vUv;#endif#ifdef USE_MAP@@ -2652,7 +2652,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,JR=`#ifdef USE_TRANSMISS#ifdef USE_THICKNESSMAPuniform mat3 thicknessMapTransform;varying vec2 vThicknessMapUv;-#endif`,XR=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+#endif`,ky=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )vUv = vec3( uv, 1 ).xy;#endif#ifdef USE_MAP@@ -2723,7 +2723,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,JR=`#ifdef USE_TRANSMISS#endif#ifdef USE_THICKNESSMAPvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;-#endif`,HR=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0+#endif`,By=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0vec4 worldPosition = vec4( transformed, 1.0 );#ifdef USE_BATCHINGworldPosition = batchingMatrix * worldPosition;@@ -2732,12 +2732,12 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,JR=`#ifdef USE_TRANSMISSworldPosition = instanceMatrix * worldPosition;#endifworldPosition = modelMatrix * worldPosition;-#endif`,NR=`varying vec2 vUv;+#endif`,Gy=`varying vec2 vUv;uniform mat3 uvTransform;void main() {vUv = ( uvTransform * vec3( uv, 1 ) ).xy;gl_Position = vec4( position.xy, 1.0, 1.0 );-}`,YR=`uniform sampler2D t2D;+}`,Hy=`uniform sampler2D t2D;uniform float backgroundIntensity;varying vec2 vUv;void main() {@@ -2749,14 +2749,14 @@ void main() {gl_FragColor = texColor;#include <tonemapping_fragment>#include <colorspace_fragment>-}`,GR=`varying vec3 vWorldDirection;+}`,Vy=`varying vec3 vWorldDirection;#include <common>void main() {vWorldDirection = transformDirection( position, modelMatrix );#include <begin_vertex>#include <project_vertex>gl_Position.z = gl_Position.w;-}`,OR=`#ifdef ENVMAP_TYPE_CUBE+}`,Wy=`#ifdef ENVMAP_TYPE_CUBEuniform samplerCube envMap;#elif defined( ENVMAP_TYPE_CUBE_UV )uniform sampler2D envMap;@@ -2778,14 +2778,14 @@ void main() {gl_FragColor = texColor;#include <tonemapping_fragment>#include <colorspace_fragment>-}`,ER=`varying vec3 vWorldDirection;+}`,$y=`varying vec3 vWorldDirection;#include <common>void main() {vWorldDirection = transformDirection( position, modelMatrix );#include <begin_vertex>#include <project_vertex>gl_Position.z = gl_Position.w;-}`,kR=`uniform samplerCube tCube;+}`,Zy=`uniform samplerCube tCube;uniform float tFlip;uniform float opacity;varying vec3 vWorldDirection;@@ -2795,7 +2795,7 @@ void main() {gl_FragColor.a *= opacity;#include <tonemapping_fragment>#include <colorspace_fragment>-}`,qR=`#include <common>+}`,Xy=`#include <common>#include <batching_pars_vertex>#include <uv_pars_vertex>#include <displacementmap_pars_vertex>@@ -2822,7 +2822,7 @@ void main() {#include <logdepthbuf_vertex>#include <clipping_planes_vertex>vHighPrecisionZW = gl_Position.zw;-}`,ZR=`#if DEPTH_PACKING == 3200+}`,qy=`#if DEPTH_PACKING == 3200uniform float opacity;#endif#include <common>@@ -2860,7 +2860,7 @@ void main() {#elif DEPTH_PACKING == 3203gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );#endif-}`,IR=`#define DISTANCE+}`,Yy=`#define DISTANCEvarying vec3 vWorldPosition;#include <common>#include <batching_pars_vertex>@@ -2887,7 +2887,7 @@ void main() {#include <worldpos_vertex>#include <clipping_planes_vertex>vWorldPosition = worldPosition.xyz;-}`,DR=`#define DISTANCE+}`;var jy=`#define DISTANCEuniform vec3 referencePosition;uniform float nearDistance;uniform float farDistance;@@ -2910,13 +2910,13 @@ void main() {dist = ( dist - nearDistance ) / ( farDistance - nearDistance );dist = saturate( dist );gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );-}`,FR=`varying vec3 vWorldDirection;+}`,Jy=`varying vec3 vWorldDirection;#include <common>void main() {vWorldDirection = transformDirection( position, modelMatrix );#include <begin_vertex>#include <project_vertex>-}`,LR=`uniform sampler2D tEquirect;+}`,Ky=`uniform sampler2D tEquirect;varying vec3 vWorldDirection;#include <common>void main() {@@ -2925,7 +2925,7 @@ void main() {gl_FragColor = texture2D( tEquirect, sampleUV );#include <tonemapping_fragment>#include <colorspace_fragment>-}`,RR=`uniform float scale;+}`,Qy=`uniform float scale;attribute float lineDistance;varying float vLineDistance;#include <common>@@ -2947,7 +2947,7 @@ void main() {#include <logdepthbuf_vertex>#include <clipping_planes_vertex>#include <fog_vertex>-}`,VR=`uniform vec3 diffuse;+}`,eb=`uniform vec3 diffuse;uniform float opacity;uniform float dashSize;uniform float totalSize;@@ -2975,7 +2975,7 @@ void main() {#include <colorspace_fragment>#include <fog_fragment>#include <premultiplied_alpha_fragment>-}`,wR=`#include <common>+}`,tb=`#include <common>#include <batching_pars_vertex>#include <uv_pars_vertex>#include <envmap_pars_vertex>@@ -3007,7 +3007,7 @@ void main() {#include <worldpos_vertex>#include <envmap_vertex>#include <fog_vertex>-}`,MR=`uniform vec3 diffuse;+}`,nb=`uniform vec3 diffuse;uniform float opacity;#ifndef FLAT_SHADEDvarying vec3 vNormal;@@ -3055,7 +3055,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,BR=`#define LAMBERT+}`,ib=`#define LAMBERTvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3094,7 +3094,7 @@ void main() {#include <envmap_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,PR=`#define LAMBERT+}`,rb=`#define LAMBERTuniform vec3 diffuse;uniform vec3 emissive;uniform float opacity;@@ -3152,7 +3152,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,zR=`#define MATCAP+}`,sb=`#define MATCAPvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3186,7 +3186,7 @@ void main() {#include <clipping_planes_vertex>#include <fog_vertex>vViewPosition = - mvPosition.xyz;-}`,_R=`#define MATCAP+}`,ob=`#define MATCAPuniform vec3 diffuse;uniform float opacity;uniform sampler2D matcap;@@ -3232,7 +3232,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,AR=`#define NORMAL+}`,ab=`#define NORMAL#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )varying vec3 vViewPosition;#endif@@ -3265,7 +3265,7 @@ void main() {#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )vViewPosition = - mvPosition.xyz;#endif-}`,CR=`#define NORMAL+}`,cb=`#define NORMALuniform float opacity;#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )varying vec3 vViewPosition;@@ -3286,7 +3286,7 @@ void main() {#ifdef OPAQUEgl_FragColor.a = 1.0;#endif-}`,SR=`#define PHONG+}`,lb=`#define PHONGvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3325,7 +3325,7 @@ void main() {#include <envmap_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,TR=`#define PHONG+}`,ub=`#define PHONGuniform vec3 diffuse;uniform vec3 emissive;uniform vec3 specular;@@ -3385,7 +3385,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,vR=`#define STANDARD+}`,hb=`#define STANDARDvarying vec3 vViewPosition;#ifdef USE_TRANSMISSIONvarying vec3 vWorldPosition;@@ -3428,7 +3428,7 @@ void main() {#ifdef USE_TRANSMISSIONvWorldPosition = worldPosition.xyz;#endif-}`,jR=`#define STANDARD+}`,fb=`#define STANDARD#ifdef PHYSICAL#define IOR#define USE_SPECULAR@@ -3553,7 +3553,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,gR=`#define TOON+}`,db=`#define TOONvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3590,7 +3590,7 @@ void main() {#include <worldpos_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,bR=`#define TOON+}`,pb=`#define TOONuniform vec3 diffuse;uniform vec3 emissive;uniform float opacity;@@ -3642,7 +3642,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,yR=`uniform float size;+}`,mb=`uniform float size;uniform float scale;#include <common>#include <color_pars_vertex>@@ -3673,7 +3673,7 @@ void main() {#include <clipping_planes_vertex>#include <worldpos_vertex>#include <fog_vertex>-}`,xR=`uniform vec3 diffuse;+}`,gb=`uniform vec3 diffuse;uniform float opacity;#include <common>#include <color_pars_fragment>@@ -3698,7 +3698,7 @@ void main() {#include <colorspace_fragment>#include <fog_fragment>#include <premultiplied_alpha_fragment>-}`,hR=`#include <common>+}`,_b=`#include <common>#include <batching_pars_vertex>#include <fog_pars_vertex>#include <morphtarget_pars_vertex>@@ -3721,7 +3721,7 @@ void main() {#include <worldpos_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,fR=`uniform vec3 color;+}`,xb=`uniform vec3 color;uniform float opacity;#include <common>#include <fog_pars_fragment>@@ -3737,7 +3737,7 @@ void main() {#include <colorspace_fragment>#include <fog_fragment>#include <premultiplied_alpha_fragment>-}`,uR=`uniform float rotation;+}`,vb=`uniform float rotation;uniform vec2 center;#include <common>#include <uv_pars_vertex>@@ -3761,7 +3761,7 @@ void main() {#include <logdepthbuf_vertex>#include <clipping_planes_vertex>#include <fog_vertex>-}`,lR=`uniform vec3 diffuse;+}`,yb=`uniform vec3 diffuse;uniform float opacity;#include <common>#include <uv_pars_fragment>@@ -3786,7 +3786,7 @@ void main() {#include <tonemapping_fragment>#include <colorspace_fragment>#include <fog_fragment>-}`,i$={alphahash_fragment:N4,alphahash_pars_fragment:Y4,alphamap_fragment:G4,alphamap_pars_fragment:O4,alphatest_fragment:E4,alphatest_pars_fragment:k4,aomap_fragment:q4,aomap_pars_fragment:Z4,batching_pars_vertex:I4,batching_vertex:D4,begin_vertex:F4,beginnormal_vertex:L4,bsdfs:R4,iridescence_fragment:V4,bumpmap_pars_fragment:w4,clipping_planes_fragment:M4,clipping_planes_pars_fragment:B4,clipping_planes_pars_vertex:P4,clipping_planes_vertex:z4,color_fragment:_4,color_pars_fragment:A4,color_pars_vertex:C4,color_vertex:S4,common:T4,cube_uv_reflection_fragment:v4,defaultnormal_vertex:j4,displacementmap_pars_vertex:g4,displacementmap_vertex:b4,emissivemap_fragment:y4,emissivemap_pars_fragment:x4,colorspace_fragment:h4,colorspace_pars_fragment:f4,envmap_fragment:u4,envmap_common_pars_fragment:l4,envmap_pars_fragment:m4,envmap_pars_vertex:p4,envmap_physical_pars_fragment:$L,envmap_vertex:d4,fog_vertex:c4,fog_pars_vertex:n4,fog_fragment:i4,fog_pars_fragment:o4,gradientmap_pars_fragment:r4,lightmap_pars_fragment:a4,lights_lambert_fragment:s4,lights_lambert_pars_fragment:t4,lights_pars_begin:e4,lights_toon_fragment:UL,lights_toon_pars_fragment:JL,lights_phong_fragment:WL,lights_phong_pars_fragment:QL,lights_physical_fragment:KL,lights_physical_pars_fragment:XL,lights_fragment_begin:HL,lights_fragment_maps:NL,lights_fragment_end:YL,lightprobes_pars_fragment:GL,logdepthbuf_fragment:OL,logdepthbuf_pars_fragment:EL,logdepthbuf_pars_vertex:kL,logdepthbuf_vertex:qL,map_fragment:ZL,map_pars_fragment:IL,map_particle_fragment:DL,map_particle_pars_fragment:FL,metalnessmap_fragment:LL,metalnessmap_pars_fragment:RL,morphinstance_vertex:VL,morphcolor_vertex:wL,morphnormal_vertex:ML,morphtarget_pars_vertex:BL,morphtarget_vertex:PL,normal_fragment_begin:zL,normal_fragment_maps:_L,normal_pars_fragment:AL,normal_pars_vertex:CL,normal_vertex:SL,normalmap_pars_fragment:TL,clearcoat_normal_fragment_begin:vL,clearcoat_normal_fragment_maps:jL,clearcoat_pars_fragment:gL,iridescence_pars_fragment:bL,opaque_fragment:yL,packing:xL,premultiplied_alpha_fragment:hL,project_vertex:fL,dithering_fragment:uL,dithering_pars_fragment:lL,roughnessmap_fragment:mL,roughnessmap_pars_fragment:pL,shadowmap_pars_fragment:dL,shadowmap_pars_vertex:cL,shadowmap_vertex:nL,shadowmask_pars_fragment:iL,skinbase_vertex:oL,skinning_pars_vertex:rL,skinning_vertex:aL,skinnormal_vertex:sL,specularmap_fragment:tL,specularmap_pars_fragment:eL,tonemapping_fragment:$R,tonemapping_pars_fragment:UR,transmission_fragment:JR,transmission_pars_fragment:WR,uv_pars_fragment:QR,uv_pars_vertex:KR,uv_vertex:XR,worldpos_vertex:HR,background_vert:NR,background_frag:YR,backgroundCube_vert:GR,backgroundCube_frag:OR,cube_vert:ER,cube_frag:kR,depth_vert:qR,depth_frag:ZR,distance_vert:IR,distance_frag:DR,equirect_vert:FR,equirect_frag:LR,linedashed_vert:RR,linedashed_frag:VR,meshbasic_vert:wR,meshbasic_frag:MR,meshlambert_vert:BR,meshlambert_frag:PR,meshmatcap_vert:zR,meshmatcap_frag:_R,meshnormal_vert:AR,meshnormal_frag:CR,meshphong_vert:SR,meshphong_frag:TR,meshphysical_vert:vR,meshphysical_frag:jR,meshtoon_vert:gR,meshtoon_frag:bR,points_vert:yR,points_frag:xR,shadow_vert:hR,shadow_frag:fR,sprite_vert:uR,sprite_frag:lR},Z$={common:{diffuse:{value:new y$(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new f$},alphaMap:{value:null},alphaMapTransform:{value:new f$},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new f$}},envmap:{envMap:{value:null},envMapRotation:{value:new f$},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:0.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new f$}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new f$}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new f$},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new f$},normalScale:{value:new g$(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new f$},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new f$}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new f$}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new f$}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:0.00025},fogNear:{value:1},fogFar:{value:2000},fogColor:{value:new y$(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 j},probesMax:{value:new j},probesResolution:{value:new j}},points:{diffuse:{value:new y$(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new f$},alphaTest:{value:0},uvTransform:{value:new f$}},sprite:{diffuse:{value:new y$(16777215)},opacity:{value:1},center:{value:new g$(0.5,0.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new f$},alphaMap:{value:null},alphaMapTransform:{value:new f$},alphaTest:{value:0}}},HJ={basic:{uniforms:UU([Z$.common,Z$.specularmap,Z$.envmap,Z$.aomap,Z$.lightmap,Z$.fog]),vertexShader:i$.meshbasic_vert,fragmentShader:i$.meshbasic_frag},lambert:{uniforms:UU([Z$.common,Z$.specularmap,Z$.envmap,Z$.aomap,Z$.lightmap,Z$.emissivemap,Z$.bumpmap,Z$.normalmap,Z$.displacementmap,Z$.fog,Z$.lights,{emissive:{value:new y$(0)},envMapIntensity:{value:1}}]),vertexShader:i$.meshlambert_vert,fragmentShader:i$.meshlambert_frag},phong:{uniforms:UU([Z$.common,Z$.specularmap,Z$.envmap,Z$.aomap,Z$.lightmap,Z$.emissivemap,Z$.bumpmap,Z$.normalmap,Z$.displacementmap,Z$.fog,Z$.lights,{emissive:{value:new y$(0)},specular:{value:new y$(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:i$.meshphong_vert,fragmentShader:i$.meshphong_frag},standard:{uniforms:UU([Z$.common,Z$.envmap,Z$.aomap,Z$.lightmap,Z$.emissivemap,Z$.bumpmap,Z$.normalmap,Z$.displacementmap,Z$.roughnessmap,Z$.metalnessmap,Z$.fog,Z$.lights,{emissive:{value:new y$(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:i$.meshphysical_vert,fragmentShader:i$.meshphysical_frag},toon:{uniforms:UU([Z$.common,Z$.aomap,Z$.lightmap,Z$.emissivemap,Z$.bumpmap,Z$.normalmap,Z$.displacementmap,Z$.gradientmap,Z$.fog,Z$.lights,{emissive:{value:new y$(0)}}]),vertexShader:i$.meshtoon_vert,fragmentShader:i$.meshtoon_frag},matcap:{uniforms:UU([Z$.common,Z$.bumpmap,Z$.normalmap,Z$.displacementmap,Z$.fog,{matcap:{value:null}}]),vertexShader:i$.meshmatcap_vert,fragmentShader:i$.meshmatcap_frag},points:{uniforms:UU([Z$.points,Z$.fog]),vertexShader:i$.points_vert,fragmentShader:i$.points_frag},dashed:{uniforms:UU([Z$.common,Z$.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:i$.linedashed_vert,fragmentShader:i$.linedashed_frag},depth:{uniforms:UU([Z$.common,Z$.displacementmap]),vertexShader:i$.depth_vert,fragmentShader:i$.depth_frag},normal:{uniforms:UU([Z$.common,Z$.bumpmap,Z$.normalmap,Z$.displacementmap,{opacity:{value:1}}]),vertexShader:i$.meshnormal_vert,fragmentShader:i$.meshnormal_frag},sprite:{uniforms:UU([Z$.sprite,Z$.fog]),vertexShader:i$.sprite_vert,fragmentShader:i$.sprite_frag},background:{uniforms:{uvTransform:{value:new f$},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:i$.background_vert,fragmentShader:i$.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new f$}},vertexShader:i$.backgroundCube_vert,fragmentShader:i$.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:i$.cube_vert,fragmentShader:i$.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:i$.equirect_vert,fragmentShader:i$.equirect_frag},distance:{uniforms:UU([Z$.common,Z$.displacementmap,{referencePosition:{value:new j},nearDistance:{value:1},farDistance:{value:1000}}]),vertexShader:i$.distance_vert,fragmentShader:i$.distance_frag},shadow:{uniforms:UU([Z$.lights,Z$.fog,{color:{value:new y$(0)},opacity:{value:1}}]),vertexShader:i$.shadow_vert,fragmentShader:i$.shadow_frag}};HJ.physical={uniforms:UU([HJ.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new f$},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new f$},clearcoatNormalScale:{value:new g$(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new f$},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new f$},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new f$},sheen:{value:0},sheenColor:{value:new y$(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new f$},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new f$},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new f$},transmissionSamplerSize:{value:new g$},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new f$},attenuationDistance:{value:0},attenuationColor:{value:new y$(0)},specularColor:{value:new y$(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new f$},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new f$},anisotropyVector:{value:new g$},anisotropyMap:{value:null},anisotropyMapTransform:{value:new f$}}]),vertexShader:i$.meshphysical_vert,fragmentShader:i$.meshphysical_frag};var m9={r:0,b:0,g:0},mR=new m$,zZ=new f$;zZ.set(-1,0,0,0,1,0,0,0,1);function pR($,U,J,Q,W,K){let X=new y$(0),H=W===!0?0:1,N,Y,G=null,O=0,E=null;function k(_){let P=_.isScene===!0?_.background:null;if(P&&P.isTexture){let L=_.backgroundBlurriness>0;P=U.get(P,L)}return P}function I(_){let P=!1,L=k(_);if(L===null)q(X,H);else if(L&&L.isColor)q(L,1),P=!0;let B=$.xr.getEnvironmentBlendMode();if(B==="additive")J.buffers.color.setClear(0,0,0,1,K);else if(B==="alpha-blend")J.buffers.color.setClear(0,0,0,0,K);if($.autoClear||P)J.buffers.depth.setTest(!0),J.buffers.depth.setMask(!0),J.buffers.color.setMask(!0),$.clear($.autoClearColor,$.autoClearDepth,$.autoClearStencil)}function R(_,P){let L=k(P);if(L&&(L.isCubeTexture||L.mapping===MW)){if(Y===void 0)Y=new B6(new $0(1,1,1),new gU({name:"BackgroundCubeMaterial",uniforms:v0(HJ.backgroundCube.uniforms),vertexShader:HJ.backgroundCube.vertexShader,fragmentShader:HJ.backgroundCube.fragmentShader,side:$U,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),Y.geometry.deleteAttribute("normal"),Y.geometry.deleteAttribute("uv"),Y.onBeforeRender=function(B,z,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(Y.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),Q.update(Y);if(Y.material.uniforms.envMap.value=L,Y.material.uniforms.backgroundBlurriness.value=P.backgroundBlurriness,Y.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,Y.material.uniforms.backgroundRotation.value.setFromMatrix4(mR.makeRotationFromEuler(P.backgroundRotation)).transpose(),L.isCubeTexture&&L.isRenderTargetTexture===!1)Y.material.uniforms.backgroundRotation.value.premultiply(zZ);if(Y.material.toneMapped=r$.getTransfer(L.colorSpace)!==R6,G!==L||O!==L.version||E!==$.toneMapping)Y.material.needsUpdate=!0,G=L,O=L.version,E=$.toneMapping;Y.layers.enableAll(),_.unshift(Y,Y.geometry,Y.material,0,0,null)}else if(L&&L.isTexture){if(N===void 0)N=new B6(new yW(2,2),new gU({name:"BackgroundMaterial",uniforms:v0(HJ.background.uniforms),vertexShader:HJ.background.vertexShader,fragmentShader:HJ.background.fragmentShader,side:oJ,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),N.geometry.deleteAttribute("normal"),Object.defineProperty(N.material,"map",{get:function(){return this.uniforms.t2D.value}}),Q.update(N);if(N.material.uniforms.t2D.value=L,N.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,N.material.toneMapped=r$.getTransfer(L.colorSpace)!==R6,L.matrixAutoUpdate===!0)L.updateMatrix();if(N.material.uniforms.uvTransform.value.copy(L.matrix),G!==L||O!==L.version||E!==$.toneMapping)N.material.needsUpdate=!0,G=L,O=L.version,E=$.toneMapping;N.layers.enableAll(),_.unshift(N,N.geometry,N.material,0,0,null)}}function q(_,P){_.getRGB(m9,NH($)),J.buffers.color.setClear(m9.r,m9.g,m9.b,P,K)}function Z(){if(Y!==void 0)Y.geometry.dispose(),Y.material.dispose(),Y=void 0;if(N!==void 0)N.geometry.dispose(),N.material.dispose(),N=void 0}return{getClearColor:function(){return X},setClearColor:function(_,P=1){X.set(_),H=P,q(X,H)},getClearAlpha:function(){return H},setClearAlpha:function(_){H=_,q(X,H)},render:I,addToRenderList:R,dispose:Z}}function dR($,U){let J=$.getParameter($.MAX_VERTEX_ATTRIBS),Q={},W=E(null),K=W,X=!1;function H(C,f,s,x,d){let c=!1,y=O(C,x,s,f);if(K!==y)K=y,Y(K.object);if(c=k(C,x,s,d),c)I(C,x,s,d);if(d!==null)U.update(d,$.ELEMENT_ARRAY_BUFFER);if(c||X){if(X=!1,L(C,f,s,x),d!==null)$.bindBuffer($.ELEMENT_ARRAY_BUFFER,U.get(d).buffer)}}function N(){return $.createVertexArray()}function Y(C){return $.bindVertexArray(C)}function G(C){return $.deleteVertexArray(C)}function O(C,f,s,x){let d=x.wireframe===!0,c=Q[f.id];if(c===void 0)c={},Q[f.id]=c;let y=C.isInstancedMesh===!0?C.id:0,t=c[y];if(t===void 0)t={},c[y]=t;let e=t[s.id];if(e===void 0)e={},t[s.id]=e;let Y$=e[d];if(Y$===void 0)Y$=E(N()),e[d]=Y$;return Y$}function E(C){let f=[],s=[],x=[];for(let d=0;d<J;d++)f[d]=0,s[d]=0,x[d]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:f,enabledAttributes:s,attributeDivisors:x,object:C,attributes:{},index:null}}function k(C,f,s,x){let d=K.attributes,c=f.attributes,y=0,t=s.getAttributes();for(let e in t)if(t[e].location>=0){let R$=d[e],w$=c[e];if(w$===void 0){if(e==="instanceMatrix"&&C.instanceMatrix)w$=C.instanceMatrix;if(e==="instanceColor"&&C.instanceColor)w$=C.instanceColor}if(R$===void 0)return!0;if(R$.attribute!==w$)return!0;if(w$&&R$.data!==w$.data)return!0;y++}if(K.attributesNum!==y)return!0;if(K.index!==x)return!0;return!1}function I(C,f,s,x){let d={},c=f.attributes,y=0,t=s.getAttributes();for(let e in t)if(t[e].location>=0){let R$=c[e];if(R$===void 0){if(e==="instanceMatrix"&&C.instanceMatrix)R$=C.instanceMatrix;if(e==="instanceColor"&&C.instanceColor)R$=C.instanceColor}let w$={};if(w$.attribute=R$,R$&&R$.data)w$.data=R$.data;d[e]=w$,y++}K.attributes=d,K.attributesNum=y,K.index=x}function R(){let C=K.newAttributes;for(let f=0,s=C.length;f<s;f++)C[f]=0}function q(C){Z(C,0)}function Z(C,f){let{newAttributes:s,enabledAttributes:x,attributeDivisors:d}=K;if(s[C]=1,x[C]===0)$.enableVertexAttribArray(C),x[C]=1;if(d[C]!==f)$.vertexAttribDivisor(C,f),d[C]=f}function _(){let{newAttributes:C,enabledAttributes:f}=K;for(let s=0,x=f.length;s<x;s++)if(f[s]!==C[s])$.disableVertexAttribArray(s),f[s]=0}function P(C,f,s,x,d,c,y){if(y===!0)$.vertexAttribIPointer(C,f,s,d,c);else $.vertexAttribPointer(C,f,s,x,d,c)}function L(C,f,s,x){R();let d=x.attributes,c=s.getAttributes(),y=f.defaultAttributeValues;for(let t in c){let e=c[t];if(e.location>=0){let Y$=d[t];if(Y$===void 0){if(t==="instanceMatrix"&&C.instanceMatrix)Y$=C.instanceMatrix;if(t==="instanceColor"&&C.instanceColor)Y$=C.instanceColor}if(Y$!==void 0){let{normalized:R$,itemSize:w$}=Y$,$6=U.get(Y$);if($6===void 0)continue;let{buffer:n$,type:i,bytesPerElement:X$}=$6,D$=i===$.INT||i===$.UNSIGNED_INT||Y$.gpuType===ZX;if(Y$.isInterleavedBufferAttribute){let F$=Y$.data,v$=F$.stride,t$=Y$.offset;if(F$.isInstancedInterleavedBuffer){for(let u$=0;u$<e.locationSize;u$++)Z(e.location+u$,F$.meshPerAttribute);if(C.isInstancedMesh!==!0&&x._maxInstanceCount===void 0)x._maxInstanceCount=F$.meshPerAttribute*F$.count}else for(let u$=0;u$<e.locationSize;u$++)q(e.location+u$);$.bindBuffer($.ARRAY_BUFFER,n$);for(let u$=0;u$<e.locationSize;u$++)P(e.location+u$,w$/e.locationSize,i,R$,v$*X$,(t$+w$/e.locationSize*u$)*X$,D$)}else{if(Y$.isInstancedBufferAttribute){for(let F$=0;F$<e.locationSize;F$++)Z(e.location+F$,Y$.meshPerAttribute);if(C.isInstancedMesh!==!0&&x._maxInstanceCount===void 0)x._maxInstanceCount=Y$.meshPerAttribute*Y$.count}else for(let F$=0;F$<e.locationSize;F$++)q(e.location+F$);$.bindBuffer($.ARRAY_BUFFER,n$);for(let F$=0;F$<e.locationSize;F$++)P(e.location+F$,w$/e.locationSize,i,R$,w$*X$,w$/e.locationSize*F$*X$,D$)}}else if(y!==void 0){let R$=y[t];if(R$!==void 0)switch(R$.length){case 2:$.vertexAttrib2fv(e.location,R$);break;case 3:$.vertexAttrib3fv(e.location,R$);break;case 4:$.vertexAttrib4fv(e.location,R$);break;default:$.vertexAttrib1fv(e.location,R$)}}}}_()}function B(){w();for(let C in Q){let f=Q[C];for(let s in f){let x=f[s];for(let d in x){let c=x[d];for(let y in c)G(c[y].object),delete c[y];delete x[d]}}delete Q[C]}}function z(C){if(Q[C.id]===void 0)return;let f=Q[C.id];for(let s in f){let x=f[s];for(let d in x){let c=x[d];for(let y in c)G(c[y].object),delete c[y];delete x[d]}}delete Q[C.id]}function A(C){for(let f in Q){let s=Q[f];for(let x in s){let d=s[x];if(d[C.id]===void 0)continue;let c=d[C.id];for(let y in c)G(c[y].object),delete c[y];delete d[C.id]}}}function D(C){for(let f in Q){let s=Q[f],x=C.isInstancedMesh===!0?C.id:0,d=s[x];if(d===void 0)continue;for(let c in d){let y=d[c];for(let t in y)G(y[t].object),delete y[t];delete d[c]}if(delete s[x],Object.keys(s).length===0)delete Q[f]}}function w(){if(h(),X=!0,K===W)return;K=W,Y(K.object)}function h(){W.geometry=null,W.program=null,W.wireframe=!1}return{setup:H,reset:w,resetDefaultState:h,dispose:B,releaseStatesOfGeometry:z,releaseStatesOfObject:D,releaseStatesOfProgram:A,initAttributes:R,enableAttribute:q,disableUnusedAttributes:_}}function cR($,U,J){let Q;function W(N){Q=N}function K(N,Y){$.drawArrays(Q,N,Y),J.update(Y,Q,1)}function X(N,Y,G){if(G===0)return;$.drawArraysInstanced(Q,N,Y,G),J.update(Y,Q,G)}function H(N,Y,G){if(G===0)return;U.get("WEBGL_multi_draw").multiDrawArraysWEBGL(Q,N,0,Y,0,G);let E=0;for(let k=0;k<G;k++)E+=Y[k];J.update(E,Q,1)}this.setMode=W,this.render=K,this.renderInstances=X,this.renderMultiDraw=H}function nR($,U,J,Q){let W;function K(){if(W!==void 0)return W;if(U.has("EXT_texture_filter_anisotropic")===!0){let A=U.get("EXT_texture_filter_anisotropic");W=$.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else W=0;return W}function X(A){if(A!==QJ&&Q.convert(A)!==$.getParameter($.IMPLEMENTATION_COLOR_READ_FORMAT))return!1;return!0}function H(A){let D=A===CJ&&(U.has("EXT_color_buffer_half_float")||U.has("EXT_color_buffer_float"));if(A!==nU&&Q.convert(A)!==$.getParameter($.IMPLEMENTATION_COLOR_READ_TYPE)&&A!==AJ&&!D)return!1;return!0}function N(A){if(A==="highp"){if($.getShaderPrecisionFormat($.VERTEX_SHADER,$.HIGH_FLOAT).precision>0&&$.getShaderPrecisionFormat($.FRAGMENT_SHADER,$.HIGH_FLOAT).precision>0)return"highp";A="mediump"}if(A==="mediump"){if($.getShaderPrecisionFormat($.VERTEX_SHADER,$.MEDIUM_FLOAT).precision>0&&$.getShaderPrecisionFormat($.FRAGMENT_SHADER,$.MEDIUM_FLOAT).precision>0)return"mediump"}return"lowp"}let Y=J.precision!==void 0?J.precision:"highp",G=N(Y);if(G!==Y)A$("WebGLRenderer:",Y,"not supported, using",G,"instead."),Y=G;let O=J.logarithmicDepthBuffer===!0,E=J.reversedDepthBuffer===!0&&U.has("EXT_clip_control");if(J.reversedDepthBuffer===!0&&E===!1)A$("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let k=$.getParameter($.MAX_TEXTURE_IMAGE_UNITS),I=$.getParameter($.MAX_VERTEX_TEXTURE_IMAGE_UNITS),R=$.getParameter($.MAX_TEXTURE_SIZE),q=$.getParameter($.MAX_CUBE_MAP_TEXTURE_SIZE),Z=$.getParameter($.MAX_VERTEX_ATTRIBS),_=$.getParameter($.MAX_VERTEX_UNIFORM_VECTORS),P=$.getParameter($.MAX_VARYING_VECTORS),L=$.getParameter($.MAX_FRAGMENT_UNIFORM_VECTORS),B=$.getParameter($.MAX_SAMPLES),z=$.getParameter($.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:K,getMaxPrecision:N,textureFormatReadable:X,textureTypeReadable:H,precision:Y,logarithmicDepthBuffer:O,reversedDepthBuffer:E,maxTextures:k,maxVertexTextures:I,maxTextureSize:R,maxCubemapSize:q,maxAttributes:Z,maxVertexUniforms:_,maxVaryings:P,maxFragmentUniforms:L,maxSamples:B,samples:z}}function iR($){let U=this,J=null,Q=0,W=!1,K=!1,X=new lU,H=new f$,N={value:null,needsUpdate:!1};this.uniform=N,this.numPlanes=0,this.numIntersection=0,this.init=function(O,E){let k=O.length!==0||E||Q!==0||W;return W=E,Q=O.length,k},this.beginShadows=function(){K=!0,G(null)},this.endShadows=function(){K=!1},this.setGlobalState=function(O,E){J=G(O,E,0)},this.setState=function(O,E,k){let{clippingPlanes:I,clipIntersection:R,clipShadows:q}=O,Z=$.get(O);if(!W||I===null||I.length===0||K&&!q)if(K)G(null);else Y();else{let _=K?0:Q,P=_*4,L=Z.clippingState||null;N.value=L,L=G(I,E,P,k);for(let B=0;B!==P;++B)L[B]=J[B];Z.clippingState=L,this.numIntersection=R?this.numPlanes:0,this.numPlanes+=_}};function Y(){if(N.value!==J)N.value=J,N.needsUpdate=Q>0;U.numPlanes=Q,U.numIntersection=0}function G(O,E,k,I){let R=O!==null?O.length:0,q=null;if(R!==0){if(q=N.value,I!==!0||q===null){let Z=k+R*4,_=E.matrixWorldInverse;if(H.getNormalMatrix(_),q===null||q.length<Z)q=new Float32Array(Z);for(let P=0,L=k;P!==R;++P,L+=4)X.copy(O[P]).applyMatrix4(_,H),X.normal.toArray(q,L),q[L+3]=X.constant}N.value=q,N.needsUpdate=!0}return U.numPlanes=R,U.numIntersection=0,q}}var X0=4,WZ=[0.125,0.215,0.35,0.446,0.526,0.582],b0=20,oR=256,uW=new g0,QZ=new y$,PH=null,zH=0,_H=0,AH=!1,rR=new j;class dW{constructor($){this._renderer=$,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($,U=0,J=0.1,Q=100,W={}){let{size:K=256,position:X=rR}=W;PH=this._renderer.getRenderTarget(),zH=this._renderer.getActiveCubeFace(),_H=this._renderer.getActiveMipmapLevel(),AH=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(K);let H=this._allocateTargets();if(H.depthBuffer=!0,this._sceneToCubeUV($,J,Q,H,X),U>0)this._blur(H,0,0,U);return this._applyPMREM(H),this._cleanup(H),H}fromEquirectangular($,U=null){return this._fromTexture($,U)}fromCubemap($,U=null){return this._fromTexture($,U)}compileCubemapShader(){if(this._cubemapMaterial===null)this._cubemapMaterial=HZ(),this._compileMaterial(this._cubemapMaterial)}compileEquirectangularShader(){if(this._equirectMaterial===null)this._equirectMaterial=XZ(),this._compileMaterial(this._equirectMaterial)}dispose(){if(this._dispose(),this._cubemapMaterial!==null)this._cubemapMaterial.dispose();if(this._equirectMaterial!==null)this._equirectMaterial.dispose();if(this._backgroundBox!==null)this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose()}_setSize($){this._lodMax=Math.floor(Math.log2($)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){if(this._blurMaterial!==null)this._blurMaterial.dispose();if(this._ggxMaterial!==null)this._ggxMaterial.dispose();if(this._pingPongRenderTarget!==null)this._pingPongRenderTarget.dispose();for(let $=0;$<this._lodMeshes.length;$++)this._lodMeshes[$].geometry.dispose()}_cleanup($){this._renderer.setRenderTarget(PH,zH,_H),this._renderer.xr.enabled=AH,$.scissorTest=!1,A8($,0,0,$.width,$.height)}_fromTexture($,U){if($.mapping===Z8||$.mapping===z0)this._setSize($.image.length===0?16:$.image[0].width||$.image[0].image.width);else this._setSize($.image.width/4);PH=this._renderer.getRenderTarget(),zH=this._renderer.getActiveCubeFace(),_H=this._renderer.getActiveMipmapLevel(),AH=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let J=U||this._allocateTargets();return this._textureToCubeUV($,J),this._applyPMREM(J),this._cleanup(J),J}_allocateTargets(){let $=3*Math.max(this._cubeSize,112),U=4*this._cubeSize,J={magFilter:n6,minFilter:n6,generateMipmaps:!1,type:CJ,format:QJ,colorSpace:RU,depthBuffer:!1},Q=KZ($,U,J);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==$||this._pingPongRenderTarget.height!==U){if(this._pingPongRenderTarget!==null)this._dispose();this._pingPongRenderTarget=KZ($,U,J);let{_lodMax:W}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=aR(W)),this._blurMaterial=tR(W,$,U),this._ggxMaterial=sR(W,$,U)}return Q}_compileMaterial($){let U=new B6(new KU,$);this._renderer.compile(U,uW)}_sceneToCubeUV($,U,J,Q,W){let H=new x6(90,1,U,J),N=[1,-1,1,1,1,1],Y=[1,1,1,-1,-1,-1],G=this._renderer,O=G.autoClear,E=G.toneMapping;if(G.getClearColor(QZ),G.toneMapping=dU,G.autoClear=!1,G.state.buffers.depth.getReversed())G.setRenderTarget(Q),G.clearDepth(),G.setRenderTarget(null);if(this._backgroundBox===null)this._backgroundBox=new B6(new $0,new KJ({name:"PMREM.Background",side:$U,depthWrite:!1,depthTest:!1}));let I=this._backgroundBox,R=I.material,q=!1,Z=$.background;if(Z){if(Z.isColor)R.color.copy(Z),$.background=null,q=!0}else R.color.copy(QZ),q=!0;for(let _=0;_<6;_++){let P=_%3;if(P===0)H.up.set(0,N[_],0),H.position.set(W.x,W.y,W.z),H.lookAt(W.x+Y[_],W.y,W.z);else if(P===1)H.up.set(0,0,N[_]),H.position.set(W.x,W.y,W.z),H.lookAt(W.x,W.y+Y[_],W.z);else H.up.set(0,N[_],0),H.position.set(W.x,W.y,W.z),H.lookAt(W.x,W.y,W.z+Y[_]);let L=this._cubeSize;if(A8(Q,P*L,_>2?L:0,L,L),G.setRenderTarget(Q),q)G.render(I,H);G.render($,H)}G.toneMapping=E,G.autoClear=O,$.background=Z}_textureToCubeUV($,U){let J=this._renderer,Q=$.mapping===Z8||$.mapping===z0;if(Q){if(this._cubemapMaterial===null)this._cubemapMaterial=HZ();this._cubemapMaterial.uniforms.flipEnvMap.value=$.isRenderTargetTexture===!1?-1:1}else if(this._equirectMaterial===null)this._equirectMaterial=XZ();let W=Q?this._cubemapMaterial:this._equirectMaterial,K=this._lodMeshes[0];K.material=W;let X=W.uniforms;X.envMap.value=$;let H=this._cubeSize;A8(U,0,0,3*H,2*H),J.setRenderTarget(U),J.render(K,uW)}_applyPMREM($){let U=this._renderer,J=U.autoClear;U.autoClear=!1;let Q=this._lodMeshes.length;for(let W=1;W<Q;W++)this._applyGGXFilter($,W-1,W);U.autoClear=J}_applyGGXFilter($,U,J){let Q=this._renderer,W=this._pingPongRenderTarget,K=this._ggxMaterial,X=this._lodMeshes[J];X.material=K;let H=K.uniforms,N=J/(this._lodMeshes.length-1),Y=U/(this._lodMeshes.length-1),G=Math.sqrt(N*N-Y*Y),O=0+N*1.25,E=G*O,{_lodMax:k}=this,I=this._sizeLods[J],R=3*I*(J>k-X0?J-k+X0:0),q=4*(this._cubeSize-I);H.envMap.value=$.texture,H.roughness.value=E,H.mipInt.value=k-U,A8(W,R,q,3*I,2*I),Q.setRenderTarget(W),Q.render(X,uW),H.envMap.value=W.texture,H.roughness.value=0,H.mipInt.value=k-J,A8($,R,q,3*I,2*I),Q.setRenderTarget($),Q.render(X,uW)}_blur($,U,J,Q,W){let K=this._pingPongRenderTarget;this._halfBlur($,K,U,J,Q,"latitudinal",W),this._halfBlur(K,$,J,J,Q,"longitudinal",W)}_halfBlur($,U,J,Q,W,K,X){let H=this._renderer,N=this._blurMaterial;if(K!=="latitudinal"&&K!=="longitudinal")x$("blur direction must be either latitudinal or longitudinal!");let Y=3,G=this._lodMeshes[Q];G.material=N;let O=N.uniforms,E=this._sizeLods[J]-1,k=isFinite(W)?Math.PI/(2*E):2*Math.PI/(2*b0-1),I=W/k,R=isFinite(W)?1+Math.floor(Y*I):b0;if(R>b0)A$(`sigmaRadians, ${W}, is too large and will clip, as it requested ${R} samples when the maximum is set to ${b0}`);let q=[],Z=0;for(let z=0;z<b0;++z){let A=z/I,D=Math.exp(-A*A/2);if(q.push(D),z===0)Z+=D;else if(z<R)Z+=2*D}for(let z=0;z<q.length;z++)q[z]=q[z]/Z;if(O.envMap.value=$.texture,O.samples.value=R,O.weights.value=q,O.latitudinal.value=K==="latitudinal",X)O.poleAxis.value=X;let{_lodMax:_}=this;O.dTheta.value=k,O.mipInt.value=_-J;let P=this._sizeLods[Q],L=3*P*(Q>_-X0?Q-_+X0:0),B=4*(this._cubeSize-P);A8(U,L,B,3*P,2*P),H.setRenderTarget(U),H.render(G,uW)}}function aR($){let U=[],J=[],Q=[],W=$,K=$-X0+1+WZ.length;for(let X=0;X<K;X++){let H=Math.pow(2,W);U.push(H);let N=1/H;if(X>$-X0)N=WZ[X-$+X0-1];else if(X===0)N=0;J.push(N);let Y=1/(H-2),G=-Y,O=1+Y,E=[G,G,O,G,O,O,G,G,O,O,G,O],k=6,I=6,R=3,q=2,Z=1,_=new Float32Array(R*I*k),P=new Float32Array(q*I*k),L=new Float32Array(Z*I*k);for(let z=0;z<k;z++){let A=z%3*2/3-1,D=z>2?0:-1,w=[A,D,0,A+0.6666666666666666,D,0,A+0.6666666666666666,D+1,0,A,D,0,A+0.6666666666666666,D+1,0,A,D+1,0];_.set(w,R*I*z),P.set(E,q*I*z);let h=[z,z,z,z,z,z];L.set(h,Z*I*z)}let B=new KU;if(B.setAttribute("position",new h6(_,R)),B.setAttribute("uv",new h6(P,q)),B.setAttribute("faceIndex",new h6(L,Z)),Q.push(new B6(B,null)),W>X0)W--}return{lodMeshes:Q,sizeLods:U,sigmas:J}}function KZ($,U,J){let Q=new jU($,U,J);return Q.texture.mapping=MW,Q.texture.name="PMREM.cubeUv",Q.scissorTest=!0,Q}function A8($,U,J,Q,W){$.viewport.set(U,J,Q,W),$.scissor.set(U,J,Q,W)}function sR($,U,J){return new gU({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:oR,CUBEUV_TEXEL_WIDTH:1/U,CUBEUV_TEXEL_HEIGHT:1/J,CUBEUV_MAX_MIP:`${$}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:d9(),fragmentShader:`+}`,Ge={alphahash_fragment:Gx,alphahash_pars_fragment:Hx,alphamap_fragment:Vx,alphamap_pars_fragment:Wx,alphatest_fragment:$x,alphatest_pars_fragment:Zx,aomap_fragment:Xx,aomap_pars_fragment:qx,batching_pars_vertex:Yx,batching_vertex:jx,begin_vertex:Jx,beginnormal_vertex:Kx,bsdfs:Qx,iridescence_fragment:ev,bumpmap_pars_fragment:tv,clipping_planes_fragment:nv,clipping_planes_pars_fragment:iv,clipping_planes_pars_vertex:rv,clipping_planes_vertex:sv,color_fragment:ov,color_pars_fragment:av,color_pars_vertex:cv,color_vertex:lv,common:uv,cube_uv_reflection_fragment:hv,defaultnormal_vertex:fv,displacementmap_pars_vertex:dv,displacementmap_vertex:pv,emissivemap_fragment:mv,emissivemap_pars_fragment:gv,colorspace_fragment:_v,colorspace_pars_fragment:xv,envmap_fragment:vv,envmap_common_pars_fragment:yv,envmap_pars_fragment:bv,envmap_pars_vertex:Sv,envmap_physical_pars_fragment:Nv,envmap_vertex:Mv,fog_vertex:wv,fog_pars_vertex:Tv,fog_fragment:Ev,fog_pars_fragment:Av,gradientmap_pars_fragment:Rv,lightmap_pars_fragment:Cv,lights_lambert_fragment:Pv,lights_lambert_pars_fragment:Iv,lights_pars_begin:Lv,lights_toon_fragment:Dv,lights_toon_pars_fragment:Uv,lights_phong_fragment:Ov,lights_phong_pars_fragment:Fv,lights_physical_fragment:zv,lights_physical_pars_fragment:kv,lights_fragment_begin:Bv,lights_fragment_maps:Gv,lights_fragment_end:Hv,lightprobes_pars_fragment:Vv,logdepthbuf_fragment:Wv,logdepthbuf_pars_fragment:$v,logdepthbuf_pars_vertex:Zv,logdepthbuf_vertex:Xv,map_fragment:qv,map_pars_fragment:Yv,map_particle_fragment:jv,map_particle_pars_fragment:Jv,metalnessmap_fragment:Kv,metalnessmap_pars_fragment:Qv,morphinstance_vertex:ey,morphcolor_vertex:ty,morphnormal_vertex:ny,morphtarget_pars_vertex:iy,morphtarget_vertex:ry,normal_fragment_begin:sy,normal_fragment_maps:oy,normal_pars_fragment:ay,normal_pars_vertex:cy,normal_vertex:ly,normalmap_pars_fragment:uy,clearcoat_normal_fragment_begin:hy,clearcoat_normal_fragment_maps:fy,clearcoat_pars_fragment:dy,iridescence_pars_fragment:py,opaque_fragment:my,packing:gy,premultiplied_alpha_fragment:_y,project_vertex:xy,dithering_fragment:vy,dithering_pars_fragment:yy,roughnessmap_fragment:by,roughnessmap_pars_fragment:Sy,shadowmap_pars_fragment:My,shadowmap_pars_vertex:wy,shadowmap_vertex:Ty,shadowmask_pars_fragment:Ey,skinbase_vertex:Ay,skinning_pars_vertex:Ry,skinning_vertex:Cy,skinnormal_vertex:Py,specularmap_fragment:Iy,specularmap_pars_fragment:Ly,tonemapping_fragment:Ny,tonemapping_pars_fragment:Dy,transmission_fragment:Uy,transmission_pars_fragment:Oy,uv_pars_fragment:Fy,uv_pars_vertex:zy,uv_vertex:ky,worldpos_vertex:By,background_vert:Gy,background_frag:Hy,backgroundCube_vert:Vy,backgroundCube_frag:Wy,cube_vert:$y,cube_frag:Zy,depth_vert:Xy,depth_frag:qy,distance_vert:Yy,distance_frag:jy,equirect_vert:Jy,equirect_frag:Ky,linedashed_vert:Qy,linedashed_frag:eb,meshbasic_vert:tb,meshbasic_frag:nb,meshlambert_vert:ib,meshlambert_frag:rb,meshmatcap_vert:sb,meshmatcap_frag:ob,meshnormal_vert:ab,meshnormal_frag:cb,meshphong_vert:lb,meshphong_frag:ub,meshphysical_vert:hb,meshphysical_frag:fb,meshtoon_vert:db,meshtoon_frag:pb,points_vert:mb,points_frag:gb,shadow_vert:_b,shadow_frag:xb,sprite_vert:vb,sprite_frag:yb},he={common:{diffuse:{value:new Le(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new De},alphaMap:{value:null},alphaMapTransform:{value:new De},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new De}},envmap:{envMap:{value:null},envMapRotation:{value:new De},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:0.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new De}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new De}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new De},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new De},normalScale:{value:new Pe(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new De},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new De}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new De}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new De}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:0.00025},fogNear:{value:1},fogFar:{value:2000},fogColor:{value:new Le(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 N},probesMax:{value:new N},probesResolution:{value:new N}},points:{diffuse:{value:new Le(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new De},alphaTest:{value:0},uvTransform:{value:new De}},sprite:{diffuse:{value:new Le(16777215)},opacity:{value:1},center:{value:new Pe(0.5,0.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new De},alphaMap:{value:null},alphaMapTransform:{value:new De},alphaTest:{value:0}}},qn={basic:{uniforms:qt([he.common,he.specularmap,he.envmap,he.aomap,he.lightmap,he.fog]),vertexShader:Ge.meshbasic_vert,fragmentShader:Ge.meshbasic_frag},lambert:{uniforms:qt([he.common,he.specularmap,he.envmap,he.aomap,he.lightmap,he.emissivemap,he.bumpmap,he.normalmap,he.displacementmap,he.fog,he.lights,{emissive:{value:new Le(0)},envMapIntensity:{value:1}}]),vertexShader:Ge.meshlambert_vert,fragmentShader:Ge.meshlambert_frag},phong:{uniforms:qt([he.common,he.specularmap,he.envmap,he.aomap,he.lightmap,he.emissivemap,he.bumpmap,he.normalmap,he.displacementmap,he.fog,he.lights,{emissive:{value:new Le(0)},specular:{value:new Le(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Ge.meshphong_vert,fragmentShader:Ge.meshphong_frag},standard:{uniforms:qt([he.common,he.envmap,he.aomap,he.lightmap,he.emissivemap,he.bumpmap,he.normalmap,he.displacementmap,he.roughnessmap,he.metalnessmap,he.fog,he.lights,{emissive:{value:new Le(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ge.meshphysical_vert,fragmentShader:Ge.meshphysical_frag},toon:{uniforms:qt([he.common,he.aomap,he.lightmap,he.emissivemap,he.bumpmap,he.normalmap,he.displacementmap,he.gradientmap,he.fog,he.lights,{emissive:{value:new Le(0)}}]),vertexShader:Ge.meshtoon_vert,fragmentShader:Ge.meshtoon_frag},matcap:{uniforms:qt([he.common,he.bumpmap,he.normalmap,he.displacementmap,he.fog,{matcap:{value:null}}]),vertexShader:Ge.meshmatcap_vert,fragmentShader:Ge.meshmatcap_frag},points:{uniforms:qt([he.points,he.fog]),vertexShader:Ge.points_vert,fragmentShader:Ge.points_frag},dashed:{uniforms:qt([he.common,he.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ge.linedashed_vert,fragmentShader:Ge.linedashed_frag},depth:{uniforms:qt([he.common,he.displacementmap]),vertexShader:Ge.depth_vert,fragmentShader:Ge.depth_frag},normal:{uniforms:qt([he.common,he.bumpmap,he.normalmap,he.displacementmap,{opacity:{value:1}}]),vertexShader:Ge.meshnormal_vert,fragmentShader:Ge.meshnormal_frag},sprite:{uniforms:qt([he.sprite,he.fog]),vertexShader:Ge.sprite_vert,fragmentShader:Ge.sprite_frag},background:{uniforms:{uvTransform:{value:new De},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ge.background_vert,fragmentShader:Ge.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new De}},vertexShader:Ge.backgroundCube_vert,fragmentShader:Ge.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ge.cube_vert,fragmentShader:Ge.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ge.equirect_vert,fragmentShader:Ge.equirect_frag},distance:{uniforms:qt([he.common,he.displacementmap,{referencePosition:{value:new N},nearDistance:{value:1},farDistance:{value:1000}}]),vertexShader:Ge.distance_vert,fragmentShader:Ge.distance_frag},shadow:{uniforms:qt([he.lights,he.fog,{color:{value:new Le(0)},opacity:{value:1}}]),vertexShader:Ge.shadow_vert,fragmentShader:Ge.shadow_frag}};qn.physical={uniforms:qt([qn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new De},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new De},clearcoatNormalScale:{value:new Pe(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new De},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new De},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new De},sheen:{value:0},sheenColor:{value:new Le(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new De},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new De},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new De},transmissionSamplerSize:{value:new Pe},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new De},attenuationDistance:{value:0},attenuationColor:{value:new Le(0)},specularColor:{value:new Le(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new De},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new De},anisotropyVector:{value:new Pe},anisotropyMap:{value:null},anisotropyMapTransform:{value:new De}}]),vertexShader:Ge.meshphysical_vert,fragmentShader:Ge.meshphysical_frag};var ma={r:0,b:0,g:0},bb=new Fe,Sd=new De;Sd.set(-1,0,0,0,1,0,0,0,1);function Sb(e,t,n,i,r,s){let o=new Le(0),a=r===!0?0:1,c,l,u=null,f=0,h=null;function d(A){let T=A.isScene===!0?A.background:null;if(T&&T.isTexture){let v=A.backgroundBlurriness>0;T=t.get(T,v)}return T}function g(A){let T=!1,v=d(A);if(v===null)p(o,a);else if(v&&v.isColor)p(v,1),T=!0;let w=e.xr.getEnvironmentBlendMode();if(w==="additive")n.buffers.color.setClear(0,0,0,1,s);else if(w==="alpha-blend")n.buffers.color.setClear(0,0,0,0,s);if(e.autoClear||T)n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil)}function b(A,T){let v=d(T);if(v&&(v.isCubeTexture||v.mapping===ys)){if(l===void 0)l=new dt(new Di(1,1,1),new bn({name:"BackgroundCubeMaterial",uniforms:cr(qn.backgroundCube.uniforms),vertexShader:qn.backgroundCube.vertexShader,fragmentShader:qn.backgroundCube.fragmentShader,side:Xt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(w,E,R){this.matrixWorld.copyPosition(R.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(l);if(l.material.uniforms.envMap.value=v,l.material.uniforms.backgroundBlurriness.value=T.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=T.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(bb.makeRotationFromEuler(T.backgroundRotation)).transpose(),v.isCubeTexture&&v.isRenderTargetTexture===!1)l.material.uniforms.backgroundRotation.value.premultiply(Sd);if(l.material.toneMapped=Ve.getTransfer(v.colorSpace)!==ut,u!==v||f!==v.version||h!==e.toneMapping)l.material.needsUpdate=!0,u=v,f=v.version,h=e.toneMapping;l.layers.enableAll(),A.unshift(l,l.geometry,l.material,0,0,null)}else if(v&&v.isTexture){if(c===void 0)c=new dt(new Ns(2,2),new bn({name:"BackgroundMaterial",uniforms:cr(qn.background.uniforms),vertexShader:qn.background.vertexShader,fragmentShader:qn.background.fragmentShader,side:Ri,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(c);if(c.material.uniforms.t2D.value=v,c.material.uniforms.backgroundIntensity.value=T.backgroundIntensity,c.material.toneMapped=Ve.getTransfer(v.colorSpace)!==ut,v.matrixAutoUpdate===!0)v.updateMatrix();if(c.material.uniforms.uvTransform.value.copy(v.matrix),u!==v||f!==v.version||h!==e.toneMapping)c.material.needsUpdate=!0,u=v,f=v.version,h=e.toneMapping;c.layers.enableAll(),A.unshift(c,c.geometry,c.material,0,0,null)}}function p(A,T){A.getRGB(ma,wl(e)),n.buffers.color.setClear(ma.r,ma.g,ma.b,T,s)}function m(){if(l!==void 0)l.geometry.dispose(),l.material.dispose(),l=void 0;if(c!==void 0)c.geometry.dispose(),c.material.dispose(),c=void 0}return{getClearColor:function(){return o},setClearColor:function(A,T=1){o.set(A),a=T,p(o,a)},getClearAlpha:function(){return a},setClearAlpha:function(A){a=A,p(o,a)},render:g,addToRenderList:b,dispose:m}}function Mb(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=h(null),s=r,o=!1;function a(C,z,J,O,H){let V=!1,U=f(C,O,J,z);if(s!==U)s=U,l(s.object);if(V=d(C,O,J,H),V)g(C,O,J,H);if(H!==null)t.update(H,e.ELEMENT_ARRAY_BUFFER);if(V||o){if(o=!1,v(C,z,J,O),H!==null)e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(H).buffer)}}function c(){return e.createVertexArray()}function l(C){return e.bindVertexArray(C)}function u(C){return e.deleteVertexArray(C)}function f(C,z,J,O){let H=O.wireframe===!0,V=i[z.id];if(V===void 0)V={},i[z.id]=V;let U=C.isInstancedMesh===!0?C.id:0,K=V[U];if(K===void 0)K={},V[U]=K;let Q=K[J.id];if(Q===void 0)Q={},K[J.id]=Q;let se=Q[H];if(se===void 0)se=h(c()),Q[H]=se;return se}function h(C){let z=[],J=[],O=[];for(let H=0;H<n;H++)z[H]=0,J[H]=0,O[H]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:z,enabledAttributes:J,attributeDivisors:O,object:C,attributes:{},index:null}}function d(C,z,J,O){let H=s.attributes,V=z.attributes,U=0,K=J.getAttributes();for(let Q in K)if(K[Q].location>=0){let me=H[Q],_e=V[Q];if(_e===void 0){if(Q==="instanceMatrix"&&C.instanceMatrix)_e=C.instanceMatrix;if(Q==="instanceColor"&&C.instanceColor)_e=C.instanceColor}if(me===void 0)return!0;if(me.attribute!==_e)return!0;if(_e&&me.data!==_e.data)return!0;U++}if(s.attributesNum!==U)return!0;if(s.index!==O)return!0;return!1}function g(C,z,J,O){let H={},V=z.attributes,U=0,K=J.getAttributes();for(let Q in K)if(K[Q].location>=0){let me=V[Q];if(me===void 0){if(Q==="instanceMatrix"&&C.instanceMatrix)me=C.instanceMatrix;if(Q==="instanceColor"&&C.instanceColor)me=C.instanceColor}let _e={};if(_e.attribute=me,me&&me.data)_e.data=me.data;H[Q]=_e,U++}s.attributes=H,s.attributesNum=U,s.index=O}function b(){let C=s.newAttributes;for(let z=0,J=C.length;z<J;z++)C[z]=0}function p(C){m(C,0)}function m(C,z){let J=s.newAttributes,O=s.enabledAttributes,H=s.attributeDivisors;if(J[C]=1,O[C]===0)e.enableVertexAttribArray(C),O[C]=1;if(H[C]!==z)e.vertexAttribDivisor(C,z),H[C]=z}function A(){let C=s.newAttributes,z=s.enabledAttributes;for(let J=0,O=z.length;J<O;J++)if(z[J]!==C[J])e.disableVertexAttribArray(J),z[J]=0}function T(C,z,J,O,H,V,U){if(U===!0)e.vertexAttribIPointer(C,z,J,H,V);else e.vertexAttribPointer(C,z,J,O,H,V)}function v(C,z,J,O){b();let H=O.attributes,V=J.getAttributes(),U=z.defaultAttributeValues;for(let K in V){let Q=V[K];if(Q.location>=0){let se=H[K];if(se===void 0){if(K==="instanceMatrix"&&C.instanceMatrix)se=C.instanceMatrix;if(K==="instanceColor"&&C.instanceColor)se=C.instanceColor}if(se!==void 0){let me=se.normalized,_e=se.itemSize,Xe=t.get(se);if(Xe===void 0)continue;let{buffer:Be,type:Z,bytesPerElement:ne}=Xe,fe=Z===e.INT||Z===e.UNSIGNED_INT||se.gpuType===Ic;if(se.isInterleavedBufferAttribute){let de=se.data,Re=de.stride,$e=se.offset;if(de.isInstancedInterleavedBuffer){for(let Ue=0;Ue<Q.locationSize;Ue++)m(Q.location+Ue,de.meshPerAttribute);if(C.isInstancedMesh!==!0&&O._maxInstanceCount===void 0)O._maxInstanceCount=de.meshPerAttribute*de.count}else for(let Ue=0;Ue<Q.locationSize;Ue++)p(Q.location+Ue);e.bindBuffer(e.ARRAY_BUFFER,Be);for(let Ue=0;Ue<Q.locationSize;Ue++)T(Q.location+Ue,_e/Q.locationSize,Z,me,Re*ne,($e+_e/Q.locationSize*Ue)*ne,fe)}else{if(se.isInstancedBufferAttribute){for(let de=0;de<Q.locationSize;de++)m(Q.location+de,se.meshPerAttribute);if(C.isInstancedMesh!==!0&&O._maxInstanceCount===void 0)O._maxInstanceCount=se.meshPerAttribute*se.count}else for(let de=0;de<Q.locationSize;de++)p(Q.location+de);e.bindBuffer(e.ARRAY_BUFFER,Be);for(let de=0;de<Q.locationSize;de++)T(Q.location+de,_e/Q.locationSize,Z,me,_e*ne,_e/Q.locationSize*de*ne,fe)}}else if(U!==void 0){let me=U[K];if(me!==void 0)switch(me.length){case 2:e.vertexAttrib2fv(Q.location,me);break;case 3:e.vertexAttrib3fv(Q.location,me);break;case 4:e.vertexAttrib4fv(Q.location,me);break;default:e.vertexAttrib1fv(Q.location,me)}}}}A()}function w(){S();for(let C in i){let z=i[C];for(let J in z){let O=z[J];for(let H in O){let V=O[H];for(let U in V)u(V[U].object),delete V[U];delete O[H]}}delete i[C]}}function E(C){if(i[C.id]===void 0)return;let z=i[C.id];for(let J in z){let O=z[J];for(let H in O){let V=O[H];for(let U in V)u(V[U].object),delete V[U];delete O[H]}}delete i[C.id]}function R(C){for(let z in i){let J=i[z];for(let O in J){let H=J[O];if(H[C.id]===void 0)continue;let V=H[C.id];for(let U in V)u(V[U].object),delete V[U];delete H[C.id]}}}function _(C){for(let z in i){let J=i[z],O=C.isInstancedMesh===!0?C.id:0,H=J[O];if(H===void 0)continue;for(let V in H){let U=H[V];for(let K in U)u(U[K].object),delete U[K];delete H[V]}if(delete J[O],Object.keys(J).length===0)delete i[z]}}function S(){if(F(),o=!0,s===r)return;s=r,l(s.object)}function F(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:a,reset:S,resetDefaultState:F,dispose:w,releaseStatesOfGeometry:E,releaseStatesOfObject:_,releaseStatesOfProgram:R,initAttributes:b,enableAttribute:p,disableUnusedAttributes:A}}function wb(e,t,n){let i;function r(c){i=c}function s(c,l){e.drawArrays(i,c,l),n.update(l,i,1)}function o(c,l,u){if(u===0)return;e.drawArraysInstanced(i,c,l,u),n.update(l,i,u)}function a(c,l,u){if(u===0)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,c,0,l,0,u);let h=0;for(let d=0;d<u;d++)h+=l[d];n.update(h,i,1)}this.setMode=r,this.render=s,this.renderInstances=o,this.renderMultiDraw=a}function Tb(e,t,n,i){let r;function s(){if(r!==void 0)return r;if(t.has("EXT_texture_filter_anisotropic")===!0){let R=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(R.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}function o(R){if(R!==$n&&i.convert(R)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))return!1;return!0}function a(R){let _=R===hi&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));if(R!==Ln&&i.convert(R)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&R!==ui&&!_)return!1;return!0}function c(R){if(R==="highp"){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";R="mediump"}if(R==="mediump"){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0)return"mediump"}return"lowp"}let l=n.precision!==void 0?n.precision:"highp",u=c(l);if(u!==l)Me("WebGLRenderer:",l,"not supported, using",u,"instead."),l=u;let f=n.logarithmicDepthBuffer===!0,h=n.reversedDepthBuffer===!0&&t.has("EXT_clip_control");if(n.reversedDepthBuffer===!0&&h===!1)Me("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let d=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),g=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),b=e.getParameter(e.MAX_TEXTURE_SIZE),p=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),m=e.getParameter(e.MAX_VERTEX_ATTRIBS),A=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),T=e.getParameter(e.MAX_VARYING_VECTORS),v=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),w=e.getParameter(e.MAX_SAMPLES),E=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:f,reversedDepthBuffer:h,maxTextures:d,maxVertexTextures:g,maxTextureSize:b,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:A,maxVaryings:T,maxFragmentUniforms:v,maxSamples:w,samples:E}}function Eb(e){let t=this,n=null,i=0,r=!1,s=!1,o=new An,a=new De,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(f,h){let d=f.length!==0||h||i!==0||r;return r=h,i=f.length,d},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(f,h){n=u(f,h,0)},this.setState=function(f,h,d){let{clippingPlanes:g,clipIntersection:b,clipShadows:p}=f,m=e.get(f);if(!r||g===null||g.length===0||s&&!p)if(s)u(null);else l();else{let A=s?0:i,T=A*4,v=m.clippingState||null;c.value=v,v=u(g,h,T,d);for(let w=0;w!==T;++w)v[w]=n[w];m.clippingState=v,this.numIntersection=b?this.numPlanes:0,this.numPlanes+=A}};function l(){if(c.value!==n)c.value=n,c.needsUpdate=i>0;t.numPlanes=i,t.numIntersection=0}function u(f,h,d,g){let b=f!==null?f.length:0,p=null;if(b!==0){if(p=c.value,g!==!0||p===null){let m=d+b*4,A=h.matrixWorldInverse;if(a.getNormalMatrix(A),p===null||p.length<m)p=new Float32Array(m);for(let T=0,v=d;T!==b;++T,v+=4)o.copy(f[T]).applyMatrix4(A,a),o.normal.toArray(p,v),p[v+3]=o.constant}c.value=p,c.needsUpdate=!0}return t.numPlanes=b,t.numIntersection=0,p}}var Bi=4,Qf=[0.125,0.215,0.35,0.446,0.526,0.582],hr=20,Ab=256,Fs=new ur,ed=new Le,Gl=null,Hl=0,Vl=0,Wl=!1,Rb=new N;class Gs{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=0.1,i=100,r={}){let{size:s=256,position:o=Rb}=r;Gl=this._renderer.getRenderTarget(),Hl=this._renderer.getActiveCubeFace(),Vl=this._renderer.getActiveMipmapLevel(),Wl=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);let a=this._allocateTargets();if(a.depthBuffer=!0,this._sceneToCubeUV(e,n,i,a,o),t>0)this._blur(a,0,0,t);return this._applyPMREM(a),this._cleanup(a),a}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){if(this._cubemapMaterial===null)this._cubemapMaterial=id(),this._compileMaterial(this._cubemapMaterial)}compileEquirectangularShader(){if(this._equirectMaterial===null)this._equirectMaterial=nd(),this._compileMaterial(this._equirectMaterial)}dispose(){if(this._dispose(),this._cubemapMaterial!==null)this._cubemapMaterial.dispose();if(this._equirectMaterial!==null)this._equirectMaterial.dispose();if(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(){if(this._blurMaterial!==null)this._blurMaterial.dispose();if(this._ggxMaterial!==null)this._ggxMaterial.dispose();if(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(Gl,Hl,Vl),this._renderer.xr.enabled=Wl,e.scissorTest=!1,es(e,0,0,e.width,e.height)}_fromTexture(e,t){if(e.mapping===Gr||e.mapping===nr)this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width);else this._setSize(e.image.width/4);Gl=this._renderer.getRenderTarget(),Hl=this._renderer.getActiveCubeFace(),Vl=this._renderer.getActiveMipmapLevel(),Wl=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:kt,minFilter:kt,generateMipmaps:!1,type:hi,format:$n,colorSpace:cn,depthBuffer:!1},i=td(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){if(this._pingPongRenderTarget!==null)this._dispose();this._pingPongRenderTarget=td(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=Cb(r)),this._blurMaterial=Ib(r,e,t),this._ggxMaterial=Pb(r,e,t)}return i}_compileMaterial(e){let t=new dt(new Kt,e);this._renderer.compile(t,Fs)}_sceneToCubeUV(e,t,n,i,r){let a=new Pt(90,1,t,n),c=[1,-1,1,1,1,1],l=[1,1,1,-1,-1,-1],u=this._renderer,{autoClear:f,toneMapping:h}=u;if(u.getClearColor(ed),u.toneMapping=Pn,u.autoClear=!1,u.state.buffers.depth.getReversed())u.setRenderTarget(i),u.clearDepth(),u.setRenderTarget(null);if(this._backgroundBox===null)this._backgroundBox=new dt(new Di,new Zn({name:"PMREM.Background",side:Xt,depthWrite:!1,depthTest:!1}));let g=this._backgroundBox,b=g.material,p=!1,m=e.background;if(m){if(m.isColor)b.color.copy(m),e.background=null,p=!0}else b.color.copy(ed),p=!0;for(let A=0;A<6;A++){let T=A%3;if(T===0)a.up.set(0,c[A],0),a.position.set(r.x,r.y,r.z),a.lookAt(r.x+l[A],r.y,r.z);else if(T===1)a.up.set(0,0,c[A]),a.position.set(r.x,r.y,r.z),a.lookAt(r.x,r.y+l[A],r.z);else a.up.set(0,c[A],0),a.position.set(r.x,r.y,r.z),a.lookAt(r.x,r.y,r.z+l[A]);let v=this._cubeSize;if(es(i,T*v,A>2?v:0,v,v),u.setRenderTarget(i),p)u.render(g,a);u.render(e,a)}u.toneMapping=h,u.autoClear=f,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===Gr||e.mapping===nr;if(i){if(this._cubemapMaterial===null)this._cubemapMaterial=id();this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1}else if(this._equirectMaterial===null)this._equirectMaterial=nd();let r=i?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=r;let o=r.uniforms;o.envMap.value=e;let a=this._cubeSize;es(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,Fs)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let i=this._lodMeshes.length;for(let r=1;r<i;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){let i=this._renderer,r=this._pingPongRenderTarget,s=this._ggxMaterial,o=this._lodMeshes[n];o.material=s;let a=s.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l),f=0+c*1.25,h=u*f,{_lodMax:d}=this,g=this._sizeLods[n],b=3*g*(n>d-Bi?n-d+Bi:0),p=4*(this._cubeSize-g);a.envMap.value=e.texture,a.roughness.value=h,a.mipInt.value=d-t,es(r,b,p,3*g,2*g),i.setRenderTarget(r),i.render(o,Fs),a.envMap.value=r.texture,a.roughness.value=0,a.mipInt.value=d-n,es(e,b,p,3*g,2*g),i.setRenderTarget(e),i.render(o,Fs)}_blur(e,t,n,i,r){let s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,i,"latitudinal",r),this._halfBlur(s,e,n,n,i,"longitudinal",r)}_halfBlur(e,t,n,i,r,s,o){let a=this._renderer,c=this._blurMaterial;if(s!=="latitudinal"&&s!=="longitudinal")Ne("blur direction must be either latitudinal or longitudinal!");let l=3,u=this._lodMeshes[i];u.material=c;let f=c.uniforms,h=this._sizeLods[n]-1,d=isFinite(r)?Math.PI/(2*h):2*Math.PI/(2*hr-1),g=r/d,b=isFinite(r)?1+Math.floor(l*g):hr;if(b>hr)Me(`sigmaRadians, ${r}, is too large and will clip, as it requested ${b} samples when the maximum is set to ${hr}`);let p=[],m=0;for(let E=0;E<hr;++E){let R=E/g,_=Math.exp(-R*R/2);if(p.push(_),E===0)m+=_;else if(E<b)m+=2*_}for(let E=0;E<p.length;E++)p[E]=p[E]/m;if(f.envMap.value=e.texture,f.samples.value=b,f.weights.value=p,f.latitudinal.value=s==="latitudinal",o)f.poleAxis.value=o;let{_lodMax:A}=this;f.dTheta.value=d,f.mipInt.value=A-n;let T=this._sizeLods[i],v=3*T*(i>A-Bi?i-A+Bi:0),w=4*(this._cubeSize-T);es(t,v,w,3*T,2*T),a.setRenderTarget(t),a.render(u,Fs)}}function Cb(e){let t=[],n=[],i=[],r=e,s=e-Bi+1+Qf.length;for(let o=0;o<s;o++){let a=Math.pow(2,r);t.push(a);let c=1/a;if(o>e-Bi)c=Qf[o-e+Bi-1];else if(o===0)c=0;n.push(c);let l=1/(a-2),u=-l,f=1+l,h=[u,u,f,u,f,f,u,u,f,f,u,f],d=6,g=6,b=3,p=2,m=1,A=new Float32Array(b*g*d),T=new Float32Array(p*g*d),v=new Float32Array(m*g*d);for(let E=0;E<d;E++){let R=E%3*2/3-1,_=E>2?0:-1,S=[R,_,0,R+0.6666666666666666,_,0,R+0.6666666666666666,_+1,0,R,_,0,R+0.6666666666666666,_+1,0,R,_+1,0];A.set(S,b*g*E),T.set(h,p*g*E);let F=[E,E,E,E,E,E];v.set(F,m*g*E)}let w=new Kt;if(w.setAttribute("position",new It(A,b)),w.setAttribute("uv",new It(T,p)),w.setAttribute("faceIndex",new It(v,m)),i.push(new dt(w,null)),r>Bi)r--}return{lodMeshes:i,sizeLods:t,sigmas:n}}function td(e,t,n){let i=new yn(e,t,n);return i.texture.mapping=ys,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function es(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function Pb(e,t,n){return new bn({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:Ab,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:_a(),fragmentShader:`precision highp float;precision highp int;@@ -3890,7 +3890,7 @@ void main() {gl_FragColor = vec4(prefilteredColor, 1.0);}- `,blending:JJ,depthTest:!1,depthWrite:!1})}function tR($,U,J){let Q=new Float32Array(b0),W=new j(0,1,0);return new gU({name:"SphericalGaussianBlur",defines:{n:b0,CUBEUV_TEXEL_WIDTH:1/U,CUBEUV_TEXEL_HEIGHT:1/J,CUBEUV_MAX_MIP:`${$}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:Q},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:W}},vertexShader:d9(),fragmentShader:`+ `,blending:Vn,depthTest:!1,depthWrite:!1})}function Ib(e,t,n){let i=new Float32Array(hr),r=new N(0,1,0);return new bn({name:"SphericalGaussianBlur",defines:{n:hr,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:_a(),fragmentShader:`precision mediump float;precision mediump int;@@ -3950,7 +3950,7 @@ void main() {}}- `,blending:JJ,depthTest:!1,depthWrite:!1})}function XZ(){return new gU({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:d9(),fragmentShader:`+ `,blending:Vn,depthTest:!1,depthWrite:!1})}function nd(){return new bn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:_a(),fragmentShader:`precision mediump float;precision mediump int;@@ -3969,7 +3969,7 @@ void main() {gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );}- `,blending:JJ,depthTest:!1,depthWrite:!1})}function HZ(){return new gU({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:d9(),fragmentShader:`+ `,blending:Vn,depthTest:!1,depthWrite:!1})}function id(){return new bn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:_a(),fragmentShader:`precision mediump float;precision mediump int;@@ -3985,7 +3985,7 @@ void main() {gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );}- `,blending:JJ,depthTest:!1,depthWrite:!1})}function d9(){return`+ `,blending:Vn,depthTest:!1,depthWrite:!1})}function _a(){return`precision mediump float;precision mediump int;@@ -4040,7 +4040,7 @@ void main() {gl_Position = vec4( position, 1.0 );}- `}class jH extends jU{constructor($=1,U={}){super($,$,U);this.isWebGLCubeRenderTarget=!0;let J={width:$,height:$,depth:1},Q=[J,J,J,J,J,J];this.texture=new C9(Q),this._setTextureOptions(U),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture($,U){this.texture.type=U.type,this.texture.colorSpace=U.colorSpace,this.texture.generateMipmaps=U.generateMipmaps,this.texture.minFilter=U.minFilter,this.texture.magFilter=U.magFilter;let J={uniforms:{tEquirect:{value:null}},vertexShader:`+ `}class Yl extends yn{constructor(e=1,t={}){super(e,e,t);this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new na(i),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;@@ -4075,7 +4075,7 @@ void main() {gl_FragColor = texture2D( tEquirect, sampleUV );}- `},Q=new $0(5,5,5),W=new gU({name:"CubemapFromEquirect",uniforms:v0(J.uniforms),vertexShader:J.vertexShader,fragmentShader:J.fragmentShader,side:$U,blending:JJ});W.uniforms.tEquirect.value=U;let K=new B6(Q,W),X=U.minFilter;if(U.minFilter===WJ)U.minFilter=n6;return new DH(1,10,this).update($,K),U.minFilter=X,K.geometry.dispose(),K.material.dispose(),this}clear($,U=!0,J=!0,Q=!0){let W=$.getRenderTarget();for(let K=0;K<6;K++)$.setRenderTarget(this,K),$.clear(U,J,Q);$.setRenderTarget(W)}}function eR($){let U=new WeakMap,J=new WeakMap,Q=null;function W(E,k=!1){if(E===null||E===void 0)return null;if(k)return X(E);return K(E)}function K(E){if(E&&E.isTexture){let k=E.mapping;if(k===Y9||k===G9)if(U.has(E)){let I=U.get(E).texture;return H(I,E.mapping)}else{let I=E.image;if(I&&I.height>0){let R=new jH(I.height);return R.fromEquirectangularTexture($,E),U.set(E,R),E.addEventListener("dispose",Y),H(R.texture,E.mapping)}else return null}}return E}function X(E){if(E&&E.isTexture){let k=E.mapping,I=k===Y9||k===G9,R=k===Z8||k===z0;if(I||R){let q=J.get(E),Z=q!==void 0?q.texture.pmremVersion:0;if(E.isRenderTargetTexture&&E.pmremVersion!==Z){if(Q===null)Q=new dW($);return q=I?Q.fromEquirectangular(E,q):Q.fromCubemap(E,q),q.texture.pmremVersion=E.pmremVersion,J.set(E,q),q.texture}else if(q!==void 0)return q.texture;else{let _=E.image;if(I&&_&&_.height>0||R&&_&&N(_)){if(Q===null)Q=new dW($);return q=I?Q.fromEquirectangular(E):Q.fromCubemap(E),q.texture.pmremVersion=E.pmremVersion,J.set(E,q),E.addEventListener("dispose",G),q.texture}else return null}}}return E}function H(E,k){if(k===Y9)E.mapping=Z8;else if(k===G9)E.mapping=z0;return E}function N(E){let k=0,I=6;for(let R=0;R<I;R++)if(E[R]!==void 0)k++;return k===I}function Y(E){let k=E.target;k.removeEventListener("dispose",Y);let I=U.get(k);if(I!==void 0)U.delete(k),I.dispose()}function G(E){let k=E.target;k.removeEventListener("dispose",G);let I=J.get(k);if(I!==void 0)J.delete(k),I.dispose()}function O(){if(U=new WeakMap,J=new WeakMap,Q!==null)Q.dispose(),Q=null}return{get:W,dispose:O}}function $V($){let U={};function J(Q){if(U[Q]!==void 0)return U[Q];let W=$.getExtension(Q);return U[Q]=W,W}return{has:function(Q){return J(Q)!==null},init:function(){J("EXT_color_buffer_float"),J("WEBGL_clip_cull_distance"),J("OES_texture_float_linear"),J("EXT_color_buffer_half_float"),J("WEBGL_multisampled_render_to_texture"),J("WEBGL_render_shared_exponent")},get:function(Q){let W=J(Q);if(W===null)M0("WebGLRenderer: "+Q+" extension not supported.");return W}}}function UV($,U,J,Q){let W={},K=new WeakMap;function X(O){let E=O.target;if(E.index!==null)U.remove(E.index);for(let I in E.attributes)U.remove(E.attributes[I]);E.removeEventListener("dispose",X),delete W[E.id];let k=K.get(E);if(k)U.remove(k),K.delete(E);if(Q.releaseStatesOfGeometry(E),E.isInstancedBufferGeometry===!0)delete E._maxInstanceCount;J.memory.geometries--}function H(O,E){if(W[E.id]===!0)return E;return E.addEventListener("dispose",X),W[E.id]=!0,J.memory.geometries++,E}function N(O){let E=O.attributes;for(let k in E)U.update(E[k],$.ARRAY_BUFFER)}function Y(O){let E=[],k=O.index,I=O.attributes.position,R=0;if(I===void 0)return;if(k!==null){let _=k.array;R=k.version;for(let P=0,L=_.length;P<L;P+=3){let B=_[P+0],z=_[P+1],A=_[P+2];E.push(B,z,z,A,A,B)}}else{let _=I.array;R=I.version;for(let P=0,L=_.length/3-1;P<L;P+=3){let B=P+0,z=P+1,A=P+2;E.push(B,z,z,A,A,B)}}let q=new(I.count>=65535?P9:B9)(E,1);q.version=R;let Z=K.get(O);if(Z)U.remove(Z);K.set(O,q)}function G(O){let E=K.get(O);if(E){let k=O.index;if(k!==null){if(E.version<k.version)Y(O)}}else Y(O);return K.get(O)}return{get:H,update:N,getWireframeAttribute:G}}function JV($,U,J){let Q;function W(O){Q=O}let K,X;function H(O){K=O.type,X=O.bytesPerElement}function N(O,E){$.drawElements(Q,E,K,O*X),J.update(E,Q,1)}function Y(O,E,k){if(k===0)return;$.drawElementsInstanced(Q,E,K,O*X,k),J.update(E,Q,k)}function G(O,E,k){if(k===0)return;U.get("WEBGL_multi_draw").multiDrawElementsWEBGL(Q,E,0,K,O,0,k);let R=0;for(let q=0;q<k;q++)R+=E[q];J.update(R,Q,1)}this.setMode=W,this.setIndex=H,this.render=N,this.renderInstances=Y,this.renderMultiDraw=G}function WV($){let U={geometries:0,textures:0},J={frame:0,calls:0,triangles:0,points:0,lines:0};function Q(K,X,H){switch(J.calls++,X){case $.TRIANGLES:J.triangles+=H*(K/3);break;case $.LINES:J.lines+=H*(K/2);break;case $.LINE_STRIP:J.lines+=H*(K-1);break;case $.LINE_LOOP:J.lines+=H*K;break;case $.POINTS:J.points+=H*K;break;default:x$("WebGLInfo: Unknown draw mode:",X);break}}function W(){J.calls=0,J.triangles=0,J.points=0,J.lines=0}return{memory:U,render:J,programs:null,autoReset:!0,reset:W,update:Q}}function QV($,U,J){let Q=new WeakMap,W=new E6;function K(X,H,N){let Y=X.morphTargetInfluences,G=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,O=G!==void 0?G.length:0,E=Q.get(H);if(E===void 0||E.count!==O){let w=function(){A.dispose(),Q.delete(H),H.removeEventListener("dispose",w)};if(E!==void 0)E.texture.dispose();let k=H.morphAttributes.position!==void 0,I=H.morphAttributes.normal!==void 0,R=H.morphAttributes.color!==void 0,q=H.morphAttributes.position||[],Z=H.morphAttributes.normal||[],_=H.morphAttributes.color||[],P=0;if(k===!0)P=1;if(I===!0)P=2;if(R===!0)P=3;let L=H.attributes.position.count*P,B=1;if(L>U.maxTextureSize)B=Math.ceil(L/U.maxTextureSize),L=U.maxTextureSize;let z=new Float32Array(L*B*4*O),A=new w9(z,L,B,O);A.type=AJ,A.needsUpdate=!0;let D=P*4;for(let h=0;h<O;h++){let C=q[h],f=Z[h],s=_[h],x=L*B*4*h;for(let d=0;d<C.count;d++){let c=d*D;if(k===!0)W.fromBufferAttribute(C,d),z[x+c+0]=W.x,z[x+c+1]=W.y,z[x+c+2]=W.z,z[x+c+3]=0;if(I===!0)W.fromBufferAttribute(f,d),z[x+c+4]=W.x,z[x+c+5]=W.y,z[x+c+6]=W.z,z[x+c+7]=0;if(R===!0)W.fromBufferAttribute(s,d),z[x+c+8]=W.x,z[x+c+9]=W.y,z[x+c+10]=W.z,z[x+c+11]=s.itemSize===4?W.w:1}}E={count:O,texture:A,size:new g$(L,B)},Q.set(H,E),H.addEventListener("dispose",w)}if(X.isInstancedMesh===!0&&X.morphTexture!==null)N.getUniforms().setValue($,"morphTexture",X.morphTexture,J);else{let k=0;for(let R=0;R<Y.length;R++)k+=Y[R];let I=H.morphTargetsRelative?1:1-k;N.getUniforms().setValue($,"morphTargetBaseInfluence",I),N.getUniforms().setValue($,"morphTargetInfluences",Y)}N.getUniforms().setValue($,"morphTargetsTexture",E.texture,J),N.getUniforms().setValue($,"morphTargetsTextureSize",E.size)}return{update:K}}function KV($,U,J,Q,W){let K=new WeakMap;function X(Y){let G=W.render.frame,O=Y.geometry,E=U.get(Y,O);if(K.get(E)!==G)U.update(E),K.set(E,G);if(Y.isInstancedMesh){if(Y.hasEventListener("dispose",N)===!1)Y.addEventListener("dispose",N);if(K.get(Y)!==G){if(J.update(Y.instanceMatrix,$.ARRAY_BUFFER),Y.instanceColor!==null)J.update(Y.instanceColor,$.ARRAY_BUFFER);K.set(Y,G)}}if(Y.isSkinnedMesh){let k=Y.skeleton;if(K.get(k)!==G)k.update(),K.set(k,G)}return E}function H(){K=new WeakMap}function N(Y){let G=Y.target;if(G.removeEventListener("dispose",N),Q.releaseStatesOfObject(G),J.remove(G.instanceMatrix),G.instanceColor!==null)J.remove(G.instanceColor)}return{update:X,dispose:H}}var XV={[YX]:"LINEAR_TONE_MAPPING",[GX]:"REINHARD_TONE_MAPPING",[OX]:"CINEON_TONE_MAPPING",[wW]:"ACES_FILMIC_TONE_MAPPING",[kX]:"AGX_TONE_MAPPING",[qX]:"NEUTRAL_TONE_MAPPING",[EX]:"CUSTOM_TONE_MAPPING"};function HV($,U,J,Q,W,K){let X=new jU(U,J,{type:$,depthBuffer:W,stencilBuffer:K,samples:Q?4:0,depthTexture:W?new eJ(U,J):void 0}),H=new jU(U,J,{type:CJ,depthBuffer:!1,stencilBuffer:!1}),N=new KU;N.setAttribute("position",new OU([-1,3,0,-1,-1,0,3,-1,0],3)),N.setAttribute("uv",new OU([0,2,0,0,2,0],2));let Y=new YH({uniforms:{tDiffuse:{value:null}},vertexShader:`+ `},i=new Di(5,5,5),r=new bn({name:"CubemapFromEquirect",uniforms:cr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Xt,blending:Vn});r.uniforms.tEquirect.value=t;let s=new dt(i,r),o=t.minFilter;if(t.minFilter===Wn)t.minFilter=kt;return new Nl(1,10,this).update(e,s),t.minFilter=o,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){let r=e.getRenderTarget();for(let s=0;s<6;s++)e.setRenderTarget(this,s),e.clear(t,n,i);e.setRenderTarget(r)}}function Lb(e){let t=new WeakMap,n=new WeakMap,i=null;function r(h,d=!1){if(h===null||h===void 0)return null;if(d)return o(h);return s(h)}function s(h){if(h&&h.isTexture){let d=h.mapping;if(d===Oo||d===Fo)if(t.has(h)){let g=t.get(h).texture;return a(g,h.mapping)}else{let g=h.image;if(g&&g.height>0){let b=new Yl(g.height);return b.fromEquirectangularTexture(e,h),t.set(h,b),h.addEventListener("dispose",l),a(b.texture,h.mapping)}else return null}}return h}function o(h){if(h&&h.isTexture){let d=h.mapping,g=d===Oo||d===Fo,b=d===Gr||d===nr;if(g||b){let p=n.get(h),m=p!==void 0?p.texture.pmremVersion:0;if(h.isRenderTargetTexture&&h.pmremVersion!==m){if(i===null)i=new Gs(e);return p=g?i.fromEquirectangular(h,p):i.fromCubemap(h,p),p.texture.pmremVersion=h.pmremVersion,n.set(h,p),p.texture}else if(p!==void 0)return p.texture;else{let A=h.image;if(g&&A&&A.height>0||b&&A&&c(A)){if(i===null)i=new Gs(e);return p=g?i.fromEquirectangular(h):i.fromCubemap(h),p.texture.pmremVersion=h.pmremVersion,n.set(h,p),h.addEventListener("dispose",u),p.texture}else return null}}}return h}function a(h,d){if(d===Oo)h.mapping=Gr;else if(d===Fo)h.mapping=nr;return h}function c(h){let d=0,g=6;for(let b=0;b<g;b++)if(h[b]!==void 0)d++;return d===g}function l(h){let d=h.target;d.removeEventListener("dispose",l);let g=t.get(d);if(g!==void 0)t.delete(d),g.dispose()}function u(h){let d=h.target;d.removeEventListener("dispose",u);let g=n.get(d);if(g!==void 0)n.delete(d),g.dispose()}function f(){if(t=new WeakMap,n=new WeakMap,i!==null)i.dispose(),i=null}return{get:r,dispose:f}}function Nb(e){let t={};function n(i){if(t[i]!==void 0)return t[i];let r=e.getExtension(i);return t[i]=r,r}return{has:function(i){return n(i)!==null},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(i){let r=n(i);if(r===null)Qi("WebGLRenderer: "+i+" extension not supported.");return r}}}function Db(e,t,n,i){let r={},s=new WeakMap;function o(f){let h=f.target;if(h.index!==null)t.remove(h.index);for(let g in h.attributes)t.remove(h.attributes[g]);h.removeEventListener("dispose",o),delete r[h.id];let d=s.get(h);if(d)t.remove(d),s.delete(h);if(i.releaseStatesOfGeometry(h),h.isInstancedBufferGeometry===!0)delete h._maxInstanceCount;n.memory.geometries--}function a(f,h){if(r[h.id]===!0)return h;return h.addEventListener("dispose",o),r[h.id]=!0,n.memory.geometries++,h}function c(f){let h=f.attributes;for(let d in h)t.update(h[d],e.ARRAY_BUFFER)}function l(f){let h=[],d=f.index,g=f.attributes.position,b=0;if(g===void 0)return;if(d!==null){let A=d.array;b=d.version;for(let T=0,v=A.length;T<v;T+=3){let w=A[T+0],E=A[T+1],R=A[T+2];h.push(w,E,E,R,R,w)}}else{let A=g.array;b=g.version;for(let T=0,v=A.length/3-1;T<v;T+=3){let w=T+0,E=T+1,R=T+2;h.push(w,E,E,R,R,w)}}let p=new(g.count>=65535?Ko:Jo)(h,1);p.version=b;let m=s.get(f);if(m)t.remove(m);s.set(f,p)}function u(f){let h=s.get(f);if(h){let d=f.index;if(d!==null){if(h.version<d.version)l(f)}}else l(f);return s.get(f)}return{get:a,update:c,getWireframeAttribute:u}}function Ub(e,t,n){let i;function r(f){i=f}let s,o;function a(f){s=f.type,o=f.bytesPerElement}function c(f,h){e.drawElements(i,h,s,f*o),n.update(h,i,1)}function l(f,h,d){if(d===0)return;e.drawElementsInstanced(i,h,s,f*o,d),n.update(h,i,d)}function u(f,h,d){if(d===0)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,h,0,s,f,0,d);let b=0;for(let p=0;p<d;p++)b+=h[p];n.update(b,i,1)}this.setMode=r,this.setIndex=a,this.render=c,this.renderInstances=l,this.renderMultiDraw=u}function Ob(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function i(s,o,a){switch(n.calls++,o){case e.TRIANGLES:n.triangles+=a*(s/3);break;case e.LINES:n.lines+=a*(s/2);break;case e.LINE_STRIP:n.lines+=a*(s-1);break;case e.LINE_LOOP:n.lines+=a*s;break;case e.POINTS:n.points+=a*s;break;default:Ne("WebGLInfo: Unknown draw mode:",o);break}}function r(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:t,render:n,programs:null,autoReset:!0,reset:r,update:i}}function Fb(e,t,n){let i=new WeakMap,r=new it;function s(o,a,c){let l=o.morphTargetInfluences,u=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,f=u!==void 0?u.length:0,h=i.get(a);if(h===void 0||h.count!==f){let S=function(){R.dispose(),i.delete(a),a.removeEventListener("dispose",S)};if(h!==void 0)h.texture.dispose();let d=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,b=a.morphAttributes.color!==void 0,p=a.morphAttributes.position||[],m=a.morphAttributes.normal||[],A=a.morphAttributes.color||[],T=0;if(d===!0)T=1;if(g===!0)T=2;if(b===!0)T=3;let v=a.attributes.position.count*T,w=1;if(v>t.maxTextureSize)w=Math.ceil(v/t.maxTextureSize),v=t.maxTextureSize;let E=new Float32Array(v*w*4*f),R=new Yo(E,v,w,f);R.type=ui,R.needsUpdate=!0;let _=T*4;for(let F=0;F<f;F++){let C=p[F],z=m[F],J=A[F],O=v*w*4*F;for(let H=0;H<C.count;H++){let V=H*_;if(d===!0)r.fromBufferAttribute(C,H),E[O+V+0]=r.x,E[O+V+1]=r.y,E[O+V+2]=r.z,E[O+V+3]=0;if(g===!0)r.fromBufferAttribute(z,H),E[O+V+4]=r.x,E[O+V+5]=r.y,E[O+V+6]=r.z,E[O+V+7]=0;if(b===!0)r.fromBufferAttribute(J,H),E[O+V+8]=r.x,E[O+V+9]=r.y,E[O+V+10]=r.z,E[O+V+11]=J.itemSize===4?r.w:1}}h={count:f,texture:R,size:new Pe(v,w)},i.set(a,h),a.addEventListener("dispose",S)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(e,"morphTexture",o.morphTexture,n);else{let d=0;for(let b=0;b<l.length;b++)d+=l[b];let g=a.morphTargetsRelative?1:1-d;c.getUniforms().setValue(e,"morphTargetBaseInfluence",g),c.getUniforms().setValue(e,"morphTargetInfluences",l)}c.getUniforms().setValue(e,"morphTargetsTexture",h.texture,n),c.getUniforms().setValue(e,"morphTargetsTextureSize",h.size)}return{update:s}}function zb(e,t,n,i,r){let s=new WeakMap;function o(l){let u=r.render.frame,f=l.geometry,h=t.get(l,f);if(s.get(h)!==u)t.update(h),s.set(h,u);if(l.isInstancedMesh){if(l.hasEventListener("dispose",c)===!1)l.addEventListener("dispose",c);if(s.get(l)!==u){if(n.update(l.instanceMatrix,e.ARRAY_BUFFER),l.instanceColor!==null)n.update(l.instanceColor,e.ARRAY_BUFFER);s.set(l,u)}}if(l.isSkinnedMesh){let d=l.skeleton;if(s.get(d)!==u)d.update(),s.set(d,u)}return h}function a(){s=new WeakMap}function c(l){let u=l.target;if(u.removeEventListener("dispose",c),i.releaseStatesOfObject(u),n.remove(u.instanceMatrix),u.instanceColor!==null)n.remove(u.instanceColor)}return{update:o,dispose:a}}var kb={[Tc]:"LINEAR_TONE_MAPPING",[Ec]:"REINHARD_TONE_MAPPING",[Ac]:"CINEON_TONE_MAPPING",[vs]:"ACES_FILMIC_TONE_MAPPING",[Cc]:"AGX_TONE_MAPPING",[Pc]:"NEUTRAL_TONE_MAPPING",[Rc]:"CUSTOM_TONE_MAPPING"};function Bb(e,t,n,i,r,s){let o=new yn(t,n,{type:e,depthBuffer:r,stencilBuffer:s,samples:i?4:0,depthTexture:r?new Ni(t,n):void 0}),a=new yn(t,n,{type:hi,depthBuffer:!1,stencilBuffer:!1}),c=new Kt;c.setAttribute("position",new tn([-1,3,0,-1,-1,0,3,-1,0],3)),c.setAttribute("uv",new tn([0,2,0,0,2,0],2));let l=new Tl({uniforms:{tDiffuse:{value:null}},vertexShader:`precision highp float;uniform mat4 modelViewMatrix;@@ -4121,60 +4121,60 @@ void main() {#ifdef SRGB_TRANSFERgl_FragColor = sRGBTransferOETF( gl_FragColor );#endif- }`,depthTest:!1,depthWrite:!1}),G=new B6(N,Y),O=new g0(-1,1,1,-1,0,1),E=null,k=null,I=!1,R,q=null,Z=[],_=!1;this.setSize=function(P,L){X.setSize(P,L),H.setSize(P,L);for(let B=0;B<Z.length;B++){let z=Z[B];if(z.setSize)z.setSize(P,L)}},this.setEffects=function(P){Z=P,_=Z.length>0&&Z[0].isRenderPass===!0;let{width:L,height:B}=X;for(let z=0;z<Z.length;z++){let A=Z[z];if(A.setSize)A.setSize(L,B)}},this.begin=function(P,L){if(I)return!1;if(P.toneMapping===dU&&Z.length===0)return!1;if(q=L,L!==null){let{width:B,height:z}=L;if(X.width!==B||X.height!==z)this.setSize(B,z)}if(_===!1)P.setRenderTarget(X);return R=P.toneMapping,P.toneMapping=dU,!0},this.hasRenderPass=function(){return _},this.end=function(P,L){P.toneMapping=R,I=!0;let B=X,z=H;for(let A=0;A<Z.length;A++){let D=Z[A];if(D.enabled===!1)continue;if(D.render(P,z,B,L),D.needsSwap!==!1){let w=B;B=z,z=w}}if(E!==P.outputColorSpace||k!==P.toneMapping){if(E=P.outputColorSpace,k=P.toneMapping,Y.defines={},r$.getTransfer(E)===R6)Y.defines.SRGB_TRANSFER="";let A=XV[k];if(A)Y.defines[A]="";Y.needsUpdate=!0}Y.uniforms.tDiffuse.value=B.texture,P.setRenderTarget(q),P.render(G,O),q=null,I=!1},this.isCompositing=function(){return I},this.dispose=function(){if(X.depthTexture)X.depthTexture.dispose();X.dispose(),H.dispose(),N.dispose(),Y.dispose()}}var _Z=new C6,TH=new eJ(1,1),AZ=new w9,CZ=new XH,SZ=new C9,NZ=[],YZ=[],GZ=new Float32Array(16),OZ=new Float32Array(9),EZ=new Float32Array(4);function C8($,U,J){let Q=$[0];if(Q<=0||Q>0)return $;let W=U*J,K=NZ[W];if(K===void 0)K=new Float32Array(W),NZ[W]=K;if(U!==0){Q.toArray(K,0);for(let X=1,H=0;X!==U;++X)H+=J,$[X].toArray(K,H)}return K}function f6($,U){if($.length!==U.length)return!1;for(let J=0,Q=$.length;J<Q;J++)if($[J]!==U[J])return!1;return!0}function u6($,U){for(let J=0,Q=U.length;J<Q;J++)$[J]=U[J]}function c9($,U){let J=YZ[U];if(J===void 0)J=new Int32Array(U),YZ[U]=J;for(let Q=0;Q!==U;++Q)J[Q]=$.allocateTextureUnit();return J}function NV($,U){let J=this.cache;if(J[0]===U)return;$.uniform1f(this.addr,U),J[0]=U}function YV($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y)$.uniform2f(this.addr,U.x,U.y),J[0]=U.x,J[1]=U.y}else{if(f6(J,U))return;$.uniform2fv(this.addr,U),u6(J,U)}}function GV($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z)$.uniform3f(this.addr,U.x,U.y,U.z),J[0]=U.x,J[1]=U.y,J[2]=U.z}else if(U.r!==void 0){if(J[0]!==U.r||J[1]!==U.g||J[2]!==U.b)$.uniform3f(this.addr,U.r,U.g,U.b),J[0]=U.r,J[1]=U.g,J[2]=U.b}else{if(f6(J,U))return;$.uniform3fv(this.addr,U),u6(J,U)}}function OV($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z||J[3]!==U.w)$.uniform4f(this.addr,U.x,U.y,U.z,U.w),J[0]=U.x,J[1]=U.y,J[2]=U.z,J[3]=U.w}else{if(f6(J,U))return;$.uniform4fv(this.addr,U),u6(J,U)}}function EV($,U){let J=this.cache,Q=U.elements;if(Q===void 0){if(f6(J,U))return;$.uniformMatrix2fv(this.addr,!1,U),u6(J,U)}else{if(f6(J,Q))return;EZ.set(Q),$.uniformMatrix2fv(this.addr,!1,EZ),u6(J,Q)}}function kV($,U){let J=this.cache,Q=U.elements;if(Q===void 0){if(f6(J,U))return;$.uniformMatrix3fv(this.addr,!1,U),u6(J,U)}else{if(f6(J,Q))return;OZ.set(Q),$.uniformMatrix3fv(this.addr,!1,OZ),u6(J,Q)}}function qV($,U){let J=this.cache,Q=U.elements;if(Q===void 0){if(f6(J,U))return;$.uniformMatrix4fv(this.addr,!1,U),u6(J,U)}else{if(f6(J,Q))return;GZ.set(Q),$.uniformMatrix4fv(this.addr,!1,GZ),u6(J,Q)}}function ZV($,U){let J=this.cache;if(J[0]===U)return;$.uniform1i(this.addr,U),J[0]=U}function IV($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y)$.uniform2i(this.addr,U.x,U.y),J[0]=U.x,J[1]=U.y}else{if(f6(J,U))return;$.uniform2iv(this.addr,U),u6(J,U)}}function DV($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z)$.uniform3i(this.addr,U.x,U.y,U.z),J[0]=U.x,J[1]=U.y,J[2]=U.z}else{if(f6(J,U))return;$.uniform3iv(this.addr,U),u6(J,U)}}function FV($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z||J[3]!==U.w)$.uniform4i(this.addr,U.x,U.y,U.z,U.w),J[0]=U.x,J[1]=U.y,J[2]=U.z,J[3]=U.w}else{if(f6(J,U))return;$.uniform4iv(this.addr,U),u6(J,U)}}function LV($,U){let J=this.cache;if(J[0]===U)return;$.uniform1ui(this.addr,U),J[0]=U}function RV($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y)$.uniform2ui(this.addr,U.x,U.y),J[0]=U.x,J[1]=U.y}else{if(f6(J,U))return;$.uniform2uiv(this.addr,U),u6(J,U)}}function VV($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z)$.uniform3ui(this.addr,U.x,U.y,U.z),J[0]=U.x,J[1]=U.y,J[2]=U.z}else{if(f6(J,U))return;$.uniform3uiv(this.addr,U),u6(J,U)}}function wV($,U){let J=this.cache;if(U.x!==void 0){if(J[0]!==U.x||J[1]!==U.y||J[2]!==U.z||J[3]!==U.w)$.uniform4ui(this.addr,U.x,U.y,U.z,U.w),J[0]=U.x,J[1]=U.y,J[2]=U.z,J[3]=U.w}else{if(f6(J,U))return;$.uniform4uiv(this.addr,U),u6(J,U)}}function MV($,U,J){let Q=this.cache,W=J.allocateTextureUnit();if(Q[0]!==W)$.uniform1i(this.addr,W),Q[0]=W;let K;if(this.type===$.SAMPLER_2D_SHADOW)TH.compareFunction=J.isReversedDepthBuffer()?V9:R9,K=TH;else K=_Z;J.setTexture2D(U||K,W)}function BV($,U,J){let Q=this.cache,W=J.allocateTextureUnit();if(Q[0]!==W)$.uniform1i(this.addr,W),Q[0]=W;J.setTexture3D(U||CZ,W)}function PV($,U,J){let Q=this.cache,W=J.allocateTextureUnit();if(Q[0]!==W)$.uniform1i(this.addr,W),Q[0]=W;J.setTextureCube(U||SZ,W)}function zV($,U,J){let Q=this.cache,W=J.allocateTextureUnit();if(Q[0]!==W)$.uniform1i(this.addr,W),Q[0]=W;J.setTexture2DArray(U||AZ,W)}function _V($){switch($){case 5126:return NV;case 35664:return YV;case 35665:return GV;case 35666:return OV;case 35674:return EV;case 35675:return kV;case 35676:return qV;case 5124:case 35670:return ZV;case 35667:case 35671:return IV;case 35668:case 35672:return DV;case 35669:case 35673:return FV;case 5125:return LV;case 36294:return RV;case 36295:return VV;case 36296:return wV;case 35678:case 36198:case 36298:case 36306:case 35682:return MV;case 35679:case 36299:case 36307:return BV;case 35680:case 36300:case 36308:case 36293:return PV;case 36289:case 36303:case 36311:case 36292:return zV}}function AV($,U){$.uniform1fv(this.addr,U)}function CV($,U){let J=C8(U,this.size,2);$.uniform2fv(this.addr,J)}function SV($,U){let J=C8(U,this.size,3);$.uniform3fv(this.addr,J)}function TV($,U){let J=C8(U,this.size,4);$.uniform4fv(this.addr,J)}function vV($,U){let J=C8(U,this.size,4);$.uniformMatrix2fv(this.addr,!1,J)}function jV($,U){let J=C8(U,this.size,9);$.uniformMatrix3fv(this.addr,!1,J)}function gV($,U){let J=C8(U,this.size,16);$.uniformMatrix4fv(this.addr,!1,J)}function bV($,U){$.uniform1iv(this.addr,U)}function yV($,U){$.uniform2iv(this.addr,U)}function xV($,U){$.uniform3iv(this.addr,U)}function hV($,U){$.uniform4iv(this.addr,U)}function fV($,U){$.uniform1uiv(this.addr,U)}function uV($,U){$.uniform2uiv(this.addr,U)}function lV($,U){$.uniform3uiv(this.addr,U)}function mV($,U){$.uniform4uiv(this.addr,U)}function pV($,U,J){let Q=this.cache,W=U.length,K=c9(J,W);if(!f6(Q,K))$.uniform1iv(this.addr,K),u6(Q,K);let X;if(this.type===$.SAMPLER_2D_SHADOW)X=TH;else X=_Z;for(let H=0;H!==W;++H)J.setTexture2D(U[H]||X,K[H])}function dV($,U,J){let Q=this.cache,W=U.length,K=c9(J,W);if(!f6(Q,K))$.uniform1iv(this.addr,K),u6(Q,K);for(let X=0;X!==W;++X)J.setTexture3D(U[X]||CZ,K[X])}function cV($,U,J){let Q=this.cache,W=U.length,K=c9(J,W);if(!f6(Q,K))$.uniform1iv(this.addr,K),u6(Q,K);for(let X=0;X!==W;++X)J.setTextureCube(U[X]||SZ,K[X])}function nV($,U,J){let Q=this.cache,W=U.length,K=c9(J,W);if(!f6(Q,K))$.uniform1iv(this.addr,K),u6(Q,K);for(let X=0;X!==W;++X)J.setTexture2DArray(U[X]||AZ,K[X])}function iV($){switch($){case 5126:return AV;case 35664:return CV;case 35665:return SV;case 35666:return TV;case 35674:return vV;case 35675:return jV;case 35676:return gV;case 5124:case 35670:return bV;case 35667:case 35671:return yV;case 35668:case 35672:return xV;case 35669:case 35673:return hV;case 5125:return fV;case 36294:return uV;case 36295:return lV;case 36296:return mV;case 35678:case 36198:case 36298:case 36306:case 35682:return pV;case 35679:case 36299:case 36307:return dV;case 35680:case 36300:case 36308:case 36293:return cV;case 36289:case 36303:case 36311:case 36292:return nV}}class TZ{constructor($,U,J){this.id=$,this.addr=J,this.cache=[],this.type=U.type,this.setValue=_V(U.type)}}class vZ{constructor($,U,J){this.id=$,this.addr=J,this.cache=[],this.type=U.type,this.size=U.size,this.setValue=iV(U.type)}}class jZ{constructor($){this.id=$,this.seq=[],this.map={}}setValue($,U,J){let Q=this.seq;for(let W=0,K=Q.length;W!==K;++W){let X=Q[W];X.setValue($,U[X.id],J)}}}var CH=/(\w+)(\])?(\[|\.)?/g;function kZ($,U){$.seq.push(U),$.map[U.id]=U}function oV($,U,J){let Q=$.name,W=Q.length;CH.lastIndex=0;while(!0){let K=CH.exec(Q),X=CH.lastIndex,H=K[1],N=K[2]==="]",Y=K[3];if(N)H=H|0;if(Y===void 0||Y==="["&&X+2===W){kZ(J,Y===void 0?new TZ(H,$,U):new vZ(H,$,U));break}else{let O=J.map[H];if(O===void 0)O=new jZ(H),kZ(J,O);J=O}}}class pW{constructor($,U){this.seq=[],this.map={};let J=$.getProgramParameter(U,$.ACTIVE_UNIFORMS);for(let K=0;K<J;++K){let X=$.getActiveUniform(U,K),H=$.getUniformLocation(U,X.name);oV(X,H,this)}let Q=[],W=[];for(let K of this.seq)if(K.type===$.SAMPLER_2D_SHADOW||K.type===$.SAMPLER_CUBE_SHADOW||K.type===$.SAMPLER_2D_ARRAY_SHADOW)Q.push(K);else W.push(K);if(Q.length>0)this.seq=Q.concat(W)}setValue($,U,J,Q){let W=this.map[U];if(W!==void 0)W.setValue($,J,Q)}setOptional($,U,J){let Q=U[J];if(Q!==void 0)this.setValue($,J,Q)}static upload($,U,J,Q){for(let W=0,K=U.length;W!==K;++W){let X=U[W],H=J[X.id];if(H.needsUpdate!==!1)X.setValue($,H.value,Q)}}static seqWithValue($,U){let J=[];for(let Q=0,W=$.length;Q!==W;++Q){let K=$[Q];if(K.id in U)J.push(K)}return J}}function qZ($,U,J){let Q=$.createShader(U);return $.shaderSource(Q,J),$.compileShader(Q),Q}var rV=37297,aV=0;function sV($,U){let J=$.split(`-`),Q=[],W=Math.max(U-6,0),K=Math.min(U+6,J.length);for(let X=W;X<K;X++){let H=X+1;Q.push(`${H===U?">":" "} ${H}: ${J[X]}`)}return Q.join(`-`)}var ZZ=new f$;function tV($){r$._getMatrix(ZZ,r$.workingColorSpace,$);let U=`mat3( ${ZZ.elements.map((J)=>J.toFixed(4))} )`;switch(r$.getTransfer($)){case $H:return[U,"LinearTransferOETF"];case R6:return[U,"sRGBTransferOETF"];default:return A$("WebGLProgram: Unsupported color space: ",$),[U,"LinearTransferOETF"]}}function IZ($,U,J){let Q=$.getShaderParameter(U,$.COMPILE_STATUS),K=($.getShaderInfoLog(U)||"").trim();if(Q&&K==="")return"";let X=/ERROR: 0:(\d+)/.exec(K);if(X){let H=parseInt(X[1]);return J.toUpperCase()+`--`+K+`--`+sV($.getShaderSource(U),H)}else return K}function eV($,U){let J=tV(U);return[`vec4 ${$}( vec4 value ) {`,` return ${J[1]}( vec4( value.rgb * ${J[0]}, value.a ) );`,"}"].join(`-`)}var $w={[YX]:"Linear",[GX]:"Reinhard",[OX]:"Cineon",[wW]:"ACESFilmic",[kX]:"AgX",[qX]:"Neutral",[EX]:"Custom"};function Uw($,U){let J=$w[U];if(J===void 0)return A$("WebGLProgram: Unsupported toneMapping:",U),"vec3 "+$+"( vec3 color ) { return LinearToneMapping( color ); }";return"vec3 "+$+"( vec3 color ) { return "+J+"ToneMapping( color ); }"}var p9=new j;function Jw(){r$.getLuminanceCoefficients(p9);let $=p9.x.toFixed(4),U=p9.y.toFixed(4),J=p9.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${$}, ${U}, ${J} );`,"\treturn dot( weights, rgb );","}"].join(`-`)}function Ww($){return[$.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",$.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(mW).join(`-`)}function Qw($){let U=[];for(let J in $){let Q=$[J];if(Q===!1)continue;U.push("#define "+J+" "+Q)}return U.join(`-`)}function Kw($,U){let J={},Q=$.getProgramParameter(U,$.ACTIVE_ATTRIBUTES);for(let W=0;W<Q;W++){let K=$.getActiveAttrib(U,W),X=K.name,H=1;if(K.type===$.FLOAT_MAT2)H=2;if(K.type===$.FLOAT_MAT3)H=3;if(K.type===$.FLOAT_MAT4)H=4;J[X]={type:K.type,location:$.getAttribLocation(U,X),locationSize:H}}return J}function mW($){return $!==""}function DZ($,U){let J=U.numSpotLightShadows+U.numSpotLightMaps-U.numSpotLightShadowsWithMaps;return $.replace(/NUM_DIR_LIGHTS/g,U.numDirLights).replace(/NUM_SPOT_LIGHTS/g,U.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,U.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,J).replace(/NUM_RECT_AREA_LIGHTS/g,U.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,U.numPointLights).replace(/NUM_HEMI_LIGHTS/g,U.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,U.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,U.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,U.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,U.numPointLightShadows)}function FZ($,U){return $.replace(/NUM_CLIPPING_PLANES/g,U.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,U.numClippingPlanes-U.numClipIntersection)}var Xw=/^[ \t]*#include +<([\w\d./]+)>/gm;function vH($){return $.replace(Xw,Nw)}var Hw=new Map;function Nw($,U){let J=i$[U];if(J===void 0){let Q=Hw.get(U);if(Q!==void 0)J=i$[Q],A$('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',U,Q);else throw Error("THREE.WebGLProgram: Can not resolve #include <"+U+">")}return vH(J)}var Yw=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function LZ($){return $.replace(Yw,Gw)}function Gw($,U,J,Q){let W="";for(let K=parseInt(U);K<parseInt(J);K++)W+=Q.replace(/\[\s*i\s*\]/g,"[ "+K+" ]").replace(/UNROLLED_LOOP_INDEX/g,K);return W}function RZ($){let U=`precision ${$.precision} float;- precision ${$.precision} int;- precision ${$.precision} sampler2D;- precision ${$.precision} samplerCube;- precision ${$.precision} sampler3D;- precision ${$.precision} sampler2DArray;- precision ${$.precision} sampler2DShadow;- precision ${$.precision} samplerCubeShadow;- precision ${$.precision} sampler2DArrayShadow;- precision ${$.precision} isampler2D;- precision ${$.precision} isampler3D;- precision ${$.precision} isamplerCube;- precision ${$.precision} isampler2DArray;- precision ${$.precision} usampler2D;- precision ${$.precision} usampler3D;- precision ${$.precision} usamplerCube;- precision ${$.precision} usampler2DArray;- `;if($.precision==="highp")U+=`-#define HIGH_PRECISION`;else if($.precision==="mediump")U+=`-#define MEDIUM_PRECISION`;else if($.precision==="lowp")U+=`-#define LOW_PRECISION`;return U}var Ow={[RW]:"SHADOWMAP_TYPE_PCF",[k8]:"SHADOWMAP_TYPE_VSM"};function Ew($){return Ow[$.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}var kw={[Z8]:"ENVMAP_TYPE_CUBE",[z0]:"ENVMAP_TYPE_CUBE",[MW]:"ENVMAP_TYPE_CUBE_UV"};function qw($){if($.envMap===!1)return"ENVMAP_TYPE_CUBE";return kw[$.envMapMode]||"ENVMAP_TYPE_CUBE"}var Zw={[z0]:"ENVMAP_MODE_REFRACTION"};function Iw($){if($.envMap===!1)return"ENVMAP_MODE_REFLECTION";return Zw[$.envMapMode]||"ENVMAP_MODE_REFLECTION"}var Dw={[Aq]:"ENVMAP_BLENDING_MULTIPLY",[Cq]:"ENVMAP_BLENDING_MIX",[Sq]:"ENVMAP_BLENDING_ADD"};function Fw($){if($.envMap===!1)return"ENVMAP_BLENDING_NONE";return Dw[$.combine]||"ENVMAP_BLENDING_NONE"}function Lw($){let U=$.envMapCubeUVHeight;if(U===null)return null;let J=Math.log2(U)-2,Q=1/U;return{texelWidth:1/(3*Math.max(Math.pow(2,J),112)),texelHeight:Q,maxMip:J}}function Rw($,U,J,Q){let W=$.getContext(),K=J.defines,X=J.vertexShader,H=J.fragmentShader,N=Ew(J),Y=qw(J),G=Iw(J),O=Fw(J),E=Lw(J),k=Ww(J),I=Qw(K),R=W.createProgram(),q,Z,_=J.glslVersion?"#version "+J.glslVersion+`-`:"";if(J.isRawShaderMaterial){if(q=["#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,I].filter(mW).join(`-`),q.length>0)q+=`-`;if(Z=["#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,I].filter(mW).join(`-`),Z.length>0)Z+=`-`}else q=[RZ(J),"#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,I,J.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",J.batching?"#define USE_BATCHING":"",J.batchingColor?"#define USE_BATCHING_COLOR":"",J.instancing?"#define USE_INSTANCING":"",J.instancingColor?"#define USE_INSTANCING_COLOR":"",J.instancingMorph?"#define USE_INSTANCING_MORPH":"",J.useFog&&J.fog?"#define USE_FOG":"",J.useFog&&J.fogExp2?"#define FOG_EXP2":"",J.map?"#define USE_MAP":"",J.envMap?"#define USE_ENVMAP":"",J.envMap?"#define "+G:"",J.lightMap?"#define USE_LIGHTMAP":"",J.aoMap?"#define USE_AOMAP":"",J.bumpMap?"#define USE_BUMPMAP":"",J.normalMap?"#define USE_NORMALMAP":"",J.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",J.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",J.displacementMap?"#define USE_DISPLACEMENTMAP":"",J.emissiveMap?"#define USE_EMISSIVEMAP":"",J.anisotropy?"#define USE_ANISOTROPY":"",J.anisotropyMap?"#define USE_ANISOTROPYMAP":"",J.clearcoatMap?"#define USE_CLEARCOATMAP":"",J.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",J.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",J.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",J.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",J.specularMap?"#define USE_SPECULARMAP":"",J.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",J.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",J.roughnessMap?"#define USE_ROUGHNESSMAP":"",J.metalnessMap?"#define USE_METALNESSMAP":"",J.alphaMap?"#define USE_ALPHAMAP":"",J.alphaHash?"#define USE_ALPHAHASH":"",J.transmission?"#define USE_TRANSMISSION":"",J.transmissionMap?"#define USE_TRANSMISSIONMAP":"",J.thicknessMap?"#define USE_THICKNESSMAP":"",J.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",J.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",J.mapUv?"#define MAP_UV "+J.mapUv:"",J.alphaMapUv?"#define ALPHAMAP_UV "+J.alphaMapUv:"",J.lightMapUv?"#define LIGHTMAP_UV "+J.lightMapUv:"",J.aoMapUv?"#define AOMAP_UV "+J.aoMapUv:"",J.emissiveMapUv?"#define EMISSIVEMAP_UV "+J.emissiveMapUv:"",J.bumpMapUv?"#define BUMPMAP_UV "+J.bumpMapUv:"",J.normalMapUv?"#define NORMALMAP_UV "+J.normalMapUv:"",J.displacementMapUv?"#define DISPLACEMENTMAP_UV "+J.displacementMapUv:"",J.metalnessMapUv?"#define METALNESSMAP_UV "+J.metalnessMapUv:"",J.roughnessMapUv?"#define ROUGHNESSMAP_UV "+J.roughnessMapUv:"",J.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+J.anisotropyMapUv:"",J.clearcoatMapUv?"#define CLEARCOATMAP_UV "+J.clearcoatMapUv:"",J.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+J.clearcoatNormalMapUv:"",J.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+J.clearcoatRoughnessMapUv:"",J.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+J.iridescenceMapUv:"",J.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+J.iridescenceThicknessMapUv:"",J.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+J.sheenColorMapUv:"",J.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+J.sheenRoughnessMapUv:"",J.specularMapUv?"#define SPECULARMAP_UV "+J.specularMapUv:"",J.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+J.specularColorMapUv:"",J.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+J.specularIntensityMapUv:"",J.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+J.transmissionMapUv:"",J.thicknessMapUv?"#define THICKNESSMAP_UV "+J.thicknessMapUv:"",J.vertexTangents&&J.flatShading===!1?"#define USE_TANGENT":"",J.vertexNormals?"#define HAS_NORMAL":"",J.vertexColors?"#define USE_COLOR":"",J.vertexAlphas?"#define USE_COLOR_ALPHA":"",J.vertexUv1s?"#define USE_UV1":"",J.vertexUv2s?"#define USE_UV2":"",J.vertexUv3s?"#define USE_UV3":"",J.pointsUvs?"#define USE_POINTS_UV":"",J.flatShading?"#define FLAT_SHADED":"",J.skinning?"#define USE_SKINNING":"",J.morphTargets?"#define USE_MORPHTARGETS":"",J.morphNormals&&J.flatShading===!1?"#define USE_MORPHNORMALS":"",J.morphColors?"#define USE_MORPHCOLORS":"",J.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+J.morphTextureStride:"",J.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+J.morphTargetsCount:"",J.doubleSided?"#define DOUBLE_SIDED":"",J.flipSided?"#define FLIP_SIDED":"",J.shadowMapEnabled?"#define USE_SHADOWMAP":"",J.shadowMapEnabled?"#define "+N:"",J.sizeAttenuation?"#define USE_SIZEATTENUATION":"",J.numLightProbes>0?"#define USE_LIGHT_PROBES":"",J.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",J.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","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif",`-`].filter(mW).join(`-`),Z=[RZ(J),"#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,I,J.useFog&&J.fog?"#define USE_FOG":"",J.useFog&&J.fogExp2?"#define FOG_EXP2":"",J.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",J.map?"#define USE_MAP":"",J.matcap?"#define USE_MATCAP":"",J.envMap?"#define USE_ENVMAP":"",J.envMap?"#define "+Y:"",J.envMap?"#define "+G:"",J.envMap?"#define "+O:"",E?"#define CUBEUV_TEXEL_WIDTH "+E.texelWidth:"",E?"#define CUBEUV_TEXEL_HEIGHT "+E.texelHeight:"",E?"#define CUBEUV_MAX_MIP "+E.maxMip+".0":"",J.lightMap?"#define USE_LIGHTMAP":"",J.aoMap?"#define USE_AOMAP":"",J.bumpMap?"#define USE_BUMPMAP":"",J.normalMap?"#define USE_NORMALMAP":"",J.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",J.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",J.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",J.emissiveMap?"#define USE_EMISSIVEMAP":"",J.anisotropy?"#define USE_ANISOTROPY":"",J.anisotropyMap?"#define USE_ANISOTROPYMAP":"",J.clearcoat?"#define USE_CLEARCOAT":"",J.clearcoatMap?"#define USE_CLEARCOATMAP":"",J.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",J.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",J.dispersion?"#define USE_DISPERSION":"",J.iridescence?"#define USE_IRIDESCENCE":"",J.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",J.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",J.specularMap?"#define USE_SPECULARMAP":"",J.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",J.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",J.roughnessMap?"#define USE_ROUGHNESSMAP":"",J.metalnessMap?"#define USE_METALNESSMAP":"",J.alphaMap?"#define USE_ALPHAMAP":"",J.alphaTest?"#define USE_ALPHATEST":"",J.alphaHash?"#define USE_ALPHAHASH":"",J.sheen?"#define USE_SHEEN":"",J.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",J.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",J.transmission?"#define USE_TRANSMISSION":"",J.transmissionMap?"#define USE_TRANSMISSIONMAP":"",J.thicknessMap?"#define USE_THICKNESSMAP":"",J.vertexTangents&&J.flatShading===!1?"#define USE_TANGENT":"",J.vertexColors||J.instancingColor?"#define USE_COLOR":"",J.vertexAlphas||J.batchingColor?"#define USE_COLOR_ALPHA":"",J.vertexUv1s?"#define USE_UV1":"",J.vertexUv2s?"#define USE_UV2":"",J.vertexUv3s?"#define USE_UV3":"",J.pointsUvs?"#define USE_POINTS_UV":"",J.gradientMap?"#define USE_GRADIENTMAP":"",J.flatShading?"#define FLAT_SHADED":"",J.doubleSided?"#define DOUBLE_SIDED":"",J.flipSided?"#define FLIP_SIDED":"",J.shadowMapEnabled?"#define USE_SHADOWMAP":"",J.shadowMapEnabled?"#define "+N:"",J.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",J.numLightProbes>0?"#define USE_LIGHT_PROBES":"",J.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",J.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",J.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",J.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",J.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",J.toneMapping!==dU?"#define TONE_MAPPING":"",J.toneMapping!==dU?i$.tonemapping_pars_fragment:"",J.toneMapping!==dU?Uw("toneMapping",J.toneMapping):"",J.dithering?"#define DITHERING":"",J.opaque?"#define OPAQUE":"",i$.colorspace_pars_fragment,eV("linearToOutputTexel",J.outputColorSpace),Jw(),J.useDepthPacking?"#define DEPTH_PACKING "+J.depthPacking:"",`-`].filter(mW).join(`-`);if(X=vH(X),X=DZ(X,J),X=FZ(X,J),H=vH(H),H=DZ(H,J),H=FZ(H,J),X=LZ(X),H=LZ(H),J.isRawShaderMaterial!==!0)_=`#version 300 es-`,q=[k,"#define attribute in","#define varying out","#define texture2D texture"].join(`+ }`,depthTest:!1,depthWrite:!1}),u=new dt(c,l),f=new ur(-1,1,1,-1,0,1),h=null,d=null,g=!1,b,p=null,m=[],A=!1;this.setSize=function(T,v){o.setSize(T,v),a.setSize(T,v);for(let w=0;w<m.length;w++){let E=m[w];if(E.setSize)E.setSize(T,v)}},this.setEffects=function(T){m=T,A=m.length>0&&m[0].isRenderPass===!0;let{width:v,height:w}=o;for(let E=0;E<m.length;E++){let R=m[E];if(R.setSize)R.setSize(v,w)}},this.begin=function(T,v){if(g)return!1;if(T.toneMapping===Pn&&m.length===0)return!1;if(p=v,v!==null){let{width:w,height:E}=v;if(o.width!==w||o.height!==E)this.setSize(w,E)}if(A===!1)T.setRenderTarget(o);return b=T.toneMapping,T.toneMapping=Pn,!0},this.hasRenderPass=function(){return A},this.end=function(T,v){T.toneMapping=b,g=!0;let w=o,E=a;for(let R=0;R<m.length;R++){let _=m[R];if(_.enabled===!1)continue;if(_.render(T,E,w,v),_.needsSwap!==!1){let S=w;w=E,E=S}}if(h!==T.outputColorSpace||d!==T.toneMapping){if(h=T.outputColorSpace,d=T.toneMapping,l.defines={},Ve.getTransfer(h)===ut)l.defines.SRGB_TRANSFER="";let R=kb[d];if(R)l.defines[R]="";l.needsUpdate=!0}l.uniforms.tDiffuse.value=w.texture,T.setRenderTarget(p),T.render(u,f),p=null,g=!1},this.isCompositing=function(){return g},this.dispose=function(){if(o.depthTexture)o.depthTexture.dispose();o.dispose(),a.dispose(),c.dispose(),l.dispose()}}var Md=new St,Xl=new Ni(1,1),wd=new Yo,Td=new Sl,Ed=new na,rd=[],sd=[],od=new Float32Array(16),ad=new Float32Array(9),cd=new Float32Array(4);function ts(e,t,n){let i=e[0];if(i<=0||i>0)return e;let r=t*n,s=rd[r];if(s===void 0)s=new Float32Array(r),rd[r]=s;if(t!==0){i.toArray(s,0);for(let o=1,a=0;o!==t;++o)a+=n,e[o].toArray(s,a)}return s}function Lt(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n<i;n++)if(e[n]!==t[n])return!1;return!0}function Nt(e,t){for(let n=0,i=t.length;n<i;n++)e[n]=t[n]}function xa(e,t){let n=sd[t];if(n===void 0)n=new Int32Array(t),sd[t]=n;for(let i=0;i!==t;++i)n[i]=e.allocateTextureUnit();return n}function Gb(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1f(this.addr,t),n[0]=t}function Hb(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y)e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y}else{if(Lt(n,t))return;e.uniform2fv(this.addr,t),Nt(n,t)}}function Vb(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z}else if(t.r!==void 0){if(n[0]!==t.r||n[1]!==t.g||n[2]!==t.b)e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b}else{if(Lt(n,t))return;e.uniform3fv(this.addr,t),Nt(n,t)}}function Wb(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w}else{if(Lt(n,t))return;e.uniform4fv(this.addr,t),Nt(n,t)}}function $b(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(Lt(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),Nt(n,t)}else{if(Lt(n,i))return;cd.set(i),e.uniformMatrix2fv(this.addr,!1,cd),Nt(n,i)}}function Zb(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(Lt(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),Nt(n,t)}else{if(Lt(n,i))return;ad.set(i),e.uniformMatrix3fv(this.addr,!1,ad),Nt(n,i)}}function Xb(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(Lt(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),Nt(n,t)}else{if(Lt(n,i))return;od.set(i),e.uniformMatrix4fv(this.addr,!1,od),Nt(n,i)}}function qb(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1i(this.addr,t),n[0]=t}function Yb(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y)e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y}else{if(Lt(n,t))return;e.uniform2iv(this.addr,t),Nt(n,t)}}function jb(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z}else{if(Lt(n,t))return;e.uniform3iv(this.addr,t),Nt(n,t)}}function Jb(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w}else{if(Lt(n,t))return;e.uniform4iv(this.addr,t),Nt(n,t)}}function Kb(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1ui(this.addr,t),n[0]=t}function Qb(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y)e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y}else{if(Lt(n,t))return;e.uniform2uiv(this.addr,t),Nt(n,t)}}function eS(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z}else{if(Lt(n,t))return;e.uniform3uiv(this.addr,t),Nt(n,t)}}function tS(e,t){let n=this.cache;if(t.x!==void 0){if(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w}else{if(Lt(n,t))return;e.uniform4uiv(this.addr,t),Nt(n,t)}}function nS(e,t,n){let i=this.cache,r=n.allocateTextureUnit();if(i[0]!==r)e.uniform1i(this.addr,r),i[0]=r;let s;if(this.type===e.SAMPLER_2D_SHADOW)Xl.compareFunction=n.isReversedDepthBuffer()?qo:Xo,s=Xl;else s=Md;n.setTexture2D(t||s,r)}function iS(e,t,n){let i=this.cache,r=n.allocateTextureUnit();if(i[0]!==r)e.uniform1i(this.addr,r),i[0]=r;n.setTexture3D(t||Td,r)}function rS(e,t,n){let i=this.cache,r=n.allocateTextureUnit();if(i[0]!==r)e.uniform1i(this.addr,r),i[0]=r;n.setTextureCube(t||Ed,r)}function sS(e,t,n){let i=this.cache,r=n.allocateTextureUnit();if(i[0]!==r)e.uniform1i(this.addr,r),i[0]=r;n.setTexture2DArray(t||wd,r)}function oS(e){switch(e){case 5126:return Gb;case 35664:return Hb;case 35665:return Vb;case 35666:return Wb;case 35674:return $b;case 35675:return Zb;case 35676:return Xb;case 5124:case 35670:return qb;case 35667:case 35671:return Yb;case 35668:case 35672:return jb;case 35669:case 35673:return Jb;case 5125:return Kb;case 36294:return Qb;case 36295:return eS;case 36296:return tS;case 35678:case 36198:case 36298:case 36306:case 35682:return nS;case 35679:case 36299:case 36307:return iS;case 35680:case 36300:case 36308:case 36293:return rS;case 36289:case 36303:case 36311:case 36292:return sS}}function aS(e,t){e.uniform1fv(this.addr,t)}function cS(e,t){let n=ts(t,this.size,2);e.uniform2fv(this.addr,n)}function lS(e,t){let n=ts(t,this.size,3);e.uniform3fv(this.addr,n)}function uS(e,t){let n=ts(t,this.size,4);e.uniform4fv(this.addr,n)}function hS(e,t){let n=ts(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function fS(e,t){let n=ts(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function dS(e,t){let n=ts(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function pS(e,t){e.uniform1iv(this.addr,t)}function mS(e,t){e.uniform2iv(this.addr,t)}function gS(e,t){e.uniform3iv(this.addr,t)}function _S(e,t){e.uniform4iv(this.addr,t)}function xS(e,t){e.uniform1uiv(this.addr,t)}function vS(e,t){e.uniform2uiv(this.addr,t)}function yS(e,t){e.uniform3uiv(this.addr,t)}function bS(e,t){e.uniform4uiv(this.addr,t)}function SS(e,t,n){let i=this.cache,r=t.length,s=xa(n,r);if(!Lt(i,s))e.uniform1iv(this.addr,s),Nt(i,s);let o;if(this.type===e.SAMPLER_2D_SHADOW)o=Xl;else o=Md;for(let a=0;a!==r;++a)n.setTexture2D(t[a]||o,s[a])}function MS(e,t,n){let i=this.cache,r=t.length,s=xa(n,r);if(!Lt(i,s))e.uniform1iv(this.addr,s),Nt(i,s);for(let o=0;o!==r;++o)n.setTexture3D(t[o]||Td,s[o])}function wS(e,t,n){let i=this.cache,r=t.length,s=xa(n,r);if(!Lt(i,s))e.uniform1iv(this.addr,s),Nt(i,s);for(let o=0;o!==r;++o)n.setTextureCube(t[o]||Ed,s[o])}function TS(e,t,n){let i=this.cache,r=t.length,s=xa(n,r);if(!Lt(i,s))e.uniform1iv(this.addr,s),Nt(i,s);for(let o=0;o!==r;++o)n.setTexture2DArray(t[o]||wd,s[o])}function ES(e){switch(e){case 5126:return aS;case 35664:return cS;case 35665:return lS;case 35666:return uS;case 35674:return hS;case 35675:return fS;case 35676:return dS;case 5124:case 35670:return pS;case 35667:case 35671:return mS;case 35668:case 35672:return gS;case 35669:case 35673:return _S;case 5125:return xS;case 36294:return vS;case 36295:return yS;case 36296:return bS;case 35678:case 36198:case 36298:case 36306:case 35682:return SS;case 35679:case 36299:case 36307:return MS;case 35680:case 36300:case 36308:case 36293:return wS;case 36289:case 36303:case 36311:case 36292:return TS}}class Ad{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=oS(t.type)}}class Rd{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=ES(t.type)}}class Cd{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let i=this.seq;for(let r=0,s=i.length;r!==s;++r){let o=i[r];o.setValue(e,t[o.id],n)}}}var $l=/(\w+)(\])?(\[|\.)?/g;function ld(e,t){e.seq.push(t),e.map[t.id]=t}function AS(e,t,n){let i=e.name,r=i.length;$l.lastIndex=0;while(!0){let s=$l.exec(i),o=$l.lastIndex,a=s[1],c=s[2]==="]",l=s[3];if(c)a=a|0;if(l===void 0||l==="["&&o+2===r){ld(n,l===void 0?new Ad(a,e,t):new Rd(a,e,t));break}else{let f=n.map[a];if(f===void 0)f=new Cd(a),ld(n,f);n=f}}}class Bs{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let s=0;s<n;++s){let o=e.getActiveUniform(t,s),a=e.getUniformLocation(t,o.name);AS(o,a,this)}let i=[],r=[];for(let s of this.seq)if(s.type===e.SAMPLER_2D_SHADOW||s.type===e.SAMPLER_CUBE_SHADOW||s.type===e.SAMPLER_2D_ARRAY_SHADOW)i.push(s);else r.push(s);if(i.length>0)this.seq=i.concat(r)}setValue(e,t,n,i){let r=this.map[t];if(r!==void 0)r.setValue(e,n,i)}setOptional(e,t,n){let i=t[n];if(i!==void 0)this.setValue(e,n,i)}static upload(e,t,n,i){for(let r=0,s=t.length;r!==s;++r){let o=t[r],a=n[o.id];if(a.needsUpdate!==!1)o.setValue(e,a.value,i)}}static seqWithValue(e,t){let n=[];for(let i=0,r=e.length;i!==r;++i){let s=e[i];if(s.id in t)n.push(s)}return n}}function ud(e,t,n){let i=e.createShader(t);return e.shaderSource(i,n),e.compileShader(i),i}var RS=37297,CS=0;function PS(e,t){let n=e.split(`+`),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let o=r;o<s;o++){let a=o+1;i.push(`${a===t?">":" "} ${a}: ${n[o]}`)}return i.join(`+`)}var hd=new De;function IS(e){Ve._getMatrix(hd,Ve.workingColorSpace,e);let t=`mat3( ${hd.elements.map((n)=>n.toFixed(4))} )`;switch(Ve.getTransfer(e)){case gl:return[t,"LinearTransferOETF"];case ut:return[t,"sRGBTransferOETF"];default:return Me("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}function fd(e,t,n){let i=e.getShaderParameter(t,e.COMPILE_STATUS),s=(e.getShaderInfoLog(t)||"").trim();if(i&&s==="")return"";let o=/ERROR: 0:(\d+)/.exec(s);if(o){let a=parseInt(o[1]);return n.toUpperCase()+`++`+s+`++`+PS(e.getShaderSource(t),a)}else return s}function LS(e,t){let n=IS(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(`+`)}var NS={[Tc]:"Linear",[Ec]:"Reinhard",[Ac]:"Cineon",[vs]:"ACESFilmic",[Cc]:"AgX",[Pc]:"Neutral",[Rc]:"Custom"};function DS(e,t){let n=NS[t];if(n===void 0)return Me("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }";return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}var ga=new N;function US(){Ve.getLuminanceCoefficients(ga);let e=ga.x.toFixed(4),t=ga.y.toFixed(4),n=ga.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${e}, ${t}, ${n} );`,"\treturn dot( weights, rgb );","}"].join(`+`)}function OS(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(ks).join(`+`)}function FS(e){let t=[];for(let n in e){let i=e[n];if(i===!1)continue;t.push("#define "+n+" "+i)}return t.join(`+`)}function zS(e,t){let n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<i;r++){let s=e.getActiveAttrib(t,r),o=s.name,a=1;if(s.type===e.FLOAT_MAT2)a=2;if(s.type===e.FLOAT_MAT3)a=3;if(s.type===e.FLOAT_MAT4)a=4;n[o]={type:s.type,location:e.getAttribLocation(t,o),locationSize:a}}return n}function ks(e){return e!==""}function dd(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function pd(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var kS=/^[ \t]*#include +<([\w\d./]+)>/gm;function ql(e){return e.replace(kS,GS)}var BS=new Map;function GS(e,t){let n=Ge[t];if(n===void 0){let i=BS.get(t);if(i!==void 0)n=Ge[i],Me('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,i);else throw Error("THREE.WebGLProgram: Can not resolve #include <"+t+">")}return ql(n)}var HS=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function md(e){return e.replace(HS,VS)}function VS(e,t,n,i){let r="";for(let s=parseInt(t);s<parseInt(n);s++)r+=i.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return r}function gd(e){let t=`precision ${e.precision} float;+ precision ${e.precision} int;+ precision ${e.precision} sampler2D;+ precision ${e.precision} samplerCube;+ precision ${e.precision} sampler3D;+ precision ${e.precision} sampler2DArray;+ precision ${e.precision} sampler2DShadow;+ precision ${e.precision} samplerCubeShadow;+ precision ${e.precision} sampler2DArrayShadow;+ precision ${e.precision} isampler2D;+ precision ${e.precision} isampler3D;+ precision ${e.precision} isamplerCube;+ precision ${e.precision} isampler2DArray;+ precision ${e.precision} usampler2D;+ precision ${e.precision} usampler3D;+ precision ${e.precision} usamplerCube;+ precision ${e.precision} usampler2DArray;+ `;if(e.precision==="highp")t+=`+#define HIGH_PRECISION`;else if(e.precision==="mediump")t+=`+#define MEDIUM_PRECISION`;else if(e.precision==="lowp")t+=`+#define LOW_PRECISION`;return t}var WS={[_s]:"SHADOWMAP_TYPE_PCF",[kr]:"SHADOWMAP_TYPE_VSM"};function $S(e){return WS[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}var ZS={[Gr]:"ENVMAP_TYPE_CUBE",[nr]:"ENVMAP_TYPE_CUBE",[ys]:"ENVMAP_TYPE_CUBE_UV"};function XS(e){if(e.envMap===!1)return"ENVMAP_TYPE_CUBE";return ZS[e.envMapMode]||"ENVMAP_TYPE_CUBE"}var qS={[nr]:"ENVMAP_MODE_REFRACTION"};function YS(e){if(e.envMap===!1)return"ENVMAP_MODE_REFLECTION";return qS[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}var jS={[wf]:"ENVMAP_BLENDING_MULTIPLY",[Tf]:"ENVMAP_BLENDING_MIX",[Ef]:"ENVMAP_BLENDING_ADD"};function JS(e){if(e.envMap===!1)return"ENVMAP_BLENDING_NONE";return jS[e.combine]||"ENVMAP_BLENDING_NONE"}function KS(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let n=Math.log2(t)-2,i=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:i,maxMip:n}}function QS(e,t,n,i){let r=e.getContext(),{defines:s,vertexShader:o,fragmentShader:a}=n,c=$S(n),l=XS(n),u=YS(n),f=JS(n),h=KS(n),d=OS(n),g=FS(s),b=r.createProgram(),p,m,A=n.glslVersion?"#version "+n.glslVersion+`+`:"";if(n.isRawShaderMaterial){if(p=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(ks).join(`+`),p.length>0)p+=`+`;if(m=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(ks).join(`+`),m.length>0)m+=`+`}else p=[gd(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexNormals?"#define HAS_NORMAL":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&n.flatShading===!1?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.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","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif",`+`].filter(ks).join(`+`),m=[gd(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+l:"",n.envMap?"#define "+u:"",n.envMap?"#define "+f:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas||n.batchingColor?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==Pn?"#define TONE_MAPPING":"",n.toneMapping!==Pn?Ge.tonemapping_pars_fragment:"",n.toneMapping!==Pn?DS("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Ge.colorspace_pars_fragment,LS("linearToOutputTexel",n.outputColorSpace),US(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`+`].filter(ks).join(`+`);if(o=ql(o),o=dd(o,n),o=pd(o,n),a=ql(a),a=dd(a,n),a=pd(a,n),o=md(o),a=md(a),n.isRawShaderMaterial!==!0)A=`#version 300 es+`,p=[d,"#define attribute in","#define varying out","#define texture2D texture"].join(``)+`-`+q,Z=["#define varying in",J.glslVersion===UH?"":"layout(location = 0) out highp vec4 pc_fragColor;",J.glslVersion===UH?"":"#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(`+`+p,m=["#define varying in",n.glslVersion===_l?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===_l?"":"#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(``)+`-`+Z;let P=_+q+X,L=_+Z+H,B=qZ(W,W.VERTEX_SHADER,P),z=qZ(W,W.FRAGMENT_SHADER,L);if(W.attachShader(R,B),W.attachShader(R,z),J.index0AttributeName!==void 0)W.bindAttribLocation(R,0,J.index0AttributeName);else if(J.hasPositionAttribute===!0)W.bindAttribLocation(R,0,"position");W.linkProgram(R);function A(C){if($.debug.checkShaderErrors){let f=W.getProgramInfoLog(R)||"",s=W.getShaderInfoLog(B)||"",x=W.getShaderInfoLog(z)||"",d=f.trim(),c=s.trim(),y=x.trim(),t=!0,e=!0;if(W.getProgramParameter(R,W.LINK_STATUS)===!1)if(t=!1,typeof $.debug.onShaderError==="function")$.debug.onShaderError(W,R,B,z);else{let Y$=IZ(W,B,"vertex"),R$=IZ(W,z,"fragment");x$("WebGLProgram: Shader Error "+W.getError()+" - VALIDATE_STATUS "+W.getProgramParameter(R,W.VALIDATE_STATUS)+`+`+m;let T=A+p+o,v=A+m+a,w=ud(r,r.VERTEX_SHADER,T),E=ud(r,r.FRAGMENT_SHADER,v);if(r.attachShader(b,w),r.attachShader(b,E),n.index0AttributeName!==void 0)r.bindAttribLocation(b,0,n.index0AttributeName);else if(n.hasPositionAttribute===!0)r.bindAttribLocation(b,0,"position");r.linkProgram(b);function R(C){if(e.debug.checkShaderErrors){let z=r.getProgramInfoLog(b)||"",J=r.getShaderInfoLog(w)||"",O=r.getShaderInfoLog(E)||"",H=z.trim(),V=J.trim(),U=O.trim(),K=!0,Q=!0;if(r.getProgramParameter(b,r.LINK_STATUS)===!1)if(K=!1,typeof e.debug.onShaderError==="function")e.debug.onShaderError(r,b,w,E);else{let se=fd(r,w,"vertex"),me=fd(r,E,"fragment");Ne("WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(b,r.VALIDATE_STATUS)+`Material Name: `+C.name+`Material Type: `+C.type+`-Program Info Log: `+d+`-`+Y$+`-`+R$)}else if(d!=="")A$("WebGLProgram: Program Info Log:",d);else if(c===""||y==="")e=!1;if(e)C.diagnostics={runnable:t,programLog:d,vertexShader:{log:c,prefix:q},fragmentShader:{log:y,prefix:Z}}}W.deleteShader(B),W.deleteShader(z),D=new pW(W,R),w=Kw(W,R)}let D;this.getUniforms=function(){if(D===void 0)A(this);return D};let w;this.getAttributes=function(){if(w===void 0)A(this);return w};let h=J.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){if(h===!1)h=W.getProgramParameter(R,rV);return h},this.destroy=function(){Q.releaseStatesOfProgram(this),W.deleteProgram(R),this.program=void 0},this.type=J.shaderType,this.name=J.shaderName,this.id=aV++,this.cacheKey=U,this.usedTimes=1,this.program=R,this.vertexShader=B,this.fragmentShader=z,this}var Vw=0;class gZ{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update($,U,J){let Q=this._getShaderCacheForMaterial($);if(Q.has(U)===!1)Q.add(U),U.usedTimes++;if(Q.has(J)===!1)Q.add(J),J.usedTimes++;return this}remove($){let U=this.materialCache.get($);for(let J of U)if(J.usedTimes--,J.usedTimes===0)this.shaderCache.delete(J.code);return this.materialCache.delete($),this}getVertexShaderStage($){return this._getShaderStage($.vertexShader)}getFragmentShaderStage($){return this._getShaderStage($.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial($){let U=this.materialCache,J=U.get($);if(J===void 0)J=new Set,U.set($,J);return J}_getShaderStage($){let U=this.shaderCache,J=U.get($);if(J===void 0)J=new bZ($),U.set($,J);return J}}class bZ{constructor($){this.id=Vw++,this.code=$,this.usedTimes=0}}function ww($){return $===S0||$===D9||$===F9}function Mw($,U,J,Q,W,K){let X=new M9,H=new gZ,N=new Set,Y=[],G=new Map,O=Q.logarithmicDepthBuffer,E=Q.precision,k={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 I(D){if(N.add(D),D===0)return"uv";return`uv${D}`}function R(D,w,h,C,f,s){let x=C.fog,d=f.geometry,c=D.isMeshStandardMaterial||D.isMeshLambertMaterial||D.isMeshPhongMaterial?C.environment:null,y=D.isMeshStandardMaterial||D.isMeshLambertMaterial&&!D.envMap||D.isMeshPhongMaterial&&!D.envMap,t=U.get(D.envMap||c,y),e=!!t&&t.mapping===MW?t.image.height:null,Y$=k[D.type];if(D.precision!==null){if(E=Q.getMaxPrecision(D.precision),E!==D.precision)A$("WebGLProgram.getParameters:",D.precision,"not supported, using",E,"instead.")}let R$=d.morphAttributes.position||d.morphAttributes.normal||d.morphAttributes.color,w$=R$!==void 0?R$.length:0,$6=0;if(d.morphAttributes.position!==void 0)$6=1;if(d.morphAttributes.normal!==void 0)$6=2;if(d.morphAttributes.color!==void 0)$6=3;let n$,i,X$,D$;if(Y$){let l$=HJ[Y$];n$=l$.vertexShader,i=l$.fragmentShader}else{n$=D.vertexShader,i=D.fragmentShader;let l$=H.getVertexShaderStage(D),_6=H.getFragmentShaderStage(D);H.update(D,l$,_6),X$=l$.id,D$=_6.id}let F$=$.getRenderTarget(),v$=$.state.buffers.depth.getReversed(),t$=f.isInstancedMesh===!0,u$=f.isBatchedMesh===!0,p$=!!D.map,K6=!!D.matcap,U6=!!t,Q6=!!D.aoMap,m6=!!D.lightMap,_U=!!D.bumpMap&&D.wireframe===!1,P6=!!D.normalMap,o6=!!D.displacementMap,p6=!!D.emissiveMap,y6=!!D.metalnessMap,v=!!D.roughnessMap,AU=D.anisotropy>0,Y6=D.clearcoat>0,z6=D.dispersion>0,M=D.iridescence>0,F=D.sheen>0,S=D.transmission>0,n=AU&&!!D.anisotropyMap,J$=Y6&&!!D.clearcoatMap,H$=Y6&&!!D.clearcoatNormalMap,k$=Y6&&!!D.clearcoatRoughnessMap,o=M&&!!D.iridescenceMap,a=M&&!!D.iridescenceThicknessMap,M$=F&&!!D.sheenColorMap,C$=F&&!!D.sheenRoughnessMap,q$=!!D.specularMap,N$=!!D.specularColorMap,j$=!!D.specularIntensityMap,b$=S&&!!D.transmissionMap,H6=S&&!!D.thicknessMap,T=!!D.gradientMap,G$=!!D.alphaMap,r=D.alphaTest>0,O$=!!D.alphaHash,B$=!!D.extensions,$$=dU;if(D.toneMapped){if(F$===null||F$.isXRRenderTarget===!0)$$=$.toneMapping}let E$={shaderID:Y$,shaderType:D.type,shaderName:D.name,vertexShader:n$,fragmentShader:i,defines:D.defines,customVertexShaderID:X$,customFragmentShaderID:D$,isRawShaderMaterial:D.isRawShaderMaterial===!0,glslVersion:D.glslVersion,precision:E,batching:u$,batchingColor:u$&&f._colorsTexture!==null,instancing:t$,instancingColor:t$&&f.instanceColor!==null,instancingMorph:t$&&f.morphTexture!==null,outputColorSpace:F$===null?$.outputColorSpace:F$.isXRRenderTarget===!0?F$.texture.colorSpace:r$.workingColorSpace,alphaToCoverage:!!D.alphaToCoverage,map:p$,matcap:K6,envMap:U6,envMapMode:U6&&t.mapping,envMapCubeUVHeight:e,aoMap:Q6,lightMap:m6,bumpMap:_U,normalMap:P6,displacementMap:o6,emissiveMap:p6,normalMapObjectSpace:P6&&D.normalMapType===hq,normalMapTangentSpace:P6&&D.normalMapType===eX,packedNormalMap:P6&&D.normalMapType===eX&&ww(D.normalMap.format),metalnessMap:y6,roughnessMap:v,anisotropy:AU,anisotropyMap:n,clearcoat:Y6,clearcoatMap:J$,clearcoatNormalMap:H$,clearcoatRoughnessMap:k$,dispersion:z6,iridescence:M,iridescenceMap:o,iridescenceThicknessMap:a,sheen:F,sheenColorMap:M$,sheenRoughnessMap:C$,specularMap:q$,specularColorMap:N$,specularIntensityMap:j$,transmission:S,transmissionMap:b$,thicknessMap:H6,gradientMap:T,opaque:D.transparent===!1&&D.blending===VW&&D.alphaToCoverage===!1,alphaMap:G$,alphaTest:r,alphaHash:O$,combine:D.combine,mapUv:p$&&I(D.map.channel),aoMapUv:Q6&&I(D.aoMap.channel),lightMapUv:m6&&I(D.lightMap.channel),bumpMapUv:_U&&I(D.bumpMap.channel),normalMapUv:P6&&I(D.normalMap.channel),displacementMapUv:o6&&I(D.displacementMap.channel),emissiveMapUv:p6&&I(D.emissiveMap.channel),metalnessMapUv:y6&&I(D.metalnessMap.channel),roughnessMapUv:v&&I(D.roughnessMap.channel),anisotropyMapUv:n&&I(D.anisotropyMap.channel),clearcoatMapUv:J$&&I(D.clearcoatMap.channel),clearcoatNormalMapUv:H$&&I(D.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:k$&&I(D.clearcoatRoughnessMap.channel),iridescenceMapUv:o&&I(D.iridescenceMap.channel),iridescenceThicknessMapUv:a&&I(D.iridescenceThicknessMap.channel),sheenColorMapUv:M$&&I(D.sheenColorMap.channel),sheenRoughnessMapUv:C$&&I(D.sheenRoughnessMap.channel),specularMapUv:q$&&I(D.specularMap.channel),specularColorMapUv:N$&&I(D.specularColorMap.channel),specularIntensityMapUv:j$&&I(D.specularIntensityMap.channel),transmissionMapUv:b$&&I(D.transmissionMap.channel),thicknessMapUv:H6&&I(D.thicknessMap.channel),alphaMapUv:G$&&I(D.alphaMap.channel),vertexTangents:!!d.attributes.tangent&&(P6||AU),vertexNormals:!!d.attributes.normal,vertexColors:D.vertexColors,vertexAlphas:D.vertexColors===!0&&!!d.attributes.color&&d.attributes.color.itemSize===4,pointsUvs:f.isPoints===!0&&!!d.attributes.uv&&(p$||G$),fog:!!x,useFog:D.fog===!0,fogExp2:!!x&&x.isFogExp2,flatShading:D.wireframe===!1&&(D.flatShading===!0||d.attributes.normal===void 0&&P6===!1&&(D.isMeshLambertMaterial||D.isMeshPhongMaterial||D.isMeshStandardMaterial||D.isMeshPhysicalMaterial)),sizeAttenuation:D.sizeAttenuation===!0,logarithmicDepthBuffer:O,reversedDepthBuffer:v$,skinning:f.isSkinnedMesh===!0,hasPositionAttribute:d.attributes.position!==void 0,morphTargets:d.morphAttributes.position!==void 0,morphNormals:d.morphAttributes.normal!==void 0,morphColors:d.morphAttributes.color!==void 0,morphTargetsCount:w$,morphTextureStride:$6,numDirLights:w.directional.length,numPointLights:w.point.length,numSpotLights:w.spot.length,numSpotLightMaps:w.spotLightMap.length,numRectAreaLights:w.rectArea.length,numHemiLights:w.hemi.length,numDirLightShadows:w.directionalShadowMap.length,numPointLightShadows:w.pointShadowMap.length,numSpotLightShadows:w.spotShadowMap.length,numSpotLightShadowsWithMaps:w.numSpotLightShadowsWithMaps,numLightProbes:w.numLightProbes,numLightProbeGrids:s.length,numClippingPlanes:K.numPlanes,numClipIntersection:K.numIntersection,dithering:D.dithering,shadowMapEnabled:$.shadowMap.enabled&&h.length>0,shadowMapType:$.shadowMap.type,toneMapping:$$,decodeVideoTexture:p$&&D.map.isVideoTexture===!0&&r$.getTransfer(D.map.colorSpace)===R6,decodeVideoTextureEmissive:p6&&D.emissiveMap.isVideoTexture===!0&&r$.getTransfer(D.emissiveMap.colorSpace)===R6,premultipliedAlpha:D.premultipliedAlpha,doubleSided:D.side===vU,flipSided:D.side===$U,useDepthPacking:D.depthPacking>=0,depthPacking:D.depthPacking||0,index0AttributeName:D.index0AttributeName,extensionClipCullDistance:B$&&D.extensions.clipCullDistance===!0&&J.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(B$&&D.extensions.multiDraw===!0||u$)&&J.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:J.has("KHR_parallel_shader_compile"),customProgramCacheKey:D.customProgramCacheKey()};return E$.vertexUv1s=N.has(1),E$.vertexUv2s=N.has(2),E$.vertexUv3s=N.has(3),N.clear(),E$}function q(D){let w=[];if(D.shaderID)w.push(D.shaderID);else w.push(D.customVertexShaderID),w.push(D.customFragmentShaderID);if(D.defines!==void 0)for(let h in D.defines)w.push(h),w.push(D.defines[h]);if(D.isRawShaderMaterial===!1)Z(w,D),_(w,D),w.push($.outputColorSpace);return w.push(D.customProgramCacheKey),w.join()}function Z(D,w){D.push(w.precision),D.push(w.outputColorSpace),D.push(w.envMapMode),D.push(w.envMapCubeUVHeight),D.push(w.mapUv),D.push(w.alphaMapUv),D.push(w.lightMapUv),D.push(w.aoMapUv),D.push(w.bumpMapUv),D.push(w.normalMapUv),D.push(w.displacementMapUv),D.push(w.emissiveMapUv),D.push(w.metalnessMapUv),D.push(w.roughnessMapUv),D.push(w.anisotropyMapUv),D.push(w.clearcoatMapUv),D.push(w.clearcoatNormalMapUv),D.push(w.clearcoatRoughnessMapUv),D.push(w.iridescenceMapUv),D.push(w.iridescenceThicknessMapUv),D.push(w.sheenColorMapUv),D.push(w.sheenRoughnessMapUv),D.push(w.specularMapUv),D.push(w.specularColorMapUv),D.push(w.specularIntensityMapUv),D.push(w.transmissionMapUv),D.push(w.thicknessMapUv),D.push(w.combine),D.push(w.fogExp2),D.push(w.sizeAttenuation),D.push(w.morphTargetsCount),D.push(w.morphAttributeCount),D.push(w.numDirLights),D.push(w.numPointLights),D.push(w.numSpotLights),D.push(w.numSpotLightMaps),D.push(w.numHemiLights),D.push(w.numRectAreaLights),D.push(w.numDirLightShadows),D.push(w.numPointLightShadows),D.push(w.numSpotLightShadows),D.push(w.numSpotLightShadowsWithMaps),D.push(w.numLightProbes),D.push(w.shadowMapType),D.push(w.toneMapping),D.push(w.numClippingPlanes),D.push(w.numClipIntersection),D.push(w.depthPacking)}function _(D,w){if(X.disableAll(),w.instancing)X.enable(0);if(w.instancingColor)X.enable(1);if(w.instancingMorph)X.enable(2);if(w.matcap)X.enable(3);if(w.envMap)X.enable(4);if(w.normalMapObjectSpace)X.enable(5);if(w.normalMapTangentSpace)X.enable(6);if(w.clearcoat)X.enable(7);if(w.iridescence)X.enable(8);if(w.alphaTest)X.enable(9);if(w.vertexColors)X.enable(10);if(w.vertexAlphas)X.enable(11);if(w.vertexUv1s)X.enable(12);if(w.vertexUv2s)X.enable(13);if(w.vertexUv3s)X.enable(14);if(w.vertexTangents)X.enable(15);if(w.anisotropy)X.enable(16);if(w.alphaHash)X.enable(17);if(w.batching)X.enable(18);if(w.dispersion)X.enable(19);if(w.batchingColor)X.enable(20);if(w.gradientMap)X.enable(21);if(w.packedNormalMap)X.enable(22);if(w.vertexNormals)X.enable(23);if(D.push(X.mask),X.disableAll(),w.fog)X.enable(0);if(w.useFog)X.enable(1);if(w.flatShading)X.enable(2);if(w.logarithmicDepthBuffer)X.enable(3);if(w.reversedDepthBuffer)X.enable(4);if(w.skinning)X.enable(5);if(w.morphTargets)X.enable(6);if(w.morphNormals)X.enable(7);if(w.morphColors)X.enable(8);if(w.premultipliedAlpha)X.enable(9);if(w.shadowMapEnabled)X.enable(10);if(w.doubleSided)X.enable(11);if(w.flipSided)X.enable(12);if(w.useDepthPacking)X.enable(13);if(w.dithering)X.enable(14);if(w.transmission)X.enable(15);if(w.sheen)X.enable(16);if(w.opaque)X.enable(17);if(w.pointsUvs)X.enable(18);if(w.decodeVideoTexture)X.enable(19);if(w.decodeVideoTextureEmissive)X.enable(20);if(w.alphaToCoverage)X.enable(21);if(w.numLightProbeGrids>0)X.enable(22);if(w.hasPositionAttribute)X.enable(23);D.push(X.mask)}function P(D){let w=k[D.type],h;if(w){let C=HJ[w];h=aq.clone(C.uniforms)}else h=D.uniforms;return h}function L(D,w){let h=G.get(w);if(h!==void 0)++h.usedTimes;else h=new Rw($,w,D,W),Y.push(h),G.set(w,h);return h}function B(D){if(--D.usedTimes===0){let w=Y.indexOf(D);Y[w]=Y[Y.length-1],Y.pop(),G.delete(D.cacheKey),D.destroy()}}function z(D){H.remove(D)}function A(){H.dispose()}return{getParameters:R,getProgramCacheKey:q,getUniforms:P,acquireProgram:L,releaseProgram:B,releaseShaderCache:z,programs:Y,dispose:A}}function Bw(){let $=new WeakMap;function U(X){return $.has(X)}function J(X){let H=$.get(X);if(H===void 0)H={},$.set(X,H);return H}function Q(X){$.delete(X)}function W(X,H,N){$.get(X)[H]=N}function K(){$=new WeakMap}return{has:U,get:J,remove:Q,update:W,dispose:K}}function Pw($,U){if($.groupOrder!==U.groupOrder)return $.groupOrder-U.groupOrder;else if($.renderOrder!==U.renderOrder)return $.renderOrder-U.renderOrder;else if($.material.id!==U.material.id)return $.material.id-U.material.id;else if($.materialVariant!==U.materialVariant)return $.materialVariant-U.materialVariant;else if($.z!==U.z)return $.z-U.z;else return $.id-U.id}function VZ($,U){if($.groupOrder!==U.groupOrder)return $.groupOrder-U.groupOrder;else if($.renderOrder!==U.renderOrder)return $.renderOrder-U.renderOrder;else if($.z!==U.z)return U.z-$.z;else return $.id-U.id}function wZ(){let $=[],U=0,J=[],Q=[],W=[];function K(){U=0,J.length=0,Q.length=0,W.length=0}function X(E){let k=0;if(E.isInstancedMesh)k+=2;if(E.isSkinnedMesh)k+=1;return k}function H(E,k,I,R,q,Z){let _=$[U];if(_===void 0)_={id:E.id,object:E,geometry:k,material:I,materialVariant:X(E),groupOrder:R,renderOrder:E.renderOrder,z:q,group:Z},$[U]=_;else _.id=E.id,_.object=E,_.geometry=k,_.material=I,_.materialVariant=X(E),_.groupOrder=R,_.renderOrder=E.renderOrder,_.z=q,_.group=Z;return U++,_}function N(E,k,I,R,q,Z){let _=H(E,k,I,R,q,Z);if(I.transmission>0)Q.push(_);else if(I.transparent===!0)W.push(_);else J.push(_)}function Y(E,k,I,R,q,Z){let _=H(E,k,I,R,q,Z);if(I.transmission>0)Q.unshift(_);else if(I.transparent===!0)W.unshift(_);else J.unshift(_)}function G(E,k,I){if(J.length>1)J.sort(E||Pw);if(Q.length>1)Q.sort(k||VZ);if(W.length>1)W.sort(k||VZ);if(I)J.reverse(),Q.reverse(),W.reverse()}function O(){for(let E=U,k=$.length;E<k;E++){let I=$[E];if(I.id===null)break;I.id=null,I.object=null,I.geometry=null,I.material=null,I.group=null}}return{opaque:J,transmissive:Q,transparent:W,init:K,push:N,unshift:Y,finish:O,sort:G}}function zw(){let $=new WeakMap;function U(Q,W){let K=$.get(Q),X;if(K===void 0)X=new wZ,$.set(Q,[X]);else if(W>=K.length)X=new wZ,K.push(X);else X=K[W];return X}function J(){$=new WeakMap}return{get:U,dispose:J}}function _w(){let $={};return{get:function(U){if($[U.id]!==void 0)return $[U.id];let J;switch(U.type){case"DirectionalLight":J={direction:new j,color:new y$};break;case"SpotLight":J={position:new j,direction:new j,color:new y$,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":J={position:new j,color:new y$,distance:0,decay:0};break;case"HemisphereLight":J={direction:new j,skyColor:new y$,groundColor:new y$};break;case"RectAreaLight":J={color:new y$,position:new j,halfWidth:new j,halfHeight:new j};break}return $[U.id]=J,J}}}function Aw(){let $={};return{get:function(U){if($[U.id]!==void 0)return $[U.id];let J;switch(U.type){case"DirectionalLight":J={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new g$};break;case"SpotLight":J={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new g$};break;case"PointLight":J={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new g$,shadowCameraNear:1,shadowCameraFar:1000};break}return $[U.id]=J,J}}}var Cw=0;function Sw($,U){return(U.castShadow?2:0)-($.castShadow?2:0)+(U.map?1:0)-($.map?1:0)}function Tw($){let U=new _w,J=Aw(),Q={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 Y=0;Y<9;Y++)Q.probe.push(new j);let W=new j,K=new m$,X=new m$;function H(Y){let G=0,O=0,E=0;for(let w=0;w<9;w++)Q.probe[w].set(0,0,0);let k=0,I=0,R=0,q=0,Z=0,_=0,P=0,L=0,B=0,z=0,A=0;Y.sort(Sw);for(let w=0,h=Y.length;w<h;w++){let C=Y[w],f=C.color,s=C.intensity,x=C.distance,d=null;if(C.shadow&&C.shadow.map)if(C.shadow.map.texture.format===S0)d=C.shadow.map.texture;else d=C.shadow.map.depthTexture||C.shadow.map.texture;if(C.isAmbientLight)G+=f.r*s,O+=f.g*s,E+=f.b*s;else if(C.isLightProbe){for(let c=0;c<9;c++)Q.probe[c].addScaledVector(C.sh.coefficients[c],s);A++}else if(C.isDirectionalLight){let c=U.get(C);if(c.color.copy(C.color).multiplyScalar(C.intensity),C.castShadow){let y=C.shadow,t=J.get(C);t.shadowIntensity=y.intensity,t.shadowBias=y.bias,t.shadowNormalBias=y.normalBias,t.shadowRadius=y.radius,t.shadowMapSize=y.mapSize,Q.directionalShadow[k]=t,Q.directionalShadowMap[k]=d,Q.directionalShadowMatrix[k]=C.shadow.matrix,_++}Q.directional[k]=c,k++}else if(C.isSpotLight){let c=U.get(C);c.position.setFromMatrixPosition(C.matrixWorld),c.color.copy(f).multiplyScalar(s),c.distance=x,c.coneCos=Math.cos(C.angle),c.penumbraCos=Math.cos(C.angle*(1-C.penumbra)),c.decay=C.decay,Q.spot[R]=c;let y=C.shadow;if(C.map){if(Q.spotLightMap[B]=C.map,B++,y.updateMatrices(C),C.castShadow)z++}if(Q.spotLightMatrix[R]=y.matrix,C.castShadow){let t=J.get(C);t.shadowIntensity=y.intensity,t.shadowBias=y.bias,t.shadowNormalBias=y.normalBias,t.shadowRadius=y.radius,t.shadowMapSize=y.mapSize,Q.spotShadow[R]=t,Q.spotShadowMap[R]=d,L++}R++}else if(C.isRectAreaLight){let c=U.get(C);c.color.copy(f).multiplyScalar(s),c.halfWidth.set(C.width*0.5,0,0),c.halfHeight.set(0,C.height*0.5,0),Q.rectArea[q]=c,q++}else if(C.isPointLight){let c=U.get(C);if(c.color.copy(C.color).multiplyScalar(C.intensity),c.distance=C.distance,c.decay=C.decay,C.castShadow){let y=C.shadow,t=J.get(C);t.shadowIntensity=y.intensity,t.shadowBias=y.bias,t.shadowNormalBias=y.normalBias,t.shadowRadius=y.radius,t.shadowMapSize=y.mapSize,t.shadowCameraNear=y.camera.near,t.shadowCameraFar=y.camera.far,Q.pointShadow[I]=t,Q.pointShadowMap[I]=d,Q.pointShadowMatrix[I]=C.shadow.matrix,P++}Q.point[I]=c,I++}else if(C.isHemisphereLight){let c=U.get(C);c.skyColor.copy(C.color).multiplyScalar(s),c.groundColor.copy(C.groundColor).multiplyScalar(s),Q.hemi[Z]=c,Z++}}if(q>0)if($.has("OES_texture_float_linear")===!0)Q.rectAreaLTC1=Z$.LTC_FLOAT_1,Q.rectAreaLTC2=Z$.LTC_FLOAT_2;else Q.rectAreaLTC1=Z$.LTC_HALF_1,Q.rectAreaLTC2=Z$.LTC_HALF_2;Q.ambient[0]=G,Q.ambient[1]=O,Q.ambient[2]=E;let D=Q.hash;if(D.directionalLength!==k||D.pointLength!==I||D.spotLength!==R||D.rectAreaLength!==q||D.hemiLength!==Z||D.numDirectionalShadows!==_||D.numPointShadows!==P||D.numSpotShadows!==L||D.numSpotMaps!==B||D.numLightProbes!==A)Q.directional.length=k,Q.spot.length=R,Q.rectArea.length=q,Q.point.length=I,Q.hemi.length=Z,Q.directionalShadow.length=_,Q.directionalShadowMap.length=_,Q.pointShadow.length=P,Q.pointShadowMap.length=P,Q.spotShadow.length=L,Q.spotShadowMap.length=L,Q.directionalShadowMatrix.length=_,Q.pointShadowMatrix.length=P,Q.spotLightMatrix.length=L+B-z,Q.spotLightMap.length=B,Q.numSpotLightShadowsWithMaps=z,Q.numLightProbes=A,D.directionalLength=k,D.pointLength=I,D.spotLength=R,D.rectAreaLength=q,D.hemiLength=Z,D.numDirectionalShadows=_,D.numPointShadows=P,D.numSpotShadows=L,D.numSpotMaps=B,D.numLightProbes=A,Q.version=Cw++}function N(Y,G){let O=0,E=0,k=0,I=0,R=0,q=G.matrixWorldInverse;for(let Z=0,_=Y.length;Z<_;Z++){let P=Y[Z];if(P.isDirectionalLight){let L=Q.directional[O];L.direction.setFromMatrixPosition(P.matrixWorld),W.setFromMatrixPosition(P.target.matrixWorld),L.direction.sub(W),L.direction.transformDirection(q),O++}else if(P.isSpotLight){let L=Q.spot[k];L.position.setFromMatrixPosition(P.matrixWorld),L.position.applyMatrix4(q),L.direction.setFromMatrixPosition(P.matrixWorld),W.setFromMatrixPosition(P.target.matrixWorld),L.direction.sub(W),L.direction.transformDirection(q),k++}else if(P.isRectAreaLight){let L=Q.rectArea[I];L.position.setFromMatrixPosition(P.matrixWorld),L.position.applyMatrix4(q),X.identity(),K.copy(P.matrixWorld),K.premultiply(q),X.extractRotation(K),L.halfWidth.set(P.width*0.5,0,0),L.halfHeight.set(0,P.height*0.5,0),L.halfWidth.applyMatrix4(X),L.halfHeight.applyMatrix4(X),I++}else if(P.isPointLight){let L=Q.point[E];L.position.setFromMatrixPosition(P.matrixWorld),L.position.applyMatrix4(q),E++}else if(P.isHemisphereLight){let L=Q.hemi[R];L.direction.setFromMatrixPosition(P.matrixWorld),L.direction.transformDirection(q),R++}}}return{setup:H,setupView:N,state:Q}}function MZ($){let U=new Tw($),J=[],Q=[],W=[];function K(E){O.camera=E,J.length=0,Q.length=0,W.length=0}function X(E){J.push(E)}function H(E){Q.push(E)}function N(E){W.push(E)}function Y(){U.setup(J)}function G(E){U.setupView(J,E)}let O={lightsArray:J,shadowsArray:Q,lightProbeGridArray:W,camera:null,lights:U,transmissionRenderTarget:{},textureUnits:0};return{init:K,state:O,setupLights:Y,setupLightsView:G,pushLight:X,pushShadow:H,pushLightProbeGrid:N}}function vw($){let U=new WeakMap;function J(W,K=0){let X=U.get(W),H;if(X===void 0)H=new MZ($),U.set(W,[H]);else if(K>=X.length)H=new MZ($),X.push(H);else H=X[K];return H}function Q(){U=new WeakMap}return{get:J,dispose:Q}}var jw=`void main() {+Program Info Log: `+H+`+`+se+`+`+me)}else if(H!=="")Me("WebGLProgram: Program Info Log:",H);else if(V===""||U==="")Q=!1;if(Q)C.diagnostics={runnable:K,programLog:H,vertexShader:{log:V,prefix:p},fragmentShader:{log:U,prefix:m}}}r.deleteShader(w),r.deleteShader(E),_=new Bs(r,b),S=zS(r,b)}let _;this.getUniforms=function(){if(_===void 0)R(this);return _};let S;this.getAttributes=function(){if(S===void 0)R(this);return S};let F=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){if(F===!1)F=r.getProgramParameter(b,RS);return F},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(b),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=CS++,this.cacheKey=t,this.usedTimes=1,this.program=b,this.vertexShader=w,this.fragmentShader=E,this}var eM=0;class Pd{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,n){let i=this._getShaderCacheForMaterial(e);if(i.has(t)===!1)i.add(t),t.usedTimes++;if(i.has(n)===!1)i.add(n),n.usedTimes++;return this}remove(e){let t=this.materialCache.get(e);for(let n of t)if(n.usedTimes--,n.usedTimes===0)this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);if(n===void 0)n=new Set,t.set(e,n);return n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);if(n===void 0)n=new Id(e),t.set(e,n);return n}}class Id{constructor(e){this.id=eM++,this.code=e,this.usedTimes=0}}function tM(e){return e===or||e===Wo||e===$o}function nM(e,t,n,i,r,s){let o=new jo,a=new Pd,c=new Set,l=[],u=new Map,{logarithmicDepthBuffer:f,precision:h}=i,d={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(_){if(c.add(_),_===0)return"uv";return`uv${_}`}function b(_,S,F,C,z,J){let O=C.fog,H=z.geometry,V=_.isMeshStandardMaterial||_.isMeshLambertMaterial||_.isMeshPhongMaterial?C.environment:null,U=_.isMeshStandardMaterial||_.isMeshLambertMaterial&&!_.envMap||_.isMeshPhongMaterial&&!_.envMap,K=t.get(_.envMap||V,U),Q=!!K&&K.mapping===ys?K.image.height:null,se=d[_.type];if(_.precision!==null){if(h=i.getMaxPrecision(_.precision),h!==_.precision)Me("WebGLProgram.getParameters:",_.precision,"not supported, using",h,"instead.")}let me=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,_e=me!==void 0?me.length:0,Xe=0;if(H.morphAttributes.position!==void 0)Xe=1;if(H.morphAttributes.normal!==void 0)Xe=2;if(H.morphAttributes.color!==void 0)Xe=3;let Be,Z,ne,fe;if(se){let Oe=qn[se];Be=Oe.vertexShader,Z=Oe.fragmentShader}else{Be=_.vertexShader,Z=_.fragmentShader;let Oe=a.getVertexShaderStage(_),yt=a.getFragmentShaderStage(_);a.update(_,Oe,yt),ne=Oe.id,fe=yt.id}let de=e.getRenderTarget(),Re=e.state.buffers.depth.getReversed(),$e=z.isInstancedMesh===!0,Ue=z.isBatchedMesh===!0,ze=!!_.map,Je=!!_.matcap,qe=!!K,je=!!_.aoMap,Ut=!!_.lightMap,pn=!!_.bumpMap&&_.wireframe===!1,pt=!!_.normalMap,Gt=!!_.displacementMap,Ot=!!_.emissiveMap,Ct=!!_.metalnessMap,L=!!_.roughnessMap,mn=_.anisotropy>0,tt=_.clearcoat>0,mt=_.dispersion>0,M=_.iridescence>0,x=_.sheen>0,P=_.transmission>0,W=mn&&!!_.anisotropyMap,te=tt&&!!_.clearcoatMap,ie=tt&&!!_.clearcoatNormalMap,le=tt&&!!_.clearcoatRoughnessMap,X=M&&!!_.iridescenceMap,j=M&&!!_.iridescenceThicknessMap,xe=x&&!!_.sheenColorMap,we=x&&!!_.sheenRoughnessMap,ue=!!_.specularMap,re=!!_.specularColorMap,Ce=!!_.specularIntensityMap,Ie=P&&!!_.transmissionMap,Qe=P&&!!_.thicknessMap,I=!!_.gradientMap,oe=!!_.alphaMap,Y=_.alphaTest>0,ae=!!_.alphaHash,ve=!!_.extensions,ee=Pn;if(_.toneMapped){if(de===null||de.isXRRenderTarget===!0)ee=e.toneMapping}let ce={shaderID:se,shaderType:_.type,shaderName:_.name,vertexShader:Be,fragmentShader:Z,defines:_.defines,customVertexShaderID:ne,customFragmentShaderID:fe,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:h,batching:Ue,batchingColor:Ue&&z._colorsTexture!==null,instancing:$e,instancingColor:$e&&z.instanceColor!==null,instancingMorph:$e&&z.morphTexture!==null,outputColorSpace:de===null?e.outputColorSpace:de.isXRRenderTarget===!0?de.texture.colorSpace:Ve.workingColorSpace,alphaToCoverage:!!_.alphaToCoverage,map:ze,matcap:Je,envMap:qe,envMapMode:qe&&K.mapping,envMapCubeUVHeight:Q,aoMap:je,lightMap:Ut,bumpMap:pn,normalMap:pt,displacementMap:Gt,emissiveMap:Ot,normalMapObjectSpace:pt&&_.normalMapType===Df,normalMapTangentSpace:pt&&_.normalMapType===ml,packedNormalMap:pt&&_.normalMapType===ml&&tM(_.normalMap.format),metalnessMap:Ct,roughnessMap:L,anisotropy:mn,anisotropyMap:W,clearcoat:tt,clearcoatMap:te,clearcoatNormalMap:ie,clearcoatRoughnessMap:le,dispersion:mt,iridescence:M,iridescenceMap:X,iridescenceThicknessMap:j,sheen:x,sheenColorMap:xe,sheenRoughnessMap:we,specularMap:ue,specularColorMap:re,specularIntensityMap:Ce,transmission:P,transmissionMap:Ie,thicknessMap:Qe,gradientMap:I,opaque:_.transparent===!1&&_.blending===xs&&_.alphaToCoverage===!1,alphaMap:oe,alphaTest:Y,alphaHash:ae,combine:_.combine,mapUv:ze&&g(_.map.channel),aoMapUv:je&&g(_.aoMap.channel),lightMapUv:Ut&&g(_.lightMap.channel),bumpMapUv:pn&&g(_.bumpMap.channel),normalMapUv:pt&&g(_.normalMap.channel),displacementMapUv:Gt&&g(_.displacementMap.channel),emissiveMapUv:Ot&&g(_.emissiveMap.channel),metalnessMapUv:Ct&&g(_.metalnessMap.channel),roughnessMapUv:L&&g(_.roughnessMap.channel),anisotropyMapUv:W&&g(_.anisotropyMap.channel),clearcoatMapUv:te&&g(_.clearcoatMap.channel),clearcoatNormalMapUv:ie&&g(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:le&&g(_.clearcoatRoughnessMap.channel),iridescenceMapUv:X&&g(_.iridescenceMap.channel),iridescenceThicknessMapUv:j&&g(_.iridescenceThicknessMap.channel),sheenColorMapUv:xe&&g(_.sheenColorMap.channel),sheenRoughnessMapUv:we&&g(_.sheenRoughnessMap.channel),specularMapUv:ue&&g(_.specularMap.channel),specularColorMapUv:re&&g(_.specularColorMap.channel),specularIntensityMapUv:Ce&&g(_.specularIntensityMap.channel),transmissionMapUv:Ie&&g(_.transmissionMap.channel),thicknessMapUv:Qe&&g(_.thicknessMap.channel),alphaMapUv:oe&&g(_.alphaMap.channel),vertexTangents:!!H.attributes.tangent&&(pt||mn),vertexNormals:!!H.attributes.normal,vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,pointsUvs:z.isPoints===!0&&!!H.attributes.uv&&(ze||oe),fog:!!O,useFog:_.fog===!0,fogExp2:!!O&&O.isFogExp2,flatShading:_.wireframe===!1&&(_.flatShading===!0||H.attributes.normal===void 0&&pt===!1&&(_.isMeshLambertMaterial||_.isMeshPhongMaterial||_.isMeshStandardMaterial||_.isMeshPhysicalMaterial)),sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:f,reversedDepthBuffer:Re,skinning:z.isSkinnedMesh===!0,hasPositionAttribute:H.attributes.position!==void 0,morphTargets:H.morphAttributes.position!==void 0,morphNormals:H.morphAttributes.normal!==void 0,morphColors:H.morphAttributes.color!==void 0,morphTargetsCount:_e,morphTextureStride:Xe,numDirLights:S.directional.length,numPointLights:S.point.length,numSpotLights:S.spot.length,numSpotLightMaps:S.spotLightMap.length,numRectAreaLights:S.rectArea.length,numHemiLights:S.hemi.length,numDirLightShadows:S.directionalShadowMap.length,numPointLightShadows:S.pointShadowMap.length,numSpotLightShadows:S.spotShadowMap.length,numSpotLightShadowsWithMaps:S.numSpotLightShadowsWithMaps,numLightProbes:S.numLightProbes,numLightProbeGrids:J.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:_.dithering,shadowMapEnabled:e.shadowMap.enabled&&F.length>0,shadowMapType:e.shadowMap.type,toneMapping:ee,decodeVideoTexture:ze&&_.map.isVideoTexture===!0&&Ve.getTransfer(_.map.colorSpace)===ut,decodeVideoTextureEmissive:Ot&&_.emissiveMap.isVideoTexture===!0&&Ve.getTransfer(_.emissiveMap.colorSpace)===ut,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===vn,flipSided:_.side===Xt,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionClipCullDistance:ve&&_.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ve&&_.extensions.multiDraw===!0||Ue)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()};return ce.vertexUv1s=c.has(1),ce.vertexUv2s=c.has(2),ce.vertexUv3s=c.has(3),c.clear(),ce}function p(_){let S=[];if(_.shaderID)S.push(_.shaderID);else S.push(_.customVertexShaderID),S.push(_.customFragmentShaderID);if(_.defines!==void 0)for(let F in _.defines)S.push(F),S.push(_.defines[F]);if(_.isRawShaderMaterial===!1)m(S,_),A(S,_),S.push(e.outputColorSpace);return S.push(_.customProgramCacheKey),S.join()}function m(_,S){_.push(S.precision),_.push(S.outputColorSpace),_.push(S.envMapMode),_.push(S.envMapCubeUVHeight),_.push(S.mapUv),_.push(S.alphaMapUv),_.push(S.lightMapUv),_.push(S.aoMapUv),_.push(S.bumpMapUv),_.push(S.normalMapUv),_.push(S.displacementMapUv),_.push(S.emissiveMapUv),_.push(S.metalnessMapUv),_.push(S.roughnessMapUv),_.push(S.anisotropyMapUv),_.push(S.clearcoatMapUv),_.push(S.clearcoatNormalMapUv),_.push(S.clearcoatRoughnessMapUv),_.push(S.iridescenceMapUv),_.push(S.iridescenceThicknessMapUv),_.push(S.sheenColorMapUv),_.push(S.sheenRoughnessMapUv),_.push(S.specularMapUv),_.push(S.specularColorMapUv),_.push(S.specularIntensityMapUv),_.push(S.transmissionMapUv),_.push(S.thicknessMapUv),_.push(S.combine),_.push(S.fogExp2),_.push(S.sizeAttenuation),_.push(S.morphTargetsCount),_.push(S.morphAttributeCount),_.push(S.numDirLights),_.push(S.numPointLights),_.push(S.numSpotLights),_.push(S.numSpotLightMaps),_.push(S.numHemiLights),_.push(S.numRectAreaLights),_.push(S.numDirLightShadows),_.push(S.numPointLightShadows),_.push(S.numSpotLightShadows),_.push(S.numSpotLightShadowsWithMaps),_.push(S.numLightProbes),_.push(S.shadowMapType),_.push(S.toneMapping),_.push(S.numClippingPlanes),_.push(S.numClipIntersection),_.push(S.depthPacking)}function A(_,S){if(o.disableAll(),S.instancing)o.enable(0);if(S.instancingColor)o.enable(1);if(S.instancingMorph)o.enable(2);if(S.matcap)o.enable(3);if(S.envMap)o.enable(4);if(S.normalMapObjectSpace)o.enable(5);if(S.normalMapTangentSpace)o.enable(6);if(S.clearcoat)o.enable(7);if(S.iridescence)o.enable(8);if(S.alphaTest)o.enable(9);if(S.vertexColors)o.enable(10);if(S.vertexAlphas)o.enable(11);if(S.vertexUv1s)o.enable(12);if(S.vertexUv2s)o.enable(13);if(S.vertexUv3s)o.enable(14);if(S.vertexTangents)o.enable(15);if(S.anisotropy)o.enable(16);if(S.alphaHash)o.enable(17);if(S.batching)o.enable(18);if(S.dispersion)o.enable(19);if(S.batchingColor)o.enable(20);if(S.gradientMap)o.enable(21);if(S.packedNormalMap)o.enable(22);if(S.vertexNormals)o.enable(23);if(_.push(o.mask),o.disableAll(),S.fog)o.enable(0);if(S.useFog)o.enable(1);if(S.flatShading)o.enable(2);if(S.logarithmicDepthBuffer)o.enable(3);if(S.reversedDepthBuffer)o.enable(4);if(S.skinning)o.enable(5);if(S.morphTargets)o.enable(6);if(S.morphNormals)o.enable(7);if(S.morphColors)o.enable(8);if(S.premultipliedAlpha)o.enable(9);if(S.shadowMapEnabled)o.enable(10);if(S.doubleSided)o.enable(11);if(S.flipSided)o.enable(12);if(S.useDepthPacking)o.enable(13);if(S.dithering)o.enable(14);if(S.transmission)o.enable(15);if(S.sheen)o.enable(16);if(S.opaque)o.enable(17);if(S.pointsUvs)o.enable(18);if(S.decodeVideoTexture)o.enable(19);if(S.decodeVideoTextureEmissive)o.enable(20);if(S.alphaToCoverage)o.enable(21);if(S.numLightProbeGrids>0)o.enable(22);if(S.hasPositionAttribute)o.enable(23);_.push(o.mask)}function T(_){let S=d[_.type],F;if(S){let C=qn[S];F=Zf.clone(C.uniforms)}else F=_.uniforms;return F}function v(_,S){let F=u.get(S);if(F!==void 0)++F.usedTimes;else F=new QS(e,S,_,r),l.push(F),u.set(S,F);return F}function w(_){if(--_.usedTimes===0){let S=l.indexOf(_);l[S]=l[l.length-1],l.pop(),u.delete(_.cacheKey),_.destroy()}}function E(_){a.remove(_)}function R(){a.dispose()}return{getParameters:b,getProgramCacheKey:p,getUniforms:T,acquireProgram:v,releaseProgram:w,releaseShaderCache:E,programs:l,dispose:R}}function iM(){let e=new WeakMap;function t(o){return e.has(o)}function n(o){let a=e.get(o);if(a===void 0)a={},e.set(o,a);return a}function i(o){e.delete(o)}function r(o,a,c){e.get(o)[a]=c}function s(){e=new WeakMap}return{has:t,get:n,remove:i,update:r,dispose:s}}function rM(e,t){if(e.groupOrder!==t.groupOrder)return e.groupOrder-t.groupOrder;else if(e.renderOrder!==t.renderOrder)return e.renderOrder-t.renderOrder;else if(e.material.id!==t.material.id)return e.material.id-t.material.id;else if(e.materialVariant!==t.materialVariant)return e.materialVariant-t.materialVariant;else if(e.z!==t.z)return e.z-t.z;else return e.id-t.id}function _d(e,t){if(e.groupOrder!==t.groupOrder)return e.groupOrder-t.groupOrder;else if(e.renderOrder!==t.renderOrder)return e.renderOrder-t.renderOrder;else if(e.z!==t.z)return t.z-e.z;else return e.id-t.id}function xd(){let e=[],t=0,n=[],i=[],r=[];function s(){t=0,n.length=0,i.length=0,r.length=0}function o(h){let d=0;if(h.isInstancedMesh)d+=2;if(h.isSkinnedMesh)d+=1;return d}function a(h,d,g,b,p,m){let A=e[t];if(A===void 0)A={id:h.id,object:h,geometry:d,material:g,materialVariant:o(h),groupOrder:b,renderOrder:h.renderOrder,z:p,group:m},e[t]=A;else A.id=h.id,A.object=h,A.geometry=d,A.material=g,A.materialVariant=o(h),A.groupOrder=b,A.renderOrder=h.renderOrder,A.z=p,A.group=m;return t++,A}function c(h,d,g,b,p,m){let A=a(h,d,g,b,p,m);if(g.transmission>0)i.push(A);else if(g.transparent===!0)r.push(A);else n.push(A)}function l(h,d,g,b,p,m){let A=a(h,d,g,b,p,m);if(g.transmission>0)i.unshift(A);else if(g.transparent===!0)r.unshift(A);else n.unshift(A)}function u(h,d,g){if(n.length>1)n.sort(h||rM);if(i.length>1)i.sort(d||_d);if(r.length>1)r.sort(d||_d);if(g)n.reverse(),i.reverse(),r.reverse()}function f(){for(let h=t,d=e.length;h<d;h++){let g=e[h];if(g.id===null)break;g.id=null,g.object=null,g.geometry=null,g.material=null,g.group=null}}return{opaque:n,transmissive:i,transparent:r,init:s,push:c,unshift:l,finish:f,sort:u}}function sM(){let e=new WeakMap;function t(i,r){let s=e.get(i),o;if(s===void 0)o=new xd,e.set(i,[o]);else if(r>=s.length)o=new xd,s.push(o);else o=s[r];return o}function n(){e=new WeakMap}return{get:t,dispose:n}}function oM(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new N,color:new Le};break;case"SpotLight":n={position:new N,direction:new N,color:new Le,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new N,color:new Le,distance:0,decay:0};break;case"HemisphereLight":n={direction:new N,skyColor:new Le,groundColor:new Le};break;case"RectAreaLight":n={color:new Le,position:new N,halfWidth:new N,halfHeight:new N};break}return e[t.id]=n,n}}}function aM(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Pe};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Pe};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Pe,shadowCameraNear:1,shadowCameraFar:1000};break}return e[t.id]=n,n}}}var cM=0;function lM(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function uM(e){let t=new oM,n=aM(),i={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 l=0;l<9;l++)i.probe.push(new N);let r=new N,s=new Fe,o=new Fe;function a(l){let u=0,f=0,h=0;for(let S=0;S<9;S++)i.probe[S].set(0,0,0);let d=0,g=0,b=0,p=0,m=0,A=0,T=0,v=0,w=0,E=0,R=0;l.sort(lM);for(let S=0,F=l.length;S<F;S++){let C=l[S],{color:z,intensity:J,distance:O}=C,H=null;if(C.shadow&&C.shadow.map)if(C.shadow.map.texture.format===or)H=C.shadow.map.texture;else H=C.shadow.map.depthTexture||C.shadow.map.texture;if(C.isAmbientLight)u+=z.r*J,f+=z.g*J,h+=z.b*J;else if(C.isLightProbe){for(let V=0;V<9;V++)i.probe[V].addScaledVector(C.sh.coefficients[V],J);R++}else if(C.isDirectionalLight){let V=t.get(C);if(V.color.copy(C.color).multiplyScalar(C.intensity),C.castShadow){let U=C.shadow,K=n.get(C);K.shadowIntensity=U.intensity,K.shadowBias=U.bias,K.shadowNormalBias=U.normalBias,K.shadowRadius=U.radius,K.shadowMapSize=U.mapSize,i.directionalShadow[d]=K,i.directionalShadowMap[d]=H,i.directionalShadowMatrix[d]=C.shadow.matrix,A++}i.directional[d]=V,d++}else if(C.isSpotLight){let V=t.get(C);V.position.setFromMatrixPosition(C.matrixWorld),V.color.copy(z).multiplyScalar(J),V.distance=O,V.coneCos=Math.cos(C.angle),V.penumbraCos=Math.cos(C.angle*(1-C.penumbra)),V.decay=C.decay,i.spot[b]=V;let U=C.shadow;if(C.map){if(i.spotLightMap[w]=C.map,w++,U.updateMatrices(C),C.castShadow)E++}if(i.spotLightMatrix[b]=U.matrix,C.castShadow){let K=n.get(C);K.shadowIntensity=U.intensity,K.shadowBias=U.bias,K.shadowNormalBias=U.normalBias,K.shadowRadius=U.radius,K.shadowMapSize=U.mapSize,i.spotShadow[b]=K,i.spotShadowMap[b]=H,v++}b++}else if(C.isRectAreaLight){let V=t.get(C);V.color.copy(z).multiplyScalar(J),V.halfWidth.set(C.width*0.5,0,0),V.halfHeight.set(0,C.height*0.5,0),i.rectArea[p]=V,p++}else if(C.isPointLight){let V=t.get(C);if(V.color.copy(C.color).multiplyScalar(C.intensity),V.distance=C.distance,V.decay=C.decay,C.castShadow){let U=C.shadow,K=n.get(C);K.shadowIntensity=U.intensity,K.shadowBias=U.bias,K.shadowNormalBias=U.normalBias,K.shadowRadius=U.radius,K.shadowMapSize=U.mapSize,K.shadowCameraNear=U.camera.near,K.shadowCameraFar=U.camera.far,i.pointShadow[g]=K,i.pointShadowMap[g]=H,i.pointShadowMatrix[g]=C.shadow.matrix,T++}i.point[g]=V,g++}else if(C.isHemisphereLight){let V=t.get(C);V.skyColor.copy(C.color).multiplyScalar(J),V.groundColor.copy(C.groundColor).multiplyScalar(J),i.hemi[m]=V,m++}}if(p>0)if(e.has("OES_texture_float_linear")===!0)i.rectAreaLTC1=he.LTC_FLOAT_1,i.rectAreaLTC2=he.LTC_FLOAT_2;else i.rectAreaLTC1=he.LTC_HALF_1,i.rectAreaLTC2=he.LTC_HALF_2;i.ambient[0]=u,i.ambient[1]=f,i.ambient[2]=h;let _=i.hash;if(_.directionalLength!==d||_.pointLength!==g||_.spotLength!==b||_.rectAreaLength!==p||_.hemiLength!==m||_.numDirectionalShadows!==A||_.numPointShadows!==T||_.numSpotShadows!==v||_.numSpotMaps!==w||_.numLightProbes!==R)i.directional.length=d,i.spot.length=b,i.rectArea.length=p,i.point.length=g,i.hemi.length=m,i.directionalShadow.length=A,i.directionalShadowMap.length=A,i.pointShadow.length=T,i.pointShadowMap.length=T,i.spotShadow.length=v,i.spotShadowMap.length=v,i.directionalShadowMatrix.length=A,i.pointShadowMatrix.length=T,i.spotLightMatrix.length=v+w-E,i.spotLightMap.length=w,i.numSpotLightShadowsWithMaps=E,i.numLightProbes=R,_.directionalLength=d,_.pointLength=g,_.spotLength=b,_.rectAreaLength=p,_.hemiLength=m,_.numDirectionalShadows=A,_.numPointShadows=T,_.numSpotShadows=v,_.numSpotMaps=w,_.numLightProbes=R,i.version=cM++}function c(l,u){let f=0,h=0,d=0,g=0,b=0,p=u.matrixWorldInverse;for(let m=0,A=l.length;m<A;m++){let T=l[m];if(T.isDirectionalLight){let v=i.directional[f];v.direction.setFromMatrixPosition(T.matrixWorld),r.setFromMatrixPosition(T.target.matrixWorld),v.direction.sub(r),v.direction.transformDirection(p),f++}else if(T.isSpotLight){let v=i.spot[d];v.position.setFromMatrixPosition(T.matrixWorld),v.position.applyMatrix4(p),v.direction.setFromMatrixPosition(T.matrixWorld),r.setFromMatrixPosition(T.target.matrixWorld),v.direction.sub(r),v.direction.transformDirection(p),d++}else if(T.isRectAreaLight){let v=i.rectArea[g];v.position.setFromMatrixPosition(T.matrixWorld),v.position.applyMatrix4(p),o.identity(),s.copy(T.matrixWorld),s.premultiply(p),o.extractRotation(s),v.halfWidth.set(T.width*0.5,0,0),v.halfHeight.set(0,T.height*0.5,0),v.halfWidth.applyMatrix4(o),v.halfHeight.applyMatrix4(o),g++}else if(T.isPointLight){let v=i.point[h];v.position.setFromMatrixPosition(T.matrixWorld),v.position.applyMatrix4(p),h++}else if(T.isHemisphereLight){let v=i.hemi[b];v.direction.setFromMatrixPosition(T.matrixWorld),v.direction.transformDirection(p),b++}}}return{setup:a,setupView:c,state:i}}function vd(e){let t=new uM(e),n=[],i=[],r=[];function s(h){f.camera=h,n.length=0,i.length=0,r.length=0}function o(h){n.push(h)}function a(h){i.push(h)}function c(h){r.push(h)}function l(){t.setup(n)}function u(h){t.setupView(n,h)}let f={lightsArray:n,shadowsArray:i,lightProbeGridArray:r,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:f,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:a,pushLightProbeGrid:c}}function hM(e){let t=new WeakMap;function n(r,s=0){let o=t.get(r),a;if(o===void 0)a=new vd(e),t.set(r,[a]);else if(s>=o.length)a=new vd(e),o.push(a);else a=o[s];return a}function i(){t=new WeakMap}return{get:n,dispose:i}}var fM=`void main() {gl_Position = vec4( position, 1.0 );-}`,gw=`uniform sampler2D shadow_pass;+}`,dM=`uniform sampler2D shadow_pass;uniform vec2 resolution;uniform float radius;void main() {@@ -4199,12 +4199,12 @@ void main() {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 );-}`,bw=[new j(1,0,0),new j(-1,0,0),new j(0,1,0),new j(0,-1,0),new j(0,0,1),new j(0,0,-1)],yw=[new j(0,-1,0),new j(0,-1,0),new j(0,0,1),new j(0,0,-1),new j(0,-1,0),new j(0,-1,0)],BZ=new m$,lW=new j,SH=new j;function xw($,U,J){let Q=new jW,W=new g$,K=new g$,X=new E6,H=new GH,N=new OH,Y={},G=J.maxTextureSize,O={[oJ]:$U,[$U]:oJ,[vU]:vU},E=new gU({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new g$},radius:{value:4}},vertexShader:jw,fragmentShader:gw}),k=E.clone();k.defines.HORIZONTAL_PASS=1;let I=new KU;I.setAttribute("position",new h6(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));let R=new B6(I,E),q=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=RW;let Z=this.type;this.render=function(z,A,D){if(q.enabled===!1)return;if(q.autoUpdate===!1&&q.needsUpdate===!1)return;if(z.length===0)return;if(this.type===$q)A$("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=RW;let w=$.getRenderTarget(),h=$.getActiveCubeFace(),C=$.getActiveMipmapLevel(),f=$.state;if(f.setBlending(JJ),f.buffers.depth.getReversed()===!0)f.buffers.color.setClear(0,0,0,0);else f.buffers.color.setClear(1,1,1,1);f.buffers.depth.setTest(!0),f.setScissorTest(!1);let s=Z!==this.type;if(s)A.traverse(function(x){if(x.material)if(Array.isArray(x.material))x.material.forEach((d)=>d.needsUpdate=!0);else x.material.needsUpdate=!0});for(let x=0,d=z.length;x<d;x++){let c=z[x],y=c.shadow;if(y===void 0){A$("WebGLShadowMap:",c,"has no shadow.");continue}if(y.autoUpdate===!1&&y.needsUpdate===!1)continue;W.copy(y.mapSize);let t=y.getFrameExtents();if(W.multiply(t),K.copy(y.mapSize),W.x>G||W.y>G){if(W.x>G)K.x=Math.floor(G/t.x),W.x=K.x*t.x,y.mapSize.x=K.x;if(W.y>G)K.y=Math.floor(G/t.y),W.y=K.y*t.y,y.mapSize.y=K.y}let e=$.state.buffers.depth.getReversed();if(y.camera._reversedDepth=e,y.map===null||s===!0){if(y.map!==null){if(y.map.depthTexture!==null)y.map.depthTexture.dispose(),y.map.depthTexture=null;y.map.dispose()}if(this.type===k8){if(c.isPointLight){A$("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}y.map=new jU(W.x,W.y,{format:S0,type:CJ,minFilter:n6,magFilter:n6,generateMipmaps:!1}),y.map.texture.name=c.name+".shadowMap",y.map.depthTexture=new eJ(W.x,W.y,AJ),y.map.depthTexture.name=c.name+".shadowMapDepth",y.map.depthTexture.format=A0,y.map.depthTexture.compareFunction=null,y.map.depthTexture.minFilter=cU,y.map.depthTexture.magFilter=cU}else{if(c.isPointLight)y.map=new jH(W.x),y.map.depthTexture=new HH(W.x,rJ);else y.map=new jU(W.x,W.y),y.map.depthTexture=new eJ(W.x,W.y,rJ);if(y.map.depthTexture.name=c.name+".shadowMap",y.map.depthTexture.format=A0,this.type===RW)y.map.depthTexture.compareFunction=e?V9:R9,y.map.depthTexture.minFilter=n6,y.map.depthTexture.magFilter=n6;else y.map.depthTexture.compareFunction=null,y.map.depthTexture.minFilter=cU,y.map.depthTexture.magFilter=cU}y.camera.updateProjectionMatrix()}let Y$=y.map.isWebGLCubeRenderTarget?6:1;for(let R$=0;R$<Y$;R$++){if(y.map.isWebGLCubeRenderTarget)$.setRenderTarget(y.map,R$),$.clear();else{if(R$===0)$.setRenderTarget(y.map),$.clear();let w$=y.getViewport(R$);X.set(K.x*w$.x,K.y*w$.y,K.x*w$.z,K.y*w$.w),f.viewport(X)}if(c.isPointLight){let{camera:w$,matrix:$6}=y,n$=c.distance||w$.far;if(n$!==w$.far)w$.far=n$,w$.updateProjectionMatrix();lW.setFromMatrixPosition(c.matrixWorld),w$.position.copy(lW),SH.copy(w$.position),SH.add(bw[R$]),w$.up.copy(yw[R$]),w$.lookAt(SH),w$.updateMatrixWorld(),$6.makeTranslation(-lW.x,-lW.y,-lW.z),BZ.multiplyMatrices(w$.projectionMatrix,w$.matrixWorldInverse),y._frustum.setFromProjectionMatrix(BZ,w$.coordinateSystem,w$.reversedDepth)}else y.updateMatrices(c);Q=y.getFrustum(),L(A,D,y.camera,c,this.type)}if(y.isPointLightShadow!==!0&&this.type===k8)_(y,D);y.needsUpdate=!1}Z=this.type,q.needsUpdate=!1,$.setRenderTarget(w,h,C)};function _(z,A){let D=U.update(R);if(E.defines.VSM_SAMPLES!==z.blurSamples)E.defines.VSM_SAMPLES=z.blurSamples,k.defines.VSM_SAMPLES=z.blurSamples,E.needsUpdate=!0,k.needsUpdate=!0;if(z.mapPass===null)z.mapPass=new jU(W.x,W.y,{format:S0,type:CJ});E.uniforms.shadow_pass.value=z.map.depthTexture,E.uniforms.resolution.value=z.mapSize,E.uniforms.radius.value=z.radius,$.setRenderTarget(z.mapPass),$.clear(),$.renderBufferDirect(A,null,D,E,R,null),k.uniforms.shadow_pass.value=z.mapPass.texture,k.uniforms.resolution.value=z.mapSize,k.uniforms.radius.value=z.radius,$.setRenderTarget(z.map),$.clear(),$.renderBufferDirect(A,null,D,k,R,null)}function P(z,A,D,w){let h=null,C=D.isPointLight===!0?z.customDistanceMaterial:z.customDepthMaterial;if(C!==void 0)h=C;else if(h=D.isPointLight===!0?N:H,$.localClippingEnabled&&A.clipShadows===!0&&Array.isArray(A.clippingPlanes)&&A.clippingPlanes.length!==0||A.displacementMap&&A.displacementScale!==0||A.alphaMap&&A.alphaTest>0||A.map&&A.alphaTest>0||A.alphaToCoverage===!0){let f=h.uuid,s=A.uuid,x=Y[f];if(x===void 0)x={},Y[f]=x;let d=x[s];if(d===void 0)d=h.clone(),x[s]=d,A.addEventListener("dispose",B);h=d}if(h.visible=A.visible,h.wireframe=A.wireframe,w===k8)h.side=A.shadowSide!==null?A.shadowSide:A.side;else h.side=A.shadowSide!==null?A.shadowSide:O[A.side];if(h.alphaMap=A.alphaMap,h.alphaTest=A.alphaToCoverage===!0?0.5:A.alphaTest,h.map=A.map,h.clipShadows=A.clipShadows,h.clippingPlanes=A.clippingPlanes,h.clipIntersection=A.clipIntersection,h.displacementMap=A.displacementMap,h.displacementScale=A.displacementScale,h.displacementBias=A.displacementBias,h.wireframeLinewidth=A.wireframeLinewidth,h.linewidth=A.linewidth,D.isPointLight===!0&&h.isMeshDistanceMaterial===!0){let f=$.properties.get(h);f.light=D}return h}function L(z,A,D,w,h){if(z.visible===!1)return;if(z.layers.test(A.layers)&&(z.isMesh||z.isLine||z.isPoints)){if((z.castShadow||z.receiveShadow&&h===k8)&&(!z.frustumCulled||Q.intersectsObject(z))){z.modelViewMatrix.multiplyMatrices(D.matrixWorldInverse,z.matrixWorld);let s=U.update(z),x=z.material;if(Array.isArray(x)){let d=s.groups;for(let c=0,y=d.length;c<y;c++){let t=d[c],e=x[t.materialIndex];if(e&&e.visible){let Y$=P(z,e,w,h);z.onBeforeShadow($,z,A,D,s,Y$,t),$.renderBufferDirect(D,null,s,Y$,z,t),z.onAfterShadow($,z,A,D,s,Y$,t)}}}else if(x.visible){let d=P(z,x,w,h);z.onBeforeShadow($,z,A,D,s,d,null),$.renderBufferDirect(D,null,s,d,z,null),z.onAfterShadow($,z,A,D,s,d,null)}}}let f=z.children;for(let s=0,x=f.length;s<x;s++)L(f[s],A,D,w,h)}function B(z){z.target.removeEventListener("dispose",B);for(let D in Y){let w=Y[D],h=z.target.uuid;if(h in w)w[h].dispose(),delete w[h]}}}function hw($,U){function J(){let T=!1,G$=new E6,r=null,O$=new E6(0,0,0,0);return{setMask:function(B$){if(r!==B$&&!T)$.colorMask(B$,B$,B$,B$),r=B$},setLocked:function(B$){T=B$},setClear:function(B$,$$,E$,l$,_6){if(_6===!0)B$*=l$,$$*=l$,E$*=l$;if(G$.set(B$,$$,E$,l$),O$.equals(G$)===!1)$.clearColor(B$,$$,E$,l$),O$.copy(G$)},reset:function(){T=!1,r=null,O$.set(-1,0,0,0)}}}function Q(){let T=!1,G$=!1,r=null,O$=null,B$=null;return{setReversed:function($$){if(G$!==$$){let E$=U.get("EXT_clip_control");if($$)E$.clipControlEXT(E$.LOWER_LEFT_EXT,E$.ZERO_TO_ONE_EXT);else E$.clipControlEXT(E$.LOWER_LEFT_EXT,E$.NEGATIVE_ONE_TO_ONE_EXT);G$=$$;let l$=B$;B$=null,this.setClear(l$)}},getReversed:function(){return G$},setTest:function($$){if($$)F$($.DEPTH_TEST);else v$($.DEPTH_TEST)},setMask:function($$){if(r!==$$&&!T)$.depthMask($$),r=$$},setFunc:function($$){if(G$)$$=oq[$$];if(O$!==$$){switch($$){case Vq:$.depthFunc($.NEVER);break;case wq:$.depthFunc($.ALWAYS);break;case Mq:$.depthFunc($.LESS);break;case NX:$.depthFunc($.LEQUAL);break;case Bq:$.depthFunc($.EQUAL);break;case Pq:$.depthFunc($.GEQUAL);break;case zq:$.depthFunc($.GREATER);break;case _q:$.depthFunc($.NOTEQUAL);break;default:$.depthFunc($.LEQUAL)}O$=$$}},setLocked:function($$){T=$$},setClear:function($$){if(B$!==$$){if(B$=$$,G$)$$=1-$$;$.clearDepth($$)}},reset:function(){T=!1,r=null,O$=null,B$=null,G$=!1}}}function W(){let T=!1,G$=null,r=null,O$=null,B$=null,$$=null,E$=null,l$=null,_6=null;return{setTest:function(w6){if(!T)if(w6)F$($.STENCIL_TEST);else v$($.STENCIL_TEST)},setMask:function(w6){if(G$!==w6&&!T)$.stencilMask(w6),G$=w6},setFunc:function(w6,aU,LJ){if(r!==w6||O$!==aU||B$!==LJ)$.stencilFunc(w6,aU,LJ),r=w6,O$=aU,B$=LJ},setOp:function(w6,aU,LJ){if($$!==w6||E$!==aU||l$!==LJ)$.stencilOp(w6,aU,LJ),$$=w6,E$=aU,l$=LJ},setLocked:function(w6){T=w6},setClear:function(w6){if(_6!==w6)$.clearStencil(w6),_6=w6},reset:function(){T=!1,G$=null,r=null,O$=null,B$=null,$$=null,E$=null,l$=null,_6=null}}}let K=new J,X=new Q,H=new W,N=new WeakMap,Y=new WeakMap,G={},O={},E={},k=new WeakMap,I=[],R=null,q=!1,Z=null,_=null,P=null,L=null,B=null,z=null,A=null,D=new y$(0,0,0),w=0,h=!1,C=null,f=null,s=null,x=null,d=null,c=$.getParameter($.MAX_COMBINED_TEXTURE_IMAGE_UNITS),y=!1,t=0,e=$.getParameter($.VERSION);if(e.indexOf("WebGL")!==-1)t=parseFloat(/^WebGL (\d)/.exec(e)[1]),y=t>=1;else if(e.indexOf("OpenGL ES")!==-1)t=parseFloat(/^OpenGL ES (\d)/.exec(e)[1]),y=t>=2;let Y$=null,R$={},w$=$.getParameter($.SCISSOR_BOX),$6=$.getParameter($.VIEWPORT),n$=new E6().fromArray(w$),i=new E6().fromArray($6);function X$(T,G$,r,O$){let B$=new Uint8Array(4),$$=$.createTexture();$.bindTexture(T,$$),$.texParameteri(T,$.TEXTURE_MIN_FILTER,$.NEAREST),$.texParameteri(T,$.TEXTURE_MAG_FILTER,$.NEAREST);for(let E$=0;E$<r;E$++)if(T===$.TEXTURE_3D||T===$.TEXTURE_2D_ARRAY)$.texImage3D(G$,0,$.RGBA,1,1,O$,0,$.RGBA,$.UNSIGNED_BYTE,B$);else $.texImage2D(G$+E$,0,$.RGBA,1,1,0,$.RGBA,$.UNSIGNED_BYTE,B$);return $$}let D$={};D$[$.TEXTURE_2D]=X$($.TEXTURE_2D,$.TEXTURE_2D,1),D$[$.TEXTURE_CUBE_MAP]=X$($.TEXTURE_CUBE_MAP,$.TEXTURE_CUBE_MAP_POSITIVE_X,6),D$[$.TEXTURE_2D_ARRAY]=X$($.TEXTURE_2D_ARRAY,$.TEXTURE_2D_ARRAY,1,1),D$[$.TEXTURE_3D]=X$($.TEXTURE_3D,$.TEXTURE_3D,1,1),K.setClear(0,0,0,1),X.setClear(1),H.setClear(0),F$($.DEPTH_TEST),X.setFunc(NX),_U(!1),P6(QX),F$($.CULL_FACE),Q6(JJ);function F$(T){if(G[T]!==!0)$.enable(T),G[T]=!0}function v$(T){if(G[T]!==!1)$.disable(T),G[T]=!1}function t$(T,G$){if(E[T]!==G$){if($.bindFramebuffer(T,G$),E[T]=G$,T===$.DRAW_FRAMEBUFFER)E[$.FRAMEBUFFER]=G$;if(T===$.FRAMEBUFFER)E[$.DRAW_FRAMEBUFFER]=G$;return!0}return!1}function u$(T,G$){let r=I,O$=!1;if(T){if(r=k.get(G$),r===void 0)r=[],k.set(G$,r);let B$=T.textures;if(r.length!==B$.length||r[0]!==$.COLOR_ATTACHMENT0){for(let $$=0,E$=B$.length;$$<E$;$$++)r[$$]=$.COLOR_ATTACHMENT0+$$;r.length=B$.length,O$=!0}}else if(r[0]!==$.BACK)r[0]=$.BACK,O$=!0;if(O$)$.drawBuffers(r)}function p$(T){if(R!==T)return $.useProgram(T),R=T,!0;return!1}let K6={[q8]:$.FUNC_ADD,[Jq]:$.FUNC_SUBTRACT,[Wq]:$.FUNC_REVERSE_SUBTRACT};K6[Qq]=$.MIN,K6[Kq]=$.MAX;let U6={[Xq]:$.ZERO,[Hq]:$.ONE,[Nq]:$.SRC_COLOR,[Gq]:$.SRC_ALPHA,[Iq]:$.SRC_ALPHA_SATURATE,[qq]:$.DST_COLOR,[Eq]:$.DST_ALPHA,[Yq]:$.ONE_MINUS_SRC_COLOR,[Oq]:$.ONE_MINUS_SRC_ALPHA,[Zq]:$.ONE_MINUS_DST_COLOR,[kq]:$.ONE_MINUS_DST_ALPHA,[Dq]:$.CONSTANT_COLOR,[Fq]:$.ONE_MINUS_CONSTANT_COLOR,[Lq]:$.CONSTANT_ALPHA,[Rq]:$.ONE_MINUS_CONSTANT_ALPHA};function Q6(T,G$,r,O$,B$,$$,E$,l$,_6,w6){if(T===JJ){if(q===!0)v$($.BLEND),q=!1;return}if(q===!1)F$($.BLEND),q=!0;if(T!==Uq){if(T!==Z||w6!==h){if(_!==q8||B!==q8)$.blendEquation($.FUNC_ADD),_=q8,B=q8;if(w6)switch(T){case VW:$.blendFuncSeparate($.ONE,$.ONE_MINUS_SRC_ALPHA,$.ONE,$.ONE_MINUS_SRC_ALPHA);break;case KX:$.blendFunc($.ONE,$.ONE);break;case XX:$.blendFuncSeparate($.ZERO,$.ONE_MINUS_SRC_COLOR,$.ZERO,$.ONE);break;case HX:$.blendFuncSeparate($.DST_COLOR,$.ONE_MINUS_SRC_ALPHA,$.ZERO,$.ONE);break;default:x$("WebGLState: Invalid blending: ",T);break}else switch(T){case VW:$.blendFuncSeparate($.SRC_ALPHA,$.ONE_MINUS_SRC_ALPHA,$.ONE,$.ONE_MINUS_SRC_ALPHA);break;case KX:$.blendFuncSeparate($.SRC_ALPHA,$.ONE,$.ONE,$.ONE);break;case XX:x$("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case HX:x$("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:x$("WebGLState: Invalid blending: ",T);break}P=null,L=null,z=null,A=null,D.set(0,0,0),w=0,Z=T,h=w6}return}if(B$=B$||G$,$$=$$||r,E$=E$||O$,G$!==_||B$!==B)$.blendEquationSeparate(K6[G$],K6[B$]),_=G$,B=B$;if(r!==P||O$!==L||$$!==z||E$!==A)$.blendFuncSeparate(U6[r],U6[O$],U6[$$],U6[E$]),P=r,L=O$,z=$$,A=E$;if(l$.equals(D)===!1||_6!==w)$.blendColor(l$.r,l$.g,l$.b,_6),D.copy(l$),w=_6;Z=T,h=!1}function m6(T,G$){T.side===vU?v$($.CULL_FACE):F$($.CULL_FACE);let r=T.side===$U;if(G$)r=!r;_U(r),T.blending===VW&&T.transparent===!1?Q6(JJ):Q6(T.blending,T.blendEquation,T.blendSrc,T.blendDst,T.blendEquationAlpha,T.blendSrcAlpha,T.blendDstAlpha,T.blendColor,T.blendAlpha,T.premultipliedAlpha),X.setFunc(T.depthFunc),X.setTest(T.depthTest),X.setMask(T.depthWrite),K.setMask(T.colorWrite);let O$=T.stencilWrite;if(H.setTest(O$),O$)H.setMask(T.stencilWriteMask),H.setFunc(T.stencilFunc,T.stencilRef,T.stencilFuncMask),H.setOp(T.stencilFail,T.stencilZFail,T.stencilZPass);p6(T.polygonOffset,T.polygonOffsetFactor,T.polygonOffsetUnits),T.alphaToCoverage===!0?F$($.SAMPLE_ALPHA_TO_COVERAGE):v$($.SAMPLE_ALPHA_TO_COVERAGE)}function _U(T){if(C!==T){if(T)$.frontFace($.CW);else $.frontFace($.CCW);C=T}}function P6(T){if(T!==tk){if(F$($.CULL_FACE),T!==f)if(T===QX)$.cullFace($.BACK);else if(T===ek)$.cullFace($.FRONT);else $.cullFace($.FRONT_AND_BACK)}else v$($.CULL_FACE);f=T}function o6(T){if(T!==s){if(y)$.lineWidth(T);s=T}}function p6(T,G$,r){if(T){if(F$($.POLYGON_OFFSET_FILL),x!==G$||d!==r){if(x=G$,d=r,X.getReversed())G$=-G$;$.polygonOffset(G$,r)}}else v$($.POLYGON_OFFSET_FILL)}function y6(T){if(T)F$($.SCISSOR_TEST);else v$($.SCISSOR_TEST)}function v(T){if(T===void 0)T=$.TEXTURE0+c-1;if(Y$!==T)$.activeTexture(T),Y$=T}function AU(T,G$,r){if(r===void 0)if(Y$===null)r=$.TEXTURE0+c-1;else r=Y$;let O$=R$[r];if(O$===void 0)O$={type:void 0,texture:void 0},R$[r]=O$;if(O$.type!==T||O$.texture!==G$){if(Y$!==r)$.activeTexture(r),Y$=r;$.bindTexture(T,G$||D$[T]),O$.type=T,O$.texture=G$}}function Y6(){let T=R$[Y$];if(T!==void 0&&T.type!==void 0)$.bindTexture(T.type,null),T.type=void 0,T.texture=void 0}function z6(){try{$.compressedTexImage2D(...arguments)}catch(T){x$("WebGLState:",T)}}function M(){try{$.compressedTexImage3D(...arguments)}catch(T){x$("WebGLState:",T)}}function F(){try{$.texSubImage2D(...arguments)}catch(T){x$("WebGLState:",T)}}function S(){try{$.texSubImage3D(...arguments)}catch(T){x$("WebGLState:",T)}}function n(){try{$.compressedTexSubImage2D(...arguments)}catch(T){x$("WebGLState:",T)}}function J$(){try{$.compressedTexSubImage3D(...arguments)}catch(T){x$("WebGLState:",T)}}function H$(){try{$.texStorage2D(...arguments)}catch(T){x$("WebGLState:",T)}}function k$(){try{$.texStorage3D(...arguments)}catch(T){x$("WebGLState:",T)}}function o(){try{$.texImage2D(...arguments)}catch(T){x$("WebGLState:",T)}}function a(){try{$.texImage3D(...arguments)}catch(T){x$("WebGLState:",T)}}function M$(T){if(O[T]!==void 0)return O[T];else return $.getParameter(T)}function C$(T,G$){if(O[T]!==G$)$.pixelStorei(T,G$),O[T]=G$}function q$(T){if(n$.equals(T)===!1)$.scissor(T.x,T.y,T.z,T.w),n$.copy(T)}function N$(T){if(i.equals(T)===!1)$.viewport(T.x,T.y,T.z,T.w),i.copy(T)}function j$(T,G$){let r=Y.get(G$);if(r===void 0)r=new WeakMap,Y.set(G$,r);let O$=r.get(T);if(O$===void 0)O$=$.getUniformBlockIndex(G$,T.name),r.set(T,O$)}function b$(T,G$){let O$=Y.get(G$).get(T);if(N.get(G$)!==O$)$.uniformBlockBinding(G$,O$,T.__bindingPointIndex),N.set(G$,O$)}function H6(){$.disable($.BLEND),$.disable($.CULL_FACE),$.disable($.DEPTH_TEST),$.disable($.POLYGON_OFFSET_FILL),$.disable($.SCISSOR_TEST),$.disable($.STENCIL_TEST),$.disable($.SAMPLE_ALPHA_TO_COVERAGE),$.blendEquation($.FUNC_ADD),$.blendFunc($.ONE,$.ZERO),$.blendFuncSeparate($.ONE,$.ZERO,$.ONE,$.ZERO),$.blendColor(0,0,0,0),$.colorMask(!0,!0,!0,!0),$.clearColor(0,0,0,0),$.depthMask(!0),$.depthFunc($.LESS),X.setReversed(!1),$.clearDepth(1),$.stencilMask(4294967295),$.stencilFunc($.ALWAYS,0,4294967295),$.stencilOp($.KEEP,$.KEEP,$.KEEP),$.clearStencil(0),$.cullFace($.BACK),$.frontFace($.CCW),$.polygonOffset(0,0),$.activeTexture($.TEXTURE0),$.bindFramebuffer($.FRAMEBUFFER,null),$.bindFramebuffer($.DRAW_FRAMEBUFFER,null),$.bindFramebuffer($.READ_FRAMEBUFFER,null),$.useProgram(null),$.lineWidth(1),$.scissor(0,0,$.canvas.width,$.canvas.height),$.viewport(0,0,$.canvas.width,$.canvas.height),$.pixelStorei($.PACK_ALIGNMENT,4),$.pixelStorei($.UNPACK_ALIGNMENT,4),$.pixelStorei($.UNPACK_FLIP_Y_WEBGL,!1),$.pixelStorei($.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),$.pixelStorei($.UNPACK_COLORSPACE_CONVERSION_WEBGL,$.BROWSER_DEFAULT_WEBGL),$.pixelStorei($.PACK_ROW_LENGTH,0),$.pixelStorei($.PACK_SKIP_PIXELS,0),$.pixelStorei($.PACK_SKIP_ROWS,0),$.pixelStorei($.UNPACK_ROW_LENGTH,0),$.pixelStorei($.UNPACK_IMAGE_HEIGHT,0),$.pixelStorei($.UNPACK_SKIP_PIXELS,0),$.pixelStorei($.UNPACK_SKIP_ROWS,0),$.pixelStorei($.UNPACK_SKIP_IMAGES,0),G={},O={},Y$=null,R$={},E={},k=new WeakMap,I=[],R=null,q=!1,Z=null,_=null,P=null,L=null,B=null,z=null,A=null,D=new y$(0,0,0),w=0,h=!1,C=null,f=null,s=null,x=null,d=null,n$.set(0,0,$.canvas.width,$.canvas.height),i.set(0,0,$.canvas.width,$.canvas.height),K.reset(),X.reset(),H.reset()}return{buffers:{color:K,depth:X,stencil:H},enable:F$,disable:v$,bindFramebuffer:t$,drawBuffers:u$,useProgram:p$,setBlending:Q6,setMaterial:m6,setFlipSided:_U,setCullFace:P6,setLineWidth:o6,setPolygonOffset:p6,setScissorTest:y6,activeTexture:v,bindTexture:AU,unbindTexture:Y6,compressedTexImage2D:z6,compressedTexImage3D:M,texImage2D:o,texImage3D:a,pixelStorei:C$,getParameter:M$,updateUBOMapping:j$,uniformBlockBinding:b$,texStorage2D:H$,texStorage3D:k$,texSubImage2D:F,texSubImage3D:S,compressedTexSubImage2D:n,compressedTexSubImage3D:J$,scissor:q$,viewport:N$,reset:H6}}function fw($,U,J,Q,W,K,X){let H=U.has("WEBGL_multisampled_render_to_texture")?U.get("WEBGL_multisampled_render_to_texture"):null,N=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),Y=new g$,G=new WeakMap,O=new Set,E,k=new WeakMap,I=!1;try{I=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch(M){}function R(M,F){return I?new OffscreenCanvas(M,F):G8("canvas")}function q(M,F,S){let n=1,J$=z6(M);if(J$.width>S||J$.height>S)n=S/Math.max(J$.width,J$.height);if(n<1)if(typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&M instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&M instanceof ImageBitmap||typeof VideoFrame<"u"&&M instanceof VideoFrame){let H$=Math.floor(n*J$.width),k$=Math.floor(n*J$.height);if(E===void 0)E=R(H$,k$);let o=F?R(H$,k$):E;return o.width=H$,o.height=k$,o.getContext("2d").drawImage(M,0,0,H$,k$),A$("WebGLRenderer: Texture has been resized from ("+J$.width+"x"+J$.height+") to ("+H$+"x"+k$+")."),o}else{if("data"in M)A$("WebGLRenderer: Image in DataTexture is too big ("+J$.width+"x"+J$.height+").");return M}return M}function Z(M){return M.generateMipmaps}function _(M){$.generateMipmap(M)}function P(M){if(M.isWebGLCubeRenderTarget)return $.TEXTURE_CUBE_MAP;if(M.isWebGL3DRenderTarget)return $.TEXTURE_3D;if(M.isWebGLArrayRenderTarget||M.isCompressedArrayTexture)return $.TEXTURE_2D_ARRAY;return $.TEXTURE_2D}function L(M,F,S,n,J$,H$=!1){if(M!==null){if($[M]!==void 0)return $[M];A$("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+M+"'")}let k$;if(n){if(k$=U.get("EXT_texture_norm16"),!k$)A$("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension")}let o=F;if(F===$.RED){if(S===$.FLOAT)o=$.R32F;if(S===$.HALF_FLOAT)o=$.R16F;if(S===$.UNSIGNED_BYTE)o=$.R8;if(S===$.UNSIGNED_SHORT&&k$)o=k$.R16_EXT;if(S===$.SHORT&&k$)o=k$.R16_SNORM_EXT}if(F===$.RED_INTEGER){if(S===$.UNSIGNED_BYTE)o=$.R8UI;if(S===$.UNSIGNED_SHORT)o=$.R16UI;if(S===$.UNSIGNED_INT)o=$.R32UI;if(S===$.BYTE)o=$.R8I;if(S===$.SHORT)o=$.R16I;if(S===$.INT)o=$.R32I}if(F===$.RG){if(S===$.FLOAT)o=$.RG32F;if(S===$.HALF_FLOAT)o=$.RG16F;if(S===$.UNSIGNED_BYTE)o=$.RG8;if(S===$.UNSIGNED_SHORT&&k$)o=k$.RG16_EXT;if(S===$.SHORT&&k$)o=k$.RG16_SNORM_EXT}if(F===$.RG_INTEGER){if(S===$.UNSIGNED_BYTE)o=$.RG8UI;if(S===$.UNSIGNED_SHORT)o=$.RG16UI;if(S===$.UNSIGNED_INT)o=$.RG32UI;if(S===$.BYTE)o=$.RG8I;if(S===$.SHORT)o=$.RG16I;if(S===$.INT)o=$.RG32I}if(F===$.RGB_INTEGER){if(S===$.UNSIGNED_BYTE)o=$.RGB8UI;if(S===$.UNSIGNED_SHORT)o=$.RGB16UI;if(S===$.UNSIGNED_INT)o=$.RGB32UI;if(S===$.BYTE)o=$.RGB8I;if(S===$.SHORT)o=$.RGB16I;if(S===$.INT)o=$.RGB32I}if(F===$.RGBA_INTEGER){if(S===$.UNSIGNED_BYTE)o=$.RGBA8UI;if(S===$.UNSIGNED_SHORT)o=$.RGBA16UI;if(S===$.UNSIGNED_INT)o=$.RGBA32UI;if(S===$.BYTE)o=$.RGBA8I;if(S===$.SHORT)o=$.RGBA16I;if(S===$.INT)o=$.RGBA32I}if(F===$.RGB){if(S===$.UNSIGNED_SHORT&&k$)o=k$.RGB16_EXT;if(S===$.SHORT&&k$)o=k$.RGB16_SNORM_EXT;if(S===$.UNSIGNED_INT_5_9_9_9_REV)o=$.RGB9_E5;if(S===$.UNSIGNED_INT_10F_11F_11F_REV)o=$.R11F_G11F_B10F}if(F===$.RGBA){let a=H$?$H:r$.getTransfer(J$);if(S===$.FLOAT)o=$.RGBA32F;if(S===$.HALF_FLOAT)o=$.RGBA16F;if(S===$.UNSIGNED_BYTE)o=a===R6?$.SRGB8_ALPHA8:$.RGBA8;if(S===$.UNSIGNED_SHORT&&k$)o=k$.RGBA16_EXT;if(S===$.SHORT&&k$)o=k$.RGBA16_SNORM_EXT;if(S===$.UNSIGNED_SHORT_4_4_4_4)o=$.RGBA4;if(S===$.UNSIGNED_SHORT_5_5_5_1)o=$.RGB5_A1}if(o===$.R16F||o===$.R32F||o===$.RG16F||o===$.RG32F||o===$.RGBA16F||o===$.RGBA32F)U.get("EXT_color_buffer_float");return o}function B(M,F){let S;if(M){if(F===null||F===rJ||F===L8)S=$.DEPTH24_STENCIL8;else if(F===AJ)S=$.DEPTH32F_STENCIL8;else if(F===BW)S=$.DEPTH24_STENCIL8,A$("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")}else if(F===null||F===rJ||F===L8)S=$.DEPTH_COMPONENT24;else if(F===AJ)S=$.DEPTH_COMPONENT32F;else if(F===BW)S=$.DEPTH_COMPONENT16;return S}function z(M,F){if(Z(M)===!0||M.isFramebufferTexture&&M.minFilter!==cU&&M.minFilter!==n6)return Math.log2(Math.max(F.width,F.height))+1;else if(M.mipmaps!==void 0&&M.mipmaps.length>0)return M.mipmaps.length;else if(M.isCompressedTexture&&Array.isArray(M.image))return F.mipmaps.length;else return 1}function A(M){let F=M.target;if(F.removeEventListener("dispose",A),w(F),F.isVideoTexture)G.delete(F);if(F.isHTMLTexture)O.delete(F)}function D(M){let F=M.target;F.removeEventListener("dispose",D),C(F)}function w(M){let F=Q.get(M);if(F.__webglInit===void 0)return;let S=M.source,n=k.get(S);if(n){let J$=n[F.__cacheKey];if(J$.usedTimes--,J$.usedTimes===0)h(M);if(Object.keys(n).length===0)k.delete(S)}Q.remove(M)}function h(M){let F=Q.get(M);$.deleteTexture(F.__webglTexture);let S=M.source,n=k.get(S);delete n[F.__cacheKey],X.memory.textures--}function C(M){let F=Q.get(M);if(M.depthTexture)M.depthTexture.dispose(),Q.remove(M.depthTexture);if(M.isWebGLCubeRenderTarget)for(let n=0;n<6;n++){if(Array.isArray(F.__webglFramebuffer[n]))for(let J$=0;J$<F.__webglFramebuffer[n].length;J$++)$.deleteFramebuffer(F.__webglFramebuffer[n][J$]);else $.deleteFramebuffer(F.__webglFramebuffer[n]);if(F.__webglDepthbuffer)$.deleteRenderbuffer(F.__webglDepthbuffer[n])}else{if(Array.isArray(F.__webglFramebuffer))for(let n=0;n<F.__webglFramebuffer.length;n++)$.deleteFramebuffer(F.__webglFramebuffer[n]);else $.deleteFramebuffer(F.__webglFramebuffer);if(F.__webglDepthbuffer)$.deleteRenderbuffer(F.__webglDepthbuffer);if(F.__webglMultisampledFramebuffer)$.deleteFramebuffer(F.__webglMultisampledFramebuffer);if(F.__webglColorRenderbuffer){for(let n=0;n<F.__webglColorRenderbuffer.length;n++)if(F.__webglColorRenderbuffer[n])$.deleteRenderbuffer(F.__webglColorRenderbuffer[n])}if(F.__webglDepthRenderbuffer)$.deleteRenderbuffer(F.__webglDepthRenderbuffer)}let S=M.textures;for(let n=0,J$=S.length;n<J$;n++){let H$=Q.get(S[n]);if(H$.__webglTexture)$.deleteTexture(H$.__webglTexture),X.memory.textures--;Q.remove(S[n])}Q.remove(M)}let f=0;function s(){f=0}function x(){return f}function d(M){f=M}function c(){let M=f;if(M>=W.maxTextures)A$("WebGLTextures: Trying to use "+M+" texture units while this GPU supports only "+W.maxTextures);return f+=1,M}function y(M){let F=[];return F.push(M.wrapS),F.push(M.wrapT),F.push(M.wrapR||0),F.push(M.magFilter),F.push(M.minFilter),F.push(M.anisotropy),F.push(M.internalFormat),F.push(M.format),F.push(M.type),F.push(M.generateMipmaps),F.push(M.premultiplyAlpha),F.push(M.flipY),F.push(M.unpackAlignment),F.push(M.colorSpace),F.join()}function t(M,F){let S=Q.get(M);if(M.isVideoTexture)AU(M);if(M.isRenderTargetTexture===!1&&M.isExternalTexture!==!0&&M.version>0&&S.__version!==M.version){let n=M.image;if(n===null)A$("WebGLRenderer: Texture marked for update but no image data found.");else if(n.complete===!1)A$("WebGLRenderer: Texture marked for update but image is incomplete");else{v$(S,M,F);return}}else if(M.isExternalTexture)S.__webglTexture=M.sourceTexture?M.sourceTexture:null;J.bindTexture($.TEXTURE_2D,S.__webglTexture,$.TEXTURE0+F)}function e(M,F){let S=Q.get(M);if(M.isRenderTargetTexture===!1&&M.version>0&&S.__version!==M.version){v$(S,M,F);return}else if(M.isExternalTexture)S.__webglTexture=M.sourceTexture?M.sourceTexture:null;J.bindTexture($.TEXTURE_2D_ARRAY,S.__webglTexture,$.TEXTURE0+F)}function Y$(M,F){let S=Q.get(M);if(M.isRenderTargetTexture===!1&&M.version>0&&S.__version!==M.version){v$(S,M,F);return}J.bindTexture($.TEXTURE_3D,S.__webglTexture,$.TEXTURE0+F)}function R$(M,F){let S=Q.get(M);if(M.isCubeDepthTexture!==!0&&M.version>0&&S.__version!==M.version){t$(S,M,F);return}J.bindTexture($.TEXTURE_CUBE_MAP,S.__webglTexture,$.TEXTURE0+F)}let w$={[I8]:$.REPEAT,[D8]:$.CLAMP_TO_EDGE,[O9]:$.MIRRORED_REPEAT},$6={[cU]:$.NEAREST,[E9]:$.NEAREST_MIPMAP_NEAREST,[_0]:$.NEAREST_MIPMAP_LINEAR,[n6]:$.LINEAR,[F8]:$.LINEAR_MIPMAP_NEAREST,[WJ]:$.LINEAR_MIPMAP_LINEAR},n$={[fq]:$.NEVER,[dq]:$.ALWAYS,[uq]:$.LESS,[R9]:$.LEQUAL,[lq]:$.EQUAL,[V9]:$.GEQUAL,[mq]:$.GREATER,[pq]:$.NOTEQUAL};function i(M,F){if(F.type===AJ&&U.has("OES_texture_float_linear")===!1&&(F.magFilter===n6||F.magFilter===F8||F.magFilter===_0||F.magFilter===WJ||F.minFilter===n6||F.minFilter===F8||F.minFilter===_0||F.minFilter===WJ))A$("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.");if($.texParameteri(M,$.TEXTURE_WRAP_S,w$[F.wrapS]),$.texParameteri(M,$.TEXTURE_WRAP_T,w$[F.wrapT]),M===$.TEXTURE_3D||M===$.TEXTURE_2D_ARRAY)$.texParameteri(M,$.TEXTURE_WRAP_R,w$[F.wrapR]);if($.texParameteri(M,$.TEXTURE_MAG_FILTER,$6[F.magFilter]),$.texParameteri(M,$.TEXTURE_MIN_FILTER,$6[F.minFilter]),F.compareFunction)$.texParameteri(M,$.TEXTURE_COMPARE_MODE,$.COMPARE_REF_TO_TEXTURE),$.texParameteri(M,$.TEXTURE_COMPARE_FUNC,n$[F.compareFunction]);if(U.has("EXT_texture_filter_anisotropic")===!0){if(F.magFilter===cU)return;if(F.minFilter!==_0&&F.minFilter!==WJ)return;if(F.type===AJ&&U.has("OES_texture_float_linear")===!1)return;if(F.anisotropy>1||Q.get(F).__currentAnisotropy){let S=U.get("EXT_texture_filter_anisotropic");$.texParameterf(M,S.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(F.anisotropy,W.getMaxAnisotropy())),Q.get(F).__currentAnisotropy=F.anisotropy}}}function X$(M,F){let S=!1;if(M.__webglInit===void 0)M.__webglInit=!0,F.addEventListener("dispose",A);let n=F.source,J$=k.get(n);if(J$===void 0)J$={},k.set(n,J$);let H$=y(F);if(H$!==M.__cacheKey){if(J$[H$]===void 0)J$[H$]={texture:$.createTexture(),usedTimes:0},X.memory.textures++,S=!0;J$[H$].usedTimes++;let k$=J$[M.__cacheKey];if(k$!==void 0){if(J$[M.__cacheKey].usedTimes--,k$.usedTimes===0)h(F)}M.__cacheKey=H$,M.__webglTexture=J$[H$].texture}return S}function D$(M,F,S){return Math.floor(Math.floor(M/S)/F)}function F$(M,F,S,n){let H$=M.updateRanges;if(H$.length===0)J.texSubImage2D($.TEXTURE_2D,0,0,0,F.width,F.height,S,n,F.data);else{H$.sort((C$,q$)=>C$.start-q$.start);let k$=0;for(let C$=1;C$<H$.length;C$++){let q$=H$[k$],N$=H$[C$],j$=q$.start+q$.count,b$=D$(N$.start,F.width,4),H6=D$(q$.start,F.width,4);if(N$.start<=j$+1&&b$===H6&&D$(N$.start+N$.count-1,F.width,4)===b$)q$.count=Math.max(q$.count,N$.start+N$.count-q$.start);else++k$,H$[k$]=N$}H$.length=k$+1;let o=J.getParameter($.UNPACK_ROW_LENGTH),a=J.getParameter($.UNPACK_SKIP_PIXELS),M$=J.getParameter($.UNPACK_SKIP_ROWS);J.pixelStorei($.UNPACK_ROW_LENGTH,F.width);for(let C$=0,q$=H$.length;C$<q$;C$++){let N$=H$[C$],j$=Math.floor(N$.start/4),b$=Math.ceil(N$.count/4),H6=j$%F.width,T=Math.floor(j$/F.width),G$=b$,r=1;J.pixelStorei($.UNPACK_SKIP_PIXELS,H6),J.pixelStorei($.UNPACK_SKIP_ROWS,T),J.texSubImage2D($.TEXTURE_2D,0,H6,T,G$,1,S,n,F.data)}M.clearUpdateRanges(),J.pixelStorei($.UNPACK_ROW_LENGTH,o),J.pixelStorei($.UNPACK_SKIP_PIXELS,a),J.pixelStorei($.UNPACK_SKIP_ROWS,M$)}}function v$(M,F,S){let n=$.TEXTURE_2D;if(F.isDataArrayTexture||F.isCompressedArrayTexture)n=$.TEXTURE_2D_ARRAY;if(F.isData3DTexture)n=$.TEXTURE_3D;let J$=X$(M,F),H$=F.source;J.bindTexture(n,M.__webglTexture,$.TEXTURE0+S);let k$=Q.get(H$);if(H$.version!==k$.__version||J$===!0){if(J.activeTexture($.TEXTURE0+S),(typeof ImageBitmap<"u"&&F.image instanceof ImageBitmap)===!1){let r=r$.getPrimaries(r$.workingColorSpace),O$=F.colorSpace===T0?null:r$.getPrimaries(F.colorSpace),B$=F.colorSpace===T0||r===O$?$.NONE:$.BROWSER_DEFAULT_WEBGL;J.pixelStorei($.UNPACK_FLIP_Y_WEBGL,F.flipY),J.pixelStorei($.UNPACK_PREMULTIPLY_ALPHA_WEBGL,F.premultiplyAlpha),J.pixelStorei($.UNPACK_COLORSPACE_CONVERSION_WEBGL,B$)}J.pixelStorei($.UNPACK_ALIGNMENT,F.unpackAlignment);let a=q(F.image,!1,W.maxTextureSize);a=Y6(F,a);let M$=K.convert(F.format,F.colorSpace),C$=K.convert(F.type),q$=L(F.internalFormat,M$,C$,F.normalized,F.colorSpace,F.isVideoTexture);i(n,F);let N$,j$=F.mipmaps,b$=F.isVideoTexture!==!0,H6=k$.__version===void 0||J$===!0,T=H$.dataReady,G$=z(F,a);if(F.isDepthTexture){if(q$=B(F.format===C0,F.type),H6)if(b$)J.texStorage2D($.TEXTURE_2D,1,q$,a.width,a.height);else J.texImage2D($.TEXTURE_2D,0,q$,a.width,a.height,0,M$,C$,null)}else if(F.isDataTexture)if(j$.length>0){if(b$&&H6)J.texStorage2D($.TEXTURE_2D,G$,q$,j$[0].width,j$[0].height);for(let r=0,O$=j$.length;r<O$;r++)if(N$=j$[r],b$){if(T)J.texSubImage2D($.TEXTURE_2D,r,0,0,N$.width,N$.height,M$,C$,N$.data)}else J.texImage2D($.TEXTURE_2D,r,q$,N$.width,N$.height,0,M$,C$,N$.data);F.generateMipmaps=!1}else if(b$){if(H6)J.texStorage2D($.TEXTURE_2D,G$,q$,a.width,a.height);if(T)F$(F,a,M$,C$)}else J.texImage2D($.TEXTURE_2D,0,q$,a.width,a.height,0,M$,C$,a.data);else if(F.isCompressedTexture)if(F.isCompressedArrayTexture){if(b$&&H6)J.texStorage3D($.TEXTURE_2D_ARRAY,G$,q$,j$[0].width,j$[0].height,a.depth);for(let r=0,O$=j$.length;r<O$;r++)if(N$=j$[r],F.format!==QJ)if(M$!==null)if(b$){if(T)if(F.layerUpdates.size>0){let B$=BH(N$.width,N$.height,F.format,F.type);for(let $$ of F.layerUpdates){let E$=N$.data.subarray($$*B$/N$.data.BYTES_PER_ELEMENT,($$+1)*B$/N$.data.BYTES_PER_ELEMENT);J.compressedTexSubImage3D($.TEXTURE_2D_ARRAY,r,0,0,$$,N$.width,N$.height,1,M$,E$)}F.clearLayerUpdates()}else J.compressedTexSubImage3D($.TEXTURE_2D_ARRAY,r,0,0,0,N$.width,N$.height,a.depth,M$,N$.data)}else J.compressedTexImage3D($.TEXTURE_2D_ARRAY,r,q$,N$.width,N$.height,a.depth,0,N$.data,0,0);else A$("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(b$){if(T)J.texSubImage3D($.TEXTURE_2D_ARRAY,r,0,0,0,N$.width,N$.height,a.depth,M$,C$,N$.data)}else J.texImage3D($.TEXTURE_2D_ARRAY,r,q$,N$.width,N$.height,a.depth,0,M$,C$,N$.data)}else{if(b$&&H6)J.texStorage2D($.TEXTURE_2D,G$,q$,j$[0].width,j$[0].height);for(let r=0,O$=j$.length;r<O$;r++)if(N$=j$[r],F.format!==QJ)if(M$!==null)if(b$){if(T)J.compressedTexSubImage2D($.TEXTURE_2D,r,0,0,N$.width,N$.height,M$,N$.data)}else J.compressedTexImage2D($.TEXTURE_2D,r,q$,N$.width,N$.height,0,N$.data);else A$("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(b$){if(T)J.texSubImage2D($.TEXTURE_2D,r,0,0,N$.width,N$.height,M$,C$,N$.data)}else J.texImage2D($.TEXTURE_2D,r,q$,N$.width,N$.height,0,M$,C$,N$.data)}else if(F.isDataArrayTexture)if(b$){if(H6)J.texStorage3D($.TEXTURE_2D_ARRAY,G$,q$,a.width,a.height,a.depth);if(T)if(F.layerUpdates.size>0){let r=BH(a.width,a.height,F.format,F.type);for(let O$ of F.layerUpdates){let B$=a.data.subarray(O$*r/a.data.BYTES_PER_ELEMENT,(O$+1)*r/a.data.BYTES_PER_ELEMENT);J.texSubImage3D($.TEXTURE_2D_ARRAY,0,0,0,O$,a.width,a.height,1,M$,C$,B$)}F.clearLayerUpdates()}else J.texSubImage3D($.TEXTURE_2D_ARRAY,0,0,0,0,a.width,a.height,a.depth,M$,C$,a.data)}else J.texImage3D($.TEXTURE_2D_ARRAY,0,q$,a.width,a.height,a.depth,0,M$,C$,a.data);else if(F.isData3DTexture)if(b$){if(H6)J.texStorage3D($.TEXTURE_3D,G$,q$,a.width,a.height,a.depth);if(T)J.texSubImage3D($.TEXTURE_3D,0,0,0,0,a.width,a.height,a.depth,M$,C$,a.data)}else J.texImage3D($.TEXTURE_3D,0,q$,a.width,a.height,a.depth,0,M$,C$,a.data);else if(F.isFramebufferTexture){if(H6)if(b$)J.texStorage2D($.TEXTURE_2D,G$,q$,a.width,a.height);else{let{width:r,height:O$}=a;for(let B$=0;B$<G$;B$++)J.texImage2D($.TEXTURE_2D,B$,q$,r,O$,0,M$,C$,null),r>>=1,O$>>=1}}else if(F.isHTMLTexture){if("texElementImage2D"in $){let r=$.canvas;if(!r.hasAttribute("layoutsubtree"))r.setAttribute("layoutsubtree","true");if(a.parentNode!==r){r.appendChild(a),O.add(F),r.onpaint=(O$)=>{let B$=O$.changedElements;for(let $$ of O)if(B$.includes($$.image))$$.needsUpdate=!0},r.requestPaint();return}if($.texElementImage2D.length===3)$.texElementImage2D($.TEXTURE_2D,$.RGBA8,a);else{let{RGBA:B$,RGBA:$$,UNSIGNED_BYTE:E$}=$;$.texElementImage2D($.TEXTURE_2D,0,B$,$$,E$,a)}$.texParameteri($.TEXTURE_2D,$.TEXTURE_MIN_FILTER,$.LINEAR),$.texParameteri($.TEXTURE_2D,$.TEXTURE_WRAP_S,$.CLAMP_TO_EDGE),$.texParameteri($.TEXTURE_2D,$.TEXTURE_WRAP_T,$.CLAMP_TO_EDGE)}}else if(j$.length>0){if(b$&&H6){let r=z6(j$[0]);J.texStorage2D($.TEXTURE_2D,G$,q$,r.width,r.height)}for(let r=0,O$=j$.length;r<O$;r++)if(N$=j$[r],b$){if(T)J.texSubImage2D($.TEXTURE_2D,r,0,0,M$,C$,N$)}else J.texImage2D($.TEXTURE_2D,r,q$,M$,C$,N$);F.generateMipmaps=!1}else if(b$){if(H6){let r=z6(a);J.texStorage2D($.TEXTURE_2D,G$,q$,r.width,r.height)}if(T)J.texSubImage2D($.TEXTURE_2D,0,0,0,M$,C$,a)}else J.texImage2D($.TEXTURE_2D,0,q$,M$,C$,a);if(Z(F))_(n);if(k$.__version=H$.version,F.onUpdate)F.onUpdate(F)}M.__version=F.version}function t$(M,F,S){if(F.image.length!==6)return;let n=X$(M,F),J$=F.source;J.bindTexture($.TEXTURE_CUBE_MAP,M.__webglTexture,$.TEXTURE0+S);let H$=Q.get(J$);if(J$.version!==H$.__version||n===!0){J.activeTexture($.TEXTURE0+S);let k$=r$.getPrimaries(r$.workingColorSpace),o=F.colorSpace===T0?null:r$.getPrimaries(F.colorSpace),a=F.colorSpace===T0||k$===o?$.NONE:$.BROWSER_DEFAULT_WEBGL;J.pixelStorei($.UNPACK_FLIP_Y_WEBGL,F.flipY),J.pixelStorei($.UNPACK_PREMULTIPLY_ALPHA_WEBGL,F.premultiplyAlpha),J.pixelStorei($.UNPACK_ALIGNMENT,F.unpackAlignment),J.pixelStorei($.UNPACK_COLORSPACE_CONVERSION_WEBGL,a);let M$=F.isCompressedTexture||F.image[0].isCompressedTexture,C$=F.image[0]&&F.image[0].isDataTexture,q$=[];for(let $$=0;$$<6;$$++){if(!M$&&!C$)q$[$$]=q(F.image[$$],!0,W.maxCubemapSize);else q$[$$]=C$?F.image[$$].image:F.image[$$];q$[$$]=Y6(F,q$[$$])}let N$=q$[0],j$=K.convert(F.format,F.colorSpace),b$=K.convert(F.type),H6=L(F.internalFormat,j$,b$,F.normalized,F.colorSpace),T=F.isVideoTexture!==!0,G$=H$.__version===void 0||n===!0,r=J$.dataReady,O$=z(F,N$);i($.TEXTURE_CUBE_MAP,F);let B$;if(M$){if(T&&G$)J.texStorage2D($.TEXTURE_CUBE_MAP,O$,H6,N$.width,N$.height);for(let $$=0;$$<6;$$++){B$=q$[$$].mipmaps;for(let E$=0;E$<B$.length;E$++){let l$=B$[E$];if(F.format!==QJ)if(j$!==null)if(T){if(r)J.compressedTexSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$,0,0,l$.width,l$.height,j$,l$.data)}else J.compressedTexImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$,H6,l$.width,l$.height,0,l$.data);else A$("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()");else if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$,0,0,l$.width,l$.height,j$,b$,l$.data)}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$,H6,l$.width,l$.height,0,j$,b$,l$.data)}}}else{if(B$=F.mipmaps,T&&G$){if(B$.length>0)O$++;let $$=z6(q$[0]);J.texStorage2D($.TEXTURE_CUBE_MAP,O$,H6,$$.width,$$.height)}for(let $$=0;$$<6;$$++)if(C$){if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,0,0,0,q$[$$].width,q$[$$].height,j$,b$,q$[$$].data)}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,0,H6,q$[$$].width,q$[$$].height,0,j$,b$,q$[$$].data);for(let E$=0;E$<B$.length;E$++){let _6=B$[E$].image[$$].image;if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$+1,0,0,_6.width,_6.height,j$,b$,_6.data)}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$+1,H6,_6.width,_6.height,0,j$,b$,_6.data)}}else{if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,0,0,0,j$,b$,q$[$$])}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,0,H6,j$,b$,q$[$$]);for(let E$=0;E$<B$.length;E$++){let l$=B$[E$];if(T){if(r)J.texSubImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$+1,0,0,j$,b$,l$.image[$$])}else J.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+$$,E$+1,H6,j$,b$,l$.image[$$])}}}if(Z(F))_($.TEXTURE_CUBE_MAP);if(H$.__version=J$.version,F.onUpdate)F.onUpdate(F)}M.__version=F.version}function u$(M,F,S,n,J$,H$){let k$=K.convert(S.format,S.colorSpace),o=K.convert(S.type),a=L(S.internalFormat,k$,o,S.normalized,S.colorSpace),M$=Q.get(F),C$=Q.get(S);if(C$.__renderTarget=F,!M$.__hasExternalTextures){let q$=Math.max(1,F.width>>H$),N$=Math.max(1,F.height>>H$);if(J$===$.TEXTURE_3D||J$===$.TEXTURE_2D_ARRAY)J.texImage3D(J$,H$,a,q$,N$,F.depth,0,k$,o,null);else J.texImage2D(J$,H$,a,q$,N$,0,k$,o,null)}if(J.bindFramebuffer($.FRAMEBUFFER,M),v(F))H.framebufferTexture2DMultisampleEXT($.FRAMEBUFFER,n,J$,C$.__webglTexture,0,y6(F));else if(J$===$.TEXTURE_2D||J$>=$.TEXTURE_CUBE_MAP_POSITIVE_X&&J$<=$.TEXTURE_CUBE_MAP_NEGATIVE_Z)$.framebufferTexture2D($.FRAMEBUFFER,n,J$,C$.__webglTexture,H$);J.bindFramebuffer($.FRAMEBUFFER,null)}function p$(M,F,S){if($.bindRenderbuffer($.RENDERBUFFER,M),F.depthBuffer){let n=F.depthTexture,J$=n&&n.isDepthTexture?n.type:null,H$=B(F.stencilBuffer,J$),k$=F.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT;if(v(F))H.renderbufferStorageMultisampleEXT($.RENDERBUFFER,y6(F),H$,F.width,F.height);else if(S)$.renderbufferStorageMultisample($.RENDERBUFFER,y6(F),H$,F.width,F.height);else $.renderbufferStorage($.RENDERBUFFER,H$,F.width,F.height);$.framebufferRenderbuffer($.FRAMEBUFFER,k$,$.RENDERBUFFER,M)}else{let n=F.textures;for(let J$=0;J$<n.length;J$++){let H$=n[J$],k$=K.convert(H$.format,H$.colorSpace),o=K.convert(H$.type),a=L(H$.internalFormat,k$,o,H$.normalized,H$.colorSpace);if(v(F))H.renderbufferStorageMultisampleEXT($.RENDERBUFFER,y6(F),a,F.width,F.height);else if(S)$.renderbufferStorageMultisample($.RENDERBUFFER,y6(F),a,F.width,F.height);else $.renderbufferStorage($.RENDERBUFFER,a,F.width,F.height)}}$.bindRenderbuffer($.RENDERBUFFER,null)}function K6(M,F,S){let n=F.isWebGLCubeRenderTarget===!0;if(J.bindFramebuffer($.FRAMEBUFFER,M),!(F.depthTexture&&F.depthTexture.isDepthTexture))throw Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");let J$=Q.get(F.depthTexture);if(J$.__renderTarget=F,!J$.__webglTexture||F.depthTexture.image.width!==F.width||F.depthTexture.image.height!==F.height)F.depthTexture.image.width=F.width,F.depthTexture.image.height=F.height,F.depthTexture.needsUpdate=!0;if(n){if(J$.__webglInit===void 0)J$.__webglInit=!0,F.depthTexture.addEventListener("dispose",A);if(J$.__webglTexture===void 0){J$.__webglTexture=$.createTexture(),J.bindTexture($.TEXTURE_CUBE_MAP,J$.__webglTexture),i($.TEXTURE_CUBE_MAP,F.depthTexture);let M$=K.convert(F.depthTexture.format),C$=K.convert(F.depthTexture.type),q$;if(F.depthTexture.format===A0)q$=$.DEPTH_COMPONENT24;else if(F.depthTexture.format===C0)q$=$.DEPTH24_STENCIL8;for(let N$=0;N$<6;N$++)$.texImage2D($.TEXTURE_CUBE_MAP_POSITIVE_X+N$,0,q$,F.width,F.height,0,M$,C$,null)}}else t(F.depthTexture,0);let H$=J$.__webglTexture,k$=y6(F),o=n?$.TEXTURE_CUBE_MAP_POSITIVE_X+S:$.TEXTURE_2D,a=F.depthTexture.format===C0?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT;if(F.depthTexture.format===A0)if(v(F))H.framebufferTexture2DMultisampleEXT($.FRAMEBUFFER,a,o,H$,0,k$);else $.framebufferTexture2D($.FRAMEBUFFER,a,o,H$,0);else if(F.depthTexture.format===C0)if(v(F))H.framebufferTexture2DMultisampleEXT($.FRAMEBUFFER,a,o,H$,0,k$);else $.framebufferTexture2D($.FRAMEBUFFER,a,o,H$,0);else throw Error("THREE.WebGLTextures: Unknown depthTexture format.")}function U6(M){let F=Q.get(M),S=M.isWebGLCubeRenderTarget===!0;if(F.__boundDepthTexture!==M.depthTexture){let n=M.depthTexture;if(F.__depthDisposeCallback)F.__depthDisposeCallback();if(n){let J$=()=>{delete F.__boundDepthTexture,delete F.__depthDisposeCallback,n.removeEventListener("dispose",J$)};n.addEventListener("dispose",J$),F.__depthDisposeCallback=J$}F.__boundDepthTexture=n}if(M.depthTexture&&!F.__autoAllocateDepthBuffer)if(S)for(let n=0;n<6;n++)K6(F.__webglFramebuffer[n],M,n);else{let n=M.texture.mipmaps;if(n&&n.length>0)K6(F.__webglFramebuffer[0],M,0);else K6(F.__webglFramebuffer,M,0)}else if(S){F.__webglDepthbuffer=[];for(let n=0;n<6;n++)if(J.bindFramebuffer($.FRAMEBUFFER,F.__webglFramebuffer[n]),F.__webglDepthbuffer[n]===void 0)F.__webglDepthbuffer[n]=$.createRenderbuffer(),p$(F.__webglDepthbuffer[n],M,!1);else{let J$=M.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT,H$=F.__webglDepthbuffer[n];$.bindRenderbuffer($.RENDERBUFFER,H$),$.framebufferRenderbuffer($.FRAMEBUFFER,J$,$.RENDERBUFFER,H$)}}else{let n=M.texture.mipmaps;if(n&&n.length>0)J.bindFramebuffer($.FRAMEBUFFER,F.__webglFramebuffer[0]);else J.bindFramebuffer($.FRAMEBUFFER,F.__webglFramebuffer);if(F.__webglDepthbuffer===void 0)F.__webglDepthbuffer=$.createRenderbuffer(),p$(F.__webglDepthbuffer,M,!1);else{let J$=M.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT,H$=F.__webglDepthbuffer;$.bindRenderbuffer($.RENDERBUFFER,H$),$.framebufferRenderbuffer($.FRAMEBUFFER,J$,$.RENDERBUFFER,H$)}}J.bindFramebuffer($.FRAMEBUFFER,null)}function Q6(M,F,S){let n=Q.get(M);if(F!==void 0)u$(n.__webglFramebuffer,M,M.texture,$.COLOR_ATTACHMENT0,$.TEXTURE_2D,0);if(S!==void 0)U6(M)}function m6(M){let F=M.texture,S=Q.get(M),n=Q.get(F);M.addEventListener("dispose",D);let J$=M.textures,H$=M.isWebGLCubeRenderTarget===!0,k$=J$.length>1;if(!k$){if(n.__webglTexture===void 0)n.__webglTexture=$.createTexture();n.__version=F.version,X.memory.textures++}if(H$){S.__webglFramebuffer=[];for(let o=0;o<6;o++)if(F.mipmaps&&F.mipmaps.length>0){S.__webglFramebuffer[o]=[];for(let a=0;a<F.mipmaps.length;a++)S.__webglFramebuffer[o][a]=$.createFramebuffer()}else S.__webglFramebuffer[o]=$.createFramebuffer()}else{if(F.mipmaps&&F.mipmaps.length>0){S.__webglFramebuffer=[];for(let o=0;o<F.mipmaps.length;o++)S.__webglFramebuffer[o]=$.createFramebuffer()}else S.__webglFramebuffer=$.createFramebuffer();if(k$)for(let o=0,a=J$.length;o<a;o++){let M$=Q.get(J$[o]);if(M$.__webglTexture===void 0)M$.__webglTexture=$.createTexture(),X.memory.textures++}if(M.samples>0&&v(M)===!1){S.__webglMultisampledFramebuffer=$.createFramebuffer(),S.__webglColorRenderbuffer=[],J.bindFramebuffer($.FRAMEBUFFER,S.__webglMultisampledFramebuffer);for(let o=0;o<J$.length;o++){let a=J$[o];S.__webglColorRenderbuffer[o]=$.createRenderbuffer(),$.bindRenderbuffer($.RENDERBUFFER,S.__webglColorRenderbuffer[o]);let M$=K.convert(a.format,a.colorSpace),C$=K.convert(a.type),q$=L(a.internalFormat,M$,C$,a.normalized,a.colorSpace,M.isXRRenderTarget===!0),N$=y6(M);$.renderbufferStorageMultisample($.RENDERBUFFER,N$,q$,M.width,M.height),$.framebufferRenderbuffer($.FRAMEBUFFER,$.COLOR_ATTACHMENT0+o,$.RENDERBUFFER,S.__webglColorRenderbuffer[o])}if($.bindRenderbuffer($.RENDERBUFFER,null),M.depthBuffer)S.__webglDepthRenderbuffer=$.createRenderbuffer(),p$(S.__webglDepthRenderbuffer,M,!0);J.bindFramebuffer($.FRAMEBUFFER,null)}}if(H$){J.bindTexture($.TEXTURE_CUBE_MAP,n.__webglTexture),i($.TEXTURE_CUBE_MAP,F);for(let o=0;o<6;o++)if(F.mipmaps&&F.mipmaps.length>0)for(let a=0;a<F.mipmaps.length;a++)u$(S.__webglFramebuffer[o][a],M,F,$.COLOR_ATTACHMENT0,$.TEXTURE_CUBE_MAP_POSITIVE_X+o,a);else u$(S.__webglFramebuffer[o],M,F,$.COLOR_ATTACHMENT0,$.TEXTURE_CUBE_MAP_POSITIVE_X+o,0);if(Z(F))_($.TEXTURE_CUBE_MAP);J.unbindTexture()}else if(k$){for(let o=0,a=J$.length;o<a;o++){let M$=J$[o],C$=Q.get(M$),q$=$.TEXTURE_2D;if(M.isWebGL3DRenderTarget||M.isWebGLArrayRenderTarget)q$=M.isWebGL3DRenderTarget?$.TEXTURE_3D:$.TEXTURE_2D_ARRAY;if(J.bindTexture(q$,C$.__webglTexture),i(q$,M$),u$(S.__webglFramebuffer,M,M$,$.COLOR_ATTACHMENT0+o,q$,0),Z(M$))_(q$)}J.unbindTexture()}else{let o=$.TEXTURE_2D;if(M.isWebGL3DRenderTarget||M.isWebGLArrayRenderTarget)o=M.isWebGL3DRenderTarget?$.TEXTURE_3D:$.TEXTURE_2D_ARRAY;if(J.bindTexture(o,n.__webglTexture),i(o,F),F.mipmaps&&F.mipmaps.length>0)for(let a=0;a<F.mipmaps.length;a++)u$(S.__webglFramebuffer[a],M,F,$.COLOR_ATTACHMENT0,o,a);else u$(S.__webglFramebuffer,M,F,$.COLOR_ATTACHMENT0,o,0);if(Z(F))_(o);J.unbindTexture()}if(M.depthBuffer)U6(M)}function _U(M){let F=M.textures;for(let S=0,n=F.length;S<n;S++){let J$=F[S];if(Z(J$)){let H$=P(M),k$=Q.get(J$).__webglTexture;J.bindTexture(H$,k$),_(H$),J.unbindTexture()}}}let P6=[],o6=[];function p6(M){if(M.samples>0){if(v(M)===!1){let{textures:F,width:S,height:n}=M,J$=$.COLOR_BUFFER_BIT,H$=M.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT,k$=Q.get(M),o=F.length>1;if(o)for(let M$=0;M$<F.length;M$++)J.bindFramebuffer($.FRAMEBUFFER,k$.__webglMultisampledFramebuffer),$.framebufferRenderbuffer($.FRAMEBUFFER,$.COLOR_ATTACHMENT0+M$,$.RENDERBUFFER,null),J.bindFramebuffer($.FRAMEBUFFER,k$.__webglFramebuffer),$.framebufferTexture2D($.DRAW_FRAMEBUFFER,$.COLOR_ATTACHMENT0+M$,$.TEXTURE_2D,null,0);J.bindFramebuffer($.READ_FRAMEBUFFER,k$.__webglMultisampledFramebuffer);let a=M.texture.mipmaps;if(a&&a.length>0)J.bindFramebuffer($.DRAW_FRAMEBUFFER,k$.__webglFramebuffer[0]);else J.bindFramebuffer($.DRAW_FRAMEBUFFER,k$.__webglFramebuffer);for(let M$=0;M$<F.length;M$++){if(M.resolveDepthBuffer){if(M.depthBuffer)J$|=$.DEPTH_BUFFER_BIT;if(M.stencilBuffer&&M.resolveStencilBuffer)J$|=$.STENCIL_BUFFER_BIT}if(o){$.framebufferRenderbuffer($.READ_FRAMEBUFFER,$.COLOR_ATTACHMENT0,$.RENDERBUFFER,k$.__webglColorRenderbuffer[M$]);let C$=Q.get(F[M$]).__webglTexture;$.framebufferTexture2D($.DRAW_FRAMEBUFFER,$.COLOR_ATTACHMENT0,$.TEXTURE_2D,C$,0)}if($.blitFramebuffer(0,0,S,n,0,0,S,n,J$,$.NEAREST),N===!0){if(P6.length=0,o6.length=0,P6.push($.COLOR_ATTACHMENT0+M$),M.depthBuffer&&M.resolveDepthBuffer===!1)P6.push(H$),o6.push(H$),$.invalidateFramebuffer($.DRAW_FRAMEBUFFER,o6);$.invalidateFramebuffer($.READ_FRAMEBUFFER,P6)}}if(J.bindFramebuffer($.READ_FRAMEBUFFER,null),J.bindFramebuffer($.DRAW_FRAMEBUFFER,null),o)for(let M$=0;M$<F.length;M$++){J.bindFramebuffer($.FRAMEBUFFER,k$.__webglMultisampledFramebuffer),$.framebufferRenderbuffer($.FRAMEBUFFER,$.COLOR_ATTACHMENT0+M$,$.RENDERBUFFER,k$.__webglColorRenderbuffer[M$]);let C$=Q.get(F[M$]).__webglTexture;J.bindFramebuffer($.FRAMEBUFFER,k$.__webglFramebuffer),$.framebufferTexture2D($.DRAW_FRAMEBUFFER,$.COLOR_ATTACHMENT0+M$,$.TEXTURE_2D,C$,0)}J.bindFramebuffer($.DRAW_FRAMEBUFFER,k$.__webglMultisampledFramebuffer)}else if(M.depthBuffer&&M.resolveDepthBuffer===!1&&N){let F=M.stencilBuffer?$.DEPTH_STENCIL_ATTACHMENT:$.DEPTH_ATTACHMENT;$.invalidateFramebuffer($.DRAW_FRAMEBUFFER,[F])}}}function y6(M){return Math.min(W.maxSamples,M.samples)}function v(M){let F=Q.get(M);return M.samples>0&&U.has("WEBGL_multisampled_render_to_texture")===!0&&F.__useRenderToTexture!==!1}function AU(M){let F=X.render.frame;if(G.get(M)!==F)G.set(M,F),M.update()}function Y6(M,F){let{colorSpace:S,format:n,type:J$}=M;if(M.isCompressedTexture===!0||M.isVideoTexture===!0)return F;if(S!==RU&&S!==T0)if(r$.getTransfer(S)===R6){if(n!==QJ||J$!==nU)A$("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}else x$("WebGLTextures: Unsupported texture color space:",S);return F}function z6(M){if(typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement)Y.width=M.naturalWidth||M.width,Y.height=M.naturalHeight||M.height;else if(typeof VideoFrame<"u"&&M instanceof VideoFrame)Y.width=M.displayWidth,Y.height=M.displayHeight;else Y.width=M.width,Y.height=M.height;return Y}this.allocateTextureUnit=c,this.resetTextureUnits=s,this.getTextureUnits=x,this.setTextureUnits=d,this.setTexture2D=t,this.setTexture2DArray=e,this.setTexture3D=Y$,this.setTextureCube=R$,this.rebindTextures=Q6,this.setupRenderTarget=m6,this.updateRenderTargetMipmap=_U,this.updateMultisampleRenderTarget=p6,this.setupDepthRenderbuffer=U6,this.setupFrameBufferTexture=u$,this.useMultisampledRTT=v,this.isReversedDepthBuffer=function(){return J.buffers.depth.getReversed()}}function uw($,U){function J(Q,W=T0){let K,X=r$.getTransfer(W);if(Q===nU)return $.UNSIGNED_BYTE;if(Q===IX)return $.UNSIGNED_SHORT_4_4_4_4;if(Q===DX)return $.UNSIGNED_SHORT_5_5_5_1;if(Q===jq)return $.UNSIGNED_INT_5_9_9_9_REV;if(Q===gq)return $.UNSIGNED_INT_10F_11F_11F_REV;if(Q===Tq)return $.BYTE;if(Q===vq)return $.SHORT;if(Q===BW)return $.UNSIGNED_SHORT;if(Q===ZX)return $.INT;if(Q===rJ)return $.UNSIGNED_INT;if(Q===AJ)return $.FLOAT;if(Q===CJ)return $.HALF_FLOAT;if(Q===bq)return $.ALPHA;if(Q===yq)return $.RGB;if(Q===QJ)return $.RGBA;if(Q===A0)return $.DEPTH_COMPONENT;if(Q===C0)return $.DEPTH_STENCIL;if(Q===xq)return $.RED;if(Q===FX)return $.RED_INTEGER;if(Q===S0)return $.RG;if(Q===LX)return $.RG_INTEGER;if(Q===RX)return $.RGBA_INTEGER;if(Q===k9||Q===q9||Q===Z9||Q===I9)if(X===R6)if(K=U.get("WEBGL_compressed_texture_s3tc_srgb"),K!==null){if(Q===k9)return K.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(Q===q9)return K.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(Q===Z9)return K.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(Q===I9)return K.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(K=U.get("WEBGL_compressed_texture_s3tc"),K!==null){if(Q===k9)return K.COMPRESSED_RGB_S3TC_DXT1_EXT;if(Q===q9)return K.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(Q===Z9)return K.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(Q===I9)return K.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(Q===VX||Q===wX||Q===MX||Q===BX)if(K=U.get("WEBGL_compressed_texture_pvrtc"),K!==null){if(Q===VX)return K.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(Q===wX)return K.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(Q===MX)return K.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(Q===BX)return K.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(Q===PX||Q===zX||Q===_X||Q===AX||Q===CX||Q===D9||Q===SX)if(K=U.get("WEBGL_compressed_texture_etc"),K!==null){if(Q===PX||Q===zX)return X===R6?K.COMPRESSED_SRGB8_ETC2:K.COMPRESSED_RGB8_ETC2;if(Q===_X)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:K.COMPRESSED_RGBA8_ETC2_EAC;if(Q===AX)return K.COMPRESSED_R11_EAC;if(Q===CX)return K.COMPRESSED_SIGNED_R11_EAC;if(Q===D9)return K.COMPRESSED_RG11_EAC;if(Q===SX)return K.COMPRESSED_SIGNED_RG11_EAC}else return null;if(Q===TX||Q===vX||Q===jX||Q===gX||Q===bX||Q===yX||Q===xX||Q===hX||Q===fX||Q===uX||Q===lX||Q===mX||Q===pX||Q===dX)if(K=U.get("WEBGL_compressed_texture_astc"),K!==null){if(Q===TX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:K.COMPRESSED_RGBA_ASTC_4x4_KHR;if(Q===vX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:K.COMPRESSED_RGBA_ASTC_5x4_KHR;if(Q===jX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:K.COMPRESSED_RGBA_ASTC_5x5_KHR;if(Q===gX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:K.COMPRESSED_RGBA_ASTC_6x5_KHR;if(Q===bX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:K.COMPRESSED_RGBA_ASTC_6x6_KHR;if(Q===yX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:K.COMPRESSED_RGBA_ASTC_8x5_KHR;if(Q===xX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:K.COMPRESSED_RGBA_ASTC_8x6_KHR;if(Q===hX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:K.COMPRESSED_RGBA_ASTC_8x8_KHR;if(Q===fX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:K.COMPRESSED_RGBA_ASTC_10x5_KHR;if(Q===uX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:K.COMPRESSED_RGBA_ASTC_10x6_KHR;if(Q===lX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:K.COMPRESSED_RGBA_ASTC_10x8_KHR;if(Q===mX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:K.COMPRESSED_RGBA_ASTC_10x10_KHR;if(Q===pX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:K.COMPRESSED_RGBA_ASTC_12x10_KHR;if(Q===dX)return X===R6?K.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:K.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(Q===cX||Q===nX||Q===iX)if(K=U.get("EXT_texture_compression_bptc"),K!==null){if(Q===cX)return X===R6?K.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:K.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(Q===nX)return K.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(Q===iX)return K.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(Q===oX||Q===rX||Q===F9||Q===aX)if(K=U.get("EXT_texture_compression_rgtc"),K!==null){if(Q===oX)return K.COMPRESSED_RED_RGTC1_EXT;if(Q===rX)return K.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(Q===F9)return K.COMPRESSED_RED_GREEN_RGTC2_EXT;if(Q===aX)return K.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;if(Q===L8)return $.UNSIGNED_INT_24_8;return $[Q]!==void 0?$[Q]:null}return{convert:J}}var lw=`+}`,pM=[new N(1,0,0),new N(-1,0,0),new N(0,1,0),new N(0,-1,0),new N(0,0,1),new N(0,0,-1)],mM=[new N(0,-1,0),new N(0,-1,0),new N(0,0,1),new N(0,0,-1),new N(0,-1,0),new N(0,-1,0)],yd=new Fe,zs=new N,Zl=new N;function gM(e,t,n){let i=new Ps,r=new Pe,s=new Pe,o=new it,a=new El,c=new Al,l={},u=n.maxTextureSize,f={[Ri]:Xt,[Xt]:Ri,[vn]:vn},h=new bn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Pe},radius:{value:4}},vertexShader:fM,fragmentShader:dM}),d=h.clone();d.defines.HORIZONTAL_PASS=1;let g=new Kt;g.setAttribute("position",new It(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));let b=new dt(g,h),p=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=_s;let m=this.type;this.render=function(E,R,_){if(p.enabled===!1)return;if(p.autoUpdate===!1&&p.needsUpdate===!1)return;if(E.length===0)return;if(this.type===Yh)Me("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=_s;let S=e.getRenderTarget(),F=e.getActiveCubeFace(),C=e.getActiveMipmapLevel(),z=e.state;if(z.setBlending(Vn),z.buffers.depth.getReversed()===!0)z.buffers.color.setClear(0,0,0,0);else z.buffers.color.setClear(1,1,1,1);z.buffers.depth.setTest(!0),z.setScissorTest(!1);let J=m!==this.type;if(J)R.traverse(function(O){if(O.material)if(Array.isArray(O.material))O.material.forEach((H)=>H.needsUpdate=!0);else O.material.needsUpdate=!0});for(let O=0,H=E.length;O<H;O++){let V=E[O],U=V.shadow;if(U===void 0){Me("WebGLShadowMap:",V,"has no shadow.");continue}if(U.autoUpdate===!1&&U.needsUpdate===!1)continue;r.copy(U.mapSize);let K=U.getFrameExtents();if(r.multiply(K),s.copy(U.mapSize),r.x>u||r.y>u){if(r.x>u)s.x=Math.floor(u/K.x),r.x=s.x*K.x,U.mapSize.x=s.x;if(r.y>u)s.y=Math.floor(u/K.y),r.y=s.y*K.y,U.mapSize.y=s.y}let Q=e.state.buffers.depth.getReversed();if(U.camera._reversedDepth=Q,U.map===null||J===!0){if(U.map!==null){if(U.map.depthTexture!==null)U.map.depthTexture.dispose(),U.map.depthTexture=null;U.map.dispose()}if(this.type===kr){if(V.isPointLight){Me("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}U.map=new yn(r.x,r.y,{format:or,type:hi,minFilter:kt,magFilter:kt,generateMipmaps:!1}),U.map.texture.name=V.name+".shadowMap",U.map.depthTexture=new Ni(r.x,r.y,ui),U.map.depthTexture.name=V.name+".shadowMapDepth",U.map.depthTexture.format=rr,U.map.depthTexture.compareFunction=null,U.map.depthTexture.minFilter=In,U.map.depthTexture.magFilter=In}else{if(V.isPointLight)U.map=new Yl(r.x),U.map.depthTexture=new Ml(r.x,Ci);else U.map=new yn(r.x,r.y),U.map.depthTexture=new Ni(r.x,r.y,Ci);if(U.map.depthTexture.name=V.name+".shadowMap",U.map.depthTexture.format=rr,this.type===_s)U.map.depthTexture.compareFunction=Q?qo:Xo,U.map.depthTexture.minFilter=kt,U.map.depthTexture.magFilter=kt;else U.map.depthTexture.compareFunction=null,U.map.depthTexture.minFilter=In,U.map.depthTexture.magFilter=In}U.camera.updateProjectionMatrix()}let se=U.map.isWebGLCubeRenderTarget?6:1;for(let me=0;me<se;me++){if(U.map.isWebGLCubeRenderTarget)e.setRenderTarget(U.map,me),e.clear();else{if(me===0)e.setRenderTarget(U.map),e.clear();let _e=U.getViewport(me);o.set(s.x*_e.x,s.y*_e.y,s.x*_e.z,s.y*_e.w),z.viewport(o)}if(V.isPointLight){let{camera:_e,matrix:Xe}=U,Be=V.distance||_e.far;if(Be!==_e.far)_e.far=Be,_e.updateProjectionMatrix();zs.setFromMatrixPosition(V.matrixWorld),_e.position.copy(zs),Zl.copy(_e.position),Zl.add(pM[me]),_e.up.copy(mM[me]),_e.lookAt(Zl),_e.updateMatrixWorld(),Xe.makeTranslation(-zs.x,-zs.y,-zs.z),yd.multiplyMatrices(_e.projectionMatrix,_e.matrixWorldInverse),U._frustum.setFromProjectionMatrix(yd,_e.coordinateSystem,_e.reversedDepth)}else U.updateMatrices(V);i=U.getFrustum(),v(R,_,U.camera,V,this.type)}if(U.isPointLightShadow!==!0&&this.type===kr)A(U,_);U.needsUpdate=!1}m=this.type,p.needsUpdate=!1,e.setRenderTarget(S,F,C)};function A(E,R){let _=t.update(b);if(h.defines.VSM_SAMPLES!==E.blurSamples)h.defines.VSM_SAMPLES=E.blurSamples,d.defines.VSM_SAMPLES=E.blurSamples,h.needsUpdate=!0,d.needsUpdate=!0;if(E.mapPass===null)E.mapPass=new yn(r.x,r.y,{format:or,type:hi});h.uniforms.shadow_pass.value=E.map.depthTexture,h.uniforms.resolution.value=E.mapSize,h.uniforms.radius.value=E.radius,e.setRenderTarget(E.mapPass),e.clear(),e.renderBufferDirect(R,null,_,h,b,null),d.uniforms.shadow_pass.value=E.mapPass.texture,d.uniforms.resolution.value=E.mapSize,d.uniforms.radius.value=E.radius,e.setRenderTarget(E.map),e.clear(),e.renderBufferDirect(R,null,_,d,b,null)}function T(E,R,_,S){let F=null,C=_.isPointLight===!0?E.customDistanceMaterial:E.customDepthMaterial;if(C!==void 0)F=C;else if(F=_.isPointLight===!0?c:a,e.localClippingEnabled&&R.clipShadows===!0&&Array.isArray(R.clippingPlanes)&&R.clippingPlanes.length!==0||R.displacementMap&&R.displacementScale!==0||R.alphaMap&&R.alphaTest>0||R.map&&R.alphaTest>0||R.alphaToCoverage===!0){let z=F.uuid,J=R.uuid,O=l[z];if(O===void 0)O={},l[z]=O;let H=O[J];if(H===void 0)H=F.clone(),O[J]=H,R.addEventListener("dispose",w);F=H}if(F.visible=R.visible,F.wireframe=R.wireframe,S===kr)F.side=R.shadowSide!==null?R.shadowSide:R.side;else F.side=R.shadowSide!==null?R.shadowSide:f[R.side];if(F.alphaMap=R.alphaMap,F.alphaTest=R.alphaToCoverage===!0?0.5:R.alphaTest,F.map=R.map,F.clipShadows=R.clipShadows,F.clippingPlanes=R.clippingPlanes,F.clipIntersection=R.clipIntersection,F.displacementMap=R.displacementMap,F.displacementScale=R.displacementScale,F.displacementBias=R.displacementBias,F.wireframeLinewidth=R.wireframeLinewidth,F.linewidth=R.linewidth,_.isPointLight===!0&&F.isMeshDistanceMaterial===!0){let z=e.properties.get(F);z.light=_}return F}function v(E,R,_,S,F){if(E.visible===!1)return;if(E.layers.test(R.layers)&&(E.isMesh||E.isLine||E.isPoints)){if((E.castShadow||E.receiveShadow&&F===kr)&&(!E.frustumCulled||i.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(_.matrixWorldInverse,E.matrixWorld);let J=t.update(E),O=E.material;if(Array.isArray(O)){let H=J.groups;for(let V=0,U=H.length;V<U;V++){let K=H[V],Q=O[K.materialIndex];if(Q&&Q.visible){let se=T(E,Q,S,F);E.onBeforeShadow(e,E,R,_,J,se,K),e.renderBufferDirect(_,null,J,se,E,K),E.onAfterShadow(e,E,R,_,J,se,K)}}}else if(O.visible){let H=T(E,O,S,F);E.onBeforeShadow(e,E,R,_,J,H,null),e.renderBufferDirect(_,null,J,H,E,null),E.onAfterShadow(e,E,R,_,J,H,null)}}}let z=E.children;for(let J=0,O=z.length;J<O;J++)v(z[J],R,_,S,F)}function w(E){E.target.removeEventListener("dispose",w);for(let _ in l){let S=l[_],F=E.target.uuid;if(F in S)S[F].dispose(),delete S[F]}}}function _M(e,t){function n(){let I=!1,oe=new it,Y=null,ae=new it(0,0,0,0);return{setMask:function(ve){if(Y!==ve&&!I)e.colorMask(ve,ve,ve,ve),Y=ve},setLocked:function(ve){I=ve},setClear:function(ve,ee,ce,Oe,yt){if(yt===!0)ve*=Oe,ee*=Oe,ce*=Oe;if(oe.set(ve,ee,ce,Oe),ae.equals(oe)===!1)e.clearColor(ve,ee,ce,Oe),ae.copy(oe)},reset:function(){I=!1,Y=null,ae.set(-1,0,0,0)}}}function i(){let I=!1,oe=!1,Y=null,ae=null,ve=null;return{setReversed:function(ee){if(oe!==ee){let ce=t.get("EXT_clip_control");if(ee)ce.clipControlEXT(ce.LOWER_LEFT_EXT,ce.ZERO_TO_ONE_EXT);else ce.clipControlEXT(ce.LOWER_LEFT_EXT,ce.NEGATIVE_ONE_TO_ONE_EXT);oe=ee;let Oe=ve;ve=null,this.setClear(Oe)}},getReversed:function(){return oe},setTest:function(ee){if(ee)de(e.DEPTH_TEST);else Re(e.DEPTH_TEST)},setMask:function(ee){if(Y!==ee&&!I)e.depthMask(ee),Y=ee},setFunc:function(ee){if(oe)ee=Wf[ee];if(ae!==ee){switch(ee){case _f:e.depthFunc(e.NEVER);break;case xf:e.depthFunc(e.ALWAYS);break;case vf:e.depthFunc(e.LESS);break;case wc:e.depthFunc(e.LEQUAL);break;case yf:e.depthFunc(e.EQUAL);break;case bf:e.depthFunc(e.GEQUAL);break;case Sf:e.depthFunc(e.GREATER);break;case Mf:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}ae=ee}},setLocked:function(ee){I=ee},setClear:function(ee){if(ve!==ee){if(ve=ee,oe)ee=1-ee;e.clearDepth(ee)}},reset:function(){I=!1,Y=null,ae=null,ve=null,oe=!1}}}function r(){let I=!1,oe=null,Y=null,ae=null,ve=null,ee=null,ce=null,Oe=null,yt=null;return{setTest:function(ht){if(!I)if(ht)de(e.STENCIL_TEST);else Re(e.STENCIL_TEST)},setMask:function(ht){if(oe!==ht&&!I)e.stencilMask(ht),oe=ht},setFunc:function(ht,Fn,ni){if(Y!==ht||ae!==Fn||ve!==ni)e.stencilFunc(ht,Fn,ni),Y=ht,ae=Fn,ve=ni},setOp:function(ht,Fn,ni){if(ee!==ht||ce!==Fn||Oe!==ni)e.stencilOp(ht,Fn,ni),ee=ht,ce=Fn,Oe=ni},setLocked:function(ht){I=ht},setClear:function(ht){if(yt!==ht)e.clearStencil(ht),yt=ht},reset:function(){I=!1,oe=null,Y=null,ae=null,ve=null,ee=null,ce=null,Oe=null,yt=null}}}let s=new n,o=new i,a=new r,c=new WeakMap,l=new WeakMap,u={},f={},h={},d=new WeakMap,g=[],b=null,p=!1,m=null,A=null,T=null,v=null,w=null,E=null,R=null,_=new Le(0,0,0),S=0,F=!1,C=null,z=null,J=null,O=null,H=null,V=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),U=!1,K=0,Q=e.getParameter(e.VERSION);if(Q.indexOf("WebGL")!==-1)K=parseFloat(/^WebGL (\d)/.exec(Q)[1]),U=K>=1;else if(Q.indexOf("OpenGL ES")!==-1)K=parseFloat(/^OpenGL ES (\d)/.exec(Q)[1]),U=K>=2;let se=null,me={},_e=e.getParameter(e.SCISSOR_BOX),Xe=e.getParameter(e.VIEWPORT),Be=new it().fromArray(_e),Z=new it().fromArray(Xe);function ne(I,oe,Y,ae){let ve=new Uint8Array(4),ee=e.createTexture();e.bindTexture(I,ee),e.texParameteri(I,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(I,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let ce=0;ce<Y;ce++)if(I===e.TEXTURE_3D||I===e.TEXTURE_2D_ARRAY)e.texImage3D(oe,0,e.RGBA,1,1,ae,0,e.RGBA,e.UNSIGNED_BYTE,ve);else e.texImage2D(oe+ce,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,ve);return ee}let fe={};fe[e.TEXTURE_2D]=ne(e.TEXTURE_2D,e.TEXTURE_2D,1),fe[e.TEXTURE_CUBE_MAP]=ne(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),fe[e.TEXTURE_2D_ARRAY]=ne(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),fe[e.TEXTURE_3D]=ne(e.TEXTURE_3D,e.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),a.setClear(0),de(e.DEPTH_TEST),o.setFunc(wc),pn(!1),pt(yc),de(e.CULL_FACE),je(Vn);function de(I){if(u[I]!==!0)e.enable(I),u[I]=!0}function Re(I){if(u[I]!==!1)e.disable(I),u[I]=!1}function $e(I,oe){if(h[I]!==oe){if(e.bindFramebuffer(I,oe),h[I]=oe,I===e.DRAW_FRAMEBUFFER)h[e.FRAMEBUFFER]=oe;if(I===e.FRAMEBUFFER)h[e.DRAW_FRAMEBUFFER]=oe;return!0}return!1}function Ue(I,oe){let Y=g,ae=!1;if(I){if(Y=d.get(oe),Y===void 0)Y=[],d.set(oe,Y);let ve=I.textures;if(Y.length!==ve.length||Y[0]!==e.COLOR_ATTACHMENT0){for(let ee=0,ce=ve.length;ee<ce;ee++)Y[ee]=e.COLOR_ATTACHMENT0+ee;Y.length=ve.length,ae=!0}}else if(Y[0]!==e.BACK)Y[0]=e.BACK,ae=!0;if(ae)e.drawBuffers(Y)}function ze(I){if(b!==I)return e.useProgram(I),b=I,!0;return!1}let Je={[Br]:e.FUNC_ADD,[Jh]:e.FUNC_SUBTRACT,[Kh]:e.FUNC_REVERSE_SUBTRACT};Je[Qh]=e.MIN,Je[ef]=e.MAX;let qe={[tf]:e.ZERO,[nf]:e.ONE,[rf]:e.SRC_COLOR,[of]:e.SRC_ALPHA,[ff]:e.SRC_ALPHA_SATURATE,[uf]:e.DST_COLOR,[cf]:e.DST_ALPHA,[sf]:e.ONE_MINUS_SRC_COLOR,[af]:e.ONE_MINUS_SRC_ALPHA,[hf]:e.ONE_MINUS_DST_COLOR,[lf]:e.ONE_MINUS_DST_ALPHA,[df]:e.CONSTANT_COLOR,[pf]:e.ONE_MINUS_CONSTANT_COLOR,[mf]:e.CONSTANT_ALPHA,[gf]:e.ONE_MINUS_CONSTANT_ALPHA};function je(I,oe,Y,ae,ve,ee,ce,Oe,yt,ht){if(I===Vn){if(p===!0)Re(e.BLEND),p=!1;return}if(p===!1)de(e.BLEND),p=!0;if(I!==jh){if(I!==m||ht!==F){if(A!==Br||w!==Br)e.blendEquation(e.FUNC_ADD),A=Br,w=Br;if(ht)switch(I){case xs:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case bc:e.blendFunc(e.ONE,e.ONE);break;case Sc:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case Mc:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:Ne("WebGLState: Invalid blending: ",I);break}else switch(I){case xs:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case bc:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case Sc:Ne("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Mc:Ne("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Ne("WebGLState: Invalid blending: ",I);break}T=null,v=null,E=null,R=null,_.set(0,0,0),S=0,m=I,F=ht}return}if(ve=ve||oe,ee=ee||Y,ce=ce||ae,oe!==A||ve!==w)e.blendEquationSeparate(Je[oe],Je[ve]),A=oe,w=ve;if(Y!==T||ae!==v||ee!==E||ce!==R)e.blendFuncSeparate(qe[Y],qe[ae],qe[ee],qe[ce]),T=Y,v=ae,E=ee,R=ce;if(Oe.equals(_)===!1||yt!==S)e.blendColor(Oe.r,Oe.g,Oe.b,yt),_.copy(Oe),S=yt;m=I,F=!1}function Ut(I,oe){I.side===vn?Re(e.CULL_FACE):de(e.CULL_FACE);let Y=I.side===Xt;if(oe)Y=!Y;pn(Y),I.blending===xs&&I.transparent===!1?je(Vn):je(I.blending,I.blendEquation,I.blendSrc,I.blendDst,I.blendEquationAlpha,I.blendSrcAlpha,I.blendDstAlpha,I.blendColor,I.blendAlpha,I.premultipliedAlpha),o.setFunc(I.depthFunc),o.setTest(I.depthTest),o.setMask(I.depthWrite),s.setMask(I.colorWrite);let ae=I.stencilWrite;if(a.setTest(ae),ae)a.setMask(I.stencilWriteMask),a.setFunc(I.stencilFunc,I.stencilRef,I.stencilFuncMask),a.setOp(I.stencilFail,I.stencilZFail,I.stencilZPass);Ot(I.polygonOffset,I.polygonOffsetFactor,I.polygonOffsetUnits),I.alphaToCoverage===!0?de(e.SAMPLE_ALPHA_TO_COVERAGE):Re(e.SAMPLE_ALPHA_TO_COVERAGE)}function pn(I){if(C!==I){if(I)e.frontFace(e.CW);else e.frontFace(e.CCW);C=I}}function pt(I){if(I!==Xh){if(de(e.CULL_FACE),I!==z)if(I===yc)e.cullFace(e.BACK);else if(I===qh)e.cullFace(e.FRONT);else e.cullFace(e.FRONT_AND_BACK)}else Re(e.CULL_FACE);z=I}function Gt(I){if(I!==J){if(U)e.lineWidth(I);J=I}}function Ot(I,oe,Y){if(I){if(de(e.POLYGON_OFFSET_FILL),O!==oe||H!==Y){if(O=oe,H=Y,o.getReversed())oe=-oe;e.polygonOffset(oe,Y)}}else Re(e.POLYGON_OFFSET_FILL)}function Ct(I){if(I)de(e.SCISSOR_TEST);else Re(e.SCISSOR_TEST)}function L(I){if(I===void 0)I=e.TEXTURE0+V-1;if(se!==I)e.activeTexture(I),se=I}function mn(I,oe,Y){if(Y===void 0)if(se===null)Y=e.TEXTURE0+V-1;else Y=se;let ae=me[Y];if(ae===void 0)ae={type:void 0,texture:void 0},me[Y]=ae;if(ae.type!==I||ae.texture!==oe){if(se!==Y)e.activeTexture(Y),se=Y;e.bindTexture(I,oe||fe[I]),ae.type=I,ae.texture=oe}}function tt(){let I=me[se];if(I!==void 0&&I.type!==void 0)e.bindTexture(I.type,null),I.type=void 0,I.texture=void 0}function mt(){try{e.compressedTexImage2D(...arguments)}catch(I){Ne("WebGLState:",I)}}function M(){try{e.compressedTexImage3D(...arguments)}catch(I){Ne("WebGLState:",I)}}function x(){try{e.texSubImage2D(...arguments)}catch(I){Ne("WebGLState:",I)}}function P(){try{e.texSubImage3D(...arguments)}catch(I){Ne("WebGLState:",I)}}function W(){try{e.compressedTexSubImage2D(...arguments)}catch(I){Ne("WebGLState:",I)}}function te(){try{e.compressedTexSubImage3D(...arguments)}catch(I){Ne("WebGLState:",I)}}function ie(){try{e.texStorage2D(...arguments)}catch(I){Ne("WebGLState:",I)}}function le(){try{e.texStorage3D(...arguments)}catch(I){Ne("WebGLState:",I)}}function X(){try{e.texImage2D(...arguments)}catch(I){Ne("WebGLState:",I)}}function j(){try{e.texImage3D(...arguments)}catch(I){Ne("WebGLState:",I)}}function xe(I){if(f[I]!==void 0)return f[I];else return e.getParameter(I)}function we(I,oe){if(f[I]!==oe)e.pixelStorei(I,oe),f[I]=oe}function ue(I){if(Be.equals(I)===!1)e.scissor(I.x,I.y,I.z,I.w),Be.copy(I)}function re(I){if(Z.equals(I)===!1)e.viewport(I.x,I.y,I.z,I.w),Z.copy(I)}function Ce(I,oe){let Y=l.get(oe);if(Y===void 0)Y=new WeakMap,l.set(oe,Y);let ae=Y.get(I);if(ae===void 0)ae=e.getUniformBlockIndex(oe,I.name),Y.set(I,ae)}function Ie(I,oe){let ae=l.get(oe).get(I);if(c.get(oe)!==ae)e.uniformBlockBinding(oe,ae,I.__bindingPointIndex),c.set(oe,ae)}function Qe(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},f={},se=null,me={},h={},d=new WeakMap,g=[],b=null,p=!1,m=null,A=null,T=null,v=null,w=null,E=null,R=null,_=new Le(0,0,0),S=0,F=!1,C=null,z=null,J=null,O=null,H=null,Be.set(0,0,e.canvas.width,e.canvas.height),Z.set(0,0,e.canvas.width,e.canvas.height),s.reset(),o.reset(),a.reset()}return{buffers:{color:s,depth:o,stencil:a},enable:de,disable:Re,bindFramebuffer:$e,drawBuffers:Ue,useProgram:ze,setBlending:je,setMaterial:Ut,setFlipSided:pn,setCullFace:pt,setLineWidth:Gt,setPolygonOffset:Ot,setScissorTest:Ct,activeTexture:L,bindTexture:mn,unbindTexture:tt,compressedTexImage2D:mt,compressedTexImage3D:M,texImage2D:X,texImage3D:j,pixelStorei:we,getParameter:xe,updateUBOMapping:Ce,uniformBlockBinding:Ie,texStorage2D:ie,texStorage3D:le,texSubImage2D:x,texSubImage3D:P,compressedTexSubImage2D:W,compressedTexSubImage3D:te,scissor:ue,viewport:re,reset:Qe}}function xM(e,t,n,i,r,s,o){let a=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Pe,u=new WeakMap,f=new Set,h,d=new WeakMap,g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch(M){}function b(M,x){return g?new OffscreenCanvas(M,x):Or("canvas")}function p(M,x,P){let W=1,te=mt(M);if(te.width>P||te.height>P)W=P/Math.max(te.width,te.height);if(W<1)if(typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&M instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&M instanceof ImageBitmap||typeof VideoFrame<"u"&&M instanceof VideoFrame){let ie=Math.floor(W*te.width),le=Math.floor(W*te.height);if(h===void 0)h=b(ie,le);let X=x?b(ie,le):h;return X.width=ie,X.height=le,X.getContext("2d").drawImage(M,0,0,ie,le),Me("WebGLRenderer: Texture has been resized from ("+te.width+"x"+te.height+") to ("+ie+"x"+le+")."),X}else{if("data"in M)Me("WebGLRenderer: Image in DataTexture is too big ("+te.width+"x"+te.height+").");return M}return M}function m(M){return M.generateMipmaps}function A(M){e.generateMipmap(M)}function T(M){if(M.isWebGLCubeRenderTarget)return e.TEXTURE_CUBE_MAP;if(M.isWebGL3DRenderTarget)return e.TEXTURE_3D;if(M.isWebGLArrayRenderTarget||M.isCompressedArrayTexture)return e.TEXTURE_2D_ARRAY;return e.TEXTURE_2D}function v(M,x,P,W,te,ie=!1){if(M!==null){if(e[M]!==void 0)return e[M];Me("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+M+"'")}let le;if(W){if(le=t.get("EXT_texture_norm16"),!le)Me("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension")}let X=x;if(x===e.RED){if(P===e.FLOAT)X=e.R32F;if(P===e.HALF_FLOAT)X=e.R16F;if(P===e.UNSIGNED_BYTE)X=e.R8;if(P===e.UNSIGNED_SHORT&&le)X=le.R16_EXT;if(P===e.SHORT&&le)X=le.R16_SNORM_EXT}if(x===e.RED_INTEGER){if(P===e.UNSIGNED_BYTE)X=e.R8UI;if(P===e.UNSIGNED_SHORT)X=e.R16UI;if(P===e.UNSIGNED_INT)X=e.R32UI;if(P===e.BYTE)X=e.R8I;if(P===e.SHORT)X=e.R16I;if(P===e.INT)X=e.R32I}if(x===e.RG){if(P===e.FLOAT)X=e.RG32F;if(P===e.HALF_FLOAT)X=e.RG16F;if(P===e.UNSIGNED_BYTE)X=e.RG8;if(P===e.UNSIGNED_SHORT&&le)X=le.RG16_EXT;if(P===e.SHORT&&le)X=le.RG16_SNORM_EXT}if(x===e.RG_INTEGER){if(P===e.UNSIGNED_BYTE)X=e.RG8UI;if(P===e.UNSIGNED_SHORT)X=e.RG16UI;if(P===e.UNSIGNED_INT)X=e.RG32UI;if(P===e.BYTE)X=e.RG8I;if(P===e.SHORT)X=e.RG16I;if(P===e.INT)X=e.RG32I}if(x===e.RGB_INTEGER){if(P===e.UNSIGNED_BYTE)X=e.RGB8UI;if(P===e.UNSIGNED_SHORT)X=e.RGB16UI;if(P===e.UNSIGNED_INT)X=e.RGB32UI;if(P===e.BYTE)X=e.RGB8I;if(P===e.SHORT)X=e.RGB16I;if(P===e.INT)X=e.RGB32I}if(x===e.RGBA_INTEGER){if(P===e.UNSIGNED_BYTE)X=e.RGBA8UI;if(P===e.UNSIGNED_SHORT)X=e.RGBA16UI;if(P===e.UNSIGNED_INT)X=e.RGBA32UI;if(P===e.BYTE)X=e.RGBA8I;if(P===e.SHORT)X=e.RGBA16I;if(P===e.INT)X=e.RGBA32I}if(x===e.RGB){if(P===e.UNSIGNED_SHORT&&le)X=le.RGB16_EXT;if(P===e.SHORT&&le)X=le.RGB16_SNORM_EXT;if(P===e.UNSIGNED_INT_5_9_9_9_REV)X=e.RGB9_E5;if(P===e.UNSIGNED_INT_10F_11F_11F_REV)X=e.R11F_G11F_B10F}if(x===e.RGBA){let j=ie?gl:Ve.getTransfer(te);if(P===e.FLOAT)X=e.RGBA32F;if(P===e.HALF_FLOAT)X=e.RGBA16F;if(P===e.UNSIGNED_BYTE)X=j===ut?e.SRGB8_ALPHA8:e.RGBA8;if(P===e.UNSIGNED_SHORT&&le)X=le.RGBA16_EXT;if(P===e.SHORT&&le)X=le.RGBA16_SNORM_EXT;if(P===e.UNSIGNED_SHORT_4_4_4_4)X=e.RGBA4;if(P===e.UNSIGNED_SHORT_5_5_5_1)X=e.RGB5_A1}if(X===e.R16F||X===e.R32F||X===e.RG16F||X===e.RG32F||X===e.RGBA16F||X===e.RGBA32F)t.get("EXT_color_buffer_float");return X}function w(M,x){let P;if(M){if(x===null||x===Ci||x===$r)P=e.DEPTH24_STENCIL8;else if(x===ui)P=e.DEPTH32F_STENCIL8;else if(x===bs)P=e.DEPTH24_STENCIL8,Me("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")}else if(x===null||x===Ci||x===$r)P=e.DEPTH_COMPONENT24;else if(x===ui)P=e.DEPTH_COMPONENT32F;else if(x===bs)P=e.DEPTH_COMPONENT16;return P}function E(M,x){if(m(M)===!0||M.isFramebufferTexture&&M.minFilter!==In&&M.minFilter!==kt)return Math.log2(Math.max(x.width,x.height))+1;else if(M.mipmaps!==void 0&&M.mipmaps.length>0)return M.mipmaps.length;else if(M.isCompressedTexture&&Array.isArray(M.image))return x.mipmaps.length;else return 1}function R(M){let x=M.target;if(x.removeEventListener("dispose",R),S(x),x.isVideoTexture)u.delete(x);if(x.isHTMLTexture)f.delete(x)}function _(M){let x=M.target;x.removeEventListener("dispose",_),C(x)}function S(M){let x=i.get(M);if(x.__webglInit===void 0)return;let P=M.source,W=d.get(P);if(W){let te=W[x.__cacheKey];if(te.usedTimes--,te.usedTimes===0)F(M);if(Object.keys(W).length===0)d.delete(P)}i.remove(M)}function F(M){let x=i.get(M);e.deleteTexture(x.__webglTexture);let P=M.source,W=d.get(P);delete W[x.__cacheKey],o.memory.textures--}function C(M){let x=i.get(M);if(M.depthTexture)M.depthTexture.dispose(),i.remove(M.depthTexture);if(M.isWebGLCubeRenderTarget)for(let W=0;W<6;W++){if(Array.isArray(x.__webglFramebuffer[W]))for(let te=0;te<x.__webglFramebuffer[W].length;te++)e.deleteFramebuffer(x.__webglFramebuffer[W][te]);else e.deleteFramebuffer(x.__webglFramebuffer[W]);if(x.__webglDepthbuffer)e.deleteRenderbuffer(x.__webglDepthbuffer[W])}else{if(Array.isArray(x.__webglFramebuffer))for(let W=0;W<x.__webglFramebuffer.length;W++)e.deleteFramebuffer(x.__webglFramebuffer[W]);else e.deleteFramebuffer(x.__webglFramebuffer);if(x.__webglDepthbuffer)e.deleteRenderbuffer(x.__webglDepthbuffer);if(x.__webglMultisampledFramebuffer)e.deleteFramebuffer(x.__webglMultisampledFramebuffer);if(x.__webglColorRenderbuffer){for(let W=0;W<x.__webglColorRenderbuffer.length;W++)if(x.__webglColorRenderbuffer[W])e.deleteRenderbuffer(x.__webglColorRenderbuffer[W])}if(x.__webglDepthRenderbuffer)e.deleteRenderbuffer(x.__webglDepthRenderbuffer)}let P=M.textures;for(let W=0,te=P.length;W<te;W++){let ie=i.get(P[W]);if(ie.__webglTexture)e.deleteTexture(ie.__webglTexture),o.memory.textures--;i.remove(P[W])}i.remove(M)}let z=0;function J(){z=0}function O(){return z}function H(M){z=M}function V(){let M=z;if(M>=r.maxTextures)Me("WebGLTextures: Trying to use "+M+" texture units while this GPU supports only "+r.maxTextures);return z+=1,M}function U(M){let x=[];return x.push(M.wrapS),x.push(M.wrapT),x.push(M.wrapR||0),x.push(M.magFilter),x.push(M.minFilter),x.push(M.anisotropy),x.push(M.internalFormat),x.push(M.format),x.push(M.type),x.push(M.generateMipmaps),x.push(M.premultiplyAlpha),x.push(M.flipY),x.push(M.unpackAlignment),x.push(M.colorSpace),x.join()}function K(M,x){let P=i.get(M);if(M.isVideoTexture)mn(M);if(M.isRenderTargetTexture===!1&&M.isExternalTexture!==!0&&M.version>0&&P.__version!==M.version){let W=M.image;if(W===null)Me("WebGLRenderer: Texture marked for update but no image data found.");else if(W.complete===!1)Me("WebGLRenderer: Texture marked for update but image is incomplete");else{Re(P,M,x);return}}else if(M.isExternalTexture)P.__webglTexture=M.sourceTexture?M.sourceTexture:null;n.bindTexture(e.TEXTURE_2D,P.__webglTexture,e.TEXTURE0+x)}function Q(M,x){let P=i.get(M);if(M.isRenderTargetTexture===!1&&M.version>0&&P.__version!==M.version){Re(P,M,x);return}else if(M.isExternalTexture)P.__webglTexture=M.sourceTexture?M.sourceTexture:null;n.bindTexture(e.TEXTURE_2D_ARRAY,P.__webglTexture,e.TEXTURE0+x)}function se(M,x){let P=i.get(M);if(M.isRenderTargetTexture===!1&&M.version>0&&P.__version!==M.version){Re(P,M,x);return}n.bindTexture(e.TEXTURE_3D,P.__webglTexture,e.TEXTURE0+x)}function me(M,x){let P=i.get(M);if(M.isCubeDepthTexture!==!0&&M.version>0&&P.__version!==M.version){$e(P,M,x);return}n.bindTexture(e.TEXTURE_CUBE_MAP,P.__webglTexture,e.TEXTURE0+x)}let _e={[Hr]:e.REPEAT,[Vr]:e.CLAMP_TO_EDGE,[zo]:e.MIRRORED_REPEAT},Xe={[In]:e.NEAREST,[ko]:e.NEAREST_MIPMAP_NEAREST,[ir]:e.NEAREST_MIPMAP_LINEAR,[kt]:e.LINEAR,[Wr]:e.LINEAR_MIPMAP_NEAREST,[Wn]:e.LINEAR_MIPMAP_LINEAR},Be={[Uf]:e.NEVER,[Bf]:e.ALWAYS,[Of]:e.LESS,[Xo]:e.LEQUAL,[Ff]:e.EQUAL,[qo]:e.GEQUAL,[zf]:e.GREATER,[kf]:e.NOTEQUAL};function Z(M,x){if(x.type===ui&&t.has("OES_texture_float_linear")===!1&&(x.magFilter===kt||x.magFilter===Wr||x.magFilter===ir||x.magFilter===Wn||x.minFilter===kt||x.minFilter===Wr||x.minFilter===ir||x.minFilter===Wn))Me("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.");if(e.texParameteri(M,e.TEXTURE_WRAP_S,_e[x.wrapS]),e.texParameteri(M,e.TEXTURE_WRAP_T,_e[x.wrapT]),M===e.TEXTURE_3D||M===e.TEXTURE_2D_ARRAY)e.texParameteri(M,e.TEXTURE_WRAP_R,_e[x.wrapR]);if(e.texParameteri(M,e.TEXTURE_MAG_FILTER,Xe[x.magFilter]),e.texParameteri(M,e.TEXTURE_MIN_FILTER,Xe[x.minFilter]),x.compareFunction)e.texParameteri(M,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(M,e.TEXTURE_COMPARE_FUNC,Be[x.compareFunction]);if(t.has("EXT_texture_filter_anisotropic")===!0){if(x.magFilter===In)return;if(x.minFilter!==ir&&x.minFilter!==Wn)return;if(x.type===ui&&t.has("OES_texture_float_linear")===!1)return;if(x.anisotropy>1||i.get(x).__currentAnisotropy){let P=t.get("EXT_texture_filter_anisotropic");e.texParameterf(M,P.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(x.anisotropy,r.getMaxAnisotropy())),i.get(x).__currentAnisotropy=x.anisotropy}}}function ne(M,x){let P=!1;if(M.__webglInit===void 0)M.__webglInit=!0,x.addEventListener("dispose",R);let W=x.source,te=d.get(W);if(te===void 0)te={},d.set(W,te);let ie=U(x);if(ie!==M.__cacheKey){if(te[ie]===void 0)te[ie]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,P=!0;te[ie].usedTimes++;let le=te[M.__cacheKey];if(le!==void 0){if(te[M.__cacheKey].usedTimes--,le.usedTimes===0)F(x)}M.__cacheKey=ie,M.__webglTexture=te[ie].texture}return P}function fe(M,x,P){return Math.floor(Math.floor(M/P)/x)}function de(M,x,P,W){let ie=M.updateRanges;if(ie.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,x.width,x.height,P,W,x.data);else{ie.sort((we,ue)=>we.start-ue.start);let le=0;for(let we=1;we<ie.length;we++){let ue=ie[le],re=ie[we],Ce=ue.start+ue.count,Ie=fe(re.start,x.width,4),Qe=fe(ue.start,x.width,4);if(re.start<=Ce+1&&Ie===Qe&&fe(re.start+re.count-1,x.width,4)===Ie)ue.count=Math.max(ue.count,re.start+re.count-ue.start);else++le,ie[le]=re}ie.length=le+1;let X=n.getParameter(e.UNPACK_ROW_LENGTH),j=n.getParameter(e.UNPACK_SKIP_PIXELS),xe=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,x.width);for(let we=0,ue=ie.length;we<ue;we++){let re=ie[we],Ce=Math.floor(re.start/4),Ie=Math.ceil(re.count/4),Qe=Ce%x.width,I=Math.floor(Ce/x.width),oe=Ie,Y=1;n.pixelStorei(e.UNPACK_SKIP_PIXELS,Qe),n.pixelStorei(e.UNPACK_SKIP_ROWS,I),n.texSubImage2D(e.TEXTURE_2D,0,Qe,I,oe,1,P,W,x.data)}M.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,X),n.pixelStorei(e.UNPACK_SKIP_PIXELS,j),n.pixelStorei(e.UNPACK_SKIP_ROWS,xe)}}function Re(M,x,P){let W=e.TEXTURE_2D;if(x.isDataArrayTexture||x.isCompressedArrayTexture)W=e.TEXTURE_2D_ARRAY;if(x.isData3DTexture)W=e.TEXTURE_3D;let te=ne(M,x),ie=x.source;n.bindTexture(W,M.__webglTexture,e.TEXTURE0+P);let le=i.get(ie);if(ie.version!==le.__version||te===!0){if(n.activeTexture(e.TEXTURE0+P),(typeof ImageBitmap<"u"&&x.image instanceof ImageBitmap)===!1){let Y=Ve.getPrimaries(Ve.workingColorSpace),ae=x.colorSpace===ar?null:Ve.getPrimaries(x.colorSpace),ve=x.colorSpace===ar||Y===ae?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,x.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,ve)}n.pixelStorei(e.UNPACK_ALIGNMENT,x.unpackAlignment);let j=p(x.image,!1,r.maxTextureSize);j=tt(x,j);let xe=s.convert(x.format,x.colorSpace),we=s.convert(x.type),ue=v(x.internalFormat,xe,we,x.normalized,x.colorSpace,x.isVideoTexture);Z(W,x);let re,Ce=x.mipmaps,Ie=x.isVideoTexture!==!0,Qe=le.__version===void 0||te===!0,I=ie.dataReady,oe=E(x,j);if(x.isDepthTexture){if(ue=w(x.format===sr,x.type),Qe)if(Ie)n.texStorage2D(e.TEXTURE_2D,1,ue,j.width,j.height);else n.texImage2D(e.TEXTURE_2D,0,ue,j.width,j.height,0,xe,we,null)}else if(x.isDataTexture)if(Ce.length>0){if(Ie&&Qe)n.texStorage2D(e.TEXTURE_2D,oe,ue,Ce[0].width,Ce[0].height);for(let Y=0,ae=Ce.length;Y<ae;Y++)if(re=Ce[Y],Ie){if(I)n.texSubImage2D(e.TEXTURE_2D,Y,0,0,re.width,re.height,xe,we,re.data)}else n.texImage2D(e.TEXTURE_2D,Y,ue,re.width,re.height,0,xe,we,re.data);x.generateMipmaps=!1}else if(Ie){if(Qe)n.texStorage2D(e.TEXTURE_2D,oe,ue,j.width,j.height);if(I)de(x,j,xe,we)}else n.texImage2D(e.TEXTURE_2D,0,ue,j.width,j.height,0,xe,we,j.data);else if(x.isCompressedTexture)if(x.isCompressedArrayTexture){if(Ie&&Qe)n.texStorage3D(e.TEXTURE_2D_ARRAY,oe,ue,Ce[0].width,Ce[0].height,j.depth);for(let Y=0,ae=Ce.length;Y<ae;Y++)if(re=Ce[Y],x.format!==$n)if(xe!==null)if(Ie){if(I)if(x.layerUpdates.size>0){let ve=Bl(re.width,re.height,x.format,x.type);for(let ee of x.layerUpdates){let ce=re.data.subarray(ee*ve/re.data.BYTES_PER_ELEMENT,(ee+1)*ve/re.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,Y,0,0,ee,re.width,re.height,1,xe,ce)}x.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,Y,0,0,0,re.width,re.height,j.depth,xe,re.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,Y,ue,re.width,re.height,j.depth,0,re.data,0,0);else Me("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(Ie){if(I)n.texSubImage3D(e.TEXTURE_2D_ARRAY,Y,0,0,0,re.width,re.height,j.depth,xe,we,re.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,Y,ue,re.width,re.height,j.depth,0,xe,we,re.data)}else{if(Ie&&Qe)n.texStorage2D(e.TEXTURE_2D,oe,ue,Ce[0].width,Ce[0].height);for(let Y=0,ae=Ce.length;Y<ae;Y++)if(re=Ce[Y],x.format!==$n)if(xe!==null)if(Ie){if(I)n.compressedTexSubImage2D(e.TEXTURE_2D,Y,0,0,re.width,re.height,xe,re.data)}else n.compressedTexImage2D(e.TEXTURE_2D,Y,ue,re.width,re.height,0,re.data);else Me("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(Ie){if(I)n.texSubImage2D(e.TEXTURE_2D,Y,0,0,re.width,re.height,xe,we,re.data)}else n.texImage2D(e.TEXTURE_2D,Y,ue,re.width,re.height,0,xe,we,re.data)}else if(x.isDataArrayTexture)if(Ie){if(Qe)n.texStorage3D(e.TEXTURE_2D_ARRAY,oe,ue,j.width,j.height,j.depth);if(I)if(x.layerUpdates.size>0){let Y=Bl(j.width,j.height,x.format,x.type);for(let ae of x.layerUpdates){let ve=j.data.subarray(ae*Y/j.data.BYTES_PER_ELEMENT,(ae+1)*Y/j.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,ae,j.width,j.height,1,xe,we,ve)}x.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,j.width,j.height,j.depth,xe,we,j.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,ue,j.width,j.height,j.depth,0,xe,we,j.data);else if(x.isData3DTexture)if(Ie){if(Qe)n.texStorage3D(e.TEXTURE_3D,oe,ue,j.width,j.height,j.depth);if(I)n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,j.width,j.height,j.depth,xe,we,j.data)}else n.texImage3D(e.TEXTURE_3D,0,ue,j.width,j.height,j.depth,0,xe,we,j.data);else if(x.isFramebufferTexture){if(Qe)if(Ie)n.texStorage2D(e.TEXTURE_2D,oe,ue,j.width,j.height);else{let Y=j.width,ae=j.height;for(let ve=0;ve<oe;ve++)n.texImage2D(e.TEXTURE_2D,ve,ue,Y,ae,0,xe,we,null),Y>>=1,ae>>=1}}else if(x.isHTMLTexture){if("texElementImage2D"in e){let Y=e.canvas;if(!Y.hasAttribute("layoutsubtree"))Y.setAttribute("layoutsubtree","true");if(j.parentNode!==Y){Y.appendChild(j),f.add(x),Y.onpaint=(ae)=>{let ve=ae.changedElements;for(let ee of f)if(ve.includes(ee.image))ee.needsUpdate=!0},Y.requestPaint();return}if(e.texElementImage2D.length===3)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,j);else{let{RGBA:ve,RGBA:ee,UNSIGNED_BYTE:ce}=e;e.texElementImage2D(e.TEXTURE_2D,0,ve,ee,ce,j)}e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(Ce.length>0){if(Ie&&Qe){let Y=mt(Ce[0]);n.texStorage2D(e.TEXTURE_2D,oe,ue,Y.width,Y.height)}for(let Y=0,ae=Ce.length;Y<ae;Y++)if(re=Ce[Y],Ie){if(I)n.texSubImage2D(e.TEXTURE_2D,Y,0,0,xe,we,re)}else n.texImage2D(e.TEXTURE_2D,Y,ue,xe,we,re);x.generateMipmaps=!1}else if(Ie){if(Qe){let Y=mt(j);n.texStorage2D(e.TEXTURE_2D,oe,ue,Y.width,Y.height)}if(I)n.texSubImage2D(e.TEXTURE_2D,0,0,0,xe,we,j)}else n.texImage2D(e.TEXTURE_2D,0,ue,xe,we,j);if(m(x))A(W);if(le.__version=ie.version,x.onUpdate)x.onUpdate(x)}M.__version=x.version}function $e(M,x,P){if(x.image.length!==6)return;let W=ne(M,x),te=x.source;n.bindTexture(e.TEXTURE_CUBE_MAP,M.__webglTexture,e.TEXTURE0+P);let ie=i.get(te);if(te.version!==ie.__version||W===!0){n.activeTexture(e.TEXTURE0+P);let le=Ve.getPrimaries(Ve.workingColorSpace),X=x.colorSpace===ar?null:Ve.getPrimaries(x.colorSpace),j=x.colorSpace===ar||le===X?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,x.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,x.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,j);let xe=x.isCompressedTexture||x.image[0].isCompressedTexture,we=x.image[0]&&x.image[0].isDataTexture,ue=[];for(let ee=0;ee<6;ee++){if(!xe&&!we)ue[ee]=p(x.image[ee],!0,r.maxCubemapSize);else ue[ee]=we?x.image[ee].image:x.image[ee];ue[ee]=tt(x,ue[ee])}let re=ue[0],Ce=s.convert(x.format,x.colorSpace),Ie=s.convert(x.type),Qe=v(x.internalFormat,Ce,Ie,x.normalized,x.colorSpace),I=x.isVideoTexture!==!0,oe=ie.__version===void 0||W===!0,Y=te.dataReady,ae=E(x,re);Z(e.TEXTURE_CUBE_MAP,x);let ve;if(xe){if(I&&oe)n.texStorage2D(e.TEXTURE_CUBE_MAP,ae,Qe,re.width,re.height);for(let ee=0;ee<6;ee++){ve=ue[ee].mipmaps;for(let ce=0;ce<ve.length;ce++){let Oe=ve[ce];if(x.format!==$n)if(Ce!==null)if(I){if(Y)n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce,0,0,Oe.width,Oe.height,Ce,Oe.data)}else n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce,Qe,Oe.width,Oe.height,0,Oe.data);else Me("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()");else if(I){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce,0,0,Oe.width,Oe.height,Ce,Ie,Oe.data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce,Qe,Oe.width,Oe.height,0,Ce,Ie,Oe.data)}}}else{if(ve=x.mipmaps,I&&oe){if(ve.length>0)ae++;let ee=mt(ue[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,ae,Qe,ee.width,ee.height)}for(let ee=0;ee<6;ee++)if(we){if(I){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,0,0,0,ue[ee].width,ue[ee].height,Ce,Ie,ue[ee].data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,0,Qe,ue[ee].width,ue[ee].height,0,Ce,Ie,ue[ee].data);for(let ce=0;ce<ve.length;ce++){let yt=ve[ce].image[ee].image;if(I){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce+1,0,0,yt.width,yt.height,Ce,Ie,yt.data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce+1,Qe,yt.width,yt.height,0,Ce,Ie,yt.data)}}else{if(I){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,0,0,0,Ce,Ie,ue[ee])}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,0,Qe,Ce,Ie,ue[ee]);for(let ce=0;ce<ve.length;ce++){let Oe=ve[ce];if(I){if(Y)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce+1,0,0,Ce,Ie,Oe.image[ee])}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+ee,ce+1,Qe,Ce,Ie,Oe.image[ee])}}}if(m(x))A(e.TEXTURE_CUBE_MAP);if(ie.__version=te.version,x.onUpdate)x.onUpdate(x)}M.__version=x.version}function Ue(M,x,P,W,te,ie){let le=s.convert(P.format,P.colorSpace),X=s.convert(P.type),j=v(P.internalFormat,le,X,P.normalized,P.colorSpace),xe=i.get(x),we=i.get(P);if(we.__renderTarget=x,!xe.__hasExternalTextures){let ue=Math.max(1,x.width>>ie),re=Math.max(1,x.height>>ie);if(te===e.TEXTURE_3D||te===e.TEXTURE_2D_ARRAY)n.texImage3D(te,ie,j,ue,re,x.depth,0,le,X,null);else n.texImage2D(te,ie,j,ue,re,0,le,X,null)}if(n.bindFramebuffer(e.FRAMEBUFFER,M),L(x))a.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,W,te,we.__webglTexture,0,Ct(x));else if(te===e.TEXTURE_2D||te>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&te<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)e.framebufferTexture2D(e.FRAMEBUFFER,W,te,we.__webglTexture,ie);n.bindFramebuffer(e.FRAMEBUFFER,null)}function ze(M,x,P){if(e.bindRenderbuffer(e.RENDERBUFFER,M),x.depthBuffer){let W=x.depthTexture,te=W&&W.isDepthTexture?W.type:null,ie=w(x.stencilBuffer,te),le=x.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(L(x))a.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ct(x),ie,x.width,x.height);else if(P)e.renderbufferStorageMultisample(e.RENDERBUFFER,Ct(x),ie,x.width,x.height);else e.renderbufferStorage(e.RENDERBUFFER,ie,x.width,x.height);e.framebufferRenderbuffer(e.FRAMEBUFFER,le,e.RENDERBUFFER,M)}else{let W=x.textures;for(let te=0;te<W.length;te++){let ie=W[te],le=s.convert(ie.format,ie.colorSpace),X=s.convert(ie.type),j=v(ie.internalFormat,le,X,ie.normalized,ie.colorSpace);if(L(x))a.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ct(x),j,x.width,x.height);else if(P)e.renderbufferStorageMultisample(e.RENDERBUFFER,Ct(x),j,x.width,x.height);else e.renderbufferStorage(e.RENDERBUFFER,j,x.width,x.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function Je(M,x,P){let W=x.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,M),!(x.depthTexture&&x.depthTexture.isDepthTexture))throw Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");let te=i.get(x.depthTexture);if(te.__renderTarget=x,!te.__webglTexture||x.depthTexture.image.width!==x.width||x.depthTexture.image.height!==x.height)x.depthTexture.image.width=x.width,x.depthTexture.image.height=x.height,x.depthTexture.needsUpdate=!0;if(W){if(te.__webglInit===void 0)te.__webglInit=!0,x.depthTexture.addEventListener("dispose",R);if(te.__webglTexture===void 0){te.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,te.__webglTexture),Z(e.TEXTURE_CUBE_MAP,x.depthTexture);let xe=s.convert(x.depthTexture.format),we=s.convert(x.depthTexture.type),ue;if(x.depthTexture.format===rr)ue=e.DEPTH_COMPONENT24;else if(x.depthTexture.format===sr)ue=e.DEPTH24_STENCIL8;for(let re=0;re<6;re++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+re,0,ue,x.width,x.height,0,xe,we,null)}}else K(x.depthTexture,0);let ie=te.__webglTexture,le=Ct(x),X=W?e.TEXTURE_CUBE_MAP_POSITIVE_X+P:e.TEXTURE_2D,j=x.depthTexture.format===sr?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(x.depthTexture.format===rr)if(L(x))a.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,j,X,ie,0,le);else e.framebufferTexture2D(e.FRAMEBUFFER,j,X,ie,0);else if(x.depthTexture.format===sr)if(L(x))a.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,j,X,ie,0,le);else e.framebufferTexture2D(e.FRAMEBUFFER,j,X,ie,0);else throw Error("THREE.WebGLTextures: Unknown depthTexture format.")}function qe(M){let x=i.get(M),P=M.isWebGLCubeRenderTarget===!0;if(x.__boundDepthTexture!==M.depthTexture){let W=M.depthTexture;if(x.__depthDisposeCallback)x.__depthDisposeCallback();if(W){let te=()=>{delete x.__boundDepthTexture,delete x.__depthDisposeCallback,W.removeEventListener("dispose",te)};W.addEventListener("dispose",te),x.__depthDisposeCallback=te}x.__boundDepthTexture=W}if(M.depthTexture&&!x.__autoAllocateDepthBuffer)if(P)for(let W=0;W<6;W++)Je(x.__webglFramebuffer[W],M,W);else{let W=M.texture.mipmaps;if(W&&W.length>0)Je(x.__webglFramebuffer[0],M,0);else Je(x.__webglFramebuffer,M,0)}else if(P){x.__webglDepthbuffer=[];for(let W=0;W<6;W++)if(n.bindFramebuffer(e.FRAMEBUFFER,x.__webglFramebuffer[W]),x.__webglDepthbuffer[W]===void 0)x.__webglDepthbuffer[W]=e.createRenderbuffer(),ze(x.__webglDepthbuffer[W],M,!1);else{let te=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ie=x.__webglDepthbuffer[W];e.bindRenderbuffer(e.RENDERBUFFER,ie),e.framebufferRenderbuffer(e.FRAMEBUFFER,te,e.RENDERBUFFER,ie)}}else{let W=M.texture.mipmaps;if(W&&W.length>0)n.bindFramebuffer(e.FRAMEBUFFER,x.__webglFramebuffer[0]);else n.bindFramebuffer(e.FRAMEBUFFER,x.__webglFramebuffer);if(x.__webglDepthbuffer===void 0)x.__webglDepthbuffer=e.createRenderbuffer(),ze(x.__webglDepthbuffer,M,!1);else{let te=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ie=x.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,ie),e.framebufferRenderbuffer(e.FRAMEBUFFER,te,e.RENDERBUFFER,ie)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function je(M,x,P){let W=i.get(M);if(x!==void 0)Ue(W.__webglFramebuffer,M,M.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0);if(P!==void 0)qe(M)}function Ut(M){let x=M.texture,P=i.get(M),W=i.get(x);M.addEventListener("dispose",_);let te=M.textures,ie=M.isWebGLCubeRenderTarget===!0,le=te.length>1;if(!le){if(W.__webglTexture===void 0)W.__webglTexture=e.createTexture();W.__version=x.version,o.memory.textures++}if(ie){P.__webglFramebuffer=[];for(let X=0;X<6;X++)if(x.mipmaps&&x.mipmaps.length>0){P.__webglFramebuffer[X]=[];for(let j=0;j<x.mipmaps.length;j++)P.__webglFramebuffer[X][j]=e.createFramebuffer()}else P.__webglFramebuffer[X]=e.createFramebuffer()}else{if(x.mipmaps&&x.mipmaps.length>0){P.__webglFramebuffer=[];for(let X=0;X<x.mipmaps.length;X++)P.__webglFramebuffer[X]=e.createFramebuffer()}else P.__webglFramebuffer=e.createFramebuffer();if(le)for(let X=0,j=te.length;X<j;X++){let xe=i.get(te[X]);if(xe.__webglTexture===void 0)xe.__webglTexture=e.createTexture(),o.memory.textures++}if(M.samples>0&&L(M)===!1){P.__webglMultisampledFramebuffer=e.createFramebuffer(),P.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,P.__webglMultisampledFramebuffer);for(let X=0;X<te.length;X++){let j=te[X];P.__webglColorRenderbuffer[X]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,P.__webglColorRenderbuffer[X]);let xe=s.convert(j.format,j.colorSpace),we=s.convert(j.type),ue=v(j.internalFormat,xe,we,j.normalized,j.colorSpace,M.isXRRenderTarget===!0),re=Ct(M);e.renderbufferStorageMultisample(e.RENDERBUFFER,re,ue,M.width,M.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+X,e.RENDERBUFFER,P.__webglColorRenderbuffer[X])}if(e.bindRenderbuffer(e.RENDERBUFFER,null),M.depthBuffer)P.__webglDepthRenderbuffer=e.createRenderbuffer(),ze(P.__webglDepthRenderbuffer,M,!0);n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(ie){n.bindTexture(e.TEXTURE_CUBE_MAP,W.__webglTexture),Z(e.TEXTURE_CUBE_MAP,x);for(let X=0;X<6;X++)if(x.mipmaps&&x.mipmaps.length>0)for(let j=0;j<x.mipmaps.length;j++)Ue(P.__webglFramebuffer[X][j],M,x,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+X,j);else Ue(P.__webglFramebuffer[X],M,x,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+X,0);if(m(x))A(e.TEXTURE_CUBE_MAP);n.unbindTexture()}else if(le){for(let X=0,j=te.length;X<j;X++){let xe=te[X],we=i.get(xe),ue=e.TEXTURE_2D;if(M.isWebGL3DRenderTarget||M.isWebGLArrayRenderTarget)ue=M.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY;if(n.bindTexture(ue,we.__webglTexture),Z(ue,xe),Ue(P.__webglFramebuffer,M,xe,e.COLOR_ATTACHMENT0+X,ue,0),m(xe))A(ue)}n.unbindTexture()}else{let X=e.TEXTURE_2D;if(M.isWebGL3DRenderTarget||M.isWebGLArrayRenderTarget)X=M.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY;if(n.bindTexture(X,W.__webglTexture),Z(X,x),x.mipmaps&&x.mipmaps.length>0)for(let j=0;j<x.mipmaps.length;j++)Ue(P.__webglFramebuffer[j],M,x,e.COLOR_ATTACHMENT0,X,j);else Ue(P.__webglFramebuffer,M,x,e.COLOR_ATTACHMENT0,X,0);if(m(x))A(X);n.unbindTexture()}if(M.depthBuffer)qe(M)}function pn(M){let x=M.textures;for(let P=0,W=x.length;P<W;P++){let te=x[P];if(m(te)){let ie=T(M),le=i.get(te).__webglTexture;n.bindTexture(ie,le),A(ie),n.unbindTexture()}}}let pt=[],Gt=[];function Ot(M){if(M.samples>0){if(L(M)===!1){let{textures:x,width:P,height:W}=M,te=e.COLOR_BUFFER_BIT,ie=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,le=i.get(M),X=x.length>1;if(X)for(let xe=0;xe<x.length;xe++)n.bindFramebuffer(e.FRAMEBUFFER,le.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+xe,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,le.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+xe,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,le.__webglMultisampledFramebuffer);let j=M.texture.mipmaps;if(j&&j.length>0)n.bindFramebuffer(e.DRAW_FRAMEBUFFER,le.__webglFramebuffer[0]);else n.bindFramebuffer(e.DRAW_FRAMEBUFFER,le.__webglFramebuffer);for(let xe=0;xe<x.length;xe++){if(M.resolveDepthBuffer){if(M.depthBuffer)te|=e.DEPTH_BUFFER_BIT;if(M.stencilBuffer&&M.resolveStencilBuffer)te|=e.STENCIL_BUFFER_BIT}if(X){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,le.__webglColorRenderbuffer[xe]);let we=i.get(x[xe]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,we,0)}if(e.blitFramebuffer(0,0,P,W,0,0,P,W,te,e.NEAREST),c===!0){if(pt.length=0,Gt.length=0,pt.push(e.COLOR_ATTACHMENT0+xe),M.depthBuffer&&M.resolveDepthBuffer===!1)pt.push(ie),Gt.push(ie),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,Gt);e.invalidateFramebuffer(e.READ_FRAMEBUFFER,pt)}}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),X)for(let xe=0;xe<x.length;xe++){n.bindFramebuffer(e.FRAMEBUFFER,le.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+xe,e.RENDERBUFFER,le.__webglColorRenderbuffer[xe]);let we=i.get(x[xe]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,le.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+xe,e.TEXTURE_2D,we,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,le.__webglMultisampledFramebuffer)}else if(M.depthBuffer&&M.resolveDepthBuffer===!1&&c){let x=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[x])}}}function Ct(M){return Math.min(r.maxSamples,M.samples)}function L(M){let x=i.get(M);return M.samples>0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&x.__useRenderToTexture!==!1}function mn(M){let x=o.render.frame;if(u.get(M)!==x)u.set(M,x),M.update()}function tt(M,x){let{colorSpace:P,format:W,type:te}=M;if(M.isCompressedTexture===!0||M.isVideoTexture===!0)return x;if(P!==cn&&P!==ar)if(Ve.getTransfer(P)===ut){if(W!==$n||te!==Ln)Me("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}else Ne("WebGLTextures: Unsupported texture color space:",P);return x}function mt(M){if(typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement)l.width=M.naturalWidth||M.width,l.height=M.naturalHeight||M.height;else if(typeof VideoFrame<"u"&&M instanceof VideoFrame)l.width=M.displayWidth,l.height=M.displayHeight;else l.width=M.width,l.height=M.height;return l}this.allocateTextureUnit=V,this.resetTextureUnits=J,this.getTextureUnits=O,this.setTextureUnits=H,this.setTexture2D=K,this.setTexture2DArray=Q,this.setTexture3D=se,this.setTextureCube=me,this.rebindTextures=je,this.setupRenderTarget=Ut,this.updateRenderTargetMipmap=pn,this.updateMultisampleRenderTarget=Ot,this.setupDepthRenderbuffer=qe,this.setupFrameBufferTexture=Ue,this.useMultisampledRTT=L,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function vM(e,t){function n(i,r=ar){let s,o=Ve.getTransfer(r);if(i===Ln)return e.UNSIGNED_BYTE;if(i===Lc)return e.UNSIGNED_SHORT_4_4_4_4;if(i===Nc)return e.UNSIGNED_SHORT_5_5_5_1;if(i===Cf)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===Pf)return e.UNSIGNED_INT_10F_11F_11F_REV;if(i===Af)return e.BYTE;if(i===Rf)return e.SHORT;if(i===bs)return e.UNSIGNED_SHORT;if(i===Ic)return e.INT;if(i===Ci)return e.UNSIGNED_INT;if(i===ui)return e.FLOAT;if(i===hi)return e.HALF_FLOAT;if(i===If)return e.ALPHA;if(i===Lf)return e.RGB;if(i===$n)return e.RGBA;if(i===rr)return e.DEPTH_COMPONENT;if(i===sr)return e.DEPTH_STENCIL;if(i===Nf)return e.RED;if(i===Dc)return e.RED_INTEGER;if(i===or)return e.RG;if(i===Uc)return e.RG_INTEGER;if(i===Oc)return e.RGBA_INTEGER;if(i===Bo||i===Go||i===Ho||i===Vo)if(o===ut)if(s=t.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===Bo)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Go)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Ho)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Vo)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=t.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===Bo)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Go)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Ho)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Vo)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Fc||i===zc||i===kc||i===Bc)if(s=t.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===Fc)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===zc)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===kc)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Bc)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Gc||i===Hc||i===Vc||i===Wc||i===$c||i===Wo||i===Zc)if(s=t.get("WEBGL_compressed_texture_etc"),s!==null){if(i===Gc||i===Hc)return o===ut?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===Vc)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===Wc)return s.COMPRESSED_R11_EAC;if(i===$c)return s.COMPRESSED_SIGNED_R11_EAC;if(i===Wo)return s.COMPRESSED_RG11_EAC;if(i===Zc)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===Xc||i===qc||i===Yc||i===jc||i===Jc||i===Kc||i===Qc||i===el||i===tl||i===nl||i===il||i===rl||i===sl||i===ol)if(s=t.get("WEBGL_compressed_texture_astc"),s!==null){if(i===Xc)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===qc)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Yc)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===jc)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Jc)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Kc)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Qc)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===el)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===tl)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===nl)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===il)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===rl)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===sl)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===ol)return o===ut?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===al||i===cl||i===ll)if(s=t.get("EXT_texture_compression_bptc"),s!==null){if(i===al)return o===ut?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===cl)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===ll)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===ul||i===hl||i===$o||i===fl)if(s=t.get("EXT_texture_compression_rgtc"),s!==null){if(i===ul)return s.COMPRESSED_RED_RGTC1_EXT;if(i===hl)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===$o)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===fl)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;if(i===$r)return e.UNSIGNED_INT_24_8;return e[i]!==void 0?e[i]:null}return{convert:n}}var yM=`void main() {gl_Position = vec4( position, 1.0 );-}`,mw=`+}`,bM=`uniform sampler2DArray depthColor;uniform float depthWidth;uniform float depthHeight;@@ -4223,76 +4223,75 @@ void main() {}-}`;class yZ{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init($,U){if(this.texture===null){let J=new S9($.texture);if($.depthNear!==U.depthNear||$.depthFar!==U.depthFar)this.depthNear=$.depthNear,this.depthFar=$.depthFar;this.texture=J}}getMesh($){if(this.texture!==null){if(this.mesh===null){let U=$.cameras[0].viewport,J=new gU({vertexShader:lw,fragmentShader:mw,uniforms:{depthColor:{value:this.texture},depthWidth:{value:U.z},depthHeight:{value:U.w}}});this.mesh=new B6(new yW(20,20),J)}}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class xZ extends iU{constructor($,U){super();let J=this,Q=null,W=1,K=null,X="local-floor",H=1,N=null,Y=null,G=null,O=null,E=null,k=null,I=typeof XRWebGLBinding<"u",R=new yZ,q={},Z=U.getContextAttributes(),_=null,P=null,L=[],B=[],z=new g$,A=null,D=new x6;D.viewport=new E6;let w=new x6;w.viewport=new E6;let h=[D,w],C=new FH,f=null,s=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(i){let X$=L[i];if(X$===void 0)X$=new AW,L[i]=X$;return X$.getTargetRaySpace()},this.getControllerGrip=function(i){let X$=L[i];if(X$===void 0)X$=new AW,L[i]=X$;return X$.getGripSpace()},this.getHand=function(i){let X$=L[i];if(X$===void 0)X$=new AW,L[i]=X$;return X$.getHandSpace()};function x(i){let X$=B.indexOf(i.inputSource);if(X$===-1)return;let D$=L[X$];if(D$!==void 0)D$.update(i.inputSource,i.frame,N||K),D$.dispatchEvent({type:i.type,data:i.inputSource})}function d(){Q.removeEventListener("select",x),Q.removeEventListener("selectstart",x),Q.removeEventListener("selectend",x),Q.removeEventListener("squeeze",x),Q.removeEventListener("squeezestart",x),Q.removeEventListener("squeezeend",x),Q.removeEventListener("end",d),Q.removeEventListener("inputsourceschange",c);for(let i=0;i<L.length;i++){let X$=B[i];if(X$===null)continue;B[i]=null,L[i].disconnect(X$)}f=null,s=null,R.reset();for(let i in q)delete q[i];$.setRenderTarget(_),E=null,O=null,G=null,Q=null,P=null,n$.stop(),J.isPresenting=!1,$.setPixelRatio(A),$.setSize(z.width,z.height,!1),J.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(i){if(W=i,J.isPresenting===!0)A$("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(i){if(X=i,J.isPresenting===!0)A$("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return N||K},this.setReferenceSpace=function(i){N=i},this.getBaseLayer=function(){return O!==null?O:E},this.getBinding=function(){if(G===null&&I)G=new XRWebGLBinding(Q,U);return G},this.getFrame=function(){return k},this.getSession=function(){return Q},this.setSession=async function(i){if(Q=i,Q!==null){if(_=$.getRenderTarget(),Q.addEventListener("select",x),Q.addEventListener("selectstart",x),Q.addEventListener("selectend",x),Q.addEventListener("squeeze",x),Q.addEventListener("squeezestart",x),Q.addEventListener("squeezeend",x),Q.addEventListener("end",d),Q.addEventListener("inputsourceschange",c),Z.xrCompatible!==!0)await U.makeXRCompatible();if(A=$.getPixelRatio(),$.getSize(z),!(I&&("createProjectionLayer"in XRWebGLBinding.prototype))){let D$={antialias:Z.antialias,alpha:!0,depth:Z.depth,stencil:Z.stencil,framebufferScaleFactor:W};E=new XRWebGLLayer(Q,U,D$),Q.updateRenderState({baseLayer:E}),$.setPixelRatio(1),$.setSize(E.framebufferWidth,E.framebufferHeight,!1),P=new jU(E.framebufferWidth,E.framebufferHeight,{format:QJ,type:nU,colorSpace:$.outputColorSpace,stencilBuffer:Z.stencil,resolveDepthBuffer:E.ignoreDepthValues===!1,resolveStencilBuffer:E.ignoreDepthValues===!1})}else{let D$=null,F$=null,v$=null;if(Z.depth)v$=Z.stencil?U.DEPTH24_STENCIL8:U.DEPTH_COMPONENT24,D$=Z.stencil?C0:A0,F$=Z.stencil?L8:rJ;let t$={colorFormat:U.RGBA8,depthFormat:v$,scaleFactor:W};G=this.getBinding(),O=G.createProjectionLayer(t$),Q.updateRenderState({layers:[O]}),$.setPixelRatio(1),$.setSize(O.textureWidth,O.textureHeight,!1),P=new jU(O.textureWidth,O.textureHeight,{format:QJ,type:nU,depthTexture:new eJ(O.textureWidth,O.textureHeight,F$,void 0,void 0,void 0,void 0,void 0,void 0,D$),stencilBuffer:Z.stencil,colorSpace:$.outputColorSpace,samples:Z.antialias?4:0,resolveDepthBuffer:O.ignoreDepthValues===!1,resolveStencilBuffer:O.ignoreDepthValues===!1})}P.isXRRenderTarget=!0,this.setFoveation(H),N=null,K=await Q.requestReferenceSpace(X),n$.setContext(Q),n$.start(),J.isPresenting=!0,J.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(Q!==null)return Q.environmentBlendMode},this.getDepthTexture=function(){return R.getDepthTexture()};function c(i){for(let X$=0;X$<i.removed.length;X$++){let D$=i.removed[X$],F$=B.indexOf(D$);if(F$>=0)B[F$]=null,L[F$].disconnect(D$)}for(let X$=0;X$<i.added.length;X$++){let D$=i.added[X$],F$=B.indexOf(D$);if(F$===-1){for(let t$=0;t$<L.length;t$++)if(t$>=B.length){B.push(D$),F$=t$;break}else if(B[t$]===null){B[t$]=D$,F$=t$;break}if(F$===-1)break}let v$=L[F$];if(v$)v$.connect(D$)}}let y=new j,t=new j;function e(i,X$,D$){y.setFromMatrixPosition(X$.matrixWorld),t.setFromMatrixPosition(D$.matrixWorld);let F$=y.distanceTo(t),v$=X$.projectionMatrix.elements,t$=D$.projectionMatrix.elements,u$=v$[14]/(v$[10]-1),p$=v$[14]/(v$[10]+1),K6=(v$[9]+1)/v$[5],U6=(v$[9]-1)/v$[5],Q6=(v$[8]-1)/v$[0],m6=(t$[8]+1)/t$[0],_U=u$*Q6,P6=u$*m6,o6=F$/(-Q6+m6),p6=o6*-Q6;if(X$.matrixWorld.decompose(i.position,i.quaternion,i.scale),i.translateX(p6),i.translateZ(o6),i.matrixWorld.compose(i.position,i.quaternion,i.scale),i.matrixWorldInverse.copy(i.matrixWorld).invert(),v$[10]===-1)i.projectionMatrix.copy(X$.projectionMatrix),i.projectionMatrixInverse.copy(X$.projectionMatrixInverse);else{let y6=u$+o6,v=p$+o6,AU=_U-p6,Y6=P6+(F$-p6),z6=K6*p$/v*y6,M=U6*p$/v*y6;i.projectionMatrix.makePerspective(AU,Y6,z6,M,y6,v),i.projectionMatrixInverse.copy(i.projectionMatrix).invert()}}function Y$(i,X$){if(X$===null)i.matrixWorld.copy(i.matrix);else i.matrixWorld.multiplyMatrices(X$.matrixWorld,i.matrix);i.matrixWorldInverse.copy(i.matrixWorld).invert()}this.updateCamera=function(i){if(Q===null)return;let{near:X$,far:D$}=i;if(R.texture!==null){if(R.depthNear>0)X$=R.depthNear;if(R.depthFar>0)D$=R.depthFar}if(C.near=w.near=D.near=X$,C.far=w.far=D.far=D$,f!==C.near||s!==C.far)Q.updateRenderState({depthNear:C.near,depthFar:C.far}),f=C.near,s=C.far;C.layers.mask=i.layers.mask|6,D.layers.mask=C.layers.mask&-5,w.layers.mask=C.layers.mask&-3;let F$=i.parent,v$=C.cameras;Y$(C,F$);for(let t$=0;t$<v$.length;t$++)Y$(v$[t$],F$);if(v$.length===2)e(C,D,w);else C.projectionMatrix.copy(D.projectionMatrix);R$(i,C,F$)};function R$(i,X$,D$){if(D$===null)i.matrix.copy(X$.matrixWorld);else i.matrix.copy(D$.matrixWorld),i.matrix.invert(),i.matrix.multiply(X$.matrixWorld);if(i.matrix.decompose(i.position,i.quaternion,i.scale),i.updateMatrixWorld(!0),i.projectionMatrix.copy(X$.projectionMatrix),i.projectionMatrixInverse.copy(X$.projectionMatrixInverse),i.isPerspectiveCamera)i.fov=B0*2*Math.atan(1/i.projectionMatrix.elements[5]),i.zoom=1}this.getCamera=function(){return C},this.getFoveation=function(){if(O===null&&E===null)return;return H},this.setFoveation=function(i){if(H=i,O!==null)O.fixedFoveation=i;if(E!==null&&E.fixedFoveation!==void 0)E.fixedFoveation=i},this.hasDepthSensing=function(){return R.texture!==null},this.getDepthSensingMesh=function(){return R.getMesh(C)},this.getCameraTexture=function(i){return q[i]};let w$=null;function $6(i,X$){if(Y=X$.getViewerPose(N||K),k=X$,Y!==null){let D$=Y.views;if(E!==null)$.setRenderTargetFramebuffer(P,E.framebuffer),$.setRenderTarget(P);let F$=!1;if(D$.length!==C.cameras.length)C.cameras.length=0,F$=!0;for(let p$=0;p$<D$.length;p$++){let K6=D$[p$],U6=null;if(E!==null)U6=E.getViewport(K6);else{let m6=G.getViewSubImage(O,K6);if(U6=m6.viewport,p$===0)$.setRenderTargetTextures(P,m6.colorTexture,m6.depthStencilTexture),$.setRenderTarget(P)}let Q6=h[p$];if(Q6===void 0)Q6=new x6,Q6.layers.enable(p$),Q6.viewport=new E6,h[p$]=Q6;if(Q6.matrix.fromArray(K6.transform.matrix),Q6.matrix.decompose(Q6.position,Q6.quaternion,Q6.scale),Q6.projectionMatrix.fromArray(K6.projectionMatrix),Q6.projectionMatrixInverse.copy(Q6.projectionMatrix).invert(),Q6.viewport.set(U6.x,U6.y,U6.width,U6.height),p$===0)C.matrix.copy(Q6.matrix),C.matrix.decompose(C.position,C.quaternion,C.scale);if(F$===!0)C.cameras.push(Q6)}let v$=Q.enabledFeatures;if(v$&&v$.includes("depth-sensing")&&Q.depthUsage=="gpu-optimized"&&I){G=J.getBinding();let p$=G.getDepthInformation(D$[0]);if(p$&&p$.isValid&&p$.texture)R.init(p$,Q.renderState)}if(v$&&v$.includes("camera-access")&&I){$.state.unbindTexture(),G=J.getBinding();for(let p$=0;p$<D$.length;p$++){let K6=D$[p$].camera;if(K6){let U6=q[K6];if(!U6)U6=new S9,q[K6]=U6;let Q6=G.getCameraImage(K6);U6.sourceTexture=Q6}}}}for(let D$=0;D$<L.length;D$++){let F$=B[D$],v$=L[D$];if(F$!==null&&v$!==void 0)v$.update(F$,X$,N||K)}if(w$)w$(i,X$);if(X$.detectedPlanes)J.dispatchEvent({type:"planesdetected",data:X$});k=null}let n$=new PZ;n$.setAnimationLoop($6),this.setAnimationLoop=function(i){w$=i},this.dispose=function(){}}}var pw=new m$,hZ=new f$;hZ.set(-1,0,0,0,1,0,0,0,1);function dw($,U){function J(q,Z){if(q.matrixAutoUpdate===!0)q.updateMatrix();Z.value.copy(q.matrix)}function Q(q,Z){if(Z.color.getRGB(q.fogColor.value,NH($)),Z.isFog)q.fogNear.value=Z.near,q.fogFar.value=Z.far;else if(Z.isFogExp2)q.fogDensity.value=Z.density}function W(q,Z,_,P,L){if(Z.isNodeMaterial)Z.uniformsNeedUpdate=!1;else if(Z.isMeshBasicMaterial)K(q,Z);else if(Z.isMeshLambertMaterial){if(K(q,Z),Z.envMap)q.envMapIntensity.value=Z.envMapIntensity}else if(Z.isMeshToonMaterial)K(q,Z),O(q,Z);else if(Z.isMeshPhongMaterial){if(K(q,Z),G(q,Z),Z.envMap)q.envMapIntensity.value=Z.envMapIntensity}else if(Z.isMeshStandardMaterial){if(K(q,Z),E(q,Z),Z.isMeshPhysicalMaterial)k(q,Z,L)}else if(Z.isMeshMatcapMaterial)K(q,Z),I(q,Z);else if(Z.isMeshDepthMaterial)K(q,Z);else if(Z.isMeshDistanceMaterial)K(q,Z),R(q,Z);else if(Z.isMeshNormalMaterial)K(q,Z);else if(Z.isLineBasicMaterial){if(X(q,Z),Z.isLineDashedMaterial)H(q,Z)}else if(Z.isPointsMaterial)N(q,Z,_,P);else if(Z.isSpriteMaterial)Y(q,Z);else if(Z.isShadowMaterial)q.color.value.copy(Z.color),q.opacity.value=Z.opacity;else if(Z.isShaderMaterial)Z.uniformsNeedUpdate=!1}function K(q,Z){if(q.opacity.value=Z.opacity,Z.color)q.diffuse.value.copy(Z.color);if(Z.emissive)q.emissive.value.copy(Z.emissive).multiplyScalar(Z.emissiveIntensity);if(Z.map)q.map.value=Z.map,J(Z.map,q.mapTransform);if(Z.alphaMap)q.alphaMap.value=Z.alphaMap,J(Z.alphaMap,q.alphaMapTransform);if(Z.bumpMap){if(q.bumpMap.value=Z.bumpMap,J(Z.bumpMap,q.bumpMapTransform),q.bumpScale.value=Z.bumpScale,Z.side===$U)q.bumpScale.value*=-1}if(Z.normalMap){if(q.normalMap.value=Z.normalMap,J(Z.normalMap,q.normalMapTransform),q.normalScale.value.copy(Z.normalScale),Z.side===$U)q.normalScale.value.negate()}if(Z.displacementMap)q.displacementMap.value=Z.displacementMap,J(Z.displacementMap,q.displacementMapTransform),q.displacementScale.value=Z.displacementScale,q.displacementBias.value=Z.displacementBias;if(Z.emissiveMap)q.emissiveMap.value=Z.emissiveMap,J(Z.emissiveMap,q.emissiveMapTransform);if(Z.specularMap)q.specularMap.value=Z.specularMap,J(Z.specularMap,q.specularMapTransform);if(Z.alphaTest>0)q.alphaTest.value=Z.alphaTest;let _=U.get(Z),P=_.envMap,L=_.envMapRotation;if(P){if(q.envMap.value=P,q.envMapRotation.value.setFromMatrix4(pw.makeRotationFromEuler(L)).transpose(),P.isCubeTexture&&P.isRenderTargetTexture===!1)q.envMapRotation.value.premultiply(hZ);q.reflectivity.value=Z.reflectivity,q.ior.value=Z.ior,q.refractionRatio.value=Z.refractionRatio}if(Z.lightMap)q.lightMap.value=Z.lightMap,q.lightMapIntensity.value=Z.lightMapIntensity,J(Z.lightMap,q.lightMapTransform);if(Z.aoMap)q.aoMap.value=Z.aoMap,q.aoMapIntensity.value=Z.aoMapIntensity,J(Z.aoMap,q.aoMapTransform)}function X(q,Z){if(q.diffuse.value.copy(Z.color),q.opacity.value=Z.opacity,Z.map)q.map.value=Z.map,J(Z.map,q.mapTransform)}function H(q,Z){q.dashSize.value=Z.dashSize,q.totalSize.value=Z.dashSize+Z.gapSize,q.scale.value=Z.scale}function N(q,Z,_,P){if(q.diffuse.value.copy(Z.color),q.opacity.value=Z.opacity,q.size.value=Z.size*_,q.scale.value=P*0.5,Z.map)q.map.value=Z.map,J(Z.map,q.uvTransform);if(Z.alphaMap)q.alphaMap.value=Z.alphaMap,J(Z.alphaMap,q.alphaMapTransform);if(Z.alphaTest>0)q.alphaTest.value=Z.alphaTest}function Y(q,Z){if(q.diffuse.value.copy(Z.color),q.opacity.value=Z.opacity,q.rotation.value=Z.rotation,Z.map)q.map.value=Z.map,J(Z.map,q.mapTransform);if(Z.alphaMap)q.alphaMap.value=Z.alphaMap,J(Z.alphaMap,q.alphaMapTransform);if(Z.alphaTest>0)q.alphaTest.value=Z.alphaTest}function G(q,Z){q.specular.value.copy(Z.specular),q.shininess.value=Math.max(Z.shininess,0.0001)}function O(q,Z){if(Z.gradientMap)q.gradientMap.value=Z.gradientMap}function E(q,Z){if(q.metalness.value=Z.metalness,Z.metalnessMap)q.metalnessMap.value=Z.metalnessMap,J(Z.metalnessMap,q.metalnessMapTransform);if(q.roughness.value=Z.roughness,Z.roughnessMap)q.roughnessMap.value=Z.roughnessMap,J(Z.roughnessMap,q.roughnessMapTransform);if(Z.envMap)q.envMapIntensity.value=Z.envMapIntensity}function k(q,Z,_){if(q.ior.value=Z.ior,Z.sheen>0){if(q.sheenColor.value.copy(Z.sheenColor).multiplyScalar(Z.sheen),q.sheenRoughness.value=Z.sheenRoughness,Z.sheenColorMap)q.sheenColorMap.value=Z.sheenColorMap,J(Z.sheenColorMap,q.sheenColorMapTransform);if(Z.sheenRoughnessMap)q.sheenRoughnessMap.value=Z.sheenRoughnessMap,J(Z.sheenRoughnessMap,q.sheenRoughnessMapTransform)}if(Z.clearcoat>0){if(q.clearcoat.value=Z.clearcoat,q.clearcoatRoughness.value=Z.clearcoatRoughness,Z.clearcoatMap)q.clearcoatMap.value=Z.clearcoatMap,J(Z.clearcoatMap,q.clearcoatMapTransform);if(Z.clearcoatRoughnessMap)q.clearcoatRoughnessMap.value=Z.clearcoatRoughnessMap,J(Z.clearcoatRoughnessMap,q.clearcoatRoughnessMapTransform);if(Z.clearcoatNormalMap){if(q.clearcoatNormalMap.value=Z.clearcoatNormalMap,J(Z.clearcoatNormalMap,q.clearcoatNormalMapTransform),q.clearcoatNormalScale.value.copy(Z.clearcoatNormalScale),Z.side===$U)q.clearcoatNormalScale.value.negate()}}if(Z.dispersion>0)q.dispersion.value=Z.dispersion;if(Z.iridescence>0){if(q.iridescence.value=Z.iridescence,q.iridescenceIOR.value=Z.iridescenceIOR,q.iridescenceThicknessMinimum.value=Z.iridescenceThicknessRange[0],q.iridescenceThicknessMaximum.value=Z.iridescenceThicknessRange[1],Z.iridescenceMap)q.iridescenceMap.value=Z.iridescenceMap,J(Z.iridescenceMap,q.iridescenceMapTransform);if(Z.iridescenceThicknessMap)q.iridescenceThicknessMap.value=Z.iridescenceThicknessMap,J(Z.iridescenceThicknessMap,q.iridescenceThicknessMapTransform)}if(Z.transmission>0){if(q.transmission.value=Z.transmission,q.transmissionSamplerMap.value=_.texture,q.transmissionSamplerSize.value.set(_.width,_.height),Z.transmissionMap)q.transmissionMap.value=Z.transmissionMap,J(Z.transmissionMap,q.transmissionMapTransform);if(q.thickness.value=Z.thickness,Z.thicknessMap)q.thicknessMap.value=Z.thicknessMap,J(Z.thicknessMap,q.thicknessMapTransform);q.attenuationDistance.value=Z.attenuationDistance,q.attenuationColor.value.copy(Z.attenuationColor)}if(Z.anisotropy>0){if(q.anisotropyVector.value.set(Z.anisotropy*Math.cos(Z.anisotropyRotation),Z.anisotropy*Math.sin(Z.anisotropyRotation)),Z.anisotropyMap)q.anisotropyMap.value=Z.anisotropyMap,J(Z.anisotropyMap,q.anisotropyMapTransform)}if(q.specularIntensity.value=Z.specularIntensity,q.specularColor.value.copy(Z.specularColor),Z.specularColorMap)q.specularColorMap.value=Z.specularColorMap,J(Z.specularColorMap,q.specularColorMapTransform);if(Z.specularIntensityMap)q.specularIntensityMap.value=Z.specularIntensityMap,J(Z.specularIntensityMap,q.specularIntensityMapTransform)}function I(q,Z){if(Z.matcap)q.matcap.value=Z.matcap}function R(q,Z){let _=U.get(Z).light;q.referencePosition.value.setFromMatrixPosition(_.matrixWorld),q.nearDistance.value=_.shadow.camera.near,q.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:Q,refreshMaterialUniforms:W}}function cw($,U,J,Q){let W={},K={},X=[],H=$.getParameter($.MAX_UNIFORM_BUFFER_BINDINGS);function N(L,B){let z=B.program;Q.uniformBlockBinding(L,z)}function Y(L,B){let z=W[L.id];if(z===void 0)q(L),z=G(L),W[L.id]=z,L.addEventListener("dispose",_);let A=B.program;Q.updateUBOMapping(L,A);let D=U.render.frame;if(K[L.id]!==D)E(L),K[L.id]=D}function G(L){let B=O();L.__bindingPointIndex=B;let z=$.createBuffer(),A=L.__size,D=L.usage;return $.bindBuffer($.UNIFORM_BUFFER,z),$.bufferData($.UNIFORM_BUFFER,A,D),$.bindBuffer($.UNIFORM_BUFFER,null),$.bindBufferBase($.UNIFORM_BUFFER,B,z),z}function O(){for(let L=0;L<H;L++)if(X.indexOf(L)===-1)return X.push(L),L;return x$("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function E(L){let B=W[L.id],z=L.uniforms,A=L.__cache;$.bindBuffer($.UNIFORM_BUFFER,B);for(let D=0,w=z.length;D<w;D++){let h=z[D];if(Array.isArray(h))for(let C=0,f=h.length;C<f;C++)k(h[C],D,C,A);else k(h,D,0,A)}$.bindBuffer($.UNIFORM_BUFFER,null)}function k(L,B,z,A){if(R(L,B,z,A)===!0){let{__offset:D,value:w}=L;if(Array.isArray(w)){let h=0;for(let C=0;C<w.length;C++){let f=w[C],s=Z(f);if(I(f,L.__data,h),typeof f!=="number"&&typeof f!=="boolean"&&!f.isMatrix3&&!ArrayBuffer.isView(f))h+=s.storage/Float32Array.BYTES_PER_ELEMENT}}else I(w,L.__data,0);$.bufferSubData($.UNIFORM_BUFFER,D,L.__data)}}function I(L,B,z){if(typeof L==="number"||typeof L==="boolean")B[0]=L;else if(L.isMatrix3)B[0]=L.elements[0],B[1]=L.elements[1],B[2]=L.elements[2],B[3]=0,B[4]=L.elements[3],B[5]=L.elements[4],B[6]=L.elements[5],B[7]=0,B[8]=L.elements[6],B[9]=L.elements[7],B[10]=L.elements[8],B[11]=0;else if(ArrayBuffer.isView(L))B.set(new L.constructor(L.buffer,L.byteOffset,B.length));else L.toArray(B,z)}function R(L,B,z,A){let D=L.value,w=B+"_"+z;if(A[w]===void 0){if(typeof D==="number"||typeof D==="boolean")A[w]=D;else if(ArrayBuffer.isView(D))A[w]=D.slice();else A[w]=D.clone();return!0}else{let h=A[w];if(typeof D==="number"||typeof D==="boolean"){if(h!==D)return A[w]=D,!0}else if(ArrayBuffer.isView(D))return!0;else if(h.equals(D)===!1)return h.copy(D),!0}return!1}function q(L){let B=L.uniforms,z=0,A=16;for(let w=0,h=B.length;w<h;w++){let C=Array.isArray(B[w])?B[w]:[B[w]];for(let f=0,s=C.length;f<s;f++){let x=C[f],d=Array.isArray(x.value)?x.value:[x.value];for(let c=0,y=d.length;c<y;c++){let t=d[c],e=Z(t),Y$=z%A,R$=Y$%e.boundary,w$=Y$+R$;if(z+=R$,w$!==0&&A-w$<e.storage)z+=A-w$;x.__data=new Float32Array(e.storage/Float32Array.BYTES_PER_ELEMENT),x.__offset=z,z+=e.storage}}}let D=z%A;if(D>0)z+=A-D;return L.__size=z,L.__cache={},this}function Z(L){let B={boundary:0,storage:0};if(typeof L==="number"||typeof L==="boolean")B.boundary=4,B.storage=4;else if(L.isVector2)B.boundary=8,B.storage=8;else if(L.isVector3||L.isColor)B.boundary=16,B.storage=12;else if(L.isVector4)B.boundary=16,B.storage=16;else if(L.isMatrix3)B.boundary=48,B.storage=48;else if(L.isMatrix4)B.boundary=64,B.storage=64;else if(L.isTexture)A$("WebGLRenderer: Texture samplers can not be part of an uniforms group.");else if(ArrayBuffer.isView(L))B.boundary=16,B.storage=L.byteLength;else A$("WebGLRenderer: Unsupported uniform value type.",L);return B}function _(L){let B=L.target;B.removeEventListener("dispose",_);let z=X.indexOf(B.__bindingPointIndex);X.splice(z,1),$.deleteBuffer(W[B.id]),delete W[B.id],delete K[B.id]}function P(){for(let L in W)$.deleteBuffer(W[L]);X=[],W={},K={}}return{bind:N,update:Y,dispose:P}}var nw=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]),XJ=null;function iw(){if(XJ===null)XJ=new TW(nw,16,16,S0,CJ),XJ.name="DFG_LUT",XJ.minFilter=n6,XJ.magFilter=n6,XJ.wrapS=D8,XJ.wrapT=D8,XJ.generateMipmaps=!1,XJ.needsUpdate=!0;return XJ}class gH{constructor($={}){let{canvas:U=cq(),context:J=null,depth:Q=!0,stencil:W=!1,alpha:K=!1,antialias:X=!1,premultipliedAlpha:H=!0,preserveDrawingBuffer:N=!1,powerPreference:Y="default",failIfMajorPerformanceCaveat:G=!1,reversedDepthBuffer:O=!1,outputBufferType:E=nU}=$;this.isWebGLRenderer=!0;let k;if(J!==null){if(typeof WebGLRenderingContext<"u"&&J instanceof WebGLRenderingContext)throw Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");k=J.getContextAttributes().alpha}else k=K;let I=E,R=new Set([RX,LX,FX]),q=new Set([nU,rJ,BW,L8,IX,DX]),Z=new Uint32Array(4),_=new Int32Array(4),P=new j,L=null,B=null,z=[],A=[],D=null;this.domElement=U,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=dU,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let w=this,h=!1,C=null,f=null,s=null,x=null;this._outputColorSpace=aJ;let d=0,c=0,y=null,t=-1,e=null,Y$=new E6,R$=new E6,w$=null,$6=new y$(0),n$=0,i=U.width,X$=U.height,D$=1,F$=null,v$=null,t$=new E6(0,0,i,X$),u$=new E6(0,0,i,X$),p$=!1,K6=new jW,U6=!1,Q6=!1,m6=new m$,_U=new j,P6=new E6,o6={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},p6=!1;function y6(){return y===null?D$:1}let v=J;function AU(V,b){return U.getContext(V,b)}try{let V={alpha:!0,depth:Q,stencil:W,antialias:X,premultipliedAlpha:H,preserveDrawingBuffer:N,powerPreference:Y,failIfMajorPerformanceCaveat:G};if("setAttribute"in U)U.setAttribute("data-engine",`three.js r${sk}`);if(U.addEventListener("webglcontextlost",l$,!1),U.addEventListener("webglcontextrestored",_6,!1),U.addEventListener("webglcontextcreationerror",w6,!1),v===null){if(v=AU("webgl2",V),v===null)if(AU("webgl2"))throw Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.");else throw Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(V){throw x$("WebGLRenderer: "+V.message),V}let Y6,z6,M,F,S,n,J$,H$,k$,o,a,M$,C$,q$,N$,j$,b$,H6,T,G$,r,O$,B$;function $$(){if(Y6=new $V(v),Y6.init(),r=new uw(v,Y6),z6=new nR(v,Y6,$,r),M=new hw(v,Y6),z6.reversedDepthBuffer&&O)M.buffers.depth.setReversed(!0);f=v.createFramebuffer(),s=v.createFramebuffer(),x=v.createFramebuffer(),F=new WV(v),S=new Bw,n=new fw(v,Y6,M,S,z6,r,F),J$=new eR(w),H$=new H4(v),O$=new dR(v,H$),k$=new UV(v,H$,F,O$),o=new KV(v,k$,H$,O$,F),H6=new QV(v,z6,n),N$=new iR(S),a=new Mw(w,J$,Y6,z6,O$,N$),M$=new dw(w,S),C$=new zw,q$=new vw(Y6),b$=new pR(w,J$,M,o,k,H),j$=new xw(w,o,z6),B$=new cw(v,F,z6,M),T=new cR(v,Y6,F),G$=new JV(v,Y6,F),F.programs=a.programs,w.capabilities=z6,w.extensions=Y6,w.properties=S,w.renderLists=C$,w.shadowMap=j$,w.state=M,w.info=F}if($$(),I!==nU)D=new HV(I,U.width,U.height,X,Q,W);let E$=new xZ(w,v);this.xr=E$,this.getContext=function(){return v},this.getContextAttributes=function(){return v.getContextAttributes()},this.forceContextLoss=function(){let V=Y6.get("WEBGL_lose_context");if(V)V.loseContext()},this.forceContextRestore=function(){let V=Y6.get("WEBGL_lose_context");if(V)V.restoreContext()},this.getPixelRatio=function(){return D$},this.setPixelRatio=function(V){if(V===void 0)return;D$=V,this.setSize(i,X$,!1)},this.getSize=function(V){return V.set(i,X$)},this.setSize=function(V,b,p=!0){if(E$.isPresenting){A$("WebGLRenderer: Can't change size while VR device is presenting.");return}if(i=V,X$=b,U.width=Math.floor(V*D$),U.height=Math.floor(b*D$),p===!0)U.style.width=V+"px",U.style.height=b+"px";if(D!==null)D.setSize(U.width,U.height);this.setViewport(0,0,V,b)},this.getDrawingBufferSize=function(V){return V.set(i*D$,X$*D$).floor()},this.setDrawingBufferSize=function(V,b,p){i=V,X$=b,D$=p,U.width=Math.floor(V*p),U.height=Math.floor(b*p),this.setViewport(0,0,V,b)},this.setEffects=function(V){if(I===nU){x$("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(V){for(let b=0;b<V.length;b++)if(V[b].isOutputPass===!0){A$("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}D.setEffects(V||[])},this.getCurrentViewport=function(V){return V.copy(Y$)},this.getViewport=function(V){return V.copy(t$)},this.setViewport=function(V,b,p,u){if(V.isVector4)t$.set(V.x,V.y,V.z,V.w);else t$.set(V,b,p,u);M.viewport(Y$.copy(t$).multiplyScalar(D$).round())},this.getScissor=function(V){return V.copy(u$)},this.setScissor=function(V,b,p,u){if(V.isVector4)u$.set(V.x,V.y,V.z,V.w);else u$.set(V,b,p,u);M.scissor(R$.copy(u$).multiplyScalar(D$).round())},this.getScissorTest=function(){return p$},this.setScissorTest=function(V){M.setScissorTest(p$=V)},this.setOpaqueSort=function(V){F$=V},this.setTransparentSort=function(V){v$=V},this.getClearColor=function(V){return V.copy(b$.getClearColor())},this.setClearColor=function(){b$.setClearColor(...arguments)},this.getClearAlpha=function(){return b$.getClearAlpha()},this.setClearAlpha=function(){b$.setClearAlpha(...arguments)},this.clear=function(V=!0,b=!0,p=!0){let u=0;if(V){let l=!1;if(y!==null){let V$=y.texture.format;l=R.has(V$)}if(l){let V$=y.texture.type,z$=q.has(V$),L$=b$.getClearColor(),_$=b$.getClearAlpha(),S$=L$.r,d$=L$.g,o$=L$.b;if(z$)Z[0]=S$,Z[1]=d$,Z[2]=o$,Z[3]=_$,v.clearBufferuiv(v.COLOR,0,Z);else _[0]=S$,_[1]=d$,_[2]=o$,_[3]=_$,v.clearBufferiv(v.COLOR,0,_)}else u|=v.COLOR_BUFFER_BIT}if(b)u|=v.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0);if(p)u|=v.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295);if(u!==0)v.clear(u)},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(V){V.setRenderer(this),C=V},this.dispose=function(){U.removeEventListener("webglcontextlost",l$,!1),U.removeEventListener("webglcontextrestored",_6,!1),U.removeEventListener("webglcontextcreationerror",w6,!1),b$.dispose(),C$.dispose(),q$.dispose(),S.dispose(),J$.dispose(),o.dispose(),O$.dispose(),B$.dispose(),a.dispose(),E$.dispose(),E$.removeEventListener("sessionstart",Hk),E$.removeEventListener("sessionend",Nk),F0.stop()};function l$(V){V.preventDefault(),LW("WebGLRenderer: Context Lost."),h=!0}function _6(){LW("WebGLRenderer: Context Restored."),h=!1;let V=F.autoReset,b=j$.enabled,p=j$.autoUpdate,u=j$.needsUpdate,l=j$.type;$$(),F.autoReset=V,j$.enabled=b,j$.autoUpdate=p,j$.needsUpdate=u,j$.type=l}function w6(V){x$("WebGLRenderer: A WebGL context could not be created. Reason: ",V.statusMessage)}function aU(V){let b=V.target;b.removeEventListener("dispose",aU),LJ(b)}function LJ(V){a5(V),S.remove(V)}function a5(V){let b=S.get(V).programs;if(b!==void 0){if(b.forEach(function(p){a.releaseProgram(p)}),V.isShaderMaterial)a.releaseShaderCache(V)}}this.renderBufferDirect=function(V,b,p,u,l,V$){if(b===null)b=o6;let z$=l.isMesh&&l.matrixWorld.determinantAffine()<0,L$=e5(V,b,p,u,l);M.setMaterial(u,z$);let _$=p.index,S$=1;if(u.wireframe===!0){if(_$=k$.getWireframeAttribute(p),_$===void 0)return;S$=2}let d$=p.drawRange,o$=p.attributes.position,T$=d$.start*S$,k6=(d$.start+d$.count)*S$;if(V$!==null)T$=Math.max(T$,V$.start*S$),k6=Math.min(k6,(V$.start+V$.count)*S$);if(_$!==null)T$=Math.max(T$,0),k6=Math.min(k6,_$.count);else if(o$!==void 0&&o$!==null)T$=Math.max(T$,0),k6=Math.min(k6,o$.count);let v6=k6-T$;if(v6<0||v6===1/0)return;O$.setup(l,u,L$,p,_$);let A6,F6=T;if(_$!==null)A6=H$.get(_$),F6=G$,F6.setIndex(A6);if(l.isMesh)if(u.wireframe===!0)M.setLineWidth(u.wireframeLinewidth*y6()),F6.setMode(v.LINES);else F6.setMode(v.TRIANGLES);else if(l.isLine){let s6=u.linewidth;if(s6===void 0)s6=1;if(M.setLineWidth(s6*y6()),l.isLineSegments)F6.setMode(v.LINES);else if(l.isLineLoop)F6.setMode(v.LINE_LOOP);else F6.setMode(v.LINE_STRIP)}else if(l.isPoints)F6.setMode(v.POINTS);else if(l.isSprite)F6.setMode(v.TRIANGLES);if(l.isBatchedMesh)if(!Y6.get("WEBGL_multi_draw")){let{_multiDrawStarts:s6,_multiDrawCounts:P$,_multiDrawCount:DU}=l,X6=_$?H$.get(_$).bytesPerElement:1,CU=S.get(u).currentProgram.getUniforms();for(let sU=0;sU<DU;sU++)CU.setValue(v,"_gl_DrawID",sU),F6.render(s6[sU]/X6,P$[sU])}else F6.renderMultiDraw(l._multiDrawStarts,l._multiDrawCounts,l._multiDrawCount);else if(l.isInstancedMesh)F6.renderInstances(T$,v6,l.count);else if(p.isInstancedBufferGeometry){let s6=p._maxInstanceCount!==void 0?p._maxInstanceCount:1/0,P$=Math.min(p.instanceCount,s6);F6.renderInstances(T$,v6,P$)}else F6.render(T$,v6)};function Xk(V,b,p){if(V.transparent===!0&&V.side===vU&&V.forceSinglePass===!1)V.side=$U,V.needsUpdate=!0,gQ(V,b,p),V.side=oJ,V.needsUpdate=!0,gQ(V,b,p),V.side=vU;else gQ(V,b,p)}this.compile=function(V,b,p=null){if(p===null)p=V;if(B=q$.get(p),B.init(b),A.push(B),p.traverseVisible(function(l){if(l.isLight&&l.layers.test(b.layers)){if(B.pushLight(l),l.castShadow)B.pushShadow(l)}}),V!==p)V.traverseVisible(function(l){if(l.isLight&&l.layers.test(b.layers)){if(B.pushLight(l),l.castShadow)B.pushShadow(l)}});B.setupLights();let u=new Set;return V.traverse(function(l){if(!(l.isMesh||l.isPoints||l.isLine||l.isSprite))return;let V$=l.material;if(V$)if(Array.isArray(V$))for(let z$=0;z$<V$.length;z$++){let L$=V$[z$];Xk(L$,p,l),u.add(L$)}else Xk(V$,p,l),u.add(V$)}),B=A.pop(),u},this.compileAsync=function(V,b,p=null){let u=this.compile(V,b,p);return new Promise((l)=>{function V$(){if(u.forEach(function(z$){if(S.get(z$).currentProgram.isReady())u.delete(z$)}),u.size===0){l(V);return}setTimeout(V$,10)}if(Y6.get("KHR_parallel_shader_compile")!==null)V$();else setTimeout(V$,10)})};let C7=null;function s5(V){if(C7)C7(V)}function Hk(){F0.stop()}function Nk(){F0.start()}let F0=new PZ;if(F0.setAnimationLoop(s5),typeof self<"u")F0.setContext(self);this.setAnimationLoop=function(V){C7=V,E$.setAnimationLoop(V),V===null?F0.stop():F0.start()},E$.addEventListener("sessionstart",Hk),E$.addEventListener("sessionend",Nk),this.render=function(V,b){if(b!==void 0&&b.isCamera!==!0){x$("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(h===!0)return;if(C!==null)C.renderStart(V,b);let p=E$.enabled===!0&&E$.isPresenting===!0,u=D!==null&&(y===null||p)&&D.begin(w,y);if(V.matrixWorldAutoUpdate===!0)V.updateMatrixWorld();if(b.parent===null&&b.matrixWorldAutoUpdate===!0)b.updateMatrixWorld();if(E$.enabled===!0&&E$.isPresenting===!0&&(D===null||D.isCompositing()===!1)){if(E$.cameraAutoUpdate===!0)E$.updateCamera(b);b=E$.getCamera()}if(V.isScene===!0)V.onBeforeRender(w,V,b,y);if(B=q$.get(V,A.length),B.init(b),B.state.textureUnits=n.getTextureUnits(),A.push(B),m6.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse),K6.setFromProjectionMatrix(m6,JH,b.reversedDepth),Q6=this.localClippingEnabled,U6=N$.init(this.clippingPlanes,Q6),L=C$.get(V,z.length),L.init(),z.push(L),E$.enabled===!0&&E$.isPresenting===!0){let z$=w.xr.getDepthSensingMesh();if(z$!==null)S7(z$,b,-1/0,w.sortObjects)}if(S7(V,b,0,w.sortObjects),L.finish(),w.sortObjects===!0)L.sort(F$,v$,b.reversedDepth);if(p6=E$.enabled===!1||E$.isPresenting===!1||E$.hasDepthSensing()===!1,p6)b$.addToRenderList(L,V);if(this.info.render.frame++,this.info.autoReset===!0)this.info.reset();if(U6===!0)N$.beginShadows();let l=B.state.shadowsArray;if(j$.render(l,V,b),U6===!0)N$.endShadows();if((u&&D.hasRenderPass())===!1){let{opaque:z$,transmissive:L$}=L;if(B.setupLights(),b.isArrayCamera){let _$=b.cameras;if(L$.length>0)for(let S$=0,d$=_$.length;S$<d$;S$++){let o$=_$[S$];Gk(z$,L$,V,o$)}if(p6)b$.render(V);for(let S$=0,d$=_$.length;S$<d$;S$++){let o$=_$[S$];Yk(L,V,o$,o$.viewport)}}else{if(L$.length>0)Gk(z$,L$,V,b);if(p6)b$.render(V);Yk(L,V,b)}}if(y!==null&&c===0)n.updateMultisampleRenderTarget(y),n.updateRenderTargetMipmap(y);if(u)D.end(w);if(V.isScene===!0)V.onAfterRender(w,V,b);if(O$.resetDefaultState(),t=-1,e=null,A.pop(),A.length>0){if(B=A[A.length-1],n.setTextureUnits(B.state.textureUnits),U6===!0)N$.setGlobalState(w.clippingPlanes,B.state.camera)}else B=null;if(z.pop(),z.length>0)L=z[z.length-1];else L=null;if(C!==null)C.renderEnd()};function S7(V,b,p,u){if(V.visible===!1)return;if(V.layers.test(b.layers)){if(V.isGroup)p=V.renderOrder;else if(V.isLOD){if(V.autoUpdate===!0)V.update(b)}else if(V.isLightProbeGrid)B.pushLightProbeGrid(V);else if(V.isLight){if(B.pushLight(V),V.castShadow)B.pushShadow(V)}else if(V.isSprite){if(!V.frustumCulled||K6.intersectsSprite(V)){if(u)P6.setFromMatrixPosition(V.matrixWorld).applyMatrix4(m6);let z$=o.update(V),L$=V.material;if(L$.visible)L.push(V,z$,L$,p,P6.z,null)}}else if(V.isMesh||V.isLine||V.isPoints){if(!V.frustumCulled||K6.intersectsObject(V)){let z$=o.update(V),L$=V.material;if(u){if(V.boundingSphere!==void 0){if(V.boundingSphere===null)V.computeBoundingSphere();P6.copy(V.boundingSphere.center)}else{if(z$.boundingSphere===null)z$.computeBoundingSphere();P6.copy(z$.boundingSphere.center)}P6.applyMatrix4(V.matrixWorld).applyMatrix4(m6)}if(Array.isArray(L$)){let _$=z$.groups;for(let S$=0,d$=_$.length;S$<d$;S$++){let o$=_$[S$],T$=L$[o$.materialIndex];if(T$&&T$.visible)L.push(V,z$,T$,p,P6.z,o$)}}else if(L$.visible)L.push(V,z$,L$,p,P6.z,null)}}}let V$=V.children;for(let z$=0,L$=V$.length;z$<L$;z$++)S7(V$[z$],b,p,u)}function Yk(V,b,p,u){let{opaque:l,transmissive:V$,transparent:z$}=V;if(B.setupLightsView(p),U6===!0)N$.setGlobalState(w.clippingPlanes,p);if(u)M.viewport(Y$.copy(u));if(l.length>0)jQ(l,b,p);if(V$.length>0)jQ(V$,b,p);if(z$.length>0)jQ(z$,b,p);M.buffers.depth.setTest(!0),M.buffers.depth.setMask(!0),M.buffers.color.setMask(!0),M.setPolygonOffset(!1)}function Gk(V,b,p,u){if((p.isScene===!0?p.overrideMaterial:null)!==null)return;if(B.state.transmissionRenderTarget[u.id]===void 0){let T$=Y6.has("EXT_color_buffer_half_float")||Y6.has("EXT_color_buffer_float");B.state.transmissionRenderTarget[u.id]=new jU(1,1,{generateMipmaps:!0,type:T$?CJ:nU,minFilter:WJ,samples:Math.max(4,z6.samples),stencilBuffer:W,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:r$.workingColorSpace})}let V$=B.state.transmissionRenderTarget[u.id],z$=u.viewport||Y$;V$.setSize(z$.z*w.transmissionResolutionScale,z$.w*w.transmissionResolutionScale);let L$=w.getRenderTarget(),_$=w.getActiveCubeFace(),S$=w.getActiveMipmapLevel();if(w.setRenderTarget(V$),w.getClearColor($6),n$=w.getClearAlpha(),n$<1)w.setClearColor(16777215,0.5);if(w.clear(),p6)b$.render(p);let d$=w.toneMapping;w.toneMapping=dU;let o$=u.viewport;if(u.viewport!==void 0)u.viewport=void 0;if(B.setupLightsView(u),U6===!0)N$.setGlobalState(w.clippingPlanes,u);if(jQ(V,p,u),n.updateMultisampleRenderTarget(V$),n.updateRenderTargetMipmap(V$),Y6.has("WEBGL_multisampled_render_to_texture")===!1){let T$=!1;for(let k6=0,v6=b.length;k6<v6;k6++){let A6=b[k6],{object:F6,geometry:s6,material:P$,group:DU}=A6;if(P$.side===vU&&F6.layers.test(u.layers)){let X6=P$.side;P$.side=$U,P$.needsUpdate=!0,Ok(F6,p,u,s6,P$,DU),P$.side=X6,P$.needsUpdate=!0,T$=!0}}if(T$===!0)n.updateMultisampleRenderTarget(V$),n.updateRenderTargetMipmap(V$)}if(w.setRenderTarget(L$,_$,S$),w.setClearColor($6,n$),o$!==void 0)u.viewport=o$;w.toneMapping=d$}function jQ(V,b,p){let u=b.isScene===!0?b.overrideMaterial:null;for(let l=0,V$=V.length;l<V$;l++){let z$=V[l],{object:L$,geometry:_$,group:S$}=z$,d$=z$.material;if(d$.allowOverride===!0&&u!==null)d$=u;if(L$.layers.test(p.layers))Ok(L$,b,p,_$,d$,S$)}}function Ok(V,b,p,u,l,V$){if(V.onBeforeRender(w,b,p,u,l,V$),V.modelViewMatrix.multiplyMatrices(p.matrixWorldInverse,V.matrixWorld),V.normalMatrix.getNormalMatrix(V.modelViewMatrix),l.onBeforeRender(w,b,p,u,V,V$),l.transparent===!0&&l.side===vU&&l.forceSinglePass===!1)l.side=$U,l.needsUpdate=!0,w.renderBufferDirect(p,b,u,l,V,V$),l.side=oJ,l.needsUpdate=!0,w.renderBufferDirect(p,b,u,l,V,V$),l.side=vU;else w.renderBufferDirect(p,b,u,l,V,V$);V.onAfterRender(w,b,p,u,l,V$)}function gQ(V,b,p){if(b.isScene!==!0)b=o6;let u=S.get(V),l=B.state.lights,V$=B.state.shadowsArray,z$=l.state.version,L$=a.getParameters(V,l.state,V$,b,p,B.state.lightProbeGridArray),_$=a.getProgramCacheKey(L$),S$=u.programs;u.environment=V.isMeshStandardMaterial||V.isMeshLambertMaterial||V.isMeshPhongMaterial?b.environment:null,u.fog=b.fog;let d$=V.isMeshStandardMaterial||V.isMeshLambertMaterial&&!V.envMap||V.isMeshPhongMaterial&&!V.envMap;if(u.envMap=J$.get(V.envMap||u.environment,d$),u.envMapRotation=u.environment!==null&&V.envMap===null?b.environmentRotation:V.envMapRotation,S$===void 0)V.addEventListener("dispose",aU),S$=new Map,u.programs=S$;let o$=S$.get(_$);if(o$!==void 0){if(u.currentProgram===o$&&u.lightsStateVersion===z$)return kk(V,L$),o$}else{if(L$.uniforms=a.getUniforms(V),C!==null&&V.isNodeMaterial)C.build(V,p,L$);V.onBeforeCompile(L$,w),o$=a.acquireProgram(L$,_$),S$.set(_$,o$),u.uniforms=L$.uniforms}let T$=u.uniforms;if(!V.isShaderMaterial&&!V.isRawShaderMaterial||V.clipping===!0)T$.clippingPlanes=N$.uniform;if(kk(V,L$),u.needsLights=UF(V),u.lightsStateVersion=z$,u.needsLights)T$.ambientLightColor.value=l.state.ambient,T$.lightProbe.value=l.state.probe,T$.directionalLights.value=l.state.directional,T$.directionalLightShadows.value=l.state.directionalShadow,T$.spotLights.value=l.state.spot,T$.spotLightShadows.value=l.state.spotShadow,T$.rectAreaLights.value=l.state.rectArea,T$.ltc_1.value=l.state.rectAreaLTC1,T$.ltc_2.value=l.state.rectAreaLTC2,T$.pointLights.value=l.state.point,T$.pointLightShadows.value=l.state.pointShadow,T$.hemisphereLights.value=l.state.hemi,T$.directionalShadowMatrix.value=l.state.directionalShadowMatrix,T$.spotLightMatrix.value=l.state.spotLightMatrix,T$.spotLightMap.value=l.state.spotLightMap,T$.pointShadowMatrix.value=l.state.pointShadowMatrix;return u.lightProbeGrid=B.state.lightProbeGridArray.length>0,u.currentProgram=o$,u.uniformsList=null,o$}function Ek(V){if(V.uniformsList===null){let b=V.currentProgram.getUniforms();V.uniformsList=pW.seqWithValue(b.seq,V.uniforms)}return V.uniformsList}function kk(V,b){let p=S.get(V);p.outputColorSpace=b.outputColorSpace,p.batching=b.batching,p.batchingColor=b.batchingColor,p.instancing=b.instancing,p.instancingColor=b.instancingColor,p.instancingMorph=b.instancingMorph,p.skinning=b.skinning,p.morphTargets=b.morphTargets,p.morphNormals=b.morphNormals,p.morphColors=b.morphColors,p.morphTargetsCount=b.morphTargetsCount,p.numClippingPlanes=b.numClippingPlanes,p.numIntersection=b.numClipIntersection,p.vertexAlphas=b.vertexAlphas,p.vertexTangents=b.vertexTangents,p.toneMapping=b.toneMapping}function t5(V,b){if(V.length===0)return null;if(V.length===1)return V[0].texture!==null?V[0]:null;P.setFromMatrixPosition(b.matrixWorld);for(let p=0,u=V.length;p<u;p++){let l=V[p];if(l.texture!==null&&l.boundingBox.containsPoint(P))return l}return null}function e5(V,b,p,u,l){if(b.isScene!==!0)b=o6;n.resetTextureUnits();let V$=b.fog,z$=u.isMeshStandardMaterial||u.isMeshLambertMaterial||u.isMeshPhongMaterial?b.environment:null,L$=y===null?w.outputColorSpace:y.isXRRenderTarget===!0?y.texture.colorSpace:r$.workingColorSpace,_$=u.isMeshStandardMaterial||u.isMeshLambertMaterial&&!u.envMap||u.isMeshPhongMaterial&&!u.envMap,S$=J$.get(u.envMap||z$,_$),d$=u.vertexColors===!0&&!!p.attributes.color&&p.attributes.color.itemSize===4,o$=!!p.attributes.tangent&&(!!u.normalMap||u.anisotropy>0),T$=!!p.morphAttributes.position,k6=!!p.morphAttributes.normal,v6=!!p.morphAttributes.color,A6=dU;if(u.toneMapped){if(y===null||y.isXRRenderTarget===!0)A6=w.toneMapping}let F6=p.morphAttributes.position||p.morphAttributes.normal||p.morphAttributes.color,s6=F6!==void 0?F6.length:0,P$=S.get(u),DU=B.state.lights;if(U6===!0){if(Q6===!0||V!==e){let M6=V===e&&u.id===t;N$.setState(u,V,M6)}}let X6=!1;if(u.version===P$.__version){if(P$.needsLights&&P$.lightsStateVersion!==DU.state.version)X6=!0;else if(P$.outputColorSpace!==L$)X6=!0;else if(l.isBatchedMesh&&P$.batching===!1)X6=!0;else if(!l.isBatchedMesh&&P$.batching===!0)X6=!0;else if(l.isBatchedMesh&&P$.batchingColor===!0&&l.colorTexture===null)X6=!0;else if(l.isBatchedMesh&&P$.batchingColor===!1&&l.colorTexture!==null)X6=!0;else if(l.isInstancedMesh&&P$.instancing===!1)X6=!0;else if(!l.isInstancedMesh&&P$.instancing===!0)X6=!0;else if(l.isSkinnedMesh&&P$.skinning===!1)X6=!0;else if(!l.isSkinnedMesh&&P$.skinning===!0)X6=!0;else if(l.isInstancedMesh&&P$.instancingColor===!0&&l.instanceColor===null)X6=!0;else if(l.isInstancedMesh&&P$.instancingColor===!1&&l.instanceColor!==null)X6=!0;else if(l.isInstancedMesh&&P$.instancingMorph===!0&&l.morphTexture===null)X6=!0;else if(l.isInstancedMesh&&P$.instancingMorph===!1&&l.morphTexture!==null)X6=!0;else if(P$.envMap!==S$)X6=!0;else if(u.fog===!0&&P$.fog!==V$)X6=!0;else if(P$.numClippingPlanes!==void 0&&(P$.numClippingPlanes!==N$.numPlanes||P$.numIntersection!==N$.numIntersection))X6=!0;else if(P$.vertexAlphas!==d$)X6=!0;else if(P$.vertexTangents!==o$)X6=!0;else if(P$.morphTargets!==T$)X6=!0;else if(P$.morphNormals!==k6)X6=!0;else if(P$.morphColors!==v6)X6=!0;else if(P$.toneMapping!==A6)X6=!0;else if(P$.morphTargetsCount!==s6)X6=!0;else if(!!P$.lightProbeGrid!==B.state.lightProbeGridArray.length>0)X6=!0}else X6=!0,P$.__version=u.version;let CU=P$.currentProgram;if(X6===!0){if(CU=gQ(u,b,l),C&&u.isNodeMaterial)C.onUpdateProgram(u,CU,P$)}let sU=!1,xJ=!1,i0=!1,L6=CU.getUniforms(),j6=P$.uniforms;if(M.useProgram(CU.program))sU=!0,xJ=!0,i0=!0;if(u.id!==t)t=u.id,xJ=!0;if(P$.needsLights){let M6=t5(B.state.lightProbeGridArray,l);if(P$.lightProbeGrid!==M6)P$.lightProbeGrid=M6,xJ=!0}if(sU||e!==V){if(M.buffers.depth.getReversed()&&V.reversedDepth!==!0)V._reversedDepth=!0,V.updateProjectionMatrix();L6.setValue(v,"projectionMatrix",V.projectionMatrix),L6.setValue(v,"viewMatrix",V.matrixWorldInverse);let fJ=L6.map.cameraPosition;if(fJ!==void 0)fJ.setValue(v,_U.setFromMatrixPosition(V.matrixWorld));if(z6.logarithmicDepthBuffer)L6.setValue(v,"logDepthBufFC",2/(Math.log(V.far+1)/Math.LN2));if(u.isMeshPhongMaterial||u.isMeshToonMaterial||u.isMeshLambertMaterial||u.isMeshBasicMaterial||u.isMeshStandardMaterial||u.isShaderMaterial)L6.setValue(v,"isOrthographic",V.isOrthographicCamera===!0);if(e!==V)e=V,xJ=!0,i0=!0}if(P$.needsLights){if(DU.state.directionalShadowMap.length>0)L6.setValue(v,"directionalShadowMap",DU.state.directionalShadowMap,n);if(DU.state.spotShadowMap.length>0)L6.setValue(v,"spotShadowMap",DU.state.spotShadowMap,n);if(DU.state.pointShadowMap.length>0)L6.setValue(v,"pointShadowMap",DU.state.pointShadowMap,n)}if(l.isSkinnedMesh){L6.setOptional(v,l,"bindMatrix"),L6.setOptional(v,l,"bindMatrixInverse");let M6=l.skeleton;if(M6){if(M6.boneTexture===null)M6.computeBoneTexture();L6.setValue(v,"boneTexture",M6.boneTexture,n)}}if(l.isBatchedMesh){if(L6.setOptional(v,l,"batchingTexture"),L6.setValue(v,"batchingTexture",l._matricesTexture,n),L6.setOptional(v,l,"batchingIdTexture"),L6.setValue(v,"batchingIdTexture",l._indirectTexture,n),L6.setOptional(v,l,"batchingColorTexture"),l._colorsTexture!==null)L6.setValue(v,"batchingColorTexture",l._colorsTexture,n)}let hJ=p.morphAttributes;if(hJ.position!==void 0||hJ.normal!==void 0||hJ.color!==void 0)H6.update(l,p,CU);if(xJ||P$.receiveShadow!==l.receiveShadow)P$.receiveShadow=l.receiveShadow,L6.setValue(v,"receiveShadow",l.receiveShadow);if((u.isMeshStandardMaterial||u.isMeshLambertMaterial||u.isMeshPhongMaterial)&&u.envMap===null&&b.environment!==null)j6.envMapIntensity.value=b.environmentIntensity;if(j6.dfgLUT!==void 0)j6.dfgLUT.value=iw();if(xJ){if(L6.setValue(v,"toneMappingExposure",w.toneMappingExposure),P$.needsLights)$F(j6,i0);if(V$&&u.fog===!0)M$.refreshFogUniforms(j6,V$);if(M$.refreshMaterialUniforms(j6,u,D$,X$,B.state.transmissionRenderTarget[V.id]),P$.needsLights&&P$.lightProbeGrid){let M6=P$.lightProbeGrid;j6.probesSH.value=M6.texture,j6.probesMin.value.copy(M6.boundingBox.min),j6.probesMax.value.copy(M6.boundingBox.max),j6.probesResolution.value.copy(M6.resolution)}pW.upload(v,Ek(P$),j6,n)}if(u.isShaderMaterial&&u.uniformsNeedUpdate===!0)pW.upload(v,Ek(P$),j6,n),u.uniformsNeedUpdate=!1;if(u.isSpriteMaterial)L6.setValue(v,"center",l.center);if(L6.setValue(v,"modelViewMatrix",l.modelViewMatrix),L6.setValue(v,"normalMatrix",l.normalMatrix),L6.setValue(v,"modelMatrix",l.matrixWorld),u.uniformsGroups!==void 0){let M6=u.uniformsGroups;for(let fJ=0,o0=M6.length;fJ<o0;fJ++){let qk=M6[fJ];B$.update(qk,CU),B$.bind(qk,CU)}}return CU}function $F(V,b){V.ambientLightColor.needsUpdate=b,V.lightProbe.needsUpdate=b,V.directionalLights.needsUpdate=b,V.directionalLightShadows.needsUpdate=b,V.pointLights.needsUpdate=b,V.pointLightShadows.needsUpdate=b,V.spotLights.needsUpdate=b,V.spotLightShadows.needsUpdate=b,V.rectAreaLights.needsUpdate=b,V.hemisphereLights.needsUpdate=b}function UF(V){return V.isMeshLambertMaterial||V.isMeshToonMaterial||V.isMeshPhongMaterial||V.isMeshStandardMaterial||V.isShadowMaterial||V.isShaderMaterial&&V.lights===!0}if(this.getActiveCubeFace=function(){return d},this.getActiveMipmapLevel=function(){return c},this.getRenderTarget=function(){return y},this.setRenderTargetTextures=function(V,b,p){let u=S.get(V);if(u.__autoAllocateDepthBuffer=V.resolveDepthBuffer===!1,u.__autoAllocateDepthBuffer===!1)u.__useRenderToTexture=!1;S.get(V.texture).__webglTexture=b,S.get(V.depthTexture).__webglTexture=u.__autoAllocateDepthBuffer?void 0:p,u.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(V,b){let p=S.get(V);p.__webglFramebuffer=b,p.__useDefaultFramebuffer=b===void 0},this.setRenderTarget=function(V,b=0,p=0){y=V,d=b,c=p;let u=null,l=!1,V$=!1;if(V){let L$=S.get(V);if(L$.__useDefaultFramebuffer!==void 0){M.bindFramebuffer(v.FRAMEBUFFER,L$.__webglFramebuffer),Y$.copy(V.viewport),R$.copy(V.scissor),w$=V.scissorTest,M.viewport(Y$),M.scissor(R$),M.setScissorTest(w$),t=-1;return}else if(L$.__webglFramebuffer===void 0)n.setupRenderTarget(V);else if(L$.__hasExternalTextures)n.rebindTextures(V,S.get(V.texture).__webglTexture,S.get(V.depthTexture).__webglTexture);else if(V.depthBuffer){let d$=V.depthTexture;if(L$.__boundDepthTexture!==d$){if(d$!==null&&S.has(d$)&&(V.width!==d$.image.width||V.height!==d$.image.height))throw Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");n.setupDepthRenderbuffer(V)}}let _$=V.texture;if(_$.isData3DTexture||_$.isDataArrayTexture||_$.isCompressedArrayTexture)V$=!0;let S$=S.get(V).__webglFramebuffer;if(V.isWebGLCubeRenderTarget){if(Array.isArray(S$[b]))u=S$[b][p];else u=S$[b];l=!0}else if(V.samples>0&&n.useMultisampledRTT(V)===!1)u=S.get(V).__webglMultisampledFramebuffer;else if(Array.isArray(S$))u=S$[p];else u=S$;Y$.copy(V.viewport),R$.copy(V.scissor),w$=V.scissorTest}else Y$.copy(t$).multiplyScalar(D$).floor(),R$.copy(u$).multiplyScalar(D$).floor(),w$=p$;if(p!==0)u=f;if(M.bindFramebuffer(v.FRAMEBUFFER,u))M.drawBuffers(V,u);if(M.viewport(Y$),M.scissor(R$),M.setScissorTest(w$),l){let L$=S.get(V.texture);v.framebufferTexture2D(v.FRAMEBUFFER,v.COLOR_ATTACHMENT0,v.TEXTURE_CUBE_MAP_POSITIVE_X+b,L$.__webglTexture,p)}else if(V$){let L$=b;for(let _$=0;_$<V.textures.length;_$++){let S$=S.get(V.textures[_$]);v.framebufferTextureLayer(v.FRAMEBUFFER,v.COLOR_ATTACHMENT0+_$,S$.__webglTexture,p,L$)}}else if(V!==null&&p!==0){let L$=S.get(V.texture);v.framebufferTexture2D(v.FRAMEBUFFER,v.COLOR_ATTACHMENT0,v.TEXTURE_2D,L$.__webglTexture,p)}t=-1},this.readRenderTargetPixels=function(V,b,p,u,l,V$,z$,L$=0){if(!(V&&V.isWebGLRenderTarget)){x$("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let _$=S.get(V).__webglFramebuffer;if(V.isWebGLCubeRenderTarget&&z$!==void 0)_$=_$[z$];if(_$){M.bindFramebuffer(v.FRAMEBUFFER,_$);try{let S$=V.textures[L$],d$=S$.format,o$=S$.type;if(V.textures.length>1)v.readBuffer(v.COLOR_ATTACHMENT0+L$);if(!z6.textureFormatReadable(d$)){x$("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!z6.textureTypeReadable(o$)){x$("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(b>=0&&b<=V.width-u&&(p>=0&&p<=V.height-l))v.readPixels(b,p,u,l,r.convert(d$),r.convert(o$),V$)}finally{let S$=y!==null?S.get(y).__webglFramebuffer:null;M.bindFramebuffer(v.FRAMEBUFFER,S$)}}},this.readRenderTargetPixelsAsync=async function(V,b,p,u,l,V$,z$,L$=0){if(!(V&&V.isWebGLRenderTarget))throw Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let _$=S.get(V).__webglFramebuffer;if(V.isWebGLCubeRenderTarget&&z$!==void 0)_$=_$[z$];if(_$)if(b>=0&&b<=V.width-u&&(p>=0&&p<=V.height-l)){M.bindFramebuffer(v.FRAMEBUFFER,_$);let S$=V.textures[L$],d$=S$.format,o$=S$.type;if(V.textures.length>1)v.readBuffer(v.COLOR_ATTACHMENT0+L$);if(!z6.textureFormatReadable(d$))throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!z6.textureTypeReadable(o$))throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let T$=v.createBuffer();v.bindBuffer(v.PIXEL_PACK_BUFFER,T$),v.bufferData(v.PIXEL_PACK_BUFFER,V$.byteLength,v.STREAM_READ),v.readPixels(b,p,u,l,r.convert(d$),r.convert(o$),0);let k6=y!==null?S.get(y).__webglFramebuffer:null;M.bindFramebuffer(v.FRAMEBUFFER,k6);let v6=v.fenceSync(v.SYNC_GPU_COMMANDS_COMPLETE,0);return v.flush(),await iq(v,v6,4),v.bindBuffer(v.PIXEL_PACK_BUFFER,T$),v.getBufferSubData(v.PIXEL_PACK_BUFFER,0,V$),v.deleteBuffer(T$),v.deleteSync(v6),V$}else throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(V,b=null,p=0){let u=Math.pow(2,-p),l=Math.floor(V.image.width*u),V$=Math.floor(V.image.height*u),z$=b!==null?b.x:0,L$=b!==null?b.y:0;n.setTexture2D(V,0),v.copyTexSubImage2D(v.TEXTURE_2D,p,0,0,z$,L$,l,V$),M.unbindTexture()},this.copyTextureToTexture=function(V,b,p=null,u=null,l=0,V$=0){let z$,L$,_$,S$,d$,o$,T$,k6,v6,A6=V.isCompressedTexture?V.mipmaps[V$]:V.image;if(p!==null)z$=p.max.x-p.min.x,L$=p.max.y-p.min.y,_$=p.isBox3?p.max.z-p.min.z:1,S$=p.min.x,d$=p.min.y,o$=p.isBox3?p.min.z:0;else{let j6=Math.pow(2,-l);if(z$=Math.floor(A6.width*j6),L$=Math.floor(A6.height*j6),V.isDataArrayTexture)_$=A6.depth;else if(V.isData3DTexture)_$=Math.floor(A6.depth*j6);else _$=1;S$=0,d$=0,o$=0}if(u!==null)T$=u.x,k6=u.y,v6=u.z;else T$=0,k6=0,v6=0;let F6=r.convert(b.format),s6=r.convert(b.type),P$;if(b.isData3DTexture)n.setTexture3D(b,0),P$=v.TEXTURE_3D;else if(b.isDataArrayTexture||b.isCompressedArrayTexture)n.setTexture2DArray(b,0),P$=v.TEXTURE_2D_ARRAY;else n.setTexture2D(b,0),P$=v.TEXTURE_2D;M.activeTexture(v.TEXTURE0),M.pixelStorei(v.UNPACK_FLIP_Y_WEBGL,b.flipY),M.pixelStorei(v.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),M.pixelStorei(v.UNPACK_ALIGNMENT,b.unpackAlignment);let DU=M.getParameter(v.UNPACK_ROW_LENGTH),X6=M.getParameter(v.UNPACK_IMAGE_HEIGHT),CU=M.getParameter(v.UNPACK_SKIP_PIXELS),sU=M.getParameter(v.UNPACK_SKIP_ROWS),xJ=M.getParameter(v.UNPACK_SKIP_IMAGES);M.pixelStorei(v.UNPACK_ROW_LENGTH,A6.width),M.pixelStorei(v.UNPACK_IMAGE_HEIGHT,A6.height),M.pixelStorei(v.UNPACK_SKIP_PIXELS,S$),M.pixelStorei(v.UNPACK_SKIP_ROWS,d$),M.pixelStorei(v.UNPACK_SKIP_IMAGES,o$);let i0=V.isDataArrayTexture||V.isData3DTexture,L6=b.isDataArrayTexture||b.isData3DTexture;if(V.isDepthTexture){let j6=S.get(V),hJ=S.get(b),M6=S.get(j6.__renderTarget),fJ=S.get(hJ.__renderTarget);M.bindFramebuffer(v.READ_FRAMEBUFFER,M6.__webglFramebuffer),M.bindFramebuffer(v.DRAW_FRAMEBUFFER,fJ.__webglFramebuffer);for(let o0=0;o0<_$;o0++){if(i0)v.framebufferTextureLayer(v.READ_FRAMEBUFFER,v.COLOR_ATTACHMENT0,S.get(V).__webglTexture,l,o$+o0),v.framebufferTextureLayer(v.DRAW_FRAMEBUFFER,v.COLOR_ATTACHMENT0,S.get(b).__webglTexture,V$,v6+o0);v.blitFramebuffer(S$,d$,z$,L$,T$,k6,z$,L$,v.DEPTH_BUFFER_BIT,v.NEAREST)}M.bindFramebuffer(v.READ_FRAMEBUFFER,null),M.bindFramebuffer(v.DRAW_FRAMEBUFFER,null)}else if(l!==0||V.isRenderTargetTexture||S.has(V)){let j6=S.get(V),hJ=S.get(b);M.bindFramebuffer(v.READ_FRAMEBUFFER,s),M.bindFramebuffer(v.DRAW_FRAMEBUFFER,x);for(let M6=0;M6<_$;M6++){if(i0)v.framebufferTextureLayer(v.READ_FRAMEBUFFER,v.COLOR_ATTACHMENT0,j6.__webglTexture,l,o$+M6);else v.framebufferTexture2D(v.READ_FRAMEBUFFER,v.COLOR_ATTACHMENT0,v.TEXTURE_2D,j6.__webglTexture,l);if(L6)v.framebufferTextureLayer(v.DRAW_FRAMEBUFFER,v.COLOR_ATTACHMENT0,hJ.__webglTexture,V$,v6+M6);else v.framebufferTexture2D(v.DRAW_FRAMEBUFFER,v.COLOR_ATTACHMENT0,v.TEXTURE_2D,hJ.__webglTexture,V$);if(l!==0)v.blitFramebuffer(S$,d$,z$,L$,T$,k6,z$,L$,v.COLOR_BUFFER_BIT,v.NEAREST);else if(L6)v.copyTexSubImage3D(P$,V$,T$,k6,v6+M6,S$,d$,z$,L$);else v.copyTexSubImage2D(P$,V$,T$,k6,S$,d$,z$,L$)}M.bindFramebuffer(v.READ_FRAMEBUFFER,null),M.bindFramebuffer(v.DRAW_FRAMEBUFFER,null)}else if(L6)if(V.isDataTexture||V.isData3DTexture)v.texSubImage3D(P$,V$,T$,k6,v6,z$,L$,_$,F6,s6,A6.data);else if(b.isCompressedArrayTexture)v.compressedTexSubImage3D(P$,V$,T$,k6,v6,z$,L$,_$,F6,A6.data);else v.texSubImage3D(P$,V$,T$,k6,v6,z$,L$,_$,F6,s6,A6);else if(V.isDataTexture)v.texSubImage2D(v.TEXTURE_2D,V$,T$,k6,z$,L$,F6,s6,A6.data);else if(V.isCompressedTexture)v.compressedTexSubImage2D(v.TEXTURE_2D,V$,T$,k6,A6.width,A6.height,F6,A6.data);else v.texSubImage2D(v.TEXTURE_2D,V$,T$,k6,z$,L$,F6,s6,A6);if(M.pixelStorei(v.UNPACK_ROW_LENGTH,DU),M.pixelStorei(v.UNPACK_IMAGE_HEIGHT,X6),M.pixelStorei(v.UNPACK_SKIP_PIXELS,CU),M.pixelStorei(v.UNPACK_SKIP_ROWS,sU),M.pixelStorei(v.UNPACK_SKIP_IMAGES,xJ),V$===0&&b.generateMipmaps)v.generateMipmap(P$);M.unbindTexture()},this.initRenderTarget=function(V){if(S.get(V).__webglFramebuffer===void 0)n.setupRenderTarget(V)},this.initTexture=function(V){if(V.isCubeTexture)n.setTextureCube(V,0);else if(V.isData3DTexture)n.setTexture3D(V,0);else if(V.isDataArrayTexture||V.isCompressedArrayTexture)n.setTexture2DArray(V,0);else n.setTexture2D(V,0);M.unbindTexture()},this.resetState=function(){d=0,c=0,y=null,M.reset(),O$.reset()},typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return JH}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace($){this._outputColorSpace=$;let U=this.getContext();U.drawingBufferColorSpace=r$._getDrawingBufferColorSpace($),U.unpackColorSpace=r$._getUnpackColorSpace()}}function bH($,U){if(U===tX)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),$;if(U===R8||U===PW){let J=$.getIndex();if(J===null){let X=[],H=$.getAttribute("position");if(H!==void 0){for(let N=0;N<H.count;N++)X.push(N);$.setIndex(X),J=$.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),$}let Q=J.count-2,W=[];if(U===R8)for(let X=1;X<=Q;X++)W.push(J.getX(0)),W.push(J.getX(X)),W.push(J.getX(X+1));else for(let X=0;X<Q;X++)if(X%2===0)W.push(J.getX(X)),W.push(J.getX(X+1)),W.push(J.getX(X+2));else W.push(J.getX(X+2)),W.push(J.getX(X+1)),W.push(J.getX(X));if(W.length/3!==Q)console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let K=$.clone();return K.setIndex(W),K.clearGroups(),K}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",U),$}function fZ($){let U=new Map,J=new Map,Q=$.clone();return uZ($,Q,function(W,K){U.set(K,W),J.set(W,K)}),Q.traverse(function(W){if(!W.isSkinnedMesh)return;let K=W,X=U.get(W),H=X.skeleton.bones;K.skeleton=X.skeleton.clone(),K.bindMatrix.copy(X.bindMatrix),K.skeleton.bones=H.map(function(N){return J.get(N)}),K.bind(K.skeleton,K.bindMatrix)}),Q}function uZ($,U,J){J($,U);for(let Q=0;Q<$.children.length;Q++)uZ($.children[Q],U.children[Q],J)}class mH extends vJ{constructor($){super($);this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(U){return new oZ(U)}),this.register(function(U){return new rZ(U)}),this.register(function(U){return new QI(U)}),this.register(function(U){return new KI(U)}),this.register(function(U){return new XI(U)}),this.register(function(U){return new sZ(U)}),this.register(function(U){return new tZ(U)}),this.register(function(U){return new eZ(U)}),this.register(function(U){return new $I(U)}),this.register(function(U){return new iZ(U)}),this.register(function(U){return new UI(U)}),this.register(function(U){return new aZ(U)}),this.register(function(U){return new WI(U)}),this.register(function(U){return new JI(U)}),this.register(function(U){return new cZ(U)}),this.register(function(U){return new fH(U,e$.EXT_MESHOPT_COMPRESSION)}),this.register(function(U){return new fH(U,e$.KHR_MESHOPT_COMPRESSION)}),this.register(function(U){return new HI(U)})}load($,U,J,Q){let W=this,K;if(this.resourcePath!=="")K=this.resourcePath;else if(this.path!==""){let N=K0.extractUrlBase($);K=K0.resolveURL(N,this.path)}else K=K0.extractUrlBase($);this.manager.itemStart($);let X=function(N){if(Q)Q(N);else console.error(N);W.manager.itemError($),W.manager.itemEnd($)},H=new hW(this.manager);H.setPath(this.path),H.setResponseType("arraybuffer"),H.setRequestHeader(this.requestHeader),H.setWithCredentials(this.withCredentials),H.load($,function(N){try{W.parse(N,K,function(Y){U(Y),W.manager.itemEnd($)},X)}catch(Y){X(Y)}},J,X)}setDRACOLoader($){return this.dracoLoader=$,this}setKTX2Loader($){return this.ktx2Loader=$,this}setMeshoptDecoder($){return this.meshoptDecoder=$,this}register($){if(this.pluginCallbacks.indexOf($)===-1)this.pluginCallbacks.push($);return this}unregister($){if(this.pluginCallbacks.indexOf($)!==-1)this.pluginCallbacks.splice(this.pluginCallbacks.indexOf($),1);return this}parse($,U,J,Q){let W,K={},X={},H=new TextDecoder;if(typeof $==="string")W=JSON.parse($);else if($ instanceof ArrayBuffer)if(H.decode(new Uint8Array($,0,4))===NI){try{K[e$.KHR_BINARY_GLTF]=new YI($)}catch(G){if(Q)Q(G);return}W=JSON.parse(K[e$.KHR_BINARY_GLTF].content)}else W=JSON.parse(H.decode($));else W=$;if(W.asset===void 0||W.asset.version[0]<2){if(Q)Q(Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let N=new qI(W,{path:U||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});N.fileLoader.setRequestHeader(this.requestHeader);for(let Y=0;Y<this.pluginCallbacks.length;Y++){let G=this.pluginCallbacks[Y](N);if(!G.name)console.error("THREE.GLTFLoader: Invalid plugin found: missing name");X[G.name]=G,K[G.name]=!0}if(W.extensionsUsed)for(let Y=0;Y<W.extensionsUsed.length;++Y){let G=W.extensionsUsed[Y],O=W.extensionsRequired||[];switch(G){case e$.KHR_MATERIALS_UNLIT:K[G]=new nZ;break;case e$.KHR_DRACO_MESH_COMPRESSION:K[G]=new GI(W,this.dracoLoader);break;case e$.KHR_TEXTURE_TRANSFORM:K[G]=new OI;break;case e$.KHR_MESH_QUANTIZATION:K[G]=new EI;break;default:if(O.indexOf(G)>=0&&X[G]===void 0)console.warn('THREE.GLTFLoader: Unknown extension "'+G+'".')}}N.setExtensions(K),N.setPlugins(X),N.parse(J,Q)}parseAsync($,U){let J=this;return new Promise(function(Q,W){J.parse($,U,Q,W)})}}function rw(){let $={};return{get:function(U){return $[U]},add:function(U,J){$[U]=J},remove:function(U){delete $[U]},removeAll:function(){$={}}}}function g6($,U,J){let Q=$.json.materials[U];if(Q.extensions&&Q.extensions[J])return Q.extensions[J];return null}var e$={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"};class cZ{constructor($){this.parser=$,this.name=e$.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let $=this.parser,U=this.parser.json.nodes||[];for(let J=0,Q=U.length;J<Q;J++){let W=U[J];if(W.extensions&&W.extensions[this.name]&&W.extensions[this.name].light!==void 0)$._addNodeRef(this.cache,W.extensions[this.name].light)}}_loadLight($){let U=this.parser,J="light:"+$,Q=U.cache.get(J);if(Q)return Q;let W=U.json,H=((W.extensions&&W.extensions[this.name]||{}).lights||[])[$],N,Y=new y$(16777215);if(H.color!==void 0)Y.setRGB(H.color[0],H.color[1],H.color[2],RU);let G=H.range!==void 0?H.range:0;switch(H.type){case"directional":N=new _8(Y),N.target.position.set(0,0,-1),N.add(N.target);break;case"point":N=new z8(Y),N.distance=G;break;case"spot":N=new h9(Y),N.distance=G,H.spot=H.spot||{},H.spot.innerConeAngle=H.spot.innerConeAngle!==void 0?H.spot.innerConeAngle:0,H.spot.outerConeAngle=H.spot.outerConeAngle!==void 0?H.spot.outerConeAngle:Math.PI/4,N.angle=H.spot.outerConeAngle,N.penumbra=1-H.spot.innerConeAngle/H.spot.outerConeAngle,N.target.position.set(0,0,-1),N.add(N.target);break;default:throw Error("THREE.GLTFLoader: Unexpected light type: "+H.type)}if(N.position.set(0,0,0),NJ(N,H),H.intensity!==void 0)N.intensity=H.intensity;return N.name=U.createUniqueName(H.name||"light_"+$),Q=Promise.resolve(N),U.cache.add(J,Q),Q}getDependency($,U){if($!=="light")return;return this._loadLight(U)}createNodeAttachment($){let U=this,J=this.parser,W=J.json.nodes[$],X=(W.extensions&&W.extensions[this.name]||{}).light;if(X===void 0)return null;return this._loadLight(X).then(function(H){return J._getNodeRef(U.cache,X,H)})}}class nZ{constructor(){this.name=e$.KHR_MATERIALS_UNLIT}getMaterialType(){return KJ}extendParams($,U,J){let Q=[];$.color=new y$(1,1,1),$.opacity=1;let W=U.pbrMetallicRoughness;if(W){if(Array.isArray(W.baseColorFactor)){let K=W.baseColorFactor;$.color.setRGB(K[0],K[1],K[2],RU),$.opacity=K[3]}if(W.baseColorTexture!==void 0)Q.push(J.assignTexture($,"map",W.baseColorTexture,aJ))}return Promise.all(Q)}}class iZ{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();if(J.emissiveStrength!==void 0)U.emissiveIntensity=J.emissiveStrength;return Promise.resolve()}}class oZ{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_CLEARCOAT}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(J.clearcoatFactor!==void 0)U.clearcoat=J.clearcoatFactor;if(J.clearcoatTexture!==void 0)Q.push(this.parser.assignTexture(U,"clearcoatMap",J.clearcoatTexture));if(J.clearcoatRoughnessFactor!==void 0)U.clearcoatRoughness=J.clearcoatRoughnessFactor;if(J.clearcoatRoughnessTexture!==void 0)Q.push(this.parser.assignTexture(U,"clearcoatRoughnessMap",J.clearcoatRoughnessTexture));if(J.clearcoatNormalTexture!==void 0){if(Q.push(this.parser.assignTexture(U,"clearcoatNormalMap",J.clearcoatNormalTexture)),J.clearcoatNormalTexture.scale!==void 0){let W=J.clearcoatNormalTexture.scale;U.clearcoatNormalScale=new g$(W,W)}}return Promise.all(Q)}}class rZ{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_DISPERSION}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();return U.dispersion=J.dispersion!==void 0?J.dispersion:0,Promise.resolve()}}class aZ{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_IRIDESCENCE}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(J.iridescenceFactor!==void 0)U.iridescence=J.iridescenceFactor;if(J.iridescenceTexture!==void 0)Q.push(this.parser.assignTexture(U,"iridescenceMap",J.iridescenceTexture));if(J.iridescenceIor!==void 0)U.iridescenceIOR=J.iridescenceIor;if(U.iridescenceThicknessRange===void 0)U.iridescenceThicknessRange=[100,400];if(J.iridescenceThicknessMinimum!==void 0)U.iridescenceThicknessRange[0]=J.iridescenceThicknessMinimum;if(J.iridescenceThicknessMaximum!==void 0)U.iridescenceThicknessRange[1]=J.iridescenceThicknessMaximum;if(J.iridescenceThicknessTexture!==void 0)Q.push(this.parser.assignTexture(U,"iridescenceThicknessMap",J.iridescenceThicknessTexture));return Promise.all(Q)}}class sZ{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_SHEEN}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(U.sheenColor=new y$(0,0,0),U.sheenRoughness=0,U.sheen=1,J.sheenColorFactor!==void 0){let W=J.sheenColorFactor;U.sheenColor.setRGB(W[0],W[1],W[2],RU)}if(J.sheenRoughnessFactor!==void 0)U.sheenRoughness=J.sheenRoughnessFactor;if(J.sheenColorTexture!==void 0)Q.push(this.parser.assignTexture(U,"sheenColorMap",J.sheenColorTexture,aJ));if(J.sheenRoughnessTexture!==void 0)Q.push(this.parser.assignTexture(U,"sheenRoughnessMap",J.sheenRoughnessTexture));return Promise.all(Q)}}class tZ{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_TRANSMISSION}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(J.transmissionFactor!==void 0)U.transmission=J.transmissionFactor;if(J.transmissionTexture!==void 0)Q.push(this.parser.assignTexture(U,"transmissionMap",J.transmissionTexture));return Promise.all(Q)}}class eZ{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_VOLUME}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(U.thickness=J.thicknessFactor!==void 0?J.thicknessFactor:0,J.thicknessTexture!==void 0)Q.push(this.parser.assignTexture(U,"thicknessMap",J.thicknessTexture));U.attenuationDistance=J.attenuationDistance||1/0;let W=J.attenuationColor||[1,1,1];return U.attenuationColor=new y$().setRGB(W[0],W[1],W[2],RU),Promise.all(Q)}}class $I{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_IOR}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();if(U.ior=J.ior!==void 0?J.ior:1.5,U.ior===0)U.ior=1000;return Promise.resolve()}}class UI{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_SPECULAR}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(U.specularIntensity=J.specularFactor!==void 0?J.specularFactor:1,J.specularTexture!==void 0)Q.push(this.parser.assignTexture(U,"specularIntensityMap",J.specularTexture));let W=J.specularColorFactor||[1,1,1];if(U.specularColor=new y$().setRGB(W[0],W[1],W[2],RU),J.specularColorTexture!==void 0)Q.push(this.parser.assignTexture(U,"specularColorMap",J.specularColorTexture,aJ));return Promise.all(Q)}}class JI{constructor($){this.parser=$,this.name=e$.EXT_MATERIALS_BUMP}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(U.bumpScale=J.bumpFactor!==void 0?J.bumpFactor:1,J.bumpTexture!==void 0)Q.push(this.parser.assignTexture(U,"bumpMap",J.bumpTexture));return Promise.all(Q)}}class WI{constructor($){this.parser=$,this.name=e$.KHR_MATERIALS_ANISOTROPY}getMaterialType($){return g6(this.parser,$,this.name)!==null?wU:null}extendMaterialParams($,U){let J=g6(this.parser,$,this.name);if(J===null)return Promise.resolve();let Q=[];if(J.anisotropyStrength!==void 0)U.anisotropy=J.anisotropyStrength;if(J.anisotropyRotation!==void 0)U.anisotropyRotation=J.anisotropyRotation;if(J.anisotropyTexture!==void 0)Q.push(this.parser.assignTexture(U,"anisotropyMap",J.anisotropyTexture));return Promise.all(Q)}}class QI{constructor($){this.parser=$,this.name=e$.KHR_TEXTURE_BASISU}loadTexture($){let U=this.parser,J=U.json,Q=J.textures[$];if(!Q.extensions||!Q.extensions[this.name])return null;let W=Q.extensions[this.name],K=U.options.ktx2Loader;if(!K)if(J.extensionsRequired&&J.extensionsRequired.indexOf(this.name)>=0)throw Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");else return null;return U.loadTextureImage($,W.source,K)}}class KI{constructor($){this.parser=$,this.name=e$.EXT_TEXTURE_WEBP}loadTexture($){let U=this.name,J=this.parser,Q=J.json,W=Q.textures[$];if(!W.extensions||!W.extensions[U])return null;let K=W.extensions[U],X=Q.images[K.source],H=J.textureLoader;if(X.uri){let N=J.options.manager.getHandler(X.uri);if(N!==null)H=N}return J.loadTextureImage($,K.source,H)}}class XI{constructor($){this.parser=$,this.name=e$.EXT_TEXTURE_AVIF}loadTexture($){let U=this.name,J=this.parser,Q=J.json,W=Q.textures[$];if(!W.extensions||!W.extensions[U])return null;let K=W.extensions[U],X=Q.images[K.source],H=J.textureLoader;if(X.uri){let N=J.options.manager.getHandler(X.uri);if(N!==null)H=N}return J.loadTextureImage($,K.source,H)}}class fH{constructor($,U){this.name=U,this.parser=$}loadBufferView($){let U=this.parser.json,J=U.bufferViews[$];if(J.extensions&&J.extensions[this.name]){let Q=J.extensions[this.name],W=this.parser.getDependency("buffer",Q.buffer),K=this.parser.options.meshoptDecoder;if(!K||!K.supported)if(U.extensionsRequired&&U.extensionsRequired.indexOf(this.name)>=0)throw Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");else return null;return W.then(function(X){let H=Q.byteOffset||0,N=Q.byteLength||0,Y=Q.count,G=Q.byteStride,O=new Uint8Array(X,H,N);if(K.decodeGltfBufferAsync)return K.decodeGltfBufferAsync(Y,G,O,Q.mode,Q.filter).then(function(E){return E.buffer});else return K.ready.then(function(){let E=new ArrayBuffer(Y*G);return K.decodeGltfBuffer(new Uint8Array(E),Y,G,O,Q.mode,Q.filter),E})})}else return null}}class HI{constructor($){this.name=e$.EXT_MESH_GPU_INSTANCING,this.parser=$}createNodeMesh($){let U=this.parser.json,J=U.nodes[$];if(!J.extensions||!J.extensions[this.name]||J.mesh===void 0)return null;let Q=U.meshes[J.mesh];for(let N of Q.primitives)if(N.mode!==bU.TRIANGLES&&N.mode!==bU.TRIANGLE_STRIP&&N.mode!==bU.TRIANGLE_FAN&&N.mode!==void 0)return null;let K=J.extensions[this.name].attributes,X=[],H={};for(let N in K)X.push(this.parser.getDependency("accessor",K[N]).then((Y)=>{return H[N]=Y,H[N]}));if(X.length<1)return null;return X.push(this.parser.createNodeMesh($)),Promise.all(X).then((N)=>{let Y=N.pop(),G=Y.isGroup?Y.children:[Y],O=N[0].count,E=[];for(let k of G){let I=new m$,R=new j,q=new c6,Z=new j(1,1,1),_=new M8(k.geometry,k.material,O);for(let P=0;P<O;P++){if(H.TRANSLATION)R.fromBufferAttribute(H.TRANSLATION,P);if(H.ROTATION)q.fromBufferAttribute(H.ROTATION,P);if(H.SCALE)Z.fromBufferAttribute(H.SCALE,P);_.setMatrixAt(P,I.compose(R,q,Z))}for(let P in H)if(P==="_COLOR_0"){let L=H[P];_.instanceColor=new P0(L.array,L.itemSize,L.normalized)}else if(P!=="TRANSLATION"&&P!=="ROTATION"&&P!=="SCALE")k.geometry.setAttribute(P,H[P]);q6.prototype.copy.call(_,k),this.parser.assignFinalMaterial(_),E.push(_)}if(Y.isGroup)return Y.clear(),Y.add(...E),Y;return E[0]})}}var NI="glTF",cW=12,lZ={JSON:1313821514,BIN:5130562};class YI{constructor($){this.name=e$.KHR_BINARY_GLTF,this.content=null,this.body=null;let U=new DataView($,0,cW),J=new TextDecoder;if(this.header={magic:J.decode(new Uint8Array($.slice(0,4))),version:U.getUint32(4,!0),length:U.getUint32(8,!0)},this.header.magic!==NI)throw Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");else if(this.header.version<2)throw Error("THREE.GLTFLoader: Legacy binary file detected.");let Q=this.header.length-cW,W=new DataView($,cW),K=0;while(K<Q){let X=W.getUint32(K,!0);K+=4;let H=W.getUint32(K,!0);if(K+=4,H===lZ.JSON){let N=new Uint8Array($,cW+K,X);this.content=J.decode(N)}else if(H===lZ.BIN){let N=cW+K;this.body=$.slice(N,N+X)}K+=X}if(this.content===null)throw Error("THREE.GLTFLoader: JSON content not found.")}}class GI{constructor($,U){if(!U)throw Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=e$.KHR_DRACO_MESH_COMPRESSION,this.json=$,this.dracoLoader=U,this.dracoLoader.preload()}decodePrimitive($,U){let J=this.json,Q=this.dracoLoader,W=$.extensions[this.name].bufferView,K=$.extensions[this.name].attributes,X={},H={},N={};for(let Y in K){let G=uH[Y]||Y.toLowerCase();X[G]=K[Y]}for(let Y in $.attributes){let G=uH[Y]||Y.toLowerCase();if(K[Y]!==void 0){let O=J.accessors[$.attributes[Y]],E=S8[O.componentType];N[G]=E.name,H[G]=O.normalized===!0}}return U.getDependency("bufferView",W).then(function(Y){return new Promise(function(G,O){Q.decodeDracoFile(Y,function(E){for(let k in E.attributes){let I=E.attributes[k],R=H[k];if(R!==void 0)I.normalized=R}G(E)},X,N,RU,O)})})}}class OI{constructor(){this.name=e$.KHR_TEXTURE_TRANSFORM}extendTexture($,U){if((U.texCoord===void 0||U.texCoord===$.channel)&&U.offset===void 0&&U.rotation===void 0&&U.scale===void 0)return $;if($=$.clone(),U.texCoord!==void 0)$.channel=U.texCoord;if(U.offset!==void 0)$.offset.fromArray(U.offset);if(U.rotation!==void 0)$.rotation=U.rotation;if(U.scale!==void 0)$.repeat.fromArray(U.scale);return $.needsUpdate=!0,$}}class EI{constructor(){this.name=e$.KHR_MESH_QUANTIZATION}}class pH extends TJ{constructor($,U,J,Q){super($,U,J,Q)}copySampleValue_($){let U=this.resultBuffer,J=this.sampleValues,Q=this.valueSize,W=$*Q*3+Q;for(let K=0;K!==Q;K++)U[K]=J[W+K];return U}interpolate_($,U,J,Q){let W=this.resultBuffer,K=this.sampleValues,X=this.valueSize,H=X*2,N=X*3,Y=Q-U,G=(J-U)/Y,O=G*G,E=O*G,k=$*N,I=k-N,R=-2*E+3*O,q=E-O,Z=1-R,_=q-O+G;for(let P=0;P!==X;P++){let L=K[I+P+X],B=K[I+P+H]*Y,z=K[k+P+X],A=K[k+P]*Y;W[P]=Z*L+_*B+R*z+q*A}return W}}var aw=new c6;class kI extends pH{interpolate_($,U,J,Q){let W=super.interpolate_($,U,J,Q);return aw.fromArray(W).normalize().toArray(W),W}}var bU={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},S8={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},mZ={9728:cU,9729:n6,9984:E9,9985:F8,9986:_0,9987:WJ},pZ={33071:D8,33648:O9,10497:I8},yH={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},uH={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"},H0={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},sw={CUBICSPLINE:void 0,LINEAR:L9,STEP:sX},xH={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function tw($){if($.DefaultMaterial===void 0)$.DefaultMaterial=new SJ({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:oJ});return $.DefaultMaterial}function y0($,U,J){for(let Q in J.extensions)if($[Q]===void 0)U.userData.gltfExtensions=U.userData.gltfExtensions||{},U.userData.gltfExtensions[Q]=J.extensions[Q]}function NJ($,U){if(U.extras!==void 0)if(typeof U.extras==="object")Object.assign($.userData,U.extras);else console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+U.extras)}function ew($,U,J){let Q=!1,W=!1,K=!1;for(let Y=0,G=U.length;Y<G;Y++){let O=U[Y];if(O.POSITION!==void 0)Q=!0;if(O.NORMAL!==void 0)W=!0;if(O.COLOR_0!==void 0)K=!0;if(Q&&W&&K)break}if(!Q&&!W&&!K)return Promise.resolve($);let X=[],H=[],N=[];for(let Y=0,G=U.length;Y<G;Y++){let O=U[Y];if(Q){let E=O.POSITION!==void 0?J.getDependency("accessor",O.POSITION):$.attributes.position;X.push(E)}if(W){let E=O.NORMAL!==void 0?J.getDependency("accessor",O.NORMAL):$.attributes.normal;H.push(E)}if(K){let E=O.COLOR_0!==void 0?J.getDependency("accessor",O.COLOR_0):$.attributes.color;N.push(E)}}return Promise.all([Promise.all(X),Promise.all(H),Promise.all(N)]).then(function(Y){let G=Y[0],O=Y[1],E=Y[2];if(Q)$.morphAttributes.position=G;if(W)$.morphAttributes.normal=O;if(K)$.morphAttributes.color=E;return $.morphTargetsRelative=!0,$})}function $M($,U){if($.updateMorphTargets(),U.weights!==void 0)for(let J=0,Q=U.weights.length;J<Q;J++)$.morphTargetInfluences[J]=U.weights[J];if(U.extras&&Array.isArray(U.extras.targetNames)){let J=U.extras.targetNames;if($.morphTargetInfluences.length===J.length){$.morphTargetDictionary={};for(let Q=0,W=J.length;Q<W;Q++)$.morphTargetDictionary[J[Q]]=Q}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function UM($){let U,J=$.extensions&&$.extensions[e$.KHR_DRACO_MESH_COMPRESSION];if(J)U="draco:"+J.bufferView+":"+J.indices+":"+hH(J.attributes);else U=$.indices+":"+hH($.attributes)+":"+$.mode;if($.targets!==void 0)for(let Q=0,W=$.targets.length;Q<W;Q++)U+=":"+hH($.targets[Q]);return U}function hH($){let U="",J=Object.keys($).sort();for(let Q=0,W=J.length;Q<W;Q++)U+=J[Q]+":"+$[J[Q]]+";";return U}function lH($){switch($){case Int8Array:return 0.007874015748031496;case Uint8Array:return 0.00392156862745098;case Int16Array:return 0.00003051850947599719;case Uint16Array:return 0.000015259021896696422;default:throw Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function JM($){if($.search(/\.jpe?g($|\?)/i)>0||$.search(/^data\:image\/jpeg/)===0)return"image/jpeg";if($.search(/\.webp($|\?)/i)>0||$.search(/^data\:image\/webp/)===0)return"image/webp";if($.search(/\.ktx2($|\?)/i)>0||$.search(/^data\:image\/ktx2/)===0)return"image/ktx2";return"image/png"}var WM=new m$;class qI{constructor($={},U={}){this.json=$,this.extensions={},this.plugins={},this.options=U,this.cache=new rw,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 J=!1,Q=-1,W=!1,K=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){let X=navigator.userAgent;J=/^((?!chrome|android).)*safari/i.test(X)===!0;let H=X.match(/Version\/(\d+)/);Q=J&&H?parseInt(H[1],10):-1,W=X.indexOf("Firefox")>-1,K=W?X.match(/Firefox\/([0-9]+)\./)[1]:-1}if(typeof createImageBitmap>"u"||J&&Q<17||W&&K<98)this.textureLoader=new g9(this.options.manager);else this.textureLoader=new f9(this.options.manager);if(this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new hW(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials")this.fileLoader.setWithCredentials(!0)}setExtensions($){this.extensions=$}setPlugins($){this.plugins=$}parse($,U){let J=this,Q=this.json,W=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(K){return K._markDefs&&K._markDefs()}),Promise.all(this._invokeAll(function(K){return K.beforeRoot&&K.beforeRoot()})).then(function(){return Promise.all([J.getDependencies("scene"),J.getDependencies("animation"),J.getDependencies("camera")])}).then(function(K){let X={scene:K[0][Q.scene||0],scenes:K[0],animations:K[1],cameras:K[2],asset:Q.asset,parser:J,userData:{}};return y0(W,X,Q),NJ(X,Q),Promise.all(J._invokeAll(function(H){return H.afterRoot&&H.afterRoot(X)})).then(function(){for(let H of X.scenes)H.updateMatrixWorld();$(X)})}).catch(U)}_markDefs(){let $=this.json.nodes||[],U=this.json.skins||[],J=this.json.meshes||[];for(let Q=0,W=U.length;Q<W;Q++){let K=U[Q].joints;for(let X=0,H=K.length;X<H;X++)$[K[X]].isBone=!0}for(let Q=0,W=$.length;Q<W;Q++){let K=$[Q];if(K.mesh!==void 0){if(this._addNodeRef(this.meshCache,K.mesh),K.skin!==void 0)J[K.mesh].isSkinnedMesh=!0}if(K.camera!==void 0)this._addNodeRef(this.cameraCache,K.camera)}}_addNodeRef($,U){if(U===void 0)return;if($.refs[U]===void 0)$.refs[U]=$.uses[U]=0;$.refs[U]++}_getNodeRef($,U,J){if($.refs[U]<=1)return J;let Q=J.clone(),W=(K,X)=>{let H=this.associations.get(K);if(H!=null)this.associations.set(X,H);for(let[N,Y]of K.children.entries())W(Y,X.children[N])};return W(J,Q),Q.name+="_instance_"+$.uses[U]++,Q}_invokeOne($){let U=Object.values(this.plugins);U.push(this);for(let J=0;J<U.length;J++){let Q=$(U[J]);if(Q)return Q}return null}_invokeAll($){let U=Object.values(this.plugins);U.unshift(this);let J=[];for(let Q=0;Q<U.length;Q++){let W=$(U[Q]);if(W)J.push(W)}return J}getDependency($,U){let J=$+":"+U,Q=this.cache.get(J);if(!Q){switch($){case"scene":Q=this.loadScene(U);break;case"node":Q=this._invokeOne(function(W){return W.loadNode&&W.loadNode(U)});break;case"mesh":Q=this._invokeOne(function(W){return W.loadMesh&&W.loadMesh(U)});break;case"accessor":Q=this.loadAccessor(U);break;case"bufferView":Q=this._invokeOne(function(W){return W.loadBufferView&&W.loadBufferView(U)});break;case"buffer":Q=this.loadBuffer(U);break;case"material":Q=this._invokeOne(function(W){return W.loadMaterial&&W.loadMaterial(U)});break;case"texture":Q=this._invokeOne(function(W){return W.loadTexture&&W.loadTexture(U)});break;case"skin":Q=this.loadSkin(U);break;case"animation":Q=this._invokeOne(function(W){return W.loadAnimation&&W.loadAnimation(U)});break;case"camera":Q=this.loadCamera(U);break;default:if(Q=this._invokeOne(function(W){return W!=this&&W.getDependency&&W.getDependency($,U)}),!Q)throw Error("Unknown type: "+$);break}this.cache.add(J,Q)}return Q}getDependencies($){let U=this.cache.get($);if(!U){let J=this,Q=this.json[$+($==="mesh"?"es":"s")]||[];U=Promise.all(Q.map(function(W,K){return J.getDependency($,K)})),this.cache.add($,U)}return U}loadBuffer($){let U=this.json.buffers[$],J=this.fileLoader;if(U.type&&U.type!=="arraybuffer")throw Error("THREE.GLTFLoader: "+U.type+" buffer type is not supported.");if(U.uri===void 0&&$===0)return Promise.resolve(this.extensions[e$.KHR_BINARY_GLTF].body);let Q=this.options;return new Promise(function(W,K){J.load(K0.resolveURL(U.uri,Q.path),W,void 0,function(){K(Error('THREE.GLTFLoader: Failed to load buffer "'+U.uri+'".'))})})}loadBufferView($){let U=this.json.bufferViews[$];return this.getDependency("buffer",U.buffer).then(function(J){let Q=U.byteLength||0,W=U.byteOffset||0;return J.slice(W,W+Q)})}loadAccessor($){let U=this,J=this.json,Q=this.json.accessors[$];if(Q.bufferView===void 0&&Q.sparse===void 0){let K=yH[Q.type],X=S8[Q.componentType],H=Q.normalized===!0,N=new X(Q.count*K);return Promise.resolve(new h6(N,K,H))}let W=[];if(Q.bufferView!==void 0)W.push(this.getDependency("bufferView",Q.bufferView));else W.push(null);if(Q.sparse!==void 0)W.push(this.getDependency("bufferView",Q.sparse.indices.bufferView)),W.push(this.getDependency("bufferView",Q.sparse.values.bufferView));return Promise.all(W).then(function(K){let X=K[0],H=yH[Q.type],N=S8[Q.componentType],Y=N.BYTES_PER_ELEMENT,G=Y*H,O=Q.byteOffset||0,E=Q.bufferView!==void 0?J.bufferViews[Q.bufferView].byteStride:void 0,k=Q.normalized===!0,I,R;if(E&&E!==G){let q=Math.floor(O/E),Z="InterleavedBuffer:"+Q.bufferView+":"+Q.componentType+":"+q+":"+Q.count,_=U.cache.get(Z);if(!_)I=new N(X,q*E,Q.count*E/Y),_=new CW(I,E/Y),U.cache.add(Z,_);R=new w8(_,H,O%E/Y,k)}else{if(X===null)I=new N(Q.count*H);else I=new N(X,O,Q.count*H);R=new h6(I,H,k)}if(Q.sparse!==void 0){let q=yH.SCALAR,Z=S8[Q.sparse.indices.componentType],_=Q.sparse.indices.byteOffset||0,P=Q.sparse.values.byteOffset||0,L=new Z(K[1],_,Q.sparse.count*q),B=new N(K[2],P,Q.sparse.count*H);if(X!==null)R=new h6(R.array.slice(),R.itemSize,R.normalized);R.normalized=!1;for(let z=0,A=L.length;z<A;z++){let D=L[z];if(R.setX(D,B[z*H]),H>=2)R.setY(D,B[z*H+1]);if(H>=3)R.setZ(D,B[z*H+2]);if(H>=4)R.setW(D,B[z*H+3]);if(H>=5)throw Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}R.normalized=k}return R})}loadTexture($){let U=this.json,J=this.options,W=U.textures[$].source,K=U.images[W],X=this.textureLoader;if(K.uri){let H=J.manager.getHandler(K.uri);if(H!==null)X=H}return this.loadTextureImage($,W,X)}loadTextureImage($,U,J){let Q=this,W=this.json,K=W.textures[$],X=W.images[U],H=(X.uri||X.bufferView)+":"+K.sampler;if(this.textureCache[H])return this.textureCache[H];let N=this.loadImageSource(U,J).then(function(Y){if(Y.flipY=!1,Y.name=K.name||X.name||"",Y.name===""&&typeof X.uri==="string"&&X.uri.startsWith("data:image/")===!1)Y.name=X.uri;let O=(W.samplers||{})[K.sampler]||{};return Y.magFilter=mZ[O.magFilter]||n6,Y.minFilter=mZ[O.minFilter]||WJ,Y.wrapS=pZ[O.wrapS]||I8,Y.wrapT=pZ[O.wrapT]||I8,Y.generateMipmaps=!Y.isCompressedTexture&&Y.minFilter!==cU&&Y.minFilter!==n6,Q.associations.set(Y,{textures:$}),Y}).catch(function(){return null});return this.textureCache[H]=N,N}loadImageSource($,U){let J=this,Q=this.json,W=this.options;if(this.sourceCache[$]!==void 0)return this.sourceCache[$].then((G)=>G.clone());let K=Q.images[$],X=self.URL||self.webkitURL,H=K.uri||"",N=!1;if(K.bufferView!==void 0)H=J.getDependency("bufferView",K.bufferView).then(function(G){N=!0;let O=new Blob([G],{type:K.mimeType});return H=X.createObjectURL(O),H});else if(K.uri===void 0)throw Error("THREE.GLTFLoader: Image "+$+" is missing URI and bufferView");let Y=Promise.resolve(H).then(function(G){return new Promise(function(O,E){let k=O;if(U.isImageBitmapLoader===!0)k=function(I){let R=new C6(I);R.needsUpdate=!0,O(R)};U.load(K0.resolveURL(G,W.path),k,void 0,E)})}).then(function(G){if(N===!0)X.revokeObjectURL(H);return NJ(G,K),G.userData.mimeType=K.mimeType||JM(K.uri),G}).catch(function(G){throw console.error("THREE.GLTFLoader: Couldn't load texture",H),G});return this.sourceCache[$]=Y,Y}assignTexture($,U,J,Q){let W=this;return this.getDependency("texture",J.index).then(function(K){if(!K)return null;if(J.texCoord!==void 0&&J.texCoord>0)K=K.clone(),K.channel=J.texCoord;if(W.extensions[e$.KHR_TEXTURE_TRANSFORM]){let X=J.extensions!==void 0?J.extensions[e$.KHR_TEXTURE_TRANSFORM]:void 0;if(X){let H=W.associations.get(K);K=W.extensions[e$.KHR_TEXTURE_TRANSFORM].extendTexture(K,X),W.associations.set(K,H)}}if(Q!==void 0)K.colorSpace=Q;return $[U]=K,K})}assignFinalMaterial($){let{geometry:U,material:J}=$,Q=U.attributes.tangent===void 0,W=U.attributes.color!==void 0,K=U.attributes.normal===void 0;if($.isPoints){let X="PointsMaterial:"+J.uuid,H=this.cache.get(X);if(!H)H=new bW,EU.prototype.copy.call(H,J),H.color.copy(J.color),H.map=J.map,H.sizeAttenuation=!1,this.cache.add(X,H);J=H}else if($.isLine){let X="LineBasicMaterial:"+J.uuid,H=this.cache.get(X);if(!H)H=new gW,EU.prototype.copy.call(H,J),H.color.copy(J.color),H.map=J.map,this.cache.add(X,H);J=H}if(Q||W||K){let X="ClonedMaterial:"+J.uuid+":";if(Q)X+="derivative-tangents:";if(W)X+="vertex-colors:";if(K)X+="flat-shading:";let H=this.cache.get(X);if(!H){if(H=J.clone(),W)H.vertexColors=!0;if(K)H.flatShading=!0;if(Q){if(H.normalScale)H.normalScale.y*=-1;if(H.clearcoatNormalScale)H.clearcoatNormalScale.y*=-1}this.cache.add(X,H),this.associations.set(H,this.associations.get(J))}J=H}$.material=J}getMaterialType(){return SJ}loadMaterial($){let U=this,J=this.json,Q=this.extensions,W=J.materials[$],K,X={},H=W.extensions||{},N=[];if(H[e$.KHR_MATERIALS_UNLIT]){let G=Q[e$.KHR_MATERIALS_UNLIT];K=G.getMaterialType(),N.push(G.extendParams(X,W,U))}else{let G=W.pbrMetallicRoughness||{};if(X.color=new y$(1,1,1),X.opacity=1,Array.isArray(G.baseColorFactor)){let O=G.baseColorFactor;X.color.setRGB(O[0],O[1],O[2],RU),X.opacity=O[3]}if(G.baseColorTexture!==void 0)N.push(U.assignTexture(X,"map",G.baseColorTexture,aJ));if(X.metalness=G.metallicFactor!==void 0?G.metallicFactor:1,X.roughness=G.roughnessFactor!==void 0?G.roughnessFactor:1,G.metallicRoughnessTexture!==void 0)N.push(U.assignTexture(X,"metalnessMap",G.metallicRoughnessTexture)),N.push(U.assignTexture(X,"roughnessMap",G.metallicRoughnessTexture));K=this._invokeOne(function(O){return O.getMaterialType&&O.getMaterialType($)}),N.push(Promise.all(this._invokeAll(function(O){return O.extendMaterialParams&&O.extendMaterialParams($,X)})))}if(W.doubleSided===!0)X.side=vU;let Y=W.alphaMode||xH.OPAQUE;if(Y===xH.BLEND)X.transparent=!0,X.depthWrite=!1;else if(X.transparent=!1,Y===xH.MASK)X.alphaTest=W.alphaCutoff!==void 0?W.alphaCutoff:0.5;if(W.normalTexture!==void 0&&K!==KJ){if(N.push(U.assignTexture(X,"normalMap",W.normalTexture)),X.normalScale=new g$(1,1),W.normalTexture.scale!==void 0){let G=W.normalTexture.scale;X.normalScale.set(G,G)}}if(W.occlusionTexture!==void 0&&K!==KJ){if(N.push(U.assignTexture(X,"aoMap",W.occlusionTexture)),W.occlusionTexture.strength!==void 0)X.aoMapIntensity=W.occlusionTexture.strength}if(W.emissiveFactor!==void 0&&K!==KJ){let G=W.emissiveFactor;X.emissive=new y$().setRGB(G[0],G[1],G[2],RU)}if(W.emissiveTexture!==void 0&&K!==KJ)N.push(U.assignTexture(X,"emissiveMap",W.emissiveTexture,aJ));return Promise.all(N).then(function(){let G=new K(X);if(W.name)G.name=W.name;if(NJ(G,W),U.associations.set(G,{materials:$}),W.extensions)y0(Q,G,W);return G})}createUniqueName($){let U=N6.sanitizeNodeName($||"");if(U in this.nodeNamesUsed)return U+"_"+ ++this.nodeNamesUsed[U];else return this.nodeNamesUsed[U]=0,U}loadGeometries($){let U=this,J=this.extensions,Q=this.primitiveCache;function W(X){return J[e$.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(X,U).then(function(H){return dZ(H,X,U)})}let K=[];for(let X=0,H=$.length;X<H;X++){let N=$[X],Y=UM(N),G=Q[Y];if(G)K.push(G.promise);else{let O;if(N.extensions&&N.extensions[e$.KHR_DRACO_MESH_COMPRESSION])O=W(N);else O=dZ(new KU,N,U);Q[Y]={primitive:N,promise:O},K.push(O)}}return Promise.all(K)}loadMesh($){let U=this,J=this.json,Q=this.extensions,W=J.meshes[$],K=W.primitives,X=[];for(let H=0,N=K.length;H<N;H++){let Y=K[H].material===void 0?tw(this.cache):this.getDependency("material",K[H].material);X.push(Y)}return X.push(U.loadGeometries(K)),Promise.all(X).then(function(H){let N=H.slice(0,H.length-1),Y=H[H.length-1],G=[];for(let E=0,k=Y.length;E<k;E++){let I=Y[E],R=K[E],q,Z=N[E];if(R.mode===bU.TRIANGLES||R.mode===bU.TRIANGLE_STRIP||R.mode===bU.TRIANGLE_FAN||R.mode===void 0){if(q=W.isSkinnedMesh===!0?new z9(I,Z):new B6(I,Z),q.isSkinnedMesh===!0)q.normalizeSkinWeights();if(R.mode===bU.TRIANGLE_STRIP)q.geometry=bH(q.geometry,PW);else if(R.mode===bU.TRIANGLE_FAN)q.geometry=bH(q.geometry,R8)}else if(R.mode===bU.LINES)q=new _9(I,Z);else if(R.mode===bU.LINE_STRIP)q=new tJ(I,Z);else if(R.mode===bU.LINE_LOOP)q=new A9(I,Z);else if(R.mode===bU.POINTS)q=new B8(I,Z);else throw Error("THREE.GLTFLoader: Primitive mode unsupported: "+R.mode);if(Object.keys(q.geometry.morphAttributes).length>0)$M(q,W);if(q.name=U.createUniqueName(W.name||"mesh_"+$),NJ(q,W),R.extensions)y0(Q,q,R);U.assignFinalMaterial(q),G.push(q)}for(let E=0,k=G.length;E<k;E++)U.associations.set(G[E],{meshes:$,primitives:E});if(G.length===1){if(W.extensions)y0(Q,G[0],W);return G[0]}let O=new eU;if(W.extensions)y0(Q,O,W);U.associations.set(O,{meshes:$});for(let E=0,k=G.length;E<k;E++)O.add(G[E]);return O})}loadCamera($){let U,J=this.json.cameras[$],Q=J[J.type];if(!Q){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}if(J.type==="perspective")U=new x6(zW.radToDeg(Q.yfov),Q.aspectRatio||1,Q.znear||1,Q.zfar||2000000);else if(J.type==="orthographic")U=new g0(-Q.xmag,Q.xmag,Q.ymag,-Q.ymag,Q.znear,Q.zfar);if(J.name)U.name=this.createUniqueName(J.name);return NJ(U,J),Promise.resolve(U)}loadSkin($){let U=this.json.skins[$],J=[];for(let Q=0,W=U.joints.length;Q<W;Q++)J.push(this._loadNodeShallow(U.joints[Q]));if(U.inverseBindMatrices!==void 0)J.push(this.getDependency("accessor",U.inverseBindMatrices));else J.push(null);return Promise.all(J).then(function(Q){let W=Q.pop(),K=Q,X=[],H=[];for(let N=0,Y=K.length;N<Y;N++){let G=K[N];if(G){X.push(G);let O=new m$;if(W!==null)O.fromArray(W.array,N*16);H.push(O)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',U.joints[N])}return new vW(X,H)})}loadAnimation($){let U=this.json,J=this,Q=U.animations[$],W=Q.name?Q.name:"animation_"+$,K=[],X=[],H=[],N=[],Y=[];for(let G=0,O=Q.channels.length;G<O;G++){let E=Q.channels[G],k=Q.samplers[E.sampler],I=E.target,R=I.node,q=Q.parameters!==void 0?Q.parameters[k.input]:k.input,Z=Q.parameters!==void 0?Q.parameters[k.output]:k.output;if(I.node===void 0)continue;K.push(this.getDependency("node",R)),X.push(this.getDependency("accessor",q)),H.push(this.getDependency("accessor",Z)),N.push(k),Y.push(I)}return Promise.all([Promise.all(K),Promise.all(X),Promise.all(H),Promise.all(N),Promise.all(Y)]).then(function(G){let O=G[0],E=G[1],k=G[2],I=G[3],R=G[4],q=[];for(let _=0,P=O.length;_<P;_++){let L=O[_],B=E[_],z=k[_],A=I[_],D=R[_];if(L===void 0)continue;if(L.updateMatrix)L.updateMatrix();let w=J._createAnimationTracks(L,B,z,A,D);if(w)for(let h=0;h<w.length;h++)q.push(w[h])}let Z=new E8(W,void 0,q);return NJ(Z,Q),Z})}createNodeMesh($){let U=this.json,J=this,Q=U.nodes[$];if(Q.mesh===void 0)return null;return J.getDependency("mesh",Q.mesh).then(function(W){let K=J._getNodeRef(J.meshCache,Q.mesh,W);if(Q.weights!==void 0)K.traverse(function(X){if(!X.isMesh)return;for(let H=0,N=Q.weights.length;H<N;H++)X.morphTargetInfluences[H]=Q.weights[H]});return K})}loadNode($){let U=this.json,J=this,Q=U.nodes[$],W=J._loadNodeShallow($),K=[],X=Q.children||[];for(let N=0,Y=X.length;N<Y;N++)K.push(J.getDependency("node",X[N]));let H=Q.skin===void 0?Promise.resolve(null):J.getDependency("skin",Q.skin);return Promise.all([W,Promise.all(K),H]).then(function(N){let Y=N[0],G=N[1],O=N[2];if(O!==null)Y.traverse(function(E){if(!E.isSkinnedMesh)return;E.bind(O,WM)});for(let E=0,k=G.length;E<k;E++)Y.add(G[E]);if(Y.userData.pivot!==void 0&&G.length>0){let E=Y.userData.pivot,k=G[0];Y.pivot=new j().fromArray(E),Y.position.x-=E[0],Y.position.y-=E[1],Y.position.z-=E[2],k.position.set(0,0,0),delete Y.userData.pivot}return Y})}_loadNodeShallow($){let U=this.json,J=this.extensions,Q=this;if(this.nodeCache[$]!==void 0)return this.nodeCache[$];let W=U.nodes[$],K=W.name?Q.createUniqueName(W.name):"",X=[],H=Q._invokeOne(function(N){return N.createNodeMesh&&N.createNodeMesh($)});if(H)X.push(H);if(W.camera!==void 0)X.push(Q.getDependency("camera",W.camera).then(function(N){return Q._getNodeRef(Q.cameraCache,W.camera,N)}));return Q._invokeAll(function(N){return N.createNodeAttachment&&N.createNodeAttachment($)}).forEach(function(N){X.push(N)}),this.nodeCache[$]=Promise.all(X).then(function(N){let Y;if(W.isBone===!0)Y=new SW;else if(N.length>1)Y=new eU;else if(N.length===1)Y=N[0];else Y=new q6;if(Y!==N[0])for(let G=0,O=N.length;G<O;G++)Y.add(N[G]);if(W.name)Y.userData.name=W.name,Y.name=K;if(NJ(Y,W),W.extensions)y0(J,Y,W);if(W.matrix!==void 0){let G=new m$;G.fromArray(W.matrix),Y.applyMatrix4(G)}else{if(W.translation!==void 0)Y.position.fromArray(W.translation);if(W.rotation!==void 0)Y.quaternion.fromArray(W.rotation);if(W.scale!==void 0)Y.scale.fromArray(W.scale)}if(!Q.associations.has(Y))Q.associations.set(Y,{});else if(W.mesh!==void 0&&Q.meshCache.refs[W.mesh]>1){let G=Q.associations.get(Y);Q.associations.set(Y,{...G})}return Q.associations.get(Y).nodes=$,Y}),this.nodeCache[$]}loadScene($){let U=this.extensions,J=this.json.scenes[$],Q=this,W=new eU;if(J.name)W.name=Q.createUniqueName(J.name);if(NJ(W,J),J.extensions)y0(U,W,J);let K=J.nodes||[],X=[];for(let H=0,N=K.length;H<N;H++)X.push(Q.getDependency("node",K[H]));return Promise.all(X).then(function(H){for(let Y=0,G=H.length;Y<G;Y++){let O=H[Y];if(O.parent!==null)W.add(fZ(O));else W.add(O)}let N=(Y)=>{let G=new Map;for(let[O,E]of Q.associations)if(O instanceof EU||O instanceof C6)G.set(O,E);return Y.traverse((O)=>{let E=Q.associations.get(O);if(E!=null)G.set(O,E)}),G};return Q.associations=N(W),W})}_createAnimationTracks($,U,J,Q,W){let K=[],X=$.name?$.name:$.uuid,H=[];function N(E){if(E.morphTargetInfluences)H.push(E.name?E.name:E.uuid)}if(H0[W.path]===H0.weights){if(N($),$.isGroup)$.children.forEach(N)}else H.push(X);let Y;switch(H0[W.path]){case H0.weights:Y=J0;break;case H0.rotation:Y=W0;break;case H0.translation:case H0.scale:Y=j0;break;default:switch(J.itemSize){case 1:Y=J0;break;case 2:case 3:default:Y=j0;break}break}let G=Q.interpolation!==void 0?sw[Q.interpolation]:L9,O=this._getArrayFromAccessor(J);for(let E=0,k=H.length;E<k;E++){let I=new Y(H[E]+"."+H0[W.path],U.array,O,G);if(Q.interpolation==="CUBICSPLINE")this._createCubicSplineTrackInterpolant(I);K.push(I)}return K}_getArrayFromAccessor($){let U=$.array;if($.normalized){let J=lH(U.constructor),Q=new Float32Array(U.length);for(let W=0,K=U.length;W<K;W++)Q[W]=U[W]*J;U=Q}return U}_createCubicSplineTrackInterpolant($){$.createInterpolant=function(J){return new(this instanceof W0?kI:pH)(this.times,this.values,this.getValueSize()/3,J)},$.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function QM($,U,J){let Q=U.attributes,W=new QU;if(Q.POSITION!==void 0){let H=J.json.accessors[Q.POSITION],N=H.min,Y=H.max;if(N!==void 0&&Y!==void 0){if(W.set(new j(N[0],N[1],N[2]),new j(Y[0],Y[1],Y[2])),H.normalized){let G=lH(S8[H.componentType]);W.min.multiplyScalar(G),W.max.multiplyScalar(G)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let K=U.targets;if(K!==void 0){let H=new j,N=new j;for(let Y=0,G=K.length;Y<G;Y++){let O=K[Y];if(O.POSITION!==void 0){let E=J.json.accessors[O.POSITION],k=E.min,I=E.max;if(k!==void 0&&I!==void 0){if(N.setX(Math.max(Math.abs(k[0]),Math.abs(I[0]))),N.setY(Math.max(Math.abs(k[1]),Math.abs(I[1]))),N.setZ(Math.max(Math.abs(k[2]),Math.abs(I[2]))),E.normalized){let R=lH(S8[E.componentType]);N.multiplyScalar(R)}H.max(N)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}W.expandByVector(H)}$.boundingBox=W;let X=new VU;W.getCenter(X.center),X.radius=W.min.distanceTo(W.max)/2,$.boundingSphere=X}function dZ($,U,J){let Q=U.attributes,W=[];function K(X,H){return J.getDependency("accessor",X).then(function(N){$.setAttribute(H,N)})}for(let X in Q){let H=uH[X]||X.toLowerCase();if(H in $.attributes)continue;W.push(K(Q[X],H))}if(U.indices!==void 0&&!$.index){let X=J.getDependency("accessor",U.indices).then(function(H){$.setIndex(H)});W.push(X)}if(r$.workingColorSpace!==RU&&"COLOR_0"in Q)console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${r$.workingColorSpace}" not supported.`);return NJ($,U),QM($,U,J),Promise.all(W).then(function(){return U.targets!==void 0?ew($,U.targets,J):$})}var ZI={type:"change"},cH={type:"start"},DI={type:"end"},n9=new sJ,II=new lU,KM=Math.cos(70*zW.DEG2RAD),l6=new j,kU=2*Math.PI,Z6={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},dH=0.000001;class nH extends l9{constructor($,U=null){super($,U);if(this.state=Z6.NONE,this.target=new j,this.cursor=new j,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=0.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:nJ.ROTATE,MIDDLE:nJ.DOLLY,RIGHT:nJ.PAN},this.touches={ONE:iJ.ROTATE,TWO:iJ.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new j,this._lastQuaternion=new c6,this._lastTargetPosition=new j,this._quat=new c6().setFromUnitVectors($.up,new j(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new fW,this._sphericalDelta=new fW,this._scale=1,this._panOffset=new j,this._rotateStart=new g$,this._rotateEnd=new g$,this._rotateDelta=new g$,this._panStart=new g$,this._panEnd=new g$,this._panDelta=new g$,this._dollyStart=new g$,this._dollyEnd=new g$,this._dollyDelta=new g$,this._dollyDirection=new j,this._mouse=new g$,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=HM.bind(this),this._onPointerDown=XM.bind(this),this._onPointerUp=NM.bind(this),this._onContextMenu=ZM.bind(this),this._onMouseWheel=OM.bind(this),this._onKeyDown=EM.bind(this),this._onTouchStart=kM.bind(this),this._onTouchMove=qM.bind(this),this._onMouseDown=YM.bind(this),this._onMouseMove=GM.bind(this),this._interceptControlDown=IM.bind(this),this._interceptControlUp=DM.bind(this),this.domElement!==null)this.connect(this.domElement);this.update()}set cursorStyle($){if(this._cursorStyle=$,$==="grab")this.domElement.style.cursor="grab";else this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect($){super.connect($),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents($){$.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=$}stopListenToKeyEvents(){if(this._domElementKeyEvents!==null)this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(ZI),this.update(),this.state=Z6.NONE}pan($,U){this._pan($,U),this.update()}dollyIn($){this._dollyIn($),this.update()}dollyOut($){this._dollyOut($),this.update()}rotateLeft($){this._rotateLeft($),this.update()}rotateUp($){this._rotateUp($),this.update()}update($=null){let U=this.object.position;if(l6.copy(U).sub(this.target),l6.applyQuaternion(this._quat),this._spherical.setFromVector3(l6),this.autoRotate&&this.state===Z6.NONE)this._rotateLeft(this._getAutoRotationAngle($));if(this.enableDamping)this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor;else this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi;let J=this.minAzimuthAngle,Q=this.maxAzimuthAngle;if(isFinite(J)&&isFinite(Q)){if(J<-Math.PI)J+=kU;else if(J>Math.PI)J-=kU;if(Q<-Math.PI)Q+=kU;else if(Q>Math.PI)Q-=kU;if(J<=Q)this._spherical.theta=Math.max(J,Math.min(Q,this._spherical.theta));else this._spherical.theta=this._spherical.theta>(J+Q)/2?Math.max(J,this._spherical.theta):Math.min(Q,this._spherical.theta)}if(this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0)this.target.addScaledVector(this._panOffset,this.dampingFactor);else this.target.add(this._panOffset);this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let W=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let K=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),W=K!=this._spherical.radius}if(l6.setFromSpherical(this._spherical),l6.applyQuaternion(this._quatInverse),U.copy(this.target).add(l6),this.object.lookAt(this.target),this.enableDamping===!0)this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor);else this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0);if(this.zoomToCursor&&this._performCursorZoom){let K=null;if(this.object.isPerspectiveCamera){let X=l6.length();K=this._clampDistance(X*this._scale);let H=X-K;this.object.position.addScaledVector(this._dollyDirection,H),this.object.updateMatrixWorld(),W=!!H}else if(this.object.isOrthographicCamera){let X=new j(this._mouse.x,this._mouse.y,0);X.unproject(this.object);let H=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),W=H!==this.object.zoom;let N=new j(this._mouse.x,this._mouse.y,0);N.unproject(this.object),this.object.position.sub(N).add(X),this.object.updateMatrixWorld(),K=l6.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;if(K!==null)if(this.screenSpacePanning)this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(K).add(this.object.position);else if(n9.origin.copy(this.object.position),n9.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(n9.direction))<KM)this.object.lookAt(this.target);else II.setFromNormalAndCoplanarPoint(this.object.up,this.target),n9.intersectPlane(II,this.target)}else if(this.object.isOrthographicCamera){let K=this.object.zoom;if(this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),K!==this.object.zoom)this.object.updateProjectionMatrix(),W=!0}if(this._scale=1,this._performCursorZoom=!1,W||this._lastPosition.distanceToSquared(this.object.position)>dH||8*(1-this._lastQuaternion.dot(this.object.quaternion))>dH||this._lastTargetPosition.distanceToSquared(this.target)>dH)return this.dispatchEvent(ZI),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0;return!1}_getAutoRotationAngle($){if($!==null)return kU/60*this.autoRotateSpeed*$;else return kU/60/60*this.autoRotateSpeed}_getZoomScale($){let U=Math.abs($*0.01);return Math.pow(0.95,this.zoomSpeed*U)}_rotateLeft($){this._sphericalDelta.theta-=$}_rotateUp($){this._sphericalDelta.phi-=$}_panLeft($,U){l6.setFromMatrixColumn(U,0),l6.multiplyScalar(-$),this._panOffset.add(l6)}_panUp($,U){if(this.screenSpacePanning===!0)l6.setFromMatrixColumn(U,1);else l6.setFromMatrixColumn(U,0),l6.crossVectors(this.object.up,l6);l6.multiplyScalar($),this._panOffset.add(l6)}_pan($,U){let J=this.domElement;if(this.object.isPerspectiveCamera){let Q=this.object.position;l6.copy(Q).sub(this.target);let W=l6.length();W*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*$*W/J.clientHeight,this.object.matrix),this._panUp(2*U*W/J.clientHeight,this.object.matrix)}else if(this.object.isOrthographicCamera)this._panLeft($*(this.object.right-this.object.left)/this.object.zoom/J.clientWidth,this.object.matrix),this._panUp(U*(this.object.top-this.object.bottom)/this.object.zoom/J.clientHeight,this.object.matrix);else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1}_dollyOut($){if(this.object.isPerspectiveCamera||this.object.isOrthographicCamera)this._scale/=$;else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1}_dollyIn($){if(this.object.isPerspectiveCamera||this.object.isOrthographicCamera)this._scale*=$;else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1}_updateZoomParameters($,U){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let J=this.domElement.getBoundingClientRect(),Q=$-J.left,W=U-J.top,K=J.width,X=J.height;this._mouse.x=Q/K*2-1,this._mouse.y=-(W/X)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance($){return Math.max(this.minDistance,Math.min(this.maxDistance,$))}_handleMouseDownRotate($){this._rotateStart.set($.clientX,$.clientY)}_handleMouseDownDolly($){this._updateZoomParameters($.clientX,$.clientX),this._dollyStart.set($.clientX,$.clientY)}_handleMouseDownPan($){this._panStart.set($.clientX,$.clientY)}_handleMouseMoveRotate($){this._rotateEnd.set($.clientX,$.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let U=this.domElement;this._rotateLeft(kU*this._rotateDelta.x/U.clientHeight),this._rotateUp(kU*this._rotateDelta.y/U.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly($){if(this._dollyEnd.set($.clientX,$.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0)this._dollyOut(this._getZoomScale(this._dollyDelta.y));else if(this._dollyDelta.y<0)this._dollyIn(this._getZoomScale(this._dollyDelta.y));this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan($){this._panEnd.set($.clientX,$.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel($){if(this._updateZoomParameters($.clientX,$.clientY),$.deltaY<0)this._dollyIn(this._getZoomScale($.deltaY));else if($.deltaY>0)this._dollyOut(this._getZoomScale($.deltaY));this.update()}_handleKeyDown($){let U=!1;switch($.code){case this.keys.UP:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate)this._rotateUp(kU*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(0,this.keyPanSpeed);U=!0;break;case this.keys.BOTTOM:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate)this._rotateUp(-kU*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(0,-this.keyPanSpeed);U=!0;break;case this.keys.LEFT:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate)this._rotateLeft(kU*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(this.keyPanSpeed,0);U=!0;break;case this.keys.RIGHT:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate)this._rotateLeft(-kU*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(-this.keyPanSpeed,0);U=!0;break}if(U)$.preventDefault(),this.update()}_handleTouchStartRotate($){if(this._pointers.length===1)this._rotateStart.set($.pageX,$.pageY);else{let U=this._getSecondPointerPosition($),J=0.5*($.pageX+U.x),Q=0.5*($.pageY+U.y);this._rotateStart.set(J,Q)}}_handleTouchStartPan($){if(this._pointers.length===1)this._panStart.set($.pageX,$.pageY);else{let U=this._getSecondPointerPosition($),J=0.5*($.pageX+U.x),Q=0.5*($.pageY+U.y);this._panStart.set(J,Q)}}_handleTouchStartDolly($){let U=this._getSecondPointerPosition($),J=$.pageX-U.x,Q=$.pageY-U.y,W=Math.sqrt(J*J+Q*Q);this._dollyStart.set(0,W)}_handleTouchStartDollyPan($){if(this.enableZoom)this._handleTouchStartDolly($);if(this.enablePan)this._handleTouchStartPan($)}_handleTouchStartDollyRotate($){if(this.enableZoom)this._handleTouchStartDolly($);if(this.enableRotate)this._handleTouchStartRotate($)}_handleTouchMoveRotate($){if(this._pointers.length==1)this._rotateEnd.set($.pageX,$.pageY);else{let J=this._getSecondPointerPosition($),Q=0.5*($.pageX+J.x),W=0.5*($.pageY+J.y);this._rotateEnd.set(Q,W)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let U=this.domElement;this._rotateLeft(kU*this._rotateDelta.x/U.clientHeight),this._rotateUp(kU*this._rotateDelta.y/U.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan($){if(this._pointers.length===1)this._panEnd.set($.pageX,$.pageY);else{let U=this._getSecondPointerPosition($),J=0.5*($.pageX+U.x),Q=0.5*($.pageY+U.y);this._panEnd.set(J,Q)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly($){let U=this._getSecondPointerPosition($),J=$.pageX-U.x,Q=$.pageY-U.y,W=Math.sqrt(J*J+Q*Q);this._dollyEnd.set(0,W),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let K=($.pageX+U.x)*0.5,X=($.pageY+U.y)*0.5;this._updateZoomParameters(K,X)}_handleTouchMoveDollyPan($){if(this.enableZoom)this._handleTouchMoveDolly($);if(this.enablePan)this._handleTouchMovePan($)}_handleTouchMoveDollyRotate($){if(this.enableZoom)this._handleTouchMoveDolly($);if(this.enableRotate)this._handleTouchMoveRotate($)}_addPointer($){this._pointers.push($.pointerId)}_removePointer($){delete this._pointerPositions[$.pointerId];for(let U=0;U<this._pointers.length;U++)if(this._pointers[U]==$.pointerId){this._pointers.splice(U,1);return}}_isTrackingPointer($){for(let U=0;U<this._pointers.length;U++)if(this._pointers[U]==$.pointerId)return!0;return!1}_trackPointer($){let U=this._pointerPositions[$.pointerId];if(U===void 0)U=new g$,this._pointerPositions[$.pointerId]=U;U.set($.pageX,$.pageY)}_getSecondPointerPosition($){let U=$.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[U]}_customWheelEvent($){let U=$.deltaMode,J={clientX:$.clientX,clientY:$.clientY,deltaY:$.deltaY};switch(U){case 1:J.deltaY*=16;break;case 2:J.deltaY*=100;break}if($.ctrlKey&&!this._controlActive)J.deltaY*=10;return J}}function XM($){if(this.enabled===!1)return;if(this._pointers.length===0)this.domElement.setPointerCapture($.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp);if(this._isTrackingPointer($))return;if(this._addPointer($),$.pointerType==="touch")this._onTouchStart($);else this._onMouseDown($);if(this._cursorStyle==="grab")this.domElement.style.cursor="grabbing"}function HM($){if(this.enabled===!1)return;if($.pointerType==="touch")this._onTouchMove($);else this._onMouseMove($)}function NM($){switch(this._removePointer($),this._pointers.length){case 0:if(this.domElement.releasePointerCapture($.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(DI),this.state=Z6.NONE,this._cursorStyle==="grab")this.domElement.style.cursor="grab";break;case 1:let U=this._pointers[0],J=this._pointerPositions[U];this._onTouchStart({pointerId:U,pageX:J.x,pageY:J.y});break}}function YM($){let U;switch($.button){case 0:U=this.mouseButtons.LEFT;break;case 1:U=this.mouseButtons.MIDDLE;break;case 2:U=this.mouseButtons.RIGHT;break;default:U=-1}switch(U){case nJ.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly($),this.state=Z6.DOLLY;break;case nJ.ROTATE:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan($),this.state=Z6.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate($),this.state=Z6.ROTATE}break;case nJ.PAN:if($.ctrlKey||$.metaKey||$.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate($),this.state=Z6.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan($),this.state=Z6.PAN}break;default:this.state=Z6.NONE}if(this.state!==Z6.NONE)this.dispatchEvent(cH)}function GM($){switch(this.state){case Z6.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate($);break;case Z6.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly($);break;case Z6.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan($);break}}function OM($){if(this.enabled===!1||this.enableZoom===!1||this.state!==Z6.NONE)return;$.preventDefault(),this.dispatchEvent(cH),this._handleMouseWheel(this._customWheelEvent($)),this.dispatchEvent(DI)}function EM($){if(this.enabled===!1)return;this._handleKeyDown($)}function kM($){switch(this._trackPointer($),this._pointers.length){case 1:switch(this.touches.ONE){case iJ.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate($),this.state=Z6.TOUCH_ROTATE;break;case iJ.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan($),this.state=Z6.TOUCH_PAN;break;default:this.state=Z6.NONE}break;case 2:switch(this.touches.TWO){case iJ.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan($),this.state=Z6.TOUCH_DOLLY_PAN;break;case iJ.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate($),this.state=Z6.TOUCH_DOLLY_ROTATE;break;default:this.state=Z6.NONE}break;default:this.state=Z6.NONE}if(this.state!==Z6.NONE)this.dispatchEvent(cH)}function qM($){switch(this._trackPointer($),this.state){case Z6.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate($),this.update();break;case Z6.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan($),this.update();break;case Z6.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan($),this.update();break;case Z6.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate($),this.update();break;default:this.state=Z6.NONE}}function ZM($){if(this.enabled===!1)return;$.preventDefault()}function IM($){if($.key==="Control")this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}function DM($){if($.key==="Control")this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}class iH extends V8{constructor(){super();this.name="RoomEnvironment",this.position.y=-3.5;let $=new $0;$.deleteAttribute("uv");let U=new SJ({side:$U}),J=new SJ,Q=new z8(16777215,900,28,2);Q.position.set(0.418,16.199,0.3),this.add(Q);let W=new B6($,U);W.position.set(-0.757,13.219,0.717),W.scale.set(31.713,28.305,28.591),this.add(W);let K=new M8($,J,6),X=new q6;X.position.set(-10.906,2.009,1.846),X.rotation.set(0,-0.195,0),X.scale.set(2.328,7.905,4.651),X.updateMatrix(),K.setMatrixAt(0,X.matrix),X.position.set(-5.607,-0.754,-0.758),X.rotation.set(0,0.994,0),X.scale.set(1.97,1.534,3.955),X.updateMatrix(),K.setMatrixAt(1,X.matrix),X.position.set(6.167,0.857,7.803),X.rotation.set(0,0.561,0),X.scale.set(3.927,6.285,3.687),X.updateMatrix(),K.setMatrixAt(2,X.matrix),X.position.set(-2.017,0.018,6.124),X.rotation.set(0,0.333,0),X.scale.set(2.002,4.566,2.064),X.updateMatrix(),K.setMatrixAt(3,X.matrix),X.position.set(2.291,-0.756,-2.621),X.rotation.set(0,-0.286,0),X.scale.set(1.546,1.552,1.496),X.updateMatrix(),K.setMatrixAt(4,X.matrix),X.position.set(-2.193,-0.369,-5.547),X.rotation.set(0,0.516,0),X.scale.set(3.875,3.487,2.986),X.updateMatrix(),K.setMatrixAt(5,X.matrix),this.add(K);let H=new B6($,T8(50));H.position.set(-16.116,14.37,8.208),H.scale.set(0.1,2.428,2.739),this.add(H);let N=new B6($,T8(50));N.position.set(-16.109,18.021,-8.207),N.scale.set(0.1,2.425,2.751),this.add(N);let Y=new B6($,T8(17));Y.position.set(14.904,12.198,-1.832),Y.scale.set(0.15,4.265,6.331),this.add(Y);let G=new B6($,T8(43));G.position.set(-0.462,8.89,14.52),G.scale.set(4.38,5.441,0.088),this.add(G);let O=new B6($,T8(20));O.position.set(3.235,11.486,-12.541),O.scale.set(2.5,2,0.1),this.add(O);let E=new B6($,T8(100));E.position.set(0,20,0),E.scale.set(1,0.1,1),this.add(E)}dispose(){let $=new Set;this.traverse((U)=>{if(U.isMesh)$.add(U.geometry),$.add(U.material)});for(let U of $)U.dispose()}}function T8($){return new T9({color:0,emissive:16777215,emissiveIntensity:$})}var J6={};RJ(J6,{xor:()=>rD,xid:()=>FD,void:()=>pD,uuidv7:()=>GD,uuidv6:()=>YD,uuidv4:()=>ND,uuid:()=>HD,util:()=>Q$,url:()=>OD,uppercase:()=>p8,unknown:()=>c0,union:()=>R7,undefined:()=>lD,ulid:()=>DD,uint64:()=>fD,uint32:()=>yD,tuple:()=>ZE,trim:()=>r8,treeifyError:()=>XN,transform:()=>w7,toUpperCase:()=>s8,toLowerCase:()=>a8,toJSONSchema:()=>iK,templateLiteral:()=>Y5,symbol:()=>uD,superRefine:()=>pE,success:()=>K5,stringbool:()=>D5,stringFormat:()=>CD,string:()=>ZQ,strictObject:()=>iD,startsWith:()=>c8,slugify:()=>t8,size:()=>m0,setErrorMap:()=>sP,set:()=>$5,safeParseAsync:()=>pO,safeParse:()=>mO,safeEncodeAsync:()=>aO,safeEncode:()=>oO,safeDecodeAsync:()=>sO,safeDecode:()=>rO,registry:()=>FK,regexes:()=>BU,regex:()=>l8,refine:()=>mE,record:()=>IE,readonly:()=>yE,property:()=>pK,promise:()=>G5,prettifyError:()=>HN,preprocess:()=>L5,prefault:()=>AE,positive:()=>fK,pipe:()=>$7,partialRecord:()=>sD,parseAsync:()=>lO,parse:()=>uO,overwrite:()=>oU,optional:()=>DQ,object:()=>nD,number:()=>eO,nullish:()=>Q5,nullable:()=>FQ,null:()=>QE,normalize:()=>o8,nonpositive:()=>lK,nonoptional:()=>CE,nonnegative:()=>mK,never:()=>L7,negative:()=>uK,nativeEnum:()=>U5,nanoid:()=>qD,nan:()=>X5,multipleOf:()=>E0,minSize:()=>EJ,minLength:()=>gJ,mime:()=>i8,meta:()=>Z5,maxSize:()=>k0,maxLength:()=>p0,map:()=>eD,mac:()=>VD,lte:()=>PU,lt:()=>GJ,lowercase:()=>m8,looseRecord:()=>tD,looseObject:()=>oD,locales:()=>OQ,literal:()=>J5,length:()=>d0,lazy:()=>fE,ksuid:()=>LD,keyof:()=>cD,jwt:()=>AD,json:()=>F5,iso:()=>UW,ipv6:()=>wD,ipv4:()=>RD,invertCodec:()=>N5,intersection:()=>kE,int64:()=>hD,int32:()=>bD,int:()=>eK,instanceof:()=>I5,includes:()=>d8,httpUrl:()=>ED,hostname:()=>SD,hex:()=>TD,hash:()=>vD,guid:()=>XD,gte:()=>NU,gt:()=>OJ,globalRegistry:()=>r6,getErrorMap:()=>tP,function:()=>O5,fromJSONSchema:()=>V5,formatError:()=>$Q,float64:()=>gD,float32:()=>jD,flattenError:()=>eW,file:()=>W5,exactOptional:()=>ME,enum:()=>V7,endsWith:()=>n8,encodeAsync:()=>nO,encode:()=>dO,emoji:()=>kD,email:()=>KD,e164:()=>_D,discriminatedUnion:()=>aD,describe:()=>q5,decodeAsync:()=>iO,decode:()=>cO,date:()=>dD,custom:()=>k5,cuid2:()=>ID,cuid:()=>ZD,core:()=>bJ,config:()=>S6,coerce:()=>cE,codec:()=>H5,clone:()=>XU,cidrv6:()=>BD,cidrv4:()=>MD,check:()=>E5,catch:()=>vE,boolean:()=>$E,bigint:()=>xD,base64url:()=>zD,base64:()=>PD,array:()=>wQ,any:()=>mD,_function:()=>O5,_default:()=>zE,_ZodString:()=>U7,ZodXor:()=>GE,ZodXID:()=>N7,ZodVoid:()=>NE,ZodUnknown:()=>XE,ZodUnion:()=>BQ,ZodUndefined:()=>JE,ZodUUID:()=>kJ,ZodURL:()=>RQ,ZodULID:()=>H7,ZodType:()=>c$,ZodTuple:()=>qE,ZodTransform:()=>VE,ZodTemplateLiteral:()=>xE,ZodSymbol:()=>UE,ZodSuccess:()=>SE,ZodStringFormat:()=>D6,ZodString:()=>QW,ZodSet:()=>FE,ZodRecord:()=>JW,ZodRealError:()=>IU,ZodReadonly:()=>bE,ZodPromise:()=>uE,ZodPreprocess:()=>gE,ZodPrefault:()=>_E,ZodPipe:()=>PQ,ZodOptional:()=>M7,ZodObject:()=>MQ,ZodNumberFormat:()=>n0,ZodNumber:()=>XW,ZodNullable:()=>BE,ZodNull:()=>WE,ZodNonOptional:()=>B7,ZodNever:()=>HE,ZodNanoID:()=>Q7,ZodNaN:()=>jE,ZodMap:()=>DE,ZodMAC:()=>tO,ZodLiteral:()=>LE,ZodLazy:()=>hE,ZodKSUID:()=>Y7,ZodJWT:()=>D7,ZodIssueCode:()=>aP,ZodIntersection:()=>EE,ZodISOTime:()=>sK,ZodISODuration:()=>tK,ZodISODateTime:()=>rK,ZodISODate:()=>aK,ZodIPv6:()=>O7,ZodIPv4:()=>G7,ZodGUID:()=>IQ,ZodFunction:()=>lE,ZodFirstPartyTypeKind:()=>dE,ZodFile:()=>RE,ZodExactOptional:()=>wE,ZodError:()=>oP,ZodEnum:()=>WW,ZodEmoji:()=>W7,ZodEmail:()=>J7,ZodE164:()=>I7,ZodDiscriminatedUnion:()=>OE,ZodDefault:()=>PE,ZodDate:()=>VQ,ZodCustomStringFormat:()=>KW,ZodCustom:()=>_Q,ZodCodec:()=>zQ,ZodCatch:()=>TE,ZodCUID2:()=>X7,ZodCUID:()=>K7,ZodCIDRv6:()=>k7,ZodCIDRv4:()=>E7,ZodBoolean:()=>HW,ZodBigIntFormat:()=>F7,ZodBigInt:()=>NW,ZodBase64URL:()=>Z7,ZodBase64:()=>q7,ZodArray:()=>YE,ZodAny:()=>KE,TimePrecision:()=>ZG,NEVER:()=>oH,$output:()=>YG,$input:()=>GG,$brand:()=>rH});var bJ={};RJ(bJ,{version:()=>WY,util:()=>Q$,treeifyError:()=>XN,toJSONSchema:()=>iK,toDotPath:()=>BI,safeParseAsync:()=>YN,safeParse:()=>NN,safeEncodeAsync:()=>aM,safeEncode:()=>oM,safeDecodeAsync:()=>sM,safeDecode:()=>rM,registry:()=>FK,regexes:()=>BU,process:()=>G6,prettifyError:()=>HN,parseAsync:()=>a9,parse:()=>r9,meta:()=>rG,locales:()=>OQ,isValidJWT:()=>nI,isValidBase64URL:()=>cI,isValidBase64:()=>PY,initializeContext:()=>q0,globalRegistry:()=>r6,globalConfig:()=>x0,formatError:()=>$Q,flattenError:()=>eW,finalize:()=>I0,extractDefs:()=>Z0,encodeAsync:()=>nM,encode:()=>dM,describe:()=>oG,decodeAsync:()=>iM,decode:()=>cM,createToJSONSchemaMethod:()=>sG,createStandardJSONSchemaMethod:()=>$W,config:()=>S6,clone:()=>XU,_xor:()=>BP,_xid:()=>CK,_void:()=>fG,_uuidv7:()=>MK,_uuidv6:()=>wK,_uuidv4:()=>VK,_uuid:()=>RK,_url:()=>kQ,_uppercase:()=>p8,_unknown:()=>xG,_union:()=>MP,_undefined:()=>gG,_ulid:()=>AK,_uint64:()=>vG,_uint32:()=>zG,_tuple:()=>_P,_trim:()=>r8,_transform:()=>gP,_toUpperCase:()=>s8,_toLowerCase:()=>a8,_templateLiteral:()=>pP,_symbol:()=>jG,_superRefine:()=>iG,_success:()=>fP,_stringbool:()=>aG,_stringFormat:()=>e8,_string:()=>EG,_startsWith:()=>c8,_slugify:()=>t8,_size:()=>m0,_set:()=>SP,_safeParseAsync:()=>h8,_safeParse:()=>x8,_safeEncodeAsync:()=>WK,_safeEncode:()=>UK,_safeDecodeAsync:()=>QK,_safeDecode:()=>JK,_regex:()=>l8,_refine:()=>nG,_record:()=>AP,_readonly:()=>mP,_property:()=>pK,_promise:()=>cP,_positive:()=>fK,_pipe:()=>lP,_parseAsync:()=>y8,_parse:()=>b8,_overwrite:()=>oU,_optional:()=>bP,_number:()=>RG,_nullable:()=>yP,_null:()=>bG,_normalize:()=>o8,_nonpositive:()=>lK,_nonoptional:()=>hP,_nonnegative:()=>mK,_never:()=>hG,_negative:()=>uK,_nativeEnum:()=>vP,_nanoid:()=>PK,_nan:()=>mG,_multipleOf:()=>E0,_minSize:()=>EJ,_minLength:()=>gJ,_min:()=>NU,_mime:()=>i8,_maxSize:()=>k0,_maxLength:()=>p0,_max:()=>PU,_map:()=>CP,_mac:()=>qG,_lte:()=>PU,_lt:()=>GJ,_lowercase:()=>m8,_literal:()=>jP,_length:()=>d0,_lazy:()=>dP,_ksuid:()=>SK,_jwt:()=>hK,_isoTime:()=>FG,_isoDuration:()=>LG,_isoDateTime:()=>IG,_isoDate:()=>DG,_ipv6:()=>vK,_ipv4:()=>TK,_intersection:()=>zP,_int64:()=>TG,_int32:()=>PG,_int:()=>wG,_includes:()=>d8,_guid:()=>EQ,_gte:()=>NU,_gt:()=>OJ,_float64:()=>BG,_float32:()=>MG,_file:()=>dG,_enum:()=>TP,_endsWith:()=>n8,_encodeAsync:()=>e9,_encode:()=>s9,_emoji:()=>BK,_email:()=>LK,_e164:()=>xK,_discriminatedUnion:()=>PP,_default:()=>xP,_decodeAsync:()=>$K,_decode:()=>t9,_date:()=>uG,_custom:()=>cG,_cuid2:()=>_K,_cuid:()=>zK,_coercedString:()=>kG,_coercedNumber:()=>VG,_coercedDate:()=>lG,_coercedBoolean:()=>AG,_coercedBigint:()=>SG,_cidrv6:()=>gK,_cidrv4:()=>jK,_check:()=>UD,_catch:()=>uP,_boolean:()=>_G,_bigint:()=>CG,_base64url:()=>yK,_base64:()=>bK,_array:()=>pG,_any:()=>yG,TimePrecision:()=>ZG,NEVER:()=>oH,JSONSchemaGenerator:()=>bO,JSONSchema:()=>JD,Doc:()=>NK,$output:()=>YG,$input:()=>GG,$constructor:()=>g,$brand:()=>rH,$ZodXor:()=>pY,$ZodXID:()=>qY,$ZodVoid:()=>fY,$ZodUnknown:()=>xY,$ZodUnion:()=>KQ,$ZodUndefined:()=>gY,$ZodUUID:()=>XY,$ZodURL:()=>NY,$ZodULID:()=>kY,$ZodType:()=>h$,$ZodTuple:()=>ZK,$ZodTransform:()=>tY,$ZodTemplateLiteral:()=>Y1,$ZodSymbol:()=>jY,$ZodSuccess:()=>Q1,$ZodStringFormat:()=>I6,$ZodString:()=>l0,$ZodSet:()=>oY,$ZodRegistry:()=>OG,$ZodRecord:()=>nY,$ZodRealError:()=>ZU,$ZodReadonly:()=>N1,$ZodPromise:()=>O1,$ZodPreprocess:()=>H1,$ZodPrefault:()=>J1,$ZodPipe:()=>DK,$ZodOptional:()=>IK,$ZodObjectJIT:()=>mY,$ZodObject:()=>rI,$ZodNumberFormat:()=>TY,$ZodNumber:()=>kK,$ZodNullable:()=>$1,$ZodNull:()=>bY,$ZodNonOptional:()=>W1,$ZodNever:()=>hY,$ZodNanoID:()=>GY,$ZodNaN:()=>X1,$ZodMap:()=>iY,$ZodMAC:()=>wY,$ZodLiteral:()=>aY,$ZodLazy:()=>E1,$ZodKSUID:()=>ZY,$ZodJWT:()=>CY,$ZodIntersection:()=>cY,$ZodISOTime:()=>FY,$ZodISODuration:()=>LY,$ZodISODateTime:()=>IY,$ZodISODate:()=>DY,$ZodIPv6:()=>VY,$ZodIPv4:()=>RY,$ZodGUID:()=>KY,$ZodFunction:()=>G1,$ZodFile:()=>sY,$ZodExactOptional:()=>eY,$ZodError:()=>tW,$ZodEnum:()=>rY,$ZodEncodeError:()=>h0,$ZodEmoji:()=>YY,$ZodEmail:()=>HY,$ZodE164:()=>AY,$ZodDiscriminatedUnion:()=>dY,$ZodDefault:()=>U1,$ZodDate:()=>uY,$ZodCustomStringFormat:()=>SY,$ZodCustom:()=>k1,$ZodCodec:()=>XQ,$ZodCheckUpperCase:()=>aN,$ZodCheckStringFormat:()=>f8,$ZodCheckStartsWith:()=>tN,$ZodCheckSizeEquals:()=>dN,$ZodCheckRegex:()=>oN,$ZodCheckProperty:()=>$Y,$ZodCheckOverwrite:()=>JY,$ZodCheckNumberFormat:()=>uN,$ZodCheckMultipleOf:()=>fN,$ZodCheckMinSize:()=>pN,$ZodCheckMinLength:()=>nN,$ZodCheckMimeType:()=>UY,$ZodCheckMaxSize:()=>mN,$ZodCheckMaxLength:()=>cN,$ZodCheckLowerCase:()=>rN,$ZodCheckLessThan:()=>XK,$ZodCheckLengthEquals:()=>iN,$ZodCheckIncludes:()=>sN,$ZodCheckGreaterThan:()=>HK,$ZodCheckEndsWith:()=>eN,$ZodCheckBigIntFormat:()=>lN,$ZodCheck:()=>V6,$ZodCatch:()=>K1,$ZodCUID2:()=>EY,$ZodCUID:()=>OY,$ZodCIDRv6:()=>BY,$ZodCIDRv4:()=>MY,$ZodBoolean:()=>QQ,$ZodBigIntFormat:()=>vY,$ZodBigInt:()=>qK,$ZodBase64URL:()=>_Y,$ZodBase64:()=>zY,$ZodAsyncError:()=>YJ,$ZodArray:()=>lY,$ZodAny:()=>yY});var FI,oH=Object.freeze({status:"aborted"});function g($,U,J){function Q(H,N){if(!H._zod)Object.defineProperty(H,"_zod",{value:{def:N,constr:X,traits:new Set},enumerable:!1});if(H._zod.traits.has($))return;H._zod.traits.add($),U(H,N);let Y=X.prototype,G=Object.keys(Y);for(let O=0;O<G.length;O++){let E=G[O];if(!(E in H))H[E]=Y[E].bind(H)}}let W=J?.Parent??Object;class K extends W{}Object.defineProperty(K,"name",{value:$});function X(H){var N;let Y=J?.Parent?new K:this;Q(Y,H),(N=Y._zod).deferred??(N.deferred=[]);for(let G of Y._zod.deferred)G();return Y}return Object.defineProperty(X,"init",{value:Q}),Object.defineProperty(X,Symbol.hasInstance,{value:(H)=>{if(J?.Parent&&H instanceof J.Parent)return!0;return H?._zod?.traits?.has($)}}),Object.defineProperty(X,"name",{value:$}),X}var rH=Symbol("zod_brand");class YJ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class h0 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}(FI=globalThis).__zod_globalConfig??(FI.__zod_globalConfig={});var x0=globalThis.__zod_globalConfig;function S6($){if($)Object.assign(x0,$);return x0}var Q$={};RJ(Q$,{unwrapMessage:()=>nW,uint8ArrayToHex:()=>mM,uint8ArrayToBase64url:()=>uM,uint8ArrayToBase64:()=>VI,stringifyPrimitive:()=>U$,slugify:()=>tH,shallowClone:()=>$N,safeExtend:()=>gM,required:()=>xM,randomString:()=>_M,propertyKeyTypes:()=>rW,promiseAllObject:()=>zM,primitiveTypes:()=>UN,prefixIssues:()=>qU,pick:()=>TM,partial:()=>yM,parsedType:()=>W$,optionalKeys:()=>JN,omit:()=>vM,objectClone:()=>MM,numKeys:()=>AM,nullish:()=>N0,normalizeParams:()=>K$,mergeDefs:()=>jJ,merge:()=>bM,jsonStringifyReplacer:()=>v8,joinValues:()=>m,issue:()=>g8,isPlainObject:()=>G0,isObject:()=>f0,hexToUint8Array:()=>lM,getSizableOrigin:()=>aW,getParsedType:()=>CM,getLengthableOrigin:()=>sW,getEnumValues:()=>iW,getElementAtPath:()=>PM,floatSafeRemainder:()=>sH,finalizeIssue:()=>HU,extend:()=>jM,explicitlyAborted:()=>KN,escapeRegex:()=>yU,esc:()=>i9,defineLazy:()=>s$,createTransparentProxy:()=>SM,cloneDef:()=>BM,clone:()=>XU,cleanRegex:()=>oW,cleanEnum:()=>hM,captureStackTrace:()=>o9,cached:()=>j8,base64urlToUint8Array:()=>fM,base64ToUint8Array:()=>RI,assignProp:()=>Y0,assertNotEqual:()=>LM,assertNever:()=>VM,assertIs:()=>RM,assertEqual:()=>FM,assert:()=>wM,allowsEval:()=>eH,aborted:()=>O0,NUMBER_FORMAT_RANGES:()=>WN,Class:()=>wI,BIGINT_FORMAT_RANGES:()=>QN});function FM($){return $}function LM($){return $}function RM($){}function VM($){throw Error("Unexpected value in exhaustive check")}function wM($){}function iW($){let U=Object.values($).filter((Q)=>typeof Q==="number");return Object.entries($).filter(([Q,W])=>U.indexOf(+Q)===-1).map(([Q,W])=>W)}function m($,U="|"){return $.map((J)=>U$(J)).join(U)}function v8($,U){if(typeof U==="bigint")return U.toString();return U}function j8($){return{get value(){{let J=$();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function N0($){return $===null||$===void 0}function oW($){let U=$.startsWith("^")?1:0,J=$.endsWith("$")?$.length-1:$.length;return $.slice(U,J)}function sH($,U){let J=$/U,Q=Math.round(J),W=Number.EPSILON*Math.max(Math.abs(J),1);if(Math.abs(J-Q)<W)return 0;return J-Q}var LI=Symbol("evaluating");function s$($,U,J){let Q=void 0;Object.defineProperty($,U,{get(){if(Q===LI)return;if(Q===void 0)Q=LI,Q=J();return Q},set(W){Object.defineProperty($,U,{value:W})},configurable:!0})}function MM($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function Y0($,U,J){Object.defineProperty($,U,{value:J,writable:!0,enumerable:!0,configurable:!0})}function jJ(...$){let U={};for(let J of $){let Q=Object.getOwnPropertyDescriptors(J);Object.assign(U,Q)}return Object.defineProperties({},U)}function BM($){return jJ($._zod.def)}function PM($,U){if(!U)return $;return U.reduce((J,Q)=>J?.[Q],$)}function zM($){let U=Object.keys($),J=U.map((Q)=>$[Q]);return Promise.all(J).then((Q)=>{let W={};for(let K=0;K<U.length;K++)W[U[K]]=Q[K];return W})}function _M($=10){let J="";for(let Q=0;Q<$;Q++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function i9($){return JSON.stringify($)}function tH($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var o9="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function f0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var eH=j8(()=>{if(x0.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function G0($){if(f0($)===!1)return!1;let U=$.constructor;if(U===void 0)return!0;if(typeof U!=="function")return!0;let J=U.prototype;if(f0(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function $N($){if(G0($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function AM($){let U=0;for(let J in $)if(Object.prototype.hasOwnProperty.call($,J))U++;return U}var CM=($)=>{let U=typeof $;switch(U){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${U}`)}},rW=new Set(["string","number","symbol"]),UN=new Set(["string","number","bigint","boolean","symbol","undefined"]);function yU($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XU($,U,J){let Q=new $._zod.constr(U??$._zod.def);if(!U||J?.parent)Q._zod.parent=$;return Q}function K$($){let U=$;if(!U)return{};if(typeof U==="string")return{error:()=>U};if(U?.message!==void 0){if(U?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");U.error=U.message}if(delete U.message,typeof U.error==="string")return{...U,error:()=>U.error};return U}function SM($){let U;return new Proxy({},{get(J,Q,W){return U??(U=$()),Reflect.get(U,Q,W)},set(J,Q,W,K){return U??(U=$()),Reflect.set(U,Q,W,K)},has(J,Q){return U??(U=$()),Reflect.has(U,Q)},deleteProperty(J,Q){return U??(U=$()),Reflect.deleteProperty(U,Q)},ownKeys(J){return U??(U=$()),Reflect.ownKeys(U)},getOwnPropertyDescriptor(J,Q){return U??(U=$()),Reflect.getOwnPropertyDescriptor(U,Q)},defineProperty(J,Q,W){return U??(U=$()),Reflect.defineProperty(U,Q,W)}})}function U$($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function JN($){return Object.keys($).filter((U)=>{return $[U]._zod.optin==="optional"&&$[U]._zod.optout==="optional"})}var WN={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},QN={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function TM($,U){let J=$._zod.def,Q=J.checks;if(Q&&Q.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let K=jJ($._zod.def,{get shape(){let X={};for(let H in U){if(!(H in J.shape))throw Error(`Unrecognized key: "${H}"`);if(!U[H])continue;X[H]=J.shape[H]}return Y0(this,"shape",X),X},checks:[]});return XU($,K)}function vM($,U){let J=$._zod.def,Q=J.checks;if(Q&&Q.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let K=jJ($._zod.def,{get shape(){let X={...$._zod.def.shape};for(let H in U){if(!(H in J.shape))throw Error(`Unrecognized key: "${H}"`);if(!U[H])continue;delete X[H]}return Y0(this,"shape",X),X},checks:[]});return XU($,K)}function jM($,U){if(!G0(U))throw Error("Invalid input to extend: expected a plain object");let J=$._zod.def.checks;if(J&&J.length>0){let K=$._zod.def.shape;for(let X in U)if(Object.getOwnPropertyDescriptor(K,X)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let W=jJ($._zod.def,{get shape(){let K={...$._zod.def.shape,...U};return Y0(this,"shape",K),K}});return XU($,W)}function gM($,U){if(!G0(U))throw Error("Invalid input to safeExtend: expected a plain object");let J=jJ($._zod.def,{get shape(){let Q={...$._zod.def.shape,...U};return Y0(this,"shape",Q),Q}});return XU($,J)}function bM($,U){if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let J=jJ($._zod.def,{get shape(){let Q={...$._zod.def.shape,...U._zod.def.shape};return Y0(this,"shape",Q),Q},get catchall(){return U._zod.def.catchall},checks:U._zod.def.checks??[]});return XU($,J)}function yM($,U,J){let W=U._zod.def.checks;if(W&&W.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let X=jJ(U._zod.def,{get shape(){let H=U._zod.def.shape,N={...H};if(J)for(let Y in J){if(!(Y in H))throw Error(`Unrecognized key: "${Y}"`);if(!J[Y])continue;N[Y]=$?new $({type:"optional",innerType:H[Y]}):H[Y]}else for(let Y in H)N[Y]=$?new $({type:"optional",innerType:H[Y]}):H[Y];return Y0(this,"shape",N),N},checks:[]});return XU(U,X)}function xM($,U,J){let Q=jJ(U._zod.def,{get shape(){let W=U._zod.def.shape,K={...W};if(J)for(let X in J){if(!(X in K))throw Error(`Unrecognized key: "${X}"`);if(!J[X])continue;K[X]=new $({type:"nonoptional",innerType:W[X]})}else for(let X in W)K[X]=new $({type:"nonoptional",innerType:W[X]});return Y0(this,"shape",K),K}});return XU(U,Q)}function O0($,U=0){if($.aborted===!0)return!0;for(let J=U;J<$.issues.length;J++)if($.issues[J]?.continue!==!0)return!0;return!1}function KN($,U=0){if($.aborted===!0)return!0;for(let J=U;J<$.issues.length;J++)if($.issues[J]?.continue===!1)return!0;return!1}function qU($,U){return U.map((J)=>{var Q;return(Q=J).path??(Q.path=[]),J.path.unshift($),J})}function nW($){return typeof $==="string"?$:$?.message}function HU($,U,J){let Q=$.message?$.message:nW($.inst?._zod.def?.error?.($))??nW(U?.error?.($))??nW(J.customError?.($))??nW(J.localeError?.($))??"Invalid input",{inst:W,continue:K,input:X,...H}=$;if(H.path??(H.path=[]),H.message=Q,U?.reportInput)H.input=X;return H}function aW($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function sW($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function W$($){let U=typeof $;switch(U){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let J=$;if(J&&Object.getPrototypeOf(J)!==Object.prototype&&"constructor"in J&&J.constructor)return J.constructor.name}}return U}function g8(...$){let[U,J,Q]=$;if(typeof U==="string")return{message:U,code:"custom",input:J,inst:Q};return{...U}}function hM($){return Object.entries($).filter(([U,J])=>{return Number.isNaN(Number.parseInt(U,10))}).map((U)=>U[1])}function RI($){let U=atob($),J=new Uint8Array(U.length);for(let Q=0;Q<U.length;Q++)J[Q]=U.charCodeAt(Q);return J}function VI($){let U="";for(let J=0;J<$.length;J++)U+=String.fromCharCode($[J]);return btoa(U)}function fM($){let U=$.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-U.length%4)%4);return RI(U+J)}function uM($){return VI($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function lM($){let U=$.replace(/^0x/,"");if(U.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(U.length/2);for(let Q=0;Q<U.length;Q+=2)J[Q/2]=Number.parseInt(U.slice(Q,Q+2),16);return J}function mM($){return Array.from($).map((U)=>U.toString(16).padStart(2,"0")).join("")}class wI{constructor(...$){}}var MI=($,U)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:U,enumerable:!1}),$.message=JSON.stringify(U,v8,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},tW=g("$ZodError",MI),ZU=g("$ZodError",MI,{Parent:Error});function eW($,U=(J)=>J.message){let J={},Q=[];for(let W of $.issues)if(W.path.length>0)J[W.path[0]]=J[W.path[0]]||[],J[W.path[0]].push(U(W));else Q.push(U(W));return{formErrors:Q,fieldErrors:J}}function $Q($,U=(J)=>J.message){let J={_errors:[]},Q=(W,K=[])=>{for(let X of W.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((H)=>Q({issues:H},[...K,...X.path]));else if(X.code==="invalid_key")Q({issues:X.issues},[...K,...X.path]);else if(X.code==="invalid_element")Q({issues:X.issues},[...K,...X.path]);else{let H=[...K,...X.path];if(H.length===0)J._errors.push(U(X));else{let N=J,Y=0;while(Y<H.length){let G=H[Y];if(Y!==H.length-1)N[G]=N[G]||{_errors:[]};else N[G]=N[G]||{_errors:[]},N[G]._errors.push(U(X));N=N[G],Y++}}}};return Q($),J}function XN($,U=(J)=>J.message){let J={errors:[]},Q=(W,K=[])=>{var X,H;for(let N of W.issues)if(N.code==="invalid_union"&&N.errors.length)N.errors.map((Y)=>Q({issues:Y},[...K,...N.path]));else if(N.code==="invalid_key")Q({issues:N.issues},[...K,...N.path]);else if(N.code==="invalid_element")Q({issues:N.issues},[...K,...N.path]);else{let Y=[...K,...N.path];if(Y.length===0){J.errors.push(U(N));continue}let G=J,O=0;while(O<Y.length){let E=Y[O],k=O===Y.length-1;if(typeof E==="string")G.properties??(G.properties={}),(X=G.properties)[E]??(X[E]={errors:[]}),G=G.properties[E];else G.items??(G.items=[]),(H=G.items)[E]??(H[E]={errors:[]}),G=G.items[E];if(k)G.errors.push(U(N));O++}}};return Q($),J}function BI($){let U=[],J=$.map((Q)=>typeof Q==="object"?Q.key:Q);for(let Q of J)if(typeof Q==="number")U.push(`[${Q}]`);else if(typeof Q==="symbol")U.push(`[${JSON.stringify(String(Q))}]`);else if(/[^\w$]/.test(Q))U.push(`[${JSON.stringify(Q)}]`);else{if(U.length)U.push(".");U.push(Q)}return U.join("")}function HN($){let U=[],J=[...$.issues].sort((Q,W)=>(Q.path??[]).length-(W.path??[]).length);for(let Q of J)if(U.push(`✖ ${Q.message}`),Q.path?.length)U.push(` → at ${BI(Q.path)}`);return U.join(`-`)}var b8=($)=>(U,J,Q,W)=>{let K=Q?{...Q,async:!1}:{async:!1},X=U._zod.run({value:J,issues:[]},K);if(X instanceof Promise)throw new YJ;if(X.issues.length){let H=new(W?.Err??$)(X.issues.map((N)=>HU(N,K,S6())));throw o9(H,W?.callee),H}return X.value},r9=b8(ZU),y8=($)=>async(U,J,Q,W)=>{let K=Q?{...Q,async:!0}:{async:!0},X=U._zod.run({value:J,issues:[]},K);if(X instanceof Promise)X=await X;if(X.issues.length){let H=new(W?.Err??$)(X.issues.map((N)=>HU(N,K,S6())));throw o9(H,W?.callee),H}return X.value},a9=y8(ZU),x8=($)=>(U,J,Q)=>{let W=Q?{...Q,async:!1}:{async:!1},K=U._zod.run({value:J,issues:[]},W);if(K instanceof Promise)throw new YJ;return K.issues.length?{success:!1,error:new($??tW)(K.issues.map((X)=>HU(X,W,S6())))}:{success:!0,data:K.value}},NN=x8(ZU),h8=($)=>async(U,J,Q)=>{let W=Q?{...Q,async:!0}:{async:!0},K=U._zod.run({value:J,issues:[]},W);if(K instanceof Promise)K=await K;return K.issues.length?{success:!1,error:new $(K.issues.map((X)=>HU(X,W,S6())))}:{success:!0,data:K.value}},YN=h8(ZU),s9=($)=>(U,J,Q)=>{let W=Q?{...Q,direction:"backward"}:{direction:"backward"};return b8($)(U,J,W)},dM=s9(ZU),t9=($)=>(U,J,Q)=>{return b8($)(U,J,Q)},cM=t9(ZU),e9=($)=>async(U,J,Q)=>{let W=Q?{...Q,direction:"backward"}:{direction:"backward"};return y8($)(U,J,W)},nM=e9(ZU),$K=($)=>async(U,J,Q)=>{return y8($)(U,J,Q)},iM=$K(ZU),UK=($)=>(U,J,Q)=>{let W=Q?{...Q,direction:"backward"}:{direction:"backward"};return x8($)(U,J,W)},oM=UK(ZU),JK=($)=>(U,J,Q)=>{return x8($)(U,J,Q)},rM=JK(ZU),WK=($)=>async(U,J,Q)=>{let W=Q?{...Q,direction:"backward"}:{direction:"backward"};return h8($)(U,J,W)},aM=WK(ZU),QK=($)=>async(U,J,Q)=>{return h8($)(U,J,Q)},sM=QK(ZU);var BU={};RJ(BU,{xid:()=>kN,uuid7:()=>UB,uuid6:()=>$B,uuid4:()=>eM,uuid:()=>u0,uppercase:()=>hN,unicodeEmail:()=>PI,undefined:()=>yN,ulid:()=>EN,time:()=>CN,string:()=>TN,sha512_hex:()=>wB,sha512_base64url:()=>BB,sha512_base64:()=>MB,sha384_hex:()=>LB,sha384_base64url:()=>VB,sha384_base64:()=>RB,sha256_hex:()=>IB,sha256_base64url:()=>FB,sha256_base64:()=>DB,sha1_hex:()=>kB,sha1_base64url:()=>ZB,sha1_base64:()=>qB,rfc5322Email:()=>WB,number:()=>UQ,null:()=>bN,nanoid:()=>ZN,md5_hex:()=>GB,md5_base64url:()=>EB,md5_base64:()=>OB,mac:()=>wN,lowercase:()=>xN,ksuid:()=>qN,ipv6:()=>VN,ipv4:()=>RN,integer:()=>jN,idnEmail:()=>QB,httpProtocol:()=>zN,html5Email:()=>JB,hostname:()=>HB,hex:()=>YB,guid:()=>DN,extendedDuration:()=>tM,emoji:()=>LN,email:()=>FN,e164:()=>_N,duration:()=>IN,domain:()=>NB,datetime:()=>SN,date:()=>AN,cuid2:()=>ON,cuid:()=>GN,cidrv6:()=>BN,cidrv4:()=>MN,browserEmail:()=>KB,boolean:()=>gN,bigint:()=>vN,base64url:()=>KK,base64:()=>PN});var GN=/^[cC][0-9a-z]{6,}$/,ON=/^[0-9a-z]+$/,EN=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,kN=/^[0-9a-vA-V]{20}$/,qN=/^[A-Za-z0-9]{27}$/,ZN=/^[a-zA-Z0-9_-]{21}$/,IN=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tM=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,DN=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,u0=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},eM=u0(4),$B=u0(6),UB=u0(7),FN=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,JB=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,WB=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,PI=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,QB=PI,KB=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,XB="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function LN(){return new RegExp(XB,"u")}var RN=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,VN=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,wN=($)=>{let U=yU($??":");return new RegExp(`^(?:[0-9A-F]{2}${U}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${U}){5}[0-9a-f]{2}$`)},MN=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,BN=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,PN=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,KK=/^[A-Za-z0-9_-]*$/,HB=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,NB=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,zN=/^https?$/,_N=/^\+[1-9]\d{6,14}$/,zI="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",AN=new RegExp(`^${zI}$`);function _I($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function CN($){return new RegExp(`^${_I($)}$`)}function SN($){let U=_I({precision:$.precision}),J=["Z"];if($.local)J.push("");if($.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let Q=`${U}(?:${J.join("|")})`;return new RegExp(`^${zI}T(?:${Q})$`)}var TN=($)=>{let U=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${U}$`)},vN=/^-?\d+n?$/,jN=/^-?\d+$/,UQ=/^-?\d+(?:\.\d+)?$/,gN=/^(?:true|false)$/i,bN=/^null$/i;var yN=/^undefined$/i;var xN=/^[^A-Z]*$/,hN=/^[^a-z]*$/,YB=/^[0-9a-fA-F]*$/;function JQ($,U){return new RegExp(`^[A-Za-z0-9+/]{${$}}${U}$`)}function WQ($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var GB=/^[0-9a-fA-F]{32}$/,OB=JQ(22,"=="),EB=WQ(22),kB=/^[0-9a-fA-F]{40}$/,qB=JQ(27,"="),ZB=WQ(27),IB=/^[0-9a-fA-F]{64}$/,DB=JQ(43,"="),FB=WQ(43),LB=/^[0-9a-fA-F]{96}$/,RB=JQ(64,""),VB=WQ(64),wB=/^[0-9a-fA-F]{128}$/,MB=JQ(86,"=="),BB=WQ(86);var V6=g("$ZodCheck",($,U)=>{var J;$._zod??($._zod={}),$._zod.def=U,(J=$._zod).onattach??(J.onattach=[])}),CI={number:"number",bigint:"bigint",object:"date"},XK=g("$ZodCheckLessThan",($,U)=>{V6.init($,U);let J=CI[typeof U.value];$._zod.onattach.push((Q)=>{let W=Q._zod.bag,K=(U.inclusive?W.maximum:W.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(U.value<K)if(U.inclusive)W.maximum=U.value;else W.exclusiveMaximum=U.value}),$._zod.check=(Q)=>{if(U.inclusive?Q.value<=U.value:Q.value<U.value)return;Q.issues.push({origin:J,code:"too_big",maximum:typeof U.value==="object"?U.value.getTime():U.value,input:Q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),HK=g("$ZodCheckGreaterThan",($,U)=>{V6.init($,U);let J=CI[typeof U.value];$._zod.onattach.push((Q)=>{let W=Q._zod.bag,K=(U.inclusive?W.minimum:W.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(U.value>K)if(U.inclusive)W.minimum=U.value;else W.exclusiveMinimum=U.value}),$._zod.check=(Q)=>{if(U.inclusive?Q.value>=U.value:Q.value>U.value)return;Q.issues.push({origin:J,code:"too_small",minimum:typeof U.value==="object"?U.value.getTime():U.value,input:Q.value,inclusive:U.inclusive,inst:$,continue:!U.abort})}}),fN=g("$ZodCheckMultipleOf",($,U)=>{V6.init($,U),$._zod.onattach.push((J)=>{var Q;(Q=J._zod.bag).multipleOf??(Q.multipleOf=U.value)}),$._zod.check=(J)=>{if(typeof J.value!==typeof U.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%U.value===BigInt(0):sH(J.value,U.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:U.value,input:J.value,inst:$,continue:!U.abort})}}),uN=g("$ZodCheckNumberFormat",($,U)=>{V6.init($,U),U.format=U.format||"float64";let J=U.format?.includes("int"),Q=J?"int":"number",[W,K]=WN[U.format];$._zod.onattach.push((X)=>{let H=X._zod.bag;if(H.format=U.format,H.minimum=W,H.maximum=K,J)H.pattern=jN}),$._zod.check=(X)=>{let H=X.value;if(J){if(!Number.isInteger(H)){X.issues.push({expected:Q,format:U.format,code:"invalid_type",continue:!1,input:H,inst:$});return}if(!Number.isSafeInteger(H)){if(H>0)X.issues.push({input:H,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:Q,inclusive:!0,continue:!U.abort});else X.issues.push({input:H,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:Q,inclusive:!0,continue:!U.abort});return}}if(H<W)X.issues.push({origin:"number",input:H,code:"too_small",minimum:W,inclusive:!0,inst:$,continue:!U.abort});if(H>K)X.issues.push({origin:"number",input:H,code:"too_big",maximum:K,inclusive:!0,inst:$,continue:!U.abort})}}),lN=g("$ZodCheckBigIntFormat",($,U)=>{V6.init($,U);let[J,Q]=QN[U.format];$._zod.onattach.push((W)=>{let K=W._zod.bag;K.format=U.format,K.minimum=J,K.maximum=Q}),$._zod.check=(W)=>{let K=W.value;if(K<J)W.issues.push({origin:"bigint",input:K,code:"too_small",minimum:J,inclusive:!0,inst:$,continue:!U.abort});if(K>Q)W.issues.push({origin:"bigint",input:K,code:"too_big",maximum:Q,inclusive:!0,inst:$,continue:!U.abort})}}),mN=g("$ZodCheckMaxSize",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!N0(W)&&W.size!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<W)Q._zod.bag.maximum=U.maximum}),$._zod.check=(Q)=>{let W=Q.value;if(W.size<=U.maximum)return;Q.issues.push({origin:aW(W),code:"too_big",maximum:U.maximum,inclusive:!0,input:W,inst:$,continue:!U.abort})}}),pN=g("$ZodCheckMinSize",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!N0(W)&&W.size!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>W)Q._zod.bag.minimum=U.minimum}),$._zod.check=(Q)=>{let W=Q.value;if(W.size>=U.minimum)return;Q.issues.push({origin:aW(W),code:"too_small",minimum:U.minimum,inclusive:!0,input:W,inst:$,continue:!U.abort})}}),dN=g("$ZodCheckSizeEquals",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!N0(W)&&W.size!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.minimum=U.size,W.maximum=U.size,W.size=U.size}),$._zod.check=(Q)=>{let W=Q.value,K=W.size;if(K===U.size)return;let X=K>U.size;Q.issues.push({origin:aW(W),...X?{code:"too_big",maximum:U.size}:{code:"too_small",minimum:U.size},inclusive:!0,exact:!0,input:Q.value,inst:$,continue:!U.abort})}}),cN=g("$ZodCheckMaxLength",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!N0(W)&&W.length!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag.maximum??Number.POSITIVE_INFINITY;if(U.maximum<W)Q._zod.bag.maximum=U.maximum}),$._zod.check=(Q)=>{let W=Q.value;if(W.length<=U.maximum)return;let X=sW(W);Q.issues.push({origin:X,code:"too_big",maximum:U.maximum,inclusive:!0,input:W,inst:$,continue:!U.abort})}}),nN=g("$ZodCheckMinLength",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!N0(W)&&W.length!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(U.minimum>W)Q._zod.bag.minimum=U.minimum}),$._zod.check=(Q)=>{let W=Q.value;if(W.length>=U.minimum)return;let X=sW(W);Q.issues.push({origin:X,code:"too_small",minimum:U.minimum,inclusive:!0,input:W,inst:$,continue:!U.abort})}}),iN=g("$ZodCheckLengthEquals",($,U)=>{var J;V6.init($,U),(J=$._zod.def).when??(J.when=(Q)=>{let W=Q.value;return!N0(W)&&W.length!==void 0}),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.minimum=U.length,W.maximum=U.length,W.length=U.length}),$._zod.check=(Q)=>{let W=Q.value,K=W.length;if(K===U.length)return;let X=sW(W),H=K>U.length;Q.issues.push({origin:X,...H?{code:"too_big",maximum:U.length}:{code:"too_small",minimum:U.length},inclusive:!0,exact:!0,input:Q.value,inst:$,continue:!U.abort})}}),f8=g("$ZodCheckStringFormat",($,U)=>{var J,Q;if(V6.init($,U),$._zod.onattach.push((W)=>{let K=W._zod.bag;if(K.format=U.format,U.pattern)K.patterns??(K.patterns=new Set),K.patterns.add(U.pattern)}),U.pattern)(J=$._zod).check??(J.check=(W)=>{if(U.pattern.lastIndex=0,U.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:U.format,input:W.value,...U.pattern?{pattern:U.pattern.toString()}:{},inst:$,continue:!U.abort})});else(Q=$._zod).check??(Q.check=()=>{})}),oN=g("$ZodCheckRegex",($,U)=>{f8.init($,U),$._zod.check=(J)=>{if(U.pattern.lastIndex=0,U.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:U.pattern.toString(),inst:$,continue:!U.abort})}}),rN=g("$ZodCheckLowerCase",($,U)=>{U.pattern??(U.pattern=xN),f8.init($,U)}),aN=g("$ZodCheckUpperCase",($,U)=>{U.pattern??(U.pattern=hN),f8.init($,U)}),sN=g("$ZodCheckIncludes",($,U)=>{V6.init($,U);let J=yU(U.includes),Q=new RegExp(typeof U.position==="number"?`^.{${U.position}}${J}`:J);U.pattern=Q,$._zod.onattach.push((W)=>{let K=W._zod.bag;K.patterns??(K.patterns=new Set),K.patterns.add(Q)}),$._zod.check=(W)=>{if(W.value.includes(U.includes,U.position))return;W.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:U.includes,input:W.value,inst:$,continue:!U.abort})}}),tN=g("$ZodCheckStartsWith",($,U)=>{V6.init($,U);let J=new RegExp(`^${yU(U.prefix)}.*`);U.pattern??(U.pattern=J),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(Q)=>{if(Q.value.startsWith(U.prefix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:U.prefix,input:Q.value,inst:$,continue:!U.abort})}}),eN=g("$ZodCheckEndsWith",($,U)=>{V6.init($,U);let J=new RegExp(`.*${yU(U.suffix)}$`);U.pattern??(U.pattern=J),$._zod.onattach.push((Q)=>{let W=Q._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(Q)=>{if(Q.value.endsWith(U.suffix))return;Q.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:U.suffix,input:Q.value,inst:$,continue:!U.abort})}});function AI($,U,J){if($.issues.length)U.issues.push(...qU(J,$.issues))}var $Y=g("$ZodCheckProperty",($,U)=>{V6.init($,U),$._zod.check=(J)=>{let Q=U.schema._zod.run({value:J.value[U.property],issues:[]},{});if(Q instanceof Promise)return Q.then((W)=>AI(W,J,U.property));AI(Q,J,U.property);return}}),UY=g("$ZodCheckMimeType",($,U)=>{V6.init($,U);let J=new Set(U.mime);$._zod.onattach.push((Q)=>{Q._zod.bag.mime=U.mime}),$._zod.check=(Q)=>{if(J.has(Q.value.type))return;Q.issues.push({code:"invalid_value",values:U.mime,input:Q.value.type,inst:$,continue:!U.abort})}}),JY=g("$ZodCheckOverwrite",($,U)=>{V6.init($,U),$._zod.check=(J)=>{J.value=U.tx(J.value)}});class NK{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let J=$.split(`-`).filter((K)=>K),Q=Math.min(...J.map((K)=>K.length-K.trimStart().length)),W=J.map((K)=>K.slice(Q)).map((K)=>" ".repeat(this.indent*2)+K);for(let K of W)this.content.push(K)}compile(){let $=Function,U=this?.args,Q=[...(this?.content??[""]).map((W)=>` ${W}`)];return new $(...U,Q.join(`-`))}}var WY={major:4,minor:4,patch:3};var h$=g("$ZodType",($,U)=>{var J;$??($={}),$._zod.def=U,$._zod.bag=$._zod.bag||{},$._zod.version=WY;let Q=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))Q.unshift($);for(let W of Q)for(let K of W._zod.onattach)K($);if(Q.length===0)(J=$._zod).deferred??(J.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let W=(X,H,N)=>{let Y=O0(X),G;for(let O of H){if(O._zod.def.when){if(KN(X))continue;if(!O._zod.def.when(X))continue}else if(Y)continue;let E=X.issues.length,k=O._zod.check(X);if(k instanceof Promise&&N?.async===!1)throw new YJ;if(G||k instanceof Promise)G=(G??Promise.resolve()).then(async()=>{if(await k,X.issues.length===E)return;if(!Y)Y=O0(X,E)});else{if(X.issues.length===E)continue;if(!Y)Y=O0(X,E)}}if(G)return G.then(()=>{return X});return X},K=(X,H,N)=>{if(O0(X))return X.aborted=!0,X;let Y=W(H,Q,N);if(Y instanceof Promise){if(N.async===!1)throw new YJ;return Y.then((G)=>$._zod.parse(G,N))}return $._zod.parse(Y,N)};$._zod.run=(X,H)=>{if(H.skipChecks)return $._zod.parse(X,H);if(H.direction==="backward"){let Y=$._zod.parse({value:X.value,issues:[]},{...H,skipChecks:!0});if(Y instanceof Promise)return Y.then((G)=>{return K(G,X,H)});return K(Y,X,H)}let N=$._zod.parse(X,H);if(N instanceof Promise){if(H.async===!1)throw new YJ;return N.then((Y)=>W(Y,Q,H))}return W(N,Q,H)}}s$($,"~standard",()=>({validate:(W)=>{try{let K=NN($,W);return K.success?{value:K.data}:{issues:K.error?.issues}}catch(K){return YN($,W).then((X)=>X.success?{value:X.data}:{issues:X.error?.issues})}},vendor:"zod",version:1}))}),l0=g("$ZodString",($,U)=>{h$.init($,U),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??TN($._zod.bag),$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=String(J.value)}catch(W){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:$}),J}}),I6=g("$ZodStringFormat",($,U)=>{f8.init($,U),l0.init($,U)}),KY=g("$ZodGUID",($,U)=>{U.pattern??(U.pattern=DN),I6.init($,U)}),XY=g("$ZodUUID",($,U)=>{if(U.version){let Q={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[U.version];if(Q===void 0)throw Error(`Invalid UUID version: "${U.version}"`);U.pattern??(U.pattern=u0(Q))}else U.pattern??(U.pattern=u0());I6.init($,U)}),HY=g("$ZodEmail",($,U)=>{U.pattern??(U.pattern=FN),I6.init($,U)}),NY=g("$ZodURL",($,U)=>{I6.init($,U),$._zod.check=(J)=>{try{let Q=J.value.trim();if(!U.normalize&&U.protocol?.source===zN.source){if(!/^https?:\/\//i.test(Q)){J.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:J.value,inst:$,continue:!U.abort});return}}let W=new URL(Q);if(U.hostname){if(U.hostname.lastIndex=0,!U.hostname.test(W.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:U.hostname.source,input:J.value,inst:$,continue:!U.abort})}if(U.protocol){if(U.protocol.lastIndex=0,!U.protocol.test(W.protocol.endsWith(":")?W.protocol.slice(0,-1):W.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:U.protocol.source,input:J.value,inst:$,continue:!U.abort})}if(U.normalize)J.value=W.href;else J.value=Q;return}catch(Q){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:$,continue:!U.abort})}}}),YY=g("$ZodEmoji",($,U)=>{U.pattern??(U.pattern=LN()),I6.init($,U)}),GY=g("$ZodNanoID",($,U)=>{U.pattern??(U.pattern=ZN),I6.init($,U)}),OY=g("$ZodCUID",($,U)=>{U.pattern??(U.pattern=GN),I6.init($,U)}),EY=g("$ZodCUID2",($,U)=>{U.pattern??(U.pattern=ON),I6.init($,U)}),kY=g("$ZodULID",($,U)=>{U.pattern??(U.pattern=EN),I6.init($,U)}),qY=g("$ZodXID",($,U)=>{U.pattern??(U.pattern=kN),I6.init($,U)}),ZY=g("$ZodKSUID",($,U)=>{U.pattern??(U.pattern=qN),I6.init($,U)}),IY=g("$ZodISODateTime",($,U)=>{U.pattern??(U.pattern=SN(U)),I6.init($,U)}),DY=g("$ZodISODate",($,U)=>{U.pattern??(U.pattern=AN),I6.init($,U)}),FY=g("$ZodISOTime",($,U)=>{U.pattern??(U.pattern=CN(U)),I6.init($,U)}),LY=g("$ZodISODuration",($,U)=>{U.pattern??(U.pattern=IN),I6.init($,U)}),RY=g("$ZodIPv4",($,U)=>{U.pattern??(U.pattern=RN),I6.init($,U),$._zod.bag.format="ipv4"}),VY=g("$ZodIPv6",($,U)=>{U.pattern??(U.pattern=VN),I6.init($,U),$._zod.bag.format="ipv6",$._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:$,continue:!U.abort})}}}),wY=g("$ZodMAC",($,U)=>{U.pattern??(U.pattern=wN(U.delimiter)),I6.init($,U),$._zod.bag.format="mac"}),MY=g("$ZodCIDRv4",($,U)=>{U.pattern??(U.pattern=MN),I6.init($,U)}),BY=g("$ZodCIDRv6",($,U)=>{U.pattern??(U.pattern=BN),I6.init($,U),$._zod.check=(J)=>{let Q=J.value.split("/");try{if(Q.length!==2)throw Error();let[W,K]=Q;if(!K)throw Error();let X=Number(K);if(`${X}`!==K)throw Error();if(X<0||X>128)throw Error();new URL(`http://[${W}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:$,continue:!U.abort})}}});function PY($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var zY=g("$ZodBase64",($,U)=>{U.pattern??(U.pattern=PN),I6.init($,U),$._zod.bag.contentEncoding="base64",$._zod.check=(J)=>{if(PY(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:$,continue:!U.abort})}});function cI($){if(!KK.test($))return!1;let U=$.replace(/[-_]/g,(Q)=>Q==="-"?"+":"/"),J=U.padEnd(Math.ceil(U.length/4)*4,"=");return PY(J)}var _Y=g("$ZodBase64URL",($,U)=>{U.pattern??(U.pattern=KK),I6.init($,U),$._zod.bag.contentEncoding="base64url",$._zod.check=(J)=>{if(cI(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:$,continue:!U.abort})}}),AY=g("$ZodE164",($,U)=>{U.pattern??(U.pattern=_N),I6.init($,U)});function nI($,U=null){try{let J=$.split(".");if(J.length!==3)return!1;let[Q]=J;if(!Q)return!1;let W=JSON.parse(atob(Q));if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(U&&(!("alg"in W)||W.alg!==U))return!1;return!0}catch{return!1}}var CY=g("$ZodJWT",($,U)=>{I6.init($,U),$._zod.check=(J)=>{if(nI(J.value,U.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:$,continue:!U.abort})}}),SY=g("$ZodCustomStringFormat",($,U)=>{I6.init($,U),$._zod.check=(J)=>{if(U.fn(J.value))return;J.issues.push({code:"invalid_format",format:U.format,input:J.value,inst:$,continue:!U.abort})}}),kK=g("$ZodNumber",($,U)=>{h$.init($,U),$._zod.pattern=$._zod.bag.pattern??UQ,$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=Number(J.value)}catch(X){}let W=J.value;if(typeof W==="number"&&!Number.isNaN(W)&&Number.isFinite(W))return J;let K=typeof W==="number"?Number.isNaN(W)?"NaN":!Number.isFinite(W)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:W,inst:$,...K?{received:K}:{}}),J}}),TY=g("$ZodNumberFormat",($,U)=>{uN.init($,U),kK.init($,U)}),QQ=g("$ZodBoolean",($,U)=>{h$.init($,U),$._zod.pattern=gN,$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=Boolean(J.value)}catch(K){}let W=J.value;if(typeof W==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:W,inst:$}),J}}),qK=g("$ZodBigInt",($,U)=>{h$.init($,U),$._zod.pattern=vN,$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=BigInt(J.value)}catch(W){}if(typeof J.value==="bigint")return J;return J.issues.push({expected:"bigint",code:"invalid_type",input:J.value,inst:$}),J}}),vY=g("$ZodBigIntFormat",($,U)=>{lN.init($,U),qK.init($,U)}),jY=g("$ZodSymbol",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(typeof W==="symbol")return J;return J.issues.push({expected:"symbol",code:"invalid_type",input:W,inst:$}),J}}),gY=g("$ZodUndefined",($,U)=>{h$.init($,U),$._zod.pattern=yN,$._zod.values=new Set([void 0]),$._zod.parse=(J,Q)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"undefined",code:"invalid_type",input:W,inst:$}),J}}),bY=g("$ZodNull",($,U)=>{h$.init($,U),$._zod.pattern=bN,$._zod.values=new Set([null]),$._zod.parse=(J,Q)=>{let W=J.value;if(W===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:W,inst:$}),J}}),yY=g("$ZodAny",($,U)=>{h$.init($,U),$._zod.parse=(J)=>J}),xY=g("$ZodUnknown",($,U)=>{h$.init($,U),$._zod.parse=(J)=>J}),hY=g("$ZodNever",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:$}),J}}),fY=g("$ZodVoid",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"void",code:"invalid_type",input:W,inst:$}),J}}),uY=g("$ZodDate",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{if(U.coerce)try{J.value=new Date(J.value)}catch(H){}let W=J.value,K=W instanceof Date;if(K&&!Number.isNaN(W.getTime()))return J;return J.issues.push({expected:"date",code:"invalid_type",input:W,...K?{received:"Invalid Date"}:{},inst:$}),J}});function TI($,U,J){if($.issues.length)U.issues.push(...qU(J,$.issues));U.value[J]=$.value}var lY=g("$ZodArray",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(!Array.isArray(W))return J.issues.push({expected:"array",code:"invalid_type",input:W,inst:$}),J;J.value=Array(W.length);let K=[];for(let X=0;X<W.length;X++){let H=W[X],N=U.element._zod.run({value:H,issues:[]},Q);if(N instanceof Promise)K.push(N.then((Y)=>TI(Y,J,X)));else TI(N,J,X)}if(K.length)return Promise.all(K).then(()=>J);return J}});function EK($,U,J,Q,W,K){let X=J in Q;if($.issues.length){if(W&&K&&!X)return;U.issues.push(...qU(J,$.issues))}if(!X&&!W){if(!$.issues.length)U.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[J]});return}if($.value===void 0){if(X)U.value[J]=void 0}else U.value[J]=$.value}function iI($){let U=Object.keys($.shape);for(let Q of U)if(!$.shape?.[Q]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${Q}": expected a Zod schema`);let J=JN($.shape);return{...$,keys:U,keySet:new Set(U),numKeys:U.length,optionalKeys:new Set(J)}}function oI($,U,J,Q,W,K){let X=[],H=W.keySet,N=W.catchall._zod,Y=N.def.type,G=N.optin==="optional",O=N.optout==="optional";for(let E in U){if(E==="__proto__")continue;if(H.has(E))continue;if(Y==="never"){X.push(E);continue}let k=N.run({value:U[E],issues:[]},Q);if(k instanceof Promise)$.push(k.then((I)=>EK(I,J,E,U,G,O)));else EK(k,J,E,U,G,O)}if(X.length)J.issues.push({code:"unrecognized_keys",keys:X,input:U,inst:K});if(!$.length)return J;return Promise.all($).then(()=>{return J})}var rI=g("$ZodObject",($,U)=>{if(h$.init($,U),!Object.getOwnPropertyDescriptor(U,"shape")?.get){let H=U.shape;Object.defineProperty(U,"shape",{get:()=>{let N={...H};return Object.defineProperty(U,"shape",{value:N}),N}})}let Q=j8(()=>iI(U));s$($._zod,"propValues",()=>{let H=U.shape,N={};for(let Y in H){let G=H[Y]._zod;if(G.values){N[Y]??(N[Y]=new Set);for(let O of G.values)N[Y].add(O)}}return N});let W=f0,K=U.catchall,X;$._zod.parse=(H,N)=>{X??(X=Q.value);let Y=H.value;if(!W(Y))return H.issues.push({expected:"object",code:"invalid_type",input:Y,inst:$}),H;H.value={};let G=[],O=X.shape;for(let E of X.keys){let k=O[E],I=k._zod.optin==="optional",R=k._zod.optout==="optional",q=k._zod.run({value:Y[E],issues:[]},N);if(q instanceof Promise)G.push(q.then((Z)=>EK(Z,H,E,Y,I,R)));else EK(q,H,E,Y,I,R)}if(!K)return G.length?Promise.all(G).then(()=>H):H;return oI(G,Y,H,N,Q.value,$)}}),mY=g("$ZodObjectJIT",($,U)=>{rI.init($,U);let J=$._zod.parse,Q=j8(()=>iI(U)),W=(E)=>{let k=new NK(["shape","payload","ctx"]),I=Q.value,R=(P)=>{let L=i9(P);return`shape[${L}]._zod.run({ value: input[${L}], issues: [] }, ctx)`};k.write("const input = payload.value;");let q=Object.create(null),Z=0;for(let P of I.keys)q[P]=`key_${Z++}`;k.write("const newResult = {};");for(let P of I.keys){let L=q[P],B=i9(P),z=E[P],A=z?._zod?.optin==="optional",D=z?._zod?.optout==="optional";if(k.write(`const ${L} = ${R(P)};`),A&&D)k.write(`- if (${L}.issues.length) {- if (${B} in input) {- payload.issues = payload.issues.concat(${L}.issues.map(iss => ({+}`;class Ld{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new ia(e.texture);if(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){if(this.mesh===null){let t=e.cameras[0].viewport,n=new bn({vertexShader:yM,fragmentShader:bM,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new dt(new Ns(20,20),n)}}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Nd extends Nn{constructor(e,t){super();let n=this,i=null,r=1,s=null,o="local-floor",a=1,c=null,l=null,u=null,f=null,h=null,d=null,g=typeof XRWebGLBinding<"u",b=new Ld,p={},m=t.getContextAttributes(),A=null,T=null,v=[],w=[],E=new Pe,R=null,_=new Pt;_.viewport=new it;let S=new Pt;S.viewport=new it;let F=[_,S],C=new Dl,z=null,J=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let ne=v[Z];if(ne===void 0)ne=new Ts,v[Z]=ne;return ne.getTargetRaySpace()},this.getControllerGrip=function(Z){let ne=v[Z];if(ne===void 0)ne=new Ts,v[Z]=ne;return ne.getGripSpace()},this.getHand=function(Z){let ne=v[Z];if(ne===void 0)ne=new Ts,v[Z]=ne;return ne.getHandSpace()};function O(Z){let ne=w.indexOf(Z.inputSource);if(ne===-1)return;let fe=v[ne];if(fe!==void 0)fe.update(Z.inputSource,Z.frame,c||s),fe.dispatchEvent({type:Z.type,data:Z.inputSource})}function H(){i.removeEventListener("select",O),i.removeEventListener("selectstart",O),i.removeEventListener("selectend",O),i.removeEventListener("squeeze",O),i.removeEventListener("squeezestart",O),i.removeEventListener("squeezeend",O),i.removeEventListener("end",H),i.removeEventListener("inputsourceschange",V);for(let Z=0;Z<v.length;Z++){let ne=w[Z];if(ne===null)continue;w[Z]=null,v[Z].disconnect(ne)}z=null,J=null,b.reset();for(let Z in p)delete p[Z];e.setRenderTarget(A),h=null,f=null,u=null,i=null,T=null,Be.stop(),n.isPresenting=!1,e.setPixelRatio(R),e.setSize(E.width,E.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){if(r=Z,n.isPresenting===!0)Me("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){if(o=Z,n.isPresenting===!0)Me("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||s},this.setReferenceSpace=function(Z){c=Z},this.getBaseLayer=function(){return f!==null?f:h},this.getBinding=function(){if(u===null&&g)u=new XRWebGLBinding(i,t);return u},this.getFrame=function(){return d},this.getSession=function(){return i},this.setSession=async function(Z){if(i=Z,i!==null){if(A=e.getRenderTarget(),i.addEventListener("select",O),i.addEventListener("selectstart",O),i.addEventListener("selectend",O),i.addEventListener("squeeze",O),i.addEventListener("squeezestart",O),i.addEventListener("squeezeend",O),i.addEventListener("end",H),i.addEventListener("inputsourceschange",V),m.xrCompatible!==!0)await t.makeXRCompatible();if(R=e.getPixelRatio(),e.getSize(E),!(g&&("createProjectionLayer"in XRWebGLBinding.prototype))){let fe={antialias:m.antialias,alpha:!0,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:r};h=new XRWebGLLayer(i,t,fe),i.updateRenderState({baseLayer:h}),e.setPixelRatio(1),e.setSize(h.framebufferWidth,h.framebufferHeight,!1),T=new yn(h.framebufferWidth,h.framebufferHeight,{format:$n,type:Ln,colorSpace:e.outputColorSpace,stencilBuffer:m.stencil,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1})}else{let fe=null,de=null,Re=null;if(m.depth)Re=m.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,fe=m.stencil?sr:rr,de=m.stencil?$r:Ci;let $e={colorFormat:t.RGBA8,depthFormat:Re,scaleFactor:r};u=this.getBinding(),f=u.createProjectionLayer($e),i.updateRenderState({layers:[f]}),e.setPixelRatio(1),e.setSize(f.textureWidth,f.textureHeight,!1),T=new yn(f.textureWidth,f.textureHeight,{format:$n,type:Ln,depthTexture:new Ni(f.textureWidth,f.textureHeight,de,void 0,void 0,void 0,void 0,void 0,void 0,fe),stencilBuffer:m.stencil,colorSpace:e.outputColorSpace,samples:m.antialias?4:0,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}T.isXRRenderTarget=!0,this.setFoveation(a),c=null,s=await i.requestReferenceSpace(o),Be.setContext(i),Be.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return b.getDepthTexture()};function V(Z){for(let ne=0;ne<Z.removed.length;ne++){let fe=Z.removed[ne],de=w.indexOf(fe);if(de>=0)w[de]=null,v[de].disconnect(fe)}for(let ne=0;ne<Z.added.length;ne++){let fe=Z.added[ne],de=w.indexOf(fe);if(de===-1){for(let $e=0;$e<v.length;$e++)if($e>=w.length){w.push(fe),de=$e;break}else if(w[$e]===null){w[$e]=fe,de=$e;break}if(de===-1)break}let Re=v[de];if(Re)Re.connect(fe)}}let U=new N,K=new N;function Q(Z,ne,fe){U.setFromMatrixPosition(ne.matrixWorld),K.setFromMatrixPosition(fe.matrixWorld);let de=U.distanceTo(K),Re=ne.projectionMatrix.elements,$e=fe.projectionMatrix.elements,Ue=Re[14]/(Re[10]-1),ze=Re[14]/(Re[10]+1),Je=(Re[9]+1)/Re[5],qe=(Re[9]-1)/Re[5],je=(Re[8]-1)/Re[0],Ut=($e[8]+1)/$e[0],pn=Ue*je,pt=Ue*Ut,Gt=de/(-je+Ut),Ot=Gt*-je;if(ne.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(Ot),Z.translateZ(Gt),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),Re[10]===-1)Z.projectionMatrix.copy(ne.projectionMatrix),Z.projectionMatrixInverse.copy(ne.projectionMatrixInverse);else{let Ct=Ue+Gt,L=ze+Gt,mn=pn-Ot,tt=pt+(de-Ot),mt=Je*ze/L*Ct,M=qe*ze/L*Ct;Z.projectionMatrix.makePerspective(mn,tt,mt,M,Ct,L),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function se(Z,ne){if(ne===null)Z.matrixWorld.copy(Z.matrix);else Z.matrixWorld.multiplyMatrices(ne.matrixWorld,Z.matrix);Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(i===null)return;let{near:ne,far:fe}=Z;if(b.texture!==null){if(b.depthNear>0)ne=b.depthNear;if(b.depthFar>0)fe=b.depthFar}if(C.near=S.near=_.near=ne,C.far=S.far=_.far=fe,z!==C.near||J!==C.far)i.updateRenderState({depthNear:C.near,depthFar:C.far}),z=C.near,J=C.far;C.layers.mask=Z.layers.mask|6,_.layers.mask=C.layers.mask&-5,S.layers.mask=C.layers.mask&-3;let de=Z.parent,Re=C.cameras;se(C,de);for(let $e=0;$e<Re.length;$e++)se(Re[$e],de);if(Re.length===2)Q(C,_,S);else C.projectionMatrix.copy(_.projectionMatrix);me(Z,C,de)};function me(Z,ne,fe){if(fe===null)Z.matrix.copy(ne.matrixWorld);else Z.matrix.copy(fe.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(ne.matrixWorld);if(Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(ne.projectionMatrix),Z.projectionMatrixInverse.copy(ne.projectionMatrixInverse),Z.isPerspectiveCamera)Z.fov=er*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1}this.getCamera=function(){return C},this.getFoveation=function(){if(f===null&&h===null)return;return a},this.setFoveation=function(Z){if(a=Z,f!==null)f.fixedFoveation=Z;if(h!==null&&h.fixedFoveation!==void 0)h.fixedFoveation=Z},this.hasDepthSensing=function(){return b.texture!==null},this.getDepthSensingMesh=function(){return b.getMesh(C)},this.getCameraTexture=function(Z){return p[Z]};let _e=null;function Xe(Z,ne){if(l=ne.getViewerPose(c||s),d=ne,l!==null){let fe=l.views;if(h!==null)e.setRenderTargetFramebuffer(T,h.framebuffer),e.setRenderTarget(T);let de=!1;if(fe.length!==C.cameras.length)C.cameras.length=0,de=!0;for(let ze=0;ze<fe.length;ze++){let Je=fe[ze],qe=null;if(h!==null)qe=h.getViewport(Je);else{let Ut=u.getViewSubImage(f,Je);if(qe=Ut.viewport,ze===0)e.setRenderTargetTextures(T,Ut.colorTexture,Ut.depthStencilTexture),e.setRenderTarget(T)}let je=F[ze];if(je===void 0)je=new Pt,je.layers.enable(ze),je.viewport=new it,F[ze]=je;if(je.matrix.fromArray(Je.transform.matrix),je.matrix.decompose(je.position,je.quaternion,je.scale),je.projectionMatrix.fromArray(Je.projectionMatrix),je.projectionMatrixInverse.copy(je.projectionMatrix).invert(),je.viewport.set(qe.x,qe.y,qe.width,qe.height),ze===0)C.matrix.copy(je.matrix),C.matrix.decompose(C.position,C.quaternion,C.scale);if(de===!0)C.cameras.push(je)}let Re=i.enabledFeatures;if(Re&&Re.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&g){u=n.getBinding();let ze=u.getDepthInformation(fe[0]);if(ze&&ze.isValid&&ze.texture)b.init(ze,i.renderState)}if(Re&&Re.includes("camera-access")&&g){e.state.unbindTexture(),u=n.getBinding();for(let ze=0;ze<fe.length;ze++){let Je=fe[ze].camera;if(Je){let qe=p[Je];if(!qe)qe=new ia,p[Je]=qe;let je=u.getCameraImage(Je);qe.sourceTexture=je}}}}for(let fe=0;fe<v.length;fe++){let de=w[fe],Re=v[fe];if(de!==null&&Re!==void 0)Re.update(de,ne,c||s)}if(_e)_e(Z,ne);if(ne.detectedPlanes)n.dispatchEvent({type:"planesdetected",data:ne});d=null}let Be=new bd;Be.setAnimationLoop(Xe),this.setAnimationLoop=function(Z){_e=Z},this.dispose=function(){}}}var SM=new Fe,Dd=new De;Dd.set(-1,0,0,0,1,0,0,0,1);function MM(e,t){function n(p,m){if(p.matrixAutoUpdate===!0)p.updateMatrix();m.value.copy(p.matrix)}function i(p,m){if(m.color.getRGB(p.fogColor.value,wl(e)),m.isFog)p.fogNear.value=m.near,p.fogFar.value=m.far;else if(m.isFogExp2)p.fogDensity.value=m.density}function r(p,m,A,T,v){if(m.isNodeMaterial)m.uniformsNeedUpdate=!1;else if(m.isMeshBasicMaterial)s(p,m);else if(m.isMeshLambertMaterial){if(s(p,m),m.envMap)p.envMapIntensity.value=m.envMapIntensity}else if(m.isMeshToonMaterial)s(p,m),f(p,m);else if(m.isMeshPhongMaterial){if(s(p,m),u(p,m),m.envMap)p.envMapIntensity.value=m.envMapIntensity}else if(m.isMeshStandardMaterial){if(s(p,m),h(p,m),m.isMeshPhysicalMaterial)d(p,m,v)}else if(m.isMeshMatcapMaterial)s(p,m),g(p,m);else if(m.isMeshDepthMaterial)s(p,m);else if(m.isMeshDistanceMaterial)s(p,m),b(p,m);else if(m.isMeshNormalMaterial)s(p,m);else if(m.isLineBasicMaterial){if(o(p,m),m.isLineDashedMaterial)a(p,m)}else if(m.isPointsMaterial)c(p,m,A,T);else if(m.isSpriteMaterial)l(p,m);else if(m.isShadowMaterial)p.color.value.copy(m.color),p.opacity.value=m.opacity;else if(m.isShaderMaterial)m.uniformsNeedUpdate=!1}function s(p,m){if(p.opacity.value=m.opacity,m.color)p.diffuse.value.copy(m.color);if(m.emissive)p.emissive.value.copy(m.emissive).multiplyScalar(m.emissiveIntensity);if(m.map)p.map.value=m.map,n(m.map,p.mapTransform);if(m.alphaMap)p.alphaMap.value=m.alphaMap,n(m.alphaMap,p.alphaMapTransform);if(m.bumpMap){if(p.bumpMap.value=m.bumpMap,n(m.bumpMap,p.bumpMapTransform),p.bumpScale.value=m.bumpScale,m.side===Xt)p.bumpScale.value*=-1}if(m.normalMap){if(p.normalMap.value=m.normalMap,n(m.normalMap,p.normalMapTransform),p.normalScale.value.copy(m.normalScale),m.side===Xt)p.normalScale.value.negate()}if(m.displacementMap)p.displacementMap.value=m.displacementMap,n(m.displacementMap,p.displacementMapTransform),p.displacementScale.value=m.displacementScale,p.displacementBias.value=m.displacementBias;if(m.emissiveMap)p.emissiveMap.value=m.emissiveMap,n(m.emissiveMap,p.emissiveMapTransform);if(m.specularMap)p.specularMap.value=m.specularMap,n(m.specularMap,p.specularMapTransform);if(m.alphaTest>0)p.alphaTest.value=m.alphaTest;let A=t.get(m),{envMap:T,envMapRotation:v}=A;if(T){if(p.envMap.value=T,p.envMapRotation.value.setFromMatrix4(SM.makeRotationFromEuler(v)).transpose(),T.isCubeTexture&&T.isRenderTargetTexture===!1)p.envMapRotation.value.premultiply(Dd);p.reflectivity.value=m.reflectivity,p.ior.value=m.ior,p.refractionRatio.value=m.refractionRatio}if(m.lightMap)p.lightMap.value=m.lightMap,p.lightMapIntensity.value=m.lightMapIntensity,n(m.lightMap,p.lightMapTransform);if(m.aoMap)p.aoMap.value=m.aoMap,p.aoMapIntensity.value=m.aoMapIntensity,n(m.aoMap,p.aoMapTransform)}function o(p,m){if(p.diffuse.value.copy(m.color),p.opacity.value=m.opacity,m.map)p.map.value=m.map,n(m.map,p.mapTransform)}function a(p,m){p.dashSize.value=m.dashSize,p.totalSize.value=m.dashSize+m.gapSize,p.scale.value=m.scale}function c(p,m,A,T){if(p.diffuse.value.copy(m.color),p.opacity.value=m.opacity,p.size.value=m.size*A,p.scale.value=T*0.5,m.map)p.map.value=m.map,n(m.map,p.uvTransform);if(m.alphaMap)p.alphaMap.value=m.alphaMap,n(m.alphaMap,p.alphaMapTransform);if(m.alphaTest>0)p.alphaTest.value=m.alphaTest}function l(p,m){if(p.diffuse.value.copy(m.color),p.opacity.value=m.opacity,p.rotation.value=m.rotation,m.map)p.map.value=m.map,n(m.map,p.mapTransform);if(m.alphaMap)p.alphaMap.value=m.alphaMap,n(m.alphaMap,p.alphaMapTransform);if(m.alphaTest>0)p.alphaTest.value=m.alphaTest}function u(p,m){p.specular.value.copy(m.specular),p.shininess.value=Math.max(m.shininess,0.0001)}function f(p,m){if(m.gradientMap)p.gradientMap.value=m.gradientMap}function h(p,m){if(p.metalness.value=m.metalness,m.metalnessMap)p.metalnessMap.value=m.metalnessMap,n(m.metalnessMap,p.metalnessMapTransform);if(p.roughness.value=m.roughness,m.roughnessMap)p.roughnessMap.value=m.roughnessMap,n(m.roughnessMap,p.roughnessMapTransform);if(m.envMap)p.envMapIntensity.value=m.envMapIntensity}function d(p,m,A){if(p.ior.value=m.ior,m.sheen>0){if(p.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),p.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap)p.sheenColorMap.value=m.sheenColorMap,n(m.sheenColorMap,p.sheenColorMapTransform);if(m.sheenRoughnessMap)p.sheenRoughnessMap.value=m.sheenRoughnessMap,n(m.sheenRoughnessMap,p.sheenRoughnessMapTransform)}if(m.clearcoat>0){if(p.clearcoat.value=m.clearcoat,p.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap)p.clearcoatMap.value=m.clearcoatMap,n(m.clearcoatMap,p.clearcoatMapTransform);if(m.clearcoatRoughnessMap)p.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,n(m.clearcoatRoughnessMap,p.clearcoatRoughnessMapTransform);if(m.clearcoatNormalMap){if(p.clearcoatNormalMap.value=m.clearcoatNormalMap,n(m.clearcoatNormalMap,p.clearcoatNormalMapTransform),p.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===Xt)p.clearcoatNormalScale.value.negate()}}if(m.dispersion>0)p.dispersion.value=m.dispersion;if(m.iridescence>0){if(p.iridescence.value=m.iridescence,p.iridescenceIOR.value=m.iridescenceIOR,p.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],p.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap)p.iridescenceMap.value=m.iridescenceMap,n(m.iridescenceMap,p.iridescenceMapTransform);if(m.iridescenceThicknessMap)p.iridescenceThicknessMap.value=m.iridescenceThicknessMap,n(m.iridescenceThicknessMap,p.iridescenceThicknessMapTransform)}if(m.transmission>0){if(p.transmission.value=m.transmission,p.transmissionSamplerMap.value=A.texture,p.transmissionSamplerSize.value.set(A.width,A.height),m.transmissionMap)p.transmissionMap.value=m.transmissionMap,n(m.transmissionMap,p.transmissionMapTransform);if(p.thickness.value=m.thickness,m.thicknessMap)p.thicknessMap.value=m.thicknessMap,n(m.thicknessMap,p.thicknessMapTransform);p.attenuationDistance.value=m.attenuationDistance,p.attenuationColor.value.copy(m.attenuationColor)}if(m.anisotropy>0){if(p.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap)p.anisotropyMap.value=m.anisotropyMap,n(m.anisotropyMap,p.anisotropyMapTransform)}if(p.specularIntensity.value=m.specularIntensity,p.specularColor.value.copy(m.specularColor),m.specularColorMap)p.specularColorMap.value=m.specularColorMap,n(m.specularColorMap,p.specularColorMapTransform);if(m.specularIntensityMap)p.specularIntensityMap.value=m.specularIntensityMap,n(m.specularIntensityMap,p.specularIntensityMapTransform)}function g(p,m){if(m.matcap)p.matcap.value=m.matcap}function b(p,m){let A=t.get(m).light;p.referencePosition.value.setFromMatrixPosition(A.matrixWorld),p.nearDistance.value=A.shadow.camera.near,p.farDistance.value=A.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:r}}function wM(e,t,n,i){let r={},s={},o=[],a=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(v,w){let E=w.program;i.uniformBlockBinding(v,E)}function l(v,w){let E=r[v.id];if(E===void 0)p(v),E=u(v),r[v.id]=E,v.addEventListener("dispose",A);let R=w.program;i.updateUBOMapping(v,R);let _=t.render.frame;if(s[v.id]!==_)h(v),s[v.id]=_}function u(v){let w=f();v.__bindingPointIndex=w;let E=e.createBuffer(),{__size:R,usage:_}=v;return e.bindBuffer(e.UNIFORM_BUFFER,E),e.bufferData(e.UNIFORM_BUFFER,R,_),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,w,E),E}function f(){for(let v=0;v<a;v++)if(o.indexOf(v)===-1)return o.push(v),v;return Ne("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(v){let w=r[v.id],{uniforms:E,__cache:R}=v;e.bindBuffer(e.UNIFORM_BUFFER,w);for(let _=0,S=E.length;_<S;_++){let F=E[_];if(Array.isArray(F))for(let C=0,z=F.length;C<z;C++)d(F[C],_,C,R);else d(F,_,0,R)}e.bindBuffer(e.UNIFORM_BUFFER,null)}function d(v,w,E,R){if(b(v,w,E,R)===!0){let{__offset:_,value:S}=v;if(Array.isArray(S)){let F=0;for(let C=0;C<S.length;C++){let z=S[C],J=m(z);if(g(z,v.__data,F),typeof z!=="number"&&typeof z!=="boolean"&&!z.isMatrix3&&!ArrayBuffer.isView(z))F+=J.storage/Float32Array.BYTES_PER_ELEMENT}}else g(S,v.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,_,v.__data)}}function g(v,w,E){if(typeof v==="number"||typeof v==="boolean")w[0]=v;else if(v.isMatrix3)w[0]=v.elements[0],w[1]=v.elements[1],w[2]=v.elements[2],w[3]=0,w[4]=v.elements[3],w[5]=v.elements[4],w[6]=v.elements[5],w[7]=0,w[8]=v.elements[6],w[9]=v.elements[7],w[10]=v.elements[8],w[11]=0;else if(ArrayBuffer.isView(v))w.set(new v.constructor(v.buffer,v.byteOffset,w.length));else v.toArray(w,E)}function b(v,w,E,R){let _=v.value,S=w+"_"+E;if(R[S]===void 0){if(typeof _==="number"||typeof _==="boolean")R[S]=_;else if(ArrayBuffer.isView(_))R[S]=_.slice();else R[S]=_.clone();return!0}else{let F=R[S];if(typeof _==="number"||typeof _==="boolean"){if(F!==_)return R[S]=_,!0}else if(ArrayBuffer.isView(_))return!0;else if(F.equals(_)===!1)return F.copy(_),!0}return!1}function p(v){let w=v.uniforms,E=0,R=16;for(let S=0,F=w.length;S<F;S++){let C=Array.isArray(w[S])?w[S]:[w[S]];for(let z=0,J=C.length;z<J;z++){let O=C[z],H=Array.isArray(O.value)?O.value:[O.value];for(let V=0,U=H.length;V<U;V++){let K=H[V],Q=m(K),se=E%R,me=se%Q.boundary,_e=se+me;if(E+=me,_e!==0&&R-_e<Q.storage)E+=R-_e;O.__data=new Float32Array(Q.storage/Float32Array.BYTES_PER_ELEMENT),O.__offset=E,E+=Q.storage}}}let _=E%R;if(_>0)E+=R-_;return v.__size=E,v.__cache={},this}function m(v){let w={boundary:0,storage:0};if(typeof v==="number"||typeof v==="boolean")w.boundary=4,w.storage=4;else if(v.isVector2)w.boundary=8,w.storage=8;else if(v.isVector3||v.isColor)w.boundary=16,w.storage=12;else if(v.isVector4)w.boundary=16,w.storage=16;else if(v.isMatrix3)w.boundary=48,w.storage=48;else if(v.isMatrix4)w.boundary=64,w.storage=64;else if(v.isTexture)Me("WebGLRenderer: Texture samplers can not be part of an uniforms group.");else if(ArrayBuffer.isView(v))w.boundary=16,w.storage=v.byteLength;else Me("WebGLRenderer: Unsupported uniform value type.",v);return w}function A(v){let w=v.target;w.removeEventListener("dispose",A);let E=o.indexOf(w.__bindingPointIndex);o.splice(E,1),e.deleteBuffer(r[w.id]),delete r[w.id],delete s[w.id]}function T(){for(let v in r)e.deleteBuffer(r[v]);o=[],r={},s={}}return{bind:c,update:l,dispose:T}}var TM=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]),Xn=null;function EM(){if(Xn===null)Xn=new Rs(TM,16,16,or,hi),Xn.name="DFG_LUT",Xn.minFilter=kt,Xn.magFilter=kt,Xn.wrapS=Vr,Xn.wrapT=Vr,Xn.generateMipmaps=!1,Xn.needsUpdate=!0;return Xn}class jl{constructor(e={}){let{canvas:t=Gf(),context:n=null,depth:i=!0,stencil:r=!1,alpha:s=!1,antialias:o=!1,premultipliedAlpha:a=!0,preserveDrawingBuffer:c=!1,powerPreference:l="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:f=!1,outputBufferType:h=Ln}=e;this.isWebGLRenderer=!0;let d;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=n.getContextAttributes().alpha}else d=s;let g=h,b=new Set([Oc,Uc,Dc]),p=new Set([Ln,Ci,bs,$r,Lc,Nc]),m=new Uint32Array(4),A=new Int32Array(4),T=new N,v=null,w=null,E=[],R=[],_=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=Pn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let S=this,F=!1,C=null,z=null,J=null,O=null;this._outputColorSpace=Pi;let H=0,V=0,U=null,K=-1,Q=null,se=new it,me=new it,_e=null,Xe=new Le(0),Be=0,{width:Z,height:ne}=t,fe=1,de=null,Re=null,$e=new it(0,0,Z,ne),Ue=new it(0,0,Z,ne),ze=!1,Je=new Ps,qe=!1,je=!1,Ut=new Fe,pn=new N,pt=new it,Gt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Ot=!1;function Ct(){return U===null?fe:1}let L=n;function mn(y,D){return t.getContext(y,D)}try{let y={alpha:!0,depth:i,stencil:r,antialias:o,premultipliedAlpha:a,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if("setAttribute"in t)t.setAttribute("data-engine",`three.js r${Zh}`);if(t.addEventListener("webglcontextlost",Oe,!1),t.addEventListener("webglcontextrestored",yt,!1),t.addEventListener("webglcontextcreationerror",ht,!1),L===null){if(L=mn("webgl2",y),L===null)if(mn("webgl2"))throw Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.");else throw Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(y){throw Ne("WebGLRenderer: "+y.message),y}let tt,mt,M,x,P,W,te,ie,le,X,j,xe,we,ue,re,Ce,Ie,Qe,I,oe,Y,ae,ve;function ee(){if(tt=new Nb(L),tt.init(),Y=new vM(L,tt),mt=new Tb(L,tt,e,Y),M=new _M(L,tt),mt.reversedDepthBuffer&&f)M.buffers.depth.setReversed(!0);z=L.createFramebuffer(),J=L.createFramebuffer(),O=L.createFramebuffer(),x=new Ob(L),P=new iM,W=new xM(L,tt,M,P,mt,Y,x),te=new Lb(S),ie=new Bx(L),ae=new Mb(L,ie),le=new Db(L,ie,x,ae),X=new zb(L,le,ie,ae,x),Qe=new Fb(L,mt,W),re=new Eb(P),j=new nM(S,te,tt,mt,ae,re),xe=new MM(S,P),we=new sM,ue=new hM(tt),Ie=new Sb(S,te,M,X,d,a),Ce=new gM(S,X,mt),ve=new wM(L,x,mt,M),I=new wb(L,tt,x),oe=new Ub(L,tt,x),x.programs=j.programs,S.capabilities=mt,S.extensions=tt,S.properties=P,S.renderLists=we,S.shadowMap=Ce,S.state=M,S.info=x}if(ee(),g!==Ln)_=new Bb(g,t.width,t.height,o,i,r);let ce=new Nd(S,L);this.xr=ce,this.getContext=function(){return L},this.getContextAttributes=function(){return L.getContextAttributes()},this.forceContextLoss=function(){let y=tt.get("WEBGL_lose_context");if(y)y.loseContext()},this.forceContextRestore=function(){let y=tt.get("WEBGL_lose_context");if(y)y.restoreContext()},this.getPixelRatio=function(){return fe},this.setPixelRatio=function(y){if(y===void 0)return;fe=y,this.setSize(Z,ne,!1)},this.getSize=function(y){return y.set(Z,ne)},this.setSize=function(y,D,G=!0){if(ce.isPresenting){Me("WebGLRenderer: Can't change size while VR device is presenting.");return}if(Z=y,ne=D,t.width=Math.floor(y*fe),t.height=Math.floor(D*fe),G===!0)t.style.width=y+"px",t.style.height=D+"px";if(_!==null)_.setSize(t.width,t.height);this.setViewport(0,0,y,D)},this.getDrawingBufferSize=function(y){return y.set(Z*fe,ne*fe).floor()},this.setDrawingBufferSize=function(y,D,G){Z=y,ne=D,fe=G,t.width=Math.floor(y*G),t.height=Math.floor(D*G),this.setViewport(0,0,y,D)},this.setEffects=function(y){if(g===Ln){Ne("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(y){for(let D=0;D<y.length;D++)if(y[D].isOutputPass===!0){Me("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}_.setEffects(y||[])},this.getCurrentViewport=function(y){return y.copy(se)},this.getViewport=function(y){return y.copy($e)},this.setViewport=function(y,D,G,k){if(y.isVector4)$e.set(y.x,y.y,y.z,y.w);else $e.set(y,D,G,k);M.viewport(se.copy($e).multiplyScalar(fe).round())},this.getScissor=function(y){return y.copy(Ue)},this.setScissor=function(y,D,G,k){if(y.isVector4)Ue.set(y.x,y.y,y.z,y.w);else Ue.set(y,D,G,k);M.scissor(me.copy(Ue).multiplyScalar(fe).round())},this.getScissorTest=function(){return ze},this.setScissorTest=function(y){M.setScissorTest(ze=y)},this.setOpaqueSort=function(y){de=y},this.setTransparentSort=function(y){Re=y},this.getClearColor=function(y){return y.copy(Ie.getClearColor())},this.setClearColor=function(){Ie.setClearColor(...arguments)},this.getClearAlpha=function(){return Ie.getClearAlpha()},this.setClearAlpha=function(){Ie.setClearAlpha(...arguments)},this.clear=function(y=!0,D=!0,G=!0){let k=0;if(y){let B=!1;if(U!==null){let ge=U.texture.format;B=b.has(ge)}if(B){let ge=U.texture.type,be=p.has(ge),pe=Ie.getClearColor(),Se=Ie.getClearAlpha(),{r:Ee,g:ke,b:He}=pe;if(be)m[0]=Ee,m[1]=ke,m[2]=He,m[3]=Se,L.clearBufferuiv(L.COLOR,0,m);else A[0]=Ee,A[1]=ke,A[2]=He,A[3]=Se,L.clearBufferiv(L.COLOR,0,A)}else k|=L.COLOR_BUFFER_BIT}if(D)k|=L.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0);if(G)k|=L.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295);if(k!==0)L.clear(k)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(y){y.setRenderer(this),C=y},this.dispose=function(){t.removeEventListener("webglcontextlost",Oe,!1),t.removeEventListener("webglcontextrestored",yt,!1),t.removeEventListener("webglcontextcreationerror",ht,!1),Ie.dispose(),we.dispose(),ue.dispose(),P.dispose(),te.dispose(),X.dispose(),ae.dispose(),ve.dispose(),j.dispose(),ce.dispose(),ce.removeEventListener("sessionstart",nh),ce.removeEventListener("sessionend",ih),qi.stop()};function Oe(y){y.preventDefault(),gs("WebGLRenderer: Context Lost."),F=!0}function yt(){gs("WebGLRenderer: Context Restored."),F=!1;let y=x.autoReset,D=Ce.enabled,G=Ce.autoUpdate,k=Ce.needsUpdate,B=Ce.type;ee(),x.autoReset=y,Ce.enabled=D,Ce.autoUpdate=G,Ce.needsUpdate=k,Ce.type=B}function ht(y){Ne("WebGLRenderer: A WebGL context could not be created. Reason: ",y.statusMessage)}function Fn(y){let D=y.target;D.removeEventListener("dispose",Fn),ni(D)}function ni(y){L0(y),P.remove(y)}function L0(y){let D=P.get(y).programs;if(D!==void 0){if(D.forEach(function(G){j.releaseProgram(G)}),y.isShaderMaterial)j.releaseShaderCache(y)}}this.renderBufferDirect=function(y,D,G,k,B,ge){if(D===null)D=Gt;let be=B.isMesh&&B.matrixWorld.determinantAffine()<0,pe=U0(y,D,G,k,B);M.setMaterial(k,be);let Se=G.index,Ee=1;if(k.wireframe===!0){if(Se=le.getWireframeAttribute(G),Se===void 0)return;Ee=2}let ke=G.drawRange,He=G.attributes.position,Ae=ke.start*Ee,st=(ke.start+ke.count)*Ee;if(ge!==null)Ae=Math.max(Ae,ge.start*Ee),st=Math.min(st,(ge.start+ge.count)*Ee);if(Se!==null)Ae=Math.max(Ae,0),st=Math.min(st,Se.count);else if(He!==void 0&&He!==null)Ae=Math.max(Ae,0),st=Math.min(st,He.count);let wt=st-Ae;if(wt<0||wt===1/0)return;ae.setup(B,k,pe,G,Se);let bt,ct=I;if(Se!==null)bt=ie.get(Se),ct=oe,ct.setIndex(bt);if(B.isMesh)if(k.wireframe===!0)M.setLineWidth(k.wireframeLinewidth*Ct()),ct.setMode(L.LINES);else ct.setMode(L.TRIANGLES);else if(B.isLine){let Wt=k.linewidth;if(Wt===void 0)Wt=1;if(M.setLineWidth(Wt*Ct()),B.isLineSegments)ct.setMode(L.LINES);else if(B.isLineLoop)ct.setMode(L.LINE_LOOP);else ct.setMode(L.LINE_STRIP)}else if(B.isPoints)ct.setMode(L.POINTS);else if(B.isSprite)ct.setMode(L.TRIANGLES);if(B.isBatchedMesh)if(!tt.get("WEBGL_multi_draw")){let{_multiDrawStarts:Wt,_multiDrawCounts:ye,_multiDrawCount:sn}=B,Ke=Se?ie.get(Se).bytesPerElement:1,gn=P.get(k).currentProgram.getUniforms();for(let zn=0;zn<sn;zn++)gn.setValue(L,"_gl_DrawID",zn),ct.render(Wt[zn]/Ke,ye[zn])}else ct.renderMultiDraw(B._multiDrawStarts,B._multiDrawCounts,B._multiDrawCount);else if(B.isInstancedMesh)ct.renderInstances(Ae,wt,B.count);else if(G.isInstancedBufferGeometry){let Wt=G._maxInstanceCount!==void 0?G._maxInstanceCount:1/0,ye=Math.min(G.instanceCount,Wt);ct.renderInstances(Ae,wt,ye)}else ct.render(Ae,wt)};function th(y,D,G){if(y.transparent===!0&&y.side===vn&&y.forceSinglePass===!1)y.side=Xt,y.needsUpdate=!0,oo(y,D,G),y.side=Ri,y.needsUpdate=!0,oo(y,D,G),y.side=vn;else oo(y,D,G)}this.compile=function(y,D,G=null){if(G===null)G=y;if(w=ue.get(G),w.init(D),R.push(w),G.traverseVisible(function(B){if(B.isLight&&B.layers.test(D.layers)){if(w.pushLight(B),B.castShadow)w.pushShadow(B)}}),y!==G)y.traverseVisible(function(B){if(B.isLight&&B.layers.test(D.layers)){if(w.pushLight(B),B.castShadow)w.pushShadow(B)}});w.setupLights();let k=new Set;return y.traverse(function(B){if(!(B.isMesh||B.isPoints||B.isLine||B.isSprite))return;let ge=B.material;if(ge)if(Array.isArray(ge))for(let be=0;be<ge.length;be++){let pe=ge[be];th(pe,G,B),k.add(pe)}else th(ge,G,B),k.add(ge)}),w=R.pop(),k},this.compileAsync=function(y,D,G=null){let k=this.compile(y,D,G);return new Promise((B)=>{function ge(){if(k.forEach(function(be){if(P.get(be).currentProgram.isReady())k.delete(be)}),k.size===0){B(y);return}setTimeout(ge,10)}if(tt.get("KHR_parallel_shader_compile")!==null)ge();else setTimeout(ge,10)})};let $a=null;function N0(y){if($a)$a(y)}function nh(){qi.stop()}function ih(){qi.start()}let qi=new bd;if(qi.setAnimationLoop(N0),typeof self<"u")qi.setContext(self);this.setAnimationLoop=function(y){$a=y,ce.setAnimationLoop(y),y===null?qi.stop():qi.start()},ce.addEventListener("sessionstart",nh),ce.addEventListener("sessionend",ih),this.render=function(y,D){if(D!==void 0&&D.isCamera!==!0){Ne("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(F===!0)return;if(C!==null)C.renderStart(y,D);let G=ce.enabled===!0&&ce.isPresenting===!0,k=_!==null&&(U===null||G)&&_.begin(S,U);if(y.matrixWorldAutoUpdate===!0)y.updateMatrixWorld();if(D.parent===null&&D.matrixWorldAutoUpdate===!0)D.updateMatrixWorld();if(ce.enabled===!0&&ce.isPresenting===!0&&(_===null||_.isCompositing()===!1)){if(ce.cameraAutoUpdate===!0)ce.updateCamera(D);D=ce.getCamera()}if(y.isScene===!0)y.onBeforeRender(S,y,D,U);if(w=ue.get(y,R.length),w.init(D),w.state.textureUnits=W.getTextureUnits(),R.push(w),Ut.multiplyMatrices(D.projectionMatrix,D.matrixWorldInverse),Je.setFromProjectionMatrix(Ut,xl,D.reversedDepth),je=this.localClippingEnabled,qe=re.init(this.clippingPlanes,je),v=we.get(y,E.length),v.init(),E.push(v),ce.enabled===!0&&ce.isPresenting===!0){let be=S.xr.getDepthSensingMesh();if(be!==null)Za(be,D,-1/0,S.sortObjects)}if(Za(y,D,0,S.sortObjects),v.finish(),S.sortObjects===!0)v.sort(de,Re,D.reversedDepth);if(Ot=ce.enabled===!1||ce.isPresenting===!1||ce.hasDepthSensing()===!1,Ot)Ie.addToRenderList(v,y);if(this.info.render.frame++,this.info.autoReset===!0)this.info.reset();if(qe===!0)re.beginShadows();let B=w.state.shadowsArray;if(Ce.render(B,y,D),qe===!0)re.endShadows();if((k&&_.hasRenderPass())===!1){let be=v.opaque,pe=v.transmissive;if(w.setupLights(),D.isArrayCamera){let Se=D.cameras;if(pe.length>0)for(let Ee=0,ke=Se.length;Ee<ke;Ee++){let He=Se[Ee];sh(be,pe,y,He)}if(Ot)Ie.render(y);for(let Ee=0,ke=Se.length;Ee<ke;Ee++){let He=Se[Ee];rh(v,y,He,He.viewport)}}else{if(pe.length>0)sh(be,pe,y,D);if(Ot)Ie.render(y);rh(v,y,D)}}if(U!==null&&V===0)W.updateMultisampleRenderTarget(U),W.updateRenderTargetMipmap(U);if(k)_.end(S);if(y.isScene===!0)y.onAfterRender(S,y,D);if(ae.resetDefaultState(),K=-1,Q=null,R.pop(),R.length>0){if(w=R[R.length-1],W.setTextureUnits(w.state.textureUnits),qe===!0)re.setGlobalState(S.clippingPlanes,w.state.camera)}else w=null;if(E.pop(),E.length>0)v=E[E.length-1];else v=null;if(C!==null)C.renderEnd()};function Za(y,D,G,k){if(y.visible===!1)return;if(y.layers.test(D.layers)){if(y.isGroup)G=y.renderOrder;else if(y.isLOD){if(y.autoUpdate===!0)y.update(D)}else if(y.isLightProbeGrid)w.pushLightProbeGrid(y);else if(y.isLight){if(w.pushLight(y),y.castShadow)w.pushShadow(y)}else if(y.isSprite){if(!y.frustumCulled||Je.intersectsSprite(y)){if(k)pt.setFromMatrixPosition(y.matrixWorld).applyMatrix4(Ut);let be=X.update(y),pe=y.material;if(pe.visible)v.push(y,be,pe,G,pt.z,null)}}else if(y.isMesh||y.isLine||y.isPoints){if(!y.frustumCulled||Je.intersectsObject(y)){let be=X.update(y),pe=y.material;if(k){if(y.boundingSphere!==void 0){if(y.boundingSphere===null)y.computeBoundingSphere();pt.copy(y.boundingSphere.center)}else{if(be.boundingSphere===null)be.computeBoundingSphere();pt.copy(be.boundingSphere.center)}pt.applyMatrix4(y.matrixWorld).applyMatrix4(Ut)}if(Array.isArray(pe)){let Se=be.groups;for(let Ee=0,ke=Se.length;Ee<ke;Ee++){let He=Se[Ee],Ae=pe[He.materialIndex];if(Ae&&Ae.visible)v.push(y,be,Ae,G,pt.z,He)}}else if(pe.visible)v.push(y,be,pe,G,pt.z,null)}}}let ge=y.children;for(let be=0,pe=ge.length;be<pe;be++)Za(ge[be],D,G,k)}function rh(y,D,G,k){let{opaque:B,transmissive:ge,transparent:be}=y;if(w.setupLightsView(G),qe===!0)re.setGlobalState(S.clippingPlanes,G);if(k)M.viewport(se.copy(k));if(B.length>0)so(B,D,G);if(ge.length>0)so(ge,D,G);if(be.length>0)so(be,D,G);M.buffers.depth.setTest(!0),M.buffers.depth.setMask(!0),M.buffers.color.setMask(!0),M.setPolygonOffset(!1)}function sh(y,D,G,k){if((G.isScene===!0?G.overrideMaterial:null)!==null)return;if(w.state.transmissionRenderTarget[k.id]===void 0){let Ae=tt.has("EXT_color_buffer_half_float")||tt.has("EXT_color_buffer_float");w.state.transmissionRenderTarget[k.id]=new yn(1,1,{generateMipmaps:!0,type:Ae?hi:Ln,minFilter:Wn,samples:Math.max(4,mt.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ve.workingColorSpace})}let ge=w.state.transmissionRenderTarget[k.id],be=k.viewport||se;ge.setSize(be.z*S.transmissionResolutionScale,be.w*S.transmissionResolutionScale);let pe=S.getRenderTarget(),Se=S.getActiveCubeFace(),Ee=S.getActiveMipmapLevel();if(S.setRenderTarget(ge),S.getClearColor(Xe),Be=S.getClearAlpha(),Be<1)S.setClearColor(16777215,0.5);if(S.clear(),Ot)Ie.render(G);let ke=S.toneMapping;S.toneMapping=Pn;let He=k.viewport;if(k.viewport!==void 0)k.viewport=void 0;if(w.setupLightsView(k),qe===!0)re.setGlobalState(S.clippingPlanes,k);if(so(y,G,k),W.updateMultisampleRenderTarget(ge),W.updateRenderTargetMipmap(ge),tt.has("WEBGL_multisampled_render_to_texture")===!1){let Ae=!1;for(let st=0,wt=D.length;st<wt;st++){let bt=D[st],{object:ct,geometry:Wt,material:ye,group:sn}=bt;if(ye.side===vn&&ct.layers.test(k.layers)){let Ke=ye.side;ye.side=Xt,ye.needsUpdate=!0,oh(ct,G,k,Wt,ye,sn),ye.side=Ke,ye.needsUpdate=!0,Ae=!0}}if(Ae===!0)W.updateMultisampleRenderTarget(ge),W.updateRenderTargetMipmap(ge)}if(S.setRenderTarget(pe,Se,Ee),S.setClearColor(Xe,Be),He!==void 0)k.viewport=He;S.toneMapping=ke}function so(y,D,G){let k=D.isScene===!0?D.overrideMaterial:null;for(let B=0,ge=y.length;B<ge;B++){let be=y[B],{object:pe,geometry:Se,group:Ee}=be,ke=be.material;if(ke.allowOverride===!0&&k!==null)ke=k;if(pe.layers.test(G.layers))oh(pe,D,G,Se,ke,Ee)}}function oh(y,D,G,k,B,ge){if(y.onBeforeRender(S,D,G,k,B,ge),y.modelViewMatrix.multiplyMatrices(G.matrixWorldInverse,y.matrixWorld),y.normalMatrix.getNormalMatrix(y.modelViewMatrix),B.onBeforeRender(S,D,G,k,y,ge),B.transparent===!0&&B.side===vn&&B.forceSinglePass===!1)B.side=Xt,B.needsUpdate=!0,S.renderBufferDirect(G,D,k,B,y,ge),B.side=Ri,B.needsUpdate=!0,S.renderBufferDirect(G,D,k,B,y,ge),B.side=vn;else S.renderBufferDirect(G,D,k,B,y,ge);y.onAfterRender(S,D,G,k,B,ge)}function oo(y,D,G){if(D.isScene!==!0)D=Gt;let k=P.get(y),B=w.state.lights,ge=w.state.shadowsArray,be=B.state.version,pe=j.getParameters(y,B.state,ge,D,G,w.state.lightProbeGridArray),Se=j.getProgramCacheKey(pe),Ee=k.programs;k.environment=y.isMeshStandardMaterial||y.isMeshLambertMaterial||y.isMeshPhongMaterial?D.environment:null,k.fog=D.fog;let ke=y.isMeshStandardMaterial||y.isMeshLambertMaterial&&!y.envMap||y.isMeshPhongMaterial&&!y.envMap;if(k.envMap=te.get(y.envMap||k.environment,ke),k.envMapRotation=k.environment!==null&&y.envMap===null?D.environmentRotation:y.envMapRotation,Ee===void 0)y.addEventListener("dispose",Fn),Ee=new Map,k.programs=Ee;let He=Ee.get(Se);if(He!==void 0){if(k.currentProgram===He&&k.lightsStateVersion===be)return ch(y,pe),He}else{if(pe.uniforms=j.getUniforms(y),C!==null&&y.isNodeMaterial)C.build(y,G,pe);y.onBeforeCompile(pe,S),He=j.acquireProgram(pe,Se),Ee.set(Se,He),k.uniforms=pe.uniforms}let Ae=k.uniforms;if(!y.isShaderMaterial&&!y.isRawShaderMaterial||y.clipping===!0)Ae.clippingPlanes=re.uniform;if(ch(y,pe),k.needsLights=F0(y),k.lightsStateVersion=be,k.needsLights)Ae.ambientLightColor.value=B.state.ambient,Ae.lightProbe.value=B.state.probe,Ae.directionalLights.value=B.state.directional,Ae.directionalLightShadows.value=B.state.directionalShadow,Ae.spotLights.value=B.state.spot,Ae.spotLightShadows.value=B.state.spotShadow,Ae.rectAreaLights.value=B.state.rectArea,Ae.ltc_1.value=B.state.rectAreaLTC1,Ae.ltc_2.value=B.state.rectAreaLTC2,Ae.pointLights.value=B.state.point,Ae.pointLightShadows.value=B.state.pointShadow,Ae.hemisphereLights.value=B.state.hemi,Ae.directionalShadowMatrix.value=B.state.directionalShadowMatrix,Ae.spotLightMatrix.value=B.state.spotLightMatrix,Ae.spotLightMap.value=B.state.spotLightMap,Ae.pointShadowMatrix.value=B.state.pointShadowMatrix;return k.lightProbeGrid=w.state.lightProbeGridArray.length>0,k.currentProgram=He,k.uniformsList=null,He}function ah(y){if(y.uniformsList===null){let D=y.currentProgram.getUniforms();y.uniformsList=Bs.seqWithValue(D.seq,y.uniforms)}return y.uniformsList}function ch(y,D){let G=P.get(y);G.outputColorSpace=D.outputColorSpace,G.batching=D.batching,G.batchingColor=D.batchingColor,G.instancing=D.instancing,G.instancingColor=D.instancingColor,G.instancingMorph=D.instancingMorph,G.skinning=D.skinning,G.morphTargets=D.morphTargets,G.morphNormals=D.morphNormals,G.morphColors=D.morphColors,G.morphTargetsCount=D.morphTargetsCount,G.numClippingPlanes=D.numClippingPlanes,G.numIntersection=D.numClipIntersection,G.vertexAlphas=D.vertexAlphas,G.vertexTangents=D.vertexTangents,G.toneMapping=D.toneMapping}function D0(y,D){if(y.length===0)return null;if(y.length===1)return y[0].texture!==null?y[0]:null;T.setFromMatrixPosition(D.matrixWorld);for(let G=0,k=y.length;G<k;G++){let B=y[G];if(B.texture!==null&&B.boundingBox.containsPoint(T))return B}return null}function U0(y,D,G,k,B){if(D.isScene!==!0)D=Gt;W.resetTextureUnits();let ge=D.fog,be=k.isMeshStandardMaterial||k.isMeshLambertMaterial||k.isMeshPhongMaterial?D.environment:null,pe=U===null?S.outputColorSpace:U.isXRRenderTarget===!0?U.texture.colorSpace:Ve.workingColorSpace,Se=k.isMeshStandardMaterial||k.isMeshLambertMaterial&&!k.envMap||k.isMeshPhongMaterial&&!k.envMap,Ee=te.get(k.envMap||be,Se),ke=k.vertexColors===!0&&!!G.attributes.color&&G.attributes.color.itemSize===4,He=!!G.attributes.tangent&&(!!k.normalMap||k.anisotropy>0),Ae=!!G.morphAttributes.position,st=!!G.morphAttributes.normal,wt=!!G.morphAttributes.color,bt=Pn;if(k.toneMapped){if(U===null||U.isXRRenderTarget===!0)bt=S.toneMapping}let ct=G.morphAttributes.position||G.morphAttributes.normal||G.morphAttributes.color,Wt=ct!==void 0?ct.length:0,ye=P.get(k),sn=w.state.lights;if(qe===!0){if(je===!0||y!==Q){let ft=y===Q&&k.id===K;re.setState(k,y,ft)}}let Ke=!1;if(k.version===ye.__version){if(ye.needsLights&&ye.lightsStateVersion!==sn.state.version)Ke=!0;else if(ye.outputColorSpace!==pe)Ke=!0;else if(B.isBatchedMesh&&ye.batching===!1)Ke=!0;else if(!B.isBatchedMesh&&ye.batching===!0)Ke=!0;else if(B.isBatchedMesh&&ye.batchingColor===!0&&B.colorTexture===null)Ke=!0;else if(B.isBatchedMesh&&ye.batchingColor===!1&&B.colorTexture!==null)Ke=!0;else if(B.isInstancedMesh&&ye.instancing===!1)Ke=!0;else if(!B.isInstancedMesh&&ye.instancing===!0)Ke=!0;else if(B.isSkinnedMesh&&ye.skinning===!1)Ke=!0;else if(!B.isSkinnedMesh&&ye.skinning===!0)Ke=!0;else if(B.isInstancedMesh&&ye.instancingColor===!0&&B.instanceColor===null)Ke=!0;else if(B.isInstancedMesh&&ye.instancingColor===!1&&B.instanceColor!==null)Ke=!0;else if(B.isInstancedMesh&&ye.instancingMorph===!0&&B.morphTexture===null)Ke=!0;else if(B.isInstancedMesh&&ye.instancingMorph===!1&&B.morphTexture!==null)Ke=!0;else if(ye.envMap!==Ee)Ke=!0;else if(k.fog===!0&&ye.fog!==ge)Ke=!0;else if(ye.numClippingPlanes!==void 0&&(ye.numClippingPlanes!==re.numPlanes||ye.numIntersection!==re.numIntersection))Ke=!0;else if(ye.vertexAlphas!==ke)Ke=!0;else if(ye.vertexTangents!==He)Ke=!0;else if(ye.morphTargets!==Ae)Ke=!0;else if(ye.morphNormals!==st)Ke=!0;else if(ye.morphColors!==wt)Ke=!0;else if(ye.toneMapping!==bt)Ke=!0;else if(ye.morphTargetsCount!==Wt)Ke=!0;else if(!!ye.lightProbeGrid!==w.state.lightProbeGridArray.length>0)Ke=!0}else Ke=!0,ye.__version=k.version;let gn=ye.currentProgram;if(Ke===!0){if(gn=oo(k,D,B),C&&k.isNodeMaterial)C.onUpdateProgram(k,gn,ye)}let zn=!1,_i=!1,vr=!1,lt=gn.getUniforms(),Tt=ye.uniforms;if(M.useProgram(gn.program))zn=!0,_i=!0,vr=!0;if(k.id!==K)K=k.id,_i=!0;if(ye.needsLights){let ft=D0(w.state.lightProbeGridArray,B);if(ye.lightProbeGrid!==ft)ye.lightProbeGrid=ft,_i=!0}if(zn||Q!==y){if(M.buffers.depth.getReversed()&&y.reversedDepth!==!0)y._reversedDepth=!0,y.updateProjectionMatrix();lt.setValue(L,"projectionMatrix",y.projectionMatrix),lt.setValue(L,"viewMatrix",y.matrixWorldInverse);let vi=lt.map.cameraPosition;if(vi!==void 0)vi.setValue(L,pn.setFromMatrixPosition(y.matrixWorld));if(mt.logarithmicDepthBuffer)lt.setValue(L,"logDepthBufFC",2/(Math.log(y.far+1)/Math.LN2));if(k.isMeshPhongMaterial||k.isMeshToonMaterial||k.isMeshLambertMaterial||k.isMeshBasicMaterial||k.isMeshStandardMaterial||k.isShaderMaterial)lt.setValue(L,"isOrthographic",y.isOrthographicCamera===!0);if(Q!==y)Q=y,_i=!0,vr=!0}if(ye.needsLights){if(sn.state.directionalShadowMap.length>0)lt.setValue(L,"directionalShadowMap",sn.state.directionalShadowMap,W);if(sn.state.spotShadowMap.length>0)lt.setValue(L,"spotShadowMap",sn.state.spotShadowMap,W);if(sn.state.pointShadowMap.length>0)lt.setValue(L,"pointShadowMap",sn.state.pointShadowMap,W)}if(B.isSkinnedMesh){lt.setOptional(L,B,"bindMatrix"),lt.setOptional(L,B,"bindMatrixInverse");let ft=B.skeleton;if(ft){if(ft.boneTexture===null)ft.computeBoneTexture();lt.setValue(L,"boneTexture",ft.boneTexture,W)}}if(B.isBatchedMesh){if(lt.setOptional(L,B,"batchingTexture"),lt.setValue(L,"batchingTexture",B._matricesTexture,W),lt.setOptional(L,B,"batchingIdTexture"),lt.setValue(L,"batchingIdTexture",B._indirectTexture,W),lt.setOptional(L,B,"batchingColorTexture"),B._colorsTexture!==null)lt.setValue(L,"batchingColorTexture",B._colorsTexture,W)}let xi=G.morphAttributes;if(xi.position!==void 0||xi.normal!==void 0||xi.color!==void 0)Qe.update(B,G,gn);if(_i||ye.receiveShadow!==B.receiveShadow)ye.receiveShadow=B.receiveShadow,lt.setValue(L,"receiveShadow",B.receiveShadow);if((k.isMeshStandardMaterial||k.isMeshLambertMaterial||k.isMeshPhongMaterial)&&k.envMap===null&&D.environment!==null)Tt.envMapIntensity.value=D.environmentIntensity;if(Tt.dfgLUT!==void 0)Tt.dfgLUT.value=EM();if(_i){if(lt.setValue(L,"toneMappingExposure",S.toneMappingExposure),ye.needsLights)O0(Tt,vr);if(ge&&k.fog===!0)xe.refreshFogUniforms(Tt,ge);if(xe.refreshMaterialUniforms(Tt,k,fe,ne,w.state.transmissionRenderTarget[y.id]),ye.needsLights&&ye.lightProbeGrid){let ft=ye.lightProbeGrid;Tt.probesSH.value=ft.texture,Tt.probesMin.value.copy(ft.boundingBox.min),Tt.probesMax.value.copy(ft.boundingBox.max),Tt.probesResolution.value.copy(ft.resolution)}Bs.upload(L,ah(ye),Tt,W)}if(k.isShaderMaterial&&k.uniformsNeedUpdate===!0)Bs.upload(L,ah(ye),Tt,W),k.uniformsNeedUpdate=!1;if(k.isSpriteMaterial)lt.setValue(L,"center",B.center);if(lt.setValue(L,"modelViewMatrix",B.modelViewMatrix),lt.setValue(L,"normalMatrix",B.normalMatrix),lt.setValue(L,"modelMatrix",B.matrixWorld),k.uniformsGroups!==void 0){let ft=k.uniformsGroups;for(let vi=0,yr=ft.length;vi<yr;vi++){let lh=ft[vi];ve.update(lh,gn),ve.bind(lh,gn)}}return gn}function O0(y,D){y.ambientLightColor.needsUpdate=D,y.lightProbe.needsUpdate=D,y.directionalLights.needsUpdate=D,y.directionalLightShadows.needsUpdate=D,y.pointLights.needsUpdate=D,y.pointLightShadows.needsUpdate=D,y.spotLights.needsUpdate=D,y.spotLightShadows.needsUpdate=D,y.rectAreaLights.needsUpdate=D,y.hemisphereLights.needsUpdate=D}function F0(y){return y.isMeshLambertMaterial||y.isMeshToonMaterial||y.isMeshPhongMaterial||y.isMeshStandardMaterial||y.isShadowMaterial||y.isShaderMaterial&&y.lights===!0}if(this.getActiveCubeFace=function(){return H},this.getActiveMipmapLevel=function(){return V},this.getRenderTarget=function(){return U},this.setRenderTargetTextures=function(y,D,G){let k=P.get(y);if(k.__autoAllocateDepthBuffer=y.resolveDepthBuffer===!1,k.__autoAllocateDepthBuffer===!1)k.__useRenderToTexture=!1;P.get(y.texture).__webglTexture=D,P.get(y.depthTexture).__webglTexture=k.__autoAllocateDepthBuffer?void 0:G,k.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(y,D){let G=P.get(y);G.__webglFramebuffer=D,G.__useDefaultFramebuffer=D===void 0},this.setRenderTarget=function(y,D=0,G=0){U=y,H=D,V=G;let k=null,B=!1,ge=!1;if(y){let pe=P.get(y);if(pe.__useDefaultFramebuffer!==void 0){M.bindFramebuffer(L.FRAMEBUFFER,pe.__webglFramebuffer),se.copy(y.viewport),me.copy(y.scissor),_e=y.scissorTest,M.viewport(se),M.scissor(me),M.setScissorTest(_e),K=-1;return}else if(pe.__webglFramebuffer===void 0)W.setupRenderTarget(y);else if(pe.__hasExternalTextures)W.rebindTextures(y,P.get(y.texture).__webglTexture,P.get(y.depthTexture).__webglTexture);else if(y.depthBuffer){let ke=y.depthTexture;if(pe.__boundDepthTexture!==ke){if(ke!==null&&P.has(ke)&&(y.width!==ke.image.width||y.height!==ke.image.height))throw Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");W.setupDepthRenderbuffer(y)}}let Se=y.texture;if(Se.isData3DTexture||Se.isDataArrayTexture||Se.isCompressedArrayTexture)ge=!0;let Ee=P.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget){if(Array.isArray(Ee[D]))k=Ee[D][G];else k=Ee[D];B=!0}else if(y.samples>0&&W.useMultisampledRTT(y)===!1)k=P.get(y).__webglMultisampledFramebuffer;else if(Array.isArray(Ee))k=Ee[G];else k=Ee;se.copy(y.viewport),me.copy(y.scissor),_e=y.scissorTest}else se.copy($e).multiplyScalar(fe).floor(),me.copy(Ue).multiplyScalar(fe).floor(),_e=ze;if(G!==0)k=z;if(M.bindFramebuffer(L.FRAMEBUFFER,k))M.drawBuffers(y,k);if(M.viewport(se),M.scissor(me),M.setScissorTest(_e),B){let pe=P.get(y.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+D,pe.__webglTexture,G)}else if(ge){let pe=D;for(let Se=0;Se<y.textures.length;Se++){let Ee=P.get(y.textures[Se]);L.framebufferTextureLayer(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0+Se,Ee.__webglTexture,G,pe)}}else if(y!==null&&G!==0){let pe=P.get(y.texture);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,pe.__webglTexture,G)}K=-1},this.readRenderTargetPixels=function(y,D,G,k,B,ge,be,pe=0){if(!(y&&y.isWebGLRenderTarget)){Ne("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Se=P.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&be!==void 0)Se=Se[be];if(Se){M.bindFramebuffer(L.FRAMEBUFFER,Se);try{let Ee=y.textures[pe],{format:ke,type:He}=Ee;if(y.textures.length>1)L.readBuffer(L.COLOR_ATTACHMENT0+pe);if(!mt.textureFormatReadable(ke)){Ne("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!mt.textureTypeReadable(He)){Ne("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(D>=0&&D<=y.width-k&&(G>=0&&G<=y.height-B))L.readPixels(D,G,k,B,Y.convert(ke),Y.convert(He),ge)}finally{let Ee=U!==null?P.get(U).__webglFramebuffer:null;M.bindFramebuffer(L.FRAMEBUFFER,Ee)}}},this.readRenderTargetPixelsAsync=async function(y,D,G,k,B,ge,be,pe=0){if(!(y&&y.isWebGLRenderTarget))throw Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Se=P.get(y).__webglFramebuffer;if(y.isWebGLCubeRenderTarget&&be!==void 0)Se=Se[be];if(Se)if(D>=0&&D<=y.width-k&&(G>=0&&G<=y.height-B)){M.bindFramebuffer(L.FRAMEBUFFER,Se);let Ee=y.textures[pe],{format:ke,type:He}=Ee;if(y.textures.length>1)L.readBuffer(L.COLOR_ATTACHMENT0+pe);if(!mt.textureFormatReadable(ke))throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!mt.textureTypeReadable(He))throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Ae=L.createBuffer();L.bindBuffer(L.PIXEL_PACK_BUFFER,Ae),L.bufferData(L.PIXEL_PACK_BUFFER,ge.byteLength,L.STREAM_READ),L.readPixels(D,G,k,B,Y.convert(ke),Y.convert(He),0);let st=U!==null?P.get(U).__webglFramebuffer:null;M.bindFramebuffer(L.FRAMEBUFFER,st);let wt=L.fenceSync(L.SYNC_GPU_COMMANDS_COMPLETE,0);return L.flush(),await Vf(L,wt,4),L.bindBuffer(L.PIXEL_PACK_BUFFER,Ae),L.getBufferSubData(L.PIXEL_PACK_BUFFER,0,ge),L.deleteBuffer(Ae),L.deleteSync(wt),ge}else throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(y,D=null,G=0){let k=Math.pow(2,-G),B=Math.floor(y.image.width*k),ge=Math.floor(y.image.height*k),be=D!==null?D.x:0,pe=D!==null?D.y:0;W.setTexture2D(y,0),L.copyTexSubImage2D(L.TEXTURE_2D,G,0,0,be,pe,B,ge),M.unbindTexture()},this.copyTextureToTexture=function(y,D,G=null,k=null,B=0,ge=0){let be,pe,Se,Ee,ke,He,Ae,st,wt,bt=y.isCompressedTexture?y.mipmaps[ge]:y.image;if(G!==null)be=G.max.x-G.min.x,pe=G.max.y-G.min.y,Se=G.isBox3?G.max.z-G.min.z:1,Ee=G.min.x,ke=G.min.y,He=G.isBox3?G.min.z:0;else{let Tt=Math.pow(2,-B);if(be=Math.floor(bt.width*Tt),pe=Math.floor(bt.height*Tt),y.isDataArrayTexture)Se=bt.depth;else if(y.isData3DTexture)Se=Math.floor(bt.depth*Tt);else Se=1;Ee=0,ke=0,He=0}if(k!==null)Ae=k.x,st=k.y,wt=k.z;else Ae=0,st=0,wt=0;let ct=Y.convert(D.format),Wt=Y.convert(D.type),ye;if(D.isData3DTexture)W.setTexture3D(D,0),ye=L.TEXTURE_3D;else if(D.isDataArrayTexture||D.isCompressedArrayTexture)W.setTexture2DArray(D,0),ye=L.TEXTURE_2D_ARRAY;else W.setTexture2D(D,0),ye=L.TEXTURE_2D;M.activeTexture(L.TEXTURE0),M.pixelStorei(L.UNPACK_FLIP_Y_WEBGL,D.flipY),M.pixelStorei(L.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),M.pixelStorei(L.UNPACK_ALIGNMENT,D.unpackAlignment);let sn=M.getParameter(L.UNPACK_ROW_LENGTH),Ke=M.getParameter(L.UNPACK_IMAGE_HEIGHT),gn=M.getParameter(L.UNPACK_SKIP_PIXELS),zn=M.getParameter(L.UNPACK_SKIP_ROWS),_i=M.getParameter(L.UNPACK_SKIP_IMAGES);M.pixelStorei(L.UNPACK_ROW_LENGTH,bt.width),M.pixelStorei(L.UNPACK_IMAGE_HEIGHT,bt.height),M.pixelStorei(L.UNPACK_SKIP_PIXELS,Ee),M.pixelStorei(L.UNPACK_SKIP_ROWS,ke),M.pixelStorei(L.UNPACK_SKIP_IMAGES,He);let vr=y.isDataArrayTexture||y.isData3DTexture,lt=D.isDataArrayTexture||D.isData3DTexture;if(y.isDepthTexture){let Tt=P.get(y),xi=P.get(D),ft=P.get(Tt.__renderTarget),vi=P.get(xi.__renderTarget);M.bindFramebuffer(L.READ_FRAMEBUFFER,ft.__webglFramebuffer),M.bindFramebuffer(L.DRAW_FRAMEBUFFER,vi.__webglFramebuffer);for(let yr=0;yr<Se;yr++){if(vr)L.framebufferTextureLayer(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,P.get(y).__webglTexture,B,He+yr),L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,P.get(D).__webglTexture,ge,wt+yr);L.blitFramebuffer(Ee,ke,be,pe,Ae,st,be,pe,L.DEPTH_BUFFER_BIT,L.NEAREST)}M.bindFramebuffer(L.READ_FRAMEBUFFER,null),M.bindFramebuffer(L.DRAW_FRAMEBUFFER,null)}else if(B!==0||y.isRenderTargetTexture||P.has(y)){let Tt=P.get(y),xi=P.get(D);M.bindFramebuffer(L.READ_FRAMEBUFFER,J),M.bindFramebuffer(L.DRAW_FRAMEBUFFER,O);for(let ft=0;ft<Se;ft++){if(vr)L.framebufferTextureLayer(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,Tt.__webglTexture,B,He+ft);else L.framebufferTexture2D(L.READ_FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,Tt.__webglTexture,B);if(lt)L.framebufferTextureLayer(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,xi.__webglTexture,ge,wt+ft);else L.framebufferTexture2D(L.DRAW_FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,xi.__webglTexture,ge);if(B!==0)L.blitFramebuffer(Ee,ke,be,pe,Ae,st,be,pe,L.COLOR_BUFFER_BIT,L.NEAREST);else if(lt)L.copyTexSubImage3D(ye,ge,Ae,st,wt+ft,Ee,ke,be,pe);else L.copyTexSubImage2D(ye,ge,Ae,st,Ee,ke,be,pe)}M.bindFramebuffer(L.READ_FRAMEBUFFER,null),M.bindFramebuffer(L.DRAW_FRAMEBUFFER,null)}else if(lt)if(y.isDataTexture||y.isData3DTexture)L.texSubImage3D(ye,ge,Ae,st,wt,be,pe,Se,ct,Wt,bt.data);else if(D.isCompressedArrayTexture)L.compressedTexSubImage3D(ye,ge,Ae,st,wt,be,pe,Se,ct,bt.data);else L.texSubImage3D(ye,ge,Ae,st,wt,be,pe,Se,ct,Wt,bt);else if(y.isDataTexture)L.texSubImage2D(L.TEXTURE_2D,ge,Ae,st,be,pe,ct,Wt,bt.data);else if(y.isCompressedTexture)L.compressedTexSubImage2D(L.TEXTURE_2D,ge,Ae,st,bt.width,bt.height,ct,bt.data);else L.texSubImage2D(L.TEXTURE_2D,ge,Ae,st,be,pe,ct,Wt,bt);if(M.pixelStorei(L.UNPACK_ROW_LENGTH,sn),M.pixelStorei(L.UNPACK_IMAGE_HEIGHT,Ke),M.pixelStorei(L.UNPACK_SKIP_PIXELS,gn),M.pixelStorei(L.UNPACK_SKIP_ROWS,zn),M.pixelStorei(L.UNPACK_SKIP_IMAGES,_i),ge===0&&D.generateMipmaps)L.generateMipmap(ye);M.unbindTexture()},this.initRenderTarget=function(y){if(P.get(y).__webglFramebuffer===void 0)W.setupRenderTarget(y)},this.initTexture=function(y){if(y.isCubeTexture)W.setTextureCube(y,0);else if(y.isData3DTexture)W.setTexture3D(y,0);else if(y.isDataArrayTexture||y.isCompressedArrayTexture)W.setTexture2DArray(y,0);else W.setTexture2D(y,0);M.unbindTexture()},this.resetState=function(){H=0,V=0,U=null,M.reset(),ae.reset()},typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return xl}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=Ve._getDrawingBufferColorSpace(e),t.unpackColorSpace=Ve._getUnpackColorSpace()}}function Jl(e,t){if(t===pl)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(t===Zr||t===Ss){let n=e.getIndex();if(n===null){let o=[],a=e.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)o.push(c);e.setIndex(o),n=e.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),e}let i=n.count-2,r=[];if(t===Zr)for(let o=1;o<=i;o++)r.push(n.getX(0)),r.push(n.getX(o)),r.push(n.getX(o+1));else for(let o=0;o<i;o++)if(o%2===0)r.push(n.getX(o)),r.push(n.getX(o+1)),r.push(n.getX(o+2));else r.push(n.getX(o+2)),r.push(n.getX(o+1)),r.push(n.getX(o));if(r.length/3!==i)console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let s=e.clone();return s.setIndex(r),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}function Ud(e){let t=new Map,n=new Map,i=e.clone();return Od(e,i,function(r,s){t.set(s,r),n.set(r,s)}),i.traverse(function(r){if(!r.isSkinnedMesh)return;let s=r,o=t.get(r),a=o.skeleton.bones;s.skeleton=o.skeleton.clone(),s.bindMatrix.copy(o.bindMatrix),s.skeleton.bones=a.map(function(c){return n.get(c)}),s.bind(s.skeleton,s.bindMatrix)}),i}function Od(e,t,n){n(e,t);for(let i=0;i<e.children.length;i++)Od(e.children[i],t.children[i],n)}class ru extends pi{constructor(e){super(e);this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Wd(t)}),this.register(function(t){return new $d(t)}),this.register(function(t){return new ep(t)}),this.register(function(t){return new tp(t)}),this.register(function(t){return new np(t)}),this.register(function(t){return new Xd(t)}),this.register(function(t){return new qd(t)}),this.register(function(t){return new Yd(t)}),this.register(function(t){return new jd(t)}),this.register(function(t){return new Vd(t)}),this.register(function(t){return new Jd(t)}),this.register(function(t){return new Zd(t)}),this.register(function(t){return new Qd(t)}),this.register(function(t){return new Kd(t)}),this.register(function(t){return new Gd(t)}),this.register(function(t){return new tu(t,Ze.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new tu(t,Ze.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new ip(t)})}load(e,t,n,i){let r=this,s;if(this.resourcePath!=="")s=this.resourcePath;else if(this.path!==""){let c=ki.extractUrlBase(e);s=ki.resolveURL(c,this.path)}else s=ki.extractUrlBase(e);this.manager.itemStart(e);let o=function(c){if(i)i(c);else console.error(c);r.manager.itemError(e),r.manager.itemEnd(e)},a=new Us(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(c){try{r.parse(c,s,function(l){t(l),r.manager.itemEnd(e)},o)}catch(l){o(l)}},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){if(this.pluginCallbacks.indexOf(e)===-1)this.pluginCallbacks.push(e);return this}unregister(e){if(this.pluginCallbacks.indexOf(e)!==-1)this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1);return this}parse(e,t,n,i){let r,s={},o={},a=new TextDecoder;if(typeof e==="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(a.decode(new Uint8Array(e,0,4))===rp){try{s[Ze.KHR_BINARY_GLTF]=new sp(e)}catch(u){if(i)i(u);return}r=JSON.parse(s[Ze.KHR_BINARY_GLTF].content)}else r=JSON.parse(a.decode(e));else r=e;if(r.asset===void 0||r.asset.version[0]<2){if(i)i(Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let c=new up(r,{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 l=0;l<this.pluginCallbacks.length;l++){let u=this.pluginCallbacks[l](c);if(!u.name)console.error("THREE.GLTFLoader: Invalid plugin found: missing name");o[u.name]=u,s[u.name]=!0}if(r.extensionsUsed)for(let l=0;l<r.extensionsUsed.length;++l){let u=r.extensionsUsed[l],f=r.extensionsRequired||[];switch(u){case Ze.KHR_MATERIALS_UNLIT:s[u]=new Hd;break;case Ze.KHR_DRACO_MESH_COMPRESSION:s[u]=new op(r,this.dracoLoader);break;case Ze.KHR_TEXTURE_TRANSFORM:s[u]=new ap;break;case Ze.KHR_MESH_QUANTIZATION:s[u]=new cp;break;default:if(f.indexOf(u)>=0&&o[u]===void 0)console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}c.setExtensions(s),c.setPlugins(o),c.parse(n,i)}parseAsync(e,t){let n=this;return new Promise(function(i,r){n.parse(e,t,i,r)})}}function RM(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}function Et(e,t,n){let i=e.json.materials[t];if(i.extensions&&i.extensions[n])return i.extensions[n];return null}var Ze={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"};class Gd{constructor(e){this.parser=e,this.name=Ze.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){let r=t[n];if(r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0)e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n="light:"+e,i=t.cache.get(n);if(i)return i;let r=t.json,a=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e],c,l=new Le(16777215);if(a.color!==void 0)l.setRGB(a.color[0],a.color[1],a.color[2],cn);let u=a.range!==void 0?a.range:0;switch(a.type){case"directional":c=new Qr(l),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new Kr(l),c.distance=u;break;case"spot":c=new ha(l),c.distance=u,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,c.angle=a.spot.outerConeAngle,c.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}if(c.position.set(0,0,0),Yn(c,a),a.intensity!==void 0)c.intensity=a.intensity;return c.name=t.createUniqueName(a.name||"light_"+e),i=Promise.resolve(c),t.cache.add(n,i),i}getDependency(e,t){if(e!=="light")return;return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],o=(r.extensions&&r.extensions[this.name]||{}).light;if(o===void 0)return null;return this._loadLight(o).then(function(a){return n._getNodeRef(t.cache,o,a)})}}class Hd{constructor(){this.name=Ze.KHR_MATERIALS_UNLIT}getMaterialType(){return Zn}extendParams(e,t,n){let i=[];e.color=new Le(1,1,1),e.opacity=1;let r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){let s=r.baseColorFactor;e.color.setRGB(s[0],s[1],s[2],cn),e.opacity=s[3]}if(r.baseColorTexture!==void 0)i.push(n.assignTexture(e,"map",r.baseColorTexture,Pi))}return Promise.all(i)}}class Vd{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();if(n.emissiveStrength!==void 0)t.emissiveIntensity=n.emissiveStrength;return Promise.resolve()}}class Wd{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(n.clearcoatFactor!==void 0)t.clearcoat=n.clearcoatFactor;if(n.clearcoatTexture!==void 0)i.push(this.parser.assignTexture(t,"clearcoatMap",n.clearcoatTexture));if(n.clearcoatRoughnessFactor!==void 0)t.clearcoatRoughness=n.clearcoatRoughnessFactor;if(n.clearcoatRoughnessTexture!==void 0)i.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",n.clearcoatRoughnessTexture));if(n.clearcoatNormalTexture!==void 0){if(i.push(this.parser.assignTexture(t,"clearcoatNormalMap",n.clearcoatNormalTexture)),n.clearcoatNormalTexture.scale!==void 0){let r=n.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Pe(r,r)}}return Promise.all(i)}}class $d{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_DISPERSION}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();return t.dispersion=n.dispersion!==void 0?n.dispersion:0,Promise.resolve()}}class Zd{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(n.iridescenceFactor!==void 0)t.iridescence=n.iridescenceFactor;if(n.iridescenceTexture!==void 0)i.push(this.parser.assignTexture(t,"iridescenceMap",n.iridescenceTexture));if(n.iridescenceIor!==void 0)t.iridescenceIOR=n.iridescenceIor;if(t.iridescenceThicknessRange===void 0)t.iridescenceThicknessRange=[100,400];if(n.iridescenceThicknessMinimum!==void 0)t.iridescenceThicknessRange[0]=n.iridescenceThicknessMinimum;if(n.iridescenceThicknessMaximum!==void 0)t.iridescenceThicknessRange[1]=n.iridescenceThicknessMaximum;if(n.iridescenceThicknessTexture!==void 0)i.push(this.parser.assignTexture(t,"iridescenceThicknessMap",n.iridescenceThicknessTexture));return Promise.all(i)}}class Xd{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_SHEEN}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.sheenColor=new Le(0,0,0),t.sheenRoughness=0,t.sheen=1,n.sheenColorFactor!==void 0){let r=n.sheenColorFactor;t.sheenColor.setRGB(r[0],r[1],r[2],cn)}if(n.sheenRoughnessFactor!==void 0)t.sheenRoughness=n.sheenRoughnessFactor;if(n.sheenColorTexture!==void 0)i.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,Pi));if(n.sheenRoughnessTexture!==void 0)i.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture));return Promise.all(i)}}class qd{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(n.transmissionFactor!==void 0)t.transmission=n.transmissionFactor;if(n.transmissionTexture!==void 0)i.push(this.parser.assignTexture(t,"transmissionMap",n.transmissionTexture));return Promise.all(i)}}class Yd{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_VOLUME}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.thickness=n.thicknessFactor!==void 0?n.thicknessFactor:0,n.thicknessTexture!==void 0)i.push(this.parser.assignTexture(t,"thicknessMap",n.thicknessTexture));t.attenuationDistance=n.attenuationDistance||1/0;let r=n.attenuationColor||[1,1,1];return t.attenuationColor=new Le().setRGB(r[0],r[1],r[2],cn),Promise.all(i)}}class jd{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_IOR}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();if(t.ior=n.ior!==void 0?n.ior:1.5,t.ior===0)t.ior=1000;return Promise.resolve()}}class Jd{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_SPECULAR}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.specularIntensity=n.specularFactor!==void 0?n.specularFactor:1,n.specularTexture!==void 0)i.push(this.parser.assignTexture(t,"specularIntensityMap",n.specularTexture));let r=n.specularColorFactor||[1,1,1];if(t.specularColor=new Le().setRGB(r[0],r[1],r[2],cn),n.specularColorTexture!==void 0)i.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,Pi));return Promise.all(i)}}class Kd{constructor(e){this.parser=e,this.name=Ze.EXT_MATERIALS_BUMP}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.bumpScale=n.bumpFactor!==void 0?n.bumpFactor:1,n.bumpTexture!==void 0)i.push(this.parser.assignTexture(t,"bumpMap",n.bumpTexture));return Promise.all(i)}}class Qd{constructor(e){this.parser=e,this.name=Ze.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return Et(this.parser,e,this.name)!==null?un:null}extendMaterialParams(e,t){let n=Et(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(n.anisotropyStrength!==void 0)t.anisotropy=n.anisotropyStrength;if(n.anisotropyRotation!==void 0)t.anisotropyRotation=n.anisotropyRotation;if(n.anisotropyTexture!==void 0)i.push(this.parser.assignTexture(t,"anisotropyMap",n.anisotropyTexture));return Promise.all(i)}}class ep{constructor(e){this.parser=e,this.name=Ze.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;let r=i.extensions[this.name],s=t.options.ktx2Loader;if(!s)if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");else return null;return t.loadTextureImage(e,r.source,s)}}class tp{constructor(e){this.parser=e,this.name=Ze.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],o=i.images[s.source],a=n.textureLoader;if(o.uri){let c=n.options.manager.getHandler(o.uri);if(c!==null)a=c}return n.loadTextureImage(e,s.source,a)}}class np{constructor(e){this.parser=e,this.name=Ze.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],o=i.images[s.source],a=n.textureLoader;if(o.uri){let c=n.options.manager.getHandler(o.uri);if(c!==null)a=c}return n.loadTextureImage(e,s.source,a)}}class tu{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 i=n.extensions[this.name],r=this.parser.getDependency("buffer",i.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.supported)if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");else return null;return r.then(function(o){let a=i.byteOffset||0,c=i.byteLength||0,{count:l,byteStride:u}=i,f=new Uint8Array(o,a,c);if(s.decodeGltfBufferAsync)return s.decodeGltfBufferAsync(l,u,f,i.mode,i.filter).then(function(h){return h.buffer});else return s.ready.then(function(){let h=new ArrayBuffer(l*u);return s.decodeGltfBuffer(new Uint8Array(h),l,u,f,i.mode,i.filter),h})})}else return null}}class ip{constructor(e){this.name=Ze.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 i=t.meshes[n.mesh];for(let c of i.primitives)if(c.mode!==Sn.TRIANGLES&&c.mode!==Sn.TRIANGLE_STRIP&&c.mode!==Sn.TRIANGLE_FAN&&c.mode!==void 0)return null;let s=n.extensions[this.name].attributes,o=[],a={};for(let c in s)o.push(this.parser.getDependency("accessor",s[c]).then((l)=>(a[c]=l,a[c])));if(o.length<1)return null;return o.push(this.parser.createNodeMesh(e)),Promise.all(o).then((c)=>{let l=c.pop(),u=l.isGroup?l.children:[l],f=c[0].count,h=[];for(let d of u){let g=new Fe,b=new N,p=new zt,m=new N(1,1,1),A=new Yr(d.geometry,d.material,f);for(let T=0;T<f;T++){if(a.TRANSLATION)b.fromBufferAttribute(a.TRANSLATION,T);if(a.ROTATION)p.fromBufferAttribute(a.ROTATION,T);if(a.SCALE)m.fromBufferAttribute(a.SCALE,T);A.setMatrixAt(T,g.compose(b,p,m))}for(let T in a)if(T==="_COLOR_0"){let v=a[T];A.instanceColor=new tr(v.array,v.itemSize,v.normalized)}else if(T!=="TRANSLATION"&&T!=="ROTATION"&&T!=="SCALE")d.geometry.setAttribute(T,a[T]);ot.prototype.copy.call(A,d),this.parser.assignFinalMaterial(A),h.push(A)}if(l.isGroup)return l.clear(),l.add(...h),l;return h[0]})}}var rp="glTF",Hs=12,Fd={JSON:1313821514,BIN:5130562};class sp{constructor(e){this.name=Ze.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,Hs),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!==rp)throw Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");else if(this.header.version<2)throw Error("THREE.GLTFLoader: Legacy binary file detected.");let i=this.header.length-Hs,r=new DataView(e,Hs),s=0;while(s<i){let o=r.getUint32(s,!0);s+=4;let a=r.getUint32(s,!0);if(s+=4,a===Fd.JSON){let c=new Uint8Array(e,Hs+s,o);this.content=n.decode(c)}else if(a===Fd.BIN){let c=Hs+s;this.body=e.slice(c,c+o)}s+=o}if(this.content===null)throw Error("THREE.GLTFLoader: JSON content not found.")}}class op{constructor(e,t){if(!t)throw Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Ze.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,i=this.dracoLoader,r=e.extensions[this.name].bufferView,s=e.extensions[this.name].attributes,o={},a={},c={};for(let l in s){let u=nu[l]||l.toLowerCase();o[u]=s[l]}for(let l in e.attributes){let u=nu[l]||l.toLowerCase();if(s[l]!==void 0){let f=n.accessors[e.attributes[l]],h=ns[f.componentType];c[u]=h.name,a[u]=f.normalized===!0}}return t.getDependency("bufferView",r).then(function(l){return new Promise(function(u,f){i.decodeDracoFile(l,function(h){for(let d in h.attributes){let g=h.attributes[d],b=a[d];if(b!==void 0)g.normalized=b}u(h)},o,c,cn,f)})})}}class ap{constructor(){this.name=Ze.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){if((t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0)return e;if(e=e.clone(),t.texCoord!==void 0)e.channel=t.texCoord;if(t.offset!==void 0)e.offset.fromArray(t.offset);if(t.rotation!==void 0)e.rotation=t.rotation;if(t.scale!==void 0)e.repeat.fromArray(t.scale);return e.needsUpdate=!0,e}}class cp{constructor(){this.name=Ze.KHR_MESH_QUANTIZATION}}class su extends di{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,r=e*i*3+i;for(let s=0;s!==i;s++)t[s]=n[r+s];return t}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,o=this.valueSize,a=o*2,c=o*3,l=i-t,u=(n-t)/l,f=u*u,h=f*u,d=e*c,g=d-c,b=-2*h+3*f,p=h-f,m=1-b,A=p-f+u;for(let T=0;T!==o;T++){let v=s[g+T+o],w=s[g+T+a]*l,E=s[d+T+o],R=s[d+T]*l;r[T]=m*v+A*w+b*E+p*R}return r}}var CM=new zt;class lp extends su{interpolate_(e,t,n,i){let r=super.interpolate_(e,t,n,i);return CM.fromArray(r).normalize().toArray(r),r}}var Sn={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},ns={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},zd={9728:In,9729:kt,9984:ko,9985:Wr,9986:ir,9987:Wn},kd={33071:Vr,33648:zo,10497:Hr},Kl={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},nu={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"},Gi={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},PM={CUBICSPLINE:void 0,LINEAR:Zo,STEP:dl},Ql={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function IM(e){if(e.DefaultMaterial===void 0)e.DefaultMaterial=new fi({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Ri});return e.DefaultMaterial}function fr(e,t,n){for(let i in n.extensions)if(e[i]===void 0)t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[i]=n.extensions[i]}function Yn(e,t){if(t.extras!==void 0)if(typeof t.extras==="object")Object.assign(e.userData,t.extras);else console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras)}function LM(e,t,n){let i=!1,r=!1,s=!1;for(let l=0,u=t.length;l<u;l++){let f=t[l];if(f.POSITION!==void 0)i=!0;if(f.NORMAL!==void 0)r=!0;if(f.COLOR_0!==void 0)s=!0;if(i&&r&&s)break}if(!i&&!r&&!s)return Promise.resolve(e);let o=[],a=[],c=[];for(let l=0,u=t.length;l<u;l++){let f=t[l];if(i){let h=f.POSITION!==void 0?n.getDependency("accessor",f.POSITION):e.attributes.position;o.push(h)}if(r){let h=f.NORMAL!==void 0?n.getDependency("accessor",f.NORMAL):e.attributes.normal;a.push(h)}if(s){let h=f.COLOR_0!==void 0?n.getDependency("accessor",f.COLOR_0):e.attributes.color;c.push(h)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c)]).then(function(l){let u=l[0],f=l[1],h=l[2];if(i)e.morphAttributes.position=u;if(r)e.morphAttributes.normal=f;if(s)e.morphAttributes.color=h;return e.morphTargetsRelative=!0,e})}function NM(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let n=0,i=t.weights.length;n<i;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){let n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let i=0,r=n.length;i<r;i++)e.morphTargetDictionary[n[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function DM(e){let t,n=e.extensions&&e.extensions[Ze.KHR_DRACO_MESH_COMPRESSION];if(n)t="draco:"+n.bufferView+":"+n.indices+":"+eu(n.attributes);else t=e.indices+":"+eu(e.attributes)+":"+e.mode;if(e.targets!==void 0)for(let i=0,r=e.targets.length;i<r;i++)t+=":"+eu(e.targets[i]);return t}function eu(e){let t="",n=Object.keys(e).sort();for(let i=0,r=n.length;i<r;i++)t+=n[i]+":"+e[n[i]]+";";return t}function iu(e){switch(e){case Int8Array:return 0.007874015748031496;case Uint8Array:return 0.00392156862745098;case Int16Array:return 0.00003051850947599719;case Uint16Array:return 0.000015259021896696422;default:throw Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function UM(e){if(e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0)return"image/jpeg";if(e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0)return"image/webp";if(e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0)return"image/ktx2";return"image/png"}var OM=new Fe;class up{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new RM,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,i=-1,r=!1,s=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){let o=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(o)===!0;let a=o.match(/Version\/(\d+)/);i=n&&a?parseInt(a[1],10):-1,r=o.indexOf("Firefox")>-1,s=r?o.match(/Firefox\/([0-9]+)\./)[1]:-1}if(typeof createImageBitmap>"u"||n&&i<17||r&&s<98)this.textureLoader=new aa(this.options.manager);else this.textureLoader=new fa(this.options.manager);if(this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Us(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,i=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(s){let o={scene:s[0][i.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:i.asset,parser:n,userData:{}};return fr(r,o,i),Yn(o,i),Promise.all(n._invokeAll(function(a){return a.afterRoot&&a.afterRoot(o)})).then(function(){for(let a of o.scenes)a.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,r=t.length;i<r;i++){let s=t[i].joints;for(let o=0,a=s.length;o<a;o++)e[s[o]].isBone=!0}for(let i=0,r=e.length;i<r;i++){let s=e[i];if(s.mesh!==void 0){if(this._addNodeRef(this.meshCache,s.mesh),s.skin!==void 0)n[s.mesh].isSkinnedMesh=!0}if(s.camera!==void 0)this._addNodeRef(this.cameraCache,s.camera)}}_addNodeRef(e,t){if(t===void 0)return;if(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 i=n.clone(),r=(s,o)=>{let a=this.associations.get(s);if(a!=null)this.associations.set(o,a);for(let[c,l]of s.children.entries())r(l,o.children[c])};return r(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let i=e(t[n]);if(i)return i}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let i=0;i<t.length;i++){let r=e(t[i]);if(r)n.push(r)}return n}getDependency(e,t){let n=e+":"+t,i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(r){return r.loadNode&&r.loadNode(t)});break;case"mesh":i=this._invokeOne(function(r){return r.loadMesh&&r.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(r){return r.loadBufferView&&r.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(r){return r.loadMaterial&&r.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(r){return r.loadTexture&&r.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(r){return r.loadAnimation&&r.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(r){return r!=this&&r.getDependency&&r.getDependency(e,t)}),!i)throw Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(r,s){return n.getDependency(e,s)})),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 Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Ze.KHR_BINARY_GLTF].body);let i=this.options;return new Promise(function(r,s){n.load(ki.resolveURL(t.uri,i.path),r,void 0,function(){s(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 i=t.byteLength||0,r=t.byteOffset||0;return n.slice(r,r+i)})}loadAccessor(e){let t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){let s=Kl[i.type],o=ns[i.componentType],a=i.normalized===!0,c=new o(i.count*s);return Promise.resolve(new It(c,s,a))}let r=[];if(i.bufferView!==void 0)r.push(this.getDependency("bufferView",i.bufferView));else r.push(null);if(i.sparse!==void 0)r.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",i.sparse.values.bufferView));return Promise.all(r).then(function(s){let o=s[0],a=Kl[i.type],c=ns[i.componentType],l=c.BYTES_PER_ELEMENT,u=l*a,f=i.byteOffset||0,h=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,d=i.normalized===!0,g,b;if(h&&h!==u){let p=Math.floor(f/h),m="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+p+":"+i.count,A=t.cache.get(m);if(!A)g=new c(o,p*h,i.count*h/l),A=new Es(g,h/l),t.cache.add(m,A);b=new qr(A,a,f%h/l,d)}else{if(o===null)g=new c(i.count*a);else g=new c(o,f,i.count*a);b=new It(g,a,d)}if(i.sparse!==void 0){let p=Kl.SCALAR,m=ns[i.sparse.indices.componentType],A=i.sparse.indices.byteOffset||0,T=i.sparse.values.byteOffset||0,v=new m(s[1],A,i.sparse.count*p),w=new c(s[2],T,i.sparse.count*a);if(o!==null)b=new It(b.array.slice(),b.itemSize,b.normalized);b.normalized=!1;for(let E=0,R=v.length;E<R;E++){let _=v[E];if(b.setX(_,w[E*a]),a>=2)b.setY(_,w[E*a+1]);if(a>=3)b.setZ(_,w[E*a+2]);if(a>=4)b.setW(_,w[E*a+3]);if(a>=5)throw Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}b.normalized=d}return b})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,s=t.images[r],o=this.textureLoader;if(s.uri){let a=n.manager.getHandler(s.uri);if(a!==null)o=a}return this.loadTextureImage(e,r,o)}loadTextureImage(e,t,n){let i=this,r=this.json,s=r.textures[e],o=r.images[t],a=(o.uri||o.bufferView)+":"+s.sampler;if(this.textureCache[a])return this.textureCache[a];let c=this.loadImageSource(t,n).then(function(l){if(l.flipY=!1,l.name=s.name||o.name||"",l.name===""&&typeof o.uri==="string"&&o.uri.startsWith("data:image/")===!1)l.name=o.uri;let f=(r.samplers||{})[s.sampler]||{};return l.magFilter=zd[f.magFilter]||kt,l.minFilter=zd[f.minFilter]||Wn,l.wrapS=kd[f.wrapS]||Hr,l.wrapT=kd[f.wrapT]||Hr,l.generateMipmaps=!l.isCompressedTexture&&l.minFilter!==In&&l.minFilter!==kt,i.associations.set(l,{textures:e}),l}).catch(function(){return null});return this.textureCache[a]=c,c}loadImageSource(e,t){let n=this,i=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then((u)=>u.clone());let s=i.images[e],o=self.URL||self.webkitURL,a=s.uri||"",c=!1;if(s.bufferView!==void 0)a=n.getDependency("bufferView",s.bufferView).then(function(u){c=!0;let f=new Blob([u],{type:s.mimeType});return a=o.createObjectURL(f),a});else if(s.uri===void 0)throw Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let l=Promise.resolve(a).then(function(u){return new Promise(function(f,h){let d=f;if(t.isImageBitmapLoader===!0)d=function(g){let b=new St(g);b.needsUpdate=!0,f(b)};t.load(ki.resolveURL(u,r.path),d,void 0,h)})}).then(function(u){if(c===!0)o.revokeObjectURL(a);return Yn(u,s),u.userData.mimeType=s.mimeType||UM(s.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),u});return this.sourceCache[e]=l,l}assignTexture(e,t,n,i){let r=this;return this.getDependency("texture",n.index).then(function(s){if(!s)return null;if(n.texCoord!==void 0&&n.texCoord>0)s=s.clone(),s.channel=n.texCoord;if(r.extensions[Ze.KHR_TEXTURE_TRANSFORM]){let o=n.extensions!==void 0?n.extensions[Ze.KHR_TEXTURE_TRANSFORM]:void 0;if(o){let a=r.associations.get(s);s=r.extensions[Ze.KHR_TEXTURE_TRANSFORM].extendTexture(s,o),r.associations.set(s,a)}}if(i!==void 0)s.colorSpace=i;return e[t]=s,s})}assignFinalMaterial(e){let{geometry:t,material:n}=e,i=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,s=t.attributes.normal===void 0;if(e.isPoints){let o="PointsMaterial:"+n.uuid,a=this.cache.get(o);if(!a)a=new Ls,nn.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,a.sizeAttenuation=!1,this.cache.add(o,a);n=a}else if(e.isLine){let o="LineBasicMaterial:"+n.uuid,a=this.cache.get(o);if(!a)a=new Is,nn.prototype.copy.call(a,n),a.color.copy(n.color),a.map=n.map,this.cache.add(o,a);n=a}if(i||r||s){let o="ClonedMaterial:"+n.uuid+":";if(i)o+="derivative-tangents:";if(r)o+="vertex-colors:";if(s)o+="flat-shading:";let a=this.cache.get(o);if(!a){if(a=n.clone(),r)a.vertexColors=!0;if(s)a.flatShading=!0;if(i){if(a.normalScale)a.normalScale.y*=-1;if(a.clearcoatNormalScale)a.clearcoatNormalScale.y*=-1}this.cache.add(o,a),this.associations.set(a,this.associations.get(n))}n=a}e.material=n}getMaterialType(){return fi}loadMaterial(e){let t=this,n=this.json,i=this.extensions,r=n.materials[e],s,o={},a=r.extensions||{},c=[];if(a[Ze.KHR_MATERIALS_UNLIT]){let u=i[Ze.KHR_MATERIALS_UNLIT];s=u.getMaterialType(),c.push(u.extendParams(o,r,t))}else{let u=r.pbrMetallicRoughness||{};if(o.color=new Le(1,1,1),o.opacity=1,Array.isArray(u.baseColorFactor)){let f=u.baseColorFactor;o.color.setRGB(f[0],f[1],f[2],cn),o.opacity=f[3]}if(u.baseColorTexture!==void 0)c.push(t.assignTexture(o,"map",u.baseColorTexture,Pi));if(o.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,o.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0)c.push(t.assignTexture(o,"metalnessMap",u.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",u.metallicRoughnessTexture));s=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)})))}if(r.doubleSided===!0)o.side=vn;let l=r.alphaMode||Ql.OPAQUE;if(l===Ql.BLEND)o.transparent=!0,o.depthWrite=!1;else if(o.transparent=!1,l===Ql.MASK)o.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:0.5;if(r.normalTexture!==void 0&&s!==Zn){if(c.push(t.assignTexture(o,"normalMap",r.normalTexture)),o.normalScale=new Pe(1,1),r.normalTexture.scale!==void 0){let u=r.normalTexture.scale;o.normalScale.set(u,u)}}if(r.occlusionTexture!==void 0&&s!==Zn){if(c.push(t.assignTexture(o,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0)o.aoMapIntensity=r.occlusionTexture.strength}if(r.emissiveFactor!==void 0&&s!==Zn){let u=r.emissiveFactor;o.emissive=new Le().setRGB(u[0],u[1],u[2],cn)}if(r.emissiveTexture!==void 0&&s!==Zn)c.push(t.assignTexture(o,"emissiveMap",r.emissiveTexture,Pi));return Promise.all(c).then(function(){let u=new s(o);if(r.name)u.name=r.name;if(Yn(u,r),t.associations.set(u,{materials:e}),r.extensions)fr(i,u,r);return u})}createUniqueName(e){let t=et.sanitizeNodeName(e||"");if(t in this.nodeNamesUsed)return t+"_"+ ++this.nodeNamesUsed[t];else return this.nodeNamesUsed[t]=0,t}loadGeometries(e){let t=this,n=this.extensions,i=this.primitiveCache;function r(o){return n[Ze.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(a){return Bd(a,o,t)})}let s=[];for(let o=0,a=e.length;o<a;o++){let c=e[o],l=DM(c),u=i[l];if(u)s.push(u.promise);else{let f;if(c.extensions&&c.extensions[Ze.KHR_DRACO_MESH_COMPRESSION])f=r(c);else f=Bd(new Kt,c,t);i[l]={primitive:c,promise:f},s.push(f)}}return Promise.all(s)}loadMesh(e){let t=this,n=this.json,i=this.extensions,r=n.meshes[e],s=r.primitives,o=[];for(let a=0,c=s.length;a<c;a++){let l=s[a].material===void 0?IM(this.cache):this.getDependency("material",s[a].material);o.push(l)}return o.push(t.loadGeometries(s)),Promise.all(o).then(function(a){let c=a.slice(0,a.length-1),l=a[a.length-1],u=[];for(let h=0,d=l.length;h<d;h++){let g=l[h],b=s[h],p,m=c[h];if(b.mode===Sn.TRIANGLES||b.mode===Sn.TRIANGLE_STRIP||b.mode===Sn.TRIANGLE_FAN||b.mode===void 0){if(p=r.isSkinnedMesh===!0?new Qo(g,m):new dt(g,m),p.isSkinnedMesh===!0)p.normalizeSkinWeights();if(b.mode===Sn.TRIANGLE_STRIP)p.geometry=Jl(p.geometry,Ss);else if(b.mode===Sn.TRIANGLE_FAN)p.geometry=Jl(p.geometry,Zr)}else if(b.mode===Sn.LINES)p=new ea(g,m);else if(b.mode===Sn.LINE_STRIP)p=new Li(g,m);else if(b.mode===Sn.LINE_LOOP)p=new ta(g,m);else if(b.mode===Sn.POINTS)p=new jr(g,m);else throw Error("THREE.GLTFLoader: Primitive mode unsupported: "+b.mode);if(Object.keys(p.geometry.morphAttributes).length>0)NM(p,r);if(p.name=t.createUniqueName(r.name||"mesh_"+e),Yn(p,r),b.extensions)fr(i,p,b);t.assignFinalMaterial(p),u.push(p)}for(let h=0,d=u.length;h<d;h++)t.associations.set(u[h],{meshes:e,primitives:h});if(u.length===1){if(r.extensions)fr(i,u[0],r);return u[0]}let f=new Bn;if(r.extensions)fr(i,f,r);t.associations.set(f,{meshes:e});for(let h=0,d=u.length;h<d;h++)f.add(u[h]);return f})}loadCamera(e){let t,n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}if(n.type==="perspective")t=new Pt(Ms.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2000000);else if(n.type==="orthographic")t=new ur(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar);if(n.name)t.name=this.createUniqueName(n.name);return Yn(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let i=0,r=t.joints.length;i<r;i++)n.push(this._loadNodeShallow(t.joints[i]));if(t.inverseBindMatrices!==void 0)n.push(this.getDependency("accessor",t.inverseBindMatrices));else n.push(null);return Promise.all(n).then(function(i){let r=i.pop(),s=i,o=[],a=[];for(let c=0,l=s.length;c<l;c++){let u=s[c];if(u){o.push(u);let f=new Fe;if(r!==null)f.fromArray(r.array,c*16);a.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new Cs(o,a)})}loadAnimation(e){let t=this.json,n=this,i=t.animations[e],r=i.name?i.name:"animation_"+e,s=[],o=[],a=[],c=[],l=[];for(let u=0,f=i.channels.length;u<f;u++){let h=i.channels[u],d=i.samplers[h.sampler],g=h.target,b=g.node,p=i.parameters!==void 0?i.parameters[d.input]:d.input,m=i.parameters!==void 0?i.parameters[d.output]:d.output;if(g.node===void 0)continue;s.push(this.getDependency("node",b)),o.push(this.getDependency("accessor",p)),a.push(this.getDependency("accessor",m)),c.push(d),l.push(g)}return Promise.all([Promise.all(s),Promise.all(o),Promise.all(a),Promise.all(c),Promise.all(l)]).then(function(u){let f=u[0],h=u[1],d=u[2],g=u[3],b=u[4],p=[];for(let A=0,T=f.length;A<T;A++){let v=f[A],w=h[A],E=d[A],R=g[A],_=b[A];if(v===void 0)continue;if(v.updateMatrix)v.updateMatrix();let S=n._createAnimationTracks(v,w,E,R,_);if(S)for(let F=0;F<S.length;F++)p.push(S[F])}let m=new zr(r,void 0,p);return Yn(m,i),m})}createNodeMesh(e){let t=this.json,n=this,i=t.nodes[e];if(i.mesh===void 0)return null;return n.getDependency("mesh",i.mesh).then(function(r){let s=n._getNodeRef(n.meshCache,i.mesh,r);if(i.weights!==void 0)s.traverse(function(o){if(!o.isMesh)return;for(let a=0,c=i.weights.length;a<c;a++)o.morphTargetInfluences[a]=i.weights[a]});return s})}loadNode(e){let t=this.json,n=this,i=t.nodes[e],r=n._loadNodeShallow(e),s=[],o=i.children||[];for(let c=0,l=o.length;c<l;c++)s.push(n.getDependency("node",o[c]));let a=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([r,Promise.all(s),a]).then(function(c){let l=c[0],u=c[1],f=c[2];if(f!==null)l.traverse(function(h){if(!h.isSkinnedMesh)return;h.bind(f,OM)});for(let h=0,d=u.length;h<d;h++)l.add(u[h]);if(l.userData.pivot!==void 0&&u.length>0){let h=l.userData.pivot,d=u[0];l.pivot=new N().fromArray(h),l.position.x-=h[0],l.position.y-=h[1],l.position.z-=h[2],d.position.set(0,0,0),delete l.userData.pivot}return l})}_loadNodeShallow(e){let t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let r=t.nodes[e],s=r.name?i.createUniqueName(r.name):"",o=[],a=i._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});if(a)o.push(a);if(r.camera!==void 0)o.push(i.getDependency("camera",r.camera).then(function(c){return i._getNodeRef(i.cameraCache,r.camera,c)}));return i._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 l;if(r.isBone===!0)l=new As;else if(c.length>1)l=new Bn;else if(c.length===1)l=c[0];else l=new ot;if(l!==c[0])for(let u=0,f=c.length;u<f;u++)l.add(c[u]);if(r.name)l.userData.name=r.name,l.name=s;if(Yn(l,r),r.extensions)fr(n,l,r);if(r.matrix!==void 0){let u=new Fe;u.fromArray(r.matrix),l.applyMatrix4(u)}else{if(r.translation!==void 0)l.position.fromArray(r.translation);if(r.rotation!==void 0)l.quaternion.fromArray(r.rotation);if(r.scale!==void 0)l.scale.fromArray(r.scale)}if(!i.associations.has(l))i.associations.set(l,{});else if(r.mesh!==void 0&&i.meshCache.refs[r.mesh]>1){let u=i.associations.get(l);i.associations.set(l,{...u})}return i.associations.get(l).nodes=e,l}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],i=this,r=new Bn;if(n.name)r.name=i.createUniqueName(n.name);if(Yn(r,n),n.extensions)fr(t,r,n);let s=n.nodes||[],o=[];for(let a=0,c=s.length;a<c;a++)o.push(i.getDependency("node",s[a]));return Promise.all(o).then(function(a){for(let l=0,u=a.length;l<u;l++){let f=a[l];if(f.parent!==null)r.add(Ud(f));else r.add(f)}let c=(l)=>{let u=new Map;for(let[f,h]of i.associations)if(f instanceof nn||f instanceof St)u.set(f,h);return l.traverse((f)=>{let h=i.associations.get(f);if(h!=null)u.set(f,h)}),u};return i.associations=c(r),r})}_createAnimationTracks(e,t,n,i,r){let s=[],o=e.name?e.name:e.uuid,a=[];function c(h){if(h.morphTargetInfluences)a.push(h.name?h.name:h.uuid)}if(Gi[r.path]===Gi.weights){if(c(e),e.isGroup)e.children.forEach(c)}else a.push(o);let l;switch(Gi[r.path]){case Gi.weights:l=Oi;break;case Gi.rotation:l=Fi;break;case Gi.translation:case Gi.scale:l=lr;break;default:switch(n.itemSize){case 1:l=Oi;break;case 2:case 3:default:l=lr;break}break}let u=i.interpolation!==void 0?PM[i.interpolation]:Zo,f=this._getArrayFromAccessor(n);for(let h=0,d=a.length;h<d;h++){let g=new l(a[h]+"."+Gi[r.path],t.array,f,u);if(i.interpolation==="CUBICSPLINE")this._createCubicSplineTrackInterpolant(g);s.push(g)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let n=iu(t.constructor),i=new Float32Array(t.length);for(let r=0,s=t.length;r<s;r++)i[r]=t[r]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){return new(this instanceof Fi?lp:su)(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function FM(e,t,n){let i=t.attributes,r=new Jt;if(i.POSITION!==void 0){let a=n.json.accessors[i.POSITION],{min:c,max:l}=a;if(c!==void 0&&l!==void 0){if(r.set(new N(c[0],c[1],c[2]),new N(l[0],l[1],l[2])),a.normalized){let u=iu(ns[a.componentType]);r.min.multiplyScalar(u),r.max.multiplyScalar(u)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let s=t.targets;if(s!==void 0){let a=new N,c=new N;for(let l=0,u=s.length;l<u;l++){let f=s[l];if(f.POSITION!==void 0){let h=n.json.accessors[f.POSITION],{min:d,max:g}=h;if(d!==void 0&&g!==void 0){if(c.setX(Math.max(Math.abs(d[0]),Math.abs(g[0]))),c.setY(Math.max(Math.abs(d[1]),Math.abs(g[1]))),c.setZ(Math.max(Math.abs(d[2]),Math.abs(g[2]))),h.normalized){let b=iu(ns[h.componentType]);c.multiplyScalar(b)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(a)}e.boundingBox=r;let o=new ln;r.getCenter(o.center),o.radius=r.min.distanceTo(r.max)/2,e.boundingSphere=o}function Bd(e,t,n){let i=t.attributes,r=[];function s(o,a){return n.getDependency("accessor",o).then(function(c){e.setAttribute(a,c)})}for(let o in i){let a=nu[o]||o.toLowerCase();if(a in e.attributes)continue;r.push(s(i[o],a))}if(t.indices!==void 0&&!e.index){let o=n.getDependency("accessor",t.indices).then(function(a){e.setIndex(a)});r.push(o)}if(Ve.workingColorSpace!==cn&&"COLOR_0"in i)console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Ve.workingColorSpace}" not supported.`);return Yn(e,t),FM(e,t,n),Promise.all(r).then(function(){return t.targets!==void 0?LM(e,t.targets,n):e})}var hp={type:"change"},au={type:"start"},dp={type:"end"},va=new Ii,fp=new An,zM=Math.cos(70*Ms.DEG2RAD),Dt=new N,rn=2*Math.PI,at={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},ou=0.000001;class cu extends pa{constructor(e,t=null){super(e,t);if(this.state=at.NONE,this.target=new N,this.cursor=new N,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=0.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Ei.ROTATE,MIDDLE:Ei.DOLLY,RIGHT:Ei.PAN},this.touches={ONE:Ai.ROTATE,TWO:Ai.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new N,this._lastQuaternion=new zt,this._lastTargetPosition=new N,this._quat=new zt().setFromUnitVectors(e.up,new N(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Os,this._sphericalDelta=new Os,this._scale=1,this._panOffset=new N,this._rotateStart=new Pe,this._rotateEnd=new Pe,this._rotateDelta=new Pe,this._panStart=new Pe,this._panEnd=new Pe,this._panDelta=new Pe,this._dollyStart=new Pe,this._dollyEnd=new Pe,this._dollyDelta=new Pe,this._dollyDirection=new N,this._mouse=new Pe,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=BM.bind(this),this._onPointerDown=kM.bind(this),this._onPointerUp=GM.bind(this),this._onContextMenu=qM.bind(this),this._onMouseWheel=WM.bind(this),this._onKeyDown=$M.bind(this),this._onTouchStart=ZM.bind(this),this._onTouchMove=XM.bind(this),this._onMouseDown=HM.bind(this),this._onMouseMove=VM.bind(this),this._interceptControlDown=YM.bind(this),this._interceptControlUp=jM.bind(this),this.domElement!==null)this.connect(this.domElement);this.update()}set cursorStyle(e){if(this._cursorStyle=e,e==="grab")this.domElement.style.cursor="grab";else this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){if(this._domElementKeyEvents!==null)this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(hp),this.update(),this.state=at.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){let t=this.object.position;if(Dt.copy(t).sub(this.target),Dt.applyQuaternion(this._quat),this._spherical.setFromVector3(Dt),this.autoRotate&&this.state===at.NONE)this._rotateLeft(this._getAutoRotationAngle(e));if(this.enableDamping)this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor;else this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi;let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;if(isFinite(n)&&isFinite(i)){if(n<-Math.PI)n+=rn;else if(n>Math.PI)n-=rn;if(i<-Math.PI)i+=rn;else if(i>Math.PI)i-=rn;if(n<=i)this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta));else this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)}if(this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0)this.target.addScaledVector(this._panOffset,this.dampingFactor);else this.target.add(this._panOffset);this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let s=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=s!=this._spherical.radius}if(Dt.setFromSpherical(this._spherical),Dt.applyQuaternion(this._quatInverse),t.copy(this.target).add(Dt),this.object.lookAt(this.target),this.enableDamping===!0)this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor);else this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0);if(this.zoomToCursor&&this._performCursorZoom){let s=null;if(this.object.isPerspectiveCamera){let o=Dt.length();s=this._clampDistance(o*this._scale);let a=o-s;this.object.position.addScaledVector(this._dollyDirection,a),this.object.updateMatrixWorld(),r=!!a}else if(this.object.isOrthographicCamera){let o=new N(this._mouse.x,this._mouse.y,0);o.unproject(this.object);let a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=a!==this.object.zoom;let c=new N(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),s=Dt.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;if(s!==null)if(this.screenSpacePanning)this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(s).add(this.object.position);else if(va.origin.copy(this.object.position),va.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(va.direction))<zM)this.object.lookAt(this.target);else fp.setFromNormalAndCoplanarPoint(this.object.up,this.target),va.intersectPlane(fp,this.target)}else if(this.object.isOrthographicCamera){let s=this.object.zoom;if(this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),s!==this.object.zoom)this.object.updateProjectionMatrix(),r=!0}if(this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>ou||8*(1-this._lastQuaternion.dot(this.object.quaternion))>ou||this._lastTargetPosition.distanceToSquared(this.target)>ou)return this.dispatchEvent(hp),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0;return!1}_getAutoRotationAngle(e){if(e!==null)return rn/60*this.autoRotateSpeed*e;else return rn/60/60*this.autoRotateSpeed}_getZoomScale(e){let t=Math.abs(e*0.01);return Math.pow(0.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Dt.setFromMatrixColumn(t,0),Dt.multiplyScalar(-e),this._panOffset.add(Dt)}_panUp(e,t){if(this.screenSpacePanning===!0)Dt.setFromMatrixColumn(t,1);else Dt.setFromMatrixColumn(t,0),Dt.crossVectors(this.object.up,Dt);Dt.multiplyScalar(e),this._panOffset.add(Dt)}_pan(e,t){let n=this.domElement;if(this.object.isPerspectiveCamera){let i=this.object.position;Dt.copy(i).sub(this.target);let r=Dt.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else if(this.object.isOrthographicCamera)this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix);else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1}_dollyOut(e){if(this.object.isPerspectiveCamera||this.object.isOrthographicCamera)this._scale/=e;else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1}_dollyIn(e){if(this.object.isPerspectiveCamera||this.object.isOrthographicCamera)this._scale*=e;else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let n=this.domElement.getBoundingClientRect(),i=e-n.left,r=t-n.top,{width:s,height:o}=n;this._mouse.x=i/s*2-1,this._mouse.y=-(r/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(rn*this._rotateDelta.x/t.clientHeight),this._rotateUp(rn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){if(this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0)this._dollyOut(this._getZoomScale(this._dollyDelta.y));else if(this._dollyDelta.y<0)this._dollyIn(this._getZoomScale(this._dollyDelta.y));this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){if(this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0)this._dollyIn(this._getZoomScale(e.deltaY));else if(e.deltaY>0)this._dollyOut(this._getZoomScale(e.deltaY));this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate)this._rotateUp(rn*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(0,this.keyPanSpeed);t=!0;break;case this.keys.BOTTOM:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate)this._rotateUp(-rn*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(0,-this.keyPanSpeed);t=!0;break;case this.keys.LEFT:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate)this._rotateLeft(rn*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(this.keyPanSpeed,0);t=!0;break;case this.keys.RIGHT:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate)this._rotateLeft(-rn*this.keyRotateSpeed/this.domElement.clientHeight)}else if(this.enablePan)this._pan(-this.keyPanSpeed,0);t=!0;break}if(t)e.preventDefault(),this.update()}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=0.5*(e.pageX+t.x),i=0.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=0.5*(e.pageX+t.x),i=0.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){if(this.enableZoom)this._handleTouchStartDolly(e);if(this.enablePan)this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){if(this.enableZoom)this._handleTouchStartDolly(e);if(this.enableRotate)this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let n=this._getSecondPointerPosition(e),i=0.5*(e.pageX+n.x),r=0.5*(e.pageY+n.y);this._rotateEnd.set(i,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(rn*this._rotateDelta.x/t.clientHeight),this._rotateUp(rn*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=0.5*(e.pageX+t.x),i=0.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let s=(e.pageX+t.x)*0.5,o=(e.pageY+t.y)*0.5;this._updateZoomParameters(s,o)}_handleTouchMoveDollyPan(e){if(this.enableZoom)this._handleTouchMoveDolly(e);if(this.enablePan)this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){if(this.enableZoom)this._handleTouchMoveDolly(e);if(this.enableRotate)this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];if(t===void 0)t=new Pe,this._pointerPositions[e.pointerId]=t;t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){let t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){let t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}if(e.ctrlKey&&!this._controlActive)n.deltaY*=10;return n}}function kM(e){if(this.enabled===!1)return;if(this._pointers.length===0)this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp);if(this._isTrackingPointer(e))return;if(this._addPointer(e),e.pointerType==="touch")this._onTouchStart(e);else this._onMouseDown(e);if(this._cursorStyle==="grab")this.domElement.style.cursor="grabbing"}function BM(e){if(this.enabled===!1)return;if(e.pointerType==="touch")this._onTouchMove(e);else this._onMouseMove(e)}function GM(e){switch(this._removePointer(e),this._pointers.length){case 0:if(this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(dp),this.state=at.NONE,this._cursorStyle==="grab")this.domElement.style.cursor="grab";break;case 1:let t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y});break}}function HM(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case Ei.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(e),this.state=at.DOLLY;break;case Ei.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=at.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=at.ROTATE}break;case Ei.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=at.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=at.PAN}break;default:this.state=at.NONE}if(this.state!==at.NONE)this.dispatchEvent(au)}function VM(e){switch(this.state){case at.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(e);break;case at.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(e);break;case at.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(e);break}}function WM(e){if(this.enabled===!1||this.enableZoom===!1||this.state!==at.NONE)return;e.preventDefault(),this.dispatchEvent(au),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(dp)}function $M(e){if(this.enabled===!1)return;this._handleKeyDown(e)}function ZM(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case Ai.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(e),this.state=at.TOUCH_ROTATE;break;case Ai.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(e),this.state=at.TOUCH_PAN;break;default:this.state=at.NONE}break;case 2:switch(this.touches.TWO){case Ai.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(e),this.state=at.TOUCH_DOLLY_PAN;break;case Ai.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(e),this.state=at.TOUCH_DOLLY_ROTATE;break;default:this.state=at.NONE}break;default:this.state=at.NONE}if(this.state!==at.NONE)this.dispatchEvent(au)}function XM(e){switch(this._trackPointer(e),this.state){case at.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(e),this.update();break;case at.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(e),this.update();break;case at.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(e),this.update();break;case at.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=at.NONE}}function qM(e){if(this.enabled===!1)return;e.preventDefault()}function YM(e){if(e.key==="Control")this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}function jM(e){if(e.key==="Control")this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}class lu extends Xr{constructor(){super();this.name="RoomEnvironment",this.position.y=-3.5;let e=new Di;e.deleteAttribute("uv");let t=new fi({side:Xt}),n=new fi,i=new Kr(16777215,900,28,2);i.position.set(0.418,16.199,0.3),this.add(i);let r=new dt(e,t);r.position.set(-0.757,13.219,0.717),r.scale.set(31.713,28.305,28.591),this.add(r);let s=new Yr(e,n,6),o=new ot;o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-0.195,0),o.scale.set(2.328,7.905,4.651),o.updateMatrix(),s.setMatrixAt(0,o.matrix),o.position.set(-5.607,-0.754,-0.758),o.rotation.set(0,0.994,0),o.scale.set(1.97,1.534,3.955),o.updateMatrix(),s.setMatrixAt(1,o.matrix),o.position.set(6.167,0.857,7.803),o.rotation.set(0,0.561,0),o.scale.set(3.927,6.285,3.687),o.updateMatrix(),s.setMatrixAt(2,o.matrix),o.position.set(-2.017,0.018,6.124),o.rotation.set(0,0.333,0),o.scale.set(2.002,4.566,2.064),o.updateMatrix(),s.setMatrixAt(3,o.matrix),o.position.set(2.291,-0.756,-2.621),o.rotation.set(0,-0.286,0),o.scale.set(1.546,1.552,1.496),o.updateMatrix(),s.setMatrixAt(4,o.matrix),o.position.set(-2.193,-0.369,-5.547),o.rotation.set(0,0.516,0),o.scale.set(3.875,3.487,2.986),o.updateMatrix(),s.setMatrixAt(5,o.matrix),this.add(s);let a=new dt(e,is(50));a.position.set(-16.116,14.37,8.208),a.scale.set(0.1,2.428,2.739),this.add(a);let c=new dt(e,is(50));c.position.set(-16.109,18.021,-8.207),c.scale.set(0.1,2.425,2.751),this.add(c);let l=new dt(e,is(17));l.position.set(14.904,12.198,-1.832),l.scale.set(0.15,4.265,6.331),this.add(l);let u=new dt(e,is(43));u.position.set(-0.462,8.89,14.52),u.scale.set(4.38,5.441,0.088),this.add(u);let f=new dt(e,is(20));f.position.set(3.235,11.486,-12.541),f.scale.set(2.5,2,0.1),this.add(f);let h=new dt(e,is(100));h.position.set(0,20,0),h.scale.set(1,0.1,1),this.add(h)}dispose(){let e=new Set;this.traverse((t)=>{if(t.isMesh)e.add(t.geometry),e.add(t.material)});for(let t of e)t.dispose()}}function is(e){return new ra({color:0,emissive:16777215,emissiveIntensity:e})}var pp;function q(e,t,n){function i(a,c){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=o.prototype,u=Object.keys(l);for(let f=0;f<u.length;f++){let h=u[f];if(!(h in a))a[h]=l[h].bind(a)}}let r=n?.Parent??Object;class s extends r{}Object.defineProperty(s,"name",{value:e});function o(a){var c;let l=n?.Parent?new s:this;i(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(o,"init",{value:i}),Object.defineProperty(o,Symbol.hasInstance,{value:(a)=>{if(n?.Parent&&a instanceof n.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(o,"name",{value:e}),o}var _R=Symbol("zod_brand");class mi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Vs extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(pp=globalThis).__zod_globalConfig??(pp.__zod_globalConfig={});var rs=globalThis.__zod_globalConfig;function Dn(e){if(e)Object.assign(rs,e);return rs}function ba(e){let t=Object.values(e).filter((i)=>typeof i==="number");return Object.entries(e).filter(([i,r])=>t.indexOf(+i)===-1).map(([i,r])=>r)}function $s(e,t){if(typeof t==="bigint")return t.toString();return t}function Sa(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw Error("cached value already set")}}}function Ma(e){return e===null||e===void 0}function wa(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function gp(e,t){let n=e/t,i=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-i)<r)return 0;return n-i}var mp=Symbol("evaluating");function rt(e,t,n){let i=void 0;Object.defineProperty(e,t,{get(){if(i===mp)return;if(i===void 0)i=mp,i=n();return i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function dr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Hi(...e){let t={};for(let n of e){let i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function hu(e){return JSON.stringify(e)}function _p(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var fu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ws(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var xp=Sa(()=>{if(rs.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function pr(e){if(Ws(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(Ws(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function du(e){if(pr(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var vp=new Set(["string","number","symbol"]);function Vi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jn(e,t,n){let i=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)i._zod.parent=e;return i}function Te(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function yp(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var bp={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function JM(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=Hi(e._zod.def,{get shape(){let o={};for(let a in t){if(!(a in n.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;o[a]=n.shape[a]}return dr(this,"shape",o),o},checks:[]});return jn(e,s)}function KM(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=Hi(e._zod.def,{get shape(){let o={...e._zod.def.shape};for(let a in t){if(!(a in n.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete o[a]}return dr(this,"shape",o),o},checks:[]});return jn(e,s)}function QM(e,t){if(!pr(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let s=e._zod.def.shape;for(let o in t)if(Object.getOwnPropertyDescriptor(s,o)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=Hi(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return dr(this,"shape",s),s}});return jn(e,r)}function ew(e,t){if(!pr(t))throw Error("Invalid input to safeExtend: expected a plain object");let n=Hi(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return dr(this,"shape",i),i}});return jn(e,n)}function tw(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Hi(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t._zod.def.shape};return dr(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return jn(e,n)}function nw(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let o=Hi(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(n)for(let l in n){if(!(l in a))throw Error(`Unrecognized key: "${l}"`);if(!n[l])continue;c[l]=e?new e({type:"optional",innerType:a[l]}):a[l]}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return dr(this,"shape",c),c},checks:[]});return jn(t,o)}function iw(e,t,n){let i=Hi(t._zod.def,{get shape(){let r=t._zod.def.shape,s={...r};if(n)for(let o in n){if(!(o in s))throw Error(`Unrecognized key: "${o}"`);if(!n[o])continue;s[o]=new e({type:"nonoptional",innerType:r[o]})}else for(let o in r)s[o]=new e({type:"nonoptional",innerType:r[o]});return dr(this,"shape",s),s}});return jn(t,i)}function mr(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Sp(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Wi(e,t){return t.map((n)=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function ya(e){return typeof e==="string"?e:e?.message}function Un(e,t,n){let i=e.message?e.message:ya(e.inst?._zod.def?.error?.(e))??ya(t?.error?.(e))??ya(n.customError?.(e))??ya(n.localeError?.(e))??"Invalid input",{inst:r,continue:s,input:o,...a}=e;if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=o;return a}function Ta(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function gr(...e){let[t,n,i]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:i};return{...t}}var Mp=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,$s,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ea=q("$ZodError",Mp),pu=q("$ZodError",Mp,{Parent:Error});function wp(e,t=(n)=>n.message){let n={},i=[];for(let r of e.issues)if(r.path.length>0)n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r));else i.push(t(r));return{formErrors:i,fieldErrors:n}}function Tp(e,t=(n)=>n.message){let n={_errors:[]},i=(r,s=[])=>{for(let o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map((a)=>i({issues:a},[...s,...o.path]));else if(o.code==="invalid_key")i({issues:o.issues},[...s,...o.path]);else if(o.code==="invalid_element")i({issues:o.issues},[...s,...o.path]);else{let a=[...s,...o.path];if(a.length===0)n._errors.push(t(o));else{let c=n,l=0;while(l<a.length){let u=a[l];if(l!==a.length-1)c[u]=c[u]||{_errors:[]};else c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(o));c=c[u],l++}}}};return i(e),n}var Aa=(e)=>(t,n,i,r)=>{let s=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise)throw new mi;if(o.issues.length){let a=new(r?.Err??e)(o.issues.map((c)=>Un(c,s,Dn())));throw fu(a,r?.callee),a}return o.value};var Ra=(e)=>async(t,n,i,r)=>{let s=i?{...i,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},s);if(o instanceof Promise)o=await o;if(o.issues.length){let a=new(r?.Err??e)(o.issues.map((c)=>Un(c,s,Dn())));throw fu(a,r?.callee),a}return o.value};var Zs=(e)=>(t,n,i)=>{let r=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new mi;return s.issues.length?{success:!1,error:new(e??Ea)(s.issues.map((o)=>Un(o,r,Dn())))}:{success:!0,data:s.value}},Ep=Zs(pu),Xs=(e)=>async(t,n,i)=>{let r=i?{...i,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((o)=>Un(o,r,Dn())))}:{success:!0,data:s.value}},Ap=Xs(pu),Rp=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return Aa(e)(t,n,r)};var Cp=(e)=>(t,n,i)=>Aa(e)(t,n,i);var Pp=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return Ra(e)(t,n,r)};var Ip=(e)=>async(t,n,i)=>Ra(e)(t,n,i);var Lp=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return Zs(e)(t,n,r)};var Np=(e)=>(t,n,i)=>Zs(e)(t,n,i);var Dp=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return Xs(e)(t,n,r)};var Up=(e)=>async(t,n,i)=>Xs(e)(t,n,i);var Op=/^[cC][0-9a-z]{6,}$/,Fp=/^[0-9a-z]+$/,zp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,kp=/^[0-9a-vA-V]{20}$/,Bp=/^[A-Za-z0-9]{27}$/,Gp=/^[a-zA-Z0-9_-]{21}$/,Hp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Vp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,mu=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var Wp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var sw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $p(){return new RegExp(sw,"u")}var Zp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Xp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var qp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Yp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gu=/^[A-Za-z0-9_-]*$/;var Jp=/^https?$/,Kp=/^\+[1-9]\d{6,14}$/,Qp="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",em=new RegExp(`^${Qp}$`);function tm(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function nm(e){return new RegExp(`^${tm(e)}$`)}function im(e){let t=tm({precision:e.precision}),n=["Z"];if(e.local)n.push("");if(e.offset)n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${t}(?:${n.join("|")})`;return new RegExp(`^${Qp}T(?:${i})$`)}var rm=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var sm=/^-?\d+$/,_u=/^-?\d+(?:\.\d+)?$/,om=/^(?:true|false)$/i;var am=/^[^A-Z]*$/,cm=/^[^a-z]*$/;var Ht=q("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),lm={number:"number",bigint:"bigint",object:"date"},xu=q("$ZodCheckLessThan",(e,t)=>{Ht.init(e,t);let n=lm[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,s=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)r.maximum=t.value;else r.exclusiveMaximum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value<=t.value:i.value<t.value)return;i.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),vu=q("$ZodCheckGreaterThan",(e,t)=>{Ht.init(e,t);let n=lm[typeof t.value];e._zod.onattach.push((i)=>{let r=i._zod.bag,s=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)r.minimum=t.value;else r.exclusiveMinimum=t.value}),e._zod.check=(i)=>{if(t.inclusive?i.value>=t.value:i.value>t.value)return;i.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),um=q("$ZodCheckMultipleOf",(e,t)=>{Ht.init(e,t),e._zod.onattach.push((n)=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?n.value%t.value===BigInt(0):gp(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),hm=q("$ZodCheckNumberFormat",(e,t)=>{Ht.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),i=n?"int":"number",[r,s]=bp[t.format];e._zod.onattach.push((o)=>{let a=o._zod.bag;if(a.format=t.format,a.minimum=r,a.maximum=s,n)a.pattern=sm}),e._zod.check=(o)=>{let a=o.value;if(n){if(!Number.isInteger(a)){o.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});else o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}if(a<r)o.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(a>s)o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var fm=q("$ZodCheckMaxLength",(e,t)=>{var n;Ht.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!Ma(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<r)i._zod.bag.maximum=t.maximum}),e._zod.check=(i)=>{let r=i.value;if(r.length<=t.maximum)return;let o=Ta(r);i.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),dm=q("$ZodCheckMinLength",(e,t)=>{var n;Ht.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!Ma(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>r)i._zod.bag.minimum=t.minimum}),e._zod.check=(i)=>{let r=i.value;if(r.length>=t.minimum)return;let o=Ta(r);i.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),pm=q("$ZodCheckLengthEquals",(e,t)=>{var n;Ht.init(e,t),(n=e._zod.def).when??(n.when=(i)=>{let r=i.value;return!Ma(r)&&r.length!==void 0}),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=(i)=>{let r=i.value,s=r.length;if(s===t.length)return;let o=Ta(r),a=s>t.length;i.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),qs=q("$ZodCheckStringFormat",(e,t)=>{var n,i;if(Ht.init(e,t),e._zod.onattach.push((r)=>{let s=r._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(n=e._zod).check??(n.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(i=e._zod).check??(i.check=()=>{})}),mm=q("$ZodCheckRegex",(e,t)=>{qs.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),gm=q("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=am),qs.init(e,t)}),_m=q("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=cm),qs.init(e,t)}),xm=q("$ZodCheckIncludes",(e,t)=>{Ht.init(e,t);let n=Vi(t.includes),i=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push((r)=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(i)}),e._zod.check=(r)=>{if(r.value.includes(t.includes,t.position))return;r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),vm=q("$ZodCheckStartsWith",(e,t)=>{Ht.init(e,t);let n=new RegExp(`^${Vi(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.startsWith(t.prefix))return;i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),ym=q("$ZodCheckEndsWith",(e,t)=>{Ht.init(e,t);let n=new RegExp(`.*${Vi(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push((i)=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=(i)=>{if(i.value.endsWith(t.suffix))return;i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}});var bm=q("$ZodCheckOverwrite",(e,t)=>{Ht.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class yu{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`+`).filter((s)=>s),i=Math.min(...n.map((s)=>s.length-s.trimStart().length)),r=n.map((s)=>s.slice(i)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of r)this.content.push(s)}compile(){let e=Function,t=this?.args,i=[...(this?.content??[""]).map((r)=>` ${r}`)];return new e(...t,i.join(`+`))}}var Mm={major:4,minor:4,patch:3};var _t=q("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Mm;let i=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))i.unshift(e);for(let r of i)for(let s of r._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let r=(o,a,c)=>{let l=mr(o),u;for(let f of a){if(f._zod.def.when){if(Sp(o))continue;if(!f._zod.def.when(o))continue}else if(l)continue;let h=o.issues.length,d=f._zod.check(o);if(d instanceof Promise&&c?.async===!1)throw new mi;if(u||d instanceof Promise)u=(u??Promise.resolve()).then(async()=>{if(await d,o.issues.length===h)return;if(!l)l=mr(o,h)});else{if(o.issues.length===h)continue;if(!l)l=mr(o,h)}}if(u)return u.then(()=>o);return o},s=(o,a,c)=>{if(mr(o))return o.aborted=!0,o;let l=r(a,i,c);if(l instanceof Promise){if(c.async===!1)throw new mi;return l.then((u)=>e._zod.parse(u,c))}return e._zod.parse(l,c)};e._zod.run=(o,a)=>{if(a.skipChecks)return e._zod.parse(o,a);if(a.direction==="backward"){let l=e._zod.parse({value:o.value,issues:[]},{...a,skipChecks:!0});if(l instanceof Promise)return l.then((u)=>s(u,o,a));return s(l,o,a)}let c=e._zod.parse(o,a);if(c instanceof Promise){if(a.async===!1)throw new mi;return c.then((l)=>r(l,i,a))}return r(c,i,a)}}rt(e,"~standard",()=>({validate:(r)=>{try{let s=Ep(e,r);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Ap(e,r).then((o)=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),La=q("$ZodString",(e,t)=>{_t.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??rm(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),gt=q("$ZodStringFormat",(e,t)=>{qs.init(e,t),La.init(e,t)}),Lm=q("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Vp),gt.init(e,t)}),Nm=q("$ZodUUID",(e,t)=>{if(t.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=mu(i))}else t.pattern??(t.pattern=mu());gt.init(e,t)}),Dm=q("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Wp),gt.init(e,t)}),Um=q("$ZodURL",(e,t)=>{gt.init(e,t),e._zod.check=(n)=>{try{let i=n.value.trim();if(!t.normalize&&t.protocol?.source===Jp.source){if(!/^https?:\/\//i.test(i)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}}let r=new URL(i);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(r.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}if(t.normalize)n.value=r.href;else n.value=i;return}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Om=q("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=$p()),gt.init(e,t)}),Fm=q("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Gp),gt.init(e,t)}),zm=q("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Op),gt.init(e,t)}),km=q("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Fp),gt.init(e,t)}),Bm=q("$ZodULID",(e,t)=>{t.pattern??(t.pattern=zp),gt.init(e,t)}),Gm=q("$ZodXID",(e,t)=>{t.pattern??(t.pattern=kp),gt.init(e,t)}),Hm=q("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Bp),gt.init(e,t)}),Vm=q("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=im(t)),gt.init(e,t)}),Wm=q("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=em),gt.init(e,t)}),$m=q("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=nm(t)),gt.init(e,t)}),Zm=q("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Hp),gt.init(e,t)}),Xm=q("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Zp),gt.init(e,t),e._zod.bag.format="ipv4"}),qm=q("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Xp),gt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(n)=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}});var Ym=q("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=qp),gt.init(e,t)}),jm=q("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Yp),gt.init(e,t),e._zod.check=(n)=>{let i=n.value.split("/");try{if(i.length!==2)throw Error();let[r,s]=i;if(!s)throw Error();let o=Number(s);if(`${o}`!==s)throw Error();if(o<0||o>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Jm(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Km=q("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=jp),gt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(n)=>{if(Jm(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function ow(e){if(!gu.test(e))return!1;let t=e.replace(/[-_]/g,(i)=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Jm(n)}var Qm=q("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=gu),gt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(n)=>{if(ow(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),eg=q("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Kp),gt.init(e,t)});function aw(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let r=JSON.parse(atob(i));if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&(!("alg"in r)||r.alg!==t))return!1;return!0}catch{return!1}}var tg=q("$ZodJWT",(e,t)=>{gt.init(e,t),e._zod.check=(n)=>{if(aw(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var Su=q("$ZodNumber",(e,t)=>{_t.init(e,t),e._zod.pattern=e._zod.bag.pattern??_u,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch(o){}let r=n.value;if(typeof r==="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let s=typeof r==="number"?Number.isNaN(r)?"NaN":!Number.isFinite(r)?"Infinity":void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),n}}),ng=q("$ZodNumberFormat",(e,t)=>{hm.init(e,t),Su.init(e,t)}),ig=q("$ZodBoolean",(e,t)=>{_t.init(e,t),e._zod.pattern=om,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}let r=n.value;if(typeof r==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}});var rg=q("$ZodUnknown",(e,t)=>{_t.init(e,t),e._zod.parse=(n)=>n}),sg=q("$ZodNever",(e,t)=>{_t.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function wm(e,t,n){if(e.issues.length)t.issues.push(...Wi(n,e.issues));t.value[n]=e.value}var og=q("$ZodArray",(e,t)=>{_t.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);let s=[];for(let o=0;o<r.length;o++){let a=r[o],c=t.element._zod.run({value:a,issues:[]},i);if(c instanceof Promise)s.push(c.then((l)=>wm(l,n,o)));else wm(c,n,o)}if(s.length)return Promise.all(s).then(()=>n);return n}});function Ia(e,t,n,i,r,s){let o=n in i;if(e.issues.length){if(r&&s&&!o)return;t.issues.push(...Wi(n,e.issues))}if(!o&&!r){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(o)t.value[n]=void 0}else t.value[n]=e.value}function ag(e){let t=Object.keys(e.shape);for(let i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${i}": expected a Zod schema`);let n=yp(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function cg(e,t,n,i,r,s){let o=[],a=r.keySet,c=r.catchall._zod,l=c.def.type,u=c.optin==="optional",f=c.optout==="optional";for(let h in t){if(h==="__proto__")continue;if(a.has(h))continue;if(l==="never"){o.push(h);continue}let d=c.run({value:t[h],issues:[]},i);if(d instanceof Promise)e.push(d.then((g)=>Ia(g,n,h,t,u,f)));else Ia(d,n,h,t,u,f)}if(o.length)n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s});if(!e.length)return n;return Promise.all(e).then(()=>n)}var cw=q("$ZodObject",(e,t)=>{if(_t.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let i=Sa(()=>ag(t));rt(e._zod,"propValues",()=>{let a=t.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let f of u.values)c[l].add(f)}}return c});let r=Ws,s=t.catchall,o;e._zod.parse=(a,c)=>{o??(o=i.value);let l=a.value;if(!r(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};let u=[],f=o.shape;for(let h of o.keys){let d=f[h],g=d._zod.optin==="optional",b=d._zod.optout==="optional",p=d._zod.run({value:l[h],issues:[]},c);if(p instanceof Promise)u.push(p.then((m)=>Ia(m,a,h,l,g,b)));else Ia(p,a,h,l,g,b)}if(!s)return u.length?Promise.all(u).then(()=>a):a;return cg(u,l,a,c,i.value,e)}}),lg=q("$ZodObjectJIT",(e,t)=>{cw.init(e,t);let n=e._zod.parse,i=Sa(()=>ag(t)),r=(h)=>{let d=new yu(["shape","payload","ctx"]),g=i.value,b=(T)=>{let v=hu(T);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};d.write("const input = payload.value;");let p=Object.create(null),m=0;for(let T of g.keys)p[T]=`key_${m++}`;d.write("const newResult = {};");for(let T of g.keys){let v=p[T],w=hu(T),E=h[T],R=E?._zod?.optin==="optional",_=E?._zod?.optout==="optional";if(d.write(`const ${v} = ${b(T)};`),R&&_)d.write(`+ if (${v}.issues.length) {+ if (${w} in input) {+ payload.issues = payload.issues.concat(${v}.issues.map(iss => ({...iss,- path: iss.path ? [${B}, ...iss.path] : [${B}]+ path: iss.path ? [${w}, ...iss.path] : [${w}]})));}}- if (${L}.value === undefined) {- if (${B} in input) {- newResult[${B}] = undefined;+ if (${v}.value === undefined) {+ if (${w} in input) {+ newResult[${w}] = undefined;}} else {- newResult[${B}] = ${L}.value;+ newResult[${w}] = ${v}.value;}- `);else if(!A)k.write(`- const ${L}_present = ${B} in input;- if (${L}.issues.length) {- payload.issues = payload.issues.concat(${L}.issues.map(iss => ({+ `);else if(!R)d.write(`+ const ${v}_present = ${w} in input;+ if (${v}.issues.length) {+ payload.issues = payload.issues.concat(${v}.issues.map(iss => ({...iss,- path: iss.path ? [${B}, ...iss.path] : [${B}]+ path: iss.path ? [${w}, ...iss.path] : [${w}]})));}- if (!${L}_present && !${L}.issues.length) {+ if (!${v}_present && !${v}.issues.length) {payload.issues.push({code: "invalid_type",expected: "nonoptional",input: undefined,- path: [${B}]+ path: [${w}]});}- if (${L}_present) {- if (${L}.value === undefined) {- newResult[${B}] = undefined;+ if (${v}_present) {+ if (${v}.value === undefined) {+ newResult[${w}] = undefined;} else {- newResult[${B}] = ${L}.value;+ newResult[${w}] = ${v}.value;}}- `);else k.write(`- if (${L}.issues.length) {- payload.issues = payload.issues.concat(${L}.issues.map(iss => ({+ `);else d.write(`+ if (${v}.issues.length) {+ payload.issues = payload.issues.concat(${v}.issues.map(iss => ({...iss,- path: iss.path ? [${B}, ...iss.path] : [${B}]+ path: iss.path ? [${w}, ...iss.path] : [${w}]})));}- if (${L}.value === undefined) {- if (${B} in input) {- newResult[${B}] = undefined;+ if (${v}.value === undefined) {+ if (${w} in input) {+ newResult[${w}] = undefined;}} else {- newResult[${B}] = ${L}.value;+ newResult[${w}] = ${v}.value;}- `)}k.write("payload.value = newResult;"),k.write("return payload;");let _=k.compile();return(P,L)=>_(E,P,L)},K,X=f0,H=!x0.jitless,Y=H&&eH.value,G=U.catchall,O;$._zod.parse=(E,k)=>{O??(O=Q.value);let I=E.value;if(!X(I))return E.issues.push({expected:"object",code:"invalid_type",input:I,inst:$}),E;if(H&&Y&&k?.async===!1&&k.jitless!==!0){if(!K)K=W(U.shape);if(E=K(E,k),!G)return E;return oI([],I,E,k,O,$)}return J(E,k)}});function vI($,U,J,Q){for(let K of $)if(K.issues.length===0)return U.value=K.value,U;let W=$.filter((K)=>!O0(K));if(W.length===1)return U.value=W[0].value,W[0];return U.issues.push({code:"invalid_union",input:U.value,inst:J,errors:$.map((K)=>K.issues.map((X)=>HU(X,Q,S6())))}),U}var KQ=g("$ZodUnion",($,U)=>{h$.init($,U),s$($._zod,"optin",()=>U.options.some((Q)=>Q._zod.optin==="optional")?"optional":void 0),s$($._zod,"optout",()=>U.options.some((Q)=>Q._zod.optout==="optional")?"optional":void 0),s$($._zod,"values",()=>{if(U.options.every((Q)=>Q._zod.values))return new Set(U.options.flatMap((Q)=>Array.from(Q._zod.values)));return}),s$($._zod,"pattern",()=>{if(U.options.every((Q)=>Q._zod.pattern)){let Q=U.options.map((W)=>W._zod.pattern);return new RegExp(`^(${Q.map((W)=>oW(W.source)).join("|")})$`)}return});let J=U.options.length===1?U.options[0]._zod.run:null;$._zod.parse=(Q,W)=>{if(J)return J(Q,W);let K=!1,X=[];for(let H of U.options){let N=H._zod.run({value:Q.value,issues:[]},W);if(N instanceof Promise)X.push(N),K=!0;else{if(N.issues.length===0)return N;X.push(N)}}if(!K)return vI(X,Q,$,W);return Promise.all(X).then((H)=>{return vI(H,Q,$,W)})}});function jI($,U,J,Q){let W=$.filter((K)=>K.issues.length===0);if(W.length===1)return U.value=W[0].value,U;if(W.length===0)U.issues.push({code:"invalid_union",input:U.value,inst:J,errors:$.map((K)=>K.issues.map((X)=>HU(X,Q,S6())))});else U.issues.push({code:"invalid_union",input:U.value,inst:J,errors:[],inclusive:!1});return U}var pY=g("$ZodXor",($,U)=>{KQ.init($,U),U.inclusive=!1;let J=U.options.length===1?U.options[0]._zod.run:null;$._zod.parse=(Q,W)=>{if(J)return J(Q,W);let K=!1,X=[];for(let H of U.options){let N=H._zod.run({value:Q.value,issues:[]},W);if(N instanceof Promise)X.push(N),K=!0;else X.push(N)}if(!K)return jI(X,Q,$,W);return Promise.all(X).then((H)=>{return jI(H,Q,$,W)})}}),dY=g("$ZodDiscriminatedUnion",($,U)=>{U.inclusive=!1,KQ.init($,U);let J=$._zod.parse;s$($._zod,"propValues",()=>{let W={};for(let K of U.options){let X=K._zod.propValues;if(!X||Object.keys(X).length===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(K)}"`);for(let[H,N]of Object.entries(X)){if(!W[H])W[H]=new Set;for(let Y of N)W[H].add(Y)}}return W});let Q=j8(()=>{let W=U.options,K=new Map;for(let X of W){let H=X._zod.propValues?.[U.discriminator];if(!H||H.size===0)throw Error(`Invalid discriminated union option at index "${U.options.indexOf(X)}"`);for(let N of H){if(K.has(N))throw Error(`Duplicate discriminator value "${String(N)}"`);K.set(N,X)}}return K});$._zod.parse=(W,K)=>{let X=W.value;if(!f0(X))return W.issues.push({code:"invalid_type",expected:"object",input:X,inst:$}),W;let H=Q.value.get(X?.[U.discriminator]);if(H)return H._zod.run(W,K);if(U.unionFallback||K.direction==="backward")return J(W,K);return W.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:U.discriminator,options:Array.from(Q.value.keys()),input:X,path:[U.discriminator],inst:$}),W}}),cY=g("$ZodIntersection",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value,K=U.left._zod.run({value:W,issues:[]},Q),X=U.right._zod.run({value:W,issues:[]},Q);if(K instanceof Promise||X instanceof Promise)return Promise.all([K,X]).then(([N,Y])=>{return gI(J,N,Y)});return gI(J,K,X)}});function QY($,U){if($===U)return{valid:!0,data:$};if($ instanceof Date&&U instanceof Date&&+$===+U)return{valid:!0,data:$};if(G0($)&&G0(U)){let J=Object.keys(U),Q=Object.keys($).filter((K)=>J.indexOf(K)!==-1),W={...$,...U};for(let K of Q){let X=QY($[K],U[K]);if(!X.valid)return{valid:!1,mergeErrorPath:[K,...X.mergeErrorPath]};W[K]=X.data}return{valid:!0,data:W}}if(Array.isArray($)&&Array.isArray(U)){if($.length!==U.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let Q=0;Q<$.length;Q++){let W=$[Q],K=U[Q],X=QY(W,K);if(!X.valid)return{valid:!1,mergeErrorPath:[Q,...X.mergeErrorPath]};J.push(X.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function gI($,U,J){let Q=new Map,W;for(let H of U.issues)if(H.code==="unrecognized_keys"){W??(W=H);for(let N of H.keys){if(!Q.has(N))Q.set(N,{});Q.get(N).l=!0}}else $.issues.push(H);for(let H of J.issues)if(H.code==="unrecognized_keys")for(let N of H.keys){if(!Q.has(N))Q.set(N,{});Q.get(N).r=!0}else $.issues.push(H);let K=[...Q].filter(([,H])=>H.l&&H.r).map(([H])=>H);if(K.length&&W)$.issues.push({...W,keys:K});if(O0($))return $;let X=QY(U.value,J.value);if(!X.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}var ZK=g("$ZodTuple",($,U)=>{h$.init($,U);let J=U.items;$._zod.parse=(Q,W)=>{let K=Q.value;if(!Array.isArray(K))return Q.issues.push({input:K,inst:$,expected:"tuple",code:"invalid_type"}),Q;Q.value=[];let X=[],H=bI(J,"optin"),N=bI(J,"optout");if(!U.rest){if(K.length<H)return Q.issues.push({code:"too_small",minimum:H,inclusive:!0,input:K,inst:$,origin:"array"}),Q;if(K.length>J.length)Q.issues.push({code:"too_big",maximum:J.length,inclusive:!0,input:K,inst:$,origin:"array"})}let Y=Array(J.length);for(let G=0;G<J.length;G++){let O=J[G]._zod.run({value:K[G],issues:[]},W);if(O instanceof Promise)X.push(O.then((E)=>{Y[G]=E}));else Y[G]=O}if(U.rest){let G=J.length-1,O=K.slice(J.length);for(let E of O){G++;let k=U.rest._zod.run({value:E,issues:[]},W);if(k instanceof Promise)X.push(k.then((I)=>yI(I,Q,G)));else yI(k,Q,G)}}if(X.length)return Promise.all(X).then(()=>xI(Y,Q,J,K,N));return xI(Y,Q,J,K,N)}});function bI($,U){for(let J=$.length-1;J>=0;J--)if($[J]._zod[U]!=="optional")return J+1;return 0}function yI($,U,J){if($.issues.length)U.issues.push(...qU(J,$.issues));U.value[J]=$.value}function xI($,U,J,Q,W){for(let K=0;K<J.length;K++){let X=$[K],H=K<Q.length;if(X.issues.length){if(!H&&K>=W){U.value.length=K;break}U.issues.push(...qU(K,X.issues))}U.value[K]=X.value}for(let K=U.value.length-1;K>=Q.length;K--)if(J[K]._zod.optout==="optional"&&U.value[K]===void 0)U.value.length=K;else break;return U}var nY=g("$ZodRecord",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(!G0(W))return J.issues.push({expected:"record",code:"invalid_type",input:W,inst:$}),J;let K=[],X=U.keyType._zod.values;if(X){J.value={};let H=new Set;for(let Y of X)if(typeof Y==="string"||typeof Y==="number"||typeof Y==="symbol"){H.add(typeof Y==="number"?Y.toString():Y);let G=U.keyType._zod.run({value:Y,issues:[]},Q);if(G instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(G.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:G.issues.map((k)=>HU(k,Q,S6())),input:Y,path:[Y],inst:$});continue}let O=G.value,E=U.valueType._zod.run({value:W[Y],issues:[]},Q);if(E instanceof Promise)K.push(E.then((k)=>{if(k.issues.length)J.issues.push(...qU(Y,k.issues));J.value[O]=k.value}));else{if(E.issues.length)J.issues.push(...qU(Y,E.issues));J.value[O]=E.value}}let N;for(let Y in W)if(!H.has(Y))N=N??[],N.push(Y);if(N&&N.length>0)J.issues.push({code:"unrecognized_keys",input:W,inst:$,keys:N})}else{J.value={};for(let H of Reflect.ownKeys(W)){if(H==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(W,H))continue;let N=U.keyType._zod.run({value:H,issues:[]},Q);if(N instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof H==="string"&&UQ.test(H)&&N.issues.length){let O=U.keyType._zod.run({value:Number(H),issues:[]},Q);if(O instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(O.issues.length===0)N=O}if(N.issues.length){if(U.mode==="loose")J.value[H]=W[H];else J.issues.push({code:"invalid_key",origin:"record",issues:N.issues.map((O)=>HU(O,Q,S6())),input:H,path:[H],inst:$});continue}let G=U.valueType._zod.run({value:W[H],issues:[]},Q);if(G instanceof Promise)K.push(G.then((O)=>{if(O.issues.length)J.issues.push(...qU(H,O.issues));J.value[N.value]=O.value}));else{if(G.issues.length)J.issues.push(...qU(H,G.issues));J.value[N.value]=G.value}}}if(K.length)return Promise.all(K).then(()=>J);return J}}),iY=g("$ZodMap",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(!(W instanceof Map))return J.issues.push({expected:"map",code:"invalid_type",input:W,inst:$}),J;let K=[];J.value=new Map;for(let[X,H]of W){let N=U.keyType._zod.run({value:X,issues:[]},Q),Y=U.valueType._zod.run({value:H,issues:[]},Q);if(N instanceof Promise||Y instanceof Promise)K.push(Promise.all([N,Y]).then(([G,O])=>{hI(G,O,J,X,W,$,Q)}));else hI(N,Y,J,X,W,$,Q)}if(K.length)return Promise.all(K).then(()=>J);return J}});function hI($,U,J,Q,W,K,X){if($.issues.length)if(rW.has(typeof Q))J.issues.push(...qU(Q,$.issues));else J.issues.push({code:"invalid_key",origin:"map",input:W,inst:K,issues:$.issues.map((H)=>HU(H,X,S6()))});if(U.issues.length)if(rW.has(typeof Q))J.issues.push(...qU(Q,U.issues));else J.issues.push({origin:"map",code:"invalid_element",input:W,inst:K,key:Q,issues:U.issues.map((H)=>HU(H,X,S6()))});J.value.set($.value,U.value)}var oY=g("$ZodSet",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(!(W instanceof Set))return J.issues.push({input:W,inst:$,expected:"set",code:"invalid_type"}),J;let K=[];J.value=new Set;for(let X of W){let H=U.valueType._zod.run({value:X,issues:[]},Q);if(H instanceof Promise)K.push(H.then((N)=>fI(N,J)));else fI(H,J)}if(K.length)return Promise.all(K).then(()=>J);return J}});function fI($,U){if($.issues.length)U.issues.push(...$.issues);U.value.add($.value)}var rY=g("$ZodEnum",($,U)=>{h$.init($,U);let J=iW(U.entries),Q=new Set(J);$._zod.values=Q,$._zod.pattern=new RegExp(`^(${J.filter((W)=>rW.has(typeof W)).map((W)=>typeof W==="string"?yU(W):W.toString()).join("|")})$`),$._zod.parse=(W,K)=>{let X=W.value;if(Q.has(X))return W;return W.issues.push({code:"invalid_value",values:J,input:X,inst:$}),W}}),aY=g("$ZodLiteral",($,U)=>{if(h$.init($,U),U.values.length===0)throw Error("Cannot create literal schema with no valid values");let J=new Set(U.values);$._zod.values=J,$._zod.pattern=new RegExp(`^(${U.values.map((Q)=>typeof Q==="string"?yU(Q):Q?yU(Q.toString()):String(Q)).join("|")})$`),$._zod.parse=(Q,W)=>{let K=Q.value;if(J.has(K))return Q;return Q.issues.push({code:"invalid_value",values:U.values,input:K,inst:$}),Q}}),sY=g("$ZodFile",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{let W=J.value;if(W instanceof File)return J;return J.issues.push({expected:"file",code:"invalid_type",input:W,inst:$}),J}}),tY=g("$ZodTransform",($,U)=>{h$.init($,U),$._zod.optin="optional",$._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new h0($.constructor.name);let W=U.transform(J.value,J);if(Q.async)return(W instanceof Promise?W:Promise.resolve(W)).then((X)=>{return J.value=X,J.fallback=!0,J});if(W instanceof Promise)throw new YJ;return J.value=W,J.fallback=!0,J}});function uI($,U){if(U===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}var IK=g("$ZodOptional",($,U)=>{h$.init($,U),$._zod.optin="optional",$._zod.optout="optional",s$($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,void 0]):void 0}),s$($._zod,"pattern",()=>{let J=U.innerType._zod.pattern;return J?new RegExp(`^(${oW(J.source)})?$`):void 0}),$._zod.parse=(J,Q)=>{if(U.innerType._zod.optin==="optional"){let W=J.value,K=U.innerType._zod.run(J,Q);if(K instanceof Promise)return K.then((X)=>uI(X,W));return uI(K,W)}if(J.value===void 0)return J;return U.innerType._zod.run(J,Q)}}),eY=g("$ZodExactOptional",($,U)=>{IK.init($,U),s$($._zod,"values",()=>U.innerType._zod.values),s$($._zod,"pattern",()=>U.innerType._zod.pattern),$._zod.parse=(J,Q)=>{return U.innerType._zod.run(J,Q)}}),$1=g("$ZodNullable",($,U)=>{h$.init($,U),s$($._zod,"optin",()=>U.innerType._zod.optin),s$($._zod,"optout",()=>U.innerType._zod.optout),s$($._zod,"pattern",()=>{let J=U.innerType._zod.pattern;return J?new RegExp(`^(${oW(J.source)}|null)$`):void 0}),s$($._zod,"values",()=>{return U.innerType._zod.values?new Set([...U.innerType._zod.values,null]):void 0}),$._zod.parse=(J,Q)=>{if(J.value===null)return J;return U.innerType._zod.run(J,Q)}}),U1=g("$ZodDefault",($,U)=>{h$.init($,U),$._zod.optin="optional",s$($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")return U.innerType._zod.run(J,Q);if(J.value===void 0)return J.value=U.defaultValue,J;let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>lI(K,U));return lI(W,U)}});function lI($,U){if($.value===void 0)$.value=U.defaultValue;return $}var J1=g("$ZodPrefault",($,U)=>{h$.init($,U),$._zod.optin="optional",s$($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")return U.innerType._zod.run(J,Q);if(J.value===void 0)J.value=U.defaultValue;return U.innerType._zod.run(J,Q)}}),W1=g("$ZodNonOptional",($,U)=>{h$.init($,U),s$($._zod,"values",()=>{let J=U.innerType._zod.values;return J?new Set([...J].filter((Q)=>Q!==void 0)):void 0}),$._zod.parse=(J,Q)=>{let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>mI(K,$));return mI(W,$)}});function mI($,U){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:U});return $}var Q1=g("$ZodSuccess",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new h0("ZodSuccess");let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>{return J.value=K.issues.length===0,J});return J.value=W.issues.length===0,J}}),K1=g("$ZodCatch",($,U)=>{h$.init($,U),$._zod.optin="optional",s$($._zod,"optout",()=>U.innerType._zod.optout),s$($._zod,"values",()=>U.innerType._zod.values),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")return U.innerType._zod.run(J,Q);let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>{if(J.value=K.value,K.issues.length)J.value=U.catchValue({...J,error:{issues:K.issues.map((X)=>HU(X,Q,S6()))},input:J.value}),J.issues=[],J.fallback=!0;return J});if(J.value=W.value,W.issues.length)J.value=U.catchValue({...J,error:{issues:W.issues.map((K)=>HU(K,Q,S6()))},input:J.value}),J.issues=[],J.fallback=!0;return J}}),X1=g("$ZodNaN",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{if(typeof J.value!=="number"||!Number.isNaN(J.value))return J.issues.push({input:J.value,inst:$,expected:"nan",code:"invalid_type"}),J;return J}}),DK=g("$ZodPipe",($,U)=>{h$.init($,U),s$($._zod,"values",()=>U.in._zod.values),s$($._zod,"optin",()=>U.in._zod.optin),s$($._zod,"optout",()=>U.out._zod.optout),s$($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(J,Q)=>{if(Q.direction==="backward"){let K=U.out._zod.run(J,Q);if(K instanceof Promise)return K.then((X)=>YK(X,U.in,Q));return YK(K,U.in,Q)}let W=U.in._zod.run(J,Q);if(W instanceof Promise)return W.then((K)=>YK(K,U.out,Q));return YK(W,U.out,Q)}});function YK($,U,J){if($.issues.length)return $.aborted=!0,$;return U._zod.run({value:$.value,issues:$.issues,fallback:$.fallback},J)}var XQ=g("$ZodCodec",($,U)=>{h$.init($,U),s$($._zod,"values",()=>U.in._zod.values),s$($._zod,"optin",()=>U.in._zod.optin),s$($._zod,"optout",()=>U.out._zod.optout),s$($._zod,"propValues",()=>U.in._zod.propValues),$._zod.parse=(J,Q)=>{if((Q.direction||"forward")==="forward"){let K=U.in._zod.run(J,Q);if(K instanceof Promise)return K.then((X)=>GK(X,U,Q));return GK(K,U,Q)}else{let K=U.out._zod.run(J,Q);if(K instanceof Promise)return K.then((X)=>GK(X,U,Q));return GK(K,U,Q)}}});function GK($,U,J){if($.issues.length)return $.aborted=!0,$;if((J.direction||"forward")==="forward"){let W=U.transform($.value,$);if(W instanceof Promise)return W.then((K)=>OK($,K,U.out,J));return OK($,W,U.out,J)}else{let W=U.reverseTransform($.value,$);if(W instanceof Promise)return W.then((K)=>OK($,K,U.in,J));return OK($,W,U.in,J)}}function OK($,U,J,Q){if($.issues.length)return $.aborted=!0,$;return J._zod.run({value:U,issues:$.issues},Q)}var H1=g("$ZodPreprocess",($,U)=>{DK.init($,U)}),N1=g("$ZodReadonly",($,U)=>{h$.init($,U),s$($._zod,"propValues",()=>U.innerType._zod.propValues),s$($._zod,"values",()=>U.innerType._zod.values),s$($._zod,"optin",()=>U.innerType?._zod?.optin),s$($._zod,"optout",()=>U.innerType?._zod?.optout),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")return U.innerType._zod.run(J,Q);let W=U.innerType._zod.run(J,Q);if(W instanceof Promise)return W.then(pI);return pI(W)}});function pI($){return $.value=Object.freeze($.value),$}var Y1=g("$ZodTemplateLiteral",($,U)=>{h$.init($,U);let J=[];for(let Q of U.parts)if(typeof Q==="object"&&Q!==null){if(!Q._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...Q._zod.traits].shift()}`);let W=Q._zod.pattern instanceof RegExp?Q._zod.pattern.source:Q._zod.pattern;if(!W)throw Error(`Invalid template literal part: ${Q._zod.traits}`);let K=W.startsWith("^")?1:0,X=W.endsWith("$")?W.length-1:W.length;J.push(W.slice(K,X))}else if(Q===null||UN.has(typeof Q))J.push(yU(`${Q}`));else throw Error(`Invalid template literal part: ${Q}`);$._zod.pattern=new RegExp(`^${J.join("")}$`),$._zod.parse=(Q,W)=>{if(typeof Q.value!=="string")return Q.issues.push({input:Q.value,inst:$,expected:"string",code:"invalid_type"}),Q;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(Q.value))return Q.issues.push({input:Q.value,inst:$,code:"invalid_format",format:U.format??"template_literal",pattern:$._zod.pattern.source}),Q;return Q}}),G1=g("$ZodFunction",($,U)=>{return h$.init($,U),$._def=U,$._zod.def=U,$.implement=(J)=>{if(typeof J!=="function")throw Error("implement() must be called with a function");return function(...Q){let W=$._def.input?r9($._def.input,Q):Q,K=Reflect.apply(J,this,W);if($._def.output)return r9($._def.output,K);return K}},$.implementAsync=(J)=>{if(typeof J!=="function")throw Error("implementAsync() must be called with a function");return async function(...Q){let W=$._def.input?await a9($._def.input,Q):Q,K=await Reflect.apply(J,this,W);if($._def.output)return await a9($._def.output,K);return K}},$._zod.parse=(J,Q)=>{if(typeof J.value!=="function")return J.issues.push({code:"invalid_type",expected:"function",input:J.value,inst:$}),J;if($._def.output&&$._def.output._zod.def.type==="promise")J.value=$.implementAsync(J.value);else J.value=$.implement(J.value);return J},$.input=(...J)=>{let Q=$.constructor;if(Array.isArray(J[0]))return new Q({type:"function",input:new ZK({type:"tuple",items:J[0],rest:J[1]}),output:$._def.output});return new Q({type:"function",input:J[0],output:$._def.output})},$.output=(J)=>{return new $.constructor({type:"function",input:$._def.input,output:J})},$}),O1=g("$ZodPromise",($,U)=>{h$.init($,U),$._zod.parse=(J,Q)=>{return Promise.resolve(J.value).then((W)=>U.innerType._zod.run({value:W,issues:[]},Q))}}),E1=g("$ZodLazy",($,U)=>{h$.init($,U),s$($._zod,"innerType",()=>{let J=U;if(!J._cachedInner)J._cachedInner=U.getter();return J._cachedInner}),s$($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),s$($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),s$($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),s$($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(J,Q)=>{return $._zod.innerType._zod.run(J,Q)}}),k1=g("$ZodCustom",($,U)=>{V6.init($,U),h$.init($,U),$._zod.parse=(J,Q)=>{return J},$._zod.check=(J)=>{let Q=J.value,W=U.fn(Q);if(W instanceof Promise)return W.then((K)=>dI(K,J,Q,$));dI(W,J,Q,$);return}});function dI($,U,J,Q){if(!$){let W={code:"custom",input:J,inst:Q,path:[...Q._zod.def.path??[]],continue:!Q._zod.def.abort};if(Q._zod.def.params)W.params=Q._zod.def.params;U.issues.push(g8(W))}}var OQ={};RJ(OQ,{zhTW:()=>HG,zhCN:()=>XG,yo:()=>NG,vi:()=>KG,uz:()=>QG,ur:()=>WG,uk:()=>GQ,ua:()=>JG,tr:()=>UG,th:()=>$G,ta:()=>e1,sv:()=>t1,sl:()=>s1,ru:()=>a1,ro:()=>r1,pt:()=>o1,ps:()=>n1,pl:()=>i1,ota:()=>c1,no:()=>d1,nl:()=>p1,ms:()=>m1,mk:()=>l1,lt:()=>u1,ko:()=>f1,km:()=>NQ,kh:()=>h1,ka:()=>x1,ja:()=>y1,it:()=>b1,is:()=>g1,id:()=>j1,hy:()=>v1,hu:()=>T1,hr:()=>S1,he:()=>C1,frCA:()=>A1,fr:()=>_1,fi:()=>z1,fa:()=>P1,es:()=>B1,eo:()=>M1,en:()=>HQ,el:()=>w1,de:()=>V1,da:()=>R1,cs:()=>L1,ca:()=>F1,bg:()=>D1,be:()=>I1,az:()=>Z1,ar:()=>q1});var zB=()=>{let $={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function U(W){return $[W]??null}let J={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${W.expected}، ولكن تم إدخال ${H}`;return`مدخلات غير مقبولة: يفترض إدخال ${K}، ولكن تم إدخال ${H}`}case"invalid_value":if(W.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${U$(W.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return` أكبر من اللازم: يفترض أن تكون ${W.origin??"القيمة"} ${K} ${W.maximum.toString()} ${X.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${W.origin??"القيمة"} ${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`أصغر من اللازم: يفترض لـ ${W.origin} أن يكون ${K} ${W.minimum.toString()} ${X.unit}`;return`أصغر من اللازم: يفترض لـ ${W.origin} أن يكون ${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${W.prefix}"`;if(K.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${K.suffix}"`;if(K.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${K.includes}"`;if(K.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${K.pattern}`;return`${J[K.format]??W.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${W.divisor}`;case"unrecognized_keys":return`معرف${W.keys.length>1?"ات":""} غريب${W.keys.length>1?"ة":""}: ${m(W.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${W.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${W.origin}`;default:return"مدخل غير مقبول"}}};function q1(){return{localeError:zB()}}var _B=()=>{let $={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function U(W){return $[W]??null}let J={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Yanlış dəyər: gözlənilən instanceof ${W.expected}, daxil olan ${H}`;return`Yanlış dəyər: gözlənilən ${K}, daxil olan ${H}`}case"invalid_value":if(W.values.length===1)return`Yanlış dəyər: gözlənilən ${U$(W.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Çox böyük: gözlənilən ${W.origin??"dəyər"} ${K}${W.maximum.toString()} ${X.unit??"element"}`;return`Çox böyük: gözlənilən ${W.origin??"dəyər"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Çox kiçik: gözlənilən ${W.origin} ${K}${W.minimum.toString()} ${X.unit}`;return`Çox kiçik: gözlənilən ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Yanlış mətn: "${K.prefix}" ilə başlamalıdır`;if(K.format==="ends_with")return`Yanlış mətn: "${K.suffix}" ilə bitməlidir`;if(K.format==="includes")return`Yanlış mətn: "${K.includes}" daxil olmalıdır`;if(K.format==="regex")return`Yanlış mətn: ${K.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${J[K.format]??W.format}`}case"not_multiple_of":return`Yanlış ədəd: ${W.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${W.keys.length>1?"lar":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${W.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function Z1(){return{localeError:_B()}}function aI($,U,J,Q){let W=Math.abs($),K=W%10,X=W%100;if(X>=11&&X<=19)return Q;if(K===1)return U;if(K>=2&&K<=4)return J;return Q}var AB=()=>{let $={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function U(W){return $[W]??null}let J={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},Q={nan:"NaN",number:"лік",array:"масіў"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Няправільны ўвод: чакаўся instanceof ${W.expected}, атрымана ${H}`;return`Няправільны ўвод: чакаўся ${K}, атрымана ${H}`}case"invalid_value":if(W.values.length===1)return`Няправільны ўвод: чакалася ${U$(W.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X){let H=Number(W.maximum),N=aI(H,X.unit.one,X.unit.few,X.unit.many);return`Занадта вялікі: чакалася, што ${W.origin??"значэнне"} павінна ${X.verb} ${K}${W.maximum.toString()} ${N}`}return`Занадта вялікі: чакалася, што ${W.origin??"значэнне"} павінна быць ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X){let H=Number(W.minimum),N=aI(H,X.unit.one,X.unit.few,X.unit.many);return`Занадта малы: чакалася, што ${W.origin} павінна ${X.verb} ${K}${W.minimum.toString()} ${N}`}return`Занадта малы: чакалася, што ${W.origin} павінна быць ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${K.prefix}"`;if(K.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${K.suffix}"`;if(K.format==="includes")return`Няправільны радок: павінен змяшчаць "${K.includes}"`;if(K.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${K.pattern}`;return`Няправільны ${J[K.format]??W.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${W.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${W.keys.length>1?"ключы":"ключ"}: ${m(W.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${W.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${W.origin}`;default:return"Няправільны ўвод"}}};function I1(){return{localeError:AB()}}var CB=()=>{let $={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function U(W){return $[W]??null}let J={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},Q={nan:"NaN",number:"число",array:"масив"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Невалиден вход: очакван instanceof ${W.expected}, получен ${H}`;return`Невалиден вход: очакван ${K}, получен ${H}`}case"invalid_value":if(W.values.length===1)return`Невалиден вход: очакван ${U$(W.values[0])}`;return`Невалидна опция: очаквано едно от ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Твърде голямо: очаква се ${W.origin??"стойност"} да съдържа ${K}${W.maximum.toString()} ${X.unit??"елемента"}`;return`Твърде голямо: очаква се ${W.origin??"стойност"} да бъде ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Твърде малко: очаква се ${W.origin} да съдържа ${K}${W.minimum.toString()} ${X.unit}`;return`Твърде малко: очаква се ${W.origin} да бъде ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Невалиден низ: трябва да започва с "${K.prefix}"`;if(K.format==="ends_with")return`Невалиден низ: трябва да завършва с "${K.suffix}"`;if(K.format==="includes")return`Невалиден низ: трябва да включва "${K.includes}"`;if(K.format==="regex")return`Невалиден низ: трябва да съвпада с ${K.pattern}`;let X="Невалиден";if(K.format==="emoji")X="Невалидно";if(K.format==="datetime")X="Невалидно";if(K.format==="date")X="Невалидна";if(K.format==="time")X="Невалидно";if(K.format==="duration")X="Невалидна";return`${X} ${J[K.format]??W.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${W.divisor}`;case"unrecognized_keys":return`Неразпознат${W.keys.length>1?"и":""} ключ${W.keys.length>1?"ове":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${W.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${W.origin}`;default:return"Невалиден вход"}}};function D1(){return{localeError:CB()}}var SB=()=>{let $={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function U(W){return $[W]??null}let J={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Tipus invàlid: s'esperava instanceof ${W.expected}, s'ha rebut ${H}`;return`Tipus invàlid: s'esperava ${K}, s'ha rebut ${H}`}case"invalid_value":if(W.values.length===1)return`Valor invàlid: s'esperava ${U$(W.values[0])}`;return`Opció invàlida: s'esperava una de ${m(W.values," o ")}`;case"too_big":{let K=W.inclusive?"com a màxim":"menys de",X=U(W.origin);if(X)return`Massa gran: s'esperava que ${W.origin??"el valor"} contingués ${K} ${W.maximum.toString()} ${X.unit??"elements"}`;return`Massa gran: s'esperava que ${W.origin??"el valor"} fos ${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?"com a mínim":"més de",X=U(W.origin);if(X)return`Massa petit: s'esperava que ${W.origin} contingués ${K} ${W.minimum.toString()} ${X.unit}`;return`Massa petit: s'esperava que ${W.origin} fos ${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Format invàlid: ha de començar amb "${K.prefix}"`;if(K.format==="ends_with")return`Format invàlid: ha d'acabar amb "${K.suffix}"`;if(K.format==="includes")return`Format invàlid: ha d'incloure "${K.includes}"`;if(K.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${K.pattern}`;return`Format invàlid per a ${J[K.format]??W.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${W.divisor}`;case"unrecognized_keys":return`Clau${W.keys.length>1?"s":""} no reconeguda${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${W.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${W.origin}`;default:return"Entrada invàlida"}}};function F1(){return{localeError:SB()}}var TB=()=>{let $={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function U(W){return $[W]??null}let J={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},Q={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Neplatný vstup: očekáváno instanceof ${W.expected}, obdrženo ${H}`;return`Neplatný vstup: očekáváno ${K}, obdrženo ${H}`}case"invalid_value":if(W.values.length===1)return`Neplatný vstup: očekáváno ${U$(W.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Hodnota je příliš velká: ${W.origin??"hodnota"} musí mít ${K}${W.maximum.toString()} ${X.unit??"prvků"}`;return`Hodnota je příliš velká: ${W.origin??"hodnota"} musí být ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Hodnota je příliš malá: ${W.origin??"hodnota"} musí mít ${K}${W.minimum.toString()} ${X.unit??"prvků"}`;return`Hodnota je příliš malá: ${W.origin??"hodnota"} musí být ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Neplatný řetězec: musí začínat na "${K.prefix}"`;if(K.format==="ends_with")return`Neplatný řetězec: musí končit na "${K.suffix}"`;if(K.format==="includes")return`Neplatný řetězec: musí obsahovat "${K.includes}"`;if(K.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${K.pattern}`;return`Neplatný formát ${J[K.format]??W.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${W.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${m(W.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${W.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${W.origin}`;default:return"Neplatný vstup"}}};function L1(){return{localeError:TB()}}var vB=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function U(W){return $[W]??null}let J={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ugyldigt input: forventede instanceof ${W.expected}, fik ${H}`;return`Ugyldigt input: forventede ${K}, fik ${H}`}case"invalid_value":if(W.values.length===1)return`Ugyldig værdi: forventede ${U$(W.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin),H=Q[W.origin]??W.origin;if(X)return`For stor: forventede ${H??"value"} ${X.verb} ${K} ${W.maximum.toString()} ${X.unit??"elementer"}`;return`For stor: forventede ${H??"value"} havde ${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin),H=Q[W.origin]??W.origin;if(X)return`For lille: forventede ${H} ${X.verb} ${K} ${W.minimum.toString()} ${X.unit}`;return`For lille: forventede ${H} havde ${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ugyldig streng: skal starte med "${K.prefix}"`;if(K.format==="ends_with")return`Ugyldig streng: skal ende med "${K.suffix}"`;if(K.format==="includes")return`Ugyldig streng: skal indeholde "${K.includes}"`;if(K.format==="regex")return`Ugyldig streng: skal matche mønsteret ${K.pattern}`;return`Ugyldig ${J[K.format]??W.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${m(W.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${W.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${W.origin}`;default:return"Ugyldigt input"}}};function R1(){return{localeError:vB()}}var jB=()=>{let $={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function U(W){return $[W]??null}let J={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},Q={nan:"NaN",number:"Zahl",array:"Array"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ungültige Eingabe: erwartet instanceof ${W.expected}, erhalten ${H}`;return`Ungültige Eingabe: erwartet ${K}, erhalten ${H}`}case"invalid_value":if(W.values.length===1)return`Ungültige Eingabe: erwartet ${U$(W.values[0])}`;return`Ungültige Option: erwartet eine von ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Zu groß: erwartet, dass ${W.origin??"Wert"} ${K}${W.maximum.toString()} ${X.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${W.origin??"Wert"} ${K}${W.maximum.toString()} ist`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Zu klein: erwartet, dass ${W.origin} ${K}${W.minimum.toString()} ${X.unit} hat`;return`Zu klein: erwartet, dass ${W.origin} ${K}${W.minimum.toString()} ist`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ungültiger String: muss mit "${K.prefix}" beginnen`;if(K.format==="ends_with")return`Ungültiger String: muss mit "${K.suffix}" enden`;if(K.format==="includes")return`Ungültiger String: muss "${K.includes}" enthalten`;if(K.format==="regex")return`Ungültiger String: muss dem Muster ${K.pattern} entsprechen`;return`Ungültig: ${J[K.format]??W.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${W.divisor} sein`;case"unrecognized_keys":return`${W.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${m(W.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${W.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${W.origin}`;default:return"Ungültige Eingabe"}}};function V1(){return{localeError:jB()}}var gB=()=>{let $={string:{unit:"χαρακτήρες",verb:"να έχει"},file:{unit:"bytes",verb:"να έχει"},array:{unit:"στοιχεία",verb:"να έχει"},set:{unit:"στοιχεία",verb:"να έχει"},map:{unit:"καταχωρήσεις",verb:"να έχει"}};function U(W){return $[W]??null}let J={regex:"είσοδος",email:"διεύθυνση email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ημερομηνία και ώρα",date:"ISO ημερομηνία",time:"ISO ώρα",duration:"ISO διάρκεια",ipv4:"διεύθυνση IPv4",ipv6:"διεύθυνση IPv6",mac:"διεύθυνση MAC",cidrv4:"εύρος IPv4",cidrv6:"εύρος IPv6",base64:"συμβολοσειρά κωδικοποιημένη σε base64",base64url:"συμβολοσειρά κωδικοποιημένη σε base64url",json_string:"συμβολοσειρά JSON",e164:"αριθμός E.164",jwt:"JWT",template_literal:"είσοδος"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(typeof W.expected==="string"&&/^[A-Z]/.test(W.expected))return`Μη έγκυρη είσοδος: αναμενόταν instanceof ${W.expected}, λήφθηκε ${H}`;return`Μη έγκυρη είσοδος: αναμενόταν ${K}, λήφθηκε ${H}`}case"invalid_value":if(W.values.length===1)return`Μη έγκυρη είσοδος: αναμενόταν ${U$(W.values[0])}`;return`Μη έγκυρη επιλογή: αναμενόταν ένα από ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Πολύ μεγάλο: αναμενόταν ${W.origin??"τιμή"} να έχει ${K}${W.maximum.toString()} ${X.unit??"στοιχεία"}`;return`Πολύ μεγάλο: αναμενόταν ${W.origin??"τιμή"} να είναι ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Πολύ μικρό: αναμενόταν ${W.origin} να έχει ${K}${W.minimum.toString()} ${X.unit}`;return`Πολύ μικρό: αναμενόταν ${W.origin} να είναι ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${K.prefix}"`;if(K.format==="ends_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${K.suffix}"`;if(K.format==="includes")return`Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${K.includes}"`;if(K.format==="regex")return`Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${K.pattern}`;return`Μη έγκυρο: ${J[K.format]??W.format}`}case"not_multiple_of":return`Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${W.divisor}`;case"unrecognized_keys":return`Άγνωστ${W.keys.length>1?"α":"ο"} κλειδ${W.keys.length>1?"ιά":"ί"}: ${m(W.keys,", ")}`;case"invalid_key":return`Μη έγκυρο κλειδί στο ${W.origin}`;case"invalid_union":return"Μη έγκυρη είσοδος";case"invalid_element":return`Μη έγκυρη τιμή στο ${W.origin}`;default:return"Μη έγκυρη είσοδος"}}};function w1(){return{localeError:gB()}}var bB=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function U(W){return $[W]??null}let J={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;return`Invalid input: expected ${K}, received ${H}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${U$(W.values[0])}`;return`Invalid option: expected one of ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Too big: expected ${W.origin??"value"} to have ${K}${W.maximum.toString()} ${X.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Too small: expected ${W.origin} to have ${K}${W.minimum.toString()} ${X.unit}`;return`Too small: expected ${W.origin} to be ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Invalid string: must start with "${K.prefix}"`;if(K.format==="ends_with")return`Invalid string: must end with "${K.suffix}"`;if(K.format==="includes")return`Invalid string: must include "${K.includes}"`;if(K.format==="regex")return`Invalid string: must match pattern ${K.pattern}`;return`Invalid ${J[K.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":if(W.options&&Array.isArray(W.options)&&W.options.length>0)return`Invalid discriminator value. Expected ${W.options.map((X)=>`'${X}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function HQ(){return{localeError:bB()}}var yB=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function U(W){return $[W]??null}let J={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},Q={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Nevalida enigo: atendiĝis instanceof ${W.expected}, riceviĝis ${H}`;return`Nevalida enigo: atendiĝis ${K}, riceviĝis ${H}`}case"invalid_value":if(W.values.length===1)return`Nevalida enigo: atendiĝis ${U$(W.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Tro granda: atendiĝis ke ${W.origin??"valoro"} havu ${K}${W.maximum.toString()} ${X.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${W.origin??"valoro"} havu ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Tro malgranda: atendiĝis ke ${W.origin} havu ${K}${W.minimum.toString()} ${X.unit}`;return`Tro malgranda: atendiĝis ke ${W.origin} estu ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${K.prefix}"`;if(K.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${K.suffix}"`;if(K.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${K.includes}"`;if(K.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${K.pattern}`;return`Nevalida ${J[K.format]??W.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${W.divisor}`;case"unrecognized_keys":return`Nekonata${W.keys.length>1?"j":""} ŝlosilo${W.keys.length>1?"j":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${W.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${W.origin}`;default:return"Nevalida enigo"}}};function M1(){return{localeError:yB()}}var xB=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function U(W){return $[W]??null}let J={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},Q={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Entrada inválida: se esperaba instanceof ${W.expected}, recibido ${H}`;return`Entrada inválida: se esperaba ${K}, recibido ${H}`}case"invalid_value":if(W.values.length===1)return`Entrada inválida: se esperaba ${U$(W.values[0])}`;return`Opción inválida: se esperaba una de ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin),H=Q[W.origin]??W.origin;if(X)return`Demasiado grande: se esperaba que ${H??"valor"} tuviera ${K}${W.maximum.toString()} ${X.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${H??"valor"} fuera ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin),H=Q[W.origin]??W.origin;if(X)return`Demasiado pequeño: se esperaba que ${H} tuviera ${K}${W.minimum.toString()} ${X.unit}`;return`Demasiado pequeño: se esperaba que ${H} fuera ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Cadena inválida: debe comenzar con "${K.prefix}"`;if(K.format==="ends_with")return`Cadena inválida: debe terminar en "${K.suffix}"`;if(K.format==="includes")return`Cadena inválida: debe incluir "${K.includes}"`;if(K.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${K.pattern}`;return`Inválido ${J[K.format]??W.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${W.divisor}`;case"unrecognized_keys":return`Llave${W.keys.length>1?"s":""} desconocida${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Llave inválida en ${Q[W.origin]??W.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${Q[W.origin]??W.origin}`;default:return"Entrada inválida"}}};function B1(){return{localeError:xB()}}var hB=()=>{let $={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function U(W){return $[W]??null}let J={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},Q={nan:"NaN",number:"عدد",array:"آرایه"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`ورودی نامعتبر: میبایست instanceof ${W.expected} میبود، ${H} دریافت شد`;return`ورودی نامعتبر: میبایست ${K} میبود، ${H} دریافت شد`}case"invalid_value":if(W.values.length===1)return`ورودی نامعتبر: میبایست ${U$(W.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${m(W.values,"|")} میبود`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`خیلی بزرگ: ${W.origin??"مقدار"} باید ${K}${W.maximum.toString()} ${X.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${W.origin??"مقدار"} باید ${K}${W.maximum.toString()} باشد`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`خیلی کوچک: ${W.origin} باید ${K}${W.minimum.toString()} ${X.unit} باشد`;return`خیلی کوچک: ${W.origin} باید ${K}${W.minimum.toString()} باشد`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`رشته نامعتبر: باید با "${K.prefix}" شروع شود`;if(K.format==="ends_with")return`رشته نامعتبر: باید با "${K.suffix}" تمام شود`;if(K.format==="includes")return`رشته نامعتبر: باید شامل "${K.includes}" باشد`;if(K.format==="regex")return`رشته نامعتبر: باید با الگوی ${K.pattern} مطابقت داشته باشد`;return`${J[K.format]??W.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${W.divisor} باشد`;case"unrecognized_keys":return`کلید${W.keys.length>1?"های":""} ناشناس: ${m(W.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${W.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${W.origin}`;default:return"ورودی نامعتبر"}}};function P1(){return{localeError:hB()}}var fB=()=>{let $={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function U(W){return $[W]??null}let J={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Virheellinen tyyppi: odotettiin instanceof ${W.expected}, oli ${H}`;return`Virheellinen tyyppi: odotettiin ${K}, oli ${H}`}case"invalid_value":if(W.values.length===1)return`Virheellinen syöte: täytyy olla ${U$(W.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Liian suuri: ${X.subject} täytyy olla ${K}${W.maximum.toString()} ${X.unit}`.trim();return`Liian suuri: arvon täytyy olla ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Liian pieni: ${X.subject} täytyy olla ${K}${W.minimum.toString()} ${X.unit}`.trim();return`Liian pieni: arvon täytyy olla ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${K.prefix}"`;if(K.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${K.suffix}"`;if(K.format==="includes")return`Virheellinen syöte: täytyy sisältää "${K.includes}"`;if(K.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${K.pattern}`;return`Virheellinen ${J[K.format]??W.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${W.divisor} monikerta`;case"unrecognized_keys":return`${W.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${m(W.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function z1(){return{localeError:fB()}}var uB=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(W){return $[W]??null}let J={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},Q={string:"chaîne",number:"nombre",int:"entier",boolean:"booléen",bigint:"grand entier",symbol:"symbole",undefined:"indéfini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Entrée invalide : instanceof ${W.expected} attendu, ${H} reçu`;return`Entrée invalide : ${K} attendu, ${H} reçu`}case"invalid_value":if(W.values.length===1)return`Entrée invalide : ${U$(W.values[0])} attendu`;return`Option invalide : une valeur parmi ${m(W.values,"|")} attendue`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Trop grand : ${Q[W.origin]??"valeur"} doit ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"élément(s)"}`;return`Trop grand : ${Q[W.origin]??"valeur"} doit être ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Trop petit : ${Q[W.origin]??"valeur"} doit ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Trop petit : ${Q[W.origin]??"valeur"} doit être ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Chaîne invalide : doit commencer par "${K.prefix}"`;if(K.format==="ends_with")return`Chaîne invalide : doit se terminer par "${K.suffix}"`;if(K.format==="includes")return`Chaîne invalide : doit inclure "${K.includes}"`;if(K.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${K.pattern}`;return`${J[K.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${W.divisor}`;case"unrecognized_keys":return`Clé${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${m(W.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${W.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entrée invalide"}}};function _1(){return{localeError:uB()}}var lB=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function U(W){return $[W]??null}let J={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Entrée invalide : attendu instanceof ${W.expected}, reçu ${H}`;return`Entrée invalide : attendu ${K}, reçu ${H}`}case"invalid_value":if(W.values.length===1)return`Entrée invalide : attendu ${U$(W.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"≤":"<",X=U(W.origin);if(X)return`Trop grand : attendu que ${W.origin??"la valeur"} ait ${K}${W.maximum.toString()} ${X.unit}`;return`Trop grand : attendu que ${W.origin??"la valeur"} soit ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?"≥":">",X=U(W.origin);if(X)return`Trop petit : attendu que ${W.origin} ait ${K}${W.minimum.toString()} ${X.unit}`;return`Trop petit : attendu que ${W.origin} soit ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Chaîne invalide : doit commencer par "${K.prefix}"`;if(K.format==="ends_with")return`Chaîne invalide : doit se terminer par "${K.suffix}"`;if(K.format==="includes")return`Chaîne invalide : doit inclure "${K.includes}"`;if(K.format==="regex")return`Chaîne invalide : doit correspondre au motif ${K.pattern}`;return`${J[K.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${W.divisor}`;case"unrecognized_keys":return`Clé${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${m(W.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${W.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entrée invalide"}}};function A1(){return{localeError:lB()}}var mB=()=>{let $={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},U={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},J=(Y)=>Y?$[Y]:void 0,Q=(Y)=>{let G=J(Y);if(G)return G.label;return Y??$.unknown.label},W=(Y)=>`ה${Q(Y)}`,K=(Y)=>{return(J(Y)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},X=(Y)=>{if(!Y)return null;return U[Y]??null},H={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},N={nan:"NaN"};return(Y)=>{switch(Y.code){case"invalid_type":{let G=Y.expected,O=N[G??""]??Q(G),E=W$(Y.input),k=N[E]??$[E]?.label??E;if(/^[A-Z]/.test(Y.expected))return`קלט לא תקין: צריך להיות instanceof ${Y.expected}, התקבל ${k}`;return`קלט לא תקין: צריך להיות ${O}, התקבל ${k}`}case"invalid_value":{if(Y.values.length===1)return`ערך לא תקין: הערך חייב להיות ${U$(Y.values[0])}`;let G=Y.values.map((k)=>U$(k));if(Y.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${G[0]} או ${G[1]}`;let O=G[G.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${G.slice(0,-1).join(", ")} או ${O}`}case"too_big":{let G=X(Y.origin),O=W(Y.origin??"value");if(Y.origin==="string")return`${G?.longLabel??"ארוך"} מדי: ${O} צריכה להכיל ${Y.maximum.toString()} ${G?.unit??""} ${Y.inclusive?"או פחות":"לכל היותר"}`.trim();if(Y.origin==="number"){let I=Y.inclusive?`קטן או שווה ל-${Y.maximum}`:`קטן מ-${Y.maximum}`;return`גדול מדי: ${O} צריך להיות ${I}`}if(Y.origin==="array"||Y.origin==="set"){let I=Y.origin==="set"?"צריכה":"צריך",R=Y.inclusive?`${Y.maximum} ${G?.unit??""} או פחות`:`פחות מ-${Y.maximum} ${G?.unit??""}`;return`גדול מדי: ${O} ${I} להכיל ${R}`.trim()}let E=Y.inclusive?"<=":"<",k=K(Y.origin??"value");if(G?.unit)return`${G.longLabel} מדי: ${O} ${k} ${E}${Y.maximum.toString()} ${G.unit}`;return`${G?.longLabel??"גדול"} מדי: ${O} ${k} ${E}${Y.maximum.toString()}`}case"too_small":{let G=X(Y.origin),O=W(Y.origin??"value");if(Y.origin==="string")return`${G?.shortLabel??"קצר"} מדי: ${O} צריכה להכיל ${Y.minimum.toString()} ${G?.unit??""} ${Y.inclusive?"או יותר":"לפחות"}`.trim();if(Y.origin==="number"){let I=Y.inclusive?`גדול או שווה ל-${Y.minimum}`:`גדול מ-${Y.minimum}`;return`קטן מדי: ${O} צריך להיות ${I}`}if(Y.origin==="array"||Y.origin==="set"){let I=Y.origin==="set"?"צריכה":"צריך";if(Y.minimum===1&&Y.inclusive){let q=Y.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${O} ${I} להכיל ${q}`}let R=Y.inclusive?`${Y.minimum} ${G?.unit??""} או יותר`:`יותר מ-${Y.minimum} ${G?.unit??""}`;return`קטן מדי: ${O} ${I} להכיל ${R}`.trim()}let E=Y.inclusive?">=":">",k=K(Y.origin??"value");if(G?.unit)return`${G.shortLabel} מדי: ${O} ${k} ${E}${Y.minimum.toString()} ${G.unit}`;return`${G?.shortLabel??"קטן"} מדי: ${O} ${k} ${E}${Y.minimum.toString()}`}case"invalid_format":{let G=Y;if(G.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${G.prefix}"`;if(G.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${G.suffix}"`;if(G.format==="includes")return`המחרוזת חייבת לכלול "${G.includes}"`;if(G.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${G.pattern}`;let O=H[G.format],E=O?.label??G.format,I=(O?.gender??"m")==="f"?"תקינה":"תקין";return`${E} לא ${I}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${Y.divisor}`;case"unrecognized_keys":return`מפתח${Y.keys.length>1?"ות":""} לא מזוה${Y.keys.length>1?"ים":"ה"}: ${m(Y.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${W(Y.origin??"array")}`;default:return"קלט לא תקין"}}};function C1(){return{localeError:mB()}}var pB=()=>{let $={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function U(W){return $[W]??null}let J={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},Q={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Neispravan unos: očekuje se instanceof ${W.expected}, a primljeno je ${H}`;return`Neispravan unos: očekuje se ${K}, a primljeno je ${H}`}case"invalid_value":if(W.values.length===1)return`Neispravna vrijednost: očekivano ${U$(W.values[0])}`;return`Neispravna opcija: očekivano jedno od ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin),H=Q[W.origin]??W.origin;if(X)return`Preveliko: očekivano da ${H??"vrijednost"} ima ${K}${W.maximum.toString()} ${X.unit??"elemenata"}`;return`Preveliko: očekivano da ${H??"vrijednost"} bude ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin),H=Q[W.origin]??W.origin;if(X)return`Premalo: očekivano da ${H} ima ${K}${W.minimum.toString()} ${X.unit}`;return`Premalo: očekivano da ${H} bude ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Neispravan tekst: mora započinjati s "${K.prefix}"`;if(K.format==="ends_with")return`Neispravan tekst: mora završavati s "${K.suffix}"`;if(K.format==="includes")return`Neispravan tekst: mora sadržavati "${K.includes}"`;if(K.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${K.pattern}`;return`Neispravna ${J[K.format]??W.format}`}case"not_multiple_of":return`Neispravan broj: mora biti višekratnik od ${W.divisor}`;case"unrecognized_keys":return`Neprepoznat${W.keys.length>1?"i ključevi":" ključ"}: ${m(W.keys,", ")}`;case"invalid_key":return`Neispravan ključ u ${Q[W.origin]??W.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${Q[W.origin]??W.origin}`;default:return"Neispravan unos"}}};function S1(){return{localeError:pB()}}var dB=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function U(W){return $[W]??null}let J={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},Q={nan:"NaN",number:"szám",array:"tömb"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Érvénytelen bemenet: a várt érték instanceof ${W.expected}, a kapott érték ${H}`;return`Érvénytelen bemenet: a várt érték ${K}, a kapott érték ${H}`}case"invalid_value":if(W.values.length===1)return`Érvénytelen bemenet: a várt érték ${U$(W.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Túl nagy: ${W.origin??"érték"} mérete túl nagy ${K}${W.maximum.toString()} ${X.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${W.origin??"érték"} túl nagy: ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Túl kicsi: a bemeneti érték ${W.origin} mérete túl kicsi ${K}${W.minimum.toString()} ${X.unit}`;return`Túl kicsi: a bemeneti érték ${W.origin} túl kicsi ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Érvénytelen string: "${K.prefix}" értékkel kell kezdődnie`;if(K.format==="ends_with")return`Érvénytelen string: "${K.suffix}" értékkel kell végződnie`;if(K.format==="includes")return`Érvénytelen string: "${K.includes}" értéket kell tartalmaznia`;if(K.format==="regex")return`Érvénytelen string: ${K.pattern} mintának kell megfelelnie`;return`Érvénytelen ${J[K.format]??W.format}`}case"not_multiple_of":return`Érvénytelen szám: ${W.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${W.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${W.origin}`;default:return"Érvénytelen bemenet"}}};function T1(){return{localeError:dB()}}function sI($,U,J){return Math.abs($)===1?U:J}function u8($){if(!$)return"";let U=["ա","ե","ը","ի","ո","ու","օ"],J=$[$.length-1];return $+(U.includes(J)?"ն":"ը")}var cB=()=>{let $={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function U(W){return $[W]??null}let J={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},Q={nan:"NaN",number:"թիվ",array:"զանգված"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${W.expected}, ստացվել է ${H}`;return`Սխալ մուտքագրում․ սպասվում էր ${K}, ստացվել է ${H}`}case"invalid_value":if(W.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${U$(W.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X){let H=Number(W.maximum),N=sI(H,X.unit.one,X.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${u8(W.origin??"արժեք")} կունենա ${K}${W.maximum.toString()} ${N}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${u8(W.origin??"արժեք")} լինի ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X){let H=Number(W.minimum),N=sI(H,X.unit.one,X.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${u8(W.origin)} կունենա ${K}${W.minimum.toString()} ${N}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${u8(W.origin)} լինի ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${K.prefix}"-ով`;if(K.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${K.suffix}"-ով`;if(K.format==="includes")return`Սխալ տող․ պետք է պարունակի "${K.includes}"`;if(K.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${K.pattern} ձևաչափին`;return`Սխալ ${J[K.format]??W.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${W.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${W.keys.length>1?"ներ":""}. ${m(W.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${u8(W.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${u8(W.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function v1(){return{localeError:cB()}}var nB=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function U(W){return $[W]??null}let J={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Input tidak valid: diharapkan instanceof ${W.expected}, diterima ${H}`;return`Input tidak valid: diharapkan ${K}, diterima ${H}`}case"invalid_value":if(W.values.length===1)return`Input tidak valid: diharapkan ${U$(W.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Terlalu besar: diharapkan ${W.origin??"value"} memiliki ${K}${W.maximum.toString()} ${X.unit??"elemen"}`;return`Terlalu besar: diharapkan ${W.origin??"value"} menjadi ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Terlalu kecil: diharapkan ${W.origin} memiliki ${K}${W.minimum.toString()} ${X.unit}`;return`Terlalu kecil: diharapkan ${W.origin} menjadi ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`String tidak valid: harus dimulai dengan "${K.prefix}"`;if(K.format==="ends_with")return`String tidak valid: harus berakhir dengan "${K.suffix}"`;if(K.format==="includes")return`String tidak valid: harus menyertakan "${K.includes}"`;if(K.format==="regex")return`String tidak valid: harus sesuai pola ${K.pattern}`;return`${J[K.format]??W.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${W.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${W.origin}`;default:return"Input tidak valid"}}};function j1(){return{localeError:nB()}}var iB=()=>{let $={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function U(W){return $[W]??null}let J={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},Q={nan:"NaN",number:"númer",array:"fylki"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Rangt gildi: Þú slóst inn ${H} þar sem á að vera instanceof ${W.expected}`;return`Rangt gildi: Þú slóst inn ${H} þar sem á að vera ${K}`}case"invalid_value":if(W.values.length===1)return`Rangt gildi: gert ráð fyrir ${U$(W.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Of stórt: gert er ráð fyrir að ${W.origin??"gildi"} hafi ${K}${W.maximum.toString()} ${X.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${W.origin??"gildi"} sé ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Of lítið: gert er ráð fyrir að ${W.origin} hafi ${K}${W.minimum.toString()} ${X.unit}`;return`Of lítið: gert er ráð fyrir að ${W.origin} sé ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ógildur strengur: verður að byrja á "${K.prefix}"`;if(K.format==="ends_with")return`Ógildur strengur: verður að enda á "${K.suffix}"`;if(K.format==="includes")return`Ógildur strengur: verður að innihalda "${K.includes}"`;if(K.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${K.pattern}`;return`Rangt ${J[K.format]??W.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${W.divisor}`;case"unrecognized_keys":return`Óþekkt ${W.keys.length>1?"ir lyklar":"ur lykill"}: ${m(W.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${W.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${W.origin}`;default:return"Rangt gildi"}}};function g1(){return{localeError:iB()}}var oB=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function U(W){return $[W]??null}let J={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"numero",array:"vettore"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Input non valido: atteso instanceof ${W.expected}, ricevuto ${H}`;return`Input non valido: atteso ${K}, ricevuto ${H}`}case"invalid_value":if(W.values.length===1)return`Input non valido: atteso ${U$(W.values[0])}`;return`Opzione non valida: atteso uno tra ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Troppo grande: ${W.origin??"valore"} deve avere ${K}${W.maximum.toString()} ${X.unit??"elementi"}`;return`Troppo grande: ${W.origin??"valore"} deve essere ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Troppo piccolo: ${W.origin} deve avere ${K}${W.minimum.toString()} ${X.unit}`;return`Troppo piccolo: ${W.origin} deve essere ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Stringa non valida: deve iniziare con "${K.prefix}"`;if(K.format==="ends_with")return`Stringa non valida: deve terminare con "${K.suffix}"`;if(K.format==="includes")return`Stringa non valida: deve includere "${K.includes}"`;if(K.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${K.pattern}`;return`Input non valido: ${J[K.format]??W.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${W.divisor}`;case"unrecognized_keys":return`Chiav${W.keys.length>1?"i":"e"} non riconosciut${W.keys.length>1?"e":"a"}: ${m(W.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${W.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${W.origin}`;default:return"Input non valido"}}};function b1(){return{localeError:oB()}}var rB=()=>{let $={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function U(W){return $[W]??null}let J={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},Q={nan:"NaN",number:"数値",array:"配列"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`無効な入力: instanceof ${W.expected}が期待されましたが、${H}が入力されました`;return`無効な入力: ${K}が期待されましたが、${H}が入力されました`}case"invalid_value":if(W.values.length===1)return`無効な入力: ${U$(W.values[0])}が期待されました`;return`無効な選択: ${m(W.values,"、")}のいずれかである必要があります`;case"too_big":{let K=W.inclusive?"以下である":"より小さい",X=U(W.origin);if(X)return`大きすぎる値: ${W.origin??"値"}は${W.maximum.toString()}${X.unit??"要素"}${K}必要があります`;return`大きすぎる値: ${W.origin??"値"}は${W.maximum.toString()}${K}必要があります`}case"too_small":{let K=W.inclusive?"以上である":"より大きい",X=U(W.origin);if(X)return`小さすぎる値: ${W.origin}は${W.minimum.toString()}${X.unit}${K}必要があります`;return`小さすぎる値: ${W.origin}は${W.minimum.toString()}${K}必要があります`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`無効な文字列: "${K.prefix}"で始まる必要があります`;if(K.format==="ends_with")return`無効な文字列: "${K.suffix}"で終わる必要があります`;if(K.format==="includes")return`無効な文字列: "${K.includes}"を含む必要があります`;if(K.format==="regex")return`無効な文字列: パターン${K.pattern}に一致する必要があります`;return`無効な${J[K.format]??W.format}`}case"not_multiple_of":return`無効な数値: ${W.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${W.keys.length>1?"群":""}: ${m(W.keys,"、")}`;case"invalid_key":return`${W.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${W.origin}内の無効な値`;default:return"無効な入力"}}};function y1(){return{localeError:rB()}}var aB=()=>{let $={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function U(W){return $[W]??null}let J={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული ველი",base64url:"base64url-კოდირებული ველი",json_string:"JSON ველი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},Q={nan:"NaN",number:"რიცხვი",string:"ველი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${W.expected}, მიღებული ${H}`;return`არასწორი შეყვანა: მოსალოდნელი ${K}, მიღებული ${H}`}case"invalid_value":if(W.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${U$(W.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${m(W.values,"|")}-დან`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`ზედმეტად დიდი: მოსალოდნელი ${W.origin??"მნიშვნელობა"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${W.origin??"მნიშვნელობა"} იყოს ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`ზედმეტად პატარა: მოსალოდნელი ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${W.origin} იყოს ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`არასწორი ველი: უნდა იწყებოდეს "${K.prefix}"-ით`;if(K.format==="ends_with")return`არასწორი ველი: უნდა მთავრდებოდეს "${K.suffix}"-ით`;if(K.format==="includes")return`არასწორი ველი: უნდა შეიცავდეს "${K.includes}"-ს`;if(K.format==="regex")return`არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${K.pattern}`;return`არასწორი ${J[K.format]??W.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${W.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${W.keys.length>1?"ები":"ი"}: ${m(W.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${W.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${W.origin}-ში`;default:return"არასწორი შეყვანა"}}};function x1(){return{localeError:aB()}}var sB=()=>{let $={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function U(W){return $[W]??null}let J={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},Q={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${W.expected} ប៉ុន្តែទទួលបាន ${H}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${K} ប៉ុន្តែទទួលបាន ${H}`}case"invalid_value":if(W.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${U$(W.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`ធំពេក៖ ត្រូវការ ${W.origin??"តម្លៃ"} ${K} ${W.maximum.toString()} ${X.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${W.origin??"តម្លៃ"} ${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`តូចពេក៖ ត្រូវការ ${W.origin} ${K} ${W.minimum.toString()} ${X.unit}`;return`តូចពេក៖ ត្រូវការ ${W.origin} ${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${K.prefix}"`;if(K.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${K.suffix}"`;if(K.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${K.includes}"`;if(K.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${K.pattern}`;return`មិនត្រឹមត្រូវ៖ ${J[K.format]??W.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${W.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${m(W.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${W.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${W.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function NQ(){return{localeError:sB()}}function h1(){return NQ()}var tB=()=>{let $={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function U(W){return $[W]??null}let J={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`잘못된 입력: 예상 타입은 instanceof ${W.expected}, 받은 타입은 ${H}입니다`;return`잘못된 입력: 예상 타입은 ${K}, 받은 타입은 ${H}입니다`}case"invalid_value":if(W.values.length===1)return`잘못된 입력: 값은 ${U$(W.values[0])} 이어야 합니다`;return`잘못된 옵션: ${m(W.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let K=W.inclusive?"이하":"미만",X=K==="미만"?"이어야 합니다":"여야 합니다",H=U(W.origin),N=H?.unit??"요소";if(H)return`${W.origin??"값"}이 너무 큽니다: ${W.maximum.toString()}${N} ${K}${X}`;return`${W.origin??"값"}이 너무 큽니다: ${W.maximum.toString()} ${K}${X}`}case"too_small":{let K=W.inclusive?"이상":"초과",X=K==="이상"?"이어야 합니다":"여야 합니다",H=U(W.origin),N=H?.unit??"요소";if(H)return`${W.origin??"값"}이 너무 작습니다: ${W.minimum.toString()}${N} ${K}${X}`;return`${W.origin??"값"}이 너무 작습니다: ${W.minimum.toString()} ${K}${X}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`잘못된 문자열: "${K.prefix}"(으)로 시작해야 합니다`;if(K.format==="ends_with")return`잘못된 문자열: "${K.suffix}"(으)로 끝나야 합니다`;if(K.format==="includes")return`잘못된 문자열: "${K.includes}"을(를) 포함해야 합니다`;if(K.format==="regex")return`잘못된 문자열: 정규식 ${K.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${J[K.format]??W.format}`}case"not_multiple_of":return`잘못된 숫자: ${W.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${m(W.keys,", ")}`;case"invalid_key":return`잘못된 키: ${W.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${W.origin}`;default:return"잘못된 입력"}}};function f1(){return{localeError:tB()}}var YQ=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function tI($){let U=Math.abs($),J=U%10,Q=U%100;if(Q>=11&&Q<=19||J===0)return"many";if(J===1)return"one";return"few"}var eB=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function U(W,K,X,H){let N=$[W]??null;if(N===null)return N;return{unit:N.unit[K],verb:N.verb[H][X?"inclusive":"notInclusive"]}}let J={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},Q={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Gautas tipas ${H}, o tikėtasi - instanceof ${W.expected}`;return`Gautas tipas ${H}, o tikėtasi - ${K}`}case"invalid_value":if(W.values.length===1)return`Privalo būti ${U$(W.values[0])}`;return`Privalo būti vienas iš ${m(W.values,"|")} pasirinkimų`;case"too_big":{let K=Q[W.origin]??W.origin,X=U(W.origin,tI(Number(W.maximum)),W.inclusive??!1,"smaller");if(X?.verb)return`${YQ(K??W.origin??"reikšmė")} ${X.verb} ${W.maximum.toString()} ${X.unit??"elementų"}`;let H=W.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${YQ(K??W.origin??"reikšmė")} turi būti ${H} ${W.maximum.toString()} ${X?.unit}`}case"too_small":{let K=Q[W.origin]??W.origin,X=U(W.origin,tI(Number(W.minimum)),W.inclusive??!1,"bigger");if(X?.verb)return`${YQ(K??W.origin??"reikšmė")} ${X.verb} ${W.minimum.toString()} ${X.unit??"elementų"}`;let H=W.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${YQ(K??W.origin??"reikšmė")} turi būti ${H} ${W.minimum.toString()} ${X?.unit}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Eilutė privalo prasidėti "${K.prefix}"`;if(K.format==="ends_with")return`Eilutė privalo pasibaigti "${K.suffix}"`;if(K.format==="includes")return`Eilutė privalo įtraukti "${K.includes}"`;if(K.format==="regex")return`Eilutė privalo atitikti ${K.pattern}`;return`Neteisingas ${J[K.format]??W.format}`}case"not_multiple_of":return`Skaičius privalo būti ${W.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${W.keys.length>1?"i":"as"} rakt${W.keys.length>1?"ai":"as"}: ${m(W.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let K=Q[W.origin]??W.origin;return`${YQ(K??W.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function u1(){return{localeError:eB()}}var $P=()=>{let $={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function U(W){return $[W]??null}let J={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},Q={nan:"NaN",number:"број",array:"низа"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Грешен внес: се очекува instanceof ${W.expected}, примено ${H}`;return`Грешен внес: се очекува ${K}, примено ${H}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${U$(W.values[0])}`;return`Грешана опција: се очекува една ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Премногу голем: се очекува ${W.origin??"вредноста"} да има ${K}${W.maximum.toString()} ${X.unit??"елементи"}`;return`Премногу голем: се очекува ${W.origin??"вредноста"} да биде ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Премногу мал: се очекува ${W.origin} да има ${K}${W.minimum.toString()} ${X.unit}`;return`Премногу мал: се очекува ${W.origin} да биде ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Неважечка низа: мора да започнува со "${K.prefix}"`;if(K.format==="ends_with")return`Неважечка низа: мора да завршува со "${K.suffix}"`;if(K.format==="includes")return`Неважечка низа: мора да вклучува "${K.includes}"`;if(K.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${K.pattern}`;return`Invalid ${J[K.format]??W.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${m(W.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${W.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${W.origin}`;default:return"Грешен внес"}}};function l1(){return{localeError:$P()}}var UP=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function U(W){return $[W]??null}let J={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"nombor"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Input tidak sah: dijangka instanceof ${W.expected}, diterima ${H}`;return`Input tidak sah: dijangka ${K}, diterima ${H}`}case"invalid_value":if(W.values.length===1)return`Input tidak sah: dijangka ${U$(W.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Terlalu besar: dijangka ${W.origin??"nilai"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"elemen"}`;return`Terlalu besar: dijangka ${W.origin??"nilai"} adalah ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Terlalu kecil: dijangka ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Terlalu kecil: dijangka ${W.origin} adalah ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`String tidak sah: mesti bermula dengan "${K.prefix}"`;if(K.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${K.suffix}"`;if(K.format==="includes")return`String tidak sah: mesti mengandungi "${K.includes}"`;if(K.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${K.pattern}`;return`${J[K.format]??W.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${m(W.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${W.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${W.origin}`;default:return"Input tidak sah"}}};function m1(){return{localeError:UP()}}var JP=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function U(W){return $[W]??null}let J={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},Q={nan:"NaN",number:"getal"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ongeldige invoer: verwacht instanceof ${W.expected}, ontving ${H}`;return`Ongeldige invoer: verwacht ${K}, ontving ${H}`}case"invalid_value":if(W.values.length===1)return`Ongeldige invoer: verwacht ${U$(W.values[0])}`;return`Ongeldige optie: verwacht één van ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin),H=W.origin==="date"?"laat":W.origin==="string"?"lang":"groot";if(X)return`Te ${H}: verwacht dat ${W.origin??"waarde"} ${K}${W.maximum.toString()} ${X.unit??"elementen"} ${X.verb}`;return`Te ${H}: verwacht dat ${W.origin??"waarde"} ${K}${W.maximum.toString()} is`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin),H=W.origin==="date"?"vroeg":W.origin==="string"?"kort":"klein";if(X)return`Te ${H}: verwacht dat ${W.origin} ${K}${W.minimum.toString()} ${X.unit} ${X.verb}`;return`Te ${H}: verwacht dat ${W.origin} ${K}${W.minimum.toString()} is`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ongeldige tekst: moet met "${K.prefix}" beginnen`;if(K.format==="ends_with")return`Ongeldige tekst: moet op "${K.suffix}" eindigen`;if(K.format==="includes")return`Ongeldige tekst: moet "${K.includes}" bevatten`;if(K.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${K.pattern}`;return`Ongeldig: ${J[K.format]??W.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${W.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${W.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${W.origin}`;default:return"Ongeldige invoer"}}};function p1(){return{localeError:JP()}}var WP=()=>{let $={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function U(W){return $[W]??null}let J={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"tall",array:"liste"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ugyldig input: forventet instanceof ${W.expected}, fikk ${H}`;return`Ugyldig input: forventet ${K}, fikk ${H}`}case"invalid_value":if(W.values.length===1)return`Ugyldig verdi: forventet ${U$(W.values[0])}`;return`Ugyldig valg: forventet en av ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`For stor(t): forventet ${W.origin??"value"} til å ha ${K}${W.maximum.toString()} ${X.unit??"elementer"}`;return`For stor(t): forventet ${W.origin??"value"} til å ha ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`For lite(n): forventet ${W.origin} til å ha ${K}${W.minimum.toString()} ${X.unit}`;return`For lite(n): forventet ${W.origin} til å ha ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ugyldig streng: må starte med "${K.prefix}"`;if(K.format==="ends_with")return`Ugyldig streng: må ende med "${K.suffix}"`;if(K.format==="includes")return`Ugyldig streng: må inneholde "${K.includes}"`;if(K.format==="regex")return`Ugyldig streng: må matche mønsteret ${K.pattern}`;return`Ugyldig ${J[K.format]??W.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${m(W.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${W.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${W.origin}`;default:return"Ugyldig input"}}};function d1(){return{localeError:WP()}}var QP=()=>{let $={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function U(W){return $[W]??null}let J={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},Q={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Fâsit giren: umulan instanceof ${W.expected}, alınan ${H}`;return`Fâsit giren: umulan ${K}, alınan ${H}`}case"invalid_value":if(W.values.length===1)return`Fâsit giren: umulan ${U$(W.values[0])}`;return`Fâsit tercih: mûteberler ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Fazla büyük: ${W.origin??"value"}, ${K}${W.maximum.toString()} ${X.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${W.origin??"value"}, ${K}${W.maximum.toString()} olmalıydı.`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Fazla küçük: ${W.origin}, ${K}${W.minimum.toString()} ${X.unit} sahip olmalıydı.`;return`Fazla küçük: ${W.origin}, ${K}${W.minimum.toString()} olmalıydı.`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Fâsit metin: "${K.prefix}" ile başlamalı.`;if(K.format==="ends_with")return`Fâsit metin: "${K.suffix}" ile bitmeli.`;if(K.format==="includes")return`Fâsit metin: "${K.includes}" ihtivâ etmeli.`;if(K.format==="regex")return`Fâsit metin: ${K.pattern} nakşına uymalı.`;return`Fâsit ${J[K.format]??W.format}`}case"not_multiple_of":return`Fâsit sayı: ${W.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${W.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function c1(){return{localeError:QP()}}var KP=()=>{let $={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function U(W){return $[W]??null}let J={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},Q={nan:"NaN",number:"عدد",array:"ارې"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`ناسم ورودي: باید instanceof ${W.expected} وای, مګر ${H} ترلاسه شو`;return`ناسم ورودي: باید ${K} وای, مګر ${H} ترلاسه شو`}case"invalid_value":if(W.values.length===1)return`ناسم ورودي: باید ${U$(W.values[0])} وای`;return`ناسم انتخاب: باید یو له ${m(W.values,"|")} څخه وای`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`ډیر لوی: ${W.origin??"ارزښت"} باید ${K}${W.maximum.toString()} ${X.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${W.origin??"ارزښت"} باید ${K}${W.maximum.toString()} وي`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`ډیر کوچنی: ${W.origin} باید ${K}${W.minimum.toString()} ${X.unit} ولري`;return`ډیر کوچنی: ${W.origin} باید ${K}${W.minimum.toString()} وي`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`ناسم متن: باید د "${K.prefix}" سره پیل شي`;if(K.format==="ends_with")return`ناسم متن: باید د "${K.suffix}" سره پای ته ورسيږي`;if(K.format==="includes")return`ناسم متن: باید "${K.includes}" ولري`;if(K.format==="regex")return`ناسم متن: باید د ${K.pattern} سره مطابقت ولري`;return`${J[K.format]??W.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${W.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${W.keys.length>1?"کلیډونه":"کلیډ"}: ${m(W.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${W.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${W.origin} کې`;default:return"ناسمه ورودي"}}};function n1(){return{localeError:KP()}}var XP=()=>{let $={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function U(W){return $[W]??null}let J={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},Q={nan:"NaN",number:"liczba",array:"tablica"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${W.expected}, otrzymano ${H}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${K}, otrzymano ${H}`}case"invalid_value":if(W.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${U$(W.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Za duża wartość: oczekiwano, że ${W.origin??"wartość"} będzie mieć ${K}${W.maximum.toString()} ${X.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${W.origin??"wartość"} będzie wynosić ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Za mała wartość: oczekiwano, że ${W.origin??"wartość"} będzie mieć ${K}${W.minimum.toString()} ${X.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${W.origin??"wartość"} będzie wynosić ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${K.prefix}"`;if(K.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${K.suffix}"`;if(K.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${K.includes}"`;if(K.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${K.pattern}`;return`Nieprawidłow(y/a/e) ${J[K.format]??W.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${W.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${W.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${W.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function i1(){return{localeError:XP()}}var HP=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function U(W){return $[W]??null}let J={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},Q={nan:"NaN",number:"número",null:"nulo"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Tipo inválido: esperado instanceof ${W.expected}, recebido ${H}`;return`Tipo inválido: esperado ${K}, recebido ${H}`}case"invalid_value":if(W.values.length===1)return`Entrada inválida: esperado ${U$(W.values[0])}`;return`Opção inválida: esperada uma das ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Muito grande: esperado que ${W.origin??"valor"} tivesse ${K}${W.maximum.toString()} ${X.unit??"elementos"}`;return`Muito grande: esperado que ${W.origin??"valor"} fosse ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Muito pequeno: esperado que ${W.origin} tivesse ${K}${W.minimum.toString()} ${X.unit}`;return`Muito pequeno: esperado que ${W.origin} fosse ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Texto inválido: deve começar com "${K.prefix}"`;if(K.format==="ends_with")return`Texto inválido: deve terminar com "${K.suffix}"`;if(K.format==="includes")return`Texto inválido: deve incluir "${K.includes}"`;if(K.format==="regex")return`Texto inválido: deve corresponder ao padrão ${K.pattern}`;return`${J[K.format]??W.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${W.divisor}`;case"unrecognized_keys":return`Chave${W.keys.length>1?"s":""} desconhecida${W.keys.length>1?"s":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Chave inválida em ${W.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${W.origin}`;default:return"Campo inválido"}}};function o1(){return{localeError:HP()}}var NP=()=>{let $={string:{unit:"caractere",verb:"să aibă"},file:{unit:"octeți",verb:"să aibă"},array:{unit:"elemente",verb:"să aibă"},set:{unit:"elemente",verb:"să aibă"},map:{unit:"intrări",verb:"să aibă"}};function U(W){return $[W]??null}let J={regex:"intrare",email:"adresă de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dată și oră ISO",date:"dată ISO",time:"oră ISO",duration:"durată ISO",ipv4:"adresă IPv4",ipv6:"adresă IPv6",mac:"adresă MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"șir codat base64",base64url:"șir codat base64url",json_string:"șir JSON",e164:"număr E.164",jwt:"JWT",template_literal:"intrare"},Q={nan:"NaN",string:"șir",number:"număr",boolean:"boolean",function:"funcție",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"număr mare",void:"void",never:"never",map:"hartă",set:"set"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;return`Intrare invalidă: așteptat ${K}, primit ${H}`}case"invalid_value":if(W.values.length===1)return`Intrare invalidă: așteptat ${U$(W.values[0])}`;return`Opțiune invalidă: așteptat una dintre ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Prea mare: așteptat ca ${W.origin??"valoarea"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"elemente"}`;return`Prea mare: așteptat ca ${W.origin??"valoarea"} să fie ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Prea mic: așteptat ca ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Prea mic: așteptat ca ${W.origin} să fie ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Șir invalid: trebuie să înceapă cu "${K.prefix}"`;if(K.format==="ends_with")return`Șir invalid: trebuie să se termine cu "${K.suffix}"`;if(K.format==="includes")return`Șir invalid: trebuie să includă "${K.includes}"`;if(K.format==="regex")return`Șir invalid: trebuie să se potrivească cu modelul ${K.pattern}`;return`Format invalid: ${J[K.format]??W.format}`}case"not_multiple_of":return`Număr invalid: trebuie să fie multiplu de ${W.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${m(W.keys,", ")}`;case"invalid_key":return`Cheie invalidă în ${W.origin}`;case"invalid_union":return"Intrare invalidă";case"invalid_element":return`Valoare invalidă în ${W.origin}`;default:return"Intrare invalidă"}}};function r1(){return{localeError:NP()}}function eI($,U,J,Q){let W=Math.abs($),K=W%10,X=W%100;if(X>=11&&X<=19)return Q;if(K===1)return U;if(K>=2&&K<=4)return J;return Q}var YP=()=>{let $={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function U(W){return $[W]??null}let J={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},Q={nan:"NaN",number:"число",array:"массив"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Неверный ввод: ожидалось instanceof ${W.expected}, получено ${H}`;return`Неверный ввод: ожидалось ${K}, получено ${H}`}case"invalid_value":if(W.values.length===1)return`Неверный ввод: ожидалось ${U$(W.values[0])}`;return`Неверный вариант: ожидалось одно из ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X){let H=Number(W.maximum),N=eI(H,X.unit.one,X.unit.few,X.unit.many);return`Слишком большое значение: ожидалось, что ${W.origin??"значение"} будет иметь ${K}${W.maximum.toString()} ${N}`}return`Слишком большое значение: ожидалось, что ${W.origin??"значение"} будет ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X){let H=Number(W.minimum),N=eI(H,X.unit.one,X.unit.few,X.unit.many);return`Слишком маленькое значение: ожидалось, что ${W.origin} будет иметь ${K}${W.minimum.toString()} ${N}`}return`Слишком маленькое значение: ожидалось, что ${W.origin} будет ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Неверная строка: должна начинаться с "${K.prefix}"`;if(K.format==="ends_with")return`Неверная строка: должна заканчиваться на "${K.suffix}"`;if(K.format==="includes")return`Неверная строка: должна содержать "${K.includes}"`;if(K.format==="regex")return`Неверная строка: должна соответствовать шаблону ${K.pattern}`;return`Неверный ${J[K.format]??W.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${W.divisor}`;case"unrecognized_keys":return`Нераспознанн${W.keys.length>1?"ые":"ый"} ключ${W.keys.length>1?"и":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${W.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${W.origin}`;default:return"Неверные входные данные"}}};function a1(){return{localeError:YP()}}var GP=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function U(W){return $[W]??null}let J={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},Q={nan:"NaN",number:"število",array:"tabela"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Neveljaven vnos: pričakovano instanceof ${W.expected}, prejeto ${H}`;return`Neveljaven vnos: pričakovano ${K}, prejeto ${H}`}case"invalid_value":if(W.values.length===1)return`Neveljaven vnos: pričakovano ${U$(W.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Preveliko: pričakovano, da bo ${W.origin??"vrednost"} imelo ${K}${W.maximum.toString()} ${X.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${W.origin??"vrednost"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Premajhno: pričakovano, da bo ${W.origin} imelo ${K}${W.minimum.toString()} ${X.unit}`;return`Premajhno: pričakovano, da bo ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Neveljaven niz: mora se začeti z "${K.prefix}"`;if(K.format==="ends_with")return`Neveljaven niz: mora se končati z "${K.suffix}"`;if(K.format==="includes")return`Neveljaven niz: mora vsebovati "${K.includes}"`;if(K.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${K.pattern}`;return`Neveljaven ${J[K.format]??W.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${W.divisor}`;case"unrecognized_keys":return`Neprepoznan${W.keys.length>1?"i ključi":" ključ"}: ${m(W.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${W.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${W.origin}`;default:return"Neveljaven vnos"}}};function s1(){return{localeError:GP()}}var OP=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function U(W){return $[W]??null}let J={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},Q={nan:"NaN",number:"antal",array:"lista"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ogiltig inmatning: förväntat instanceof ${W.expected}, fick ${H}`;return`Ogiltig inmatning: förväntat ${K}, fick ${H}`}case"invalid_value":if(W.values.length===1)return`Ogiltig inmatning: förväntat ${U$(W.values[0])}`;return`Ogiltigt val: förväntade en av ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`För stor(t): förväntade ${W.origin??"värdet"} att ha ${K}${W.maximum.toString()} ${X.unit??"element"}`;return`För stor(t): förväntat ${W.origin??"värdet"} att ha ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`För lite(t): förväntade ${W.origin??"värdet"} att ha ${K}${W.minimum.toString()} ${X.unit}`;return`För lite(t): förväntade ${W.origin??"värdet"} att ha ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ogiltig sträng: måste börja med "${K.prefix}"`;if(K.format==="ends_with")return`Ogiltig sträng: måste sluta med "${K.suffix}"`;if(K.format==="includes")return`Ogiltig sträng: måste innehålla "${K.includes}"`;if(K.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${K.pattern}"`;return`Ogiltig(t) ${J[K.format]??W.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${m(W.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${W.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${W.origin??"värdet"}`;default:return"Ogiltig input"}}};function t1(){return{localeError:OP()}}var EP=()=>{let $={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function U(W){return $[W]??null}let J={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},Q={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${W.expected}, பெறப்பட்டது ${H}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${K}, பெறப்பட்டது ${H}`}case"invalid_value":if(W.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${U$(W.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${m(W.values,"|")} இல் ஒன்று`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${W.origin??"மதிப்பு"} ${K}${W.maximum.toString()} ${X.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${W.origin??"மதிப்பு"} ${K}${W.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${W.origin} ${K}${W.minimum.toString()} ${X.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${W.origin} ${K}${W.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`தவறான சரம்: "${K.prefix}" இல் தொடங்க வேண்டும்`;if(K.format==="ends_with")return`தவறான சரம்: "${K.suffix}" இல் முடிவடைய வேண்டும்`;if(K.format==="includes")return`தவறான சரம்: "${K.includes}" ஐ உள்ளடக்க வேண்டும்`;if(K.format==="regex")return`தவறான சரம்: ${K.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${J[K.format]??W.format}`}case"not_multiple_of":return`தவறான எண்: ${W.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${W.keys.length>1?"கள்":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${W.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function e1(){return{localeError:EP()}}var kP=()=>{let $={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function U(W){return $[W]??null}let J={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},Q={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${W.expected} แต่ได้รับ ${H}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${K} แต่ได้รับ ${H}`}case"invalid_value":if(W.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${U$(W.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"ไม่เกิน":"น้อยกว่า",X=U(W.origin);if(X)return`เกินกำหนด: ${W.origin??"ค่า"} ควรมี${K} ${W.maximum.toString()} ${X.unit??"รายการ"}`;return`เกินกำหนด: ${W.origin??"ค่า"} ควรมี${K} ${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?"อย่างน้อย":"มากกว่า",X=U(W.origin);if(X)return`น้อยกว่ากำหนด: ${W.origin} ควรมี${K} ${W.minimum.toString()} ${X.unit}`;return`น้อยกว่ากำหนด: ${W.origin} ควรมี${K} ${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${K.prefix}"`;if(K.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${K.suffix}"`;if(K.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${K.includes}" อยู่ในข้อความ`;if(K.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${K.pattern}`;return`รูปแบบไม่ถูกต้อง: ${J[K.format]??W.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${W.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${m(W.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${W.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${W.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function $G(){return{localeError:kP()}}var qP=()=>{let $={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function U(W){return $[W]??null}let J={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Geçersiz değer: beklenen instanceof ${W.expected}, alınan ${H}`;return`Geçersiz değer: beklenen ${K}, alınan ${H}`}case"invalid_value":if(W.values.length===1)return`Geçersiz değer: beklenen ${U$(W.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Çok büyük: beklenen ${W.origin??"değer"} ${K}${W.maximum.toString()} ${X.unit??"öğe"}`;return`Çok büyük: beklenen ${W.origin??"değer"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Çok küçük: beklenen ${W.origin} ${K}${W.minimum.toString()} ${X.unit}`;return`Çok küçük: beklenen ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Geçersiz metin: "${K.prefix}" ile başlamalı`;if(K.format==="ends_with")return`Geçersiz metin: "${K.suffix}" ile bitmeli`;if(K.format==="includes")return`Geçersiz metin: "${K.includes}" içermeli`;if(K.format==="regex")return`Geçersiz metin: ${K.pattern} desenine uymalı`;return`Geçersiz ${J[K.format]??W.format}`}case"not_multiple_of":return`Geçersiz sayı: ${W.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${W.keys.length>1?"lar":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${W.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function UG(){return{localeError:qP()}}var ZP=()=>{let $={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function U(W){return $[W]??null}let J={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},Q={nan:"NaN",number:"число",array:"масив"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Неправильні вхідні дані: очікується instanceof ${W.expected}, отримано ${H}`;return`Неправильні вхідні дані: очікується ${K}, отримано ${H}`}case"invalid_value":if(W.values.length===1)return`Неправильні вхідні дані: очікується ${U$(W.values[0])}`;return`Неправильна опція: очікується одне з ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Занадто велике: очікується, що ${W.origin??"значення"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"елементів"}`;return`Занадто велике: очікується, що ${W.origin??"значення"} буде ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Занадто мале: очікується, що ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Занадто мале: очікується, що ${W.origin} буде ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Неправильний рядок: повинен починатися з "${K.prefix}"`;if(K.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${K.suffix}"`;if(K.format==="includes")return`Неправильний рядок: повинен містити "${K.includes}"`;if(K.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${K.pattern}`;return`Неправильний ${J[K.format]??W.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${W.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${W.keys.length>1?"і":""}: ${m(W.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${W.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${W.origin}`;default:return"Неправильні вхідні дані"}}};function GQ(){return{localeError:ZP()}}function JG(){return GQ()}var IP=()=>{let $={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function U(W){return $[W]??null}let J={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},Q={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`غلط ان پٹ: instanceof ${W.expected} متوقع تھا، ${H} موصول ہوا`;return`غلط ان پٹ: ${K} متوقع تھا، ${H} موصول ہوا`}case"invalid_value":if(W.values.length===1)return`غلط ان پٹ: ${U$(W.values[0])} متوقع تھا`;return`غلط آپشن: ${m(W.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`بہت بڑا: ${W.origin??"ویلیو"} کے ${K}${W.maximum.toString()} ${X.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${W.origin??"ویلیو"} کا ${K}${W.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`بہت چھوٹا: ${W.origin} کے ${K}${W.minimum.toString()} ${X.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${W.origin} کا ${K}${W.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`غلط سٹرنگ: "${K.prefix}" سے شروع ہونا چاہیے`;if(K.format==="ends_with")return`غلط سٹرنگ: "${K.suffix}" پر ختم ہونا چاہیے`;if(K.format==="includes")return`غلط سٹرنگ: "${K.includes}" شامل ہونا چاہیے`;if(K.format==="regex")return`غلط سٹرنگ: پیٹرن ${K.pattern} سے میچ ہونا چاہیے`;return`غلط ${J[K.format]??W.format}`}case"not_multiple_of":return`غلط نمبر: ${W.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${W.keys.length>1?"ز":""}: ${m(W.keys,"، ")}`;case"invalid_key":return`${W.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${W.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function WG(){return{localeError:IP()}}var DP=()=>{let $={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"},map:{unit:"yozuv",verb:"bo‘lishi kerak"}};function U(W){return $[W]??null}let J={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},Q={nan:"NaN",number:"raqam",array:"massiv"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${W.expected}, qabul qilingan ${H}`;return`Noto‘g‘ri kirish: kutilgan ${K}, qabul qilingan ${H}`}case"invalid_value":if(W.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${U$(W.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Juda katta: kutilgan ${W.origin??"qiymat"} ${K}${W.maximum.toString()} ${X.unit} ${X.verb}`;return`Juda katta: kutilgan ${W.origin??"qiymat"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Juda kichik: kutilgan ${W.origin} ${K}${W.minimum.toString()} ${X.unit} ${X.verb}`;return`Juda kichik: kutilgan ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Noto‘g‘ri satr: "${K.prefix}" bilan boshlanishi kerak`;if(K.format==="ends_with")return`Noto‘g‘ri satr: "${K.suffix}" bilan tugashi kerak`;if(K.format==="includes")return`Noto‘g‘ri satr: "${K.includes}" ni o‘z ichiga olishi kerak`;if(K.format==="regex")return`Noto‘g‘ri satr: ${K.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${J[K.format]??W.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${W.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${W.keys.length>1?"lar":""}: ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${W.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function QG(){return{localeError:DP()}}var FP=()=>{let $={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function U(W){return $[W]??null}let J={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},Q={nan:"NaN",number:"số",array:"mảng"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${W.expected}, nhận được ${H}`;return`Đầu vào không hợp lệ: mong đợi ${K}, nhận được ${H}`}case"invalid_value":if(W.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${U$(W.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Quá lớn: mong đợi ${W.origin??"giá trị"} ${X.verb} ${K}${W.maximum.toString()} ${X.unit??"phần tử"}`;return`Quá lớn: mong đợi ${W.origin??"giá trị"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Quá nhỏ: mong đợi ${W.origin} ${X.verb} ${K}${W.minimum.toString()} ${X.unit}`;return`Quá nhỏ: mong đợi ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${K.prefix}"`;if(K.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${K.suffix}"`;if(K.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${K.includes}"`;if(K.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${K.pattern}`;return`${J[K.format]??W.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${W.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${m(W.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${W.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${W.origin}`;default:return"Đầu vào không hợp lệ"}}};function KG(){return{localeError:FP()}}var LP=()=>{let $={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function U(W){return $[W]??null}let J={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},Q={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`无效输入:期望 instanceof ${W.expected},实际接收 ${H}`;return`无效输入:期望 ${K},实际接收 ${H}`}case"invalid_value":if(W.values.length===1)return`无效输入:期望 ${U$(W.values[0])}`;return`无效选项:期望以下之一 ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`数值过大:期望 ${W.origin??"值"} ${K}${W.maximum.toString()} ${X.unit??"个元素"}`;return`数值过大:期望 ${W.origin??"值"} ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`数值过小:期望 ${W.origin} ${K}${W.minimum.toString()} ${X.unit}`;return`数值过小:期望 ${W.origin} ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`无效字符串:必须以 "${K.prefix}" 开头`;if(K.format==="ends_with")return`无效字符串:必须以 "${K.suffix}" 结尾`;if(K.format==="includes")return`无效字符串:必须包含 "${K.includes}"`;if(K.format==="regex")return`无效字符串:必须满足正则表达式 ${K.pattern}`;return`无效${J[K.format]??W.format}`}case"not_multiple_of":return`无效数字:必须是 ${W.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${m(W.keys,", ")}`;case"invalid_key":return`${W.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${W.origin} 中包含无效值(value)`;default:return"无效输入"}}};function XG(){return{localeError:LP()}}var RP=()=>{let $={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function U(W){return $[W]??null}let J={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},Q={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`無效的輸入值:預期為 instanceof ${W.expected},但收到 ${H}`;return`無效的輸入值:預期為 ${K},但收到 ${H}`}case"invalid_value":if(W.values.length===1)return`無效的輸入值:預期為 ${U$(W.values[0])}`;return`無效的選項:預期為以下其中之一 ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`數值過大:預期 ${W.origin??"值"} 應為 ${K}${W.maximum.toString()} ${X.unit??"個元素"}`;return`數值過大:預期 ${W.origin??"值"} 應為 ${K}${W.maximum.toString()}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`數值過小:預期 ${W.origin} 應為 ${K}${W.minimum.toString()} ${X.unit}`;return`數值過小:預期 ${W.origin} 應為 ${K}${W.minimum.toString()}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`無效的字串:必須以 "${K.prefix}" 開頭`;if(K.format==="ends_with")return`無效的字串:必須以 "${K.suffix}" 結尾`;if(K.format==="includes")return`無效的字串:必須包含 "${K.includes}"`;if(K.format==="regex")return`無效的字串:必須符合格式 ${K.pattern}`;return`無效的 ${J[K.format]??W.format}`}case"not_multiple_of":return`無效的數字:必須為 ${W.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${W.keys.length>1?"們":""}:${m(W.keys,"、")}`;case"invalid_key":return`${W.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${W.origin} 中有無效的值`;default:return"無效的輸入值"}}};function HG(){return{localeError:RP()}}var VP=()=>{let $={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function U(W){return $[W]??null}let J={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},Q={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(W)=>{switch(W.code){case"invalid_type":{let K=Q[W.expected]??W.expected,X=W$(W.input),H=Q[X]??X;if(/^[A-Z]/.test(W.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${W.expected}, àmọ̀ a rí ${H}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${K}, àmọ̀ a rí ${H}`}case"invalid_value":if(W.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${U$(W.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${m(W.values,"|")}`;case"too_big":{let K=W.inclusive?"<=":"<",X=U(W.origin);if(X)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${W.origin??"iye"} ${X.verb} ${K}${W.maximum} ${X.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${K}${W.maximum}`}case"too_small":{let K=W.inclusive?">=":">",X=U(W.origin);if(X)return`Kéré ju: a ní láti jẹ́ pé ${W.origin} ${X.verb} ${K}${W.minimum} ${X.unit}`;return`Kéré ju: a ní láti jẹ́ ${K}${W.minimum}`}case"invalid_format":{let K=W;if(K.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${K.prefix}"`;if(K.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${K.suffix}"`;if(K.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${K.includes}"`;if(K.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${K.pattern}`;return`Aṣìṣe: ${J[K.format]??W.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${W.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${m(W.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${W.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${W.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function NG(){return{localeError:VP()}}var $D,YG=Symbol("ZodOutput"),GG=Symbol("ZodInput");class OG{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...U){let J=U[0];if(this._map.set($,J),J&&typeof J==="object"&&"id"in J)this._idmap.set(J.id,$);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let U=this._map.get($);if(U&&typeof U==="object"&&"id"in U)this._idmap.delete(U.id);return this._map.delete($),this}get($){let U=$._zod.parent;if(U){let J={...this.get(U)??{}};delete J.id;let Q={...J,...this._map.get($)};return Object.keys(Q).length?Q:void 0}return this._map.get($)}has($){return this._map.has($)}}function FK(){return new OG}($D=globalThis).__zod_globalRegistry??($D.__zod_globalRegistry=FK());var r6=globalThis.__zod_globalRegistry;function EG($,U){return new $({type:"string",...K$(U)})}function kG($,U){return new $({type:"string",coerce:!0,...K$(U)})}function LK($,U){return new $({type:"string",format:"email",check:"string_format",abort:!1,...K$(U)})}function EQ($,U){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...K$(U)})}function RK($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...K$(U)})}function VK($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...K$(U)})}function wK($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...K$(U)})}function MK($,U){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...K$(U)})}function kQ($,U){return new $({type:"string",format:"url",check:"string_format",abort:!1,...K$(U)})}function BK($,U){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...K$(U)})}function PK($,U){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...K$(U)})}function zK($,U){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...K$(U)})}function _K($,U){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...K$(U)})}function AK($,U){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...K$(U)})}function CK($,U){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...K$(U)})}function SK($,U){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...K$(U)})}function TK($,U){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...K$(U)})}function vK($,U){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...K$(U)})}function qG($,U){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...K$(U)})}function jK($,U){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...K$(U)})}function gK($,U){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...K$(U)})}function bK($,U){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...K$(U)})}function yK($,U){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...K$(U)})}function xK($,U){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...K$(U)})}function hK($,U){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...K$(U)})}var ZG={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function IG($,U){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...K$(U)})}function DG($,U){return new $({type:"string",format:"date",check:"string_format",...K$(U)})}function FG($,U){return new $({type:"string",format:"time",check:"string_format",precision:null,...K$(U)})}function LG($,U){return new $({type:"string",format:"duration",check:"string_format",...K$(U)})}function RG($,U){return new $({type:"number",checks:[],...K$(U)})}function VG($,U){return new $({type:"number",coerce:!0,checks:[],...K$(U)})}function wG($,U){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...K$(U)})}function MG($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...K$(U)})}function BG($,U){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...K$(U)})}function PG($,U){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...K$(U)})}function zG($,U){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...K$(U)})}function _G($,U){return new $({type:"boolean",...K$(U)})}function AG($,U){return new $({type:"boolean",coerce:!0,...K$(U)})}function CG($,U){return new $({type:"bigint",...K$(U)})}function SG($,U){return new $({type:"bigint",coerce:!0,...K$(U)})}function TG($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...K$(U)})}function vG($,U){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...K$(U)})}function jG($,U){return new $({type:"symbol",...K$(U)})}function gG($,U){return new $({type:"undefined",...K$(U)})}function bG($,U){return new $({type:"null",...K$(U)})}function yG($){return new $({type:"any"})}function xG($){return new $({type:"unknown"})}function hG($,U){return new $({type:"never",...K$(U)})}function fG($,U){return new $({type:"void",...K$(U)})}function uG($,U){return new $({type:"date",...K$(U)})}function lG($,U){return new $({type:"date",coerce:!0,...K$(U)})}function mG($,U){return new $({type:"nan",...K$(U)})}function GJ($,U){return new XK({check:"less_than",...K$(U),value:$,inclusive:!1})}function PU($,U){return new XK({check:"less_than",...K$(U),value:$,inclusive:!0})}function OJ($,U){return new HK({check:"greater_than",...K$(U),value:$,inclusive:!1})}function NU($,U){return new HK({check:"greater_than",...K$(U),value:$,inclusive:!0})}function fK($){return OJ(0,$)}function uK($){return GJ(0,$)}function lK($){return PU(0,$)}function mK($){return NU(0,$)}function E0($,U){return new fN({check:"multiple_of",...K$(U),value:$})}function k0($,U){return new mN({check:"max_size",...K$(U),maximum:$})}function EJ($,U){return new pN({check:"min_size",...K$(U),minimum:$})}function m0($,U){return new dN({check:"size_equals",...K$(U),size:$})}function p0($,U){return new cN({check:"max_length",...K$(U),maximum:$})}function gJ($,U){return new nN({check:"min_length",...K$(U),minimum:$})}function d0($,U){return new iN({check:"length_equals",...K$(U),length:$})}function l8($,U){return new oN({check:"string_format",format:"regex",...K$(U),pattern:$})}function m8($){return new rN({check:"string_format",format:"lowercase",...K$($)})}function p8($){return new aN({check:"string_format",format:"uppercase",...K$($)})}function d8($,U){return new sN({check:"string_format",format:"includes",...K$(U),includes:$})}function c8($,U){return new tN({check:"string_format",format:"starts_with",...K$(U),prefix:$})}function n8($,U){return new eN({check:"string_format",format:"ends_with",...K$(U),suffix:$})}function pK($,U,J){return new $Y({check:"property",property:$,schema:U,...K$(J)})}function i8($,U){return new UY({check:"mime_type",mime:$,...K$(U)})}function oU($){return new JY({check:"overwrite",tx:$})}function o8($){return oU((U)=>U.normalize($))}function r8(){return oU(($)=>$.trim())}function a8(){return oU(($)=>$.toLowerCase())}function s8(){return oU(($)=>$.toUpperCase())}function t8(){return oU(($)=>tH($))}function pG($,U,J){return new $({type:"array",element:U,...K$(J)})}function MP($,U,J){return new $({type:"union",options:U,...K$(J)})}function BP($,U,J){return new $({type:"union",options:U,inclusive:!1,...K$(J)})}function PP($,U,J,Q){return new $({type:"union",options:J,discriminator:U,...K$(Q)})}function zP($,U,J){return new $({type:"intersection",left:U,right:J})}function _P($,U,J,Q){let W=J instanceof h$;return new $({type:"tuple",items:U,rest:W?J:null,...K$(W?Q:J)})}function AP($,U,J,Q){return new $({type:"record",keyType:U,valueType:J,...K$(Q)})}function CP($,U,J,Q){return new $({type:"map",keyType:U,valueType:J,...K$(Q)})}function SP($,U,J){return new $({type:"set",valueType:U,...K$(J)})}function TP($,U,J){let Q=Array.isArray(U)?Object.fromEntries(U.map((W)=>[W,W])):U;return new $({type:"enum",entries:Q,...K$(J)})}function vP($,U,J){return new $({type:"enum",entries:U,...K$(J)})}function jP($,U,J){return new $({type:"literal",values:Array.isArray(U)?U:[U],...K$(J)})}function dG($,U){return new $({type:"file",...K$(U)})}function gP($,U){return new $({type:"transform",transform:U})}function bP($,U){return new $({type:"optional",innerType:U})}function yP($,U){return new $({type:"nullable",innerType:U})}function xP($,U,J){return new $({type:"default",innerType:U,get defaultValue(){return typeof J==="function"?J():$N(J)}})}function hP($,U,J){return new $({type:"nonoptional",innerType:U,...K$(J)})}function fP($,U){return new $({type:"success",innerType:U})}function uP($,U,J){return new $({type:"catch",innerType:U,catchValue:typeof J==="function"?J:()=>J})}function lP($,U,J){return new $({type:"pipe",in:U,out:J})}function mP($,U){return new $({type:"readonly",innerType:U})}function pP($,U,J){return new $({type:"template_literal",parts:U,...K$(J)})}function dP($,U){return new $({type:"lazy",getter:U})}function cP($,U){return new $({type:"promise",innerType:U})}function cG($,U,J){let Q=K$(J);return Q.abort??(Q.abort=!0),new $({type:"custom",check:"custom",fn:U,...Q})}function nG($,U,J){return new $({type:"custom",check:"custom",fn:U,...K$(J)})}function iG($,U){let J=UD((Q)=>{return Q.addIssue=(W)=>{if(typeof W==="string")Q.issues.push(g8(W,Q.value,J._zod.def));else{let K=W;if(K.fatal)K.continue=!1;K.code??(K.code="custom"),K.input??(K.input=Q.value),K.inst??(K.inst=J),K.continue??(K.continue=!J._zod.def.abort),Q.issues.push(g8(K))}},$(Q.value,Q)},U);return J}function UD($,U){let J=new V6({check:"custom",...K$(U)});return J._zod.check=$,J}function oG($){let U=new V6({check:"describe"});return U._zod.onattach=[(J)=>{let Q=r6.get(J)??{};r6.add(J,{...Q,description:$})}],U._zod.check=()=>{},U}function rG($){let U=new V6({check:"meta"});return U._zod.onattach=[(J)=>{let Q=r6.get(J)??{};r6.add(J,{...Q,...$})}],U._zod.check=()=>{},U}function aG($,U){let J=K$(U),Q=J.truthy??["true","1","yes","on","y","enabled"],W=J.falsy??["false","0","no","off","n","disabled"];if(J.case!=="sensitive")Q=Q.map((k)=>typeof k==="string"?k.toLowerCase():k),W=W.map((k)=>typeof k==="string"?k.toLowerCase():k);let K=new Set(Q),X=new Set(W),H=$.Codec??XQ,N=$.Boolean??QQ,G=new($.String??l0)({type:"string",error:J.error}),O=new N({type:"boolean",error:J.error}),E=new H({type:"pipe",in:G,out:O,transform:(k,I)=>{let R=k;if(J.case!=="sensitive")R=R.toLowerCase();if(K.has(R))return!0;else if(X.has(R))return!1;else return I.issues.push({code:"invalid_value",expected:"stringbool",values:[...K,...X],input:I.value,inst:E,continue:!1}),{}},reverseTransform:(k,I)=>{if(k===!0)return Q[0]||"true";else return W[0]||"false"},error:J.error});return E}function e8($,U,J,Q={}){let W=K$(Q),K={...K$(Q),check:"string_format",type:"string",format:U,fn:typeof J==="function"?J:(H)=>J.test(H),...W};if(J instanceof RegExp)K.pattern=J;return new $(K)}function q0($){let U=$?.target??"draft-2020-12";if(U==="draft-4")U="draft-04";if(U==="draft-7")U="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??r6,target:U,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,cycles:$?.cycles??"ref",reused:$?.reused??"inline",external:$?.external??void 0}}function G6($,U,J={path:[],schemaPath:[]}){var Q;let W=$._zod.def,K=U.seen.get($);if(K){if(K.count++,J.schemaPath.includes($))K.cycle=J.path;return K.schema}let X={schema:{},count:1,cycle:void 0,path:J.path};U.seen.set($,X);let H=$._zod.toJSONSchema?.();if(H)X.schema=H;else{let G={...J,schemaPath:[...J.schemaPath,$],path:J.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(U,X.schema,G);else{let E=X.schema,k=U.processors[W.type];if(!k)throw Error(`[toJSONSchema]: Non-representable type encountered: ${W.type}`);k($,U,E,G)}let O=$._zod.parent;if(O){if(!X.ref)X.ref=O;G6(O,U,G),U.seen.get(O).isParent=!0}}let N=U.metadataRegistry.get($);if(N)Object.assign(X.schema,N);if(U.io==="input"&&YU($))delete X.schema.examples,delete X.schema.default;if(U.io==="input"&&"_prefault"in X.schema)(Q=X.schema).default??(Q.default=X.schema._prefault);return delete X.schema._prefault,U.seen.get($).schema}function Z0($,U){let J=$.seen.get(U);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let Q=new Map;for(let X of $.seen.entries()){let H=$.metadataRegistry.get(X[0])?.id;if(H){let N=Q.get(H);if(N&&N!==X[0])throw Error(`Duplicate schema id "${H}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);Q.set(H,X[0])}}let W=(X)=>{let H=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let O=$.external.registry.get(X[0])?.id,E=$.external.uri??((I)=>I);if(O)return{ref:E(O)};let k=X[1].defId??X[1].schema.id??`schema${$.counter++}`;return X[1].defId=k,{defId:k,ref:`${E("__shared")}#/${H}/${k}`}}if(X[1]===J)return{ref:"#"};let Y=`${"#"}/${H}/`,G=X[1].schema.id??`__schema${$.counter++}`;return{defId:G,ref:Y+G}},K=(X)=>{if(X[1].schema.$ref)return;let H=X[1],{ref:N,defId:Y}=W(X);if(H.def={...H.schema},Y)H.defId=Y;let G=H.schema;for(let O in G)delete G[O];G.$ref=N};if($.cycles==="throw")for(let X of $.seen.entries()){let H=X[1];if(H.cycle)throw Error(`Cycle detected: #/${H.cycle?.join("/")}/<root>+ `)}d.write("payload.value = newResult;"),d.write("return payload;");let A=d.compile();return(T,v)=>A(h,T,v)},s,o=Ws,a=!rs.jitless,l=a&&xp.value,u=t.catchall,f;e._zod.parse=(h,d)=>{f??(f=i.value);let g=h.value;if(!o(g))return h.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),h;if(a&&l&&d?.async===!1&&d.jitless!==!0){if(!s)s=r(t.shape);if(h=s(h,d),!u)return h;return cg([],g,h,d,f,e)}return n(h,d)}});function Tm(e,t,n,i){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let r=e.filter((s)=>!mr(s));if(r.length===1)return t.value=r[0].value,r[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((s)=>s.issues.map((o)=>Un(o,i,Dn())))}),t}var ug=q("$ZodUnion",(e,t)=>{_t.init(e,t),rt(e._zod,"optin",()=>t.options.some((i)=>i._zod.optin==="optional")?"optional":void 0),rt(e._zod,"optout",()=>t.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),rt(e._zod,"values",()=>{if(t.options.every((i)=>i._zod.values))return new Set(t.options.flatMap((i)=>Array.from(i._zod.values)));return}),rt(e._zod,"pattern",()=>{if(t.options.every((i)=>i._zod.pattern)){let i=t.options.map((r)=>r._zod.pattern);return new RegExp(`^(${i.map((r)=>wa(r.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(i,r)=>{if(n)return n(i,r);let s=!1,o=[];for(let a of t.options){let c=a._zod.run({value:i.value,issues:[]},r);if(c instanceof Promise)o.push(c),s=!0;else{if(c.issues.length===0)return c;o.push(c)}}if(!s)return Tm(o,i,e,r);return Promise.all(o).then((a)=>Tm(a,i,e,r))}});var hg=q("$ZodIntersection",(e,t)=>{_t.init(e,t),e._zod.parse=(n,i)=>{let r=n.value,s=t.left._zod.run({value:r,issues:[]},i),o=t.right._zod.run({value:r,issues:[]},i);if(s instanceof Promise||o instanceof Promise)return Promise.all([s,o]).then(([c,l])=>Em(n,c,l));return Em(n,s,o)}});function bu(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(pr(e)&&pr(t)){let n=Object.keys(t),i=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),r={...e,...t};for(let s of i){let o=bu(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};r[s]=o.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<e.length;i++){let r=e[i],s=t[i],o=bu(r,s);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Em(e,t,n){let i=new Map,r;for(let a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(let c of a.keys){if(!i.has(c))i.set(c,{});i.get(c).l=!0}}else e.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys){if(!i.has(c))i.set(c,{});i.get(c).r=!0}else e.issues.push(a);let s=[...i].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&r)e.issues.push({...r,keys:s});if(mr(e))return e;let o=bu(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var fg=q("$ZodRecord",(e,t)=>{_t.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!pr(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;let s=[],o=t.keyType._zod.values;if(o){n.value={};let a=new Set;for(let l of o)if(typeof l==="string"||typeof l==="number"||typeof l==="symbol"){a.add(typeof l==="number"?l.toString():l);let u=t.keyType._zod.run({value:l,issues:[]},i);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((d)=>Un(d,i,Dn())),input:l,path:[l],inst:e});continue}let f=u.value,h=t.valueType._zod.run({value:r[l],issues:[]},i);if(h instanceof Promise)s.push(h.then((d)=>{if(d.issues.length)n.issues.push(...Wi(l,d.issues));n.value[f]=d.value}));else{if(h.issues.length)n.issues.push(...Wi(l,h.issues));n.value[f]=h.value}}let c;for(let l in r)if(!a.has(l))c=c??[],c.push(l);if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(r)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(r,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},i);if(c instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&_u.test(a)&&c.issues.length){let f=t.keyType._zod.run({value:Number(a),issues:[]},i);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length===0)c=f}if(c.issues.length){if(t.mode==="loose")n.value[a]=r[a];else n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map((f)=>Un(f,i,Dn())),input:a,path:[a],inst:e});continue}let u=t.valueType._zod.run({value:r[a],issues:[]},i);if(u instanceof Promise)s.push(u.then((f)=>{if(f.issues.length)n.issues.push(...Wi(a,f.issues));n.value[c.value]=f.value}));else{if(u.issues.length)n.issues.push(...Wi(a,u.issues));n.value[c.value]=u.value}}}if(s.length)return Promise.all(s).then(()=>n);return n}});var dg=q("$ZodEnum",(e,t)=>{_t.init(e,t);let n=ba(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter((r)=>vp.has(typeof r)).map((r)=>typeof r==="string"?Vi(r):r.toString()).join("|")})$`),e._zod.parse=(r,s)=>{let o=r.value;if(i.has(o))return r;return r.issues.push({code:"invalid_value",values:n,input:o,inst:e}),r}}),pg=q("$ZodLiteral",(e,t)=>{if(_t.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map((i)=>typeof i==="string"?Vi(i):i?Vi(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,r)=>{let s=i.value;if(n.has(s))return i;return i.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),i}});var mg=q("$ZodTransform",(e,t)=>{_t.init(e,t),e._zod.optin="optional",e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Vs(e.constructor.name);let r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then((o)=>(n.value=o,n.fallback=!0,n));if(r instanceof Promise)throw new mi;return n.value=r,n.fallback=!0,n}});function Am(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var Mu=q("$ZodOptional",(e,t)=>{_t.init(e,t),e._zod.optin="optional",e._zod.optout="optional",rt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),rt(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${wa(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){let r=n.value,s=t.innerType._zod.run(n,i);if(s instanceof Promise)return s.then((o)=>Am(o,r));return Am(s,r)}if(n.value===void 0)return n;return t.innerType._zod.run(n,i)}}),gg=q("$ZodExactOptional",(e,t)=>{Mu.init(e,t),rt(e._zod,"values",()=>t.innerType._zod.values),rt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),_g=q("$ZodNullable",(e,t)=>{_t.init(e,t),rt(e._zod,"optin",()=>t.innerType._zod.optin),rt(e._zod,"optout",()=>t.innerType._zod.optout),rt(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${wa(n.source)}|null)$`):void 0}),rt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>{if(n.value===null)return n;return t.innerType._zod.run(n,i)}}),xg=q("$ZodDefault",(e,t)=>{_t.init(e,t),e._zod.optin="optional",rt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>Rm(s,t));return Rm(r,t)}});function Rm(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var vg=q("$ZodPrefault",(e,t)=>{_t.init(e,t),e._zod.optin="optional",rt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,i)}}),yg=q("$ZodNonOptional",(e,t)=>{_t.init(e,t),rt(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter((i)=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>Cm(s,e));return Cm(r,e)}});function Cm(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var bg=q("$ZodCatch",(e,t)=>{_t.init(e,t),e._zod.optin="optional",rt(e._zod,"optout",()=>t.innerType._zod.optout),rt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>{if(n.value=s.value,s.issues.length)n.value=t.catchValue({...n,error:{issues:s.issues.map((o)=>Un(o,i,Dn()))},input:n.value}),n.issues=[],n.fallback=!0;return n});if(n.value=r.value,r.issues.length)n.value=t.catchValue({...n,error:{issues:r.issues.map((s)=>Un(s,i,Dn()))},input:n.value}),n.issues=[],n.fallback=!0;return n}});var Sg=q("$ZodPipe",(e,t)=>{_t.init(e,t),rt(e._zod,"values",()=>t.in._zod.values),rt(e._zod,"optin",()=>t.in._zod.optin),rt(e._zod,"optout",()=>t.out._zod.optout),rt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){let s=t.out._zod.run(n,i);if(s instanceof Promise)return s.then((o)=>Pa(o,t.in,i));return Pa(s,t.in,i)}let r=t.in._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>Pa(s,t.out,i));return Pa(r,t.out,i)}});function Pa(e,t,n){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Mg=q("$ZodReadonly",(e,t)=>{_t.init(e,t),rt(e._zod,"propValues",()=>t.innerType._zod.propValues),rt(e._zod,"values",()=>t.innerType._zod.values),rt(e._zod,"optin",()=>t.innerType?._zod?.optin),rt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);let r=t.innerType._zod.run(n,i);if(r instanceof Promise)return r.then(Pm);return Pm(r)}});function Pm(e){return e.value=Object.freeze(e.value),e}var wg=q("$ZodCustom",(e,t)=>{Ht.init(e,t),_t.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=(n)=>{let i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then((s)=>Im(s,n,i,e));Im(r,n,i,e);return}});function Im(e,t,n,i){if(!e){let r={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};if(i._zod.def.params)r.params=i._zod.def.params;t.issues.push(gr(r))}}var Tg,zR=Symbol("ZodOutput"),kR=Symbol("ZodInput");class Eg{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function lw(){return new Eg}(Tg=globalThis).__zod_globalRegistry??(Tg.__zod_globalRegistry=lw());var _r=globalThis.__zod_globalRegistry;function Ag(e,t){return new e({type:"string",...Te(t)})}function Rg(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Te(t)})}function wu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Te(t)})}function Cg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Te(t)})}function Pg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Te(t)})}function Ig(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Te(t)})}function Lg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Te(t)})}function Ng(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Te(t)})}function Dg(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Te(t)})}function Ug(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Te(t)})}function Og(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Te(t)})}function Fg(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Te(t)})}function zg(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Te(t)})}function kg(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Te(t)})}function Bg(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Te(t)})}function Gg(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Te(t)})}function Hg(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Te(t)})}function Vg(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Te(t)})}function Wg(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Te(t)})}function $g(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Te(t)})}function Zg(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Te(t)})}function Xg(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Te(t)})}function qg(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Te(t)})}function Yg(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Te(t)})}function jg(e,t){return new e({type:"string",format:"date",check:"string_format",...Te(t)})}function Jg(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Te(t)})}function Kg(e,t){return new e({type:"string",format:"duration",check:"string_format",...Te(t)})}function Qg(e,t){return new e({type:"number",checks:[],...Te(t)})}function e_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Te(t)})}function t_(e,t){return new e({type:"boolean",...Te(t)})}function n_(e){return new e({type:"unknown"})}function i_(e,t){return new e({type:"never",...Te(t)})}function Na(e,t){return new xu({check:"less_than",...Te(t),value:e,inclusive:!1})}function Ys(e,t){return new xu({check:"less_than",...Te(t),value:e,inclusive:!0})}function Da(e,t){return new vu({check:"greater_than",...Te(t),value:e,inclusive:!1})}function js(e,t){return new vu({check:"greater_than",...Te(t),value:e,inclusive:!0})}function Ua(e,t){return new um({check:"multiple_of",...Te(t),value:e})}function Oa(e,t){return new fm({check:"max_length",...Te(t),maximum:e})}function ss(e,t){return new dm({check:"min_length",...Te(t),minimum:e})}function Fa(e,t){return new pm({check:"length_equals",...Te(t),length:e})}function Tu(e,t){return new mm({check:"string_format",format:"regex",...Te(t),pattern:e})}function Eu(e){return new gm({check:"string_format",format:"lowercase",...Te(e)})}function Au(e){return new _m({check:"string_format",format:"uppercase",...Te(e)})}function Ru(e,t){return new xm({check:"string_format",format:"includes",...Te(t),includes:e})}function Cu(e,t){return new vm({check:"string_format",format:"starts_with",...Te(t),prefix:e})}function Pu(e,t){return new ym({check:"string_format",format:"ends_with",...Te(t),suffix:e})}function Zi(e){return new bm({check:"overwrite",tx:e})}function Iu(e){return Zi((t)=>t.normalize(e))}function Lu(){return Zi((e)=>e.trim())}function Nu(){return Zi((e)=>e.toLowerCase())}function Du(){return Zi((e)=>e.toUpperCase())}function Uu(){return Zi((e)=>_p(e))}function r_(e,t,n){return new e({type:"array",element:t,...Te(n)})}function s_(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Te(n)})}function o_(e,t){let n=uw((i)=>(i.addIssue=(r)=>{if(typeof r==="string")i.issues.push(gr(r,i.value,n._zod.def));else{let s=r;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=i.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),i.issues.push(gr(s))}},e(i.value,i)),t);return n}function uw(e,t){let n=new Ht({check:"custom",...Te(t)});return n._zod.check=e,n}function Ou(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??_r,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function At(e,t,n={path:[],schemaPath:[]}){var i;let r=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,n.schemaPath.includes(e))s.cycle=n.path;return s.schema}let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let a=e._zod.toJSONSchema?.();if(a)o.schema=a;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,u);else{let h=o.schema,d=t.processors[r.type];if(!d)throw Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);d(e,t,h,u)}let f=e._zod.parent;if(f){if(!o.ref)o.ref=f;At(f,t,u),t.seen.get(f).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Object.assign(o.schema,c);if(t.io==="input"&&Qt(e))delete o.schema.examples,delete o.schema.default;if(t.io==="input"&&"_prefault"in o.schema)(i=o.schema).default??(i.default=o.schema._prefault);return delete o.schema._prefault,t.seen.get(e).schema}function Fu(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=new Map;for(let o of e.seen.entries()){let a=e.metadataRegistry.get(o[0])?.id;if(a){let c=i.get(a);if(c&&c!==o[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(a,o[0])}}let r=(o)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(o[0])?.id,h=e.external.uri??((g)=>g);if(f)return{ref:h(f)};let d=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=d,{defId:d,ref:`${h("__shared")}#/${a}/${d}`}}if(o[1]===n)return{ref:"#"};let l=`${"#"}/${a}/`,u=o[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+u}},s=(o)=>{if(o[1].schema.$ref)return;let a=o[1],{ref:c,defId:l}=r(o);if(a.def={...a.schema},l)a.defId=l;let u=a.schema;for(let f in u)delete u[f];u.$ref=c};if(e.cycles==="throw")for(let o of e.seen.entries()){let a=o[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let X of $.seen.entries()){let H=X[1];if(U===X[0]){K(X);continue}if($.external){let Y=$.external.registry.get(X[0])?.id;if(U!==X[0]&&Y){K(X);continue}}if($.metadataRegistry.get(X[0])?.id){K(X);continue}if(H.cycle){K(X);continue}if(H.count>1){if($.reused==="ref"){K(X);continue}}}}function I0($,U){let J=$.seen.get(U);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let Q=(H)=>{let N=$.seen.get(H);if(N.ref===null)return;let Y=N.def??N.schema,G={...Y},O=N.ref;if(N.ref=null,O){Q(O);let k=$.seen.get(O),I=k.schema;if(I.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))Y.allOf=Y.allOf??[],Y.allOf.push(I);else Object.assign(Y,I);if(Object.assign(Y,G),H._zod.parent===O)for(let q in Y){if(q==="$ref"||q==="allOf")continue;if(!(q in G))delete Y[q]}if(I.$ref&&k.def)for(let q in Y){if(q==="$ref"||q==="allOf")continue;if(q in k.def&&JSON.stringify(Y[q])===JSON.stringify(k.def[q]))delete Y[q]}}let E=H._zod.parent;if(E&&E!==O){Q(E);let k=$.seen.get(E);if(k?.schema.$ref){if(Y.$ref=k.schema.$ref,k.def)for(let I in Y){if(I==="$ref"||I==="allOf")continue;if(I in k.def&&JSON.stringify(Y[I])===JSON.stringify(k.def[I]))delete Y[I]}}}$.override({zodSchema:H,jsonSchema:Y,path:N.path??[]})};for(let H of[...$.seen.entries()].reverse())Q(H[0]);let W={};if($.target==="draft-2020-12")W.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")W.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let H=$.external.registry.get(U)?.id;if(!H)throw Error("Schema is missing an `id` property");W.$id=$.external.uri(H)}Object.assign(W,J.def??J.schema);let K=$.metadataRegistry.get(U)?.id;if(K!==void 0&&W.id===K)delete W.id;let X=$.external?.defs??{};for(let H of $.seen.entries()){let N=H[1];if(N.def&&N.defId){if(N.def.id===N.defId)delete N.def.id;X[N.defId]=N.def}}if($.external);else if(Object.keys(X).length>0)if($.target==="draft-2020-12")W.$defs=X;else W.definitions=X;try{let H=JSON.parse(JSON.stringify(W));return Object.defineProperty(H,"~standard",{value:{...U["~standard"],jsonSchema:{input:$W(U,"input",$.processors),output:$W(U,"output",$.processors)}},enumerable:!1,writable:!1}),H}catch(H){throw Error("Error converting schema to JSON.")}}function YU($,U){let J=U??{seen:new Set};if(J.seen.has($))return!1;J.seen.add($);let Q=$._zod.def;if(Q.type==="transform")return!0;if(Q.type==="array")return YU(Q.element,J);if(Q.type==="set")return YU(Q.valueType,J);if(Q.type==="lazy")return YU(Q.getter(),J);if(Q.type==="promise"||Q.type==="optional"||Q.type==="nonoptional"||Q.type==="nullable"||Q.type==="readonly"||Q.type==="default"||Q.type==="prefault")return YU(Q.innerType,J);if(Q.type==="intersection")return YU(Q.left,J)||YU(Q.right,J);if(Q.type==="record"||Q.type==="map")return YU(Q.keyType,J)||YU(Q.valueType,J);if(Q.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return YU(Q.in,J)||YU(Q.out,J)}if(Q.type==="object"){for(let W in Q.shape)if(YU(Q.shape[W],J))return!0;return!1}if(Q.type==="union"){for(let W of Q.options)if(YU(W,J))return!0;return!1}if(Q.type==="tuple"){for(let W of Q.items)if(YU(W,J))return!0;if(Q.rest&&YU(Q.rest,J))return!0;return!1}return!1}var sG=($,U={})=>(J)=>{let Q=q0({...J,processors:U});return G6($,Q),Z0(Q,$),I0(Q,$)},$W=($,U,J={})=>(Q)=>{let{libraryOptions:W,target:K}=Q??{},X=q0({...W??{},target:K,io:U,processors:J});return G6($,X),Z0(X,$),I0(X,$)};var nP={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},tG=($,U,J,Q)=>{let W=J;W.type="string";let{minimum:K,maximum:X,format:H,patterns:N,contentEncoding:Y}=$._zod.bag;if(typeof K==="number")W.minLength=K;if(typeof X==="number")W.maxLength=X;if(H){if(W.format=nP[H]??H,W.format==="")delete W.format;if(H==="time")delete W.format}if(Y)W.contentEncoding=Y;if(N&&N.size>0){let G=[...N];if(G.length===1)W.pattern=G[0].source;else if(G.length>1)W.allOf=[...G.map((O)=>({...U.target==="draft-07"||U.target==="draft-04"||U.target==="openapi-3.0"?{type:"string"}:{},pattern:O.source}))]}},eG=($,U,J,Q)=>{let W=J,{minimum:K,maximum:X,format:H,multipleOf:N,exclusiveMaximum:Y,exclusiveMinimum:G}=$._zod.bag;if(typeof H==="string"&&H.includes("int"))W.type="integer";else W.type="number";let O=typeof G==="number"&&G>=(K??Number.NEGATIVE_INFINITY),E=typeof Y==="number"&&Y<=(X??Number.POSITIVE_INFINITY),k=U.target==="draft-04"||U.target==="openapi-3.0";if(O)if(k)W.minimum=G,W.exclusiveMinimum=!0;else W.exclusiveMinimum=G;else if(typeof K==="number")W.minimum=K;if(E)if(k)W.maximum=Y,W.exclusiveMaximum=!0;else W.exclusiveMaximum=Y;else if(typeof X==="number")W.maximum=X;if(typeof N==="number")W.multipleOf=N},$O=($,U,J,Q)=>{J.type="boolean"},UO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},JO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},WO=($,U,J,Q)=>{if(U.target==="openapi-3.0")J.type="string",J.nullable=!0,J.enum=[null];else J.type="null"},QO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},KO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},XO=($,U,J,Q)=>{J.not={}},HO=($,U,J,Q)=>{},NO=($,U,J,Q)=>{},YO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},GO=($,U,J,Q)=>{let W=$._zod.def,K=iW(W.entries);if(K.every((X)=>typeof X==="number"))J.type="number";if(K.every((X)=>typeof X==="string"))J.type="string";J.enum=K},OO=($,U,J,Q)=>{let W=$._zod.def,K=[];for(let X of W.values)if(X===void 0){if(U.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof X==="bigint")if(U.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else K.push(Number(X));else K.push(X);if(K.length===0);else if(K.length===1){let X=K[0];if(J.type=X===null?"null":typeof X,U.target==="draft-04"||U.target==="openapi-3.0")J.enum=[X];else J.const=X}else{if(K.every((X)=>typeof X==="number"))J.type="number";if(K.every((X)=>typeof X==="string"))J.type="string";if(K.every((X)=>typeof X==="boolean"))J.type="boolean";if(K.every((X)=>X===null))J.type="null";J.enum=K}},EO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},kO=($,U,J,Q)=>{let W=J,K=$._zod.pattern;if(!K)throw Error("Pattern not found in template literal");W.type="string",W.pattern=K.source},qO=($,U,J,Q)=>{let W=J,K={type:"string",format:"binary",contentEncoding:"binary"},{minimum:X,maximum:H,mime:N}=$._zod.bag;if(X!==void 0)K.minLength=X;if(H!==void 0)K.maxLength=H;if(N)if(N.length===1)K.contentMediaType=N[0],Object.assign(W,K);else Object.assign(W,K),W.anyOf=N.map((Y)=>({contentMediaType:Y}));else Object.assign(W,K)},ZO=($,U,J,Q)=>{J.type="boolean"},IO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},DO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},FO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},LO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},RO=($,U,J,Q)=>{if(U.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},VO=($,U,J,Q)=>{let W=J,K=$._zod.def,{minimum:X,maximum:H}=$._zod.bag;if(typeof X==="number")W.minItems=X;if(typeof H==="number")W.maxItems=H;W.type="array",W.items=G6(K.element,U,{...Q,path:[...Q.path,"items"]})},wO=($,U,J,Q)=>{let W=J,K=$._zod.def;W.type="object",W.properties={};let X=K.shape;for(let Y in X)W.properties[Y]=G6(X[Y],U,{...Q,path:[...Q.path,"properties",Y]});let H=new Set(Object.keys(X)),N=new Set([...H].filter((Y)=>{let G=K.shape[Y]._zod;if(U.io==="input")return G.optin===void 0;else return G.optout===void 0}));if(N.size>0)W.required=Array.from(N);if(K.catchall?._zod.def.type==="never")W.additionalProperties=!1;else if(!K.catchall){if(U.io==="output")W.additionalProperties=!1}else if(K.catchall)W.additionalProperties=G6(K.catchall,U,{...Q,path:[...Q.path,"additionalProperties"]})},cK=($,U,J,Q)=>{let W=$._zod.def,K=W.inclusive===!1,X=W.options.map((H,N)=>G6(H,U,{...Q,path:[...Q.path,K?"oneOf":"anyOf",N]}));if(K)J.oneOf=X;else J.anyOf=X},MO=($,U,J,Q)=>{let W=$._zod.def,K=G6(W.left,U,{...Q,path:[...Q.path,"allOf",0]}),X=G6(W.right,U,{...Q,path:[...Q.path,"allOf",1]}),H=(Y)=>("allOf"in Y)&&Object.keys(Y).length===1,N=[...H(K)?K.allOf:[K],...H(X)?X.allOf:[X]];J.allOf=N},BO=($,U,J,Q)=>{let W=J,K=$._zod.def;W.type="array";let X=U.target==="draft-2020-12"?"prefixItems":"items",H=U.target==="draft-2020-12"?"items":U.target==="openapi-3.0"?"items":"additionalItems",N=K.items.map((E,k)=>G6(E,U,{...Q,path:[...Q.path,X,k]})),Y=K.rest?G6(K.rest,U,{...Q,path:[...Q.path,H,...U.target==="openapi-3.0"?[K.items.length]:[]]}):null;if(U.target==="draft-2020-12"){if(W.prefixItems=N,Y)W.items=Y}else if(U.target==="openapi-3.0"){if(W.items={anyOf:N},Y)W.items.anyOf.push(Y);if(W.minItems=N.length,!Y)W.maxItems=N.length}else if(W.items=N,Y)W.additionalItems=Y;let{minimum:G,maximum:O}=$._zod.bag;if(typeof G==="number")W.minItems=G;if(typeof O==="number")W.maxItems=O},PO=($,U,J,Q)=>{let W=J,K=$._zod.def;W.type="object";let X=K.keyType,N=X._zod.bag?.patterns;if(K.mode==="loose"&&N&&N.size>0){let G=G6(K.valueType,U,{...Q,path:[...Q.path,"patternProperties","*"]});W.patternProperties={};for(let O of N)W.patternProperties[O.source]=G}else{if(U.target==="draft-07"||U.target==="draft-2020-12")W.propertyNames=G6(K.keyType,U,{...Q,path:[...Q.path,"propertyNames"]});W.additionalProperties=G6(K.valueType,U,{...Q,path:[...Q.path,"additionalProperties"]})}let Y=X._zod.values;if(Y){let G=[...Y].filter((O)=>typeof O==="string"||typeof O==="number");if(G.length>0)W.required=G}},zO=($,U,J,Q)=>{let W=$._zod.def,K=G6(W.innerType,U,Q),X=U.seen.get($);if(U.target==="openapi-3.0")X.ref=W.innerType,J.nullable=!0;else J.anyOf=[K,{type:"null"}]},_O=($,U,J,Q)=>{let W=$._zod.def;G6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType},AO=($,U,J,Q)=>{let W=$._zod.def;G6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType,J.default=JSON.parse(JSON.stringify(W.defaultValue))},CO=($,U,J,Q)=>{let W=$._zod.def;G6(W.innerType,U,Q);let K=U.seen.get($);if(K.ref=W.innerType,U.io==="input")J._prefault=JSON.parse(JSON.stringify(W.defaultValue))},SO=($,U,J,Q)=>{let W=$._zod.def;G6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType;let X;try{X=W.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}J.default=X},TO=($,U,J,Q)=>{let W=$._zod.def,K=W.in._zod.traits.has("$ZodTransform"),X=U.io==="input"?K?W.out:W.in:W.out;G6(X,U,Q);let H=U.seen.get($);H.ref=X},vO=($,U,J,Q)=>{let W=$._zod.def;G6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType,J.readOnly=!0},jO=($,U,J,Q)=>{let W=$._zod.def;G6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType},nK=($,U,J,Q)=>{let W=$._zod.def;G6(W.innerType,U,Q);let K=U.seen.get($);K.ref=W.innerType},gO=($,U,J,Q)=>{let W=$._zod.innerType;G6(W,U,Q);let K=U.seen.get($);K.ref=W},dK={string:tG,number:eG,boolean:$O,bigint:UO,symbol:JO,null:WO,undefined:QO,void:KO,never:XO,any:HO,unknown:NO,date:YO,enum:GO,literal:OO,nan:EO,template_literal:kO,file:qO,success:ZO,custom:IO,function:DO,transform:FO,map:LO,set:RO,array:VO,object:wO,union:cK,intersection:MO,tuple:BO,record:PO,nullable:zO,nonoptional:_O,default:AO,prefault:CO,catch:SO,pipe:TO,readonly:vO,promise:jO,optional:nK,lazy:gO};function iK($,U){if("_idmap"in $){let Q=$,W=q0({...U,processors:dK}),K={};for(let N of Q._idmap.entries()){let[Y,G]=N;G6(G,W)}let X={},H={registry:Q,uri:U?.uri,defs:K};W.external=H;for(let N of Q._idmap.entries()){let[Y,G]=N;Z0(W,G),X[Y]=I0(W,G)}if(Object.keys(K).length>0){let N=W.target==="draft-2020-12"?"$defs":"definitions";X.__shared={[N]:K}}return{schemas:X}}let J=q0({...U,processors:dK});return G6($,J),Z0(J,$),I0(J,$)}class bO{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter($){this.ctx.counter=$}get seen(){return this.ctx.seen}constructor($){let U=$?.target??"draft-2020-12";if(U==="draft-4")U="draft-04";if(U==="draft-7")U="draft-07";this.ctx=q0({processors:dK,target:U,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,U={path:[],schemaPath:[]}){return G6($,this.ctx,U)}emit($,U){if(U){if(U.cycles)this.ctx.cycles=U.cycles;if(U.reused)this.ctx.reused=U.reused;if(U.external)this.ctx.external=U.external}Z0(this.ctx,$);let J=I0(this.ctx,$),{"~standard":Q,...W}=J;return W}}var JD={};var qQ={};RJ(qQ,{xor:()=>rD,xid:()=>FD,void:()=>pD,uuidv7:()=>GD,uuidv6:()=>YD,uuidv4:()=>ND,uuid:()=>HD,url:()=>OD,unknown:()=>c0,union:()=>R7,undefined:()=>lD,ulid:()=>DD,uint64:()=>fD,uint32:()=>yD,tuple:()=>ZE,transform:()=>w7,templateLiteral:()=>Y5,symbol:()=>uD,superRefine:()=>pE,success:()=>K5,stringbool:()=>D5,stringFormat:()=>CD,string:()=>ZQ,strictObject:()=>iD,set:()=>$5,refine:()=>mE,record:()=>IE,readonly:()=>yE,promise:()=>G5,preprocess:()=>L5,prefault:()=>AE,pipe:()=>$7,partialRecord:()=>sD,optional:()=>DQ,object:()=>nD,number:()=>eO,nullish:()=>Q5,nullable:()=>FQ,null:()=>QE,nonoptional:()=>CE,never:()=>L7,nativeEnum:()=>U5,nanoid:()=>qD,nan:()=>X5,meta:()=>Z5,map:()=>eD,mac:()=>VD,looseRecord:()=>tD,looseObject:()=>oD,literal:()=>J5,lazy:()=>fE,ksuid:()=>LD,keyof:()=>cD,jwt:()=>AD,json:()=>F5,ipv6:()=>wD,ipv4:()=>RD,invertCodec:()=>N5,intersection:()=>kE,int64:()=>hD,int32:()=>bD,int:()=>eK,instanceof:()=>I5,httpUrl:()=>ED,hostname:()=>SD,hex:()=>TD,hash:()=>vD,guid:()=>XD,function:()=>O5,float64:()=>gD,float32:()=>jD,file:()=>W5,exactOptional:()=>ME,enum:()=>V7,emoji:()=>kD,email:()=>KD,e164:()=>_D,discriminatedUnion:()=>aD,describe:()=>q5,date:()=>dD,custom:()=>k5,cuid2:()=>ID,cuid:()=>ZD,codec:()=>H5,cidrv6:()=>BD,cidrv4:()=>MD,check:()=>E5,catch:()=>vE,boolean:()=>$E,bigint:()=>xD,base64url:()=>zD,base64:()=>PD,array:()=>wQ,any:()=>mD,_function:()=>O5,_default:()=>zE,_ZodString:()=>U7,ZodXor:()=>GE,ZodXID:()=>N7,ZodVoid:()=>NE,ZodUnknown:()=>XE,ZodUnion:()=>BQ,ZodUndefined:()=>JE,ZodUUID:()=>kJ,ZodURL:()=>RQ,ZodULID:()=>H7,ZodType:()=>c$,ZodTuple:()=>qE,ZodTransform:()=>VE,ZodTemplateLiteral:()=>xE,ZodSymbol:()=>UE,ZodSuccess:()=>SE,ZodStringFormat:()=>D6,ZodString:()=>QW,ZodSet:()=>FE,ZodRecord:()=>JW,ZodReadonly:()=>bE,ZodPromise:()=>uE,ZodPreprocess:()=>gE,ZodPrefault:()=>_E,ZodPipe:()=>PQ,ZodOptional:()=>M7,ZodObject:()=>MQ,ZodNumberFormat:()=>n0,ZodNumber:()=>XW,ZodNullable:()=>BE,ZodNull:()=>WE,ZodNonOptional:()=>B7,ZodNever:()=>HE,ZodNanoID:()=>Q7,ZodNaN:()=>jE,ZodMap:()=>DE,ZodMAC:()=>tO,ZodLiteral:()=>LE,ZodLazy:()=>hE,ZodKSUID:()=>Y7,ZodJWT:()=>D7,ZodIntersection:()=>EE,ZodIPv6:()=>O7,ZodIPv4:()=>G7,ZodGUID:()=>IQ,ZodFunction:()=>lE,ZodFile:()=>RE,ZodExactOptional:()=>wE,ZodEnum:()=>WW,ZodEmoji:()=>W7,ZodEmail:()=>J7,ZodE164:()=>I7,ZodDiscriminatedUnion:()=>OE,ZodDefault:()=>PE,ZodDate:()=>VQ,ZodCustomStringFormat:()=>KW,ZodCustom:()=>_Q,ZodCodec:()=>zQ,ZodCatch:()=>TE,ZodCUID2:()=>X7,ZodCUID:()=>K7,ZodCIDRv6:()=>k7,ZodCIDRv4:()=>E7,ZodBoolean:()=>HW,ZodBigIntFormat:()=>F7,ZodBigInt:()=>NW,ZodBase64URL:()=>Z7,ZodBase64:()=>q7,ZodArray:()=>YE,ZodAny:()=>KE});var oK={};RJ(oK,{uppercase:()=>p8,trim:()=>r8,toUpperCase:()=>s8,toLowerCase:()=>a8,startsWith:()=>c8,slugify:()=>t8,size:()=>m0,regex:()=>l8,property:()=>pK,positive:()=>fK,overwrite:()=>oU,normalize:()=>o8,nonpositive:()=>lK,nonnegative:()=>mK,negative:()=>uK,multipleOf:()=>E0,minSize:()=>EJ,minLength:()=>gJ,mime:()=>i8,maxSize:()=>k0,maxLength:()=>p0,lte:()=>PU,lt:()=>GJ,lowercase:()=>m8,length:()=>d0,includes:()=>d8,gte:()=>NU,gt:()=>OJ,endsWith:()=>n8});var UW={};RJ(UW,{time:()=>hO,duration:()=>fO,datetime:()=>yO,date:()=>xO,ZodISOTime:()=>sK,ZodISODuration:()=>tK,ZodISODateTime:()=>rK,ZodISODate:()=>aK});var rK=g("ZodISODateTime",($,U)=>{IY.init($,U),D6.init($,U)});function yO($){return IG(rK,$)}var aK=g("ZodISODate",($,U)=>{DY.init($,U),D6.init($,U)});function xO($){return DG(aK,$)}var sK=g("ZodISOTime",($,U)=>{FY.init($,U),D6.init($,U)});function hO($){return FG(sK,$)}var tK=g("ZodISODuration",($,U)=>{LY.init($,U),D6.init($,U)});function fO($){return LG(tK,$)}var WD=($,U)=>{tW.init($,U),$.name="ZodError",Object.defineProperties($,{format:{value:(J)=>$Q($,J)},flatten:{value:(J)=>eW($,J)},addIssue:{value:(J)=>{$.issues.push(J),$.message=JSON.stringify($.issues,v8,2)}},addIssues:{value:(J)=>{$.issues.push(...J),$.message=JSON.stringify($.issues,v8,2)}},isEmpty:{get(){return $.issues.length===0}}})},oP=g("ZodError",WD),IU=g("ZodError",WD,{Parent:Error});var uO=b8(IU),lO=y8(IU),mO=x8(IU),pO=h8(IU),dO=s9(IU),cO=t9(IU),nO=e9(IU),iO=$K(IU),oO=UK(IU),rO=JK(IU),aO=WK(IU),sO=QK(IU);var QD=new WeakMap;function LQ($,U,J){let Q=Object.getPrototypeOf($),W=QD.get(Q);if(!W)W=new Set,QD.set(Q,W);if(W.has(U))return;W.add(U);for(let K in J){let X=J[K];Object.defineProperty(Q,K,{configurable:!0,enumerable:!1,get(){let H=X.bind(this);return Object.defineProperty(this,K,{configurable:!0,writable:!0,enumerable:!0,value:H}),H},set(H){Object.defineProperty(this,K,{configurable:!0,writable:!0,enumerable:!0,value:H})}})}}var c$=g("ZodType",($,U)=>{return h$.init($,U),Object.assign($["~standard"],{jsonSchema:{input:$W($,"input"),output:$W($,"output")}}),$.toJSONSchema=sG($,{}),$.def=U,$.type=U.type,Object.defineProperty($,"_def",{value:U}),$.parse=(J,Q)=>uO($,J,Q,{callee:$.parse}),$.safeParse=(J,Q)=>mO($,J,Q),$.parseAsync=async(J,Q)=>lO($,J,Q,{callee:$.parseAsync}),$.safeParseAsync=async(J,Q)=>pO($,J,Q),$.spa=$.safeParseAsync,$.encode=(J,Q)=>dO($,J,Q),$.decode=(J,Q)=>cO($,J,Q),$.encodeAsync=async(J,Q)=>nO($,J,Q),$.decodeAsync=async(J,Q)=>iO($,J,Q),$.safeEncode=(J,Q)=>oO($,J,Q),$.safeDecode=(J,Q)=>rO($,J,Q),$.safeEncodeAsync=async(J,Q)=>aO($,J,Q),$.safeDecodeAsync=async(J,Q)=>sO($,J,Q),LQ($,"ZodType",{check(...J){let Q=this.def;return this.clone(Q$.mergeDefs(Q,{checks:[...Q.checks??[],...J.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}),{parent:!0})},with(...J){return this.check(...J)},clone(J,Q){return XU(this,J,Q)},brand(){return this},register(J,Q){return J.add(this,Q),this},refine(J,Q){return this.check(mE(J,Q))},superRefine(J,Q){return this.check(pE(J,Q))},overwrite(J){return this.check(oU(J))},optional(){return DQ(this)},exactOptional(){return ME(this)},nullable(){return FQ(this)},nullish(){return DQ(FQ(this))},nonoptional(J){return CE(this,J)},array(){return wQ(this)},or(J){return R7([this,J])},and(J){return kE(this,J)},transform(J){return $7(this,w7(J))},default(J){return zE(this,J)},prefault(J){return AE(this,J)},catch(J){return vE(this,J)},pipe(J){return $7(this,J)},readonly(){return yE(this)},describe(J){let Q=this.clone();return r6.add(Q,{description:J}),Q},meta(...J){if(J.length===0)return r6.get(this);let Q=this.clone();return r6.add(Q,J[0]),Q},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(J){return J(this)}}),Object.defineProperty($,"description",{get(){return r6.get($)?.description},configurable:!0}),$}),U7=g("_ZodString",($,U)=>{l0.init($,U),c$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>tG($,Q,W,K);let J=$._zod.bag;$.format=J.format??null,$.minLength=J.minimum??null,$.maxLength=J.maximum??null,LQ($,"_ZodString",{regex(...Q){return this.check(l8(...Q))},includes(...Q){return this.check(d8(...Q))},startsWith(...Q){return this.check(c8(...Q))},endsWith(...Q){return this.check(n8(...Q))},min(...Q){return this.check(gJ(...Q))},max(...Q){return this.check(p0(...Q))},length(...Q){return this.check(d0(...Q))},nonempty(...Q){return this.check(gJ(1,...Q))},lowercase(Q){return this.check(m8(Q))},uppercase(Q){return this.check(p8(Q))},trim(){return this.check(r8())},normalize(...Q){return this.check(o8(...Q))},toLowerCase(){return this.check(a8())},toUpperCase(){return this.check(s8())},slugify(){return this.check(t8())}})}),QW=g("ZodString",($,U)=>{l0.init($,U),U7.init($,U),$.email=(J)=>$.check(LK(J7,J)),$.url=(J)=>$.check(kQ(RQ,J)),$.jwt=(J)=>$.check(hK(D7,J)),$.emoji=(J)=>$.check(BK(W7,J)),$.guid=(J)=>$.check(EQ(IQ,J)),$.uuid=(J)=>$.check(RK(kJ,J)),$.uuidv4=(J)=>$.check(VK(kJ,J)),$.uuidv6=(J)=>$.check(wK(kJ,J)),$.uuidv7=(J)=>$.check(MK(kJ,J)),$.nanoid=(J)=>$.check(PK(Q7,J)),$.guid=(J)=>$.check(EQ(IQ,J)),$.cuid=(J)=>$.check(zK(K7,J)),$.cuid2=(J)=>$.check(_K(X7,J)),$.ulid=(J)=>$.check(AK(H7,J)),$.base64=(J)=>$.check(bK(q7,J)),$.base64url=(J)=>$.check(yK(Z7,J)),$.xid=(J)=>$.check(CK(N7,J)),$.ksuid=(J)=>$.check(SK(Y7,J)),$.ipv4=(J)=>$.check(TK(G7,J)),$.ipv6=(J)=>$.check(vK(O7,J)),$.cidrv4=(J)=>$.check(jK(E7,J)),$.cidrv6=(J)=>$.check(gK(k7,J)),$.e164=(J)=>$.check(xK(I7,J)),$.datetime=(J)=>$.check(yO(J)),$.date=(J)=>$.check(xO(J)),$.time=(J)=>$.check(hO(J)),$.duration=(J)=>$.check(fO(J))});function ZQ($){return EG(QW,$)}var D6=g("ZodStringFormat",($,U)=>{I6.init($,U),U7.init($,U)}),J7=g("ZodEmail",($,U)=>{HY.init($,U),D6.init($,U)});function KD($){return LK(J7,$)}var IQ=g("ZodGUID",($,U)=>{KY.init($,U),D6.init($,U)});function XD($){return EQ(IQ,$)}var kJ=g("ZodUUID",($,U)=>{XY.init($,U),D6.init($,U)});function HD($){return RK(kJ,$)}function ND($){return VK(kJ,$)}function YD($){return wK(kJ,$)}function GD($){return MK(kJ,$)}var RQ=g("ZodURL",($,U)=>{NY.init($,U),D6.init($,U)});function OD($){return kQ(RQ,$)}function ED($){return kQ(RQ,{protocol:BU.httpProtocol,hostname:BU.domain,...Q$.normalizeParams($)})}var W7=g("ZodEmoji",($,U)=>{YY.init($,U),D6.init($,U)});function kD($){return BK(W7,$)}var Q7=g("ZodNanoID",($,U)=>{GY.init($,U),D6.init($,U)});function qD($){return PK(Q7,$)}var K7=g("ZodCUID",($,U)=>{OY.init($,U),D6.init($,U)});function ZD($){return zK(K7,$)}var X7=g("ZodCUID2",($,U)=>{EY.init($,U),D6.init($,U)});function ID($){return _K(X7,$)}var H7=g("ZodULID",($,U)=>{kY.init($,U),D6.init($,U)});function DD($){return AK(H7,$)}var N7=g("ZodXID",($,U)=>{qY.init($,U),D6.init($,U)});function FD($){return CK(N7,$)}var Y7=g("ZodKSUID",($,U)=>{ZY.init($,U),D6.init($,U)});function LD($){return SK(Y7,$)}var G7=g("ZodIPv4",($,U)=>{RY.init($,U),D6.init($,U)});function RD($){return TK(G7,$)}var tO=g("ZodMAC",($,U)=>{wY.init($,U),D6.init($,U)});function VD($){return qG(tO,$)}var O7=g("ZodIPv6",($,U)=>{VY.init($,U),D6.init($,U)});function wD($){return vK(O7,$)}var E7=g("ZodCIDRv4",($,U)=>{MY.init($,U),D6.init($,U)});function MD($){return jK(E7,$)}var k7=g("ZodCIDRv6",($,U)=>{BY.init($,U),D6.init($,U)});function BD($){return gK(k7,$)}var q7=g("ZodBase64",($,U)=>{zY.init($,U),D6.init($,U)});function PD($){return bK(q7,$)}var Z7=g("ZodBase64URL",($,U)=>{_Y.init($,U),D6.init($,U)});function zD($){return yK(Z7,$)}var I7=g("ZodE164",($,U)=>{AY.init($,U),D6.init($,U)});function _D($){return xK(I7,$)}var D7=g("ZodJWT",($,U)=>{CY.init($,U),D6.init($,U)});function AD($){return hK(D7,$)}var KW=g("ZodCustomStringFormat",($,U)=>{SY.init($,U),D6.init($,U)});function CD($,U,J={}){return e8(KW,$,U,J)}function SD($){return e8(KW,"hostname",BU.hostname,$)}function TD($){return e8(KW,"hex",BU.hex,$)}function vD($,U){let J=U?.enc??"hex",Q=`${$}_${J}`,W=BU[Q];if(!W)throw Error(`Unrecognized hash format: ${Q}`);return e8(KW,Q,W,U)}var XW=g("ZodNumber",($,U)=>{kK.init($,U),c$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>eG($,Q,W,K),LQ($,"ZodNumber",{gt(Q,W){return this.check(OJ(Q,W))},gte(Q,W){return this.check(NU(Q,W))},min(Q,W){return this.check(NU(Q,W))},lt(Q,W){return this.check(GJ(Q,W))},lte(Q,W){return this.check(PU(Q,W))},max(Q,W){return this.check(PU(Q,W))},int(Q){return this.check(eK(Q))},safe(Q){return this.check(eK(Q))},positive(Q){return this.check(OJ(0,Q))},nonnegative(Q){return this.check(NU(0,Q))},negative(Q){return this.check(GJ(0,Q))},nonpositive(Q){return this.check(PU(0,Q))},multipleOf(Q,W){return this.check(E0(Q,W))},step(Q,W){return this.check(E0(Q,W))},finite(){return this}});let J=$._zod.bag;$.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),$.isFinite=!0,$.format=J.format??null});function eO($){return RG(XW,$)}var n0=g("ZodNumberFormat",($,U)=>{TY.init($,U),XW.init($,U)});function eK($){return wG(n0,$)}function jD($){return MG(n0,$)}function gD($){return BG(n0,$)}function bD($){return PG(n0,$)}function yD($){return zG(n0,$)}var HW=g("ZodBoolean",($,U)=>{QQ.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>$O($,J,Q,W)});function $E($){return _G(HW,$)}var NW=g("ZodBigInt",($,U)=>{qK.init($,U),c$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>UO($,Q,W,K),$.gte=(Q,W)=>$.check(NU(Q,W)),$.min=(Q,W)=>$.check(NU(Q,W)),$.gt=(Q,W)=>$.check(OJ(Q,W)),$.gte=(Q,W)=>$.check(NU(Q,W)),$.min=(Q,W)=>$.check(NU(Q,W)),$.lt=(Q,W)=>$.check(GJ(Q,W)),$.lte=(Q,W)=>$.check(PU(Q,W)),$.max=(Q,W)=>$.check(PU(Q,W)),$.positive=(Q)=>$.check(OJ(BigInt(0),Q)),$.negative=(Q)=>$.check(GJ(BigInt(0),Q)),$.nonpositive=(Q)=>$.check(PU(BigInt(0),Q)),$.nonnegative=(Q)=>$.check(NU(BigInt(0),Q)),$.multipleOf=(Q,W)=>$.check(E0(Q,W));let J=$._zod.bag;$.minValue=J.minimum??null,$.maxValue=J.maximum??null,$.format=J.format??null});function xD($){return CG(NW,$)}var F7=g("ZodBigIntFormat",($,U)=>{vY.init($,U),NW.init($,U)});function hD($){return TG(F7,$)}function fD($){return vG(F7,$)}var UE=g("ZodSymbol",($,U)=>{jY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>JO($,J,Q,W)});function uD($){return jG(UE,$)}var JE=g("ZodUndefined",($,U)=>{gY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>QO($,J,Q,W)});function lD($){return gG(JE,$)}var WE=g("ZodNull",($,U)=>{bY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>WO($,J,Q,W)});function QE($){return bG(WE,$)}var KE=g("ZodAny",($,U)=>{yY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>HO($,J,Q,W)});function mD(){return yG(KE)}var XE=g("ZodUnknown",($,U)=>{xY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>NO($,J,Q,W)});function c0(){return xG(XE)}var HE=g("ZodNever",($,U)=>{hY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>XO($,J,Q,W)});function L7($){return hG(HE,$)}var NE=g("ZodVoid",($,U)=>{fY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>KO($,J,Q,W)});function pD($){return fG(NE,$)}var VQ=g("ZodDate",($,U)=>{uY.init($,U),c$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>YO($,Q,W,K),$.min=(Q,W)=>$.check(NU(Q,W)),$.max=(Q,W)=>$.check(PU(Q,W));let J=$._zod.bag;$.minDate=J.minimum?new Date(J.minimum):null,$.maxDate=J.maximum?new Date(J.maximum):null});function dD($){return uG(VQ,$)}var YE=g("ZodArray",($,U)=>{lY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>VO($,J,Q,W),$.element=U.element,LQ($,"ZodArray",{min(J,Q){return this.check(gJ(J,Q))},nonempty(J){return this.check(gJ(1,J))},max(J,Q){return this.check(p0(J,Q))},length(J,Q){return this.check(d0(J,Q))},unwrap(){return this.element}})});function wQ($,U){return pG(YE,$,U)}function cD($){let U=$._zod.def.shape;return V7(Object.keys(U))}var MQ=g("ZodObject",($,U)=>{mY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>wO($,J,Q,W),Q$.defineLazy($,"shape",()=>{return U.shape}),LQ($,"ZodObject",{keyof(){return V7(Object.keys(this._zod.def.shape))},catchall(J){return this.clone({...this._zod.def,catchall:J})},passthrough(){return this.clone({...this._zod.def,catchall:c0()})},loose(){return this.clone({...this._zod.def,catchall:c0()})},strict(){return this.clone({...this._zod.def,catchall:L7()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(J){return Q$.extend(this,J)},safeExtend(J){return Q$.safeExtend(this,J)},merge(J){return Q$.merge(this,J)},pick(J){return Q$.pick(this,J)},omit(J){return Q$.omit(this,J)},partial(...J){return Q$.partial(M7,this,J[0])},required(...J){return Q$.required(B7,this,J[0])}})});function nD($,U){let J={type:"object",shape:$??{},...Q$.normalizeParams(U)};return new MQ(J)}function iD($,U){return new MQ({type:"object",shape:$,catchall:L7(),...Q$.normalizeParams(U)})}function oD($,U){return new MQ({type:"object",shape:$,catchall:c0(),...Q$.normalizeParams(U)})}var BQ=g("ZodUnion",($,U)=>{KQ.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>cK($,J,Q,W),$.options=U.options});function R7($,U){return new BQ({type:"union",options:$,...Q$.normalizeParams(U)})}var GE=g("ZodXor",($,U)=>{BQ.init($,U),pY.init($,U),$._zod.processJSONSchema=(J,Q,W)=>cK($,J,Q,W),$.options=U.options});function rD($,U){return new GE({type:"union",options:$,inclusive:!1,...Q$.normalizeParams(U)})}var OE=g("ZodDiscriminatedUnion",($,U)=>{BQ.init($,U),dY.init($,U)});function aD($,U,J){return new OE({type:"union",options:U,discriminator:$,...Q$.normalizeParams(J)})}var EE=g("ZodIntersection",($,U)=>{cY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>MO($,J,Q,W)});function kE($,U){return new EE({type:"intersection",left:$,right:U})}var qE=g("ZodTuple",($,U)=>{ZK.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>BO($,J,Q,W),$.rest=(J)=>$.clone({...$._zod.def,rest:J})});function ZE($,U,J){let Q=U instanceof h$,W=Q?J:U;return new qE({type:"tuple",items:$,rest:Q?U:null,...Q$.normalizeParams(W)})}var JW=g("ZodRecord",($,U)=>{nY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>PO($,J,Q,W),$.keyType=U.keyType,$.valueType=U.valueType});function IE($,U,J){if(!U||!U._zod)return new JW({type:"record",keyType:ZQ(),valueType:$,...Q$.normalizeParams(U)});return new JW({type:"record",keyType:$,valueType:U,...Q$.normalizeParams(J)})}function sD($,U,J){let Q=XU($);return Q._zod.values=void 0,new JW({type:"record",keyType:Q,valueType:U,...Q$.normalizeParams(J)})}function tD($,U,J){return new JW({type:"record",keyType:$,valueType:U,mode:"loose",...Q$.normalizeParams(J)})}var DE=g("ZodMap",($,U)=>{iY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>LO($,J,Q,W),$.keyType=U.keyType,$.valueType=U.valueType,$.min=(...J)=>$.check(EJ(...J)),$.nonempty=(J)=>$.check(EJ(1,J)),$.max=(...J)=>$.check(k0(...J)),$.size=(...J)=>$.check(m0(...J))});function eD($,U,J){return new DE({type:"map",keyType:$,valueType:U,...Q$.normalizeParams(J)})}var FE=g("ZodSet",($,U)=>{oY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>RO($,J,Q,W),$.min=(...J)=>$.check(EJ(...J)),$.nonempty=(J)=>$.check(EJ(1,J)),$.max=(...J)=>$.check(k0(...J)),$.size=(...J)=>$.check(m0(...J))});function $5($,U){return new FE({type:"set",valueType:$,...Q$.normalizeParams(U)})}var WW=g("ZodEnum",($,U)=>{rY.init($,U),c$.init($,U),$._zod.processJSONSchema=(Q,W,K)=>GO($,Q,W,K),$.enum=U.entries,$.options=Object.values(U.entries);let J=new Set(Object.keys(U.entries));$.extract=(Q,W)=>{let K={};for(let X of Q)if(J.has(X))K[X]=U.entries[X];else throw Error(`Key ${X} not found in enum`);return new WW({...U,checks:[],...Q$.normalizeParams(W),entries:K})},$.exclude=(Q,W)=>{let K={...U.entries};for(let X of Q)if(J.has(X))delete K[X];else throw Error(`Key ${X} not found in enum`);return new WW({...U,checks:[],...Q$.normalizeParams(W),entries:K})}});function V7($,U){let J=Array.isArray($)?Object.fromEntries($.map((Q)=>[Q,Q])):$;return new WW({type:"enum",entries:J,...Q$.normalizeParams(U)})}function U5($,U){return new WW({type:"enum",entries:$,...Q$.normalizeParams(U)})}var LE=g("ZodLiteral",($,U)=>{aY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>OO($,J,Q,W),$.values=new Set(U.values),Object.defineProperty($,"value",{get(){if(U.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return U.values[0]}})});function J5($,U){return new LE({type:"literal",values:Array.isArray($)?$:[$],...Q$.normalizeParams(U)})}var RE=g("ZodFile",($,U)=>{sY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>qO($,J,Q,W),$.min=(J,Q)=>$.check(EJ(J,Q)),$.max=(J,Q)=>$.check(k0(J,Q)),$.mime=(J,Q)=>$.check(i8(Array.isArray(J)?J:[J],Q))});function W5($){return dG(RE,$)}var VE=g("ZodTransform",($,U)=>{tY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>FO($,J,Q,W),$._zod.parse=(J,Q)=>{if(Q.direction==="backward")throw new h0($.constructor.name);J.addIssue=(K)=>{if(typeof K==="string")J.issues.push(Q$.issue(K,J.value,U));else{let X=K;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=J.value),X.inst??(X.inst=$),J.issues.push(Q$.issue(X))}};let W=U.transform(J.value,J);if(W instanceof Promise)return W.then((K)=>{return J.value=K,J.fallback=!0,J});return J.value=W,J.fallback=!0,J}});function w7($){return new VE({type:"transform",transform:$})}var M7=g("ZodOptional",($,U)=>{IK.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>nK($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function DQ($){return new M7({type:"optional",innerType:$})}var wE=g("ZodExactOptional",($,U)=>{eY.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>nK($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function ME($){return new wE({type:"optional",innerType:$})}var BE=g("ZodNullable",($,U)=>{$1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>zO($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function FQ($){return new BE({type:"nullable",innerType:$})}function Q5($){return DQ(FQ($))}var PE=g("ZodDefault",($,U)=>{U1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>AO($,J,Q,W),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function zE($,U){return new PE({type:"default",innerType:$,get defaultValue(){return typeof U==="function"?U():Q$.shallowClone(U)}})}var _E=g("ZodPrefault",($,U)=>{J1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>CO($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function AE($,U){return new _E({type:"prefault",innerType:$,get defaultValue(){return typeof U==="function"?U():Q$.shallowClone(U)}})}var B7=g("ZodNonOptional",($,U)=>{W1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>_O($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function CE($,U){return new B7({type:"nonoptional",innerType:$,...Q$.normalizeParams(U)})}var SE=g("ZodSuccess",($,U)=>{Q1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>ZO($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function K5($){return new SE({type:"success",innerType:$})}var TE=g("ZodCatch",($,U)=>{K1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>SO($,J,Q,W),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function vE($,U){return new TE({type:"catch",innerType:$,catchValue:typeof U==="function"?U:()=>U})}var jE=g("ZodNaN",($,U)=>{X1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>EO($,J,Q,W)});function X5($){return mG(jE,$)}var PQ=g("ZodPipe",($,U)=>{DK.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>TO($,J,Q,W),$.in=U.in,$.out=U.out});function $7($,U){return new PQ({type:"pipe",in:$,out:U})}var zQ=g("ZodCodec",($,U)=>{PQ.init($,U),XQ.init($,U)});function H5($,U,J){return new zQ({type:"pipe",in:$,out:U,transform:J.decode,reverseTransform:J.encode})}function N5($){let U=$._zod.def;return new zQ({type:"pipe",in:U.out,out:U.in,transform:U.reverseTransform,reverseTransform:U.transform})}var gE=g("ZodPreprocess",($,U)=>{PQ.init($,U),H1.init($,U)}),bE=g("ZodReadonly",($,U)=>{N1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>vO($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function yE($){return new bE({type:"readonly",innerType:$})}var xE=g("ZodTemplateLiteral",($,U)=>{Y1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>kO($,J,Q,W)});function Y5($,U){return new xE({type:"template_literal",parts:$,...Q$.normalizeParams(U)})}var hE=g("ZodLazy",($,U)=>{E1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>gO($,J,Q,W),$.unwrap=()=>$._zod.def.getter()});function fE($){return new hE({type:"lazy",getter:$})}var uE=g("ZodPromise",($,U)=>{O1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>jO($,J,Q,W),$.unwrap=()=>$._zod.def.innerType});function G5($){return new uE({type:"promise",innerType:$})}var lE=g("ZodFunction",($,U)=>{G1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>DO($,J,Q,W)});function O5($){return new lE({type:"function",input:Array.isArray($?.input)?ZE($?.input):$?.input??wQ(c0()),output:$?.output??c0()})}var _Q=g("ZodCustom",($,U)=>{k1.init($,U),c$.init($,U),$._zod.processJSONSchema=(J,Q,W)=>IO($,J,Q,W)});function E5($){let U=new V6({check:"custom"});return U._zod.check=$,U}function k5($,U){return cG(_Q,$??(()=>!0),U)}function mE($,U={}){return nG(_Q,$,U)}function pE($,U){return iG($,U)}var q5=oG,Z5=rG;function I5($,U={}){let J=new _Q({type:"custom",check:"custom",fn:(Q)=>Q instanceof $,abort:!0,...Q$.normalizeParams(U)});return J._zod.bag.Class=$,J._zod.check=(Q)=>{if(!(Q.value instanceof $))Q.issues.push({code:"invalid_type",expected:$.name,input:Q.value,inst:J,path:[...J._zod.def.path??[]]})},J}var D5=(...$)=>aG({Codec:zQ,Boolean:HW,String:QW},...$);function F5($){let U=fE(()=>{return R7([ZQ($),eO(),$E(),QE(),wQ(U),IE(ZQ(),U)])});return U}function L5($,U){return new gE({type:"pipe",in:w7($),out:U})}var aP={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function sP($){S6({customError:$})}function tP(){return S6().customError}var dE;(function($){})(dE||(dE={}));var I$={...qQ,...oK,iso:UW},eP=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function $z($,U){let J=$.$schema;if(J==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(J==="http://json-schema.org/draft-07/schema#")return"draft-7";if(J==="http://json-schema.org/draft-04/schema#")return"draft-4";return U??"draft-2020-12"}function Uz($,U){if(!$.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let J=$.slice(1).split("/").filter(Boolean);if(J.length===0)return U.rootSchema;let Q=U.version==="draft-2020-12"?"$defs":"definitions";if(J[0]===Q){let W=J[1];if(!W||!U.defs[W])throw Error(`Reference not found: ${$}`);return U.defs[W]}throw Error(`Reference not found: ${$}`)}function R5($,U){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return I$.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if($.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if($.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if($.if!==void 0||$.then!==void 0||$.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if($.dependentSchemas!==void 0||$.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if($.$ref){let W=$.$ref;if(U.refs.has(W))return U.refs.get(W);if(U.processing.has(W))return I$.lazy(()=>{if(!U.refs.has(W))throw Error(`Circular reference not resolved: ${W}`);return U.refs.get(W)});U.processing.add(W);let K=Uz(W,U),X=JU(K,U);return U.refs.set(W,X),U.processing.delete(W),X}if($.enum!==void 0){let W=$.enum;if(U.version==="openapi-3.0"&&$.nullable===!0&&W.length===1&&W[0]===null)return I$.null();if(W.length===0)return I$.never();if(W.length===1)return I$.literal(W[0]);if(W.every((X)=>typeof X==="string"))return I$.enum(W);let K=W.map((X)=>I$.literal(X));if(K.length<2)return K[0];return I$.union([K[0],K[1],...K.slice(2)])}if($.const!==void 0)return I$.literal($.const);let J=$.type;if(Array.isArray(J)){let W=J.map((K)=>{let X={...$,type:K};return R5(X,U)});if(W.length===0)return I$.never();if(W.length===1)return W[0];return I$.union(W)}if(!J)return I$.any();let Q;switch(J){case"string":{let W=I$.string();if($.format){let K=$.format;if(K==="email")W=W.check(I$.email());else if(K==="uri"||K==="uri-reference")W=W.check(I$.url());else if(K==="uuid"||K==="guid")W=W.check(I$.uuid());else if(K==="date-time")W=W.check(I$.iso.datetime());else if(K==="date")W=W.check(I$.iso.date());else if(K==="time")W=W.check(I$.iso.time());else if(K==="duration")W=W.check(I$.iso.duration());else if(K==="ipv4")W=W.check(I$.ipv4());else if(K==="ipv6")W=W.check(I$.ipv6());else if(K==="mac")W=W.check(I$.mac());else if(K==="cidr")W=W.check(I$.cidrv4());else if(K==="cidr-v6")W=W.check(I$.cidrv6());else if(K==="base64")W=W.check(I$.base64());else if(K==="base64url")W=W.check(I$.base64url());else if(K==="e164")W=W.check(I$.e164());else if(K==="jwt")W=W.check(I$.jwt());else if(K==="emoji")W=W.check(I$.emoji());else if(K==="nanoid")W=W.check(I$.nanoid());else if(K==="cuid")W=W.check(I$.cuid());else if(K==="cuid2")W=W.check(I$.cuid2());else if(K==="ulid")W=W.check(I$.ulid());else if(K==="xid")W=W.check(I$.xid());else if(K==="ksuid")W=W.check(I$.ksuid())}if(typeof $.minLength==="number")W=W.min($.minLength);if(typeof $.maxLength==="number")W=W.max($.maxLength);if($.pattern)W=W.regex(new RegExp($.pattern));Q=W;break}case"number":case"integer":{let W=J==="integer"?I$.number().int():I$.number();if(typeof $.minimum==="number")W=W.min($.minimum);if(typeof $.maximum==="number")W=W.max($.maximum);if(typeof $.exclusiveMinimum==="number")W=W.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")W=W.gt($.minimum);if(typeof $.exclusiveMaximum==="number")W=W.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")W=W.lt($.maximum);if(typeof $.multipleOf==="number")W=W.multipleOf($.multipleOf);Q=W;break}case"boolean":{Q=I$.boolean();break}case"null":{Q=I$.null();break}case"object":{let W={},K=$.properties||{},X=new Set($.required||[]);for(let[N,Y]of Object.entries(K)){let G=JU(Y,U);W[N]=X.has(N)?G:G.optional()}if($.propertyNames){let N=JU($.propertyNames,U),Y=$.additionalProperties&&typeof $.additionalProperties==="object"?JU($.additionalProperties,U):I$.any();if(Object.keys(W).length===0){Q=I$.record(N,Y);break}let G=I$.object(W).passthrough(),O=I$.looseRecord(N,Y);Q=I$.intersection(G,O);break}if($.patternProperties){let N=$.patternProperties,Y=Object.keys(N),G=[];for(let E of Y){let k=JU(N[E],U),I=I$.string().regex(new RegExp(E));G.push(I$.looseRecord(I,k))}let O=[];if(Object.keys(W).length>0)O.push(I$.object(W).passthrough());if(O.push(...G),O.length===0)Q=I$.object({}).passthrough();else if(O.length===1)Q=O[0];else{let E=I$.intersection(O[0],O[1]);for(let k=2;k<O.length;k++)E=I$.intersection(E,O[k]);Q=E}break}let H=I$.object(W);if($.additionalProperties===!1)Q=H.strict();else if(typeof $.additionalProperties==="object")Q=H.catchall(JU($.additionalProperties,U));else Q=H.passthrough();break}case"array":{let{prefixItems:W,items:K}=$;if(W&&Array.isArray(W)){let X=W.map((N)=>JU(N,U)),H=K&&typeof K==="object"&&!Array.isArray(K)?JU(K,U):void 0;if(H)Q=I$.tuple(X).rest(H);else Q=I$.tuple(X);if(typeof $.minItems==="number")Q=Q.check(I$.minLength($.minItems));if(typeof $.maxItems==="number")Q=Q.check(I$.maxLength($.maxItems))}else if(Array.isArray(K)){let X=K.map((N)=>JU(N,U)),H=$.additionalItems&&typeof $.additionalItems==="object"?JU($.additionalItems,U):void 0;if(H)Q=I$.tuple(X).rest(H);else Q=I$.tuple(X);if(typeof $.minItems==="number")Q=Q.check(I$.minLength($.minItems));if(typeof $.maxItems==="number")Q=Q.check(I$.maxLength($.maxItems))}else if(K!==void 0){let X=JU(K,U),H=I$.array(X);if(typeof $.minItems==="number")H=H.min($.minItems);if(typeof $.maxItems==="number")H=H.max($.maxItems);Q=H}else Q=I$.array(I$.any());break}default:throw Error(`Unsupported type: ${J}`)}return Q}function JU($,U){if(typeof $==="boolean")return $?I$.any():I$.never();let J=R5($,U),Q=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let H=$.anyOf.map((Y)=>JU(Y,U)),N=I$.union(H);J=Q?I$.intersection(J,N):N}if($.oneOf&&Array.isArray($.oneOf)){let H=$.oneOf.map((Y)=>JU(Y,U)),N=I$.xor(H);J=Q?I$.intersection(J,N):N}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)J=Q?J:I$.any();else{let H=Q?J:JU($.allOf[0],U),N=Q?0:1;for(let Y=N;Y<$.allOf.length;Y++)H=I$.intersection(H,JU($.allOf[Y],U));J=H}if($.nullable===!0&&U.version==="openapi-3.0")J=I$.nullable(J);if($.readOnly===!0)J=I$.readonly(J);if($.default!==void 0)J=J.default($.default);let W={},K=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let H of K)if(H in $)W[H]=$[H];let X=["contentEncoding","contentMediaType","contentSchema"];for(let H of X)if(H in $)W[H]=$[H];for(let H of Object.keys($))if(!eP.has(H))W[H]=$[H];if(Object.keys(W).length>0)U.registry.add(J,W);if($.description)J=J.describe($.description);return J}function V5($,U){if(typeof $==="boolean")return $?I$.any():I$.never();let J;try{J=JSON.parse(JSON.stringify($))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let Q=$z(J,U?.defaultTarget),W=J.$defs||J.definitions||{},K={version:Q,defs:W,refs:new Map,processing:new Set,rootSchema:J,registry:U?.registry??r6};return JU(J,K)}var cE={};RJ(cE,{string:()=>Jz,number:()=>Wz,date:()=>Xz,boolean:()=>Qz,bigint:()=>Kz});function Jz($){return kG(QW,$)}function Wz($){return VG(XW,$)}function Qz($){return AG(HW,$)}function Kz($){return SG(NW,$)}function Xz($){return lG(VQ,$)}S6(HQ());/*!+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of e.seen.entries()){let a=o[1];if(t===o[0]){s(o);continue}if(e.external){let l=e.external.registry.get(o[0])?.id;if(t!==o[0]&&l){s(o);continue}}if(e.metadataRegistry.get(o[0])?.id){s(o);continue}if(a.cycle){s(o);continue}if(a.count>1){if(e.reused==="ref"){s(o);continue}}}}function zu(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},f=c.ref;if(c.ref=null,f){i(f);let d=e.seen.get(f),g=d.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(g);else Object.assign(l,g);if(Object.assign(l,u),a._zod.parent===f)for(let p in l){if(p==="$ref"||p==="allOf")continue;if(!(p in u))delete l[p]}if(g.$ref&&d.def)for(let p in l){if(p==="$ref"||p==="allOf")continue;if(p in d.def&&JSON.stringify(l[p])===JSON.stringify(d.def[p]))delete l[p]}}let h=a._zod.parent;if(h&&h!==f){i(h);let d=e.seen.get(h);if(d?.schema.$ref){if(l.$ref=d.schema.$ref,d.def)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(g in d.def&&JSON.stringify(l[g])===JSON.stringify(d.def[g]))delete l[g]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())i(a[0]);let r={};if(e.target==="draft-2020-12")r.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")r.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")r.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}Object.assign(r,n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&r.id===s)delete r.id;let o=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;o[c.defId]=c.def}}if(e.external);else if(Object.keys(o).length>0)if(e.target==="draft-2020-12")r.$defs=o;else r.definitions=o;try{let a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Js(t,"input",e.processors),output:Js(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Qt(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return Qt(i.element,n);if(i.type==="set")return Qt(i.valueType,n);if(i.type==="lazy")return Qt(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return Qt(i.innerType,n);if(i.type==="intersection")return Qt(i.left,n)||Qt(i.right,n);if(i.type==="record"||i.type==="map")return Qt(i.keyType,n)||Qt(i.valueType,n);if(i.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Qt(i.in,n)||Qt(i.out,n)}if(i.type==="object"){for(let r in i.shape)if(Qt(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(let r of i.options)if(Qt(r,n))return!0;return!1}if(i.type==="tuple"){for(let r of i.items)if(Qt(r,n))return!0;if(i.rest&&Qt(i.rest,n))return!0;return!1}return!1}var a_=(e,t={})=>(n)=>{let i=Ou({...n,processors:t});return At(e,i),Fu(i,e),zu(i,e)},Js=(e,t,n={})=>(i)=>{let{libraryOptions:r,target:s}=i??{},o=Ou({...r??{},target:s,io:t,processors:n});return At(e,o),Fu(o,e),zu(o,e)};var hw={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},c_=(e,t,n,i)=>{let r=n;r.type="string";let{minimum:s,maximum:o,format:a,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof s==="number")r.minLength=s;if(typeof o==="number")r.maxLength=o;if(a){if(r.format=hw[a]??a,r.format==="")delete r.format;if(a==="time")delete r.format}if(l)r.contentEncoding=l;if(c&&c.size>0){let u=[...c];if(u.length===1)r.pattern=u[0].source;else if(u.length>1)r.allOf=[...u.map((f)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}},l_=(e,t,n,i)=>{let r=n,{minimum:s,maximum:o,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))r.type="integer";else r.type="number";let f=typeof u==="number"&&u>=(s??Number.NEGATIVE_INFINITY),h=typeof l==="number"&&l<=(o??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(d)r.minimum=u,r.exclusiveMinimum=!0;else r.exclusiveMinimum=u;else if(typeof s==="number")r.minimum=s;if(h)if(d)r.maximum=l,r.exclusiveMaximum=!0;else r.exclusiveMaximum=l;else if(typeof o==="number")r.maximum=o;if(typeof c==="number")r.multipleOf=c},u_=(e,t,n,i)=>{n.type="boolean"};var h_=(e,t,n,i)=>{n.not={}};var f_=(e,t,n,i)=>{};var d_=(e,t,n,i)=>{let r=e._zod.def,s=ba(r.entries);if(s.every((o)=>typeof o==="number"))n.type="number";if(s.every((o)=>typeof o==="string"))n.type="string";n.enum=s},p_=(e,t,n,i)=>{let r=e._zod.def,s=[];for(let o of r.values)if(o===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(o));else s.push(o);if(s.length===0);else if(s.length===1){let o=s[0];if(n.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[o];else n.const=o}else{if(s.every((o)=>typeof o==="number"))n.type="number";if(s.every((o)=>typeof o==="string"))n.type="string";if(s.every((o)=>typeof o==="boolean"))n.type="boolean";if(s.every((o)=>o===null))n.type="null";n.enum=s}};var m_=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")};var g_=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")};var __=(e,t,n,i)=>{let r=n,s=e._zod.def,{minimum:o,maximum:a}=e._zod.bag;if(typeof o==="number")r.minItems=o;if(typeof a==="number")r.maxItems=a;r.type="array",r.items=At(s.element,t,{...i,path:[...i.path,"items"]})},x_=(e,t,n,i)=>{let r=n,s=e._zod.def;r.type="object",r.properties={};let o=s.shape;for(let l in o)r.properties[l]=At(o[l],t,{...i,path:[...i.path,"properties",l]});let a=new Set(Object.keys(o)),c=new Set([...a].filter((l)=>{let u=s.shape[l]._zod;if(t.io==="input")return u.optin===void 0;else return u.optout===void 0}));if(c.size>0)r.required=Array.from(c);if(s.catchall?._zod.def.type==="never")r.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")r.additionalProperties=!1}else if(s.catchall)r.additionalProperties=At(s.catchall,t,{...i,path:[...i.path,"additionalProperties"]})},v_=(e,t,n,i)=>{let r=e._zod.def,s=r.inclusive===!1,o=r.options.map((a,c)=>At(a,t,{...i,path:[...i.path,s?"oneOf":"anyOf",c]}));if(s)n.oneOf=o;else n.anyOf=o},y_=(e,t,n,i)=>{let r=e._zod.def,s=At(r.left,t,{...i,path:[...i.path,"allOf",0]}),o=At(r.right,t,{...i,path:[...i.path,"allOf",1]}),a=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...a(s)?s.allOf:[s],...a(o)?o.allOf:[o]];n.allOf=c};var b_=(e,t,n,i)=>{let r=n,s=e._zod.def;r.type="object";let o=s.keyType,c=o._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let u=At(s.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(let f of c)r.patternProperties[f.source]=u}else{if(t.target==="draft-07"||t.target==="draft-2020-12")r.propertyNames=At(s.keyType,t,{...i,path:[...i.path,"propertyNames"]});r.additionalProperties=At(s.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let l=o._zod.values;if(l){let u=[...l].filter((f)=>typeof f==="string"||typeof f==="number");if(u.length>0)r.required=u}},S_=(e,t,n,i)=>{let r=e._zod.def,s=At(r.innerType,t,i),o=t.seen.get(e);if(t.target==="openapi-3.0")o.ref=r.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},M_=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType},w_=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},T_=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);if(s.ref=r.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(r.defaultValue))},E_=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},A_=(e,t,n,i)=>{let r=e._zod.def,s=r.in._zod.traits.has("$ZodTransform"),o=t.io==="input"?s?r.out:r.in:r.out;At(o,t,i);let a=t.seen.get(e);a.ref=o},R_=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0};var ku=(e,t,n,i)=>{let r=e._zod.def;At(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType};var xw=q("ZodISODateTime",(e,t)=>{Vm.init(e,t),xt.init(e,t)});function C_(e){return Yg(xw,e)}var vw=q("ZodISODate",(e,t)=>{Wm.init(e,t),xt.init(e,t)});function P_(e){return jg(vw,e)}var yw=q("ZodISOTime",(e,t)=>{$m.init(e,t),xt.init(e,t)});function I_(e){return Jg(yw,e)}var bw=q("ZodISODuration",(e,t)=>{Zm.init(e,t),xt.init(e,t)});function L_(e){return Kg(bw,e)}var ww=(e,t)=>{Ea.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>Tp(e,n)},flatten:{value:(n)=>wp(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,$s,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,$s,2)}},isEmpty:{get(){return e.issues.length===0}}})};var fn=q("ZodError",ww,{Parent:Error});var N_=Aa(fn),D_=Ra(fn),U_=Zs(fn),O_=Xs(fn),F_=Rp(fn),z_=Cp(fn),k_=Pp(fn),B_=Ip(fn),G_=Lp(fn),H_=Np(fn),V_=Dp(fn),W_=Up(fn);var $_=new WeakMap;function Ks(e,t,n){let i=Object.getPrototypeOf(e),r=$_.get(i);if(!r)r=new Set,$_.set(i,r);if(r.has(t))return;r.add(t);for(let s in n){let o=n[s];Object.defineProperty(i,s,{configurable:!0,enumerable:!1,get(){let a=o.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var vt=q("ZodType",(e,t)=>(_t.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Js(e,"input"),output:Js(e,"output")}}),e.toJSONSchema=a_(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,i)=>N_(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>U_(e,n,i),e.parseAsync=async(n,i)=>D_(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>O_(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>F_(e,n,i),e.decode=(n,i)=>z_(e,n,i),e.encodeAsync=async(n,i)=>k_(e,n,i),e.decodeAsync=async(n,i)=>B_(e,n,i),e.safeEncode=(n,i)=>G_(e,n,i),e.safeDecode=(n,i)=>H_(e,n,i),e.safeEncodeAsync=async(n,i)=>V_(e,n,i),e.safeDecodeAsync=async(n,i)=>W_(e,n,i),Ks(e,"ZodType",{check(...n){let i=this.def;return this.clone(Hi(i,{checks:[...i.checks??[],...n.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,i){return jn(this,n,i)},brand(){return this},register(n,i){return n.add(this,i),this},refine(n,i){return this.check(bT(n,i))},superRefine(n,i){return this.check(ST(n,i))},overwrite(n){return this.check(Zi(n))},optional(){return Y_(this)},exactOptional(){return cT(this)},nullable(){return j_(this)},nullish(){return Y_(j_(this))},nonoptional(n){return pT(this,n)},array(){return Ba(this)},or(n){return eT([this,n])},and(n){return nT(this,n)},transform(n){return J_(this,oT(n))},default(n){return hT(this,n)},prefault(n){return dT(this,n)},catch(n){return gT(this,n)},pipe(n){return J_(this,n)},readonly(){return vT(this)},describe(n){let i=this.clone();return _r.add(i,{description:n}),i},meta(...n){if(n.length===0)return _r.get(this);let i=this.clone();return _r.add(i,n[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return _r.get(e)?.description},configurable:!0}),e)),K_=q("_ZodString",(e,t)=>{La.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(i,r,s)=>c_(e,i,r,s);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ks(e,"_ZodString",{regex(...i){return this.check(Tu(...i))},includes(...i){return this.check(Ru(...i))},startsWith(...i){return this.check(Cu(...i))},endsWith(...i){return this.check(Pu(...i))},min(...i){return this.check(ss(...i))},max(...i){return this.check(Oa(...i))},length(...i){return this.check(Fa(...i))},nonempty(...i){return this.check(ss(1,...i))},lowercase(i){return this.check(Eu(i))},uppercase(i){return this.check(Au(i))},trim(){return this.check(Lu())},normalize(...i){return this.check(Iu(...i))},toLowerCase(){return this.check(Nu())},toUpperCase(){return this.check(Du())},slugify(){return this.check(Uu())}})}),Ew=q("ZodString",(e,t)=>{La.init(e,t),K_.init(e,t),e.email=(n)=>e.check(Rg(Aw,n)),e.url=(n)=>e.check(Ng(Rw,n)),e.jwt=(n)=>e.check(qg(Vw,n)),e.emoji=(n)=>e.check(Dg(Cw,n)),e.guid=(n)=>e.check(wu(Z_,n)),e.uuid=(n)=>e.check(Cg(ka,n)),e.uuidv4=(n)=>e.check(Pg(ka,n)),e.uuidv6=(n)=>e.check(Ig(ka,n)),e.uuidv7=(n)=>e.check(Lg(ka,n)),e.nanoid=(n)=>e.check(Ug(Pw,n)),e.guid=(n)=>e.check(wu(Z_,n)),e.cuid=(n)=>e.check(Og(Iw,n)),e.cuid2=(n)=>e.check(Fg(Lw,n)),e.ulid=(n)=>e.check(zg(Nw,n)),e.base64=(n)=>e.check($g(Bw,n)),e.base64url=(n)=>e.check(Zg(Gw,n)),e.xid=(n)=>e.check(kg(Dw,n)),e.ksuid=(n)=>e.check(Bg(Uw,n)),e.ipv4=(n)=>e.check(Gg(Ow,n)),e.ipv6=(n)=>e.check(Hg(Fw,n)),e.cidrv4=(n)=>e.check(Vg(zw,n)),e.cidrv6=(n)=>e.check(Wg(kw,n)),e.e164=(n)=>e.check(Xg(Hw,n)),e.datetime=(n)=>e.check(C_(n)),e.date=(n)=>e.check(P_(n)),e.time=(n)=>e.check(I_(n)),e.duration=(n)=>e.check(L_(n))});function Yt(e){return Ag(Ew,e)}var xt=q("ZodStringFormat",(e,t)=>{gt.init(e,t),K_.init(e,t)}),Aw=q("ZodEmail",(e,t)=>{Dm.init(e,t),xt.init(e,t)});var Z_=q("ZodGUID",(e,t)=>{Lm.init(e,t),xt.init(e,t)});var ka=q("ZodUUID",(e,t)=>{Nm.init(e,t),xt.init(e,t)});var Rw=q("ZodURL",(e,t)=>{Um.init(e,t),xt.init(e,t)});var Cw=q("ZodEmoji",(e,t)=>{Om.init(e,t),xt.init(e,t)});var Pw=q("ZodNanoID",(e,t)=>{Fm.init(e,t),xt.init(e,t)});var Iw=q("ZodCUID",(e,t)=>{zm.init(e,t),xt.init(e,t)});var Lw=q("ZodCUID2",(e,t)=>{km.init(e,t),xt.init(e,t)});var Nw=q("ZodULID",(e,t)=>{Bm.init(e,t),xt.init(e,t)});var Dw=q("ZodXID",(e,t)=>{Gm.init(e,t),xt.init(e,t)});var Uw=q("ZodKSUID",(e,t)=>{Hm.init(e,t),xt.init(e,t)});var Ow=q("ZodIPv4",(e,t)=>{Xm.init(e,t),xt.init(e,t)});var Fw=q("ZodIPv6",(e,t)=>{qm.init(e,t),xt.init(e,t)});var zw=q("ZodCIDRv4",(e,t)=>{Ym.init(e,t),xt.init(e,t)});var kw=q("ZodCIDRv6",(e,t)=>{jm.init(e,t),xt.init(e,t)});var Bw=q("ZodBase64",(e,t)=>{Km.init(e,t),xt.init(e,t)});var Gw=q("ZodBase64URL",(e,t)=>{Qm.init(e,t),xt.init(e,t)});var Hw=q("ZodE164",(e,t)=>{eg.init(e,t),xt.init(e,t)});var Vw=q("ZodJWT",(e,t)=>{tg.init(e,t),xt.init(e,t)});var Q_=q("ZodNumber",(e,t)=>{Su.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(i,r,s)=>l_(e,i,r,s),Ks(e,"ZodNumber",{gt(i,r){return this.check(Da(i,r))},gte(i,r){return this.check(js(i,r))},min(i,r){return this.check(js(i,r))},lt(i,r){return this.check(Na(i,r))},lte(i,r){return this.check(Ys(i,r))},max(i,r){return this.check(Ys(i,r))},int(i){return this.check(X_(i))},safe(i){return this.check(X_(i))},positive(i){return this.check(Da(0,i))},nonnegative(i){return this.check(js(0,i))},negative(i){return this.check(Na(0,i))},nonpositive(i){return this.check(Ys(0,i))},multipleOf(i,r){return this.check(Ua(i,r))},step(i,r){return this.check(Ua(i,r))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??0.5),e.isFinite=!0,e.format=n.format??null});function Ww(e){return Qg(Q_,e)}var $w=q("ZodNumberFormat",(e,t)=>{ng.init(e,t),Q_.init(e,t)});function X_(e){return e_($w,e)}var Zw=q("ZodBoolean",(e,t)=>{ig.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>u_(e,n,i,r)});function Xw(e){return t_(Zw,e)}var qw=q("ZodUnknown",(e,t)=>{rg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>f_(e,n,i,r)});function xr(){return n_(qw)}var Yw=q("ZodNever",(e,t)=>{sg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>h_(e,n,i,r)});function jw(e){return i_(Yw,e)}var Jw=q("ZodArray",(e,t)=>{og.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>__(e,n,i,r),e.element=t.element,Ks(e,"ZodArray",{min(n,i){return this.check(ss(n,i))},nonempty(n){return this.check(ss(1,n))},max(n,i){return this.check(Oa(n,i))},length(n,i){return this.check(Fa(n,i))},unwrap(){return this.element}})});function Ba(e,t){return r_(Jw,e,t)}var Kw=q("ZodObject",(e,t)=>{lg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>x_(e,n,i,r),rt(e,"shape",()=>t.shape),Ks(e,"ZodObject",{keyof(){return t0(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:xr()})},loose(){return this.clone({...this._zod.def,catchall:xr()})},strict(){return this.clone({...this._zod.def,catchall:jw()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return QM(this,n)},safeExtend(n){return ew(this,n)},merge(n){return tw(this,n)},pick(n){return JM(this,n)},omit(n){return KM(this,n)},partial(...n){return nw(n0,this,n[0])},required(...n){return iw(i0,this,n[0])}})});function Qs(e,t){let n={type:"object",shape:e??{},...Te(t)};return new Kw(n)}var Qw=q("ZodUnion",(e,t)=>{ug.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>v_(e,n,i,r),e.options=t.options});function eT(e,t){return new Qw({type:"union",options:e,...Te(t)})}var tT=q("ZodIntersection",(e,t)=>{hg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>y_(e,n,i,r)});function nT(e,t){return new tT({type:"intersection",left:e,right:t})}var q_=q("ZodRecord",(e,t)=>{fg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>b_(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function e0(e,t,n){if(!t||!t._zod)return new q_({type:"record",keyType:Yt(),valueType:e,...Te(t)});return new q_({type:"record",keyType:e,valueType:t,...Te(n)})}var Bu=q("ZodEnum",(e,t)=>{dg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(i,r,s)=>d_(e,i,r,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{let s={};for(let o of i)if(n.has(o))s[o]=t.entries[o];else throw Error(`Key ${o} not found in enum`);return new Bu({...t,checks:[],...Te(r),entries:s})},e.exclude=(i,r)=>{let s={...t.entries};for(let o of i)if(n.has(o))delete s[o];else throw Error(`Key ${o} not found in enum`);return new Bu({...t,checks:[],...Te(r),entries:s})}});function t0(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((i)=>[i,i])):e;return new Bu({type:"enum",entries:n,...Te(t)})}var iT=q("ZodLiteral",(e,t)=>{pg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>p_(e,n,i,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function rT(e,t){return new iT({type:"literal",values:Array.isArray(e)?e:[e],...Te(t)})}var sT=q("ZodTransform",(e,t)=>{mg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>g_(e,n,i,r),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Vs(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(gr(s,n.value,t));else{let o=s;if(o.fatal)o.continue=!1;o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),n.issues.push(gr(o))}};let r=t.transform(n.value,n);if(r instanceof Promise)return r.then((s)=>(n.value=s,n.fallback=!0,n));return n.value=r,n.fallback=!0,n}});function oT(e){return new sT({type:"transform",transform:e})}var n0=q("ZodOptional",(e,t)=>{Mu.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ku(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function Y_(e){return new n0({type:"optional",innerType:e})}var aT=q("ZodExactOptional",(e,t)=>{gg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>ku(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function cT(e){return new aT({type:"optional",innerType:e})}var lT=q("ZodNullable",(e,t)=>{_g.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>S_(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function j_(e){return new lT({type:"nullable",innerType:e})}var uT=q("ZodDefault",(e,t)=>{xg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>w_(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function hT(e,t){return new uT({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():du(t)}})}var fT=q("ZodPrefault",(e,t)=>{vg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>T_(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function dT(e,t){return new fT({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():du(t)}})}var i0=q("ZodNonOptional",(e,t)=>{yg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>M_(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function pT(e,t){return new i0({type:"nonoptional",innerType:e,...Te(t)})}var mT=q("ZodCatch",(e,t)=>{bg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>E_(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function gT(e,t){return new mT({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var _T=q("ZodPipe",(e,t)=>{Sg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>A_(e,n,i,r),e.in=t.in,e.out=t.out});function J_(e,t){return new _T({type:"pipe",in:e,out:t})}var xT=q("ZodReadonly",(e,t)=>{Mg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>R_(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function vT(e){return new xT({type:"readonly",innerType:e})}var yT=q("ZodCustom",(e,t)=>{wg.init(e,t),vt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>m_(e,n,i,r)});function bT(e,t={}){return s_(yT,e,t)}function ST(e,t){return o_(e,t)}/*!fflate - fast JavaScript compression/decompression<https://101arrowz.github.io/fflate>Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSEversion 0.8.2-*/var T6=Uint8Array,zU=Uint16Array,$k=Int32Array,P7=new T6([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]),z7=new T6([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]),rE=new T6([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),A5=function($,U){var J=new zU(31);for(var Q=0;Q<31;++Q)J[Q]=U+=1<<$[Q-1];var W=new $k(J[30]);for(var Q=1;Q<30;++Q)for(var K=J[Q];K<J[Q+1];++K)W[K]=K-J[Q]<<5|Q;return{b:J,r:W}},C5=A5(P7,2),S5=C5.b,aE=C5.r;S5[28]=258,aE[258]=28;var T5=A5(z7,0),Hz=T5.b,w5=T5.r,sE=new zU(32768);for(W6=0;W6<32768;++W6)qJ=(W6&43690)>>1|(W6&21845)<<1,qJ=(qJ&52428)>>2|(qJ&13107)<<2,qJ=(qJ&61680)>>4|(qJ&3855)<<4,sE[W6]=((qJ&65280)>>8|(qJ&255)<<8)>>1;var qJ,W6,ZJ=function($,U,J){var Q=$.length,W=0,K=new zU(U);for(;W<Q;++W)if($[W])++K[$[W]-1];var X=new zU(U);for(W=1;W<U;++W)X[W]=X[W-1]+K[W-1]<<1;var H;if(J){H=new zU(1<<U);var N=15-U;for(W=0;W<Q;++W)if($[W]){var Y=W<<4|$[W],G=U-$[W],O=X[$[W]-1]++<<G;for(var E=O|(1<<G)-1;O<=E;++O)H[sE[O]>>N]=Y}}else{H=new zU(Q);for(W=0;W<Q;++W)if($[W])H[W]=sE[X[$[W]-1]++]>>15-$[W]}return H},D0=new T6(288);for(W6=0;W6<144;++W6)D0[W6]=8;var W6;for(W6=144;W6<256;++W6)D0[W6]=9;var W6;for(W6=256;W6<280;++W6)D0[W6]=7;var W6;for(W6=280;W6<288;++W6)D0[W6]=8;var W6,SQ=new T6(32);for(W6=0;W6<32;++W6)SQ[W6]=5;var W6,Nz=ZJ(D0,9,0),Yz=ZJ(D0,9,1),Gz=ZJ(SQ,5,0),Oz=ZJ(SQ,5,1),nE=function($){var U=$[0];for(var J=1;J<$.length;++J)if($[J]>U)U=$[J];return U},rU=function($,U,J){var Q=U/8|0;return($[Q]|$[Q+1]<<8)>>(U&7)&J},iE=function($,U){var J=U/8|0;return($[J]|$[J+1]<<8|$[J+2]<<16)>>(U&7)},Uk=function($){return($+7)/8|0},Jk=function($,U,J){if(U==null||U<0)U=0;if(J==null||J>$.length)J=$.length;return new T6($.subarray(U,J))};var Ez=["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"],xU=function($,U,J){var Q=Error(U||Ez[$]);if(Q.code=$,Error.captureStackTrace)Error.captureStackTrace(Q,xU);if(!J)throw Q;return Q},kz=function($,U,J,Q){var W=$.length,K=Q?Q.length:0;if(!W||U.f&&!U.l)return J||new T6(0);var X=!J,H=X||U.i!=2,N=U.i;if(X)J=new T6(W*3);var Y=function(u$){var p$=J.length;if(u$>p$){var K6=new T6(Math.max(p$*2,u$));K6.set(J),J=K6}},G=U.f||0,O=U.p||0,E=U.b||0,k=U.l,I=U.d,R=U.m,q=U.n,Z=W*8;do{if(!k){G=rU($,O,1);var _=rU($,O+1,3);if(O+=3,!_){var P=Uk(O)+4,L=$[P-4]|$[P-3]<<8,B=P+L;if(B>W){if(N)xU(0);break}if(H)Y(E+L);J.set($.subarray(P,B),E),U.b=E+=L,U.p=O=B*8,U.f=G;continue}else if(_==1)k=Yz,I=Oz,R=9,q=5;else if(_==2){var z=rU($,O,31)+257,A=rU($,O+10,15)+4,D=z+rU($,O+5,31)+1;O+=14;var w=new T6(D),h=new T6(19);for(var C=0;C<A;++C)h[rE[C]]=rU($,O+C*3,7);O+=A*3;var f=nE(h),s=(1<<f)-1,x=ZJ(h,f,1);for(var C=0;C<D;){var d=x[rU($,O,s)];O+=d&15;var P=d>>4;if(P<16)w[C++]=P;else{var c=0,y=0;if(P==16)y=3+rU($,O,3),O+=2,c=w[C-1];else if(P==17)y=3+rU($,O,7),O+=3;else if(P==18)y=11+rU($,O,127),O+=7;while(y--)w[C++]=c}}var t=w.subarray(0,z),e=w.subarray(z);R=nE(t),q=nE(e),k=ZJ(t,R,1),I=ZJ(e,q,1)}else xU(1);if(O>Z){if(N)xU(0);break}}if(H)Y(E+131072);var Y$=(1<<R)-1,R$=(1<<q)-1,w$=O;for(;;w$=O){var c=k[iE($,O)&Y$],$6=c>>4;if(O+=c&15,O>Z){if(N)xU(0);break}if(!c)xU(2);if($6<256)J[E++]=$6;else if($6==256){w$=O,k=null;break}else{var n$=$6-254;if($6>264){var C=$6-257,i=P7[C];n$=rU($,O,(1<<i)-1)+S5[C],O+=i}var X$=I[iE($,O)&R$],D$=X$>>4;if(!X$)xU(3);O+=X$&15;var e=Hz[D$];if(D$>3){var i=z7[D$];e+=iE($,O)&(1<<i)-1,O+=i}if(O>Z){if(N)xU(0);break}if(H)Y(E+131072);var F$=E+n$;if(E<e){var v$=K-e,t$=Math.min(e,F$);if(v$+E<0)xU(3);for(;E<t$;++E)J[E]=Q[v$+E]}for(;E<F$;++E)J[E]=J[E-e]}}if(U.l=k,U.p=w$,U.b=E,U.f=G,k)G=1,U.m=R,U.d=I,U.n=q}while(!G);return E!=J.length&&X?Jk(J,0,E):J.subarray(0,E)},yJ=function($,U,J){J<<=U&7;var Q=U/8|0;$[Q]|=J,$[Q+1]|=J>>8},AQ=function($,U,J){J<<=U&7;var Q=U/8|0;$[Q]|=J,$[Q+1]|=J>>8,$[Q+2]|=J>>16},oE=function($,U){var J=[];for(var Q=0;Q<$.length;++Q)if($[Q])J.push({s:Q,f:$[Q]});var W=J.length,K=J.slice();if(!W)return{t:j5,l:0};if(W==1){var X=new T6(J[0].s+1);return X[J[0].s]=1,{t:X,l:1}}J.sort(function(B,z){return B.f-z.f}),J.push({s:-1,f:25001});var H=J[0],N=J[1],Y=0,G=1,O=2;J[0]={s:-1,f:H.f+N.f,l:H,r:N};while(G!=W-1)H=J[J[Y].f<J[O].f?Y++:O++],N=J[Y!=G&&J[Y].f<J[O].f?Y++:O++],J[G++]={s:-1,f:H.f+N.f,l:H,r:N};var E=K[0].s;for(var Q=1;Q<W;++Q)if(K[Q].s>E)E=K[Q].s;var k=new zU(E+1),I=tE(J[G-1],k,0);if(I>U){var Q=0,R=0,q=I-U,Z=1<<q;K.sort(function(z,A){return k[A.s]-k[z.s]||z.f-A.f});for(;Q<W;++Q){var _=K[Q].s;if(k[_]>U)R+=Z-(1<<I-k[_]),k[_]=U;else break}R>>=q;while(R>0){var P=K[Q].s;if(k[P]<U)R-=1<<U-k[P]++-1;else++Q}for(;Q>=0&&R;--Q){var L=K[Q].s;if(k[L]==U)--k[L],++R}I=U}return{t:new T6(k),l:I}},tE=function($,U,J){return $.s==-1?Math.max(tE($.l,U,J+1),tE($.r,U,J+1)):U[$.s]=J},M5=function($){var U=$.length;while(U&&!$[--U]);var J=new zU(++U),Q=0,W=$[0],K=1,X=function(N){J[Q++]=N};for(var H=1;H<=U;++H)if($[H]==W&&H!=U)++K;else{if(!W&&K>2){for(;K>138;K-=138)X(32754);if(K>2)X(K>10?K-11<<5|28690:K-3<<5|12305),K=0}else if(K>3){X(W),--K;for(;K>6;K-=6)X(8304);if(K>2)X(K-3<<5|8208),K=0}while(K--)X(W);K=1,W=$[H]}return{c:J.subarray(0,Q),n:U}},CQ=function($,U){var J=0;for(var Q=0;Q<U.length;++Q)J+=$[Q]*U[Q];return J},v5=function($,U,J){var Q=J.length,W=Uk(U+2);$[W]=Q&255,$[W+1]=Q>>8,$[W+2]=$[W]^255,$[W+3]=$[W+1]^255;for(var K=0;K<Q;++K)$[W+K+4]=J[K];return(W+4+Q)*8},B5=function($,U,J,Q,W,K,X,H,N,Y,G){yJ(U,G++,J),++W[256];var O=oE(W,15),E=O.t,k=O.l,I=oE(K,15),R=I.t,q=I.l,Z=M5(E),_=Z.c,P=Z.n,L=M5(R),B=L.c,z=L.n,A=new zU(19);for(var D=0;D<_.length;++D)++A[_[D]&31];for(var D=0;D<B.length;++D)++A[B[D]&31];var w=oE(A,7),h=w.t,C=w.l,f=19;for(;f>4&&!h[rE[f-1]];--f);var s=Y+5<<3,x=CQ(W,D0)+CQ(K,SQ)+X,d=CQ(W,E)+CQ(K,R)+X+14+3*f+CQ(A,h)+2*A[16]+3*A[17]+7*A[18];if(N>=0&&s<=x&&s<=d)return v5(U,G,$.subarray(N,N+Y));var c,y,t,e;if(yJ(U,G,1+(d<x)),G+=2,d<x){c=ZJ(E,k,0),y=E,t=ZJ(R,q,0),e=R;var Y$=ZJ(h,C,0);yJ(U,G,P-257),yJ(U,G+5,z-1),yJ(U,G+10,f-4),G+=14;for(var D=0;D<f;++D)yJ(U,G+3*D,h[rE[D]]);G+=3*f;var R$=[_,B];for(var w$=0;w$<2;++w$){var $6=R$[w$];for(var D=0;D<$6.length;++D){var n$=$6[D]&31;if(yJ(U,G,Y$[n$]),G+=h[n$],n$>15)yJ(U,G,$6[D]>>5&127),G+=$6[D]>>12}}}else c=Nz,y=D0,t=Gz,e=SQ;for(var D=0;D<H;++D){var i=Q[D];if(i>255){var n$=i>>18&31;if(AQ(U,G,c[n$+257]),G+=y[n$+257],n$>7)yJ(U,G,i>>23&31),G+=P7[n$];var X$=i&31;if(AQ(U,G,t[X$]),G+=e[X$],X$>3)AQ(U,G,i>>5&8191),G+=z7[X$]}else AQ(U,G,c[i]),G+=y[i]}return AQ(U,G,c[256]),G+y[256]},qz=new $k([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),j5=new T6(0),Zz=function($,U,J,Q,W,K){var X=K.z||$.length,H=new T6(Q+X+5*(1+Math.ceil(X/7000))+W),N=H.subarray(Q,H.length-W),Y=K.l,G=(K.r||0)&7;if(U){if(G)N[0]=K.r>>3;var O=qz[U-1],E=O>>13,k=O&8191,I=(1<<J)-1,R=K.p||new zU(32768),q=K.h||new zU(I+1),Z=Math.ceil(J/3),_=2*Z,P=function(U6){return($[U6]^$[U6+1]<<Z^$[U6+2]<<_)&I},L=new $k(25000),B=new zU(288),z=new zU(32),A=0,D=0,w=K.i||0,h=0,C=K.w||0,f=0;for(;w+2<X;++w){var s=P(w),x=w&32767,d=q[s];if(R[x]=d,q[s]=x,C<=w){var c=X-w;if((A>7000||h>24576)&&(c>423||!Y)){G=B5($,N,0,L,B,z,D,h,f,w-f,G),h=A=D=0,f=w;for(var y=0;y<286;++y)B[y]=0;for(var y=0;y<30;++y)z[y]=0}var t=2,e=0,Y$=k,R$=x-d&32767;if(c>2&&s==P(w-R$)){var w$=Math.min(E,c)-1,$6=Math.min(32767,w),n$=Math.min(258,c);while(R$<=$6&&--Y$&&x!=d){if($[w+t]==$[w+t-R$]){var i=0;for(;i<n$&&$[w+i]==$[w+i-R$];++i);if(i>t){if(t=i,e=R$,i>w$)break;var X$=Math.min(R$,i-2),D$=0;for(var y=0;y<X$;++y){var F$=w-R$+y&32767,v$=R[F$],t$=F$-v$&32767;if(t$>D$)D$=t$,d=F$}}}x=d,d=R[x],R$+=x-d&32767}}if(e){L[h++]=268435456|aE[t]<<18|w5[e];var u$=aE[t]&31,p$=w5[e]&31;D+=P7[u$]+z7[p$],++B[257+u$],++z[p$],C=w+t,++A}else L[h++]=$[w],++B[$[w]]}}for(w=Math.max(w,C);w<X;++w)L[h++]=$[w],++B[$[w]];if(G=B5($,N,Y,L,B,z,D,h,f,w-f,G),!Y)K.r=G&7|N[G/8|0]<<3,G-=7,K.h=q,K.p=R,K.i=w,K.w=C}else{for(var w=K.w||0;w<X+Y;w+=65535){var K6=w+65535;if(K6>=X)N[G/8|0]=Y,K6=X;G=v5(N,G+1,$.subarray(w,K6))}K.i=X}return Jk(H,0,Q+Uk(G)+W)},Iz=function(){var $=new Int32Array(256);for(var U=0;U<256;++U){var J=U,Q=9;while(--Q)J=(J&1&&-306674912)^J>>>1;$[U]=J}return $}(),Dz=function(){var $=-1;return{p:function(U){var J=$;for(var Q=0;Q<U.length;++Q)J=Iz[J&255^U[Q]]^J>>>8;$=J},d:function(){return~$}}};var Fz=function($,U,J,Q,W){if(!W){if(W={l:1},U.dictionary){var K=U.dictionary.subarray(-32768),X=new T6(K.length+$.length);X.set(K),X.set($,K.length),$=X,W.w=K.length}}return Zz($,U.level==null?6:U.level,U.mem==null?W.l?Math.ceil(Math.max(8,Math.min(13,Math.log($.length)))*1.5):20:12+U.mem,J,Q,W)},g5=function($,U){var J={};for(var Q in $)J[Q]=$[Q];for(var Q in U)J[Q]=U[Q];return J};var a6=function($,U,J){for(;J;++U)$[U]=J,J>>>=8};function b5($,U){return Fz($,U||{},0,0)}function y5($,U){return kz($,{i:2},U&&U.out,U&&U.dictionary)}var x5=function($,U,J,Q){for(var W in $){var K=$[W],X=U+W,H=Q;if(Array.isArray(K))H=g5(Q,K[1]),K=K[0];if(K instanceof T6)J[X]=[K,H];else J[X+="/"]=[new T6(0),H],x5(K,X,J,Q)}},P5=typeof TextEncoder<"u"&&new TextEncoder,Lz=typeof TextDecoder<"u"&&new TextDecoder,Rz=0;try{Lz.decode(j5,{stream:!0}),Rz=1}catch($){}function z5($,U){if(U){var J=new T6($.length);for(var Q=0;Q<$.length;++Q)J[Q]=$.charCodeAt(Q);return J}if(P5)return P5.encode($);var W=$.length,K=new T6($.length+($.length>>1)),X=0,H=function(G){K[X++]=G};for(var Q=0;Q<W;++Q){if(X+5>K.length){var N=new T6(X+8+(W-Q<<1));N.set(K),K=N}var Y=$.charCodeAt(Q);if(Y<128||U)H(Y);else if(Y<2048)H(192|Y>>6),H(128|Y&63);else if(Y>55295&&Y<57344)Y=65536+(Y&1047552)|$.charCodeAt(++Q)&1023,H(240|Y>>18),H(128|Y>>12&63),H(128|Y>>6&63),H(128|Y&63);else H(224|Y>>12),H(128|Y>>6&63),H(128|Y&63)}return Jk(K,0,X)}var eE=function($){var U=0;if($)for(var J in $){var Q=$[J].length;if(Q>65535)xU(9);U+=Q+4}return U},_5=function($,U,J,Q,W,K,X,H){var N=Q.length,Y=J.extra,G=H&&H.length,O=eE(Y);if(a6($,U,X!=null?33639248:67324752),U+=4,X!=null)$[U++]=20,$[U++]=J.os;$[U]=20,U+=2,$[U++]=J.flag<<1|(K<0&&8),$[U++]=W&&8,$[U++]=J.compression&255,$[U++]=J.compression>>8;var E=new Date(J.mtime==null?Date.now():J.mtime),k=E.getFullYear()-1980;if(k<0||k>119)xU(10);if(a6($,U,k<<25|E.getMonth()+1<<21|E.getDate()<<16|E.getHours()<<11|E.getMinutes()<<5|E.getSeconds()>>1),U+=4,K!=-1)a6($,U,J.crc),a6($,U+4,K<0?-K-2:K),a6($,U+8,J.size);if(a6($,U+12,N),a6($,U+14,O),U+=16,X!=null)a6($,U,G),a6($,U+6,J.attrs),a6($,U+10,X),U+=14;if($.set(Q,U),U+=N,O)for(var I in Y){var R=Y[I],q=R.length;a6($,U,+I),a6($,U+2,q),$.set(R,U+4),U+=4+q}if(G)$.set(H,U),U+=G;return U},Vz=function($,U,J,Q,W){a6($,U,101010256),a6($,U+8,J),a6($,U+10,J),a6($,U+12,Q),a6($,U+16,W)};function h5($,U){if(!U)U={};var J={},Q=[];x5($,"",J,U);var W=0,K=0;for(var X in J){var H=J[X],N=H[0],Y=H[1],G=Y.level==0?0:8,O=z5(X),E=O.length,k=Y.comment,I=k&&z5(k),R=I&&I.length,q=eE(Y.extra);if(E>65535)xU(11);var Z=G?b5(N,Y):N,_=Z.length,P=Dz();P.p(N),Q.push(g5(Y,{size:N.length,crc:P.d(),c:Z,f:O,m:I,u:E!=X.length||I&&k.length!=R,o:W,compression:G})),W+=30+E+q+_,K+=76+2*(E+q)+(R||0)+_}var L=new T6(K+22),B=W,z=K-W;for(var A=0;A<Q.length;++A){var O=Q[A];_5(L,O.o,O,O.f,O.u,O.c.length);var D=30+O.f.length+eE(O.extra);L.set(O.c,O.o+D),_5(L,W,O,O.f,O.u,O.c.length,O.o,O.m),W+=16+D+(O.m?O.m.length:0)}return Vz(L,W,Q.length,z,B),L}var _7=67108864,Wk=J6.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),wz=J6.string().regex(/^sha256:[a-f0-9]{64}$/),Qk=J6.object({version:J6.literal("kiln.asset.v1"),assetId:Wk,revisionId:Wk,parentRevision:Wk.optional(),name:J6.string().min(1).max(200),tags:J6.array(J6.string().max(80)).max(30),createdAt:J6.string().datetime(),description:J6.string().max(4000).optional(),brief:J6.string().max(8000).optional(),attribution:J6.object({model:J6.string().max(200).optional(),harness:J6.string().max(200).optional(),author:J6.string().max(200).optional()}).optional(),editable:J6.boolean(),files:J6.record(J6.string(),J6.object({sha256:wz,bytes:J6.number().int().nonnegative().max(_7)})),build:J6.object({engine:J6.string(),options:J6.record(J6.string(),J6.unknown()),warnings:J6.array(J6.string()),integration:J6.unknown().optional(),qa:J6.unknown().optional(),dependencies:J6.array(J6.unknown()).optional(),rebuild:J6.enum(["engine-required","external-dependencies-required"])}).optional(),preview:J6.object({fidelity:J6.unknown().optional(),error:J6.string().optional()}).optional()}),Mz=new Set(["asset.glb","source.kiln.js","preview.png"]);function Bz($){let U=Qk.parse($.manifest),J=Object.keys($.files);if(J.length!==Object.keys(U.files).length||!J.includes("asset.glb"))throw Error("Asset file inventory mismatch");let Q=0;for(let W of J){if(!Mz.has(W)||!U.files[W]||U.files[W].bytes!==$.files[W].length)throw Error("Invalid asset file inventory");Q+=$.files[W].length}if(Q>_7||U.editable!==J.includes("source.kiln.js"))throw Error("Invalid asset size or source inventory");if(($.files["source.kiln.js"]?.length??0)>1048576)throw Error("Source exceeds 1 MiB");Kk($.files["asset.glb"])}function Kk($){if($.length<20||$.length>_7)throw Error("Invalid GLB size");let U=new DataView($.buffer,$.byteOffset,$.byteLength);if(U.getUint32(0,!0)!==1179937895||U.getUint32(4,!0)!==2||U.getUint32(8,!0)!==$.length||U.getUint32(16,!0)!==1313821514)throw Error("Invalid GLB header");let J=20+U.getUint32(12,!0);if(J>$.length)throw Error("Invalid GLB JSON length");let Q=JSON.parse(new TextDecoder().decode($.subarray(20,J)));for(let W of[...Q.buffers??[],...Q.images??[]])if(W.uri&&!String(W.uri).startsWith("data:"))throw Error("GLB must embed its resources")}function f5($){if(!$.length||$.length>100)throw Error("Bundle requires 1..100 revisions");let U={},J=0;for(let Q of $){Bz(Q);let W=`${Q.manifest.assetId}/${Q.manifest.revisionId}/`;if(U[`${W}manifest.json`])throw Error("Duplicate bundle revision");U[`${W}manifest.json`]=new TextEncoder().encode(JSON.stringify(Q.manifest,null,2));for(let[K,X]of Object.entries(Q.files))U[W+K]=X}for(let Q of Object.values(U))J+=Q.length;if(J>_7)throw Error("Bundle exceeds 64 MiB");return h5(U,{level:0})}function u5($,U,J=40,Q=[$]){let W=$.getCenter(new j),K=Math.max($.getSize(new j).length()/2,0.01),X=new j(1,0.65,1.25).normalize(),H=new j().crossVectors(new j(0,1,0),X).normalize(),N=new j().crossVectors(X,H),Y=[];for(let _ of Q.length?Q:[$])for(let P of[_.min.x,_.max.x])for(let L of[_.min.y,_.max.y])for(let B of[_.min.z,_.max.z])Y.push(new j(P,L,B));let G=1/0,O=-1/0,E=1/0,k=-1/0;for(let _ of Y){let P=_.clone().sub(W),L=P.dot(H),B=P.dot(N);G=Math.min(G,L),O=Math.max(O,L),E=Math.min(E,B),k=Math.max(k,B)}W.addScaledVector(H,(G+O)/2),W.addScaledVector(N,(E+k)/2);let I=Math.tan(J*Math.PI/360),R=I*U,q=K;for(let _ of Y){let P=_.clone().sub(W),L=P.dot(X);q=Math.max(q,L+Math.abs(P.dot(H))*1.12/R,L+Math.abs(P.dot(N))*1.12/I)}let Z=W.clone().addScaledVector(X,q);return{center:W,radius:K,distance:q,position:Z}}function l5($){let U=new gH({antialias:!0,alpha:!1});U.setPixelRatio(Math.min(devicePixelRatio,2)),U.setClearColor(1382930),U.toneMapping=wW,U.toneMappingExposure=1.15,$.replaceChildren(U.domElement);let J=new V8,Q=new x6(40,1,0.01,1000),W=new nH(Q,U.domElement);W.enableDamping=!0;let K=new dW(U),X=new iH,H=K.fromScene(X,0.04);J.environment=H.texture,X.dispose(),K.dispose();let N=new _8(16773591,2.4);N.position.set(4,8,5),J.add(N),J.add(new b9(14806490,5065021,1.7));let Y,G,O=[],E=!0,k=performance.now(),I=0,R=0,q=!1,Z=(B)=>{let z=new Set,A=new Set,D=new Set;B.traverse((w)=>{let h=w;if(!h.isMesh)return;z.add(h.geometry);for(let C of Array.isArray(h.material)?h.material:[h.material]){A.add(C);for(let f of Object.values(C))if(f instanceof C6)D.add(f)}});for(let w of[...z,...A,...D])w.dispose()},_=()=>{if(!Y)return;let B=new QU().setFromObject(Y,!0),z=[];Y.traverse((C)=>{if(C instanceof B6||C instanceof tJ||C instanceof B8){let f=new QU().setFromObject(C,!0);if(!f.isEmpty())z.push(f)}});let{center:A,radius:D,distance:w,position:h}=u5(B,Q.aspect,Q.fov,z);W.target.copy(A),Q.position.copy(h),Q.near=Math.max(D/1000,0.0001),Q.far=w+D*100,W.minDistance=D*0.1,W.maxDistance=D*80,Q.updateProjectionMatrix(),W.update()},P=new ResizeObserver(()=>{let{clientWidth:B,clientHeight:z}=$;if(!B||!z)return;U.setSize(B,z),Q.aspect=B/z,Q.updateProjectionMatrix()});P.observe($);let L=(B)=>{if(q)return;let z=Math.min((B-k)/1000,0.1);if(k=B,E)G?.update(z);W.update(),U.render(J,Q),I=requestAnimationFrame(L)};return I=requestAnimationFrame(L),{async load(B){let z=++R;Kk(B);let A=new xW;A.setURLModifier((x)=>{if(!x.startsWith("blob:")&&!x.startsWith("data:"))throw Error("External model resources are not loaded");return x});let D=await new mH(A).parseAsync(Uint8Array.from(B).buffer,"");if(q||z!==R){Z(D.scene);return}if(Y)G?.stopAllAction(),G?.uncacheRoot(Y),J.remove(Y),Z(Y);Y=D.scene,J.add(Y),O=D.animations,G=new u9(Y),E=!0;let{clientWidth:w,clientHeight:h}=$;U.setSize(w,h),Q.aspect=w/h,_();let C=0,f=0,s=new Set;return Y.traverse((x)=>{let d=x;if(!d.isMesh)return;f++,C+=(d.geometry.index?.count??d.geometry.attributes.position?.count??0)/3*(d.isInstancedMesh?d.count:1);for(let c of Array.isArray(d.material)?d.material:[d.material])s.add(c)}),{triangles:C,meshes:f,materials:s.size,clips:O.map((x)=>x.name)}},reset:_,wire(B){Y?.traverse((z)=>{let A=z;if(A.isMesh){for(let D of Array.isArray(A.material)?A.material:[A.material])if("wireframe"in D)D.wireframe=B}})},lighting(B){U.toneMappingExposure=B==="bright"?1.65:B==="soft"?0.85:1.15,N.intensity=B==="soft"?0.8:2.4},clip(B){if(G?.stopAllAction(),O[B])G?.clipAction(O[B]).play()},pause(B){E=!B},dispose(){if(q=!0,R++,cancelAnimationFrame(I),P.disconnect(),W.dispose(),Y)Z(Y);H.dispose(),U.dispose(),$.replaceChildren()}}}async function m5($,U,J,Q,W,K){let X="";for(let H=0;H<$.length;H+=8192)X+=String.fromCharCode(...$.subarray(H,H+8192));try{if((await Q("ui/download-file",{contents:[{type:"resource",resource:{uri:`file:///${U}`,mimeType:J,blob:btoa(X)}}]}))?.isError)throw Error("The chat host could not download this file.");return{}}catch(H){if(H.code!==-32601)throw H;if(K){let O=new URL(K);if(O.protocol!=="https:"&&!(O.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(O.hostname)))throw Error("Invalid host download URL");return{downloadUrl:O.href}}if(!W)throw H;let N=new File([Uint8Array.from($)],U,{type:J}),{fileId:Y}=await W.uploadFile(N),{downloadUrl:G}=await W.getFileDownloadUrl({fileId:Y});if(new URL(G).protocol!=="https:")throw Error("Invalid host download URL");return{downloadUrl:G}}}var d5=16777216,c5=Math.ceil(d5/3)*4,i6=($)=>{throw Error(`Asset transfer ${$}. Present the saved asset again or open it in Kiln; the saved files are unchanged.`)};function Pz($){let U="";for(let J=0;J<$.length;J+=8192)U+=String.fromCharCode(...$.subarray(J,J+8192));return btoa(U)}function p5($){if(typeof $!=="string"||$.length>c5)return i6("exceeds the encoded size limit");if($.length%4||!/^[A-Za-z0-9+/]*={0,2}$/.test($))i6("contains damaged base64 data");let U;try{U=atob($)}catch{return i6("contains damaged base64 data")}let J=Uint8Array.from(U,(Q)=>Q.charCodeAt(0));if(Pz(J)!==$)i6("contains noncanonical base64 data");return J}function TQ($){return!!$&&typeof $==="object"&&!Array.isArray($)}async function n5($){if(!TQ($))return i6("metadata is missing");if(typeof $.error==="string")throw Error($.error);let U=Qk.safeParse($.manifest);if(!U.success||!TQ($.files))return i6("metadata is malformed");let J=U.data,Q=Object.entries($.files);if(!Q.length||Q.length>16||!Object.hasOwn($.files,"asset.glb"))return i6("file list is missing or invalid");let W=0,K=0;for(let[N,Y]of Q){if(!/^[a-z0-9][a-z0-9._-]{0,127}$/.test(N)||!Object.hasOwn(J.files,N))return i6("file metadata is missing");if(W+=J.files[N].bytes,W>d5)return i6("exceeds the decoded size limit");let G=typeof Y==="string"?Y:TQ(Y)?Y.data:void 0;if(typeof G!=="string")return i6("file encoding is malformed");if(K+=G.length,K>c5)return i6("exceeds the encoded size limit")}let X={};for(let[N,Y]of Q){let G=J.files[N],O;if(typeof Y==="string")O=p5(Y);else{if(!TQ(Y)||Y.encoding!=="kiln.deflate-base64.v1")return i6("encoding is unsupported");let I=p5(Y.data);try{O=y5(I,{out:new Uint8Array(G.bytes+1)})}catch{return i6("compressed data is damaged")}}if(O.length!==G.bytes)return i6("byte count does not match the saved file");let E=await crypto.subtle.digest("SHA-256",Uint8Array.from(O));if(`sha256:${Array.from(new Uint8Array(E),(I)=>I.toString(16).padStart(2,"0")).join("")}`!==G.sha256)return i6("integrity check failed");X[N]=O}for(let N of Object.keys(J.files))if(!Object.hasOwn(X,N))return i6("is missing a saved file");let H={};if($.downloadUrls!==void 0){if(!TQ($.downloadUrls))return i6("download metadata is malformed");for(let[N,Y]of Object.entries($.downloadUrls)){if(typeof Y!=="string")return i6("download metadata is malformed");H[N]=Y}}return{record:{manifest:J,files:X},downloadUrls:H}}var IJ=($)=>document.getElementById($),DJ=IJ("status"),GU,o5={},vQ,zz=0,FJ=0,A7=new Map;function r5($,U){let J=++zz;return new Promise((Q,W)=>{let K=setTimeout(()=>{A7.delete(J),W(Error("Chat host did not respond."))},20000);A7.set(J,{resolve(X){clearTimeout(K),Q(X)},reject(X){clearTimeout(K),W(X)}}),window.parent.postMessage({jsonrpc:"2.0",id:J,method:$,params:U},"*")})}function i5($,U={}){window.parent.postMessage({jsonrpc:"2.0",method:$,params:U},"*")}function _z($){let U="";for(let J=0;J<$.length;J+=8192)U+=String.fromCharCode(...$.subarray(J,J+8192));return btoa(U)}async function Az($){let U=++FJ;GU=void 0;for(let J of document.querySelectorAll("button[data-download]"))J.disabled=!0;try{if(!$||typeof $!=="object"||Array.isArray($))throw Error("Asset transfer metadata is missing. Present the saved asset again.");await Cz($,U)}catch(J){if(U!==FJ)return;DJ.textContent=J instanceof Error?J.message:"Asset transfer failed. Present the saved asset again."}}async function Cz($,U){if($.isError){DJ.textContent=$.content?.find((Q)=>Q.type==="text")?.text??"This asset could not be opened.";return}let J;try{J=await n5($._meta?.kilnAsset)}catch(Q){if(U!==FJ)return;DJ.textContent=Q instanceof Error?Q.message:"Asset transfer failed. Present the saved asset again.";return}if(U!==FJ)return;GU=J.record,IJ("name").textContent=GU.manifest.name,o5=J.downloadUrls,IJ("revision").textContent=`${GU.manifest.editable?"Editable source included":"GLB asset"} · ${GU.manifest.revisionId.slice(0,10)}`;try{vQ??=l5(IJ("stage"));let Q=await vQ.load(GU.files["asset.glb"]);if(U!==FJ)return;if(Q){IJ("stats").textContent=`${Q.triangles.toLocaleString()} triangles · ${Q.materials} materials · ${(GU.files["asset.glb"].length/1024).toFixed(0)} KB`;let W=IJ("clips");W.replaceChildren(new Option("Rest pose","-1"),...Q.clips.map((K,X)=>new Option(K,String(X)))),W.hidden=!Q.clips.length}DJ.textContent="Drag to orbit · Scroll to zoom"}catch(Q){if(U!==FJ)return;let W=GU.files["preview.png"];if(W){let K=new Image;K.alt=GU.manifest.name,K.src=`data:image/png;base64,${_z(W)}`,IJ("stage").replaceChildren(K)}DJ.textContent=`3D preview unavailable: ${String(Q)}`}for(let Q of document.querySelectorAll("button[data-download]"))Q.disabled=!1;IJ("source").hidden=!GU.files["source.kiln.js"]}window.addEventListener("message",($)=>{if($.source!==window.parent||$.data?.jsonrpc!=="2.0")return;let U=$.data;if(U.id!==void 0&&!U.method){let J=A7.get(U.id);if(A7.delete(U.id),U.error)J?.reject(Object.assign(Error(U.error.message),{code:U.error.code}));else J?.resolve(U.result)}if(U.method==="ui/notifications/tool-result")Az(U.params);if(U.method==="ui/resource-teardown")vQ?.dispose(),window.parent.postMessage({jsonrpc:"2.0",id:U.id,result:{}},"*")});IJ("reset").onclick=()=>vQ?.reset();IJ("clips").onchange=($)=>vQ?.clip(Number($.target.value));for(let $ of document.querySelectorAll("button[data-download]"))$.onclick=async()=>{if(!GU)return;let U=FJ,J=$.dataset.download,Q=J==="bundle"?"editable.zip":J==="source"?"source.kiln.js":"asset.glb",W=J==="bundle"?f5([GU]):GU.files[Q],K=J==="bundle"?"application/zip":J==="source"?"text/javascript":"model/gltf-binary",X=GU.manifest.name.replace(/[^a-zA-Z0-9_-]+/g,"-").slice(0,80);$.disabled=!0,DJ.textContent="Requesting download…";try{let H=typeof window.openai?.uploadFile==="function"&&typeof window.openai?.getFileDownloadUrl==="function"?window.openai:void 0,N=await m5(W,`${X}-${Q}`,K,r5,H,o5[Q]);if(U!==FJ)return;if(N.downloadUrl){let Y=document.createElement("a");Y.href=N.downloadUrl,Y.textContent=`Save ${X}-${Q}`,Y.style.color="#d5f4a2",Y.target="_blank",Y.rel="noopener noreferrer",Y.onclick=(G)=>{if(window.openai?.openExternal)G.preventDefault(),window.openai.openExternal({href:N.downloadUrl})},DJ.replaceChildren("Download ready. ",Y)}else DJ.textContent="Download requested."}catch(H){if(U===FJ)DJ.textContent=`Download unavailable in this host: ${H.message}`}finally{$.disabled=!GU||U!==FJ}};r5("ui/initialize",{appInfo:{name:"Kiln Asset Viewer",version:"0.6.0"},appCapabilities:{},protocolVersion:"2026-01-26"}).then(()=>{i5("ui/notifications/initialized"),i5("ui/notifications/size-changed",{height:document.documentElement.scrollHeight})}).catch(($)=>{DJ.textContent=$.message});+*/var Mt=Uint8Array,dn=Uint16Array,Yu=Int32Array,Ga=new Mt([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]),Ha=new Mt([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]),Wu=new Mt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),u0=function(e,t){var n=new dn(31);for(var i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new Yu(n[30]);for(var i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)r[s]=s-n[i]<<5|i;return{b:n,r}},h0=u0(Ga,2),{b:f0,r:$u}=h0;f0[28]=258,$u[258]=28;var d0=u0(Ha,0),{b:wT,r:r0}=d0,Zu=new dn(32768);for(Ye=0;Ye<32768;++Ye)Jn=(Ye&43690)>>1|(Ye&21845)<<1,Jn=(Jn&52428)>>2|(Jn&13107)<<2,Jn=(Jn&61680)>>4|(Jn&3855)<<4,Zu[Ye]=((Jn&65280)>>8|(Jn&255)<<8)>>1;var Jn,Ye,Kn=function(e,t,n){var i=e.length,r=0,s=new dn(t);for(;r<i;++r)if(e[r])++s[e[r]-1];var o=new dn(t);for(r=1;r<t;++r)o[r]=o[r-1]+s[r-1]<<1;var a;if(n){a=new dn(1<<t);var c=15-t;for(r=0;r<i;++r)if(e[r]){var l=r<<4|e[r],u=t-e[r],f=o[e[r]-1]++<<u;for(var h=f|(1<<u)-1;f<=h;++f)a[Zu[f]>>c]=l}}else{a=new dn(i);for(r=0;r<i;++r)if(e[r])a[r]=Zu[o[e[r]-1]++]>>15-e[r]}return a},Xi=new Mt(288);for(Ye=0;Ye<144;++Ye)Xi[Ye]=8;var Ye;for(Ye=144;Ye<256;++Ye)Xi[Ye]=9;var Ye;for(Ye=256;Ye<280;++Ye)Xi[Ye]=7;var Ye;for(Ye=280;Ye<288;++Ye)Xi[Ye]=8;var Ye,no=new Mt(32);for(Ye=0;Ye<32;++Ye)no[Ye]=5;var Ye,TT=Kn(Xi,9,0),ET=Kn(Xi,9,1),AT=Kn(no,5,0),RT=Kn(no,5,1),Gu=function(e){var t=e[0];for(var n=1;n<e.length;++n)if(e[n]>t)t=e[n];return t},On=function(e,t,n){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(t&7)&n},Hu=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},ju=function(e){return(e+7)/8|0},Ju=function(e,t,n){if(t==null||t<0)t=0;if(n==null||n>e.length)n=e.length;return new Mt(e.subarray(t,n))};var CT=["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"],Mn=function(e,t,n){var i=Error(t||CT[e]);if(i.code=e,Error.captureStackTrace)Error.captureStackTrace(i,Mn);if(!n)throw i;return i},PT=function(e,t,n,i){var r=e.length,s=i?i.length:0;if(!r||t.f&&!t.l)return n||new Mt(0);var o=!n,a=o||t.i!=2,c=t.i;if(o)n=new Mt(r*3);var l=function(Ue){var ze=n.length;if(Ue>ze){var Je=new Mt(Math.max(ze*2,Ue));Je.set(n),n=Je}},u=t.f||0,f=t.p||0,h=t.b||0,{l:d,d:g,m:b,n:p}=t,m=r*8;do{if(!d){u=On(e,f,1);var A=On(e,f+1,3);if(f+=3,!A){var T=ju(f)+4,v=e[T-4]|e[T-3]<<8,w=T+v;if(w>r){if(c)Mn(0);break}if(a)l(h+v);n.set(e.subarray(T,w),h),t.b=h+=v,t.p=f=w*8,t.f=u;continue}else if(A==1)d=ET,g=RT,b=9,p=5;else if(A==2){var E=On(e,f,31)+257,R=On(e,f+10,15)+4,_=E+On(e,f+5,31)+1;f+=14;var S=new Mt(_),F=new Mt(19);for(var C=0;C<R;++C)F[Wu[C]]=On(e,f+C*3,7);f+=R*3;var z=Gu(F),J=(1<<z)-1,O=Kn(F,z,1);for(var C=0;C<_;){var H=O[On(e,f,J)];f+=H&15;var T=H>>4;if(T<16)S[C++]=T;else{var V=0,U=0;if(T==16)U=3+On(e,f,3),f+=2,V=S[C-1];else if(T==17)U=3+On(e,f,7),f+=3;else if(T==18)U=11+On(e,f,127),f+=7;while(U--)S[C++]=V}}var K=S.subarray(0,E),Q=S.subarray(E);b=Gu(K),p=Gu(Q),d=Kn(K,b,1),g=Kn(Q,p,1)}else Mn(1);if(f>m){if(c)Mn(0);break}}if(a)l(h+131072);var se=(1<<b)-1,me=(1<<p)-1,_e=f;for(;;_e=f){var V=d[Hu(e,f)&se],Xe=V>>4;if(f+=V&15,f>m){if(c)Mn(0);break}if(!V)Mn(2);if(Xe<256)n[h++]=Xe;else if(Xe==256){_e=f,d=null;break}else{var Be=Xe-254;if(Xe>264){var C=Xe-257,Z=Ga[C];Be=On(e,f,(1<<Z)-1)+f0[C],f+=Z}var ne=g[Hu(e,f)&me],fe=ne>>4;if(!ne)Mn(3);f+=ne&15;var Q=wT[fe];if(fe>3){var Z=Ha[fe];Q+=Hu(e,f)&(1<<Z)-1,f+=Z}if(f>m){if(c)Mn(0);break}if(a)l(h+131072);var de=h+Be;if(h<Q){var Re=s-Q,$e=Math.min(Q,de);if(Re+h<0)Mn(3);for(;h<$e;++h)n[h]=i[Re+h]}for(;h<de;++h)n[h]=n[h-Q]}}if(t.l=d,t.p=_e,t.b=h,t.f=u,d)u=1,t.m=b,t.d=g,t.n=p}while(!u);return h!=n.length&&o?Ju(n,0,h):n.subarray(0,h)},gi=function(e,t,n){n<<=t&7;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8},eo=function(e,t,n){n<<=t&7;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8,e[i+2]|=n>>16},Vu=function(e,t){var n=[];for(var i=0;i<e.length;++i)if(e[i])n.push({s:i,f:e[i]});var r=n.length,s=n.slice();if(!r)return{t:m0,l:0};if(r==1){var o=new Mt(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(w,E){return w.f-E.f}),n.push({s:-1,f:25001});var a=n[0],c=n[1],l=0,u=1,f=2;n[0]={s:-1,f:a.f+c.f,l:a,r:c};while(u!=r-1)a=n[n[l].f<n[f].f?l++:f++],c=n[l!=u&&n[l].f<n[f].f?l++:f++],n[u++]={s:-1,f:a.f+c.f,l:a,r:c};var h=s[0].s;for(var i=1;i<r;++i)if(s[i].s>h)h=s[i].s;var d=new dn(h+1),g=Xu(n[u-1],d,0);if(g>t){var i=0,b=0,p=g-t,m=1<<p;s.sort(function(E,R){return d[R.s]-d[E.s]||E.f-R.f});for(;i<r;++i){var A=s[i].s;if(d[A]>t)b+=m-(1<<g-d[A]),d[A]=t;else break}b>>=p;while(b>0){var T=s[i].s;if(d[T]<t)b-=1<<t-d[T]++-1;else++i}for(;i>=0&&b;--i){var v=s[i].s;if(d[v]==t)--d[v],++b}g=t}return{t:new Mt(d),l:g}},Xu=function(e,t,n){return e.s==-1?Math.max(Xu(e.l,t,n+1),Xu(e.r,t,n+1)):t[e.s]=n},s0=function(e){var t=e.length;while(t&&!e[--t]);var n=new dn(++t),i=0,r=e[0],s=1,o=function(c){n[i++]=c};for(var a=1;a<=t;++a)if(e[a]==r&&a!=t)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);if(s>2)o(s>10?s-11<<5|28690:s-3<<5|12305),s=0}else if(s>3){o(r),--s;for(;s>6;s-=6)o(8304);if(s>2)o(s-3<<5|8208),s=0}while(s--)o(r);s=1,r=e[a]}return{c:n.subarray(0,i),n:t}},to=function(e,t){var n=0;for(var i=0;i<t.length;++i)n+=e[i]*t[i];return n},p0=function(e,t,n){var i=n.length,r=ju(t+2);e[r]=i&255,e[r+1]=i>>8,e[r+2]=e[r]^255,e[r+3]=e[r+1]^255;for(var s=0;s<i;++s)e[r+s+4]=n[s];return(r+4+i)*8},o0=function(e,t,n,i,r,s,o,a,c,l,u){gi(t,u++,n),++r[256];var f=Vu(r,15),{t:h,l:d}=f,g=Vu(s,15),{t:b,l:p}=g,m=s0(h),{c:A,n:T}=m,v=s0(b),{c:w,n:E}=v,R=new dn(19);for(var _=0;_<A.length;++_)++R[A[_]&31];for(var _=0;_<w.length;++_)++R[w[_]&31];var S=Vu(R,7),{t:F,l:C}=S,z=19;for(;z>4&&!F[Wu[z-1]];--z);var J=l+5<<3,O=to(r,Xi)+to(s,no)+o,H=to(r,h)+to(s,b)+o+14+3*z+to(R,F)+2*R[16]+3*R[17]+7*R[18];if(c>=0&&J<=O&&J<=H)return p0(t,u,e.subarray(c,c+l));var V,U,K,Q;if(gi(t,u,1+(H<O)),u+=2,H<O){V=Kn(h,d,0),U=h,K=Kn(b,p,0),Q=b;var se=Kn(F,C,0);gi(t,u,T-257),gi(t,u+5,E-1),gi(t,u+10,z-4),u+=14;for(var _=0;_<z;++_)gi(t,u+3*_,F[Wu[_]]);u+=3*z;var me=[A,w];for(var _e=0;_e<2;++_e){var Xe=me[_e];for(var _=0;_<Xe.length;++_){var Be=Xe[_]&31;if(gi(t,u,se[Be]),u+=F[Be],Be>15)gi(t,u,Xe[_]>>5&127),u+=Xe[_]>>12}}}else V=TT,U=Xi,K=AT,Q=no;for(var _=0;_<a;++_){var Z=i[_];if(Z>255){var Be=Z>>18&31;if(eo(t,u,V[Be+257]),u+=U[Be+257],Be>7)gi(t,u,Z>>23&31),u+=Ga[Be];var ne=Z&31;if(eo(t,u,K[ne]),u+=Q[ne],ne>3)eo(t,u,Z>>5&8191),u+=Ha[ne]}else eo(t,u,V[Z]),u+=U[Z]}return eo(t,u,V[256]),u+U[256]},IT=new Yu([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),m0=new Mt(0),LT=function(e,t,n,i,r,s){var o=s.z||e.length,a=new Mt(i+o+5*(1+Math.ceil(o/7000))+r),c=a.subarray(i,a.length-r),l=s.l,u=(s.r||0)&7;if(t){if(u)c[0]=s.r>>3;var f=IT[t-1],h=f>>13,d=f&8191,g=(1<<n)-1,b=s.p||new dn(32768),p=s.h||new dn(g+1),m=Math.ceil(n/3),A=2*m,T=function(qe){return(e[qe]^e[qe+1]<<m^e[qe+2]<<A)&g},v=new Yu(25000),w=new dn(288),E=new dn(32),R=0,_=0,S=s.i||0,F=0,C=s.w||0,z=0;for(;S+2<o;++S){var J=T(S),O=S&32767,H=p[J];if(b[O]=H,p[J]=O,C<=S){var V=o-S;if((R>7000||F>24576)&&(V>423||!l)){u=o0(e,c,0,v,w,E,_,F,z,S-z,u),F=R=_=0,z=S;for(var U=0;U<286;++U)w[U]=0;for(var U=0;U<30;++U)E[U]=0}var K=2,Q=0,se=d,me=O-H&32767;if(V>2&&J==T(S-me)){var _e=Math.min(h,V)-1,Xe=Math.min(32767,S),Be=Math.min(258,V);while(me<=Xe&&--se&&O!=H){if(e[S+K]==e[S+K-me]){var Z=0;for(;Z<Be&&e[S+Z]==e[S+Z-me];++Z);if(Z>K){if(K=Z,Q=me,Z>_e)break;var ne=Math.min(me,Z-2),fe=0;for(var U=0;U<ne;++U){var de=S-me+U&32767,Re=b[de],$e=de-Re&32767;if($e>fe)fe=$e,H=de}}}O=H,H=b[O],me+=O-H&32767}}if(Q){v[F++]=268435456|$u[K]<<18|r0[Q];var Ue=$u[K]&31,ze=r0[Q]&31;_+=Ga[Ue]+Ha[ze],++w[257+Ue],++E[ze],C=S+K,++R}else v[F++]=e[S],++w[e[S]]}}for(S=Math.max(S,C);S<o;++S)v[F++]=e[S],++w[e[S]];if(u=o0(e,c,l,v,w,E,_,F,z,S-z,u),!l)s.r=u&7|c[u/8|0]<<3,u-=7,s.h=p,s.p=b,s.i=S,s.w=C}else{for(var S=s.w||0;S<o+l;S+=65535){var Je=S+65535;if(Je>=o)c[u/8|0]=l,Je=o;u=p0(c,u+1,e.subarray(S,Je))}s.i=o}return Ju(a,0,i+ju(u)+r)},NT=function(){var e=new Int32Array(256);for(var t=0;t<256;++t){var n=t,i=9;while(--i)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e}(),DT=function(){var e=-1;return{p:function(t){var n=e;for(var i=0;i<t.length;++i)n=NT[n&255^t[i]]^n>>>8;e=n},d:function(){return~e}}};var UT=function(e,t,n,i,r){if(!r){if(r={l:1},t.dictionary){var s=t.dictionary.subarray(-32768),o=new Mt(s.length+e.length);o.set(s),o.set(e,s.length),e=o,r.w=s.length}}return LT(e,t.level==null?6:t.level,t.mem==null?r.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,i,r)},g0=function(e,t){var n={};for(var i in e)n[i]=e[i];for(var i in t)n[i]=t[i];return n};var Vt=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function _0(e,t){return UT(e,t||{},0,0)}function x0(e,t){return PT(e,{i:2},t&&t.out,t&&t.dictionary)}var v0=function(e,t,n,i){for(var r in e){var s=e[r],o=t+r,a=i;if(Array.isArray(s))a=g0(i,s[1]),s=s[0];if(s instanceof Mt)n[o]=[s,a];else n[o+="/"]=[new Mt(0),a],v0(s,o,n,i)}},a0=typeof TextEncoder<"u"&&new TextEncoder,OT=typeof TextDecoder<"u"&&new TextDecoder,FT=0;try{OT.decode(m0,{stream:!0}),FT=1}catch(e){}function c0(e,t){if(t){var n=new Mt(e.length);for(var i=0;i<e.length;++i)n[i]=e.charCodeAt(i);return n}if(a0)return a0.encode(e);var r=e.length,s=new Mt(e.length+(e.length>>1)),o=0,a=function(u){s[o++]=u};for(var i=0;i<r;++i){if(o+5>s.length){var c=new Mt(o+8+(r-i<<1));c.set(s),s=c}var l=e.charCodeAt(i);if(l<128||t)a(l);else if(l<2048)a(192|l>>6),a(128|l&63);else if(l>55295&&l<57344)l=65536+(l&1047552)|e.charCodeAt(++i)&1023,a(240|l>>18),a(128|l>>12&63),a(128|l>>6&63),a(128|l&63);else a(224|l>>12),a(128|l>>6&63),a(128|l&63)}return Ju(s,0,o)}var qu=function(e){var t=0;if(e)for(var n in e){var i=e[n].length;if(i>65535)Mn(9);t+=i+4}return t},l0=function(e,t,n,i,r,s,o,a){var c=i.length,l=n.extra,u=a&&a.length,f=qu(l);if(Vt(e,t,o!=null?33639248:67324752),t+=4,o!=null)e[t++]=20,e[t++]=n.os;e[t]=20,t+=2,e[t++]=n.flag<<1|(s<0&&8),e[t++]=r&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var h=new Date(n.mtime==null?Date.now():n.mtime),d=h.getFullYear()-1980;if(d<0||d>119)Mn(10);if(Vt(e,t,d<<25|h.getMonth()+1<<21|h.getDate()<<16|h.getHours()<<11|h.getMinutes()<<5|h.getSeconds()>>1),t+=4,s!=-1)Vt(e,t,n.crc),Vt(e,t+4,s<0?-s-2:s),Vt(e,t+8,n.size);if(Vt(e,t+12,c),Vt(e,t+14,f),t+=16,o!=null)Vt(e,t,u),Vt(e,t+6,n.attrs),Vt(e,t+10,o),t+=14;if(e.set(i,t),t+=c,f)for(var g in l){var b=l[g],p=b.length;Vt(e,t,+g),Vt(e,t+2,p),e.set(b,t+4),t+=4+p}if(u)e.set(a,t),t+=u;return t},zT=function(e,t,n,i,r){Vt(e,t,101010256),Vt(e,t+8,n),Vt(e,t+10,n),Vt(e,t+12,i),Vt(e,t+16,r)};function y0(e,t){if(!t)t={};var n={},i=[];v0(e,"",n,t);var r=0,s=0;for(var o in n){var a=n[o],c=a[0],l=a[1],u=l.level==0?0:8,f=c0(o),h=f.length,d=l.comment,g=d&&c0(d),b=g&&g.length,p=qu(l.extra);if(h>65535)Mn(11);var m=u?_0(c,l):c,A=m.length,T=DT();T.p(c),i.push(g0(l,{size:c.length,crc:T.d(),c:m,f,m:g,u:h!=o.length||g&&d.length!=b,o:r,compression:u})),r+=30+h+p+A,s+=76+2*(h+p)+(b||0)+A}var v=new Mt(s+22),w=r,E=s-r;for(var R=0;R<i.length;++R){var f=i[R];l0(v,f.o,f,f.f,f.u,f.c.length);var _=30+f.f.length+qu(f.extra);v.set(f.c,f.o+_),l0(v,r,f,f.f,f.u,f.c.length,f.o,f.m),r+=16+_+(f.m?f.m.length:0)}return zT(v,r,i.length,E,w),v}var Va=67108864,Ku=Yt().regex(/^[a-z][a-z0-9_-]{0,79}$/),kT=Yt().regex(/^sha256:[a-f0-9]{64}$/),Qu=Qs({version:rT("kiln.asset.v1"),assetId:Ku,revisionId:Ku,parentRevision:Ku.optional(),name:Yt().min(1).max(200),tags:Ba(Yt().max(80)).max(30),createdAt:Yt().datetime(),description:Yt().max(4000).optional(),brief:Yt().max(8000).optional(),attribution:Qs({model:Yt().max(200).optional(),harness:Yt().max(200).optional(),author:Yt().max(200).optional()}).optional(),editable:Xw(),files:e0(Yt(),Qs({sha256:kT,bytes:Ww().int().nonnegative().max(Va)})),build:Qs({engine:Yt(),options:e0(Yt(),xr()),warnings:Ba(Yt()),integration:xr().optional(),qa:xr().optional(),dependencies:Ba(xr()).optional(),rebuild:t0(["engine-required","external-dependencies-required"])}).optional(),preview:Qs({fidelity:xr().optional(),error:Yt().optional()}).optional()}),BT=new Set(["asset.glb","source.kiln.js","preview.png"]);function GT(e){let t=Qu.parse(e.manifest),n=Object.keys(e.files);if(n.length!==Object.keys(t.files).length||!n.includes("asset.glb"))throw Error("Asset file inventory mismatch");let i=0;for(let r of n){if(!BT.has(r)||!t.files[r]||t.files[r].bytes!==e.files[r].length)throw Error("Invalid asset file inventory");i+=e.files[r].length}if(i>Va||t.editable!==n.includes("source.kiln.js"))throw Error("Invalid asset size or source inventory");if((e.files["source.kiln.js"]?.length??0)>1048576)throw Error("Source exceeds 1 MiB");eh(e.files["asset.glb"])}function eh(e){if(e.length<20||e.length>Va)throw Error("Invalid GLB size");let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t.getUint32(0,!0)!==1179937895||t.getUint32(4,!0)!==2||t.getUint32(8,!0)!==e.length||t.getUint32(16,!0)!==1313821514)throw Error("Invalid GLB header");let n=20+t.getUint32(12,!0);if(n>e.length)throw Error("Invalid GLB JSON length");let i=JSON.parse(new TextDecoder().decode(e.subarray(20,n)));for(let r of[...i.buffers??[],...i.images??[]])if(r.uri&&!String(r.uri).startsWith("data:"))throw Error("GLB must embed its resources")}function b0(e){if(!e.length||e.length>100)throw Error("Bundle requires 1..100 revisions");let t={},n=0;for(let i of e){GT(i);let r=`${i.manifest.assetId}/${i.manifest.revisionId}/`;if(t[`${r}manifest.json`])throw Error("Duplicate bundle revision");t[`${r}manifest.json`]=new TextEncoder().encode(JSON.stringify(i.manifest,null,2));for(let[s,o]of Object.entries(i.files))t[r+s]=o}for(let i of Object.values(t))n+=i.length;if(n>Va)throw Error("Bundle exceeds 64 MiB");return y0(t,{level:0})}function S0(e,t,n=40,i=[e]){let r=e.getCenter(new N),s=Math.max(e.getSize(new N).length()/2,0.01),o=new N(1,0.65,1.25).normalize(),a=new N().crossVectors(new N(0,1,0),o).normalize(),c=new N().crossVectors(o,a),l=[];for(let A of i.length?i:[e])for(let T of[A.min.x,A.max.x])for(let v of[A.min.y,A.max.y])for(let w of[A.min.z,A.max.z])l.push(new N(T,v,w));let u=1/0,f=-1/0,h=1/0,d=-1/0;for(let A of l){let T=A.clone().sub(r),v=T.dot(a),w=T.dot(c);u=Math.min(u,v),f=Math.max(f,v),h=Math.min(h,w),d=Math.max(d,w)}r.addScaledVector(a,(u+f)/2),r.addScaledVector(c,(h+d)/2);let g=Math.tan(n*Math.PI/360),b=g*t,p=s;for(let A of l){let T=A.clone().sub(r),v=T.dot(o);p=Math.max(p,v+Math.abs(T.dot(a))*1.12/b,v+Math.abs(T.dot(c))*1.12/g)}let m=r.clone().addScaledVector(o,p);return{center:r,radius:s,distance:p,position:m}}function M0(e){let t=new jl({antialias:!0,alpha:!1});t.setPixelRatio(Math.min(devicePixelRatio,2)),t.setClearColor(1382930),t.toneMapping=vs,t.toneMappingExposure=1.15,e.replaceChildren(t.domElement);let n=new Xr,i=new Pt(40,1,0.01,1000),r=new cu(i,t.domElement);r.enableDamping=!0;let s=new Gs(t),o=new lu,a=s.fromScene(o,0.04);n.environment=a.texture,o.dispose(),s.dispose();let c=new Qr(16773591,2.4);c.position.set(4,8,5),n.add(c),n.add(new ca(14806490,5065021,1.7));let l,u,f=[],h=!0,d=performance.now(),g=0,b=0,p=!1,m=(w)=>{let E=new Set,R=new Set,_=new Set;w.traverse((S)=>{let F=S;if(!F.isMesh)return;E.add(F.geometry);for(let C of Array.isArray(F.material)?F.material:[F.material]){R.add(C);for(let z of Object.values(C))if(z instanceof St)_.add(z)}});for(let S of[...E,...R,..._])S.dispose()},A=()=>{if(!l)return;let w=new Jt().setFromObject(l,!0),E=[];l.traverse((C)=>{if(C instanceof dt||C instanceof Li||C instanceof jr){let z=new Jt().setFromObject(C,!0);if(!z.isEmpty())E.push(z)}});let{center:R,radius:_,distance:S,position:F}=S0(w,i.aspect,i.fov,E);r.target.copy(R),i.position.copy(F),i.near=Math.max(_/1000,0.0001),i.far=S+_*100,r.minDistance=_*0.1,r.maxDistance=_*80,i.updateProjectionMatrix(),r.update()},T=new ResizeObserver(()=>{let{clientWidth:w,clientHeight:E}=e;if(!w||!E)return;t.setSize(w,E),i.aspect=w/E,i.updateProjectionMatrix()});T.observe(e);let v=(w)=>{if(p)return;let E=Math.min((w-d)/1000,0.1);if(d=w,h)u?.update(E);r.update(),t.render(n,i),g=requestAnimationFrame(v)};return g=requestAnimationFrame(v),{async load(w){let E=++b;eh(w);let R=new Ds;R.setURLModifier((O)=>{if(!O.startsWith("blob:")&&!O.startsWith("data:"))throw Error("External model resources are not loaded");return O});let _=await new ru(R).parseAsync(Uint8Array.from(w).buffer,"");if(p||E!==b){m(_.scene);return}if(l)u?.stopAllAction(),u?.uncacheRoot(l),n.remove(l),m(l);l=_.scene,n.add(l),f=_.animations,u=new da(l),h=!0;let{clientWidth:S,clientHeight:F}=e;t.setSize(S,F),i.aspect=S/F,A();let C=0,z=0,J=new Set;return l.traverse((O)=>{let H=O;if(!H.isMesh)return;z++,C+=(H.geometry.index?.count??H.geometry.attributes.position?.count??0)/3*(H.isInstancedMesh?H.count:1);for(let V of Array.isArray(H.material)?H.material:[H.material])J.add(V)}),{triangles:C,meshes:z,materials:J.size,clips:f.map((O)=>O.name)}},reset:A,wire(w){l?.traverse((E)=>{let R=E;if(R.isMesh){for(let _ of Array.isArray(R.material)?R.material:[R.material])if("wireframe"in _)_.wireframe=w}})},lighting(w){t.toneMappingExposure=w==="bright"?1.65:w==="soft"?0.85:1.15,c.intensity=w==="soft"?0.8:2.4},clip(w){if(u?.stopAllAction(),f[w])u?.clipAction(f[w]).play()},pause(w){h=!w},dispose(){if(p=!0,b++,cancelAnimationFrame(g),T.disconnect(),r.dispose(),l)m(l);a.dispose(),t.dispose(),e.replaceChildren()}}}async function w0(e,t,n,i,r,s){let o="";for(let a=0;a<e.length;a+=8192)o+=String.fromCharCode(...e.subarray(a,a+8192));try{if((await i("ui/download-file",{contents:[{type:"resource",resource:{uri:`file:///${t}`,mimeType:n,blob:btoa(o)}}]}))?.isError)throw Error("The chat host could not download this file.");return{}}catch(a){if(a.code!==-32601)throw a;if(s){let f=new URL(s);if(f.protocol!=="https:"&&!(f.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(f.hostname)))throw Error("Invalid host download URL");return{downloadUrl:f.href}}if(!r)throw a;let c=new File([Uint8Array.from(e)],t,{type:n}),{fileId:l}=await r.uploadFile(c),{downloadUrl:u}=await r.getFileDownloadUrl({fileId:l});if(new URL(u).protocol!=="https:")throw Error("Invalid host download URL");return{downloadUrl:u}}}var E0=16777216,A0=Math.ceil(E0/3)*4,Bt=(e)=>{throw Error(`Asset transfer ${e}. Present the saved asset again or open it in Kiln; the saved files are unchanged.`)};function HT(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return btoa(t)}function T0(e){if(typeof e!=="string"||e.length>A0)return Bt("exceeds the encoded size limit");if(e.length%4||!/^[A-Za-z0-9+/]*={0,2}$/.test(e))Bt("contains damaged base64 data");let t;try{t=atob(e)}catch{return Bt("contains damaged base64 data")}let n=Uint8Array.from(t,(i)=>i.charCodeAt(0));if(HT(n)!==e)Bt("contains noncanonical base64 data");return n}function io(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}async function R0(e){if(!io(e))return Bt("metadata is missing");if(typeof e.error==="string")throw Error(e.error);let t=Qu.safeParse(e.manifest);if(!t.success||!io(e.files))return Bt("metadata is malformed");let n=t.data,i=Object.entries(e.files);if(!i.length||i.length>16||!Object.hasOwn(e.files,"asset.glb"))return Bt("file list is missing or invalid");let r=0,s=0;for(let[c,l]of i){if(!/^[a-z0-9][a-z0-9._-]{0,127}$/.test(c)||!Object.hasOwn(n.files,c))return Bt("file metadata is missing");if(r+=n.files[c].bytes,r>E0)return Bt("exceeds the decoded size limit");let u=typeof l==="string"?l:io(l)?l.data:void 0;if(typeof u!=="string")return Bt("file encoding is malformed");if(s+=u.length,s>A0)return Bt("exceeds the encoded size limit")}let o={};for(let[c,l]of i){let u=n.files[c],f;if(typeof l==="string")f=T0(l);else{if(!io(l)||l.encoding!=="kiln.deflate-base64.v1")return Bt("encoding is unsupported");let g=T0(l.data);try{f=x0(g,{out:new Uint8Array(u.bytes+1)})}catch{return Bt("compressed data is damaged")}}if(f.length!==u.bytes)return Bt("byte count does not match the saved file");let h=await crypto.subtle.digest("SHA-256",Uint8Array.from(f));if(`sha256:${Array.from(new Uint8Array(h),(g)=>g.toString(16).padStart(2,"0")).join("")}`!==u.sha256)return Bt("integrity check failed");o[c]=f}for(let c of Object.keys(n.files))if(!Object.hasOwn(o,c))return Bt("is missing a saved file");let a={};if(e.downloadUrls!==void 0){if(!io(e.downloadUrls))return Bt("download metadata is malformed");for(let[c,l]of Object.entries(e.downloadUrls)){if(typeof l!=="string")return Bt("download metadata is malformed");a[c]=l}}return{record:{manifest:n,files:o},downloadUrls:a}}var Qn=(e)=>document.getElementById(e),ei=Qn("status"),en,P0={},ro,VT=0,ti=0,Wa=new Map;function I0(e,t){let n=++VT;return new Promise((i,r)=>{let s=setTimeout(()=>{Wa.delete(n),r(Error("Chat host did not respond."))},20000);Wa.set(n,{resolve(o){clearTimeout(s),i(o)},reject(o){clearTimeout(s),r(o)}}),window.parent.postMessage({jsonrpc:"2.0",id:n,method:e,params:t},"*")})}function C0(e,t={}){window.parent.postMessage({jsonrpc:"2.0",method:e,params:t},"*")}function WT(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return btoa(t)}async function $T(e){let t=++ti;en=void 0;for(let n of document.querySelectorAll("button[data-download]"))n.disabled=!0;try{if(!e||typeof e!=="object"||Array.isArray(e))throw Error("Asset transfer metadata is missing. Present the saved asset again.");await ZT(e,t)}catch(n){if(t!==ti)return;ei.textContent=n instanceof Error?n.message:"Asset transfer failed. Present the saved asset again."}}async function ZT(e,t){if(e.isError){ei.textContent=e.content?.find((i)=>i.type==="text")?.text??"This asset could not be opened.";return}let n;try{n=await R0(e._meta?.kilnAsset)}catch(i){if(t!==ti)return;ei.textContent=i instanceof Error?i.message:"Asset transfer failed. Present the saved asset again.";return}if(t!==ti)return;en=n.record,Qn("name").textContent=en.manifest.name,P0=n.downloadUrls,Qn("revision").textContent=`${en.manifest.editable?"Editable source included":"GLB asset"} · ${en.manifest.revisionId.slice(0,10)}`;try{ro??=M0(Qn("stage"));let i=await ro.load(en.files["asset.glb"]);if(t!==ti)return;if(i){Qn("stats").textContent=`${i.triangles.toLocaleString()} triangles · ${i.materials} materials · ${(en.files["asset.glb"].length/1024).toFixed(0)} KB`;let r=Qn("clips");r.replaceChildren(new Option("Rest pose","-1"),...i.clips.map((s,o)=>new Option(s,String(o)))),r.hidden=!i.clips.length}ei.textContent="Drag to orbit · Scroll to zoom"}catch(i){if(t!==ti)return;let r=en.files["preview.png"];if(r){let s=new Image;s.alt=en.manifest.name,s.src=`data:image/png;base64,${WT(r)}`,Qn("stage").replaceChildren(s)}ei.textContent=`3D preview unavailable: ${String(i)}`}for(let i of document.querySelectorAll("button[data-download]"))i.disabled=!1;Qn("source").hidden=!en.files["source.kiln.js"]}window.addEventListener("message",(e)=>{if(e.source!==window.parent||e.data?.jsonrpc!=="2.0")return;let t=e.data;if(t.id!==void 0&&!t.method){let n=Wa.get(t.id);if(Wa.delete(t.id),t.error)n?.reject(Object.assign(Error(t.error.message),{code:t.error.code}));else n?.resolve(t.result)}if(t.method==="ui/notifications/tool-result")$T(t.params);if(t.method==="ui/resource-teardown")ro?.dispose(),window.parent.postMessage({jsonrpc:"2.0",id:t.id,result:{}},"*")});Qn("reset").onclick=()=>ro?.reset();Qn("clips").onchange=(e)=>ro?.clip(Number(e.target.value));for(let e of document.querySelectorAll("button[data-download]"))e.onclick=async()=>{if(!en)return;let t=ti,n=e.dataset.download,i=n==="bundle"?"editable.zip":n==="source"?"source.kiln.js":"asset.glb",r=n==="bundle"?b0([en]):en.files[i],s=n==="bundle"?"application/zip":n==="source"?"text/javascript":"model/gltf-binary",o=en.manifest.name.replace(/[^a-zA-Z0-9_-]+/g,"-").slice(0,80);e.disabled=!0,ei.textContent="Requesting download…";try{let a=typeof window.openai?.uploadFile==="function"&&typeof window.openai?.getFileDownloadUrl==="function"?window.openai:void 0,c=await w0(r,`${o}-${i}`,s,I0,a,P0[i]);if(t!==ti)return;if(c.downloadUrl){let l=document.createElement("a");l.href=c.downloadUrl,l.textContent=`Save ${o}-${i}`,l.style.color="#d5f4a2",l.target="_blank",l.rel="noopener noreferrer",l.onclick=(u)=>{if(window.openai?.openExternal)u.preventDefault(),window.openai.openExternal({href:c.downloadUrl})},ei.replaceChildren("Download ready. ",l)}else ei.textContent="Download requested."}catch(a){if(t===ti)ei.textContent=`Download unavailable in this host: ${a.message}`}finally{e.disabled=!en||t!==ti}};I0("ui/initialize",{appInfo:{name:"Kiln Asset Viewer",version:"0.6.0"},appCapabilities:{},protocolVersion:"2026-01-26"}).then(()=>{C0("ui/notifications/initialized"),C0("ui/notifications/size-changed",{height:document.documentElement.scrollHeight})}).catch((e)=>{ei.textContent=e.message});</script></body>diff --git a/docs/plans/repo-size-and-r2-migration-2026-09-10.md b/docs/plans/repo-size-and-r2-migration-2026-09-10.mdindex 4229e234..b976e52b 100644--- a/docs/plans/repo-size-and-r2-migration-2026-09-10.md+++ b/docs/plans/repo-size-and-r2-migration-2026-09-10.md@@ -1056,6 +1056,49 @@ in 6 concurrent runs to 6 of 6 passing.| 8.3 | Point `src/asset-cli.test.ts` at an interpreter that reflects how the CLI actually ships, or assert non-empty stdout before parsing so the failure names the real cause | Done -- asserts non-empty stdout before `JSON.parse`. Left on Bun deliberately: Bun is the documented toolchain, so the test should keep exercising the runtime that exposed this || 8.4 | Re-check the other two intermittent tests against this finding | Done, and the hypothesis does not hold. `shipping proxy forwards actual PNGs ...` in `scripts/evaluation/observe-shipping.test.mjs` passed 8 of 8 under the same concurrency that reproduced the `save` failure on demand, and its entry is event-driven with a live child-process handle rather than an awaited `main()`, so it cannot reach this state. That test's intermittency is still unexplained; it is not this defect |+## Phase 10 -- Toolchain currency, and what the bump uncovered++Taken 2026-09-11. Bun 1.3.14 -> 1.4.2, Node 22.23.1 -> 22.23.2, npm 12.0.1 ->+12.0.2. Deliberately its own pass with nothing else in it, because every gate in+this repository runs on Bun and a regression needed exactly one suspect. That+discipline paid for itself immediately: the bump surfaced a shipped defect that+had been present since the bundle was introduced.++Bun 1.4 also fixes Phase 8 at its source. Running the *pre-fix* CLI from+`origin/main` against both runtimes: 2 of 8 concurrent runs produced output on+1.3.14, 8 of 8 on 1.4.2, and 16 of 16 on a longer trial. `withProcessAlive`+stays anyway -- it holds for anyone still on 1.3.x, and no runtime contract+promises the behaviour. The offline suite runs about 18% faster (133 s against+163 s).++### 10.1 -- `dist/mcp-server.mjs` started a server when merely imported++`src/mcp-server.ts` guarded its entry block with `import.meta.main`. That is a+Bun property, and no Bun release lowers it correctly for a `--target=node`+bundle. Both lowerings observed emit `__require.main == __require.module`; under+Node ESM both sides are `undefined`, so the guard was **always true**. Verified+directly against the committed 1.3.14 bundle: importing it printed+`kiln MCP server on stdio (auto)` and left a live stdio server attached to a+process that only wanted to read the module.++Bun 1.4 then stopped emitting the `__require` helper the line still references,+so the same expression became a `ReferenceError` at startup -- loud where it had+been silent, which is the only reason this was caught at all. The bundle is what+every harness launches, so a bundle built on 1.4 without this fix would not have+started at all.++Both entries now share `isDirectEntry` in `src/direct-entry.ts`, deciding from+`process.argv[1]` rather than from whatever the bundler makes of+`import.meta.main`. `src/cli.ts` already did this correctly through a private+`isDirectCliEntry`; the two are now one function, and `mcp-bundle.test.ts` has+the inertness guard `cli-entry.test.ts` always had.++| ID | Task | State |+| --- | --- | --- |+| 10.1 | `import.meta.main` does not survive bundling to Node; the MCP entry block ran on import and became a `ReferenceError` under Bun 1.4 | Done 2026-09-11 -- shared `isDirectEntry`, guarded by a new inertness test |+| 10.2 | Re-record the coverage baseline measured under Bun 1.4.2 | Done 2026-09-11 |+| 10.3 | Consider whether other Bun-only globals reach a `--target=node` bundle. `import.meta.main` was the one that mattered; nothing else is asserted | Pending; audit, no known defect |+## Phase 9 -- Review surfaces that misreport a correct assetFound 2026-09-10 into 2026-09-11 by a blind clone-and-author run: an agent givendiff --git a/package.json b/package.jsonindex fd910693..ea2fc8ca 100644--- a/package.json+++ b/package.json@@ -6,11 +6,11 @@"license": "MIT","author": "Matthew Kissinger","type": "module",- "packageManager": "[email protected]",+ "packageManager": "[email protected]","engines": {- "bun": "1.3.14",- "node": "22.23.1",- "npm": "12.0.1"+ "bun": "1.4.2",+ "node": "22.23.2",+ "npm": "12.0.2"},"bin": {"kiln": "./dist/cli.mjs",@@ -143,7 +143,7 @@"@biomejs/biome": "^2.5.3","@google/genai": "^2.17.1","@strands-agents/sdk": "1.13.0",- "@types/bun": "^1.3.14",+ "@types/bun": "^1.4.2","ai": "^6.0.222","openai": "^6.46.0","typescript": "^7.0.2"diff --git a/scripts/check-toolchain.mjs b/scripts/check-toolchain.mjsindex fa811b35..143ca1e8 100644--- a/scripts/check-toolchain.mjs+++ b/scripts/check-toolchain.mjs@@ -5,8 +5,8 @@ const filesOnly = process.argv.includes('--files-only');const packageJson = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));const workflow = await readFile(new URL('../.github/workflows/ci.yml', import.meta.url), 'utf8');-const expectedPackageManager = '[email protected]';-const expectedEngines = { bun: '1.3.14', node: '22.23.1', npm: '12.0.1' };+const expectedPackageManager = '[email protected]';+const expectedEngines = { bun: '1.4.2', node: '22.23.2', npm: '12.0.2' };const errors = [];if (packageJson.packageManager !== expectedPackageManager) {@@ -21,14 +21,14 @@ if (packageJson.engines?.node !== expectedEngines.node) {if (packageJson.engines?.npm !== expectedEngines.npm) {errors.push(`engines.npm must be ${expectedEngines.npm}`);}-if (!/^\s*bun-version:\s*1\.3\.14\s*$/mu.test(workflow)) {- errors.push('CI bun-version must be 1.3.14');+if (!/^\s*bun-version:\s*1\.4\.2\s*$/mu.test(workflow)) {+ errors.push('CI bun-version must be 1.4.2');}-if (!/^\s*node-version:\s*22\.23\.1\s*$/mu.test(workflow)) {- errors.push('CI node-version must be 22.23.1');+if (!/^\s*node-version:\s*22\.23\.2\s*$/mu.test(workflow)) {+ errors.push('CI node-version must be 22.23.2');}-if (!workflow.includes('npm install --global [email protected]')) {- errors.push('CI npm version must be 12.0.1');+if (!workflow.includes('npm install --global [email protected]')) {+ errors.push('CI npm version must be 12.0.2');}if (!workflow.includes('run: bun run check:toolchain')) {errors.push('CI must run the toolchain metadata check');@@ -42,8 +42,8 @@ if (!filesOnly && process.versions.bun !== expectedEngines.bun) {if (!filesOnly) {const revision = spawnSync('bun', ['--revision'], { encoding: 'utf8', shell: false });const value = String(revision.stdout || revision.stderr || '').trim();- if (revision.status !== 0 || !/^1\.3\.14\+[0-9a-f]+$/i.test(value)) {- errors.push(`runtime Bun must be stable 1.3.14 (found ${value || 'missing'})`);+ if (revision.status !== 0 || !/^1\.4\.2\+[0-9a-f]+$/i.test(value)) {+ errors.push(`runtime Bun must be stable 1.4.2 (found ${value || 'missing'})`);}}diff --git a/scripts/reliability.test.mjs b/scripts/reliability.test.mjsindex 9588362b..3d34d632 100644--- a/scripts/reliability.test.mjs+++ b/scripts/reliability.test.mjs@@ -18,8 +18,8 @@ describe('repository reliability contracts', () => {test('package metadata declares the CI-supported runtimes', async () => {const pkg = await readJson('package.json');- expect(pkg.packageManager).toBe('[email protected]');- expect(pkg.engines).toEqual({ bun: '1.3.14', node: '22.23.1', npm: '12.0.1' });+ expect(pkg.packageManager).toBe('[email protected]');+ expect(pkg.engines).toEqual({ bun: '1.4.2', node: '22.23.2', npm: '12.0.2' });});test('the toolchain checker verifies package and workflow metadata', async () => {@@ -31,7 +31,7 @@ describe('repository reliability contracts', () => {expect(pkg.scripts['check:toolchain']).toBe('bun scripts/check-toolchain.mjs');expect(result.status, result.stderr || result.stdout).toBe(0);- expect(result.stdout.trim()).toBe('Toolchain metadata: Bun 1.3.14, Node 22.23.1, npm 12.0.1');+ expect(result.stdout.trim()).toBe('Toolchain metadata: Bun 1.4.2, Node 22.23.2, npm 12.0.2');});test('coverage is measured, ratcheted, and retained by CI', async () => {diff --git a/src/__tests__/mcp-bundle.test.ts b/src/__tests__/mcp-bundle.test.tsindex 5eac9efc..1fdcc1b8 100644--- a/src/__tests__/mcp-bundle.test.ts+++ b/src/__tests__/mcp-bundle.test.ts@@ -23,9 +23,10 @@ import { spawnSync } from 'node:child_process';import { Client } from '@modelcontextprotocol/client';import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';import { createHash } from 'node:crypto';-import { readFile } from 'node:fs/promises';+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';-import { join, resolve } from 'node:path';+import { dirname, join, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';import { describe, expect, it } from 'bun:test';@@ -104,6 +105,41 @@ describe('mcp server bundle', () => {expect(names).toEqual(expected);}, 70_000);++ /**+ * Importing the bundle must not start a server.+ *+ * `import.meta.main` is a Bun property, and no Bun release has lowered it to+ * something Node evaluates correctly. Both lowerings seen so far emit+ * `__require.main == __require.module`: under Node ESM both sides are+ * `undefined`, so the guard is always true and the entry block runs on a plain+ * `import` -- a stdio server attaches itself to a process that only wanted to+ * read the module. Bun 1.4 then stopped emitting the `__require` helper it+ * still references, turning the same line into a hard `ReferenceError` at+ * startup. The fix is not to chase the lowering: decide directly, from+ * `process.argv[1]`, the way `src/cli.ts` already does.+ */+ it('stays inert when imported rather than launched', async () => {+ const probe = join(REPO, 'tmp', `mcp-import-probe-${process.pid}.mjs`);+ await mkdir(dirname(probe), { recursive: true });+ await writeFile(+ probe,+ `await import(${JSON.stringify(pathToFileURL(BUNDLE).href)});\n` ++ `process.stdout.write('IMPORTED_ONLY');\n`,+ );+ try {+ const run = spawnSync('node', [probe], {+ cwd: REPO,+ encoding: 'utf8',+ timeout: 30_000,+ env: { ...process.env, KILN_RENDER: 'cpu' },+ });+ expect(run.stderr).toBe('');+ expect(run.stdout).toBe('IMPORTED_ONLY');+ } finally {+ await rm(probe, { force: true });+ }+ }, 40_000);});describe('harness manifests', () => {diff --git a/src/cli.ts b/src/cli.tsindex d65b6b23..aae0e76e 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -5,13 +5,12 @@* shares one evaluation through the program-aware registry.*/import { open, readFile, writeFile } from 'node:fs/promises';-import { realpathSync } from 'node:fs';import { resolve as resolvePath } from 'node:path';import { prepareDestination } from './cli-output';+import { isDirectEntry } from './direct-entry';import { createPackagedLocalToolContext } from './local-runtime';import { createKilnProgramToolRegistry, type KilnToolContext } from './tools/registry';-import { fileURLToPath } from 'node:url';import { resolveRenderMode, buildRenderPort, describeDrawnBy } from './cli-render-mode';import type { RenderMode } from './cli-render-mode';import { localProgramStore } from './program-store-node';@@ -396,19 +395,7 @@ async function runMain(argv: readonly string[]): Promise<number> {}}-function isDirectCliEntry(): boolean {- if (!process.argv[1]) return false;- try {- // npm's Unix bin is a symlink; compare the actual files on both sides.- return (- realpathSync(resolvePath(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url))- );- } catch {- return false;- }-}--if (isDirectCliEntry()) {+if (isDirectEntry(import.meta.url)) {main(process.argv.slice(2)).then((code) => {process.exitCode = code;diff --git a/src/direct-entry.ts b/src/direct-entry.tsnew file mode 100644index 00000000..a80c4545--- /dev/null+++ b/src/direct-entry.ts@@ -0,0 +1,28 @@+import { realpathSync } from 'node:fs';+import { resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++/**+ * Is this module the file the process was told to run?+ *+ * Deliberately decided here rather than delegated to `import.meta.main`. That+ * property is Bun's, and no Bun release has lowered it to something Node+ * evaluates correctly when a bundle is built with `--target=node`. Every+ * lowering seen so far emits `__require.main == __require.module`, where both+ * sides are `undefined` under Node ESM: the guard is always true, so a plain+ * `import` of the bundle starts the process's entry work. Bun 1.4 then stopped+ * emitting the `__require` helper that line still references, turning the same+ * expression into a `ReferenceError` before the server could speak a word.+ *+ * `process.argv[1]` needs no lowering and means the same thing on both runtimes.+ * Compare real paths on each side, because npm's Unix bin is a symlink and the+ * launcher is reached through it.+ */+export function isDirectEntry(moduleUrl: string): boolean {+ if (!process.argv[1]) return false;+ try {+ return realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(moduleUrl));+ } catch {+ return false;+ }+}diff --git a/src/mcp-server.ts b/src/mcp-server.tsindex 28dd67f1..a298179d 100644--- a/src/mcp-server.ts+++ b/src/mcp-server.ts@@ -19,6 +19,7 @@ import {} from './tools/registry';import { buildRenderPort, resolveRenderMode } from './cli-render-mode';import { localProgramStore } from './program-store-node';+import { isDirectEntry } from './direct-entry';import { createPackagedLocalToolContext } from './local-runtime';/** Server identity reported in the MCP handshake. */@@ -277,7 +278,7 @@ export function createKilnMcpServer(context: KilnToolContext = {}): McpServer {return server;}-if (import.meta.main) {+if (isDirectEntry(import.meta.url)) {const mode = resolveRenderMode(process.env['KILN_RENDER'] ?? 'auto');// Resolved once, before the first connection: probing a render service per// connection would put a network round trip in front of every client attach.