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
build: rebuild dist for the runtime export options
Matt Kissingerf2c72c9d1203
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex 00643aa7..fb765950 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -13938,6 +13938,9 @@ var init_gltf_io = __esm(() => {listLevels() {return this.listRefs("levels");}+ removeLevel(level) {+ return this.removeRef("levels", level);+ }};MSFTLod = class MSFTLod extends Extension {extensionName = MSFT_LOD;@@ -24717,6 +24720,56 @@ function summarizeLodChains(doc) {};});}+function trimLodChains(doc, maxLod) {+ const chains = listLodChainNodes(doc);+ const doomed = new Set;+ for (const { levels } of chains)+ for (const level of levels.slice(maxLod + 1))+ level.traverse((node) => {+ doomed.add(node);+ });+ for (const animation of doc.getRoot().listAnimations())+ for (const channel of animation.listChannels()) {+ const target = channel.getTargetNode();+ if (target && doomed.has(target))+ throw new Error(`maxLod ${maxLod} would drop ${target.getName() || "a node"}, which animation ${JSON.stringify(animation.getName())} targets; keep that level.`);+ }+ const trimmed = chains.map(({ levels, paths }) => {+ const [base, ...lower] = levels;+ const dropped = lower.slice(maxLod);+ if (dropped.length > 0) {+ const lod = base.getExtension(MSFT_LOD);+ for (const level of dropped)+ lod.removeLevel(level);+ const extras = { ...base.getExtras() };+ const coverage = screenCoverageOf(base);+ if (maxLod === 0) {+ base.setExtension(MSFT_LOD, null);+ lod.dispose();+ delete extras[MSFT_SCREENCOVERAGE];+ } else if (coverage)+ extras[MSFT_SCREENCOVERAGE] = coverage.slice(0, maxLod + 1);+ base.setExtras(extras);+ for (const level of dropped) {+ const subtree = [];+ level.traverse((node) => {+ subtree.push(node);+ });+ for (const node of subtree.reverse())+ node.dispose();+ }+ }+ return {+ path: paths[0],+ levels: levels.length - dropped.length,+ dropped: dropped.map((level) => level.getName())+ };+ });+ const root = doc.getRoot();+ if (!root.listNodes().some((node) => node.getExtension(MSFT_LOD)))+ root.listExtensionsUsed().find((extension) => extension.extensionName === MSFT_LOD)?.dispose();+ return trimmed;+}var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;var init_lod_export = __esm(() => {init_semantic();@@ -27214,6 +27267,7 @@ function readBudgetDeclaration(value) {}}function evaluateBudget(declaration, measuredLod0, chains) {+ const instanced = measuredLod0.instancedDraws === undefined ? {} : { instancedDraws: measuredLod0.instancedDraws };const outside = measuredLod0.triangles - chains.reduce((sum, chain) => sum + chain.levels[0].triangles, 0);const tierTriangles = (level) => outside + chains.reduce((sum, chain) => sum + chain.levels[Math.min(level, chain.levels.length - 1)].triangles, 0);const tiers = Object.entries(declaration.triangles).map(([tier, limit]) => {@@ -27229,7 +27283,7 @@ function evaluateBudget(declaration, measuredLod0, chains) {},measured: {triangles,- ...drawsDeclared === undefined ? {} : { draws: measuredLod0.draws }+ ...drawsDeclared === undefined ? {} : { draws: measuredLod0.draws, ...instanced }},status: pass ? "pass" : "fail"};@@ -27238,7 +27292,7 @@ function evaluateBudget(declaration, measuredLod0, chains) {tiers.unshift({tier: "LOD0",declared: { draws: declaration.draws },- measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws },+ measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws, ...instanced },status: measuredLod0.draws <= declaration.draws ? "pass" : "fail"});return { status: tiers.every((tier) => tier.status === "pass") ? "pass" : "fail", tiers };@@ -34251,4524 +34305,4672 @@ var init_texture_bake = __esm(() => {];});-// src/exporter-node.ts-var exports_exporter_node = {};-__export(exports_exporter_node, {- nodeExportPlatform: () => nodeExportPlatform-});-async function prepareNodeExport(hasTextures) {- const host = globalThis;- if (!host["FileReader"])- host["FileReader"] = ExportFileReader;- if (!hasTextures || host["OffscreenCanvas"] || host["document"])- return;- const { Canvas, ImageData: ImageData2 } = await import("@napi-rs/canvas").catch((cause) => {- throw new Error("Headless textured export requires @napi-rs/canvas. Reinstall Kiln with optional dependencies enabled, then verify the native binding in the same Node runtime and platform used by the Kiln host.", { cause });- });-- class ExportCanvas extends Canvas {- constructor(width, height) {- super(width, height);- Object.defineProperty(this, "data", { value: undefined });- }- async convertToBlob(options = {}) {- const type = options.type ?? options.mime ?? "image/png";- if (type !== "image/png" && type !== "image/jpeg" && type !== "image/webp")- throw new Error(`Unsupported export image type: ${type}`);- const bytes = type === "image/png" ? this.toBuffer("image/png") : this.toBuffer(type);- return new Blob([new Uint8Array(bytes)], { type });- }- }- host["OffscreenCanvas"] = ExportCanvas;- if (!host["ImageData"])- host["ImageData"] = ImageData2;+// src/runtime-textures.ts+async function sha256Hex2(bytes) {+ const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");}--class ExportFileReader {- result = null;- error = null;- onloadend = null;- onerror = null;- readAsArrayBuffer(blob) {- this.read(blob, false);+function imageDimensions(bytes) {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const fail = () => {+ throw new Error("Texture manifest cannot read image dimensions");+ };+ const at = (offset, length) => {+ if (offset + length > bytes.byteLength)+ fail();+ };+ if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {+ at(16, 8);+ return { width: view.getUint32(16), height: view.getUint32(20) };}- readAsDataURL(blob) {- this.read(blob, true);+ if (isKtx2(bytes)) {+ at(20, 8);+ return { width: view.getUint32(20, true), height: view.getUint32(24, true) };}- read(blob, dataUrl) {- blob.arrayBuffer().then((bytes) => {- this.result = dataUrl ? `data:${blob.type};base64,${Buffer.from(bytes).toString("base64")}` : bytes;- this.onloadend?.();- }, (error) => {- this.error = error;- this.onerror?.();- this.onloadend?.();- });+ if (bytes[0] === 255 && bytes[1] === 216) {+ let offset = 2;+ while (offset + 4 <= bytes.byteLength) {+ if (bytes[offset] !== 255)+ fail();+ const marker = bytes[offset + 1];+ if (marker === 255) {+ offset++;+ continue;+ }+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {+ offset += 2;+ continue;+ }+ const length = view.getUint16(offset + 2);+ if (marker >= 192 && marker <= 207 && ![196, 200, 204].includes(marker)) {+ at(offset + 5, 4);+ return { width: view.getUint16(offset + 7), height: view.getUint16(offset + 5) };+ }+ offset += 2 + length;+ }+ fail();}-}-var nodeExportPlatform;-var init_exporter_node = __esm(() => {- nodeExportPlatform = {- prepare: prepareNodeExport,- async decode(bytes) {- const { default: sharp } = await import("sharp");- const decoded = await sharp(bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ const text = (offset) => String.fromCharCode(...bytes.subarray(offset, Math.min(offset + 4, bytes.byteLength)));+ if (text(0) === "RIFF" && text(8) === "WEBP") {+ at(12, 19);+ const chunk = text(12);+ if (chunk === "VP8X")return {- data: new Uint8Array(decoded.data),- width: decoded.info.width,- height: decoded.info.height+ width: 1 + (view.getUint32(24, true) & 16777215),+ height: 1 + (view.getUint32(27, true) & 16777215)+ };+ if (chunk === "VP8L") {+ const bits = view.getUint32(21, true);+ return { width: 1 + (bits & 16383), height: 1 + (bits >> 14 & 16383) };+ }+ if (chunk === "VP8 ") {+ at(26, 4);+ return {+ width: view.getUint16(26, true) & 16383,+ height: view.getUint16(28, true) & 16383};}- };-});--// src/views/character.ts-import * as THREE50 from "three";-function rounded(value) {- const result = Math.round(value * 1e9) / 1e9;- return Object.is(result, -0) ? 0 : result;-}-function tuple6(vector) {- return [rounded(vector.x), rounded(vector.y), rounded(vector.z)];-}-function chainIdFor(descriptor, byRole) {- if (AXIAL_ROLES.has(descriptor.role))- return "axial";- let current = descriptor;- const seen = new Set([current.role]);- while (current.parentRole && !AXIAL_ROLES.has(current.parentRole)) {- const parent = byRole.get(current.parentRole);- if (!parent || seen.has(parent.role))- break;- seen.add(parent.role);- current = parent;}- return current.role;+ return fail();}-function colorFor(value) {- let hash = 2166136261;- for (let index = 0;index < value.length; index++) {- hash ^= value.charCodeAt(index);- hash = Math.imul(hash, 16777619);+function textureSource(texture) {+ if (!object2(texture))+ return;+ const extensions = object2(texture.extensions) ? texture.extensions : {};+ for (const name of ["KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif"]) {+ const extension = extensions[name];+ if (object2(extension) && index(extension.source) !== undefined)+ return index(extension.source);}- return CHAIN_COLORS[Math.abs(hash) % CHAIN_COLORS.length];+ return index(texture.source);}-function buildCharacterDiagnosticDescriptor(root, findings = []) {- root.updateMatrixWorld(true);- 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((finding) => finding.code === "CHAR_PARENT_EDGE").map((finding) => finding.affected?.nodePath).filter((path) => Boolean(path)))- ].sort();- const invalidPaths = new Set(invalidFindingNodePaths);- const joints = evidence.map((joint) => {- const relative = rootInverse.clone().multiply(joint.node.matrixWorld);- const position = new THREE50.Vector3().setFromMatrixPosition(relative);- const forward = new THREE50.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);- const bend = new THREE50.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);- const chainId = chainIdFor(joint.descriptor, descriptorByRole);- return {- role: joint.descriptor.role,- aliases: [...joint.descriptor.aliases],- side: joint.descriptor.side,- nodeName: joint.node.name,- nodePath: joint.nodePath,- label: joint.descriptor.role,- chainId,- color: colorFor(chainId),- assetPosition: tuple6(position),- forwardAxisEnd: tuple6(forward),- bendAxisEnd: tuple6(bend),- endEffector: joint.descriptor.endEffector,- contact: joint.descriptor.contact- };- });- 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);- return {- parentRole,- childRole: joint.descriptor.role,- ...parent ? { parentNodePath: parent.nodePath } : {},- childNodePath: joint.nodePath,- valid: Boolean(parent) && !invalidPaths.has(joint.nodePath),- color: colorFor(chainId)- };- }).sort((a, b) => `${a.parentRole}:${a.childRole}`.localeCompare(`${b.parentRole}:${b.childRole}`));- return {- schemaVersion: 1,- joints,- edges,- contacts: joints.filter((joint) => joint.contact).map((joint) => ({- role: joint.role,- nodePath: joint.nodePath,- assetPosition: joint.assetPosition- })),- canonicalForwardArrow: { start: [0, 0, 0], end: [1, 0, 0], label: "+X forward" },- invalidFindingNodePaths- };+function srgbImages(json) {+ const textures = Array.isArray(json.textures) ? json.textures : [];+ const result = new Set;+ for (const material of Array.isArray(json.materials) ? json.materials : []) {+ if (!object2(material))+ continue;+ const pbr = object2(material.pbrMetallicRoughness) ? material.pbrMetallicRoughness : {};+ for (const info of [pbr.baseColorTexture, material.emissiveTexture]) {+ const texture = object2(info) ? index(info.index) : undefined;+ const image = texture === undefined ? undefined : textureSource(textures[texture]);+ if (image !== undefined)+ result.add(image);+ }+ }+ return result;}-function safeClipId(name) {- return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");+function base64(text) {+ const binary = atob(text);+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));}-function planCharacterDiagnosticRequests(requirements) {- const requests = [- diagnosticRequest({- id: "character.skeleton.front",- label: "Character skeleton front",- cameraId: "front",- buffer: "semantic-overlay",- variant: "character-skeleton",- focusRolePrefixes: ["skeleton.", "joint.", "contact."],- automatic: true- }),- diagnosticRequest({- id: "character.skeleton.right",- label: "Character skeleton right",- cameraId: "right",- buffer: "semantic-overlay",- variant: "character-skeleton",- focusRolePrefixes: ["skeleton.", "joint.", "contact."],- automatic: true- })- ];- const locomotion = (requirements.clips ?? []).find((clip) => clip.playback === "loop" && new RegExp(requirements.locomotion === "stationary" ? "idle" : requirements.locomotion ?? "", "i").test(clip.name)) ?? (requirements.clips ?? []).find((clip) => clip.playback === "loop");- const action = (requirements.clips ?? []).find((clip) => clip.playback === "oneShot");- const selected = [locomotion, action].filter((clip, index, values) => Boolean(clip) && values.findIndex((candidate) => candidate?.name === clip?.name) === index);- for (const clip of selected) {- for (const cameraId of ["front", "right"]) {- requests.push(diagnosticRequest({- id: `character.motion-strip.${cameraId}.${safeClipId(clip.name)}`,- label: `${clip.name} fixed-phase ${cameraId} strip`,- cameraId,- buffer: "silhouette-unlit",- variant: "character-motion-strip",- clipName: clip.name,- phaseFractions: CHARACTER_MOTION_DIAGNOSTIC_PHASES,- focusRolePrefixes: ["skeleton.", "joint.", "limb.", "held-item"],- automatic: true- }));+function embeddedImages(json, binary) {+ const views = Array.isArray(json.bufferViews) ? json.bufferViews : [];+ return (Array.isArray(json.images) ? json.images : []).map((image) => {+ if (!object2(image))+ throw new Error("Invalid glTF image");+ const view = index(image.bufferView);+ if (view !== undefined) {+ const def = views[view];+ if (!object2(def) || index(def.buffer) !== 0 || !binary)+ throw new Error("Texture manifest requires images embedded in the GLB binary chunk");+ const offset = index(def.byteOffset) ?? 0;+ const length = index(def.byteLength);+ if (length === undefined || offset + length > binary.byteLength)+ throw new Error("Invalid glTF image buffer view");+ if (typeof image.mimeType !== "string")+ throw new Error("Embedded image needs a mimeType");+ return { bytes: binary.subarray(offset, offset + length), mimeType: image.mimeType };}+ const match = typeof image.uri === "string" ? /^data:([^;,]+);base64,(.*)$/s.exec(image.uri) : null;+ if (!match)+ throw new Error("Texture manifest requires embedded image bytes");+ return { bytes: base64(match[2]), mimeType: match[1] };+ });+}+async function runtimeTextureManifest(json, binary, options = {}) {+ const srgb = srgbImages(json);+ const entries = [];+ for (const [image, { bytes, mimeType }] of embeddedImages(json, binary).entries()) {+ const sha256 = `sha256:${await sha256Hex2(bytes)}`;+ const sourceSha256 = options.sources?.get(image);+ const original = sourceSha256 ?? sha256;+ const map = options.maps?.find((candidate) => candidate.sha256 === original);+ entries.push({+ image,+ sha256,+ bytes: bytes.byteLength,+ mimeType,+ ...imageDimensions(bytes),+ colorSpace: srgb.has(image) ? "srgb" : "linear",+ ...sourceSha256 && sourceSha256 !== sha256 ? { sourceSha256 } : {},+ ...map ? { material: { pin: { ...map.pin }, slot: map.slot } } : {}+ });}- return Object.freeze(requests);+ return entries;}-var CHAIN_COLORS, AXIAL_ROLES, CHARACTER_MOTION_DIAGNOSTIC_PHASES, diagnosticRequest = (value) => Object.freeze({- ...value,- focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]),- ...value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}-});-var init_character3 = __esm(() => {- init_character();- CHAIN_COLORS = Object.freeze([- "#4fc3f7",- "#ff8a65",- "#81c784",- "#ba68c8",- "#ffd54f",- "#4db6ac",- "#f06292",- "#90a4ae"+function textureFileExtension(mimeType) {+ const extension = {+ "image/png": "png",+ "image/jpeg": "jpg",+ "image/webp": "webp",+ "image/ktx2": "ktx2"+ }[mimeType];+ if (!extension)+ throw new Error(`External textures do not support ${mimeType}`);+ return extension;+}+var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), index = (value) => Number.isInteger(value) && value >= 0 ? value : undefined, KTX2_IDENTIFIER, isKtx2 = (bytes) => bytes.byteLength >= 12 && KTX2_IDENTIFIER.every((value, at) => bytes[at] === value);+var init_runtime_textures = __esm(() => {+ KTX2_IDENTIFIER = Object.freeze([+ 171,+ 75,+ 84,+ 88,+ 32,+ 50,+ 48,+ 187,+ 13,+ 10,+ 26,+ 10]);- AXIAL_ROLES = new Set(["root", "hips", "spine", "neck", "head"]);- CHARACTER_MOTION_DIAGNOSTIC_PHASES = Object.freeze([0, 0.2, 0.4, 0.6, 0.8, 1]);});-// src/views/diagnostic.ts-function multiplyMatrices(a, b) {- const out = new Float64Array(16);- for (let column = 0;column < 4; column++) {- for (let row = 0;row < 4; row++) {- let value = 0;- for (let k = 0;k < 4; k++)- value += a[k * 4 + row] * b[column * 4 + k];- out[column * 4 + row] = value;+// src/runtime-three.ts+var exports_runtime_three = {};+__export(exports_runtime_three, {+ deliverRuntimeThreeGlb: () => deliverRuntimeThreeGlb,+ instancedDrawEstimate: () => instancedDrawEstimate+});+import {+ Accessor,+ Format,+ Logger,+ PropertyType as PropertyType5+} from "@gltf-transform/core";+import {+ EXTMeshGPUInstancing,+ EXTMeshoptCompression,+ KHRMeshQuantization,+ KHRTextureBasisu as KHRTextureBasisu2+} from "@gltf-transform/extensions";+import { cloneDocument, dedup, prune, quantize, reorder } from "@gltf-transform/functions";+import * as THREE50 from "three";+function meshSignature(mesh, ids) {+ const id = (property) => {+ if (!property)+ return -1;+ if (!ids.has(property))+ ids.set(property, ids.size);+ return ids.get(property);+ };+ return mesh.listPrimitives().map((primitive) => `${primitive.getMode()}:${id(primitive.getMaterial())}:${id(primitive.getIndices())}:${primitive.listSemantics().sort().map((semantic) => `${semantic}=${id(primitive.getAttribute(semantic))}`).join(",")}:${primitive.listTargets().length}`).join("|");+}+async function instancedDrawEstimate(doc) {+ const copy = cloneDocument(doc);+ copy.setLogger(new Logger(Logger.Verbosity.SILENT));+ await copy.transform(dedup({ propertyTypes: [PropertyType5.ACCESSOR], keepUniqueNames: true }));+ applyScopedInstancing(copy);+ return collectGlbMetrics(copy).drawCalls;+}+function applyScopedInstancing(doc) {+ const report = [];+ const ids = new Map;+ const parents = doc.getRoot().listNodes().filter((node) => node.getExtras()[KILN_REPEAT_INSTANCES_KEY] !== undefined);+ let extension;+ for (const parent of parents) {+ const groups = new Map;+ for (const child of parent.listChildren()) {+ const mesh = child.getMesh();+ if (!mesh || child.listChildren().length || child.getSkin() || child.listExtensions().length || isHiddenGltfNode(child) || rolesOf4(child).length || Object.keys(child.getExtras()).length || child.getWeights().length)+ continue;+ const signature = meshSignature(mesh, ids);+ groups.set(signature, [...groups.get(signature) ?? [], child]);+ }+ let batchIndex = 0;+ for (const nodes of groups.values()) {+ if (nodes.length < 2)+ continue;+ const mesh = nodes[0].getMesh();+ extension ??= doc.createExtension(EXTMeshGPUInstancing).setRequired(true);+ const buffer = doc.getRoot().listBuffers()[0];+ const accessor = (type, values) => doc.createAccessor().setType(type).setArray(new Float32Array(values)).setBuffer(buffer ?? null);+ const t = [], r = [], s = [];+ for (const node of nodes) {+ t.push(...node.getTranslation());+ r.push(...node.getRotation());+ s.push(...node.getScale());+ }+ const batch = extension.createInstancedMesh().setAttribute("TRANSLATION", accessor("VEC3", t)).setAttribute("ROTATION", accessor("VEC4", r)).setAttribute("SCALE", accessor("VEC3", s));+ const name = `${parent.getName() || "Node"}_Instances${batchIndex ? `_${batchIndex}` : ""}`;+ batchIndex++;+ const batchNode = doc.createNode(name).setMesh(mesh).setExtension("EXT_mesh_gpu_instancing", batch);+ parent.addChild(batchNode);+ report.push({+ node: batchNode,+ mesh: mesh.getName(),+ count: nodes.length,+ instances: nodes.map((node) => node.getName())+ });+ for (const node of nodes) {+ const own = node.getMesh();+ node.dispose();+ if (own && own !== mesh && !own.listParents().some((p) => p.propertyType === PropertyType5.NODE))+ own.dispose();+ }}+ const extras = { ...parent.getExtras() };+ delete extras[KILN_REPEAT_INSTANCES_KEY];+ parent.setExtras(extras);}- return out;+ return report;}-function composeLocalMatrix(node) {- if (node.matrixAutoUpdate === false && node.matrix?.elements) {- return new Float64Array(Array.from(node.matrix.elements));- }- const p = node.position;- const q = node.quaternion;- const s = node.scale;- if (!p || !q || !s) {- return node.matrix?.elements ? new Float64Array(Array.from(node.matrix.elements)) : new Float64Array(IDENTITY);+function splitColliderProxies(doc) {+ const report = [];+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh || !isCollider(node))+ continue;+ const proxy = doc.createNode(`${node.getName()}_Proxy`).setMesh(mesh);+ node.setMesh(null).addChild(proxy);+ report.push({ collider: node, proxy });}- const x2 = q.x + q.x;- const y2 = q.y + q.y;- const z2 = q.z + q.z;- const xx = q.x * x2;- const xy = q.x * y2;- const xz = q.x * z2;- const yy = q.y * y2;- const yz = q.y * z2;- const zz = q.z * z2;- const wx = q.w * x2;- const wy = q.w * y2;- const wz = q.w * z2;- return new Float64Array([- (1 - (yy + zz)) * s.x,- (xy + wz) * s.x,- (xz - wy) * s.x,- 0,- (xy - wz) * s.y,- (1 - (xx + zz)) * s.y,- (yz + wx) * s.y,- 0,- (xz + wy) * s.z,- (yz - wx) * s.z,- (1 - (xx + yy)) * s.z,- 0,- p.x,- p.y,- p.z,- 1- ]);-}-function transformPoint2(matrix, x, y, z) {- return [- 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]- ];+ return report;}-function matchesRole(roles, prefixes) {- return Boolean(prefixes?.some((prefix) => roles.some((role) => role.startsWith(prefix))));+async function encodeKtx2(doc, encoder, sources) {+ const textures = doc.getRoot().listTextures().filter((texture) => texture.getMimeType() !== "image/ktx2" && texture.getImage());+ if (!encoder)+ return {+ status: "skipped",+ textures: textures.length,+ reason: "No KTX2 encoder was supplied; textures stay PNG or JPEG."+ };+ const slots = new Map;+ const use = (texture, slot) => {+ if (texture)+ slots.set(texture, (slots.get(texture) ?? new Set).add(slot));+ };+ for (const material of doc.getRoot().listMaterials()) {+ use(material.getBaseColorTexture(), "baseColor");+ use(material.getEmissiveTexture(), "emissive");+ use(material.getNormalTexture(), "normal");+ use(material.getMetallicRoughnessTexture(), "metallicRoughness");+ use(material.getOcclusionTexture(), "occlusion");+ }+ const order = [+ "baseColor",+ "emissive",+ "normal",+ "metallicRoughness",+ "occlusion"+ ];+ for (const texture of textures) {+ const used = slots.get(texture) ?? new Set;+ const srgb = used.has("baseColor") || used.has("emissive");+ const other = texture.listParents().some((parent) => parent.propertyType !== PropertyType5.ROOT && !isCoreMaterialUse(parent));+ const linear = [...used].some((slot) => slot !== "baseColor" && slot !== "emissive") || other;+ if (srgb && linear)+ throw new Error(`Texture ${JSON.stringify(texture.getName())} is used by both sRGB and linear material slots; one KTX2 encoding cannot serve both. Use separate images.`);+ const original = texture.getImage();+ const image = await encoder({+ image: original,+ mimeType: texture.getMimeType(),+ name: texture.getName(),+ colorSpace: srgb ? "srgb" : "linear",+ slot: order.find((slot) => used.has(slot)) ?? "other"+ });+ if (!(image instanceof Uint8Array) || !isKtx2(image))+ throw new Error("ktx2Encoder must return KTX2 bytes starting with the KTX2 identifier");+ sources.set(texture, `sha256:${await sha256Hex2(original)}`);+ texture.setImage(image).setMimeType("image/ktx2");+ const uri = texture.getURI();+ if (uri)+ texture.setURI(uri.replace(/\.(png|jpe?g)$/i, ".ktx2"));+ }+ if (textures.length) {+ doc.createExtension(KHRTextureBasisu2).setRequired(true);+ await Promise.resolve().then(() => init_atlas_provenance());+ await refreshAtlasDocumentProvenance(doc);+ await validateAtlasDocumentProvenance(doc);+ }+ return {+ status: "encoded",+ textures: textures.length,+ ...encoder.identity ? { encoder: structuredClone(encoder.identity) } : {}+ };}-function semanticRoles2(node) {- const metadata = readSemanticMetadataV1FromExtras(node.userData ?? {});- if (metadata)- return metadata.roles;- const geometryRole = node.geometry?.userData?.["kilnGeometryRole"];- return typeof geometryRole === "string" ? [geometryRole] : [];+function isCoreMaterialUse(parent) {+ return parent.propertyType === PropertyType5.MATERIAL;}-function clamp012(value) {- return value < 0 ? 0 : value > 1 ? 1 : value;+function decomposeDelta(before, after) {+ const delta = new THREE50.Matrix4().fromArray(before).invert().multiply(new THREE50.Matrix4().fromArray(after));+ const position = new THREE50.Vector3, quaternion = new THREE50.Quaternion, scale = new THREE50.Vector3;+ delta.decompose(position, quaternion, scale);+ return {+ scale: scale.x,+ offset: [position.x, position.y, position.z]+ };}-function collectScene(root, requestValue) {- const triangles = [];- const min = [Infinity, Infinity, Infinity];- const max = [-Infinity, -Infinity, -Infinity];- const focusMin = [Infinity, Infinity, Infinity];- const focusMax = [-Infinity, -Infinity, -Infinity];- const visit = (node, parentMatrix, parentPath, siblingIndex, ancestorVisible, inheritedRoles) => {- const local = composeLocalMatrix(node);- const world = multiplyMatrices(parentMatrix, local);- const visible = ancestorVisible && node.visible !== false;- const segment = `${node.name?.trim() || node.type || "Node"}[${siblingIndex}]`;- 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];- if (material?.visible !== false) {- const position = node.geometry.getAttribute?.("position");- if (position?.itemSize === 3) {- const worldPositions = [];- 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 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)))) {- return;- }- const vertices = new Float64Array(9);- points.forEach((point, pointIndex) => {- for (let axis = 0;axis < 3; axis++) {- const value = point[axis];- vertices[pointIndex * 3 + axis] = value;- min[axis] = Math.min(min[axis], value);- max[axis] = Math.max(max[axis], value);- if (focused) {- focusMin[axis] = Math.min(focusMin[axis], value);- focusMax[axis] = Math.max(focusMax[axis], value);- }- }- });- triangles.push({- vertices,- color,- nodeName: node.name ?? "",- nodePath,- semanticRoles: roles- });- };- const index = node.geometry.index;- if (index) {- for (let i = 0;i + 2 < index.count; i += 3) {- addTriangle(index.array[i], index.array[i + 1], index.array[i + 2]);- }- } else {- for (let i = 0;i + 2 < position.count; i += 3)- addTriangle(i, i + 1, i + 2);- }+function hasQuantizedVertexData(doc) {+ const quantized = (semantic, accessor) => {+ if (accessor.getComponentSize() >= 4)+ return false;+ if (semantic === "POSITION" || semantic === "NORMAL" || semantic === "TANGENT")+ return true;+ if (!semantic.startsWith("TEXCOORD_"))+ return false;+ const type = accessor.getComponentType();+ return !(accessor.getNormalized() && (type === Accessor.ComponentType.UNSIGNED_BYTE || type === Accessor.ComponentType.UNSIGNED_SHORT));+ };+ return doc.getRoot().listMeshes().flatMap((mesh) => mesh.listPrimitives()).flatMap((primitive) => [primitive, ...primitive.listTargets()]).some((target) => target.listSemantics().some((semantic) => quantized(semantic, target.getAttribute(semantic))));+}+function positionGridSteps(doc, bits) {+ const levels = 2 ** (bits - 1) - 1;+ const lodBase = new Map;+ for (const node of doc.getRoot().listNodes())+ for (const level of node.getExtension(MSFT_LOD)?.listLevels() ?? [])+ if (level.propertyType === PropertyType5.NODE)+ lodBase.set(level, node);+ const world = (node) => {+ const matrix = new THREE50.Matrix4().fromArray(node.getWorldMatrix());+ let top = node;+ while (top.getParentNode())+ top = top.getParentNode();+ const placed = lodBase.get(top)?.getParentNode();+ return placed ? new THREE50.Matrix4().fromArray(placed.getWorldMatrix()).multiply(matrix) : matrix;+ };+ const halfExtent = (mesh) => {+ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];+ const widen = (values, doubleFromZero) => {+ for (let axis = 0;axis < 3; axis++) {+ const value = values[axis];+ const candidates = doubleFromZero ? [value, value * 2, 0] : [value];+ min[axis] = Math.min(min[axis], ...candidates);+ max[axis] = Math.max(max[axis], ...candidates);+ }+ };+ for (const primitive of mesh.listPrimitives()) {+ const position = primitive.getAttribute("POSITION");+ if (position) {+ widen(position.getMin([]), false);+ widen(position.getMax([]), false);+ }+ for (const target of primitive.listTargets()) {+ const delta = target.getAttribute("POSITION");+ if (delta) {+ widen(delta.getMin([]), true);+ widen(delta.getMax([]), true);}}}- (node.children ?? []).forEach((child, index) => {- visit(child, world, nodePath, index, visible && !omitted, roles);- });+ return Math.max(...[0, 1, 2].map((axis) => (max[axis] - min[axis]) / 2));};- visit(root, IDENTITY, "", 0, true, []);- const empty = !Number.isFinite(min[0]);- const focusEmpty = !Number.isFinite(focusMin[0]);- return {- triangles,- bounds: empty ? { min: [0, 0, 0], max: [0, 0, 0] } : { min, max },- ...!focusEmpty ? { focusBounds: { min: focusMin, max: focusMax } } : {}+ const instanceScale = (node) => {+ const scale = node.getExtension("EXT_mesh_gpu_instancing")?.getAttribute("SCALE");+ if (!scale)+ return 1;+ let largest = 0;+ for (let i = 0;i < scale.getCount(); i++)+ largest = Math.max(largest, ...scale.getElement(i, []).map(Math.abs));+ return largest;};-}-function normalize4(vector) {- 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]];-}-function dot4(a, b) {- return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];-}-function stableColor(key) {- let hash = 2166136261;- for (let index = 0;index < key.length; index++) {- hash ^= key.charCodeAt(index);- hash = Math.imul(hash, 16777619);+ const steps = [];+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh?.listPrimitives().some((primitive) => primitive.getAttribute("POSITION")))+ continue;+ const scale = node.getSkin() ? 1 : world(node).getMaxScaleOnAxis() * instanceScale(node);+ steps.push({ node, mesh: mesh.getName(), step: halfExtent(mesh) * scale / levels });+ }+ return steps;+}+async function trimLevels(doc, maxLod) {+ const chains = trimLodChains(doc, maxLod);+ const budgetTiersOmitted = [];+ if (chains.some((chain) => chain.dropped.length > 0)) {+ await doc.transform(prune({+ propertyTypes: [+ PropertyType5.MESH,+ PropertyType5.PRIMITIVE,+ PropertyType5.PRIMITIVE_TARGET,+ PropertyType5.ACCESSOR,+ PropertyType5.MATERIAL,+ PropertyType5.TEXTURE+ ],+ keepAttributes: true,+ keepIndices: true,+ keepLeaves: true,+ keepExtras: true,+ keepSolidTextures: true+ }));+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ const extras = { ...scene?.getExtras() ?? {} };+ const budget = extras[KILN_BUDGET_KEY];+ if (scene && budget?.triangles) {+ const triangles = { ...budget.triangles };+ for (const tier of Object.keys(triangles))+ if (Number(tier.slice(3)) > maxLod) {+ budgetTiersOmitted.push(tier);+ delete triangles[tier];+ }+ if (Object.keys(triangles).length > 0)+ extras[KILN_BUDGET_KEY] = { ...budget, triangles };+ else+ delete extras[KILN_BUDGET_KEY];+ scene.setExtras(extras);+ }}- return [96 + (hash & 127), 96 + (hash >>> 8 & 127), 96 + (hash >>> 16 & 127)];+ return { maxLod, chains, budgetTiersOmitted };}-function projectScene(scene, camera, size) {- const zAxis = normalize4(camera.dir);- const upHint = Math.abs(zAxis[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];- const xAxis = normalize4(cross3(upHint, zAxis));- const yAxis = cross3(zAxis, xAxis);- const frame = scene.focusBounds ?? scene.bounds;- const center = [- (frame.min[0] + frame.max[0]) / 2,- (frame.min[1] + frame.max[1]) / 2,- (frame.min[2] + frame.max[2]) / 2- ];- 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]- ];- extent = Math.max(extent, Math.abs(dot4(point, xAxis)), Math.abs(dot4(point, yAxis)));- }- 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 length = Math.hypot(...normalRaw);- if (length < 0.000000000001)- return [];- const normal = normalRaw.map((component) => component / length);- const xs = [];- const ys = [];- const zs = [];- const worldY = [];- for (let index = 0;index < 3; index++) {- const point = [- v[index * 3] - center[0],- v[index * 3 + 1] - center[1],- v[index * 3 + 2] - center[2]- ];- 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]);- }- return [- {- source: triangle,- x: xs,- y: ys,- z: zs,- worldY,- normal,- frontFacing: dot4(normal, zAxis) > 0- }- ];+async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layout = {}) {+ const compression = options.compression ?? "meshopt";+ if (compression !== "meshopt" && compression !== "none")+ throw new Error("Runtime three compression must be meshopt or none");+ const { maxLod } = options;+ if (maxLod !== undefined && !(Number.isSafeInteger(maxLod) && maxLod >= 0))+ throw new Error("Runtime three maxLod must be a non-negative integer");+ const positionBits = options.positionBits ?? RUNTIME_THREE_QUANTIZATION.position;+ if (positionBits !== "float" && !(Number.isSafeInteger(positionBits) && positionBits >= 8 && positionBits <= 16))+ throw new Error("Runtime three positionBits must be an integer from 8 to 16, or float");+ const io = createGltfIO().registerDependencies({+ "meshopt.encoder": meshoptEncoder});-}-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]);- const y1 = Math.round(to[1]);- const dx = Math.abs(x1 - x0);- const sx = x0 < x1 ? 1 : -1;- const dy = -Math.abs(y1 - y0);- const sy = y0 < y1 ? 1 : -1;- let error = dx + dy;- while (true) {- if (x0 >= 0 && x0 < size && y0 >= 0 && y0 < size) {- const offset = (y0 * size + x0) * 3;- rgb[offset] = color[0];- rgb[offset + 1] = color[1];- rgb[offset + 2] = color[2];- }- if (x0 === x1 && y0 === y1)- break;- const doubled = 2 * error;- if (doubled >= dy) {- error += dy;- x0 += sx;- }- if (doubled <= dx) {- error += dx;- y0 += sy;- }- }-}-function drawRegionBox(rgb, size, region) {- const [minX, minY, maxX, maxY] = region.pixelBounds;- 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);- if (!camera)- throw new TypeError(`Unknown diagnostic camera ${JSON.stringify(requestValue.cameraId)}.`);- const size = Math.max(16, Math.min(1024, Math.round(options.size ?? 256)));- const groundY = options.groundY ?? 0;- const scene = collectScene(root, requestValue);- const triangles = projectScene(scene, camera, size);- const background = [18, 20, 24];- const rgb = new Uint8Array(size * size * 3);- for (let pixel = 0;pixel < size * size; pixel++) {- rgb[pixel * 3] = background[0];- rgb[pixel * 3 + 1] = background[1];- rgb[pixel * 3 + 2] = background[2];+ const doc = await io.readBinary(bytes);+ doc.setLogger(new Logger(Logger.Verbosity.SILENT));+ const lod = maxLod === undefined ? undefined : await trimLevels(doc, maxLod);+ await doc.transform(dedup({ propertyTypes: [PropertyType5.ACCESSOR], keepUniqueNames: true }));+ const instanced = applyScopedInstancing(doc);+ const proxies = splitColliderProxies(doc);+ const matrices = new Map;+ for (const node of doc.getRoot().listNodes())+ if (node.getMesh())+ matrices.set(node, [...node.getMatrix()]);+ const steps = positionBits === "float" ? [] : positionGridSteps(doc, positionBits);+ const semantics = positionBits === "float" ? QUANTIZED_SEMANTICS_EXCEPT_POSITION : QUANTIZED_SEMANTICS;+ await doc.transform(reorder({ encoder: meshoptEncoder, target: "size" }), quantize({+ pattern: semantics,+ patternTargets: semantics,+ quantizationVolume: "mesh",+ quantizePosition: positionBits === "float" ? RUNTIME_THREE_QUANTIZATION.position : positionBits,+ quantizeNormal: RUNTIME_THREE_QUANTIZATION.normal,+ quantizeTexcoord: RUNTIME_THREE_QUANTIZATION.texcoord,+ quantizeColor: RUNTIME_THREE_QUANTIZATION.color,+ quantizeWeight: RUNTIME_THREE_QUANTIZATION.weight+ }));+ if (positionBits === "float" && hasQuantizedVertexData(doc))+ doc.createExtension(KHRMeshQuantization).setRequired(true);+ if (compression === "meshopt")+ doc.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE });+ const encodedSources = new Map;+ const ktx2 = await encodeKtx2(doc, options.ktx2Encoder, encodedSources);+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh || matrices.has(node) || node.getName())+ continue;+ const parent = node.getParentNode();+ node.setName(`${parent?.getName() || "Node"}_Mesh`);}- const depth = new Float64Array(size * size).fill(-Infinity);- const depths = triangles.flatMap((triangle) => triangle.z);- const minDepth = depths.length > 0 ? Math.min(...depths) : 0;- const maxDepth = depths.length > 0 ? Math.max(...depths) : 1;- const depthRange = Math.max(0.000000001, maxDepth - minDepth);- const contactTolerance = Math.max(0.0001, (scene.bounds.max[1] - scene.bounds.min[1]) * 0.015);- const regionMap = new Map;- for (const triangle of triangles) {- const minX = Math.max(0, Math.floor(Math.min(...triangle.x)));- const maxX = Math.min(size - 1, Math.ceil(Math.max(...triangle.x)));- const minY = Math.max(0, Math.floor(Math.min(...triangle.y)));- const maxY = Math.min(size - 1, Math.ceil(Math.max(...triangle.y)));- if (minX > maxX || minY > maxY)+ const after = deliveryNodePaths(doc);+ const pathOf = (node) => after.get(node) ?? `#${encodeURIComponent(node.getName())}`;+ const proxyNodes = new Set(proxies.map((entry) => entry.proxy));+ const nodeScale = [];+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh || node.getExtension("EXT_mesh_gpu_instancing"))continue;- const key = triangle.source.semanticRoles.at(-1) ?? triangle.source.nodePath;- const regionColor = stableColor(key);- const existing = regionMap.get(triangle.source.nodePath);- if (existing) {- existing.pixelBounds[0] = Math.min(existing.pixelBounds[0], minX);- existing.pixelBounds[1] = Math.min(existing.pixelBounds[1], minY);- existing.pixelBounds[2] = Math.max(existing.pixelBounds[2], maxX);- existing.pixelBounds[3] = Math.max(existing.pixelBounds[3], maxY);- existing.triangleCount++;- } else {- regionMap.set(triangle.source.nodePath, {- nodeName: triangle.source.nodeName,- nodePath: triangle.source.nodePath,- semanticRoles: [...triangle.source.semanticRoles],- pixelBounds: [minX, minY, maxX, maxY],- color: regionColor,- triangleCount: 1- });- }- if (requestValue.buffer === "wireframe")+ const path = after.get(node);+ if (path === undefined)continue;- const ax = triangle.x[0];- const ay = triangle.y[0];- const bx = triangle.x[1];- const by = triangle.y[1];- const cx = triangle.x[2];- const cy = triangle.y[2];- const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);- if (Math.abs(area) < 0.000000001)+ const original = matrices.get(node);+ const moved = original === undefined;+ const split = moved || proxyNodes.has(node);+ const reference = moved ? new THREE50.Matrix4().identity().toArray() : original;+ const current = [...node.getMatrix()];+ const { scale, offset } = decomposeDelta(reference, current);+ if (!moved && Math.abs(scale - 1) < 0.000000000001 && offset.every((v) => v === 0))continue;- const inverseArea = 1 / area;- for (let py = minY;py <= maxY; py++) {- for (let px = minX;px <= maxX; px++) {- const sampleX = px + 0.5;- const sampleY = py + 0.5;- const w0 = ((bx - ax) * (sampleY - ay) - (by - ay) * (sampleX - ax)) * inverseArea;- const w1 = ((cx - bx) * (sampleY - by) - (cy - by) * (sampleX - bx)) * inverseArea;- const w2 = 1 - w0 - w1;- if (w0 < 0 || w1 < 0 || w2 < 0)- continue;- const pixelDepth = w1 * triangle.z[0] + w2 * triangle.z[1] + w0 * triangle.z[2];- const pixel = py * size + px;- if (pixelDepth <= depth[pixel])- continue;- depth[pixel] = pixelDepth;- const offset = pixel * 3;- let color;- if (requestValue.variant === "material-grazing-light") {- const grazingDirection = normalize4([0.25, 0.08, 1]);- const light = 0.08 + 0.92 * Math.max(0, dot4(triangle.normal, grazingDirection));- color = triangle.source.color.map((value) => Math.round(clamp012(value * light) * 255));- } else if (requestValue.buffer === "silhouette-unlit") {- color = [235, 238, 242];- } else if (requestValue.buffer === "normals-backface") {- 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)- color = [58, 220, 126];- else if (worldY < groundY - contactTolerance)- color = [245, 94, 72];- else {- const value = Math.round(48 + 190 * ((pixelDepth - minDepth) / depthRange));- color = [value, value, value];- }- } else {- color = regionColor;- }- rgb[offset] = color[0];- rgb[offset + 1] = color[1];- rgb[offset + 2] = color[2];- }- }- }- if (requestValue.buffer === "wireframe") {- for (const triangle of triangles) {- const color = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];- for (const [a, b] of [- [0, 1],- [1, 2],- [2, 0]- ]) {- drawLine(rgb, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color);- }- }+ const parent = node.getParentNode();+ nodeScale.push({+ node: path,+ mesh: mesh.getName(),+ meshMovedToChild: split,+ ...split && parent ? { authoredNode: pathOf(parent) } : {},+ dequantization: { scale, offset },+ localScale: [...node.getScale()]+ });}- const regions = [...regionMap.values()].sort((a, b) => a.nodePath.localeCompare(b.nodePath));- if (requestValue.buffer === "semantic-overlay") {- for (const region of regions)- drawRegionBox(rgb, size, region);+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh || after.has(node) || !matrices.has(node))+ continue;+ const { scale, offset } = decomposeDelta(matrices.get(node), [...node.getMatrix()]);+ nodeScale.push({+ node: `#lod/${encodeURIComponent(node.getName())}`,+ mesh: mesh.getName(),+ meshMovedToChild: false,+ dequantization: { scale, offset },+ localScale: [...node.getScale()]+ });}- return {- id: requestValue.id,- label: requestValue.label,- camera,- buffer: requestValue.buffer,- ...requestValue.variant ? { variant: requestValue.variant } : {},- width: size,- height: size,- rgb,- png: encodePng(rgb, size, size),- regions,- ...requestValue.phaseFractions ? { phaseFractions: requestValue.phaseFractions } : {}- };-}-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]) } : {},- ...value.focusRolePrefixes ? { focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]) } : {},- ...value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}-}), GENERIC_DIAGNOSTIC_REQUESTS, CATEGORY_REQUESTS, MOBILITY_DIAGNOSTIC_REQUESTS, MATERIAL_GRAZING_REQUEST, IDENTITY;-var init_diagnostic = __esm(() => {- init_contracts();- init_character3();- init_png();- GENERIC_DIAGNOSTIC_BUFFER_IDS = [- "silhouette-unlit",- "wireframe",- "normals-backface",- "depth-contact",- "semantic-overlay"- ];- GENERIC_DIAGNOSTIC_CAMERAS = Object.freeze([- frozenCamera("front", "Front", [1, 0, 0]),- frozenCamera("right", "Right", [0, 0, 1]),- frozenCamera("back", "Back", [-1, 0, 0]),- frozenCamera("left", "Left", [0, 0, -1]),- frozenCamera("top", "Top", [0, 1, 0.0001]),- frozenCamera("three-quarter", "3/4", [0.7, 0.5, 0.7])- ]);- EXTRA_CAMERAS = Object.freeze({- underside: frozenCamera("underside", "Canopy underside", [0.15, -0.85, 0.5]),- grazing: frozenCamera("grazing", "Material grazing light", [0.08, 0.12, 1])- });- cameraById = new Map([...GENERIC_DIAGNOSTIC_CAMERAS, ...Object.values(EXTRA_CAMERAS)].map((camera) => [- camera.id,- camera- ]));- GENERIC_DIAGNOSTIC_REQUESTS = Object.freeze(GENERIC_DIAGNOSTIC_CAMERAS.flatMap((camera) => GENERIC_DIAGNOSTIC_BUFFER_IDS.map((buffer) => request({- id: `generic.${camera.id}.${buffer}`,- label: `${camera.name} ${buffer}`,- cameraId: camera.id,- buffer,- scope: "generic"- }))));- CATEGORY_REQUESTS = Object.freeze({- prop: Object.freeze([]),- vfx: Object.freeze([]),- environment: Object.freeze([]),- architecture: Object.freeze([]),- character: Object.freeze([]),- vehicle: Object.freeze([- request({- id: "vehicle.underbody",- label: "Vehicle underbody and support plane",- cameraId: "underside",- buffer: "semantic-overlay",- scope: "category",- variant: "vehicle-underbody",- focusRolePrefixes: [- "chassis.",- "wheel.",- "axle.",- "support.",- "contact.",- "diagnostic.vehicle."- ]- }),- request({- id: "vehicle.wheel-section.right",- label: "Vehicle wheel section",- cameraId: "right",- buffer: "semantic-overlay",- scope: "category",- variant: "vehicle-wheel-section",- focusRolePrefixes: ["wheel.", "axle.", "hub.", "tire."]- })- ]),- vegetation: Object.freeze([- request({- id: "vegetation.canopy-underside",- label: "Vegetation canopy underside",- cameraId: "underside",- buffer: "normals-backface",- scope: "category",- variant: "vegetation-canopy-underside",- focusRolePrefixes: ["canopy.", "foliage.", "leaf."]- })- ])+ const customAttributes = new Map;+ for (const mesh of doc.getRoot().listMeshes())+ for (const primitive of mesh.listPrimitives())+ for (const semantic of primitive.listSemantics())+ if (semantic.startsWith("_"))+ customAttributes.set(semantic, (customAttributes.get(semantic) ?? new Set).add(mesh));+ const all = doc.getRoot().listNodes();+ const glb = await io.writeBinary(doc);+ const json = (await io.binaryToJSON(glb)).json;+ const imageSources = new Map;+ doc.getRoot().listTextures().forEach((texture, image) => {+ const source = encodedSources.get(texture);+ if (source)+ imageSources.set(image, source);});- MOBILITY_DIAGNOSTIC_REQUESTS = CATEGORY_REQUESTS.vehicle;- MATERIAL_GRAZING_REQUEST = request({- id: "material.grazing-light",- label: "Material grazing light",- cameraId: "grazing",- buffer: "silhouette-unlit",- scope: "material",- variant: "material-grazing-light"+ const gltf = layout.gltfBasename ? await io.writeJSON(doc, { format: Format.GLTF, basename: layout.gltfBasename }) : undefined;+ const delivery = {+ target: "three",+ extensionsUsed: [...json.extensionsUsed ?? []].sort(),+ extensionsRequired: [...json.extensionsRequired ?? []].sort(),+ compression: compression === "meshopt" ? { extension: "EXT_meshopt_compression", method: "quantize" } : { extension: "none" },+ quantization: {+ extension: "KHR_mesh_quantization",+ volume: "mesh",+ bits: {+ position: positionBits === "float" ? "float32" : positionBits,+ normal: RUNTIME_THREE_QUANTIZATION.normal,+ texcoord: RUNTIME_THREE_QUANTIZATION.texcoord,+ color: RUNTIME_THREE_QUANTIZATION.color,+ weight: RUNTIME_THREE_QUANTIZATION.weight+ },+ customAttributes: "float32",+ positionSteps: steps.map(({ node, mesh, step }) => ({+ node: after.get(node) ?? `#lod/${encodeURIComponent(node.getName())}`,+ mesh,+ step+ })),+ maxPositionStep: Math.max(0, ...steps.map(({ step }) => step))+ },+ nodeScale,+ colliderProxies: proxies.map(({ collider, proxy }) => ({+ collider: pathOf(collider),+ proxy: pathOf(proxy)+ })),+ customAttributes: [...customAttributes].sort(([a], [b]) => customRank(a) - customRank(b) || (a < b ? -1 : a > b ? 1 : 0)).map(([name, meshes]) => ({+ name,+ meshes: meshes.size,+ componentType: "FLOAT",+ normalized: false+ })),+ instancing: instanced.map(({ node, ...rest }) => ({ node: pathOf(node), ...rest })),+ ktx2,+ ...lod ? { lod } : {},+ preserved: {+ lodChains: all.filter((node) => node.getExtension(MSFT_LOD)).length,+ hiddenNodes: all.filter((node) => isHiddenGltfNode(node)).length,+ colliders: all.filter(isCollider).length,+ anchors: all.filter((node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.anchor}.`))).length,+ ports: all.filter((node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.kitPort}.`))).length,+ kitModules: all.filter((node) => rolesOf4(node).includes(KILN_SEMANTIC_ROLES.kitModule)).length+ }+ };+ return {+ glb,+ delivery,+ imageSources,+ ...gltf ? {+ gltf: {+ json: gltf.json,+ resources: gltf.resources+ }+ } : {}+ };+}+var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, QUANTIZED_SEMANTICS_EXCEPT_POSITION, customRank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2, rolesOf4 = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));+var init_runtime_three = __esm(() => {+ init_semantic();+ init_gltf_io();+ init_delivery_inspect();+ init_delivery();+ init_metrics();+ init_runtime_textures();+ init_lod_export();+ init_budget();+ RUNTIME_THREE_QUANTIZATION = Object.freeze({+ volume: "mesh",+ position: 14,+ normal: 10,+ texcoord: 12,+ color: 8,+ weight: 8});- IDENTITY = new Float64Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+ QUANTIZED_SEMANTICS = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;+ QUANTIZED_SEMANTICS_EXCEPT_POSITION = /^(NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;});-// src/views/capture.ts-function captureCellLabel(azimuthDeg, elevationDeg) {- const az = Math.round((azimuthDeg % 360 + 360) % 360);- const el = Math.round(elevationDeg);- return `A${az} ${el < 0 ? "D" : "U"}${Math.abs(el)}`;-}-function resolveCaptureBackdrop(backdrop) {- if (backdrop === undefined)- return DEFAULT_BACKDROP_ID;- if (!isBackdropId(backdrop))- throw new CaptureConfigError(`capture.backdrop must be one of ${BACKDROP_IDS.join(", ")} (got ${JSON.stringify(backdrop)}).`);- return backdrop;-}-function resolveCapture(config) {- const backdrop = resolveCaptureBackdrop(config?.backdrop);- if (!config || config.preset === undefined && config.cells === undefined) {- return {- preset: DEFAULT_CAPTURE_PRESET,- views: PRESET_VIEWS[DEFAULT_CAPTURE_PRESET],- cols: PRESET_COLS[DEFAULT_CAPTURE_PRESET],- zooms: new Array(PRESET_CAPACITY[DEFAULT_CAPTURE_PRESET]).fill(undefined),- isDefault: true,- backdrop- };- }- const cells = config.cells;- let preset = config.preset;- if (preset !== undefined && !CAPTURE_PRESETS.includes(preset)) {- throw new CaptureConfigError(`capture.preset must be one of ${CAPTURE_PRESETS.join(", ")} (got ${JSON.stringify(preset)}).`);- }- if (cells !== undefined) {- if (!Array.isArray(cells) || cells.length === 0) {- throw new CaptureConfigError("capture.cells must be a non-empty array of camera angles.");- }- if (cells.length > MAX_CAPTURE_CELLS) {- throw new CaptureConfigError(`capture.cells has ${cells.length} entries; the maximum is ${MAX_CAPTURE_CELLS}.`);- }- for (let i = 0;i < cells.length; i++) {- const c = cells[i];- if (!Number.isFinite(c?.azimuthDeg) || !Number.isFinite(c?.elevationDeg)) {- throw new CaptureConfigError(`capture.cells[${i}] needs finite azimuthDeg and elevationDeg (got ${JSON.stringify(c)}).`);- }- if (c.zoom !== undefined && (!Number.isFinite(c.zoom) || c.zoom <= 0)) {- throw new CaptureConfigError(`capture.cells[${i}].zoom must be a positive number (got ${c.zoom}).`);- }+// src/exporter-node.ts+var exports_exporter_node = {};+__export(exports_exporter_node, {+ nodeExportPlatform: () => nodeExportPlatform+});+async function prepareNodeExport(hasTextures) {+ const host = globalThis;+ if (!host["FileReader"])+ host["FileReader"] = ExportFileReader;+ if (!hasTextures || host["OffscreenCanvas"] || host["document"])+ return;+ const { Canvas, ImageData: ImageData2 } = await import("@napi-rs/canvas").catch((cause) => {+ throw new Error("Headless textured export requires @napi-rs/canvas. Reinstall Kiln with optional dependencies enabled, then verify the native binding in the same Node runtime and platform used by the Kiln host.", { cause });+ });++ class ExportCanvas extends Canvas {+ constructor(width, height) {+ super(width, height);+ Object.defineProperty(this, "data", { value: undefined });}- if (preset === undefined) {- preset = CAPTURE_PRESETS.find((p) => PRESET_CAPACITY[p] >= cells.length);- } else if (cells.length > PRESET_CAPACITY[preset]) {- throw new CaptureConfigError(`capture.preset ${preset} holds ${PRESET_CAPACITY[preset]} cells but ${cells.length} were given. ` + `Use a larger preset or fewer cells.`);+ async convertToBlob(options = {}) {+ const type = options.type ?? options.mime ?? "image/png";+ if (type !== "image/png" && type !== "image/jpeg" && type !== "image/webp")+ throw new Error(`Unsupported export image type: ${type}`);+ const bytes = type === "image/png" ? this.toBuffer("image/png") : this.toBuffer(type);+ return new Blob([new Uint8Array(bytes)], { type });}- return {- preset,- views: cells.map((c) => ({- name: c.name?.trim().toUpperCase() || captureCellLabel(c.azimuthDeg, c.elevationDeg),- dir: orbitDir(c.azimuthDeg, c.elevationDeg)- })),- cols: PRESET_COLS[preset],- zooms: cells.map((c) => c.zoom),- isDefault: false,- backdrop- };}- const chosen = preset;- return {- preset: chosen,- views: PRESET_VIEWS[chosen],- cols: PRESET_COLS[chosen],- zooms: new Array(PRESET_VIEWS[chosen].length).fill(undefined),- isDefault: chosen === DEFAULT_CAPTURE_PRESET,- backdrop- };-}-function resolveGridCapture(config, envVariant) {- const resolved = resolveCapture(config);- if (config)- return resolved;- const views = resolveGridViews(envVariant);- return views === resolved.views ? resolved : { ...resolved, views };+ host["OffscreenCanvas"] = ExportCanvas;+ if (!host["ImageData"])+ host["ImageData"] = ImageData2;}-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(() => {- init_raster();- init_background();- CAPTURE_PRESETS = [- "1x1",- "1x2",- "2x1",- "3x1",- "2x2",- "3x2",- "3x3"- ];- PRESET_COLS = {- "1x1": 1,- "1x2": 1,- "2x1": 2,- "3x1": 3,- "2x2": 2,- "3x2": 3,- "3x3": 3- };- PRESET_CAPACITY = {- "1x1": 1,- "1x2": 2,- "2x1": 2,- "3x1": 3,- "2x2": 4,- "3x2": 6,- "3x3": 9- };- BOTTOM = { name: "BOTTOM", dir: [0, -1, 0.0001] };- THREE_QUARTER_REAR = { name: "REAR 34", dir: [-0.7, 0.5, -0.7] };- THREE_QUARTER_LOW = { name: "LOW 34", dir: [0.7, -0.35, 0.7] };- PRESET_VIEWS = {- "1x1": [SIX_VIEWS[5]],- "1x2": [SIX_VIEWS[0], SIX_VIEWS[5]],- "2x1": [SIX_VIEWS[0], SIX_VIEWS[5]],- "3x1": [SIX_VIEWS[0], SIX_VIEWS[1], SIX_VIEWS[5]],- "2x2": [SIX_VIEWS[0], SIX_VIEWS[1], SIX_VIEWS[4], SIX_VIEWS[5]],- "3x2": SIX_VIEWS,- "3x3": [...SIX_VIEWS, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW]- };- CaptureConfigError = class CaptureConfigError extends Error {++class ExportFileReader {+ result = null;+ error = null;+ onloadend = null;+ onerror = null;+ readAsArrayBuffer(blob) {+ this.read(blob, false);+ }+ readAsDataURL(blob) {+ this.read(blob, true);+ }+ read(blob, dataUrl) {+ blob.arrayBuffer().then((bytes) => {+ this.result = dataUrl ? `data:${blob.type};base64,${Buffer.from(bytes).toString("base64")}` : bytes;+ this.onloadend?.();+ }, (error) => {+ this.error = error;+ this.onerror?.();+ this.onloadend?.();+ });+ }+}+var nodeExportPlatform;+var init_exporter_node = __esm(() => {+ nodeExportPlatform = {+ prepare: prepareNodeExport,+ async decode(bytes) {+ const { default: sharp } = await import("sharp");+ const decoded = await sharp(bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ return {+ data: new Uint8Array(decoded.data),+ width: decoded.info.width,+ height: decoded.info.height+ };+ }};});-// src/views/lod.ts-function registerReviewLodChains(root, chains) {- if (chains.length > 0)- CHAINS.set(root, chains);-}-function reviewLodChains(root) {- return typeof root === "object" && root !== null ? CHAINS.get(root) ?? [] : [];-}-function drawnLevels(root) {- return reviewLodChains(root).map((chain) => {- const drawn = chain.levels.findIndex((level) => level.parent !== null);- return drawn < 0 ? 0 : drawn + 1;- });+// src/views/character.ts+import * as THREE51 from "three";+function rounded(value) {+ const result = Math.round(value * 1e9) / 1e9;+ return Object.is(result, -0) ? 0 : result;}-function swap(out, into) {- const parent = out.parent;- parent.children[parent.children.indexOf(out)] = into;- into.parent = parent;- out.parent = null;+function tuple6(vector) {+ return [rounded(vector.x), rounded(vector.y), rounded(vector.z)];}-function levelForSubject(root, subject) {- const chains = reviewLodChains(root);- if (chains.length === 0 || typeof subject !== "object" || subject === null)- return;- const byPath = typeof subject.path === "string";- if (!byPath && typeof subject.name !== "string")- return;- const subjects = listCameraSubjects(root);- if (subjects.some((entry) => byPath ? entry.path === subject.path : entry.name === subject.name))- return;- const paths = new Map(subjects.map((entry) => [entry.node, entry.path]));- const matches = [];- for (const chain of chains) {- const parent = chain.base.parent;- const parentPath = parent ? paths.get(parent) : undefined;- if (!parent || parentPath === undefined)- continue;- const before = parent.children.slice(0, parent.children.indexOf(chain.base));- chain.levels.forEach((level, index) => {- const occurrence = before.filter((sibling) => sibling.name === level.name).length;- const own = `/${encodeURIComponent(level.name)}[0]`;- const at = `${parentPath}/${encodeURIComponent(level.name)}[${occurrence}]`;- for (const entry of listCameraSubjects(level)) {- const path = at + entry.path.slice(own.length);- if (byPath ? path === subject.path : entry.name === subject.name)- matches.push({ chain, level: index + 1, path });- }- });+function chainIdFor(descriptor, byRole) {+ if (AXIAL_ROLES.has(descriptor.role))+ return "axial";+ let current = descriptor;+ const seen = new Set([current.role]);+ while (current.parentRole && !AXIAL_ROLES.has(current.parentRole)) {+ const parent = byRole.get(current.parentRole);+ if (!parent || seen.has(parent.role))+ break;+ seen.add(parent.role);+ current = parent;}- if (matches.length > 1)- throw new Error(`ambiguous camera subject: ${matches.length} nodes in lower levels of detail match ${JSON.stringify(subject.path ?? subject.name)}; choose one path: ${matches.map((match) => match.path).join(", ")}`);- return matches[0];+ return current.role;}-async function withSubjectLevel(root, subject, run) {- const scene = root;- const match = levelForSubject(scene, subject);- if (!match)- return run(drawnLevels(root));- const level = match.chain.levels[match.level - 1];- swap(match.chain.base, level);- scene.updateMatrixWorld(true);- try {- return await run(drawnLevels(root));- } finally {- swap(level, match.chain.base);- scene.updateMatrixWorld(true);+function colorFor(value) {+ let hash = 2166136261;+ for (let index = 0;index < value.length; index++) {+ hash ^= value.charCodeAt(index);+ hash = Math.imul(hash, 16777619);}+ return CHAIN_COLORS[Math.abs(hash) % CHAIN_COLORS.length];}-var CHAINS;-var init_lod3 = __esm(() => {- init_camera();- CHAINS = new WeakMap;-});--// src/views/camera-capture.ts-function validateAdvancedCapture(config) {- for (const key of Object.keys(config))- if (!["version", "shots", "cols", "size", "output", "backdrop"].includes(key))- throw new Error(`capture.${key} is unknown or incompatible with shots`);- if (config.version !== "kiln.capture.v1" && config.version !== "kiln.capture.v2")- throw new Error("advanced capture requires version kiln.capture.v1 or kiln.capture.v2");- if (!Array.isArray(config.shots) || config.shots.length < 1 || config.shots.length > 9)- throw new Error("capture.shots must contain 1..9 shots");- if (config.version !== "kiln.capture.v2" && config.shots.some((shot) => shot.hide !== undefined))- throw new Error("shot.hide requires version kiln.capture.v2");- if (config.cols !== undefined && (!Number.isInteger(config.cols) || config.cols < 1 || config.cols > 3))- throw new Error("capture.cols must be 1..3");- if (config.size !== undefined && (!Number.isInteger(config.size) || config.size < 128 || config.size > MAX_CAPTURE_SHOT_SIZE))- throw new Error(`capture.size must be 128..${MAX_CAPTURE_SHOT_SIZE}`);- if (config.output !== undefined && !["grid", "separate"].includes(config.output))- throw new Error("capture.output must be grid or separate");- resolveCaptureBackdrop(config.backdrop);+function buildCharacterDiagnosticDescriptor(root, findings = []) {+ root.updateMatrixWorld(true);+ 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((finding) => finding.code === "CHAR_PARENT_EDGE").map((finding) => finding.affected?.nodePath).filter((path) => Boolean(path)))+ ].sort();+ const invalidPaths = new Set(invalidFindingNodePaths);+ const joints = evidence.map((joint) => {+ const relative = rootInverse.clone().multiply(joint.node.matrixWorld);+ const position = new THREE51.Vector3().setFromMatrixPosition(relative);+ const forward = new THREE51.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE51.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const chainId = chainIdFor(joint.descriptor, descriptorByRole);+ return {+ role: joint.descriptor.role,+ aliases: [...joint.descriptor.aliases],+ side: joint.descriptor.side,+ nodeName: joint.node.name,+ nodePath: joint.nodePath,+ label: joint.descriptor.role,+ chainId,+ color: colorFor(chainId),+ assetPosition: tuple6(position),+ forwardAxisEnd: tuple6(forward),+ bendAxisEnd: tuple6(bend),+ endEffector: joint.descriptor.endEffector,+ contact: joint.descriptor.contact+ };+ });+ 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);+ return {+ parentRole,+ childRole: joint.descriptor.role,+ ...parent ? { parentNodePath: parent.nodePath } : {},+ childNodePath: joint.nodePath,+ valid: Boolean(parent) && !invalidPaths.has(joint.nodePath),+ color: colorFor(chainId)+ };+ }).sort((a, b) => `${a.parentRole}:${a.childRole}`.localeCompare(`${b.parentRole}:${b.childRole}`));+ return {+ schemaVersion: 1,+ joints,+ edges,+ contacts: joints.filter((joint) => joint.contact).map((joint) => ({+ role: joint.role,+ nodePath: joint.nodePath,+ assetPosition: joint.assetPosition+ })),+ canonicalForwardArrow: { start: [0, 0, 0], end: [1, 0, 0], label: "+X forward" },+ invalidFindingNodePaths+ };}-async function renderCaptureGrid(root, config, render, limits) {- validateAdvancedCapture(config);- const plans = [];- for (const request of config.shots)- plans.push(await withSubjectLevel(root, request.subject, async (levels) => ({- subject: request.subject,- shot: resolveAssetCamera(root, request),- levels- })));- const shots = plans.map((plan) => plan.shot);- const size = config.size ?? 384;- const cols = config.cols ?? Math.min(3, shots.length);- const backdrop = resolveCaptureBackdrop(config.backdrop);- enforceCapturePixels(shots.length, size, cols, limits);- const cells = [];- const perFramePngs = [];- const derivativeReceipts = [];- for (const { subject, shot } of plans) {- const dir = shot.camera.position.map((n, i) => n - shot.camera.target[i]);- const view = { name: shot.name, dir };- const png = await withSubjectLevel(root, subject, () => withCameraVisibility(root, shot, async () => {- if (render) {- const result = await render({- root,- label: shot.name,- view,- size,- camera: shot.camera,- backdrop- });- derivativeReceipts.push(result.receipt);- return result.png;- }- return encodePng(rasterizeCamera(root, shot.camera, size, true, backdrop), size, size);- }));- 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));+function safeClipId(name) {+ return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");+}+function planCharacterDiagnosticRequests(requirements) {+ const requests = [+ diagnosticRequest({+ id: "character.skeleton.front",+ label: "Character skeleton front",+ cameraId: "front",+ buffer: "semantic-overlay",+ variant: "character-skeleton",+ focusRolePrefixes: ["skeleton.", "joint.", "contact."],+ automatic: true+ }),+ diagnosticRequest({+ id: "character.skeleton.right",+ label: "Character skeleton right",+ cameraId: "right",+ buffer: "semantic-overlay",+ variant: "character-skeleton",+ focusRolePrefixes: ["skeleton.", "joint.", "contact."],+ automatic: true+ })+ ];+ const locomotion = (requirements.clips ?? []).find((clip) => clip.playback === "loop" && new RegExp(requirements.locomotion === "stationary" ? "idle" : requirements.locomotion ?? "", "i").test(clip.name)) ?? (requirements.clips ?? []).find((clip) => clip.playback === "loop");+ const action = (requirements.clips ?? []).find((clip) => clip.playback === "oneShot");+ const selected = [locomotion, action].filter((clip, index, values) => Boolean(clip) && values.findIndex((candidate) => candidate?.name === clip?.name) === index);+ for (const clip of selected) {+ for (const cameraId of ["front", "right"]) {+ requests.push(diagnosticRequest({+ id: `character.motion-strip.${cameraId}.${safeClipId(clip.name)}`,+ label: `${clip.name} fixed-phase ${cameraId} strip`,+ cameraId,+ buffer: "silhouette-unlit",+ variant: "character-motion-strip",+ clipName: clip.name,+ phaseFractions: CHARACTER_MOTION_DIAGNOSTIC_PHASES,+ focusRolePrefixes: ["skeleton.", "joint.", "limb.", "held-item"],+ automatic: true+ }));+ }}- const { rgb, width, height } = compositeCellGrid(cells, size, cols);- const png = encodePng(rgb, width, height);- enforceCaptureBytes(config.output === "separate" ? perFramePngs : [png], limits);- return {- png,- width,- height,- views: shots.map((s) => s.name),- capture: {- preset: `${cols}x${Math.ceil(shots.length / cols)}`,- cols,- cells: shots.length,- backdrop,- output: config.output ?? "grid"- },- cameraShots: shots,- perFramePngs,- derivativeReceipts,- ...reviewLodChains(root).length ? { viewLevels: plans.map((plan) => plan.levels) } : {},- ...derivativeReceipts.length ? {- captureCache: {- hit: derivativeReceipts.every((r) => r.captureCache?.hit),- reused: derivativeReceipts.filter((r) => r.captureCache?.hit).length,- total: derivativeReceipts.length- }- } : {}- };+ return Object.freeze(requests);}-var init_camera_capture = __esm(() => {- init_capture_limits();- init_camera();- init_capture();- init_png();- init_grid();- init_annotate();- init_lod3();+var CHAIN_COLORS, AXIAL_ROLES, CHARACTER_MOTION_DIAGNOSTIC_PHASES, diagnosticRequest = (value) => Object.freeze({+ ...value,+ focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]),+ ...value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}+});+var init_character3 = __esm(() => {+ init_character();+ CHAIN_COLORS = Object.freeze([+ "#4fc3f7",+ "#ff8a65",+ "#81c784",+ "#ba68c8",+ "#ffd54f",+ "#4db6ac",+ "#f06292",+ "#90a4ae"+ ]);+ AXIAL_ROLES = new Set(["root", "hips", "spine", "neck", "head"]);+ CHARACTER_MOTION_DIAGNOSTIC_PHASES = Object.freeze([0, 0.2, 0.4, 0.6, 0.8, 1]);});-// src/views/architecture.ts-function nodeRoles(node) {- return readSemanticMetadataV1FromExtras(node.userData ?? {})?.roles ?? [];-}-function hasArchitectureRoofRole(node) {- return nodeRoles(node).some((role) => ARCHITECTURE_ROOF_ROLE_PREFIXES.some((prefix) => role.startsWith(prefix)));+// src/views/diagnostic.ts+function multiplyMatrices(a, b) {+ const out = new Float64Array(16);+ for (let column = 0;column < 4; column++) {+ for (let row = 0;row < 4; row++) {+ let value = 0;+ for (let k = 0;k < 4; k++)+ value += a[k * 4 + row] * b[column * 4 + k];+ out[column * 4 + row] = value;+ }+ }+ return out;}-function legacyRoofName(name) {- if (!name)- return false;- return /^roof(?:$|[_. -]|(?:slope|panel|gable|ridge)|[ab](?:$|[_. -]))/i.test(name.trim());+function composeLocalMatrix(node) {+ if (node.matrixAutoUpdate === false && node.matrix?.elements) {+ return new Float64Array(Array.from(node.matrix.elements));+ }+ const p = node.position;+ const q = node.quaternion;+ const s = node.scale;+ if (!p || !q || !s) {+ return node.matrix?.elements ? new Float64Array(Array.from(node.matrix.elements)) : new Float64Array(IDENTITY);+ }+ const x2 = q.x + q.x;+ const y2 = q.y + q.y;+ const z2 = q.z + q.z;+ const xx = q.x * x2;+ const xy = q.x * y2;+ const xz = q.x * z2;+ const yy = q.y * y2;+ const yz = q.y * z2;+ const zz = q.z * z2;+ const wx = q.w * x2;+ const wy = q.w * y2;+ const wz = q.w * z2;+ return new Float64Array([+ (1 - (yy + zz)) * s.x,+ (xy + wz) * s.x,+ (xz - wy) * s.x,+ 0,+ (xy - wz) * s.y,+ (1 - (xx + zz)) * s.y,+ (yz + wx) * s.y,+ 0,+ (xz + wy) * s.z,+ (yz - wx) * s.z,+ (1 - (xx + yy)) * s.z,+ 0,+ p.x,+ p.y,+ p.z,+ 1+ ]);}-function minimalMatches(root, predicate) {- const matches = [];- const visit = (node, ancestorMatched) => {- const matched = predicate(node);- if (matched && !ancestorMatched)- matches.push(node);- for (const child of node.children ?? [])- visit(child, ancestorMatched || matched);- };- visit(root, false);- return matches;+function transformPoint2(matrix, x, y, z) {+ return [+ 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 selectArchitectureRoofNodes(root) {- const candidate = root;- 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: [] };+function matchesRole(roles, prefixes) {+ return Boolean(prefixes?.some((prefix) => roles.some((role) => role.startsWith(prefix))));}-function setSubtreeVisibility(node, visible) {- node.visible = visible;- for (const child of node.children ?? [])- setSubtreeVisibility(child, visible);+function semanticRoles2(node) {+ const metadata = readSemanticMetadataV1FromExtras(node.userData ?? {});+ if (metadata)+ return metadata.roles;+ const geometryRole = node.geometry?.userData?.["kilnGeometryRole"];+ return typeof geometryRole === "string" ? [geometryRole] : [];}-function hideArchitectureRoofInScene(root) {- const selection = selectArchitectureRoofNodes(root);- for (const node of selection.nodes)- setSubtreeVisibility(node, false);- return selection;+function clamp012(value) {+ return value < 0 ? 0 : value > 1 ? 1 : value;}-var ARCHITECTURE_ROOF_ROLE_PREFIXES;-var init_architecture3 = __esm(() => {- init_contracts();- ARCHITECTURE_ROOF_ROLE_PREFIXES = Object.freeze([- `${KILN_SEMANTIC_ROLES.roof}.`,- `${KILN_SEMANTIC_ROLES.architectureRoof}.`- ]);-});--// src/views/glb.ts-import {- Primitive as Primitive2-} from "@gltf-transform/core";-import {- BufferAttribute as BufferAttribute12,- BufferGeometry as BufferGeometry15,- Group as Group5,- Matrix4 as Matrix417,- Mesh as Mesh14,- Bone as Bone2,- SkinnedMesh as SkinnedMesh2,- Skeleton as Skeleton3,- MeshStandardMaterial as MeshStandardMaterial5,- NoColorSpace as NoColorSpace5,- SRGBColorSpace as SRGBColorSpace6,- Texture as Texture4,- AnimationClip as AnimationClip4,- QuaternionKeyframeTrack as QuaternionKeyframeTrack2,- NumberKeyframeTrack,- PropertyBinding as PropertyBinding3,- VectorKeyframeTrack as VectorKeyframeTrack2,- Quaternion as Quaternion19,- Vector3 as Vector339,- InterpolateDiscrete as InterpolateDiscrete2,- InterpolateLinear as InterpolateLinear2-} from "three";-function record9(value) {- return typeof value === "object" && value !== null && !Array.isArray(value);+function collectScene(root, requestValue) {+ const triangles = [];+ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];+ const focusMin = [Infinity, Infinity, Infinity];+ const focusMax = [-Infinity, -Infinity, -Infinity];+ const visit = (node, parentMatrix, parentPath, siblingIndex, ancestorVisible, inheritedRoles) => {+ const local = composeLocalMatrix(node);+ const world = multiplyMatrices(parentMatrix, local);+ const visible = ancestorVisible && node.visible !== false;+ const segment = `${node.name?.trim() || node.type || "Node"}[${siblingIndex}]`;+ 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];+ if (material?.visible !== false) {+ const position = node.geometry.getAttribute?.("position");+ if (position?.itemSize === 3) {+ const worldPositions = [];+ 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 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)))) {+ return;+ }+ const vertices = new Float64Array(9);+ points.forEach((point, pointIndex) => {+ for (let axis = 0;axis < 3; axis++) {+ const value = point[axis];+ vertices[pointIndex * 3 + axis] = value;+ min[axis] = Math.min(min[axis], value);+ max[axis] = Math.max(max[axis], value);+ if (focused) {+ focusMin[axis] = Math.min(focusMin[axis], value);+ focusMax[axis] = Math.max(focusMax[axis], value);+ }+ }+ });+ triangles.push({+ vertices,+ color,+ nodeName: node.name ?? "",+ nodePath,+ semanticRoles: roles+ });+ };+ const index = node.geometry.index;+ if (index) {+ for (let i = 0;i + 2 < index.count; i += 3) {+ addTriangle(index.array[i], index.array[i + 1], index.array[i + 2]);+ }+ } else {+ for (let i = 0;i + 2 < position.count; i += 3)+ addTriangle(i, i + 1, i + 2);+ }+ }+ }+ }+ (node.children ?? []).forEach((child, index) => {+ visit(child, world, nodePath, index, visible && !omitted, roles);+ });+ };+ visit(root, IDENTITY, "", 0, true, []);+ const empty = !Number.isFinite(min[0]);+ const focusEmpty = !Number.isFinite(focusMin[0]);+ return {+ triangles,+ bounds: empty ? { min: [0, 0, 0], max: [0, 0, 0] } : { min, max },+ ...!focusEmpty ? { focusBounds: { min: focusMin, max: focusMax } } : {}+ };}-function withLoopIntent(clip, intent) {- if (intent === "loop" || intent === "once")- clip.userData.kilnLoopIntent = intent;- return clip;+function normalize4(vector) {+ const length = Math.hypot(...vector) || 1;+ return [vector[0] / length, vector[1] / length, vector[2] / length];}-function reviewClipsFromExtras(extras) {- if (!record9(extras))- return;- const envelope = extras[REVIEW_CLIPS_EXTRAS_KEY];- if (!record9(envelope) || envelope.version !== 1 && envelope.version !== 2 || !Array.isArray(envelope.clips)) {- return;+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]];+}+function dot4(a, b) {+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+}+function stableColor(key) {+ let hash = 2166136261;+ for (let index = 0;index < key.length; index++) {+ hash ^= key.charCodeAt(index);+ hash = Math.imul(hash, 16777619);}- const cubicAllowed = envelope.version === 2;- if (envelope.clips.length > REVIEW_CLIP_LIMITS.clips) {- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Animation review clip limit exceeded.");+ return [96 + (hash & 127), 96 + (hash >>> 8 & 127), 96 + (hash >>> 16 & 127)];+}+function projectScene(scene, camera, size) {+ const zAxis = normalize4(camera.dir);+ const upHint = Math.abs(zAxis[1]) > 0.99 ? [0, 0, -1] : [0, 1, 0];+ const xAxis = normalize4(cross3(upHint, zAxis));+ const yAxis = cross3(zAxis, xAxis);+ const frame = scene.focusBounds ?? scene.bounds;+ const center = [+ (frame.min[0] + frame.max[0]) / 2,+ (frame.min[1] + frame.max[1]) / 2,+ (frame.min[2] + frame.max[2]) / 2+ ];+ 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]+ ];+ extent = Math.max(extent, Math.abs(dot4(point, xAxis)), Math.abs(dot4(point, yAxis)));}- let trackCount = 0;- return envelope.clips.map((candidate) => {- if (!record9(candidate) || typeof candidate.name !== "string" || candidate.name.length > 256 || typeof candidate.duration !== "number" || !Number.isFinite(candidate.duration) || candidate.duration < 0 || !Array.isArray(candidate.tracks)) {- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review clip.");+ 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 length = Math.hypot(...normalRaw);+ if (length < 0.000000000001)+ return [];+ const normal = normalRaw.map((component) => component / length);+ const xs = [];+ const ys = [];+ const zs = [];+ const worldY = [];+ for (let index = 0;index < 3; index++) {+ const point = [+ v[index * 3] - center[0],+ v[index * 3 + 1] - center[1],+ v[index * 3 + 2] - center[2]+ ];+ 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]);}- const tracks = candidate.tracks.map((track) => {- trackCount++;- if (trackCount > REVIEW_CLIP_LIMITS.tracks || !record9(track) || typeof track.name !== "string" || track.name.length > 512 || !Array.isArray(track.times) || !Array.isArray(track.values) || track.interpolation !== undefined && track.interpolation !== "LINEAR" && track.interpolation !== "STEP" && !(cubicAllowed && track.interpolation === "CUBICSPLINE") || track.times.length > REVIEW_CLIP_LIMITS.samplesPerTrack || track.values.length > REVIEW_CLIP_LIMITS.valuesPerTrack || !track.times.every((value) => typeof value === "number" && Number.isFinite(value)) || !track.values.every((value) => typeof value === "number" && Number.isFinite(value))) {- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review track.");- }- const property = track.name.slice(track.name.lastIndexOf(".") + 1);- const morph = /^morphTargetInfluences(?:\[[^\]]+\])?$/.test(property);- const Track = morph ? NumberKeyframeTrack : property === "quaternion" ? QuaternionKeyframeTrack2 : VectorKeyframeTrack2;- if (track.interpolation === "CUBICSPLINE") {- const tuple = morph ? track.values.length / track.times.length : cubicTuple(property);- if (track.times.length < 2 || track.values.length !== track.times.length * tuple || !Number.isInteger(tuple / 3) || tuple < 3) {- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review track.");- }- return useCubicSpline(new Track(track.name, track.times, track.values));+ return [+ {+ source: triangle,+ x: xs,+ y: ys,+ z: zs,+ worldY,+ normal,+ frontFacing: dot4(normal, zAxis) > 0}- return new Track(track.name, track.times, track.values, track.interpolation === "STEP" ? InterpolateDiscrete2 : InterpolateLinear2);- });- return withLoopIntent(new AnimationClip4(candidate.name, candidate.duration, tracks), candidate.loopIntent);+ ];});}-function geometryFlatTextureReasonCode(mimeType) {- return mimeType === "image/ktx2" ? GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED : GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED;-}-function decodedAccessor(accessor) {- const itemSize = accessor.getElementSize();- const output = new Float64Array(accessor.getCount() * itemSize);- const element = [];- for (let index = 0;index < accessor.getCount(); index++) {- accessor.getElement(index, element);- for (let component = 0;component < itemSize; component++) {- output[index * itemSize + component] = element[component];+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]);+ const y1 = Math.round(to[1]);+ const dx = Math.abs(x1 - x0);+ const sx = x0 < x1 ? 1 : -1;+ const dy = -Math.abs(y1 - y0);+ const sy = y0 < y1 ? 1 : -1;+ let error = dx + dy;+ while (true) {+ if (x0 >= 0 && x0 < size && y0 >= 0 && y0 < size) {+ const offset = (y0 * size + x0) * 3;+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}- }- return output;-}-function triangleIndices(primitive, vertexCount) {- const sourceAccessor = primitive.getIndices();- const source = sourceAccessor ? Array.from(decodedAccessor(sourceAccessor), (value) => Math.trunc(value)) : Array.from({ length: vertexCount }, (_, index) => index);- switch (primitive.getMode()) {- case Primitive2.Mode.TRIANGLES:- return Uint32Array.from(source);- case Primitive2.Mode.TRIANGLE_STRIP: {- const triangles = [];- for (let index = 0;index + 2 < source.length; index++) {- triangles.push(source[index], source[index + 1 + index % 2], source[index + 2 - index % 2]);- }- return Uint32Array.from(triangles);+ if (x0 === x1 && y0 === y1)+ break;+ const doubled = 2 * error;+ if (doubled >= dy) {+ error += dy;+ x0 += sx;}- case Primitive2.Mode.TRIANGLE_FAN: {- const triangles = [];- for (let index = 1;index + 1 < source.length; index++) {- triangles.push(source[index], source[index + 1], source[0]);- }- return Uint32Array.from(triangles);+ if (doubled <= dx) {+ error += dx;+ y0 += sy;}- default:- return;}}-function flatMaterial(material) {- if (!material) {- return {- color: { r: 0.7, g: 0.7, b: 0.7 },- opacity: 1,- doubleSided: false,- metalness: 0,- roughness: 1,- alphaMode: "OPAQUE",- alphaCutoff: 0.5,- emissive: [0, 0, 0],- emissiveIntensity: 1- };- }- const [r, g, b, factorAlpha] = material.getBaseColorFactor();- 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,- alphaCutoff: material.getAlphaCutoff(),- emissive: material.getEmissiveFactor(),- emissiveIntensity: material.getExtension("KHR_materials_emissive_strength")?.getEmissiveStrength() ?? 1- };-}-function preserveTexture(source, usage, cache, info, atlas) {- if (!source)- return null;- const encoded = source.getImage();- const mime = source.getMimeType();- if (!encoded || !mime)- return null;- let byUsage = cache.get(source);- if (!byUsage) {- byUsage = new Map;- cache.set(source, byUsage);- }- const reference = info?.getExtras()["kilnAtlasReference"];- const cacheKey = `${usage}:${gltfTextureBindingKey(info)}`;- const existing = byUsage.get(cacheKey);- if (existing)- return existing;- const texture = new Texture4;- texture.name = source.getName();- texture.colorSpace = usage === "color" ? SRGBColorSpace6 : NoColorSpace5;- texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };- texture.flipY = false;- if (info)- restoreGltfTextureBinding(texture, info);- if (reference && info && atlas)- restoreAtlasTextureProvenance(texture, info, atlas);- byUsage.set(cacheKey, texture);- return texture;-}-function noteMaterialTextures(material, reasons) {- if (!material)- return;- const textures = [- material.getBaseColorTexture(),- material.getNormalTexture(),- material.getMetallicRoughnessTexture(),- material.getEmissiveTexture(),- material.getOcclusionTexture()- ];- for (const texture of textures) {- if (texture)- reasons.add(geometryFlatTextureReasonCode(texture.getMimeType()));- }-}-function instanceMatrices(node) {- const world = new Matrix417().fromArray(node.getWorldMatrix());- const extension = node.getExtension("EXT_mesh_gpu_instancing");- if (!extension)- return { matrices: [world], count: 1 };- const attributes = extension.listAttributes();- if (attributes.length === 0) {- throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", `Node ${JSON.stringify(node.getName())} has EXT_mesh_gpu_instancing with no attributes.`);- }- const count = attributes[0].getCount();- if (attributes.some((attribute) => attribute.getCount() !== count)) {- throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", `Node ${JSON.stringify(node.getName())} has mismatched EXT_mesh_gpu_instancing counts.`);- }- const translations = extension.getAttribute("TRANSLATION");- const rotations = extension.getAttribute("ROTATION");- const scales = extension.getAttribute("SCALE");- const translation = [];- const rotation = [];- const scale = [];- const matrices = [];- for (let index = 0;index < count; index++) {- translations?.getElement(index, translation);- rotations?.getElement(index, rotation);- scales?.getElement(index, scale);- const local = new Matrix417().compose(new Vector339(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion19(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector339(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));- matrices.push(world.clone().multiply(local));- }- return { matrices, count };+function drawRegionBox(rgb, size, region) {+ const [minX, minY, maxX, maxY] = region.pixelBounds;+ 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);}-async function loadGlbGeometryFlatScene(bytes) {- let document;- try {- document = await glbIO().readBinary(Uint8Array.from(bytes));- } catch (error) {- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Could not parse final GLB bytes: ${error instanceof Error ? error.message : String(error)}`);- }- await validateAtlasDocumentProvenance(document);- const scene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];- if (!scene)- throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");- const reasons = new Set;- const meshes = [];- let instanceCount = 0;- const sceneNodes = new Set;- const visit = (node) => {- if (sceneNodes.has(node) || isHiddenGltfNode(node))- return;- sceneNodes.add(node);- for (const child of node.listChildren())- visit(child);- };- for (const child of scene.listChildren())- visit(child);- if ([...sceneNodes].some((node) => node.getSkin() || node.getMesh()?.listPrimitives().some((p) => p.listTargets().length))) {- await validateAtlasDocumentProvenance(document);- return reviewSceneFromDocument(document);+function renderDiagnosticView(root, requestValue, options = {}) {+ const camera = cameraById.get(requestValue.cameraId);+ if (!camera)+ throw new TypeError(`Unknown diagnostic camera ${JSON.stringify(requestValue.cameraId)}.`);+ const size = Math.max(16, Math.min(1024, Math.round(options.size ?? 256)));+ const groundY = options.groundY ?? 0;+ const scene = collectScene(root, requestValue);+ const triangles = projectScene(scene, camera, size);+ const background = [18, 20, 24];+ const rgb = new Uint8Array(size * size * 3);+ for (let pixel = 0;pixel < size * size; pixel++) {+ rgb[pixel * 3] = background[0];+ rgb[pixel * 3 + 1] = background[1];+ rgb[pixel * 3 + 2] = background[2];}- for (const node of sceneNodes) {- const mesh = node.getMesh();- if (!mesh)+ const depth = new Float64Array(size * size).fill(-Infinity);+ const depths = triangles.flatMap((triangle) => triangle.z);+ const minDepth = depths.length > 0 ? Math.min(...depths) : 0;+ const maxDepth = depths.length > 0 ? Math.max(...depths) : 1;+ const depthRange = Math.max(0.000000001, maxDepth - minDepth);+ const contactTolerance = Math.max(0.0001, (scene.bounds.max[1] - scene.bounds.min[1]) * 0.015);+ const regionMap = new Map;+ for (const triangle of triangles) {+ const minX = Math.max(0, Math.floor(Math.min(...triangle.x)));+ const maxX = Math.min(size - 1, Math.ceil(Math.max(...triangle.x)));+ const minY = Math.max(0, Math.floor(Math.min(...triangle.y)));+ const maxY = Math.min(size - 1, Math.ceil(Math.max(...triangle.y)));+ if (minX > maxX || minY > maxY)continue;- const instances = instanceMatrices(node);- instanceCount += instances.count;- for (const primitive of mesh.listPrimitives()) {- const positionAccessor = primitive.getAttribute("POSITION");- if (positionAccessor?.getElementSize() !== 3)- continue;- const positions = decodedAccessor(positionAccessor);- const indices = triangleIndices(primitive, positionAccessor.getCount());- if (!indices) {- reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);- continue;+ const key = triangle.source.semanticRoles.at(-1) ?? triangle.source.nodePath;+ const regionColor = stableColor(key);+ const existing = regionMap.get(triangle.source.nodePath);+ if (existing) {+ existing.pixelBounds[0] = Math.min(existing.pixelBounds[0], minX);+ existing.pixelBounds[1] = Math.min(existing.pixelBounds[1], minY);+ existing.pixelBounds[2] = Math.max(existing.pixelBounds[2], maxX);+ existing.pixelBounds[3] = Math.max(existing.pixelBounds[3], maxY);+ existing.triangleCount++;+ } else {+ regionMap.set(triangle.source.nodePath, {+ nodeName: triangle.source.nodeName,+ nodePath: triangle.source.nodePath,+ semanticRoles: [...triangle.source.semanticRoles],+ pixelBounds: [minX, minY, maxX, maxY],+ color: regionColor,+ triangleCount: 1+ });+ }+ if (requestValue.buffer === "wireframe")+ continue;+ const ax = triangle.x[0];+ const ay = triangle.y[0];+ const bx = triangle.x[1];+ const by = triangle.y[1];+ const cx = triangle.x[2];+ const cy = triangle.y[2];+ const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);+ if (Math.abs(area) < 0.000000001)+ continue;+ const inverseArea = 1 / area;+ for (let py = minY;py <= maxY; py++) {+ for (let px = minX;px <= maxX; px++) {+ const sampleX = px + 0.5;+ const sampleY = py + 0.5;+ const w0 = ((bx - ax) * (sampleY - ay) - (by - ay) * (sampleX - ax)) * inverseArea;+ const w1 = ((cx - bx) * (sampleY - by) - (cy - by) * (sampleX - bx)) * inverseArea;+ const w2 = 1 - w0 - w1;+ if (w0 < 0 || w1 < 0 || w2 < 0)+ continue;+ const pixelDepth = w1 * triangle.z[0] + w2 * triangle.z[1] + w0 * triangle.z[2];+ const pixel = py * size + px;+ if (pixelDepth <= depth[pixel])+ continue;+ depth[pixel] = pixelDepth;+ const offset = pixel * 3;+ let color;+ if (requestValue.variant === "material-grazing-light") {+ const grazingDirection = normalize4([0.25, 0.08, 1]);+ const light = 0.08 + 0.92 * Math.max(0, dot4(triangle.normal, grazingDirection));+ color = triangle.source.color.map((value) => Math.round(clamp012(value * light) * 255));+ } else if (requestValue.buffer === "silhouette-unlit") {+ color = [235, 238, 242];+ } else if (requestValue.buffer === "normals-backface") {+ 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)+ color = [58, 220, 126];+ else if (worldY < groundY - contactTolerance)+ color = [245, 94, 72];+ else {+ const value = Math.round(48 + 190 * ((pixelDepth - minDepth) / depthRange));+ color = [value, value, value];+ }+ } else {+ color = regionColor;+ }+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}- const material = primitive.getMaterial();- noteMaterialTextures(material, reasons);- const geometry = {- getAttribute(name) {- return name === "position" ? { array: positions, itemSize: 3, count: positionAccessor.getCount() } : undefined;- },- index: { array: indices, itemSize: 1, count: indices.length }- };- for (const matrix of instances.matrices) {- meshes.push({- isMesh: true,- visible: true,- geometry,- material: flatMaterial(material),- matrixWorld: { elements: [...matrix.elements] }- });+ }+ }+ if (requestValue.buffer === "wireframe") {+ for (const triangle of triangles) {+ const color = triangle.frontFacing ? [225, 235, 245] : [230, 72, 84];+ for (const [a, b] of [+ [0, 1],+ [1, 2],+ [2, 0]+ ]) {+ drawLine(rgb, size, [triangle.x[a], triangle.y[a]], [triangle.x[b], triangle.y[b]], color);}}}- if (meshes.length === 0) {- throw new GlbGeometryFlatError("GLB_FLAT_NO_RENDERABLE_GEOMETRY", "Final GLB contains no triangle geometry supported by the CPU fallback.");+ const regions = [...regionMap.values()].sort((a, b) => a.nodePath.localeCompare(b.nodePath));+ if (requestValue.buffer === "semantic-overlay") {+ for (const region of regions)+ drawRegionBox(rgb, size, region);}- const root = {- updateMatrixWorld() {},- traverse(callback) {- for (const mesh of meshes)- callback(mesh);- }- };return {- root,- reasonCodes: REASON_ORDER.filter((reason) => reasons.has(reason)),- meshCount: meshes.length,- instanceCount+ id: requestValue.id,+ label: requestValue.label,+ camera,+ buffer: requestValue.buffer,+ ...requestValue.variant ? { variant: requestValue.variant } : {},+ width: size,+ height: size,+ rgb,+ png: encodePng(rgb, size, size),+ regions,+ ...requestValue.phaseFractions ? { phaseFractions: requestValue.phaseFractions } : {}};}-function localInstanceMatrices(node) {- const extension = node.getExtension("EXT_mesh_gpu_instancing");- if (!extension)- return [new Matrix417];- const attributes = extension.listAttributes();- if (attributes.length === 0) {- throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Invalid empty instancing data.");- }- const count = attributes[0].getCount();- if (attributes.some((attribute) => attribute.getCount() !== count)) {- throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Mismatched instancing data.");- }- const translations = extension.getAttribute("TRANSLATION");- const rotations = extension.getAttribute("ROTATION");- const scales = extension.getAttribute("SCALE");- const translation = [];- const rotation = [];- const scale = [];- return Array.from({ length: count }, (_, index) => {- translations?.getElement(index, translation);- rotations?.getElement(index, rotation);- scales?.getElement(index, scale);- return new Matrix417().compose(new Vector339(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion19(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector339(...scales ? scale.slice(0, 3) : [1, 1, 1]));+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]) } : {},+ ...value.focusRolePrefixes ? { focusRolePrefixes: Object.freeze([...value.focusRolePrefixes]) } : {},+ ...value.phaseFractions ? { phaseFractions: Object.freeze([...value.phaseFractions]) } : {}+}), GENERIC_DIAGNOSTIC_REQUESTS, CATEGORY_REQUESTS, MOBILITY_DIAGNOSTIC_REQUESTS, MATERIAL_GRAZING_REQUEST, IDENTITY;+var init_diagnostic = __esm(() => {+ init_contracts();+ init_character3();+ init_png();+ GENERIC_DIAGNOSTIC_BUFFER_IDS = [+ "silhouette-unlit",+ "wireframe",+ "normals-backface",+ "depth-contact",+ "semantic-overlay"+ ];+ GENERIC_DIAGNOSTIC_CAMERAS = Object.freeze([+ frozenCamera("front", "Front", [1, 0, 0]),+ frozenCamera("right", "Right", [0, 0, 1]),+ frozenCamera("back", "Back", [-1, 0, 0]),+ frozenCamera("left", "Left", [0, 0, -1]),+ frozenCamera("top", "Top", [0, 1, 0.0001]),+ frozenCamera("three-quarter", "3/4", [0.7, 0.5, 0.7])+ ]);+ EXTRA_CAMERAS = Object.freeze({+ underside: frozenCamera("underside", "Canopy underside", [0.15, -0.85, 0.5]),+ grazing: frozenCamera("grazing", "Material grazing light", [0.08, 0.12, 1])+ });+ cameraById = new Map([...GENERIC_DIAGNOSTIC_CAMERAS, ...Object.values(EXTRA_CAMERAS)].map((camera) => [+ camera.id,+ camera+ ]));+ GENERIC_DIAGNOSTIC_REQUESTS = Object.freeze(GENERIC_DIAGNOSTIC_CAMERAS.flatMap((camera) => GENERIC_DIAGNOSTIC_BUFFER_IDS.map((buffer) => request({+ id: `generic.${camera.id}.${buffer}`,+ label: `${camera.name} ${buffer}`,+ cameraId: camera.id,+ buffer,+ scope: "generic"+ }))));+ CATEGORY_REQUESTS = Object.freeze({+ prop: Object.freeze([]),+ vfx: Object.freeze([]),+ environment: Object.freeze([]),+ architecture: Object.freeze([]),+ character: Object.freeze([]),+ vehicle: Object.freeze([+ request({+ id: "vehicle.underbody",+ label: "Vehicle underbody and support plane",+ cameraId: "underside",+ buffer: "semantic-overlay",+ scope: "category",+ variant: "vehicle-underbody",+ focusRolePrefixes: [+ "chassis.",+ "wheel.",+ "axle.",+ "support.",+ "contact.",+ "diagnostic.vehicle."+ ]+ }),+ request({+ id: "vehicle.wheel-section.right",+ label: "Vehicle wheel section",+ cameraId: "right",+ buffer: "semantic-overlay",+ scope: "category",+ variant: "vehicle-wheel-section",+ focusRolePrefixes: ["wheel.", "axle.", "hub.", "tire."]+ })+ ]),+ vegetation: Object.freeze([+ request({+ id: "vegetation.canopy-underside",+ label: "Vegetation canopy underside",+ cameraId: "underside",+ buffer: "normals-backface",+ scope: "category",+ variant: "vegetation-canopy-underside",+ focusRolePrefixes: ["canopy.", "foliage.", "leaf."]+ })+ ])+ });+ MOBILITY_DIAGNOSTIC_REQUESTS = CATEGORY_REQUESTS.vehicle;+ MATERIAL_GRAZING_REQUEST = request({+ id: "material.grazing-light",+ label: "Material grazing light",+ cameraId: "grazing",+ buffer: "silhouette-unlit",+ scope: "material",+ variant: "material-grazing-light"});+ IDENTITY = new Float64Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+});++// src/views/capture.ts+function captureCellLabel(azimuthDeg, elevationDeg) {+ const az = Math.round((azimuthDeg % 360 + 360) % 360);+ const el = Math.round(elevationDeg);+ return `A${az} ${el < 0 ? "D" : "U"}${Math.abs(el)}`;}-async function loadGlbReviewScene(bytes) {- let document;- try {- document = await glbIO().readBinary(Uint8Array.from(bytes));- } catch {- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Could not parse final GLB bytes.");- }- await validateAtlasDocumentProvenance(document);- return reviewSceneFromDocument(document);+function resolveCaptureBackdrop(backdrop) {+ if (backdrop === undefined)+ return DEFAULT_BACKDROP_ID;+ if (!isBackdropId(backdrop))+ throw new CaptureConfigError(`capture.backdrop must be one of ${BACKDROP_IDS.join(", ")} (got ${JSON.stringify(backdrop)}).`);+ return backdrop;}-function reviewSceneFromDocument(document) {- const sourceScene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];- if (!sourceScene)- throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");- const reasons = new Set;- const root = new Group5;- root.name = sourceScene.getName() || "Scene";- const nodeMap = new Map;- const atlas = atlasDocumentTable(document);- const textureCache = new Map;- const morphMeshes = new Map;- const usedNames = new Set(document.getRoot().listNodes().map((node) => node.getName()));- const nodeIds = new Map(document.getRoot().listNodes().map((node, index) => [node, index]));- let morphValues = 0;- const morphError = (detail) => {- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Invalid morph review data: ${detail}`);+function resolveCapture(config) {+ const backdrop = resolveCaptureBackdrop(config?.backdrop);+ if (!config || config.preset === undefined && config.cells === undefined) {+ return {+ preset: DEFAULT_CAPTURE_PRESET,+ views: PRESET_VIEWS[DEFAULT_CAPTURE_PRESET],+ cols: PRESET_COLS[DEFAULT_CAPTURE_PRESET],+ zooms: new Array(PRESET_CAPACITY[DEFAULT_CAPTURE_PRESET]).fill(undefined),+ isDefault: true,+ backdrop+ };+ }+ const cells = config.cells;+ let preset = config.preset;+ if (preset !== undefined && !CAPTURE_PRESETS.includes(preset)) {+ throw new CaptureConfigError(`capture.preset must be one of ${CAPTURE_PRESETS.join(", ")} (got ${JSON.stringify(preset)}).`);+ }+ if (cells !== undefined) {+ if (!Array.isArray(cells) || cells.length === 0) {+ throw new CaptureConfigError("capture.cells must be a non-empty array of camera angles.");+ }+ if (cells.length > MAX_CAPTURE_CELLS) {+ throw new CaptureConfigError(`capture.cells has ${cells.length} entries; the maximum is ${MAX_CAPTURE_CELLS}.`);+ }+ for (let i = 0;i < cells.length; i++) {+ const c = cells[i];+ if (!Number.isFinite(c?.azimuthDeg) || !Number.isFinite(c?.elevationDeg)) {+ throw new CaptureConfigError(`capture.cells[${i}] needs finite azimuthDeg and elevationDeg (got ${JSON.stringify(c)}).`);+ }+ if (c.zoom !== undefined && (!Number.isFinite(c.zoom) || c.zoom <= 0)) {+ throw new CaptureConfigError(`capture.cells[${i}].zoom must be a positive number (got ${c.zoom}).`);+ }+ }+ if (preset === undefined) {+ preset = CAPTURE_PRESETS.find((p) => PRESET_CAPACITY[p] >= cells.length);+ } else if (cells.length > PRESET_CAPACITY[preset]) {+ throw new CaptureConfigError(`capture.preset ${preset} holds ${PRESET_CAPACITY[preset]} cells but ${cells.length} were given. ` + `Use a larger preset or fewer cells.`);+ }+ return {+ preset,+ views: cells.map((c) => ({+ name: c.name?.trim().toUpperCase() || captureCellLabel(c.azimuthDeg, c.elevationDeg),+ dir: orbitDir(c.azimuthDeg, c.elevationDeg)+ })),+ cols: PRESET_COLS[preset],+ zooms: cells.map((c) => c.zoom),+ isDefault: false,+ backdrop+ };+ }+ const chosen = preset;+ return {+ preset: chosen,+ views: PRESET_VIEWS[chosen],+ cols: PRESET_COLS[chosen],+ zooms: new Array(PRESET_VIEWS[chosen].length).fill(undefined),+ isDefault: chosen === DEFAULT_CAPTURE_PRESET,+ backdrop};- const joints = new Set(document.getRoot().listSkins().flatMap((skin) => skin.listJoints()));- const pendingSkins = [];- let meshCount = 0;- let instanceCount = 0;- const buildNode = (source) => {- const existing = nodeMap.get(source);- if (existing)- return existing;- const target = joints.has(source) ? new Bone2 : new Group5;- target.name = source.getName();- target.position.fromArray(source.getTranslation());- target.quaternion.fromArray(source.getRotation());- target.scale.fromArray(source.getScale());- target.userData = { ...source.getExtras() };- if (isHiddenGltfNode(source))- target.visible = false;- nodeMap.set(source, target);- const sourceMesh = source.getMesh();- if (sourceMesh) {- const targetCount = sourceMesh.listPrimitives()[0]?.listTargets().length ?? 0;- if (sourceMesh.listPrimitives().some((p) => p.listTargets().length !== targetCount))- morphError("primitives must have equal target counts.");- const nodeWeights = source.getWeights(), meshWeights = sourceMesh.getWeights();- for (const weights of [nodeWeights, meshWeights])- if (weights.length && (weights.length !== targetCount || !weights.every(Number.isFinite)))- morphError("default weight count or values.");- const weights = nodeWeights.length ? nodeWeights : meshWeights.length ? meshWeights : Array(targetCount).fill(0);- const targetNames = sourceMesh.listPrimitives()[0]?.listTargets().map((target, index) => target.getName() || String(index)) ?? [];- target.userData.kilnGlbMeshNode = true;- const matrices = localInstanceMatrices(source);- instanceCount += matrices.length;- for (const [primitiveIndex, primitive] of sourceMesh.listPrimitives().entries()) {- const position = primitive.getAttribute("POSITION");- if (position?.getElementSize() !== 3)- continue;- const indices = triangleIndices(primitive, position.getCount());- if (!indices) {- reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);- continue;- }- const material = primitive.getMaterial();- noteMaterialTextures(material, reasons);- const flat = flatMaterial(material);- const geometry = new BufferGeometry15;- const atlasBinding = primitive.getExtras()["kilnAtlasBinding"];- if (atlasBinding !== undefined && atlas)- geometry.userData.kilnAtlasBinding = expandAtlasBinding(atlasBinding, atlas);- geometry.setAttribute("position", new BufferAttribute12(Float32Array.from(decodedAccessor(position)), 3));- const normal = primitive.getAttribute("NORMAL");- if (normal) {- geometry.setAttribute("normal", new BufferAttribute12(Float32Array.from(decodedAccessor(normal)), 3));- }- for (let channel = 0;channel < 4; channel++) {- const uv = primitive.getAttribute(`TEXCOORD_${channel}`);- if (uv)- geometry.setAttribute(channel ? `uv${channel}` : "uv", new BufferAttribute12(Float32Array.from(decodedAccessor(uv)), 2));- }- const color = primitive.getAttribute("COLOR_0");- if (color)- geometry.setAttribute("color", new BufferAttribute12(Float32Array.from(decodedAccessor(color)), color.getElementSize()));- const tangent = primitive.getAttribute("TANGENT");- if (tangent) {- geometry.setAttribute("tangent", new BufferAttribute12(Float32Array.from(decodedAccessor(tangent)), 4));- }- geometry.setIndex(new BufferAttribute12(indices, 1));- if (targetCount) {- const targets = primitive.listTargets();- for (const target of targets)- for (const semantic of target.listSemantics()) {- const attribute = target.getAttribute(semantic);- if (!primitive.getAttribute(semantic) || attribute.getCount() !== position.getCount() || (semantic === "POSITION" || semantic === "NORMAL" || semantic === "TANGENT") && attribute.getElementSize() !== 3)- morphError(`target attribute ${semantic} does not match the base primitive.`);- if (semantic !== "POSITION" && semantic !== "NORMAL")- reasons.add(GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED);- }- const semantics = targets.some((target) => target.getAttribute("NORMAL")) ? ["POSITION", "NORMAL"] : ["POSITION"];- morphValues += targetCount * position.getCount() * 3 * semantics.length;- if (morphValues > 16777216)- morphError("expanded morph attributes exceed the 64 MiB review budget.");- geometry.morphTargetsRelative = true;- for (const semantic of semantics) {- const attributes = targets.map((target) => {- const attribute = target.getAttribute(semantic);- const values = attribute ? Float32Array.from(decodedAccessor(attribute)) : new Float32Array(position.getCount() * 3);- if (!values.every(Number.isFinite))- morphError(`nonfinite ${semantic} displacement.`);- return new BufferAttribute12(values, 3);- });- if (semantic === "POSITION")- geometry.morphAttributes.position = attributes;- else- geometry.morphAttributes.normal = attributes;- }- }- if (source.getSkin()) {- const skinIndices = primitive.getAttribute("JOINTS_0");- const skinWeights = primitive.getAttribute("WEIGHTS_0");- if (!skinIndices || !skinWeights || skinIndices.getElementSize() !== 4 || skinWeights.getElementSize() !== 4 || skinIndices.getCount() !== position.getCount() || skinWeights.getCount() !== position.getCount())- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Invalid skin attributes on ${source.getName()}.`);- if (primitive.getAttribute("JOINTS_1") || primitive.getAttribute("WEIGHTS_1"))- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Skin review supports four influences per vertex; ${source.getName()} has additional joint/weight sets.`);- geometry.setAttribute("skinIndex", new BufferAttribute12(Uint16Array.from(decodedAccessor(skinIndices)), 4));- geometry.setAttribute("skinWeight", new BufferAttribute12(Float32Array.from(decodedAccessor(skinWeights)), 4));- }- const threeMaterial = new MeshStandardMaterial5({- vertexColors: color !== null,- opacity: flat.opacity,- transparent: flat.alphaMode === "BLEND",- alphaTest: flat.alphaMode === "MASK" ? flat.alphaCutoff : 0,- side: flat.doubleSided ? 2 : 0,- metalness: flat.metalness,- roughness: flat.roughness- });- threeMaterial.color.setRGB(flat.color.r, flat.color.g, flat.color.b);- threeMaterial.emissive.fromArray(flat.emissive);- threeMaterial.emissiveIntensity = flat.emissiveIntensity;- if (material) {- threeMaterial.userData = { ...material.getExtras() };- threeMaterial.map = preserveTexture(material.getBaseColorTexture(), "color", textureCache, material.getBaseColorTextureInfo(), atlas);- threeMaterial.normalMap = preserveTexture(material.getNormalTexture(), "data", textureCache, material.getNormalTextureInfo(), atlas);- threeMaterial.normalScale.setScalar(material.getNormalScale());- const metallicRoughness = preserveTexture(material.getMetallicRoughnessTexture(), "data", textureCache, material.getMetallicRoughnessTextureInfo(), atlas);- threeMaterial.metalnessMap = metallicRoughness;- threeMaterial.roughnessMap = metallicRoughness;- threeMaterial.emissiveMap = preserveTexture(material.getEmissiveTexture(), "color", textureCache, material.getEmissiveTextureInfo(), atlas);- threeMaterial.aoMap = preserveTexture(material.getOcclusionTexture(), "data", textureCache, material.getOcclusionTextureInfo(), atlas);- threeMaterial.aoMapIntensity = material.getOcclusionStrength();- }- for (const [index, matrix] of matrices.entries()) {- const mesh = source.getSkin() ? new SkinnedMesh2(geometry, threeMaterial) : new Mesh14(geometry, threeMaterial);- if (mesh instanceof SkinnedMesh2)- pendingSkins.push({ source, mesh });- const baseName = source.getName() || sourceMesh.getName() || "Mesh";- mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;- if (targetCount) {- let bindingName = `${PropertyBinding3.sanitizeNodeName(baseName)}_morph_${nodeIds.get(source)}_${primitiveIndex}_${index}`;- while (usedNames.has(bindingName))- bindingName += "_";- usedNames.add(bindingName);- mesh.name = bindingName;- mesh.morphTargetInfluences = [...weights];- if (Array.isArray(targetNames) && targetNames.length === targetCount && targetNames.every((name) => typeof name === "string"))- mesh.morphTargetDictionary = Object.fromEntries(targetNames.map((name, index) => [name, index]));- const siblings = morphMeshes.get(source) ?? [];- siblings.push(mesh);- morphMeshes.set(source, siblings);- }- mesh.matrixAutoUpdate = false;- mesh.matrix.copy(matrix);- target.add(mesh);- meshCount++;- }- }- }- for (const child of source.listChildren())- target.add(buildNode(child));- return target;- };- for (const child of sourceScene.listChildren())- root.add(buildNode(child));- root.updateMatrixWorld(true);- if (meshCount === 0)- throw new GlbGeometryFlatError("GLB_FLAT_NO_RENDERABLE_GEOMETRY", "Final GLB contains no renderable geometry.");- const sceneMeshCount = meshCount;- const sceneInstanceCount = instanceCount;- const sceneReasons = new Set(reasons);- registerReviewLodChains(root, listLodChainNodes(document).map(({ levels: [base, ...lower] }) => ({- base: nodeMap.get(base),- levels: lower.some((level) => nodeMap.has(level)) ? [] : lower.map(buildNode)- })));- for (const { source, mesh } of pendingSkins) {- const skin = source.getSkin();- const bones = skin.listJoints().map((joint) => nodeMap.get(joint));- const inverse = skin.getInverseBindMatrices();- if (!bones.length || bones.some((bone) => !(bone instanceof Bone2)) || inverse && (inverse.getElementSize() !== 16 || inverse.getCount() < bones.length))- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Invalid or unavailable skin joints/bind matrices on ${source.getName()}.`);- const indices = mesh.geometry.getAttribute("skinIndex");- const weights = mesh.geometry.getAttribute("skinWeight");- for (let i = 0;i < indices.array.length; i++)- if (indices.array[i] >= bones.length || !Number.isFinite(weights.array[i]) || weights.array[i] < 0)- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Invalid skin joint index or weight on ${source.getName()}.`);- const matrices = bones.map((_, index) => new Matrix417().fromArray(inverse ? inverse.getElement(index, []) : new Matrix417().elements));- mesh.bind(new Skeleton3(bones, matrices), new Matrix417);- }- root.updateMatrixWorld(true);- const nativeClips = document.getRoot().listAnimations().map((animation) => withLoopIntent(new AnimationClip4(animation.getName(), -1, animation.listChannels().flatMap((channel) => {- const node = channel.getTargetNode();- const path = channel.getTargetPath();- const sampler = channel.getSampler();- const input = sampler?.getInput()?.getArray();- const output = sampler?.getOutput()?.getArray();- const property = path === "translation" ? "position" : path === "rotation" ? "quaternion" : path;- if (!node || !property || !input || !output)- return [];- const interpolation = sampler.getInterpolation();- if (interpolation !== "STEP" && interpolation !== "LINEAR" && interpolation !== "CUBICSPLINE") {- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Animation review does not support ${interpolation} interpolation; use LINEAR, STEP or CUBICSPLINE.`);- }- if (property === "weights") {- const targets = morphMeshes.get(node);- if (!targets?.length)- return [];- const width = targets[0].morphTargetInfluences.length;- const values = decodedAccessor(sampler.getOutput());- if (input.length < 1 || input.length > REVIEW_CLIP_LIMITS.samplesPerTrack || values.length > REVIEW_CLIP_LIMITS.valuesPerTrack || values.length !== input.length * width * (interpolation === "CUBICSPLINE" ? 3 : 1) || !Array.from(input).every((v, i) => Number.isFinite(v) && v >= 0 && (i === 0 || v > input[i - 1])) || !Array.from(values).every(Number.isFinite))- morphError("animation weight sampler width or values.");- return targets.map((mesh) => {- const track = new NumberKeyframeTrack(`${mesh.name}.morphTargetInfluences`, input, values, interpolation === "STEP" ? InterpolateDiscrete2 : InterpolateLinear2);- return interpolation === "CUBICSPLINE" ? useCubicSpline(track) : track;- });- }- const Track = path === "rotation" ? QuaternionKeyframeTrack2 : VectorKeyframeTrack2;- if (interpolation === "CUBICSPLINE") {- if (input.length < 2 || output.length !== input.length * cubicTuple(property)) {- throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Animation sampler for ${node.getName()}.${property} is not a valid CUBICSPLINE sampler: it needs at least two keys and three values per key.`);- }- return [useCubicSpline(new Track(`${node.getName()}.${property}`, input, output))];- }- return [- new Track(`${node.getName()}.${property}`, input, output, interpolation === "STEP" ? InterpolateDiscrete2 : InterpolateLinear2)- ];- })), animation.getExtras().kilnLoopIntent));- const extrasClips = reviewClipsFromExtras(sourceScene.getExtras());- if (extrasClips)- for (const clip of extrasClips)- clip.tracks = clip.tracks.flatMap((track) => {- const dot = track.name.lastIndexOf("."), property = track.name.slice(dot + 1);- if (!/^morphTargetInfluences(?:\[[^\]]+\])?$/.test(property))- return [track];- const sources = [...morphMeshes.keys()].filter((node) => node.getName() === track.name.slice(0, dot));- if (sources.length !== 1)- return [track];- return morphMeshes.get(sources[0]).map((mesh) => {- const copy = new NumberKeyframeTrack(`${mesh.name}.${property}`, track.times, track.values, track.getInterpolation());- return isCubicSplineTrack(track) ? useCubicSpline(copy) : copy;- });- });- const clips = extrasClips ?? nativeClips;- return {- root,- clips,- reasonCodes: REASON_ORDER.filter((reason) => sceneReasons.has(reason)),- meshCount: sceneMeshCount,- instanceCount: sceneInstanceCount- };-}-var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO, cubicTuple = (property) => property === "quaternion" ? 12 : 9;-var init_glb = __esm(() => {- init_animation_cubic();- init_gltf_texture_binding();- init_animation_spline();- init_gltf_io();- init_lod_export();- init_metrics();- init_lod3();- init_atlas_provenance();- GLB_GEOMETRY_FLAT_REASON = {- TEXTURE_SAMPLING_UNSUPPORTED: "GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED",- KTX2_SAMPLING_UNSUPPORTED: "GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED",- NON_TRIANGLE_PRIMITIVE_UNSUPPORTED: "GLB_FLAT_NON_TRIANGLE_PRIMITIVE_UNSUPPORTED",- SKIN_DEFORMATION_UNSUPPORTED: "GLB_FLAT_SKIN_DEFORMATION_UNSUPPORTED",- MORPH_TARGETS_UNSUPPORTED: "GLB_FLAT_MORPH_TARGETS_UNSUPPORTED"- };- REASON_ORDER = [- GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED,- GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED,- GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED,- GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED,- GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED- ];- REVIEW_CLIP_LIMITS = {- clips: 32,- tracks: 256,- samplesPerTrack: 4096,- valuesPerTrack: 16384- };- GlbGeometryFlatError = class GlbGeometryFlatError extends Error {- code;- constructor(code, message) {- super(message);- this.code = code;- this.name = "GlbGeometryFlatError";- }- };- glbIO = createGltfIO;-});--// src/evaluator/handler.ts-var init_handler = __esm(() => {- init_authoring_diagnostic();- init_solid_diagnostic();- init_render();- init_run();- init_protocol();-});--// src/evaluator/subprocess.ts-var DEFAULT_MAX_GLB_BYTES, DEFAULT_MAX_RESPONSE_BYTES, MAX_STDERR_BYTES;-var init_subprocess = __esm(() => {- init_authoring_diagnostic();- init_solid_diagnostic();- init_run();- init_requirements_context();- init_material_library_node();- init_protocol();- DEFAULT_MAX_GLB_BYTES = 16 * 1024 * 1024;- DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;- MAX_STDERR_BYTES = 16 * 1024;-});-// src/evaluator/isolation.ts-var MAX_READINESS_PROTOCOL_BYTES;-var init_isolation = __esm(() => {- init_subprocess();- MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;-});--// src/evaluator/index.ts-var init_evaluator = __esm(() => {- init_protocol();- init_handler();- init_subprocess();- init_isolation();-});--// src/views/renderer-id.ts-import { readFileSync } from "node:fs";-function engineVersion() {- for (const path of ["../package.json", "../../package.json"]) {- try {- const raw = readFileSync(new URL(path, import.meta.url), "utf8");- const pkg = JSON.parse(raw);- if (pkg.name === "@instruktlabs/kiln" && typeof pkg.version === "string" && pkg.version) {- return pkg.version;- }- } catch {}- }- return "unknown";-}-var CPU_RASTER_RENDERER_ID;-var init_renderer_id = __esm(() => {- CPU_RASTER_RENDERER_ID = `cpu-raster:${engineVersion()}`;-});--// src/views/scene-raster.ts-import * as THREE51 from "three";-var DEG2;-var init_scene_raster = __esm(() => {- init_evaluator();- init_glb();- init_png();- init_raster();- init_scene_copy();- DEG2 = Math.PI / 180;-});--// src/views/vehicle.ts-import * as THREE52 from "three";-function hasRole2(node, prefix) {- return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;-}-function chassisBounds(root, inverse) {- const bounds = new THREE52.Box3;- let found = false;- root.traverse((node) => {- if (!hasRole2(node, "chassis"))- return;- node.traverse((part) => {- if (!(part instanceof THREE52.Mesh) || !(part.geometry instanceof THREE52.BufferGeometry))- return;- part.geometry.computeBoundingBox();- const box = part.geometry.boundingBox;- if (!box)- return;- 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 z of [box.min.z, box.max.z]) {- bounds.expandByPoint(new THREE52.Vector3(x, y, z).applyMatrix4(matrix));- found = true;- }- });- });- return found ? bounds : undefined;-}-function describeVehicleDiagnostics(root) {- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- const assemblies = resolveVehicleWheelAssemblies(root);- const wheels = assemblies.map((wheel) => ({- id: wheel.id,- center: tuple7(wheel.centerWorld.clone().applyMatrix4(inverse)),- radius: wheel.radius ?? 0,- width: wheel.width ?? 0,- axle: tuple7(wheel.spinAxisWorld.clone().transformDirection(inverse)),- loadBearing: wheel.loadBearing- }));- const byAxle = new Map;- for (let index = 0;index < assemblies.length; index++) {- const key = assemblies[index].index ?? assemblies[index].id;- const group = byAxle.get(key) ?? [];- group.push(wheels[index]);- byAxle.set(key, group);- }- const axles = [...byAxle].flatMap(([id, members]) => {- if (members.length < 2)- return [];- const sorted = [...members].sort((a, b) => a.center[2] - b.center[2]);- return [{ id, start: sorted[0].center, end: sorted.at(-1).center }];- });- const contacts = wheels.filter((wheel) => wheel.loadBearing && wheel.radius > 0).map((wheel) => wheel.center[1] - wheel.radius);- const supportPlaneY = contacts.length > 0 ? contacts.reduce((sum, value) => sum + value, 0) / contacts.length : undefined;- const chassis = chassisBounds(root, inverse);- const views = [- { id: "vehicle.front-direction", label: "+X front and chassis", cameraDirection: [1, 0.15, 0] },- {- id: "vehicle.axles.top",- label: "Chassis and axle projection",- cameraDirection: [0.001, 1, 0]- },- {- id: "vehicle.underbody",- label: "Underbody support plane",- cameraDirection: [-0.3, -0.8, 0.5]- },- ...wheels.slice(0, 2).map((wheel) => ({- id: `vehicle.wheel-section.${wheel.id.replace(/[^a-zA-Z0-9.-]/g, "-")}`,- label: `Wheel section ${wheel.id}`,- cameraDirection: [0, 0, wheel.center[2] < 0 ? -1 : 1],- focus: wheel.id- }))- ];- return {- schemaVersion: 1,- forwardArrow: { start: [0, 0, 0], end: [1, 0, 0] },- ...chassis ? { chassisBox: { min: tuple7(chassis.min), max: tuple7(chassis.max) } } : {},- axles,- wheels,- ...supportPlaneY !== undefined ? { supportPlaneY } : {},- views- };-}-function tagDiagnostic(node, role) {- stampSemanticMetadataV1(node, { roles: [role] });-}-function rod(name, start, end, radius, color, role) {- const from = new THREE52.Vector3(...start);- const to = new THREE52.Vector3(...end);- const direction = to.clone().sub(from);- const length = direction.length();- const geometry = length > 0.000000001 ? new THREE52.CylinderGeometry(radius, radius, length, 8) : new THREE52.SphereGeometry(radius, 8, 6);- const result = new THREE52.Mesh(geometry, new THREE52.MeshBasicMaterial({ color }));- result.name = name;- result.position.copy(from).add(to).multiplyScalar(0.5);- if (length > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE52.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));- }- tagDiagnostic(result, role);- return result;}-function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {- const overlay = new THREE52.Group;- overlay.name = "VehicleDiagnosticOverlay";- 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 THREE52.Group;- arrow.name = "Diagnostic_Forward_+X";- tagDiagnostic(arrow, "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 THREE52.Mesh(new THREE52.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE52.MeshBasicMaterial({ color: 16724804 }));- arrowHead.name = "Diagnostic_Forward_Head";- arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);- arrowHead.quaternion.setFromUnitVectors(new THREE52.Vector3(0, 1, 0), new THREE52.Vector3(1, 0, 0));- tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");- arrow.add(arrowHead);- overlay.add(arrow);- 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 descriptor.wheels) {- const ring = new THREE52.Mesh(new THREE52.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE52.MeshBasicMaterial({ color: 16763955 }));- ring.name = `Diagnostic_Wheel_${wheel.id}`;- ring.position.set(...wheel.center);- const axle = new THREE52.Vector3(...wheel.axle);- if (axle.lengthSq() > 0.000000000001) {- ring.quaternion.setFromUnitVectors(new THREE52.Vector3(0, 0, 1), axle.normalize());- }- tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);- overlay.add(ring);- }- if (descriptor.chassisBox) {- const chassis = new THREE52.Group;- chassis.name = "Diagnostic_ChassisBox";- tagDiagnostic(chassis, "diagnostic.vehicle.chassis");- const { min, max } = descriptor.chassisBox;- const corners = [- [min[0], min[1], min[2]],- [max[0], min[1], min[2]],- [max[0], max[1], min[2]],- [min[0], max[1], min[2]],- [min[0], min[1], max[2]],- [max[0], min[1], max[2]],- [max[0], max[1], max[2]],- [min[0], max[1], max[2]]- ];- const edges = [- [0, 1],- [1, 2],- [2, 3],- [3, 0],- [4, 5],- [5, 6],- [6, 7],- [7, 4],- [0, 4],- [1, 5],- [2, 6],- [3, 7]- ];- for (const [index, edge] of edges.entries()) {- chassis.add(rod(`Diagnostic_ChassisEdge_${index}`, corners[edge[0]], corners[edge[1]], thickness, 5635959, "diagnostic.vehicle.chassis"));- }- overlay.add(chassis);- }- if (descriptor.supportPlaneY !== undefined) {- const plane = new THREE52.Group;- plane.name = "Diagnostic_SupportPlane";- tagDiagnostic(plane, "diagnostic.vehicle.support-plane");- 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],- [halfX, y, -halfZ]- ],- [- [halfX, y, -halfZ],- [halfX, y, halfZ]- ],- [- [halfX, y, halfZ],- [-halfX, y, halfZ]- ],- [- [-halfX, y, halfZ],- [-halfX, y, -halfZ]- ],- [- [-halfX, y, 0],- [halfX, y, 0]- ],- [- [0, y, -halfZ],- [0, y, halfZ]- ]- ];- for (const [index, [start, end]] of planeLines.entries()) {- plane.add(rod(`Diagnostic_SupportLine_${index}`, start, end, thickness * 0.7, 6750207, "diagnostic.vehicle.support-plane"));- }- overlay.add(plane);- }- return overlay;+function resolveGridCapture(config, envVariant) {+ const resolved = resolveCapture(config);+ if (config)+ return resolved;+ const views = resolveGridViews(envVariant);+ return views === resolved.views ? resolved : { ...resolved, views };}-function compositeForCapture(root, overlay) {- if (root.matrixAutoUpdate === false) {- overlay.matrix.copy(root.matrix);- overlay.matrixAutoUpdate = false;- } else {- overlay.position.copy(root.position);- overlay.quaternion.copy(root.quaternion);- overlay.scale.copy(root.scale);- }- return {- name: "VehicleDiagnosticCaptureRoot",- type: "Group",- visible: true,- position: { x: 0, y: 0, z: 0 },- quaternion: { x: 0, y: 0, z: 0, w: 1 },- scale: { x: 1, y: 1, z: 1 },- children: [root, overlay]+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(() => {+ init_raster();+ init_background();+ CAPTURE_PRESETS = [+ "1x1",+ "1x2",+ "2x1",+ "3x1",+ "2x2",+ "3x2",+ "3x3"+ ];+ PRESET_COLS = {+ "1x1": 1,+ "1x2": 1,+ "2x1": 2,+ "3x1": 3,+ "2x2": 2,+ "3x2": 3,+ "3x3": 3};-}-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, "-");- return {- ...requestValue,- id: `vehicle.wheel-section.${suffix}`,- label: `Vehicle wheel section ${target.id}`,- focusRolePrefixes: [target.id]+ PRESET_CAPACITY = {+ "1x1": 1,+ "1x2": 2,+ "2x1": 2,+ "3x1": 3,+ "2x2": 4,+ "3x2": 6,+ "3x3": 9+ };+ BOTTOM = { name: "BOTTOM", dir: [0, -1, 0.0001] };+ THREE_QUARTER_REAR = { name: "REAR 34", dir: [-0.7, 0.5, -0.7] };+ THREE_QUARTER_LOW = { name: "LOW 34", dir: [0.7, -0.35, 0.7] };+ PRESET_VIEWS = {+ "1x1": [SIX_VIEWS[5]],+ "1x2": [SIX_VIEWS[0], SIX_VIEWS[5]],+ "2x1": [SIX_VIEWS[0], SIX_VIEWS[5]],+ "3x1": [SIX_VIEWS[0], SIX_VIEWS[1], SIX_VIEWS[5]],+ "2x2": [SIX_VIEWS[0], SIX_VIEWS[1], SIX_VIEWS[4], SIX_VIEWS[5]],+ "3x2": SIX_VIEWS,+ "3x3": [...SIX_VIEWS, BOTTOM, THREE_QUARTER_REAR, THREE_QUARTER_LOW]+ };+ CaptureConfigError = class CaptureConfigError extends Error {};+});++// src/views/lod.ts+function registerReviewLodChains(root, chains) {+ if (chains.length > 0)+ CHAINS.set(root, chains);}-function captureVehicleDiagnosticViews(root, size = 256) {- if (!Number.isInteger(size) || size < 1 || size > 2048)- throw new RangeError("Diagnostic size must be an integer from 1 to 2048; category/intent selection is retired.");- const descriptor = describeVehicleDiagnostics(root);- const overlay = createVehicleDiagnosticOverlay(root, descriptor);- const composite = compositeForCapture(root, overlay);- const requests = MOBILITY_DIAGNOSTIC_REQUESTS;- return requests.map((baseRequest) => {- const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor) : baseRequest;- const frame = renderDiagnosticView(composite, requestValue, { size });- return {- id: frame.id,- label: frame.label,- cameraId: frame.camera.id,- kind: requestValue.variant === "vehicle-underbody" ? "underbody" : "wheel-section",- buffer: "semantic-overlay",- width: frame.width,- height: frame.height,- png: frame.png,- regions: frame.regions,- descriptor- };+function reviewLodChains(root) {+ return typeof root === "object" && root !== null ? CHAINS.get(root) ?? [] : [];+}+function drawnLevels(root) {+ return reviewLodChains(root).map((chain) => {+ const drawn = chain.levels.findIndex((level) => level.parent !== null);+ return drawn < 0 ? 0 : drawn + 1;});}-var tuple7 = (value) => [value.x, value.y, value.z];-var init_vehicle3 = __esm(() => {- init_contracts();- init_vehicle();- init_diagnostic();-});--// src/views/index.ts-function setLinearColor(color, rgb) {- if (!color)- return;- color.r = rgb[0];- color.g = rgb[1];- color.b = rgb[2];+function swap(out, into) {+ const parent = out.parent;+ parent.children[parent.children.indexOf(out)] = into;+ into.parent = parent;+ out.parent = null;}-function snapMaterialToPalette(mat, slots, idx) {- if (!mat.color)+function levelForSubject(root, subject) {+ const chains = reviewLodChains(root);+ if (chains.length === 0 || typeof subject !== "object" || subject === null)+ return;+ const byPath = typeof subject.path === "string";+ if (!byPath && typeof subject.name !== "string")return;- if (mat.map || mat.vertexColors)- return false;- const emissive = mat.emissive && (mat.emissiveIntensity ?? 1) > 0 ? [- mat.emissive.r * (mat.emissiveIntensity ?? 1),- mat.emissive.g * (mat.emissiveIntensity ?? 1),- mat.emissive.b * (mat.emissiveIntensity ?? 1)- ] : undefined;- const slotI = chooseSlot(idx, {- baseLinear: [mat.color.r, mat.color.g, mat.color.b],- ...emissive ? { emissiveLinear: emissive } : {},- transparent: mat.transparent === true || mat.opacity !== undefined && mat.opacity < 0.98- });- if (slotI === undefined)- return false;- const slot = slots[slotI];- const kind = slot.kind ?? "opaque";- const rgb = hexToLinearRgb(slot.color);- setLinearColor(mat.color, rgb);- if (mat.metalness !== undefined)- mat.metalness = slot.metalness ?? 0;- if (mat.roughness !== undefined)- mat.roughness = slot.roughness ?? (kind === "glass" ? 0.1 : 0.85);- if (kind === "glass") {- mat.transparent = true;- mat.opacity = slot.opacity ?? 0.4;- } else {- if (mat.transparent !== undefined)- mat.transparent = false;- if (mat.opacity !== undefined)- mat.opacity = 1;+ const subjects = listCameraSubjects(root);+ if (subjects.some((entry) => byPath ? entry.path === subject.path : entry.name === subject.name))+ return;+ const paths = new Map(subjects.map((entry) => [entry.node, entry.path]));+ const matches = [];+ for (const chain of chains) {+ const parent = chain.base.parent;+ const parentPath = parent ? paths.get(parent) : undefined;+ if (!parent || parentPath === undefined)+ continue;+ const before = parent.children.slice(0, parent.children.indexOf(chain.base));+ chain.levels.forEach((level, index) => {+ const occurrence = before.filter((sibling) => sibling.name === level.name).length;+ const own = `/${encodeURIComponent(level.name)}[0]`;+ const at = `${parentPath}/${encodeURIComponent(level.name)}[${occurrence}]`;+ for (const entry of listCameraSubjects(level)) {+ const path = at + entry.path.slice(own.length);+ if (byPath ? path === subject.path : entry.name === subject.name)+ matches.push({ chain, level: index + 1, path });+ }+ });}- if (mat.emissive) {- if (kind === "glow") {- setLinearColor(mat.emissive, rgb);- mat.emissiveIntensity = Math.max(mat.emissiveIntensity ?? 1, 1);- } else {- setLinearColor(mat.emissive, [0, 0, 0]);- if (mat.emissiveIntensity !== undefined)- mat.emissiveIntensity = 0;- }+ if (matches.length > 1)+ throw new Error(`ambiguous camera subject: ${matches.length} nodes in lower levels of detail match ${JSON.stringify(subject.path ?? subject.name)}; choose one path: ${matches.map((match) => match.path).join(", ")}`);+ return matches[0];+}+async function withSubjectLevel(root, subject, run) {+ const scene = root;+ const match = levelForSubject(scene, subject);+ if (!match)+ return run(drawnLevels(root));+ const level = match.chain.levels[match.level - 1];+ swap(match.chain.base, level);+ scene.updateMatrixWorld(true);+ try {+ return await run(drawnLevels(root));+ } finally {+ swap(level, match.chain.base);+ scene.updateMatrixWorld(true);}- return true;}-function snapSceneToPalette(root, slots) {- if (slots.length === 0)- return { snapped: 0, skipped: 0 };- const traverse = root?.traverse;- if (!traverse)- return { snapped: 0, skipped: 0 };- const idx = buildSlotIndex(slots);- let snapped = 0;- let skipped = 0;- traverse.call(root, (obj) => {- if (!obj.isMesh || !obj.material)- return;- const materials = Array.isArray(obj.material) ? obj.material : [obj.material];- for (const mat of materials) {- const didSnap = snapMaterialToPalette(mat, slots, idx);- if (didSnap === true)- snapped++;- else if (didSnap === false)- skipped++;- }- });- return { snapped, skipped };+var CHAINS;+var init_lod3 = __esm(() => {+ init_camera();+ CHAINS = new WeakMap;+});++// src/views/camera-capture.ts+function validateAdvancedCapture(config) {+ for (const key of Object.keys(config))+ if (!["version", "shots", "cols", "size", "output", "backdrop"].includes(key))+ throw new Error(`capture.${key} is unknown or incompatible with shots`);+ if (config.version !== "kiln.capture.v1" && config.version !== "kiln.capture.v2")+ throw new Error("advanced capture requires version kiln.capture.v1 or kiln.capture.v2");+ if (!Array.isArray(config.shots) || config.shots.length < 1 || config.shots.length > 9)+ throw new Error("capture.shots must contain 1..9 shots");+ if (config.version !== "kiln.capture.v2" && config.shots.some((shot) => shot.hide !== undefined))+ throw new Error("shot.hide requires version kiln.capture.v2");+ if (config.cols !== undefined && (!Number.isInteger(config.cols) || config.cols < 1 || config.cols > 3))+ throw new Error("capture.cols must be 1..3");+ if (config.size !== undefined && (!Number.isInteger(config.size) || config.size < 128 || config.size > MAX_CAPTURE_SHOT_SIZE))+ throw new Error(`capture.size must be 128..${MAX_CAPTURE_SHOT_SIZE}`);+ if (config.output !== undefined && !["grid", "separate"].includes(config.output))+ throw new Error("capture.output must be grid or separate");+ resolveCaptureBackdrop(config.backdrop);}-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 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 = resolved.zooms.some((z) => z !== undefined);- const sceneBounds = wantsZoom ? measureBounds(root) : undefined;- const backdrop = opts.backdrop ?? resolved.backdrop;- const cache = opts.snapPalette?.length ? undefined : opts.captureCache;- let reused = 0;+async function renderCaptureGrid(root, config, render, limits) {+ validateAdvancedCapture(config);+ const plans = [];+ for (const request of config.shots)+ plans.push(await withSubjectLevel(root, request.subject, async (levels) => ({+ subject: request.subject,+ shot: resolveAssetCamera(root, request),+ levels+ })));+ const shots = plans.map((plan) => plan.shot);+ const size = config.size ?? 384;+ const cols = config.cols ?? Math.min(3, shots.length);+ const backdrop = resolveCaptureBackdrop(config.backdrop);+ enforceCapturePixels(shots.length, size, cols, limits);const cells = [];- for (let vi = 0;vi < views.length; vi++) {- const zoom = resolved.zooms[vi];- const rasterOptions = {- size,- backfaceCull: opts.backfaceCull,- backdrop,- ...opts.frameBounds ? { frameBounds: opts.frameBounds } : {},- ...sceneBounds && zoom !== undefined ? { frameBounds: expandFrameBounds(sceneBounds, zoom) } : {}- };- let cell;- if (cache && opts.artifactGlbSha256) {- 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_ID}/legacy-fit`,- camera: camera2,- size,- backfaceCull: opts.backfaceCull ?? true,- backdrop- }, async () => ({- png: encodePng(rasterizeView(root, views[vi].dir, rasterOptions), size, size),- width: size,- height: size,- inputGlbSha256: opts.artifactGlbSha256,- reasonCodes: [],- meshCount: 0,- instanceCount: 0- }));- if (result.captureCache?.hit)- reused++;- cell = decodePng(result.png).rgb;- } else- cell = rasterizeView(root, views[vi].dir, rasterOptions);- annotateViewCell(cell, size, views[vi]);- cells.push(cell);+ const perFramePngs = [];+ const derivativeReceipts = [];+ for (const { subject, shot } of plans) {+ const dir = shot.camera.position.map((n, i) => n - shot.camera.target[i]);+ const view = { name: shot.name, dir };+ const png = await withSubjectLevel(root, subject, () => withCameraVisibility(root, shot, async () => {+ if (render) {+ const result = await render({+ root,+ label: shot.name,+ view,+ size,+ camera: shot.camera,+ backdrop+ });+ derivativeReceipts.push(result.receipt);+ return result.png;+ }+ return encodePng(rasterizeCamera(root, shot.camera, size, true, backdrop), size, size);+ }));+ 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, width, height } = compositeCellGrid(cells, size, cols);const png = encodePng(rgb, width, height);- enforceCaptureBytes([png], opts.captureLimits);+ enforceCaptureBytes(config.output === "separate" ? perFramePngs : [png], limits);return {png,width,height,- views: views.map((v) => v.name),- capture: { preset: resolved.preset, cols, cells: views.length, backdrop },- ...cache && opts.artifactGlbSha256 ? { captureCache: { hit: reused === views.length, reused, total: views.length } } : {}+ views: shots.map((s) => s.name),+ capture: {+ preset: `${cols}x${Math.ceil(shots.length / cols)}`,+ cols,+ cells: shots.length,+ backdrop,+ output: config.output ?? "grid"+ },+ cameraShots: shots,+ perFramePngs,+ derivativeReceipts,+ ...reviewLodChains(root).length ? { viewLevels: plans.map((plan) => plan.levels) } : {},+ ...derivativeReceipts.length ? {+ captureCache: {+ hit: derivativeReceipts.every((r) => r.captureCache?.hit),+ reused: derivativeReceipts.filter((r) => r.captureCache?.hit).length,+ total: derivativeReceipts.length+ }+ } : {}};}-async function hashGlbViewInput(bytes) {- const copy = Uint8Array.from(bytes);- const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));- return `sha256:${[...digest].map((value) => value.toString(16).padStart(2, "0")).join("")}`;+var init_camera_capture = __esm(() => {+ init_capture_limits();+ init_camera();+ init_capture();+ init_png();+ init_grid();+ init_annotate();+ init_lod3();+});++// src/views/architecture.ts+function nodeRoles(node) {+ return readSemanticMetadataV1FromExtras(node.userData ?? {})?.roles ?? [];+}+function hasArchitectureRoofRole(node) {+ return nodeRoles(node).some((role) => ARCHITECTURE_ROOF_ROLE_PREFIXES.some((prefix) => role.startsWith(prefix)));+}+function legacyRoofName(name) {+ if (!name)+ return false;+ return /^roof(?:$|[_. -]|(?:slope|panel|gable|ridge)|[ab](?:$|[_. -]))/i.test(name.trim());}-async function renderGlbViewCell(bytes, view, options = {}) {- const exactBytes = Uint8Array.from(bytes);- const loaded = await loadGlbGeometryFlatScene(exactBytes);- const size = options.size ?? 256;- const rgb = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull, options.backdrop) : rasterizeView(loaded.root, view.dir, {- size,- ...options.backdrop ? { backdrop: options.backdrop } : {},- ...options.backfaceCull !== undefined ? { backfaceCull: options.backfaceCull } : {},- ...options.frameBounds ? { frameBounds: options.frameBounds } : {}- });- return {- png: encodePng(rgb, size, size),- width: size,- height: size,- inputGlbSha256: await hashGlbViewInput(exactBytes),- reasonCodes: loaded.reasonCodes,- meshCount: loaded.meshCount,- instanceCount: loaded.instanceCount+function minimalMatches(root, predicate) {+ const matches = [];+ const visit = (node, ancestorMatched) => {+ const matched = predicate(node);+ if (matched && !ancestorMatched)+ matches.push(node);+ for (const child of node.children ?? [])+ visit(child, ancestorMatched || matched);};+ visit(root, false);+ return matches;}-async function renderGlbViewGrid(bytes, options = {}) {- const exactBytes = Uint8Array.from(bytes);- const loaded = options.capture?.version || options.capture?.shots ? await loadGlbReviewScene(exactBytes) : await loadGlbGeometryFlatScene(exactBytes);- const artifactGlbSha256 = await hashGlbViewInput(exactBytes);- const grid = await renderViewGrid(loaded.root, { ...options, artifactGlbSha256 });- return {- ...grid,- inputGlbSha256: await hashGlbViewInput(exactBytes),- reasonCodes: loaded.reasonCodes,- meshCount: loaded.meshCount,- instanceCount: loaded.instanceCount- };+function selectArchitectureRoofNodes(root) {+ const candidate = root;+ 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: [] };}-function expandFrameBounds(b, factor) {- const min = [0, 0, 0];- const max = [0, 0, 0];- for (let a = 0;a < 3; a++) {- const center = (b.min[a] + b.max[a]) / 2;- const half = (b.max[a] - b.min[a]) / 2 * factor;- min[a] = center - half;- max[a] = center + half;- }- return { min, max };+function setSubtreeVisibility(node, visible) {+ node.visible = visible;+ for (const child of node.children ?? [])+ setSubtreeVisibility(child, visible);}-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"];+function hideArchitectureRoofInScene(root) {+ const selection = selectArchitectureRoofNodes(root);+ for (const node of selection.nodes)+ setSubtreeVisibility(node, false);+ return selection;}-function worldOrigin(node) {- const e = node.matrixWorld.elements;- return [e[12], e[13], e[14]];+var ARCHITECTURE_ROOF_ROLE_PREFIXES;+var init_architecture3 = __esm(() => {+ init_contracts();+ ARCHITECTURE_ROOF_ROLE_PREFIXES = Object.freeze([+ `${KILN_SEMANTIC_ROLES.roof}.`,+ `${KILN_SEMANTIC_ROLES.architectureRoof}.`+ ]);+});++// src/views/glb.ts+import {+ Primitive as Primitive2+} from "@gltf-transform/core";+import {+ BufferAttribute as BufferAttribute12,+ BufferGeometry as BufferGeometry15,+ Group as Group5,+ Matrix4 as Matrix418,+ Mesh as Mesh14,+ Bone as Bone2,+ SkinnedMesh as SkinnedMesh2,+ Skeleton as Skeleton3,+ MeshStandardMaterial as MeshStandardMaterial5,+ NoColorSpace as NoColorSpace5,+ SRGBColorSpace as SRGBColorSpace6,+ Texture as Texture4,+ AnimationClip as AnimationClip4,+ QuaternionKeyframeTrack as QuaternionKeyframeTrack2,+ NumberKeyframeTrack,+ PropertyBinding as PropertyBinding3,+ VectorKeyframeTrack as VectorKeyframeTrack2,+ Quaternion as Quaternion20,+ Vector3 as Vector340,+ InterpolateDiscrete as InterpolateDiscrete2,+ InterpolateLinear as InterpolateLinear2+} from "three";+function record9(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);}-function boxDistance(point, box) {- let sum = 0;- for (let a = 0;a < 3; a++) {- const d = Math.max(box.min[a] - point[a], 0, point[a] - box.max[a]);- sum += d * d;- }- return Math.sqrt(sum);+function withLoopIntent(clip, intent) {+ if (intent === "loop" || intent === "once")+ clip.userData.kilnLoopIntent = intent;+ return clip;}-async function renderClipAnimation(root, clips, opts = {}) {- const size = opts.size ?? 256;- const frameCount = Math.max(2, Math.min(opts.frames ?? 6, 6));- const cam = resolveCamera(opts.camera);- if (!clips || clips.length === 0) {- return {- ok: false,- frames: 0,- frameTimes: [],- error: "this asset has no animation clips",- availableClips: []- };+function reviewClipsFromExtras(extras) {+ if (!record9(extras))+ return;+ const envelope = extras[REVIEW_CLIPS_EXTRAS_KEY];+ if (!record9(envelope) || envelope.version !== 1 && envelope.version !== 2 || !Array.isArray(envelope.clips)) {+ return;}- const requested = opts.clip?.trim();- const chosen = requested ? findClip(clips, requested) : clips[0];- if (!chosen) {- return {- ok: false,- frames: 0,- frameTimes: [],- ...requested ? { clip: requested } : {},- error: `clip "${requested}" not found in this asset`,- availableClips: clipNames(clips)- };+ const cubicAllowed = envelope.version === 2;+ if (envelope.clips.length > REVIEW_CLIP_LIMITS.clips) {+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Animation review clip limit exceeded.");}- const prepared = prepareClip(root, chosen);- if (opts.frameTimes && opts.frames !== undefined)- throw new Error("frameTimes and frames are mutually exclusive");- if (opts.shot && opts.camera)- throw new Error("shot and camera are mutually exclusive");- if (opts.frameTimes && (opts.frameTimes.length < 1 || opts.frameTimes.length > 9 || opts.frameTimes.some((v, i) => !Number.isFinite(v) || v < 0 || v > 1 || i > 0 && v <= opts.frameTimes[i - 1])))- throw new Error("frameTimes must contain 1..9 strictly increasing phases in 0..1");- const times = opts.frameTimes ? opts.frameTimes.map((t) => t * prepared.duration) : planFrameTimes(prepared.duration, frameCount);- const frameTimes = times.map((t) => prepared.duration > 0 ? t / prepared.duration : 0);- if (opts.measureParts && (opts.measureParts.length < 1 || opts.measureParts.length > 16))- throw new Error("measureParts must contain 1..16 exact selectors");- const measuredParts = opts.measureParts?.map((selector) => selectCameraSubject(root, selector));- if (measuredParts && new Set(measuredParts.map((part) => part.node)).size !== measuredParts.length)- throw new Error("measureParts contains duplicate part selections");- const min = [Infinity, Infinity, Infinity];- const max = [-Infinity, -Infinity, -Infinity];- const poseBounds = [];- for (const [i, t] of times.entries()) {- poseSceneAtTime(root, prepared, t);- const scene = measureBounds(root);- const subject = opts.shot?.subject ? measureBounds(selectCameraSubject(root, opts.shot.subject).node) : undefined;- poseBounds.push({- phase: frameTimes[i],- timeSeconds: t,- scene,- ...subject ? { subject } : {},- ...measuredParts ? {- parts: measuredParts.map(({ path, name, node }) => ({- path,- name,- bounds: measurePartBounds(node),- origin: worldOrigin(node)- }))- } : {}- });- const b = subject ?? scene;- for (let a = 0;a < 3; a++) {- const lo = b.min[a];- const hi = b.max[a];- if (lo < min[a])- min[a] = lo;- if (hi > max[a])- max[a] = hi;+ let trackCount = 0;+ return envelope.clips.map((candidate) => {+ if (!record9(candidate) || typeof candidate.name !== "string" || candidate.name.length > 256 || typeof candidate.duration !== "number" || !Number.isFinite(candidate.duration) || candidate.duration < 0 || !Array.isArray(candidate.tracks)) {+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review clip.");}- }- const frameBounds = Number.isFinite(min[0]) ? { min, max } : undefined;- poseSceneAtTime(root, prepared, times[0]);- const initialShot = opts.shot ? resolveAssetCamera(root, opts.shot) : undefined;- let lockedCamera = initialShot?.camera;- if (initialShot && opts.shot?.camera?.type !== "explicit" && frameBounds) {- const dir = initialShot.camera.position.map((v, i) => v - initialShot.camera.target[i]);- lockedCamera = cameraFromBounds(frameBounds, dir, opts.shot?.camera?.type === "orbit" ? opts.shot.camera.padding ?? 1.2 : 1.2, initialShot.camera.up);- }- const lens = opts.shot?.camera;- if (lockedCamera && opts.framing !== "follow" && lens?.type === "explicit" && lens.projection === "perspective" && lens.near === undefined) {- const union = { min: [...poseBounds[0].scene.min], max: [...poseBounds[0].scene.max] };- for (const { scene } of poseBounds)- for (let a = 0;a < 3; a++) {- union.min[a] = Math.min(union.min[a], scene.min[a]);- union.max[a] = Math.max(union.max[a], scene.max[a]);+ const tracks = candidate.tracks.map((track) => {+ trackCount++;+ if (trackCount > REVIEW_CLIP_LIMITS.tracks || !record9(track) || typeof track.name !== "string" || track.name.length > 512 || !Array.isArray(track.times) || !Array.isArray(track.values) || track.interpolation !== undefined && track.interpolation !== "LINEAR" && track.interpolation !== "STEP" && !(cubicAllowed && track.interpolation === "CUBICSPLINE") || track.times.length > REVIEW_CLIP_LIMITS.samplesPerTrack || track.values.length > REVIEW_CLIP_LIMITS.valuesPerTrack || !track.times.every((value) => typeof value === "number" && Number.isFinite(value)) || !track.values.every((value) => typeof value === "number" && Number.isFinite(value))) {+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review track.");}- lockedCamera = {- ...lockedCamera,- near: Math.max(0.001, Math.min(lockedCamera.near, boxDistance(lockedCamera.position, union) / 2))- };+ const property = track.name.slice(track.name.lastIndexOf(".") + 1);+ const morph = /^morphTargetInfluences(?:\[[^\]]+\])?$/.test(property);+ const Track = morph ? NumberKeyframeTrack : property === "quaternion" ? QuaternionKeyframeTrack2 : VectorKeyframeTrack2;+ if (track.interpolation === "CUBICSPLINE") {+ const tuple = morph ? track.values.length / track.times.length : cubicTuple(property);+ if (track.times.length < 2 || track.values.length !== track.times.length * tuple || !Number.isInteger(tuple / 3) || tuple < 3) {+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Invalid animation review track.");+ }+ return useCubicSpline(new Track(track.name, track.times, track.values));+ }+ return new Track(track.name, track.times, track.values, track.interpolation === "STEP" ? InterpolateDiscrete2 : InterpolateLinear2);+ });+ return withLoopIntent(new AnimationClip4(candidate.name, candidate.duration, tracks), candidate.loopIntent);+ });+}+function geometryFlatTextureReasonCode(mimeType) {+ return mimeType === "image/ktx2" ? GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED : GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED;+}+function decodedAccessor(accessor) {+ const itemSize = accessor.getElementSize();+ const output = new Float64Array(accessor.getCount() * itemSize);+ const element = [];+ for (let index = 0;index < accessor.getCount(); index++) {+ accessor.getElement(index, element);+ for (let component = 0;component < itemSize; component++) {+ output[index * itemSize + component] = element[component];+ }}- const cameraShots = [];- const labelScale = Math.max(2, Math.round(size / 80));- const cells = [];- const derivativeReceipts = [];- for (let i = 0;i < times.length; i++) {- poseSceneAtTime(root, prepared, times[i]);- const resolvedShot = opts.shot ? resolveAssetCamera(root, opts.shot) : undefined;- if (resolvedShot) {- if (opts.framing !== "follow")- resolvedShot.camera = lockedCamera;- cameraShots.push(resolvedShot);+ return output;+}+function triangleIndices(primitive, vertexCount) {+ const sourceAccessor = primitive.getIndices();+ const source = sourceAccessor ? Array.from(decodedAccessor(sourceAccessor), (value) => Math.trunc(value)) : Array.from({ length: vertexCount }, (_, index) => index);+ switch (primitive.getMode()) {+ case Primitive2.Mode.TRIANGLES:+ return Uint32Array.from(source);+ case Primitive2.Mode.TRIANGLE_STRIP: {+ const triangles = [];+ for (let index = 0;index + 2 < source.length; index++) {+ triangles.push(source[index], source[index + 1 + index % 2], source[index + 2 - index % 2]);+ }+ return Uint32Array.from(triangles);}- let cell;- if (opts.renderDerivativeCell) {- const produce = () => opts.renderDerivativeCell({- root,- ...resolvedShot ? { camera: resolvedShot.camera } : {},- label: `${Math.round(frameTimes[i] * 100)}%`,- view: cam,- size,- ...opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {},- ...frameBounds ? { frameBounds } : {}- });- const rendered = resolvedShot ? await withCameraVisibility(root, resolvedShot, produce) : await produce();- const decoded = decodePng(rendered.png);- if (decoded.width !== size || decoded.height !== size) {- throw new Error(`derivative animation cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`);+ case Primitive2.Mode.TRIANGLE_FAN: {+ const triangles = [];+ for (let index = 1;index + 1 < source.length; index++) {+ triangles.push(source[index], source[index + 1], source[0]);}- cell = decoded.rgb;- derivativeReceipts.push(rendered.receipt);- } else {- cell = resolvedShot ? await withCameraVisibility(root, resolvedShot, async () => rasterizeCamera(root, resolvedShot.camera, size)) : rasterizeView(root, cam.dir, {- size,- ...opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {},- ...frameBounds ? { frameBounds } : {}- });+ return Uint32Array.from(triangles);}- stampLabel(cell, size, size, labelScale, labelScale, `${Math.round(frameTimes[i] * 100)}%`, labelScale);- cells.push(cell);+ default:+ return;}- const baseMeta = {- ok: true,- loopClosure: measureLoopClosure(root, chosen),- clip: prepared.name,- camera: cam.name,- frames: times.length,- frameTimes,- poseBounds,- ...cameraShots.length ? { cameraShots } : {},- duration: prepared.duration,- ...prepared.unresolved.length ? { unresolvedTracks: prepared.unresolved } : {},- ...derivativeReceipts.length ? { derivativeReceipts } : {}- };- if (opts.perFrame) {+}+function flatMaterial(material) {+ if (!material) {return {- ...baseMeta,- width: size,- height: size,- pngs: cells.map((c) => encodePng(c, size, size))+ color: { r: 0.7, g: 0.7, b: 0.7 },+ opacity: 1,+ doubleSided: false,+ metalness: 0,+ roughness: 1,+ alphaMode: "OPAQUE",+ alphaCutoff: 0.5,+ emissive: [0, 0, 0],+ emissiveIntensity: 1};}- const { rgb, width, height } = compositeCellGrid(cells, size);- return { ...baseMeta, width, height, png: encodePng(rgb, width, height) };+ const [r, g, b, factorAlpha] = material.getBaseColorFactor();+ 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,+ alphaCutoff: material.getAlphaCutoff(),+ emissive: material.getEmissiveFactor(),+ emissiveIntensity: material.getExtension("KHR_materials_emissive_strength")?.getEmissiveStrength() ?? 1+ };}-function normalizeVec(v) {- const len = Math.hypot(v[0], v[1], v[2]) || 1;- return [v[0] / len, v[1] / len, v[2] / len];+function preserveTexture(source, usage, cache, info, atlas) {+ if (!source)+ return null;+ const encoded = source.getImage();+ const mime = source.getMimeType();+ if (!encoded || !mime)+ return null;+ let byUsage = cache.get(source);+ if (!byUsage) {+ byUsage = new Map;+ cache.set(source, byUsage);+ }+ const reference = info?.getExtras()["kilnAtlasReference"];+ const cacheKey = `${usage}:${gltfTextureBindingKey(info)}`;+ const existing = byUsage.get(cacheKey);+ if (existing)+ return existing;+ const texture = new Texture4;+ texture.name = source.getName();+ texture.colorSpace = usage === "color" ? SRGBColorSpace6 : NoColorSpace5;+ texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };+ texture.flipY = false;+ if (info)+ restoreGltfTextureBinding(texture, info);+ if (reference && info && atlas)+ restoreAtlasTextureProvenance(texture, info, atlas);+ byUsage.set(cacheKey, texture);+ return texture;}-function dotVec(a, b) {- return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+function noteMaterialTextures(material, reasons) {+ if (!material)+ return;+ const textures = [+ material.getBaseColorTexture(),+ material.getNormalTexture(),+ material.getMetallicRoughnessTexture(),+ material.getEmissiveTexture(),+ material.getOcclusionTexture()+ ];+ for (const texture of textures) {+ if (texture)+ reasons.add(geometryFlatTextureReasonCode(texture.getMimeType()));+ }}-async function renderInteriorGrid(root, opts = {}) {- const size = opts.size ?? 256;- const labelScale = Math.max(2, Math.round(size / 80));- const roofsHidden = opts.nodeName ? hideNodeInScene(root, opts.nodeName) : hideArchitectureRoofInScene(root).nodes.length;- if (opts.capture) {- const grid = await renderCaptureGrid(root, opts.capture, opts.renderDerivativeCell);- return { ...grid, roofsHidden, wallsHidden: 0 };+function instanceMatrices(node) {+ const world = new Matrix418().fromArray(node.getWorldMatrix());+ const extension = node.getExtension("EXT_mesh_gpu_instancing");+ if (!extension)+ return { matrices: [world], count: 1 };+ const attributes = extension.listAttributes();+ if (attributes.length === 0) {+ throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", `Node ${JSON.stringify(node.getName())} has EXT_mesh_gpu_instancing with no attributes.`);}- let wallsHidden = 0;- const cells = [];- const derivativeReceipts = [];- for (const view of INTERIOR_VIEWS) {- if (view.name === "Eye-level") {- const d = normalizeVec(view.dir);- wallsHidden = hideNodeInScene(root, (name) => {- const lower = name.toLowerCase();- for (const w of ROOM_WALL_NORMALS) {- if (lower.endsWith(w.suffix) && dotVec(w.n, d) > 0.2)- return true;- }- return false;- });- }- let cell;- if (opts.renderDerivativeCell) {- const rendered = await opts.renderDerivativeCell({- root,- label: view.name,- view,- size,- backfaceCull: false- });- const decoded = decodePng(rendered.png);- if (decoded.width !== size || decoded.height !== size) {- throw new Error(`derivative interior cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`);+ const count = attributes[0].getCount();+ if (attributes.some((attribute) => attribute.getCount() !== count)) {+ throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", `Node ${JSON.stringify(node.getName())} has mismatched EXT_mesh_gpu_instancing counts.`);+ }+ const translations = extension.getAttribute("TRANSLATION");+ const rotations = extension.getAttribute("ROTATION");+ const scales = extension.getAttribute("SCALE");+ const translation = [];+ const rotation = [];+ const scale = [];+ const matrices = [];+ for (let index = 0;index < count; index++) {+ translations?.getElement(index, translation);+ rotations?.getElement(index, rotation);+ scales?.getElement(index, scale);+ const local = new Matrix418().compose(new Vector340(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion20(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector340(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));+ matrices.push(world.clone().multiply(local));+ }+ return { matrices, count };+}+async function loadGlbGeometryFlatScene(bytes) {+ let document;+ try {+ document = await glbIO().readBinary(Uint8Array.from(bytes));+ } catch (error) {+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Could not parse final GLB bytes: ${error instanceof Error ? error.message : String(error)}`);+ }+ await validateAtlasDocumentProvenance(document);+ const scene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];+ if (!scene)+ throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");+ const reasons = new Set;+ const meshes = [];+ let instanceCount = 0;+ const sceneNodes = new Set;+ const visit = (node) => {+ if (sceneNodes.has(node) || isHiddenGltfNode(node))+ return;+ sceneNodes.add(node);+ for (const child of node.listChildren())+ visit(child);+ };+ for (const child of scene.listChildren())+ visit(child);+ if ([...sceneNodes].some((node) => node.getSkin() || node.getMesh()?.listPrimitives().some((p) => p.listTargets().length))) {+ await validateAtlasDocumentProvenance(document);+ return reviewSceneFromDocument(document);+ }+ for (const node of sceneNodes) {+ const mesh = node.getMesh();+ if (!mesh)+ continue;+ const instances = instanceMatrices(node);+ instanceCount += instances.count;+ for (const primitive of mesh.listPrimitives()) {+ const positionAccessor = primitive.getAttribute("POSITION");+ if (positionAccessor?.getElementSize() !== 3)+ continue;+ const positions = decodedAccessor(positionAccessor);+ const indices = triangleIndices(primitive, positionAccessor.getCount());+ if (!indices) {+ reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);+ continue;+ }+ const material = primitive.getMaterial();+ noteMaterialTextures(material, reasons);+ const geometry = {+ getAttribute(name) {+ return name === "position" ? { array: positions, itemSize: 3, count: positionAccessor.getCount() } : undefined;+ },+ index: { array: indices, itemSize: 1, count: indices.length }+ };+ for (const matrix of instances.matrices) {+ meshes.push({+ isMesh: true,+ visible: true,+ geometry,+ material: flatMaterial(material),+ matrixWorld: { elements: [...matrix.elements] }+ });}- cell = decoded.rgb;- derivativeReceipts.push(rendered.receipt);- } else {- cell = rasterizeView(root, view.dir, { size, backfaceCull: false });}- stampLabel(cell, size, size, labelScale, labelScale, view.name, labelScale);- cells.push(cell);}- const { rgb, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);+ if (meshes.length === 0) {+ throw new GlbGeometryFlatError("GLB_FLAT_NO_RENDERABLE_GEOMETRY", "Final GLB contains no triangle geometry supported by the CPU fallback.");+ }+ const root = {+ updateMatrixWorld() {},+ traverse(callback) {+ for (const mesh of meshes)+ callback(mesh);+ }+ };return {- png: encodePng(rgb, width, height),- width,- height,- views: INTERIOR_VIEWS.map((v) => v.name),- capture: {- preset: "interior",- cols: INTERIOR_VIEWS.length,- cells: INTERIOR_VIEWS.length,- backdrop: DEFAULT_BACKDROP_ID- },- roofsHidden,- wallsHidden,- ...derivativeReceipts.length ? { derivativeReceipts } : {}+ root,+ reasonCodes: REASON_ORDER.filter((reason) => reasons.has(reason)),+ meshCount: meshes.length,+ instanceCount};}-var ANIM_CAMERAS, ANIM_CAMERA_ALIASES, ROOM_WALL_NORMALS, INTERIOR_VIEWS;-var init_views = __esm(() => {- init_capture_limits();- init_background();- init_capture_limits();- init_capture_cache();- init_camera();- init_camera_capture();- init_raster();- init_png();- init_png();- init_grid();- init_annotate();- init_capture();- init_pose();- init_architecture3();- init_glb();- init_evaluator();- init_raster();- init_annotate();- init_background();- init_png();- init_capture();- init_grid();- init_evidence_history();- init_renderer_id();- init_glb();- init_architecture3();- init_scene_raster();- init_diagnostic();- init_character3();- init_vehicle3();- init_pose();- init_capture_cache();- init_camera();- init_camera_capture();- ANIM_CAMERAS = {- front: { name: "Front", dir: [1, 0, 0] },- right: { name: "Right", dir: [0, 0, 1] },- back: { name: "Back", dir: [-1, 0, 0] },- left: { name: "Left", dir: [0, 0, -1] },- top: { name: "Top", dir: [0, 1, 0.0001] },- "three-quarter": { name: "3/4", dir: [0.7, 0.5, 0.7] }- };- ANIM_CAMERA_ALIASES = {- "3/4": "three-quarter",- "34": "three-quarter",- threequarter: "three-quarter",- quarter: "three-quarter",- perspective: "three-quarter",- side: "right",- profile: "right"+function localInstanceMatrices(node) {+ const extension = node.getExtension("EXT_mesh_gpu_instancing");+ if (!extension)+ return [new Matrix418];+ const attributes = extension.listAttributes();+ if (attributes.length === 0) {+ throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Invalid empty instancing data.");+ }+ const count = attributes[0].getCount();+ if (attributes.some((attribute) => attribute.getCount() !== count)) {+ throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Mismatched instancing data.");+ }+ const translations = extension.getAttribute("TRANSLATION");+ const rotations = extension.getAttribute("ROTATION");+ const scales = extension.getAttribute("SCALE");+ const translation = [];+ const rotation = [];+ const scale = [];+ return Array.from({ length: count }, (_, index) => {+ translations?.getElement(index, translation);+ rotations?.getElement(index, rotation);+ scales?.getElement(index, scale);+ return new Matrix418().compose(new Vector340(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion20(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector340(...scales ? scale.slice(0, 3) : [1, 1, 1]));+ });+}+async function loadGlbReviewScene(bytes) {+ let document;+ try {+ document = await glbIO().readBinary(Uint8Array.from(bytes));+ } catch {+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", "Could not parse final GLB bytes.");+ }+ await validateAtlasDocumentProvenance(document);+ return reviewSceneFromDocument(document);+}+function reviewSceneFromDocument(document) {+ const sourceScene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];+ if (!sourceScene)+ throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");+ const reasons = new Set;+ const root = new Group5;+ root.name = sourceScene.getName() || "Scene";+ const nodeMap = new Map;+ const atlas = atlasDocumentTable(document);+ const textureCache = new Map;+ const morphMeshes = new Map;+ const usedNames = new Set(document.getRoot().listNodes().map((node) => node.getName()));+ const nodeIds = new Map(document.getRoot().listNodes().map((node, index) => [node, index]));+ let morphValues = 0;+ const morphError = (detail) => {+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Invalid morph review data: ${detail}`);};- ROOM_WALL_NORMALS = [- { suffix: "wallfront", n: [1, 0, 0] },- { suffix: "wallback", n: [-1, 0, 0] },- { suffix: "wallleft", n: [0, 0, -1] },- { suffix: "wallright", n: [0, 0, 1] }- ];- INTERIOR_VIEWS = [- { name: "Floor plan", dir: [0, 1, 0.0001] },- { name: "Dollhouse", dir: [0.7, 0.5, 0.7] },- { name: "Eye-level", dir: [0.55, 0.35, 0.45] }- ];-});--// src/views/character-capture.ts-import * as THREE53 from "three";-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]);- const y1 = Math.round(to[1]);- const dx = Math.abs(x1 - x0);- const sx = x0 < x1 ? 1 : -1;- const dy = -Math.abs(y1 - y0);- const sy = y0 < y1 ? 1 : -1;- let error = dx + dy;- while (true) {- if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {- const offset = (y0 * width + x0) * 3;- rgb[offset] = color[0];- rgb[offset + 1] = color[1];- rgb[offset + 2] = color[2];- }- if (x0 === x1 && y0 === y1)- break;- const doubled = 2 * error;- if (doubled >= dy) {- error += dy;- x0 += sx;- }- if (doubled <= dx) {- error += dx;- y0 += sy;+ const joints = new Set(document.getRoot().listSkins().flatMap((skin) => skin.listJoints()));+ const pendingSkins = [];+ let meshCount = 0;+ let instanceCount = 0;+ const buildNode = (source) => {+ const existing = nodeMap.get(source);+ if (existing)+ return existing;+ const target = joints.has(source) ? new Bone2 : new Group5;+ target.name = source.getName();+ target.position.fromArray(source.getTranslation());+ target.quaternion.fromArray(source.getRotation());+ target.scale.fromArray(source.getScale());+ target.userData = { ...source.getExtras() };+ if (isHiddenGltfNode(source))+ target.visible = false;+ nodeMap.set(source, target);+ const sourceMesh = source.getMesh();+ if (sourceMesh) {+ const targetCount = sourceMesh.listPrimitives()[0]?.listTargets().length ?? 0;+ if (sourceMesh.listPrimitives().some((p) => p.listTargets().length !== targetCount))+ morphError("primitives must have equal target counts.");+ const nodeWeights = source.getWeights(), meshWeights = sourceMesh.getWeights();+ for (const weights of [nodeWeights, meshWeights])+ if (weights.length && (weights.length !== targetCount || !weights.every(Number.isFinite)))+ morphError("default weight count or values.");+ const weights = nodeWeights.length ? nodeWeights : meshWeights.length ? meshWeights : Array(targetCount).fill(0);+ const targetNames = sourceMesh.listPrimitives()[0]?.listTargets().map((target, index) => target.getName() || String(index)) ?? [];+ target.userData.kilnGlbMeshNode = true;+ const matrices = localInstanceMatrices(source);+ instanceCount += matrices.length;+ for (const [primitiveIndex, primitive] of sourceMesh.listPrimitives().entries()) {+ const position = primitive.getAttribute("POSITION");+ if (position?.getElementSize() !== 3)+ continue;+ const indices = triangleIndices(primitive, position.getCount());+ if (!indices) {+ reasons.add(GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED);+ continue;+ }+ const material = primitive.getMaterial();+ noteMaterialTextures(material, reasons);+ const flat = flatMaterial(material);+ const geometry = new BufferGeometry15;+ const atlasBinding = primitive.getExtras()["kilnAtlasBinding"];+ if (atlasBinding !== undefined && atlas)+ geometry.userData.kilnAtlasBinding = expandAtlasBinding(atlasBinding, atlas);+ geometry.setAttribute("position", new BufferAttribute12(Float32Array.from(decodedAccessor(position)), 3));+ const normal = primitive.getAttribute("NORMAL");+ if (normal) {+ geometry.setAttribute("normal", new BufferAttribute12(Float32Array.from(decodedAccessor(normal)), 3));+ }+ for (let channel = 0;channel < 4; channel++) {+ const uv = primitive.getAttribute(`TEXCOORD_${channel}`);+ if (uv)+ geometry.setAttribute(channel ? `uv${channel}` : "uv", new BufferAttribute12(Float32Array.from(decodedAccessor(uv)), 2));+ }+ const color = primitive.getAttribute("COLOR_0");+ if (color)+ geometry.setAttribute("color", new BufferAttribute12(Float32Array.from(decodedAccessor(color)), color.getElementSize()));+ const tangent = primitive.getAttribute("TANGENT");+ if (tangent) {+ geometry.setAttribute("tangent", new BufferAttribute12(Float32Array.from(decodedAccessor(tangent)), 4));+ }+ geometry.setIndex(new BufferAttribute12(indices, 1));+ if (targetCount) {+ const targets = primitive.listTargets();+ for (const target of targets)+ for (const semantic of target.listSemantics()) {+ const attribute = target.getAttribute(semantic);+ if (!primitive.getAttribute(semantic) || attribute.getCount() !== position.getCount() || (semantic === "POSITION" || semantic === "NORMAL" || semantic === "TANGENT") && attribute.getElementSize() !== 3)+ morphError(`target attribute ${semantic} does not match the base primitive.`);+ if (semantic !== "POSITION" && semantic !== "NORMAL")+ reasons.add(GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED);+ }+ const semantics = targets.some((target) => target.getAttribute("NORMAL")) ? ["POSITION", "NORMAL"] : ["POSITION"];+ morphValues += targetCount * position.getCount() * 3 * semantics.length;+ if (morphValues > 16777216)+ morphError("expanded morph attributes exceed the 64 MiB review budget.");+ geometry.morphTargetsRelative = true;+ for (const semantic of semantics) {+ const attributes = targets.map((target) => {+ const attribute = target.getAttribute(semantic);+ const values = attribute ? Float32Array.from(decodedAccessor(attribute)) : new Float32Array(position.getCount() * 3);+ if (!values.every(Number.isFinite))+ morphError(`nonfinite ${semantic} displacement.`);+ return new BufferAttribute12(values, 3);+ });+ if (semantic === "POSITION")+ geometry.morphAttributes.position = attributes;+ else+ geometry.morphAttributes.normal = attributes;+ }+ }+ if (source.getSkin()) {+ const skinIndices = primitive.getAttribute("JOINTS_0");+ const skinWeights = primitive.getAttribute("WEIGHTS_0");+ if (!skinIndices || !skinWeights || skinIndices.getElementSize() !== 4 || skinWeights.getElementSize() !== 4 || skinIndices.getCount() !== position.getCount() || skinWeights.getCount() !== position.getCount())+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Invalid skin attributes on ${source.getName()}.`);+ if (primitive.getAttribute("JOINTS_1") || primitive.getAttribute("WEIGHTS_1"))+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Skin review supports four influences per vertex; ${source.getName()} has additional joint/weight sets.`);+ geometry.setAttribute("skinIndex", new BufferAttribute12(Uint16Array.from(decodedAccessor(skinIndices)), 4));+ geometry.setAttribute("skinWeight", new BufferAttribute12(Float32Array.from(decodedAccessor(skinWeights)), 4));+ }+ const threeMaterial = new MeshStandardMaterial5({+ vertexColors: color !== null,+ opacity: flat.opacity,+ transparent: flat.alphaMode === "BLEND",+ alphaTest: flat.alphaMode === "MASK" ? flat.alphaCutoff : 0,+ side: flat.doubleSided ? 2 : 0,+ metalness: flat.metalness,+ roughness: flat.roughness+ });+ threeMaterial.color.setRGB(flat.color.r, flat.color.g, flat.color.b);+ threeMaterial.emissive.fromArray(flat.emissive);+ threeMaterial.emissiveIntensity = flat.emissiveIntensity;+ if (material) {+ threeMaterial.userData = { ...material.getExtras() };+ threeMaterial.map = preserveTexture(material.getBaseColorTexture(), "color", textureCache, material.getBaseColorTextureInfo(), atlas);+ threeMaterial.normalMap = preserveTexture(material.getNormalTexture(), "data", textureCache, material.getNormalTextureInfo(), atlas);+ threeMaterial.normalScale.setScalar(material.getNormalScale());+ const metallicRoughness = preserveTexture(material.getMetallicRoughnessTexture(), "data", textureCache, material.getMetallicRoughnessTextureInfo(), atlas);+ threeMaterial.metalnessMap = metallicRoughness;+ threeMaterial.roughnessMap = metallicRoughness;+ threeMaterial.emissiveMap = preserveTexture(material.getEmissiveTexture(), "color", textureCache, material.getEmissiveTextureInfo(), atlas);+ threeMaterial.aoMap = preserveTexture(material.getOcclusionTexture(), "data", textureCache, material.getOcclusionTextureInfo(), atlas);+ threeMaterial.aoMapIntensity = material.getOcclusionStrength();+ }+ for (const [index, matrix] of matrices.entries()) {+ const mesh = source.getSkin() ? new SkinnedMesh2(geometry, threeMaterial) : new Mesh14(geometry, threeMaterial);+ if (mesh instanceof SkinnedMesh2)+ pendingSkins.push({ source, mesh });+ const baseName = source.getName() || sourceMesh.getName() || "Mesh";+ mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;+ if (targetCount) {+ let bindingName = `${PropertyBinding3.sanitizeNodeName(baseName)}_morph_${nodeIds.get(source)}_${primitiveIndex}_${index}`;+ while (usedNames.has(bindingName))+ bindingName += "_";+ usedNames.add(bindingName);+ mesh.name = bindingName;+ mesh.morphTargetInfluences = [...weights];+ if (Array.isArray(targetNames) && targetNames.length === targetCount && targetNames.every((name) => typeof name === "string"))+ mesh.morphTargetDictionary = Object.fromEntries(targetNames.map((name, index) => [name, index]));+ const siblings = morphMeshes.get(source) ?? [];+ siblings.push(mesh);+ morphMeshes.set(source, siblings);+ }+ mesh.matrixAutoUpdate = false;+ mesh.matrix.copy(matrix);+ target.add(mesh);+ meshCount++;+ }+ }}- }-}-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);- const bounds = new THREE53.Box3().setFromObject(root);- if (bounds.isEmpty())- bounds.set(new THREE53.Vector3(-0.5, 0, -0.5), new THREE53.Vector3(0.5, 1, 0.5));- const center = bounds.getCenter(new THREE53.Vector3);- const camera = cameraId === "front" ? new THREE53.Vector3(1, 0, 0) : new THREE53.Vector3(0, 0, 1);- const upHint = new THREE53.Vector3(0, 1, 0);- const xAxis = new THREE53.Vector3().crossVectors(upHint, camera).normalize();- const yAxis = new THREE53.Vector3().crossVectors(camera, xAxis).normalize();- let extent = 0.000001;- for (let corner = 0;corner < 8; corner++) {- const point = new THREE53.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);- extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));- }- const scale = size * 0.45 / extent;- return (assetPoint) => {- const world = new THREE53.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);- return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];- };-}-function skeletonCapture(root, request, findings, size) {- const baseRequest = {- id: request.id,- label: request.label,- cameraId: request.cameraId,- buffer: "semantic-overlay",- scope: "category",- variant: "character-skeleton",- focusRolePrefixes: request.focusRolePrefixes+ for (const child of source.listChildren())+ target.add(buildNode(child));+ return target;};- const frame = renderDiagnosticView(root, baseRequest, { size });- 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, 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,- nodePath: joint.nodePath,- semanticRoles: [`joint.${joint.role}`, ...joint.contact ? ["contact.character"] : []],- pixelBounds: [- Math.max(0, Math.round(point[0]) - 4),- Math.max(0, Math.round(point[1]) - 4),- Math.min(frame.width - 1, Math.round(point[0]) + 4),- Math.min(frame.height - 1, Math.round(point[1]) + 4)- ],- color,- triangleCount: 0- });+ for (const child of sourceScene.listChildren())+ root.add(buildNode(child));+ root.updateMatrixWorld(true);+ if (meshCount === 0)+ throw new GlbGeometryFlatError("GLB_FLAT_NO_RENDERABLE_GEOMETRY", "Final GLB contains no renderable geometry.");+ const sceneMeshCount = meshCount;+ const sceneInstanceCount = instanceCount;+ const sceneReasons = new Set(reasons);+ registerReviewLodChains(root, listLodChainNodes(document).map(({ levels: [base, ...lower] }) => ({+ base: nodeMap.get(base),+ levels: lower.some((level) => nodeMap.has(level)) ? [] : lower.map(buildNode)+ })));+ for (const { source, mesh } of pendingSkins) {+ const skin = source.getSkin();+ const bones = skin.listJoints().map((joint) => nodeMap.get(joint));+ const inverse = skin.getInverseBindMatrices();+ if (!bones.length || bones.some((bone) => !(bone instanceof Bone2)) || inverse && (inverse.getElementSize() !== 16 || inverse.getCount() < bones.length))+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Invalid or unavailable skin joints/bind matrices on ${source.getName()}.`);+ const indices = mesh.geometry.getAttribute("skinIndex");+ const weights = mesh.geometry.getAttribute("skinWeight");+ for (let i = 0;i < indices.array.length; i++)+ if (indices.array[i] >= bones.length || !Number.isFinite(weights.array[i]) || weights.array[i] < 0)+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Invalid skin joint index or weight on ${source.getName()}.`);+ const matrices = bones.map((_, index) => new Matrix418().fromArray(inverse ? inverse.getElement(index, []) : new Matrix418().elements));+ mesh.bind(new Skeleton3(bones, matrices), new Matrix418);}- 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: request.cameraId,- kind: "skeleton",- width: frame.width,- height: frame.height,- png: encodePng(frame.rgb, frame.width, frame.height),- regions: frame.regions- };-}-async function captureCharacterDiagnosticViews(root, clips, requirements, findings = [], size = 256) {- if (!Number.isInteger(size) || size < 1 || size > 2048)- throw new RangeError("Diagnostic size must be an integer from 1 to 2048.");- const transforms = [];- root.traverse((node) => {- transforms.push({- node,- position: node.position.clone(),- quaternion: node.quaternion.clone(),- scale: node.scale.clone()- });- });- const requests = planCharacterDiagnosticRequests(requirements);- const captures = [];- try {- for (const request of requests) {- if (request.variant === "character-skeleton") {- captures.push(skeletonCapture(root, request, findings, size));- continue;- }- if (!request.clipName)- continue;- const strip = await renderClipAnimation(root, clips, {- 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: request.id,- label: request.label,- cameraId: request.cameraId,- kind: "motion-strip",- width: strip.width,- height: strip.height,- png: strip.png,- regions: [],- clipName: request.clipName,- phaseFractions: request.phaseFractions+ root.updateMatrixWorld(true);+ const nativeClips = document.getRoot().listAnimations().map((animation) => withLoopIntent(new AnimationClip4(animation.getName(), -1, animation.listChannels().flatMap((channel) => {+ const node = channel.getTargetNode();+ const path = channel.getTargetPath();+ const sampler = channel.getSampler();+ const input = sampler?.getInput()?.getArray();+ const output = sampler?.getOutput()?.getArray();+ const property = path === "translation" ? "position" : path === "rotation" ? "quaternion" : path;+ if (!node || !property || !input || !output)+ return [];+ const interpolation = sampler.getInterpolation();+ if (interpolation !== "STEP" && interpolation !== "LINEAR" && interpolation !== "CUBICSPLINE") {+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Animation review does not support ${interpolation} interpolation; use LINEAR, STEP or CUBICSPLINE.`);+ }+ if (property === "weights") {+ const targets = morphMeshes.get(node);+ if (!targets?.length)+ return [];+ const width = targets[0].morphTargetInfluences.length;+ const values = decodedAccessor(sampler.getOutput());+ if (input.length < 1 || input.length > REVIEW_CLIP_LIMITS.samplesPerTrack || values.length > REVIEW_CLIP_LIMITS.valuesPerTrack || values.length !== input.length * width * (interpolation === "CUBICSPLINE" ? 3 : 1) || !Array.from(input).every((v, i) => Number.isFinite(v) && v >= 0 && (i === 0 || v > input[i - 1])) || !Array.from(values).every(Number.isFinite))+ morphError("animation weight sampler width or values.");+ return targets.map((mesh) => {+ const track = new NumberKeyframeTrack(`${mesh.name}.morphTargetInfluences`, input, values, interpolation === "STEP" ? InterpolateDiscrete2 : InterpolateLinear2);+ return interpolation === "CUBICSPLINE" ? useCubicSpline(track) : track;});}- } finally {- for (const saved of transforms) {- saved.node.position.copy(saved.position);- saved.node.quaternion.copy(saved.quaternion);- saved.node.scale.copy(saved.scale);+ const Track = path === "rotation" ? QuaternionKeyframeTrack2 : VectorKeyframeTrack2;+ if (interpolation === "CUBICSPLINE") {+ if (input.length < 2 || output.length !== input.length * cubicTuple(property)) {+ throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Animation sampler for ${node.getName()}.${property} is not a valid CUBICSPLINE sampler: it needs at least two keys and three values per key.`);+ }+ return [useCubicSpline(new Track(`${node.getName()}.${property}`, input, output))];+ }+ return [+ new Track(`${node.getName()}.${property}`, input, output, interpolation === "STEP" ? InterpolateDiscrete2 : InterpolateLinear2)+ ];+ })), animation.getExtras().kilnLoopIntent));+ const extrasClips = reviewClipsFromExtras(sourceScene.getExtras());+ if (extrasClips)+ for (const clip of extrasClips)+ clip.tracks = clip.tracks.flatMap((track) => {+ const dot = track.name.lastIndexOf("."), property = track.name.slice(dot + 1);+ if (!/^morphTargetInfluences(?:\[[^\]]+\])?$/.test(property))+ return [track];+ const sources = [...morphMeshes.keys()].filter((node) => node.getName() === track.name.slice(0, dot));+ if (sources.length !== 1)+ return [track];+ return morphMeshes.get(sources[0]).map((mesh) => {+ const copy = new NumberKeyframeTrack(`${mesh.name}.${property}`, track.times, track.values, track.getInterpolation());+ return isCubicSplineTrack(track) ? useCubicSpline(copy) : copy;+ });+ });+ const clips = extrasClips ?? nativeClips;+ return {+ root,+ clips,+ reasonCodes: REASON_ORDER.filter((reason) => sceneReasons.has(reason)),+ meshCount: sceneMeshCount,+ instanceCount: sceneInstanceCount+ };+}+var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO, cubicTuple = (property) => property === "quaternion" ? 12 : 9;+var init_glb = __esm(() => {+ init_animation_cubic();+ init_gltf_texture_binding();+ init_animation_spline();+ init_gltf_io();+ init_lod_export();+ init_metrics();+ init_lod3();+ init_atlas_provenance();+ GLB_GEOMETRY_FLAT_REASON = {+ TEXTURE_SAMPLING_UNSUPPORTED: "GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED",+ KTX2_SAMPLING_UNSUPPORTED: "GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED",+ NON_TRIANGLE_PRIMITIVE_UNSUPPORTED: "GLB_FLAT_NON_TRIANGLE_PRIMITIVE_UNSUPPORTED",+ SKIN_DEFORMATION_UNSUPPORTED: "GLB_FLAT_SKIN_DEFORMATION_UNSUPPORTED",+ MORPH_TARGETS_UNSUPPORTED: "GLB_FLAT_MORPH_TARGETS_UNSUPPORTED"+ };+ REASON_ORDER = [+ GLB_GEOMETRY_FLAT_REASON.KTX2_SAMPLING_UNSUPPORTED,+ GLB_GEOMETRY_FLAT_REASON.TEXTURE_SAMPLING_UNSUPPORTED,+ GLB_GEOMETRY_FLAT_REASON.NON_TRIANGLE_PRIMITIVE_UNSUPPORTED,+ GLB_GEOMETRY_FLAT_REASON.SKIN_DEFORMATION_UNSUPPORTED,+ GLB_GEOMETRY_FLAT_REASON.MORPH_TARGETS_UNSUPPORTED+ ];+ REVIEW_CLIP_LIMITS = {+ clips: 32,+ tracks: 256,+ samplesPerTrack: 4096,+ valuesPerTrack: 16384+ };+ GlbGeometryFlatError = class GlbGeometryFlatError extends Error {+ code;+ constructor(code, message) {+ super(message);+ this.code = code;+ this.name = "GlbGeometryFlatError";}- root.updateMatrixWorld(true);+ };+ glbIO = createGltfIO;+});++// src/evaluator/handler.ts+var init_handler = __esm(() => {+ init_authoring_diagnostic();+ init_solid_diagnostic();+ init_render();+ init_run();+ init_protocol();+});++// src/evaluator/subprocess.ts+var DEFAULT_MAX_GLB_BYTES, DEFAULT_MAX_RESPONSE_BYTES, MAX_STDERR_BYTES;+var init_subprocess = __esm(() => {+ init_authoring_diagnostic();+ init_solid_diagnostic();+ init_run();+ init_requirements_context();+ init_material_library_node();+ init_protocol();+ DEFAULT_MAX_GLB_BYTES = 16 * 1024 * 1024;+ DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;+ MAX_STDERR_BYTES = 16 * 1024;+});+// src/evaluator/isolation.ts+var MAX_READINESS_PROTOCOL_BYTES;+var init_isolation = __esm(() => {+ init_subprocess();+ MAX_READINESS_PROTOCOL_BYTES = 16 * 1024;+});++// src/evaluator/index.ts+var init_evaluator = __esm(() => {+ init_protocol();+ init_handler();+ init_subprocess();+ init_isolation();+});++// src/views/renderer-id.ts+import { readFileSync } from "node:fs";+function engineVersion() {+ for (const path of ["../package.json", "../../package.json"]) {+ try {+ const raw = readFileSync(new URL(path, import.meta.url), "utf8");+ const pkg = JSON.parse(raw);+ if (pkg.name === "@instruktlabs/kiln" && typeof pkg.version === "string" && pkg.version) {+ return pkg.version;+ }+ } catch {}}- return captures;+ return "unknown";}-var rgbFromHex = (value) => {- const parsed = Number.parseInt(value.replace(/^#/, ""), 16);- return [parsed >>> 16 & 255, parsed >>> 8 & 255, parsed & 255];-};-var init_character_capture = __esm(() => {- init_character3();- init_diagnostic();+var CPU_RASTER_RENDERER_ID;+var init_renderer_id = __esm(() => {+ CPU_RASTER_RENDERER_ID = `cpu-raster:${engineVersion()}`;+});++// src/views/scene-raster.ts+import * as THREE52 from "three";+var DEG2;+var init_scene_raster = __esm(() => {+ init_evaluator();+ init_glb();init_png();- init_views();- init_pose();+ init_raster();+ init_scene_copy();+ DEG2 = Math.PI / 180;});-// src/render.ts-import * as THREE54 from "three";-import { Document, Logger } from "@gltf-transform/core";-import { KHRMaterialsEmissiveStrength } from "@gltf-transform/extensions";-import { dedup, instance, palette, weld as weld2, prune, mergeDocuments } from "@gltf-transform/functions";-function applySurfaceBakeExtras(root, doc) {- const baked = [];- root.traverse((node) => {- const mesh = node;- const record = mesh.isMesh ? surfaceBakeRecord(mesh.geometry) : undefined;- if (record && Object.keys(record).length)- baked.push([mesh, { ...record }]);- });- if (baked.length === 0)- return;- const written = writtenNodeResolver(root, doc, "Surface bake export");- for (const [node, record] of baked) {- const mesh = written(node).getMesh();- if (mesh)- mesh.setExtras({ ...mesh.getExtras(), [SURFACE_BAKE_KEY]: record });- }-}-function hiddenTriangles(root, lowerLevels) {- let hidden = 0;- const visit = (node) => {- if (lowerLevels.has(node))- return;- if (node.visible === false) {- hidden += countTriangles(node);- return;- }- for (const child of node.children)- visit(child);- };- visit(root);- return hidden;-}-function ensureDefaultScene(doc) {- const root = doc.getRoot();- const scene = root.getDefaultScene() ?? root.listScenes()[0];- if (scene && !root.getDefaultScene())- root.setDefaultScene(scene);- return scene;-}-async function sha256Hex2(bytes) {- 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);- const root = doc.getRoot();- const explicitDefault = root.getDefaultScene();- const scene = explicitDefault ?? root.listScenes()[0];- if (!scene)- return;- const { min, max } = drawnSceneBounds(scene);- const finiteBounds = min.every(Number.isFinite) && max.every(Number.isFinite);- if (!finiteBounds)- return;- const metrics = collectGlbMetrics(doc);- const validation = opts.validation ?? await validateFinalGlbBytes(bytes);- const scenes = root.listScenes();- const minTuple = [min[0], min[1], min[2]];- const maxTuple = [max[0], max[1], max[2]];- const minY = minTuple[1];- const levelsOfDetail = summarizeLodChains(doc);- const hiddenNodes = summarizeHiddenNodes(doc);- const delivery = inspectDelivery(doc);- const vertexAttributes = summarizeVertexAttributes(doc);- const budgetDeclaration = readBudgetDeclaration(scene.getExtras()[KILN_BUDGET_KEY]);- const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, { triangles: metrics.triangles, draws: metrics.drawCalls }, levelsOfDetail) : undefined;- const paletteDeclaration = readPaletteDeclaration(scene.getExtras()[KILN_PALETTE_KEY]);- const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;- return {- schemaVersion: "kiln.integration-manifest.v1",- analyzerVersion: 1,- artifactSha256: await sha256Hex2(bytes),- units: "m",- axes: { forward: "+X", up: "+Y", right: "+Z" },- bounds: {- min: minTuple,- max: maxTuple,- size: [maxTuple[0] - minTuple[0], maxTuple[1] - minTuple[1], maxTuple[2] - minTuple[2]],- center: [- (minTuple[0] + maxTuple[0]) / 2,- (minTuple[1] + maxTuple[1]) / 2,- (minTuple[2] + maxTuple[2]) / 2- ]- },- pivot: { convention: "author-origin", position: [0, 0, 0] },- ground: {- groundY: 0,- contactTolerance: GROUND_CONTACT_TOLERANCE,- minY,- offsetToGround: -minY,- grounded: Math.abs(minY) <= GROUND_CONTACT_TOLERANCE- },- defaultScene: { index: scenes.indexOf(scene), name: scene.getName() },- ...opts.requestedRole ? { requestedRole: opts.requestedRole } : {},- ...opts.assessedRole ? { assessedRole: opts.assessedRole } : {},- renderMetrics: {- triangles: metrics.triangles,- drawCalls: metrics.drawCalls,- uniqueGeometries: metrics.uniqueGeometries,- uniqueMaterials: metrics.uniqueMaterials,- textureCount: metrics.textureCount,- transparentMaterials: metrics.transparentMaterials,- skinned: metrics.skinned+// src/views/vehicle.ts+import * as THREE53 from "three";+function hasRole2(node, prefix) {+ return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;+}+function chassisBounds(root, inverse) {+ const bounds = new THREE53.Box3;+ let found = false;+ root.traverse((node) => {+ if (!hasRole2(node, "chassis"))+ return;+ node.traverse((part) => {+ if (!(part instanceof THREE53.Mesh) || !(part.geometry instanceof THREE53.BufferGeometry))+ return;+ part.geometry.computeBoundingBox();+ const box = part.geometry.boundingBox;+ if (!box)+ return;+ 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 z of [box.min.z, box.max.z]) {+ bounds.expandByPoint(new THREE53.Vector3(x, y, z).applyMatrix4(matrix));+ found = true;+ }+ });+ });+ return found ? bounds : undefined;+}+function describeVehicleDiagnostics(root) {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const assemblies = resolveVehicleWheelAssemblies(root);+ const wheels = assemblies.map((wheel) => ({+ id: wheel.id,+ center: tuple7(wheel.centerWorld.clone().applyMatrix4(inverse)),+ radius: wheel.radius ?? 0,+ width: wheel.width ?? 0,+ axle: tuple7(wheel.spinAxisWorld.clone().transformDirection(inverse)),+ loadBearing: wheel.loadBearing+ }));+ const byAxle = new Map;+ for (let index = 0;index < assemblies.length; index++) {+ const key = assemblies[index].index ?? assemblies[index].id;+ const group = byAxle.get(key) ?? [];+ group.push(wheels[index]);+ byAxle.set(key, group);+ }+ const axles = [...byAxle].flatMap(([id, members]) => {+ if (members.length < 2)+ return [];+ const sorted = [...members].sort((a, b) => a.center[2] - b.center[2]);+ return [{ id, start: sorted[0].center, end: sorted.at(-1).center }];+ });+ const contacts = wheels.filter((wheel) => wheel.loadBearing && wheel.radius > 0).map((wheel) => wheel.center[1] - wheel.radius);+ const supportPlaneY = contacts.length > 0 ? contacts.reduce((sum, value) => sum + value, 0) / contacts.length : undefined;+ const chassis = chassisBounds(root, inverse);+ const views = [+ { id: "vehicle.front-direction", label: "+X front and chassis", cameraDirection: [1, 0.15, 0] },+ {+ id: "vehicle.axles.top",+ label: "Chassis and axle projection",+ cameraDirection: [0.001, 1, 0]},- ...levelsOfDetail.length ? { levelsOfDetail } : {},- ...hiddenNodes.length ? { hiddenNodes } : {},- ...delivery.colliders.length ? { colliders: delivery.colliders } : {},- ...delivery.anchors.length ? { anchors: delivery.anchors } : {},- ...delivery.kit ? { kit: delivery.kit } : {},- ...delivery.ports.length ? { ports: delivery.ports } : {},- ...budget ? { budget } : {},- ...palette ? { palette } : {},- ...vertexAttributes.length ? { vertexAttributes } : {},- ...delivery.diagnostics.length ? { deliveryDiagnostics: delivery.diagnostics } : {},- structuralQa: {- hasDefaultScene: explicitDefault !== null,- finiteBounds,- validatorErrors: validation.issues.numErrors,- validatorWarnings: validation.issues.numWarnings+ {+ id: "vehicle.underbody",+ label: "Underbody support plane",+ cameraDirection: [-0.3, -0.8, 0.5]},- visualQa: "not_assessed"+ ...wheels.slice(0, 2).map((wheel) => ({+ id: `vehicle.wheel-section.${wheel.id.replace(/[^a-zA-Z0-9.-]/g, "-")}`,+ label: `Wheel section ${wheel.id}`,+ cameraDirection: [0, 0, wheel.center[2] < 0 ? -1 : 1],+ focus: wheel.id+ }))+ ];+ return {+ schemaVersion: 1,+ forwardArrow: { start: [0, 0, 0], end: [1, 0, 0] },+ ...chassis ? { chassisBox: { min: tuple7(chassis.min), max: tuple7(chassis.max) } } : {},+ axles,+ wheels,+ ...supportPlaneY !== undefined ? { supportPlaneY } : {},+ views};}-async function executeKilnCode(code, options = {}) {- if (!code || typeof code !== "string") {- throw new Error("executeKilnCode: code must be a non-empty string");+function tagDiagnostic(node, role) {+ stampSemanticMetadataV1(node, { roles: [role] });+}+function rod(name, start, end, radius, color, role) {+ const from = new THREE53.Vector3(...start);+ const to = new THREE53.Vector3(...end);+ const direction = to.clone().sub(from);+ const length = direction.length();+ const geometry = length > 0.000000001 ? new THREE53.CylinderGeometry(radius, radius, length, 8) : new THREE53.SphereGeometry(radius, 8, 6);+ const result = new THREE53.Mesh(geometry, new THREE53.MeshBasicMaterial({ color }));+ result.name = name;+ result.position.copy(from).add(to).multiplyScalar(0.5);+ if (length > 0.000000001) {+ result.quaternion.setFromUnitVectors(new THREE53.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}- const normalized = code.replace(/\r\n/g, `-`);- assertGeneratedSourceSafe(normalized);- try {- const primitiveUsage = {};- const globals = buildSandboxGlobals(primitiveUsage, {- textureResolver: options.textureResolver ?? DEFAULT_TEXTURE_RESOLVER,- console: options.console- });- const globalNames = Object.keys(globals);- const globalValues = Object.values(globals);- const fn = new Function(...globalNames, `'use strict';-${normalized}-return { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof animate !== 'undefined' ? animate : null };`);- const { meta, build, animate } = fn(...globalValues);- if (typeof build !== "function") {- throw new AuthoringDiagnosticError("BUILD_RESULT", "executeKilnCode: generated code did not define `build`");+ tagDiagnostic(result, role);+ return result;+}+function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {+ const overlay = new THREE53.Group;+ overlay.name = "VehicleDiagnosticOverlay";+ 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 THREE53.Group;+ arrow.name = "Diagnostic_Forward_+X";+ tagDiagnostic(arrow, "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 THREE53.Mesh(new THREE53.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE53.MeshBasicMaterial({ color: 16724804 }));+ arrowHead.name = "Diagnostic_Forward_Head";+ arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);+ arrowHead.quaternion.setFromUnitVectors(new THREE53.Vector3(0, 1, 0), new THREE53.Vector3(1, 0, 0));+ tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");+ arrow.add(arrowHead);+ overlay.add(arrow);+ 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 descriptor.wheels) {+ const ring = new THREE53.Mesh(new THREE53.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE53.MeshBasicMaterial({ color: 16763955 }));+ ring.name = `Diagnostic_Wheel_${wheel.id}`;+ ring.position.set(...wheel.center);+ const axle = new THREE53.Vector3(...wheel.axle);+ if (axle.lengthSq() > 0.000000000001) {+ ring.quaternion.setFromUnitVectors(new THREE53.Vector3(0, 0, 1), axle.normalize());}- const root = await build();- if (!root?.isObject3D) {- throw new AuthoringDiagnosticError("BUILD_RESULT", "executeKilnCode: build() did not return a THREE.Object3D");+ tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);+ overlay.add(ring);+ }+ if (descriptor.chassisBox) {+ const chassis = new THREE53.Group;+ chassis.name = "Diagnostic_ChassisBox";+ tagDiagnostic(chassis, "diagnostic.vehicle.chassis");+ const { min, max } = descriptor.chassisBox;+ const corners = [+ [min[0], min[1], min[2]],+ [max[0], min[1], min[2]],+ [max[0], max[1], min[2]],+ [min[0], max[1], min[2]],+ [min[0], min[1], max[2]],+ [max[0], min[1], max[2]],+ [max[0], max[1], max[2]],+ [min[0], max[1], max[2]]+ ];+ const edges = [+ [0, 1],+ [1, 2],+ [2, 3],+ [3, 0],+ [4, 5],+ [5, 6],+ [6, 7],+ [7, 4],+ [0, 4],+ [1, 5],+ [2, 6],+ [3, 7]+ ];+ for (const [index, edge] of edges.entries()) {+ chassis.add(rod(`Diagnostic_ChassisEdge_${index}`, corners[edge[0]], corners[edge[1]], thickness, 5635959, "diagnostic.vehicle.chassis"));}- const declared = globals[SANDBOX_DECLARATIONS];- if (declared?.budget && root.userData[KILN_BUDGET_KEY] === undefined)- root.userData[KILN_BUDGET_KEY] = declared.budget;- if (declared?.palette && root.userData[KILN_PALETTE_KEY] === undefined)- root.userData[KILN_PALETTE_KEY] = declared.palette;- const clips = animate ? await animate(root) ?? [] : [];- return { meta: meta ?? {}, root, clips, primitiveUsage };- } catch (error) {- rethrowAuthoringError(error);+ overlay.add(chassis);+ }+ if (descriptor.supportPlaneY !== undefined) {+ const plane = new THREE53.Group;+ plane.name = "Diagnostic_SupportPlane";+ tagDiagnostic(plane, "diagnostic.vehicle.support-plane");+ 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],+ [halfX, y, -halfZ]+ ],+ [+ [halfX, y, -halfZ],+ [halfX, y, halfZ]+ ],+ [+ [halfX, y, halfZ],+ [-halfX, y, halfZ]+ ],+ [+ [-halfX, y, halfZ],+ [-halfX, y, -halfZ]+ ],+ [+ [-halfX, y, 0],+ [halfX, y, 0]+ ],+ [+ [0, y, -halfZ],+ [0, y, halfZ]+ ]+ ];+ for (const [index, [start, end]] of planeLines.entries()) {+ plane.add(rod(`Diagnostic_SupportLine_${index}`, start, end, thickness * 0.7, 6750207, "diagnostic.vehicle.support-plane"));+ }+ overlay.add(plane);+ }+ return overlay;+}+function compositeForCapture(root, overlay) {+ if (root.matrixAutoUpdate === false) {+ overlay.matrix.copy(root.matrix);+ overlay.matrixAutoUpdate = false;+ } else {+ overlay.position.copy(root.position);+ overlay.quaternion.copy(root.quaternion);+ overlay.scale.copy(root.scale);}+ return {+ name: "VehicleDiagnosticCaptureRoot",+ type: "Group",+ visible: true,+ position: { x: 0, y: 0, z: 0 },+ quaternion: { x: 0, y: 0, z: 0, w: 1 },+ scale: { x: 1, y: 1, z: 1 },+ children: [root, overlay]+ };+}+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, "-");+ return {+ ...requestValue,+ id: `vehicle.wheel-section.${suffix}`,+ label: `Vehicle wheel section ${target.id}`,+ focusRolePrefixes: [target.id]+ };}-function bridgeEmissive(doc, target, source) {- const color = source.emissive;+function captureVehicleDiagnosticViews(root, size = 256) {+ if (!Number.isInteger(size) || size < 1 || size > 2048)+ throw new RangeError("Diagnostic size must be an integer from 1 to 2048; category/intent selection is retired.");+ const descriptor = describeVehicleDiagnostics(root);+ const overlay = createVehicleDiagnosticOverlay(root, descriptor);+ const composite = compositeForCapture(root, overlay);+ const requests = MOBILITY_DIAGNOSTIC_REQUESTS;+ return requests.map((baseRequest) => {+ const requestValue = baseRequest.variant === "vehicle-wheel-section" ? selectWheelSectionRequest(baseRequest, descriptor) : baseRequest;+ const frame = renderDiagnosticView(composite, requestValue, { size });+ return {+ id: frame.id,+ label: frame.label,+ cameraId: frame.camera.id,+ kind: requestValue.variant === "vehicle-underbody" ? "underbody" : "wheel-section",+ buffer: "semantic-overlay",+ width: frame.width,+ height: frame.height,+ png: frame.png,+ regions: frame.regions,+ descriptor+ };+ });+}+var tuple7 = (value) => [value.x, value.y, value.z];+var init_vehicle3 = __esm(() => {+ init_contracts();+ init_vehicle();+ init_diagnostic();+});++// src/views/index.ts+function setLinearColor(color, rgb) {if (!color)return;- const intensity = source.emissiveIntensity ?? 1;- const scale = Number.isFinite(intensity) ? Math.max(0, intensity) : 1;- const emitted = [color.r * scale, color.g * scale, color.b * scale];- const peak = Math.max(...emitted);- if (!(peak > 1)) {- target.setEmissiveFactor(emitted);+ color.r = rgb[0];+ color.g = rgb[1];+ color.b = rgb[2];+}+function snapMaterialToPalette(mat, slots, idx) {+ if (!mat.color)return;+ if (mat.map || mat.vertexColors)+ return false;+ const emissive = mat.emissive && (mat.emissiveIntensity ?? 1) > 0 ? [+ mat.emissive.r * (mat.emissiveIntensity ?? 1),+ mat.emissive.g * (mat.emissiveIntensity ?? 1),+ mat.emissive.b * (mat.emissiveIntensity ?? 1)+ ] : undefined;+ const slotI = chooseSlot(idx, {+ baseLinear: [mat.color.r, mat.color.g, mat.color.b],+ ...emissive ? { emissiveLinear: emissive } : {},+ transparent: mat.transparent === true || mat.opacity !== undefined && mat.opacity < 0.98+ });+ if (slotI === undefined)+ return false;+ const slot = slots[slotI];+ const kind = slot.kind ?? "opaque";+ const rgb = hexToLinearRgb(slot.color);+ setLinearColor(mat.color, rgb);+ if (mat.metalness !== undefined)+ mat.metalness = slot.metalness ?? 0;+ if (mat.roughness !== undefined)+ mat.roughness = slot.roughness ?? (kind === "glass" ? 0.1 : 0.85);+ if (kind === "glass") {+ mat.transparent = true;+ mat.opacity = slot.opacity ?? 0.4;+ } else {+ if (mat.transparent !== undefined)+ mat.transparent = false;+ if (mat.opacity !== undefined)+ mat.opacity = 1;}- target.setEmissiveFactor([emitted[0] / peak, emitted[1] / peak, emitted[2] / peak]);- target.setExtension("KHR_materials_emissive_strength", doc.createExtension(KHRMaterialsEmissiveStrength).createEmissiveStrength().setEmissiveStrength(peak));-}-function bridgeTextureSampler(source, target, atlas) {- const min = GLTF_MIN_FILTER[source.minFilter];- const mag = GLTF_MAG_FILTER[source.magFilter];- const s = GLTF_WRAP[source.wrapS];- const t = GLTF_WRAP[source.wrapT];- for (const [property, value] of [- ["minFilter", min],- ["magFilter", mag],- ["wrapS", s],- ["wrapT", t]- ]) {- if (typeof source[property] !== "number" || value === undefined) {- throw new TypeError(`${source.name || "(unnamed texture)"}: unsupported ${property} ${source[property]}`);+ if (mat.emissive) {+ if (kind === "glow") {+ setLinearColor(mat.emissive, rgb);+ mat.emissiveIntensity = Math.max(mat.emissiveIntensity ?? 1, 1);+ } else {+ setLinearColor(mat.emissive, [0, 0, 0]);+ if (mat.emissiveIntensity !== undefined)+ mat.emissiveIntensity = 0;}}- target.setMinFilter(min).setMagFilter(mag).setWrapS(s).setWrapT(t);- if (source.channel === 1)- target.setTexCoord(1);- const ref = atlas?.texture(source);- if (ref)- target.setExtras({ ...target.getExtras(), kilnAtlasReference: ref });+ return true;}-function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas) {- const cached = cache.get(threeMat);- if (cached)- return cached;- const mat = doc.createMaterial(threeMat.name || undefined);- const author = authorExtras?.material(threeMat);- if (author)- mat.setExtras(author);- const matFlags = threeMat;- if (matFlags.isMeshStandardMaterial) {- const stdMat = threeMat;- mat.setBaseColorFactor([stdMat.color.r, stdMat.color.g, stdMat.color.b, stdMat.opacity]);- mat.setRoughnessFactor(stdMat.roughness);- mat.setMetallicFactor(stdMat.metalness);- bridgeEmissive(doc, mat, stdMat);- if (stdMat.alphaTest > 0) {- mat.setAlphaMode("MASK");- mat.setAlphaCutoff(stdMat.alphaTest);- } else if (stdMat.transparent) {- mat.setAlphaMode("BLEND");- }- if (stdMat.side === THREE54.DoubleSide) {- mat.setDoubleSided(true);- }- if (stdMat.map) {- const t = bridgeTexture(doc, stdMat.map, textureCache);- if (t) {- mat.setBaseColorTexture(t);- bridgeTextureSampler(stdMat.map, mat.getBaseColorTextureInfo(), atlas);- }- }- if (stdMat.normalMap) {- const t = bridgeTexture(doc, stdMat.normalMap, textureCache);- if (t) {- mat.setNormalTexture(t);- bridgeTextureSampler(stdMat.normalMap, mat.getNormalTextureInfo(), atlas);- }- }- if (stdMat.roughnessMap && stdMat.metalnessMap && stdMat.roughnessMap !== stdMat.metalnessMap) {- throw new TypeError(`Material ${JSON.stringify(threeMat.name || "(unnamed)")} uses separate roughness/metalness textures. Pack G=roughness/B=metalness before export.`);- }- const mrSource = stdMat.roughnessMap ?? stdMat.metalnessMap;- if (mrSource) {- const t = bridgeTexture(doc, mrSource, textureCache);- if (t) {- mat.setMetallicRoughnessTexture(t);- bridgeTextureSampler(mrSource, mat.getMetallicRoughnessTextureInfo(), atlas);- }- }- if (stdMat.emissiveMap) {- const t = bridgeTexture(doc, stdMat.emissiveMap, textureCache);- if (t) {- mat.setEmissiveTexture(t);- bridgeTextureSampler(stdMat.emissiveMap, mat.getEmissiveTextureInfo(), atlas);- }- }- if (stdMat.aoMap) {- const t = bridgeTexture(doc, stdMat.aoMap, textureCache);- if (t) {- mat.setOcclusionTexture(t);- bridgeTextureSampler(stdMat.aoMap, mat.getOcclusionTextureInfo(), atlas);- }- mat.setOcclusionStrength(stdMat.aoMapIntensity ?? 1);- }- } else if (matFlags.isMeshLambertMaterial) {- const lambMat = threeMat;- mat.setBaseColorFactor([lambMat.color.r, lambMat.color.g, lambMat.color.b, lambMat.opacity]);- mat.setRoughnessFactor(1);- mat.setMetallicFactor(0);- bridgeEmissive(doc, mat, lambMat);- } else if (matFlags.isMeshBasicMaterial) {- const basicMat = threeMat;- mat.setBaseColorFactor([- basicMat.color.r,- basicMat.color.g,- basicMat.color.b,- basicMat.opacity- ]);- mat.setRoughnessFactor(1);- mat.setMetallicFactor(0);- } else if (matFlags.isSpriteMaterial) {- const spriteMat = threeMat;- mat.setBaseColorFactor([- spriteMat.color.r,- spriteMat.color.g,- spriteMat.color.b,- spriteMat.opacity- ]);- mat.setRoughnessFactor(1);- mat.setMetallicFactor(0);- }- const common = threeMat;- if ((common.alphaTest ?? 0) > 0) {- mat.setAlphaMode("MASK");- mat.setAlphaCutoff(common.alphaTest ?? 0.5);- } else if (common.transparent || (common.opacity ?? 1) < 1) {- mat.setAlphaMode("BLEND");- }- if (threeMat.side === THREE54.DoubleSide)- mat.setDoubleSided(true);- if (common.map && !mat.getBaseColorTexture()) {- const texture = bridgeTexture(doc, common.map, textureCache);- if (texture) {- mat.setBaseColorTexture(texture);- bridgeTextureSampler(common.map, mat.getBaseColorTextureInfo(), atlas);+function snapSceneToPalette(root, slots) {+ if (slots.length === 0)+ return { snapped: 0, skipped: 0 };+ const traverse = root?.traverse;+ if (!traverse)+ return { snapped: 0, skipped: 0 };+ const idx = buildSlotIndex(slots);+ let snapped = 0;+ let skipped = 0;+ traverse.call(root, (obj) => {+ if (!obj.isMesh || !obj.material)+ return;+ const materials = Array.isArray(obj.material) ? obj.material : [obj.material];+ for (const mat of materials) {+ const didSnap = snapMaterialToPalette(mat, slots, idx);+ if (didSnap === true)+ snapped++;+ else if (didSnap === false)+ skipped++;}+ });+ return { snapped, skipped };+}+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 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 = resolved.zooms.some((z) => z !== undefined);+ const sceneBounds = wantsZoom ? measureBounds(root) : undefined;+ const backdrop = opts.backdrop ?? resolved.backdrop;+ const cache = opts.snapPalette?.length ? undefined : opts.captureCache;+ let reused = 0;+ const cells = [];+ for (let vi = 0;vi < views.length; vi++) {+ const zoom = resolved.zooms[vi];+ const rasterOptions = {+ size,+ backfaceCull: opts.backfaceCull,+ backdrop,+ ...opts.frameBounds ? { frameBounds: opts.frameBounds } : {},+ ...sceneBounds && zoom !== undefined ? { frameBounds: expandFrameBounds(sceneBounds, zoom) } : {}+ };+ let cell;+ if (cache && opts.artifactGlbSha256) {+ 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_ID}/legacy-fit`,+ camera: camera2,+ size,+ backfaceCull: opts.backfaceCull ?? true,+ backdrop+ }, async () => ({+ png: encodePng(rasterizeView(root, views[vi].dir, rasterOptions), size, size),+ width: size,+ height: size,+ inputGlbSha256: opts.artifactGlbSha256,+ reasonCodes: [],+ meshCount: 0,+ instanceCount: 0+ }));+ if (result.captureCache?.hit)+ reused++;+ cell = decodePng(result.png).rgb;+ } else+ cell = rasterizeView(root, views[vi].dir, rasterOptions);+ annotateViewCell(cell, size, views[vi]);+ cells.push(cell);}- cache.set(threeMat, mat);- return mat;+ 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: resolved.preset, cols, cells: views.length, backdrop },+ ...cache && opts.artifactGlbSha256 ? { captureCache: { hit: reused === views.length, reused, total: views.length } } : {}+ };}-function bridgeTexture(doc, threeTex, cache) {- const cached = cache.get(threeTex);- if (cached)- return cached;- const encoded = threeTex.userData["encoded"];- if (!encoded)- return null;- const t = doc.createTexture(threeTex.name || "texture");- t.setMimeType(encoded.mime);- t.setImage(encoded.bytes);- cache.set(threeTex, t);- return t;+async function hashGlbViewInput(bytes) {+ const copy = Uint8Array.from(bytes);+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", copy));+ return `sha256:${[...digest].map((value) => value.toString(16).padStart(2, "0")).join("")}`;}-function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {- if (!geometry.getAttribute("normal")) {- geometry.computeVertexNormals();- }- const prim = doc.createPrimitive().setMaterial(Array.isArray(material) ? material[0] : material);- const posAttr = geometry.getAttribute("position");- if (posAttr) {- prim.setAttribute("POSITION", doc.createAccessor(`${meshName}_pos`).setArray(geometryAttributeValues(posAttr)).setType(TYPE_VEC3).setBuffer(buf));- }- const normAttr = geometry.getAttribute("normal");- if (normAttr) {- prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(unitNormalValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));- }- const uvAttr = geometry.getAttribute("uv");- if (uvAttr) {- prim.setAttribute("TEXCOORD_0", doc.createAccessor(`${meshName}_uv`).setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));- }- const uv1Attr = geometry.getAttribute("uv1");- if (uv1Attr) {- prim.setAttribute("TEXCOORD_1", doc.createAccessor(`${meshName}_uv1`).setArray(geometryAttributeValues(uv1Attr)).setType(TYPE_VEC2).setBuffer(buf));- }- 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 colorAttr = geometry.getAttribute("color");- if (colorAttr?.itemSize === 3 || colorAttr?.itemSize === 4) {- prim.setAttribute("COLOR_0", doc.createAccessor(`${meshName}_color`).setArray(geometryAttributeValues(colorAttr)).setType(colorAttr.itemSize === 4 ? TYPE_VEC4 : TYPE_VEC3).setBuffer(buf));+async function renderGlbViewCell(bytes, view, options = {}) {+ const exactBytes = Uint8Array.from(bytes);+ const loaded = await loadGlbGeometryFlatScene(exactBytes);+ const size = options.size ?? 256;+ const rgb = options.camera ? rasterizeCamera(loaded.root, options.camera, size, options.backfaceCull, options.backdrop) : rasterizeView(loaded.root, view.dir, {+ size,+ ...options.backdrop ? { backdrop: options.backdrop } : {},+ ...options.backfaceCull !== undefined ? { backfaceCull: options.backfaceCull } : {},+ ...options.frameBounds ? { frameBounds: options.frameBounds } : {}+ });+ return {+ png: encodePng(rgb, size, size),+ width: size,+ height: size,+ inputGlbSha256: await hashGlbViewInput(exactBytes),+ reasonCodes: loaded.reasonCodes,+ meshCount: loaded.meshCount,+ instanceCount: loaded.instanceCount+ };+}+async function renderGlbViewGrid(bytes, options = {}) {+ const exactBytes = Uint8Array.from(bytes);+ const loaded = options.capture?.version || options.capture?.shots ? await loadGlbReviewScene(exactBytes) : await loadGlbGeometryFlatScene(exactBytes);+ const artifactGlbSha256 = await hashGlbViewInput(exactBytes);+ const grid = await renderViewGrid(loaded.root, { ...options, artifactGlbSha256 });+ return {+ ...grid,+ inputGlbSha256: await hashGlbViewInput(exactBytes),+ reasonCodes: loaded.reasonCodes,+ meshCount: loaded.meshCount,+ instanceCount: loaded.instanceCount+ };+}+function expandFrameBounds(b, factor) {+ const min = [0, 0, 0];+ const max = [0, 0, 0];+ for (let a = 0;a < 3; a++) {+ const center = (b.min[a] + b.max[a]) / 2;+ const half = (b.max[a] - b.min[a]) / 2 * factor;+ min[a] = center - half;+ max[a] = center + half;}- const customKeys = [- ...Object.keys(CUSTOM_EXPORT_ATTRIBUTES),- ...Object.keys(geometry.attributes).filter((key) => !(key in CUSTOM_EXPORT_ATTRIBUTES)).sort()- ];- for (const key of customKeys) {- const gltfName = customAttributeSemantic(key);- const custom = geometry.getAttribute(key);- if (!gltfName || !custom || custom.itemSize < 1 || custom.itemSize > 4)- continue;- prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(ACCESSOR_TYPES[custom.itemSize - 1]).setBuffer(buf));+ return { min, max };+}+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"];+}+function worldOrigin(node) {+ const e = node.matrixWorld.elements;+ return [e[12], e[13], e[14]];+}+function boxDistance(point, box) {+ let sum = 0;+ for (let a = 0;a < 3; a++) {+ const d = Math.max(box.min[a] - point[a], 0, point[a] - box.max[a]);+ sum += d * d;}- 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));+ return Math.sqrt(sum);+}+async function renderClipAnimation(root, clips, opts = {}) {+ const size = opts.size ?? 256;+ const frameCount = Math.max(2, Math.min(opts.frames ?? 6, 6));+ const cam = resolveCamera(opts.camera);+ if (!clips || clips.length === 0) {+ return {+ ok: false,+ frames: 0,+ frameTimes: [],+ error: "this asset has no animation clips",+ availableClips: []+ };}- const binding = atlas?.binding(geometry);- if (binding)- prim.setExtras({ kilnAtlasBinding: binding });- const mesh = doc.createMesh(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 = validateMaterialGroups(geometry, material.length, meshName);- for (const group of groups) {- const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);- 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));- if (binding)- part.setExtras({ kilnAtlasBinding: binding });- mesh.addPrimitive(part);+ const requested = opts.clip?.trim();+ const chosen = requested ? findClip(clips, requested) : clips[0];+ if (!chosen) {+ return {+ ok: false,+ frames: 0,+ frameTimes: [],+ ...requested ? { clip: requested } : {},+ error: `clip "${requested}" not found in this asset`,+ availableClips: clipNames(clips)+ };}- prim.dispose();- return mesh;-}-function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache, authorExtras, atlas) {- const gtNode = doc.createNode(threeObj.name || undefined);- const semanticValue = threeObj.userData[KILN_SEMANTIC_EXTRAS_KEY];- const extras = {- ...authorExtras?.node(threeObj),- ...rigExtrasForExport(threeObj),- ...openShellExtras(threeObj),- ...kitExtras(threeObj),- ...repeatInstancesExtras(threeObj)- };- let semanticForExport = semanticValue;- if (threeObj.isSprite) {- if (semanticValue === undefined) {- semanticForExport = createSemanticMetadataV1({- roles: ["vfx.facing.camera-spherical", "vfx.effect.surface.card"]- });- } else {- const existing = validateSemanticMetadataV1(semanticValue);- if (existing.valid && existing.value) {- semanticForExport = {- ...cloneSemanticMetadataV1(existing.value),- roles: [- ...existing.value.roles.filter((role) => !role.startsWith("vfx.facing.")),- "vfx.facing.camera-spherical",- ...existing.value.roles.some((role) => role.startsWith("vfx.effect.surface")) ? [] : ["vfx.effect.surface.card"]- ]- };- }+ const prepared = prepareClip(root, chosen);+ if (opts.frameTimes && opts.frames !== undefined)+ throw new Error("frameTimes and frames are mutually exclusive");+ if (opts.shot && opts.camera)+ throw new Error("shot and camera are mutually exclusive");+ if (opts.frameTimes && (opts.frameTimes.length < 1 || opts.frameTimes.length > 9 || opts.frameTimes.some((v, i) => !Number.isFinite(v) || v < 0 || v > 1 || i > 0 && v <= opts.frameTimes[i - 1])))+ throw new Error("frameTimes must contain 1..9 strictly increasing phases in 0..1");+ const times = opts.frameTimes ? opts.frameTimes.map((t) => t * prepared.duration) : planFrameTimes(prepared.duration, frameCount);+ const frameTimes = times.map((t) => prepared.duration > 0 ? t / prepared.duration : 0);+ if (opts.measureParts && (opts.measureParts.length < 1 || opts.measureParts.length > 16))+ throw new Error("measureParts must contain 1..16 exact selectors");+ const measuredParts = opts.measureParts?.map((selector) => selectCameraSubject(root, selector));+ if (measuredParts && new Set(measuredParts.map((part) => part.node)).size !== measuredParts.length)+ throw new Error("measureParts contains duplicate part selections");+ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];+ const poseBounds = [];+ for (const [i, t] of times.entries()) {+ poseSceneAtTime(root, prepared, t);+ const scene = measureBounds(root);+ const subject = opts.shot?.subject ? measureBounds(selectCameraSubject(root, opts.shot.subject).node) : undefined;+ poseBounds.push({+ phase: frameTimes[i],+ timeSeconds: t,+ scene,+ ...subject ? { subject } : {},+ ...measuredParts ? {+ parts: measuredParts.map(({ path, name, node }) => ({+ path,+ name,+ bounds: measurePartBounds(node),+ origin: worldOrigin(node)+ }))+ } : {}+ });+ const b = subject ?? scene;+ for (let a = 0;a < 3; a++) {+ const lo = b.min[a];+ const hi = b.max[a];+ if (lo < min[a])+ min[a] = lo;+ if (hi > max[a])+ max[a] = hi;}}- if (semanticForExport !== undefined) {- 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}`);- }- extras[KILN_SEMANTIC_EXTRAS_KEY] = cloneSemanticMetadataV1(semantic.value);+ const frameBounds = Number.isFinite(min[0]) ? { min, max } : undefined;+ poseSceneAtTime(root, prepared, times[0]);+ const initialShot = opts.shot ? resolveAssetCamera(root, opts.shot) : undefined;+ let lockedCamera = initialShot?.camera;+ if (initialShot && opts.shot?.camera?.type !== "explicit" && frameBounds) {+ const dir = initialShot.camera.position.map((v, i) => v - initialShot.camera.target[i]);+ lockedCamera = cameraFromBounds(frameBounds, dir, opts.shot?.camera?.type === "orbit" ? opts.shot.camera.padding ?? 1.2 : 1.2, initialShot.camera.up);}- if (Object.keys(extras).length)- gtNode.setExtras(extras);- gtNode.setTranslation([threeObj.position.x, threeObj.position.y, threeObj.position.z]);- gtNode.setRotation([- threeObj.quaternion.x,- threeObj.quaternion.y,- threeObj.quaternion.z,- threeObj.quaternion.w- ]);- gtNode.setScale([threeObj.scale.x, threeObj.scale.y, threeObj.scale.z]);- if (!threeObj.matrixAutoUpdate)- gtNode.setMatrix(threeObj.matrix.toArray());- if (threeObj.isMesh) {- const threeMesh = threeObj;- const threeMats = Array.isArray(threeMesh.material) ? threeMesh.material : [threeMesh.material];- const gtMats = threeMats.map((material) => bridgeMaterial(doc, material, matCache, texCache, authorExtras, atlas));- const gtMat = Array.isArray(threeMesh.material) ? gtMats : gtMats[0];- const cacheKey = `${threeMesh.geometry.uuid}__${threeMats.map((material) => material.uuid).join("_")}`;- let gtMesh = meshCache.get(cacheKey);- if (!gtMesh) {- gtMesh = bridgeGeometry(doc, buf, threeMesh.geometry, gtMat, threeMesh.name || "mesh", atlas);- meshCache.set(cacheKey, gtMesh);- }- gtNode.setMesh(gtMesh);- } else if (threeObj.isSprite) {- const sprite = threeObj;- const threeMat = sprite.material;- const gtMat = bridgeMaterial(doc, threeMat, matCache, texCache, authorExtras, atlas);- const centerX = sprite.center?.x ?? 0.5;- const centerY = sprite.center?.y ?? 0.5;- const rotation = sprite.material.rotation ?? 0;- const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;- let gtMesh = meshCache.get(cacheKey);- if (!gtMesh) {- const geometry = new THREE54.PlaneGeometry(1, 1);- if (centerX !== 0.5 || centerY !== 0.5) {- geometry.translate(0.5 - centerX, 0.5 - centerY, 0);+ const lens = opts.shot?.camera;+ if (lockedCamera && opts.framing !== "follow" && lens?.type === "explicit" && lens.projection === "perspective" && lens.near === undefined) {+ const union = { min: [...poseBounds[0].scene.min], max: [...poseBounds[0].scene.max] };+ for (const { scene } of poseBounds)+ for (let a = 0;a < 3; a++) {+ union.min[a] = Math.min(union.min[a], scene.min[a]);+ union.max[a] = Math.max(union.max[a], scene.max[a]);}- if (rotation !== 0)- geometry.rotateZ(rotation);- gtMesh = bridgeGeometry(doc, buf, geometry, gtMat, sprite.name || "sprite-quad", atlas);- meshCache.set(cacheKey, gtMesh);- }- gtNode.setMesh(gtMesh);- }- if (threeObj.name) {- nodeMap.set(threeObj.name, gtNode);- }- for (const child of threeObj.children) {- const childNode = bridgeNode(doc, buf, child, matCache, nodeMap, meshCache, texCache, authorExtras, atlas);- gtNode.addChild(childNode);+ lockedCamera = {+ ...lockedCamera,+ near: Math.max(0.001, Math.min(lockedCamera.near, boxDistance(lockedCamera.position, union) / 2))+ };}- return gtNode;-}-function animationInterpolation(track) {- if (isCubicSplineTrack(track))- return "CUBICSPLINE";- const mode = track.getInterpolation();- if (mode === THREE54.InterpolateDiscrete)- return "STEP";- if (mode === THREE54.InterpolateLinear)- return "LINEAR";- throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);-}-function valuesWithHeldKey(track) {- const values = Array.from(track.values);- const tuple = track.getValueSize();- if (!isCubicSplineTrack(track))- return Float32Array.from([...values, ...values.slice(-tuple)]);- const size = tuple / 3;- values.fill(0, values.length - size);- const rest = new Array(size).fill(0);- const held = values.slice(values.length - 2 * size, values.length - size);- return Float32Array.from([...values, ...rest, ...held, ...rest]);-}-function clipsWithDurationSamples(clips) {- return clips.map((clip) => {- const end = Math.fround(clip.duration);- const needsHold = (track) => track.times.length > 0 && track.times[track.times.length - 1] < end;- if (!clip.tracks.some(needsHold))- return clip;- const copied = clip.clone();- for (const track of copied.tracks) {- if (!needsHold(track))- continue;- const values = valuesWithHeldKey(track);- track.times = Float32Array.from([...track.times, end]);- track.values = values;+ const cameraShots = [];+ const labelScale = Math.max(2, Math.round(size / 80));+ const cells = [];+ const derivativeReceipts = [];+ for (let i = 0;i < times.length; i++) {+ poseSceneAtTime(root, prepared, times[i]);+ const resolvedShot = opts.shot ? resolveAssetCamera(root, opts.shot) : undefined;+ if (resolvedShot) {+ if (opts.framing !== "follow")+ resolvedShot.camera = lockedCamera;+ cameraShots.push(resolvedShot);}- return copied;- });-}-function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {- for (const clip of clips) {- const anim = doc.createAnimation(clip.name);- for (const track of clip.tracks) {- const dotIdx = track.name.lastIndexOf(".");- const nodeName = track.name.substring(0, dotIdx);- const property = track.name.substring(dotIdx + 1);- const targetNode = nodeMap.get(nodeName);- if (!targetNode) {- warnings.push(`Animation target "${nodeName}" not found - skipped`);- continue;- }- let targetPath;- let valueType;- if (property === "position") {- targetPath = "translation";- valueType = TYPE_VEC3;- } else if (property === "quaternion") {- targetPath = "rotation";- valueType = TYPE_VEC4;- } else if (property === "scale") {- targetPath = "scale";- valueType = TYPE_VEC3;- } else {- warnings.push(`Unsupported animation property "${property}" on "${nodeName}" - skipped`);- continue;+ let cell;+ if (opts.renderDerivativeCell) {+ const produce = () => opts.renderDerivativeCell({+ root,+ ...resolvedShot ? { camera: resolvedShot.camera } : {},+ label: `${Math.round(frameTimes[i] * 100)}%`,+ view: cam,+ size,+ ...opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {},+ ...frameBounds ? { frameBounds } : {}+ });+ const rendered = resolvedShot ? await withCameraVisibility(root, resolvedShot, produce) : await produce();+ const decoded = decodePng(rendered.png);+ if (decoded.width !== size || decoded.height !== size) {+ throw new Error(`derivative animation cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`);}- 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(animationInterpolation(track));- const channel = doc.createAnimationChannel().setTargetNode(targetNode).setTargetPath(targetPath).setSampler(sampler);- anim.addSampler(sampler);- anim.addChannel(channel);+ cell = decoded.rgb;+ derivativeReceipts.push(rendered.receipt);+ } else {+ cell = resolvedShot ? await withCameraVisibility(root, resolvedShot, async () => rasterizeCamera(root, resolvedShot.camera, size)) : rasterizeView(root, cam.dir, {+ size,+ ...opts.backfaceCull !== undefined ? { backfaceCull: opts.backfaceCull } : {},+ ...frameBounds ? { frameBounds } : {}+ });}- if (anim.listChannels().length === 0)- anim.dispose();- }-}-function clipLoopIntent(clip) {- const intent = clip.userData?.kilnLoopIntent;- return intent === "loop" || intent === "once" ? intent : undefined;-}-function finishNativeAnimations(doc, clips) {- const animations = doc.getRoot().listAnimations();- let complete = true;- for (const clip of clips) {- const matches = animations.filter((animation) => animation.getName() === clip.name);- const animation = matches.length === 1 ? matches[0] : undefined;- if (!animation || animation.listChannels().length !== clip.tracks.length)- complete = false;- const intent = clipLoopIntent(clip);- if (animation && intent)- animation.setExtras({ ...animation.getExtras(), kilnLoopIntent: intent });- }- return complete && animations.length === clips.length;-}-function reviewClipExtras(clips) {- if (clips.length > REVIEW_CLIP_LIMITS2.clips) {- throw new Error(`Animation review clip limit exceeded (${REVIEW_CLIP_LIMITS2.clips}).`);+ stampLabel(cell, size, size, labelScale, labelScale, `${Math.round(frameTimes[i] * 100)}%`, labelScale);+ cells.push(cell);}- let trackCount = 0;- return {- version: clips.some((clip) => clip.tracks.some(isCubicSplineTrack)) ? 2 : 1,- clips: clips.map((clip) => ({- name: clip.name,- duration: clip.duration,- ...clipLoopIntent(clip) ? { loopIntent: clipLoopIntent(clip) } : {},- tracks: clip.tracks.map((track) => {- trackCount++;- if (trackCount > REVIEW_CLIP_LIMITS2.tracks) {- throw new Error(`Animation review track limit exceeded (${REVIEW_CLIP_LIMITS2.tracks}).`);- }- if (track.times.length > REVIEW_CLIP_LIMITS2.samplesPerTrack || track.values.length > REVIEW_CLIP_LIMITS2.valuesPerTrack) {- throw new Error("Animation review sample limit exceeded.");- }- const times = Array.from(track.times);- const values = Array.from(track.values);- if (!times.every(Number.isFinite) || !values.every(Number.isFinite)) {- throw new Error("Animation review tracks must contain only finite values.");- }- return { name: track.name, times, values, interpolation: animationInterpolation(track) };- })- }))+ const baseMeta = {+ ok: true,+ loopClosure: measureLoopClosure(root, chosen),+ clip: prepared.name,+ camera: cam.name,+ frames: times.length,+ frameTimes,+ poseBounds,+ ...cameraShots.length ? { cameraShots } : {},+ duration: prepared.duration,+ ...prepared.unresolved.length ? { unresolvedTracks: prepared.unresolved } : {},+ ...derivativeReceipts.length ? { derivativeReceipts } : {}};-}-function resolveOptimize(opt) {- if (opt)- return opt;- const env = process.env["KILN_BAKE_OPTIMIZE"];- return env === "auto" || env === "palette" || env === "full" ? env : "off";-}-function resolveInstance(opt) {- if (opt)- return opt;- const env = process.env["KILN_BAKE_INSTANCE"];- return env === "off" || env === "auto" || env === "on" ? env : "auto";-}-function hasJointPivots(doc) {- return doc.getRoot().listNodes().some((n) => /^joint[_-]/i.test(n.getName()));-}-function hasNodeLevelsOfDetail(doc) {- return doc.getRoot().listNodes().some((n) => n.getExtension(MSFT_LOD) !== null);-}-function hasPreservedNodeState(doc) {- return doc.getRoot().listNodes().some((node) => node.getExtension("KHR_node_visibility") !== null || Object.keys(node.getExtras()).length > 0);-}-async function applyGpuInstancing(doc, mode, role) {- if (mode === "off")- return;- if (mode === "auto" && role !== "fill")- return;- const root = doc.getRoot();- if (root.listAnimations().length > 0 || root.listSkins().length > 0)- return;- if (hasJointPivots(doc) || hasNodeLevelsOfDetail(doc) || hasPreservedNodeState(doc))- return;- const before = collectGlbMetrics(doc);- await doc.transform(instance({ min: INSTANCE_MIN }));- let batches = 0;- let instances = 0;- for (const node of root.listNodes()) {- const ext = node.getExtension("EXT_mesh_gpu_instancing");- if (!ext)- continue;- batches += 1;- instances += ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 0;+ if (opts.perFrame) {+ return {+ ...baseMeta,+ width: size,+ height: size,+ pngs: cells.map((c) => encodePng(c, size, size))+ };}- if (batches === 0)- return;- const after = collectGlbMetrics(doc);- return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };+ const { rgb, width, height } = compositeCellGrid(cells, size);+ return { ...baseMeta, width, height, png: encodePng(rgb, width, height) };}-async function consolidateMaterials(doc, mode, keep = []) {- doc.setLogger(new Logger(Logger.Verbosity.WARN));- const before = collectGlbMetrics(doc);- const root = doc.getRoot();- const steps = root.listMaterials().some((material) => Object.keys(material.getExtras()).length > 0) ? [] : [palette({ min: PALETTE_MIN })];- let merge;- if (mode === "full")- steps.push(rigidMerge({ keep }, (summary) => {- merge = summary;- }));- steps.push(weld2(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));- await doc.transform(...steps);- const after = collectGlbMetrics(doc);- return {- mode,- materialsBefore: before.uniqueMaterials,- materialsAfter: after.uniqueMaterials,- drawsBefore: before.drawCalls,- drawsAfter: after.drawCalls,- ...merge ? { rigidMerge: merge } : {}- };+function normalizeVec(v) {+ const len = Math.hypot(v[0], v[1], v[2]) || 1;+ return [v[0] / len, v[1] / len, v[2] / len];}-function optimizeWarnings(summary) {- const merge = summary.rigidMerge;- if (!merge)- return [];- const warnings = [];- if (merge.skipped)- warnings.push(`Rigid merge skipped: ${merge.skipped}; geometry left separate.`);- if (merge.rejected.length)- warnings.push(`Rigid merge retained ${merge.rejected.length} rejected buckets; first: ${merge.rejected[0].error}`);- if (merge.unmatchedKeep.length)- warnings.push(`Rigid merge did not find ${merge.unmatchedKeep.length} requested boundary names.`);- return warnings;+function dotVec(a, b) {+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];}-async function renderSceneToGLB(root, opts = {}) {- assertNoLegacyRuntimePolicy(opts);- const requirements = resolveRequirementsContext(opts.requirements);- const clips = opts.clips ?? [];- const indexPolicy = resolveIndexPolicy(opts.indexPolicy);- if (indexPolicy === "asBuilt" && resolveOptimize(opts.optimize) !== "off")- throw new Error("asBuilt indexPolicy requires optimize off to preserve authored buffers");- if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))- throw new Error("geometryPolicy must be warn or strict");- const exporter = resolveGltfExporter(opts.gltfExporter);- const skinIntegrity = inspectSkinIntegrity(root);- if (skinIntegrity.findings.length) {- throw new AssetQaBlockedError(createRequirementsQaReport(requirements, {- findings: skinIntegrity.findings,- executedRules: [],- evaluatedDimensions: ["exportIntegrity"],- metrics: {- exportIntegrity: {- skinMeshesChecked: skinIntegrity.meshesChecked,- skinVerticesChecked: skinIntegrity.verticesChecked,- skinInspectionTruncated: skinIntegrity.truncated+async function renderInteriorGrid(root, opts = {}) {+ const size = opts.size ?? 256;+ const labelScale = Math.max(2, Math.round(size / 80));+ const roofsHidden = opts.nodeName ? hideNodeInScene(root, opts.nodeName) : hideArchitectureRoofInScene(root).nodes.length;+ if (opts.capture) {+ const grid = await renderCaptureGrid(root, opts.capture, opts.renderDerivativeCell);+ return { ...grid, roofsHidden, wallsHidden: 0 };+ }+ let wallsHidden = 0;+ const cells = [];+ const derivativeReceipts = [];+ for (const view of INTERIOR_VIEWS) {+ if (view.name === "Eye-level") {+ const d = normalizeVec(view.dir);+ wallsHidden = hideNodeInScene(root, (name) => {+ const lower = name.toLowerCase();+ for (const w of ROOM_WALL_NORMALS) {+ if (lower.endsWith(w.suffix) && dotVec(w.n, d) > 0.2)+ return true;}+ return false;+ });+ }+ let cell;+ if (opts.renderDerivativeCell) {+ const rendered = await opts.renderDerivativeCell({+ root,+ label: view.name,+ view,+ size,+ backfaceCull: false+ });+ const decoded = decodePng(rendered.png);+ if (decoded.width !== size || decoded.height !== size) {+ throw new Error(`derivative interior cell must be ${size}x${size}; got ${decoded.width}x${decoded.height}`);}- }), "scene");- }- assertPortableMaterialSides(root);- const lodSets = opts.derivative === true ? [] : collectLodSets(root);- if (opts.derivative !== true)- assertRequiredSolids(root);- const warnings = inspectGeometryExport(root, opts.geometryPolicy, exporter);- let tris = countTriangles(root);- for (const set of lodSets)- for (const level of set.levels.slice(1))- tris -= countTriangles(level);- const hiddenTris = hiddenTriangles(root, new Set(lodSets.flatMap((set) => set.levels.slice(1))));- if (hiddenTris > 0 && hiddenTris === tris)- throw new Error("renderSceneToGLB: every triangle is hidden (visible = false on the root or on every part), so nothing draws. Hide parts inside the asset, not all of it.");- tris -= hiddenTris;- const materialRecipeApplications = collectMaterialRecipeApplications(root);- const materialResourceProvenance = collectMaterialResourceProvenance(root);- for (const w of inspectGeneratedAnimation(root, clips))- warnings.push(w);- const externalSupport = requirements.requirements.requirements.externalSupport;- for (const w of inspectSceneStructure(root, {- ...externalSupport?.state === "requested" ? { externalSupport: externalSupport.value.supports } : {}- }))- warnings.push(w);- const atlas = collectAtlasProvenance(root);- const bakedTextures = await bakeSceneTextures(root, warnings);- ensureNormalMapTangents(root, warnings);- const qaPolicy = qaPolicyFromEnv();- const sceneEvidence = await collectRequirementsSceneEvidence(requirements, root, qaPolicy);- const sceneQaReport = runRequirementsSceneQa(requirements, root, clips, qaPolicy, sceneEvidence);- const qaBlocks = qaBlockingEnabled() && opts.derivative !== true;- const qaSuppressedBy = opts.derivative === true ? "derivative re-serialization" : "KILN_QA_MODE";- if (sceneQaReport.disposition === "block") {- const blocked = new AssetQaBlockedError(sceneQaReport, "scene");- if (qaBlocks)- throw blocked;- warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);+ cell = decoded.rgb;+ derivativeReceipts.push(rendered.receipt);+ } else {+ cell = rasterizeView(root, view.dir, { size, backfaceCull: false });+ }+ stampLabel(cell, size, size, labelScale, labelScale, view.name, labelScale);+ cells.push(cell);}- const nativeClips = clipsWithDurationSamples(clips);- const authorExtras = collectAuthorExtras(root);- warnings.push(...authorExtras.warnings);- const doc = exporter === "three" ? await communitySceneDocument(root, nativeClips, (await Promise.resolve().then(() => (init_exporter_node(), exports_exporter_node))).nodeExportPlatform, authorExtras, atlas) : new Document;- doc.getRoot().getAsset().generator = "Kiln";- if (exporter === "legacy") {- const buf = doc.createBuffer();- const matCache = new Map;- const meshCache = new Map;- const texCache = new Map;- const nodeMap = new Map;- const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache, authorExtras, atlas);- const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);- doc.getRoot().setDefaultScene(gltfScene);- if (clips.length > 0) {- const review = reviewClipExtras(clips);- bridgeAnimations(doc, buf, nativeClips, nodeMap, warnings);- if (!finishNativeAnimations(doc, nativeClips))- gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: review });+ const { rgb, width, height } = compositeCellGrid(cells, size, INTERIOR_VIEWS.length);+ return {+ png: encodePng(rgb, width, height),+ width,+ height,+ views: INTERIOR_VIEWS.map((v) => v.name),+ capture: {+ preset: "interior",+ cols: INTERIOR_VIEWS.length,+ cells: INTERIOR_VIEWS.length,+ backdrop: DEFAULT_BACKDROP_ID+ },+ roofsHidden,+ wallsHidden,+ ...derivativeReceipts.length ? { derivativeReceipts } : {}+ };+}+var ANIM_CAMERAS, ANIM_CAMERA_ALIASES, ROOM_WALL_NORMALS, INTERIOR_VIEWS;+var init_views = __esm(() => {+ init_capture_limits();+ init_background();+ init_capture_limits();+ init_capture_cache();+ init_camera();+ init_camera_capture();+ init_raster();+ init_png();+ init_png();+ init_grid();+ init_annotate();+ init_capture();+ init_pose();+ init_architecture3();+ init_glb();+ init_evaluator();+ init_raster();+ init_annotate();+ init_background();+ init_png();+ init_capture();+ init_grid();+ init_evidence_history();+ init_renderer_id();+ init_glb();+ init_architecture3();+ init_scene_raster();+ init_diagnostic();+ init_character3();+ init_vehicle3();+ init_pose();+ init_capture_cache();+ init_camera();+ init_camera_capture();+ ANIM_CAMERAS = {+ front: { name: "Front", dir: [1, 0, 0] },+ right: { name: "Right", dir: [0, 0, 1] },+ back: { name: "Back", dir: [-1, 0, 0] },+ left: { name: "Left", dir: [0, 0, -1] },+ top: { name: "Top", dir: [0, 1, 0.0001] },+ "three-quarter": { name: "3/4", dir: [0.7, 0.5, 0.7] }+ };+ ANIM_CAMERA_ALIASES = {+ "3/4": "three-quarter",+ "34": "three-quarter",+ threequarter: "three-quarter",+ quarter: "three-quarter",+ perspective: "three-quarter",+ side: "right",+ profile: "right"+ };+ ROOM_WALL_NORMALS = [+ { suffix: "wallfront", n: [1, 0, 0] },+ { suffix: "wallback", n: [-1, 0, 0] },+ { suffix: "wallleft", n: [0, 0, -1] },+ { suffix: "wallright", n: [0, 0, 1] }+ ];+ INTERIOR_VIEWS = [+ { name: "Floor plan", dir: [0, 1, 0.0001] },+ { name: "Dollhouse", dir: [0.7, 0.5, 0.7] },+ { name: "Eye-level", dir: [0.55, 0.35, 0.45] }+ ];+});++// src/views/character-capture.ts+import * as THREE54 from "three";+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]);+ const y1 = Math.round(to[1]);+ const dx = Math.abs(x1 - x0);+ const sx = x0 < x1 ? 1 : -1;+ const dy = -Math.abs(y1 - y0);+ const sy = y0 < y1 ? 1 : -1;+ let error = dx + dy;+ while (true) {+ if (x0 >= 0 && x0 < width && y0 >= 0 && y0 < height) {+ const offset = (y0 * width + x0) * 3;+ rgb[offset] = color[0];+ rgb[offset + 1] = color[1];+ rgb[offset + 2] = color[2];}- } else {- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];- if (!scene)- throw new Error("Community exporter produced no scene.");- scene.setName(opts.sceneName ?? "Scene");- if (clips.length > 0) {- const review = reviewClipExtras(clips);- if (!finishNativeAnimations(doc, nativeClips))- scene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: review });+ if (x0 === x1 && y0 === y1)+ break;+ const doubled = 2 * error;+ if (doubled >= dy) {+ error += dy;+ x0 += sx;}- }- if (atlas.table) {- const scene = doc.getRoot().getDefaultScene();- scene.setExtras({ ...scene.getExtras(), kilnAtlasProvenance: atlas.table });- }- if (root.userData[KILN_BUDGET_KEY] !== undefined && opts.derivative !== true) {- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];- scene.setExtras({- ...scene.getExtras(),- [KILN_BUDGET_KEY]: normalizeBudget(root.userData[KILN_BUDGET_KEY])- });- }- if (root.userData[KILN_PALETTE_KEY] !== undefined && opts.derivative !== true) {- const declared = root.userData[KILN_PALETTE_KEY];- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];- scene.setExtras({- ...scene.getExtras(),- [KILN_PALETTE_KEY]: normalizePalette(declared?.colors, { threshold: declared?.threshold })- });- }- applySurfaceBakeExtras(root, doc);- applyNodeVisibility(root, doc);- applyLodChains(root, lodSets, doc);- const indexBuffers = applyIndexPolicy(doc, indexPolicy);- if (opts.dedup !== false) {- try {- await doc.transform(dedup());- } catch (err) {- warnings.push(`dedup transform failed: ${err instanceof Error ? err.message : String(err)}`);+ if (doubled <= dx) {+ error += dx;+ y0 += sy;}}- let instancing;- try {- instancing = await applyGpuInstancing(doc, resolveInstance(opts.instance), opts.role);- } catch (err) {- warnings.push(`instance transform failed: ${err instanceof Error ? err.message : String(err)}`);- }- const optimizeMode = resolveOptimize(opts.optimize);- let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;- if (optimizeMode === "auto" && collectGlbMetrics(doc, tris).uniqueMaterials >= PALETTE_MIN) {- effectiveOptimize = "palette";- }- let optimize;- if (effectiveOptimize !== "off") {- try {- optimize = await consolidateMaterials(doc, effectiveOptimize);- warnings.push(...optimizeWarnings(optimize));- } catch (err) {- warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);- }+}+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);+ const bounds = new THREE54.Box3().setFromObject(root);+ if (bounds.isEmpty())+ bounds.set(new THREE54.Vector3(-0.5, 0, -0.5), new THREE54.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE54.Vector3);+ const camera = cameraId === "front" ? new THREE54.Vector3(1, 0, 0) : new THREE54.Vector3(0, 0, 1);+ const upHint = new THREE54.Vector3(0, 1, 0);+ const xAxis = new THREE54.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE54.Vector3().crossVectors(camera, xAxis).normalize();+ let extent = 0.000001;+ for (let corner = 0;corner < 8; corner++) {+ const point = new THREE54.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);+ extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));}- let instanceability;- let metricsError;- try {- const metrics = collectGlbMetrics(doc, optimize || instancing ? undefined : tris);- instanceability = gradeInstanceability(metrics, {- mergeCandidates: materialMergeCandidates(doc)- });- } catch (err) {- metricsError = err instanceof Error ? err.message : String(err);+ const scale = size * 0.45 / extent;+ return (assetPoint) => {+ const world = new THREE54.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];+ };+}+function skeletonCapture(root, request, findings, size) {+ const baseRequest = {+ id: request.id,+ label: request.label,+ cameraId: request.cameraId,+ buffer: "semantic-overlay",+ scope: "category",+ variant: "character-skeleton",+ focusRolePrefixes: request.focusRolePrefixes+ };+ const frame = renderDiagnosticView(root, baseRequest, { size });+ 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, project(parent.assetPosition), project(child.assetPosition), edge.valid ? rgbFromHex(edge.color) : [255, 62, 72]);}- let materialMetrics;- let materialBudgetWarnings = [];- try {- materialMetrics = collectMaterialMetricsV1(doc);- materialBudgetWarnings = evaluateMaterialBudgetV1(materialMetrics, {- profile: "web.portable.v1",- tier: "standard"+ 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,+ nodePath: joint.nodePath,+ semanticRoles: [`joint.${joint.role}`, ...joint.contact ? ["contact.character"] : []],+ pixelBounds: [+ Math.max(0, Math.round(point[0]) - 4),+ Math.max(0, Math.round(point[1]) - 4),+ Math.min(frame.width - 1, Math.round(point[0]) + 4),+ Math.min(frame.height - 1, Math.round(point[1]) + 4)+ ],+ color,+ triangleCount: 0});- } catch (error) {- warnings.push(`material metrics failed: ${error instanceof Error ? error.message : String(error)}`);- }- const io = engineIO();- ensureDefaultScene(doc);- await refreshAtlasDocumentProvenance(doc);- await validateAtlasDocumentProvenance(doc);- const bytes = await io.writeBinary(doc);- const artifactGlbSha256 = `sha256:${await sha256Hex2(bytes)}`;- const boundBakedTextures = bakedTextures.map((entry) => ({- ...entry,- artifactGlbSha256- }));- const gltfValidation = await validateFinalGlbBytes(bytes);- const qaReport = await appendRequirementsFinalQa(requirements, sceneQaReport, gltfValidation, bytes, instanceability, metricsError, materialMetrics, materialBudgetWarnings);- if (qaReport.disposition === "block") {- const blocked = new AssetQaBlockedError(qaReport, "final-glb", gltfValidation);- if (qaBlocks)- throw blocked;- warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);- }- for (const issue of gltfValidation.issues.messages) {- if (issue.severity !== 1)- continue;- warnings.push(`glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ""}: ${issue.message}`);}- const integrationManifest = await inspectGlbIntegration(bytes, {- ...opts.role ? { requestedRole: opts.role } : {},- validation: gltfValidation- });- if (!integrationManifest)- throw new Error("renderSceneToGLB: final GLB has no measurable scene");- for (const finding of integrationManifest.deliveryDiagnostics ?? [])- warnings.push(`${finding.code} ${finding.path}: ${finding.message}`);- const palette = integrationManifest.palette;- for (const finding of palette?.offPalette ?? [])- warnings.push(`PALETTE_OFF material ${JSON.stringify(finding.material)} ${finding.color} is delta E ${finding.deltaE} from the nearest palette entry ${finding.nearest} (threshold ${palette.threshold})${finding.textured ? "; the factor tints a texture that is not judged" : ""}.`);- const diagnosticViews = [];- const rig = requirements.requirements.requirements.rig;- const diagnosticParents = new Map(lodSets.map(({ parent }) => [parent, [...parent.children]]));- for (const { parent, levels } of lodSets)- for (const level of levels.slice(1))- parent.remove(level);+ 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: request.cameraId,+ kind: "skeleton",+ width: frame.width,+ height: frame.height,+ png: encodePng(frame.rgb, frame.width, frame.height),+ regions: frame.regions+ };+}+async function captureCharacterDiagnosticViews(root, clips, requirements, findings = [], size = 256) {+ if (!Number.isInteger(size) || size < 1 || size > 2048)+ throw new RangeError("Diagnostic size must be an integer from 1 to 2048.");+ const transforms = [];+ root.traverse((node) => {+ transforms.push({+ node,+ position: node.position.clone(),+ quaternion: node.quaternion.clone(),+ scale: node.scale.clone()+ });+ });+ const requests = planCharacterDiagnosticRequests(requirements);+ const captures = [];try {- if (rig?.state === "requested") {- await Promise.resolve().then(() => init_character_capture());- diagnosticViews.push(...await captureCharacterDiagnosticViews(root, clips, rig.value, Object.values(qaReport.dimensions).flatMap((d) => d.findings)));- }- if (requirements.requirements.requirements.mobility?.state === "requested") {- await Promise.resolve().then(() => init_views());- diagnosticViews.push(...captureVehicleDiagnosticViews(root));+ for (const request of requests) {+ if (request.variant === "character-skeleton") {+ captures.push(skeletonCapture(root, request, findings, size));+ continue;+ }+ if (!request.clipName)+ continue;+ const strip = await renderClipAnimation(root, clips, {+ 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: request.id,+ label: request.label,+ cameraId: request.cameraId,+ kind: "motion-strip",+ width: strip.width,+ height: strip.height,+ png: strip.png,+ regions: [],+ clipName: request.clipName,+ phaseFractions: request.phaseFractions+ });}} finally {- for (const [parent, children] of diagnosticParents) {- parent.clear();- parent.add(...children);+ for (const saved of transforms) {+ saved.node.position.copy(saved.position);+ saved.node.quaternion.copy(saved.quaternion);+ saved.node.scale.copy(saved.scale);}+ root.updateMatrixWorld(true);}- return {- bytes,- indexBuffers,- requirements,- artifactGlbSha256,- tris,- warnings,- gltfValidation,- qaReport,- instanceability,- metricsError,- ...optimize ? { optimize } : {},- ...instancing ? { instancing } : {},- ...materialMetrics ? { materialMetrics } : {},- ...materialRecipeApplications.length ? { materialRecipeApplications } : {},- ...materialResourceProvenance.length ? { materialResourceProvenance } : {},- ...boundBakedTextures.length ? { bakedTextures: boundBakedTextures } : {},- integrationManifest,- ...diagnosticViews.length ? { diagnosticViews } : {}- };+ return captures;}-async function renderGLBInProcess(code, opts = {}) {- assertNoLegacyRuntimePolicy(opts);- const requirements = resolveRequirementsContext(opts.requirements);- if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))- throw new Error("geometryPolicy must be warn or strict");- let textureResolver = opts.textureResolver ?? DEFAULT_TEXTURE_RESOLVER;- const rebuildOptions = {- indexPolicy: resolveIndexPolicy(opts.indexPolicy),- gltfExporter: resolveGltfExporter(opts.gltfExporter),- geometryPolicy: opts.geometryPolicy ?? "warn",- optimize: resolveOptimize(opts.optimize),- ...resolveOptimize(opts.optimize) === "full" ? { optimizationPipeline: FULL_OPTIMIZATION_PIPELINE } : {},- instance: resolveInstance(opts.instance)- };- let materialLibraryDependencies;- if (opts.materialResources) {- await Promise.resolve().then(() => init_material_library_node());- const materialRecords = await decodeMaterialLibraryPayload(opts.materialResources);- materialLibraryDependencies = materialRecords.map((record) => structuredClone(record.manifest));- textureResolver = await createMaterialLibraryTextureResolver(materialRecords, textureResolver);- }- const { meta, root, clips, primitiveUsage } = await executeKilnCode(code, {- textureResolver,- console: opts.diagnosticConsole- });- const scene = await renderSceneToGLB(root, {- ...rebuildOptions,- sceneName: meta.name || "Scene",- clips,- requirements: requirements.binding,- role: meta.role+var rgbFromHex = (value) => {+ const parsed = Number.parseInt(value.replace(/^#/, ""), 16);+ return [parsed >>> 16 & 255, parsed >>> 8 & 255, parsed & 255];+};+var init_character_capture = __esm(() => {+ init_character3();+ init_diagnostic();+ init_png();+ init_views();+ init_pose();+});++// src/render.ts+import * as THREE55 from "three";+import { Document, Logger as Logger2 } from "@gltf-transform/core";+import { KHRMaterialsEmissiveStrength } from "@gltf-transform/extensions";+import { dedup as dedup2, instance, palette, weld as weld2, prune as prune2, mergeDocuments } from "@gltf-transform/functions";+function applySurfaceBakeExtras(root, doc) {+ const baked = [];+ root.traverse((node) => {+ const mesh = node;+ const record = mesh.isMesh ? surfaceBakeRecord(mesh.geometry) : undefined;+ if (record && Object.keys(record).length)+ baked.push([mesh, { ...record }]);});- const {- category: modelCategory,- requirements: _requirements,- intent: _intent,- policyHash: _policyHash,- adviceHash: _adviceHash,- binding: _binding,- ...modelMeta- } = meta;+ if (baked.length === 0)+ return;+ const written = writtenNodeResolver(root, doc, "Surface bake export");+ for (const [node, record] of baked) {+ const mesh = written(node).getMesh();+ if (mesh)+ mesh.setExtras({ ...mesh.getExtras(), [SURFACE_BAKE_KEY]: record });+ }+}+function hiddenTriangles(root, lowerLevels) {+ let hidden = 0;+ const visit = (node) => {+ if (lowerLevels.has(node))+ return;+ if (node.visible === false) {+ hidden += countTriangles(node);+ return;+ }+ for (const child of node.children)+ visit(child);+ };+ visit(root);+ return hidden;+}+function ensureDefaultScene(doc) {+ const root = doc.getRoot();+ const scene = root.getDefaultScene() ?? root.listScenes()[0];+ if (scene && !root.getDefaultScene())+ root.setDefaultScene(scene);+ return scene;+}+async function sha256Hex3(bytes) {+ 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);+ const root = doc.getRoot();+ const explicitDefault = root.getDefaultScene();+ const scene = explicitDefault ?? root.listScenes()[0];+ if (!scene)+ return;+ const { min, max } = drawnSceneBounds(scene);+ const finiteBounds = min.every(Number.isFinite) && max.every(Number.isFinite);+ if (!finiteBounds)+ return;+ const metrics = collectGlbMetrics(doc);+ const validation = opts.validation ?? await validateFinalGlbBytes(bytes);+ const scenes = root.listScenes();+ const minTuple = [min[0], min[1], min[2]];+ const maxTuple = [max[0], max[1], max[2]];+ const minY = minTuple[1];+ const levelsOfDetail = summarizeLodChains(doc);+ const hiddenNodes = summarizeHiddenNodes(doc);+ const delivery = inspectDelivery(doc);+ const vertexAttributes = summarizeVertexAttributes(doc);+ const budgetDeclaration = readBudgetDeclaration(scene.getExtras()[KILN_BUDGET_KEY]);+ const instancedDraws = budgetDeclaration?.draws === undefined ? undefined : await (await Promise.resolve().then(() => (init_runtime_three(), exports_runtime_three))).instancedDrawEstimate(doc);+ const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, {+ triangles: metrics.triangles,+ draws: metrics.drawCalls,+ ...instancedDraws === undefined ? {} : { instancedDraws }+ }, levelsOfDetail) : undefined;+ const paletteDeclaration = readPaletteDeclaration(scene.getExtras()[KILN_PALETTE_KEY]);+ const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;return {- glb: Buffer.from(scene.bytes),- rebuildOptions,- ...materialLibraryDependencies ? { materialLibraryDependencies } : {},- requirements: scene.requirements,- artifactGlbSha256: scene.artifactGlbSha256,- tris: scene.tris,- meta: {- ...modelMeta,- indexBuffers: scene.indexBuffers,- ...modelCategory !== undefined ? { modelCategory } : {},- tris: scene.tris,- primitiveUsage,- ...scene.instanceability ? { instanceability: scene.instanceability, tier: scene.instanceability.grade } : {},- ...scene.metricsError ? { metricsError: scene.metricsError } : {},- ...scene.optimize ? { optimize: scene.optimize } : {},- ...scene.instancing ? { instancing: scene.instancing } : {},- gltfValidation: scene.gltfValidation,- qaReport: scene.qaReport+ schemaVersion: "kiln.integration-manifest.v1",+ analyzerVersion: 1,+ artifactSha256: await sha256Hex3(bytes),+ units: "m",+ axes: { forward: "+X", up: "+Y", right: "+Z" },+ bounds: {+ min: minTuple,+ max: maxTuple,+ size: [maxTuple[0] - minTuple[0], maxTuple[1] - minTuple[1], maxTuple[2] - minTuple[2]],+ center: [+ (minTuple[0] + maxTuple[0]) / 2,+ (minTuple[1] + maxTuple[1]) / 2,+ (minTuple[2] + maxTuple[2]) / 2+ ]+ },+ pivot: { convention: "author-origin", position: [0, 0, 0] },+ ground: {+ groundY: 0,+ contactTolerance: GROUND_CONTACT_TOLERANCE,+ minY,+ offsetToGround: -minY,+ grounded: Math.abs(minY) <= GROUND_CONTACT_TOLERANCE+ },+ defaultScene: { index: scenes.indexOf(scene), name: scene.getName() },+ ...opts.requestedRole ? { requestedRole: opts.requestedRole } : {},+ ...opts.assessedRole ? { assessedRole: opts.assessedRole } : {},+ renderMetrics: {+ triangles: metrics.triangles,+ drawCalls: metrics.drawCalls,+ uniqueGeometries: metrics.uniqueGeometries,+ uniqueMaterials: metrics.uniqueMaterials,+ textureCount: metrics.textureCount,+ transparentMaterials: metrics.transparentMaterials,+ skinned: metrics.skinned+ },+ ...levelsOfDetail.length ? { levelsOfDetail } : {},+ ...hiddenNodes.length ? { hiddenNodes } : {},+ ...delivery.colliders.length ? { colliders: delivery.colliders } : {},+ ...delivery.anchors.length ? { anchors: delivery.anchors } : {},+ ...delivery.kit ? { kit: delivery.kit } : {},+ ...delivery.ports.length ? { ports: delivery.ports } : {},+ ...budget ? { budget } : {},+ ...palette ? { palette } : {},+ ...vertexAttributes.length ? { vertexAttributes } : {},+ ...delivery.diagnostics.length ? { deliveryDiagnostics: delivery.diagnostics } : {},+ structuralQa: {+ hasDefaultScene: explicitDefault !== null,+ finiteBounds,+ validatorErrors: validation.issues.numErrors,+ validatorWarnings: validation.issues.numWarnings},- warnings: scene.warnings,- ...scene.diagnosticViews ? { diagnosticViews: scene.diagnosticViews } : {},- ...scene.materialMetrics ? { materialMetrics: scene.materialMetrics } : {},- ...scene.materialRecipeApplications ? { materialRecipeApplications: scene.materialRecipeApplications } : {},- ...scene.materialResourceProvenance ? { materialResourceProvenance: scene.materialResourceProvenance } : {},- ...scene.bakedTextures ? { bakedTextures: scene.bakedTextures } : {},- integrationManifest: scene.integrationManifest+ visualQa: "not_assessed"};}-function inspectGeneratedAnimation(root, clips) {- const warnings = [];- if (clips.length === 0)- return warnings;- const nodeNames = new Set;- root.traverse((obj) => {- if (obj.name)- nodeNames.add(obj.name);- });- for (const clip of clips) {- for (const track of clip.tracks) {- const dotIdx = track.name.lastIndexOf(".");- if (dotIdx === -1) {- warnings.push(`Track "${track.name}" is missing a node.property separator`);- continue;- }- const nodeName = track.name.substring(0, dotIdx);- const property = track.name.substring(dotIdx + 1);- 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}"`);- }- }+async function executeKilnCode(code, options = {}) {+ if (!code || typeof code !== "string") {+ throw new Error("executeKilnCode: code must be a non-empty string");}- return warnings;-}-function collectMeshStats(root) {- root.updateMatrixWorld(true);- const out = [];- root.traverseVisible((obj) => {- if (!obj.isMesh)- return;- const meshObj = obj;- const geo = meshObj.geometry;- if (!geo)- return;- const idx = geo.getIndex();- const tri = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;- const bounded = meshObj;- let localBounds;- if (bounded.boundingBox !== undefined) {- if (bounded.boundingBox === null)- bounded.computeBoundingBox?.();- localBounds = bounded.boundingBox ?? null;- } else {- if (geo.boundingBox === null)- geo.computeBoundingBox();- localBounds = geo.boundingBox;+ const normalized = code.replace(/\r\n/g, `+`);+ assertGeneratedSourceSafe(normalized);+ try {+ const primitiveUsage = {};+ const globals = buildSandboxGlobals(primitiveUsage, {+ textureResolver: options.textureResolver ?? DEFAULT_TEXTURE_RESOLVER,+ console: options.console+ });+ const globalNames = Object.keys(globals);+ const globalValues = Object.values(globals);+ const fn = new Function(...globalNames, `'use strict';+${normalized}+return { meta: typeof meta !== 'undefined' ? meta : {}, build, animate: typeof animate !== 'undefined' ? animate : null };`);+ const { meta, build, animate } = fn(...globalValues);+ if (typeof build !== "function") {+ throw new AuthoringDiagnosticError("BUILD_RESULT", "executeKilnCode: generated code did not define `build`");}- if (!localBounds)- return;- const box = localBounds.clone().applyMatrix4(meshObj.matrixWorld);- if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {- return;+ const root = await build();+ if (!root?.isObject3D) {+ throw new AuthoringDiagnosticError("BUILD_RESULT", "executeKilnCode: build() did not return a THREE.Object3D");}- const center = new THREE54.Vector3;- const size = new THREE54.Vector3;- box.getCenter(center);- box.getSize(size);- out.push({- object: obj,- name: obj.name || "(unnamed)",- triCount: Math.floor(tri),- isPlaneGeo: geo.type === "PlaneGeometry",- center,- size,- box- });- });- return out;+ const declared = globals[SANDBOX_DECLARATIONS];+ if (declared?.budget && root.userData[KILN_BUDGET_KEY] === undefined)+ root.userData[KILN_BUDGET_KEY] = declared.budget;+ if (declared?.palette && root.userData[KILN_PALETTE_KEY] === undefined)+ root.userData[KILN_PALETTE_KEY] = declared.palette;+ const clips = animate ? await animate(root) ?? [] : [];+ return { meta: meta ?? {}, root, clips, primitiveUsage };+ } catch (error) {+ rethrowAuthoringError(error);+ }}-function minimalGapVector(a, b) {- const v = new THREE54.Vector3;- for (const axis of ["x", "y", "z"]) {- if (a.min[axis] > b.max[axis])- v[axis] = b.max[axis] - a.min[axis];- else if (a.max[axis] < b.min[axis])- v[axis] = b.min[axis] - a.max[axis];- else- v[axis] = 0;+function bridgeEmissive(doc, target, source) {+ const color = source.emissive;+ if (!color)+ return;+ const intensity = source.emissiveIntensity ?? 1;+ const scale = Number.isFinite(intensity) ? Math.max(0, intensity) : 1;+ const emitted = [color.r * scale, color.g * scale, color.b * scale];+ const peak = Math.max(...emitted);+ if (!(peak > 1)) {+ target.setEmissiveFactor(emitted);+ return;}- return v;+ target.setEmissiveFactor([emitted[0] / peak, emitted[1] / peak, emitted[2] / peak]);+ target.setExtension("KHR_materials_emissive_strength", doc.createExtension(KHRMaterialsEmissiveStrength).createEmissiveStrength().setEmissiveStrength(peak));}-function inspectSceneStructure(root, opts = {}) {- const warnings = [];- const meshes = collectMeshStats(root);- if (meshes.length === 0)- return warnings;- const cat = opts.category?.toLowerCase();- if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {- const all = new THREE54.Box3;- for (const m of meshes)- all.union(m.box);- const size = new THREE54.Vector3;- all.getSize(size);- if (cat === "aircraft") {- if (size.y > size.x * 1.2) {- warnings.push(`Orientation: this aircraft is ${size.y.toFixed(2)} tall but only ${size.x.toFixed(2)} long along +X (the nose axis). Kiln aircraft fly nose-first along +X — it may be built vertically or sideways.`);- }- } else if (size.z > size.x * 1.3) {- warnings.push(`Orientation: this ${cat} spans ${size.z.toFixed(2)} along Z but only ${size.x.toFixed(2)} along +X. Kiln ${cat}s face +X (forward/muzzle/bow) — it looks built sideways; rebuild the long axis along X.`);+function bridgeTextureSampler(source, target, atlas) {+ const min = GLTF_MIN_FILTER[source.minFilter];+ const mag = GLTF_MAG_FILTER[source.magFilter];+ const s = GLTF_WRAP[source.wrapS];+ const t = GLTF_WRAP[source.wrapT];+ for (const [property, value] of [+ ["minFilter", min],+ ["magFilter", mag],+ ["wrapS", s],+ ["wrapT", t]+ ]) {+ if (typeof source[property] !== "number" || value === undefined) {+ throw new TypeError(`${source.name || "(unnamed texture)"}: unsupported ${property} ${source[property]}`);}}- const STRAY_CENTROID_TOL = 0.02;- const FLOATING_EXPAND = 0.02;- const DECAL_EXTENT_MAX = 0.5;- for (const m of meshes) {- if (!m.isPlaneGeo)- continue;- if (m.triCount > 2)- continue;- if (m.size.length() > DECAL_EXTENT_MAX)- continue;- if (m.center.length() < STRAY_CENTROID_TOL) {- warnings.push(`Stray plane "${m.name}" at world origin (centroid ≈ [0,0,0]). Replace planeGeo with decalBox and position on a host surface, or move this mesh into place.`);+ target.setMinFilter(min).setMagFilter(mag).setWrapS(s).setWrapT(t);+ if (source.channel === 1)+ target.setTexCoord(1);+ const ref = atlas?.texture(source);+ if (ref)+ target.setExtras({ ...target.getExtras(), kilnAtlasReference: ref });+}+function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas) {+ const cached = cache.get(threeMat);+ if (cached)+ return cached;+ const mat = doc.createMaterial(threeMat.name || undefined);+ const author = authorExtras?.material(threeMat);+ if (author)+ mat.setExtras(author);+ const matFlags = threeMat;+ if (matFlags.isMeshStandardMaterial) {+ const stdMat = threeMat;+ mat.setBaseColorFactor([stdMat.color.r, stdMat.color.g, stdMat.color.b, stdMat.opacity]);+ mat.setRoughnessFactor(stdMat.roughness);+ mat.setMetallicFactor(stdMat.metalness);+ bridgeEmissive(doc, mat, stdMat);+ if (stdMat.alphaTest > 0) {+ mat.setAlphaMode("MASK");+ mat.setAlphaCutoff(stdMat.alphaTest);+ } else if (stdMat.transparent) {+ mat.setAlphaMode("BLEND");}- }- if (meshes.length > 1) {- const floaters = [];- const supported = [];- for (let i = 0;i < meshes.length; i++) {- const a = meshes[i];- const ax = a.box.clone().expandByScalar(FLOATING_EXPAND);- let overlapsAny = false;- for (let j = 0;j < meshes.length; j++) {- if (i === j)- continue;- const b = meshes[j];- if (ax.intersectsBox(b.box)) {- overlapsAny = true;- break;- }+ if (stdMat.side === THREE55.DoubleSide) {+ mat.setDoubleSided(true);+ }+ if (stdMat.map) {+ const t = bridgeTexture(doc, stdMat.map, textureCache);+ if (t) {+ mat.setBaseColorTexture(t);+ bridgeTextureSampler(stdMat.map, mat.getBaseColorTextureInfo(), atlas);}- if (overlapsAny)- continue;- const support = restingSupport(a.object, a.box.min.y, opts.externalSupport);- if (support) {- supported.push(`${a.name} at Y=${support.planeY.toFixed(3)}`);- continue;+ }+ if (stdMat.normalMap) {+ const t = bridgeTexture(doc, stdMat.normalMap, textureCache);+ if (t) {+ mat.setNormalTexture(t);+ bridgeTextureSampler(stdMat.normalMap, mat.getNormalTextureInfo(), atlas);}- const declared = declaredSupports(a.object, opts.externalSupport)[0];- let nearest;- 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()) {- nearest = meshes[j];- nearestGap = gap;- }+ }+ if (stdMat.roughnessMap && stdMat.metalnessMap && stdMat.roughnessMap !== stdMat.metalnessMap) {+ throw new TypeError(`Material ${JSON.stringify(threeMat.name || "(unnamed)")} uses separate roughness/metalness textures. Pack G=roughness/B=metalness before export.`);+ }+ const mrSource = stdMat.roughnessMap ?? stdMat.metalnessMap;+ if (mrSource) {+ const t = bridgeTexture(doc, mrSource, textureCache);+ if (t) {+ mat.setMetallicRoughnessTexture(t);+ bridgeTextureSampler(mrSource, mat.getMetallicRoughnessTextureInfo(), atlas);+ }+ }+ if (stdMat.emissiveMap) {+ const t = bridgeTexture(doc, stdMat.emissiveMap, textureCache);+ if (t) {+ mat.setEmissiveTexture(t);+ bridgeTextureSampler(stdMat.emissiveMap, mat.getEmissiveTextureInfo(), atlas);}- const fix = nearest && nearestGap ? ` Fix: shift "${a.name}" by [${nearestGap.x.toFixed(3)}, ${nearestGap.y.toFixed(3)}, ${nearestGap.z.toFixed(3)}] toward "${nearest.name}", or call snapTo(part, hostPart) to do it automatically.` : "";- const mismatch = declared ? ` It is named in a declared external support at Y=${declared.planeY.toFixed(3)}, but its bottom is at Y=${a.box.min.y.toFixed(3)}.` : "";- floaters.push({ name: a.name, fix: fix + mismatch });}- if (floaters.length > 0) {- const entries = floaters.slice(0, FLOATER_FIXES_SHOWN).map(({ name, fix }) => `${name}${fix ? ` —${fix}` : ""}`);- const rest = floaters.slice(FLOATER_FIXES_SHOWN);- if (rest.length > 0) {- const names = rest.slice(0, FLOATER_NAMES_SHOWN).map((floater) => floater.name);- if (rest.length > names.length)- names.push(`+${rest.length - names.length} more`);- entries.push(`+${rest.length} more floating: ${names.join(", ")} — the same fix applies: shift each onto its nearest sibling, or call snapTo(part, hostPart).`);+ if (stdMat.aoMap) {+ const t = bridgeTexture(doc, stdMat.aoMap, textureCache);+ if (t) {+ mat.setOcclusionTexture(t);+ bridgeTextureSampler(stdMat.aoMap, mat.getOcclusionTextureInfo(), atlas);}- warnings.push(`Floating parts (no mesh overlap with any sibling, 2cm tol): ${entries.join(" | ")}`);+ mat.setOcclusionStrength(stdMat.aoMapIntensity ?? 1);}- if (supported.length > 0) {- const shown = supported.slice(0, FLOATER_NAMES_SHOWN);- if (supported.length > shown.length)- shown.push(`+${supported.length - shown.length} more`);- warnings.push(`Declared external support (requirements.externalSupport): ${shown.join(", ")} rest on a support composed outside this asset; information only, no action needed.`);+ } else if (matFlags.isMeshLambertMaterial) {+ const lambMat = threeMat;+ mat.setBaseColorFactor([lambMat.color.r, lambMat.color.g, lambMat.color.b, lambMat.opacity]);+ mat.setRoughnessFactor(1);+ mat.setMetallicFactor(0);+ bridgeEmissive(doc, mat, lambMat);+ } else if (matFlags.isMeshBasicMaterial) {+ const basicMat = threeMat;+ mat.setBaseColorFactor([+ basicMat.color.r,+ basicMat.color.g,+ basicMat.color.b,+ basicMat.opacity+ ]);+ mat.setRoughnessFactor(1);+ mat.setMetallicFactor(0);+ } else if (matFlags.isSpriteMaterial) {+ const spriteMat = threeMat;+ mat.setBaseColorFactor([+ spriteMat.color.r,+ spriteMat.color.g,+ spriteMat.color.b,+ spriteMat.opacity+ ]);+ mat.setRoughnessFactor(1);+ mat.setMetallicFactor(0);+ }+ const common = threeMat;+ if ((common.alphaTest ?? 0) > 0) {+ mat.setAlphaMode("MASK");+ mat.setAlphaCutoff(common.alphaTest ?? 0.5);+ } else if (common.transparent || (common.opacity ?? 1) < 1) {+ mat.setAlphaMode("BLEND");+ }+ if (threeMat.side === THREE55.DoubleSide)+ mat.setDoubleSided(true);+ if (common.map && !mat.getBaseColorTexture()) {+ const texture = bridgeTexture(doc, common.map, textureCache);+ if (texture) {+ mat.setBaseColorTexture(texture);+ bridgeTextureSampler(common.map, mat.getBaseColorTextureInfo(), atlas);}}- return warnings;+ cache.set(threeMat, mat);+ return mat;}-var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", ACCESSOR_TYPES, GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;-var init_render = __esm(() => {- init_requirements_context();- init_requirements_run();- init_requirements_report();- init_skin_integrity();- init_authoring_diagnostic();- init_gltf_io();- init_lod();- init_lod_export();- init_node_visibility();- init_community_exporter();- init_atlas_provenance();- init_material_export();- init_animation_spline();- init_index_policy();- init_open_shell();- init_delivery();- init_delivery_inspect();- init_surface_bake();- init_require_solid();- init_rig_export();- init_geometry_export();- init_primitives();- init_budget();- init_palette_check();- init_metrics();- init_contracts();- init_gltf();- init_run();- init_material_metrics();- init_material_recipe_runtime();- init_material_resources();- init_texture_resolver();- init_rebuild_options();- init_rigid_merge();- init_validation();- init_kit();- init_texture_bake();- engineIO = createGltfIO;- ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];- GLTF_MIN_FILTER = {- [THREE54.NearestFilter]: 9728,- [THREE54.LinearFilter]: 9729,- [THREE54.NearestMipmapNearestFilter]: 9984,- [THREE54.LinearMipmapNearestFilter]: 9985,- [THREE54.NearestMipmapLinearFilter]: 9986,- [THREE54.LinearMipmapLinearFilter]: 9987- };- GLTF_MAG_FILTER = { [THREE54.NearestFilter]: 9728, [THREE54.LinearFilter]: 9729 };- GLTF_WRAP = {- [THREE54.ClampToEdgeWrapping]: 33071,- [THREE54.MirroredRepeatWrapping]: 33648,- [THREE54.RepeatWrapping]: 10497- };- REVIEW_CLIP_LIMITS2 = {- clips: 32,- tracks: 256,- samplesPerTrack: 4096,- valuesPerTrack: 16384- };-});--// src/evaluator/protocol.ts-function evaluatorOutcomeMessage(code) {- return EVALUATOR_OUTCOME_MESSAGES[code];+function bridgeTexture(doc, threeTex, cache) {+ const cached = cache.get(threeTex);+ if (cached)+ return cached;+ const encoded = threeTex.userData["encoded"];+ if (!encoded)+ return null;+ const t = doc.createTexture(threeTex.name || "texture");+ t.setMimeType(encoded.mime);+ t.setImage(encoded.bytes);+ cache.set(threeTex, t);+ return t;}-function resolveEvaluatorPortV2(port, profile) {- if (port)- return port;- if (profile === "evaluator-required") {- throw new EvaluatorPortError("ISOLATION_UNAVAILABLE", "Evaluator port is required.");+function bridgeGeometry(doc, buf, geometry, material, meshName, atlas) {+ if (!geometry.getAttribute("normal")) {+ geometry.computeVertexNormals();}- return trustedInProcessEvaluatorPortV2;-}-var MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV2;-var init_protocol = __esm(() => {- init_authoring_diagnostic();- init_requirements_context();- init_requirements_report();- init_material_library_node();- init_material_library();- init_rebuild_options();- init_solid_diagnostic();- MAX_EVALUATOR_CODE_BYTES = 512 * 1024;- MAX_EVALUATOR_REQUEST_BYTES = 24 * 1024 * 1024;- DEFAULT_EVALUATOR_MAX_GLB_BYTES = 16 * 1024 * 1024;- DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;- EVALUATOR_OUTCOME_MESSAGES = {- INPUT_INVALID: "Evaluator request was invalid. Use kiln.evaluator.request.v2 and update the host and worker together. Retired category/intent options require explicit requirements migration; see docs/migration.md.",- EXECUTION_REJECTED: "Generated asset execution was rejected.",- QA_BLOCKED: "Generated asset did not pass quality checks.",- DEADLINE_EXCEEDED: "Evaluator deadline exceeded.",- CANCELLED: "Evaluator request was cancelled.",- OUTPUT_LIMIT_EXCEEDED: "Evaluator output limit exceeded.",- ISOLATION_UNAVAILABLE: "Isolated evaluator is unavailable.",- WORKER_FAILED: "Evaluator worker failed.",- PROTOCOL_ERROR: "Evaluator returned invalid data."- };- EvaluatorPortError = class EvaluatorPortError extends Error {- code;- diagnostic;- solid;- constructor(code, message = evaluatorOutcomeMessage(code), diagnostic, solid) {- super(diagnostic ? `${message} ${authoringDiagnosticAdvice(diagnostic)}${solidFailureAdvice(solid)}` : code === "EXECUTION_REJECTED" ? `${message} ${EXECUTION_REJECTED_ADVICE}` : message);- this.code = code;- this.diagnostic = diagnostic;- this.solid = solid;- this.name = "EvaluatorPortError";- }- };- trustedInProcessEvaluatorPortV2 = {- async render(code, options = {}, controls = {}) {- if (controls.signal?.aborted)- throw new EvaluatorPortError("CANCELLED");- await Promise.resolve().then(() => init_render());- const result = await renderGLBInProcess(code, options);- if (controls.signal?.aborted)- throw new EvaluatorPortError("CANCELLED");- return result;- }- };-});--// src/runtime-textures.ts-async function sha256Hex3(bytes) {- const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));- return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");+ const prim = doc.createPrimitive().setMaterial(Array.isArray(material) ? material[0] : material);+ const posAttr = geometry.getAttribute("position");+ if (posAttr) {+ prim.setAttribute("POSITION", doc.createAccessor(`${meshName}_pos`).setArray(geometryAttributeValues(posAttr)).setType(TYPE_VEC3).setBuffer(buf));+ }+ const normAttr = geometry.getAttribute("normal");+ if (normAttr) {+ prim.setAttribute("NORMAL", doc.createAccessor(`${meshName}_norm`).setArray(unitNormalValues(normAttr)).setType(TYPE_VEC3).setBuffer(buf));+ }+ const uvAttr = geometry.getAttribute("uv");+ if (uvAttr) {+ prim.setAttribute("TEXCOORD_0", doc.createAccessor(`${meshName}_uv`).setArray(geometryAttributeValues(uvAttr)).setType(TYPE_VEC2).setBuffer(buf));+ }+ const uv1Attr = geometry.getAttribute("uv1");+ if (uv1Attr) {+ prim.setAttribute("TEXCOORD_1", doc.createAccessor(`${meshName}_uv1`).setArray(geometryAttributeValues(uv1Attr)).setType(TYPE_VEC2).setBuffer(buf));+ }+ 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 colorAttr = geometry.getAttribute("color");+ if (colorAttr?.itemSize === 3 || colorAttr?.itemSize === 4) {+ prim.setAttribute("COLOR_0", doc.createAccessor(`${meshName}_color`).setArray(geometryAttributeValues(colorAttr)).setType(colorAttr.itemSize === 4 ? TYPE_VEC4 : TYPE_VEC3).setBuffer(buf));+ }+ const customKeys = [+ ...Object.keys(CUSTOM_EXPORT_ATTRIBUTES),+ ...Object.keys(geometry.attributes).filter((key) => !(key in CUSTOM_EXPORT_ATTRIBUTES)).sort()+ ];+ for (const key of customKeys) {+ const gltfName = customAttributeSemantic(key);+ const custom = geometry.getAttribute(key);+ if (!gltfName || !custom || custom.itemSize < 1 || custom.itemSize > 4)+ continue;+ prim.setAttribute(gltfName, doc.createAccessor(`${meshName}${gltfName.toLowerCase()}`).setArray(geometryAttributeValues(custom)).setType(ACCESSOR_TYPES[custom.itemSize - 1]).setBuffer(buf));+ }+ 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));+ }+ const binding = atlas?.binding(geometry);+ if (binding)+ prim.setExtras({ kilnAtlasBinding: binding });+ const mesh = doc.createMesh(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 = validateMaterialGroups(geometry, material.length, meshName);+ for (const group of groups) {+ const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);+ 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));+ if (binding)+ part.setExtras({ kilnAtlasBinding: binding });+ mesh.addPrimitive(part);+ }+ prim.dispose();+ return mesh;}-function imageDimensions(bytes) {- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);- const fail = () => {- throw new Error("Texture manifest cannot read image dimensions");- };- const at = (offset, length) => {- if (offset + length > bytes.byteLength)- fail();+function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache, authorExtras, atlas) {+ const gtNode = doc.createNode(threeObj.name || undefined);+ const semanticValue = threeObj.userData[KILN_SEMANTIC_EXTRAS_KEY];+ const extras = {+ ...authorExtras?.node(threeObj),+ ...rigExtrasForExport(threeObj),+ ...openShellExtras(threeObj),+ ...kitExtras(threeObj),+ ...repeatInstancesExtras(threeObj)};- if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {- at(16, 8);- return { width: view.getUint32(16), height: view.getUint32(20) };+ let semanticForExport = semanticValue;+ if (threeObj.isSprite) {+ if (semanticValue === undefined) {+ semanticForExport = createSemanticMetadataV1({+ roles: ["vfx.facing.camera-spherical", "vfx.effect.surface.card"]+ });+ } else {+ const existing = validateSemanticMetadataV1(semanticValue);+ if (existing.valid && existing.value) {+ semanticForExport = {+ ...cloneSemanticMetadataV1(existing.value),+ roles: [+ ...existing.value.roles.filter((role) => !role.startsWith("vfx.facing.")),+ "vfx.facing.camera-spherical",+ ...existing.value.roles.some((role) => role.startsWith("vfx.effect.surface")) ? [] : ["vfx.effect.surface.card"]+ ]+ };+ }+ }}- if (isKtx2(bytes)) {- at(20, 8);- return { width: view.getUint32(20, true), height: view.getUint32(24, true) };+ if (semanticForExport !== undefined) {+ 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}`);+ }+ extras[KILN_SEMANTIC_EXTRAS_KEY] = cloneSemanticMetadataV1(semantic.value);}- if (bytes[0] === 255 && bytes[1] === 216) {- let offset = 2;- while (offset + 4 <= bytes.byteLength) {- if (bytes[offset] !== 255)- fail();- const marker = bytes[offset + 1];- if (marker === 255) {- offset++;- continue;+ if (Object.keys(extras).length)+ gtNode.setExtras(extras);+ gtNode.setTranslation([threeObj.position.x, threeObj.position.y, threeObj.position.z]);+ gtNode.setRotation([+ threeObj.quaternion.x,+ threeObj.quaternion.y,+ threeObj.quaternion.z,+ threeObj.quaternion.w+ ]);+ gtNode.setScale([threeObj.scale.x, threeObj.scale.y, threeObj.scale.z]);+ if (!threeObj.matrixAutoUpdate)+ gtNode.setMatrix(threeObj.matrix.toArray());+ if (threeObj.isMesh) {+ const threeMesh = threeObj;+ const threeMats = Array.isArray(threeMesh.material) ? threeMesh.material : [threeMesh.material];+ const gtMats = threeMats.map((material) => bridgeMaterial(doc, material, matCache, texCache, authorExtras, atlas));+ const gtMat = Array.isArray(threeMesh.material) ? gtMats : gtMats[0];+ const cacheKey = `${threeMesh.geometry.uuid}__${threeMats.map((material) => material.uuid).join("_")}`;+ let gtMesh = meshCache.get(cacheKey);+ if (!gtMesh) {+ gtMesh = bridgeGeometry(doc, buf, threeMesh.geometry, gtMat, threeMesh.name || "mesh", atlas);+ meshCache.set(cacheKey, gtMesh);+ }+ gtNode.setMesh(gtMesh);+ } else if (threeObj.isSprite) {+ const sprite = threeObj;+ const threeMat = sprite.material;+ const gtMat = bridgeMaterial(doc, threeMat, matCache, texCache, authorExtras, atlas);+ const centerX = sprite.center?.x ?? 0.5;+ const centerY = sprite.center?.y ?? 0.5;+ const rotation = sprite.material.rotation ?? 0;+ const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;+ let gtMesh = meshCache.get(cacheKey);+ if (!gtMesh) {+ const geometry = new THREE55.PlaneGeometry(1, 1);+ if (centerX !== 0.5 || centerY !== 0.5) {+ geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}- if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {- offset += 2;+ if (rotation !== 0)+ geometry.rotateZ(rotation);+ gtMesh = bridgeGeometry(doc, buf, geometry, gtMat, sprite.name || "sprite-quad", atlas);+ meshCache.set(cacheKey, gtMesh);+ }+ gtNode.setMesh(gtMesh);+ }+ if (threeObj.name) {+ nodeMap.set(threeObj.name, gtNode);+ }+ for (const child of threeObj.children) {+ const childNode = bridgeNode(doc, buf, child, matCache, nodeMap, meshCache, texCache, authorExtras, atlas);+ gtNode.addChild(childNode);+ }+ return gtNode;+}+function animationInterpolation(track) {+ if (isCubicSplineTrack(track))+ return "CUBICSPLINE";+ const mode = track.getInterpolation();+ if (mode === THREE55.InterpolateDiscrete)+ return "STEP";+ if (mode === THREE55.InterpolateLinear)+ return "LINEAR";+ throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);+}+function valuesWithHeldKey(track) {+ const values = Array.from(track.values);+ const tuple = track.getValueSize();+ if (!isCubicSplineTrack(track))+ return Float32Array.from([...values, ...values.slice(-tuple)]);+ const size = tuple / 3;+ values.fill(0, values.length - size);+ const rest = new Array(size).fill(0);+ const held = values.slice(values.length - 2 * size, values.length - size);+ return Float32Array.from([...values, ...rest, ...held, ...rest]);+}+function clipsWithDurationSamples(clips) {+ return clips.map((clip) => {+ const end = Math.fround(clip.duration);+ const needsHold = (track) => track.times.length > 0 && track.times[track.times.length - 1] < end;+ if (!clip.tracks.some(needsHold))+ return clip;+ const copied = clip.clone();+ for (const track of copied.tracks) {+ if (!needsHold(track))+ continue;+ const values = valuesWithHeldKey(track);+ track.times = Float32Array.from([...track.times, end]);+ track.values = values;+ }+ return copied;+ });+}+function bridgeAnimations(doc, buf, clips, nodeMap, warnings) {+ for (const clip of clips) {+ const anim = doc.createAnimation(clip.name);+ for (const track of clip.tracks) {+ const dotIdx = track.name.lastIndexOf(".");+ const nodeName = track.name.substring(0, dotIdx);+ const property = track.name.substring(dotIdx + 1);+ const targetNode = nodeMap.get(nodeName);+ if (!targetNode) {+ warnings.push(`Animation target "${nodeName}" not found - skipped`);continue;}- const length = view.getUint16(offset + 2);- if (marker >= 192 && marker <= 207 && ![196, 200, 204].includes(marker)) {- at(offset + 5, 4);- return { width: view.getUint16(offset + 7), height: view.getUint16(offset + 5) };+ let targetPath;+ let valueType;+ if (property === "position") {+ targetPath = "translation";+ valueType = TYPE_VEC3;+ } else if (property === "quaternion") {+ targetPath = "rotation";+ valueType = TYPE_VEC4;+ } else if (property === "scale") {+ targetPath = "scale";+ valueType = TYPE_VEC3;+ } else {+ warnings.push(`Unsupported animation property "${property}" on "${nodeName}" - skipped`);+ continue;}- offset += 2 + length;+ 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(animationInterpolation(track));+ const channel = doc.createAnimationChannel().setTargetNode(targetNode).setTargetPath(targetPath).setSampler(sampler);+ anim.addSampler(sampler);+ anim.addChannel(channel);}- fail();+ if (anim.listChannels().length === 0)+ anim.dispose();}- const text = (offset) => String.fromCharCode(...bytes.subarray(offset, Math.min(offset + 4, bytes.byteLength)));- if (text(0) === "RIFF" && text(8) === "WEBP") {- at(12, 19);- const chunk = text(12);- if (chunk === "VP8X")- return {- width: 1 + (view.getUint32(24, true) & 16777215),- height: 1 + (view.getUint32(27, true) & 16777215)- };- if (chunk === "VP8L") {- const bits = view.getUint32(21, true);- return { width: 1 + (bits & 16383), height: 1 + (bits >> 14 & 16383) };- }- if (chunk === "VP8 ") {- at(26, 4);- return {- width: view.getUint16(26, true) & 16383,- height: view.getUint16(28, true) & 16383- };- }+}+function clipLoopIntent(clip) {+ const intent = clip.userData?.kilnLoopIntent;+ return intent === "loop" || intent === "once" ? intent : undefined;+}+function finishNativeAnimations(doc, clips) {+ const animations = doc.getRoot().listAnimations();+ let complete = true;+ for (const clip of clips) {+ const matches = animations.filter((animation) => animation.getName() === clip.name);+ const animation = matches.length === 1 ? matches[0] : undefined;+ if (!animation || animation.listChannels().length !== clip.tracks.length)+ complete = false;+ const intent = clipLoopIntent(clip);+ if (animation && intent)+ animation.setExtras({ ...animation.getExtras(), kilnLoopIntent: intent });}- return fail();+ return complete && animations.length === clips.length;+}+function reviewClipExtras(clips) {+ if (clips.length > REVIEW_CLIP_LIMITS2.clips) {+ throw new Error(`Animation review clip limit exceeded (${REVIEW_CLIP_LIMITS2.clips}).`);+ }+ let trackCount = 0;+ return {+ version: clips.some((clip) => clip.tracks.some(isCubicSplineTrack)) ? 2 : 1,+ clips: clips.map((clip) => ({+ name: clip.name,+ duration: clip.duration,+ ...clipLoopIntent(clip) ? { loopIntent: clipLoopIntent(clip) } : {},+ tracks: clip.tracks.map((track) => {+ trackCount++;+ if (trackCount > REVIEW_CLIP_LIMITS2.tracks) {+ throw new Error(`Animation review track limit exceeded (${REVIEW_CLIP_LIMITS2.tracks}).`);+ }+ if (track.times.length > REVIEW_CLIP_LIMITS2.samplesPerTrack || track.values.length > REVIEW_CLIP_LIMITS2.valuesPerTrack) {+ throw new Error("Animation review sample limit exceeded.");+ }+ const times = Array.from(track.times);+ const values = Array.from(track.values);+ if (!times.every(Number.isFinite) || !values.every(Number.isFinite)) {+ throw new Error("Animation review tracks must contain only finite values.");+ }+ return { name: track.name, times, values, interpolation: animationInterpolation(track) };+ })+ }))+ };}-function textureSource(texture) {- if (!object2(texture))- return;- const extensions = object2(texture.extensions) ? texture.extensions : {};- for (const name of ["KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif"]) {- const extension = extensions[name];- if (object2(extension) && index(extension.source) !== undefined)- return index(extension.source);- }- return index(texture.source);+function resolveOptimize(opt) {+ if (opt)+ return opt;+ const env = process.env["KILN_BAKE_OPTIMIZE"];+ return env === "auto" || env === "palette" || env === "full" ? env : "off";}-function srgbImages(json) {- const textures = Array.isArray(json.textures) ? json.textures : [];- const result = new Set;- for (const material of Array.isArray(json.materials) ? json.materials : []) {- if (!object2(material))- continue;- const pbr = object2(material.pbrMetallicRoughness) ? material.pbrMetallicRoughness : {};- for (const info of [pbr.baseColorTexture, material.emissiveTexture]) {- const texture = object2(info) ? index(info.index) : undefined;- const image = texture === undefined ? undefined : textureSource(textures[texture]);- if (image !== undefined)- result.add(image);- }- }- return result;+function resolveInstance(opt) {+ if (opt)+ return opt;+ const env = process.env["KILN_BAKE_INSTANCE"];+ return env === "off" || env === "auto" || env === "on" ? env : "auto";}-function base64(text) {- const binary = atob(text);- return Uint8Array.from(binary, (character) => character.charCodeAt(0));+function hasJointPivots(doc) {+ return doc.getRoot().listNodes().some((n) => /^joint[_-]/i.test(n.getName()));}-function embeddedImages(json, binary) {- const views = Array.isArray(json.bufferViews) ? json.bufferViews : [];- return (Array.isArray(json.images) ? json.images : []).map((image) => {- if (!object2(image))- throw new Error("Invalid glTF image");- const view = index(image.bufferView);- if (view !== undefined) {- const def = views[view];- if (!object2(def) || index(def.buffer) !== 0 || !binary)- throw new Error("Texture manifest requires images embedded in the GLB binary chunk");- const offset = index(def.byteOffset) ?? 0;- const length = index(def.byteLength);- if (length === undefined || offset + length > binary.byteLength)- throw new Error("Invalid glTF image buffer view");- if (typeof image.mimeType !== "string")- throw new Error("Embedded image needs a mimeType");- return { bytes: binary.subarray(offset, offset + length), mimeType: image.mimeType };- }- const match = typeof image.uri === "string" ? /^data:([^;,]+);base64,(.*)$/s.exec(image.uri) : null;- if (!match)- throw new Error("Texture manifest requires embedded image bytes");- return { bytes: base64(match[2]), mimeType: match[1] };- });+function hasNodeLevelsOfDetail(doc) {+ return doc.getRoot().listNodes().some((n) => n.getExtension(MSFT_LOD) !== null);}-async function runtimeTextureManifest(json, binary, options = {}) {- const srgb = srgbImages(json);- const entries = [];- for (const [image, { bytes, mimeType }] of embeddedImages(json, binary).entries()) {- const sha256 = `sha256:${await sha256Hex3(bytes)}`;- const sourceSha256 = options.sources?.get(image);- const original = sourceSha256 ?? sha256;- const map = options.maps?.find((candidate) => candidate.sha256 === original);- entries.push({- image,- sha256,- bytes: bytes.byteLength,- mimeType,- ...imageDimensions(bytes),- colorSpace: srgb.has(image) ? "srgb" : "linear",- ...sourceSha256 && sourceSha256 !== sha256 ? { sourceSha256 } : {},- ...map ? { material: { pin: { ...map.pin }, slot: map.slot } } : {}- });- }- return entries;+function hasPreservedNodeState(doc) {+ return doc.getRoot().listNodes().some((node) => node.getExtension("KHR_node_visibility") !== null || Object.keys(node.getExtras()).length > 0);}-function textureFileExtension(mimeType) {- const extension = {- "image/png": "png",- "image/jpeg": "jpg",- "image/webp": "webp",- "image/ktx2": "ktx2"- }[mimeType];- if (!extension)- throw new Error(`External textures do not support ${mimeType}`);- return extension;+async function applyGpuInstancing(doc, mode, role) {+ if (mode === "off")+ return;+ if (mode === "auto" && role !== "fill")+ return;+ const root = doc.getRoot();+ if (root.listAnimations().length > 0 || root.listSkins().length > 0)+ return;+ if (hasJointPivots(doc) || hasNodeLevelsOfDetail(doc) || hasPreservedNodeState(doc))+ return;+ const before = collectGlbMetrics(doc);+ await doc.transform(instance({ min: INSTANCE_MIN }));+ let batches = 0;+ let instances = 0;+ for (const node of root.listNodes()) {+ const ext = node.getExtension("EXT_mesh_gpu_instancing");+ if (!ext)+ continue;+ batches += 1;+ instances += ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 0;+ }+ if (batches === 0)+ return;+ const after = collectGlbMetrics(doc);+ return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };}-var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), index = (value) => Number.isInteger(value) && value >= 0 ? value : undefined, KTX2_IDENTIFIER, isKtx2 = (bytes) => bytes.byteLength >= 12 && KTX2_IDENTIFIER.every((value, at) => bytes[at] === value);-var init_runtime_textures = __esm(() => {- KTX2_IDENTIFIER = Object.freeze([- 171,- 75,- 84,- 88,- 32,- 50,- 48,- 187,- 13,- 10,- 26,- 10- ]);-});--// src/runtime-three.ts-var exports_runtime_three = {};-__export(exports_runtime_three, {- deliverRuntimeThreeGlb: () => deliverRuntimeThreeGlb-});-import {- Format,- Logger as Logger2,- PropertyType as PropertyType5-} from "@gltf-transform/core";-import {- EXTMeshGPUInstancing,- EXTMeshoptCompression,- KHRTextureBasisu as KHRTextureBasisu2-} from "@gltf-transform/extensions";-import { dedup as dedup2, quantize, reorder } from "@gltf-transform/functions";-import * as THREE55 from "three";-function meshSignature(mesh, ids) {- const id = (property) => {- if (!property)- return -1;- if (!ids.has(property))- ids.set(property, ids.size);- return ids.get(property);+async function consolidateMaterials(doc, mode, keep = []) {+ doc.setLogger(new Logger2(Logger2.Verbosity.WARN));+ const before = collectGlbMetrics(doc);+ const root = doc.getRoot();+ const steps = root.listMaterials().some((material) => Object.keys(material.getExtras()).length > 0) ? [] : [palette({ min: PALETTE_MIN })];+ let merge;+ if (mode === "full")+ steps.push(rigidMerge({ keep }, (summary) => {+ merge = summary;+ }));+ steps.push(weld2(), prune2({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));+ await doc.transform(...steps);+ const after = collectGlbMetrics(doc);+ return {+ mode,+ materialsBefore: before.uniqueMaterials,+ materialsAfter: after.uniqueMaterials,+ drawsBefore: before.drawCalls,+ drawsAfter: after.drawCalls,+ ...merge ? { rigidMerge: merge } : {}};- return mesh.listPrimitives().map((primitive) => `${primitive.getMode()}:${id(primitive.getMaterial())}:${id(primitive.getIndices())}:${primitive.listSemantics().sort().map((semantic) => `${semantic}=${id(primitive.getAttribute(semantic))}`).join(",")}:${primitive.listTargets().length}`).join("|");}-function applyScopedInstancing(doc) {- const report = [];- const ids = new Map;- const parents = doc.getRoot().listNodes().filter((node) => node.getExtras()[KILN_REPEAT_INSTANCES_KEY] !== undefined);- let extension;- for (const parent of parents) {- const groups = new Map;- for (const child of parent.listChildren()) {- const mesh = child.getMesh();- if (!mesh || child.listChildren().length || child.getSkin() || child.listExtensions().length || isHiddenGltfNode(child) || rolesOf4(child).length || Object.keys(child.getExtras()).length || child.getWeights().length)- continue;- const signature = meshSignature(mesh, ids);- groups.set(signature, [...groups.get(signature) ?? [], child]);- }- let batchIndex = 0;- for (const nodes of groups.values()) {- if (nodes.length < 2)- continue;- const mesh = nodes[0].getMesh();- extension ??= doc.createExtension(EXTMeshGPUInstancing).setRequired(true);- const buffer = doc.getRoot().listBuffers()[0];- const accessor = (type, values) => doc.createAccessor().setType(type).setArray(new Float32Array(values)).setBuffer(buffer ?? null);- const t = [], r = [], s = [];- for (const node of nodes) {- t.push(...node.getTranslation());- r.push(...node.getRotation());- s.push(...node.getScale());- }- const batch = extension.createInstancedMesh().setAttribute("TRANSLATION", accessor("VEC3", t)).setAttribute("ROTATION", accessor("VEC4", r)).setAttribute("SCALE", accessor("VEC3", s));- const name = `${parent.getName() || "Node"}_Instances${batchIndex ? `_${batchIndex}` : ""}`;- batchIndex++;- const batchNode = doc.createNode(name).setMesh(mesh).setExtension("EXT_mesh_gpu_instancing", batch);- parent.addChild(batchNode);- report.push({- node: batchNode,- mesh: mesh.getName(),- count: nodes.length,- instances: nodes.map((node) => node.getName())- });- for (const node of nodes) {- const own = node.getMesh();- node.dispose();- if (own && own !== mesh && !own.listParents().some((p) => p.propertyType === PropertyType5.NODE))- own.dispose();+function optimizeWarnings(summary) {+ const merge = summary.rigidMerge;+ if (!merge)+ return [];+ const warnings = [];+ if (merge.skipped)+ warnings.push(`Rigid merge skipped: ${merge.skipped}; geometry left separate.`);+ if (merge.rejected.length)+ warnings.push(`Rigid merge retained ${merge.rejected.length} rejected buckets; first: ${merge.rejected[0].error}`);+ if (merge.unmatchedKeep.length)+ warnings.push(`Rigid merge did not find ${merge.unmatchedKeep.length} requested boundary names.`);+ return warnings;+}+async function renderSceneToGLB(root, opts = {}) {+ assertNoLegacyRuntimePolicy(opts);+ const requirements = resolveRequirementsContext(opts.requirements);+ const clips = opts.clips ?? [];+ const indexPolicy = resolveIndexPolicy(opts.indexPolicy);+ if (indexPolicy === "asBuilt" && resolveOptimize(opts.optimize) !== "off")+ throw new Error("asBuilt indexPolicy requires optimize off to preserve authored buffers");+ if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))+ throw new Error("geometryPolicy must be warn or strict");+ const exporter = resolveGltfExporter(opts.gltfExporter);+ const skinIntegrity = inspectSkinIntegrity(root);+ if (skinIntegrity.findings.length) {+ throw new AssetQaBlockedError(createRequirementsQaReport(requirements, {+ findings: skinIntegrity.findings,+ executedRules: [],+ evaluatedDimensions: ["exportIntegrity"],+ metrics: {+ exportIntegrity: {+ skinMeshesChecked: skinIntegrity.meshesChecked,+ skinVerticesChecked: skinIntegrity.verticesChecked,+ skinInspectionTruncated: skinIntegrity.truncated+ }}+ }), "scene");+ }+ assertPortableMaterialSides(root);+ const lodSets = opts.derivative === true ? [] : collectLodSets(root);+ if (opts.derivative !== true)+ assertRequiredSolids(root);+ const warnings = inspectGeometryExport(root, opts.geometryPolicy, exporter);+ let tris = countTriangles(root);+ for (const set of lodSets)+ for (const level of set.levels.slice(1))+ tris -= countTriangles(level);+ const hiddenTris = hiddenTriangles(root, new Set(lodSets.flatMap((set) => set.levels.slice(1))));+ if (hiddenTris > 0 && hiddenTris === tris)+ throw new Error("renderSceneToGLB: every triangle is hidden (visible = false on the root or on every part), so nothing draws. Hide parts inside the asset, not all of it.");+ tris -= hiddenTris;+ const materialRecipeApplications = collectMaterialRecipeApplications(root);+ const materialResourceProvenance = collectMaterialResourceProvenance(root);+ for (const w of inspectGeneratedAnimation(root, clips))+ warnings.push(w);+ const externalSupport = requirements.requirements.requirements.externalSupport;+ for (const w of inspectSceneStructure(root, {+ ...externalSupport?.state === "requested" ? { externalSupport: externalSupport.value.supports } : {}+ }))+ warnings.push(w);+ const atlas = collectAtlasProvenance(root);+ const bakedTextures = await bakeSceneTextures(root, warnings);+ ensureNormalMapTangents(root, warnings);+ const qaPolicy = qaPolicyFromEnv();+ const sceneEvidence = await collectRequirementsSceneEvidence(requirements, root, qaPolicy);+ const sceneQaReport = runRequirementsSceneQa(requirements, root, clips, qaPolicy, sceneEvidence);+ const qaBlocks = qaBlockingEnabled() && opts.derivative !== true;+ const qaSuppressedBy = opts.derivative === true ? "derivative re-serialization" : "KILN_QA_MODE";+ if (sceneQaReport.disposition === "block") {+ const blocked = new AssetQaBlockedError(sceneQaReport, "scene");+ if (qaBlocks)+ throw blocked;+ warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);+ }+ const nativeClips = clipsWithDurationSamples(clips);+ const authorExtras = collectAuthorExtras(root);+ warnings.push(...authorExtras.warnings);+ const doc = exporter === "three" ? await communitySceneDocument(root, nativeClips, (await Promise.resolve().then(() => (init_exporter_node(), exports_exporter_node))).nodeExportPlatform, authorExtras, atlas) : new Document;+ doc.getRoot().getAsset().generator = "Kiln";+ if (exporter === "legacy") {+ const buf = doc.createBuffer();+ const matCache = new Map;+ const meshCache = new Map;+ const texCache = new Map;+ const nodeMap = new Map;+ const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache, authorExtras, atlas);+ const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);+ doc.getRoot().setDefaultScene(gltfScene);+ if (clips.length > 0) {+ const review = reviewClipExtras(clips);+ bridgeAnimations(doc, buf, nativeClips, nodeMap, warnings);+ if (!finishNativeAnimations(doc, nativeClips))+ gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: review });+ }+ } else {+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ if (!scene)+ throw new Error("Community exporter produced no scene.");+ scene.setName(opts.sceneName ?? "Scene");+ if (clips.length > 0) {+ const review = reviewClipExtras(clips);+ if (!finishNativeAnimations(doc, nativeClips))+ scene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: review });}- const extras = { ...parent.getExtras() };- delete extras[KILN_REPEAT_INSTANCES_KEY];- parent.setExtras(extras);}- return report;-}-function splitColliderProxies(doc) {- const report = [];- for (const node of doc.getRoot().listNodes()) {- const mesh = node.getMesh();- if (!mesh || !isCollider(node))- continue;- const proxy = doc.createNode(`${node.getName()}_Proxy`).setMesh(mesh);- node.setMesh(null).addChild(proxy);- report.push({ collider: node, proxy });+ if (atlas.table) {+ const scene = doc.getRoot().getDefaultScene();+ scene.setExtras({ ...scene.getExtras(), kilnAtlasProvenance: atlas.table });}- return report;-}-async function encodeKtx2(doc, encoder, sources) {- const textures = doc.getRoot().listTextures().filter((texture) => texture.getMimeType() !== "image/ktx2" && texture.getImage());- if (!encoder)- return {- status: "skipped",- textures: textures.length,- reason: "No KTX2 encoder was supplied; textures stay PNG or JPEG."- };- const slots = new Map;- const use = (texture, slot) => {- if (texture)- slots.set(texture, (slots.get(texture) ?? new Set).add(slot));- };- for (const material of doc.getRoot().listMaterials()) {- use(material.getBaseColorTexture(), "baseColor");- use(material.getEmissiveTexture(), "emissive");- use(material.getNormalTexture(), "normal");- use(material.getMetallicRoughnessTexture(), "metallicRoughness");- use(material.getOcclusionTexture(), "occlusion");+ if (root.userData[KILN_BUDGET_KEY] !== undefined && opts.derivative !== true) {+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ scene.setExtras({+ ...scene.getExtras(),+ [KILN_BUDGET_KEY]: normalizeBudget(root.userData[KILN_BUDGET_KEY])+ });}- const order = [- "baseColor",- "emissive",- "normal",- "metallicRoughness",- "occlusion"- ];- for (const texture of textures) {- const used = slots.get(texture) ?? new Set;- const srgb = used.has("baseColor") || used.has("emissive");- const other = texture.listParents().some((parent) => parent.propertyType !== PropertyType5.ROOT && !isCoreMaterialUse(parent));- const linear = [...used].some((slot) => slot !== "baseColor" && slot !== "emissive") || other;- if (srgb && linear)- throw new Error(`Texture ${JSON.stringify(texture.getName())} is used by both sRGB and linear material slots; one KTX2 encoding cannot serve both. Use separate images.`);- const original = texture.getImage();- const image = await encoder({- image: original,- mimeType: texture.getMimeType(),- name: texture.getName(),- colorSpace: srgb ? "srgb" : "linear",- slot: order.find((slot) => used.has(slot)) ?? "other"+ if (root.userData[KILN_PALETTE_KEY] !== undefined && opts.derivative !== true) {+ const declared = root.userData[KILN_PALETTE_KEY];+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ scene.setExtras({+ ...scene.getExtras(),+ [KILN_PALETTE_KEY]: normalizePalette(declared?.colors, { threshold: declared?.threshold })});- if (!(image instanceof Uint8Array) || !isKtx2(image))- throw new Error("ktx2Encoder must return KTX2 bytes starting with the KTX2 identifier");- sources.set(texture, `sha256:${await sha256Hex3(original)}`);- texture.setImage(image).setMimeType("image/ktx2");- const uri = texture.getURI();- if (uri)- texture.setURI(uri.replace(/\.(png|jpe?g)$/i, ".ktx2"));}- if (textures.length) {- doc.createExtension(KHRTextureBasisu2).setRequired(true);- await Promise.resolve().then(() => init_atlas_provenance());- await refreshAtlasDocumentProvenance(doc);- await validateAtlasDocumentProvenance(doc);+ applySurfaceBakeExtras(root, doc);+ applyNodeVisibility(root, doc);+ applyLodChains(root, lodSets, doc);+ const indexBuffers = applyIndexPolicy(doc, indexPolicy);+ if (opts.dedup !== false) {+ try {+ await doc.transform(dedup2());+ } catch (err) {+ warnings.push(`dedup transform failed: ${err instanceof Error ? err.message : String(err)}`);+ }+ }+ let instancing;+ try {+ instancing = await applyGpuInstancing(doc, resolveInstance(opts.instance), opts.role);+ } catch (err) {+ warnings.push(`instance transform failed: ${err instanceof Error ? err.message : String(err)}`);+ }+ const optimizeMode = resolveOptimize(opts.optimize);+ let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;+ if (optimizeMode === "auto" && collectGlbMetrics(doc, tris).uniqueMaterials >= PALETTE_MIN) {+ effectiveOptimize = "palette";+ }+ let optimize;+ if (effectiveOptimize !== "off") {+ try {+ optimize = await consolidateMaterials(doc, effectiveOptimize);+ warnings.push(...optimizeWarnings(optimize));+ } catch (err) {+ warnings.push(`optimize (${effectiveOptimize}) failed: ${err instanceof Error ? err.message : String(err)}`);+ }+ }+ let instanceability;+ let metricsError;+ try {+ const metrics = collectGlbMetrics(doc, optimize || instancing ? undefined : tris);+ instanceability = gradeInstanceability(metrics, {+ mergeCandidates: materialMergeCandidates(doc)+ });+ } catch (err) {+ metricsError = err instanceof Error ? err.message : String(err);+ }+ let materialMetrics;+ let materialBudgetWarnings = [];+ try {+ materialMetrics = collectMaterialMetricsV1(doc);+ materialBudgetWarnings = evaluateMaterialBudgetV1(materialMetrics, {+ profile: "web.portable.v1",+ tier: "standard"+ });+ } catch (error) {+ warnings.push(`material metrics failed: ${error instanceof Error ? error.message : String(error)}`);+ }+ const io = engineIO();+ ensureDefaultScene(doc);+ await refreshAtlasDocumentProvenance(doc);+ await validateAtlasDocumentProvenance(doc);+ const bytes = await io.writeBinary(doc);+ const artifactGlbSha256 = `sha256:${await sha256Hex3(bytes)}`;+ const boundBakedTextures = bakedTextures.map((entry) => ({+ ...entry,+ artifactGlbSha256+ }));+ const gltfValidation = await validateFinalGlbBytes(bytes);+ const qaReport = await appendRequirementsFinalQa(requirements, sceneQaReport, gltfValidation, bytes, instanceability, metricsError, materialMetrics, materialBudgetWarnings);+ if (qaReport.disposition === "block") {+ const blocked = new AssetQaBlockedError(qaReport, "final-glb", gltfValidation);+ if (qaBlocks)+ throw blocked;+ warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);+ }+ for (const issue of gltfValidation.issues.messages) {+ if (issue.severity !== 1)+ continue;+ warnings.push(`glTF ${issue.code}${issue.pointer ? ` at ${issue.pointer}` : ""}: ${issue.message}`);+ }+ const integrationManifest = await inspectGlbIntegration(bytes, {+ ...opts.role ? { requestedRole: opts.role } : {},+ validation: gltfValidation+ });+ if (!integrationManifest)+ throw new Error("renderSceneToGLB: final GLB has no measurable scene");+ for (const finding of integrationManifest.deliveryDiagnostics ?? [])+ warnings.push(`${finding.code} ${finding.path}: ${finding.message}`);+ const palette = integrationManifest.palette;+ for (const finding of palette?.offPalette ?? [])+ warnings.push(`PALETTE_OFF material ${JSON.stringify(finding.material)} ${finding.color} is delta E ${finding.deltaE} from the nearest palette entry ${finding.nearest} (threshold ${palette.threshold})${finding.textured ? "; the factor tints a texture that is not judged" : ""}.`);+ const diagnosticViews = [];+ const rig = requirements.requirements.requirements.rig;+ const diagnosticParents = new Map(lodSets.map(({ parent }) => [parent, [...parent.children]]));+ for (const { parent, levels } of lodSets)+ for (const level of levels.slice(1))+ parent.remove(level);+ try {+ if (rig?.state === "requested") {+ await Promise.resolve().then(() => init_character_capture());+ diagnosticViews.push(...await captureCharacterDiagnosticViews(root, clips, rig.value, Object.values(qaReport.dimensions).flatMap((d) => d.findings)));+ }+ if (requirements.requirements.requirements.mobility?.state === "requested") {+ await Promise.resolve().then(() => init_views());+ diagnosticViews.push(...captureVehicleDiagnosticViews(root));+ }+ } finally {+ for (const [parent, children] of diagnosticParents) {+ parent.clear();+ parent.add(...children);+ }}return {- status: "encoded",- textures: textures.length,- ...encoder.identity ? { encoder: structuredClone(encoder.identity) } : {}+ bytes,+ indexBuffers,+ requirements,+ artifactGlbSha256,+ tris,+ warnings,+ gltfValidation,+ qaReport,+ instanceability,+ metricsError,+ ...optimize ? { optimize } : {},+ ...instancing ? { instancing } : {},+ ...materialMetrics ? { materialMetrics } : {},+ ...materialRecipeApplications.length ? { materialRecipeApplications } : {},+ ...materialResourceProvenance.length ? { materialResourceProvenance } : {},+ ...boundBakedTextures.length ? { bakedTextures: boundBakedTextures } : {},+ integrationManifest,+ ...diagnosticViews.length ? { diagnosticViews } : {}};}-function isCoreMaterialUse(parent) {- return parent.propertyType === PropertyType5.MATERIAL;-}-function decomposeDelta(before, after) {- const delta = new THREE55.Matrix4().fromArray(before).invert().multiply(new THREE55.Matrix4().fromArray(after));- const position = new THREE55.Vector3, quaternion = new THREE55.Quaternion, scale = new THREE55.Vector3;- delta.decompose(position, quaternion, scale);+async function renderGLBInProcess(code, opts = {}) {+ assertNoLegacyRuntimePolicy(opts);+ const requirements = resolveRequirementsContext(opts.requirements);+ if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))+ throw new Error("geometryPolicy must be warn or strict");+ let textureResolver = opts.textureResolver ?? DEFAULT_TEXTURE_RESOLVER;+ const rebuildOptions = {+ indexPolicy: resolveIndexPolicy(opts.indexPolicy),+ gltfExporter: resolveGltfExporter(opts.gltfExporter),+ geometryPolicy: opts.geometryPolicy ?? "warn",+ optimize: resolveOptimize(opts.optimize),+ ...resolveOptimize(opts.optimize) === "full" ? { optimizationPipeline: FULL_OPTIMIZATION_PIPELINE } : {},+ instance: resolveInstance(opts.instance)+ };+ let materialLibraryDependencies;+ if (opts.materialResources) {+ await Promise.resolve().then(() => init_material_library_node());+ const materialRecords = await decodeMaterialLibraryPayload(opts.materialResources);+ materialLibraryDependencies = materialRecords.map((record) => structuredClone(record.manifest));+ textureResolver = await createMaterialLibraryTextureResolver(materialRecords, textureResolver);+ }+ const { meta, root, clips, primitiveUsage } = await executeKilnCode(code, {+ textureResolver,+ console: opts.diagnosticConsole+ });+ const scene = await renderSceneToGLB(root, {+ ...rebuildOptions,+ sceneName: meta.name || "Scene",+ clips,+ requirements: requirements.binding,+ role: meta.role+ });+ const {+ category: modelCategory,+ requirements: _requirements,+ intent: _intent,+ policyHash: _policyHash,+ adviceHash: _adviceHash,+ binding: _binding,+ ...modelMeta+ } = meta;return {- scale: scale.x,- offset: [position.x, position.y, position.z]+ glb: Buffer.from(scene.bytes),+ rebuildOptions,+ ...materialLibraryDependencies ? { materialLibraryDependencies } : {},+ requirements: scene.requirements,+ artifactGlbSha256: scene.artifactGlbSha256,+ tris: scene.tris,+ meta: {+ ...modelMeta,+ indexBuffers: scene.indexBuffers,+ ...modelCategory !== undefined ? { modelCategory } : {},+ tris: scene.tris,+ primitiveUsage,+ ...scene.instanceability ? { instanceability: scene.instanceability, tier: scene.instanceability.grade } : {},+ ...scene.metricsError ? { metricsError: scene.metricsError } : {},+ ...scene.optimize ? { optimize: scene.optimize } : {},+ ...scene.instancing ? { instancing: scene.instancing } : {},+ gltfValidation: scene.gltfValidation,+ qaReport: scene.qaReport+ },+ warnings: scene.warnings,+ ...scene.diagnosticViews ? { diagnosticViews: scene.diagnosticViews } : {},+ ...scene.materialMetrics ? { materialMetrics: scene.materialMetrics } : {},+ ...scene.materialRecipeApplications ? { materialRecipeApplications: scene.materialRecipeApplications } : {},+ ...scene.materialResourceProvenance ? { materialResourceProvenance: scene.materialResourceProvenance } : {},+ ...scene.bakedTextures ? { bakedTextures: scene.bakedTextures } : {},+ integrationManifest: scene.integrationManifest};}-async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layout = {}) {- const compression = options.compression ?? "meshopt";- if (compression !== "meshopt" && compression !== "none")- throw new Error("Runtime three compression must be meshopt or none");- const io = createGltfIO().registerDependencies({- "meshopt.encoder": meshoptEncoder+function inspectGeneratedAnimation(root, clips) {+ const warnings = [];+ if (clips.length === 0)+ return warnings;+ const nodeNames = new Set;+ root.traverse((obj) => {+ if (obj.name)+ nodeNames.add(obj.name);});- const doc = await io.readBinary(bytes);- doc.setLogger(new Logger2(Logger2.Verbosity.SILENT));- await doc.transform(dedup2({ propertyTypes: [PropertyType5.ACCESSOR], keepUniqueNames: true }));- const instanced = applyScopedInstancing(doc);- const proxies = splitColliderProxies(doc);- const matrices = new Map;- for (const node of doc.getRoot().listNodes())- if (node.getMesh())- matrices.set(node, [...node.getMatrix()]);- await doc.transform(reorder({ encoder: meshoptEncoder, target: "size" }), quantize({- pattern: QUANTIZED_SEMANTICS,- patternTargets: QUANTIZED_SEMANTICS,- quantizationVolume: "mesh",- quantizePosition: RUNTIME_THREE_QUANTIZATION.position,- quantizeNormal: RUNTIME_THREE_QUANTIZATION.normal,- quantizeTexcoord: RUNTIME_THREE_QUANTIZATION.texcoord,- quantizeColor: RUNTIME_THREE_QUANTIZATION.color,- quantizeWeight: RUNTIME_THREE_QUANTIZATION.weight- }));- if (compression === "meshopt")- doc.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE });- const encodedSources = new Map;- const ktx2 = await encodeKtx2(doc, options.ktx2Encoder, encodedSources);- for (const node of doc.getRoot().listNodes()) {- const mesh = node.getMesh();- if (!mesh || matrices.has(node) || node.getName())- continue;- const parent = node.getParentNode();- node.setName(`${parent?.getName() || "Node"}_Mesh`);+ for (const clip of clips) {+ for (const track of clip.tracks) {+ const dotIdx = track.name.lastIndexOf(".");+ if (dotIdx === -1) {+ warnings.push(`Track "${track.name}" is missing a node.property separator`);+ continue;+ }+ const nodeName = track.name.substring(0, dotIdx);+ const property = track.name.substring(dotIdx + 1);+ 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}"`);+ }+ }}- const after = deliveryNodePaths(doc);- const pathOf = (node) => after.get(node) ?? `#${encodeURIComponent(node.getName())}`;- const proxyNodes = new Set(proxies.map((entry) => entry.proxy));- const nodeScale = [];- for (const node of doc.getRoot().listNodes()) {- const mesh = node.getMesh();- if (!mesh || node.getExtension("EXT_mesh_gpu_instancing"))- continue;- const path = after.get(node);- if (path === undefined)- continue;- const original = matrices.get(node);- const moved = original === undefined;- const split = moved || proxyNodes.has(node);- const reference = moved ? new THREE55.Matrix4().identity().toArray() : original;- const current = [...node.getMatrix()];- const { scale, offset } = decomposeDelta(reference, current);- if (!moved && Math.abs(scale - 1) < 0.000000000001 && offset.every((v) => v === 0))- continue;- const parent = node.getParentNode();- nodeScale.push({- node: path,- mesh: mesh.getName(),- meshMovedToChild: split,- ...split && parent ? { authoredNode: pathOf(parent) } : {},- dequantization: { scale, offset },- localScale: [...node.getScale()]+ return warnings;+}+function collectMeshStats(root) {+ root.updateMatrixWorld(true);+ const out = [];+ root.traverseVisible((obj) => {+ if (!obj.isMesh)+ return;+ const meshObj = obj;+ const geo = meshObj.geometry;+ if (!geo)+ return;+ const idx = geo.getIndex();+ const tri = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;+ const bounded = meshObj;+ let localBounds;+ if (bounded.boundingBox !== undefined) {+ if (bounded.boundingBox === null)+ bounded.computeBoundingBox?.();+ localBounds = bounded.boundingBox ?? null;+ } else {+ if (geo.boundingBox === null)+ geo.computeBoundingBox();+ localBounds = geo.boundingBox;+ }+ if (!localBounds)+ return;+ const box = localBounds.clone().applyMatrix4(meshObj.matrixWorld);+ if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {+ return;+ }+ const center = new THREE55.Vector3;+ const size = new THREE55.Vector3;+ box.getCenter(center);+ box.getSize(size);+ out.push({+ object: obj,+ name: obj.name || "(unnamed)",+ triCount: Math.floor(tri),+ isPlaneGeo: geo.type === "PlaneGeometry",+ center,+ size,+ box});+ });+ return out;+}+function minimalGapVector(a, b) {+ const v = new THREE55.Vector3;+ for (const axis of ["x", "y", "z"]) {+ if (a.min[axis] > b.max[axis])+ v[axis] = b.max[axis] - a.min[axis];+ else if (a.max[axis] < b.min[axis])+ v[axis] = b.min[axis] - a.max[axis];+ else+ v[axis] = 0;}- for (const node of doc.getRoot().listNodes()) {- const mesh = node.getMesh();- if (!mesh || after.has(node) || !matrices.has(node))+ return v;+}+function inspectSceneStructure(root, opts = {}) {+ const warnings = [];+ const meshes = collectMeshStats(root);+ if (meshes.length === 0)+ return warnings;+ const cat = opts.category?.toLowerCase();+ if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {+ const all = new THREE55.Box3;+ for (const m of meshes)+ all.union(m.box);+ const size = new THREE55.Vector3;+ all.getSize(size);+ if (cat === "aircraft") {+ if (size.y > size.x * 1.2) {+ warnings.push(`Orientation: this aircraft is ${size.y.toFixed(2)} tall but only ${size.x.toFixed(2)} long along +X (the nose axis). Kiln aircraft fly nose-first along +X — it may be built vertically or sideways.`);+ }+ } else if (size.z > size.x * 1.3) {+ warnings.push(`Orientation: this ${cat} spans ${size.z.toFixed(2)} along Z but only ${size.x.toFixed(2)} along +X. Kiln ${cat}s face +X (forward/muzzle/bow) — it looks built sideways; rebuild the long axis along X.`);+ }+ }+ const STRAY_CENTROID_TOL = 0.02;+ const FLOATING_EXPAND = 0.02;+ const DECAL_EXTENT_MAX = 0.5;+ for (const m of meshes) {+ if (!m.isPlaneGeo)continue;- const { scale, offset } = decomposeDelta(matrices.get(node), [...node.getMatrix()]);- nodeScale.push({- node: `#lod/${encodeURIComponent(node.getName())}`,- mesh: mesh.getName(),- meshMovedToChild: false,- dequantization: { scale, offset },- localScale: [...node.getScale()]- });+ if (m.triCount > 2)+ continue;+ if (m.size.length() > DECAL_EXTENT_MAX)+ continue;+ if (m.center.length() < STRAY_CENTROID_TOL) {+ warnings.push(`Stray plane "${m.name}" at world origin (centroid ≈ [0,0,0]). Replace planeGeo with decalBox and position on a host surface, or move this mesh into place.`);+ }}- const customAttributes = new Map;- for (const mesh of doc.getRoot().listMeshes())- for (const primitive of mesh.listPrimitives())- for (const semantic of primitive.listSemantics())- if (semantic.startsWith("_"))- customAttributes.set(semantic, (customAttributes.get(semantic) ?? new Set).add(mesh));- const all = doc.getRoot().listNodes();- const glb = await io.writeBinary(doc);- const json = (await io.binaryToJSON(glb)).json;- const imageSources = new Map;- doc.getRoot().listTextures().forEach((texture, image) => {- const source = encodedSources.get(texture);- if (source)- imageSources.set(image, source);- });- const gltf = layout.gltfBasename ? await io.writeJSON(doc, { format: Format.GLTF, basename: layout.gltfBasename }) : undefined;- const delivery = {- target: "three",- extensionsUsed: [...json.extensionsUsed ?? []].sort(),- extensionsRequired: [...json.extensionsRequired ?? []].sort(),- compression: compression === "meshopt" ? { extension: "EXT_meshopt_compression", method: "quantize" } : { extension: "none" },- quantization: {- extension: "KHR_mesh_quantization",- volume: "mesh",- bits: {- position: RUNTIME_THREE_QUANTIZATION.position,- normal: RUNTIME_THREE_QUANTIZATION.normal,- texcoord: RUNTIME_THREE_QUANTIZATION.texcoord,- color: RUNTIME_THREE_QUANTIZATION.color,- weight: RUNTIME_THREE_QUANTIZATION.weight- },- customAttributes: "float32"- },- nodeScale,- colliderProxies: proxies.map(({ collider, proxy }) => ({- collider: pathOf(collider),- proxy: pathOf(proxy)- })),- customAttributes: [...customAttributes].sort(([a], [b]) => customRank(a) - customRank(b) || (a < b ? -1 : a > b ? 1 : 0)).map(([name, meshes]) => ({- name,- meshes: meshes.size,- componentType: "FLOAT",- normalized: false- })),- instancing: instanced.map(({ node, ...rest }) => ({ node: pathOf(node), ...rest })),- ktx2,- preserved: {- lodChains: all.filter((node) => node.getExtension(MSFT_LOD)).length,- hiddenNodes: all.filter((node) => isHiddenGltfNode(node)).length,- colliders: all.filter(isCollider).length,- anchors: all.filter((node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.anchor}.`))).length,- ports: all.filter((node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.kitPort}.`))).length,- kitModules: all.filter((node) => rolesOf4(node).includes(KILN_SEMANTIC_ROLES.kitModule)).length+ if (meshes.length > 1) {+ const floaters = [];+ const supported = [];+ for (let i = 0;i < meshes.length; i++) {+ const a = meshes[i];+ const ax = a.box.clone().expandByScalar(FLOATING_EXPAND);+ let overlapsAny = false;+ for (let j = 0;j < meshes.length; j++) {+ if (i === j)+ continue;+ const b = meshes[j];+ if (ax.intersectsBox(b.box)) {+ overlapsAny = true;+ break;+ }+ }+ if (overlapsAny)+ continue;+ const support = restingSupport(a.object, a.box.min.y, opts.externalSupport);+ if (support) {+ supported.push(`${a.name} at Y=${support.planeY.toFixed(3)}`);+ continue;+ }+ const declared = declaredSupports(a.object, opts.externalSupport)[0];+ let nearest;+ 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()) {+ nearest = meshes[j];+ nearestGap = gap;+ }+ }+ const fix = nearest && nearestGap ? ` Fix: shift "${a.name}" by [${nearestGap.x.toFixed(3)}, ${nearestGap.y.toFixed(3)}, ${nearestGap.z.toFixed(3)}] toward "${nearest.name}", or call snapTo(part, hostPart) to do it automatically.` : "";+ const mismatch = declared ? ` It is named in a declared external support at Y=${declared.planeY.toFixed(3)}, but its bottom is at Y=${a.box.min.y.toFixed(3)}.` : "";+ floaters.push({ name: a.name, fix: fix + mismatch });}- };- return {- glb,- delivery,- imageSources,- ...gltf ? {- gltf: {- json: gltf.json,- resources: gltf.resources+ if (floaters.length > 0) {+ const entries = floaters.slice(0, FLOATER_FIXES_SHOWN).map(({ name, fix }) => `${name}${fix ? ` —${fix}` : ""}`);+ const rest = floaters.slice(FLOATER_FIXES_SHOWN);+ if (rest.length > 0) {+ const names = rest.slice(0, FLOATER_NAMES_SHOWN).map((floater) => floater.name);+ if (rest.length > names.length)+ names.push(`+${rest.length - names.length} more`);+ entries.push(`+${rest.length} more floating: ${names.join(", ")} — the same fix applies: shift each onto its nearest sibling, or call snapTo(part, hostPart).`);}- } : {}- };+ warnings.push(`Floating parts (no mesh overlap with any sibling, 2cm tol): ${entries.join(" | ")}`);+ }+ if (supported.length > 0) {+ const shown = supported.slice(0, FLOATER_NAMES_SHOWN);+ if (supported.length > shown.length)+ shown.push(`+${supported.length - shown.length} more`);+ warnings.push(`Declared external support (requirements.externalSupport): ${shown.join(", ")} rest on a support composed outside this asset; information only, no action needed.`);+ }+ }+ return warnings;}-var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, customRank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2, rolesOf4 = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));-var init_runtime_three = __esm(() => {- init_semantic();+var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", ACCESSOR_TYPES, GROUND_CONTACT_TOLERANCE = 0.02, GLTF_MIN_FILTER, GLTF_MAG_FILTER, GLTF_WRAP, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5, FLOATER_FIXES_SHOWN = 6, FLOATER_NAMES_SHOWN = 24;+var init_render = __esm(() => {+ init_requirements_context();+ init_requirements_run();+ init_requirements_report();+ init_skin_integrity();+ init_authoring_diagnostic();init_gltf_io();- init_delivery_inspect();+ init_lod();+ init_lod_export();+ init_node_visibility();+ init_community_exporter();+ init_atlas_provenance();+ init_material_export();+ init_animation_spline();+ init_index_policy();+ init_open_shell();init_delivery();+ init_delivery_inspect();+ init_surface_bake();+ init_require_solid();+ init_rig_export();+ init_geometry_export();+ init_primitives();+ init_budget();+ init_palette_check();init_metrics();- init_runtime_textures();- RUNTIME_THREE_QUANTIZATION = Object.freeze({- volume: "mesh",- position: 14,- normal: 10,- texcoord: 12,- color: 8,- weight: 8- });- QUANTIZED_SEMANTICS = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;+ init_contracts();+ init_gltf();+ init_run();+ init_material_metrics();+ init_material_recipe_runtime();+ init_material_resources();+ init_texture_resolver();+ init_rebuild_options();+ init_rigid_merge();+ init_validation();+ init_kit();+ init_texture_bake();+ engineIO = createGltfIO;+ ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];+ GLTF_MIN_FILTER = {+ [THREE55.NearestFilter]: 9728,+ [THREE55.LinearFilter]: 9729,+ [THREE55.NearestMipmapNearestFilter]: 9984,+ [THREE55.LinearMipmapNearestFilter]: 9985,+ [THREE55.NearestMipmapLinearFilter]: 9986,+ [THREE55.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE55.NearestFilter]: 9728, [THREE55.LinearFilter]: 9729 };+ GLTF_WRAP = {+ [THREE55.ClampToEdgeWrapping]: 33071,+ [THREE55.MirroredRepeatWrapping]: 33648,+ [THREE55.RepeatWrapping]: 10497+ };+ REVIEW_CLIP_LIMITS2 = {+ clips: 32,+ tracks: 256,+ samplesPerTrack: 4096,+ valuesPerTrack: 16384+ };+});++// src/evaluator/protocol.ts+function evaluatorOutcomeMessage(code) {+ return EVALUATOR_OUTCOME_MESSAGES[code];+}+function resolveEvaluatorPortV2(port, profile) {+ if (port)+ return port;+ if (profile === "evaluator-required") {+ throw new EvaluatorPortError("ISOLATION_UNAVAILABLE", "Evaluator port is required.");+ }+ return trustedInProcessEvaluatorPortV2;+}+var MAX_EVALUATOR_CODE_BYTES, MAX_EVALUATOR_REQUEST_BYTES, DEFAULT_EVALUATOR_MAX_GLB_BYTES, DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES, EVALUATOR_OUTCOME_MESSAGES, EvaluatorPortError, trustedInProcessEvaluatorPortV2;+var init_protocol = __esm(() => {+ init_authoring_diagnostic();+ init_requirements_context();+ init_requirements_report();+ init_material_library_node();+ init_material_library();+ init_rebuild_options();+ init_solid_diagnostic();+ MAX_EVALUATOR_CODE_BYTES = 512 * 1024;+ MAX_EVALUATOR_REQUEST_BYTES = 24 * 1024 * 1024;+ DEFAULT_EVALUATOR_MAX_GLB_BYTES = 16 * 1024 * 1024;+ DEFAULT_EVALUATOR_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;+ EVALUATOR_OUTCOME_MESSAGES = {+ INPUT_INVALID: "Evaluator request was invalid. Use kiln.evaluator.request.v2 and update the host and worker together. Retired category/intent options require explicit requirements migration; see docs/migration.md.",+ EXECUTION_REJECTED: "Generated asset execution was rejected.",+ QA_BLOCKED: "Generated asset did not pass quality checks.",+ DEADLINE_EXCEEDED: "Evaluator deadline exceeded.",+ CANCELLED: "Evaluator request was cancelled.",+ OUTPUT_LIMIT_EXCEEDED: "Evaluator output limit exceeded.",+ ISOLATION_UNAVAILABLE: "Isolated evaluator is unavailable.",+ WORKER_FAILED: "Evaluator worker failed.",+ PROTOCOL_ERROR: "Evaluator returned invalid data."+ };+ EvaluatorPortError = class EvaluatorPortError extends Error {+ code;+ diagnostic;+ solid;+ constructor(code, message = evaluatorOutcomeMessage(code), diagnostic, solid) {+ super(diagnostic ? `${message} ${authoringDiagnosticAdvice(diagnostic)}${solidFailureAdvice(solid)}` : code === "EXECUTION_REJECTED" ? `${message} ${EXECUTION_REJECTED_ADVICE}` : message);+ this.code = code;+ this.diagnostic = diagnostic;+ this.solid = solid;+ this.name = "EvaluatorPortError";+ }+ };+ trustedInProcessEvaluatorPortV2 = {+ async render(code, options = {}, controls = {}) {+ if (controls.signal?.aborted)+ throw new EvaluatorPortError("CANCELLED");+ await Promise.resolve().then(() => init_render());+ const result = await renderGLBInProcess(code, options);+ if (controls.signal?.aborted)+ throw new EvaluatorPortError("CANCELLED");+ return result;+ }+ };});// src/asset-export.ts@@ -38868,6 +39070,10 @@ async function exportAssetGlb(record, options = {}) {throw new Error("A runtime export target requires the runtime profile");if (options.compression !== undefined && options.target !== "three")throw new Error("Runtime compression requires the three runtime target");+ if (options.maxLod !== undefined && options.target !== "three")+ throw new Error("Runtime maxLod requires the three runtime target");+ if (options.positionBits !== undefined && options.target !== "three")+ throw new Error("Runtime positionBits requires the three runtime target");const textures = options.textures;if (textures !== undefined && textures !== "manifest" && textures !== "external")throw new Error("Unknown runtime texture option");@@ -38921,7 +39127,9 @@ async function exportAssetGlb(record, options = {}) {if (options.target === "three") {const derived = await deriveThree(writeGlbJson(bytes, jsonEnd, json), {...options.ktx2Encoder ? { ktx2Encoder: options.ktx2Encoder } : {},- ...options.compression ? { compression: options.compression } : {}+ ...options.compression ? { compression: options.compression } : {},+ ...options.maxLod !== undefined ? { maxLod: options.maxLod } : {},+ ...options.positionBits !== undefined ? { positionBits: options.positionBits } : {}}, textures === "external" ? { gltfBasename: gltfName.slice(0, -".gltf".length) } : {});metadata.target = "three";metadata.delivery = derived.delivery;@@ -38982,7 +39190,7 @@ async function externalLayout(gltf, manifest) {const entry = manifest[index];const written = typeof image.uri === "string" ? image.uri : "";const bytes = resources.get(written);- if (!bytes || `sha256:${await sha256Hex3(bytes)}` !== entry.sha256)+ if (!bytes || `sha256:${await sha256Hex2(bytes)}` !== entry.sha256)throw new Error("External texture bytes differ from the delivered GLB");resources.delete(written);const uri = `textures/${entry.sha256.slice("sha256:".length)}.${textureFileExtension(entry.mimeType)}`;@@ -40079,7 +40287,7 @@ __export(exports_draw_diagnostics, {inspectDrawDiagnostics: () => inspectDrawDiagnostics});import { Primitive as Primitive3 } from "@gltf-transform/core";-import { cloneDocument } from "@gltf-transform/functions";+import { cloneDocument as cloneDocument2 } from "@gltf-transform/functions";import * as THREE57 from "three";function withinLimits(doc) {const root = doc.getRoot();@@ -40235,7 +40443,7 @@ function analyzeDrawDiagnostics(doc, options = {}) {return skipped("input-limit");const keep = options.keep ?? [];const before = collect2(doc, keep);- const copy = cloneDocument(doc);+ const copy = cloneDocument2(doc);const merge = mergeRigidGroups(copy, { keep });const after = collect2(copy, keep);const all = [...before.anchors.values()].map((anchor) => ({diff --git a/dist/build.json b/dist/build.jsonindex 2d222ed1..14336e41 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:b50cf2013753343e8998fcfedc36b915fa7f98d24d559899859568661750d8ec",+ "identity": "sha256:87c7fb34b7cc2b739a5d619f14ad030c0b4da46d01c37c830b1d3369311b9cf1","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "ad7089d583651cdbde8b79a2b80cd3105cfbfcd9d689c3141da9e00253cc5b5b",+ "sourceHash": "acbeee50ed8f5686ce03b9d87173147b4b20c2f32004c0cc11cfcb33019c931c","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -37,13 +37,13 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:376245021b450ae807e0aa0ae3148aef4896e8c036c03150084c2a212e9863ed"+ "bundleHash": "sha256:f5220ec2fccfca9b9586135a8f7b07cd5d1bab9fed038d1d179e2846f3d4c525"},"agent-run": {- "identity": "sha256:b50cf2013753343e8998fcfedc36b915fa7f98d24d559899859568661750d8ec",+ "identity": "sha256:87c7fb34b7cc2b739a5d619f14ad030c0b4da46d01c37c830b1d3369311b9cf1","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "ad7089d583651cdbde8b79a2b80cd3105cfbfcd9d689c3141da9e00253cc5b5b",+ "sourceHash": "acbeee50ed8f5686ce03b9d87173147b4b20c2f32004c0cc11cfcb33019c931c","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -75,13 +75,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:252172855a5c20ce2a62555a88db26911ff15de7be430e3652dfa5c5d780b7a8"+ "bundleHash": "sha256:e2e64cd8b82bc63be80be969710138b29f8d32e9b2bda9819dd25d2c57500a8f"},"agent-providers": {- "identity": "sha256:b50cf2013753343e8998fcfedc36b915fa7f98d24d559899859568661750d8ec",+ "identity": "sha256:87c7fb34b7cc2b739a5d619f14ad030c0b4da46d01c37c830b1d3369311b9cf1","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "ad7089d583651cdbde8b79a2b80cd3105cfbfcd9d689c3141da9e00253cc5b5b",+ "sourceHash": "acbeee50ed8f5686ce03b9d87173147b4b20c2f32004c0cc11cfcb33019c931c","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -116,10 +116,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:b50cf2013753343e8998fcfedc36b915fa7f98d24d559899859568661750d8ec",+ "identity": "sha256:87c7fb34b7cc2b739a5d619f14ad030c0b4da46d01c37c830b1d3369311b9cf1","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "ad7089d583651cdbde8b79a2b80cd3105cfbfcd9d689c3141da9e00253cc5b5b",+ "sourceHash": "acbeee50ed8f5686ce03b9d87173147b4b20c2f32004c0cc11cfcb33019c931c","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -154,10 +154,10 @@"bundleHash": "sha256:8c2fcbae79116bb20b75e98313f9c5044835b4f8d28def79c8333944748202a9"},"cli": {- "identity": "sha256:b50cf2013753343e8998fcfedc36b915fa7f98d24d559899859568661750d8ec",+ "identity": "sha256:87c7fb34b7cc2b739a5d619f14ad030c0b4da46d01c37c830b1d3369311b9cf1","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "ad7089d583651cdbde8b79a2b80cd3105cfbfcd9d689c3141da9e00253cc5b5b",+ "sourceHash": "acbeee50ed8f5686ce03b9d87173147b4b20c2f32004c0cc11cfcb33019c931c","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -189,13 +189,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:e133b28c7bd660ce1693471fea51606c6f0c22134d88b4c1ecf75bd79b685cef"+ "bundleHash": "sha256:c45bf9b9a3542e509aba243ac6ddf61064d8f56b13ac849e4b5333ff456d3491"},"engine": {- "identity": "sha256:b50cf2013753343e8998fcfedc36b915fa7f98d24d559899859568661750d8ec",+ "identity": "sha256:87c7fb34b7cc2b739a5d619f14ad030c0b4da46d01c37c830b1d3369311b9cf1","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "ad7089d583651cdbde8b79a2b80cd3105cfbfcd9d689c3141da9e00253cc5b5b",+ "sourceHash": "acbeee50ed8f5686ce03b9d87173147b4b20c2f32004c0cc11cfcb33019c931c","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -227,7 +227,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:ee67f1995cd78c9f7c3611cbdde526a277c0adb97053dfd143ff3af476569327"+ "bundleHash": "sha256:55c6a263727bb3646f4062586ef8f8715be49067b9139a80275cafedf009f476"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex d210d47b..a101326a 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -14274,6 +14274,9 @@ var init_gltf_io = __esm(() => {listLevels() {return this.listRefs("levels");}+ removeLevel(level) {+ return this.removeRef("levels", level);+ }};MSFTLod = class MSFTLod extends Extension {extensionName = MSFT_LOD;@@ -22449,6 +22452,56 @@ function summarizeLodChains(doc) {};});}+function trimLodChains(doc, maxLod) {+ const chains = listLodChainNodes(doc);+ const doomed = new Set;+ for (const { levels } of chains)+ for (const level of levels.slice(maxLod + 1))+ level.traverse((node) => {+ doomed.add(node);+ });+ for (const animation of doc.getRoot().listAnimations())+ for (const channel of animation.listChannels()) {+ const target = channel.getTargetNode();+ if (target && doomed.has(target))+ throw new Error(`maxLod ${maxLod} would drop ${target.getName() || "a node"}, which animation ${JSON.stringify(animation.getName())} targets; keep that level.`);+ }+ const trimmed = chains.map(({ levels, paths }) => {+ const [base, ...lower] = levels;+ const dropped = lower.slice(maxLod);+ if (dropped.length > 0) {+ const lod = base.getExtension(MSFT_LOD);+ for (const level of dropped)+ lod.removeLevel(level);+ const extras = { ...base.getExtras() };+ const coverage = screenCoverageOf(base);+ if (maxLod === 0) {+ base.setExtension(MSFT_LOD, null);+ lod.dispose();+ delete extras[MSFT_SCREENCOVERAGE];+ } else if (coverage)+ extras[MSFT_SCREENCOVERAGE] = coverage.slice(0, maxLod + 1);+ base.setExtras(extras);+ for (const level of dropped) {+ const subtree = [];+ level.traverse((node) => {+ subtree.push(node);+ });+ for (const node of subtree.reverse())+ node.dispose();+ }+ }+ return {+ path: paths[0],+ levels: levels.length - dropped.length,+ dropped: dropped.map((level) => level.getName())+ };+ });+ const root = doc.getRoot();+ if (!root.listNodes().some((node) => node.getExtension(MSFT_LOD)))+ root.listExtensionsUsed().find((extension) => extension.extensionName === MSFT_LOD)?.dispose();+ return trimmed;+}var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;var init_lod_export = __esm(() => {init_semantic();@@ -24946,6 +24999,7 @@ function readBudgetDeclaration(value) {}}function evaluateBudget(declaration, measuredLod0, chains) {+ const instanced = measuredLod0.instancedDraws === undefined ? {} : { instancedDraws: measuredLod0.instancedDraws };const outside = measuredLod0.triangles - chains.reduce((sum, chain) => sum + chain.levels[0].triangles, 0);const tierTriangles = (level) => outside + chains.reduce((sum, chain) => sum + chain.levels[Math.min(level, chain.levels.length - 1)].triangles, 0);const tiers = Object.entries(declaration.triangles).map(([tier, limit]) => {@@ -24961,7 +25015,7 @@ function evaluateBudget(declaration, measuredLod0, chains) {},measured: {triangles,- ...drawsDeclared === undefined ? {} : { draws: measuredLod0.draws }+ ...drawsDeclared === undefined ? {} : { draws: measuredLod0.draws, ...instanced }},status: pass ? "pass" : "fail"};@@ -24970,7 +25024,7 @@ function evaluateBudget(declaration, measuredLod0, chains) {tiers.unshift({tier: "LOD0",declared: { draws: declaration.draws },- measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws },+ measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws, ...instanced },status: measuredLod0.draws <= declaration.draws ? "pass" : "fail"});return { status: tiers.every((tier) => tier.status === "pass") ? "pass" : "fail", tiers };@@ -33143,6 +33197,652 @@ var init_texture_bake = __esm(() => {];});+// src/runtime-textures.ts+async function sha256Hex2(bytes) {+ const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");+}+function imageDimensions(bytes) {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const fail = () => {+ throw new Error("Texture manifest cannot read image dimensions");+ };+ const at = (offset, length) => {+ if (offset + length > bytes.byteLength)+ fail();+ };+ if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {+ at(16, 8);+ return { width: view.getUint32(16), height: view.getUint32(20) };+ }+ if (isKtx2(bytes)) {+ at(20, 8);+ return { width: view.getUint32(20, true), height: view.getUint32(24, true) };+ }+ if (bytes[0] === 255 && bytes[1] === 216) {+ let offset = 2;+ while (offset + 4 <= bytes.byteLength) {+ if (bytes[offset] !== 255)+ fail();+ const marker = bytes[offset + 1];+ if (marker === 255) {+ offset++;+ continue;+ }+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {+ offset += 2;+ continue;+ }+ const length = view.getUint16(offset + 2);+ if (marker >= 192 && marker <= 207 && ![196, 200, 204].includes(marker)) {+ at(offset + 5, 4);+ return { width: view.getUint16(offset + 7), height: view.getUint16(offset + 5) };+ }+ offset += 2 + length;+ }+ fail();+ }+ const text = (offset) => String.fromCharCode(...bytes.subarray(offset, Math.min(offset + 4, bytes.byteLength)));+ if (text(0) === "RIFF" && text(8) === "WEBP") {+ at(12, 19);+ const chunk = text(12);+ if (chunk === "VP8X")+ return {+ width: 1 + (view.getUint32(24, true) & 16777215),+ height: 1 + (view.getUint32(27, true) & 16777215)+ };+ if (chunk === "VP8L") {+ const bits = view.getUint32(21, true);+ return { width: 1 + (bits & 16383), height: 1 + (bits >> 14 & 16383) };+ }+ if (chunk === "VP8 ") {+ at(26, 4);+ return {+ width: view.getUint16(26, true) & 16383,+ height: view.getUint16(28, true) & 16383+ };+ }+ }+ return fail();+}+function textureSource(texture) {+ if (!object2(texture))+ return;+ const extensions = object2(texture.extensions) ? texture.extensions : {};+ for (const name of ["KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif"]) {+ const extension = extensions[name];+ if (object2(extension) && index(extension.source) !== undefined)+ return index(extension.source);+ }+ return index(texture.source);+}+function srgbImages(json) {+ const textures = Array.isArray(json.textures) ? json.textures : [];+ const result = new Set;+ for (const material of Array.isArray(json.materials) ? json.materials : []) {+ if (!object2(material))+ continue;+ const pbr = object2(material.pbrMetallicRoughness) ? material.pbrMetallicRoughness : {};+ for (const info of [pbr.baseColorTexture, material.emissiveTexture]) {+ const texture = object2(info) ? index(info.index) : undefined;+ const image = texture === undefined ? undefined : textureSource(textures[texture]);+ if (image !== undefined)+ result.add(image);+ }+ }+ return result;+}+function base64(text) {+ const binary = atob(text);+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));+}+function embeddedImages(json, binary) {+ const views = Array.isArray(json.bufferViews) ? json.bufferViews : [];+ return (Array.isArray(json.images) ? json.images : []).map((image) => {+ if (!object2(image))+ throw new Error("Invalid glTF image");+ const view = index(image.bufferView);+ if (view !== undefined) {+ const def = views[view];+ if (!object2(def) || index(def.buffer) !== 0 || !binary)+ throw new Error("Texture manifest requires images embedded in the GLB binary chunk");+ const offset = index(def.byteOffset) ?? 0;+ const length = index(def.byteLength);+ if (length === undefined || offset + length > binary.byteLength)+ throw new Error("Invalid glTF image buffer view");+ if (typeof image.mimeType !== "string")+ throw new Error("Embedded image needs a mimeType");+ return { bytes: binary.subarray(offset, offset + length), mimeType: image.mimeType };+ }+ const match = typeof image.uri === "string" ? /^data:([^;,]+);base64,(.*)$/s.exec(image.uri) : null;+ if (!match)+ throw new Error("Texture manifest requires embedded image bytes");+ return { bytes: base64(match[2]), mimeType: match[1] };+ });+}+async function runtimeTextureManifest(json, binary, options = {}) {+ const srgb = srgbImages(json);+ const entries = [];+ for (const [image, { bytes, mimeType }] of embeddedImages(json, binary).entries()) {+ const sha256 = `sha256:${await sha256Hex2(bytes)}`;+ const sourceSha256 = options.sources?.get(image);+ const original = sourceSha256 ?? sha256;+ const map = options.maps?.find((candidate) => candidate.sha256 === original);+ entries.push({+ image,+ sha256,+ bytes: bytes.byteLength,+ mimeType,+ ...imageDimensions(bytes),+ colorSpace: srgb.has(image) ? "srgb" : "linear",+ ...sourceSha256 && sourceSha256 !== sha256 ? { sourceSha256 } : {},+ ...map ? { material: { pin: { ...map.pin }, slot: map.slot } } : {}+ });+ }+ return entries;+}+function textureFileExtension(mimeType) {+ const extension = {+ "image/png": "png",+ "image/jpeg": "jpg",+ "image/webp": "webp",+ "image/ktx2": "ktx2"+ }[mimeType];+ if (!extension)+ throw new Error(`External textures do not support ${mimeType}`);+ return extension;+}+var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), index = (value) => Number.isInteger(value) && value >= 0 ? value : undefined, KTX2_IDENTIFIER, isKtx2 = (bytes) => bytes.byteLength >= 12 && KTX2_IDENTIFIER.every((value, at) => bytes[at] === value);+var init_runtime_textures = __esm(() => {+ KTX2_IDENTIFIER = Object.freeze([+ 171,+ 75,+ 84,+ 88,+ 32,+ 50,+ 48,+ 187,+ 13,+ 10,+ 26,+ 10+ ]);+});++// src/runtime-three.ts+var exports_runtime_three = {};+__export(exports_runtime_three, {+ deliverRuntimeThreeGlb: () => deliverRuntimeThreeGlb,+ instancedDrawEstimate: () => instancedDrawEstimate+});+import {+ Accessor,+ Format,+ Logger,+ PropertyType as PropertyType5+} from "@gltf-transform/core";+import {+ EXTMeshGPUInstancing,+ EXTMeshoptCompression,+ KHRMeshQuantization,+ KHRTextureBasisu as KHRTextureBasisu2+} from "@gltf-transform/extensions";+import { cloneDocument, dedup, prune, quantize, reorder } from "@gltf-transform/functions";+import * as THREE50 from "three";+function meshSignature(mesh, ids) {+ const id = (property) => {+ if (!property)+ return -1;+ if (!ids.has(property))+ ids.set(property, ids.size);+ return ids.get(property);+ };+ return mesh.listPrimitives().map((primitive) => `${primitive.getMode()}:${id(primitive.getMaterial())}:${id(primitive.getIndices())}:${primitive.listSemantics().sort().map((semantic) => `${semantic}=${id(primitive.getAttribute(semantic))}`).join(",")}:${primitive.listTargets().length}`).join("|");+}+async function instancedDrawEstimate(doc) {+ const copy = cloneDocument(doc);+ copy.setLogger(new Logger(Logger.Verbosity.SILENT));+ await copy.transform(dedup({ propertyTypes: [PropertyType5.ACCESSOR], keepUniqueNames: true }));+ applyScopedInstancing(copy);+ return collectGlbMetrics(copy).drawCalls;+}+function applyScopedInstancing(doc) {+ const report = [];+ const ids = new Map;+ const parents = doc.getRoot().listNodes().filter((node) => node.getExtras()[KILN_REPEAT_INSTANCES_KEY] !== undefined);+ let extension;+ for (const parent of parents) {+ const groups = new Map;+ for (const child of parent.listChildren()) {+ const mesh = child.getMesh();+ if (!mesh || child.listChildren().length || child.getSkin() || child.listExtensions().length || isHiddenGltfNode(child) || rolesOf4(child).length || Object.keys(child.getExtras()).length || child.getWeights().length)+ continue;+ const signature = meshSignature(mesh, ids);+ groups.set(signature, [...groups.get(signature) ?? [], child]);+ }+ let batchIndex = 0;+ for (const nodes of groups.values()) {+ if (nodes.length < 2)+ continue;+ const mesh = nodes[0].getMesh();+ extension ??= doc.createExtension(EXTMeshGPUInstancing).setRequired(true);+ const buffer = doc.getRoot().listBuffers()[0];+ const accessor = (type, values) => doc.createAccessor().setType(type).setArray(new Float32Array(values)).setBuffer(buffer ?? null);+ const t = [], r = [], s = [];+ for (const node of nodes) {+ t.push(...node.getTranslation());+ r.push(...node.getRotation());+ s.push(...node.getScale());+ }+ const batch = extension.createInstancedMesh().setAttribute("TRANSLATION", accessor("VEC3", t)).setAttribute("ROTATION", accessor("VEC4", r)).setAttribute("SCALE", accessor("VEC3", s));+ const name = `${parent.getName() || "Node"}_Instances${batchIndex ? `_${batchIndex}` : ""}`;+ batchIndex++;+ const batchNode = doc.createNode(name).setMesh(mesh).setExtension("EXT_mesh_gpu_instancing", batch);+ parent.addChild(batchNode);+ report.push({+ node: batchNode,+ mesh: mesh.getName(),+ count: nodes.length,+ instances: nodes.map((node) => node.getName())+ });+ for (const node of nodes) {+ const own = node.getMesh();+ node.dispose();+ if (own && own !== mesh && !own.listParents().some((p) => p.propertyType === PropertyType5.NODE))+ own.dispose();+ }+ }+ const extras = { ...parent.getExtras() };+ delete extras[KILN_REPEAT_INSTANCES_KEY];+ parent.setExtras(extras);+ }+ return report;+}+function splitColliderProxies(doc) {+ const report = [];+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh || !isCollider(node))+ continue;+ const proxy = doc.createNode(`${node.getName()}_Proxy`).setMesh(mesh);+ node.setMesh(null).addChild(proxy);+ report.push({ collider: node, proxy });+ }+ return report;+}+async function encodeKtx2(doc, encoder, sources) {+ const textures = doc.getRoot().listTextures().filter((texture) => texture.getMimeType() !== "image/ktx2" && texture.getImage());+ if (!encoder)+ return {+ status: "skipped",+ textures: textures.length,+ reason: "No KTX2 encoder was supplied; textures stay PNG or JPEG."+ };+ const slots = new Map;+ const use = (texture, slot) => {+ if (texture)+ slots.set(texture, (slots.get(texture) ?? new Set).add(slot));+ };+ for (const material of doc.getRoot().listMaterials()) {+ use(material.getBaseColorTexture(), "baseColor");+ use(material.getEmissiveTexture(), "emissive");+ use(material.getNormalTexture(), "normal");+ use(material.getMetallicRoughnessTexture(), "metallicRoughness");+ use(material.getOcclusionTexture(), "occlusion");+ }+ const order = [+ "baseColor",+ "emissive",+ "normal",+ "metallicRoughness",+ "occlusion"+ ];+ for (const texture of textures) {+ const used = slots.get(texture) ?? new Set;+ const srgb = used.has("baseColor") || used.has("emissive");+ const other = texture.listParents().some((parent) => parent.propertyType !== PropertyType5.ROOT && !isCoreMaterialUse(parent));+ const linear = [...used].some((slot) => slot !== "baseColor" && slot !== "emissive") || other;+ if (srgb && linear)+ throw new Error(`Texture ${JSON.stringify(texture.getName())} is used by both sRGB and linear material slots; one KTX2 encoding cannot serve both. Use separate images.`);+ const original = texture.getImage();+ const image = await encoder({+ image: original,+ mimeType: texture.getMimeType(),+ name: texture.getName(),+ colorSpace: srgb ? "srgb" : "linear",+ slot: order.find((slot) => used.has(slot)) ?? "other"+ });+ if (!(image instanceof Uint8Array) || !isKtx2(image))+ throw new Error("ktx2Encoder must return KTX2 bytes starting with the KTX2 identifier");+ sources.set(texture, `sha256:${await sha256Hex2(original)}`);+ texture.setImage(image).setMimeType("image/ktx2");+ const uri = texture.getURI();+ if (uri)+ texture.setURI(uri.replace(/\.(png|jpe?g)$/i, ".ktx2"));+ }+ if (textures.length) {+ doc.createExtension(KHRTextureBasisu2).setRequired(true);+ await Promise.resolve().then(() => init_atlas_provenance());+ await refreshAtlasDocumentProvenance(doc);+ await validateAtlasDocumentProvenance(doc);+ }+ return {+ status: "encoded",+ textures: textures.length,+ ...encoder.identity ? { encoder: structuredClone(encoder.identity) } : {}+ };+}+function isCoreMaterialUse(parent) {+ return parent.propertyType === PropertyType5.MATERIAL;+}+function decomposeDelta(before, after) {+ const delta = new THREE50.Matrix4().fromArray(before).invert().multiply(new THREE50.Matrix4().fromArray(after));+ const position = new THREE50.Vector3, quaternion = new THREE50.Quaternion, scale = new THREE50.Vector3;+ delta.decompose(position, quaternion, scale);+ return {+ scale: scale.x,+ offset: [position.x, position.y, position.z]+ };+}+function hasQuantizedVertexData(doc) {+ const quantized = (semantic, accessor) => {+ if (accessor.getComponentSize() >= 4)+ return false;+ if (semantic === "POSITION" || semantic === "NORMAL" || semantic === "TANGENT")+ return true;+ if (!semantic.startsWith("TEXCOORD_"))+ return false;+ const type = accessor.getComponentType();+ return !(accessor.getNormalized() && (type === Accessor.ComponentType.UNSIGNED_BYTE || type === Accessor.ComponentType.UNSIGNED_SHORT));+ };+ return doc.getRoot().listMeshes().flatMap((mesh) => mesh.listPrimitives()).flatMap((primitive) => [primitive, ...primitive.listTargets()]).some((target) => target.listSemantics().some((semantic) => quantized(semantic, target.getAttribute(semantic))));+}+function positionGridSteps(doc, bits) {+ const levels = 2 ** (bits - 1) - 1;+ const lodBase = new Map;+ for (const node of doc.getRoot().listNodes())+ for (const level of node.getExtension(MSFT_LOD)?.listLevels() ?? [])+ if (level.propertyType === PropertyType5.NODE)+ lodBase.set(level, node);+ const world = (node) => {+ const matrix = new THREE50.Matrix4().fromArray(node.getWorldMatrix());+ let top = node;+ while (top.getParentNode())+ top = top.getParentNode();+ const placed = lodBase.get(top)?.getParentNode();+ return placed ? new THREE50.Matrix4().fromArray(placed.getWorldMatrix()).multiply(matrix) : matrix;+ };+ const halfExtent = (mesh) => {+ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];+ const widen = (values, doubleFromZero) => {+ for (let axis = 0;axis < 3; axis++) {+ const value = values[axis];+ const candidates = doubleFromZero ? [value, value * 2, 0] : [value];+ min[axis] = Math.min(min[axis], ...candidates);+ max[axis] = Math.max(max[axis], ...candidates);+ }+ };+ for (const primitive of mesh.listPrimitives()) {+ const position = primitive.getAttribute("POSITION");+ if (position) {+ widen(position.getMin([]), false);+ widen(position.getMax([]), false);+ }+ for (const target of primitive.listTargets()) {+ const delta = target.getAttribute("POSITION");+ if (delta) {+ widen(delta.getMin([]), true);+ widen(delta.getMax([]), true);+ }+ }+ }+ return Math.max(...[0, 1, 2].map((axis) => (max[axis] - min[axis]) / 2));+ };+ const instanceScale = (node) => {+ const scale = node.getExtension("EXT_mesh_gpu_instancing")?.getAttribute("SCALE");+ if (!scale)+ return 1;+ let largest = 0;+ for (let i = 0;i < scale.getCount(); i++)+ largest = Math.max(largest, ...scale.getElement(i, []).map(Math.abs));+ return largest;+ };+ const steps = [];+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh?.listPrimitives().some((primitive) => primitive.getAttribute("POSITION")))+ continue;+ const scale = node.getSkin() ? 1 : world(node).getMaxScaleOnAxis() * instanceScale(node);+ steps.push({ node, mesh: mesh.getName(), step: halfExtent(mesh) * scale / levels });+ }+ return steps;+}+async function trimLevels(doc, maxLod) {+ const chains = trimLodChains(doc, maxLod);+ const budgetTiersOmitted = [];+ if (chains.some((chain) => chain.dropped.length > 0)) {+ await doc.transform(prune({+ propertyTypes: [+ PropertyType5.MESH,+ PropertyType5.PRIMITIVE,+ PropertyType5.PRIMITIVE_TARGET,+ PropertyType5.ACCESSOR,+ PropertyType5.MATERIAL,+ PropertyType5.TEXTURE+ ],+ keepAttributes: true,+ keepIndices: true,+ keepLeaves: true,+ keepExtras: true,+ keepSolidTextures: true+ }));+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ const extras = { ...scene?.getExtras() ?? {} };+ const budget = extras[KILN_BUDGET_KEY];+ if (scene && budget?.triangles) {+ const triangles = { ...budget.triangles };+ for (const tier of Object.keys(triangles))+ if (Number(tier.slice(3)) > maxLod) {+ budgetTiersOmitted.push(tier);+ delete triangles[tier];+ }+ if (Object.keys(triangles).length > 0)+ extras[KILN_BUDGET_KEY] = { ...budget, triangles };+ else+ delete extras[KILN_BUDGET_KEY];+ scene.setExtras(extras);+ }+ }+ return { maxLod, chains, budgetTiersOmitted };+}+async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layout = {}) {+ const compression = options.compression ?? "meshopt";+ if (compression !== "meshopt" && compression !== "none")+ throw new Error("Runtime three compression must be meshopt or none");+ const { maxLod } = options;+ if (maxLod !== undefined && !(Number.isSafeInteger(maxLod) && maxLod >= 0))+ throw new Error("Runtime three maxLod must be a non-negative integer");+ const positionBits = options.positionBits ?? RUNTIME_THREE_QUANTIZATION.position;+ if (positionBits !== "float" && !(Number.isSafeInteger(positionBits) && positionBits >= 8 && positionBits <= 16))+ throw new Error("Runtime three positionBits must be an integer from 8 to 16, or float");+ const io = createGltfIO().registerDependencies({+ "meshopt.encoder": meshoptEncoder+ });+ const doc = await io.readBinary(bytes);+ doc.setLogger(new Logger(Logger.Verbosity.SILENT));+ const lod = maxLod === undefined ? undefined : await trimLevels(doc, maxLod);+ await doc.transform(dedup({ propertyTypes: [PropertyType5.ACCESSOR], keepUniqueNames: true }));+ const instanced = applyScopedInstancing(doc);+ const proxies = splitColliderProxies(doc);+ const matrices = new Map;+ for (const node of doc.getRoot().listNodes())+ if (node.getMesh())+ matrices.set(node, [...node.getMatrix()]);+ const steps = positionBits === "float" ? [] : positionGridSteps(doc, positionBits);+ const semantics = positionBits === "float" ? QUANTIZED_SEMANTICS_EXCEPT_POSITION : QUANTIZED_SEMANTICS;+ await doc.transform(reorder({ encoder: meshoptEncoder, target: "size" }), quantize({+ pattern: semantics,+ patternTargets: semantics,+ quantizationVolume: "mesh",+ quantizePosition: positionBits === "float" ? RUNTIME_THREE_QUANTIZATION.position : positionBits,+ quantizeNormal: RUNTIME_THREE_QUANTIZATION.normal,+ quantizeTexcoord: RUNTIME_THREE_QUANTIZATION.texcoord,+ quantizeColor: RUNTIME_THREE_QUANTIZATION.color,+ quantizeWeight: RUNTIME_THREE_QUANTIZATION.weight+ }));+ if (positionBits === "float" && hasQuantizedVertexData(doc))+ doc.createExtension(KHRMeshQuantization).setRequired(true);+ if (compression === "meshopt")+ doc.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE });+ const encodedSources = new Map;+ const ktx2 = await encodeKtx2(doc, options.ktx2Encoder, encodedSources);+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh || matrices.has(node) || node.getName())+ continue;+ const parent = node.getParentNode();+ node.setName(`${parent?.getName() || "Node"}_Mesh`);+ }+ const after = deliveryNodePaths(doc);+ const pathOf = (node) => after.get(node) ?? `#${encodeURIComponent(node.getName())}`;+ const proxyNodes = new Set(proxies.map((entry) => entry.proxy));+ const nodeScale = [];+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh || node.getExtension("EXT_mesh_gpu_instancing"))+ continue;+ const path = after.get(node);+ if (path === undefined)+ continue;+ const original = matrices.get(node);+ const moved = original === undefined;+ const split = moved || proxyNodes.has(node);+ const reference = moved ? new THREE50.Matrix4().identity().toArray() : original;+ const current = [...node.getMatrix()];+ const { scale, offset } = decomposeDelta(reference, current);+ if (!moved && Math.abs(scale - 1) < 0.000000000001 && offset.every((v) => v === 0))+ continue;+ const parent = node.getParentNode();+ nodeScale.push({+ node: path,+ mesh: mesh.getName(),+ meshMovedToChild: split,+ ...split && parent ? { authoredNode: pathOf(parent) } : {},+ dequantization: { scale, offset },+ localScale: [...node.getScale()]+ });+ }+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh || after.has(node) || !matrices.has(node))+ continue;+ const { scale, offset } = decomposeDelta(matrices.get(node), [...node.getMatrix()]);+ nodeScale.push({+ node: `#lod/${encodeURIComponent(node.getName())}`,+ mesh: mesh.getName(),+ meshMovedToChild: false,+ dequantization: { scale, offset },+ localScale: [...node.getScale()]+ });+ }+ const customAttributes = new Map;+ for (const mesh of doc.getRoot().listMeshes())+ for (const primitive of mesh.listPrimitives())+ for (const semantic of primitive.listSemantics())+ if (semantic.startsWith("_"))+ customAttributes.set(semantic, (customAttributes.get(semantic) ?? new Set).add(mesh));+ const all = doc.getRoot().listNodes();+ const glb = await io.writeBinary(doc);+ const json = (await io.binaryToJSON(glb)).json;+ const imageSources = new Map;+ doc.getRoot().listTextures().forEach((texture, image) => {+ const source = encodedSources.get(texture);+ if (source)+ imageSources.set(image, source);+ });+ const gltf = layout.gltfBasename ? await io.writeJSON(doc, { format: Format.GLTF, basename: layout.gltfBasename }) : undefined;+ const delivery = {+ target: "three",+ extensionsUsed: [...json.extensionsUsed ?? []].sort(),+ extensionsRequired: [...json.extensionsRequired ?? []].sort(),+ compression: compression === "meshopt" ? { extension: "EXT_meshopt_compression", method: "quantize" } : { extension: "none" },+ quantization: {+ extension: "KHR_mesh_quantization",+ volume: "mesh",+ bits: {+ position: positionBits === "float" ? "float32" : positionBits,+ normal: RUNTIME_THREE_QUANTIZATION.normal,+ texcoord: RUNTIME_THREE_QUANTIZATION.texcoord,+ color: RUNTIME_THREE_QUANTIZATION.color,+ weight: RUNTIME_THREE_QUANTIZATION.weight+ },+ customAttributes: "float32",+ positionSteps: steps.map(({ node, mesh, step }) => ({+ node: after.get(node) ?? `#lod/${encodeURIComponent(node.getName())}`,+ mesh,+ step+ })),+ maxPositionStep: Math.max(0, ...steps.map(({ step }) => step))+ },+ nodeScale,+ colliderProxies: proxies.map(({ collider, proxy }) => ({+ collider: pathOf(collider),+ proxy: pathOf(proxy)+ })),+ customAttributes: [...customAttributes].sort(([a], [b]) => customRank(a) - customRank(b) || (a < b ? -1 : a > b ? 1 : 0)).map(([name, meshes]) => ({+ name,+ meshes: meshes.size,+ componentType: "FLOAT",+ normalized: false+ })),+ instancing: instanced.map(({ node, ...rest }) => ({ node: pathOf(node), ...rest })),+ ktx2,+ ...lod ? { lod } : {},+ preserved: {+ lodChains: all.filter((node) => node.getExtension(MSFT_LOD)).length,+ hiddenNodes: all.filter((node) => isHiddenGltfNode(node)).length,+ colliders: all.filter(isCollider).length,+ anchors: all.filter((node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.anchor}.`))).length,+ ports: all.filter((node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.kitPort}.`))).length,+ kitModules: all.filter((node) => rolesOf4(node).includes(KILN_SEMANTIC_ROLES.kitModule)).length+ }+ };+ return {+ glb,+ delivery,+ imageSources,+ ...gltf ? {+ gltf: {+ json: gltf.json,+ resources: gltf.resources+ }+ } : {}+ };+}+var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, QUANTIZED_SEMANTICS_EXCEPT_POSITION, customRank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2, rolesOf4 = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));+var init_runtime_three = __esm(() => {+ init_semantic();+ init_gltf_io();+ init_delivery_inspect();+ init_delivery();+ init_metrics();+ init_runtime_textures();+ init_lod_export();+ init_budget();+ RUNTIME_THREE_QUANTIZATION = Object.freeze({+ volume: "mesh",+ position: 14,+ normal: 10,+ texcoord: 12,+ color: 8,+ weight: 8+ });+ QUANTIZED_SEMANTICS = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;+ QUANTIZED_SEMANTICS_EXCEPT_POSITION = /^(NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;+});+// src/exporter-node.tsvar exports_exporter_node = {};__export(exports_exporter_node, {@@ -33215,7 +33915,7 @@ var init_exporter_node = __esm(() => {});// src/views/character.ts-import * as THREE50 from "three";+import * as THREE51 from "three";function rounded(value) {const result = Math.round(value * 1e9) / 1e9;return Object.is(result, -0) ? 0 : result;@@ -33257,9 +33957,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {const invalidPaths = new Set(invalidFindingNodePaths);const joints = evidence.map((joint) => {const relative = rootInverse.clone().multiply(joint.node.matrixWorld);- const position = new THREE50.Vector3().setFromMatrixPosition(relative);- const forward = new THREE50.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);- const bend = new THREE50.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const position = new THREE51.Vector3().setFromMatrixPosition(relative);+ const forward = new THREE51.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE51.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -34671,7 +35371,7 @@ function prepareTriangleCoverage(ax, ay, bx, by, cx, cy, size) {}// src/views/raster.ts-import { Vector3 as Vector337 } from "three";+import { Vector3 as Vector338 } from "three";function orbitDir(azimuthDeg, elevationDeg) {const el = Math.min(MAX_ELEVATION_DEG, Math.max(MIN_ELEVATION_DEG, elevationDeg)) * Math.PI / 180;const az = azimuthDeg * Math.PI / 180;@@ -34706,7 +35406,7 @@ function updateSurfaceMatrices(root) {function surfaceVertexReader(mesh, position) {for (const bone of mesh.skeleton?.bones ?? [])bone.updateWorldMatrix?.(true, false);- const vertex = new Vector337;+ const vertex = new Vector338;if (mesh.getVertexPosition)return (index) => mesh.getVertexPosition(index, vertex);if (position.getX && position.getY && position.getZ)@@ -35116,7 +35816,7 @@ function cloneReviewScene(root, options = {}) {var init_scene_copy = () => {};// src/views/camera.ts-import { Vector3 as Vector338, Matrix4 as Matrix416, Euler as Euler5, Group as Group4 } from "three";+import { Vector3 as Vector339, Matrix4 as Matrix417, Euler as Euler5, Group as Group4 } from "three";function strict(value, keys, label) {for (const key of Object.keys(value))if (!keys.includes(key)) {@@ -35210,14 +35910,14 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {const z = vec(dir).normalize();if (!z.length())throw new Error("camera direction must be non-zero");- const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector338(0, 0, -1) : new Vector338(0, 1, 0);+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector339(0, 0, -1) : new Vector339(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 = z.clone().cross(x);let extent = 0.000001;for (let i = 0;i < 8; i++) {- const p = new Vector338((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);+ const p = new Vector339((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);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]));@@ -35298,7 +35998,7 @@ function resolveAssetCamera(root, shot = {}) {if (relative !== "world") {const node = relative === "part" ? selected.node : rootNode;dir.transformDirection(node.matrixWorld);- up = tuple6(new Vector338(0, 1, 0).transformDirection(node.matrixWorld));+ up = tuple6(new Vector339(0, 1, 0).transformDirection(node.matrixWorld));}camera = cameraFromBounds(bounds, tuple6(dir), request.padding ?? 1.2, up, measureBounds(root));} else if (request.type === "explicit") {@@ -35333,7 +36033,7 @@ function resolveAssetCamera(root, shot = {}) {throw new Error("padding requires bounds framing");if (request.framing === "bounds" && request.halfHeight !== undefined)throw new Error("bounds framing derives halfHeight");- let matrix = new Matrix416;+ let matrix = new Matrix417;if (relative === "asset" || relative === "part")matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;if (request.frame) {@@ -35345,7 +36045,7 @@ function resolveAssetCamera(root, shot = {}) {const position = vec(triple2(request.position, "position")).applyMatrix4(matrix);const target = request.target ? vec(triple2(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);const up = vec(triple2(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);- const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector338().setFromMatrixPosition(matrix));+ const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector339().setFromMatrixPosition(matrix));const radius = vec(bounds.max).sub(vec(bounds.min)).length();camera = {version: "kiln.camera.v1",@@ -35474,11 +36174,11 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return result;};- const key = new Vector338(1.5, 2, 1).normalize();+ const key = new Vector339(1.5, 2, 1).normalize();const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;const ordered = compositingOrder(collectTriangles(root).tris, (px, py, pz) => camera.projection === "perspective" ? Math.hypot(px - position.x, py - position.y, pz - position.z) : (position.x - px) * z.x + (position.y - py) * z.y + (position.z - pz) * z.z);for (const tri of ordered) {- const world = [0, 1, 2].map((i) => new Vector338(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));+ const world = [0, 1, 2].map((i) => new Vector339(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().multiplyScalar(tri.windingParity);const normalSign = visibleNormalSign(normal.dot(camera.projection === "perspective" ? position.clone().sub(world[0]) : z), tri.side, backfaceCull);if (normalSign === 0)@@ -35489,7 +36189,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)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 Vector338(d.dot(x), d.dot(y), -d.dot(z));+ return new Vector339(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++) {@@ -35521,7 +36221,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return out;}-var vec = (a) => new Vector338(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;+var vec = (a) => new Vector339(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;var init_camera = __esm(() => {init_raster();init_background();@@ -36277,7 +36977,7 @@ import {BufferAttribute as BufferAttribute12,BufferGeometry as BufferGeometry15,Group as Group5,- Matrix4 as Matrix417,+ Matrix4 as Matrix418,Mesh as Mesh14,Bone as Bone2,SkinnedMesh as SkinnedMesh2,@@ -36291,8 +36991,8 @@ import {NumberKeyframeTrack,PropertyBinding as PropertyBinding3,VectorKeyframeTrack as VectorKeyframeTrack2,- Quaternion as Quaternion19,- Vector3 as Vector339,+ Quaternion as Quaternion20,+ Vector3 as Vector340,InterpolateDiscrete as InterpolateDiscrete2,InterpolateLinear as InterpolateLinear2} from "three";@@ -36453,7 +37153,7 @@ function noteMaterialTextures(material, reasons) {}}function instanceMatrices(node) {- const world = new Matrix417().fromArray(node.getWorldMatrix());+ const world = new Matrix418().fromArray(node.getWorldMatrix());const extension = node.getExtension("EXT_mesh_gpu_instancing");if (!extension)return { matrices: [world], count: 1 };@@ -36476,7 +37176,7 @@ function instanceMatrices(node) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);scales?.getElement(index, scale);- const local = new Matrix417().compose(new Vector339(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion19(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector339(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));+ const local = new Matrix418().compose(new Vector340(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion20(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector340(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));matrices.push(world.clone().multiply(local));}return { matrices, count };@@ -36564,7 +37264,7 @@ async function loadGlbGeometryFlatScene(bytes) {function localInstanceMatrices(node) {const extension = node.getExtension("EXT_mesh_gpu_instancing");if (!extension)- return [new Matrix417];+ return [new Matrix418];const attributes = extension.listAttributes();if (attributes.length === 0) {throw new GlbGeometryFlatError("GLB_FLAT_INVALID_INSTANCING", "Invalid empty instancing data.");@@ -36583,7 +37283,7 @@ function localInstanceMatrices(node) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);scales?.getElement(index, scale);- return new Matrix417().compose(new Vector339(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion19(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector339(...scales ? scale.slice(0, 3) : [1, 1, 1]));+ return new Matrix418().compose(new Vector340(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion20(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector340(...scales ? scale.slice(0, 3) : [1, 1, 1]));});}async function loadGlbReviewScene(bytes) {@@ -36794,8 +37494,8 @@ function reviewSceneFromDocument(document) {for (let i = 0;i < indices.array.length; i++)if (indices.array[i] >= bones.length || !Number.isFinite(weights.array[i]) || weights.array[i] < 0)throw new GlbGeometryFlatError("GLB_FLAT_PARSE_FAILED", `Invalid skin joint index or weight on ${source.getName()}.`);- const matrices = bones.map((_, index) => new Matrix417().fromArray(inverse ? inverse.getElement(index, []) : new Matrix417().elements));- mesh.bind(new Skeleton3(bones, matrices), new Matrix417);+ const matrices = bones.map((_, index) => new Matrix418().fromArray(inverse ? inverse.getElement(index, []) : new Matrix418().elements));+ mesh.bind(new Skeleton3(bones, matrices), new Matrix418);}root.updateMatrixWorld(true);const nativeClips = document.getRoot().listAnimations().map((animation) => withLoopIntent(new AnimationClip4(animation.getName(), -1, animation.listChannels().flatMap((channel) => {@@ -37181,7 +37881,7 @@ var init_renderer_id = __esm(() => {});// src/views/scene-raster.ts-import * as THREE51 from "three";+import * as THREE52 from "three";var DEG2;var init_scene_raster = __esm(() => {init_evaluator();@@ -37193,18 +37893,18 @@ var init_scene_raster = __esm(() => {});// src/views/vehicle.ts-import * as THREE52 from "three";+import * as THREE53 from "three";function hasRole2(node, prefix) {return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;}function chassisBounds(root, inverse) {- const bounds = new THREE52.Box3;+ const bounds = new THREE53.Box3;let found = false;root.traverse((node) => {if (!hasRole2(node, "chassis"))return;node.traverse((part) => {- if (!(part instanceof THREE52.Mesh) || !(part.geometry instanceof THREE52.BufferGeometry))+ if (!(part instanceof THREE53.Mesh) || !(part.geometry instanceof THREE53.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -37214,7 +37914,7 @@ function chassisBounds(root, inverse) {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 THREE52.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE53.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -37282,33 +37982,33 @@ function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}function rod(name, start, end, radius, color, role) {- const from = new THREE52.Vector3(...start);- const to = new THREE52.Vector3(...end);+ const from = new THREE53.Vector3(...start);+ const to = new THREE53.Vector3(...end);const direction = to.clone().sub(from);const length = direction.length();- const geometry = length > 0.000000001 ? new THREE52.CylinderGeometry(radius, radius, length, 8) : new THREE52.SphereGeometry(radius, 8, 6);- const result = new THREE52.Mesh(geometry, new THREE52.MeshBasicMaterial({ color }));+ const geometry = length > 0.000000001 ? new THREE53.CylinderGeometry(radius, radius, length, 8) : new THREE53.SphereGeometry(radius, 8, 6);+ const result = new THREE53.Mesh(geometry, new THREE53.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);if (length > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE52.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));+ result.quaternion.setFromUnitVectors(new THREE53.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {- const overlay = new THREE52.Group;+ const overlay = new THREE53.Group;overlay.name = "VehicleDiagnosticOverlay";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 THREE52.Group;+ const arrow = new THREE53.Group;arrow.name = "Diagnostic_Forward_+X";tagDiagnostic(arrow, "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 THREE52.Mesh(new THREE52.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE52.MeshBasicMaterial({ color: 16724804 }));+ const arrowHead = new THREE53.Mesh(new THREE53.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE53.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);- arrowHead.quaternion.setFromUnitVectors(new THREE52.Vector3(0, 1, 0), new THREE52.Vector3(1, 0, 0));+ arrowHead.quaternion.setFromUnitVectors(new THREE53.Vector3(0, 1, 0), new THREE53.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);@@ -37316,18 +38016,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));}for (const wheel of descriptor.wheels) {- const ring = new THREE52.Mesh(new THREE52.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE52.MeshBasicMaterial({ color: 16763955 }));+ const ring = new THREE53.Mesh(new THREE53.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE53.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);- const axle = new THREE52.Vector3(...wheel.axle);+ const axle = new THREE53.Vector3(...wheel.axle);if (axle.lengthSq() > 0.000000000001) {- ring.quaternion.setFromUnitVectors(new THREE52.Vector3(0, 0, 1), axle.normalize());+ ring.quaternion.setFromUnitVectors(new THREE53.Vector3(0, 0, 1), axle.normalize());}tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}if (descriptor.chassisBox) {- const chassis = new THREE52.Group;+ const chassis = new THREE53.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");const { min, max } = descriptor.chassisBox;@@ -37361,7 +38061,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(chassis);}if (descriptor.supportPlaneY !== undefined) {- const plane = new THREE52.Group;+ const plane = new THREE53.Group;plane.name = "Diagnostic_SupportPlane";tagDiagnostic(plane, "diagnostic.vehicle.support-plane");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;@@ -37959,7 +38659,7 @@ var init_views = __esm(() => {});// src/views/character-capture.ts-import * as THREE53 from "three";+import * as THREE54 from "three";function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);@@ -37996,22 +38696,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {}function projector(root, cameraId, size) {root.updateMatrixWorld(true);- const bounds = new THREE53.Box3().setFromObject(root);+ const bounds = new THREE54.Box3().setFromObject(root);if (bounds.isEmpty())- bounds.set(new THREE53.Vector3(-0.5, 0, -0.5), new THREE53.Vector3(0.5, 1, 0.5));- const center = bounds.getCenter(new THREE53.Vector3);- const camera = cameraId === "front" ? new THREE53.Vector3(1, 0, 0) : new THREE53.Vector3(0, 0, 1);- const upHint = new THREE53.Vector3(0, 1, 0);- const xAxis = new THREE53.Vector3().crossVectors(upHint, camera).normalize();- const yAxis = new THREE53.Vector3().crossVectors(camera, xAxis).normalize();+ bounds.set(new THREE54.Vector3(-0.5, 0, -0.5), new THREE54.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE54.Vector3);+ const camera = cameraId === "front" ? new THREE54.Vector3(1, 0, 0) : new THREE54.Vector3(0, 0, 1);+ const upHint = new THREE54.Vector3(0, 1, 0);+ const xAxis = new THREE54.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE54.Vector3().crossVectors(camera, xAxis).normalize();let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {- const point = new THREE53.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);+ const point = new THREE54.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);extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));}const scale = size * 0.45 / extent;return (assetPoint) => {- const world = new THREE53.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ const world = new THREE54.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}@@ -38137,10 +38837,10 @@ var init_character_capture = __esm(() => {});// src/render.ts-import * as THREE54 from "three";-import { Document, Logger } from "@gltf-transform/core";+import * as THREE55 from "three";+import { Document, Logger as Logger2 } from "@gltf-transform/core";import { KHRMaterialsEmissiveStrength } from "@gltf-transform/extensions";-import { dedup, instance, palette, weld as weld2, prune, mergeDocuments } from "@gltf-transform/functions";+import { dedup as dedup2, instance, palette, weld as weld2, prune as prune2, mergeDocuments } from "@gltf-transform/functions";function applySurfaceBakeExtras(root, doc) {const baked = [];root.traverse((node) => {@@ -38180,7 +38880,7 @@ function ensureDefaultScene(doc) {root.setDefaultScene(scene);return scene;}-async function sha256Hex2(bytes) {+async function sha256Hex3(bytes) {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("");}@@ -38206,13 +38906,18 @@ async function inspectGlbIntegration(bytes, opts = {}) {const delivery = inspectDelivery(doc);const vertexAttributes = summarizeVertexAttributes(doc);const budgetDeclaration = readBudgetDeclaration(scene.getExtras()[KILN_BUDGET_KEY]);- const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, { triangles: metrics.triangles, draws: metrics.drawCalls }, levelsOfDetail) : undefined;+ const instancedDraws = budgetDeclaration?.draws === undefined ? undefined : await (await Promise.resolve().then(() => (init_runtime_three(), exports_runtime_three))).instancedDrawEstimate(doc);+ const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, {+ triangles: metrics.triangles,+ draws: metrics.drawCalls,+ ...instancedDraws === undefined ? {} : { instancedDraws }+ }, levelsOfDetail) : undefined;const paletteDeclaration = readPaletteDeclaration(scene.getExtras()[KILN_PALETTE_KEY]);const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;return {schemaVersion: "kiln.integration-manifest.v1",analyzerVersion: 1,- artifactSha256: await sha256Hex2(bytes),+ artifactSha256: await sha256Hex3(bytes),units: "m",axes: { forward: "+X", up: "+Y", right: "+Z" },bounds: {@@ -38359,7 +39064,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (stdMat.transparent) {mat.setAlphaMode("BLEND");}- if (stdMat.side === THREE54.DoubleSide) {+ if (stdMat.side === THREE55.DoubleSide) {mat.setDoubleSided(true);}if (stdMat.map) {@@ -38436,7 +39141,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (common.transparent || (common.opacity ?? 1) < 1) {mat.setAlphaMode("BLEND");}- if (threeMat.side === THREE54.DoubleSide)+ if (threeMat.side === THREE55.DoubleSide)mat.setDoubleSided(true);if (common.map && !mat.getBaseColorTexture()) {const texture = bridgeTexture(doc, common.map, textureCache);@@ -38599,7 +39304,7 @@ 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 geometry = new THREE54.PlaneGeometry(1, 1);+ const geometry = new THREE55.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}@@ -38623,9 +39328,9 @@ function animationInterpolation(track) {if (isCubicSplineTrack(track))return "CUBICSPLINE";const mode = track.getInterpolation();- if (mode === THREE54.InterpolateDiscrete)+ if (mode === THREE55.InterpolateDiscrete)return "STEP";- if (mode === THREE54.InterpolateLinear)+ if (mode === THREE55.InterpolateLinear)return "LINEAR";throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);}@@ -38790,7 +39495,7 @@ async function applyGpuInstancing(doc, mode, role) {return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };}async function consolidateMaterials(doc, mode, keep = []) {- doc.setLogger(new Logger(Logger.Verbosity.WARN));+ doc.setLogger(new Logger2(Logger2.Verbosity.WARN));const before = collectGlbMetrics(doc);const root = doc.getRoot();const steps = root.listMaterials().some((material) => Object.keys(material.getExtras()).length > 0) ? [] : [palette({ min: PALETTE_MIN })];@@ -38799,7 +39504,7 @@ async function consolidateMaterials(doc, mode, keep = []) {steps.push(rigidMerge({ keep }, (summary) => {merge = summary;}));- steps.push(weld2(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));+ steps.push(weld2(), prune2({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));await doc.transform(...steps);const after = collectGlbMetrics(doc);return {@@ -38941,7 +39646,7 @@ async function renderSceneToGLB(root, opts = {}) {const indexBuffers = applyIndexPolicy(doc, indexPolicy);if (opts.dedup !== false) {try {- await doc.transform(dedup());+ await doc.transform(dedup2());} catch (err) {warnings.push(`dedup transform failed: ${err instanceof Error ? err.message : String(err)}`);}@@ -38992,7 +39697,7 @@ async function renderSceneToGLB(root, opts = {}) {await refreshAtlasDocumentProvenance(doc);await validateAtlasDocumentProvenance(doc);const bytes = await io.writeBinary(doc);- const artifactGlbSha256 = `sha256:${await sha256Hex2(bytes)}`;+ const artifactGlbSha256 = `sha256:${await sha256Hex3(bytes)}`;const boundBakedTextures = bakedTextures.map((entry) => ({...entry,artifactGlbSha256@@ -39200,8 +39905,8 @@ function collectMeshStats(root) {if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {return;}- const center = new THREE54.Vector3;- const size = new THREE54.Vector3;+ const center = new THREE55.Vector3;+ const size = new THREE55.Vector3;box.getCenter(center);box.getSize(size);out.push({@@ -39217,7 +39922,7 @@ function collectMeshStats(root) {return out;}function minimalGapVector(a, b) {- const v = new THREE54.Vector3;+ const v = new THREE55.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])v[axis] = b.max[axis] - a.min[axis];@@ -39235,10 +39940,10 @@ function inspectSceneStructure(root, opts = {}) {return warnings;const cat = opts.category?.toLowerCase();if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {- const all = new THREE54.Box3;+ const all = new THREE55.Box3;for (const m of meshes)all.union(m.box);- const size = new THREE54.Vector3;+ const size = new THREE55.Vector3;all.getSize(size);if (cat === "aircraft") {if (size.y > size.x * 1.2) {@@ -39363,18 +40068,18 @@ var init_render = __esm(() => {engineIO = createGltfIO;ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];GLTF_MIN_FILTER = {- [THREE54.NearestFilter]: 9728,- [THREE54.LinearFilter]: 9729,- [THREE54.NearestMipmapNearestFilter]: 9984,- [THREE54.LinearMipmapNearestFilter]: 9985,- [THREE54.NearestMipmapLinearFilter]: 9986,- [THREE54.LinearMipmapLinearFilter]: 9987- };- GLTF_MAG_FILTER = { [THREE54.NearestFilter]: 9728, [THREE54.LinearFilter]: 9729 };+ [THREE55.NearestFilter]: 9728,+ [THREE55.LinearFilter]: 9729,+ [THREE55.NearestMipmapNearestFilter]: 9984,+ [THREE55.LinearMipmapNearestFilter]: 9985,+ [THREE55.NearestMipmapLinearFilter]: 9986,+ [THREE55.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE55.NearestFilter]: 9728, [THREE55.LinearFilter]: 9729 };GLTF_WRAP = {- [THREE54.ClampToEdgeWrapping]: 33071,- [THREE54.MirroredRepeatWrapping]: 33648,- [THREE54.RepeatWrapping]: 10497+ [THREE55.ClampToEdgeWrapping]: 33071,+ [THREE55.MirroredRepeatWrapping]: 33648,+ [THREE55.RepeatWrapping]: 10497};REVIEW_CLIP_LIMITS2 = {clips: 32,@@ -42443,179 +43148,6 @@ var init_assets_node = __esm(() => {windowsSharePath = /^[\\/]{2}[^\\/]+[\\/][^\\/]+/;});-// src/runtime-textures.ts-async function sha256Hex3(bytes) {- const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));- return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");-}-function imageDimensions(bytes) {- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);- const fail = () => {- throw new Error("Texture manifest cannot read image dimensions");- };- const at = (offset, length) => {- if (offset + length > bytes.byteLength)- fail();- };- if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) {- at(16, 8);- return { width: view.getUint32(16), height: view.getUint32(20) };- }- if (isKtx2(bytes)) {- at(20, 8);- return { width: view.getUint32(20, true), height: view.getUint32(24, true) };- }- if (bytes[0] === 255 && bytes[1] === 216) {- let offset = 2;- while (offset + 4 <= bytes.byteLength) {- if (bytes[offset] !== 255)- fail();- const marker = bytes[offset + 1];- if (marker === 255) {- offset++;- continue;- }- if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {- offset += 2;- continue;- }- const length = view.getUint16(offset + 2);- if (marker >= 192 && marker <= 207 && ![196, 200, 204].includes(marker)) {- at(offset + 5, 4);- return { width: view.getUint16(offset + 7), height: view.getUint16(offset + 5) };- }- offset += 2 + length;- }- fail();- }- const text = (offset) => String.fromCharCode(...bytes.subarray(offset, Math.min(offset + 4, bytes.byteLength)));- if (text(0) === "RIFF" && text(8) === "WEBP") {- at(12, 19);- const chunk = text(12);- if (chunk === "VP8X")- return {- width: 1 + (view.getUint32(24, true) & 16777215),- height: 1 + (view.getUint32(27, true) & 16777215)- };- if (chunk === "VP8L") {- const bits = view.getUint32(21, true);- return { width: 1 + (bits & 16383), height: 1 + (bits >> 14 & 16383) };- }- if (chunk === "VP8 ") {- at(26, 4);- return {- width: view.getUint16(26, true) & 16383,- height: view.getUint16(28, true) & 16383- };- }- }- return fail();-}-function textureSource(texture) {- if (!object2(texture))- return;- const extensions = object2(texture.extensions) ? texture.extensions : {};- for (const name of ["KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif"]) {- const extension = extensions[name];- if (object2(extension) && index(extension.source) !== undefined)- return index(extension.source);- }- return index(texture.source);-}-function srgbImages(json) {- const textures = Array.isArray(json.textures) ? json.textures : [];- const result = new Set;- for (const material of Array.isArray(json.materials) ? json.materials : []) {- if (!object2(material))- continue;- const pbr = object2(material.pbrMetallicRoughness) ? material.pbrMetallicRoughness : {};- for (const info of [pbr.baseColorTexture, material.emissiveTexture]) {- const texture = object2(info) ? index(info.index) : undefined;- const image = texture === undefined ? undefined : textureSource(textures[texture]);- if (image !== undefined)- result.add(image);- }- }- return result;-}-function base64(text) {- const binary = atob(text);- return Uint8Array.from(binary, (character) => character.charCodeAt(0));-}-function embeddedImages(json, binary) {- const views = Array.isArray(json.bufferViews) ? json.bufferViews : [];- return (Array.isArray(json.images) ? json.images : []).map((image) => {- if (!object2(image))- throw new Error("Invalid glTF image");- const view = index(image.bufferView);- if (view !== undefined) {- const def = views[view];- if (!object2(def) || index(def.buffer) !== 0 || !binary)- throw new Error("Texture manifest requires images embedded in the GLB binary chunk");- const offset = index(def.byteOffset) ?? 0;- const length = index(def.byteLength);- if (length === undefined || offset + length > binary.byteLength)- throw new Error("Invalid glTF image buffer view");- if (typeof image.mimeType !== "string")- throw new Error("Embedded image needs a mimeType");- return { bytes: binary.subarray(offset, offset + length), mimeType: image.mimeType };- }- const match = typeof image.uri === "string" ? /^data:([^;,]+);base64,(.*)$/s.exec(image.uri) : null;- if (!match)- throw new Error("Texture manifest requires embedded image bytes");- return { bytes: base64(match[2]), mimeType: match[1] };- });-}-async function runtimeTextureManifest(json, binary, options = {}) {- const srgb = srgbImages(json);- const entries = [];- for (const [image, { bytes, mimeType }] of embeddedImages(json, binary).entries()) {- const sha256 = `sha256:${await sha256Hex3(bytes)}`;- const sourceSha256 = options.sources?.get(image);- const original = sourceSha256 ?? sha256;- const map = options.maps?.find((candidate) => candidate.sha256 === original);- entries.push({- image,- sha256,- bytes: bytes.byteLength,- mimeType,- ...imageDimensions(bytes),- colorSpace: srgb.has(image) ? "srgb" : "linear",- ...sourceSha256 && sourceSha256 !== sha256 ? { sourceSha256 } : {},- ...map ? { material: { pin: { ...map.pin }, slot: map.slot } } : {}- });- }- return entries;-}-function textureFileExtension(mimeType) {- const extension = {- "image/png": "png",- "image/jpeg": "jpg",- "image/webp": "webp",- "image/ktx2": "ktx2"- }[mimeType];- if (!extension)- throw new Error(`External textures do not support ${mimeType}`);- return extension;-}-var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), index = (value) => Number.isInteger(value) && value >= 0 ? value : undefined, KTX2_IDENTIFIER, isKtx2 = (bytes) => bytes.byteLength >= 12 && KTX2_IDENTIFIER.every((value, at) => bytes[at] === value);-var init_runtime_textures = __esm(() => {- KTX2_IDENTIFIER = Object.freeze([- 171,- 75,- 84,- 88,- 32,- 50,- 48,- 187,- 13,- 10,- 26,- 10- ]);-});-// src/ktx2-basis.tsimport { createHash as createHash16 } from "node:crypto";import { readFile as readFile8 } from "node:fs/promises";@@ -42722,336 +43254,6 @@ var init_ktx2_basis = __esm(() => {});});-// src/runtime-three.ts-var exports_runtime_three = {};-__export(exports_runtime_three, {- deliverRuntimeThreeGlb: () => deliverRuntimeThreeGlb-});-import {- Format,- Logger as Logger2,- PropertyType as PropertyType5-} from "@gltf-transform/core";-import {- EXTMeshGPUInstancing,- EXTMeshoptCompression,- KHRTextureBasisu as KHRTextureBasisu2-} from "@gltf-transform/extensions";-import { dedup as dedup2, quantize, reorder } from "@gltf-transform/functions";-import * as THREE55 from "three";-function meshSignature(mesh, ids) {- const id = (property) => {- if (!property)- return -1;- if (!ids.has(property))- ids.set(property, ids.size);- return ids.get(property);- };- return mesh.listPrimitives().map((primitive) => `${primitive.getMode()}:${id(primitive.getMaterial())}:${id(primitive.getIndices())}:${primitive.listSemantics().sort().map((semantic) => `${semantic}=${id(primitive.getAttribute(semantic))}`).join(",")}:${primitive.listTargets().length}`).join("|");-}-function applyScopedInstancing(doc) {- const report = [];- const ids = new Map;- const parents = doc.getRoot().listNodes().filter((node) => node.getExtras()[KILN_REPEAT_INSTANCES_KEY] !== undefined);- let extension;- for (const parent of parents) {- const groups = new Map;- for (const child of parent.listChildren()) {- const mesh = child.getMesh();- if (!mesh || child.listChildren().length || child.getSkin() || child.listExtensions().length || isHiddenGltfNode(child) || rolesOf4(child).length || Object.keys(child.getExtras()).length || child.getWeights().length)- continue;- const signature = meshSignature(mesh, ids);- groups.set(signature, [...groups.get(signature) ?? [], child]);- }- let batchIndex = 0;- for (const nodes of groups.values()) {- if (nodes.length < 2)- continue;- const mesh = nodes[0].getMesh();- extension ??= doc.createExtension(EXTMeshGPUInstancing).setRequired(true);- const buffer = doc.getRoot().listBuffers()[0];- const accessor = (type, values) => doc.createAccessor().setType(type).setArray(new Float32Array(values)).setBuffer(buffer ?? null);- const t = [], r = [], s = [];- for (const node of nodes) {- t.push(...node.getTranslation());- r.push(...node.getRotation());- s.push(...node.getScale());- }- const batch = extension.createInstancedMesh().setAttribute("TRANSLATION", accessor("VEC3", t)).setAttribute("ROTATION", accessor("VEC4", r)).setAttribute("SCALE", accessor("VEC3", s));- const name = `${parent.getName() || "Node"}_Instances${batchIndex ? `_${batchIndex}` : ""}`;- batchIndex++;- const batchNode = doc.createNode(name).setMesh(mesh).setExtension("EXT_mesh_gpu_instancing", batch);- parent.addChild(batchNode);- report.push({- node: batchNode,- mesh: mesh.getName(),- count: nodes.length,- instances: nodes.map((node) => node.getName())- });- for (const node of nodes) {- const own = node.getMesh();- node.dispose();- if (own && own !== mesh && !own.listParents().some((p) => p.propertyType === PropertyType5.NODE))- own.dispose();- }- }- const extras = { ...parent.getExtras() };- delete extras[KILN_REPEAT_INSTANCES_KEY];- parent.setExtras(extras);- }- return report;-}-function splitColliderProxies(doc) {- const report = [];- for (const node of doc.getRoot().listNodes()) {- const mesh = node.getMesh();- if (!mesh || !isCollider(node))- continue;- const proxy = doc.createNode(`${node.getName()}_Proxy`).setMesh(mesh);- node.setMesh(null).addChild(proxy);- report.push({ collider: node, proxy });- }- return report;-}-async function encodeKtx2(doc, encoder, sources) {- const textures = doc.getRoot().listTextures().filter((texture) => texture.getMimeType() !== "image/ktx2" && texture.getImage());- if (!encoder)- return {- status: "skipped",- textures: textures.length,- reason: "No KTX2 encoder was supplied; textures stay PNG or JPEG."- };- const slots = new Map;- const use = (texture, slot) => {- if (texture)- slots.set(texture, (slots.get(texture) ?? new Set).add(slot));- };- for (const material of doc.getRoot().listMaterials()) {- use(material.getBaseColorTexture(), "baseColor");- use(material.getEmissiveTexture(), "emissive");- use(material.getNormalTexture(), "normal");- use(material.getMetallicRoughnessTexture(), "metallicRoughness");- use(material.getOcclusionTexture(), "occlusion");- }- const order = [- "baseColor",- "emissive",- "normal",- "metallicRoughness",- "occlusion"- ];- for (const texture of textures) {- const used = slots.get(texture) ?? new Set;- const srgb = used.has("baseColor") || used.has("emissive");- const other = texture.listParents().some((parent) => parent.propertyType !== PropertyType5.ROOT && !isCoreMaterialUse(parent));- const linear = [...used].some((slot) => slot !== "baseColor" && slot !== "emissive") || other;- if (srgb && linear)- throw new Error(`Texture ${JSON.stringify(texture.getName())} is used by both sRGB and linear material slots; one KTX2 encoding cannot serve both. Use separate images.`);- const original = texture.getImage();- const image = await encoder({- image: original,- mimeType: texture.getMimeType(),- name: texture.getName(),- colorSpace: srgb ? "srgb" : "linear",- slot: order.find((slot) => used.has(slot)) ?? "other"- });- if (!(image instanceof Uint8Array) || !isKtx2(image))- throw new Error("ktx2Encoder must return KTX2 bytes starting with the KTX2 identifier");- sources.set(texture, `sha256:${await sha256Hex3(original)}`);- texture.setImage(image).setMimeType("image/ktx2");- const uri = texture.getURI();- if (uri)- texture.setURI(uri.replace(/\.(png|jpe?g)$/i, ".ktx2"));- }- if (textures.length) {- doc.createExtension(KHRTextureBasisu2).setRequired(true);- await Promise.resolve().then(() => init_atlas_provenance());- await refreshAtlasDocumentProvenance(doc);- await validateAtlasDocumentProvenance(doc);- }- return {- status: "encoded",- textures: textures.length,- ...encoder.identity ? { encoder: structuredClone(encoder.identity) } : {}- };-}-function isCoreMaterialUse(parent) {- return parent.propertyType === PropertyType5.MATERIAL;-}-function decomposeDelta(before, after) {- const delta = new THREE55.Matrix4().fromArray(before).invert().multiply(new THREE55.Matrix4().fromArray(after));- const position = new THREE55.Vector3, quaternion = new THREE55.Quaternion, scale = new THREE55.Vector3;- delta.decompose(position, quaternion, scale);- return {- scale: scale.x,- offset: [position.x, position.y, position.z]- };-}-async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layout = {}) {- const compression = options.compression ?? "meshopt";- if (compression !== "meshopt" && compression !== "none")- throw new Error("Runtime three compression must be meshopt or none");- const io = createGltfIO().registerDependencies({- "meshopt.encoder": meshoptEncoder- });- const doc = await io.readBinary(bytes);- doc.setLogger(new Logger2(Logger2.Verbosity.SILENT));- await doc.transform(dedup2({ propertyTypes: [PropertyType5.ACCESSOR], keepUniqueNames: true }));- const instanced = applyScopedInstancing(doc);- const proxies = splitColliderProxies(doc);- const matrices = new Map;- for (const node of doc.getRoot().listNodes())- if (node.getMesh())- matrices.set(node, [...node.getMatrix()]);- await doc.transform(reorder({ encoder: meshoptEncoder, target: "size" }), quantize({- pattern: QUANTIZED_SEMANTICS,- patternTargets: QUANTIZED_SEMANTICS,- quantizationVolume: "mesh",- quantizePosition: RUNTIME_THREE_QUANTIZATION.position,- quantizeNormal: RUNTIME_THREE_QUANTIZATION.normal,- quantizeTexcoord: RUNTIME_THREE_QUANTIZATION.texcoord,- quantizeColor: RUNTIME_THREE_QUANTIZATION.color,- quantizeWeight: RUNTIME_THREE_QUANTIZATION.weight- }));- if (compression === "meshopt")- doc.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE });- const encodedSources = new Map;- const ktx2 = await encodeKtx2(doc, options.ktx2Encoder, encodedSources);- for (const node of doc.getRoot().listNodes()) {- const mesh = node.getMesh();- if (!mesh || matrices.has(node) || node.getName())- continue;- const parent = node.getParentNode();- node.setName(`${parent?.getName() || "Node"}_Mesh`);- }- const after = deliveryNodePaths(doc);- const pathOf = (node) => after.get(node) ?? `#${encodeURIComponent(node.getName())}`;- const proxyNodes = new Set(proxies.map((entry) => entry.proxy));- const nodeScale = [];- for (const node of doc.getRoot().listNodes()) {- const mesh = node.getMesh();- if (!mesh || node.getExtension("EXT_mesh_gpu_instancing"))- continue;- const path = after.get(node);- if (path === undefined)- continue;- const original = matrices.get(node);- const moved = original === undefined;- const split = moved || proxyNodes.has(node);- const reference = moved ? new THREE55.Matrix4().identity().toArray() : original;- const current = [...node.getMatrix()];- const { scale, offset } = decomposeDelta(reference, current);- if (!moved && Math.abs(scale - 1) < 0.000000000001 && offset.every((v) => v === 0))- continue;- const parent = node.getParentNode();- nodeScale.push({- node: path,- mesh: mesh.getName(),- meshMovedToChild: split,- ...split && parent ? { authoredNode: pathOf(parent) } : {},- dequantization: { scale, offset },- localScale: [...node.getScale()]- });- }- for (const node of doc.getRoot().listNodes()) {- const mesh = node.getMesh();- if (!mesh || after.has(node) || !matrices.has(node))- continue;- const { scale, offset } = decomposeDelta(matrices.get(node), [...node.getMatrix()]);- nodeScale.push({- node: `#lod/${encodeURIComponent(node.getName())}`,- mesh: mesh.getName(),- meshMovedToChild: false,- dequantization: { scale, offset },- localScale: [...node.getScale()]- });- }- const customAttributes = new Map;- for (const mesh of doc.getRoot().listMeshes())- for (const primitive of mesh.listPrimitives())- for (const semantic of primitive.listSemantics())- if (semantic.startsWith("_"))- customAttributes.set(semantic, (customAttributes.get(semantic) ?? new Set).add(mesh));- const all = doc.getRoot().listNodes();- const glb = await io.writeBinary(doc);- const json = (await io.binaryToJSON(glb)).json;- const imageSources = new Map;- doc.getRoot().listTextures().forEach((texture, image) => {- const source = encodedSources.get(texture);- if (source)- imageSources.set(image, source);- });- const gltf = layout.gltfBasename ? await io.writeJSON(doc, { format: Format.GLTF, basename: layout.gltfBasename }) : undefined;- const delivery = {- target: "three",- extensionsUsed: [...json.extensionsUsed ?? []].sort(),- extensionsRequired: [...json.extensionsRequired ?? []].sort(),- compression: compression === "meshopt" ? { extension: "EXT_meshopt_compression", method: "quantize" } : { extension: "none" },- quantization: {- extension: "KHR_mesh_quantization",- volume: "mesh",- bits: {- position: RUNTIME_THREE_QUANTIZATION.position,- normal: RUNTIME_THREE_QUANTIZATION.normal,- texcoord: RUNTIME_THREE_QUANTIZATION.texcoord,- color: RUNTIME_THREE_QUANTIZATION.color,- weight: RUNTIME_THREE_QUANTIZATION.weight- },- customAttributes: "float32"- },- nodeScale,- colliderProxies: proxies.map(({ collider, proxy }) => ({- collider: pathOf(collider),- proxy: pathOf(proxy)- })),- customAttributes: [...customAttributes].sort(([a], [b]) => customRank(a) - customRank(b) || (a < b ? -1 : a > b ? 1 : 0)).map(([name, meshes]) => ({- name,- meshes: meshes.size,- componentType: "FLOAT",- normalized: false- })),- instancing: instanced.map(({ node, ...rest }) => ({ node: pathOf(node), ...rest })),- ktx2,- preserved: {- lodChains: all.filter((node) => node.getExtension(MSFT_LOD)).length,- hiddenNodes: all.filter((node) => isHiddenGltfNode(node)).length,- colliders: all.filter(isCollider).length,- anchors: all.filter((node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.anchor}.`))).length,- ports: all.filter((node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.kitPort}.`))).length,- kitModules: all.filter((node) => rolesOf4(node).includes(KILN_SEMANTIC_ROLES.kitModule)).length- }- };- return {- glb,- delivery,- imageSources,- ...gltf ? {- gltf: {- json: gltf.json,- resources: gltf.resources- }- } : {}- };-}-var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, customRank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2, rolesOf4 = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf4(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));-var init_runtime_three = __esm(() => {- init_semantic();- init_gltf_io();- init_delivery_inspect();- init_delivery();- init_metrics();- init_runtime_textures();- RUNTIME_THREE_QUANTIZATION = Object.freeze({- volume: "mesh",- position: 14,- normal: 10,- texcoord: 12,- color: 8,- weight: 8- });- QUANTIZED_SEMANTICS = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;-});-// src/asset-export.tsvar exports_asset_export = {};__export(exports_asset_export, {@@ -43154,6 +43356,10 @@ async function exportAssetGlb(record, options = {}) {throw new Error("A runtime export target requires the runtime profile");if (options.compression !== undefined && options.target !== "three")throw new Error("Runtime compression requires the three runtime target");+ if (options.maxLod !== undefined && options.target !== "three")+ throw new Error("Runtime maxLod requires the three runtime target");+ if (options.positionBits !== undefined && options.target !== "three")+ throw new Error("Runtime positionBits requires the three runtime target");const textures = options.textures;if (textures !== undefined && textures !== "manifest" && textures !== "external")throw new Error("Unknown runtime texture option");@@ -43207,7 +43413,9 @@ async function exportAssetGlb(record, options = {}) {if (options.target === "three") {const derived = await deriveThree(writeGlbJson(bytes, jsonEnd, json), {...options.ktx2Encoder ? { ktx2Encoder: options.ktx2Encoder } : {},- ...options.compression ? { compression: options.compression } : {}+ ...options.compression ? { compression: options.compression } : {},+ ...options.maxLod !== undefined ? { maxLod: options.maxLod } : {},+ ...options.positionBits !== undefined ? { positionBits: options.positionBits } : {}}, textures === "external" ? { gltfBasename: gltfName.slice(0, -".gltf".length) } : {});metadata.target = "three";metadata.delivery = derived.delivery;@@ -43268,7 +43476,7 @@ async function externalLayout(gltf, manifest) {const entry = manifest[index];const written = typeof image.uri === "string" ? image.uri : "";const bytes = resources.get(written);- if (!bytes || `sha256:${await sha256Hex3(bytes)}` !== entry.sha256)+ if (!bytes || `sha256:${await sha256Hex2(bytes)}` !== entry.sha256)throw new Error("External texture bytes differ from the delivered GLB");resources.delete(written);const uri = `textures/${entry.sha256.slice("sha256:".length)}.${textureFileExtension(entry.mimeType)}`;@@ -51692,7 +51900,7 @@ __export(exports_draw_diagnostics, {inspectDrawDiagnostics: () => inspectDrawDiagnostics});import { Primitive as Primitive3 } from "@gltf-transform/core";-import { cloneDocument } from "@gltf-transform/functions";+import { cloneDocument as cloneDocument2 } from "@gltf-transform/functions";import * as THREE57 from "three";function withinLimits(doc) {const root = doc.getRoot();@@ -51848,7 +52056,7 @@ function analyzeDrawDiagnostics(doc, options = {}) {return skipped("input-limit");const keep = options.keep ?? [];const before = collect2(doc, keep);- const copy = cloneDocument(doc);+ const copy = cloneDocument2(doc);const merge = mergeRigidGroups(copy, { keep });const after = collect2(copy, keep);const all = [...before.anchors.values()].map((anchor) => ({@@ -54953,6 +55161,8 @@ async function assetMain(argv) {"profile","target","compression",+ "max-lod",+ "position-bits","textures","port","render",@@ -55165,6 +55375,18 @@ async function assetMain(argv) {throw new Error("--compression must be meshopt or none");if (compression !== undefined && target !== "three")throw new Error("--compression requires --target three");+ const maxLodFlag = flags["max-lod"];+ if (maxLodFlag !== undefined && !/^\d+$/.test(maxLodFlag))+ throw new Error("--max-lod must be a non-negative integer, such as 0 for LOD0 only");+ if (maxLodFlag !== undefined && target !== "three")+ throw new Error("--max-lod requires --target three");+ const maxLod = maxLodFlag === undefined ? undefined : Number(maxLodFlag);+ const bitsFlag = flags["position-bits"];+ if (bitsFlag !== undefined && bitsFlag !== "float" && !(/^\d+$/.test(bitsFlag) && Number(bitsFlag) >= 8 && Number(bitsFlag) <= 16))+ throw new Error("--position-bits must be an integer from 8 to 16, or float");+ if (bitsFlag !== undefined && target !== "three")+ throw new Error("--position-bits requires --target three");+ const positionBits = bitsFlag === undefined || bitsFlag === "float" ? bitsFlag : Number(bitsFlag);const textures = flags.textures;if (textures !== undefined && textures !== "manifest" && textures !== "external")throw new Error("Unknown --textures value; use manifest or external");@@ -55197,6 +55419,8 @@ async function assetMain(argv) {metadataFileName,...target ? { target } : {},...compression ? { compression } : {},+ ...maxLod !== undefined ? { maxLod } : {},+ ...positionBits !== undefined ? { positionBits } : {},...textures ? { textures } : {},...gltfLayout ? { gltfFileName: basename2(destination) } : {},...flags.ktx2 ? { ktx2Encoder: await createKtx2Encoder2() } : {}@@ -55255,6 +55479,8 @@ async function assetMain(argv) {profile,...target ? { target } : {},...compression ? { compression } : {},+ ...maxLod !== undefined ? { maxLod } : {},+ ...positionBits !== undefined ? { positionBits } : {},format,...ktx2Receipt ? { ktx2: ktx2Receipt } : {},...format !== "source" ? {@@ -55381,6 +55607,10 @@ ${SAVE_LINES}instancing; sidecar states node scales; KTX2 skipped unless --ktx2[--compression meshopt|none] with --target three: none writes plain buffersfor loaders without a Meshopt decoder (default meshopt)+ [--max-lod N] with --target three: keep LOD0..LODN of each MSFT_lod chain and+ drop the rest (0 keeps LOD0 only); the sidecar lists what was dropped+ [--position-bits 8..16|float] with --target three: position quantization bits+ (default 14) or float positions; the sidecar reports the grid step[--ktx2] with --target three: KTX2 through the optional [email protected] peer(npm install [email protected]), ETC1S colour, UASTC data maps[--textures manifest] runtime only: the sidecar names each image's exact bytes@@ -57343,6 +57573,7 @@ function assertNodeRuntime(capability = "core", version = process.versions.node)}// src/cli.ts+init_engine_identity();var USAGE3 = `kiln — vision-in-the-loop 3D asset generationUSAGE@@ -57358,6 +57589,7 @@ USAGEkiln animation <program.js|ref> [options] review sampled motion of an exported clipkiln inspect <program.js|ref> [options] close-up views and surface/anchor measurementskiln service status|start|stop|reprobe the shared GPU render service (see below)+ kiln --version print the installed Kiln versionOPTIONS--out <path> GLB output path (default: out.glb)@@ -57905,6 +58137,10 @@ function main(argv) {return withProcessAlive(() => runMain(argv));}async function runMain(argv) {+ if (argv.length === 1 && argv[0] === "--version") {+ console.log(ENGINE_VERSION);+ return 0;+ }try {assertNodeRuntime();} catch (error) {diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex bac67b72..9daa0bcd 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -2891,6 +2891,9 @@ var init_gltf_io = __esm(() => {listLevels() {return this.listRefs("levels");}+ removeLevel(level) {+ return this.removeRef("levels", level);+ }};MSFTLod = class MSFTLod extends Extension {extensionName = MSFT_LOD;@@ -18390,6 +18393,7 @@ function readBudgetDeclaration(value) {}}function evaluateBudget(declaration, measuredLod0, chains) {+ const instanced = measuredLod0.instancedDraws === undefined ? {} : { instancedDraws: measuredLod0.instancedDraws };const outside = measuredLod0.triangles - chains.reduce((sum, chain) => sum + chain.levels[0].triangles, 0);const tierTriangles = (level) => outside + chains.reduce((sum, chain) => sum + chain.levels[Math.min(level, chain.levels.length - 1)].triangles, 0);const tiers = Object.entries(declaration.triangles).map(([tier, limit]) => {@@ -18405,7 +18409,7 @@ function evaluateBudget(declaration, measuredLod0, chains) {},measured: {triangles,- ...drawsDeclared === undefined ? {} : { draws: measuredLod0.draws }+ ...drawsDeclared === undefined ? {} : { draws: measuredLod0.draws, ...instanced }},status: pass ? "pass" : "fail"};@@ -18414,7 +18418,7 @@ function evaluateBudget(declaration, measuredLod0, chains) {tiers.unshift({tier: "LOD0",declared: { draws: declaration.draws },- measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws },+ measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws, ...instanced },status: measuredLod0.draws <= declaration.draws ? "pass" : "fail"});return { status: tiers.every((tier) => tier.status === "pass") ? "pass" : "fail", tiers };@@ -29070,6 +29074,133 @@ var init_texture_bake = __esm(() => {];});+// src/runtime-textures.ts+var KTX2_IDENTIFIER;+var init_runtime_textures = __esm(() => {+ KTX2_IDENTIFIER = Object.freeze([+ 171,+ 75,+ 84,+ 88,+ 32,+ 50,+ 48,+ 187,+ 13,+ 10,+ 26,+ 10+ ]);+});++// src/runtime-three.ts+var exports_runtime_three = {};+__export(exports_runtime_three, {+ instancedDrawEstimate: () => instancedDrawEstimate+});+import {+ Accessor,+ Format,+ Logger,+ PropertyType as PropertyType5+} from "@gltf-transform/core";+import {+ EXTMeshGPUInstancing,+ EXTMeshoptCompression,+ KHRMeshQuantization,+ KHRTextureBasisu as KHRTextureBasisu2+} from "@gltf-transform/extensions";+import { cloneDocument, dedup, prune, quantize, reorder } from "@gltf-transform/functions";+import * as THREE50 from "three";+function meshSignature(mesh, ids) {+ const id = (property) => {+ if (!property)+ return -1;+ if (!ids.has(property))+ ids.set(property, ids.size);+ return ids.get(property);+ };+ return mesh.listPrimitives().map((primitive) => `${primitive.getMode()}:${id(primitive.getMaterial())}:${id(primitive.getIndices())}:${primitive.listSemantics().sort().map((semantic) => `${semantic}=${id(primitive.getAttribute(semantic))}`).join(",")}:${primitive.listTargets().length}`).join("|");+}+async function instancedDrawEstimate(doc) {+ const copy = cloneDocument(doc);+ copy.setLogger(new Logger(Logger.Verbosity.SILENT));+ await copy.transform(dedup({ propertyTypes: [PropertyType5.ACCESSOR], keepUniqueNames: true }));+ applyScopedInstancing(copy);+ return collectGlbMetrics(copy).drawCalls;+}+function applyScopedInstancing(doc) {+ const report = [];+ const ids = new Map;+ const parents = doc.getRoot().listNodes().filter((node) => node.getExtras()[KILN_REPEAT_INSTANCES_KEY] !== undefined);+ let extension;+ for (const parent of parents) {+ const groups = new Map;+ for (const child of parent.listChildren()) {+ const mesh = child.getMesh();+ if (!mesh || child.listChildren().length || child.getSkin() || child.listExtensions().length || isHiddenGltfNode(child) || rolesOf4(child).length || Object.keys(child.getExtras()).length || child.getWeights().length)+ continue;+ const signature = meshSignature(mesh, ids);+ groups.set(signature, [...groups.get(signature) ?? [], child]);+ }+ let batchIndex = 0;+ for (const nodes of groups.values()) {+ if (nodes.length < 2)+ continue;+ const mesh = nodes[0].getMesh();+ extension ??= doc.createExtension(EXTMeshGPUInstancing).setRequired(true);+ const buffer = doc.getRoot().listBuffers()[0];+ const accessor = (type, values) => doc.createAccessor().setType(type).setArray(new Float32Array(values)).setBuffer(buffer ?? null);+ const t = [], r = [], s = [];+ for (const node of nodes) {+ t.push(...node.getTranslation());+ r.push(...node.getRotation());+ s.push(...node.getScale());+ }+ const batch = extension.createInstancedMesh().setAttribute("TRANSLATION", accessor("VEC3", t)).setAttribute("ROTATION", accessor("VEC4", r)).setAttribute("SCALE", accessor("VEC3", s));+ const name = `${parent.getName() || "Node"}_Instances${batchIndex ? `_${batchIndex}` : ""}`;+ batchIndex++;+ const batchNode = doc.createNode(name).setMesh(mesh).setExtension("EXT_mesh_gpu_instancing", batch);+ parent.addChild(batchNode);+ report.push({+ node: batchNode,+ mesh: mesh.getName(),+ count: nodes.length,+ instances: nodes.map((node) => node.getName())+ });+ for (const node of nodes) {+ const own = node.getMesh();+ node.dispose();+ if (own && own !== mesh && !own.listParents().some((p) => p.propertyType === PropertyType5.NODE))+ own.dispose();+ }+ }+ const extras = { ...parent.getExtras() };+ delete extras[KILN_REPEAT_INSTANCES_KEY];+ parent.setExtras(extras);+ }+ return report;+}+var RUNTIME_THREE_QUANTIZATION, rolesOf4 = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];+var init_runtime_three = __esm(() => {+ init_semantic();+ init_gltf_io();+ init_delivery_inspect();+ init_delivery();+ init_metrics();+ init_runtime_textures();+ init_lod_export();+ init_budget();+ RUNTIME_THREE_QUANTIZATION = Object.freeze({+ volume: "mesh",+ position: 14,+ normal: 10,+ texcoord: 12,+ color: 8,+ weight: 8+ });+});+// src/exporter-node.tsvar exports_exporter_node = {};__export(exports_exporter_node, {@@ -29142,7 +29273,7 @@ var init_exporter_node = __esm(() => {});// src/views/character.ts-import * as THREE50 from "three";+import * as THREE51 from "three";function rounded(value) {const result = Math.round(value * 1e9) / 1e9;return Object.is(result, -0) ? 0 : result;@@ -29184,9 +29315,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {const invalidPaths = new Set(invalidFindingNodePaths);const joints = evidence.map((joint) => {const relative = rootInverse.clone().multiply(joint.node.matrixWorld);- const position = new THREE50.Vector3().setFromMatrixPosition(relative);- const forward = new THREE50.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);- const bend = new THREE50.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const position = new THREE51.Vector3().setFromMatrixPosition(relative);+ const forward = new THREE51.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE51.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -30449,7 +30580,7 @@ function prepareTriangleCoverage(ax, ay, bx, by, cx, cy, size) {}// src/views/raster.ts-import { Vector3 as Vector337 } from "three";+import { Vector3 as Vector338 } from "three";function orbitDir(azimuthDeg, elevationDeg) {const el = Math.min(MAX_ELEVATION_DEG, Math.max(MIN_ELEVATION_DEG, elevationDeg)) * Math.PI / 180;const az = azimuthDeg * Math.PI / 180;@@ -30473,7 +30604,7 @@ function updateSurfaceMatrices(root) {function surfaceVertexReader(mesh, position) {for (const bone of mesh.skeleton?.bones ?? [])bone.updateWorldMatrix?.(true, false);- const vertex = new Vector337;+ const vertex = new Vector338;if (mesh.getVertexPosition)return (index) => mesh.getVertexPosition(index, vertex);if (position.getX && position.getY && position.getZ)@@ -30750,7 +30881,7 @@ import {var init_scene_copy = () => {};// src/views/camera.ts-import { Vector3 as Vector338, Matrix4 as Matrix416, Euler as Euler5, Group as Group4 } from "three";+import { Vector3 as Vector339, Matrix4 as Matrix417, Euler as Euler5, Group as Group4 } from "three";function strict(value, keys, label) {for (const key of Object.keys(value))if (!keys.includes(key)) {@@ -30844,14 +30975,14 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {const z = vec(dir).normalize();if (!z.length())throw new Error("camera direction must be non-zero");- const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector338(0, 0, -1) : new Vector338(0, 1, 0);+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector339(0, 0, -1) : new Vector339(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 = z.clone().cross(x);let extent = 0.000001;for (let i = 0;i < 8; i++) {- const p = new Vector338((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);+ const p = new Vector339((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);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]));@@ -30932,7 +31063,7 @@ function resolveAssetCamera(root, shot = {}) {if (relative !== "world") {const node = relative === "part" ? selected.node : rootNode;dir.transformDirection(node.matrixWorld);- up = tuple6(new Vector338(0, 1, 0).transformDirection(node.matrixWorld));+ up = tuple6(new Vector339(0, 1, 0).transformDirection(node.matrixWorld));}camera = cameraFromBounds(bounds, tuple6(dir), request.padding ?? 1.2, up, measureBounds(root));} else if (request.type === "explicit") {@@ -30967,7 +31098,7 @@ function resolveAssetCamera(root, shot = {}) {throw new Error("padding requires bounds framing");if (request.framing === "bounds" && request.halfHeight !== undefined)throw new Error("bounds framing derives halfHeight");- let matrix = new Matrix416;+ let matrix = new Matrix417;if (relative === "asset" || relative === "part")matrix = (relative === "asset" ? rootNode : selected.node).matrixWorld;if (request.frame) {@@ -30979,7 +31110,7 @@ function resolveAssetCamera(root, shot = {}) {const position = vec(triple2(request.position, "position")).applyMatrix4(matrix);const target = request.target ? vec(triple2(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);const up = vec(triple2(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);- const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector338().setFromMatrixPosition(matrix));+ const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector339().setFromMatrixPosition(matrix));const radius = vec(bounds.max).sub(vec(bounds.min)).length();camera = {version: "kiln.camera.v1",@@ -31092,11 +31223,11 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return result;};- const key = new Vector338(1.5, 2, 1).normalize();+ const key = new Vector339(1.5, 2, 1).normalize();const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;const ordered = compositingOrder(collectTriangles(root).tris, (px, py, pz) => camera.projection === "perspective" ? Math.hypot(px - position.x, py - position.y, pz - position.z) : (position.x - px) * z.x + (position.y - py) * z.y + (position.z - pz) * z.z);for (const tri of ordered) {- const world = [0, 1, 2].map((i) => new Vector338(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));+ const world = [0, 1, 2].map((i) => new Vector339(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().multiplyScalar(tri.windingParity);const normalSign = visibleNormalSign(normal.dot(camera.projection === "perspective" ? position.clone().sub(world[0]) : z), tri.side, backfaceCull);if (normalSign === 0)@@ -31107,7 +31238,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)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 Vector338(d.dot(x), d.dot(y), -d.dot(z));+ return new Vector339(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++) {@@ -31139,7 +31270,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return out;}-var vec = (a) => new Vector338(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;+var vec = (a) => new Vector339(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;var init_camera = __esm(() => {init_raster();init_background();@@ -31235,7 +31366,7 @@ import {BufferAttribute as BufferAttribute12,BufferGeometry as BufferGeometry15,Group as Group5,- Matrix4 as Matrix417,+ Matrix4 as Matrix418,Mesh as Mesh14,Bone as Bone2,SkinnedMesh as SkinnedMesh2,@@ -31249,8 +31380,8 @@ import {NumberKeyframeTrack,PropertyBinding as PropertyBinding3,VectorKeyframeTrack as VectorKeyframeTrack2,- Quaternion as Quaternion19,- Vector3 as Vector339,+ Quaternion as Quaternion20,+ Vector3 as Vector340,InterpolateDiscrete as InterpolateDiscrete2,InterpolateLinear as InterpolateLinear2} from "three";@@ -32754,7 +32885,7 @@ var init_renderer_id = __esm(() => {});// src/views/scene-raster.ts-import * as THREE51 from "three";+import * as THREE52 from "three";var DEG2;var init_scene_raster = __esm(() => {init_evaluator();@@ -32766,18 +32897,18 @@ var init_scene_raster = __esm(() => {});// src/views/vehicle.ts-import * as THREE52 from "three";+import * as THREE53 from "three";function hasRole2(node, prefix) {return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;}function chassisBounds(root, inverse) {- const bounds = new THREE52.Box3;+ const bounds = new THREE53.Box3;let found = false;root.traverse((node) => {if (!hasRole2(node, "chassis"))return;node.traverse((part) => {- if (!(part instanceof THREE52.Mesh) || !(part.geometry instanceof THREE52.BufferGeometry))+ if (!(part instanceof THREE53.Mesh) || !(part.geometry instanceof THREE53.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -32787,7 +32918,7 @@ function chassisBounds(root, inverse) {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 THREE52.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE53.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -32855,33 +32986,33 @@ function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}function rod(name, start, end, radius, color, role) {- const from = new THREE52.Vector3(...start);- const to = new THREE52.Vector3(...end);+ const from = new THREE53.Vector3(...start);+ const to = new THREE53.Vector3(...end);const direction = to.clone().sub(from);const length = direction.length();- const geometry = length > 0.000000001 ? new THREE52.CylinderGeometry(radius, radius, length, 8) : new THREE52.SphereGeometry(radius, 8, 6);- const result = new THREE52.Mesh(geometry, new THREE52.MeshBasicMaterial({ color }));+ const geometry = length > 0.000000001 ? new THREE53.CylinderGeometry(radius, radius, length, 8) : new THREE53.SphereGeometry(radius, 8, 6);+ const result = new THREE53.Mesh(geometry, new THREE53.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);if (length > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE52.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));+ result.quaternion.setFromUnitVectors(new THREE53.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {- const overlay = new THREE52.Group;+ const overlay = new THREE53.Group;overlay.name = "VehicleDiagnosticOverlay";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 THREE52.Group;+ const arrow = new THREE53.Group;arrow.name = "Diagnostic_Forward_+X";tagDiagnostic(arrow, "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 THREE52.Mesh(new THREE52.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE52.MeshBasicMaterial({ color: 16724804 }));+ const arrowHead = new THREE53.Mesh(new THREE53.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE53.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);- arrowHead.quaternion.setFromUnitVectors(new THREE52.Vector3(0, 1, 0), new THREE52.Vector3(1, 0, 0));+ arrowHead.quaternion.setFromUnitVectors(new THREE53.Vector3(0, 1, 0), new THREE53.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);@@ -32889,18 +33020,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));}for (const wheel of descriptor.wheels) {- const ring = new THREE52.Mesh(new THREE52.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE52.MeshBasicMaterial({ color: 16763955 }));+ const ring = new THREE53.Mesh(new THREE53.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE53.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);- const axle = new THREE52.Vector3(...wheel.axle);+ const axle = new THREE53.Vector3(...wheel.axle);if (axle.lengthSq() > 0.000000000001) {- ring.quaternion.setFromUnitVectors(new THREE52.Vector3(0, 0, 1), axle.normalize());+ ring.quaternion.setFromUnitVectors(new THREE53.Vector3(0, 0, 1), axle.normalize());}tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}if (descriptor.chassisBox) {- const chassis = new THREE52.Group;+ const chassis = new THREE53.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");const { min, max } = descriptor.chassisBox;@@ -32934,7 +33065,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(chassis);}if (descriptor.supportPlaneY !== undefined) {- const plane = new THREE52.Group;+ const plane = new THREE53.Group;plane.name = "Diagnostic_SupportPlane";tagDiagnostic(plane, "diagnostic.vehicle.support-plane");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;@@ -33263,7 +33394,7 @@ var init_views = __esm(() => {});// src/views/character-capture.ts-import * as THREE53 from "three";+import * as THREE54 from "three";function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);@@ -33300,22 +33431,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {}function projector(root, cameraId, size) {root.updateMatrixWorld(true);- const bounds = new THREE53.Box3().setFromObject(root);+ const bounds = new THREE54.Box3().setFromObject(root);if (bounds.isEmpty())- bounds.set(new THREE53.Vector3(-0.5, 0, -0.5), new THREE53.Vector3(0.5, 1, 0.5));- const center = bounds.getCenter(new THREE53.Vector3);- const camera = cameraId === "front" ? new THREE53.Vector3(1, 0, 0) : new THREE53.Vector3(0, 0, 1);- const upHint = new THREE53.Vector3(0, 1, 0);- const xAxis = new THREE53.Vector3().crossVectors(upHint, camera).normalize();- const yAxis = new THREE53.Vector3().crossVectors(camera, xAxis).normalize();+ bounds.set(new THREE54.Vector3(-0.5, 0, -0.5), new THREE54.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE54.Vector3);+ const camera = cameraId === "front" ? new THREE54.Vector3(1, 0, 0) : new THREE54.Vector3(0, 0, 1);+ const upHint = new THREE54.Vector3(0, 1, 0);+ const xAxis = new THREE54.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE54.Vector3().crossVectors(camera, xAxis).normalize();let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {- const point = new THREE53.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);+ const point = new THREE54.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);extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));}const scale = size * 0.45 / extent;return (assetPoint) => {- const world = new THREE53.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ const world = new THREE54.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}@@ -33441,10 +33572,10 @@ var init_character_capture = __esm(() => {});// src/render.ts-import * as THREE54 from "three";-import { Document, Logger } from "@gltf-transform/core";+import * as THREE55 from "three";+import { Document, Logger as Logger2 } from "@gltf-transform/core";import { KHRMaterialsEmissiveStrength } from "@gltf-transform/extensions";-import { dedup, instance, palette, weld as weld2, prune, mergeDocuments } from "@gltf-transform/functions";+import { dedup as dedup2, instance, palette, weld as weld2, prune as prune2, mergeDocuments } from "@gltf-transform/functions";function applySurfaceBakeExtras(root, doc) {const baked = [];root.traverse((node) => {@@ -33484,7 +33615,7 @@ function ensureDefaultScene(doc) {root.setDefaultScene(scene);return scene;}-async function sha256Hex2(bytes) {+async function sha256Hex3(bytes) {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("");}@@ -33510,13 +33641,18 @@ async function inspectGlbIntegration(bytes, opts = {}) {const delivery = inspectDelivery(doc);const vertexAttributes = summarizeVertexAttributes(doc);const budgetDeclaration = readBudgetDeclaration(scene.getExtras()[KILN_BUDGET_KEY]);- const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, { triangles: metrics.triangles, draws: metrics.drawCalls }, levelsOfDetail) : undefined;+ const instancedDraws = budgetDeclaration?.draws === undefined ? undefined : await (await Promise.resolve().then(() => (init_runtime_three(), exports_runtime_three))).instancedDrawEstimate(doc);+ const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, {+ triangles: metrics.triangles,+ draws: metrics.drawCalls,+ ...instancedDraws === undefined ? {} : { instancedDraws }+ }, levelsOfDetail) : undefined;const paletteDeclaration = readPaletteDeclaration(scene.getExtras()[KILN_PALETTE_KEY]);const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;return {schemaVersion: "kiln.integration-manifest.v1",analyzerVersion: 1,- artifactSha256: await sha256Hex2(bytes),+ artifactSha256: await sha256Hex3(bytes),units: "m",axes: { forward: "+X", up: "+Y", right: "+Z" },bounds: {@@ -33663,7 +33799,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (stdMat.transparent) {mat.setAlphaMode("BLEND");}- if (stdMat.side === THREE54.DoubleSide) {+ if (stdMat.side === THREE55.DoubleSide) {mat.setDoubleSided(true);}if (stdMat.map) {@@ -33740,7 +33876,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (common.transparent || (common.opacity ?? 1) < 1) {mat.setAlphaMode("BLEND");}- if (threeMat.side === THREE54.DoubleSide)+ if (threeMat.side === THREE55.DoubleSide)mat.setDoubleSided(true);if (common.map && !mat.getBaseColorTexture()) {const texture = bridgeTexture(doc, common.map, textureCache);@@ -33903,7 +34039,7 @@ 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 geometry = new THREE54.PlaneGeometry(1, 1);+ const geometry = new THREE55.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}@@ -33927,9 +34063,9 @@ function animationInterpolation(track) {if (isCubicSplineTrack(track))return "CUBICSPLINE";const mode = track.getInterpolation();- if (mode === THREE54.InterpolateDiscrete)+ if (mode === THREE55.InterpolateDiscrete)return "STEP";- if (mode === THREE54.InterpolateLinear)+ if (mode === THREE55.InterpolateLinear)return "LINEAR";throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);}@@ -34094,7 +34230,7 @@ async function applyGpuInstancing(doc, mode, role) {return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };}async function consolidateMaterials(doc, mode, keep = []) {- doc.setLogger(new Logger(Logger.Verbosity.WARN));+ doc.setLogger(new Logger2(Logger2.Verbosity.WARN));const before = collectGlbMetrics(doc);const root = doc.getRoot();const steps = root.listMaterials().some((material) => Object.keys(material.getExtras()).length > 0) ? [] : [palette({ min: PALETTE_MIN })];@@ -34103,7 +34239,7 @@ async function consolidateMaterials(doc, mode, keep = []) {steps.push(rigidMerge({ keep }, (summary) => {merge = summary;}));- steps.push(weld2(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));+ steps.push(weld2(), prune2({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));await doc.transform(...steps);const after = collectGlbMetrics(doc);return {@@ -34245,7 +34381,7 @@ async function renderSceneToGLB(root, opts = {}) {const indexBuffers = applyIndexPolicy(doc, indexPolicy);if (opts.dedup !== false) {try {- await doc.transform(dedup());+ await doc.transform(dedup2());} catch (err) {warnings.push(`dedup transform failed: ${err instanceof Error ? err.message : String(err)}`);}@@ -34296,7 +34432,7 @@ async function renderSceneToGLB(root, opts = {}) {await refreshAtlasDocumentProvenance(doc);await validateAtlasDocumentProvenance(doc);const bytes = await io.writeBinary(doc);- const artifactGlbSha256 = `sha256:${await sha256Hex2(bytes)}`;+ const artifactGlbSha256 = `sha256:${await sha256Hex3(bytes)}`;const boundBakedTextures = bakedTextures.map((entry) => ({...entry,artifactGlbSha256@@ -34494,8 +34630,8 @@ function collectMeshStats(root) {if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {return;}- const center = new THREE54.Vector3;- const size = new THREE54.Vector3;+ const center = new THREE55.Vector3;+ const size = new THREE55.Vector3;box.getCenter(center);box.getSize(size);out.push({@@ -34511,7 +34647,7 @@ function collectMeshStats(root) {return out;}function minimalGapVector(a, b) {- const v = new THREE54.Vector3;+ const v = new THREE55.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])v[axis] = b.max[axis] - a.min[axis];@@ -34529,10 +34665,10 @@ function inspectSceneStructure(root, opts = {}) {return warnings;const cat = opts.category?.toLowerCase();if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {- const all = new THREE54.Box3;+ const all = new THREE55.Box3;for (const m of meshes)all.union(m.box);- const size = new THREE54.Vector3;+ const size = new THREE55.Vector3;all.getSize(size);if (cat === "aircraft") {if (size.y > size.x * 1.2) {@@ -34657,18 +34793,18 @@ var init_render = __esm(() => {engineIO = createGltfIO;ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];GLTF_MIN_FILTER = {- [THREE54.NearestFilter]: 9728,- [THREE54.LinearFilter]: 9729,- [THREE54.NearestMipmapNearestFilter]: 9984,- [THREE54.LinearMipmapNearestFilter]: 9985,- [THREE54.NearestMipmapLinearFilter]: 9986,- [THREE54.LinearMipmapLinearFilter]: 9987- };- GLTF_MAG_FILTER = { [THREE54.NearestFilter]: 9728, [THREE54.LinearFilter]: 9729 };+ [THREE55.NearestFilter]: 9728,+ [THREE55.LinearFilter]: 9729,+ [THREE55.NearestMipmapNearestFilter]: 9984,+ [THREE55.LinearMipmapNearestFilter]: 9985,+ [THREE55.NearestMipmapLinearFilter]: 9986,+ [THREE55.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE55.NearestFilter]: 9728, [THREE55.LinearFilter]: 9729 };GLTF_WRAP = {- [THREE54.ClampToEdgeWrapping]: 33071,- [THREE54.MirroredRepeatWrapping]: 33648,- [THREE54.RepeatWrapping]: 10497+ [THREE55.ClampToEdgeWrapping]: 33071,+ [THREE55.MirroredRepeatWrapping]: 33648,+ [THREE55.RepeatWrapping]: 10497};REVIEW_CLIP_LIMITS = {clips: 32,diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex 70e15a36..d3f03404 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -7319,6 +7319,9 @@ var init_gltf_io = __esm(() => {listLevels() {return this.listRefs("levels");}+ removeLevel(level) {+ return this.removeRef("levels", level);+ }};MSFTLod = class MSFTLod extends Extension {extensionName = MSFT_LOD;@@ -9012,6 +9015,228 @@ var init_delivery_inspect = __esm(() => {init_node_visibility();});+// src/lod-export.ts+import { PropertyType as PropertyType3 } from "@gltf-transform/core";+function applyLodChains(root, sets, doc) {+ if (sets.length === 0)+ return;+ const exported = writtenNodeResolver(root, doc, "LOD export");+ const chains = sets.map((set) => ({+ set,+ parent: exported(set.parent),+ levels: set.levels.map(exported)+ }));+ const extension = doc.createExtension(MSFTLod);+ for (const { set, parent, levels } of chains) {+ const [base, ...lower] = levels;+ const lod = extension.createLod();+ for (const level of lower) {+ parent.removeChild(level);+ lod.addLevel(level);+ }+ base.setExtension(MSFT_LOD, lod);+ base.setExtras({ ...base.getExtras(), [MSFT_SCREENCOVERAGE]: [...set.screenCoverage] });+ }+}+function occurrence(siblings, index, name) {+ let count = 0;+ for (let i = 0;i < index; i++)+ if (siblings[i].getName() === name)+ count++;+ return count;+}+function screenCoverageOf(node) {+ const value = node.getExtras()[MSFT_SCREENCOVERAGE];+ return Array.isArray(value) && value.every((item) => typeof item === "number") ? [...value] : undefined;+}+function listLodChainNodes(doc) {+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ if (!scene)+ return [];+ const chains = [];+ const visit = (siblings, parentPath) => {+ siblings.forEach((node, index) => {+ const at = (name) => `${parentPath}${segment4(name, occurrence(siblings, index, name))}`;+ const path = at(node.getName());+ const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);+ if (lower.length > 0)+ chains.push({+ levels: [node, ...lower],+ paths: [path, ...lower.map((level) => at(level.getName()))]+ });+ visit(node.listChildren(), path);+ });+ };+ visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));+ return chains;+}+function isImpostorLevel(node) {+ const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];+ return roles.includes(KILN_SEMANTIC_ROLES.lodImpostor);+}+function summarizeLodChains(doc) {+ return listLodChainNodes(doc).map(({ levels, paths }) => {+ const screenCoverage = screenCoverageOf(levels[0]);+ return {+ path: paths[0],+ ...screenCoverage ? { screenCoverage } : {},+ levels: levels.map((level, number) => ({+ level: number,+ name: level.getName(),+ path: paths[number],+ triangles: drawnNodeTriangles(level),+ ...number > 0 && isImpostorLevel(level) ? { impostor: true } : {}+ }))+ };+ });+}+function trimLodChains(doc, maxLod) {+ const chains = listLodChainNodes(doc);+ const doomed = new Set;+ for (const { levels } of chains)+ for (const level of levels.slice(maxLod + 1))+ level.traverse((node) => {+ doomed.add(node);+ });+ for (const animation of doc.getRoot().listAnimations())+ for (const channel of animation.listChannels()) {+ const target = channel.getTargetNode();+ if (target && doomed.has(target))+ throw new Error(`maxLod ${maxLod} would drop ${target.getName() || "a node"}, which animation ${JSON.stringify(animation.getName())} targets; keep that level.`);+ }+ const trimmed = chains.map(({ levels, paths }) => {+ const [base, ...lower] = levels;+ const dropped = lower.slice(maxLod);+ if (dropped.length > 0) {+ const lod = base.getExtension(MSFT_LOD);+ for (const level of dropped)+ lod.removeLevel(level);+ const extras = { ...base.getExtras() };+ const coverage = screenCoverageOf(base);+ if (maxLod === 0) {+ base.setExtension(MSFT_LOD, null);+ lod.dispose();+ delete extras[MSFT_SCREENCOVERAGE];+ } else if (coverage)+ extras[MSFT_SCREENCOVERAGE] = coverage.slice(0, maxLod + 1);+ base.setExtras(extras);+ for (const level of dropped) {+ const subtree = [];+ level.traverse((node) => {+ subtree.push(node);+ });+ for (const node of subtree.reverse())+ node.dispose();+ }+ }+ return {+ path: paths[0],+ levels: levels.length - dropped.length,+ dropped: dropped.map((level) => level.getName())+ };+ });+ const root = doc.getRoot();+ if (!root.listNodes().some((node) => node.getExtension(MSFT_LOD)))+ root.listExtensionsUsed().find((extension) => extension.extensionName === MSFT_LOD)?.dispose();+ return trimmed;+}+var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;+var init_lod_export = __esm(() => {+ init_semantic();+ init_gltf_io();+ init_metrics();+});++// src/budget.ts+function normalizeBudget(spec) {+ if (!spec || typeof spec !== "object" || Array.isArray(spec))+ fail4("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");+ const value = spec;+ for (const key of Object.keys(value))+ if (key !== "triangles" && key !== "draws" && key !== "schemaVersion")+ fail4(`unknown field ${JSON.stringify(key)}.`);+ const triangles = {};+ if (typeof value.triangles === "number")+ triangles.LOD0 = count2("triangles", value.triangles);+ else if (value.triangles && typeof value.triangles === "object" && !Array.isArray(value.triangles)) {+ const entries = Object.entries(value.triangles);+ if (entries.length === 0)+ fail4("triangles needs at least one tier.");+ for (const [tier, limit] of entries) {+ if (!/^LOD(0|[1-9][0-9]?)$/.test(tier))+ fail4(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);+ triangles[tier] = count2(`triangles.${tier}`, limit);+ }+ } else+ fail4("triangles must be a positive integer or a record of LOD tiers.");+ const ordered = Object.fromEntries(Object.entries(triangles).sort(([a], [b]) => Number(a.slice(3)) - Number(b.slice(3))));+ return {+ schemaVersion: 1,+ triangles: ordered,+ ...value.draws === undefined ? {} : { draws: count2("draws", value.draws) }+ };+}+function defineBudget(spec, target) {+ const declaration = normalizeBudget(spec);+ if (target !== undefined) {+ if (target?.isObject3D !== true)+ fail4("target must be a scene node, normally the root.");+ target.userData[KILN_BUDGET_KEY] = structuredClone(declaration);+ }+ return declaration;+}+function readBudgetDeclaration(value) {+ if (value === undefined)+ return;+ try {+ const declaration = normalizeBudget(value);+ return value.schemaVersion === 1 ? declaration : undefined;+ } catch {+ return;+ }+}+function evaluateBudget(declaration, measuredLod0, chains) {+ const instanced = measuredLod0.instancedDraws === undefined ? {} : { instancedDraws: measuredLod0.instancedDraws };+ const outside = measuredLod0.triangles - chains.reduce((sum, chain) => sum + chain.levels[0].triangles, 0);+ const tierTriangles = (level) => outside + chains.reduce((sum, chain) => sum + chain.levels[Math.min(level, chain.levels.length - 1)].triangles, 0);+ const tiers = Object.entries(declaration.triangles).map(([tier, limit]) => {+ const level = Number(tier.slice(3));+ const triangles = level === 0 ? measuredLod0.triangles : tierTriangles(level);+ const drawsDeclared = level === 0 ? declaration.draws : undefined;+ const pass = triangles <= limit && (drawsDeclared === undefined || measuredLod0.draws <= drawsDeclared);+ return {+ tier,+ declared: {+ triangles: limit,+ ...drawsDeclared === undefined ? {} : { draws: drawsDeclared }+ },+ measured: {+ triangles,+ ...drawsDeclared === undefined ? {} : { draws: measuredLod0.draws, ...instanced }+ },+ status: pass ? "pass" : "fail"+ };+ });+ if (declaration.draws !== undefined && declaration.triangles.LOD0 === undefined)+ tiers.unshift({+ tier: "LOD0",+ declared: { draws: declaration.draws },+ measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws, ...instanced },+ status: measuredLod0.draws <= declaration.draws ? "pass" : "fail"+ });+ return { status: tiers.every((tier) => tier.status === "pass") ? "pass" : "fail", tiers };+}+var KILN_BUDGET_KEY = "kilnBudgetV1", fail4 = (detail) => {+ throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `defineBudget(spec): ${detail}`);+}, count2 = (label, value) => {+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)+ fail4(`${label} must be a positive integer, got ${String(value)}.`);+ return value;+};+var init_budget = __esm(() => {+ init_authoring_diagnostic();+});+// src/gltf-texture-binding.tsimport * as THREE7 from "three";function restoreGltfTextureBinding(texture, info) {@@ -9069,26 +9294,26 @@ var init_gltf_texture_binding = __esm(() => {// src/atlas-provenance.tsimport * as THREE8 from "three";-function fail4(message) {+function fail5(message) {throw new TypeError(`atlas provenance: ${message}`);}function field(input, key) {if (!input || typeof input !== "object" || Array.isArray(input))- fail4("plain metadata object required.");+ fail5("plain metadata object required.");const proto = Object.getPrototypeOf(input);if (proto !== null && proto !== Object.prototype)- fail4("plain metadata prototype required.");+ fail5("plain metadata prototype required.");const d = Object.getOwnPropertyDescriptor(input, key);if (!d)return;if (!d.enumerable || !("value" in d))- fail4("metadata accessors/hidden fields are unsupported.");+ fail5("metadata accessors/hidden fields are unsupported.");return d.value;}function closed(input, keys) {for (const key of Reflect.ownKeys(input))if (typeof key !== "string" || !keys.includes(key))- fail4("unsupported metadata field.");+ fail5("unsupported metadata field.");for (const key of keys)field(input, key);return input;@@ -9114,7 +9339,7 @@ function normalizeCandidates(candidates) {for (const candidate of candidates) {const p = normalize(candidate);if (result && canonicalAtlasMetadataJsonV1(result) !== canonicalAtlasMetadataJsonV1(p))- fail4("direct and saved atlas identities disagree.");+ fail5("direct and saved atlas identities disagree.");result = p;}return result;@@ -9125,23 +9350,23 @@ function readAtlasTextureProvenance(texture) {function admitTable(input) {const r = closed(input, ["version", "atlases"]);if (r["version"] !== ATLAS_PROVENANCE_VERSION)- fail4("unsupported version.");+ fail5("unsupported version.");const entries = r["atlases"];if (!Array.isArray(entries) || Object.getPrototypeOf(entries) !== Array.prototype)- fail4("dense atlas array required.");+ fail5("dense atlas array required.");const n = Object.getOwnPropertyDescriptor(entries, "length").value;if (n > ATLAS_PROVENANCE_LIMITS.atlases || Reflect.ownKeys(entries).length !== n + 1)- fail4("atlas count/density budget exceeded.");+ fail5("atlas count/density budget exceeded.");let bytes = TABLE_ENVELOPE_BYTES;const admitted = [];for (let i = 0;i < n; i++) {const d = Object.getOwnPropertyDescriptor(entries, String(i));if (!d?.enumerable || !("value" in d))- fail4("atlas array accessors are unsupported.");+ fail5("atlas array accessors are unsupported.");const json = canonicalAtlasMetadataJsonV1(d.value);bytes += new TextEncoder().encode(json).length + (i > 0 ? 1 : 0);if (bytes > ATLAS_PROVENANCE_LIMITS.bytes)- fail4("aggregate metadata byte budget exceeded.");+ fail5("aggregate metadata byte budget exceeded.");admitted.push(closed(d.value, ["id", "spec", "manifest"]));}return admitted;@@ -9151,7 +9376,7 @@ function validateAtlasProvenanceTable(input) {for (const e of admitted) {const p = normalize({ spec: e["spec"], manifest: e["manifest"] });if (e["id"] !== p.manifest.manifestHash || ids.has(e["id"]))- fail4("duplicate or mismatched atlas identity.");+ fail5("duplicate or mismatched atlas identity.");ids.add(e["id"]);atlases.push({ id: e["id"], ...p });}@@ -9160,15 +9385,15 @@ function validateAtlasProvenanceTable(input) {function lookup(table, id) {const found = table.atlases.find((a) => a.id === id);if (!found)- fail4("unknown atlas reference.");+ fail5("unknown atlas reference.");return found;}function derivedBinding(p, regionName, origin, mode) {if (!["top-left", "bottom-left"].includes(origin) || !["content-boundary", "texel-center"].includes(mode))- fail4("explicit binding origin/mode required.");+ fail5("explicit binding origin/mode required.");const r = p.manifest.regions.find((r) => r.name === regionName);if (!r)- fail4("unknown named region.");+ fail5("unknown named region.");const { x, y, width: w, height: h } = r.content, center = mode === "texel-center", bottom = origin === "bottom-left";return {manifestHash: p.manifest.manifestHash,@@ -9193,7 +9418,7 @@ function expandAtlasBinding(input, table) {canonicalAtlasMetadataJsonV1(input);const r = closed(input, ["version", "atlasId", "region", "inputOrigin", "mode"]);if (r["version"] !== ATLAS_PROVENANCE_VERSION)- fail4("unsupported binding version.");+ fail5("unsupported binding version.");return derivedBinding(lookup(table, r["atlasId"]), r["region"], r["inputOrigin"], r["mode"]);}function readAtlasGeometryBinding(geometry, provenance) {@@ -9203,7 +9428,7 @@ function readAtlasGeometryBinding(geometry, provenance) {canonicalAtlasMetadataJsonV1(stamp);const r = stamp, derived = derivedBinding(provenance, r["region"], r["inputOrigin"], r["mode"]);if (canonicalAtlasMetadataJsonV1(stamp) !== canonicalAtlasMetadataJsonV1(derived))- fail4("named binding identity or remap formula mismatch.");+ fail5("named binding identity or remap formula mismatch.");return {version: ATLAS_PROVENANCE_VERSION,atlasId: provenance.manifest.manifestHash,@@ -9241,26 +9466,26 @@ function collectAtlasProvenance(root) {canonicalAtlasMetadataJsonV1(candidate);const r = closed(candidate, ["spec", "manifest"]), id = field(r["manifest"], "manifestHash");if (typeof id !== "string" || !/^sha256:[0-9a-f]{64}$/.test(id))- fail4("invalid atlas identity.");+ fail5("invalid atlas identity.");const bytes = new TextEncoder().encode(canonicalAtlasMetadataJsonV1({ ...r, id })).length;const prior = sizes.get(id) ?? 0;total += Math.max(0, bytes - prior) + (prior === 0 && sizes.size > 0 ? 1 : 0);sizes.set(id, Math.max(prior, bytes));if (total > ATLAS_PROVENANCE_LIMITS.bytes || sizes.size > ATLAS_PROVENANCE_LIMITS.atlases)- fail4("aggregate metadata budget exceeded.");+ fail5("aggregate metadata budget exceeded.");ref ??= { version: ATLAS_PROVENANCE_VERSION, id };}const spec = field(raw[0], "spec"), width = field(spec, "width"), height = field(spec, "height");if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1)- fail4("invalid atlas image dimensions.");+ fail5("invalid atlas image dimensions.");pixelBytes += width * height * 4;if (pixelBytes > ATLAS_PROVENANCE_LIMITS.bakeDecodedBytes)- fail4("aggregate atlas bake pixel budget exceeded.");+ fail5("aggregate atlas bake pixel budget exceeded.");candidates.set(texture, raw);textures.set(texture, ref);}if (++bindings > ATLAS_PROVENANCE_LIMITS.bindings)- fail4("texture binding budget exceeded.");+ fail5("texture binding budget exceeded.");meshIds.add(ref.id);}if (!mesh.isMesh)@@ -9269,18 +9494,18 @@ function collectAtlasProvenance(root) {if (stamp === undefined)return;if (++bindings > ATLAS_PROVENANCE_LIMITS.bindings)- fail4("primitive binding budget exceeded.");+ fail5("primitive binding budget exceeded.");canonicalAtlasMetadataJsonV1(stamp);const id = field(stamp, "manifestHash");if (typeof id !== "string" || !meshIds.has(id))- fail4("named binding has no matching primary atlas texture on this mesh.");+ fail5("named binding has no matching primary atlas texture on this mesh.");pendingGeometry.set(mesh.geometry, id);});const identities = new Map;for (const [texture, raw] of candidates) {const p = normalizeCandidates(raw), id = p.manifest.manifestHash, prior = identities.get(id);if (prior && canonicalAtlasMetadataJsonV1(prior) !== canonicalAtlasMetadataJsonV1(p))- fail4("conflicting atlas identity.");+ fail5("conflicting atlas identity.");identities.set(id, p);textures.set(texture, { version: ATLAS_PROVENANCE_VERSION, id });}@@ -9312,7 +9537,7 @@ function atlasMaterialUses(doc) {])if (texture && info && field(info.getExtras(), "kilnAtlasReference") !== undefined) {if (uses.length >= ATLAS_PROVENANCE_LIMITS.bindings)- fail4("document binding budget exceeded.");+ fail5("document binding budget exceeded.");uses.push({ texture, info });}return uses;@@ -9320,7 +9545,7 @@ function atlasMaterialUses(doc) {async function imageHash(texture) {const bytes = texture.getImage();if (!bytes || bytes.byteLength > ATLAS_PROVENANCE_LIMITS.encodedBytes)- fail4("encoded image missing or over budget.");+ fail5("encoded image missing or over budget.");const result = await crypto.subtle.digest("SHA-256", bytes);return `sha256:${[...new Uint8Array(result)].map((v) => v.toString(16).padStart(2, "0")).join("")}`;}@@ -9332,14 +9557,14 @@ function sampler(info) {wrapT: info.getWrapT()};if (![null, 9728, 9729, 9984, 9985, 9986, 9987].includes(value.minFilter) || ![null, 9728, 9729].includes(value.magFilter) || ![33071, 33648, 10497].includes(value.wrapS) || ![33071, 33648, 10497].includes(value.wrapT))- fail4("unsupported effective sampler.");+ fail5("unsupported effective sampler.");return value;}function reference(input, table) {canonicalAtlasMetadataJsonV1(input);const r = closed(input, ["version", "id", "effectiveSampler", "finalMime", "finalImageSha256"]);if (r["version"] !== ATLAS_PROVENANCE_VERSION)- fail4("unsupported texture reference version.");+ fail5("unsupported texture reference version.");lookup(table, r["id"]);return r;}@@ -9352,10 +9577,10 @@ function admitEncodedImages(uses) {seen.add(texture);const bytes = texture.getImage();if (!bytes || bytes.byteLength > ATLAS_PROVENANCE_LIMITS.encodedBytes)- fail4("encoded image missing or over budget.");+ fail5("encoded image missing or over budget.");total += bytes.byteLength;if (total > ATLAS_PROVENANCE_LIMITS.aggregateEncodedBytes)- fail4("aggregate encoded image hash budget exceeded.");+ fail5("aggregate encoded image hash budget exceeded.");}}async function refreshAtlasDocumentProvenance(doc) {@@ -9363,7 +9588,7 @@ async function refreshAtlasDocumentProvenance(doc) {if (!uses.length)return;if (!table)- fail4("atlas table missing.");+ fail5("atlas table missing.");admitEncodedImages(uses);const hashes = new Map;for (const { texture, info } of uses) {@@ -9388,12 +9613,12 @@ async function refreshAtlasDocumentProvenance(doc) {async function validateAtlasDocumentProvenance(doc) {const table = atlasDocumentTable(doc), uses = atlasMaterialUses(doc);if (uses.length && !table)- fail4("atlas table missing.");+ fail5("atlas table missing.");if (!table) {for (const mesh of doc.getRoot().listMeshes())for (const primitive of mesh.listPrimitives())if (field(primitive.getExtras(), "kilnAtlasBinding") !== undefined)- fail4("atlas table missing.");+ fail5("atlas table missing.");return;}admitEncodedImages(uses);@@ -9406,7 +9631,7 @@ async function validateAtlasDocumentProvenance(doc) {hashes.set(texture, hash);}if (r.finalImageSha256 !== hash || r.finalMime !== texture.getMimeType() || canonicalAtlasMetadataJsonV1(r.effectiveSampler) !== canonicalAtlasMetadataJsonV1(sampler(info)))- fail4("final image or effective sampler identity mismatch.");+ fail5("final image or effective sampler identity mismatch.");}let bindings = 0;for (const mesh of doc.getRoot().listMeshes())@@ -9414,7 +9639,7 @@ async function validateAtlasDocumentProvenance(doc) {const binding = field(prim.getExtras(), "kilnAtlasBinding");if (binding !== undefined) {if (++bindings > ATLAS_PROVENANCE_LIMITS.bindings)- fail4("primitive budget exceeded.");+ fail5("primitive budget exceeded.");expandAtlasBinding(binding, table);const material = prim.getMaterial(), id = field(binding, "atlasId");const infos = material ? [@@ -9425,7 +9650,7 @@ async function validateAtlasDocumentProvenance(doc) {material.getOcclusionTextureInfo()] : [];if (!infos.some((info) => info && field(info.getExtras(), "kilnAtlasReference") !== undefined && field(field(info.getExtras(), "kilnAtlasReference"), "id") === id))- fail4("named binding has no matching material atlas reference.");+ fail5("named binding has no matching material atlas reference.");}}}@@ -9439,7 +9664,7 @@ function readAtlasEncodedTexture(texture) {return;const r = closed(encoded, ["mime", "bytes"]);if (r["mime"] !== "image/png" || !(r["bytes"] instanceof Uint8Array) || r["bytes"].byteLength > ATLAS_PROVENANCE_LIMITS.encodedBytes)- fail4("bounded PNG encoding required.");+ fail5("bounded PNG encoding required.");return { mime: "image/png", bytes: r["bytes"] };}function restoreAtlasTextureProvenance(texture, info, table) {@@ -9468,19 +9693,22 @@ var init_atlas_provenance = __esm(() => {// src/runtime-three.tsvar exports_runtime_three = {};__export(exports_runtime_three, {- deliverRuntimeThreeGlb: () => deliverRuntimeThreeGlb+ deliverRuntimeThreeGlb: () => deliverRuntimeThreeGlb,+ instancedDrawEstimate: () => instancedDrawEstimate});import {+ Accessor,Format,Logger,- PropertyType as PropertyType3+ PropertyType as PropertyType4} from "@gltf-transform/core";import {EXTMeshGPUInstancing,EXTMeshoptCompression,+ KHRMeshQuantization,KHRTextureBasisu} from "@gltf-transform/extensions";-import { dedup, quantize, reorder } from "@gltf-transform/functions";+import { cloneDocument, dedup, prune, quantize, reorder } from "@gltf-transform/functions";import * as THREE9 from "three";function meshSignature(mesh, ids) {const id = (property) => {@@ -9492,6 +9720,13 @@ function meshSignature(mesh, ids) {};return mesh.listPrimitives().map((primitive) => `${primitive.getMode()}:${id(primitive.getMaterial())}:${id(primitive.getIndices())}:${primitive.listSemantics().sort().map((semantic) => `${semantic}=${id(primitive.getAttribute(semantic))}`).join(",")}:${primitive.listTargets().length}`).join("|");}+async function instancedDrawEstimate(doc) {+ const copy = cloneDocument(doc);+ copy.setLogger(new Logger(Logger.Verbosity.SILENT));+ await copy.transform(dedup({ propertyTypes: [PropertyType4.ACCESSOR], keepUniqueNames: true }));+ applyScopedInstancing(copy);+ return collectGlbMetrics(copy).drawCalls;+}function applyScopedInstancing(doc) {const report = [];const ids = new Map;@@ -9534,7 +9769,7 @@ function applyScopedInstancing(doc) {for (const node of nodes) {const own = node.getMesh();node.dispose();- if (own && own !== mesh && !own.listParents().some((p) => p.propertyType === PropertyType3.NODE))+ if (own && own !== mesh && !own.listParents().some((p) => p.propertyType === PropertyType4.NODE))own.dispose();}}@@ -9586,7 +9821,7 @@ async function encodeKtx2(doc, encoder, sources) {for (const texture of textures) {const used = slots.get(texture) ?? new Set;const srgb = used.has("baseColor") || used.has("emissive");- const other = texture.listParents().some((parent) => parent.propertyType !== PropertyType3.ROOT && !isCoreMaterialUse(parent));+ const other = texture.listParents().some((parent) => parent.propertyType !== PropertyType4.ROOT && !isCoreMaterialUse(parent));const linear = [...used].some((slot) => slot !== "baseColor" && slot !== "emissive") || other;if (srgb && linear)throw new Error(`Texture ${JSON.stringify(texture.getName())} is used by both sRGB and linear material slots; one KTX2 encoding cannot serve both. Use separate images.`);@@ -9619,7 +9854,7 @@ async function encodeKtx2(doc, encoder, sources) {};}function isCoreMaterialUse(parent) {- return parent.propertyType === PropertyType3.MATERIAL;+ return parent.propertyType === PropertyType4.MATERIAL;}function decomposeDelta(before, after) {const delta = new THREE9.Matrix4().fromArray(before).invert().multiply(new THREE9.Matrix4().fromArray(after));@@ -9630,32 +9865,155 @@ function decomposeDelta(before, after) {offset: [position.x, position.y, position.z]};}+function hasQuantizedVertexData(doc) {+ const quantized = (semantic, accessor) => {+ if (accessor.getComponentSize() >= 4)+ return false;+ if (semantic === "POSITION" || semantic === "NORMAL" || semantic === "TANGENT")+ return true;+ if (!semantic.startsWith("TEXCOORD_"))+ return false;+ const type = accessor.getComponentType();+ return !(accessor.getNormalized() && (type === Accessor.ComponentType.UNSIGNED_BYTE || type === Accessor.ComponentType.UNSIGNED_SHORT));+ };+ return doc.getRoot().listMeshes().flatMap((mesh) => mesh.listPrimitives()).flatMap((primitive) => [primitive, ...primitive.listTargets()]).some((target) => target.listSemantics().some((semantic) => quantized(semantic, target.getAttribute(semantic))));+}+function positionGridSteps(doc, bits) {+ const levels = 2 ** (bits - 1) - 1;+ const lodBase = new Map;+ for (const node of doc.getRoot().listNodes())+ for (const level of node.getExtension(MSFT_LOD)?.listLevels() ?? [])+ if (level.propertyType === PropertyType4.NODE)+ lodBase.set(level, node);+ const world = (node) => {+ const matrix = new THREE9.Matrix4().fromArray(node.getWorldMatrix());+ let top = node;+ while (top.getParentNode())+ top = top.getParentNode();+ const placed = lodBase.get(top)?.getParentNode();+ return placed ? new THREE9.Matrix4().fromArray(placed.getWorldMatrix()).multiply(matrix) : matrix;+ };+ const halfExtent = (mesh) => {+ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];+ const widen = (values, doubleFromZero) => {+ for (let axis = 0;axis < 3; axis++) {+ const value = values[axis];+ const candidates = doubleFromZero ? [value, value * 2, 0] : [value];+ min[axis] = Math.min(min[axis], ...candidates);+ max[axis] = Math.max(max[axis], ...candidates);+ }+ };+ for (const primitive of mesh.listPrimitives()) {+ const position = primitive.getAttribute("POSITION");+ if (position) {+ widen(position.getMin([]), false);+ widen(position.getMax([]), false);+ }+ for (const target of primitive.listTargets()) {+ const delta = target.getAttribute("POSITION");+ if (delta) {+ widen(delta.getMin([]), true);+ widen(delta.getMax([]), true);+ }+ }+ }+ return Math.max(...[0, 1, 2].map((axis) => (max[axis] - min[axis]) / 2));+ };+ const instanceScale = (node) => {+ const scale = node.getExtension("EXT_mesh_gpu_instancing")?.getAttribute("SCALE");+ if (!scale)+ return 1;+ let largest = 0;+ for (let i = 0;i < scale.getCount(); i++)+ largest = Math.max(largest, ...scale.getElement(i, []).map(Math.abs));+ return largest;+ };+ const steps = [];+ for (const node of doc.getRoot().listNodes()) {+ const mesh = node.getMesh();+ if (!mesh?.listPrimitives().some((primitive) => primitive.getAttribute("POSITION")))+ continue;+ const scale = node.getSkin() ? 1 : world(node).getMaxScaleOnAxis() * instanceScale(node);+ steps.push({ node, mesh: mesh.getName(), step: halfExtent(mesh) * scale / levels });+ }+ return steps;+}+async function trimLevels(doc, maxLod) {+ const chains = trimLodChains(doc, maxLod);+ const budgetTiersOmitted = [];+ if (chains.some((chain) => chain.dropped.length > 0)) {+ await doc.transform(prune({+ propertyTypes: [+ PropertyType4.MESH,+ PropertyType4.PRIMITIVE,+ PropertyType4.PRIMITIVE_TARGET,+ PropertyType4.ACCESSOR,+ PropertyType4.MATERIAL,+ PropertyType4.TEXTURE+ ],+ keepAttributes: true,+ keepIndices: true,+ keepLeaves: true,+ keepExtras: true,+ keepSolidTextures: true+ }));+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];+ const extras = { ...scene?.getExtras() ?? {} };+ const budget = extras[KILN_BUDGET_KEY];+ if (scene && budget?.triangles) {+ const triangles = { ...budget.triangles };+ for (const tier of Object.keys(triangles))+ if (Number(tier.slice(3)) > maxLod) {+ budgetTiersOmitted.push(tier);+ delete triangles[tier];+ }+ if (Object.keys(triangles).length > 0)+ extras[KILN_BUDGET_KEY] = { ...budget, triangles };+ else+ delete extras[KILN_BUDGET_KEY];+ scene.setExtras(extras);+ }+ }+ return { maxLod, chains, budgetTiersOmitted };+}async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layout = {}) {const compression = options.compression ?? "meshopt";if (compression !== "meshopt" && compression !== "none")throw new Error("Runtime three compression must be meshopt or none");+ const { maxLod } = options;+ if (maxLod !== undefined && !(Number.isSafeInteger(maxLod) && maxLod >= 0))+ throw new Error("Runtime three maxLod must be a non-negative integer");+ const positionBits = options.positionBits ?? RUNTIME_THREE_QUANTIZATION.position;+ if (positionBits !== "float" && !(Number.isSafeInteger(positionBits) && positionBits >= 8 && positionBits <= 16))+ throw new Error("Runtime three positionBits must be an integer from 8 to 16, or float");const io = createGltfIO().registerDependencies({"meshopt.encoder": meshoptEncoder});const doc = await io.readBinary(bytes);doc.setLogger(new Logger(Logger.Verbosity.SILENT));- await doc.transform(dedup({ propertyTypes: [PropertyType3.ACCESSOR], keepUniqueNames: true }));+ const lod = maxLod === undefined ? undefined : await trimLevels(doc, maxLod);+ await doc.transform(dedup({ propertyTypes: [PropertyType4.ACCESSOR], keepUniqueNames: true }));const instanced = applyScopedInstancing(doc);const proxies = splitColliderProxies(doc);const matrices = new Map;for (const node of doc.getRoot().listNodes())if (node.getMesh())matrices.set(node, [...node.getMatrix()]);+ const steps = positionBits === "float" ? [] : positionGridSteps(doc, positionBits);+ const semantics = positionBits === "float" ? QUANTIZED_SEMANTICS_EXCEPT_POSITION : QUANTIZED_SEMANTICS;await doc.transform(reorder({ encoder: meshoptEncoder, target: "size" }), quantize({- pattern: QUANTIZED_SEMANTICS,- patternTargets: QUANTIZED_SEMANTICS,+ pattern: semantics,+ patternTargets: semantics,quantizationVolume: "mesh",- quantizePosition: RUNTIME_THREE_QUANTIZATION.position,+ quantizePosition: positionBits === "float" ? RUNTIME_THREE_QUANTIZATION.position : positionBits,quantizeNormal: RUNTIME_THREE_QUANTIZATION.normal,quantizeTexcoord: RUNTIME_THREE_QUANTIZATION.texcoord,quantizeColor: RUNTIME_THREE_QUANTIZATION.color,quantizeWeight: RUNTIME_THREE_QUANTIZATION.weight}));+ if (positionBits === "float" && hasQuantizedVertexData(doc))+ doc.createExtension(KHRMeshQuantization).setRequired(true);if (compression === "meshopt")doc.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE });const encodedSources = new Map;@@ -9734,13 +10092,19 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layouextension: "KHR_mesh_quantization",volume: "mesh",bits: {- position: RUNTIME_THREE_QUANTIZATION.position,+ position: positionBits === "float" ? "float32" : positionBits,normal: RUNTIME_THREE_QUANTIZATION.normal,texcoord: RUNTIME_THREE_QUANTIZATION.texcoord,color: RUNTIME_THREE_QUANTIZATION.color,weight: RUNTIME_THREE_QUANTIZATION.weight},- customAttributes: "float32"+ customAttributes: "float32",+ positionSteps: steps.map(({ node, mesh, step }) => ({+ node: after.get(node) ?? `#lod/${encodeURIComponent(node.getName())}`,+ mesh,+ step+ })),+ maxPositionStep: Math.max(0, ...steps.map(({ step }) => step))},nodeScale,colliderProxies: proxies.map(({ collider, proxy }) => ({@@ -9755,6 +10119,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layou})),instancing: instanced.map(({ node, ...rest }) => ({ node: pathOf(node), ...rest })),ktx2,+ ...lod ? { lod } : {},preserved: {lodChains: all.filter((node) => node.getExtension(MSFT_LOD)).length,hiddenNodes: all.filter((node) => isHiddenGltfNode(node)).length,@@ -9776,7 +10141,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layou} : {}};}-var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, customRank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2, rolesOf = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));+var RUNTIME_THREE_QUANTIZATION, QUANTIZED_SEMANTICS, QUANTIZED_SEMANTICS_EXCEPT_POSITION, customRank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2, rolesOf = (node) => readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [], isCollider = (node) => rolesOf(node).some((role) => role.startsWith(`${KILN_SEMANTIC_ROLES.collider}.`));var init_runtime_three = __esm(() => {init_semantic();init_gltf_io();@@ -9784,6 +10149,8 @@ var init_runtime_three = __esm(() => {init_delivery();init_metrics();init_runtime_textures();+ init_lod_export();+ init_budget();RUNTIME_THREE_QUANTIZATION = Object.freeze({volume: "mesh",position: 14,@@ -9793,6 +10160,7 @@ var init_runtime_three = __esm(() => {weight: 8});QUANTIZED_SEMANTICS = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;+ QUANTIZED_SEMANTICS_EXCEPT_POSITION = /^(NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;});// src/asset-export.ts@@ -9892,6 +10260,10 @@ async function exportAssetGlb(record, options = {}) {throw new Error("A runtime export target requires the runtime profile");if (options.compression !== undefined && options.target !== "three")throw new Error("Runtime compression requires the three runtime target");+ if (options.maxLod !== undefined && options.target !== "three")+ throw new Error("Runtime maxLod requires the three runtime target");+ if (options.positionBits !== undefined && options.target !== "three")+ throw new Error("Runtime positionBits requires the three runtime target");const textures = options.textures;if (textures !== undefined && textures !== "manifest" && textures !== "external")throw new Error("Unknown runtime texture option");@@ -9945,7 +10317,9 @@ async function exportAssetGlb(record, options = {}) {if (options.target === "three") {const derived = await deriveThree(writeGlbJson(bytes, jsonEnd, json), {...options.ktx2Encoder ? { ktx2Encoder: options.ktx2Encoder } : {},- ...options.compression ? { compression: options.compression } : {}+ ...options.compression ? { compression: options.compression } : {},+ ...options.maxLod !== undefined ? { maxLod: options.maxLod } : {},+ ...options.positionBits !== undefined ? { positionBits: options.positionBits } : {}}, textures === "external" ? { gltfBasename: gltfName.slice(0, -".gltf".length) } : {});metadata.target = "three";metadata.delivery = derived.delivery;@@ -10153,7 +10527,7 @@ var init_export_root = __esm(() => {// src/evaluator/solid-diagnostic.tsfunction validSolidFailureDetails(value) {- if (!record5(value) || !keys(value, ["total", "truncated", "meshes"]) || !count2(value.total) || value.total < 1 || !Array.isArray(value.meshes) || value.meshes.length !== Math.min(value.total, MAX_SOLID_FAILURE_MESHES) || value.truncated !== value.total > value.meshes.length)+ if (!record5(value) || !keys(value, ["total", "truncated", "meshes"]) || !count3(value.total) || value.total < 1 || !Array.isArray(value.meshes) || value.meshes.length !== Math.min(value.total, MAX_SOLID_FAILURE_MESHES) || value.truncated !== value.total > value.meshes.length)return false;return value.meshes.every((mesh) => record5(mesh) && keys(mesh, ["childPath",@@ -10163,7 +10537,7 @@ function validSolidFailureDetails(value) {"boundaryEdges","nonManifoldEdges","orientationConflicts"- ]) && (mesh.childPath === null || Array.isArray(mesh.childPath) && mesh.childPath.length <= MAX_SOLID_FAILURE_PATH && mesh.childPath.every(count2)) && typeof mesh.closed === "boolean" && typeof mesh.manifold === "boolean" && typeof mesh.orientation === "string" && ["outward", "inward", "mixed"].includes(mesh.orientation) && count2(mesh.boundaryEdges) && count2(mesh.nonManifoldEdges) && count2(mesh.orientationConflicts));+ ]) && (mesh.childPath === null || Array.isArray(mesh.childPath) && mesh.childPath.length <= MAX_SOLID_FAILURE_PATH && mesh.childPath.every(count3)) && typeof mesh.closed === "boolean" && typeof mesh.manifold === "boolean" && typeof mesh.orientation === "string" && ["outward", "inward", "mixed"].includes(mesh.orientation) && count3(mesh.boundaryEdges) && count3(mesh.nonManifoldEdges) && count3(mesh.orientationConflicts));}function solidFailureAdvice(value) {if (!value || !validSolidFailureDetails(value))@@ -10174,7 +10548,7 @@ function solidFailureAdvice(value) {});return ` Required solid measurements (${value.meshes.length} of ${value.total} failing meshes): ${rows.join("; ")}. Child indices locate nodes in the authored build root before export; names are not forwarded. Read the retained source and check that node's geometryDiagnostics().solid.`;}-var MAX_SOLID_FAILURE_MESHES = 4, MAX_SOLID_FAILURE_PATH = 64, RequiredSolidError, record5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), keys = (value, names) => Object.keys(value).length === names.length && names.every((name) => Object.hasOwn(value, name)), count2 = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;+var MAX_SOLID_FAILURE_MESHES = 4, MAX_SOLID_FAILURE_PATH = 64, RequiredSolidError, record5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), keys = (value, names) => Object.keys(value).length === names.length && names.every((name) => Object.hasOwn(value, name)), count3 = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;var init_solid_diagnostic = __esm(() => {init_authoring_diagnostic();RequiredSolidError = class RequiredSolidError extends AuthoringDiagnosticError {@@ -17227,7 +17601,7 @@ function lodName(name) {pattern: `${name.slice(0, start)}${token}<n>${name.slice(end)}`};}-function fail5(message) {+function fail6(message) {throw new AuthoringDiagnosticError("LOD_SET", message);}function coverageProblem(values, levels) {@@ -17250,25 +17624,25 @@ function format(values) {}function defineLod(levels, options) {if (!Array.isArray(levels) || levels.length < 2 || levels.some((level) => level?.isObject3D !== true))- fail5(`defineLod: levels must list at least two tier nodes, LOD0 first, as in ${EXAMPLE}.`);+ fail6(`defineLod: levels must list at least two tier nodes, LOD0 first, as in ${EXAMPLE}.`);const first = lodName(levels[0].name);for (const [index, level] of levels.entries()) {const parsed = lodName(level.name);if (!parsed || parsed.level !== index || parsed.stem !== first?.stem) {const expected = first ? first.pattern.replace("<n>", String(index)) : `a name with the token LOD${index}`;- fail5(`defineLod: level ${index} is named ${JSON.stringify(level.name)}; name each tier with one stem and its level's token in order (${expected}).`);+ fail6(`defineLod: level ${index} is named ${JSON.stringify(level.name)}; name each tier with one stem and its level's token in order (${expected}).`);}}const parents = new Set(levels.map((level) => level.parent));if (!parents.has(null) && parents.size > 1)- fail5(`defineLod: the tiers of ${JSON.stringify(first.pattern)} must share the same parent; lower levels replace LOD0 in place.`);+ fail6(`defineLod: the tiers of ${JSON.stringify(first.pattern)} must share the same parent; lower levels replace LOD0 in place.`);const coverage = options?.screenCoverage;const problem = coverageProblem(coverage, levels.length);if (problem)- fail5(`defineLod: ${problem}; got ${format(coverage)}. For example ${EXAMPLE}.`);+ fail6(`defineLod: ${problem}; got ${format(coverage)}. For example ${EXAMPLE}.`);const impostor = options?.impostor;if (impostor !== undefined && typeof impostor !== "boolean")- fail5(`defineLod: impostor must be true or false; got ${format(impostor)}.`);+ fail6(`defineLod: impostor must be true or false; got ${format(impostor)}.`);const declaration = {screenCoverage: [...coverage],...impostor ? { impostor: true } : {}@@ -17305,18 +17679,18 @@ function collectLodSets(root) {const ordered = [...members].sort((a, b) => a.name.level - b.name.level);const found = ordered.map((member) => member.name.level);if (found.some((level, index) => level !== index))- fail5(`LOD set ${where} has levels ${found.join(", ")}; a set needs LOD0 and consecutive levels with no repeats.`);+ fail6(`LOD set ${where} has levels ${found.join(", ")}; a set needs LOD0 and consecutive levels with no repeats.`);const levels = ordered.map((member) => member.node);const declaration = declarationOf(levels[0]);const names = levels.map((level) => level.name).join(", ");if (declaration === undefined)- fail5(`LOD set ${where} (${names}) has no screen coverage. Declare it once: defineLod([${names}], { screenCoverage: [...] }) with one value per level, from 0 to 1, strictly decreasing.`);+ fail6(`LOD set ${where} (${names}) has no screen coverage. Declare it once: defineLod([${names}], { screenCoverage: [...] }) with one value per level, from 0 to 1, strictly decreasing.`);const coverage = declaration?.screenCoverage;if (Array.isArray(coverage) && coverage.length !== levels.length)- fail5(`LOD set ${where} declares ${coverage.length} levels but has ${levels.length} (${names}); call defineLod again with every tier.`);+ fail6(`LOD set ${where} declares ${coverage.length} levels but has ${levels.length} (${names}); call defineLod again with every tier.`);const problem = coverageProblem(coverage, levels.length);if (problem)- fail5(`LOD set ${where}: ${problem}.`);+ fail6(`LOD set ${where}: ${problem}.`);declaredBases.add(levels[0]);sets.push({ parent, levels, screenCoverage: [...coverage] });}@@ -17330,7 +17704,7 @@ function collectLodSets(root) {return;const coverage = declaration?.screenCoverage;const count = Array.isArray(coverage) ? coverage.length : "its";- fail5(`${JSON.stringify(node.name)} declares ${count} levels with defineLod but is not the LOD0 of a set of sibling tiers; attach every tier under the same parent (sets cannot nest inside another tier).`);+ fail6(`${JSON.stringify(node.name)} declares ${count} levels with defineLod but is not the LOD0 of a set of sibling tiers; attach every tier under the same parent (sets cannot nest inside another tier).`);});return sets;}@@ -17603,10 +17977,10 @@ var init_reference_comparison = __esm(() => {function markOpenShell(part, reason) {const node = part;if (!node || typeof node !== "object" || node.isObject3D !== true)- fail6("part must be a scene node, such as the mesh createPart returned or a group.");+ fail7("part must be a scene node, such as the mesh createPart returned or a group.");const kept = validReason(reason);if (kept === undefined)- fail6(`reason must be a non-empty string of at most ${MAX_OPEN_SHELL_REASON} characters saying why the shell is open.`);+ fail7(`reason must be a non-empty string of at most ${MAX_OPEN_SHELL_REASON} characters saying why the shell is open.`);const target = node;if (!target.userData || typeof target.userData !== "object")target.userData = {};@@ -17639,10 +18013,10 @@ function openShellExtras(node) {return {};const reason = markReason(value);if (reason === undefined)- fail6(`userData.${OPEN_SHELL_KEY} on ${JSON.stringify(target?.name || "(unnamed node)")} is not a mark this helper wrote; the engine owns that key, so set it only through markOpenShell.`);+ fail7(`userData.${OPEN_SHELL_KEY} on ${JSON.stringify(target?.name || "(unnamed node)")} is not a mark this helper wrote; the engine owns that key, so set it only through markOpenShell.`);return { [OPEN_SHELL_KEY]: { schemaVersion: 1, reason } };}-var OPEN_SHELL_KEY = "kilnOpenShell", MAX_OPEN_SHELL_REASON = 200, EXAMPLE2 = 'markOpenShell(rail, "C-channel closed by the end plates")', fail6 = (detail) => {+var OPEN_SHELL_KEY = "kilnOpenShell", MAX_OPEN_SHELL_REASON = 200, EXAMPLE2 = 'markOpenShell(rail, "C-channel closed by the end plates")', fail7 = (detail) => {throw new AuthoringDiagnosticError("OPEN_SHELL", `markOpenShell(part, reason): ${detail} For example ${EXAMPLE2}.`);}, validReason = (reason) => {if (typeof reason !== "string")@@ -20721,7 +21095,7 @@ function createAssetRequirementsV1(input = {}) {...input});}-var text2, positive2, nonnegative, count3, names, marker, supportParts, roof, structure, effects, requirements, AssetRequirementsV1Schema;+var text2, positive2, nonnegative, count4, names, marker, supportParts, roof, structure, effects, requirements, AssetRequirementsV1Schema;var init_requirements = __esm(() => {init_asset();init_breadth();@@ -20729,7 +21103,7 @@ var init_requirements = __esm(() => {text2 = z6.string().refine((value) => value.trim().length > 0, { message: "Must be non-empty." });positive2 = z6.number().finite().positive();nonnegative = z6.number().finite().nonnegative();- count3 = z6.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);+ count4 = z6.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);names = z6.array(text2).refine((values) => new Set(values).size === values.length, {message: "Values must be unique."});@@ -20748,7 +21122,7 @@ var init_requirements = __esm(() => {structure = z6.strictObject({subtype: text2.optional(),enterable: z6.boolean().optional(),- storeyCount: count3.min(1).optional(),+ storeyCount: count4.min(1).optional(),interiorMode: z6.enum(ARCHITECTURE_INTERIOR_MODES).optional(),roofMode: z6.enum(ARCHITECTURE_ROOF_MODES).optional(),footprint: z6.strictObject({ spanX: positive2, spanZ: positive2, units: z6.literal("m") }).optional(),@@ -20796,8 +21170,8 @@ var init_requirements = __esm(() => {supportAssemblies: names.optional(),propulsionAssemblies: names.optional(),frontFrame: z6.literal("+X").optional(),- wheelCount: count3.optional(),- axleCount: count3.optional(),+ wheelCount: count4.optional(),+ axleCount: count4.optional(),steering: z6.enum(VEHICLE_STEERING_ARRANGEMENTS).optional(),supportPolicy: z6.enum(VEHICLE_SUPPORT_POLICIES).optional(),animationAssemblies: names.optional()@@ -22241,88 +22615,6 @@ function inspectSkinIntegrity(root) {var MAX_FINDINGS = 64, WEIGHT_TOLERANCE = 0.00001;var init_skin_integrity = () => {};-// src/lod-export.ts-import { PropertyType as PropertyType4 } from "@gltf-transform/core";-function applyLodChains(root, sets, doc) {- if (sets.length === 0)- return;- const exported = writtenNodeResolver(root, doc, "LOD export");- const chains = sets.map((set) => ({- set,- parent: exported(set.parent),- levels: set.levels.map(exported)- }));- const extension = doc.createExtension(MSFTLod);- for (const { set, parent, levels } of chains) {- const [base, ...lower] = levels;- const lod = extension.createLod();- for (const level of lower) {- parent.removeChild(level);- lod.addLevel(level);- }- base.setExtension(MSFT_LOD, lod);- base.setExtras({ ...base.getExtras(), [MSFT_SCREENCOVERAGE]: [...set.screenCoverage] });- }-}-function occurrence(siblings, index, name) {- let count = 0;- for (let i = 0;i < index; i++)- if (siblings[i].getName() === name)- count++;- return count;-}-function screenCoverageOf(node) {- const value = node.getExtras()[MSFT_SCREENCOVERAGE];- return Array.isArray(value) && value.every((item) => typeof item === "number") ? [...value] : undefined;-}-function listLodChainNodes(doc) {- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];- if (!scene)- return [];- const chains = [];- const visit = (siblings, parentPath) => {- siblings.forEach((node, index) => {- const at = (name) => `${parentPath}${segment4(name, occurrence(siblings, index, name))}`;- const path = at(node.getName());- const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType4.NODE);- if (lower.length > 0)- chains.push({- levels: [node, ...lower],- paths: [path, ...lower.map((level) => at(level.getName()))]- });- visit(node.listChildren(), path);- });- };- visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));- return chains;-}-function isImpostorLevel(node) {- const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];- return roles.includes(KILN_SEMANTIC_ROLES.lodImpostor);-}-function summarizeLodChains(doc) {- return listLodChainNodes(doc).map(({ levels, paths }) => {- const screenCoverage = screenCoverageOf(levels[0]);- return {- path: paths[0],- ...screenCoverage ? { screenCoverage } : {},- levels: levels.map((level, number) => ({- level: number,- name: level.getName(),- path: paths[number],- triangles: drawnNodeTriangles(level),- ...number > 0 && isImpostorLevel(level) ? { impostor: true } : {}- }))- };- });-}-var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;-var init_lod_export = __esm(() => {- init_semantic();- init_gltf_io();- init_metrics();-});-// src/rig-export.tsfunction rigExtrasForExport(node) {const extras = {};@@ -24648,25 +24940,25 @@ var init_assembly = __esm(() => {// src/palette-check.tsfunction hex(value, label) {if (typeof value !== "string" || !/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(value))- fail7(`${label} must be a hex colour such as '#6b6f73', got ${JSON.stringify(value)}.`);+ fail8(`${label} must be a hex colour such as '#6b6f73', got ${JSON.stringify(value)}.`);const digits = value.replace("#", "").toLowerCase();return `#${digits.length === 3 ? [...digits].map((d) => d + d).join("") : digits}`;}function normalizePalette(colors, opts) {if (!Array.isArray(colors) || colors.length === 0 || colors.length > PALETTE_MAX_COLORS)- fail7(`colors must be an array of 1..${PALETTE_MAX_COLORS} hex colours.`);+ fail8(`colors must be an array of 1..${PALETTE_MAX_COLORS} hex colours.`);const entries = colors.map((value, i) => hex(value, `colors[${i}]`));let threshold = PALETTE_DEFAULT_THRESHOLD;if (opts !== undefined) {if (!opts || typeof opts !== "object" || Array.isArray(opts))- fail7("opts must be { threshold? }.");+ fail8("opts must be { threshold? }.");for (const key of Object.keys(opts))if (key !== "threshold")- fail7(`unknown option ${JSON.stringify(key)}.`);+ fail8(`unknown option ${JSON.stringify(key)}.`);const t = opts.threshold;if (t !== undefined) {if (typeof t !== "number" || !Number.isFinite(t) || t <= 0 || t > 100)- fail7(`threshold must be a delta E in (0, 100], got ${String(t)}.`);+ fail8(`threshold must be a delta E in (0, 100], got ${String(t)}.`);threshold = t;}}@@ -24676,7 +24968,7 @@ function definePalette(colors, opts, target) {const declaration = normalizePalette(colors, opts);if (target !== undefined) {if (target?.isObject3D !== true)- fail7("target must be a scene node, normally the root.");+ fail8("target must be a scene node, normally the root.");target.userData[KILN_PALETTE_KEY] = structuredClone(declaration);}return declaration;@@ -24752,7 +25044,7 @@ function evaluatePalette(declaration, doc) {offPalette};}-var KILN_PALETTE_KEY = "kilnPaletteV1", PALETTE_DEFAULT_THRESHOLD = 10, PALETTE_MAX_COLORS = 64, fail7 = (detail) => {+var KILN_PALETTE_KEY = "kilnPaletteV1", PALETTE_DEFAULT_THRESHOLD = 10, PALETTE_MAX_COLORS = 64, fail8 = (detail) => {throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `definePalette(colors, opts?): ${detail}`);}, srgbToLinear = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4, linearToSrgb = (c) => c <= 0.0031308 ? c * 12.92 : 1.055 * Math.max(0, c) ** (1 / 2.4) - 0.055, hexToLinear = (value) => {const n = Number.parseInt(value.slice(1), 16);@@ -24764,95 +25056,6 @@ var init_palette_check = __esm(() => {init_metrics();});-// src/budget.ts-function normalizeBudget(spec) {- if (!spec || typeof spec !== "object" || Array.isArray(spec))- fail8("spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.");- const value = spec;- for (const key of Object.keys(value))- if (key !== "triangles" && key !== "draws" && key !== "schemaVersion")- fail8(`unknown field ${JSON.stringify(key)}.`);- const triangles = {};- if (typeof value.triangles === "number")- triangles.LOD0 = count4("triangles", value.triangles);- else if (value.triangles && typeof value.triangles === "object" && !Array.isArray(value.triangles)) {- const entries = Object.entries(value.triangles);- if (entries.length === 0)- fail8("triangles needs at least one tier.");- for (const [tier, limit] of entries) {- if (!/^LOD(0|[1-9][0-9]?)$/.test(tier))- fail8(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);- triangles[tier] = count4(`triangles.${tier}`, limit);- }- } else- fail8("triangles must be a positive integer or a record of LOD tiers.");- const ordered = Object.fromEntries(Object.entries(triangles).sort(([a], [b]) => Number(a.slice(3)) - Number(b.slice(3))));- return {- schemaVersion: 1,- triangles: ordered,- ...value.draws === undefined ? {} : { draws: count4("draws", value.draws) }- };-}-function defineBudget(spec, target) {- const declaration = normalizeBudget(spec);- if (target !== undefined) {- if (target?.isObject3D !== true)- fail8("target must be a scene node, normally the root.");- target.userData[KILN_BUDGET_KEY] = structuredClone(declaration);- }- return declaration;-}-function readBudgetDeclaration(value) {- if (value === undefined)- return;- try {- const declaration = normalizeBudget(value);- return value.schemaVersion === 1 ? declaration : undefined;- } catch {- return;- }-}-function evaluateBudget(declaration, measuredLod0, chains) {- const outside = measuredLod0.triangles - chains.reduce((sum, chain) => sum + chain.levels[0].triangles, 0);- const tierTriangles = (level) => outside + chains.reduce((sum, chain) => sum + chain.levels[Math.min(level, chain.levels.length - 1)].triangles, 0);- const tiers = Object.entries(declaration.triangles).map(([tier, limit]) => {- const level = Number(tier.slice(3));- const triangles = level === 0 ? measuredLod0.triangles : tierTriangles(level);- const drawsDeclared = level === 0 ? declaration.draws : undefined;- const pass = triangles <= limit && (drawsDeclared === undefined || measuredLod0.draws <= drawsDeclared);- return {- tier,- declared: {- triangles: limit,- ...drawsDeclared === undefined ? {} : { draws: drawsDeclared }- },- measured: {- triangles,- ...drawsDeclared === undefined ? {} : { draws: measuredLod0.draws }- },- status: pass ? "pass" : "fail"- };- });- if (declaration.draws !== undefined && declaration.triangles.LOD0 === undefined)- tiers.unshift({- tier: "LOD0",- declared: { draws: declaration.draws },- measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws },- status: measuredLod0.draws <= declaration.draws ? "pass" : "fail"- });- return { status: tiers.every((tier) => tier.status === "pass") ? "pass" : "fail", tiers };-}-var KILN_BUDGET_KEY = "kilnBudgetV1", fail8 = (detail) => {- throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `defineBudget(spec): ${detail}`);-}, count4 = (label, value) => {- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)- fail8(`${label} must be a positive integer, got ${String(value)}.`);- return value;-};-var init_budget = __esm(() => {- init_authoring_diagnostic();-});-// src/animation-cubic.tsimport * as THREE34 from "three";function useCubicSpline(track) {@@ -37980,7 +38183,7 @@ var init_character_capture = __esm(() => {import * as THREE55 from "three";import { Document, Logger as Logger2 } from "@gltf-transform/core";import { KHRMaterialsEmissiveStrength } from "@gltf-transform/extensions";-import { dedup as dedup2, instance, palette, weld as weld2, prune, mergeDocuments } from "@gltf-transform/functions";+import { dedup as dedup2, instance, palette, weld as weld2, prune as prune2, mergeDocuments } from "@gltf-transform/functions";function applySurfaceBakeExtras(root, doc) {const baked = [];root.traverse((node) => {@@ -38046,7 +38249,12 @@ async function inspectGlbIntegration(bytes, opts = {}) {const delivery = inspectDelivery(doc);const vertexAttributes = summarizeVertexAttributes(doc);const budgetDeclaration = readBudgetDeclaration(scene.getExtras()[KILN_BUDGET_KEY]);- const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, { triangles: metrics.triangles, draws: metrics.drawCalls }, levelsOfDetail) : undefined;+ const instancedDraws = budgetDeclaration?.draws === undefined ? undefined : await (await Promise.resolve().then(() => (init_runtime_three(), exports_runtime_three))).instancedDrawEstimate(doc);+ const budget = budgetDeclaration ? evaluateBudget(budgetDeclaration, {+ triangles: metrics.triangles,+ draws: metrics.drawCalls,+ ...instancedDraws === undefined ? {} : { instancedDraws }+ }, levelsOfDetail) : undefined;const paletteDeclaration = readPaletteDeclaration(scene.getExtras()[KILN_PALETTE_KEY]);const palette = paletteDeclaration ? evaluatePalette(paletteDeclaration, doc) : undefined;return {@@ -38639,7 +38847,7 @@ async function consolidateMaterials(doc, mode, keep = []) {steps.push(rigidMerge({ keep }, (summary) => {merge = summary;}));- steps.push(weld2(), prune({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));+ steps.push(weld2(), prune2({ keepLeaves: true, keepExtras: true, keepSolidTextures: true }));await doc.transform(...steps);const after = collectGlbMetrics(doc);return {@@ -41112,7 +41320,7 @@ __export(exports_draw_diagnostics, {inspectDrawDiagnostics: () => inspectDrawDiagnostics});import { Primitive as Primitive3 } from "@gltf-transform/core";-import { cloneDocument } from "@gltf-transform/functions";+import { cloneDocument as cloneDocument2 } from "@gltf-transform/functions";import * as THREE57 from "three";function withinLimits(doc) {const root = doc.getRoot();@@ -41268,7 +41476,7 @@ function analyzeDrawDiagnostics(doc, options = {}) {return skipped("input-limit");const keep = options.keep ?? [];const before = collect2(doc, keep);- const copy = cloneDocument(doc);+ const copy = cloneDocument2(doc);const merge = mergeRigidGroups(copy, { keep });const after = collect2(copy, keep);const all = [...before.anchors.values()].map((anchor) => ({diff --git a/dist/viewer/app.js b/dist/viewer/app.jsindex bbdc0828..babb586b 100644--- a/dist/viewer/app.js+++ b/dist/viewer/app.js@@ -1,12 +1,12 @@-var QR=Object.create;var{getPrototypeOf:eI,defineProperty:Of,getOwnPropertyNames:tI}=Object;var Nb=Object.prototype.hasOwnProperty;function nI(e){return this[e]}var iI,rI,kf=(e,t,n)=>{var i=e!=null&&typeof e==="object";if(i){var r=t?iI??=new WeakMap:rI??=new WeakMap,s=r.get(e);if(s)return s}n=e!=null?QR(eI(e)):{};let a=t||!e||!e.__esModule||!Nb.call(e,"default")?Of(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let o of tI(e))if(!Nb.call(a,o))Of(a,o,{get:nI.bind(e,o),enumerable:!0})}if(i)r.set(e,a);return a};var Jr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var sI=(e)=>e;function aI(e,t){this[e]=sI.bind(null,t)}var Pb=(e,t)=>{for(var n in t)Of(e,n,{get:t[n],enumerable:!0,configurable:!0,set:aI.bind(t,n)})};var mt=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(i){n=[i]}if(n)throw n[0];return t};var ir;var Ec=mt(()=>{ir=["albedo","emissive","normal","roughness","metalness","metallicRoughness","occlusion"]});function OC(e){if(e==="PORTABLE_MATERIAL_V3_CONTRACT")return'compilePortableMaterialSpecV3 requires schemaVersion 3, model pbrMetallicRoughness, typed V3 procedural or injected resource references, and complete minFilter/magFilter/wrapS/wrapT samplers. Match texture usage to its slot and split work exceeding the material budget. Resource bindings need a host with verified-byte admission. V2 remains available unchanged. Shader code, paths, raw textures and V3 height derivation are unsupported. Read kiln_discover ids ["compilePortableMaterialSpecV3"] for the exact contract.';if(e==="TEXTURE_ATLAS_CONTRACT")return'textureAtlas requires bounded named integer content rectangles with nonoverlapping gutter allocations, matching source crops and usage, and explicit portable sampling. Sources are V3 recipes or exact host-injected library map pins. Split atlases exceeding aggregate work or allocation budgets. remapUVToAtlas requires finite unit UV0, a named content region, inputOrigin and mapping mode; it preserves topology and does not unwrap or tile a region. Read kiln_discover ids ["textureAtlas", "remapUVToAtlas"] for the exact contracts.';if(e==="PROCEDURAL_TEXTURE_V3_CONTRACT")return'proceduralTexture schemaVersion 3 requires bounded JSON: width/height 4..1024, byte RGBA, integer pixel shapes and at most 64 operations. Palette/dither supports only albedo/emissive; seeded stamps accept every usage. Work includes polygon edges and periodic copies. Read kiln_discover ids ["proceduralTexture"] for the V3 contract; keep schemaVersion 2 for existing opaque patterns.';if(e==="BONE_CHAIN_ARGUMENT")return'createBoneChain requires 1..1024 valid local joint descriptors with unique roles and animation-safe names across the parent hierarchy. Use normalized perpendicular forward/bend axes and finite rest transforms; an explicit parentRole must match the declared parent. Read the retained source and kiln_discover ids ["createBoneChain"] for the exact contract.';if(e==="SKIN_BINDING_ARGUMENT")return'createSkinnedPart requires four valid bone indices and finite nonnegative weights per vertex, summing to one unless normalizeWeights:true is explicit. Zero sums are rejected. Assemble distinct named Bones and the parent in one rest-pose hierarchy before binding. Use unbound geometry within the documented budgets and finite invertible transforms. Read the retained source and kiln_discover ids ["createSkinnedPart"] for the exact contract; the Three exporter is required for skin delivery.';if(e==="EXPORT_MATERIAL_SIDE_UNSUPPORTED")return"EXPORT_MATERIAL_SIDE_UNSUPPORTED: A used material has BackSide, which glTF cannot encode directly. Author inward-facing triangles with FrontSide, or choose DoubleSide when both faces are intended. Neither adds missing geometry. Read the retained program with kiln_source query BackSide to locate the material; source names and exception text do not cross the evaluator boundary.";if(e==="UNINITIALIZED_BINDING")return"A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.";if(e==="LOD_SET")return'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].';if(e==="OPEN_SHELL")return'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].';if(e==="DELIVERY_CONTRACT")return'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws? }) takes positive integers; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].';if(e==="REQUIRE_SOLID")return'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].';if(e==="BUILD_RESULT")return'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.';if(e==="MATERIAL_RECIPE_OVERRIDE")return'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.';if(e==="PROGRAM_TYPE_ERROR")return"The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.";if(e==="PROGRAM_RANGE_ERROR")return"The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.";if(e==="MESH_DATA_NONFINITE")return"meshGeo positions, normals, UVs and tangents must contain finite numbers representable in Float32. Check missing XYZ components, undefined values, division by zero and overflowing calculations before constructing the arrays. Do not replace invalid values blindly with zero; correct the source calculation. Call kiln_discover for the exact meshGeo data contract.";if(e==="PORTABLE_COLOR_ARGUMENT")return"compilePortableMaterialSpecV2 baseColor and emissive must be numeric color integers from 0x000000 to 0xffffff, for example baseColor: 0x8a867c. CSS strings and materialRecipe hex-string overrides use different contracts. Omit these fields for their defaults, or call kiln_discover for the exact helper contract.";if(e==="MATERIAL_RECIPE_TEXTURE_BINDING")return"materialRecipe textureResources maps portable slots to approved resource ID strings. Slots are baseColor, normal, metallicRoughness, emissive and occlusion. albedo is a pbrMaterial field, not a recipe slot. Use kiln_discover to check each resource allowedSlots and recipeIds before binding it; no slot or resource substitution is applied.";if(e==="PORTABLE_TEXTURE_REFERENCE")return'compilePortableMaterialSpecV2 textures require typed references: { kind: "resource", resourceId: "kiln.texture..." } for an approved resource, or { kind: "procedural", spec: { schemaVersion: 2, ... } } for a procedural texture. Bare resource ID strings are invalid here. Use portable slots such as baseColor and check the exact helper/resource contracts with kiln_discover.';if(e==="TAPER_CONE_AXIS")return'taperConeGeo(radiusBottom, radiusTop, height, axis, segments): the fourth argument is axis, "x", "y" or "z" (default "y"). Segment count is the fifth argument, for example taperConeGeo(0.03, 0.02, 0.01, "x", 12). Call kiln_discover for the full contract.';if(e==="PROCEDURAL_TEXTURE_BLEND")return'proceduralTexture layer blend must be normal, multiply, screen, or overlay. Omit blend for normal compositing. Call kiln_discover with ids ["proceduralTexture"] for the supported layer fields.';if(e==="PART_NAME_ARGUMENT")return"createPart(name, geometry, material, options?): the first argument is a string name. Put the parent Object3D in the fourth argument as { parent: root }.";if(e==="PART_GEOMETRY_ARGUMENT")return"createPart(name, geometry, material, options?): the second argument must be a BufferGeometry. Call geometry helpers, for example boxGeo(1, 1, 1), instead of passing the function. For async helpers such as roundedBoxGeo, extrudeProfile and revolveProfile, await the result inside async build() before passing it to createPart. Call kiln_discover for the exact return contract.";if(e==="PART_MATERIAL_ARGUMENT")return"createPart(name, geometry, material, options?): the third argument must be a Three.js material. Wrap a color with gameMaterial(0x808080); a number or settings object alone is not a material. Call kiln_discover for the chosen material helper contract.";if(e==="SOLID_FLOAT32_COLLAPSE")return"Solid output cannot retain valid faces at Float32 precision. Simplify subprecision features or recenter local geometry; review coincident cut boundaries. Smoothing or replacing normals does not repair collapsed triangles. Kiln did not export a partially repaired solid.";if(e==="PROFILE_BEVEL_COLLAPSE")return"extrudeProfile or revolveProfile: bevel is too large for this profile; erosion leaves nothing. Reduce bevel below half the narrowest section width, set bevel to 0, or widen the profile. Dimensions and bevel use the same asset units.";if(e==="TUBE_RADIUS")return"curveToMesh and pipeAlongPath require an explicit positive finite radius representable in Float32, in asset units. A missing or undefined radius is invalid; check the referenced dimension. Radius is half the tube diameter.";if(e==="MATERIAL_ALPHA_MODE")return'pbrMaterial and portable material specs require lowercase alphaMode: "opaque", "mask", or "blend". Omit it for opaque. Exported glTF uses uppercase mode names; those are not authoring input values.';if(e==="MATERIAL_COLOR_ARGUMENT")return"gameMaterial, basicMaterial, glassMaterial and lambertMaterial take a color first: a hex number or CSS string. Settings belong in the second argument, for example gameMaterial(0x9a9a96, { roughness: 0.4, metalness: 0.8 }). pbrMaterial uses a different object-form contract; call kiln_discover for its texture and material fields.";if(e==="MATERIAL_PACKED_CHANNELS")return'pbrMaterial requires one packed texture with G=roughness and B=metalness. Generate or load it for usage "metallicRoughness" and pass metallicRoughness, or pass the same packed texture in both roughness and metalness. Do not combine those forms or pass a texture in only one scalar slot. Plain roughness and metalness values are 0..1 numbers. Call kiln_discover for the exact texture contract.';if(e==="REMOVED_HELPER")return"Generated source references a retired Kiln global. Call kiln_validate for name-specific migration guidance, then kiln_discover for the replacement contract. No compatibility aliases are provided.";if(e==="UNBOUND_VARIABLE")return"Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.";if(e==="ROUNDED_BOX_RADIUS")return"roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.";if(e==="GEAR_RADII_ORDER")return"gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.";if(e==="PROCEDURAL_TEXTURE_UNKNOWN_KEY")return'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.';if(e==="PROCEDURAL_TEXTURE_USAGE")return'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].';if(e==="MATERIAL_FRACTION_RANGE")return"Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.";if(e==="PROFILE_HOLES_UNSUPPORTED")return"loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.";if(e==="PROFILE_CORRESPONDENCE_COLLAPSE")return"loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.";return e==="PARAMETRIC_PERIODIC_ENDPOINT"?"Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.":""}var Xa;var vu=mt(()=>{Xa=class Xa extends Error{diagnostic;constructor(e,t=OC(e)){super(t);this.diagnostic=e;this.name="AuthoringDiagnosticError"}}});function wu(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw new yt(`${t} must be a plain JSON object.`);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new yt(`${t} must be a plain JSON object with no custom prototype.`);for(let i of Reflect.ownKeys(e)){if(typeof i!=="string")throw new yt(`${t} must not contain symbol keys.`);if(kC.has(i))throw new yt(`${t} contains forbidden key ${JSON.stringify(i)}.`);if(!Object.prototype.propertyIsEnumerable.call(e,i))throw new yt(`${t}.${i} must be an enumerable JSON field.`);let r=Object.getOwnPropertyDescriptor(e,i);if(!r||!("value"in r))throw new yt(`${t}.${i} must be a plain JSON data field.`)}return e}function DC(e,t){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)throw new yt(`${t} must be a plain JSON array.`);for(let n of Reflect.ownKeys(e)){if(typeof n!=="string")throw new yt(`${t} must not contain symbol keys.`);if(n==="length")continue;if(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=e.length)throw new yt(`${t} has non-index JSON array key ${JSON.stringify(n)}.`)}for(let n=0;n<e.length;n++)if(!Object.hasOwn(e,n))throw new yt(`${t} must be a dense JSON array (missing index ${n}).`);return e}function ts(e,t,n){let i=new Set(t);for(let r of Object.keys(e))if(!i.has(r))throw new yt(`${n} has unknown key ${JSON.stringify(r)}.`,"PROCEDURAL_TEXTURE_UNKNOWN_KEY")}function Ni(e,t,n){if(typeof e!=="number"||!Number.isInteger(e)||e<0||e>16777215)throw new yt(`${t} must be a color integer between 0x000000 and 0xffffff, got ${JSON.stringify(e)}.`,n);return e}function la(e,t,n,i,r){if(e===void 0)return n;if(typeof e!=="number"||!Number.isInteger(e)||e<i||e>r)throw new yt(`${t} must be a whole number between ${i} and ${r}, got ${JSON.stringify(e)}.`);return e}function kv(e,t,n,i,r,s){if(e===void 0)return n;if(typeof e!=="number"||!Number.isFinite(e)||e<i||e>r)throw new yt(`${t} must be a finite number between ${i} and ${r}, got ${JSON.stringify(e)}.`,s);return e}function Gh(e,t,n){return kv(e,t,n,0,1,"MATERIAL_FRACTION_RANGE")}function LC(e,t){if(e===void 0)return;let n=typeof e==="string"&&[...e].some((i)=>{let r=i.charCodeAt(0);return r<32||r===127});if(typeof e!=="string"||e.length===0||e.length>Cv||n)throw new yt(`${t} must be 1..${Cv} visible characters.`);return e}function FC(e,t,n){if(e===void 0)return n;if(!ir.includes(e))throw new yt(`${t} must be one of ${ir.join(", ")}, got ${JSON.stringify(e)}.`,"PROCEDURAL_TEXTURE_USAGE");return e}function Ov(e,t){let i=(kv(e,t,0,-36000,36000)%360+360)%360;return Object.is(i,-0)?0:i}function UC(e,t){let n=e.blend??"normal";if(!Pv.includes(n))throw new yt(`${t}.blend ${JSON.stringify(n)} is not one of ${Pv.join(", ")}.`,"PROCEDURAL_TEXTURE_BLEND");return n}function BC(e,t){let n=`proceduralTexture.layers[${t}]`,i=wu(e,n),r=i.op;if(!Nv.includes(r))throw new yt(`${n}.op ${JSON.stringify(r)} is not one of ${Nv.join(", ")}.`);let s=UC(i,n),a=Gh(i.opacity,`${n}.opacity`,1),o={blend:t===0?"normal":s,opacity:t===0?1:a};switch(r){case"solid":return ts(i,["op","color","blend","opacity"],n),{op:r,color:Ni(i.color,`${n}.color`),...o};case"checker":return ts(i,["op","colorA","colorB","squares","blend","opacity"],n),{op:r,colorA:Ni(i.colorA,`${n}.colorA`),colorB:Ni(i.colorB,`${n}.colorB`),squares:la(i.squares,`${n}.squares`,8,1,ua),...o};case"stripes":return ts(i,["op","colorA","colorB","count","angleDeg","blend","opacity"],n),{op:r,colorA:Ni(i.colorA,`${n}.colorA`),colorB:Ni(i.colorB,`${n}.colorB`),count:la(i.count,`${n}.count`,8,1,ua),angleDeg:Ov(i.angleDeg,`${n}.angleDeg`),...o};case"gradient":return ts(i,["op","from","to","angleDeg","blend","opacity"],n),{op:r,from:Ni(i.from,`${n}.from`),to:Ni(i.to,`${n}.to`),angleDeg:Ov(i.angleDeg,`${n}.angleDeg`),...o};case"bricks":return ts(i,["op","brick","mortar","rows","cols","mortarWidth","stagger","blend","opacity"],n),{op:r,brick:Ni(i.brick,`${n}.brick`),mortar:Ni(i.mortar,`${n}.mortar`),rows:la(i.rows,`${n}.rows`,8,1,ua),cols:la(i.cols,`${n}.cols`,4,1,ua),mortarWidth:Gh(i.mortarWidth,`${n}.mortarWidth`,0.06),stagger:Gh(i.stagger,`${n}.stagger`,0.5),...o};case"noise":return ts(i,["op","colorA","colorB","scale","octaves","seed","blend","opacity"],n),{op:r,colorA:Ni(i.colorA,`${n}.colorA`),colorB:Ni(i.colorB,`${n}.colorB`),scale:la(i.scale,`${n}.scale`,8,1,ua),octaves:la(i.octaves,`${n}.octaves`,3,1,$h),seed:la(i.seed,`${n}.seed`,0,-2147483648,2147483647),...o};default:throw new yt(`${n}.op is unsupported.`)}}function zC(e){let t=wu(e,"proceduralTexture");if(ts(t,["schemaVersion","size","usage","name","layers"],"proceduralTexture"),t.schemaVersion!==void 0&&t.schemaVersion!==1)throw new yt(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(t.schemaVersion)}.`);return{schemaVersion:2,...t.size!==void 0?{size:t.size}:{},...t.usage!==void 0?{usage:t.usage}:{},...t.name!==void 0?{name:t.name}:{},layers:t.layers}}function Tc(e){let t=wu(e,"proceduralTexture"),n=t.schemaVersion===void 0||t.schemaVersion===1?wu(zC(t),"proceduralTexture"):t;if(ts(n,["schemaVersion","size","usage","name","layers"],"proceduralTexture"),n.schemaVersion!==2)throw new yt(`proceduralTexture.schemaVersion must be 2, got ${JSON.stringify(n.schemaVersion)}.`);let i=n.size??256;if(typeof i!=="number"||!Number.isInteger(i)||i<Tu||i>Eu||(i&i-1)!==0)throw new yt(`proceduralTexture.size must be a power of two between ${Tu} and ${Eu}, got ${JSON.stringify(n.size)}.`);let r=n.layers;if(!Array.isArray(r)||r.length===0)throw new yt("proceduralTexture.layers must be a non-empty array — the bottom layer is the base pattern.");let s=DC(r,"proceduralTexture.layers");if(s.length>Au)throw new yt(`proceduralTexture: ${s.length} layers exceeds the maximum of ${Au}.`);let a=LC(n.name,"proceduralTexture.name");return{schemaVersion:2,size:i,usage:FC(n.usage,"proceduralTexture.usage","albedo"),...a!==void 0?{name:a}:{},layers:s.map(BC)}}function qa(e){let t=new TextEncoder().encode(e),n=t.length*8,i=Math.ceil((t.length+9)/64)*64,r=new Uint8Array(i);r.set(t),r[t.length]=128;let s=new DataView(r.buffer);s.setUint32(i-8,Math.floor(n/4294967296),!1),s.setUint32(i-4,n>>>0,!1);let a=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64);for(let c=0;c<r.length;c+=64){for(let x=0;x<16;x++)o[x]=s.getUint32(c+x*4,!1);for(let x=16;x<64;x++){let _=o[x-15],y=o[x-2],v=rr(_,7)^rr(_,18)^_>>>3,T=rr(y,17)^rr(y,19)^y>>>10;o[x]=o[x-16]+v+o[x-7]+T>>>0}let[l,u,d,f,h,b,m,g]=a;for(let x=0;x<64;x++){let _=rr(h,6)^rr(h,11)^rr(h,25),y=h&b^~h&m,v=g+_+y+VC[x]+o[x]>>>0,T=rr(l,2)^rr(l,13)^rr(l,22),A=l&u^l&d^u&d,E=T+A>>>0;g=m,m=b,b=h,h=f+v>>>0,f=d,d=u,u=l,l=v+E>>>0}let p=[l,u,d,f,h,b,m,g];for(let x=0;x<8;x++)a[x]=a[x]+p[x]>>>0}return[...a].map((c)=>c.toString(16).padStart(8,"0")).join("")}var Eu=1024,Tu=4,Au=8,$h=6,Cv=80,ua=256,yt,Nv,Pv,kC,VC,rr=(e,t)=>e>>>t|e<<32-t;var Ja=mt(()=>{Ec();vu();yt=class yt extends Xa{constructor(e,t){super(t,e);this.name="ProceduralTextureError"}};Nv=["solid","checker","stripes","gradient","bricks","noise"],Pv=["normal","multiply","screen","overlay"],kC=new Set(["__proto__","prototype","constructor"]);VC=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])});function bt(e,t="PROCEDURAL_TEXTURE_V3_CONTRACT"){throw new yt(`proceduralTexture V3: ${e}`,t)}function $C(e){let t=0,n=(i,r,s)=>{if(++t>16384||s>10)bt(`${r} exceeds the JSON size/depth budget.`);if(i===null||typeof i==="boolean")return;if(typeof i==="string"){if(i.length>4096)bt(`${r} string is too long.`);return}if(typeof i==="number"){if(!Number.isFinite(i))bt(`${r} must be finite.`);return}if(typeof i!=="object")bt(`${r} must contain only JSON data.`);let a=Array.isArray(i),o=Object.getPrototypeOf(i);if(a?o!==Array.prototype:o!==Object.prototype&&o!==null)bt(`${r} must be a plain JSON ${a?"array":"object"}.`);let c=a?Object.getOwnPropertyDescriptor(i,"length")?.value:void 0;if(a&&(typeof c!=="number"||c>1024))bt(`${r} array is too long.`);let l=Reflect.ownKeys(i);if(l.length>1024)bt(`${r} has too many fields.`);let u=Object.getOwnPropertyDescriptors(i);for(let d of l){if(typeof d!=="string"||GC.has(d))bt(`${r} has a forbidden key.`);if(a&&d==="length")continue;let f=u[d];if(!f.enumerable||!("value"in f))bt(`${r}.${d} must be an enumerable JSON data field, never an accessor.`);if(a&&(!/^(0|[1-9][0-9]*)$/.test(d)||Number(d)>=c))bt(`${r} has an invalid array key.`)}if(a&&l.length!==c+1)bt(`${r} must be a dense JSON array.`);for(let d of l)if(d!=="length"||!a)n(u[d].value,`${r}.${String(d)}`,s+1)};n(e,"recipe",0)}function bi(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))bt(`${n} must be a JSON object.`);let i=e;for(let r of Object.keys(i))if(!t.includes(r))bt(`${n} has unknown field ${r}.`);return i}function Vn(e,t,n,i,r){if(e===void 0&&r!==void 0)return r;if(typeof e!=="number"||!Number.isInteger(e)||e<t||e>n)bt(`${i} must be an integer ${t}..${n}.`);return e===0?0:e}function Lv(e,t){if(e===void 0)return!1;if(typeof e!=="boolean")bt(`${t} must be boolean.`);return e}function Su(e,t,n,i,r){if(!Array.isArray(e)||e.length!==t)bt(`${n} must be a ${t}-element array.`);return e.map((s,a)=>Vn(s,i,r,`${n}[${a}]`))}function Fv(e,t){let n=Su(e,4,t,0,255);return n[3]===0?[0,0,0,0]:n}function Uv(e,t,n){let i=bi(e,["x","y","width","height",...n?["kind"]:[]],t);return{x:Vn(i.x,-4096,4096,`${t}.x`),y:Vn(i.y,-4096,4096,`${t}.y`),width:Vn(i.width,1,2048,`${t}.width`),height:Vn(i.height,1,2048,`${t}.height`)}}function KC(e,t){let n=bi(e,["kind","x","y","width","height","from","to","points"],t);if(n.kind==="rectangle"||n.kind==="ellipse")return{kind:n.kind,...Uv(n,t,n.kind)};if(n.kind==="polygon"){bi(n,["kind","points"],t);let i=n.points;if(!Array.isArray(i)||i.length<3||i.length>Mu)bt(`${t}.points requires 3..${Mu} vertices.`);return{kind:"polygon",points:i.map((r,s)=>Su(r,2,`${t}.points[${s}]`,-4096,4096))}}if(n.kind==="line")return bi(n,["kind","from","to","width"],t),{kind:"line",from:Su(n.from,2,`${t}.from`,-4096,4096),to:Su(n.to,2,`${t}.to`,-4096,4096),width:Vn(n.width,1,2048,`${t}.width`)};return bt(`${t}.kind must be rectangle, ellipse, polygon or line.`)}function Bv(e){if(e.kind==="rectangle"||e.kind==="ellipse")return[e.x,e.y,e.x+e.width,e.y+e.height];let t=e.kind==="polygon"?e.points:[e.from,e.to],n=e.kind==="line"?e.width/2:0;return[Math.min(...t.map((i)=>i[0]))-n,Math.min(...t.map((i)=>i[1]))-n,Math.max(...t.map((i)=>i[0]))+n,Math.max(...t.map((i)=>i[1]))+n]}function WC(e){return e.kind==="polygon"?e.points.length+1:e.kind==="line"?4:e.kind==="ellipse"?3:1}function XC(e,t,n,i=0,r=0){let[s,a,o,c]=Bv(e);return[Math.max(0,Math.ceil(s+i-0.5)),Math.max(0,Math.ceil(a+r-0.5)),Math.min(t,Math.floor(o+i-0.5)+1),Math.min(n,Math.floor(c+r-0.5)+1)]}function Iu(e){$C(e);let t=bi(e,["schemaVersion","width","height","usage","name","background","operations","palette"],"recipe");if(t.schemaVersion!==3)bt("schemaVersion must be 3.");let n=Vn(t.width,4,wc,"width"),i=Vn(t.height,4,wc,"height"),r=n*i;if(r>jC)bt("output texel budget exceeded.");let s=t.usage===void 0?"albedo":t.usage;if(!ir.includes(s))bt("usage must be a known texture usage.","PROCEDURAL_TEXTURE_USAGE");let a=s==="albedo"||s==="emissive",o=t.name;if(o!==void 0&&(typeof o!=="string"||!o.length||o.length>80||[...o].some((g)=>g.charCodeAt(0)<32||g.charCodeAt(0)===127)))bt("name must be 1..80 visible characters.");let c=t.operations;if(!Array.isArray(c)||c.length>Sc)bt(`operations must be an array with at most ${Sc} entries.`);let l=r,u=0,d=0,f=c.map((g,p)=>{let x=`operations[${p}]`,_=bi(g,["op","shape","rgba","opacity","alpha","invert","spec","count","seed","area","periodic"],x);if(_.op==="legacy-v2"){bi(_,["op","spec","alpha","opacity"],x);let K=bi(_.spec,["schemaVersion","size","usage","name","layers"],`${x}.spec`);if(K.schemaVersion!==2)bt(`${x}.spec requires explicit schemaVersion 2.`);let B=Tc(K);if(B.size!==n||B.size!==i||B.usage!==s)bt(`${x} legacy-v2 dimensions and usage must match the V3 surface.`);return l+=r*(1+B.layers.reduce((X,q)=>X+(q.op==="noise"?q.octaves*16:4),0)),d+=r*4,{op:"legacy-v2",spec:B,alpha:Vn(_.alpha,0,255,`${x}.alpha`,255),opacity:Vn(_.opacity,0,255,`${x}.opacity`,255)}}let y=KC(_.shape,`${x}.shape`),v=WC(y),[T,A,E,w]=XC(y,n,i),P=Math.max(0,E-T)*Math.max(0,w-A);if(_.op==="mask")return bi(_,["op","shape","alpha","invert"],x),l+=r+P*v,{op:"mask",shape:y,alpha:Vn(_.alpha,0,255,`${x}.alpha`,255),invert:Lv(_.invert,`${x}.invert`)};if(_.op!=="paint"&&_.op!=="stamps")return bt(`${x}.op must be paint, mask, stamps or legacy-v2.`);let S={shape:y,rgba:Fv(_.rgba,`${x}.rgba`),opacity:Vn(_.opacity,0,255,`${x}.opacity`,255)};if(_.op==="paint")return bi(_,["op","shape","rgba","opacity"],x),l+=P*(v+1),{op:"paint",...S};bi(_,["op","shape","rgba","opacity","count","seed","area","periodic"],x);let I=Vn(_.count,1,Ac,`${x}.count`),U=Lv(_.periodic,`${x}.periodic`),[N,F,D,O]=Bv(y);if(U&&(D-N>n||O-F>i))bt(`${x} periodic shape bounds must fit one surface period.`);if(u+=I*(U?9:1),u>Ac)bt(`expanded stamps budget exceeds ${Ac}.`);return l+=I*(U?9:1)*Math.min(n,Math.ceil(D-N)+1)*Math.min(i,Math.ceil(O-F)+1)*(v+1),{op:"stamps",...S,count:I,seed:Vn(_.seed,0,4294967295,`${x}.seed`),area:Uv(_.area,`${x}.area`),periodic:U}}),h;if(t.palette!==void 0){if(!a)bt("palette and dither are supported only for color usages albedo and emissive.");let g=bi(t.palette,["colors","dither"],"palette"),p=g.colors;if(!Array.isArray(p)||p.length<1||p.length>Ru)bt(`palette.colors requires 1..${Ru} entries.`);let x=g.dither===void 0?"none":g.dither;if(x!=="none"&&x!=="bayer4")bt("palette.dither must be none or bayer4.");h={colors:p.map((_,y)=>Vn(_,0,16777215,`palette.colors[${y}]`)),dither:x},l+=r*(p.length+1)}if(l>Dv)bt(`estimated work budget ${l} exceeds ${Dv}.`);if(r*4+d>HC)bt("transient allocation budget exceeded.");let b={schemaVersion:3,width:n,height:i,usage:s,...o!==void 0?{name:o}:{},background:t.background===void 0?[0,0,0,0]:Fv(t.background,"background"),operations:f,...h?{palette:h}:{}},m=JSON.stringify(b);if(m.length>262144)bt("canonical JSON byte budget exceeded.");return{spec:b,canonicalJson:m,estimatedWorkUnits:l,conservativePixelAllocationBytes:r*4+d}}function Kh(e){return Iu(e).spec}function qC(e){return Iu(e).canonicalJson}function Wh(e){return`sha256:${qa(`${Za}-${qC(e)}`)}`}var Za="kiln.procedural-rgba.v3.1",wc=1024,jC=1048576,Sc=64,Mu=64,Ac=256,Ru=32,Dv=64000000,HC=67108864,GC;var Cu=mt(()=>{Ja();Ec();GC=new Set(["__proto__","prototype","constructor"])});function Nu(e){if(!e||typeof e!=="object"||Array.isArray(e))throw new yt("portableSampler requires a complete JSON object.");let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new yt("portableSampler must be plain JSON data.");for(let r of Reflect.ownKeys(e)){let s=Object.getOwnPropertyDescriptor(e,r);if(typeof r!=="string"||!s.enumerable||!("value"in s))throw new yt("portableSampler requires enumerable JSON data fields, never accessors.")}let n=e,i={minFilter:Xh,magFilter:qh,wrapS:Mc,wrapT:Mc};if(Object.keys(n).some((r)=>!Object.hasOwn(i,r)))throw new yt("portableSampler contains an unsupported field.");for(let[r,s]of Object.entries(i))if(!s.includes(n[r]))throw new yt(`portableSampler.${r} requires one of ${s.join(", ")}.`);return{minFilter:n.minFilter,magFilter:n.magFilter,wrapS:n.wrapS,wrapT:n.wrapT}}var Xh,qh,Mc;var Pu=mt(()=>{Ja();Xh=["nearest","linear","nearest-mipmap-nearest","linear-mipmap-nearest","nearest-mipmap-linear","linear-mipmap-linear"],qh=["nearest","linear"],Mc=["repeat","clamp-to-edge","mirrored-repeat"]});function Gv(e){return e.pack===void 0?jv:Hv}function JC(e){return e.pack===void 0?da:Nr}function He(e){throw new $v(e)}function Yh(e){let t=0,n=0,i=new TextEncoder,r=(a)=>{if(n+=a,n>da.jsonBytes)He("JSON byte budget exceeded.")},s=(a,o)=>{if(++t>65536||o>16)He("JSON node/depth budget exceeded.");if(a===null||typeof a==="boolean"){r(a===!1?5:4);return}if(typeof a==="number"){if(!Number.isFinite(a))He("JSON numbers must be finite.");r(JSON.stringify(a).length);return}if(typeof a==="string"){if(a.length>4096)He("JSON string budget exceeded.");r(i.encode(JSON.stringify(a)).length);return}if(typeof a!=="object")He("plain JSON data is required.");let c=Array.isArray(a),l=Object.getPrototypeOf(a);if(c?l!==Array.prototype:l!==null&&l!==Object.prototype)He("plain JSON prototypes are required.");let u=c?Object.getOwnPropertyDescriptor(a,"length")?.value:void 0;if(c&&(!Number.isSafeInteger(u)||u>1024))He("JSON array budget exceeded.");let d=Reflect.ownKeys(a);if(d.length>1024||c&&d.length!==u+1)He("dense bounded JSON fields are required.");r(2+Math.max(0,d.length-(c?1:0)-1));for(let f of d){if(c&&f==="length")continue;if(typeof f!=="string"||["__proto__","prototype","constructor"].includes(f))He("forbidden JSON field.");if(f.length>4096)He("JSON field name budget exceeded.");if(!c)r(i.encode(JSON.stringify(f)).length+1);let h=Object.getOwnPropertyDescriptor(a,f);if(!h.enumerable||!("value"in h))He("JSON accessors/hidden fields are unsupported.");if(c&&(!/^(0|[1-9][0-9]*)$/.test(f)||Number(f)>=u))He("invalid JSON array key.");s(h.value,o+1)}};s(e,0)}function jn(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))He(`${n} must be a JSON object.`);let i=e;if(Object.keys(i).some((r)=>!t.includes(r)))He(`${n} has an unknown field.`);return i}function ri(e,t,n,i){if(typeof e!=="number"||!Number.isSafeInteger(e)||e<t||e>n)He(`${i} must be an integer ${t}..${n}.`);return e===0?0:e}function ns(e,t){if(typeof e!=="string"||!/^sha256:[a-f0-9]{64}$/.test(e))He(`${t} must be an exact SHA-256 hash.`);return e}function zv(e,t){let n=jn(e,["x","y","width","height"],t);return{x:ri(n.x,0,4096,`${t}.x`),y:ri(n.y,0,4096,`${t}.y`),width:ri(n.width,1,4096,`${t}.width`),height:ri(n.height,1,4096,`${t}.height`)}}function Ya(e){let{content:t,gutter:n}=e;return{x:t.x-n,y:t.y-n,width:t.width+2*n,height:t.height+2*n}}function Kv(e,t,n,i){if(e.x+e.width>n||e.y+e.height>i)He("source crop is out of bounds.");if(e.width!==t.width||e.height!==t.height)He("source crop/content dimensions must match; resampling is unsupported.")}function Jh(e){return e.kind==="procedural"?`procedural:${Wh(e.spec)}`:`resource:${e.pin.resourceId}:${e.pin.revisionId}:${e.resourceId}`}function YC(e,t,n,i){let r=[{x:0,y:0,width:e,height:t}],s=(o)=>{let c=[];for(let l of r){if(!ZC(l,o)){c.push(l);continue}if(o.x>l.x)c.push({x:l.x,y:l.y,width:o.x-l.x,height:l.height});if(o.x+o.width<l.x+l.width)c.push({x:o.x+o.width,y:l.y,width:l.x+l.width-o.x-o.width,height:l.height});if(o.y>l.y)c.push({x:l.x,y:l.y,width:l.width,height:o.y-l.y});if(o.y+o.height<l.y+l.height)c.push({x:l.x,y:o.y+o.height,width:l.width,height:l.y+l.height-o.y-o.height})}if(r=c.filter((l,u)=>!c.some((d,f)=>f!==u&&Vv(d,l)&&(!Vv(l,d)||f<u))),r.length>16384)He("pack: free-space bookkeeping budget exceeded.")};for(let o of n)s(o);let a=[...i].sort((o,c)=>c.width*c.height-o.width*o.height||(o.region.name<c.region.name?-1:o.region.name>c.region.name?1:0));for(let o of a){let c,l;for(let u of r){if(u.width<o.width||u.height<o.height)continue;let d=u.width-o.width,f=u.height-o.height,h=[Math.min(d,f),Math.max(d,f),u.y,u.x];if(!l||h[0]<l[0]||h[0]===l[0]&&(h[1]<l[1]||h[1]===l[1]&&(h[2]<l[2]||h[2]===l[2]&&h[3]<l[3])))c=u,l=h}if(!c)He(`pack: region ${o.region.name} (${o.width}x${o.height} texels with its gutter) does not fit in the ${e}x${t} atlas beside the regions already placed.`);o.region.content={x:c.x+o.region.gutter,y:c.y+o.region.gutter,width:o.region.content.width,height:o.region.content.height},s({x:c.x,y:c.y,width:o.width,height:o.height})}}function fa(e){Yh(e);let t=jn(e,["schemaVersion","width","height","usage","sampler","regions","pack"],"atlas");if(t.schemaVersion!==1)He("schemaVersion must be 1.");let n;if(t.pack!==void 0){let f=jn(t.pack,["edge","gutter","algorithm"],"pack");if(!Zh.includes(f.edge))He("pack.edge must be 1024 or 2048.");if(f.algorithm!==void 0&&f.algorithm!=="maxrects")He("pack.algorithm must be 'maxrects'.");n={edge:f.edge,gutter:f.gutter===void 0?2:ri(f.gutter,0,32,"pack.gutter"),algorithm:"maxrects"}}let i=n?Nr:da,r=n?n.edge:i.edge,s=n&&t.width===void 0?n.edge:ri(t.width,4,r,"width"),a=n&&t.height===void 0?n.edge:ri(t.height,4,r,"height");if(s*a>i.outputTexels)He("output texel budget exceeded.");if(!ir.includes(t.usage))He("usage must be a texture usage.");let o=t.usage;if(!Array.isArray(t.regions)||!t.regions.length||t.regions.length>i.regions)He(`regions must contain 1..${i.regions} entries.`);let c=[],l=t.regions.map((f,h)=>{let b=jn(f,["name","content","gutter","edgeMode","source","crop","packed"],`regions[${h}]`);if(typeof b.name!=="string"||!/^[a-z][a-z0-9_-]{0,79}$/.test(b.name))He("region name must be a stable lowercase identifier.");let m=b.content!==void 0;if(!m&&!n)He(`region ${b.name}: content is required unless the atlas sets pack.`);if(b.packed!==void 0&&(b.packed!==!0||!n||!m))He("packed is the resolved-placement marker: true, with content, in an atlas that sets pack.");let g=m?zv(b.content,"content"):void 0,p=b.gutter===void 0?n?.gutter??2:ri(b.gutter,0,32,"gutter"),x=b.edgeMode===void 0?"copy-edge":b.edgeMode;if(!["copy-edge","mask-rgb-dilate"].includes(x))He("unsupported edgeMode.");if(x==="mask-rgb-dilate"&&o!=="albedo"&&o!=="emissive")He("mask RGB dilation requires color usage.");let _=jn(b.source,["kind","spec","resourceId","pin","expected"],"source"),y,v=b.crop===void 0?void 0:zv(b.crop,"crop");if(_.kind==="procedural"){jn(_,["kind","spec"],"procedural source");let A=Iu(_.spec);if(A.spec.usage!==o)He("source usage does not match atlas usage.");y={kind:"procedural",spec:A.spec},v??={x:0,y:0,width:A.spec.width,height:A.spec.height},g??={x:0,y:0,width:v.width,height:v.height},Kv(v,g,A.spec.width,A.spec.height)}else if(_.kind==="resource"){if(jn(_,["kind","resourceId","pin","expected"],"resource source"),typeof _.resourceId!=="string"||!/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/.test(_.resourceId))He("source resourceId must be an exact returned map ID.");let A=jn(_.pin,["resourceId","revisionId","sha256"],"source pin");if(typeof A.resourceId!=="string"||!/^[a-z][a-z0-9_-]{0,79}$/.test(A.resourceId))He("pin resourceId must be a material ID.");let E=ns(A.revisionId,"pin revisionId"),w=ns(A.sha256,"pin sha256");if(E!==w)He("source pin revision/hash mismatch.");let P;if(_.expected!==void 0){let S=jn(_.expected,["width","height","imageSha256","decodedPixelHash"],"source expected");P={...S.width===void 0?{}:{width:ri(S.width,1,4096,"expected.width")},...S.height===void 0?{}:{height:ri(S.height,1,4096,"expected.height")},...S.imageSha256===void 0?{}:{imageSha256:ns(S.imageSha256,"expected.imageSha256")},...S.decodedPixelHash===void 0?{}:{decodedPixelHash:ns(S.decodedPixelHash,"expected.decodedPixelHash")}}}if(y={kind:"resource",resourceId:_.resourceId,pin:{resourceId:A.resourceId,revisionId:E,sha256:w},...P?{expected:P}:{}},!g){let S=v??(P?.width!==void 0&&P.height!==void 0?{width:P.width,height:P.height}:He(`region ${b.name}: a packed resource region needs a crop or expected width and height (its size).`));g={x:0,y:0,width:S.width,height:S.height}}if(v&&(v.width!==g.width||v.height!==g.height))He("source crop/content dimensions must match; resampling is unsupported.")}else He("source kind must be procedural or pinned resource.");let T={name:b.name,content:g,gutter:p,edgeMode:x,source:y,...v?{crop:v}:{},...n&&(!m||b.packed===!0)?{packed:!0}:{}};if(!m)c.push({region:T,width:T.content.width+2*p,height:T.content.height+2*p});return T}).sort((f,h)=>f.name<h.name?-1:f.name>h.name?1:0);if(new Set(l.map((f)=>f.name)).size!==l.length)He("duplicate region name.");if(c.length){let f=new Set(c.map((h)=>h.region));YC(s,a,l.filter((h)=>!f.has(h)).map((h)=>Ya(h)),c)}for(let f of l){let h=Ya(f);if(h.x<0||h.y<0||h.x+h.width>s||h.y+h.height>a)He("padded allocation is out of bounds.")}for(let f=0;f<l.length;f++)for(let h=f+1;h<l.length;h++){let b=Ya(l[f]),m=Ya(l[h]);if(b.x<m.x+m.width&&m.x<b.x+b.width&&b.y<m.y+m.height&&m.y<b.y+b.height)He(`padded allocations overlap: ${l[f].name}, ${l[h].name}.`)}if(new Set(l.map((f)=>Jh(f.source))).size>i.sources)He(`distinct source budget exceeds ${i.sources}.`);let u;try{u=Nu(t.sampler===void 0?{minFilter:"linear-mipmap-linear",magFilter:"linear",wrapS:"clamp-to-edge",wrapT:"clamp-to-edge"}:t.sampler)}catch(f){He(`sampler: ${f.message}`)}let d={schemaVersion:1,width:s,height:a,usage:o,sampler:u,regions:l,...n?{pack:n}:{}};if(new TextEncoder().encode(JSON.stringify(d)).length>da.jsonBytes)He("canonical JSON byte budget exceeded.");return d}function QC(e){let t=fa(e);return`sha256:${qa(`${Gv(t)}-${JSON.stringify(t)}`)}`}function Mn(e){Yh(e);let t=(n)=>Array.isArray(n)?n.map(t):n!==null&&typeof n==="object"?Object.fromEntries(Object.entries(n).sort(([i],[r])=>i<r?-1:i>r?1:0).map(([i,r])=>[i,t(r)])):n;return JSON.stringify(t(e))}function eN(e){return`sha256:${qa(`kiln.atlas-layout.v1-${Mn({width:e.width,height:e.height,origin:"top-left",regions:e.regions.map((t)=>({name:t.name,content:t.content,allocation:Ya(t)}))})}`)}`}function Rc(e,t){Yh(e);let n=fa(t),i=jn(e,["version","compilerId","width","height","usage","origin","sampler","specHash","layoutHash","decodedPixelHash","atlasPixelHash","sources","regions","manifestHash"],"manifest");if(i.version!=="kiln.atlas-manifest.v1"||i.compilerId!==Gv(n)||i.width!==n.width||i.height!==n.height||i.usage!==n.usage||i.origin!=="top-left")He("manifest version/compiler/dimensions/usage/origin mismatch.");if(Mn(i.sampler)!==Mn(n.sampler)||i.specHash!==QC(n)||i.layoutHash!==eN(n))He("manifest sampler/spec/layout identity mismatch.");ns(i.decodedPixelHash,"manifest decodedPixelHash"),ns(i.atlasPixelHash,"manifest atlasPixelHash");let r=new Map(n.regions.map((c)=>[Jh(c.source),c.source]));if(!Array.isArray(i.sources)||i.sources.length!==r.size||!Array.isArray(i.regions)||i.regions.length!==n.regions.length)He("manifest source/region inventory mismatch.");let s=new Map;for(let c of i.sources){let l=jn(c,["id","kind","width","height","decodedPixelHash","recipeHash","compilerId","descriptor"],"manifest source");if(typeof l.id!=="string"||s.has(l.id))He("duplicate/invalid manifest source identity.");let u=r.get(l.id);if(!u||l.kind!==u.kind)He("manifest source identity mismatch.");let d=ri(l.width,1,4096,"manifest source width"),f=ri(l.height,1,4096,"manifest source height");if(ns(l.decodedPixelHash,"manifest source decodedPixelHash"),u.kind==="procedural"){if(jn(l,["id","kind","width","height","decodedPixelHash","recipeHash","compilerId"],"manifest procedural source"),d!==u.spec.width||f!==u.spec.height||l.recipeHash!==Wh(u.spec)||l.compilerId!=="kiln.procedural-rgba.v3.1")He("manifest procedural source identity mismatch.")}else{jn(l,["id","kind","width","height","decodedPixelHash","descriptor"],"manifest resource source");let h=jn(l.descriptor,["materialId","revisionId","resourceId","slot","usage","colorSpace","width","height","encodedByteLength","imageSha256","decodedPixelHash"],"manifest source descriptor"),b={baseColor:"albedo",normal:"normal",metallicRoughness:"metallicRoughness",emissive:"emissive",occlusion:"occlusion"};if(h.materialId!==u.pin.resourceId||h.revisionId!==u.pin.revisionId||h.resourceId!==u.resourceId||h.width!==d||h.height!==f||h.usage!==n.usage||typeof h.slot!=="string"||b[h.slot]!==n.usage||h.colorSpace!==(n.usage==="albedo"||n.usage==="emissive"?"srgb":"linear"))He("manifest pinned resource descriptor mismatch.");if(ns(h.imageSha256,"manifest source imageSha256"),ri(h.encodedByteLength,1,JC(n).encodedSourceBytes,"manifest encodedByteLength"),h.decodedPixelHash!==void 0&&h.decodedPixelHash!==l.decodedPixelHash)He("manifest source decodedPixelHash mismatch.");for(let m of["width","height","imageSha256","decodedPixelHash"]){let g=u.expected?.[m];if(g!==void 0&&g!==(m==="decodedPixelHash"?l[m]:h[m]))He("manifest source expectation mismatch.")}}s.set(l.id,{width:d,height:f})}for(let c=0;c<n.regions.length;c++){let l=n.regions[c],u=jn(i.regions[c],["name","content","allocation","crop","sourceId"],"manifest region"),d=Jh(l.source),f=s.get(d),h=l.crop??{x:0,y:0,width:f.width,height:f.height};if(Kv(h,l.content,f.width,f.height),u.name!==l.name||u.sourceId!==d||Mn(u.content)!==Mn(l.content)||Mn(u.allocation)!==Mn(Ya(l))||Mn(u.crop)!==Mn(h))He("manifest named region/crop/allocation identity mismatch.")}let{manifestHash:a,...o}=i;if(a!==`sha256:${qa(`kiln.atlas-manifest.v1-${Mn(o)}`)}`)He("manifest hash mismatch.");return structuredClone(e)}var jv="kiln.texture-atlas.v1.1",Hv="kiln.texture-atlas.v1.2",Ou,da,Nr,Zh,$v,ZC=(e,t)=>e.x<t.x+t.width&&t.x<e.x+e.width&&e.y<t.y+t.height&&t.y<e.y+e.height,Vv=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height;var ku=mt(()=>{Pu();Cu();Ja();Ec();vu();Ou=Object.freeze([jv,Hv]),da=Object.freeze({edge:1024,outputTexels:1048576,regions:64,sources:16,sourceTexels:4194304,encodedSourceBytes:8388608,encodedBytes:16777216,jsonBytes:262144,work:64000000,allocatedBytes:67108864,uvVertices:262144,uvAttributeBytes:134217728}),Nr=Object.freeze({...da,edge:2048,outputTexels:4194304,regions:128,sources:32,work:192000000,allocatedBytes:134217728}),Zh=Object.freeze([1024,2048]);$v=class $v extends Xa{constructor(e){super("TEXTURE_ATLAS_CONTRACT",`textureAtlas: ${e}`);this.name="TextureAtlasError"}}});function pN(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function mN(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function vo(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function VT(){let e=vo("canvas");return e.style.display="block",e}function $c(...e){let t="THREE."+e.shift();if(Eo)Eo("log",t,...e);else console.log(t,...e)}function jT(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 je(...e){e=jT(e);let t="THREE."+e.shift();if(Eo)Eo("warn",t,...e);else{let n=e[0];if(n&&n.isStackTrace)console.warn(n.getError(t));else console.warn(t,...e)}}function Ze(...e){e=jT(e);let t="THREE."+e.shift();if(Eo)Eo("error",t,...e);else{let n=e[0];if(n&&n.isStackTrace)console.error(n.getError(t));else console.error(t,...e)}}function ba(...e){let t=e.join(" ");if(t in uE)return;uE[t]=!0,je(...e)}function HT(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)})}class Vi{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}}}function Fi(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Pn[e&255]+Pn[e>>8&255]+Pn[e>>16&255]+Pn[e>>24&255]+"-"+Pn[t&255]+Pn[t>>8&255]+"-"+Pn[t>>16&15|64]+Pn[t>>24&255]+"-"+Pn[n&63|128]+Pn[n>>8&255]+"-"+Pn[n>>16&255]+Pn[n>>24&255]+Pn[i&255]+Pn[i>>8&255]+Pn[i>>16&255]+Pn[i>>24&255]).toLowerCase()}function ct(e,t,n){return Math.max(t,Math.min(n,e))}function Im(e,t){return(e%t+t)%t}function gN(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)}function bN(e,t,n){if(e!==t)return(n-e)/(t-e);else return 0}function Gc(e,t,n){return(1-n)*e+n*t}function xN(e,t,n,i){return Gc(e,t,1-Math.exp(-n*i))}function yN(e,t=1){return t-Math.abs(Im(e,t*2)-t)}function _N(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 vN(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 EN(e,t){return e+Math.floor(Math.random()*(t-e+1))}function TN(e,t){return e+Math.random()*(t-e)}function AN(e){return e*(0.5-Math.random())}function wN(e){if(e!==void 0)dE=e;let t=dE+=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 SN(e){return e*Hc}function MN(e){return e*xa}function RN(e){return e>0&&Number.isInteger(e)&&2**Math.round(Math.log2(e))===e}function IN(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))}function CN(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function NN(e,t,n,i,r){let{cos:s,sin:a}=Math,o=s(n/2),c=a(n/2),l=s((t+i)/2),u=a((t+i)/2),d=s((t-i)/2),f=a((t-i)/2),h=s((i-t)/2),b=a((i-t)/2);switch(r){case"XYX":e.set(o*u,c*d,c*f,o*l);break;case"YZY":e.set(c*f,o*u,c*d,o*l);break;case"ZXZ":e.set(c*d,c*f,o*u,o*l);break;case"XZX":e.set(o*u,c*b,c*h,o*l);break;case"YXY":e.set(c*h,o*u,c*b,o*l);break;case"ZYZ":e.set(c*b,c*h,o*u,o*l);break;default:je("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function Li(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray: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:case Uint8ClampedArray: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.")}}function PN(){let e={enabled:!0,workingColorSpace:"srgb-linear",spaces:{},convert:function(r,s,a){if(this.enabled===!1||s===a||!s||!a)return r;if(this.spaces[s].transfer==="srgb")r.r=Ur(r.r),r.g=Ur(r.g),r.b=Ur(r.b);if(this.spaces[s].primaries!==this.spaces[a].primaries)r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[a].fromXYZ);if(this.spaces[a].transfer==="srgb")r.r=_o(r.r),r.g=_o(r.g),r.b=_o(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,a){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(r,s){return ba("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return ba("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:hE,fromXYZ:pE,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:"srgb"},outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}},["srgb"]:{primaries:t,whitePoint:i,transfer:"srgb",toXYZ:hE,fromXYZ:pE,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}}}),e}function Ur(e){return e<0.04045?e*0.0773993808:Math.pow(e*0.9478672986+0.0521327014,2.4)}function _o(e){return e<0.0031308?e*12.92:1.055*Math.pow(e,0.41666)-0.055}class Cm{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(so===void 0)so=vo("canvas");so.width=e.width,so.height=e.height;let i=so.getContext("2d");if(e instanceof ImageData)i.putImageData(e,0,0);else i.drawImage(e,0,0,e.width,e.height);n=so}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=vo("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]=Ur(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(Ur(t[n]/255)*255);else t[n]=Ur(t[n]);return{data:t,width:e.width,height:e.height}}else return je("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}class Qc{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:ON++}),this.uuid=Fi(),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,a=i.length;s<a;s++)if(i[s].isDataTexture)r.push(op(i[s].image));else r.push(op(i[s]))}else r=op(i);n.url=r}if(!t)e.images[this.uuid]=n;return n}}function op(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap)return Cm.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 je("Texture: Unable to serialize Texture."),{}}class Ad{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}}class el{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){if(this._hand===null)this._hand=new cr,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 cr,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 cr,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(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,a=this._targetRay,o=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){s=!0;for(let b of e.hand.values()){let m=t.getJointPose(b,n),g=this._getHandJoint(c,b);if(m!==null)g.matrix.fromArray(m.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=m.radius;g.visible=m!==null}let l=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=l.position.distanceTo(u.position),f=0.02,h=0.005;if(c.inputState.pinching&&d>f+h)c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this});else if(!c.inputState.pinching&&d<=f-h)c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this})}else if(o!==null&&e.gripSpace){if(r=t.getPose(e.gripSpace,n),r!==null){if(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity)o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity);else o.hasLinearVelocity=!1;if(r.angularVelocity)o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity);else o.hasAngularVelocity=!1;if(o.eventsEnabled)o.dispatchEvent({type:"gripUpdated",data:e,target:this})}}if(a!==null){if(i=t.getPose(e.targetRaySpace,n),i===null&&r!==null)i=r;if(i!==null){if(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity)a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity);else a.hasLinearVelocity=!1;if(i.angularVelocity)a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity);else a.hasAngularVelocity=!1;this.dispatchEvent(VN)}}}if(a!==null)a.visible=i!==null;if(o!==null)o.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 cr;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}function up(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 _i{constructor(e=new j,t=new j,n=new j){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),ki.subVectors(e,t),i.cross(ki);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){ki.subVectors(i,t),Or.subVectors(n,t),dp.subVectors(e,t);let s=ki.dot(ki),a=ki.dot(Or),o=ki.dot(dp),c=Or.dot(Or),l=Or.dot(dp),u=s*c-a*a;if(u===0)return r.set(0,0,0),null;let d=1/u,f=(c*o-a*l)*d,h=(s*l-a*o)*d;return r.set(1-f-h,h,f)}static containsPoint(e,t,n,i){if(this.getBarycoord(e,t,n,i,kr)===null)return!1;return kr.x>=0&&kr.y>=0&&kr.x+kr.y<=1}static getInterpolation(e,t,n,i,r,s,a,o){if(this.getBarycoord(e,t,n,i,kr)===null){if(o.x=0,o.y=0,"z"in o)o.z=0;if("w"in o)o.w=0;return null}return o.setScalar(0),o.addScaledVector(r,kr.x),o.addScaledVector(s,kr.y),o.addScaledVector(a,kr.z),o}static getInterpolatedAttribute(e,t,n,i,r,s){return mp.setScalar(0),gp.setScalar(0),bp.setScalar(0),mp.fromBufferAttribute(e,t),gp.fromBufferAttribute(e,n),bp.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(mp,r.x),s.addScaledVector(gp,r.y),s.addScaledVector(bp,r.z),s}static isFrontFacing(e,t,n,i){return ki.subVectors(n,t),Or.subVectors(e,t),ki.cross(Or).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 ki.subVectors(this.c,this.b),Or.subVectors(this.a,this.b),ki.cross(Or).length()*0.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(0.3333333333333333)}getNormal(e){return _i.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return _i.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return _i.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return _i.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return _i.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,r=this.c,s,a;lo.subVectors(i,n),uo.subVectors(r,n),fp.subVectors(e,n);let o=lo.dot(fp),c=uo.dot(fp);if(o<=0&&c<=0)return t.copy(n);hp.subVectors(e,i);let l=lo.dot(hp),u=uo.dot(hp);if(l>=0&&u<=l)return t.copy(i);let d=o*u-l*c;if(d<=0&&o>=0&&l<=0)return s=o/(o-l),t.copy(n).addScaledVector(lo,s);pp.subVectors(e,r);let f=lo.dot(pp),h=uo.dot(pp);if(h>=0&&f<=h)return t.copy(r);let b=f*c-o*h;if(b<=0&&c>=0&&h<=0)return a=c/(c-h),t.copy(n).addScaledVector(uo,a);let m=l*h-f*u;if(m<=0&&u-l>=0&&f-h>=0)return EE.subVectors(r,i),a=(u-l)/(u-l+(f-h)),t.copy(i).addScaledVector(EE,a);let g=1/(m+b+d);return s=b*g,a=d*g,t.copy(n).addScaledVector(lo,s).addScaledVector(uo,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class hn{constructor(e=new j(1/0,1/0,1/0),t=new j(-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(Di.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Di.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=Di.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,a=r.count;s<a;s++){if(e.isMesh===!0)e.getVertexPosition(s,Di);else Di.fromBufferAttribute(r,s);Di.applyMatrix4(e.matrixWorld),this.expandByPoint(Di)}else{if(e.boundingBox!==void 0){if(e.boundingBox===null)e.computeBoundingBox();Bu.copy(e.boundingBox)}else{if(n.boundingBox===null)n.computeBoundingBox();Bu.copy(n.boundingBox)}Bu.applyMatrix4(e.matrixWorld),this.union(Bu)}}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,Di),Di.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(Lc),zu.subVectors(this.max,Lc),fo.subVectors(e.a,Lc),ho.subVectors(e.b,Lc),po.subVectors(e.c,Lc),ss.subVectors(ho,fo),as.subVectors(po,ho),ha.subVectors(fo,po);let t=[0,-ss.z,ss.y,0,-as.z,as.y,0,-ha.z,ha.y,ss.z,0,-ss.x,as.z,0,-as.x,ha.z,0,-ha.x,-ss.y,ss.x,0,-as.y,as.x,0,-ha.y,ha.x,0];if(!xp(t,fo,ho,po,zu))return!1;if(t=[1,0,0,0,1,0,0,0,1],!xp(t,fo,ho,po,zu))return!1;return Vu.crossVectors(ss,as),t=[Vu.x,Vu.y,Vu.z],xp(t,fo,ho,po,zu)}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Di).distanceTo(e)}getBoundingSphere(e){if(this.isEmpty())e.makeEmpty();else this.getCenter(e.center),e.radius=this.getSize(Di).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 Dr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Dr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Dr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Dr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Dr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Dr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Dr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Dr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Dr),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}}function xp(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){pa.fromArray(e,s);let o=r.x*Math.abs(pa.x)+r.y*Math.abs(pa.y)+r.z*Math.abs(pa.z),c=t.dot(pa),l=n.dot(pa),u=i.dot(pa);if(Math.max(-Math.max(c,l,u),Math.min(c,l,u))>o)return!1}return!0}class li{constructor(e=new j,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 HN.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;Fc.subVectors(e,this.center);let t=Fc.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=(n-this.radius)*0.5;this.center.addScaledVector(Fc,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 yp.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Fc.copy(e.center).add(yp)),this.expandByPoint(Fc.copy(e.center).sub(yp));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}}class tl{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=Fi()}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=Fi();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=Fi();if(e.arrayBuffers[this.array.buffer._uuid]===void 0)e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer));let t={uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride};return t.usage=this.usage,t}}class Oo{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++)Hn.fromBufferAttribute(this,t),Hn.applyMatrix4(e),this.setXYZ(t,Hn.x,Hn.y,Hn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Hn.fromBufferAttribute(this,t),Hn.applyNormalMatrix(e),this.setXYZ(t,Hn.x,Hn.y,Hn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Hn.fromBufferAttribute(this,t),Hn.transformDirection(e),this.setXYZ(t,Hn.x,Hn.y,Hn.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];if(this.normalized)n=Li(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=Li(t,this.array);return t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];if(this.normalized)t=Li(t,this.array);return t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];if(this.normalized)t=Li(t,this.array);return t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];if(this.normalized)t=Li(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){$c("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 vn(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 Oo(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}}toJSON(e){if(e===void 0){$c("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}}}}class yi{constructor(e=new j(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=vp.subVectors(n,t).cross($N.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(vp),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||KN.getNormalMatrix(e),i=this.coplanarPoint(vp).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)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}}class ms{constructor(e=new j,t=new j(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,Lr)),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=Lr.subVectors(e,this.origin).dot(this.direction);if(t<0)return this.origin.distanceToSquared(e);return Lr.copy(this.origin).addScaledVector(this.direction,t),Lr.distanceToSquared(e)}distanceSqToSegment(e,t,n,i){Ep.copy(e).add(t).multiplyScalar(0.5),Hu.copy(t).sub(e).normalize(),Gu.copy(this.origin).sub(Ep);let r=e.distanceTo(t)*0.5,s=-this.direction.dot(Hu),a=Gu.dot(this.direction),o=-Gu.dot(Hu),c=Gu.lengthSq(),l=Math.abs(1-s*s),u,d,f,h;if(l>0)if(u=s*o-a,d=s*a-o,h=r*l,u>=0)if(d>=-h)if(d<=h){let b=1/l;u*=b,d*=b,f=u*(u+s*d+2*a)+d*(s*u+d+2*o)+c}else d=r,u=Math.max(0,-(s*d+a)),f=-u*u+d*(d+2*o)+c;else d=-r,u=Math.max(0,-(s*d+a)),f=-u*u+d*(d+2*o)+c;else if(d<=-h)u=Math.max(0,-(-s*r+a)),d=u>0?-r:Math.min(Math.max(-r,-o),r),f=-u*u+d*(d+2*o)+c;else if(d<=h)u=0,d=Math.min(Math.max(-r,-o),r),f=d*(d+2*o)+c;else u=Math.max(0,-(s*r+a)),d=u>0?r:Math.min(Math.max(-r,-o),r),f=-u*u+d*(d+2*o)+c;else d=s>0?-r:r,u=Math.max(0,-(s*d+a)),f=-u*u+d*(d+2*o)+c;if(n)n.copy(this.origin).addScaledVector(this.direction,u);if(i)i.copy(Ep).addScaledVector(Hu,d);return f}intersectSphere(e,t){if(e.radius<0)return null;Lr.subVectors(e.center,this.origin);let n=Lr.dot(this.direction),i=Lr.dot(Lr)-n*n,r=e.radius*e.radius;if(i>r)return null;let s=Math.sqrt(r-i),a=n-s,o=n+s;if(o<0)return null;if(a<0)return this.at(o,t);return this.at(a,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,a,o,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;if(c>=0)n=(e.min.x-d.x)*c,i=(e.max.x-d.x)*c;else n=(e.max.x-d.x)*c,i=(e.min.x-d.x)*c;if(l>=0)r=(e.min.y-d.y)*l,s=(e.max.y-d.y)*l;else r=(e.max.y-d.y)*l,s=(e.min.y-d.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)a=(e.min.z-d.z)*u,o=(e.max.z-d.z)*u;else a=(e.max.z-d.z)*u,o=(e.min.z-d.z)*u;if(n>o||a>i)return null;if(a>n||n!==n)n=a;if(o<i||i!==i)i=o;if(i<0)return null;return this.at(n>=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,Lr)!==null}intersectTriangle(e,t,n,i,r){let s=this.origin,a=this.direction,{x:o,y:c,z:l}=a,u=e.x-s.x,d=e.y-s.y,f=e.z-s.z,h=t.x-s.x,b=t.y-s.y,m=t.z-s.z,g=n.x-s.x,p=n.y-s.y,x=n.z-s.z,_=Math.abs(o),y=Math.abs(c),v=Math.abs(l),T,A,E,w,P,S,I,U,N,F,D,O;if(_>=y&&_>=v)if(E=o,S=u,N=h,O=g,o>=0)T=c,A=l,w=d,P=f,I=b,U=m,F=p,D=x;else T=l,A=c,w=f,P=d,I=m,U=b,F=x,D=p;else if(y>=v)if(E=c,S=d,N=b,O=p,c>=0)T=l,A=o,w=f,P=u,I=m,U=h,F=x,D=g;else T=o,A=l,w=u,P=f,I=h,U=m,F=g,D=x;else if(E=l,S=f,N=m,O=x,l>=0)T=o,A=c,w=u,P=d,I=h,U=b,F=g,D=p;else T=c,A=o,w=d,P=u,I=b,U=h,F=p,D=g;if(E===0)return null;let K=T/E,B=A/E,X=1/E,q=w-K*S,le=P-B*S,de=I-K*N,Me=U-B*N,pe=F-K*O,J=D-B*O,L=pe*Me-J*de,W=q*J-le*pe,ne=de*le-Me*q;if(i){if(L<0||W<0||ne<0)return null}else if((L<0||W<0||ne<0)&&(L>0||W>0||ne>0))return null;let ie=L+W+ne;if(ie===0)return null;let ce=X*(L*S+W*N+ne*O);if(ie>0?ce<0:ce>0)return null;return this.at(ce/ie,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)}}function XN(e,t,n,i,r,s,a,o){let c;if(t.side===1)c=i.intersectTriangle(a,s,r,!0,o);else c=i.intersectTriangle(r,s,a,t.side===0,o);if(c===null)return null;Ju.copy(o),Ju.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(Ju);if(l<n.near||l>n.far)return null;return{distance:l,point:Ju.clone(),object:e}}function Zu(e,t,n,i,r,s,a,o,c,l){e.getVertexPosition(o,Ku),e.getVertexPosition(c,Wu),e.getVertexPosition(l,Xu);let u=XN(e,t,n,i,Ku,Wu,Xu,wE);if(u){let d=new j;if(_i.getBarycoord(wE,Ku,Wu,Xu,d),r)u.uv=_i.getInterpolatedAttribute(r,o,c,l,d,new Ke);if(s)u.uv1=_i.getInterpolatedAttribute(s,o,c,l,d,new Ke);if(a){if(u.normal=_i.getInterpolatedAttribute(a,o,c,l,d,new j),u.normal.dot(i.direction)>0)u.normal.multiplyScalar(-1)}let f={a:o,b:c,c:l,normal:new j,materialIndex:0};_i.getNormal(Ku,Wu,Xu,f.normal),u.face=f,u.barycoord=d}return u}class rl{constructor(e=[],t=[]){this.uuid=Fi(),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){je("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 Qe)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let n=new Qe;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 a=e[r]?e[r].matrixWorld:JN;CE.multiplyMatrices(a,t[r]),CE.toArray(n,r*16)}if(i!==null)i.needsUpdate=!0}clone(){return new rl(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 il(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)je("Skeleton: No bone found with UUID:",r),s=new nl;this.bones.push(s),this.boneInverses.push(new Qe().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 a=n[i];e.boneInverses.push(a.toArray())}return e}}class sl{constructor(e=new yi,t=new yi,n=new yi,i=new yi,r=new yi,s=new yi){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){let a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[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],a=r[1],o=r[2],c=r[3],l=r[4],u=r[5],d=r[6],f=r[7],h=r[8],b=r[9],m=r[10],g=r[11],p=r[12],x=r[13],_=r[14],y=r[15];if(i[0].setComponents(c-s,f-l,g-h,y-p).normalize(),i[1].setComponents(c+s,f+l,g+h,y+p).normalize(),i[2].setComponents(c+a,f+u,g+b,y+x).normalize(),i[3].setComponents(c-a,f-u,g-b,y-x).normalize(),n)i[4].setComponents(o,d,m,_).normalize(),i[5].setComponents(c-o,f-d,g-m,y-_).normalize();else if(i[4].setComponents(c-o,f-d,g-m,y-_).normalize(),t===2000)i[5].setComponents(c+o,f+d,g+m,y+_).normalize();else if(t===2001)i[5].setComponents(o,d,m,_).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();ga.copy(e.boundingSphere).applyMatrix4(e.matrixWorld)}else{let t=e.geometry;if(t.boundingSphere===null)t.computeBoundingSphere();ga.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ga)}intersectsSprite(e){ga.center.set(0,0,0);let t=YN.distanceTo(e.center);return ga.radius=0.7071067811865476+t,ga.applyMatrix4(e.matrixWorld),this.intersectsSphere(ga)}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(ed.x=i.normal.x>0?e.max.x:e.min.x,ed.y=i.normal.y>0?e.max.y:e.min.y,ed.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(ed)<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)}}function nd(e,t,n,i,r,s,a){let o=e.geometry.attributes.position;if(cd.fromBufferAttribute(o,r),ld.fromBufferAttribute(o,s),n.distanceSqToSegment(cd,ld,Sp,kE)>i)return;Sp.applyMatrix4(e.matrixWorld);let l=t.ray.origin.distanceTo(Sp);if(l<t.near||l>t.far)return;return{distance:l,point:kE.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}function UE(e,t,n,i,r,s,a){let o=Ip.distanceSqToPoint(e);if(o<n){let c=new j;Ip.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(o),point:c,index:t,face:null,faceIndex:null,barycoord:null,object:a})}}function Sa(e){let t={};for(let n in e){t[n]={};for(let i in e[n]){let r=e[n][i];if(BE(r))if(r.isRenderTargetTexture)je("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(BE(r[0])){let s=[];for(let a=0,o=r.length;a<o;a++)s[a]=r[a].clone();t[n][i]=s}else t[n][i]=r.slice();else t[n][i]=r}}return t}function Ln(e){let t={};for(let n=0;n<e.length;n++){let i=Sa(e[n]);for(let r in i)t[r]=i[r]}return t}function BE(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function QN(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function km(e){let t=e.getRenderTarget();if(t===null)return e.outputColorSpace;if(t.isXRRenderTarget===!0)return t.texture.colorSpace;return ot.workingColorSpace}function cs(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 od(e){return e!==void 0&&e.inTangents!==void 0&&e.outTangents!==void 0}function nP(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 zE(e,t,n){let i=e.length,r=new e.constructor(i);for(let s=0,a=0;a!==i;++s){let o=n[s]*t;for(let c=0;c!==t;++c)r[a++]=e[o+c]}return r}function iP(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 a=s[i];if(a===void 0)return;if(Array.isArray(a))do{if(a=s[i],a!==void 0)t.push(s.time),n.push(...a);s=e[r++]}while(s!==void 0);else if(a.toArray!==void 0)do{if(a=s[i],a!==void 0)t.push(s.time),a.toArray(n,n.length);s=e[r++]}while(s!==void 0);else do{if(a=s[i],a!==void 0)t.push(s.time),n.push(a);s=e[r++]}while(s!==void 0)}class Vr{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 a=n+2;;){if(i===void 0){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(r=i,i=t[++n],e<i)break t}s=t.length;break n}if(!(e>=r)){let a=t[1];if(e<a)n=2,r=a;for(let o=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===o)break;if(i=r,r=t[--n-1],e>=r)break t}s=n,n=0;break n}break e}while(n<s){let a=n+s>>>1;if(e<t[a])s=a;else n=a+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_(){}}function WT(e,t,n,i,r){let s=1-e;return s*s*s*t+3*s*s*e*n+3*s*e*e*i+e*e*e*r}function rP(e,t,n,i,r){let s=1-e;return 3*s*s*(n-t)+6*s*e*(i-n)+3*e*e*(r-i)}function sP(e,t,n,i,r){let s=(e-t)/(r-t);for(let a=0;a<8;a++){let o=WT(s,t,n,i,r)-e;if(Math.abs(o)<0.0000000001)break;let c=rP(s,t,n,i,r);if(Math.abs(c)<0.0000000001)break;s=Math.max(0,Math.min(1,s-o/c))}return s}class di{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=cs(t,this.TimeBufferType),this.values=cs(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:cs(e.times,Array),values:cs(e.values,Array)};let i=e.getInterpolation();if(i!==e.DefaultInterpolation)n.interpolation=i;if(od(e.settings))n.settings={inTangents:cs(e.settings.inTangents,Array),outTangents:cs(e.settings.outTangents,Array)}}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Bm(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Od(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Um(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new zm(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 je("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;if(od(this.settings))VE(this.settings.inTangents,e),VE(this.settings.outTangents,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 a=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*a,s*a)}return this}validate(){let e=!0,t=this.getValueSize();if(t-Math.floor(t)!==0)Ze("KeyframeTrack: Invalid value size in track.",this),e=!1;let n=this.times,i=this.values,r=n.length;if(r===0)Ze("KeyframeTrack: Track is empty.",this),e=!1;let s=null;for(let a=0;a!==r;a++){let o=n[a];if(typeof o==="number"&&isNaN(o)){Ze("KeyframeTrack: Time is not a valid number.",this,a,o),e=!1;break}if(s!==null&&s>o){Ze("KeyframeTrack: Out of order keys.",this,a,o,s),e=!1;break}s=o}if(i!==void 0){if(mN(i))for(let a=0,o=i.length;a!==o;++a){let c=i[a];if(isNaN(c)){Ze("KeyframeTrack: Value is not a valid number.",this,a,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 a=1;a<r;++a){let o=!1,c=e[a],l=e[a+1];if(c!==l&&(a!==1||c!==e[0]))if(!i){let u=a*n,d=u-n,f=u+n;for(let h=0;h!==n;++h){let b=t[u+h];if(b!==t[d+h]||b!==t[f+h]){o=!0;break}}}else o=!0;if(o){if(a!==s){e[s]=e[a];let u=a*n,d=s*n;for(let f=0;f!==n;++f)t[d+f]=t[u+f]}++s}}if(r>0){e[s]=e[r];for(let a=r*n,o=s*n,c=0;c!==n;++c)t[o+c]=t[a+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);if(i.createInterpolant=this.createInterpolant,od(this.settings))i.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()};return i}}function VE(e,t){for(let n=0,i=e.length;n!==i;n+=2)e[n]*=t}class To{constructor(e="",t=-1,n=[],i=2500){if(this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=Fi(),this.userData={},this.duration<0)this.resetDuration()}static parse(e){let t=[],n=e.tracks,i=1/(e.fps||1);for(let s=0,a=n.length;s!==a;++s)t.push(oP(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(di.toJSON(n[r]));return i}static CreateFromMorphTargetSequence(e,t,n,i){let r=t.length,s=[];for(let a=0;a<r;a++){let o=[],c=[];o.push((a+r-1)%r,a,(a+1)%r),c.push(0,1,0);let l=nP(o);if(o=zE(o,1,l),c=zE(c,1,l),!i&&o[0]===0)o.push(r),c.push(c[0]);s.push(new ys(".morphTargetInfluences["+t[a].name+"]",o,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 a=0,o=e.length;a<o;a++){let c=e[a],l=c.name.match(r);if(l&&l.length>1){let u=l[1],d=i[u];if(!d)i[u]=d=[];d.push(c)}}let s=[];for(let a in i)s.push(this.CreateFromMorphTargetSequence(a,i[a],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 aP(e){switch(e.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return ys;case"vector":case"vector2":case"vector3":case"vector4":return Ma;case"color":return kd;case"quaternion":return _s;case"bool":case"boolean":return xs;case"string":return vs}throw Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}function oP(e){if(e.type===void 0)throw Error("THREE.KeyframeTrack: track type undefined, can not parse");let t=aP(e.type);if(e.times===void 0){let i=[],r=[];iP(e.keys,i,r,"value"),e.times=i,e.values=r}let n;if(t.parse!==void 0)n=t.parse(e);else n=new t(e.name,e.times,e.values,e.interpolation);if(od(e.settings))n.settings={inTangents:cs(e.settings.inTangents,Float32Array),outTangents:cs(e.settings.outTangents,Float32Array)};return n}function jE(e){try{let t=e.slice(e.indexOf(":")+1);return new URL(t).protocol==="blob:"}catch(t){return!1}}class ll{constructor(e,t,n){let i=this,r=!1,s=0,a=0,o=void 0,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(l){if(a++,r===!1){if(i.onStart!==void 0)i.onStart(l,s,a)}r=!0},this.itemEnd=function(l){if(s++,i.onProgress!==void 0)i.onProgress(l,s,a);if(s===a){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"),o)return o(l);return l},this.setURLModifier=function(l){return o=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,d=c.length;u<d;u+=2){let f=c[u],h=c[u+1];if(f.global)f.lastIndex=0;if(f.test(l))return h}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}}class jr{constructor(e){if(this.manager=e!==void 0?e:XT,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}}class dl{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 Ke(512,512),this.mapType=1009,this.map=null,this.mapPass=null,this.matrix=new Qe,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new sl,this._frameExtents=new Ke(1,1),this._viewportCount=1,this._viewports=[new Pt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getCamera(){return this.camera}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera;HE.setFromMatrixPosition(e.matrixWorld),t.position.copy(HE),GE.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(GE),t.updateMatrixWorld(),this._updateMatrix(t,this.matrix,this._frustum)}_updateMatrix(e,t,n,i){Mp.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),n.setFromProjectionMatrix(Mp,e.coordinateSystem,e.reversedDepth);let r=this._frameExtents,s=i?i.z/r.x:1,a=i?i.w/r.y:1,o=i?i.x/r.x:0,c=i?i.y/r.y:0;if(e.coordinateSystem===2001||e.reversedDepth)t.set(0.5*s,0,0,0.5*s+o,0,0.5*a,0,0.5*a+c,0,0,1,0,0,0,0,1);else t.set(0.5*s,0,0,0.5*s+o,0,0.5*a,0,0.5*a+c,0,0,0.5,0.5,0,0,0,1);t.multiply(Mp)}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={};return e.intensity=this.intensity,e.bias=this.bias,e.normalBias=this.normalBias,e.radius=this.radius,e.blurSamples=this.blurSamples,e.mapSize=this.mapSize.toArray(),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class Es{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}}class $m{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 a=0;a!==i;++a)n[r+a]=n[a];s=t}else{s+=t;let a=t/s;this._mixBufferRegion(n,r,0,a,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,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){let o=t*this._origIndex;this._mixBufferRegion(n,i,o,1-r,t)}if(s>0)this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let o=t,c=t+t;o!==c;++o)if(n[o]!==n[o+t]){a.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){ln.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,r){let s=this._workIndex*r;ln.multiplyQuaternionsFlat(e,s,e,t,e,n),ln.slerpFlat(e,t,e,t,e,s,i)}_lerp(e,t,n,i,r){let s=1-i;for(let a=0;a!==r;++a){let o=t+a;e[o]=e[o]*s+e[n+a]*i}}_lerpAdditive(e,t,n,i,r){for(let s=0;s!==r;++s){let a=t+s;e[a]=e[a]+e[n+s]*i}}}class QT{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(cP,"")}static parseTrackName(e){let t=pP.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(mP.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 a=r[s];if(a.name===t||a.uuid===t)return a;let o=n(a.children);if(o)return o}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){je("PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let c=t.objectIndex;switch(n){case"materials":if(!e.material){Ze("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){Ze("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){Ze("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){Ze("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){Ze("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){Ze("PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(c!==void 0){if(e[c]===void 0){Ze("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;Ze("PropertyBinding: Trying to update property for track: "+c+"."+i+" but it wasn't found.",e);return}let a=this.Versioning.None;if(this.targetObject=e,e.isMaterial===!0)a=this.Versioning.NeedsUpdate;else if(e.isObject3D===!0)a=this.Versioning.MatrixWorldNeedsUpdate;let o=this.BindingType.Direct;if(r!==void 0){if(i==="morphTargetInfluences"){if(!e.geometry){Ze("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){Ze("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]}o=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=r}else if(s.fromArray!==void 0&&s.toArray!==void 0)o=this.BindingType.HasFromToArray,this.resolvedProperty=s;else if(Array.isArray(s))o=this.BindingType.EntireArray,this.resolvedProperty=s;else this.propertyName=i;this.getValue=this.GetterByBindingType[o],this.setValue=this.SetterByBindingTypeAndVersioning[o][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}class Xm{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,a=Array(s),o={endingStart:2400,endingEnd:2400};for(let c=0;c!==s;++c){let l=r[c].createInterpolant(null);a[c]=l,l.settings=o}this._interpolantSettings=o,this._interpolants=a,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,a=i/r;e._restoreTimeScale=e.timeScale,this._restoreTimeScale=this.timeScale,e.warp(1,s,t),this.warp(a,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,a=this._timeScaleInterpolant;if(a===null)a=i._lendControlInterpolant(),this._timeScaleInterpolant=a;let o=a.parameterPositions,c=a.sampleValues;return o[0]=r,o[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 o=(e-r)*n;if(o<0||n===0)t=0;else this._startTime=null,t=n*o}t*=this._updateTimeScale(e);let s=this._updateTime(t),a=this._updateWeight(e);if(a>0){let o=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case 2501:for(let l=0,u=o.length;l!==u;++l)o[l].evaluate(s),c[l].accumulateAdditive(a);break;case 2500:default:for(let l=0,u=o.length;l!==u;++l)o[l].evaluate(s),c[l].accumulate(i,a)}}}_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 a=Math.floor(i/t);i-=t*a,r+=Math.abs(a);let o=this.repetitions-r;if(o<=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(o===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:a})}}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 a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=t,a[1]=r+e,o[1]=n,this}}class fl{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=ct(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(ct(t/this.radius,-1,1));return this}clone(){return new this.constructor().copy(this)}}function Jm(e,t,n,i){let r=bP(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 bP(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}.`)}var WE="186",us,ds,XE=0,Cp=1,qE=2,Kc=1,JE=2,Ao=3,fs=0,kn=1,vi=2,dr=0,Wc=1,Np=2,Pp=3,Op=4,ZE=5,wo=100,YE=101,QE=102,eT=103,tT=104,nT=200,iT=201,rT=202,sT=203,aT=204,oT=205,cT=206,lT=207,uT=208,dT=209,fT=210,hT=211,pT=212,mT=213,gT=214,bT=0,xT=1,yT=2,kp=3,_T=4,vT=5,ET=6,TT=7,AT=0,wT=1,ST=2,Ui=0,Dp=1,Lp=2,Fp=3,Xc=4,Up=5,Bp=6,zp=7,So=301,ya=302,ud=303,dd=304,qc=306,Mo=1000,Ro=1001,fd=1002,Bi=1003,hd=1004,_a=1005,En=1006,Io=1007,fr=1008,zi=1009,MT=1010,RT=1011,Jc=1012,Vp=1013,hs=1014,Br=1015,hr=1016,jp=1017,Hp=1018,Co=1020,IT=35902,CT=35899,NT=1021,PT=1022,pr=1023,va=1026,Ea=1027,OT=1028,Gp=1029,Ta=1030,$p=1031,Kp=1033,pd=33776,md=33777,gd=33778,bd=33779,Wp=35840,Xp=35841,qp=35842,Jp=35843,Zp=36196,Yp=37492,Qp=37496,em=37488,tm=37489,xd=37490,nm=37491,im=37808,rm=37809,sm=37810,am=37811,om=37812,cm=37813,lm=37814,um=37815,dm=37816,fm=37817,hm=37818,pm=37819,mm=37820,gm=37821,bm=36492,xm=36494,ym=36495,_m=36283,vm=36284,yd=36285,Em=36286,Tm=2300,_d=2301,Am=0,Zc=1,No=2,wm=0,kT=1,Aa="",ps="srgb",oi="srgb-linear",Sm="linear",Bt="srgb",DT=512,LT=513,FT=514,vd=515,UT=516,BT=517,Ed=518,zT=519,Mm="300 es",Rm=2000,uE,Eo=null,GT,Pn,dE=1234567,Hc,xa,Yc,Ke,ln,j,sp,fE,tt,ap,hE,pE,ot,so,ON=0,kN=0,cp,en,Pt,Nm,ci,Td,Pm,Qe,ao,Oi,DN,LN,is,Lu,si,mE,gE,ur,FN=0,bE,oo,Pr,Fu,Dc,UN,BN,xE,yE,_E,vE,zN,co,lp,Dt,cr,VN,$T,rs,Uu,qe,On,Po,ki,Or,dp,kr,lo,uo,EE,fp,hp,pp,mp,gp,bp,Dr,Di,Bu,fo,ho,po,ss,as,ha,Lc,zu,Vu,pa,cn,ju,jN=0,vn,wd,Sd,Wn,HN,Fc,yp,GN=0,xi,_p,mo,ai,Uc,_n,Dn,Hn,vp,$N,KN,WN=0,Xn,Lr,Ep,Hu,Gu,mr,TE,ma,$u,AE,Ku,Wu,Xu,Tp,qu,wE,Ju,jt,Bc,SE,ME,qN,RE,Yu,Ap,IE,wp,Md,nl,il,CE,JN,ls,go,NE,Qu,PE,ZN,zc,Vc,ko,ga,YN,ed,al,cd,ld,OE,jc,td,Sp,kE,gs,DE,LE,Rd,Id,ol,FE,Ip,id,rd,Do,Cd,wa,Om,Nd,bs,cl,KT,eP=`void main() {+var rI=Object.create;var{getPrototypeOf:sI,defineProperty:Uf,getOwnPropertyNames:aI}=Object;var Db=Object.prototype.hasOwnProperty;function oI(e){return this[e]}var cI,lI,Bf=(e,t,n)=>{var i=e!=null&&typeof e==="object";if(i){var r=t?cI??=new WeakMap:lI??=new WeakMap,s=r.get(e);if(s)return s}n=e!=null?rI(sI(e)):{};let a=t||!e||!e.__esModule||!Db.call(e,"default")?Uf(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let o of aI(e))if(!Db.call(a,o))Uf(a,o,{get:oI.bind(e,o),enumerable:!0})}if(i)r.set(e,a);return a};var Jr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var uI=(e)=>e;function dI(e,t){this[e]=uI.bind(null,t)}var Lb=(e,t)=>{for(var n in t)Uf(e,n,{get:t[n],enumerable:!0,configurable:!0,set:dI.bind(t,n)})};var ht=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(i){n=[i]}if(n)throw n[0];return t};var ir;var Tc=ht(()=>{ir=["albedo","emissive","normal","roughness","metalness","metallicRoughness","occlusion"]});function UC(e){if(e==="PORTABLE_MATERIAL_V3_CONTRACT")return'compilePortableMaterialSpecV3 requires schemaVersion 3, model pbrMetallicRoughness, typed V3 procedural or injected resource references, and complete minFilter/magFilter/wrapS/wrapT samplers. Match texture usage to its slot and split work exceeding the material budget. Resource bindings need a host with verified-byte admission. V2 remains available unchanged. Shader code, paths, raw textures and V3 height derivation are unsupported. Read kiln_discover ids ["compilePortableMaterialSpecV3"] for the exact contract.';if(e==="TEXTURE_ATLAS_CONTRACT")return'textureAtlas requires bounded named integer content rectangles with nonoverlapping gutter allocations, matching source crops and usage, and explicit portable sampling. Sources are V3 recipes or exact host-injected library map pins. Split atlases exceeding aggregate work or allocation budgets. remapUVToAtlas requires finite unit UV0, a named content region, inputOrigin and mapping mode; it preserves topology and does not unwrap or tile a region. Read kiln_discover ids ["textureAtlas", "remapUVToAtlas"] for the exact contracts.';if(e==="PROCEDURAL_TEXTURE_V3_CONTRACT")return'proceduralTexture schemaVersion 3 requires bounded JSON: width/height 4..1024, byte RGBA, integer pixel shapes and at most 64 operations. Palette/dither supports only albedo/emissive; seeded stamps accept every usage. Work includes polygon edges and periodic copies. Read kiln_discover ids ["proceduralTexture"] for the V3 contract; keep schemaVersion 2 for existing opaque patterns.';if(e==="BONE_CHAIN_ARGUMENT")return'createBoneChain requires 1..1024 valid local joint descriptors with unique roles and animation-safe names across the parent hierarchy. Use normalized perpendicular forward/bend axes and finite rest transforms; an explicit parentRole must match the declared parent. Read the retained source and kiln_discover ids ["createBoneChain"] for the exact contract.';if(e==="SKIN_BINDING_ARGUMENT")return'createSkinnedPart requires four valid bone indices and finite nonnegative weights per vertex, summing to one unless normalizeWeights:true is explicit. Zero sums are rejected. Assemble distinct named Bones and the parent in one rest-pose hierarchy before binding. Use unbound geometry within the documented budgets and finite invertible transforms. Read the retained source and kiln_discover ids ["createSkinnedPart"] for the exact contract; the Three exporter is required for skin delivery.';if(e==="EXPORT_MATERIAL_SIDE_UNSUPPORTED")return"EXPORT_MATERIAL_SIDE_UNSUPPORTED: A used material has BackSide, which glTF cannot encode directly. Author inward-facing triangles with FrontSide, or choose DoubleSide when both faces are intended. Neither adds missing geometry. Read the retained program with kiln_source query BackSide to locate the material; source names and exception text do not cross the evaluator boundary.";if(e==="UNINITIALIZED_BINDING")return"A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.";if(e==="LOD_SET")return'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].';if(e==="OPEN_SHELL")return'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].';if(e==="DELIVERY_CONTRACT")return'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws? }) takes positive integers; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].';if(e==="REQUIRE_SOLID")return'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].';if(e==="BUILD_RESULT")return'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.';if(e==="MATERIAL_RECIPE_OVERRIDE")return'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.';if(e==="PROGRAM_TYPE_ERROR")return"The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.";if(e==="PROGRAM_RANGE_ERROR")return"The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.";if(e==="MESH_DATA_NONFINITE")return"meshGeo positions, normals, UVs and tangents must contain finite numbers representable in Float32. Check missing XYZ components, undefined values, division by zero and overflowing calculations before constructing the arrays. Do not replace invalid values blindly with zero; correct the source calculation. Call kiln_discover for the exact meshGeo data contract.";if(e==="PORTABLE_COLOR_ARGUMENT")return"compilePortableMaterialSpecV2 baseColor and emissive must be numeric color integers from 0x000000 to 0xffffff, for example baseColor: 0x8a867c. CSS strings and materialRecipe hex-string overrides use different contracts. Omit these fields for their defaults, or call kiln_discover for the exact helper contract.";if(e==="MATERIAL_RECIPE_TEXTURE_BINDING")return"materialRecipe textureResources maps portable slots to approved resource ID strings. Slots are baseColor, normal, metallicRoughness, emissive and occlusion. albedo is a pbrMaterial field, not a recipe slot. Use kiln_discover to check each resource allowedSlots and recipeIds before binding it; no slot or resource substitution is applied.";if(e==="PORTABLE_TEXTURE_REFERENCE")return'compilePortableMaterialSpecV2 textures require typed references: { kind: "resource", resourceId: "kiln.texture..." } for an approved resource, or { kind: "procedural", spec: { schemaVersion: 2, ... } } for a procedural texture. Bare resource ID strings are invalid here. Use portable slots such as baseColor and check the exact helper/resource contracts with kiln_discover.';if(e==="TAPER_CONE_AXIS")return'taperConeGeo(radiusBottom, radiusTop, height, axis, segments): the fourth argument is axis, "x", "y" or "z" (default "y"). Segment count is the fifth argument, for example taperConeGeo(0.03, 0.02, 0.01, "x", 12). Call kiln_discover for the full contract.';if(e==="PROCEDURAL_TEXTURE_BLEND")return'proceduralTexture layer blend must be normal, multiply, screen, or overlay. Omit blend for normal compositing. Call kiln_discover with ids ["proceduralTexture"] for the supported layer fields.';if(e==="PART_NAME_ARGUMENT")return"createPart(name, geometry, material, options?): the first argument is a string name. Put the parent Object3D in the fourth argument as { parent: root }.";if(e==="PART_GEOMETRY_ARGUMENT")return"createPart(name, geometry, material, options?): the second argument must be a BufferGeometry. Call geometry helpers, for example boxGeo(1, 1, 1), instead of passing the function. For async helpers such as roundedBoxGeo, extrudeProfile and revolveProfile, await the result inside async build() before passing it to createPart. Call kiln_discover for the exact return contract.";if(e==="PART_MATERIAL_ARGUMENT")return"createPart(name, geometry, material, options?): the third argument must be a Three.js material. Wrap a color with gameMaterial(0x808080); a number or settings object alone is not a material. Call kiln_discover for the chosen material helper contract.";if(e==="SOLID_FLOAT32_COLLAPSE")return"Solid output cannot retain valid faces at Float32 precision. Simplify subprecision features or recenter local geometry; review coincident cut boundaries. Smoothing or replacing normals does not repair collapsed triangles. Kiln did not export a partially repaired solid.";if(e==="PROFILE_BEVEL_COLLAPSE")return"extrudeProfile or revolveProfile: bevel is too large for this profile; erosion leaves nothing. Reduce bevel below half the narrowest section width, set bevel to 0, or widen the profile. Dimensions and bevel use the same asset units.";if(e==="TUBE_RADIUS")return"curveToMesh and pipeAlongPath require an explicit positive finite radius representable in Float32, in asset units. A missing or undefined radius is invalid; check the referenced dimension. Radius is half the tube diameter.";if(e==="MATERIAL_ALPHA_MODE")return'pbrMaterial and portable material specs require lowercase alphaMode: "opaque", "mask", or "blend". Omit it for opaque. Exported glTF uses uppercase mode names; those are not authoring input values.';if(e==="MATERIAL_COLOR_ARGUMENT")return"gameMaterial, basicMaterial, glassMaterial and lambertMaterial take a color first: a hex number or CSS string. Settings belong in the second argument, for example gameMaterial(0x9a9a96, { roughness: 0.4, metalness: 0.8 }). pbrMaterial uses a different object-form contract; call kiln_discover for its texture and material fields.";if(e==="MATERIAL_PACKED_CHANNELS")return'pbrMaterial requires one packed texture with G=roughness and B=metalness. Generate or load it for usage "metallicRoughness" and pass metallicRoughness, or pass the same packed texture in both roughness and metalness. Do not combine those forms or pass a texture in only one scalar slot. Plain roughness and metalness values are 0..1 numbers. Call kiln_discover for the exact texture contract.';if(e==="REMOVED_HELPER")return"Generated source references a retired Kiln global. Call kiln_validate for name-specific migration guidance, then kiln_discover for the replacement contract. No compatibility aliases are provided.";if(e==="UNBOUND_VARIABLE")return"Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.";if(e==="ROUNDED_BOX_RADIUS")return"roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.";if(e==="GEAR_RADII_ORDER")return"gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.";if(e==="PROCEDURAL_TEXTURE_UNKNOWN_KEY")return'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.';if(e==="PROCEDURAL_TEXTURE_USAGE")return'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].';if(e==="MATERIAL_FRACTION_RANGE")return"Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.";if(e==="PROFILE_HOLES_UNSUPPORTED")return"loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.";if(e==="PROFILE_CORRESPONDENCE_COLLAPSE")return"loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.";return e==="PARAMETRIC_PERIODIC_ENDPOINT"?"Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.":""}var ua;var Ac=ht(()=>{ua=class ua extends Error{diagnostic;constructor(e,t=UC(e)){super(t);this.diagnostic=e;this.name="AuthoringDiagnosticError"}}});function Ru(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw new yt(`${t} must be a plain JSON object.`);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new yt(`${t} must be a plain JSON object with no custom prototype.`);for(let i of Reflect.ownKeys(e)){if(typeof i!=="string")throw new yt(`${t} must not contain symbol keys.`);if(BC.has(i))throw new yt(`${t} contains forbidden key ${JSON.stringify(i)}.`);if(!Object.prototype.propertyIsEnumerable.call(e,i))throw new yt(`${t}.${i} must be an enumerable JSON field.`);let r=Object.getOwnPropertyDescriptor(e,i);if(!r||!("value"in r))throw new yt(`${t}.${i} must be a plain JSON data field.`)}return e}function zC(e,t){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)throw new yt(`${t} must be a plain JSON array.`);for(let n of Reflect.ownKeys(e)){if(typeof n!=="string")throw new yt(`${t} must not contain symbol keys.`);if(n==="length")continue;if(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=e.length)throw new yt(`${t} has non-index JSON array key ${JSON.stringify(n)}.`)}for(let n=0;n<e.length;n++)if(!Object.hasOwn(e,n))throw new yt(`${t} must be a dense JSON array (missing index ${n}).`);return e}function ts(e,t,n){let i=new Set(t);for(let r of Object.keys(e))if(!i.has(r))throw new yt(`${n} has unknown key ${JSON.stringify(r)}.`,"PROCEDURAL_TEXTURE_UNKNOWN_KEY")}function Ni(e,t,n){if(typeof e!=="number"||!Number.isInteger(e)||e<0||e>16777215)throw new yt(`${t} must be a color integer between 0x000000 and 0xffffff, got ${JSON.stringify(e)}.`,n);return e}function da(e,t,n,i,r){if(e===void 0)return n;if(typeof e!=="number"||!Number.isInteger(e)||e<i||e>r)throw new yt(`${t} must be a whole number between ${i} and ${r}, got ${JSON.stringify(e)}.`);return e}function U0(e,t,n,i,r,s){if(e===void 0)return n;if(typeof e!=="number"||!Number.isFinite(e)||e<i||e>r)throw new yt(`${t} must be a finite number between ${i} and ${r}, got ${JSON.stringify(e)}.`,s);return e}function qh(e,t,n){return U0(e,t,n,0,1,"MATERIAL_FRACTION_RANGE")}function VC(e,t){if(e===void 0)return;let n=typeof e==="string"&&[...e].some((i)=>{let r=i.charCodeAt(0);return r<32||r===127});if(typeof e!=="string"||e.length===0||e.length>k0||n)throw new yt(`${t} must be 1..${k0} visible characters.`);return e}function jC(e,t,n){if(e===void 0)return n;if(!ir.includes(e))throw new yt(`${t} must be one of ${ir.join(", ")}, got ${JSON.stringify(e)}.`,"PROCEDURAL_TEXTURE_USAGE");return e}function F0(e,t){let i=(U0(e,t,0,-36000,36000)%360+360)%360;return Object.is(i,-0)?0:i}function HC(e,t){let n=e.blend??"normal";if(!L0.includes(n))throw new yt(`${t}.blend ${JSON.stringify(n)} is not one of ${L0.join(", ")}.`,"PROCEDURAL_TEXTURE_BLEND");return n}function GC(e,t){let n=`proceduralTexture.layers[${t}]`,i=Ru(e,n),r=i.op;if(!D0.includes(r))throw new yt(`${n}.op ${JSON.stringify(r)} is not one of ${D0.join(", ")}.`);let s=HC(i,n),a=qh(i.opacity,`${n}.opacity`,1),o={blend:t===0?"normal":s,opacity:t===0?1:a};switch(r){case"solid":return ts(i,["op","color","blend","opacity"],n),{op:r,color:Ni(i.color,`${n}.color`),...o};case"checker":return ts(i,["op","colorA","colorB","squares","blend","opacity"],n),{op:r,colorA:Ni(i.colorA,`${n}.colorA`),colorB:Ni(i.colorB,`${n}.colorB`),squares:da(i.squares,`${n}.squares`,8,1,fa),...o};case"stripes":return ts(i,["op","colorA","colorB","count","angleDeg","blend","opacity"],n),{op:r,colorA:Ni(i.colorA,`${n}.colorA`),colorB:Ni(i.colorB,`${n}.colorB`),count:da(i.count,`${n}.count`,8,1,fa),angleDeg:F0(i.angleDeg,`${n}.angleDeg`),...o};case"gradient":return ts(i,["op","from","to","angleDeg","blend","opacity"],n),{op:r,from:Ni(i.from,`${n}.from`),to:Ni(i.to,`${n}.to`),angleDeg:F0(i.angleDeg,`${n}.angleDeg`),...o};case"bricks":return ts(i,["op","brick","mortar","rows","cols","mortarWidth","stagger","blend","opacity"],n),{op:r,brick:Ni(i.brick,`${n}.brick`),mortar:Ni(i.mortar,`${n}.mortar`),rows:da(i.rows,`${n}.rows`,8,1,fa),cols:da(i.cols,`${n}.cols`,4,1,fa),mortarWidth:qh(i.mortarWidth,`${n}.mortarWidth`,0.06),stagger:qh(i.stagger,`${n}.stagger`,0.5),...o};case"noise":return ts(i,["op","colorA","colorB","scale","octaves","seed","blend","opacity"],n),{op:r,colorA:Ni(i.colorA,`${n}.colorA`),colorB:Ni(i.colorB,`${n}.colorB`),scale:da(i.scale,`${n}.scale`,8,1,fa),octaves:da(i.octaves,`${n}.octaves`,3,1,Jh),seed:da(i.seed,`${n}.seed`,0,-2147483648,2147483647),...o};default:throw new yt(`${n}.op is unsupported.`)}}function $C(e){let t=Ru(e,"proceduralTexture");if(ts(t,["schemaVersion","size","usage","name","layers"],"proceduralTexture"),t.schemaVersion!==void 0&&t.schemaVersion!==1)throw new yt(`proceduralTexture.schemaVersion must be 1 or absent for V1 migration, got ${JSON.stringify(t.schemaVersion)}.`);return{schemaVersion:2,...t.size!==void 0?{size:t.size}:{},...t.usage!==void 0?{usage:t.usage}:{},...t.name!==void 0?{name:t.name}:{},layers:t.layers}}function wc(e){let t=Ru(e,"proceduralTexture"),n=t.schemaVersion===void 0||t.schemaVersion===1?Ru($C(t),"proceduralTexture"):t;if(ts(n,["schemaVersion","size","usage","name","layers"],"proceduralTexture"),n.schemaVersion!==2)throw new yt(`proceduralTexture.schemaVersion must be 2, got ${JSON.stringify(n.schemaVersion)}.`);let i=n.size??256;if(typeof i!=="number"||!Number.isInteger(i)||i<Su||i>wu||(i&i-1)!==0)throw new yt(`proceduralTexture.size must be a power of two between ${Su} and ${wu}, got ${JSON.stringify(n.size)}.`);let r=n.layers;if(!Array.isArray(r)||r.length===0)throw new yt("proceduralTexture.layers must be a non-empty array — the bottom layer is the base pattern.");let s=zC(r,"proceduralTexture.layers");if(s.length>Mu)throw new yt(`proceduralTexture: ${s.length} layers exceeds the maximum of ${Mu}.`);let a=VC(n.name,"proceduralTexture.name");return{schemaVersion:2,size:i,usage:jC(n.usage,"proceduralTexture.usage","albedo"),...a!==void 0?{name:a}:{},layers:s.map(GC)}}function qa(e){let t=new TextEncoder().encode(e),n=t.length*8,i=Math.ceil((t.length+9)/64)*64,r=new Uint8Array(i);r.set(t),r[t.length]=128;let s=new DataView(r.buffer);s.setUint32(i-8,Math.floor(n/4294967296),!1),s.setUint32(i-4,n>>>0,!1);let a=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64);for(let c=0;c<r.length;c+=64){for(let x=0;x<16;x++)o[x]=s.getUint32(c+x*4,!1);for(let x=16;x<64;x++){let _=o[x-15],y=o[x-2],v=rr(_,7)^rr(_,18)^_>>>3,E=rr(y,17)^rr(y,19)^y>>>10;o[x]=o[x-16]+v+o[x-7]+E>>>0}let[l,u,d,f,h,b,m,g]=a;for(let x=0;x<64;x++){let _=rr(h,6)^rr(h,11)^rr(h,25),y=h&b^~h&m,v=g+_+y+KC[x]+o[x]>>>0,E=rr(l,2)^rr(l,13)^rr(l,22),w=l&u^l&d^u&d,T=E+w>>>0;g=m,m=b,b=h,h=f+v>>>0,f=d,d=u,u=l,l=v+T>>>0}let p=[l,u,d,f,h,b,m,g];for(let x=0;x<8;x++)a[x]=a[x]+p[x]>>>0}return[...a].map((c)=>c.toString(16).padStart(8,"0")).join("")}var wu=1024,Su=4,Mu=8,Jh=6,k0=80,fa=256,yt,D0,L0,BC,KC,rr=(e,t)=>e>>>t|e<<32-t;var Ja=ht(()=>{Tc();Ac();yt=class yt extends ua{constructor(e,t){super(t,e);this.name="ProceduralTextureError"}};D0=["solid","checker","stripes","gradient","bricks","noise"],L0=["normal","multiply","screen","overlay"],BC=new Set(["__proto__","prototype","constructor"]);KC=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])});function bt(e,t="PROCEDURAL_TEXTURE_V3_CONTRACT"){throw new yt(`proceduralTexture V3: ${e}`,t)}function JC(e){let t=0,n=(i,r,s)=>{if(++t>16384||s>10)bt(`${r} exceeds the JSON size/depth budget.`);if(i===null||typeof i==="boolean")return;if(typeof i==="string"){if(i.length>4096)bt(`${r} string is too long.`);return}if(typeof i==="number"){if(!Number.isFinite(i))bt(`${r} must be finite.`);return}if(typeof i!=="object")bt(`${r} must contain only JSON data.`);let a=Array.isArray(i),o=Object.getPrototypeOf(i);if(a?o!==Array.prototype:o!==Object.prototype&&o!==null)bt(`${r} must be a plain JSON ${a?"array":"object"}.`);let c=a?Object.getOwnPropertyDescriptor(i,"length")?.value:void 0;if(a&&(typeof c!=="number"||c>1024))bt(`${r} array is too long.`);let l=Reflect.ownKeys(i);if(l.length>1024)bt(`${r} has too many fields.`);let u=Object.getOwnPropertyDescriptors(i);for(let d of l){if(typeof d!=="string"||qC.has(d))bt(`${r} has a forbidden key.`);if(a&&d==="length")continue;let f=u[d];if(!f.enumerable||!("value"in f))bt(`${r}.${d} must be an enumerable JSON data field, never an accessor.`);if(a&&(!/^(0|[1-9][0-9]*)$/.test(d)||Number(d)>=c))bt(`${r} has an invalid array key.`)}if(a&&l.length!==c+1)bt(`${r} must be a dense JSON array.`);for(let d of l)if(d!=="length"||!a)n(u[d].value,`${r}.${String(d)}`,s+1)};n(e,"recipe",0)}function bi(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))bt(`${n} must be a JSON object.`);let i=e;for(let r of Object.keys(i))if(!t.includes(r))bt(`${n} has unknown field ${r}.`);return i}function jn(e,t,n,i,r){if(e===void 0&&r!==void 0)return r;if(typeof e!=="number"||!Number.isInteger(e)||e<t||e>n)bt(`${i} must be an integer ${t}..${n}.`);return e===0?0:e}function z0(e,t){if(e===void 0)return!1;if(typeof e!=="boolean")bt(`${t} must be boolean.`);return e}function Iu(e,t,n,i,r){if(!Array.isArray(e)||e.length!==t)bt(`${n} must be a ${t}-element array.`);return e.map((s,a)=>jn(s,i,r,`${n}[${a}]`))}function V0(e,t){let n=Iu(e,4,t,0,255);return n[3]===0?[0,0,0,0]:n}function j0(e,t,n){let i=bi(e,["x","y","width","height",...n?["kind"]:[]],t);return{x:jn(i.x,-4096,4096,`${t}.x`),y:jn(i.y,-4096,4096,`${t}.y`),width:jn(i.width,1,2048,`${t}.width`),height:jn(i.height,1,2048,`${t}.height`)}}function ZC(e,t){let n=bi(e,["kind","x","y","width","height","from","to","points"],t);if(n.kind==="rectangle"||n.kind==="ellipse")return{kind:n.kind,...j0(n,t,n.kind)};if(n.kind==="polygon"){bi(n,["kind","points"],t);let i=n.points;if(!Array.isArray(i)||i.length<3||i.length>Cu)bt(`${t}.points requires 3..${Cu} vertices.`);return{kind:"polygon",points:i.map((r,s)=>Iu(r,2,`${t}.points[${s}]`,-4096,4096))}}if(n.kind==="line")return bi(n,["kind","from","to","width"],t),{kind:"line",from:Iu(n.from,2,`${t}.from`,-4096,4096),to:Iu(n.to,2,`${t}.to`,-4096,4096),width:jn(n.width,1,2048,`${t}.width`)};return bt(`${t}.kind must be rectangle, ellipse, polygon or line.`)}function H0(e){if(e.kind==="rectangle"||e.kind==="ellipse")return[e.x,e.y,e.x+e.width,e.y+e.height];let t=e.kind==="polygon"?e.points:[e.from,e.to],n=e.kind==="line"?e.width/2:0;return[Math.min(...t.map((i)=>i[0]))-n,Math.min(...t.map((i)=>i[1]))-n,Math.max(...t.map((i)=>i[0]))+n,Math.max(...t.map((i)=>i[1]))+n]}function YC(e){return e.kind==="polygon"?e.points.length+1:e.kind==="line"?4:e.kind==="ellipse"?3:1}function QC(e,t,n,i=0,r=0){let[s,a,o,c]=H0(e);return[Math.max(0,Math.ceil(s+i-0.5)),Math.max(0,Math.ceil(a+r-0.5)),Math.min(t,Math.floor(o+i-0.5)+1),Math.min(n,Math.floor(c+r-0.5)+1)]}function Pu(e){JC(e);let t=bi(e,["schemaVersion","width","height","usage","name","background","operations","palette"],"recipe");if(t.schemaVersion!==3)bt("schemaVersion must be 3.");let n=jn(t.width,4,Mc,"width"),i=jn(t.height,4,Mc,"height"),r=n*i;if(r>WC)bt("output texel budget exceeded.");let s=t.usage===void 0?"albedo":t.usage;if(!ir.includes(s))bt("usage must be a known texture usage.","PROCEDURAL_TEXTURE_USAGE");let a=s==="albedo"||s==="emissive",o=t.name;if(o!==void 0&&(typeof o!=="string"||!o.length||o.length>80||[...o].some((g)=>g.charCodeAt(0)<32||g.charCodeAt(0)===127)))bt("name must be 1..80 visible characters.");let c=t.operations;if(!Array.isArray(c)||c.length>Rc)bt(`operations must be an array with at most ${Rc} entries.`);let l=r,u=0,d=0,f=c.map((g,p)=>{let x=`operations[${p}]`,_=bi(g,["op","shape","rgba","opacity","alpha","invert","spec","count","seed","area","periodic"],x);if(_.op==="legacy-v2"){bi(_,["op","spec","alpha","opacity"],x);let K=bi(_.spec,["schemaVersion","size","usage","name","layers"],`${x}.spec`);if(K.schemaVersion!==2)bt(`${x}.spec requires explicit schemaVersion 2.`);let B=wc(K);if(B.size!==n||B.size!==i||B.usage!==s)bt(`${x} legacy-v2 dimensions and usage must match the V3 surface.`);return l+=r*(1+B.layers.reduce((X,q)=>X+(q.op==="noise"?q.octaves*16:4),0)),d+=r*4,{op:"legacy-v2",spec:B,alpha:jn(_.alpha,0,255,`${x}.alpha`,255),opacity:jn(_.opacity,0,255,`${x}.opacity`,255)}}let y=ZC(_.shape,`${x}.shape`),v=YC(y),[E,w,T,A]=QC(y,n,i),P=Math.max(0,T-E)*Math.max(0,A-w);if(_.op==="mask")return bi(_,["op","shape","alpha","invert"],x),l+=r+P*v,{op:"mask",shape:y,alpha:jn(_.alpha,0,255,`${x}.alpha`,255),invert:z0(_.invert,`${x}.invert`)};if(_.op!=="paint"&&_.op!=="stamps")return bt(`${x}.op must be paint, mask, stamps or legacy-v2.`);let S={shape:y,rgba:V0(_.rgba,`${x}.rgba`),opacity:jn(_.opacity,0,255,`${x}.opacity`,255)};if(_.op==="paint")return bi(_,["op","shape","rgba","opacity"],x),l+=P*(v+1),{op:"paint",...S};bi(_,["op","shape","rgba","opacity","count","seed","area","periodic"],x);let R=jn(_.count,1,Sc,`${x}.count`),k=z0(_.periodic,`${x}.periodic`),[C,U,L,O]=H0(y);if(k&&(L-C>n||O-U>i))bt(`${x} periodic shape bounds must fit one surface period.`);if(u+=R*(k?9:1),u>Sc)bt(`expanded stamps budget exceeds ${Sc}.`);return l+=R*(k?9:1)*Math.min(n,Math.ceil(L-C)+1)*Math.min(i,Math.ceil(O-U)+1)*(v+1),{op:"stamps",...S,count:R,seed:jn(_.seed,0,4294967295,`${x}.seed`),area:j0(_.area,`${x}.area`),periodic:k}}),h;if(t.palette!==void 0){if(!a)bt("palette and dither are supported only for color usages albedo and emissive.");let g=bi(t.palette,["colors","dither"],"palette"),p=g.colors;if(!Array.isArray(p)||p.length<1||p.length>Nu)bt(`palette.colors requires 1..${Nu} entries.`);let x=g.dither===void 0?"none":g.dither;if(x!=="none"&&x!=="bayer4")bt("palette.dither must be none or bayer4.");h={colors:p.map((_,y)=>jn(_,0,16777215,`palette.colors[${y}]`)),dither:x},l+=r*(p.length+1)}if(l>B0)bt(`estimated work budget ${l} exceeds ${B0}.`);if(r*4+d>XC)bt("transient allocation budget exceeded.");let b={schemaVersion:3,width:n,height:i,usage:s,...o!==void 0?{name:o}:{},background:t.background===void 0?[0,0,0,0]:V0(t.background,"background"),operations:f,...h?{palette:h}:{}},m=JSON.stringify(b);if(m.length>262144)bt("canonical JSON byte budget exceeded.");return{spec:b,canonicalJson:m,estimatedWorkUnits:l,conservativePixelAllocationBytes:r*4+d}}function Zh(e){return Pu(e).spec}function eN(e){return Pu(e).canonicalJson}function Yh(e){return`sha256:${qa(`${Za}+${eN(e)}`)}`}var Za="kiln.procedural-rgba.v3.1",Mc=1024,WC=1048576,Rc=64,Cu=64,Sc=256,Nu=32,B0=64000000,XC=67108864,qC;var Ou=ht(()=>{Ja();Tc();qC=new Set(["__proto__","prototype","constructor"])});function ku(e){if(!e||typeof e!=="object"||Array.isArray(e))throw new yt("portableSampler requires a complete JSON object.");let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new yt("portableSampler must be plain JSON data.");for(let r of Reflect.ownKeys(e)){let s=Object.getOwnPropertyDescriptor(e,r);if(typeof r!=="string"||!s.enumerable||!("value"in s))throw new yt("portableSampler requires enumerable JSON data fields, never accessors.")}let n=e,i={minFilter:Qh,magFilter:ep,wrapS:Ic,wrapT:Ic};if(Object.keys(n).some((r)=>!Object.hasOwn(i,r)))throw new yt("portableSampler contains an unsupported field.");for(let[r,s]of Object.entries(i))if(!s.includes(n[r]))throw new yt(`portableSampler.${r} requires one of ${s.join(", ")}.`);return{minFilter:n.minFilter,magFilter:n.magFilter,wrapS:n.wrapS,wrapT:n.wrapT}}var Qh,ep,Ic;var Du=ht(()=>{Ja();Qh=["nearest","linear","nearest-mipmap-nearest","linear-mipmap-nearest","nearest-mipmap-linear","linear-mipmap-linear"],ep=["nearest","linear"],Ic=["repeat","clamp-to-edge","mirrored-repeat"]});function X0(e){return e.pack===void 0?K0:W0}function tN(e){return e.pack===void 0?ha:Nr}function He(e){throw new q0(e)}function ip(e){let t=0,n=0,i=new TextEncoder,r=(a)=>{if(n+=a,n>ha.jsonBytes)He("JSON byte budget exceeded.")},s=(a,o)=>{if(++t>65536||o>16)He("JSON node/depth budget exceeded.");if(a===null||typeof a==="boolean"){r(a===!1?5:4);return}if(typeof a==="number"){if(!Number.isFinite(a))He("JSON numbers must be finite.");r(JSON.stringify(a).length);return}if(typeof a==="string"){if(a.length>4096)He("JSON string budget exceeded.");r(i.encode(JSON.stringify(a)).length);return}if(typeof a!=="object")He("plain JSON data is required.");let c=Array.isArray(a),l=Object.getPrototypeOf(a);if(c?l!==Array.prototype:l!==null&&l!==Object.prototype)He("plain JSON prototypes are required.");let u=c?Object.getOwnPropertyDescriptor(a,"length")?.value:void 0;if(c&&(!Number.isSafeInteger(u)||u>1024))He("JSON array budget exceeded.");let d=Reflect.ownKeys(a);if(d.length>1024||c&&d.length!==u+1)He("dense bounded JSON fields are required.");r(2+Math.max(0,d.length-(c?1:0)-1));for(let f of d){if(c&&f==="length")continue;if(typeof f!=="string"||["__proto__","prototype","constructor"].includes(f))He("forbidden JSON field.");if(f.length>4096)He("JSON field name budget exceeded.");if(!c)r(i.encode(JSON.stringify(f)).length+1);let h=Object.getOwnPropertyDescriptor(a,f);if(!h.enumerable||!("value"in h))He("JSON accessors/hidden fields are unsupported.");if(c&&(!/^(0|[1-9][0-9]*)$/.test(f)||Number(f)>=u))He("invalid JSON array key.");s(h.value,o+1)}};s(e,0)}function Hn(e,t,n){if(!e||typeof e!=="object"||Array.isArray(e))He(`${n} must be a JSON object.`);let i=e;if(Object.keys(i).some((r)=>!t.includes(r)))He(`${n} has an unknown field.`);return i}function si(e,t,n,i){if(typeof e!=="number"||!Number.isSafeInteger(e)||e<t||e>n)He(`${i} must be an integer ${t}..${n}.`);return e===0?0:e}function ns(e,t){if(typeof e!=="string"||!/^sha256:[a-f0-9]{64}$/.test(e))He(`${t} must be an exact SHA-256 hash.`);return e}function G0(e,t){let n=Hn(e,["x","y","width","height"],t);return{x:si(n.x,0,4096,`${t}.x`),y:si(n.y,0,4096,`${t}.y`),width:si(n.width,1,4096,`${t}.width`),height:si(n.height,1,4096,`${t}.height`)}}function Ya(e){let{content:t,gutter:n}=e;return{x:t.x-n,y:t.y-n,width:t.width+2*n,height:t.height+2*n}}function J0(e,t,n,i){if(e.x+e.width>n||e.y+e.height>i)He("source crop is out of bounds.");if(e.width!==t.width||e.height!==t.height)He("source crop/content dimensions must match; resampling is unsupported.")}function tp(e){return e.kind==="procedural"?`procedural:${Yh(e.spec)}`:`resource:${e.pin.resourceId}:${e.pin.revisionId}:${e.resourceId}`}function iN(e,t,n,i){let r=[{x:0,y:0,width:e,height:t}],s=(o)=>{let c=[];for(let l of r){if(!nN(l,o)){c.push(l);continue}if(o.x>l.x)c.push({x:l.x,y:l.y,width:o.x-l.x,height:l.height});if(o.x+o.width<l.x+l.width)c.push({x:o.x+o.width,y:l.y,width:l.x+l.width-o.x-o.width,height:l.height});if(o.y>l.y)c.push({x:l.x,y:l.y,width:l.width,height:o.y-l.y});if(o.y+o.height<l.y+l.height)c.push({x:l.x,y:o.y+o.height,width:l.width,height:l.y+l.height-o.y-o.height})}if(r=c.filter((l,u)=>!c.some((d,f)=>f!==u&&$0(d,l)&&(!$0(l,d)||f<u))),r.length>16384)He("pack: free-space bookkeeping budget exceeded.")};for(let o of n)s(o);let a=[...i].sort((o,c)=>c.width*c.height-o.width*o.height||(o.region.name<c.region.name?-1:o.region.name>c.region.name?1:0));for(let o of a){let c,l;for(let u of r){if(u.width<o.width||u.height<o.height)continue;let d=u.width-o.width,f=u.height-o.height,h=[Math.min(d,f),Math.max(d,f),u.y,u.x];if(!l||h[0]<l[0]||h[0]===l[0]&&(h[1]<l[1]||h[1]===l[1]&&(h[2]<l[2]||h[2]===l[2]&&h[3]<l[3])))c=u,l=h}if(!c)He(`pack: region ${o.region.name} (${o.width}x${o.height} texels with its gutter) does not fit in the ${e}x${t} atlas beside the regions already placed.`);o.region.content={x:c.x+o.region.gutter,y:c.y+o.region.gutter,width:o.region.content.width,height:o.region.content.height},s({x:c.x,y:c.y,width:o.width,height:o.height})}}function pa(e){ip(e);let t=Hn(e,["schemaVersion","width","height","usage","sampler","regions","pack"],"atlas");if(t.schemaVersion!==1)He("schemaVersion must be 1.");let n;if(t.pack!==void 0){let f=Hn(t.pack,["edge","gutter","algorithm"],"pack");if(!np.includes(f.edge))He("pack.edge must be 1024 or 2048.");if(f.algorithm!==void 0&&f.algorithm!=="maxrects")He("pack.algorithm must be 'maxrects'.");n={edge:f.edge,gutter:f.gutter===void 0?2:si(f.gutter,0,32,"pack.gutter"),algorithm:"maxrects"}}let i=n?Nr:ha,r=n?n.edge:i.edge,s=n&&t.width===void 0?n.edge:si(t.width,4,r,"width"),a=n&&t.height===void 0?n.edge:si(t.height,4,r,"height");if(s*a>i.outputTexels)He("output texel budget exceeded.");if(!ir.includes(t.usage))He("usage must be a texture usage.");let o=t.usage;if(!Array.isArray(t.regions)||!t.regions.length||t.regions.length>i.regions)He(`regions must contain 1..${i.regions} entries.`);let c=[],l=t.regions.map((f,h)=>{let b=Hn(f,["name","content","gutter","edgeMode","source","crop","packed"],`regions[${h}]`);if(typeof b.name!=="string"||!/^[a-z][a-z0-9_-]{0,79}$/.test(b.name))He("region name must be a stable lowercase identifier.");let m=b.content!==void 0;if(!m&&!n)He(`region ${b.name}: content is required unless the atlas sets pack.`);if(b.packed!==void 0&&(b.packed!==!0||!n||!m))He("packed is the resolved-placement marker: true, with content, in an atlas that sets pack.");let g=m?G0(b.content,"content"):void 0,p=b.gutter===void 0?n?.gutter??2:si(b.gutter,0,32,"gutter"),x=b.edgeMode===void 0?"copy-edge":b.edgeMode;if(!["copy-edge","mask-rgb-dilate"].includes(x))He("unsupported edgeMode.");if(x==="mask-rgb-dilate"&&o!=="albedo"&&o!=="emissive")He("mask RGB dilation requires color usage.");let _=Hn(b.source,["kind","spec","resourceId","pin","expected"],"source"),y,v=b.crop===void 0?void 0:G0(b.crop,"crop");if(_.kind==="procedural"){Hn(_,["kind","spec"],"procedural source");let w=Pu(_.spec);if(w.spec.usage!==o)He("source usage does not match atlas usage.");y={kind:"procedural",spec:w.spec},v??={x:0,y:0,width:w.spec.width,height:w.spec.height},g??={x:0,y:0,width:v.width,height:v.height},J0(v,g,w.spec.width,w.spec.height)}else if(_.kind==="resource"){if(Hn(_,["kind","resourceId","pin","expected"],"resource source"),typeof _.resourceId!=="string"||!/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/.test(_.resourceId))He("source resourceId must be an exact returned map ID.");let w=Hn(_.pin,["resourceId","revisionId","sha256"],"source pin");if(typeof w.resourceId!=="string"||!/^[a-z][a-z0-9_-]{0,79}$/.test(w.resourceId))He("pin resourceId must be a material ID.");let T=ns(w.revisionId,"pin revisionId"),A=ns(w.sha256,"pin sha256");if(T!==A)He("source pin revision/hash mismatch.");let P;if(_.expected!==void 0){let S=Hn(_.expected,["width","height","imageSha256","decodedPixelHash"],"source expected");P={...S.width===void 0?{}:{width:si(S.width,1,4096,"expected.width")},...S.height===void 0?{}:{height:si(S.height,1,4096,"expected.height")},...S.imageSha256===void 0?{}:{imageSha256:ns(S.imageSha256,"expected.imageSha256")},...S.decodedPixelHash===void 0?{}:{decodedPixelHash:ns(S.decodedPixelHash,"expected.decodedPixelHash")}}}if(y={kind:"resource",resourceId:_.resourceId,pin:{resourceId:w.resourceId,revisionId:T,sha256:A},...P?{expected:P}:{}},!g){let S=v??(P?.width!==void 0&&P.height!==void 0?{width:P.width,height:P.height}:He(`region ${b.name}: a packed resource region needs a crop or expected width and height (its size).`));g={x:0,y:0,width:S.width,height:S.height}}if(v&&(v.width!==g.width||v.height!==g.height))He("source crop/content dimensions must match; resampling is unsupported.")}else He("source kind must be procedural or pinned resource.");let E={name:b.name,content:g,gutter:p,edgeMode:x,source:y,...v?{crop:v}:{},...n&&(!m||b.packed===!0)?{packed:!0}:{}};if(!m)c.push({region:E,width:E.content.width+2*p,height:E.content.height+2*p});return E}).sort((f,h)=>f.name<h.name?-1:f.name>h.name?1:0);if(new Set(l.map((f)=>f.name)).size!==l.length)He("duplicate region name.");if(c.length){let f=new Set(c.map((h)=>h.region));iN(s,a,l.filter((h)=>!f.has(h)).map((h)=>Ya(h)),c)}for(let f of l){let h=Ya(f);if(h.x<0||h.y<0||h.x+h.width>s||h.y+h.height>a)He("padded allocation is out of bounds.")}for(let f=0;f<l.length;f++)for(let h=f+1;h<l.length;h++){let b=Ya(l[f]),m=Ya(l[h]);if(b.x<m.x+m.width&&m.x<b.x+b.width&&b.y<m.y+m.height&&m.y<b.y+b.height)He(`padded allocations overlap: ${l[f].name}, ${l[h].name}.`)}if(new Set(l.map((f)=>tp(f.source))).size>i.sources)He(`distinct source budget exceeds ${i.sources}.`);let u;try{u=ku(t.sampler===void 0?{minFilter:"linear-mipmap-linear",magFilter:"linear",wrapS:"clamp-to-edge",wrapT:"clamp-to-edge"}:t.sampler)}catch(f){He(`sampler: ${f.message}`)}let d={schemaVersion:1,width:s,height:a,usage:o,sampler:u,regions:l,...n?{pack:n}:{}};if(new TextEncoder().encode(JSON.stringify(d)).length>ha.jsonBytes)He("canonical JSON byte budget exceeded.");return d}function rN(e){let t=pa(e);return`sha256:${qa(`${X0(t)}+${JSON.stringify(t)}`)}`}function Rn(e){ip(e);let t=(n)=>Array.isArray(n)?n.map(t):n!==null&&typeof n==="object"?Object.fromEntries(Object.entries(n).sort(([i],[r])=>i<r?-1:i>r?1:0).map(([i,r])=>[i,t(r)])):n;return JSON.stringify(t(e))}function sN(e){return`sha256:${qa(`kiln.atlas-layout.v1+${Rn({width:e.width,height:e.height,origin:"top-left",regions:e.regions.map((t)=>({name:t.name,content:t.content,allocation:Ya(t)}))})}`)}`}function Cc(e,t){ip(e);let n=pa(t),i=Hn(e,["version","compilerId","width","height","usage","origin","sampler","specHash","layoutHash","decodedPixelHash","atlasPixelHash","sources","regions","manifestHash"],"manifest");if(i.version!=="kiln.atlas-manifest.v1"||i.compilerId!==X0(n)||i.width!==n.width||i.height!==n.height||i.usage!==n.usage||i.origin!=="top-left")He("manifest version/compiler/dimensions/usage/origin mismatch.");if(Rn(i.sampler)!==Rn(n.sampler)||i.specHash!==rN(n)||i.layoutHash!==sN(n))He("manifest sampler/spec/layout identity mismatch.");ns(i.decodedPixelHash,"manifest decodedPixelHash"),ns(i.atlasPixelHash,"manifest atlasPixelHash");let r=new Map(n.regions.map((c)=>[tp(c.source),c.source]));if(!Array.isArray(i.sources)||i.sources.length!==r.size||!Array.isArray(i.regions)||i.regions.length!==n.regions.length)He("manifest source/region inventory mismatch.");let s=new Map;for(let c of i.sources){let l=Hn(c,["id","kind","width","height","decodedPixelHash","recipeHash","compilerId","descriptor"],"manifest source");if(typeof l.id!=="string"||s.has(l.id))He("duplicate/invalid manifest source identity.");let u=r.get(l.id);if(!u||l.kind!==u.kind)He("manifest source identity mismatch.");let d=si(l.width,1,4096,"manifest source width"),f=si(l.height,1,4096,"manifest source height");if(ns(l.decodedPixelHash,"manifest source decodedPixelHash"),u.kind==="procedural"){if(Hn(l,["id","kind","width","height","decodedPixelHash","recipeHash","compilerId"],"manifest procedural source"),d!==u.spec.width||f!==u.spec.height||l.recipeHash!==Yh(u.spec)||l.compilerId!=="kiln.procedural-rgba.v3.1")He("manifest procedural source identity mismatch.")}else{Hn(l,["id","kind","width","height","decodedPixelHash","descriptor"],"manifest resource source");let h=Hn(l.descriptor,["materialId","revisionId","resourceId","slot","usage","colorSpace","width","height","encodedByteLength","imageSha256","decodedPixelHash"],"manifest source descriptor"),b={baseColor:"albedo",normal:"normal",metallicRoughness:"metallicRoughness",emissive:"emissive",occlusion:"occlusion"};if(h.materialId!==u.pin.resourceId||h.revisionId!==u.pin.revisionId||h.resourceId!==u.resourceId||h.width!==d||h.height!==f||h.usage!==n.usage||typeof h.slot!=="string"||b[h.slot]!==n.usage||h.colorSpace!==(n.usage==="albedo"||n.usage==="emissive"?"srgb":"linear"))He("manifest pinned resource descriptor mismatch.");if(ns(h.imageSha256,"manifest source imageSha256"),si(h.encodedByteLength,1,tN(n).encodedSourceBytes,"manifest encodedByteLength"),h.decodedPixelHash!==void 0&&h.decodedPixelHash!==l.decodedPixelHash)He("manifest source decodedPixelHash mismatch.");for(let m of["width","height","imageSha256","decodedPixelHash"]){let g=u.expected?.[m];if(g!==void 0&&g!==(m==="decodedPixelHash"?l[m]:h[m]))He("manifest source expectation mismatch.")}}s.set(l.id,{width:d,height:f})}for(let c=0;c<n.regions.length;c++){let l=n.regions[c],u=Hn(i.regions[c],["name","content","allocation","crop","sourceId"],"manifest region"),d=tp(l.source),f=s.get(d),h=l.crop??{x:0,y:0,width:f.width,height:f.height};if(J0(h,l.content,f.width,f.height),u.name!==l.name||u.sourceId!==d||Rn(u.content)!==Rn(l.content)||Rn(u.allocation)!==Rn(Ya(l))||Rn(u.crop)!==Rn(h))He("manifest named region/crop/allocation identity mismatch.")}let{manifestHash:a,...o}=i;if(a!==`sha256:${qa(`kiln.atlas-manifest.v1+${Rn(o)}`)}`)He("manifest hash mismatch.");return structuredClone(e)}var K0="kiln.texture-atlas.v1.1",W0="kiln.texture-atlas.v1.2",Lu,ha,Nr,np,q0,nN=(e,t)=>e.x<t.x+t.width&&t.x<e.x+e.width&&e.y<t.y+t.height&&t.y<e.y+e.height,$0=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height;var Fu=ht(()=>{Du();Ou();Ja();Tc();Ac();Lu=Object.freeze([K0,W0]),ha=Object.freeze({edge:1024,outputTexels:1048576,regions:64,sources:16,sourceTexels:4194304,encodedSourceBytes:8388608,encodedBytes:16777216,jsonBytes:262144,work:64000000,allocatedBytes:67108864,uvVertices:262144,uvAttributeBytes:134217728}),Nr=Object.freeze({...ha,edge:2048,outputTexels:4194304,regions:128,sources:32,work:192000000,allocatedBytes:134217728}),np=Object.freeze([1024,2048]);q0=class q0 extends ua{constructor(e){super("TEXTURE_ATLAS_CONTRACT",`textureAtlas: ${e}`);this.name="TextureAtlasError"}}});function yN(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function _N(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function vo(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function $T(){let e=vo("canvas");return e.style.display="block",e}function Wc(...e){let t="THREE."+e.shift();if(Eo)Eo("log",t,...e);else console.log(t,...e)}function KT(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 je(...e){e=KT(e);let t="THREE."+e.shift();if(Eo)Eo("warn",t,...e);else{let n=e[0];if(n&&n.isStackTrace)console.warn(n.getError(t));else console.warn(t,...e)}}function Ye(...e){e=KT(e);let t="THREE."+e.shift();if(Eo)Eo("error",t,...e);else{let n=e[0];if(n&&n.isStackTrace)console.error(n.getError(t));else console.error(t,...e)}}function ya(...e){let t=e.join(" ");if(t in pE)return;pE[t]=!0,je(...e)}function WT(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)})}class Vi{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}}}function Fi(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(On[e&255]+On[e>>8&255]+On[e>>16&255]+On[e>>24&255]+"-"+On[t&255]+On[t>>8&255]+"-"+On[t>>16&15|64]+On[t>>24&255]+"-"+On[n&63|128]+On[n>>8&255]+"-"+On[n>>16&255]+On[n>>24&255]+On[i&255]+On[i>>8&255]+On[i>>16&255]+On[i>>24&255]).toLowerCase()}function ct(e,t,n){return Math.max(t,Math.min(n,e))}function km(e,t){return(e%t+t)%t}function vN(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)}function EN(e,t,n){if(e!==t)return(n-e)/(t-e);else return 0}function Kc(e,t,n){return(1-n)*e+n*t}function TN(e,t,n,i){return Kc(e,t,1-Math.exp(-n*i))}function AN(e,t=1){return t-Math.abs(km(e,t*2)-t)}function wN(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 SN(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 MN(e,t){return e+Math.floor(Math.random()*(t-e+1))}function RN(e,t){return e+Math.random()*(t-e)}function IN(e){return e*(0.5-Math.random())}function CN(e){if(e!==void 0)mE=e;let t=mE+=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 NN(e){return e*$c}function PN(e){return e*_a}function ON(e){return e>0&&Number.isInteger(e)&&2**Math.round(Math.log2(e))===e}function kN(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))}function DN(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function LN(e,t,n,i,r){let{cos:s,sin:a}=Math,o=s(n/2),c=a(n/2),l=s((t+i)/2),u=a((t+i)/2),d=s((t-i)/2),f=a((t-i)/2),h=s((i-t)/2),b=a((i-t)/2);switch(r){case"XYX":e.set(o*u,c*d,c*f,o*l);break;case"YZY":e.set(c*f,o*u,c*d,o*l);break;case"ZXZ":e.set(c*d,c*f,o*u,o*l);break;case"XZX":e.set(o*u,c*b,c*h,o*l);break;case"YXY":e.set(c*h,o*u,c*b,o*l);break;case"ZYZ":e.set(c*b,c*h,o*u,o*l);break;default:je("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function Li(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray: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:case Uint8ClampedArray: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.")}}function FN(){let e={enabled:!0,workingColorSpace:"srgb-linear",spaces:{},convert:function(r,s,a){if(this.enabled===!1||s===a||!s||!a)return r;if(this.spaces[s].transfer==="srgb")r.r=Ur(r.r),r.g=Ur(r.g),r.b=Ur(r.b);if(this.spaces[s].primaries!==this.spaces[a].primaries)r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[a].fromXYZ);if(this.spaces[a].transfer==="srgb")r.r=_o(r.r),r.g=_o(r.g),r.b=_o(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,a){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(r,s){return ya("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return ya("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:bE,fromXYZ:xE,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:"srgb"},outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}},["srgb"]:{primaries:t,whitePoint:i,transfer:"srgb",toXYZ:bE,fromXYZ:xE,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}}}),e}function Ur(e){return e<0.04045?e*0.0773993808:Math.pow(e*0.9478672986+0.0521327014,2.4)}function _o(e){return e<0.0031308?e*12.92:1.055*Math.pow(e,0.41666)-0.055}class Dm{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(so===void 0)so=vo("canvas");so.width=e.width,so.height=e.height;let i=so.getContext("2d");if(e instanceof ImageData)i.putImageData(e,0,0);else i.drawImage(e,0,0,e.width,e.height);n=so}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=vo("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]=Ur(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(Ur(t[n]/255)*255);else t[n]=Ur(t[n]);return{data:t,width:e.width,height:e.height}}else return je("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}class tl{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:UN++}),this.uuid=Fi(),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,a=i.length;s<a;s++)if(i[s].isDataTexture)r.push(fp(i[s].image));else r.push(fp(i[s]))}else r=fp(i);n.url=r}if(!t)e.images[this.uuid]=n;return n}}function fp(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap)return Dm.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 je("Texture: Unable to serialize Texture."),{}}class Md{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}}class nl{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){if(this._hand===null)this._hand=new cr,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 cr,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 cr,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(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,a=this._targetRay,o=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){s=!0;for(let b of e.hand.values()){let m=t.getJointPose(b,n),g=this._getHandJoint(c,b);if(m!==null)g.matrix.fromArray(m.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=m.radius;g.visible=m!==null}let l=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=l.position.distanceTo(u.position),f=0.02,h=0.005;if(c.inputState.pinching&&d>f+h)c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this});else if(!c.inputState.pinching&&d<=f-h)c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this})}else if(o!==null&&e.gripSpace){if(r=t.getPose(e.gripSpace,n),r!==null){if(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity)o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity);else o.hasLinearVelocity=!1;if(r.angularVelocity)o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity);else o.hasAngularVelocity=!1;if(o.eventsEnabled)o.dispatchEvent({type:"gripUpdated",data:e,target:this})}}if(a!==null){if(i=t.getPose(e.targetRaySpace,n),i===null&&r!==null)i=r;if(i!==null){if(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity)a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity);else a.hasLinearVelocity=!1;if(i.angularVelocity)a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity);else a.hasAngularVelocity=!1;this.dispatchEvent(KN)}}}if(a!==null)a.visible=i!==null;if(o!==null)o.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 cr;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}function mp(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 _i{constructor(e=new j,t=new j,n=new j){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),ki.subVectors(e,t),i.cross(ki);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){ki.subVectors(i,t),Or.subVectors(n,t),gp.subVectors(e,t);let s=ki.dot(ki),a=ki.dot(Or),o=ki.dot(gp),c=Or.dot(Or),l=Or.dot(gp),u=s*c-a*a;if(u===0)return r.set(0,0,0),null;let d=1/u,f=(c*o-a*l)*d,h=(s*l-a*o)*d;return r.set(1-f-h,h,f)}static containsPoint(e,t,n,i){if(this.getBarycoord(e,t,n,i,kr)===null)return!1;return kr.x>=0&&kr.y>=0&&kr.x+kr.y<=1}static getInterpolation(e,t,n,i,r,s,a,o){if(this.getBarycoord(e,t,n,i,kr)===null){if(o.x=0,o.y=0,"z"in o)o.z=0;if("w"in o)o.w=0;return null}return o.setScalar(0),o.addScaledVector(r,kr.x),o.addScaledVector(s,kr.y),o.addScaledVector(a,kr.z),o}static getInterpolatedAttribute(e,t,n,i,r,s){return _p.setScalar(0),vp.setScalar(0),Ep.setScalar(0),_p.fromBufferAttribute(e,t),vp.fromBufferAttribute(e,n),Ep.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(_p,r.x),s.addScaledVector(vp,r.y),s.addScaledVector(Ep,r.z),s}static isFrontFacing(e,t,n,i){return ki.subVectors(n,t),Or.subVectors(e,t),ki.cross(Or).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 ki.subVectors(this.c,this.b),Or.subVectors(this.a,this.b),ki.cross(Or).length()*0.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(0.3333333333333333)}getNormal(e){return _i.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return _i.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return _i.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return _i.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return _i.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,r=this.c,s,a;lo.subVectors(i,n),uo.subVectors(r,n),bp.subVectors(e,n);let o=lo.dot(bp),c=uo.dot(bp);if(o<=0&&c<=0)return t.copy(n);xp.subVectors(e,i);let l=lo.dot(xp),u=uo.dot(xp);if(l>=0&&u<=l)return t.copy(i);let d=o*u-l*c;if(d<=0&&o>=0&&l<=0)return s=o/(o-l),t.copy(n).addScaledVector(lo,s);yp.subVectors(e,r);let f=lo.dot(yp),h=uo.dot(yp);if(h>=0&&f<=h)return t.copy(r);let b=f*c-o*h;if(b<=0&&c>=0&&h<=0)return a=c/(c-h),t.copy(n).addScaledVector(uo,a);let m=l*h-f*u;if(m<=0&&u-l>=0&&f-h>=0)return SE.subVectors(r,i),a=(u-l)/(u-l+(f-h)),t.copy(i).addScaledVector(SE,a);let g=1/(m+b+d);return s=b*g,a=d*g,t.copy(n).addScaledVector(lo,s).addScaledVector(uo,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class pn{constructor(e=new j(1/0,1/0,1/0),t=new j(-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(Di.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Di.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=Di.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,a=r.count;s<a;s++){if(e.isMesh===!0)e.getVertexPosition(s,Di);else Di.fromBufferAttribute(r,s);Di.applyMatrix4(e.matrixWorld),this.expandByPoint(Di)}else{if(e.boundingBox!==void 0){if(e.boundingBox===null)e.computeBoundingBox();ju.copy(e.boundingBox)}else{if(n.boundingBox===null)n.computeBoundingBox();ju.copy(n.boundingBox)}ju.applyMatrix4(e.matrixWorld),this.union(ju)}}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,Di),Di.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(Uc),Hu.subVectors(this.max,Uc),fo.subVectors(e.a,Uc),ho.subVectors(e.b,Uc),po.subVectors(e.c,Uc),ss.subVectors(ho,fo),as.subVectors(po,ho),ma.subVectors(fo,po);let t=[0,-ss.z,ss.y,0,-as.z,as.y,0,-ma.z,ma.y,ss.z,0,-ss.x,as.z,0,-as.x,ma.z,0,-ma.x,-ss.y,ss.x,0,-as.y,as.x,0,-ma.y,ma.x,0];if(!Tp(t,fo,ho,po,Hu))return!1;if(t=[1,0,0,0,1,0,0,0,1],!Tp(t,fo,ho,po,Hu))return!1;return Gu.crossVectors(ss,as),t=[Gu.x,Gu.y,Gu.z],Tp(t,fo,ho,po,Hu)}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Di).distanceTo(e)}getBoundingSphere(e){if(this.isEmpty())e.makeEmpty();else this.getCenter(e.center),e.radius=this.getSize(Di).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 Dr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Dr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Dr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Dr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Dr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Dr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Dr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Dr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Dr),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}}function Tp(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){ga.fromArray(e,s);let o=r.x*Math.abs(ga.x)+r.y*Math.abs(ga.y)+r.z*Math.abs(ga.z),c=t.dot(ga),l=n.dot(ga),u=i.dot(ga);if(Math.max(-Math.max(c,l,u),Math.min(c,l,u))>o)return!1}return!0}class ui{constructor(e=new j,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 XN.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;Bc.subVectors(e,this.center);let t=Bc.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=(n-this.radius)*0.5;this.center.addScaledVector(Bc,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 Ap.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Bc.copy(e.center).add(Ap)),this.expandByPoint(Bc.copy(e.center).sub(Ap));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}}class il{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=Fi()}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=Fi();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=Fi();if(e.arrayBuffers[this.array.buffer._uuid]===void 0)e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer));let t={uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride};return t.usage=this.usage,t}}class Oo{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++)Gn.fromBufferAttribute(this,t),Gn.applyMatrix4(e),this.setXYZ(t,Gn.x,Gn.y,Gn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Gn.fromBufferAttribute(this,t),Gn.applyNormalMatrix(e),this.setXYZ(t,Gn.x,Gn.y,Gn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Gn.fromBufferAttribute(this,t),Gn.transformDirection(e),this.setXYZ(t,Gn.x,Gn.y,Gn.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];if(this.normalized)n=Li(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=Li(t,this.array);return t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];if(this.normalized)t=Li(t,this.array);return t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];if(this.normalized)t=Li(t,this.array);return t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];if(this.normalized)t=Li(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){Wc("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 En(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 Oo(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}}toJSON(e){if(e===void 0){Wc("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}}}}class yi{constructor(e=new j(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=Sp.subVectors(n,t).cross(JN.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(Sp),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||ZN.getNormalMatrix(e),i=this.coplanarPoint(Sp).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)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}}class ms{constructor(e=new j,t=new j(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,Lr)),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=Lr.subVectors(e,this.origin).dot(this.direction);if(t<0)return this.origin.distanceToSquared(e);return Lr.copy(this.origin).addScaledVector(this.direction,t),Lr.distanceToSquared(e)}distanceSqToSegment(e,t,n,i){Mp.copy(e).add(t).multiplyScalar(0.5),Ku.copy(t).sub(e).normalize(),Wu.copy(this.origin).sub(Mp);let r=e.distanceTo(t)*0.5,s=-this.direction.dot(Ku),a=Wu.dot(this.direction),o=-Wu.dot(Ku),c=Wu.lengthSq(),l=Math.abs(1-s*s),u,d,f,h;if(l>0)if(u=s*o-a,d=s*a-o,h=r*l,u>=0)if(d>=-h)if(d<=h){let b=1/l;u*=b,d*=b,f=u*(u+s*d+2*a)+d*(s*u+d+2*o)+c}else d=r,u=Math.max(0,-(s*d+a)),f=-u*u+d*(d+2*o)+c;else d=-r,u=Math.max(0,-(s*d+a)),f=-u*u+d*(d+2*o)+c;else if(d<=-h)u=Math.max(0,-(-s*r+a)),d=u>0?-r:Math.min(Math.max(-r,-o),r),f=-u*u+d*(d+2*o)+c;else if(d<=h)u=0,d=Math.min(Math.max(-r,-o),r),f=d*(d+2*o)+c;else u=Math.max(0,-(s*r+a)),d=u>0?r:Math.min(Math.max(-r,-o),r),f=-u*u+d*(d+2*o)+c;else d=s>0?-r:r,u=Math.max(0,-(s*d+a)),f=-u*u+d*(d+2*o)+c;if(n)n.copy(this.origin).addScaledVector(this.direction,u);if(i)i.copy(Mp).addScaledVector(Ku,d);return f}intersectSphere(e,t){if(e.radius<0)return null;Lr.subVectors(e.center,this.origin);let n=Lr.dot(this.direction),i=Lr.dot(Lr)-n*n,r=e.radius*e.radius;if(i>r)return null;let s=Math.sqrt(r-i),a=n-s,o=n+s;if(o<0)return null;if(a<0)return this.at(o,t);return this.at(a,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,a,o,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;if(c>=0)n=(e.min.x-d.x)*c,i=(e.max.x-d.x)*c;else n=(e.max.x-d.x)*c,i=(e.min.x-d.x)*c;if(l>=0)r=(e.min.y-d.y)*l,s=(e.max.y-d.y)*l;else r=(e.max.y-d.y)*l,s=(e.min.y-d.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)a=(e.min.z-d.z)*u,o=(e.max.z-d.z)*u;else a=(e.max.z-d.z)*u,o=(e.min.z-d.z)*u;if(n>o||a>i)return null;if(a>n||n!==n)n=a;if(o<i||i!==i)i=o;if(i<0)return null;return this.at(n>=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,Lr)!==null}intersectTriangle(e,t,n,i,r){let s=this.origin,a=this.direction,{x:o,y:c,z:l}=a,u=e.x-s.x,d=e.y-s.y,f=e.z-s.z,h=t.x-s.x,b=t.y-s.y,m=t.z-s.z,g=n.x-s.x,p=n.y-s.y,x=n.z-s.z,_=Math.abs(o),y=Math.abs(c),v=Math.abs(l),E,w,T,A,P,S,R,k,C,U,L,O;if(_>=y&&_>=v)if(T=o,S=u,C=h,O=g,o>=0)E=c,w=l,A=d,P=f,R=b,k=m,U=p,L=x;else E=l,w=c,A=f,P=d,R=m,k=b,U=x,L=p;else if(y>=v)if(T=c,S=d,C=b,O=p,c>=0)E=l,w=o,A=f,P=u,R=m,k=h,U=x,L=g;else E=o,w=l,A=u,P=f,R=h,k=m,U=g,L=x;else if(T=l,S=f,C=m,O=x,l>=0)E=o,w=c,A=u,P=d,R=h,k=b,U=g,L=p;else E=c,w=o,A=d,P=u,R=b,k=h,U=p,L=g;if(T===0)return null;let K=E/T,B=w/T,X=1/T,q=A-K*S,le=P-B*S,de=R-K*C,Me=k-B*C,pe=U-K*O,J=L-B*O,F=pe*Me-J*de,W=q*J-le*pe,ne=de*le-Me*q;if(i){if(F<0||W<0||ne<0)return null}else if((F<0||W<0||ne<0)&&(F>0||W>0||ne>0))return null;let ie=F+W+ne;if(ie===0)return null;let ce=X*(F*S+W*C+ne*O);if(ie>0?ce<0:ce>0)return null;return this.at(ce/ie,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)}}function QN(e,t,n,i,r,s,a,o){let c;if(t.side===1)c=i.intersectTriangle(a,s,r,!0,o);else c=i.intersectTriangle(r,s,a,t.side===0,o);if(c===null)return null;Qu.copy(o),Qu.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(Qu);if(l<n.near||l>n.far)return null;return{distance:l,point:Qu.clone(),object:e}}function ed(e,t,n,i,r,s,a,o,c,l){e.getVertexPosition(o,qu),e.getVertexPosition(c,Ju),e.getVertexPosition(l,Zu);let u=QN(e,t,n,i,qu,Ju,Zu,IE);if(u){let d=new j;if(_i.getBarycoord(IE,qu,Ju,Zu,d),r)u.uv=_i.getInterpolatedAttribute(r,o,c,l,d,new Ke);if(s)u.uv1=_i.getInterpolatedAttribute(s,o,c,l,d,new Ke);if(a){if(u.normal=_i.getInterpolatedAttribute(a,o,c,l,d,new j),u.normal.dot(i.direction)>0)u.normal.multiplyScalar(-1)}let f={a:o,b:c,c:l,normal:new j,materialIndex:0};_i.getNormal(qu,Ju,Zu,f.normal),u.face=f,u.barycoord=d}return u}class al{constructor(e=[],t=[]){this.uuid=Fi(),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){je("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 Je)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let n=new Je;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 a=e[r]?e[r].matrixWorld:tP;kE.multiplyMatrices(a,t[r]),kE.toArray(n,r*16)}if(i!==null)i.needsUpdate=!0}clone(){return new al(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 sl(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)je("Skeleton: No bone found with UUID:",r),s=new rl;this.bones.push(s),this.boneInverses.push(new Je().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 a=n[i];e.boneInverses.push(a.toArray())}return e}}class ol{constructor(e=new yi,t=new yi,n=new yi,i=new yi,r=new yi,s=new yi){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){let a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[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],a=r[1],o=r[2],c=r[3],l=r[4],u=r[5],d=r[6],f=r[7],h=r[8],b=r[9],m=r[10],g=r[11],p=r[12],x=r[13],_=r[14],y=r[15];if(i[0].setComponents(c-s,f-l,g-h,y-p).normalize(),i[1].setComponents(c+s,f+l,g+h,y+p).normalize(),i[2].setComponents(c+a,f+u,g+b,y+x).normalize(),i[3].setComponents(c-a,f-u,g-b,y-x).normalize(),n)i[4].setComponents(o,d,m,_).normalize(),i[5].setComponents(c-o,f-d,g-m,y-_).normalize();else if(i[4].setComponents(c-o,f-d,g-m,y-_).normalize(),t===2000)i[5].setComponents(c+o,f+d,g+m,y+_).normalize();else if(t===2001)i[5].setComponents(o,d,m,_).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();xa.copy(e.boundingSphere).applyMatrix4(e.matrixWorld)}else{let t=e.geometry;if(t.boundingSphere===null)t.computeBoundingSphere();xa.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(xa)}intersectsSprite(e){xa.center.set(0,0,0);let t=iP.distanceTo(e.center);return xa.radius=0.7071067811865476+t,xa.applyMatrix4(e.matrixWorld),this.intersectsSphere(xa)}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(id.x=i.normal.x>0?e.max.x:e.min.x,id.y=i.normal.y>0?e.max.y:e.min.y,id.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(id)<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)}}function sd(e,t,n,i,r,s,a){let o=e.geometry.attributes.position;if(dd.fromBufferAttribute(o,r),fd.fromBufferAttribute(o,s),n.distanceSqToSegment(dd,fd,Np,UE)>i)return;Np.applyMatrix4(e.matrixWorld);let l=t.ray.origin.distanceTo(Np);if(l<t.near||l>t.far)return;return{distance:l,point:UE.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}function jE(e,t,n,i,r,s,a){let o=kp.distanceSqToPoint(e);if(o<n){let c=new j;kp.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(o),point:c,index:t,face:null,faceIndex:null,barycoord:null,object:a})}}function Ra(e){let t={};for(let n in e){t[n]={};for(let i in e[n]){let r=e[n][i];if(HE(r))if(r.isRenderTargetTexture)je("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(HE(r[0])){let s=[];for(let a=0,o=r.length;a<o;a++)s[a]=r[a].clone();t[n][i]=s}else t[n][i]=r.slice();else t[n][i]=r}}return t}function Fn(e){let t={};for(let n=0;n<e.length;n++){let i=Ra(e[n]);for(let r in i)t[r]=i[r]}return t}function HE(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function rP(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function Bm(e){let t=e.getRenderTarget();if(t===null)return e.outputColorSpace;if(t.isXRRenderTarget===!0)return t.texture.colorSpace;return ot.workingColorSpace}function cs(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 ud(e){return e!==void 0&&e.inTangents!==void 0&&e.outTangents!==void 0}function oP(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 GE(e,t,n){let i=e.length,r=new e.constructor(i);for(let s=0,a=0;a!==i;++s){let o=n[s]*t;for(let c=0;c!==t;++c)r[a++]=e[o+c]}return r}function cP(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 a=s[i];if(a===void 0)return;if(Array.isArray(a))do{if(a=s[i],a!==void 0)t.push(s.time),n.push(...a);s=e[r++]}while(s!==void 0);else if(a.toArray!==void 0)do{if(a=s[i],a!==void 0)t.push(s.time),a.toArray(n,n.length);s=e[r++]}while(s!==void 0);else do{if(a=s[i],a!==void 0)t.push(s.time),n.push(a);s=e[r++]}while(s!==void 0)}class Vr{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 a=n+2;;){if(i===void 0){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(r=i,i=t[++n],e<i)break t}s=t.length;break n}if(!(e>=r)){let a=t[1];if(e<a)n=2,r=a;for(let o=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===o)break;if(i=r,r=t[--n-1],e>=r)break t}s=n,n=0;break n}break e}while(n<s){let a=n+s>>>1;if(e<t[a])s=a;else n=a+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_(){}}function ZT(e,t,n,i,r){let s=1-e;return s*s*s*t+3*s*s*e*n+3*s*e*e*i+e*e*e*r}function lP(e,t,n,i,r){let s=1-e;return 3*s*s*(n-t)+6*s*e*(i-n)+3*e*e*(r-i)}function uP(e,t,n,i,r){let s=(e-t)/(r-t);for(let a=0;a<8;a++){let o=ZT(s,t,n,i,r)-e;if(Math.abs(o)<0.0000000001)break;let c=lP(s,t,n,i,r);if(Math.abs(c)<0.0000000001)break;s=Math.max(0,Math.min(1,s-o/c))}return s}class fi{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=cs(t,this.TimeBufferType),this.values=cs(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:cs(e.times,Array),values:cs(e.values,Array)};let i=e.getInterpolation();if(i!==e.DefaultInterpolation)n.interpolation=i;if(ud(e.settings))n.settings={inTangents:cs(e.settings.inTangents,Array),outTangents:cs(e.settings.outTangents,Array)}}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Gm(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Ld(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Hm(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new $m(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 je("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;if(ud(this.settings))$E(this.settings.inTangents,e),$E(this.settings.outTangents,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 a=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*a,s*a)}return this}validate(){let e=!0,t=this.getValueSize();if(t-Math.floor(t)!==0)Ye("KeyframeTrack: Invalid value size in track.",this),e=!1;let n=this.times,i=this.values,r=n.length;if(r===0)Ye("KeyframeTrack: Track is empty.",this),e=!1;let s=null;for(let a=0;a!==r;a++){let o=n[a];if(typeof o==="number"&&isNaN(o)){Ye("KeyframeTrack: Time is not a valid number.",this,a,o),e=!1;break}if(s!==null&&s>o){Ye("KeyframeTrack: Out of order keys.",this,a,o,s),e=!1;break}s=o}if(i!==void 0){if(_N(i))for(let a=0,o=i.length;a!==o;++a){let c=i[a];if(isNaN(c)){Ye("KeyframeTrack: Value is not a valid number.",this,a,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 a=1;a<r;++a){let o=!1,c=e[a],l=e[a+1];if(c!==l&&(a!==1||c!==e[0]))if(!i){let u=a*n,d=u-n,f=u+n;for(let h=0;h!==n;++h){let b=t[u+h];if(b!==t[d+h]||b!==t[f+h]){o=!0;break}}}else o=!0;if(o){if(a!==s){e[s]=e[a];let u=a*n,d=s*n;for(let f=0;f!==n;++f)t[d+f]=t[u+f]}++s}}if(r>0){e[s]=e[r];for(let a=r*n,o=s*n,c=0;c!==n;++c)t[o+c]=t[a+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);if(i.createInterpolant=this.createInterpolant,ud(this.settings))i.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()};return i}}function $E(e,t){for(let n=0,i=e.length;n!==i;n+=2)e[n]*=t}class To{constructor(e="",t=-1,n=[],i=2500){if(this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=Fi(),this.userData={},this.duration<0)this.resetDuration()}static parse(e){let t=[],n=e.tracks,i=1/(e.fps||1);for(let s=0,a=n.length;s!==a;++s)t.push(fP(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(fi.toJSON(n[r]));return i}static CreateFromMorphTargetSequence(e,t,n,i){let r=t.length,s=[];for(let a=0;a<r;a++){let o=[],c=[];o.push((a+r-1)%r,a,(a+1)%r),c.push(0,1,0);let l=oP(o);if(o=GE(o,1,l),c=GE(c,1,l),!i&&o[0]===0)o.push(r),c.push(c[0]);s.push(new ys(".morphTargetInfluences["+t[a].name+"]",o,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 a=0,o=e.length;a<o;a++){let c=e[a],l=c.name.match(r);if(l&&l.length>1){let u=l[1],d=i[u];if(!d)i[u]=d=[];d.push(c)}}let s=[];for(let a in i)s.push(this.CreateFromMorphTargetSequence(a,i[a],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 dP(e){switch(e.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return ys;case"vector":case"vector2":case"vector3":case"vector4":return Ia;case"color":return Fd;case"quaternion":return _s;case"bool":case"boolean":return xs;case"string":return vs}throw Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}function fP(e){if(e.type===void 0)throw Error("THREE.KeyframeTrack: track type undefined, can not parse");let t=dP(e.type);if(e.times===void 0){let i=[],r=[];cP(e.keys,i,r,"value"),e.times=i,e.values=r}let n;if(t.parse!==void 0)n=t.parse(e);else n=new t(e.name,e.times,e.values,e.interpolation);if(ud(e.settings))n.settings={inTangents:cs(e.settings.inTangents,Float32Array),outTangents:cs(e.settings.outTangents,Float32Array)};return n}function KE(e){try{let t=e.slice(e.indexOf(":")+1);return new URL(t).protocol==="blob:"}catch(t){return!1}}class dl{constructor(e,t,n){let i=this,r=!1,s=0,a=0,o=void 0,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(l){if(a++,r===!1){if(i.onStart!==void 0)i.onStart(l,s,a)}r=!0},this.itemEnd=function(l){if(s++,i.onProgress!==void 0)i.onProgress(l,s,a);if(s===a){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"),o)return o(l);return l},this.setURLModifier=function(l){return o=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,d=c.length;u<d;u+=2){let f=c[u],h=c[u+1];if(f.global)f.lastIndex=0;if(f.test(l))return h}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}}class jr{constructor(e){if(this.manager=e!==void 0?e:YT,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}}class hl{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 Ke(512,512),this.mapType=1009,this.map=null,this.mapPass=null,this.matrix=new Je,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new ol,this._frameExtents=new Ke(1,1),this._viewportCount=1,this._viewports=[new Pt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getCamera(){return this.camera}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera;WE.setFromMatrixPosition(e.matrixWorld),t.position.copy(WE),XE.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(XE),t.updateMatrixWorld(),this._updateMatrix(t,this.matrix,this._frustum)}_updateMatrix(e,t,n,i){Pp.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),n.setFromProjectionMatrix(Pp,e.coordinateSystem,e.reversedDepth);let r=this._frameExtents,s=i?i.z/r.x:1,a=i?i.w/r.y:1,o=i?i.x/r.x:0,c=i?i.y/r.y:0;if(e.coordinateSystem===2001||e.reversedDepth)t.set(0.5*s,0,0,0.5*s+o,0,0.5*a,0,0.5*a+c,0,0,1,0,0,0,0,1);else t.set(0.5*s,0,0,0.5*s+o,0,0.5*a,0,0.5*a+c,0,0,0.5,0.5,0,0,0,1);t.multiply(Pp)}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={};return e.intensity=this.intensity,e.bias=this.bias,e.normalBias=this.normalBias,e.radius=this.radius,e.blurSamples=this.blurSamples,e.mapSize=this.mapSize.toArray(),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class Es{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}}class Jm{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 a=0;a!==i;++a)n[r+a]=n[a];s=t}else{s+=t;let a=t/s;this._mixBufferRegion(n,r,0,a,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,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){let o=t*this._origIndex;this._mixBufferRegion(n,i,o,1-r,t)}if(s>0)this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let o=t,c=t+t;o!==c;++o)if(n[o]!==n[o+t]){a.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){ln.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,r){let s=this._workIndex*r;ln.multiplyQuaternionsFlat(e,s,e,t,e,n),ln.slerpFlat(e,t,e,t,e,s,i)}_lerp(e,t,n,i,r){let s=1-i;for(let a=0;a!==r;++a){let o=t+a;e[o]=e[o]*s+e[n+a]*i}}_lerpAdditive(e,t,n,i,r){for(let s=0;s!==r;++s){let a=t+s;e[a]=e[a]+e[n+s]*i}}}class iA{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(hP,"")}static parseTrackName(e){let t=yP.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(_P.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 a=r[s];if(a.name===t||a.uuid===t)return a;let o=n(a.children);if(o)return o}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){je("PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let c=t.objectIndex;switch(n){case"materials":if(!e.material){Ye("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){Ye("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){Ye("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){Ye("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){Ye("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){Ye("PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(c!==void 0){if(e[c]===void 0){Ye("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;Ye("PropertyBinding: Trying to update property for track: "+c+"."+i+" but it wasn't found.",e);return}let a=this.Versioning.None;if(this.targetObject=e,e.isMaterial===!0)a=this.Versioning.NeedsUpdate;else if(e.isObject3D===!0)a=this.Versioning.MatrixWorldNeedsUpdate;let o=this.BindingType.Direct;if(r!==void 0){if(i==="morphTargetInfluences"){if(!e.geometry){Ye("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){Ye("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]}o=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=r}else if(s.fromArray!==void 0&&s.toArray!==void 0)o=this.BindingType.HasFromToArray,this.resolvedProperty=s;else if(Array.isArray(s))o=this.BindingType.EntireArray,this.resolvedProperty=s;else this.propertyName=i;this.getValue=this.GetterByBindingType[o],this.setValue=this.SetterByBindingTypeAndVersioning[o][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}class Qm{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,a=Array(s),o={endingStart:2400,endingEnd:2400};for(let c=0;c!==s;++c){let l=r[c].createInterpolant(null);a[c]=l,l.settings=o}this._interpolantSettings=o,this._interpolants=a,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,a=i/r;e._restoreTimeScale=e.timeScale,this._restoreTimeScale=this.timeScale,e.warp(1,s,t),this.warp(a,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,a=this._timeScaleInterpolant;if(a===null)a=i._lendControlInterpolant(),this._timeScaleInterpolant=a;let o=a.parameterPositions,c=a.sampleValues;return o[0]=r,o[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 o=(e-r)*n;if(o<0||n===0)t=0;else this._startTime=null,t=n*o}t*=this._updateTimeScale(e);let s=this._updateTime(t),a=this._updateWeight(e);if(a>0){let o=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case 2501:for(let l=0,u=o.length;l!==u;++l)o[l].evaluate(s),c[l].accumulateAdditive(a);break;case 2500:default:for(let l=0,u=o.length;l!==u;++l)o[l].evaluate(s),c[l].accumulate(i,a)}}}_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 a=Math.floor(i/t);i-=t*a,r+=Math.abs(a);let o=this.repetitions-r;if(o<=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(o===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:a})}}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 a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=t,a[1]=r+e,o[1]=n,this}}class pl{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=ct(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(ct(t/this.radius,-1,1));return this}clone(){return new this.constructor().copy(this)}}function tg(e,t,n,i){let r=EP(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 EP(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}.`)}var ZE="186",us,ds,YE=0,Dp=1,QE=2,Xc=1,eT=2,Ao=3,fs=0,Dn=1,vi=2,dr=0,qc=1,Lp=2,Fp=3,Up=4,tT=5,wo=100,nT=101,iT=102,rT=103,sT=104,aT=200,oT=201,cT=202,lT=203,uT=204,dT=205,fT=206,hT=207,pT=208,mT=209,gT=210,bT=211,xT=212,yT=213,_T=214,vT=0,ET=1,TT=2,Bp=3,AT=4,wT=5,ST=6,MT=7,RT=0,IT=1,CT=2,Ui=0,zp=1,Vp=2,jp=3,Jc=4,Hp=5,Gp=6,$p=7,So=301,va=302,hd=303,pd=304,Zc=306,Mo=1000,Ro=1001,md=1002,Bi=1003,gd=1004,Ea=1005,Tn=1006,Io=1007,fr=1008,zi=1009,NT=1010,PT=1011,Yc=1012,Kp=1013,hs=1014,Br=1015,hr=1016,Wp=1017,Xp=1018,Co=1020,OT=35902,kT=35899,DT=1021,LT=1022,pr=1023,Ta=1026,Aa=1027,FT=1028,qp=1029,wa=1030,Jp=1031,Zp=1033,bd=33776,xd=33777,yd=33778,_d=33779,Yp=35840,Qp=35841,em=35842,tm=35843,nm=36196,im=37492,rm=37496,sm=37488,am=37489,vd=37490,om=37491,cm=37808,lm=37809,um=37810,dm=37811,fm=37812,hm=37813,pm=37814,mm=37815,gm=37816,bm=37817,xm=37818,ym=37819,_m=37820,vm=37821,Em=36492,Tm=36494,Am=36495,wm=36283,Sm=36284,Ed=36285,Mm=36286,Rm=2300,Td=2301,Im=0,Qc=1,No=2,Cm=0,UT=1,Sa="",ps="srgb",ci="srgb-linear",Nm="linear",Bt="srgb",BT=512,zT=513,VT=514,Ad=515,jT=516,HT=517,wd=518,GT=519,Pm="300 es",Om=2000,pE,Eo=null,XT,On,mE=1234567,$c,_a,el,Ke,ln,j,up,gE,tt,dp,bE,xE,ot,so,UN=0,BN=0,hp,en,Pt,Lm,li,Sd,Fm,Je,ao,Oi,zN,VN,is,Bu,ai,yE,_E,ur,jN=0,vE,oo,Pr,zu,Fc,HN,GN,EE,TE,AE,wE,$N,co,pp,Dt,cr,KN,qT,rs,Vu,qe,kn,Po,ki,Or,gp,kr,lo,uo,SE,bp,xp,yp,_p,vp,Ep,Dr,Di,ju,fo,ho,po,ss,as,ma,Uc,Hu,Gu,ga,cn,$u,WN=0,En,Rd,Id,Xn,XN,Bc,Ap,qN=0,xi,wp,mo,oi,zc,vn,Ln,Gn,Sp,JN,ZN,YN=0,qn,Lr,Mp,Ku,Wu,mr,ME,ba,Xu,RE,qu,Ju,Zu,Rp,Yu,IE,Qu,jt,Vc,CE,NE,eP,PE,td,Ip,OE,Cp,Cd,rl,sl,kE,tP,ls,go,DE,nd,LE,nP,jc,Hc,ko,xa,iP,id,cl,dd,fd,FE,Gc,rd,Np,UE,gs,BE,zE,Nd,Pd,ll,VE,kp,ad,od,Do,Od,Ma,Um,kd,bs,ul,JT,sP=`void main() {gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );-}`,tP=`void main() {+}`,aP=`void main() {gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );-}`,Ei,Dm,zr,ui,Pd,Lm,Fm,Um,Od,Bm,zm,xs,kd,ys,Vm,_s,vs,Ma,lr,XT,Fr,qT,ul,bo,jm,Lo,Fo,Dd,Mp,HE,GE,sd,ad,or,Ld,os,$E,KE,fn,JT,Fd,ZT,Uo,Ra,YT,Bo,Rp,Ud,xo=-90,yo=1,Hm,Gm,Km="\\[\\]\\.:\\/",cP,Wm,lP,uP,dP,fP,hP,pP,mP,gP,Bd,qm,zd;var Zm=mt(()=>{us={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},ds={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3};uE={};GT={[0]:1,[2]:6,[4]:7,[3]:5,[1]:0,[6]:2,[7]:4,[5]:3};Pn=["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"],Hc=Math.PI/180,xa=180/Math.PI;Yc={DEG2RAD:Hc,RAD2DEG:xa,generateUUID:Fi,clamp:ct,euclideanModulo:Im,mapLinear:gN,inverseLerp:bN,lerp:Gc,damp:xN,pingpong:yN,smoothstep:_N,smootherstep:vN,randInt:EN,randFloat:TN,randFloatSpread:AN,seededRandom:wN,degToRad:SN,radToDeg:MN,isPowerOfTwo:RN,ceilPowerOfTwo:IN,floorPowerOfTwo:CN,setQuaternionFromProperEuler:NN,normalize:Nt,denormalize:Li};Ke=class Ke{static{Ke.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=ct(this.x,e.x,t.x),this.y=ct(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=ct(this.x,e,t),this.y=ct(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ct(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(ct(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}};ln=class ln{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,a){let o=n[i+0],c=n[i+1],l=n[i+2],u=n[i+3],d=r[s+0],f=r[s+1],h=r[s+2],b=r[s+3];if(u!==b||o!==d||c!==f||l!==h){let m=o*d+c*f+l*h+u*b;if(m<0)d=-d,f=-f,h=-h,b=-b,m=-m;let g=1-a;if(m<0.9995){let p=Math.acos(m),x=Math.sin(p);g=Math.sin(g*p)/x,a=Math.sin(a*p)/x,o=o*g+d*a,c=c*g+f*a,l=l*g+h*a,u=u*g+b*a}else{o=o*g+d*a,c=c*g+f*a,l=l*g+h*a,u=u*g+b*a;let p=1/Math.sqrt(o*o+c*c+l*l+u*u);o*=p,c*=p,l*=p,u*=p}}e[t]=o,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,s){let a=n[i],o=n[i+1],c=n[i+2],l=n[i+3],u=r[s],d=r[s+1],f=r[s+2],h=r[s+3];return e[t]=a*h+l*u+o*f-c*d,e[t+1]=o*h+l*d+c*u-a*f,e[t+2]=c*h+l*f+a*d-o*u,e[t+3]=l*h-a*u-o*d-c*f,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:a,sin:o}=Math,c=a(n/2),l=a(i/2),u=a(r/2),d=o(n/2),f=o(i/2),h=o(r/2);switch(s){case"XYZ":this._x=d*l*u+c*f*h,this._y=c*f*u-d*l*h,this._z=c*l*h+d*f*u,this._w=c*l*u-d*f*h;break;case"YXZ":this._x=d*l*u+c*f*h,this._y=c*f*u-d*l*h,this._z=c*l*h-d*f*u,this._w=c*l*u+d*f*h;break;case"ZXY":this._x=d*l*u-c*f*h,this._y=c*f*u+d*l*h,this._z=c*l*h+d*f*u,this._w=c*l*u-d*f*h;break;case"ZYX":this._x=d*l*u-c*f*h,this._y=c*f*u+d*l*h,this._z=c*l*h-d*f*u,this._w=c*l*u+d*f*h;break;case"YZX":this._x=d*l*u+c*f*h,this._y=c*f*u+d*l*h,this._z=c*l*h-d*f*u,this._w=c*l*u-d*f*h;break;case"XZY":this._x=d*l*u-c*f*h,this._y=c*f*u-d*l*h,this._z=c*l*h+d*f*u,this._w=c*l*u+d*f*h;break;default:je("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],a=t[5],o=t[9],c=t[2],l=t[6],u=t[10],d=n+a+u;if(d>0){let f=0.5/Math.sqrt(d+1);this._w=0.25/f,this._x=(l-o)*f,this._y=(r-c)*f,this._z=(s-i)*f}else if(n>a&&n>u){let f=2*Math.sqrt(1+n-a-u);this._w=(l-o)/f,this._x=0.25*f,this._y=(i+s)/f,this._z=(r+c)/f}else if(a>u){let f=2*Math.sqrt(1+a-n-u);this._w=(r-c)/f,this._x=(i+s)/f,this._y=0.25*f,this._z=(o+l)/f}else{let f=2*Math.sqrt(1+u-n-a);this._w=(s-i)/f,this._x=(r+c)/f,this._y=(o+l)/f,this._z=0.25*f}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(ct(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:a,_y:o,_z:c,_w:l}=t;return this._x=n*l+s*a+i*c-r*o,this._y=i*l+s*o+r*a-n*c,this._z=r*l+s*c+n*o-i*a,this._w=s*l-n*a-i*o-r*c,this._onChangeCallback(),this}slerp(e,t){let{_x:n,_y:i,_z:r,_w:s}=e,a=this.dot(e);if(a<0)n=-n,i=-i,r=-r,s=-s,a=-a;let o=1-t;if(a<0.9995){let c=Math.acos(a),l=Math.sin(c);o=Math.sin(o*c)/l,t=Math.sin(t*c)/l,this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this._onChangeCallback()}else this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+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}};j=class j{static{j.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(fE.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(fE.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:a,w:o}=e,c=2*(s*i-a*n),l=2*(a*t-r*i),u=2*(r*n-s*t);return this.x=t+o*c+s*u-a*l,this.y=n+o*l+a*c-r*u,this.z=i+o*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=ct(this.x,e.x,t.x),this.y=ct(this.y,e.y,t.y),this.z=ct(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=ct(this.x,e,t),this.y=ct(this.y,e,t),this.z=ct(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ct(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:a,z:o}=t;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-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 sp.copy(this).projectOnVector(e),this.sub(sp)}reflect(e){return this.sub(sp.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(ct(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}};sp=new j,fE=new ln;tt=class tt{static{tt.prototype.isMatrix3=!0}constructor(e,t,n,i,r,s,a,o,c){if(this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0)this.set(e,t,n,i,r,s,a,o,c)}set(e,t,n,i,r,s,a,o,c){let l=this.elements;return l[0]=e,l[1]=i,l[2]=a,l[3]=t,l[4]=r,l[5]=o,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],a=n[3],o=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],h=n[8],b=i[0],m=i[3],g=i[6],p=i[1],x=i[4],_=i[7],y=i[2],v=i[5],T=i[8];return r[0]=s*b+a*p+o*y,r[3]=s*m+a*x+o*v,r[6]=s*g+a*_+o*T,r[1]=c*b+l*p+u*y,r[4]=c*m+l*x+u*v,r[7]=c*g+l*_+u*T,r[2]=d*b+f*p+h*y,r[5]=d*m+f*x+h*v,r[8]=d*g+f*_+h*T,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],a=e[5],o=e[6],c=e[7],l=e[8];return t*s*l-t*a*c-n*r*l+n*a*o+i*r*c-i*s*o}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],c=e[7],l=e[8],u=l*s-a*c,d=a*o-l*r,f=c*r-s*o,h=t*u+n*d+i*f;if(h===0)return this.set(0,0,0,0,0,0,0,0,0);let b=1/h;return e[0]=u*b,e[1]=(i*c-l*n)*b,e[2]=(a*n-i*s)*b,e[3]=d*b,e[4]=(l*t-i*o)*b,e[5]=(i*r-a*t)*b,e[6]=f*b,e[7]=(n*o-c*t)*b,e[8]=(s*t-n*r)*b,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,a){let o=Math.cos(r),c=Math.sin(r);return this.set(n*o,n*c,-n*(o*s+c*a)+s+e,-i*c,i*o,-i*(-c*s+o*a)+a+t,0,0,1),this}scale(e,t){return ba("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(ap.makeScale(e,t)),this}rotate(e){return ba("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(ap.makeRotation(-e)),this}translate(e,t){return ba("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(ap.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)}};ap=new tt,hE=new tt().set(0.4123908,0.3575843,0.1804808,0.212639,0.7151687,0.0721923,0.0193308,0.1191948,0.9505322),pE=new tt().set(3.2409699,-1.5373832,-0.4986108,-0.9692436,1.8759675,0.0415551,0.0556301,-0.203977,1.0569715);ot=PN();cp=new j;en=class en extends Vi{constructor(e=en.DEFAULT_IMAGE,t=en.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,a=1023,o=1009,c=en.DEFAULT_ANISOTROPY,l=""){super();this.isTexture=!0,Object.defineProperty(this,"id",{value:kN++}),this.uuid=Fi(),this.name="",this.source=new Qc(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=a,this.internalFormat=null,this.type=o,this.offset=new Ke(0,0),this.repeat=new Ke(1,1),this.center=new Ke(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new tt,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(cp).x}get height(){return this.source.getSize(cp).y}get depth(){return this.source.getSize(cp).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){je(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){je(`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++}};en.DEFAULT_IMAGE=null;en.DEFAULT_MAPPING=300;en.DEFAULT_ANISOTROPY=1;Pt=class Pt{static{Pt.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,a=0.1,o=e.elements,c=o[0],l=o[4],u=o[8],d=o[1],f=o[5],h=o[9],b=o[2],m=o[6],g=o[10];if(Math.abs(l-d)<0.01&&Math.abs(u-b)<0.01&&Math.abs(h-m)<0.01){if(Math.abs(l+d)<0.1&&Math.abs(u+b)<0.1&&Math.abs(h+m)<0.1&&Math.abs(c+f+g-3)<0.1)return this.set(1,0,0,0),this;t=Math.PI;let x=(c+1)/2,_=(f+1)/2,y=(g+1)/2,v=(l+d)/4,T=(u+b)/4,A=(h+m)/4;if(x>_&&x>y)if(x<0.01)n=0,i=0.707106781,r=0.707106781;else n=Math.sqrt(x),i=v/n,r=T/n;else if(_>y)if(_<0.01)n=0.707106781,i=0,r=0.707106781;else i=Math.sqrt(_),n=v/i,r=A/i;else if(y<0.01)n=0.707106781,i=0.707106781,r=0;else r=Math.sqrt(y),n=T/r,i=A/r;return this.set(n,i,r,t),this}let p=Math.sqrt((m-h)*(m-h)+(u-b)*(u-b)+(d-l)*(d-l));if(Math.abs(p)<0.001)p=1;return this.x=(m-h)/p,this.y=(u-b)/p,this.z=(d-l)/p,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=ct(this.x,e.x,t.x),this.y=ct(this.y,e.y,t.y),this.z=ct(this.z,e.z,t.z),this.w=ct(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=ct(this.x,e,t),this.y=ct(this.y,e,t),this.z=ct(this.z,e,t),this.w=ct(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ct(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}};Nm=class Nm extends Vi{constructor(e=1,t=1,n={}){super();n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Pt(0,0,e,t),this.scissorTest=!1,this.viewport=new Pt(0,0,e,t),this.textures=[];let i={width:e,height:t,depth:n.depth},r=new en(i),s=n.count;for(let a=0;a<s;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(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===this)this._depthTexture.renderTarget=null;if(e!==null&&e.renderTarget===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 Qc(i)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null)if(e.depthTexture.renderTarget===e){let t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture;return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}};ci=class ci extends Nm{constructor(e=1,t=1,n={}){super(e,t,n);this.isWebGLRenderTarget=!0}};Td=class Td extends en{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}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}};Pm=class Pm extends en{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}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}};Qe=class Qe{static{Qe.prototype.isMatrix4=!0}constructor(e,t,n,i,r,s,a,o,c,l,u,d,f,h,b,m){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,a,o,c,l,u,d,f,h,b,m)}set(e,t,n,i,r,s,a,o,c,l,u,d,f,h,b,m){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=h,g[11]=b,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Qe().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/ao.setFromMatrixColumn(e,0).length(),r=1/ao.setFromMatrixColumn(e,1).length(),s=1/ao.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),a=Math.sin(n),o=Math.cos(i),c=Math.sin(i),l=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){let d=s*l,f=s*u,h=a*l,b=a*u;t[0]=o*l,t[4]=-o*u,t[8]=c,t[1]=f+h*c,t[5]=d-b*c,t[9]=-a*o,t[2]=b-d*c,t[6]=h+f*c,t[10]=s*o}else if(e.order==="YXZ"){let d=o*l,f=o*u,h=c*l,b=c*u;t[0]=d+b*a,t[4]=h*a-f,t[8]=s*c,t[1]=s*u,t[5]=s*l,t[9]=-a,t[2]=f*a-h,t[6]=b+d*a,t[10]=s*o}else if(e.order==="ZXY"){let d=o*l,f=o*u,h=c*l,b=c*u;t[0]=d-b*a,t[4]=-s*u,t[8]=h+f*a,t[1]=f+h*a,t[5]=s*l,t[9]=b-d*a,t[2]=-s*c,t[6]=a,t[10]=s*o}else if(e.order==="ZYX"){let d=s*l,f=s*u,h=a*l,b=a*u;t[0]=o*l,t[4]=h*c-f,t[8]=d*c+b,t[1]=o*u,t[5]=b*c+d,t[9]=f*c-h,t[2]=-c,t[6]=a*o,t[10]=s*o}else if(e.order==="YZX"){let d=s*o,f=s*c,h=a*o,b=a*c;t[0]=o*l,t[4]=b-d*u,t[8]=h*u+f,t[1]=u,t[5]=s*l,t[9]=-a*l,t[2]=-c*l,t[6]=f*u+h,t[10]=d-b*u}else if(e.order==="XZY"){let d=s*o,f=s*c,h=a*o,b=a*c;t[0]=o*l,t[4]=-u,t[8]=c*l,t[1]=d*u+b,t[5]=s*l,t[9]=f*u-h,t[2]=h*u-f,t[6]=a*l,t[10]=b*u+d}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(DN,e,LN)}lookAt(e,t,n){let i=this.elements;if(si.subVectors(e,t),si.lengthSq()===0)si.z=1;if(si.normalize(),is.crossVectors(n,si),is.lengthSq()===0){if(Math.abs(n.z)===1)si.x+=0.0001;else si.z+=0.0001;si.normalize(),is.crossVectors(n,si)}return is.normalize(),Lu.crossVectors(si,is),i[0]=is.x,i[4]=Lu.x,i[8]=si.x,i[1]=is.y,i[5]=Lu.y,i[9]=si.y,i[2]=is.z,i[6]=Lu.z,i[10]=si.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],a=n[4],o=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],h=n[2],b=n[6],m=n[10],g=n[14],p=n[3],x=n[7],_=n[11],y=n[15],v=i[0],T=i[4],A=i[8],E=i[12],w=i[1],P=i[5],S=i[9],I=i[13],U=i[2],N=i[6],F=i[10],D=i[14],O=i[3],K=i[7],B=i[11],X=i[15];return r[0]=s*v+a*w+o*U+c*O,r[4]=s*T+a*P+o*N+c*K,r[8]=s*A+a*S+o*F+c*B,r[12]=s*E+a*I+o*D+c*X,r[1]=l*v+u*w+d*U+f*O,r[5]=l*T+u*P+d*N+f*K,r[9]=l*A+u*S+d*F+f*B,r[13]=l*E+u*I+d*D+f*X,r[2]=h*v+b*w+m*U+g*O,r[6]=h*T+b*P+m*N+g*K,r[10]=h*A+b*S+m*F+g*B,r[14]=h*E+b*I+m*D+g*X,r[3]=p*v+x*w+_*U+y*O,r[7]=p*T+x*P+_*N+y*K,r[11]=p*A+x*S+_*F+y*B,r[15]=p*E+x*I+_*D+y*X,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],a=e[5],o=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],h=e[3],b=e[7],m=e[11],g=e[15],p=o*f-c*d,x=a*f-c*u,_=a*d-o*u,y=s*f-c*l,v=s*d-o*l,T=s*u-a*l;return t*(b*p-m*x+g*_)-n*(h*p-m*y+g*v)+i*(h*x-b*y+g*T)-r*(h*_-b*v+m*T)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],i=e[8],r=e[1],s=e[5],a=e[9],o=e[2],c=e[6],l=e[10];return t*(s*l-a*c)-n*(r*l-a*o)+i*(r*c-s*o)}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],a=e[5],o=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],h=e[12],b=e[13],m=e[14],g=e[15],p=t*a-n*s,x=t*o-i*s,_=t*c-r*s,y=n*o-i*a,v=n*c-r*a,T=i*c-r*o,A=l*b-u*h,E=l*m-d*h,w=l*g-f*h,P=u*m-d*b,S=u*g-f*b,I=d*g-f*m,U=p*I-x*S+_*P+y*w-v*E+T*A;if(U===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let N=1/U;return e[0]=(a*I-o*S+c*P)*N,e[1]=(i*S-n*I-r*P)*N,e[2]=(b*T-m*v+g*y)*N,e[3]=(d*v-u*T-f*y)*N,e[4]=(o*w-s*I-c*E)*N,e[5]=(t*I-i*w+r*E)*N,e[6]=(m*_-h*T-g*x)*N,e[7]=(l*T-d*_+f*x)*N,e[8]=(s*S-a*w+c*A)*N,e[9]=(n*w-t*S-r*A)*N,e[10]=(h*v-b*_+g*p)*N,e[11]=(u*_-l*v-f*p)*N,e[12]=(a*E-s*P-o*A)*N,e[13]=(t*P-n*E+i*A)*N,e[14]=(b*x-h*y-m*p)*N,e[15]=(l*y-u*x+d*p)*N,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:a,z:o}=e,c=r*s,l=r*a;return this.set(c*s+n,c*a-i*o,c*o+i*a,0,c*a+i*o,l*a+n,l*o-i*s,0,c*o-i*a,l*o+i*s,r*o*o+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:a,_w:o}=t,c=r+r,l=s+s,u=a+a,d=r*c,f=r*l,h=r*u,b=s*l,m=s*u,g=a*u,p=o*c,x=o*l,_=o*u,{x:y,y:v,z:T}=n;return i[0]=(1-(b+g))*y,i[1]=(f+_)*y,i[2]=(h-x)*y,i[3]=0,i[4]=(f-_)*v,i[5]=(1-(d+g))*v,i[6]=(m+p)*v,i[7]=0,i[8]=(h+x)*T,i[9]=(m-p)*T,i[10]=(1-(d+b))*T,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=ao.set(i[0],i[1],i[2]).length(),a=ao.set(i[4],i[5],i[6]).length(),o=ao.set(i[8],i[9],i[10]).length();if(r<0)s=-s;Oi.copy(this);let c=1/s,l=1/a,u=1/o;return Oi.elements[0]*=c,Oi.elements[1]*=c,Oi.elements[2]*=c,Oi.elements[4]*=l,Oi.elements[5]*=l,Oi.elements[6]*=l,Oi.elements[8]*=u,Oi.elements[9]*=u,Oi.elements[10]*=u,t.setFromRotationMatrix(Oi),n.x=s,n.y=a,n.z=o,this}makePerspective(e,t,n,i,r,s,a=2000,o=!1){let c=this.elements,l=2*r/(t-e),u=2*r/(n-i),d=(t+e)/(t-e),f=(n+i)/(n-i),h,b;if(o)h=r/(s-r),b=s*r/(s-r);else if(a===2000)h=-(s+r)/(s-r),b=-2*s*r/(s-r);else if(a===2001)h=-s/(s-r),b=-s*r/(s-r);else throw Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=h,c[14]=b,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,i,r,s,a=2000,o=!1){let c=this.elements,l=2/(t-e),u=2/(n-i),d=-(t+e)/(t-e),f=-(n+i)/(n-i),h,b;if(o)h=1/(s-r),b=s/(s-r);else if(a===2000)h=-2/(s-r),b=-(s+r)/(s-r);else if(a===2001)h=-1/(s-r),b=-r/(s-r);else throw Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=h,c[14]=b,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}};ao=new j,Oi=new Qe,DN=new j(0,0,0),LN=new j(1,1,1),is=new j,Lu=new j,si=new j,mE=new Qe,gE=new ln;ur=class ur{constructor(e=0,t=0,n=0,i=ur.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],a=i[8],o=i[1],c=i[5],l=i[9],u=i[2],d=i[6],f=i[10];switch(t){case"XYZ":if(this._y=Math.asin(ct(a,-1,1)),Math.abs(a)<0.9999999)this._x=Math.atan2(-l,f),this._z=Math.atan2(-s,r);else this._x=Math.atan2(d,c),this._z=0;break;case"YXZ":if(this._x=Math.asin(-ct(l,-1,1)),Math.abs(l)<0.9999999)this._y=Math.atan2(a,f),this._z=Math.atan2(o,c);else this._y=Math.atan2(-u,r),this._z=0;break;case"ZXY":if(this._x=Math.asin(ct(d,-1,1)),Math.abs(d)<0.9999999)this._y=Math.atan2(-u,f),this._z=Math.atan2(-s,c);else this._y=0,this._z=Math.atan2(o,r);break;case"ZYX":if(this._y=Math.asin(-ct(u,-1,1)),Math.abs(u)<0.9999999)this._x=Math.atan2(d,f),this._z=Math.atan2(o,r);else this._x=0,this._z=Math.atan2(-s,c);break;case"YZX":if(this._z=Math.asin(ct(o,-1,1)),Math.abs(o)<0.9999999)this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,r);else this._x=0,this._y=Math.atan2(a,f);break;case"XZY":if(this._z=Math.asin(-ct(s,-1,1)),Math.abs(s)<0.9999999)this._x=Math.atan2(d,c),this._y=Math.atan2(a,r);else this._x=Math.atan2(-l,f),this._y=0;break;default:je("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}if(this._order=t,n===!0)this._onChangeCallback();return this}setFromQuaternion(e,t,n){return mE.makeRotationFromQuaternion(e),this.setFromRotationMatrix(mE,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return gE.setFromEuler(this),this.setFromQuaternion(gE,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}};ur.DEFAULT_ORDER="XYZ";bE=new j,oo=new ln,Pr=new Qe,Fu=new j,Dc=new j,UN=new j,BN=new ln,xE=new j(1,0,0),yE=new j(0,1,0),_E=new j(0,0,1),vE={type:"added"},zN={type:"removed"},co={type:"childadded",child:null},lp={type:"childremoved",child:null};Dt=class Dt extends Vi{constructor(){super();this.isObject3D=!0,Object.defineProperty(this,"id",{value:FN++}),this.uuid=Fi(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Dt.DEFAULT_UP.clone();let e=new j,t=new ur,n=new ln,i=new j(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 Qe},normalMatrix:{value:new tt}}),this.matrix=new Qe,this.matrixWorld=new Qe,this.matrixAutoUpdate=Dt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Ad,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 oo.setFromAxisAngle(e,t),this.quaternion.multiply(oo),this}rotateOnWorldAxis(e,t){return oo.setFromAxisAngle(e,t),this.quaternion.premultiply(oo),this}rotateX(e){return this.rotateOnAxis(xE,e)}rotateY(e){return this.rotateOnAxis(yE,e)}rotateZ(e){return this.rotateOnAxis(_E,e)}translateOnAxis(e,t){return bE.copy(e).applyQuaternion(this.quaternion),this.position.add(bE.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(xE,e)}translateY(e){return this.translateOnAxis(yE,e)}translateZ(e){return this.translateOnAxis(_E,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Pr.copy(this.matrixWorld).invert())}lookAt(e,t,n){if(e.isVector3)Fu.copy(e);else Fu.set(e,t,n);let i=this.parent;if(this.updateWorldMatrix(!0,!1),Dc.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight)Pr.lookAt(Dc,Fu,this.up);else Pr.lookAt(Fu,Dc,this.up);if(this.quaternion.setFromRotationMatrix(Pr),i)Pr.extractRotation(i.matrixWorld),oo.setFromRotationMatrix(Pr),this.quaternion.premultiply(oo.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 Ze("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(vE),co.child=e,this.dispatchEvent(co),co.child=null;else Ze("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(zN),lp.child=e,this.dispatchEvent(lp),lp.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),Pr.copy(this.matrixWorld).invert(),e.parent!==null)e.parent.updateWorldMatrix(!0,!1),Pr.multiply(e.parent.matrixWorld);return e.applyMatrix4(Pr),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(vE),co.child=e,this.dispatchEvent(co),co.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(Dc,e,UN),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Dc,BN,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}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,a=r.length;s<a;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,i.name=this.name,i.castShadow=this.castShadow,i.receiveShadow=this.receiveShadow,i.visible=this.visible,i.frustumCulled=this.frustumCulled,i.renderOrder=this.renderOrder,i.static=this.static,i.matrixAutoUpdate=this.matrixAutoUpdate,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.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((a)=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map((a)=>({...a})),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(a,o){if(a[o.uuid]===void 0)a[o.uuid]=o.toJSON(e);return o.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 a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){let o=a.shapes;if(Array.isArray(o))for(let c=0,l=o.length;c<l;c++){let u=o[c];r(e.shapes,u)}else r(e.shapes,o)}}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 a=[];for(let o=0,c=this.material.length;o<c;o++)a.push(r(e.materials,this.material[o]));i.material=a}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let a=0;a<this.children.length;a++)i.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let a=0;a<this.animations.length;a++){let o=this.animations[a];i.animations.push(r(e.animations,o))}}if(t){let a=s(e.geometries),o=s(e.materials),c=s(e.textures),l=s(e.images),u=s(e.shapes),d=s(e.skeletons),f=s(e.animations),h=s(e.nodes);if(a.length>0)n.geometries=a;if(o.length>0)n.materials=o;if(c.length>0)n.textures=c;if(l.length>0)n.images=l;if(u.length>0)n.shapes=u;if(d.length>0)n.skeletons=d;if(f.length>0)n.animations=f;if(h.length>0)n.nodes=h}return n.object=i,n;function s(a){let o=[];for(let c in a){let l=a[c];delete l.metadata,o.push(l)}return o}}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}dispose(){this.dispatchEvent({type:"dispose"})}};Dt.DEFAULT_UP=new j(0,1,0);Dt.DEFAULT_MATRIX_AUTO_UPDATE=!0;Dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;cr=class cr extends Dt{constructor(){super();this.isGroup=!0,this.type="Group"}};VN={type:"move"};$T={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},rs={h:0,s:0,l:0},Uu={h:0,s:0,l:0};qe=class qe{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,ot.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=ot.workingColorSpace){return this.r=e,this.g=t,this.b=n,ot.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=ot.workingColorSpace){if(e=Im(e,1),t=ct(t,0,1),n=ct(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=up(s,r,e+0.3333333333333333),this.g=up(s,r,e),this.b=up(s,r,e-0.3333333333333333)}return ot.colorSpaceToWorking(this,i),this}setStyle(e,t="srgb"){function n(r){if(r===void 0)return;if(parseFloat(r)<1)je("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r,s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,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(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:je("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 je("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t="srgb"){let n=$T[e.toLowerCase()];if(n!==void 0)this.setHex(n,t);else je("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=Ur(e.r),this.g=Ur(e.g),this.b=Ur(e.b),this}copyLinearToSRGB(e){return this.r=_o(e.r),this.g=_o(e.g),this.b=_o(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e="srgb"){return ot.workingToColorSpace(On.copy(this),e),Math.round(ct(On.r*255,0,255))*65536+Math.round(ct(On.g*255,0,255))*256+Math.round(ct(On.b*255,0,255))}getHexString(e="srgb"){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ot.workingColorSpace){ot.workingToColorSpace(On.copy(this),t);let{r:n,g:i,b:r}=On,s=Math.max(n,i,r),a=Math.min(n,i,r),o,c,l=(a+s)/2;if(a===s)o=0,c=0;else{let u=s-a;switch(c=l<=0.5?u/(s+a):u/(2-s-a),s){case n:o=(i-r)/u+(i<r?6:0);break;case i:o=(r-n)/u+2;break;case r:o=(n-i)/u+4;break}o/=6}return e.h=o,e.s=c,e.l=l,e}getRGB(e,t=ot.workingColorSpace){return ot.workingToColorSpace(On.copy(this),t),e.r=On.r,e.g=On.g,e.b=On.b,e}getStyle(e="srgb"){ot.workingToColorSpace(On.copy(this),e);let{r:t,g:n,b:i}=On;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(rs),this.setHSL(rs.h+e,rs.s+t,rs.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(rs),e.getHSL(Uu);let n=Gc(rs.h,Uu.h,t),i=Gc(rs.s,Uu.s,t),r=Gc(rs.l,Uu.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}};On=new qe;qe.NAMES=$T;Po=class Po extends Dt{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 ur,this.environmentIntensity=1,this.environmentRotation=new ur,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();return t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}};ki=new j,Or=new j,dp=new j,kr=new j,lo=new j,uo=new j,EE=new j,fp=new j,hp=new j,pp=new j,mp=new Pt,gp=new Pt,bp=new Pt;Dr=[new j,new j,new j,new j,new j,new j,new j,new j],Di=new j,Bu=new hn,fo=new j,ho=new j,po=new j,ss=new j,as=new j,ha=new j,Lc=new j,zu=new j,Vu=new j,pa=new j;cn=new j,ju=new Ke;vn=class vn extends Vi{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:jN++}),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++)ju.fromBufferAttribute(this,t),ju.applyMatrix3(e),this.setXY(t,ju.x,ju.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)cn.fromBufferAttribute(this,t),cn.applyMatrix3(e),this.setXYZ(t,cn.x,cn.y,cn.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)cn.fromBufferAttribute(this,t),cn.applyMatrix4(e),this.setXYZ(t,cn.x,cn.y,cn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)cn.fromBufferAttribute(this,t),cn.applyNormalMatrix(e),this.setXYZ(t,cn.x,cn.y,cn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)cn.fromBufferAttribute(this,t),cn.transformDirection(e),this.setXYZ(t,cn.x,cn.y,cn.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=Li(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=Li(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=Li(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=Li(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=Li(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};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:"dispose"})}};wd=class wd extends vn{constructor(e,t,n){super(new Uint16Array(e),t,n)}};Sd=class Sd extends vn{constructor(e,t,n){super(new Uint32Array(e),t,n)}};Wn=class Wn extends vn{constructor(e,t,n){super(new Float32Array(e),t,n)}};HN=new hn,Fc=new j,yp=new j;xi=new Qe,_p=new Dt,mo=new j,ai=new hn,Uc=new hn,_n=new j;Dn=class Dn extends Vi{constructor(){super();this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:GN++}),this.uuid=Fi(),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((pN(e))?Sd:wd)(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 tt().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 xi.makeRotationFromQuaternion(e),this.applyMatrix4(xi),this}rotateX(e){return xi.makeRotationX(e),this.applyMatrix4(xi),this}rotateY(e){return xi.makeRotationY(e),this.applyMatrix4(xi),this}rotateZ(e){return xi.makeRotationZ(e),this.applyMatrix4(xi),this}translate(e,t,n){return xi.makeTranslation(e,t,n),this.applyMatrix4(xi),this}scale(e,t,n){return xi.makeScale(e,t,n),this.applyMatrix4(xi),this}lookAt(e){return _p.lookAt(e),_p.updateMatrix(),this.applyMatrix4(_p.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(mo).negate(),this.translate(mo.x,mo.y,mo.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 Wn(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)je("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 hn;let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ze("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(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n<i;n++){let r=t[n];if(ai.setFromBufferAttribute(r),this.morphTargetsRelative)_n.addVectors(this.boundingBox.min,ai.min),this.boundingBox.expandByPoint(_n),_n.addVectors(this.boundingBox.max,ai.max),this.boundingBox.expandByPoint(_n);else this.boundingBox.expandByPoint(ai.min),this.boundingBox.expandByPoint(ai.max)}}else this.boundingBox.makeEmpty();if(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))Ze('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 li;let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ze("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new j,1/0);return}if(e){let n=this.boundingSphere.center;if(ai.setFromBufferAttribute(e),t)for(let r=0,s=t.length;r<s;r++){let a=t[r];if(Uc.setFromBufferAttribute(a),this.morphTargetsRelative)_n.addVectors(ai.min,Uc.min),ai.expandByPoint(_n),_n.addVectors(ai.max,Uc.max),ai.expandByPoint(_n);else ai.expandByPoint(Uc.min),ai.expandByPoint(Uc.max)}ai.getCenter(n);let i=0;for(let r=0,s=e.count;r<s;r++)_n.fromBufferAttribute(e,r),i=Math.max(i,n.distanceToSquared(_n));if(t)for(let r=0,s=t.length;r<s;r++){let a=t[r],o=this.morphTargetsRelative;for(let c=0,l=a.count;c<l;c++){if(_n.fromBufferAttribute(a,c),o)mo.fromBufferAttribute(e,c),_n.add(mo);i=Math.max(i,n.distanceToSquared(_n))}}if(this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius))Ze('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){Ze("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 vn(new Float32Array(4*n.count),4),this.setAttribute("tangent",s);let a=[],o=[];for(let A=0;A<n.count;A++)a[A]=new j,o[A]=new j;let c=new j,l=new j,u=new j,d=new Ke,f=new Ke,h=new Ke,b=new j,m=new j;function g(A,E,w){c.fromBufferAttribute(n,A),l.fromBufferAttribute(n,E),u.fromBufferAttribute(n,w),d.fromBufferAttribute(r,A),f.fromBufferAttribute(r,E),h.fromBufferAttribute(r,w),l.sub(c),u.sub(c),f.sub(d),h.sub(d);let P=1/(f.x*h.y-h.x*f.y);if(!isFinite(P))return;b.copy(l).multiplyScalar(h.y).addScaledVector(u,-f.y).multiplyScalar(P),m.copy(u).multiplyScalar(f.x).addScaledVector(l,-h.x).multiplyScalar(P),a[A].add(b),a[E].add(b),a[w].add(b),o[A].add(m),o[E].add(m),o[w].add(m)}let p=this.groups;if(p.length===0)p=[{start:0,count:e.count}];for(let A=0,E=p.length;A<E;++A){let w=p[A],{start:P,count:S}=w;for(let I=P,U=P+S;I<U;I+=3)g(e.getX(I+0),e.getX(I+1),e.getX(I+2))}let x=new j,_=new j,y=new j,v=new j;function T(A){y.fromBufferAttribute(i,A),v.copy(y);let E=a[A];x.copy(E),x.sub(y.multiplyScalar(y.dot(E))).normalize(),_.crossVectors(v,E);let P=_.dot(o[A])<0?-1:1;s.setXYZW(A,x.x,x.y,x.z,P)}for(let A=0,E=p.length;A<E;++A){let w=p[A],{start:P,count:S}=w;for(let I=P,U=P+S;I<U;I+=3)T(e.getX(I+0)),T(e.getX(I+1)),T(e.getX(I+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 vn(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let d=0,f=n.count;d<f;d++)n.setXYZ(d,0,0,0);let i=new j,r=new j,s=new j,a=new j,o=new j,c=new j,l=new j,u=new j;if(e)for(let d=0,f=e.count;d<f;d+=3){let h=e.getX(d+0),b=e.getX(d+1),m=e.getX(d+2);i.fromBufferAttribute(t,h),r.fromBufferAttribute(t,b),s.fromBufferAttribute(t,m),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),a.fromBufferAttribute(n,h),o.fromBufferAttribute(n,b),c.fromBufferAttribute(n,m),a.add(l),o.add(l),c.add(l),n.setXYZ(h,a.x,a.y,a.z),n.setXYZ(b,o.x,o.y,o.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let d=0,f=t.count;d<f;d+=3)i.fromBufferAttribute(t,d+0),r.fromBufferAttribute(t,d+1),s.fromBufferAttribute(t,d+2),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),n.setXYZ(d+0,l.x,l.y,l.z),n.setXYZ(d+1,l.x,l.y,l.z),n.setXYZ(d+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++)_n.fromBufferAttribute(e,t),_n.normalize(),e.setXYZ(t,_n.x,_n.y,_n.z)}toNonIndexed(){function e(a,o){let{array:c,itemSize:l,normalized:u}=a,d=new c.constructor(o.length*l),f=0,h=0;for(let b=0,m=o.length;b<m;b++){if(a.isInterleavedBufferAttribute)f=o[b]*a.data.stride+a.offset;else f=o[b]*l;for(let g=0;g<l;g++)d[h++]=c[f++]}return new vn(d,l,u)}if(this.index===null)return je("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let t=new Dn,n=this.index.array,i=this.attributes;for(let a in i){let o=i[a],c=e(o,n);t.setAttribute(a,c)}let r=this.morphAttributes;for(let a in r){let o=[],c=r[a];for(let l=0,u=c.length;l<u;l++){let d=c[l],f=e(d,n);o.push(f)}t.morphAttributes[a]=o}t.morphTargetsRelative=this.morphTargetsRelative;let s=this.groups;for(let a=0,o=s.length;a<o;a++){let c=s[a];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,e.name=this.name,Object.keys(this.userData).length>0)e.userData=this.userData;if(this.parameters!==void 0&&this._transformed!==!0){let o=this.parameters;for(let c in o)if(o[c]!==void 0)e[c]=o[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 o in n){let c=n[o];e.data.attributes[o]=c.toJSON(e.data)}let i={},r=!1;for(let o in this.morphAttributes){let c=this.morphAttributes[o],l=[];for(let u=0,d=c.length;u<d;u++){let f=c[u];l.push(f.toJSON(e.data))}if(l.length>0)i[o]=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 a=this.boundingSphere;if(a!==null)e.data.boundingSphere=a.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 d=0,f=u.length;d<f;d++)l.push(u[d].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 a=e.boundingBox;if(a!==null)this.boundingBox=a.clone();let o=e.boundingSphere;if(o!==null)this.boundingSphere=o.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"})}};Hn=new j;vp=new j,$N=new j,KN=new tt;Xn=class Xn extends Vi{constructor(){super();this.isMaterial=!0,Object.defineProperty(this,"id",{value:WN++}),this.uuid=Fi(),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 qe(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){je(`Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){je(`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,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor)n.color=this.color.getHex();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)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.retroreflectivity!==void 0)n.retroreflectivity=this.retroreflectivity;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)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.sizeAttenuation!==void 0)n.sizeAttenuation=this.sizeAttenuation;if(Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0)n.clippingPlanes=this.clippingPlanes.map((r)=>r.toJSON());if(this.rotation!==void 0)n.rotation=this.rotation;if(this.depthPacking!==void 0)n.depthPacking=this.depthPacking;if(this.linewidth!==void 0)n.linewidth=this.linewidth;if(this.linecap!==void 0)n.linecap=this.linecap;if(this.linejoin!==void 0)n.linejoin=this.linejoin;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.wireframe!==void 0)n.wireframe=this.wireframe;if(this.wireframeLinewidth!==void 0)n.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!==void 0)n.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!==void 0)n.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading!==void 0)n.flatShading=this.flatShading;if(this.fog!==void 0)n.fog=this.fog;if(Object.keys(this.userData).length>0)n.userData=this.userData;function i(r){let s=[];for(let a in r){let o=r[a];delete o.metadata,s.push(o)}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 qe().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.retroreflectivity!==void 0)this.retroreflectivity=e.retroreflectivity;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.clippingPlanes!==void 0)this.clippingPlanes=e.clippingPlanes.map((n)=>new yi().fromJSON(n));if(e.clipIntersection!==void 0)this.clipIntersection=e.clipIntersection;if(e.clipShadows!==void 0)this.clipShadows=e.clipShadows;if(e.depthPacking!==void 0)this.depthPacking=e.depthPacking;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.linecap!==void 0)this.linecap=e.linecap;if(e.linejoin!==void 0)this.linejoin=e.linejoin;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 Ke().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 Ke().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++}};Lr=new j,Ep=new j,Hu=new j,Gu=new j;mr=class mr extends Xn{constructor(e){super();this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new qe(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 ur,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}};TE=new Qe,ma=new ms,$u=new li,AE=new j,Ku=new j,Wu=new j,Xu=new j,Tp=new j,qu=new j,wE=new j,Ju=new j;jt=class jt extends Dt{constructor(e=new Dn,t=new mr){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 a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(e,t){let n=this.geometry,i=n.attributes.position,r=n.morphAttributes.position,s=n.morphTargetsRelative;t.fromBufferAttribute(i,e);let a=this.morphTargetInfluences;if(r&&a){qu.set(0,0,0);for(let o=0,c=r.length;o<c;o++){let l=a[o],u=r[o];if(l===0)continue;if(Tp.fromBufferAttribute(u,e),s)qu.addScaledVector(Tp,l);else qu.addScaledVector(Tp.sub(t),l)}t.add(qu)}return t}intersectsFrustum(e){return e.intersectsObject(this)}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($u.copy(n.boundingSphere),$u.applyMatrix4(r),ma.copy(e.ray).recast(e.near),$u.containsPoint(ma.origin)===!1){if(ma.intersectSphere($u,AE)===null)return;if(ma.origin.distanceToSquared(AE)>(e.far-e.near)**2)return}if(TE.copy(r).invert(),ma.copy(e.ray).applyMatrix4(TE),n.boundingBox!==null){if(ma.intersectsBox(n.boundingBox)===!1)return}this._computeIntersections(e,t,ma)}_computeIntersections(e,t,n){let i,r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,c=r.attributes.uv,l=r.attributes.uv1,u=r.attributes.normal,{groups:d,drawRange:f}=r;if(a!==null)if(Array.isArray(s))for(let h=0,b=d.length;h<b;h++){let m=d[h],g=s[m.materialIndex],p=Math.max(m.start,f.start),x=Math.min(a.count,Math.min(m.start+m.count,f.start+f.count));for(let _=p,y=x;_<y;_+=3){let v=a.getX(_),T=a.getX(_+1),A=a.getX(_+2);if(i=Zu(this,g,e,n,c,l,u,v,T,A),i)i.faceIndex=Math.floor(_/3),i.face.materialIndex=m.materialIndex,t.push(i)}}else{let h=Math.max(0,f.start),b=Math.min(a.count,f.start+f.count);for(let m=h,g=b;m<g;m+=3){let p=a.getX(m),x=a.getX(m+1),_=a.getX(m+2);if(i=Zu(this,s,e,n,c,l,u,p,x,_),i)i.faceIndex=Math.floor(m/3),t.push(i)}}else if(o!==void 0)if(Array.isArray(s))for(let h=0,b=d.length;h<b;h++){let m=d[h],g=s[m.materialIndex],p=Math.max(m.start,f.start),x=Math.min(o.count,Math.min(m.start+m.count,f.start+f.count));for(let _=p,y=x;_<y;_+=3){let v=_,T=_+1,A=_+2;if(i=Zu(this,g,e,n,c,l,u,v,T,A),i)i.faceIndex=Math.floor(_/3),i.face.materialIndex=m.materialIndex,t.push(i)}}else{let h=Math.max(0,f.start),b=Math.min(o.count,f.start+f.count);for(let m=h,g=b;m<g;m+=3){let p=m,x=m+1,_=m+2;if(i=Zu(this,s,e,n,c,l,u,p,x,_),i)i.faceIndex=Math.floor(m/3),t.push(i)}}}};Bc=new Pt,SE=new Pt,ME=new Pt,qN=new Pt,RE=new Qe,Yu=new j,Ap=new li,IE=new Qe,wp=new ms;Md=class Md extends jt{constructor(e,t){super(e,t);this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new Qe,this.bindMatrixInverse=new Qe,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;if(this.boundingBox===null)this.boundingBox=new hn;this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,Yu),this.boundingBox.expandByPoint(Yu)}computeBoundingSphere(){let e=this.geometry;if(this.boundingSphere===null)this.boundingSphere=new li;this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,Yu),this.boundingSphere.expandByPoint(Yu)}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(Ap.copy(this.boundingSphere),Ap.applyMatrix4(i),e.ray.intersectsSphere(Ap)===!1)return;if(IE.copy(i).invert(),wp.copy(e.ray).applyMatrix4(IE),this.boundingBox!==null){if(wp.intersectsBox(this.boundingBox)===!1)return}this._computeIntersections(e,t,wp)}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 Pt,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 je("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,i=this.geometry;if(SE.fromBufferAttribute(i.attributes.skinIndex,e),ME.fromBufferAttribute(i.attributes.skinWeight,e),t.isVector4)Bc.copy(t),t.set(0,0,0,0);else Bc.set(...t,1),t.set(0,0,0);Bc.applyMatrix4(this.bindMatrix);for(let r=0;r<4;r++){let s=ME.getComponent(r);if(s!==0){let a=SE.getComponent(r);RE.multiplyMatrices(n.bones[a].matrixWorld,n.boneInverses[a]),t.addScaledVector(qN.copy(Bc).applyMatrix4(RE),s)}}if(t.isVector4)t.w=Bc.w;return t.applyMatrix4(this.bindMatrixInverse)}};nl=class nl extends Dt{constructor(){super();this.isBone=!0,this.type="Bone"}};il=class il extends en{constructor(e=null,t=1,n=1,i,r,s,a,o,c=1003,l=1003,u,d){super(null,s,a,o,c,l,i,r,u,d);this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};CE=new Qe,JN=new Qe;ls=class ls extends vn{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}};go=new Qe,NE=new Qe,Qu=[],PE=new hn,ZN=new Qe,zc=new jt,Vc=new li;ko=class ko extends jt{constructor(e,t,n){super(e,t);this.isInstancedMesh=!0,this.instanceMatrix=new ls(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,ZN)}computeBoundingBox(){let e=this.geometry,t=this.count;if(this.boundingBox===null)this.boundingBox=new hn;if(e.boundingBox===null)e.computeBoundingBox();this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,go),PE.copy(e.boundingBox).applyMatrix4(go),this.boundingBox.union(PE)}computeBoundingSphere(){let e=this.geometry,t=this.count;if(this.boundingSphere===null)this.boundingSphere=new li;if(e.boundingSphere===null)e.computeBoundingSphere();this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,go),Vc.copy(e.boundingSphere).applyMatrix4(go),this.boundingSphere.union(Vc)}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 a=0;a<n.length;a++)n[a]=i[s+a]}raycast(e,t){let n=this.matrixWorld,i=this.count;if(zc.geometry=this.geometry,zc.material=this.material,zc.material===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(Vc.copy(this.boundingSphere),Vc.applyMatrix4(n),e.ray.intersectsSphere(Vc)===!1)return;for(let r=0;r<i;r++){this.getMatrixAt(r,go),NE.multiplyMatrices(n,go),zc.matrixWorld=NE,zc.raycast(e,Qu);for(let s=0,a=Qu.length;s<a;s++){let o=Qu[s];o.instanceId=r,o.object=this,t.push(o)}Qu.length=0}}setColorAt(e,t){if(this.instanceColor===null)this.instanceColor=new ls(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 il(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 a=this.geometry.morphTargetsRelative?1:1-s,o=i*e;return r[o]=a,r.set(n,o+1),this}updateMorphTargets(){}dispose(){if(super.dispose(),this.morphTexture!==null)this.morphTexture.dispose(),this.morphTexture=null}};ga=new li,YN=new Ke(0.5,0.5),ed=new j;al=class al extends Xn{constructor(e){super();this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new qe(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}};cd=new j,ld=new j,OE=new Qe,jc=new ms,td=new li,Sp=new j,kE=new j;gs=class gs extends Dt{constructor(e=new Dn,t=new al){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++)cd.fromBufferAttribute(t,i-1),ld.fromBufferAttribute(t,i),n[i]=n[i-1],n[i]+=cd.distanceTo(ld);e.setAttribute("lineDistance",new Wn(n,1))}else je("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}intersectsFrustum(e){return e.intersectsObject(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(td.copy(n.boundingSphere),td.applyMatrix4(i),td.radius+=r,e.ray.intersectsSphere(td)===!1)return;OE.copy(i).invert(),jc.copy(e.ray).applyMatrix4(OE);let a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,c=this.isLineSegments?2:1,l=n.index,d=n.attributes.position;if(l!==null){let f=Math.max(0,s.start),h=Math.min(l.count,s.start+s.count);for(let b=f,m=h-1;b<m;b+=c){let g=l.getX(b),p=l.getX(b+1),x=nd(this,e,jc,o,g,p,b);if(x)t.push(x)}if(this.isLineLoop){let b=l.getX(h-1),m=l.getX(f),g=nd(this,e,jc,o,b,m,h-1);if(g)t.push(g)}}else{let f=Math.max(0,s.start),h=Math.min(d.count,s.start+s.count);for(let b=f,m=h-1;b<m;b+=c){let g=nd(this,e,jc,o,b,b+1,b);if(g)t.push(g)}if(this.isLineLoop){let b=nd(this,e,jc,o,h-1,f,h-1);if(b)t.push(b)}}}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 a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}};DE=new j,LE=new j;Rd=class Rd extends gs{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)DE.fromBufferAttribute(t,i),LE.fromBufferAttribute(t,i+1),n[i]=i===0?0:n[i-1],n[i+1]=n[i]+DE.distanceTo(LE);e.setAttribute("lineDistance",new Wn(n,1))}else je("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}};Id=class Id extends gs{constructor(e,t){super(e,t);this.isLineLoop=!0,this.type="LineLoop"}};ol=class ol extends Xn{constructor(e){super();this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new qe(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}};FE=new Qe,Ip=new ms,id=new li,rd=new j;Do=class Do extends Dt{constructor(e=new Dn,t=new ol){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}intersectsFrustum(e){return e.intersectsObject(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(id.copy(n.boundingSphere),id.applyMatrix4(i),id.radius+=r,e.ray.intersectsSphere(id)===!1)return;FE.copy(i).invert(),Ip.copy(e.ray).applyMatrix4(FE);let a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,c=n.index,u=n.attributes.position;if(c!==null){let d=Math.max(0,s.start),f=Math.min(c.count,s.start+s.count);for(let h=d,b=f;h<b;h++){let m=c.getX(h);rd.fromBufferAttribute(u,m),UE(rd,m,o,i,e,t,this)}}else{let d=Math.max(0,s.start),f=Math.min(u.count,s.start+s.count);for(let h=d,b=f;h<b;h++)rd.fromBufferAttribute(u,h),UE(rd,h,o,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 a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}};Cd=class Cd extends en{constructor(e=[],t=301,n,i,r,s,a,o,c,l){super(e,t,n,i,r,s,a,o,c,l);this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}};wa=class wa extends en{constructor(e,t,n=1014,i,r,s,a=1003,o=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 d={width:e,height:t,depth:u};super(d,i,r,s,a,o,l,n,c);this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Qc(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}};Om=class Om extends wa{constructor(e,t=1014,n=301,i,r,s=1003,a=1003,o,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,a,o,c);this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}};Nd=class Nd extends en{constructor(e=null){super();this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}};bs=class bs extends Dn{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 a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);let o=[],c=[],l=[],u=[],d=0,f=0;h("z","y","x",-1,-1,n,t,e,s,r,0),h("z","y","x",1,-1,n,t,-e,s,r,1),h("x","z","y",1,1,e,n,t,i,s,2),h("x","z","y",1,-1,e,n,-t,i,s,3),h("x","y","z",1,-1,e,t,n,i,r,4),h("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(o),this.setAttribute("position",new Wn(c,3)),this.setAttribute("normal",new Wn(l,3)),this.setAttribute("uv",new Wn(u,2));function h(b,m,g,p,x,_,y,v,T,A,E){let w=_/T,P=y/A,S=_/2,I=y/2,U=v/2,N=T+1,F=A+1,D=0,O=0,K=new j;for(let B=0;B<F;B++){let X=B*P-I;for(let q=0;q<N;q++){let le=q*w-S;K[b]=le*p,K[m]=X*x,K[g]=U,c.push(K.x,K.y,K.z),K[b]=0,K[m]=0,K[g]=v>0?1:-1,l.push(K.x,K.y,K.z),u.push(q/T),u.push(1-B/A),D+=1}}for(let B=0;B<A;B++)for(let X=0;X<T;X++){let q=d+X+N*B,le=d+X+N*(B+1),de=d+(X+1)+N*(B+1),Me=d+(X+1)+N*B;o.push(q,le,Me),o.push(le,de,Me),O+=6}a.addGroup(f,O,E),f+=O,d+=D}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new bs(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}};cl=class cl extends Dn{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,a=Math.floor(n),o=Math.floor(i),c=a+1,l=o+1,u=e/a,d=t/o,f=[],h=[],b=[],m=[];for(let g=0;g<l;g++){let p=g*d-s;for(let x=0;x<c;x++){let _=x*u-r;h.push(_,-p,0),b.push(0,0,1),m.push(x/a),m.push(1-g/o)}}for(let g=0;g<o;g++)for(let p=0;p<a;p++){let x=p+c*g,_=p+c*(g+1),y=p+1+c*(g+1),v=p+1+c*g;f.push(x,_,v),f.push(_,y,v)}this.setIndex(f),this.setAttribute("position",new Wn(h,3)),this.setAttribute("normal",new Wn(b,3)),this.setAttribute("uv",new Wn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new cl(e.width,e.height,e.widthSegments,e.heightSegments)}};KT={clone:Sa,merge:Ln};Ei=class Ei extends Xn{constructor(e){super();if(this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=eP,this.fragmentShader=tP,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=Sa(e.uniforms),this.uniformsGroups=QN(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 qe().setHex(i.value);break;case"v2":this.uniforms[n].value=new Ke().fromArray(i.value);break;case"v3":this.uniforms[n].value=new j().fromArray(i.value);break;case"v4":this.uniforms[n].value=new Pt().fromArray(i.value);break;case"m3":this.uniforms[n].value=new tt().fromArray(i.value);break;case"m4":this.uniforms[n].value=new Qe().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}};Dm=class Dm extends Ei{constructor(e){super(e);this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}};zr=class zr extends Xn{constructor(e){super();this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new qe(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 qe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ke(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 ur,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}};ui=class ui extends zr{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 Ke(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return ct(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 qe(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 qe(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new qe(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._retroreflectivity=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 retroreflectivity(){return this._retroreflectivity}set retroreflectivity(e){if(this._retroreflectivity>0!==e>0)this.version++;this._retroreflectivity=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.retroreflectivity=e.retroreflectivity,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}};Pd=class Pd extends Xn{constructor(e){super();this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new qe(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new qe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ke(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ur,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}};Lm=class Lm extends Xn{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}};Fm=class Fm extends Xn{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}};Um=class Um extends Vr{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,a=i[r],o=i[s];if(a===void 0)switch(this.getSettings_().endingStart){case 2401:r=e,a=2*t-n;break;case 2402:r=i.length-2,a=t+i[r]-i[r+1];break;default:r=e,a=n}if(o===void 0)switch(this.getSettings_().endingEnd){case 2401:s=e,o=2*n-t;break;case 2402:s=1,o=n+i[1]-i[0];break;default:s=e-1,o=t}let c=(n-t)*0.5,l=this.valueSize;this._weightPrev=c/(t-a),this._weightNext=c/(o-n),this._offsetPrev=r*l,this._offsetNext=s*l}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,c=o-a,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,h=(n-t)/(i-t),b=h*h,m=b*h,g=-d*m+2*d*b-d*h,p=(1+d)*m+(-1.5-2*d)*b+(-0.5+d)*h+1,x=(-1-f)*m+(1.5+f)*b+0.5*h,_=f*m-f*b;for(let y=0;y!==a;++y)r[y]=g*s[l+y]+p*s[c+y]+x*s[o+y]+_*s[u+y];return r}};Od=class Od extends Vr{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,c=o-a,l=(n-t)/(i-t),u=1-l;for(let d=0;d!==a;++d)r[d]=s[c+d]*u+s[o+d]*l;return r}};Bm=class Bm extends Vr{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e){return this.copySampleValue_(e-1)}};zm=class zm extends Vr{interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,c=o-a,l=this.inTangents,u=this.outTangents;if(!l||!u){let h=(n-t)/(i-t),b=1-h;for(let m=0;m!==a;++m)r[m]=s[c+m]*b+s[o+m]*h;return r}let d=a*2,f=e-1;for(let h=0;h!==a;++h){let b=s[c+h],m=s[o+h],g=f*d+h*2,p=u[g],x=u[g+1],_=e*d+h*2,y=l[_],v=l[_+1],T=sP(n,t,p,y,i);r[h]=WT(T,b,x,v,m)}return r}};di.prototype.ValueTypeName="";di.prototype.TimeBufferType=Float32Array;di.prototype.ValueBufferType=Float32Array;di.prototype.DefaultInterpolation=2301;xs=class xs extends di{constructor(e,t,n){super(e,t,n)}};xs.prototype.ValueTypeName="bool";xs.prototype.ValueBufferType=Array;xs.prototype.DefaultInterpolation=2300;xs.prototype.InterpolantFactoryMethodLinear=void 0;xs.prototype.InterpolantFactoryMethodSmooth=void 0;kd=class kd extends di{constructor(e,t,n,i){super(e,t,n,i)}};kd.prototype.ValueTypeName="color";ys=class ys extends di{constructor(e,t,n,i){super(e,t,n,i)}};ys.prototype.ValueTypeName="number";Vm=class Vm extends Vr{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-t)/(i-t),c=e*a;for(let l=c+a;c!==l;c+=4)ln.slerpFlat(r,0,s,c-a,s,c,o);return r}};_s=class _s extends di{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new Vm(this.times,this.values,this.getValueSize(),e)}};_s.prototype.ValueTypeName="quaternion";_s.prototype.InterpolantFactoryMethodSmooth=void 0;vs=class vs extends di{constructor(e,t,n){super(e,t,n)}};vs.prototype.ValueTypeName="string";vs.prototype.ValueBufferType=Array;vs.prototype.DefaultInterpolation=2300;vs.prototype.InterpolantFactoryMethodLinear=void 0;vs.prototype.InterpolantFactoryMethodSmooth=void 0;Ma=class Ma extends di{constructor(e,t,n,i){super(e,t,n,i)}};Ma.prototype.ValueTypeName="vector";lr={enabled:!1,files:{},add:function(e,t){if(this.enabled===!1)return;if(jE(e))return;this.files[e]=t},get:function(e){if(this.enabled===!1)return;if(jE(e))return;return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};XT=new ll;jr.DEFAULT_MATERIAL_NAME="__DEFAULT";Fr={};qT=class qT extends Error{constructor(e,t){super(e);this.response=t}};ul=class ul extends jr{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=lr.get(`file:${e}`);if(r!==void 0){this.manager.itemStart(e),setTimeout(()=>{if(t)t(r);this.manager.itemEnd(e)},0);return}if(Fr[e]!==void 0){Fr[e].push({onLoad:t,onProgress:n,onError:i});return}Fr[e]=[],Fr[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}),a=this.mimeType,o=this.responseType;fetch(s).then((c)=>{if(c.status===200||c.status===0){if(c.status===0)je("FileLoader: HTTP Status 0 received.");if(typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;let l=Fr[e],u=c.body.getReader(),d=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),f=d?parseInt(d):0,h=f!==0,b=0,m=new ReadableStream({start(g){p();function p(){u.read().then(({done:x,value:_})=>{if(x)g.close();else{b+=_.byteLength;let y=new ProgressEvent("progress",{lengthComputable:h,loaded:b,total:f});for(let v=0,T=l.length;v<T;v++){let A=l[v];if(A.onProgress)A.onProgress(y)}g.enqueue(_),p()}},(x)=>{g.error(x)})}}});return new Response(m)}else throw new qT(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then((c)=>{switch(o){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then((l)=>new DOMParser().parseFromString(l,a));case"json":return c.json();default:if(a==="")return c.text();else{let u=/charset="?([^;"\s]*)"?/i.exec(a),d=u&&u[1]?u[1].toLowerCase():void 0,f=new TextDecoder(d);return c.arrayBuffer().then((h)=>f.decode(h))}}}).then((c)=>{lr.add(`file:${e}`,c);let l=Fr[e];delete Fr[e];for(let u=0,d=l.length;u<d;u++){let f=l[u];if(f.onLoad)f.onLoad(c)}}).catch((c)=>{let l=Fr[e];if(l===void 0)throw this.manager.itemError(e),c;delete Fr[e];for(let u=0,d=l.length;u<d;u++){let f=l[u];if(f.onError)f.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}};bo=new WeakMap;jm=class jm extends jr{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=lr.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=bo.get(s);if(u===void 0)u=[],bo.set(s,u);u.push({onLoad:t,onError:i})}return s}let a=vo("img");function o(){if(l(),t)t(this);let u=bo.get(this)||[];for(let d=0;d<u.length;d++){let f=u[d];if(f.onLoad)f.onLoad(this)}bo.delete(this),r.manager.itemEnd(e)}function c(u){if(l(),i)i(u);lr.remove(`image:${e}`);let d=bo.get(this)||[];for(let f=0;f<d.length;f++){let h=d[f];if(h.onError)h.onError(u)}bo.delete(this),r.manager.itemError(e),r.manager.itemEnd(e)}function l(){a.removeEventListener("load",o,!1),a.removeEventListener("error",c,!1)}if(a.addEventListener("load",o,!1),a.addEventListener("error",c,!1),e.slice(0,5)!=="data:"){if(this.crossOrigin!==void 0)a.crossOrigin=this.crossOrigin}return lr.add(`image:${e}`,a),r.manager.itemStart(e),a.src=e,a}};Lo=class Lo extends jr{constructor(e){super(e)}load(e,t,n,i){let r=new en,s=new jm(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(a){if(r.image=a,r.needsUpdate=!0,t!==void 0)t(r)},n,i),r}};Fo=class Fo extends Dt{constructor(e,t=1){super();this.isLight=!0,this.type="Light",this.color=new qe(e),this.intensity=t}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}};Dd=class Dd extends Fo{constructor(e,t,n){super(e,n);this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Dt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new qe(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}};Mp=new Qe,HE=new j,GE=new j;sd=new j,ad=new ln,or=new j;Ld=class Ld extends Dt{constructor(){super();this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Qe,this.projectionMatrix=new Qe,this.projectionMatrixInverse=new Qe,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(sd,ad,or),or.x===1&&or.y===1&&or.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(sd,ad,or.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){if(super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(sd,ad,or),or.x===1&&or.y===1&&or.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(sd,ad,or.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}};os=new j,$E=new Ke,KE=new Ke;fn=class fn extends Ld{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=xa*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Hc*0.5*this.fov);return 0.5*this.getFilmHeight()/e}getEffectiveFOV(){return xa*2*Math.atan(Math.tan(Hc*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){os.set(-1,-1,0.5).applyMatrix4(this.projectionMatrixInverse),t.set(os.x,os.y).multiplyScalar(-e/os.z),os.set(1,1,0.5).applyMatrix4(this.projectionMatrixInverse),n.set(os.x,os.y).multiplyScalar(-e/os.z)}getViewSize(e,t){return this.getViewBounds(e,$E,KE),t.subVectors(KE,$E)}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(Hc*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:o,fullHeight:c}=s;r+=s.offsetX*i/o,t-=s.offsetY*n/c,i*=s.width/o,n*=s.height/c}let a=this.filmOffset;if(a!==0)r+=e*a/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}};JT=class JT extends dl{constructor(){super(new fn(50,1,0.5,500));this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=xa*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.aspect=e.aspect,this}toJSON(){let e=super.toJSON();return e.focus=this.focus,e.aspect=this.aspect,e}};Fd=class Fd extends Fo{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(Dt.DEFAULT_UP),this.updateMatrix(),this.target=new Dt,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new JT}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}};ZT=class ZT extends dl{constructor(){super(new fn(90,1,0.5,500));this.isPointLightShadow=!0}};Uo=class Uo extends Fo{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 ZT}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}};Ra=class Ra extends Ld{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,a=i+t,o=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,a-=l*this.view.offsetY,o=a-l*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,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}};YT=class YT extends dl{constructor(){super(new Ra(-5,5,5,-5,0.5,500));this.isDirectionalLightShadow=!0}};Bo=class Bo extends Fo{constructor(e,t){super(e,t);this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Dt.DEFAULT_UP),this.updateMatrix(),this.target=new Dt,this.shadow=new YT}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}};Rp=new WeakMap;Ud=class Ud extends jr{constructor(e){super(e);if(this.isImageBitmapLoader=!0,typeof createImageBitmap>"u")je("ImageBitmapLoader: createImageBitmap() not supported.");if(typeof fetch>"u")je("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=lr.get(`image-bitmap:${e}`);if(s!==void 0){if(r.manager.itemStart(e),s.then){s.then((c)=>{if(Rp.has(s)===!0){if(i)i(Rp.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 a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader,a.signal=typeof AbortSignal.any==="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let o=fetch(e,a).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign({},r.options,{colorSpaceConversion:"none"}))}).then(function(c){if(lr.add(`image-bitmap:${e}`,c),t)t(c);return r.manager.itemEnd(e),c}).catch(function(c){if(i)i(c);Rp.set(o,c),lr.remove(`image-bitmap:${e}`),r.manager.itemError(e),r.manager.itemEnd(e)});lr.add(`image-bitmap:${e}`,o),r.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}};Hm=class Hm extends Dt{constructor(e,t,n){super();this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new fn(xo,yo,e,t);i.layers=this.layers,this.add(i);let r=new fn(xo,yo,e,t);r.layers=this.layers,this.add(r);let s=new fn(xo,yo,e,t);s.layers=this.layers,this.add(s);let a=new fn(xo,yo,e,t);a.layers=this.layers,this.add(a);let o=new fn(xo,yo,e,t);o.layers=this.layers,this.add(o);let c=new fn(xo,yo,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,a,o]=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),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.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),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.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,a,o,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),h=e.xr.enabled;e.xr.enabled=!1;let b=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let m=!1;if(e.isWebGLRenderer===!0)m=e.state.buffers.depth.getReversed();else m=e.reversedDepthBuffer;if(e.setRenderTarget(n,0,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,r),e.setRenderTarget(n,1,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,s),e.setRenderTarget(n,2,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,a),e.setRenderTarget(n,3,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,o),e.setRenderTarget(n,4,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,c),n.texture.generateMipmaps=b,e.setRenderTarget(n,5,i),m&&e.autoClear===!1)e.clearDepth();e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=h,n.texture.needsPMREMUpdate=!0}};Gm=class Gm extends fn{constructor(e=[]){super();this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}};cP=new RegExp("["+Km+"]","g"),Wm="[^"+Km+"]",lP="[^"+Km.replace("\\.","")+"]",uP=/((?:WC+[\/:])*)/.source.replace("WC",Wm),dP=/(WCOD+)?/.source.replace("WCOD",lP),fP=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Wm),hP=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Wm),pP=new RegExp("^"+uP+dP+fP+hP+"$"),mP=["material","materials","bones","map"];Tt.Composite=QT;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]];gP=new Float32Array(1);Bd=class Bd extends Vi{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:a}=e,o=n.uuid,c=this._bindingsByRootAndName,l=c[o];if(l===void 0)l={},c[o]=l;for(let u=0;u!==r;++u){let d=i[u],f=d.name,h=l[f];if(h!==void 0)++h.referenceCount,s[u]=h;else{if(h=s[u],h!==void 0){if(h._cacheIndex===null)++h.referenceCount,this._addInactiveBinding(h,o,f);continue}let b=t&&t._propertyBindings[u].binding.parsedPath;h=new $m(Tt.create(n,f,b),d.ValueTypeName,d.getValueSize()),++h.referenceCount,this._addInactiveBinding(h,o,f),s[u]=h}a[u].resultBuffer=h.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 a=s.knownActions;e._byClipCacheIndex=a.length,a.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,a=s[r],o=a.knownActions,c=o[o.length-1],l=e._byClipCacheIndex;c._byClipCacheIndex=l,o[l]=c,o.pop(),e._byClipCacheIndex=null;let u=a.actionByRoot,d=(e._localRoot||this._root).uuid;if(delete u[d],o.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,a=s[i],o=t[t.length-1],c=e._cacheIndex;if(o._cacheIndex=c,t[c]=o,t.pop(),delete a[r],Object.keys(a).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 Od(new Float32Array(2),new Float32Array(2),1,gP),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"?To.findByName(i,e):e,a=s!==null?s.uuid:e,o=this._actionsByClip[a],c=null;if(n===void 0)if(s!==null)n=s.blendMode;else n=2500;if(o!==void 0){let u=o.actionByRoot[r];if(u!==void 0&&u.blendMode===n)return u;if(c=o.knownActions[0],s===null)s=c._clip}if(s===null)return null;let l=new Xm(this,s,t,n);return this._bindAction(l,c),this._addInactiveAction(l,a,r),l}existingAction(e,t){let n=t||this._root,i=n.uuid,r=typeof e==="string"?To.findByName(n,e):e,s=r?r.uuid:e,a=this._actionsByClip[s];if(a!==void 0)return a.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 a=this._bindings,o=this._nActiveBindings;for(let c=0;c!==o;++c)a[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 a=0,o=s.length;a!==o;++a){let c=s[a];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 a=n[s].actionByRoot,o=a[t];if(o!==void 0)this._deactivateAction(o),this._removeInactiveAction(o)}let i=this._bindingsByRootAndName,r=i[t];if(r!==void 0)for(let s in r){let a=r[s];a.restoreOriginalState(),this._removeInactiveBinding(a)}}uncacheAction(e,t){let n=this.existingAction(e,t);if(n!==null)this._deactivateAction(n),this._removeInactiveAction(n)}};qm=class qm{static{qm.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}};zd=class zd extends Vi{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(this.domElement!==null)this.disconnect();this.domElement=e}disconnect(){}dispose(){}update(){}};if(typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"186"}}));if(typeof window<"u")if(window.__THREE__)je("WARNING: Multiple instances of Three.js being imported.");else window.__THREE__="186"});function vA(){let e=null,t=!1,n=null,i=null;function r(s,a){i=e.requestAnimationFrame(r),n(s,a)}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 xP(e){let t=new WeakMap;function n(o,c){let{array:l,usage:u}=o,d=l.byteLength,f=e.createBuffer();e.bindBuffer(c,f),e.bufferData(c,l,u),o.onUploadCallback();let h;if(l instanceof Float32Array)h=e.FLOAT;else if(typeof Float16Array<"u"&&l instanceof Float16Array)h=e.HALF_FLOAT;else if(l instanceof Uint16Array)if(o.isFloat16BufferAttribute)h=e.HALF_FLOAT;else h=e.UNSIGNED_SHORT;else if(l instanceof Int16Array)h=e.SHORT;else if(l instanceof Uint32Array)h=e.UNSIGNED_INT;else if(l instanceof Int32Array)h=e.INT;else if(l instanceof Int8Array)h=e.BYTE;else if(l instanceof Uint8Array)h=e.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)h=e.UNSIGNED_BYTE;else throw Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:f,type:h,bytesPerElement:l.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,c,l){let{array:u,updateRanges:d}=c;if(e.bindBuffer(l,o),d.length===0)e.bufferSubData(l,0,u);else{d.sort((h,b)=>h.start-b.start);let f=0;for(let h=1;h<d.length;h++){let b=d[f],m=d[h];if(m.start<=b.start+b.count+1)b.count=Math.max(b.count,m.start+m.count-b.start);else++f,d[f]=m}d.length=f+1;for(let h=0,b=d.length;h<b;h++){let m=d[h];e.bufferSubData(l,m.start*u.BYTES_PER_ELEMENT,u,m.start,m.count)}c.clearUpdateRanges()}c.onUploadCallback()}function r(o){if(o.isInterleavedBufferAttribute)o=o.data;return t.get(o)}function s(o){if(o.isInterleavedBufferAttribute)o=o.data;let c=t.get(o);if(c)e.deleteBuffer(c.buffer),t.delete(o)}function a(o,c){if(o.isInterleavedBufferAttribute)o=o.data;if(o.isGLBufferAttribute){let u=t.get(o);if(!u||u.version<o.version)t.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}let l=t.get(o);if(l===void 0)t.set(o,n(o,c));else if(l.version<o.version){if(l.size!==o.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,o,c),l.version=o.version}}return{get:r,remove:s,update:a}}function eD(e,t,n,i,r,s){let a=new qe(0),o=r===!0?0:1,c,l,u=null,d=0,f=null;function h(x){let _=x.isScene===!0?x.background:null;if(_&&_.isTexture){let y=x.backgroundBlurriness>0;_=t.get(_,y)}return _}function b(x){let _=!1,y=h(x);if(y===null)g(a,o);else if(y&&y.isColor)g(y,1),_=!0;let v=e.xr.getEnvironmentBlendMode();if(v==="additive")n.buffers.color.setClear(0,0,0,1,s);else if(v==="alpha-blend")n.buffers.color.setClear(0,0,0,0,s);if(e.autoClear||_)n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil)}function m(x,_){let y=h(_);if(y&&(y.isCubeTexture||y.mapping===qc)){if(l===void 0)l=new jt(new bs(1,1,1),new Ei({name:"BackgroundCubeMaterial",uniforms:Sa(br.backgroundCube.uniforms),vertexShader:br.backgroundCube.vertexShader,fragmentShader:br.backgroundCube.fragmentShader,side:kn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(v,T,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(l);if(l.material.uniforms.envMap.value=y,l.material.uniforms.backgroundBlurriness.value=_.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(Qk.makeRotationFromEuler(_.backgroundRotation)).transpose(),y.isCubeTexture&&y.isRenderTargetTexture===!1)l.material.uniforms.backgroundRotation.value.premultiply(EA);if(l.material.toneMapped=ot.getTransfer(y.colorSpace)!==Bt,u!==y||d!==y.version||f!==e.toneMapping)l.material.needsUpdate=!0,u=y,d=y.version,f=e.toneMapping;l.layers.enableAll(),x.unshift(l,l.geometry,l.material,0,0,null)}else if(y&&y.isTexture){if(c===void 0)c=new jt(new cl(2,2),new Ei({name:"BackgroundMaterial",uniforms:Sa(br.background.uniforms),vertexShader:br.background.vertexShader,fragmentShader:br.background.fragmentShader,side:fs,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=y,c.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,c.material.toneMapped=ot.getTransfer(y.colorSpace)!==Bt,y.matrixAutoUpdate===!0)y.updateMatrix();if(c.material.uniforms.uvTransform.value.copy(y.matrix),u!==y||d!==y.version||f!==e.toneMapping)c.material.needsUpdate=!0,u=y,d=y.version,f=e.toneMapping;c.layers.enableAll(),x.unshift(c,c.geometry,c.material,0,0,null)}}function g(x,_){x.getRGB(Vd,km(e)),n.buffers.color.setClear(Vd.r,Vd.g,Vd.b,_,s)}function p(){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 a},setClearColor:function(x,_=1){a.set(x),o=_,g(a,o)},getClearAlpha:function(){return o},setClearAlpha:function(x){o=x,g(a,o)},render:b,addToRenderList:m,dispose:p}}function tD(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=f(null),s=r,a=!1;function o(S,I,U,N,F){let D=!1,O=d(S,N,U,I);if(s!==O)s=O,l(s.object);if(D=h(S,N,U,F),D)b(S,N,U,F);if(F!==null)t.update(F,e.ELEMENT_ARRAY_BUFFER);if(D||a){if(a=!1,y(S,I,U,N),F!==null)e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(F).buffer)}}function c(){return e.createVertexArray()}function l(S){return e.bindVertexArray(S)}function u(S){return e.deleteVertexArray(S)}function d(S,I,U,N){let F=N.wireframe===!0,D=i[I.id];if(D===void 0)D={},i[I.id]=D;let O=S.isInstancedMesh===!0?S.id:0,K=D[O];if(K===void 0)K={},D[O]=K;let B=K[U.id];if(B===void 0)B={},K[U.id]=B;let X=B[F];if(X===void 0)X=f(c()),B[F]=X;return X}function f(S){let I=[],U=[],N=[];for(let F=0;F<n;F++)I[F]=0,U[F]=0,N[F]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:I,enabledAttributes:U,attributeDivisors:N,object:S,attributes:{},index:null}}function h(S,I,U,N){let F=s.attributes,D=I.attributes,O=0,K=U.getAttributes();for(let B in K)if(K[B].location>=0){let q=F[B],le=D[B];if(le===void 0){if(B==="instanceMatrix"&&S.instanceMatrix)le=S.instanceMatrix;if(B==="instanceColor"&&S.instanceColor)le=S.instanceColor}if(q===void 0)return!0;if(q.attribute!==le)return!0;if(le&&q.data!==le.data)return!0;O++}if(s.attributesNum!==O)return!0;if(s.index!==N)return!0;return!1}function b(S,I,U,N){let F={},D=I.attributes,O=0,K=U.getAttributes();for(let B in K)if(K[B].location>=0){let q=D[B];if(q===void 0){if(B==="instanceMatrix"&&S.instanceMatrix)q=S.instanceMatrix;if(B==="instanceColor"&&S.instanceColor)q=S.instanceColor}let le={};if(le.attribute=q,q&&q.data)le.data=q.data;F[B]=le,O++}s.attributes=F,s.attributesNum=O,s.index=N}function m(){let S=s.newAttributes;for(let I=0,U=S.length;I<U;I++)S[I]=0}function g(S){p(S,0)}function p(S,I){let U=s.newAttributes,N=s.enabledAttributes,F=s.attributeDivisors;if(U[S]=1,N[S]===0)e.enableVertexAttribArray(S),N[S]=1;if(F[S]!==I)e.vertexAttribDivisor(S,I),F[S]=I}function x(){let S=s.newAttributes,I=s.enabledAttributes;for(let U=0,N=I.length;U<N;U++)if(I[U]!==S[U])e.disableVertexAttribArray(U),I[U]=0}function _(S,I,U,N,F,D,O){if(O===!0)e.vertexAttribIPointer(S,I,U,F,D);else e.vertexAttribPointer(S,I,U,N,F,D)}function y(S,I,U,N){m();let F=N.attributes,D=U.getAttributes(),O=I.defaultAttributeValues;for(let K in D){let B=D[K];if(B.location>=0){let X=F[K];if(X===void 0){if(K==="instanceMatrix"&&S.instanceMatrix)X=S.instanceMatrix;if(K==="instanceColor"&&S.instanceColor)X=S.instanceColor}if(X!==void 0){let q=X.normalized,le=X.itemSize,de=t.get(X);if(de===void 0)continue;let{buffer:Me,type:pe,bytesPerElement:J}=de,L=pe===e.INT||pe===e.UNSIGNED_INT||X.gpuType===Vp;if(X.isInterleavedBufferAttribute){let W=X.data,ne=W.stride,ie=X.offset;if(W.isInstancedInterleavedBuffer){for(let ce=0;ce<B.locationSize;ce++)p(B.location+ce,W.meshPerAttribute);if(S.isInstancedMesh!==!0&&N._maxInstanceCount===void 0)N._maxInstanceCount=W.meshPerAttribute*W.count}else for(let ce=0;ce<B.locationSize;ce++)g(B.location+ce);e.bindBuffer(e.ARRAY_BUFFER,Me);for(let ce=0;ce<B.locationSize;ce++)_(B.location+ce,le/B.locationSize,pe,q,ne*J,(ie+le/B.locationSize*ce)*J,L)}else{if(X.isInstancedBufferAttribute){for(let W=0;W<B.locationSize;W++)p(B.location+W,X.meshPerAttribute);if(S.isInstancedMesh!==!0&&N._maxInstanceCount===void 0)N._maxInstanceCount=X.meshPerAttribute*X.count}else for(let W=0;W<B.locationSize;W++)g(B.location+W);e.bindBuffer(e.ARRAY_BUFFER,Me);for(let W=0;W<B.locationSize;W++)_(B.location+W,le/B.locationSize,pe,q,le*J,le/B.locationSize*W*J,L)}}else if(O!==void 0){let q=O[K];if(q!==void 0)switch(q.length){case 2:e.vertexAttrib2fv(B.location,q);break;case 3:e.vertexAttrib3fv(B.location,q);break;case 4:e.vertexAttrib4fv(B.location,q);break;default:e.vertexAttrib1fv(B.location,q)}}}}x()}function v(){w();for(let S in i){let I=i[S];for(let U in I){let N=I[U];for(let F in N){let D=N[F];for(let O in D)u(D[O].object),delete D[O];delete N[F]}}delete i[S]}}function T(S){if(i[S.id]===void 0)return;let I=i[S.id];for(let U in I){let N=I[U];for(let F in N){let D=N[F];for(let O in D)u(D[O].object),delete D[O];delete N[F]}}delete i[S.id]}function A(S){for(let I in i){let U=i[I];for(let N in U){let F=U[N];if(F[S.id]===void 0)continue;let D=F[S.id];for(let O in D)u(D[O].object),delete D[O];delete F[S.id]}}}function E(S){for(let I in i){let U=i[I],N=S.isInstancedMesh===!0?S.id:0,F=U[N];if(F===void 0)continue;for(let D in F){let O=F[D];for(let K in O)u(O[K].object),delete O[K];delete F[D]}if(delete U[N],Object.keys(U).length===0)delete i[I]}}function w(){if(P(),a=!0,s===r)return;s=r,l(s.object)}function P(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:o,reset:w,resetDefaultState:P,dispose:v,releaseStatesOfGeometry:T,releaseStatesOfObject:E,releaseStatesOfProgram:A,initAttributes:m,enableAttribute:g,disableUnusedAttributes:x}}function nD(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 a(c,l,u){if(u===0)return;e.drawArraysInstanced(i,c,l,u),n.update(l,i,u)}function o(c,l,u){if(u===0)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,c,0,l,0,u);let f=0;for(let h=0;h<u;h++)f+=l[h];n.update(f,i,1)}this.setMode=r,this.render=s,this.renderInstances=a,this.renderMultiDraw=o}function iD(e,t,n,i){let r;function s(){if(r!==void 0)return r;if(t.has("EXT_texture_filter_anisotropic")===!0){let A=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}function a(A){if(A!==pr&&i.convert(A)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))return!1;return!0}function o(A){let E=A===hr&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));if(A!==zi&&A!==Br&&!E&&i.convert(A)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))return!1;return!0}function c(A){if(A==="highp"){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";A="mediump"}if(A==="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)je("WebGLRenderer:",l,"not supported, using",u,"instead."),l=u;let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has("EXT_clip_control");if(n.reversedDepthBuffer===!0&&f===!1)je("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let h=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),b=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),p=e.getParameter(e.MAX_VERTEX_ATTRIBS),x=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),_=e.getParameter(e.MAX_VARYING_VECTORS),y=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),v=e.getParameter(e.MAX_SAMPLES),T=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:a,textureTypeReadable:o,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:h,maxVertexTextures:b,maxTextureSize:m,maxCubemapSize:g,maxAttributes:p,maxVertexUniforms:x,maxVaryings:_,maxFragmentUniforms:y,maxSamples:v,samples:T}}function rD(e){let t=this,n=null,i=0,r=!1,s=!1,a=new yi,o=new tt,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(d,f){let h=d.length!==0||f||i!==0||r;return r=f,i=d.length,h},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(d,f){n=u(d,f,0)},this.setState=function(d,f,h){let{clippingPlanes:b,clipIntersection:m,clipShadows:g}=d,p=e.get(d);if(!r||b===null||b.length===0||s&&!g)if(s)u(null);else l();else{let x=s?0:i,_=x*4,y=p.clippingState||null;c.value=y,y=u(b,f,_,h);for(let v=0;v!==_;++v)y[v]=n[v];p.clippingState=y,this.numIntersection=m?this.numPlanes:0,this.numPlanes+=x}};function l(){if(c.value!==n)c.value=n,c.needsUpdate=i>0;t.numPlanes=i,t.numIntersection=0}function u(d,f,h,b){let m=d!==null?d.length:0,g=null;if(m!==0){if(g=c.value,b!==!0||g===null){let p=h+m*4,x=f.matrixWorldInverse;if(o.getNormalMatrix(x),g===null||g.length<p)g=new Float32Array(p);for(let _=0,y=h;_!==m;++_,y+=4)a.copy(d[_]).applyMatrix4(x,o),a.normal.toArray(g,y),g[y+3]=a.constant}c.value=g,c.needsUpdate=!0}return t.numPlanes=m,t.numIntersection=0,g}}class bl{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=0.1,i=100,r={}){let{size:s=256,position:a=cD}=r;Ym=this._renderer.getRenderTarget(),Qm=this._renderer.getActiveCubeFace(),eg=this._renderer.getActiveMipmapLevel(),tg=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);let o=this._allocateTargets();if(o.depthBuffer=!0,this._sceneToCubeUV(e,n,i,o,a),t>0)this._blur(o,0,0,t);return this._applyPMREM(o),this._cleanup(o),o}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=iA(),this._compileMaterial(this._cubemapMaterial)}compileEquirectangularShader(){if(this._equirectMaterial===null)this._equirectMaterial=nA(),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(Ym,Qm,eg),this._renderer.xr.enabled=tg,e.scissorTest=!1,zo(e,0,0,e.width,e.height)}_fromTexture(e,t){if(e.mapping===So||e.mapping===ya)this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width);else this._setSize(e.image.width/4);Ym=this._renderer.getRenderTarget(),Qm=this._renderer.getActiveCubeFace(),eg=this._renderer.getActiveMipmapLevel(),tg=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:En,minFilter:En,generateMipmaps:!1,type:hr,format:pr,colorSpace:oi,depthBuffer:!1},i=tA(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){if(this._pingPongRenderTarget!==null)this._dispose();this._pingPongRenderTarget=tA(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=lD(r)),this._blurMaterial=dD(r,e,t),this._ggxMaterial=uD(r,e,t)}return i}_compileMaterial(e){let t=new jt(new Dn,e);this._renderer.compile(t,hl)}_sceneToCubeUV(e,t,n,i,r){let o=new fn(90,1,t,n),c=[1,-1,1,1,1,1],l=[1,1,1,-1,-1,-1],u=this._renderer,{autoClear:d,toneMapping:f}=u;if(u.getClearColor(eA),u.toneMapping=Ui,u.autoClear=!1,u.state.buffers.depth.getReversed())u.setRenderTarget(i),u.clearDepth(),u.setRenderTarget(null);if(this._backgroundBox===null)this._backgroundBox=new jt(new bs,new mr({name:"PMREM.Background",side:kn,depthWrite:!1,depthTest:!1}));let b=this._backgroundBox,m=b.material,g=!1,p=e.background;if(p){if(p.isColor)m.color.copy(p),e.background=null,g=!0}else m.color.copy(eA),g=!0;for(let x=0;x<6;x++){let _=x%3;if(_===0)o.up.set(0,c[x],0),o.position.set(r.x,r.y,r.z),o.lookAt(r.x+l[x],r.y,r.z);else if(_===1)o.up.set(0,0,c[x]),o.position.set(r.x,r.y,r.z),o.lookAt(r.x,r.y+l[x],r.z);else o.up.set(0,c[x],0),o.position.set(r.x,r.y,r.z),o.lookAt(r.x,r.y,r.z+l[x]);let y=this._cubeSize;if(zo(i,_*y,x>2?y:0,y,y),u.setRenderTarget(i),g)u.render(b,o);u.render(e,o)}u.toneMapping=f,u.autoClear=d,e.background=p}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===So||e.mapping===ya;if(i){if(this._cubemapMaterial===null)this._cubemapMaterial=iA();this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1}else if(this._equirectMaterial===null)this._equirectMaterial=nA();let r=i?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=r;let a=r.uniforms;a.envMap.value=e;let o=this._cubeSize;zo(t,0,0,3*o,2*o),n.setRenderTarget(t),n.render(s,hl)}_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,a=this._lodMeshes[n];a.material=s;let o=s.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l),d=c*1.25,f=u*d,{_lodMax:h}=this,b=this._sizeLods[n],m=3*b*(n>h-Vo?n-h+Vo:0),g=4*(this._cubeSize-b);o.envMap.value=e.texture,o.roughness.value=f,o.mipInt.value=h-t,zo(r,m,g,3*b,2*b),i.setRenderTarget(r),i.render(a,hl),o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=h-n,zo(e,m,g,3*b,2*b),i.setRenderTarget(e),i.render(a,hl)}_blur(e,t,n,i){let r=this._pingPongRenderTarget,s=Math.min(i,Math.PI)/Math.SQRT2;this._blurPass(e,r,t,n,s),this._blurPass(r,e,n,n,s)}_blurPass(e,t,n,i,r){let s=this._renderer,a=this._blurMaterial,o=this._lodMeshes[i];o.material=a;let c=a.uniforms;c.envMap.value=e.texture,c.sigma.value=r,c.mipInt.value=this._lodMax-n;let l=this._sizeLods[i],u=3*l*(i>this._lodMax-Vo?i-this._lodMax+Vo:0),d=4*(this._cubeSize-l);zo(t,u,d,3*l,2*l),s.setRenderTarget(t),s.render(o,hl)}}function lD(e){let t=[],n=[],i=e,r=e-Vo+1+sD;for(let s=0;s<r;s++){let a=Math.pow(2,i);t.push(a);let o=1/(a-2),c=-o,l=1+o,u=[c,c,l,c,l,l,c,c,l,l,c,l],d=6,f=6,h=3,b=new Float32Array(h*f*d),m=new Float32Array(h*f*d);for(let p=0;p<d;p++){let x=p%3*2/3-1,_=p>2?0:-1,y=[x,_,0,x+0.6666666666666666,_,0,x+0.6666666666666666,_+1,0,x,_,0,x+0.6666666666666666,_+1,0,x,_+1,0];b.set(y,h*f*p);for(let v=0;v<f;v++){let T=u[v*2]*2-1,A=u[v*2+1]*2-1;if(p===0)Ia.set(1,A,T);else if(p===1)Ia.set(-T,1,-A);else if(p===2)Ia.set(-T,A,1);else if(p===3)Ia.set(-1,A,-T);else if(p===4)Ia.set(-T,-1,A);else Ia.set(T,A,-1);Ia.toArray(m,(p*f+v)*h)}}let g=new Dn;if(g.setAttribute("position",new vn(b,h)),g.setAttribute("outputDirection",new vn(m,h)),n.push(new jt(g,null)),i>Vo)i--}return{lodMeshes:n,sizeLods:t}}function tA(e,t,n){let i=new ci(e,t,n);return i.texture.mapping=qc,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function zo(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function uD(e,t,n){return new Ei({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:oD,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:Hd(),fragmentShader:`+}`,Ei,zm,zr,di,Dd,Vm,jm,Hm,Ld,Gm,$m,xs,Fd,ys,Km,_s,vs,Ia,lr,YT,Fr,QT,fl,bo,Wm,Lo,Fo,Ud,Pp,WE,XE,cd,ld,or,Bd,os,qE,JE,hn,eA,zd,tA,Uo,Ca,nA,Bo,Op,Vd,xo=-90,yo=1,Xm,qm,Zm="\\[\\]\\.:\\/",hP,Ym,pP,mP,gP,bP,xP,yP,_P,vP,jd,eg,Hd;var ng=ht(()=>{us={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},ds={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3};pE={};XT={[0]:1,[2]:6,[4]:7,[3]:5,[1]:0,[6]:2,[7]:4,[5]:3};On=["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"],$c=Math.PI/180,_a=180/Math.PI;el={DEG2RAD:$c,RAD2DEG:_a,generateUUID:Fi,clamp:ct,euclideanModulo:km,mapLinear:vN,inverseLerp:EN,lerp:Kc,damp:TN,pingpong:AN,smoothstep:wN,smootherstep:SN,randInt:MN,randFloat:RN,randFloatSpread:IN,seededRandom:CN,degToRad:NN,radToDeg:PN,isPowerOfTwo:ON,ceilPowerOfTwo:kN,floorPowerOfTwo:DN,setQuaternionFromProperEuler:LN,normalize:Nt,denormalize:Li};Ke=class Ke{static{Ke.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=ct(this.x,e.x,t.x),this.y=ct(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=ct(this.x,e,t),this.y=ct(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ct(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(ct(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}};ln=class ln{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,a){let o=n[i+0],c=n[i+1],l=n[i+2],u=n[i+3],d=r[s+0],f=r[s+1],h=r[s+2],b=r[s+3];if(u!==b||o!==d||c!==f||l!==h){let m=o*d+c*f+l*h+u*b;if(m<0)d=-d,f=-f,h=-h,b=-b,m=-m;let g=1-a;if(m<0.9995){let p=Math.acos(m),x=Math.sin(p);g=Math.sin(g*p)/x,a=Math.sin(a*p)/x,o=o*g+d*a,c=c*g+f*a,l=l*g+h*a,u=u*g+b*a}else{o=o*g+d*a,c=c*g+f*a,l=l*g+h*a,u=u*g+b*a;let p=1/Math.sqrt(o*o+c*c+l*l+u*u);o*=p,c*=p,l*=p,u*=p}}e[t]=o,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,s){let a=n[i],o=n[i+1],c=n[i+2],l=n[i+3],u=r[s],d=r[s+1],f=r[s+2],h=r[s+3];return e[t]=a*h+l*u+o*f-c*d,e[t+1]=o*h+l*d+c*u-a*f,e[t+2]=c*h+l*f+a*d-o*u,e[t+3]=l*h-a*u-o*d-c*f,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:a,sin:o}=Math,c=a(n/2),l=a(i/2),u=a(r/2),d=o(n/2),f=o(i/2),h=o(r/2);switch(s){case"XYZ":this._x=d*l*u+c*f*h,this._y=c*f*u-d*l*h,this._z=c*l*h+d*f*u,this._w=c*l*u-d*f*h;break;case"YXZ":this._x=d*l*u+c*f*h,this._y=c*f*u-d*l*h,this._z=c*l*h-d*f*u,this._w=c*l*u+d*f*h;break;case"ZXY":this._x=d*l*u-c*f*h,this._y=c*f*u+d*l*h,this._z=c*l*h+d*f*u,this._w=c*l*u-d*f*h;break;case"ZYX":this._x=d*l*u-c*f*h,this._y=c*f*u+d*l*h,this._z=c*l*h-d*f*u,this._w=c*l*u+d*f*h;break;case"YZX":this._x=d*l*u+c*f*h,this._y=c*f*u+d*l*h,this._z=c*l*h-d*f*u,this._w=c*l*u-d*f*h;break;case"XZY":this._x=d*l*u-c*f*h,this._y=c*f*u-d*l*h,this._z=c*l*h+d*f*u,this._w=c*l*u+d*f*h;break;default:je("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],a=t[5],o=t[9],c=t[2],l=t[6],u=t[10],d=n+a+u;if(d>0){let f=0.5/Math.sqrt(d+1);this._w=0.25/f,this._x=(l-o)*f,this._y=(r-c)*f,this._z=(s-i)*f}else if(n>a&&n>u){let f=2*Math.sqrt(1+n-a-u);this._w=(l-o)/f,this._x=0.25*f,this._y=(i+s)/f,this._z=(r+c)/f}else if(a>u){let f=2*Math.sqrt(1+a-n-u);this._w=(r-c)/f,this._x=(i+s)/f,this._y=0.25*f,this._z=(o+l)/f}else{let f=2*Math.sqrt(1+u-n-a);this._w=(s-i)/f,this._x=(r+c)/f,this._y=(o+l)/f,this._z=0.25*f}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(ct(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:a,_y:o,_z:c,_w:l}=t;return this._x=n*l+s*a+i*c-r*o,this._y=i*l+s*o+r*a-n*c,this._z=r*l+s*c+n*o-i*a,this._w=s*l-n*a-i*o-r*c,this._onChangeCallback(),this}slerp(e,t){let{_x:n,_y:i,_z:r,_w:s}=e,a=this.dot(e);if(a<0)n=-n,i=-i,r=-r,s=-s,a=-a;let o=1-t;if(a<0.9995){let c=Math.acos(a),l=Math.sin(c);o=Math.sin(o*c)/l,t=Math.sin(t*c)/l,this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this._onChangeCallback()}else this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+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}};j=class j{static{j.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(gE.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(gE.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:a,w:o}=e,c=2*(s*i-a*n),l=2*(a*t-r*i),u=2*(r*n-s*t);return this.x=t+o*c+s*u-a*l,this.y=n+o*l+a*c-r*u,this.z=i+o*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=ct(this.x,e.x,t.x),this.y=ct(this.y,e.y,t.y),this.z=ct(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=ct(this.x,e,t),this.y=ct(this.y,e,t),this.z=ct(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ct(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:a,z:o}=t;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-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 up.copy(this).projectOnVector(e),this.sub(up)}reflect(e){return this.sub(up.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(ct(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}};up=new j,gE=new ln;tt=class tt{static{tt.prototype.isMatrix3=!0}constructor(e,t,n,i,r,s,a,o,c){if(this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0)this.set(e,t,n,i,r,s,a,o,c)}set(e,t,n,i,r,s,a,o,c){let l=this.elements;return l[0]=e,l[1]=i,l[2]=a,l[3]=t,l[4]=r,l[5]=o,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],a=n[3],o=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],h=n[8],b=i[0],m=i[3],g=i[6],p=i[1],x=i[4],_=i[7],y=i[2],v=i[5],E=i[8];return r[0]=s*b+a*p+o*y,r[3]=s*m+a*x+o*v,r[6]=s*g+a*_+o*E,r[1]=c*b+l*p+u*y,r[4]=c*m+l*x+u*v,r[7]=c*g+l*_+u*E,r[2]=d*b+f*p+h*y,r[5]=d*m+f*x+h*v,r[8]=d*g+f*_+h*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],a=e[5],o=e[6],c=e[7],l=e[8];return t*s*l-t*a*c-n*r*l+n*a*o+i*r*c-i*s*o}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],c=e[7],l=e[8],u=l*s-a*c,d=a*o-l*r,f=c*r-s*o,h=t*u+n*d+i*f;if(h===0)return this.set(0,0,0,0,0,0,0,0,0);let b=1/h;return e[0]=u*b,e[1]=(i*c-l*n)*b,e[2]=(a*n-i*s)*b,e[3]=d*b,e[4]=(l*t-i*o)*b,e[5]=(i*r-a*t)*b,e[6]=f*b,e[7]=(n*o-c*t)*b,e[8]=(s*t-n*r)*b,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,a){let o=Math.cos(r),c=Math.sin(r);return this.set(n*o,n*c,-n*(o*s+c*a)+s+e,-i*c,i*o,-i*(-c*s+o*a)+a+t,0,0,1),this}scale(e,t){return ya("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(dp.makeScale(e,t)),this}rotate(e){return ya("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(dp.makeRotation(-e)),this}translate(e,t){return ya("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(dp.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)}};dp=new tt,bE=new tt().set(0.4123908,0.3575843,0.1804808,0.212639,0.7151687,0.0721923,0.0193308,0.1191948,0.9505322),xE=new tt().set(3.2409699,-1.5373832,-0.4986108,-0.9692436,1.8759675,0.0415551,0.0556301,-0.203977,1.0569715);ot=FN();hp=new j;en=class en extends Vi{constructor(e=en.DEFAULT_IMAGE,t=en.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,a=1023,o=1009,c=en.DEFAULT_ANISOTROPY,l=""){super();this.isTexture=!0,Object.defineProperty(this,"id",{value:BN++}),this.uuid=Fi(),this.name="",this.source=new tl(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=a,this.internalFormat=null,this.type=o,this.offset=new Ke(0,0),this.repeat=new Ke(1,1),this.center=new Ke(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new tt,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(hp).x}get height(){return this.source.getSize(hp).y}get depth(){return this.source.getSize(hp).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){je(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){je(`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++}};en.DEFAULT_IMAGE=null;en.DEFAULT_MAPPING=300;en.DEFAULT_ANISOTROPY=1;Pt=class Pt{static{Pt.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,a=0.1,o=e.elements,c=o[0],l=o[4],u=o[8],d=o[1],f=o[5],h=o[9],b=o[2],m=o[6],g=o[10];if(Math.abs(l-d)<0.01&&Math.abs(u-b)<0.01&&Math.abs(h-m)<0.01){if(Math.abs(l+d)<0.1&&Math.abs(u+b)<0.1&&Math.abs(h+m)<0.1&&Math.abs(c+f+g-3)<0.1)return this.set(1,0,0,0),this;t=Math.PI;let x=(c+1)/2,_=(f+1)/2,y=(g+1)/2,v=(l+d)/4,E=(u+b)/4,w=(h+m)/4;if(x>_&&x>y)if(x<0.01)n=0,i=0.707106781,r=0.707106781;else n=Math.sqrt(x),i=v/n,r=E/n;else if(_>y)if(_<0.01)n=0.707106781,i=0,r=0.707106781;else i=Math.sqrt(_),n=v/i,r=w/i;else if(y<0.01)n=0.707106781,i=0.707106781,r=0;else r=Math.sqrt(y),n=E/r,i=w/r;return this.set(n,i,r,t),this}let p=Math.sqrt((m-h)*(m-h)+(u-b)*(u-b)+(d-l)*(d-l));if(Math.abs(p)<0.001)p=1;return this.x=(m-h)/p,this.y=(u-b)/p,this.z=(d-l)/p,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=ct(this.x,e.x,t.x),this.y=ct(this.y,e.y,t.y),this.z=ct(this.z,e.z,t.z),this.w=ct(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=ct(this.x,e,t),this.y=ct(this.y,e,t),this.z=ct(this.z,e,t),this.w=ct(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(ct(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}};Lm=class Lm extends Vi{constructor(e=1,t=1,n={}){super();n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Pt(0,0,e,t),this.scissorTest=!1,this.viewport=new Pt(0,0,e,t),this.textures=[];let i={width:e,height:t,depth:n.depth},r=new en(i),s=n.count;for(let a=0;a<s;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(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===this)this._depthTexture.renderTarget=null;if(e!==null&&e.renderTarget===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 tl(i)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null)if(e.depthTexture.renderTarget===e){let t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture;return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}};li=class li extends Lm{constructor(e=1,t=1,n={}){super(e,t,n);this.isWebGLRenderTarget=!0}};Sd=class Sd extends en{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}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}};Fm=class Fm extends en{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}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}};Je=class Je{static{Je.prototype.isMatrix4=!0}constructor(e,t,n,i,r,s,a,o,c,l,u,d,f,h,b,m){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,a,o,c,l,u,d,f,h,b,m)}set(e,t,n,i,r,s,a,o,c,l,u,d,f,h,b,m){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=h,g[11]=b,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Je().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/ao.setFromMatrixColumn(e,0).length(),r=1/ao.setFromMatrixColumn(e,1).length(),s=1/ao.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),a=Math.sin(n),o=Math.cos(i),c=Math.sin(i),l=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){let d=s*l,f=s*u,h=a*l,b=a*u;t[0]=o*l,t[4]=-o*u,t[8]=c,t[1]=f+h*c,t[5]=d-b*c,t[9]=-a*o,t[2]=b-d*c,t[6]=h+f*c,t[10]=s*o}else if(e.order==="YXZ"){let d=o*l,f=o*u,h=c*l,b=c*u;t[0]=d+b*a,t[4]=h*a-f,t[8]=s*c,t[1]=s*u,t[5]=s*l,t[9]=-a,t[2]=f*a-h,t[6]=b+d*a,t[10]=s*o}else if(e.order==="ZXY"){let d=o*l,f=o*u,h=c*l,b=c*u;t[0]=d-b*a,t[4]=-s*u,t[8]=h+f*a,t[1]=f+h*a,t[5]=s*l,t[9]=b-d*a,t[2]=-s*c,t[6]=a,t[10]=s*o}else if(e.order==="ZYX"){let d=s*l,f=s*u,h=a*l,b=a*u;t[0]=o*l,t[4]=h*c-f,t[8]=d*c+b,t[1]=o*u,t[5]=b*c+d,t[9]=f*c-h,t[2]=-c,t[6]=a*o,t[10]=s*o}else if(e.order==="YZX"){let d=s*o,f=s*c,h=a*o,b=a*c;t[0]=o*l,t[4]=b-d*u,t[8]=h*u+f,t[1]=u,t[5]=s*l,t[9]=-a*l,t[2]=-c*l,t[6]=f*u+h,t[10]=d-b*u}else if(e.order==="XZY"){let d=s*o,f=s*c,h=a*o,b=a*c;t[0]=o*l,t[4]=-u,t[8]=c*l,t[1]=d*u+b,t[5]=s*l,t[9]=f*u-h,t[2]=h*u-f,t[6]=a*l,t[10]=b*u+d}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(zN,e,VN)}lookAt(e,t,n){let i=this.elements;if(ai.subVectors(e,t),ai.lengthSq()===0)ai.z=1;if(ai.normalize(),is.crossVectors(n,ai),is.lengthSq()===0){if(Math.abs(n.z)===1)ai.x+=0.0001;else ai.z+=0.0001;ai.normalize(),is.crossVectors(n,ai)}return is.normalize(),Bu.crossVectors(ai,is),i[0]=is.x,i[4]=Bu.x,i[8]=ai.x,i[1]=is.y,i[5]=Bu.y,i[9]=ai.y,i[2]=is.z,i[6]=Bu.z,i[10]=ai.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],a=n[4],o=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],h=n[2],b=n[6],m=n[10],g=n[14],p=n[3],x=n[7],_=n[11],y=n[15],v=i[0],E=i[4],w=i[8],T=i[12],A=i[1],P=i[5],S=i[9],R=i[13],k=i[2],C=i[6],U=i[10],L=i[14],O=i[3],K=i[7],B=i[11],X=i[15];return r[0]=s*v+a*A+o*k+c*O,r[4]=s*E+a*P+o*C+c*K,r[8]=s*w+a*S+o*U+c*B,r[12]=s*T+a*R+o*L+c*X,r[1]=l*v+u*A+d*k+f*O,r[5]=l*E+u*P+d*C+f*K,r[9]=l*w+u*S+d*U+f*B,r[13]=l*T+u*R+d*L+f*X,r[2]=h*v+b*A+m*k+g*O,r[6]=h*E+b*P+m*C+g*K,r[10]=h*w+b*S+m*U+g*B,r[14]=h*T+b*R+m*L+g*X,r[3]=p*v+x*A+_*k+y*O,r[7]=p*E+x*P+_*C+y*K,r[11]=p*w+x*S+_*U+y*B,r[15]=p*T+x*R+_*L+y*X,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],a=e[5],o=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],h=e[3],b=e[7],m=e[11],g=e[15],p=o*f-c*d,x=a*f-c*u,_=a*d-o*u,y=s*f-c*l,v=s*d-o*l,E=s*u-a*l;return t*(b*p-m*x+g*_)-n*(h*p-m*y+g*v)+i*(h*x-b*y+g*E)-r*(h*_-b*v+m*E)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],i=e[8],r=e[1],s=e[5],a=e[9],o=e[2],c=e[6],l=e[10];return t*(s*l-a*c)-n*(r*l-a*o)+i*(r*c-s*o)}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],a=e[5],o=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],h=e[12],b=e[13],m=e[14],g=e[15],p=t*a-n*s,x=t*o-i*s,_=t*c-r*s,y=n*o-i*a,v=n*c-r*a,E=i*c-r*o,w=l*b-u*h,T=l*m-d*h,A=l*g-f*h,P=u*m-d*b,S=u*g-f*b,R=d*g-f*m,k=p*R-x*S+_*P+y*A-v*T+E*w;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let C=1/k;return e[0]=(a*R-o*S+c*P)*C,e[1]=(i*S-n*R-r*P)*C,e[2]=(b*E-m*v+g*y)*C,e[3]=(d*v-u*E-f*y)*C,e[4]=(o*A-s*R-c*T)*C,e[5]=(t*R-i*A+r*T)*C,e[6]=(m*_-h*E-g*x)*C,e[7]=(l*E-d*_+f*x)*C,e[8]=(s*S-a*A+c*w)*C,e[9]=(n*A-t*S-r*w)*C,e[10]=(h*v-b*_+g*p)*C,e[11]=(u*_-l*v-f*p)*C,e[12]=(a*T-s*P-o*w)*C,e[13]=(t*P-n*T+i*w)*C,e[14]=(b*x-h*y-m*p)*C,e[15]=(l*y-u*x+d*p)*C,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:a,z:o}=e,c=r*s,l=r*a;return this.set(c*s+n,c*a-i*o,c*o+i*a,0,c*a+i*o,l*a+n,l*o-i*s,0,c*o-i*a,l*o+i*s,r*o*o+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:a,_w:o}=t,c=r+r,l=s+s,u=a+a,d=r*c,f=r*l,h=r*u,b=s*l,m=s*u,g=a*u,p=o*c,x=o*l,_=o*u,{x:y,y:v,z:E}=n;return i[0]=(1-(b+g))*y,i[1]=(f+_)*y,i[2]=(h-x)*y,i[3]=0,i[4]=(f-_)*v,i[5]=(1-(d+g))*v,i[6]=(m+p)*v,i[7]=0,i[8]=(h+x)*E,i[9]=(m-p)*E,i[10]=(1-(d+b))*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=ao.set(i[0],i[1],i[2]).length(),a=ao.set(i[4],i[5],i[6]).length(),o=ao.set(i[8],i[9],i[10]).length();if(r<0)s=-s;Oi.copy(this);let c=1/s,l=1/a,u=1/o;return Oi.elements[0]*=c,Oi.elements[1]*=c,Oi.elements[2]*=c,Oi.elements[4]*=l,Oi.elements[5]*=l,Oi.elements[6]*=l,Oi.elements[8]*=u,Oi.elements[9]*=u,Oi.elements[10]*=u,t.setFromRotationMatrix(Oi),n.x=s,n.y=a,n.z=o,this}makePerspective(e,t,n,i,r,s,a=2000,o=!1){let c=this.elements,l=2*r/(t-e),u=2*r/(n-i),d=(t+e)/(t-e),f=(n+i)/(n-i),h,b;if(o)h=r/(s-r),b=s*r/(s-r);else if(a===2000)h=-(s+r)/(s-r),b=-2*s*r/(s-r);else if(a===2001)h=-s/(s-r),b=-s*r/(s-r);else throw Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=h,c[14]=b,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,i,r,s,a=2000,o=!1){let c=this.elements,l=2/(t-e),u=2/(n-i),d=-(t+e)/(t-e),f=-(n+i)/(n-i),h,b;if(o)h=1/(s-r),b=s/(s-r);else if(a===2000)h=-2/(s-r),b=-(s+r)/(s-r);else if(a===2001)h=-1/(s-r),b=-r/(s-r);else throw Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=h,c[14]=b,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}};ao=new j,Oi=new Je,zN=new j(0,0,0),VN=new j(1,1,1),is=new j,Bu=new j,ai=new j,yE=new Je,_E=new ln;ur=class ur{constructor(e=0,t=0,n=0,i=ur.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],a=i[8],o=i[1],c=i[5],l=i[9],u=i[2],d=i[6],f=i[10];switch(t){case"XYZ":if(this._y=Math.asin(ct(a,-1,1)),Math.abs(a)<0.9999999)this._x=Math.atan2(-l,f),this._z=Math.atan2(-s,r);else this._x=Math.atan2(d,c),this._z=0;break;case"YXZ":if(this._x=Math.asin(-ct(l,-1,1)),Math.abs(l)<0.9999999)this._y=Math.atan2(a,f),this._z=Math.atan2(o,c);else this._y=Math.atan2(-u,r),this._z=0;break;case"ZXY":if(this._x=Math.asin(ct(d,-1,1)),Math.abs(d)<0.9999999)this._y=Math.atan2(-u,f),this._z=Math.atan2(-s,c);else this._y=0,this._z=Math.atan2(o,r);break;case"ZYX":if(this._y=Math.asin(-ct(u,-1,1)),Math.abs(u)<0.9999999)this._x=Math.atan2(d,f),this._z=Math.atan2(o,r);else this._x=0,this._z=Math.atan2(-s,c);break;case"YZX":if(this._z=Math.asin(ct(o,-1,1)),Math.abs(o)<0.9999999)this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,r);else this._x=0,this._y=Math.atan2(a,f);break;case"XZY":if(this._z=Math.asin(-ct(s,-1,1)),Math.abs(s)<0.9999999)this._x=Math.atan2(d,c),this._y=Math.atan2(a,r);else this._x=Math.atan2(-l,f),this._y=0;break;default:je("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}if(this._order=t,n===!0)this._onChangeCallback();return this}setFromQuaternion(e,t,n){return yE.makeRotationFromQuaternion(e),this.setFromRotationMatrix(yE,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return _E.setFromEuler(this),this.setFromQuaternion(_E,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}};ur.DEFAULT_ORDER="XYZ";vE=new j,oo=new ln,Pr=new Je,zu=new j,Fc=new j,HN=new j,GN=new ln,EE=new j(1,0,0),TE=new j(0,1,0),AE=new j(0,0,1),wE={type:"added"},$N={type:"removed"},co={type:"childadded",child:null},pp={type:"childremoved",child:null};Dt=class Dt extends Vi{constructor(){super();this.isObject3D=!0,Object.defineProperty(this,"id",{value:jN++}),this.uuid=Fi(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Dt.DEFAULT_UP.clone();let e=new j,t=new ur,n=new ln,i=new j(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 Je},normalMatrix:{value:new tt}}),this.matrix=new Je,this.matrixWorld=new Je,this.matrixAutoUpdate=Dt.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Md,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 oo.setFromAxisAngle(e,t),this.quaternion.multiply(oo),this}rotateOnWorldAxis(e,t){return oo.setFromAxisAngle(e,t),this.quaternion.premultiply(oo),this}rotateX(e){return this.rotateOnAxis(EE,e)}rotateY(e){return this.rotateOnAxis(TE,e)}rotateZ(e){return this.rotateOnAxis(AE,e)}translateOnAxis(e,t){return vE.copy(e).applyQuaternion(this.quaternion),this.position.add(vE.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(EE,e)}translateY(e){return this.translateOnAxis(TE,e)}translateZ(e){return this.translateOnAxis(AE,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Pr.copy(this.matrixWorld).invert())}lookAt(e,t,n){if(e.isVector3)zu.copy(e);else zu.set(e,t,n);let i=this.parent;if(this.updateWorldMatrix(!0,!1),Fc.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight)Pr.lookAt(Fc,zu,this.up);else Pr.lookAt(zu,Fc,this.up);if(this.quaternion.setFromRotationMatrix(Pr),i)Pr.extractRotation(i.matrixWorld),oo.setFromRotationMatrix(Pr),this.quaternion.premultiply(oo.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 Ye("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(wE),co.child=e,this.dispatchEvent(co),co.child=null;else Ye("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($N),pp.child=e,this.dispatchEvent(pp),pp.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),Pr.copy(this.matrixWorld).invert(),e.parent!==null)e.parent.updateWorldMatrix(!0,!1),Pr.multiply(e.parent.matrixWorld);return e.applyMatrix4(Pr),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(wE),co.child=e,this.dispatchEvent(co),co.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(Fc,e,HN),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Fc,GN,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}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,a=r.length;s<a;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,i.name=this.name,i.castShadow=this.castShadow,i.receiveShadow=this.receiveShadow,i.visible=this.visible,i.frustumCulled=this.frustumCulled,i.renderOrder=this.renderOrder,i.static=this.static,i.matrixAutoUpdate=this.matrixAutoUpdate,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.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((a)=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map((a)=>({...a})),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(a,o){if(a[o.uuid]===void 0)a[o.uuid]=o.toJSON(e);return o.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 a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){let o=a.shapes;if(Array.isArray(o))for(let c=0,l=o.length;c<l;c++){let u=o[c];r(e.shapes,u)}else r(e.shapes,o)}}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 a=[];for(let o=0,c=this.material.length;o<c;o++)a.push(r(e.materials,this.material[o]));i.material=a}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let a=0;a<this.children.length;a++)i.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let a=0;a<this.animations.length;a++){let o=this.animations[a];i.animations.push(r(e.animations,o))}}if(t){let a=s(e.geometries),o=s(e.materials),c=s(e.textures),l=s(e.images),u=s(e.shapes),d=s(e.skeletons),f=s(e.animations),h=s(e.nodes);if(a.length>0)n.geometries=a;if(o.length>0)n.materials=o;if(c.length>0)n.textures=c;if(l.length>0)n.images=l;if(u.length>0)n.shapes=u;if(d.length>0)n.skeletons=d;if(f.length>0)n.animations=f;if(h.length>0)n.nodes=h}return n.object=i,n;function s(a){let o=[];for(let c in a){let l=a[c];delete l.metadata,o.push(l)}return o}}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}dispose(){this.dispatchEvent({type:"dispose"})}};Dt.DEFAULT_UP=new j(0,1,0);Dt.DEFAULT_MATRIX_AUTO_UPDATE=!0;Dt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;cr=class cr extends Dt{constructor(){super();this.isGroup=!0,this.type="Group"}};KN={type:"move"};qT={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},rs={h:0,s:0,l:0},Vu={h:0,s:0,l:0};qe=class qe{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,ot.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=ot.workingColorSpace){return this.r=e,this.g=t,this.b=n,ot.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=ot.workingColorSpace){if(e=km(e,1),t=ct(t,0,1),n=ct(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=mp(s,r,e+0.3333333333333333),this.g=mp(s,r,e),this.b=mp(s,r,e-0.3333333333333333)}return ot.colorSpaceToWorking(this,i),this}setStyle(e,t="srgb"){function n(r){if(r===void 0)return;if(parseFloat(r)<1)je("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r,s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,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(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:je("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 je("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t="srgb"){let n=qT[e.toLowerCase()];if(n!==void 0)this.setHex(n,t);else je("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=Ur(e.r),this.g=Ur(e.g),this.b=Ur(e.b),this}copyLinearToSRGB(e){return this.r=_o(e.r),this.g=_o(e.g),this.b=_o(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e="srgb"){return ot.workingToColorSpace(kn.copy(this),e),Math.round(ct(kn.r*255,0,255))*65536+Math.round(ct(kn.g*255,0,255))*256+Math.round(ct(kn.b*255,0,255))}getHexString(e="srgb"){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ot.workingColorSpace){ot.workingToColorSpace(kn.copy(this),t);let{r:n,g:i,b:r}=kn,s=Math.max(n,i,r),a=Math.min(n,i,r),o,c,l=(a+s)/2;if(a===s)o=0,c=0;else{let u=s-a;switch(c=l<=0.5?u/(s+a):u/(2-s-a),s){case n:o=(i-r)/u+(i<r?6:0);break;case i:o=(r-n)/u+2;break;case r:o=(n-i)/u+4;break}o/=6}return e.h=o,e.s=c,e.l=l,e}getRGB(e,t=ot.workingColorSpace){return ot.workingToColorSpace(kn.copy(this),t),e.r=kn.r,e.g=kn.g,e.b=kn.b,e}getStyle(e="srgb"){ot.workingToColorSpace(kn.copy(this),e);let{r:t,g:n,b:i}=kn;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(rs),this.setHSL(rs.h+e,rs.s+t,rs.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(rs),e.getHSL(Vu);let n=Kc(rs.h,Vu.h,t),i=Kc(rs.s,Vu.s,t),r=Kc(rs.l,Vu.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}};kn=new qe;qe.NAMES=qT;Po=class Po extends Dt{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 ur,this.environmentIntensity=1,this.environmentRotation=new ur,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();return t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}};ki=new j,Or=new j,gp=new j,kr=new j,lo=new j,uo=new j,SE=new j,bp=new j,xp=new j,yp=new j,_p=new Pt,vp=new Pt,Ep=new Pt;Dr=[new j,new j,new j,new j,new j,new j,new j,new j],Di=new j,ju=new pn,fo=new j,ho=new j,po=new j,ss=new j,as=new j,ma=new j,Uc=new j,Hu=new j,Gu=new j,ga=new j;cn=new j,$u=new Ke;En=class En extends Vi{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:WN++}),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++)$u.fromBufferAttribute(this,t),$u.applyMatrix3(e),this.setXY(t,$u.x,$u.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)cn.fromBufferAttribute(this,t),cn.applyMatrix3(e),this.setXYZ(t,cn.x,cn.y,cn.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)cn.fromBufferAttribute(this,t),cn.applyMatrix4(e),this.setXYZ(t,cn.x,cn.y,cn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)cn.fromBufferAttribute(this,t),cn.applyNormalMatrix(e),this.setXYZ(t,cn.x,cn.y,cn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)cn.fromBufferAttribute(this,t),cn.transformDirection(e),this.setXYZ(t,cn.x,cn.y,cn.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=Li(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=Li(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=Li(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=Li(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=Li(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};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:"dispose"})}};Rd=class Rd extends En{constructor(e,t,n){super(new Uint16Array(e),t,n)}};Id=class Id extends En{constructor(e,t,n){super(new Uint32Array(e),t,n)}};Xn=class Xn extends En{constructor(e,t,n){super(new Float32Array(e),t,n)}};XN=new pn,Bc=new j,Ap=new j;xi=new Je,wp=new Dt,mo=new j,oi=new pn,zc=new pn,vn=new j;Ln=class Ln extends Vi{constructor(){super();this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:qN++}),this.uuid=Fi(),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((yN(e))?Id:Rd)(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 tt().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 xi.makeRotationFromQuaternion(e),this.applyMatrix4(xi),this}rotateX(e){return xi.makeRotationX(e),this.applyMatrix4(xi),this}rotateY(e){return xi.makeRotationY(e),this.applyMatrix4(xi),this}rotateZ(e){return xi.makeRotationZ(e),this.applyMatrix4(xi),this}translate(e,t,n){return xi.makeTranslation(e,t,n),this.applyMatrix4(xi),this}scale(e,t,n){return xi.makeScale(e,t,n),this.applyMatrix4(xi),this}lookAt(e){return wp.lookAt(e),wp.updateMatrix(),this.applyMatrix4(wp.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(mo).negate(),this.translate(mo.x,mo.y,mo.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 Xn(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)je("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 pn;let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ye("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(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n<i;n++){let r=t[n];if(oi.setFromBufferAttribute(r),this.morphTargetsRelative)vn.addVectors(this.boundingBox.min,oi.min),this.boundingBox.expandByPoint(vn),vn.addVectors(this.boundingBox.max,oi.max),this.boundingBox.expandByPoint(vn);else this.boundingBox.expandByPoint(oi.min),this.boundingBox.expandByPoint(oi.max)}}else this.boundingBox.makeEmpty();if(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))Ye('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 ui;let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ye("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new j,1/0);return}if(e){let n=this.boundingSphere.center;if(oi.setFromBufferAttribute(e),t)for(let r=0,s=t.length;r<s;r++){let a=t[r];if(zc.setFromBufferAttribute(a),this.morphTargetsRelative)vn.addVectors(oi.min,zc.min),oi.expandByPoint(vn),vn.addVectors(oi.max,zc.max),oi.expandByPoint(vn);else oi.expandByPoint(zc.min),oi.expandByPoint(zc.max)}oi.getCenter(n);let i=0;for(let r=0,s=e.count;r<s;r++)vn.fromBufferAttribute(e,r),i=Math.max(i,n.distanceToSquared(vn));if(t)for(let r=0,s=t.length;r<s;r++){let a=t[r],o=this.morphTargetsRelative;for(let c=0,l=a.count;c<l;c++){if(vn.fromBufferAttribute(a,c),o)mo.fromBufferAttribute(e,c),vn.add(mo);i=Math.max(i,n.distanceToSquared(vn))}}if(this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius))Ye('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){Ye("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 En(new Float32Array(4*n.count),4),this.setAttribute("tangent",s);let a=[],o=[];for(let w=0;w<n.count;w++)a[w]=new j,o[w]=new j;let c=new j,l=new j,u=new j,d=new Ke,f=new Ke,h=new Ke,b=new j,m=new j;function g(w,T,A){c.fromBufferAttribute(n,w),l.fromBufferAttribute(n,T),u.fromBufferAttribute(n,A),d.fromBufferAttribute(r,w),f.fromBufferAttribute(r,T),h.fromBufferAttribute(r,A),l.sub(c),u.sub(c),f.sub(d),h.sub(d);let P=1/(f.x*h.y-h.x*f.y);if(!isFinite(P))return;b.copy(l).multiplyScalar(h.y).addScaledVector(u,-f.y).multiplyScalar(P),m.copy(u).multiplyScalar(f.x).addScaledVector(l,-h.x).multiplyScalar(P),a[w].add(b),a[T].add(b),a[A].add(b),o[w].add(m),o[T].add(m),o[A].add(m)}let p=this.groups;if(p.length===0)p=[{start:0,count:e.count}];for(let w=0,T=p.length;w<T;++w){let A=p[w],{start:P,count:S}=A;for(let R=P,k=P+S;R<k;R+=3)g(e.getX(R+0),e.getX(R+1),e.getX(R+2))}let x=new j,_=new j,y=new j,v=new j;function E(w){y.fromBufferAttribute(i,w),v.copy(y);let T=a[w];x.copy(T),x.sub(y.multiplyScalar(y.dot(T))).normalize(),_.crossVectors(v,T);let P=_.dot(o[w])<0?-1:1;s.setXYZW(w,x.x,x.y,x.z,P)}for(let w=0,T=p.length;w<T;++w){let A=p[w],{start:P,count:S}=A;for(let R=P,k=P+S;R<k;R+=3)E(e.getX(R+0)),E(e.getX(R+1)),E(e.getX(R+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 En(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let d=0,f=n.count;d<f;d++)n.setXYZ(d,0,0,0);let i=new j,r=new j,s=new j,a=new j,o=new j,c=new j,l=new j,u=new j;if(e)for(let d=0,f=e.count;d<f;d+=3){let h=e.getX(d+0),b=e.getX(d+1),m=e.getX(d+2);i.fromBufferAttribute(t,h),r.fromBufferAttribute(t,b),s.fromBufferAttribute(t,m),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),a.fromBufferAttribute(n,h),o.fromBufferAttribute(n,b),c.fromBufferAttribute(n,m),a.add(l),o.add(l),c.add(l),n.setXYZ(h,a.x,a.y,a.z),n.setXYZ(b,o.x,o.y,o.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let d=0,f=t.count;d<f;d+=3)i.fromBufferAttribute(t,d+0),r.fromBufferAttribute(t,d+1),s.fromBufferAttribute(t,d+2),l.subVectors(s,r),u.subVectors(i,r),l.cross(u),n.setXYZ(d+0,l.x,l.y,l.z),n.setXYZ(d+1,l.x,l.y,l.z),n.setXYZ(d+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++)vn.fromBufferAttribute(e,t),vn.normalize(),e.setXYZ(t,vn.x,vn.y,vn.z)}toNonIndexed(){function e(a,o){let{array:c,itemSize:l,normalized:u}=a,d=new c.constructor(o.length*l),f=0,h=0;for(let b=0,m=o.length;b<m;b++){if(a.isInterleavedBufferAttribute)f=o[b]*a.data.stride+a.offset;else f=o[b]*l;for(let g=0;g<l;g++)d[h++]=c[f++]}return new En(d,l,u)}if(this.index===null)return je("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let t=new Ln,n=this.index.array,i=this.attributes;for(let a in i){let o=i[a],c=e(o,n);t.setAttribute(a,c)}let r=this.morphAttributes;for(let a in r){let o=[],c=r[a];for(let l=0,u=c.length;l<u;l++){let d=c[l],f=e(d,n);o.push(f)}t.morphAttributes[a]=o}t.morphTargetsRelative=this.morphTargetsRelative;let s=this.groups;for(let a=0,o=s.length;a<o;a++){let c=s[a];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,e.name=this.name,Object.keys(this.userData).length>0)e.userData=this.userData;if(this.parameters!==void 0&&this._transformed!==!0){let o=this.parameters;for(let c in o)if(o[c]!==void 0)e[c]=o[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 o in n){let c=n[o];e.data.attributes[o]=c.toJSON(e.data)}let i={},r=!1;for(let o in this.morphAttributes){let c=this.morphAttributes[o],l=[];for(let u=0,d=c.length;u<d;u++){let f=c[u];l.push(f.toJSON(e.data))}if(l.length>0)i[o]=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 a=this.boundingSphere;if(a!==null)e.data.boundingSphere=a.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 d=0,f=u.length;d<f;d++)l.push(u[d].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 a=e.boundingBox;if(a!==null)this.boundingBox=a.clone();let o=e.boundingSphere;if(o!==null)this.boundingSphere=o.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"})}};Gn=new j;Sp=new j,JN=new j,ZN=new tt;qn=class qn extends Vi{constructor(){super();this.isMaterial=!0,Object.defineProperty(this,"id",{value:YN++}),this.uuid=Fi(),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 qe(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){je(`Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){je(`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,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor)n.color=this.color.getHex();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)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.retroreflectivity!==void 0)n.retroreflectivity=this.retroreflectivity;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)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.sizeAttenuation!==void 0)n.sizeAttenuation=this.sizeAttenuation;if(Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0)n.clippingPlanes=this.clippingPlanes.map((r)=>r.toJSON());if(this.rotation!==void 0)n.rotation=this.rotation;if(this.depthPacking!==void 0)n.depthPacking=this.depthPacking;if(this.linewidth!==void 0)n.linewidth=this.linewidth;if(this.linecap!==void 0)n.linecap=this.linecap;if(this.linejoin!==void 0)n.linejoin=this.linejoin;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.wireframe!==void 0)n.wireframe=this.wireframe;if(this.wireframeLinewidth!==void 0)n.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!==void 0)n.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!==void 0)n.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading!==void 0)n.flatShading=this.flatShading;if(this.fog!==void 0)n.fog=this.fog;if(Object.keys(this.userData).length>0)n.userData=this.userData;function i(r){let s=[];for(let a in r){let o=r[a];delete o.metadata,s.push(o)}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 qe().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.retroreflectivity!==void 0)this.retroreflectivity=e.retroreflectivity;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.clippingPlanes!==void 0)this.clippingPlanes=e.clippingPlanes.map((n)=>new yi().fromJSON(n));if(e.clipIntersection!==void 0)this.clipIntersection=e.clipIntersection;if(e.clipShadows!==void 0)this.clipShadows=e.clipShadows;if(e.depthPacking!==void 0)this.depthPacking=e.depthPacking;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.linecap!==void 0)this.linecap=e.linecap;if(e.linejoin!==void 0)this.linejoin=e.linejoin;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 Ke().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 Ke().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++}};Lr=new j,Mp=new j,Ku=new j,Wu=new j;mr=class mr extends qn{constructor(e){super();this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new qe(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 ur,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}};ME=new Je,ba=new ms,Xu=new ui,RE=new j,qu=new j,Ju=new j,Zu=new j,Rp=new j,Yu=new j,IE=new j,Qu=new j;jt=class jt extends Dt{constructor(e=new Ln,t=new mr){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 a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(e,t){let n=this.geometry,i=n.attributes.position,r=n.morphAttributes.position,s=n.morphTargetsRelative;t.fromBufferAttribute(i,e);let a=this.morphTargetInfluences;if(r&&a){Yu.set(0,0,0);for(let o=0,c=r.length;o<c;o++){let l=a[o],u=r[o];if(l===0)continue;if(Rp.fromBufferAttribute(u,e),s)Yu.addScaledVector(Rp,l);else Yu.addScaledVector(Rp.sub(t),l)}t.add(Yu)}return t}intersectsFrustum(e){return e.intersectsObject(this)}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(Xu.copy(n.boundingSphere),Xu.applyMatrix4(r),ba.copy(e.ray).recast(e.near),Xu.containsPoint(ba.origin)===!1){if(ba.intersectSphere(Xu,RE)===null)return;if(ba.origin.distanceToSquared(RE)>(e.far-e.near)**2)return}if(ME.copy(r).invert(),ba.copy(e.ray).applyMatrix4(ME),n.boundingBox!==null){if(ba.intersectsBox(n.boundingBox)===!1)return}this._computeIntersections(e,t,ba)}_computeIntersections(e,t,n){let i,r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,c=r.attributes.uv,l=r.attributes.uv1,u=r.attributes.normal,{groups:d,drawRange:f}=r;if(a!==null)if(Array.isArray(s))for(let h=0,b=d.length;h<b;h++){let m=d[h],g=s[m.materialIndex],p=Math.max(m.start,f.start),x=Math.min(a.count,Math.min(m.start+m.count,f.start+f.count));for(let _=p,y=x;_<y;_+=3){let v=a.getX(_),E=a.getX(_+1),w=a.getX(_+2);if(i=ed(this,g,e,n,c,l,u,v,E,w),i)i.faceIndex=Math.floor(_/3),i.face.materialIndex=m.materialIndex,t.push(i)}}else{let h=Math.max(0,f.start),b=Math.min(a.count,f.start+f.count);for(let m=h,g=b;m<g;m+=3){let p=a.getX(m),x=a.getX(m+1),_=a.getX(m+2);if(i=ed(this,s,e,n,c,l,u,p,x,_),i)i.faceIndex=Math.floor(m/3),t.push(i)}}else if(o!==void 0)if(Array.isArray(s))for(let h=0,b=d.length;h<b;h++){let m=d[h],g=s[m.materialIndex],p=Math.max(m.start,f.start),x=Math.min(o.count,Math.min(m.start+m.count,f.start+f.count));for(let _=p,y=x;_<y;_+=3){let v=_,E=_+1,w=_+2;if(i=ed(this,g,e,n,c,l,u,v,E,w),i)i.faceIndex=Math.floor(_/3),i.face.materialIndex=m.materialIndex,t.push(i)}}else{let h=Math.max(0,f.start),b=Math.min(o.count,f.start+f.count);for(let m=h,g=b;m<g;m+=3){let p=m,x=m+1,_=m+2;if(i=ed(this,s,e,n,c,l,u,p,x,_),i)i.faceIndex=Math.floor(m/3),t.push(i)}}}};Vc=new Pt,CE=new Pt,NE=new Pt,eP=new Pt,PE=new Je,td=new j,Ip=new ui,OE=new Je,Cp=new ms;Cd=class Cd extends jt{constructor(e,t){super(e,t);this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode="attached",this.bindMatrix=new Je,this.bindMatrixInverse=new Je,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;if(this.boundingBox===null)this.boundingBox=new pn;this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,td),this.boundingBox.expandByPoint(td)}computeBoundingSphere(){let e=this.geometry;if(this.boundingSphere===null)this.boundingSphere=new ui;this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,td),this.boundingSphere.expandByPoint(td)}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(Ip.copy(this.boundingSphere),Ip.applyMatrix4(i),e.ray.intersectsSphere(Ip)===!1)return;if(OE.copy(i).invert(),Cp.copy(e.ray).applyMatrix4(OE),this.boundingBox!==null){if(Cp.intersectsBox(this.boundingBox)===!1)return}this._computeIntersections(e,t,Cp)}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 Pt,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 je("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,i=this.geometry;if(CE.fromBufferAttribute(i.attributes.skinIndex,e),NE.fromBufferAttribute(i.attributes.skinWeight,e),t.isVector4)Vc.copy(t),t.set(0,0,0,0);else Vc.set(...t,1),t.set(0,0,0);Vc.applyMatrix4(this.bindMatrix);for(let r=0;r<4;r++){let s=NE.getComponent(r);if(s!==0){let a=CE.getComponent(r);PE.multiplyMatrices(n.bones[a].matrixWorld,n.boneInverses[a]),t.addScaledVector(eP.copy(Vc).applyMatrix4(PE),s)}}if(t.isVector4)t.w=Vc.w;return t.applyMatrix4(this.bindMatrixInverse)}};rl=class rl extends Dt{constructor(){super();this.isBone=!0,this.type="Bone"}};sl=class sl extends en{constructor(e=null,t=1,n=1,i,r,s,a,o,c=1003,l=1003,u,d){super(null,s,a,o,c,l,i,r,u,d);this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};kE=new Je,tP=new Je;ls=class ls extends En{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}};go=new Je,DE=new Je,nd=[],LE=new pn,nP=new Je,jc=new jt,Hc=new ui;ko=class ko extends jt{constructor(e,t,n){super(e,t);this.isInstancedMesh=!0,this.instanceMatrix=new ls(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,nP)}computeBoundingBox(){let e=this.geometry,t=this.count;if(this.boundingBox===null)this.boundingBox=new pn;if(e.boundingBox===null)e.computeBoundingBox();this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,go),LE.copy(e.boundingBox).applyMatrix4(go),this.boundingBox.union(LE)}computeBoundingSphere(){let e=this.geometry,t=this.count;if(this.boundingSphere===null)this.boundingSphere=new ui;if(e.boundingSphere===null)e.computeBoundingSphere();this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,go),Hc.copy(e.boundingSphere).applyMatrix4(go),this.boundingSphere.union(Hc)}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 a=0;a<n.length;a++)n[a]=i[s+a]}raycast(e,t){let n=this.matrixWorld,i=this.count;if(jc.geometry=this.geometry,jc.material=this.material,jc.material===void 0)return;if(this.boundingSphere===null)this.computeBoundingSphere();if(Hc.copy(this.boundingSphere),Hc.applyMatrix4(n),e.ray.intersectsSphere(Hc)===!1)return;for(let r=0;r<i;r++){this.getMatrixAt(r,go),DE.multiplyMatrices(n,go),jc.matrixWorld=DE,jc.raycast(e,nd);for(let s=0,a=nd.length;s<a;s++){let o=nd[s];o.instanceId=r,o.object=this,t.push(o)}nd.length=0}}setColorAt(e,t){if(this.instanceColor===null)this.instanceColor=new ls(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 sl(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 a=this.geometry.morphTargetsRelative?1:1-s,o=i*e;return r[o]=a,r.set(n,o+1),this}updateMorphTargets(){}dispose(){if(super.dispose(),this.morphTexture!==null)this.morphTexture.dispose(),this.morphTexture=null}};xa=new ui,iP=new Ke(0.5,0.5),id=new j;cl=class cl extends qn{constructor(e){super();this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new qe(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}};dd=new j,fd=new j,FE=new Je,Gc=new ms,rd=new ui,Np=new j,UE=new j;gs=class gs extends Dt{constructor(e=new Ln,t=new cl){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++)dd.fromBufferAttribute(t,i-1),fd.fromBufferAttribute(t,i),n[i]=n[i-1],n[i]+=dd.distanceTo(fd);e.setAttribute("lineDistance",new Xn(n,1))}else je("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}intersectsFrustum(e){return e.intersectsObject(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(rd.copy(n.boundingSphere),rd.applyMatrix4(i),rd.radius+=r,e.ray.intersectsSphere(rd)===!1)return;FE.copy(i).invert(),Gc.copy(e.ray).applyMatrix4(FE);let a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,c=this.isLineSegments?2:1,l=n.index,d=n.attributes.position;if(l!==null){let f=Math.max(0,s.start),h=Math.min(l.count,s.start+s.count);for(let b=f,m=h-1;b<m;b+=c){let g=l.getX(b),p=l.getX(b+1),x=sd(this,e,Gc,o,g,p,b);if(x)t.push(x)}if(this.isLineLoop){let b=l.getX(h-1),m=l.getX(f),g=sd(this,e,Gc,o,b,m,h-1);if(g)t.push(g)}}else{let f=Math.max(0,s.start),h=Math.min(d.count,s.start+s.count);for(let b=f,m=h-1;b<m;b+=c){let g=sd(this,e,Gc,o,b,b+1,b);if(g)t.push(g)}if(this.isLineLoop){let b=sd(this,e,Gc,o,h-1,f,h-1);if(b)t.push(b)}}}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 a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}};BE=new j,zE=new j;Nd=class Nd extends gs{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)BE.fromBufferAttribute(t,i),zE.fromBufferAttribute(t,i+1),n[i]=i===0?0:n[i-1],n[i+1]=n[i]+BE.distanceTo(zE);e.setAttribute("lineDistance",new Xn(n,1))}else je("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}};Pd=class Pd extends gs{constructor(e,t){super(e,t);this.isLineLoop=!0,this.type="LineLoop"}};ll=class ll extends qn{constructor(e){super();this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new qe(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}};VE=new Je,kp=new ms,ad=new ui,od=new j;Do=class Do extends Dt{constructor(e=new Ln,t=new ll){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}intersectsFrustum(e){return e.intersectsObject(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(ad.copy(n.boundingSphere),ad.applyMatrix4(i),ad.radius+=r,e.ray.intersectsSphere(ad)===!1)return;VE.copy(i).invert(),kp.copy(e.ray).applyMatrix4(VE);let a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,c=n.index,u=n.attributes.position;if(c!==null){let d=Math.max(0,s.start),f=Math.min(c.count,s.start+s.count);for(let h=d,b=f;h<b;h++){let m=c.getX(h);od.fromBufferAttribute(u,m),jE(od,m,o,i,e,t,this)}}else{let d=Math.max(0,s.start),f=Math.min(u.count,s.start+s.count);for(let h=d,b=f;h<b;h++)od.fromBufferAttribute(u,h),jE(od,h,o,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 a=i[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}};Od=class Od extends en{constructor(e=[],t=301,n,i,r,s,a,o,c,l){super(e,t,n,i,r,s,a,o,c,l);this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}};Ma=class Ma extends en{constructor(e,t,n=1014,i,r,s,a=1003,o=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 d={width:e,height:t,depth:u};super(d,i,r,s,a,o,l,n,c);this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new tl(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}};Um=class Um extends Ma{constructor(e,t=1014,n=301,i,r,s=1003,a=1003,o,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,a,o,c);this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}};kd=class kd extends en{constructor(e=null){super();this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}};bs=class bs extends Ln{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 a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);let o=[],c=[],l=[],u=[],d=0,f=0;h("z","y","x",-1,-1,n,t,e,s,r,0),h("z","y","x",1,-1,n,t,-e,s,r,1),h("x","z","y",1,1,e,n,t,i,s,2),h("x","z","y",1,-1,e,n,-t,i,s,3),h("x","y","z",1,-1,e,t,n,i,r,4),h("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(o),this.setAttribute("position",new Xn(c,3)),this.setAttribute("normal",new Xn(l,3)),this.setAttribute("uv",new Xn(u,2));function h(b,m,g,p,x,_,y,v,E,w,T){let A=_/E,P=y/w,S=_/2,R=y/2,k=v/2,C=E+1,U=w+1,L=0,O=0,K=new j;for(let B=0;B<U;B++){let X=B*P-R;for(let q=0;q<C;q++){let le=q*A-S;K[b]=le*p,K[m]=X*x,K[g]=k,c.push(K.x,K.y,K.z),K[b]=0,K[m]=0,K[g]=v>0?1:-1,l.push(K.x,K.y,K.z),u.push(q/E),u.push(1-B/w),L+=1}}for(let B=0;B<w;B++)for(let X=0;X<E;X++){let q=d+X+C*B,le=d+X+C*(B+1),de=d+(X+1)+C*(B+1),Me=d+(X+1)+C*B;o.push(q,le,Me),o.push(le,de,Me),O+=6}a.addGroup(f,O,T),f+=O,d+=L}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new bs(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}};ul=class ul extends Ln{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,a=Math.floor(n),o=Math.floor(i),c=a+1,l=o+1,u=e/a,d=t/o,f=[],h=[],b=[],m=[];for(let g=0;g<l;g++){let p=g*d-s;for(let x=0;x<c;x++){let _=x*u-r;h.push(_,-p,0),b.push(0,0,1),m.push(x/a),m.push(1-g/o)}}for(let g=0;g<o;g++)for(let p=0;p<a;p++){let x=p+c*g,_=p+c*(g+1),y=p+1+c*(g+1),v=p+1+c*g;f.push(x,_,v),f.push(_,y,v)}this.setIndex(f),this.setAttribute("position",new Xn(h,3)),this.setAttribute("normal",new Xn(b,3)),this.setAttribute("uv",new Xn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ul(e.width,e.height,e.widthSegments,e.heightSegments)}};JT={clone:Ra,merge:Fn};Ei=class Ei extends qn{constructor(e){super();if(this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=sP,this.fragmentShader=aP,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=Ra(e.uniforms),this.uniformsGroups=rP(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 qe().setHex(i.value);break;case"v2":this.uniforms[n].value=new Ke().fromArray(i.value);break;case"v3":this.uniforms[n].value=new j().fromArray(i.value);break;case"v4":this.uniforms[n].value=new Pt().fromArray(i.value);break;case"m3":this.uniforms[n].value=new tt().fromArray(i.value);break;case"m4":this.uniforms[n].value=new Je().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}};zm=class zm extends Ei{constructor(e){super(e);this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}};zr=class zr extends qn{constructor(e){super();this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new qe(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 qe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ke(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 ur,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}};di=class di extends zr{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 Ke(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return ct(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 qe(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 qe(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new qe(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._retroreflectivity=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 retroreflectivity(){return this._retroreflectivity}set retroreflectivity(e){if(this._retroreflectivity>0!==e>0)this.version++;this._retroreflectivity=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.retroreflectivity=e.retroreflectivity,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}};Dd=class Dd extends qn{constructor(e){super();this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new qe(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new qe(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Ke(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ur,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}};Vm=class Vm extends qn{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}};jm=class jm extends qn{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}};Hm=class Hm extends Vr{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,a=i[r],o=i[s];if(a===void 0)switch(this.getSettings_().endingStart){case 2401:r=e,a=2*t-n;break;case 2402:r=i.length-2,a=t+i[r]-i[r+1];break;default:r=e,a=n}if(o===void 0)switch(this.getSettings_().endingEnd){case 2401:s=e,o=2*n-t;break;case 2402:s=1,o=n+i[1]-i[0];break;default:s=e-1,o=t}let c=(n-t)*0.5,l=this.valueSize;this._weightPrev=c/(t-a),this._weightNext=c/(o-n),this._offsetPrev=r*l,this._offsetNext=s*l}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,c=o-a,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,h=(n-t)/(i-t),b=h*h,m=b*h,g=-d*m+2*d*b-d*h,p=(1+d)*m+(-1.5-2*d)*b+(-0.5+d)*h+1,x=(-1-f)*m+(1.5+f)*b+0.5*h,_=f*m-f*b;for(let y=0;y!==a;++y)r[y]=g*s[l+y]+p*s[c+y]+x*s[o+y]+_*s[u+y];return r}};Ld=class Ld extends Vr{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,c=o-a,l=(n-t)/(i-t),u=1-l;for(let d=0;d!==a;++d)r[d]=s[c+d]*u+s[o+d]*l;return r}};Gm=class Gm extends Vr{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e){return this.copySampleValue_(e-1)}};$m=class $m extends Vr{interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,c=o-a,l=this.inTangents,u=this.outTangents;if(!l||!u){let h=(n-t)/(i-t),b=1-h;for(let m=0;m!==a;++m)r[m]=s[c+m]*b+s[o+m]*h;return r}let d=a*2,f=e-1;for(let h=0;h!==a;++h){let b=s[c+h],m=s[o+h],g=f*d+h*2,p=u[g],x=u[g+1],_=e*d+h*2,y=l[_],v=l[_+1],E=uP(n,t,p,y,i);r[h]=ZT(E,b,x,v,m)}return r}};fi.prototype.ValueTypeName="";fi.prototype.TimeBufferType=Float32Array;fi.prototype.ValueBufferType=Float32Array;fi.prototype.DefaultInterpolation=2301;xs=class xs extends fi{constructor(e,t,n){super(e,t,n)}};xs.prototype.ValueTypeName="bool";xs.prototype.ValueBufferType=Array;xs.prototype.DefaultInterpolation=2300;xs.prototype.InterpolantFactoryMethodLinear=void 0;xs.prototype.InterpolantFactoryMethodSmooth=void 0;Fd=class Fd extends fi{constructor(e,t,n,i){super(e,t,n,i)}};Fd.prototype.ValueTypeName="color";ys=class ys extends fi{constructor(e,t,n,i){super(e,t,n,i)}};ys.prototype.ValueTypeName="number";Km=class Km extends Vr{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-t)/(i-t),c=e*a;for(let l=c+a;c!==l;c+=4)ln.slerpFlat(r,0,s,c-a,s,c,o);return r}};_s=class _s extends fi{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new Km(this.times,this.values,this.getValueSize(),e)}};_s.prototype.ValueTypeName="quaternion";_s.prototype.InterpolantFactoryMethodSmooth=void 0;vs=class vs extends fi{constructor(e,t,n){super(e,t,n)}};vs.prototype.ValueTypeName="string";vs.prototype.ValueBufferType=Array;vs.prototype.DefaultInterpolation=2300;vs.prototype.InterpolantFactoryMethodLinear=void 0;vs.prototype.InterpolantFactoryMethodSmooth=void 0;Ia=class Ia extends fi{constructor(e,t,n,i){super(e,t,n,i)}};Ia.prototype.ValueTypeName="vector";lr={enabled:!1,files:{},add:function(e,t){if(this.enabled===!1)return;if(KE(e))return;this.files[e]=t},get:function(e){if(this.enabled===!1)return;if(KE(e))return;return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};YT=new dl;jr.DEFAULT_MATERIAL_NAME="__DEFAULT";Fr={};QT=class QT extends Error{constructor(e,t){super(e);this.response=t}};fl=class fl extends jr{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=lr.get(`file:${e}`);if(r!==void 0){this.manager.itemStart(e),setTimeout(()=>{if(t)t(r);this.manager.itemEnd(e)},0);return}if(Fr[e]!==void 0){Fr[e].push({onLoad:t,onProgress:n,onError:i});return}Fr[e]=[],Fr[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}),a=this.mimeType,o=this.responseType;fetch(s).then((c)=>{if(c.status===200||c.status===0){if(c.status===0)je("FileLoader: HTTP Status 0 received.");if(typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;let l=Fr[e],u=c.body.getReader(),d=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),f=d?parseInt(d):0,h=f!==0,b=0,m=new ReadableStream({start(g){p();function p(){u.read().then(({done:x,value:_})=>{if(x)g.close();else{b+=_.byteLength;let y=new ProgressEvent("progress",{lengthComputable:h,loaded:b,total:f});for(let v=0,E=l.length;v<E;v++){let w=l[v];if(w.onProgress)w.onProgress(y)}g.enqueue(_),p()}},(x)=>{g.error(x)})}}});return new Response(m)}else throw new QT(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then((c)=>{switch(o){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then((l)=>new DOMParser().parseFromString(l,a));case"json":return c.json();default:if(a==="")return c.text();else{let u=/charset="?([^;"\s]*)"?/i.exec(a),d=u&&u[1]?u[1].toLowerCase():void 0,f=new TextDecoder(d);return c.arrayBuffer().then((h)=>f.decode(h))}}}).then((c)=>{lr.add(`file:${e}`,c);let l=Fr[e];delete Fr[e];for(let u=0,d=l.length;u<d;u++){let f=l[u];if(f.onLoad)f.onLoad(c)}}).catch((c)=>{let l=Fr[e];if(l===void 0)throw this.manager.itemError(e),c;delete Fr[e];for(let u=0,d=l.length;u<d;u++){let f=l[u];if(f.onError)f.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}};bo=new WeakMap;Wm=class Wm extends jr{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=lr.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=bo.get(s);if(u===void 0)u=[],bo.set(s,u);u.push({onLoad:t,onError:i})}return s}let a=vo("img");function o(){if(l(),t)t(this);let u=bo.get(this)||[];for(let d=0;d<u.length;d++){let f=u[d];if(f.onLoad)f.onLoad(this)}bo.delete(this),r.manager.itemEnd(e)}function c(u){if(l(),i)i(u);lr.remove(`image:${e}`);let d=bo.get(this)||[];for(let f=0;f<d.length;f++){let h=d[f];if(h.onError)h.onError(u)}bo.delete(this),r.manager.itemError(e),r.manager.itemEnd(e)}function l(){a.removeEventListener("load",o,!1),a.removeEventListener("error",c,!1)}if(a.addEventListener("load",o,!1),a.addEventListener("error",c,!1),e.slice(0,5)!=="data:"){if(this.crossOrigin!==void 0)a.crossOrigin=this.crossOrigin}return lr.add(`image:${e}`,a),r.manager.itemStart(e),a.src=e,a}};Lo=class Lo extends jr{constructor(e){super(e)}load(e,t,n,i){let r=new en,s=new Wm(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(a){if(r.image=a,r.needsUpdate=!0,t!==void 0)t(r)},n,i),r}};Fo=class Fo extends Dt{constructor(e,t=1){super();this.isLight=!0,this.type="Light",this.color=new qe(e),this.intensity=t}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}};Ud=class Ud extends Fo{constructor(e,t,n){super(e,n);this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Dt.DEFAULT_UP),this.updateMatrix(),this.groundColor=new qe(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}};Pp=new Je,WE=new j,XE=new j;cd=new j,ld=new ln,or=new j;Bd=class Bd extends Dt{constructor(){super();this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Je,this.projectionMatrix=new Je,this.projectionMatrixInverse=new Je,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(cd,ld,or),or.x===1&&or.y===1&&or.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(cd,ld,or.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){if(super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(cd,ld,or),or.x===1&&or.y===1&&or.z===1)this.matrixWorldInverse.copy(this.matrixWorld).invert();else this.matrixWorldInverse.compose(cd,ld,or.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}};os=new j,qE=new Ke,JE=new Ke;hn=class hn extends Bd{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=_a*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan($c*0.5*this.fov);return 0.5*this.getFilmHeight()/e}getEffectiveFOV(){return _a*2*Math.atan(Math.tan($c*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){os.set(-1,-1,0.5).applyMatrix4(this.projectionMatrixInverse),t.set(os.x,os.y).multiplyScalar(-e/os.z),os.set(1,1,0.5).applyMatrix4(this.projectionMatrixInverse),n.set(os.x,os.y).multiplyScalar(-e/os.z)}getViewSize(e,t){return this.getViewBounds(e,qE,JE),t.subVectors(JE,qE)}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($c*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:o,fullHeight:c}=s;r+=s.offsetX*i/o,t-=s.offsetY*n/c,i*=s.width/o,n*=s.height/c}let a=this.filmOffset;if(a!==0)r+=e*a/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}};eA=class eA extends hl{constructor(){super(new hn(50,1,0.5,500));this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=_a*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.aspect=e.aspect,this}toJSON(){let e=super.toJSON();return e.focus=this.focus,e.aspect=this.aspect,e}};zd=class zd extends Fo{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(Dt.DEFAULT_UP),this.updateMatrix(),this.target=new Dt,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new eA}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}};tA=class tA extends hl{constructor(){super(new hn(90,1,0.5,500));this.isPointLightShadow=!0}};Uo=class Uo extends Fo{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 tA}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}};Ca=class Ca extends Bd{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,a=i+t,o=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,a-=l*this.view.offsetY,o=a-l*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,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}};nA=class nA extends hl{constructor(){super(new Ca(-5,5,5,-5,0.5,500));this.isDirectionalLightShadow=!0}};Bo=class Bo extends Fo{constructor(e,t){super(e,t);this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Dt.DEFAULT_UP),this.updateMatrix(),this.target=new Dt,this.shadow=new nA}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}};Op=new WeakMap;Vd=class Vd extends jr{constructor(e){super(e);if(this.isImageBitmapLoader=!0,typeof createImageBitmap>"u")je("ImageBitmapLoader: createImageBitmap() not supported.");if(typeof fetch>"u")je("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=lr.get(`image-bitmap:${e}`);if(s!==void 0){if(r.manager.itemStart(e),s.then){s.then((c)=>{if(Op.has(s)===!0){if(i)i(Op.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 a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader,a.signal=typeof AbortSignal.any==="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let o=fetch(e,a).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign({},r.options,{colorSpaceConversion:"none"}))}).then(function(c){if(lr.add(`image-bitmap:${e}`,c),t)t(c);return r.manager.itemEnd(e),c}).catch(function(c){if(i)i(c);Op.set(o,c),lr.remove(`image-bitmap:${e}`),r.manager.itemError(e),r.manager.itemEnd(e)});lr.add(`image-bitmap:${e}`,o),r.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}};Xm=class Xm extends Dt{constructor(e,t,n){super();this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new hn(xo,yo,e,t);i.layers=this.layers,this.add(i);let r=new hn(xo,yo,e,t);r.layers=this.layers,this.add(r);let s=new hn(xo,yo,e,t);s.layers=this.layers,this.add(s);let a=new hn(xo,yo,e,t);a.layers=this.layers,this.add(a);let o=new hn(xo,yo,e,t);o.layers=this.layers,this.add(o);let c=new hn(xo,yo,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,a,o]=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),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.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),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.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,a,o,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),h=e.xr.enabled;e.xr.enabled=!1;let b=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let m=!1;if(e.isWebGLRenderer===!0)m=e.state.buffers.depth.getReversed();else m=e.reversedDepthBuffer;if(e.setRenderTarget(n,0,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,r),e.setRenderTarget(n,1,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,s),e.setRenderTarget(n,2,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,a),e.setRenderTarget(n,3,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,o),e.setRenderTarget(n,4,i),m&&e.autoClear===!1)e.clearDepth();if(e.render(t,c),n.texture.generateMipmaps=b,e.setRenderTarget(n,5,i),m&&e.autoClear===!1)e.clearDepth();e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=h,n.texture.needsPMREMUpdate=!0}};qm=class qm extends hn{constructor(e=[]){super();this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}};hP=new RegExp("["+Zm+"]","g"),Ym="[^"+Zm+"]",pP="[^"+Zm.replace("\\.","")+"]",mP=/((?:WC+[\/:])*)/.source.replace("WC",Ym),gP=/(WCOD+)?/.source.replace("WCOD",pP),bP=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Ym),xP=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Ym),yP=new RegExp("^"+mP+gP+bP+xP+"$"),_P=["material","materials","bones","map"];Tt.Composite=iA;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]];vP=new Float32Array(1);jd=class jd extends Vi{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:a}=e,o=n.uuid,c=this._bindingsByRootAndName,l=c[o];if(l===void 0)l={},c[o]=l;for(let u=0;u!==r;++u){let d=i[u],f=d.name,h=l[f];if(h!==void 0)++h.referenceCount,s[u]=h;else{if(h=s[u],h!==void 0){if(h._cacheIndex===null)++h.referenceCount,this._addInactiveBinding(h,o,f);continue}let b=t&&t._propertyBindings[u].binding.parsedPath;h=new Jm(Tt.create(n,f,b),d.ValueTypeName,d.getValueSize()),++h.referenceCount,this._addInactiveBinding(h,o,f),s[u]=h}a[u].resultBuffer=h.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 a=s.knownActions;e._byClipCacheIndex=a.length,a.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,a=s[r],o=a.knownActions,c=o[o.length-1],l=e._byClipCacheIndex;c._byClipCacheIndex=l,o[l]=c,o.pop(),e._byClipCacheIndex=null;let u=a.actionByRoot,d=(e._localRoot||this._root).uuid;if(delete u[d],o.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,a=s[i],o=t[t.length-1],c=e._cacheIndex;if(o._cacheIndex=c,t[c]=o,t.pop(),delete a[r],Object.keys(a).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 Ld(new Float32Array(2),new Float32Array(2),1,vP),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"?To.findByName(i,e):e,a=s!==null?s.uuid:e,o=this._actionsByClip[a],c=null;if(n===void 0)if(s!==null)n=s.blendMode;else n=2500;if(o!==void 0){let u=o.actionByRoot[r];if(u!==void 0&&u.blendMode===n)return u;if(c=o.knownActions[0],s===null)s=c._clip}if(s===null)return null;let l=new Qm(this,s,t,n);return this._bindAction(l,c),this._addInactiveAction(l,a,r),l}existingAction(e,t){let n=t||this._root,i=n.uuid,r=typeof e==="string"?To.findByName(n,e):e,s=r?r.uuid:e,a=this._actionsByClip[s];if(a!==void 0)return a.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 a=this._bindings,o=this._nActiveBindings;for(let c=0;c!==o;++c)a[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 a=0,o=s.length;a!==o;++a){let c=s[a];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 a=n[s].actionByRoot,o=a[t];if(o!==void 0)this._deactivateAction(o),this._removeInactiveAction(o)}let i=this._bindingsByRootAndName,r=i[t];if(r!==void 0)for(let s in r){let a=r[s];a.restoreOriginalState(),this._removeInactiveBinding(a)}}uncacheAction(e,t){let n=this.existingAction(e,t);if(n!==null)this._deactivateAction(n),this._removeInactiveAction(n)}};eg=class eg{static{eg.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}};Hd=class Hd extends Vi{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(this.domElement!==null)this.disconnect();this.domElement=e}disconnect(){}dispose(){}update(){}};if(typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"186"}}));if(typeof window<"u")if(window.__THREE__)je("WARNING: Multiple instances of Three.js being imported.");else window.__THREE__="186"});function wA(){let e=null,t=!1,n=null,i=null;function r(s,a){i=e.requestAnimationFrame(r),n(s,a)}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 TP(e){let t=new WeakMap;function n(o,c){let{array:l,usage:u}=o,d=l.byteLength,f=e.createBuffer();e.bindBuffer(c,f),e.bufferData(c,l,u),o.onUploadCallback();let h;if(l instanceof Float32Array)h=e.FLOAT;else if(typeof Float16Array<"u"&&l instanceof Float16Array)h=e.HALF_FLOAT;else if(l instanceof Uint16Array)if(o.isFloat16BufferAttribute)h=e.HALF_FLOAT;else h=e.UNSIGNED_SHORT;else if(l instanceof Int16Array)h=e.SHORT;else if(l instanceof Uint32Array)h=e.UNSIGNED_INT;else if(l instanceof Int32Array)h=e.INT;else if(l instanceof Int8Array)h=e.BYTE;else if(l instanceof Uint8Array)h=e.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)h=e.UNSIGNED_BYTE;else throw Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:f,type:h,bytesPerElement:l.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,c,l){let{array:u,updateRanges:d}=c;if(e.bindBuffer(l,o),d.length===0)e.bufferSubData(l,0,u);else{d.sort((h,b)=>h.start-b.start);let f=0;for(let h=1;h<d.length;h++){let b=d[f],m=d[h];if(m.start<=b.start+b.count+1)b.count=Math.max(b.count,m.start+m.count-b.start);else++f,d[f]=m}d.length=f+1;for(let h=0,b=d.length;h<b;h++){let m=d[h];e.bufferSubData(l,m.start*u.BYTES_PER_ELEMENT,u,m.start,m.count)}c.clearUpdateRanges()}c.onUploadCallback()}function r(o){if(o.isInterleavedBufferAttribute)o=o.data;return t.get(o)}function s(o){if(o.isInterleavedBufferAttribute)o=o.data;let c=t.get(o);if(c)e.deleteBuffer(c.buffer),t.delete(o)}function a(o,c){if(o.isInterleavedBufferAttribute)o=o.data;if(o.isGLBufferAttribute){let u=t.get(o);if(!u||u.version<o.version)t.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}let l=t.get(o);if(l===void 0)t.set(o,n(o,c));else if(l.version<o.version){if(l.size!==o.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,o,c),l.version=o.version}}return{get:r,remove:s,update:a}}function sD(e,t,n,i,r,s){let a=new qe(0),o=r===!0?0:1,c,l,u=null,d=0,f=null;function h(x){let _=x.isScene===!0?x.background:null;if(_&&_.isTexture){let y=x.backgroundBlurriness>0;_=t.get(_,y)}return _}function b(x){let _=!1,y=h(x);if(y===null)g(a,o);else if(y&&y.isColor)g(y,1),_=!0;let v=e.xr.getEnvironmentBlendMode();if(v==="additive")n.buffers.color.setClear(0,0,0,1,s);else if(v==="alpha-blend")n.buffers.color.setClear(0,0,0,0,s);if(e.autoClear||_)n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil)}function m(x,_){let y=h(_);if(y&&(y.isCubeTexture||y.mapping===Zc)){if(l===void 0)l=new jt(new bs(1,1,1),new Ei({name:"BackgroundCubeMaterial",uniforms:Ra(br.backgroundCube.uniforms),vertexShader:br.backgroundCube.vertexShader,fragmentShader:br.backgroundCube.fragmentShader,side:Dn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(v,E,w){this.matrixWorld.copyPosition(w.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(l);if(l.material.uniforms.envMap.value=y,l.material.uniforms.backgroundBlurriness.value=_.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(rD.makeRotationFromEuler(_.backgroundRotation)).transpose(),y.isCubeTexture&&y.isRenderTargetTexture===!1)l.material.uniforms.backgroundRotation.value.premultiply(SA);if(l.material.toneMapped=ot.getTransfer(y.colorSpace)!==Bt,u!==y||d!==y.version||f!==e.toneMapping)l.material.needsUpdate=!0,u=y,d=y.version,f=e.toneMapping;l.layers.enableAll(),x.unshift(l,l.geometry,l.material,0,0,null)}else if(y&&y.isTexture){if(c===void 0)c=new jt(new ul(2,2),new Ei({name:"BackgroundMaterial",uniforms:Ra(br.background.uniforms),vertexShader:br.background.vertexShader,fragmentShader:br.background.fragmentShader,side:fs,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=y,c.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,c.material.toneMapped=ot.getTransfer(y.colorSpace)!==Bt,y.matrixAutoUpdate===!0)y.updateMatrix();if(c.material.uniforms.uvTransform.value.copy(y.matrix),u!==y||d!==y.version||f!==e.toneMapping)c.material.needsUpdate=!0,u=y,d=y.version,f=e.toneMapping;c.layers.enableAll(),x.unshift(c,c.geometry,c.material,0,0,null)}}function g(x,_){x.getRGB(Gd,Bm(e)),n.buffers.color.setClear(Gd.r,Gd.g,Gd.b,_,s)}function p(){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 a},setClearColor:function(x,_=1){a.set(x),o=_,g(a,o)},getClearAlpha:function(){return o},setClearAlpha:function(x){o=x,g(a,o)},render:b,addToRenderList:m,dispose:p}}function aD(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=f(null),s=r,a=!1;function o(S,R,k,C,U){let L=!1,O=d(S,C,k,R);if(s!==O)s=O,l(s.object);if(L=h(S,C,k,U),L)b(S,C,k,U);if(U!==null)t.update(U,e.ELEMENT_ARRAY_BUFFER);if(L||a){if(a=!1,y(S,R,k,C),U!==null)e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(U).buffer)}}function c(){return e.createVertexArray()}function l(S){return e.bindVertexArray(S)}function u(S){return e.deleteVertexArray(S)}function d(S,R,k,C){let U=C.wireframe===!0,L=i[R.id];if(L===void 0)L={},i[R.id]=L;let O=S.isInstancedMesh===!0?S.id:0,K=L[O];if(K===void 0)K={},L[O]=K;let B=K[k.id];if(B===void 0)B={},K[k.id]=B;let X=B[U];if(X===void 0)X=f(c()),B[U]=X;return X}function f(S){let R=[],k=[],C=[];for(let U=0;U<n;U++)R[U]=0,k[U]=0,C[U]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:R,enabledAttributes:k,attributeDivisors:C,object:S,attributes:{},index:null}}function h(S,R,k,C){let U=s.attributes,L=R.attributes,O=0,K=k.getAttributes();for(let B in K)if(K[B].location>=0){let q=U[B],le=L[B];if(le===void 0){if(B==="instanceMatrix"&&S.instanceMatrix)le=S.instanceMatrix;if(B==="instanceColor"&&S.instanceColor)le=S.instanceColor}if(q===void 0)return!0;if(q.attribute!==le)return!0;if(le&&q.data!==le.data)return!0;O++}if(s.attributesNum!==O)return!0;if(s.index!==C)return!0;return!1}function b(S,R,k,C){let U={},L=R.attributes,O=0,K=k.getAttributes();for(let B in K)if(K[B].location>=0){let q=L[B];if(q===void 0){if(B==="instanceMatrix"&&S.instanceMatrix)q=S.instanceMatrix;if(B==="instanceColor"&&S.instanceColor)q=S.instanceColor}let le={};if(le.attribute=q,q&&q.data)le.data=q.data;U[B]=le,O++}s.attributes=U,s.attributesNum=O,s.index=C}function m(){let S=s.newAttributes;for(let R=0,k=S.length;R<k;R++)S[R]=0}function g(S){p(S,0)}function p(S,R){let k=s.newAttributes,C=s.enabledAttributes,U=s.attributeDivisors;if(k[S]=1,C[S]===0)e.enableVertexAttribArray(S),C[S]=1;if(U[S]!==R)e.vertexAttribDivisor(S,R),U[S]=R}function x(){let S=s.newAttributes,R=s.enabledAttributes;for(let k=0,C=R.length;k<C;k++)if(R[k]!==S[k])e.disableVertexAttribArray(k),R[k]=0}function _(S,R,k,C,U,L,O){if(O===!0)e.vertexAttribIPointer(S,R,k,U,L);else e.vertexAttribPointer(S,R,k,C,U,L)}function y(S,R,k,C){m();let U=C.attributes,L=k.getAttributes(),O=R.defaultAttributeValues;for(let K in L){let B=L[K];if(B.location>=0){let X=U[K];if(X===void 0){if(K==="instanceMatrix"&&S.instanceMatrix)X=S.instanceMatrix;if(K==="instanceColor"&&S.instanceColor)X=S.instanceColor}if(X!==void 0){let q=X.normalized,le=X.itemSize,de=t.get(X);if(de===void 0)continue;let{buffer:Me,type:pe,bytesPerElement:J}=de,F=pe===e.INT||pe===e.UNSIGNED_INT||X.gpuType===Kp;if(X.isInterleavedBufferAttribute){let W=X.data,ne=W.stride,ie=X.offset;if(W.isInstancedInterleavedBuffer){for(let ce=0;ce<B.locationSize;ce++)p(B.location+ce,W.meshPerAttribute);if(S.isInstancedMesh!==!0&&C._maxInstanceCount===void 0)C._maxInstanceCount=W.meshPerAttribute*W.count}else for(let ce=0;ce<B.locationSize;ce++)g(B.location+ce);e.bindBuffer(e.ARRAY_BUFFER,Me);for(let ce=0;ce<B.locationSize;ce++)_(B.location+ce,le/B.locationSize,pe,q,ne*J,(ie+le/B.locationSize*ce)*J,F)}else{if(X.isInstancedBufferAttribute){for(let W=0;W<B.locationSize;W++)p(B.location+W,X.meshPerAttribute);if(S.isInstancedMesh!==!0&&C._maxInstanceCount===void 0)C._maxInstanceCount=X.meshPerAttribute*X.count}else for(let W=0;W<B.locationSize;W++)g(B.location+W);e.bindBuffer(e.ARRAY_BUFFER,Me);for(let W=0;W<B.locationSize;W++)_(B.location+W,le/B.locationSize,pe,q,le*J,le/B.locationSize*W*J,F)}}else if(O!==void 0){let q=O[K];if(q!==void 0)switch(q.length){case 2:e.vertexAttrib2fv(B.location,q);break;case 3:e.vertexAttrib3fv(B.location,q);break;case 4:e.vertexAttrib4fv(B.location,q);break;default:e.vertexAttrib1fv(B.location,q)}}}}x()}function v(){A();for(let S in i){let R=i[S];for(let k in R){let C=R[k];for(let U in C){let L=C[U];for(let O in L)u(L[O].object),delete L[O];delete C[U]}}delete i[S]}}function E(S){if(i[S.id]===void 0)return;let R=i[S.id];for(let k in R){let C=R[k];for(let U in C){let L=C[U];for(let O in L)u(L[O].object),delete L[O];delete C[U]}}delete i[S.id]}function w(S){for(let R in i){let k=i[R];for(let C in k){let U=k[C];if(U[S.id]===void 0)continue;let L=U[S.id];for(let O in L)u(L[O].object),delete L[O];delete U[S.id]}}}function T(S){for(let R in i){let k=i[R],C=S.isInstancedMesh===!0?S.id:0,U=k[C];if(U===void 0)continue;for(let L in U){let O=U[L];for(let K in O)u(O[K].object),delete O[K];delete U[L]}if(delete k[C],Object.keys(k).length===0)delete i[R]}}function A(){if(P(),a=!0,s===r)return;s=r,l(s.object)}function P(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:o,reset:A,resetDefaultState:P,dispose:v,releaseStatesOfGeometry:E,releaseStatesOfObject:T,releaseStatesOfProgram:w,initAttributes:m,enableAttribute:g,disableUnusedAttributes:x}}function oD(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 a(c,l,u){if(u===0)return;e.drawArraysInstanced(i,c,l,u),n.update(l,i,u)}function o(c,l,u){if(u===0)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,c,0,l,0,u);let f=0;for(let h=0;h<u;h++)f+=l[h];n.update(f,i,1)}this.setMode=r,this.render=s,this.renderInstances=a,this.renderMultiDraw=o}function cD(e,t,n,i){let r;function s(){if(r!==void 0)return r;if(t.has("EXT_texture_filter_anisotropic")===!0){let w=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(w.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}function a(w){if(w!==pr&&i.convert(w)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))return!1;return!0}function o(w){let T=w===hr&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));if(w!==zi&&w!==Br&&!T&&i.convert(w)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))return!1;return!0}function c(w){if(w==="highp"){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";w="mediump"}if(w==="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)je("WebGLRenderer:",l,"not supported, using",u,"instead."),l=u;let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has("EXT_clip_control");if(n.reversedDepthBuffer===!0&&f===!1)je("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let h=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),b=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),p=e.getParameter(e.MAX_VERTEX_ATTRIBS),x=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),_=e.getParameter(e.MAX_VARYING_VECTORS),y=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),v=e.getParameter(e.MAX_SAMPLES),E=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:a,textureTypeReadable:o,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:h,maxVertexTextures:b,maxTextureSize:m,maxCubemapSize:g,maxAttributes:p,maxVertexUniforms:x,maxVaryings:_,maxFragmentUniforms:y,maxSamples:v,samples:E}}function lD(e){let t=this,n=null,i=0,r=!1,s=!1,a=new yi,o=new tt,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(d,f){let h=d.length!==0||f||i!==0||r;return r=f,i=d.length,h},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(d,f){n=u(d,f,0)},this.setState=function(d,f,h){let{clippingPlanes:b,clipIntersection:m,clipShadows:g}=d,p=e.get(d);if(!r||b===null||b.length===0||s&&!g)if(s)u(null);else l();else{let x=s?0:i,_=x*4,y=p.clippingState||null;c.value=y,y=u(b,f,_,h);for(let v=0;v!==_;++v)y[v]=n[v];p.clippingState=y,this.numIntersection=m?this.numPlanes:0,this.numPlanes+=x}};function l(){if(c.value!==n)c.value=n,c.needsUpdate=i>0;t.numPlanes=i,t.numIntersection=0}function u(d,f,h,b){let m=d!==null?d.length:0,g=null;if(m!==0){if(g=c.value,b!==!0||g===null){let p=h+m*4,x=f.matrixWorldInverse;if(o.getNormalMatrix(x),g===null||g.length<p)g=new Float32Array(p);for(let _=0,y=h;_!==m;++_,y+=4)a.copy(d[_]).applyMatrix4(x,o),a.normal.toArray(g,y),g[y+3]=a.constant}c.value=g,c.needsUpdate=!0}return t.numPlanes=m,t.numIntersection=0,g}}class yl{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=0.1,i=100,r={}){let{size:s=256,position:a=hD}=r;ig=this._renderer.getRenderTarget(),rg=this._renderer.getActiveCubeFace(),sg=this._renderer.getActiveMipmapLevel(),ag=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);let o=this._allocateTargets();if(o.depthBuffer=!0,this._sceneToCubeUV(e,n,i,o,a),t>0)this._blur(o,0,0,t);return this._applyPMREM(o),this._cleanup(o),o}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=oA(),this._compileMaterial(this._cubemapMaterial)}compileEquirectangularShader(){if(this._equirectMaterial===null)this._equirectMaterial=aA(),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(ig,rg,sg),this._renderer.xr.enabled=ag,e.scissorTest=!1,zo(e,0,0,e.width,e.height)}_fromTexture(e,t){if(e.mapping===So||e.mapping===va)this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width);else this._setSize(e.image.width/4);ig=this._renderer.getRenderTarget(),rg=this._renderer.getActiveCubeFace(),sg=this._renderer.getActiveMipmapLevel(),ag=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:Tn,minFilter:Tn,generateMipmaps:!1,type:hr,format:pr,colorSpace:ci,depthBuffer:!1},i=sA(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){if(this._pingPongRenderTarget!==null)this._dispose();this._pingPongRenderTarget=sA(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=pD(r)),this._blurMaterial=gD(r,e,t),this._ggxMaterial=mD(r,e,t)}return i}_compileMaterial(e){let t=new jt(new Ln,e);this._renderer.compile(t,ml)}_sceneToCubeUV(e,t,n,i,r){let o=new hn(90,1,t,n),c=[1,-1,1,1,1,1],l=[1,1,1,-1,-1,-1],u=this._renderer,{autoClear:d,toneMapping:f}=u;if(u.getClearColor(rA),u.toneMapping=Ui,u.autoClear=!1,u.state.buffers.depth.getReversed())u.setRenderTarget(i),u.clearDepth(),u.setRenderTarget(null);if(this._backgroundBox===null)this._backgroundBox=new jt(new bs,new mr({name:"PMREM.Background",side:Dn,depthWrite:!1,depthTest:!1}));let b=this._backgroundBox,m=b.material,g=!1,p=e.background;if(p){if(p.isColor)m.color.copy(p),e.background=null,g=!0}else m.color.copy(rA),g=!0;for(let x=0;x<6;x++){let _=x%3;if(_===0)o.up.set(0,c[x],0),o.position.set(r.x,r.y,r.z),o.lookAt(r.x+l[x],r.y,r.z);else if(_===1)o.up.set(0,0,c[x]),o.position.set(r.x,r.y,r.z),o.lookAt(r.x,r.y+l[x],r.z);else o.up.set(0,c[x],0),o.position.set(r.x,r.y,r.z),o.lookAt(r.x,r.y,r.z+l[x]);let y=this._cubeSize;if(zo(i,_*y,x>2?y:0,y,y),u.setRenderTarget(i),g)u.render(b,o);u.render(e,o)}u.toneMapping=f,u.autoClear=d,e.background=p}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===So||e.mapping===va;if(i){if(this._cubemapMaterial===null)this._cubemapMaterial=oA();this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1}else if(this._equirectMaterial===null)this._equirectMaterial=aA();let r=i?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=r;let a=r.uniforms;a.envMap.value=e;let o=this._cubeSize;zo(t,0,0,3*o,2*o),n.setRenderTarget(t),n.render(s,ml)}_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,a=this._lodMeshes[n];a.material=s;let o=s.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l),d=c*1.25,f=u*d,{_lodMax:h}=this,b=this._sizeLods[n],m=3*b*(n>h-Vo?n-h+Vo:0),g=4*(this._cubeSize-b);o.envMap.value=e.texture,o.roughness.value=f,o.mipInt.value=h-t,zo(r,m,g,3*b,2*b),i.setRenderTarget(r),i.render(a,ml),o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=h-n,zo(e,m,g,3*b,2*b),i.setRenderTarget(e),i.render(a,ml)}_blur(e,t,n,i){let r=this._pingPongRenderTarget,s=Math.min(i,Math.PI)/Math.SQRT2;this._blurPass(e,r,t,n,s),this._blurPass(r,e,n,n,s)}_blurPass(e,t,n,i,r){let s=this._renderer,a=this._blurMaterial,o=this._lodMeshes[i];o.material=a;let c=a.uniforms;c.envMap.value=e.texture,c.sigma.value=r,c.mipInt.value=this._lodMax-n;let l=this._sizeLods[i],u=3*l*(i>this._lodMax-Vo?i-this._lodMax+Vo:0),d=4*(this._cubeSize-l);zo(t,u,d,3*l,2*l),s.setRenderTarget(t),s.render(o,ml)}}function pD(e){let t=[],n=[],i=e,r=e-Vo+1+uD;for(let s=0;s<r;s++){let a=Math.pow(2,i);t.push(a);let o=1/(a-2),c=-o,l=1+o,u=[c,c,l,c,l,l,c,c,l,l,c,l],d=6,f=6,h=3,b=new Float32Array(h*f*d),m=new Float32Array(h*f*d);for(let p=0;p<d;p++){let x=p%3*2/3-1,_=p>2?0:-1,y=[x,_,0,x+0.6666666666666666,_,0,x+0.6666666666666666,_+1,0,x,_,0,x+0.6666666666666666,_+1,0,x,_+1,0];b.set(y,h*f*p);for(let v=0;v<f;v++){let E=u[v*2]*2-1,w=u[v*2+1]*2-1;if(p===0)Na.set(1,w,E);else if(p===1)Na.set(-E,1,-w);else if(p===2)Na.set(-E,w,1);else if(p===3)Na.set(-1,w,-E);else if(p===4)Na.set(-E,-1,w);else Na.set(E,w,-1);Na.toArray(m,(p*f+v)*h)}}let g=new Ln;if(g.setAttribute("position",new En(b,h)),g.setAttribute("outputDirection",new En(m,h)),n.push(new jt(g,null)),i>Vo)i--}return{lodMeshes:n,sizeLods:t}}function sA(e,t,n){let i=new li(e,t,n);return i.texture.mapping=Zc,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function zo(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function mD(e,t,n){return new Ei({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:fD,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:Kd(),fragmentShader:`precision highp float;precision highp int;@@ -110,7 +110,7 @@ ${Mn(o)}`)}`)He("manifest hash mismatch.");return structuredClone(e)}var jv="kilgl_FragColor = vec4(prefilteredColor, 1.0);}- `,blending:dr,depthTest:!1,depthWrite:!1})}function dD(e,t,n){return new Ei({name:"SphericalGaussianBlur",defines:{SAMPLES:aD,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},sigma:{value:0},mipInt:{value:0}},vertexShader:Hd(),fragmentShader:`+ `,blending:dr,depthTest:!1,depthWrite:!1})}function gD(e,t,n){return new Ei({name:"SphericalGaussianBlur",defines:{SAMPLES:dD,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},sigma:{value:0},mipInt:{value:0}},vertexShader:Kd(),fragmentShader:`precision highp float;precision highp int;@@ -170,7 +170,7 @@ ${Mn(o)}`)}`)He("manifest hash mismatch.");return structuredClone(e)}var jv="kilgl_FragColor = vec4( accumColor / accumWeight, 1.0 );}- `,blending:dr,depthTest:!1,depthWrite:!1})}function nA(){return new Ei({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Hd(),fragmentShader:`+ `,blending:dr,depthTest:!1,depthWrite:!1})}function aA(){return new Ei({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Kd(),fragmentShader:`precision mediump float;precision mediump int;@@ -189,7 +189,7 @@ ${Mn(o)}`)}`)He("manifest hash mismatch.");return structuredClone(e)}var jv="kilgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );}- `,blending:dr,depthTest:!1,depthWrite:!1})}function iA(){return new Ei({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Hd(),fragmentShader:`+ `,blending:dr,depthTest:!1,depthWrite:!1})}function oA(){return new Ei({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Kd(),fragmentShader:`precision mediump float;precision mediump int;@@ -205,7 +205,7 @@ ${Mn(o)}`)}`)He("manifest hash mismatch.");return structuredClone(e)}var jv="kilgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );}- `,blending:dr,depthTest:!1,depthWrite:!1})}function Hd(){return`+ `,blending:dr,depthTest:!1,depthWrite:!1})}function Kd(){return`precision mediump float;precision mediump int;@@ -220,7 +220,7 @@ ${Mn(o)}`)}`)He("manifest hash mismatch.");return structuredClone(e)}var jv="kilgl_Position = vec4( position, 1.0 );}- `}function fD(e){let t=new WeakMap,n=new WeakMap,i=null;function r(f,h=!1){if(f===null||f===void 0)return null;if(h)return a(f);return s(f)}function s(f){if(f&&f.isTexture){let h=f.mapping;if(h===ud||h===dd)if(t.has(f)){let b=t.get(f).texture;return o(b,f.mapping)}else{let b=f.image;if(b&&b.height>0){let m=new ag(b.height);return m.fromEquirectangularTexture(e,f),t.set(f,m),f.addEventListener("dispose",l),o(m.texture,f.mapping)}else return null}}return f}function a(f){if(f&&f.isTexture){let h=f.mapping,b=h===ud||h===dd,m=h===So||h===ya;if(b||m){let g=n.get(f),p=g!==void 0?g.texture.pmremVersion:0;if(f.isRenderTargetTexture&&f.pmremVersion!==p){if(i===null)i=new bl(e);return g=b?i.fromEquirectangular(f,g):i.fromCubemap(f,g),g.texture.pmremVersion=f.pmremVersion,n.set(f,g),g.texture}else if(g!==void 0)return g.texture;else{let x=f.image;if(b&&x&&x.height>0||m&&x&&c(x)){if(i===null)i=new bl(e);return g=b?i.fromEquirectangular(f):i.fromCubemap(f),g.texture.pmremVersion=f.pmremVersion,n.set(f,g),f.addEventListener("dispose",u),g.texture}else return null}}}return f}function o(f,h){if(h===ud)f.mapping=So;else if(h===dd)f.mapping=ya;return f}function c(f){let h=0,b=6;for(let m=0;m<b;m++)if(f[m]!==void 0)h++;return h===b}function l(f){let h=f.target;h.removeEventListener("dispose",l);let b=t.get(h);if(b!==void 0)t.delete(h),b.dispose()}function u(f){let h=f.target;h.removeEventListener("dispose",u);let b=n.get(h);if(b!==void 0)n.delete(h),b.dispose()}function d(){if(t=new WeakMap,n=new WeakMap,i!==null)i.dispose(),i=null}return{get:r,dispose:d}}function hD(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)ba("WebGLRenderer: "+i+" extension not supported.");return r}}}function pD(e,t,n,i){let r={},s=new WeakMap;function a(d){let f=d.target;if(f.index!==null)t.remove(f.index);for(let b in f.attributes)t.remove(f.attributes[b]);f.removeEventListener("dispose",a),delete r[f.id];let h=s.get(f);if(h)t.remove(h),s.delete(f);if(i.releaseStatesOfGeometry(f),f.isInstancedBufferGeometry===!0)delete f._maxInstanceCount;n.memory.geometries--}function o(d,f){if(r[f.id]===!0)return f;return f.addEventListener("dispose",a),r[f.id]=!0,n.memory.geometries++,f}function c(d){let f=d.attributes;for(let h in f)t.update(f[h],e.ARRAY_BUFFER)}function l(d){let f=[],h=d.index,b=d.attributes.position,m=0;if(b===void 0)return;if(h!==null){let x=h.array;m=h.version;for(let _=0,y=x.length;_<y;_+=3){let v=x[_+0],T=x[_+1],A=x[_+2];f.push(v,T,T,A,A,v)}}else{let x=b.array;m=b.version;for(let _=0,y=x.length/3-1;_<y;_+=3){let v=_+0,T=_+1,A=_+2;f.push(v,T,T,A,A,v)}}let g=new(b.count>=65535?Sd:wd)(f,1);g.version=m;let p=s.get(d);if(p)t.remove(p);s.set(d,g)}function u(d){let f=s.get(d);if(f){let h=d.index;if(h!==null){if(f.version<h.version)l(d)}}else l(d);return s.get(d)}return{get:o,update:c,getWireframeAttribute:u}}function mD(e,t,n){let i;function r(d){i=d}let s,a;function o(d){s=d.type,a=d.bytesPerElement}function c(d,f){e.drawElements(i,f,s,d*a),n.update(f,i,1)}function l(d,f,h){if(h===0)return;e.drawElementsInstanced(i,f,s,d*a,h),n.update(f,i,h)}function u(d,f,h){if(h===0)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,f,0,s,d,0,h);let m=0;for(let g=0;g<h;g++)m+=f[g];n.update(m,i,1)}this.setMode=r,this.setIndex=o,this.render=c,this.renderInstances=l,this.renderMultiDraw=u}function gD(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function i(s,a,o){switch(n.calls++,a){case e.TRIANGLES:n.triangles+=o*(s/3);break;case e.LINES:n.lines+=o*(s/2);break;case e.LINE_STRIP:n.lines+=o*(s-1);break;case e.LINE_LOOP:n.lines+=o*s;break;case e.POINTS:n.points+=o*s;break;default:Ze("WebGLInfo: Unknown draw mode:",a);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 bD(e,t,n){let i=new WeakMap,r=new Pt;function s(a,o,c){let l=a.morphTargetInfluences,u=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,d=u!==void 0?u.length:0,f=i.get(o);if(f===void 0||f.count!==d){let w=function(){A.dispose(),i.delete(o),o.removeEventListener("dispose",w)};if(f!==void 0)f.texture.dispose();let h=o.morphAttributes.position!==void 0,b=o.morphAttributes.normal!==void 0,m=o.morphAttributes.color!==void 0,g=o.morphAttributes.position||[],p=o.morphAttributes.normal||[],x=o.morphAttributes.color||[],_=0;if(h===!0)_=1;if(b===!0)_=2;if(m===!0)_=3;let y=o.attributes.position.count*_,v=1;if(y>t.maxTextureSize)v=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize;let T=new Float32Array(y*v*4*d),A=new Td(T,y,v,d);A.type=Br,A.needsUpdate=!0;let E=_*4;for(let P=0;P<d;P++){let S=g[P],I=p[P],U=x[P],N=y*v*4*P;for(let F=0;F<S.count;F++){let D=F*E;if(h===!0)r.fromBufferAttribute(S,F),T[N+D+0]=r.x,T[N+D+1]=r.y,T[N+D+2]=r.z,T[N+D+3]=0;if(b===!0)r.fromBufferAttribute(I,F),T[N+D+4]=r.x,T[N+D+5]=r.y,T[N+D+6]=r.z,T[N+D+7]=0;if(m===!0)r.fromBufferAttribute(U,F),T[N+D+8]=r.x,T[N+D+9]=r.y,T[N+D+10]=r.z,T[N+D+11]=U.itemSize===4?r.w:1}}f={count:d,texture:A,size:new Ke(y,v)},i.set(o,f),o.addEventListener("dispose",w)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)c.getUniforms().setValue(e,"morphTexture",a.morphTexture,n);else{let h=0;for(let m=0;m<l.length;m++)h+=l[m];let b=o.morphTargetsRelative?1:1-h;c.getUniforms().setValue(e,"morphTargetBaseInfluence",b),c.getUniforms().setValue(e,"morphTargetInfluences",l)}c.getUniforms().setValue(e,"morphTargetsTexture",f.texture,n),c.getUniforms().setValue(e,"morphTargetsTextureSize",f.size)}return{update:s}}function xD(e,t,n,i,r){let s=new WeakMap;function a(l){let u=r.render.frame,d=l.geometry,f=t.get(l,d);if(s.get(f)!==u)t.update(f),s.set(f,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 h=l.skeleton;if(s.get(h)!==u)h.update(),s.set(h,u)}return f}function o(){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:a,dispose:o}}function _D(e,t,n,i,r,s){let a=new ci(t,n,{type:e,depthBuffer:r,stencilBuffer:s,samples:i?4:0,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),o=null,c=null,l=new Dn;l.setAttribute("position",new Wn([-1,3,0,-1,-1,0,3,-1,0],3)),l.setAttribute("uv",new Wn([0,2,0,0,2,0],2));let u=new Dm({uniforms:{tDiffuse:{value:null}},vertexShader:`+ `}function bD(e){let t=new WeakMap,n=new WeakMap,i=null;function r(f,h=!1){if(f===null||f===void 0)return null;if(h)return a(f);return s(f)}function s(f){if(f&&f.isTexture){let h=f.mapping;if(h===hd||h===pd)if(t.has(f)){let b=t.get(f).texture;return o(b,f.mapping)}else{let b=f.image;if(b&&b.height>0){let m=new dg(b.height);return m.fromEquirectangularTexture(e,f),t.set(f,m),f.addEventListener("dispose",l),o(m.texture,f.mapping)}else return null}}return f}function a(f){if(f&&f.isTexture){let h=f.mapping,b=h===hd||h===pd,m=h===So||h===va;if(b||m){let g=n.get(f),p=g!==void 0?g.texture.pmremVersion:0;if(f.isRenderTargetTexture&&f.pmremVersion!==p){if(i===null)i=new yl(e);return g=b?i.fromEquirectangular(f,g):i.fromCubemap(f,g),g.texture.pmremVersion=f.pmremVersion,n.set(f,g),g.texture}else if(g!==void 0)return g.texture;else{let x=f.image;if(b&&x&&x.height>0||m&&x&&c(x)){if(i===null)i=new yl(e);return g=b?i.fromEquirectangular(f):i.fromCubemap(f),g.texture.pmremVersion=f.pmremVersion,n.set(f,g),f.addEventListener("dispose",u),g.texture}else return null}}}return f}function o(f,h){if(h===hd)f.mapping=So;else if(h===pd)f.mapping=va;return f}function c(f){let h=0,b=6;for(let m=0;m<b;m++)if(f[m]!==void 0)h++;return h===b}function l(f){let h=f.target;h.removeEventListener("dispose",l);let b=t.get(h);if(b!==void 0)t.delete(h),b.dispose()}function u(f){let h=f.target;h.removeEventListener("dispose",u);let b=n.get(h);if(b!==void 0)n.delete(h),b.dispose()}function d(){if(t=new WeakMap,n=new WeakMap,i!==null)i.dispose(),i=null}return{get:r,dispose:d}}function xD(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)ya("WebGLRenderer: "+i+" extension not supported.");return r}}}function yD(e,t,n,i){let r={},s=new WeakMap;function a(d){let f=d.target;if(f.index!==null)t.remove(f.index);for(let b in f.attributes)t.remove(f.attributes[b]);f.removeEventListener("dispose",a),delete r[f.id];let h=s.get(f);if(h)t.remove(h),s.delete(f);if(i.releaseStatesOfGeometry(f),f.isInstancedBufferGeometry===!0)delete f._maxInstanceCount;n.memory.geometries--}function o(d,f){if(r[f.id]===!0)return f;return f.addEventListener("dispose",a),r[f.id]=!0,n.memory.geometries++,f}function c(d){let f=d.attributes;for(let h in f)t.update(f[h],e.ARRAY_BUFFER)}function l(d){let f=[],h=d.index,b=d.attributes.position,m=0;if(b===void 0)return;if(h!==null){let x=h.array;m=h.version;for(let _=0,y=x.length;_<y;_+=3){let v=x[_+0],E=x[_+1],w=x[_+2];f.push(v,E,E,w,w,v)}}else{let x=b.array;m=b.version;for(let _=0,y=x.length/3-1;_<y;_+=3){let v=_+0,E=_+1,w=_+2;f.push(v,E,E,w,w,v)}}let g=new(b.count>=65535?Id:Rd)(f,1);g.version=m;let p=s.get(d);if(p)t.remove(p);s.set(d,g)}function u(d){let f=s.get(d);if(f){let h=d.index;if(h!==null){if(f.version<h.version)l(d)}}else l(d);return s.get(d)}return{get:o,update:c,getWireframeAttribute:u}}function _D(e,t,n){let i;function r(d){i=d}let s,a;function o(d){s=d.type,a=d.bytesPerElement}function c(d,f){e.drawElements(i,f,s,d*a),n.update(f,i,1)}function l(d,f,h){if(h===0)return;e.drawElementsInstanced(i,f,s,d*a,h),n.update(f,i,h)}function u(d,f,h){if(h===0)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,f,0,s,d,0,h);let m=0;for(let g=0;g<h;g++)m+=f[g];n.update(m,i,1)}this.setMode=r,this.setIndex=o,this.render=c,this.renderInstances=l,this.renderMultiDraw=u}function vD(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function i(s,a,o){switch(n.calls++,a){case e.TRIANGLES:n.triangles+=o*(s/3);break;case e.LINES:n.lines+=o*(s/2);break;case e.LINE_STRIP:n.lines+=o*(s-1);break;case e.LINE_LOOP:n.lines+=o*s;break;case e.POINTS:n.points+=o*s;break;default:Ye("WebGLInfo: Unknown draw mode:",a);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 ED(e,t,n){let i=new WeakMap,r=new Pt;function s(a,o,c){let l=a.morphTargetInfluences,u=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,d=u!==void 0?u.length:0,f=i.get(o);if(f===void 0||f.count!==d){let A=function(){w.dispose(),i.delete(o),o.removeEventListener("dispose",A)};if(f!==void 0)f.texture.dispose();let h=o.morphAttributes.position!==void 0,b=o.morphAttributes.normal!==void 0,m=o.morphAttributes.color!==void 0,g=o.morphAttributes.position||[],p=o.morphAttributes.normal||[],x=o.morphAttributes.color||[],_=0;if(h===!0)_=1;if(b===!0)_=2;if(m===!0)_=3;let y=o.attributes.position.count*_,v=1;if(y>t.maxTextureSize)v=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize;let E=new Float32Array(y*v*4*d),w=new Sd(E,y,v,d);w.type=Br,w.needsUpdate=!0;let T=_*4;for(let P=0;P<d;P++){let S=g[P],R=p[P],k=x[P],C=y*v*4*P;for(let U=0;U<S.count;U++){let L=U*T;if(h===!0)r.fromBufferAttribute(S,U),E[C+L+0]=r.x,E[C+L+1]=r.y,E[C+L+2]=r.z,E[C+L+3]=0;if(b===!0)r.fromBufferAttribute(R,U),E[C+L+4]=r.x,E[C+L+5]=r.y,E[C+L+6]=r.z,E[C+L+7]=0;if(m===!0)r.fromBufferAttribute(k,U),E[C+L+8]=r.x,E[C+L+9]=r.y,E[C+L+10]=r.z,E[C+L+11]=k.itemSize===4?r.w:1}}f={count:d,texture:w,size:new Ke(y,v)},i.set(o,f),o.addEventListener("dispose",A)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)c.getUniforms().setValue(e,"morphTexture",a.morphTexture,n);else{let h=0;for(let m=0;m<l.length;m++)h+=l[m];let b=o.morphTargetsRelative?1:1-h;c.getUniforms().setValue(e,"morphTargetBaseInfluence",b),c.getUniforms().setValue(e,"morphTargetInfluences",l)}c.getUniforms().setValue(e,"morphTargetsTexture",f.texture,n),c.getUniforms().setValue(e,"morphTargetsTextureSize",f.size)}return{update:s}}function TD(e,t,n,i,r){let s=new WeakMap;function a(l){let u=r.render.frame,d=l.geometry,f=t.get(l,d);if(s.get(f)!==u)t.update(f),s.set(f,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 h=l.skeleton;if(s.get(h)!==u)h.update(),s.set(h,u)}return f}function o(){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:a,dispose:o}}function wD(e,t,n,i,r,s){let a=new li(t,n,{type:e,depthBuffer:r,stencilBuffer:s,samples:i?4:0,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),o=null,c=null,l=new Ln;l.setAttribute("position",new Xn([-1,3,0,-1,-1,0,3,-1,0],3)),l.setAttribute("uv",new Xn([0,2,0,0,2,0],2));let u=new zm({uniforms:{tDiffuse:{value:null}},vertexShader:`precision highp float;uniform mat4 modelViewMatrix;@@ -266,17 +266,17 @@ ${Mn(o)}`)}`)He("manifest hash mismatch.");return structuredClone(e)}var jv="kil#ifdef SRGB_TRANSFERgl_FragColor = sRGBTransferOETF( gl_FragColor );#endif- }`,depthTest:!1,depthWrite:!1}),d=new jt(l,u),f=new Ra(-1,1,1,-1,0,1),h=null,b=null,m=!1,g,p=null,x=[],_=!1;this.setSize=function(y,v){if(a.setSize(y,v),o!==null)o.setSize(y,v);if(c!==null)c.setSize(y,v);for(let T=0;T<x.length;T++){let A=x[T];if(A.setSize)A.setSize(y,v)}},this.setEffects=function(y){x=y,_=x.length>0&&x[0].isRenderPass===!0;let{width:v,height:T}=a;if(x.length>0&&o===null)o=new ci(v,T,{type:hr,depthBuffer:!1,stencilBuffer:!1}),c=new ci(v,T,{type:hr,depthBuffer:!1,stencilBuffer:!1});for(let A=0;A<x.length;A++){let E=x[A];if(E.setSize)E.setSize(v,T)}},this.begin=function(y,v){if(m)return!1;if(y.toneMapping===Ui&&x.length===0)return!1;if(p=v,v!==null){let{width:T,height:A}=v;if(a.width!==T||a.height!==A)this.setSize(T,A)}if(_===!1)y.setRenderTarget(a);return g=y.toneMapping,y.toneMapping=Ui,!0},this.hasRenderPass=function(){return _},this.end=function(y,v){y.toneMapping=g,m=!0;let T=a,A=o;for(let E=0;E<x.length;E++){let w=x[E];if(w.enabled===!1)continue;if(w.render(y,A,T,v),w.needsSwap!==!1)T=A,A=A===o?c:o}if(h!==y.outputColorSpace||b!==y.toneMapping){if(h=y.outputColorSpace,b=y.toneMapping,u.defines={},ot.getTransfer(h)===Bt)u.defines.SRGB_TRANSFER="";let E=yD[b];if(E)u.defines[E]="";u.needsUpdate=!0}u.uniforms.tDiffuse.value=T.texture,y.setRenderTarget(p),y.render(d,f),p=null,m=!1},this.isCompositing=function(){return m},this.dispose=function(){if(a.dispose(),o!==null)o.dispose();if(c!==null)c.dispose();l.dispose(),u.dispose()}}function jo(e,t,n){let i=e[0];if(i<=0||i>0)return e;let r=t*n,s=rA[r];if(s===void 0)s=new Float32Array(r),rA[r]=s;if(t!==0){i.toArray(s,0);for(let a=1,o=0;a!==t;++a)o+=n,e[a].toArray(s,o)}return s}function pn(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 mn(e,t){for(let n=0,i=t.length;n<i;n++)e[n]=t[n]}function Gd(e,t){let n=sA[t];if(n===void 0)n=new Int32Array(t),sA[t]=n;for(let i=0;i!==t;++i)n[i]=e.allocateTextureUnit();return n}function vD(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1f(this.addr,t),n[0]=t}function ED(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(pn(n,t))return;e.uniform2fv(this.addr,t),mn(n,t)}}function TD(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(pn(n,t))return;e.uniform3fv(this.addr,t),mn(n,t)}}function AD(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(pn(n,t))return;e.uniform4fv(this.addr,t),mn(n,t)}}function wD(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(pn(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),mn(n,t)}else{if(pn(n,i))return;cA.set(i),e.uniformMatrix2fv(this.addr,!1,cA),mn(n,i)}}function SD(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(pn(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),mn(n,t)}else{if(pn(n,i))return;oA.set(i),e.uniformMatrix3fv(this.addr,!1,oA),mn(n,i)}}function MD(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(pn(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),mn(n,t)}else{if(pn(n,i))return;aA.set(i),e.uniformMatrix4fv(this.addr,!1,aA),mn(n,i)}}function RD(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1i(this.addr,t),n[0]=t}function ID(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(pn(n,t))return;e.uniform2iv(this.addr,t),mn(n,t)}}function CD(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(pn(n,t))return;e.uniform3iv(this.addr,t),mn(n,t)}}function ND(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(pn(n,t))return;e.uniform4iv(this.addr,t),mn(n,t)}}function PD(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1ui(this.addr,t),n[0]=t}function OD(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(pn(n,t))return;e.uniform2uiv(this.addr,t),mn(n,t)}}function kD(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(pn(n,t))return;e.uniform3uiv(this.addr,t),mn(n,t)}}function DD(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(pn(n,t))return;e.uniform4uiv(this.addr,t),mn(n,t)}}function LD(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)rg.compareFunction=n.isReversedDepthBuffer()?Ed:vd,s=rg;else s=TA;n.setTexture2D(t||s,r)}function FD(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||wA,r)}function UD(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||SA,r)}function BD(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||AA,r)}function zD(e){switch(e){case 5126:return vD;case 35664:return ED;case 35665:return TD;case 35666:return AD;case 35674:return wD;case 35675:return SD;case 35676:return MD;case 5124:case 35670:return RD;case 35667:case 35671:return ID;case 35668:case 35672:return CD;case 35669:case 35673:return ND;case 5125:return PD;case 36294:return OD;case 36295:return kD;case 36296:return DD;case 35678:case 36198:case 36298:case 36306:case 35682:return LD;case 35679:case 36299:case 36307:return FD;case 35680:case 36300:case 36308:case 36293:return UD;case 36289:case 36303:case 36311:case 36292:return BD}}function VD(e,t){e.uniform1fv(this.addr,t)}function jD(e,t){let n=jo(t,this.size,2);e.uniform2fv(this.addr,n)}function HD(e,t){let n=jo(t,this.size,3);e.uniform3fv(this.addr,n)}function GD(e,t){let n=jo(t,this.size,4);e.uniform4fv(this.addr,n)}function $D(e,t){let n=jo(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function KD(e,t){let n=jo(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function WD(e,t){let n=jo(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function XD(e,t){e.uniform1iv(this.addr,t)}function qD(e,t){e.uniform2iv(this.addr,t)}function JD(e,t){e.uniform3iv(this.addr,t)}function ZD(e,t){e.uniform4iv(this.addr,t)}function YD(e,t){e.uniform1uiv(this.addr,t)}function QD(e,t){e.uniform2uiv(this.addr,t)}function eL(e,t){e.uniform3uiv(this.addr,t)}function tL(e,t){e.uniform4uiv(this.addr,t)}function nL(e,t,n){let i=this.cache,r=t.length,s=Gd(n,r);if(!pn(i,s))e.uniform1iv(this.addr,s),mn(i,s);let a;if(this.type===e.SAMPLER_2D_SHADOW)a=rg;else a=TA;for(let o=0;o!==r;++o)n.setTexture2D(t[o]||a,s[o])}function iL(e,t,n){let i=this.cache,r=t.length,s=Gd(n,r);if(!pn(i,s))e.uniform1iv(this.addr,s),mn(i,s);for(let a=0;a!==r;++a)n.setTexture3D(t[a]||wA,s[a])}function rL(e,t,n){let i=this.cache,r=t.length,s=Gd(n,r);if(!pn(i,s))e.uniform1iv(this.addr,s),mn(i,s);for(let a=0;a!==r;++a)n.setTextureCube(t[a]||SA,s[a])}function sL(e,t,n){let i=this.cache,r=t.length,s=Gd(n,r);if(!pn(i,s))e.uniform1iv(this.addr,s),mn(i,s);for(let a=0;a!==r;++a)n.setTexture2DArray(t[a]||AA,s[a])}function aL(e){switch(e){case 5126:return VD;case 35664:return jD;case 35665:return HD;case 35666:return GD;case 35674:return $D;case 35675:return KD;case 35676:return WD;case 5124:case 35670:return XD;case 35667:case 35671:return qD;case 35668:case 35672:return JD;case 35669:case 35673:return ZD;case 5125:return YD;case 36294:return QD;case 36295:return eL;case 36296:return tL;case 35678:case 36198:case 36298:case 36306:case 35682:return nL;case 35679:case 36299:case 36307:return iL;case 35680:case 36300:case 36308:case 36293:return rL;case 36289:case 36303:case 36311:case 36292:return sL}}class MA{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=zD(t.type)}}class RA{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=aL(t.type)}}class IA{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 a=i[r];a.setValue(e,t[a.id],n)}}}function lA(e,t){e.seq.push(t),e.map[t.id]=t}function oL(e,t,n){let i=e.name,r=i.length;ng.lastIndex=0;while(!0){let s=ng.exec(i),a=ng.lastIndex,o=s[1],c=s[2]==="]",l=s[3];if(c)o=o|0;if(l===void 0||l==="["&&a+2===r){lA(n,l===void 0?new MA(o,e,t):new RA(o,e,t));break}else{let d=n.map[o];if(d===void 0)d=new IA(o),lA(n,d);n=d}}}class gl{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let s=0;s<n;++s){let a=e.getActiveUniform(t,s),o=e.getUniformLocation(t,a.name);oL(a,o,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 a=t[r],o=n[a.id];if(o.needsUpdate!==!1)a.setValue(e,o.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 uA(e,t,n){let i=e.createShader(t);return e.shaderSource(i,n),e.compileShader(i),i}function uL(e,t){let n=e.split(`+ }`,depthTest:!1,depthWrite:!1}),d=new jt(l,u),f=new Ca(-1,1,1,-1,0,1),h=null,b=null,m=!1,g,p=null,x=[],_=!1;this.setSize=function(y,v){if(a.setSize(y,v),o!==null)o.setSize(y,v);if(c!==null)c.setSize(y,v);for(let E=0;E<x.length;E++){let w=x[E];if(w.setSize)w.setSize(y,v)}},this.setEffects=function(y){x=y,_=x.length>0&&x[0].isRenderPass===!0;let{width:v,height:E}=a;if(x.length>0&&o===null)o=new li(v,E,{type:hr,depthBuffer:!1,stencilBuffer:!1}),c=new li(v,E,{type:hr,depthBuffer:!1,stencilBuffer:!1});for(let w=0;w<x.length;w++){let T=x[w];if(T.setSize)T.setSize(v,E)}},this.begin=function(y,v){if(m)return!1;if(y.toneMapping===Ui&&x.length===0)return!1;if(p=v,v!==null){let{width:E,height:w}=v;if(a.width!==E||a.height!==w)this.setSize(E,w)}if(_===!1)y.setRenderTarget(a);return g=y.toneMapping,y.toneMapping=Ui,!0},this.hasRenderPass=function(){return _},this.end=function(y,v){y.toneMapping=g,m=!0;let E=a,w=o;for(let T=0;T<x.length;T++){let A=x[T];if(A.enabled===!1)continue;if(A.render(y,w,E,v),A.needsSwap!==!1)E=w,w=w===o?c:o}if(h!==y.outputColorSpace||b!==y.toneMapping){if(h=y.outputColorSpace,b=y.toneMapping,u.defines={},ot.getTransfer(h)===Bt)u.defines.SRGB_TRANSFER="";let T=AD[b];if(T)u.defines[T]="";u.needsUpdate=!0}u.uniforms.tDiffuse.value=E.texture,y.setRenderTarget(p),y.render(d,f),p=null,m=!1},this.isCompositing=function(){return m},this.dispose=function(){if(a.dispose(),o!==null)o.dispose();if(c!==null)c.dispose();l.dispose(),u.dispose()}}function jo(e,t,n){let i=e[0];if(i<=0||i>0)return e;let r=t*n,s=cA[r];if(s===void 0)s=new Float32Array(r),cA[r]=s;if(t!==0){i.toArray(s,0);for(let a=1,o=0;a!==t;++a)o+=n,e[a].toArray(s,o)}return s}function mn(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 gn(e,t){for(let n=0,i=t.length;n<i;n++)e[n]=t[n]}function Wd(e,t){let n=lA[t];if(n===void 0)n=new Int32Array(t),lA[t]=n;for(let i=0;i!==t;++i)n[i]=e.allocateTextureUnit();return n}function SD(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1f(this.addr,t),n[0]=t}function MD(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(mn(n,t))return;e.uniform2fv(this.addr,t),gn(n,t)}}function RD(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(mn(n,t))return;e.uniform3fv(this.addr,t),gn(n,t)}}function ID(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(mn(n,t))return;e.uniform4fv(this.addr,t),gn(n,t)}}function CD(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(mn(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),gn(n,t)}else{if(mn(n,i))return;fA.set(i),e.uniformMatrix2fv(this.addr,!1,fA),gn(n,i)}}function ND(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(mn(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),gn(n,t)}else{if(mn(n,i))return;dA.set(i),e.uniformMatrix3fv(this.addr,!1,dA),gn(n,i)}}function PD(e,t){let n=this.cache,i=t.elements;if(i===void 0){if(mn(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),gn(n,t)}else{if(mn(n,i))return;uA.set(i),e.uniformMatrix4fv(this.addr,!1,uA),gn(n,i)}}function OD(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1i(this.addr,t),n[0]=t}function kD(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(mn(n,t))return;e.uniform2iv(this.addr,t),gn(n,t)}}function DD(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(mn(n,t))return;e.uniform3iv(this.addr,t),gn(n,t)}}function LD(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(mn(n,t))return;e.uniform4iv(this.addr,t),gn(n,t)}}function FD(e,t){let n=this.cache;if(n[0]===t)return;e.uniform1ui(this.addr,t),n[0]=t}function UD(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(mn(n,t))return;e.uniform2uiv(this.addr,t),gn(n,t)}}function BD(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(mn(n,t))return;e.uniform3uiv(this.addr,t),gn(n,t)}}function zD(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(mn(n,t))return;e.uniform4uiv(this.addr,t),gn(n,t)}}function VD(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)lg.compareFunction=n.isReversedDepthBuffer()?wd:Ad,s=lg;else s=MA;n.setTexture2D(t||s,r)}function jD(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||IA,r)}function HD(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||CA,r)}function GD(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||RA,r)}function $D(e){switch(e){case 5126:return SD;case 35664:return MD;case 35665:return RD;case 35666:return ID;case 35674:return CD;case 35675:return ND;case 35676:return PD;case 5124:case 35670:return OD;case 35667:case 35671:return kD;case 35668:case 35672:return DD;case 35669:case 35673:return LD;case 5125:return FD;case 36294:return UD;case 36295:return BD;case 36296:return zD;case 35678:case 36198:case 36298:case 36306:case 35682:return VD;case 35679:case 36299:case 36307:return jD;case 35680:case 36300:case 36308:case 36293:return HD;case 36289:case 36303:case 36311:case 36292:return GD}}function KD(e,t){e.uniform1fv(this.addr,t)}function WD(e,t){let n=jo(t,this.size,2);e.uniform2fv(this.addr,n)}function XD(e,t){let n=jo(t,this.size,3);e.uniform3fv(this.addr,n)}function qD(e,t){let n=jo(t,this.size,4);e.uniform4fv(this.addr,n)}function JD(e,t){let n=jo(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function ZD(e,t){let n=jo(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function YD(e,t){let n=jo(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function QD(e,t){e.uniform1iv(this.addr,t)}function eL(e,t){e.uniform2iv(this.addr,t)}function tL(e,t){e.uniform3iv(this.addr,t)}function nL(e,t){e.uniform4iv(this.addr,t)}function iL(e,t){e.uniform1uiv(this.addr,t)}function rL(e,t){e.uniform2uiv(this.addr,t)}function sL(e,t){e.uniform3uiv(this.addr,t)}function aL(e,t){e.uniform4uiv(this.addr,t)}function oL(e,t,n){let i=this.cache,r=t.length,s=Wd(n,r);if(!mn(i,s))e.uniform1iv(this.addr,s),gn(i,s);let a;if(this.type===e.SAMPLER_2D_SHADOW)a=lg;else a=MA;for(let o=0;o!==r;++o)n.setTexture2D(t[o]||a,s[o])}function cL(e,t,n){let i=this.cache,r=t.length,s=Wd(n,r);if(!mn(i,s))e.uniform1iv(this.addr,s),gn(i,s);for(let a=0;a!==r;++a)n.setTexture3D(t[a]||IA,s[a])}function lL(e,t,n){let i=this.cache,r=t.length,s=Wd(n,r);if(!mn(i,s))e.uniform1iv(this.addr,s),gn(i,s);for(let a=0;a!==r;++a)n.setTextureCube(t[a]||CA,s[a])}function uL(e,t,n){let i=this.cache,r=t.length,s=Wd(n,r);if(!mn(i,s))e.uniform1iv(this.addr,s),gn(i,s);for(let a=0;a!==r;++a)n.setTexture2DArray(t[a]||RA,s[a])}function dL(e){switch(e){case 5126:return KD;case 35664:return WD;case 35665:return XD;case 35666:return qD;case 35674:return JD;case 35675:return ZD;case 35676:return YD;case 5124:case 35670:return QD;case 35667:case 35671:return eL;case 35668:case 35672:return tL;case 35669:case 35673:return nL;case 5125:return iL;case 36294:return rL;case 36295:return sL;case 36296:return aL;case 35678:case 36198:case 36298:case 36306:case 35682:return oL;case 35679:case 36299:case 36307:return cL;case 35680:case 36300:case 36308:case 36293:return lL;case 36289:case 36303:case 36311:case 36292:return uL}}class NA{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=$D(t.type)}}class PA{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=dL(t.type)}}class OA{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 a=i[r];a.setValue(e,t[a.id],n)}}}function hA(e,t){e.seq.push(t),e.map[t.id]=t}function fL(e,t,n){let i=e.name,r=i.length;og.lastIndex=0;while(!0){let s=og.exec(i),a=og.lastIndex,o=s[1],c=s[2]==="]",l=s[3];if(c)o=o|0;if(l===void 0||l==="["&&a+2===r){hA(n,l===void 0?new NA(o,e,t):new PA(o,e,t));break}else{let d=n.map[o];if(d===void 0)d=new OA(o),hA(n,d);n=d}}}class xl{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let s=0;s<n;++s){let a=e.getActiveUniform(t,s),o=e.getUniformLocation(t,a.name);fL(a,o,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 a=t[r],o=n[a.id];if(o.needsUpdate!==!1)a.setValue(e,o.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 pA(e,t,n){let i=e.createShader(t);return e.shaderSource(i,n),e.compileShader(i),i}function mL(e,t){let n=e.split(``),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let a=r;a<s;a++){let o=a+1;i.push(`${o===t?">":" "} ${o}: ${n[a]}`)}return i.join(`-`)}function dL(e){ot._getMatrix(dA,ot.workingColorSpace,e);let t=`mat3( ${dA.elements.map((n)=>n.toFixed(4))} )`;switch(ot.getTransfer(e)){case Sm:return[t,"LinearTransferOETF"];case Bt:return[t,"sRGBTransferOETF"];default:return je("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}function fA(e,t,n){let i=e.getShaderParameter(t,e.COMPILE_STATUS),s=(e.getShaderInfoLog(t)||"").trim();if(i&&s==="")return"";let a=/ERROR: 0:(\d+)/.exec(s);if(a){let o=parseInt(a[1]);return n.toUpperCase()+`+`)}function gL(e){ot._getMatrix(mA,ot.workingColorSpace,e);let t=`mat3( ${mA.elements.map((n)=>n.toFixed(4))} )`;switch(ot.getTransfer(e)){case Nm:return[t,"LinearTransferOETF"];case Bt:return[t,"sRGBTransferOETF"];default:return je("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}function gA(e,t,n){let i=e.getShaderParameter(t,e.COMPILE_STATUS),s=(e.getShaderInfoLog(t)||"").trim();if(i&&s==="")return"";let a=/ERROR: 0:(\d+)/.exec(s);if(a){let o=parseInt(a[1]);return n.toUpperCase()+``+s+`-`+uL(e.getShaderSource(t),o)}else return s}function fL(e,t){let n=dL(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(`-`)}function pL(e,t){let n=hL[t];if(n===void 0)return je("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }";return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function mL(){ot.getLuminanceCoefficients(jd);let e=jd.x.toFixed(4),t=jd.y.toFixed(4),n=jd.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${e}, ${t}, ${n} );`,"\treturn dot( weights, rgb );","}"].join(`-`)}function gL(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(ml).join(`-`)}function bL(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 xL(e,t){let n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<i;r++){let s=e.getActiveAttrib(t,r),a=s.name,o=1;if(s.type===e.FLOAT_MAT2)o=2;if(s.type===e.FLOAT_MAT3)o=3;if(s.type===e.FLOAT_MAT4)o=4;n[a]={type:s.type,location:e.getAttribLocation(t,a),locationSize:o}}return n}function ml(e){return e!==""}function hA(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_SUN_LIGHTS/g,t.numSunLights).replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,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_SUN_LIGHT_SHADOWS/g,t.numSunLightShadows).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function pA(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}function sg(e){return e.replace(yL,vL)}function vL(e,t){let n=st[t];if(n===void 0){let i=_L.get(t);if(i!==void 0)n=st[i],je('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,i);else throw Error("THREE.WebGLProgram: Can not resolve #include <"+t+">")}return sg(n)}function mA(e){return e.replace(EL,TL)}function TL(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 gA(e){let t=`precision ${e.precision} float;+`+mL(e.getShaderSource(t),o)}else return s}function bL(e,t){let n=gL(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(`+`)}function yL(e,t){let n=xL[t];if(n===void 0)return je("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }";return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function _L(){ot.getLuminanceCoefficients($d);let e=$d.x.toFixed(4),t=$d.y.toFixed(4),n=$d.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${e}, ${t}, ${n} );`,"\treturn dot( weights, rgb );","}"].join(`+`)}function vL(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(bl).join(`+`)}function EL(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 TL(e,t){let n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<i;r++){let s=e.getActiveAttrib(t,r),a=s.name,o=1;if(s.type===e.FLOAT_MAT2)o=2;if(s.type===e.FLOAT_MAT3)o=3;if(s.type===e.FLOAT_MAT4)o=4;n[a]={type:s.type,location:e.getAttribLocation(t,a),locationSize:o}}return n}function bl(e){return e!==""}function bA(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_SUN_LIGHTS/g,t.numSunLights).replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,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_SUN_LIGHT_SHADOWS/g,t.numSunLightShadows).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function xA(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}function ug(e){return e.replace(AL,SL)}function SL(e,t){let n=st[t];if(n===void 0){let i=wL.get(t);if(i!==void 0)n=st[i],je('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,i);else throw Error("THREE.WebGLProgram: Can not resolve #include <"+t+">")}return ug(n)}function yA(e){return e.replace(ML,RL)}function RL(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 _A(e){let t=`precision ${e.precision} float;precision ${e.precision} int;precision ${e.precision} sampler2D;precision ${e.precision} samplerCube;@@ -296,30 +296,30 @@ ${Mn(o)}`)}`)He("manifest hash mismatch.");return structuredClone(e)}var jv="kil`;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}function wL(e){return AL[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}function ML(e){if(e.envMap===!1)return"ENVMAP_TYPE_CUBE";return SL[e.envMapMode]||"ENVMAP_TYPE_CUBE"}function IL(e){if(e.envMap===!1)return"ENVMAP_MODE_REFLECTION";return RL[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}function NL(e){if(e.envMap===!1)return"ENVMAP_BLENDING_NONE";return CL[e.combine]||"ENVMAP_BLENDING_NONE"}function PL(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 OL(e,t,n,i){let r=e.getContext(),{defines:s,vertexShader:a,fragmentShader:o}=n,c=wL(n),l=ML(n),u=IL(n),d=NL(n),f=PL(n),h=gL(n),b=bL(s),m=r.createProgram(),g,p,x=n.glslVersion?"#version "+n.glslVersion+`-`:"";if(n.isRawShaderMaterial){if(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,b].filter(ml).join(`+#define LOW_PRECISION`;return t}function CL(e){return IL[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}function PL(e){if(e.envMap===!1)return"ENVMAP_TYPE_CUBE";return NL[e.envMapMode]||"ENVMAP_TYPE_CUBE"}function kL(e){if(e.envMap===!1)return"ENVMAP_MODE_REFLECTION";return OL[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}function LL(e){if(e.envMap===!1)return"ENVMAP_BLENDING_NONE";return DL[e.combine]||"ENVMAP_BLENDING_NONE"}function FL(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 UL(e,t,n,i){let r=e.getContext(),{defines:s,vertexShader:a,fragmentShader:o}=n,c=CL(n),l=PL(n),u=kL(n),d=LL(n),f=FL(n),h=vL(n),b=EL(s),m=r.createProgram(),g,p,x=n.glslVersion?"#version "+n.glslVersion+`+`:"";if(n.isRawShaderMaterial){if(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,b].filter(bl).join(``),g.length>0)g+=`-`;if(p=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,b].filter(ml).join(`+`;if(p=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,b].filter(bl).join(``),p.length>0)p+=`-`}else g=[gA(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,b,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(ml).join(`-`),p=[gA(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,b,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 "+d:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.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.retroreflection?"#define USE_RETROREFLECTION":"",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!==Ui?"#define TONE_MAPPING":"",n.toneMapping!==Ui?st.tonemapping_pars_fragment:"",n.toneMapping!==Ui?pL("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",st.colorspace_pars_fragment,fL("linearToOutputTexel",n.outputColorSpace),mL(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`-`].filter(ml).join(`-`);if(a=sg(a),a=hA(a,n),a=pA(a,n),o=sg(o),o=hA(o,n),o=pA(o,n),a=mA(a),o=mA(o),n.isRawShaderMaterial!==!0)x=`#version 300 es+`}else g=[_A(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,b,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(bl).join(`+`),p=[_A(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,b,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 "+d:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.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.retroreflection?"#define USE_RETROREFLECTION":"",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!==Ui?"#define TONE_MAPPING":"",n.toneMapping!==Ui?st.tonemapping_pars_fragment:"",n.toneMapping!==Ui?yL("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",st.colorspace_pars_fragment,bL("linearToOutputTexel",n.outputColorSpace),_L(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`+`].filter(bl).join(`+`);if(a=ug(a),a=bA(a,n),a=xA(a,n),o=ug(o),o=bA(o,n),o=xA(o,n),a=yA(a),o=yA(o),n.isRawShaderMaterial!==!0)x=`#version 300 es`,g=[h,"#define attribute in","#define varying out","#define texture2D texture"].join(``)+`-`+g,p=["#define varying in",n.glslVersion===Mm?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Mm?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`+`+g,p=["#define varying in",n.glslVersion===Pm?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Pm?"":"#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;let _=x+g+a,y=x+p+o,v=uA(r,r.VERTEX_SHADER,_),T=uA(r,r.FRAGMENT_SHADER,y);if(r.attachShader(m,v),r.attachShader(m,T),n.index0AttributeName!==void 0)r.bindAttribLocation(m,0,n.index0AttributeName);else if(n.hasPositionAttribute===!0)r.bindAttribLocation(m,0,"position");r.linkProgram(m);function A(S){if(e.debug.checkShaderErrors){let I=r.getProgramInfoLog(m)||"",U=r.getShaderInfoLog(v)||"",N=r.getShaderInfoLog(T)||"",F=I.trim(),D=U.trim(),O=N.trim(),K=!0,B=!0;if(r.getProgramParameter(m,r.LINK_STATUS)===!1)if(K=!1,typeof e.debug.onShaderError==="function")e.debug.onShaderError(r,m,v,T);else{let X=fA(r,v,"vertex"),q=fA(r,T,"fragment");Ze("WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+`+`+p;let _=x+g+a,y=x+p+o,v=pA(r,r.VERTEX_SHADER,_),E=pA(r,r.FRAGMENT_SHADER,y);if(r.attachShader(m,v),r.attachShader(m,E),n.index0AttributeName!==void 0)r.bindAttribLocation(m,0,n.index0AttributeName);else if(n.hasPositionAttribute===!0)r.bindAttribLocation(m,0,"position");r.linkProgram(m);function w(S){if(e.debug.checkShaderErrors){let R=r.getProgramInfoLog(m)||"",k=r.getShaderInfoLog(v)||"",C=r.getShaderInfoLog(E)||"",U=R.trim(),L=k.trim(),O=C.trim(),K=!0,B=!0;if(r.getProgramParameter(m,r.LINK_STATUS)===!1)if(K=!1,typeof e.debug.onShaderError==="function")e.debug.onShaderError(r,m,v,E);else{let X=gA(r,v,"vertex"),q=gA(r,E,"fragment");Ye("WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+`Material Name: `+S.name+`Material Type: `+S.type+`-Program Info Log: `+F+`+Program Info Log: `+U+``+X+`-`+q)}else if(F!=="")je("WebGLProgram: Program Info Log:",F);else if(D===""||O==="")B=!1;if(B)S.diagnostics={runnable:K,programLog:F,vertexShader:{log:D,prefix:g},fragmentShader:{log:O,prefix:p}}}r.deleteShader(v),r.deleteShader(T),E=new gl(r,m),w=xL(r,m)}let E;this.getUniforms=function(){if(E===void 0)A(this);return E};let w;this.getAttributes=function(){if(w===void 0)A(this);return w};let P=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){if(P===!1)P=r.getProgramParameter(m,cL);return P},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(m),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=lL++,this.cacheKey=t,this.usedTimes=1,this.program=m,this.vertexShader=v,this.fragmentShader=T,this}class CA{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 NA(e),t.set(e,n);return n}}class NA{constructor(e){this.id=kL++,this.code=e,this.usedTimes=0}}function DL(e){return e===Ta||e===xd||e===yd}function LL(e,t,n,i,r,s){let a=new Ad,o=new CA,c=new Set,l=[],u=new Map,{logarithmicDepthBuffer:d,precision:f}=i,h={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 b(E){if(c.add(E),E===0)return"uv";return`uv${E}`}function m(E,w,P,S,I,U){let N=S.fog,F=I.geometry,D=E.isMeshStandardMaterial||E.isMeshLambertMaterial||E.isMeshPhongMaterial?S.environment:null,O=E.isMeshStandardMaterial||E.isMeshLambertMaterial&&!E.envMap||E.isMeshPhongMaterial&&!E.envMap,K=t.get(E.envMap||D,O),B=!!K&&K.mapping===qc?K.image.height:null,X=h[E.type];if(E.precision!==null){if(f=i.getMaxPrecision(E.precision),f!==E.precision)je("WebGLProgram.getParameters:",E.precision,"not supported, using",f,"instead.")}let q=F.morphAttributes.position||F.morphAttributes.normal||F.morphAttributes.color,le=q!==void 0?q.length:0,de=0;if(F.morphAttributes.position!==void 0)de=1;if(F.morphAttributes.normal!==void 0)de=2;if(F.morphAttributes.color!==void 0)de=3;let Me,pe,J,L;if(X){let zt=br[X];Me=zt.vertexShader,pe=zt.fragmentShader}else{Me=E.vertexShader,pe=E.fragmentShader;let zt=o.getVertexShaderStage(E),Mt=o.getFragmentShaderStage(E);o.update(E,zt,Mt),J=zt.id,L=Mt.id}let W=e.getRenderTarget(),ne=e.state.buffers.depth.getReversed(),ie=I.isInstancedMesh===!0,ce=I.isBatchedMesh===!0,_e=!!E.map,Re=!!E.matcap,Oe=!!K,We=!!E.aoMap,Ye=!!E.lightMap,Wt=!!E.bumpMap&&E.wireframe===!1,lt=!!E.normalMap,Lt=!!E.displacementMap,Qt=!!E.emissiveMap,nn=!!E.metalnessMap,z=!!E.roughnessMap,yn=E.anisotropy>0,St=E.clearcoat>0,Xt=E.dispersion>0,C=E.retroreflectivity>0,M=E.iridescence>0,V=E.sheen>0,Q=E.transmission>0,he=yn&&!!E.anisotropyMap,ge=St&&!!E.clearcoatMap,ve=St&&!!E.clearcoatNormalMap,re=St&&!!E.clearcoatRoughnessMap,oe=M&&!!E.iridescenceMap,Ie=M&&!!E.iridescenceThicknessMap,Ve=V&&!!E.sheenColorMap,Ee=V&&!!E.sheenRoughnessMap,me=!!E.specularMap,Ge=!!E.specularColorMap,Xe=!!E.specularIntensityMap,vt=Q&&!!E.transmissionMap,G=Q&&!!E.thicknessMap,xe=!!E.gradientMap,ae=!!E.alphaMap,ye=E.alphaTest>0,Ce=!!E.alphaHash,fe=!!E.extensions,Ae=Ui;if(E.toneMapped){if(W===null||W.isXRRenderTarget===!0)Ae=e.toneMapping}let it={shaderID:X,shaderType:E.type,shaderName:E.name,vertexShader:Me,fragmentShader:pe,defines:E.defines,customVertexShaderID:J,customFragmentShaderID:L,isRawShaderMaterial:E.isRawShaderMaterial===!0,glslVersion:E.glslVersion,precision:f,batching:ce,batchingColor:ce&&I._colorsTexture!==null,instancing:ie,instancingColor:ie&&I.instanceColor!==null,instancingMorph:ie&&I.morphTexture!==null,outputColorSpace:W===null?e.outputColorSpace:W.isXRRenderTarget===!0?W.texture.colorSpace:ot.workingColorSpace,alphaToCoverage:!!E.alphaToCoverage,map:_e,matcap:Re,envMap:Oe,envMapMode:Oe&&K.mapping,envMapCubeUVHeight:B,aoMap:We,lightMap:Ye,bumpMap:Wt,normalMap:lt,displacementMap:Lt,emissiveMap:Qt,normalMapObjectSpace:lt&&E.normalMapType===kT,normalMapTangentSpace:lt&&E.normalMapType===wm,packedNormalMap:lt&&E.normalMapType===wm&&DL(E.normalMap.format),metalnessMap:nn,roughnessMap:z,anisotropy:yn,anisotropyMap:he,clearcoat:St,clearcoatMap:ge,clearcoatNormalMap:ve,clearcoatRoughnessMap:re,dispersion:Xt,retroreflection:C,iridescence:M,iridescenceMap:oe,iridescenceThicknessMap:Ie,sheen:V,sheenColorMap:Ve,sheenRoughnessMap:Ee,specularMap:me,specularColorMap:Ge,specularIntensityMap:Xe,transmission:Q,transmissionMap:vt,thicknessMap:G,gradientMap:xe,opaque:E.transparent===!1&&E.blending===Wc&&E.alphaToCoverage===!1,alphaMap:ae,alphaTest:ye,alphaHash:Ce,combine:E.combine,mapUv:_e&&b(E.map.channel),aoMapUv:We&&b(E.aoMap.channel),lightMapUv:Ye&&b(E.lightMap.channel),bumpMapUv:Wt&&b(E.bumpMap.channel),normalMapUv:lt&&b(E.normalMap.channel),displacementMapUv:Lt&&b(E.displacementMap.channel),emissiveMapUv:Qt&&b(E.emissiveMap.channel),metalnessMapUv:nn&&b(E.metalnessMap.channel),roughnessMapUv:z&&b(E.roughnessMap.channel),anisotropyMapUv:he&&b(E.anisotropyMap.channel),clearcoatMapUv:ge&&b(E.clearcoatMap.channel),clearcoatNormalMapUv:ve&&b(E.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:re&&b(E.clearcoatRoughnessMap.channel),iridescenceMapUv:oe&&b(E.iridescenceMap.channel),iridescenceThicknessMapUv:Ie&&b(E.iridescenceThicknessMap.channel),sheenColorMapUv:Ve&&b(E.sheenColorMap.channel),sheenRoughnessMapUv:Ee&&b(E.sheenRoughnessMap.channel),specularMapUv:me&&b(E.specularMap.channel),specularColorMapUv:Ge&&b(E.specularColorMap.channel),specularIntensityMapUv:Xe&&b(E.specularIntensityMap.channel),transmissionMapUv:vt&&b(E.transmissionMap.channel),thicknessMapUv:G&&b(E.thicknessMap.channel),alphaMapUv:ae&&b(E.alphaMap.channel),vertexTangents:!!F.attributes.tangent&&(lt||yn),vertexNormals:!!F.attributes.normal,vertexColors:E.vertexColors,vertexAlphas:E.vertexColors===!0&&!!F.attributes.color&&F.attributes.color.itemSize===4,pointsUvs:I.isPoints===!0&&!!F.attributes.uv&&(_e||ae),fog:!!N,useFog:E.fog===!0,fogExp2:!!N&&N.isFogExp2,flatShading:E.wireframe===!1&&(E.flatShading===!0||F.attributes.normal===void 0&<===!1&&(E.isMeshLambertMaterial||E.isMeshPhongMaterial||E.isMeshStandardMaterial||E.isMeshPhysicalMaterial)),sizeAttenuation:E.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ne,skinning:I.isSkinnedMesh===!0,hasPositionAttribute:F.attributes.position!==void 0,morphTargets:F.morphAttributes.position!==void 0,morphNormals:F.morphAttributes.normal!==void 0,morphColors:F.morphAttributes.color!==void 0,morphTargetsCount:le,morphTextureStride:de,numSunLights:w.sun.length,numDirLights:w.directional.length,numPointLights:w.point.length,numSpotLights:w.spot.length,numSpotLightMaps:w.spotLightMap.length,numRectAreaLights:w.rectArea.length,numHemiLights:w.hemi.length,numSunLightShadows:w.sunShadowMap.length,numDirLightShadows:w.directionalShadowMap.length,numPointLightShadows:w.pointShadowMap.length,numSpotLightShadows:w.spotShadowMap.length,numSpotLightShadowsWithMaps:w.numSpotLightShadowsWithMaps,numLightProbes:w.numLightProbes,numLightProbeGrids:U.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:E.dithering,shadowMapEnabled:e.shadowMap.enabled&&P.length>0,shadowMapType:e.shadowMap.type,toneMapping:Ae,decodeVideoTexture:_e&&E.map.isVideoTexture===!0&&ot.getTransfer(E.map.colorSpace)===Bt,decodeVideoTextureEmissive:Qt&&E.emissiveMap.isVideoTexture===!0&&ot.getTransfer(E.emissiveMap.colorSpace)===Bt,premultipliedAlpha:E.premultipliedAlpha,doubleSided:E.side===vi,flipSided:E.side===kn,useDepthPacking:E.depthPacking>=0,depthPacking:E.depthPacking||0,index0AttributeName:E.index0AttributeName,extensionClipCullDistance:fe&&E.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(fe&&E.extensions.multiDraw===!0||ce)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:E.customProgramCacheKey()};return it.vertexUv1s=c.has(1),it.vertexUv2s=c.has(2),it.vertexUv3s=c.has(3),c.clear(),it}function g(E){let w=[];if(E.shaderID)w.push(E.shaderID);else w.push(E.customVertexShaderID),w.push(E.customFragmentShaderID);if(E.defines!==void 0)for(let P in E.defines)w.push(P),w.push(E.defines[P]);if(E.isRawShaderMaterial===!1)p(w,E),x(w,E),w.push(e.outputColorSpace);return w.push(E.customProgramCacheKey),w.join()}function p(E,w){E.push(w.precision),E.push(w.outputColorSpace),E.push(w.envMapMode),E.push(w.envMapCubeUVHeight),E.push(w.mapUv),E.push(w.alphaMapUv),E.push(w.lightMapUv),E.push(w.aoMapUv),E.push(w.bumpMapUv),E.push(w.normalMapUv),E.push(w.displacementMapUv),E.push(w.emissiveMapUv),E.push(w.metalnessMapUv),E.push(w.roughnessMapUv),E.push(w.anisotropyMapUv),E.push(w.clearcoatMapUv),E.push(w.clearcoatNormalMapUv),E.push(w.clearcoatRoughnessMapUv),E.push(w.iridescenceMapUv),E.push(w.iridescenceThicknessMapUv),E.push(w.sheenColorMapUv),E.push(w.sheenRoughnessMapUv),E.push(w.specularMapUv),E.push(w.specularColorMapUv),E.push(w.specularIntensityMapUv),E.push(w.transmissionMapUv),E.push(w.thicknessMapUv),E.push(w.combine),E.push(w.fogExp2),E.push(w.sizeAttenuation),E.push(w.morphTargetsCount),E.push(w.morphAttributeCount),E.push(w.numSunLights),E.push(w.numDirLights),E.push(w.numPointLights),E.push(w.numSpotLights),E.push(w.numSpotLightMaps),E.push(w.numHemiLights),E.push(w.numRectAreaLights),E.push(w.numSunLightShadows),E.push(w.numDirLightShadows),E.push(w.numPointLightShadows),E.push(w.numSpotLightShadows),E.push(w.numSpotLightShadowsWithMaps),E.push(w.numLightProbes),E.push(w.shadowMapType),E.push(w.toneMapping),E.push(w.numClippingPlanes),E.push(w.numClipIntersection),E.push(w.depthPacking)}function x(E,w){if(a.disableAll(),w.instancing)a.enable(0);if(w.instancingColor)a.enable(1);if(w.instancingMorph)a.enable(2);if(w.matcap)a.enable(3);if(w.envMap)a.enable(4);if(w.normalMapObjectSpace)a.enable(5);if(w.normalMapTangentSpace)a.enable(6);if(w.clearcoat)a.enable(7);if(w.iridescence)a.enable(8);if(w.alphaTest)a.enable(9);if(w.vertexColors)a.enable(10);if(w.vertexAlphas)a.enable(11);if(w.vertexUv1s)a.enable(12);if(w.vertexUv2s)a.enable(13);if(w.vertexUv3s)a.enable(14);if(w.vertexTangents)a.enable(15);if(w.anisotropy)a.enable(16);if(w.alphaHash)a.enable(17);if(w.batching)a.enable(18);if(w.dispersion)a.enable(19);if(w.retroreflection)a.enable(24);if(w.batchingColor)a.enable(20);if(w.gradientMap)a.enable(21);if(w.packedNormalMap)a.enable(22);if(w.vertexNormals)a.enable(23);if(E.push(a.mask),a.disableAll(),w.fog)a.enable(0);if(w.useFog)a.enable(1);if(w.flatShading)a.enable(2);if(w.logarithmicDepthBuffer)a.enable(3);if(w.reversedDepthBuffer)a.enable(4);if(w.skinning)a.enable(5);if(w.morphTargets)a.enable(6);if(w.morphNormals)a.enable(7);if(w.morphColors)a.enable(8);if(w.premultipliedAlpha)a.enable(9);if(w.shadowMapEnabled)a.enable(10);if(w.doubleSided)a.enable(11);if(w.flipSided)a.enable(12);if(w.useDepthPacking)a.enable(13);if(w.dithering)a.enable(14);if(w.transmission)a.enable(15);if(w.sheen)a.enable(16);if(w.opaque)a.enable(17);if(w.pointsUvs)a.enable(18);if(w.decodeVideoTexture)a.enable(19);if(w.decodeVideoTextureEmissive)a.enable(20);if(w.alphaToCoverage)a.enable(21);if(w.numLightProbeGrids>0)a.enable(22);if(w.hasPositionAttribute)a.enable(23);E.push(a.mask)}function _(E){let w=h[E.type],P;if(w){let S=br[w];P=KT.clone(S.uniforms)}else P=E.uniforms;return P}function y(E,w){let P=u.get(w);if(P!==void 0)++P.usedTimes;else P=new OL(e,w,E,r),l.push(P),u.set(w,P);return P}function v(E){if(--E.usedTimes===0){let w=l.indexOf(E);l[w]=l[l.length-1],l.pop(),u.delete(E.cacheKey),E.destroy()}}function T(E){o.remove(E)}function A(){o.dispose()}return{getParameters:m,getProgramCacheKey:g,getUniforms:_,acquireProgram:y,releaseProgram:v,releaseShaderCache:T,programs:l,dispose:A}}function FL(){let e=new WeakMap;function t(a){return e.has(a)}function n(a){let o=e.get(a);if(o===void 0)o={},e.set(a,o);return o}function i(a){e.delete(a)}function r(a,o,c){e.get(a)[o]=c}function s(){e=new WeakMap}return{has:t,get:n,remove:i,update:r,dispose:s}}function UL(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 bA(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 xA(){let e=[],t=0,n=[],i=[],r=[];function s(){t=0,n.length=0,i.length=0,r.length=0}function a(f){let h=0;if(f.isInstancedMesh)h+=2;if(f.isSkinnedMesh)h+=1;return h}function o(f,h,b,m,g,p){let x=e[t];if(x===void 0)x={id:f.id,object:f,geometry:h,material:b,materialVariant:a(f),groupOrder:m,renderOrder:f.renderOrder,z:g,group:p},e[t]=x;else x.id=f.id,x.object=f,x.geometry=h,x.material=b,x.materialVariant=a(f),x.groupOrder=m,x.renderOrder=f.renderOrder,x.z=g,x.group=p;return t++,x}function c(f,h,b,m,g,p,x){if(x.reversedDepth===!0)g=-g;let _=o(f,h,b,m,g,p);if(b.transmission>0)i.push(_);else if(b.transparent===!0)r.push(_);else n.push(_)}function l(f,h,b,m,g,p){let x=o(f,h,b,m,g,p);if(b.transmission>0)i.unshift(x);else if(b.transparent===!0)r.unshift(x);else n.unshift(x)}function u(f,h){if(n.length>1)n.sort(f||UL);if(i.length>1)i.sort(h||bA);if(r.length>1)r.sort(h||bA)}function d(){for(let f=t,h=e.length;f<h;f++){let b=e[f];if(b.id===null)break;b.id=null,b.object=null,b.geometry=null,b.material=null,b.group=null}}return{opaque:n,transmissive:i,transparent:r,init:s,push:c,unshift:l,finish:d,sort:u}}function BL(){let e=new WeakMap;function t(i,r){let s=e.get(i),a;if(s===void 0)a=new xA,e.set(i,[a]);else if(r>=s.length)a=new xA,s.push(a);else a=s[r];return a}function n(){e=new WeakMap}return{get:t,dispose:n}}function zL(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case"SunLight":case"DirectionalLight":n={direction:new j,color:new qe};break;case"SpotLight":n={position:new j,direction:new j,color:new qe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new j,color:new qe,distance:0,decay:0};break;case"HemisphereLight":n={direction:new j,skyColor:new qe,groundColor:new qe};break;case"RectAreaLight":n={color:new qe,position:new j,halfWidth:new j,halfHeight:new j};break}return e[t.id]=n,n}}}function VL(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case"SunLight":case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ke};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ke};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ke,shadowCameraNear:1,shadowCameraFar:1000};break}return e[t.id]=n,n}}}function HL(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function GL(e){let t=new zL,n=VL(),i={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)i.probe.push(new j);let r=new j,s=new Qe,a=new Qe;function o(l){let u=0,d=0,f=0;for(let I=0;I<9;I++)i.probe[I].set(0,0,0);let h=0,b=0,m=0,g=0,p=0,x=0,_=0,y=0,v=0,T=0,A=0,E=0,w=0,P=0;l.sort(HL);for(let I=0,U=l.length;I<U;I++){let N=l[I],{color:F,intensity:D,distance:O}=N,K=null;if(N.shadow&&N.shadow.map)if(N.shadow.map.texture.format===Ta)K=N.shadow.map.texture;else K=N.shadow.map.depthTexture||N.shadow.map.texture;if(N.isAmbientLight)u+=F.r*D,d+=F.g*D,f+=F.b*D;else if(N.isLightProbe){for(let B=0;B<9;B++)i.probe[B].addScaledVector(N.sh.coefficients[B],D);P++}else if(N.isSunLight){let B=t.get(N);if(B.color.copy(N.color).multiplyScalar(N.intensity),N.castShadow){let X=N.shadow,q=n.get(N);q.shadowIntensity=X.intensity,q.shadowBias=X.bias,q.shadowNormalBias=X.normalBias,q.shadowRadius=X.radius,q.shadowMapSize.copy(X.mapSize).multiply(X.getFrameExtents()),i.sunShadow[b]=q,i.sunShadowMap[b]=K;let le=X.getViewportCount();for(let de=0;de<le;de++)i.sunShadowMatrix[m+de]=X.getMatrix(de),i.sunShadowCascade[m+de]=X._cascadeData[de];m+=le,b++}i.sun[h]=B,h++}else if(N.isDirectionalLight){let B=t.get(N);if(B.color.copy(N.color).multiplyScalar(N.intensity),N.castShadow){let X=N.shadow,q=n.get(N);q.shadowIntensity=X.intensity,q.shadowBias=X.bias,q.shadowNormalBias=X.normalBias,q.shadowRadius=X.radius,q.shadowMapSize=X.mapSize,i.directionalShadow[g]=q,i.directionalShadowMap[g]=K,i.directionalShadowMatrix[g]=N.shadow.matrix,v++}i.directional[g]=B,g++}else if(N.isSpotLight){let B=t.get(N);B.position.setFromMatrixPosition(N.matrixWorld),B.color.copy(F).multiplyScalar(D),B.distance=O,B.coneCos=Math.cos(N.angle),B.penumbraCos=Math.cos(N.angle*(1-N.penumbra)),B.decay=N.decay,i.spot[x]=B;let X=N.shadow;if(N.map){if(i.spotLightMap[E]=N.map,E++,X.updateMatrices(N),N.castShadow)w++}if(i.spotLightMatrix[x]=X.matrix,N.castShadow){let q=n.get(N);q.shadowIntensity=X.intensity,q.shadowBias=X.bias,q.shadowNormalBias=X.normalBias,q.shadowRadius=X.radius,q.shadowMapSize=X.mapSize,i.spotShadow[x]=q,i.spotShadowMap[x]=K,A++}x++}else if(N.isRectAreaLight){let B=t.get(N);B.color.copy(F).multiplyScalar(D),B.halfWidth.set(N.width*0.5,0,0),B.halfHeight.set(0,N.height*0.5,0),i.rectArea[_]=B,_++}else if(N.isPointLight){let B=t.get(N);if(B.color.copy(N.color).multiplyScalar(N.intensity),B.distance=N.distance,B.decay=N.decay,N.castShadow){let X=N.shadow,q=n.get(N);q.shadowIntensity=X.intensity,q.shadowBias=X.bias,q.shadowNormalBias=X.normalBias,q.shadowRadius=X.radius,q.shadowMapSize=X.mapSize,q.shadowCameraNear=X.camera.near,q.shadowCameraFar=X.camera.far,i.pointShadow[p]=q,i.pointShadowMap[p]=K,i.pointShadowMatrix[p]=N.shadow.matrix,T++}i.point[p]=B,p++}else if(N.isHemisphereLight){let B=t.get(N);B.skyColor.copy(N.color).multiplyScalar(D),B.groundColor.copy(N.groundColor).multiplyScalar(D),i.hemi[y]=B,y++}}if(_>0)if(e.has("OES_texture_float_linear")===!0)i.rectAreaLTC1=Te.LTC_FLOAT_1,i.rectAreaLTC2=Te.LTC_FLOAT_2;else i.rectAreaLTC1=Te.LTC_HALF_1,i.rectAreaLTC2=Te.LTC_HALF_2;i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=f;let S=i.hash;if(S.sunLength!==h||S.directionalLength!==g||S.pointLength!==p||S.spotLength!==x||S.rectAreaLength!==_||S.hemiLength!==y||S.numSunShadows!==b||S.numDirectionalShadows!==v||S.numPointShadows!==T||S.numSpotShadows!==A||S.numSpotMaps!==E||S.numLightProbes!==P)i.sun.length=h,i.directional.length=g,i.spot.length=x,i.rectArea.length=_,i.point.length=p,i.hemi.length=y,i.sunShadow.length=b,i.sunShadowMap.length=b,i.sunShadowMatrix.length=m,i.sunShadowCascade.length=m,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.directionalShadowMatrix.length=v,i.pointShadow.length=T,i.pointShadowMap.length=T,i.pointShadowMatrix.length=T,i.spotShadow.length=A,i.spotShadowMap.length=A,i.spotLightMatrix.length=A+E-w,i.spotLightMap.length=E,i.numSpotLightShadowsWithMaps=w,i.numLightProbes=P,S.sunLength=h,S.directionalLength=g,S.pointLength=p,S.spotLength=x,S.rectAreaLength=_,S.hemiLength=y,S.numSunShadows=b,S.numDirectionalShadows=v,S.numPointShadows=T,S.numSpotShadows=A,S.numSpotMaps=E,S.numLightProbes=P,i.version=jL++}function c(l,u){let d=0,f=0,h=0,b=0,m=0,g=0,p=u.matrixWorldInverse;for(let x=0,_=l.length;x<_;x++){let y=l[x];if(y.isSunLight){let v=i.sun[d];v.direction.setFromMatrixPosition(y.matrixWorld),v.direction.transformDirection(p),d++}else if(y.isDirectionalLight){let v=i.directional[f];v.direction.setFromMatrixPosition(y.matrixWorld),r.setFromMatrixPosition(y.target.matrixWorld),v.direction.sub(r),v.direction.transformDirection(p),f++}else if(y.isSpotLight){let v=i.spot[b];v.position.setFromMatrixPosition(y.matrixWorld),v.position.applyMatrix4(p),v.direction.setFromMatrixPosition(y.matrixWorld),r.setFromMatrixPosition(y.target.matrixWorld),v.direction.sub(r),v.direction.transformDirection(p),b++}else if(y.isRectAreaLight){let v=i.rectArea[m];v.position.setFromMatrixPosition(y.matrixWorld),v.position.applyMatrix4(p),a.identity(),s.copy(y.matrixWorld),s.premultiply(p),a.extractRotation(s),v.halfWidth.set(y.width*0.5,0,0),v.halfHeight.set(0,y.height*0.5,0),v.halfWidth.applyMatrix4(a),v.halfHeight.applyMatrix4(a),m++}else if(y.isPointLight){let v=i.point[h];v.position.setFromMatrixPosition(y.matrixWorld),v.position.applyMatrix4(p),h++}else if(y.isHemisphereLight){let v=i.hemi[g];v.direction.setFromMatrixPosition(y.matrixWorld),v.direction.transformDirection(p),g++}}}return{setup:o,setupView:c,state:i}}function yA(e){let t=new GL(e),n=[],i=[],r=[];function s(f){d.camera=f,n.length=0,i.length=0,r.length=0}function a(f){n.push(f)}function o(f){i.push(f)}function c(f){r.push(f)}function l(){t.setup(n)}function u(f){t.setupView(n,f)}let d={lightsArray:n,shadowsArray:i,lightProbeGridArray:r,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:d,setupLights:l,setupLightsView:u,pushLight:a,pushShadow:o,pushLightProbeGrid:c}}function $L(e){let t=new WeakMap;function n(r,s=0){let a=t.get(r),o;if(a===void 0)o=new yA(e),t.set(r,[o]);else if(s>=a.length)o=new yA(e),a.push(o);else o=a[s];return o}function i(){t=new WeakMap}return{get:n,dispose:i}}function JL(e,t,n){let i=new sl,r=new Ke,s=new Ke,a=new Pt,o=new Lm,c=new Fm,l={},u=n.maxTextureSize,d={[fs]:kn,[kn]:fs,[vi]:vi},f=new Ei({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Ke},radius:{value:4}},vertexShader:KL,fragmentShader:WL}),h=f.clone();h.defines.HORIZONTAL_PASS=1;let b=new Dn;b.setAttribute("position",new vn(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));let m=new jt(b,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Kc;let p=this.type;this.render=function(T,A,E){if(g.enabled===!1)return;if(g.autoUpdate===!1&&g.needsUpdate===!1)return;if(T.length===0)return;if(this.type===JE)je("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=Kc;let w=e.getRenderTarget(),P=e.getActiveCubeFace(),S=e.getActiveMipmapLevel(),I=e.state;if(I.setBlending(dr),I.buffers.depth.getReversed()===!0)I.buffers.color.setClear(0,0,0,0);else I.buffers.color.setClear(1,1,1,1);I.buffers.depth.setTest(!0),I.setScissorTest(!1);let U=p!==this.type;if(U)A.traverse(function(N){if(N.material)if(Array.isArray(N.material))N.material.forEach((F)=>F.needsUpdate=!0);else N.material.needsUpdate=!0});for(let N=0,F=T.length;N<F;N++){let D=T[N],O=D.shadow;if(O===void 0){je("WebGLShadowMap:",D,"has no shadow.");continue}if(O.autoUpdate===!1&&O.needsUpdate===!1)continue;r.copy(O.mapSize);let K=O.getFrameExtents();if(r.multiply(K),s.copy(O.mapSize),r.x>u||r.y>u){if(r.x>u)s.x=Math.floor(u/K.x),r.x=s.x*K.x,O.mapSize.x=s.x;if(r.y>u)s.y=Math.floor(u/K.y),r.y=s.y*K.y,O.mapSize.y=s.y}let B=e.state.buffers.depth.getReversed();if(O.camera._reversedDepth=B,O.map===null||U===!0){if(O.map!==null){if(O.map.depthTexture!==null)O.map.depthTexture.dispose(),O.map.depthTexture=null;O.map.dispose()}if(this.type===Ao){if(D.isPointLight){je("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}O.map=new ci(r.x,r.y,{format:Ta,type:hr,minFilter:En,magFilter:En,generateMipmaps:!1}),O.map.texture.name=D.name+".shadowMap",O.map.depthTexture=new wa(r.x,r.y,Br),O.map.depthTexture.name=D.name+".shadowMapDepth",O.map.depthTexture.format=va,O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=Bi,O.map.depthTexture.magFilter=Bi}else{if(D.isPointLight)O.map=new ag(r.x),O.map.depthTexture=new Om(r.x,hs);else O.map=new ci(r.x,r.y),O.map.depthTexture=new wa(r.x,r.y,hs);if(O.map.depthTexture.name=D.name+".shadowMap",O.map.depthTexture.format=va,this.type===Kc)O.map.depthTexture.compareFunction=B?Ed:vd,O.map.depthTexture.minFilter=En,O.map.depthTexture.magFilter=En;else O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=Bi,O.map.depthTexture.magFilter=Bi}O.camera.updateProjectionMatrix()}if(O.map.isWebGLCubeRenderTarget!==!0&&(O.map.width!==r.x||O.map.height!==r.y))O.map.setSize(r.x,r.y);let X=O.map.isWebGLCubeRenderTarget?6:O.getViewportCount();if(D.isPointLight!==!0)O.updateMatrices(D,E);for(let q=0;q<X;q++){let le=O.getCamera(q);if(D.isPointLight){let{camera:de,matrix:Me}=O,pe=D.distance||de.far;if(pe!==de.far)de.far=pe,de.updateProjectionMatrix();pl.setFromMatrixPosition(D.matrixWorld),de.position.copy(pl),ig.copy(de.position),ig.add(XL[q]),de.up.copy(qL[q]),de.lookAt(ig),de.updateMatrixWorld(),Me.makeTranslation(-pl.x,-pl.y,-pl.z),_A.multiplyMatrices(de.projectionMatrix,de.matrixWorldInverse),O._frustum.setFromProjectionMatrix(_A,de.coordinateSystem,de.reversedDepth)}if(O.map.isWebGLCubeRenderTarget)e.setRenderTarget(O.map,q),e.clear();else{if(q===0)e.setRenderTarget(O.map),e.clear();let de=O.getViewport(q);a.set(s.x*de.x,s.y*de.y,s.x*de.z,s.y*de.w),I.viewport(a)}i=O.getFrustum(q),y(A,E,le,D,this.type)}if(O.isPointLightShadow!==!0&&this.type===Ao)x(O,E);O.needsUpdate=!1}p=this.type,g.needsUpdate=!1,e.setRenderTarget(w,P,S)};function x(T,A){let E=t.update(m);if(f.defines.VSM_SAMPLES!==T.blurSamples)f.defines.VSM_SAMPLES=T.blurSamples,h.defines.VSM_SAMPLES=T.blurSamples,f.needsUpdate=!0,h.needsUpdate=!0;if(T.mapPass===null)T.mapPass=new ci(r.x,r.y,{format:Ta,type:hr});else if(T.mapPass.width!==T.map.width||T.mapPass.height!==T.map.height)T.mapPass.setSize(T.map.width,T.map.height);f.uniforms.shadow_pass.value=T.map.depthTexture,f.uniforms.resolution.value.set(T.map.width,T.map.height),f.uniforms.radius.value=T.radius,e.setRenderTarget(T.mapPass),e.clear(),e.renderBufferDirect(A,null,E,f,m,null),h.uniforms.shadow_pass.value=T.mapPass.texture,h.uniforms.resolution.value.set(T.map.width,T.map.height),h.uniforms.radius.value=T.radius,e.setRenderTarget(T.map),e.clear(),e.renderBufferDirect(A,null,E,h,m,null)}function _(T,A,E,w){let P=null,S=E.isPointLight===!0?T.customDistanceMaterial:T.customDepthMaterial;if(S!==void 0)P=S;else if(P=E.isPointLight===!0?c:o,e.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 I=P.uuid,U=A.uuid,N=l[I];if(N===void 0)N={},l[I]=N;let F=N[U];if(F===void 0)F=P.clone(),N[U]=F,A.addEventListener("dispose",v);P=F}if(P.visible=A.visible,P.wireframe=A.wireframe,w===Ao)P.side=A.shadowSide!==null?A.shadowSide:A.side;else P.side=A.shadowSide!==null?A.shadowSide:d[A.side];if(P.alphaMap=A.alphaMap,P.alphaTest=A.alphaToCoverage===!0?0.5:A.alphaTest,P.map=A.map,P.clipShadows=A.clipShadows,P.clippingPlanes=A.clippingPlanes,P.clipIntersection=A.clipIntersection,P.displacementMap=A.displacementMap,P.displacementScale=A.displacementScale,P.displacementBias=A.displacementBias,P.wireframeLinewidth=A.wireframeLinewidth,P.linewidth=A.linewidth,E.isPointLight===!0&&P.isMeshDistanceMaterial===!0){let I=e.properties.get(P);I.light=E}return P}function y(T,A,E,w,P){if(T.visible===!1)return;if(T.layers.test(A.layers)&&(T.isMesh||T.isLine||T.isPoints)){if((T.castShadow||T.receiveShadow&&P===Ao)&&(!T.frustumCulled||T.intersectsFrustum(i))){T.modelViewMatrix.multiplyMatrices(E.matrixWorldInverse,T.matrixWorld);let U=t.update(T),N=T.material;if(Array.isArray(N)){let F=U.groups;for(let D=0,O=F.length;D<O;D++){let K=F[D],B=N[K.materialIndex];if(B&&B.visible){let X=_(T,B,w,P);T.onBeforeShadow(e,T,A,E,U,X,K),e.renderBufferDirect(E,null,U,X,T,K),T.onAfterShadow(e,T,A,E,U,X,K)}}}else if(N.visible){let F=_(T,N,w,P);T.onBeforeShadow(e,T,A,E,U,F,null),e.renderBufferDirect(E,null,U,F,T,null),T.onAfterShadow(e,T,A,E,U,F,null)}}}let I=T.children;for(let U=0,N=I.length;U<N;U++)y(I[U],A,E,w,P)}function v(T){T.target.removeEventListener("dispose",v);for(let E in l){let w=l[E],P=T.target.uuid;if(P in w)w[P].dispose(),delete w[P]}}}function ZL(e,t){function n(){let G=!1,xe=new Pt,ae=null,ye=new Pt(0,0,0,0);return{setMask:function(Ce){if(ae!==Ce&&!G)e.colorMask(Ce,Ce,Ce,Ce),ae=Ce},setLocked:function(Ce){G=Ce},setClear:function(Ce,fe,Ae,it,zt){if(zt===!0)Ce*=it,fe*=it,Ae*=it;if(xe.set(Ce,fe,Ae,it),ye.equals(xe)===!1)e.clearColor(Ce,fe,Ae,it),ye.copy(xe)},reset:function(){G=!1,ae=null,ye.set(-1,0,0,0)}}}function i(){let G=!1,xe=!1,ae=null,ye=null,Ce=null;return{setReversed:function(fe){if(xe!==fe){let Ae=t.get("EXT_clip_control");if(fe)Ae.clipControlEXT(Ae.LOWER_LEFT_EXT,Ae.ZERO_TO_ONE_EXT);else Ae.clipControlEXT(Ae.LOWER_LEFT_EXT,Ae.NEGATIVE_ONE_TO_ONE_EXT);xe=fe;let it=Ce;Ce=null,this.setClear(it)}},getReversed:function(){return xe},setTest:function(fe){if(fe)W(e.DEPTH_TEST);else ne(e.DEPTH_TEST)},setMask:function(fe){if(ae!==fe&&!G)e.depthMask(fe),ae=fe},setFunc:function(fe){if(xe)fe=GT[fe];if(ye!==fe){switch(fe){case bT:e.depthFunc(e.NEVER);break;case xT:e.depthFunc(e.ALWAYS);break;case yT:e.depthFunc(e.LESS);break;case kp:e.depthFunc(e.LEQUAL);break;case _T:e.depthFunc(e.EQUAL);break;case vT:e.depthFunc(e.GEQUAL);break;case ET:e.depthFunc(e.GREATER);break;case TT:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}ye=fe}},setLocked:function(fe){G=fe},setClear:function(fe){if(Ce!==fe){if(Ce=fe,xe)fe=1-fe;e.clearDepth(fe)}},reset:function(){G=!1,ae=null,ye=null,Ce=null,xe=!1}}}function r(){let G=!1,xe=null,ae=null,ye=null,Ce=null,fe=null,Ae=null,it=null,zt=null;return{setTest:function(Mt){if(!G)if(Mt)W(e.STENCIL_TEST);else ne(e.STENCIL_TEST)},setMask:function(Mt){if(xe!==Mt&&!G)e.stencilMask(Mt),xe=Mt},setFunc:function(Mt,Xi,wr){if(ae!==Mt||ye!==Xi||Ce!==wr)e.stencilFunc(Mt,Xi,wr),ae=Mt,ye=Xi,Ce=wr},setOp:function(Mt,Xi,wr){if(fe!==Mt||Ae!==Xi||it!==wr)e.stencilOp(Mt,Xi,wr),fe=Mt,Ae=Xi,it=wr},setLocked:function(Mt){G=Mt},setClear:function(Mt){if(zt!==Mt)e.clearStencil(Mt),zt=Mt},reset:function(){G=!1,xe=null,ae=null,ye=null,Ce=null,fe=null,Ae=null,it=null,zt=null}}}let s=new n,a=new i,o=new r,c=new WeakMap,l=new WeakMap,u={},d={},f={},h=new WeakMap,b=[],m=null,g=!1,p=null,x=null,_=null,y=null,v=null,T=null,A=null,E=new qe(0,0,0),w=0,P=!1,S=null,I=null,U=null,N=null,F=null,D=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),O=!1,K=0,B=e.getParameter(e.VERSION);if(B.indexOf("WebGL")!==-1)K=parseFloat(/^WebGL (\d)/.exec(B)[1]),O=K>=1;else if(B.indexOf("OpenGL ES")!==-1)K=parseFloat(/^OpenGL ES (\d)/.exec(B)[1]),O=K>=2;let X=null,q={},le=e.getParameter(e.SCISSOR_BOX),de=e.getParameter(e.VIEWPORT),Me=new Pt().fromArray(le),pe=new Pt().fromArray(de);function J(G,xe,ae,ye){let Ce=new Uint8Array(4),fe=e.createTexture();e.bindTexture(G,fe),e.texParameteri(G,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(G,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let Ae=0;Ae<ae;Ae++)if(G===e.TEXTURE_3D||G===e.TEXTURE_2D_ARRAY)e.texImage3D(xe,0,e.RGBA,1,1,ye,0,e.RGBA,e.UNSIGNED_BYTE,Ce);else e.texImage2D(xe+Ae,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,Ce);return fe}let L={};L[e.TEXTURE_2D]=J(e.TEXTURE_2D,e.TEXTURE_2D,1),L[e.TEXTURE_CUBE_MAP]=J(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),L[e.TEXTURE_2D_ARRAY]=J(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),L[e.TEXTURE_3D]=J(e.TEXTURE_3D,e.TEXTURE_3D,1,1),s.setClear(0,0,0,1),a.setClear(1),o.setClear(0),W(e.DEPTH_TEST),a.setFunc(kp),Wt(!1),lt(Cp),W(e.CULL_FACE),We(dr);function W(G){if(u[G]!==!0)e.enable(G),u[G]=!0}function ne(G){if(u[G]!==!1)e.disable(G),u[G]=!1}function ie(G,xe){if(f[G]!==xe){if(e.bindFramebuffer(G,xe),f[G]=xe,G===e.DRAW_FRAMEBUFFER)f[e.FRAMEBUFFER]=xe;if(G===e.FRAMEBUFFER)f[e.DRAW_FRAMEBUFFER]=xe;return!0}return!1}function ce(G,xe){let ae=b,ye=!1;if(G){if(ae=h.get(xe),ae===void 0)ae=[],h.set(xe,ae);let Ce=G.textures;if(ae.length!==Ce.length||ae[0]!==e.COLOR_ATTACHMENT0){for(let fe=0,Ae=Ce.length;fe<Ae;fe++)ae[fe]=e.COLOR_ATTACHMENT0+fe;ae.length=Ce.length,ye=!0}}else if(ae[0]!==e.BACK)ae[0]=e.BACK,ye=!0;if(ye)e.drawBuffers(ae)}function _e(G){if(m!==G)return e.useProgram(G),m=G,!0;return!1}let Re={[wo]:e.FUNC_ADD,[YE]:e.FUNC_SUBTRACT,[QE]:e.FUNC_REVERSE_SUBTRACT};Re[eT]=e.MIN,Re[tT]=e.MAX;let Oe={[nT]:e.ZERO,[iT]:e.ONE,[rT]:e.SRC_COLOR,[aT]:e.SRC_ALPHA,[fT]:e.SRC_ALPHA_SATURATE,[uT]:e.DST_COLOR,[cT]:e.DST_ALPHA,[sT]:e.ONE_MINUS_SRC_COLOR,[oT]:e.ONE_MINUS_SRC_ALPHA,[dT]:e.ONE_MINUS_DST_COLOR,[lT]:e.ONE_MINUS_DST_ALPHA,[hT]:e.CONSTANT_COLOR,[pT]:e.ONE_MINUS_CONSTANT_COLOR,[mT]:e.CONSTANT_ALPHA,[gT]:e.ONE_MINUS_CONSTANT_ALPHA};function We(G,xe,ae,ye,Ce,fe,Ae,it,zt,Mt){if(G===dr){if(g===!0)ne(e.BLEND),g=!1;return}if(g===!1)W(e.BLEND),g=!0;if(G!==ZE){if(G!==p||Mt!==P){if(x!==wo||v!==wo)e.blendEquation(e.FUNC_ADD),x=wo,v=wo;if(Mt)switch(G){case Wc:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case Np:e.blendFunc(e.ONE,e.ONE);break;case Pp:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case Op:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:Ze("WebGLState: Invalid blending: ",G);break}else switch(G){case Wc:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case Np:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case Pp:Ze("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Op:Ze("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Ze("WebGLState: Invalid blending: ",G);break}_=null,y=null,T=null,A=null,E.set(0,0,0),w=0,p=G,P=Mt}return}if(Ce=Ce||xe,fe=fe||ae,Ae=Ae||ye,xe!==x||Ce!==v)e.blendEquationSeparate(Re[xe],Re[Ce]),x=xe,v=Ce;if(ae!==_||ye!==y||fe!==T||Ae!==A)e.blendFuncSeparate(Oe[ae],Oe[ye],Oe[fe],Oe[Ae]),_=ae,y=ye,T=fe,A=Ae;if(it.equals(E)===!1||zt!==w)e.blendColor(it.r,it.g,it.b,zt),E.copy(it),w=zt;p=G,P=!1}function Ye(G,xe){G.side===vi?ne(e.CULL_FACE):W(e.CULL_FACE);let ae=G.side===kn;if(xe)ae=!ae;Wt(ae),G.blending===Wc&&G.transparent===!1?We(dr):We(G.blending,G.blendEquation,G.blendSrc,G.blendDst,G.blendEquationAlpha,G.blendSrcAlpha,G.blendDstAlpha,G.blendColor,G.blendAlpha,G.premultipliedAlpha),a.setFunc(G.depthFunc),a.setTest(G.depthTest),a.setMask(G.depthWrite),s.setMask(G.colorWrite);let ye=G.stencilWrite;if(o.setTest(ye),ye)o.setMask(G.stencilWriteMask),o.setFunc(G.stencilFunc,G.stencilRef,G.stencilFuncMask),o.setOp(G.stencilFail,G.stencilZFail,G.stencilZPass);Qt(G.polygonOffset,G.polygonOffsetFactor,G.polygonOffsetUnits),G.alphaToCoverage===!0?W(e.SAMPLE_ALPHA_TO_COVERAGE):ne(e.SAMPLE_ALPHA_TO_COVERAGE)}function Wt(G){if(S!==G){if(G)e.frontFace(e.CW);else e.frontFace(e.CCW);S=G}}function lt(G){if(G!==XE){if(W(e.CULL_FACE),G!==I)if(G===Cp)e.cullFace(e.BACK);else if(G===qE)e.cullFace(e.FRONT);else e.cullFace(e.FRONT_AND_BACK)}else ne(e.CULL_FACE);I=G}function Lt(G){if(G!==U){if(O)e.lineWidth(G);U=G}}function Qt(G,xe,ae){if(G){if(W(e.POLYGON_OFFSET_FILL),N!==xe||F!==ae){if(N=xe,F=ae,a.getReversed())xe=-xe;e.polygonOffset(xe,ae)}}else ne(e.POLYGON_OFFSET_FILL)}function nn(G){if(G)W(e.SCISSOR_TEST);else ne(e.SCISSOR_TEST)}function z(G){if(G===void 0)G=e.TEXTURE0+D-1;if(X!==G)e.activeTexture(G),X=G}function yn(G,xe,ae){if(ae===void 0)if(X===null)ae=e.TEXTURE0+D-1;else ae=X;let ye=q[ae];if(ye===void 0)ye={type:void 0,texture:void 0},q[ae]=ye;if(ye.type!==G||ye.texture!==xe){if(X!==ae)e.activeTexture(ae),X=ae;e.bindTexture(G,xe||L[G]),ye.type=G,ye.texture=xe}}function St(){let G=q[X];if(G!==void 0&&G.type!==void 0)e.bindTexture(G.type,null),G.type=void 0,G.texture=void 0}function Xt(){try{e.compressedTexImage2D(...arguments)}catch(G){Ze("WebGLState:",G)}}function C(){try{e.compressedTexImage3D(...arguments)}catch(G){Ze("WebGLState:",G)}}function M(){try{e.texSubImage2D(...arguments)}catch(G){Ze("WebGLState:",G)}}function V(){try{e.texSubImage3D(...arguments)}catch(G){Ze("WebGLState:",G)}}function Q(){try{e.compressedTexSubImage2D(...arguments)}catch(G){Ze("WebGLState:",G)}}function he(){try{e.compressedTexSubImage3D(...arguments)}catch(G){Ze("WebGLState:",G)}}function ge(){try{e.texStorage2D(...arguments)}catch(G){Ze("WebGLState:",G)}}function ve(){try{e.texStorage3D(...arguments)}catch(G){Ze("WebGLState:",G)}}function re(){try{e.texImage2D(...arguments)}catch(G){Ze("WebGLState:",G)}}function oe(){try{e.texImage3D(...arguments)}catch(G){Ze("WebGLState:",G)}}function Ie(G){if(d[G]!==void 0)return d[G];else return e.getParameter(G)}function Ve(G,xe){if(d[G]!==xe)e.pixelStorei(G,xe),d[G]=xe}function Ee(G){if(Me.equals(G)===!1)e.scissor(G.x,G.y,G.z,G.w),Me.copy(G)}function me(G){if(pe.equals(G)===!1)e.viewport(G.x,G.y,G.z,G.w),pe.copy(G)}function Ge(G,xe){let ae=l.get(xe);if(ae===void 0)ae=new WeakMap,l.set(xe,ae);let ye=ae.get(G);if(ye===void 0)ye=e.getUniformBlockIndex(xe,G.name),ae.set(G,ye)}function Xe(G,xe){let ye=l.get(xe).get(G);if(c.get(xe)!==ye)e.uniformBlockBinding(xe,ye,G.__bindingPointIndex),c.set(xe,ye)}function vt(){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),a.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={},d={},X=null,q={},f={},h=new WeakMap,b=[],m=null,g=!1,p=null,x=null,_=null,y=null,v=null,T=null,A=null,E=new qe(0,0,0),w=0,P=!1,S=null,I=null,U=null,N=null,F=null,Me.set(0,0,e.canvas.width,e.canvas.height),pe.set(0,0,e.canvas.width,e.canvas.height),s.reset(),a.reset(),o.reset()}return{buffers:{color:s,depth:a,stencil:o},enable:W,disable:ne,bindFramebuffer:ie,drawBuffers:ce,useProgram:_e,setBlending:We,setMaterial:Ye,setFlipSided:Wt,setCullFace:lt,setLineWidth:Lt,setPolygonOffset:Qt,setScissorTest:nn,activeTexture:z,bindTexture:yn,unbindTexture:St,compressedTexImage2D:Xt,compressedTexImage3D:C,texImage2D:re,texImage3D:oe,pixelStorei:Ve,getParameter:Ie,updateUBOMapping:Ge,uniformBlockBinding:Xe,texStorage2D:ge,texStorage3D:ve,texSubImage2D:M,texSubImage3D:V,compressedTexSubImage2D:Q,compressedTexSubImage3D:he,scissor:Ee,viewport:me,reset:vt}}function YL(e,t,n,i,r,s,a){let o=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 Ke,u=new WeakMap,d=new Set,f,h=new WeakMap,b=!1;try{b=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch(C){}function m(C,M){return b?new OffscreenCanvas(C,M):vo("canvas")}function g(C,M,V){let Q=1,he=Xt(C);if(he.width>V||he.height>V)Q=V/Math.max(he.width,he.height);if(Q<1)if(typeof HTMLImageElement<"u"&&C instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&C instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&C instanceof ImageBitmap||typeof VideoFrame<"u"&&C instanceof VideoFrame){let ge=Math.floor(Q*he.width),ve=Math.floor(Q*he.height);if(f===void 0)f=m(ge,ve);let re=M?m(ge,ve):f;return re.width=ge,re.height=ve,re.getContext("2d").drawImage(C,0,0,ge,ve),je("WebGLRenderer: Texture has been resized from ("+he.width+"x"+he.height+") to ("+ge+"x"+ve+")."),re}else{if("data"in C)je("WebGLRenderer: Image in DataTexture is too big ("+he.width+"x"+he.height+").");return C}return C}function p(C){return C.generateMipmaps}function x(C){e.generateMipmap(C)}function _(C){if(C.isWebGLCubeRenderTarget)return e.TEXTURE_CUBE_MAP;if(C.isWebGL3DRenderTarget)return e.TEXTURE_3D;if(C.isWebGLArrayRenderTarget||C.isCompressedArrayTexture)return e.TEXTURE_2D_ARRAY;return e.TEXTURE_2D}function y(C,M,V,Q,he,ge=!1){if(C!==null){if(e[C]!==void 0)return e[C];je("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+C+"'")}let ve;if(Q){if(ve=t.get("EXT_texture_norm16"),!ve)je("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension")}let re=M;if(M===e.RED){if(V===e.FLOAT)re=e.R32F;if(V===e.HALF_FLOAT)re=e.R16F;if(V===e.UNSIGNED_BYTE)re=e.R8;if(V===e.UNSIGNED_SHORT&&ve)re=ve.R16_EXT;if(V===e.SHORT&&ve)re=ve.R16_SNORM_EXT}if(M===e.RED_INTEGER){if(V===e.UNSIGNED_BYTE)re=e.R8UI;if(V===e.UNSIGNED_SHORT)re=e.R16UI;if(V===e.UNSIGNED_INT)re=e.R32UI;if(V===e.BYTE)re=e.R8I;if(V===e.SHORT)re=e.R16I;if(V===e.INT)re=e.R32I}if(M===e.RG){if(V===e.FLOAT)re=e.RG32F;if(V===e.HALF_FLOAT)re=e.RG16F;if(V===e.UNSIGNED_BYTE)re=e.RG8;if(V===e.UNSIGNED_SHORT&&ve)re=ve.RG16_EXT;if(V===e.SHORT&&ve)re=ve.RG16_SNORM_EXT}if(M===e.RG_INTEGER){if(V===e.UNSIGNED_BYTE)re=e.RG8UI;if(V===e.UNSIGNED_SHORT)re=e.RG16UI;if(V===e.UNSIGNED_INT)re=e.RG32UI;if(V===e.BYTE)re=e.RG8I;if(V===e.SHORT)re=e.RG16I;if(V===e.INT)re=e.RG32I}if(M===e.RGB_INTEGER){if(V===e.UNSIGNED_BYTE)re=e.RGB8UI;if(V===e.UNSIGNED_SHORT)re=e.RGB16UI;if(V===e.UNSIGNED_INT)re=e.RGB32UI;if(V===e.BYTE)re=e.RGB8I;if(V===e.SHORT)re=e.RGB16I;if(V===e.INT)re=e.RGB32I}if(M===e.RGBA_INTEGER){if(V===e.UNSIGNED_BYTE)re=e.RGBA8UI;if(V===e.UNSIGNED_SHORT)re=e.RGBA16UI;if(V===e.UNSIGNED_INT)re=e.RGBA32UI;if(V===e.BYTE)re=e.RGBA8I;if(V===e.SHORT)re=e.RGBA16I;if(V===e.INT)re=e.RGBA32I}if(M===e.RGB){if(V===e.UNSIGNED_SHORT&&ve)re=ve.RGB16_EXT;if(V===e.SHORT&&ve)re=ve.RGB16_SNORM_EXT;if(V===e.UNSIGNED_INT_5_9_9_9_REV)re=e.RGB9_E5;if(V===e.UNSIGNED_INT_10F_11F_11F_REV)re=e.R11F_G11F_B10F}if(M===e.RGBA){let oe=ge?Sm:ot.getTransfer(he);if(V===e.FLOAT)re=e.RGBA32F;if(V===e.HALF_FLOAT)re=e.RGBA16F;if(V===e.UNSIGNED_BYTE)re=oe===Bt?e.SRGB8_ALPHA8:e.RGBA8;if(V===e.UNSIGNED_SHORT&&ve)re=ve.RGBA16_EXT;if(V===e.SHORT&&ve)re=ve.RGBA16_SNORM_EXT;if(V===e.UNSIGNED_SHORT_4_4_4_4)re=e.RGBA4;if(V===e.UNSIGNED_SHORT_5_5_5_1)re=e.RGB5_A1}if(re===e.R16F||re===e.R32F||re===e.RG16F||re===e.RG32F||re===e.RGBA16F||re===e.RGBA32F)t.get("EXT_color_buffer_float");return re}function v(C,M){let V;if(C){if(M===null||M===hs||M===Co)V=e.DEPTH24_STENCIL8;else if(M===Br)V=e.DEPTH32F_STENCIL8;else if(M===Jc)V=e.DEPTH24_STENCIL8,je("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")}else if(M===null||M===hs||M===Co)V=e.DEPTH_COMPONENT24;else if(M===Br)V=e.DEPTH_COMPONENT32F;else if(M===Jc)V=e.DEPTH_COMPONENT16;return V}function T(C,M){if(p(C)===!0||C.isFramebufferTexture&&C.minFilter!==Bi&&C.minFilter!==En)return Math.log2(Math.max(M.width,M.height))+1;else if(C.mipmaps!==void 0&&C.mipmaps.length>0)return C.mipmaps.length;else if(C.isCompressedTexture&&Array.isArray(C.image))return M.mipmaps.length;else return 1}function A(C){let M=C.target;if(M.removeEventListener("dispose",A),w(M),M.isVideoTexture)u.delete(M);if(M.isHTMLTexture)d.delete(M)}function E(C){let M=C.target;M.removeEventListener("dispose",E),S(M)}function w(C){let M=i.get(C);if(M.__webglInit===void 0)return;let V=C.source,Q=h.get(V);if(Q){let he=Q[M.__cacheKey];if(he.usedTimes--,he.usedTimes===0)P(C);if(Object.keys(Q).length===0)h.delete(V)}i.remove(C)}function P(C){let M=i.get(C);e.deleteTexture(M.__webglTexture);let V=C.source,Q=h.get(V);delete Q[M.__cacheKey],a.memory.textures--}function S(C){let M=i.get(C);if(C.depthTexture)C.depthTexture.dispose(),i.remove(C.depthTexture);if(C.isWebGLCubeRenderTarget)for(let Q=0;Q<6;Q++){if(Array.isArray(M.__webglFramebuffer[Q]))for(let he=0;he<M.__webglFramebuffer[Q].length;he++)e.deleteFramebuffer(M.__webglFramebuffer[Q][he]);else e.deleteFramebuffer(M.__webglFramebuffer[Q]);if(M.__webglDepthbuffer)e.deleteRenderbuffer(M.__webglDepthbuffer[Q])}else{if(Array.isArray(M.__webglFramebuffer))for(let Q=0;Q<M.__webglFramebuffer.length;Q++)e.deleteFramebuffer(M.__webglFramebuffer[Q]);else e.deleteFramebuffer(M.__webglFramebuffer);if(M.__webglDepthbuffer)e.deleteRenderbuffer(M.__webglDepthbuffer);if(M.__webglMultisampledFramebuffer)e.deleteFramebuffer(M.__webglMultisampledFramebuffer);if(M.__webglColorRenderbuffer){for(let Q=0;Q<M.__webglColorRenderbuffer.length;Q++)if(M.__webglColorRenderbuffer[Q])e.deleteRenderbuffer(M.__webglColorRenderbuffer[Q])}if(M.__webglDepthRenderbuffer)e.deleteRenderbuffer(M.__webglDepthRenderbuffer)}let V=C.textures;for(let Q=0,he=V.length;Q<he;Q++){let ge=i.get(V[Q]);if(ge.__webglTexture)e.deleteTexture(ge.__webglTexture),a.memory.textures--;i.remove(V[Q])}i.remove(C)}let I=0;function U(){I=0}function N(){return I}function F(C){I=C}function D(){let C=I;if(C>=r.maxTextures)je("WebGLTextures: Trying to use "+(C+1)+" texture units while this GPU supports only "+r.maxTextures);return I+=1,C}function O(C){let M=[];return M.push(C.wrapS),M.push(C.wrapT),M.push(C.wrapR||0),M.push(C.magFilter),M.push(C.minFilter),M.push(C.anisotropy),M.push(C.internalFormat),M.push(C.format),M.push(C.type),M.push(C.generateMipmaps),M.push(C.premultiplyAlpha),M.push(C.flipY),M.push(C.unpackAlignment),M.push(C.colorSpace),M.join()}function K(C,M){let V=i.get(C);if(C.isVideoTexture)yn(C);if(C.isRenderTargetTexture===!1&&C.isExternalTexture!==!0&&C.version>0&&V.__version!==C.version){let Q=C.image;if(Q===null)je("WebGLRenderer: Texture marked for update but no image data found.");else if(Q.complete===!1)je("WebGLRenderer: Texture marked for update but image is incomplete");else{ne(V,C,M);return}}else if(C.isExternalTexture)V.__webglTexture=C.sourceTexture?C.sourceTexture:null;n.bindTexture(e.TEXTURE_2D,V.__webglTexture,e.TEXTURE0+M)}function B(C,M){let V=i.get(C);if(C.isRenderTargetTexture===!1&&C.version>0&&V.__version!==C.version){ne(V,C,M);return}else if(C.isExternalTexture)V.__webglTexture=C.sourceTexture?C.sourceTexture:null;n.bindTexture(e.TEXTURE_2D_ARRAY,V.__webglTexture,e.TEXTURE0+M)}function X(C,M){let V=i.get(C);if(C.isRenderTargetTexture===!1&&C.version>0&&V.__version!==C.version){ne(V,C,M);return}n.bindTexture(e.TEXTURE_3D,V.__webglTexture,e.TEXTURE0+M)}function q(C,M){let V=i.get(C);if(C.isCubeDepthTexture!==!0&&C.version>0&&V.__version!==C.version){ie(V,C,M);return}n.bindTexture(e.TEXTURE_CUBE_MAP,V.__webglTexture,e.TEXTURE0+M)}let le={[Mo]:e.REPEAT,[Ro]:e.CLAMP_TO_EDGE,[fd]:e.MIRRORED_REPEAT},de={[Bi]:e.NEAREST,[hd]:e.NEAREST_MIPMAP_NEAREST,[_a]:e.NEAREST_MIPMAP_LINEAR,[En]:e.LINEAR,[Io]:e.LINEAR_MIPMAP_NEAREST,[fr]:e.LINEAR_MIPMAP_LINEAR},Me={[DT]:e.NEVER,[zT]:e.ALWAYS,[LT]:e.LESS,[vd]:e.LEQUAL,[FT]:e.EQUAL,[Ed]:e.GEQUAL,[UT]:e.GREATER,[BT]:e.NOTEQUAL};function pe(C,M){if(M.type===Br&&t.has("OES_texture_float_linear")===!1&&(M.magFilter===En||M.magFilter===Io||M.magFilter===_a||M.magFilter===fr||M.minFilter===En||M.minFilter===Io||M.minFilter===_a||M.minFilter===fr))je("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.");if(e.texParameteri(C,e.TEXTURE_WRAP_S,le[M.wrapS]),e.texParameteri(C,e.TEXTURE_WRAP_T,le[M.wrapT]),C===e.TEXTURE_3D||C===e.TEXTURE_2D_ARRAY)e.texParameteri(C,e.TEXTURE_WRAP_R,le[M.wrapR]);if(e.texParameteri(C,e.TEXTURE_MAG_FILTER,de[M.magFilter]),e.texParameteri(C,e.TEXTURE_MIN_FILTER,de[M.minFilter]),M.compareFunction)e.texParameteri(C,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(C,e.TEXTURE_COMPARE_FUNC,Me[M.compareFunction]);if(t.has("EXT_texture_filter_anisotropic")===!0){if(M.magFilter===Bi)return;if(M.minFilter!==_a&&M.minFilter!==fr)return;if(M.type===Br&&t.has("OES_texture_float_linear")===!1)return;if(M.anisotropy>1||i.get(M).__currentAnisotropy){let V=t.get("EXT_texture_filter_anisotropic");e.texParameterf(C,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,r.getMaxAnisotropy())),i.get(M).__currentAnisotropy=M.anisotropy}}}function J(C,M){let V=!1;if(C.__webglInit===void 0)C.__webglInit=!0,M.addEventListener("dispose",A);let Q=M.source,he=h.get(Q);if(he===void 0)he={},h.set(Q,he);let ge=O(M);if(ge!==C.__cacheKey){if(he[ge]===void 0)he[ge]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,V=!0;he[ge].usedTimes++;let ve=he[C.__cacheKey];if(ve!==void 0){if(he[C.__cacheKey].usedTimes--,ve.usedTimes===0)P(M)}C.__cacheKey=ge,C.__webglTexture=he[ge].texture}return V}function L(C,M,V){return Math.floor(Math.floor(C/V)/M)}function W(C,M,V,Q){let ge=C.updateRanges;if(ge.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,M.width,M.height,V,Q,M.data);else{ge.sort((Ve,Ee)=>Ve.start-Ee.start);let ve=0;for(let Ve=1;Ve<ge.length;Ve++){let Ee=ge[ve],me=ge[Ve],Ge=Ee.start+Ee.count,Xe=L(me.start,M.width,4),vt=L(Ee.start,M.width,4);if(me.start<=Ge+1&&Xe===vt&&L(me.start+me.count-1,M.width,4)===Xe)Ee.count=Math.max(Ee.count,me.start+me.count-Ee.start);else++ve,ge[ve]=me}ge.length=ve+1;let re=n.getParameter(e.UNPACK_ROW_LENGTH),oe=n.getParameter(e.UNPACK_SKIP_PIXELS),Ie=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,M.width);for(let Ve=0,Ee=ge.length;Ve<Ee;Ve++){let me=ge[Ve],Ge=Math.floor(me.start/4),Xe=Math.ceil(me.count/4),vt=Ge%M.width,G=Math.floor(Ge/M.width),xe=Xe,ae=1;n.pixelStorei(e.UNPACK_SKIP_PIXELS,vt),n.pixelStorei(e.UNPACK_SKIP_ROWS,G),n.texSubImage2D(e.TEXTURE_2D,0,vt,G,xe,1,V,Q,M.data)}C.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,re),n.pixelStorei(e.UNPACK_SKIP_PIXELS,oe),n.pixelStorei(e.UNPACK_SKIP_ROWS,Ie)}}function ne(C,M,V){let Q=e.TEXTURE_2D;if(M.isDataArrayTexture||M.isCompressedArrayTexture)Q=e.TEXTURE_2D_ARRAY;if(M.isData3DTexture)Q=e.TEXTURE_3D;let he=J(C,M),ge=M.source;n.bindTexture(Q,C.__webglTexture,e.TEXTURE0+V);let ve=i.get(ge);if(ge.version!==ve.__version||he===!0){if(n.activeTexture(e.TEXTURE0+V),(typeof ImageBitmap<"u"&&M.image instanceof ImageBitmap)===!1){let ae=ot.getPrimaries(ot.workingColorSpace),ye=M.colorSpace===Aa?null:ot.getPrimaries(M.colorSpace),Ce=M.colorSpace===Aa||ae===ye?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,M.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ce)}n.pixelStorei(e.UNPACK_ALIGNMENT,M.unpackAlignment);let oe=g(M.image,!1,r.maxTextureSize);oe=St(M,oe);let Ie=s.convert(M.format,M.colorSpace),Ve=s.convert(M.type),Ee=y(M.internalFormat,Ie,Ve,M.normalized,M.colorSpace,M.isVideoTexture);pe(Q,M);let me,Ge=M.mipmaps,Xe=M.isVideoTexture!==!0,vt=ve.__version===void 0||he===!0,G=ge.dataReady,xe=T(M,oe);if(M.isDepthTexture){if(Ee=v(M.format===Ea,M.type),vt)if(Xe)n.texStorage2D(e.TEXTURE_2D,1,Ee,oe.width,oe.height);else n.texImage2D(e.TEXTURE_2D,0,Ee,oe.width,oe.height,0,Ie,Ve,null)}else if(M.isDataTexture)if(Ge.length>0){if(Xe&&vt)n.texStorage2D(e.TEXTURE_2D,xe,Ee,Ge[0].width,Ge[0].height);for(let ae=0,ye=Ge.length;ae<ye;ae++)if(me=Ge[ae],Xe){if(G)n.texSubImage2D(e.TEXTURE_2D,ae,0,0,me.width,me.height,Ie,Ve,me.data)}else n.texImage2D(e.TEXTURE_2D,ae,Ee,me.width,me.height,0,Ie,Ve,me.data);M.generateMipmaps=!1}else if(Xe){if(vt)n.texStorage2D(e.TEXTURE_2D,xe,Ee,oe.width,oe.height);if(G)W(M,oe,Ie,Ve)}else n.texImage2D(e.TEXTURE_2D,0,Ee,oe.width,oe.height,0,Ie,Ve,oe.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){if(Xe&&vt)n.texStorage3D(e.TEXTURE_2D_ARRAY,xe,Ee,Ge[0].width,Ge[0].height,oe.depth);for(let ae=0,ye=Ge.length;ae<ye;ae++)if(me=Ge[ae],M.format!==pr)if(Ie!==null)if(Xe){if(G)if(M.layerUpdates.size>0){let Ce=Jm(me.width,me.height,M.format,M.type);for(let fe of M.layerUpdates){let Ae=me.data.subarray(fe*Ce/me.data.BYTES_PER_ELEMENT,(fe+1)*Ce/me.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,ae,0,0,fe,me.width,me.height,1,Ie,Ae)}}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,ae,0,0,0,me.width,me.height,oe.depth,Ie,me.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,ae,Ee,me.width,me.height,oe.depth,0,me.data,0,0);else je("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(Xe){if(G)n.texSubImage3D(e.TEXTURE_2D_ARRAY,ae,0,0,0,me.width,me.height,oe.depth,Ie,Ve,me.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,ae,Ee,me.width,me.height,oe.depth,0,Ie,Ve,me.data);if(M.layerUpdates.size>0)M.clearLayerUpdates()}else{if(Xe&&vt)n.texStorage2D(e.TEXTURE_2D,xe,Ee,Ge[0].width,Ge[0].height);for(let ae=0,ye=Ge.length;ae<ye;ae++)if(me=Ge[ae],M.format!==pr)if(Ie!==null)if(Xe){if(G)n.compressedTexSubImage2D(e.TEXTURE_2D,ae,0,0,me.width,me.height,Ie,me.data)}else n.compressedTexImage2D(e.TEXTURE_2D,ae,Ee,me.width,me.height,0,me.data);else je("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(Xe){if(G)n.texSubImage2D(e.TEXTURE_2D,ae,0,0,me.width,me.height,Ie,Ve,me.data)}else n.texImage2D(e.TEXTURE_2D,ae,Ee,me.width,me.height,0,Ie,Ve,me.data)}else if(M.isDataArrayTexture)if(Xe){if(vt)n.texStorage3D(e.TEXTURE_2D_ARRAY,xe,Ee,oe.width,oe.height,oe.depth);if(G)if(M.layerUpdates.size>0){let ae=Jm(oe.width,oe.height,M.format,M.type);for(let ye of M.layerUpdates){let Ce=oe.data.subarray(ye*ae/oe.data.BYTES_PER_ELEMENT,(ye+1)*ae/oe.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,ye,oe.width,oe.height,1,Ie,Ve,Ce)}M.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,oe.width,oe.height,oe.depth,Ie,Ve,oe.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,Ee,oe.width,oe.height,oe.depth,0,Ie,Ve,oe.data);else if(M.isData3DTexture)if(Xe){if(vt)n.texStorage3D(e.TEXTURE_3D,xe,Ee,oe.width,oe.height,oe.depth);if(G)n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,oe.width,oe.height,oe.depth,Ie,Ve,oe.data)}else n.texImage3D(e.TEXTURE_3D,0,Ee,oe.width,oe.height,oe.depth,0,Ie,Ve,oe.data);else if(M.isFramebufferTexture){if(vt)if(Xe)n.texStorage2D(e.TEXTURE_2D,xe,Ee,oe.width,oe.height);else{let ae=oe.width,ye=oe.height;for(let Ce=0;Ce<xe;Ce++)n.texImage2D(e.TEXTURE_2D,Ce,Ee,ae,ye,0,Ie,Ve,null),ae>>=1,ye>>=1}}else if(M.isHTMLTexture){if("texElementImage2D"in e){let ae=e.canvas;if(!ae.hasAttribute("layoutsubtree"))ae.setAttribute("layoutsubtree","true");if(oe.parentNode!==ae){ae.appendChild(oe),d.add(M),ae.onpaint=(ye)=>{let Ce=ye.changedElements;for(let fe of d)if(Ce.includes(fe.image))fe.needsUpdate=!0},ae.requestPaint();return}if(e.texElementImage2D.length===3)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,oe);else{let{RGBA:Ce,RGBA:fe,UNSIGNED_BYTE:Ae}=e;e.texElementImage2D(e.TEXTURE_2D,0,Ce,fe,Ae,oe)}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(Ge.length>0){if(Xe&&vt){let ae=Xt(Ge[0]);n.texStorage2D(e.TEXTURE_2D,xe,Ee,ae.width,ae.height)}for(let ae=0,ye=Ge.length;ae<ye;ae++)if(me=Ge[ae],Xe){if(G)n.texSubImage2D(e.TEXTURE_2D,ae,0,0,Ie,Ve,me)}else n.texImage2D(e.TEXTURE_2D,ae,Ee,Ie,Ve,me);M.generateMipmaps=!1}else if(Xe){if(vt){let ae=Xt(oe);n.texStorage2D(e.TEXTURE_2D,xe,Ee,ae.width,ae.height)}if(G)n.texSubImage2D(e.TEXTURE_2D,0,0,0,Ie,Ve,oe)}else n.texImage2D(e.TEXTURE_2D,0,Ee,Ie,Ve,oe);if(p(M))x(Q);if(ve.__version=ge.version,M.onUpdate)M.onUpdate(M)}C.__version=M.version}function ie(C,M,V){if(M.image.length!==6)return;let Q=J(C,M),he=M.source;n.bindTexture(e.TEXTURE_CUBE_MAP,C.__webglTexture,e.TEXTURE0+V);let ge=i.get(he);if(he.version!==ge.__version||Q===!0){n.activeTexture(e.TEXTURE0+V);let ve=ot.getPrimaries(ot.workingColorSpace),re=M.colorSpace===Aa?null:ot.getPrimaries(M.colorSpace),oe=M.colorSpace===Aa||ve===re?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,M.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,M.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,oe);let Ie=M.isCompressedTexture||M.image[0].isCompressedTexture,Ve=M.image[0]&&M.image[0].isDataTexture,Ee=[];for(let fe=0;fe<6;fe++){if(!Ie&&!Ve)Ee[fe]=g(M.image[fe],!0,r.maxCubemapSize);else Ee[fe]=Ve?M.image[fe].image:M.image[fe];Ee[fe]=St(M,Ee[fe])}let me=Ee[0],Ge=s.convert(M.format,M.colorSpace),Xe=s.convert(M.type),vt=y(M.internalFormat,Ge,Xe,M.normalized,M.colorSpace),G=M.isVideoTexture!==!0,xe=ge.__version===void 0||Q===!0,ae=he.dataReady,ye=T(M,me);pe(e.TEXTURE_CUBE_MAP,M);let Ce;if(Ie){if(G&&xe)n.texStorage2D(e.TEXTURE_CUBE_MAP,ye,vt,me.width,me.height);for(let fe=0;fe<6;fe++){Ce=Ee[fe].mipmaps;for(let Ae=0;Ae<Ce.length;Ae++){let it=Ce[Ae];if(M.format!==pr)if(Ge!==null)if(G){if(ae)n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae,0,0,it.width,it.height,Ge,it.data)}else n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae,vt,it.width,it.height,0,it.data);else je("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()");else if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae,0,0,it.width,it.height,Ge,Xe,it.data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae,vt,it.width,it.height,0,Ge,Xe,it.data)}}}else{if(Ce=M.mipmaps,G&&xe){if(Ce.length>0)ye++;let fe=Xt(Ee[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,ye,vt,fe.width,fe.height)}for(let fe=0;fe<6;fe++)if(Ve){if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0,0,0,Ee[fe].width,Ee[fe].height,Ge,Xe,Ee[fe].data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0,vt,Ee[fe].width,Ee[fe].height,0,Ge,Xe,Ee[fe].data);for(let Ae=0;Ae<Ce.length;Ae++){let zt=Ce[Ae].image[fe].image;if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae+1,0,0,zt.width,zt.height,Ge,Xe,zt.data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae+1,vt,zt.width,zt.height,0,Ge,Xe,zt.data)}}else{if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0,0,0,Ge,Xe,Ee[fe])}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0,vt,Ge,Xe,Ee[fe]);for(let Ae=0;Ae<Ce.length;Ae++){let it=Ce[Ae];if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae+1,0,0,Ge,Xe,it.image[fe])}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae+1,vt,Ge,Xe,it.image[fe])}}}if(p(M))x(e.TEXTURE_CUBE_MAP);if(ge.__version=he.version,M.onUpdate)M.onUpdate(M)}C.__version=M.version}function ce(C,M,V,Q,he,ge){let ve=s.convert(V.format,V.colorSpace),re=s.convert(V.type),oe=y(V.internalFormat,ve,re,V.normalized,V.colorSpace),Ie=i.get(M),Ve=i.get(V);if(Ve.__renderTarget=M,!Ie.__hasExternalTextures){let Ee=Math.max(1,M.width>>ge),me=Math.max(1,M.height>>ge);if(he===e.TEXTURE_3D||he===e.TEXTURE_2D_ARRAY)n.texImage3D(he,ge,oe,Ee,me,M.depth,0,ve,re,null);else n.texImage2D(he,ge,oe,Ee,me,0,ve,re,null)}if(n.bindFramebuffer(e.FRAMEBUFFER,C),z(M))o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,Q,he,Ve.__webglTexture,0,nn(M));else if(he===e.TEXTURE_2D||he>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&he<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)e.framebufferTexture2D(e.FRAMEBUFFER,Q,he,Ve.__webglTexture,ge);n.bindFramebuffer(e.FRAMEBUFFER,null)}function _e(C,M,V){if(e.bindRenderbuffer(e.RENDERBUFFER,C),M.depthBuffer){let Q=M.depthTexture,he=Q&&Q.isDepthTexture?Q.type:null,ge=v(M.stencilBuffer,he),ve=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(z(M))o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,nn(M),ge,M.width,M.height);else if(V)e.renderbufferStorageMultisample(e.RENDERBUFFER,nn(M),ge,M.width,M.height);else e.renderbufferStorage(e.RENDERBUFFER,ge,M.width,M.height);e.framebufferRenderbuffer(e.FRAMEBUFFER,ve,e.RENDERBUFFER,C)}else{let Q=M.textures;for(let he=0;he<Q.length;he++){let ge=Q[he],ve=s.convert(ge.format,ge.colorSpace),re=s.convert(ge.type),oe=y(ge.internalFormat,ve,re,ge.normalized,ge.colorSpace);if(z(M))o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,nn(M),oe,M.width,M.height);else if(V)e.renderbufferStorageMultisample(e.RENDERBUFFER,nn(M),oe,M.width,M.height);else e.renderbufferStorage(e.RENDERBUFFER,oe,M.width,M.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function Re(C,M,V){let Q=M.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,C),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");let he=i.get(M.depthTexture);if(he.__renderTarget=M,!he.__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0;if(Q){if(he.__webglInit===void 0)he.__webglInit=!0,M.depthTexture.addEventListener("dispose",A);if(he.__webglTexture===void 0){he.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,he.__webglTexture),pe(e.TEXTURE_CUBE_MAP,M.depthTexture);let Ie=s.convert(M.depthTexture.format),Ve=s.convert(M.depthTexture.type),Ee;if(M.depthTexture.format===va)Ee=e.DEPTH_COMPONENT24;else if(M.depthTexture.format===Ea)Ee=e.DEPTH24_STENCIL8;for(let me=0;me<6;me++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,Ee,M.width,M.height,0,Ie,Ve,null)}}else K(M.depthTexture,0);let ge=he.__webglTexture,ve=nn(M),re=Q?e.TEXTURE_CUBE_MAP_POSITIVE_X+V:e.TEXTURE_2D,oe=M.depthTexture.format===Ea?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(M.depthTexture.format===va)if(z(M))o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,oe,re,ge,0,ve);else e.framebufferTexture2D(e.FRAMEBUFFER,oe,re,ge,0);else if(M.depthTexture.format===Ea)if(z(M))o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,oe,re,ge,0,ve);else e.framebufferTexture2D(e.FRAMEBUFFER,oe,re,ge,0);else throw Error("THREE.WebGLTextures: Unknown depthTexture format.")}function Oe(C){let M=i.get(C),V=C.isWebGLCubeRenderTarget===!0;if(M.__boundDepthTexture!==C.depthTexture){let Q=C.depthTexture;if(M.__depthDisposeCallback)M.__depthDisposeCallback();if(Q){let he=()=>{delete M.__boundDepthTexture,delete M.__depthDisposeCallback,Q.removeEventListener("dispose",he)};Q.addEventListener("dispose",he),M.__depthDisposeCallback=he}M.__boundDepthTexture=Q}if(C.depthTexture&&!M.__autoAllocateDepthBuffer)if(V)for(let Q=0;Q<6;Q++)Re(M.__webglFramebuffer[Q],C,Q);else{let Q=C.texture.mipmaps;if(Q&&Q.length>0)Re(M.__webglFramebuffer[0],C,0);else Re(M.__webglFramebuffer,C,0)}else if(V){M.__webglDepthbuffer=[];for(let Q=0;Q<6;Q++)if(n.bindFramebuffer(e.FRAMEBUFFER,M.__webglFramebuffer[Q]),M.__webglDepthbuffer[Q]===void 0)M.__webglDepthbuffer[Q]=e.createRenderbuffer(),_e(M.__webglDepthbuffer[Q],C,!1);else{let he=C.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ge=M.__webglDepthbuffer[Q];e.bindRenderbuffer(e.RENDERBUFFER,ge),e.framebufferRenderbuffer(e.FRAMEBUFFER,he,e.RENDERBUFFER,ge)}}else{let Q=C.texture.mipmaps;if(Q&&Q.length>0)n.bindFramebuffer(e.FRAMEBUFFER,M.__webglFramebuffer[0]);else n.bindFramebuffer(e.FRAMEBUFFER,M.__webglFramebuffer);if(M.__webglDepthbuffer===void 0)M.__webglDepthbuffer=e.createRenderbuffer(),_e(M.__webglDepthbuffer,C,!1);else{let he=C.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ge=M.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,ge),e.framebufferRenderbuffer(e.FRAMEBUFFER,he,e.RENDERBUFFER,ge)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function We(C,M,V){let Q=i.get(C);if(M!==void 0)ce(Q.__webglFramebuffer,C,C.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0);if(V!==void 0)Oe(C)}function Ye(C){let M=C.texture,V=i.get(C),Q=i.get(M);C.addEventListener("dispose",E);let he=C.textures,ge=C.isWebGLCubeRenderTarget===!0,ve=he.length>1;if(!ve){if(Q.__webglTexture===void 0)Q.__webglTexture=e.createTexture();Q.__version=M.version,a.memory.textures++}if(ge){V.__webglFramebuffer=[];for(let re=0;re<6;re++)if(M.mipmaps&&M.mipmaps.length>0){V.__webglFramebuffer[re]=[];for(let oe=0;oe<M.mipmaps.length;oe++)V.__webglFramebuffer[re][oe]=e.createFramebuffer()}else V.__webglFramebuffer[re]=e.createFramebuffer()}else{if(M.mipmaps&&M.mipmaps.length>0){V.__webglFramebuffer=[];for(let re=0;re<M.mipmaps.length;re++)V.__webglFramebuffer[re]=e.createFramebuffer()}else V.__webglFramebuffer=e.createFramebuffer();if(ve)for(let re=0,oe=he.length;re<oe;re++){let Ie=i.get(he[re]);if(Ie.__webglTexture===void 0)Ie.__webglTexture=e.createTexture(),a.memory.textures++}if(C.samples>0&&z(C)===!1){V.__webglMultisampledFramebuffer=e.createFramebuffer(),V.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let re=0;re<he.length;re++){let oe=he[re];V.__webglColorRenderbuffer[re]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,V.__webglColorRenderbuffer[re]);let Ie=s.convert(oe.format,oe.colorSpace),Ve=s.convert(oe.type),Ee=y(oe.internalFormat,Ie,Ve,oe.normalized,oe.colorSpace,C.isXRRenderTarget===!0),me=nn(C);e.renderbufferStorageMultisample(e.RENDERBUFFER,me,Ee,C.width,C.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+re,e.RENDERBUFFER,V.__webglColorRenderbuffer[re])}if(e.bindRenderbuffer(e.RENDERBUFFER,null),C.depthBuffer)V.__webglDepthRenderbuffer=e.createRenderbuffer(),_e(V.__webglDepthRenderbuffer,C,!0);n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(ge){n.bindTexture(e.TEXTURE_CUBE_MAP,Q.__webglTexture),pe(e.TEXTURE_CUBE_MAP,M);for(let re=0;re<6;re++)if(M.mipmaps&&M.mipmaps.length>0)for(let oe=0;oe<M.mipmaps.length;oe++)ce(V.__webglFramebuffer[re][oe],C,M,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+re,oe);else ce(V.__webglFramebuffer[re],C,M,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+re,0);if(p(M))x(e.TEXTURE_CUBE_MAP);n.unbindTexture()}else if(ve){for(let re=0,oe=he.length;re<oe;re++){let Ie=he[re],Ve=i.get(Ie),Ee=e.TEXTURE_2D;if(C.isWebGL3DRenderTarget||C.isWebGLArrayRenderTarget)Ee=C.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY;if(n.bindTexture(Ee,Ve.__webglTexture),pe(Ee,Ie),ce(V.__webglFramebuffer,C,Ie,e.COLOR_ATTACHMENT0+re,Ee,0),p(Ie))x(Ee)}n.unbindTexture()}else{let re=e.TEXTURE_2D;if(C.isWebGL3DRenderTarget||C.isWebGLArrayRenderTarget)re=C.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY;if(n.bindTexture(re,Q.__webglTexture),pe(re,M),M.mipmaps&&M.mipmaps.length>0)for(let oe=0;oe<M.mipmaps.length;oe++)ce(V.__webglFramebuffer[oe],C,M,e.COLOR_ATTACHMENT0,re,oe);else ce(V.__webglFramebuffer,C,M,e.COLOR_ATTACHMENT0,re,0);if(p(M))x(re);n.unbindTexture()}if(C.depthBuffer)Oe(C)}function Wt(C){let M=C.textures;for(let V=0,Q=M.length;V<Q;V++){let he=M[V];if(p(he)){let ge=_(C),ve=i.get(he).__webglTexture;n.bindTexture(ge,ve),x(ge),n.unbindTexture()}}}let lt=[],Lt=[];function Qt(C){if(C.samples>0){if(z(C)===!1){let{textures:M,width:V,height:Q}=C,he=e.COLOR_BUFFER_BIT,ge=C.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ve=i.get(C),re=M.length>1;if(re)for(let Ie=0;Ie<M.length;Ie++)n.bindFramebuffer(e.FRAMEBUFFER,ve.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ie,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,ve.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ie,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,ve.__webglMultisampledFramebuffer);let oe=C.texture.mipmaps;if(oe&&oe.length>0)n.bindFramebuffer(e.DRAW_FRAMEBUFFER,ve.__webglFramebuffer[0]);else n.bindFramebuffer(e.DRAW_FRAMEBUFFER,ve.__webglFramebuffer);for(let Ie=0;Ie<M.length;Ie++){if(C.resolveDepthBuffer){if(C.depthBuffer)he|=e.DEPTH_BUFFER_BIT;if(C.stencilBuffer&&C.resolveStencilBuffer)he|=e.STENCIL_BUFFER_BIT}if(re){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,ve.__webglColorRenderbuffer[Ie]);let Ve=i.get(M[Ie]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,Ve,0)}if(e.blitFramebuffer(0,0,V,Q,0,0,V,Q,he,e.NEAREST),c===!0){if(lt.length=0,Lt.length=0,lt.push(e.COLOR_ATTACHMENT0+Ie),C.depthBuffer&&C.storeMultisampledDepthBuffer===!1)lt.push(ge),Lt.push(ge),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,Lt);e.invalidateFramebuffer(e.READ_FRAMEBUFFER,lt)}}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),re)for(let Ie=0;Ie<M.length;Ie++){n.bindFramebuffer(e.FRAMEBUFFER,ve.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ie,e.RENDERBUFFER,ve.__webglColorRenderbuffer[Ie]);let Ve=i.get(M[Ie]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,ve.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ie,e.TEXTURE_2D,Ve,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,ve.__webglMultisampledFramebuffer)}else if(C.depthBuffer&&C.storeMultisampledDepthBuffer===!1&&c){let M=C.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[M])}}}function nn(C){return Math.min(r.maxSamples,C.samples)}function z(C){let M=i.get(C);return C.samples>0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function yn(C){let M=a.render.frame;if(u.get(C)!==M)u.set(C,M),C.update()}function St(C,M){let{colorSpace:V,format:Q,type:he}=C;if(C.isCompressedTexture===!0||C.isVideoTexture===!0)return M;if(V!==oi&&V!==Aa)if(ot.getTransfer(V)===Bt){if(Q!==pr||he!==zi)je("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}else Ze("WebGLTextures: Unsupported texture color space:",V);return M}function Xt(C){if(typeof HTMLImageElement<"u"&&C instanceof HTMLImageElement)l.width=C.naturalWidth||C.width,l.height=C.naturalHeight||C.height;else if(typeof VideoFrame<"u"&&C instanceof VideoFrame)l.width=C.displayWidth,l.height=C.displayHeight;else l.width=C.width,l.height=C.height;return l}this.allocateTextureUnit=D,this.resetTextureUnits=U,this.getTextureUnits=N,this.setTextureUnits=F,this.setTexture2D=K,this.setTexture2DArray=B,this.setTexture3D=X,this.setTextureCube=q,this.rebindTextures=We,this.setupRenderTarget=Ye,this.updateRenderTargetMipmap=Wt,this.updateMultisampleRenderTarget=Qt,this.setupDepthRenderbuffer=Oe,this.setupFrameBufferTexture=ce,this.useMultisampledRTT=z,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function QL(e,t){function n(i,r=Aa){let s,a=ot.getTransfer(r);if(i===zi)return e.UNSIGNED_BYTE;if(i===jp)return e.UNSIGNED_SHORT_4_4_4_4;if(i===Hp)return e.UNSIGNED_SHORT_5_5_5_1;if(i===IT)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===CT)return e.UNSIGNED_INT_10F_11F_11F_REV;if(i===MT)return e.BYTE;if(i===RT)return e.SHORT;if(i===Jc)return e.UNSIGNED_SHORT;if(i===Vp)return e.INT;if(i===hs)return e.UNSIGNED_INT;if(i===Br)return e.FLOAT;if(i===hr)return e.HALF_FLOAT;if(i===NT)return e.ALPHA;if(i===PT)return e.RGB;if(i===pr)return e.RGBA;if(i===va)return e.DEPTH_COMPONENT;if(i===Ea)return e.DEPTH_STENCIL;if(i===OT)return e.RED;if(i===Gp)return e.RED_INTEGER;if(i===Ta)return e.RG;if(i===$p)return e.RG_INTEGER;if(i===Kp)return e.RGBA_INTEGER;if(i===pd||i===md||i===gd||i===bd)if(a===Bt)if(s=t.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===pd)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===md)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===gd)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===bd)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=t.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===pd)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===md)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===gd)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===bd)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Wp||i===Xp||i===qp||i===Jp)if(s=t.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===Wp)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Xp)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===qp)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Jp)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Zp||i===Yp||i===Qp||i===em||i===tm||i===xd||i===nm)if(s=t.get("WEBGL_compressed_texture_etc"),s!==null){if(i===Zp||i===Yp)return a===Bt?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===Qp)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===em)return s.COMPRESSED_R11_EAC;if(i===tm)return s.COMPRESSED_SIGNED_R11_EAC;if(i===xd)return s.COMPRESSED_RG11_EAC;if(i===nm)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===im||i===rm||i===sm||i===am||i===om||i===cm||i===lm||i===um||i===dm||i===fm||i===hm||i===pm||i===mm||i===gm)if(s=t.get("WEBGL_compressed_texture_astc"),s!==null){if(i===im)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===rm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===sm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===am)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===om)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===cm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===lm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===um)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===dm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===fm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===hm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===pm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===mm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===gm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===bm||i===xm||i===ym)if(s=t.get("EXT_texture_compression_bptc"),s!==null){if(i===bm)return a===Bt?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===xm)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===ym)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===_m||i===vm||i===yd||i===Em)if(s=t.get("EXT_texture_compression_rgtc"),s!==null){if(i===_m)return s.COMPRESSED_RED_RGTC1_EXT;if(i===vm)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===yd)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Em)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;if(i===Co)return e.UNSIGNED_INT_24_8;return e[i]!==void 0?e[i]:null}return{convert:n}}class PA{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new Nd(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 Ei({vertexShader:e8,fragmentShader:t8,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new jt(new cl(20,20),n)}}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}function i8(e,t){function n(g,p){if(g.matrixAutoUpdate===!0)g.updateMatrix();p.value.copy(g.matrix)}function i(g,p){if(p.color.getRGB(g.fogColor.value,km(e)),p.isFog)g.fogNear.value=p.near,g.fogFar.value=p.far;else if(p.isFogExp2)g.fogDensity.value=p.density}function r(g,p,x,_,y){if(p.isNodeMaterial)p.uniformsNeedUpdate=!1;else if(p.isMeshBasicMaterial)s(g,p);else if(p.isMeshLambertMaterial){if(s(g,p),p.envMap)g.envMapIntensity.value=p.envMapIntensity}else if(p.isMeshToonMaterial)s(g,p),d(g,p);else if(p.isMeshPhongMaterial){if(s(g,p),u(g,p),p.envMap)g.envMapIntensity.value=p.envMapIntensity}else if(p.isMeshStandardMaterial){if(s(g,p),f(g,p),p.isMeshPhysicalMaterial)h(g,p,y)}else if(p.isMeshMatcapMaterial)s(g,p),b(g,p);else if(p.isMeshDepthMaterial)s(g,p);else if(p.isMeshDistanceMaterial)s(g,p),m(g,p);else if(p.isMeshNormalMaterial)s(g,p);else if(p.isLineBasicMaterial){if(a(g,p),p.isLineDashedMaterial)o(g,p)}else if(p.isPointsMaterial)c(g,p,x,_);else if(p.isSpriteMaterial)l(g,p);else if(p.isShadowMaterial)g.color.value.copy(p.color),g.opacity.value=p.opacity;else if(p.isShaderMaterial)p.uniformsNeedUpdate=!1}function s(g,p){if(g.opacity.value=p.opacity,p.color)g.diffuse.value.copy(p.color);if(p.emissive)g.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity);if(p.map)g.map.value=p.map,n(p.map,g.mapTransform);if(p.alphaMap)g.alphaMap.value=p.alphaMap,n(p.alphaMap,g.alphaMapTransform);if(p.bumpMap){if(g.bumpMap.value=p.bumpMap,n(p.bumpMap,g.bumpMapTransform),g.bumpScale.value=p.bumpScale,p.side===kn)g.bumpScale.value*=-1}if(p.normalMap){if(g.normalMap.value=p.normalMap,n(p.normalMap,g.normalMapTransform),g.normalScale.value.copy(p.normalScale),p.side===kn)g.normalScale.value.negate()}if(p.displacementMap)g.displacementMap.value=p.displacementMap,n(p.displacementMap,g.displacementMapTransform),g.displacementScale.value=p.displacementScale,g.displacementBias.value=p.displacementBias;if(p.emissiveMap)g.emissiveMap.value=p.emissiveMap,n(p.emissiveMap,g.emissiveMapTransform);if(p.specularMap)g.specularMap.value=p.specularMap,n(p.specularMap,g.specularMapTransform);if(p.alphaTest>0)g.alphaTest.value=p.alphaTest;let x=t.get(p),{envMap:_,envMapRotation:y}=x;if(_){if(g.envMap.value=_,g.envMapRotation.value.setFromMatrix4(n8.makeRotationFromEuler(y)).transpose(),_.isCubeTexture&&_.isRenderTargetTexture===!1)g.envMapRotation.value.premultiply(kA);g.reflectivity.value=p.reflectivity,g.ior.value=p.ior,g.refractionRatio.value=p.refractionRatio}if(p.lightMap)g.lightMap.value=p.lightMap,g.lightMapIntensity.value=p.lightMapIntensity,n(p.lightMap,g.lightMapTransform);if(p.aoMap)g.aoMap.value=p.aoMap,g.aoMapIntensity.value=p.aoMapIntensity,n(p.aoMap,g.aoMapTransform)}function a(g,p){if(g.diffuse.value.copy(p.color),g.opacity.value=p.opacity,p.map)g.map.value=p.map,n(p.map,g.mapTransform)}function o(g,p){g.dashSize.value=p.dashSize,g.totalSize.value=p.dashSize+p.gapSize,g.scale.value=p.scale}function c(g,p,x,_){if(g.diffuse.value.copy(p.color),g.opacity.value=p.opacity,g.size.value=p.size*x,g.scale.value=_*0.5,p.map)g.map.value=p.map,n(p.map,g.uvTransform);if(p.alphaMap)g.alphaMap.value=p.alphaMap,n(p.alphaMap,g.alphaMapTransform);if(p.alphaTest>0)g.alphaTest.value=p.alphaTest}function l(g,p){if(g.diffuse.value.copy(p.color),g.opacity.value=p.opacity,g.rotation.value=p.rotation,p.map)g.map.value=p.map,n(p.map,g.mapTransform);if(p.alphaMap)g.alphaMap.value=p.alphaMap,n(p.alphaMap,g.alphaMapTransform);if(p.alphaTest>0)g.alphaTest.value=p.alphaTest}function u(g,p){g.specular.value.copy(p.specular),g.shininess.value=Math.max(p.shininess,0.0001)}function d(g,p){if(p.gradientMap)g.gradientMap.value=p.gradientMap}function f(g,p){if(g.metalness.value=p.metalness,p.metalnessMap)g.metalnessMap.value=p.metalnessMap,n(p.metalnessMap,g.metalnessMapTransform);if(g.roughness.value=p.roughness,p.roughnessMap)g.roughnessMap.value=p.roughnessMap,n(p.roughnessMap,g.roughnessMapTransform);if(p.envMap)g.envMapIntensity.value=p.envMapIntensity}function h(g,p,x){if(g.ior.value=p.ior,p.sheen>0){if(g.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),g.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap)g.sheenColorMap.value=p.sheenColorMap,n(p.sheenColorMap,g.sheenColorMapTransform);if(p.sheenRoughnessMap)g.sheenRoughnessMap.value=p.sheenRoughnessMap,n(p.sheenRoughnessMap,g.sheenRoughnessMapTransform)}if(p.clearcoat>0){if(g.clearcoat.value=p.clearcoat,g.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap)g.clearcoatMap.value=p.clearcoatMap,n(p.clearcoatMap,g.clearcoatMapTransform);if(p.clearcoatRoughnessMap)g.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,n(p.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform);if(p.clearcoatNormalMap){if(g.clearcoatNormalMap.value=p.clearcoatNormalMap,n(p.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===kn)g.clearcoatNormalScale.value.negate()}}if(p.dispersion>0)g.dispersion.value=p.dispersion;if(p.retroreflectivity>0)g.retroreflectivity.value=p.retroreflectivity;if(p.iridescence>0){if(g.iridescence.value=p.iridescence,g.iridescenceIOR.value=p.iridescenceIOR,g.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap)g.iridescenceMap.value=p.iridescenceMap,n(p.iridescenceMap,g.iridescenceMapTransform);if(p.iridescenceThicknessMap)g.iridescenceThicknessMap.value=p.iridescenceThicknessMap,n(p.iridescenceThicknessMap,g.iridescenceThicknessMapTransform)}if(p.transmission>0){if(g.transmission.value=p.transmission,g.transmissionSamplerMap.value=x.texture,g.transmissionSamplerSize.value.set(x.width,x.height),p.transmissionMap)g.transmissionMap.value=p.transmissionMap,n(p.transmissionMap,g.transmissionMapTransform);if(g.thickness.value=p.thickness,p.thicknessMap)g.thicknessMap.value=p.thicknessMap,n(p.thicknessMap,g.thicknessMapTransform);g.attenuationDistance.value=p.attenuationDistance,g.attenuationColor.value.copy(p.attenuationColor)}if(p.anisotropy>0){if(g.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap)g.anisotropyMap.value=p.anisotropyMap,n(p.anisotropyMap,g.anisotropyMapTransform)}if(g.specularIntensity.value=p.specularIntensity,g.specularColor.value.copy(p.specularColor),p.specularColorMap)g.specularColorMap.value=p.specularColorMap,n(p.specularColorMap,g.specularColorMapTransform);if(p.specularIntensityMap)g.specularIntensityMap.value=p.specularIntensityMap,n(p.specularIntensityMap,g.specularIntensityMapTransform)}function b(g,p){if(p.matcap)g.matcap.value=p.matcap}function m(g,p){let x=t.get(p).light;g.referencePosition.value.setFromMatrixPosition(x.matrixWorld),g.nearDistance.value=x.shadow.camera.near,g.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:r}}function r8(e,t,n,i){let r={},s={},a=[],o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(y,v){let T=v.program;i.uniformBlockBinding(y,T)}function l(y,v){let T=r[y.id];if(T===void 0)g(y),T=u(y),r[y.id]=T,y.addEventListener("dispose",x);let A=v.program;i.updateUBOMapping(y,A);let E=t.render.frame;if(s[y.id]!==E)f(y),s[y.id]=E}function u(y){let v=d();y.__bindingPointIndex=v;let T=e.createBuffer(),{__size:A,usage:E}=y;return e.bindBuffer(e.UNIFORM_BUFFER,T),e.bufferData(e.UNIFORM_BUFFER,A,E),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,v,T),T}function d(){for(let y=0;y<o;y++)if(a.indexOf(y)===-1)return a.push(y),y;return Ze("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function f(y){let v=r[y.id],{uniforms:T,__cache:A}=y;e.bindBuffer(e.UNIFORM_BUFFER,v);for(let E=0,w=T.length;E<w;E++){let P=T[E];if(Array.isArray(P))for(let S=0,I=P.length;S<I;S++)h(P[S],E,S,A);else h(P,E,0,A)}e.bindBuffer(e.UNIFORM_BUFFER,null)}function h(y,v,T,A){if(m(y,v,T,A)===!0){let{__offset:E,value:w}=y;if(Array.isArray(w)){let P=0;for(let S=0;S<w.length;S++){let I=w[S],U=p(I);if(b(I,y.__data,P),typeof I!=="number"&&typeof I!=="boolean"&&!I.isMatrix3&&!ArrayBuffer.isView(I))P+=U.storage/Float32Array.BYTES_PER_ELEMENT}}else b(w,y.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,E,y.__data)}}function b(y,v,T){if(typeof y==="number"||typeof y==="boolean")v[0]=y;else if(y.isMatrix3)v[0]=y.elements[0],v[1]=y.elements[1],v[2]=y.elements[2],v[3]=0,v[4]=y.elements[3],v[5]=y.elements[4],v[6]=y.elements[5],v[7]=0,v[8]=y.elements[6],v[9]=y.elements[7],v[10]=y.elements[8],v[11]=0;else if(ArrayBuffer.isView(y))v.set(new y.constructor(y.buffer,y.byteOffset,v.length));else y.toArray(v,T)}function m(y,v,T,A){let E=y.value,w=v+"_"+T;if(A[w]===void 0){if(typeof E==="number"||typeof E==="boolean")A[w]=E;else if(ArrayBuffer.isView(E))A[w]=E.slice();else A[w]=E.clone();return!0}else{let P=A[w];if(typeof E==="number"||typeof E==="boolean"){if(P!==E)return A[w]=E,!0}else if(ArrayBuffer.isView(E))return!0;else if(P.equals(E)===!1)return P.copy(E),!0}return!1}function g(y){let v=y.uniforms,T=0,A=16;for(let w=0,P=v.length;w<P;w++){let S=Array.isArray(v[w])?v[w]:[v[w]];for(let I=0,U=S.length;I<U;I++){let N=S[I],F=Array.isArray(N.value)?N.value:[N.value];for(let D=0,O=F.length;D<O;D++){let K=F[D],B=p(K),X=T%A,q=X%B.boundary,le=X+q;if(T+=q,le!==0&&A-le<B.storage)T+=A-le;N.__data=new Float32Array(B.storage/Float32Array.BYTES_PER_ELEMENT),N.__offset=T,T+=B.storage}}}let E=T%A;if(E>0)T+=A-E;return y.__size=T,y.__cache={},this}function p(y){let v={boundary:0,storage:0};if(typeof y==="number"||typeof y==="boolean")v.boundary=4,v.storage=4;else if(y.isVector2)v.boundary=8,v.storage=8;else if(y.isVector3||y.isColor)v.boundary=16,v.storage=12;else if(y.isVector4)v.boundary=16,v.storage=16;else if(y.isMatrix3)v.boundary=48,v.storage=48;else if(y.isMatrix4)v.boundary=64,v.storage=64;else if(y.isTexture)je("WebGLRenderer: Texture samplers can not be part of an uniforms group.");else if(ArrayBuffer.isView(y))v.boundary=16,v.storage=y.byteLength;else je("WebGLRenderer: Unsupported uniform value type.",y);return v}function x(y){let v=y.target;v.removeEventListener("dispose",x);let T=a.indexOf(v.__bindingPointIndex);a.splice(T,1),e.deleteBuffer(r[v.id]),delete r[v.id],delete s[v.id]}function _(){for(let y in r)e.deleteBuffer(r[y]);a=[],r={},s={}}return{bind:c,update:l,dispose:_}}function a8(){if(gr===null)gr=new il(s8,16,16,Ta,hr),gr.name="DFG_LUT",gr.minFilter=En,gr.magFilter=En,gr.wrapS=Ro,gr.wrapT=Ro,gr.generateMipmaps=!1,gr.needsUpdate=!0;return gr}class og{constructor(e={}){let{canvas:t=VT(),context:n=null,depth:i=!0,stencil:r=!1,alpha:s=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:c=!1,powerPreference:l="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=zi}=e;this.isWebGLRenderer=!0;let h;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");h=n.getContextAttributes().alpha}else h=s;let b=f,m=new Set([Kp,$p,Gp]),g=new Set([zi,hs,Jc,Co,jp,Hp]),p=new Uint32Array(4),x=new Int32Array(4),_=new j,y=null,v=null,T=[],A=[],E=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Ui,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let w=this,P=!1,S=null,I=null,U=null,N=null;this._outputColorSpace=ps;let F=0,D=0,O=null,K=-1,B=null,X=new Pt,q=new Pt,le=null,de=new qe(0),Me=0,{width:pe,height:J}=t,L=1,W=null,ne=null,ie=new Pt(0,0,pe,J),ce=new Pt(0,0,pe,J),_e=!1,Re=new sl,Oe=!1,We=!1,Ye=new Qe,Wt=new j,lt=new Pt,Lt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Qt=!1;function nn(){return O===null?L:1}let z=n;function yn(R,H){return t.getContext(R,H)}let St,Xt,C,M,V,Q,he,ge,ve,re,oe,Ie,Ve,Ee,me,Ge,Xe,vt,G,xe,ae,ye,Ce;try{let R={alpha:!0,depth:i,stencil:r,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if("setAttribute"in t)t.setAttribute("data-engine",`three.js r${WE}`);if(t.addEventListener("webglcontextlost",it,!1),t.addEventListener("webglcontextrestored",zt,!1),t.addEventListener("webglcontextcreationerror",Mt,!1),z===null){if(z=yn("webgl2",R),z===null)if(yn("webgl2"))throw Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.");else throw Error("THREE.WebGLRenderer: Error creating WebGL context.")}fe()}catch(R){throw t.removeEventListener("webglcontextlost",it,!1),t.removeEventListener("webglcontextrestored",zt,!1),t.removeEventListener("webglcontextcreationerror",Mt,!1),Ze("WebGLRenderer: "+R.message),R}function fe(){if(St=new hD(z),St.init(),ae=new QL(z,St),Xt=new iD(z,St,e,ae),C=new ZL(z,St),Xt.reversedDepthBuffer&&d)C.buffers.depth.setReversed(!0);I=z.createFramebuffer(),U=z.createFramebuffer(),N=z.createFramebuffer(),M=new gD(z),V=new FL,Q=new YL(z,St,C,V,Xt,ae,M),he=new fD(w),ge=new xP(z),ye=new tD(z,ge),ve=new pD(z,ge,M,ye),re=new xD(z,ve,ge,ye,M),vt=new bD(z,Xt,Q),me=new rD(V),oe=new LL(w,he,St,Xt,ye,me),Ie=new i8(w,V),Ve=new BL,Ee=new $L(St),Xe=new eD(w,he,C,re,h,o),Ge=new JL(w,re,Xt),Ce=new r8(z,M,Xt,C),G=new nD(z,St,M),xe=new mD(z,St,M),M.programs=oe.programs,w.capabilities=Xt,w.extensions=St,w.properties=V,w.renderLists=Ve,w.shadowMap=Ge,w.state=C,w.info=M}if(b!==zi)E=new _D(b,t.width,t.height,a,i,r);let Ae=new OA(w,z);this.xr=Ae,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){let R=St.get("WEBGL_lose_context");if(R)R.loseContext()},this.forceContextRestore=function(){let R=St.get("WEBGL_lose_context");if(R)R.restoreContext()},this.getPixelRatio=function(){return L},this.setPixelRatio=function(R){if(R===void 0)return;L=R,this.setSize(pe,J,!1)},this.getSize=function(R){return R.set(pe,J)},this.setSize=function(R,H,ee=!0){if(Ae.isPresenting){je("WebGLRenderer: Can't change size while VR device is presenting.");return}if(pe=R,J=H,t.width=Math.floor(R*L),t.height=Math.floor(H*L),ee===!0)t.style.width=R+"px",t.style.height=H+"px";if(E!==null)E.setSize(t.width,t.height);this.setViewport(0,0,R,H)},this.getDrawingBufferSize=function(R){return R.set(pe*L,J*L).floor()},this.setDrawingBufferSize=function(R,H,ee){pe=R,J=H,L=ee,t.width=Math.floor(R*ee),t.height=Math.floor(H*ee),this.setViewport(0,0,R,H)},this.setEffects=function(R){if(b===zi){Ze("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(R){for(let H=0;H<R.length;H++)if(R[H].isOutputPass===!0){je("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}E.setEffects(R||[])},this.getCurrentViewport=function(R){return R.copy(X)},this.getViewport=function(R){return R.copy(ie)},this.setViewport=function(R,H,ee,Z){if(R.isVector4)ie.set(R.x,R.y,R.z,R.w);else ie.set(R,H,ee,Z);C.viewport(X.copy(ie).multiplyScalar(L).round())},this.getScissor=function(R){return R.copy(ce)},this.setScissor=function(R,H,ee,Z){if(R.isVector4)ce.set(R.x,R.y,R.z,R.w);else ce.set(R,H,ee,Z);C.scissor(q.copy(ce).multiplyScalar(L).round())},this.getScissorTest=function(){return _e},this.setScissorTest=function(R){C.setScissorTest(_e=R)},this.setOpaqueSort=function(R){W=R},this.setTransparentSort=function(R){ne=R},this.getClearColor=function(R){return R.copy(Xe.getClearColor())},this.setClearColor=function(){Xe.setClearColor(...arguments)},this.getClearAlpha=function(){return Xe.getClearAlpha()},this.setClearAlpha=function(){Xe.setClearAlpha(...arguments)},this.clear=function(R=!0,H=!0,ee=!0){let Z=0;if(R){let Y=!1;if(O!==null){let Se=O.texture.format;Y=m.has(Se)}if(Y){let Se=O.texture.type,Pe=g.has(Se),we=Xe.getClearColor(),ke=Xe.getClearAlpha(),{r:ze,g:rt,b:ft}=we;if(Pe)p[0]=ze,p[1]=rt,p[2]=ft,p[3]=ke,z.clearBufferuiv(z.COLOR,0,p);else x[0]=ze,x[1]=rt,x[2]=ft,x[3]=ke,z.clearBufferiv(z.COLOR,0,x)}else Z|=z.COLOR_BUFFER_BIT}if(H)Z|=z.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0);if(ee)Z|=z.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295);if(Z!==0)z.clear(Z)},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(R){R.setRenderer(this),S=R},this.dispose=function(){t.removeEventListener("webglcontextlost",it,!1),t.removeEventListener("webglcontextrestored",zt,!1),t.removeEventListener("webglcontextcreationerror",Mt,!1),Xe.dispose(),Ve.dispose(),Ee.dispose(),V.dispose(),he.dispose(),re.dispose(),ye.dispose(),Ce.dispose(),oe.dispose(),Ae.dispose(),Ae.removeEventListener("sessionstart",Eb),Ae.removeEventListener("sessionend",Tb),na.stop()};function it(R){R.preventDefault(),$c("WebGLRenderer: Context Lost."),P=!0}function zt(){$c("WebGLRenderer: Context Restored."),P=!1;let R=M.autoReset,H=Ge.enabled,ee=Ge.autoUpdate,Z=Ge.needsUpdate,Y=Ge.type;fe(),M.autoReset=R,Ge.enabled=H,Ge.autoUpdate=ee,Ge.needsUpdate=Z,Ge.type=Y}function Mt(R){Ze("WebGLRenderer: A WebGL context could not be created. Reason: ",R.statusMessage)}function Xi(R){let H=R.target;H.removeEventListener("dispose",Xi),wr(H)}function wr(R){WR(R),V.remove(R)}function WR(R){let H=V.get(R).programs;if(H!==void 0){if(H.forEach(function(ee){oe.releaseProgram(ee)}),R.isShaderMaterial)oe.releaseShaderCache(R)}}this.renderBufferDirect=function(R,H,ee,Z,Y,Se){if(H===null)H=Lt;let Pe=Y.isMesh&&Y.matrixWorld.determinantAffine()<0,we=JR(R,H,ee,Z,Y);C.setMaterial(Z,Pe);let ke=ee.index,ze=1;if(Z.wireframe===!0){if(ke=ve.getWireframeAttribute(ee),ke===void 0)return;ze=2}let rt=ee.drawRange,ft=ee.attributes.position,De=rt.start*ze,Rt=(rt.start+rt.count)*ze;if(Se!==null)De=Math.max(De,Se.start*ze),Rt=Math.min(Rt,(Se.start+Se.count)*ze);if(ke!==null)De=Math.max(De,0),Rt=Math.min(Rt,ke.count);else if(ft!==void 0&&ft!==null)De=Math.max(De,0),Rt=Math.min(Rt,ft.count);let on=Rt-De;if(on<0||on===1/0)return;ye.setup(Y,Z,we,ee,ke);let Gt,Ft=G;if(ke!==null)Gt=ge.get(ke),Ft=xe,Ft.setIndex(Gt);if(Y.isMesh)if(Z.wireframe===!0)C.setLineWidth(Z.wireframeLinewidth*nn()),Ft.setMode(z.LINES);else Ft.setMode(z.TRIANGLES);else if(Y.isLine){let In=Z.linewidth;if(In===void 0)In=1;if(C.setLineWidth(In*nn()),Y.isLineSegments)Ft.setMode(z.LINES);else if(Y.isLineLoop)Ft.setMode(z.LINE_LOOP);else Ft.setMode(z.LINE_STRIP)}else if(Y.isPoints)Ft.setMode(z.POINTS);else if(Y.isSprite)Ft.setMode(z.TRIANGLES);if(Y.isBatchedMesh)if(!St.get("WEBGL_multi_draw")){let{_multiDrawStarts:In,_multiDrawCounts:Ne,_multiDrawCount:Fn}=Y,xt=ke?ge.get(ke).bytesPerElement:1,pi=V.get(Z).currentProgram.getUniforms();for(let qi=0;qi<Fn;qi++)pi.setValue(z,"_gl_DrawID",qi),Ft.render(In[qi]/xt,Ne[qi])}else Ft.renderMultiDraw(Y._multiDrawStarts,Y._multiDrawCounts,Y._multiDrawCount);else if(Y.isInstancedMesh)Ft.renderInstances(De,on,Y.count);else if(ee.isInstancedBufferGeometry){let In=ee._maxInstanceCount!==void 0?ee._maxInstanceCount:1/0,Ne=Math.min(ee.instanceCount,In);Ft.renderInstances(De,on,Ne)}else Ft.render(De,on)};function vb(R,H,ee,Z){if(S!==null&&R.isNodeMaterial)S.setObject(Z,R);if(Oe===!0)me.setState(R,ee,!1);if(R.transparent===!0&&R.side===vi&&R.forceSinglePass===!1)R.side=kn,R.needsUpdate=!0,Vl(R,H,Z),R.side=fs,R.needsUpdate=!0,Vl(R,H,Z),R.side=vi;else Vl(R,H,Z)}this.compile=function(R,H,ee=null){if(ee===null)ee=R;if(S!==null)S.renderStart(R,H,ee);if(v=Ee.get(ee),v.init(H),A.push(v),ee.traverseVisible(function(Y){if(Y.isLight&&Y.layers.test(H.layers)){if(v.pushLight(Y),Y.castShadow)v.pushShadow(Y)}}),R!==ee)R.traverseVisible(function(Y){if(Y.isLight&&Y.layers.test(H.layers)){if(v.pushLight(Y),Y.castShadow)v.pushShadow(Y)}});if(v.setupLights(),S!==null)S.updateLights(v.state.lightsArray);if(We=this.localClippingEnabled,Oe=me.init(this.clippingPlanes,We),Oe===!0)me.setGlobalState(this.clippingPlanes,H);if(S!==null)Ge.render(v.state.shadowsArray,ee,H);let Z=new Set;if(R.traverse(function(Y){if(!(Y.isMesh||Y.isPoints||Y.isLine||Y.isSprite))return;let Se=Y.material;if(Se)if(Array.isArray(Se))for(let Pe=0;Pe<Se.length;Pe++){let we=Se[Pe];vb(we,ee,H,Y),Z.add(we)}else vb(Se,ee,H,Y),Z.add(Se)}),v=A.pop(),S!==null)S.renderEnd();return Z},this.compileAsync=function(R,H,ee=null){let Z=this.compile(R,H,ee);return new Promise((Y)=>{function Se(){if(Z.forEach(function(Pe){let ke=V.get(Pe).currentProgram;if(ke===void 0||ke.isReady())Z.delete(Pe)}),Z.size===0){Y(R);return}setTimeout(Se,10)}if(St.get("KHR_parallel_shader_compile")!==null)Se();else setTimeout(Se,10)})};let Nf=null;function XR(R){if(Nf)Nf(R)}function Eb(){na.stop()}function Tb(){na.start()}let na=new vA;if(na.setAnimationLoop(XR),typeof self<"u")na.setContext(self);this.setAnimationLoop=function(R){Nf=R,Ae.setAnimationLoop(R),R===null?na.stop():na.start()},Ae.addEventListener("sessionstart",Eb),Ae.addEventListener("sessionend",Tb),this.render=function(R,H){if(H!==void 0&&H.isCamera!==!0){Ze("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(P===!0)return;if(S!==null)S.renderStart(R,H);let ee=Ae.enabled===!0&&Ae.isPresenting===!0,Z=E!==null&&(O===null||ee)&&E.begin(w,O);if(R.matrixWorldAutoUpdate===!0)R.updateMatrixWorld();if(H.parent===null&&H.matrixWorldAutoUpdate===!0)H.updateMatrixWorld();if(Ae.enabled===!0&&Ae.isPresenting===!0&&(E===null||E.isCompositing()===!1)){if(Ae.cameraAutoUpdate===!0)Ae.updateCamera(H);H=Ae.getCamera()}if(R.isScene===!0)R.onBeforeRender(w,R,H,O);if(v=Ee.get(R,A.length),v.init(H),v.state.textureUnits=Q.getTextureUnits(),A.push(v),Ye.multiplyMatrices(H.projectionMatrix,H.matrixWorldInverse),Re.setFromProjectionMatrix(Ye,Rm,H.reversedDepth),We=this.localClippingEnabled,Oe=me.init(this.clippingPlanes,We),y=Ve.get(R,T.length),y.init(),T.push(y),Ae.enabled===!0&&Ae.isPresenting===!0){let Pe=w.xr.getDepthSensingMesh();if(Pe!==null)Pf(Pe,H,-1/0,w.sortObjects)}if(Pf(R,H,0,w.sortObjects),y.finish(),S!==null)S.updateLights(v.state.lightsArray);if(w.sortObjects===!0)y.sort(W,ne);if(Qt=Ae.enabled===!1||Ae.isPresenting===!1||Ae.hasDepthSensing()===!1,Qt)Xe.addToRenderList(y,R);if(this.info.render.frame++,this.info.autoReset===!0)this.info.reset();if(Oe===!0)me.beginShadows();let Y=v.state.shadowsArray;if(Ge.render(Y,R,H),Oe===!0)me.endShadows();if((Z&&E.hasRenderPass())===!1){let Pe=y.opaque,we=y.transmissive;if(v.setupLights(),H.isArrayCamera){let ke=H.cameras;if(we.length>0)for(let ze=0,rt=ke.length;ze<rt;ze++){let ft=ke[ze];wb(Pe,we,R,ft)}if(Qt)Xe.render(R);for(let ze=0,rt=ke.length;ze<rt;ze++){let ft=ke[ze];Ab(y,R,ft,ft.viewport)}}else{if(we.length>0)wb(Pe,we,R,H);if(Qt)Xe.render(R);Ab(y,R,H)}}if(O!==null&&D===0)Q.updateMultisampleRenderTarget(O),Q.updateRenderTargetMipmap(O);if(Z)E.end(w);if(R.isScene===!0)R.onAfterRender(w,R,H);if(ye.resetDefaultState(),K=-1,B=null,A.pop(),A.length>0){if(v=A[A.length-1],Q.setTextureUnits(v.state.textureUnits),Oe===!0)me.setGlobalState(w.clippingPlanes,v.state.camera)}else v=null;if(T.pop(),T.length>0)y=T[T.length-1];else y=null;if(S!==null)S.renderEnd()};function Pf(R,H,ee,Z){if(R.visible===!1)return;if(R.layers.test(H.layers)){if(R.isGroup)ee=R.renderOrder;else if(R.isLOD){if(R.autoUpdate===!0)R.update(H)}else if(R.isLightProbeGrid)v.pushLightProbeGrid(R);else if(R.isLight){if(v.pushLight(R),R.castShadow)v.pushShadow(R)}else if(R.isSprite){if(!R.frustumCulled||R.intersectsFrustum(Re)){if(Z)lt.setFromMatrixPosition(R.matrixWorld).applyMatrix4(Ye);let Pe=re.update(R),we=R.material;if(we.visible)y.push(R,Pe,we,ee,lt.z,null,H)}}else if(R.isMesh||R.isLine||R.isPoints){if(!R.frustumCulled||R.intersectsFrustum(Re)){let Pe=re.update(R),we=R.material;if(Z){if(R.boundingSphere!==void 0){if(R.boundingSphere===null)R.computeBoundingSphere();lt.copy(R.boundingSphere.center)}else{if(Pe.boundingSphere===null)Pe.computeBoundingSphere();lt.copy(Pe.boundingSphere.center)}lt.applyMatrix4(R.matrixWorld).applyMatrix4(Ye)}if(Array.isArray(we)){let ke=Pe.groups;for(let ze=0,rt=ke.length;ze<rt;ze++){let ft=ke[ze],De=we[ft.materialIndex];if(De&&De.visible)y.push(R,Pe,De,ee,lt.z,ft,H)}}else if(we.visible)y.push(R,Pe,we,ee,lt.z,null,H)}}}let Se=R.children;for(let Pe=0,we=Se.length;Pe<we;Pe++)Pf(Se[Pe],H,ee,Z)}function Ab(R,H,ee,Z){let{opaque:Y,transmissive:Se,transparent:Pe}=R;if(v.setupLightsView(ee),Oe===!0)me.setGlobalState(w.clippingPlanes,ee);if(Z)C.viewport(X.copy(Z));if(Y.length>0)zl(Y,H,ee);if(Se.length>0)zl(Se,H,ee);if(Pe.length>0)zl(Pe,H,ee);C.buffers.depth.setTest(!0),C.buffers.depth.setMask(!0),C.buffers.color.setMask(!0),C.setPolygonOffset(!1)}function wb(R,H,ee,Z){if((ee.isScene===!0?ee.overrideMaterial:null)!==null)return;if(v.state.transmissionRenderTarget[Z.id]===void 0){let De=St.has("EXT_color_buffer_half_float")||St.has("EXT_color_buffer_float");v.state.transmissionRenderTarget[Z.id]=new ci(1,1,{generateMipmaps:!0,type:De?hr:zi,minFilter:fr,samples:Math.max(4,Xt.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:ot.workingColorSpace})}let Se=v.state.transmissionRenderTarget[Z.id],Pe=Z.viewport||X;Se.setSize(Pe.z*w.transmissionResolutionScale,Pe.w*w.transmissionResolutionScale);let we=w.getRenderTarget(),ke=w.getActiveCubeFace(),ze=w.getActiveMipmapLevel();if(w.setRenderTarget(Se),w.getClearColor(de),Me=w.getClearAlpha(),Me<1)w.setClearColor(16777215,0.5);if(w.clear(),Qt)Xe.render(ee);let rt=w.toneMapping;w.toneMapping=Ui;let ft=Z.viewport;if(Z.viewport!==void 0)Z.viewport=void 0;if(v.setupLightsView(Z),Oe===!0)me.setGlobalState(w.clippingPlanes,Z);if(zl(R,ee,Z),Q.updateMultisampleRenderTarget(Se),Q.updateRenderTargetMipmap(Se),St.has("WEBGL_multisampled_render_to_texture")===!1){let De=!1;for(let Rt=0,on=H.length;Rt<on;Rt++){let Gt=H[Rt],{object:Ft,geometry:In,material:Ne,group:Fn}=Gt;if(Ne.side===vi&&Ft.layers.test(Z.layers)){let xt=Ne.side;Ne.side=kn,Ne.needsUpdate=!0,Sb(Ft,ee,Z,In,Ne,Fn),Ne.side=xt,Ne.needsUpdate=!0,De=!0}}if(De===!0)Q.updateMultisampleRenderTarget(Se),Q.updateRenderTargetMipmap(Se)}if(w.setRenderTarget(we,ke,ze),w.setClearColor(de,Me),ft!==void 0)Z.viewport=ft;w.toneMapping=rt}function zl(R,H,ee){let Z=H.isScene===!0?H.overrideMaterial:null;for(let Y=0,Se=R.length;Y<Se;Y++){let Pe=R[Y],{object:we,geometry:ke,group:ze}=Pe,rt=Pe.material;if(rt.allowOverride===!0&&Z!==null)rt=Z;if(we.layers.test(ee.layers))Sb(we,H,ee,ke,rt,ze)}}function Sb(R,H,ee,Z,Y,Se){if(S!==null&&Y.isNodeMaterial)S.setObject(R,Y);if(R.onBeforeRender(w,H,ee,Z,Y,Se),R.modelViewMatrix.multiplyMatrices(ee.matrixWorldInverse,R.matrixWorld),R.normalMatrix.getNormalMatrix(R.modelViewMatrix),Y.onBeforeRender(w,H,ee,Z,R,Se),Y.transparent===!0&&Y.side===vi&&Y.forceSinglePass===!1)Y.side=kn,Y.needsUpdate=!0,w.renderBufferDirect(ee,H,Z,Y,R,Se),Y.side=fs,Y.needsUpdate=!0,w.renderBufferDirect(ee,H,Z,Y,R,Se),Y.side=vi;else w.renderBufferDirect(ee,H,Z,Y,R,Se);R.onAfterRender(w,H,ee,Z,Y,Se)}function Vl(R,H,ee){if(H.isScene!==!0)H=Lt;let Z=V.get(R),Y=v.state.lights,Se=v.state.shadowsArray,Pe=Y.state.version,we=oe.getParameters(R,Y.state,Se,H,ee,v.state.lightProbeGridArray),ke=oe.getProgramCacheKey(we),ze=Z.programs;Z.environment=R.isMeshStandardMaterial||R.isMeshLambertMaterial||R.isMeshPhongMaterial?H.environment:null,Z.fog=H.fog;let rt=R.isMeshStandardMaterial||R.isMeshLambertMaterial&&!R.envMap||R.isMeshPhongMaterial&&!R.envMap;if(Z.envMap=he.get(R.envMap||Z.environment,rt),Z.envMapRotation=Z.environment!==null&&R.envMap===null?H.environmentRotation:R.envMapRotation,ze===void 0)R.addEventListener("dispose",Xi),ze=new Map,Z.programs=ze;let ft=ze.get(ke);if(ft!==void 0){if(Z.currentProgram===ft&&Z.lightsStateVersion===Pe)return Rb(R,we),ft}else{if(we.uniforms=oe.getUniforms(R),S!==null&&R.isNodeMaterial)S.build(R,ee,we);R.onBeforeCompile(we,w),ft=oe.acquireProgram(we,ke),ze.set(ke,ft),Z.uniforms=we.uniforms}let De=Z.uniforms;if(!R.isShaderMaterial&&!R.isRawShaderMaterial||R.clipping===!0)De.clippingPlanes=me.uniform;if(Rb(R,we),Z.needsLights=YR(R),Z.lightsStateVersion=Pe,Z.needsLights)De.ambientLightColor.value=Y.state.ambient,De.lightProbe.value=Y.state.probe,De.sunLights.value=Y.state.sun,De.sunLightShadows.value=Y.state.sunShadow,De.directionalLights.value=Y.state.directional,De.directionalLightShadows.value=Y.state.directionalShadow,De.spotLights.value=Y.state.spot,De.spotLightShadows.value=Y.state.spotShadow,De.rectAreaLights.value=Y.state.rectArea,De.ltc_1.value=Y.state.rectAreaLTC1,De.ltc_2.value=Y.state.rectAreaLTC2,De.pointLights.value=Y.state.point,De.pointLightShadows.value=Y.state.pointShadow,De.hemisphereLights.value=Y.state.hemi,De.sunShadowMatrix.value=Y.state.sunShadowMatrix,De.sunShadowCascade.value=Y.state.sunShadowCascade,De.directionalShadowMatrix.value=Y.state.directionalShadowMatrix,De.spotLightMatrix.value=Y.state.spotLightMatrix,De.spotLightMap.value=Y.state.spotLightMap,De.pointShadowMatrix.value=Y.state.pointShadowMatrix;return Z.lightProbeGrid=v.state.lightProbeGridArray.length>0,Z.currentProgram=ft,Z.uniformsList=null,ft}function Mb(R){if(R.uniformsList===null){let H=R.currentProgram.getUniforms();R.uniformsList=gl.seqWithValue(H.seq,R.uniforms)}return R.uniformsList}function Rb(R,H){let ee=V.get(R);ee.outputColorSpace=H.outputColorSpace,ee.batching=H.batching,ee.batchingColor=H.batchingColor,ee.instancing=H.instancing,ee.instancingColor=H.instancingColor,ee.instancingMorph=H.instancingMorph,ee.skinning=H.skinning,ee.morphTargets=H.morphTargets,ee.morphNormals=H.morphNormals,ee.morphColors=H.morphColors,ee.morphTargetsCount=H.morphTargetsCount,ee.numClippingPlanes=H.numClippingPlanes,ee.numIntersection=H.numClipIntersection,ee.vertexAlphas=H.vertexAlphas,ee.vertexTangents=H.vertexTangents,ee.toneMapping=H.toneMapping}function qR(R,H){if(R.length===0)return null;if(R.length===1)return R[0].texture!==null?R[0]:null;_.setFromMatrixPosition(H.matrixWorld);for(let ee=0,Z=R.length;ee<Z;ee++){let Y=R[ee];if(Y.texture!==null&&Y.boundingBox.containsPoint(_))return Y}return null}function JR(R,H,ee,Z,Y){if(H.isScene!==!0)H=Lt;Q.resetTextureUnits();let Se=H.fog,Pe=Z.isMeshStandardMaterial||Z.isMeshLambertMaterial||Z.isMeshPhongMaterial?H.environment:null,we=O===null?w.outputColorSpace:O.isXRRenderTarget===!0?O.texture.colorSpace:ot.workingColorSpace,ke=Z.isMeshStandardMaterial||Z.isMeshLambertMaterial&&!Z.envMap||Z.isMeshPhongMaterial&&!Z.envMap,ze=he.get(Z.envMap||Pe,ke),rt=Z.vertexColors===!0&&!!ee.attributes.color&&ee.attributes.color.itemSize===4,ft=!!ee.attributes.tangent&&(!!Z.normalMap||Z.anisotropy>0),De=!!ee.morphAttributes.position,Rt=!!ee.morphAttributes.normal,on=!!ee.morphAttributes.color,Gt=Ui;if(Z.toneMapped){if(O===null||O.isXRRenderTarget===!0)Gt=w.toneMapping}let Ft=ee.morphAttributes.position||ee.morphAttributes.normal||ee.morphAttributes.color,In=Ft!==void 0?Ft.length:0,Ne=V.get(Z),Fn=v.state.lights;if(Oe===!0){if(We===!0||R!==B){let Vt=R===B&&Z.id===K;me.setState(Z,R,Vt)}}let xt=!1;if(Z.version===Ne.__version){if(Ne.needsLights&&Ne.lightsStateVersion!==Fn.state.version)xt=!0;else if(Ne.outputColorSpace!==we)xt=!0;else if(Y.isBatchedMesh&&Ne.batching===!1)xt=!0;else if(!Y.isBatchedMesh&&Ne.batching===!0)xt=!0;else if(Y.isBatchedMesh&&Ne.batchingColor===!0&&Y._colorsTexture===null)xt=!0;else if(Y.isBatchedMesh&&Ne.batchingColor===!1&&Y._colorsTexture!==null)xt=!0;else if(Y.isInstancedMesh&&Ne.instancing===!1)xt=!0;else if(!Y.isInstancedMesh&&Ne.instancing===!0)xt=!0;else if(Y.isSkinnedMesh&&Ne.skinning===!1)xt=!0;else if(!Y.isSkinnedMesh&&Ne.skinning===!0)xt=!0;else if(Y.isInstancedMesh&&Ne.instancingColor===!0&&Y.instanceColor===null)xt=!0;else if(Y.isInstancedMesh&&Ne.instancingColor===!1&&Y.instanceColor!==null)xt=!0;else if(Y.isInstancedMesh&&Ne.instancingMorph===!0&&Y.morphTexture===null)xt=!0;else if(Y.isInstancedMesh&&Ne.instancingMorph===!1&&Y.morphTexture!==null)xt=!0;else if(Ne.envMap!==ze)xt=!0;else if(Z.fog===!0&&Ne.fog!==Se)xt=!0;else if(Ne.numClippingPlanes!==void 0&&(Ne.numClippingPlanes!==me.numPlanes||Ne.numIntersection!==me.numIntersection))xt=!0;else if(Ne.vertexAlphas!==rt)xt=!0;else if(Ne.vertexTangents!==ft)xt=!0;else if(Ne.morphTargets!==De)xt=!0;else if(Ne.morphNormals!==Rt)xt=!0;else if(Ne.morphColors!==on)xt=!0;else if(Ne.toneMapping!==Gt)xt=!0;else if(Ne.morphTargetsCount!==In)xt=!0;else if(!!Ne.lightProbeGrid!==v.state.lightProbeGridArray.length>0)xt=!0}else xt=!0,Ne.__version=Z.version;let pi=Ne.currentProgram;if(xt===!0){if(pi=Vl(Z,H,Y),S&&Z.isNodeMaterial)S.onUpdateProgram(Z,pi,Ne)}let qi=!1,Wr=!1,za=!1,kt=pi.getUniforms(),rn=Ne.uniforms;if(C.useProgram(pi.program))qi=!0,Wr=!0,za=!0;if(Z.id!==K)K=Z.id,Wr=!0;if(Ne.needsLights){let Vt=qR(v.state.lightProbeGridArray,Y);if(Ne.lightProbeGrid!==Vt)Ne.lightProbeGrid=Vt,Wr=!0}if(qi||B!==R){if(C.buffers.depth.getReversed()&&R.reversedDepth!==!0)R._reversedDepth=!0,R.updateProjectionMatrix();kt.setValue(z,"projectionMatrix",R.projectionMatrix),kt.setValue(z,"viewMatrix",R.matrixWorldInverse);let qr=kt.map.cameraPosition;if(qr!==void 0)qr.setValue(z,Wt.setFromMatrixPosition(R.matrixWorld));if(Xt.logarithmicDepthBuffer)kt.setValue(z,"logDepthBufFC",2/(Math.log(R.far+1)/Math.LN2));if(Z.isMeshPhongMaterial||Z.isMeshToonMaterial||Z.isMeshLambertMaterial||Z.isMeshBasicMaterial||Z.isMeshStandardMaterial||Z.isShaderMaterial)kt.setValue(z,"isOrthographic",R.isOrthographicCamera===!0);if(B!==R)B=R,Wr=!0,za=!0}if(Ne.needsLights){if(Fn.state.sunShadowMap.length>0)kt.setValue(z,"sunShadowMap",Fn.state.sunShadowMap,Q);if(Fn.state.directionalShadowMap.length>0)kt.setValue(z,"directionalShadowMap",Fn.state.directionalShadowMap,Q);if(Fn.state.spotShadowMap.length>0)kt.setValue(z,"spotShadowMap",Fn.state.spotShadowMap,Q);if(Fn.state.pointShadowMap.length>0)kt.setValue(z,"pointShadowMap",Fn.state.pointShadowMap,Q)}if(Y.isSkinnedMesh){kt.setOptional(z,Y,"bindMatrix"),kt.setOptional(z,Y,"bindMatrixInverse");let Vt=Y.skeleton;if(Vt){if(Vt.boneTexture===null)Vt.computeBoneTexture();kt.setValue(z,"boneTexture",Vt.boneTexture,Q)}}if(Y.isBatchedMesh){if(kt.setOptional(z,Y,"batchingTexture"),kt.setValue(z,"batchingTexture",Y._matricesTexture,Q),kt.setOptional(z,Y,"batchingIdTexture"),kt.setValue(z,"batchingIdTexture",Y._indirectTexture,Q),kt.setOptional(z,Y,"batchingColorTexture"),Y._colorsTexture!==null)kt.setValue(z,"batchingColorTexture",Y._colorsTexture,Q)}let Xr=ee.morphAttributes;if(Xr.position!==void 0||Xr.normal!==void 0||Xr.color!==void 0)vt.update(Y,ee,pi);if(Wr||Ne.receiveShadow!==Y.receiveShadow)Ne.receiveShadow=Y.receiveShadow,kt.setValue(z,"receiveShadow",Y.receiveShadow);if((Z.isMeshStandardMaterial||Z.isMeshLambertMaterial||Z.isMeshPhongMaterial)&&Z.envMap===null&&H.environment!==null)rn.envMapIntensity.value=H.environmentIntensity;if(rn.dfgLUT!==void 0)rn.dfgLUT.value=a8();if(Wr){if(kt.setValue(z,"toneMappingExposure",w.toneMappingExposure),Ne.needsLights)ZR(rn,za);if(Se&&Z.fog===!0)Ie.refreshFogUniforms(rn,Se);if(Ie.refreshMaterialUniforms(rn,Z,L,J,v.state.transmissionRenderTarget[R.id]),Ne.needsLights&&Ne.lightProbeGrid){let Vt=Ne.lightProbeGrid;rn.probesSH.value=Vt.texture,rn.probesMin.value.copy(Vt.boundingBox.min),rn.probesMax.value.copy(Vt.boundingBox.max),rn.probesResolution.value.copy(Vt.resolution)}gl.upload(z,Mb(Ne),rn,Q)}if(Z.isShaderMaterial&&Z.uniformsNeedUpdate===!0)gl.upload(z,Mb(Ne),rn,Q),Z.uniformsNeedUpdate=!1;if(Z.isSpriteMaterial)kt.setValue(z,"center",Y.center);if(kt.setValue(z,"modelViewMatrix",Y.modelViewMatrix),kt.setValue(z,"normalMatrix",Y.normalMatrix),kt.setValue(z,"modelMatrix",Y.matrixWorld),Z.uniformsGroups!==void 0){let Vt=Z.uniformsGroups;for(let qr=0,Va=Vt.length;qr<Va;qr++){let Cb=Vt[qr];Ce.update(Cb,pi),Ce.bind(Cb,pi)}}return pi}function ZR(R,H){R.ambientLightColor.needsUpdate=H,R.lightProbe.needsUpdate=H,R.sunLights.needsUpdate=H,R.sunLightShadows.needsUpdate=H,R.directionalLights.needsUpdate=H,R.directionalLightShadows.needsUpdate=H,R.pointLights.needsUpdate=H,R.pointLightShadows.needsUpdate=H,R.spotLights.needsUpdate=H,R.spotLightShadows.needsUpdate=H,R.rectAreaLights.needsUpdate=H,R.hemisphereLights.needsUpdate=H}function YR(R){return R.isMeshLambertMaterial||R.isMeshToonMaterial||R.isMeshPhongMaterial||R.isMeshStandardMaterial||R.isShadowMaterial||R.isShaderMaterial&&R.lights===!0}this.getActiveCubeFace=function(){return F},this.getActiveMipmapLevel=function(){return D},this.getRenderTarget=function(){return O},this.setRenderTargetTextures=function(R,H,ee){let Z=V.get(R);if(Z.__autoAllocateDepthBuffer=R.resolveDepthBuffer===!1,Z.__autoAllocateDepthBuffer===!1)Z.__useRenderToTexture=!1;V.get(R.texture).__webglTexture=H,V.get(R.depthTexture).__webglTexture=Z.__autoAllocateDepthBuffer?void 0:ee,Z.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(R,H){let ee=V.get(R);ee.__webglFramebuffer=H,ee.__useDefaultFramebuffer=H===void 0},this.setRenderTarget=function(R,H=0,ee=0){O=R,F=H,D=ee;let Z=null,Y=!1,Se=!1;if(R){let we=V.get(R);if(we.__useDefaultFramebuffer!==void 0){C.bindFramebuffer(z.FRAMEBUFFER,we.__webglFramebuffer),X.copy(R.viewport),q.copy(R.scissor),le=R.scissorTest,C.viewport(X),C.scissor(q),C.setScissorTest(le),K=-1;return}else if(we.__webglFramebuffer===void 0)Q.setupRenderTarget(R);else if(we.__hasExternalTextures)Q.rebindTextures(R,V.get(R.texture).__webglTexture,V.get(R.depthTexture).__webglTexture);else if(R.depthBuffer){let rt=R.depthTexture;if(we.__boundDepthTexture!==rt){if(rt!==null&&V.has(rt)&&(R.width!==rt.image.width||R.height!==rt.image.height))throw Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");Q.setupDepthRenderbuffer(R)}}let ke=R.texture;if(ke.isData3DTexture||ke.isDataArrayTexture||ke.isCompressedArrayTexture)Se=!0;let ze=V.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget){if(Array.isArray(ze[H]))Z=ze[H][ee];else Z=ze[H];Y=!0}else if(R.samples>0&&Q.useMultisampledRTT(R)===!1)Z=V.get(R).__webglMultisampledFramebuffer;else if(Array.isArray(ze))Z=ze[ee];else Z=ze;X.copy(R.viewport),q.copy(R.scissor),le=R.scissorTest}else X.copy(ie).multiplyScalar(L).floor(),q.copy(ce).multiplyScalar(L).floor(),le=_e;if(ee!==0)Z=I;if(C.bindFramebuffer(z.FRAMEBUFFER,Z))C.drawBuffers(R,Z);if(C.viewport(X),C.scissor(q),C.setScissorTest(le),Y){let we=V.get(R.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+H,we.__webglTexture,ee)}else if(Se){let we=H;for(let ke=0;ke<R.textures.length;ke++){let ze=V.get(R.textures[ke]);z.framebufferTextureLayer(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0+ke,ze.__webglTexture,ee,we)}}else if(R!==null&&ee!==0){let we=V.get(R.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,we.__webglTexture,ee)}K=-1};function Ib(R){let H=V.get(R);if(H.__readFormat!==R.format||H.__readType!==R.type)H.__readFormat=R.format,H.__readType=R.type,H.__formatReadable=Xt.textureFormatReadable(R.format),H.__typeReadable=Xt.textureTypeReadable(R.type);return H}if(this.readRenderTargetPixels=function(R,H,ee,Z,Y,Se,Pe,we=0){if(!(R&&R.isWebGLRenderTarget)){Ze("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let ke=V.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&Pe!==void 0)ke=ke[Pe];if(ke){C.bindFramebuffer(z.FRAMEBUFFER,ke);try{let ze=R.textures[we],{format:rt,type:ft}=ze;if(R.textures.length>1)z.readBuffer(z.COLOR_ATTACHMENT0+we);let De=Ib(ze);if(De.__formatReadable===!1){Ze("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(De.__typeReadable===!1){Ze("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(H>=0&&H<=R.width-Z&&(ee>=0&&ee<=R.height-Y))z.readPixels(H,ee,Z,Y,ae.convert(rt),ae.convert(ft),Se)}finally{let ze=O!==null?V.get(O).__webglFramebuffer:null;C.bindFramebuffer(z.FRAMEBUFFER,ze)}}},this.readRenderTargetPixelsAsync=async function(R,H,ee,Z,Y,Se,Pe,we=0){if(!(R&&R.isWebGLRenderTarget))throw Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let ke=V.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&Pe!==void 0)ke=ke[Pe];if(ke)if(H>=0&&H<=R.width-Z&&(ee>=0&&ee<=R.height-Y)){C.bindFramebuffer(z.FRAMEBUFFER,ke);let ze=R.textures[we],{format:rt,type:ft}=ze;if(R.textures.length>1)z.readBuffer(z.COLOR_ATTACHMENT0+we);let De=Ib(ze);if(De.__formatReadable===!1)throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(De.__typeReadable===!1)throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Rt=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,Rt),z.bufferData(z.PIXEL_PACK_BUFFER,Se.byteLength,z.STREAM_READ),z.readPixels(H,ee,Z,Y,ae.convert(rt),ae.convert(ft),0),z.bindBuffer(z.PIXEL_PACK_BUFFER,null);let on=O!==null?V.get(O).__webglFramebuffer:null;C.bindFramebuffer(z.FRAMEBUFFER,on);let Gt=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await HT(z,Gt,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,Rt),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,Se),z.bindBuffer(z.PIXEL_PACK_BUFFER,null),z.deleteBuffer(Rt),z.deleteSync(Gt),Se}else throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(R,H=null,ee=0){let Z=Math.pow(2,-ee),Y=Math.floor(R.image.width*Z),Se=Math.floor(R.image.height*Z),Pe=H!==null?H.x:0,we=H!==null?H.y:0;Q.setTexture2D(R,0),z.copyTexSubImage2D(z.TEXTURE_2D,ee,0,0,Pe,we,Y,Se),C.unbindTexture()},this.copyTextureToTexture=function(R,H,ee=null,Z=null,Y=0,Se=0){let Pe,we,ke,ze,rt,ft,De,Rt,on,Gt=R.isCompressedTexture?R.mipmaps[Se]:R.image;if(ee!==null)Pe=ee.max.x-ee.min.x,we=ee.max.y-ee.min.y,ke=ee.isBox3?ee.max.z-ee.min.z:1,ze=ee.min.x,rt=ee.min.y,ft=ee.isBox3?ee.min.z:0;else{let rn=Math.pow(2,-Y);if(Pe=Math.floor(Gt.width*rn),we=Math.floor(Gt.height*rn),R.isDataArrayTexture)ke=Gt.depth;else if(R.isData3DTexture)ke=Math.floor(Gt.depth*rn);else ke=1;ze=0,rt=0,ft=0}if(Z!==null)De=Z.x,Rt=Z.y,on=Z.z;else De=0,Rt=0,on=0;let Ft=ae.convert(H.format),In=ae.convert(H.type),Ne;if(H.isData3DTexture)Q.setTexture3D(H,0),Ne=z.TEXTURE_3D;else if(H.isDataArrayTexture||H.isCompressedArrayTexture)Q.setTexture2DArray(H,0),Ne=z.TEXTURE_2D_ARRAY;else Q.setTexture2D(H,0),Ne=z.TEXTURE_2D;C.activeTexture(z.TEXTURE0),C.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,H.flipY),C.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,H.premultiplyAlpha),C.pixelStorei(z.UNPACK_ALIGNMENT,H.unpackAlignment);let Fn=C.getParameter(z.UNPACK_ROW_LENGTH),xt=C.getParameter(z.UNPACK_IMAGE_HEIGHT),pi=C.getParameter(z.UNPACK_SKIP_PIXELS),qi=C.getParameter(z.UNPACK_SKIP_ROWS),Wr=C.getParameter(z.UNPACK_SKIP_IMAGES);C.pixelStorei(z.UNPACK_ROW_LENGTH,Gt.width),C.pixelStorei(z.UNPACK_IMAGE_HEIGHT,Gt.height),C.pixelStorei(z.UNPACK_SKIP_PIXELS,ze),C.pixelStorei(z.UNPACK_SKIP_ROWS,rt),C.pixelStorei(z.UNPACK_SKIP_IMAGES,ft);let za=R.isDataArrayTexture||R.isData3DTexture,kt=H.isDataArrayTexture||H.isData3DTexture;if(R.isDepthTexture){let rn=V.get(R),Xr=V.get(H),Vt=V.get(rn.__renderTarget),qr=V.get(Xr.__renderTarget);C.bindFramebuffer(z.READ_FRAMEBUFFER,Vt.__webglFramebuffer),C.bindFramebuffer(z.DRAW_FRAMEBUFFER,qr.__webglFramebuffer);for(let Va=0;Va<ke;Va++){if(za)z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,V.get(R).__webglTexture,Y,ft+Va),z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,V.get(H).__webglTexture,Se,on+Va);z.blitFramebuffer(ze,rt,Pe,we,De,Rt,Pe,we,z.DEPTH_BUFFER_BIT,z.NEAREST)}C.bindFramebuffer(z.READ_FRAMEBUFFER,null),C.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if(Y!==0||R.isRenderTargetTexture||V.has(R)){let rn=V.get(R),Xr=V.get(H);C.bindFramebuffer(z.READ_FRAMEBUFFER,U),C.bindFramebuffer(z.DRAW_FRAMEBUFFER,N);for(let Vt=0;Vt<ke;Vt++){if(za)z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,rn.__webglTexture,Y,ft+Vt);else z.framebufferTexture2D(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,rn.__webglTexture,Y);if(kt)z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Xr.__webglTexture,Se,on+Vt);else z.framebufferTexture2D(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,Xr.__webglTexture,Se);if(Y!==0)z.blitFramebuffer(ze,rt,Pe,we,De,Rt,Pe,we,z.COLOR_BUFFER_BIT,z.NEAREST);else if(kt)z.copyTexSubImage3D(Ne,Se,De,Rt,on+Vt,ze,rt,Pe,we);else z.copyTexSubImage2D(Ne,Se,De,Rt,ze,rt,Pe,we)}C.bindFramebuffer(z.READ_FRAMEBUFFER,null),C.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if(kt)if(R.isDataTexture||R.isData3DTexture)z.texSubImage3D(Ne,Se,De,Rt,on,Pe,we,ke,Ft,In,Gt.data);else if(H.isCompressedArrayTexture)z.compressedTexSubImage3D(Ne,Se,De,Rt,on,Pe,we,ke,Ft,Gt.data);else z.texSubImage3D(Ne,Se,De,Rt,on,Pe,we,ke,Ft,In,Gt);else if(R.isDataTexture)z.texSubImage2D(z.TEXTURE_2D,Se,De,Rt,Pe,we,Ft,In,Gt.data);else if(R.isCompressedTexture)z.compressedTexSubImage2D(z.TEXTURE_2D,Se,De,Rt,Gt.width,Gt.height,Ft,Gt.data);else z.texSubImage2D(z.TEXTURE_2D,Se,De,Rt,Pe,we,Ft,In,Gt);if(C.pixelStorei(z.UNPACK_ROW_LENGTH,Fn),C.pixelStorei(z.UNPACK_IMAGE_HEIGHT,xt),C.pixelStorei(z.UNPACK_SKIP_PIXELS,pi),C.pixelStorei(z.UNPACK_SKIP_ROWS,qi),C.pixelStorei(z.UNPACK_SKIP_IMAGES,Wr),Se===0&&H.generateMipmaps)z.generateMipmap(Ne);C.unbindTexture()},this.initRenderTarget=function(R){if(V.get(R).__webglFramebuffer===void 0)Q.setupRenderTarget(R)},this.initTexture=function(R){if(R.isCubeTexture)Q.setTextureCube(R,0);else if(R.isData3DTexture)Q.setTexture3D(R,0);else if(R.isDataArrayTexture||R.isCompressedArrayTexture)Q.setTexture2DArray(R,0);else Q.setTexture2D(R,0);C.unbindTexture()},this.resetState=function(){F=0,D=0,O=null,C.reset(),ye.reset()},typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Rm}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=ot._getDrawingBufferColorSpace(e),t.unpackColorSpace=ot._getUnpackColorSpace()}}var yP=`#ifdef USE_ALPHAHASH+`+q)}else if(U!=="")je("WebGLProgram: Program Info Log:",U);else if(L===""||O==="")B=!1;if(B)S.diagnostics={runnable:K,programLog:U,vertexShader:{log:L,prefix:g},fragmentShader:{log:O,prefix:p}}}r.deleteShader(v),r.deleteShader(E),T=new xl(r,m),A=TL(r,m)}let T;this.getUniforms=function(){if(T===void 0)w(this);return T};let A;this.getAttributes=function(){if(A===void 0)w(this);return A};let P=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){if(P===!1)P=r.getProgramParameter(m,hL);return P},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(m),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=pL++,this.cacheKey=t,this.usedTimes=1,this.program=m,this.vertexShader=v,this.fragmentShader=E,this}class kA{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 DA(e),t.set(e,n);return n}}class DA{constructor(e){this.id=BL++,this.code=e,this.usedTimes=0}}function zL(e){return e===wa||e===vd||e===Ed}function VL(e,t,n,i,r,s){let a=new Md,o=new kA,c=new Set,l=[],u=new Map,{logarithmicDepthBuffer:d,precision:f}=i,h={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 b(T){if(c.add(T),T===0)return"uv";return`uv${T}`}function m(T,A,P,S,R,k){let C=S.fog,U=R.geometry,L=T.isMeshStandardMaterial||T.isMeshLambertMaterial||T.isMeshPhongMaterial?S.environment:null,O=T.isMeshStandardMaterial||T.isMeshLambertMaterial&&!T.envMap||T.isMeshPhongMaterial&&!T.envMap,K=t.get(T.envMap||L,O),B=!!K&&K.mapping===Zc?K.image.height:null,X=h[T.type];if(T.precision!==null){if(f=i.getMaxPrecision(T.precision),f!==T.precision)je("WebGLProgram.getParameters:",T.precision,"not supported, using",f,"instead.")}let q=U.morphAttributes.position||U.morphAttributes.normal||U.morphAttributes.color,le=q!==void 0?q.length:0,de=0;if(U.morphAttributes.position!==void 0)de=1;if(U.morphAttributes.normal!==void 0)de=2;if(U.morphAttributes.color!==void 0)de=3;let Me,pe,J,F;if(X){let zt=br[X];Me=zt.vertexShader,pe=zt.fragmentShader}else{Me=T.vertexShader,pe=T.fragmentShader;let zt=o.getVertexShaderStage(T),Mt=o.getFragmentShaderStage(T);o.update(T,zt,Mt),J=zt.id,F=Mt.id}let W=e.getRenderTarget(),ne=e.state.buffers.depth.getReversed(),ie=R.isInstancedMesh===!0,ce=R.isBatchedMesh===!0,_e=!!T.map,Re=!!T.matcap,ke=!!K,We=!!T.aoMap,Qe=!!T.lightMap,Wt=!!T.bumpMap&&T.wireframe===!1,lt=!!T.normalMap,Lt=!!T.displacementMap,Qt=!!T.emissiveMap,nn=!!T.metalnessMap,z=!!T.roughnessMap,_n=T.anisotropy>0,St=T.clearcoat>0,Xt=T.dispersion>0,N=T.retroreflectivity>0,M=T.iridescence>0,V=T.sheen>0,ee=T.transmission>0,he=_n&&!!T.anisotropyMap,ge=St&&!!T.clearcoatMap,ve=St&&!!T.clearcoatNormalMap,re=St&&!!T.clearcoatRoughnessMap,oe=M&&!!T.iridescenceMap,Ie=M&&!!T.iridescenceThicknessMap,Ve=V&&!!T.sheenColorMap,Ee=V&&!!T.sheenRoughnessMap,me=!!T.specularMap,Ge=!!T.specularColorMap,Xe=!!T.specularIntensityMap,vt=ee&&!!T.transmissionMap,G=ee&&!!T.thicknessMap,xe=!!T.gradientMap,ae=!!T.alphaMap,ye=T.alphaTest>0,Ce=!!T.alphaHash,fe=!!T.extensions,Ae=Ui;if(T.toneMapped){if(W===null||W.isXRRenderTarget===!0)Ae=e.toneMapping}let it={shaderID:X,shaderType:T.type,shaderName:T.name,vertexShader:Me,fragmentShader:pe,defines:T.defines,customVertexShaderID:J,customFragmentShaderID:F,isRawShaderMaterial:T.isRawShaderMaterial===!0,glslVersion:T.glslVersion,precision:f,batching:ce,batchingColor:ce&&R._colorsTexture!==null,instancing:ie,instancingColor:ie&&R.instanceColor!==null,instancingMorph:ie&&R.morphTexture!==null,outputColorSpace:W===null?e.outputColorSpace:W.isXRRenderTarget===!0?W.texture.colorSpace:ot.workingColorSpace,alphaToCoverage:!!T.alphaToCoverage,map:_e,matcap:Re,envMap:ke,envMapMode:ke&&K.mapping,envMapCubeUVHeight:B,aoMap:We,lightMap:Qe,bumpMap:Wt,normalMap:lt,displacementMap:Lt,emissiveMap:Qt,normalMapObjectSpace:lt&&T.normalMapType===UT,normalMapTangentSpace:lt&&T.normalMapType===Cm,packedNormalMap:lt&&T.normalMapType===Cm&&zL(T.normalMap.format),metalnessMap:nn,roughnessMap:z,anisotropy:_n,anisotropyMap:he,clearcoat:St,clearcoatMap:ge,clearcoatNormalMap:ve,clearcoatRoughnessMap:re,dispersion:Xt,retroreflection:N,iridescence:M,iridescenceMap:oe,iridescenceThicknessMap:Ie,sheen:V,sheenColorMap:Ve,sheenRoughnessMap:Ee,specularMap:me,specularColorMap:Ge,specularIntensityMap:Xe,transmission:ee,transmissionMap:vt,thicknessMap:G,gradientMap:xe,opaque:T.transparent===!1&&T.blending===qc&&T.alphaToCoverage===!1,alphaMap:ae,alphaTest:ye,alphaHash:Ce,combine:T.combine,mapUv:_e&&b(T.map.channel),aoMapUv:We&&b(T.aoMap.channel),lightMapUv:Qe&&b(T.lightMap.channel),bumpMapUv:Wt&&b(T.bumpMap.channel),normalMapUv:lt&&b(T.normalMap.channel),displacementMapUv:Lt&&b(T.displacementMap.channel),emissiveMapUv:Qt&&b(T.emissiveMap.channel),metalnessMapUv:nn&&b(T.metalnessMap.channel),roughnessMapUv:z&&b(T.roughnessMap.channel),anisotropyMapUv:he&&b(T.anisotropyMap.channel),clearcoatMapUv:ge&&b(T.clearcoatMap.channel),clearcoatNormalMapUv:ve&&b(T.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:re&&b(T.clearcoatRoughnessMap.channel),iridescenceMapUv:oe&&b(T.iridescenceMap.channel),iridescenceThicknessMapUv:Ie&&b(T.iridescenceThicknessMap.channel),sheenColorMapUv:Ve&&b(T.sheenColorMap.channel),sheenRoughnessMapUv:Ee&&b(T.sheenRoughnessMap.channel),specularMapUv:me&&b(T.specularMap.channel),specularColorMapUv:Ge&&b(T.specularColorMap.channel),specularIntensityMapUv:Xe&&b(T.specularIntensityMap.channel),transmissionMapUv:vt&&b(T.transmissionMap.channel),thicknessMapUv:G&&b(T.thicknessMap.channel),alphaMapUv:ae&&b(T.alphaMap.channel),vertexTangents:!!U.attributes.tangent&&(lt||_n),vertexNormals:!!U.attributes.normal,vertexColors:T.vertexColors,vertexAlphas:T.vertexColors===!0&&!!U.attributes.color&&U.attributes.color.itemSize===4,pointsUvs:R.isPoints===!0&&!!U.attributes.uv&&(_e||ae),fog:!!C,useFog:T.fog===!0,fogExp2:!!C&&C.isFogExp2,flatShading:T.wireframe===!1&&(T.flatShading===!0||U.attributes.normal===void 0&<===!1&&(T.isMeshLambertMaterial||T.isMeshPhongMaterial||T.isMeshStandardMaterial||T.isMeshPhysicalMaterial)),sizeAttenuation:T.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ne,skinning:R.isSkinnedMesh===!0,hasPositionAttribute:U.attributes.position!==void 0,morphTargets:U.morphAttributes.position!==void 0,morphNormals:U.morphAttributes.normal!==void 0,morphColors:U.morphAttributes.color!==void 0,morphTargetsCount:le,morphTextureStride:de,numSunLights:A.sun.length,numDirLights:A.directional.length,numPointLights:A.point.length,numSpotLights:A.spot.length,numSpotLightMaps:A.spotLightMap.length,numRectAreaLights:A.rectArea.length,numHemiLights:A.hemi.length,numSunLightShadows:A.sunShadowMap.length,numDirLightShadows:A.directionalShadowMap.length,numPointLightShadows:A.pointShadowMap.length,numSpotLightShadows:A.spotShadowMap.length,numSpotLightShadowsWithMaps:A.numSpotLightShadowsWithMaps,numLightProbes:A.numLightProbes,numLightProbeGrids:k.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:T.dithering,shadowMapEnabled:e.shadowMap.enabled&&P.length>0,shadowMapType:e.shadowMap.type,toneMapping:Ae,decodeVideoTexture:_e&&T.map.isVideoTexture===!0&&ot.getTransfer(T.map.colorSpace)===Bt,decodeVideoTextureEmissive:Qt&&T.emissiveMap.isVideoTexture===!0&&ot.getTransfer(T.emissiveMap.colorSpace)===Bt,premultipliedAlpha:T.premultipliedAlpha,doubleSided:T.side===vi,flipSided:T.side===Dn,useDepthPacking:T.depthPacking>=0,depthPacking:T.depthPacking||0,index0AttributeName:T.index0AttributeName,extensionClipCullDistance:fe&&T.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(fe&&T.extensions.multiDraw===!0||ce)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:T.customProgramCacheKey()};return it.vertexUv1s=c.has(1),it.vertexUv2s=c.has(2),it.vertexUv3s=c.has(3),c.clear(),it}function g(T){let A=[];if(T.shaderID)A.push(T.shaderID);else A.push(T.customVertexShaderID),A.push(T.customFragmentShaderID);if(T.defines!==void 0)for(let P in T.defines)A.push(P),A.push(T.defines[P]);if(T.isRawShaderMaterial===!1)p(A,T),x(A,T),A.push(e.outputColorSpace);return A.push(T.customProgramCacheKey),A.join()}function p(T,A){T.push(A.precision),T.push(A.outputColorSpace),T.push(A.envMapMode),T.push(A.envMapCubeUVHeight),T.push(A.mapUv),T.push(A.alphaMapUv),T.push(A.lightMapUv),T.push(A.aoMapUv),T.push(A.bumpMapUv),T.push(A.normalMapUv),T.push(A.displacementMapUv),T.push(A.emissiveMapUv),T.push(A.metalnessMapUv),T.push(A.roughnessMapUv),T.push(A.anisotropyMapUv),T.push(A.clearcoatMapUv),T.push(A.clearcoatNormalMapUv),T.push(A.clearcoatRoughnessMapUv),T.push(A.iridescenceMapUv),T.push(A.iridescenceThicknessMapUv),T.push(A.sheenColorMapUv),T.push(A.sheenRoughnessMapUv),T.push(A.specularMapUv),T.push(A.specularColorMapUv),T.push(A.specularIntensityMapUv),T.push(A.transmissionMapUv),T.push(A.thicknessMapUv),T.push(A.combine),T.push(A.fogExp2),T.push(A.sizeAttenuation),T.push(A.morphTargetsCount),T.push(A.morphAttributeCount),T.push(A.numSunLights),T.push(A.numDirLights),T.push(A.numPointLights),T.push(A.numSpotLights),T.push(A.numSpotLightMaps),T.push(A.numHemiLights),T.push(A.numRectAreaLights),T.push(A.numSunLightShadows),T.push(A.numDirLightShadows),T.push(A.numPointLightShadows),T.push(A.numSpotLightShadows),T.push(A.numSpotLightShadowsWithMaps),T.push(A.numLightProbes),T.push(A.shadowMapType),T.push(A.toneMapping),T.push(A.numClippingPlanes),T.push(A.numClipIntersection),T.push(A.depthPacking)}function x(T,A){if(a.disableAll(),A.instancing)a.enable(0);if(A.instancingColor)a.enable(1);if(A.instancingMorph)a.enable(2);if(A.matcap)a.enable(3);if(A.envMap)a.enable(4);if(A.normalMapObjectSpace)a.enable(5);if(A.normalMapTangentSpace)a.enable(6);if(A.clearcoat)a.enable(7);if(A.iridescence)a.enable(8);if(A.alphaTest)a.enable(9);if(A.vertexColors)a.enable(10);if(A.vertexAlphas)a.enable(11);if(A.vertexUv1s)a.enable(12);if(A.vertexUv2s)a.enable(13);if(A.vertexUv3s)a.enable(14);if(A.vertexTangents)a.enable(15);if(A.anisotropy)a.enable(16);if(A.alphaHash)a.enable(17);if(A.batching)a.enable(18);if(A.dispersion)a.enable(19);if(A.retroreflection)a.enable(24);if(A.batchingColor)a.enable(20);if(A.gradientMap)a.enable(21);if(A.packedNormalMap)a.enable(22);if(A.vertexNormals)a.enable(23);if(T.push(a.mask),a.disableAll(),A.fog)a.enable(0);if(A.useFog)a.enable(1);if(A.flatShading)a.enable(2);if(A.logarithmicDepthBuffer)a.enable(3);if(A.reversedDepthBuffer)a.enable(4);if(A.skinning)a.enable(5);if(A.morphTargets)a.enable(6);if(A.morphNormals)a.enable(7);if(A.morphColors)a.enable(8);if(A.premultipliedAlpha)a.enable(9);if(A.shadowMapEnabled)a.enable(10);if(A.doubleSided)a.enable(11);if(A.flipSided)a.enable(12);if(A.useDepthPacking)a.enable(13);if(A.dithering)a.enable(14);if(A.transmission)a.enable(15);if(A.sheen)a.enable(16);if(A.opaque)a.enable(17);if(A.pointsUvs)a.enable(18);if(A.decodeVideoTexture)a.enable(19);if(A.decodeVideoTextureEmissive)a.enable(20);if(A.alphaToCoverage)a.enable(21);if(A.numLightProbeGrids>0)a.enable(22);if(A.hasPositionAttribute)a.enable(23);T.push(a.mask)}function _(T){let A=h[T.type],P;if(A){let S=br[A];P=JT.clone(S.uniforms)}else P=T.uniforms;return P}function y(T,A){let P=u.get(A);if(P!==void 0)++P.usedTimes;else P=new UL(e,A,T,r),l.push(P),u.set(A,P);return P}function v(T){if(--T.usedTimes===0){let A=l.indexOf(T);l[A]=l[l.length-1],l.pop(),u.delete(T.cacheKey),T.destroy()}}function E(T){o.remove(T)}function w(){o.dispose()}return{getParameters:m,getProgramCacheKey:g,getUniforms:_,acquireProgram:y,releaseProgram:v,releaseShaderCache:E,programs:l,dispose:w}}function jL(){let e=new WeakMap;function t(a){return e.has(a)}function n(a){let o=e.get(a);if(o===void 0)o={},e.set(a,o);return o}function i(a){e.delete(a)}function r(a,o,c){e.get(a)[o]=c}function s(){e=new WeakMap}return{has:t,get:n,remove:i,update:r,dispose:s}}function HL(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 vA(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 EA(){let e=[],t=0,n=[],i=[],r=[];function s(){t=0,n.length=0,i.length=0,r.length=0}function a(f){let h=0;if(f.isInstancedMesh)h+=2;if(f.isSkinnedMesh)h+=1;return h}function o(f,h,b,m,g,p){let x=e[t];if(x===void 0)x={id:f.id,object:f,geometry:h,material:b,materialVariant:a(f),groupOrder:m,renderOrder:f.renderOrder,z:g,group:p},e[t]=x;else x.id=f.id,x.object=f,x.geometry=h,x.material=b,x.materialVariant=a(f),x.groupOrder=m,x.renderOrder=f.renderOrder,x.z=g,x.group=p;return t++,x}function c(f,h,b,m,g,p,x){if(x.reversedDepth===!0)g=-g;let _=o(f,h,b,m,g,p);if(b.transmission>0)i.push(_);else if(b.transparent===!0)r.push(_);else n.push(_)}function l(f,h,b,m,g,p){let x=o(f,h,b,m,g,p);if(b.transmission>0)i.unshift(x);else if(b.transparent===!0)r.unshift(x);else n.unshift(x)}function u(f,h){if(n.length>1)n.sort(f||HL);if(i.length>1)i.sort(h||vA);if(r.length>1)r.sort(h||vA)}function d(){for(let f=t,h=e.length;f<h;f++){let b=e[f];if(b.id===null)break;b.id=null,b.object=null,b.geometry=null,b.material=null,b.group=null}}return{opaque:n,transmissive:i,transparent:r,init:s,push:c,unshift:l,finish:d,sort:u}}function GL(){let e=new WeakMap;function t(i,r){let s=e.get(i),a;if(s===void 0)a=new EA,e.set(i,[a]);else if(r>=s.length)a=new EA,s.push(a);else a=s[r];return a}function n(){e=new WeakMap}return{get:t,dispose:n}}function $L(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case"SunLight":case"DirectionalLight":n={direction:new j,color:new qe};break;case"SpotLight":n={position:new j,direction:new j,color:new qe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new j,color:new qe,distance:0,decay:0};break;case"HemisphereLight":n={direction:new j,skyColor:new qe,groundColor:new qe};break;case"RectAreaLight":n={color:new qe,position:new j,halfWidth:new j,halfHeight:new j};break}return e[t.id]=n,n}}}function KL(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case"SunLight":case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ke};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ke};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ke,shadowCameraNear:1,shadowCameraFar:1000};break}return e[t.id]=n,n}}}function XL(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function qL(e){let t=new $L,n=KL(),i={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)i.probe.push(new j);let r=new j,s=new Je,a=new Je;function o(l){let u=0,d=0,f=0;for(let R=0;R<9;R++)i.probe[R].set(0,0,0);let h=0,b=0,m=0,g=0,p=0,x=0,_=0,y=0,v=0,E=0,w=0,T=0,A=0,P=0;l.sort(XL);for(let R=0,k=l.length;R<k;R++){let C=l[R],{color:U,intensity:L,distance:O}=C,K=null;if(C.shadow&&C.shadow.map)if(C.shadow.map.texture.format===wa)K=C.shadow.map.texture;else K=C.shadow.map.depthTexture||C.shadow.map.texture;if(C.isAmbientLight)u+=U.r*L,d+=U.g*L,f+=U.b*L;else if(C.isLightProbe){for(let B=0;B<9;B++)i.probe[B].addScaledVector(C.sh.coefficients[B],L);P++}else if(C.isSunLight){let B=t.get(C);if(B.color.copy(C.color).multiplyScalar(C.intensity),C.castShadow){let X=C.shadow,q=n.get(C);q.shadowIntensity=X.intensity,q.shadowBias=X.bias,q.shadowNormalBias=X.normalBias,q.shadowRadius=X.radius,q.shadowMapSize.copy(X.mapSize).multiply(X.getFrameExtents()),i.sunShadow[b]=q,i.sunShadowMap[b]=K;let le=X.getViewportCount();for(let de=0;de<le;de++)i.sunShadowMatrix[m+de]=X.getMatrix(de),i.sunShadowCascade[m+de]=X._cascadeData[de];m+=le,b++}i.sun[h]=B,h++}else if(C.isDirectionalLight){let B=t.get(C);if(B.color.copy(C.color).multiplyScalar(C.intensity),C.castShadow){let X=C.shadow,q=n.get(C);q.shadowIntensity=X.intensity,q.shadowBias=X.bias,q.shadowNormalBias=X.normalBias,q.shadowRadius=X.radius,q.shadowMapSize=X.mapSize,i.directionalShadow[g]=q,i.directionalShadowMap[g]=K,i.directionalShadowMatrix[g]=C.shadow.matrix,v++}i.directional[g]=B,g++}else if(C.isSpotLight){let B=t.get(C);B.position.setFromMatrixPosition(C.matrixWorld),B.color.copy(U).multiplyScalar(L),B.distance=O,B.coneCos=Math.cos(C.angle),B.penumbraCos=Math.cos(C.angle*(1-C.penumbra)),B.decay=C.decay,i.spot[x]=B;let X=C.shadow;if(C.map){if(i.spotLightMap[T]=C.map,T++,X.updateMatrices(C),C.castShadow)A++}if(i.spotLightMatrix[x]=X.matrix,C.castShadow){let q=n.get(C);q.shadowIntensity=X.intensity,q.shadowBias=X.bias,q.shadowNormalBias=X.normalBias,q.shadowRadius=X.radius,q.shadowMapSize=X.mapSize,i.spotShadow[x]=q,i.spotShadowMap[x]=K,w++}x++}else if(C.isRectAreaLight){let B=t.get(C);B.color.copy(U).multiplyScalar(L),B.halfWidth.set(C.width*0.5,0,0),B.halfHeight.set(0,C.height*0.5,0),i.rectArea[_]=B,_++}else if(C.isPointLight){let B=t.get(C);if(B.color.copy(C.color).multiplyScalar(C.intensity),B.distance=C.distance,B.decay=C.decay,C.castShadow){let X=C.shadow,q=n.get(C);q.shadowIntensity=X.intensity,q.shadowBias=X.bias,q.shadowNormalBias=X.normalBias,q.shadowRadius=X.radius,q.shadowMapSize=X.mapSize,q.shadowCameraNear=X.camera.near,q.shadowCameraFar=X.camera.far,i.pointShadow[p]=q,i.pointShadowMap[p]=K,i.pointShadowMatrix[p]=C.shadow.matrix,E++}i.point[p]=B,p++}else if(C.isHemisphereLight){let B=t.get(C);B.skyColor.copy(C.color).multiplyScalar(L),B.groundColor.copy(C.groundColor).multiplyScalar(L),i.hemi[y]=B,y++}}if(_>0)if(e.has("OES_texture_float_linear")===!0)i.rectAreaLTC1=Te.LTC_FLOAT_1,i.rectAreaLTC2=Te.LTC_FLOAT_2;else i.rectAreaLTC1=Te.LTC_HALF_1,i.rectAreaLTC2=Te.LTC_HALF_2;i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=f;let S=i.hash;if(S.sunLength!==h||S.directionalLength!==g||S.pointLength!==p||S.spotLength!==x||S.rectAreaLength!==_||S.hemiLength!==y||S.numSunShadows!==b||S.numDirectionalShadows!==v||S.numPointShadows!==E||S.numSpotShadows!==w||S.numSpotMaps!==T||S.numLightProbes!==P)i.sun.length=h,i.directional.length=g,i.spot.length=x,i.rectArea.length=_,i.point.length=p,i.hemi.length=y,i.sunShadow.length=b,i.sunShadowMap.length=b,i.sunShadowMatrix.length=m,i.sunShadowCascade.length=m,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.directionalShadowMatrix.length=v,i.pointShadow.length=E,i.pointShadowMap.length=E,i.pointShadowMatrix.length=E,i.spotShadow.length=w,i.spotShadowMap.length=w,i.spotLightMatrix.length=w+T-A,i.spotLightMap.length=T,i.numSpotLightShadowsWithMaps=A,i.numLightProbes=P,S.sunLength=h,S.directionalLength=g,S.pointLength=p,S.spotLength=x,S.rectAreaLength=_,S.hemiLength=y,S.numSunShadows=b,S.numDirectionalShadows=v,S.numPointShadows=E,S.numSpotShadows=w,S.numSpotMaps=T,S.numLightProbes=P,i.version=WL++}function c(l,u){let d=0,f=0,h=0,b=0,m=0,g=0,p=u.matrixWorldInverse;for(let x=0,_=l.length;x<_;x++){let y=l[x];if(y.isSunLight){let v=i.sun[d];v.direction.setFromMatrixPosition(y.matrixWorld),v.direction.transformDirection(p),d++}else if(y.isDirectionalLight){let v=i.directional[f];v.direction.setFromMatrixPosition(y.matrixWorld),r.setFromMatrixPosition(y.target.matrixWorld),v.direction.sub(r),v.direction.transformDirection(p),f++}else if(y.isSpotLight){let v=i.spot[b];v.position.setFromMatrixPosition(y.matrixWorld),v.position.applyMatrix4(p),v.direction.setFromMatrixPosition(y.matrixWorld),r.setFromMatrixPosition(y.target.matrixWorld),v.direction.sub(r),v.direction.transformDirection(p),b++}else if(y.isRectAreaLight){let v=i.rectArea[m];v.position.setFromMatrixPosition(y.matrixWorld),v.position.applyMatrix4(p),a.identity(),s.copy(y.matrixWorld),s.premultiply(p),a.extractRotation(s),v.halfWidth.set(y.width*0.5,0,0),v.halfHeight.set(0,y.height*0.5,0),v.halfWidth.applyMatrix4(a),v.halfHeight.applyMatrix4(a),m++}else if(y.isPointLight){let v=i.point[h];v.position.setFromMatrixPosition(y.matrixWorld),v.position.applyMatrix4(p),h++}else if(y.isHemisphereLight){let v=i.hemi[g];v.direction.setFromMatrixPosition(y.matrixWorld),v.direction.transformDirection(p),g++}}}return{setup:o,setupView:c,state:i}}function TA(e){let t=new qL(e),n=[],i=[],r=[];function s(f){d.camera=f,n.length=0,i.length=0,r.length=0}function a(f){n.push(f)}function o(f){i.push(f)}function c(f){r.push(f)}function l(){t.setup(n)}function u(f){t.setupView(n,f)}let d={lightsArray:n,shadowsArray:i,lightProbeGridArray:r,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:d,setupLights:l,setupLightsView:u,pushLight:a,pushShadow:o,pushLightProbeGrid:c}}function JL(e){let t=new WeakMap;function n(r,s=0){let a=t.get(r),o;if(a===void 0)o=new TA(e),t.set(r,[o]);else if(s>=a.length)o=new TA(e),a.push(o);else o=a[s];return o}function i(){t=new WeakMap}return{get:n,dispose:i}}function t8(e,t,n){let i=new ol,r=new Ke,s=new Ke,a=new Pt,o=new Vm,c=new jm,l={},u=n.maxTextureSize,d={[fs]:Dn,[Dn]:fs,[vi]:vi},f=new Ei({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Ke},radius:{value:4}},vertexShader:ZL,fragmentShader:YL}),h=f.clone();h.defines.HORIZONTAL_PASS=1;let b=new Ln;b.setAttribute("position",new En(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));let m=new jt(b,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Xc;let p=this.type;this.render=function(E,w,T){if(g.enabled===!1)return;if(g.autoUpdate===!1&&g.needsUpdate===!1)return;if(E.length===0)return;if(this.type===eT)je("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=Xc;let A=e.getRenderTarget(),P=e.getActiveCubeFace(),S=e.getActiveMipmapLevel(),R=e.state;if(R.setBlending(dr),R.buffers.depth.getReversed()===!0)R.buffers.color.setClear(0,0,0,0);else R.buffers.color.setClear(1,1,1,1);R.buffers.depth.setTest(!0),R.setScissorTest(!1);let k=p!==this.type;if(k)w.traverse(function(C){if(C.material)if(Array.isArray(C.material))C.material.forEach((U)=>U.needsUpdate=!0);else C.material.needsUpdate=!0});for(let C=0,U=E.length;C<U;C++){let L=E[C],O=L.shadow;if(O===void 0){je("WebGLShadowMap:",L,"has no shadow.");continue}if(O.autoUpdate===!1&&O.needsUpdate===!1)continue;r.copy(O.mapSize);let K=O.getFrameExtents();if(r.multiply(K),s.copy(O.mapSize),r.x>u||r.y>u){if(r.x>u)s.x=Math.floor(u/K.x),r.x=s.x*K.x,O.mapSize.x=s.x;if(r.y>u)s.y=Math.floor(u/K.y),r.y=s.y*K.y,O.mapSize.y=s.y}let B=e.state.buffers.depth.getReversed();if(O.camera._reversedDepth=B,O.map===null||k===!0){if(O.map!==null){if(O.map.depthTexture!==null)O.map.depthTexture.dispose(),O.map.depthTexture=null;O.map.dispose()}if(this.type===Ao){if(L.isPointLight){je("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}O.map=new li(r.x,r.y,{format:wa,type:hr,minFilter:Tn,magFilter:Tn,generateMipmaps:!1}),O.map.texture.name=L.name+".shadowMap",O.map.depthTexture=new Ma(r.x,r.y,Br),O.map.depthTexture.name=L.name+".shadowMapDepth",O.map.depthTexture.format=Ta,O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=Bi,O.map.depthTexture.magFilter=Bi}else{if(L.isPointLight)O.map=new dg(r.x),O.map.depthTexture=new Um(r.x,hs);else O.map=new li(r.x,r.y),O.map.depthTexture=new Ma(r.x,r.y,hs);if(O.map.depthTexture.name=L.name+".shadowMap",O.map.depthTexture.format=Ta,this.type===Xc)O.map.depthTexture.compareFunction=B?wd:Ad,O.map.depthTexture.minFilter=Tn,O.map.depthTexture.magFilter=Tn;else O.map.depthTexture.compareFunction=null,O.map.depthTexture.minFilter=Bi,O.map.depthTexture.magFilter=Bi}O.camera.updateProjectionMatrix()}if(O.map.isWebGLCubeRenderTarget!==!0&&(O.map.width!==r.x||O.map.height!==r.y))O.map.setSize(r.x,r.y);let X=O.map.isWebGLCubeRenderTarget?6:O.getViewportCount();if(L.isPointLight!==!0)O.updateMatrices(L,T);for(let q=0;q<X;q++){let le=O.getCamera(q);if(L.isPointLight){let{camera:de,matrix:Me}=O,pe=L.distance||de.far;if(pe!==de.far)de.far=pe,de.updateProjectionMatrix();gl.setFromMatrixPosition(L.matrixWorld),de.position.copy(gl),cg.copy(de.position),cg.add(QL[q]),de.up.copy(e8[q]),de.lookAt(cg),de.updateMatrixWorld(),Me.makeTranslation(-gl.x,-gl.y,-gl.z),AA.multiplyMatrices(de.projectionMatrix,de.matrixWorldInverse),O._frustum.setFromProjectionMatrix(AA,de.coordinateSystem,de.reversedDepth)}if(O.map.isWebGLCubeRenderTarget)e.setRenderTarget(O.map,q),e.clear();else{if(q===0)e.setRenderTarget(O.map),e.clear();let de=O.getViewport(q);a.set(s.x*de.x,s.y*de.y,s.x*de.z,s.y*de.w),R.viewport(a)}i=O.getFrustum(q),y(w,T,le,L,this.type)}if(O.isPointLightShadow!==!0&&this.type===Ao)x(O,T);O.needsUpdate=!1}p=this.type,g.needsUpdate=!1,e.setRenderTarget(A,P,S)};function x(E,w){let T=t.update(m);if(f.defines.VSM_SAMPLES!==E.blurSamples)f.defines.VSM_SAMPLES=E.blurSamples,h.defines.VSM_SAMPLES=E.blurSamples,f.needsUpdate=!0,h.needsUpdate=!0;if(E.mapPass===null)E.mapPass=new li(r.x,r.y,{format:wa,type:hr});else if(E.mapPass.width!==E.map.width||E.mapPass.height!==E.map.height)E.mapPass.setSize(E.map.width,E.map.height);f.uniforms.shadow_pass.value=E.map.depthTexture,f.uniforms.resolution.value.set(E.map.width,E.map.height),f.uniforms.radius.value=E.radius,e.setRenderTarget(E.mapPass),e.clear(),e.renderBufferDirect(w,null,T,f,m,null),h.uniforms.shadow_pass.value=E.mapPass.texture,h.uniforms.resolution.value.set(E.map.width,E.map.height),h.uniforms.radius.value=E.radius,e.setRenderTarget(E.map),e.clear(),e.renderBufferDirect(w,null,T,h,m,null)}function _(E,w,T,A){let P=null,S=T.isPointLight===!0?E.customDistanceMaterial:E.customDepthMaterial;if(S!==void 0)P=S;else if(P=T.isPointLight===!0?c:o,e.localClippingEnabled&&w.clipShadows===!0&&Array.isArray(w.clippingPlanes)&&w.clippingPlanes.length!==0||w.displacementMap&&w.displacementScale!==0||w.alphaMap&&w.alphaTest>0||w.map&&w.alphaTest>0||w.alphaToCoverage===!0){let R=P.uuid,k=w.uuid,C=l[R];if(C===void 0)C={},l[R]=C;let U=C[k];if(U===void 0)U=P.clone(),C[k]=U,w.addEventListener("dispose",v);P=U}if(P.visible=w.visible,P.wireframe=w.wireframe,A===Ao)P.side=w.shadowSide!==null?w.shadowSide:w.side;else P.side=w.shadowSide!==null?w.shadowSide:d[w.side];if(P.alphaMap=w.alphaMap,P.alphaTest=w.alphaToCoverage===!0?0.5:w.alphaTest,P.map=w.map,P.clipShadows=w.clipShadows,P.clippingPlanes=w.clippingPlanes,P.clipIntersection=w.clipIntersection,P.displacementMap=w.displacementMap,P.displacementScale=w.displacementScale,P.displacementBias=w.displacementBias,P.wireframeLinewidth=w.wireframeLinewidth,P.linewidth=w.linewidth,T.isPointLight===!0&&P.isMeshDistanceMaterial===!0){let R=e.properties.get(P);R.light=T}return P}function y(E,w,T,A,P){if(E.visible===!1)return;if(E.layers.test(w.layers)&&(E.isMesh||E.isLine||E.isPoints)){if((E.castShadow||E.receiveShadow&&P===Ao)&&(!E.frustumCulled||E.intersectsFrustum(i))){E.modelViewMatrix.multiplyMatrices(T.matrixWorldInverse,E.matrixWorld);let k=t.update(E),C=E.material;if(Array.isArray(C)){let U=k.groups;for(let L=0,O=U.length;L<O;L++){let K=U[L],B=C[K.materialIndex];if(B&&B.visible){let X=_(E,B,A,P);E.onBeforeShadow(e,E,w,T,k,X,K),e.renderBufferDirect(T,null,k,X,E,K),E.onAfterShadow(e,E,w,T,k,X,K)}}}else if(C.visible){let U=_(E,C,A,P);E.onBeforeShadow(e,E,w,T,k,U,null),e.renderBufferDirect(T,null,k,U,E,null),E.onAfterShadow(e,E,w,T,k,U,null)}}}let R=E.children;for(let k=0,C=R.length;k<C;k++)y(R[k],w,T,A,P)}function v(E){E.target.removeEventListener("dispose",v);for(let T in l){let A=l[T],P=E.target.uuid;if(P in A)A[P].dispose(),delete A[P]}}}function n8(e,t){function n(){let G=!1,xe=new Pt,ae=null,ye=new Pt(0,0,0,0);return{setMask:function(Ce){if(ae!==Ce&&!G)e.colorMask(Ce,Ce,Ce,Ce),ae=Ce},setLocked:function(Ce){G=Ce},setClear:function(Ce,fe,Ae,it,zt){if(zt===!0)Ce*=it,fe*=it,Ae*=it;if(xe.set(Ce,fe,Ae,it),ye.equals(xe)===!1)e.clearColor(Ce,fe,Ae,it),ye.copy(xe)},reset:function(){G=!1,ae=null,ye.set(-1,0,0,0)}}}function i(){let G=!1,xe=!1,ae=null,ye=null,Ce=null;return{setReversed:function(fe){if(xe!==fe){let Ae=t.get("EXT_clip_control");if(fe)Ae.clipControlEXT(Ae.LOWER_LEFT_EXT,Ae.ZERO_TO_ONE_EXT);else Ae.clipControlEXT(Ae.LOWER_LEFT_EXT,Ae.NEGATIVE_ONE_TO_ONE_EXT);xe=fe;let it=Ce;Ce=null,this.setClear(it)}},getReversed:function(){return xe},setTest:function(fe){if(fe)W(e.DEPTH_TEST);else ne(e.DEPTH_TEST)},setMask:function(fe){if(ae!==fe&&!G)e.depthMask(fe),ae=fe},setFunc:function(fe){if(xe)fe=XT[fe];if(ye!==fe){switch(fe){case vT:e.depthFunc(e.NEVER);break;case ET:e.depthFunc(e.ALWAYS);break;case TT:e.depthFunc(e.LESS);break;case Bp:e.depthFunc(e.LEQUAL);break;case AT:e.depthFunc(e.EQUAL);break;case wT:e.depthFunc(e.GEQUAL);break;case ST:e.depthFunc(e.GREATER);break;case MT:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}ye=fe}},setLocked:function(fe){G=fe},setClear:function(fe){if(Ce!==fe){if(Ce=fe,xe)fe=1-fe;e.clearDepth(fe)}},reset:function(){G=!1,ae=null,ye=null,Ce=null,xe=!1}}}function r(){let G=!1,xe=null,ae=null,ye=null,Ce=null,fe=null,Ae=null,it=null,zt=null;return{setTest:function(Mt){if(!G)if(Mt)W(e.STENCIL_TEST);else ne(e.STENCIL_TEST)},setMask:function(Mt){if(xe!==Mt&&!G)e.stencilMask(Mt),xe=Mt},setFunc:function(Mt,Xi,wr){if(ae!==Mt||ye!==Xi||Ce!==wr)e.stencilFunc(Mt,Xi,wr),ae=Mt,ye=Xi,Ce=wr},setOp:function(Mt,Xi,wr){if(fe!==Mt||Ae!==Xi||it!==wr)e.stencilOp(Mt,Xi,wr),fe=Mt,Ae=Xi,it=wr},setLocked:function(Mt){G=Mt},setClear:function(Mt){if(zt!==Mt)e.clearStencil(Mt),zt=Mt},reset:function(){G=!1,xe=null,ae=null,ye=null,Ce=null,fe=null,Ae=null,it=null,zt=null}}}let s=new n,a=new i,o=new r,c=new WeakMap,l=new WeakMap,u={},d={},f={},h=new WeakMap,b=[],m=null,g=!1,p=null,x=null,_=null,y=null,v=null,E=null,w=null,T=new qe(0,0,0),A=0,P=!1,S=null,R=null,k=null,C=null,U=null,L=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),O=!1,K=0,B=e.getParameter(e.VERSION);if(B.indexOf("WebGL")!==-1)K=parseFloat(/^WebGL (\d)/.exec(B)[1]),O=K>=1;else if(B.indexOf("OpenGL ES")!==-1)K=parseFloat(/^OpenGL ES (\d)/.exec(B)[1]),O=K>=2;let X=null,q={},le=e.getParameter(e.SCISSOR_BOX),de=e.getParameter(e.VIEWPORT),Me=new Pt().fromArray(le),pe=new Pt().fromArray(de);function J(G,xe,ae,ye){let Ce=new Uint8Array(4),fe=e.createTexture();e.bindTexture(G,fe),e.texParameteri(G,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(G,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let Ae=0;Ae<ae;Ae++)if(G===e.TEXTURE_3D||G===e.TEXTURE_2D_ARRAY)e.texImage3D(xe,0,e.RGBA,1,1,ye,0,e.RGBA,e.UNSIGNED_BYTE,Ce);else e.texImage2D(xe+Ae,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,Ce);return fe}let F={};F[e.TEXTURE_2D]=J(e.TEXTURE_2D,e.TEXTURE_2D,1),F[e.TEXTURE_CUBE_MAP]=J(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),F[e.TEXTURE_2D_ARRAY]=J(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),F[e.TEXTURE_3D]=J(e.TEXTURE_3D,e.TEXTURE_3D,1,1),s.setClear(0,0,0,1),a.setClear(1),o.setClear(0),W(e.DEPTH_TEST),a.setFunc(Bp),Wt(!1),lt(Dp),W(e.CULL_FACE),We(dr);function W(G){if(u[G]!==!0)e.enable(G),u[G]=!0}function ne(G){if(u[G]!==!1)e.disable(G),u[G]=!1}function ie(G,xe){if(f[G]!==xe){if(e.bindFramebuffer(G,xe),f[G]=xe,G===e.DRAW_FRAMEBUFFER)f[e.FRAMEBUFFER]=xe;if(G===e.FRAMEBUFFER)f[e.DRAW_FRAMEBUFFER]=xe;return!0}return!1}function ce(G,xe){let ae=b,ye=!1;if(G){if(ae=h.get(xe),ae===void 0)ae=[],h.set(xe,ae);let Ce=G.textures;if(ae.length!==Ce.length||ae[0]!==e.COLOR_ATTACHMENT0){for(let fe=0,Ae=Ce.length;fe<Ae;fe++)ae[fe]=e.COLOR_ATTACHMENT0+fe;ae.length=Ce.length,ye=!0}}else if(ae[0]!==e.BACK)ae[0]=e.BACK,ye=!0;if(ye)e.drawBuffers(ae)}function _e(G){if(m!==G)return e.useProgram(G),m=G,!0;return!1}let Re={[wo]:e.FUNC_ADD,[nT]:e.FUNC_SUBTRACT,[iT]:e.FUNC_REVERSE_SUBTRACT};Re[rT]=e.MIN,Re[sT]=e.MAX;let ke={[aT]:e.ZERO,[oT]:e.ONE,[cT]:e.SRC_COLOR,[uT]:e.SRC_ALPHA,[gT]:e.SRC_ALPHA_SATURATE,[pT]:e.DST_COLOR,[fT]:e.DST_ALPHA,[lT]:e.ONE_MINUS_SRC_COLOR,[dT]:e.ONE_MINUS_SRC_ALPHA,[mT]:e.ONE_MINUS_DST_COLOR,[hT]:e.ONE_MINUS_DST_ALPHA,[bT]:e.CONSTANT_COLOR,[xT]:e.ONE_MINUS_CONSTANT_COLOR,[yT]:e.CONSTANT_ALPHA,[_T]:e.ONE_MINUS_CONSTANT_ALPHA};function We(G,xe,ae,ye,Ce,fe,Ae,it,zt,Mt){if(G===dr){if(g===!0)ne(e.BLEND),g=!1;return}if(g===!1)W(e.BLEND),g=!0;if(G!==tT){if(G!==p||Mt!==P){if(x!==wo||v!==wo)e.blendEquation(e.FUNC_ADD),x=wo,v=wo;if(Mt)switch(G){case qc:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case Lp:e.blendFunc(e.ONE,e.ONE);break;case Fp:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case Up:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:Ye("WebGLState: Invalid blending: ",G);break}else switch(G){case qc:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case Lp:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case Fp:Ye("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Up:Ye("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Ye("WebGLState: Invalid blending: ",G);break}_=null,y=null,E=null,w=null,T.set(0,0,0),A=0,p=G,P=Mt}return}if(Ce=Ce||xe,fe=fe||ae,Ae=Ae||ye,xe!==x||Ce!==v)e.blendEquationSeparate(Re[xe],Re[Ce]),x=xe,v=Ce;if(ae!==_||ye!==y||fe!==E||Ae!==w)e.blendFuncSeparate(ke[ae],ke[ye],ke[fe],ke[Ae]),_=ae,y=ye,E=fe,w=Ae;if(it.equals(T)===!1||zt!==A)e.blendColor(it.r,it.g,it.b,zt),T.copy(it),A=zt;p=G,P=!1}function Qe(G,xe){G.side===vi?ne(e.CULL_FACE):W(e.CULL_FACE);let ae=G.side===Dn;if(xe)ae=!ae;Wt(ae),G.blending===qc&&G.transparent===!1?We(dr):We(G.blending,G.blendEquation,G.blendSrc,G.blendDst,G.blendEquationAlpha,G.blendSrcAlpha,G.blendDstAlpha,G.blendColor,G.blendAlpha,G.premultipliedAlpha),a.setFunc(G.depthFunc),a.setTest(G.depthTest),a.setMask(G.depthWrite),s.setMask(G.colorWrite);let ye=G.stencilWrite;if(o.setTest(ye),ye)o.setMask(G.stencilWriteMask),o.setFunc(G.stencilFunc,G.stencilRef,G.stencilFuncMask),o.setOp(G.stencilFail,G.stencilZFail,G.stencilZPass);Qt(G.polygonOffset,G.polygonOffsetFactor,G.polygonOffsetUnits),G.alphaToCoverage===!0?W(e.SAMPLE_ALPHA_TO_COVERAGE):ne(e.SAMPLE_ALPHA_TO_COVERAGE)}function Wt(G){if(S!==G){if(G)e.frontFace(e.CW);else e.frontFace(e.CCW);S=G}}function lt(G){if(G!==YE){if(W(e.CULL_FACE),G!==R)if(G===Dp)e.cullFace(e.BACK);else if(G===QE)e.cullFace(e.FRONT);else e.cullFace(e.FRONT_AND_BACK)}else ne(e.CULL_FACE);R=G}function Lt(G){if(G!==k){if(O)e.lineWidth(G);k=G}}function Qt(G,xe,ae){if(G){if(W(e.POLYGON_OFFSET_FILL),C!==xe||U!==ae){if(C=xe,U=ae,a.getReversed())xe=-xe;e.polygonOffset(xe,ae)}}else ne(e.POLYGON_OFFSET_FILL)}function nn(G){if(G)W(e.SCISSOR_TEST);else ne(e.SCISSOR_TEST)}function z(G){if(G===void 0)G=e.TEXTURE0+L-1;if(X!==G)e.activeTexture(G),X=G}function _n(G,xe,ae){if(ae===void 0)if(X===null)ae=e.TEXTURE0+L-1;else ae=X;let ye=q[ae];if(ye===void 0)ye={type:void 0,texture:void 0},q[ae]=ye;if(ye.type!==G||ye.texture!==xe){if(X!==ae)e.activeTexture(ae),X=ae;e.bindTexture(G,xe||F[G]),ye.type=G,ye.texture=xe}}function St(){let G=q[X];if(G!==void 0&&G.type!==void 0)e.bindTexture(G.type,null),G.type=void 0,G.texture=void 0}function Xt(){try{e.compressedTexImage2D(...arguments)}catch(G){Ye("WebGLState:",G)}}function N(){try{e.compressedTexImage3D(...arguments)}catch(G){Ye("WebGLState:",G)}}function M(){try{e.texSubImage2D(...arguments)}catch(G){Ye("WebGLState:",G)}}function V(){try{e.texSubImage3D(...arguments)}catch(G){Ye("WebGLState:",G)}}function ee(){try{e.compressedTexSubImage2D(...arguments)}catch(G){Ye("WebGLState:",G)}}function he(){try{e.compressedTexSubImage3D(...arguments)}catch(G){Ye("WebGLState:",G)}}function ge(){try{e.texStorage2D(...arguments)}catch(G){Ye("WebGLState:",G)}}function ve(){try{e.texStorage3D(...arguments)}catch(G){Ye("WebGLState:",G)}}function re(){try{e.texImage2D(...arguments)}catch(G){Ye("WebGLState:",G)}}function oe(){try{e.texImage3D(...arguments)}catch(G){Ye("WebGLState:",G)}}function Ie(G){if(d[G]!==void 0)return d[G];else return e.getParameter(G)}function Ve(G,xe){if(d[G]!==xe)e.pixelStorei(G,xe),d[G]=xe}function Ee(G){if(Me.equals(G)===!1)e.scissor(G.x,G.y,G.z,G.w),Me.copy(G)}function me(G){if(pe.equals(G)===!1)e.viewport(G.x,G.y,G.z,G.w),pe.copy(G)}function Ge(G,xe){let ae=l.get(xe);if(ae===void 0)ae=new WeakMap,l.set(xe,ae);let ye=ae.get(G);if(ye===void 0)ye=e.getUniformBlockIndex(xe,G.name),ae.set(G,ye)}function Xe(G,xe){let ye=l.get(xe).get(G);if(c.get(xe)!==ye)e.uniformBlockBinding(xe,ye,G.__bindingPointIndex),c.set(xe,ye)}function vt(){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),a.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={},d={},X=null,q={},f={},h=new WeakMap,b=[],m=null,g=!1,p=null,x=null,_=null,y=null,v=null,E=null,w=null,T=new qe(0,0,0),A=0,P=!1,S=null,R=null,k=null,C=null,U=null,Me.set(0,0,e.canvas.width,e.canvas.height),pe.set(0,0,e.canvas.width,e.canvas.height),s.reset(),a.reset(),o.reset()}return{buffers:{color:s,depth:a,stencil:o},enable:W,disable:ne,bindFramebuffer:ie,drawBuffers:ce,useProgram:_e,setBlending:We,setMaterial:Qe,setFlipSided:Wt,setCullFace:lt,setLineWidth:Lt,setPolygonOffset:Qt,setScissorTest:nn,activeTexture:z,bindTexture:_n,unbindTexture:St,compressedTexImage2D:Xt,compressedTexImage3D:N,texImage2D:re,texImage3D:oe,pixelStorei:Ve,getParameter:Ie,updateUBOMapping:Ge,uniformBlockBinding:Xe,texStorage2D:ge,texStorage3D:ve,texSubImage2D:M,texSubImage3D:V,compressedTexSubImage2D:ee,compressedTexSubImage3D:he,scissor:Ee,viewport:me,reset:vt}}function i8(e,t,n,i,r,s,a){let o=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 Ke,u=new WeakMap,d=new Set,f,h=new WeakMap,b=!1;try{b=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch(N){}function m(N,M){return b?new OffscreenCanvas(N,M):vo("canvas")}function g(N,M,V){let ee=1,he=Xt(N);if(he.width>V||he.height>V)ee=V/Math.max(he.width,he.height);if(ee<1)if(typeof HTMLImageElement<"u"&&N instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&N instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&N instanceof ImageBitmap||typeof VideoFrame<"u"&&N instanceof VideoFrame){let ge=Math.floor(ee*he.width),ve=Math.floor(ee*he.height);if(f===void 0)f=m(ge,ve);let re=M?m(ge,ve):f;return re.width=ge,re.height=ve,re.getContext("2d").drawImage(N,0,0,ge,ve),je("WebGLRenderer: Texture has been resized from ("+he.width+"x"+he.height+") to ("+ge+"x"+ve+")."),re}else{if("data"in N)je("WebGLRenderer: Image in DataTexture is too big ("+he.width+"x"+he.height+").");return N}return N}function p(N){return N.generateMipmaps}function x(N){e.generateMipmap(N)}function _(N){if(N.isWebGLCubeRenderTarget)return e.TEXTURE_CUBE_MAP;if(N.isWebGL3DRenderTarget)return e.TEXTURE_3D;if(N.isWebGLArrayRenderTarget||N.isCompressedArrayTexture)return e.TEXTURE_2D_ARRAY;return e.TEXTURE_2D}function y(N,M,V,ee,he,ge=!1){if(N!==null){if(e[N]!==void 0)return e[N];je("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+N+"'")}let ve;if(ee){if(ve=t.get("EXT_texture_norm16"),!ve)je("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension")}let re=M;if(M===e.RED){if(V===e.FLOAT)re=e.R32F;if(V===e.HALF_FLOAT)re=e.R16F;if(V===e.UNSIGNED_BYTE)re=e.R8;if(V===e.UNSIGNED_SHORT&&ve)re=ve.R16_EXT;if(V===e.SHORT&&ve)re=ve.R16_SNORM_EXT}if(M===e.RED_INTEGER){if(V===e.UNSIGNED_BYTE)re=e.R8UI;if(V===e.UNSIGNED_SHORT)re=e.R16UI;if(V===e.UNSIGNED_INT)re=e.R32UI;if(V===e.BYTE)re=e.R8I;if(V===e.SHORT)re=e.R16I;if(V===e.INT)re=e.R32I}if(M===e.RG){if(V===e.FLOAT)re=e.RG32F;if(V===e.HALF_FLOAT)re=e.RG16F;if(V===e.UNSIGNED_BYTE)re=e.RG8;if(V===e.UNSIGNED_SHORT&&ve)re=ve.RG16_EXT;if(V===e.SHORT&&ve)re=ve.RG16_SNORM_EXT}if(M===e.RG_INTEGER){if(V===e.UNSIGNED_BYTE)re=e.RG8UI;if(V===e.UNSIGNED_SHORT)re=e.RG16UI;if(V===e.UNSIGNED_INT)re=e.RG32UI;if(V===e.BYTE)re=e.RG8I;if(V===e.SHORT)re=e.RG16I;if(V===e.INT)re=e.RG32I}if(M===e.RGB_INTEGER){if(V===e.UNSIGNED_BYTE)re=e.RGB8UI;if(V===e.UNSIGNED_SHORT)re=e.RGB16UI;if(V===e.UNSIGNED_INT)re=e.RGB32UI;if(V===e.BYTE)re=e.RGB8I;if(V===e.SHORT)re=e.RGB16I;if(V===e.INT)re=e.RGB32I}if(M===e.RGBA_INTEGER){if(V===e.UNSIGNED_BYTE)re=e.RGBA8UI;if(V===e.UNSIGNED_SHORT)re=e.RGBA16UI;if(V===e.UNSIGNED_INT)re=e.RGBA32UI;if(V===e.BYTE)re=e.RGBA8I;if(V===e.SHORT)re=e.RGBA16I;if(V===e.INT)re=e.RGBA32I}if(M===e.RGB){if(V===e.UNSIGNED_SHORT&&ve)re=ve.RGB16_EXT;if(V===e.SHORT&&ve)re=ve.RGB16_SNORM_EXT;if(V===e.UNSIGNED_INT_5_9_9_9_REV)re=e.RGB9_E5;if(V===e.UNSIGNED_INT_10F_11F_11F_REV)re=e.R11F_G11F_B10F}if(M===e.RGBA){let oe=ge?Nm:ot.getTransfer(he);if(V===e.FLOAT)re=e.RGBA32F;if(V===e.HALF_FLOAT)re=e.RGBA16F;if(V===e.UNSIGNED_BYTE)re=oe===Bt?e.SRGB8_ALPHA8:e.RGBA8;if(V===e.UNSIGNED_SHORT&&ve)re=ve.RGBA16_EXT;if(V===e.SHORT&&ve)re=ve.RGBA16_SNORM_EXT;if(V===e.UNSIGNED_SHORT_4_4_4_4)re=e.RGBA4;if(V===e.UNSIGNED_SHORT_5_5_5_1)re=e.RGB5_A1}if(re===e.R16F||re===e.R32F||re===e.RG16F||re===e.RG32F||re===e.RGBA16F||re===e.RGBA32F)t.get("EXT_color_buffer_float");return re}function v(N,M){let V;if(N){if(M===null||M===hs||M===Co)V=e.DEPTH24_STENCIL8;else if(M===Br)V=e.DEPTH32F_STENCIL8;else if(M===Yc)V=e.DEPTH24_STENCIL8,je("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")}else if(M===null||M===hs||M===Co)V=e.DEPTH_COMPONENT24;else if(M===Br)V=e.DEPTH_COMPONENT32F;else if(M===Yc)V=e.DEPTH_COMPONENT16;return V}function E(N,M){if(p(N)===!0||N.isFramebufferTexture&&N.minFilter!==Bi&&N.minFilter!==Tn)return Math.log2(Math.max(M.width,M.height))+1;else if(N.mipmaps!==void 0&&N.mipmaps.length>0)return N.mipmaps.length;else if(N.isCompressedTexture&&Array.isArray(N.image))return M.mipmaps.length;else return 1}function w(N){let M=N.target;if(M.removeEventListener("dispose",w),A(M),M.isVideoTexture)u.delete(M);if(M.isHTMLTexture)d.delete(M)}function T(N){let M=N.target;M.removeEventListener("dispose",T),S(M)}function A(N){let M=i.get(N);if(M.__webglInit===void 0)return;let V=N.source,ee=h.get(V);if(ee){let he=ee[M.__cacheKey];if(he.usedTimes--,he.usedTimes===0)P(N);if(Object.keys(ee).length===0)h.delete(V)}i.remove(N)}function P(N){let M=i.get(N);e.deleteTexture(M.__webglTexture);let V=N.source,ee=h.get(V);delete ee[M.__cacheKey],a.memory.textures--}function S(N){let M=i.get(N);if(N.depthTexture)N.depthTexture.dispose(),i.remove(N.depthTexture);if(N.isWebGLCubeRenderTarget)for(let ee=0;ee<6;ee++){if(Array.isArray(M.__webglFramebuffer[ee]))for(let he=0;he<M.__webglFramebuffer[ee].length;he++)e.deleteFramebuffer(M.__webglFramebuffer[ee][he]);else e.deleteFramebuffer(M.__webglFramebuffer[ee]);if(M.__webglDepthbuffer)e.deleteRenderbuffer(M.__webglDepthbuffer[ee])}else{if(Array.isArray(M.__webglFramebuffer))for(let ee=0;ee<M.__webglFramebuffer.length;ee++)e.deleteFramebuffer(M.__webglFramebuffer[ee]);else e.deleteFramebuffer(M.__webglFramebuffer);if(M.__webglDepthbuffer)e.deleteRenderbuffer(M.__webglDepthbuffer);if(M.__webglMultisampledFramebuffer)e.deleteFramebuffer(M.__webglMultisampledFramebuffer);if(M.__webglColorRenderbuffer){for(let ee=0;ee<M.__webglColorRenderbuffer.length;ee++)if(M.__webglColorRenderbuffer[ee])e.deleteRenderbuffer(M.__webglColorRenderbuffer[ee])}if(M.__webglDepthRenderbuffer)e.deleteRenderbuffer(M.__webglDepthRenderbuffer)}let V=N.textures;for(let ee=0,he=V.length;ee<he;ee++){let ge=i.get(V[ee]);if(ge.__webglTexture)e.deleteTexture(ge.__webglTexture),a.memory.textures--;i.remove(V[ee])}i.remove(N)}let R=0;function k(){R=0}function C(){return R}function U(N){R=N}function L(){let N=R;if(N>=r.maxTextures)je("WebGLTextures: Trying to use "+(N+1)+" texture units while this GPU supports only "+r.maxTextures);return R+=1,N}function O(N){let M=[];return M.push(N.wrapS),M.push(N.wrapT),M.push(N.wrapR||0),M.push(N.magFilter),M.push(N.minFilter),M.push(N.anisotropy),M.push(N.internalFormat),M.push(N.format),M.push(N.type),M.push(N.generateMipmaps),M.push(N.premultiplyAlpha),M.push(N.flipY),M.push(N.unpackAlignment),M.push(N.colorSpace),M.join()}function K(N,M){let V=i.get(N);if(N.isVideoTexture)_n(N);if(N.isRenderTargetTexture===!1&&N.isExternalTexture!==!0&&N.version>0&&V.__version!==N.version){let ee=N.image;if(ee===null)je("WebGLRenderer: Texture marked for update but no image data found.");else if(ee.complete===!1)je("WebGLRenderer: Texture marked for update but image is incomplete");else{ne(V,N,M);return}}else if(N.isExternalTexture)V.__webglTexture=N.sourceTexture?N.sourceTexture:null;n.bindTexture(e.TEXTURE_2D,V.__webglTexture,e.TEXTURE0+M)}function B(N,M){let V=i.get(N);if(N.isRenderTargetTexture===!1&&N.version>0&&V.__version!==N.version){ne(V,N,M);return}else if(N.isExternalTexture)V.__webglTexture=N.sourceTexture?N.sourceTexture:null;n.bindTexture(e.TEXTURE_2D_ARRAY,V.__webglTexture,e.TEXTURE0+M)}function X(N,M){let V=i.get(N);if(N.isRenderTargetTexture===!1&&N.version>0&&V.__version!==N.version){ne(V,N,M);return}n.bindTexture(e.TEXTURE_3D,V.__webglTexture,e.TEXTURE0+M)}function q(N,M){let V=i.get(N);if(N.isCubeDepthTexture!==!0&&N.version>0&&V.__version!==N.version){ie(V,N,M);return}n.bindTexture(e.TEXTURE_CUBE_MAP,V.__webglTexture,e.TEXTURE0+M)}let le={[Mo]:e.REPEAT,[Ro]:e.CLAMP_TO_EDGE,[md]:e.MIRRORED_REPEAT},de={[Bi]:e.NEAREST,[gd]:e.NEAREST_MIPMAP_NEAREST,[Ea]:e.NEAREST_MIPMAP_LINEAR,[Tn]:e.LINEAR,[Io]:e.LINEAR_MIPMAP_NEAREST,[fr]:e.LINEAR_MIPMAP_LINEAR},Me={[BT]:e.NEVER,[GT]:e.ALWAYS,[zT]:e.LESS,[Ad]:e.LEQUAL,[VT]:e.EQUAL,[wd]:e.GEQUAL,[jT]:e.GREATER,[HT]:e.NOTEQUAL};function pe(N,M){if(M.type===Br&&t.has("OES_texture_float_linear")===!1&&(M.magFilter===Tn||M.magFilter===Io||M.magFilter===Ea||M.magFilter===fr||M.minFilter===Tn||M.minFilter===Io||M.minFilter===Ea||M.minFilter===fr))je("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.");if(e.texParameteri(N,e.TEXTURE_WRAP_S,le[M.wrapS]),e.texParameteri(N,e.TEXTURE_WRAP_T,le[M.wrapT]),N===e.TEXTURE_3D||N===e.TEXTURE_2D_ARRAY)e.texParameteri(N,e.TEXTURE_WRAP_R,le[M.wrapR]);if(e.texParameteri(N,e.TEXTURE_MAG_FILTER,de[M.magFilter]),e.texParameteri(N,e.TEXTURE_MIN_FILTER,de[M.minFilter]),M.compareFunction)e.texParameteri(N,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(N,e.TEXTURE_COMPARE_FUNC,Me[M.compareFunction]);if(t.has("EXT_texture_filter_anisotropic")===!0){if(M.magFilter===Bi)return;if(M.minFilter!==Ea&&M.minFilter!==fr)return;if(M.type===Br&&t.has("OES_texture_float_linear")===!1)return;if(M.anisotropy>1||i.get(M).__currentAnisotropy){let V=t.get("EXT_texture_filter_anisotropic");e.texParameterf(N,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,r.getMaxAnisotropy())),i.get(M).__currentAnisotropy=M.anisotropy}}}function J(N,M){let V=!1;if(N.__webglInit===void 0)N.__webglInit=!0,M.addEventListener("dispose",w);let ee=M.source,he=h.get(ee);if(he===void 0)he={},h.set(ee,he);let ge=O(M);if(ge!==N.__cacheKey){if(he[ge]===void 0)he[ge]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,V=!0;he[ge].usedTimes++;let ve=he[N.__cacheKey];if(ve!==void 0){if(he[N.__cacheKey].usedTimes--,ve.usedTimes===0)P(M)}N.__cacheKey=ge,N.__webglTexture=he[ge].texture}return V}function F(N,M,V){return Math.floor(Math.floor(N/V)/M)}function W(N,M,V,ee){let ge=N.updateRanges;if(ge.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,M.width,M.height,V,ee,M.data);else{ge.sort((Ve,Ee)=>Ve.start-Ee.start);let ve=0;for(let Ve=1;Ve<ge.length;Ve++){let Ee=ge[ve],me=ge[Ve],Ge=Ee.start+Ee.count,Xe=F(me.start,M.width,4),vt=F(Ee.start,M.width,4);if(me.start<=Ge+1&&Xe===vt&&F(me.start+me.count-1,M.width,4)===Xe)Ee.count=Math.max(Ee.count,me.start+me.count-Ee.start);else++ve,ge[ve]=me}ge.length=ve+1;let re=n.getParameter(e.UNPACK_ROW_LENGTH),oe=n.getParameter(e.UNPACK_SKIP_PIXELS),Ie=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,M.width);for(let Ve=0,Ee=ge.length;Ve<Ee;Ve++){let me=ge[Ve],Ge=Math.floor(me.start/4),Xe=Math.ceil(me.count/4),vt=Ge%M.width,G=Math.floor(Ge/M.width),xe=Xe,ae=1;n.pixelStorei(e.UNPACK_SKIP_PIXELS,vt),n.pixelStorei(e.UNPACK_SKIP_ROWS,G),n.texSubImage2D(e.TEXTURE_2D,0,vt,G,xe,1,V,ee,M.data)}N.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,re),n.pixelStorei(e.UNPACK_SKIP_PIXELS,oe),n.pixelStorei(e.UNPACK_SKIP_ROWS,Ie)}}function ne(N,M,V){let ee=e.TEXTURE_2D;if(M.isDataArrayTexture||M.isCompressedArrayTexture)ee=e.TEXTURE_2D_ARRAY;if(M.isData3DTexture)ee=e.TEXTURE_3D;let he=J(N,M),ge=M.source;n.bindTexture(ee,N.__webglTexture,e.TEXTURE0+V);let ve=i.get(ge);if(ge.version!==ve.__version||he===!0){if(n.activeTexture(e.TEXTURE0+V),(typeof ImageBitmap<"u"&&M.image instanceof ImageBitmap)===!1){let ae=ot.getPrimaries(ot.workingColorSpace),ye=M.colorSpace===Sa?null:ot.getPrimaries(M.colorSpace),Ce=M.colorSpace===Sa||ae===ye?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,M.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ce)}n.pixelStorei(e.UNPACK_ALIGNMENT,M.unpackAlignment);let oe=g(M.image,!1,r.maxTextureSize);oe=St(M,oe);let Ie=s.convert(M.format,M.colorSpace),Ve=s.convert(M.type),Ee=y(M.internalFormat,Ie,Ve,M.normalized,M.colorSpace,M.isVideoTexture);pe(ee,M);let me,Ge=M.mipmaps,Xe=M.isVideoTexture!==!0,vt=ve.__version===void 0||he===!0,G=ge.dataReady,xe=E(M,oe);if(M.isDepthTexture){if(Ee=v(M.format===Aa,M.type),vt)if(Xe)n.texStorage2D(e.TEXTURE_2D,1,Ee,oe.width,oe.height);else n.texImage2D(e.TEXTURE_2D,0,Ee,oe.width,oe.height,0,Ie,Ve,null)}else if(M.isDataTexture)if(Ge.length>0){if(Xe&&vt)n.texStorage2D(e.TEXTURE_2D,xe,Ee,Ge[0].width,Ge[0].height);for(let ae=0,ye=Ge.length;ae<ye;ae++)if(me=Ge[ae],Xe){if(G)n.texSubImage2D(e.TEXTURE_2D,ae,0,0,me.width,me.height,Ie,Ve,me.data)}else n.texImage2D(e.TEXTURE_2D,ae,Ee,me.width,me.height,0,Ie,Ve,me.data);M.generateMipmaps=!1}else if(Xe){if(vt)n.texStorage2D(e.TEXTURE_2D,xe,Ee,oe.width,oe.height);if(G)W(M,oe,Ie,Ve)}else n.texImage2D(e.TEXTURE_2D,0,Ee,oe.width,oe.height,0,Ie,Ve,oe.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){if(Xe&&vt)n.texStorage3D(e.TEXTURE_2D_ARRAY,xe,Ee,Ge[0].width,Ge[0].height,oe.depth);for(let ae=0,ye=Ge.length;ae<ye;ae++)if(me=Ge[ae],M.format!==pr)if(Ie!==null)if(Xe){if(G)if(M.layerUpdates.size>0){let Ce=tg(me.width,me.height,M.format,M.type);for(let fe of M.layerUpdates){let Ae=me.data.subarray(fe*Ce/me.data.BYTES_PER_ELEMENT,(fe+1)*Ce/me.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,ae,0,0,fe,me.width,me.height,1,Ie,Ae)}}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,ae,0,0,0,me.width,me.height,oe.depth,Ie,me.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,ae,Ee,me.width,me.height,oe.depth,0,me.data,0,0);else je("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(Xe){if(G)n.texSubImage3D(e.TEXTURE_2D_ARRAY,ae,0,0,0,me.width,me.height,oe.depth,Ie,Ve,me.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,ae,Ee,me.width,me.height,oe.depth,0,Ie,Ve,me.data);if(M.layerUpdates.size>0)M.clearLayerUpdates()}else{if(Xe&&vt)n.texStorage2D(e.TEXTURE_2D,xe,Ee,Ge[0].width,Ge[0].height);for(let ae=0,ye=Ge.length;ae<ye;ae++)if(me=Ge[ae],M.format!==pr)if(Ie!==null)if(Xe){if(G)n.compressedTexSubImage2D(e.TEXTURE_2D,ae,0,0,me.width,me.height,Ie,me.data)}else n.compressedTexImage2D(e.TEXTURE_2D,ae,Ee,me.width,me.height,0,me.data);else je("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(Xe){if(G)n.texSubImage2D(e.TEXTURE_2D,ae,0,0,me.width,me.height,Ie,Ve,me.data)}else n.texImage2D(e.TEXTURE_2D,ae,Ee,me.width,me.height,0,Ie,Ve,me.data)}else if(M.isDataArrayTexture)if(Xe){if(vt)n.texStorage3D(e.TEXTURE_2D_ARRAY,xe,Ee,oe.width,oe.height,oe.depth);if(G)if(M.layerUpdates.size>0){let ae=tg(oe.width,oe.height,M.format,M.type);for(let ye of M.layerUpdates){let Ce=oe.data.subarray(ye*ae/oe.data.BYTES_PER_ELEMENT,(ye+1)*ae/oe.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,ye,oe.width,oe.height,1,Ie,Ve,Ce)}M.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,oe.width,oe.height,oe.depth,Ie,Ve,oe.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,Ee,oe.width,oe.height,oe.depth,0,Ie,Ve,oe.data);else if(M.isData3DTexture)if(Xe){if(vt)n.texStorage3D(e.TEXTURE_3D,xe,Ee,oe.width,oe.height,oe.depth);if(G)n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,oe.width,oe.height,oe.depth,Ie,Ve,oe.data)}else n.texImage3D(e.TEXTURE_3D,0,Ee,oe.width,oe.height,oe.depth,0,Ie,Ve,oe.data);else if(M.isFramebufferTexture){if(vt)if(Xe)n.texStorage2D(e.TEXTURE_2D,xe,Ee,oe.width,oe.height);else{let ae=oe.width,ye=oe.height;for(let Ce=0;Ce<xe;Ce++)n.texImage2D(e.TEXTURE_2D,Ce,Ee,ae,ye,0,Ie,Ve,null),ae>>=1,ye>>=1}}else if(M.isHTMLTexture){if("texElementImage2D"in e){let ae=e.canvas;if(!ae.hasAttribute("layoutsubtree"))ae.setAttribute("layoutsubtree","true");if(oe.parentNode!==ae){ae.appendChild(oe),d.add(M),ae.onpaint=(ye)=>{let Ce=ye.changedElements;for(let fe of d)if(Ce.includes(fe.image))fe.needsUpdate=!0},ae.requestPaint();return}if(e.texElementImage2D.length===3)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,oe);else{let{RGBA:Ce,RGBA:fe,UNSIGNED_BYTE:Ae}=e;e.texElementImage2D(e.TEXTURE_2D,0,Ce,fe,Ae,oe)}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(Ge.length>0){if(Xe&&vt){let ae=Xt(Ge[0]);n.texStorage2D(e.TEXTURE_2D,xe,Ee,ae.width,ae.height)}for(let ae=0,ye=Ge.length;ae<ye;ae++)if(me=Ge[ae],Xe){if(G)n.texSubImage2D(e.TEXTURE_2D,ae,0,0,Ie,Ve,me)}else n.texImage2D(e.TEXTURE_2D,ae,Ee,Ie,Ve,me);M.generateMipmaps=!1}else if(Xe){if(vt){let ae=Xt(oe);n.texStorage2D(e.TEXTURE_2D,xe,Ee,ae.width,ae.height)}if(G)n.texSubImage2D(e.TEXTURE_2D,0,0,0,Ie,Ve,oe)}else n.texImage2D(e.TEXTURE_2D,0,Ee,Ie,Ve,oe);if(p(M))x(ee);if(ve.__version=ge.version,M.onUpdate)M.onUpdate(M)}N.__version=M.version}function ie(N,M,V){if(M.image.length!==6)return;let ee=J(N,M),he=M.source;n.bindTexture(e.TEXTURE_CUBE_MAP,N.__webglTexture,e.TEXTURE0+V);let ge=i.get(he);if(he.version!==ge.__version||ee===!0){n.activeTexture(e.TEXTURE0+V);let ve=ot.getPrimaries(ot.workingColorSpace),re=M.colorSpace===Sa?null:ot.getPrimaries(M.colorSpace),oe=M.colorSpace===Sa||ve===re?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,M.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,M.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,oe);let Ie=M.isCompressedTexture||M.image[0].isCompressedTexture,Ve=M.image[0]&&M.image[0].isDataTexture,Ee=[];for(let fe=0;fe<6;fe++){if(!Ie&&!Ve)Ee[fe]=g(M.image[fe],!0,r.maxCubemapSize);else Ee[fe]=Ve?M.image[fe].image:M.image[fe];Ee[fe]=St(M,Ee[fe])}let me=Ee[0],Ge=s.convert(M.format,M.colorSpace),Xe=s.convert(M.type),vt=y(M.internalFormat,Ge,Xe,M.normalized,M.colorSpace),G=M.isVideoTexture!==!0,xe=ge.__version===void 0||ee===!0,ae=he.dataReady,ye=E(M,me);pe(e.TEXTURE_CUBE_MAP,M);let Ce;if(Ie){if(G&&xe)n.texStorage2D(e.TEXTURE_CUBE_MAP,ye,vt,me.width,me.height);for(let fe=0;fe<6;fe++){Ce=Ee[fe].mipmaps;for(let Ae=0;Ae<Ce.length;Ae++){let it=Ce[Ae];if(M.format!==pr)if(Ge!==null)if(G){if(ae)n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae,0,0,it.width,it.height,Ge,it.data)}else n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae,vt,it.width,it.height,0,it.data);else je("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()");else if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae,0,0,it.width,it.height,Ge,Xe,it.data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae,vt,it.width,it.height,0,Ge,Xe,it.data)}}}else{if(Ce=M.mipmaps,G&&xe){if(Ce.length>0)ye++;let fe=Xt(Ee[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,ye,vt,fe.width,fe.height)}for(let fe=0;fe<6;fe++)if(Ve){if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0,0,0,Ee[fe].width,Ee[fe].height,Ge,Xe,Ee[fe].data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0,vt,Ee[fe].width,Ee[fe].height,0,Ge,Xe,Ee[fe].data);for(let Ae=0;Ae<Ce.length;Ae++){let zt=Ce[Ae].image[fe].image;if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae+1,0,0,zt.width,zt.height,Ge,Xe,zt.data)}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae+1,vt,zt.width,zt.height,0,Ge,Xe,zt.data)}}else{if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0,0,0,Ge,Xe,Ee[fe])}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,0,vt,Ge,Xe,Ee[fe]);for(let Ae=0;Ae<Ce.length;Ae++){let it=Ce[Ae];if(G){if(ae)n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae+1,0,0,Ge,Xe,it.image[fe])}else n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+fe,Ae+1,vt,Ge,Xe,it.image[fe])}}}if(p(M))x(e.TEXTURE_CUBE_MAP);if(ge.__version=he.version,M.onUpdate)M.onUpdate(M)}N.__version=M.version}function ce(N,M,V,ee,he,ge){let ve=s.convert(V.format,V.colorSpace),re=s.convert(V.type),oe=y(V.internalFormat,ve,re,V.normalized,V.colorSpace),Ie=i.get(M),Ve=i.get(V);if(Ve.__renderTarget=M,!Ie.__hasExternalTextures){let Ee=Math.max(1,M.width>>ge),me=Math.max(1,M.height>>ge);if(he===e.TEXTURE_3D||he===e.TEXTURE_2D_ARRAY)n.texImage3D(he,ge,oe,Ee,me,M.depth,0,ve,re,null);else n.texImage2D(he,ge,oe,Ee,me,0,ve,re,null)}if(n.bindFramebuffer(e.FRAMEBUFFER,N),z(M))o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,ee,he,Ve.__webglTexture,0,nn(M));else if(he===e.TEXTURE_2D||he>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&he<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)e.framebufferTexture2D(e.FRAMEBUFFER,ee,he,Ve.__webglTexture,ge);n.bindFramebuffer(e.FRAMEBUFFER,null)}function _e(N,M,V){if(e.bindRenderbuffer(e.RENDERBUFFER,N),M.depthBuffer){let ee=M.depthTexture,he=ee&&ee.isDepthTexture?ee.type:null,ge=v(M.stencilBuffer,he),ve=M.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(z(M))o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,nn(M),ge,M.width,M.height);else if(V)e.renderbufferStorageMultisample(e.RENDERBUFFER,nn(M),ge,M.width,M.height);else e.renderbufferStorage(e.RENDERBUFFER,ge,M.width,M.height);e.framebufferRenderbuffer(e.FRAMEBUFFER,ve,e.RENDERBUFFER,N)}else{let ee=M.textures;for(let he=0;he<ee.length;he++){let ge=ee[he],ve=s.convert(ge.format,ge.colorSpace),re=s.convert(ge.type),oe=y(ge.internalFormat,ve,re,ge.normalized,ge.colorSpace);if(z(M))o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,nn(M),oe,M.width,M.height);else if(V)e.renderbufferStorageMultisample(e.RENDERBUFFER,nn(M),oe,M.width,M.height);else e.renderbufferStorage(e.RENDERBUFFER,oe,M.width,M.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function Re(N,M,V){let ee=M.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,N),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");let he=i.get(M.depthTexture);if(he.__renderTarget=M,!he.__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0;if(ee){if(he.__webglInit===void 0)he.__webglInit=!0,M.depthTexture.addEventListener("dispose",w);if(he.__webglTexture===void 0){he.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,he.__webglTexture),pe(e.TEXTURE_CUBE_MAP,M.depthTexture);let Ie=s.convert(M.depthTexture.format),Ve=s.convert(M.depthTexture.type),Ee;if(M.depthTexture.format===Ta)Ee=e.DEPTH_COMPONENT24;else if(M.depthTexture.format===Aa)Ee=e.DEPTH24_STENCIL8;for(let me=0;me<6;me++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,Ee,M.width,M.height,0,Ie,Ve,null)}}else K(M.depthTexture,0);let ge=he.__webglTexture,ve=nn(M),re=ee?e.TEXTURE_CUBE_MAP_POSITIVE_X+V:e.TEXTURE_2D,oe=M.depthTexture.format===Aa?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(M.depthTexture.format===Ta)if(z(M))o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,oe,re,ge,0,ve);else e.framebufferTexture2D(e.FRAMEBUFFER,oe,re,ge,0);else if(M.depthTexture.format===Aa)if(z(M))o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,oe,re,ge,0,ve);else e.framebufferTexture2D(e.FRAMEBUFFER,oe,re,ge,0);else throw Error("THREE.WebGLTextures: Unknown depthTexture format.")}function ke(N){let M=i.get(N),V=N.isWebGLCubeRenderTarget===!0;if(M.__boundDepthTexture!==N.depthTexture){let ee=N.depthTexture;if(M.__depthDisposeCallback)M.__depthDisposeCallback();if(ee){let he=()=>{delete M.__boundDepthTexture,delete M.__depthDisposeCallback,ee.removeEventListener("dispose",he)};ee.addEventListener("dispose",he),M.__depthDisposeCallback=he}M.__boundDepthTexture=ee}if(N.depthTexture&&!M.__autoAllocateDepthBuffer)if(V)for(let ee=0;ee<6;ee++)Re(M.__webglFramebuffer[ee],N,ee);else{let ee=N.texture.mipmaps;if(ee&&ee.length>0)Re(M.__webglFramebuffer[0],N,0);else Re(M.__webglFramebuffer,N,0)}else if(V){M.__webglDepthbuffer=[];for(let ee=0;ee<6;ee++)if(n.bindFramebuffer(e.FRAMEBUFFER,M.__webglFramebuffer[ee]),M.__webglDepthbuffer[ee]===void 0)M.__webglDepthbuffer[ee]=e.createRenderbuffer(),_e(M.__webglDepthbuffer[ee],N,!1);else{let he=N.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ge=M.__webglDepthbuffer[ee];e.bindRenderbuffer(e.RENDERBUFFER,ge),e.framebufferRenderbuffer(e.FRAMEBUFFER,he,e.RENDERBUFFER,ge)}}else{let ee=N.texture.mipmaps;if(ee&&ee.length>0)n.bindFramebuffer(e.FRAMEBUFFER,M.__webglFramebuffer[0]);else n.bindFramebuffer(e.FRAMEBUFFER,M.__webglFramebuffer);if(M.__webglDepthbuffer===void 0)M.__webglDepthbuffer=e.createRenderbuffer(),_e(M.__webglDepthbuffer,N,!1);else{let he=N.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ge=M.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,ge),e.framebufferRenderbuffer(e.FRAMEBUFFER,he,e.RENDERBUFFER,ge)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function We(N,M,V){let ee=i.get(N);if(M!==void 0)ce(ee.__webglFramebuffer,N,N.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0);if(V!==void 0)ke(N)}function Qe(N){let M=N.texture,V=i.get(N),ee=i.get(M);N.addEventListener("dispose",T);let he=N.textures,ge=N.isWebGLCubeRenderTarget===!0,ve=he.length>1;if(!ve){if(ee.__webglTexture===void 0)ee.__webglTexture=e.createTexture();ee.__version=M.version,a.memory.textures++}if(ge){V.__webglFramebuffer=[];for(let re=0;re<6;re++)if(M.mipmaps&&M.mipmaps.length>0){V.__webglFramebuffer[re]=[];for(let oe=0;oe<M.mipmaps.length;oe++)V.__webglFramebuffer[re][oe]=e.createFramebuffer()}else V.__webglFramebuffer[re]=e.createFramebuffer()}else{if(M.mipmaps&&M.mipmaps.length>0){V.__webglFramebuffer=[];for(let re=0;re<M.mipmaps.length;re++)V.__webglFramebuffer[re]=e.createFramebuffer()}else V.__webglFramebuffer=e.createFramebuffer();if(ve)for(let re=0,oe=he.length;re<oe;re++){let Ie=i.get(he[re]);if(Ie.__webglTexture===void 0)Ie.__webglTexture=e.createTexture(),a.memory.textures++}if(N.samples>0&&z(N)===!1){V.__webglMultisampledFramebuffer=e.createFramebuffer(),V.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let re=0;re<he.length;re++){let oe=he[re];V.__webglColorRenderbuffer[re]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,V.__webglColorRenderbuffer[re]);let Ie=s.convert(oe.format,oe.colorSpace),Ve=s.convert(oe.type),Ee=y(oe.internalFormat,Ie,Ve,oe.normalized,oe.colorSpace,N.isXRRenderTarget===!0),me=nn(N);e.renderbufferStorageMultisample(e.RENDERBUFFER,me,Ee,N.width,N.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+re,e.RENDERBUFFER,V.__webglColorRenderbuffer[re])}if(e.bindRenderbuffer(e.RENDERBUFFER,null),N.depthBuffer)V.__webglDepthRenderbuffer=e.createRenderbuffer(),_e(V.__webglDepthRenderbuffer,N,!0);n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(ge){n.bindTexture(e.TEXTURE_CUBE_MAP,ee.__webglTexture),pe(e.TEXTURE_CUBE_MAP,M);for(let re=0;re<6;re++)if(M.mipmaps&&M.mipmaps.length>0)for(let oe=0;oe<M.mipmaps.length;oe++)ce(V.__webglFramebuffer[re][oe],N,M,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+re,oe);else ce(V.__webglFramebuffer[re],N,M,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+re,0);if(p(M))x(e.TEXTURE_CUBE_MAP);n.unbindTexture()}else if(ve){for(let re=0,oe=he.length;re<oe;re++){let Ie=he[re],Ve=i.get(Ie),Ee=e.TEXTURE_2D;if(N.isWebGL3DRenderTarget||N.isWebGLArrayRenderTarget)Ee=N.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY;if(n.bindTexture(Ee,Ve.__webglTexture),pe(Ee,Ie),ce(V.__webglFramebuffer,N,Ie,e.COLOR_ATTACHMENT0+re,Ee,0),p(Ie))x(Ee)}n.unbindTexture()}else{let re=e.TEXTURE_2D;if(N.isWebGL3DRenderTarget||N.isWebGLArrayRenderTarget)re=N.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY;if(n.bindTexture(re,ee.__webglTexture),pe(re,M),M.mipmaps&&M.mipmaps.length>0)for(let oe=0;oe<M.mipmaps.length;oe++)ce(V.__webglFramebuffer[oe],N,M,e.COLOR_ATTACHMENT0,re,oe);else ce(V.__webglFramebuffer,N,M,e.COLOR_ATTACHMENT0,re,0);if(p(M))x(re);n.unbindTexture()}if(N.depthBuffer)ke(N)}function Wt(N){let M=N.textures;for(let V=0,ee=M.length;V<ee;V++){let he=M[V];if(p(he)){let ge=_(N),ve=i.get(he).__webglTexture;n.bindTexture(ge,ve),x(ge),n.unbindTexture()}}}let lt=[],Lt=[];function Qt(N){if(N.samples>0){if(z(N)===!1){let{textures:M,width:V,height:ee}=N,he=e.COLOR_BUFFER_BIT,ge=N.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ve=i.get(N),re=M.length>1;if(re)for(let Ie=0;Ie<M.length;Ie++)n.bindFramebuffer(e.FRAMEBUFFER,ve.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ie,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,ve.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ie,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,ve.__webglMultisampledFramebuffer);let oe=N.texture.mipmaps;if(oe&&oe.length>0)n.bindFramebuffer(e.DRAW_FRAMEBUFFER,ve.__webglFramebuffer[0]);else n.bindFramebuffer(e.DRAW_FRAMEBUFFER,ve.__webglFramebuffer);for(let Ie=0;Ie<M.length;Ie++){if(N.resolveDepthBuffer){if(N.depthBuffer)he|=e.DEPTH_BUFFER_BIT;if(N.stencilBuffer&&N.resolveStencilBuffer)he|=e.STENCIL_BUFFER_BIT}if(re){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,ve.__webglColorRenderbuffer[Ie]);let Ve=i.get(M[Ie]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,Ve,0)}if(e.blitFramebuffer(0,0,V,ee,0,0,V,ee,he,e.NEAREST),c===!0){if(lt.length=0,Lt.length=0,lt.push(e.COLOR_ATTACHMENT0+Ie),N.depthBuffer&&N.storeMultisampledDepthBuffer===!1)lt.push(ge),Lt.push(ge),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,Lt);e.invalidateFramebuffer(e.READ_FRAMEBUFFER,lt)}}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),re)for(let Ie=0;Ie<M.length;Ie++){n.bindFramebuffer(e.FRAMEBUFFER,ve.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ie,e.RENDERBUFFER,ve.__webglColorRenderbuffer[Ie]);let Ve=i.get(M[Ie]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,ve.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+Ie,e.TEXTURE_2D,Ve,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,ve.__webglMultisampledFramebuffer)}else if(N.depthBuffer&&N.storeMultisampledDepthBuffer===!1&&c){let M=N.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[M])}}}function nn(N){return Math.min(r.maxSamples,N.samples)}function z(N){let M=i.get(N);return N.samples>0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function _n(N){let M=a.render.frame;if(u.get(N)!==M)u.set(N,M),N.update()}function St(N,M){let{colorSpace:V,format:ee,type:he}=N;if(N.isCompressedTexture===!0||N.isVideoTexture===!0)return M;if(V!==ci&&V!==Sa)if(ot.getTransfer(V)===Bt){if(ee!==pr||he!==zi)je("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}else Ye("WebGLTextures: Unsupported texture color space:",V);return M}function Xt(N){if(typeof HTMLImageElement<"u"&&N instanceof HTMLImageElement)l.width=N.naturalWidth||N.width,l.height=N.naturalHeight||N.height;else if(typeof VideoFrame<"u"&&N instanceof VideoFrame)l.width=N.displayWidth,l.height=N.displayHeight;else l.width=N.width,l.height=N.height;return l}this.allocateTextureUnit=L,this.resetTextureUnits=k,this.getTextureUnits=C,this.setTextureUnits=U,this.setTexture2D=K,this.setTexture2DArray=B,this.setTexture3D=X,this.setTextureCube=q,this.rebindTextures=We,this.setupRenderTarget=Qe,this.updateRenderTargetMipmap=Wt,this.updateMultisampleRenderTarget=Qt,this.setupDepthRenderbuffer=ke,this.setupFrameBufferTexture=ce,this.useMultisampledRTT=z,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function r8(e,t){function n(i,r=Sa){let s,a=ot.getTransfer(r);if(i===zi)return e.UNSIGNED_BYTE;if(i===Wp)return e.UNSIGNED_SHORT_4_4_4_4;if(i===Xp)return e.UNSIGNED_SHORT_5_5_5_1;if(i===OT)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===kT)return e.UNSIGNED_INT_10F_11F_11F_REV;if(i===NT)return e.BYTE;if(i===PT)return e.SHORT;if(i===Yc)return e.UNSIGNED_SHORT;if(i===Kp)return e.INT;if(i===hs)return e.UNSIGNED_INT;if(i===Br)return e.FLOAT;if(i===hr)return e.HALF_FLOAT;if(i===DT)return e.ALPHA;if(i===LT)return e.RGB;if(i===pr)return e.RGBA;if(i===Ta)return e.DEPTH_COMPONENT;if(i===Aa)return e.DEPTH_STENCIL;if(i===FT)return e.RED;if(i===qp)return e.RED_INTEGER;if(i===wa)return e.RG;if(i===Jp)return e.RG_INTEGER;if(i===Zp)return e.RGBA_INTEGER;if(i===bd||i===xd||i===yd||i===_d)if(a===Bt)if(s=t.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===bd)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===xd)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===yd)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===_d)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=t.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===bd)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===xd)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===yd)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===_d)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Yp||i===Qp||i===em||i===tm)if(s=t.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===Yp)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Qp)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===em)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===tm)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===nm||i===im||i===rm||i===sm||i===am||i===vd||i===om)if(s=t.get("WEBGL_compressed_texture_etc"),s!==null){if(i===nm||i===im)return a===Bt?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===rm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===sm)return s.COMPRESSED_R11_EAC;if(i===am)return s.COMPRESSED_SIGNED_R11_EAC;if(i===vd)return s.COMPRESSED_RG11_EAC;if(i===om)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===cm||i===lm||i===um||i===dm||i===fm||i===hm||i===pm||i===mm||i===gm||i===bm||i===xm||i===ym||i===_m||i===vm)if(s=t.get("WEBGL_compressed_texture_astc"),s!==null){if(i===cm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===lm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===um)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===dm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===fm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===hm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===pm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===mm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===gm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===bm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===xm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===ym)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===_m)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===vm)return a===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Em||i===Tm||i===Am)if(s=t.get("EXT_texture_compression_bptc"),s!==null){if(i===Em)return a===Bt?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===Tm)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Am)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===wm||i===Sm||i===Ed||i===Mm)if(s=t.get("EXT_texture_compression_rgtc"),s!==null){if(i===wm)return s.COMPRESSED_RED_RGTC1_EXT;if(i===Sm)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===Ed)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Mm)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;if(i===Co)return e.UNSIGNED_INT_24_8;return e[i]!==void 0?e[i]:null}return{convert:n}}class LA{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new kd(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 Ei({vertexShader:s8,fragmentShader:a8,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new jt(new ul(20,20),n)}}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}function c8(e,t){function n(g,p){if(g.matrixAutoUpdate===!0)g.updateMatrix();p.value.copy(g.matrix)}function i(g,p){if(p.color.getRGB(g.fogColor.value,Bm(e)),p.isFog)g.fogNear.value=p.near,g.fogFar.value=p.far;else if(p.isFogExp2)g.fogDensity.value=p.density}function r(g,p,x,_,y){if(p.isNodeMaterial)p.uniformsNeedUpdate=!1;else if(p.isMeshBasicMaterial)s(g,p);else if(p.isMeshLambertMaterial){if(s(g,p),p.envMap)g.envMapIntensity.value=p.envMapIntensity}else if(p.isMeshToonMaterial)s(g,p),d(g,p);else if(p.isMeshPhongMaterial){if(s(g,p),u(g,p),p.envMap)g.envMapIntensity.value=p.envMapIntensity}else if(p.isMeshStandardMaterial){if(s(g,p),f(g,p),p.isMeshPhysicalMaterial)h(g,p,y)}else if(p.isMeshMatcapMaterial)s(g,p),b(g,p);else if(p.isMeshDepthMaterial)s(g,p);else if(p.isMeshDistanceMaterial)s(g,p),m(g,p);else if(p.isMeshNormalMaterial)s(g,p);else if(p.isLineBasicMaterial){if(a(g,p),p.isLineDashedMaterial)o(g,p)}else if(p.isPointsMaterial)c(g,p,x,_);else if(p.isSpriteMaterial)l(g,p);else if(p.isShadowMaterial)g.color.value.copy(p.color),g.opacity.value=p.opacity;else if(p.isShaderMaterial)p.uniformsNeedUpdate=!1}function s(g,p){if(g.opacity.value=p.opacity,p.color)g.diffuse.value.copy(p.color);if(p.emissive)g.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity);if(p.map)g.map.value=p.map,n(p.map,g.mapTransform);if(p.alphaMap)g.alphaMap.value=p.alphaMap,n(p.alphaMap,g.alphaMapTransform);if(p.bumpMap){if(g.bumpMap.value=p.bumpMap,n(p.bumpMap,g.bumpMapTransform),g.bumpScale.value=p.bumpScale,p.side===Dn)g.bumpScale.value*=-1}if(p.normalMap){if(g.normalMap.value=p.normalMap,n(p.normalMap,g.normalMapTransform),g.normalScale.value.copy(p.normalScale),p.side===Dn)g.normalScale.value.negate()}if(p.displacementMap)g.displacementMap.value=p.displacementMap,n(p.displacementMap,g.displacementMapTransform),g.displacementScale.value=p.displacementScale,g.displacementBias.value=p.displacementBias;if(p.emissiveMap)g.emissiveMap.value=p.emissiveMap,n(p.emissiveMap,g.emissiveMapTransform);if(p.specularMap)g.specularMap.value=p.specularMap,n(p.specularMap,g.specularMapTransform);if(p.alphaTest>0)g.alphaTest.value=p.alphaTest;let x=t.get(p),{envMap:_,envMapRotation:y}=x;if(_){if(g.envMap.value=_,g.envMapRotation.value.setFromMatrix4(o8.makeRotationFromEuler(y)).transpose(),_.isCubeTexture&&_.isRenderTargetTexture===!1)g.envMapRotation.value.premultiply(UA);g.reflectivity.value=p.reflectivity,g.ior.value=p.ior,g.refractionRatio.value=p.refractionRatio}if(p.lightMap)g.lightMap.value=p.lightMap,g.lightMapIntensity.value=p.lightMapIntensity,n(p.lightMap,g.lightMapTransform);if(p.aoMap)g.aoMap.value=p.aoMap,g.aoMapIntensity.value=p.aoMapIntensity,n(p.aoMap,g.aoMapTransform)}function a(g,p){if(g.diffuse.value.copy(p.color),g.opacity.value=p.opacity,p.map)g.map.value=p.map,n(p.map,g.mapTransform)}function o(g,p){g.dashSize.value=p.dashSize,g.totalSize.value=p.dashSize+p.gapSize,g.scale.value=p.scale}function c(g,p,x,_){if(g.diffuse.value.copy(p.color),g.opacity.value=p.opacity,g.size.value=p.size*x,g.scale.value=_*0.5,p.map)g.map.value=p.map,n(p.map,g.uvTransform);if(p.alphaMap)g.alphaMap.value=p.alphaMap,n(p.alphaMap,g.alphaMapTransform);if(p.alphaTest>0)g.alphaTest.value=p.alphaTest}function l(g,p){if(g.diffuse.value.copy(p.color),g.opacity.value=p.opacity,g.rotation.value=p.rotation,p.map)g.map.value=p.map,n(p.map,g.mapTransform);if(p.alphaMap)g.alphaMap.value=p.alphaMap,n(p.alphaMap,g.alphaMapTransform);if(p.alphaTest>0)g.alphaTest.value=p.alphaTest}function u(g,p){g.specular.value.copy(p.specular),g.shininess.value=Math.max(p.shininess,0.0001)}function d(g,p){if(p.gradientMap)g.gradientMap.value=p.gradientMap}function f(g,p){if(g.metalness.value=p.metalness,p.metalnessMap)g.metalnessMap.value=p.metalnessMap,n(p.metalnessMap,g.metalnessMapTransform);if(g.roughness.value=p.roughness,p.roughnessMap)g.roughnessMap.value=p.roughnessMap,n(p.roughnessMap,g.roughnessMapTransform);if(p.envMap)g.envMapIntensity.value=p.envMapIntensity}function h(g,p,x){if(g.ior.value=p.ior,p.sheen>0){if(g.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),g.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap)g.sheenColorMap.value=p.sheenColorMap,n(p.sheenColorMap,g.sheenColorMapTransform);if(p.sheenRoughnessMap)g.sheenRoughnessMap.value=p.sheenRoughnessMap,n(p.sheenRoughnessMap,g.sheenRoughnessMapTransform)}if(p.clearcoat>0){if(g.clearcoat.value=p.clearcoat,g.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap)g.clearcoatMap.value=p.clearcoatMap,n(p.clearcoatMap,g.clearcoatMapTransform);if(p.clearcoatRoughnessMap)g.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,n(p.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform);if(p.clearcoatNormalMap){if(g.clearcoatNormalMap.value=p.clearcoatNormalMap,n(p.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===Dn)g.clearcoatNormalScale.value.negate()}}if(p.dispersion>0)g.dispersion.value=p.dispersion;if(p.retroreflectivity>0)g.retroreflectivity.value=p.retroreflectivity;if(p.iridescence>0){if(g.iridescence.value=p.iridescence,g.iridescenceIOR.value=p.iridescenceIOR,g.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap)g.iridescenceMap.value=p.iridescenceMap,n(p.iridescenceMap,g.iridescenceMapTransform);if(p.iridescenceThicknessMap)g.iridescenceThicknessMap.value=p.iridescenceThicknessMap,n(p.iridescenceThicknessMap,g.iridescenceThicknessMapTransform)}if(p.transmission>0){if(g.transmission.value=p.transmission,g.transmissionSamplerMap.value=x.texture,g.transmissionSamplerSize.value.set(x.width,x.height),p.transmissionMap)g.transmissionMap.value=p.transmissionMap,n(p.transmissionMap,g.transmissionMapTransform);if(g.thickness.value=p.thickness,p.thicknessMap)g.thicknessMap.value=p.thicknessMap,n(p.thicknessMap,g.thicknessMapTransform);g.attenuationDistance.value=p.attenuationDistance,g.attenuationColor.value.copy(p.attenuationColor)}if(p.anisotropy>0){if(g.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap)g.anisotropyMap.value=p.anisotropyMap,n(p.anisotropyMap,g.anisotropyMapTransform)}if(g.specularIntensity.value=p.specularIntensity,g.specularColor.value.copy(p.specularColor),p.specularColorMap)g.specularColorMap.value=p.specularColorMap,n(p.specularColorMap,g.specularColorMapTransform);if(p.specularIntensityMap)g.specularIntensityMap.value=p.specularIntensityMap,n(p.specularIntensityMap,g.specularIntensityMapTransform)}function b(g,p){if(p.matcap)g.matcap.value=p.matcap}function m(g,p){let x=t.get(p).light;g.referencePosition.value.setFromMatrixPosition(x.matrixWorld),g.nearDistance.value=x.shadow.camera.near,g.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:r}}function l8(e,t,n,i){let r={},s={},a=[],o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(y,v){let E=v.program;i.uniformBlockBinding(y,E)}function l(y,v){let E=r[y.id];if(E===void 0)g(y),E=u(y),r[y.id]=E,y.addEventListener("dispose",x);let w=v.program;i.updateUBOMapping(y,w);let T=t.render.frame;if(s[y.id]!==T)f(y),s[y.id]=T}function u(y){let v=d();y.__bindingPointIndex=v;let E=e.createBuffer(),{__size:w,usage:T}=y;return e.bindBuffer(e.UNIFORM_BUFFER,E),e.bufferData(e.UNIFORM_BUFFER,w,T),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,v,E),E}function d(){for(let y=0;y<o;y++)if(a.indexOf(y)===-1)return a.push(y),y;return Ye("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function f(y){let v=r[y.id],{uniforms:E,__cache:w}=y;e.bindBuffer(e.UNIFORM_BUFFER,v);for(let T=0,A=E.length;T<A;T++){let P=E[T];if(Array.isArray(P))for(let S=0,R=P.length;S<R;S++)h(P[S],T,S,w);else h(P,T,0,w)}e.bindBuffer(e.UNIFORM_BUFFER,null)}function h(y,v,E,w){if(m(y,v,E,w)===!0){let{__offset:T,value:A}=y;if(Array.isArray(A)){let P=0;for(let S=0;S<A.length;S++){let R=A[S],k=p(R);if(b(R,y.__data,P),typeof R!=="number"&&typeof R!=="boolean"&&!R.isMatrix3&&!ArrayBuffer.isView(R))P+=k.storage/Float32Array.BYTES_PER_ELEMENT}}else b(A,y.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,T,y.__data)}}function b(y,v,E){if(typeof y==="number"||typeof y==="boolean")v[0]=y;else if(y.isMatrix3)v[0]=y.elements[0],v[1]=y.elements[1],v[2]=y.elements[2],v[3]=0,v[4]=y.elements[3],v[5]=y.elements[4],v[6]=y.elements[5],v[7]=0,v[8]=y.elements[6],v[9]=y.elements[7],v[10]=y.elements[8],v[11]=0;else if(ArrayBuffer.isView(y))v.set(new y.constructor(y.buffer,y.byteOffset,v.length));else y.toArray(v,E)}function m(y,v,E,w){let T=y.value,A=v+"_"+E;if(w[A]===void 0){if(typeof T==="number"||typeof T==="boolean")w[A]=T;else if(ArrayBuffer.isView(T))w[A]=T.slice();else w[A]=T.clone();return!0}else{let P=w[A];if(typeof T==="number"||typeof T==="boolean"){if(P!==T)return w[A]=T,!0}else if(ArrayBuffer.isView(T))return!0;else if(P.equals(T)===!1)return P.copy(T),!0}return!1}function g(y){let v=y.uniforms,E=0,w=16;for(let A=0,P=v.length;A<P;A++){let S=Array.isArray(v[A])?v[A]:[v[A]];for(let R=0,k=S.length;R<k;R++){let C=S[R],U=Array.isArray(C.value)?C.value:[C.value];for(let L=0,O=U.length;L<O;L++){let K=U[L],B=p(K),X=E%w,q=X%B.boundary,le=X+q;if(E+=q,le!==0&&w-le<B.storage)E+=w-le;C.__data=new Float32Array(B.storage/Float32Array.BYTES_PER_ELEMENT),C.__offset=E,E+=B.storage}}}let T=E%w;if(T>0)E+=w-T;return y.__size=E,y.__cache={},this}function p(y){let v={boundary:0,storage:0};if(typeof y==="number"||typeof y==="boolean")v.boundary=4,v.storage=4;else if(y.isVector2)v.boundary=8,v.storage=8;else if(y.isVector3||y.isColor)v.boundary=16,v.storage=12;else if(y.isVector4)v.boundary=16,v.storage=16;else if(y.isMatrix3)v.boundary=48,v.storage=48;else if(y.isMatrix4)v.boundary=64,v.storage=64;else if(y.isTexture)je("WebGLRenderer: Texture samplers can not be part of an uniforms group.");else if(ArrayBuffer.isView(y))v.boundary=16,v.storage=y.byteLength;else je("WebGLRenderer: Unsupported uniform value type.",y);return v}function x(y){let v=y.target;v.removeEventListener("dispose",x);let E=a.indexOf(v.__bindingPointIndex);a.splice(E,1),e.deleteBuffer(r[v.id]),delete r[v.id],delete s[v.id]}function _(){for(let y in r)e.deleteBuffer(r[y]);a=[],r={},s={}}return{bind:c,update:l,dispose:_}}function d8(){if(gr===null)gr=new sl(u8,16,16,wa,hr),gr.name="DFG_LUT",gr.minFilter=Tn,gr.magFilter=Tn,gr.wrapS=Ro,gr.wrapT=Ro,gr.generateMipmaps=!1,gr.needsUpdate=!0;return gr}class fg{constructor(e={}){let{canvas:t=$T(),context:n=null,depth:i=!0,stencil:r=!1,alpha:s=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:c=!1,powerPreference:l="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=zi}=e;this.isWebGLRenderer=!0;let h;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");h=n.getContextAttributes().alpha}else h=s;let b=f,m=new Set([Zp,Jp,qp]),g=new Set([zi,hs,Yc,Co,Wp,Xp]),p=new Uint32Array(4),x=new Int32Array(4),_=new j,y=null,v=null,E=[],w=[],T=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Ui,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let A=this,P=!1,S=null,R=null,k=null,C=null;this._outputColorSpace=ps;let U=0,L=0,O=null,K=-1,B=null,X=new Pt,q=new Pt,le=null,de=new qe(0),Me=0,{width:pe,height:J}=t,F=1,W=null,ne=null,ie=new Pt(0,0,pe,J),ce=new Pt(0,0,pe,J),_e=!1,Re=new ol,ke=!1,We=!1,Qe=new Je,Wt=new j,lt=new Pt,Lt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Qt=!1;function nn(){return O===null?F:1}let z=n;function _n(I,H){return t.getContext(I,H)}let St,Xt,N,M,V,ee,he,ge,ve,re,oe,Ie,Ve,Ee,me,Ge,Xe,vt,G,xe,ae,ye,Ce;try{let I={alpha:!0,depth:i,stencil:r,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if("setAttribute"in t)t.setAttribute("data-engine",`three.js r${ZE}`);if(t.addEventListener("webglcontextlost",it,!1),t.addEventListener("webglcontextrestored",zt,!1),t.addEventListener("webglcontextcreationerror",Mt,!1),z===null){if(z=_n("webgl2",I),z===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.")}fe()}catch(I){throw t.removeEventListener("webglcontextlost",it,!1),t.removeEventListener("webglcontextrestored",zt,!1),t.removeEventListener("webglcontextcreationerror",Mt,!1),Ye("WebGLRenderer: "+I.message),I}function fe(){if(St=new xD(z),St.init(),ae=new r8(z,St),Xt=new cD(z,St,e,ae),N=new n8(z,St),Xt.reversedDepthBuffer&&d)N.buffers.depth.setReversed(!0);R=z.createFramebuffer(),k=z.createFramebuffer(),C=z.createFramebuffer(),M=new vD(z),V=new jL,ee=new i8(z,St,N,V,Xt,ae,M),he=new bD(A),ge=new TP(z),ye=new aD(z,ge),ve=new yD(z,ge,M,ye),re=new TD(z,ve,ge,ye,M),vt=new ED(z,Xt,ee),me=new lD(V),oe=new VL(A,he,St,Xt,ye,me),Ie=new c8(A,V),Ve=new GL,Ee=new JL(St),Xe=new sD(A,he,N,re,h,o),Ge=new t8(A,re,Xt),Ce=new l8(z,M,Xt,N),G=new oD(z,St,M),xe=new _D(z,St,M),M.programs=oe.programs,A.capabilities=Xt,A.extensions=St,A.properties=V,A.renderLists=Ve,A.shadowMap=Ge,A.state=N,A.info=M}if(b!==zi)T=new wD(b,t.width,t.height,a,i,r);let Ae=new FA(A,z);this.xr=Ae,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){let I=St.get("WEBGL_lose_context");if(I)I.loseContext()},this.forceContextRestore=function(){let I=St.get("WEBGL_lose_context");if(I)I.restoreContext()},this.getPixelRatio=function(){return F},this.setPixelRatio=function(I){if(I===void 0)return;F=I,this.setSize(pe,J,!1)},this.getSize=function(I){return I.set(pe,J)},this.setSize=function(I,H,te=!0){if(Ae.isPresenting){je("WebGLRenderer: Can't change size while VR device is presenting.");return}if(pe=I,J=H,t.width=Math.floor(I*F),t.height=Math.floor(H*F),te===!0)t.style.width=I+"px",t.style.height=H+"px";if(T!==null)T.setSize(t.width,t.height);this.setViewport(0,0,I,H)},this.getDrawingBufferSize=function(I){return I.set(pe*F,J*F).floor()},this.setDrawingBufferSize=function(I,H,te){pe=I,J=H,F=te,t.width=Math.floor(I*te),t.height=Math.floor(H*te),this.setViewport(0,0,I,H)},this.setEffects=function(I){if(b===zi){Ye("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(I){for(let H=0;H<I.length;H++)if(I[H].isOutputPass===!0){je("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}T.setEffects(I||[])},this.getCurrentViewport=function(I){return I.copy(X)},this.getViewport=function(I){return I.copy(ie)},this.setViewport=function(I,H,te,Z){if(I.isVector4)ie.set(I.x,I.y,I.z,I.w);else ie.set(I,H,te,Z);N.viewport(X.copy(ie).multiplyScalar(F).round())},this.getScissor=function(I){return I.copy(ce)},this.setScissor=function(I,H,te,Z){if(I.isVector4)ce.set(I.x,I.y,I.z,I.w);else ce.set(I,H,te,Z);N.scissor(q.copy(ce).multiplyScalar(F).round())},this.getScissorTest=function(){return _e},this.setScissorTest=function(I){N.setScissorTest(_e=I)},this.setOpaqueSort=function(I){W=I},this.setTransparentSort=function(I){ne=I},this.getClearColor=function(I){return I.copy(Xe.getClearColor())},this.setClearColor=function(){Xe.setClearColor(...arguments)},this.getClearAlpha=function(){return Xe.getClearAlpha()},this.setClearAlpha=function(){Xe.setClearAlpha(...arguments)},this.clear=function(I=!0,H=!0,te=!0){let Z=0;if(I){let Y=!1;if(O!==null){let Se=O.texture.format;Y=m.has(Se)}if(Y){let Se=O.texture.type,Pe=g.has(Se),we=Xe.getClearColor(),De=Xe.getClearAlpha(),{r:ze,g:rt,b:ft}=we;if(Pe)p[0]=ze,p[1]=rt,p[2]=ft,p[3]=De,z.clearBufferuiv(z.COLOR,0,p);else x[0]=ze,x[1]=rt,x[2]=ft,x[3]=De,z.clearBufferiv(z.COLOR,0,x)}else Z|=z.COLOR_BUFFER_BIT}if(H)Z|=z.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0);if(te)Z|=z.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295);if(Z!==0)z.clear(Z)},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(I){I.setRenderer(this),S=I},this.dispose=function(){t.removeEventListener("webglcontextlost",it,!1),t.removeEventListener("webglcontextrestored",zt,!1),t.removeEventListener("webglcontextcreationerror",Mt,!1),Xe.dispose(),Ve.dispose(),Ee.dispose(),V.dispose(),he.dispose(),re.dispose(),ye.dispose(),Ce.dispose(),oe.dispose(),Ae.dispose(),Ae.removeEventListener("sessionstart",Sb),Ae.removeEventListener("sessionend",Mb),ia.stop()};function it(I){I.preventDefault(),Wc("WebGLRenderer: Context Lost."),P=!0}function zt(){Wc("WebGLRenderer: Context Restored."),P=!1;let I=M.autoReset,H=Ge.enabled,te=Ge.autoUpdate,Z=Ge.needsUpdate,Y=Ge.type;fe(),M.autoReset=I,Ge.enabled=H,Ge.autoUpdate=te,Ge.needsUpdate=Z,Ge.type=Y}function Mt(I){Ye("WebGLRenderer: A WebGL context could not be created. Reason: ",I.statusMessage)}function Xi(I){let H=I.target;H.removeEventListener("dispose",Xi),wr(H)}function wr(I){YR(I),V.remove(I)}function YR(I){let H=V.get(I).programs;if(H!==void 0){if(H.forEach(function(te){oe.releaseProgram(te)}),I.isShaderMaterial)oe.releaseShaderCache(I)}}this.renderBufferDirect=function(I,H,te,Z,Y,Se){if(H===null)H=Lt;let Pe=Y.isMesh&&Y.matrixWorld.determinantAffine()<0,we=tI(I,H,te,Z,Y);N.setMaterial(Z,Pe);let De=te.index,ze=1;if(Z.wireframe===!0){if(De=ve.getWireframeAttribute(te),De===void 0)return;ze=2}let rt=te.drawRange,ft=te.attributes.position,Le=rt.start*ze,Rt=(rt.start+rt.count)*ze;if(Se!==null)Le=Math.max(Le,Se.start*ze),Rt=Math.min(Rt,(Se.start+Se.count)*ze);if(De!==null)Le=Math.max(Le,0),Rt=Math.min(Rt,De.count);else if(ft!==void 0&&ft!==null)Le=Math.max(Le,0),Rt=Math.min(Rt,ft.count);let on=Rt-Le;if(on<0||on===1/0)return;ye.setup(Y,Z,we,te,De);let Gt,Ft=G;if(De!==null)Gt=ge.get(De),Ft=xe,Ft.setIndex(Gt);if(Y.isMesh)if(Z.wireframe===!0)N.setLineWidth(Z.wireframeLinewidth*nn()),Ft.setMode(z.LINES);else Ft.setMode(z.TRIANGLES);else if(Y.isLine){let Cn=Z.linewidth;if(Cn===void 0)Cn=1;if(N.setLineWidth(Cn*nn()),Y.isLineSegments)Ft.setMode(z.LINES);else if(Y.isLineLoop)Ft.setMode(z.LINE_LOOP);else Ft.setMode(z.LINE_STRIP)}else if(Y.isPoints)Ft.setMode(z.POINTS);else if(Y.isSprite)Ft.setMode(z.TRIANGLES);if(Y.isBatchedMesh)if(!St.get("WEBGL_multi_draw")){let{_multiDrawStarts:Cn,_multiDrawCounts:Ne,_multiDrawCount:Un}=Y,xt=De?ge.get(De).bytesPerElement:1,pi=V.get(Z).currentProgram.getUniforms();for(let qi=0;qi<Un;qi++)pi.setValue(z,"_gl_DrawID",qi),Ft.render(Cn[qi]/xt,Ne[qi])}else Ft.renderMultiDraw(Y._multiDrawStarts,Y._multiDrawCounts,Y._multiDrawCount);else if(Y.isInstancedMesh)Ft.renderInstances(Le,on,Y.count);else if(te.isInstancedBufferGeometry){let Cn=te._maxInstanceCount!==void 0?te._maxInstanceCount:1/0,Ne=Math.min(te.instanceCount,Cn);Ft.renderInstances(Le,on,Ne)}else Ft.render(Le,on)};function wb(I,H,te,Z){if(S!==null&&I.isNodeMaterial)S.setObject(Z,I);if(ke===!0)me.setState(I,te,!1);if(I.transparent===!0&&I.side===vi&&I.forceSinglePass===!1)I.side=Dn,I.needsUpdate=!0,$l(I,H,Z),I.side=fs,I.needsUpdate=!0,$l(I,H,Z),I.side=vi;else $l(I,H,Z)}this.compile=function(I,H,te=null){if(te===null)te=I;if(S!==null)S.renderStart(I,H,te);if(v=Ee.get(te),v.init(H),w.push(v),te.traverseVisible(function(Y){if(Y.isLight&&Y.layers.test(H.layers)){if(v.pushLight(Y),Y.castShadow)v.pushShadow(Y)}}),I!==te)I.traverseVisible(function(Y){if(Y.isLight&&Y.layers.test(H.layers)){if(v.pushLight(Y),Y.castShadow)v.pushShadow(Y)}});if(v.setupLights(),S!==null)S.updateLights(v.state.lightsArray);if(We=this.localClippingEnabled,ke=me.init(this.clippingPlanes,We),ke===!0)me.setGlobalState(this.clippingPlanes,H);if(S!==null)Ge.render(v.state.shadowsArray,te,H);let Z=new Set;if(I.traverse(function(Y){if(!(Y.isMesh||Y.isPoints||Y.isLine||Y.isSprite))return;let Se=Y.material;if(Se)if(Array.isArray(Se))for(let Pe=0;Pe<Se.length;Pe++){let we=Se[Pe];wb(we,te,H,Y),Z.add(we)}else wb(Se,te,H,Y),Z.add(Se)}),v=w.pop(),S!==null)S.renderEnd();return Z},this.compileAsync=function(I,H,te=null){let Z=this.compile(I,H,te);return new Promise((Y)=>{function Se(){if(Z.forEach(function(Pe){let De=V.get(Pe).currentProgram;if(De===void 0||De.isReady())Z.delete(Pe)}),Z.size===0){Y(I);return}setTimeout(Se,10)}if(St.get("KHR_parallel_shader_compile")!==null)Se();else setTimeout(Se,10)})};let Lf=null;function QR(I){if(Lf)Lf(I)}function Sb(){ia.stop()}function Mb(){ia.start()}let ia=new wA;if(ia.setAnimationLoop(QR),typeof self<"u")ia.setContext(self);this.setAnimationLoop=function(I){Lf=I,Ae.setAnimationLoop(I),I===null?ia.stop():ia.start()},Ae.addEventListener("sessionstart",Sb),Ae.addEventListener("sessionend",Mb),this.render=function(I,H){if(H!==void 0&&H.isCamera!==!0){Ye("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(P===!0)return;if(S!==null)S.renderStart(I,H);let te=Ae.enabled===!0&&Ae.isPresenting===!0,Z=T!==null&&(O===null||te)&&T.begin(A,O);if(I.matrixWorldAutoUpdate===!0)I.updateMatrixWorld();if(H.parent===null&&H.matrixWorldAutoUpdate===!0)H.updateMatrixWorld();if(Ae.enabled===!0&&Ae.isPresenting===!0&&(T===null||T.isCompositing()===!1)){if(Ae.cameraAutoUpdate===!0)Ae.updateCamera(H);H=Ae.getCamera()}if(I.isScene===!0)I.onBeforeRender(A,I,H,O);if(v=Ee.get(I,w.length),v.init(H),v.state.textureUnits=ee.getTextureUnits(),w.push(v),Qe.multiplyMatrices(H.projectionMatrix,H.matrixWorldInverse),Re.setFromProjectionMatrix(Qe,Om,H.reversedDepth),We=this.localClippingEnabled,ke=me.init(this.clippingPlanes,We),y=Ve.get(I,E.length),y.init(),E.push(y),Ae.enabled===!0&&Ae.isPresenting===!0){let Pe=A.xr.getDepthSensingMesh();if(Pe!==null)Ff(Pe,H,-1/0,A.sortObjects)}if(Ff(I,H,0,A.sortObjects),y.finish(),S!==null)S.updateLights(v.state.lightsArray);if(A.sortObjects===!0)y.sort(W,ne);if(Qt=Ae.enabled===!1||Ae.isPresenting===!1||Ae.hasDepthSensing()===!1,Qt)Xe.addToRenderList(y,I);if(this.info.render.frame++,this.info.autoReset===!0)this.info.reset();if(ke===!0)me.beginShadows();let Y=v.state.shadowsArray;if(Ge.render(Y,I,H),ke===!0)me.endShadows();if((Z&&T.hasRenderPass())===!1){let Pe=y.opaque,we=y.transmissive;if(v.setupLights(),H.isArrayCamera){let De=H.cameras;if(we.length>0)for(let ze=0,rt=De.length;ze<rt;ze++){let ft=De[ze];Ib(Pe,we,I,ft)}if(Qt)Xe.render(I);for(let ze=0,rt=De.length;ze<rt;ze++){let ft=De[ze];Rb(y,I,ft,ft.viewport)}}else{if(we.length>0)Ib(Pe,we,I,H);if(Qt)Xe.render(I);Rb(y,I,H)}}if(O!==null&&L===0)ee.updateMultisampleRenderTarget(O),ee.updateRenderTargetMipmap(O);if(Z)T.end(A);if(I.isScene===!0)I.onAfterRender(A,I,H);if(ye.resetDefaultState(),K=-1,B=null,w.pop(),w.length>0){if(v=w[w.length-1],ee.setTextureUnits(v.state.textureUnits),ke===!0)me.setGlobalState(A.clippingPlanes,v.state.camera)}else v=null;if(E.pop(),E.length>0)y=E[E.length-1];else y=null;if(S!==null)S.renderEnd()};function Ff(I,H,te,Z){if(I.visible===!1)return;if(I.layers.test(H.layers)){if(I.isGroup)te=I.renderOrder;else if(I.isLOD){if(I.autoUpdate===!0)I.update(H)}else if(I.isLightProbeGrid)v.pushLightProbeGrid(I);else if(I.isLight){if(v.pushLight(I),I.castShadow)v.pushShadow(I)}else if(I.isSprite){if(!I.frustumCulled||I.intersectsFrustum(Re)){if(Z)lt.setFromMatrixPosition(I.matrixWorld).applyMatrix4(Qe);let Pe=re.update(I),we=I.material;if(we.visible)y.push(I,Pe,we,te,lt.z,null,H)}}else if(I.isMesh||I.isLine||I.isPoints){if(!I.frustumCulled||I.intersectsFrustum(Re)){let Pe=re.update(I),we=I.material;if(Z){if(I.boundingSphere!==void 0){if(I.boundingSphere===null)I.computeBoundingSphere();lt.copy(I.boundingSphere.center)}else{if(Pe.boundingSphere===null)Pe.computeBoundingSphere();lt.copy(Pe.boundingSphere.center)}lt.applyMatrix4(I.matrixWorld).applyMatrix4(Qe)}if(Array.isArray(we)){let De=Pe.groups;for(let ze=0,rt=De.length;ze<rt;ze++){let ft=De[ze],Le=we[ft.materialIndex];if(Le&&Le.visible)y.push(I,Pe,Le,te,lt.z,ft,H)}}else if(we.visible)y.push(I,Pe,we,te,lt.z,null,H)}}}let Se=I.children;for(let Pe=0,we=Se.length;Pe<we;Pe++)Ff(Se[Pe],H,te,Z)}function Rb(I,H,te,Z){let{opaque:Y,transmissive:Se,transparent:Pe}=I;if(v.setupLightsView(te),ke===!0)me.setGlobalState(A.clippingPlanes,te);if(Z)N.viewport(X.copy(Z));if(Y.length>0)Gl(Y,H,te);if(Se.length>0)Gl(Se,H,te);if(Pe.length>0)Gl(Pe,H,te);N.buffers.depth.setTest(!0),N.buffers.depth.setMask(!0),N.buffers.color.setMask(!0),N.setPolygonOffset(!1)}function Ib(I,H,te,Z){if((te.isScene===!0?te.overrideMaterial:null)!==null)return;if(v.state.transmissionRenderTarget[Z.id]===void 0){let Le=St.has("EXT_color_buffer_half_float")||St.has("EXT_color_buffer_float");v.state.transmissionRenderTarget[Z.id]=new li(1,1,{generateMipmaps:!0,type:Le?hr:zi,minFilter:fr,samples:Math.max(4,Xt.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:ot.workingColorSpace})}let Se=v.state.transmissionRenderTarget[Z.id],Pe=Z.viewport||X;Se.setSize(Pe.z*A.transmissionResolutionScale,Pe.w*A.transmissionResolutionScale);let we=A.getRenderTarget(),De=A.getActiveCubeFace(),ze=A.getActiveMipmapLevel();if(A.setRenderTarget(Se),A.getClearColor(de),Me=A.getClearAlpha(),Me<1)A.setClearColor(16777215,0.5);if(A.clear(),Qt)Xe.render(te);let rt=A.toneMapping;A.toneMapping=Ui;let ft=Z.viewport;if(Z.viewport!==void 0)Z.viewport=void 0;if(v.setupLightsView(Z),ke===!0)me.setGlobalState(A.clippingPlanes,Z);if(Gl(I,te,Z),ee.updateMultisampleRenderTarget(Se),ee.updateRenderTargetMipmap(Se),St.has("WEBGL_multisampled_render_to_texture")===!1){let Le=!1;for(let Rt=0,on=H.length;Rt<on;Rt++){let Gt=H[Rt],{object:Ft,geometry:Cn,material:Ne,group:Un}=Gt;if(Ne.side===vi&&Ft.layers.test(Z.layers)){let xt=Ne.side;Ne.side=Dn,Ne.needsUpdate=!0,Cb(Ft,te,Z,Cn,Ne,Un),Ne.side=xt,Ne.needsUpdate=!0,Le=!0}}if(Le===!0)ee.updateMultisampleRenderTarget(Se),ee.updateRenderTargetMipmap(Se)}if(A.setRenderTarget(we,De,ze),A.setClearColor(de,Me),ft!==void 0)Z.viewport=ft;A.toneMapping=rt}function Gl(I,H,te){let Z=H.isScene===!0?H.overrideMaterial:null;for(let Y=0,Se=I.length;Y<Se;Y++){let Pe=I[Y],{object:we,geometry:De,group:ze}=Pe,rt=Pe.material;if(rt.allowOverride===!0&&Z!==null)rt=Z;if(we.layers.test(te.layers))Cb(we,H,te,De,rt,ze)}}function Cb(I,H,te,Z,Y,Se){if(S!==null&&Y.isNodeMaterial)S.setObject(I,Y);if(I.onBeforeRender(A,H,te,Z,Y,Se),I.modelViewMatrix.multiplyMatrices(te.matrixWorldInverse,I.matrixWorld),I.normalMatrix.getNormalMatrix(I.modelViewMatrix),Y.onBeforeRender(A,H,te,Z,I,Se),Y.transparent===!0&&Y.side===vi&&Y.forceSinglePass===!1)Y.side=Dn,Y.needsUpdate=!0,A.renderBufferDirect(te,H,Z,Y,I,Se),Y.side=fs,Y.needsUpdate=!0,A.renderBufferDirect(te,H,Z,Y,I,Se),Y.side=vi;else A.renderBufferDirect(te,H,Z,Y,I,Se);I.onAfterRender(A,H,te,Z,Y,Se)}function $l(I,H,te){if(H.isScene!==!0)H=Lt;let Z=V.get(I),Y=v.state.lights,Se=v.state.shadowsArray,Pe=Y.state.version,we=oe.getParameters(I,Y.state,Se,H,te,v.state.lightProbeGridArray),De=oe.getProgramCacheKey(we),ze=Z.programs;Z.environment=I.isMeshStandardMaterial||I.isMeshLambertMaterial||I.isMeshPhongMaterial?H.environment:null,Z.fog=H.fog;let rt=I.isMeshStandardMaterial||I.isMeshLambertMaterial&&!I.envMap||I.isMeshPhongMaterial&&!I.envMap;if(Z.envMap=he.get(I.envMap||Z.environment,rt),Z.envMapRotation=Z.environment!==null&&I.envMap===null?H.environmentRotation:I.envMapRotation,ze===void 0)I.addEventListener("dispose",Xi),ze=new Map,Z.programs=ze;let ft=ze.get(De);if(ft!==void 0){if(Z.currentProgram===ft&&Z.lightsStateVersion===Pe)return Pb(I,we),ft}else{if(we.uniforms=oe.getUniforms(I),S!==null&&I.isNodeMaterial)S.build(I,te,we);I.onBeforeCompile(we,A),ft=oe.acquireProgram(we,De),ze.set(De,ft),Z.uniforms=we.uniforms}let Le=Z.uniforms;if(!I.isShaderMaterial&&!I.isRawShaderMaterial||I.clipping===!0)Le.clippingPlanes=me.uniform;if(Pb(I,we),Z.needsLights=iI(I),Z.lightsStateVersion=Pe,Z.needsLights)Le.ambientLightColor.value=Y.state.ambient,Le.lightProbe.value=Y.state.probe,Le.sunLights.value=Y.state.sun,Le.sunLightShadows.value=Y.state.sunShadow,Le.directionalLights.value=Y.state.directional,Le.directionalLightShadows.value=Y.state.directionalShadow,Le.spotLights.value=Y.state.spot,Le.spotLightShadows.value=Y.state.spotShadow,Le.rectAreaLights.value=Y.state.rectArea,Le.ltc_1.value=Y.state.rectAreaLTC1,Le.ltc_2.value=Y.state.rectAreaLTC2,Le.pointLights.value=Y.state.point,Le.pointLightShadows.value=Y.state.pointShadow,Le.hemisphereLights.value=Y.state.hemi,Le.sunShadowMatrix.value=Y.state.sunShadowMatrix,Le.sunShadowCascade.value=Y.state.sunShadowCascade,Le.directionalShadowMatrix.value=Y.state.directionalShadowMatrix,Le.spotLightMatrix.value=Y.state.spotLightMatrix,Le.spotLightMap.value=Y.state.spotLightMap,Le.pointShadowMatrix.value=Y.state.pointShadowMatrix;return Z.lightProbeGrid=v.state.lightProbeGridArray.length>0,Z.currentProgram=ft,Z.uniformsList=null,ft}function Nb(I){if(I.uniformsList===null){let H=I.currentProgram.getUniforms();I.uniformsList=xl.seqWithValue(H.seq,I.uniforms)}return I.uniformsList}function Pb(I,H){let te=V.get(I);te.outputColorSpace=H.outputColorSpace,te.batching=H.batching,te.batchingColor=H.batchingColor,te.instancing=H.instancing,te.instancingColor=H.instancingColor,te.instancingMorph=H.instancingMorph,te.skinning=H.skinning,te.morphTargets=H.morphTargets,te.morphNormals=H.morphNormals,te.morphColors=H.morphColors,te.morphTargetsCount=H.morphTargetsCount,te.numClippingPlanes=H.numClippingPlanes,te.numIntersection=H.numClipIntersection,te.vertexAlphas=H.vertexAlphas,te.vertexTangents=H.vertexTangents,te.toneMapping=H.toneMapping}function eI(I,H){if(I.length===0)return null;if(I.length===1)return I[0].texture!==null?I[0]:null;_.setFromMatrixPosition(H.matrixWorld);for(let te=0,Z=I.length;te<Z;te++){let Y=I[te];if(Y.texture!==null&&Y.boundingBox.containsPoint(_))return Y}return null}function tI(I,H,te,Z,Y){if(H.isScene!==!0)H=Lt;ee.resetTextureUnits();let Se=H.fog,Pe=Z.isMeshStandardMaterial||Z.isMeshLambertMaterial||Z.isMeshPhongMaterial?H.environment:null,we=O===null?A.outputColorSpace:O.isXRRenderTarget===!0?O.texture.colorSpace:ot.workingColorSpace,De=Z.isMeshStandardMaterial||Z.isMeshLambertMaterial&&!Z.envMap||Z.isMeshPhongMaterial&&!Z.envMap,ze=he.get(Z.envMap||Pe,De),rt=Z.vertexColors===!0&&!!te.attributes.color&&te.attributes.color.itemSize===4,ft=!!te.attributes.tangent&&(!!Z.normalMap||Z.anisotropy>0),Le=!!te.morphAttributes.position,Rt=!!te.morphAttributes.normal,on=!!te.morphAttributes.color,Gt=Ui;if(Z.toneMapped){if(O===null||O.isXRRenderTarget===!0)Gt=A.toneMapping}let Ft=te.morphAttributes.position||te.morphAttributes.normal||te.morphAttributes.color,Cn=Ft!==void 0?Ft.length:0,Ne=V.get(Z),Un=v.state.lights;if(ke===!0){if(We===!0||I!==B){let Vt=I===B&&Z.id===K;me.setState(Z,I,Vt)}}let xt=!1;if(Z.version===Ne.__version){if(Ne.needsLights&&Ne.lightsStateVersion!==Un.state.version)xt=!0;else if(Ne.outputColorSpace!==we)xt=!0;else if(Y.isBatchedMesh&&Ne.batching===!1)xt=!0;else if(!Y.isBatchedMesh&&Ne.batching===!0)xt=!0;else if(Y.isBatchedMesh&&Ne.batchingColor===!0&&Y._colorsTexture===null)xt=!0;else if(Y.isBatchedMesh&&Ne.batchingColor===!1&&Y._colorsTexture!==null)xt=!0;else if(Y.isInstancedMesh&&Ne.instancing===!1)xt=!0;else if(!Y.isInstancedMesh&&Ne.instancing===!0)xt=!0;else if(Y.isSkinnedMesh&&Ne.skinning===!1)xt=!0;else if(!Y.isSkinnedMesh&&Ne.skinning===!0)xt=!0;else if(Y.isInstancedMesh&&Ne.instancingColor===!0&&Y.instanceColor===null)xt=!0;else if(Y.isInstancedMesh&&Ne.instancingColor===!1&&Y.instanceColor!==null)xt=!0;else if(Y.isInstancedMesh&&Ne.instancingMorph===!0&&Y.morphTexture===null)xt=!0;else if(Y.isInstancedMesh&&Ne.instancingMorph===!1&&Y.morphTexture!==null)xt=!0;else if(Ne.envMap!==ze)xt=!0;else if(Z.fog===!0&&Ne.fog!==Se)xt=!0;else if(Ne.numClippingPlanes!==void 0&&(Ne.numClippingPlanes!==me.numPlanes||Ne.numIntersection!==me.numIntersection))xt=!0;else if(Ne.vertexAlphas!==rt)xt=!0;else if(Ne.vertexTangents!==ft)xt=!0;else if(Ne.morphTargets!==Le)xt=!0;else if(Ne.morphNormals!==Rt)xt=!0;else if(Ne.morphColors!==on)xt=!0;else if(Ne.toneMapping!==Gt)xt=!0;else if(Ne.morphTargetsCount!==Cn)xt=!0;else if(!!Ne.lightProbeGrid!==v.state.lightProbeGridArray.length>0)xt=!0}else xt=!0,Ne.__version=Z.version;let pi=Ne.currentProgram;if(xt===!0){if(pi=$l(Z,H,Y),S&&Z.isNodeMaterial)S.onUpdateProgram(Z,pi,Ne)}let qi=!1,Wr=!1,Va=!1,kt=pi.getUniforms(),rn=Ne.uniforms;if(N.useProgram(pi.program))qi=!0,Wr=!0,Va=!0;if(Z.id!==K)K=Z.id,Wr=!0;if(Ne.needsLights){let Vt=eI(v.state.lightProbeGridArray,Y);if(Ne.lightProbeGrid!==Vt)Ne.lightProbeGrid=Vt,Wr=!0}if(qi||B!==I){if(N.buffers.depth.getReversed()&&I.reversedDepth!==!0)I._reversedDepth=!0,I.updateProjectionMatrix();kt.setValue(z,"projectionMatrix",I.projectionMatrix),kt.setValue(z,"viewMatrix",I.matrixWorldInverse);let qr=kt.map.cameraPosition;if(qr!==void 0)qr.setValue(z,Wt.setFromMatrixPosition(I.matrixWorld));if(Xt.logarithmicDepthBuffer)kt.setValue(z,"logDepthBufFC",2/(Math.log(I.far+1)/Math.LN2));if(Z.isMeshPhongMaterial||Z.isMeshToonMaterial||Z.isMeshLambertMaterial||Z.isMeshBasicMaterial||Z.isMeshStandardMaterial||Z.isShaderMaterial)kt.setValue(z,"isOrthographic",I.isOrthographicCamera===!0);if(B!==I)B=I,Wr=!0,Va=!0}if(Ne.needsLights){if(Un.state.sunShadowMap.length>0)kt.setValue(z,"sunShadowMap",Un.state.sunShadowMap,ee);if(Un.state.directionalShadowMap.length>0)kt.setValue(z,"directionalShadowMap",Un.state.directionalShadowMap,ee);if(Un.state.spotShadowMap.length>0)kt.setValue(z,"spotShadowMap",Un.state.spotShadowMap,ee);if(Un.state.pointShadowMap.length>0)kt.setValue(z,"pointShadowMap",Un.state.pointShadowMap,ee)}if(Y.isSkinnedMesh){kt.setOptional(z,Y,"bindMatrix"),kt.setOptional(z,Y,"bindMatrixInverse");let Vt=Y.skeleton;if(Vt){if(Vt.boneTexture===null)Vt.computeBoneTexture();kt.setValue(z,"boneTexture",Vt.boneTexture,ee)}}if(Y.isBatchedMesh){if(kt.setOptional(z,Y,"batchingTexture"),kt.setValue(z,"batchingTexture",Y._matricesTexture,ee),kt.setOptional(z,Y,"batchingIdTexture"),kt.setValue(z,"batchingIdTexture",Y._indirectTexture,ee),kt.setOptional(z,Y,"batchingColorTexture"),Y._colorsTexture!==null)kt.setValue(z,"batchingColorTexture",Y._colorsTexture,ee)}let Xr=te.morphAttributes;if(Xr.position!==void 0||Xr.normal!==void 0||Xr.color!==void 0)vt.update(Y,te,pi);if(Wr||Ne.receiveShadow!==Y.receiveShadow)Ne.receiveShadow=Y.receiveShadow,kt.setValue(z,"receiveShadow",Y.receiveShadow);if((Z.isMeshStandardMaterial||Z.isMeshLambertMaterial||Z.isMeshPhongMaterial)&&Z.envMap===null&&H.environment!==null)rn.envMapIntensity.value=H.environmentIntensity;if(rn.dfgLUT!==void 0)rn.dfgLUT.value=d8();if(Wr){if(kt.setValue(z,"toneMappingExposure",A.toneMappingExposure),Ne.needsLights)nI(rn,Va);if(Se&&Z.fog===!0)Ie.refreshFogUniforms(rn,Se);if(Ie.refreshMaterialUniforms(rn,Z,F,J,v.state.transmissionRenderTarget[I.id]),Ne.needsLights&&Ne.lightProbeGrid){let Vt=Ne.lightProbeGrid;rn.probesSH.value=Vt.texture,rn.probesMin.value.copy(Vt.boundingBox.min),rn.probesMax.value.copy(Vt.boundingBox.max),rn.probesResolution.value.copy(Vt.resolution)}xl.upload(z,Nb(Ne),rn,ee)}if(Z.isShaderMaterial&&Z.uniformsNeedUpdate===!0)xl.upload(z,Nb(Ne),rn,ee),Z.uniformsNeedUpdate=!1;if(Z.isSpriteMaterial)kt.setValue(z,"center",Y.center);if(kt.setValue(z,"modelViewMatrix",Y.modelViewMatrix),kt.setValue(z,"normalMatrix",Y.normalMatrix),kt.setValue(z,"modelMatrix",Y.matrixWorld),Z.uniformsGroups!==void 0){let Vt=Z.uniformsGroups;for(let qr=0,ja=Vt.length;qr<ja;qr++){let kb=Vt[qr];Ce.update(kb,pi),Ce.bind(kb,pi)}}return pi}function nI(I,H){I.ambientLightColor.needsUpdate=H,I.lightProbe.needsUpdate=H,I.sunLights.needsUpdate=H,I.sunLightShadows.needsUpdate=H,I.directionalLights.needsUpdate=H,I.directionalLightShadows.needsUpdate=H,I.pointLights.needsUpdate=H,I.pointLightShadows.needsUpdate=H,I.spotLights.needsUpdate=H,I.spotLightShadows.needsUpdate=H,I.rectAreaLights.needsUpdate=H,I.hemisphereLights.needsUpdate=H}function iI(I){return I.isMeshLambertMaterial||I.isMeshToonMaterial||I.isMeshPhongMaterial||I.isMeshStandardMaterial||I.isShadowMaterial||I.isShaderMaterial&&I.lights===!0}this.getActiveCubeFace=function(){return U},this.getActiveMipmapLevel=function(){return L},this.getRenderTarget=function(){return O},this.setRenderTargetTextures=function(I,H,te){let Z=V.get(I);if(Z.__autoAllocateDepthBuffer=I.resolveDepthBuffer===!1,Z.__autoAllocateDepthBuffer===!1)Z.__useRenderToTexture=!1;V.get(I.texture).__webglTexture=H,V.get(I.depthTexture).__webglTexture=Z.__autoAllocateDepthBuffer?void 0:te,Z.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(I,H){let te=V.get(I);te.__webglFramebuffer=H,te.__useDefaultFramebuffer=H===void 0},this.setRenderTarget=function(I,H=0,te=0){O=I,U=H,L=te;let Z=null,Y=!1,Se=!1;if(I){let we=V.get(I);if(we.__useDefaultFramebuffer!==void 0){N.bindFramebuffer(z.FRAMEBUFFER,we.__webglFramebuffer),X.copy(I.viewport),q.copy(I.scissor),le=I.scissorTest,N.viewport(X),N.scissor(q),N.setScissorTest(le),K=-1;return}else if(we.__webglFramebuffer===void 0)ee.setupRenderTarget(I);else if(we.__hasExternalTextures)ee.rebindTextures(I,V.get(I.texture).__webglTexture,V.get(I.depthTexture).__webglTexture);else if(I.depthBuffer){let rt=I.depthTexture;if(we.__boundDepthTexture!==rt){if(rt!==null&&V.has(rt)&&(I.width!==rt.image.width||I.height!==rt.image.height))throw Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");ee.setupDepthRenderbuffer(I)}}let De=I.texture;if(De.isData3DTexture||De.isDataArrayTexture||De.isCompressedArrayTexture)Se=!0;let ze=V.get(I).__webglFramebuffer;if(I.isWebGLCubeRenderTarget){if(Array.isArray(ze[H]))Z=ze[H][te];else Z=ze[H];Y=!0}else if(I.samples>0&&ee.useMultisampledRTT(I)===!1)Z=V.get(I).__webglMultisampledFramebuffer;else if(Array.isArray(ze))Z=ze[te];else Z=ze;X.copy(I.viewport),q.copy(I.scissor),le=I.scissorTest}else X.copy(ie).multiplyScalar(F).floor(),q.copy(ce).multiplyScalar(F).floor(),le=_e;if(te!==0)Z=R;if(N.bindFramebuffer(z.FRAMEBUFFER,Z))N.drawBuffers(I,Z);if(N.viewport(X),N.scissor(q),N.setScissorTest(le),Y){let we=V.get(I.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+H,we.__webglTexture,te)}else if(Se){let we=H;for(let De=0;De<I.textures.length;De++){let ze=V.get(I.textures[De]);z.framebufferTextureLayer(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0+De,ze.__webglTexture,te,we)}}else if(I!==null&&te!==0){let we=V.get(I.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,we.__webglTexture,te)}K=-1};function Ob(I){let H=V.get(I);if(H.__readFormat!==I.format||H.__readType!==I.type)H.__readFormat=I.format,H.__readType=I.type,H.__formatReadable=Xt.textureFormatReadable(I.format),H.__typeReadable=Xt.textureTypeReadable(I.type);return H}if(this.readRenderTargetPixels=function(I,H,te,Z,Y,Se,Pe,we=0){if(!(I&&I.isWebGLRenderTarget)){Ye("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let De=V.get(I).__webglFramebuffer;if(I.isWebGLCubeRenderTarget&&Pe!==void 0)De=De[Pe];if(De){N.bindFramebuffer(z.FRAMEBUFFER,De);try{let ze=I.textures[we],{format:rt,type:ft}=ze;if(I.textures.length>1)z.readBuffer(z.COLOR_ATTACHMENT0+we);let Le=Ob(ze);if(Le.__formatReadable===!1){Ye("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(Le.__typeReadable===!1){Ye("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(H>=0&&H<=I.width-Z&&(te>=0&&te<=I.height-Y))z.readPixels(H,te,Z,Y,ae.convert(rt),ae.convert(ft),Se)}finally{let ze=O!==null?V.get(O).__webglFramebuffer:null;N.bindFramebuffer(z.FRAMEBUFFER,ze)}}},this.readRenderTargetPixelsAsync=async function(I,H,te,Z,Y,Se,Pe,we=0){if(!(I&&I.isWebGLRenderTarget))throw Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let De=V.get(I).__webglFramebuffer;if(I.isWebGLCubeRenderTarget&&Pe!==void 0)De=De[Pe];if(De)if(H>=0&&H<=I.width-Z&&(te>=0&&te<=I.height-Y)){N.bindFramebuffer(z.FRAMEBUFFER,De);let ze=I.textures[we],{format:rt,type:ft}=ze;if(I.textures.length>1)z.readBuffer(z.COLOR_ATTACHMENT0+we);let Le=Ob(ze);if(Le.__formatReadable===!1)throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(Le.__typeReadable===!1)throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Rt=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,Rt),z.bufferData(z.PIXEL_PACK_BUFFER,Se.byteLength,z.STREAM_READ),z.readPixels(H,te,Z,Y,ae.convert(rt),ae.convert(ft),0),z.bindBuffer(z.PIXEL_PACK_BUFFER,null);let on=O!==null?V.get(O).__webglFramebuffer:null;N.bindFramebuffer(z.FRAMEBUFFER,on);let Gt=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await WT(z,Gt,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,Rt),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,Se),z.bindBuffer(z.PIXEL_PACK_BUFFER,null),z.deleteBuffer(Rt),z.deleteSync(Gt),Se}else throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(I,H=null,te=0){let Z=Math.pow(2,-te),Y=Math.floor(I.image.width*Z),Se=Math.floor(I.image.height*Z),Pe=H!==null?H.x:0,we=H!==null?H.y:0;ee.setTexture2D(I,0),z.copyTexSubImage2D(z.TEXTURE_2D,te,0,0,Pe,we,Y,Se),N.unbindTexture()},this.copyTextureToTexture=function(I,H,te=null,Z=null,Y=0,Se=0){let Pe,we,De,ze,rt,ft,Le,Rt,on,Gt=I.isCompressedTexture?I.mipmaps[Se]:I.image;if(te!==null)Pe=te.max.x-te.min.x,we=te.max.y-te.min.y,De=te.isBox3?te.max.z-te.min.z:1,ze=te.min.x,rt=te.min.y,ft=te.isBox3?te.min.z:0;else{let rn=Math.pow(2,-Y);if(Pe=Math.floor(Gt.width*rn),we=Math.floor(Gt.height*rn),I.isDataArrayTexture)De=Gt.depth;else if(I.isData3DTexture)De=Math.floor(Gt.depth*rn);else De=1;ze=0,rt=0,ft=0}if(Z!==null)Le=Z.x,Rt=Z.y,on=Z.z;else Le=0,Rt=0,on=0;let Ft=ae.convert(H.format),Cn=ae.convert(H.type),Ne;if(H.isData3DTexture)ee.setTexture3D(H,0),Ne=z.TEXTURE_3D;else if(H.isDataArrayTexture||H.isCompressedArrayTexture)ee.setTexture2DArray(H,0),Ne=z.TEXTURE_2D_ARRAY;else ee.setTexture2D(H,0),Ne=z.TEXTURE_2D;N.activeTexture(z.TEXTURE0),N.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,H.flipY),N.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,H.premultiplyAlpha),N.pixelStorei(z.UNPACK_ALIGNMENT,H.unpackAlignment);let Un=N.getParameter(z.UNPACK_ROW_LENGTH),xt=N.getParameter(z.UNPACK_IMAGE_HEIGHT),pi=N.getParameter(z.UNPACK_SKIP_PIXELS),qi=N.getParameter(z.UNPACK_SKIP_ROWS),Wr=N.getParameter(z.UNPACK_SKIP_IMAGES);N.pixelStorei(z.UNPACK_ROW_LENGTH,Gt.width),N.pixelStorei(z.UNPACK_IMAGE_HEIGHT,Gt.height),N.pixelStorei(z.UNPACK_SKIP_PIXELS,ze),N.pixelStorei(z.UNPACK_SKIP_ROWS,rt),N.pixelStorei(z.UNPACK_SKIP_IMAGES,ft);let Va=I.isDataArrayTexture||I.isData3DTexture,kt=H.isDataArrayTexture||H.isData3DTexture;if(I.isDepthTexture){let rn=V.get(I),Xr=V.get(H),Vt=V.get(rn.__renderTarget),qr=V.get(Xr.__renderTarget);N.bindFramebuffer(z.READ_FRAMEBUFFER,Vt.__webglFramebuffer),N.bindFramebuffer(z.DRAW_FRAMEBUFFER,qr.__webglFramebuffer);for(let ja=0;ja<De;ja++){if(Va)z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,V.get(I).__webglTexture,Y,ft+ja),z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,V.get(H).__webglTexture,Se,on+ja);z.blitFramebuffer(ze,rt,Pe,we,Le,Rt,Pe,we,z.DEPTH_BUFFER_BIT,z.NEAREST)}N.bindFramebuffer(z.READ_FRAMEBUFFER,null),N.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if(Y!==0||I.isRenderTargetTexture||V.has(I)){let rn=V.get(I),Xr=V.get(H);N.bindFramebuffer(z.READ_FRAMEBUFFER,k),N.bindFramebuffer(z.DRAW_FRAMEBUFFER,C);for(let Vt=0;Vt<De;Vt++){if(Va)z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,rn.__webglTexture,Y,ft+Vt);else z.framebufferTexture2D(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,rn.__webglTexture,Y);if(kt)z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Xr.__webglTexture,Se,on+Vt);else z.framebufferTexture2D(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,Xr.__webglTexture,Se);if(Y!==0)z.blitFramebuffer(ze,rt,Pe,we,Le,Rt,Pe,we,z.COLOR_BUFFER_BIT,z.NEAREST);else if(kt)z.copyTexSubImage3D(Ne,Se,Le,Rt,on+Vt,ze,rt,Pe,we);else z.copyTexSubImage2D(Ne,Se,Le,Rt,ze,rt,Pe,we)}N.bindFramebuffer(z.READ_FRAMEBUFFER,null),N.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if(kt)if(I.isDataTexture||I.isData3DTexture)z.texSubImage3D(Ne,Se,Le,Rt,on,Pe,we,De,Ft,Cn,Gt.data);else if(H.isCompressedArrayTexture)z.compressedTexSubImage3D(Ne,Se,Le,Rt,on,Pe,we,De,Ft,Gt.data);else z.texSubImage3D(Ne,Se,Le,Rt,on,Pe,we,De,Ft,Cn,Gt);else if(I.isDataTexture)z.texSubImage2D(z.TEXTURE_2D,Se,Le,Rt,Pe,we,Ft,Cn,Gt.data);else if(I.isCompressedTexture)z.compressedTexSubImage2D(z.TEXTURE_2D,Se,Le,Rt,Gt.width,Gt.height,Ft,Gt.data);else z.texSubImage2D(z.TEXTURE_2D,Se,Le,Rt,Pe,we,Ft,Cn,Gt);if(N.pixelStorei(z.UNPACK_ROW_LENGTH,Un),N.pixelStorei(z.UNPACK_IMAGE_HEIGHT,xt),N.pixelStorei(z.UNPACK_SKIP_PIXELS,pi),N.pixelStorei(z.UNPACK_SKIP_ROWS,qi),N.pixelStorei(z.UNPACK_SKIP_IMAGES,Wr),Se===0&&H.generateMipmaps)z.generateMipmap(Ne);N.unbindTexture()},this.initRenderTarget=function(I){if(V.get(I).__webglFramebuffer===void 0)ee.setupRenderTarget(I)},this.initTexture=function(I){if(I.isCubeTexture)ee.setTextureCube(I,0);else if(I.isData3DTexture)ee.setTexture3D(I,0);else if(I.isDataArrayTexture||I.isCompressedArrayTexture)ee.setTexture2DArray(I,0);else ee.setTexture2D(I,0);N.unbindTexture()},this.resetState=function(){U=0,L=0,O=null,N.reset(),ye.reset()},typeof __THREE_DEVTOOLS__<"u")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Om}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=ot._getDrawingBufferColorSpace(e),t.unpackColorSpace=ot._getUnpackColorSpace()}}var AP=`#ifdef USE_ALPHAHASHif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;-#endif`,_P=`#ifdef USE_ALPHAHASH+#endif`,wP=`#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 ) ) ) );@@ -354,20 +354,20 @@ Program Info Log: `+F+`: cases.z;return clamp( threshold , 1.0e-6, 1.0 );}-#endif`,vP=`#ifdef USE_ALPHAMAP+#endif`,SP=`#ifdef USE_ALPHAMAPdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;-#endif`,EP=`#ifdef USE_ALPHAMAP+#endif`,MP=`#ifdef USE_ALPHAMAPuniform sampler2D alphaMap;-#endif`,TP=`#ifdef USE_ALPHATEST+#endif`,RP=`#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`,AP=`#ifdef USE_ALPHATEST+#endif`,IP=`#ifdef USE_ALPHATESTuniform float alphaTest;-#endif`,wP=`#ifdef USE_AOMAP+#endif`,CP=`#ifdef USE_AOMAPfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;reflectedLight.indirectDiffuse *= ambientOcclusion;#if defined( USE_CLEARCOAT )@@ -380,10 +380,10 @@ Program Info Log: `+F+`float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );#endif-#endif`,SP=`#ifdef USE_AOMAP+#endif`,NP=`#ifdef USE_AOMAPuniform sampler2D aoMap;uniform float aoMapIntensity;-#endif`,MP=`#ifdef USE_BATCHING+#endif`,PP=`#ifdef USE_BATCHING#if ! defined( GL_ANGLE_multi_draw )#define gl_DrawID _gl_DrawIDuniform int _gl_DrawID;@@ -417,15 +417,15 @@ Program Info Log: `+F+`int y = j / size;return texelFetch( batchingColorTexture, ivec2( x, y ), 0 );}-#endif`,RP=`#ifdef USE_BATCHING+#endif`,OP=`#ifdef USE_BATCHINGmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );-#endif`,IP=`vec3 transformed = vec3( position );+#endif`,kP=`vec3 transformed = vec3( position );#ifdef USE_ALPHAHASHvPosition = vec3( position );-#endif`,CP=`vec3 objectNormal = vec3( normal );+#endif`,DP=`vec3 objectNormal = vec3( normal );#ifdef USE_TANGENTvec3 objectTangent = vec3( tangent.xyz );-#endif`,NP=`float G_BlinnPhong_Implicit( ) {+#endif`,LP=`float G_BlinnPhong_Implicit( ) {return 0.25;}float D_BlinnPhong( const in float shininess, const in float dotNH ) {@@ -439,7 +439,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`,PP=`#ifdef USE_IRIDESCENCE+} // validated`,FP=`#ifdef USE_IRIDESCENCEconst mat3 XYZ_TO_REC709 = mat3(3.2404542, -0.9692660, 0.0556434,-1.5371385, 1.8760108, -0.2040259,@@ -502,7 +502,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve}return max( I, vec3( 0.0 ) );}-#endif`,OP=`#ifdef USE_BUMPMAP+#endif`,UP=`#ifdef USE_BUMPMAPuniform sampler2D bumpMap;uniform float bumpScale;vec2 dHdxy_fwd() {@@ -523,7 +523,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`,kP=`#if NUM_CLIPPING_PLANES > 0+#endif`,BP=`#if NUM_CLIPPING_PLANES > 0vec4 plane;#ifdef ALPHA_TO_COVERAGEfloat distanceToPlane, distanceGradient;@@ -569,20 +569,20 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in veif ( clipped ) discard;#endif#endif-#endif`,DP=`#if NUM_CLIPPING_PLANES > 0+#endif`,zP=`#if NUM_CLIPPING_PLANES > 0varying vec3 vClipPosition;uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];-#endif`,LP=`#if NUM_CLIPPING_PLANES > 0+#endif`,VP=`#if NUM_CLIPPING_PLANES > 0varying vec3 vClipPosition;-#endif`,FP=`#if NUM_CLIPPING_PLANES > 0+#endif`,jP=`#if NUM_CLIPPING_PLANES > 0vClipPosition = - mvPosition.xyz;-#endif`,UP=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )+#endif`,HP=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )diffuseColor *= vColor;-#endif`,BP=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )+#endif`,GP=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )varying vec4 vColor;-#endif`,zP=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+#endif`,$P=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )varying vec4 vColor;-#endif`,VP=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+#endif`,KP=`#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@@ -595,7 +595,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`,jP=`#define PI 3.141592653589793+#endif`,WP=`#define PI 3.141592653589793#define PI2 6.283185307179586#define PI_HALF 1.5707963267948966#define RECIPROCAL_PI 0.3183098861837907@@ -666,7 +666,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`,HP=`#ifdef ENVMAP_TYPE_CUBE_UV+} // validated`,XP=`#ifdef ENVMAP_TYPE_CUBE_UV#define cubeUV_minMipLevel 4.0#define cubeUV_minTileSize 16.0float getFace( vec3 direction ) {@@ -759,7 +759,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`,GP=`vec3 transformedNormal = objectNormal;+#endif`,qP=`vec3 transformedNormal = objectNormal;#ifdef USE_TANGENTvec3 transformedTangent = objectTangent;#endif@@ -785,21 +785,21 @@ transformedNormal = normalMatrix * transformedNormal;#endif#ifdef USE_TANGENTtransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;-#endif`,$P=`#ifdef USE_DISPLACEMENTMAP+#endif`,JP=`#ifdef USE_DISPLACEMENTMAPuniform sampler2D displacementMap;uniform float displacementScale;uniform float displacementBias;-#endif`,KP=`#ifdef USE_DISPLACEMENTMAP+#endif`,ZP=`#ifdef USE_DISPLACEMENTMAPtransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );-#endif`,WP=`#ifdef USE_EMISSIVEMAP+#endif`,YP=`#ifdef USE_EMISSIVEMAPvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );#ifdef DECODE_VIDEO_TEXTURE_EMISSIVEemissiveColor = sRGBTransferEOTF( emissiveColor );#endiftotalEmissiveRadiance *= emissiveColor.rgb;-#endif`,XP=`#ifdef USE_EMISSIVEMAP+#endif`,QP=`#ifdef USE_EMISSIVEMAPuniform sampler2D emissiveMap;-#endif`,qP="gl_FragColor = linearToOutputTexel( gl_FragColor );",JP=`vec4 LinearTransferOETF( in vec4 value ) {+#endif`,eO="gl_FragColor = linearToOutputTexel( gl_FragColor );",tO=`vec4 LinearTransferOETF( in vec4 value ) {return value;}vec4 sRGBTransferEOTF( in vec4 value ) {@@ -807,7 +807,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 );-}`,ZP=`#ifdef USE_ENVMAP+}`,nO=`#ifdef USE_ENVMAP#ifdef ENV_WORLDPOSvec3 cameraToFrag;if ( isOrthographic ) {@@ -834,7 +834,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {outgoingLight += envColor.xyz * specularStrength * reflectivity;#endif#endif-#endif`,YP=`#ifdef USE_ENVMAP+#endif`,iO=`#ifdef USE_ENVMAPuniform float envMapIntensity;uniform mat3 envMapRotation;#ifdef ENVMAP_TYPE_CUBE@@ -842,7 +842,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {#elseuniform sampler2D envMap;#endif-#endif`,QP=`#ifdef USE_ENVMAP+#endif`,rO=`#ifdef USE_ENVMAPuniform float reflectivity;#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )#define ENV_WORLDPOS@@ -853,7 +853,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {#elsevarying vec3 vReflect;#endif-#endif`,eO=`#ifdef USE_ENVMAP+#endif`,sO=`#ifdef USE_ENVMAP#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )#define ENV_WORLDPOS#endif@@ -864,7 +864,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {varying vec3 vReflect;uniform float refractionRatio;#endif-#endif`,tO=`#ifdef USE_ENVMAP+#endif`,aO=`#ifdef USE_ENVMAP#ifdef ENV_WORLDPOSvWorldPosition = worldPosition.xyz;#else@@ -881,18 +881,18 @@ vec4 sRGBTransferOETF( in vec4 value ) {vReflect = refract( cameraToVertex, worldNormal, refractionRatio );#endif#endif-#endif`,nO=`#ifdef USE_FOG+#endif`,oO=`#ifdef USE_FOGvFogDepth = - mvPosition.z;-#endif`,iO=`#ifdef USE_FOG+#endif`,cO=`#ifdef USE_FOGvarying float vFogDepth;-#endif`,rO=`#ifdef USE_FOG+#endif`,lO=`#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`,sO=`#ifdef USE_FOG+#endif`,uO=`#ifdef USE_FOGuniform vec3 fogColor;varying float vFogDepth;#ifdef FOG_EXP2@@ -901,7 +901,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {uniform float fogNear;uniform float fogFar;#endif-#endif`,aO=`#ifdef USE_GRADIENTMAP+#endif`,dO=`#ifdef USE_GRADIENTMAPuniform sampler2D gradientMap;#endifvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {@@ -913,12 +913,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-}`,oO=`#ifdef USE_LIGHTMAP+}`,fO=`#ifdef USE_LIGHTMAPuniform sampler2D lightMap;uniform float lightMapIntensity;-#endif`,cO=`LambertMaterial material;+#endif`,hO=`LambertMaterial material;material.diffuseColor = diffuseColor.rgb;-material.specularStrength = specularStrength;`,lO=`varying vec3 vViewPosition;+material.specularStrength = specularStrength;`,pO=`varying vec3 vViewPosition;struct LambertMaterial {vec3 diffuseColor;float specularStrength;@@ -932,7 +932,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`,uO=`uniform bool receiveShadow;+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,mO=`uniform bool receiveShadow;uniform vec3 ambientLightColor;#if defined( USE_LIGHT_PROBES )uniform vec3 lightProbe[ 9 ];@@ -1061,7 +1061,7 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosireturn irradiance;}#endif-#include <lightprobes_pars_fragment>`,dO=`#ifdef USE_ENVMAP+#include <lightprobes_pars_fragment>`,gO=`#ifdef USE_ENVMAPvec3 getIBLIrradiance( const in vec3 normal ) {#ifdef ENVMAP_TYPE_CUBE_UVvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );@@ -1118,8 +1118,8 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi}#endif#endif-#endif`,fO=`ToonMaterial material;-material.diffuseColor = diffuseColor.rgb;`,hO=`varying vec3 vViewPosition;+#endif`,bO=`ToonMaterial material;+material.diffuseColor = diffuseColor.rgb;`,xO=`varying vec3 vViewPosition;struct ToonMaterial {vec3 diffuseColor;};@@ -1131,11 +1131,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`,pO=`BlinnPhongMaterial material;+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,yO=`BlinnPhongMaterial material;material.diffuseColor = diffuseColor.rgb;material.specularColor = specular;material.specularShininess = shininess;-material.specularStrength = specularStrength;`,mO=`varying vec3 vViewPosition;+material.specularStrength = specularStrength;`,_O=`varying vec3 vViewPosition;struct BlinnPhongMaterial {vec3 diffuseColor;vec3 specularColor;@@ -1152,7 +1152,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`,gO=`PhysicalMaterial material;+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,vO=`PhysicalMaterial material;material.diffuseColor = diffuseColor.rgb;material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );material.metalness = metalnessFactor;@@ -1245,7 +1245,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`,bO=`uniform sampler2D dfgLUT;+#endif`,EO=`uniform sampler2D dfgLUT;struct PhysicalMaterial {vec3 diffuseColor;vec3 diffuseContribution;@@ -1612,7 +1612,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 );-}`,xO=`+}`,TO=`vec3 geometryPosition = - vViewPosition;vec3 geometryNormal = normal;vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );@@ -1760,7 +1760,7 @@ IncidentLight directLight;#if defined( RE_IndirectSpecular )vec3 radiance = vec3( 0.0 );vec3 clearcoatRadiance = vec3( 0.0 );-#endif`,yO=`#if defined( RE_IndirectDiffuse )+#endif`,AO=`#if defined( RE_IndirectDiffuse )#ifdef USE_LIGHTMAPvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;@@ -1790,7 +1790,7 @@ IncidentLight directLight;#ifdef USE_CLEARCOATclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );#endif-#endif`,_O=`#if defined( RE_IndirectDiffuse )+#endif`,wO=`#if defined( RE_IndirectDiffuse )#if defined( LAMBERT ) || defined( PHONG )irradiance += iblIrradiance;#endif@@ -1798,7 +1798,7 @@ IncidentLight directLight;#endif#if defined( RE_IndirectSpecular )RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );-#endif`,vO=`#ifdef USE_LIGHT_PROBES_GRID+#endif`,SO=`#ifdef USE_LIGHT_PROBES_GRIDuniform highp sampler3D probesSH;uniform vec3 probesMin;uniform vec3 probesMax;@@ -1843,27 +1843,27 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {result += c8 * 0.429043 * ( x * x - y * y );return max( result, vec3( 0.0 ) );}-#endif`,EO=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+#endif`,MO=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;-#endif`,TO=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+#endif`,RO=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )uniform float logDepthBufFC;varying float vFragDepth;varying float vIsPerspective;-#endif`,AO=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+#endif`,IO=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFERvarying float vFragDepth;varying float vIsPerspective;-#endif`,wO=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+#endif`,CO=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFERvFragDepth = 1.0 + gl_Position.w;vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );-#endif`,SO=`#ifdef USE_MAP+#endif`,NO=`#ifdef USE_MAPvec4 sampledDiffuseColor = texture2D( map, vMapUv );#ifdef DECODE_VIDEO_TEXTUREsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );#endifdiffuseColor *= sampledDiffuseColor;-#endif`,MO=`#ifdef USE_MAP+#endif`,PO=`#ifdef USE_MAPuniform sampler2D map;-#endif`,RO=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )+#endif`,OO=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )#if defined( USE_POINTS_UV )vec2 uv = vUv;#else@@ -1875,7 +1875,7 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {#endif#ifdef USE_ALPHAMAPdiffuseColor.a *= texture2D( alphaMap, uv ).g;-#endif`,IO=`#if defined( USE_POINTS_UV )+#endif`,kO=`#if defined( USE_POINTS_UV )varying vec2 vUv;#else#if defined( USE_MAP ) || defined( USE_ALPHAMAP )@@ -1887,19 +1887,19 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {#endif#ifdef USE_ALPHAMAPuniform sampler2D alphaMap;-#endif`,CO=`float metalnessFactor = metalness;+#endif`,DO=`float metalnessFactor = metalness;#ifdef USE_METALNESSMAPvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );metalnessFactor *= texelMetalness.b;-#endif`,NO=`#ifdef USE_METALNESSMAP+#endif`,LO=`#ifdef USE_METALNESSMAPuniform sampler2D metalnessMap;-#endif`,PO=`#ifdef USE_INSTANCING_MORPH+#endif`,FO=`#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`,OO=`#if defined( USE_MORPHCOLORS )+#endif`,UO=`#if defined( USE_MORPHCOLORS )vColor *= morphTargetBaseInfluence;for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {#if defined( USE_COLOR_ALPHA )@@ -1908,12 +1908,12 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];#endif}-#endif`,kO=`#ifdef USE_MORPHNORMALS+#endif`,BO=`#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`,DO=`#ifdef USE_MORPHTARGETS+#endif`,zO=`#ifdef USE_MORPHTARGETS#ifndef USE_INSTANCING_MORPHuniform float morphTargetBaseInfluence;uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];@@ -1927,12 +1927,12 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {ivec3 morphUV = ivec3( x, y, morphTargetIndex );return texelFetch( morphTargetsTexture, morphUV, 0 );}-#endif`,LO=`#ifdef USE_MORPHTARGETS+#endif`,VO=`#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`,FO=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;+#endif`,jO=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;#ifdef FLAT_SHADEDvec3 fdx = dFdx( vViewPosition );vec3 fdy = dFdy( vViewPosition );@@ -1973,7 +1973,7 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {tbn2[1] *= faceDirection;#endif#endif-vec3 nonPerturbedNormal = normal;`,UO=`#ifdef USE_NORMALMAP_OBJECTSPACE+vec3 nonPerturbedNormal = normal;`,HO=`#ifdef USE_NORMALMAP_OBJECTSPACEnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;#ifdef FLIP_SIDEDnormal = - normal;@@ -1991,19 +1991,19 @@ vec3 nonPerturbedNormal = normal;`,UO=`#ifdef USE_NORMALMAP_OBJECTSPACEnormal = normalize( tbn * mapN );#elif defined( USE_BUMPMAP )normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );-#endif`,BO=`#ifndef FLAT_SHADED+#endif`,GO=`#ifndef FLAT_SHADEDvarying vec3 vNormal;#ifdef USE_TANGENTvarying vec3 vTangent;varying vec3 vBitangent;#endif-#endif`,zO=`#ifndef FLAT_SHADED+#endif`,$O=`#ifndef FLAT_SHADEDvarying vec3 vNormal;#ifdef USE_TANGENTvarying vec3 vTangent;varying vec3 vBitangent;#endif-#endif`,VO=`#ifndef FLAT_SHADED+#endif`,KO=`#ifndef FLAT_SHADEDvNormal = normalize( transformedNormal );#ifdef USE_TANGENTvTangent = normalize( transformedTangent );@@ -2012,7 +2012,7 @@ vec3 nonPerturbedNormal = normal;`,UO=`#ifdef USE_NORMALMAP_OBJECTSPACEvBitangent = - vBitangent;#endif#endif-#endif`,jO=`#ifdef USE_NORMALMAP+#endif`,WO=`#ifdef USE_NORMALMAPuniform sampler2D normalMap;uniform vec2 normalScale;#endif@@ -2034,13 +2034,13 @@ vec3 nonPerturbedNormal = normal;`,UO=`#ifdef USE_NORMALMAP_OBJECTSPACEfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );return mat3( T * scale, B * scale, N );}-#endif`,HO=`#ifdef USE_CLEARCOAT+#endif`,XO=`#ifdef USE_CLEARCOATvec3 clearcoatNormal = nonPerturbedNormal;-#endif`,GO=`#ifdef USE_CLEARCOAT_NORMALMAP+#endif`,qO=`#ifdef USE_CLEARCOAT_NORMALMAPvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;clearcoatMapN.xy *= clearcoatNormalScale;clearcoatNormal = normalize( tbn2 * clearcoatMapN );-#endif`,$O=`#ifdef USE_CLEARCOATMAP+#endif`,JO=`#ifdef USE_CLEARCOATMAPuniform sampler2D clearcoatMap;#endif#ifdef USE_CLEARCOAT_NORMALMAP@@ -2049,18 +2049,18 @@ vec3 nonPerturbedNormal = normal;`,UO=`#ifdef USE_NORMALMAP_OBJECTSPACE#endif#ifdef USE_CLEARCOAT_ROUGHNESSMAPuniform sampler2D clearcoatRoughnessMap;-#endif`,KO=`#ifdef USE_IRIDESCENCEMAP+#endif`,ZO=`#ifdef USE_IRIDESCENCEMAPuniform sampler2D iridescenceMap;#endif#ifdef USE_IRIDESCENCE_THICKNESSMAPuniform sampler2D iridescenceThicknessMap;-#endif`,WO=`#ifdef OPAQUE+#endif`,YO=`#ifdef OPAQUEdiffuseColor.a = 1.0;#endif#ifdef USE_TRANSMISSIONdiffuseColor.a *= material.transmissionAlpha;#endif-gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,XO=`vec3 packNormalToRGB( const in vec3 normal ) {+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,QO=`vec3 packNormalToRGB( const in vec3 normal ) {return normalize( normal ) * 0.5 + 0.5;}vec3 unpackRGBToNormal( const in vec3 rgb ) {@@ -2139,9 +2139,9 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const#elsereturn ( near * far ) / ( ( far - near ) * depth - far );#endif-}`,qO=`#ifdef PREMULTIPLIED_ALPHA+}`,ek=`#ifdef PREMULTIPLIED_ALPHAgl_FragColor.rgb *= gl_FragColor.a;-#endif`,JO=`vec4 mvPosition = vec4( transformed, 1.0 );+#endif`,tk=`vec4 mvPosition = vec4( transformed, 1.0 );#ifdef USE_BATCHINGmvPosition = batchingMatrix * mvPosition;#endif@@ -2149,22 +2149,22 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, constmvPosition = instanceMatrix * mvPosition;#endifmvPosition = modelViewMatrix * mvPosition;-gl_Position = projectionMatrix * mvPosition;`,ZO=`#ifdef DITHERING+gl_Position = projectionMatrix * mvPosition;`,nk=`#ifdef DITHERINGgl_FragColor.rgb = dithering( gl_FragColor.rgb );-#endif`,YO=`#ifdef DITHERING+#endif`,ik=`#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`,QO=`float roughnessFactor = roughness;+#endif`,rk=`float roughnessFactor = roughness;#ifdef USE_ROUGHNESSMAPvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );roughnessFactor *= texelRoughness.g;-#endif`,ek=`#ifdef USE_ROUGHNESSMAP+#endif`,sk=`#ifdef USE_ROUGHNESSMAPuniform sampler2D roughnessMap;-#endif`,tk=`#if NUM_SPOT_LIGHT_COORDS > 0+#endif`,ak=`#if NUM_SPOT_LIGHT_COORDS > 0varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];#endif#if NUM_SPOT_LIGHT_MAPS > 0@@ -2415,7 +2415,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZO=`#ifdef DITHERING}#endif#endif-#endif`,nk=`#if NUM_SPOT_LIGHT_COORDS > 0+#endif`,ok=`#if NUM_SPOT_LIGHT_COORDS > 0uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];#endif@@ -2460,7 +2460,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZO=`#ifdef DITHERING};uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];#endif-#endif`,ik=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )+#endif`,ck=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )#ifdef HAS_NORMALvec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );#else@@ -2500,7 +2500,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZO=`#ifdef DITHERINGvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;}#pragma unroll_loop_end-#endif`,rk=`float getShadowMask() {+#endif`,lk=`float getShadowMask() {float shadow = 1.0;#ifdef USE_SHADOWMAP#if NUM_SUN_LIGHT_SHADOWS > 0@@ -2541,12 +2541,12 @@ gl_Position = projectionMatrix * mvPosition;`,ZO=`#ifdef DITHERING#endif#endifreturn shadow;-}`,sk=`#ifdef USE_SKINNING+}`,uk=`#ifdef USE_SKINNINGmat4 boneMatX = getBoneMatrix( skinIndex.x );mat4 boneMatY = getBoneMatrix( skinIndex.y );mat4 boneMatZ = getBoneMatrix( skinIndex.z );mat4 boneMatW = getBoneMatrix( skinIndex.w );-#endif`,ak=`#ifdef USE_SKINNING+#endif`,dk=`#ifdef USE_SKINNINGuniform mat4 bindMatrix;uniform mat4 bindMatrixInverse;uniform highp sampler2D boneTexture;@@ -2561,7 +2561,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZO=`#ifdef DITHERINGvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );return mat4( v1, v2, v3, v4 );}-#endif`,ok=`#ifdef USE_SKINNING+#endif`,fk=`#ifdef USE_SKINNINGvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );vec4 skinned = vec4( 0.0 );skinned += boneMatX * skinVertex * skinWeight.x;@@ -2569,7 +2569,7 @@ gl_Position = projectionMatrix * mvPosition;`,ZO=`#ifdef DITHERINGskinned += boneMatZ * skinVertex * skinWeight.z;skinned += boneMatW * skinVertex * skinWeight.w;transformed = ( bindMatrixInverse * skinned ).xyz;-#endif`,ck=`#ifdef USE_SKINNING+#endif`,hk=`#ifdef USE_SKINNINGmat4 skinMatrix = mat4( 0.0 );skinMatrix += skinWeight.x * boneMatX;skinMatrix += skinWeight.y * boneMatY;@@ -2580,17 +2580,17 @@ gl_Position = projectionMatrix * mvPosition;`,ZO=`#ifdef DITHERING#ifdef USE_TANGENTobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;#endif-#endif`,lk=`float specularStrength;+#endif`,pk=`float specularStrength;#ifdef USE_SPECULARMAPvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );specularStrength = texelSpecular.r;#elsespecularStrength = 1.0;-#endif`,uk=`#ifdef USE_SPECULARMAP+#endif`,mk=`#ifdef USE_SPECULARMAPuniform sampler2D specularMap;-#endif`,dk=`#if defined( TONE_MAPPING )+#endif`,gk=`#if defined( TONE_MAPPING )gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );-#endif`,fk=`#ifndef saturate+#endif`,bk=`#ifndef saturate#define saturate( a ) clamp( a, 0.0, 1.0 )#endifuniform float toneMappingExposure;@@ -2687,7 +2687,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; }`,hk=`#ifdef USE_TRANSMISSION+vec3 CustomToneMapping( vec3 color ) { return color; }`,xk=`#ifdef USE_TRANSMISSIONmaterial.transmission = transmission;material.transmissionAlpha = 1.0;material.thickness = thickness;@@ -2708,7 +2708,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,hk=`#ifdef USE_TRANSMISSmaterial.attenuationColor, material.attenuationDistance );material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );-#endif`,pk=`#ifdef USE_TRANSMISSION+#endif`,yk=`#ifdef USE_TRANSMISSIONuniform float transmission;uniform float thickness;uniform float attenuationDistance;@@ -2834,7 +2834,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,hk=`#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`,mk=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+#endif`,_k=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )varying vec2 vUv;#endif#ifdef USE_MAP@@ -2904,7 +2904,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,hk=`#ifdef USE_TRANSMISS#ifdef USE_THICKNESSMAPuniform mat3 thicknessMapTransform;varying vec2 vThicknessMapUv;-#endif`,gk=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+#endif`,vk=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )varying vec2 vUv;#endif#ifdef USE_MAP@@ -2998,7 +2998,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,hk=`#ifdef USE_TRANSMISS#ifdef USE_THICKNESSMAPuniform mat3 thicknessMapTransform;varying vec2 vThicknessMapUv;-#endif`,bk=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+#endif`,Ek=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )vUv = vec3( uv, 1 ).xy;#endif#ifdef USE_MAP@@ -3069,7 +3069,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,hk=`#ifdef USE_TRANSMISS#endif#ifdef USE_THICKNESSMAPvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;-#endif`,xk=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0+#endif`,Tk=`#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;@@ -3078,12 +3078,12 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,hk=`#ifdef USE_TRANSMISSworldPosition = instanceMatrix * worldPosition;#endifworldPosition = modelMatrix * worldPosition;-#endif`,yk=`varying vec2 vUv;+#endif`,Ak=`varying vec2 vUv;uniform mat3 uvTransform;void main() {vUv = ( uvTransform * vec3( uv, 1 ) ).xy;gl_Position = vec4( position.xy, 1.0, 1.0 );-}`,_k=`uniform sampler2D t2D;+}`,wk=`uniform sampler2D t2D;uniform float backgroundIntensity;varying vec2 vUv;void main() {@@ -3095,14 +3095,14 @@ void main() {gl_FragColor = texColor;#include <tonemapping_fragment>#include <colorspace_fragment>-}`,vk=`varying vec3 vWorldDirection;+}`,Sk=`varying vec3 vWorldDirection;#include <common>void main() {vWorldDirection = transformDirection( position, modelMatrix );#include <begin_vertex>#include <project_vertex>gl_Position.z = gl_Position.w;-}`,Ek=`#ifdef ENVMAP_TYPE_CUBE+}`,Mk=`#ifdef ENVMAP_TYPE_CUBEuniform samplerCube envMap;#elif defined( ENVMAP_TYPE_CUBE_UV )uniform sampler2D envMap;@@ -3124,14 +3124,14 @@ void main() {gl_FragColor = texColor;#include <tonemapping_fragment>#include <colorspace_fragment>-}`,Tk=`varying vec3 vWorldDirection;+}`,Rk=`varying vec3 vWorldDirection;#include <common>void main() {vWorldDirection = transformDirection( position, modelMatrix );#include <begin_vertex>#include <project_vertex>gl_Position.z = gl_Position.w;-}`,Ak=`uniform samplerCube tCube;+}`,Ik=`uniform samplerCube tCube;uniform float tFlip;uniform float opacity;varying vec3 vWorldDirection;@@ -3141,7 +3141,7 @@ void main() {gl_FragColor.a *= opacity;#include <tonemapping_fragment>#include <colorspace_fragment>-}`,wk=`#include <common>+}`,Ck=`#include <common>#include <batching_pars_vertex>#include <uv_pars_vertex>#include <displacementmap_pars_vertex>@@ -3168,7 +3168,7 @@ void main() {#include <logdepthbuf_vertex>#include <clipping_planes_vertex>vHighPrecisionZW = gl_Position.zw;-}`,Sk=`#if DEPTH_PACKING == 3200+}`,Nk=`#if DEPTH_PACKING == 3200uniform float opacity;#endif#include <common>@@ -3206,7 +3206,7 @@ void main() {#elif DEPTH_PACKING == 3203gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );#endif-}`,Mk=`#define DISTANCE+}`,Pk=`#define DISTANCEvarying vec3 vWorldPosition;#include <common>#include <batching_pars_vertex>@@ -3233,7 +3233,7 @@ void main() {#include <worldpos_vertex>#include <clipping_planes_vertex>vWorldPosition = worldPosition.xyz;-}`,Rk=`#define DISTANCE+}`,Ok=`#define DISTANCEuniform vec3 referencePosition;uniform float nearDistance;uniform float farDistance;@@ -3256,13 +3256,13 @@ void main() {dist = ( dist - nearDistance ) / ( farDistance - nearDistance );dist = saturate( dist );gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );-}`,Ik=`varying vec3 vWorldDirection;+}`,kk=`varying vec3 vWorldDirection;#include <common>void main() {vWorldDirection = transformDirection( position, modelMatrix );#include <begin_vertex>#include <project_vertex>-}`,Ck=`uniform sampler2D tEquirect;+}`,Dk=`uniform sampler2D tEquirect;varying vec3 vWorldDirection;#include <common>void main() {@@ -3271,7 +3271,7 @@ void main() {gl_FragColor = texture2D( tEquirect, sampleUV );#include <tonemapping_fragment>#include <colorspace_fragment>-}`,Nk=`uniform float scale;+}`,Lk=`uniform float scale;attribute float lineDistance;varying float vLineDistance;#include <common>@@ -3293,7 +3293,7 @@ void main() {#include <logdepthbuf_vertex>#include <clipping_planes_vertex>#include <fog_vertex>-}`,Pk=`uniform vec3 diffuse;+}`,Fk=`uniform vec3 diffuse;uniform float opacity;uniform float dashSize;uniform float totalSize;@@ -3321,7 +3321,7 @@ void main() {#include <colorspace_fragment>#include <fog_fragment>#include <premultiplied_alpha_fragment>-}`,Ok=`#include <common>+}`,Uk=`#include <common>#include <batching_pars_vertex>#include <uv_pars_vertex>#include <envmap_pars_vertex>@@ -3353,7 +3353,7 @@ void main() {#include <worldpos_vertex>#include <envmap_vertex>#include <fog_vertex>-}`,kk=`uniform vec3 diffuse;+}`,Bk=`uniform vec3 diffuse;uniform float opacity;#ifndef FLAT_SHADEDvarying vec3 vNormal;@@ -3401,7 +3401,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,Dk=`#define LAMBERT+}`,zk=`#define LAMBERTvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3440,7 +3440,7 @@ void main() {#include <envmap_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,Lk=`#define LAMBERT+}`,Vk=`#define LAMBERTuniform vec3 diffuse;uniform vec3 emissive;uniform float opacity;@@ -3498,7 +3498,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,Fk=`#define MATCAP+}`,jk=`#define MATCAPvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3532,7 +3532,7 @@ void main() {#include <clipping_planes_vertex>#include <fog_vertex>vViewPosition = - mvPosition.xyz;-}`,Uk=`#define MATCAP+}`,Hk=`#define MATCAPuniform vec3 diffuse;uniform float opacity;uniform sampler2D matcap;@@ -3578,7 +3578,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,Bk=`#define NORMAL+}`,Gk=`#define NORMAL#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )varying vec3 vViewPosition;#endif@@ -3611,7 +3611,7 @@ void main() {#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )vViewPosition = - mvPosition.xyz;#endif-}`,zk=`#define NORMAL+}`,$k=`#define NORMALuniform float opacity;#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )varying vec3 vViewPosition;@@ -3632,7 +3632,7 @@ void main() {#ifdef OPAQUEgl_FragColor.a = 1.0;#endif-}`,Vk=`#define PHONG+}`,Kk=`#define PHONGvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3671,7 +3671,7 @@ void main() {#include <envmap_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,jk=`#define PHONG+}`,Wk=`#define PHONGuniform vec3 diffuse;uniform vec3 emissive;uniform vec3 specular;@@ -3731,7 +3731,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,Hk=`#define STANDARD+}`,Xk=`#define STANDARDvarying vec3 vViewPosition;#ifdef USE_TRANSMISSIONvarying vec3 vWorldPosition;@@ -3774,7 +3774,7 @@ void main() {#ifdef USE_TRANSMISSIONvWorldPosition = worldPosition.xyz;#endif-}`,Gk=`#define STANDARD+}`,qk=`#define STANDARD#ifdef PHYSICAL#define IOR#define USE_SPECULAR@@ -3902,7 +3902,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,$k=`#define TOON+}`,Jk=`#define TOONvarying vec3 vViewPosition;#include <common>#include <batching_pars_vertex>@@ -3939,7 +3939,7 @@ void main() {#include <worldpos_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,Kk=`#define TOON+}`,Zk=`#define TOONuniform vec3 diffuse;uniform vec3 emissive;uniform float opacity;@@ -3991,7 +3991,7 @@ void main() {#include <fog_fragment>#include <premultiplied_alpha_fragment>#include <dithering_fragment>-}`,Wk=`uniform float size;+}`,Yk=`uniform float size;uniform float scale;#include <common>#include <color_pars_vertex>@@ -4022,7 +4022,7 @@ void main() {#include <clipping_planes_vertex>#include <worldpos_vertex>#include <fog_vertex>-}`,Xk=`uniform vec3 diffuse;+}`,Qk=`uniform vec3 diffuse;uniform float opacity;#include <common>#include <color_pars_fragment>@@ -4047,7 +4047,7 @@ void main() {#include <colorspace_fragment>#include <fog_fragment>#include <premultiplied_alpha_fragment>-}`,qk=`#include <common>+}`,eD=`#include <common>#include <batching_pars_vertex>#include <fog_pars_vertex>#include <morphtarget_pars_vertex>@@ -4070,7 +4070,7 @@ void main() {#include <worldpos_vertex>#include <shadowmap_vertex>#include <fog_vertex>-}`,Jk=`uniform vec3 color;+}`,tD=`uniform vec3 color;uniform float opacity;#include <common>#include <fog_pars_fragment>@@ -4086,7 +4086,7 @@ void main() {#include <colorspace_fragment>#include <fog_fragment>#include <premultiplied_alpha_fragment>-}`,Zk=`uniform float rotation;+}`,nD=`uniform float rotation;uniform vec2 center;#include <common>#include <uv_pars_vertex>@@ -4110,7 +4110,7 @@ void main() {#include <logdepthbuf_vertex>#include <clipping_planes_vertex>#include <fog_vertex>-}`,Yk=`uniform vec3 diffuse;+}`,iD=`uniform vec3 diffuse;uniform float opacity;#include <common>#include <uv_pars_fragment>@@ -4135,9 +4135,9 @@ void main() {#include <tonemapping_fragment>#include <colorspace_fragment>#include <fog_fragment>-}`,st,Te,br,Vd,Qk,EA,Vo=4,sD=6,aD=20,oD=256,hl,eA,Ym=null,Qm=0,eg=0,tg=!1,cD,Ia,ag,yD,TA,rg,AA,wA,SA,rA,sA,aA,oA,cA,ng,cL=37297,lL=0,dA,hL,jd,yL,_L,EL,AL,SL,RL,CL,kL=0,jL=0,KL=`void main() {+}`,st,Te,br,Gd,rD,SA,Vo=4,uD=6,dD=20,fD=256,ml,rA,ig=null,rg=0,sg=0,ag=!1,hD,Na,dg,AD,MA,lg,RA,IA,CA,cA,lA,uA,dA,fA,og,hL=37297,pL=0,mA,xL,$d,AL,wL,ML,IL,NL,OL,DL,BL=0,WL=0,ZL=`void main() {gl_Position = vec4( position, 1.0 );-}`,WL=`uniform sampler2D shadow_pass;+}`,YL=`uniform sampler2D shadow_pass;uniform vec2 resolution;uniform float radius;void main() {@@ -4162,12 +4162,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 );-}`,XL,qL,_A,pl,ig,e8=`+}`,QL,e8,AA,gl,cg,s8=`void main() {gl_Position = vec4( position, 1.0 );-}`,t8=`+}`,a8=`uniform sampler2DArray depthColor;uniform float depthWidth;uniform float depthHeight;@@ -4186,7 +4186,7 @@ void main() {}-}`,OA,n8,kA,s8,gr=null;var ji=mt(()=>{Zm();Zm();st={alphahash_fragment:yP,alphahash_pars_fragment:_P,alphamap_fragment:vP,alphamap_pars_fragment:EP,alphatest_fragment:TP,alphatest_pars_fragment:AP,aomap_fragment:wP,aomap_pars_fragment:SP,batching_pars_vertex:MP,batching_vertex:RP,begin_vertex:IP,beginnormal_vertex:CP,bsdfs:NP,iridescence_fragment:PP,bumpmap_pars_fragment:OP,clipping_planes_fragment:kP,clipping_planes_pars_fragment:DP,clipping_planes_pars_vertex:LP,clipping_planes_vertex:FP,color_fragment:UP,color_pars_fragment:BP,color_pars_vertex:zP,color_vertex:VP,common:jP,cube_uv_reflection_fragment:HP,defaultnormal_vertex:GP,displacementmap_pars_vertex:$P,displacementmap_vertex:KP,emissivemap_fragment:WP,emissivemap_pars_fragment:XP,colorspace_fragment:qP,colorspace_pars_fragment:JP,envmap_fragment:ZP,envmap_common_pars_fragment:YP,envmap_pars_fragment:QP,envmap_pars_vertex:eO,envmap_physical_pars_fragment:dO,envmap_vertex:tO,fog_vertex:nO,fog_pars_vertex:iO,fog_fragment:rO,fog_pars_fragment:sO,gradientmap_pars_fragment:aO,lightmap_pars_fragment:oO,lights_lambert_fragment:cO,lights_lambert_pars_fragment:lO,lights_pars_begin:uO,lights_toon_fragment:fO,lights_toon_pars_fragment:hO,lights_phong_fragment:pO,lights_phong_pars_fragment:mO,lights_physical_fragment:gO,lights_physical_pars_fragment:bO,lights_fragment_begin:xO,lights_fragment_maps:yO,lights_fragment_end:_O,lightprobes_pars_fragment:vO,logdepthbuf_fragment:EO,logdepthbuf_pars_fragment:TO,logdepthbuf_pars_vertex:AO,logdepthbuf_vertex:wO,map_fragment:SO,map_pars_fragment:MO,map_particle_fragment:RO,map_particle_pars_fragment:IO,metalnessmap_fragment:CO,metalnessmap_pars_fragment:NO,morphinstance_vertex:PO,morphcolor_vertex:OO,morphnormal_vertex:kO,morphtarget_pars_vertex:DO,morphtarget_vertex:LO,normal_fragment_begin:FO,normal_fragment_maps:UO,normal_pars_fragment:BO,normal_pars_vertex:zO,normal_vertex:VO,normalmap_pars_fragment:jO,clearcoat_normal_fragment_begin:HO,clearcoat_normal_fragment_maps:GO,clearcoat_pars_fragment:$O,iridescence_pars_fragment:KO,opaque_fragment:WO,packing:XO,premultiplied_alpha_fragment:qO,project_vertex:JO,dithering_fragment:ZO,dithering_pars_fragment:YO,roughnessmap_fragment:QO,roughnessmap_pars_fragment:ek,shadowmap_pars_fragment:tk,shadowmap_pars_vertex:nk,shadowmap_vertex:ik,shadowmask_pars_fragment:rk,skinbase_vertex:sk,skinning_pars_vertex:ak,skinning_vertex:ok,skinnormal_vertex:ck,specularmap_fragment:lk,specularmap_pars_fragment:uk,tonemapping_fragment:dk,tonemapping_pars_fragment:fk,transmission_fragment:hk,transmission_pars_fragment:pk,uv_pars_fragment:mk,uv_pars_vertex:gk,uv_vertex:bk,worldpos_vertex:xk,background_vert:yk,background_frag:_k,backgroundCube_vert:vk,backgroundCube_frag:Ek,cube_vert:Tk,cube_frag:Ak,depth_vert:wk,depth_frag:Sk,distance_vert:Mk,distance_frag:Rk,equirect_vert:Ik,equirect_frag:Ck,linedashed_vert:Nk,linedashed_frag:Pk,meshbasic_vert:Ok,meshbasic_frag:kk,meshlambert_vert:Dk,meshlambert_frag:Lk,meshmatcap_vert:Fk,meshmatcap_frag:Uk,meshnormal_vert:Bk,meshnormal_frag:zk,meshphong_vert:Vk,meshphong_frag:jk,meshphysical_vert:Hk,meshphysical_frag:Gk,meshtoon_vert:$k,meshtoon_frag:Kk,points_vert:Wk,points_frag:Xk,shadow_vert:qk,shadow_frag:Jk,sprite_vert:Zk,sprite_frag:Yk},Te={common:{diffuse:{value:new qe(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new tt},alphaMap:{value:null},alphaMapTransform:{value:new tt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new tt}},envmap:{envMap:{value:null},envMapRotation:{value:new tt},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:0.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new tt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new tt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new tt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new tt},normalScale:{value:new Ke(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new tt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new tt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new tt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new tt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:0.00025},fogNear:{value:1},fogFar:{value:2000},fogColor:{value:new qe(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new j},probesMax:{value:new j},probesResolution:{value:new j}},points:{diffuse:{value:new qe(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new tt},alphaTest:{value:0},uvTransform:{value:new tt}},sprite:{diffuse:{value:new qe(16777215)},opacity:{value:1},center:{value:new Ke(0.5,0.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new tt},alphaMap:{value:null},alphaMapTransform:{value:new tt},alphaTest:{value:0}}},br={basic:{uniforms:Ln([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.fog]),vertexShader:st.meshbasic_vert,fragmentShader:st.meshbasic_frag},lambert:{uniforms:Ln([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new qe(0)},envMapIntensity:{value:1}}]),vertexShader:st.meshlambert_vert,fragmentShader:st.meshlambert_frag},phong:{uniforms:Ln([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new qe(0)},specular:{value:new qe(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:st.meshphong_vert,fragmentShader:st.meshphong_frag},standard:{uniforms:Ln([Te.common,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.roughnessmap,Te.metalnessmap,Te.fog,Te.lights,{emissive:{value:new qe(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:st.meshphysical_vert,fragmentShader:st.meshphysical_frag},toon:{uniforms:Ln([Te.common,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.gradientmap,Te.fog,Te.lights,{emissive:{value:new qe(0)}}]),vertexShader:st.meshtoon_vert,fragmentShader:st.meshtoon_frag},matcap:{uniforms:Ln([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,{matcap:{value:null}}]),vertexShader:st.meshmatcap_vert,fragmentShader:st.meshmatcap_frag},points:{uniforms:Ln([Te.points,Te.fog]),vertexShader:st.points_vert,fragmentShader:st.points_frag},dashed:{uniforms:Ln([Te.common,Te.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:st.linedashed_vert,fragmentShader:st.linedashed_frag},depth:{uniforms:Ln([Te.common,Te.displacementmap]),vertexShader:st.depth_vert,fragmentShader:st.depth_frag},normal:{uniforms:Ln([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,{opacity:{value:1}}]),vertexShader:st.meshnormal_vert,fragmentShader:st.meshnormal_frag},sprite:{uniforms:Ln([Te.sprite,Te.fog]),vertexShader:st.sprite_vert,fragmentShader:st.sprite_frag},background:{uniforms:{uvTransform:{value:new tt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:st.background_vert,fragmentShader:st.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new tt}},vertexShader:st.backgroundCube_vert,fragmentShader:st.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:st.cube_vert,fragmentShader:st.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:st.equirect_vert,fragmentShader:st.equirect_frag},distance:{uniforms:Ln([Te.common,Te.displacementmap,{referencePosition:{value:new j},nearDistance:{value:1},farDistance:{value:1000}}]),vertexShader:st.distance_vert,fragmentShader:st.distance_frag},shadow:{uniforms:Ln([Te.lights,Te.fog,{color:{value:new qe(0)},opacity:{value:1}}]),vertexShader:st.shadow_vert,fragmentShader:st.shadow_frag}};br.physical={uniforms:Ln([br.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new tt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new tt},clearcoatNormalScale:{value:new Ke(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new tt},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new tt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new tt},sheen:{value:0},sheenColor:{value:new qe(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new tt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new tt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new tt},transmissionSamplerSize:{value:new Ke},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new tt},attenuationDistance:{value:0},attenuationColor:{value:new qe(0)},specularColor:{value:new qe(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new tt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new tt},anisotropyVector:{value:new Ke},anisotropyMap:{value:null},anisotropyMapTransform:{value:new tt}}]),vertexShader:st.meshphysical_vert,fragmentShader:st.meshphysical_frag};Vd={r:0,b:0,g:0},Qk=new Qe,EA=new tt;EA.set(-1,0,0,0,1,0,0,0,1);hl=new Ra,eA=new qe,cD=new j,Ia=new j;ag=class ag extends ci{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 Cd(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:`+}`,FA,o8,UA,u8,gr=null;var ji=ht(()=>{ng();ng();st={alphahash_fragment:AP,alphahash_pars_fragment:wP,alphamap_fragment:SP,alphamap_pars_fragment:MP,alphatest_fragment:RP,alphatest_pars_fragment:IP,aomap_fragment:CP,aomap_pars_fragment:NP,batching_pars_vertex:PP,batching_vertex:OP,begin_vertex:kP,beginnormal_vertex:DP,bsdfs:LP,iridescence_fragment:FP,bumpmap_pars_fragment:UP,clipping_planes_fragment:BP,clipping_planes_pars_fragment:zP,clipping_planes_pars_vertex:VP,clipping_planes_vertex:jP,color_fragment:HP,color_pars_fragment:GP,color_pars_vertex:$P,color_vertex:KP,common:WP,cube_uv_reflection_fragment:XP,defaultnormal_vertex:qP,displacementmap_pars_vertex:JP,displacementmap_vertex:ZP,emissivemap_fragment:YP,emissivemap_pars_fragment:QP,colorspace_fragment:eO,colorspace_pars_fragment:tO,envmap_fragment:nO,envmap_common_pars_fragment:iO,envmap_pars_fragment:rO,envmap_pars_vertex:sO,envmap_physical_pars_fragment:gO,envmap_vertex:aO,fog_vertex:oO,fog_pars_vertex:cO,fog_fragment:lO,fog_pars_fragment:uO,gradientmap_pars_fragment:dO,lightmap_pars_fragment:fO,lights_lambert_fragment:hO,lights_lambert_pars_fragment:pO,lights_pars_begin:mO,lights_toon_fragment:bO,lights_toon_pars_fragment:xO,lights_phong_fragment:yO,lights_phong_pars_fragment:_O,lights_physical_fragment:vO,lights_physical_pars_fragment:EO,lights_fragment_begin:TO,lights_fragment_maps:AO,lights_fragment_end:wO,lightprobes_pars_fragment:SO,logdepthbuf_fragment:MO,logdepthbuf_pars_fragment:RO,logdepthbuf_pars_vertex:IO,logdepthbuf_vertex:CO,map_fragment:NO,map_pars_fragment:PO,map_particle_fragment:OO,map_particle_pars_fragment:kO,metalnessmap_fragment:DO,metalnessmap_pars_fragment:LO,morphinstance_vertex:FO,morphcolor_vertex:UO,morphnormal_vertex:BO,morphtarget_pars_vertex:zO,morphtarget_vertex:VO,normal_fragment_begin:jO,normal_fragment_maps:HO,normal_pars_fragment:GO,normal_pars_vertex:$O,normal_vertex:KO,normalmap_pars_fragment:WO,clearcoat_normal_fragment_begin:XO,clearcoat_normal_fragment_maps:qO,clearcoat_pars_fragment:JO,iridescence_pars_fragment:ZO,opaque_fragment:YO,packing:QO,premultiplied_alpha_fragment:ek,project_vertex:tk,dithering_fragment:nk,dithering_pars_fragment:ik,roughnessmap_fragment:rk,roughnessmap_pars_fragment:sk,shadowmap_pars_fragment:ak,shadowmap_pars_vertex:ok,shadowmap_vertex:ck,shadowmask_pars_fragment:lk,skinbase_vertex:uk,skinning_pars_vertex:dk,skinning_vertex:fk,skinnormal_vertex:hk,specularmap_fragment:pk,specularmap_pars_fragment:mk,tonemapping_fragment:gk,tonemapping_pars_fragment:bk,transmission_fragment:xk,transmission_pars_fragment:yk,uv_pars_fragment:_k,uv_pars_vertex:vk,uv_vertex:Ek,worldpos_vertex:Tk,background_vert:Ak,background_frag:wk,backgroundCube_vert:Sk,backgroundCube_frag:Mk,cube_vert:Rk,cube_frag:Ik,depth_vert:Ck,depth_frag:Nk,distance_vert:Pk,distance_frag:Ok,equirect_vert:kk,equirect_frag:Dk,linedashed_vert:Lk,linedashed_frag:Fk,meshbasic_vert:Uk,meshbasic_frag:Bk,meshlambert_vert:zk,meshlambert_frag:Vk,meshmatcap_vert:jk,meshmatcap_frag:Hk,meshnormal_vert:Gk,meshnormal_frag:$k,meshphong_vert:Kk,meshphong_frag:Wk,meshphysical_vert:Xk,meshphysical_frag:qk,meshtoon_vert:Jk,meshtoon_frag:Zk,points_vert:Yk,points_frag:Qk,shadow_vert:eD,shadow_frag:tD,sprite_vert:nD,sprite_frag:iD},Te={common:{diffuse:{value:new qe(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new tt},alphaMap:{value:null},alphaMapTransform:{value:new tt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new tt}},envmap:{envMap:{value:null},envMapRotation:{value:new tt},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:0.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new tt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new tt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new tt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new tt},normalScale:{value:new Ke(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new tt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new tt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new tt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new tt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:0.00025},fogNear:{value:1},fogFar:{value:2000},fogColor:{value:new qe(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new j},probesMax:{value:new j},probesResolution:{value:new j}},points:{diffuse:{value:new qe(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new tt},alphaTest:{value:0},uvTransform:{value:new tt}},sprite:{diffuse:{value:new qe(16777215)},opacity:{value:1},center:{value:new Ke(0.5,0.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new tt},alphaMap:{value:null},alphaMapTransform:{value:new tt},alphaTest:{value:0}}},br={basic:{uniforms:Fn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.fog]),vertexShader:st.meshbasic_vert,fragmentShader:st.meshbasic_frag},lambert:{uniforms:Fn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new qe(0)},envMapIntensity:{value:1}}]),vertexShader:st.meshlambert_vert,fragmentShader:st.meshlambert_frag},phong:{uniforms:Fn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new qe(0)},specular:{value:new qe(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:st.meshphong_vert,fragmentShader:st.meshphong_frag},standard:{uniforms:Fn([Te.common,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.roughnessmap,Te.metalnessmap,Te.fog,Te.lights,{emissive:{value:new qe(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:st.meshphysical_vert,fragmentShader:st.meshphysical_frag},toon:{uniforms:Fn([Te.common,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.gradientmap,Te.fog,Te.lights,{emissive:{value:new qe(0)}}]),vertexShader:st.meshtoon_vert,fragmentShader:st.meshtoon_frag},matcap:{uniforms:Fn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,{matcap:{value:null}}]),vertexShader:st.meshmatcap_vert,fragmentShader:st.meshmatcap_frag},points:{uniforms:Fn([Te.points,Te.fog]),vertexShader:st.points_vert,fragmentShader:st.points_frag},dashed:{uniforms:Fn([Te.common,Te.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:st.linedashed_vert,fragmentShader:st.linedashed_frag},depth:{uniforms:Fn([Te.common,Te.displacementmap]),vertexShader:st.depth_vert,fragmentShader:st.depth_frag},normal:{uniforms:Fn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,{opacity:{value:1}}]),vertexShader:st.meshnormal_vert,fragmentShader:st.meshnormal_frag},sprite:{uniforms:Fn([Te.sprite,Te.fog]),vertexShader:st.sprite_vert,fragmentShader:st.sprite_frag},background:{uniforms:{uvTransform:{value:new tt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:st.background_vert,fragmentShader:st.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new tt}},vertexShader:st.backgroundCube_vert,fragmentShader:st.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:st.cube_vert,fragmentShader:st.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:st.equirect_vert,fragmentShader:st.equirect_frag},distance:{uniforms:Fn([Te.common,Te.displacementmap,{referencePosition:{value:new j},nearDistance:{value:1},farDistance:{value:1000}}]),vertexShader:st.distance_vert,fragmentShader:st.distance_frag},shadow:{uniforms:Fn([Te.lights,Te.fog,{color:{value:new qe(0)},opacity:{value:1}}]),vertexShader:st.shadow_vert,fragmentShader:st.shadow_frag}};br.physical={uniforms:Fn([br.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new tt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new tt},clearcoatNormalScale:{value:new Ke(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new tt},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new tt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new tt},sheen:{value:0},sheenColor:{value:new qe(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new tt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new tt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new tt},transmissionSamplerSize:{value:new Ke},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new tt},attenuationDistance:{value:0},attenuationColor:{value:new qe(0)},specularColor:{value:new qe(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new tt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new tt},anisotropyVector:{value:new Ke},anisotropyMap:{value:null},anisotropyMapTransform:{value:new tt}}]),vertexShader:st.meshphysical_vert,fragmentShader:st.meshphysical_frag};Gd={r:0,b:0,g:0},rD=new Je,SA=new tt;SA.set(-1,0,0,0,1,0,0,0,1);ml=new Ca,rA=new qe,hD=new j,Na=new j;dg=class dg extends li{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 Od(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;@@ -4221,61 +4221,61 @@ void main() {gl_FragColor = texture2D( tEquirect, sampleUV );}- `},i=new bs(5,5,5),r=new Ei({name:"CubemapFromEquirect",uniforms:Sa(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:kn,blending:dr});r.uniforms.tEquirect.value=t;let s=new jt(i,r),a=t.minFilter;if(t.minFilter===fr)t.minFilter=En;return new Hm(1,10,this).update(e,s),t.minFilter=a,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)}};yD={[Dp]:"LINEAR_TONE_MAPPING",[Lp]:"REINHARD_TONE_MAPPING",[Fp]:"CINEON_TONE_MAPPING",[Xc]:"ACES_FILMIC_TONE_MAPPING",[Bp]:"AGX_TONE_MAPPING",[zp]:"NEUTRAL_TONE_MAPPING",[Up]:"CUSTOM_TONE_MAPPING"};TA=new en,rg=new wa(1,1),AA=new Td,wA=new Pm,SA=new Cd,rA=[],sA=[],aA=new Float32Array(16),oA=new Float32Array(9),cA=new Float32Array(4);ng=/(\w+)(\])?(\[|\.)?/g;dA=new tt;hL={[Dp]:"Linear",[Lp]:"Reinhard",[Fp]:"Cineon",[Xc]:"ACESFilmic",[Bp]:"AgX",[zp]:"Neutral",[Up]:"Custom"};jd=new j;yL=/^[ \t]*#include +<([\w\d./]+)>/gm;_L=new Map;EL=/#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;AL={[Kc]:"SHADOWMAP_TYPE_PCF",[Ao]:"SHADOWMAP_TYPE_VSM"};SL={[So]:"ENVMAP_TYPE_CUBE",[ya]:"ENVMAP_TYPE_CUBE",[qc]:"ENVMAP_TYPE_CUBE_UV"};RL={[ya]:"ENVMAP_MODE_REFRACTION"};CL={[AT]:"ENVMAP_BLENDING_MULTIPLY",[wT]:"ENVMAP_BLENDING_MIX",[ST]:"ENVMAP_BLENDING_ADD"};XL=[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)],qL=[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)],_A=new Qe,pl=new j,ig=new j;OA=class OA extends Vi{constructor(e,t){super();let n=this,i=null,r=1,s=null,a="local-floor",o=1,c=null,l=null,u=null,d=null,f=null,h=null,b=typeof XRWebGLBinding<"u",m=new PA,g={},p=t.getContextAttributes(),x=null,_=null,y=[],v=[],T=new Ke,A=null,E=null,w=new fn;w.viewport=new Pt;let P=new fn;P.viewport=new Pt;let S=[w,P],I=new Gm,U=null,N=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(J){let L=y[J];if(L===void 0)L=new el,y[J]=L;return L.getTargetRaySpace()},this.getControllerGrip=function(J){let L=y[J];if(L===void 0)L=new el,y[J]=L;return L.getGripSpace()},this.getHand=function(J){let L=y[J];if(L===void 0)L=new el,y[J]=L;return L.getHandSpace()};function F(J){let L=v.indexOf(J.inputSource);if(L===-1)return;let W=y[L];if(W!==void 0)W.update(J.inputSource,J.frame,c||s),W.dispatchEvent({type:J.type,data:J.inputSource})}function D(){i.removeEventListener("select",F),i.removeEventListener("selectstart",F),i.removeEventListener("selectend",F),i.removeEventListener("squeeze",F),i.removeEventListener("squeezestart",F),i.removeEventListener("squeezeend",F),i.removeEventListener("end",D),i.removeEventListener("inputsourceschange",O);for(let J=0;J<y.length;J++){let L=v[J];if(L===null)continue;v[J]=null,y[J].disconnect(L)}U=null,N=null,m.reset();for(let J in g)delete g[J];if(e.setRenderTarget(x),f=null,d=null,u=null,i=null,_=null,pe.stop(),n.isPresenting=!1,e.setPixelRatio(A),e.setSize(T.width,T.height,!1),E!==null){let J=E.camera;J.fov=E.fov,J.zoom=E.zoom,J.updateProjectionMatrix(),E=null}n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(J){if(r=J,n.isPresenting===!0)je("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(J){if(a=J,n.isPresenting===!0)je("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||s},this.setReferenceSpace=function(J){c=J},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){if(u===null&&b)u=new XRWebGLBinding(i,t);return u},this.getFrame=function(){return h},this.getSession=function(){return i},this.setSession=async function(J){if(i=J,i!==null){if(x=e.getRenderTarget(),i.addEventListener("select",F),i.addEventListener("selectstart",F),i.addEventListener("selectend",F),i.addEventListener("squeeze",F),i.addEventListener("squeezestart",F),i.addEventListener("squeezeend",F),i.addEventListener("end",D),i.addEventListener("inputsourceschange",O),p.xrCompatible!==!0)await t.makeXRCompatible();if(A=e.getPixelRatio(),e.getSize(T),!(b&&("createProjectionLayer"in XRWebGLBinding.prototype))){let W={antialias:p.antialias,alpha:!0,depth:p.depth,stencil:p.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(i,t,W),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),_=new ci(f.framebufferWidth,f.framebufferHeight,{format:pr,type:zi,colorSpace:e.outputColorSpace,stencilBuffer:p.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1,storeMultisampledDepthBuffer:f.ignoreDepthValues===!1,storeMultisampledStencilBuffer:f.ignoreDepthValues===!1})}else{let W=null,ne=null,ie=null;if(p.depth)ie=p.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,W=p.stencil?Ea:va,ne=p.stencil?Co:hs;let ce={colorFormat:t.RGBA8,depthFormat:ie,scaleFactor:r};u=this.getBinding(),d=u.createProjectionLayer(ce),i.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),_=new ci(d.textureWidth,d.textureHeight,{format:pr,type:zi,depthTexture:new wa(d.textureWidth,d.textureHeight,ne,void 0,void 0,void 0,void 0,void 0,void 0,W),stencilBuffer:p.stencil,colorSpace:e.outputColorSpace,samples:p.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1,storeMultisampledDepthBuffer:d.ignoreDepthValues===!1,storeMultisampledStencilBuffer:d.ignoreDepthValues===!1})}_.isXRRenderTarget=!0,this.setFoveation(o),c=null,s=await i.requestReferenceSpace(a),pe.setContext(i),pe.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function O(J){for(let L=0;L<J.removed.length;L++){let W=J.removed[L],ne=v.indexOf(W);if(ne>=0)v[ne]=null,y[ne].disconnect(W)}for(let L=0;L<J.added.length;L++){let W=J.added[L],ne=v.indexOf(W);if(ne===-1){for(let ce=0;ce<y.length;ce++)if(ce>=v.length){v.push(W),ne=ce;break}else if(v[ce]===null){v[ce]=W,ne=ce;break}if(ne===-1)break}let ie=y[ne];if(ie)ie.connect(W)}}let K=new j,B=new j;function X(J,L,W){K.setFromMatrixPosition(L.matrixWorld),B.setFromMatrixPosition(W.matrixWorld);let ne=K.distanceTo(B),ie=L.projectionMatrix.elements,ce=W.projectionMatrix.elements,_e=ie[14]/(ie[10]-1),Re=ie[14]/(ie[10]+1),Oe=(ie[9]+1)/ie[5],We=(ie[9]-1)/ie[5],Ye=(ie[8]-1)/ie[0],Wt=(ce[8]+1)/ce[0],lt=_e*Ye,Lt=_e*Wt,Qt=ne/(-Ye+Wt),nn=Qt*-Ye;if(L.matrixWorld.decompose(J.position,J.quaternion,J.scale),J.translateX(nn),J.translateZ(Qt),J.matrixWorld.compose(J.position,J.quaternion,J.scale),J.matrixWorldInverse.copy(J.matrixWorld).invert(),ie[10]===-1)J.projectionMatrix.copy(L.projectionMatrix),J.projectionMatrixInverse.copy(L.projectionMatrixInverse);else{let z=_e+Qt,yn=Re+Qt,St=lt-nn,Xt=Lt+(ne-nn),C=Oe*Re/yn*z,M=We*Re/yn*z;J.projectionMatrix.makePerspective(St,Xt,C,M,z,yn),J.projectionMatrixInverse.copy(J.projectionMatrix).invert()}}function q(J,L){if(L===null)J.matrixWorld.copy(J.matrix);else J.matrixWorld.multiplyMatrices(L.matrixWorld,J.matrix);J.matrixWorldInverse.copy(J.matrixWorld).invert()}this.updateCamera=function(J){if(i===null)return;let{near:L,far:W}=J;if(m.texture!==null){if(m.depthNear>0)L=m.depthNear;if(m.depthFar>0)W=m.depthFar}if(I.near=P.near=w.near=L,I.far=P.far=w.far=W,U!==I.near||N!==I.far)i.updateRenderState({depthNear:I.near,depthFar:I.far}),U=I.near,N=I.far;I.layers.mask=J.layers.mask|6,w.layers.mask=I.layers.mask&-5,P.layers.mask=I.layers.mask&-3;let ne=J.parent,ie=I.cameras;q(I,ne);for(let ce=0;ce<ie.length;ce++)q(ie[ce],ne);if(ie.length===2)X(I,w,P);else I.projectionMatrix.copy(w.projectionMatrix);if(E===null&&J.isPerspectiveCamera)E={camera:J,fov:J.fov,zoom:J.zoom};le(J,I,ne)};function le(J,L,W){if(W===null)J.matrix.copy(L.matrixWorld);else J.matrix.copy(W.matrixWorld),J.matrix.invert(),J.matrix.multiply(L.matrixWorld);if(J.matrix.decompose(J.position,J.quaternion,J.scale),J.updateMatrixWorld(!0),J.projectionMatrix.copy(L.projectionMatrix),J.projectionMatrixInverse.copy(L.projectionMatrixInverse),J.isPerspectiveCamera)J.fov=xa*2*Math.atan(1/J.projectionMatrix.elements[5]),J.zoom=1}this.getCamera=function(){return I},this.getFoveation=function(){if(d===null&&f===null)return;return o},this.setFoveation=function(J){if(o=J,d!==null)d.fixedFoveation=J;if(f!==null&&f.fixedFoveation!==void 0)f.fixedFoveation=J},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(I)},this.getCameraTexture=function(J){return g[J]};let de=null;function Me(J,L){if(l=L.getViewerPose(c||s),h=L,l!==null){let W=l.views;if(f!==null)e.setRenderTargetFramebuffer(_,f.framebuffer),e.setRenderTarget(_);let ne=!1;if(W.length!==I.cameras.length)I.cameras.length=0,ne=!0;for(let Re=0;Re<W.length;Re++){let Oe=W[Re],We=null;if(f!==null)We=f.getViewport(Oe);else{let Wt=u.getViewSubImage(d,Oe);if(We=Wt.viewport,Re===0)e.setRenderTargetTextures(_,Wt.colorTexture,Wt.depthStencilTexture),e.setRenderTarget(_)}let Ye=S[Re];if(Ye===void 0)Ye=new fn,Ye.layers.enable(Re),Ye.viewport=new Pt,S[Re]=Ye;if(Ye.matrix.fromArray(Oe.transform.matrix),Ye.matrix.decompose(Ye.position,Ye.quaternion,Ye.scale),Ye.projectionMatrix.fromArray(Oe.projectionMatrix),Ye.projectionMatrixInverse.copy(Ye.projectionMatrix).invert(),Ye.viewport.set(We.x,We.y,We.width,We.height),Re===0)I.matrix.copy(Ye.matrix),I.matrix.decompose(I.position,I.quaternion,I.scale);if(ne===!0)I.cameras.push(Ye)}let ie=i.enabledFeatures;if(ie&&ie.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&b){u=n.getBinding();let Re=u.getDepthInformation(W[0]);if(Re&&Re.isValid&&Re.texture)m.init(Re,i.renderState)}if(ie&&ie.includes("camera-access")&&b){e.state.unbindTexture(),u=n.getBinding();for(let Re=0;Re<W.length;Re++){let Oe=W[Re].camera;if(Oe){let We=g[Oe];if(!We)We=new Nd,g[Oe]=We;let Ye=u.getCameraImage(Oe);We.sourceTexture=Ye}}}}for(let W=0;W<y.length;W++){let ne=v[W],ie=y[W];if(ne!==null&&ie!==void 0)ie.update(ne,L,c||s)}if(de)de(J,L);if(L.detectedPlanes)n.dispatchEvent({type:"planesdetected",data:L});h=null}let pe=new vA;pe.setAnimationLoop(Me),this.setAnimationLoop=function(J){de=J},this.dispose=function(){}}};n8=new Qe,kA=new tt;kA.set(-1,0,0,0,1,0,0,0,1);s8=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])});async function El(e){let t=await crypto.subtle.digest("SHA-256",Uint8Array.from(e));return Array.from(new Uint8Array(t),(n)=>n.toString(16).padStart(2,"0")).join("")}function P8(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=()=>{throw Error("Texture manifest cannot read image dimensions")},i=(s,a)=>{if(s+a>e.byteLength)n()};if(e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return i(16,8),{width:t.getUint32(16),height:t.getUint32(20)};if(Sg(e))return i(20,8),{width:t.getUint32(20,!0),height:t.getUint32(24,!0)};if(e[0]===255&&e[1]===216){let s=2;while(s+4<=e.byteLength){if(e[s]!==255)n();let a=e[s+1];if(a===255){s++;continue}if(a===216||a===1||a>=208&&a<=215){s+=2;continue}let o=t.getUint16(s+2);if(a>=192&&a<=207&&![196,200,204].includes(a))return i(s+5,4),{width:t.getUint16(s+7),height:t.getUint16(s+5)};s+=2+o}n()}let r=(s)=>String.fromCharCode(...e.subarray(s,Math.min(s+4,e.byteLength)));if(r(0)==="RIFF"&&r(8)==="WEBP"){i(12,19);let s=r(12);if(s==="VP8X")return{width:1+(t.getUint32(24,!0)&16777215),height:1+(t.getUint32(27,!0)&16777215)};if(s==="VP8L"){let a=t.getUint32(21,!0);return{width:1+(a&16383),height:1+(a>>14&16383)}}if(s==="VP8 ")return i(26,4),{width:t.getUint16(26,!0)&16383,height:t.getUint16(28,!0)&16383}}return n()}function O8(e){if(!Ss(e))return;let t=Ss(e.extensions)?e.extensions:{};for(let n of["KHR_texture_basisu","EXT_texture_webp","EXT_texture_avif"]){let i=t[n];if(Ss(i)&&ws(i.source)!==void 0)return ws(i.source)}return ws(e.source)}function k8(e){let t=Array.isArray(e.textures)?e.textures:[],n=new Set;for(let i of Array.isArray(e.materials)?e.materials:[]){if(!Ss(i))continue;let r=Ss(i.pbrMetallicRoughness)?i.pbrMetallicRoughness:{};for(let s of[r.baseColorTexture,i.emissiveTexture]){let a=Ss(s)?ws(s.index):void 0,o=a===void 0?void 0:O8(t[a]);if(o!==void 0)n.add(o)}}return n}function D8(e){let t=atob(e);return Uint8Array.from(t,(n)=>n.charCodeAt(0))}function L8(e,t){let n=Array.isArray(e.bufferViews)?e.bufferViews:[];return(Array.isArray(e.images)?e.images:[]).map((i)=>{if(!Ss(i))throw Error("Invalid glTF image");let r=ws(i.bufferView);if(r!==void 0){let a=n[r];if(!Ss(a)||ws(a.buffer)!==0||!t)throw Error("Texture manifest requires images embedded in the GLB binary chunk");let o=ws(a.byteOffset)??0,c=ws(a.byteLength);if(c===void 0||o+c>t.byteLength)throw Error("Invalid glTF image buffer view");if(typeof i.mimeType!=="string")throw Error("Embedded image needs a mimeType");return{bytes:t.subarray(o,o+c),mimeType:i.mimeType}}let s=typeof i.uri==="string"?/^data:([^;,]+);base64,(.*)$/s.exec(i.uri):null;if(!s)throw Error("Texture manifest requires embedded image bytes");return{bytes:D8(s[2]),mimeType:s[1]}})}async function Rw(e,t,n={}){let i=k8(e),r=[];for(let[s,{bytes:a,mimeType:o}]of L8(e,t).entries()){let c=`sha256:${await El(a)}`,l=n.sources?.get(s),u=l??c,d=n.maps?.find((f)=>f.sha256===u);r.push({image:s,sha256:c,bytes:a.byteLength,mimeType:o,...P8(a),colorSpace:i.has(s)?"srgb":"linear",...l&&l!==c?{sourceSha256:l}:{},...d?{material:{pin:{...d.pin},slot:d.slot}}:{}})}return r}function Iw(e){let t={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/ktx2":"ktx2"}[e];if(!t)throw Error(`External textures do not support ${e}`);return t}var Ss=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),ws=(e)=>Number.isInteger(e)&&e>=0?e:void 0,N8,Sg=(e)=>e.byteLength>=12&&N8.every((t,n)=>e[n]===t);var Mg=mt(()=>{N8=Object.freeze([171,75,84,88,32,50,48,187,13,10,26,10])});var Cw=class{_listeners={};addEventListener(e,t){let n=this._listeners;if(n[e]===void 0)n[e]=[];if(n[e].indexOf(t)===-1)n[e].push(t);return this}removeEventListener(e,t){let n=this._listeners[e];if(n!==void 0){let i=n.indexOf(t);if(i!==-1)n.splice(i,1)}return this}dispatchEvent(e){let t=this._listeners[e.type];if(t!==void 0){let n=t.slice(0);for(let i=0,r=n.length;i<r;i++)n[i].call(this,e)}return this}dispose(){for(let e in this._listeners)delete this._listeners[e]}},Rs=class{_disposed=!1;_name;_parent;_child;_attributes;constructor(e,t,n,i={}){if(this._name=e,this._parent=t,this._child=n,this._attributes=i,!t.isOnGraph(n))throw Error("Cannot connect disconnected graphs.")}getName(){return this._name}getParent(){return this._parent}getChild(){return this._child}setChild(e){return this._child=e,this}getAttributes(){return this._attributes}dispose(){if(this._disposed)return;this._parent._destroyRef(this),this._disposed=!0}isDisposed(){return this._disposed}},Rg,bn=class{list=[];constructor(e){if(e)for(let t of e)this.list.push(t)}add(e){this.list.push(e)}remove(e){let t=this.list.indexOf(e);if(t>=0)this.list.splice(t,1)}removeChild(e){let t=[];for(let n of this.list)if(n.getChild()===e)t.push(n);for(let n of t)this.remove(n);return t}listRefsByChild(e){let t=[];for(let n of this.list)if(n.getChild()===e)t.push(n);return t}values(){return this.list}},It=class{set=new Set;map=new Map;constructor(e){if(e)for(let t of e)this.add(t)}add(e){let t=e.getChild();this.removeChild(t),this.set.add(e),this.map.set(t,e)}remove(e){this.set.delete(e),this.map.delete(e.getChild())}removeChild(e){let t=this.map.get(e)||null;if(t)this.remove(t);return t}getRefByChild(e){return this.map.get(e)||null}values(){return Array.from(this.set)}},dn=class{map={};constructor(e){if(e)Object.assign(this.map,e)}set(e,t){this.map[e]=t}delete(e){delete this.map[e]}get(e){return this.map[e]||null}keys(){return Object.keys(this.map)}values(){return Object.values(this.map)}},At,Ms,Nw;var Pw=mt(()=>{Rg=class extends Cw{_emptySet=new Set;_edges=new Set;_parentEdges=new Map;_childEdges=new Map;listEdges(){return Array.from(this._edges)}listParentEdges(e){return Array.from(this._childEdges.get(e)||this._emptySet)}listParents(e){let t=new Set;for(let n of this.listParentEdges(e))t.add(n.getParent());return Array.from(t)}listChildEdges(e){return Array.from(this._parentEdges.get(e)||this._emptySet)}listChildren(e){let t=new Set;for(let n of this.listChildEdges(e))t.add(n.getChild());return Array.from(t)}disconnectParents(e,t){for(let n of this.listParentEdges(e))if(!t||t(n.getParent()))n.dispose();return this}_createEdge(e,t,n,i){let r=new Rs(e,t,n,i);this._edges.add(r);let s=r.getParent();if(!this._parentEdges.has(s))this._parentEdges.set(s,new Set);this._parentEdges.get(s).add(r);let a=r.getChild();if(!this._childEdges.has(a))this._childEdges.set(a,new Set);return this._childEdges.get(a).add(r),r}_destroyEdge(e){return this._edges.delete(e),this._parentEdges.get(e.getParent()).delete(e),this._childEdges.get(e.getChild()).delete(e),this}},At=Symbol("attributes"),Ms=Symbol("immutableKeys"),Nw=class e extends Cw{_disposed=!1;graph;[At];[Ms];constructor(t){super();this.graph=t,this[Ms]=new Set,this[At]=this._createAttributes()}getDefaults(){return{}}_createAttributes(){let t=this.getDefaults(),n={};for(let i in t){let r=t[i];if(r instanceof e){let s=this.graph._createEdge(i,this,r);this[Ms].add(i),n[i]=s}else n[i]=r}return n}isOnGraph(t){return this.graph===t.graph}isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this.graph.listChildEdges(this).forEach((t)=>t.dispose()),this.graph.disconnectParents(this),this._disposed=!0,this.dispatchEvent({type:"dispose"})}detach(){return this.graph.disconnectParents(this),this}swap(t,n){for(let i in this[At]){let r=this[At][i];if(r instanceof Rs){let s=r;if(s.getChild()===t)this.setRef(i,n,s.getAttributes())}else if(r instanceof bn)for(let s of r.listRefsByChild(t)){let a=s.getAttributes();this.removeRef(i,t),this.addRef(i,n,a)}else if(r instanceof It){let s=r.getRefByChild(t);if(s){let a=s.getAttributes();this.removeRef(i,t),this.addRef(i,n,a)}}else if(r instanceof dn)for(let s of r.keys()){let a=r.get(s);if(a.getChild()===t)this.setRefMap(i,s,n,a.getAttributes())}}return this}get(t){return this[At][t]}set(t,n){return this[At][t]=n,this.dispatchEvent({type:"change",attribute:t})}getRef(t){let n=this[At][t];return n?n.getChild():null}setRef(t,n,i){if(this[Ms].has(t))throw Error(`Cannot overwrite immutable attribute, "${t}".`);let r=this[At][t];if(r)r.dispose();if(!n)return this;let s=this.graph._createEdge(t,this,n,i);return this[At][t]=s,this.dispatchEvent({type:"change",attribute:t})}listRefs(t){return this.assertRefList(t).values().map((n)=>n.getChild())}addRef(t,n,i){let r=this.graph._createEdge(t,this,n,i);return this.assertRefList(t).add(r),this.dispatchEvent({type:"change",attribute:t})}removeRef(t,n){let i=this.assertRefList(t);if(i instanceof bn)for(let r of i.listRefsByChild(n))r.dispose();else{let r=i.getRefByChild(n);if(r)r.dispose()}return this}assertRefList(t){let n=this[At][t];if(n instanceof bn||n instanceof It)return n;throw Error(`Expected RefList or RefSet for attribute "${t}"`)}listRefMapKeys(t){return this.assertRefMap(t).keys()}listRefMapValues(t){return this.assertRefMap(t).values().map((n)=>n.getChild())}getRefMap(t,n){let i=this.assertRefMap(t).get(n);return i?i.getChild():null}setRefMap(t,n,i,r){let s=this.assertRefMap(t),a=s.get(n);if(a)a.dispose();if(!i)return this;r=Object.assign(r||{},{key:n});let o=this.graph._createEdge(t,this,i,{...r,key:n});return s.set(n,o),this.dispatchEvent({type:"change",attribute:t,key:n})}assertRefMap(t){let n=this[At][t];if(n instanceof dn)return n;throw Error(`Expected RefMap for attribute "${t}"`)}dispatchEvent(t){return super.dispatchEvent({...t,target:this}),this.graph.dispatchEvent({...t,target:this,type:`node:${t.type}`}),this}_destroyRef(t){let n=t.getName();if(this[At][n]===t){if(this[At][n]=null,this[Ms].has(n))t.getChild().dispose()}else if(this[At][n]instanceof bn)this[At][n].remove(t);else if(this[At][n]instanceof It)this[At][n].remove(t);else if(this[At][n]instanceof dn){let i=this[At][n];for(let r of i.keys())if(i.get(r)===t)i.delete(r)}else return;this.graph._destroyEdge(t),this.dispatchEvent({type:"change",attribute:n})}}});function V8(e,t){if(t>e.byteLength)throw TypeError("Corrupt JPG, exceeded buffer limits");if(e.getUint8(t)!==255)throw TypeError("Invalid JPG, marker table corrupted");return e}function j8(){var e=new Ng(3);if(Ng!=Float32Array)e[0]=0,e[1]=0,e[2]=0;return e}function Ig(e){var t=e[0],n=e[1],i=e[2];return Math.sqrt(t*t+n*n+i*i)}function H8(e,t,n){var i=t[0],r=t[1],s=t[2],a=n[3]*i+n[7]*r+n[11]*s+n[15];return a=a||1,e[0]=(n[0]*i+n[4]*r+n[8]*s+n[12])/a,e[1]=(n[1]*i+n[5]*r+n[9]*s+n[13])/a,e[2]=(n[2]*i+n[6]*r+n[10]*s+n[14])/a,e}function Og(e){let t=jw(),n=e.propertyType==="Node"?[e]:e.listChildren();for(let i of n)i.traverse((r)=>{let s=r.getMesh();if(!s)return;let a=G8(s,r.getWorldMatrix());if(a.min.every(isFinite)&&a.max.every(isFinite))Pg(a.min,t),Pg(a.max,t)});return t}function G8(e,t){let n=jw();for(let i of e.listPrimitives()){let r=i.getAttribute("POSITION"),s=i.getIndices();if(!r)continue;let a=[0,0,0],o=[0,0,0];for(let c=0,l=s?s.getCount():r.getCount();c<l;c++){let u=s?s.getScalar(c):c;a=r.getElement(u,a),o=H8(o,a,t),Pg(o,n)}}return n}function Pg(e,t){for(let n=0;n<3;n++)t.min[n]=Math.min(e[n],t.min[n]),t.max[n]=Math.max(e[n],t.max[n])}function jw(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}function kw(e){return Object.prototype.toString.call(e)==="[object Object]"}function Na(e){if(kw(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;if(kw(n)===!1)return!1;if(Object.hasOwn(n,"isPrototypeOf")===!1)return!1;return!0}function K8(e){var t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],h=e[12],b=e[13],m=e[14],g=e[15],p=t*a-n*s,x=t*o-i*s,_=n*o-i*a,y=l*b-u*h,v=l*m-d*h,T=u*m-d*b,A=t*T-n*v+i*y,E=s*T-a*v+o*y,w=l*_-u*x+d*p,P=h*_-b*x+m*p;return c*A-r*E+g*w-f*P}function W8(e,t,n){var i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],c=t[5],l=t[6],u=t[7],d=t[8],f=t[9],h=t[10],b=t[11],m=t[12],g=t[13],p=t[14],x=t[15],_=n[0],y=n[1],v=n[2],T=n[3];return e[0]=_*i+y*o+v*d+T*m,e[1]=_*r+y*c+v*f+T*g,e[2]=_*s+y*l+v*h+T*p,e[3]=_*a+y*u+v*b+T*x,_=n[4],y=n[5],v=n[6],T=n[7],e[4]=_*i+y*o+v*d+T*m,e[5]=_*r+y*c+v*f+T*g,e[6]=_*s+y*l+v*h+T*p,e[7]=_*a+y*u+v*b+T*x,_=n[8],y=n[9],v=n[10],T=n[11],e[8]=_*i+y*o+v*d+T*m,e[9]=_*r+y*c+v*f+T*g,e[10]=_*s+y*l+v*h+T*p,e[11]=_*a+y*u+v*b+T*x,_=n[12],y=n[13],v=n[14],T=n[15],e[12]=_*i+y*o+v*d+T*m,e[13]=_*r+y*c+v*f+T*g,e[14]=_*s+y*l+v*h+T*p,e[15]=_*a+y*u+v*b+T*x,e}function X8(e,t){var n=t[0],i=t[1],r=t[2],s=t[4],a=t[5],o=t[6],c=t[8],l=t[9],u=t[10];return e[0]=Math.sqrt(n*n+i*i+r*r),e[1]=Math.sqrt(s*s+a*a+o*o),e[2]=Math.sqrt(c*c+l*l+u*u),e}function q8(e,t){var n=new Ng(3);X8(n,t);var i=1/n[0],r=1/n[1],s=1/n[2],a=t[0]*i,o=t[1]*r,c=t[2]*s,l=t[4]*i,u=t[5]*r,d=t[6]*s,f=t[8]*i,h=t[9]*r,b=t[10]*s,m=a+u+b,g=0;if(m>0)g=Math.sqrt(m+1)*2,e[3]=0.25*g,e[0]=(d-h)/g,e[1]=(f-c)/g,e[2]=(o-l)/g;else if(a>u&&a>b)g=Math.sqrt(1+a-u-b)*2,e[3]=(d-h)/g,e[0]=0.25*g,e[1]=(o+l)/g,e[2]=(f+c)/g;else if(u>b)g=Math.sqrt(1+u-a-b)*2,e[3]=(f-c)/g,e[0]=(o+l)/g,e[1]=0.25*g,e[2]=(d+h)/g;else g=Math.sqrt(1+b-a-u)*2,e[3]=(o-l)/g,e[0]=(f+c)/g,e[1]=(d+h)/g,e[2]=0.25*g;return e}function J8(e,t){if(!!e!==!!t)return!1;let n=e.getChild(),i=t.getChild();return n===i||n.equals(i)}function Z8(e,t){if(!!e!==!!t)return!1;let n=e.values(),i=t.values();if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++){let s=n[r],a=i[r];if(s.getChild()===a.getChild())continue;if(!s.getChild().equals(a.getChild()))return!1}return!0}function Y8(e,t){if(!!e!==!!t)return!1;let n=e.keys(),i=t.keys();if(n.length!==i.length)return!1;for(let r of n){let s=e.get(r),a=t.get(r);if(!!s!==!!a)return!1;let o=s.getChild(),c=a.getChild();if(o===c)continue;if(!o.equals(c))return!1}return!0}function Hw(e,t){if(e===t)return!0;if(!!e!==!!t||!e||!t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Gw(e,t){if(e===t)return!0;if(!!e!==!!t)return!1;if(!Na(e)||!Na(t))return e===t;let n=e,i=t,r=0,s=0,a;for(a in n)r++;for(a in i)s++;if(r!==s)return!1;for(a in n){let o=n[a],c=i[a];if(Qd(o)&&Qd(c)){if(!Hw(o,c))return!1}else if(Na(o)&&Na(c)){if(!Gw(o,c))return!1}else if(o!==c)return!1}return!0}function Qd(e){return Array.isArray(e)||ArrayBuffer.isView(e)}function rF(e){switch(e.constructor){case Float32Array:return Be.ComponentType.FLOAT;case Uint32Array:return Be.ComponentType.UNSIGNED_INT;case Uint16Array:return Be.ComponentType.UNSIGNED_SHORT;case Uint8Array:return Be.ComponentType.UNSIGNED_BYTE;case Int16Array:return Be.ComponentType.SHORT;case Int8Array:return Be.ComponentType.BYTE;case Float64Array:return Be.ComponentType.FLOAT64}if(typeof Float16Array<"u"&&e.constructor===Float16Array)return Be.ComponentType.FLOAT16;throw Error("Unknown accessor componentType.")}function lF(e,t){let n=t.jsonDoc,i=t.bufferViews[e.bufferView],r=n.json.bufferViews[e.bufferView],s=Tl[e.componentType],a=Be.getElementSize(e.type),o=s.BYTES_PER_ELEMENT,c=e.byteOffset||0,l=new s(e.count*a),u=new DataView(i.buffer,i.byteOffset,i.byteLength),d=r.byteStride;for(let f=0;f<e.count;f++)for(let h=0;h<a;h++){let b=c+f*d+h*o,m;switch(e.componentType){case Be.ComponentType.FLOAT:m=u.getFloat32(b,!0);break;case Be.ComponentType.UNSIGNED_INT:m=u.getUint32(b,!0);break;case Be.ComponentType.UNSIGNED_SHORT:m=u.getUint16(b,!0);break;case Be.ComponentType.UNSIGNED_BYTE:m=u.getUint8(b);break;case Be.ComponentType.SHORT:m=u.getInt16(b,!0);break;case Be.ComponentType.BYTE:m=u.getInt8(b);break;case Be.ComponentType.FLOAT16:m=u.getFloat16(b,!0);break;case Be.ComponentType.FLOAT64:m=u.getFloat64(b,!0);break;default:throw Error(`Unexpected componentType "${e.componentType}".`)}l[f*a+h]=m}return l}function Yd(e,t){let n=t.jsonDoc,i=t.bufferViews[e.bufferView],r=n.json.bufferViews[e.bufferView],s=Tl[e.componentType],a=Be.getElementSize(e.type),o=s.BYTES_PER_ELEMENT,c=a*o;if(r.byteStride!==void 0&&r.byteStride!==c)return lF(e,t);let l=i.byteOffset+(e.byteOffset||0),u=e.count*a*o;return new s(i.buffer.slice(l,l+u))}function uF(e,t){let n=Tl[e.componentType],i=Be.getElementSize(e.type),r;if(e.bufferView!==void 0)r=Yd(e,t);else r=new n(e.count*i);let s=e.sparse;if(!s)return r;let a=s.count,o={...e,...s.indices,count:a,type:"SCALAR"},c={...e,...s.values,count:a},l=Yd(o,t),u=Yd(c,t);for(let d=0;d<o.count;d++)for(let f=0;f<i;f++)r[l[d]*i+f]=u[d*i+f];return r}function dF(e,t){let n=e.getGraph().listParentEdges(t).find((i)=>i.getParent()!==e.getRoot());return n?n.getName().replace(/texture$/i,""):""}function bF(e){let t=[];for(let n in e){let i=e[n];if(Array.isArray(i)&&i.length===0)t.push(n);else if(i===null||i==="")t.push(n);else if(i&&typeof i==="object"&&Object.keys(i).length===0)t.push(n)}for(let n of t)delete e[n]}function yF(e,t){return t.uri!==void 0&&!(t.uri in e.resources)}function _F(e,t){return t.uri!==void 0&&!(t.uri in e.resources)&&t.bufferView===void 0}function Uw(e){if(e.byteLength<3*Uint32Array.BYTES_PER_ELEMENT)return!1;let t=new Uint32Array(e.buffer,e.byteOffset,3);return t[0]===1179937895&&t[1]===2}var Bw="v4.5.1",Cs="@glb.bin",te,F8,Ai,zw,U8,Tl,Je=class{static createBufferFromDataURI(e){if(typeof Buffer>"u"){let t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}else{let t=e.split(",")[1],n=e.indexOf("base64")>=0;return Buffer.from(t,n?"base64":"utf8")}}static encodeText(e){return new TextEncoder().encode(e)}static decodeText(e){return new TextDecoder().decode(e)}static concat(e){let t=0;for(let r of e)t+=r.byteLength;let n=new Uint8Array(t),i=0;for(let r of e)n.set(r,i),i+=r.byteLength;return n}static pad(e,t=0){let n=this.padNumber(e.byteLength);if(n===e.byteLength)return e;let i=new Uint8Array(n);if(i.set(e),t!==0)for(let r=e.byteLength;r<n;r++)i[r]=t;return i}static padNumber(e){return Math.ceil(e/4)*4}static equals(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;let n=e.byteLength;while(n--)if(e[n]!==t[n])return!1;return!0}static toView(e,t=0,n=1/0){return new Uint8Array(e.buffer,e.byteOffset+t,Math.min(e.byteLength,n))}static assertView(e){if(e&&!ArrayBuffer.isView(e))throw Error(`Method requires Uint8Array parameter; received "${typeof e}".`);return e}},Vw=class{static hexToFactor(e,t){e=Math.floor(e);let n=t;return n[0]=(e>>16&255)/255,n[1]=(e>>8&255)/255,n[2]=(e&255)/255,this.convertSRGBToLinear(t,t)}static factorToHex(e){let t=[...e],[n,i,r]=this.convertLinearToSRGB(e,t);return n*255<<16^i*255<<8^r*255<<0}static convertSRGBToLinear(e,t){let n=e,i=t;for(let r=0;r<3;r++)i[r]=n[r]<0.04045?n[r]*0.0773993808:Math.pow(n[r]*0.9478672986+0.0521327014,2.4);return t}static convertLinearToSRGB(e,t){let n=e,i=t;for(let r=0;r<3;r++)i[r]=n[r]<0.0031308?n[r]*12.92:1.055*Math.pow(n[r],0.41666)-0.055;return t}},B8=class{match(e){return e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255}getSize(e){let t=new DataView(e.buffer,e.byteOffset+4),n,i;while(t.byteLength){if(n=t.getUint16(0,!1),V8(t,n),i=t.getUint8(n+1),i===192||i===193||i===194)return[t.getUint16(n+7,!1),t.getUint16(n+5,!1)];t=new DataView(e.buffer,t.byteOffset+n+2)}throw TypeError("Invalid JPG, no size found")}getChannels(e){return 3}},z8=class e{static PNG_FRIED_CHUNK_NAME="CgBI";match(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10}getSize(t){let n=new DataView(t.buffer,t.byteOffset);if(Je.decodeText(t.slice(12,16))===e.PNG_FRIED_CHUNK_NAME)return[n.getUint32(32,!1),n.getUint32(36,!1)];return[n.getUint32(16,!1),n.getUint32(20,!1)]}getChannels(t){return 4}},Gi,Pa=class{static basename(e){let t=e.split(/[\\/]/).pop();return t.substring(0,t.lastIndexOf("."))}static extension(e){if(e.startsWith("data:image/")){let t=e.match(/data:(image\/\w+)/)[1];return Gi.mimeTypeToExtension(t)}else if(e.startsWith("data:model/gltf+json"))return"gltf";else if(e.startsWith("data:model/gltf-binary"))return"glb";else if(e.startsWith("data:application/"))return"bin";return e.split(/[\\/]/).pop().split(/[.]/).pop()}},Ng,Ow="https://null.example",Cg,$8,ka,pt=class e{static identity(t){return t}static eq(t,n,i=0.00001){if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(Math.abs(t[r]-n[r])>i)return!1;return!0}static clamp(t,n,i){if(t<n)return n;if(t>i)return i;return t}static decodeNormalizedInt(t,n){switch(n){case 5126:return t;case 5123:return t/65535;case 5121:return t/255;case 5122:return Math.max(t/32767,-1);case 5120:return Math.max(t/127,-1);default:throw Error("Invalid component type.")}}static encodeNormalizedInt(t,n){switch(n){case 5126:return t;case 5123:return Math.round(e.clamp(t,0,1)*65535);case 5121:return Math.round(e.clamp(t,0,1)*255);case 5122:return Math.round(e.clamp(t,-1,1)*32767);case 5120:return Math.round(e.clamp(t,-1,1)*127);default:throw Error("Invalid component type.")}}static decompose(t,n,i,r){let s=Ig([t[0],t[1],t[2]]),a=Ig([t[4],t[5],t[6]]),o=Ig([t[8],t[9],t[10]]);if(K8(t)<0)s=-s;n[0]=t[12],n[1]=t[13],n[2]=t[14];let c=t.slice(),l=1/s,u=1/a,d=1/o;c[0]*=l,c[1]*=l,c[2]*=l,c[4]*=u,c[5]*=u,c[6]*=u,c[8]*=d,c[9]*=d,c[10]*=d,q8(i,c),r[0]=s,r[1]=a,r[2]=o}static compose(t,n,i,r){let s=r,a=n[0],o=n[1],c=n[2],l=n[3],u=a+a,d=o+o,f=c+c,h=a*u,b=a*d,m=a*f,g=o*d,p=o*f,x=c*f,_=l*u,y=l*d,v=l*f,T=i[0],A=i[1],E=i[2];return s[0]=(1-(g+x))*T,s[1]=(b+v)*T,s[2]=(m-y)*T,s[3]=0,s[4]=(b-v)*A,s[5]=(1-(h+x))*A,s[6]=(p+_)*A,s[7]=0,s[8]=(m+y)*E,s[9]=(p-_)*E,s[10]=(1-(h+g))*E,s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s}},Q8="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",eF=999,tF=6,Dw,nF=function(){let e="";for(let t=0;t<tF;t++)e+=Q8.charAt(Math.floor(Math.random()*42));return e},$w=function(){for(let e=0;e<eF;e++){let t=nF();if(!Dw.has(t))return Dw.add(t),t}return""},Ns=(e)=>e,iF,kg,Gn,Be,Kw,Da,Al,Ww,ef,nt,wt,Xd,qd,Jd,sF,Oa,Dg,tf,Jn,Lg,nf,Xw,Xo,Ps,rf,_t=class{static EXTENSION_NAME;extensionName="";prereadTypes=[];prewriteTypes=[];readDependencies=[];writeDependencies=[];document;required=!1;properties=new Set;_listener;constructor(e){this.document=e,e.getRoot()._enableExtension(this),this._listener=(n)=>{let i=n,r=i.target;if(r instanceof nt&&r.extensionName===this.extensionName){if(i.type==="node:create")this._addExtensionProperty(r);if(i.type==="node:dispose")this._removeExtensionProperty(r)}};let t=e.getGraph();t.addEventListener("node:create",this._listener),t.addEventListener("node:dispose",this._listener)}dispose(){this.document.getRoot()._disableExtension(this);let e=this.document.getGraph();e.removeEventListener("node:create",this._listener),e.removeEventListener("node:dispose",this._listener);for(let t of this.properties)t.dispose()}static register(){}isRequired(){return this.required}setRequired(e){return this.required=e,this}listProperties(){return Array.from(this.properties)}_addExtensionProperty(e){return this.properties.add(e),this}_removeExtensionProperty(e){return this.properties.delete(e),this}install(e,t){return this}preread(e,t){return this}prewrite(e,t){return this}},aF=class{jsonDoc;buffers=[];bufferViews=[];bufferViewBuffers=[];accessors=[];textures=[];textureInfos=new Map;materials=[];meshes=[];cameras=[];nodes=[];skins=[];animations=[];scenes=[];constructor(e){this.jsonDoc=e}setTextureInfo(e,t){if(this.textureInfos.set(e,t),t.texCoord!==void 0)e.setTexCoord(t.texCoord);if(t.extras!==void 0)e.setExtras(t.extras);let n=this.jsonDoc.json.textures[t.index];if(n.sampler===void 0)return;let i=this.jsonDoc.json.samplers[n.sampler];if(i.magFilter!==void 0)e.setMagFilter(i.magFilter);if(i.minFilter!==void 0)e.setMinFilter(i.minFilter);if(i.wrapS!==void 0)e.setWrapS(i.wrapS);if(i.wrapT!==void 0)e.setWrapT(i.wrapT)}},Lw,oF,cF=class{static read(e,t=Lw){let n={...Lw,...t},{json:i}=e,r=new rf().setLogger(n.logger);this.validate(e,n);let s=new aF(e),a=i.asset,o=r.getRoot().getAsset();if(a.copyright)o.copyright=a.copyright;if(a.extras)o.extras=a.extras;if(i.extras!==void 0)r.getRoot().setExtras({...i.extras});let c=i.extensionsUsed||[],l=i.extensionsRequired||[];n.extensions.sort((p,x)=>p.EXTENSION_NAME>x.EXTENSION_NAME?1:-1);for(let p of n.extensions)if(c.includes(p.EXTENSION_NAME)){let x=r.createExtension(p).setRequired(l.includes(p.EXTENSION_NAME)),_=x.prereadTypes.filter((y)=>!oF.has(y));if(_.length)n.logger.warn(`Preread hooks for some types (${_.join()}), requested by extension ${x.extensionName}, are unsupported. Please file an issue or a PR.`);for(let y of x.readDependencies)x.install(y,n.dependencies[y])}let u=i.buffers||[];r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Buffer")).forEach((p)=>p.preread(s,"Buffer")),s.buffers=u.map((p)=>{let x=r.createBuffer(p.name);if(p.extras)x.setExtras(p.extras);if(p.uri&&p.uri.indexOf("__")!==0)x.setURI(p.uri);return x}),s.bufferViewBuffers=(i.bufferViews||[]).map((p,x)=>{if(!s.bufferViews[x]){let _=e.json.buffers[p.buffer],y=_.uri?e.resources[_.uri]:e.resources[Cs],v=p.byteOffset||0;s.bufferViews[x]=Je.toView(y,v,p.byteLength)}return s.buffers[p.buffer]});let d=i.accessors||[];s.accessors=d.map((p)=>{let x=s.bufferViewBuffers[p.bufferView],_=r.createAccessor(p.name,x).setType(p.type);if(p.extras)_.setExtras(p.extras);if(p.normalized!==void 0)_.setNormalized(p.normalized);if(p.bufferView===void 0)return _;return _.setArray(Yd(p,s)),_});let f=i.images||[],h=i.textures||[];r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Texture")).forEach((p)=>p.preread(s,"Texture")),s.textures=f.map((p)=>{let x=r.createTexture(p.name);if(p.extras)x.setExtras(p.extras);if(p.bufferView!==void 0){let _=i.bufferViews[p.bufferView],y=e.json.buffers[_.buffer],v=y.uri?e.resources[y.uri]:e.resources[Cs],T=_.byteOffset||0,A=_.byteLength,E=v.slice(T,T+A);x.setImage(E)}else if(p.uri!==void 0){if(x.setImage(e.resources[p.uri]),p.uri.indexOf("__")!==0)x.setURI(p.uri)}if(p.mimeType!==void 0)x.setMimeType(p.mimeType);else if(p.uri){let _=Pa.extension(p.uri);x.setMimeType(Gi.extensionToMimeType(_))}return x}),r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Material")).forEach((p)=>p.preread(s,"Material")),s.materials=(i.materials||[]).map((p)=>{let x=r.createMaterial(p.name);if(p.extras)x.setExtras(p.extras);if(p.alphaMode!==void 0)x.setAlphaMode(p.alphaMode);if(p.alphaCutoff!==void 0)x.setAlphaCutoff(p.alphaCutoff);if(p.doubleSided!==void 0)x.setDoubleSided(p.doubleSided);let _=p.pbrMetallicRoughness||{};if(_.baseColorFactor!==void 0)x.setBaseColorFactor(_.baseColorFactor);if(p.emissiveFactor!==void 0)x.setEmissiveFactor(p.emissiveFactor);if(_.metallicFactor!==void 0)x.setMetallicFactor(_.metallicFactor);if(_.roughnessFactor!==void 0)x.setRoughnessFactor(_.roughnessFactor);if(_.baseColorTexture!==void 0){let y=_.baseColorTexture,v=s.textures[h[y.index].source];x.setBaseColorTexture(v),s.setTextureInfo(x.getBaseColorTextureInfo(),y)}if(p.emissiveTexture!==void 0){let y=p.emissiveTexture,v=s.textures[h[y.index].source];x.setEmissiveTexture(v),s.setTextureInfo(x.getEmissiveTextureInfo(),y)}if(p.normalTexture!==void 0){let y=p.normalTexture,v=s.textures[h[y.index].source];if(x.setNormalTexture(v),s.setTextureInfo(x.getNormalTextureInfo(),y),p.normalTexture.scale!==void 0)x.setNormalScale(p.normalTexture.scale)}if(p.occlusionTexture!==void 0){let y=p.occlusionTexture,v=s.textures[h[y.index].source];if(x.setOcclusionTexture(v),s.setTextureInfo(x.getOcclusionTextureInfo(),y),p.occlusionTexture.strength!==void 0)x.setOcclusionStrength(p.occlusionTexture.strength)}if(_.metallicRoughnessTexture!==void 0){let y=_.metallicRoughnessTexture,v=s.textures[h[y.index].source];x.setMetallicRoughnessTexture(v),s.setTextureInfo(x.getMetallicRoughnessTextureInfo(),y)}return x}),r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Mesh")).forEach((p)=>p.preread(s,"Mesh"));let b=i.meshes||[];r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Primitive")).forEach((p)=>p.preread(s,"Primitive")),s.meshes=b.map((p)=>{let x=r.createMesh(p.name);if(p.extras)x.setExtras(p.extras);if(p.weights!==void 0)x.setWeights(p.weights);return(p.primitives||[]).forEach((_)=>{let y=r.createPrimitive();if(_.extras)y.setExtras(_.extras);if(_.material!==void 0)y.setMaterial(s.materials[_.material]);if(_.mode!==void 0)y.setMode(_.mode);for(let[T,A]of Object.entries(_.attributes||{}))y.setAttribute(T,s.accessors[A]);if(_.indices!==void 0)y.setIndices(s.accessors[_.indices]);let v=p.extras&&p.extras.targetNames||[];(_.targets||[]).forEach((T,A)=>{let E=v[A]||A.toString(),w=r.createPrimitiveTarget(E);for(let[P,S]of Object.entries(T))w.setAttribute(P,s.accessors[S]);y.addTarget(w)}),x.addPrimitive(y)}),x}),s.cameras=(i.cameras||[]).map((p)=>{let x=r.createCamera(p.name).setType(p.type);if(p.extras)x.setExtras(p.extras);if(p.type===ef.Type.PERSPECTIVE){let _=p.perspective;if(x.setYFov(_.yfov),x.setZNear(_.znear),_.zfar!==void 0)x.setZFar(_.zfar);if(_.aspectRatio!==void 0)x.setAspectRatio(_.aspectRatio)}else{let _=p.orthographic;x.setZNear(_.znear).setZFar(_.zfar).setXMag(_.xmag).setYMag(_.ymag)}return x});let m=i.nodes||[];r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Node")).forEach((p)=>p.preread(s,"Node")),s.nodes=m.map((p)=>{let x=r.createNode(p.name);if(p.extras)x.setExtras(p.extras);if(p.translation!==void 0)x.setTranslation(p.translation);if(p.rotation!==void 0)x.setRotation(p.rotation);if(p.scale!==void 0)x.setScale(p.scale);if(p.matrix!==void 0){let _=[0,0,0],y=[0,0,0,1],v=[1,1,1];pt.decompose(p.matrix,_,y,v),x.setTranslation(_),x.setRotation(y),x.setScale(v)}if(p.weights!==void 0)x.setWeights(p.weights);return x}),s.skins=(i.skins||[]).map((p)=>{let x=r.createSkin(p.name);if(p.extras)x.setExtras(p.extras);if(p.inverseBindMatrices!==void 0)x.setInverseBindMatrices(s.accessors[p.inverseBindMatrices]);if(p.skeleton!==void 0)x.setSkeleton(s.nodes[p.skeleton]);for(let _ of p.joints)x.addJoint(s.nodes[_]);return x}),m.map((p,x)=>{let _=s.nodes[x];if((p.children||[]).forEach((y)=>_.addChild(s.nodes[y])),p.mesh!==void 0)_.setMesh(s.meshes[p.mesh]);if(p.camera!==void 0)_.setCamera(s.cameras[p.camera]);if(p.skin!==void 0)_.setSkin(s.skins[p.skin])}),s.animations=(i.animations||[]).map((p)=>{let x=r.createAnimation(p.name);if(p.extras)x.setExtras(p.extras);let _=(p.samplers||[]).map((y)=>{let v=r.createAnimationSampler().setInput(s.accessors[y.input]).setOutput(s.accessors[y.output]).setInterpolation(y.interpolation||Al.Interpolation.LINEAR);if(y.extras)v.setExtras(y.extras);return x.addSampler(v),v});return(p.channels||[]).forEach((y)=>{let v=r.createAnimationChannel().setSampler(_[y.sampler]).setTargetPath(y.target.path);if(y.target.node!==void 0)v.setTargetNode(s.nodes[y.target.node]);if(y.extras)v.setExtras(y.extras);x.addChannel(v)}),x});let g=i.scenes||[];if(r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Scene")).forEach((p)=>p.preread(s,"Scene")),s.scenes=g.map((p)=>{let x=r.createScene(p.name);if(p.extras)x.setExtras(p.extras);return(p.nodes||[]).map((_)=>s.nodes[_]).forEach((_)=>x.addChild(_)),x}),i.scene!==void 0)r.getRoot().setDefaultScene(s.scenes[i.scene]);return r.getRoot().listExtensionsUsed().forEach((p)=>p.read(s)),d.forEach((p,x)=>{let _=s.accessors[x],y=!!p.sparse,v=!p.bufferView&&!_.getArray();if(y||v)_.setSparse(!0).setArray(uF(p,s))}),r}static validate(e,t){let n=e.json;if(n.asset.version!=="2.0")throw Error(`Unsupported glTF version, "${n.asset.version}".`);if(n.extensionsRequired){for(let i of n.extensionsRequired)if(!t.extensions.find((r)=>r.EXTENSION_NAME===i))throw Error(`Missing required extension, "${i}".`)}if(n.extensionsUsed){for(let i of n.extensionsUsed)if(!t.extensions.find((r)=>r.EXTENSION_NAME===i))t.logger.warn(`Missing optional extension, "${i}".`)}}},qw,Is,Fw=class{multiple;basename;counter={};constructor(e,t){this.multiple=e,this.basename=t}createURI(e,t){if(e.getURI())return e.getURI();else if(!this.multiple)return`${this.basename(e)}.${t}`;else{let n=this.basename(e);return this.counter[n]=this.counter[n]||1,`${n}_${this.counter[n]++}.${t}`}}},Zd,fF,hF,pF,mF,gF=class{static write(e,t){let n=e.getGraph(),i=e.getRoot(),r={asset:{generator:`glTF-Transform ${Bw}`,...i.getAsset()},extras:{...i.getExtras()}},s={json:r,resources:{}},a=new Is(e,s,t),o=t.logger||ka.DEFAULT_INSTANCE,c=new Set(t.extensions.map((m)=>m.EXTENSION_NAME)),l=e.getRoot().listExtensionsUsed().filter((m)=>c.has(m.extensionName)).sort((m,g)=>m.extensionName>g.extensionName?1:-1),u=e.getRoot().listExtensionsRequired().filter((m)=>c.has(m.extensionName)).sort((m,g)=>m.extensionName>g.extensionName?1:-1);if(l.length<e.getRoot().listExtensionsUsed().length)o.warn("Some extensions were not registered for I/O, and will not be written.");for(let m of l){let g=m.prewriteTypes.filter((p)=>!mF.has(p));if(g.length)o.warn(`Prewrite hooks for some types (${g.join()}), requested by extension ${m.extensionName}, are unsupported. Please file an issue or a PR.`);for(let p of m.writeDependencies)m.install(p,t.dependencies[p])}function d(m,g,p,x){let _=[],y=0;for(let T of m){let A=a.createAccessorDef(T);A.bufferView=r.bufferViews.length;let E=T.getArray(),w=Je.pad(Je.toView(E));A.byteOffset=y,y+=w.byteLength,_.push(w),a.accessorIndexMap.set(T,r.accessors.length),r.accessors.push(A)}let v={buffer:g,byteOffset:p,byteLength:Je.concat(_).byteLength};if(x)v.target=x;return r.bufferViews.push(v),{buffers:_,byteLength:y}}function f(m,g,p){let x=m[0].getCount(),_=0;for(let E of m){let w=a.createAccessorDef(E);w.bufferView=r.bufferViews.length,w.byteOffset=_;let P=E.getElementSize(),S=E.getComponentSize();_+=Je.padNumber(P*S),a.accessorIndexMap.set(E,r.accessors.length),r.accessors.push(w)}let y=x*_,v=new ArrayBuffer(y),T=new DataView(v);for(let E=0;E<x;E++){let w=0;for(let P of m){let S=P.getElementSize(),I=P.getComponentSize(),U=P.getComponentType(),N=P.getArray();for(let F=0;F<S;F++){let D=E*_+w+F*I,O=N[E*S+F];switch(U){case Be.ComponentType.FLOAT:T.setFloat32(D,O,!0);break;case Be.ComponentType.BYTE:T.setInt8(D,O);break;case Be.ComponentType.SHORT:T.setInt16(D,O,!0);break;case Be.ComponentType.UNSIGNED_BYTE:T.setUint8(D,O);break;case Be.ComponentType.UNSIGNED_SHORT:T.setUint16(D,O,!0);break;case Be.ComponentType.UNSIGNED_INT:T.setUint32(D,O,!0);break;case Be.ComponentType.FLOAT16:T.setFloat16(D,O,!0);break;case Be.ComponentType.FLOAT64:T.setFloat64(D,O,!0);break;default:throw Error("Unexpected component type: "+U)}}w+=Je.padNumber(S*I)}}let A={buffer:g,byteOffset:p,byteLength:y,byteStride:_,target:Is.BufferViewTarget.ARRAY_BUFFER};return r.bufferViews.push(A),{byteLength:y,buffers:[new Uint8Array(v)]}}function h(m,g,p){let x=[],_=0,y=new Map,v=-1/0,T=!1;for(let U of m){let N=a.createAccessorDef(U);r.accessors.push(N),a.accessorIndexMap.set(U,r.accessors.length-1);let F=[],D=[],O=[],K=Array(U.getElementSize()).fill(0);for(let le=0,de=U.getCount();le<de;le++){if(U.getElement(le,O),pt.eq(O,K,0))continue;v=Math.max(le,v),F.push(le);for(let Me=0;Me<O.length;Me++)D.push(O[Me])}let B=F.length,X={accessorDef:N,count:B};if(y.set(U,X),B===0)continue;if(B>U.getCount()/2)T=!0;let q=Tl[U.getComponentType()];X.indices=F,X.values=new q(D)}if(!Number.isFinite(v))return{buffers:x,byteLength:_};if(T)o.warn("Some sparse accessors have >50% non-zero elements, which may increase file size.");let A=v<255?Uint8Array:v<65535?Uint16Array:Uint32Array,E=v<255?pF:v<65535?hF:fF,w={buffer:g,byteOffset:p+_,byteLength:0};for(let U of m){let N=y.get(U);if(N.count===0)continue;N.indicesByteOffset=w.byteLength;let F=Je.pad(Je.toView(new A(N.indices)));x.push(F),_+=F.byteLength,w.byteLength+=F.byteLength}r.bufferViews.push(w);let P=r.bufferViews.length-1,S={buffer:g,byteOffset:p+_,byteLength:0};for(let U of m){let N=y.get(U);if(N.count===0)continue;N.valuesByteOffset=S.byteLength;let F=Je.pad(Je.toView(N.values));x.push(F),_+=F.byteLength,S.byteLength+=F.byteLength}r.bufferViews.push(S);let I=r.bufferViews.length-1;for(let U of m){let N=y.get(U);if(N.count===0)continue;N.accessorDef.sparse={count:N.count,indices:{bufferView:P,byteOffset:N.indicesByteOffset,componentType:E},values:{bufferView:I,byteOffset:N.valuesByteOffset}}}return{buffers:x,byteLength:_}}if(r.accessors=[],r.bufferViews=[],r.samplers=[],r.textures=[],r.images=i.listTextures().map((m,g)=>{let p=a.createPropertyDef(m);if(m.getMimeType())p.mimeType=m.getMimeType();let x=m.getImage();if(x)a.createImageData(p,x,m);return a.imageIndexMap.set(m,g),p}),l.filter((m)=>m.prewriteTypes.includes("Accessor")).forEach((m)=>m.prewrite(a,"Accessor")),i.listAccessors().forEach((m)=>{let{accessorUsageGroupedByParent:g,accessorParents:p}=a;if(a.accessorIndexMap.has(m))return;let x=a.getAccessorUsage(m);if(a.addAccessorToUsageGroup(m,x),g.has(x)){let _=n.listParents(m).find((y)=>y.propertyType!=="Root");p.set(m,_)}}),l.filter((m)=>m.prewriteTypes.includes("Buffer")).forEach((m)=>m.prewrite(a,"Buffer")),(i.listAccessors().length>0||a.otherBufferViews.size>0||i.listTextures().length>0&&t.format==="GLB")&&i.listBuffers().length===0)throw Error("Buffer required for Document resources, but none was found.");if(r.buffers=[],i.listBuffers().forEach((m,g)=>{let p=a.createPropertyDef(m),x=a.accessorUsageGroupedByParent,_=m.listParents().filter((P)=>P instanceof Be),y=new Set(_.map((P)=>a.accessorParents.get(P))),v=new Map(Array.from(y).map((P,S)=>[P,S])),T={};for(let P of _){if(a.accessorIndexMap.has(P))continue;let S=a.getAccessorUsage(P),I=S;if(x.has(S)){let U=a.accessorParents.get(P);I+=`:${v.get(U)}`}T[I]||={usage:S,accessors:[]},T[I].accessors.push(P)}let A=[],E=r.buffers.length,w=0;for(let{usage:P,accessors:S}of Object.values(T))if(P===Zd.ARRAY_BUFFER&&t.vertexLayout==="interleaved"){let I=f(S,E,w);w+=I.byteLength;for(let U of I.buffers)A.push(U)}else if(P===Zd.ARRAY_BUFFER)for(let I of S){let U=f([I],E,w);w+=U.byteLength;for(let N of U.buffers)A.push(N)}else if(P===Zd.SPARSE){let I=h(S,E,w);w+=I.byteLength;for(let U of I.buffers)A.push(U)}else if(P===Zd.ELEMENT_ARRAY_BUFFER){let I=Is.BufferViewTarget.ELEMENT_ARRAY_BUFFER,U=d(S,E,w,I);w+=U.byteLength;for(let N of U.buffers)A.push(N)}else{let I=d(S,E,w);w+=I.byteLength;for(let U of I.buffers)A.push(U)}if(a.imageBufferViews.length&&g===0){for(let P=0;P<a.imageBufferViews.length;P++)if(r.bufferViews[r.images[P].bufferView].byteOffset=w,w+=a.imageBufferViews[P].byteLength,A.push(a.imageBufferViews[P]),w%8){let S=8-w%8;w+=S,A.push(new Uint8Array(S))}}if(a.otherBufferViews.has(m))for(let P of a.otherBufferViews.get(m))r.bufferViews.push({buffer:E,byteOffset:w,byteLength:P.byteLength}),a.otherBufferViewsIndexMap.set(P,r.bufferViews.length-1),w+=P.byteLength,A.push(P);if(w){let P;if(t.format==="GLB")P=Cs;else P=a.bufferURIGenerator.createURI(m,"bin"),p.uri=P;p.byteLength=w,a.assignResourceURI(P,Je.concat(A),!0)}r.buffers.push(p),a.bufferIndexMap.set(m,g)}),i.listAccessors().find((m)=>!m.getBuffer()))o.warn("Skipped writing one or more Accessors: no Buffer assigned.");l.filter((m)=>m.prewriteTypes.includes("Material")).forEach((m)=>m.prewrite(a,"Material")),r.materials=i.listMaterials().map((m,g)=>{let p=a.createPropertyDef(m);if(m.getAlphaMode()!==Oa.AlphaMode.OPAQUE)p.alphaMode=m.getAlphaMode();if(m.getAlphaMode()===Oa.AlphaMode.MASK)p.alphaCutoff=m.getAlphaCutoff();if(m.getDoubleSided())p.doubleSided=!0;if(p.pbrMetallicRoughness={},!pt.eq(m.getBaseColorFactor(),[1,1,1,1]))p.pbrMetallicRoughness.baseColorFactor=m.getBaseColorFactor();if(!pt.eq(m.getEmissiveFactor(),[0,0,0]))p.emissiveFactor=m.getEmissiveFactor();if(m.getRoughnessFactor()!==1)p.pbrMetallicRoughness.roughnessFactor=m.getRoughnessFactor();if(m.getMetallicFactor()!==1)p.pbrMetallicRoughness.metallicFactor=m.getMetallicFactor();if(m.getBaseColorTexture()){let x=m.getBaseColorTexture(),_=m.getBaseColorTextureInfo();p.pbrMetallicRoughness.baseColorTexture=a.createTextureInfoDef(x,_)}if(m.getEmissiveTexture()){let x=m.getEmissiveTexture(),_=m.getEmissiveTextureInfo();p.emissiveTexture=a.createTextureInfoDef(x,_)}if(m.getNormalTexture()){let x=m.getNormalTexture(),_=m.getNormalTextureInfo(),y=a.createTextureInfoDef(x,_);if(m.getNormalScale()!==1)y.scale=m.getNormalScale();p.normalTexture=y}if(m.getOcclusionTexture()){let x=m.getOcclusionTexture(),_=m.getOcclusionTextureInfo(),y=a.createTextureInfoDef(x,_);if(m.getOcclusionStrength()!==1)y.strength=m.getOcclusionStrength();p.occlusionTexture=y}if(m.getMetallicRoughnessTexture()){let x=m.getMetallicRoughnessTexture(),_=m.getMetallicRoughnessTextureInfo();p.pbrMetallicRoughness.metallicRoughnessTexture=a.createTextureInfoDef(x,_)}return a.materialIndexMap.set(m,g),p}),l.filter((m)=>m.prewriteTypes.includes("Mesh")).forEach((m)=>m.prewrite(a,"Mesh")),r.meshes=i.listMeshes().map((m,g)=>{let p=a.createPropertyDef(m),x=null;if(p.primitives=m.listPrimitives().map((_)=>{let y={attributes:{}};y.mode=_.getMode();let v=_.getMaterial();if(v)y.material=a.materialIndexMap.get(v);if(Object.keys(_.getExtras()).length)y.extras=_.getExtras();let T=_.getIndices();if(T)y.indices=a.accessorIndexMap.get(T);for(let A of _.listSemantics())y.attributes[A]=a.accessorIndexMap.get(_.getAttribute(A));for(let A of _.listTargets()){let E={};for(let w of A.listSemantics())E[w]=a.accessorIndexMap.get(A.getAttribute(w));y.targets=y.targets||[],y.targets.push(E)}if(_.listTargets().length&&!x)x=_.listTargets().map((A)=>A.getName());return y}),m.getWeights().length)p.weights=m.getWeights();if(x)p.extras=p.extras||{},p.extras.targetNames=x;return a.meshIndexMap.set(m,g),p}),r.cameras=i.listCameras().map((m,g)=>{let p=a.createPropertyDef(m);if(p.type=m.getType(),p.type===ef.Type.PERSPECTIVE){p.perspective={znear:m.getZNear(),zfar:m.getZFar(),yfov:m.getYFov()};let x=m.getAspectRatio();if(x!==null)p.perspective.aspectRatio=x}else p.orthographic={znear:m.getZNear(),zfar:m.getZFar(),xmag:m.getXMag(),ymag:m.getYMag()};return a.cameraIndexMap.set(m,g),p}),r.nodes=i.listNodes().map((m,g)=>{let p=a.createPropertyDef(m);if(!pt.eq(m.getTranslation(),[0,0,0]))p.translation=m.getTranslation();if(!pt.eq(m.getRotation(),[0,0,0,1]))p.rotation=m.getRotation();if(!pt.eq(m.getScale(),[1,1,1]))p.scale=m.getScale();if(m.getWeights().length)p.weights=m.getWeights();return a.nodeIndexMap.set(m,g),p}),r.skins=i.listSkins().map((m,g)=>{let p=a.createPropertyDef(m),x=m.getInverseBindMatrices();if(x)p.inverseBindMatrices=a.accessorIndexMap.get(x);let _=m.getSkeleton();if(_)p.skeleton=a.nodeIndexMap.get(_);return p.joints=m.listJoints().map((y)=>a.nodeIndexMap.get(y)),a.skinIndexMap.set(m,g),p}),i.listNodes().forEach((m,g)=>{let p=r.nodes[g],x=m.getMesh();if(x)p.mesh=a.meshIndexMap.get(x);let _=m.getCamera();if(_)p.camera=a.cameraIndexMap.get(_);let y=m.getSkin();if(y)p.skin=a.skinIndexMap.get(y);if(m.listChildren().length>0)p.children=m.listChildren().map((v)=>a.nodeIndexMap.get(v))}),r.animations=i.listAnimations().map((m,g)=>{let p=a.createPropertyDef(m),x=new Map;return p.samplers=m.listSamplers().map((_,y)=>{let v=a.createPropertyDef(_);return v.input=a.accessorIndexMap.get(_.getInput()),v.output=a.accessorIndexMap.get(_.getOutput()),v.interpolation=_.getInterpolation(),x.set(_,y),v}),p.channels=m.listChannels().map((_)=>{let y=a.createPropertyDef(_);return y.sampler=x.get(_.getSampler()),y.target={node:a.nodeIndexMap.get(_.getTargetNode()),path:_.getTargetPath()},y}),a.animationIndexMap.set(m,g),p}),r.scenes=i.listScenes().map((m,g)=>{let p=a.createPropertyDef(m);return p.nodes=m.listChildren().map((x)=>a.nodeIndexMap.get(x)),a.sceneIndexMap.set(m,g),p});let b=i.getDefaultScene();if(b)r.scene=i.listScenes().indexOf(b);return r.extensionsUsed=l.map((m)=>m.extensionName),r.extensionsRequired=u.map((m)=>m.extensionName),l.forEach((m)=>m.write(a)),bF(r),s}},xF=class{_logger=ka.DEFAULT_INSTANCE;_extensions=new Set;_dependencies={};_vertexLayout="interleaved";_strictResources=!0;lastReadBytes=0;lastWriteBytes=0;setLogger(e){return this._logger=e,this}registerExtensions(e){for(let t of e)this._extensions.add(t),t.register();return this}registerDependencies(e){return Object.assign(this._dependencies,e),this}setVertexLayout(e){return this._vertexLayout=e,this}setStrictResources(e){return this._strictResources=e,this}async read(e){return await this.readJSON(await this.readAsJSON(e))}async readAsJSON(e){let t=await this.readURI(e,"view");this.lastReadBytes=t.byteLength;let n=Uw(t)?this._binaryToJSON(t):{json:JSON.parse(Je.decodeText(t)),resources:{}};return await this._readResourcesExternal(n,this.dirname(e)),this._readResourcesInternal(n),n}async readJSON(e){return e=this._copyJSON(e),this._readResourcesInternal(e),cF.read(e,{extensions:Array.from(this._extensions),dependencies:this._dependencies,logger:this._logger})}async binaryToJSON(e){let t=this._binaryToJSON(Je.assertView(e));this._readResourcesInternal(t);let n=t.json;if(n.buffers&&n.buffers.some((i)=>yF(t,i)))throw Error("Cannot resolve external buffers with binaryToJSON().");else if(n.images&&n.images.some((i)=>_F(t,i)))throw Error("Cannot resolve external images with binaryToJSON().");return t}async readBinary(e){return this.readJSON(await this.binaryToJSON(Je.assertView(e)))}async writeJSON(e,t={}){if(t.format==="GLB"&&e.getRoot().listBuffers().length>1)throw Error("GLB must have 0–1 buffers.");return gF.write(e,{format:t.format||"GLTF",basename:t.basename||"",logger:this._logger,vertexLayout:this._vertexLayout,dependencies:{...this._dependencies},extensions:Array.from(this._extensions)})}async writeBinary(e){let{json:t,resources:n}=await this.writeJSON(e,{format:"GLB"}),i=new Uint32Array([1179937895,2,12]),r=JSON.stringify(t),s=Je.pad(Je.encodeText(r),32),a=Je.toView(new Uint32Array([s.byteLength,1313821514])),o=Je.concat([a,s]);i[i.length-1]+=o.byteLength;let c=Object.values(n)[0];if(!c||!c.byteLength)return Je.concat([Je.toView(i),o]);let l=Je.pad(c,0),u=Je.toView(new Uint32Array([l.byteLength,5130562])),d=Je.concat([u,l]);return i[i.length-1]+=d.byteLength,Je.concat([Je.toView(i),o,d])}async _readResourcesExternal(e,t){let n=e.json.images||[],i=e.json.buffers||[],r=[...n,...i].map(async(s)=>{let a=s.uri;if(!a||a.match(/data:/))return Promise.resolve();try{e.resources[a]=await this.readURI(this.resolve(t,a),"view"),this.lastReadBytes+=e.resources[a].byteLength}catch(o){if(!this._strictResources&&n.includes(s))this._logger.warn(`Failed to load image URI, "${a}". ${o}`),e.resources[a]=null;else throw o}});await Promise.all(r)}_readResourcesInternal(e){function t(n){if(!n.uri)return;if(n.uri in e.resources){Je.assertView(e.resources[n.uri]);return}if(n.uri.match(/data:/)){let i=`__${$w()}.${Pa.extension(n.uri)}`;e.resources[i]=Je.createBufferFromDataURI(n.uri),n.uri=i}}(e.json.images||[]).forEach((n)=>{if(n.bufferView===void 0&&n.uri===void 0)throw Error("Missing resource URI or buffer view.");t(n)}),(e.json.buffers||[]).forEach(t)}_copyJSON(e){let{images:t,buffers:n}=e.json;if(e={json:{...e.json},resources:{...e.resources}},t)e.json.images=t.map((i)=>({...i}));if(n)e.json.buffers=n.map((i)=>({...i}));return e}_binaryToJSON(e){if(!Uw(e))throw Error("Invalid glTF 2.0 binary.");let t=new Uint32Array(e.buffer,e.byteOffset+12,2);if(t[1]!==1313821514)throw Error("Missing required GLB JSON chunk.");let n=20,i=t[0],r=Je.decodeText(Je.toView(e,n,i)),s=JSON.parse(r),a=n+i;if(e.byteLength<=a)return{json:s,resources:{}};let o=new Uint32Array(e.buffer,e.byteOffset+a,2);if(o[1]!==5130562)return{json:s,resources:{}};let c=o[0],l=Je.toView(e,a+8,c);return{json:s,resources:{[Cs]:l}}}},Jw;var wl=mt(()=>{Pw();te=function(e){return e.ACCESSOR="Accessor",e.ANIMATION="Animation",e.ANIMATION_CHANNEL="AnimationChannel",e.ANIMATION_SAMPLER="AnimationSampler",e.BUFFER="Buffer",e.CAMERA="Camera",e.MATERIAL="Material",e.MESH="Mesh",e.PRIMITIVE="Primitive",e.PRIMITIVE_TARGET="PrimitiveTarget",e.NODE="Node",e.ROOT="Root",e.SCENE="Scene",e.SKIN="Skin",e.TEXTURE="Texture",e.TEXTURE_INFO="TextureInfo",e}({}),F8=function(e){return e.ARRAY_BUFFER="ARRAY_BUFFER",e.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",e.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",e.OTHER="OTHER",e.SPARSE="SPARSE",e}({}),Ai=function(e){return e[e.R=4096]="R",e[e.G=256]="G",e[e.B=16]="B",e[e.A=1]="A",e}({}),zw=function(e){return e.GLTF="GLTF",e.GLB="GLB",e}({}),U8=class extends Float32Array{constructor(){super();throw Error("Unsupported typed array instantiation.")}},Tl={"5120":Int8Array,"5121":Uint8Array,"5122":Int16Array,"5123":Uint16Array,"5125":Uint32Array,"5131":typeof Float16Array<"u"?Float16Array:U8,"5126":Float32Array,"5130":Float64Array},Gi=class{static impls={"image/jpeg":new B8,"image/png":new z8};static registerFormat(e,t){this.impls[e]=t}static getMimeType(e){for(let t in this.impls)if(this.impls[t].match(e))return t;return null}static getSize(e,t){if(!this.impls[t])return null;return this.impls[t].getSize(e)}static getChannels(e,t){if(!this.impls[t])return null;return this.impls[t].getChannels(e)}static getVRAMByteLength(e,t){if(!this.impls[t])return null;if(this.impls[t].getVRAMByteLength)return this.impls[t].getVRAMByteLength(e);let n=0,i=4,r=this.getSize(e,t);if(!r)return null;while(r[0]>1||r[1]>1)n+=r[0]*r[1]*i,r[0]=Math.max(Math.floor(r[0]/2),1),r[1]=Math.max(Math.floor(r[1]/2),1);return n+=4,n}static mimeTypeToExtension(e){if(e==="image/jpeg")return"jpg";return e.split("/").pop()}static extensionToMimeType(e){if(e==="jpg")return"image/jpeg";if(!e)return"";return`image/${e}`}};Ng=typeof Float32Array<"u"?Float32Array:Array;Math.PI/180;180/Math.PI;(function(){var e=j8();return function(t,n,i,r,s,a){var o,c;if(!n)n=3;if(!i)i=0;if(r)c=Math.min(r*n+i,t.length);else c=t.length;for(o=i;o<c;o+=n)e[0]=t[o],e[1]=t[o+1],e[2]=t[o+2],s(e,e,a),t[o]=e[0],t[o+1]=e[1],t[o+2]=e[2];return t}})();Cg=class{static DEFAULT_INIT={};static PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;static dirname(e){let t=e.lastIndexOf("/");if(t===-1)return"./";return e.substring(0,t+1)}static basename(e){return Pa.basename(new URL(e,Ow).pathname)}static extension(e){return Pa.extension(new URL(e,Ow).pathname)}static resolve(e,t){if(!this.isRelativePath(t))return t;let n=e.split("/"),i=t.split("/");n.pop();for(let r=0;r<i.length;r++){if(i[r]===".")continue;if(i[r]==="..")n.pop();else n.push(i[r])}return n.join("/")}static isAbsoluteURL(e){return this.PROTOCOL_REGEXP.test(e)}static isRelativePath(e){return!/^(?:[a-zA-Z]+:)?\//.test(e)}};$8=function(e){return e[e.SILENT=4]="SILENT",e[e.ERROR=3]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=1]="INFO",e[e.DEBUG=0]="DEBUG",e}({}),ka=class e{verbosity;static Verbosity=$8;static DEFAULT_INSTANCE=new e(1);constructor(t){this.verbosity=t}debug(t){if(this.verbosity<=0)console.debug(t)}info(t){if(this.verbosity<=1)console.info(t)}warn(t){if(this.verbosity<=2)console.warn(t)}error(t){if(this.verbosity<=3)console.error(t)}};Dw=new Set,iF=new Set,kg=class extends Nw{constructor(e,t=""){super(e);this[At].name=t,this.init(),this.dispatchEvent({type:"create"})}getGraph(){return this.graph}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}set(e,t){if(Array.isArray(t))t=t.slice();return super.set(e,t)}getName(){return this.get("name")}setName(e){return this.set("name",e)}getExtras(){return this.get("extras")}setExtras(e){return this.set("extras",e)}clone(){return new this.constructor(this.graph).copy(this,Ns)}copy(e,t=Ns){for(let n in this[At]){let i=this[At][n];if(i instanceof Rs){if(!this[Ms].has(n))i.dispose()}else if(i instanceof bn||i instanceof It)for(let r of i.values())r.dispose();else if(i instanceof dn)for(let r of i.values())r.dispose()}for(let n in e[At]){let i=this[At][n],r=e[At][n];if(r instanceof Rs)if(this[Ms].has(n))i.getChild().copy(t(r.getChild()),t);else this.setRef(n,t(r.getChild()),r.getAttributes());else if(r instanceof It||r instanceof bn)for(let s of r.values())this.addRef(n,t(s.getChild()),s.getAttributes());else if(r instanceof dn)for(let s of r.keys()){let a=r.get(s);this.setRefMap(n,s,t(a.getChild()),a.getAttributes())}else if(Na(r))this[At][n]=JSON.parse(JSON.stringify(r));else if(Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r))this[At][n]=r.slice();else this[At][n]=r}return this}equals(e,t=iF){if(this===e)return!0;if(this.propertyType!==e.propertyType)return!1;for(let n in this[At]){if(t.has(n))continue;let i=this[At][n],r=e[At][n];if(i instanceof Rs||r instanceof Rs){if(!J8(i,r))return!1}else if(i instanceof It||r instanceof It||i instanceof bn||r instanceof bn){if(!Z8(i,r))return!1}else if(i instanceof dn||r instanceof dn){if(!Y8(i,r))return!1}else if(Na(i)||Na(r)){if(!Gw(i,r))return!1}else if(Qd(i)||Qd(r)){if(!Hw(i,r))return!1}else if(i!==r)return!1}return!0}detach(){return this.graph.disconnectParents(this,(e)=>e.propertyType!=="Root"),this}listParents(){return this.graph.listParents(this)}},Gn=class extends kg{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new dn})}getExtension(e){return this.getRefMap("extensions",e)}setExtension(e,t){if(t)t._validateParent(this);return this.setRefMap("extensions",e,t)}listExtensions(){return this.listRefMapValues("extensions")}},Be=class e extends Gn{static Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};static ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126,FLOAT16:5131,FLOAT64:5130};init(){this.propertyType="Accessor"}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:e.Type.SCALAR,componentType:e.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(t){switch(t){case e.Type.SCALAR:return 1;case e.Type.VEC2:return 2;case e.Type.VEC3:return 3;case e.Type.VEC4:return 4;case e.Type.MAT2:return 4;case e.Type.MAT3:return 9;case e.Type.MAT4:return 16;default:throw Error("Unexpected type: "+t)}}static getComponentSize(t){switch(t){case e.ComponentType.BYTE:case e.ComponentType.UNSIGNED_BYTE:return 1;case e.ComponentType.SHORT:case e.ComponentType.UNSIGNED_SHORT:return 2;case e.ComponentType.UNSIGNED_INT:case e.ComponentType.FLOAT:return 4;case e.ComponentType.FLOAT16:return 2;case e.ComponentType.FLOAT64:return 8;default:throw Error("Unexpected component type: "+t)}}getMinNormalized(t){let n=this.getNormalized(),i=this.getElementSize(),r=this.getComponentType();if(this.getMin(t),n)for(let s=0;s<i;s++)t[s]=pt.decodeNormalizedInt(t[s],r);return t}getMin(t){let n=this.getArray(),i=this.getCount(),r=this.getElementSize();for(let s=0;s<r;s++)t[s]=1/0;for(let s=0;s<i*r;s+=r)for(let a=0;a<r;a++){let o=n[s+a];if(Number.isFinite(o))t[a]=Math.min(t[a],o)}return t}getMaxNormalized(t){let n=this.getNormalized(),i=this.getElementSize(),r=this.getComponentType();if(this.getMax(t),n)for(let s=0;s<i;s++)t[s]=pt.decodeNormalizedInt(t[s],r);return t}getMax(t){let n=this.get("array"),i=this.getCount(),r=this.getElementSize();for(let s=0;s<r;s++)t[s]=-1/0;for(let s=0;s<i*r;s+=r)for(let a=0;a<r;a++){let o=n[s+a];if(Number.isFinite(o))t[a]=Math.max(t[a],o)}return t}getCount(){let t=this.get("array");return t?t.length/this.getElementSize():0}getType(){return this.get("type")}setType(t){return this.set("type",t)}getElementSize(){return e.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(t){return this.set("normalized",t)}getScalar(t){let n=this.getElementSize(),i=this.getComponentType(),r=this.getArray();if(this.getNormalized())return pt.decodeNormalizedInt(r[t*n],i);return r[t*n]}setScalar(t,n){let i=this.getElementSize(),r=this.getComponentType(),s=this.getArray();if(this.getNormalized())s[t*i]=pt.encodeNormalizedInt(n,r);else s[t*i]=n;return this}getElement(t,n){let i=this.getNormalized(),r=this.getElementSize(),s=this.getComponentType(),a=this.getArray();for(let o=0;o<r;o++)if(i)n[o]=pt.decodeNormalizedInt(a[t*r+o],s);else n[o]=a[t*r+o];return n}setElement(t,n){let i=this.getNormalized(),r=this.getElementSize(),s=this.getComponentType(),a=this.getArray();for(let o=0;o<r;o++)if(i)a[t*r+o]=pt.encodeNormalizedInt(n[o],s);else a[t*r+o]=n[o];return this}getSparse(){return this.get("sparse")}setSparse(t){return this.set("sparse",t)}getBuffer(){return this.getRef("buffer")}setBuffer(t){return this.setRef("buffer",t)}getArray(){return this.get("array")}setArray(t){return this.set("componentType",t?rF(t):e.ComponentType.FLOAT),this.set("array",t),this}getByteLength(){let t=this.get("array");return t?t.byteLength:0}};Kw=class extends Gn{init(){this.propertyType="Animation"}getDefaults(){return Object.assign(super.getDefaults(),{channels:new It,samplers:new It})}addChannel(e){return this.addRef("channels",e)}removeChannel(e){return this.removeRef("channels",e)}listChannels(){return this.listRefs("channels")}addSampler(e){return this.addRef("samplers",e)}removeSampler(e){return this.removeRef("samplers",e)}listSamplers(){return this.listRefs("samplers")}},Da=class extends Gn{static TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};init(){this.propertyType="AnimationChannel"}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(e){return this.set("targetPath",e)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(e){return this.setRef("targetNode",e)}getSampler(){return this.getRef("sampler")}setSampler(e){return this.setRef("sampler",e)}},Al=class e extends Gn{static Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};init(){this.propertyType="AnimationSampler"}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:e.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(t){return this.set("interpolation",t)}getInput(){return this.getRef("input")}setInput(t){return this.setRef("input",t,{usage:"OTHER"})}getOutput(){return this.getRef("output")}setOutput(t){return this.setRef("output",t,{usage:"OTHER"})}},Ww=class extends Gn{init(){this.propertyType="Buffer"}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(e){return this.set("uri",e)}},ef=class e extends Gn{static Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};init(){this.propertyType="Camera"}getDefaults(){return Object.assign(super.getDefaults(),{type:e.Type.PERSPECTIVE,znear:0.1,zfar:100,aspectRatio:null,yfov:Math.PI*2*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(t){return this.set("type",t)}getZNear(){return this.get("znear")}setZNear(t){return this.set("znear",t)}getZFar(){return this.get("zfar")}setZFar(t){return this.set("zfar",t)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(t){return this.set("aspectRatio",t)}getYFov(){return this.get("yfov")}setYFov(t){return this.set("yfov",t)}getXMag(){return this.get("xmag")}setXMag(t){return this.set("xmag",t)}getYMag(){return this.get("ymag")}setYMag(t){return this.set("ymag",t)}},nt=class extends kg{static EXTENSION_NAME;_validateParent(e){if(!this.parentTypes.includes(e.propertyType))throw Error(`Parent "${e.propertyType}" invalid for child "${this.propertyType}".`)}},wt=class e extends Gn{static WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};static MagFilter={NEAREST:9728,LINEAR:9729};static MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};init(){this.propertyType="TextureInfo"}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:e.WrapMode.REPEAT,wrapT:e.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(t){return this.set("texCoord",t)}getMagFilter(){return this.get("magFilter")}setMagFilter(t){return this.set("magFilter",t)}getMinFilter(){return this.get("minFilter")}setMinFilter(t){return this.set("minFilter",t)}getWrapS(){return this.get("wrapS")}setWrapS(t){return this.set("wrapS",t)}getWrapT(){return this.get("wrapT")}setWrapT(t){return this.set("wrapT",t)}},{R:Xd,G:qd,B:Jd,A:sF}=Ai,Oa=class e extends Gn{static AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};init(){this.propertyType="Material"}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:e.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new wt(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new wt(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new wt(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new wt(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new wt(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(t){return this.set("doubleSided",t)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(t){let n=this.get("baseColorFactor").slice();return n[3]=t,this.set("baseColorFactor",n)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(t){return this.set("alphaMode",t)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(t){return this.set("alphaCutoff",t)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(t){return this.set("baseColorFactor",t)}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(t){return this.setRef("baseColorTexture",t,{channels:Xd|qd|Jd|sF,isColor:!0})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(t){return this.set("emissiveFactor",t)}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(t){return this.setRef("emissiveTexture",t,{channels:Xd|qd|Jd,isColor:!0})}getNormalScale(){return this.get("normalScale")}setNormalScale(t){return this.set("normalScale",t)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(t){return this.setRef("normalTexture",t,{channels:Xd|qd|Jd})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(t){return this.set("occlusionStrength",t)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(t){return this.setRef("occlusionTexture",t,{channels:Xd})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(t){return this.set("roughnessFactor",t)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(t){return this.set("metallicFactor",t)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(t){return this.setRef("metallicRoughnessTexture",t,{channels:qd|Jd})}},Dg=class extends Gn{init(){this.propertyType="Mesh"}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:new It})}addPrimitive(e){return this.addRef("primitives",e)}removePrimitive(e){return this.removeRef("primitives",e)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(e){return this.set("weights",e)}},tf=class extends Gn{init(){this.propertyType="Node"}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:new It})}copy(e,t=Ns){if(t===Ns)throw Error("Node cannot be copied.");return super.copy(e,t)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(e){return this.set("translation",e)}setRotation(e){return this.set("rotation",e)}setScale(e){return this.set("scale",e)}getMatrix(){return pt.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(e){let t=this.get("translation").slice(),n=this.get("rotation").slice(),i=this.get("scale").slice();return pt.decompose(e,t,n,i),this.set("translation",t).set("rotation",n).set("scale",i)}getWorldTranslation(){let e=[0,0,0];return pt.decompose(this.getWorldMatrix(),e,[0,0,0,1],[1,1,1]),e}getWorldRotation(){let e=[0,0,0,1];return pt.decompose(this.getWorldMatrix(),[0,0,0],e,[1,1,1]),e}getWorldScale(){let e=[1,1,1];return pt.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],e),e}getWorldMatrix(){let e=[];for(let i=this;i!=null;i=i.getParentNode())e.push(i);let t,n=e.pop().getMatrix();while(t=e.pop())W8(n,n,t.getMatrix());return n}addChild(e){let t=e.getParentNode();if(t)t.removeChild(e);for(let n of e.listParents())if(n.propertyType==="Scene")n.removeChild(e);return this.addRef("children",e)}removeChild(e){return this.removeRef("children",e)}listChildren(){return this.listRefs("children")}getParentNode(){for(let e of this.listParents())if(e.propertyType==="Node")return e;return null}getMesh(){return this.getRef("mesh")}setMesh(e){return this.setRef("mesh",e)}getCamera(){return this.getRef("camera")}setCamera(e){return this.setRef("camera",e)}getSkin(){return this.getRef("skin")}setSkin(e){return this.setRef("skin",e)}getWeights(){return this.get("weights")}setWeights(e){return this.set("weights",e)}traverse(e){e(this);for(let t of this.listChildren())t.traverse(e);return this}},Jn=class e extends Gn{static Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};init(){this.propertyType="Primitive"}getDefaults(){return Object.assign(super.getDefaults(),{mode:e.Mode.TRIANGLES,material:null,indices:null,attributes:new dn,targets:new It})}getIndices(){return this.getRef("indices")}setIndices(t){return this.setRef("indices",t,{usage:"ELEMENT_ARRAY_BUFFER"})}getAttribute(t){return this.getRefMap("attributes",t)}setAttribute(t,n){return this.setRefMap("attributes",t,n,{usage:"ARRAY_BUFFER"})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(t){return this.setRef("material",t)}getMode(){return this.get("mode")}setMode(t){return this.set("mode",t)}listTargets(){return this.listRefs("targets")}addTarget(t){return this.addRef("targets",t)}removeTarget(t){return this.removeRef("targets",t)}},Lg=class extends kg{init(){this.propertyType="PrimitiveTarget"}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new dn})}getAttribute(e){return this.getRefMap("attributes",e)}setAttribute(e,t){return this.setRefMap("attributes",e,t,{usage:"ARRAY_BUFFER"})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}},nf=class extends Gn{init(){this.propertyType="Scene"}getDefaults(){return Object.assign(super.getDefaults(),{children:new It})}copy(e,t=Ns){if(t===Ns)throw Error("Scene cannot be copied.");return super.copy(e,t)}addChild(e){let t=e.getParentNode();if(t)t.removeChild(e);return this.addRef("children",e)}removeChild(e){return this.removeRef("children",e)}listChildren(){return this.listRefs("children")}traverse(e){for(let t of this.listChildren())t.traverse(e);return this}},Xw=class extends Gn{init(){this.propertyType="Skin"}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:new It})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(e){return this.setRef("skeleton",e)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(e){return this.setRef("inverseBindMatrices",e,{usage:"INVERSE_BIND_MATRICES"})}addJoint(e){return this.addRef("joints",e)}removeJoint(e){return this.removeRef("joints",e)}listJoints(){return this.listRefs("joints")}},Xo=class extends Gn{init(){this.propertyType="Texture"}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||Gi.extensionToMimeType(Pa.extension(this.get("uri")))}setMimeType(e){return this.set("mimeType",e)}getURI(){return this.get("uri")}setURI(e){this.set("uri",e);let t=Gi.extensionToMimeType(Pa.extension(e));if(t)this.set("mimeType",t);return this}getImage(){return this.get("image")}setImage(e){return this.set("image",Je.assertView(e))}getSize(){let e=this.get("image");if(!e)return null;return Gi.getSize(e,this.getMimeType())}},Ps=class extends Gn{_extensions=new Set;init(){this.propertyType="Root"}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${Bw}`,version:"2.0"},defaultScene:null,accessors:new It,animations:new It,buffers:new It,cameras:new It,materials:new It,meshes:new It,nodes:new It,scenes:new It,skins:new It,textures:new It})}constructor(e){super(e);e.addEventListener("node:create",(t)=>{this._addChildOfRoot(t.target)})}clone(){throw Error("Root cannot be cloned.")}copy(e,t=Ns){if(t===Ns)throw Error("Root cannot be copied.");this.set("asset",{...e.get("asset")}),this.setName(e.getName()),this.setExtras({...e.getExtras()}),this.setDefaultScene(e.getDefaultScene()?t(e.getDefaultScene()):null);for(let n of e.listRefMapKeys("extensions")){let i=e.getExtension(n);this.setExtension(n,t(i))}return this}_addChildOfRoot(e){if(e instanceof nf)this.addRef("scenes",e);else if(e instanceof tf)this.addRef("nodes",e);else if(e instanceof ef)this.addRef("cameras",e);else if(e instanceof Xw)this.addRef("skins",e);else if(e instanceof Dg)this.addRef("meshes",e);else if(e instanceof Oa)this.addRef("materials",e);else if(e instanceof Xo)this.addRef("textures",e);else if(e instanceof Kw)this.addRef("animations",e);else if(e instanceof Be)this.addRef("accessors",e);else if(e instanceof Ww)this.addRef("buffers",e);return this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this._extensions)}listExtensionsRequired(){return this.listExtensionsUsed().filter((e)=>e.isRequired())}_enableExtension(e){return this._extensions.add(e),this}_disableExtension(e){return this._extensions.delete(e),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(e){return this.setRef("defaultScene",e)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}},rf=class e{_graph=new Rg;_root=new Ps(this._graph);_logger=ka.DEFAULT_INSTANCE;static _GRAPH_DOCUMENTS=new WeakMap;static fromGraph(t){return e._GRAPH_DOCUMENTS.get(t)||null}constructor(){e._GRAPH_DOCUMENTS.set(this._graph,this)}getRoot(){return this._root}getGraph(){return this._graph}getLogger(){return this._logger}setLogger(t){return this._logger=t,this}clone(){throw Error("Use 'cloneDocument(source)' from '@gltf-transform/functions'.")}merge(t){throw Error("Use 'mergeDocuments(target, source)' from '@gltf-transform/functions'.")}async transform(...t){let n=t.map((i)=>i.name);for(let i of t)await i(this,{stack:n});return this}hasExtension(t){return this.getRoot().listExtensionsUsed().some((n)=>n.extensionName===t)}createExtension(t){let n=t.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find((i)=>i.extensionName===n)||new t(this)}disposeExtension(t){let n=this.getRoot().listExtensionsUsed().find((i)=>i.extensionName===t);if(n)n.dispose()}createScene(t=""){return new nf(this._graph,t)}createNode(t=""){return new tf(this._graph,t)}createCamera(t=""){return new ef(this._graph,t)}createSkin(t=""){return new Xw(this._graph,t)}createMesh(t=""){return new Dg(this._graph,t)}createPrimitive(){return new Jn(this._graph)}createPrimitiveTarget(t=""){return new Lg(this._graph,t)}createMaterial(t=""){return new Oa(this._graph,t)}createTexture(t=""){return new Xo(this._graph,t)}createAnimation(t=""){return new Kw(this._graph,t)}createAnimationChannel(t=""){return new Da(this._graph,t)}createAnimationSampler(t=""){return new Al(this._graph,t)}createAccessor(t="",n=null){if(!n)n=this.getRoot().listBuffers()[0];return new Be(this._graph,t).setBuffer(n)}createBuffer(t=""){return new Ww(this._graph,t)}},Lw={logger:ka.DEFAULT_INSTANCE,extensions:[],dependencies:{}},oF=new Set(["Buffer","Texture","Material","Mesh","Primitive","Node","Scene"]);qw=function(e){return e[e.ARRAY_BUFFER=34962]="ARRAY_BUFFER",e[e.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",e}(qw||{}),Is=class{_doc;jsonDoc;options;static BufferViewTarget=qw;static BufferViewUsage=F8;static USAGE_TO_TARGET={["ARRAY_BUFFER"]:34962,["ELEMENT_ARRAY_BUFFER"]:34963};accessorIndexMap=new Map;animationIndexMap=new Map;bufferIndexMap=new Map;cameraIndexMap=new Map;skinIndexMap=new Map;materialIndexMap=new Map;meshIndexMap=new Map;nodeIndexMap=new Map;imageIndexMap=new Map;textureDefIndexMap=new Map;textureInfoDefMap=new Map;samplerDefIndexMap=new Map;sceneIndexMap=new Map;imageBufferViews=[];otherBufferViews=new Map;otherBufferViewsIndexMap=new Map;extensionData={};bufferURIGenerator;imageURIGenerator;logger;_accessorUsageMap=new Map;accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]);accessorParents=new Map;constructor(e,t,n){this._doc=e,this.jsonDoc=t,this.options=n;let i=e.getRoot(),r=i.listBuffers().length,s=i.listTextures().length;this.bufferURIGenerator=new Fw(r>1,()=>n.basename||"buffer"),this.imageURIGenerator=new Fw(s>1,(a)=>dF(e,a)||n.basename||"texture"),this.logger=e.getLogger()}createTextureInfoDef(e,t){let n={magFilter:t.getMagFilter()||void 0,minFilter:t.getMinFilter()||void 0,wrapS:t.getWrapS(),wrapT:t.getWrapT()},i=JSON.stringify(n);if(!this.samplerDefIndexMap.has(i))this.samplerDefIndexMap.set(i,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(n);let r={source:this.imageIndexMap.get(e),sampler:this.samplerDefIndexMap.get(i)},s=JSON.stringify(r);if(!this.textureDefIndexMap.has(s))this.textureDefIndexMap.set(s,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push(r);let a={index:this.textureDefIndexMap.get(s)};if(t.getTexCoord()!==0)a.texCoord=t.getTexCoord();if(Object.keys(t.getExtras()).length>0)a.extras=t.getExtras();return this.textureInfoDefMap.set(t,a),a}createPropertyDef(e){let t={};if(e.getName())t.name=e.getName();if(Object.keys(e.getExtras()).length>0)t.extras=e.getExtras();return t}createAccessorDef(e){let t=this.createPropertyDef(e);if(t.type=e.getType(),t.componentType=e.getComponentType(),t.count=e.getCount(),this._doc.getGraph().listParentEdges(e).some((n)=>n.getName()==="attributes"&&n.getAttributes().key==="POSITION"||n.getName()==="input"))t.max=e.getMax([]).map(Math.fround),t.min=e.getMin([]).map(Math.fround);if(e.getNormalized())t.normalized=e.getNormalized();return t}createImageData(e,t,n){if(this.options.format==="GLB")this.imageBufferViews.push(t),e.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:t.byteLength});else{let i=Gi.mimeTypeToExtension(n.getMimeType());e.uri=this.imageURIGenerator.createURI(n,i),this.assignResourceURI(e.uri,t,!1)}}assignResourceURI(e,t,n){let i=this.jsonDoc.resources;if(!(e in i)){i[e]=t;return}if(t===i[e]){this.logger.warn(`Duplicate resource URI, "${e}".`);return}let r=`Resource URI "${e}" already assigned to different data.`;if(!n){this.logger.warn(r);return}throw Error(r)}getAccessorUsage(e){let t=this._accessorUsageMap.get(e);if(t)return t;if(e.getSparse())return"SPARSE";for(let n of this._doc.getGraph().listParentEdges(e)){let{usage:i}=n.getAttributes();if(i)return i;if(n.getParent().propertyType!=="Root")this.logger.warn(`Missing attribute ".usage" on edge, "${n.getName()}".`)}return"OTHER"}addAccessorToUsageGroup(e,t){let n=this._accessorUsageMap.get(e);if(n&&n!==t)throw Error(`Accessor with usage "${n}" cannot be reused as "${t}".`);return this._accessorUsageMap.set(e,t),this}};({BufferViewUsage:Zd}=Is),{UNSIGNED_INT:fF,UNSIGNED_SHORT:hF,UNSIGNED_BYTE:pF}=Be.ComponentType,mF=new Set(["Accessor","Buffer","Material","Mesh"]);Jw=class extends xF{_fetchConfig;constructor(e=Cg.DEFAULT_INIT){super();this._fetchConfig=e}async readURI(e,t){let n=await fetch(e,this._fetchConfig);switch(t){case"view":return new Uint8Array(await n.arrayBuffer());case"text":return n.text()}}resolve(e,t){return Cg.resolve(e,t)}dirname(e){return Cg.dirname(e)}}});function vF(){return{vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,levelCount:0,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null}}class qo{constructor(e,t,n,i){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,n),this._littleEndian=i,this._offset=0}_nextUint8(){let e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){let e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){let e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){let e=this._dataView.getUint32(this._offset,this._littleEndian),t=this._dataView.getUint32(this._offset+4,this._littleEndian),n=e+4294967296*t;return this._offset+=8,n}_nextInt32(){let e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){let t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t=0){let n=this._offset,i=0;while(this._dataView.getUint8(this._offset)!==t&&i<e)i++,this._offset++;if(i<e)this._offset++;return new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,i)}}function Zw(e){return new TextDecoder().decode(e)}function sf(e){let t=new Uint8Array(e.buffer,e.byteOffset,$n.length);if(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])throw Error("Missing KTX 2.0 identifier.");let n=vF(),i=17*Uint32Array.BYTES_PER_ELEMENT,r=new qo(e,$n.length,i,!0);n.vkFormat=r._nextUint32(),n.typeSize=r._nextUint32(),n.pixelWidth=r._nextUint32(),n.pixelHeight=r._nextUint32(),n.pixelDepth=r._nextUint32(),n.layerCount=r._nextUint32(),n.faceCount=r._nextUint32(),n.levelCount=r._nextUint32(),n.supercompressionScheme=r._nextUint32();let s=r._nextUint32(),a=r._nextUint32(),o=r._nextUint32(),c=r._nextUint32(),l=r._nextUint64(),u=r._nextUint64(),d=Math.max(n.levelCount,1)*3*8,f=new qo(e,$n.length+i,d,!0);for(let ie=0,ce=Math.max(n.levelCount,1);ie<ce;ie++)n.levels.push({levelData:new Uint8Array(e.buffer,e.byteOffset+f._nextUint64(),f._nextUint64()),uncompressedByteLength:f._nextUint64()});let h=new qo(e,s,a,!0);h._skip(4);let b=h._nextUint16(),m=h._nextUint16(),g=h._nextUint16(),p=h._nextUint16(),x=h._nextUint8(),_=h._nextUint8(),y=h._nextUint8(),v=h._nextUint8(),T=[h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8()],A=[h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8()],w={vendorId:b,descriptorType:m,versionNumber:g,colorModel:x,colorPrimaries:_,transferFunction:y,flags:v,texelBlockDimension:T,bytesPlane:A,samples:[]},P=6,S=4,I=(p/4-P)/S;for(let ie=0;ie<I;ie++){let ce={bitOffset:h._nextUint16(),bitLength:h._nextUint8(),channelType:h._nextUint8(),samplePosition:[h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};if(ce.channelType&64)ce.sampleLower=h._nextInt32(),ce.sampleUpper=h._nextInt32();else ce.sampleLower=h._nextUint32(),ce.sampleUpper=h._nextUint32();w.samples[ie]=ce}n.dataFormatDescriptor.length=0,n.dataFormatDescriptor.push(w);let U=new qo(e,o,c,!0);while(U._offset<c){let ie=U._nextUint32(),ce=U._scan(ie),_e=Zw(ce);if(n.keyValue[_e]=U._nextUint8Array(ie-ce.byteLength-1),_e.match(/^ktx/i)){let Oe=Zw(n.keyValue[_e]);n.keyValue[_e]=Oe.substring(0,Oe.lastIndexOf("\x00"))}let Re=ie%4?4-ie%4:0;U._skip(Re)}if(u<=0)return n;let N=new qo(e,l,u,!0),F=N._nextUint16(),D=N._nextUint16(),O=N._nextUint32(),K=N._nextUint32(),B=N._nextUint32(),X=N._nextUint32(),q=[];for(let ie=0,ce=Math.max(n.levelCount,1);ie<ce;ie++)q.push({imageFlags:N._nextUint32(),rgbSliceByteOffset:N._nextUint32(),rgbSliceByteLength:N._nextUint32(),alphaSliceByteOffset:N._nextUint32(),alphaSliceByteLength:N._nextUint32()});let le=l+N._offset,de=le+O,Me=de+K,pe=Me+B,J=new Uint8Array(e.buffer,e.byteOffset+le,O),L=new Uint8Array(e.buffer,e.byteOffset+de,K),W=new Uint8Array(e.buffer,e.byteOffset+Me,B),ne=new Uint8Array(e.buffer,e.byteOffset+pe,X);return n.globalData={endpointCount:F,selectorCount:D,imageDescs:q,endpointsData:J,selectorsData:L,tablesData:W,extendedData:ne},n}var Yw=0,Qw=163,eS=166,Fg=0,tS=123,nS=1000066000,x$,$n;var iS=mt(()=>{x$=new Uint8Array([0]),$n=[171,75,84,88,32,50,48,187,13,10,26,10]});function RF(e,t,n,i){let r=t.createFeatureID().setFeatureCount(i.featureCount);if(i.nullFeatureId!==void 0)r.setNullFeatureID(i.nullFeatureId);if(i.label!==void 0)r.setLabel(i.label);if(i.attribute!==void 0)r.setAttribute(i.attribute);let s=i.texture;if(s!==void 0){let a=IF(t,n,s);r.setTexture(a)}if(i.propertyTable!==void 0){let a=e.getRoot().getExtension(et).listPropertyTables();r.setPropertyTable(a[i.propertyTable])}return r}function IF(e,t,n){let i=e.createFeatureIDTexture(),{json:r}=t.jsonDoc;if(n.channels)i.setChannels(n.channels);if(n.index!==void 0){let s=r.textures[n.index].source;i.setTexture(t.textures[s]),t.setTextureInfo(i.getTextureInfo(),n)}return i}function CF(e,t,n){let i=e.getRoot(),r={featureCount:n.getFeatureCount()};if(n.getNullFeatureID()!=null)r.nullFeatureId=n.getNullFeatureID();if(n.getLabel())r.label=n.getLabel();if(n.getAttribute()!=null)r.attribute=n.getAttribute();if(n.getTexture()){let s=n.getTexture(),a=s.getTexture(),o=s.getTextureInfo();r.texture=t.createTextureInfoDef(a,o);let c=s.getChannels();if(!pt.eq(c,[0]))r.texture.channels=c}if(n.getPropertyTable()){let s=i.getExtension(et),a=n.getPropertyTable();r.propertyTable=s.listPropertyTables().indexOf(a)}return r}function OF(e){if(!e.extensions||!e.extensions.EXT_meshopt_compression)return!1;return!!e.extensions[Zn].fallback}function LF(e,t,n,i){let{filter:r,bits:s}=i,a={array:e.getArray(),byteStride:e.getElementSize()*e.getComponentSize(),componentType:e.getComponentType(),normalized:e.getNormalized()};if(n!=="ATTRIBUTES")return a;if(r!=="NONE"){let o=e.getNormalized()?FF(e):new Float32Array(a.array);switch(r){case"EXPONENTIAL":a.byteStride=e.getElementSize()*4,a.componentType=DF,a.normalized=!1,a.array=t.encodeFilterExp(o,e.getCount(),a.byteStride,s);break;case"OCTAHEDRAL":a.byteStride=s>8?8:4,a.componentType=s>8?aS:kF,a.normalized=!0,o=e.getElementSize()===3?BF(o):o,a.array=t.encodeFilterOct(o,e.getCount(),a.byteStride,s);break;case"QUATERNION":a.byteStride=8,a.componentType=aS,a.normalized=!0,a.array=t.encodeFilterQuat(o,e.getCount(),a.byteStride,s);break;default:throw Error("Invalid filter.")}if(a.min=e.getMin([]),a.max=e.getMax([]),e.getNormalized())a.min=a.min.map((c)=>Vg(c,e.getComponentType())),a.max=a.max.map((c)=>Vg(c,e.getComponentType()));if(a.normalized)a.min=a.min.map((c)=>oS(c,a.componentType)),a.max=a.max.map((c)=>oS(c,a.componentType))}else if(a.byteStride%4)a.array=UF(a.array,e.getElementSize()),a.byteStride=a.array.byteLength/e.getCount();return a}function FF(e){let t=e.getComponentType(),n=e.getArray(),i=new Float32Array(n.length);for(let r=0;r<n.length;r++)i[r]=Vg(n[r],t);return i}function UF(e,t){let n=Je.padNumber(e.BYTES_PER_ELEMENT*t)/e.BYTES_PER_ELEMENT,i=e.length/t,r=new e.constructor(i*n);for(let s=0;s*t<e.length;s++)for(let a=0;a<t;a++)r[s*n+a]=e[s*t+a];return r}function BF(e){let t=new Float32Array(e.length*4/3);for(let n=0,i=e.length/3;n<i;n++)t[n*4]=e[n*3],t[n*4+1]=e[n*3+1],t[n*4+2]=e[n*3+2];return t}function zF(e,t){if(t===Is.BufferViewUsage.ELEMENT_ARRAY_BUFFER)return e.listParents().some((n)=>n instanceof Jn&&n.getMode()===Jn.Mode.TRIANGLES)?"TRIANGLES":"INDICES";return"ATTRIBUTES"}function VF(e,t){let n=t.getGraph().listParentEdges(e).filter((i)=>!(i.getParent()instanceof Ps));for(let i of n){let r=i.getName(),s=i.getAttributes().key||"",a=i.getParent().propertyType===te.PRIMITIVE_TARGET;if(r==="indices")return{filter:"NONE"};if(r==="attributes"){if(s==="POSITION")return{filter:"NONE"};if(s==="TEXCOORD_0")return{filter:"NONE"};if(s.startsWith("JOINTS_"))return{filter:"NONE"};if(s.startsWith("WEIGHTS_"))return{filter:"NONE"};if(s==="NORMAL"||s==="TANGENT")return a?{filter:"NONE"}:{filter:"OCTAHEDRAL",bits:8}}if(r==="output"){let o=TS(e);if(o==="rotation")return{filter:"QUATERNION",bits:16};if(o==="translation")return{filter:"EXPONENTIAL",bits:12};if(o==="scale")return{filter:"EXPONENTIAL",bits:12};return{filter:"NONE"}}if(r==="input")return{filter:"NONE"};if(r==="inverseBindMatrices")return{filter:"NONE"}}return{filter:"NONE"}}function TS(e){for(let t of e.listParents()){if(!(t instanceof Al))continue;for(let n of t.listParents()){if(!(n instanceof Da))continue;return n.getTargetPath()}}return null}function i2(e,t,n){let i=e.createStructuralMetadata();if(n.schema!==void 0){let o=r2(e,n.schema);i.setSchema(o)}else if(n.schemaUri){let o=n.schemaUri;i.setSchemaUri(o)}let r=n.propertyTextures||[];for(let o of r){let c=l2(e,t,o);i.addPropertyTexture(c)}let s=n.propertyTables||[];for(let o of s){let c=d2(e,t,o);i.addPropertyTable(c)}let a=n.propertyAttributes||[];for(let o of a){let c=h2(e,o);i.addPropertyAttribute(c)}return i}function r2(e,t){let n=e.createSchema().setId(t.id);if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);if(t.version!==void 0)n.setVersion(t.version);let i=t.classes||{};for(let s of Object.keys(i)){let a=i[s];n.setClass(s,s2(e,a))}let r=t.enums||{};for(let s of Object.keys(r))n.setEnum(s,o2(e,r[s]));return n}function s2(e,t){let n=e.createClass();if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);let i=t.properties||{};for(let r of Object.keys(i)){let s=a2(e,i[r]);n.setProperty(r,s)}return n}function a2(e,t){let n=e.createClassProperty().setType(t.type);if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);if(t.componentType!==void 0)n.setComponentType(t.componentType);if(t.enumType!==void 0)n.setEnumType(t.enumType);if(t.array!==void 0)n.setArray(t.array);if(t.count!==void 0)n.setCount(t.count);if(t.normalized!==void 0)n.setNormalized(t.normalized);if(t.offset!==void 0)n.setOffset(t.offset);if(t.scale!==void 0)n.setScale(t.scale);if(t.max!==void 0)n.setMax(t.max);if(t.min!==void 0)n.setMin(t.min);if(t.required!==void 0)n.setRequired(t.required);if(t.noData!==void 0)n.setNoData(t.noData);if(t.default!==void 0)n.setDefault(t.default);return n}function o2(e,t){let n=e.createEnum();if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);if(t.valueType!==void 0)n.setValueType(t.valueType);let i=t.values||{};for(let r of i)n.addEnumValue(c2(e,r));return n}function c2(e,t){let n=e.createEnumValue();if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);if(t.value!==void 0)n.setValue(t.value);return n}function l2(e,t,n){let i=e.createPropertyTexture();if(i.setClass(n.class),n.name!==void 0)i.setName(n.name);let r=n.properties||{};for(let s of Object.keys(r)){let a=u2(e,t,r[s]);i.setProperty(s,a)}return i}function u2(e,t,n){let i=e.createPropertyTextureProperty(),r=t.jsonDoc.json.textures||[];if(n.channels)i.setChannels(n.channels);let s=r[n.index].source;if(s!==void 0){let a=t.textures[s];i.setTexture(a);let o=i.getTextureInfo();if(o)t.setTextureInfo(o,n)}if(n.offset!==void 0)i.setOffset(n.offset);if(n.scale!==void 0)i.setScale(n.scale);if(n.max!==void 0)i.setMax(n.max);if(n.min!==void 0)i.setMin(n.min);return i}function d2(e,t,n){let i=e.createPropertyTable().setClass(n.class).setCount(n.count);if(n.name!==void 0)i.setName(n.name);let r=n.properties||{};for(let s of Object.keys(r)){let a=f2(e,t,r[s]);i.setProperty(s,a)}return i}function f2(e,t,n){let i=e.createPropertyTableProperty(),r=Ug(t,n.values);if(i.setValues(r),n.arrayOffsets!==void 0){let s=Ug(t,n.arrayOffsets);i.setArrayOffsets(s)}if(n.stringOffsets!==void 0){let s=Ug(t,n.stringOffsets);i.setStringOffsets(s)}if(n.arrayOffsetType!==void 0)i.setArrayOffsetType(n.arrayOffsetType);if(n.stringOffsetType!==void 0)i.setStringOffsetType(n.stringOffsetType);if(n.offset!==void 0)i.setOffset(n.offset);if(n.scale!==void 0)i.setScale(n.scale);if(n.max!==void 0)i.setMax(n.max);if(n.min!==void 0)i.setMin(n.min);return i}function h2(e,t){let n=e.createPropertyAttribute();if(n.setClass(t.class),t.name!==void 0)n.setName(t.name);let i=t.properties||{};for(let r of Object.keys(i)){let s=p2(e,i[r]);n.setProperty(r,s)}return n}function p2(e,t){let n=e.createPropertyAttributeProperty();if(n.setAttribute(t.attribute),t.offset!==void 0)n.setOffset(t.offset);if(t.scale!==void 0)n.setScale(t.scale);if(t.max!==void 0)n.setMax(t.max);if(t.min!==void 0)n.setMin(t.min);return n}function m2(e,t){let n={},i=t.getSchema();if(i)n.schema=g2(i);let r=t.getSchemaUri();if(r)n.schemaUri=r;let s=t.listPropertyTables();if(s.length>0){let c=[];for(let l of s){let u=v2(e,l);c.push(u)}n.propertyTables=c}let a=t.listPropertyTextures();if(a.length>0){let c=[];for(let l of a){let u=w2(e,l);c.push(u)}n.propertyTextures=c}let o=t.listPropertyAttributes();if(o.length>0){let c=[];for(let l of o){let u=T2(l);c.push(u)}n.propertyAttributes=c}return n}function g2(e){let t={id:e.getId()},n=e.listClassKeys();if(n.length>0){t.classes={};for(let r of n){let s=b2(e.getClass(r));t.classes[r]=s}}let i=e.listEnumKeys();if(i.length>0){t.enums={};for(let r of i){let s=y2(e.getEnum(r));t.enums[r]=s}}if(e.getName())t.name=e.getName();if(e.getDescription())t.description=e.getDescription();if(e.getVersion())t.version=e.getVersion();return t}function b2(e){let t={},n=e.listPropertyKeys();if(n.length>0){t.properties={};for(let i of n){let r=e.getProperty(i);t.properties[i]=x2(r)}}if(e.getName())t.name=e.getName();if(e.getDescription())t.description=e.getDescription();return t}function x2(e){let t={type:e.getType()};if(e.getArray())t.array=e.getArray();if(e.getNormalized())t.normalized=e.getNormalized();if(e.getRequired())t.required=e.getRequired();if(e.getName())t.name=e.getName();if(e.getDescription())t.description=e.getDescription();if(e.getComponentType()!=null)t.componentType=e.getComponentType();if(e.getEnumType()!=null)t.enumType=e.getEnumType();if(e.getCount()!=null)t.count=e.getCount();if(e.getOffset()!=null)t.offset=e.getOffset();if(e.getScale()!=null)t.scale=e.getScale();if(e.getMax()!=null)t.max=e.getMax();if(e.getMin()!=null)t.min=e.getMin();if(e.getNoData()!=null)t.noData=e.getNoData();if(e.getDefault()!=null)t.default=e.getDefault();return t}function y2(e){let t={values:e.listValues().map(_2)};if(e.getName())t.name=e.getName();if(e.getDescription())t.description=e.getDescription();if(e.getValueType()!=="UINT16")t.valueType=e.getValueType();return t}function _2(e){let t={name:e.getName(),value:e.getValue()};if(e.getDescription())t.description=e.getDescription();return t}function v2(e,t){let n={class:t.getClass(),count:t.getCount()};if(t.getName())n.name=t.getName();let i=t.listPropertyKeys();if(i.length>0){n.properties={};for(let r of i){let s=E2(e,t.getProperty(r));n.properties[r]=s}}return n}function E2(e,t){let n=t.getValues(),i={values:e.otherBufferViewsIndexMap.get(n)};if(t.getArrayOffsets()){let r=t.getArrayOffsets();i.arrayOffsets=e.otherBufferViewsIndexMap.get(r)}if(t.getStringOffsets()){let r=t.getStringOffsets();i.stringOffsets=e.otherBufferViewsIndexMap.get(r)}if(t.getArrayOffsetType()!=null)i.arrayOffsetType=t.getArrayOffsetType();if(t.getStringOffsetType()!=null)i.stringOffsetType=t.getStringOffsetType();if(t.getOffset()!=null)i.offset=t.getOffset();if(t.getScale()!=null)i.scale=t.getScale();if(t.getMax()!=null)i.max=t.getMax();if(t.getMin()!=null)i.min=t.getMin();return i}function T2(e){let t={class:e.getClass()};if(e.getName())t.name=e.getName();let n=e.listPropertyKeys();if(n.length>0){t.properties={};for(let i of n){let r=A2(e.getProperty(i));t.properties[i]=r}}return t}function A2(e){let t={attribute:e.getAttribute()};if(e.getOffset()!=null)t.offset=e.getOffset();if(e.getScale()!=null)t.scale=e.getScale();if(e.getMax()!=null)t.max=e.getMax();if(e.getMin()!=null)t.min=e.getMin();return t}function w2(e,t){let n={class:t.getClass()};if(t.getName())n.name=t.getName();let i=t.listPropertyKeys();if(i.length>0){n.properties={};for(let r of i){let s=S2(e,t.getProperty(r));n.properties[r]=s}}return n}function S2(e,t){let n=t.getTexture(),i=t.getTextureInfo(),r=t.getChannels(),s=e.createTextureInfoDef(n,i);if(!pt.eq(r,[0]))s.channels=r;if(t.getOffset()!=null)s.offset=t.getOffset();if(t.getScale()!=null)s.scale=t.getScale();if(t.getMax()!=null)s.max=t.getMax();if(t.getMin()!=null)s.min=t.getMin();return s}function Ug(e,t){let n=e.jsonDoc,i=n.json.buffers||[],r=(n.json.bufferViews||[])[t],s=i[r.buffer],a=s.uri?n.resources[s.uri]:n.resources[Cs],o=r.byteOffset||0,c=r.byteLength;return a.slice(o,o+c)}function M2(e,t){let n=e.getRoot().listBuffers()[0],i=t.otherBufferViews.get(n);if(!i)i=[],t.otherBufferViews.set(n,i);return i}function lS(e,t){if(e.byteLength<4+t)return null;let n=e.getUint32(t);if(e.byteLength<n+t||n<8)return null;return{type:Je.decodeText(new Uint8Array(e.buffer,e.byteOffset+t+4,4)),start:t+8,end:t+n}}function P2(e,t){let n=new xn.DecoderBuffer;try{if(n.Init(t,t.length),e.GetEncodedGeometryType(n)!==xn.TRIANGULAR_MESH)throw Error(`[${tn}] Unknown geometry type.`);let i=new xn.Mesh;if(!e.DecodeBufferToMesh(n,i).ok()||i.ptr===0)throw Error(`[${tn}] Decoding failure.`);return i}finally{xn.destroy(n)}}function O2(e,t){let n=t.num_faces()*3,i,r;if(t.num_points()<=65534){let s=n*Uint16Array.BYTES_PER_ELEMENT;i=xn._malloc(s),e.GetTrianglesUInt16Array(t,s,i),r=new Uint16Array(xn.HEAPU16.buffer,i,n).slice()}else{let s=n*Uint32Array.BYTES_PER_ELEMENT;i=xn._malloc(s),e.GetTrianglesUInt32Array(t,s,i),r=new Uint32Array(xn.HEAPU32.buffer,i,n).slice()}return xn._free(i),r}function k2(e,t,n,i){let r=MS[i.componentType],s=SS[i.componentType],a=n.num_components(),o=t.num_points()*a,c=o*s.BYTES_PER_ELEMENT,l=xn._malloc(c);e.GetAttributeDataArrayForAllPoints(t,n,r,c,l);let u=new s(xn.HEAPF32.buffer,l,o).slice();return xn._free(l),u}function D2(e){xn=e,SS={[Be.ComponentType.FLOAT]:Float32Array,[Be.ComponentType.UNSIGNED_INT]:Uint32Array,[Be.ComponentType.UNSIGNED_SHORT]:Uint16Array,[Be.ComponentType.UNSIGNED_BYTE]:Uint8Array,[Be.ComponentType.SHORT]:Int16Array,[Be.ComponentType.BYTE]:Int8Array},MS={[Be.ComponentType.FLOAT]:xn.DT_FLOAT32,[Be.ComponentType.UNSIGNED_INT]:xn.DT_UINT32,[Be.ComponentType.UNSIGNED_SHORT]:xn.DT_UINT16,[Be.ComponentType.UNSIGNED_BYTE]:xn.DT_UINT8,[Be.ComponentType.SHORT]:xn.DT_INT16,[Be.ComponentType.BYTE]:xn.DT_INT8}}function F2(e){wi=e}function U2(e,t=fS){let n={...fS,...t};n.quantizationBits={...RS,...t.quantizationBits};let i=new wi.MeshBuilder,r=new wi.Mesh,s=new wi.ExpertEncoder(r),a={},o=new wi.DracoInt8Array,c=e.listTargets().length>0,l=!1;for(let m of e.listSemantics()){let g=e.getAttribute(m);if(g.getSparse()){l=!0;continue}let p=B2(m),x=z2(i,g.getComponentType(),r,wi[p],g.getCount(),g.getElementSize(),g.getArray());if(x===-1)throw Error(`Error compressing "${m}" attribute.`);if(a[m]=x,n.quantizationVolume==="mesh"||m!=="POSITION")s.SetAttributeQuantization(x,n.quantizationBits[p]);else if(typeof n.quantizationVolume==="object"){let{quantizationVolume:_}=n,y=Math.max(_.max[0]-_.min[0],_.max[1]-_.min[1],_.max[2]-_.min[2]);s.SetAttributeExplicitQuantization(x,n.quantizationBits[p],g.getElementSize(),_.min,y)}else throw Error("Invalid quantization volume state.")}let u=e.getIndices();if(!u)throw new jg("Primitive must have indices.");if(i.AddFacesToMesh(r,u.getCount()/3,u.getArray()),s.SetSpeedOptions(n.encodeSpeed,n.decodeSpeed),s.SetTrackEncodedProperties(!0),n.method===0||c||l)s.SetEncodingMethod(wi.MESH_SEQUENTIAL_ENCODING);else s.SetEncodingMethod(wi.MESH_EDGEBREAKER_ENCODING);let d=s.EncodeToDracoBuffer(!(c||l),o);if(d<=0)throw new jg("Error applying Draco compression.");let f=new Uint8Array(d);for(let m=0;m<d;++m)f[m]=o.GetValue(m);let h=s.GetNumberOfEncodedPoints(),b=s.GetNumberOfEncodedFaces()*3;return wi.destroy(o),wi.destroy(r),wi.destroy(i),wi.destroy(s),{numVertices:h,numIndices:b,data:f,attributeIDs:a}}function B2(e){if(e==="POSITION")return"POSITION";else if(e==="NORMAL")return"NORMAL";else if(e.startsWith("COLOR_"))return"COLOR";else if(e.startsWith("TEXCOORD_"))return"TEX_COORD";return"GENERIC"}function z2(e,t,n,i,r,s,a){switch(t){case Be.ComponentType.UNSIGNED_BYTE:return e.AddUInt8Attribute(n,i,r,s,a);case Be.ComponentType.BYTE:return e.AddInt8Attribute(n,i,r,s,a);case Be.ComponentType.UNSIGNED_SHORT:return e.AddUInt16Attribute(n,i,r,s,a);case Be.ComponentType.SHORT:return e.AddInt16Attribute(n,i,r,s,a);case Be.ComponentType.UNSIGNED_INT:return e.AddUInt32Attribute(n,i,r,s,a);case Be.ComponentType.FLOAT:return e.AddFloatAttribute(n,i,r,s,a);default:throw Error(`Unexpected component type, "${t}".`)}}function V2(e){let t=e.getLogger(),n=new Set,i=new Set,r=0,s=0;for(let d of e.getRoot().listMeshes())for(let f of d.listPrimitives())if(!f.getIndices())i.add(f),r++;else if(f.getMode()!==Jn.Mode.TRIANGLES)i.add(f),s++;else n.add(f);if(r>0)t.warn(`[${tn}] Skipping Draco compression of ${r} non-indexed primitives.`);if(s>0)t.warn(`[${tn}] Skipping Draco compression of ${s} non-TRIANGLES primitives.`);let a=e.getRoot().listAccessors(),o=new Map;for(let d=0;d<a.length;d++)o.set(a[d],d);let c=new Map,l=new Set,u=new Map;for(let d of Array.from(n)){let f=hS(d,o);if(l.has(f)){u.set(d,f);continue}if(c.has(d.getIndices())){let h=d.getIndices(),b=h.clone();o.set(b,e.getRoot().listAccessors().length-1),d.swap(h,b)}for(let h of d.listAttributes())if(c.has(h)){let b=h.clone();o.set(b,e.getRoot().listAccessors().length-1),d.swap(h,b)}f=hS(d,o),l.add(f),u.set(d,f),c.set(d.getIndices(),f);for(let h of d.listAttributes())c.set(h,f)}for(let d of Array.from(c.keys())){let f=new Set(d.listParents().map((h)=>h.propertyType));if(f.size!==2||!f.has(te.PRIMITIVE)||!f.has(te.ROOT))throw Error(`[${tn}] Compressed accessors must only be used as indices or vertex attributes.`)}for(let d of Array.from(n)){let f=u.get(d),h=d.getIndices();if(c.get(h)!==f||d.listAttributes().some((b)=>c.get(b)!==f))throw Error(`[${tn}] Draco primitives must share all, or no, accessors.`)}for(let d of Array.from(i)){let f=d.getIndices();if(c.has(f)||d.listAttributes().some((h)=>c.has(h)))throw Error(`[${tn}] Accessor cannot be shared by compressed and uncompressed primitives.`)}return u}function hS(e,t){let n=[],i=e.getIndices();n.push(t.get(i));for(let r of e.listAttributes())n.push(t.get(r));return n.sort().join("|")}function LU(e){return e.vkFormat>Fg&&e.vkFormat<=tS}function ES(e){let t=e.vkFormat===nS&&e.dataFormatDescriptor[0].colorModel===167;return e.vkFormat===Fg||t}function Bg(e){return JSON.parse(JSON.stringify(e))}var Os="EXT_mesh_gpu_instancing",Gr="EXT_mesh_features",Zn="EXT_meshopt_compression",et="EXT_structural_metadata",af="EXT_texture_webp",of="EXT_texture_avif",EF="KHR_accessor_float16",TF="KHR_accessor_float64",tn="KHR_draco_mesh_compression",Hr="KHR_lights_punctual",ks="KHR_materials_anisotropy",Ds="KHR_materials_clearcoat",Ls="KHR_materials_diffuse_transmission",Fs="KHR_materials_dispersion",Us="KHR_materials_emissive_strength",Bs="KHR_materials_ior",zs="KHR_materials_iridescence",Vs="KHR_materials_pbrSpecularGlossiness",js="KHR_materials_sheen",Hs="KHR_materials_specular",Gs="KHR_materials_transmission",Jo="KHR_materials_unlit",$s="KHR_materials_volume",fi="KHR_materials_variants",rS="KHR_mesh_primitive_restart",sS="KHR_mesh_quantization",Ks="KHR_node_visibility",cf="KHR_texture_basisu",Ws="KHR_texture_transform",$i="KHR_xmp_json_ld",AF,wF,SF,Sl,MF,zg="INSTANCE_ATTRIBUTE",NF,lf,PF,kF,aS,DF,oS,Vg,cS,Ml,jF,HF,GF,$F,KF,WF,XF,qF,JF,ZF,YF,QF,e2,t2,n2,R2=class{match(e){return e.length>=12&&Je.decodeText(e.slice(4,12))==="ftypavif"}getSize(e){if(!this.match(e))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=lS(t,0);if(!n)return null;let i=n.end;while(n=lS(t,i))if(n.type==="meta")i=n.start+4;else if(n.type==="iprp"||n.type==="ipco")i=n.start;else if(n.type==="ispe")return[t.getUint32(n.start+4),t.getUint32(n.start+8)];else if(n.type==="mdat")break;else i=n.end;return null}getChannels(e){return 4}},AS,I2=class{match(e){return e.length>=12&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}getSize(e){let t=Je.decodeText(e.slice(0,4)),n=Je.decodeText(e.slice(8,12));if(t!=="RIFF"||n!=="WEBP")return null;let i=new DataView(e.buffer,e.byteOffset),r=12;while(r<i.byteLength){let s=Je.decodeText(new Uint8Array([i.getUint8(r),i.getUint8(r+1),i.getUint8(r+2),i.getUint8(r+3)])),a=i.getUint32(r+4,!0);if(s==="VP8 ")return[i.getInt16(r+14,!0)&16383,i.getInt16(r+16,!0)&16383];else if(s==="VP8L"){let o=i.getUint8(r+9),c=i.getUint8(r+10),l=i.getUint8(r+11),u=i.getUint8(r+12);return[1+((c&63)<<8|o),1+((u&15)<<10|l<<2|(c&192)>>6)]}r+=8+a+a%2}return null}getChannels(e){return 4}},wS,uS,C2,dS,N2,xn,SS,MS,wi,L2,RS,fS,jg,IS,pS,j2,H2,G2,$2,K2,W2,mS,gS,X2,q2,J2,Z2,Y2,Q2,eU,tU,nU,iU,rU,sU,aU,oU,CS,cU,lU,uU,dU,bS,xS,yS,_S,fU,NS,hU,pU,mU,gU,bU,xU,yU,_U,vU,EU,TU,PS,AU,wU,SU,MU,OS,RU,IU,vS,CU,NU,PU,OU,kS,Hg,kU,DU,FU=class{match(e){return e[0]===171&&e[1]===75&&e[2]===84&&e[3]===88&&e[4]===32&&e[5]===50&&e[6]===48&&e[7]===187&&e[8]===13&&e[9]===10&&e[10]===26&&e[11]===10}getSize(e){let t=sf(e);return[t.pixelWidth,t.pixelHeight]}getChannels(e){let t=sf(e),n=t.dataFormatDescriptor[0];if(LU(t))return n.samples.length;if(ES(t))switch(n.colorModel){case Qw:return n.samples.length===2&&(n.samples[1].channelType&15)===15?4:3;case eS:return(n.samples[0].channelType&15)===3?4:3;default:throw Error(`Unexpected KTX2 colorModel, "${n.colorModel}".`)}throw Error(`Unexpected KTX2 vkFormat, "${t.vkFormat}".`)}getVRAMByteLength(e){let t=sf(e),n=0;if(ES(t)){let i=this.getChannels(e)>3;for(let r=0;r<t.levels.length;r++){let s=t.levels[r];if(s.uncompressedByteLength)n+=s.uncompressedByteLength;else{let a=Math.max(1,Math.floor(t.pixelWidth/Math.pow(2,r))),o=Math.max(1,Math.floor(t.pixelHeight/Math.pow(2,r))),c=i?16:8;n+=a/4*(o/4)*c}}}else for(let i of t.levels)if(t.supercompressionScheme===Yw)n+=i.levelData.byteLength;else n+=i.uncompressedByteLength;return n}},Gg,UU,BU,zU,VU,jU,HU,DS;var uf=mt(()=>{wl();iS();AF=class extends nt{static EXTENSION_NAME=Gr;init(){this.extensionName=Gr,this.propertyType="FeatureID",this.parentTypes=["Features"]}getDefaults(){return Object.assign(super.getDefaults(),{nullFeatureId:null,label:"",attribute:null,texture:null,propertyTable:null})}getFeatureCount(){return this.get("featureCount")}setFeatureCount(e){return this.set("featureCount",e)}getNullFeatureID(){return this.get("nullFeatureId")}setNullFeatureID(e){return this.set("nullFeatureId",e)}getLabel(){return this.get("label")}setLabel(e){return this.set("label",e)}getAttribute(){return this.get("attribute")}setAttribute(e){return this.set("attribute",e)}getTexture(){return this.getRef("texture")}setTexture(e){return this.setRef("texture",e)}getPropertyTable(){return this.getRef("propertyTable")}setPropertyTable(e){return this.setRef("propertyTable",e)}},wF=class extends nt{static EXTENSION_NAME=Gr;init(){this.extensionName=Gr,this.propertyType="FeatureIDTexture",this.parentTypes=["FeatureID"]}getDefaults(){let e=new wt(this.graph,"textureInfo");return e.setMinFilter(wt.MagFilter.NEAREST),e.setMagFilter(wt.MagFilter.NEAREST),Object.assign(super.getDefaults(),{channels:[0],texture:null,textureInfo:e})}getChannels(){return this.get("channels")}setChannels(e){return this.set("channels",e)}getTexture(){return this.getRef("texture")}setTexture(e){return this.setRef("texture",e)}getTextureInfo(){return this.getRef("texture")?this.getRef("textureInfo"):null}},SF=class extends nt{static EXTENSION_NAME=Gr;init(){this.extensionName=Gr,this.propertyType="Features",this.parentTypes=[te.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{featureIds:new It([])})}listFeatureIDs(){return this.listRefs("featureIds")}addFeatureID(e){return this.addRef("featureIds",e)}removeFeatureID(e){return this.removeRef("featureIds",e)}},Sl=Gr,MF=class extends _t{extensionName=Gr;static EXTENSION_NAME=Gr;createFeatures(){return new SF(this.document.getGraph())}createFeatureID(){return new AF(this.document.getGraph())}createFeatureIDTexture(){return new wF(this.document.getGraph())}read(e){return(e.jsonDoc.json.meshes||[]).forEach((t,n)=>{(t.primitives||[]).forEach((i,r)=>{this._readPrimitive(e,n,i,r)})}),this}_readPrimitive(e,t,n,i){if(!n.extensions||!n.extensions[Sl])return;let r=this.createFeatures(),s=n.extensions[Sl];for(let a of s.featureIds){let o=RF(this.document,this,e,a);r.addFeatureID(o)}e.meshes[t].listPrimitives()[i].setExtension(Sl,r)}write(e){let t=e.jsonDoc.json.meshes;if(!t)return this;for(let n of this.document.getRoot().listMeshes()){let i=t[e.meshIndexMap.get(n)];n.listPrimitives().forEach((r,s)=>{let a=i.primitives[s];this._writePrimitive(e,r,a)})}return this}_writePrimitive(e,t,n){let i=t.getExtension(Sl);if(!i)return;let r={featureIds:[]};i.listFeatureIDs().forEach((s)=>{r.featureIds.push(CF(this.document,e,s))}),n.extensions=n.extensions||{},n.extensions[Sl]=r}};NF=class extends nt{static EXTENSION_NAME=Os;init(){this.extensionName=Os,this.propertyType="InstancedMesh",this.parentTypes=[te.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new dn})}getAttribute(e){return this.getRefMap("attributes",e)}setAttribute(e,t){return this.setRefMap("attributes",e,t,{usage:zg})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}},lf=class extends _t{static EXTENSION_NAME=Os;extensionName=Os;prewriteTypes=[te.ACCESSOR];createInstancedMesh(){return new NF(this.document.getGraph())}read(e){return(e.jsonDoc.json.nodes||[]).forEach((t,n)=>{if(!t.extensions||!t.extensions.EXT_mesh_gpu_instancing)return;let i=t.extensions[Os],r=this.createInstancedMesh();for(let s in i.attributes)r.setAttribute(s,e.accessors[i.attributes[s]]);e.nodes[n].setExtension(Os,r)}),this}prewrite(e){e.accessorUsageGroupedByParent.add(zg);for(let t of this.properties)for(let n of t.listAttributes())e.addAccessorToUsageGroup(n,zg);return this}write(e){let t=e.jsonDoc;return this.document.getRoot().listNodes().forEach((n)=>{let i=n.getExtension(Os);if(i){let r=e.nodeIndexMap.get(n),s=t.json.nodes[r],a={attributes:{}};i.listSemantics().forEach((o)=>{let c=i.getAttribute(o);a.attributes[o]=e.accessorIndexMap.get(c)}),s.extensions=s.extensions||{},s.extensions[Os]=a}}),this}},PF=function(e){return e.QUANTIZE="quantize",e.FILTER="filter",e}({});({BYTE:kF,SHORT:aS,FLOAT:DF}=Be.ComponentType),{encodeNormalizedInt:oS,decodeNormalizedInt:Vg}=pt;cS={method:"quantize"},Ml=class extends _t{extensionName=Zn;prereadTypes=[te.BUFFER,te.PRIMITIVE];prewriteTypes=[te.BUFFER,te.ACCESSOR];readDependencies=["meshopt.decoder"];writeDependencies=["meshopt.encoder"];static EXTENSION_NAME=Zn;static EncoderMethod=PF;_decoder=null;_decoderFallbackBufferMap=new Map;_encoder=null;_encoderOptions=cS;_encoderFallbackBuffer=null;_encoderBufferViews={};_encoderBufferViewData={};_encoderBufferViewAccessors={};install(e,t){if(e==="meshopt.decoder")this._decoder=t;if(e==="meshopt.encoder")this._encoder=t;return this}setEncoderOptions(e){return this._encoderOptions={...cS,...e},this}preread(e,t){if(!this._decoder){if(!this.isRequired())return this;throw Error(`[${Zn}] Please install extension dependency, "meshopt.decoder".`)}if(!this._decoder.supported){if(!this.isRequired())return this;throw Error(`[${Zn}]: Missing WASM support.`)}if(t===te.BUFFER)this._prereadBuffers(e);else if(t===te.PRIMITIVE)this._prereadPrimitives(e);return this}_prereadBuffers(e){let t=e.jsonDoc;(t.json.bufferViews||[]).forEach((n,i)=>{if(!n.extensions||!n.extensions.EXT_meshopt_compression)return;let r=n.extensions[Zn],s=r.byteOffset||0,a=r.byteLength||0,{count:o,byteStride:c}=r,l=new Uint8Array(o*c),u=t.json.buffers[r.buffer],d=u.uri?t.resources[u.uri]:t.resources[Cs],f=Je.toView(d,s,a);this._decoder.decodeGltfBuffer(l,o,c,f,r.mode,r.filter),e.bufferViews[i]=l})}_prereadPrimitives(e){let t=e.jsonDoc;(t.json.bufferViews||[]).forEach((n)=>{if(!n.extensions||!n.extensions.EXT_meshopt_compression)return;let i=n.extensions[Zn],r=e.buffers[i.buffer],s=e.buffers[n.buffer],a=t.json.buffers[n.buffer];if(OF(a))this._decoderFallbackBufferMap.set(s,r)})}read(e){if(!this.isRequired())return this;for(let[t,n]of this._decoderFallbackBufferMap){for(let i of t.listParents())if(i instanceof Be)i.swap(t,n);t.dispose()}return this}prewrite(e,t){if(t===te.ACCESSOR)this._prewriteAccessors(e);else if(t===te.BUFFER)this._prewriteBuffers(e);return this}_prewriteAccessors(e){let t=e.jsonDoc.json,n=this._encoder,i=this._encoderOptions,r=this.document.getGraph(),s=this.document.createBuffer(),a=this.document.getRoot().listBuffers().indexOf(s),o=1,c=new Map,l=(u)=>{for(let d of r.listParents(u)){if(d.propertyType===te.ROOT)continue;let f=c.get(u);if(f===void 0)c.set(u,f=o++);return f}return-1};this._encoderFallbackBuffer=s,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={};for(let u of this.document.getRoot().listAccessors()){if(TS(u)==="weights")continue;if(u.getSparse())continue;let d=e.getAccessorUsage(u),f=e.accessorUsageGroupedByParent.has(d)?l(u):null,h=zF(u,d),b=i.method==="filter"?VF(u,this.document):{filter:"NONE"},m=LF(u,n,h,b),{array:g,byteStride:p}=m,x=u.getBuffer();if(!x)throw Error(`${Zn}: Missing buffer for accessor.`);let _=this.document.getRoot().listBuffers().indexOf(x),y=[d,f,h,b.filter,p,_].join(":"),v=this._encoderBufferViews[y],T=this._encoderBufferViewData[y],A=this._encoderBufferViewAccessors[y];if(!v||!T)A=this._encoderBufferViewAccessors[y]=[],T=this._encoderBufferViewData[y]=[],v=this._encoderBufferViews[y]={buffer:a,target:Is.USAGE_TO_TARGET[d],byteOffset:0,byteLength:0,byteStride:d===Is.BufferViewUsage.ARRAY_BUFFER?p:void 0,extensions:{[Zn]:{buffer:_,byteOffset:0,byteLength:0,mode:h,filter:b.filter!=="NONE"?b.filter:void 0,byteStride:p,count:0}}};let E=e.createAccessorDef(u);if(E.componentType=m.componentType,E.normalized=m.normalized,E.byteOffset=v.byteLength,E.min&&m.min)E.min=m.min;if(E.max&&m.max)E.max=m.max;e.accessorIndexMap.set(u,t.accessors.length),t.accessors.push(E),A.push(E),T.push(new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),v.byteLength+=g.byteLength,v.extensions.EXT_meshopt_compression.count+=u.getCount()}}_prewriteBuffers(e){let t=this._encoder;for(let n in this._encoderBufferViews){let i=this._encoderBufferViews[n],r=this._encoderBufferViewData[n],s=this.document.getRoot().listBuffers()[i.extensions[Zn].buffer],a=e.otherBufferViews.get(s)||[],{count:o,byteStride:c,mode:l}=i.extensions[Zn],u=Je.concat(r),d=t.encodeGltfBuffer(u,o,c,l),f=Je.pad(d);i.extensions[Zn].byteLength=d.byteLength,r.length=0,r.push(f),a.push(f),e.otherBufferViews.set(s,a)}}write(e){let t=0;for(let s in this._encoderBufferViews){let a=this._encoderBufferViews[s],o=this._encoderBufferViewData[s][0],c=e.otherBufferViewsIndexMap.get(o),l=this._encoderBufferViewAccessors[s];for(let h of l)h.bufferView=c;let u=e.jsonDoc.json.bufferViews[c],d=u.byteOffset||0;Object.assign(u,a),u.byteOffset=t;let f=u.extensions[Zn];f.byteOffset=d,t+=Je.padNumber(a.byteLength)}let n=this._encoderFallbackBuffer,i=e.bufferIndexMap.get(n),r=e.jsonDoc.json.buffers[i];return r.byteLength=t,r.extensions={[Zn]:{fallback:!0}},n.dispose(),this}},jF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="StructuralMetadata",this.parentTypes=[te.ROOT]}getDefaults(){return Object.assign(super.getDefaults(),{schema:null,schemaUri:"",propertyTables:new bn,propertyTextures:new bn,propertyAttributes:new bn})}getSchema(){return this.getRef("schema")}setSchema(e){return this.setRef("schema",e)}getSchemaUri(){return this.get("schemaUri")}setSchemaUri(e){return this.set("schemaUri",e)}listPropertyTables(){return this.listRefs("propertyTables")}addPropertyTable(e){return this.addRef("propertyTables",e)}removePropertyTable(e){return this.removeRef("propertyTables",e)}listPropertyTextures(){return this.listRefs("propertyTextures")}addPropertyTexture(e){return this.addRef("propertyTextures",e)}removePropertyTexture(e){return this.removeRef("propertyTextures",e)}listPropertyAttributes(){return this.listRefs("propertyAttributes")}addPropertyAttribute(e){return this.addRef("propertyAttributes",e)}removePropertyAttribute(e){return this.removeRef("propertyAttributes",e)}},HF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="Schema",this.parentTypes=["StructuralMetadata"]}getDefaults(){return Object.assign(super.getDefaults(),{description:"",version:"",classes:new dn,enums:new dn})}getId(){return this.get("id")}setId(e){return this.set("id",e)}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}getVersion(){return this.get("version")}setVersion(e){return this.set("version",e)}setClass(e,t){return this.setRefMap("classes",e,t)}getClass(e){return this.getRefMap("classes",e)}listClassKeys(){return this.listRefMapKeys("classes")}listClassValues(){return this.listRefMapValues("classes")}setEnum(e,t){return this.setRefMap("enums",e,t)}getEnum(e){return this.getRefMap("enums",e)}listEnumKeys(){return this.listRefMapKeys("enums")}listEnumValues(){return this.listRefMapValues("enums")}},GF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="Class",this.parentTypes=["Schema"]}getDefaults(){return Object.assign(super.getDefaults(),{description:"",properties:new dn})}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}setProperty(e,t){return this.setRefMap("properties",e,t)}getProperty(e){return this.getRefMap("properties",e)}listPropertyKeys(){return this.listRefMapKeys("properties")}listPropertyValues(){return this.listRefMapValues("properties")}},$F=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="ClassProperty",this.parentTypes=["Class"]}getDefaults(){return Object.assign(super.getDefaults(),{description:"",componentType:null,enumType:null,array:null,count:null,normalized:null,offset:null,scale:null,max:null,min:null,required:null,noData:null,default:null})}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}getType(){return this.get("type")}setType(e){return this.set("type",e)}getComponentType(){return this.get("componentType")}setComponentType(e){return this.set("componentType",e)}getEnumType(){return this.get("enumType")}setEnumType(e){return this.set("enumType",e)}getArray(){return this.get("array")}setArray(e){return this.set("array",e)}getCount(){return this.get("count")}setCount(e){return this.set("count",e)}getNormalized(){return this.get("normalized")}setNormalized(e){return this.set("normalized",e)}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getMax(){return this.get("max")}setMax(e){return this.set("max",e)}getMin(){return this.get("min")}setMin(e){return this.set("min",e)}getRequired(){return this.get("required")}setRequired(e){return this.set("required",e)}getNoData(){return this.get("noData")}setNoData(e){return this.set("noData",e)}getDefault(){return this.get("default")}setDefault(e){return this.set("default",e)}},KF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="Enum",this.parentTypes=["Schema"]}getDefaults(){return Object.assign(super.getDefaults(),{description:"",valueType:"UINT16",values:new bn})}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}getValueType(){return this.get("valueType")}setValueType(e){return this.set("valueType",e)}listValues(){return this.listRefs("values")}addEnumValue(e){return this.addRef("values",e)}removeEnumValue(e){return this.removeRef("values",e)}},WF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="EnumValue",this.parentTypes=["Enum"]}getDefaults(){return Object.assign(super.getDefaults(),{description:null})}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}getValue(){return this.get("value")}setValue(e){return this.set("value",e)}},XF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyTable",this.parentTypes=["StructuralMetadata"]}getDefaults(){return Object.assign(super.getDefaults(),{properties:new dn})}getClass(){return this.get("class")}setClass(e){return this.set("class",e)}getCount(){return this.get("count")}setCount(e){return this.set("count",e)}setProperty(e,t){return this.setRefMap("properties",e,t)}getProperty(e){return this.getRefMap("properties",e)}listPropertyKeys(){return this.listRefMapKeys("properties")}listPropertyValues(){return this.listRefMapValues("properties")}},qF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyTableProperty",this.parentTypes=["PropertyTable"]}getDefaults(){return Object.assign(super.getDefaults(),{arrayOffsets:null,stringOffsets:null,arrayOffsetType:null,stringOffsetType:null,offset:null,scale:null,max:null,min:null})}getValues(){return this.get("values")}setValues(e){return this.set("values",e)}getArrayOffsets(){return this.get("arrayOffsets")}setArrayOffsets(e){return this.set("arrayOffsets",e)}getStringOffsets(){return this.get("stringOffsets")}setStringOffsets(e){return this.set("stringOffsets",e)}getArrayOffsetType(){return this.get("arrayOffsetType")}setArrayOffsetType(e){return this.set("arrayOffsetType",e)}getStringOffsetType(){return this.get("stringOffsetType")}setStringOffsetType(e){return this.set("stringOffsetType",e)}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getMax(){return this.get("max")}setMax(e){return this.set("max",e)}getMin(){return this.get("min")}setMin(e){return this.set("min",e)}},JF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyTexture",this.parentTypes=["StructuralMetadata"]}getDefaults(){return Object.assign(super.getDefaults(),{properties:new dn})}getClass(){return this.get("class")}setClass(e){return this.set("class",e)}setProperty(e,t){return this.setRefMap("properties",e,t)}getProperty(e){return this.getRefMap("properties",e)}listPropertyKeys(){return this.listRefMapKeys("properties")}listPropertyValues(){return this.listRefMapValues("properties")}},ZF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyTextureProperty",this.parentTypes=["PropertyTexture"]}getDefaults(){let e=new wt(this.graph,"textureInfo");return e.setMinFilter(wt.MagFilter.NEAREST),e.setMagFilter(wt.MagFilter.NEAREST),Object.assign(super.getDefaults(),{channels:[0],texture:null,textureInfo:e,offset:null,scale:null,max:null,min:null})}getChannels(){return this.get("channels")}setChannels(e){return this.set("channels",e)}getTexture(){return this.getRef("texture")}setTexture(e){return this.setRef("texture",e)}getTextureInfo(){return this.getRef("texture")?this.getRef("textureInfo"):null}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getMax(){return this.get("max")}setMax(e){return this.set("max",e)}getMin(){return this.get("min")}setMin(e){return this.set("min",e)}},YF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyAttribute",this.parentTypes=["StructuralMetadata"]}getDefaults(){return Object.assign(super.getDefaults(),{properties:new dn})}getClass(){return this.get("class")}setClass(e){return this.set("class",e)}setProperty(e,t){return this.setRefMap("properties",e,t)}getProperty(e){return this.getRefMap("properties",e)}listPropertyKeys(){return this.listRefMapKeys("properties")}listPropertyValues(){return this.listRefMapValues("properties")}},QF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyAttributeProperty",this.parentTypes=["PropertyAttribute"]}getDefaults(){return Object.assign(super.getDefaults(),{offset:null,scale:null,max:null,min:null})}getAttribute(){return this.get("attribute")}setAttribute(e){return this.set("attribute",e)}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getMax(){return this.get("max")}setMax(e){return this.set("max",e)}getMin(){return this.get("min")}setMin(e){return this.set("min",e)}},e2=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="NodeStructuralMetadata",this.parentTypes=[te.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{class:"",properties:{}})}getClass(){return this.get("class")}setClass(e){return this.set("class",e)}getProperties(){return this.get("properties")}setProperties(e){return this.set("properties",e)}},t2=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="MeshPrimitiveStructuralMetadata",this.parentTypes=[te.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{propertyTextures:new bn,propertyAttributes:new bn})}listPropertyTextures(){return this.listRefs("propertyTextures")}addPropertyTexture(e){return this.addRef("propertyTextures",e)}removePropertyTexture(e){return this.removeRef("propertyTextures",e)}listPropertyAttributes(){return this.listRefs("propertyAttributes")}addPropertyAttribute(e){return this.addRef("propertyAttributes",e)}removePropertyAttribute(e){return this.removeRef("propertyAttributes",e)}},n2=class extends _t{extensionName=et;static EXTENSION_NAME=et;prewriteTypes=[te.BUFFER];prereadTypes=[te.SCENE];createStructuralMetadata(){return new jF(this.document.getGraph())}createSchema(){return new HF(this.document.getGraph())}createClass(){return new GF(this.document.getGraph())}createClassProperty(){return new $F(this.document.getGraph())}createEnum(){return new KF(this.document.getGraph())}createEnumValue(){return new WF(this.document.getGraph())}createPropertyTable(){return new XF(this.document.getGraph())}createPropertyTableProperty(){return new qF(this.document.getGraph())}createPropertyTexture(){return new JF(this.document.getGraph())}createPropertyTextureProperty(){return new ZF(this.document.getGraph())}createPropertyAttribute(){return new YF(this.document.getGraph())}createPropertyAttributeProperty(){return new QF(this.document.getGraph())}createNodeStructuralMetadata(){return new e2(this.document.getGraph())}createMeshPrimitiveStructuralMetadata(){return new t2(this.document.getGraph())}read(e){return this}preread(e){let t=this.document.getRoot(),{json:n}=e.jsonDoc,i=n.extensions[et],r=i2(this,e,i);return t.setExtension(et,r),(n.meshes||[]).forEach((s,a)=>{let o=e.meshes[a].listPrimitives();(s.primitives||[]).forEach((c,l)=>{let u=o[l];this._readPrimitive(r,u,c)})}),(n.nodes||[]).forEach((s,a)=>{this._readNode(e.nodes[a],s)}),this}_readPrimitive(e,t,n){if(!n.extensions||!n.extensions.EXT_structural_metadata)return;let i=this.createMeshPrimitiveStructuralMetadata(),r=n.extensions[et],s=e.listPropertyTextures(),a=r.propertyTextures||[];for(let l of a){let u=s[l];i.addPropertyTexture(u)}let o=e.listPropertyAttributes(),c=r.propertyAttributes||[];for(let l of c){let u=o[l];i.addPropertyAttribute(u)}t.setExtension(et,i)}_readNode(e,t){if(!t.extensions||!t.extensions.EXT_structural_metadata)return;let n=t.extensions[et],i=this.createNodeStructuralMetadata().setClass(n.class).setProperties(n.properties);e.setExtension(et,i)}write(e){let t=this.document.getRoot(),n=t.getExtension(et);if(!n)return this;let i=e.jsonDoc.json,r=m2(e,n);i.extensions=i.extensions||{},i.extensions[et]=r;let s=t.listMeshes(),a=i.meshes;if(a)for(let l of s){let u=a[e.meshIndexMap.get(l)];l.listPrimitives().forEach((d,f)=>{let h=u.primitives[f];this._writePrimitive(n,d,h)})}let o=t.listNodes(),c=i.nodes;if(c)for(let l of o){let u=e.nodeIndexMap.get(l);this._writeNode(l,c[u])}return this}_writePrimitive(e,t,n){let i=t.getExtension(et);if(!i)return;let r=e.listPropertyTextures(),s=e.listPropertyAttributes(),a,o,c=i.listPropertyTextures();if(c.length>0){a=[];for(let d of c){let f=r.indexOf(d);if(f>=0)a.push(f);else throw Error(`${et}: Invalid property texture in mesh primitive`)}}let l=i.listPropertyAttributes();if(l.length>0){o=[];for(let d of l){let f=s.indexOf(d);if(f>=0)o.push(f);else throw Error(`${et}: Invalid property attribute in mesh primitive`)}}let u={propertyTextures:a,propertyAttributes:o};n.extensions=n.extensions||{},n.extensions[et]=u}_writeNode(e,t){let n=e.getExtension("EXT_structural_metadata");if(!n)return;t.extensions=t.extensions||{},t.extensions[et]={class:n.getClass(),properties:n.getProperties()}}prewrite(e,t){if(t===te.BUFFER)this._prewriteBuffers(e);return this}_prewriteBuffers(e){let t=this.document,n=t.getRoot().getExtension(et);e.jsonDoc.json.bufferViews||=[];for(let i of n.listPropertyTables())for(let r of i.listPropertyValues()){let s=M2(t,e);s.push(r.getValues());let a=r.getArrayOffsets();if(a)s.push(a);let o=r.getStringOffsets();if(o)s.push(o)}}};AS=class extends _t{extensionName=of;prereadTypes=[te.TEXTURE];static EXTENSION_NAME=of;static register(){Gi.registerFormat("image/avif",new R2)}preread(e){return(e.jsonDoc.json.textures||[]).forEach((t)=>{if(t.extensions&&t.extensions.EXT_texture_avif)t.source=t.extensions[of].source}),this}read(e){return this}write(e){let t=e.jsonDoc;return this.document.getRoot().listTextures().forEach((n)=>{if(n.getMimeType()==="image/avif"){let i=e.imageIndexMap.get(n);(t.json.textures||[]).forEach((r)=>{if(r.source===i)r.extensions=r.extensions||{},r.extensions[of]={source:r.source},delete r.source})}}),this}};wS=class extends _t{extensionName=af;prereadTypes=[te.TEXTURE];static EXTENSION_NAME=af;static register(){Gi.registerFormat("image/webp",new I2)}preread(e){return(e.jsonDoc.json.textures||[]).forEach((t)=>{if(t.extensions&&t.extensions.EXT_texture_webp)t.source=t.extensions[af].source}),this}read(e){return this}write(e){let t=e.jsonDoc;return this.document.getRoot().listTextures().forEach((n)=>{if(n.getMimeType()==="image/webp"){let i=e.imageIndexMap.get(n);(t.json.textures||[]).forEach((r)=>{if(r.source===i)r.extensions=r.extensions||{},r.extensions[af]={source:r.source},delete r.source})}}),this}},uS=EF,C2=class extends _t{extensionName=uS;static EXTENSION_NAME=uS;read(e){return this}write(e){return this}},dS=TF,N2=class extends _t{extensionName=dS;static EXTENSION_NAME=dS;read(e){return this}write(e){return this}};L2=function(e){return e[e.EDGEBREAKER=1]="EDGEBREAKER",e[e.SEQUENTIAL=0]="SEQUENTIAL",e}({}),RS={["POSITION"]:14,["NORMAL"]:10,["COLOR"]:8,["TEX_COORD"]:12,["GENERIC"]:12},fS={decodeSpeed:5,encodeSpeed:5,method:1,quantizationBits:RS,quantizationVolume:"mesh"};jg=class extends Error{},IS=class extends _t{extensionName=tn;prereadTypes=[te.PRIMITIVE];prewriteTypes=[te.ACCESSOR];readDependencies=["draco3d.decoder"];writeDependencies=["draco3d.encoder"];static EXTENSION_NAME=tn;static EncoderMethod=L2;_decoderModule=null;_encoderModule=null;_encoderOptions={};install(e,t){if(e==="draco3d.decoder")this._decoderModule=t,D2(this._decoderModule);if(e==="draco3d.encoder")this._encoderModule=t,F2(this._encoderModule);return this}setEncoderOptions(e){return this._encoderOptions=e,this}preread(e){if(!this._decoderModule)throw Error(`[${tn}] Please install extension dependency, "draco3d.decoder".`);let t=this.document.getLogger(),n=e.jsonDoc,i=new Map;try{let r=n.json.meshes||[];for(let s of r)for(let a of s.primitives){if(!a.extensions||!a.extensions.KHR_draco_mesh_compression)continue;let o=a.extensions[tn],[c,l]=i.get(o.bufferView)||[];if(!l||!c){let u=n.json.bufferViews[o.bufferView],d=n.json.buffers[u.buffer],f=d.uri?n.resources[d.uri]:n.resources[Cs],h=u.byteOffset||0,b=u.byteLength,m=Je.toView(f,h,b);c=new this._decoderModule.Decoder,l=P2(c,m),i.set(o.bufferView,[c,l]),t.debug(`[${tn}] Decompressed ${m.byteLength} bytes.`)}for(let u in o.attributes){let d=e.jsonDoc.json.accessors[a.attributes[u]],f=c.GetAttributeByUniqueId(l,o.attributes[u]),h=k2(c,l,f,d);e.accessors[a.attributes[u]].setArray(h)}if(a.indices!==void 0)e.accessors[a.indices].setArray(O2(c,l))}}finally{for(let[r,s]of Array.from(i.values()))this._decoderModule.destroy(r),this._decoderModule.destroy(s)}return this}read(e){return this}prewrite(e,t){if(!this._encoderModule)throw Error(`[${tn}] Please install extension dependency, "draco3d.encoder".`);let n=this.document.getLogger();n.debug(`[${tn}] Compression options: ${JSON.stringify(this._encoderOptions)}`);let i=V2(this.document),r=new Map,s="mesh";if(this._encoderOptions.quantizationVolume==="scene")if(this.document.getRoot().listScenes().length!==1)n.warn(`[${tn}]: quantizationVolume=scene requires exactly 1 scene.`);else s=Og(this.document.getRoot().listScenes().pop());for(let a of Array.from(i.keys())){let o=i.get(a);if(!o)throw Error("Unexpected primitive.");if(r.has(o)){r.set(o,r.get(o));continue}let c=a.getIndices(),l=e.jsonDoc.json.accessors,u;try{u=U2(a,{...this._encoderOptions,quantizationVolume:s})}catch(h){if(h instanceof jg){n.warn(`[${tn}]: ${h.message} Skipping primitive compression.`);continue}throw h}r.set(o,u);let d=e.createAccessorDef(c);if(d.count=u.numIndices,e.accessorIndexMap.set(c,l.length),l.push(d),u.numVertices>65534&&Be.getComponentSize(d.componentType)<=2)d.componentType=Be.ComponentType.UNSIGNED_INT;else if(u.numVertices>254&&Be.getComponentSize(d.componentType)<=1)d.componentType=Be.ComponentType.UNSIGNED_SHORT;for(let h of a.listSemantics()){let b=a.getAttribute(h);if(u.attributeIDs[h]===void 0)continue;let m=e.createAccessorDef(b);m.count=u.numVertices,e.accessorIndexMap.set(b,l.length),l.push(m)}let f=a.getAttribute("POSITION").getBuffer()||this.document.getRoot().listBuffers()[0];if(!e.otherBufferViews.has(f))e.otherBufferViews.set(f,[]);e.otherBufferViews.get(f).push(u.data)}return n.debug(`[${tn}] Compressed ${i.size} primitives.`),e.extensionData[tn]={primitiveHashMap:i,primitiveEncodingMap:r},this}write(e){let t=e.extensionData[tn];for(let n of this.document.getRoot().listMeshes()){let i=e.jsonDoc.json.meshes[e.meshIndexMap.get(n)];for(let r=0;r<n.listPrimitives().length;r++){let s=n.listPrimitives()[r],a=i.primitives[r],o=t.primitiveHashMap.get(s);if(!o)continue;let c=t.primitiveEncodingMap.get(o);if(!c)continue;a.extensions=a.extensions||{},a.extensions[tn]={bufferView:e.otherBufferViewsIndexMap.get(c.data),attributes:c.attributeIDs}}}if(!t.primitiveHashMap.size){let n=e.jsonDoc.json;n.extensionsUsed=(n.extensionsUsed||[]).filter((i)=>i!==tn),n.extensionsRequired=(n.extensionsRequired||[]).filter((i)=>i!==tn)}return this}};pS=class e extends nt{static EXTENSION_NAME=Hr;static Type={POINT:"point",SPOT:"spot",DIRECTIONAL:"directional"};init(){this.extensionName=Hr,this.propertyType="Light",this.parentTypes=[te.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{color:[1,1,1],intensity:1,type:e.Type.POINT,range:null,innerConeAngle:0,outerConeAngle:Math.PI/4})}getColor(){return this.get("color")}setColor(t){return this.set("color",t)}getIntensity(){return this.get("intensity")}setIntensity(t){return this.set("intensity",t)}getType(){return this.get("type")}setType(t){return this.set("type",t)}getRange(){return this.get("range")}setRange(t){return this.set("range",t)}getInnerConeAngle(){return this.get("innerConeAngle")}setInnerConeAngle(t){return this.set("innerConeAngle",t)}getOuterConeAngle(){return this.get("outerConeAngle")}setOuterConeAngle(t){return this.set("outerConeAngle",t)}},j2=class extends _t{extensionName=Hr;static EXTENSION_NAME=Hr;createLight(e=""){return new pS(this.document.getGraph(),e)}read(e){let t=e.jsonDoc;if(!t.json.extensions||!t.json.extensions.KHR_lights_punctual)return this;let n=(t.json.extensions.KHR_lights_punctual.lights||[]).map((i)=>{let r=this.createLight().setName(i.name||"").setType(i.type);if(i.extras)r.setExtras(i.extras);if(i.color!==void 0)r.setColor(i.color);if(i.intensity!==void 0)r.setIntensity(i.intensity);if(i.range!==void 0)r.setRange(i.range);if(i.spot?.innerConeAngle!==void 0)r.setInnerConeAngle(i.spot.innerConeAngle);if(i.spot?.outerConeAngle!==void 0)r.setOuterConeAngle(i.spot.outerConeAngle);return r});return t.json.nodes.forEach((i,r)=>{if(!i.extensions||!i.extensions.KHR_lights_punctual)return;let s=i.extensions[Hr];e.nodes[r].setExtension(Hr,n[s.light])}),this}write(e){let t=e.jsonDoc;if(this.properties.size===0)return this;let n=[],i=new Map;for(let r of this.properties){let s=r,a=e.createPropertyDef(r);if(a.type=s.getType(),!pt.eq(s.getColor(),[1,1,1]))a.color=s.getColor();if(s.getIntensity()!==1)a.intensity=s.getIntensity();if(s.getRange()!=null)a.range=s.getRange();if(s.getName())a.name=s.getName();if(s.getType()===pS.Type.SPOT)a.spot={innerConeAngle:s.getInnerConeAngle(),outerConeAngle:s.getOuterConeAngle()};n.push(a),i.set(s,n.length-1)}return this.document.getRoot().listNodes().forEach((r)=>{let s=r.getExtension(Hr);if(s){let a=e.nodeIndexMap.get(r),o=t.json.nodes[a];o.extensions=o.extensions||{},o.extensions[Hr]={light:i.get(s)}}}),t.json.extensions=t.json.extensions||{},t.json.extensions[Hr]={lights:n},this}},{R:H2,G:G2,B:$2}=Ai,K2=class extends nt{static EXTENSION_NAME=ks;init(){this.extensionName=ks,this.propertyType="Anisotropy",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{anisotropyStrength:0,anisotropyRotation:0,anisotropyTexture:null,anisotropyTextureInfo:new wt(this.graph,"anisotropyTextureInfo")})}getAnisotropyStrength(){return this.get("anisotropyStrength")}setAnisotropyStrength(e){return this.set("anisotropyStrength",e)}getAnisotropyRotation(){return this.get("anisotropyRotation")}setAnisotropyRotation(e){return this.set("anisotropyRotation",e)}getAnisotropyTexture(){return this.getRef("anisotropyTexture")}getAnisotropyTextureInfo(){return this.getRef("anisotropyTexture")?this.getRef("anisotropyTextureInfo"):null}setAnisotropyTexture(e){return this.setRef("anisotropyTexture",e,{channels:H2|G2|$2})}},W2=class extends _t{static EXTENSION_NAME=ks;extensionName=ks;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createAnisotropy(){return new K2(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_anisotropy){let a=this.createAnisotropy();e.materials[s].setExtension(ks,a);let o=r.extensions[ks];if(o.extras)a.setExtras(o.extras);if(o.anisotropyStrength!==void 0)a.setAnisotropyStrength(o.anisotropyStrength);if(o.anisotropyRotation!==void 0)a.setAnisotropyRotation(o.anisotropyRotation);if(o.anisotropyTexture!==void 0){let c=o.anisotropyTexture,l=e.textures[i[c.index].source];a.setAnisotropyTexture(l),e.setTextureInfo(a.getAnisotropyTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(ks);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[ks]=a,i.getAnisotropyStrength()>0)a.anisotropyStrength=i.getAnisotropyStrength();if(i.getAnisotropyRotation()!==0)a.anisotropyRotation=i.getAnisotropyRotation();if(i.getAnisotropyTexture()){let o=i.getAnisotropyTexture(),c=i.getAnisotropyTextureInfo();a.anisotropyTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:mS,G:gS,B:X2}=Ai,q2=class extends nt{static EXTENSION_NAME=Ds;init(){this.extensionName=Ds,this.propertyType="Clearcoat",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{clearcoatFactor:0,clearcoatTexture:null,clearcoatTextureInfo:new wt(this.graph,"clearcoatTextureInfo"),clearcoatRoughnessFactor:0,clearcoatRoughnessTexture:null,clearcoatRoughnessTextureInfo:new wt(this.graph,"clearcoatRoughnessTextureInfo"),clearcoatNormalScale:1,clearcoatNormalTexture:null,clearcoatNormalTextureInfo:new wt(this.graph,"clearcoatNormalTextureInfo")})}getClearcoatFactor(){return this.get("clearcoatFactor")}setClearcoatFactor(e){return this.set("clearcoatFactor",e)}getClearcoatTexture(){return this.getRef("clearcoatTexture")}getClearcoatTextureInfo(){return this.getRef("clearcoatTexture")?this.getRef("clearcoatTextureInfo"):null}setClearcoatTexture(e){return this.setRef("clearcoatTexture",e,{channels:mS})}getClearcoatRoughnessFactor(){return this.get("clearcoatRoughnessFactor")}setClearcoatRoughnessFactor(e){return this.set("clearcoatRoughnessFactor",e)}getClearcoatRoughnessTexture(){return this.getRef("clearcoatRoughnessTexture")}getClearcoatRoughnessTextureInfo(){return this.getRef("clearcoatRoughnessTexture")?this.getRef("clearcoatRoughnessTextureInfo"):null}setClearcoatRoughnessTexture(e){return this.setRef("clearcoatRoughnessTexture",e,{channels:gS})}getClearcoatNormalScale(){return this.get("clearcoatNormalScale")}setClearcoatNormalScale(e){return this.set("clearcoatNormalScale",e)}getClearcoatNormalTexture(){return this.getRef("clearcoatNormalTexture")}getClearcoatNormalTextureInfo(){return this.getRef("clearcoatNormalTexture")?this.getRef("clearcoatNormalTextureInfo"):null}setClearcoatNormalTexture(e){return this.setRef("clearcoatNormalTexture",e,{channels:mS|gS|X2})}},J2=class extends _t{static EXTENSION_NAME=Ds;extensionName=Ds;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createClearcoat(){return new q2(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_clearcoat){let a=this.createClearcoat();e.materials[s].setExtension(Ds,a);let o=r.extensions[Ds];if(o.extras)a.setExtras(o.extras);if(o.clearcoatFactor!==void 0)a.setClearcoatFactor(o.clearcoatFactor);if(o.clearcoatRoughnessFactor!==void 0)a.setClearcoatRoughnessFactor(o.clearcoatRoughnessFactor);if(o.clearcoatTexture!==void 0){let c=o.clearcoatTexture,l=e.textures[i[c.index].source];a.setClearcoatTexture(l),e.setTextureInfo(a.getClearcoatTextureInfo(),c)}if(o.clearcoatRoughnessTexture!==void 0){let c=o.clearcoatRoughnessTexture,l=e.textures[i[c.index].source];a.setClearcoatRoughnessTexture(l),e.setTextureInfo(a.getClearcoatRoughnessTextureInfo(),c)}if(o.clearcoatNormalTexture!==void 0){let c=o.clearcoatNormalTexture,l=e.textures[i[c.index].source];if(a.setClearcoatNormalTexture(l),e.setTextureInfo(a.getClearcoatNormalTextureInfo(),c),c.scale!==void 0)a.setClearcoatNormalScale(c.scale)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Ds);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Ds]=a,a.clearcoatFactor=i.getClearcoatFactor(),a.clearcoatRoughnessFactor=i.getClearcoatRoughnessFactor(),i.getClearcoatTexture()){let o=i.getClearcoatTexture(),c=i.getClearcoatTextureInfo();a.clearcoatTexture=e.createTextureInfoDef(o,c)}if(i.getClearcoatRoughnessTexture()){let o=i.getClearcoatRoughnessTexture(),c=i.getClearcoatRoughnessTextureInfo();a.clearcoatRoughnessTexture=e.createTextureInfoDef(o,c)}if(i.getClearcoatNormalTexture()){let o=i.getClearcoatNormalTexture(),c=i.getClearcoatNormalTextureInfo();if(a.clearcoatNormalTexture=e.createTextureInfoDef(o,c),i.getClearcoatNormalScale()!==1)a.clearcoatNormalTexture.scale=i.getClearcoatNormalScale()}}}),this}},{R:Z2,G:Y2,B:Q2,A:eU}=Ai,tU=class extends nt{static EXTENSION_NAME=Ls;init(){this.extensionName=Ls,this.propertyType="DiffuseTransmission",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseTransmissionFactor:0,diffuseTransmissionTexture:null,diffuseTransmissionTextureInfo:new wt(this.graph,"diffuseTransmissionTextureInfo"),diffuseTransmissionColorFactor:[1,1,1],diffuseTransmissionColorTexture:null,diffuseTransmissionColorTextureInfo:new wt(this.graph,"diffuseTransmissionColorTextureInfo")})}getDiffuseTransmissionFactor(){return this.get("diffuseTransmissionFactor")}setDiffuseTransmissionFactor(e){return this.set("diffuseTransmissionFactor",e)}getDiffuseTransmissionTexture(){return this.getRef("diffuseTransmissionTexture")}getDiffuseTransmissionTextureInfo(){return this.getRef("diffuseTransmissionTexture")?this.getRef("diffuseTransmissionTextureInfo"):null}setDiffuseTransmissionTexture(e){return this.setRef("diffuseTransmissionTexture",e,{channels:eU})}getDiffuseTransmissionColorFactor(){return this.get("diffuseTransmissionColorFactor")}setDiffuseTransmissionColorFactor(e){return this.set("diffuseTransmissionColorFactor",e)}getDiffuseTransmissionColorTexture(){return this.getRef("diffuseTransmissionColorTexture")}getDiffuseTransmissionColorTextureInfo(){return this.getRef("diffuseTransmissionColorTexture")?this.getRef("diffuseTransmissionColorTextureInfo"):null}setDiffuseTransmissionColorTexture(e){return this.setRef("diffuseTransmissionColorTexture",e,{channels:Z2|Y2|Q2})}},nU=class extends _t{extensionName=Ls;static EXTENSION_NAME=Ls;createDiffuseTransmission(){return new tU(this.document.getGraph())}read(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_diffuse_transmission){let a=this.createDiffuseTransmission();e.materials[s].setExtension(Ls,a);let o=r.extensions[Ls];if(o.extras)a.setExtras(o.extras);if(o.diffuseTransmissionFactor!==void 0)a.setDiffuseTransmissionFactor(o.diffuseTransmissionFactor);if(o.diffuseTransmissionColorFactor!==void 0)a.setDiffuseTransmissionColorFactor(o.diffuseTransmissionColorFactor);if(o.diffuseTransmissionTexture!==void 0){let c=o.diffuseTransmissionTexture,l=e.textures[i[c.index].source];a.setDiffuseTransmissionTexture(l),e.setTextureInfo(a.getDiffuseTransmissionTextureInfo(),c)}if(o.diffuseTransmissionColorTexture!==void 0){let c=o.diffuseTransmissionColorTexture,l=e.textures[i[c.index].source];a.setDiffuseTransmissionColorTexture(l),e.setTextureInfo(a.getDiffuseTransmissionColorTextureInfo(),c)}}}),this}write(e){let t=e.jsonDoc;for(let n of this.document.getRoot().listMaterials()){let i=n.getExtension(Ls);if(!i)continue;let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Ls]=a,a.diffuseTransmissionFactor=i.getDiffuseTransmissionFactor(),a.diffuseTransmissionColorFactor=i.getDiffuseTransmissionColorFactor(),i.getDiffuseTransmissionTexture()){let o=i.getDiffuseTransmissionTexture(),c=i.getDiffuseTransmissionTextureInfo();a.diffuseTransmissionTexture=e.createTextureInfoDef(o,c)}if(i.getDiffuseTransmissionColorTexture()){let o=i.getDiffuseTransmissionColorTexture(),c=i.getDiffuseTransmissionColorTextureInfo();a.diffuseTransmissionColorTexture=e.createTextureInfoDef(o,c)}}return this}},iU=class extends nt{static EXTENSION_NAME=Fs;init(){this.extensionName=Fs,this.propertyType="Dispersion",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{dispersion:0})}getDispersion(){return this.get("dispersion")}setDispersion(e){return this.set("dispersion",e)}},rU=class extends _t{static EXTENSION_NAME=Fs;extensionName=Fs;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createDispersion(){return new iU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){return(e.jsonDoc.json.materials||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_materials_dispersion){let i=this.createDispersion();e.materials[n].setExtension(Fs,i);let r=t.extensions[Fs];if(r.extras)i.setExtras(r.extras);if(r.dispersion!==void 0)i.setDispersion(r.dispersion)}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Fs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);s.extensions=s.extensions||{},s.extensions[Fs]=a,a.dispersion=i.getDispersion()}}),this}},sU=class extends nt{static EXTENSION_NAME=Us;init(){this.extensionName=Us,this.propertyType="EmissiveStrength",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{emissiveStrength:1})}getEmissiveStrength(){return this.get("emissiveStrength")}setEmissiveStrength(e){return this.set("emissiveStrength",e)}},aU=class extends _t{static EXTENSION_NAME=Us;extensionName=Us;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createEmissiveStrength(){return new sU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){return(e.jsonDoc.json.materials||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_materials_emissive_strength){let i=this.createEmissiveStrength();e.materials[n].setExtension(Us,i);let r=t.extensions[Us];if(r.extras)i.setExtras(r.extras);if(r.emissiveStrength!==void 0)i.setEmissiveStrength(r.emissiveStrength)}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Us);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);s.extensions=s.extensions||{},s.extensions[Us]=a,a.emissiveStrength=i.getEmissiveStrength()}}),this}},oU=class extends nt{static EXTENSION_NAME=Bs;init(){this.extensionName=Bs,this.propertyType="IOR",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{ior:1.5})}getIOR(){return this.get("ior")}setIOR(e){return this.set("ior",e)}},CS=class extends _t{static EXTENSION_NAME=Bs;extensionName=Bs;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createIOR(){return new oU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){return(e.jsonDoc.json.materials||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_materials_ior){let i=this.createIOR();e.materials[n].setExtension(Bs,i);let r=t.extensions[Bs];if(r.extras)i.setExtras(r.extras);if(r.ior!==void 0)i.setIOR(r.ior)}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Bs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);s.extensions=s.extensions||{},s.extensions[Bs]=a,a.ior=i.getIOR()}}),this}},{R:cU,G:lU}=Ai,uU=class extends nt{static EXTENSION_NAME=zs;init(){this.extensionName=zs,this.propertyType="Iridescence",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{iridescenceFactor:0,iridescenceTexture:null,iridescenceTextureInfo:new wt(this.graph,"iridescenceTextureInfo"),iridescenceIOR:1.3,iridescenceThicknessMinimum:100,iridescenceThicknessMaximum:400,iridescenceThicknessTexture:null,iridescenceThicknessTextureInfo:new wt(this.graph,"iridescenceThicknessTextureInfo")})}getIridescenceFactor(){return this.get("iridescenceFactor")}setIridescenceFactor(e){return this.set("iridescenceFactor",e)}getIridescenceTexture(){return this.getRef("iridescenceTexture")}getIridescenceTextureInfo(){return this.getRef("iridescenceTexture")?this.getRef("iridescenceTextureInfo"):null}setIridescenceTexture(e){return this.setRef("iridescenceTexture",e,{channels:cU})}getIridescenceIOR(){return this.get("iridescenceIOR")}setIridescenceIOR(e){return this.set("iridescenceIOR",e)}getIridescenceThicknessMinimum(){return this.get("iridescenceThicknessMinimum")}setIridescenceThicknessMinimum(e){return this.set("iridescenceThicknessMinimum",e)}getIridescenceThicknessMaximum(){return this.get("iridescenceThicknessMaximum")}setIridescenceThicknessMaximum(e){return this.set("iridescenceThicknessMaximum",e)}getIridescenceThicknessTexture(){return this.getRef("iridescenceThicknessTexture")}getIridescenceThicknessTextureInfo(){return this.getRef("iridescenceThicknessTexture")?this.getRef("iridescenceThicknessTextureInfo"):null}setIridescenceThicknessTexture(e){return this.setRef("iridescenceThicknessTexture",e,{channels:lU})}},dU=class extends _t{static EXTENSION_NAME=zs;extensionName=zs;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createIridescence(){return new uU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_iridescence){let a=this.createIridescence();e.materials[s].setExtension(zs,a);let o=r.extensions[zs];if(o.extras)a.setExtras(o.extras);if(o.iridescenceFactor!==void 0)a.setIridescenceFactor(o.iridescenceFactor);if(o.iridescenceIor!==void 0)a.setIridescenceIOR(o.iridescenceIor);if(o.iridescenceThicknessMinimum!==void 0)a.setIridescenceThicknessMinimum(o.iridescenceThicknessMinimum);if(o.iridescenceThicknessMaximum!==void 0)a.setIridescenceThicknessMaximum(o.iridescenceThicknessMaximum);if(o.iridescenceTexture!==void 0){let c=o.iridescenceTexture,l=e.textures[i[c.index].source];a.setIridescenceTexture(l),e.setTextureInfo(a.getIridescenceTextureInfo(),c)}if(o.iridescenceThicknessTexture!==void 0){let c=o.iridescenceThicknessTexture,l=e.textures[i[c.index].source];a.setIridescenceThicknessTexture(l),e.setTextureInfo(a.getIridescenceThicknessTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(zs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[zs]=a,i.getIridescenceFactor()>0)a.iridescenceFactor=i.getIridescenceFactor();if(i.getIridescenceIOR()!==1.3)a.iridescenceIor=i.getIridescenceIOR();if(i.getIridescenceThicknessMinimum()!==100)a.iridescenceThicknessMinimum=i.getIridescenceThicknessMinimum();if(i.getIridescenceThicknessMaximum()!==400)a.iridescenceThicknessMaximum=i.getIridescenceThicknessMaximum();if(i.getIridescenceTexture()){let o=i.getIridescenceTexture(),c=i.getIridescenceTextureInfo();a.iridescenceTexture=e.createTextureInfoDef(o,c)}if(i.getIridescenceThicknessTexture()){let o=i.getIridescenceThicknessTexture(),c=i.getIridescenceThicknessTextureInfo();a.iridescenceThicknessTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:bS,G:xS,B:yS,A:_S}=Ai,fU=class extends nt{static EXTENSION_NAME=Vs;init(){this.extensionName=Vs,this.propertyType="PBRSpecularGlossiness",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseFactor:[1,1,1,1],diffuseTexture:null,diffuseTextureInfo:new wt(this.graph,"diffuseTextureInfo"),specularFactor:[1,1,1],glossinessFactor:1,specularGlossinessTexture:null,specularGlossinessTextureInfo:new wt(this.graph,"specularGlossinessTextureInfo")})}getDiffuseFactor(){return this.get("diffuseFactor")}setDiffuseFactor(e){return this.set("diffuseFactor",e)}getDiffuseTexture(){return this.getRef("diffuseTexture")}getDiffuseTextureInfo(){return this.getRef("diffuseTexture")?this.getRef("diffuseTextureInfo"):null}setDiffuseTexture(e){return this.setRef("diffuseTexture",e,{channels:bS|xS|yS|_S,isColor:!0})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(e){return this.set("specularFactor",e)}getGlossinessFactor(){return this.get("glossinessFactor")}setGlossinessFactor(e){return this.set("glossinessFactor",e)}getSpecularGlossinessTexture(){return this.getRef("specularGlossinessTexture")}getSpecularGlossinessTextureInfo(){return this.getRef("specularGlossinessTexture")?this.getRef("specularGlossinessTextureInfo"):null}setSpecularGlossinessTexture(e){return this.setRef("specularGlossinessTexture",e,{channels:bS|xS|yS|_S})}},NS=class extends _t{static EXTENSION_NAME=Vs;extensionName=Vs;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createPBRSpecularGlossiness(){return new fU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_pbrSpecularGlossiness){let a=this.createPBRSpecularGlossiness();e.materials[s].setExtension(Vs,a);let o=r.extensions[Vs];if(o.extras)a.setExtras(o.extras);if(o.diffuseFactor!==void 0)a.setDiffuseFactor(o.diffuseFactor);if(o.specularFactor!==void 0)a.setSpecularFactor(o.specularFactor);if(o.glossinessFactor!==void 0)a.setGlossinessFactor(o.glossinessFactor);if(o.diffuseTexture!==void 0){let c=o.diffuseTexture,l=e.textures[i[c.index].source];a.setDiffuseTexture(l),e.setTextureInfo(a.getDiffuseTextureInfo(),c)}if(o.specularGlossinessTexture!==void 0){let c=o.specularGlossinessTexture,l=e.textures[i[c.index].source];a.setSpecularGlossinessTexture(l),e.setTextureInfo(a.getSpecularGlossinessTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Vs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Vs]=a,a.diffuseFactor=i.getDiffuseFactor(),a.specularFactor=i.getSpecularFactor(),a.glossinessFactor=i.getGlossinessFactor(),i.getDiffuseTexture()){let o=i.getDiffuseTexture(),c=i.getDiffuseTextureInfo();a.diffuseTexture=e.createTextureInfoDef(o,c)}if(i.getSpecularGlossinessTexture()){let o=i.getSpecularGlossinessTexture(),c=i.getSpecularGlossinessTextureInfo();a.specularGlossinessTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:hU,G:pU,B:mU,A:gU}=Ai,bU=class extends nt{static EXTENSION_NAME=js;init(){this.extensionName=js,this.propertyType="Sheen",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{sheenColorFactor:[0,0,0],sheenColorTexture:null,sheenColorTextureInfo:new wt(this.graph,"sheenColorTextureInfo"),sheenRoughnessFactor:0,sheenRoughnessTexture:null,sheenRoughnessTextureInfo:new wt(this.graph,"sheenRoughnessTextureInfo")})}getSheenColorFactor(){return this.get("sheenColorFactor")}setSheenColorFactor(e){return this.set("sheenColorFactor",e)}getSheenColorTexture(){return this.getRef("sheenColorTexture")}getSheenColorTextureInfo(){return this.getRef("sheenColorTexture")?this.getRef("sheenColorTextureInfo"):null}setSheenColorTexture(e){return this.setRef("sheenColorTexture",e,{channels:hU|pU|mU,isColor:!0})}getSheenRoughnessFactor(){return this.get("sheenRoughnessFactor")}setSheenRoughnessFactor(e){return this.set("sheenRoughnessFactor",e)}getSheenRoughnessTexture(){return this.getRef("sheenRoughnessTexture")}getSheenRoughnessTextureInfo(){return this.getRef("sheenRoughnessTexture")?this.getRef("sheenRoughnessTextureInfo"):null}setSheenRoughnessTexture(e){return this.setRef("sheenRoughnessTexture",e,{channels:gU})}},xU=class extends _t{static EXTENSION_NAME=js;extensionName=js;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createSheen(){return new bU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_sheen){let a=this.createSheen();e.materials[s].setExtension(js,a);let o=r.extensions[js];if(o.extras)a.setExtras(o.extras);if(o.sheenColorFactor!==void 0)a.setSheenColorFactor(o.sheenColorFactor);if(o.sheenRoughnessFactor!==void 0)a.setSheenRoughnessFactor(o.sheenRoughnessFactor);if(o.sheenColorTexture!==void 0){let c=o.sheenColorTexture,l=e.textures[i[c.index].source];a.setSheenColorTexture(l),e.setTextureInfo(a.getSheenColorTextureInfo(),c)}if(o.sheenRoughnessTexture!==void 0){let c=o.sheenRoughnessTexture,l=e.textures[i[c.index].source];a.setSheenRoughnessTexture(l),e.setTextureInfo(a.getSheenRoughnessTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(js);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[js]=a,a.sheenColorFactor=i.getSheenColorFactor(),a.sheenRoughnessFactor=i.getSheenRoughnessFactor(),i.getSheenColorTexture()){let o=i.getSheenColorTexture(),c=i.getSheenColorTextureInfo();a.sheenColorTexture=e.createTextureInfoDef(o,c)}if(i.getSheenRoughnessTexture()){let o=i.getSheenRoughnessTexture(),c=i.getSheenRoughnessTextureInfo();a.sheenRoughnessTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:yU,G:_U,B:vU,A:EU}=Ai,TU=class extends nt{static EXTENSION_NAME=Hs;init(){this.extensionName=Hs,this.propertyType="Specular",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{specularFactor:1,specularTexture:null,specularTextureInfo:new wt(this.graph,"specularTextureInfo"),specularColorFactor:[1,1,1],specularColorTexture:null,specularColorTextureInfo:new wt(this.graph,"specularColorTextureInfo")})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(e){return this.set("specularFactor",e)}getSpecularColorFactor(){return this.get("specularColorFactor")}setSpecularColorFactor(e){return this.set("specularColorFactor",e)}getSpecularTexture(){return this.getRef("specularTexture")}getSpecularTextureInfo(){return this.getRef("specularTexture")?this.getRef("specularTextureInfo"):null}setSpecularTexture(e){return this.setRef("specularTexture",e,{channels:EU})}getSpecularColorTexture(){return this.getRef("specularColorTexture")}getSpecularColorTextureInfo(){return this.getRef("specularColorTexture")?this.getRef("specularColorTextureInfo"):null}setSpecularColorTexture(e){return this.setRef("specularColorTexture",e,{channels:yU|_U|vU,isColor:!0})}},PS=class extends _t{static EXTENSION_NAME=Hs;extensionName=Hs;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createSpecular(){return new TU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_specular){let a=this.createSpecular();e.materials[s].setExtension(Hs,a);let o=r.extensions[Hs];if(o.extras)a.setExtras(o.extras);if(o.specularFactor!==void 0)a.setSpecularFactor(o.specularFactor);if(o.specularColorFactor!==void 0)a.setSpecularColorFactor(o.specularColorFactor);if(o.specularTexture!==void 0){let c=o.specularTexture,l=e.textures[i[c.index].source];a.setSpecularTexture(l),e.setTextureInfo(a.getSpecularTextureInfo(),c)}if(o.specularColorTexture!==void 0){let c=o.specularColorTexture,l=e.textures[i[c.index].source];a.setSpecularColorTexture(l),e.setTextureInfo(a.getSpecularColorTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Hs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Hs]=a,i.getSpecularFactor()!==1)a.specularFactor=i.getSpecularFactor();if(!pt.eq(i.getSpecularColorFactor(),[1,1,1]))a.specularColorFactor=i.getSpecularColorFactor();if(i.getSpecularTexture()){let o=i.getSpecularTexture(),c=i.getSpecularTextureInfo();a.specularTexture=e.createTextureInfoDef(o,c)}if(i.getSpecularColorTexture()){let o=i.getSpecularColorTexture(),c=i.getSpecularColorTextureInfo();a.specularColorTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:AU}=Ai,wU=class extends nt{static EXTENSION_NAME=Gs;init(){this.extensionName=Gs,this.propertyType="Transmission",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{transmissionFactor:0,transmissionTexture:null,transmissionTextureInfo:new wt(this.graph,"transmissionTextureInfo")})}getTransmissionFactor(){return this.get("transmissionFactor")}setTransmissionFactor(e){return this.set("transmissionFactor",e)}getTransmissionTexture(){return this.getRef("transmissionTexture")}getTransmissionTextureInfo(){return this.getRef("transmissionTexture")?this.getRef("transmissionTextureInfo"):null}setTransmissionTexture(e){return this.setRef("transmissionTexture",e,{channels:AU})}},SU=class extends _t{static EXTENSION_NAME=Gs;extensionName=Gs;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createTransmission(){return new wU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_transmission){let a=this.createTransmission();e.materials[s].setExtension(Gs,a);let o=r.extensions[Gs];if(o.extras)a.setExtras(o.extras);if(o.transmissionFactor!==void 0)a.setTransmissionFactor(o.transmissionFactor);if(o.transmissionTexture!==void 0){let c=o.transmissionTexture,l=e.textures[i[c.index].source];a.setTransmissionTexture(l),e.setTextureInfo(a.getTransmissionTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Gs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Gs]=a,a.transmissionFactor=i.getTransmissionFactor(),i.getTransmissionTexture()){let o=i.getTransmissionTexture(),c=i.getTransmissionTextureInfo();a.transmissionTexture=e.createTextureInfoDef(o,c)}}}),this}},MU=class extends nt{static EXTENSION_NAME=Jo;init(){this.extensionName=Jo,this.propertyType="Unlit",this.parentTypes=[te.MATERIAL]}},OS=class extends _t{static EXTENSION_NAME=Jo;extensionName=Jo;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createUnlit(){return new MU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){return(e.jsonDoc.json.materials||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_materials_unlit)e.materials[n].setExtension(Jo,this.createUnlit())}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{if(n.getExtension("KHR_materials_unlit")){let i=e.materialIndexMap.get(n),r=t.json.materials[i];r.extensions=r.extensions||{},r.extensions[Jo]={}}}),this}},RU=class extends nt{static EXTENSION_NAME=fi;init(){this.extensionName=fi,this.propertyType="Mapping",this.parentTypes=["MappingList"]}getDefaults(){return Object.assign(super.getDefaults(),{material:null,variants:new It})}getMaterial(){return this.getRef("material")}setMaterial(e){return this.setRef("material",e)}addVariant(e){return this.addRef("variants",e)}removeVariant(e){return this.removeRef("variants",e)}listVariants(){return this.listRefs("variants")}},IU=class extends nt{static EXTENSION_NAME=fi;init(){this.extensionName=fi,this.propertyType="MappingList",this.parentTypes=[te.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{mappings:new It})}addMapping(e){return this.addRef("mappings",e)}removeMapping(e){return this.removeRef("mappings",e)}listMappings(){return this.listRefs("mappings")}},vS=class extends nt{static EXTENSION_NAME=fi;init(){this.extensionName=fi,this.propertyType="Variant",this.parentTypes=["MappingList"]}},CU=class extends _t{extensionName=fi;static EXTENSION_NAME=fi;createMappingList(){return new IU(this.document.getGraph())}createVariant(e=""){return new vS(this.document.getGraph(),e)}createMapping(){return new RU(this.document.getGraph())}listVariants(){return Array.from(this.properties).filter((e)=>e instanceof vS)}read(e){let t=e.jsonDoc;if(!t.json.extensions||!t.json.extensions.KHR_materials_variants)return this;let n=(t.json.extensions.KHR_materials_variants.variants||[]).map((i)=>this.createVariant().setName(i.name||""));return(t.json.meshes||[]).forEach((i,r)=>{let s=e.meshes[r];(i.primitives||[]).forEach((a,o)=>{if(!a.extensions||!a.extensions.KHR_materials_variants)return;let c=this.createMappingList(),l=a.extensions[fi];for(let u of l.mappings){let d=this.createMapping();if(u.material!==void 0)d.setMaterial(e.materials[u.material]);for(let f of u.variants||[])d.addVariant(n[f]);c.addMapping(d)}s.listPrimitives()[o].setExtension(fi,c)})}),this}write(e){let t=e.jsonDoc,n=this.listVariants();if(!n.length)return this;let i=[],r=new Map;for(let s of n)r.set(s,i.length),i.push(e.createPropertyDef(s));for(let s of this.document.getRoot().listMeshes()){let a=e.meshIndexMap.get(s);s.listPrimitives().forEach((o,c)=>{let l=o.getExtension(fi);if(!l)return;let u=e.jsonDoc.json.meshes[a].primitives[c],d=l.listMappings().map((f)=>{let h=e.createPropertyDef(f),b=f.getMaterial();if(b)h.material=e.materialIndexMap.get(b);return h.variants=f.listVariants().map((m)=>r.get(m)),h});u.extensions=u.extensions||{},u.extensions[fi]={mappings:d}})}return t.json.extensions=t.json.extensions||{},t.json.extensions[fi]={variants:i},this}},{G:NU}=Ai,PU=class extends nt{static EXTENSION_NAME=$s;init(){this.extensionName=$s,this.propertyType="Volume",this.parentTypes=[te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{thicknessFactor:0,thicknessTexture:null,thicknessTextureInfo:new wt(this.graph,"thicknessTexture"),attenuationDistance:1/0,attenuationColor:[1,1,1]})}getThicknessFactor(){return this.get("thicknessFactor")}setThicknessFactor(e){return this.set("thicknessFactor",e)}getThicknessTexture(){return this.getRef("thicknessTexture")}getThicknessTextureInfo(){return this.getRef("thicknessTexture")?this.getRef("thicknessTextureInfo"):null}setThicknessTexture(e){return this.setRef("thicknessTexture",e,{channels:NU})}getAttenuationDistance(){return this.get("attenuationDistance")}setAttenuationDistance(e){return this.set("attenuationDistance",e)}getAttenuationColor(){return this.get("attenuationColor")}setAttenuationColor(e){return this.set("attenuationColor",e)}},OU=class extends _t{static EXTENSION_NAME=$s;extensionName=$s;prereadTypes=[te.MESH];prewriteTypes=[te.MESH];createVolume(){return new PU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_volume){let a=this.createVolume();e.materials[s].setExtension($s,a);let o=r.extensions[$s];if(o.extras)a.setExtras(o.extras);if(o.thicknessFactor!==void 0)a.setThicknessFactor(o.thicknessFactor);if(o.attenuationDistance!==void 0)a.setAttenuationDistance(o.attenuationDistance);if(o.attenuationColor!==void 0)a.setAttenuationColor(o.attenuationColor);if(o.thicknessTexture!==void 0){let c=o.thicknessTexture,l=e.textures[i[c.index].source];a.setThicknessTexture(l),e.setTextureInfo(a.getThicknessTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension($s);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[$s]=a,i.getThicknessFactor()>0)a.thicknessFactor=i.getThicknessFactor();if(Number.isFinite(i.getAttenuationDistance()))a.attenuationDistance=i.getAttenuationDistance();if(!pt.eq(i.getAttenuationColor(),[1,1,1]))a.attenuationColor=i.getAttenuationColor();if(i.getThicknessTexture()){let o=i.getThicknessTexture(),c=i.getThicknessTextureInfo();a.thicknessTexture=e.createTextureInfoDef(o,c)}}}),this}},kS=class extends _t{extensionName=rS;static EXTENSION_NAME=rS;read(e){return this}write(e){return this}},Hg=class extends _t{extensionName=sS;static EXTENSION_NAME=sS;read(e){return this}write(e){return this}},kU=class extends nt{static EXTENSION_NAME=Ks;init(){this.extensionName=Ks,this.propertyType="Visibility",this.parentTypes=[te.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{visible:!0})}getVisible(){return this.get("visible")}setVisible(e){return this.set("visible",e)}},DU=class extends _t{static EXTENSION_NAME=Ks;extensionName=Ks;createVisibility(){return new kU(this.document.getGraph())}read(e){return(e.jsonDoc.json.nodes||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_node_visibility){let i=this.createVisibility();e.nodes[n].setExtension(Ks,i);let r=t.extensions[Ks];if(r.visible!==void 0)i.setVisible(r.visible)}}),this}write(e){let t=e.jsonDoc;for(let n of this.document.getRoot().listNodes()){let i=n.getExtension(Ks);if(!i)continue;let r=e.nodeIndexMap.get(n),s=t.json.nodes[r];s.extensions=s.extensions||{},s.extensions[Ks]={visible:i.getVisible()}}return this}};Gg=class extends _t{static EXTENSION_NAME=cf;extensionName=cf;prereadTypes=[te.TEXTURE];static register(){Gi.registerFormat("image/ktx2",new FU)}preread(e){if(e.jsonDoc.json.textures)e.jsonDoc.json.textures.forEach((t)=>{if(t.extensions&&t.extensions.KHR_texture_basisu)t.source=t.extensions[cf].source});return this}read(e){return this}write(e){let t=e.jsonDoc;return this.document.getRoot().listTextures().forEach((n)=>{if(n.getMimeType()==="image/ktx2"){let i=e.imageIndexMap.get(n);t.json.textures.forEach((r)=>{if(r.source===i)r.extensions=r.extensions||{},r.extensions[cf]={source:r.source},delete r.source})}}),this}},UU=class extends nt{static EXTENSION_NAME=Ws;init(){this.extensionName=Ws,this.propertyType="Transform",this.parentTypes=[te.TEXTURE_INFO]}getDefaults(){return Object.assign(super.getDefaults(),{offset:[0,0],rotation:0,scale:[1,1],texCoord:null})}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getRotation(){return this.get("rotation")}setRotation(e){return this.set("rotation",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getTexCoord(){return this.get("texCoord")}setTexCoord(e){return this.set("texCoord",e)}},BU=class extends _t{extensionName=Ws;static EXTENSION_NAME=Ws;createTransform(){return new UU(this.document.getGraph())}read(e){for(let[t,n]of Array.from(e.textureInfos.entries())){if(!n.extensions||!n.extensions.KHR_texture_transform)continue;let i=this.createTransform(),r=n.extensions[Ws];if(r.offset!==void 0)i.setOffset(r.offset);if(r.rotation!==void 0)i.setRotation(r.rotation);if(r.scale!==void 0)i.setScale(r.scale);if(r.texCoord!==void 0)i.setTexCoord(r.texCoord);t.setExtension(Ws,i)}return this}write(e){let t=Array.from(e.textureInfoDefMap.entries());for(let[n,i]of t){let r=n.getExtension(Ws);if(!r)continue;i.extensions=i.extensions||{};let s={},a=pt.eq;if(!a(r.getOffset(),[0,0]))s.offset=r.getOffset();if(r.getRotation()!==0)s.rotation=r.getRotation();if(!a(r.getScale(),[1,1]))s.scale=r.getScale();if(r.getTexCoord()!=null)s.texCoord=r.getTexCoord();i.extensions[Ws]=s}return this}},zU=[te.ROOT,te.SCENE,te.NODE,te.MESH,te.MATERIAL,te.TEXTURE,te.ANIMATION],VU=class extends nt{static EXTENSION_NAME=$i;init(){this.extensionName=$i,this.propertyType="Packet",this.parentTypes=zU}getDefaults(){return Object.assign(super.getDefaults(),{context:{},properties:{}})}getContext(){return this.get("context")}setContext(e){return this.set("context",{...e})}listProperties(){return Object.keys(this.get("properties"))}getProperty(e){let t=this.get("properties");return e in t?t[e]:null}setProperty(e,t){this._assertContext(e);let n={...this.get("properties")};if(t)n[e]=t;else delete n[e];return this.set("properties",n)}toJSONLD(){return{"@context":Bg(this.get("context")),...Bg(this.get("properties"))}}fromJSONLD(e){e=Bg(e);let t=e["@context"];if(t)this.set("context",t);return delete e["@context"],this.set("properties",e)}_assertContext(e){if(!(e.split(":")[0]in this.get("context")))throw Error(`${$i}: Missing context for term, "${e}".`)}};jU=class extends _t{extensionName=$i;static EXTENSION_NAME=$i;createPacket(){return new VU(this.document.getGraph())}listPackets(){return Array.from(this.properties)}read(e){let t=e.jsonDoc.json.extensions?.[$i];if(!t||!t.packets)return this;let n=e.jsonDoc.json,i=this.document.getRoot(),r=t.packets.map((o)=>this.createPacket().fromJSONLD(o)),s=[[n.asset],n.scenes,n.nodes,n.meshes,n.materials,n.images,n.animations],a=[[i],i.listScenes(),i.listNodes(),i.listMeshes(),i.listMaterials(),i.listTextures(),i.listAnimations()];for(let o=0;o<s.length;o++){let c=s[o]||[];for(let l=0;l<c.length;l++){let u=c[l];if(u.extensions&&u.extensions.KHR_xmp_json_ld){let d=u.extensions[$i];a[o][l].setExtension($i,r[d.packet])}}}return this}write(e){let{json:t}=e.jsonDoc,n=[];for(let i of this.properties){n.push(i.toJSONLD());for(let r of i.listParents()){let s;switch(r.propertyType){case te.ROOT:s=t.asset;break;case te.SCENE:s=t.scenes[e.sceneIndexMap.get(r)];break;case te.NODE:s=t.nodes[e.nodeIndexMap.get(r)];break;case te.MESH:s=t.meshes[e.meshIndexMap.get(r)];break;case te.MATERIAL:s=t.materials[e.materialIndexMap.get(r)];break;case te.TEXTURE:s=t.images[e.imageIndexMap.get(r)];break;case te.ANIMATION:s=t.animations[e.animationIndexMap.get(r)];break;default:s=null,this.document.getLogger().warn(`[${$i}]: Unsupported parent property, "${r.propertyType}"`)}if(!s)continue;s.extensions=s.extensions||{},s.extensions[$i]={packet:n.length-1}}}if(n.length>0)t.extensions=t.extensions||{},t.extensions[$i]={packets:n};return this}},HU=[C2,N2,IS,j2,W2,J2,nU,rU,aU,CS,dU,NS,PS,xU,SU,OS,CU,OU,kS,Hg,DU,Gg,BU,jU],DS=[lf,MF,Ml,n2,AS,wS,...HU]});var FS=Jr(function(z5,LS){function GU(e){var t=Array(e);for(var n=0;n<e;++n)t[n]=n;return t}LS.exports=GU});var zS=Jr(function(V5,BS){/*!+ `},i=new bs(5,5,5),r=new Ei({name:"CubemapFromEquirect",uniforms:Ra(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Dn,blending:dr});r.uniforms.tEquirect.value=t;let s=new jt(i,r),a=t.minFilter;if(t.minFilter===fr)t.minFilter=Tn;return new Xm(1,10,this).update(e,s),t.minFilter=a,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)}};AD={[zp]:"LINEAR_TONE_MAPPING",[Vp]:"REINHARD_TONE_MAPPING",[jp]:"CINEON_TONE_MAPPING",[Jc]:"ACES_FILMIC_TONE_MAPPING",[Gp]:"AGX_TONE_MAPPING",[$p]:"NEUTRAL_TONE_MAPPING",[Hp]:"CUSTOM_TONE_MAPPING"};MA=new en,lg=new Ma(1,1),RA=new Sd,IA=new Fm,CA=new Od,cA=[],lA=[],uA=new Float32Array(16),dA=new Float32Array(9),fA=new Float32Array(4);og=/(\w+)(\])?(\[|\.)?/g;mA=new tt;xL={[zp]:"Linear",[Vp]:"Reinhard",[jp]:"Cineon",[Jc]:"ACESFilmic",[Gp]:"AgX",[$p]:"Neutral",[Hp]:"Custom"};$d=new j;AL=/^[ \t]*#include +<([\w\d./]+)>/gm;wL=new Map;ML=/#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;IL={[Xc]:"SHADOWMAP_TYPE_PCF",[Ao]:"SHADOWMAP_TYPE_VSM"};NL={[So]:"ENVMAP_TYPE_CUBE",[va]:"ENVMAP_TYPE_CUBE",[Zc]:"ENVMAP_TYPE_CUBE_UV"};OL={[va]:"ENVMAP_MODE_REFRACTION"};DL={[RT]:"ENVMAP_BLENDING_MULTIPLY",[IT]:"ENVMAP_BLENDING_MIX",[CT]:"ENVMAP_BLENDING_ADD"};QL=[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)],e8=[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)],AA=new Je,gl=new j,cg=new j;FA=class FA extends Vi{constructor(e,t){super();let n=this,i=null,r=1,s=null,a="local-floor",o=1,c=null,l=null,u=null,d=null,f=null,h=null,b=typeof XRWebGLBinding<"u",m=new LA,g={},p=t.getContextAttributes(),x=null,_=null,y=[],v=[],E=new Ke,w=null,T=null,A=new hn;A.viewport=new Pt;let P=new hn;P.viewport=new Pt;let S=[A,P],R=new qm,k=null,C=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(J){let F=y[J];if(F===void 0)F=new nl,y[J]=F;return F.getTargetRaySpace()},this.getControllerGrip=function(J){let F=y[J];if(F===void 0)F=new nl,y[J]=F;return F.getGripSpace()},this.getHand=function(J){let F=y[J];if(F===void 0)F=new nl,y[J]=F;return F.getHandSpace()};function U(J){let F=v.indexOf(J.inputSource);if(F===-1)return;let W=y[F];if(W!==void 0)W.update(J.inputSource,J.frame,c||s),W.dispatchEvent({type:J.type,data:J.inputSource})}function L(){i.removeEventListener("select",U),i.removeEventListener("selectstart",U),i.removeEventListener("selectend",U),i.removeEventListener("squeeze",U),i.removeEventListener("squeezestart",U),i.removeEventListener("squeezeend",U),i.removeEventListener("end",L),i.removeEventListener("inputsourceschange",O);for(let J=0;J<y.length;J++){let F=v[J];if(F===null)continue;v[J]=null,y[J].disconnect(F)}k=null,C=null,m.reset();for(let J in g)delete g[J];if(e.setRenderTarget(x),f=null,d=null,u=null,i=null,_=null,pe.stop(),n.isPresenting=!1,e.setPixelRatio(w),e.setSize(E.width,E.height,!1),T!==null){let J=T.camera;J.fov=T.fov,J.zoom=T.zoom,J.updateProjectionMatrix(),T=null}n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(J){if(r=J,n.isPresenting===!0)je("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(J){if(a=J,n.isPresenting===!0)je("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||s},this.setReferenceSpace=function(J){c=J},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){if(u===null&&b)u=new XRWebGLBinding(i,t);return u},this.getFrame=function(){return h},this.getSession=function(){return i},this.setSession=async function(J){if(i=J,i!==null){if(x=e.getRenderTarget(),i.addEventListener("select",U),i.addEventListener("selectstart",U),i.addEventListener("selectend",U),i.addEventListener("squeeze",U),i.addEventListener("squeezestart",U),i.addEventListener("squeezeend",U),i.addEventListener("end",L),i.addEventListener("inputsourceschange",O),p.xrCompatible!==!0)await t.makeXRCompatible();if(w=e.getPixelRatio(),e.getSize(E),!(b&&("createProjectionLayer"in XRWebGLBinding.prototype))){let W={antialias:p.antialias,alpha:!0,depth:p.depth,stencil:p.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(i,t,W),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),_=new li(f.framebufferWidth,f.framebufferHeight,{format:pr,type:zi,colorSpace:e.outputColorSpace,stencilBuffer:p.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1,storeMultisampledDepthBuffer:f.ignoreDepthValues===!1,storeMultisampledStencilBuffer:f.ignoreDepthValues===!1})}else{let W=null,ne=null,ie=null;if(p.depth)ie=p.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,W=p.stencil?Aa:Ta,ne=p.stencil?Co:hs;let ce={colorFormat:t.RGBA8,depthFormat:ie,scaleFactor:r};u=this.getBinding(),d=u.createProjectionLayer(ce),i.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),_=new li(d.textureWidth,d.textureHeight,{format:pr,type:zi,depthTexture:new Ma(d.textureWidth,d.textureHeight,ne,void 0,void 0,void 0,void 0,void 0,void 0,W),stencilBuffer:p.stencil,colorSpace:e.outputColorSpace,samples:p.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1,storeMultisampledDepthBuffer:d.ignoreDepthValues===!1,storeMultisampledStencilBuffer:d.ignoreDepthValues===!1})}_.isXRRenderTarget=!0,this.setFoveation(o),c=null,s=await i.requestReferenceSpace(a),pe.setContext(i),pe.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function O(J){for(let F=0;F<J.removed.length;F++){let W=J.removed[F],ne=v.indexOf(W);if(ne>=0)v[ne]=null,y[ne].disconnect(W)}for(let F=0;F<J.added.length;F++){let W=J.added[F],ne=v.indexOf(W);if(ne===-1){for(let ce=0;ce<y.length;ce++)if(ce>=v.length){v.push(W),ne=ce;break}else if(v[ce]===null){v[ce]=W,ne=ce;break}if(ne===-1)break}let ie=y[ne];if(ie)ie.connect(W)}}let K=new j,B=new j;function X(J,F,W){K.setFromMatrixPosition(F.matrixWorld),B.setFromMatrixPosition(W.matrixWorld);let ne=K.distanceTo(B),ie=F.projectionMatrix.elements,ce=W.projectionMatrix.elements,_e=ie[14]/(ie[10]-1),Re=ie[14]/(ie[10]+1),ke=(ie[9]+1)/ie[5],We=(ie[9]-1)/ie[5],Qe=(ie[8]-1)/ie[0],Wt=(ce[8]+1)/ce[0],lt=_e*Qe,Lt=_e*Wt,Qt=ne/(-Qe+Wt),nn=Qt*-Qe;if(F.matrixWorld.decompose(J.position,J.quaternion,J.scale),J.translateX(nn),J.translateZ(Qt),J.matrixWorld.compose(J.position,J.quaternion,J.scale),J.matrixWorldInverse.copy(J.matrixWorld).invert(),ie[10]===-1)J.projectionMatrix.copy(F.projectionMatrix),J.projectionMatrixInverse.copy(F.projectionMatrixInverse);else{let z=_e+Qt,_n=Re+Qt,St=lt-nn,Xt=Lt+(ne-nn),N=ke*Re/_n*z,M=We*Re/_n*z;J.projectionMatrix.makePerspective(St,Xt,N,M,z,_n),J.projectionMatrixInverse.copy(J.projectionMatrix).invert()}}function q(J,F){if(F===null)J.matrixWorld.copy(J.matrix);else J.matrixWorld.multiplyMatrices(F.matrixWorld,J.matrix);J.matrixWorldInverse.copy(J.matrixWorld).invert()}this.updateCamera=function(J){if(i===null)return;let{near:F,far:W}=J;if(m.texture!==null){if(m.depthNear>0)F=m.depthNear;if(m.depthFar>0)W=m.depthFar}if(R.near=P.near=A.near=F,R.far=P.far=A.far=W,k!==R.near||C!==R.far)i.updateRenderState({depthNear:R.near,depthFar:R.far}),k=R.near,C=R.far;R.layers.mask=J.layers.mask|6,A.layers.mask=R.layers.mask&-5,P.layers.mask=R.layers.mask&-3;let ne=J.parent,ie=R.cameras;q(R,ne);for(let ce=0;ce<ie.length;ce++)q(ie[ce],ne);if(ie.length===2)X(R,A,P);else R.projectionMatrix.copy(A.projectionMatrix);if(T===null&&J.isPerspectiveCamera)T={camera:J,fov:J.fov,zoom:J.zoom};le(J,R,ne)};function le(J,F,W){if(W===null)J.matrix.copy(F.matrixWorld);else J.matrix.copy(W.matrixWorld),J.matrix.invert(),J.matrix.multiply(F.matrixWorld);if(J.matrix.decompose(J.position,J.quaternion,J.scale),J.updateMatrixWorld(!0),J.projectionMatrix.copy(F.projectionMatrix),J.projectionMatrixInverse.copy(F.projectionMatrixInverse),J.isPerspectiveCamera)J.fov=_a*2*Math.atan(1/J.projectionMatrix.elements[5]),J.zoom=1}this.getCamera=function(){return R},this.getFoveation=function(){if(d===null&&f===null)return;return o},this.setFoveation=function(J){if(o=J,d!==null)d.fixedFoveation=J;if(f!==null&&f.fixedFoveation!==void 0)f.fixedFoveation=J},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(R)},this.getCameraTexture=function(J){return g[J]};let de=null;function Me(J,F){if(l=F.getViewerPose(c||s),h=F,l!==null){let W=l.views;if(f!==null)e.setRenderTargetFramebuffer(_,f.framebuffer),e.setRenderTarget(_);let ne=!1;if(W.length!==R.cameras.length)R.cameras.length=0,ne=!0;for(let Re=0;Re<W.length;Re++){let ke=W[Re],We=null;if(f!==null)We=f.getViewport(ke);else{let Wt=u.getViewSubImage(d,ke);if(We=Wt.viewport,Re===0)e.setRenderTargetTextures(_,Wt.colorTexture,Wt.depthStencilTexture),e.setRenderTarget(_)}let Qe=S[Re];if(Qe===void 0)Qe=new hn,Qe.layers.enable(Re),Qe.viewport=new Pt,S[Re]=Qe;if(Qe.matrix.fromArray(ke.transform.matrix),Qe.matrix.decompose(Qe.position,Qe.quaternion,Qe.scale),Qe.projectionMatrix.fromArray(ke.projectionMatrix),Qe.projectionMatrixInverse.copy(Qe.projectionMatrix).invert(),Qe.viewport.set(We.x,We.y,We.width,We.height),Re===0)R.matrix.copy(Qe.matrix),R.matrix.decompose(R.position,R.quaternion,R.scale);if(ne===!0)R.cameras.push(Qe)}let ie=i.enabledFeatures;if(ie&&ie.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&b){u=n.getBinding();let Re=u.getDepthInformation(W[0]);if(Re&&Re.isValid&&Re.texture)m.init(Re,i.renderState)}if(ie&&ie.includes("camera-access")&&b){e.state.unbindTexture(),u=n.getBinding();for(let Re=0;Re<W.length;Re++){let ke=W[Re].camera;if(ke){let We=g[ke];if(!We)We=new kd,g[ke]=We;let Qe=u.getCameraImage(ke);We.sourceTexture=Qe}}}}for(let W=0;W<y.length;W++){let ne=v[W],ie=y[W];if(ne!==null&&ie!==void 0)ie.update(ne,F,c||s)}if(de)de(J,F);if(F.detectedPlanes)n.dispatchEvent({type:"planesdetected",data:F});h=null}let pe=new wA;pe.setAnimationLoop(Me),this.setAnimationLoop=function(J){de=J},this.dispose=function(){}}};o8=new Je,UA=new tt;UA.set(-1,0,0,0,1,0,0,0,1);u8=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])});async function Al(e){let t=await crypto.subtle.digest("SHA-256",Uint8Array.from(e));return Array.from(new Uint8Array(t),(n)=>n.toString(16).padStart(2,"0")).join("")}function F8(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=()=>{throw Error("Texture manifest cannot read image dimensions")},i=(s,a)=>{if(s+a>e.byteLength)n()};if(e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return i(16,8),{width:t.getUint32(16),height:t.getUint32(20)};if(Ng(e))return i(20,8),{width:t.getUint32(20,!0),height:t.getUint32(24,!0)};if(e[0]===255&&e[1]===216){let s=2;while(s+4<=e.byteLength){if(e[s]!==255)n();let a=e[s+1];if(a===255){s++;continue}if(a===216||a===1||a>=208&&a<=215){s+=2;continue}let o=t.getUint16(s+2);if(a>=192&&a<=207&&![196,200,204].includes(a))return i(s+5,4),{width:t.getUint16(s+7),height:t.getUint16(s+5)};s+=2+o}n()}let r=(s)=>String.fromCharCode(...e.subarray(s,Math.min(s+4,e.byteLength)));if(r(0)==="RIFF"&&r(8)==="WEBP"){i(12,19);let s=r(12);if(s==="VP8X")return{width:1+(t.getUint32(24,!0)&16777215),height:1+(t.getUint32(27,!0)&16777215)};if(s==="VP8L"){let a=t.getUint32(21,!0);return{width:1+(a&16383),height:1+(a>>14&16383)}}if(s==="VP8 ")return i(26,4),{width:t.getUint16(26,!0)&16383,height:t.getUint16(28,!0)&16383}}return n()}function U8(e){if(!Ss(e))return;let t=Ss(e.extensions)?e.extensions:{};for(let n of["KHR_texture_basisu","EXT_texture_webp","EXT_texture_avif"]){let i=t[n];if(Ss(i)&&ws(i.source)!==void 0)return ws(i.source)}return ws(e.source)}function B8(e){let t=Array.isArray(e.textures)?e.textures:[],n=new Set;for(let i of Array.isArray(e.materials)?e.materials:[]){if(!Ss(i))continue;let r=Ss(i.pbrMetallicRoughness)?i.pbrMetallicRoughness:{};for(let s of[r.baseColorTexture,i.emissiveTexture]){let a=Ss(s)?ws(s.index):void 0,o=a===void 0?void 0:U8(t[a]);if(o!==void 0)n.add(o)}}return n}function z8(e){let t=atob(e);return Uint8Array.from(t,(n)=>n.charCodeAt(0))}function V8(e,t){let n=Array.isArray(e.bufferViews)?e.bufferViews:[];return(Array.isArray(e.images)?e.images:[]).map((i)=>{if(!Ss(i))throw Error("Invalid glTF image");let r=ws(i.bufferView);if(r!==void 0){let a=n[r];if(!Ss(a)||ws(a.buffer)!==0||!t)throw Error("Texture manifest requires images embedded in the GLB binary chunk");let o=ws(a.byteOffset)??0,c=ws(a.byteLength);if(c===void 0||o+c>t.byteLength)throw Error("Invalid glTF image buffer view");if(typeof i.mimeType!=="string")throw Error("Embedded image needs a mimeType");return{bytes:t.subarray(o,o+c),mimeType:i.mimeType}}let s=typeof i.uri==="string"?/^data:([^;,]+);base64,(.*)$/s.exec(i.uri):null;if(!s)throw Error("Texture manifest requires embedded image bytes");return{bytes:z8(s[2]),mimeType:s[1]}})}async function Pw(e,t,n={}){let i=B8(e),r=[];for(let[s,{bytes:a,mimeType:o}]of V8(e,t).entries()){let c=`sha256:${await Al(a)}`,l=n.sources?.get(s),u=l??c,d=n.maps?.find((f)=>f.sha256===u);r.push({image:s,sha256:c,bytes:a.byteLength,mimeType:o,...F8(a),colorSpace:i.has(s)?"srgb":"linear",...l&&l!==c?{sourceSha256:l}:{},...d?{material:{pin:{...d.pin},slot:d.slot}}:{}})}return r}function Ow(e){let t={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/ktx2":"ktx2"}[e];if(!t)throw Error(`External textures do not support ${e}`);return t}var Ss=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),ws=(e)=>Number.isInteger(e)&&e>=0?e:void 0,L8,Ng=(e)=>e.byteLength>=12&&L8.every((t,n)=>e[n]===t);var Pg=ht(()=>{L8=Object.freeze([171,75,84,88,32,50,48,187,13,10,26,10])});var kw=class{_listeners={};addEventListener(e,t){let n=this._listeners;if(n[e]===void 0)n[e]=[];if(n[e].indexOf(t)===-1)n[e].push(t);return this}removeEventListener(e,t){let n=this._listeners[e];if(n!==void 0){let i=n.indexOf(t);if(i!==-1)n.splice(i,1)}return this}dispatchEvent(e){let t=this._listeners[e.type];if(t!==void 0){let n=t.slice(0);for(let i=0,r=n.length;i<r;i++)n[i].call(this,e)}return this}dispose(){for(let e in this._listeners)delete this._listeners[e]}},Rs=class{_disposed=!1;_name;_parent;_child;_attributes;constructor(e,t,n,i={}){if(this._name=e,this._parent=t,this._child=n,this._attributes=i,!t.isOnGraph(n))throw Error("Cannot connect disconnected graphs.")}getName(){return this._name}getParent(){return this._parent}getChild(){return this._child}setChild(e){return this._child=e,this}getAttributes(){return this._attributes}dispose(){if(this._disposed)return;this._parent._destroyRef(this),this._disposed=!0}isDisposed(){return this._disposed}},Og,xn=class{list=[];constructor(e){if(e)for(let t of e)this.list.push(t)}add(e){this.list.push(e)}remove(e){let t=this.list.indexOf(e);if(t>=0)this.list.splice(t,1)}removeChild(e){let t=[];for(let n of this.list)if(n.getChild()===e)t.push(n);for(let n of t)this.remove(n);return t}listRefsByChild(e){let t=[];for(let n of this.list)if(n.getChild()===e)t.push(n);return t}values(){return this.list}},It=class{set=new Set;map=new Map;constructor(e){if(e)for(let t of e)this.add(t)}add(e){let t=e.getChild();this.removeChild(t),this.set.add(e),this.map.set(t,e)}remove(e){this.set.delete(e),this.map.delete(e.getChild())}removeChild(e){let t=this.map.get(e)||null;if(t)this.remove(t);return t}getRefByChild(e){return this.map.get(e)||null}values(){return Array.from(this.set)}},dn=class{map={};constructor(e){if(e)Object.assign(this.map,e)}set(e,t){this.map[e]=t}delete(e){delete this.map[e]}get(e){return this.map[e]||null}keys(){return Object.keys(this.map)}values(){return Object.values(this.map)}},At,Ms,Dw;var Lw=ht(()=>{Og=class extends kw{_emptySet=new Set;_edges=new Set;_parentEdges=new Map;_childEdges=new Map;listEdges(){return Array.from(this._edges)}listParentEdges(e){return Array.from(this._childEdges.get(e)||this._emptySet)}listParents(e){let t=new Set;for(let n of this.listParentEdges(e))t.add(n.getParent());return Array.from(t)}listChildEdges(e){return Array.from(this._parentEdges.get(e)||this._emptySet)}listChildren(e){let t=new Set;for(let n of this.listChildEdges(e))t.add(n.getChild());return Array.from(t)}disconnectParents(e,t){for(let n of this.listParentEdges(e))if(!t||t(n.getParent()))n.dispose();return this}_createEdge(e,t,n,i){let r=new Rs(e,t,n,i);this._edges.add(r);let s=r.getParent();if(!this._parentEdges.has(s))this._parentEdges.set(s,new Set);this._parentEdges.get(s).add(r);let a=r.getChild();if(!this._childEdges.has(a))this._childEdges.set(a,new Set);return this._childEdges.get(a).add(r),r}_destroyEdge(e){return this._edges.delete(e),this._parentEdges.get(e.getParent()).delete(e),this._childEdges.get(e.getChild()).delete(e),this}},At=Symbol("attributes"),Ms=Symbol("immutableKeys"),Dw=class e extends kw{_disposed=!1;graph;[At];[Ms];constructor(t){super();this.graph=t,this[Ms]=new Set,this[At]=this._createAttributes()}getDefaults(){return{}}_createAttributes(){let t=this.getDefaults(),n={};for(let i in t){let r=t[i];if(r instanceof e){let s=this.graph._createEdge(i,this,r);this[Ms].add(i),n[i]=s}else n[i]=r}return n}isOnGraph(t){return this.graph===t.graph}isDisposed(){return this._disposed}dispose(){if(this._disposed)return;this.graph.listChildEdges(this).forEach((t)=>t.dispose()),this.graph.disconnectParents(this),this._disposed=!0,this.dispatchEvent({type:"dispose"})}detach(){return this.graph.disconnectParents(this),this}swap(t,n){for(let i in this[At]){let r=this[At][i];if(r instanceof Rs){let s=r;if(s.getChild()===t)this.setRef(i,n,s.getAttributes())}else if(r instanceof xn)for(let s of r.listRefsByChild(t)){let a=s.getAttributes();this.removeRef(i,t),this.addRef(i,n,a)}else if(r instanceof It){let s=r.getRefByChild(t);if(s){let a=s.getAttributes();this.removeRef(i,t),this.addRef(i,n,a)}}else if(r instanceof dn)for(let s of r.keys()){let a=r.get(s);if(a.getChild()===t)this.setRefMap(i,s,n,a.getAttributes())}}return this}get(t){return this[At][t]}set(t,n){return this[At][t]=n,this.dispatchEvent({type:"change",attribute:t})}getRef(t){let n=this[At][t];return n?n.getChild():null}setRef(t,n,i){if(this[Ms].has(t))throw Error(`Cannot overwrite immutable attribute, "${t}".`);let r=this[At][t];if(r)r.dispose();if(!n)return this;let s=this.graph._createEdge(t,this,n,i);return this[At][t]=s,this.dispatchEvent({type:"change",attribute:t})}listRefs(t){return this.assertRefList(t).values().map((n)=>n.getChild())}addRef(t,n,i){let r=this.graph._createEdge(t,this,n,i);return this.assertRefList(t).add(r),this.dispatchEvent({type:"change",attribute:t})}removeRef(t,n){let i=this.assertRefList(t);if(i instanceof xn)for(let r of i.listRefsByChild(n))r.dispose();else{let r=i.getRefByChild(n);if(r)r.dispose()}return this}assertRefList(t){let n=this[At][t];if(n instanceof xn||n instanceof It)return n;throw Error(`Expected RefList or RefSet for attribute "${t}"`)}listRefMapKeys(t){return this.assertRefMap(t).keys()}listRefMapValues(t){return this.assertRefMap(t).values().map((n)=>n.getChild())}getRefMap(t,n){let i=this.assertRefMap(t).get(n);return i?i.getChild():null}setRefMap(t,n,i,r){let s=this.assertRefMap(t),a=s.get(n);if(a)a.dispose();if(!i)return this;r=Object.assign(r||{},{key:n});let o=this.graph._createEdge(t,this,i,{...r,key:n});return s.set(n,o),this.dispatchEvent({type:"change",attribute:t,key:n})}assertRefMap(t){let n=this[At][t];if(n instanceof dn)return n;throw Error(`Expected RefMap for attribute "${t}"`)}dispatchEvent(t){return super.dispatchEvent({...t,target:this}),this.graph.dispatchEvent({...t,target:this,type:`node:${t.type}`}),this}_destroyRef(t){let n=t.getName();if(this[At][n]===t){if(this[At][n]=null,this[Ms].has(n))t.getChild().dispose()}else if(this[At][n]instanceof xn)this[At][n].remove(t);else if(this[At][n]instanceof It)this[At][n].remove(t);else if(this[At][n]instanceof dn){let i=this[At][n];for(let r of i.keys())if(i.get(r)===t)i.delete(r)}else return;this.graph._destroyEdge(t),this.dispatchEvent({type:"change",attribute:n})}}});function K8(e,t){if(t>e.byteLength)throw TypeError("Corrupt JPG, exceeded buffer limits");if(e.getUint8(t)!==255)throw TypeError("Invalid JPG, marker table corrupted");return e}function W8(){var e=new Lg(3);if(Lg!=Float32Array)e[0]=0,e[1]=0,e[2]=0;return e}function kg(e){var t=e[0],n=e[1],i=e[2];return Math.sqrt(t*t+n*n+i*i)}function X8(e,t,n){var i=t[0],r=t[1],s=t[2],a=n[3]*i+n[7]*r+n[11]*s+n[15];return a=a||1,e[0]=(n[0]*i+n[4]*r+n[8]*s+n[12])/a,e[1]=(n[1]*i+n[5]*r+n[9]*s+n[13])/a,e[2]=(n[2]*i+n[6]*r+n[10]*s+n[14])/a,e}function Ug(e){let t=Kw(),n=e.propertyType==="Node"?[e]:e.listChildren();for(let i of n)i.traverse((r)=>{let s=r.getMesh();if(!s)return;let a=q8(s,r.getWorldMatrix());if(a.min.every(isFinite)&&a.max.every(isFinite))Fg(a.min,t),Fg(a.max,t)});return t}function q8(e,t){let n=Kw();for(let i of e.listPrimitives()){let r=i.getAttribute("POSITION"),s=i.getIndices();if(!r)continue;let a=[0,0,0],o=[0,0,0];for(let c=0,l=s?s.getCount():r.getCount();c<l;c++){let u=s?s.getScalar(c):c;a=r.getElement(u,a),o=X8(o,a,t),Fg(o,n)}}return n}function Fg(e,t){for(let n=0;n<3;n++)t.min[n]=Math.min(e[n],t.min[n]),t.max[n]=Math.max(e[n],t.max[n])}function Kw(){return{min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}function Uw(e){return Object.prototype.toString.call(e)==="[object Object]"}function Oa(e){if(Uw(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;if(Uw(n)===!1)return!1;if(Object.hasOwn(n,"isPrototypeOf")===!1)return!1;return!0}function Z8(e){var t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],h=e[12],b=e[13],m=e[14],g=e[15],p=t*a-n*s,x=t*o-i*s,_=n*o-i*a,y=l*b-u*h,v=l*m-d*h,E=u*m-d*b,w=t*E-n*v+i*y,T=s*E-a*v+o*y,A=l*_-u*x+d*p,P=h*_-b*x+m*p;return c*w-r*T+g*A-f*P}function Y8(e,t,n){var i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],c=t[5],l=t[6],u=t[7],d=t[8],f=t[9],h=t[10],b=t[11],m=t[12],g=t[13],p=t[14],x=t[15],_=n[0],y=n[1],v=n[2],E=n[3];return e[0]=_*i+y*o+v*d+E*m,e[1]=_*r+y*c+v*f+E*g,e[2]=_*s+y*l+v*h+E*p,e[3]=_*a+y*u+v*b+E*x,_=n[4],y=n[5],v=n[6],E=n[7],e[4]=_*i+y*o+v*d+E*m,e[5]=_*r+y*c+v*f+E*g,e[6]=_*s+y*l+v*h+E*p,e[7]=_*a+y*u+v*b+E*x,_=n[8],y=n[9],v=n[10],E=n[11],e[8]=_*i+y*o+v*d+E*m,e[9]=_*r+y*c+v*f+E*g,e[10]=_*s+y*l+v*h+E*p,e[11]=_*a+y*u+v*b+E*x,_=n[12],y=n[13],v=n[14],E=n[15],e[12]=_*i+y*o+v*d+E*m,e[13]=_*r+y*c+v*f+E*g,e[14]=_*s+y*l+v*h+E*p,e[15]=_*a+y*u+v*b+E*x,e}function Q8(e,t){var n=t[0],i=t[1],r=t[2],s=t[4],a=t[5],o=t[6],c=t[8],l=t[9],u=t[10];return e[0]=Math.sqrt(n*n+i*i+r*r),e[1]=Math.sqrt(s*s+a*a+o*o),e[2]=Math.sqrt(c*c+l*l+u*u),e}function eF(e,t){var n=new Lg(3);Q8(n,t);var i=1/n[0],r=1/n[1],s=1/n[2],a=t[0]*i,o=t[1]*r,c=t[2]*s,l=t[4]*i,u=t[5]*r,d=t[6]*s,f=t[8]*i,h=t[9]*r,b=t[10]*s,m=a+u+b,g=0;if(m>0)g=Math.sqrt(m+1)*2,e[3]=0.25*g,e[0]=(d-h)/g,e[1]=(f-c)/g,e[2]=(o-l)/g;else if(a>u&&a>b)g=Math.sqrt(1+a-u-b)*2,e[3]=(d-h)/g,e[0]=0.25*g,e[1]=(o+l)/g,e[2]=(f+c)/g;else if(u>b)g=Math.sqrt(1+u-a-b)*2,e[3]=(f-c)/g,e[0]=(o+l)/g,e[1]=0.25*g,e[2]=(d+h)/g;else g=Math.sqrt(1+b-a-u)*2,e[3]=(o-l)/g,e[0]=(f+c)/g,e[1]=(d+h)/g,e[2]=0.25*g;return e}function tF(e,t){if(!!e!==!!t)return!1;let n=e.getChild(),i=t.getChild();return n===i||n.equals(i)}function nF(e,t){if(!!e!==!!t)return!1;let n=e.values(),i=t.values();if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++){let s=n[r],a=i[r];if(s.getChild()===a.getChild())continue;if(!s.getChild().equals(a.getChild()))return!1}return!0}function iF(e,t){if(!!e!==!!t)return!1;let n=e.keys(),i=t.keys();if(n.length!==i.length)return!1;for(let r of n){let s=e.get(r),a=t.get(r);if(!!s!==!!a)return!1;let o=s.getChild(),c=a.getChild();if(o===c)continue;if(!o.equals(c))return!1}return!0}function Ww(e,t){if(e===t)return!0;if(!!e!==!!t||!e||!t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Xw(e,t){if(e===t)return!0;if(!!e!==!!t)return!1;if(!Oa(e)||!Oa(t))return e===t;let n=e,i=t,r=0,s=0,a;for(a in n)r++;for(a in i)s++;if(r!==s)return!1;for(a in n){let o=n[a],c=i[a];if(nf(o)&&nf(c)){if(!Ww(o,c))return!1}else if(Oa(o)&&Oa(c)){if(!Xw(o,c))return!1}else if(o!==c)return!1}return!0}function nf(e){return Array.isArray(e)||ArrayBuffer.isView(e)}function lF(e){switch(e.constructor){case Float32Array:return Oe.ComponentType.FLOAT;case Uint32Array:return Oe.ComponentType.UNSIGNED_INT;case Uint16Array:return Oe.ComponentType.UNSIGNED_SHORT;case Uint8Array:return Oe.ComponentType.UNSIGNED_BYTE;case Int16Array:return Oe.ComponentType.SHORT;case Int8Array:return Oe.ComponentType.BYTE;case Float64Array:return Oe.ComponentType.FLOAT64}if(typeof Float16Array<"u"&&e.constructor===Float16Array)return Oe.ComponentType.FLOAT16;throw Error("Unknown accessor componentType.")}function pF(e,t){let n=t.jsonDoc,i=t.bufferViews[e.bufferView],r=n.json.bufferViews[e.bufferView],s=wl[e.componentType],a=Oe.getElementSize(e.type),o=s.BYTES_PER_ELEMENT,c=e.byteOffset||0,l=new s(e.count*a),u=new DataView(i.buffer,i.byteOffset,i.byteLength),d=r.byteStride;for(let f=0;f<e.count;f++)for(let h=0;h<a;h++){let b=c+f*d+h*o,m;switch(e.componentType){case Oe.ComponentType.FLOAT:m=u.getFloat32(b,!0);break;case Oe.ComponentType.UNSIGNED_INT:m=u.getUint32(b,!0);break;case Oe.ComponentType.UNSIGNED_SHORT:m=u.getUint16(b,!0);break;case Oe.ComponentType.UNSIGNED_BYTE:m=u.getUint8(b);break;case Oe.ComponentType.SHORT:m=u.getInt16(b,!0);break;case Oe.ComponentType.BYTE:m=u.getInt8(b);break;case Oe.ComponentType.FLOAT16:m=u.getFloat16(b,!0);break;case Oe.ComponentType.FLOAT64:m=u.getFloat64(b,!0);break;default:throw Error(`Unexpected componentType "${e.componentType}".`)}l[f*a+h]=m}return l}function tf(e,t){let n=t.jsonDoc,i=t.bufferViews[e.bufferView],r=n.json.bufferViews[e.bufferView],s=wl[e.componentType],a=Oe.getElementSize(e.type),o=s.BYTES_PER_ELEMENT,c=a*o;if(r.byteStride!==void 0&&r.byteStride!==c)return pF(e,t);let l=i.byteOffset+(e.byteOffset||0),u=e.count*a*o;return new s(i.buffer.slice(l,l+u))}function mF(e,t){let n=wl[e.componentType],i=Oe.getElementSize(e.type),r;if(e.bufferView!==void 0)r=tf(e,t);else r=new n(e.count*i);let s=e.sparse;if(!s)return r;let a=s.count,o={...e,...s.indices,count:a,type:"SCALAR"},c={...e,...s.values,count:a},l=tf(o,t),u=tf(c,t);for(let d=0;d<o.count;d++)for(let f=0;f<i;f++)r[l[d]*i+f]=u[d*i+f];return r}function gF(e,t){let n=e.getGraph().listParentEdges(t).find((i)=>i.getParent()!==e.getRoot());return n?n.getName().replace(/texture$/i,""):""}function EF(e){let t=[];for(let n in e){let i=e[n];if(Array.isArray(i)&&i.length===0)t.push(n);else if(i===null||i==="")t.push(n);else if(i&&typeof i==="object"&&Object.keys(i).length===0)t.push(n)}for(let n of t)delete e[n]}function AF(e,t){return t.uri!==void 0&&!(t.uri in e.resources)}function wF(e,t){return t.uri!==void 0&&!(t.uri in e.resources)&&t.bufferView===void 0}function jw(e){if(e.byteLength<3*Uint32Array.BYTES_PER_ELEMENT)return!1;let t=new Uint32Array(e.buffer,e.byteOffset,3);return t[0]===1179937895&&t[1]===2}var Hw="v4.5.1",Cs="@glb.bin",Q,j8,Ai,Gw,H8,wl,Ze=class{static createBufferFromDataURI(e){if(typeof Buffer>"u"){let t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}else{let t=e.split(",")[1],n=e.indexOf("base64")>=0;return Buffer.from(t,n?"base64":"utf8")}}static encodeText(e){return new TextEncoder().encode(e)}static decodeText(e){return new TextDecoder().decode(e)}static concat(e){let t=0;for(let r of e)t+=r.byteLength;let n=new Uint8Array(t),i=0;for(let r of e)n.set(r,i),i+=r.byteLength;return n}static pad(e,t=0){let n=this.padNumber(e.byteLength);if(n===e.byteLength)return e;let i=new Uint8Array(n);if(i.set(e),t!==0)for(let r=e.byteLength;r<n;r++)i[r]=t;return i}static padNumber(e){return Math.ceil(e/4)*4}static equals(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;let n=e.byteLength;while(n--)if(e[n]!==t[n])return!1;return!0}static toView(e,t=0,n=1/0){return new Uint8Array(e.buffer,e.byteOffset+t,Math.min(e.byteLength,n))}static assertView(e){if(e&&!ArrayBuffer.isView(e))throw Error(`Method requires Uint8Array parameter; received "${typeof e}".`);return e}},$w=class{static hexToFactor(e,t){e=Math.floor(e);let n=t;return n[0]=(e>>16&255)/255,n[1]=(e>>8&255)/255,n[2]=(e&255)/255,this.convertSRGBToLinear(t,t)}static factorToHex(e){let t=[...e],[n,i,r]=this.convertLinearToSRGB(e,t);return n*255<<16^i*255<<8^r*255<<0}static convertSRGBToLinear(e,t){let n=e,i=t;for(let r=0;r<3;r++)i[r]=n[r]<0.04045?n[r]*0.0773993808:Math.pow(n[r]*0.9478672986+0.0521327014,2.4);return t}static convertLinearToSRGB(e,t){let n=e,i=t;for(let r=0;r<3;r++)i[r]=n[r]<0.0031308?n[r]*12.92:1.055*Math.pow(n[r],0.41666)-0.055;return t}},G8=class{match(e){return e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255}getSize(e){let t=new DataView(e.buffer,e.byteOffset+4),n,i;while(t.byteLength){if(n=t.getUint16(0,!1),K8(t,n),i=t.getUint8(n+1),i===192||i===193||i===194)return[t.getUint16(n+7,!1),t.getUint16(n+5,!1)];t=new DataView(e.buffer,t.byteOffset+n+2)}throw TypeError("Invalid JPG, no size found")}getChannels(e){return 3}},$8=class e{static PNG_FRIED_CHUNK_NAME="CgBI";match(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10}getSize(t){let n=new DataView(t.buffer,t.byteOffset);if(Ze.decodeText(t.slice(12,16))===e.PNG_FRIED_CHUNK_NAME)return[n.getUint32(32,!1),n.getUint32(36,!1)];return[n.getUint32(16,!1),n.getUint32(20,!1)]}getChannels(t){return 4}},Gi,ka=class{static basename(e){let t=e.split(/[\\/]/).pop();return t.substring(0,t.lastIndexOf("."))}static extension(e){if(e.startsWith("data:image/")){let t=e.match(/data:(image\/\w+)/)[1];return Gi.mimeTypeToExtension(t)}else if(e.startsWith("data:model/gltf+json"))return"gltf";else if(e.startsWith("data:model/gltf-binary"))return"glb";else if(e.startsWith("data:application/"))return"bin";return e.split(/[\\/]/).pop().split(/[.]/).pop()}},Lg,Fw="https://null.example",Dg,J8,La,mt=class e{static identity(t){return t}static eq(t,n,i=0.00001){if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(Math.abs(t[r]-n[r])>i)return!1;return!0}static clamp(t,n,i){if(t<n)return n;if(t>i)return i;return t}static decodeNormalizedInt(t,n){switch(n){case 5126:return t;case 5123:return t/65535;case 5121:return t/255;case 5122:return Math.max(t/32767,-1);case 5120:return Math.max(t/127,-1);default:throw Error("Invalid component type.")}}static encodeNormalizedInt(t,n){switch(n){case 5126:return t;case 5123:return Math.round(e.clamp(t,0,1)*65535);case 5121:return Math.round(e.clamp(t,0,1)*255);case 5122:return Math.round(e.clamp(t,-1,1)*32767);case 5120:return Math.round(e.clamp(t,-1,1)*127);default:throw Error("Invalid component type.")}}static decompose(t,n,i,r){let s=kg([t[0],t[1],t[2]]),a=kg([t[4],t[5],t[6]]),o=kg([t[8],t[9],t[10]]);if(Z8(t)<0)s=-s;n[0]=t[12],n[1]=t[13],n[2]=t[14];let c=t.slice(),l=1/s,u=1/a,d=1/o;c[0]*=l,c[1]*=l,c[2]*=l,c[4]*=u,c[5]*=u,c[6]*=u,c[8]*=d,c[9]*=d,c[10]*=d,eF(i,c),r[0]=s,r[1]=a,r[2]=o}static compose(t,n,i,r){let s=r,a=n[0],o=n[1],c=n[2],l=n[3],u=a+a,d=o+o,f=c+c,h=a*u,b=a*d,m=a*f,g=o*d,p=o*f,x=c*f,_=l*u,y=l*d,v=l*f,E=i[0],w=i[1],T=i[2];return s[0]=(1-(g+x))*E,s[1]=(b+v)*E,s[2]=(m-y)*E,s[3]=0,s[4]=(b-v)*w,s[5]=(1-(h+x))*w,s[6]=(p+_)*w,s[7]=0,s[8]=(m+y)*T,s[9]=(p-_)*T,s[10]=(1-(h+g))*T,s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s}},rF="23456789abdegjkmnpqrvwxyzABDEGJKMNPQRVWXYZ",sF=999,aF=6,Bw,oF=function(){let e="";for(let t=0;t<aF;t++)e+=rF.charAt(Math.floor(Math.random()*42));return e},qw=function(){for(let e=0;e<sF;e++){let t=oF();if(!Bw.has(t))return Bw.add(t),t}return""},Ns=(e)=>e,cF,Bg,$n,Oe,Jw,Fa,Sl,Zw,rf,nt,wt,Zd,Yd,Qd,uF,Da,zg,sf,Zn,Vg,af,Yw,Xo,Ps,of,_t=class{static EXTENSION_NAME;extensionName="";prereadTypes=[];prewriteTypes=[];readDependencies=[];writeDependencies=[];document;required=!1;properties=new Set;_listener;constructor(e){this.document=e,e.getRoot()._enableExtension(this),this._listener=(n)=>{let i=n,r=i.target;if(r instanceof nt&&r.extensionName===this.extensionName){if(i.type==="node:create")this._addExtensionProperty(r);if(i.type==="node:dispose")this._removeExtensionProperty(r)}};let t=e.getGraph();t.addEventListener("node:create",this._listener),t.addEventListener("node:dispose",this._listener)}dispose(){this.document.getRoot()._disableExtension(this);let e=this.document.getGraph();e.removeEventListener("node:create",this._listener),e.removeEventListener("node:dispose",this._listener);for(let t of this.properties)t.dispose()}static register(){}isRequired(){return this.required}setRequired(e){return this.required=e,this}listProperties(){return Array.from(this.properties)}_addExtensionProperty(e){return this.properties.add(e),this}_removeExtensionProperty(e){return this.properties.delete(e),this}install(e,t){return this}preread(e,t){return this}prewrite(e,t){return this}},dF=class{jsonDoc;buffers=[];bufferViews=[];bufferViewBuffers=[];accessors=[];textures=[];textureInfos=new Map;materials=[];meshes=[];cameras=[];nodes=[];skins=[];animations=[];scenes=[];constructor(e){this.jsonDoc=e}setTextureInfo(e,t){if(this.textureInfos.set(e,t),t.texCoord!==void 0)e.setTexCoord(t.texCoord);if(t.extras!==void 0)e.setExtras(t.extras);let n=this.jsonDoc.json.textures[t.index];if(n.sampler===void 0)return;let i=this.jsonDoc.json.samplers[n.sampler];if(i.magFilter!==void 0)e.setMagFilter(i.magFilter);if(i.minFilter!==void 0)e.setMinFilter(i.minFilter);if(i.wrapS!==void 0)e.setWrapS(i.wrapS);if(i.wrapT!==void 0)e.setWrapT(i.wrapT)}},zw,fF,hF=class{static read(e,t=zw){let n={...zw,...t},{json:i}=e,r=new of().setLogger(n.logger);this.validate(e,n);let s=new dF(e),a=i.asset,o=r.getRoot().getAsset();if(a.copyright)o.copyright=a.copyright;if(a.extras)o.extras=a.extras;if(i.extras!==void 0)r.getRoot().setExtras({...i.extras});let c=i.extensionsUsed||[],l=i.extensionsRequired||[];n.extensions.sort((p,x)=>p.EXTENSION_NAME>x.EXTENSION_NAME?1:-1);for(let p of n.extensions)if(c.includes(p.EXTENSION_NAME)){let x=r.createExtension(p).setRequired(l.includes(p.EXTENSION_NAME)),_=x.prereadTypes.filter((y)=>!fF.has(y));if(_.length)n.logger.warn(`Preread hooks for some types (${_.join()}), requested by extension ${x.extensionName}, are unsupported. Please file an issue or a PR.`);for(let y of x.readDependencies)x.install(y,n.dependencies[y])}let u=i.buffers||[];r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Buffer")).forEach((p)=>p.preread(s,"Buffer")),s.buffers=u.map((p)=>{let x=r.createBuffer(p.name);if(p.extras)x.setExtras(p.extras);if(p.uri&&p.uri.indexOf("__")!==0)x.setURI(p.uri);return x}),s.bufferViewBuffers=(i.bufferViews||[]).map((p,x)=>{if(!s.bufferViews[x]){let _=e.json.buffers[p.buffer],y=_.uri?e.resources[_.uri]:e.resources[Cs],v=p.byteOffset||0;s.bufferViews[x]=Ze.toView(y,v,p.byteLength)}return s.buffers[p.buffer]});let d=i.accessors||[];s.accessors=d.map((p)=>{let x=s.bufferViewBuffers[p.bufferView],_=r.createAccessor(p.name,x).setType(p.type);if(p.extras)_.setExtras(p.extras);if(p.normalized!==void 0)_.setNormalized(p.normalized);if(p.bufferView===void 0)return _;return _.setArray(tf(p,s)),_});let f=i.images||[],h=i.textures||[];r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Texture")).forEach((p)=>p.preread(s,"Texture")),s.textures=f.map((p)=>{let x=r.createTexture(p.name);if(p.extras)x.setExtras(p.extras);if(p.bufferView!==void 0){let _=i.bufferViews[p.bufferView],y=e.json.buffers[_.buffer],v=y.uri?e.resources[y.uri]:e.resources[Cs],E=_.byteOffset||0,w=_.byteLength,T=v.slice(E,E+w);x.setImage(T)}else if(p.uri!==void 0){if(x.setImage(e.resources[p.uri]),p.uri.indexOf("__")!==0)x.setURI(p.uri)}if(p.mimeType!==void 0)x.setMimeType(p.mimeType);else if(p.uri){let _=ka.extension(p.uri);x.setMimeType(Gi.extensionToMimeType(_))}return x}),r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Material")).forEach((p)=>p.preread(s,"Material")),s.materials=(i.materials||[]).map((p)=>{let x=r.createMaterial(p.name);if(p.extras)x.setExtras(p.extras);if(p.alphaMode!==void 0)x.setAlphaMode(p.alphaMode);if(p.alphaCutoff!==void 0)x.setAlphaCutoff(p.alphaCutoff);if(p.doubleSided!==void 0)x.setDoubleSided(p.doubleSided);let _=p.pbrMetallicRoughness||{};if(_.baseColorFactor!==void 0)x.setBaseColorFactor(_.baseColorFactor);if(p.emissiveFactor!==void 0)x.setEmissiveFactor(p.emissiveFactor);if(_.metallicFactor!==void 0)x.setMetallicFactor(_.metallicFactor);if(_.roughnessFactor!==void 0)x.setRoughnessFactor(_.roughnessFactor);if(_.baseColorTexture!==void 0){let y=_.baseColorTexture,v=s.textures[h[y.index].source];x.setBaseColorTexture(v),s.setTextureInfo(x.getBaseColorTextureInfo(),y)}if(p.emissiveTexture!==void 0){let y=p.emissiveTexture,v=s.textures[h[y.index].source];x.setEmissiveTexture(v),s.setTextureInfo(x.getEmissiveTextureInfo(),y)}if(p.normalTexture!==void 0){let y=p.normalTexture,v=s.textures[h[y.index].source];if(x.setNormalTexture(v),s.setTextureInfo(x.getNormalTextureInfo(),y),p.normalTexture.scale!==void 0)x.setNormalScale(p.normalTexture.scale)}if(p.occlusionTexture!==void 0){let y=p.occlusionTexture,v=s.textures[h[y.index].source];if(x.setOcclusionTexture(v),s.setTextureInfo(x.getOcclusionTextureInfo(),y),p.occlusionTexture.strength!==void 0)x.setOcclusionStrength(p.occlusionTexture.strength)}if(_.metallicRoughnessTexture!==void 0){let y=_.metallicRoughnessTexture,v=s.textures[h[y.index].source];x.setMetallicRoughnessTexture(v),s.setTextureInfo(x.getMetallicRoughnessTextureInfo(),y)}return x}),r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Mesh")).forEach((p)=>p.preread(s,"Mesh"));let b=i.meshes||[];r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Primitive")).forEach((p)=>p.preread(s,"Primitive")),s.meshes=b.map((p)=>{let x=r.createMesh(p.name);if(p.extras)x.setExtras(p.extras);if(p.weights!==void 0)x.setWeights(p.weights);return(p.primitives||[]).forEach((_)=>{let y=r.createPrimitive();if(_.extras)y.setExtras(_.extras);if(_.material!==void 0)y.setMaterial(s.materials[_.material]);if(_.mode!==void 0)y.setMode(_.mode);for(let[E,w]of Object.entries(_.attributes||{}))y.setAttribute(E,s.accessors[w]);if(_.indices!==void 0)y.setIndices(s.accessors[_.indices]);let v=p.extras&&p.extras.targetNames||[];(_.targets||[]).forEach((E,w)=>{let T=v[w]||w.toString(),A=r.createPrimitiveTarget(T);for(let[P,S]of Object.entries(E))A.setAttribute(P,s.accessors[S]);y.addTarget(A)}),x.addPrimitive(y)}),x}),s.cameras=(i.cameras||[]).map((p)=>{let x=r.createCamera(p.name).setType(p.type);if(p.extras)x.setExtras(p.extras);if(p.type===rf.Type.PERSPECTIVE){let _=p.perspective;if(x.setYFov(_.yfov),x.setZNear(_.znear),_.zfar!==void 0)x.setZFar(_.zfar);if(_.aspectRatio!==void 0)x.setAspectRatio(_.aspectRatio)}else{let _=p.orthographic;x.setZNear(_.znear).setZFar(_.zfar).setXMag(_.xmag).setYMag(_.ymag)}return x});let m=i.nodes||[];r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Node")).forEach((p)=>p.preread(s,"Node")),s.nodes=m.map((p)=>{let x=r.createNode(p.name);if(p.extras)x.setExtras(p.extras);if(p.translation!==void 0)x.setTranslation(p.translation);if(p.rotation!==void 0)x.setRotation(p.rotation);if(p.scale!==void 0)x.setScale(p.scale);if(p.matrix!==void 0){let _=[0,0,0],y=[0,0,0,1],v=[1,1,1];mt.decompose(p.matrix,_,y,v),x.setTranslation(_),x.setRotation(y),x.setScale(v)}if(p.weights!==void 0)x.setWeights(p.weights);return x}),s.skins=(i.skins||[]).map((p)=>{let x=r.createSkin(p.name);if(p.extras)x.setExtras(p.extras);if(p.inverseBindMatrices!==void 0)x.setInverseBindMatrices(s.accessors[p.inverseBindMatrices]);if(p.skeleton!==void 0)x.setSkeleton(s.nodes[p.skeleton]);for(let _ of p.joints)x.addJoint(s.nodes[_]);return x}),m.map((p,x)=>{let _=s.nodes[x];if((p.children||[]).forEach((y)=>_.addChild(s.nodes[y])),p.mesh!==void 0)_.setMesh(s.meshes[p.mesh]);if(p.camera!==void 0)_.setCamera(s.cameras[p.camera]);if(p.skin!==void 0)_.setSkin(s.skins[p.skin])}),s.animations=(i.animations||[]).map((p)=>{let x=r.createAnimation(p.name);if(p.extras)x.setExtras(p.extras);let _=(p.samplers||[]).map((y)=>{let v=r.createAnimationSampler().setInput(s.accessors[y.input]).setOutput(s.accessors[y.output]).setInterpolation(y.interpolation||Sl.Interpolation.LINEAR);if(y.extras)v.setExtras(y.extras);return x.addSampler(v),v});return(p.channels||[]).forEach((y)=>{let v=r.createAnimationChannel().setSampler(_[y.sampler]).setTargetPath(y.target.path);if(y.target.node!==void 0)v.setTargetNode(s.nodes[y.target.node]);if(y.extras)v.setExtras(y.extras);x.addChannel(v)}),x});let g=i.scenes||[];if(r.getRoot().listExtensionsUsed().filter((p)=>p.prereadTypes.includes("Scene")).forEach((p)=>p.preread(s,"Scene")),s.scenes=g.map((p)=>{let x=r.createScene(p.name);if(p.extras)x.setExtras(p.extras);return(p.nodes||[]).map((_)=>s.nodes[_]).forEach((_)=>x.addChild(_)),x}),i.scene!==void 0)r.getRoot().setDefaultScene(s.scenes[i.scene]);return r.getRoot().listExtensionsUsed().forEach((p)=>p.read(s)),d.forEach((p,x)=>{let _=s.accessors[x],y=!!p.sparse,v=!p.bufferView&&!_.getArray();if(y||v)_.setSparse(!0).setArray(mF(p,s))}),r}static validate(e,t){let n=e.json;if(n.asset.version!=="2.0")throw Error(`Unsupported glTF version, "${n.asset.version}".`);if(n.extensionsRequired){for(let i of n.extensionsRequired)if(!t.extensions.find((r)=>r.EXTENSION_NAME===i))throw Error(`Missing required extension, "${i}".`)}if(n.extensionsUsed){for(let i of n.extensionsUsed)if(!t.extensions.find((r)=>r.EXTENSION_NAME===i))t.logger.warn(`Missing optional extension, "${i}".`)}}},Qw,Is,Vw=class{multiple;basename;counter={};constructor(e,t){this.multiple=e,this.basename=t}createURI(e,t){if(e.getURI())return e.getURI();else if(!this.multiple)return`${this.basename(e)}.${t}`;else{let n=this.basename(e);return this.counter[n]=this.counter[n]||1,`${n}_${this.counter[n]++}.${t}`}}},ef,bF,xF,yF,_F,vF=class{static write(e,t){let n=e.getGraph(),i=e.getRoot(),r={asset:{generator:`glTF-Transform ${Hw}`,...i.getAsset()},extras:{...i.getExtras()}},s={json:r,resources:{}},a=new Is(e,s,t),o=t.logger||La.DEFAULT_INSTANCE,c=new Set(t.extensions.map((m)=>m.EXTENSION_NAME)),l=e.getRoot().listExtensionsUsed().filter((m)=>c.has(m.extensionName)).sort((m,g)=>m.extensionName>g.extensionName?1:-1),u=e.getRoot().listExtensionsRequired().filter((m)=>c.has(m.extensionName)).sort((m,g)=>m.extensionName>g.extensionName?1:-1);if(l.length<e.getRoot().listExtensionsUsed().length)o.warn("Some extensions were not registered for I/O, and will not be written.");for(let m of l){let g=m.prewriteTypes.filter((p)=>!_F.has(p));if(g.length)o.warn(`Prewrite hooks for some types (${g.join()}), requested by extension ${m.extensionName}, are unsupported. Please file an issue or a PR.`);for(let p of m.writeDependencies)m.install(p,t.dependencies[p])}function d(m,g,p,x){let _=[],y=0;for(let E of m){let w=a.createAccessorDef(E);w.bufferView=r.bufferViews.length;let T=E.getArray(),A=Ze.pad(Ze.toView(T));w.byteOffset=y,y+=A.byteLength,_.push(A),a.accessorIndexMap.set(E,r.accessors.length),r.accessors.push(w)}let v={buffer:g,byteOffset:p,byteLength:Ze.concat(_).byteLength};if(x)v.target=x;return r.bufferViews.push(v),{buffers:_,byteLength:y}}function f(m,g,p){let x=m[0].getCount(),_=0;for(let T of m){let A=a.createAccessorDef(T);A.bufferView=r.bufferViews.length,A.byteOffset=_;let P=T.getElementSize(),S=T.getComponentSize();_+=Ze.padNumber(P*S),a.accessorIndexMap.set(T,r.accessors.length),r.accessors.push(A)}let y=x*_,v=new ArrayBuffer(y),E=new DataView(v);for(let T=0;T<x;T++){let A=0;for(let P of m){let S=P.getElementSize(),R=P.getComponentSize(),k=P.getComponentType(),C=P.getArray();for(let U=0;U<S;U++){let L=T*_+A+U*R,O=C[T*S+U];switch(k){case Oe.ComponentType.FLOAT:E.setFloat32(L,O,!0);break;case Oe.ComponentType.BYTE:E.setInt8(L,O);break;case Oe.ComponentType.SHORT:E.setInt16(L,O,!0);break;case Oe.ComponentType.UNSIGNED_BYTE:E.setUint8(L,O);break;case Oe.ComponentType.UNSIGNED_SHORT:E.setUint16(L,O,!0);break;case Oe.ComponentType.UNSIGNED_INT:E.setUint32(L,O,!0);break;case Oe.ComponentType.FLOAT16:E.setFloat16(L,O,!0);break;case Oe.ComponentType.FLOAT64:E.setFloat64(L,O,!0);break;default:throw Error("Unexpected component type: "+k)}}A+=Ze.padNumber(S*R)}}let w={buffer:g,byteOffset:p,byteLength:y,byteStride:_,target:Is.BufferViewTarget.ARRAY_BUFFER};return r.bufferViews.push(w),{byteLength:y,buffers:[new Uint8Array(v)]}}function h(m,g,p){let x=[],_=0,y=new Map,v=-1/0,E=!1;for(let k of m){let C=a.createAccessorDef(k);r.accessors.push(C),a.accessorIndexMap.set(k,r.accessors.length-1);let U=[],L=[],O=[],K=Array(k.getElementSize()).fill(0);for(let le=0,de=k.getCount();le<de;le++){if(k.getElement(le,O),mt.eq(O,K,0))continue;v=Math.max(le,v),U.push(le);for(let Me=0;Me<O.length;Me++)L.push(O[Me])}let B=U.length,X={accessorDef:C,count:B};if(y.set(k,X),B===0)continue;if(B>k.getCount()/2)E=!0;let q=wl[k.getComponentType()];X.indices=U,X.values=new q(L)}if(!Number.isFinite(v))return{buffers:x,byteLength:_};if(E)o.warn("Some sparse accessors have >50% non-zero elements, which may increase file size.");let w=v<255?Uint8Array:v<65535?Uint16Array:Uint32Array,T=v<255?yF:v<65535?xF:bF,A={buffer:g,byteOffset:p+_,byteLength:0};for(let k of m){let C=y.get(k);if(C.count===0)continue;C.indicesByteOffset=A.byteLength;let U=Ze.pad(Ze.toView(new w(C.indices)));x.push(U),_+=U.byteLength,A.byteLength+=U.byteLength}r.bufferViews.push(A);let P=r.bufferViews.length-1,S={buffer:g,byteOffset:p+_,byteLength:0};for(let k of m){let C=y.get(k);if(C.count===0)continue;C.valuesByteOffset=S.byteLength;let U=Ze.pad(Ze.toView(C.values));x.push(U),_+=U.byteLength,S.byteLength+=U.byteLength}r.bufferViews.push(S);let R=r.bufferViews.length-1;for(let k of m){let C=y.get(k);if(C.count===0)continue;C.accessorDef.sparse={count:C.count,indices:{bufferView:P,byteOffset:C.indicesByteOffset,componentType:T},values:{bufferView:R,byteOffset:C.valuesByteOffset}}}return{buffers:x,byteLength:_}}if(r.accessors=[],r.bufferViews=[],r.samplers=[],r.textures=[],r.images=i.listTextures().map((m,g)=>{let p=a.createPropertyDef(m);if(m.getMimeType())p.mimeType=m.getMimeType();let x=m.getImage();if(x)a.createImageData(p,x,m);return a.imageIndexMap.set(m,g),p}),l.filter((m)=>m.prewriteTypes.includes("Accessor")).forEach((m)=>m.prewrite(a,"Accessor")),i.listAccessors().forEach((m)=>{let{accessorUsageGroupedByParent:g,accessorParents:p}=a;if(a.accessorIndexMap.has(m))return;let x=a.getAccessorUsage(m);if(a.addAccessorToUsageGroup(m,x),g.has(x)){let _=n.listParents(m).find((y)=>y.propertyType!=="Root");p.set(m,_)}}),l.filter((m)=>m.prewriteTypes.includes("Buffer")).forEach((m)=>m.prewrite(a,"Buffer")),(i.listAccessors().length>0||a.otherBufferViews.size>0||i.listTextures().length>0&&t.format==="GLB")&&i.listBuffers().length===0)throw Error("Buffer required for Document resources, but none was found.");if(r.buffers=[],i.listBuffers().forEach((m,g)=>{let p=a.createPropertyDef(m),x=a.accessorUsageGroupedByParent,_=m.listParents().filter((P)=>P instanceof Oe),y=new Set(_.map((P)=>a.accessorParents.get(P))),v=new Map(Array.from(y).map((P,S)=>[P,S])),E={};for(let P of _){if(a.accessorIndexMap.has(P))continue;let S=a.getAccessorUsage(P),R=S;if(x.has(S)){let k=a.accessorParents.get(P);R+=`:${v.get(k)}`}E[R]||={usage:S,accessors:[]},E[R].accessors.push(P)}let w=[],T=r.buffers.length,A=0;for(let{usage:P,accessors:S}of Object.values(E))if(P===ef.ARRAY_BUFFER&&t.vertexLayout==="interleaved"){let R=f(S,T,A);A+=R.byteLength;for(let k of R.buffers)w.push(k)}else if(P===ef.ARRAY_BUFFER)for(let R of S){let k=f([R],T,A);A+=k.byteLength;for(let C of k.buffers)w.push(C)}else if(P===ef.SPARSE){let R=h(S,T,A);A+=R.byteLength;for(let k of R.buffers)w.push(k)}else if(P===ef.ELEMENT_ARRAY_BUFFER){let R=Is.BufferViewTarget.ELEMENT_ARRAY_BUFFER,k=d(S,T,A,R);A+=k.byteLength;for(let C of k.buffers)w.push(C)}else{let R=d(S,T,A);A+=R.byteLength;for(let k of R.buffers)w.push(k)}if(a.imageBufferViews.length&&g===0){for(let P=0;P<a.imageBufferViews.length;P++)if(r.bufferViews[r.images[P].bufferView].byteOffset=A,A+=a.imageBufferViews[P].byteLength,w.push(a.imageBufferViews[P]),A%8){let S=8-A%8;A+=S,w.push(new Uint8Array(S))}}if(a.otherBufferViews.has(m))for(let P of a.otherBufferViews.get(m))r.bufferViews.push({buffer:T,byteOffset:A,byteLength:P.byteLength}),a.otherBufferViewsIndexMap.set(P,r.bufferViews.length-1),A+=P.byteLength,w.push(P);if(A){let P;if(t.format==="GLB")P=Cs;else P=a.bufferURIGenerator.createURI(m,"bin"),p.uri=P;p.byteLength=A,a.assignResourceURI(P,Ze.concat(w),!0)}r.buffers.push(p),a.bufferIndexMap.set(m,g)}),i.listAccessors().find((m)=>!m.getBuffer()))o.warn("Skipped writing one or more Accessors: no Buffer assigned.");l.filter((m)=>m.prewriteTypes.includes("Material")).forEach((m)=>m.prewrite(a,"Material")),r.materials=i.listMaterials().map((m,g)=>{let p=a.createPropertyDef(m);if(m.getAlphaMode()!==Da.AlphaMode.OPAQUE)p.alphaMode=m.getAlphaMode();if(m.getAlphaMode()===Da.AlphaMode.MASK)p.alphaCutoff=m.getAlphaCutoff();if(m.getDoubleSided())p.doubleSided=!0;if(p.pbrMetallicRoughness={},!mt.eq(m.getBaseColorFactor(),[1,1,1,1]))p.pbrMetallicRoughness.baseColorFactor=m.getBaseColorFactor();if(!mt.eq(m.getEmissiveFactor(),[0,0,0]))p.emissiveFactor=m.getEmissiveFactor();if(m.getRoughnessFactor()!==1)p.pbrMetallicRoughness.roughnessFactor=m.getRoughnessFactor();if(m.getMetallicFactor()!==1)p.pbrMetallicRoughness.metallicFactor=m.getMetallicFactor();if(m.getBaseColorTexture()){let x=m.getBaseColorTexture(),_=m.getBaseColorTextureInfo();p.pbrMetallicRoughness.baseColorTexture=a.createTextureInfoDef(x,_)}if(m.getEmissiveTexture()){let x=m.getEmissiveTexture(),_=m.getEmissiveTextureInfo();p.emissiveTexture=a.createTextureInfoDef(x,_)}if(m.getNormalTexture()){let x=m.getNormalTexture(),_=m.getNormalTextureInfo(),y=a.createTextureInfoDef(x,_);if(m.getNormalScale()!==1)y.scale=m.getNormalScale();p.normalTexture=y}if(m.getOcclusionTexture()){let x=m.getOcclusionTexture(),_=m.getOcclusionTextureInfo(),y=a.createTextureInfoDef(x,_);if(m.getOcclusionStrength()!==1)y.strength=m.getOcclusionStrength();p.occlusionTexture=y}if(m.getMetallicRoughnessTexture()){let x=m.getMetallicRoughnessTexture(),_=m.getMetallicRoughnessTextureInfo();p.pbrMetallicRoughness.metallicRoughnessTexture=a.createTextureInfoDef(x,_)}return a.materialIndexMap.set(m,g),p}),l.filter((m)=>m.prewriteTypes.includes("Mesh")).forEach((m)=>m.prewrite(a,"Mesh")),r.meshes=i.listMeshes().map((m,g)=>{let p=a.createPropertyDef(m),x=null;if(p.primitives=m.listPrimitives().map((_)=>{let y={attributes:{}};y.mode=_.getMode();let v=_.getMaterial();if(v)y.material=a.materialIndexMap.get(v);if(Object.keys(_.getExtras()).length)y.extras=_.getExtras();let E=_.getIndices();if(E)y.indices=a.accessorIndexMap.get(E);for(let w of _.listSemantics())y.attributes[w]=a.accessorIndexMap.get(_.getAttribute(w));for(let w of _.listTargets()){let T={};for(let A of w.listSemantics())T[A]=a.accessorIndexMap.get(w.getAttribute(A));y.targets=y.targets||[],y.targets.push(T)}if(_.listTargets().length&&!x)x=_.listTargets().map((w)=>w.getName());return y}),m.getWeights().length)p.weights=m.getWeights();if(x)p.extras=p.extras||{},p.extras.targetNames=x;return a.meshIndexMap.set(m,g),p}),r.cameras=i.listCameras().map((m,g)=>{let p=a.createPropertyDef(m);if(p.type=m.getType(),p.type===rf.Type.PERSPECTIVE){p.perspective={znear:m.getZNear(),zfar:m.getZFar(),yfov:m.getYFov()};let x=m.getAspectRatio();if(x!==null)p.perspective.aspectRatio=x}else p.orthographic={znear:m.getZNear(),zfar:m.getZFar(),xmag:m.getXMag(),ymag:m.getYMag()};return a.cameraIndexMap.set(m,g),p}),r.nodes=i.listNodes().map((m,g)=>{let p=a.createPropertyDef(m);if(!mt.eq(m.getTranslation(),[0,0,0]))p.translation=m.getTranslation();if(!mt.eq(m.getRotation(),[0,0,0,1]))p.rotation=m.getRotation();if(!mt.eq(m.getScale(),[1,1,1]))p.scale=m.getScale();if(m.getWeights().length)p.weights=m.getWeights();return a.nodeIndexMap.set(m,g),p}),r.skins=i.listSkins().map((m,g)=>{let p=a.createPropertyDef(m),x=m.getInverseBindMatrices();if(x)p.inverseBindMatrices=a.accessorIndexMap.get(x);let _=m.getSkeleton();if(_)p.skeleton=a.nodeIndexMap.get(_);return p.joints=m.listJoints().map((y)=>a.nodeIndexMap.get(y)),a.skinIndexMap.set(m,g),p}),i.listNodes().forEach((m,g)=>{let p=r.nodes[g],x=m.getMesh();if(x)p.mesh=a.meshIndexMap.get(x);let _=m.getCamera();if(_)p.camera=a.cameraIndexMap.get(_);let y=m.getSkin();if(y)p.skin=a.skinIndexMap.get(y);if(m.listChildren().length>0)p.children=m.listChildren().map((v)=>a.nodeIndexMap.get(v))}),r.animations=i.listAnimations().map((m,g)=>{let p=a.createPropertyDef(m),x=new Map;return p.samplers=m.listSamplers().map((_,y)=>{let v=a.createPropertyDef(_);return v.input=a.accessorIndexMap.get(_.getInput()),v.output=a.accessorIndexMap.get(_.getOutput()),v.interpolation=_.getInterpolation(),x.set(_,y),v}),p.channels=m.listChannels().map((_)=>{let y=a.createPropertyDef(_);return y.sampler=x.get(_.getSampler()),y.target={node:a.nodeIndexMap.get(_.getTargetNode()),path:_.getTargetPath()},y}),a.animationIndexMap.set(m,g),p}),r.scenes=i.listScenes().map((m,g)=>{let p=a.createPropertyDef(m);return p.nodes=m.listChildren().map((x)=>a.nodeIndexMap.get(x)),a.sceneIndexMap.set(m,g),p});let b=i.getDefaultScene();if(b)r.scene=i.listScenes().indexOf(b);return r.extensionsUsed=l.map((m)=>m.extensionName),r.extensionsRequired=u.map((m)=>m.extensionName),l.forEach((m)=>m.write(a)),EF(r),s}},TF=class{_logger=La.DEFAULT_INSTANCE;_extensions=new Set;_dependencies={};_vertexLayout="interleaved";_strictResources=!0;lastReadBytes=0;lastWriteBytes=0;setLogger(e){return this._logger=e,this}registerExtensions(e){for(let t of e)this._extensions.add(t),t.register();return this}registerDependencies(e){return Object.assign(this._dependencies,e),this}setVertexLayout(e){return this._vertexLayout=e,this}setStrictResources(e){return this._strictResources=e,this}async read(e){return await this.readJSON(await this.readAsJSON(e))}async readAsJSON(e){let t=await this.readURI(e,"view");this.lastReadBytes=t.byteLength;let n=jw(t)?this._binaryToJSON(t):{json:JSON.parse(Ze.decodeText(t)),resources:{}};return await this._readResourcesExternal(n,this.dirname(e)),this._readResourcesInternal(n),n}async readJSON(e){return e=this._copyJSON(e),this._readResourcesInternal(e),hF.read(e,{extensions:Array.from(this._extensions),dependencies:this._dependencies,logger:this._logger})}async binaryToJSON(e){let t=this._binaryToJSON(Ze.assertView(e));this._readResourcesInternal(t);let n=t.json;if(n.buffers&&n.buffers.some((i)=>AF(t,i)))throw Error("Cannot resolve external buffers with binaryToJSON().");else if(n.images&&n.images.some((i)=>wF(t,i)))throw Error("Cannot resolve external images with binaryToJSON().");return t}async readBinary(e){return this.readJSON(await this.binaryToJSON(Ze.assertView(e)))}async writeJSON(e,t={}){if(t.format==="GLB"&&e.getRoot().listBuffers().length>1)throw Error("GLB must have 0–1 buffers.");return vF.write(e,{format:t.format||"GLTF",basename:t.basename||"",logger:this._logger,vertexLayout:this._vertexLayout,dependencies:{...this._dependencies},extensions:Array.from(this._extensions)})}async writeBinary(e){let{json:t,resources:n}=await this.writeJSON(e,{format:"GLB"}),i=new Uint32Array([1179937895,2,12]),r=JSON.stringify(t),s=Ze.pad(Ze.encodeText(r),32),a=Ze.toView(new Uint32Array([s.byteLength,1313821514])),o=Ze.concat([a,s]);i[i.length-1]+=o.byteLength;let c=Object.values(n)[0];if(!c||!c.byteLength)return Ze.concat([Ze.toView(i),o]);let l=Ze.pad(c,0),u=Ze.toView(new Uint32Array([l.byteLength,5130562])),d=Ze.concat([u,l]);return i[i.length-1]+=d.byteLength,Ze.concat([Ze.toView(i),o,d])}async _readResourcesExternal(e,t){let n=e.json.images||[],i=e.json.buffers||[],r=[...n,...i].map(async(s)=>{let a=s.uri;if(!a||a.match(/data:/))return Promise.resolve();try{e.resources[a]=await this.readURI(this.resolve(t,a),"view"),this.lastReadBytes+=e.resources[a].byteLength}catch(o){if(!this._strictResources&&n.includes(s))this._logger.warn(`Failed to load image URI, "${a}". ${o}`),e.resources[a]=null;else throw o}});await Promise.all(r)}_readResourcesInternal(e){function t(n){if(!n.uri)return;if(n.uri in e.resources){Ze.assertView(e.resources[n.uri]);return}if(n.uri.match(/data:/)){let i=`__${qw()}.${ka.extension(n.uri)}`;e.resources[i]=Ze.createBufferFromDataURI(n.uri),n.uri=i}}(e.json.images||[]).forEach((n)=>{if(n.bufferView===void 0&&n.uri===void 0)throw Error("Missing resource URI or buffer view.");t(n)}),(e.json.buffers||[]).forEach(t)}_copyJSON(e){let{images:t,buffers:n}=e.json;if(e={json:{...e.json},resources:{...e.resources}},t)e.json.images=t.map((i)=>({...i}));if(n)e.json.buffers=n.map((i)=>({...i}));return e}_binaryToJSON(e){if(!jw(e))throw Error("Invalid glTF 2.0 binary.");let t=new Uint32Array(e.buffer,e.byteOffset+12,2);if(t[1]!==1313821514)throw Error("Missing required GLB JSON chunk.");let n=20,i=t[0],r=Ze.decodeText(Ze.toView(e,n,i)),s=JSON.parse(r),a=n+i;if(e.byteLength<=a)return{json:s,resources:{}};let o=new Uint32Array(e.buffer,e.byteOffset+a,2);if(o[1]!==5130562)return{json:s,resources:{}};let c=o[0],l=Ze.toView(e,a+8,c);return{json:s,resources:{[Cs]:l}}}},eS;var qo=ht(()=>{Lw();Q=function(e){return e.ACCESSOR="Accessor",e.ANIMATION="Animation",e.ANIMATION_CHANNEL="AnimationChannel",e.ANIMATION_SAMPLER="AnimationSampler",e.BUFFER="Buffer",e.CAMERA="Camera",e.MATERIAL="Material",e.MESH="Mesh",e.PRIMITIVE="Primitive",e.PRIMITIVE_TARGET="PrimitiveTarget",e.NODE="Node",e.ROOT="Root",e.SCENE="Scene",e.SKIN="Skin",e.TEXTURE="Texture",e.TEXTURE_INFO="TextureInfo",e}({}),j8=function(e){return e.ARRAY_BUFFER="ARRAY_BUFFER",e.ELEMENT_ARRAY_BUFFER="ELEMENT_ARRAY_BUFFER",e.INVERSE_BIND_MATRICES="INVERSE_BIND_MATRICES",e.OTHER="OTHER",e.SPARSE="SPARSE",e}({}),Ai=function(e){return e[e.R=4096]="R",e[e.G=256]="G",e[e.B=16]="B",e[e.A=1]="A",e}({}),Gw=function(e){return e.GLTF="GLTF",e.GLB="GLB",e}({}),H8=class extends Float32Array{constructor(){super();throw Error("Unsupported typed array instantiation.")}},wl={"5120":Int8Array,"5121":Uint8Array,"5122":Int16Array,"5123":Uint16Array,"5125":Uint32Array,"5131":typeof Float16Array<"u"?Float16Array:H8,"5126":Float32Array,"5130":Float64Array},Gi=class{static impls={"image/jpeg":new G8,"image/png":new $8};static registerFormat(e,t){this.impls[e]=t}static getMimeType(e){for(let t in this.impls)if(this.impls[t].match(e))return t;return null}static getSize(e,t){if(!this.impls[t])return null;return this.impls[t].getSize(e)}static getChannels(e,t){if(!this.impls[t])return null;return this.impls[t].getChannels(e)}static getVRAMByteLength(e,t){if(!this.impls[t])return null;if(this.impls[t].getVRAMByteLength)return this.impls[t].getVRAMByteLength(e);let n=0,i=4,r=this.getSize(e,t);if(!r)return null;while(r[0]>1||r[1]>1)n+=r[0]*r[1]*i,r[0]=Math.max(Math.floor(r[0]/2),1),r[1]=Math.max(Math.floor(r[1]/2),1);return n+=4,n}static mimeTypeToExtension(e){if(e==="image/jpeg")return"jpg";return e.split("/").pop()}static extensionToMimeType(e){if(e==="jpg")return"image/jpeg";if(!e)return"";return`image/${e}`}};Lg=typeof Float32Array<"u"?Float32Array:Array;Math.PI/180;180/Math.PI;(function(){var e=W8();return function(t,n,i,r,s,a){var o,c;if(!n)n=3;if(!i)i=0;if(r)c=Math.min(r*n+i,t.length);else c=t.length;for(o=i;o<c;o+=n)e[0]=t[o],e[1]=t[o+1],e[2]=t[o+2],s(e,e,a),t[o]=e[0],t[o+1]=e[1],t[o+2]=e[2];return t}})();Dg=class{static DEFAULT_INIT={};static PROTOCOL_REGEXP=/^[a-zA-Z]+:\/\//;static dirname(e){let t=e.lastIndexOf("/");if(t===-1)return"./";return e.substring(0,t+1)}static basename(e){return ka.basename(new URL(e,Fw).pathname)}static extension(e){return ka.extension(new URL(e,Fw).pathname)}static resolve(e,t){if(!this.isRelativePath(t))return t;let n=e.split("/"),i=t.split("/");n.pop();for(let r=0;r<i.length;r++){if(i[r]===".")continue;if(i[r]==="..")n.pop();else n.push(i[r])}return n.join("/")}static isAbsoluteURL(e){return this.PROTOCOL_REGEXP.test(e)}static isRelativePath(e){return!/^(?:[a-zA-Z]+:)?\//.test(e)}};J8=function(e){return e[e.SILENT=4]="SILENT",e[e.ERROR=3]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=1]="INFO",e[e.DEBUG=0]="DEBUG",e}({}),La=class e{verbosity;static Verbosity=J8;static DEFAULT_INSTANCE=new e(1);constructor(t){this.verbosity=t}debug(t){if(this.verbosity<=0)console.debug(t)}info(t){if(this.verbosity<=1)console.info(t)}warn(t){if(this.verbosity<=2)console.warn(t)}error(t){if(this.verbosity<=3)console.error(t)}};Bw=new Set,cF=new Set,Bg=class extends Dw{constructor(e,t=""){super(e);this[At].name=t,this.init(),this.dispatchEvent({type:"create"})}getGraph(){return this.graph}getDefaults(){return Object.assign(super.getDefaults(),{name:"",extras:{}})}set(e,t){if(Array.isArray(t))t=t.slice();return super.set(e,t)}getName(){return this.get("name")}setName(e){return this.set("name",e)}getExtras(){return this.get("extras")}setExtras(e){return this.set("extras",e)}clone(){return new this.constructor(this.graph).copy(this,Ns)}copy(e,t=Ns){for(let n in this[At]){let i=this[At][n];if(i instanceof Rs){if(!this[Ms].has(n))i.dispose()}else if(i instanceof xn||i instanceof It)for(let r of i.values())r.dispose();else if(i instanceof dn)for(let r of i.values())r.dispose()}for(let n in e[At]){let i=this[At][n],r=e[At][n];if(r instanceof Rs)if(this[Ms].has(n))i.getChild().copy(t(r.getChild()),t);else this.setRef(n,t(r.getChild()),r.getAttributes());else if(r instanceof It||r instanceof xn)for(let s of r.values())this.addRef(n,t(s.getChild()),s.getAttributes());else if(r instanceof dn)for(let s of r.keys()){let a=r.get(s);this.setRefMap(n,s,t(a.getChild()),a.getAttributes())}else if(Oa(r))this[At][n]=JSON.parse(JSON.stringify(r));else if(Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r))this[At][n]=r.slice();else this[At][n]=r}return this}equals(e,t=cF){if(this===e)return!0;if(this.propertyType!==e.propertyType)return!1;for(let n in this[At]){if(t.has(n))continue;let i=this[At][n],r=e[At][n];if(i instanceof Rs||r instanceof Rs){if(!tF(i,r))return!1}else if(i instanceof It||r instanceof It||i instanceof xn||r instanceof xn){if(!nF(i,r))return!1}else if(i instanceof dn||r instanceof dn){if(!iF(i,r))return!1}else if(Oa(i)||Oa(r)){if(!Xw(i,r))return!1}else if(nf(i)||nf(r)){if(!Ww(i,r))return!1}else if(i!==r)return!1}return!0}detach(){return this.graph.disconnectParents(this,(e)=>e.propertyType!=="Root"),this}listParents(){return this.graph.listParents(this)}},$n=class extends Bg{getDefaults(){return Object.assign(super.getDefaults(),{extensions:new dn})}getExtension(e){return this.getRefMap("extensions",e)}setExtension(e,t){if(t)t._validateParent(this);return this.setRefMap("extensions",e,t)}listExtensions(){return this.listRefMapValues("extensions")}},Oe=class e extends $n{static Type={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};static ComponentType={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:5126,FLOAT16:5131,FLOAT64:5130};init(){this.propertyType="Accessor"}getDefaults(){return Object.assign(super.getDefaults(),{array:null,type:e.Type.SCALAR,componentType:e.ComponentType.FLOAT,normalized:!1,sparse:!1,buffer:null})}static getElementSize(t){switch(t){case e.Type.SCALAR:return 1;case e.Type.VEC2:return 2;case e.Type.VEC3:return 3;case e.Type.VEC4:return 4;case e.Type.MAT2:return 4;case e.Type.MAT3:return 9;case e.Type.MAT4:return 16;default:throw Error("Unexpected type: "+t)}}static getComponentSize(t){switch(t){case e.ComponentType.BYTE:case e.ComponentType.UNSIGNED_BYTE:return 1;case e.ComponentType.SHORT:case e.ComponentType.UNSIGNED_SHORT:return 2;case e.ComponentType.UNSIGNED_INT:case e.ComponentType.FLOAT:return 4;case e.ComponentType.FLOAT16:return 2;case e.ComponentType.FLOAT64:return 8;default:throw Error("Unexpected component type: "+t)}}getMinNormalized(t){let n=this.getNormalized(),i=this.getElementSize(),r=this.getComponentType();if(this.getMin(t),n)for(let s=0;s<i;s++)t[s]=mt.decodeNormalizedInt(t[s],r);return t}getMin(t){let n=this.getArray(),i=this.getCount(),r=this.getElementSize();for(let s=0;s<r;s++)t[s]=1/0;for(let s=0;s<i*r;s+=r)for(let a=0;a<r;a++){let o=n[s+a];if(Number.isFinite(o))t[a]=Math.min(t[a],o)}return t}getMaxNormalized(t){let n=this.getNormalized(),i=this.getElementSize(),r=this.getComponentType();if(this.getMax(t),n)for(let s=0;s<i;s++)t[s]=mt.decodeNormalizedInt(t[s],r);return t}getMax(t){let n=this.get("array"),i=this.getCount(),r=this.getElementSize();for(let s=0;s<r;s++)t[s]=-1/0;for(let s=0;s<i*r;s+=r)for(let a=0;a<r;a++){let o=n[s+a];if(Number.isFinite(o))t[a]=Math.max(t[a],o)}return t}getCount(){let t=this.get("array");return t?t.length/this.getElementSize():0}getType(){return this.get("type")}setType(t){return this.set("type",t)}getElementSize(){return e.getElementSize(this.get("type"))}getComponentSize(){return this.get("array").BYTES_PER_ELEMENT}getComponentType(){return this.get("componentType")}getNormalized(){return this.get("normalized")}setNormalized(t){return this.set("normalized",t)}getScalar(t){let n=this.getElementSize(),i=this.getComponentType(),r=this.getArray();if(this.getNormalized())return mt.decodeNormalizedInt(r[t*n],i);return r[t*n]}setScalar(t,n){let i=this.getElementSize(),r=this.getComponentType(),s=this.getArray();if(this.getNormalized())s[t*i]=mt.encodeNormalizedInt(n,r);else s[t*i]=n;return this}getElement(t,n){let i=this.getNormalized(),r=this.getElementSize(),s=this.getComponentType(),a=this.getArray();for(let o=0;o<r;o++)if(i)n[o]=mt.decodeNormalizedInt(a[t*r+o],s);else n[o]=a[t*r+o];return n}setElement(t,n){let i=this.getNormalized(),r=this.getElementSize(),s=this.getComponentType(),a=this.getArray();for(let o=0;o<r;o++)if(i)a[t*r+o]=mt.encodeNormalizedInt(n[o],s);else a[t*r+o]=n[o];return this}getSparse(){return this.get("sparse")}setSparse(t){return this.set("sparse",t)}getBuffer(){return this.getRef("buffer")}setBuffer(t){return this.setRef("buffer",t)}getArray(){return this.get("array")}setArray(t){return this.set("componentType",t?lF(t):e.ComponentType.FLOAT),this.set("array",t),this}getByteLength(){let t=this.get("array");return t?t.byteLength:0}};Jw=class extends $n{init(){this.propertyType="Animation"}getDefaults(){return Object.assign(super.getDefaults(),{channels:new It,samplers:new It})}addChannel(e){return this.addRef("channels",e)}removeChannel(e){return this.removeRef("channels",e)}listChannels(){return this.listRefs("channels")}addSampler(e){return this.addRef("samplers",e)}removeSampler(e){return this.removeRef("samplers",e)}listSamplers(){return this.listRefs("samplers")}},Fa=class extends $n{static TargetPath={TRANSLATION:"translation",ROTATION:"rotation",SCALE:"scale",WEIGHTS:"weights"};init(){this.propertyType="AnimationChannel"}getDefaults(){return Object.assign(super.getDefaults(),{targetPath:null,targetNode:null,sampler:null})}getTargetPath(){return this.get("targetPath")}setTargetPath(e){return this.set("targetPath",e)}getTargetNode(){return this.getRef("targetNode")}setTargetNode(e){return this.setRef("targetNode",e)}getSampler(){return this.getRef("sampler")}setSampler(e){return this.setRef("sampler",e)}},Sl=class e extends $n{static Interpolation={LINEAR:"LINEAR",STEP:"STEP",CUBICSPLINE:"CUBICSPLINE"};init(){this.propertyType="AnimationSampler"}getDefaultAttributes(){return Object.assign(super.getDefaults(),{interpolation:e.Interpolation.LINEAR,input:null,output:null})}getInterpolation(){return this.get("interpolation")}setInterpolation(t){return this.set("interpolation",t)}getInput(){return this.getRef("input")}setInput(t){return this.setRef("input",t,{usage:"OTHER"})}getOutput(){return this.getRef("output")}setOutput(t){return this.setRef("output",t,{usage:"OTHER"})}},Zw=class extends $n{init(){this.propertyType="Buffer"}getDefaults(){return Object.assign(super.getDefaults(),{uri:""})}getURI(){return this.get("uri")}setURI(e){return this.set("uri",e)}},rf=class e extends $n{static Type={PERSPECTIVE:"perspective",ORTHOGRAPHIC:"orthographic"};init(){this.propertyType="Camera"}getDefaults(){return Object.assign(super.getDefaults(),{type:e.Type.PERSPECTIVE,znear:0.1,zfar:100,aspectRatio:null,yfov:Math.PI*2*50/360,xmag:1,ymag:1})}getType(){return this.get("type")}setType(t){return this.set("type",t)}getZNear(){return this.get("znear")}setZNear(t){return this.set("znear",t)}getZFar(){return this.get("zfar")}setZFar(t){return this.set("zfar",t)}getAspectRatio(){return this.get("aspectRatio")}setAspectRatio(t){return this.set("aspectRatio",t)}getYFov(){return this.get("yfov")}setYFov(t){return this.set("yfov",t)}getXMag(){return this.get("xmag")}setXMag(t){return this.set("xmag",t)}getYMag(){return this.get("ymag")}setYMag(t){return this.set("ymag",t)}},nt=class extends Bg{static EXTENSION_NAME;_validateParent(e){if(!this.parentTypes.includes(e.propertyType))throw Error(`Parent "${e.propertyType}" invalid for child "${this.propertyType}".`)}},wt=class e extends $n{static WrapMode={CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497};static MagFilter={NEAREST:9728,LINEAR:9729};static MinFilter={NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987};init(){this.propertyType="TextureInfo"}getDefaults(){return Object.assign(super.getDefaults(),{texCoord:0,magFilter:null,minFilter:null,wrapS:e.WrapMode.REPEAT,wrapT:e.WrapMode.REPEAT})}getTexCoord(){return this.get("texCoord")}setTexCoord(t){return this.set("texCoord",t)}getMagFilter(){return this.get("magFilter")}setMagFilter(t){return this.set("magFilter",t)}getMinFilter(){return this.get("minFilter")}setMinFilter(t){return this.set("minFilter",t)}getWrapS(){return this.get("wrapS")}setWrapS(t){return this.set("wrapS",t)}getWrapT(){return this.get("wrapT")}setWrapT(t){return this.set("wrapT",t)}},{R:Zd,G:Yd,B:Qd,A:uF}=Ai,Da=class e extends $n{static AlphaMode={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};init(){this.propertyType="Material"}getDefaults(){return Object.assign(super.getDefaults(),{alphaMode:e.AlphaMode.OPAQUE,alphaCutoff:0.5,doubleSided:!1,baseColorFactor:[1,1,1,1],baseColorTexture:null,baseColorTextureInfo:new wt(this.graph,"baseColorTextureInfo"),emissiveFactor:[0,0,0],emissiveTexture:null,emissiveTextureInfo:new wt(this.graph,"emissiveTextureInfo"),normalScale:1,normalTexture:null,normalTextureInfo:new wt(this.graph,"normalTextureInfo"),occlusionStrength:1,occlusionTexture:null,occlusionTextureInfo:new wt(this.graph,"occlusionTextureInfo"),roughnessFactor:1,metallicFactor:1,metallicRoughnessTexture:null,metallicRoughnessTextureInfo:new wt(this.graph,"metallicRoughnessTextureInfo")})}getDoubleSided(){return this.get("doubleSided")}setDoubleSided(t){return this.set("doubleSided",t)}getAlpha(){return this.get("baseColorFactor")[3]}setAlpha(t){let n=this.get("baseColorFactor").slice();return n[3]=t,this.set("baseColorFactor",n)}getAlphaMode(){return this.get("alphaMode")}setAlphaMode(t){return this.set("alphaMode",t)}getAlphaCutoff(){return this.get("alphaCutoff")}setAlphaCutoff(t){return this.set("alphaCutoff",t)}getBaseColorFactor(){return this.get("baseColorFactor")}setBaseColorFactor(t){return this.set("baseColorFactor",t)}getBaseColorTexture(){return this.getRef("baseColorTexture")}getBaseColorTextureInfo(){return this.getRef("baseColorTexture")?this.getRef("baseColorTextureInfo"):null}setBaseColorTexture(t){return this.setRef("baseColorTexture",t,{channels:Zd|Yd|Qd|uF,isColor:!0})}getEmissiveFactor(){return this.get("emissiveFactor")}setEmissiveFactor(t){return this.set("emissiveFactor",t)}getEmissiveTexture(){return this.getRef("emissiveTexture")}getEmissiveTextureInfo(){return this.getRef("emissiveTexture")?this.getRef("emissiveTextureInfo"):null}setEmissiveTexture(t){return this.setRef("emissiveTexture",t,{channels:Zd|Yd|Qd,isColor:!0})}getNormalScale(){return this.get("normalScale")}setNormalScale(t){return this.set("normalScale",t)}getNormalTexture(){return this.getRef("normalTexture")}getNormalTextureInfo(){return this.getRef("normalTexture")?this.getRef("normalTextureInfo"):null}setNormalTexture(t){return this.setRef("normalTexture",t,{channels:Zd|Yd|Qd})}getOcclusionStrength(){return this.get("occlusionStrength")}setOcclusionStrength(t){return this.set("occlusionStrength",t)}getOcclusionTexture(){return this.getRef("occlusionTexture")}getOcclusionTextureInfo(){return this.getRef("occlusionTexture")?this.getRef("occlusionTextureInfo"):null}setOcclusionTexture(t){return this.setRef("occlusionTexture",t,{channels:Zd})}getRoughnessFactor(){return this.get("roughnessFactor")}setRoughnessFactor(t){return this.set("roughnessFactor",t)}getMetallicFactor(){return this.get("metallicFactor")}setMetallicFactor(t){return this.set("metallicFactor",t)}getMetallicRoughnessTexture(){return this.getRef("metallicRoughnessTexture")}getMetallicRoughnessTextureInfo(){return this.getRef("metallicRoughnessTexture")?this.getRef("metallicRoughnessTextureInfo"):null}setMetallicRoughnessTexture(t){return this.setRef("metallicRoughnessTexture",t,{channels:Yd|Qd})}},zg=class extends $n{init(){this.propertyType="Mesh"}getDefaults(){return Object.assign(super.getDefaults(),{weights:[],primitives:new It})}addPrimitive(e){return this.addRef("primitives",e)}removePrimitive(e){return this.removeRef("primitives",e)}listPrimitives(){return this.listRefs("primitives")}getWeights(){return this.get("weights")}setWeights(e){return this.set("weights",e)}},sf=class extends $n{init(){this.propertyType="Node"}getDefaults(){return Object.assign(super.getDefaults(),{translation:[0,0,0],rotation:[0,0,0,1],scale:[1,1,1],weights:[],camera:null,mesh:null,skin:null,children:new It})}copy(e,t=Ns){if(t===Ns)throw Error("Node cannot be copied.");return super.copy(e,t)}getTranslation(){return this.get("translation")}getRotation(){return this.get("rotation")}getScale(){return this.get("scale")}setTranslation(e){return this.set("translation",e)}setRotation(e){return this.set("rotation",e)}setScale(e){return this.set("scale",e)}getMatrix(){return mt.compose(this.get("translation"),this.get("rotation"),this.get("scale"),[])}setMatrix(e){let t=this.get("translation").slice(),n=this.get("rotation").slice(),i=this.get("scale").slice();return mt.decompose(e,t,n,i),this.set("translation",t).set("rotation",n).set("scale",i)}getWorldTranslation(){let e=[0,0,0];return mt.decompose(this.getWorldMatrix(),e,[0,0,0,1],[1,1,1]),e}getWorldRotation(){let e=[0,0,0,1];return mt.decompose(this.getWorldMatrix(),[0,0,0],e,[1,1,1]),e}getWorldScale(){let e=[1,1,1];return mt.decompose(this.getWorldMatrix(),[0,0,0],[0,0,0,1],e),e}getWorldMatrix(){let e=[];for(let i=this;i!=null;i=i.getParentNode())e.push(i);let t,n=e.pop().getMatrix();while(t=e.pop())Y8(n,n,t.getMatrix());return n}addChild(e){let t=e.getParentNode();if(t)t.removeChild(e);for(let n of e.listParents())if(n.propertyType==="Scene")n.removeChild(e);return this.addRef("children",e)}removeChild(e){return this.removeRef("children",e)}listChildren(){return this.listRefs("children")}getParentNode(){for(let e of this.listParents())if(e.propertyType==="Node")return e;return null}getMesh(){return this.getRef("mesh")}setMesh(e){return this.setRef("mesh",e)}getCamera(){return this.getRef("camera")}setCamera(e){return this.setRef("camera",e)}getSkin(){return this.getRef("skin")}setSkin(e){return this.setRef("skin",e)}getWeights(){return this.get("weights")}setWeights(e){return this.set("weights",e)}traverse(e){e(this);for(let t of this.listChildren())t.traverse(e);return this}},Zn=class e extends $n{static Mode={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6};init(){this.propertyType="Primitive"}getDefaults(){return Object.assign(super.getDefaults(),{mode:e.Mode.TRIANGLES,material:null,indices:null,attributes:new dn,targets:new It})}getIndices(){return this.getRef("indices")}setIndices(t){return this.setRef("indices",t,{usage:"ELEMENT_ARRAY_BUFFER"})}getAttribute(t){return this.getRefMap("attributes",t)}setAttribute(t,n){return this.setRefMap("attributes",t,n,{usage:"ARRAY_BUFFER"})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}getMaterial(){return this.getRef("material")}setMaterial(t){return this.setRef("material",t)}getMode(){return this.get("mode")}setMode(t){return this.set("mode",t)}listTargets(){return this.listRefs("targets")}addTarget(t){return this.addRef("targets",t)}removeTarget(t){return this.removeRef("targets",t)}},Vg=class extends Bg{init(){this.propertyType="PrimitiveTarget"}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new dn})}getAttribute(e){return this.getRefMap("attributes",e)}setAttribute(e,t){return this.setRefMap("attributes",e,t,{usage:"ARRAY_BUFFER"})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}},af=class extends $n{init(){this.propertyType="Scene"}getDefaults(){return Object.assign(super.getDefaults(),{children:new It})}copy(e,t=Ns){if(t===Ns)throw Error("Scene cannot be copied.");return super.copy(e,t)}addChild(e){let t=e.getParentNode();if(t)t.removeChild(e);return this.addRef("children",e)}removeChild(e){return this.removeRef("children",e)}listChildren(){return this.listRefs("children")}traverse(e){for(let t of this.listChildren())t.traverse(e);return this}},Yw=class extends $n{init(){this.propertyType="Skin"}getDefaults(){return Object.assign(super.getDefaults(),{skeleton:null,inverseBindMatrices:null,joints:new It})}getSkeleton(){return this.getRef("skeleton")}setSkeleton(e){return this.setRef("skeleton",e)}getInverseBindMatrices(){return this.getRef("inverseBindMatrices")}setInverseBindMatrices(e){return this.setRef("inverseBindMatrices",e,{usage:"INVERSE_BIND_MATRICES"})}addJoint(e){return this.addRef("joints",e)}removeJoint(e){return this.removeRef("joints",e)}listJoints(){return this.listRefs("joints")}},Xo=class extends $n{init(){this.propertyType="Texture"}getDefaults(){return Object.assign(super.getDefaults(),{image:null,mimeType:"",uri:""})}getMimeType(){return this.get("mimeType")||Gi.extensionToMimeType(ka.extension(this.get("uri")))}setMimeType(e){return this.set("mimeType",e)}getURI(){return this.get("uri")}setURI(e){this.set("uri",e);let t=Gi.extensionToMimeType(ka.extension(e));if(t)this.set("mimeType",t);return this}getImage(){return this.get("image")}setImage(e){return this.set("image",Ze.assertView(e))}getSize(){let e=this.get("image");if(!e)return null;return Gi.getSize(e,this.getMimeType())}},Ps=class extends $n{_extensions=new Set;init(){this.propertyType="Root"}getDefaults(){return Object.assign(super.getDefaults(),{asset:{generator:`glTF-Transform ${Hw}`,version:"2.0"},defaultScene:null,accessors:new It,animations:new It,buffers:new It,cameras:new It,materials:new It,meshes:new It,nodes:new It,scenes:new It,skins:new It,textures:new It})}constructor(e){super(e);e.addEventListener("node:create",(t)=>{this._addChildOfRoot(t.target)})}clone(){throw Error("Root cannot be cloned.")}copy(e,t=Ns){if(t===Ns)throw Error("Root cannot be copied.");this.set("asset",{...e.get("asset")}),this.setName(e.getName()),this.setExtras({...e.getExtras()}),this.setDefaultScene(e.getDefaultScene()?t(e.getDefaultScene()):null);for(let n of e.listRefMapKeys("extensions")){let i=e.getExtension(n);this.setExtension(n,t(i))}return this}_addChildOfRoot(e){if(e instanceof af)this.addRef("scenes",e);else if(e instanceof sf)this.addRef("nodes",e);else if(e instanceof rf)this.addRef("cameras",e);else if(e instanceof Yw)this.addRef("skins",e);else if(e instanceof zg)this.addRef("meshes",e);else if(e instanceof Da)this.addRef("materials",e);else if(e instanceof Xo)this.addRef("textures",e);else if(e instanceof Jw)this.addRef("animations",e);else if(e instanceof Oe)this.addRef("accessors",e);else if(e instanceof Zw)this.addRef("buffers",e);return this}getAsset(){return this.get("asset")}listExtensionsUsed(){return Array.from(this._extensions)}listExtensionsRequired(){return this.listExtensionsUsed().filter((e)=>e.isRequired())}_enableExtension(e){return this._extensions.add(e),this}_disableExtension(e){return this._extensions.delete(e),this}listScenes(){return this.listRefs("scenes")}setDefaultScene(e){return this.setRef("defaultScene",e)}getDefaultScene(){return this.getRef("defaultScene")}listNodes(){return this.listRefs("nodes")}listCameras(){return this.listRefs("cameras")}listSkins(){return this.listRefs("skins")}listMeshes(){return this.listRefs("meshes")}listMaterials(){return this.listRefs("materials")}listTextures(){return this.listRefs("textures")}listAnimations(){return this.listRefs("animations")}listAccessors(){return this.listRefs("accessors")}listBuffers(){return this.listRefs("buffers")}},of=class e{_graph=new Og;_root=new Ps(this._graph);_logger=La.DEFAULT_INSTANCE;static _GRAPH_DOCUMENTS=new WeakMap;static fromGraph(t){return e._GRAPH_DOCUMENTS.get(t)||null}constructor(){e._GRAPH_DOCUMENTS.set(this._graph,this)}getRoot(){return this._root}getGraph(){return this._graph}getLogger(){return this._logger}setLogger(t){return this._logger=t,this}clone(){throw Error("Use 'cloneDocument(source)' from '@gltf-transform/functions'.")}merge(t){throw Error("Use 'mergeDocuments(target, source)' from '@gltf-transform/functions'.")}async transform(...t){let n=t.map((i)=>i.name);for(let i of t)await i(this,{stack:n});return this}hasExtension(t){return this.getRoot().listExtensionsUsed().some((n)=>n.extensionName===t)}createExtension(t){let n=t.EXTENSION_NAME;return this.getRoot().listExtensionsUsed().find((i)=>i.extensionName===n)||new t(this)}disposeExtension(t){let n=this.getRoot().listExtensionsUsed().find((i)=>i.extensionName===t);if(n)n.dispose()}createScene(t=""){return new af(this._graph,t)}createNode(t=""){return new sf(this._graph,t)}createCamera(t=""){return new rf(this._graph,t)}createSkin(t=""){return new Yw(this._graph,t)}createMesh(t=""){return new zg(this._graph,t)}createPrimitive(){return new Zn(this._graph)}createPrimitiveTarget(t=""){return new Vg(this._graph,t)}createMaterial(t=""){return new Da(this._graph,t)}createTexture(t=""){return new Xo(this._graph,t)}createAnimation(t=""){return new Jw(this._graph,t)}createAnimationChannel(t=""){return new Fa(this._graph,t)}createAnimationSampler(t=""){return new Sl(this._graph,t)}createAccessor(t="",n=null){if(!n)n=this.getRoot().listBuffers()[0];return new Oe(this._graph,t).setBuffer(n)}createBuffer(t=""){return new Zw(this._graph,t)}},zw={logger:La.DEFAULT_INSTANCE,extensions:[],dependencies:{}},fF=new Set(["Buffer","Texture","Material","Mesh","Primitive","Node","Scene"]);Qw=function(e){return e[e.ARRAY_BUFFER=34962]="ARRAY_BUFFER",e[e.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",e}(Qw||{}),Is=class{_doc;jsonDoc;options;static BufferViewTarget=Qw;static BufferViewUsage=j8;static USAGE_TO_TARGET={["ARRAY_BUFFER"]:34962,["ELEMENT_ARRAY_BUFFER"]:34963};accessorIndexMap=new Map;animationIndexMap=new Map;bufferIndexMap=new Map;cameraIndexMap=new Map;skinIndexMap=new Map;materialIndexMap=new Map;meshIndexMap=new Map;nodeIndexMap=new Map;imageIndexMap=new Map;textureDefIndexMap=new Map;textureInfoDefMap=new Map;samplerDefIndexMap=new Map;sceneIndexMap=new Map;imageBufferViews=[];otherBufferViews=new Map;otherBufferViewsIndexMap=new Map;extensionData={};bufferURIGenerator;imageURIGenerator;logger;_accessorUsageMap=new Map;accessorUsageGroupedByParent=new Set(["ARRAY_BUFFER"]);accessorParents=new Map;constructor(e,t,n){this._doc=e,this.jsonDoc=t,this.options=n;let i=e.getRoot(),r=i.listBuffers().length,s=i.listTextures().length;this.bufferURIGenerator=new Vw(r>1,()=>n.basename||"buffer"),this.imageURIGenerator=new Vw(s>1,(a)=>gF(e,a)||n.basename||"texture"),this.logger=e.getLogger()}createTextureInfoDef(e,t){let n={magFilter:t.getMagFilter()||void 0,minFilter:t.getMinFilter()||void 0,wrapS:t.getWrapS(),wrapT:t.getWrapT()},i=JSON.stringify(n);if(!this.samplerDefIndexMap.has(i))this.samplerDefIndexMap.set(i,this.jsonDoc.json.samplers.length),this.jsonDoc.json.samplers.push(n);let r={source:this.imageIndexMap.get(e),sampler:this.samplerDefIndexMap.get(i)},s=JSON.stringify(r);if(!this.textureDefIndexMap.has(s))this.textureDefIndexMap.set(s,this.jsonDoc.json.textures.length),this.jsonDoc.json.textures.push(r);let a={index:this.textureDefIndexMap.get(s)};if(t.getTexCoord()!==0)a.texCoord=t.getTexCoord();if(Object.keys(t.getExtras()).length>0)a.extras=t.getExtras();return this.textureInfoDefMap.set(t,a),a}createPropertyDef(e){let t={};if(e.getName())t.name=e.getName();if(Object.keys(e.getExtras()).length>0)t.extras=e.getExtras();return t}createAccessorDef(e){let t=this.createPropertyDef(e);if(t.type=e.getType(),t.componentType=e.getComponentType(),t.count=e.getCount(),this._doc.getGraph().listParentEdges(e).some((n)=>n.getName()==="attributes"&&n.getAttributes().key==="POSITION"||n.getName()==="input"))t.max=e.getMax([]).map(Math.fround),t.min=e.getMin([]).map(Math.fround);if(e.getNormalized())t.normalized=e.getNormalized();return t}createImageData(e,t,n){if(this.options.format==="GLB")this.imageBufferViews.push(t),e.bufferView=this.jsonDoc.json.bufferViews.length,this.jsonDoc.json.bufferViews.push({buffer:0,byteOffset:-1,byteLength:t.byteLength});else{let i=Gi.mimeTypeToExtension(n.getMimeType());e.uri=this.imageURIGenerator.createURI(n,i),this.assignResourceURI(e.uri,t,!1)}}assignResourceURI(e,t,n){let i=this.jsonDoc.resources;if(!(e in i)){i[e]=t;return}if(t===i[e]){this.logger.warn(`Duplicate resource URI, "${e}".`);return}let r=`Resource URI "${e}" already assigned to different data.`;if(!n){this.logger.warn(r);return}throw Error(r)}getAccessorUsage(e){let t=this._accessorUsageMap.get(e);if(t)return t;if(e.getSparse())return"SPARSE";for(let n of this._doc.getGraph().listParentEdges(e)){let{usage:i}=n.getAttributes();if(i)return i;if(n.getParent().propertyType!=="Root")this.logger.warn(`Missing attribute ".usage" on edge, "${n.getName()}".`)}return"OTHER"}addAccessorToUsageGroup(e,t){let n=this._accessorUsageMap.get(e);if(n&&n!==t)throw Error(`Accessor with usage "${n}" cannot be reused as "${t}".`);return this._accessorUsageMap.set(e,t),this}};({BufferViewUsage:ef}=Is),{UNSIGNED_INT:bF,UNSIGNED_SHORT:xF,UNSIGNED_BYTE:yF}=Oe.ComponentType,_F=new Set(["Accessor","Buffer","Material","Mesh"]);eS=class extends TF{_fetchConfig;constructor(e=Dg.DEFAULT_INIT){super();this._fetchConfig=e}async readURI(e,t){let n=await fetch(e,this._fetchConfig);switch(t){case"view":return new Uint8Array(await n.arrayBuffer());case"text":return n.text()}}resolve(e,t){return Dg.resolve(e,t)}dirname(e){return Dg.dirname(e)}}});function SF(){return{vkFormat:0,typeSize:1,pixelWidth:0,pixelHeight:0,pixelDepth:0,layerCount:0,faceCount:1,levelCount:0,supercompressionScheme:0,levels:[],dataFormatDescriptor:[{vendorId:0,descriptorType:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],keyValue:{},globalData:null}}class Jo{constructor(e,t,n,i){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,n),this._littleEndian=i,this._offset=0}_nextUint8(){let e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){let e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){let e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){let e=this._dataView.getUint32(this._offset,this._littleEndian),t=this._dataView.getUint32(this._offset+4,this._littleEndian),n=e+4294967296*t;return this._offset+=8,n}_nextInt32(){let e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){let t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t=0){let n=this._offset,i=0;while(this._dataView.getUint8(this._offset)!==t&&i<e)i++,this._offset++;if(i<e)this._offset++;return new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,i)}}function tS(e){return new TextDecoder().decode(e)}function cf(e){let t=new Uint8Array(e.buffer,e.byteOffset,Kn.length);if(t[0]!==Kn[0]||t[1]!==Kn[1]||t[2]!==Kn[2]||t[3]!==Kn[3]||t[4]!==Kn[4]||t[5]!==Kn[5]||t[6]!==Kn[6]||t[7]!==Kn[7]||t[8]!==Kn[8]||t[9]!==Kn[9]||t[10]!==Kn[10]||t[11]!==Kn[11])throw Error("Missing KTX 2.0 identifier.");let n=SF(),i=17*Uint32Array.BYTES_PER_ELEMENT,r=new Jo(e,Kn.length,i,!0);n.vkFormat=r._nextUint32(),n.typeSize=r._nextUint32(),n.pixelWidth=r._nextUint32(),n.pixelHeight=r._nextUint32(),n.pixelDepth=r._nextUint32(),n.layerCount=r._nextUint32(),n.faceCount=r._nextUint32(),n.levelCount=r._nextUint32(),n.supercompressionScheme=r._nextUint32();let s=r._nextUint32(),a=r._nextUint32(),o=r._nextUint32(),c=r._nextUint32(),l=r._nextUint64(),u=r._nextUint64(),d=Math.max(n.levelCount,1)*3*8,f=new Jo(e,Kn.length+i,d,!0);for(let ie=0,ce=Math.max(n.levelCount,1);ie<ce;ie++)n.levels.push({levelData:new Uint8Array(e.buffer,e.byteOffset+f._nextUint64(),f._nextUint64()),uncompressedByteLength:f._nextUint64()});let h=new Jo(e,s,a,!0);h._skip(4);let b=h._nextUint16(),m=h._nextUint16(),g=h._nextUint16(),p=h._nextUint16(),x=h._nextUint8(),_=h._nextUint8(),y=h._nextUint8(),v=h._nextUint8(),E=[h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8()],w=[h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8()],A={vendorId:b,descriptorType:m,versionNumber:g,colorModel:x,colorPrimaries:_,transferFunction:y,flags:v,texelBlockDimension:E,bytesPlane:w,samples:[]},P=6,S=4,R=(p/4-P)/S;for(let ie=0;ie<R;ie++){let ce={bitOffset:h._nextUint16(),bitLength:h._nextUint8(),channelType:h._nextUint8(),samplePosition:[h._nextUint8(),h._nextUint8(),h._nextUint8(),h._nextUint8()],sampleLower:Number.NEGATIVE_INFINITY,sampleUpper:Number.POSITIVE_INFINITY};if(ce.channelType&64)ce.sampleLower=h._nextInt32(),ce.sampleUpper=h._nextInt32();else ce.sampleLower=h._nextUint32(),ce.sampleUpper=h._nextUint32();A.samples[ie]=ce}n.dataFormatDescriptor.length=0,n.dataFormatDescriptor.push(A);let k=new Jo(e,o,c,!0);while(k._offset<c){let ie=k._nextUint32(),ce=k._scan(ie),_e=tS(ce);if(n.keyValue[_e]=k._nextUint8Array(ie-ce.byteLength-1),_e.match(/^ktx/i)){let ke=tS(n.keyValue[_e]);n.keyValue[_e]=ke.substring(0,ke.lastIndexOf("\x00"))}let Re=ie%4?4-ie%4:0;k._skip(Re)}if(u<=0)return n;let C=new Jo(e,l,u,!0),U=C._nextUint16(),L=C._nextUint16(),O=C._nextUint32(),K=C._nextUint32(),B=C._nextUint32(),X=C._nextUint32(),q=[];for(let ie=0,ce=Math.max(n.levelCount,1);ie<ce;ie++)q.push({imageFlags:C._nextUint32(),rgbSliceByteOffset:C._nextUint32(),rgbSliceByteLength:C._nextUint32(),alphaSliceByteOffset:C._nextUint32(),alphaSliceByteLength:C._nextUint32()});let le=l+C._offset,de=le+O,Me=de+K,pe=Me+B,J=new Uint8Array(e.buffer,e.byteOffset+le,O),F=new Uint8Array(e.buffer,e.byteOffset+de,K),W=new Uint8Array(e.buffer,e.byteOffset+Me,B),ne=new Uint8Array(e.buffer,e.byteOffset+pe,X);return n.globalData={endpointCount:U,selectorCount:L,imageDescs:q,endpointsData:J,selectorsData:F,tablesData:W,extendedData:ne},n}var nS=0,iS=163,rS=166,jg=0,sS=123,aS=1000066000,P$,Kn;var oS=ht(()=>{P$=new Uint8Array([0]),Kn=[171,75,84,88,32,50,48,187,13,10,26,10]});function OF(e,t,n,i){let r=t.createFeatureID().setFeatureCount(i.featureCount);if(i.nullFeatureId!==void 0)r.setNullFeatureID(i.nullFeatureId);if(i.label!==void 0)r.setLabel(i.label);if(i.attribute!==void 0)r.setAttribute(i.attribute);let s=i.texture;if(s!==void 0){let a=kF(t,n,s);r.setTexture(a)}if(i.propertyTable!==void 0){let a=e.getRoot().getExtension(et).listPropertyTables();r.setPropertyTable(a[i.propertyTable])}return r}function kF(e,t,n){let i=e.createFeatureIDTexture(),{json:r}=t.jsonDoc;if(n.channels)i.setChannels(n.channels);if(n.index!==void 0){let s=r.textures[n.index].source;i.setTexture(t.textures[s]),t.setTextureInfo(i.getTextureInfo(),n)}return i}function DF(e,t,n){let i=e.getRoot(),r={featureCount:n.getFeatureCount()};if(n.getNullFeatureID()!=null)r.nullFeatureId=n.getNullFeatureID();if(n.getLabel())r.label=n.getLabel();if(n.getAttribute()!=null)r.attribute=n.getAttribute();if(n.getTexture()){let s=n.getTexture(),a=s.getTexture(),o=s.getTextureInfo();r.texture=t.createTextureInfoDef(a,o);let c=s.getChannels();if(!mt.eq(c,[0]))r.texture.channels=c}if(n.getPropertyTable()){let s=i.getExtension(et),a=n.getPropertyTable();r.propertyTable=s.listPropertyTables().indexOf(a)}return r}function UF(e){if(!e.extensions||!e.extensions.EXT_meshopt_compression)return!1;return!!e.extensions[Yn].fallback}function VF(e,t,n,i){let{filter:r,bits:s}=i,a={array:e.getArray(),byteStride:e.getElementSize()*e.getComponentSize(),componentType:e.getComponentType(),normalized:e.getNormalized()};if(n!=="ATTRIBUTES")return a;if(r!=="NONE"){let o=e.getNormalized()?jF(e):new Float32Array(a.array);switch(r){case"EXPONENTIAL":a.byteStride=e.getElementSize()*4,a.componentType=zF,a.normalized=!1,a.array=t.encodeFilterExp(o,e.getCount(),a.byteStride,s);break;case"OCTAHEDRAL":a.byteStride=s>8?8:4,a.componentType=s>8?uS:BF,a.normalized=!0,o=e.getElementSize()===3?GF(o):o,a.array=t.encodeFilterOct(o,e.getCount(),a.byteStride,s);break;case"QUATERNION":a.byteStride=8,a.componentType=uS,a.normalized=!0,a.array=t.encodeFilterQuat(o,e.getCount(),a.byteStride,s);break;default:throw Error("Invalid filter.")}if(a.min=e.getMin([]),a.max=e.getMax([]),e.getNormalized())a.min=a.min.map((c)=>Kg(c,e.getComponentType())),a.max=a.max.map((c)=>Kg(c,e.getComponentType()));if(a.normalized)a.min=a.min.map((c)=>dS(c,a.componentType)),a.max=a.max.map((c)=>dS(c,a.componentType))}else if(a.byteStride%4)a.array=HF(a.array,e.getElementSize()),a.byteStride=a.array.byteLength/e.getCount();return a}function jF(e){let t=e.getComponentType(),n=e.getArray(),i=new Float32Array(n.length);for(let r=0;r<n.length;r++)i[r]=Kg(n[r],t);return i}function HF(e,t){let n=Ze.padNumber(e.BYTES_PER_ELEMENT*t)/e.BYTES_PER_ELEMENT,i=e.length/t,r=new e.constructor(i*n);for(let s=0;s*t<e.length;s++)for(let a=0;a<t;a++)r[s*n+a]=e[s*t+a];return r}function GF(e){let t=new Float32Array(e.length*4/3);for(let n=0,i=e.length/3;n<i;n++)t[n*4]=e[n*3],t[n*4+1]=e[n*3+1],t[n*4+2]=e[n*3+2];return t}function $F(e,t){if(t===Is.BufferViewUsage.ELEMENT_ARRAY_BUFFER)return e.listParents().some((n)=>n instanceof Zn&&n.getMode()===Zn.Mode.TRIANGLES)?"TRIANGLES":"INDICES";return"ATTRIBUTES"}function KF(e,t){let n=t.getGraph().listParentEdges(e).filter((i)=>!(i.getParent()instanceof Ps));for(let i of n){let r=i.getName(),s=i.getAttributes().key||"",a=i.getParent().propertyType===Q.PRIMITIVE_TARGET;if(r==="indices")return{filter:"NONE"};if(r==="attributes"){if(s==="POSITION")return{filter:"NONE"};if(s==="TEXCOORD_0")return{filter:"NONE"};if(s.startsWith("JOINTS_"))return{filter:"NONE"};if(s.startsWith("WEIGHTS_"))return{filter:"NONE"};if(s==="NORMAL"||s==="TANGENT")return a?{filter:"NONE"}:{filter:"OCTAHEDRAL",bits:8}}if(r==="output"){let o=MS(e);if(o==="rotation")return{filter:"QUATERNION",bits:16};if(o==="translation")return{filter:"EXPONENTIAL",bits:12};if(o==="scale")return{filter:"EXPONENTIAL",bits:12};return{filter:"NONE"}}if(r==="input")return{filter:"NONE"};if(r==="inverseBindMatrices")return{filter:"NONE"}}return{filter:"NONE"}}function MS(e){for(let t of e.listParents()){if(!(t instanceof Sl))continue;for(let n of t.listParents()){if(!(n instanceof Fa))continue;return n.getTargetPath()}}return null}function c2(e,t,n){let i=e.createStructuralMetadata();if(n.schema!==void 0){let o=l2(e,n.schema);i.setSchema(o)}else if(n.schemaUri){let o=n.schemaUri;i.setSchemaUri(o)}let r=n.propertyTextures||[];for(let o of r){let c=p2(e,t,o);i.addPropertyTexture(c)}let s=n.propertyTables||[];for(let o of s){let c=g2(e,t,o);i.addPropertyTable(c)}let a=n.propertyAttributes||[];for(let o of a){let c=x2(e,o);i.addPropertyAttribute(c)}return i}function l2(e,t){let n=e.createSchema().setId(t.id);if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);if(t.version!==void 0)n.setVersion(t.version);let i=t.classes||{};for(let s of Object.keys(i)){let a=i[s];n.setClass(s,u2(e,a))}let r=t.enums||{};for(let s of Object.keys(r))n.setEnum(s,f2(e,r[s]));return n}function u2(e,t){let n=e.createClass();if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);let i=t.properties||{};for(let r of Object.keys(i)){let s=d2(e,i[r]);n.setProperty(r,s)}return n}function d2(e,t){let n=e.createClassProperty().setType(t.type);if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);if(t.componentType!==void 0)n.setComponentType(t.componentType);if(t.enumType!==void 0)n.setEnumType(t.enumType);if(t.array!==void 0)n.setArray(t.array);if(t.count!==void 0)n.setCount(t.count);if(t.normalized!==void 0)n.setNormalized(t.normalized);if(t.offset!==void 0)n.setOffset(t.offset);if(t.scale!==void 0)n.setScale(t.scale);if(t.max!==void 0)n.setMax(t.max);if(t.min!==void 0)n.setMin(t.min);if(t.required!==void 0)n.setRequired(t.required);if(t.noData!==void 0)n.setNoData(t.noData);if(t.default!==void 0)n.setDefault(t.default);return n}function f2(e,t){let n=e.createEnum();if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);if(t.valueType!==void 0)n.setValueType(t.valueType);let i=t.values||{};for(let r of i)n.addEnumValue(h2(e,r));return n}function h2(e,t){let n=e.createEnumValue();if(t.name!==void 0)n.setName(t.name);if(t.description!==void 0)n.setDescription(t.description);if(t.value!==void 0)n.setValue(t.value);return n}function p2(e,t,n){let i=e.createPropertyTexture();if(i.setClass(n.class),n.name!==void 0)i.setName(n.name);let r=n.properties||{};for(let s of Object.keys(r)){let a=m2(e,t,r[s]);i.setProperty(s,a)}return i}function m2(e,t,n){let i=e.createPropertyTextureProperty(),r=t.jsonDoc.json.textures||[];if(n.channels)i.setChannels(n.channels);let s=r[n.index].source;if(s!==void 0){let a=t.textures[s];i.setTexture(a);let o=i.getTextureInfo();if(o)t.setTextureInfo(o,n)}if(n.offset!==void 0)i.setOffset(n.offset);if(n.scale!==void 0)i.setScale(n.scale);if(n.max!==void 0)i.setMax(n.max);if(n.min!==void 0)i.setMin(n.min);return i}function g2(e,t,n){let i=e.createPropertyTable().setClass(n.class).setCount(n.count);if(n.name!==void 0)i.setName(n.name);let r=n.properties||{};for(let s of Object.keys(r)){let a=b2(e,t,r[s]);i.setProperty(s,a)}return i}function b2(e,t,n){let i=e.createPropertyTableProperty(),r=Hg(t,n.values);if(i.setValues(r),n.arrayOffsets!==void 0){let s=Hg(t,n.arrayOffsets);i.setArrayOffsets(s)}if(n.stringOffsets!==void 0){let s=Hg(t,n.stringOffsets);i.setStringOffsets(s)}if(n.arrayOffsetType!==void 0)i.setArrayOffsetType(n.arrayOffsetType);if(n.stringOffsetType!==void 0)i.setStringOffsetType(n.stringOffsetType);if(n.offset!==void 0)i.setOffset(n.offset);if(n.scale!==void 0)i.setScale(n.scale);if(n.max!==void 0)i.setMax(n.max);if(n.min!==void 0)i.setMin(n.min);return i}function x2(e,t){let n=e.createPropertyAttribute();if(n.setClass(t.class),t.name!==void 0)n.setName(t.name);let i=t.properties||{};for(let r of Object.keys(i)){let s=y2(e,i[r]);n.setProperty(r,s)}return n}function y2(e,t){let n=e.createPropertyAttributeProperty();if(n.setAttribute(t.attribute),t.offset!==void 0)n.setOffset(t.offset);if(t.scale!==void 0)n.setScale(t.scale);if(t.max!==void 0)n.setMax(t.max);if(t.min!==void 0)n.setMin(t.min);return n}function _2(e,t){let n={},i=t.getSchema();if(i)n.schema=v2(i);let r=t.getSchemaUri();if(r)n.schemaUri=r;let s=t.listPropertyTables();if(s.length>0){let c=[];for(let l of s){let u=S2(e,l);c.push(u)}n.propertyTables=c}let a=t.listPropertyTextures();if(a.length>0){let c=[];for(let l of a){let u=C2(e,l);c.push(u)}n.propertyTextures=c}let o=t.listPropertyAttributes();if(o.length>0){let c=[];for(let l of o){let u=R2(l);c.push(u)}n.propertyAttributes=c}return n}function v2(e){let t={id:e.getId()},n=e.listClassKeys();if(n.length>0){t.classes={};for(let r of n){let s=E2(e.getClass(r));t.classes[r]=s}}let i=e.listEnumKeys();if(i.length>0){t.enums={};for(let r of i){let s=A2(e.getEnum(r));t.enums[r]=s}}if(e.getName())t.name=e.getName();if(e.getDescription())t.description=e.getDescription();if(e.getVersion())t.version=e.getVersion();return t}function E2(e){let t={},n=e.listPropertyKeys();if(n.length>0){t.properties={};for(let i of n){let r=e.getProperty(i);t.properties[i]=T2(r)}}if(e.getName())t.name=e.getName();if(e.getDescription())t.description=e.getDescription();return t}function T2(e){let t={type:e.getType()};if(e.getArray())t.array=e.getArray();if(e.getNormalized())t.normalized=e.getNormalized();if(e.getRequired())t.required=e.getRequired();if(e.getName())t.name=e.getName();if(e.getDescription())t.description=e.getDescription();if(e.getComponentType()!=null)t.componentType=e.getComponentType();if(e.getEnumType()!=null)t.enumType=e.getEnumType();if(e.getCount()!=null)t.count=e.getCount();if(e.getOffset()!=null)t.offset=e.getOffset();if(e.getScale()!=null)t.scale=e.getScale();if(e.getMax()!=null)t.max=e.getMax();if(e.getMin()!=null)t.min=e.getMin();if(e.getNoData()!=null)t.noData=e.getNoData();if(e.getDefault()!=null)t.default=e.getDefault();return t}function A2(e){let t={values:e.listValues().map(w2)};if(e.getName())t.name=e.getName();if(e.getDescription())t.description=e.getDescription();if(e.getValueType()!=="UINT16")t.valueType=e.getValueType();return t}function w2(e){let t={name:e.getName(),value:e.getValue()};if(e.getDescription())t.description=e.getDescription();return t}function S2(e,t){let n={class:t.getClass(),count:t.getCount()};if(t.getName())n.name=t.getName();let i=t.listPropertyKeys();if(i.length>0){n.properties={};for(let r of i){let s=M2(e,t.getProperty(r));n.properties[r]=s}}return n}function M2(e,t){let n=t.getValues(),i={values:e.otherBufferViewsIndexMap.get(n)};if(t.getArrayOffsets()){let r=t.getArrayOffsets();i.arrayOffsets=e.otherBufferViewsIndexMap.get(r)}if(t.getStringOffsets()){let r=t.getStringOffsets();i.stringOffsets=e.otherBufferViewsIndexMap.get(r)}if(t.getArrayOffsetType()!=null)i.arrayOffsetType=t.getArrayOffsetType();if(t.getStringOffsetType()!=null)i.stringOffsetType=t.getStringOffsetType();if(t.getOffset()!=null)i.offset=t.getOffset();if(t.getScale()!=null)i.scale=t.getScale();if(t.getMax()!=null)i.max=t.getMax();if(t.getMin()!=null)i.min=t.getMin();return i}function R2(e){let t={class:e.getClass()};if(e.getName())t.name=e.getName();let n=e.listPropertyKeys();if(n.length>0){t.properties={};for(let i of n){let r=I2(e.getProperty(i));t.properties[i]=r}}return t}function I2(e){let t={attribute:e.getAttribute()};if(e.getOffset()!=null)t.offset=e.getOffset();if(e.getScale()!=null)t.scale=e.getScale();if(e.getMax()!=null)t.max=e.getMax();if(e.getMin()!=null)t.min=e.getMin();return t}function C2(e,t){let n={class:t.getClass()};if(t.getName())n.name=t.getName();let i=t.listPropertyKeys();if(i.length>0){n.properties={};for(let r of i){let s=N2(e,t.getProperty(r));n.properties[r]=s}}return n}function N2(e,t){let n=t.getTexture(),i=t.getTextureInfo(),r=t.getChannels(),s=e.createTextureInfoDef(n,i);if(!mt.eq(r,[0]))s.channels=r;if(t.getOffset()!=null)s.offset=t.getOffset();if(t.getScale()!=null)s.scale=t.getScale();if(t.getMax()!=null)s.max=t.getMax();if(t.getMin()!=null)s.min=t.getMin();return s}function Hg(e,t){let n=e.jsonDoc,i=n.json.buffers||[],r=(n.json.bufferViews||[])[t],s=i[r.buffer],a=s.uri?n.resources[s.uri]:n.resources[Cs],o=r.byteOffset||0,c=r.byteLength;return a.slice(o,o+c)}function P2(e,t){let n=e.getRoot().listBuffers()[0],i=t.otherBufferViews.get(n);if(!i)i=[],t.otherBufferViews.set(n,i);return i}function hS(e,t){if(e.byteLength<4+t)return null;let n=e.getUint32(t);if(e.byteLength<n+t||n<8)return null;return{type:Ze.decodeText(new Uint8Array(e.buffer,e.byteOffset+t+4,4)),start:t+8,end:t+n}}function F2(e,t){let n=new yn.DecoderBuffer;try{if(n.Init(t,t.length),e.GetEncodedGeometryType(n)!==yn.TRIANGULAR_MESH)throw Error(`[${tn}] Unknown geometry type.`);let i=new yn.Mesh;if(!e.DecodeBufferToMesh(n,i).ok()||i.ptr===0)throw Error(`[${tn}] Decoding failure.`);return i}finally{yn.destroy(n)}}function U2(e,t){let n=t.num_faces()*3,i,r;if(t.num_points()<=65534){let s=n*Uint16Array.BYTES_PER_ELEMENT;i=yn._malloc(s),e.GetTrianglesUInt16Array(t,s,i),r=new Uint16Array(yn.HEAPU16.buffer,i,n).slice()}else{let s=n*Uint32Array.BYTES_PER_ELEMENT;i=yn._malloc(s),e.GetTrianglesUInt32Array(t,s,i),r=new Uint32Array(yn.HEAPU32.buffer,i,n).slice()}return yn._free(i),r}function B2(e,t,n,i){let r=NS[i.componentType],s=CS[i.componentType],a=n.num_components(),o=t.num_points()*a,c=o*s.BYTES_PER_ELEMENT,l=yn._malloc(c);e.GetAttributeDataArrayForAllPoints(t,n,r,c,l);let u=new s(yn.HEAPF32.buffer,l,o).slice();return yn._free(l),u}function z2(e){yn=e,CS={[Oe.ComponentType.FLOAT]:Float32Array,[Oe.ComponentType.UNSIGNED_INT]:Uint32Array,[Oe.ComponentType.UNSIGNED_SHORT]:Uint16Array,[Oe.ComponentType.UNSIGNED_BYTE]:Uint8Array,[Oe.ComponentType.SHORT]:Int16Array,[Oe.ComponentType.BYTE]:Int8Array},NS={[Oe.ComponentType.FLOAT]:yn.DT_FLOAT32,[Oe.ComponentType.UNSIGNED_INT]:yn.DT_UINT32,[Oe.ComponentType.UNSIGNED_SHORT]:yn.DT_UINT16,[Oe.ComponentType.UNSIGNED_BYTE]:yn.DT_UINT8,[Oe.ComponentType.SHORT]:yn.DT_INT16,[Oe.ComponentType.BYTE]:yn.DT_INT8}}function j2(e){wi=e}function H2(e,t=gS){let n={...gS,...t};n.quantizationBits={...PS,...t.quantizationBits};let i=new wi.MeshBuilder,r=new wi.Mesh,s=new wi.ExpertEncoder(r),a={},o=new wi.DracoInt8Array,c=e.listTargets().length>0,l=!1;for(let m of e.listSemantics()){let g=e.getAttribute(m);if(g.getSparse()){l=!0;continue}let p=G2(m),x=$2(i,g.getComponentType(),r,wi[p],g.getCount(),g.getElementSize(),g.getArray());if(x===-1)throw Error(`Error compressing "${m}" attribute.`);if(a[m]=x,n.quantizationVolume==="mesh"||m!=="POSITION")s.SetAttributeQuantization(x,n.quantizationBits[p]);else if(typeof n.quantizationVolume==="object"){let{quantizationVolume:_}=n,y=Math.max(_.max[0]-_.min[0],_.max[1]-_.min[1],_.max[2]-_.min[2]);s.SetAttributeExplicitQuantization(x,n.quantizationBits[p],g.getElementSize(),_.min,y)}else throw Error("Invalid quantization volume state.")}let u=e.getIndices();if(!u)throw new Wg("Primitive must have indices.");if(i.AddFacesToMesh(r,u.getCount()/3,u.getArray()),s.SetSpeedOptions(n.encodeSpeed,n.decodeSpeed),s.SetTrackEncodedProperties(!0),n.method===0||c||l)s.SetEncodingMethod(wi.MESH_SEQUENTIAL_ENCODING);else s.SetEncodingMethod(wi.MESH_EDGEBREAKER_ENCODING);let d=s.EncodeToDracoBuffer(!(c||l),o);if(d<=0)throw new Wg("Error applying Draco compression.");let f=new Uint8Array(d);for(let m=0;m<d;++m)f[m]=o.GetValue(m);let h=s.GetNumberOfEncodedPoints(),b=s.GetNumberOfEncodedFaces()*3;return wi.destroy(o),wi.destroy(r),wi.destroy(i),wi.destroy(s),{numVertices:h,numIndices:b,data:f,attributeIDs:a}}function G2(e){if(e==="POSITION")return"POSITION";else if(e==="NORMAL")return"NORMAL";else if(e.startsWith("COLOR_"))return"COLOR";else if(e.startsWith("TEXCOORD_"))return"TEX_COORD";return"GENERIC"}function $2(e,t,n,i,r,s,a){switch(t){case Oe.ComponentType.UNSIGNED_BYTE:return e.AddUInt8Attribute(n,i,r,s,a);case Oe.ComponentType.BYTE:return e.AddInt8Attribute(n,i,r,s,a);case Oe.ComponentType.UNSIGNED_SHORT:return e.AddUInt16Attribute(n,i,r,s,a);case Oe.ComponentType.SHORT:return e.AddInt16Attribute(n,i,r,s,a);case Oe.ComponentType.UNSIGNED_INT:return e.AddUInt32Attribute(n,i,r,s,a);case Oe.ComponentType.FLOAT:return e.AddFloatAttribute(n,i,r,s,a);default:throw Error(`Unexpected component type, "${t}".`)}}function K2(e){let t=e.getLogger(),n=new Set,i=new Set,r=0,s=0;for(let d of e.getRoot().listMeshes())for(let f of d.listPrimitives())if(!f.getIndices())i.add(f),r++;else if(f.getMode()!==Zn.Mode.TRIANGLES)i.add(f),s++;else n.add(f);if(r>0)t.warn(`[${tn}] Skipping Draco compression of ${r} non-indexed primitives.`);if(s>0)t.warn(`[${tn}] Skipping Draco compression of ${s} non-TRIANGLES primitives.`);let a=e.getRoot().listAccessors(),o=new Map;for(let d=0;d<a.length;d++)o.set(a[d],d);let c=new Map,l=new Set,u=new Map;for(let d of Array.from(n)){let f=bS(d,o);if(l.has(f)){u.set(d,f);continue}if(c.has(d.getIndices())){let h=d.getIndices(),b=h.clone();o.set(b,e.getRoot().listAccessors().length-1),d.swap(h,b)}for(let h of d.listAttributes())if(c.has(h)){let b=h.clone();o.set(b,e.getRoot().listAccessors().length-1),d.swap(h,b)}f=bS(d,o),l.add(f),u.set(d,f),c.set(d.getIndices(),f);for(let h of d.listAttributes())c.set(h,f)}for(let d of Array.from(c.keys())){let f=new Set(d.listParents().map((h)=>h.propertyType));if(f.size!==2||!f.has(Q.PRIMITIVE)||!f.has(Q.ROOT))throw Error(`[${tn}] Compressed accessors must only be used as indices or vertex attributes.`)}for(let d of Array.from(n)){let f=u.get(d),h=d.getIndices();if(c.get(h)!==f||d.listAttributes().some((b)=>c.get(b)!==f))throw Error(`[${tn}] Draco primitives must share all, or no, accessors.`)}for(let d of Array.from(i)){let f=d.getIndices();if(c.has(f)||d.listAttributes().some((h)=>c.has(h)))throw Error(`[${tn}] Accessor cannot be shared by compressed and uncompressed primitives.`)}return u}function bS(e,t){let n=[],i=e.getIndices();n.push(t.get(i));for(let r of e.listAttributes())n.push(t.get(r));return n.sort().join("|")}function VU(e){return e.vkFormat>jg&&e.vkFormat<=sS}function SS(e){let t=e.vkFormat===aS&&e.dataFormatDescriptor[0].colorModel===167;return e.vkFormat===jg||t}function Gg(e){return JSON.parse(JSON.stringify(e))}var Os="EXT_mesh_gpu_instancing",Gr="EXT_mesh_features",Yn="EXT_meshopt_compression",et="EXT_structural_metadata",lf="EXT_texture_webp",uf="EXT_texture_avif",MF="KHR_accessor_float16",RF="KHR_accessor_float64",tn="KHR_draco_mesh_compression",Hr="KHR_lights_punctual",ks="KHR_materials_anisotropy",Ds="KHR_materials_clearcoat",Ls="KHR_materials_diffuse_transmission",Fs="KHR_materials_dispersion",Us="KHR_materials_emissive_strength",Bs="KHR_materials_ior",zs="KHR_materials_iridescence",Vs="KHR_materials_pbrSpecularGlossiness",js="KHR_materials_sheen",Hs="KHR_materials_specular",Gs="KHR_materials_transmission",Zo="KHR_materials_unlit",$s="KHR_materials_volume",hi="KHR_materials_variants",cS="KHR_mesh_primitive_restart",lS="KHR_mesh_quantization",Ks="KHR_node_visibility",df="KHR_texture_basisu",Ws="KHR_texture_transform",$i="KHR_xmp_json_ld",IF,CF,NF,Ml,PF,$g="INSTANCE_ATTRIBUTE",LF,ff,FF,BF,uS,zF,dS,Kg,fS,Rl,WF,XF,qF,JF,ZF,YF,QF,e2,t2,n2,i2,r2,s2,a2,o2,O2=class{match(e){return e.length>=12&&Ze.decodeText(e.slice(4,12))==="ftypavif"}getSize(e){if(!this.match(e))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=hS(t,0);if(!n)return null;let i=n.end;while(n=hS(t,i))if(n.type==="meta")i=n.start+4;else if(n.type==="iprp"||n.type==="ipco")i=n.start;else if(n.type==="ispe")return[t.getUint32(n.start+4),t.getUint32(n.start+8)];else if(n.type==="mdat")break;else i=n.end;return null}getChannels(e){return 4}},RS,k2=class{match(e){return e.length>=12&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}getSize(e){let t=Ze.decodeText(e.slice(0,4)),n=Ze.decodeText(e.slice(8,12));if(t!=="RIFF"||n!=="WEBP")return null;let i=new DataView(e.buffer,e.byteOffset),r=12;while(r<i.byteLength){let s=Ze.decodeText(new Uint8Array([i.getUint8(r),i.getUint8(r+1),i.getUint8(r+2),i.getUint8(r+3)])),a=i.getUint32(r+4,!0);if(s==="VP8 ")return[i.getInt16(r+14,!0)&16383,i.getInt16(r+16,!0)&16383];else if(s==="VP8L"){let o=i.getUint8(r+9),c=i.getUint8(r+10),l=i.getUint8(r+11),u=i.getUint8(r+12);return[1+((c&63)<<8|o),1+((u&15)<<10|l<<2|(c&192)>>6)]}r+=8+a+a%2}return null}getChannels(e){return 4}},IS,pS,D2,mS,L2,yn,CS,NS,wi,V2,PS,gS,Wg,OS,xS,W2,X2,q2,J2,Z2,Y2,yS,_S,Q2,eU,tU,nU,iU,rU,sU,aU,oU,cU,lU,uU,dU,fU,kS,hU,pU,mU,gU,vS,ES,TS,AS,bU,DS,xU,yU,_U,vU,EU,TU,AU,wU,SU,MU,RU,LS,IU,CU,NU,PU,FS,OU,kU,wS,DU,LU,FU,UU,US,Il,BU,zU,jU=class{match(e){return e[0]===171&&e[1]===75&&e[2]===84&&e[3]===88&&e[4]===32&&e[5]===50&&e[6]===48&&e[7]===187&&e[8]===13&&e[9]===10&&e[10]===26&&e[11]===10}getSize(e){let t=cf(e);return[t.pixelWidth,t.pixelHeight]}getChannels(e){let t=cf(e),n=t.dataFormatDescriptor[0];if(VU(t))return n.samples.length;if(SS(t))switch(n.colorModel){case iS:return n.samples.length===2&&(n.samples[1].channelType&15)===15?4:3;case rS:return(n.samples[0].channelType&15)===3?4:3;default:throw Error(`Unexpected KTX2 colorModel, "${n.colorModel}".`)}throw Error(`Unexpected KTX2 vkFormat, "${t.vkFormat}".`)}getVRAMByteLength(e){let t=cf(e),n=0;if(SS(t)){let i=this.getChannels(e)>3;for(let r=0;r<t.levels.length;r++){let s=t.levels[r];if(s.uncompressedByteLength)n+=s.uncompressedByteLength;else{let a=Math.max(1,Math.floor(t.pixelWidth/Math.pow(2,r))),o=Math.max(1,Math.floor(t.pixelHeight/Math.pow(2,r))),c=i?16:8;n+=a/4*(o/4)*c}}}else for(let i of t.levels)if(t.supercompressionScheme===nS)n+=i.levelData.byteLength;else n+=i.uncompressedByteLength;return n}},Xg,HU,GU,$U,KU,WU,XU,BS;var hf=ht(()=>{qo();oS();IF=class extends nt{static EXTENSION_NAME=Gr;init(){this.extensionName=Gr,this.propertyType="FeatureID",this.parentTypes=["Features"]}getDefaults(){return Object.assign(super.getDefaults(),{nullFeatureId:null,label:"",attribute:null,texture:null,propertyTable:null})}getFeatureCount(){return this.get("featureCount")}setFeatureCount(e){return this.set("featureCount",e)}getNullFeatureID(){return this.get("nullFeatureId")}setNullFeatureID(e){return this.set("nullFeatureId",e)}getLabel(){return this.get("label")}setLabel(e){return this.set("label",e)}getAttribute(){return this.get("attribute")}setAttribute(e){return this.set("attribute",e)}getTexture(){return this.getRef("texture")}setTexture(e){return this.setRef("texture",e)}getPropertyTable(){return this.getRef("propertyTable")}setPropertyTable(e){return this.setRef("propertyTable",e)}},CF=class extends nt{static EXTENSION_NAME=Gr;init(){this.extensionName=Gr,this.propertyType="FeatureIDTexture",this.parentTypes=["FeatureID"]}getDefaults(){let e=new wt(this.graph,"textureInfo");return e.setMinFilter(wt.MagFilter.NEAREST),e.setMagFilter(wt.MagFilter.NEAREST),Object.assign(super.getDefaults(),{channels:[0],texture:null,textureInfo:e})}getChannels(){return this.get("channels")}setChannels(e){return this.set("channels",e)}getTexture(){return this.getRef("texture")}setTexture(e){return this.setRef("texture",e)}getTextureInfo(){return this.getRef("texture")?this.getRef("textureInfo"):null}},NF=class extends nt{static EXTENSION_NAME=Gr;init(){this.extensionName=Gr,this.propertyType="Features",this.parentTypes=[Q.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{featureIds:new It([])})}listFeatureIDs(){return this.listRefs("featureIds")}addFeatureID(e){return this.addRef("featureIds",e)}removeFeatureID(e){return this.removeRef("featureIds",e)}},Ml=Gr,PF=class extends _t{extensionName=Gr;static EXTENSION_NAME=Gr;createFeatures(){return new NF(this.document.getGraph())}createFeatureID(){return new IF(this.document.getGraph())}createFeatureIDTexture(){return new CF(this.document.getGraph())}read(e){return(e.jsonDoc.json.meshes||[]).forEach((t,n)=>{(t.primitives||[]).forEach((i,r)=>{this._readPrimitive(e,n,i,r)})}),this}_readPrimitive(e,t,n,i){if(!n.extensions||!n.extensions[Ml])return;let r=this.createFeatures(),s=n.extensions[Ml];for(let a of s.featureIds){let o=OF(this.document,this,e,a);r.addFeatureID(o)}e.meshes[t].listPrimitives()[i].setExtension(Ml,r)}write(e){let t=e.jsonDoc.json.meshes;if(!t)return this;for(let n of this.document.getRoot().listMeshes()){let i=t[e.meshIndexMap.get(n)];n.listPrimitives().forEach((r,s)=>{let a=i.primitives[s];this._writePrimitive(e,r,a)})}return this}_writePrimitive(e,t,n){let i=t.getExtension(Ml);if(!i)return;let r={featureIds:[]};i.listFeatureIDs().forEach((s)=>{r.featureIds.push(DF(this.document,e,s))}),n.extensions=n.extensions||{},n.extensions[Ml]=r}};LF=class extends nt{static EXTENSION_NAME=Os;init(){this.extensionName=Os,this.propertyType="InstancedMesh",this.parentTypes=[Q.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{attributes:new dn})}getAttribute(e){return this.getRefMap("attributes",e)}setAttribute(e,t){return this.setRefMap("attributes",e,t,{usage:$g})}listAttributes(){return this.listRefMapValues("attributes")}listSemantics(){return this.listRefMapKeys("attributes")}},ff=class extends _t{static EXTENSION_NAME=Os;extensionName=Os;prewriteTypes=[Q.ACCESSOR];createInstancedMesh(){return new LF(this.document.getGraph())}read(e){return(e.jsonDoc.json.nodes||[]).forEach((t,n)=>{if(!t.extensions||!t.extensions.EXT_mesh_gpu_instancing)return;let i=t.extensions[Os],r=this.createInstancedMesh();for(let s in i.attributes)r.setAttribute(s,e.accessors[i.attributes[s]]);e.nodes[n].setExtension(Os,r)}),this}prewrite(e){e.accessorUsageGroupedByParent.add($g);for(let t of this.properties)for(let n of t.listAttributes())e.addAccessorToUsageGroup(n,$g);return this}write(e){let t=e.jsonDoc;return this.document.getRoot().listNodes().forEach((n)=>{let i=n.getExtension(Os);if(i){let r=e.nodeIndexMap.get(n),s=t.json.nodes[r],a={attributes:{}};i.listSemantics().forEach((o)=>{let c=i.getAttribute(o);a.attributes[o]=e.accessorIndexMap.get(c)}),s.extensions=s.extensions||{},s.extensions[Os]=a}}),this}},FF=function(e){return e.QUANTIZE="quantize",e.FILTER="filter",e}({});({BYTE:BF,SHORT:uS,FLOAT:zF}=Oe.ComponentType),{encodeNormalizedInt:dS,decodeNormalizedInt:Kg}=mt;fS={method:"quantize"},Rl=class extends _t{extensionName=Yn;prereadTypes=[Q.BUFFER,Q.PRIMITIVE];prewriteTypes=[Q.BUFFER,Q.ACCESSOR];readDependencies=["meshopt.decoder"];writeDependencies=["meshopt.encoder"];static EXTENSION_NAME=Yn;static EncoderMethod=FF;_decoder=null;_decoderFallbackBufferMap=new Map;_encoder=null;_encoderOptions=fS;_encoderFallbackBuffer=null;_encoderBufferViews={};_encoderBufferViewData={};_encoderBufferViewAccessors={};install(e,t){if(e==="meshopt.decoder")this._decoder=t;if(e==="meshopt.encoder")this._encoder=t;return this}setEncoderOptions(e){return this._encoderOptions={...fS,...e},this}preread(e,t){if(!this._decoder){if(!this.isRequired())return this;throw Error(`[${Yn}] Please install extension dependency, "meshopt.decoder".`)}if(!this._decoder.supported){if(!this.isRequired())return this;throw Error(`[${Yn}]: Missing WASM support.`)}if(t===Q.BUFFER)this._prereadBuffers(e);else if(t===Q.PRIMITIVE)this._prereadPrimitives(e);return this}_prereadBuffers(e){let t=e.jsonDoc;(t.json.bufferViews||[]).forEach((n,i)=>{if(!n.extensions||!n.extensions.EXT_meshopt_compression)return;let r=n.extensions[Yn],s=r.byteOffset||0,a=r.byteLength||0,{count:o,byteStride:c}=r,l=new Uint8Array(o*c),u=t.json.buffers[r.buffer],d=u.uri?t.resources[u.uri]:t.resources[Cs],f=Ze.toView(d,s,a);this._decoder.decodeGltfBuffer(l,o,c,f,r.mode,r.filter),e.bufferViews[i]=l})}_prereadPrimitives(e){let t=e.jsonDoc;(t.json.bufferViews||[]).forEach((n)=>{if(!n.extensions||!n.extensions.EXT_meshopt_compression)return;let i=n.extensions[Yn],r=e.buffers[i.buffer],s=e.buffers[n.buffer],a=t.json.buffers[n.buffer];if(UF(a))this._decoderFallbackBufferMap.set(s,r)})}read(e){if(!this.isRequired())return this;for(let[t,n]of this._decoderFallbackBufferMap){for(let i of t.listParents())if(i instanceof Oe)i.swap(t,n);t.dispose()}return this}prewrite(e,t){if(t===Q.ACCESSOR)this._prewriteAccessors(e);else if(t===Q.BUFFER)this._prewriteBuffers(e);return this}_prewriteAccessors(e){let t=e.jsonDoc.json,n=this._encoder,i=this._encoderOptions,r=this.document.getGraph(),s=this.document.createBuffer(),a=this.document.getRoot().listBuffers().indexOf(s),o=1,c=new Map,l=(u)=>{for(let d of r.listParents(u)){if(d.propertyType===Q.ROOT)continue;let f=c.get(u);if(f===void 0)c.set(u,f=o++);return f}return-1};this._encoderFallbackBuffer=s,this._encoderBufferViews={},this._encoderBufferViewData={},this._encoderBufferViewAccessors={};for(let u of this.document.getRoot().listAccessors()){if(MS(u)==="weights")continue;if(u.getSparse())continue;let d=e.getAccessorUsage(u),f=e.accessorUsageGroupedByParent.has(d)?l(u):null,h=$F(u,d),b=i.method==="filter"?KF(u,this.document):{filter:"NONE"},m=VF(u,n,h,b),{array:g,byteStride:p}=m,x=u.getBuffer();if(!x)throw Error(`${Yn}: Missing buffer for accessor.`);let _=this.document.getRoot().listBuffers().indexOf(x),y=[d,f,h,b.filter,p,_].join(":"),v=this._encoderBufferViews[y],E=this._encoderBufferViewData[y],w=this._encoderBufferViewAccessors[y];if(!v||!E)w=this._encoderBufferViewAccessors[y]=[],E=this._encoderBufferViewData[y]=[],v=this._encoderBufferViews[y]={buffer:a,target:Is.USAGE_TO_TARGET[d],byteOffset:0,byteLength:0,byteStride:d===Is.BufferViewUsage.ARRAY_BUFFER?p:void 0,extensions:{[Yn]:{buffer:_,byteOffset:0,byteLength:0,mode:h,filter:b.filter!=="NONE"?b.filter:void 0,byteStride:p,count:0}}};let T=e.createAccessorDef(u);if(T.componentType=m.componentType,T.normalized=m.normalized,T.byteOffset=v.byteLength,T.min&&m.min)T.min=m.min;if(T.max&&m.max)T.max=m.max;e.accessorIndexMap.set(u,t.accessors.length),t.accessors.push(T),w.push(T),E.push(new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),v.byteLength+=g.byteLength,v.extensions.EXT_meshopt_compression.count+=u.getCount()}}_prewriteBuffers(e){let t=this._encoder;for(let n in this._encoderBufferViews){let i=this._encoderBufferViews[n],r=this._encoderBufferViewData[n],s=this.document.getRoot().listBuffers()[i.extensions[Yn].buffer],a=e.otherBufferViews.get(s)||[],{count:o,byteStride:c,mode:l}=i.extensions[Yn],u=Ze.concat(r),d=t.encodeGltfBuffer(u,o,c,l),f=Ze.pad(d);i.extensions[Yn].byteLength=d.byteLength,r.length=0,r.push(f),a.push(f),e.otherBufferViews.set(s,a)}}write(e){let t=0;for(let s in this._encoderBufferViews){let a=this._encoderBufferViews[s],o=this._encoderBufferViewData[s][0],c=e.otherBufferViewsIndexMap.get(o),l=this._encoderBufferViewAccessors[s];for(let h of l)h.bufferView=c;let u=e.jsonDoc.json.bufferViews[c],d=u.byteOffset||0;Object.assign(u,a),u.byteOffset=t;let f=u.extensions[Yn];f.byteOffset=d,t+=Ze.padNumber(a.byteLength)}let n=this._encoderFallbackBuffer,i=e.bufferIndexMap.get(n),r=e.jsonDoc.json.buffers[i];return r.byteLength=t,r.extensions={[Yn]:{fallback:!0}},n.dispose(),this}},WF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="StructuralMetadata",this.parentTypes=[Q.ROOT]}getDefaults(){return Object.assign(super.getDefaults(),{schema:null,schemaUri:"",propertyTables:new xn,propertyTextures:new xn,propertyAttributes:new xn})}getSchema(){return this.getRef("schema")}setSchema(e){return this.setRef("schema",e)}getSchemaUri(){return this.get("schemaUri")}setSchemaUri(e){return this.set("schemaUri",e)}listPropertyTables(){return this.listRefs("propertyTables")}addPropertyTable(e){return this.addRef("propertyTables",e)}removePropertyTable(e){return this.removeRef("propertyTables",e)}listPropertyTextures(){return this.listRefs("propertyTextures")}addPropertyTexture(e){return this.addRef("propertyTextures",e)}removePropertyTexture(e){return this.removeRef("propertyTextures",e)}listPropertyAttributes(){return this.listRefs("propertyAttributes")}addPropertyAttribute(e){return this.addRef("propertyAttributes",e)}removePropertyAttribute(e){return this.removeRef("propertyAttributes",e)}},XF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="Schema",this.parentTypes=["StructuralMetadata"]}getDefaults(){return Object.assign(super.getDefaults(),{description:"",version:"",classes:new dn,enums:new dn})}getId(){return this.get("id")}setId(e){return this.set("id",e)}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}getVersion(){return this.get("version")}setVersion(e){return this.set("version",e)}setClass(e,t){return this.setRefMap("classes",e,t)}getClass(e){return this.getRefMap("classes",e)}listClassKeys(){return this.listRefMapKeys("classes")}listClassValues(){return this.listRefMapValues("classes")}setEnum(e,t){return this.setRefMap("enums",e,t)}getEnum(e){return this.getRefMap("enums",e)}listEnumKeys(){return this.listRefMapKeys("enums")}listEnumValues(){return this.listRefMapValues("enums")}},qF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="Class",this.parentTypes=["Schema"]}getDefaults(){return Object.assign(super.getDefaults(),{description:"",properties:new dn})}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}setProperty(e,t){return this.setRefMap("properties",e,t)}getProperty(e){return this.getRefMap("properties",e)}listPropertyKeys(){return this.listRefMapKeys("properties")}listPropertyValues(){return this.listRefMapValues("properties")}},JF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="ClassProperty",this.parentTypes=["Class"]}getDefaults(){return Object.assign(super.getDefaults(),{description:"",componentType:null,enumType:null,array:null,count:null,normalized:null,offset:null,scale:null,max:null,min:null,required:null,noData:null,default:null})}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}getType(){return this.get("type")}setType(e){return this.set("type",e)}getComponentType(){return this.get("componentType")}setComponentType(e){return this.set("componentType",e)}getEnumType(){return this.get("enumType")}setEnumType(e){return this.set("enumType",e)}getArray(){return this.get("array")}setArray(e){return this.set("array",e)}getCount(){return this.get("count")}setCount(e){return this.set("count",e)}getNormalized(){return this.get("normalized")}setNormalized(e){return this.set("normalized",e)}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getMax(){return this.get("max")}setMax(e){return this.set("max",e)}getMin(){return this.get("min")}setMin(e){return this.set("min",e)}getRequired(){return this.get("required")}setRequired(e){return this.set("required",e)}getNoData(){return this.get("noData")}setNoData(e){return this.set("noData",e)}getDefault(){return this.get("default")}setDefault(e){return this.set("default",e)}},ZF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="Enum",this.parentTypes=["Schema"]}getDefaults(){return Object.assign(super.getDefaults(),{description:"",valueType:"UINT16",values:new xn})}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}getValueType(){return this.get("valueType")}setValueType(e){return this.set("valueType",e)}listValues(){return this.listRefs("values")}addEnumValue(e){return this.addRef("values",e)}removeEnumValue(e){return this.removeRef("values",e)}},YF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="EnumValue",this.parentTypes=["Enum"]}getDefaults(){return Object.assign(super.getDefaults(),{description:null})}getDescription(){return this.get("description")}setDescription(e){return this.set("description",e)}getValue(){return this.get("value")}setValue(e){return this.set("value",e)}},QF=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyTable",this.parentTypes=["StructuralMetadata"]}getDefaults(){return Object.assign(super.getDefaults(),{properties:new dn})}getClass(){return this.get("class")}setClass(e){return this.set("class",e)}getCount(){return this.get("count")}setCount(e){return this.set("count",e)}setProperty(e,t){return this.setRefMap("properties",e,t)}getProperty(e){return this.getRefMap("properties",e)}listPropertyKeys(){return this.listRefMapKeys("properties")}listPropertyValues(){return this.listRefMapValues("properties")}},e2=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyTableProperty",this.parentTypes=["PropertyTable"]}getDefaults(){return Object.assign(super.getDefaults(),{arrayOffsets:null,stringOffsets:null,arrayOffsetType:null,stringOffsetType:null,offset:null,scale:null,max:null,min:null})}getValues(){return this.get("values")}setValues(e){return this.set("values",e)}getArrayOffsets(){return this.get("arrayOffsets")}setArrayOffsets(e){return this.set("arrayOffsets",e)}getStringOffsets(){return this.get("stringOffsets")}setStringOffsets(e){return this.set("stringOffsets",e)}getArrayOffsetType(){return this.get("arrayOffsetType")}setArrayOffsetType(e){return this.set("arrayOffsetType",e)}getStringOffsetType(){return this.get("stringOffsetType")}setStringOffsetType(e){return this.set("stringOffsetType",e)}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getMax(){return this.get("max")}setMax(e){return this.set("max",e)}getMin(){return this.get("min")}setMin(e){return this.set("min",e)}},t2=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyTexture",this.parentTypes=["StructuralMetadata"]}getDefaults(){return Object.assign(super.getDefaults(),{properties:new dn})}getClass(){return this.get("class")}setClass(e){return this.set("class",e)}setProperty(e,t){return this.setRefMap("properties",e,t)}getProperty(e){return this.getRefMap("properties",e)}listPropertyKeys(){return this.listRefMapKeys("properties")}listPropertyValues(){return this.listRefMapValues("properties")}},n2=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyTextureProperty",this.parentTypes=["PropertyTexture"]}getDefaults(){let e=new wt(this.graph,"textureInfo");return e.setMinFilter(wt.MagFilter.NEAREST),e.setMagFilter(wt.MagFilter.NEAREST),Object.assign(super.getDefaults(),{channels:[0],texture:null,textureInfo:e,offset:null,scale:null,max:null,min:null})}getChannels(){return this.get("channels")}setChannels(e){return this.set("channels",e)}getTexture(){return this.getRef("texture")}setTexture(e){return this.setRef("texture",e)}getTextureInfo(){return this.getRef("texture")?this.getRef("textureInfo"):null}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getMax(){return this.get("max")}setMax(e){return this.set("max",e)}getMin(){return this.get("min")}setMin(e){return this.set("min",e)}},i2=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyAttribute",this.parentTypes=["StructuralMetadata"]}getDefaults(){return Object.assign(super.getDefaults(),{properties:new dn})}getClass(){return this.get("class")}setClass(e){return this.set("class",e)}setProperty(e,t){return this.setRefMap("properties",e,t)}getProperty(e){return this.getRefMap("properties",e)}listPropertyKeys(){return this.listRefMapKeys("properties")}listPropertyValues(){return this.listRefMapValues("properties")}},r2=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="PropertyAttributeProperty",this.parentTypes=["PropertyAttribute"]}getDefaults(){return Object.assign(super.getDefaults(),{offset:null,scale:null,max:null,min:null})}getAttribute(){return this.get("attribute")}setAttribute(e){return this.set("attribute",e)}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getMax(){return this.get("max")}setMax(e){return this.set("max",e)}getMin(){return this.get("min")}setMin(e){return this.set("min",e)}},s2=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="NodeStructuralMetadata",this.parentTypes=[Q.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{class:"",properties:{}})}getClass(){return this.get("class")}setClass(e){return this.set("class",e)}getProperties(){return this.get("properties")}setProperties(e){return this.set("properties",e)}},a2=class extends nt{static EXTENSION_NAME=et;init(){this.extensionName=et,this.propertyType="MeshPrimitiveStructuralMetadata",this.parentTypes=[Q.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{propertyTextures:new xn,propertyAttributes:new xn})}listPropertyTextures(){return this.listRefs("propertyTextures")}addPropertyTexture(e){return this.addRef("propertyTextures",e)}removePropertyTexture(e){return this.removeRef("propertyTextures",e)}listPropertyAttributes(){return this.listRefs("propertyAttributes")}addPropertyAttribute(e){return this.addRef("propertyAttributes",e)}removePropertyAttribute(e){return this.removeRef("propertyAttributes",e)}},o2=class extends _t{extensionName=et;static EXTENSION_NAME=et;prewriteTypes=[Q.BUFFER];prereadTypes=[Q.SCENE];createStructuralMetadata(){return new WF(this.document.getGraph())}createSchema(){return new XF(this.document.getGraph())}createClass(){return new qF(this.document.getGraph())}createClassProperty(){return new JF(this.document.getGraph())}createEnum(){return new ZF(this.document.getGraph())}createEnumValue(){return new YF(this.document.getGraph())}createPropertyTable(){return new QF(this.document.getGraph())}createPropertyTableProperty(){return new e2(this.document.getGraph())}createPropertyTexture(){return new t2(this.document.getGraph())}createPropertyTextureProperty(){return new n2(this.document.getGraph())}createPropertyAttribute(){return new i2(this.document.getGraph())}createPropertyAttributeProperty(){return new r2(this.document.getGraph())}createNodeStructuralMetadata(){return new s2(this.document.getGraph())}createMeshPrimitiveStructuralMetadata(){return new a2(this.document.getGraph())}read(e){return this}preread(e){let t=this.document.getRoot(),{json:n}=e.jsonDoc,i=n.extensions[et],r=c2(this,e,i);return t.setExtension(et,r),(n.meshes||[]).forEach((s,a)=>{let o=e.meshes[a].listPrimitives();(s.primitives||[]).forEach((c,l)=>{let u=o[l];this._readPrimitive(r,u,c)})}),(n.nodes||[]).forEach((s,a)=>{this._readNode(e.nodes[a],s)}),this}_readPrimitive(e,t,n){if(!n.extensions||!n.extensions.EXT_structural_metadata)return;let i=this.createMeshPrimitiveStructuralMetadata(),r=n.extensions[et],s=e.listPropertyTextures(),a=r.propertyTextures||[];for(let l of a){let u=s[l];i.addPropertyTexture(u)}let o=e.listPropertyAttributes(),c=r.propertyAttributes||[];for(let l of c){let u=o[l];i.addPropertyAttribute(u)}t.setExtension(et,i)}_readNode(e,t){if(!t.extensions||!t.extensions.EXT_structural_metadata)return;let n=t.extensions[et],i=this.createNodeStructuralMetadata().setClass(n.class).setProperties(n.properties);e.setExtension(et,i)}write(e){let t=this.document.getRoot(),n=t.getExtension(et);if(!n)return this;let i=e.jsonDoc.json,r=_2(e,n);i.extensions=i.extensions||{},i.extensions[et]=r;let s=t.listMeshes(),a=i.meshes;if(a)for(let l of s){let u=a[e.meshIndexMap.get(l)];l.listPrimitives().forEach((d,f)=>{let h=u.primitives[f];this._writePrimitive(n,d,h)})}let o=t.listNodes(),c=i.nodes;if(c)for(let l of o){let u=e.nodeIndexMap.get(l);this._writeNode(l,c[u])}return this}_writePrimitive(e,t,n){let i=t.getExtension(et);if(!i)return;let r=e.listPropertyTextures(),s=e.listPropertyAttributes(),a,o,c=i.listPropertyTextures();if(c.length>0){a=[];for(let d of c){let f=r.indexOf(d);if(f>=0)a.push(f);else throw Error(`${et}: Invalid property texture in mesh primitive`)}}let l=i.listPropertyAttributes();if(l.length>0){o=[];for(let d of l){let f=s.indexOf(d);if(f>=0)o.push(f);else throw Error(`${et}: Invalid property attribute in mesh primitive`)}}let u={propertyTextures:a,propertyAttributes:o};n.extensions=n.extensions||{},n.extensions[et]=u}_writeNode(e,t){let n=e.getExtension("EXT_structural_metadata");if(!n)return;t.extensions=t.extensions||{},t.extensions[et]={class:n.getClass(),properties:n.getProperties()}}prewrite(e,t){if(t===Q.BUFFER)this._prewriteBuffers(e);return this}_prewriteBuffers(e){let t=this.document,n=t.getRoot().getExtension(et);e.jsonDoc.json.bufferViews||=[];for(let i of n.listPropertyTables())for(let r of i.listPropertyValues()){let s=P2(t,e);s.push(r.getValues());let a=r.getArrayOffsets();if(a)s.push(a);let o=r.getStringOffsets();if(o)s.push(o)}}};RS=class extends _t{extensionName=uf;prereadTypes=[Q.TEXTURE];static EXTENSION_NAME=uf;static register(){Gi.registerFormat("image/avif",new O2)}preread(e){return(e.jsonDoc.json.textures||[]).forEach((t)=>{if(t.extensions&&t.extensions.EXT_texture_avif)t.source=t.extensions[uf].source}),this}read(e){return this}write(e){let t=e.jsonDoc;return this.document.getRoot().listTextures().forEach((n)=>{if(n.getMimeType()==="image/avif"){let i=e.imageIndexMap.get(n);(t.json.textures||[]).forEach((r)=>{if(r.source===i)r.extensions=r.extensions||{},r.extensions[uf]={source:r.source},delete r.source})}}),this}};IS=class extends _t{extensionName=lf;prereadTypes=[Q.TEXTURE];static EXTENSION_NAME=lf;static register(){Gi.registerFormat("image/webp",new k2)}preread(e){return(e.jsonDoc.json.textures||[]).forEach((t)=>{if(t.extensions&&t.extensions.EXT_texture_webp)t.source=t.extensions[lf].source}),this}read(e){return this}write(e){let t=e.jsonDoc;return this.document.getRoot().listTextures().forEach((n)=>{if(n.getMimeType()==="image/webp"){let i=e.imageIndexMap.get(n);(t.json.textures||[]).forEach((r)=>{if(r.source===i)r.extensions=r.extensions||{},r.extensions[lf]={source:r.source},delete r.source})}}),this}},pS=MF,D2=class extends _t{extensionName=pS;static EXTENSION_NAME=pS;read(e){return this}write(e){return this}},mS=RF,L2=class extends _t{extensionName=mS;static EXTENSION_NAME=mS;read(e){return this}write(e){return this}};V2=function(e){return e[e.EDGEBREAKER=1]="EDGEBREAKER",e[e.SEQUENTIAL=0]="SEQUENTIAL",e}({}),PS={["POSITION"]:14,["NORMAL"]:10,["COLOR"]:8,["TEX_COORD"]:12,["GENERIC"]:12},gS={decodeSpeed:5,encodeSpeed:5,method:1,quantizationBits:PS,quantizationVolume:"mesh"};Wg=class extends Error{},OS=class extends _t{extensionName=tn;prereadTypes=[Q.PRIMITIVE];prewriteTypes=[Q.ACCESSOR];readDependencies=["draco3d.decoder"];writeDependencies=["draco3d.encoder"];static EXTENSION_NAME=tn;static EncoderMethod=V2;_decoderModule=null;_encoderModule=null;_encoderOptions={};install(e,t){if(e==="draco3d.decoder")this._decoderModule=t,z2(this._decoderModule);if(e==="draco3d.encoder")this._encoderModule=t,j2(this._encoderModule);return this}setEncoderOptions(e){return this._encoderOptions=e,this}preread(e){if(!this._decoderModule)throw Error(`[${tn}] Please install extension dependency, "draco3d.decoder".`);let t=this.document.getLogger(),n=e.jsonDoc,i=new Map;try{let r=n.json.meshes||[];for(let s of r)for(let a of s.primitives){if(!a.extensions||!a.extensions.KHR_draco_mesh_compression)continue;let o=a.extensions[tn],[c,l]=i.get(o.bufferView)||[];if(!l||!c){let u=n.json.bufferViews[o.bufferView],d=n.json.buffers[u.buffer],f=d.uri?n.resources[d.uri]:n.resources[Cs],h=u.byteOffset||0,b=u.byteLength,m=Ze.toView(f,h,b);c=new this._decoderModule.Decoder,l=F2(c,m),i.set(o.bufferView,[c,l]),t.debug(`[${tn}] Decompressed ${m.byteLength} bytes.`)}for(let u in o.attributes){let d=e.jsonDoc.json.accessors[a.attributes[u]],f=c.GetAttributeByUniqueId(l,o.attributes[u]),h=B2(c,l,f,d);e.accessors[a.attributes[u]].setArray(h)}if(a.indices!==void 0)e.accessors[a.indices].setArray(U2(c,l))}}finally{for(let[r,s]of Array.from(i.values()))this._decoderModule.destroy(r),this._decoderModule.destroy(s)}return this}read(e){return this}prewrite(e,t){if(!this._encoderModule)throw Error(`[${tn}] Please install extension dependency, "draco3d.encoder".`);let n=this.document.getLogger();n.debug(`[${tn}] Compression options: ${JSON.stringify(this._encoderOptions)}`);let i=K2(this.document),r=new Map,s="mesh";if(this._encoderOptions.quantizationVolume==="scene")if(this.document.getRoot().listScenes().length!==1)n.warn(`[${tn}]: quantizationVolume=scene requires exactly 1 scene.`);else s=Ug(this.document.getRoot().listScenes().pop());for(let a of Array.from(i.keys())){let o=i.get(a);if(!o)throw Error("Unexpected primitive.");if(r.has(o)){r.set(o,r.get(o));continue}let c=a.getIndices(),l=e.jsonDoc.json.accessors,u;try{u=H2(a,{...this._encoderOptions,quantizationVolume:s})}catch(h){if(h instanceof Wg){n.warn(`[${tn}]: ${h.message} Skipping primitive compression.`);continue}throw h}r.set(o,u);let d=e.createAccessorDef(c);if(d.count=u.numIndices,e.accessorIndexMap.set(c,l.length),l.push(d),u.numVertices>65534&&Oe.getComponentSize(d.componentType)<=2)d.componentType=Oe.ComponentType.UNSIGNED_INT;else if(u.numVertices>254&&Oe.getComponentSize(d.componentType)<=1)d.componentType=Oe.ComponentType.UNSIGNED_SHORT;for(let h of a.listSemantics()){let b=a.getAttribute(h);if(u.attributeIDs[h]===void 0)continue;let m=e.createAccessorDef(b);m.count=u.numVertices,e.accessorIndexMap.set(b,l.length),l.push(m)}let f=a.getAttribute("POSITION").getBuffer()||this.document.getRoot().listBuffers()[0];if(!e.otherBufferViews.has(f))e.otherBufferViews.set(f,[]);e.otherBufferViews.get(f).push(u.data)}return n.debug(`[${tn}] Compressed ${i.size} primitives.`),e.extensionData[tn]={primitiveHashMap:i,primitiveEncodingMap:r},this}write(e){let t=e.extensionData[tn];for(let n of this.document.getRoot().listMeshes()){let i=e.jsonDoc.json.meshes[e.meshIndexMap.get(n)];for(let r=0;r<n.listPrimitives().length;r++){let s=n.listPrimitives()[r],a=i.primitives[r],o=t.primitiveHashMap.get(s);if(!o)continue;let c=t.primitiveEncodingMap.get(o);if(!c)continue;a.extensions=a.extensions||{},a.extensions[tn]={bufferView:e.otherBufferViewsIndexMap.get(c.data),attributes:c.attributeIDs}}}if(!t.primitiveHashMap.size){let n=e.jsonDoc.json;n.extensionsUsed=(n.extensionsUsed||[]).filter((i)=>i!==tn),n.extensionsRequired=(n.extensionsRequired||[]).filter((i)=>i!==tn)}return this}};xS=class e extends nt{static EXTENSION_NAME=Hr;static Type={POINT:"point",SPOT:"spot",DIRECTIONAL:"directional"};init(){this.extensionName=Hr,this.propertyType="Light",this.parentTypes=[Q.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{color:[1,1,1],intensity:1,type:e.Type.POINT,range:null,innerConeAngle:0,outerConeAngle:Math.PI/4})}getColor(){return this.get("color")}setColor(t){return this.set("color",t)}getIntensity(){return this.get("intensity")}setIntensity(t){return this.set("intensity",t)}getType(){return this.get("type")}setType(t){return this.set("type",t)}getRange(){return this.get("range")}setRange(t){return this.set("range",t)}getInnerConeAngle(){return this.get("innerConeAngle")}setInnerConeAngle(t){return this.set("innerConeAngle",t)}getOuterConeAngle(){return this.get("outerConeAngle")}setOuterConeAngle(t){return this.set("outerConeAngle",t)}},W2=class extends _t{extensionName=Hr;static EXTENSION_NAME=Hr;createLight(e=""){return new xS(this.document.getGraph(),e)}read(e){let t=e.jsonDoc;if(!t.json.extensions||!t.json.extensions.KHR_lights_punctual)return this;let n=(t.json.extensions.KHR_lights_punctual.lights||[]).map((i)=>{let r=this.createLight().setName(i.name||"").setType(i.type);if(i.extras)r.setExtras(i.extras);if(i.color!==void 0)r.setColor(i.color);if(i.intensity!==void 0)r.setIntensity(i.intensity);if(i.range!==void 0)r.setRange(i.range);if(i.spot?.innerConeAngle!==void 0)r.setInnerConeAngle(i.spot.innerConeAngle);if(i.spot?.outerConeAngle!==void 0)r.setOuterConeAngle(i.spot.outerConeAngle);return r});return t.json.nodes.forEach((i,r)=>{if(!i.extensions||!i.extensions.KHR_lights_punctual)return;let s=i.extensions[Hr];e.nodes[r].setExtension(Hr,n[s.light])}),this}write(e){let t=e.jsonDoc;if(this.properties.size===0)return this;let n=[],i=new Map;for(let r of this.properties){let s=r,a=e.createPropertyDef(r);if(a.type=s.getType(),!mt.eq(s.getColor(),[1,1,1]))a.color=s.getColor();if(s.getIntensity()!==1)a.intensity=s.getIntensity();if(s.getRange()!=null)a.range=s.getRange();if(s.getName())a.name=s.getName();if(s.getType()===xS.Type.SPOT)a.spot={innerConeAngle:s.getInnerConeAngle(),outerConeAngle:s.getOuterConeAngle()};n.push(a),i.set(s,n.length-1)}return this.document.getRoot().listNodes().forEach((r)=>{let s=r.getExtension(Hr);if(s){let a=e.nodeIndexMap.get(r),o=t.json.nodes[a];o.extensions=o.extensions||{},o.extensions[Hr]={light:i.get(s)}}}),t.json.extensions=t.json.extensions||{},t.json.extensions[Hr]={lights:n},this}},{R:X2,G:q2,B:J2}=Ai,Z2=class extends nt{static EXTENSION_NAME=ks;init(){this.extensionName=ks,this.propertyType="Anisotropy",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{anisotropyStrength:0,anisotropyRotation:0,anisotropyTexture:null,anisotropyTextureInfo:new wt(this.graph,"anisotropyTextureInfo")})}getAnisotropyStrength(){return this.get("anisotropyStrength")}setAnisotropyStrength(e){return this.set("anisotropyStrength",e)}getAnisotropyRotation(){return this.get("anisotropyRotation")}setAnisotropyRotation(e){return this.set("anisotropyRotation",e)}getAnisotropyTexture(){return this.getRef("anisotropyTexture")}getAnisotropyTextureInfo(){return this.getRef("anisotropyTexture")?this.getRef("anisotropyTextureInfo"):null}setAnisotropyTexture(e){return this.setRef("anisotropyTexture",e,{channels:X2|q2|J2})}},Y2=class extends _t{static EXTENSION_NAME=ks;extensionName=ks;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createAnisotropy(){return new Z2(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_anisotropy){let a=this.createAnisotropy();e.materials[s].setExtension(ks,a);let o=r.extensions[ks];if(o.extras)a.setExtras(o.extras);if(o.anisotropyStrength!==void 0)a.setAnisotropyStrength(o.anisotropyStrength);if(o.anisotropyRotation!==void 0)a.setAnisotropyRotation(o.anisotropyRotation);if(o.anisotropyTexture!==void 0){let c=o.anisotropyTexture,l=e.textures[i[c.index].source];a.setAnisotropyTexture(l),e.setTextureInfo(a.getAnisotropyTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(ks);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[ks]=a,i.getAnisotropyStrength()>0)a.anisotropyStrength=i.getAnisotropyStrength();if(i.getAnisotropyRotation()!==0)a.anisotropyRotation=i.getAnisotropyRotation();if(i.getAnisotropyTexture()){let o=i.getAnisotropyTexture(),c=i.getAnisotropyTextureInfo();a.anisotropyTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:yS,G:_S,B:Q2}=Ai,eU=class extends nt{static EXTENSION_NAME=Ds;init(){this.extensionName=Ds,this.propertyType="Clearcoat",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{clearcoatFactor:0,clearcoatTexture:null,clearcoatTextureInfo:new wt(this.graph,"clearcoatTextureInfo"),clearcoatRoughnessFactor:0,clearcoatRoughnessTexture:null,clearcoatRoughnessTextureInfo:new wt(this.graph,"clearcoatRoughnessTextureInfo"),clearcoatNormalScale:1,clearcoatNormalTexture:null,clearcoatNormalTextureInfo:new wt(this.graph,"clearcoatNormalTextureInfo")})}getClearcoatFactor(){return this.get("clearcoatFactor")}setClearcoatFactor(e){return this.set("clearcoatFactor",e)}getClearcoatTexture(){return this.getRef("clearcoatTexture")}getClearcoatTextureInfo(){return this.getRef("clearcoatTexture")?this.getRef("clearcoatTextureInfo"):null}setClearcoatTexture(e){return this.setRef("clearcoatTexture",e,{channels:yS})}getClearcoatRoughnessFactor(){return this.get("clearcoatRoughnessFactor")}setClearcoatRoughnessFactor(e){return this.set("clearcoatRoughnessFactor",e)}getClearcoatRoughnessTexture(){return this.getRef("clearcoatRoughnessTexture")}getClearcoatRoughnessTextureInfo(){return this.getRef("clearcoatRoughnessTexture")?this.getRef("clearcoatRoughnessTextureInfo"):null}setClearcoatRoughnessTexture(e){return this.setRef("clearcoatRoughnessTexture",e,{channels:_S})}getClearcoatNormalScale(){return this.get("clearcoatNormalScale")}setClearcoatNormalScale(e){return this.set("clearcoatNormalScale",e)}getClearcoatNormalTexture(){return this.getRef("clearcoatNormalTexture")}getClearcoatNormalTextureInfo(){return this.getRef("clearcoatNormalTexture")?this.getRef("clearcoatNormalTextureInfo"):null}setClearcoatNormalTexture(e){return this.setRef("clearcoatNormalTexture",e,{channels:yS|_S|Q2})}},tU=class extends _t{static EXTENSION_NAME=Ds;extensionName=Ds;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createClearcoat(){return new eU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_clearcoat){let a=this.createClearcoat();e.materials[s].setExtension(Ds,a);let o=r.extensions[Ds];if(o.extras)a.setExtras(o.extras);if(o.clearcoatFactor!==void 0)a.setClearcoatFactor(o.clearcoatFactor);if(o.clearcoatRoughnessFactor!==void 0)a.setClearcoatRoughnessFactor(o.clearcoatRoughnessFactor);if(o.clearcoatTexture!==void 0){let c=o.clearcoatTexture,l=e.textures[i[c.index].source];a.setClearcoatTexture(l),e.setTextureInfo(a.getClearcoatTextureInfo(),c)}if(o.clearcoatRoughnessTexture!==void 0){let c=o.clearcoatRoughnessTexture,l=e.textures[i[c.index].source];a.setClearcoatRoughnessTexture(l),e.setTextureInfo(a.getClearcoatRoughnessTextureInfo(),c)}if(o.clearcoatNormalTexture!==void 0){let c=o.clearcoatNormalTexture,l=e.textures[i[c.index].source];if(a.setClearcoatNormalTexture(l),e.setTextureInfo(a.getClearcoatNormalTextureInfo(),c),c.scale!==void 0)a.setClearcoatNormalScale(c.scale)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Ds);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Ds]=a,a.clearcoatFactor=i.getClearcoatFactor(),a.clearcoatRoughnessFactor=i.getClearcoatRoughnessFactor(),i.getClearcoatTexture()){let o=i.getClearcoatTexture(),c=i.getClearcoatTextureInfo();a.clearcoatTexture=e.createTextureInfoDef(o,c)}if(i.getClearcoatRoughnessTexture()){let o=i.getClearcoatRoughnessTexture(),c=i.getClearcoatRoughnessTextureInfo();a.clearcoatRoughnessTexture=e.createTextureInfoDef(o,c)}if(i.getClearcoatNormalTexture()){let o=i.getClearcoatNormalTexture(),c=i.getClearcoatNormalTextureInfo();if(a.clearcoatNormalTexture=e.createTextureInfoDef(o,c),i.getClearcoatNormalScale()!==1)a.clearcoatNormalTexture.scale=i.getClearcoatNormalScale()}}}),this}},{R:nU,G:iU,B:rU,A:sU}=Ai,aU=class extends nt{static EXTENSION_NAME=Ls;init(){this.extensionName=Ls,this.propertyType="DiffuseTransmission",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseTransmissionFactor:0,diffuseTransmissionTexture:null,diffuseTransmissionTextureInfo:new wt(this.graph,"diffuseTransmissionTextureInfo"),diffuseTransmissionColorFactor:[1,1,1],diffuseTransmissionColorTexture:null,diffuseTransmissionColorTextureInfo:new wt(this.graph,"diffuseTransmissionColorTextureInfo")})}getDiffuseTransmissionFactor(){return this.get("diffuseTransmissionFactor")}setDiffuseTransmissionFactor(e){return this.set("diffuseTransmissionFactor",e)}getDiffuseTransmissionTexture(){return this.getRef("diffuseTransmissionTexture")}getDiffuseTransmissionTextureInfo(){return this.getRef("diffuseTransmissionTexture")?this.getRef("diffuseTransmissionTextureInfo"):null}setDiffuseTransmissionTexture(e){return this.setRef("diffuseTransmissionTexture",e,{channels:sU})}getDiffuseTransmissionColorFactor(){return this.get("diffuseTransmissionColorFactor")}setDiffuseTransmissionColorFactor(e){return this.set("diffuseTransmissionColorFactor",e)}getDiffuseTransmissionColorTexture(){return this.getRef("diffuseTransmissionColorTexture")}getDiffuseTransmissionColorTextureInfo(){return this.getRef("diffuseTransmissionColorTexture")?this.getRef("diffuseTransmissionColorTextureInfo"):null}setDiffuseTransmissionColorTexture(e){return this.setRef("diffuseTransmissionColorTexture",e,{channels:nU|iU|rU})}},oU=class extends _t{extensionName=Ls;static EXTENSION_NAME=Ls;createDiffuseTransmission(){return new aU(this.document.getGraph())}read(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_diffuse_transmission){let a=this.createDiffuseTransmission();e.materials[s].setExtension(Ls,a);let o=r.extensions[Ls];if(o.extras)a.setExtras(o.extras);if(o.diffuseTransmissionFactor!==void 0)a.setDiffuseTransmissionFactor(o.diffuseTransmissionFactor);if(o.diffuseTransmissionColorFactor!==void 0)a.setDiffuseTransmissionColorFactor(o.diffuseTransmissionColorFactor);if(o.diffuseTransmissionTexture!==void 0){let c=o.diffuseTransmissionTexture,l=e.textures[i[c.index].source];a.setDiffuseTransmissionTexture(l),e.setTextureInfo(a.getDiffuseTransmissionTextureInfo(),c)}if(o.diffuseTransmissionColorTexture!==void 0){let c=o.diffuseTransmissionColorTexture,l=e.textures[i[c.index].source];a.setDiffuseTransmissionColorTexture(l),e.setTextureInfo(a.getDiffuseTransmissionColorTextureInfo(),c)}}}),this}write(e){let t=e.jsonDoc;for(let n of this.document.getRoot().listMaterials()){let i=n.getExtension(Ls);if(!i)continue;let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Ls]=a,a.diffuseTransmissionFactor=i.getDiffuseTransmissionFactor(),a.diffuseTransmissionColorFactor=i.getDiffuseTransmissionColorFactor(),i.getDiffuseTransmissionTexture()){let o=i.getDiffuseTransmissionTexture(),c=i.getDiffuseTransmissionTextureInfo();a.diffuseTransmissionTexture=e.createTextureInfoDef(o,c)}if(i.getDiffuseTransmissionColorTexture()){let o=i.getDiffuseTransmissionColorTexture(),c=i.getDiffuseTransmissionColorTextureInfo();a.diffuseTransmissionColorTexture=e.createTextureInfoDef(o,c)}}return this}},cU=class extends nt{static EXTENSION_NAME=Fs;init(){this.extensionName=Fs,this.propertyType="Dispersion",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{dispersion:0})}getDispersion(){return this.get("dispersion")}setDispersion(e){return this.set("dispersion",e)}},lU=class extends _t{static EXTENSION_NAME=Fs;extensionName=Fs;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createDispersion(){return new cU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){return(e.jsonDoc.json.materials||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_materials_dispersion){let i=this.createDispersion();e.materials[n].setExtension(Fs,i);let r=t.extensions[Fs];if(r.extras)i.setExtras(r.extras);if(r.dispersion!==void 0)i.setDispersion(r.dispersion)}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Fs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);s.extensions=s.extensions||{},s.extensions[Fs]=a,a.dispersion=i.getDispersion()}}),this}},uU=class extends nt{static EXTENSION_NAME=Us;init(){this.extensionName=Us,this.propertyType="EmissiveStrength",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{emissiveStrength:1})}getEmissiveStrength(){return this.get("emissiveStrength")}setEmissiveStrength(e){return this.set("emissiveStrength",e)}},dU=class extends _t{static EXTENSION_NAME=Us;extensionName=Us;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createEmissiveStrength(){return new uU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){return(e.jsonDoc.json.materials||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_materials_emissive_strength){let i=this.createEmissiveStrength();e.materials[n].setExtension(Us,i);let r=t.extensions[Us];if(r.extras)i.setExtras(r.extras);if(r.emissiveStrength!==void 0)i.setEmissiveStrength(r.emissiveStrength)}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Us);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);s.extensions=s.extensions||{},s.extensions[Us]=a,a.emissiveStrength=i.getEmissiveStrength()}}),this}},fU=class extends nt{static EXTENSION_NAME=Bs;init(){this.extensionName=Bs,this.propertyType="IOR",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{ior:1.5})}getIOR(){return this.get("ior")}setIOR(e){return this.set("ior",e)}},kS=class extends _t{static EXTENSION_NAME=Bs;extensionName=Bs;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createIOR(){return new fU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){return(e.jsonDoc.json.materials||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_materials_ior){let i=this.createIOR();e.materials[n].setExtension(Bs,i);let r=t.extensions[Bs];if(r.extras)i.setExtras(r.extras);if(r.ior!==void 0)i.setIOR(r.ior)}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Bs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);s.extensions=s.extensions||{},s.extensions[Bs]=a,a.ior=i.getIOR()}}),this}},{R:hU,G:pU}=Ai,mU=class extends nt{static EXTENSION_NAME=zs;init(){this.extensionName=zs,this.propertyType="Iridescence",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{iridescenceFactor:0,iridescenceTexture:null,iridescenceTextureInfo:new wt(this.graph,"iridescenceTextureInfo"),iridescenceIOR:1.3,iridescenceThicknessMinimum:100,iridescenceThicknessMaximum:400,iridescenceThicknessTexture:null,iridescenceThicknessTextureInfo:new wt(this.graph,"iridescenceThicknessTextureInfo")})}getIridescenceFactor(){return this.get("iridescenceFactor")}setIridescenceFactor(e){return this.set("iridescenceFactor",e)}getIridescenceTexture(){return this.getRef("iridescenceTexture")}getIridescenceTextureInfo(){return this.getRef("iridescenceTexture")?this.getRef("iridescenceTextureInfo"):null}setIridescenceTexture(e){return this.setRef("iridescenceTexture",e,{channels:hU})}getIridescenceIOR(){return this.get("iridescenceIOR")}setIridescenceIOR(e){return this.set("iridescenceIOR",e)}getIridescenceThicknessMinimum(){return this.get("iridescenceThicknessMinimum")}setIridescenceThicknessMinimum(e){return this.set("iridescenceThicknessMinimum",e)}getIridescenceThicknessMaximum(){return this.get("iridescenceThicknessMaximum")}setIridescenceThicknessMaximum(e){return this.set("iridescenceThicknessMaximum",e)}getIridescenceThicknessTexture(){return this.getRef("iridescenceThicknessTexture")}getIridescenceThicknessTextureInfo(){return this.getRef("iridescenceThicknessTexture")?this.getRef("iridescenceThicknessTextureInfo"):null}setIridescenceThicknessTexture(e){return this.setRef("iridescenceThicknessTexture",e,{channels:pU})}},gU=class extends _t{static EXTENSION_NAME=zs;extensionName=zs;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createIridescence(){return new mU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_iridescence){let a=this.createIridescence();e.materials[s].setExtension(zs,a);let o=r.extensions[zs];if(o.extras)a.setExtras(o.extras);if(o.iridescenceFactor!==void 0)a.setIridescenceFactor(o.iridescenceFactor);if(o.iridescenceIor!==void 0)a.setIridescenceIOR(o.iridescenceIor);if(o.iridescenceThicknessMinimum!==void 0)a.setIridescenceThicknessMinimum(o.iridescenceThicknessMinimum);if(o.iridescenceThicknessMaximum!==void 0)a.setIridescenceThicknessMaximum(o.iridescenceThicknessMaximum);if(o.iridescenceTexture!==void 0){let c=o.iridescenceTexture,l=e.textures[i[c.index].source];a.setIridescenceTexture(l),e.setTextureInfo(a.getIridescenceTextureInfo(),c)}if(o.iridescenceThicknessTexture!==void 0){let c=o.iridescenceThicknessTexture,l=e.textures[i[c.index].source];a.setIridescenceThicknessTexture(l),e.setTextureInfo(a.getIridescenceThicknessTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(zs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[zs]=a,i.getIridescenceFactor()>0)a.iridescenceFactor=i.getIridescenceFactor();if(i.getIridescenceIOR()!==1.3)a.iridescenceIor=i.getIridescenceIOR();if(i.getIridescenceThicknessMinimum()!==100)a.iridescenceThicknessMinimum=i.getIridescenceThicknessMinimum();if(i.getIridescenceThicknessMaximum()!==400)a.iridescenceThicknessMaximum=i.getIridescenceThicknessMaximum();if(i.getIridescenceTexture()){let o=i.getIridescenceTexture(),c=i.getIridescenceTextureInfo();a.iridescenceTexture=e.createTextureInfoDef(o,c)}if(i.getIridescenceThicknessTexture()){let o=i.getIridescenceThicknessTexture(),c=i.getIridescenceThicknessTextureInfo();a.iridescenceThicknessTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:vS,G:ES,B:TS,A:AS}=Ai,bU=class extends nt{static EXTENSION_NAME=Vs;init(){this.extensionName=Vs,this.propertyType="PBRSpecularGlossiness",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{diffuseFactor:[1,1,1,1],diffuseTexture:null,diffuseTextureInfo:new wt(this.graph,"diffuseTextureInfo"),specularFactor:[1,1,1],glossinessFactor:1,specularGlossinessTexture:null,specularGlossinessTextureInfo:new wt(this.graph,"specularGlossinessTextureInfo")})}getDiffuseFactor(){return this.get("diffuseFactor")}setDiffuseFactor(e){return this.set("diffuseFactor",e)}getDiffuseTexture(){return this.getRef("diffuseTexture")}getDiffuseTextureInfo(){return this.getRef("diffuseTexture")?this.getRef("diffuseTextureInfo"):null}setDiffuseTexture(e){return this.setRef("diffuseTexture",e,{channels:vS|ES|TS|AS,isColor:!0})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(e){return this.set("specularFactor",e)}getGlossinessFactor(){return this.get("glossinessFactor")}setGlossinessFactor(e){return this.set("glossinessFactor",e)}getSpecularGlossinessTexture(){return this.getRef("specularGlossinessTexture")}getSpecularGlossinessTextureInfo(){return this.getRef("specularGlossinessTexture")?this.getRef("specularGlossinessTextureInfo"):null}setSpecularGlossinessTexture(e){return this.setRef("specularGlossinessTexture",e,{channels:vS|ES|TS|AS})}},DS=class extends _t{static EXTENSION_NAME=Vs;extensionName=Vs;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createPBRSpecularGlossiness(){return new bU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_pbrSpecularGlossiness){let a=this.createPBRSpecularGlossiness();e.materials[s].setExtension(Vs,a);let o=r.extensions[Vs];if(o.extras)a.setExtras(o.extras);if(o.diffuseFactor!==void 0)a.setDiffuseFactor(o.diffuseFactor);if(o.specularFactor!==void 0)a.setSpecularFactor(o.specularFactor);if(o.glossinessFactor!==void 0)a.setGlossinessFactor(o.glossinessFactor);if(o.diffuseTexture!==void 0){let c=o.diffuseTexture,l=e.textures[i[c.index].source];a.setDiffuseTexture(l),e.setTextureInfo(a.getDiffuseTextureInfo(),c)}if(o.specularGlossinessTexture!==void 0){let c=o.specularGlossinessTexture,l=e.textures[i[c.index].source];a.setSpecularGlossinessTexture(l),e.setTextureInfo(a.getSpecularGlossinessTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Vs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Vs]=a,a.diffuseFactor=i.getDiffuseFactor(),a.specularFactor=i.getSpecularFactor(),a.glossinessFactor=i.getGlossinessFactor(),i.getDiffuseTexture()){let o=i.getDiffuseTexture(),c=i.getDiffuseTextureInfo();a.diffuseTexture=e.createTextureInfoDef(o,c)}if(i.getSpecularGlossinessTexture()){let o=i.getSpecularGlossinessTexture(),c=i.getSpecularGlossinessTextureInfo();a.specularGlossinessTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:xU,G:yU,B:_U,A:vU}=Ai,EU=class extends nt{static EXTENSION_NAME=js;init(){this.extensionName=js,this.propertyType="Sheen",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{sheenColorFactor:[0,0,0],sheenColorTexture:null,sheenColorTextureInfo:new wt(this.graph,"sheenColorTextureInfo"),sheenRoughnessFactor:0,sheenRoughnessTexture:null,sheenRoughnessTextureInfo:new wt(this.graph,"sheenRoughnessTextureInfo")})}getSheenColorFactor(){return this.get("sheenColorFactor")}setSheenColorFactor(e){return this.set("sheenColorFactor",e)}getSheenColorTexture(){return this.getRef("sheenColorTexture")}getSheenColorTextureInfo(){return this.getRef("sheenColorTexture")?this.getRef("sheenColorTextureInfo"):null}setSheenColorTexture(e){return this.setRef("sheenColorTexture",e,{channels:xU|yU|_U,isColor:!0})}getSheenRoughnessFactor(){return this.get("sheenRoughnessFactor")}setSheenRoughnessFactor(e){return this.set("sheenRoughnessFactor",e)}getSheenRoughnessTexture(){return this.getRef("sheenRoughnessTexture")}getSheenRoughnessTextureInfo(){return this.getRef("sheenRoughnessTexture")?this.getRef("sheenRoughnessTextureInfo"):null}setSheenRoughnessTexture(e){return this.setRef("sheenRoughnessTexture",e,{channels:vU})}},TU=class extends _t{static EXTENSION_NAME=js;extensionName=js;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createSheen(){return new EU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_sheen){let a=this.createSheen();e.materials[s].setExtension(js,a);let o=r.extensions[js];if(o.extras)a.setExtras(o.extras);if(o.sheenColorFactor!==void 0)a.setSheenColorFactor(o.sheenColorFactor);if(o.sheenRoughnessFactor!==void 0)a.setSheenRoughnessFactor(o.sheenRoughnessFactor);if(o.sheenColorTexture!==void 0){let c=o.sheenColorTexture,l=e.textures[i[c.index].source];a.setSheenColorTexture(l),e.setTextureInfo(a.getSheenColorTextureInfo(),c)}if(o.sheenRoughnessTexture!==void 0){let c=o.sheenRoughnessTexture,l=e.textures[i[c.index].source];a.setSheenRoughnessTexture(l),e.setTextureInfo(a.getSheenRoughnessTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(js);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[js]=a,a.sheenColorFactor=i.getSheenColorFactor(),a.sheenRoughnessFactor=i.getSheenRoughnessFactor(),i.getSheenColorTexture()){let o=i.getSheenColorTexture(),c=i.getSheenColorTextureInfo();a.sheenColorTexture=e.createTextureInfoDef(o,c)}if(i.getSheenRoughnessTexture()){let o=i.getSheenRoughnessTexture(),c=i.getSheenRoughnessTextureInfo();a.sheenRoughnessTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:AU,G:wU,B:SU,A:MU}=Ai,RU=class extends nt{static EXTENSION_NAME=Hs;init(){this.extensionName=Hs,this.propertyType="Specular",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{specularFactor:1,specularTexture:null,specularTextureInfo:new wt(this.graph,"specularTextureInfo"),specularColorFactor:[1,1,1],specularColorTexture:null,specularColorTextureInfo:new wt(this.graph,"specularColorTextureInfo")})}getSpecularFactor(){return this.get("specularFactor")}setSpecularFactor(e){return this.set("specularFactor",e)}getSpecularColorFactor(){return this.get("specularColorFactor")}setSpecularColorFactor(e){return this.set("specularColorFactor",e)}getSpecularTexture(){return this.getRef("specularTexture")}getSpecularTextureInfo(){return this.getRef("specularTexture")?this.getRef("specularTextureInfo"):null}setSpecularTexture(e){return this.setRef("specularTexture",e,{channels:MU})}getSpecularColorTexture(){return this.getRef("specularColorTexture")}getSpecularColorTextureInfo(){return this.getRef("specularColorTexture")?this.getRef("specularColorTextureInfo"):null}setSpecularColorTexture(e){return this.setRef("specularColorTexture",e,{channels:AU|wU|SU,isColor:!0})}},LS=class extends _t{static EXTENSION_NAME=Hs;extensionName=Hs;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createSpecular(){return new RU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_specular){let a=this.createSpecular();e.materials[s].setExtension(Hs,a);let o=r.extensions[Hs];if(o.extras)a.setExtras(o.extras);if(o.specularFactor!==void 0)a.setSpecularFactor(o.specularFactor);if(o.specularColorFactor!==void 0)a.setSpecularColorFactor(o.specularColorFactor);if(o.specularTexture!==void 0){let c=o.specularTexture,l=e.textures[i[c.index].source];a.setSpecularTexture(l),e.setTextureInfo(a.getSpecularTextureInfo(),c)}if(o.specularColorTexture!==void 0){let c=o.specularColorTexture,l=e.textures[i[c.index].source];a.setSpecularColorTexture(l),e.setTextureInfo(a.getSpecularColorTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Hs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Hs]=a,i.getSpecularFactor()!==1)a.specularFactor=i.getSpecularFactor();if(!mt.eq(i.getSpecularColorFactor(),[1,1,1]))a.specularColorFactor=i.getSpecularColorFactor();if(i.getSpecularTexture()){let o=i.getSpecularTexture(),c=i.getSpecularTextureInfo();a.specularTexture=e.createTextureInfoDef(o,c)}if(i.getSpecularColorTexture()){let o=i.getSpecularColorTexture(),c=i.getSpecularColorTextureInfo();a.specularColorTexture=e.createTextureInfoDef(o,c)}}}),this}},{R:IU}=Ai,CU=class extends nt{static EXTENSION_NAME=Gs;init(){this.extensionName=Gs,this.propertyType="Transmission",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{transmissionFactor:0,transmissionTexture:null,transmissionTextureInfo:new wt(this.graph,"transmissionTextureInfo")})}getTransmissionFactor(){return this.get("transmissionFactor")}setTransmissionFactor(e){return this.set("transmissionFactor",e)}getTransmissionTexture(){return this.getRef("transmissionTexture")}getTransmissionTextureInfo(){return this.getRef("transmissionTexture")?this.getRef("transmissionTextureInfo"):null}setTransmissionTexture(e){return this.setRef("transmissionTexture",e,{channels:IU})}},NU=class extends _t{static EXTENSION_NAME=Gs;extensionName=Gs;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createTransmission(){return new CU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_transmission){let a=this.createTransmission();e.materials[s].setExtension(Gs,a);let o=r.extensions[Gs];if(o.extras)a.setExtras(o.extras);if(o.transmissionFactor!==void 0)a.setTransmissionFactor(o.transmissionFactor);if(o.transmissionTexture!==void 0){let c=o.transmissionTexture,l=e.textures[i[c.index].source];a.setTransmissionTexture(l),e.setTextureInfo(a.getTransmissionTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension(Gs);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[Gs]=a,a.transmissionFactor=i.getTransmissionFactor(),i.getTransmissionTexture()){let o=i.getTransmissionTexture(),c=i.getTransmissionTextureInfo();a.transmissionTexture=e.createTextureInfoDef(o,c)}}}),this}},PU=class extends nt{static EXTENSION_NAME=Zo;init(){this.extensionName=Zo,this.propertyType="Unlit",this.parentTypes=[Q.MATERIAL]}},FS=class extends _t{static EXTENSION_NAME=Zo;extensionName=Zo;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createUnlit(){return new PU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){return(e.jsonDoc.json.materials||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_materials_unlit)e.materials[n].setExtension(Zo,this.createUnlit())}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{if(n.getExtension("KHR_materials_unlit")){let i=e.materialIndexMap.get(n),r=t.json.materials[i];r.extensions=r.extensions||{},r.extensions[Zo]={}}}),this}},OU=class extends nt{static EXTENSION_NAME=hi;init(){this.extensionName=hi,this.propertyType="Mapping",this.parentTypes=["MappingList"]}getDefaults(){return Object.assign(super.getDefaults(),{material:null,variants:new It})}getMaterial(){return this.getRef("material")}setMaterial(e){return this.setRef("material",e)}addVariant(e){return this.addRef("variants",e)}removeVariant(e){return this.removeRef("variants",e)}listVariants(){return this.listRefs("variants")}},kU=class extends nt{static EXTENSION_NAME=hi;init(){this.extensionName=hi,this.propertyType="MappingList",this.parentTypes=[Q.PRIMITIVE]}getDefaults(){return Object.assign(super.getDefaults(),{mappings:new It})}addMapping(e){return this.addRef("mappings",e)}removeMapping(e){return this.removeRef("mappings",e)}listMappings(){return this.listRefs("mappings")}},wS=class extends nt{static EXTENSION_NAME=hi;init(){this.extensionName=hi,this.propertyType="Variant",this.parentTypes=["MappingList"]}},DU=class extends _t{extensionName=hi;static EXTENSION_NAME=hi;createMappingList(){return new kU(this.document.getGraph())}createVariant(e=""){return new wS(this.document.getGraph(),e)}createMapping(){return new OU(this.document.getGraph())}listVariants(){return Array.from(this.properties).filter((e)=>e instanceof wS)}read(e){let t=e.jsonDoc;if(!t.json.extensions||!t.json.extensions.KHR_materials_variants)return this;let n=(t.json.extensions.KHR_materials_variants.variants||[]).map((i)=>this.createVariant().setName(i.name||""));return(t.json.meshes||[]).forEach((i,r)=>{let s=e.meshes[r];(i.primitives||[]).forEach((a,o)=>{if(!a.extensions||!a.extensions.KHR_materials_variants)return;let c=this.createMappingList(),l=a.extensions[hi];for(let u of l.mappings){let d=this.createMapping();if(u.material!==void 0)d.setMaterial(e.materials[u.material]);for(let f of u.variants||[])d.addVariant(n[f]);c.addMapping(d)}s.listPrimitives()[o].setExtension(hi,c)})}),this}write(e){let t=e.jsonDoc,n=this.listVariants();if(!n.length)return this;let i=[],r=new Map;for(let s of n)r.set(s,i.length),i.push(e.createPropertyDef(s));for(let s of this.document.getRoot().listMeshes()){let a=e.meshIndexMap.get(s);s.listPrimitives().forEach((o,c)=>{let l=o.getExtension(hi);if(!l)return;let u=e.jsonDoc.json.meshes[a].primitives[c],d=l.listMappings().map((f)=>{let h=e.createPropertyDef(f),b=f.getMaterial();if(b)h.material=e.materialIndexMap.get(b);return h.variants=f.listVariants().map((m)=>r.get(m)),h});u.extensions=u.extensions||{},u.extensions[hi]={mappings:d}})}return t.json.extensions=t.json.extensions||{},t.json.extensions[hi]={variants:i},this}},{G:LU}=Ai,FU=class extends nt{static EXTENSION_NAME=$s;init(){this.extensionName=$s,this.propertyType="Volume",this.parentTypes=[Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{thicknessFactor:0,thicknessTexture:null,thicknessTextureInfo:new wt(this.graph,"thicknessTexture"),attenuationDistance:1/0,attenuationColor:[1,1,1]})}getThicknessFactor(){return this.get("thicknessFactor")}setThicknessFactor(e){return this.set("thicknessFactor",e)}getThicknessTexture(){return this.getRef("thicknessTexture")}getThicknessTextureInfo(){return this.getRef("thicknessTexture")?this.getRef("thicknessTextureInfo"):null}setThicknessTexture(e){return this.setRef("thicknessTexture",e,{channels:LU})}getAttenuationDistance(){return this.get("attenuationDistance")}setAttenuationDistance(e){return this.set("attenuationDistance",e)}getAttenuationColor(){return this.get("attenuationColor")}setAttenuationColor(e){return this.set("attenuationColor",e)}},UU=class extends _t{static EXTENSION_NAME=$s;extensionName=$s;prereadTypes=[Q.MESH];prewriteTypes=[Q.MESH];createVolume(){return new FU(this.document.getGraph())}read(e){return this}write(e){return this}preread(e){let t=e.jsonDoc,n=t.json.materials||[],i=t.json.textures||[];return n.forEach((r,s)=>{if(r.extensions&&r.extensions.KHR_materials_volume){let a=this.createVolume();e.materials[s].setExtension($s,a);let o=r.extensions[$s];if(o.extras)a.setExtras(o.extras);if(o.thicknessFactor!==void 0)a.setThicknessFactor(o.thicknessFactor);if(o.attenuationDistance!==void 0)a.setAttenuationDistance(o.attenuationDistance);if(o.attenuationColor!==void 0)a.setAttenuationColor(o.attenuationColor);if(o.thicknessTexture!==void 0){let c=o.thicknessTexture,l=e.textures[i[c.index].source];a.setThicknessTexture(l),e.setTextureInfo(a.getThicknessTextureInfo(),c)}}}),this}prewrite(e){let t=e.jsonDoc;return this.document.getRoot().listMaterials().forEach((n)=>{let i=n.getExtension($s);if(i){let r=e.materialIndexMap.get(n),s=t.json.materials[r],a=e.createPropertyDef(i);if(s.extensions=s.extensions||{},s.extensions[$s]=a,i.getThicknessFactor()>0)a.thicknessFactor=i.getThicknessFactor();if(Number.isFinite(i.getAttenuationDistance()))a.attenuationDistance=i.getAttenuationDistance();if(!mt.eq(i.getAttenuationColor(),[1,1,1]))a.attenuationColor=i.getAttenuationColor();if(i.getThicknessTexture()){let o=i.getThicknessTexture(),c=i.getThicknessTextureInfo();a.thicknessTexture=e.createTextureInfoDef(o,c)}}}),this}},US=class extends _t{extensionName=cS;static EXTENSION_NAME=cS;read(e){return this}write(e){return this}},Il=class extends _t{extensionName=lS;static EXTENSION_NAME=lS;read(e){return this}write(e){return this}},BU=class extends nt{static EXTENSION_NAME=Ks;init(){this.extensionName=Ks,this.propertyType="Visibility",this.parentTypes=[Q.NODE]}getDefaults(){return Object.assign(super.getDefaults(),{visible:!0})}getVisible(){return this.get("visible")}setVisible(e){return this.set("visible",e)}},zU=class extends _t{static EXTENSION_NAME=Ks;extensionName=Ks;createVisibility(){return new BU(this.document.getGraph())}read(e){return(e.jsonDoc.json.nodes||[]).forEach((t,n)=>{if(t.extensions&&t.extensions.KHR_node_visibility){let i=this.createVisibility();e.nodes[n].setExtension(Ks,i);let r=t.extensions[Ks];if(r.visible!==void 0)i.setVisible(r.visible)}}),this}write(e){let t=e.jsonDoc;for(let n of this.document.getRoot().listNodes()){let i=n.getExtension(Ks);if(!i)continue;let r=e.nodeIndexMap.get(n),s=t.json.nodes[r];s.extensions=s.extensions||{},s.extensions[Ks]={visible:i.getVisible()}}return this}};Xg=class extends _t{static EXTENSION_NAME=df;extensionName=df;prereadTypes=[Q.TEXTURE];static register(){Gi.registerFormat("image/ktx2",new jU)}preread(e){if(e.jsonDoc.json.textures)e.jsonDoc.json.textures.forEach((t)=>{if(t.extensions&&t.extensions.KHR_texture_basisu)t.source=t.extensions[df].source});return this}read(e){return this}write(e){let t=e.jsonDoc;return this.document.getRoot().listTextures().forEach((n)=>{if(n.getMimeType()==="image/ktx2"){let i=e.imageIndexMap.get(n);t.json.textures.forEach((r)=>{if(r.source===i)r.extensions=r.extensions||{},r.extensions[df]={source:r.source},delete r.source})}}),this}},HU=class extends nt{static EXTENSION_NAME=Ws;init(){this.extensionName=Ws,this.propertyType="Transform",this.parentTypes=[Q.TEXTURE_INFO]}getDefaults(){return Object.assign(super.getDefaults(),{offset:[0,0],rotation:0,scale:[1,1],texCoord:null})}getOffset(){return this.get("offset")}setOffset(e){return this.set("offset",e)}getRotation(){return this.get("rotation")}setRotation(e){return this.set("rotation",e)}getScale(){return this.get("scale")}setScale(e){return this.set("scale",e)}getTexCoord(){return this.get("texCoord")}setTexCoord(e){return this.set("texCoord",e)}},GU=class extends _t{extensionName=Ws;static EXTENSION_NAME=Ws;createTransform(){return new HU(this.document.getGraph())}read(e){for(let[t,n]of Array.from(e.textureInfos.entries())){if(!n.extensions||!n.extensions.KHR_texture_transform)continue;let i=this.createTransform(),r=n.extensions[Ws];if(r.offset!==void 0)i.setOffset(r.offset);if(r.rotation!==void 0)i.setRotation(r.rotation);if(r.scale!==void 0)i.setScale(r.scale);if(r.texCoord!==void 0)i.setTexCoord(r.texCoord);t.setExtension(Ws,i)}return this}write(e){let t=Array.from(e.textureInfoDefMap.entries());for(let[n,i]of t){let r=n.getExtension(Ws);if(!r)continue;i.extensions=i.extensions||{};let s={},a=mt.eq;if(!a(r.getOffset(),[0,0]))s.offset=r.getOffset();if(r.getRotation()!==0)s.rotation=r.getRotation();if(!a(r.getScale(),[1,1]))s.scale=r.getScale();if(r.getTexCoord()!=null)s.texCoord=r.getTexCoord();i.extensions[Ws]=s}return this}},$U=[Q.ROOT,Q.SCENE,Q.NODE,Q.MESH,Q.MATERIAL,Q.TEXTURE,Q.ANIMATION],KU=class extends nt{static EXTENSION_NAME=$i;init(){this.extensionName=$i,this.propertyType="Packet",this.parentTypes=$U}getDefaults(){return Object.assign(super.getDefaults(),{context:{},properties:{}})}getContext(){return this.get("context")}setContext(e){return this.set("context",{...e})}listProperties(){return Object.keys(this.get("properties"))}getProperty(e){let t=this.get("properties");return e in t?t[e]:null}setProperty(e,t){this._assertContext(e);let n={...this.get("properties")};if(t)n[e]=t;else delete n[e];return this.set("properties",n)}toJSONLD(){return{"@context":Gg(this.get("context")),...Gg(this.get("properties"))}}fromJSONLD(e){e=Gg(e);let t=e["@context"];if(t)this.set("context",t);return delete e["@context"],this.set("properties",e)}_assertContext(e){if(!(e.split(":")[0]in this.get("context")))throw Error(`${$i}: Missing context for term, "${e}".`)}};WU=class extends _t{extensionName=$i;static EXTENSION_NAME=$i;createPacket(){return new KU(this.document.getGraph())}listPackets(){return Array.from(this.properties)}read(e){let t=e.jsonDoc.json.extensions?.[$i];if(!t||!t.packets)return this;let n=e.jsonDoc.json,i=this.document.getRoot(),r=t.packets.map((o)=>this.createPacket().fromJSONLD(o)),s=[[n.asset],n.scenes,n.nodes,n.meshes,n.materials,n.images,n.animations],a=[[i],i.listScenes(),i.listNodes(),i.listMeshes(),i.listMaterials(),i.listTextures(),i.listAnimations()];for(let o=0;o<s.length;o++){let c=s[o]||[];for(let l=0;l<c.length;l++){let u=c[l];if(u.extensions&&u.extensions.KHR_xmp_json_ld){let d=u.extensions[$i];a[o][l].setExtension($i,r[d.packet])}}}return this}write(e){let{json:t}=e.jsonDoc,n=[];for(let i of this.properties){n.push(i.toJSONLD());for(let r of i.listParents()){let s;switch(r.propertyType){case Q.ROOT:s=t.asset;break;case Q.SCENE:s=t.scenes[e.sceneIndexMap.get(r)];break;case Q.NODE:s=t.nodes[e.nodeIndexMap.get(r)];break;case Q.MESH:s=t.meshes[e.meshIndexMap.get(r)];break;case Q.MATERIAL:s=t.materials[e.materialIndexMap.get(r)];break;case Q.TEXTURE:s=t.images[e.imageIndexMap.get(r)];break;case Q.ANIMATION:s=t.animations[e.animationIndexMap.get(r)];break;default:s=null,this.document.getLogger().warn(`[${$i}]: Unsupported parent property, "${r.propertyType}"`)}if(!s)continue;s.extensions=s.extensions||{},s.extensions[$i]={packet:n.length-1}}}if(n.length>0)t.extensions=t.extensions||{},t.extensions[$i]={packets:n};return this}},XU=[D2,L2,OS,W2,Y2,tU,oU,lU,dU,kS,gU,DS,LS,TU,NU,FS,DU,UU,US,Il,zU,Xg,GU,WU],BS=[ff,PF,Rl,o2,RS,IS,...XU]});var VS=Jr(function(eK,zS){function qU(e){var t=Array(e);for(var n=0;n<e;++n)t[n]=n;return t}zS.exports=qU});var GS=Jr(function(tK,HS){/*!* Determine if an object is a Buffer** @author Feross Aboukhadijeh <https://feross.org>* @license MIT- */BS.exports=function(e){return e!=null&&(US(e)||$U(e)||!!e._isBuffer)};function US(e){return!!e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)}function $U(e){return typeof e.readFloatLE==="function"&&typeof e.slice==="function"&&US(e.slice(0,0))}});var $g=Jr(function(j5,VS){var KU=FS(),WU=zS(),XU=typeof Float64Array<"u";function qU(e,t){return e[0]-t[0]}function JU(){var e=this.stride,t=Array(e.length),n;for(n=0;n<t.length;++n)t[n]=[Math.abs(e[n]),n];t.sort(qU);var i=Array(t.length);for(n=0;n<i.length;++n)i[n]=t[n][1];return i}function ZU(e,t){var n=["View",t,"d",e].join("");if(t<0)n="View_Nil"+e;var i=e==="generic";if(t===-1){var r="function "+n+"(a){this.data=a;};var proto="+n+".prototype;proto.dtype='"+e+"';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new "+n+"(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_"+n+"(a){return new "+n+"(a);}",m=Function(r);return m()}else if(t===0){var r="function "+n+"(a,d) {this.data = a;this.offset = d};var proto="+n+".prototype;proto.dtype='"+e+"';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function "+n+"_copy() {return new "+n+"(this.data,this.offset)};proto.pick=function "+n+"_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function "+n+"_get(){return "+(i?"this.data.get(this.offset)":"this.data[this.offset]")+"};proto.set=function "+n+"_set(v){return "+(i?"this.data.set(this.offset,v)":"this.data[this.offset]=v")+"};return function construct_"+n+"(a,b,c,d){return new "+n+"(a,d)}",m=Function("TrivialArray",r);return m(df[e][0])}var r=["'use strict'"],s=KU(t),a=s.map(function(g){return"i"+g}),o="this.offset+"+s.map(function(g){return"this.stride["+g+"]*i"+g}).join("+"),c=s.map(function(g){return"b"+g}).join(","),l=s.map(function(g){return"c"+g}).join(",");if(r.push("function "+n+"(a,"+c+","+l+",d){this.data=a","this.shape=["+c+"]","this.stride=["+l+"]","this.offset=d|0}","var proto="+n+".prototype","proto.dtype='"+e+"'","proto.dimension="+t),r.push("Object.defineProperty(proto,'size',{get:function "+n+"_size(){return "+s.map(function(g){return"this.shape["+g+"]"}).join("*"),"}})"),t===1)r.push("proto.order=[0]");else if(r.push("Object.defineProperty(proto,'order',{get:"),t<4){if(r.push("function "+n+"_order(){"),t===2)r.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})");else if(t===3)r.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")}else r.push("ORDER})");if(r.push("proto.set=function "+n+"_set("+a.join(",")+",v){"),i)r.push("return this.data.set("+o+",v)}");else r.push("return this.data["+o+"]=v}");if(r.push("proto.get=function "+n+"_get("+a.join(",")+"){"),i)r.push("return this.data.get("+o+")}");else r.push("return this.data["+o+"]}");r.push("proto.index=function "+n+"_index(",a.join(),"){return "+o+"}"),r.push("proto.hi=function "+n+"_hi("+a.join(",")+"){return new "+n+"(this.data,"+s.map(function(g){return["(typeof i",g,"!=='number'||i",g,"<0)?this.shape[",g,"]:i",g,"|0"].join("")}).join(",")+","+s.map(function(g){return"this.stride["+g+"]"}).join(",")+",this.offset)}");var u=s.map(function(g){return"a"+g+"=this.shape["+g+"]"}),d=s.map(function(g){return"c"+g+"=this.stride["+g+"]"});r.push("proto.lo=function "+n+"_lo("+a.join(",")+"){var b=this.offset,d=0,"+u.join(",")+","+d.join(","));for(var f=0;f<t;++f)r.push("if(typeof i"+f+"==='number'&&i"+f+">=0){d=i"+f+"|0;b+=c"+f+"*d;a"+f+"-=d}");r.push("return new "+n+"(this.data,"+s.map(function(g){return"a"+g}).join(",")+","+s.map(function(g){return"c"+g}).join(",")+",b)}"),r.push("proto.step=function "+n+"_step("+a.join(",")+"){var "+s.map(function(g){return"a"+g+"=this.shape["+g+"]"}).join(",")+","+s.map(function(g){return"b"+g+"=this.stride["+g+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(var f=0;f<t;++f)r.push("if(typeof i"+f+"==='number'){d=i"+f+"|0;if(d<0){c+=b"+f+"*(a"+f+"-1);a"+f+"=ceil(-a"+f+"/d)}else{a"+f+"=ceil(a"+f+"/d)}b"+f+"*=d}");r.push("return new "+n+"(this.data,"+s.map(function(g){return"a"+g}).join(",")+","+s.map(function(g){return"b"+g}).join(",")+",c)}");var h=Array(t),b=Array(t);for(var f=0;f<t;++f)h[f]="a[i"+f+"]",b[f]="b[i"+f+"]";r.push("proto.transpose=function "+n+"_transpose("+a+"){"+a.map(function(g,p){return g+"=("+g+"===undefined?"+p+":"+g+"|0)"}).join(";"),"var a=this.shape,b=this.stride;return new "+n+"(this.data,"+h.join(",")+","+b.join(",")+",this.offset)}"),r.push("proto.pick=function "+n+"_pick("+a+"){var a=[],b=[],c=this.offset");for(var f=0;f<t;++f)r.push("if(typeof i"+f+"==='number'&&i"+f+">=0){c=(c+this.stride["+f+"]*i"+f+")|0}else{a.push(this.shape["+f+"]);b.push(this.stride["+f+"])}");r.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),r.push("return function construct_"+n+"(data,shape,stride,offset){return new "+n+"(data,"+s.map(function(g){return"shape["+g+"]"}).join(",")+","+s.map(function(g){return"stride["+g+"]"}).join(",")+",offset)}");var m=Function("CTOR_LIST","ORDER",r.join(`-`));return m(df[e],JU)}function YU(e){if(WU(e))return"buffer";if(XU)switch(Object.prototype.toString.call(e)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped";case"[object BigInt64Array]":return"bigint64";case"[object BigUint64Array]":return"biguint64"}if(Array.isArray(e))return"array";return"generic"}var df={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],bigint64:[],biguint64:[],buffer:[],generic:[]};function QU(e,t,n,i){if(e===void 0){var l=df.array[0];return l([])}else if(typeof e==="number")e=[e];if(t===void 0)t=[e.length];var r=t.length;if(n===void 0){n=Array(r);for(var s=r-1,a=1;s>=0;--s)n[s]=a,a*=t[s]}if(i===void 0){i=0;for(var s=0;s<r;++s)if(n[s]<0)i-=(t[s]-1)*n[s]}var o=YU(e),c=df[o];while(c.length<=r+1)c.push(ZU(o,c.length-1));var l=c[r+1];return l(e,t,n,i)}VS.exports=QU});var HS=Jr(function(H5,jS){function e3(e,t){var n=1,i=e.length,r=e[0],s=e[0];for(var a=1;a<i;++a)if(s=r,r=e[a],t(r,s)){if(a===n){n++;continue}e[n++]=r}return e.length=n,e}function t3(e){var t=1,n=e.length,i=e[0],r=e[0];for(var s=1;s<n;++s,r=i)if(r=i,i=e[s],i!==r){if(s===t){t++;continue}e[t++]=i}return e.length=t,e}function n3(e,t,n){if(e.length===0)return e;if(t){if(!n)e.sort(t);return e3(e,t)}if(!n)e.sort();return t3(e)}jS.exports=n3});var KS=Jr(function(G5,$S){var i3=HS();function GS(e,t,n){var i=e.length,r=t.arrayArgs.length,s=t.indexArgs.length>0,a=[],o=[],c=0,l=0,u,d;for(u=0;u<i;++u)o.push(["i",u,"=0"].join(""));for(d=0;d<r;++d)for(u=0;u<i;++u)if(l=c,c=e[u],u===0)o.push(["d",d,"s",u,"=t",d,"p",c].join(""));else o.push(["d",d,"s",u,"=(t",d,"p",c,"-s",l,"*t",d,"p",l,")"].join(""));if(o.length>0)a.push("var "+o.join(","));for(u=i-1;u>=0;--u)c=e[u],a.push(["for(i",u,"=0;i",u,"<s",c,";++i",u,"){"].join(""));a.push(n);for(u=0;u<i;++u){l=c,c=e[u];for(d=0;d<r;++d)a.push(["p",d,"+=d",d,"s",u].join(""));if(s){if(u>0)a.push(["index[",l,"]-=s",l].join(""));a.push(["++index[",c,"]"].join(""))}a.push("}")}return a.join(`-`)}function r3(e,t,n,i){var r=t.length,s=n.arrayArgs.length,a=n.blockSize,o=n.indexArgs.length>0,c=[];for(var l=0;l<s;++l)c.push(["var offset",l,"=p",l].join(""));for(var l=e;l<r;++l)if(c.push(["for(var j"+l+"=SS[",t[l],"]|0;j",l,">0;){"].join("")),c.push(["if(j",l,"<",a,"){"].join("")),c.push(["s",t[l],"=j",l].join("")),c.push(["j",l,"=0"].join("")),c.push(["}else{s",t[l],"=",a].join("")),c.push(["j",l,"-=",a,"}"].join("")),o)c.push(["index[",t[l],"]=j",l].join(""));for(var l=0;l<s;++l){var u=["offset"+l];for(var d=e;d<r;++d)u.push(["j",d,"*t",l,"p",t[d]].join(""));c.push(["p",l,"=(",u.join("+"),")"].join(""))}c.push(GS(t,n,i));for(var l=e;l<r;++l)c.push("}");return c.join(`-`)}function s3(e){var t=0,n=e[0].length;while(t<n){for(var i=1;i<e.length;++i)if(e[i][t]!==e[0][t])return t;++t}return t}function Kg(e,t,n){var i=e.body,r=[],s=[];for(var a=0;a<e.args.length;++a){var o=e.args[a];if(o.count<=0)continue;var c=new RegExp(o.name,"g"),l="",u=t.arrayArgs.indexOf(a);switch(t.argTypes[a]){case"offset":var d=t.offsetArgIndex.indexOf(a),f=t.offsetArgs[d];u=f.array,l="+q"+d;case"array":l="p"+u+l;var h="l"+a,b="a"+u;if(t.arrayBlockIndices[u]===0){if(o.count===1)if(n[u]==="generic")if(o.lvalue)r.push(["var ",h,"=",b,".get(",l,")"].join("")),i=i.replace(c,h),s.push([b,".set(",l,",",h,")"].join(""));else i=i.replace(c,[b,".get(",l,")"].join(""));else i=i.replace(c,[b,"[",l,"]"].join(""));else if(n[u]==="generic"){if(r.push(["var ",h,"=",b,".get(",l,")"].join("")),i=i.replace(c,h),o.lvalue)s.push([b,".set(",l,",",h,")"].join(""))}else if(r.push(["var ",h,"=",b,"[",l,"]"].join("")),i=i.replace(c,h),o.lvalue)s.push([b,"[",l,"]=",h].join(""))}else{var m=[o.name],g=[l];for(var p=0;p<Math.abs(t.arrayBlockIndices[u]);p++)m.push("\\s*\\[([^\\]]+)\\]"),g.push("$"+(p+1)+"*t"+u+"b"+p);if(c=new RegExp(m.join(""),"g"),l=g.join("+"),n[u]==="generic")throw Error("cwise: Generic arrays not supported in combination with blocks!");else i=i.replace(c,[b,"[",l,"]"].join(""))}break;case"scalar":i=i.replace(c,"Y"+t.scalarArgs.indexOf(a));break;case"index":i=i.replace(c,"index");break;case"shape":i=i.replace(c,"shape");break}}return[r.join(`+ */HS.exports=function(e){return e!=null&&(jS(e)||JU(e)||!!e._isBuffer)};function jS(e){return!!e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)}function JU(e){return typeof e.readFloatLE==="function"&&typeof e.slice==="function"&&jS(e.slice(0,0))}});var qg=Jr(function(nK,$S){var ZU=VS(),YU=GS(),QU=typeof Float64Array<"u";function e3(e,t){return e[0]-t[0]}function t3(){var e=this.stride,t=Array(e.length),n;for(n=0;n<t.length;++n)t[n]=[Math.abs(e[n]),n];t.sort(e3);var i=Array(t.length);for(n=0;n<i.length;++n)i[n]=t[n][1];return i}function n3(e,t){var n=["View",t,"d",e].join("");if(t<0)n="View_Nil"+e;var i=e==="generic";if(t===-1){var r="function "+n+"(a){this.data=a;};var proto="+n+".prototype;proto.dtype='"+e+"';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new "+n+"(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_"+n+"(a){return new "+n+"(a);}",m=Function(r);return m()}else if(t===0){var r="function "+n+"(a,d) {this.data = a;this.offset = d};var proto="+n+".prototype;proto.dtype='"+e+"';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function "+n+"_copy() {return new "+n+"(this.data,this.offset)};proto.pick=function "+n+"_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function "+n+"_get(){return "+(i?"this.data.get(this.offset)":"this.data[this.offset]")+"};proto.set=function "+n+"_set(v){return "+(i?"this.data.set(this.offset,v)":"this.data[this.offset]=v")+"};return function construct_"+n+"(a,b,c,d){return new "+n+"(a,d)}",m=Function("TrivialArray",r);return m(pf[e][0])}var r=["'use strict'"],s=ZU(t),a=s.map(function(g){return"i"+g}),o="this.offset+"+s.map(function(g){return"this.stride["+g+"]*i"+g}).join("+"),c=s.map(function(g){return"b"+g}).join(","),l=s.map(function(g){return"c"+g}).join(",");if(r.push("function "+n+"(a,"+c+","+l+",d){this.data=a","this.shape=["+c+"]","this.stride=["+l+"]","this.offset=d|0}","var proto="+n+".prototype","proto.dtype='"+e+"'","proto.dimension="+t),r.push("Object.defineProperty(proto,'size',{get:function "+n+"_size(){return "+s.map(function(g){return"this.shape["+g+"]"}).join("*"),"}})"),t===1)r.push("proto.order=[0]");else if(r.push("Object.defineProperty(proto,'order',{get:"),t<4){if(r.push("function "+n+"_order(){"),t===2)r.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})");else if(t===3)r.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")}else r.push("ORDER})");if(r.push("proto.set=function "+n+"_set("+a.join(",")+",v){"),i)r.push("return this.data.set("+o+",v)}");else r.push("return this.data["+o+"]=v}");if(r.push("proto.get=function "+n+"_get("+a.join(",")+"){"),i)r.push("return this.data.get("+o+")}");else r.push("return this.data["+o+"]}");r.push("proto.index=function "+n+"_index(",a.join(),"){return "+o+"}"),r.push("proto.hi=function "+n+"_hi("+a.join(",")+"){return new "+n+"(this.data,"+s.map(function(g){return["(typeof i",g,"!=='number'||i",g,"<0)?this.shape[",g,"]:i",g,"|0"].join("")}).join(",")+","+s.map(function(g){return"this.stride["+g+"]"}).join(",")+",this.offset)}");var u=s.map(function(g){return"a"+g+"=this.shape["+g+"]"}),d=s.map(function(g){return"c"+g+"=this.stride["+g+"]"});r.push("proto.lo=function "+n+"_lo("+a.join(",")+"){var b=this.offset,d=0,"+u.join(",")+","+d.join(","));for(var f=0;f<t;++f)r.push("if(typeof i"+f+"==='number'&&i"+f+">=0){d=i"+f+"|0;b+=c"+f+"*d;a"+f+"-=d}");r.push("return new "+n+"(this.data,"+s.map(function(g){return"a"+g}).join(",")+","+s.map(function(g){return"c"+g}).join(",")+",b)}"),r.push("proto.step=function "+n+"_step("+a.join(",")+"){var "+s.map(function(g){return"a"+g+"=this.shape["+g+"]"}).join(",")+","+s.map(function(g){return"b"+g+"=this.stride["+g+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(var f=0;f<t;++f)r.push("if(typeof i"+f+"==='number'){d=i"+f+"|0;if(d<0){c+=b"+f+"*(a"+f+"-1);a"+f+"=ceil(-a"+f+"/d)}else{a"+f+"=ceil(a"+f+"/d)}b"+f+"*=d}");r.push("return new "+n+"(this.data,"+s.map(function(g){return"a"+g}).join(",")+","+s.map(function(g){return"b"+g}).join(",")+",c)}");var h=Array(t),b=Array(t);for(var f=0;f<t;++f)h[f]="a[i"+f+"]",b[f]="b[i"+f+"]";r.push("proto.transpose=function "+n+"_transpose("+a+"){"+a.map(function(g,p){return g+"=("+g+"===undefined?"+p+":"+g+"|0)"}).join(";"),"var a=this.shape,b=this.stride;return new "+n+"(this.data,"+h.join(",")+","+b.join(",")+",this.offset)}"),r.push("proto.pick=function "+n+"_pick("+a+"){var a=[],b=[],c=this.offset");for(var f=0;f<t;++f)r.push("if(typeof i"+f+"==='number'&&i"+f+">=0){c=(c+this.stride["+f+"]*i"+f+")|0}else{a.push(this.shape["+f+"]);b.push(this.stride["+f+"])}");r.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),r.push("return function construct_"+n+"(data,shape,stride,offset){return new "+n+"(data,"+s.map(function(g){return"shape["+g+"]"}).join(",")+","+s.map(function(g){return"stride["+g+"]"}).join(",")+",offset)}");var m=Function("CTOR_LIST","ORDER",r.join(`+`));return m(pf[e],t3)}function i3(e){if(YU(e))return"buffer";if(QU)switch(Object.prototype.toString.call(e)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped";case"[object BigInt64Array]":return"bigint64";case"[object BigUint64Array]":return"biguint64"}if(Array.isArray(e))return"array";return"generic"}var pf={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],bigint64:[],biguint64:[],buffer:[],generic:[]};function r3(e,t,n,i){if(e===void 0){var l=pf.array[0];return l([])}else if(typeof e==="number")e=[e];if(t===void 0)t=[e.length];var r=t.length;if(n===void 0){n=Array(r);for(var s=r-1,a=1;s>=0;--s)n[s]=a,a*=t[s]}if(i===void 0){i=0;for(var s=0;s<r;++s)if(n[s]<0)i-=(t[s]-1)*n[s]}var o=i3(e),c=pf[o];while(c.length<=r+1)c.push(n3(o,c.length-1));var l=c[r+1];return l(e,t,n,i)}$S.exports=r3});var WS=Jr(function(iK,KS){function s3(e,t){var n=1,i=e.length,r=e[0],s=e[0];for(var a=1;a<i;++a)if(s=r,r=e[a],t(r,s)){if(a===n){n++;continue}e[n++]=r}return e.length=n,e}function a3(e){var t=1,n=e.length,i=e[0],r=e[0];for(var s=1;s<n;++s,r=i)if(r=i,i=e[s],i!==r){if(s===t){t++;continue}e[t++]=i}return e.length=t,e}function o3(e,t,n){if(e.length===0)return e;if(t){if(!n)e.sort(t);return s3(e,t)}if(!n)e.sort();return a3(e)}KS.exports=o3});var JS=Jr(function(rK,qS){var c3=WS();function XS(e,t,n){var i=e.length,r=t.arrayArgs.length,s=t.indexArgs.length>0,a=[],o=[],c=0,l=0,u,d;for(u=0;u<i;++u)o.push(["i",u,"=0"].join(""));for(d=0;d<r;++d)for(u=0;u<i;++u)if(l=c,c=e[u],u===0)o.push(["d",d,"s",u,"=t",d,"p",c].join(""));else o.push(["d",d,"s",u,"=(t",d,"p",c,"-s",l,"*t",d,"p",l,")"].join(""));if(o.length>0)a.push("var "+o.join(","));for(u=i-1;u>=0;--u)c=e[u],a.push(["for(i",u,"=0;i",u,"<s",c,";++i",u,"){"].join(""));a.push(n);for(u=0;u<i;++u){l=c,c=e[u];for(d=0;d<r;++d)a.push(["p",d,"+=d",d,"s",u].join(""));if(s){if(u>0)a.push(["index[",l,"]-=s",l].join(""));a.push(["++index[",c,"]"].join(""))}a.push("}")}return a.join(`+`)}function l3(e,t,n,i){var r=t.length,s=n.arrayArgs.length,a=n.blockSize,o=n.indexArgs.length>0,c=[];for(var l=0;l<s;++l)c.push(["var offset",l,"=p",l].join(""));for(var l=e;l<r;++l)if(c.push(["for(var j"+l+"=SS[",t[l],"]|0;j",l,">0;){"].join("")),c.push(["if(j",l,"<",a,"){"].join("")),c.push(["s",t[l],"=j",l].join("")),c.push(["j",l,"=0"].join("")),c.push(["}else{s",t[l],"=",a].join("")),c.push(["j",l,"-=",a,"}"].join("")),o)c.push(["index[",t[l],"]=j",l].join(""));for(var l=0;l<s;++l){var u=["offset"+l];for(var d=e;d<r;++d)u.push(["j",d,"*t",l,"p",t[d]].join(""));c.push(["p",l,"=(",u.join("+"),")"].join(""))}c.push(XS(t,n,i));for(var l=e;l<r;++l)c.push("}");return c.join(`+`)}function u3(e){var t=0,n=e[0].length;while(t<n){for(var i=1;i<e.length;++i)if(e[i][t]!==e[0][t])return t;++t}return t}function Jg(e,t,n){var i=e.body,r=[],s=[];for(var a=0;a<e.args.length;++a){var o=e.args[a];if(o.count<=0)continue;var c=new RegExp(o.name,"g"),l="",u=t.arrayArgs.indexOf(a);switch(t.argTypes[a]){case"offset":var d=t.offsetArgIndex.indexOf(a),f=t.offsetArgs[d];u=f.array,l="+q"+d;case"array":l="p"+u+l;var h="l"+a,b="a"+u;if(t.arrayBlockIndices[u]===0){if(o.count===1)if(n[u]==="generic")if(o.lvalue)r.push(["var ",h,"=",b,".get(",l,")"].join("")),i=i.replace(c,h),s.push([b,".set(",l,",",h,")"].join(""));else i=i.replace(c,[b,".get(",l,")"].join(""));else i=i.replace(c,[b,"[",l,"]"].join(""));else if(n[u]==="generic"){if(r.push(["var ",h,"=",b,".get(",l,")"].join("")),i=i.replace(c,h),o.lvalue)s.push([b,".set(",l,",",h,")"].join(""))}else if(r.push(["var ",h,"=",b,"[",l,"]"].join("")),i=i.replace(c,h),o.lvalue)s.push([b,"[",l,"]=",h].join(""))}else{var m=[o.name],g=[l];for(var p=0;p<Math.abs(t.arrayBlockIndices[u]);p++)m.push("\\s*\\[([^\\]]+)\\]"),g.push("$"+(p+1)+"*t"+u+"b"+p);if(c=new RegExp(m.join(""),"g"),l=g.join("+"),n[u]==="generic")throw Error("cwise: Generic arrays not supported in combination with blocks!");else i=i.replace(c,[b,"[",l,"]"].join(""))}break;case"scalar":i=i.replace(c,"Y"+t.scalarArgs.indexOf(a));break;case"index":i=i.replace(c,"index");break;case"shape":i=i.replace(c,"shape");break}}return[r.join(``),i,s.join(``)].join(`-`).trim()}function a3(e){var t=Array(e.length),n=!0;for(var i=0;i<e.length;++i){var r=e[i],s=r.match(/\d+/);if(!s)s="";else s=s[0];if(r.charAt(0)===0)t[i]="u"+r.charAt(1)+s;else t[i]=r.charAt(0)+s;if(i>0)n=n&&t[i]===t[i-1]}if(n)return t[0];return t.join("")}function o3(e,t){var n=t[1].length-Math.abs(e.arrayBlockIndices[0])|0,i=Array(e.arrayArgs.length),r=Array(e.arrayArgs.length);for(var s=0;s<e.arrayArgs.length;++s)r[s]=t[2*s],i[s]=t[2*s+1];var a=[],o=[],c=[],l=[],u=[];for(var s=0;s<e.arrayArgs.length;++s){if(e.arrayBlockIndices[s]<0)c.push(0),l.push(n),a.push(n),o.push(n+e.arrayBlockIndices[s]);else c.push(e.arrayBlockIndices[s]),l.push(e.arrayBlockIndices[s]+n),a.push(0),o.push(e.arrayBlockIndices[s]);var d=[];for(var f=0;f<i[s].length;f++)if(c[s]<=i[s][f]&&i[s][f]<l[s])d.push(i[s][f]-c[s]);u.push(d)}var h=["SS"],b=["'use strict'"],m=[];for(var f=0;f<n;++f)m.push(["s",f,"=SS[",f,"]"].join(""));for(var s=0;s<e.arrayArgs.length;++s){h.push("a"+s),h.push("t"+s),h.push("p"+s);for(var f=0;f<n;++f)m.push(["t",s,"p",f,"=t",s,"[",c[s]+f,"]"].join(""));for(var f=0;f<Math.abs(e.arrayBlockIndices[s]);++f)m.push(["t",s,"b",f,"=t",s,"[",a[s]+f,"]"].join(""))}for(var s=0;s<e.scalarArgs.length;++s)h.push("Y"+s);if(e.shapeArgs.length>0)m.push("shape=SS.slice(0)");if(e.indexArgs.length>0){var g=Array(n);for(var s=0;s<n;++s)g[s]="0";m.push(["index=[",g.join(","),"]"].join(""))}for(var s=0;s<e.offsetArgs.length;++s){var p=e.offsetArgs[s],x=[];for(var f=0;f<p.offset.length;++f)if(p.offset[f]===0)continue;else if(p.offset[f]===1)x.push(["t",p.array,"p",f].join(""));else x.push([p.offset[f],"*t",p.array,"p",f].join(""));if(x.length===0)m.push("q"+s+"=0");else m.push(["q",s,"=",x.join("+")].join(""))}var _=i3([].concat(e.pre.thisVars).concat(e.body.thisVars).concat(e.post.thisVars));if(m=m.concat(_),m.length>0)b.push("var "+m.join(","));for(var s=0;s<e.arrayArgs.length;++s)b.push("p"+s+"|=0");if(e.pre.body.length>3)b.push(Kg(e.pre,e,r));var y=Kg(e.body,e,r),v=s3(u);if(v<n)b.push(r3(v,u[0],e,y));else b.push(GS(u[0],e,y));if(e.post.body.length>3)b.push(Kg(e.post,e,r));if(e.debug)console.log("-----Generated cwise routine for ",t,`:+`).trim()}function d3(e){var t=Array(e.length),n=!0;for(var i=0;i<e.length;++i){var r=e[i],s=r.match(/\d+/);if(!s)s="";else s=s[0];if(r.charAt(0)===0)t[i]="u"+r.charAt(1)+s;else t[i]=r.charAt(0)+s;if(i>0)n=n&&t[i]===t[i-1]}if(n)return t[0];return t.join("")}function f3(e,t){var n=t[1].length-Math.abs(e.arrayBlockIndices[0])|0,i=Array(e.arrayArgs.length),r=Array(e.arrayArgs.length);for(var s=0;s<e.arrayArgs.length;++s)r[s]=t[2*s],i[s]=t[2*s+1];var a=[],o=[],c=[],l=[],u=[];for(var s=0;s<e.arrayArgs.length;++s){if(e.arrayBlockIndices[s]<0)c.push(0),l.push(n),a.push(n),o.push(n+e.arrayBlockIndices[s]);else c.push(e.arrayBlockIndices[s]),l.push(e.arrayBlockIndices[s]+n),a.push(0),o.push(e.arrayBlockIndices[s]);var d=[];for(var f=0;f<i[s].length;f++)if(c[s]<=i[s][f]&&i[s][f]<l[s])d.push(i[s][f]-c[s]);u.push(d)}var h=["SS"],b=["'use strict'"],m=[];for(var f=0;f<n;++f)m.push(["s",f,"=SS[",f,"]"].join(""));for(var s=0;s<e.arrayArgs.length;++s){h.push("a"+s),h.push("t"+s),h.push("p"+s);for(var f=0;f<n;++f)m.push(["t",s,"p",f,"=t",s,"[",c[s]+f,"]"].join(""));for(var f=0;f<Math.abs(e.arrayBlockIndices[s]);++f)m.push(["t",s,"b",f,"=t",s,"[",a[s]+f,"]"].join(""))}for(var s=0;s<e.scalarArgs.length;++s)h.push("Y"+s);if(e.shapeArgs.length>0)m.push("shape=SS.slice(0)");if(e.indexArgs.length>0){var g=Array(n);for(var s=0;s<n;++s)g[s]="0";m.push(["index=[",g.join(","),"]"].join(""))}for(var s=0;s<e.offsetArgs.length;++s){var p=e.offsetArgs[s],x=[];for(var f=0;f<p.offset.length;++f)if(p.offset[f]===0)continue;else if(p.offset[f]===1)x.push(["t",p.array,"p",f].join(""));else x.push([p.offset[f],"*t",p.array,"p",f].join(""));if(x.length===0)m.push("q"+s+"=0");else m.push(["q",s,"=",x.join("+")].join(""))}var _=c3([].concat(e.pre.thisVars).concat(e.body.thisVars).concat(e.post.thisVars));if(m=m.concat(_),m.length>0)b.push("var "+m.join(","));for(var s=0;s<e.arrayArgs.length;++s)b.push("p"+s+"|=0");if(e.pre.body.length>3)b.push(Jg(e.pre,e,r));var y=Jg(e.body,e,r),v=u3(u);if(v<n)b.push(l3(v,u[0],e,y));else b.push(XS(u[0],e,y));if(e.post.body.length>3)b.push(Jg(e.post,e,r));if(e.debug)console.log("-----Generated cwise routine for ",t,`:`+b.join(``)+`-----------`);var T=[e.funcName||"unnamed","_cwise_loop_",i[0].join("s"),"m",v,a3(r)].join(""),A=Function(["function ",T,"(",h.join(","),"){",b.join(`-`),"} return ",T].join(""));return A()}$S.exports=o3});var XS=Jr(function($5,WS){var c3=KS();function l3(e){var t=["'use strict'","var CACHED={}"],n=[],i=e.funcName+"_cwise_thunk";t.push(["return function ",i,"(",e.shimArgs.join(","),"){"].join(""));var r=[],s=[],a=[["array",e.arrayArgs[0],".shape.slice(",Math.max(0,e.arrayBlockIndices[0]),e.arrayBlockIndices[0]<0?","+e.arrayBlockIndices[0]+")":")"].join("")],o=[],c=[];for(var l=0;l<e.arrayArgs.length;++l){var u=e.arrayArgs[l];if(n.push(["t",u,"=array",u,".dtype,","r",u,"=array",u,".order"].join("")),r.push("t"+u),r.push("r"+u),s.push("t"+u),s.push("r"+u+".join()"),a.push("array"+u+".data"),a.push("array"+u+".stride"),a.push("array"+u+".offset|0"),l>0)o.push("array"+e.arrayArgs[0]+".shape.length===array"+u+".shape.length+"+(Math.abs(e.arrayBlockIndices[0])-Math.abs(e.arrayBlockIndices[l]))),c.push("array"+e.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,e.arrayBlockIndices[0])+"]===array"+u+".shape[shapeIndex+"+Math.max(0,e.arrayBlockIndices[l])+"]")}if(e.arrayArgs.length>1)t.push("if (!("+o.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),t.push("for(var shapeIndex=array"+e.arrayArgs[0]+".shape.length-"+Math.abs(e.arrayBlockIndices[0])+"; shapeIndex-->0;) {"),t.push("if (!("+c.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),t.push("}");for(var l=0;l<e.scalarArgs.length;++l)a.push("scalar"+e.scalarArgs[l]);if(n.push(["type=[",s.join(","),"].join()"].join("")),n.push("proc=CACHED[type]"),t.push("var "+n.join(",")),t.push(["if(!proc){","CACHED[type]=proc=compile([",r.join(","),"])}","return proc(",a.join(","),")}"].join("")),e.debug)console.log(`-----Generated thunk:+----------`);var E=[e.funcName||"unnamed","_cwise_loop_",i[0].join("s"),"m",v,d3(r)].join(""),w=Function(["function ",E,"(",h.join(","),"){",b.join(`+`),"} return ",E].join(""));return w()}qS.exports=f3});var YS=Jr(function(sK,ZS){var h3=JS();function p3(e){var t=["'use strict'","var CACHED={}"],n=[],i=e.funcName+"_cwise_thunk";t.push(["return function ",i,"(",e.shimArgs.join(","),"){"].join(""));var r=[],s=[],a=[["array",e.arrayArgs[0],".shape.slice(",Math.max(0,e.arrayBlockIndices[0]),e.arrayBlockIndices[0]<0?","+e.arrayBlockIndices[0]+")":")"].join("")],o=[],c=[];for(var l=0;l<e.arrayArgs.length;++l){var u=e.arrayArgs[l];if(n.push(["t",u,"=array",u,".dtype,","r",u,"=array",u,".order"].join("")),r.push("t"+u),r.push("r"+u),s.push("t"+u),s.push("r"+u+".join()"),a.push("array"+u+".data"),a.push("array"+u+".stride"),a.push("array"+u+".offset|0"),l>0)o.push("array"+e.arrayArgs[0]+".shape.length===array"+u+".shape.length+"+(Math.abs(e.arrayBlockIndices[0])-Math.abs(e.arrayBlockIndices[l]))),c.push("array"+e.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,e.arrayBlockIndices[0])+"]===array"+u+".shape[shapeIndex+"+Math.max(0,e.arrayBlockIndices[l])+"]")}if(e.arrayArgs.length>1)t.push("if (!("+o.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),t.push("for(var shapeIndex=array"+e.arrayArgs[0]+".shape.length-"+Math.abs(e.arrayBlockIndices[0])+"; shapeIndex-->0;) {"),t.push("if (!("+c.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),t.push("}");for(var l=0;l<e.scalarArgs.length;++l)a.push("scalar"+e.scalarArgs[l]);if(n.push(["type=[",s.join(","),"].join()"].join("")),n.push("proc=CACHED[type]"),t.push("var "+n.join(",")),t.push(["if(!proc){","CACHED[type]=proc=compile([",r.join(","),"])}","return proc(",a.join(","),")}"].join("")),e.debug)console.log(`-----Generated thunk:`+t.join(``)+`----------`);var d=Function("compile",t.join(`-`));return d(c3.bind(void 0,e))}WS.exports=l3});var JS=Jr(function(K5,qS){var u3=XS();function d3(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function f3(e){var t=new d3;t.pre=e.pre,t.body=e.body,t.post=e.post;var n=e.args.slice(0);t.argTypes=n;for(var i=0;i<n.length;++i){var r=n[i];if(r==="array"||typeof r==="object"&&r.blockIndices){if(t.argTypes[i]="array",t.arrayArgs.push(i),t.arrayBlockIndices.push(r.blockIndices?r.blockIndices:0),t.shimArgs.push("array"+i),i<t.pre.args.length&&t.pre.args[i].count>0)throw Error("cwise: pre() block may not reference array args");if(i<t.post.args.length&&t.post.args[i].count>0)throw Error("cwise: post() block may not reference array args")}else if(r==="scalar")t.scalarArgs.push(i),t.shimArgs.push("scalar"+i);else if(r==="index"){if(t.indexArgs.push(i),i<t.pre.args.length&&t.pre.args[i].count>0)throw Error("cwise: pre() block may not reference array index");if(i<t.body.args.length&&t.body.args[i].lvalue)throw Error("cwise: body() block may not write to array index");if(i<t.post.args.length&&t.post.args[i].count>0)throw Error("cwise: post() block may not reference array index")}else if(r==="shape"){if(t.shapeArgs.push(i),i<t.pre.args.length&&t.pre.args[i].lvalue)throw Error("cwise: pre() block may not write to array shape");if(i<t.body.args.length&&t.body.args[i].lvalue)throw Error("cwise: body() block may not write to array shape");if(i<t.post.args.length&&t.post.args[i].lvalue)throw Error("cwise: post() block may not write to array shape")}else if(typeof r==="object"&&r.offset)t.argTypes[i]="offset",t.offsetArgs.push({array:r.array,offset:r.offset}),t.offsetArgIndex.push(i);else throw Error("cwise: Unknown argument type "+n[i])}if(t.arrayArgs.length<=0)throw Error("cwise: No array arguments specified");if(t.pre.args.length>n.length)throw Error("cwise: Too many arguments in pre() block");if(t.body.args.length>n.length)throw Error("cwise: Too many arguments in body() block");if(t.post.args.length>n.length)throw Error("cwise: Too many arguments in post() block");return t.debug=!!e.printCode||!!e.debug,t.funcName=e.funcName||"cwise",t.blockSize=e.blockSize||64,u3(t)}qS.exports=f3});var iM=Jr(function(an){var Yn=JS(),ff={body:"",args:[],thisVars:[],localVars:[]};function Wg(e){if(!e)return ff;for(var t=0;t<e.args.length;++t){var n=e.args[t];if(t===0)e.args[t]={name:n,lvalue:!0,rvalue:!!e.rvalue,count:e.count||1};else e.args[t]={name:n,lvalue:!1,rvalue:!0,count:1}}if(!e.thisVars)e.thisVars=[];if(!e.localVars)e.localVars=[];return e}function h3(e){return Yn({args:e.args,pre:Wg(e.pre),body:Wg(e.body),post:Wg(e.proc),funcName:e.funcName})}function Yt(e){var t=[];for(var n=0;n<e.args.length;++n)t.push("a"+n);var i=Function("P",["return function ",e.funcName,"_ndarrayops(",t.join(","),") {P(",t.join(","),");return a0}"].join(""));return i(h3(e))}var ZS={add:"+",sub:"-",mul:"*",div:"/",mod:"%",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"};(function(){for(var e in ZS){var t=ZS[e];an[e]=Yt({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+t+"c"},funcName:e}),an[e+"eq"]=Yt({args:["array","array"],body:{args:["a","b"],body:"a"+t+"=b"},rvalue:!0,funcName:e+"eq"}),an[e+"s"]=Yt({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+t+"s"},funcName:e+"s"}),an[e+"seq"]=Yt({args:["array","scalar"],body:{args:["a","s"],body:"a"+t+"=s"},rvalue:!0,funcName:e+"seq"})}})();var YS={not:"!",bnot:"~",neg:"-",recip:"1.0/"};(function(){for(var e in YS){var t=YS[e];an[e]=Yt({args:["array","array"],body:{args:["a","b"],body:"a="+t+"b"},funcName:e}),an[e+"eq"]=Yt({args:["array"],body:{args:["a"],body:"a="+t+"a"},rvalue:!0,count:2,funcName:e+"eq"})}})();var QS={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};(function(){for(var e in QS){var t=QS[e];an[e]=Yt({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+t+"c"},funcName:e}),an[e+"s"]=Yt({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+t+"s"},funcName:e+"s"}),an[e+"eq"]=Yt({args:["array","array"],body:{args:["a","b"],body:"a=a"+t+"b"},rvalue:!0,count:2,funcName:e+"eq"}),an[e+"seq"]=Yt({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+t+"s"},rvalue:!0,count:2,funcName:e+"seq"})}})();var eM=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];(function(){for(var e=0;e<eM.length;++e){var t=eM[e];an[t]=Yt({args:["array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b)",thisVars:["this_f"]},funcName:t}),an[t+"eq"]=Yt({args:["array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a"],body:"a=this_f(a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"eq"})}})();var tM=["max","min","atan2","pow"];(function(){for(var e=0;e<tM.length;++e){var t=tM[e];an[t]=Yt({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:t}),an[t+"s"]=Yt({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:t+"s"}),an[t+"eq"]=Yt({args:["array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"eq"}),an[t+"seq"]=Yt({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"seq"})}})();var nM=["atan2","pow"];(function(){for(var e=0;e<nM.length;++e){var t=nM[e];an[t+"op"]=Yt({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:t+"op"}),an[t+"ops"]=Yt({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:t+"ops"}),an[t+"opeq"]=Yt({args:["array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"opeq"}),an[t+"opseq"]=Yt({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"opseq"})}})();an.any=Yn({args:["array"],pre:ff,body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"if(a){return true}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return false"},funcName:"any"});an.all=Yn({args:["array"],pre:ff,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1}],body:"if(!x){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"all"});an.sum=Yn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s+=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"sum"});an.prod=Yn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=1"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s*=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"prod"});an.norm2squared=Yn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm2squared"});an.norm2=Yn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return Math.sqrt(this_s)"},funcName:"norm2"});an.norminf=Yn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:4}],body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"});an.norm1=Yn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"});an.sup=Yn({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}});an.inf=Yn({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}});an.argmin=Yn({args:["index","array","shape"],pre:{body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}});an.argmax=Yn({args:["index","array","shape"],pre:{body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}});an.random=Yt({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"});an.assign=Yt({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"});an.assigns=Yt({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"});an.equals=Yn({args:["array","array"],pre:ff,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})});function N3(e,t){if(!(e instanceof Uint8Array))throw Error("[ndarray-pixels] Input must be Uint8Array or Buffer.");let n=new Blob([e],{type:t});return createImageBitmap(n,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then((i)=>{let r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);let s=r.getImageData(0,0,i.width,i.height);return rM.default(new Uint8Array(s.data),[i.width,i.height,4],[4,4*i.width,1],0)})}async function sM(e,t){return N3(e,t)}var rM,C3;var aM=mt(()=>{rM=kf($g(),1),C3=kf(iM(),1)});function vf(e,t){return Object.defineProperty(t,"name",{value:e}),t}function Ef(e,t){let n={...e};for(let i in t)if(t[i]!==void 0)n[i]=t[i];return n}function EM(e){let t=[];for(let n of e.listAttributes())t.push(n);for(let n of e.listTargets())for(let i of n.listAttributes())t.push(i);return Array.from(new Set(t))}function O3(e,t){if(e==null&&t==null)return!0;if(e==null||t==null)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function gf(e,t){return e.createAccessor(t.getName()).setArray(t.getArray()).setType(t.getType()).setBuffer(t.getBuffer()).setNormalized(t.getNormalized()).setSparse(t.getSparse())}function k3(e,t=e){let n=TM(e,t);for(let i=0;i<n.length;i++)n[i]=i;return n}function TM(e,t=e){return t<=65534?new Uint16Array(e):new Uint32Array(e)}function AM(e){for(let t in e)return!1;return!0}function D3(e,t){var n=t[0],i=t[1],r=t[2],s=t[3],a=t[4],o=t[5],c=t[6],l=t[7],u=t[8],d=t[9],f=t[10],h=t[11],b=t[12],m=t[13],g=t[14],p=t[15],x=n*o-i*a,_=n*c-r*a,y=n*l-s*a,v=i*c-r*o,T=i*l-s*o,A=r*l-s*c,E=u*m-d*b,w=u*g-f*b,P=u*p-h*b,S=d*g-f*m,I=d*p-h*m,U=f*p-h*g,N=x*U-_*I+y*S+v*P-T*w+A*E;if(!N)return null;return N=1/N,e[0]=(o*U-c*I+l*S)*N,e[1]=(r*I-i*U-s*S)*N,e[2]=(m*A-g*T+p*v)*N,e[3]=(f*T-d*A-h*v)*N,e[4]=(c*P-a*U-l*w)*N,e[5]=(n*U-r*P+s*w)*N,e[6]=(g*y-b*A-p*_)*N,e[7]=(u*A-f*y+h*_)*N,e[8]=(a*I-o*P+l*E)*N,e[9]=(i*P-n*I-s*E)*N,e[10]=(b*T-m*y+p*x)*N,e[11]=(d*y-u*T-h*x)*N,e[12]=(o*w-a*S-c*E)*N,e[13]=(n*S-i*w+r*E)*N,e[14]=(m*_-b*v-g*x)*N,e[15]=(u*v-d*_+f*x)*N,e}function eb(e,t,n){var i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],c=t[5],l=t[6],u=t[7],d=t[8],f=t[9],h=t[10],b=t[11],m=t[12],g=t[13],p=t[14],x=t[15],_=n[0],y=n[1],v=n[2],T=n[3];return e[0]=_*i+y*o+v*d+T*m,e[1]=_*r+y*c+v*f+T*g,e[2]=_*s+y*l+v*h+T*p,e[3]=_*a+y*u+v*b+T*x,_=n[4],y=n[5],v=n[6],T=n[7],e[4]=_*i+y*o+v*d+T*m,e[5]=_*r+y*c+v*f+T*g,e[6]=_*s+y*l+v*h+T*p,e[7]=_*a+y*u+v*b+T*x,_=n[8],y=n[9],v=n[10],T=n[11],e[8]=_*i+y*o+v*d+T*m,e[9]=_*r+y*c+v*f+T*g,e[10]=_*s+y*l+v*h+T*p,e[11]=_*a+y*u+v*b+T*x,_=n[12],y=n[13],v=n[14],T=n[15],e[12]=_*i+y*o+v*d+T*m,e[13]=_*r+y*c+v*f+T*g,e[14]=_*s+y*l+v*h+T*p,e[15]=_*a+y*u+v*b+T*x,e}function L3(e,t){return e[0]=t[0],e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=t[1],e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=t[2],e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function F3(e,t,n,i){var r=t[0],s=t[1],a=t[2],o=t[3],c=r+r,l=s+s,u=a+a,d=r*c,f=r*l,h=r*u,b=s*l,m=s*u,g=a*u,p=o*c,x=o*l,_=o*u,y=i[0],v=i[1],T=i[2];return e[0]=(1-(b+g))*y,e[1]=(f+_)*y,e[2]=(h-x)*y,e[3]=0,e[4]=(f-_)*v,e[5]=(1-(d+g))*v,e[6]=(m+p)*v,e[7]=0,e[8]=(h+x)*T,e[9]=(m-p)*T,e[10]=(1-(d+b))*T,e[11]=0,e[12]=n[0],e[13]=n[1],e[14]=n[2],e[15]=1,e}function xf(e,t){let n=e.getAttribute("POSITION"),i=e.getIndices();if(!n)return 0;switch(t){case"render":return i?i.getCount():n.getCount();case"render-cached":return i?new Set(i.getArray()).size:n.getCount();case"upload-naive":case"upload":return n.getCount();case"distinct":case"distinct-position":return U3(t);case"unused":return i?n.getCount()-new Set(i.getArray()).size:0;default:return B3(t)}}function U3(e){throw Error(`Not implemented: ${e}`)}function B3(e){throw Error(`Unexpected value: ${e}`)}function z3(e,t,n){let i=rf.fromGraph(e.getGraph());if(!t||!n)[t,n]=V3(e);let r=e.getIndices(),s=r?r.getArray():null,a=xf(e,"render"),o=i.createAccessor(),c=a,l=TM(c,n);for(let d=0;d<c;d++)l[d]=t[s?s[d]:d];e.setIndices(o.setArray(l));let u=EM(e);for(let d of e.listAttributes()){let f=gf(i,d);Jg(d,r,t,f,n),e.swap(d,f)}for(let d of e.listTargets())for(let f of d.listAttributes()){let h=gf(i,f);Jg(f,r,t,h,n),d.swap(f,h)}if(r&&r.listParents().length===1)r.dispose();for(let d of u)if(d.listParents().length===1)d.dispose();return e}function Jg(e,t,n,i,r){let s=e.getElementSize(),a=e.getArray(),o=t?t.getArray():null,c=t?t.getCount():e.getCount(),l=new a.constructor(r*s),u=new Uint8Array(r);for(let d=0;d<c;d++){let f=o?o[d]:d,h=n[f];if(u[h])continue;for(let b=0;b<s;b++)l[h*s+b]=a[f*s+b];u[h]=1}return i.setArray(l)}function V3(e){let t=xf(e,"upload"),n=e.getIndices(),i=n?n.getArray():null;if(!n||!i)return[k3(t,1e6),t];let r=new Uint32Array(t).fill(oM),s=0;for(let a=0;a<i.length;a++){let o=i[a];if(r[o]===oM)r[o]=s++}return[r,s]}function j3(){var e=new bf(3);if(bf!=Float32Array)e[0]=0,e[1]=0,e[2]=0;return e}function H3(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e[2]=t[2]*n[2],e}function Zg(e,t,n){return e[0]=Math.min(t[0],n[0]),e[1]=Math.min(t[1],n[1]),e[2]=Math.min(t[2],n[2]),e}function Yg(e,t,n){return e[0]=Math.max(t[0],n[0]),e[1]=Math.max(t[1],n[1]),e[2]=Math.max(t[2],n[2]),e}function cM(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e}function G3(e,t,n){var i=t[0],r=t[1],s=t[2],a=n[3]*i+n[7]*r+n[11]*s+n[15];return a=a||1,e[0]=(n[0]*i+n[4]*r+n[8]*s+n[12])/a,e[1]=(n[1]*i+n[5]*r+n[9]*s+n[13])/a,e[2]=(n[2]*i+n[6]*r+n[10]*s+n[14])/a,e}function tb(e=qg){let t=Ef(qg,e),n=new Set(t.propertyTypes);for(let i of t.propertyTypes)if(!qg.propertyTypes.includes(i))throw Error(`${qs}: Unsupported deduplication on type "${i}".`);return vf(qs,(i)=>{let r=i.getLogger();if(n.has(te.ACCESSOR))K3(i);if(n.has(te.TEXTURE))X3(i,t);if(n.has(te.MATERIAL))q3(i,t);if(n.has(te.MESH))W3(i,t);if(n.has(te.SKIN))J3(i,t);r.debug(`${qs}: Complete.`)})}function K3(e){let t=e.getLogger(),n=new Map,i=new Map,r=new Map,s=new Map,a=e.getRoot().listMeshes();a.forEach((d)=>{d.listPrimitives().forEach((f)=>{f.listAttributes().forEach((h)=>o(h,i)),o(f.getIndices(),n)})});for(let d of e.getRoot().listAnimations())for(let f of d.listSamplers())o(f.getInput(),r),o(f.getOutput(),s);function o(d,f){if(!d)return;let h=[d.getCount(),d.getType(),d.getComponentType(),d.getNormalized(),d.getSparse()].join(":"),b=f.get(h);if(!b)f.set(h,b=new Set);b.add(d)}function c(d,f){for(let h=0;h<d.length;h++){let b=d[h],m=Je.toView(b.getArray());if(f.has(b))continue;for(let g=h+1;g<d.length;g++){let p=d[g];if(f.has(p))continue;if(Je.equals(m,Je.toView(p.getArray())))f.set(p,b)}}}let l=0,u=new Map;for(let d of[i,n,r,s])for(let f of d.values())l+=f.size,c(Array.from(f),u);t.debug(`${qs}: Merged ${u.size} of ${l} accessors.`),a.forEach((d)=>{d.listPrimitives().forEach((f)=>{f.listAttributes().forEach((b)=>{if(u.has(b))f.swap(b,u.get(b))});let h=f.getIndices();if(h&&u.has(h))f.swap(h,u.get(h))})});for(let d of e.getRoot().listAnimations())for(let f of d.listSamplers()){let h=f.getInput(),b=f.getOutput();if(h&&u.has(h))f.swap(h,u.get(h));if(b&&u.has(b))f.swap(b,u.get(b))}Array.from(u.keys()).forEach((d)=>d.dispose())}function W3(e,t){let n=e.getLogger(),i=e.getRoot(),r=new Map;i.listAccessors().forEach((o,c)=>r.set(o,c)),i.listMaterials().forEach((o,c)=>r.set(o,c));let s=i.listMeshes().length,a=new Map;for(let o of i.listMeshes()){let c=[];for(let u of o.listPrimitives())c.push(wM(u,r));let l="";if(t.keepUniqueNames)l+=o.getName()+";";if(l+=c.join(";"),a.has(l)){let u=a.get(l);o.listParents().forEach((d)=>{if(d.propertyType!==te.ROOT)d.swap(o,u)}),o.dispose()}else a.set(l,o)}n.debug(`${qs}: Merged ${s-a.size} of ${s} meshes.`)}function X3(e,t){let n=e.getLogger(),i=e.getRoot(),r=i.listTextures(),s=new Map;for(let a=0;a<r.length;a++){let o=r[a],c=o.getImage();if(s.has(o))continue;for(let l=a+1;l<r.length;l++){let u=r[l],d=u.getImage();if(s.has(u))continue;if(o.getMimeType()!==u.getMimeType())continue;if(t.keepUniqueNames&&o.getName()!==u.getName())continue;let f=o.getSize(),h=u.getSize();if(!f||!h)continue;if(f[0]!==h[0])continue;if(f[1]!==h[1])continue;if(!c||!d)continue;if(Je.equals(c,d))s.set(u,o)}}n.debug(`${qs}: Merged ${s.size} of ${i.listTextures().length} textures.`),Array.from(s.entries()).forEach(([a,o])=>{a.listParents().forEach((c)=>{if(!(c instanceof Ps))c.swap(a,o)}),a.dispose()})}function q3(e,t){let n=e.getLogger(),i=e.getRoot().listMaterials(),r=new Map,s=new Map,a=new Set;if(!t.keepUniqueNames)a.add("name");for(let o=0;o<i.length;o++){let c=i[o];if(r.has(c))continue;if(lM(c,s))continue;for(let l=o+1;l<i.length;l++){let u=i[l];if(r.has(u))continue;if(lM(u,s))continue;if(c.equals(u,a))r.set(u,c)}}n.debug(`${qs}: Merged ${r.size} of ${i.length} materials.`),Array.from(r.entries()).forEach(([o,c])=>{o.listParents().forEach((l)=>{if(!(l instanceof Ps))l.swap(o,c)}),o.dispose()})}function J3(e,t){let n=e.getLogger(),i=e.getRoot().listSkins(),r=new Map,s=new Set(["joints"]);if(!t.keepUniqueNames)s.add("name");for(let a=0;a<i.length;a++){let o=i[a];if(r.has(o))continue;for(let c=a+1;c<i.length;c++){let l=i[c];if(r.has(l))continue;if(o.equals(l,s)&&O3(o.listJoints(),l.listJoints()))r.set(l,o)}}n.debug(`${qs}: Merged ${r.size} of ${i.length} skins.`),Array.from(r.entries()).forEach(([a,o])=>{a.listParents().forEach((c)=>{if(!(c instanceof Ps))c.swap(a,o)}),a.dispose()})}function wM(e,t){let n=[];for(let i of e.listSemantics()){let r=e.getAttribute(i);n.push(i+":"+t.get(r))}if(e instanceof Jn){let i=e.getIndices();if(i)n.push("indices:"+t.get(i));let r=e.getMaterial();if(r)n.push("material:"+t.get(r));n.push("mode:"+e.getMode());for(let s of e.listTargets())n.push("target:"+wM(s,t))}return n.join(",")}function lM(e,t){if(t.has(e))return t.get(e);let n=e.getGraph(),i=new Set,r=n.listParentEdges(e);while(r.length>0){let s=r.pop();if(s.getAttributes().modifyChild===!0)return t.set(e,!0),!0;let a=s.getChild();if(i.has(a))continue;for(let o of n.listChildEdges(a))r.push(o)}return t.set(e,!1),!1}function SM(){var e=new bf(4);if(bf!=Float32Array)e[0]=0,e[1]=0,e[2]=0,e[3]=0;return e}function Z3(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e[3]=t[3]+n[3],e}function Y3(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e[2]=t[2]-n[2],e[3]=t[3]-n[3],e}function Q3(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e[2]=t[2]*n[2],e[3]=t[3]*n[3],e}function e9(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e}function t9(e){var t=e[0],n=e[1],i=e[2],r=e[3];return Math.sqrt(t*t+n*n+i*i+r*r)}function r9(e){return e.getGraph().listParentEdges(e).some((t)=>t.getAttributes().isColor||i9.test(t.getName()))?"srgb":null}function s9(e){let t=e.getGraph(),n=new Set,i=new Set;function r(s){let a=new Set;for(let o of t.listChildEdges(s))if(o.getChild()instanceof Xo)a.add(o.getName()+"Info");for(let o of t.listChildEdges(s)){let c=o.getChild();if(n.has(c))continue;if(n.add(c),c instanceof wt&&a.has(o.getName()))i.add(c);else if(c instanceof nt)r(c)}}return r(e),Array.from(i)}function a9(e){let t=rf.fromGraph(e.getGraph()).getRoot(),n=e.getGraph().listParentEdges(e).filter((i)=>i.getParent()!==t).map((i)=>i.getName());return Array.from(new Set(n))}function IM(e=uM){let t=Ef(uM,e),n=new Set(t.propertyTypes),i=t.keepExtras;return vf(Zo,async(r)=>{let s=r.getLogger(),a=r.getRoot(),o=r.getGraph(),c=new o9,l=(u)=>c.dispose(u.target);if(o.addEventListener("node:dispose",l),n.has(te.MESH))for(let u of a.listMeshes()){if(u.listPrimitives().length>0)continue;u.dispose()}if(n.has(te.NODE)){if(!t.keepLeaves)for(let u of a.listScenes())CM(o,u,i);for(let u of a.listNodes())Si(u,i)}if(n.has(te.SKIN))for(let u of a.listSkins())Si(u,i);if(n.has(te.MESH))for(let u of a.listMeshes())Si(u,i);if(n.has(te.CAMERA))for(let u of a.listCameras())Si(u,i);if(n.has(te.PRIMITIVE))dM(o,te.PRIMITIVE,i);if(n.has(te.PRIMITIVE_TARGET))dM(o,te.PRIMITIVE_TARGET,i);if(!t.keepAttributes&&n.has(te.ACCESSOR)){let u=new Map;for(let d of a.listMeshes())for(let f of d.listPrimitives()){let h=f.getMaterial();if(!h)continue;let b=c9(f,NM(r,f,h));fM(f,b),f.listTargets().forEach((m)=>fM(m,b)),u.has(h)?u.get(h).add(f):u.set(h,new Set([f]))}for(let[d,f]of u)l9(d,Array.from(f))}if(n.has(te.ANIMATION))for(let u of a.listAnimations()){for(let d of u.listChannels())if(!d.getTargetNode())d.dispose();if(!u.listChannels().length){let d=u.listSamplers();Si(u,i),d.forEach((f)=>Si(f,i))}else u.listSamplers().forEach((d)=>Si(d,i))}if(n.has(te.MATERIAL))a.listMaterials().forEach((u)=>Si(u,i));if(n.has(te.TEXTURE)){if(a.listTextures().forEach((u)=>Si(u,i)),!t.keepSolidTextures)await u9(r)}if(n.has(te.ACCESSOR))a.listAccessors().forEach((u)=>Si(u,i));if(n.has(te.BUFFER))a.listBuffers().forEach((u)=>Si(u,i));if(o.removeEventListener("node:dispose",l),!c.empty()){let u=c.entries().map(([d,f])=>`${d} (${f})`).join(", ");s.info(`${Zo}: Removed types... ${u}`)}else s.debug(`${Zo}: No unused properties found.`);s.debug(`${Zo}: Complete.`)})}function Si(e,t){let n=e.listParents().filter((r)=>!(r instanceof Ps||r instanceof Da)),i=t&&!AM(e.getExtras());if(!n.length&&!i)e.dispose()}function dM(e,t,n){for(let i of e.listEdges()){let r=i.getParent();if(r.propertyType===t)Si(r,n)}}function CM(e,t,n){if(t.listChildren().forEach((a)=>CM(e,a,n)),t instanceof nf)return;let i=e.listParentEdges(t).some((a)=>{let o=a.getParent().propertyType;return o!==te.ROOT&&o!==te.SCENE&&o!==te.NODE}),r=e.listChildren(t).length===0,s=n&&!AM(t.getExtras());if(r&&!i&&!s)t.dispose()}function fM(e,t){for(let n of t)e.setAttribute(n,null)}function c9(e,t){let n=[];for(let i of e.listSemantics())if(i==="NORMAL"&&!t.has(i))n.push(i);else if(i==="TANGENT"&&!t.has(i))n.push(i);else if(i.startsWith("TEXCOORD_")&&!t.has(i))n.push(i);else if(i.startsWith("COLOR_")&&i!=="COLOR_0")n.push(i);return n}function NM(e,t,n,i=new Set){let r=e.getGraph().listChildEdges(n),s=new Set;for(let c of r)if(c.getChild()instanceof Xo)s.add(c.getName());for(let c of r){let l=c.getName(),u=c.getChild();if(u instanceof wt){if(s.has(l.replace(/Info$/,"")))i.add(`TEXCOORD_${u.getTexCoord()}`)}if(u instanceof Xo&&l.match(/normalTexture/i))i.add("TANGENT");if(u instanceof nt)NM(e,t,u,i)}let a=n instanceof Oa&&!n.getExtension("KHR_materials_unlit"),o=t.getMode()===Jn.Mode.POINTS;if(a&&!o)i.add("NORMAL");return i}function l9(e,t){let n=s9(e),i=new Set(n.map((c)=>c.getTexCoord())),r=Array.from(i).sort(),s=new Map(r.map((c,l)=>[c,l])),a=new Map(r.map((c,l)=>[`TEXCOORD_${c}`,`TEXCOORD_${l}`]));for(let c of n){let l=c.getTexCoord();c.setTexCoord(s.get(l))}for(let c of t){let l=c.listSemantics().filter((u)=>u.startsWith("TEXCOORD_")).sort();o(c,l),c.listTargets().forEach((u)=>o(u,l))}function o(c,l){for(let u of l){let d=c.getAttribute(u);if(!d)continue;let f=a.get(u);if(f===u)continue;c.setAttribute(f,d),c.setAttribute(u,null)}}}async function u9(e){let t=e.getRoot(),n=e.getGraph(),i=e.getLogger(),r=t.listTextures().map(async(s)=>{let a=await f9(s);if(!a)return;if(r9(s)==="srgb")Vw.convertSRGBToLinear(a,a);let o=s.getName()||s.getURI(),c=s.getSize()?.join("x"),l=a9(s);for(let u of n.listParentEdges(s)){let d=u.getParent();if(d!==t&&d9(d,a,u.getName(),i))u.dispose()}if(s.listParents().length===1)s.dispose(),i.debug(`${Zo}: Removed solid-color texture "${o}" (${c}px ${l.join(", ")})`)});await Promise.all(r)}function d9(e,t,n,i){if(e instanceof Oa)switch(n){case"baseColorTexture":return e.setBaseColorFactor(n9(t,t,e.getBaseColorFactor())),!0;case"emissiveTexture":return e.setEmissiveFactor($3([0,0,0],t.slice(0,3),e.getEmissiveFactor())),!0;case"occlusionTexture":return Math.abs(t[0]-1)<=Qg;case"metallicRoughnessTexture":return e.setRoughnessFactor(t[1]*e.getRoughnessFactor()),e.setMetallicFactor(t[2]*e.getMetallicFactor()),!0;case"normalTexture":return RM(MM(SM(),t,[0.5,0.5,1,1]))<=Qg}return i.warn(`${Zo}: Detected single-color ${n} texture. Pruning ${n} not yet supported.`),!1}async function f9(e){let t=await h9(e);if(!t)return null;let n=[1/0,1/0,1/0,1/0],i=[-1/0,-1/0,-1/0,-1/0],r=[0,0,0,0],[s,a]=t.shape;for(let o=0;o<s;o++){for(let c=0;c<a;c++)for(let l=0;l<4;l++)n[l]=Math.min(n[l],t.get(o,c,l)),i[l]=Math.max(i[l],t.get(o,c,l));if(RM(MM(r,i,n))/255>Qg)return null}return e9(r,Z3(r,i,n),0.00196078431372549)}async function h9(e){try{return await sM(e.getImage(),e.getMimeType())}catch{return null}}function p9(e,t=1/0){if(Number.isFinite(t)&&t%4||t<=0)throw Error("Limit must be positive multiple of four.");let n=e.getAttribute("POSITION").getCount(),i=e.listSemantics().filter((l)=>l.startsWith("WEIGHTS_")).length,r=new Uint16Array(i*4),s=new Float32Array(i*4),a=new Float32Array(i*4),o=new Uint32Array(i*4),c=new Uint32Array(i*4);for(let l=0;l<n;l++){yf(e,l,"WEIGHTS",s),yf(e,l,"JOINTS",o);for(let u=0;u<i*4;u++)r[u]=u;r.sort((u,d)=>s[u]>s[d]?-1:1);for(let u=0;u<r.length;u++)a[u]=s[r[u]],c[u]=o[r[u]];_f(e,l,"WEIGHTS",a),_f(e,l,"JOINTS",c)}for(let l=i;l*4>t;l--){let u=e.getAttribute(`WEIGHTS_${l-1}`),d=e.getAttribute(`JOINTS_${l-1}`);if(e.setAttribute(`WEIGHTS_${l-1}`,null),e.setAttribute(`JOINTS_${l-1}`,null),u.listParents().length===1)u.dispose();if(d.listParents().length===1)d.dispose()}m9(e)}function m9(e){if(!g9(e))return;let t=e.getAttribute("POSITION").getCount(),n=e.listSemantics().filter((d)=>d.startsWith("WEIGHTS_")).length,i=e.getAttribute("WEIGHTS_0"),r=i.getArray(),s=i.getComponentType(),a=i.getNormalized(),o=a?s:void 0,c=a?pt.decodeNormalizedInt(1,s):Number.EPSILON,l=new Uint32Array(n*4).fill(0),u=r.slice(0,n*4).fill(0);for(let d=0;d<t;d++){yf(e,d,"JOINTS",l),yf(e,d,"WEIGHTS",u,o);let f=hM(u,o);if(f!==0&&f!==1){if(Math.abs(1-f)>c)for(let h=0;h<u.length;h++)if(a){let b=pt.decodeNormalizedInt(u[h],s);u[h]=pt.encodeNormalizedInt(b/f,s)}else u[h]/=f;if(f=hM(u,o),a&&f!==1){for(let h=u.length-1;h>=0;h--)if(u[h]>0){let b=1-f;u[h]+=Math.sign(b)*pt.encodeNormalizedInt(Math.abs(b),s);break}}}for(let h=u.length-1;h>=0;h--)if(u[h]===0)l[h]=0;_f(e,d,"JOINTS",l),_f(e,d,"WEIGHTS",u,o)}}function yf(e,t,n,i,r){let s,a=[0,0,0,0];for(let o=0;s=e.getAttribute(`${n}_${o}`);o++){s.getElement(t,a);for(let c=0;c<4;c++)if(r)i[o*4+c]=pt.encodeNormalizedInt(a[c],r);else i[o*4+c]=a[c]}return i}function _f(e,t,n,i,r){let s,a=[0,0,0,0];for(let o=0;s=e.getAttribute(`${n}_${o}`);o++){for(let c=0;c<4;c++)if(r)a[c]=pt.decodeNormalizedInt(i[o*4+c],r);else a[c]=i[o*4+c];s.setElement(t,a)}}function hM(e,t){let n=0;for(let i=0;i<e.length;i++)if(t)n+=pt.decodeNormalizedInt(e[i],t);else n+=e[i];return n}function g9(e){let t=e.listSemantics().filter((r)=>r.startsWith("WEIGHTS_")).map((r)=>e.getAttribute(r)),n=t.map((r)=>r.getNormalized()),i=t.map((r)=>r.getComponentType());return new Set(n).size===1&&new Set(i).size===1}function PM(e=mf){let t=Ef(mf,{patternTargets:e.pattern||mf.pattern,...e});return vf(Xs,async(n)=>{let i=n.getLogger(),r=n.getRoot();if(n.hasExtension("KHR_mesh_primitive_restart"))throw Error("quantize: Missing support for KHR_mesh_primitive_restart.");let s;if(t.quantizationVolume==="scene")s=mM(C9(r.listMeshes().map(gM)));for(let a of n.getRoot().listMeshes()){if(t.quantizationVolume==="mesh")s=mM(gM(a));if(s&&t.pattern.test("POSITION"))T9(n,a,s),S9(a,1/s.scale);for(let o of a.listPrimitives()){if(xf(o,"render")<xf(o,"upload")/2)z3(o);pM(n,o,s,t);for(let c of o.listTargets())pM(n,c,s,t)}}if(r.listMeshes().flatMap((a)=>a.listPrimitives()).some(OM))n.createExtension(Hg).setRequired(!0);if(t.cleanup)await n.transform(IM({propertyTypes:[te.ACCESSOR,te.SKIN,te.MATERIAL],keepAttributes:!0,keepIndices:!0,keepLeaves:!0,keepSolidTextures:!0}),tb({propertyTypes:[te.ACCESSOR,te.MATERIAL,te.SKIN],keepUniqueNames:!0}));i.debug(`${Xs}: Complete.`)})}function pM(e,t,n,i){let r=t instanceof Lg,s=e.getLogger();for(let a of t.listSemantics()){if(!r&&!i.pattern.test(a))continue;if(r&&!i.patternTargets.test(a))continue;let o=t.getAttribute(a),{bits:c,ctor:l}=R9(a,o,s,i);if(!l)continue;if(c<8||c>16)throw Error(`${Xs}: Requires bits = 8–16.`);if(o.getComponentSize()<=c/8)continue;let u=o.clone();if(a==="POSITION"){let d=n.scale,f=[];t instanceof Jn?D3(f,Tf(n)):L3(f,[1/d,1/d,1/d]);for(let h=0,b=[0,0,0],m=u.getCount();h<m;h++)u.getElement(h,b),u.setElement(h,G3(b,b,f))}M9(u,l,c),t.setAttribute(a,u)}if(i.normalizeWeights&&t.getAttribute("WEIGHTS_0"))p9(t,1/0);if(t instanceof Jn&&t.getIndices()&&t.listAttributes().length&&t.listAttributes()[0].getCount()<65535){let a=t.getIndices();a.setArray(new Uint16Array(a.getArray()))}}function mM(e){let{min:t,max:n}=e,i=Math.max((n[0]-t[0])/2,(n[1]-t[1])/2,(n[2]-t[2])/2);return{offset:[t[0]+(n[0]-t[0])/2,t[1]+(n[1]-t[1])/2,t[2]+(n[2]-t[2])/2],scale:i}}function T9(e,t,n){let i=Tf(n);for(let r of t.listParents()){if(!(r instanceof tf))continue;let s=r.listParents().filter((f)=>f instanceof Da),a=s.some((f)=>E9.includes(f.getTargetPath())),o=r.listChildren().length>0,c=r.getSkin();if(c){r.setSkin(A9(c,n));continue}let l=r.getExtension("EXT_mesh_gpu_instancing");if(l){r.setExtension("EXT_mesh_gpu_instancing",w9(e,l,n));continue}let u;if(o||a)u=e.createNode("").setMesh(t),r.addChild(u).setMesh(null),s.filter((f)=>f.getTargetPath()===v9).forEach((f)=>f.setTargetNode(u));else u=r;let d=u.getMatrix();eb(d,d,i),u.setMatrix(d)}}function A9(e,t){e=e.clone();let n=Tf(t),i=e.getInverseBindMatrices().clone(),r=[];for(let s=0,a=i.getCount();s<a;s++)i.getElement(s,r),eb(r,r,n),i.setElement(s,r);return e.setInverseBindMatrices(i)}function w9(e,t,n){if(!t.getAttribute("TRANSLATION")&&!t.getAttribute("ROTATION")&&!t.getAttribute("SCALE"))return t;t=t.clone();let i=t.getAttribute("TRANSLATION")?.clone(),r=t.getAttribute("ROTATION")?.clone(),s=t.getAttribute("SCALE")?.clone(),a=i||r||s,o=[0,0,0],c=[0,0,0,1],l=[1,1,1];if(!i&&n.offset)i=e.createAccessor().setType("VEC3").setArray(xM(a.getCount(),o));if(!s&&n.scale)s=e.createAccessor().setType("VEC3").setArray(xM(a.getCount(),l));let u=[0,0,0],d=[0,0,0,1],f=[1,1,1],h=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],b=Tf(n);for(let m=0,g=a.getCount();m<g;m++){if(pt.compose(i?i.getElement(m,u):o,r?r.getElement(m,d):c,s?s.getElement(m,f):l,h),eb(h,h,b),pt.decompose(h,u,d,f),i)i.setElement(m,u);if(r)r.setElement(m,d);if(s)s.setElement(m,f)}if(i)t.setAttribute("TRANSLATION",i);if(r)t.setAttribute("ROTATION",r);if(s)t.setAttribute("SCALE",s);return t}function S9(e,t){for(let n of e.listPrimitives()){let i=n.getMaterial();if(!i)continue;let r=i.getExtension("KHR_materials_volume");if(!r||r.getThicknessFactor()<=0)continue;r=r.clone().setThicknessFactor(r.getThicknessFactor()*t),i=i.clone().setExtension("KHR_materials_volume",r),n.setMaterial(i)}}function M9(e,t,n){let i=new t(e.getArray().length),r=b9.includes(t)?1:0,s=n-r,a=t.BYTES_PER_ELEMENT*8-r,o=Math.pow(2,s)-1,c=a-s,l=2*s-a,u=[r>0?-1:0,1];for(let d=0,f=0,h=[];d<e.getCount();d++){e.getElement(d,h);for(let b=0;b<h.length;b++){let m=N9(h[b],u);m=Math.round(Math.abs(m)*o),m=m<<c|m>>l,i[f++]=m*Math.sign(h[b])}}e.setArray(i).setNormalized(!0).setSparse(!1)}function R9(e,t,n,i){let r=t.getMinNormalized([]),s=t.getMaxNormalized([]),a,o;if(e==="POSITION")a=i.quantizePosition,o=a<=8?Int8Array:Int16Array;else if(e==="NORMAL"||e==="TANGENT")a=i.quantizeNormal,o=a<=8?Int8Array:Int16Array;else if(e.startsWith("COLOR_"))a=i.quantizeColor,o=a<=8?Uint8Array:Uint16Array;else if(e.startsWith("TEXCOORD_")){if(r.some((c)=>c<0)||s.some((c)=>c>1))return n.warn(`${Xs}: Skipping ${e}; out of [0,1] range.`),{bits:-1};a=i.quantizeTexcoord,o=a<=8?Uint8Array:Uint16Array}else if(e.startsWith("JOINTS_")){if(a=Math.max(...t.getMax([]))<=255?8:16,o=a<=8?Uint8Array:Uint16Array,t.getComponentSize()>a/8)t.setArray(new o(t.getArray()));return{bits:-1}}else if(e.startsWith("WEIGHTS_")){if(r.some((c)=>c<0)||s.some((c)=>c>1))return n.warn(`${Xs}: Skipping ${e}; out of [0,1] range.`),{bits:-1};a=i.quantizeWeight,o=a<=8?Uint8Array:Uint16Array}else if(e.startsWith("_")){if(r.some((c)=>c<-1)||s.some((c)=>c>1))return n.warn(`${Xs}: Skipping ${e}; out of [-1,1] range.`),{bits:-1};a=i.quantizeGeneric,o=r.some((c)=>c<0)?o=a<=8?Int8Array:Int16Array:o=a<=8?Uint8Array:Uint16Array}else throw Error(`${Xs}: Unexpected semantic, "${e}".`);return{bits:a,ctor:o}}function gM(e){let t=[],n=[];for(let r of e.listPrimitives()){let s=r.getAttribute("POSITION");if(s)t.push(s);for(let a of r.listTargets()){let o=a.getAttribute("POSITION");if(o)n.push(o)}}if(t.length===0)throw Error(`${Xs}: Missing "POSITION" attribute.`);let i=bM(t,3);if(n.length>0){let{min:r,max:s}=bM(n,3);Zg(i.min,i.min,Zg(r,cM(r,r,2),[0,0,0])),Yg(i.max,i.max,Yg(s,cM(s,s,2),[0,0,0]))}return i}function I9(e,t){let n=t.getComponentSize();if(e==="POSITION")return n<4;if(e==="NORMAL")return n<4;if(e==="TANGENT")return n<4;if(e.startsWith("TEXCOORD_")){let i=t.getComponentType(),r=t.getNormalized();return n<4&&!(r&&i===Be.ComponentType.UNSIGNED_BYTE)&&!(r&&i===Be.ComponentType.UNSIGNED_SHORT)}return!1}function OM(e){for(let t of e.listSemantics())if(I9(t,e.getAttribute("POSITION")))return!0;if(e.propertyType===te.PRIMITIVE)return e.listTargets().some(OM);return!1}function bM(e,t){let n=Array(t).fill(1/0),i=Array(t).fill(-1/0),r=[],s=[];for(let a of e){a.getMinNormalized(r),a.getMaxNormalized(s);for(let o=0;o<t;o++)n[o]=Math.min(n[o],r[o]),i[o]=Math.max(i[o],s[o])}return{min:n,max:i}}function C9(e){let t=e[0];for(let n of e)Zg(t.min,t.min,n.min),Yg(t.max,t.max,n.max);return t}function Tf(e){return F3([],[0,0,0,1],e.offset,[e.scale,e.scale,e.scale])}function N9(e,t){return Math.min(Math.max(e,t[0]),t[1])}function xM(e,t){let n=t.length,i=new Float32Array(e*n);for(let r=0;r<e;r++)i.set(t,r*n);return i}function kM(e){let t=Ef(P9,e),n=t.encoder;if(!n)throw Error(`${hf}: encoder dependency required — install "meshoptimizer".`);return vf(hf,async(i)=>{let r=i.getLogger();if(i.hasExtension("KHR_mesh_primitive_restart"))throw Error("reorder: Missing support for KHR_mesh_primitive_restart.");await n.ready;let s=O9(i);for(let a of s.indicesToAttributes.keys()){let o=a.getArray();if(!(o instanceof Uint32Array))o=new Uint32Array(o);else o=o.slice();let[c,l]=n.reorderMesh(o,s.indicesToMode.get(a)===Jn.Mode.TRIANGLES,t.target==="size"),u=gf(i,a);u.setArray(l<=65534?new Uint16Array(o):o);for(let d of s.indicesToAttributes.get(a)){let f=gf(i,d);Jg(d,a,c,f,l);for(let h of s.indicesToPrimitives.get(a)){if(h.getIndices()===a)h.swap(a,u);h.swap(d,f);for(let b of h.listTargets())b.swap(d,f)}}}if(t.cleanup)await i.transform(IM({propertyTypes:[te.ACCESSOR],keepAttributes:!0,keepIndices:!0}));if(!s.indicesToAttributes.size)r.warn(`${hf}: No qualifying primitives found; may need to weld first.`);else r.debug(`${hf}: Complete.`)})}function O9(e){let t=new Map,n=new Xg,i=new Xg,r=new Xg;for(let s of e.getRoot().listMeshes())for(let a of s.listPrimitives()){let o=a.getIndices();if(!o)continue;t.set(o,a.getMode()),n.add(o,a);for(let c of EM(a))i.add(o,c),r.add(c,a)}return{indicesToPrimitives:n,indicesToAttributes:i,indicesToMode:t,attributesToPrimitives:r}}function D9(e,t,n,i=0.0001){let r=t.length/e.length,s=Array(r).fill(0),a=Array(r).fill(0),o=Array(r).fill(0),c=Array(r).fill(0),l=e.length-1,u=1;for(let d=1;d<l;++d){let f=e[u-1],h=e[d],b=e[d+1],m=(h-f)/(b-f),g=!1;if(h!==b&&(d!==1||h!==e[0])){if(Rl(t,u-1,c),Rl(t,d,a),Rl(t,d+1,o),n==="slerp"){let p=U9(s,c,o,m),x=vM(c,a)+vM(a,o);g=!pf(a,p,i)||x+Number.EPSILON>=Math.PI}else if(n==="lerp")g=!pf(a,F9(s,c,o,m),i);else if(n==="step")g=!pf(a,c)||!pf(a,o)}if(g){if(d!==u)e[u]=e[d],_M(t,u,Rl(t,d,s));u++}}if(l>0)e[u]=e[l],_M(t,u,Rl(t,l,s)),u++;return u}function Rl(e,t,n){for(let i=0,r=n.length;i<r;i++)n[i]=e[t*r+i];return n}function _M(e,t,n){for(let i=0,r=n.length;i<r;i++)e[t*r+i]=n[i]}function pf(e,t,n=0){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(Math.abs(e[i]-t[i])>n)return!1;return!0}function L9(e,t,n){return e*(1-n)+t*n}function F9(e,t,n,i){for(let r=0;r<t.length;r++)e[r]=L9(t[r],n[r],i);return e}function U9(e,t,n,i){let r=t[0],s=t[1],a=t[2],o=t[3],c=n[0],l=n[1],u=n[2],d=n[3],f,h,b,m,g;if(h=r*c+s*l+a*u+o*d,h<0)h=-h,c=-c,l=-l,u=-u,d=-d;if(1-h>k9)f=Math.acos(h),b=Math.sin(f),m=Math.sin((1-i)*f)/b,g=Math.sin(i*f)/b;else m=1-i,g=i;return e[0]=m*r+g*c,e[1]=m*s+g*l,e[2]=m*a+g*u,e[3]=m*o+g*d,e}function vM(e,t){let n=B9(e,t);return Math.acos(2*n*n-1)}function B9(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}var P3,Q5,eK,tK,nK,iK,rK,sK,Xg=class{_map=new Map;get size(){return this._map.size}has(e){return this._map.has(e)}add(e,t){let n=this._map.get(e);if(!n)n=new Set,this._map.set(e,n);return n.add(t),this}get(e){return this._map.get(e)||new Set}keys(){return this._map.keys()}},aK,bf,oM=4294967295,$3,oK,cK,lK,uK,dK,fK,hK,qs="dedup",qg,pK,mK,MM,n9,RM,i9,Zo="prune",Qg=0.011764705882352941,uM,o9=class{disposed={};empty(){for(let e in this.disposed)return!1;return!0}entries(){return Object.entries(this.disposed)}dispose(e){this.disposed[e.propertyType]=this.disposed[e.propertyType]||0,this.disposed[e.propertyType]++}},gK,bK,xK,yK,_K,Xs="quantize",b9,x9,y9,_9,v9,E9,mf,hf="reorder",P9,vK,yM,k9=0.000001,EK,TK,AK,wK,SK,MK,RK,IK;var DM=mt(()=>{wl();aM();uf();P3=kf($g(),1),{POINTS:Q5,LINES:eK,LINE_STRIP:tK,LINE_LOOP:nK,TRIANGLES:iK,TRIANGLE_STRIP:rK,TRIANGLE_FAN:sK}=Jn.Mode;aK=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});bf=typeof Float32Array<"u"?Float32Array:Array;Math.PI/180;180/Math.PI;$3=H3;(function(){var e=j3();return function(t,n,i,r,s,a){var o,c;if(!n)n=3;if(!i)i=0;if(r)c=Math.min(r*n+i,t.length);else c=t.length;for(o=i;o<c;o+=n)e[0]=t[o],e[1]=t[o+1],e[2]=t[o+2],s(e,e,a),t[o]=e[0],t[o+1]=e[1],t[o+2]=e[2];return t}})();({FLOAT:oK}=Be.ComponentType),{LINES:cK,LINE_STRIP:lK,LINE_LOOP:uK,TRIANGLES:dK,TRIANGLE_STRIP:fK,TRIANGLE_FAN:hK}=Jn.Mode,qg={keepUniqueNames:!1,propertyTypes:[te.ACCESSOR,te.MESH,te.TEXTURE,te.MATERIAL,te.SKIN]};({TEXTURE_INFO:pK,ROOT:mK}=te);MM=Y3,n9=Q3,RM=t9;(function(){var e=SM();return function(t,n,i,r,s,a){var o,c;if(!n)n=4;if(!i)i=0;if(r)c=Math.min(r*n+i,t.length);else c=t.length;for(o=i;o<c;o+=n)e[0]=t[o],e[1]=t[o+1],e[2]=t[o+2],e[3]=t[o+3],s(e,e,a),t[o]=e[0],t[o+1]=e[1],t[o+2]=e[2],t[o+3]=e[3];return t}})();i9=/color|emissive|diffuse/i;uM={propertyTypes:[te.NODE,te.SKIN,te.MESH,te.CAMERA,te.PRIMITIVE,te.PRIMITIVE_TARGET,te.ANIMATION,te.MATERIAL,te.TEXTURE,te.ACCESSOR,te.BUFFER],keepLeaves:!1,keepAttributes:!1,keepIndices:!1,keepSolidTextures:!1,keepExtras:!1};({ROOT:gK,NODE:bK,MESH:xK,PRIMITIVE:yK,ACCESSOR:_K}=te);b9=[Int8Array,Int16Array,Int32Array],{TRANSLATION:x9,ROTATION:y9,SCALE:_9,WEIGHTS:v9}=Da.TargetPath,E9=[x9,y9,_9],mf={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12,normalizeWeights:!0,cleanup:!0};P9={target:"size",cleanup:!0};vK={level:"high",...mf};(function(e){e[e.STEP=0]="STEP",e[e.LERP=1]="LERP",e[e.SLERP=2]="SLERP"})(yM||(yM={}));EK={ready:Promise.resolve(),resample:D9,tolerance:0.0001,cleanup:!0},{POINTS:TK,LINES:AK,LINE_STRIP:wK,LINE_LOOP:SK,TRIANGLES:MK,TRIANGLE_STRIP:RK,TRIANGLE_FAN:IK}=Jn.Mode});function FM(e,t,n,i={}){if(!Array.isArray(t))return e.push({code:"EXPECTED_ARRAY",path:n,message:`${n} must be an array.`}),!1;if(!i.allowEmpty&&t.length===0)e.push({code:"EXPECTED_NONEMPTY_ARRAY",path:n,message:`${n} must not be empty.`});let r=new Set;for(let s=0;s<t.length;s++){let a=t[s];if(!$r(a)){e.push({code:"EXPECTED_NONEMPTY_STRING",path:`${n}[${s}]`,message:`${n}[${s}] must be a trimmed non-empty string.`});continue}if(r.has(a))e.push({code:"DUPLICATE_VALUE",path:`${n}[${s}]`,message:`${n} contains duplicate value ${JSON.stringify(a)}.`});r.add(a)}return!0}function j9(e,t,n){let i=`frames[${t}]`;if(!Js(e))return n.push({code:"INVALID_FRAME",path:i,message:`${i} must be an object.`}),!1;if(!$r(e.id))n.push({code:"INVALID_FRAME_ID",path:`${i}.id`,message:"Frame ID is required."});if(!LM(e.translation,3))n.push({code:"INVALID_FRAME_TRANSLATION",path:`${i}.translation`,message:"Frame translation must be three finite meters."});if(!LM(e.rotation,4))n.push({code:"INVALID_FRAME_ROTATION",path:`${i}.rotation`,message:"Frame rotation must be a finite quaternion."});else{let r=Math.hypot(...e.rotation);if(Math.abs(r-1)>0.000001)n.push({code:"NON_UNIT_FRAME_ROTATION",path:`${i}.rotation`,message:"Frame rotation quaternion must be normalized within 1e-6."})}return!0}function H9(e,t,n){let i=`relationships[${t}]`;if(!Js(e))return n.push({code:"INVALID_RELATIONSHIP",path:i,message:`${i} must be an object.`}),!1;for(let r of["kind","target"])if(!$r(e[r]))n.push({code:"INVALID_RELATIONSHIP_FIELD",path:`${i}.${r}`,message:`${i}.${r} must be a trimmed non-empty string.`});if(e.targetType!=="node"&&e.targetType!=="role"&&e.targetType!=="socket")n.push({code:"INVALID_RELATIONSHIP_TARGET_TYPE",path:`${i}.targetType`,message:"Relationship targetType must be node, role, or socket."});for(let r of["sourceFrame","targetFrame"])if(e[r]!==void 0&&!$r(e[r]))n.push({code:"INVALID_RELATIONSHIP_FRAME",path:`${i}.${r}`,message:`${i}.${r} must be a trimmed non-empty string.`});return!0}function G9(e,t,n){let i=`sockets[${t}]`;if(!Js(e))return n.push({code:"INVALID_SOCKET",path:i,message:`${i} must be an object.`}),!1;for(let r of["id","type","frame"])if(!$r(e[r]))n.push({code:"INVALID_SOCKET_FIELD",path:`${i}.${r}`,message:`${i}.${r} must be a trimmed non-empty string.`});if(FM(n,e.compatibleTypes,`${i}.compatibleTypes`,{allowEmpty:!0}),e.allowedRotationsDegrees!==void 0){if(!Array.isArray(e.allowedRotationsDegrees)||e.allowedRotationsDegrees.some((r)=>typeof r!=="number"||!Number.isFinite(r)))n.push({code:"INVALID_ALLOWED_ROTATIONS",path:`${i}.allowedRotationsDegrees`,message:"Allowed rotations must be finite degree values."})}return!0}function $9(e){let t=[];if(!Js(e))return{valid:!1,issues:[{code:"EXPECTED_OBJECT",path:"",message:"SemanticMetadataV1 must be an object."}]};if(e.schemaVersion!==1)t.push({code:"UNSUPPORTED_SCHEMA_VERSION",path:"schemaVersion",message:"schemaVersion must be 1."});FM(t,e.roles,"roles");let n=Array.isArray(e.frames)?e.frames:[];if(!Array.isArray(e.frames))t.push({code:"EXPECTED_ARRAY",path:"frames",message:"frames must be an array."});let i=new Set;n.forEach((o,c)=>{if(j9(o,c,t),Js(o)&&$r(o.id)){if(i.has(o.id))t.push({code:"DUPLICATE_FRAME_ID",path:`frames[${c}].id`,message:`Duplicate frame ID ${JSON.stringify(o.id)}.`});i.add(o.id)}});let r=Array.isArray(e.relationships)?e.relationships:[];if(!Array.isArray(e.relationships))t.push({code:"EXPECTED_ARRAY",path:"relationships",message:"relationships must be an array."});r.forEach((o,c)=>{if(H9(o,c,t),Js(o))for(let l of["sourceFrame","targetFrame"]){let u=o[l];if($r(u)&&!i.has(u))t.push({code:"UNKNOWN_FRAME_REFERENCE",path:`relationships[${c}].${l}`,message:`Unknown frame ${JSON.stringify(u)}.`})}});let s=Array.isArray(e.sockets)?e.sockets:[];if(!Array.isArray(e.sockets))t.push({code:"EXPECTED_ARRAY",path:"sockets",message:"sockets must be an array."});let a=new Set;if(s.forEach((o,c)=>{if(G9(o,c,t),Js(o)&&$r(o.id)){if(a.has(o.id))t.push({code:"DUPLICATE_SOCKET_ID",path:`sockets[${c}].id`,message:`Duplicate socket ID ${JSON.stringify(o.id)}.`});a.add(o.id)}if(Js(o)&&$r(o.frame)&&!i.has(o.frame))t.push({code:"UNKNOWN_FRAME_REFERENCE",path:`sockets[${c}].frame`,message:`Unknown frame ${JSON.stringify(o.frame)}.`})}),t.length>0)return{valid:!1,issues:t};return{valid:!0,value:K9(e),issues:t}}function K9(e){return{schemaVersion:1,roles:[...e.roles],relationships:e.relationships.map((t)=>({kind:t.kind,target:t.target,targetType:t.targetType,...t.sourceFrame?{sourceFrame:t.sourceFrame}:{},...t.targetFrame?{targetFrame:t.targetFrame}:{}})),frames:e.frames.map((t)=>({id:t.id,translation:z9(t.translation),rotation:V9(t.rotation)})),sockets:e.sockets.map((t)=>({id:t.id,type:t.type,frame:t.frame,compatibleTypes:[...t.compatibleTypes],...t.allowedRotationsDegrees?{allowedRotationsDegrees:[...t.allowedRotationsDegrees]}:{}}))}}function nb(e){let t=e.kilnSemantic;if(t===void 0)return;let n=$9(t);return n.valid?n.value:void 0}var La,Js=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),$r=(e)=>typeof e==="string"&&e.trim().length>0&&e===e.trim(),LM=(e,t)=>Array.isArray(e)&&e.length===t&&e.every((n)=>typeof n==="number"&&Number.isFinite(n)),z9=(e)=>[e[0],e[1],e[2]],V9=(e)=>[e[0],e[1],e[2],e[3]];var Af=mt(()=>{La=Object.freeze({vehicleFrame:"vehicle.frame",vehicleForward:"vehicle.front.+x",socket:"socket",chassis:"chassis",chassisMain:"chassis.main",axle:"axle",seat:"seat",contact:"contact",steering:"steering",propulsion:"propulsion",wheelAssembly:"wheel.assembly",wheelPivot:"wheel.pivot",wheelLoadBearing:"wheel.load-bearing",wheelTire:"wheel.tire",wheelRim:"wheel.rim",wheelHub:"wheel.hub",wheelContact:"wheel.contact",steeringPivot:"steering.pivot",roof:"roof",architectureRoof:"architecture.roof",collider:"collider",colliderBox:"collider.box",colliderCapsule:"collider.capsule",colliderHull:"collider.hull",anchor:"anchor",kitModule:"kit.module",kitPort:"kit.port",lodImpostor:"lod.impostor"})});function zM(){return new Jw().registerExtensions([...DS,BM])}var hi="MSFT_lod",UM,BM;var ib=mt(()=>{wl();uf();UM=class UM extends nt{static EXTENSION_NAME=hi;init(){this.extensionName=hi,this.propertyType="Lod",this.parentTypes=[te.NODE,te.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{levels:new bn})}addLevel(e){return this.addRef("levels",e)}listLevels(){return this.listRefs("levels")}};BM=class BM extends _t{extensionName=hi;static EXTENSION_NAME=hi;createLod(e=""){return new UM(this.document.getGraph(),e)}read(e){let t=e.jsonDoc.json;return this.readLevels(t.nodes,e.nodes),this.readLevels(t.materials,e.materials),this}readLevels(e,t){(e??[]).forEach((n,i)=>{let r=n.extensions?.[hi]?.ids,s=t[i];if(!s||!Array.isArray(r))return;let a=this.createLod();for(let o of r){let c=typeof o==="number"?t[o]:void 0;if(c&&c!==s)a.addLevel(c)}s.setExtension(hi,a)})}write(e){let t=e.jsonDoc.json,n=this.document.getRoot();for(let i of n.listNodes()){let r=e.nodeIndexMap.get(i),s=i.getExtension(hi)?.listLevels().filter((o)=>o.propertyType===te.NODE).map((o)=>e.nodeIndexMap.get(o)).filter((o)=>o!==void 0),a=r===void 0?void 0:t.nodes?.[r];if(a&&s?.length)a.extensions={...a.extensions,[hi]:{ids:s}}}for(let i of n.listMaterials()){let r=e.materialIndexMap.get(i),s=i.getExtension(hi)?.listLevels().filter((o)=>o.propertyType===te.MATERIAL).map((o)=>e.materialIndexMap.get(o)).filter((o)=>o!==void 0),a=r===void 0?void 0:t.materials?.[r];if(a&&s?.length)a.extensions={...a.extensions,[hi]:{ids:s}}}return this}}});var W9;var rb=mt(()=>{W9=Object.freeze([1,1,1])});var jK,HK;var VM=mt(()=>{rb();jK=Object.freeze({units:"m",forward:"+X",up:"+Y",right:"+Z",groundY:0}),HK=Math.PI/180});var jM=()=>{};var HM=()=>{};var GM=mt(()=>{VM();rb();jM();HM();Af()});var X9;var $M=mt(()=>{X9=Object.freeze({parametricSamples:262144,subdivisionTriangles:1e6,subdivisionAttributeBytes:134217728,subdivisionIterations:10,repeatedMeshes:1e4,curveRepeatVertices:262144,primitiveSegments:4096,primitiveGridVertices:262144,unwrapVertices:65536,unwrapTriangles:1e6,unwrapAttributeBytes:134217728,unwrapResolution:4096,skinBones:1024,skinVertices:262144,skinAttributeBytes:134217728,colliderHullVertices:65536,surfaceBakeVertices:262144,surfaceBakeTriangles:1e6,surfaceBakeRays:8388608,surfaceBakeRayDirections:256})});var sb="kilnRepeatInstances";var ab=mt(()=>{GM();vu();$M()});function Il(e){return e.getExtension("KHR_node_visibility")?.getVisible?.()===!1}var oW;var wf=mt(()=>{oW=[{grade:"A",max:1,range:"0-1"},{grade:"B",max:3,range:"2-3"},{grade:"C",max:6,range:"4-6"},{grade:"D",max:12,range:"7-12"},{grade:"F",max:Number.POSITIVE_INFINITY,range:"13+"}]});var KM=mt(()=>{wf()});function XM(e){let t=new Map,n=e.getRoot().getDefaultScene()??e.getRoot().listScenes()[0];if(!n)return t;let i=(r,s)=>{let a=new Map;for(let o of r){let c=o.getName(),l=a.get(c)??0;a.set(c,l+1);let u=`${s}${WM(c,l)}`;t.set(o,u),i(o.listChildren(),u)}};return i(n.listChildren(),WM(n.getName()||"Scene",0)),t}var WM=(e,t)=>`/${encodeURIComponent(e)}[${t}]`;var qM=mt(()=>{ib();Af();ab();wf();KM()});var JM=()=>{};function Ht(e){throw TypeError(`atlas provenance: ${e}`)}function Ki(e,t){if(!e||typeof e!=="object"||Array.isArray(e))Ht("plain metadata object required.");let n=Object.getPrototypeOf(e);if(n!==null&&n!==Object.prototype)Ht("plain metadata prototype required.");let i=Object.getOwnPropertyDescriptor(e,t);if(!i)return;if(!i.enumerable||!("value"in i))Ht("metadata accessors/hidden fields are unsupported.");return i.value}function Cl(e,t){for(let n of Reflect.ownKeys(e))if(typeof n!=="string"||!t.includes(n))Ht("unsupported metadata field.");for(let n of t)Ki(e,n);return e}function Z9(e){Mn(e);let t=Cl(e,["spec","manifest"]),n=fa(t.spec);return{spec:n,manifest:Rc(t.manifest,n)}}function Y9(e){let t=Cl(e,["version","atlases"]);if(t.version!==Yo)Ht("unsupported version.");let n=t.atlases;if(!Array.isArray(n)||Object.getPrototypeOf(n)!==Array.prototype)Ht("dense atlas array required.");let i=Object.getOwnPropertyDescriptor(n,"length").value;if(i>Fa.atlases||Reflect.ownKeys(n).length!==i+1)Ht("atlas count/density budget exceeded.");let r=J9,s=[];for(let a=0;a<i;a++){let o=Object.getOwnPropertyDescriptor(n,String(a));if(!o?.enumerable||!("value"in o))Ht("atlas array accessors are unsupported.");let c=Mn(o.value);if(r+=new TextEncoder().encode(c).length+(a>0?1:0),r>Fa.bytes)Ht("aggregate metadata byte budget exceeded.");s.push(Cl(o.value,["id","spec","manifest"]))}return s}function Q9(e){let t=Y9(e),n=new Set,i=[];for(let r of t){let s=Z9({spec:r.spec,manifest:r.manifest});if(r.id!==s.manifest.manifestHash||n.has(r.id))Ht("duplicate or mismatched atlas identity.");n.add(r.id),i.push({id:r.id,...s})}return{version:Yo,atlases:i}}function ZM(e,t){let n=e.atlases.find((i)=>i.id===t);if(!n)Ht("unknown atlas reference.");return n}function eB(e,t,n,i){if(!["top-left","bottom-left"].includes(n)||!["content-boundary","texel-center"].includes(i))Ht("explicit binding origin/mode required.");let r=e.manifest.regions.find((d)=>d.name===t);if(!r)Ht("unknown named region.");let{x:s,y:a,width:o,height:c}=r.content,l=i==="texel-center",u=n==="bottom-left";return{manifestHash:e.manifest.manifestHash,specHash:e.manifest.specHash,layoutHash:e.manifest.layoutHash,region:r.name,content:structuredClone(r.content),allocation:structuredClone(r.allocation),inputOrigin:n,mode:i,scale:[(o-(l?1:0))/e.manifest.width,(u?-1:1)*(c-(l?1:0))/e.manifest.height],offset:[(s+(l?0.5:0))/e.manifest.width,(a+(u?c-(l?0.5:0):l?0.5:0))/e.manifest.height]}}function tB(e,t){Mn(e);let n=Cl(e,["version","atlasId","region","inputOrigin","mode"]);if(n.version!==Yo)Ht("unsupported binding version.");return eB(ZM(t,n.atlasId),n.region,n.inputOrigin,n.mode)}function nB(e){let t=e.getRoot().getDefaultScene()??e.getRoot().listScenes()[0];return t?Ki(t.getExtras(),"kilnAtlasProvenance"):void 0}function YM(e){let t=nB(e);return t===void 0?void 0:Q9(t)}function QM(e){let t=[];for(let n of e.getRoot().listMaterials())for(let[i,r]of[[n.getBaseColorTexture(),n.getBaseColorTextureInfo()],[n.getNormalTexture(),n.getNormalTextureInfo()],[n.getMetallicRoughnessTexture(),n.getMetallicRoughnessTextureInfo()],[n.getEmissiveTexture(),n.getEmissiveTextureInfo()],[n.getOcclusionTexture(),n.getOcclusionTextureInfo()]])if(i&&r&&Ki(r.getExtras(),"kilnAtlasReference")!==void 0){if(t.length>=Fa.bindings)Ht("document binding budget exceeded.");t.push({texture:i,info:r})}return t}async function eR(e){let t=e.getImage();if(!t||t.byteLength>Fa.encodedBytes)Ht("encoded image missing or over budget.");let n=await crypto.subtle.digest("SHA-256",t);return`sha256:${[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join("")}`}function tR(e){let t={minFilter:e.getMinFilter(),magFilter:e.getMagFilter(),wrapS:e.getWrapS(),wrapT:e.getWrapT()};if(![null,9728,9729,9984,9985,9986,9987].includes(t.minFilter)||![null,9728,9729].includes(t.magFilter)||![33071,33648,10497].includes(t.wrapS)||![33071,33648,10497].includes(t.wrapT))Ht("unsupported effective sampler.");return t}function nR(e,t){Mn(e);let n=Cl(e,["version","id","effectiveSampler","finalMime","finalImageSha256"]);if(n.version!==Yo)Ht("unsupported texture reference version.");return ZM(t,n.id),n}function iR(e){let t=new Set,n=0;for(let{texture:i}of e){if(t.has(i))continue;t.add(i);let r=i.getImage();if(!r||r.byteLength>Fa.encodedBytes)Ht("encoded image missing or over budget.");if(n+=r.byteLength,n>Fa.aggregateEncodedBytes)Ht("aggregate encoded image hash budget exceeded.")}}async function rR(e){let t=YM(e),n=QM(e);if(!n.length)return;if(!t)Ht("atlas table missing.");iR(n);let i=new Map;for(let{texture:r,info:s}of n){let a=nR(Ki(s.getExtras(),"kilnAtlasReference"),t),o=i.get(r);if(!o)o=await eR(r),i.set(r,o);s.setExtras({...s.getExtras(),kilnAtlasReference:{version:Yo,id:a.id,effectiveSampler:tR(s),finalMime:r.getMimeType(),finalImageSha256:o}})}}async function sR(e){let t=YM(e),n=QM(e);if(n.length&&!t)Ht("atlas table missing.");if(!t){for(let s of e.getRoot().listMeshes())for(let a of s.listPrimitives())if(Ki(a.getExtras(),"kilnAtlasBinding")!==void 0)Ht("atlas table missing.");return}iR(n);let i=new Map;for(let{texture:s,info:a}of n){let o=nR(Ki(a.getExtras(),"kilnAtlasReference"),t),c=i.get(s);if(!c)c=await eR(s),i.set(s,c);if(o.finalImageSha256!==c||o.finalMime!==s.getMimeType()||Mn(o.effectiveSampler)!==Mn(tR(a)))Ht("final image or effective sampler identity mismatch.")}let r=0;for(let s of e.getRoot().listMeshes())for(let a of s.listPrimitives()){let o=Ki(a.getExtras(),"kilnAtlasBinding");if(o!==void 0){if(++r>Fa.bindings)Ht("primitive budget exceeded.");tB(o,t);let c=a.getMaterial(),l=Ki(o,"atlasId");if(!(c?[c.getBaseColorTextureInfo(),c.getNormalTextureInfo(),c.getMetallicRoughnessTextureInfo(),c.getEmissiveTextureInfo(),c.getOcclusionTextureInfo()]:[]).some((d)=>d&&Ki(d.getExtras(),"kilnAtlasReference")!==void 0&&Ki(Ki(d.getExtras(),"kilnAtlasReference"),"id")===l))Ht("named binding has no matching material atlas reference.")}}}var Yo="kiln.atlas-provenance.v1",J9,Fa;var aR=mt(()=>{JM();ku();J9=new TextEncoder().encode(JSON.stringify({version:Yo,atlases:[]})).length,Fa=Object.freeze({atlases:128,bytes:4194304,bindings:1024,entryBytes:262144,encodedBytes:16777216,aggregateEncodedBytes:67108864,bakeDecodedBytes:67108864})});var dR={};Pb(dR,{deliverRuntimeThreeGlb:()=>cB});function iB(e,t){let n=(i)=>{if(!i)return-1;if(!t.has(i))t.set(i,t.size);return t.get(i)};return e.listPrimitives().map((i)=>`${i.getMode()}:${n(i.getMaterial())}:${n(i.getIndices())}:${i.listSemantics().sort().map((r)=>`${r}=${n(i.getAttribute(r))}`).join(",")}:${i.listTargets().length}`).join("|")}function rB(e){let t=[],n=new Map,i=e.getRoot().listNodes().filter((s)=>s.getExtras()[sb]!==void 0),r;for(let s of i){let a=new Map;for(let l of s.listChildren()){let u=l.getMesh();if(!u||l.listChildren().length||l.getSkin()||l.listExtensions().length||Il(l)||Nl(l).length||Object.keys(l.getExtras()).length||l.getWeights().length)continue;let d=iB(u,n);a.set(d,[...a.get(d)??[],l])}let o=0;for(let l of a.values()){if(l.length<2)continue;let u=l[0].getMesh();r??=e.createExtension(lf).setRequired(!0);let d=e.getRoot().listBuffers()[0],f=(_,y)=>e.createAccessor().setType(_).setArray(new Float32Array(y)).setBuffer(d??null),h=[],b=[],m=[];for(let _ of l)h.push(..._.getTranslation()),b.push(..._.getRotation()),m.push(..._.getScale());let g=r.createInstancedMesh().setAttribute("TRANSLATION",f("VEC3",h)).setAttribute("ROTATION",f("VEC4",b)).setAttribute("SCALE",f("VEC3",m)),p=`${s.getName()||"Node"}_Instances${o?`_${o}`:""}`;o++;let x=e.createNode(p).setMesh(u).setExtension("EXT_mesh_gpu_instancing",g);s.addChild(x),t.push({node:x,mesh:u.getName(),count:l.length,instances:l.map((_)=>_.getName())});for(let _ of l){let y=_.getMesh();if(_.dispose(),y&&y!==u&&!y.listParents().some((v)=>v.propertyType===te.NODE))y.dispose()}}let c={...s.getExtras()};delete c[sb],s.setExtras(c)}return t}function sB(e){let t=[];for(let n of e.getRoot().listNodes()){let i=n.getMesh();if(!i||!uR(n))continue;let r=e.createNode(`${n.getName()}_Proxy`).setMesh(i);n.setMesh(null).addChild(r),t.push({collider:n,proxy:r})}return t}async function aB(e,t,n){let i=e.getRoot().listTextures().filter((o)=>o.getMimeType()!=="image/ktx2"&&o.getImage());if(!t)return{status:"skipped",textures:i.length,reason:"No KTX2 encoder was supplied; textures stay PNG or JPEG."};let r=new Map,s=(o,c)=>{if(o)r.set(o,(r.get(o)??new Set).add(c))};for(let o of e.getRoot().listMaterials())s(o.getBaseColorTexture(),"baseColor"),s(o.getEmissiveTexture(),"emissive"),s(o.getNormalTexture(),"normal"),s(o.getMetallicRoughnessTexture(),"metallicRoughness"),s(o.getOcclusionTexture(),"occlusion");let a=["baseColor","emissive","normal","metallicRoughness","occlusion"];for(let o of i){let c=r.get(o)??new Set,l=c.has("baseColor")||c.has("emissive"),u=o.listParents().some((m)=>m.propertyType!==te.ROOT&&!oB(m)),d=[...c].some((m)=>m!=="baseColor"&&m!=="emissive")||u;if(l&&d)throw Error(`Texture ${JSON.stringify(o.getName())} is used by both sRGB and linear material slots; one KTX2 encoding cannot serve both. Use separate images.`);let f=o.getImage(),h=await t({image:f,mimeType:o.getMimeType(),name:o.getName(),colorSpace:l?"srgb":"linear",slot:a.find((m)=>c.has(m))??"other"});if(!(h instanceof Uint8Array)||!Sg(h))throw Error("ktx2Encoder must return KTX2 bytes starting with the KTX2 identifier");n.set(o,`sha256:${await El(f)}`),o.setImage(h).setMimeType("image/ktx2");let b=o.getURI();if(b)o.setURI(b.replace(/\.(png|jpe?g)$/i,".ktx2"))}if(i.length){e.createExtension(Gg).setRequired(!0);await Promise.resolve().then(() => aR());await rR(e),await sR(e)}return{status:"encoded",textures:i.length,...t.identity?{encoder:structuredClone(t.identity)}:{}}}function oB(e){return e.propertyType===te.MATERIAL}function lR(e,t){let n=new Qe().fromArray(e).invert().multiply(new Qe().fromArray(t)),i=new j,r=new ln,s=new j;return n.decompose(i,r,s),{scale:s.x,offset:[i.x,i.y,i.z]}}async function cB(e,t,n={},i={}){let r=n.compression??"meshopt";if(r!=="meshopt"&&r!=="none")throw Error("Runtime three compression must be meshopt or none");let s=zM().registerDependencies({"meshopt.encoder":t}),a=await s.readBinary(e);a.setLogger(new ka(ka.Verbosity.SILENT)),await a.transform(tb({propertyTypes:[te.ACCESSOR],keepUniqueNames:!0}));let o=rB(a),c=sB(a),l=new Map;for(let A of a.getRoot().listNodes())if(A.getMesh())l.set(A,[...A.getMatrix()]);if(await a.transform(kM({encoder:t,target:"size"}),PM({pattern:oR,patternTargets:oR,quantizationVolume:"mesh",quantizePosition:_r.position,quantizeNormal:_r.normal,quantizeTexcoord:_r.texcoord,quantizeColor:_r.color,quantizeWeight:_r.weight})),r==="meshopt")a.createExtension(Ml).setRequired(!0).setEncoderOptions({method:Ml.EncoderMethod.QUANTIZE});let u=new Map,d=await aB(a,n.ktx2Encoder,u);for(let A of a.getRoot().listNodes()){if(!A.getMesh()||l.has(A)||A.getName())continue;let w=A.getParentNode();A.setName(`${w?.getName()||"Node"}_Mesh`)}let f=XM(a),h=(A)=>f.get(A)??`#${encodeURIComponent(A.getName())}`,b=new Set(c.map((A)=>A.proxy)),m=[];for(let A of a.getRoot().listNodes()){let E=A.getMesh();if(!E||A.getExtension("EXT_mesh_gpu_instancing"))continue;let w=f.get(A);if(w===void 0)continue;let P=l.get(A),S=P===void 0,I=S||b.has(A),U=S?new Qe().identity().toArray():P,N=[...A.getMatrix()],{scale:F,offset:D}=lR(U,N);if(!S&&Math.abs(F-1)<0.000000000001&&D.every((K)=>K===0))continue;let O=A.getParentNode();m.push({node:w,mesh:E.getName(),meshMovedToChild:I,...I&&O?{authoredNode:h(O)}:{},dequantization:{scale:F,offset:D},localScale:[...A.getScale()]})}for(let A of a.getRoot().listNodes()){let E=A.getMesh();if(!E||f.has(A)||!l.has(A))continue;let{scale:w,offset:P}=lR(l.get(A),[...A.getMatrix()]);m.push({node:`#lod/${encodeURIComponent(A.getName())}`,mesh:E.getName(),meshMovedToChild:!1,dequantization:{scale:w,offset:P},localScale:[...A.getScale()]})}let g=new Map;for(let A of a.getRoot().listMeshes())for(let E of A.listPrimitives())for(let w of E.listSemantics())if(w.startsWith("_"))g.set(w,(g.get(w)??new Set).add(A));let p=a.getRoot().listNodes(),x=await s.writeBinary(a),_=(await s.binaryToJSON(x)).json,y=new Map;a.getRoot().listTextures().forEach((A,E)=>{let w=u.get(A);if(w)y.set(E,w)});let v=i.gltfBasename?await s.writeJSON(a,{format:zw.GLTF,basename:i.gltfBasename}):void 0,T={target:"three",extensionsUsed:[..._.extensionsUsed??[]].sort(),extensionsRequired:[..._.extensionsRequired??[]].sort(),compression:r==="meshopt"?{extension:"EXT_meshopt_compression",method:"quantize"}:{extension:"none"},quantization:{extension:"KHR_mesh_quantization",volume:"mesh",bits:{position:_r.position,normal:_r.normal,texcoord:_r.texcoord,color:_r.color,weight:_r.weight},customAttributes:"float32"},nodeScale:m,colliderProxies:c.map(({collider:A,proxy:E})=>({collider:h(A),proxy:h(E)})),customAttributes:[...g].sort(([A],[E])=>cR(A)-cR(E)||(A<E?-1:A>E?1:0)).map(([A,E])=>({name:A,meshes:E.size,componentType:"FLOAT",normalized:!1})),instancing:o.map(({node:A,...E})=>({node:h(A),...E})),ktx2:d,preserved:{lodChains:p.filter((A)=>A.getExtension(hi)).length,hiddenNodes:p.filter((A)=>Il(A)).length,colliders:p.filter(uR).length,anchors:p.filter((A)=>Nl(A).some((E)=>E.startsWith(`${La.anchor}.`))).length,ports:p.filter((A)=>Nl(A).some((E)=>E.startsWith(`${La.kitPort}.`))).length,kitModules:p.filter((A)=>Nl(A).includes(La.kitModule)).length}};return{glb:x,delivery:T,imageSources:y,...v?{gltf:{json:v.json,resources:v.resources}}:{}}}var _r,oR,cR=(e)=>e==="_EDGE"?0:e==="_CAVITY"?1:2,Nl=(e)=>nb(e.getExtras())?.roles??[],uR=(e)=>Nl(e).some((t)=>t.startsWith(`${La.collider}.`));var fR=mt(()=>{wl();uf();DM();ji();Af();ib();qM();ab();wf();Mg();_r=Object.freeze({volume:"mesh",position:14,normal:10,texcoord:12,color:8,weight:8}),oR=/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/});var lB;var hR=mt(()=>{lB=function(){var e="b9H79Tebbbe9ok9Geueu9Geub9Gbb9Gruuuuuuueu9Gvuuuuueu9Gduueu9Gluuuueu9Gvuuuuub9Gouuuuuub9Gluuuub9GiuuueuiE8AdilveoveovrrwrrrDDoDrbqqbelve9Weiiviebeoweuecj:Gdkr:PlCo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8F9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWV9mW4W2be8A9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWVbd8F9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWV9c9V919U9KbiE9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949wWV79P9V9UblY9TW79O9V9Wt9FW9U9J9V9KW69U9KW949c919M9MWVbv8E9TW79O9V9Wt9FW9U9J9V9KW69U9KW949c919M9MWV9c9V919U9Kbo8A9TW79O9V9Wt9FW9U9J9V9KW69U9KW949wWV79P9V9UbrE9TW79O9V9Wt9FW9U9J9V9KW69U9KW949tWG91W9U9JWbwa9TW79O9V9Wt9FW9U9J9V9KW69U9KW949tWG91W9U9JW9c9V919U9KbDL9TW79O9V9Wt9FW9U9J9V9KWS9P2tWV9p9JtbqK9TW79O9V9Wt9FW9U9J9V9KWS9P2tWV9r919HtbkL9TW79O9V9Wt9FW9U9J9V9KWS9P2tWVT949WbxY9TW79O9V9Wt9FW9U9J9V9KWS9P2tWVJ9V29VVbmE9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94J9H9J9OWbza9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94J9H9J9OW9ttV9P9WbHa9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94SWt9J9O9sW9T9H9WbOK9TW79O9V9Wt9F79W9Ht9P9H29t9VVt9sW9T9H9WbAl79IV9RbXDwebcekdKYq:8f8Adbk;wadhud9:8Jjjjjbc;qw9Rgr8KjjjjbcbhwdnaeTmbabcbyd;i:I:cjbaoaocb9iEgDc:GeV86bbarc;adfcbcjdz:xjjjb8AdnaiTmbarc;adfadalz:wjjjb8Akarc;abfalfcbcbcjdal9RalcFe0Ez:xjjjb8Aarc;abfarc;adfalz:wjjjb8Aar9cb83iUar9cb83i8War9cb83iyar9cb83iaar9cb83iKar9cb83izar9cb83iwar9cb83ibcj;abal9Uc;WFbGcjdalca0Ehqdnaicd6mbavcd9imbaDTmbadcefhkaqci2gxal2hmarc;alfclfhParc;qlfceVhsarc;qofclVhzcbhHincdhOcbhAdnavci6mbar9cb83i;Ooar9cb83i;Goar9cb83i;yoar9cb83i;qoadaHfgoybbhCcbhXincbhwcbhQdninaoalfhLaoybbgKaC7aQVhQawcP0meaLhoaKhCawcefgwaXfai6mbkkcbhCarc;qofhwincwhYcwh8AdnaQaC93gocFeGgEcs0mbclh8AaEci0mbcdcbaEEh8Akdnaocw4cFeGgEcs0mbclhYaEci0mbcdcbaEEhYkaYa8AfhEawydbh3cwhYcwh8Adnaocz4cFeGg5cs0mbclh8Aa5ci0mbcdcba5Eh8AkaEa3fhEdnaocFFFFb0mbclhYaocFFF8F0mbcbcdaocjjjw6EhYkawaEa8AfaYfBdbawclfhwaCcefgCcw9hmbkaLhoaKhCaXczfgXai6mbkcbhocehwazhQinawaoaQydbarc;qofaocdtfydb6EhoaQclfhQawcefgwcw9hmbkaoclthAcihOkcbhEarc;qlfcbcjdz:xjjjb8AarcbBd;ilar9cb83i;aladh8Eaqh8Fakh3inarc;qlfadaEaEcb9h9Ral2falz:wjjjb8Aaia8Faia8F6EhadnaqaiaE9RaEaqfai6EgKcsfc9WGgoaK9nmbarc;qofaKfcbaoaK9Rz:xjjjb8AkadaEal2fhhcbhginagaAVcl4hXarc;alfagcdtfh8JaHh8Kcbh8Lina8LaHfhwdndndndndndndnagPlbedibkaKTmvahawfhoarc;qlfawfRbbhQarc;qofhwaahCinawaoRbbgYaQ9RgQcetaQcKtc8F91786bbawcefhwaoalfhoaYhQaEaCcufgC9hmbxvkkaKTmla8Kc9:Ghoa8LcitcwGh8Aarc;qlfawceVfRbbcwtarc;qlfawc9:GfRbbVhQarc;qofhwaahCinawa3aofRbbcwta8EaofRbbVgYaQ9RgQcetaQcztc8F917cFFiGa8A486bbaoalfhoawcefhwaYhQaEaCcufgC9hmbxlkkasa8Kc98GgQfhoa3aQfhYarc;qlfawc98GgQfRbbhCcwhwinaoRbbawtaCVhCaocefhoawcwfgwca9hmbxdkkaKTmdxekaKTmea8Lcith5ahaQfh8AcbhLina8ARbbhQcwhoaYhwinawRbbaotaQVhQawcefhwaocwfgoca9hmbkarc;qofaLfaQaC7aX93a5486bbaYalfhYa8Aalfh8AaQhCaLcefgLaK9hmbkka8Jydbh8AcbhLarc;qofhoincdhQcbhwinaQaoawfRbbcb9hfhQawcefgwcz9hmbkclhCcbhwinaCaoawfRbbcd0fhCawcefgwcz9hmbkcwhYcbhwinaYaoawfRbbcP0fhYawcefgwcz9hmbkaQaCaQaC6EgwaYawaY6Egwczawcz6Ea8Afh8AaoczfhoaLczfgLaK6mbka8Ja8ABdbka8Kcefh8Ka8Lcefg8Lcl9hmbkagcefggaO9hmbka8Eamfh8Ea8Faxfh8Fa3amfh3aEaxfgEai6mbkcbhocehwaPhQinawaoaQydbarc;alfaocdtfydb6EhoaQclfhQaOawcefgw9hmbkaraHcd4faAcdVaoaocdSE86bbaHclfgHal6mbkkabaefhgabcefhoalcd4g8McbaDEhkadcefh8Narc;abfceVhecbhmdndninaiam9nmearc;qofcbcjdz:xjjjb8Aagao9Rak6mdadamal2gwfhxcbhHa8Nawfhzaocbakz:xjjjbg8Fakfh3aqaiam9Ramaqfai6Egscsfgocl4cifcd4hOaoc9WGg8JThPindndndndndndndndndndnaDTmbaraHcd4fRbbgQciGPlbedlbkasTmdaxaHfhoarc;abfaHfRbbhQarc;qofhwashCinawaoRbbgYaQ9RgQcetaQcKtc8F91786bbawcefhwaoalfhoaYhQaCcufgCmbxikkasTmiaHcitcwGh8Aarc;abfaHceVfRbbcwtarc;abfaHc9:GgofRbbVhQaxaofhoarc;qofhwashCinawao8VbbgYaQ9RgQcetaQcztc8F917cFFiGa8A486bbawcefhwaoalfhoaYhQaCcufgCmbxikkaeaHc98Gg8Afhoaza8AfhYarc;abfa8AfRbbhCcwhwinaoRbbawtaCVhCaocefhoawcwfgwca9hmbkasTmdaQcl4hKaHcitcKGhEaxa8Afh8AcbhLina8ARbbhQcwhoaYhwinawRbbaotaQVhQawcefhwaocwfgoca9hmbkarc;qofaLfaQaC7aK93aE486bbaYalfhYa8Aalfh8AaQhCaLcefgLas9hmbkkaDmbcbhoxlka8JTmbcbhodninarc;qofaofgwcwf8Pibaw8Pib:e9qTmeaoczfgoa8J9pmdxbkkdnavmbcehoxikcbh8AaOhLaOhKinarc;qofa8Afgocwf8Pibhyao8Pibh8PcdhQcbhwinaQaoawfRbbcb9hfhQawcefgwcz9hmbkclhCcbhwinaCaoawfRbbcd0fhCawcefgwcz9hmbkcwhYcbhwinaYaoawfRbbcP0fhYawcefgwcz9hmbkaQaCaQaC6EgoaYaoaY6Egoczaocz6EaKfhKaocucbaya8P:e9cb9sEgwaoaw6EaLfhLa8Aczfg8Aa8J9pmdxbkka8FaHcd4fgoaoRbbcdaHcetcoGtV86bbxikdnaLas6mbaKas6mba8FaHcd4fgoaoRbbciaHcetcoGtV86bbaga39Ras6mra3arc;qofasz:wjjjbasfh3xikaLaK9phoka8FaHcd4fgwawRbbaoaHcetcoGtV86bbkaga39RaO6mla3cbaOz:xjjjbgaaOfhKdndna8JmbaPhoxekdnagaK9RcK9pmbaPhoxekaocdtc:q:G:cjbfcj:G:cjbaDEg3ydxghcetc;:FFFeGhAcuhEcuahtcu7cFeGh8Ecbh8Karc;qofhQinarc;qofa8KfhXczh8AdndndnahPDbeeeeeeedekcucbaXcwf8PibaX8Pib:e9cb9sEh8AxekcbhoaAh8Aina8Aa8EaQaofRbb9nfh8Aaocefgocz9hmbkkcih5cbhYinczhwdndndna3aYcdtfydbgLPDbeeeeeeedekcucbaXcwf8PibaX8Pib:e9cb9sEhwxekaLcetc;:FFFeGhwcuaLtcu7cFeGhCcbhoinawaCaQaofRbb9nfhwaocefgocz9hmbkkdndnawa8A6mbaLaE9hmeawa8A9hmea3a5cdtfydbcwSmekaYh5awh8AkaYcefgYci9hmbkaaa8Kco4fgoaoRbba5a8Kci4coGtV86bbdndndna3a5cdtfydbgEPDdbbbbbbbebkdncwaE9Tg5TmbcuaEtcu7hwdndnaEceSmbcbh8LaQhXinaXhoa5hYcbhCinaoRbbg8AawcFeGgLa8AaL6EaCaEtVhCaocefhoaYcufgYmbkaKaC86bbaXa5fhXaKcefhKa8La5fg8Lcz6mbxdkkcbh8LaQhXinaXhoa5hYcbhCinaoRbbg8AawcFeGgLa8AaL6EaCcetVhCaocefhoaYcufgYmbkaKaC:T9cFe:d9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:9ca188bbaXa5fhXaKcefhKa8La5fg8Lcz6mbkkcbhoinaKaQaofRbbgC86bbaKaCawcFeG9pfhKaocefgocz9hmbxikkdnaEceSmbinaKcb86bbaKcefhKxbkkinaKcb86bbaKcefhKxbkkaKaX8Pbw83bwaKaX8Pbb83bbaKczfhKka8Kczfg8Ka8J9pgomeaQczfhQagaK9RcK9pmbkkaoTmlaKh3aKTmlkaHcefgHal9hmbkarc;abfaxascufal2falz:wjjjb8Aasamfhma3hoa3mbkcbhwxdkdnagao9RakalfgwcKcaaDEgQawaQ0EgC9pmbcbhwxdkdnawaQ9pmbaocbaCaw9Rgwz:xjjjbawfhokaoarc;adfalz:wjjjbalfhodnaDTmbaoara8Mz:wjjjba8Mfhokaoab9Rhwxekcbhwkarc;qwf8Kjjjjbawk5babaeadaialcdcbyd;i:I:cjbz:bjjjbk9reduaecd4gdaefgicaaica0Eabcj;abae9Uc;WFbGcjdaeca0Egifcufai9Uae2aiadfaicl4cifcd4f2fcefkmbcbabBd;i:I:cjbk;HPeLu8Jjjjjbc;ae9Rgl8Kjjjjbcbhvdnaeaici9UgocHf6mbabcbyd;m:I:cjbgrc;GeV86bbalc;abfcFecjez:xjjjb8Aal9cu83iUal9cu83i8Wal9cu83iyal9cu83iaal9cu83iKal9cu83izal9cu83iwal9cu83ibabaefc9WfhwabcefgDaofhednaiTmbcmcsarcb9kgqEhkcbhxcbhmcbhPcbhscbhzindnaeaw9nmbcbhvxikazcufhvadaPcdtfgHydbhOaHcwfydbhAaHclfydbhCcbhXdndndninalc;abfavcsGcitfgoydlhQdndndnaoydbgoaO9hmbaQaCSmekdnaoaC9hmbaQaA9hmbaXcefhXxekaoaA9hmeaQaO9hmeaXcdfhXkaXc870mdascufhvaHaXcdtgAcxGgoyd:4:G:cjbcdtfydbhQaHaoyd:0:G:cjbcdtfydbhCaHaoyd:W:G:cjbcdtfydbhOcbhodnindnalavcsGcdtfydbaQ9hmbaohXxdkcuhXavcufhvaocefgocz9hmbkkaxaQaxSgvaXce9iaXak9oVgoGfhxdndndncbcsavEaXaoEgvcs9hmbarce9imbaQaQamaQcefamSgvEgmcefSmecmcsavEhvkaDavaAc;WeGV86bbavcs9hmeaQam9Rgvcetavc8F917hvinaecbcjeavcje6EavcFbGV86bbaecefheavcr4gvmbkaQhmxvkcPhvaDaAcPV86bbaQhmkavTmiavak9omicdhocehXazhAxlkavcufhvaXclfgXc;ab9hmbkkdnaHcecdcbaAaxSEaCaxSEcdtgvyd:W:G:cjbcdtfydbgOTaHavyd:0:G:cjbcdtfydbgCceSGaHavyd:4:G:cjbcdtfydbgQcdSGaxcb9hGaqGgLce9hmbal9cu83iUal9cu83i8Wal9cu83iyal9cu83iaal9cu83iKal9cu83izal9cu83iwal9cu83ibcbhxkcbhXascufgvhodnindnalaocsGcdtfydbaC9hmbaXhAxdkcuhAaocufhoaXcefgXcz9hmbkkcbhodnindnalavcsGcdtfydbaQ9hmbaohXxdkcuhXavcufhvaocefgocz9hmbkkaxaOaxSgKfhHdndnaAcm0mbaAcefhAxekcbcsaCaHSgvEhAaHavfhHkdndnaXcm0mbaXcefhXxekcbcsaQaHSgvEhXaHavfhHkc9:cuaKEhYcbhvaXaAcltVg8AcFeGhodndndninavc;q:G:cjbfRbbaoSmeavcefgvcz9hmbxdkkaLaOax9havcm0VVmbaDavc;WeV86bbxekaDaY86bbaea8A86bbaecefhekdnaKmbaOam9Rgvcetavc8F917hvinaecbcjeavcje6EavcFbGV86bbaecefheavcr4gvmbkaOhmkdnaAcs9hmbaCam9Rgvcetavc8F917hvinaecbcjeavcje6EavcFbGV86bbaecefheavcr4gvmbkaChmkdnaXcs9hmbaQam9Rgvcetavc8F917hvinaecbcjeavcje6EavcFbGV86bbaecefheavcr4gvmbkaQhmkalascdtfaOBdbascefcsGhvdndnaAPzbeeeeeeeeeeeeeebekalavcdtfaCBdbascdfcsGhvkdndnaXPzbeeeeeeeeeeeeeebekalavcdtfaQBdbavcefcsGhvkcihoalc;abfazcitfgXaOBdlaXaCBdbazcefcsGhAcdhXavhsaHhxxekcdhoalascdtfaQBdbcehXascefcsGhsazhAkalc;abfaAcitfgvaCBdlavaQBdbalc;abfazaXfcsGcitfgvaQBdlavaOBdbaDcefhDazaofcsGhzaPcifgPai6mbkkdnaeaw9nmbcbhvxekcbhvinaeavfavc;q:G:cjbfRbb86bbavcefgvcz9hmbkaeab9Ravfhvkalc;aef8KjjjjbavkZeeucbhddninadcefgdc8F0meaeceadt0mbkkadcrfcFeGcr9Uci2cdfabci9U2cHfkmbcbabBd;m:I:cjbk:zderu8Jjjjjbcz9Rhlcbhvdnaeaicvf6mbabcbRb;m:I:cjbc;qeV86bbal9cb83iwabcefhvabaefc98fhodnaiTmbcbhecbhrcbhwindnavao6mbcbskadawcdtfydbgDalcwfaraDae9Rgeaec8F91ge7ae9Rc507grcdtfgqydb9Rgec8E91c9:Gaecdt7arVheinavcbcjeaecje6EaecFbGV86bbavcefhvaecr4gembkaqaDBdbaDheawcefgwai9hmbkkdnavao9nmbcbskavcbBbbavab9RclfhvkavkBeeucbhddninadcefgdc8F0meaeceadt0mbkkabadcwfcFeGcr9U2cvfk:dvli99dui99ludnaeTmbcuadcetcuftcu7:Zhvdndncuaicuftcu7:ZgoJbbbZMgr:lJbbb9p9DTmbar:Ohwxekcjjjj94hwkcbhicbhDinalclfIdbgrJbbbbJbbjZalIdbgq:lar:lMalcwfIdbgk:lMgr:varJbbbb9BEgrNhxaqarNhralcxfIdbhqdndnakJbbbb9GTmbaxhkxekJbbjZar:l:tgkak:maxJbbbb9GEhkJbbjZax:l:tgxax:marJbbbb9GEhrkdndnaqJbbj:;aqJbbj:;9GEgxJbbjZaxJbbjZ9FEavNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohmxekcjjjj94hmkdndnakJbbj:;akJbbj:;9GEgqJbbjZaqJbbjZ9FEaoNJbbbZJbbb:;akJbbbb9GEMgq:lJbbb9p9DTmbaq:OhPxekcjjjj94hPkdndnarJbbj:;arJbbj:;9GEgqJbbjZaqJbbjZ9FEaoNJbbbZJbbb:;arJbbbb9GEMgr:lJbbb9p9DTmbar:Ohsxekcjjjj94hskdndnadcl9hmbabaDfgzas86bbazcifam86bbazcdfaw86bbazcefaP86bbxekabaifgzas87ebazcofam87ebazclfaw87ebazcdfaP87ebkaicwfhiaDclfhDalczfhlaecufgembkkk;hlld99eud99eudnaeTmbdndncuaicuftcu7:ZgvJbbbZMgo:lJbbb9p9DTmbao:Ohixekcjjjj94hikaic;8FiGhrinabcofcicdalclfIdb:lalIdb:l9EgialcwfIdb:lalaicdtfIdb:l9EEgialcxfIdb:lalaicdtfIdb:l9EEgiarV87ebdndnJbbj:;JbbjZalaicdtfIdbJbbbb9DEgoalaicd7cdtfIdbJ;Zl:1ZNNgwJbbj:;awJbbj:;9GEgDJbbjZaDJbbjZ9FEavNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohqxekcjjjj94hqkabcdfaq87ebdndnalaicefciGcdtfIdbJ;Zl:1ZNaoNgwJbbj:;awJbbj:;9GEgDJbbjZaDJbbjZ9FEavNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohqxekcjjjj94hqkabaq87ebdndnaoalaicufciGcdtfIdbJ;Zl:1ZNNgoJbbj:;aoJbbj:;9GEgwJbbjZawJbbjZ9FEavNJbbbZJbbb:;aoJbbbb9GEMgo:lJbbb9p9DTmbao:Ohixekcjjjj94hikabclfai87ebabcwfhbalczfhlaecufgembkkk;Pviwue99eu8Jjjjjbcjd9Rgo8Kjjjjbadcd4hrdndndnavcd9hmbarTmbaohdarhwinadc:CuBdbadclfhdawcufgwmbkaeTmdarcdthDalhqcbhkinaohdaqhwarhxinadadydbgmcbawIdbgP:8cL4cFeGc:cufaPJbbbb9BEgsamas9kEBdbawclfhwadclfhdaxcufgxmbkaqaDfhqakcefgkae9hmbxdkkaeTmekarcdthqavce9hhDcbhkindndndnaDmbarTmdc:CuhwalhdarhxinawcbadIdbgP:8cL4cFeGc:cufaPJbbbb9BEgmawam9kEhwadclfhdaxcufgxmbxdkkdndndndnavPleddbdkarTmlaohdalhwarhxinadcbcbawIdbgP:8cL4cFeGgmc:cufgsasam0EaPJbbbb9BEBdbadclfhdawclfhwaxcufgxmbxikkarTmicbhdarhwinaoadfcbaladfIdbgP:8cL4cFeGgxc8Aaxc8A0Ec:cufaPJbbbb9BEBdbadclfhdawcufgwmbxdkkarTmdkc:CuhwkcbhdarhminawhxdnavceSmbaoadfydbhxkdndnaladfIdbgPcjjj;8iaxai9RcefgxcLt9R::NJbbbZJbbb:;aPJbbbb9GEMgP:lJbbb9p9DTmbaP:Ohsxekcjjjj94hskabadfascFFFrGaxcKtVBdbadclfhdamcufgmmbkkabaqfhbalaqfhlakcefgkae9hmbkkaocjdf8Kjjjjbk:Olveue99iue99iudnaeTmbceaicufthvcuaitcu7:Zhocbhradcl9hhwcbhDindndnalcwfIdbgqJbbbbaqJbbbb9GEgqJbbjZaqJbbjZ9FEaoNJbbbZMgq:lJbbb9p9DTmbaq:Ohixekcjjjj94hikdndnalIdbgqJbbbbaqJbbbb9GEgqJbbjZaqJbbjZ9FEaoNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkadai9Rcd9TgkaifhidndnalclfIdbgqJbbbbaqJbbbb9GEgqJbbjZaqJbbjZ9FEaoNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkadai9Rcd9ThddndnalcxfIdbgqJbbbbaqJbbbb9GEgqJbbjZaqJbbjZ9FEaoNJbbbZMgq:lJbbb9p9DTmbaq:Ohxxekcjjjj94hxkadaifhiaxce91avVhxdndnawmbabaDfgmai86bbamcifax86bbamcdfad86bbamcefak86bbxekabarfgmai87ebamcofax87ebamclfad87ebamcdfak87ebkarcwfhraDclfhDalczfhlaecufgembkkk;mqdQui998Jjjjjbc:qd9Rgv8Kjjjjbavc:Sefcbc;Kbz:xjjjb8AdnadTmbaiTmbdndnabaeSmbaehoxekavcuadcdtgradcFFFFi0Ecbyd;q:I:cjbHjjjjbbgoBd:SeavceBd:mdaoaearz:wjjjb8AkavcbBd:Oeav9cb83i:Geavc:Gefaoadaiavc:Sefz:pjjjbavyd:Gehwadci9UgDcbyd;q:I:cjbHjjjjbbheavc:Sefavyd:mdgqcdtfaeBdbavaqcefgrBd:mdaecbaDz:xjjjbhkavc:SefarcdtfcuaicdtaicFFFFi0Ecbyd;q:I:cjbHjjjjbbgxBdbavaqcdfgmBd:mdalc;ebfhPawheaxhrinaralIdbaPaeydbgscwascw6EcdtfIdbMUdbaeclfhearclfhraicufgimbkavc:SefamcdtfcuaDcdtadcFFFF970Ecbyd;q:I:cjbHjjjjbbgmBdbdnadci6mbaoheamhraDhiinaraxaeydbcdtfIdbaxaeclfydbcdtfIdbMaxaecwfydbcdtfIdbMUdbaecxfhearclfhraicufgimbkkaqcifhzalc;ebfhHavc;qbfhOavheavyd:KehAavyd:OehCcbhscbhrcbhXcehQinaehLaoarcx2fgKydbhPaKclfydbhdabaXcx2fgecwfaKcwfydbgYBdbaeclfadBdbaeaPBdbakarfce86bbaOaYBdwaOadBdlaOaPBdbamarcdtfcbBdbcih8AdnasTmbaLhiinaOa8AcdtfaiydbgeBdba8AaeaY9haeaP9haead9hGGfh8AaiclfhiascufgsmbkkaXcefhXcbhsinaCaAaKascdtfydbcdtgifydbcdtfgYheawaifgdydbgPhidnaPTmbdninaeydbarSmeaeclfheaicufgiTmdxbkkaeaYaPcdtfc98fydbBdbadadydbcufBdbkascefgsci9hmbkdndndna8ATmbcuhrJbbbbhEcbhdavyd:KehYavyd:OehKindnawaOadcdtfydbcdtgsfydbgeTmbaxasfgiIdbh3aialcuadadcs0EcdtfclfIdbaHaecwaecw6EcdtfIdbMg5Udba5a3:th5aecdthiaKaYasfydbcdtfheinamaeydbgscdtfgPa5aPIdbMg3Udba3aEaEa39DgPEhEasaraPEhraeclfheaic98fgimbkkadcefgda8A9hmbkarcu9hmekaQaD9pmeindnakaQfRbbmbaQhrxdkaDaQcefgQ9hmbxdkka8Acza8Acz6EhsaOheaLhOarcu9hmekkazTmbaqcdtavc:Seffcwfheinaeydbcbyd;u:I:cjbH:bjjjbbaec98fheazcufgzmbkkavc:qdf8Kjjjjbk:0leoucuaicdtgvaicFFFFi0Egocbyd;q:I:cjbHjjjjbbhralalyd9GgwcdtfarBdbalawcefBd9GabarBdbaocbyd;q:I:cjbHjjjjbbhralalyd9GgocdtfarBdbalaocefBd9GabarBdlcuadcdtadcFFFFi0Ecbyd;q:I:cjbHjjjjbbhralalyd9GgocdtfarBdbalaocefBd9GabarBdwabydbcbavz:xjjjb8AabydbhraehladhvinaralydbcdtfgoaoydbcefBdbalclfhlavcufgvmbkcbhvabydlglhoarhwaihDinaoavBdbaoclfhoawydbavfhvawclfhwaDcufgDmbkadci9Uhqdnadcd9nmbabydwhocbhvinaecwfydbhwaeclfydbhDalaeydbcdtfgbabydbgbcefBdbaoabcdtfavBdbalaDcdtfgDaDydbgDcefBdbaoaDcdtfavBdbalawcdtfgwawydbgwcefBdbaoawcdtfavBdbaecxfheaqavcefgv9hmbkkinalalydbarydb9RBdbarclfhralclfhlaicufgimbkkQbabaeadaic;G:G:cjbz:ojjjbkQbabaeadaic;i:H:cjbz:ojjjbk9DeeuabcFeaicdtz:xjjjbhlcbhbdnadTmbindnalaeydbcdtfgiydbcu9hmbaiabBdbabcefhbkaeclfheadcufgdmbkkabk:3vioud9:du8Jjjjjbc;Wa9Rgl8Kjjjjbcbhvalcxfcbc;Kbz:xjjjb8AalcuadcitgoadcFFFFe0Ecbyd;q:I:cjbHjjjjbbgrBdxalceBd2araeadaicezNjjjbalcuaoadcjjjjoGEcbyd;q:I:cjbHjjjjbbgwBdzadcdthednadTmbabhiinaiavBdbaiclfhiadavcefgv9hmbkkawaefhDalabBdwalawBdl9cbhqindnadTmbaq9cq9:hkarhvaDhiadheinaiav8Pibak1:NcFrG87ebavcwfhvaicdfhiaecufgembkkalclfaq:NceGcdtfydbhxalclfaq9ce98gq:NceGcdtfydbhmalc;Wbfcbcjaz:xjjjb8AaDhvadhidnadTmbinalc;Wbfav8VebcdtfgeaeydbcefBdbavcdfhvaicufgimbkkcbhvcbhiinalc;WbfavfgeydbhoaeaiBdbaoaifhiavclfgvcja9hmbkadhvdndnadTmbinalc;WbfaDamydbgicetf8VebcdtfgeaeydbgecefBdbaxaecdtfaiBdbamclfhmavcufgvmbkaq9cv9smdcbhvinabawydbcdtfavBdbawclfhwadavcefgv9hmbxdkkaq9cv9smekkcwhvcbhiinalcxfavfc98fydbcbyd;u:I:cjbH:bjjjbbaiceGheclhvcehiaeTmbkalc;Waf8Kjjjjbk:Awliuo99iud9:cbhv8Jjjjjbca9Rgocbyd:4:I:cjbBdKaocb8Pd:W:I:cjb83izaocbyd;e:I:cjbBdwaocb8Pd:8:I:cjb83ibaicd4hrdndnadmbJFFuFhwJFFuuhDJFFuuhqJFFuFhkJFFuuhxJFFuFhmxekarcdthPaehsincbhiinaoczfaifgzasaifIdbgwazIdbgDaDaw9EEUdbaoaifgzawazIdbgDaDaw9DEUdbaiclfgicx9hmbkasaPfhsavcefgvad9hmbkaoIdKhDaoIdwhwaoIdChqaoIdlhkaoIdzhxaoIdbhmkdnadTmbJbbbbJbFu9hJbbbbamax:tgmamJbbbb9DEgmakaq:tgkakam9DEgkawaD:tgwawak9DEgw:vawJbbbb9BEhwdnalmbarcdthoindndnaeclfIdbaq:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikai:S9cC:ghHdndnaeIdbax:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikaHai:S:ehHdndnaecwfIdbaD:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabaHai:T9cy:g:e83ibaeaofheabcwfhbadcufgdmbxdkkarcdthoindndnaeIdbax:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikai:SgH9ca:gaH9cz:g9cjjj;4s:d:eaH9cFe:d:e9cF:bj;4:pj;ar:d9c:bd9:9c:p;G:d;4j:E;ar:d9cH9:9c;d;H:W:y:m:g;d;Hb:d9cv9:9c;j:KM;j:KM;j:Kd:dhOdndnaeclfIdbaq:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikai:SgH9ca:gaH9cz:g9cjjj;4s:d:eaH9cFe:d:e9cF:bj;4:pj;ar:d9c:bd9:9c:p;G:d;4j:E;ar:d9cH9:9c;d;H:W:y:m:g;d;Hb:d9cq9:9cM;j:KM;j:KM;jl:daO:ehOdndnaecwfIdbaD:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabaOai:SgH9ca:gaH9cz:g9cjjj;4s:d:eaH9cFe:d:e9cF:bj;4:pj;ar:d9c:bd9:9c:p;G:d;4j:E;ar:d9cH9:9c;d;H:W:y:m:g;d;Hb:d9cC9:9c:KM;j:KM;j:KMD:d:e83ibaeaofheabcwfhbadcufgdmbkkk9teiucbcbyd;y:I:cjbgeabcifc98GfgbBd;y:I:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabk9teiucbcbyd;y:I:cjbgeabcrfc94GfgbBd;y:I:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikTeeucbabcbyd;y:I:cjbge9Rcifc98GaefgbBd;y:I:cjbdnabZbcztge9nmbabae9RcFFifcz4nb8Akkk;Sddbcj:Gdk;idbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbbbbbbbbbbbbbbbbebbbdbbbbbbbebbbbbbbbbbbbbbbb4:h9w9N94:P:gW:j9O:ye9Pbbbbbb:l29hZ;69:9kZ;N;76Z;rg97Z;z;o9xZ8J;B85Z;:;u9yZ;b;k9HZ:2;Z9DZ9e:l9mZ59A8KZ:r;T3Z:A:zYZ79OHZ;j4::8::Y:D9V8:bbbb9s:49:Z8R:hBZ9M9M;M8:L;z;o8:;8:PG89q;x:J878R:hQ8::M:B;e87bbbbbbjZbbjZbbjZ:E;V;N8::Y:DsZ9i;H;68:xd;R8:;h0838:;W:NoZbbbb:WV9O8:uf888:9i;H;68:9c9G;L89;n;m9m89;D8Ko8:bbbbf:8tZ9m836ZS:2AZL;zPZZ818EZ9e:lxZ;U98F8:819E;68:FFuuFFuuFFuuFFuFFFuFFFuFbc;i:IdkCebbbebbbebbbdbbb9G:rbb",t=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!=="object")return{supported:!1};var n,i=WebAssembly.instantiate(r(e),{}).then(function(h){n=h.instance,n.exports.__wasm_call_ctors(),n.exports.meshopt_encodeVertexVersion(1),n.exports.meshopt_encodeIndexVersion(1)});function r(h){var b=new Uint8Array(h.length);for(var m=0;m<h.length;++m){var g=h.charCodeAt(m);b[m]=g>96?g-97:g>64?g-39:g+4}var p=0;for(var m=0;m<h.length;++m)b[p++]=b[m]<60?t[b[m]]:(b[m]-60)*64+b[++m];return b.buffer.slice(0,p)}function s(h){if(!h)throw Error("Assertion failed")}function a(h){return new Uint8Array(h.buffer,h.byteOffset,h.byteLength)}function o(h,b,m,g){var p=n.exports.sbrk,x=p(b.length*4),_=p(m*4),y=new Uint8Array(n.exports.memory.buffer),v=a(b);if(y.set(v,x),g)g(x,x,b.length,m);var T=h(_,x,b.length,m);y=new Uint8Array(n.exports.memory.buffer);var A=new Uint32Array(m);new Uint8Array(A.buffer).set(y.subarray(_,_+m*4)),v.set(y.subarray(x,x+b.length*4)),p(x-p(0));for(var E=0;E<b.length;++E)b[E]=A[b[E]];return[A,T]}function c(h,b,m,g){var p=n.exports.sbrk,x=p(m*4),_=p(m*g),y=new Uint8Array(n.exports.memory.buffer);y.set(a(b),_),h(x,_,m,g),y=new Uint8Array(n.exports.memory.buffer);var v=new Uint32Array(m);return new Uint8Array(v.buffer).set(y.subarray(x,x+m*4)),p(x-p(0)),v}function l(h,b,m,g,p,x,_){var y=n.exports.sbrk,v=y(b),T=y(g*p),A=new Uint8Array(n.exports.memory.buffer);A.set(a(m),T);var E=h(v,b,T,g,p,x,_),w=new Uint8Array(E);return w.set(A.subarray(v,v+E)),y(v-y(0)),w}function u(h){var b=0;for(var m=0;m<h.length;++m){var g=h[m];b=b<g?g:b}return b}function d(h,b){if(s(b==2||b==4),b==4)return new Uint32Array(h.buffer,h.byteOffset,h.byteLength/4);else{var m=new Uint16Array(h.buffer,h.byteOffset,h.byteLength/2);return new Uint32Array(m)}}function f(h,b,m,g,p,x,_){var y=n.exports.sbrk,v=y(m*g),T=y(m*x),A=new Uint8Array(n.exports.memory.buffer);A.set(a(b),T),h(v,m,g,p,T,_);var E=new Uint8Array(m*g);return E.set(A.subarray(v,v+m*g)),y(v-y(0)),E}return{ready:i,supported:!0,reorderMesh:function(h,b,m){s(h instanceof Uint32Array||h instanceof Int32Array),s(!b||h.length%3==0);var g=b?m?n.exports.meshopt_optimizeVertexCacheStrip:n.exports.meshopt_optimizeVertexCache:void 0;return o(n.exports.meshopt_optimizeVertexFetchRemap,h,u(h)+1,g)},reorderPoints:function(h,b){return s(h instanceof Float32Array),s(h.length%b==0),s(b>=3),c(n.exports.meshopt_spatialSortRemap,h,h.length/b,b*4)},encodeVertexBuffer:function(h,b,m){s(m>0&&m<=256),s(m%4==0);var g=n.exports.meshopt_encodeVertexBufferBound(b,m);return l(n.exports.meshopt_encodeVertexBuffer,g,h,b,m)},encodeVertexBufferLevel:function(h,b,m,g,p){s(m>0&&m<=256),s(m%4==0),s(g>=0&&g<=3),s(p===void 0||p==0||p==1);var x=n.exports.meshopt_encodeVertexBufferBound(b,m);return l(n.exports.meshopt_encodeVertexBufferLevel,x,h,b,m,g,p===void 0?-1:p)},encodeIndexBuffer:function(h,b,m){s(m==2||m==4),s(b%3==0);var g=d(h,m),p=n.exports.meshopt_encodeIndexBufferBound(b,u(g)+1);return l(n.exports.meshopt_encodeIndexBuffer,p,g,b,4)},encodeIndexSequence:function(h,b,m){s(m==2||m==4);var g=d(h,m),p=n.exports.meshopt_encodeIndexSequenceBound(b,u(g)+1);return l(n.exports.meshopt_encodeIndexSequence,p,g,b,4)},encodeGltfBuffer:function(h,b,m,g,p){var x={ATTRIBUTES:this.encodeVertexBufferLevel,TRIANGLES:this.encodeIndexBuffer,INDICES:this.encodeIndexSequence};return s(x[g]),x[g](h,b,m,2,p===void 0?0:p)},encodeFilterOct:function(h,b,m,g){return s(m==4||m==8),s(g>=2&&g<=16),f(n.exports.meshopt_encodeFilterOct,h,b,m,g,16)},encodeFilterQuat:function(h,b,m,g){return s(m==8),s(g>=4&&g<=16),f(n.exports.meshopt_encodeFilterQuat,h,b,m,g,16)},encodeFilterExp:function(h,b,m,g,p){s(m>0&&m%4==0),s(g>=1&&g<=24);var x={Separate:0,SharedVector:1,SharedComponent:2,Clamped:3};return s(!p||p in x),f(n.exports.meshopt_encodeFilterExp,h,b,m,g,m,p?x[p]:1)},encodeFilterColor:function(h,b,m,g){return s(m==4||m==8),s(g>=2&&g<=16),f(n.exports.meshopt_encodeFilterColor,h,b,m,g,16)}}}()});var BW;var pR=mt(()=>{BW=function(){var e="b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuixkbeeeddddillviebeoweuecj:Gdkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WboY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbrl79IV9Rbwq:VZkdbk:XYi5ud9:du8Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxcj;abad9Uc;WFbGcjdadca0EhmaialfgPar9Rgoadfhsavaoadz:jjjjbgzceVhHcbhOdndninaeaO9nmeaPax9RaD6mdamaeaO9RaOamfgoae6EgAcsfglc9WGhCabaOad2fhXaAcethQaxaDfhiaOaeaoaeao6E9RhLalcl4cifcd4hKazcj;cbfaAfhYcbh8AazcjdfhEaHh3incbh5dnawTmbaxa8Acd4fRbbh5kcbh8Eazcj;cbfhqinaih8Fdndndndna5a8Ecet4ciGgoc9:fPdebdkaPa8F9RaA6mrazcj;cbfa8EaA2fa8FaAz:jjjjb8Aa8FaAfhixdkazcj;cbfa8EaA2fcbaAz:kjjjb8Aa8FhixekaPa8F9RaK6mva8FaKfhidnaCTmbaPai9RcK6mbaocdtc:q:G:cjbfcj:G:cjbawEhaczhrcbhlinargoc9Wfghaqfhrdndndndndndnaaa8Fahco4fRbbalcoG4ciGcdtfydbPDbedvivvvlvkar9cb83bwar9cb83bbxlkarcbaiRbdai8Xbb9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbaqaofgrcGfcbaicdfa8J9c8N1:NfghRbbag9cjjjjjw:dg8J9qE86bbarcVfcbaha8J9c8M1:NfghRbbag9cjjjjjl:dg8J9qE86bbarc7fcbaha8J9c8L1:NfghRbbag9cjjjjjd:dg8J9qE86bbarctfcbaha8J9c8K1:NfghRbbag9cjjjjje:dg8J9qE86bbarc91fcbaha8J9c8J1:NfghRbbag9cjjjj;ab:dg8J9qE86bbarc4fcbaha8J9cg1:NfghRbbag9cjjjja:dg8J9qE86bbarc93fcbaha8J9ch1:NfghRbbag9cjjjjz:dgg9qE86bbarc94fcbahag9ca1:NfghRbbai8Xbe9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbarc95fcbaha8J9c8N1:NfgiRbbag9cjjjjjw:dg8J9qE86bbarc96fcbaia8J9c8M1:NfgiRbbag9cjjjjjl:dg8J9qE86bbarc97fcbaia8J9c8L1:NfgiRbbag9cjjjjjd:dg8J9qE86bbarc98fcbaia8J9c8K1:NfgiRbbag9cjjjjje:dg8J9qE86bbarc99fcbaia8J9c8J1:NfgiRbbag9cjjjj;ab:dg8J9qE86bbarc9:fcbaia8J9cg1:NfgiRbbag9cjjjja:dg8J9qE86bbarcufcbaia8J9ch1:NfgiRbbag9cjjjjz:dgg9qE86bbaiag9ca1:NfhixikaraiRblaiRbbghco4g8Ka8KciSg8KE86bbaqaofgrcGfaiclfa8Kfg8KRbbahcl4ciGg8La8LciSg8LE86bbarcVfa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc7fa8Ka8Lfg8KRbbahciGghahciSghE86bbarctfa8Kahfg8KRbbaiRbeghco4g8La8LciSg8LE86bbarc91fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc4fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc93fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc94fa8Kahfg8KRbbaiRbdghco4g8La8LciSg8LE86bbarc95fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc96fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc97fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc98fa8KahfghRbbaiRbigico4g8Ka8KciSg8KE86bbarc99faha8KfghRbbaicl4ciGg8Ka8KciSg8KE86bbarc9:faha8KfghRbbaicd4ciGg8Ka8KciSg8KE86bbarcufaha8KfgrRbbaiciGgiaiciSgiE86bbaraifhixdkaraiRbwaiRbbghcl4g8Ka8KcsSg8KE86bbaqaofgrcGfaicwfa8Kfg8KRbbahcsGghahcsSghE86bbarcVfa8KahfghRbbaiRbeg8Kcl4g8La8LcsSg8LE86bbarc7faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarctfaha8KfghRbbaiRbdg8Kcl4g8La8LcsSg8LE86bbarc91faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc4faha8KfghRbbaiRbig8Kcl4g8La8LcsSg8LE86bbarc93faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc94faha8KfghRbbaiRblg8Kcl4g8La8LcsSg8LE86bbarc95faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc96faha8KfghRbbaiRbvg8Kcl4g8La8LcsSg8LE86bbarc97faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc98faha8KfghRbbaiRbog8Kcl4g8La8LcsSg8LE86bbarc99faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc9:faha8KfghRbbaiRbrgicl4g8Ka8KcsSg8KE86bbarcufaha8KfgrRbbaicsGgiaicsSgiE86bbaraifhixekarai8Pbw83bwarai8Pbb83bbaiczfhikdnaoaC9pmbalcdfhlaoczfhraPai9RcL0mekkaoaC6moaimexokaCmva8FTmvkaqaAfhqa8Ecefg8Ecl9hmbkdndndndnawTmbasa8Acd4fRbbgociGPlbedrbkaATmdaza8Afh8Fazcj;cbfhhcbh8EaEhaina8FRbbhraahocbhlinaoahalfRbbgqce4cbaqceG9R7arfgr86bbaoadfhoaAalcefgl9hmbkaacefhaa8Fcefh8FahaAfhha8Ecefg8Ecl9hmbxikkaATmeaza8Afhaazcj;cbfhhcbhoceh8EaYh8FinaEaofhlaa8Vbbhrcbhoinala8FaofRbbcwtahaofRbbgqVc;:FiGce4cbaqceG9R7arfgr87bbaladfhlaLaocefgofmbka8FaQfh8FcdhoaacdfhaahaQfhha8EceGhlcbh8EalmbxdkkaATmbaocl4h8Eaza8AfRbbhqcwhoa3hlinalRbbaotaqVhqalcefhlaocwfgoca9hmbkcbhhaEh8FaYhainazcj;cbfahfRbbhrcwhoaahlinalRbbaotarVhralaAfhlaocwfgoca9hmbkara8E94aq7hqcbhoa8Fhlinalaqao486bbalcefhlaocwfgoca9hmbka8Fadfh8FaacefhaahcefghaA9hmbkkaEclfhEa3clfh3a8Aclfg8Aad6mbkaXazcjdfaAad2z:jjjjb8AazazcjdfaAcufad2fadz:jjjjb8AaAaOfhOaihxaimbkc9:hoxdkcbc99aPax9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaok:ysezu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnalaeci9UgrcHf6mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:kjjjb8Aav9cu83iUav9cu83i8Wav9cu83iyav9cu83iaav9cu83iKav9cu83izav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbavaiaqaDcsGfRbbgscl4gP9RcsGcdtfydbaxcefgOaPEhDavaias9RcsGcdtfydbaOaPTgzfgOascsGgPEhsaPThPdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiazfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaPfhiaOaPfhxxekaxcbalRbbgsEgHaDc;:eSgDfhOascsGhAdndnascl4gCmbaOcefhzxekaOhzavaiaC9RcsGcdtfydbhOkdndnaAmbazcefhxxekazhxavaias9RcsGcdtfydbhzkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhHascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaHhDxekaDcefhDkasce4cbasceG9R7amfgmhHkdndnaCcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhOaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkaOhsxekascefhskaPce4cbaPceG9R7amfgmhOkdndnaAcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhzaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkazhlxekalcefhlkaPce4cbaPceG9R7amfgmhzkdndnadcd9hmbabarcetfgDaH87ebaDclfaz87ebaDcdfaO87ebxekabarcdtfgDaHBdbaDcwfazBdbaDclfaOBdbkavc;abfaocitfgDaOBdbaDaHBdlavaicdtfaHBdbavc;abfaocefcsGcitfgDazBdbaDaOBdlavaicefgicsGcdtfaOBdbavc;abfaocdfcsGcitfgDaHBdbaDazBdlavaiaCTaCcsSVfgicsGcdtfazBdbaiaATaAcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnalaecvf9pmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk:4ioiue99dud99dud99dnaeTmbcbhiabhlindndnal8Uebgv:YgoJ:ji:1Salcof8UebgrciVgw:Y:vgDNJbbbZJbbb:;avcu9kEMgq:lJbbb9p9DTmbaq:Ohkxekcjjjj94hkkalclf8Uebhvalcdf8UebhxalarcefciGcetfak87ebdndnax:YgqaDNJbbbZJbbb:;axcu9kEMgm:lJbbb9p9DTmbam:Ohxxekcjjjj94hxkabaiarciGgkfcd7cetfax87ebdndnav:YgmaDNJbbbZJbbb:;avcu9kEMgP:lJbbb9p9DTmbaP:Ohvxekcjjjj94hvkalarcufciGcetfav87ebdndnawaw2:ZgPaPMaoaoN:taqaqN:tamamN:tgoJbbbbaoJbbbb9GE:raDNJbbbZMgD:lJbbb9p9DTmbaD:Ohrxekcjjjj94hrkalakcetfar87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2gdTmbinababydbgecwtcw91:Yaece91cjjj98Gcjjj;8if::NUdbabclfhbadcufgdmbkkk:Tvirud99eudndnadcl9hmbaeTmeindndnabRbbgiabcefgl8Sbbgvabcdfgo8Sbbgrf9R:YJbbuJabcifgwRbbgdce4adVgDcd4aDVgDcl4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax86bbdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao86bbdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai86bbdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad86bbabclfhbaecufgembxdkkaeTmbindndnab8Vebgiabcdfgl8Uebgvabclfgo8Uebgrf9R:YJbFu9habcofgw8Vebgdce4adVgDcd4aDVgDcl4aDVgDcw4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax87ebdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao87ebdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai87ebdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad87ebabcwfhbaecufgembkkk9teiucbcbyd:K:G:cjbgeabcifc98GfgbBd:K:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkk83dbcj:Gdk8Kbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbc:K:Gdkl8W:qbb",t="b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuixkbbebeeddddilve9Weeeviebeoweuecj:Gdkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WbwY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbDl79IV9Rbqq:W9Dklbzik94evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaeai86b:q:W:cjbaecitab8Piw83i:q:G:cjbaecefgecjd9hmbkk:JBl8Aud97dur978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaialfgxar9RhodnadTgmmbavaoad;8qbbkaicefhPcj;abad9Uc;WFbGcjdadca0EhsdndndnadTmbaoadfhzcbhHinaeaH9nmdaxaP9RaD6miabaHad2fhOaPaDfhAasaeaH9RaHasfae6EgCcsfgocl4cifcd4hXavcj;cbfaoc9WGgQcetfhLavcj;cbfaQci2fhKavcj;cbfaQfhYcbh8Aaoc;ab6hEincbh3dnawTmbaPa8Acd4fRbbh3kcbh5avcj;cbfh8Eindndndndna3a5cet4ciGgoc9:fPdebdkaxaA9RaQ6mwdnaQTmbavcj;cbfa5aQ2faAaQ;8qbbkaAaCfhAxdkaQTmeavcj;cbfa5aQ2fcbaQ;8kbxekaxaA9RaX6moaoclVcbawEhraAaXfhocbhidnaEmbaxao9Rc;Gb6mbcbhlina8EalfhidndndndndndnaAalco4fRbbgqciGarfPDbedibledibkaipxbbbbbbbbbbbbbbbbpklbxlkaiaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaoclffagRb:q:W:cjbfhoxikaiaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaocwffagRb:q:W:cjbfhoxdkaiaopbbbpklbaoczfhoxekaiaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbahaocdffagRb:q:W:cjbfhokdndndndndndnaqcd4ciGarfPDbedibledibkaiczfpxbbbbbbbbbbbbbbbbpklbxlkaiczfaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaoclffagRb:q:W:cjbfhoxikaiczfaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaocwffagRb:q:W:cjbfhoxdkaiczfaopbbbpklbaoczfhoxekaiczfaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbahaocdffagRb:q:W:cjbfhokdndndndndndnaqcl4ciGarfPDbedibledibkaicafpxbbbbbbbbbbbbbbbbpklbxlkaicafaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaoclffagRb:q:W:cjbfhoxikaicafaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaocwffagRb:q:W:cjbfhoxdkaicafaopbbbpklbaoczfhoxekaicafaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbahaocdffagRb:q:W:cjbfhokdndndndndndnaqco4arfPDbedibledibkaic8Wfpxbbbbbbbbbbbbbbbbpklbxlkaic8Wfaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Ngicitpbi:q:G:cjbaiRb:q:W:cjbgipsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbaiaoclffaqRb:q:W:cjbfhoxikaic8Wfaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Ngicitpbi:q:G:cjbaiRb:q:W:cjbgipsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbaiaocwffaqRb:q:W:cjbfhoxdkaic8Wfaopbbbpklbaoczfhoxekaic8WfaopbbdaoRbbgicitpbi:q:G:cjbaiRb:q:W:cjbgipsaoRbegqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbaiaocdffaqRb:q:W:cjbfhokalc;abfhialcjefaQ0meaihlaxao9Rc;Fb0mbkkdnaiaQ9pmbaici4hlinaxao9RcK6mwa8EaifhqdndndndndndnaAaico4fRbbalcoG4ciGarfPDbedibledibkaqpxbbbbbbbbbbbbbbbbpkbbxlkaqaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spkbbahaoclffagRb:q:W:cjbfhoxikaqaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spkbbahaocwffagRb:q:W:cjbfhoxdkaqaopbbbpkbbaoczfhoxekaqaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpkbbahaocdffagRb:q:W:cjbfhokalcdfhlaiczfgiaQ6mbkkaohAaoTmoka8EaQfh8Ea5cefg5cl9hmbkdndndndnawTmbaza8Acd4fRbbglciGPlbedwbkaQTmdavcjdfa8Afhlava8Afpbdbh8Jcbhoinalavcj;cbfaofpblbg8KaYaofpblbg8LpmbzeHdOiAlCvXoQrLg8MaLaofpblbg8NaKaofpblbgypmbzeHdOiAlCvXoQrLg8PpmbezHdiOAlvCXorQLg8Fcep9Ta8Fpxeeeeeeeeeeeeeeeegap9op9Hp9rg8Fa8Jp9Ug8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9Abbbaladfgla8Ja8Ma8PpmwDKYqk8AExm35Ps8E8Fg8Fcep9Ta8Faap9op9Hp9rg8Fp9Ug8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9Abbbaladfgla8Ja8Ka8LpmwKDYq8AkEx3m5P8Es8Fg8Ka8NaypmwKDYq8AkEx3m5P8Es8Fg8LpmbezHdiOAlvCXorQLg8Fcep9Ta8Faap9op9Hp9rg8Fp9Ug8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9Abbbaladfgla8Ja8Ka8LpmwDKYqk8AExm35Ps8E8Fg8Fcep9Ta8Faap9op9Hp9rg8Fp9Ugap9Abbbaladfglaaa8Fa8Fpmlvorlvorlvorlvorp9Ugap9Abbbaladfglaaa8Fa8FpmwDqkwDqkwDqkwDqkp9Ugap9Abbbaladfglaaa8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9AbbbaladfhlaoczfgoaQ6mbxikkaQTmeavcjdfa8Afhlava8Afpbdbh8Jcbhoinalavcj;cbfaofpblbg8KaYaofpblbg8LpmbzeHdOiAlCvXoQrLg8MaLaofpblbg8NaKaofpblbgypmbzeHdOiAlCvXoQrLg8PpmbezHdiOAlvCXorQLg8Fcep:nea8Fpxebebebebebebebebgap9op:bep9rg8Fa8Jp:oeg8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9Abbbaladfgla8Ja8Ma8PpmwDKYqk8AExm35Ps8E8Fg8Fcep:nea8Faap9op:bep9rg8Fp:oeg8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9Abbbaladfgla8Ja8Ka8LpmwKDYq8AkEx3m5P8Es8Fg8Ka8NaypmwKDYq8AkEx3m5P8Es8Fg8LpmbezHdiOAlvCXorQLg8Fcep:nea8Faap9op:bep9rg8Fp:oeg8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9Abbbaladfgla8Ja8Ka8LpmwDKYqk8AExm35Ps8E8Fg8Fcep:nea8Faap9op:bep9rg8Fp:oegap9Abbbaladfglaaa8Fa8Fpmlvorlvorlvorlvorp:oegap9Abbbaladfglaaa8Fa8FpmwDqkwDqkwDqkwDqkp:oegap9Abbbaladfglaaa8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9AbbbaladfhlaoczfgoaQ6mbxdkkaQTmbcbhocbalcl4gl9Rc8FGhiavcjdfa8Afhrava8Afpbdbhainaravcj;cbfaofpblbg8JaYaofpblbg8KpmbzeHdOiAlCvXoQrLg8LaLaofpblbg8MaKaofpblbg8NpmbzeHdOiAlCvXoQrLgypmbezHdiOAlvCXorQLg8Faip:Rea8Falp:Tep9qg8Faap9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9Abbbaradfgraaa8LaypmwDKYqk8AExm35Ps8E8Fg8Faip:Rea8Falp:Tep9qg8Fp9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9Abbbaradfgraaa8Ja8KpmwKDYq8AkEx3m5P8Es8Fg8Ja8Ma8NpmwKDYq8AkEx3m5P8Es8Fg8KpmbezHdiOAlvCXorQLg8Faip:Rea8Falp:Tep9qg8Fp9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9Abbbaradfgraaa8Ja8KpmwDKYqk8AExm35Ps8E8Fg8Faip:Rea8Falp:Tep9qg8Fp9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9AbbbaradfhraoczfgoaQ6mbkka8Aclfg8Aad6mbkdnaCad2goTmbaOavcjdfao;8qbbkdnammbavavcjdfaCcufad2fad;8qbbkaCaHfhHc9:hoaAhPaAmbxlkkaeTmbaDalfhrcbhocuhlinaralaD9RglfaD6mdasaeao9Raoasfae6Eaofgoae6mbkaial9RhPkcbc99axaP9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaokwbz:bjjjbkNsezu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnalaeci9UgrcHf6mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbav9cu83iUav9cu83i8Wav9cu83iyav9cu83iaav9cu83iKav9cu83izav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbavaiaqaDcsGfRbbgscl4gP9RcsGcdtfydbaxcefgOaPEhDavaias9RcsGcdtfydbaOaPTgzfgOascsGgPEhsaPThPdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiazfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaPfhiaOaPfhxxekaxcbalRbbgsEgHaDc;:eSgDfhOascsGhAdndnascl4gCmbaOcefhzxekaOhzavaiaC9RcsGcdtfydbhOkdndnaAmbazcefhxxekazhxavaias9RcsGcdtfydbhzkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhHascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaHhDxekaDcefhDkasce4cbasceG9R7amfgmhHkdndnaCcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhOaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkaOhsxekascefhskaPce4cbaPceG9R7amfgmhOkdndnaAcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhzaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkazhlxekalcefhlkaPce4cbaPceG9R7amfgmhzkdndnadcd9hmbabarcetfgDaH87ebaDclfaz87ebaDcdfaO87ebxekabarcdtfgDaHBdbaDcwfazBdbaDclfaOBdbkavc;abfaocitfgDaOBdbaDaHBdlavaicdtfaHBdbavc;abfaocefcsGcitfgDazBdbaDaOBdlavaicefgicsGcdtfaOBdbavc;abfaocdfcsGcitfgDaHBdbaDazBdlavaiaCTaCcsSVfgicsGcdtfazBdbaiaATaAcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnalaecvf9pmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk;Toio97eue97aec98Ghedndnadcl9hmbaeTmecbhdinababpbbbgicKp:RecKp:Sep;6eglaicwp:RecKp:Sep;6ealp;Geaiczp:RecKp:Sep;6egvp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egralpxbbbjbbbjbbbjbbbjgwp9op9rp;Keglpxbb;:9cbb;:9cbb;:9cbb;:9calalp;Meaoaop;Meavaravawp9op9rp;Keglalp;Mep;Kep;Kep;Jep;Negvp;Mepxbbn0bbn0bbn0bbn0grp;KepxFbbbFbbbFbbbFbbbp9oaipxbbbFbbbFbbbFbbbFp9op9qalavp;Mearp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaoavp;Mearp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbabczfhbadclfgdae6mbxdkkaeTmbcbhdinabczfgDaDpbbbgipxbbbbbbFFbbbbbbFFgwp9oabpbbbgoaipmbediwDqkzHOAKY8AEgvczp:Reczp:Sep;6eglaoaipmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eavczp:Sep;6egvp;Gealp;Gep;Kep;Legipxbbbbbbbbbbbbbbbbp:2egralpxbbbjbbbjbbbjbbbjgqp9op9rp;Keglpxb;:FSb;:FSb;:FSb;:FSalalp;Meaiaip;Meavaravaqp9op9rp;Keglalp;Mep;Kep;Kep;Jep;Negvp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbp9oaiavp;Mearp;Keczp:Rep9qgialavp;Mearp;KepxFFbbFFbbFFbbFFbbp9oglpmwDKYqk8AExm35Ps8E8Fp9qpkbbabaoawp9oaialpmbezHdiOAlvCXorQLp9qpkbbabcafhbadclfgdae6mbkkk;2ileue97euo97dnaec98GgiTmbcbheinabcKfpx:ji:1S:ji:1S:ji:1S:ji:1SabpbbbglabczfgvpbbbgopmlvorxmPsCXQL358E8Fgrczp:Segwpxibbbibbbibbbibbbp9qp;6egDp;NegqaDaDp;MegDaDp;KealaopmbediwDqkzHOAKY8AEgDczp:Reczp:Sep;6eglalp;MeaDczp:Sep;6egoaop;Mearczp:Reczp:Sep;6egrarp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gDp;KepxFFbbFFbbFFbbFFbbgkp9oaqaop;MeaDp;Keczp:Rep9qgoaqalp;MeaDp;Keakp9oaqarp;MeaDp;Keczp:Rep9qgDpmwDKYqk8AExm35Ps8E8Fglp5eawclp:RegqpEi:T:j83ibavalp5baqpEd:T:j83ibabcwfaoaDpmbezHdiOAlvCXorQLgDp5eaqpEe:T:j83ibabaDp5baqpEb:T:j83ibabcafhbaeclfgeai6mbkkkuee97dnadcd4ae2c98GgeTmbcbhdinababpbbbgicwp:Recwp:Sep;6eaicep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepkbbabczfhbadclfgdae6mbkkk:Sodw97euaec98Ghedndnadcl9hmbaeTmecbhdinabpxbbuJbbuJbbuJbbuJabpbbbgicKp:TeglaicYp:Tep9qgvcdp:Teavp9qgvclp:Teavp9qgop;6ep;Negvaicwp:RecKp:SegraipxFbbbFbbbFbbbFbbbgwp9ogDp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oavaDarp:Xeaiczp:RecKp:Segip:Uep;6ep;Meaqp;Keawp9op9qavaDaraip:Uep:Xep;6ep;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qavaoalcep:Rep9oalpxebbbebbbebbbebbbp9op9qp;6ep;Meaqp;KecKp:Rep9qpkbbabczfhbadclfgdae6mbxdkkaeTmbcbhdinabczfgkpxbFu9hbFu9hbFu9hbFu9habpbbbglakpbbbgrpmlvorxmPsCXQL358E8Fgvczp:TegqavcHp:Tep9qgicdp:Teaip9qgiclp:Teaip9qgicwp:Teaip9qgop;6ep;NegialarpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbglp9ograDczp:Segwp:Ueavczp:Reczp:SegDp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gvp;Kealp9oaiarawaDp:Uep:Xep;6ep;Meavp;Keczp:Rep9qgwaiaoaqcep:Rep9oaqpxebbbebbbebbbebbbp9op9qp;6ep;Meavp;Keczp:ReaiaDarp:Uep;6ep;Meavp;Kealp9op9qgipmwDKYqk8AExm35Ps8E8FpkbbabawaipmbezHdiOAlvCXorQLpkbbabcafhbadclfgdae6mbkkk9teiucbcbydj:G:cjbgeabcifc98GfgbBdj:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkxebcj:Gdklz:zbb",n=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),i=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!=="object")return{supported:!1};var r=WebAssembly.validate(n)?o(t):o(e),s,a=WebAssembly.instantiate(r,{}).then(function(p){s=p.instance,s.exports.__wasm_call_ctors()});function o(p){var x=new Uint8Array(p.length);for(var _=0;_<p.length;++_){var y=p.charCodeAt(_);x[_]=y>96?y-97:y>64?y-39:y+4}var v=0;for(var _=0;_<p.length;++_)x[v++]=x[_]<60?i[x[_]]:(x[_]-60)*64+x[++_];return x.buffer.slice(0,v)}function c(p,x,_,y,v,T,A){var E=p.exports.sbrk,w=y+3&-4,P=E(w*v),S=E(T.length),I=new Uint8Array(p.exports.memory.buffer);I.set(T,S);var U=x(P,y,v,S,T.length);if(U==0&&A)A(P,w,v);if(_.set(I.subarray(P,P+y*v)),E(P-E(0)),U!=0)throw Error("Malformed buffer data: "+U)}var l={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp",COLOR:"meshopt_decodeFilterColor"},u={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"},d=[],f=0;function h(p){var x={object:new Worker(p),pending:0,requests:{}};return x.object.onmessage=function(_){var y=_.data;x.pending-=y.count,x.requests[y.id][y.action](y.value),delete x.requests[y.id]},x}function b(p){var x="self.ready = WebAssembly.instantiate(new Uint8Array(["+new Uint8Array(r)+"]), {}).then(function(result) { result.instance.exports.__wasm_call_ctors(); return result.instance; });self.onmessage = "+g.name+";"+c.toString()+g.toString(),_=new Blob([x],{type:"text/javascript"}),y=URL.createObjectURL(_);for(var v=d.length;v<p;++v)d[v]=h(y);for(var v=p;v<d.length;++v)d[v].object.postMessage({});d.length=p,URL.revokeObjectURL(y)}function m(p,x,_,y,v){var T=d[0];for(var A=1;A<d.length;++A)if(d[A].pending<T.pending)T=d[A];return new Promise(function(E,w){var P=new Uint8Array(_),S=++f;T.pending+=p,T.requests[S]={resolve:E,reject:w},T.object.postMessage({id:S,count:p,size:x,source:P,mode:y,filter:v},[P.buffer])})}function g(p){var x=p.data;self.ready.then(function(_){if(!x.id)return self.close();try{var y=new Uint8Array(x.count*x.size);c(_,_.exports[x.mode],y,x.count,x.size,x.source,_.exports[x.filter]),self.postMessage({id:x.id,count:x.count,action:"resolve",value:y},[y.buffer])}catch(v){self.postMessage({id:x.id,count:x.count,action:"reject",value:v})}})}return{ready:a,supported:!0,useWorkers:function(p){b(p)},decodeVertexBuffer:function(p,x,_,y,v){c(s,s.exports.meshopt_decodeVertexBuffer,p,x,_,y,s.exports[l[v]])},decodeIndexBuffer:function(p,x,_,y){c(s,s.exports.meshopt_decodeIndexBuffer,p,x,_,y)},decodeIndexSequence:function(p,x,_,y){c(s,s.exports.meshopt_decodeIndexSequence,p,x,_,y)},decodeGltfBuffer:function(p,x,_,y,v,T){c(s,s.exports[u[v]],p,x,_,y,s.exports[l[T]])},decodeGltfBufferAsync:function(p,x,_,y,v){if(d.length>0)return m(p,x,_,u[y],l[v]);return a.then(function(){var T=new Uint8Array(p*x);return c(s,s.exports[u[y]],T,p,x,_,s.exports[l[v]]),T})}}}()});var VW;var mR=mt(()=>{VW=function(){var e="b9H79Tebbbe:6eO9Geueu9Geub9Gbb9Gsuuuuuuuuuuuu99uueu9Gvuuuuub9Gruuuuuuub9Gouuuuuue999Gvuuuuueu9Gzuuuuuuuuuuu99uuuub9Gquuuuuuu99uueu9GPuuuuuuuuuuu99uueu9Gquuuuuuuu99ueu9Gruuuuuu99eu9Gwuuuuuu99ueu9Giuuue999Gluuuueu9Gluuuub9GiuuueuiLQdilvorlwDiqkxmPszbHHbelve9Weiiviebeoweuecj:Gdkr:Bdxo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bbz9TW79O9V9Wt9F79P9T9W29P9M95bw8E9TW79O9V9Wt9F79P9T9W29P9M959x9Pt9OcttV9P9I91tW7bD8A9TW79O9V9Wt9F79P9T9W29P9M959x9Pt9O9v9W9K9HtWbqQ9TW79O9V9Wt9F79P9T9W29P9M959t29V9W9W95bkX9TW79O9V9Wt9F79P9T9W29P9M959qV919UWbxQ9TW79O9V9Wt9F79P9T9W29P9M959q9V9P9Ut7bmX9TW79O9V9Wt9F79P9T9W29P9M959t9J9H2WbPa9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94SWt9J9O9sW9T9H9Wbs59TW79O9V9Wt9F9NW9UWV9HtW9q9V79Pt9P9V9U9sW9T9H9Wbzl79IV9RbHDwebcekdCXq;y;WeQdbk;r:herYue99iuY99Xue9:D998Jjjjjbcj;sb9Rgs8Kjjjjbcbhzasc:Cefcbc;Kbz:tjjjb8AdnabaeSmbabaeadcdtzMjjjb8AkdnamcdGTmbalcrfci4cbyd1:H:cjbHjjjjbbhHasc:Cefasyd;8egecdtfaHBdbasaecefBd;8ecbhlcbhednadTmbabheadhOinaHaeydbci4fcb86bbaeclfheaOcufgOmbkcbhlabheadhOinaHaeydbgAci4fgCaCRbbgCceaAcrGgAtV86bbaCcu7aA4ceGalfhlaeclfheaOcufgOmbkcualcdtalcFFFFi0Ehekaecbyd1:H:cjbHjjjjbbhzasc:Cefasyd;8egecdtfazBdbasaecefBd;8ealcd4alfhOcehHinaHgecethHaeaO6mbkcbhXcuaecdtgOaecFFFFi0Ecbyd1:H:cjbHjjjjbbhHasc:Cefasyd;8egAcdtfaHBdbasaAcefBd;8eaHcFeaOz:tjjjbhQdnadTmbaecufhLcbhKindndnaQabaKcdtfgYydbgAc:v;t;h;Ev2aLGgOcdtfgCydbgHcuSmbceheinazaHcdtfydbaASmdaOaefhHaecefheaQaHaLGgOcdtfgCydbgHcu9hmbkkazaXcdtfaABdbaCaXBdbaXhHaXcefhXkaYaHBdbaKcefgKad9hmbkkaQcbyd:m:H:cjbH:bjjjbbasasyd;8ecufBd;8ekcbh8AcualcefgecdtaecFFFFi0Ecbyd1:H:cjbHjjjjbbhLasc:Cefasyd;8egecdtfaLBdbasaLBdNeasaecefBd;8ecuadcitadcFFFFe0Ecbyd1:H:cjbHjjjjbbhEasc:Cefasyd;8egecdtfaEBdbasaEBd:yeasaecefBd;8eascNefabadalcbz:cjjjbcualcdtgealcFFFFi0Eg3cbyd1:H:cjbHjjjjbbhOasc:Cefasyd;8egHcdtfaOBdbasaHcefBd;8ea3cbyd1:H:cjbHjjjjbbhQasc:Cefasyd;8egHcdtfaQBdbasaHcefBd;8eaOaQaialavazasc:Cefz:djjjbalcbyd1:H:cjbHjjjjbbhYasc:Cefasyd;8egHcdtfaYBdbasaHcefBd;8ea3cbyd1:H:cjbHjjjjbbhHasc:Cefasyd;8egAcdtfaHBdbasaAcefBd;8ea3cbyd1:H:cjbHjjjjbbhAasc:Cefasyd;8egCcdtfaABdbasaCcefBd;8eaHcFeaez:tjjjbh5aAcFeaez:tjjjbh8EdnalTmbindnaLa8AgAcefg8AcdtfydbgCaLaAcdtgefydbgHSmbaCaH9Rh8FaEaHcitfhaa8Eaefhha5aefhKcbhCindndnaaaCcitfydbgXaA9hmbaKaABdbahaABdbxekdnaLaXcdtggfgeclfydbgHaeydbgeSmbaHae9RhHaEaecitfheinaeydbaASmdaecwfheaHcufgHmbkka8EagfgeaAaXaeydbcuSEBdbaKaXaAaKydbcuSEBdbkaCcefgCa8F9hmbkka8Aal9hmbkaOhHaQhAa5hXa8EhCcbheindndnaeaHydbgK9hmbdnaeaAydbgK9hmbaXydbhKdnaCydbg8Fcu9hmbaKcu9hmbaYaefcb86bbxikdna8FcuSmbaKcuSmbaea8FSmbaOa8FcdtfydbaOaKcdtfydb9hmbaYaefcd86bbxikaYaefhadnaea8FSmbaeaKSmbaace86bbxikaacl86bbxdkdnaeaQaKcdtg8Ffydb9hmbdnaCydbgacuSmbaeaaSmbaXydbggcuSmbaeagSmba8Ea8FfydbghcuSmbahaKSmba5a8Ffydbg8FcuSmba8FaKSmbdnaOaacdtfydbgKaOa8Fcdtfydb9hmbaKaOagcdtfydbg8FSmba8FaOahcdtfydb9hmbaYaefcd86bbxlkaYaefcl86bbxikaYaefcl86bbxdkaYaefcl86bbxekaYaefaYaKfRbb86bbkaHclfhHaAclfhAaXclfhXaCclfhCalaecefge9hmbkdnamcaGTmbcbh8JindndnaYa8Jfg8KRbbg8Lc9:fPibebekdndndnaOa8Jcdtfydbgea8J9hmbdnaqmbcbh8FxdkdnazTmbcbh8Fa8JheinaqazaecdtgefydbfRbbce4a8FVceGh8FaQaefydbgea8J9hmbxikkcbh8Fa8JheinaqaefRbbce4a8FVceGh8FaQaecdtfydbgea8J9hmbxdkkaYaefRbbhexeka8JheindnaLaecdtg8AfgeclfydbgHaeydbgeSmbaHae9RhgaEaecitfhhaOa8AfhacbhKinahaKcitfydbgXhednindnaLaecdtgCfgeclfydbgHaeydbgeSmbaHae9RhHaEaecitfheaaydbhAdninaOaeydbcdtfydbaASmeaecwfheaHcufgHTmdxbkkcbhexdkaQaCfydbgeaX9hmbkceheka8FaeVh8FaKcefgKag9hmbkkaQa8Afydbgea8J9hmbka8Lcia8FceGEheka8Kae86bbka8Jcefg8Jal9hmbkkdnaqTmbdndnazTmbazheaOhHalhAindnaqaeydbfRbbceGTmbaYaHydbfcl86bbkaeclfheaHclfhHaAcufgAmbxdkkaqheaOhHalhAindnaeRbbceGTmbaYaHydbfcl86bbkaecefheaHclfhHaAcufgAmbkkaOhealhAaYhHindnaYaeydbfRbbcl9hmbaHcl86bbkaeclfheaHcefhHaAcufgAmbkkamceGTmbaYhealhHindnaeRbbce9hmbaecl86bbkaecefheaHcufgHmbkkcbh8Mcualcx2alc;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbh8Nasc:Cefasyd;8egecdtfa8NBdbasaecefBd;8eascbBd:qeas9cb83i1ea8Naialavazasc1efz:ejjjbhydndnaDmbcbh8PcbhCxekcbhCawhecbhHindnaeIdbJbbbb9ETmbasaCcdtfaHBdbaCcefhCkaeclfheaDaHcefgH9hmbkcuaCal2gecdtaecFFFFi0Ecbyd1:H:cjbHjjjjbbh8Pasc:Cefasyd;8egecdtfa8PBdbasaecefBd;8ealTmbdnaCmbcbhCxekarcd4hgdnazTmbaCcdthhcbh8Fa8Phainaoaza8Fcdtfydbag2cdtfhKasheaahHaChAinaHaKaeydbcdtgXfIdbawaXfIdbNUdbaeclfheaHclfhHaAcufgAmbkaaahfhaa8Fcefg8Fal9hmbxdkkaCcdthhcbh8Fa8Phainaoa8Fag2cdtfhKasheaahHaChAinaHaKaeydbcdtgXfIdbawaXfIdbNUdbaeclfheaHclfhHaAcufgAmbkaaahfhaa8Fcefg8Fal9hmbkkcualc8S2gHalc;D;O;f8U0EgXcbyd1:H:cjbHjjjjbbheasc:Cefasyd;8egAcdtfaeBdbasaAcefBd;8eaecbaHz:tjjjbhIcbh8RcbhgdnaCTmbcbh8MaXcbyd1:H:cjbHjjjjbbhgasc:Cefasyd;8egecdtfagBdbasaecefBd;8eagcbaHz:tjjjb8AcuaCal2gecltgHaecFFFFb0Ecbyd1:H:cjbHjjjjbbh8Rasc:Cefasyd;8egecdtfa8RBdbasaecefBd;8ea8RcbaHz:tjjjb8AamcjjjjdGTmbcualcltgealcFFFFb0Ecbyd1:H:cjbHjjjjbbh8Masc:Cefasyd;8egHcdtfa8MBdbasaHcefBd;8ea8Mcbaez:tjjjb8AkdnadTmbcbhKabhHina8NaHclfydbg8Fcx2fgeIdba8NaHydbgacx2fgAIdbg8S:tgRa8NaHcwfydbghcx2fgXIdlaAIdlg8U:tg8VNaeIdla8U:tg8WaXIdba8S:tg8XN:tg8Ya8YNa8WaXIdwaAIdwg8Z:tg80NaeIdwa8Z:tg8Wa8VN:tg81a81Na8Wa8XNaRa80N:tg80a80NMMg8V:rhBa8Yh8Xa80h8Wa81hRdna8VJbbbb9EgATmba8YaB:vh8Xa80aB:vh8Wa81aB:vhRkaIaOaacdtfydbgXc8S2fgeaRaB:rg8VaRNNg83aeIdbMUdbaea8Wa8Va8WNgUNg85aeIdlMUdlaea8Xa8Va8XNg86Ng87aeIdwMUdwaeaRaUNgUaeIdxMUdxaea86aRNg88aeIdzMUdzaea8Wa86Ng89aeIdCMUdCaeaRa8Va8Xa8ZNaRa8SNa8Ua8WNMM:mg8:Ng86NgRaeIdKMUdKaea8Wa86Ng8WaeId3MUd3aea8Xa86Ng8XaeIdaMUdaaea86a8:Ng86aeId8KMUd8Kaea8VaeIdyMUdyaIaOa8Fcdtfydbg8Fc8S2fgea83aeIdbMUdbaea85aeIdlMUdlaea87aeIdwMUdwaeaUaeIdxMUdxaea88aeIdzMUdzaea89aeIdCMUdCaeaRaeIdKMUdKaea8WaeId3MUd3aea8XaeIdaMUdaaea86aeId8KMUd8Kaea8VaeIdyMUdyaIaOahcdtfydbgac8S2fgea83aeIdbMUdbaea85aeIdlMUdlaea87aeIdwMUdwaeaUaeIdxMUdxaea88aeIdzMUdzaea89aeIdCMUdCaeaRaeIdKMUdKaea8WaeId3MUd3aea8XaeIdaMUdaaea86aeId8KMUd8Kaea8VaeIdyMUdydna8MTmbdnaATmba8YaB:vh8Ya80aB:vh80a81aB:vh81ka8MaXcltfgeaBJbbbZNgRa80Ng8VaeIdlMUdlaeaRa8YNg8WaeIdwMUdwaeaRa81Ng8XaeIdbMUdbaeaRa8S:ma81Na8Ua80N:ta8Za8YN:tNgRaeIdxMUdxa8Ma8Fcltfgea8VaeIdlMUdlaea8WaeIdwMUdwaea8XaeIdbMUdbaeaRaeIdxMUdxa8Maacltfgea8VaeIdlMUdlaea8WaeIdwMUdwaea8XaeIdbMUdbaeaRaeIdxMUdxkaHcxfhHaKcifgKad6mbkkdnalTmbJq;x8J88J;n;m;m89J:v:;;w8ZamczGEamc;abGEh80cbhHaOhXazhKaIhea8NhAindnaHaXydb9hmbaHh8FdnazTmbaKydbh8Fka80hRdnaqTmbJbbjZa80aqa8FfRbbclGEhRkaecxfg8Fa8FIdbJbbbbMUdbaeczfg8Fa8FIdbJbbbbMUdbaecCfg8Fa8FIdbJbbbbMUdbaeaRaecyfg8FIdbg8YNgRaeIdbMUdbaeclfgaaRaaIdbMUdbaecwfgaaRaaIdbMUdbaecKfgaaaIdbaAIdbg8WaRN:tUdbaAcwfIdbh8Vaec3fgaaaIdbaRaAclfIdbg8XN:tUdbaecafgaaaIdbaRa8VN:tUdbaec8KfgaIdbh81a8Fa8YaRMUdbaaa81aRa8Va8VNa8Wa8WNa8Xa8XNMMNMUdbkaXclfhXaKclfhKaec8SfheaAcxfhAalaHcefgH9hmbkkdnadTmbcbh8Aabhainaba8Acdtfh8FcbhHinaYa8FaHc:G:G:cjbfydbcdtfydbgAfRbbhedndnaYaaaHfydbgXfRbbgKc99fcFeGcpe0mbaec99fcFeGc;:e6mekdnaKcufcFeGce0mba5aXcdtfydbaA9hmekdnaecufcFeGce0mba8EaAcdtfydbaX9hmekJbbacJbbacJbbbZaecFeGceSEaKcFeGceSEhUdna8Na8FaHc:K:G:cjbfydbcdtfydbcx2fgeIdwa8NaXcx2fgKIdwg86:tg8Sa8NaAcx2fghIdwa86:tg8Xa8XNahIdbaKIdbg8U:tg80a80NahIdlaKIdlg8Z:tg8Va8VNMMg81Na8Xa8Sa8XNaeIdba8U:tg83a80Na8VaeIdla8Z:tg85NMMg8WN:tg8Ya8YNa83a81Na80a8WN:tgRaRNa85a81Na8Va8WN:tg8Wa8WNMMgBJbbbb9ETmba8YaB:rgB:vh8Ya8WaB:vh8WaRaB:vhRkaUa81:rNgBa8Ya86NaRa8UNa8Za8WNMM:mg81Ng87a81Nh88a80a85Na8Va83N:tg81a81Na8Va8SNa8Xa85N:tg8Va8VNa8Xa83Na80a8SN:tg8Xa8XNMMg83:rh80a8Ya87Nh85a8Wa87Nh89aRa87Nh87a8WaBa8YNg8SNh8:a8SaRNhZaRaBa8WNgnNhca8Ya8SNh8Ya8WanNh8WaRaBaRNNh8Sdna83Jbbbb9ETmba81a80:vh81a8Xa80:vh8Xa8Va80:vh8VkaIaOaXcdtfydbc8S2fgeaeIdba8Sa8VaUa80:rNgRa8VNNMg80MUdbaea8Wa8XaRa8XNg8SNMg83aeIdlMUdlaea8Ya81aRa81Ng8WNMg8YaeIdwMUdwaeaca8Va8SNMg8SaeIdxMUdxaeaZa8Wa8VNMgUaeIdzMUdzaea8:a8Xa8WNMg8WaeIdCMUdCaea87a8VaRa81a86Na8Va8UNa8Za8XNMMg86:mNgRNMg8VaeIdKMUdKaea89a8XaRNMg8XaeId3MUd3aea85a81aRNMg81aeIdaMUdaaea88a86aRN:tgRaeId8KMUd8KaeaBaeIdyMUdyaIaOaAcdtfydbc8S2fgea80aeIdbMUdbaea83aeIdlMUdlaea8YaeIdwMUdwaea8SaeIdxMUdxaeaUaeIdzMUdzaea8WaeIdCMUdCaea8VaeIdKMUdKaea8XaeId3MUd3aea81aeIdaMUdaaeaRaeId8KMUd8KaeaBaeIdyMUdykaHclfgHcx9hmbkaacxfhaa8Acifg8Aad6mbkaCTmbcbhainJbbbbh80a8Nabaacdtfgeclfydbg8Fcx2fgHIdwa8Naeydbghcx2fgAIdwg8Z:tg8Va8VNaHIdbaAIdbg83:tg8Wa8WNaHIdlaAIdlg85:tg8Xa8XNMMg8Sa8Naecwfydbg8Acx2fgeIdwa8Z:tg8YNa8Va8YNa8WaeIdba83:tg81Na8XaeIdla85:tgBNMMgRa8VN:tJbbbbJbbjZa8Sa8Ya8YNa81a81NaBaBNMMg8UNaRaRN:tg86:va86Jbbbb9BEg86Nh88a8Ua8VNaRa8YN:ta86Nh89a8SaBNaRa8XN:ta86Nh8:a8Ua8XNaRaBN:ta86NhZa8Sa81NaRa8WN:ta86Nhna8Ua8WNaRa81N:ta86Nhca8WaBNa8Xa81N:tgRaRNa8Xa8YNa8VaBN:tgRaRNa8Va81Na8Wa8YN:tgRaRNMM:rJbbbZNhRa8PahaC2g8JcdtfhHa8Pa8AaC2gDcdtfhAa8Pa8FaC2g8KcdtfhXa8Z:mh9ca85:mhJa83:mh9eascjdfheaChKJbbbbhBJbbbbh86Jbbbbh8SJbbbbh8UJbbbbh8ZJbbbbh83Jbbbbh85Jbbbbh87JbbbbhUinaecwfaRa89aXIdbaHIdbg8Y:tg8XNa88aAIdba8Y:tg81NMg8VNUdbaeclfaRaZa8XNa8:a81NMg8WNUdbaeaRaca8XNana81NMg8XNUdbaecxfaRa9ca8VNaJa8WNa8Ya9ea8XNMMMg8YNUdbaRa8Va8WNNa8ZMh8ZaRa8Va8XNNa8UMh8UaRa8Wa8XNNa8SMh8SaRa8Ya8YNNaUMhUaRa8Va8YNNa87Mh87aRa8Wa8YNNa85Mh85aRa8Xa8YNNa83Mh83aRa8Va8VNNa86Mh86aRa8Wa8WNNaBMhBaRa8Xa8XNNa80Mh80aHclfhHaXclfhXaAclfhAaeczfheaKcufgKmbkagahc8S2fgea80aeIdbMUdbaeaBaeIdlMUdlaea86aeIdwMUdwaea8SaeIdxMUdxaea8UaeIdzMUdzaea8ZaeIdCMUdCaea83aeIdKMUdKaea85aeId3MUd3aea87aeIdaMUdaaeaUaeId8KMUd8KaeaRaeIdyMUdyaga8Fc8S2fgea80aeIdbMUdbaeaBaeIdlMUdlaea86aeIdwMUdwaea8SaeIdxMUdxaea8UaeIdzMUdzaea8ZaeIdCMUdCaea83aeIdKMUdKaea85aeId3MUd3aea87aeIdaMUdaaeaUaeId8KMUd8KaeaRaeIdyMUdyaga8Ac8S2fgea80aeIdbMUdbaeaBaeIdlMUdlaea86aeIdwMUdwaea8SaeIdxMUdxaea8UaeIdzMUdzaea8ZaeIdCMUdCaea83aeIdKMUdKaea85aeId3MUd3aea87aeIdaMUdaaeaUaeId8KMUd8KaeaRaeIdyMUdya8Ra8Jcltfh8FcbhHaChXina8FaHfgeascjdfaHfgAIdbaeIdbMUdbaeclfgKaAclfIdbaKIdbMUdbaecwfgKaAcwfIdbaKIdbMUdbaecxfgeaAcxfIdbaeIdbMUdbaHczfhHaXcufgXmbka8Ra8Kcltfh8FcbhHaChXina8FaHfgeascjdfaHfgAIdbaeIdbMUdbaeclfgKaAclfIdbaKIdbMUdbaecwfgKaAcwfIdbaKIdbMUdbaecxfgeaAcxfIdbaeIdbMUdbaHczfhHaXcufgXmbka8RaDcltfh8FcbhHaChXina8FaHfgeascjdfaHfgAIdbaeIdbMUdbaeclfgKaAclfIdbaKIdbMUdbaecwfgKaAcwfIdbaKIdbMUdbaecxfgeaAcxfIdbaeIdbMUdbaHczfhHaXcufgXmbkaacifgaad6mbkkcbhAdndnamcwGgTmbJbbbbh8ScbhScbh9hcbh9ixekcbhSa3cbyd1:H:cjbHjjjjbbh9iasc:Cefasyd;8egecdtfa9iBdbasaecefBd;8ecua9ialabadaOz:fjjjbgXcltaXcjjjjiGEcbyd1:H:cjbHjjjjbbh9hasc:Cefasyd;8egecdtfa9hBdbasaecefBd;8ea9haXa9ia8Nalz:gjjjbJFFuuh8SaXTmba9hheaXhHinaeIdbgRa8Sa8SaR9EEh8SaeclfheaHcufgHmbkaXhSkdnalTmbaLclfheaLydbhXaYhHalhKcbhAincbaeydbg8FaX9RaHRbbcpeGEaAfhAaHcefhHaeclfhea8FhXaKcufgKmbkaAce4hAkcuadaA9Rcifg6cx2a6c;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbh9kasc:Cefasyd;8egecdtfa9kBdbasaecefBd;8ecua6cdta6cFFFFi0Ecbyd1:H:cjbHjjjjbbh0asc:Cefasyd;8egecdtfa0BdbasaecefBd;8ea3cbyd1:H:cjbHjjjjbbh9masc:Cefasyd;8egecdtfa9mBdbasaecefBd;8ealcbyd1:H:cjbHjjjjbbh9nasc:Cefasyd;8egecdtfa9nBdbasaecefBd;8eaxaxNayJbbjZamclGEgZaZN:vh87JbbbbhUdnadak9nmbdna6ci6mbaCclth9oa9kcwfh9pJbbbbh85JbbbbhUinascNefabadalaOz:cjjjbabh8Acbh9qcbh9rinaba9rcdtfhDcbheindnaOa8AaefydbgAcdtghfydbgXaOaDaec:W:G:cjbfydbcdtfydbgHcdtg8JfydbgKSmbaYaHfRbbgacv2aYaAfRbbg8FfRb;a:G:cjbg8La8Fcv2aafg8KRb;a:G:cjbg3VcFeGTmbdnaKaX9nmba8KRb;G:G:cjbcFeGmekdna8FcufcFeGce0mbaaTmba5ahfydbaH9hmekdna8FTmbaacufcFeGce0mba8Ea8JfydbaA9hmeka9ka9qcx2fgXaHaAa3cFeGgKEBdlaXaAaHaKEBdbaXaKa8LGcb9hBdwa9qcefh9qkaeclfgecx9hmbkdna9rcifg9rad9pmba8Acxfh8Aa9qcifa69nmekka9qTmdcbh8KinaIaOa9ka8Kcx2fghydbgKcdtgXfydbg8Ac8S2fgeIdwa8Nahydlg8Fcx2fgHIdwg8WNaeIdzaHIdbg8XNaeIdaMgRaRMMa8WNaeIdlaHIdlg8YNaeIdCa8WNaeId3MgRaRMMa8YNaeIdba8XNaeIdxa8YNaeIdKMgRaRMMa8XNaeId8KMMM:lhRJbbbbJbbjZaeIdyg8V:va8VJbbbb9BEh8VdndnahydwgDmbJFFuuh86xekJbbbbJbbjZaIaOa8Fcdtfydbc8S2fgeIdyg81:va81Jbbbb9BEaeIdwa8NaKcx2fgHIdwg81NaeIdzaHIdbg80NaeIdaMgBaBMMa81NaeIdlaHIdlgBNaeIdCa81NaeId3Mg81a81MMaBNaeIdba80NaeIdxaBNaeIdKMg81a81MMa80NaeId8KMMM:lNh86ka8VaRNhBdnaCTmbagaKc8S2fgAIdwa8WNaAIdza8XNaAIdaMgRaRMMa8WNaAIdla8YNaAIdCa8WNaAId3MgRaRMMa8YNaAIdba8XNaAIdxa8YNaAIdKMgRaRMMa8XNaAId8KMMMhRa8Pa8FaC2gacdtfhHa8RaKaC2g8JcltfheaAIdyh81aChAinaHIdbg8Va8Va81NaecxfIdba8WaecwfIdbNa8XaeIdbNa8YaeclfIdbNMMMg8Va8VM:tNaRMhRaHclfhHaeczfheaAcufgAmbkdndnaDmbJbbbbh8Vxekaga8Fc8S2fgAIdwa8NaKcx2fgeIdwg8XNaAIdzaeIdbg8YNaAIdaMg8Va8VMMa8XNaAIdlaeIdlg81NaAIdCa8XNaAId3Mg8Va8VMMa81NaAIdba8YNaAIdxa81NaAIdKMg8Va8VMMa8YNaAId8KMMMh8Va8Pa8JcdtfhHa8RaacltfheaAIdyh80aChAinaHIdbg8Wa8Wa80NaecxfIdba8XaecwfIdbNa8YaeIdbNa81aeclfIdbNMMMg8Wa8WM:tNa8VMh8VaHclfhHaeczfheaAcufgAmbka8V:lh8VkaBaR:lMhBa86a8VMh86dndndnaYaKfRbbc9:fPddbekaQaXfydbgXaKSmbaOa8Fcdtfydbh8Jindndna5aXcdtgafydbgecuSmbaOaecdtfydba8JSmekdna8EaafydbgecuSmbaOaecdtfydba8JSmeka8FhekagaXc8S2fgAIdwa8Naecx2fgHIdwg8WNaAIdzaHIdbg8XNaAIdaMgRaRMMa8WNaAIdlaHIdlg8YNaAIdCa8WNaAId3MgRaRMMa8YNaAIdba8XNaAIdxa8YNaAIdKMgRaRMMa8XNaAId8KMMMhRa8PaeaC2cdtfhHa8RaXaC2cltfheaAIdyh81aChAinaHIdbg8Va8Va81NaecxfIdba8WaecwfIdbNa8XaeIdbNa8YaeclfIdbNMMMg8Va8VM:tNaRMhRaHclfhHaeczfheaAcufgAmbkaBaR:lMhBaQaafydbgXaK9hmbkkaYa8FfRbbci9hmeaDTmeaQa8FcdtfydbgXa8FSmeindndna5aXcdtgafydbgecuSmbaOaecdtfydba8ASmekdna8EaafydbgecuSmbaOaecdtfydba8ASmekaKhekagaXc8S2fgAIdwa8Naecx2fgHIdwg8WNaAIdzaHIdbg8XNaAIdaMgRaRMMa8WNaAIdlaHIdlg8YNaAIdCa8WNaAId3MgRaRMMa8YNaAIdba8XNaAIdxa8YNaAIdKMgRaRMMa8XNaAId8KMMMhRa8PaeaC2cdtfhHa8RaXaC2cltfheaAIdyh81aChAinaHIdbg8Va8Va81NaecxfIdba8WaecwfIdbNa8XaeIdbNa8YaeclfIdbNMMMg8Va8VM:tNaRMhRaHclfhHaeczfheaAcufgAmbka86aR:lMh86aQaafydbgXa8F9hmbxdkkdna8Ea5a5aXfydba8FSEaQaXfydbgacdtfydbgXcu9hmbaQa8FcdtfydbhXkagaac8S2fgAIdwa8NaXcx2fgeIdwg8WNaAIdzaeIdbg8XNaAIdaMgRaRMMa8WNaAIdlaeIdlg8YNaAIdCa8WNaAId3MgRaRMMa8YNaAIdba8XNaAIdxa8YNaAIdKMgRaRMMa8XNaAId8KMMMhRa8PaXaC2g8AcdtfhHa8RaaaC2g8JcltfheaAIdyh81aChAinaHIdbg8Va8Va81NaecxfIdba8WaecwfIdbNa8XaeIdbNa8YaeclfIdbNMMMg8Va8VM:tNaRMhRaHclfhHaeczfheaAcufgAmbkdndnaDmbJbbbbh8VxekagaXc8S2fgAIdwa8Naacx2fgeIdwg8XNaAIdzaeIdbg8YNaAIdaMg8Va8VMMa8XNaAIdlaeIdlg81NaAIdCa8XNaAId3Mg8Va8VMMa81NaAIdba8YNaAIdxa81NaAIdKMg8Va8VMMa8YNaAId8KMMMh8Va8Pa8JcdtfhHa8Ra8AcltfheaAIdyh80aChAinaHIdbg8Wa8Wa80NaecxfIdba8XaecwfIdbNa8YaeIdbNa81aeclfIdbNMMMg8Wa8WM:tNa8VMh8VaHclfhHaeczfheaAcufgAmbka8V:lh8VkaBaR:lMhBa86a8VMh86kaha86aBa86aB9DgeEUdwahaKa8FaeaDcb9hGgeEBdlaha8FaKaeEBdba8Kcefg8Ka9q9hmbkascjdfcbcj;qbz:tjjjb8Aa9phea9qhHinascjdfaeydbcA4cF8FGgAcFAaAcFA6EcdtfgAaAydbcefBdbaecxfheaHcufgHmbkcbhecbhHinascjdfaefgAydbhXaAaHBdbaXaHfhHaeclfgecj;qb9hmbkcbhea9phHinascjdfaHydbcA4cF8FGgAcFAaAcFA6EcdtfgAaAydbgAcefBdba0aAcdtfaeBdbaHcxfhHa9qaecefge9hmbkadak9RgAci9Uh9sdnalTmbcbhea9mhHinaHaeBdbaHclfhHalaecefge9hmbkkcbh9ta9ncbalz:tjjjbh3aAcO9Uh9ua9sce4h9rcbh8Lcbh8Kdnina9ka0a8Kcdtfydbcx2fg8JIdwgRa879Emea8La9s9pmeJFFuuh8Vdna9ra9q9pmba9ka0a9rcdtfydbcx2fIdwJbb;aZNh8VkdnaRa8V9ETmbaRaU9ETmba8La9u0mdkdna3aOa8JydlgDcdtg9vfg8AydbgAfg9wRbba3aOa8Jydbghcdtg9xfydbgefg9yRbbVmbaYahfRbbh9zdndnaLaecdtfgHclfydbgXaHydbgHSmbaXaH9RhXa8NaAcx2fh8Fa8Naecx2fhaaEaHcitfheindna9maeydbcdtfydbgHaASmba9maeclfydbcdtfydbgKaASmbaHaKSmba8NaKcx2fgKIdba8NaHcx2fgHIdbg8W:tgRaaIdlaHIdlg8X:tg80NaKIdla8X:tg8VaaIdba8W:tgBN:tg8YaRa8FIdla8X:tg86Na8Va8FIdba8W:tg8UN:tg8XNa8VaaIdwaHIdwg81:tg8ZNaKIdwa81:tg8Wa80N:tg80a8Va8FIdwa81:tg83Na8Wa86N:tg8VNa8WaBNaRa8ZN:tg81a8Wa8UNaRa83N:tgRNMMa8Ya8YNa80a80Na81a81NMMa8Xa8XNa8Va8VNaRaRNMMN:rJbbj8:N9FmikaecwfheaXcufgXmbkkdndndndna9zc9:fPdebdkahheina8AydbhAdndna5aecdtgHfydbgecuSmbaOaecdtfydbaASmekdna8EaHfydbgecuSmbaOaecdtfydbaASmekaDheka9maHfaeBdbaQaHfydbgeah9hmbxikkdna8Ea5a5a9xfydbaDSEaQa9xfydbghcdtfydbgecu9hmbaQa9vfydbheka9ma9xfaDBdbaehDka9mahcdtfaDBdbka9yce86bba9wce86bba8JIdwgRaUaUaR9DEhUa9tcefh9tcecda9zceSEa8Lfh8Lxeka9rcefh9rka8Kcefg8Ka9q9hmbkka9tTmddnalTmbcbh8Fcbhhindna9mahcdtgefydbgAahSmbaOaAcdtfydbh8AdnahaOaefydb9hg8JmbaIa8Ac8S2fgeaIahc8S2fgHIdbaeIdbMUdbaeaHIdlaeIdlMUdlaeaHIdwaeIdwMUdwaeaHIdxaeIdxMUdxaeaHIdzaeIdzMUdzaeaHIdCaeIdCMUdCaeaHIdKaeIdKMUdKaeaHId3aeId3MUd3aeaHIdaaeIdaMUdaaeaHId8KaeId8KMUd8KaeaHIdyaeIdyMUdya8MTmba8Ma8Acltfgea8MahcltfgHIdbaeIdbMUdbaeaHIdlaeIdlMUdlaeaHIdwaeIdwMUdwaeaHIdxaeIdxMUdxkaCTmbagaAc8S2fgeagahc8S2gDfgHIdbaeIdbMUdbaeaHIdlaeIdlMUdlaeaHIdwaeIdwMUdwaeaHIdxaeIdxMUdxaeaHIdzaeIdzMUdzaeaHIdCaeIdCMUdCaeaHIdKaeIdKMUdKaeaHId3aeId3MUd3aeaHIdaaeIdaMUdaaeaHId8KaeId8KMUd8KaeaHIdyaeIdyMUdya9oaA2haa8RhHaChXinaHaafgeaHa8FfgAIdbaeIdbMUdbaeclfgKaAclfIdbaKIdbMUdbaecwfgKaAcwfIdbaKIdbMUdbaecxfgeaAcxfIdbaeIdbMUdbaHczfhHaXcufgXmbka8JmbJbbbbJbbjZaIaDfgeIdygR:vaRJbbbb9BEaeIdwa8Na8Acx2fgHIdwgRNaeIdzaHIdbg8VNaeIdaMg8Wa8WMMaRNaeIdlaHIdlg8WNaeIdCaRNaeId3MgRaRMMa8WNaeIdba8VNaeIdxa8WNaeIdKMgRaRMMa8VNaeId8KMMM:lNgRa85a85aR9DEh85ka8Fa9ofh8Fahcefghal9hmbkcbhHa5heindnaeydbgAcuSmbdnaHa9maAcdtgXfydbgA9hmbcuhAa5aXfydbgXcuSmba9maXcdtfydbhAkaeaABdbkaeclfhealaHcefgH9hmbkcbhHa8EheindnaeydbgAcuSmbdnaHa9maAcdtgXfydbgA9hmbcuhAa8EaXfydbgXcuSmba9maXcdtfydbhAkaeaABdbkaeclfhealaHcefgH9hmbkka85aUaCEh85cbhHabhecbhAindnaOa9maeydbcdtfydbg8FcdtfydbgXaOa9maeclfydbcdtfydbgacdtfydbgKSmbaXaOa9maecwfydbcdtfydbg8AcdtfydbghSmbaKahSmbabaHcdtfgXa8FBdbaXcwfa8ABdbaXclfaaBdbaHcifhHkaecxfheaAcifgAad6mbkdndnaTmbaHhdxekdnaHak0mbaHhdxekdna8Sa859FmbaHhdxekJFFuuh8ScbhdabhecbhAindna9ha9iaeydbgXcdtfydbcdtfIdbgRa859ETmbaeclf8Pdbh9AabadcdtfgKaXBdbaKclfa9A83dbaRa8Sa8SaR9EEh8SadcifhdkaecxfheaAcifgAaH6mbkkadak0mbxdkkascNefabadalaOz:cjjjbkdndnadak0mbadhaxekdnaTmbadhaxekdna8Sa879FmbadhaxekcehKina8SJbb;aZNgRa87aRa879DEh8WJbbbbhRdnaSTmba9hheaShHinaeIdbg8VaRa8Va8W9FEaRa8VaR9EEhRaeclfheaHcufgHmbkkJFFuuh8ScbhaabhecbhHindna9ha9iaeydbgAcdtfydbcdtfIdbg8Va8W9ETmbaeclf8Pdbh9AabaacdtfgXaABdbaXclfa9A83dba8Va8Sa8Sa8V9EEh8SaacifhakaecxfheaHcifgHad6mbkdnaKaaad9hVceGmbadhaxdkaRaUaUaR9DEhUaaak9nmecbhKaahda8Sa879FmbkkdnamcjjjjdGTmba9ncbalz:tjjjbh8AdnaaTmbabheaahHina8AaeydbgAfce86bba8AaOaAcdtfydbfce86bbaeclfheaHcufgHmbkkascNefabaaalaOz:cjjjbdndnalTmbcbhXindna8AaXfRbbTmbdnaYaXfRbbgecl0mbceaetcQGmekdnaOaXcdtg8FfydbgeaXSmba8NaXcx2fgHa8Naecx2fgeydwBdwaHae8Pdb83dbxekaIaXc8S2fgKIdygcacJL:3;rUNgRMh87aKIdwg9BaRMh8SaKIdlg9CaRMh8UaKIdbg9DaRMh81aKIdag9EaRa8NaXcx2fg8JIdwg88N:th8ZaKId3g9FaRa8JIdlg89N:th83aKIdKg9Ga8JIdbg8:aRN:th80JbbbbhnaKIdCg9HJbbbbMh85aKIdzg9IJbbbbMhBaKIdxg9JJbbbbMh86dndnaCTmbaXhAinJbbbba87agaAc8S2fgHIdygR:vaRJbbbb9BEhRa8RaAaC2cltfheaHIdaa87Na8ZMh8ZaHId3a87Na83Mh83aHIdKa87Na80Mh80aHIdCa87Na85Mh85aHIdza87NaBMhBaHIdxa87Na86Mh86aHIdwa87Na8SMh8SaHIdla87Na8UMh8UaHIdba87Na81Mh81aChHina8ZaecwfIdbg8VaecxfIdbg8YNaRN:th8Za83aeclfIdbg8Wa8YNaRN:th83a85a8Wa8VNaRN:th85a81aeIdbg8Xa8XNaRN:th81a80a8Xa8YNaRN:th80aBa8Xa8VNaRN:thBa86a8Xa8WNaRN:th86a8Sa8Va8VNaRN:th8Sa8Ua8Wa8WNaRN:th8UaeczfheaHcufgHmbkaQaAcdtfydbgAaX9hmbka8MTmba8MaXcltfgeIdxhxaeIdwh9caeIdlhJaeIdbhRxekJbbbbhxJbbbbh9cJbbbbhJJbbbbhRkaBa81:vg8Wa80Na8Z:ta85aBa86a81:vg8VN:tg8Za8Ua86a8VN:tg8Y:vg8Xa8Va80Na83:tg8UN:th83a9caRa8WN:taJaRa8VN:tg86a8XN:tg85a8SaBa8WN:ta8Za8XN:tgB:vg8S:mh8Za86a8Y:vg9c:mhJdnJbbbbaRaRa81:vg9eN:ta86a9cN:ta85a8SN:tg86:la87J:983:g81NgR9ETmba8Za83NaJa8UNa9ea80Nax:tMMa86:vhnka81:laR9ETmba8Y:laR9ETmbaB:laR9ETmba9e:manNa8W:ma8ZanNa83aB:vMgBNa8V:maJanNa8X:maBNa8Ua8Y:vMMg85Na80:ma81:vMMMh87aLa8FfgeclfydbgHaeydbge9RhhaEaecitfh8FJbbbbhRdnaHaeSgDmbJbbbbhRa8FheahhAina8Naeclfydbcx2fgHIdwa88:tg8Va8VNaHIdba8::tg8Va8VNaHIdla89:tg8Va8VNMMg8Va8Naeydbcx2fgHIdwa88:tg8Wa8WNaHIdba8::tg8Wa8WNaHIdla89:tg8Wa8WNMMg8WaRaRa8W9DEgRaRa8V9DEhRaecwfheaAcufgAmbkaR:rgRaRNhRkaBa88:tg8Va8VNa87a8::tg8Va8VNa85a89:tg8Va8VNMMaR9EmbaKId8KhndnaDmbina8Na8Fclfydbcx2fgeIdba8Na8Fydbcx2fgHIdbg8W:tgRa89aHIdlg8X:tg80NaeIdla8X:tg8Va8:a8W:tg86N:tg8YaRa85a8X:tg8SNa8Va87a8W:tg8UN:tg8XNa8Va88aHIdwg81:tg8ZNaeIdwa81:tg8Wa80N:tg80a8VaBa81:tg83Na8Wa8SN:tg8VNa8Wa86NaRa8ZN:tg81a8Wa8UNaRa83N:tgRNMMa8Ya8YNa80a80Na81a81NMMa8Xa8XNa8Va8VNaRaRNMMN:rJbbj8:N9Fmda8Fcwfh8FahcufghmbkkJbbbbJbbjZac:vacJbbbb9BEgRa9BaBNa9Ia87Na9EMg8Va8VMMaBNa9Ca85Na9HaBNa9FMg8Va8VMMa85Na9Da87Na9Ja85Na9GMg8Va8VMMa87NanMMM:lNaRa9Ba88Na9Ia8:Na9EMg8Va8VMMa88Na9Ca89Na9Ha88Na9FMg8Va8VMMa89Na9Da8:Na9Ja89Na9GMg8Va8VMMa8:NanMMM:lNJbb;aZNJ:983:g81M9Emba8JaBUdwa8Ja85Udla8Ja87UdbkaXcefgXal9hmbkdnaCmbcbhCxdkcbhXindna8AaXfRbbTmbaOaXcdtgefydbaX9hmbaYaXfhhaQaefh8Ja8NaXcx2fhAa8PaXaC2cdtfhDcbhEincuhLdnahRbbci9hmbaXhLa8JydbgeaXSmba8PaEcdtgHfhKaDaHfIdbhRaXhLinaLhHcuhLdnaKaeaC2cdtfIdbaR9CmbaHcuSmbaHhLagaec8S2fIdyagaHc8S2fIdy9ETmbaehLkaQaecdtfydbgeaX9hmbkka8PaEcdtfhKa8RaEcltfh8FaXheinaKaeaC2cdtfJbbbbJbbjZagaeaLaLcuSEgHc8S2fIdygR:vaRJbbbb9BEa8FaHaC2cltfgHIdwaAIdwNaHIdbaAIdbNaHIdlaAIdlNMMaHIdxMNUdbaQaecdtfydbgeaX9hmbkaEcefgEaC9hmbkkaXcefgXal9hmbxdkkaCmbcbhCkaiavaoarawaCala8Na8Pazasayasc1efaYa8Aaqz:hjjjbkdnamcjjjjlGTmbazmbaaTmbabhecbhLinaYaeydbgAfRbbc3thQaecwfgXydbhHcjjjj94hCdna5aAcdtgEfydbaeclfgKydbgOSmbcjjjj94cba8EaOcdtfydbaASEhCkaeaQaCVaAVBdbaYaOfRbbc3th8Fcjjjj94hCcjjjj94hQdna5aOcdtfydbaHSmbcjjjj94cba8EaHcdtfydbaOSEhQkaKa8FaQVaOVBdbaYaHfRbbc3thOdna5aHcdtfydbaASmbcjjjj94cba8EaEfydbaHSEhCkaXaOaCVaHVBdbaecxfheaLcifgLaa6mbkkdnazTmbaaTmbaaheinabazabydbcdtfydbBdbabclfhbaecufgembkkdnaPTmbaPaZaU:rNUdbkdnasyd;8egHTmbaHcdtasc:Ceffc98fheinaeydbcbyd:m:H:cjbH:bjjjbbaec98fheaHcufgHmbkkascj;sbf8Kjjjjbaak;Yieouabydlhvabydbclfcbaicdtz:tjjjbhoadci9UhrdnadTmbdnalTmbaehwadhDinaoalawydbcdtfydbcdtfgqaqydbcefBdbawclfhwaDcufgDmbxdkkaehwadhDinaoawydbcdtfgqaqydbcefBdbawclfhwaDcufgDmbkkdnaiTmbcbhDaohwinawydbhqawaDBdbawclfhwaqaDfhDaicufgimbkkdnadci6mbinaecwfydbhwaeclfydbhDaeydbhidnalTmbalawcdtfydbhwalaDcdtfydbhDalaicdtfydbhikavaoaicdtfgqydbcitfaDBdbavaqydbcitfawBdlaqaqydbcefBdbavaoaDcdtfgqydbcitfawBdbavaqydbcitfaiBdlaqaqydbcefBdbavaoawcdtfgwydbcitfaiBdbavawydbcitfaDBdlawawydbcefBdbaecxfhearcufgrmbkkabydbcbBdbk:todDue99aicd4aifhrcehwinawgDcethwaDar6mbkcuaDcdtgraDcFFFFi0Ecbyd1:H:cjbHjjjjbbhwaoaoyd9GgqcefBd9GaoaqcdtfawBdbawcFearz:tjjjbhkdnaiTmbalcd4hlaDcufhxcbhminamhDdnavTmbavamcdtfydbhDkcbadaDal2cdtfgDydlgwawcjjjj94SEgwcH4aw7c:F:b:DD2cbaDydbgwawcjjjj94SEgwcH4aw7c;D;O:B8J27cbaDydwgDaDcjjjj94SEgDcH4aD7c:3F;N8N27axGhwamcdthPdndndnavTmbakawcdtfgrydbgDcuSmeadavaPfydbal2cdtfgsIdbhzcehqinaqhrdnadavaDcdtfydbal2cdtfgqIdbaz9CmbaqIdlasIdl9CmbaqIdwasIdw9BmlkarcefhqakawarfaxGgwcdtfgrydbgDcu9hmbxdkkakawcdtfgrydbgDcuSmbadamal2cdtfgsIdbhzcehqinaqhrdnadaDal2cdtfgqIdbaz9CmbaqIdlasIdl9CmbaqIdwasIdw9BmikarcefhqakawarfaxGgwcdtfgrydbgDcu9hmbkkaramBdbamhDkabaPfaDBdbamcefgmai9hmbkkakcbyd:m:H:cjbH:bjjjbbaoaoyd9GcufBd9GdnaeTmbaiTmbcbhDaehwinawaDBdbawclfhwaiaDcefgD9hmbkcbhDaehwindnaDabydbgrSmbawaearcdtfgrydbBdbaraDBdbkabclfhbawclfhwaiaDcefgD9hmbkkk;:odvuv998Jjjjjbca9Rgocbyd1:G:cjbBdKaocb8Pdj:G:cjb83izaocbydN:G:cjbBdwaocb8Pd:m:G:cjb83ibdnadTmbaicd4hrdnabmbdnalTmbcbhwinaealawcdtfydbar2cdtfhDcbhiinaoczfaifgqaDaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkawcefgwad9hmbxikkarcdthwcbhDincbhiinaoczfaifgqaeaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkaeawfheaDcefgDad9hmbxdkkdnalTmbcbhwinabawcx2fgiaealawcdtfydbar2cdtfgDIdbUdbaiaDIdlUdlaiaDIdwUdwcbhiinaoczfaifgqaDaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkawcefgwad9hmbxdkkarcdthlcbhwaehDinabawcx2fgiaeawar2cdtfgqIdbUdbaiaqIdlUdlaiaqIdwUdwcbhiinaoczfaifgqaDaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkaDalfhDawcefgwad9hmbkkJbbbbaoIdbaoIdzgx:tgkakJbbbb9DEgkaoIdlaoIdCgm:tgPaPak9DEgkaoIdwaoIdKgP:tgsasak9DEhsdnabTmbadTmbJbbbbJbbjZas:vasJbbbb9BEhkinabakabIdbax:tNUdbabclfgoakaoIdbam:tNUdbabcwfgoakaoIdbaP:tNUdbabcxfhbadcufgdmbkkdnavTmbavaPUdwavamUdlavaxUdbkask:WlewudnaeTmbcbhvabhoinaoavBdbaoclfhoaeavcefgv9hmbkkdnaiTmbcbhrinadarcdtfhwcbhDinalawaDcdtgvyd:G:G:cjbcdtfydbcdtfydbhodnalawavfydbcdtfydbgqabaqcdtfgkydbgvSmbinakabavgqcdtfgxydbgvBdbaxhkaqav9hmbkkdnaoabaocdtfgkydbgvSmbinakabavgocdtfgxydbgvBdbaxhkaoav9hmbkkdnaqaoSmbabaqaoaqao0Ecdtfaqaoaqao6EBdbkaDcefgDci9hmbkarcifgrai6mbkkdnaembcbskcbhxindnalaxcdtgvfydbax9hmbaxhodnaxabavfgDydbgvSmbaDhqinaqabavgocdtfgkydbgvBdbakhqaoav9hmbkkaDaoBdbkaxcefgxae9hmbkcbhkabhvcbhoindndnaoalydbgq9hmbdnaoavydbgq9hmbavakBdbakcefhkxdkavabaqcdtfydbBdbxekavabaqcdtfydbBdbkalclfhlavclfhvaeaocefgo9hmbkakk;jiilud99euabcbaecltz:tjjjbhvdnalTmbadhoaihralhwinarcwfIdbhDarclfIdbhqavaoydbcltfgkarIdbakIdbMUdbakaqakIdlMUdlakaDakIdwMUdwakakIdxJbbjZMUdxaoclfhoarcxfhrawcufgwmbkkdnaeTmbavhkaehrinakcxfgoIdbhDaocbBdbakakIdbJbbbbJbbjZaD:vaDJbbbb9BEgDNUdbakclfgoaDaoIdbNUdbakcwfgoaDaoIdbNUdbakczfhkarcufgrmbkkdnalTmbinavadydbcltfgkaicwfIdbakIdw:tgDaDNaiIdbakIdb:tgDaDNaiclfIdbakIdl:tgDaDNMMgDakIdxgqaqaD9DEUdxadclfhdaicxfhialcufglmbkkdnaeTmbavcxfhkinabakIdbUdbakczfhkabclfhbaecufgembkkk:moerudnaoTmbaecd4hzdnavTmbaicd4hHavcdthOcbhAindnaPaAfRbbTmbaAhednaDTmbaDaAcdtfydbhekdnasTmbasaefRbbceGmekdnamaAfRbbclSmbabaeaz2cdtfgiaraAcx2fgCIdbakNaxIdbMUdbaiaCIdlakNaxIdlMUdlaiaCIdwakNaxIdwMUdwkadaeaH2cdtfhXaqheawhiavhCinaXaeydbcdtgQfaiIdbalaQfIdb:vUdbaeclfheaiclfhiaCcufgCmbkkawaOfhwaAcefgAao9hmbxdkkdnasmbcbheaDhiindnaPaefRbbTmbaehCdnaDTmbaiydbhCkamaefRbbclSmbabaCaz2cdtfgCarIdbakNaxIdbMUdbaCarclfIdbakNaxIdlMUdlaCarcwfIdbakNaxIdwMUdwkaiclfhiarcxfhraoaecefge9hmbxdkkdnaDTmbindnaPRbbTmbasaDydbgefRbbceGmbamRbbclSmbabaeaz2cdtfgearIdbakNaxIdbMUdbaearclfIdbakNaxIdlMUdlaearcwfIdbakNaxIdwMUdwkaPcefhPaDclfhDamcefhmarcxfhraocufgombxdkkazcdthicbheindnaPaefRbbTmbasaefRbbceGmbamaefRbbclSmbabarIdbakNaxIdbMUdbabclfarclfIdbakNaxIdlMUdbabcwfarcwfIdbakNaxIdwMUdbkarcxfhrabaifhbaoaecefge9hmbkkk8MbabaeadaialavcbcbcbcbcbaoarawaDz:bjjjbk8MbabaeadaialavaoarawaDaqakaxamaPz:bjjjbkRbababaeadaialavaoarawaDaqakaxcjjjjdVamz:bjjjbk:g8Koque99due99duq998Jjjjjbc;Wb9Rgq8Kjjjjbcbhkaqcxfcbc;Kbz:tjjjb8Aaqcualcx2alc;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbgxBdxaqceBd2axaialavcbcbz:ejjjb8AaqcualcdtalcFFFFi0Egmcbyd1:H:cjbHjjjjbbgiBdzaqcdBd2dndnJFF959eJbbjZawJbbjZawJbbjZ9DE:vawJ9VO:d869DEgw:lJbbb9p9DTmbaw:OhPxekcjjjj94hPkadci9Uhsarco9UhzdndnaombaPcd9imekdnalTmbaPcuf:YhwdnaoTmbcbhvaihHaxhOindndnaoavfRbbceGTmbavcjjjjlVhAxekdndnaOclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcqthAdndnaOcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXVhAdndnaOIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXcCtVhAkaHaABdbaHclfhHaOcxfhOalavcefgv9hmbxdkkaxhvaihOalhHindndnavIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcCthAdndnavclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcqtaAVhAdndnavcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaOaAaXVBdbavcxfhvaOclfhOaHcufgHmbkkadTmbcbhkaehvcbhOinakaiavclfydbcdtfydbgHaiavcwfydbcdtfydbgA9haiavydbcdtfydbgXaH9haXaA9hGGfhkavcxfhvaOcifgOad6mbkkarci9UhQdndnaz:Z:rJbbbZMgw:lJbbb9p9DTmbaw:Ohvxekcjjjj94hvkaQ:ZhLcbhKc:bwhzdninakaQ9pmeazaP9Rcd9imeavazcufgOavaO9iEaPcefavaP9kEhYdnalTmbaYcuf:YhwdnaoTmbcbhOaihHaxhvindndnaoaOfRbbceGTmbaOcjjjjlVhAxekdndnavclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcqthAdndnavcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXVhAdndnavIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXcCtVhAkaHaABdbaHclfhHavcxfhvalaOcefgO9hmbxdkkaxhvaihOalhHindndnavIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcCthAdndnavclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcqtaAVhAdndnavcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaOaAaXVBdbavcxfhvaOclfhOaHcufgHmbkkcbhOdnadTmbaehvcbhHinaOaiavclfydbcdtfydbgAaiavcwfydbcdtfydbgX9haiavydbcdtfydbgraA9haraX9hGGfhOavcxfhvaHcifgHad6mbkkdnas:ZgCaL:taY:Ygwaz:Y:tg8ANak:ZgEaO:Zg3:tNaEaL:tawaP:Y:tg5Na3aC:tNMg8EJbbbb9BmbaCaE:ta5a8Aa3aL:tNNNa8E:vawMhwkdndnaOaQ0mbaOhkaYhPxekaOhsaYhzkdndnaKcl0mbdnawJbbbZMgw:lJbbb9p9DTmbaw:Ohvxdkcjjjj94hvxekaPazfcd9ThvkaKcefgKcs9hmbkkdndndnakmbJbbjZhwcbhOcdhvaDmexdkalcd4alfhHcehOinaOgvcethOavaH6mbkcbhOaqcuavcdtgYavcFFFFi0Ecbyd1:H:cjbHjjjjbbgKBdCaqciBd2aqamcbyd1:H:cjbHjjjjbbgzBdKaqclBd2dndndndnalTmbaPcuf:YhwaoTmecbhOaihAaxhHindndnaoaOfRbbceGTmbaOcjjjjlVhXxekdndnaHclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcqthXdndnaHcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkaXarVhXdndnaHIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkaXarcCtVhXkaAaXBdbaAclfhAaHcxfhHalaOcefgO9hmbxikkaKcFeaYz:tjjjb8AcbhPcbhvxdkaxhOaihHalhAindndnaOIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcCthXdndnaOclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkarcqtaXVhXdndnaOcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkaHaXarVBdbaOcxfhOaHclfhHaAcufgAmbkkaKcFeaYz:tjjjbhravcufhocbhPcbhYindndndnaraiaYcdtgKfydbgAcm4aA7c:v;t;h;Ev2gvcs4av7aoGgHcdtfgXydbgOcuSmbcehvinaiaOcdtgOfydbaASmdaHavfhOavcefhvaraOaoGgHcdtfgXydbgOcu9hmbkkaXaYBdbaPhvaPcefhPxekazaOfydbhvkazaKfavBdbaYcefgYal9hmbkcuaPc8S2gOaPc;D;O;f8U0EhvkcbhXaqavcbyd1:H:cjbHjjjjbbgvBd3aqcvBd2avcbaOz:tjjjbhOdnadTmbaehiinaxaiclfydbgrcx2fgvIdbaxaiydbgocx2fgHIdbg3:tgCaxaicwfydbgYcx2fgAIdlaHIdlg8A:tgwNavIdla8A:tgEaAIdba3:tg8EN:tgLaLNaEaAIdwaHIdwg5:tg8FNavIdwa5:tgEawN:tgwawNaEa8ENaCa8FN:tgCaCNMMg8E:rhEJbbnnJbbjZazaocdtfydbgvazarcdtfydbgASavazaYcdtfydbgrSGgHEh8Fdna8EJbbbb9ETmbaLaE:vhLaCaE:vhCawaE:vhwkaOavc8S2fgvavIdbawa8FaE:rNgEawNNg8FMUdbavaCaEaCNgaNghavIdlMUdlavaLaEaLNg8ENggavIdwMUdwavawaaNgaavIdxMUdxava8EawNg8JavIdzMUdzavaCa8ENg8EavIdCMUdCavawaEaLa5Nawa3Na8AaCNMM:mg8ANg3NgwavIdKMUdKavaCa3NgCavId3MUd3avaLa3NgLavIdaMUdaava3a8ANg3avId8KMUd8KavaEavIdyMUdydnaHmbaOaAc8S2fgva8FavIdbMUdbavahavIdlMUdlavagavIdwMUdwavaaavIdxMUdxava8JavIdzMUdzava8EavIdCMUdCavawavIdKMUdKavaCavId3MUd3avaLavIdaMUdaava3avId8KMUd8KavaEavIdyMUdyaOarc8S2fgva8FavIdbMUdbavahavIdlMUdlavagavIdwMUdwavaaavIdxMUdxava8JavIdzMUdzava8EavIdCMUdCavawavIdKMUdKavaCavId3MUd3avaLavIdaMUdaava3avId8KMUd8KavaEavIdyMUdykaicxfhiaXcifgXad6mbkkcbhAaqcuaPcdtgvaPcFFFFi0Egicbyd1:H:cjbHjjjjbbgHBdaaqcoBd2aqaicbyd1:H:cjbHjjjjbbgiBd8KaqcrBd2aHcFeavz:tjjjbhYdnalTmbazhHinJbbbbJbbjZaOaHydbgXc8S2fgvIdygw:vawJbbbb9BEavIdwaxcwfIdbgwNavIdzaxIdbgCNavIdaMgLaLMMawNavIdlaxclfIdbgLNavIdCawNavId3MgwawMMaLNavIdbaCNavIdxaLNavIdKMgwawMMaCNavId8KMMM:lNhwdndnaYaXcdtgvfgXydbcuSmbaiavfIdbaw9ETmekaXaABdbaiavfawUdbkaHclfhHaxcxfhxalaAcefgA9hmbkkdndnaPmbJbbbbhwxekJbbbbhwinaiIdbgCawawaC9DEhwaiclfhiaPcufgPmbkaw:rhwkakcd4akfhOcehiinaigvcethiavaO6mbkcbhOaqcuavcdtgiavcFFFFi0Ecbyd1:H:cjbHjjjjbbgHBdyaHcFeaiz:tjjjbhXdnadTmbavcufhrcbhPcbhxindnazaeaxcdtfgvydbcdtfydbgiazavclfydbcdtfydbgOSmbaiazavcwfydbcdtfydbgvSmbaOavSmbaYavcdtfydbhAdndnaYaOcdtfydbgvaYaicdtfydbgi9pmbavaA9pmbaAhlaihoavhAxekdnaAai9pmbaAav9pmbaihlavhoxekavhlaAhoaihAkabaPcx2fgvaABdbavcwfaoBdbavclfalBdbdnaXaoc:3F;N8N2alc:F:b:DD27aAc;D;O:B8J27arGgOcdtfgvydbgicuSmbcehHinaHhvdnabaicx2fgiydbaA9hmbaiydlal9hmbaiydwaoSmikavcefhHaXaOavfarGgOcdtfgvydbgicu9hmbkkavaPBdbaPcefhPkaxcifgxad6mbkaPci2hOkcwhvaDTmekaDawUdbkavcdthvaqcxfc98fhiinaiavfydbcbyd:m:H:cjbH:bjjjbbavc98fgvmbkaqc;Wbf8KjjjjbaOk:3ldrue9:8Jjjjjbc;Wb9Rgr8Kjjjjbcbhwarcxfcbc;Kbz:tjjjb8AdnabaeSmbabaeadcdtzMjjjb8AkarcualcdtalcFFFFi0EgDcbyd1:H:cjbHjjjjbbgqBdxarceBd2aqcbaialavcbarcxfz:djjjbcualcx2alc;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbhkarcxfaryd2gxcdtfakBdbaraxcefgmBd2akaialavcbcbz:ejjjb8AarcxfamcdtfaDcbyd1:H:cjbHjjjjbbgiBdbaraxcdfgvBd2arcxfavcdtfcuaialaeadaqz:fjjjbgecltaecjjjjiGEcbyd1:H:cjbHjjjjbbgqBdbaqaeaiakalz:gjjjbaxcifhkdnadTmbaoaoNhocbhwabhlcbheindnaqaialydbgvcdtfydbcdtfIdbao9ETmbalclf8PdbhPabawcdtfgDavBdbaDclfaP83dbawcifhwkalcxfhlaecifgead6mbkkdnakTmbaxcdtarcxffcwfhlinalydbcbyd:m:H:cjbH:bjjjbbalc98fhlakcufgkmbkkarc;Wbf8Kjjjjbawk:WCoDud99vue99vuv998Jjjjjbc;Wb9Rgw8KjjjjbdndnarmbcbhDxekawcxfcbc;Kbz:tjjjb8Aawcuadcx2adc;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbgqBdxawceBd2aqaeadaicbcbz:ejjjb8AawcuadcdtadcFFFFi0Egkcbyd1:H:cjbHjjjjbbgxBdzawcdBd2adcd4adfhmceheinaegicetheaiam6mbkcbhPawcuaicdtgsaicFFFFi0Ecbyd1:H:cjbHjjjjbbgzBdCawciBd2dndnar:ZgH:rJbbbZMgO:lJbbb9p9DTmbaO:Ohexekcjjjj94hekaicufhAc:bwhCcbhXadhQcbhLinaeaCcufgiaeai9iEaPcefaeaP9kEhDdndnadTmbaDcuf:YhOaqhiaxheadhmindndnaiIdbaONJbbbZMgK:lJbbb9p9DTmbaK:OhYxekcjjjj94hYkaYcCthYdndnaiclfIdbaONJbbbZMgK:lJbbb9p9DTmbaK:Oh8Axekcjjjj94h8Aka8AcqtaYVhYdndnaicwfIdbaONJbbbZMgK:lJbbb9p9DTmbaK:Oh8Axekcjjjj94h8AkaeaYa8AVBdbaicxfhiaeclfheamcufgmmbkazcFeasz:tjjjbhEcbh3cbh5indnaEaxa5cdtfydbgYcm4aY7c:v;t;h;Ev2gics4ai7aAGgmcdtfg8AydbgecuSmbaeaYSmbcehiinaEamaifaAGgmcdtfg8AydbgecuSmeaicefhiaeaY9hmbkka8AaYBdba3aecuSfh3a5cefg5ad9hmbxdkkazcFeasz:tjjjb8Acbh3kdnaQ:ZgKaH:taD:YgOaC:Y:tg8ENaX:Zg8Fa3:Zga:tNa8FaH:taOaP:Y:tghNaaaK:tNMggJbbbb9BmbaKa8F:taha8EaaaH:tNNNag:vaOMhOkaPaDa3ar0giEhPaXa3aiEhXdna3arSmbaDaCaiEgCaP9Rcd9imbdndnaLcl0mbdnaOJbbbZMgO:lJbbb9p9DTmbaO:Ohexdkcjjjj94hexekaPaCfcd9Theka3aQaiEhQaLcefgLcs9hmekkdndnaXmbcihicbhDxekcbhiawakcbyd1:H:cjbHjjjjbbg5BdKawclBd2aPcuf:YhKdndnadTmbaqhiaxheadhmindndnaiIdbaKNJbbbZMgO:lJbbb9p9DTmbaO:OhYxekcjjjj94hYkaYcCthYdndnaiclfIdbaKNJbbbZMgO:lJbbb9p9DTmbaO:Oh8Axekcjjjj94h8Aka8AcqtaYVhYdndnaicwfIdbaKNJbbbZMgO:lJbbb9p9DTmbaO:Oh8Axekcjjjj94h8AkaeaYa8AVBdbaicxfhiaeclfheamcufgmmbkazcFeasz:tjjjbhEcbhDcbh3indndndnaEaxa3cdtgCfydbgYcm4aY7c:v;t;h;Ev2gics4ai7aAGgmcdtfg8AydbgecuSmbcehiinaxaecdtgefydbaYSmdamaifheaicefhiaEaeaAGgmcdtfg8Aydbgecu9hmbkka8Aa3BdbaDhiaDcefhDxeka5aefydbhika5aCfaiBdba3cefg3ad9hmbkcuaDc32giaDc;j:KM;jb0EhexekazcFeasz:tjjjb8AcbhDcbhekawaecbyd1:H:cjbHjjjjbbgeBd3awcvBd2aecbaiz:tjjjbh8Aavcd4hxdnadTmbdnalTmbaxcdthEa5hYaqhealhmadhAina8AaYydbc32fgiaeIdbaiIdbMUdbaiaeclfIdbaiIdlMUdlaiaecwfIdbaiIdwMUdwaiamIdbaiIdxMUdxaiamclfIdbaiIdzMUdzaiamcwfIdbaiIdCMUdCaiaiIdKJbbjZMUdKaYclfhYaecxfheamaEfhmaAcufgAmbxdkka5hmaqheadhYina8Aamydbc32fgiaeIdbaiIdbMUdbaiaeclfIdbaiIdlMUdlaiaecwfIdbaiIdwMUdwaiaiIdxJbbbbMUdxaiaiIdzJbbbbMUdzaiaiIdCJbbbbMUdCaiaiIdKJbbjZMUdKamclfhmaecxfheaYcufgYmbkkdnaDTmba8AhiaDheinaiaiIdbJbbbbJbbjZaicKfIdbgO:vaOJbbbb9BEgONUdbaiclfgmaOamIdbNUdbaicwfgmaOamIdbNUdbaicxfgmaOamIdbNUdbaiczfgmaOamIdbNUdbaicCfgmaOamIdbNUdbaic3fhiaecufgembkkcbhYawcuaDcdtgCaDcFFFFi0Egicbyd1:H:cjbHjjjjbbgeBdaawcoBd2awaicbyd1:H:cjbHjjjjbbgEBd8KaecFeaCz:tjjjbh3dnadTmbaoJbbjZJbbjZaK:vaPceSENgOaONhKaxcdthxalheinaKaec;8:G:cjbalEgmIdwa8Aa5ydbgAc32fgiIdC:tgOaONamIdbaiIdx:tgOaONamIdlaiIdz:tgOaONMMNaqcwfIdbaiIdw:tgOaONaqIdbaiIdb:tgOaONaqclfIdbaiIdl:tgOaONMMMhOdndna3aAcdtgifgmydbcuSmbaEaifIdbaO9ETmekamaYBdbaEaifaOUdbka5clfh5aqcxfhqaeaxfheadaYcefgY9hmbkkaba3aCzMjjjb8Acrhikaicdthiawcxfc98fheinaeaifydbcbyd:m:H:cjbH:bjjjbbaic98fgimbkkawc;Wbf8KjjjjbaDk:Pdidui99ducbhi8Jjjjjbca9Rglcbyd1:G:cjbBdKalcb8Pdj:G:cjb83izalcbydN:G:cjbBdwalcb8Pd:m:G:cjb83ibdndnaembJbbjFhvJbbjFhoJbbjFhrxekadcd4cdthwincbhdinalczfadfgDabadfIdbgvaDIdbgoaoav9EEUdbaladfgDavaDIdbgoaoav9DEUdbadclfgdcx9hmbkabawfhbaicefgiae9hmbkalIdwalIdK:thralIdlalIdC:thoalIdbalIdz:thvkJbbbbavavJbbbb9DEgvaoaoav9DEgvararav9DEk9DeeuabcFeaicdtz:tjjjbhlcbhbdnadTmbindnalaeydbcdtfgiydbcu9hmbaiabBdbabcefhbkaeclfheadcufgdmbkkabk;Bidqui998Jjjjjbc;Wb9Rgl8Kjjjjbalcxfcbc;Kbz:tjjjb8Aadcd4adfhvcehoinaogrcethoarav6mbkalcuarcdtgoarcFFFFi0Ecbyd1:H:cjbHjjjjbbgvBdxavcFeaoz:tjjjbhwdnadTmbaicd4hDarcufhqcbhkindndnawcbaeakaD2cdtfgrydlgiaicjjjj94SEgocH4ao7c:F:b:DD2cbarydbgxaxcjjjj94SEgocH4ao7c;D;O:B8J27cbarydwgmamcjjjj94SEgrcH4ar7c:3F;N8N27aqGgvcdtfgrydbgocuSmbam::hPai::hsax::hzcehiinaihrdnaeaoaD2cdtfgiIdbaz9CmbaiIdlas9CmbaiIdwaP9BmikarcefhiawavarfaqGgvcdtfgrydbgocu9hmbkkarakBdbakhokabakcdtfaoBdbakcefgkad9hmbkkalydxcbyd:m:H:cjbH:bjjjbbalc;Wbf8Kjjjjbk9teiucbcbyd:q:H:cjbgeabcifc98GfgbBd:q:H:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabk9teiucbcbyd:q:H:cjbgeabcrfc94GfgbBd:q:H:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikTeeucbabcbyd:q:H:cjbge9Rcifc98GaefgbBd:q:H:cjbdnabZbcztge9nmbabae9RcFFifcz4nb8Akkk:Kedbcj:Gdk1eFFuuFFuuFFuuFFuFFFuFFFuFbbbbbbbbebbbdbbbbbbbebbbebbbdbbbbbbbbbbbeeeeebebbebbebebbbeebbbbbbbbbbbbeeeeeebebbeeebeebbbbebebbbbbbbbbbbbbbbbbbc1:Hdkxebbbdbbb:G:qbb",t=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!=="object")return{supported:!1};var n,i=WebAssembly.instantiate(r(e),{}).then(function(x){n=x.instance,n.exports.__wasm_call_ctors()});function r(x){var _=new Uint8Array(x.length);for(var y=0;y<x.length;++y){var v=x.charCodeAt(y);_[y]=v>96?v-97:v>64?v-39:v+4}var T=0;for(var y=0;y<x.length;++y)_[T++]=_[y]<60?t[_[y]]:(_[y]-60)*64+_[++y];return _.buffer.slice(0,T)}function s(x){if(!x)throw Error("Assertion failed")}function a(x){return new Uint8Array(x.buffer,x.byteOffset,x.byteLength)}function o(x,_,y,v){var T=n.exports.sbrk,A=T(y*4),E=T(y*v*4),w=new Uint8Array(n.exports.memory.buffer);w.set(a(_),E),x(A,E,y,v*4),w=new Uint8Array(n.exports.memory.buffer);var P=new Uint32Array(y);return new Uint8Array(P.buffer).set(w.subarray(A,A+y*4)),T(A-T(0)),P}function c(x,_,y){var v=n.exports.sbrk,T=v(_.length*4),A=v(y*4),E=new Uint8Array(n.exports.memory.buffer),w=a(_);E.set(w,T);var P=x(A,T,_.length,y);E=new Uint8Array(n.exports.memory.buffer);var S=new Uint32Array(y);new Uint8Array(S.buffer).set(E.subarray(A,A+y*4)),v(T-v(0));for(var I=0;I<_.length;++I)_[I]=S[_[I]];return[S,P]}function l(x){var _=0;for(var y=0;y<x.length;++y){var v=x[y];_=_<v?v:_}return _}function u(x,_,y,v,T,A,E,w,P){var S=n.exports.sbrk,I=S(4),U=S(y*4),N=S(T*A),F=S(y*4),D=new Uint8Array(n.exports.memory.buffer);D.set(a(v),N),D.set(a(_),F);var O=x(U,F,y,N,T,A,E,w,P,I);D=new Uint8Array(n.exports.memory.buffer);var K=new Uint32Array(O);a(K).set(D.subarray(U,U+O*4));var B=new Float32Array(1);return a(B).set(D.subarray(I,I+4)),S(I-S(0)),[K,B[0]]}function d(x,_,y,v,T,A,E,w,P,S,I,U,N){var F=n.exports.sbrk,D=F(4),O=F(y*4),K=F(T*A),B=F(T*w),X=F(P.length*4),q=F(y*4),le=S?F(T):0,de=new Uint8Array(n.exports.memory.buffer);if(de.set(a(v),K),de.set(a(E),B),de.set(a(P),X),de.set(a(_),q),S)de.set(a(S),le);var Me=x(O,q,y,K,T,A,B,w,X,P.length,le,I,U,N,D);de=new Uint8Array(n.exports.memory.buffer);var pe=new Uint32Array(Me);a(pe).set(de.subarray(O,O+Me*4));var J=new Float32Array(1);return a(J).set(de.subarray(D,D+4)),F(D-F(0)),[pe,J[0]]}function f(x,_,y,v,T,A,E,w,P,S,I,U,N){var F=n.exports.sbrk,D=F(4),O=F(T*A),K=F(T*w),B=F(P.length*4),X=F(y*4),q=S?F(T):0,le=new Uint8Array(n.exports.memory.buffer);if(le.set(a(v),O),le.set(a(E),K),le.set(a(P),B),le.set(a(_),X),S)le.set(a(S),q);var de=x(X,y,O,T,A,K,w,B,P.length,q,I,U,N,D);le=new Uint8Array(n.exports.memory.buffer),a(_).set(le.subarray(X,X+de*4)),a(v).set(le.subarray(O,O+T*A)),a(E).set(le.subarray(K,K+T*w));var Me=new Float32Array(1);return a(Me).set(le.subarray(D,D+4)),F(D-F(0)),[de,Me[0]]}function h(x,_,y,v){var T=n.exports.sbrk,A=T(y*v),E=new Uint8Array(n.exports.memory.buffer);E.set(a(_),A);var w=x(A,y,v);return T(A-T(0)),w}function b(x,_,y,v,T,A,E,w){var P=n.exports.sbrk,S=P(w*4),I=P(y*v),U=T?P(y*A):0,N=new Uint8Array(n.exports.memory.buffer);if(N.set(a(_),I),T)N.set(a(T),U);var F=x(S,I,y,v,U,A,E,w);N=new Uint8Array(n.exports.memory.buffer);var D=new Uint32Array(F);return a(D).set(N.subarray(S,S+F*4)),P(S-P(0)),D}function m(x,_,y,v,T,A,E,w,P){var S=n.exports.sbrk,I=S(4),U=S(y*4),N=S(T*A),F=S(y*4),D=E?S(T):0,O=new Uint8Array(n.exports.memory.buffer);if(O.set(a(v),N),O.set(a(_),F),E)O.set(a(E),D);var K=x(U,F,y,N,T,A,D,w,P,I);O=new Uint8Array(n.exports.memory.buffer);var B=new Uint32Array(K);a(B).set(O.subarray(U,U+K*4));var X=new Float32Array(1);return a(X).set(O.subarray(I,I+4)),S(I-S(0)),[B,X[0]]}function g(x,_,y,v,T,A,E){var w=n.exports.sbrk,P=w(y*4),S=w(T*A),I=w(y*4),U=new Uint8Array(n.exports.memory.buffer);U.set(a(v),S),U.set(a(_),I);var N=x(P,I,y,S,T,A,E);U=new Uint8Array(n.exports.memory.buffer);var F=new Uint32Array(N);return a(F).set(U.subarray(P,P+N*4)),w(P-w(0)),F}var p={LockBorder:1,Sparse:2,ErrorAbsolute:4,Prune:8,Regularize:16,Permissive:32,_InternalDebug:1073741824};return{ready:i,supported:!0,compactMesh:function(x){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0);var _=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),y=c(n.exports.meshopt_optimizeVertexFetchRemap,_,l(x)+1);if(x!==_)for(var v=0;v<_.length;++v)x[v]=_[v];return y},generatePositionRemap:function(x,_){return s(x instanceof Float32Array),s(x.length%_==0),s(_>=3),o(n.exports.meshopt_generatePositionRemap,x,x.length/_,_)},simplify:function(x,_,y,v,T,A){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v>=0&&v<=x.length),s(v%3==0),s(T>=0);var E=0;for(var w=0;w<(A?A.length:0);++w)s(A[w]in p),E|=p[A[w]];var P=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),S=u(n.exports.meshopt_simplify,P,x.length,_,_.length/y,y*4,v,T,E);return S[0]=x instanceof Uint32Array?S[0]:new x.constructor(S[0]),S},simplifyWithAttributes:function(x,_,y,v,T,A,E,w,P,S){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v instanceof Float32Array),s(v.length==T*(_.length/y)),s(T>=0),s(E==null||E instanceof Uint8Array),s(E==null||E.length==_.length/y),s(w>=0&&w<=x.length),s(w%3==0),s(P>=0),s(Array.isArray(A)),s(T>=A.length),s(A.length<=32);for(var I=0;I<A.length;++I)s(A[I]>=0);var U=0;for(var I=0;I<(S?S.length:0);++I)s(S[I]in p),U|=p[S[I]];var N=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),F=d(n.exports.meshopt_simplifyWithAttributes,N,x.length,_,_.length/y,y*4,v,T*4,new Float32Array(A),E,w,P,U);return F[0]=x instanceof Uint32Array?F[0]:new x.constructor(F[0]),F},simplifyWithUpdate:function(x,_,y,v,T,A,E,w,P,S){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v instanceof Float32Array),s(v.length==T*(_.length/y)),s(T>=0),s(E==null||E instanceof Uint8Array),s(E==null||E.length==_.length/y),s(w>=0&&w<=x.length),s(w%3==0),s(P>=0),s(Array.isArray(A)),s(T>=A.length),s(A.length<=32);for(var I=0;I<A.length;++I)s(A[I]>=0);var U=0;for(var I=0;I<(S?S.length:0);++I)s(S[I]in p),U|=p[S[I]];var N=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),F=f(n.exports.meshopt_simplifyWithUpdate,N,x.length,_,_.length/y,y*4,v,T*4,new Float32Array(A),E,w,P,U);if(x!==N)for(var I=0;I<F[0];++I)x[I]=N[I];return F},getScale:function(x,_){return s(x instanceof Float32Array),s(x.length%_==0),s(_>=3),h(n.exports.meshopt_simplifyScale,x,x.length/_,_*4)},simplifyPoints:function(x,_,y,v,T,A){if(s(x instanceof Float32Array),s(x.length%_==0),s(_>=3),s(y>=0&&y<=x.length/_),v)return s(v instanceof Float32Array),s(v.length%T==0),s(T>=3),s(x.length/_==v.length/T),b(n.exports.meshopt_simplifyPoints,x,x.length/_,_*4,v,T*4,A||0,y);else return b(n.exports.meshopt_simplifyPoints,x,x.length/_,_*4,void 0,0,0,y)},simplifySloppy:function(x,_,y,v,T,A){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v==null||v instanceof Uint8Array),s(v==null||v.length==_.length/y),s(T>=0&&T<=x.length),s(T%3==0),s(A>=0);var E=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),w=m(n.exports.meshopt_simplifySloppy,E,x.length,_,_.length/y,y*4,v,T,A);return w[0]=x instanceof Uint32Array?w[0]:new x.constructor(w[0]),w},simplifyPrune:function(x,_,y,v){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v>=0);var T=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),A=g(n.exports.meshopt_simplifyPrune,T,x.length,_,_.length/y,y*4,v);return A=x instanceof Uint32Array?A:new x.constructor(A),A}}}()});var HW;var gR=mt(()=>{HW=function(){var e="b9H79Tebbbe:neP9Geueu9Geub9Gbb9Giuuueu9Gmuuuuuuuuuuu9999eu9Gouuuuuueu9Gruuuuuuub9Gxuuuuuuuuuuuueu9Gxuuuuuuuuuuu99eu9GPuuuuuuuuuuuuu99b9Gouuuuuub9Gwuuuuuuuub9Gvuuuuub9GluuuubiQXdilvorwDqokoqxmbiibeilve9Weiiviebeoweuecj:Gdkr;Zeqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9I919P29K9nW79O2Wt79c9V919U9KbeY9TW79O9V9Wt9F9I919P29K9nW79O2Wt7S2W94bd39TW79O9V9Wt9F9I919P29K9nW79O2Wt79t9W9Ht9P9H2bo39TW79O9V9Wt9F9J9V9T9W91tWJ2917tWV9c9V919U9K7bw39TW79O9V9Wt9F9J9V9T9W91tW9nW79O2Wt9c9V919U9K7bkE9TW79O9V9Wt9F9J9V9T9W91tW9t9W9OWVW9c9V919U9K7bxL9TW79O9V9Wt9F9V9Wt9P9T9P96W9nW79O2WtbPl79IV9RbsDwebcekdOAq;W:leXdbkIbabaec9:fgefcufae9Ugeabci9Uadfcufad9Ugbaeab0Ek:88JDPue99eux99due99euo99iu8Jjjjjbc:WD9Rgm8KjjjjbdndnalmbcbhPxekamc:Cwfcbc;Kbz:rjjjb8AcuaocdtgsaocFFFFi0Ehzcbyd;0:G:cjbhHdndnalcb9imbaoal9nmbamazaHHjjjjbbgHBd:CwamceBd;8wamazcbyd;0:G:cjbHjjjjbbgOBd:GwamcdBd;8wamcualcdtalcFFFFi0Ecbyd;0:G:cjbHjjjjbbgABd:KwamciBd;8waihzalhsinaHazydbcdtfcbBdbazclfhzascufgsmbkaihzalhsinaHazydbcdtfgCaCydbcefBdbazclfhzascufgsmbkaihzalhCcbhXindnaHazydbcdtgQfgsydbcb9imbaOaQfaXBdbasasydbgQcjjjj94VBdbaQaXfhXkazclfhzaCcufgCmbkalci9UhLdnalci6mbcbhzaihsinascwfydbhCasclfydbhXaOasydbcdtfgQaQydbgQcefBdbaAaQcdtfazBdbaOaXcdtfgXaXydbgXcefBdbaAaXcdtfazBdbaOaCcdtfgCaCydbgCcefBdbaAaCcdtfazBdbascxfhsaLazcefgz9hmbkkaihzalhsindnaHazydbcdtgCfgXydbgQcu9kmbaXaQcFFFFrGgQBdbaOaCfgCaCydbaQ9RBdbkazclfhzascufgsmbxdkkamazaHHjjjjbbgHBd:CwamceBd;8wamazcbyd;0:G:cjbHjjjjbbgOBd:GwamcdBd;8wamcualcdtalcFFFFi0Ecbyd;0:G:cjbHjjjjbbgABd:KwamciBd;8waHcbasz:rjjjbhXaihzalhsinaXazydbcdtfgCaCydbcefBdbazclfhzascufgsmbkalci9UhLdnaoTmbcbhzaOhsaXhCaohQinasazBdbasclfhsaCydbazfhzaCclfhCaQcufgQmbkkdnalci6mbcbhzaihsinascwfydbhCasclfydbhQaOasydbcdtfgKaKydbgKcefBdbaAaKcdtfazBdbaOaQcdtfgQaQydbgQcefBdbaAaQcdtfazBdbaOaCcdtfgCaCydbgCcefBdbaAaCcdtfazBdbascxfhsaLazcefgz9hmbkkaoTmbcbhzaohsinaOazfgCaCydbaXazfydb9RBdbazclfhzascufgsmbkkamaLcbyd;0:G:cjbHjjjjbbgzBd:OwamclBd;8wazcbaLz:rjjjbhYamcuaLcK2alcjjjjd0Ecbyd;0:G:cjbHjjjjbbg8ABd:SwamcvBd;8wJbbbbhEdnalci6g3mbarcd4hKaihsa8AhzaLhrJbbbbh5inavasclfydbaK2cdtfgCIdlh8EavasydbaK2cdtfgXIdlhEavascwfydbaK2cdtfgQIdlh8FaCIdwhaaXIdwhhaQIdwhgazaCIdbg8JaXIdbg8KMaQIdbg8LMJbbnn:vUdbazclfaXIdlaCIdlMaQIdlMJbbnn:vUdbaQIdwh8MaCIdwh8NaXIdwhyazcxfa8EaE:tg8Eagah:tggNaaah:tgaa8FaE:tghN:tgEJbbbbJbbjZa8Ja8K:tg8FahNa8Ea8La8K:tg8KN:tghahNaEaENaaa8KNa8FagN:tgEaENMMg8K:rg8E:va8KJbbbb9BEg8KNUdbazczfaEa8KNUdbazcCfaha8KNUdbazcwfa8Maya8NMMJbbnn:vUdba5a8EMh5ascxfhsazcKfhzarcufgrmbka5aL:Z:vJbbbZNhEkamcuaLcdtalcFFFF970Ecbyd;0:G:cjbHjjjjbbgCBd:WwamcoBd;8waq:Zhhdna3mbcbhzaChsinasazBdbasclfhsaLazcefgz9hmbkkaEahNhhamcuaLcltalcFFFFd0Ecbyd;0:G:cjbHjjjjbbg8PBd:0wamcrBd;8wcba8Pa8AaCaLcbz:djjjb8AJFFuuh8MJFFuuh8NJFFuuhydnalci6mbJFFuuhya8AhzaLhsJFFuuh8NJFFuuh8MinazcwfIdbgEa8Ma8MaE9EEh8MazclfIdbgEa8Na8NaE9EEh8NazIdbgEayayaE9EEhyazcKfhzascufgsmbkkah:rhEamaocetgzcuaocu9kEcbyd;0:G:cjbHjjjjbbgCBd:4wdndnaoal9nmbaihzalhsinaCazydbcetfcFFi87ebazclfhzascufgsmbxdkkaCcFeazz:rjjjb8AkaEJbbbZNh8JcuhIdnalci6mbcbhsJFFuuhEa8AhzcuhIinazcwfIdba8M:tghahNazIdbay:tghahNazclfIdba8N:tghahNMM:rghaEaIcuSahaE9DVgXEhEasaIaXEhIazcKfhzaLascefgs9hmbkkamczfcbcjwz:rjjjb8Aam9cb83iwam9cb83ibaxa8JNh8RJbbjZak:th8Lcbh8SJbbbbhRJbbbbh8UJbbbbh8VJbbbbh8WJbbbbh8XJbbbbh8Ycbh8ZcbhPinJbbbbhEdna8STmbJbbjZa8S:Z:vhEkJbbbbhhdna8Ya8YNa8Wa8WNa8Xa8XNMMg8KJbbbb9BmbJbbjZa8K:r:vhhka8VaENh8Ka8UaENh5aRaENh8EaIhLdndndndndna8SaPVTmbamydwg80Tmea8YahNh8Fa8XahNhaa8WahNhgaeamydbcdtfh81cbh3JFFuuhEcvhQcuhLindnaHa81a3cdtfydbcdtgzfydbgvTmbaAaOazfydbcdtfhsindndnaCaiasydbgKcx2fgzclfydbgrcetf8Vebcs4aCazydbgXcetf8Vebcs4faCazcwfydbglcetf8Vebcs4fgombcbhzxekcehzaHaXcdtfydbgXceSmbcehzaHarcdtfydbgrceSmbcehzaHalcdtfydbglceSmbdnarcdSaXcdSfalcdSfcd6mbaocefhzxekaocdfhzkdnazaQ9kmba8AaKcK2fgXIdwa8K:tghahNaXIdba8E:tghahNaXIdla5:tghahNMM:ra8J:va8LNJbbjZMJ9VO:d86JbbjZaXIdCa8FNaXIdxagNaaaXIdzNMMakN:tghahJ9VO:d869DENghaEazaQ6ahaE9DVgXEhEaKaLaXEhLazaQaXEhQkasclfhsavcufgvmbkka3cefg3a809hmbkkaLcu9hmekama8KUd:ODama5Ud:KDama8EUd:GDamcuBd:qDamcFFF;7rBdjDa8Pcba8AaYamc:GDfamc:qDfamcjDfz:ejjjbamyd:qDhLdndnaxJbbbb9ETmba8SaD6mbaLcuSmeceh3amIdjDa8R9EmixdkaLcu9hmekdna8STmbabaPcltfgHam8Piw83dwaHam8Pib83dbaPcefhPkc3hHinamc:CwfaHfydbcbyd;4:G:cjbH:bjjjbbaHc98fgHc989hmbxvkkcbh3a8Saq9pmbamydwaCaiaLcx2fgzydbcetf8Vebcs4aCazcwfydbcetf8Vebcs4faCazclfydbcetf8Vebcs4ffaw9nmekcbhzcbhsdna8ZTmbcbhsamczfhXinamczfascdtfaXydbgQBdbaXclfhXasaYaQfRbbTfhsa8Zcufg8ZmbkkamydwhlamydbhXam9cu83i:GDam9cu83i:ODam9cu83i:qDam9cu83i:yDinamcjDfazfcFFF;7rBdbazclfgzcz9hmbkasc;8easclfc:bd6Eg8Zcdth80dnalTmbaeaXcdtfhocbhrindnaHaoarcdtfydbcdtgzfydbgvTmbaAaOazfydbcdtfhscuhQcuhzinaHaiasydbgKcx2fgXclfydbcdtfydbaHaXydbcdtfydbfaHaXcwfydbcdtfydbfgXazaXaz6gXEhzaKaQaXEhQasclfhsavcufgvmbkaQcuSmba8AaQcK2fgsIdwa8M:tgEaENasIdbay:tgEaENasIdla8N:tgEaENMM:rhEcbhsindndnazamc:qDfasfgvydbgX6mbazaX9hmeaEamcjDfasfIdb9FTmekavazBdbamc:GDfasfaQBdbamcjDfasfaEUdbxdkasclfgscz9hmbkkarcefgral9hmbkkamczfa80fhQcbhzcbhsindnamc:GDfazfydbgXcuSmbaQascdtfaXBdbascefhskazclfgzcz9hmbkasa8Zfg8ZTmbJFFuuhhcuhKamczfhza8ZhvcuhQina8AazydbgXcK2fgsIdwa8M:tgEaENasIdbay:tgEaENasIdla8N:tgEaENMM:rhEdndnaHaiaXcx2fgsclfydbcdtfydbaHasydbcdtfydbfaHascwfydbcdtfydbfgsaQ6mbasaQ9hmeaEah9DTmekaEhhashQaXhKkazclfhzavcufgvmbkaKcuSmbaKhLkdnamaiaLcx2fgrydbarclfydbarcwfydbaCabaeadaPawaqa3z:fjjjbTmbaPcefhPJbbbbhRJbbbbh8UJbbbbh8VJbbbbh8WJbbbbh8XJbbbbh8YkcbhXinaAaOaraXcdtfydbcdtgsfydbcdtfgKhzaHasfgvydbgQhsdnaQTmbdninazydbaLSmeazclfhzascufgsTmdxbkkazaKaQcdtfc98fydbBdbavavydbcufBdbkaXcefgXci9hmbka8AaLcK2fgzIdbhEazIdlhhazIdwh8KazIdxh5azIdzh8EazIdCh8FaYaLfce86bba8Ya8FMh8Ya8Xa8EMh8Xa8Wa5Mh8Wa8Va8KMh8Va8UahMh8UaRaEMhRamydxh8Sxbkkamc:WDf8KjjjjbaPkjoivuv99lu8Jjjjjbca9Rgo8Kjjjjbdndnalcw0mbaiydbhraeabcitfgwalcdtciVBdlawarBdbdnalcd6mbaiclfhralcufhDawcxfhwinarydbhqawcuBdbawc98faqBdbawcwfhwarclfhraDcufgDmbkkalabfhwxekcbhqaocbBdKao9cb83izaocbBdwao9cb83ibJbbjZhkJbbjZhxinadaiaqcdtfydbcK2fhDcbhwinaoczfawfgraDawfIdbgmarIdbgP:tgsaxNaPMgPUdbaoawfgrasamaP:tNarIdbMUdbawclfgwcx9hmbkJbbjZakJbbjZMgk:vhxaqcefgqal9hmbkcbhradcbcecdaoIdlgmaoIdwgP9GEgwaoIdbgsaP9GEawasam9GEgzcdtgwfhHaoczfawfIdbhmaihwalhDinaiarcdtfgqydbhOaqawydbgABdbawaOBdbawclfhwaraHaAcK2fIdbam9DfhraDcufgDmbkdndnarcv6mbavc8X9kmbaralc98f6mekaiydbhraeabcitfgwalcdtciVBdlawarBdbaiclfhralcufhDawcxfhwinarydbhqawcuBdbawc98faqBdbawcwfhwarclfhraDcufgDmbkalabfhwxekaeabcitfgwamUdbawawydlc98GazVBdlabcefaeadaiaravcefgqz:djjjbhDawawydlciGaDabcu7fcdtVBdlaDaeadaiarcdtfalar9Raqz:djjjbhwkaocaf8Kjjjjbawk;Oddvue99dninabaecitfgrydlgwcd4gDTmednawciGgqci9hmbcihqdnawcl6mbabaecitfhbcbheawhqcehkindnaiabydbgDfRbbmbcbhkadaDcK2fgwIdwalIdw:tgxaxNawIdbalIdb:tgxaxNawIdlalIdl:tgxaxNMM:rgxaoIdb9DTmbaoaxUdbavaDBdbarydlhqkabcwfhbaecefgeaqcd46mbkakceGTmikaraqciGBdlskdnabcbaDalaqcdtfIdbarIdb:tgxJbbbb9FEgwaD7aecefgDfgecitfydlabawaDfgDcitfydlVci0mbaraqBdlkabaDadaialavaoz:ejjjbax:laoIdb9Fmbkkkjlevudndnabydwgxaladcetfgm8Vebcs4alaecetfgP8Vebgscs4falaicetfgz8Vebcs4ffaD0mbakmbcbhDabydxaq6mekavawcltfgxab8Pdw83dwaxab8Pdb83dbabydbhDdnabydwgwTmbaoaDcdtfhxawhsinalaxydbcetfcFFi87ebaxclfhxascufgsmbkkabaDawfBdbabydxhxab9cb83dwababydlaxci2fBdlaP8VebhscehDcbhxkdnascztcz91cu9kmbabaxcefBdwaPax87ebaoabydbcdtfaxcdtfaeBdbkdnam8Uebcu9kmbababydwgxcefBdwamax87ebaoabydbcdtfaxcdtfadBdbkdnaz8Uebcu9kmbababydwgxcefBdwazax87ebaoabydbcdtfaxcdtfaiBdbkarabydlfabydxci2faPRbb86bbarabydlfabydxci2fcefamRbb86bbarabydlfabydxci2fcdfazRbb86bbababydxcefBdxaDk:mPrHue99eue99eue99iu8Jjjjjbc;W;Gb9Rgx8KjjjjbdndnalmbcbhmxekcbhPaxc:m;Gbfcbc;Kbz:rjjjb8Aaxcualci9UgscltascjjjjiGEcbyd;0:G:cjbHjjjjbbgzBd:m9GaxceBd;S9GaxcuascK2gHcKfalcpFFFe0Ecbyd;0:G:cjbHjjjjbbgOBd:q9GaxcdBd;S9Gdnalci6gAmbarcd4hCascdthXaOhQazhLinavaiaPcx2fgrydwaC2cdtfhKavarydlaC2cdtfhYavarydbaC2cdtfh8AcbhraLhEinaQarfgma8Aarfg3Idbg5aYarfg8EIdbg8Fa5a8F9DEg5UdbamaKarfgaIdbg8Fa5a8Fa59DEg8FUdbamcxfgma3Idbg5a8EIdbgha5ah9EEg5UdbamaaIdbgha5aha59EEg5UdbaEa8Fa5MJbbbZNUdbaEaXfhEarclfgrcx9hmbkaQcKfhQaLclfhLaPcefgPas9hmbkkaOaHfgr9cb83dbar9cb83dzar9cb83dwaxcuascx2gralc:bjjjl0Ecbyd;0:G:cjbHjjjjbbgHBdN9GaxciBd;S9GascdthgazarfhvaxcwVhPaxclVhCaHh8Jazh8KcbhLinaxcbcj;Gbz:rjjjbhEaLas2cdthadnaAmba8Khrash3inaEarydbgmc8F91cjjjj94Vam7gmcQ4cx2fg8Ea8EydwcefBdwaEamcd4cFrGcx2fg8Ea8EydbcefBdbaEamcx4cFrGcx2fgmamydlcefBdlarclfhra3cufg3mbkkazaafh8AaHaafhXcbhmcbh3cbh8EcbhainaEamfgrydbhQara3BdbarcwfgKydbhYaKaaBdbarclfgrydbhKara8EBdbaQa3fh3aYaafhaaKa8Efh8Eamcxfgmcj;Gb9hmbkdnaAmbcbhravhminamarBdbamclfhmasarcefgr9hmbkavhrashminaEa8Aarydbg3cdtfydbg8Ec8F91a8E7cd4cFrGcx2fg8Ea8Eydbg8EcefBdbaXa8Ecdtfa3Bdbarclfhramcufgmmbka8JhrashminaCa8Aarydbg3cdtfydbg8Ec8F91a8E7cx4cFrGcx2fg8Ea8Eydbg8EcefBdbava8Ecdtfa3BdbarclfhramcufgmmbkavhrashminaPa8Aarydbg3cdtfydbg8Ec8F91cjjjj94Va8E7cQ4cx2fg8Ea8Eydbg8EcefBdbaXa8Ecdtfa3Bdbarclfhramcufgmmbkka8Jagfh8Ja8Kagfh8KaLcefgLci9hmbkaEaocetgrcuaocu9kEcbyd;0:G:cjbHjjjjbbgKBd:y9GaEclBd;S9Gdndnaoal9nmbaihralhminaKarydbcetfcFFi87ebarclfhramcufgmmbxdkkaKcFearz:rjjjb8Akcbh8EaEascbyd;0:G:cjbHjjjjbbg8ABd:C9GaOaHaHascdtfaHascitfa8AascbazaKaiawaDaqakz:hjjjbdndnalci6mba8Ahrashmina8EarRbbfh8EarcefhramcufgmmbkaE9cb83iwaE9cb83ibalawc9:fgrfcufar9UgrasaDfcufaD9Ugmaram0EhYcbhmcbhra8Ehaincbh3dnarTmba8AarfRbbceSh3kamaEaiaHydbcx2fgQydbaQclfydbaQcwfydbaKabaeadamawaqa3a3ce7a8EaY9nVaaamfaY6VGz:fjjjbfhmaHclfhHaaa8AarfRbb9Rhaasarcefgr9hmbkaEydxTmeabamcltfgraE8Piw83dwaraE8Pib83dbamcefhmxekaE9cb83iwaE9cb83ibcbhmkczhrinaEc:m;Gbfarfydbcbyd;4:G:cjbH:bjjjbbarc98fgrc989hmbkkaxc;W;Gbf8Kjjjjbamk:wKDQue99iue99iul9:euw99iu8Jjjjjbc;qb9RgP8Kjjjjbaxhsaxhzdndnavax0gHmbdnavTmbcbhOaehzavhAinawaDazydbcx2fgCcwfydbcetfgX8VebhQawaCclfydbcetfgL8VebhKawaCydbcetfgC8VebhYaXce87ebaLce87ebaCce87ebaOaKcs4aYcs4faQcs4ffhOazclfhzaAcufgAmbkaehzavhAinawaDazydbcx2fgCcwfydbcetfcFFi87ebawaCclfydbcetfcFFi87ebawaCydbcetfcFFi87ebazclfhzaAcufgAmbkcehzaqhsaOaq0mekalce86bbalcefcbavcufz:rjjjb8AxekaPaiBdxaPadBdwaPaeBdlavakaqci9Ug8Aaka8Aak6EaHEgK9RhEaxaK9Rh3aKcufh5aKceth8EaKcdtgCc98fh8FavcitgOaC9Rarfc98fhaascufhhavcufhgaraOfh8JJbbjZas:Y:vh8KcbazceakaxSEg8Lcdtg8M9Rh8NJFFuuhycuh8PcbhIcbh8RinaPclfa8RcdtfydbhQaPcb8Pd:y:G:cjbg8S83i9iaPcb8Pd:q:G:cjbgR83inaPcb8Pd1:G:cjbg8U83iUaPcb8Pdj:G:cjbg8V83i8WaPa8S83iyaPaR83iaaPa8U83iKaPa8V83izaQavcdtgYfh8WcbhXinabaQaXcdtgLfydbcK2fhAcbhzinaPc8WfazfgCaAazfgOIdbg8XaCIdbg8Ya8Xa8Y9DEUdbaCczfgCaOcxfIdbg8XaCIdbg8Ya8Xa8Y9EEUdbazclfgzcx9hmbkaba8WaXcu7cdtfydbcK2fhAcbhzaPIdUh8ZaPId9ih80aPId80h81aPId9ehBaPId8Wh83aPIdnhUinaPczfazfgCaAazfgOIdbg8XaCIdbg8Ya8Xa8Y9DEUdbaCczfgCaOcxfIdbg8XaCIdbg8Ya8Xa8Y9EEUdbazclfgzcx9hmbkaraLfgzaBa81:tg8Xa80a8Z:tg8YNaUa83:tg8Za8XNa8Za8YNMMUdbazaYfaPId8KaPIdC:tg8XaPIdyaPIdK:tg8YNaPIdaaPIdz:tg8Za8XNa8Za8YNMMUdbaXcefgXav9hmbkcbh85dnaHmbcbhAaQhza8JhCavhXinawaDazydbcx2fgOcwfydbcetfgL8Vebh8WawaOclfydbcetfg858Vebh86awaOydbcetfgO8Vebh87aLce87eba85ce87ebaOce87ebaCaAa86cs4a87cs4fa8Wcs4ffgABdbazclfhzaCclfhCaXcufgXmbkavhCinawaDaQydbcx2fgzcwfydbcetfcFFi87ebawazclfydbcetfcFFi87ebawazydbcetfcFFi87ebaQclfhQaCcufgCmbka8Jh85kdndndndndndndndndndndnava8E6mba8Eax9nmeavavaK9UgzaK29Raza320mda5aE9pmqa85Th87ceh8WaEhQxwka5ag9pmDa8Eax9nmixokavaK6mea5aE9pmwcehQaEhXa85Tmixlka5ag6mlxrka5ag9pmokcbhQaghXa85mekJFFuuh8XcbhLa5hzindnazcefgCaK6mbaQavaC9RgOaK6GmbarazcdtfIdbg8YaC:YNaravaz9RcdtfaYfc94fIdbg8ZaO:YNMg80a8X9Embdndna8KaOahf:YNg81:lJbbb9p9DTmba81:OhAxekcjjjj94hAka8ZasaA2aO9R:YNh8Zdndna8Kazasf:YNg81:lJbbb9p9DTmba81:OhOxekcjjjj94hOkamasaO2aC9R:Ya8YNa8ZMNa80Mg8Ya8Xa8Ya8X9DgOEh8XaCaLaOEhLkaza8LfgzaX6mbxlkkJFFuuh8XcbhLaEhCaahAa8FhOaKhzindnazaK6mbaQaCaK6GmbaraOfIdbg8Yaz:YNaAIdbg8ZaC:YNMg80a8X9Embdndna8Ka85aOfydbgYahf:YNg81:lJbbb9p9DTmba81:Oh8Wxekcjjjj94h8Wkamasa8W2aY9R:Yg81a8YNa8Za81NMNa80Mg8Ya8Xa8Ya8X9DgYEh8XazaLaYEhLkaCa8L9RhCaAa8NfhAaOa8MfhOaza8LfgzcufaX6mbxikka85Th87cbh8WaghQkJFFuuh8XcbhLaEhCaahAa8FhOaKhzindnazazaK9UgXaK29RaXa320mbdna8WTmbaCaCaK9UgXaK29RaXa320mekaraOfIdbg8Yaz:YNaAIdbg8ZaC:YNMg80a8X9EmbazhXaChYdna87mba85aOfydbgXhYkdndna8KaYahf:YNg81:lJbbb9p9DTmba81:Oh86xekcjjjj94h86ka8Zasa862aY9R:YNh8Zdndna8KaXahf:YNg81:lJbbb9p9DTmba81:OhYxekcjjjj94hYkamasaY2aX9R:Ya8YNa8ZMNa80Mg8Ya8Xa8Ya8X9DgXEh8XazaLaXEhLkaCa8L9RhCaAa8NfhAaOa8MfhOaza8LfgzcufaQ6mbkkaLTmba8Xay9DTmba8XhyaLhIa8Rh8Pka8Rcefg8Rci9hmbkdndnaoc8X9kmba8Pcb9omeka8Acufh85cbhYindndndnavaY9RaxaYaxfav0Eg8WTmbcbhAaeaYcdtfgzhCa8WhXinawaDaCydbcx2fgOcwfydbcetfgQ8VebhbawaOclfydbcetfgL8VebhrawaOydbcetfgO8VebhKaQce87ebaLce87ebaOce87ebaAarcs4aKcs4fabcs4ffhAaCclfhCaXcufgXmbka8WhOinawaDazydbcx2fgCcwfydbcetfcFFi87ebawaCclfydbcetfcFFi87ebawaCydbcetfcFFi87ebazclfhzaOcufgOmbkaAaq0mekalaYfgzce86bbazcefcba8Wcufz:rjjjb8AxekalaYfgzce86bbazcefcba85z:rjjjb8Aa8Ah8Wka8WaYfgYav9pmdxbkkaravcdtg8WfhLdnaITmbaPclfa8PcdtfydbhzaIhCinaLazydbfcb86bbazclfhzaCcufgCmbkkdnavaI9nmbaPclfa8PcdtfydbaIcdtfhzavaI9RhCinaLazydbfce86bbazclfhzaCcufgCmbkkcbhYindnaYa8PSmbcbhzaraPclfaYcdtfydbgKa8Wz:qjjjbhCavhXaIhOinaKaOazaLaCydbgQfRbbgAEcdtfaQBdbaCclfhCaOaAfhOazaA9RcefhzaXcufgXmbkkaYcefgYci9hmbkabaeadaialaIaocefgCarawaDaqakaxamz:hjjjbabaeaIcdtgzfadazfaiazfalaIfavaI9RaCarawaDaqakaxamz:hjjjbkaPc;qbf8Kjjjjbk:Seeru8Jjjjjbc:q;ab9Rgo8Kjjjjbaoc:q8WfcFecjzz:rjjjb8AcbhrdnadTmbaehwadhDinaoarcdtfawydbgqBdbaoc:q8WfaqcFiGcdtfgkydbhxakaqBdbawclfhwaraxaq9hfhraDcufgDmbkkabaeadaoaraiavz:jjjjbaoc:q;abf8Kjjjjbk;Sqloud99euD998Jjjjjbc:W;ab9Rgr8KjjjjbdndnadTmbaocd4hwcbhDcbhqindnavaeclfydbaw2cdtfgkIdbavaeydbaw2cdtfgxIdbgm:tgPavaecwfydbaw2cdtfgsIdlaxIdlgz:tgHNakIdlaz:tgOasIdbam:tgAN:tgCaCNaOasIdwaxIdwgX:tgQNakIdwaX:tgOaHN:tgHaHNaOaANaPaQN:tgPaPNMMgOJbbbb9Bmbarc8WfaDcltfgkaCaO:rgO:vgCUdwakaPaO:vgPUdlakaHaO:vgHUdbakaCaXNaHamNazaPNMM:mUdxaDcefhDkaecxfheaqcifgqad6mbkab9cb83dyab9cb83daab9cb83dKab9cb83dzab9cb83dwab9cb83dbaDTmearcbBd8Sar9cb83iKar9cb83izarczfavalaoarc8Sfcbcraiz:kjjjbarIdKhQarIdChLarIdzhKar9cb83iwar9cb83ibararc8WfaDczarc8Sfcbcicbz:kjjjbJbbbbhmdnarIdwgzazNarIdbgHaHNarIdlgXaXNMMgCJbbbb9BmbJbbjZaC:r:vhmkazamNhCaXamNhXaHamNhHJbbjZhmarc8WfheaDhvinaecwfIdbaCNaeIdbaHNaXaeclfIdbNMMgzamazam9DEhmaeczfheavcufgvmbkabaQUdwabaLUdlabaKUdbabarId3UdxdndnamJ;n;m;m899FmbJbbbbhzarc8WfheinaecxfIdbaQaecwfIdbgPNaKaeIdbgONaLaeclfIdbgANMMMaCaPNaHaONaXaANMM:vgPazaPaz9EEhzaeczfheaDcufgDmbkabaCUd8KabaXUdaabaHUd3abaQaCazN:tUdKabaLaXazN:tUdCabaKaHazN:tUdzabJbbjZamamN:t:rgmUdydndnaCJbbj:;aCJbbj:;9GEgzJbbjZazJbbjZ9FEJbb;:9cNJbbbZJbbb:;aCJbbbb9GEMgz:lJbbb9p9DTmbaz:Ohexekcjjjj94hekabae86b8UdndnaXJbbj:;aXJbbj:;9GEgzJbbjZazJbbjZ9FEJbb;:9cNJbbbZJbbb:;aXJbbbb9GEMgz:lJbbb9p9DTmbaz:Ohvxekcjjjj94hvkabav86bRdndnaHJbbj:;aHJbbj:;9GEgzJbbjZazJbbjZ9FEJbb;:9cNJbbbZJbbb:;aHJbbbb9GEMgz:lJbbb9p9DTmbaz:Ohwxekcjjjj94hwkabaw86b8SdndnaecKtcK91:YJbb;:9c:vaC:t:lavcKtcK91:YJbb;:9c:vaX:t:lawcKtcK91:YJbb;:9c:vaH:t:lamMMMJbb;:9cNJbbjZMgm:lJbbb9p9DTmbam:Ohexekcjjjj94hekaecFbaecFb9iEhexekabcjjj;8iBdycFbhekabae86b8Vxekab9cb83dyab9cb83daab9cb83dKab9cb83dzab9cb83dwab9cb83dbkarc:W;abf8Kjjjjbk;7woDuo99eue99euv998Jjjjjbcje9Rgw8Kjjjjbawc;abfcbaocdtgDz:rjjjb8Aawc;GbfcbaDz:rjjjb8AawcafhDawhqaohkinaqcFFF97BdbaDcFFF;7rBdbaqclfhqaDclfhDakcufgkmbkavcd4hxaicd4hmdnadTmbaocx2hPcbhsinashzdnarTmbarascdtfydbhzkaeazam2cdtfgDIdwhHaDIdlhOaDIdbhAalazax2cdtfIdbhCcbhDawcafhqawc;Gbfhvawhkawc;abfhiinaCaDc:O:G:cjbfIdbaHNaDc:G:G:cjbfIdbaANaDc:K:G:cjbfIdbaONMMgXMhQazhLdnaXaC:tgXaqIdbgK9DgYmbavydbhLkavaLBdbazhLdnaQakIdbg8A9EmbaiydbhLa8AhQkaiaLBdbakaQUdbaqaXaKaYEUdbaiclfhiakclfhkavclfhvaqclfhqaPaDcxfgD9hmbkascefgsad9hmbkkJbbbbhQcbhLawc;GbfhDawc;abfhqcbhkinalaqydbgvax2cdtfIdbalaDydbgiax2cdtfIdbaeavam2cdtfgvIdwaeaiam2cdtfgiIdw:tgCaCNavIdbaiIdb:tgCaCNavIdlaiIdl:tgCaCNMM:rMMgCaQaCaQ9EgvEhQakaLavEhLaqclfhqaDclfhDaoakcefgk9hmbkJbbbbhCdnaeawc;abfaLcdtgqfydbgkam2cdtfgDIdwaeawc;Gbfaqfydbgvam2cdtfgqIdwgH:tgXaXNaDIdbaqIdbgA:tg8Aa8ANaDIdlaqIdlgE:tgOaONMMgKJbbbb9ETmbaK:rgCalakax2cdtfIdbMalavax2cdtfIdb:taCaCM:vhCkaQJbbbZNhKaXaCNaHMhHaOaCNaEMhOa8AaCNaAMhAdnadTmbcbhqarhkinaqhDdnarTmbakydbhDkdnalaDax2cdtfIdbg3aeaDam2cdtfgDIdwaH:tgQaQNaDIdbaA:tgCaCNaDIdlaO:tgXaXNMMg5:rgEMg8EaK9ETmbJbbbbh8Adna5Jbbbb9ETmba8EaK:taEaEM:vh8Aka8AaQNaHMhHa8AaXNaOMhOa8AaCNaAMhAa3aKaEMMJbbbZNhKkakclfhkadaqcefgq9hmbkkabaKUdxabaHUdwabaOUdlabaAUdbawcjef8Kjjjjbk:reevu8Jjjjjbcj8W9Rgr8Kjjjjbaici2hwcbhDdnaiTmbarhiawhqinaiaeadRbbgkcdtfydbBdbaDakcefgkaDak0EhDaiclfhiadcefhdaqcufgqmbkkabarawaeaDalaoz:jjjjbarcj8Wf8Kjjjjbk:Eeeeu8Jjjjjbca9Rgo8Kjjjjbab9cb83dyab9cb83daab9cb83dKab9cb83dzab9cb83dwab9cb83dbdnadTmbaocbBd3ao9cb83iwao9cb83ibaoaeadaialaoc3falEavcbalEcrcbz:kjjjbabao8Pib83dbabao8Piw83dwkaocaf8Kjjjjbk::meQu8Jjjjjbcjz9Rgv8KjjjjbcbhoavcjPfcbaez:rjjjb8Aavcjxfcbaez:rjjjb8AdnaiTmbadhoaihrinavcjxfaoRbbfgwawRbbcef86bbavcjxfaocefRbbfgwawRbbcef86bbavcjxfaocdfRbbfgwawRbbcef86bbaocifhoarcufgrmbkcbhDcjehoadhqcehkindndnalTmbcbhxcuhmaqhrakhwcuhPinawcufamaoavcjPfarcefRbbgsfRbb9RcFeGgzci6aoavcjPfarRbbgHfRbb9RcFeGgOci6faoavcjPfarcdfRbbgAfRbb9RcFeGgCci6fgXcOtaOcFr7azaCf9RcwtVavcjxfaAfRbbgzavcjxfaHfRbbgHavcjxfasfRbbgsaHas6Egsazas6EcFe7VgsaP9kgzEhmaXcd6gHaxcefgOal9iVce9hmdasaPazEhPaxaOaHEhxarcifhrawai6hsawcefhwasmbxdkkcuhmaqhrakhwcuhxinawcufamaoavcjPfarcefRbbfRbb9RcFeGci6aoavcjPfarRbbfRbb9RcFeGci6faoavcjPfarcdfRbbfRbb9RcFeGci6fgPax9kgsEhmaPce0meaPaxasEhxarcifhrawai6hPawcefhwaPmbkkadamci2fgrcdfRbbhwarcefRbbhxarRbbhPadaDci2fgrcifaramaD9Rci2zNjjjb8AaPavcjPffaocefgo86bbaPavcjxffgmamRbbcuf86bbaxavcjPffao86bbaxavcjxffgmamRbbcuf86bbarcdfaw86bbarcefax86bbaraP86bbawavcjPffao86bbawavcjxffgrarRbbcuf86bbaqcifhqakcefhkaDcefgDai9hmbkcbhzdnalcb9mmbcbhsavcjPfcbaez:rjjjb8Aadcvfhlinadasci2fgxcefgDRbbhoaxcdfgqRbbhrdndnavcjPfaxRbbgmfRbbmbavcjPfarfRbbhwdndndnavcjPfaofRbbTmbawcFeGTmexikawcFeGmdascefgAai9pmdasc980mdascifhQcbhLarcFeGhCamcFeGhXalhwcbhKcbhYinawcufRbbhPawRbbhOcehkdndnawc9:fRbbgHao9hmbaPcFeGamSmekdnaPcFeGao9hmbaOcFeGamSmekaHamSaOcFeGaoSGhkkceh8AaYceGhYdndnaHar9hmbaPcFeGaoSmekdnaPcFeGar9hmbaOcFeGaoSmekaHaoSaOcFeGarSGh8AkakaYVhYaLaHcFeGgHaXSaPcFeGgPaCSGaPaXSaOcFeGgPaCSGVaHaCSaPaXSGVVhLa8AaKceGVhKdnaAcefgPai9pmbawcifhwaAaQ6hHaPhAaHmekkaYTmeaKmekarhwaohPaohHarhOamhrxdkdnaYTaLVceGTmbaYaKTVaLVceGmekamhwarhParhHamhOaohrxekaohwamhPamhHaohOkavcjPfarfce86bbavcjPfawfce86bbaxaH86bbaqar86bbaDaO86bbavcjPfaPfce86bbalcifhlascefgsai9hmbkkavcFeaecetz:rjjjbhwaici2hrindnawadRbbgmcetfgx8Uebgocu9kmbaxaz87ebawcjlfazcdtfabamcdtfydbBdbazhoazcefhzkadao86bbadcefhdarcufgrmbkazcdthokabavcjlfaoz:qjjjb8Aavcjzf8KjjjjbkObabaiaeadcbz:njjjbk9teiucbcbyd;8:G:cjbgeabcifc98GfgbBd;8:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabk9teiucbcbyd;8:G:cjbgeabcrfc94GfgbBd;8:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikTeeucbabcbyd;8:G:cjbge9Rcifc98GaefgbBd;8:G:cjbdnabZbcztge9nmbabae9RcFFifcz4nb8Akk:3qeludndnadch6mbadTmeabaead;8qbbabskabaeSmbdnaeadabfgi9Rcbadcet9R0mbadTmeabaead;8qbbabskaeab7ciGhldndndnabae9pmbdnalTmbadhvabhixikdnabciGmbadhvabhixdkadTmiabaeRbb86bbadcufhvdnabcefgiciGmbaecefhexdkavTmiabaeRbe86beadc9:fhvdnabcdfgiciGmbaecdfhexdkavTmiabaeRbd86bdadc99fhvdnabcifgiciGmbaecifhexdkavTmiabaeRbi86biabclfhiaeclfheadc98fhvxekdnalmbdnaiciGTmbadTmlabadcufgifglaeaifRbb86bbdnalciGmbaihdxekaiTmlabadc9:fgifglaeaifRbb86bbdnalciGmbaihdxekaiTmlabadc99fgifglaeaifRbb86bbdnalciGmbaihdxekaiTmlabadc98fgdfaeadfRbb86bbkadcl6mbdnadc98fgocxGcxSmbaocd4cefciGhiaec98fhlabc98fhvinavadfaladfydbBdbadc98fhdaicufgimbkkaocx6mbaec9Wfhvabc9WfhoinaoadfgicxfavadfglcxfydbBdbaicwfalcwfydbBdbaiclfalclfydbBdbaialydbBdbadc9Wfgdci0mbkkadTmdadhidnadciGglTmbaecufhvabcufhoadhiinaoaifavaifRbb86bbaicufhialcufglmbkkadcl6mdaec98fhlabc98fhvinavaifgecifalaifgdcifRbb86bbaecdfadcdfRbb86bbaecefadcefRbb86bbaeadRbb86bbaic98fgimbxikkavcl6mbdnavc98fglc3Gc3Smbavalcd4cefcrGgdcdt9RhvinaiaeydbBdbaeclfheaiclfhiadcufgdmbkkalc36mbinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaiczfaeczfydbBdbaicCfaecCfydbBdbaicKfaecKfydbBdbaic3faec3fydbBdbaecafheaicafhiavc9Gfgvci0mbkkavTmbdndnavcrGgdmbavhlxekavc94GhlinaiaeRbb86bbaicefhiaecefheadcufgdmbkkavcw6mbinaiaeRbb86bbaicefaecefRbb86bbaicdfaecdfRbb86bbaicifaecifRbb86bbaiclfaeclfRbb86bbaicvfaecvfRbb86bbaicofaecofRbb86bbaicrfaecrfRbb86bbaicwfhiaecwfhealc94fglmbkkabkk:pedbcj:GdktFFuuFFuuFFuubbbbFFuFFFuFFFuFbbbbbbjZbbbbbbbbbbbbbbjZbbbbbbbbbbbbbbjZ86;nAZ86;nAZ86;nAZ86;nA:;86;nAZ86;nAZ86;nAZ86;nA:;86;nAZ86;nAZ86;nAZ86;nA:;bc;0:Gdkxebbbdbbbj:qbb",t=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!=="object")return{supported:!1};var n,i=WebAssembly.instantiate(r(e),{}).then(function(m){n=m.instance,n.exports.__wasm_call_ctors()});function r(m){var g=new Uint8Array(m.length);for(var p=0;p<m.length;++p){var x=m.charCodeAt(p);g[p]=x>96?x-97:x>64?x-39:x+4}var _=0;for(var p=0;p<m.length;++p)g[_++]=g[p]<60?t[g[p]]:(g[p]-60)*64+g[++p];return g.buffer.slice(0,_)}function s(m){if(!m)throw Error("Assertion failed")}function a(m){return new Uint8Array(m.buffer,m.byteOffset,m.byteLength)}var o=48,c=16;function l(m,g){var p=m.meshlets[g*4+0],x=m.meshlets[g*4+1],_=m.meshlets[g*4+2],y=m.meshlets[g*4+3];return{vertices:m.vertices.subarray(p,p+_),triangles:m.triangles.subarray(x,x+y*3)}}function u(m,g,p,x,_,y,v,T,A,E){var w=n.exports.sbrk,P=n.exports.meshopt_buildMeshletsBound(g.length,y,v),S=w(P*c),I=w(g.length*4),U=w(g.length),N=w(g.byteLength),F=w(p.byteLength),D=new Uint8Array(n.exports.memory.buffer);D.set(a(g),N),D.set(a(p),F);var O=m(S,I,U,N,g.length,F,x,_,y,v,T,A,E);D=new Uint8Array(n.exports.memory.buffer);var K=D.subarray(S,S+O*c),B=new Uint32Array(K.buffer,K.byteOffset,K.byteLength/4).slice();for(var X=0;X<O;++X){var q=B[X*4+0],le=B[X*4+1],x=B[X*4+2],de=B[X*4+3];n.exports.meshopt_optimizeMeshlet(I+q*4,U+le,de,x)}var Me=O?B[(O-1)*4+0]+B[(O-1)*4+2]:0,pe=O?B[(O-1)*4+1]+B[(O-1)*4+3]*3:0,J={meshlets:B,vertices:new Uint32Array(D.buffer,I,Me).slice(),triangles:new Uint8Array(D.buffer,U,pe).slice(),meshletCount:O};return w(S-w(0)),J}function d(m){var g=new Float32Array(n.exports.memory.buffer,m,o/4);return{centerX:g[0],centerY:g[1],centerZ:g[2],radius:g[3],coneApexX:g[4],coneApexY:g[5],coneApexZ:g[6],coneAxisX:g[7],coneAxisY:g[8],coneAxisZ:g[9],coneCutoff:g[10]}}function f(m,g,p,x){var _=n.exports.sbrk,y=[],v=_(g.byteLength),T=_(m.vertices.byteLength),A=_(m.triangles.byteLength),E=_(o),w=new Uint8Array(n.exports.memory.buffer);w.set(a(g),v),w.set(a(m.vertices),T),w.set(a(m.triangles),A);for(var P=0;P<m.meshletCount;++P){var S=m.meshlets[P*4+0],I=m.meshlets[P*4+1],U=m.meshlets[P*4+3];n.exports.meshopt_computeMeshletBounds(E,T+S*4,A+I,U,v,p,x),y.push(d(E))}return _(v-_(0)),y}function h(m,g,p,x){var _=n.exports.sbrk,y=_(o),v=_(m.byteLength),T=_(g.byteLength),A=new Uint8Array(n.exports.memory.buffer);A.set(a(m),v),A.set(a(g),T),n.exports.meshopt_computeClusterBounds(y,v,m.length,T,p,x);var E=d(y);return _(y-_(0)),E}function b(m,g,p,x,_){var y=n.exports.sbrk,v=y(o),T=y(m.byteLength),A=x?y(x.byteLength):0,E=new Uint8Array(n.exports.memory.buffer);if(E.set(a(m),T),x)E.set(a(x),A);n.exports.meshopt_computeSphereBounds(v,T,g,p,A,x?_:0);var w=d(v);return y(v-y(0)),w}return{ready:i,supported:!0,buildMeshlets:function(m,g,p,x,_,y){s(m.length%3==0),s(g instanceof Float32Array),s(g.length%p==0),s(p>=3),s(x>=3&&x<=256),s(_>=1&&_<=512),y=y||0;var v=m.BYTES_PER_ELEMENT==4?m:new Uint32Array(m);return u(n.exports.meshopt_buildMeshletsFlex,v,g,g.length/p,p*4,x,_,_,y,0)},buildMeshletsFlex:function(m,g,p,x,_,y,v,T){s(m.length%3==0),s(g instanceof Float32Array),s(g.length%p==0),s(p>=3),s(x>=3&&x<=256),s(_>=1&&y<=512),s(_<=y),v=v||0,T=T||0;var A=m.BYTES_PER_ELEMENT==4?m:new Uint32Array(m);return u(n.exports.meshopt_buildMeshletsFlex,A,g,g.length/p,p*4,x,_,y,v,T)},buildMeshletsSpatial:function(m,g,p,x,_,y,v){s(m.length%3==0),s(g instanceof Float32Array),s(g.length%p==0),s(p>=3),s(x>=3&&x<=256),s(_>=1&&y<=512),s(_<=y),v=v||0;var T=m.BYTES_PER_ELEMENT==4?m:new Uint32Array(m);return u(n.exports.meshopt_buildMeshletsSpatial,T,g,g.length/p,p*4,x,_,y,v)},extractMeshlet:function(m,g){return s(g>=0&&g<m.meshletCount),l(m,g)},computeClusterBounds:function(m,g,p){s(m.length%3==0),s(m.length/3<=512),s(g instanceof Float32Array),s(g.length%p==0),s(p>=3);var x=m.BYTES_PER_ELEMENT==4?m:new Uint32Array(m);return h(x,g,g.length/p,p*4)},computeMeshletBounds:function(m,g,p){return s(g instanceof Float32Array),s(g.length%p==0),s(p>=3),f(m,g,g.length/p,p*4)},computeSphereBounds:function(m,g,p,x){return s(m instanceof Float32Array),s(m.length%g==0),s(g>=3),s(!p||p instanceof Float32Array),s(!p||p.length%x==0),s(!p||x>=1),s(!p||m.length/g==p.length/x),x=x||0,b(m,m.length/g,g*4,p,x*4)}}}()});var bR={};Pb(bR,{MeshoptEncoder:()=>lB});var xR=mt(()=>{hR();pR();mR();gR()});function ic(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 Lf(e,t="|"){return e.map((n)=>Bf(n)).join(t)}function rc(e,t){if(typeof t==="bigint")return t.toString();return t}class Ob{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function sc(e){return new Ob(e)}function kb(e){return e===null||e===void 0}function Yr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Db(e,t){let n=e/t,i=Math.round(n),r=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-i)<r)return 0;return n-i}function mi(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ac(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Sr(e){return ac(e._zod.def)??e._zod.def.shape}function Lb(e,t,n){Object.defineProperty(e,t,{get(){let i=n();return mi(this,t,i),i},enumerable:!0,configurable:!0})}function Fb(e,t,n){if(t in e)mi(e,t,n);else e[t]=n}function ia(e,t,n,i){let r=Sr(t);for(let s of n){let a=Object.getOwnPropertyDescriptor(r,s);if(!a.enumerable)continue;if(a.get)Lb(e,s,()=>{let o=t._zod.def.shape[s];return i?i(o,s):o});else Fb(e,s,i?i(a.value,s):a.value)}}function oI(e,t){for(let n of Reflect.ownKeys(t)){let i=Object.getOwnPropertyDescriptor(t,n);if(!i.enumerable)continue;if(i.get)Lb(e,n,()=>t[n]);else Fb(e,n,i.value)}}function Qn(...e){let t={};for(let n of e){let i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function Ub(e){return JSON.stringify(e)}function Bb(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Ff="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ja(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var zb=sc(()=>{if(Un.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function ra(e){if(ja(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(ja(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Uf(e){if(ra(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 Vb=new Set(["string","number","symbol"]),jb=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Rr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ji(e,t,n){let i=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)i._zod.parent=e;return i}function Fe(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 Bf(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Hb(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var jl=(()=>({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]}))(),zf={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function cI(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={};return ia(s,e,Hl(e,t)),Ji(e,Qn(n,{shape:s,checks:[]}))}function Hl(e,t){let n=Sr(e),i=[];for(let r of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,r)?.enumerable)throw Error(`Unrecognized key: "${String(r)}"`);if(t[r])i.push(r)}return i}function lI(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=new Set(Hl(e,t)),a={};return ia(a,e,Reflect.ownKeys(Sr(e)).filter((o)=>!s.has(o))),Ji(e,Qn(n,{shape:a,checks:[]}))}function uI(e,t){if(!ra(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let r=Sr(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(r,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ji(e,Qn(e._zod.def,{shape:Gb(e,t)}))}function Gb(e,t){let n={};return ia(n,e,Reflect.ownKeys(Sr(e))),oI(n,t),n}function dI(e,t){if(!ra(t))throw Error("Invalid input to safeExtend: expected a plain object");return Ji(e,Qn(e._zod.def,{shape:Gb(e,t)}))}function fI(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};ia(n,e,Reflect.ownKeys(Sr(e))),ia(n,t,Reflect.ownKeys(Sr(t)));let i=Qn(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ji(e,i)}function $b(e,t,n,i="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw Error(`.${i}() cannot be used on object schemas containing refinements`);let o=n?new Set(Hl(t,n)):void 0,c={};return ia(c,t,Reflect.ownKeys(Sr(t)),e&&((l,u)=>o&&!o.has(u)?l:new e({type:"optional",innerType:l}))),Ji(t,Qn(t._zod.def,{shape:c,checks:[]}))}function hI(e,t,n){let i=n?new Set(Hl(t,n)):void 0,r={};return ia(r,t,Reflect.ownKeys(Sr(t)),(s,a)=>i&&!i.has(a)?s:new e({type:"nonoptional",innerType:s})),Ji(t,Qn(t._zod.def,{shape:r}))}function gi(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 Kb(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 Zi(e,t){return t.map((n)=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function nc(e){return typeof e==="string"?e:e?.message}function Vf(e,t,n){var i;for(let r=t;r<e.length;r++)(i=e[r]).schema??(i.schema=n)}function Yi(e,t,n){var i;let r=e.inst?._zod?.traits;if(r?.has("$ZodType"))if(r.has("$ZodCheck"))(i=e).schema??(i.schema=e.inst);else e.schema=e.inst;let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:nc(e.inst?._zod.def?.error?.(e))??nc(s?.(e))??nc(t?.error?.(e))??nc(n.customError?.(e))??nc(n.localeError?.(e))??"Invalid input",o={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;o[c]=e[c]}if(o.path??(o.path=[]),o.message=a,t?.reportInput)o.input=e.input;return o}var pI=/[\uD800-\uDBFF]/;function Gl(e){let t=e.length;if(!pI.test(e))return t;let n=t;for(let i=0;i<t-1;i++)if((e.charCodeAt(i)&64512)===55296&&(e.charCodeAt(i+1)&64512)===56320)n--,i++;return n}function $l(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Wb(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function sa(...e){let[t,n,i]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:i};return{...t}}function Xb(e,t){for(let n in t){let i=Object.getOwnPropertyDescriptor(t,n);if(i.get)Object.defineProperty(e,n,{...i,enumerable:!1});else mI(e,n,i.value)}}function Mr(e,t,n,i=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:i,value:n}),n}function Kl(e,t,n){return Mr(e,t,n,!1)}function qb(e,t){for(let n in e){let i=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Mr(this,n,i(this))},set(r){Mr(this,n,r)}})}return t}function mI(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Mr(this,t,n.bind(this))},set(i){Mr(this,t,i)}})}function gI(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var Df,Zr=!1,bI={configurable:!0,get(){Zr=!0;return}};function Et(e,t,n){let i=Object.getPrototypeOf(e._zod);if(t in i&&Df!==e._zod){Df=void 0;return}Df=e._zod,Object.defineProperty(i,t,{configurable:!0,get(){Object.defineProperty(this,t,bI);let r=Zr;Zr=!1;try{let s=n(this);if(Zr)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s});return Zr=Zr||r,s}catch(s){throw delete this[t],Zr=Zr||r,s}},set(r){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r})}})}function xI(e,t,n,i){let r=gI(e,t);if(!r)return;Object.defineProperty(r,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:i,value:void 0};return Object.defineProperty(this,t,s),s.value=n(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:i,value:s})}})}var yI="~constantCatch";function Jb(e){let t=()=>e;return t[yI]=!0,t}var Zb;var jf={value:void 0,enumerable:!1},Yb="captureStackTrace"in Error?Error:null;function _I(e){let t=Yb;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return Yb=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function se(e,t,n,i){let r={};function s(f){this.def=f,this.constr=d,this.traits=new Set}s.prototype=r;let a=n,o=a&&new WeakSet;function c(f,h){if(!f._zod){jf.value=new s(h);try{Object.defineProperty(f,"_zod",jf)}finally{jf.value=void 0}}else if(f._zod.traits.has(e))return;if(f._zod.traits.add(e),t(f,h),o){let m=Object.getPrototypeOf(f),g=f._zod.constr.prototype,p=m;while(p&&p!==g)p=Object.getPrototypeOf(p);let x=p??m;if(!o.has(x))o.add(x),Xb(x,a)}let b=d.prototype;for(let m in b){if(!Object.prototype.hasOwnProperty.call(b,m))continue;if(!(m in f))f[m]=b[m].bind(f)}}let l=i?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(f){let h=i?.Parent?_I(u):this;c(h,f);let b=h._zod.deferred;if(b){for(let g of b)g();h._zod.deferred=void 0}let m=globalThis.__zod_globalConfig?.postProcessor;if(m)m(h);return h}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:(f)=>{if(i?.Parent&&f instanceof i.Parent)return!0;return f?._zod?.traits?.has(e)}}),Object.defineProperty(d,"name",{value:e}),d}class Qi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class oc extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Zb=globalThis).__zod_globalConfig??(Zb.__zod_globalConfig={});var Un=globalThis.__zod_globalConfig;function ei(e){if(e)Object.assign(Un,e);return Un}function vI(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,rc,2)),e.message}function EI(e){this._zod.message=e}var TI={get:vI,set:EI,enumerable:!0,configurable:!0},Gf={value:void 0,enumerable:!1},Qb=new WeakSet([Object.prototype,Error.prototype]),ex=(e,t)=>{e.name="$ZodError",Gf.value=t,Object.defineProperty(e,"issues",Gf),Gf.value=void 0,Object.defineProperty(e,"message",TI);let n=Object.getPrototypeOf(e);if(!Qb.has(n))Qb.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let i=()=>this.message;return Object.defineProperty(this,"toString",{value:i,configurable:!0,writable:!0}),i},set(i){Object.defineProperty(this,"toString",{value:i,configurable:!0,writable:!0})}})},tx=se("$ZodError",ex),IB=se("$ZodError",ex,void 0,{Parent:Error});function AI(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function nx(e,t=(n)=>n.message){let n={},i=[];for(let r of e.issues)if(r.path.length>0)AI(n,r.path[0],()=>[]).push(t(r));else i.push(t(r));return{formErrors:i,fieldErrors:n}}function ix(e,t=(n)=>n.message){let n={_errors:[]},i=(r,s=[])=>{for(let a of r.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map((o)=>i({issues:o},[...s,...a.path]));else if(a.code==="invalid_key")i({issues:a.issues},[...s,...a.path]);else if(a.code==="invalid_element")i({issues:a.issues},[...s,...a.path]);else{let o=[...s,...a.path];if(o.length===0)n._errors.push(t(a));else{let c=n,l=0;while(l<o.length){let u=o[l],d=l===o.length-1;if(u==="_errors"){if(d)c._errors.push(t(a));l++;continue}if(!Object.prototype.hasOwnProperty.call(c,u))Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let f=c[u];if(d)f._errors.push(t(a));c=f,l++}}}};return i(e),n}function Wl(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Xl=(e)=>{let t=(n,i,r,s)=>{let a=r?{...r,async:!1}:{async:!1},o=n._zod.run({value:i,issues:[]},a);if(o instanceof Promise)throw new Qi;if(o.issues.length){let c=new(s?.Err??e)(o.issues.map((l)=>Yi(l,a,ei())));throw Ff(c,s?.callee??t),c}return o.value};return t};var ql=(e)=>{let t=async(n,i,r,s)=>{let a=r?{...r,async:!0}:{async:!0},o=n._zod.run({value:i,issues:[]},a);if(o instanceof Promise)o=await o;if(o.issues.length){let c=new(s?.Err??e)(o.issues.map((l)=>Yi(l,a,ei())));throw Ff(c,s?.callee??t),c}return o.value};return t};var Jl=(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 Qi;return s.issues.length?rx(e,s.issues,r):{success:!0,data:s.value}};function rx(e,t,n){let i;return{success:!1,get error(){if(!i)i=new e(t.map((r)=>Yi(r,n,ei()))),t=void 0,n=void 0;return i},set error(r){i=r,t=void 0,n=void 0}}}var Zl=(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?rx(e,s.issues,r):{success:!0,data:s.value}};var wI=Symbol.for("zod.compile.invalid"),SI=Symbol.for("zod.compile.fallback"),$f=(e,t,n)=>{let i=e._zod.bag.validator;if(i!==void 0){if(i(t)!==wI)return!0;if(i.definite===!0&&n===void 0)return!1}return MI(e,t,n)};function MI(e,t,n){let i=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},r=e._zod.bag.fallbackRun,s;if(r)i[SI]=!0,s=r({value:t,issues:[]},i);else s=e._zod.run({value:t,issues:[]},i);if(s instanceof Promise)throw new Qi;return s.issues.length===0}var Kf=async(e,t,n)=>{let i=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},r=e._zod.run({value:t,issues:[]},i);if(r instanceof Promise)r=await r;return r.issues.length===0},sx=(e)=>{let t=Xl(e),n=(i,r,s,a)=>{let o=s?{...s,direction:"backward"}:{direction:"backward"};return t(i,r,o,Wl(n,a))};return n};var ax=(e)=>{let t=Xl(e),n=(i,r,s,a)=>t(i,r,s,Wl(n,a));return n};var ox=(e)=>{let t=ql(e),n=async(i,r,s,a)=>{let o=s?{...s,direction:"backward"}:{direction:"backward"};return await t(i,r,o,Wl(n,a))};return n};var cx=(e)=>{let t=ql(e),n=async(i,r,s,a)=>await t(i,r,s,Wl(n,a));return n};var lx=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return Jl(e)(t,n,r)};var ux=(e)=>(t,n,i)=>Jl(e)(t,n,i);var dx=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return Zl(e)(t,n,r)};var fx=(e)=>async(t,n,i)=>Zl(e)(t,n,i);var hx=/^[cC][0-9a-z]{6,}$/,px=/^[0-9a-z]+$/,mx=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,gx=/^[0-9a-vA-V]{20}$/,bx=/^[A-Za-z0-9]{27}$/,xx=/^[a-zA-Z0-9_-]{21}$/;function yx(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var _x=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var vx=/^([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})$/,Xf=(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 Ex=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var RI="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Tx(){return new RegExp(RI,"u")}var Ax=/^(?:(?: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])$/,wx=/^(([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 Sx=/^((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])$/,Mx=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Rx=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ix=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var Cx=/^https?$/,Nx=/^\+[1-9]\d{6,14}$/;var Px="(?:(?:\\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])))";function II(e){return new RegExp(`^${e}$`)}var Ox=II(Px);function Wf(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}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function kx(e){return new RegExp(`^${Wf(e)}$`)}function Dx(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${Wf({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,i=e.local?`${n}|${Wf({precision:e.precision})}`:n;return new RegExp(`^${Px}T(?:${i})$`)}var Lx=/^[\s\S]{0,}$/,Fx=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Yl=/^-?\d+$/,Ha=/^-?\d+(?:\.\d+)?$/,Ux=/^(?:true|false)$/i;var Bx=/^[^A-Z]*$/,zx=/^[^a-z]*$/;var wn=se("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var qf=(e)=>{let t=e.value;return!kb(t)&&t.length!==void 0},Ql={number:"number",bigint:"bigint",object:"date"},Jf=se("$ZodCheckLessThan",(e,t)=>{wn.init(e,t);let n=Ql[typeof t.value];e._zod.check=(i)=>{if(t.inclusive?i.value<=t.value:i.value<t.value)return;i.issues.push({origin:Ql[typeof i.value]??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})}}),Zf=se("$ZodCheckGreaterThan",(e,t)=>{wn.init(e,t);let n=Ql[typeof t.value];e._zod.check=(i)=>{if(t.inclusive?i.value>=t.value:i.value>t.value)return;i.issues.push({origin:Ql[typeof i.value]??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})}}),Vx=se("$ZodCheckMultipleOf",(e,t)=>{wn.init(e,t),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"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Db(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})}}),jx=se("$ZodCheckNumberFormat",(e,t)=>{wn.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),i=n?"int":"number",[r,s]=jl[t.format];e._zod.check=(a)=>{let o=a.value;if(n){if(!Number.isInteger(o)){a.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});return}if(!Number.isSafeInteger(o)){if(o>0)a.issues.push({input:o,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 a.issues.push({input:o,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(o<r)a.issues.push({origin:"number",input:o,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(o>s)a.issues.push({origin:"number",input:o,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Hx=se("$ZodCheckMaxLength",(e,t)=>{var n;wn.init(e,t),(n=e._zod.def).when??(n.when=qf),e._zod.check=(i)=>{let r=i.value,s=r.length;if((typeof r==="string"&&s>t.maximum?Gl(r):s)<=t.maximum)return;let o=$l(r);i.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Gx=se("$ZodCheckMinLength",(e,t)=>{var n;wn.init(e,t),(n=e._zod.def).when??(n.when=qf),e._zod.check=(i)=>{let r=i.value,s=r.length;if((typeof r==="string"&&s>=t.minimum&&s<t.minimum*2?Gl(r):s)>=t.minimum)return;let o=$l(r);i.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$x=se("$ZodCheckLengthEquals",(e,t)=>{var n;wn.init(e,t),(n=e._zod.def).when??(n.when=qf),e._zod.check=(i)=>{let r=i.value,s=r.length,a=typeof r==="string"&&s>=t.length&&s<=t.length*2?Gl(r):s;if(a===t.length)return;let o=$l(r),c=a>t.length;i.issues.push({origin:o,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),lc=se("$ZodCheckStringFormat",(e,t)=>{var n,i;if(wn.init(e,t),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=()=>{})}),Kx=se("$ZodCheckRegex",(e,t)=>{lc.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})}}),Wx=se("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Bx),lc.init(e,t)}),Xx=se("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=zx),lc.init(e,t)}),qx=se("$ZodCheckIncludes",(e,t)=>{wn.init(e,t);let n=Rr(t.includes),i=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=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})}}),Jx=se("$ZodCheckStartsWith",(e,t)=>{wn.init(e,t);let n=new RegExp(`^${Rr(t.prefix)}.*`);t.pattern??(t.pattern=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})}}),Zx=se("$ZodCheckEndsWith",(e,t)=>{wn.init(e,t);let n=new RegExp(`.*${Rr(t.suffix)}$`);t.pattern??(t.pattern=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 Yx=se("$ZodCheckOverwrite",(e,t)=>{wn.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Yf{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`+`));return d(h3.bind(void 0,e))}ZS.exports=p3});var eM=Jr(function(aK,QS){var m3=YS();function g3(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function b3(e){var t=new g3;t.pre=e.pre,t.body=e.body,t.post=e.post;var n=e.args.slice(0);t.argTypes=n;for(var i=0;i<n.length;++i){var r=n[i];if(r==="array"||typeof r==="object"&&r.blockIndices){if(t.argTypes[i]="array",t.arrayArgs.push(i),t.arrayBlockIndices.push(r.blockIndices?r.blockIndices:0),t.shimArgs.push("array"+i),i<t.pre.args.length&&t.pre.args[i].count>0)throw Error("cwise: pre() block may not reference array args");if(i<t.post.args.length&&t.post.args[i].count>0)throw Error("cwise: post() block may not reference array args")}else if(r==="scalar")t.scalarArgs.push(i),t.shimArgs.push("scalar"+i);else if(r==="index"){if(t.indexArgs.push(i),i<t.pre.args.length&&t.pre.args[i].count>0)throw Error("cwise: pre() block may not reference array index");if(i<t.body.args.length&&t.body.args[i].lvalue)throw Error("cwise: body() block may not write to array index");if(i<t.post.args.length&&t.post.args[i].count>0)throw Error("cwise: post() block may not reference array index")}else if(r==="shape"){if(t.shapeArgs.push(i),i<t.pre.args.length&&t.pre.args[i].lvalue)throw Error("cwise: pre() block may not write to array shape");if(i<t.body.args.length&&t.body.args[i].lvalue)throw Error("cwise: body() block may not write to array shape");if(i<t.post.args.length&&t.post.args[i].lvalue)throw Error("cwise: post() block may not write to array shape")}else if(typeof r==="object"&&r.offset)t.argTypes[i]="offset",t.offsetArgs.push({array:r.array,offset:r.offset}),t.offsetArgIndex.push(i);else throw Error("cwise: Unknown argument type "+n[i])}if(t.arrayArgs.length<=0)throw Error("cwise: No array arguments specified");if(t.pre.args.length>n.length)throw Error("cwise: Too many arguments in pre() block");if(t.body.args.length>n.length)throw Error("cwise: Too many arguments in body() block");if(t.post.args.length>n.length)throw Error("cwise: Too many arguments in post() block");return t.debug=!!e.printCode||!!e.debug,t.funcName=e.funcName||"cwise",t.blockSize=e.blockSize||64,m3(t)}QS.exports=b3});var oM=Jr(function(an){var Qn=eM(),mf={body:"",args:[],thisVars:[],localVars:[]};function Zg(e){if(!e)return mf;for(var t=0;t<e.args.length;++t){var n=e.args[t];if(t===0)e.args[t]={name:n,lvalue:!0,rvalue:!!e.rvalue,count:e.count||1};else e.args[t]={name:n,lvalue:!1,rvalue:!0,count:1}}if(!e.thisVars)e.thisVars=[];if(!e.localVars)e.localVars=[];return e}function x3(e){return Qn({args:e.args,pre:Zg(e.pre),body:Zg(e.body),post:Zg(e.proc),funcName:e.funcName})}function Yt(e){var t=[];for(var n=0;n<e.args.length;++n)t.push("a"+n);var i=Function("P",["return function ",e.funcName,"_ndarrayops(",t.join(","),") {P(",t.join(","),");return a0}"].join(""));return i(x3(e))}var tM={add:"+",sub:"-",mul:"*",div:"/",mod:"%",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"};(function(){for(var e in tM){var t=tM[e];an[e]=Yt({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+t+"c"},funcName:e}),an[e+"eq"]=Yt({args:["array","array"],body:{args:["a","b"],body:"a"+t+"=b"},rvalue:!0,funcName:e+"eq"}),an[e+"s"]=Yt({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+t+"s"},funcName:e+"s"}),an[e+"seq"]=Yt({args:["array","scalar"],body:{args:["a","s"],body:"a"+t+"=s"},rvalue:!0,funcName:e+"seq"})}})();var nM={not:"!",bnot:"~",neg:"-",recip:"1.0/"};(function(){for(var e in nM){var t=nM[e];an[e]=Yt({args:["array","array"],body:{args:["a","b"],body:"a="+t+"b"},funcName:e}),an[e+"eq"]=Yt({args:["array"],body:{args:["a"],body:"a="+t+"a"},rvalue:!0,count:2,funcName:e+"eq"})}})();var iM={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};(function(){for(var e in iM){var t=iM[e];an[e]=Yt({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+t+"c"},funcName:e}),an[e+"s"]=Yt({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+t+"s"},funcName:e+"s"}),an[e+"eq"]=Yt({args:["array","array"],body:{args:["a","b"],body:"a=a"+t+"b"},rvalue:!0,count:2,funcName:e+"eq"}),an[e+"seq"]=Yt({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+t+"s"},rvalue:!0,count:2,funcName:e+"seq"})}})();var rM=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];(function(){for(var e=0;e<rM.length;++e){var t=rM[e];an[t]=Yt({args:["array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b)",thisVars:["this_f"]},funcName:t}),an[t+"eq"]=Yt({args:["array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a"],body:"a=this_f(a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"eq"})}})();var sM=["max","min","atan2","pow"];(function(){for(var e=0;e<sM.length;++e){var t=sM[e];an[t]=Yt({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:t}),an[t+"s"]=Yt({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:t+"s"}),an[t+"eq"]=Yt({args:["array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"eq"}),an[t+"seq"]=Yt({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"seq"})}})();var aM=["atan2","pow"];(function(){for(var e=0;e<aM.length;++e){var t=aM[e];an[t+"op"]=Yt({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:t+"op"}),an[t+"ops"]=Yt({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:t+"ops"}),an[t+"opeq"]=Yt({args:["array","array"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"opeq"}),an[t+"opseq"]=Yt({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+t,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:t+"opseq"})}})();an.any=Qn({args:["array"],pre:mf,body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"if(a){return true}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return false"},funcName:"any"});an.all=Qn({args:["array"],pre:mf,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1}],body:"if(!x){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"all"});an.sum=Qn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s+=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"sum"});an.prod=Qn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=1"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s*=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"prod"});an.norm2squared=Qn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm2squared"});an.norm2=Qn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return Math.sqrt(this_s)"},funcName:"norm2"});an.norminf=Qn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:4}],body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"});an.norm1=Qn({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"});an.sup=Qn({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}});an.inf=Qn({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}});an.argmin=Qn({args:["index","array","shape"],pre:{body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}});an.argmax=Qn({args:["index","array","shape"],pre:{body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}});an.random=Yt({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"});an.assign=Yt({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"});an.assigns=Yt({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"});an.equals=Qn({args:["array","array"],pre:mf,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})});function L3(e,t){if(!(e instanceof Uint8Array))throw Error("[ndarray-pixels] Input must be Uint8Array or Buffer.");let n=new Blob([e],{type:t});return createImageBitmap(n,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then((i)=>{let r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);let s=r.getImageData(0,0,i.width,i.height);return cM.default(new Uint8Array(s.data),[i.width,i.height,4],[4,4*i.width,1],0)})}async function lM(e,t){return L3(e,t)}var cM,D3;var uM=ht(()=>{cM=Bf(qg(),1),D3=Bf(oM(),1)});function Af(e,t){return Object.defineProperty(t,"name",{value:e}),t}function wf(e,t){let n={...e};for(let i in t)if(t[i]!==void 0)n[i]=t[i];return n}function SM(e){let t=[];for(let n of e.listAttributes())t.push(n);for(let n of e.listTargets())for(let i of n.listAttributes())t.push(i);return Array.from(new Set(t))}function U3(e,t){if(e==null&&t==null)return!0;if(e==null||t==null)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function yf(e,t){return e.createAccessor(t.getName()).setArray(t.getArray()).setType(t.getType()).setBuffer(t.getBuffer()).setNormalized(t.getNormalized()).setSparse(t.getSparse())}function B3(e,t=e){let n=MM(e,t);for(let i=0;i<n.length;i++)n[i]=i;return n}function MM(e,t=e){return t<=65534?new Uint16Array(e):new Uint32Array(e)}function RM(e){for(let t in e)return!1;return!0}function z3(e,t){var n=t[0],i=t[1],r=t[2],s=t[3],a=t[4],o=t[5],c=t[6],l=t[7],u=t[8],d=t[9],f=t[10],h=t[11],b=t[12],m=t[13],g=t[14],p=t[15],x=n*o-i*a,_=n*c-r*a,y=n*l-s*a,v=i*c-r*o,E=i*l-s*o,w=r*l-s*c,T=u*m-d*b,A=u*g-f*b,P=u*p-h*b,S=d*g-f*m,R=d*p-h*m,k=f*p-h*g,C=x*k-_*R+y*S+v*P-E*A+w*T;if(!C)return null;return C=1/C,e[0]=(o*k-c*R+l*S)*C,e[1]=(r*R-i*k-s*S)*C,e[2]=(m*w-g*E+p*v)*C,e[3]=(f*E-d*w-h*v)*C,e[4]=(c*P-a*k-l*A)*C,e[5]=(n*k-r*P+s*A)*C,e[6]=(g*y-b*w-p*_)*C,e[7]=(u*w-f*y+h*_)*C,e[8]=(a*R-o*P+l*T)*C,e[9]=(i*P-n*R-s*T)*C,e[10]=(b*E-m*y+p*x)*C,e[11]=(d*y-u*E-h*x)*C,e[12]=(o*A-a*S-c*T)*C,e[13]=(n*S-i*A+r*T)*C,e[14]=(m*_-b*v-g*x)*C,e[15]=(u*v-d*_+f*x)*C,e}function rb(e,t,n){var i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],c=t[5],l=t[6],u=t[7],d=t[8],f=t[9],h=t[10],b=t[11],m=t[12],g=t[13],p=t[14],x=t[15],_=n[0],y=n[1],v=n[2],E=n[3];return e[0]=_*i+y*o+v*d+E*m,e[1]=_*r+y*c+v*f+E*g,e[2]=_*s+y*l+v*h+E*p,e[3]=_*a+y*u+v*b+E*x,_=n[4],y=n[5],v=n[6],E=n[7],e[4]=_*i+y*o+v*d+E*m,e[5]=_*r+y*c+v*f+E*g,e[6]=_*s+y*l+v*h+E*p,e[7]=_*a+y*u+v*b+E*x,_=n[8],y=n[9],v=n[10],E=n[11],e[8]=_*i+y*o+v*d+E*m,e[9]=_*r+y*c+v*f+E*g,e[10]=_*s+y*l+v*h+E*p,e[11]=_*a+y*u+v*b+E*x,_=n[12],y=n[13],v=n[14],E=n[15],e[12]=_*i+y*o+v*d+E*m,e[13]=_*r+y*c+v*f+E*g,e[14]=_*s+y*l+v*h+E*p,e[15]=_*a+y*u+v*b+E*x,e}function V3(e,t){return e[0]=t[0],e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=t[1],e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=t[2],e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function j3(e,t,n,i){var r=t[0],s=t[1],a=t[2],o=t[3],c=r+r,l=s+s,u=a+a,d=r*c,f=r*l,h=r*u,b=s*l,m=s*u,g=a*u,p=o*c,x=o*l,_=o*u,y=i[0],v=i[1],E=i[2];return e[0]=(1-(b+g))*y,e[1]=(f+_)*y,e[2]=(h-x)*y,e[3]=0,e[4]=(f-_)*v,e[5]=(1-(d+g))*v,e[6]=(m+p)*v,e[7]=0,e[8]=(h+x)*E,e[9]=(m-p)*E,e[10]=(1-(d+b))*E,e[11]=0,e[12]=n[0],e[13]=n[1],e[14]=n[2],e[15]=1,e}function vf(e,t){let n=e.getAttribute("POSITION"),i=e.getIndices();if(!n)return 0;switch(t){case"render":return i?i.getCount():n.getCount();case"render-cached":return i?new Set(i.getArray()).size:n.getCount();case"upload-naive":case"upload":return n.getCount();case"distinct":case"distinct-position":return H3(t);case"unused":return i?n.getCount()-new Set(i.getArray()).size:0;default:return G3(t)}}function H3(e){throw Error(`Not implemented: ${e}`)}function G3(e){throw Error(`Unexpected value: ${e}`)}function $3(e,t,n){let i=of.fromGraph(e.getGraph());if(!t||!n)[t,n]=K3(e);let r=e.getIndices(),s=r?r.getArray():null,a=vf(e,"render"),o=i.createAccessor(),c=a,l=MM(c,n);for(let d=0;d<c;d++)l[d]=t[s?s[d]:d];e.setIndices(o.setArray(l));let u=SM(e);for(let d of e.listAttributes()){let f=yf(i,d);eb(d,r,t,f,n),e.swap(d,f)}for(let d of e.listTargets())for(let f of d.listAttributes()){let h=yf(i,f);eb(f,r,t,h,n),d.swap(f,h)}if(r&&r.listParents().length===1)r.dispose();for(let d of u)if(d.listParents().length===1)d.dispose();return e}function eb(e,t,n,i,r){let s=e.getElementSize(),a=e.getArray(),o=t?t.getArray():null,c=t?t.getCount():e.getCount(),l=new a.constructor(r*s),u=new Uint8Array(r);for(let d=0;d<c;d++){let f=o?o[d]:d,h=n[f];if(u[h])continue;for(let b=0;b<s;b++)l[h*s+b]=a[f*s+b];u[h]=1}return i.setArray(l)}function K3(e){let t=vf(e,"upload"),n=e.getIndices(),i=n?n.getArray():null;if(!n||!i)return[B3(t,1e6),t];let r=new Uint32Array(t).fill(dM),s=0;for(let a=0;a<i.length;a++){let o=i[a];if(r[o]===dM)r[o]=s++}return[r,s]}function W3(){var e=new _f(3);if(_f!=Float32Array)e[0]=0,e[1]=0,e[2]=0;return e}function X3(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e[2]=t[2]*n[2],e}function tb(e,t,n){return e[0]=Math.min(t[0],n[0]),e[1]=Math.min(t[1],n[1]),e[2]=Math.min(t[2],n[2]),e}function nb(e,t,n){return e[0]=Math.max(t[0],n[0]),e[1]=Math.max(t[1],n[1]),e[2]=Math.max(t[2],n[2]),e}function fM(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e}function q3(e,t,n){var i=t[0],r=t[1],s=t[2],a=n[3]*i+n[7]*r+n[11]*s+n[15];return a=a||1,e[0]=(n[0]*i+n[4]*r+n[8]*s+n[12])/a,e[1]=(n[1]*i+n[5]*r+n[9]*s+n[13])/a,e[2]=(n[2]*i+n[6]*r+n[10]*s+n[14])/a,e}function sb(e=Qg){let t=wf(Qg,e),n=new Set(t.propertyTypes);for(let i of t.propertyTypes)if(!Qg.propertyTypes.includes(i))throw Error(`${qs}: Unsupported deduplication on type "${i}".`);return Af(qs,(i)=>{let r=i.getLogger();if(n.has(Q.ACCESSOR))Z3(i);if(n.has(Q.TEXTURE))Q3(i,t);if(n.has(Q.MATERIAL))e9(i,t);if(n.has(Q.MESH))Y3(i,t);if(n.has(Q.SKIN))t9(i,t);r.debug(`${qs}: Complete.`)})}function Z3(e){let t=e.getLogger(),n=new Map,i=new Map,r=new Map,s=new Map,a=e.getRoot().listMeshes();a.forEach((d)=>{d.listPrimitives().forEach((f)=>{f.listAttributes().forEach((h)=>o(h,i)),o(f.getIndices(),n)})});for(let d of e.getRoot().listAnimations())for(let f of d.listSamplers())o(f.getInput(),r),o(f.getOutput(),s);function o(d,f){if(!d)return;let h=[d.getCount(),d.getType(),d.getComponentType(),d.getNormalized(),d.getSparse()].join(":"),b=f.get(h);if(!b)f.set(h,b=new Set);b.add(d)}function c(d,f){for(let h=0;h<d.length;h++){let b=d[h],m=Ze.toView(b.getArray());if(f.has(b))continue;for(let g=h+1;g<d.length;g++){let p=d[g];if(f.has(p))continue;if(Ze.equals(m,Ze.toView(p.getArray())))f.set(p,b)}}}let l=0,u=new Map;for(let d of[i,n,r,s])for(let f of d.values())l+=f.size,c(Array.from(f),u);t.debug(`${qs}: Merged ${u.size} of ${l} accessors.`),a.forEach((d)=>{d.listPrimitives().forEach((f)=>{f.listAttributes().forEach((b)=>{if(u.has(b))f.swap(b,u.get(b))});let h=f.getIndices();if(h&&u.has(h))f.swap(h,u.get(h))})});for(let d of e.getRoot().listAnimations())for(let f of d.listSamplers()){let h=f.getInput(),b=f.getOutput();if(h&&u.has(h))f.swap(h,u.get(h));if(b&&u.has(b))f.swap(b,u.get(b))}Array.from(u.keys()).forEach((d)=>d.dispose())}function Y3(e,t){let n=e.getLogger(),i=e.getRoot(),r=new Map;i.listAccessors().forEach((o,c)=>r.set(o,c)),i.listMaterials().forEach((o,c)=>r.set(o,c));let s=i.listMeshes().length,a=new Map;for(let o of i.listMeshes()){let c=[];for(let u of o.listPrimitives())c.push(IM(u,r));let l="";if(t.keepUniqueNames)l+=o.getName()+";";if(l+=c.join(";"),a.has(l)){let u=a.get(l);o.listParents().forEach((d)=>{if(d.propertyType!==Q.ROOT)d.swap(o,u)}),o.dispose()}else a.set(l,o)}n.debug(`${qs}: Merged ${s-a.size} of ${s} meshes.`)}function Q3(e,t){let n=e.getLogger(),i=e.getRoot(),r=i.listTextures(),s=new Map;for(let a=0;a<r.length;a++){let o=r[a],c=o.getImage();if(s.has(o))continue;for(let l=a+1;l<r.length;l++){let u=r[l],d=u.getImage();if(s.has(u))continue;if(o.getMimeType()!==u.getMimeType())continue;if(t.keepUniqueNames&&o.getName()!==u.getName())continue;let f=o.getSize(),h=u.getSize();if(!f||!h)continue;if(f[0]!==h[0])continue;if(f[1]!==h[1])continue;if(!c||!d)continue;if(Ze.equals(c,d))s.set(u,o)}}n.debug(`${qs}: Merged ${s.size} of ${i.listTextures().length} textures.`),Array.from(s.entries()).forEach(([a,o])=>{a.listParents().forEach((c)=>{if(!(c instanceof Ps))c.swap(a,o)}),a.dispose()})}function e9(e,t){let n=e.getLogger(),i=e.getRoot().listMaterials(),r=new Map,s=new Map,a=new Set;if(!t.keepUniqueNames)a.add("name");for(let o=0;o<i.length;o++){let c=i[o];if(r.has(c))continue;if(hM(c,s))continue;for(let l=o+1;l<i.length;l++){let u=i[l];if(r.has(u))continue;if(hM(u,s))continue;if(c.equals(u,a))r.set(u,c)}}n.debug(`${qs}: Merged ${r.size} of ${i.length} materials.`),Array.from(r.entries()).forEach(([o,c])=>{o.listParents().forEach((l)=>{if(!(l instanceof Ps))l.swap(o,c)}),o.dispose()})}function t9(e,t){let n=e.getLogger(),i=e.getRoot().listSkins(),r=new Map,s=new Set(["joints"]);if(!t.keepUniqueNames)s.add("name");for(let a=0;a<i.length;a++){let o=i[a];if(r.has(o))continue;for(let c=a+1;c<i.length;c++){let l=i[c];if(r.has(l))continue;if(o.equals(l,s)&&U3(o.listJoints(),l.listJoints()))r.set(l,o)}}n.debug(`${qs}: Merged ${r.size} of ${i.length} skins.`),Array.from(r.entries()).forEach(([a,o])=>{a.listParents().forEach((c)=>{if(!(c instanceof Ps))c.swap(a,o)}),a.dispose()})}function IM(e,t){let n=[];for(let i of e.listSemantics()){let r=e.getAttribute(i);n.push(i+":"+t.get(r))}if(e instanceof Zn){let i=e.getIndices();if(i)n.push("indices:"+t.get(i));let r=e.getMaterial();if(r)n.push("material:"+t.get(r));n.push("mode:"+e.getMode());for(let s of e.listTargets())n.push("target:"+IM(s,t))}return n.join(",")}function hM(e,t){if(t.has(e))return t.get(e);let n=e.getGraph(),i=new Set,r=n.listParentEdges(e);while(r.length>0){let s=r.pop();if(s.getAttributes().modifyChild===!0)return t.set(e,!0),!0;let a=s.getChild();if(i.has(a))continue;for(let o of n.listChildEdges(a))r.push(o)}return t.set(e,!1),!1}function CM(){var e=new _f(4);if(_f!=Float32Array)e[0]=0,e[1]=0,e[2]=0,e[3]=0;return e}function n9(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e[3]=t[3]+n[3],e}function i9(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e[2]=t[2]-n[2],e[3]=t[3]-n[3],e}function r9(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e[2]=t[2]*n[2],e[3]=t[3]*n[3],e}function s9(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e}function a9(e){var t=e[0],n=e[1],i=e[2],r=e[3];return Math.sqrt(t*t+n*n+i*i+r*r)}function l9(e){return e.getGraph().listParentEdges(e).some((t)=>t.getAttributes().isColor||c9.test(t.getName()))?"srgb":null}function u9(e){let t=e.getGraph(),n=new Set,i=new Set;function r(s){let a=new Set;for(let o of t.listChildEdges(s))if(o.getChild()instanceof Xo)a.add(o.getName()+"Info");for(let o of t.listChildEdges(s)){let c=o.getChild();if(n.has(c))continue;if(n.add(c),c instanceof wt&&a.has(o.getName()))i.add(c);else if(c instanceof nt)r(c)}}return r(e),Array.from(i)}function d9(e){let t=of.fromGraph(e.getGraph()).getRoot(),n=e.getGraph().listParentEdges(e).filter((i)=>i.getParent()!==t).map((i)=>i.getName());return Array.from(new Set(n))}function Sf(e=pM){let t=wf(pM,e),n=new Set(t.propertyTypes),i=t.keepExtras;return Af(Yo,async(r)=>{let s=r.getLogger(),a=r.getRoot(),o=r.getGraph(),c=new f9,l=(u)=>c.dispose(u.target);if(o.addEventListener("node:dispose",l),n.has(Q.MESH))for(let u of a.listMeshes()){if(u.listPrimitives().length>0)continue;u.dispose()}if(n.has(Q.NODE)){if(!t.keepLeaves)for(let u of a.listScenes())OM(o,u,i);for(let u of a.listNodes())Si(u,i)}if(n.has(Q.SKIN))for(let u of a.listSkins())Si(u,i);if(n.has(Q.MESH))for(let u of a.listMeshes())Si(u,i);if(n.has(Q.CAMERA))for(let u of a.listCameras())Si(u,i);if(n.has(Q.PRIMITIVE))mM(o,Q.PRIMITIVE,i);if(n.has(Q.PRIMITIVE_TARGET))mM(o,Q.PRIMITIVE_TARGET,i);if(!t.keepAttributes&&n.has(Q.ACCESSOR)){let u=new Map;for(let d of a.listMeshes())for(let f of d.listPrimitives()){let h=f.getMaterial();if(!h)continue;let b=h9(f,kM(r,f,h));gM(f,b),f.listTargets().forEach((m)=>gM(m,b)),u.has(h)?u.get(h).add(f):u.set(h,new Set([f]))}for(let[d,f]of u)p9(d,Array.from(f))}if(n.has(Q.ANIMATION))for(let u of a.listAnimations()){for(let d of u.listChannels())if(!d.getTargetNode())d.dispose();if(!u.listChannels().length){let d=u.listSamplers();Si(u,i),d.forEach((f)=>Si(f,i))}else u.listSamplers().forEach((d)=>Si(d,i))}if(n.has(Q.MATERIAL))a.listMaterials().forEach((u)=>Si(u,i));if(n.has(Q.TEXTURE)){if(a.listTextures().forEach((u)=>Si(u,i)),!t.keepSolidTextures)await m9(r)}if(n.has(Q.ACCESSOR))a.listAccessors().forEach((u)=>Si(u,i));if(n.has(Q.BUFFER))a.listBuffers().forEach((u)=>Si(u,i));if(o.removeEventListener("node:dispose",l),!c.empty()){let u=c.entries().map(([d,f])=>`${d} (${f})`).join(", ");s.info(`${Yo}: Removed types... ${u}`)}else s.debug(`${Yo}: No unused properties found.`);s.debug(`${Yo}: Complete.`)})}function Si(e,t){let n=e.listParents().filter((r)=>!(r instanceof Ps||r instanceof Fa)),i=t&&!RM(e.getExtras());if(!n.length&&!i)e.dispose()}function mM(e,t,n){for(let i of e.listEdges()){let r=i.getParent();if(r.propertyType===t)Si(r,n)}}function OM(e,t,n){if(t.listChildren().forEach((a)=>OM(e,a,n)),t instanceof af)return;let i=e.listParentEdges(t).some((a)=>{let o=a.getParent().propertyType;return o!==Q.ROOT&&o!==Q.SCENE&&o!==Q.NODE}),r=e.listChildren(t).length===0,s=n&&!RM(t.getExtras());if(r&&!i&&!s)t.dispose()}function gM(e,t){for(let n of t)e.setAttribute(n,null)}function h9(e,t){let n=[];for(let i of e.listSemantics())if(i==="NORMAL"&&!t.has(i))n.push(i);else if(i==="TANGENT"&&!t.has(i))n.push(i);else if(i.startsWith("TEXCOORD_")&&!t.has(i))n.push(i);else if(i.startsWith("COLOR_")&&i!=="COLOR_0")n.push(i);return n}function kM(e,t,n,i=new Set){let r=e.getGraph().listChildEdges(n),s=new Set;for(let c of r)if(c.getChild()instanceof Xo)s.add(c.getName());for(let c of r){let l=c.getName(),u=c.getChild();if(u instanceof wt){if(s.has(l.replace(/Info$/,"")))i.add(`TEXCOORD_${u.getTexCoord()}`)}if(u instanceof Xo&&l.match(/normalTexture/i))i.add("TANGENT");if(u instanceof nt)kM(e,t,u,i)}let a=n instanceof Da&&!n.getExtension("KHR_materials_unlit"),o=t.getMode()===Zn.Mode.POINTS;if(a&&!o)i.add("NORMAL");return i}function p9(e,t){let n=u9(e),i=new Set(n.map((c)=>c.getTexCoord())),r=Array.from(i).sort(),s=new Map(r.map((c,l)=>[c,l])),a=new Map(r.map((c,l)=>[`TEXCOORD_${c}`,`TEXCOORD_${l}`]));for(let c of n){let l=c.getTexCoord();c.setTexCoord(s.get(l))}for(let c of t){let l=c.listSemantics().filter((u)=>u.startsWith("TEXCOORD_")).sort();o(c,l),c.listTargets().forEach((u)=>o(u,l))}function o(c,l){for(let u of l){let d=c.getAttribute(u);if(!d)continue;let f=a.get(u);if(f===u)continue;c.setAttribute(f,d),c.setAttribute(u,null)}}}async function m9(e){let t=e.getRoot(),n=e.getGraph(),i=e.getLogger(),r=t.listTextures().map(async(s)=>{let a=await b9(s);if(!a)return;if(l9(s)==="srgb")$w.convertSRGBToLinear(a,a);let o=s.getName()||s.getURI(),c=s.getSize()?.join("x"),l=d9(s);for(let u of n.listParentEdges(s)){let d=u.getParent();if(d!==t&&g9(d,a,u.getName(),i))u.dispose()}if(s.listParents().length===1)s.dispose(),i.debug(`${Yo}: Removed solid-color texture "${o}" (${c}px ${l.join(", ")})`)});await Promise.all(r)}function g9(e,t,n,i){if(e instanceof Da)switch(n){case"baseColorTexture":return e.setBaseColorFactor(o9(t,t,e.getBaseColorFactor())),!0;case"emissiveTexture":return e.setEmissiveFactor(J3([0,0,0],t.slice(0,3),e.getEmissiveFactor())),!0;case"occlusionTexture":return Math.abs(t[0]-1)<=ib;case"metallicRoughnessTexture":return e.setRoughnessFactor(t[1]*e.getRoughnessFactor()),e.setMetallicFactor(t[2]*e.getMetallicFactor()),!0;case"normalTexture":return PM(NM(CM(),t,[0.5,0.5,1,1]))<=ib}return i.warn(`${Yo}: Detected single-color ${n} texture. Pruning ${n} not yet supported.`),!1}async function b9(e){let t=await x9(e);if(!t)return null;let n=[1/0,1/0,1/0,1/0],i=[-1/0,-1/0,-1/0,-1/0],r=[0,0,0,0],[s,a]=t.shape;for(let o=0;o<s;o++){for(let c=0;c<a;c++)for(let l=0;l<4;l++)n[l]=Math.min(n[l],t.get(o,c,l)),i[l]=Math.max(i[l],t.get(o,c,l));if(PM(NM(r,i,n))/255>ib)return null}return s9(r,n9(r,i,n),0.00196078431372549)}async function x9(e){try{return await lM(e.getImage(),e.getMimeType())}catch{return null}}function y9(e,t=1/0){if(Number.isFinite(t)&&t%4||t<=0)throw Error("Limit must be positive multiple of four.");let n=e.getAttribute("POSITION").getCount(),i=e.listSemantics().filter((l)=>l.startsWith("WEIGHTS_")).length,r=new Uint16Array(i*4),s=new Float32Array(i*4),a=new Float32Array(i*4),o=new Uint32Array(i*4),c=new Uint32Array(i*4);for(let l=0;l<n;l++){Ef(e,l,"WEIGHTS",s),Ef(e,l,"JOINTS",o);for(let u=0;u<i*4;u++)r[u]=u;r.sort((u,d)=>s[u]>s[d]?-1:1);for(let u=0;u<r.length;u++)a[u]=s[r[u]],c[u]=o[r[u]];Tf(e,l,"WEIGHTS",a),Tf(e,l,"JOINTS",c)}for(let l=i;l*4>t;l--){let u=e.getAttribute(`WEIGHTS_${l-1}`),d=e.getAttribute(`JOINTS_${l-1}`);if(e.setAttribute(`WEIGHTS_${l-1}`,null),e.setAttribute(`JOINTS_${l-1}`,null),u.listParents().length===1)u.dispose();if(d.listParents().length===1)d.dispose()}_9(e)}function _9(e){if(!v9(e))return;let t=e.getAttribute("POSITION").getCount(),n=e.listSemantics().filter((d)=>d.startsWith("WEIGHTS_")).length,i=e.getAttribute("WEIGHTS_0"),r=i.getArray(),s=i.getComponentType(),a=i.getNormalized(),o=a?s:void 0,c=a?mt.decodeNormalizedInt(1,s):Number.EPSILON,l=new Uint32Array(n*4).fill(0),u=r.slice(0,n*4).fill(0);for(let d=0;d<t;d++){Ef(e,d,"JOINTS",l),Ef(e,d,"WEIGHTS",u,o);let f=bM(u,o);if(f!==0&&f!==1){if(Math.abs(1-f)>c)for(let h=0;h<u.length;h++)if(a){let b=mt.decodeNormalizedInt(u[h],s);u[h]=mt.encodeNormalizedInt(b/f,s)}else u[h]/=f;if(f=bM(u,o),a&&f!==1){for(let h=u.length-1;h>=0;h--)if(u[h]>0){let b=1-f;u[h]+=Math.sign(b)*mt.encodeNormalizedInt(Math.abs(b),s);break}}}for(let h=u.length-1;h>=0;h--)if(u[h]===0)l[h]=0;Tf(e,d,"JOINTS",l),Tf(e,d,"WEIGHTS",u,o)}}function Ef(e,t,n,i,r){let s,a=[0,0,0,0];for(let o=0;s=e.getAttribute(`${n}_${o}`);o++){s.getElement(t,a);for(let c=0;c<4;c++)if(r)i[o*4+c]=mt.encodeNormalizedInt(a[c],r);else i[o*4+c]=a[c]}return i}function Tf(e,t,n,i,r){let s,a=[0,0,0,0];for(let o=0;s=e.getAttribute(`${n}_${o}`);o++){for(let c=0;c<4;c++)if(r)a[c]=mt.decodeNormalizedInt(i[o*4+c],r);else a[c]=i[o*4+c];s.setElement(t,a)}}function bM(e,t){let n=0;for(let i=0;i<e.length;i++)if(t)n+=mt.decodeNormalizedInt(e[i],t);else n+=e[i];return n}function v9(e){let t=e.listSemantics().filter((r)=>r.startsWith("WEIGHTS_")).map((r)=>e.getAttribute(r)),n=t.map((r)=>r.getNormalized()),i=t.map((r)=>r.getComponentType());return new Set(n).size===1&&new Set(i).size===1}function DM(e=xf){let t=wf(xf,{patternTargets:e.pattern||xf.pattern,...e});return Af(Xs,async(n)=>{let i=n.getLogger(),r=n.getRoot();if(n.hasExtension("KHR_mesh_primitive_restart"))throw Error("quantize: Missing support for KHR_mesh_primitive_restart.");let s;if(t.quantizationVolume==="scene")s=yM(D9(r.listMeshes().map(_M)));for(let a of n.getRoot().listMeshes()){if(t.quantizationVolume==="mesh")s=yM(_M(a));if(s&&t.pattern.test("POSITION"))R9(n,a,s),N9(a,1/s.scale);for(let o of a.listPrimitives()){if(vf(o,"render")<vf(o,"upload")/2)$3(o);xM(n,o,s,t);for(let c of o.listTargets())xM(n,c,s,t)}}if(r.listMeshes().flatMap((a)=>a.listPrimitives()).some(LM))n.createExtension(Il).setRequired(!0);if(t.cleanup)await n.transform(Sf({propertyTypes:[Q.ACCESSOR,Q.SKIN,Q.MATERIAL],keepAttributes:!0,keepIndices:!0,keepLeaves:!0,keepSolidTextures:!0}),sb({propertyTypes:[Q.ACCESSOR,Q.MATERIAL,Q.SKIN],keepUniqueNames:!0}));i.debug(`${Xs}: Complete.`)})}function xM(e,t,n,i){let r=t instanceof Vg,s=e.getLogger();for(let a of t.listSemantics()){if(!r&&!i.pattern.test(a))continue;if(r&&!i.patternTargets.test(a))continue;let o=t.getAttribute(a),{bits:c,ctor:l}=O9(a,o,s,i);if(!l)continue;if(c<8||c>16)throw Error(`${Xs}: Requires bits = 8–16.`);if(o.getComponentSize()<=c/8)continue;let u=o.clone();if(a==="POSITION"){let d=n.scale,f=[];t instanceof Zn?z3(f,Mf(n)):V3(f,[1/d,1/d,1/d]);for(let h=0,b=[0,0,0],m=u.getCount();h<m;h++)u.getElement(h,b),u.setElement(h,q3(b,b,f))}P9(u,l,c),t.setAttribute(a,u)}if(i.normalizeWeights&&t.getAttribute("WEIGHTS_0"))y9(t,1/0);if(t instanceof Zn&&t.getIndices()&&t.listAttributes().length&&t.listAttributes()[0].getCount()<65535){let a=t.getIndices();a.setArray(new Uint16Array(a.getArray()))}}function yM(e){let{min:t,max:n}=e,i=Math.max((n[0]-t[0])/2,(n[1]-t[1])/2,(n[2]-t[2])/2);return{offset:[t[0]+(n[0]-t[0])/2,t[1]+(n[1]-t[1])/2,t[2]+(n[2]-t[2])/2],scale:i}}function R9(e,t,n){let i=Mf(n);for(let r of t.listParents()){if(!(r instanceof sf))continue;let s=r.listParents().filter((f)=>f instanceof Fa),a=s.some((f)=>M9.includes(f.getTargetPath())),o=r.listChildren().length>0,c=r.getSkin();if(c){r.setSkin(I9(c,n));continue}let l=r.getExtension("EXT_mesh_gpu_instancing");if(l){r.setExtension("EXT_mesh_gpu_instancing",C9(e,l,n));continue}let u;if(o||a)u=e.createNode("").setMesh(t),r.addChild(u).setMesh(null),s.filter((f)=>f.getTargetPath()===S9).forEach((f)=>f.setTargetNode(u));else u=r;let d=u.getMatrix();rb(d,d,i),u.setMatrix(d)}}function I9(e,t){e=e.clone();let n=Mf(t),i=e.getInverseBindMatrices().clone(),r=[];for(let s=0,a=i.getCount();s<a;s++)i.getElement(s,r),rb(r,r,n),i.setElement(s,r);return e.setInverseBindMatrices(i)}function C9(e,t,n){if(!t.getAttribute("TRANSLATION")&&!t.getAttribute("ROTATION")&&!t.getAttribute("SCALE"))return t;t=t.clone();let i=t.getAttribute("TRANSLATION")?.clone(),r=t.getAttribute("ROTATION")?.clone(),s=t.getAttribute("SCALE")?.clone(),a=i||r||s,o=[0,0,0],c=[0,0,0,1],l=[1,1,1];if(!i&&n.offset)i=e.createAccessor().setType("VEC3").setArray(EM(a.getCount(),o));if(!s&&n.scale)s=e.createAccessor().setType("VEC3").setArray(EM(a.getCount(),l));let u=[0,0,0],d=[0,0,0,1],f=[1,1,1],h=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],b=Mf(n);for(let m=0,g=a.getCount();m<g;m++){if(mt.compose(i?i.getElement(m,u):o,r?r.getElement(m,d):c,s?s.getElement(m,f):l,h),rb(h,h,b),mt.decompose(h,u,d,f),i)i.setElement(m,u);if(r)r.setElement(m,d);if(s)s.setElement(m,f)}if(i)t.setAttribute("TRANSLATION",i);if(r)t.setAttribute("ROTATION",r);if(s)t.setAttribute("SCALE",s);return t}function N9(e,t){for(let n of e.listPrimitives()){let i=n.getMaterial();if(!i)continue;let r=i.getExtension("KHR_materials_volume");if(!r||r.getThicknessFactor()<=0)continue;r=r.clone().setThicknessFactor(r.getThicknessFactor()*t),i=i.clone().setExtension("KHR_materials_volume",r),n.setMaterial(i)}}function P9(e,t,n){let i=new t(e.getArray().length),r=E9.includes(t)?1:0,s=n-r,a=t.BYTES_PER_ELEMENT*8-r,o=Math.pow(2,s)-1,c=a-s,l=2*s-a,u=[r>0?-1:0,1];for(let d=0,f=0,h=[];d<e.getCount();d++){e.getElement(d,h);for(let b=0;b<h.length;b++){let m=L9(h[b],u);m=Math.round(Math.abs(m)*o),m=m<<c|m>>l,i[f++]=m*Math.sign(h[b])}}e.setArray(i).setNormalized(!0).setSparse(!1)}function O9(e,t,n,i){let r=t.getMinNormalized([]),s=t.getMaxNormalized([]),a,o;if(e==="POSITION")a=i.quantizePosition,o=a<=8?Int8Array:Int16Array;else if(e==="NORMAL"||e==="TANGENT")a=i.quantizeNormal,o=a<=8?Int8Array:Int16Array;else if(e.startsWith("COLOR_"))a=i.quantizeColor,o=a<=8?Uint8Array:Uint16Array;else if(e.startsWith("TEXCOORD_")){if(r.some((c)=>c<0)||s.some((c)=>c>1))return n.warn(`${Xs}: Skipping ${e}; out of [0,1] range.`),{bits:-1};a=i.quantizeTexcoord,o=a<=8?Uint8Array:Uint16Array}else if(e.startsWith("JOINTS_")){if(a=Math.max(...t.getMax([]))<=255?8:16,o=a<=8?Uint8Array:Uint16Array,t.getComponentSize()>a/8)t.setArray(new o(t.getArray()));return{bits:-1}}else if(e.startsWith("WEIGHTS_")){if(r.some((c)=>c<0)||s.some((c)=>c>1))return n.warn(`${Xs}: Skipping ${e}; out of [0,1] range.`),{bits:-1};a=i.quantizeWeight,o=a<=8?Uint8Array:Uint16Array}else if(e.startsWith("_")){if(r.some((c)=>c<-1)||s.some((c)=>c>1))return n.warn(`${Xs}: Skipping ${e}; out of [-1,1] range.`),{bits:-1};a=i.quantizeGeneric,o=r.some((c)=>c<0)?o=a<=8?Int8Array:Int16Array:o=a<=8?Uint8Array:Uint16Array}else throw Error(`${Xs}: Unexpected semantic, "${e}".`);return{bits:a,ctor:o}}function _M(e){let t=[],n=[];for(let r of e.listPrimitives()){let s=r.getAttribute("POSITION");if(s)t.push(s);for(let a of r.listTargets()){let o=a.getAttribute("POSITION");if(o)n.push(o)}}if(t.length===0)throw Error(`${Xs}: Missing "POSITION" attribute.`);let i=vM(t,3);if(n.length>0){let{min:r,max:s}=vM(n,3);tb(i.min,i.min,tb(r,fM(r,r,2),[0,0,0])),nb(i.max,i.max,nb(s,fM(s,s,2),[0,0,0]))}return i}function k9(e,t){let n=t.getComponentSize();if(e==="POSITION")return n<4;if(e==="NORMAL")return n<4;if(e==="TANGENT")return n<4;if(e.startsWith("TEXCOORD_")){let i=t.getComponentType(),r=t.getNormalized();return n<4&&!(r&&i===Oe.ComponentType.UNSIGNED_BYTE)&&!(r&&i===Oe.ComponentType.UNSIGNED_SHORT)}return!1}function LM(e){for(let t of e.listSemantics())if(k9(t,e.getAttribute("POSITION")))return!0;if(e.propertyType===Q.PRIMITIVE)return e.listTargets().some(LM);return!1}function vM(e,t){let n=Array(t).fill(1/0),i=Array(t).fill(-1/0),r=[],s=[];for(let a of e){a.getMinNormalized(r),a.getMaxNormalized(s);for(let o=0;o<t;o++)n[o]=Math.min(n[o],r[o]),i[o]=Math.max(i[o],s[o])}return{min:n,max:i}}function D9(e){let t=e[0];for(let n of e)tb(t.min,t.min,n.min),nb(t.max,t.max,n.max);return t}function Mf(e){return j3([],[0,0,0,1],e.offset,[e.scale,e.scale,e.scale])}function L9(e,t){return Math.min(Math.max(e,t[0]),t[1])}function EM(e,t){let n=t.length,i=new Float32Array(e*n);for(let r=0;r<e;r++)i.set(t,r*n);return i}function FM(e){let t=wf(F9,e),n=t.encoder;if(!n)throw Error(`${gf}: encoder dependency required — install "meshoptimizer".`);return Af(gf,async(i)=>{let r=i.getLogger();if(i.hasExtension("KHR_mesh_primitive_restart"))throw Error("reorder: Missing support for KHR_mesh_primitive_restart.");await n.ready;let s=U9(i);for(let a of s.indicesToAttributes.keys()){let o=a.getArray();if(!(o instanceof Uint32Array))o=new Uint32Array(o);else o=o.slice();let[c,l]=n.reorderMesh(o,s.indicesToMode.get(a)===Zn.Mode.TRIANGLES,t.target==="size"),u=yf(i,a);u.setArray(l<=65534?new Uint16Array(o):o);for(let d of s.indicesToAttributes.get(a)){let f=yf(i,d);eb(d,a,c,f,l);for(let h of s.indicesToPrimitives.get(a)){if(h.getIndices()===a)h.swap(a,u);h.swap(d,f);for(let b of h.listTargets())b.swap(d,f)}}}if(t.cleanup)await i.transform(Sf({propertyTypes:[Q.ACCESSOR],keepAttributes:!0,keepIndices:!0}));if(!s.indicesToAttributes.size)r.warn(`${gf}: No qualifying primitives found; may need to weld first.`);else r.debug(`${gf}: Complete.`)})}function U9(e){let t=new Map,n=new Yg,i=new Yg,r=new Yg;for(let s of e.getRoot().listMeshes())for(let a of s.listPrimitives()){let o=a.getIndices();if(!o)continue;t.set(o,a.getMode()),n.add(o,a);for(let c of SM(a))i.add(o,c),r.add(c,a)}return{indicesToPrimitives:n,indicesToAttributes:i,indicesToMode:t,attributesToPrimitives:r}}function z9(e,t,n,i=0.0001){let r=t.length/e.length,s=Array(r).fill(0),a=Array(r).fill(0),o=Array(r).fill(0),c=Array(r).fill(0),l=e.length-1,u=1;for(let d=1;d<l;++d){let f=e[u-1],h=e[d],b=e[d+1],m=(h-f)/(b-f),g=!1;if(h!==b&&(d!==1||h!==e[0])){if(Cl(t,u-1,c),Cl(t,d,a),Cl(t,d+1,o),n==="slerp"){let p=H9(s,c,o,m),x=wM(c,a)+wM(a,o);g=!bf(a,p,i)||x+Number.EPSILON>=Math.PI}else if(n==="lerp")g=!bf(a,j9(s,c,o,m),i);else if(n==="step")g=!bf(a,c)||!bf(a,o)}if(g){if(d!==u)e[u]=e[d],AM(t,u,Cl(t,d,s));u++}}if(l>0)e[u]=e[l],AM(t,u,Cl(t,l,s)),u++;return u}function Cl(e,t,n){for(let i=0,r=n.length;i<r;i++)n[i]=e[t*r+i];return n}function AM(e,t,n){for(let i=0,r=n.length;i<r;i++)e[t*r+i]=n[i]}function bf(e,t,n=0){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(Math.abs(e[i]-t[i])>n)return!1;return!0}function V9(e,t,n){return e*(1-n)+t*n}function j9(e,t,n,i){for(let r=0;r<t.length;r++)e[r]=V9(t[r],n[r],i);return e}function H9(e,t,n,i){let r=t[0],s=t[1],a=t[2],o=t[3],c=n[0],l=n[1],u=n[2],d=n[3],f,h,b,m,g;if(h=r*c+s*l+a*u+o*d,h<0)h=-h,c=-c,l=-l,u=-u,d=-d;if(1-h>B9)f=Math.acos(h),b=Math.sin(f),m=Math.sin((1-i)*f)/b,g=Math.sin(i*f)/b;else m=1-i,g=i;return e[0]=m*r+g*c,e[1]=m*s+g*l,e[2]=m*a+g*u,e[3]=m*o+g*d,e}function wM(e,t){let n=G9(e,t);return Math.acos(2*n*n-1)}function G9(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}var F3,hK,pK,mK,gK,bK,xK,yK,Yg=class{_map=new Map;get size(){return this._map.size}has(e){return this._map.has(e)}add(e,t){let n=this._map.get(e);if(!n)n=new Set,this._map.set(e,n);return n.add(t),this}get(e){return this._map.get(e)||new Set}keys(){return this._map.keys()}},_K,_f,dM=4294967295,J3,vK,EK,TK,AK,wK,SK,MK,qs="dedup",Qg,RK,IK,NM,o9,PM,c9,Yo="prune",ib=0.011764705882352941,pM,f9=class{disposed={};empty(){for(let e in this.disposed)return!1;return!0}entries(){return Object.entries(this.disposed)}dispose(e){this.disposed[e.propertyType]=this.disposed[e.propertyType]||0,this.disposed[e.propertyType]++}},CK,NK,PK,OK,kK,Xs="quantize",E9,T9,A9,w9,S9,M9,xf,gf="reorder",F9,DK,TM,B9=0.000001,LK,FK,UK,BK,zK,VK,jK,HK;var UM=ht(()=>{qo();uM();hf();F3=Bf(qg(),1),{POINTS:hK,LINES:pK,LINE_STRIP:mK,LINE_LOOP:gK,TRIANGLES:bK,TRIANGLE_STRIP:xK,TRIANGLE_FAN:yK}=Zn.Mode;_K=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});_f=typeof Float32Array<"u"?Float32Array:Array;Math.PI/180;180/Math.PI;J3=X3;(function(){var e=W3();return function(t,n,i,r,s,a){var o,c;if(!n)n=3;if(!i)i=0;if(r)c=Math.min(r*n+i,t.length);else c=t.length;for(o=i;o<c;o+=n)e[0]=t[o],e[1]=t[o+1],e[2]=t[o+2],s(e,e,a),t[o]=e[0],t[o+1]=e[1],t[o+2]=e[2];return t}})();({FLOAT:vK}=Oe.ComponentType),{LINES:EK,LINE_STRIP:TK,LINE_LOOP:AK,TRIANGLES:wK,TRIANGLE_STRIP:SK,TRIANGLE_FAN:MK}=Zn.Mode,Qg={keepUniqueNames:!1,propertyTypes:[Q.ACCESSOR,Q.MESH,Q.TEXTURE,Q.MATERIAL,Q.SKIN]};({TEXTURE_INFO:RK,ROOT:IK}=Q);NM=i9,o9=r9,PM=a9;(function(){var e=CM();return function(t,n,i,r,s,a){var o,c;if(!n)n=4;if(!i)i=0;if(r)c=Math.min(r*n+i,t.length);else c=t.length;for(o=i;o<c;o+=n)e[0]=t[o],e[1]=t[o+1],e[2]=t[o+2],e[3]=t[o+3],s(e,e,a),t[o]=e[0],t[o+1]=e[1],t[o+2]=e[2],t[o+3]=e[3];return t}})();c9=/color|emissive|diffuse/i;pM={propertyTypes:[Q.NODE,Q.SKIN,Q.MESH,Q.CAMERA,Q.PRIMITIVE,Q.PRIMITIVE_TARGET,Q.ANIMATION,Q.MATERIAL,Q.TEXTURE,Q.ACCESSOR,Q.BUFFER],keepLeaves:!1,keepAttributes:!1,keepIndices:!1,keepSolidTextures:!1,keepExtras:!1};({ROOT:CK,NODE:NK,MESH:PK,PRIMITIVE:OK,ACCESSOR:kK}=Q);E9=[Int8Array,Int16Array,Int32Array],{TRANSLATION:T9,ROTATION:A9,SCALE:w9,WEIGHTS:S9}=Fa.TargetPath,M9=[T9,A9,w9],xf={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12,normalizeWeights:!0,cleanup:!0};F9={target:"size",cleanup:!0};DK={level:"high",...xf};(function(e){e[e.STEP=0]="STEP",e[e.LERP=1]="LERP",e[e.SLERP=2]="SLERP"})(TM||(TM={}));LK={ready:Promise.resolve(),resample:z9,tolerance:0.0001,cleanup:!0},{POINTS:FK,LINES:UK,LINE_STRIP:BK,LINE_LOOP:zK,TRIANGLES:VK,TRIANGLE_STRIP:jK,TRIANGLE_FAN:HK}=Zn.Mode});function zM(e,t,n,i={}){if(!Array.isArray(t))return e.push({code:"EXPECTED_ARRAY",path:n,message:`${n} must be an array.`}),!1;if(!i.allowEmpty&&t.length===0)e.push({code:"EXPECTED_NONEMPTY_ARRAY",path:n,message:`${n} must not be empty.`});let r=new Set;for(let s=0;s<t.length;s++){let a=t[s];if(!$r(a)){e.push({code:"EXPECTED_NONEMPTY_STRING",path:`${n}[${s}]`,message:`${n}[${s}] must be a trimmed non-empty string.`});continue}if(r.has(a))e.push({code:"DUPLICATE_VALUE",path:`${n}[${s}]`,message:`${n} contains duplicate value ${JSON.stringify(a)}.`});r.add(a)}return!0}function W9(e,t,n){let i=`frames[${t}]`;if(!Js(e))return n.push({code:"INVALID_FRAME",path:i,message:`${i} must be an object.`}),!1;if(!$r(e.id))n.push({code:"INVALID_FRAME_ID",path:`${i}.id`,message:"Frame ID is required."});if(!BM(e.translation,3))n.push({code:"INVALID_FRAME_TRANSLATION",path:`${i}.translation`,message:"Frame translation must be three finite meters."});if(!BM(e.rotation,4))n.push({code:"INVALID_FRAME_ROTATION",path:`${i}.rotation`,message:"Frame rotation must be a finite quaternion."});else{let r=Math.hypot(...e.rotation);if(Math.abs(r-1)>0.000001)n.push({code:"NON_UNIT_FRAME_ROTATION",path:`${i}.rotation`,message:"Frame rotation quaternion must be normalized within 1e-6."})}return!0}function X9(e,t,n){let i=`relationships[${t}]`;if(!Js(e))return n.push({code:"INVALID_RELATIONSHIP",path:i,message:`${i} must be an object.`}),!1;for(let r of["kind","target"])if(!$r(e[r]))n.push({code:"INVALID_RELATIONSHIP_FIELD",path:`${i}.${r}`,message:`${i}.${r} must be a trimmed non-empty string.`});if(e.targetType!=="node"&&e.targetType!=="role"&&e.targetType!=="socket")n.push({code:"INVALID_RELATIONSHIP_TARGET_TYPE",path:`${i}.targetType`,message:"Relationship targetType must be node, role, or socket."});for(let r of["sourceFrame","targetFrame"])if(e[r]!==void 0&&!$r(e[r]))n.push({code:"INVALID_RELATIONSHIP_FRAME",path:`${i}.${r}`,message:`${i}.${r} must be a trimmed non-empty string.`});return!0}function q9(e,t,n){let i=`sockets[${t}]`;if(!Js(e))return n.push({code:"INVALID_SOCKET",path:i,message:`${i} must be an object.`}),!1;for(let r of["id","type","frame"])if(!$r(e[r]))n.push({code:"INVALID_SOCKET_FIELD",path:`${i}.${r}`,message:`${i}.${r} must be a trimmed non-empty string.`});if(zM(n,e.compatibleTypes,`${i}.compatibleTypes`,{allowEmpty:!0}),e.allowedRotationsDegrees!==void 0){if(!Array.isArray(e.allowedRotationsDegrees)||e.allowedRotationsDegrees.some((r)=>typeof r!=="number"||!Number.isFinite(r)))n.push({code:"INVALID_ALLOWED_ROTATIONS",path:`${i}.allowedRotationsDegrees`,message:"Allowed rotations must be finite degree values."})}return!0}function J9(e){let t=[];if(!Js(e))return{valid:!1,issues:[{code:"EXPECTED_OBJECT",path:"",message:"SemanticMetadataV1 must be an object."}]};if(e.schemaVersion!==1)t.push({code:"UNSUPPORTED_SCHEMA_VERSION",path:"schemaVersion",message:"schemaVersion must be 1."});zM(t,e.roles,"roles");let n=Array.isArray(e.frames)?e.frames:[];if(!Array.isArray(e.frames))t.push({code:"EXPECTED_ARRAY",path:"frames",message:"frames must be an array."});let i=new Set;n.forEach((o,c)=>{if(W9(o,c,t),Js(o)&&$r(o.id)){if(i.has(o.id))t.push({code:"DUPLICATE_FRAME_ID",path:`frames[${c}].id`,message:`Duplicate frame ID ${JSON.stringify(o.id)}.`});i.add(o.id)}});let r=Array.isArray(e.relationships)?e.relationships:[];if(!Array.isArray(e.relationships))t.push({code:"EXPECTED_ARRAY",path:"relationships",message:"relationships must be an array."});r.forEach((o,c)=>{if(X9(o,c,t),Js(o))for(let l of["sourceFrame","targetFrame"]){let u=o[l];if($r(u)&&!i.has(u))t.push({code:"UNKNOWN_FRAME_REFERENCE",path:`relationships[${c}].${l}`,message:`Unknown frame ${JSON.stringify(u)}.`})}});let s=Array.isArray(e.sockets)?e.sockets:[];if(!Array.isArray(e.sockets))t.push({code:"EXPECTED_ARRAY",path:"sockets",message:"sockets must be an array."});let a=new Set;if(s.forEach((o,c)=>{if(q9(o,c,t),Js(o)&&$r(o.id)){if(a.has(o.id))t.push({code:"DUPLICATE_SOCKET_ID",path:`sockets[${c}].id`,message:`Duplicate socket ID ${JSON.stringify(o.id)}.`});a.add(o.id)}if(Js(o)&&$r(o.frame)&&!i.has(o.frame))t.push({code:"UNKNOWN_FRAME_REFERENCE",path:`sockets[${c}].frame`,message:`Unknown frame ${JSON.stringify(o.frame)}.`})}),t.length>0)return{valid:!1,issues:t};return{valid:!0,value:Z9(e),issues:t}}function Z9(e){return{schemaVersion:1,roles:[...e.roles],relationships:e.relationships.map((t)=>({kind:t.kind,target:t.target,targetType:t.targetType,...t.sourceFrame?{sourceFrame:t.sourceFrame}:{},...t.targetFrame?{targetFrame:t.targetFrame}:{}})),frames:e.frames.map((t)=>({id:t.id,translation:$9(t.translation),rotation:K9(t.rotation)})),sockets:e.sockets.map((t)=>({id:t.id,type:t.type,frame:t.frame,compatibleTypes:[...t.compatibleTypes],...t.allowedRotationsDegrees?{allowedRotationsDegrees:[...t.allowedRotationsDegrees]}:{}}))}}function Rf(e){let t=e.kilnSemantic;if(t===void 0)return;let n=J9(t);return n.valid?n.value:void 0}var Zs,Js=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),$r=(e)=>typeof e==="string"&&e.trim().length>0&&e===e.trim(),BM=(e,t)=>Array.isArray(e)&&e.length===t&&e.every((n)=>typeof n==="number"&&Number.isFinite(n)),$9=(e)=>[e[0],e[1],e[2]],K9=(e)=>[e[0],e[1],e[2],e[3]];var Nl=ht(()=>{Zs=Object.freeze({vehicleFrame:"vehicle.frame",vehicleForward:"vehicle.front.+x",socket:"socket",chassis:"chassis",chassisMain:"chassis.main",axle:"axle",seat:"seat",contact:"contact",steering:"steering",propulsion:"propulsion",wheelAssembly:"wheel.assembly",wheelPivot:"wheel.pivot",wheelLoadBearing:"wheel.load-bearing",wheelTire:"wheel.tire",wheelRim:"wheel.rim",wheelHub:"wheel.hub",wheelContact:"wheel.contact",steeringPivot:"steering.pivot",roof:"roof",architectureRoof:"architecture.roof",collider:"collider",colliderBox:"collider.box",colliderCapsule:"collider.capsule",colliderHull:"collider.hull",anchor:"anchor",kitModule:"kit.module",kitPort:"kit.port",lodImpostor:"lod.impostor"})});function jM(){return new eS().registerExtensions([...BS,ab])}var fn="MSFT_lod",VM,ab;var If=ht(()=>{qo();hf();VM=class VM extends nt{static EXTENSION_NAME=fn;init(){this.extensionName=fn,this.propertyType="Lod",this.parentTypes=[Q.NODE,Q.MATERIAL]}getDefaults(){return Object.assign(super.getDefaults(),{levels:new xn})}addLevel(e){return this.addRef("levels",e)}listLevels(){return this.listRefs("levels")}removeLevel(e){return this.removeRef("levels",e)}};ab=class ab extends _t{extensionName=fn;static EXTENSION_NAME=fn;createLod(e=""){return new VM(this.document.getGraph(),e)}read(e){let t=e.jsonDoc.json;return this.readLevels(t.nodes,e.nodes),this.readLevels(t.materials,e.materials),this}readLevels(e,t){(e??[]).forEach((n,i)=>{let r=n.extensions?.[fn]?.ids,s=t[i];if(!s||!Array.isArray(r))return;let a=this.createLod();for(let o of r){let c=typeof o==="number"?t[o]:void 0;if(c&&c!==s)a.addLevel(c)}s.setExtension(fn,a)})}write(e){let t=e.jsonDoc.json,n=this.document.getRoot();for(let i of n.listNodes()){let r=e.nodeIndexMap.get(i),s=i.getExtension(fn)?.listLevels().filter((o)=>o.propertyType===Q.NODE).map((o)=>e.nodeIndexMap.get(o)).filter((o)=>o!==void 0),a=r===void 0?void 0:t.nodes?.[r];if(a&&s?.length)a.extensions={...a.extensions,[fn]:{ids:s}}}for(let i of n.listMaterials()){let r=e.materialIndexMap.get(i),s=i.getExtension(fn)?.listLevels().filter((o)=>o.propertyType===Q.MATERIAL).map((o)=>e.materialIndexMap.get(o)).filter((o)=>o!==void 0),a=r===void 0?void 0:t.materials?.[r];if(a&&s?.length)a.extensions={...a.extensions,[fn]:{ids:s}}}return this}}});var Y9;var ob=ht(()=>{Y9=Object.freeze([1,1,1])});var nW,iW;var HM=ht(()=>{ob();nW=Object.freeze({units:"m",forward:"+X",up:"+Y",right:"+Z",groundY:0}),iW=Math.PI/180});var GM=()=>{};var $M=()=>{};var KM=ht(()=>{HM();ob();GM();$M();Nl()});var Q9;var WM=ht(()=>{Q9=Object.freeze({parametricSamples:262144,subdivisionTriangles:1e6,subdivisionAttributeBytes:134217728,subdivisionIterations:10,repeatedMeshes:1e4,curveRepeatVertices:262144,primitiveSegments:4096,primitiveGridVertices:262144,unwrapVertices:65536,unwrapTriangles:1e6,unwrapAttributeBytes:134217728,unwrapResolution:4096,skinBones:1024,skinVertices:262144,skinAttributeBytes:134217728,colliderHullVertices:65536,surfaceBakeVertices:262144,surfaceBakeTriangles:1e6,surfaceBakeRays:8388608,surfaceBakeRayDirections:256})});var cb="kilnRepeatInstances";var lb=ht(()=>{KM();Ac();WM()});function Pl(e){return e.getExtension("KHR_node_visibility")?.getVisible?.()===!1}var vW;var Ol=ht(()=>{vW=[{grade:"A",max:1,range:"0-1"},{grade:"B",max:3,range:"2-3"},{grade:"C",max:6,range:"4-6"},{grade:"D",max:12,range:"7-12"},{grade:"F",max:Number.POSITIVE_INFINITY,range:"13+"}]});var XM=ht(()=>{Ol()});function JM(e){let t=new Map,n=e.getRoot().getDefaultScene()??e.getRoot().listScenes()[0];if(!n)return t;let i=(r,s)=>{let a=new Map;for(let o of r){let c=o.getName(),l=a.get(c)??0;a.set(c,l+1);let u=`${s}${qM(c,l)}`;t.set(o,u),i(o.listChildren(),u)}};return i(n.listChildren(),qM(n.getName()||"Scene",0)),t}var qM=(e,t)=>`/${encodeURIComponent(e)}[${t}]`;var ZM=ht(()=>{If();Nl();lb();Ol();XM()});function nB(e,t,n){let i=0;for(let r=0;r<t;r++)if(e[r].getName()===n)i++;return i}function iB(e){let t=e.getExtras()[ub];return Array.isArray(t)&&t.every((n)=>typeof n==="number")?[...t]:void 0}function rB(e){let t=e.getRoot().getDefaultScene()??e.getRoot().listScenes()[0];if(!t)return[];let n=[],i=(r,s)=>{r.forEach((a,o)=>{let c=(d)=>`${s}${YM(d,nB(r,o,d))}`,l=c(a.getName()),u=(a.getExtension(fn)?.listLevels()??[]).filter((d)=>d.propertyType===Q.NODE);if(u.length>0)n.push({levels:[a,...u],paths:[l,...u.map((d)=>c(d.getName()))]});i(a.listChildren(),l)})};return i(t.listChildren(),YM(t.getName()||"Scene",0)),n}function QM(e,t){let n=rB(e),i=new Set;for(let{levels:a}of n)for(let o of a.slice(t+1))o.traverse((c)=>{i.add(c)});for(let a of e.getRoot().listAnimations())for(let o of a.listChannels()){let c=o.getTargetNode();if(c&&i.has(c))throw Error(`maxLod ${t} would drop ${c.getName()||"a node"}, which animation ${JSON.stringify(a.getName())} targets; keep that level.`)}let r=n.map(({levels:a,paths:o})=>{let[c,...l]=a,u=l.slice(t);if(u.length>0){let d=c.getExtension(fn);for(let b of u)d.removeLevel(b);let f={...c.getExtras()},h=iB(c);if(t===0)c.setExtension(fn,null),d.dispose(),delete f[ub];else if(h)f[ub]=h.slice(0,t+1);c.setExtras(f);for(let b of u){let m=[];b.traverse((g)=>{m.push(g)});for(let g of m.reverse())g.dispose()}}return{path:o[0],levels:a.length-u.length,dropped:u.map((d)=>d.getName())}}),s=e.getRoot();if(!s.listNodes().some((a)=>a.getExtension(fn)))s.listExtensionsUsed().find((a)=>a.extensionName===fn)?.dispose();return r}var ub="MSFT_screencoverage",YM=(e,t)=>`/${encodeURIComponent(e)}[${t}]`;var eR=ht(()=>{qo();Nl();If();Ol()});var Cf="kilnBudgetV1";var tR=ht(()=>{Ac()});var nR=()=>{};function Ht(e){throw TypeError(`atlas provenance: ${e}`)}function Ki(e,t){if(!e||typeof e!=="object"||Array.isArray(e))Ht("plain metadata object required.");let n=Object.getPrototypeOf(e);if(n!==null&&n!==Object.prototype)Ht("plain metadata prototype required.");let i=Object.getOwnPropertyDescriptor(e,t);if(!i)return;if(!i.enumerable||!("value"in i))Ht("metadata accessors/hidden fields are unsupported.");return i.value}function kl(e,t){for(let n of Reflect.ownKeys(e))if(typeof n!=="string"||!t.includes(n))Ht("unsupported metadata field.");for(let n of t)Ki(e,n);return e}function aB(e){Rn(e);let t=kl(e,["spec","manifest"]),n=pa(t.spec);return{spec:n,manifest:Cc(t.manifest,n)}}function oB(e){let t=kl(e,["version","atlases"]);if(t.version!==Qo)Ht("unsupported version.");let n=t.atlases;if(!Array.isArray(n)||Object.getPrototypeOf(n)!==Array.prototype)Ht("dense atlas array required.");let i=Object.getOwnPropertyDescriptor(n,"length").value;if(i>Ua.atlases||Reflect.ownKeys(n).length!==i+1)Ht("atlas count/density budget exceeded.");let r=sB,s=[];for(let a=0;a<i;a++){let o=Object.getOwnPropertyDescriptor(n,String(a));if(!o?.enumerable||!("value"in o))Ht("atlas array accessors are unsupported.");let c=Rn(o.value);if(r+=new TextEncoder().encode(c).length+(a>0?1:0),r>Ua.bytes)Ht("aggregate metadata byte budget exceeded.");s.push(kl(o.value,["id","spec","manifest"]))}return s}function cB(e){let t=oB(e),n=new Set,i=[];for(let r of t){let s=aB({spec:r.spec,manifest:r.manifest});if(r.id!==s.manifest.manifestHash||n.has(r.id))Ht("duplicate or mismatched atlas identity.");n.add(r.id),i.push({id:r.id,...s})}return{version:Qo,atlases:i}}function iR(e,t){let n=e.atlases.find((i)=>i.id===t);if(!n)Ht("unknown atlas reference.");return n}function lB(e,t,n,i){if(!["top-left","bottom-left"].includes(n)||!["content-boundary","texel-center"].includes(i))Ht("explicit binding origin/mode required.");let r=e.manifest.regions.find((d)=>d.name===t);if(!r)Ht("unknown named region.");let{x:s,y:a,width:o,height:c}=r.content,l=i==="texel-center",u=n==="bottom-left";return{manifestHash:e.manifest.manifestHash,specHash:e.manifest.specHash,layoutHash:e.manifest.layoutHash,region:r.name,content:structuredClone(r.content),allocation:structuredClone(r.allocation),inputOrigin:n,mode:i,scale:[(o-(l?1:0))/e.manifest.width,(u?-1:1)*(c-(l?1:0))/e.manifest.height],offset:[(s+(l?0.5:0))/e.manifest.width,(a+(u?c-(l?0.5:0):l?0.5:0))/e.manifest.height]}}function uB(e,t){Rn(e);let n=kl(e,["version","atlasId","region","inputOrigin","mode"]);if(n.version!==Qo)Ht("unsupported binding version.");return lB(iR(t,n.atlasId),n.region,n.inputOrigin,n.mode)}function dB(e){let t=e.getRoot().getDefaultScene()??e.getRoot().listScenes()[0];return t?Ki(t.getExtras(),"kilnAtlasProvenance"):void 0}function rR(e){let t=dB(e);return t===void 0?void 0:cB(t)}function sR(e){let t=[];for(let n of e.getRoot().listMaterials())for(let[i,r]of[[n.getBaseColorTexture(),n.getBaseColorTextureInfo()],[n.getNormalTexture(),n.getNormalTextureInfo()],[n.getMetallicRoughnessTexture(),n.getMetallicRoughnessTextureInfo()],[n.getEmissiveTexture(),n.getEmissiveTextureInfo()],[n.getOcclusionTexture(),n.getOcclusionTextureInfo()]])if(i&&r&&Ki(r.getExtras(),"kilnAtlasReference")!==void 0){if(t.length>=Ua.bindings)Ht("document binding budget exceeded.");t.push({texture:i,info:r})}return t}async function aR(e){let t=e.getImage();if(!t||t.byteLength>Ua.encodedBytes)Ht("encoded image missing or over budget.");let n=await crypto.subtle.digest("SHA-256",t);return`sha256:${[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join("")}`}function oR(e){let t={minFilter:e.getMinFilter(),magFilter:e.getMagFilter(),wrapS:e.getWrapS(),wrapT:e.getWrapT()};if(![null,9728,9729,9984,9985,9986,9987].includes(t.minFilter)||![null,9728,9729].includes(t.magFilter)||![33071,33648,10497].includes(t.wrapS)||![33071,33648,10497].includes(t.wrapT))Ht("unsupported effective sampler.");return t}function cR(e,t){Rn(e);let n=kl(e,["version","id","effectiveSampler","finalMime","finalImageSha256"]);if(n.version!==Qo)Ht("unsupported texture reference version.");return iR(t,n.id),n}function lR(e){let t=new Set,n=0;for(let{texture:i}of e){if(t.has(i))continue;t.add(i);let r=i.getImage();if(!r||r.byteLength>Ua.encodedBytes)Ht("encoded image missing or over budget.");if(n+=r.byteLength,n>Ua.aggregateEncodedBytes)Ht("aggregate encoded image hash budget exceeded.")}}async function uR(e){let t=rR(e),n=sR(e);if(!n.length)return;if(!t)Ht("atlas table missing.");lR(n);let i=new Map;for(let{texture:r,info:s}of n){let a=cR(Ki(s.getExtras(),"kilnAtlasReference"),t),o=i.get(r);if(!o)o=await aR(r),i.set(r,o);s.setExtras({...s.getExtras(),kilnAtlasReference:{version:Qo,id:a.id,effectiveSampler:oR(s),finalMime:r.getMimeType(),finalImageSha256:o}})}}async function dR(e){let t=rR(e),n=sR(e);if(n.length&&!t)Ht("atlas table missing.");if(!t){for(let s of e.getRoot().listMeshes())for(let a of s.listPrimitives())if(Ki(a.getExtras(),"kilnAtlasBinding")!==void 0)Ht("atlas table missing.");return}lR(n);let i=new Map;for(let{texture:s,info:a}of n){let o=cR(Ki(a.getExtras(),"kilnAtlasReference"),t),c=i.get(s);if(!c)c=await aR(s),i.set(s,c);if(o.finalImageSha256!==c||o.finalMime!==s.getMimeType()||Rn(o.effectiveSampler)!==Rn(oR(a)))Ht("final image or effective sampler identity mismatch.")}let r=0;for(let s of e.getRoot().listMeshes())for(let a of s.listPrimitives()){let o=Ki(a.getExtras(),"kilnAtlasBinding");if(o!==void 0){if(++r>Ua.bindings)Ht("primitive budget exceeded.");uB(o,t);let c=a.getMaterial(),l=Ki(o,"atlasId");if(!(c?[c.getBaseColorTextureInfo(),c.getNormalTextureInfo(),c.getMetallicRoughnessTextureInfo(),c.getEmissiveTextureInfo(),c.getOcclusionTextureInfo()]:[]).some((d)=>d&&Ki(d.getExtras(),"kilnAtlasReference")!==void 0&&Ki(Ki(d.getExtras(),"kilnAtlasReference"),"id")===l))Ht("named binding has no matching material atlas reference.")}}}var Qo="kiln.atlas-provenance.v1",sB,Ua;var fR=ht(()=>{nR();Fu();sB=new TextEncoder().encode(JSON.stringify({version:Qo,atlases:[]})).length,Ua=Object.freeze({atlases:128,bytes:4194304,bindings:1024,entryBytes:262144,encodedBytes:16777216,aggregateEncodedBytes:67108864,bakeDecodedBytes:67108864})});var gR={};Lb(gR,{deliverRuntimeThreeGlb:()=>EB});function pB(e,t){let n=(i)=>{if(!i)return-1;if(!t.has(i))t.set(i,t.size);return t.get(i)};return e.listPrimitives().map((i)=>`${i.getMode()}:${n(i.getMaterial())}:${n(i.getIndices())}:${i.listSemantics().sort().map((r)=>`${r}=${n(i.getAttribute(r))}`).join(",")}:${i.listTargets().length}`).join("|")}function mB(e){let t=[],n=new Map,i=e.getRoot().listNodes().filter((s)=>s.getExtras()[cb]!==void 0),r;for(let s of i){let a=new Map;for(let l of s.listChildren()){let u=l.getMesh();if(!u||l.listChildren().length||l.getSkin()||l.listExtensions().length||Pl(l)||Dl(l).length||Object.keys(l.getExtras()).length||l.getWeights().length)continue;let d=pB(u,n);a.set(d,[...a.get(d)??[],l])}let o=0;for(let l of a.values()){if(l.length<2)continue;let u=l[0].getMesh();r??=e.createExtension(ff).setRequired(!0);let d=e.getRoot().listBuffers()[0],f=(_,y)=>e.createAccessor().setType(_).setArray(new Float32Array(y)).setBuffer(d??null),h=[],b=[],m=[];for(let _ of l)h.push(..._.getTranslation()),b.push(..._.getRotation()),m.push(..._.getScale());let g=r.createInstancedMesh().setAttribute("TRANSLATION",f("VEC3",h)).setAttribute("ROTATION",f("VEC4",b)).setAttribute("SCALE",f("VEC3",m)),p=`${s.getName()||"Node"}_Instances${o?`_${o}`:""}`;o++;let x=e.createNode(p).setMesh(u).setExtension("EXT_mesh_gpu_instancing",g);s.addChild(x),t.push({node:x,mesh:u.getName(),count:l.length,instances:l.map((_)=>_.getName())});for(let _ of l){let y=_.getMesh();if(_.dispose(),y&&y!==u&&!y.listParents().some((v)=>v.propertyType===Q.NODE))y.dispose()}}let c={...s.getExtras()};delete c[cb],s.setExtras(c)}return t}function gB(e){let t=[];for(let n of e.getRoot().listNodes()){let i=n.getMesh();if(!i||!mR(n))continue;let r=e.createNode(`${n.getName()}_Proxy`).setMesh(i);n.setMesh(null).addChild(r),t.push({collider:n,proxy:r})}return t}async function bB(e,t,n){let i=e.getRoot().listTextures().filter((o)=>o.getMimeType()!=="image/ktx2"&&o.getImage());if(!t)return{status:"skipped",textures:i.length,reason:"No KTX2 encoder was supplied; textures stay PNG or JPEG."};let r=new Map,s=(o,c)=>{if(o)r.set(o,(r.get(o)??new Set).add(c))};for(let o of e.getRoot().listMaterials())s(o.getBaseColorTexture(),"baseColor"),s(o.getEmissiveTexture(),"emissive"),s(o.getNormalTexture(),"normal"),s(o.getMetallicRoughnessTexture(),"metallicRoughness"),s(o.getOcclusionTexture(),"occlusion");let a=["baseColor","emissive","normal","metallicRoughness","occlusion"];for(let o of i){let c=r.get(o)??new Set,l=c.has("baseColor")||c.has("emissive"),u=o.listParents().some((m)=>m.propertyType!==Q.ROOT&&!xB(m)),d=[...c].some((m)=>m!=="baseColor"&&m!=="emissive")||u;if(l&&d)throw Error(`Texture ${JSON.stringify(o.getName())} is used by both sRGB and linear material slots; one KTX2 encoding cannot serve both. Use separate images.`);let f=o.getImage(),h=await t({image:f,mimeType:o.getMimeType(),name:o.getName(),colorSpace:l?"srgb":"linear",slot:a.find((m)=>c.has(m))??"other"});if(!(h instanceof Uint8Array)||!Ng(h))throw Error("ktx2Encoder must return KTX2 bytes starting with the KTX2 identifier");n.set(o,`sha256:${await Al(f)}`),o.setImage(h).setMimeType("image/ktx2");let b=o.getURI();if(b)o.setURI(b.replace(/\.(png|jpe?g)$/i,".ktx2"))}if(i.length){e.createExtension(Xg).setRequired(!0);await Promise.resolve().then(() => fR());await uR(e),await dR(e)}return{status:"encoded",textures:i.length,...t.identity?{encoder:structuredClone(t.identity)}:{}}}function xB(e){return e.propertyType===Q.MATERIAL}function pR(e,t){let n=new Je().fromArray(e).invert().multiply(new Je().fromArray(t)),i=new j,r=new ln,s=new j;return n.decompose(i,r,s),{scale:s.x,offset:[i.x,i.y,i.z]}}function yB(e){let t=(n,i)=>{if(i.getComponentSize()>=4)return!1;if(n==="POSITION"||n==="NORMAL"||n==="TANGENT")return!0;if(!n.startsWith("TEXCOORD_"))return!1;let r=i.getComponentType();return!(i.getNormalized()&&(r===Oe.ComponentType.UNSIGNED_BYTE||r===Oe.ComponentType.UNSIGNED_SHORT))};return e.getRoot().listMeshes().flatMap((n)=>n.listPrimitives()).flatMap((n)=>[n,...n.listTargets()]).some((n)=>n.listSemantics().some((i)=>t(i,n.getAttribute(i))))}function _B(e,t){let n=2**(t-1)-1,i=new Map;for(let c of e.getRoot().listNodes())for(let l of c.getExtension(fn)?.listLevels()??[])if(l.propertyType===Q.NODE)i.set(l,c);let r=(c)=>{let l=new Je().fromArray(c.getWorldMatrix()),u=c;while(u.getParentNode())u=u.getParentNode();let d=i.get(u)?.getParentNode();return d?new Je().fromArray(d.getWorldMatrix()).multiply(l):l},s=(c)=>{let l=[1/0,1/0,1/0],u=[-1/0,-1/0,-1/0],d=(f,h)=>{for(let b=0;b<3;b++){let m=f[b],g=h?[m,m*2,0]:[m];l[b]=Math.min(l[b],...g),u[b]=Math.max(u[b],...g)}};for(let f of c.listPrimitives()){let h=f.getAttribute("POSITION");if(h)d(h.getMin([]),!1),d(h.getMax([]),!1);for(let b of f.listTargets()){let m=b.getAttribute("POSITION");if(m)d(m.getMin([]),!0),d(m.getMax([]),!0)}}return Math.max(...[0,1,2].map((f)=>(u[f]-l[f])/2))},a=(c)=>{let l=c.getExtension("EXT_mesh_gpu_instancing")?.getAttribute("SCALE");if(!l)return 1;let u=0;for(let d=0;d<l.getCount();d++)u=Math.max(u,...l.getElement(d,[]).map(Math.abs));return u},o=[];for(let c of e.getRoot().listNodes()){let l=c.getMesh();if(!l?.listPrimitives().some((d)=>d.getAttribute("POSITION")))continue;let u=c.getSkin()?1:r(c).getMaxScaleOnAxis()*a(c);o.push({node:c,mesh:l.getName(),step:s(l)*u/n})}return o}async function vB(e,t){let n=QM(e,t),i=[];if(n.some((r)=>r.dropped.length>0)){await e.transform(Sf({propertyTypes:[Q.MESH,Q.PRIMITIVE,Q.PRIMITIVE_TARGET,Q.ACCESSOR,Q.MATERIAL,Q.TEXTURE],keepAttributes:!0,keepIndices:!0,keepLeaves:!0,keepExtras:!0,keepSolidTextures:!0}));let r=e.getRoot().getDefaultScene()??e.getRoot().listScenes()[0],s={...r?.getExtras()??{}},a=s[Cf];if(r&&a?.triangles){let o={...a.triangles};for(let c of Object.keys(o))if(Number(c.slice(3))>t)i.push(c),delete o[c];if(Object.keys(o).length>0)s[Cf]={...a,triangles:o};else delete s[Cf];r.setExtras(s)}}return{maxLod:t,chains:n,budgetTiersOmitted:i}}async function EB(e,t,n={},i={}){let r=n.compression??"meshopt";if(r!=="meshopt"&&r!=="none")throw Error("Runtime three compression must be meshopt or none");let{maxLod:s}=n;if(s!==void 0&&!(Number.isSafeInteger(s)&&s>=0))throw Error("Runtime three maxLod must be a non-negative integer");let a=n.positionBits??_r.position;if(a!=="float"&&!(Number.isSafeInteger(a)&&a>=8&&a<=16))throw Error("Runtime three positionBits must be an integer from 8 to 16, or float");let o=jM().registerDependencies({"meshopt.encoder":t}),c=await o.readBinary(e);c.setLogger(new La(La.Verbosity.SILENT));let l=s===void 0?void 0:await vB(c,s);await c.transform(sb({propertyTypes:[Q.ACCESSOR],keepUniqueNames:!0}));let u=mB(c),d=gB(c),f=new Map;for(let R of c.getRoot().listNodes())if(R.getMesh())f.set(R,[...R.getMatrix()]);let h=a==="float"?[]:_B(c,a),b=a==="float"?hB:fB;if(await c.transform(FM({encoder:t,target:"size"}),DM({pattern:b,patternTargets:b,quantizationVolume:"mesh",quantizePosition:a==="float"?_r.position:a,quantizeNormal:_r.normal,quantizeTexcoord:_r.texcoord,quantizeColor:_r.color,quantizeWeight:_r.weight})),a==="float"&&yB(c))c.createExtension(Il).setRequired(!0);if(r==="meshopt")c.createExtension(Rl).setRequired(!0).setEncoderOptions({method:Rl.EncoderMethod.QUANTIZE});let m=new Map,g=await bB(c,n.ktx2Encoder,m);for(let R of c.getRoot().listNodes()){if(!R.getMesh()||f.has(R)||R.getName())continue;let C=R.getParentNode();R.setName(`${C?.getName()||"Node"}_Mesh`)}let p=JM(c),x=(R)=>p.get(R)??`#${encodeURIComponent(R.getName())}`,_=new Set(d.map((R)=>R.proxy)),y=[];for(let R of c.getRoot().listNodes()){let k=R.getMesh();if(!k||R.getExtension("EXT_mesh_gpu_instancing"))continue;let C=p.get(R);if(C===void 0)continue;let U=f.get(R),L=U===void 0,O=L||_.has(R),K=L?new Je().identity().toArray():U,B=[...R.getMatrix()],{scale:X,offset:q}=pR(K,B);if(!L&&Math.abs(X-1)<0.000000000001&&q.every((de)=>de===0))continue;let le=R.getParentNode();y.push({node:C,mesh:k.getName(),meshMovedToChild:O,...O&&le?{authoredNode:x(le)}:{},dequantization:{scale:X,offset:q},localScale:[...R.getScale()]})}for(let R of c.getRoot().listNodes()){let k=R.getMesh();if(!k||p.has(R)||!f.has(R))continue;let{scale:C,offset:U}=pR(f.get(R),[...R.getMatrix()]);y.push({node:`#lod/${encodeURIComponent(R.getName())}`,mesh:k.getName(),meshMovedToChild:!1,dequantization:{scale:C,offset:U},localScale:[...R.getScale()]})}let v=new Map;for(let R of c.getRoot().listMeshes())for(let k of R.listPrimitives())for(let C of k.listSemantics())if(C.startsWith("_"))v.set(C,(v.get(C)??new Set).add(R));let E=c.getRoot().listNodes(),w=await o.writeBinary(c),T=(await o.binaryToJSON(w)).json,A=new Map;c.getRoot().listTextures().forEach((R,k)=>{let C=m.get(R);if(C)A.set(k,C)});let P=i.gltfBasename?await o.writeJSON(c,{format:Gw.GLTF,basename:i.gltfBasename}):void 0,S={target:"three",extensionsUsed:[...T.extensionsUsed??[]].sort(),extensionsRequired:[...T.extensionsRequired??[]].sort(),compression:r==="meshopt"?{extension:"EXT_meshopt_compression",method:"quantize"}:{extension:"none"},quantization:{extension:"KHR_mesh_quantization",volume:"mesh",bits:{position:a==="float"?"float32":a,normal:_r.normal,texcoord:_r.texcoord,color:_r.color,weight:_r.weight},customAttributes:"float32",positionSteps:h.map(({node:R,mesh:k,step:C})=>({node:p.get(R)??`#lod/${encodeURIComponent(R.getName())}`,mesh:k,step:C})),maxPositionStep:Math.max(0,...h.map(({step:R})=>R))},nodeScale:y,colliderProxies:d.map(({collider:R,proxy:k})=>({collider:x(R),proxy:x(k)})),customAttributes:[...v].sort(([R],[k])=>hR(R)-hR(k)||(R<k?-1:R>k?1:0)).map(([R,k])=>({name:R,meshes:k.size,componentType:"FLOAT",normalized:!1})),instancing:u.map(({node:R,...k})=>({node:x(R),...k})),ktx2:g,...l?{lod:l}:{},preserved:{lodChains:E.filter((R)=>R.getExtension(fn)).length,hiddenNodes:E.filter((R)=>Pl(R)).length,colliders:E.filter(mR).length,anchors:E.filter((R)=>Dl(R).some((k)=>k.startsWith(`${Zs.anchor}.`))).length,ports:E.filter((R)=>Dl(R).some((k)=>k.startsWith(`${Zs.kitPort}.`))).length,kitModules:E.filter((R)=>Dl(R).includes(Zs.kitModule)).length}};return{glb:w,delivery:S,imageSources:A,...P?{gltf:{json:P.json,resources:P.resources}}:{}}}var _r,fB,hB,hR=(e)=>e==="_EDGE"?0:e==="_CAVITY"?1:2,Dl=(e)=>Rf(e.getExtras())?.roles??[],mR=(e)=>Dl(e).some((t)=>t.startsWith(`${Zs.collider}.`));var bR=ht(()=>{qo();hf();UM();ji();Nl();If();ZM();lb();Ol();Pg();eR();tR();_r=Object.freeze({volume:"mesh",position:14,normal:10,texcoord:12,color:8,weight:8}),fB=/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/,hB=/^(NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/});var TB;var xR=ht(()=>{TB=function(){var e="b9H79Tebbbe9ok9Geueu9Geub9Gbb9Gruuuuuuueu9Gvuuuuueu9Gduueu9Gluuuueu9Gvuuuuub9Gouuuuuub9Gluuuub9GiuuueuiE8AdilveoveovrrwrrrDDoDrbqqbelve9Weiiviebeoweuecj:Gdkr:PlCo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8F9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWV9mW4W2be8A9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWVbd8F9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWV9c9V919U9KbiE9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949wWV79P9V9UblY9TW79O9V9Wt9FW9U9J9V9KW69U9KW949c919M9MWVbv8E9TW79O9V9Wt9FW9U9J9V9KW69U9KW949c919M9MWV9c9V919U9Kbo8A9TW79O9V9Wt9FW9U9J9V9KW69U9KW949wWV79P9V9UbrE9TW79O9V9Wt9FW9U9J9V9KW69U9KW949tWG91W9U9JWbwa9TW79O9V9Wt9FW9U9J9V9KW69U9KW949tWG91W9U9JW9c9V919U9KbDL9TW79O9V9Wt9FW9U9J9V9KWS9P2tWV9p9JtbqK9TW79O9V9Wt9FW9U9J9V9KWS9P2tWV9r919HtbkL9TW79O9V9Wt9FW9U9J9V9KWS9P2tWVT949WbxY9TW79O9V9Wt9FW9U9J9V9KWS9P2tWVJ9V29VVbmE9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94J9H9J9OWbza9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94J9H9J9OW9ttV9P9WbHa9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94SWt9J9O9sW9T9H9WbOK9TW79O9V9Wt9F79W9Ht9P9H29t9VVt9sW9T9H9WbAl79IV9RbXDwebcekdKYq:8f8Adbk;wadhud9:8Jjjjjbc;qw9Rgr8KjjjjbcbhwdnaeTmbabcbyd;i:I:cjbaoaocb9iEgDc:GeV86bbarc;adfcbcjdz:xjjjb8AdnaiTmbarc;adfadalz:wjjjb8Akarc;abfalfcbcbcjdal9RalcFe0Ez:xjjjb8Aarc;abfarc;adfalz:wjjjb8Aar9cb83iUar9cb83i8War9cb83iyar9cb83iaar9cb83iKar9cb83izar9cb83iwar9cb83ibcj;abal9Uc;WFbGcjdalca0Ehqdnaicd6mbavcd9imbaDTmbadcefhkaqci2gxal2hmarc;alfclfhParc;qlfceVhsarc;qofclVhzcbhHincdhOcbhAdnavci6mbar9cb83i;Ooar9cb83i;Goar9cb83i;yoar9cb83i;qoadaHfgoybbhCcbhXincbhwcbhQdninaoalfhLaoybbgKaC7aQVhQawcP0meaLhoaKhCawcefgwaXfai6mbkkcbhCarc;qofhwincwhYcwh8AdnaQaC93gocFeGgEcs0mbclh8AaEci0mbcdcbaEEh8Akdnaocw4cFeGgEcs0mbclhYaEci0mbcdcbaEEhYkaYa8AfhEawydbh3cwhYcwh8Adnaocz4cFeGg5cs0mbclh8Aa5ci0mbcdcba5Eh8AkaEa3fhEdnaocFFFFb0mbclhYaocFFF8F0mbcbcdaocjjjw6EhYkawaEa8AfaYfBdbawclfhwaCcefgCcw9hmbkaLhoaKhCaXczfgXai6mbkcbhocehwazhQinawaoaQydbarc;qofaocdtfydb6EhoaQclfhQawcefgwcw9hmbkaoclthAcihOkcbhEarc;qlfcbcjdz:xjjjb8AarcbBd;ilar9cb83i;aladh8Eaqh8Fakh3inarc;qlfadaEaEcb9h9Ral2falz:wjjjb8Aaia8Faia8F6EhadnaqaiaE9RaEaqfai6EgKcsfc9WGgoaK9nmbarc;qofaKfcbaoaK9Rz:xjjjb8AkadaEal2fhhcbhginagaAVcl4hXarc;alfagcdtfh8JaHh8Kcbh8Lina8LaHfhwdndndndndndndnagPlbedibkaKTmvahawfhoarc;qlfawfRbbhQarc;qofhwaahCinawaoRbbgYaQ9RgQcetaQcKtc8F91786bbawcefhwaoalfhoaYhQaEaCcufgC9hmbxvkkaKTmla8Kc9:Ghoa8LcitcwGh8Aarc;qlfawceVfRbbcwtarc;qlfawc9:GfRbbVhQarc;qofhwaahCinawa3aofRbbcwta8EaofRbbVgYaQ9RgQcetaQcztc8F917cFFiGa8A486bbaoalfhoawcefhwaYhQaEaCcufgC9hmbxlkkasa8Kc98GgQfhoa3aQfhYarc;qlfawc98GgQfRbbhCcwhwinaoRbbawtaCVhCaocefhoawcwfgwca9hmbxdkkaKTmdxekaKTmea8Lcith5ahaQfh8AcbhLina8ARbbhQcwhoaYhwinawRbbaotaQVhQawcefhwaocwfgoca9hmbkarc;qofaLfaQaC7aX93a5486bbaYalfhYa8Aalfh8AaQhCaLcefgLaK9hmbkka8Jydbh8AcbhLarc;qofhoincdhQcbhwinaQaoawfRbbcb9hfhQawcefgwcz9hmbkclhCcbhwinaCaoawfRbbcd0fhCawcefgwcz9hmbkcwhYcbhwinaYaoawfRbbcP0fhYawcefgwcz9hmbkaQaCaQaC6EgwaYawaY6Egwczawcz6Ea8Afh8AaoczfhoaLczfgLaK6mbka8Ja8ABdbka8Kcefh8Ka8Lcefg8Lcl9hmbkagcefggaO9hmbka8Eamfh8Ea8Faxfh8Fa3amfh3aEaxfgEai6mbkcbhocehwaPhQinawaoaQydbarc;alfaocdtfydb6EhoaQclfhQaOawcefgw9hmbkaraHcd4faAcdVaoaocdSE86bbaHclfgHal6mbkkabaefhgabcefhoalcd4g8McbaDEhkadcefh8Narc;abfceVhecbhmdndninaiam9nmearc;qofcbcjdz:xjjjb8Aagao9Rak6mdadamal2gwfhxcbhHa8Nawfhzaocbakz:xjjjbg8Fakfh3aqaiam9Ramaqfai6Egscsfgocl4cifcd4hOaoc9WGg8JThPindndndndndndndndndndnaDTmbaraHcd4fRbbgQciGPlbedlbkasTmdaxaHfhoarc;abfaHfRbbhQarc;qofhwashCinawaoRbbgYaQ9RgQcetaQcKtc8F91786bbawcefhwaoalfhoaYhQaCcufgCmbxikkasTmiaHcitcwGh8Aarc;abfaHceVfRbbcwtarc;abfaHc9:GgofRbbVhQaxaofhoarc;qofhwashCinawao8VbbgYaQ9RgQcetaQcztc8F917cFFiGa8A486bbawcefhwaoalfhoaYhQaCcufgCmbxikkaeaHc98Gg8Afhoaza8AfhYarc;abfa8AfRbbhCcwhwinaoRbbawtaCVhCaocefhoawcwfgwca9hmbkasTmdaQcl4hKaHcitcKGhEaxa8Afh8AcbhLina8ARbbhQcwhoaYhwinawRbbaotaQVhQawcefhwaocwfgoca9hmbkarc;qofaLfaQaC7aK93aE486bbaYalfhYa8Aalfh8AaQhCaLcefgLas9hmbkkaDmbcbhoxlka8JTmbcbhodninarc;qofaofgwcwf8Pibaw8Pib:e9qTmeaoczfgoa8J9pmdxbkkdnavmbcehoxikcbh8AaOhLaOhKinarc;qofa8Afgocwf8Pibhyao8Pibh8PcdhQcbhwinaQaoawfRbbcb9hfhQawcefgwcz9hmbkclhCcbhwinaCaoawfRbbcd0fhCawcefgwcz9hmbkcwhYcbhwinaYaoawfRbbcP0fhYawcefgwcz9hmbkaQaCaQaC6EgoaYaoaY6Egoczaocz6EaKfhKaocucbaya8P:e9cb9sEgwaoaw6EaLfhLa8Aczfg8Aa8J9pmdxbkka8FaHcd4fgoaoRbbcdaHcetcoGtV86bbxikdnaLas6mbaKas6mba8FaHcd4fgoaoRbbciaHcetcoGtV86bbaga39Ras6mra3arc;qofasz:wjjjbasfh3xikaLaK9phoka8FaHcd4fgwawRbbaoaHcetcoGtV86bbkaga39RaO6mla3cbaOz:xjjjbgaaOfhKdndna8JmbaPhoxekdnagaK9RcK9pmbaPhoxekaocdtc:q:G:cjbfcj:G:cjbaDEg3ydxghcetc;:FFFeGhAcuhEcuahtcu7cFeGh8Ecbh8Karc;qofhQinarc;qofa8KfhXczh8AdndndnahPDbeeeeeeedekcucbaXcwf8PibaX8Pib:e9cb9sEh8AxekcbhoaAh8Aina8Aa8EaQaofRbb9nfh8Aaocefgocz9hmbkkcih5cbhYinczhwdndndna3aYcdtfydbgLPDbeeeeeeedekcucbaXcwf8PibaX8Pib:e9cb9sEhwxekaLcetc;:FFFeGhwcuaLtcu7cFeGhCcbhoinawaCaQaofRbb9nfhwaocefgocz9hmbkkdndnawa8A6mbaLaE9hmeawa8A9hmea3a5cdtfydbcwSmekaYh5awh8AkaYcefgYci9hmbkaaa8Kco4fgoaoRbba5a8Kci4coGtV86bbdndndna3a5cdtfydbgEPDdbbbbbbbebkdncwaE9Tg5TmbcuaEtcu7hwdndnaEceSmbcbh8LaQhXinaXhoa5hYcbhCinaoRbbg8AawcFeGgLa8AaL6EaCaEtVhCaocefhoaYcufgYmbkaKaC86bbaXa5fhXaKcefhKa8La5fg8Lcz6mbxdkkcbh8LaQhXinaXhoa5hYcbhCinaoRbbg8AawcFeGgLa8AaL6EaCcetVhCaocefhoaYcufgYmbkaKaC:T9cFe:d9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:9ca188bbaXa5fhXaKcefhKa8La5fg8Lcz6mbkkcbhoinaKaQaofRbbgC86bbaKaCawcFeG9pfhKaocefgocz9hmbxikkdnaEceSmbinaKcb86bbaKcefhKxbkkinaKcb86bbaKcefhKxbkkaKaX8Pbw83bwaKaX8Pbb83bbaKczfhKka8Kczfg8Ka8J9pgomeaQczfhQagaK9RcK9pmbkkaoTmlaKh3aKTmlkaHcefgHal9hmbkarc;abfaxascufal2falz:wjjjb8Aasamfhma3hoa3mbkcbhwxdkdnagao9RakalfgwcKcaaDEgQawaQ0EgC9pmbcbhwxdkdnawaQ9pmbaocbaCaw9Rgwz:xjjjbawfhokaoarc;adfalz:wjjjbalfhodnaDTmbaoara8Mz:wjjjba8Mfhokaoab9Rhwxekcbhwkarc;qwf8Kjjjjbawk5babaeadaialcdcbyd;i:I:cjbz:bjjjbk9reduaecd4gdaefgicaaica0Eabcj;abae9Uc;WFbGcjdaeca0Egifcufai9Uae2aiadfaicl4cifcd4f2fcefkmbcbabBd;i:I:cjbk;HPeLu8Jjjjjbc;ae9Rgl8Kjjjjbcbhvdnaeaici9UgocHf6mbabcbyd;m:I:cjbgrc;GeV86bbalc;abfcFecjez:xjjjb8Aal9cu83iUal9cu83i8Wal9cu83iyal9cu83iaal9cu83iKal9cu83izal9cu83iwal9cu83ibabaefc9WfhwabcefgDaofhednaiTmbcmcsarcb9kgqEhkcbhxcbhmcbhPcbhscbhzindnaeaw9nmbcbhvxikazcufhvadaPcdtfgHydbhOaHcwfydbhAaHclfydbhCcbhXdndndninalc;abfavcsGcitfgoydlhQdndndnaoydbgoaO9hmbaQaCSmekdnaoaC9hmbaQaA9hmbaXcefhXxekaoaA9hmeaQaO9hmeaXcdfhXkaXc870mdascufhvaHaXcdtgAcxGgoyd:4:G:cjbcdtfydbhQaHaoyd:0:G:cjbcdtfydbhCaHaoyd:W:G:cjbcdtfydbhOcbhodnindnalavcsGcdtfydbaQ9hmbaohXxdkcuhXavcufhvaocefgocz9hmbkkaxaQaxSgvaXce9iaXak9oVgoGfhxdndndncbcsavEaXaoEgvcs9hmbarce9imbaQaQamaQcefamSgvEgmcefSmecmcsavEhvkaDavaAc;WeGV86bbavcs9hmeaQam9Rgvcetavc8F917hvinaecbcjeavcje6EavcFbGV86bbaecefheavcr4gvmbkaQhmxvkcPhvaDaAcPV86bbaQhmkavTmiavak9omicdhocehXazhAxlkavcufhvaXclfgXc;ab9hmbkkdnaHcecdcbaAaxSEaCaxSEcdtgvyd:W:G:cjbcdtfydbgOTaHavyd:0:G:cjbcdtfydbgCceSGaHavyd:4:G:cjbcdtfydbgQcdSGaxcb9hGaqGgLce9hmbal9cu83iUal9cu83i8Wal9cu83iyal9cu83iaal9cu83iKal9cu83izal9cu83iwal9cu83ibcbhxkcbhXascufgvhodnindnalaocsGcdtfydbaC9hmbaXhAxdkcuhAaocufhoaXcefgXcz9hmbkkcbhodnindnalavcsGcdtfydbaQ9hmbaohXxdkcuhXavcufhvaocefgocz9hmbkkaxaOaxSgKfhHdndnaAcm0mbaAcefhAxekcbcsaCaHSgvEhAaHavfhHkdndnaXcm0mbaXcefhXxekcbcsaQaHSgvEhXaHavfhHkc9:cuaKEhYcbhvaXaAcltVg8AcFeGhodndndninavc;q:G:cjbfRbbaoSmeavcefgvcz9hmbxdkkaLaOax9havcm0VVmbaDavc;WeV86bbxekaDaY86bbaea8A86bbaecefhekdnaKmbaOam9Rgvcetavc8F917hvinaecbcjeavcje6EavcFbGV86bbaecefheavcr4gvmbkaOhmkdnaAcs9hmbaCam9Rgvcetavc8F917hvinaecbcjeavcje6EavcFbGV86bbaecefheavcr4gvmbkaChmkdnaXcs9hmbaQam9Rgvcetavc8F917hvinaecbcjeavcje6EavcFbGV86bbaecefheavcr4gvmbkaQhmkalascdtfaOBdbascefcsGhvdndnaAPzbeeeeeeeeeeeeeebekalavcdtfaCBdbascdfcsGhvkdndnaXPzbeeeeeeeeeeeeeebekalavcdtfaQBdbavcefcsGhvkcihoalc;abfazcitfgXaOBdlaXaCBdbazcefcsGhAcdhXavhsaHhxxekcdhoalascdtfaQBdbcehXascefcsGhsazhAkalc;abfaAcitfgvaCBdlavaQBdbalc;abfazaXfcsGcitfgvaQBdlavaOBdbaDcefhDazaofcsGhzaPcifgPai6mbkkdnaeaw9nmbcbhvxekcbhvinaeavfavc;q:G:cjbfRbb86bbavcefgvcz9hmbkaeab9Ravfhvkalc;aef8KjjjjbavkZeeucbhddninadcefgdc8F0meaeceadt0mbkkadcrfcFeGcr9Uci2cdfabci9U2cHfkmbcbabBd;m:I:cjbk:zderu8Jjjjjbcz9Rhlcbhvdnaeaicvf6mbabcbRb;m:I:cjbc;qeV86bbal9cb83iwabcefhvabaefc98fhodnaiTmbcbhecbhrcbhwindnavao6mbcbskadawcdtfydbgDalcwfaraDae9Rgeaec8F91ge7ae9Rc507grcdtfgqydb9Rgec8E91c9:Gaecdt7arVheinavcbcjeaecje6EaecFbGV86bbavcefhvaecr4gembkaqaDBdbaDheawcefgwai9hmbkkdnavao9nmbcbskavcbBbbavab9RclfhvkavkBeeucbhddninadcefgdc8F0meaeceadt0mbkkabadcwfcFeGcr9U2cvfk:dvli99dui99ludnaeTmbcuadcetcuftcu7:Zhvdndncuaicuftcu7:ZgoJbbbZMgr:lJbbb9p9DTmbar:Ohwxekcjjjj94hwkcbhicbhDinalclfIdbgrJbbbbJbbjZalIdbgq:lar:lMalcwfIdbgk:lMgr:varJbbbb9BEgrNhxaqarNhralcxfIdbhqdndnakJbbbb9GTmbaxhkxekJbbjZar:l:tgkak:maxJbbbb9GEhkJbbjZax:l:tgxax:marJbbbb9GEhrkdndnaqJbbj:;aqJbbj:;9GEgxJbbjZaxJbbjZ9FEavNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohmxekcjjjj94hmkdndnakJbbj:;akJbbj:;9GEgqJbbjZaqJbbjZ9FEaoNJbbbZJbbb:;akJbbbb9GEMgq:lJbbb9p9DTmbaq:OhPxekcjjjj94hPkdndnarJbbj:;arJbbj:;9GEgqJbbjZaqJbbjZ9FEaoNJbbbZJbbb:;arJbbbb9GEMgr:lJbbb9p9DTmbar:Ohsxekcjjjj94hskdndnadcl9hmbabaDfgzas86bbazcifam86bbazcdfaw86bbazcefaP86bbxekabaifgzas87ebazcofam87ebazclfaw87ebazcdfaP87ebkaicwfhiaDclfhDalczfhlaecufgembkkk;hlld99eud99eudnaeTmbdndncuaicuftcu7:ZgvJbbbZMgo:lJbbb9p9DTmbao:Ohixekcjjjj94hikaic;8FiGhrinabcofcicdalclfIdb:lalIdb:l9EgialcwfIdb:lalaicdtfIdb:l9EEgialcxfIdb:lalaicdtfIdb:l9EEgiarV87ebdndnJbbj:;JbbjZalaicdtfIdbJbbbb9DEgoalaicd7cdtfIdbJ;Zl:1ZNNgwJbbj:;awJbbj:;9GEgDJbbjZaDJbbjZ9FEavNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohqxekcjjjj94hqkabcdfaq87ebdndnalaicefciGcdtfIdbJ;Zl:1ZNaoNgwJbbj:;awJbbj:;9GEgDJbbjZaDJbbjZ9FEavNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohqxekcjjjj94hqkabaq87ebdndnaoalaicufciGcdtfIdbJ;Zl:1ZNNgoJbbj:;aoJbbj:;9GEgwJbbjZawJbbjZ9FEavNJbbbZJbbb:;aoJbbbb9GEMgo:lJbbb9p9DTmbao:Ohixekcjjjj94hikabclfai87ebabcwfhbalczfhlaecufgembkkk;Pviwue99eu8Jjjjjbcjd9Rgo8Kjjjjbadcd4hrdndndnavcd9hmbarTmbaohdarhwinadc:CuBdbadclfhdawcufgwmbkaeTmdarcdthDalhqcbhkinaohdaqhwarhxinadadydbgmcbawIdbgP:8cL4cFeGc:cufaPJbbbb9BEgsamas9kEBdbawclfhwadclfhdaxcufgxmbkaqaDfhqakcefgkae9hmbxdkkaeTmekarcdthqavce9hhDcbhkindndndnaDmbarTmdc:CuhwalhdarhxinawcbadIdbgP:8cL4cFeGc:cufaPJbbbb9BEgmawam9kEhwadclfhdaxcufgxmbxdkkdndndndnavPleddbdkarTmlaohdalhwarhxinadcbcbawIdbgP:8cL4cFeGgmc:cufgsasam0EaPJbbbb9BEBdbadclfhdawclfhwaxcufgxmbxikkarTmicbhdarhwinaoadfcbaladfIdbgP:8cL4cFeGgxc8Aaxc8A0Ec:cufaPJbbbb9BEBdbadclfhdawcufgwmbxdkkarTmdkc:CuhwkcbhdarhminawhxdnavceSmbaoadfydbhxkdndnaladfIdbgPcjjj;8iaxai9RcefgxcLt9R::NJbbbZJbbb:;aPJbbbb9GEMgP:lJbbb9p9DTmbaP:Ohsxekcjjjj94hskabadfascFFFrGaxcKtVBdbadclfhdamcufgmmbkkabaqfhbalaqfhlakcefgkae9hmbkkaocjdf8Kjjjjbk:Olveue99iue99iudnaeTmbceaicufthvcuaitcu7:Zhocbhradcl9hhwcbhDindndnalcwfIdbgqJbbbbaqJbbbb9GEgqJbbjZaqJbbjZ9FEaoNJbbbZMgq:lJbbb9p9DTmbaq:Ohixekcjjjj94hikdndnalIdbgqJbbbbaqJbbbb9GEgqJbbjZaqJbbjZ9FEaoNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkadai9Rcd9TgkaifhidndnalclfIdbgqJbbbbaqJbbbb9GEgqJbbjZaqJbbjZ9FEaoNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkadai9Rcd9ThddndnalcxfIdbgqJbbbbaqJbbbb9GEgqJbbjZaqJbbjZ9FEaoNJbbbZMgq:lJbbb9p9DTmbaq:Ohxxekcjjjj94hxkadaifhiaxce91avVhxdndnawmbabaDfgmai86bbamcifax86bbamcdfad86bbamcefak86bbxekabarfgmai87ebamcofax87ebamclfad87ebamcdfak87ebkarcwfhraDclfhDalczfhlaecufgembkkk;mqdQui998Jjjjjbc:qd9Rgv8Kjjjjbavc:Sefcbc;Kbz:xjjjb8AdnadTmbaiTmbdndnabaeSmbaehoxekavcuadcdtgradcFFFFi0Ecbyd;q:I:cjbHjjjjbbgoBd:SeavceBd:mdaoaearz:wjjjb8AkavcbBd:Oeav9cb83i:Geavc:Gefaoadaiavc:Sefz:pjjjbavyd:Gehwadci9UgDcbyd;q:I:cjbHjjjjbbheavc:Sefavyd:mdgqcdtfaeBdbavaqcefgrBd:mdaecbaDz:xjjjbhkavc:SefarcdtfcuaicdtaicFFFFi0Ecbyd;q:I:cjbHjjjjbbgxBdbavaqcdfgmBd:mdalc;ebfhPawheaxhrinaralIdbaPaeydbgscwascw6EcdtfIdbMUdbaeclfhearclfhraicufgimbkavc:SefamcdtfcuaDcdtadcFFFF970Ecbyd;q:I:cjbHjjjjbbgmBdbdnadci6mbaoheamhraDhiinaraxaeydbcdtfIdbaxaeclfydbcdtfIdbMaxaecwfydbcdtfIdbMUdbaecxfhearclfhraicufgimbkkaqcifhzalc;ebfhHavc;qbfhOavheavyd:KehAavyd:OehCcbhscbhrcbhXcehQinaehLaoarcx2fgKydbhPaKclfydbhdabaXcx2fgecwfaKcwfydbgYBdbaeclfadBdbaeaPBdbakarfce86bbaOaYBdwaOadBdlaOaPBdbamarcdtfcbBdbcih8AdnasTmbaLhiinaOa8AcdtfaiydbgeBdba8AaeaY9haeaP9haead9hGGfh8AaiclfhiascufgsmbkkaXcefhXcbhsinaCaAaKascdtfydbcdtgifydbcdtfgYheawaifgdydbgPhidnaPTmbdninaeydbarSmeaeclfheaicufgiTmdxbkkaeaYaPcdtfc98fydbBdbadadydbcufBdbkascefgsci9hmbkdndndna8ATmbcuhrJbbbbhEcbhdavyd:KehYavyd:OehKindnawaOadcdtfydbcdtgsfydbgeTmbaxasfgiIdbh3aialcuadadcs0EcdtfclfIdbaHaecwaecw6EcdtfIdbMg5Udba5a3:th5aecdthiaKaYasfydbcdtfheinamaeydbgscdtfgPa5aPIdbMg3Udba3aEaEa39DgPEhEasaraPEhraeclfheaic98fgimbkkadcefgda8A9hmbkarcu9hmekaQaD9pmeindnakaQfRbbmbaQhrxdkaDaQcefgQ9hmbxdkka8Acza8Acz6EhsaOheaLhOarcu9hmekkazTmbaqcdtavc:Seffcwfheinaeydbcbyd;u:I:cjbH:bjjjbbaec98fheazcufgzmbkkavc:qdf8Kjjjjbk:0leoucuaicdtgvaicFFFFi0Egocbyd;q:I:cjbHjjjjbbhralalyd9GgwcdtfarBdbalawcefBd9GabarBdbaocbyd;q:I:cjbHjjjjbbhralalyd9GgocdtfarBdbalaocefBd9GabarBdlcuadcdtadcFFFFi0Ecbyd;q:I:cjbHjjjjbbhralalyd9GgocdtfarBdbalaocefBd9GabarBdwabydbcbavz:xjjjb8AabydbhraehladhvinaralydbcdtfgoaoydbcefBdbalclfhlavcufgvmbkcbhvabydlglhoarhwaihDinaoavBdbaoclfhoawydbavfhvawclfhwaDcufgDmbkadci9Uhqdnadcd9nmbabydwhocbhvinaecwfydbhwaeclfydbhDalaeydbcdtfgbabydbgbcefBdbaoabcdtfavBdbalaDcdtfgDaDydbgDcefBdbaoaDcdtfavBdbalawcdtfgwawydbgwcefBdbaoawcdtfavBdbaecxfheaqavcefgv9hmbkkinalalydbarydb9RBdbarclfhralclfhlaicufgimbkkQbabaeadaic;G:G:cjbz:ojjjbkQbabaeadaic;i:H:cjbz:ojjjbk9DeeuabcFeaicdtz:xjjjbhlcbhbdnadTmbindnalaeydbcdtfgiydbcu9hmbaiabBdbabcefhbkaeclfheadcufgdmbkkabk:3vioud9:du8Jjjjjbc;Wa9Rgl8Kjjjjbcbhvalcxfcbc;Kbz:xjjjb8AalcuadcitgoadcFFFFe0Ecbyd;q:I:cjbHjjjjbbgrBdxalceBd2araeadaicezNjjjbalcuaoadcjjjjoGEcbyd;q:I:cjbHjjjjbbgwBdzadcdthednadTmbabhiinaiavBdbaiclfhiadavcefgv9hmbkkawaefhDalabBdwalawBdl9cbhqindnadTmbaq9cq9:hkarhvaDhiadheinaiav8Pibak1:NcFrG87ebavcwfhvaicdfhiaecufgembkkalclfaq:NceGcdtfydbhxalclfaq9ce98gq:NceGcdtfydbhmalc;Wbfcbcjaz:xjjjb8AaDhvadhidnadTmbinalc;Wbfav8VebcdtfgeaeydbcefBdbavcdfhvaicufgimbkkcbhvcbhiinalc;WbfavfgeydbhoaeaiBdbaoaifhiavclfgvcja9hmbkadhvdndnadTmbinalc;WbfaDamydbgicetf8VebcdtfgeaeydbgecefBdbaxaecdtfaiBdbamclfhmavcufgvmbkaq9cv9smdcbhvinabawydbcdtfavBdbawclfhwadavcefgv9hmbxdkkaq9cv9smekkcwhvcbhiinalcxfavfc98fydbcbyd;u:I:cjbH:bjjjbbaiceGheclhvcehiaeTmbkalc;Waf8Kjjjjbk:Awliuo99iud9:cbhv8Jjjjjbca9Rgocbyd:4:I:cjbBdKaocb8Pd:W:I:cjb83izaocbyd;e:I:cjbBdwaocb8Pd:8:I:cjb83ibaicd4hrdndnadmbJFFuFhwJFFuuhDJFFuuhqJFFuFhkJFFuuhxJFFuFhmxekarcdthPaehsincbhiinaoczfaifgzasaifIdbgwazIdbgDaDaw9EEUdbaoaifgzawazIdbgDaDaw9DEUdbaiclfgicx9hmbkasaPfhsavcefgvad9hmbkaoIdKhDaoIdwhwaoIdChqaoIdlhkaoIdzhxaoIdbhmkdnadTmbJbbbbJbFu9hJbbbbamax:tgmamJbbbb9DEgmakaq:tgkakam9DEgkawaD:tgwawak9DEgw:vawJbbbb9BEhwdnalmbarcdthoindndnaeclfIdbaq:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikai:S9cC:ghHdndnaeIdbax:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikaHai:S:ehHdndnaecwfIdbaD:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabaHai:T9cy:g:e83ibaeaofheabcwfhbadcufgdmbxdkkarcdthoindndnaeIdbax:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikai:SgH9ca:gaH9cz:g9cjjj;4s:d:eaH9cFe:d:e9cF:bj;4:pj;ar:d9c:bd9:9c:p;G:d;4j:E;ar:d9cH9:9c;d;H:W:y:m:g;d;Hb:d9cv9:9c;j:KM;j:KM;j:Kd:dhOdndnaeclfIdbaq:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikai:SgH9ca:gaH9cz:g9cjjj;4s:d:eaH9cFe:d:e9cF:bj;4:pj;ar:d9c:bd9:9c:p;G:d;4j:E;ar:d9cH9:9c;d;H:W:y:m:g;d;Hb:d9cq9:9cM;j:KM;j:KM;jl:daO:ehOdndnaecwfIdbaD:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabaOai:SgH9ca:gaH9cz:g9cjjj;4s:d:eaH9cFe:d:e9cF:bj;4:pj;ar:d9c:bd9:9c:p;G:d;4j:E;ar:d9cH9:9c;d;H:W:y:m:g;d;Hb:d9cC9:9c:KM;j:KM;j:KMD:d:e83ibaeaofheabcwfhbadcufgdmbkkk9teiucbcbyd;y:I:cjbgeabcifc98GfgbBd;y:I:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabk9teiucbcbyd;y:I:cjbgeabcrfc94GfgbBd;y:I:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikTeeucbabcbyd;y:I:cjbge9Rcifc98GaefgbBd;y:I:cjbdnabZbcztge9nmbabae9RcFFifcz4nb8Akkk;Sddbcj:Gdk;idbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbbbbbbbbbbbbbbbbebbbdbbbbbbbebbbbbbbbbbbbbbbb4:h9w9N94:P:gW:j9O:ye9Pbbbbbb:l29hZ;69:9kZ;N;76Z;rg97Z;z;o9xZ8J;B85Z;:;u9yZ;b;k9HZ:2;Z9DZ9e:l9mZ59A8KZ:r;T3Z:A:zYZ79OHZ;j4::8::Y:D9V8:bbbb9s:49:Z8R:hBZ9M9M;M8:L;z;o8:;8:PG89q;x:J878R:hQ8::M:B;e87bbbbbbjZbbjZbbjZ:E;V;N8::Y:DsZ9i;H;68:xd;R8:;h0838:;W:NoZbbbb:WV9O8:uf888:9i;H;68:9c9G;L89;n;m9m89;D8Ko8:bbbbf:8tZ9m836ZS:2AZL;zPZZ818EZ9e:lxZ;U98F8:819E;68:FFuuFFuuFFuuFFuFFFuFFFuFbc;i:IdkCebbbebbbebbbdbbb9G:rbb",t=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!=="object")return{supported:!1};var n,i=WebAssembly.instantiate(r(e),{}).then(function(h){n=h.instance,n.exports.__wasm_call_ctors(),n.exports.meshopt_encodeVertexVersion(1),n.exports.meshopt_encodeIndexVersion(1)});function r(h){var b=new Uint8Array(h.length);for(var m=0;m<h.length;++m){var g=h.charCodeAt(m);b[m]=g>96?g-97:g>64?g-39:g+4}var p=0;for(var m=0;m<h.length;++m)b[p++]=b[m]<60?t[b[m]]:(b[m]-60)*64+b[++m];return b.buffer.slice(0,p)}function s(h){if(!h)throw Error("Assertion failed")}function a(h){return new Uint8Array(h.buffer,h.byteOffset,h.byteLength)}function o(h,b,m,g){var p=n.exports.sbrk,x=p(b.length*4),_=p(m*4),y=new Uint8Array(n.exports.memory.buffer),v=a(b);if(y.set(v,x),g)g(x,x,b.length,m);var E=h(_,x,b.length,m);y=new Uint8Array(n.exports.memory.buffer);var w=new Uint32Array(m);new Uint8Array(w.buffer).set(y.subarray(_,_+m*4)),v.set(y.subarray(x,x+b.length*4)),p(x-p(0));for(var T=0;T<b.length;++T)b[T]=w[b[T]];return[w,E]}function c(h,b,m,g){var p=n.exports.sbrk,x=p(m*4),_=p(m*g),y=new Uint8Array(n.exports.memory.buffer);y.set(a(b),_),h(x,_,m,g),y=new Uint8Array(n.exports.memory.buffer);var v=new Uint32Array(m);return new Uint8Array(v.buffer).set(y.subarray(x,x+m*4)),p(x-p(0)),v}function l(h,b,m,g,p,x,_){var y=n.exports.sbrk,v=y(b),E=y(g*p),w=new Uint8Array(n.exports.memory.buffer);w.set(a(m),E);var T=h(v,b,E,g,p,x,_),A=new Uint8Array(T);return A.set(w.subarray(v,v+T)),y(v-y(0)),A}function u(h){var b=0;for(var m=0;m<h.length;++m){var g=h[m];b=b<g?g:b}return b}function d(h,b){if(s(b==2||b==4),b==4)return new Uint32Array(h.buffer,h.byteOffset,h.byteLength/4);else{var m=new Uint16Array(h.buffer,h.byteOffset,h.byteLength/2);return new Uint32Array(m)}}function f(h,b,m,g,p,x,_){var y=n.exports.sbrk,v=y(m*g),E=y(m*x),w=new Uint8Array(n.exports.memory.buffer);w.set(a(b),E),h(v,m,g,p,E,_);var T=new Uint8Array(m*g);return T.set(w.subarray(v,v+m*g)),y(v-y(0)),T}return{ready:i,supported:!0,reorderMesh:function(h,b,m){s(h instanceof Uint32Array||h instanceof Int32Array),s(!b||h.length%3==0);var g=b?m?n.exports.meshopt_optimizeVertexCacheStrip:n.exports.meshopt_optimizeVertexCache:void 0;return o(n.exports.meshopt_optimizeVertexFetchRemap,h,u(h)+1,g)},reorderPoints:function(h,b){return s(h instanceof Float32Array),s(h.length%b==0),s(b>=3),c(n.exports.meshopt_spatialSortRemap,h,h.length/b,b*4)},encodeVertexBuffer:function(h,b,m){s(m>0&&m<=256),s(m%4==0);var g=n.exports.meshopt_encodeVertexBufferBound(b,m);return l(n.exports.meshopt_encodeVertexBuffer,g,h,b,m)},encodeVertexBufferLevel:function(h,b,m,g,p){s(m>0&&m<=256),s(m%4==0),s(g>=0&&g<=3),s(p===void 0||p==0||p==1);var x=n.exports.meshopt_encodeVertexBufferBound(b,m);return l(n.exports.meshopt_encodeVertexBufferLevel,x,h,b,m,g,p===void 0?-1:p)},encodeIndexBuffer:function(h,b,m){s(m==2||m==4),s(b%3==0);var g=d(h,m),p=n.exports.meshopt_encodeIndexBufferBound(b,u(g)+1);return l(n.exports.meshopt_encodeIndexBuffer,p,g,b,4)},encodeIndexSequence:function(h,b,m){s(m==2||m==4);var g=d(h,m),p=n.exports.meshopt_encodeIndexSequenceBound(b,u(g)+1);return l(n.exports.meshopt_encodeIndexSequence,p,g,b,4)},encodeGltfBuffer:function(h,b,m,g,p){var x={ATTRIBUTES:this.encodeVertexBufferLevel,TRIANGLES:this.encodeIndexBuffer,INDICES:this.encodeIndexSequence};return s(x[g]),x[g](h,b,m,2,p===void 0?0:p)},encodeFilterOct:function(h,b,m,g){return s(m==4||m==8),s(g>=2&&g<=16),f(n.exports.meshopt_encodeFilterOct,h,b,m,g,16)},encodeFilterQuat:function(h,b,m,g){return s(m==8),s(g>=4&&g<=16),f(n.exports.meshopt_encodeFilterQuat,h,b,m,g,16)},encodeFilterExp:function(h,b,m,g,p){s(m>0&&m%4==0),s(g>=1&&g<=24);var x={Separate:0,SharedVector:1,SharedComponent:2,Clamped:3};return s(!p||p in x),f(n.exports.meshopt_encodeFilterExp,h,b,m,g,m,p?x[p]:1)},encodeFilterColor:function(h,b,m,g){return s(m==4||m==8),s(g>=2&&g<=16),f(n.exports.meshopt_encodeFilterColor,h,b,m,g,16)}}}()});var dX;var yR=ht(()=>{dX=function(){var e="b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuixkbeeeddddillviebeoweuecj:Gdkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WboY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbrl79IV9Rbwq:VZkdbk:XYi5ud9:du8Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaicefhxcj;abad9Uc;WFbGcjdadca0EhmaialfgPar9Rgoadfhsavaoadz:jjjjbgzceVhHcbhOdndninaeaO9nmeaPax9RaD6mdamaeaO9RaOamfgoae6EgAcsfglc9WGhCabaOad2fhXaAcethQaxaDfhiaOaeaoaeao6E9RhLalcl4cifcd4hKazcj;cbfaAfhYcbh8AazcjdfhEaHh3incbh5dnawTmbaxa8Acd4fRbbh5kcbh8Eazcj;cbfhqinaih8Fdndndndna5a8Ecet4ciGgoc9:fPdebdkaPa8F9RaA6mrazcj;cbfa8EaA2fa8FaAz:jjjjb8Aa8FaAfhixdkazcj;cbfa8EaA2fcbaAz:kjjjb8Aa8FhixekaPa8F9RaK6mva8FaKfhidnaCTmbaPai9RcK6mbaocdtc:q:G:cjbfcj:G:cjbawEhaczhrcbhlinargoc9Wfghaqfhrdndndndndndnaaa8Fahco4fRbbalcoG4ciGcdtfydbPDbedvivvvlvkar9cb83bwar9cb83bbxlkarcbaiRbdai8Xbb9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbaqaofgrcGfcbaicdfa8J9c8N1:NfghRbbag9cjjjjjw:dg8J9qE86bbarcVfcbaha8J9c8M1:NfghRbbag9cjjjjjl:dg8J9qE86bbarc7fcbaha8J9c8L1:NfghRbbag9cjjjjjd:dg8J9qE86bbarctfcbaha8J9c8K1:NfghRbbag9cjjjjje:dg8J9qE86bbarc91fcbaha8J9c8J1:NfghRbbag9cjjjj;ab:dg8J9qE86bbarc4fcbaha8J9cg1:NfghRbbag9cjjjja:dg8J9qE86bbarc93fcbaha8J9ch1:NfghRbbag9cjjjjz:dgg9qE86bbarc94fcbahag9ca1:NfghRbbai8Xbe9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:gg9cjjjjjz:dg8J9qE86bbarc95fcbaha8J9c8N1:NfgiRbbag9cjjjjjw:dg8J9qE86bbarc96fcbaia8J9c8M1:NfgiRbbag9cjjjjjl:dg8J9qE86bbarc97fcbaia8J9c8L1:NfgiRbbag9cjjjjjd:dg8J9qE86bbarc98fcbaia8J9c8K1:NfgiRbbag9cjjjjje:dg8J9qE86bbarc99fcbaia8J9c8J1:NfgiRbbag9cjjjj;ab:dg8J9qE86bbarc9:fcbaia8J9cg1:NfgiRbbag9cjjjja:dg8J9qE86bbarcufcbaia8J9ch1:NfgiRbbag9cjjjjz:dgg9qE86bbaiag9ca1:NfhixikaraiRblaiRbbghco4g8Ka8KciSg8KE86bbaqaofgrcGfaiclfa8Kfg8KRbbahcl4ciGg8La8LciSg8LE86bbarcVfa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc7fa8Ka8Lfg8KRbbahciGghahciSghE86bbarctfa8Kahfg8KRbbaiRbeghco4g8La8LciSg8LE86bbarc91fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc4fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc93fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc94fa8Kahfg8KRbbaiRbdghco4g8La8LciSg8LE86bbarc95fa8Ka8Lfg8KRbbahcl4ciGg8La8LciSg8LE86bbarc96fa8Ka8Lfg8KRbbahcd4ciGg8La8LciSg8LE86bbarc97fa8Ka8Lfg8KRbbahciGghahciSghE86bbarc98fa8KahfghRbbaiRbigico4g8Ka8KciSg8KE86bbarc99faha8KfghRbbaicl4ciGg8Ka8KciSg8KE86bbarc9:faha8KfghRbbaicd4ciGg8Ka8KciSg8KE86bbarcufaha8KfgrRbbaiciGgiaiciSgiE86bbaraifhixdkaraiRbwaiRbbghcl4g8Ka8KcsSg8KE86bbaqaofgrcGfaicwfa8Kfg8KRbbahcsGghahcsSghE86bbarcVfa8KahfghRbbaiRbeg8Kcl4g8La8LcsSg8LE86bbarc7faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarctfaha8KfghRbbaiRbdg8Kcl4g8La8LcsSg8LE86bbarc91faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc4faha8KfghRbbaiRbig8Kcl4g8La8LcsSg8LE86bbarc93faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc94faha8KfghRbbaiRblg8Kcl4g8La8LcsSg8LE86bbarc95faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc96faha8KfghRbbaiRbvg8Kcl4g8La8LcsSg8LE86bbarc97faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc98faha8KfghRbbaiRbog8Kcl4g8La8LcsSg8LE86bbarc99faha8LfghRbba8KcsGg8Ka8KcsSg8KE86bbarc9:faha8KfghRbbaiRbrgicl4g8Ka8KcsSg8KE86bbarcufaha8KfgrRbbaicsGgiaicsSgiE86bbaraifhixekarai8Pbw83bwarai8Pbb83bbaiczfhikdnaoaC9pmbalcdfhlaoczfhraPai9RcL0mekkaoaC6moaimexokaCmva8FTmvkaqaAfhqa8Ecefg8Ecl9hmbkdndndndnawTmbasa8Acd4fRbbgociGPlbedrbkaATmdaza8Afh8Fazcj;cbfhhcbh8EaEhaina8FRbbhraahocbhlinaoahalfRbbgqce4cbaqceG9R7arfgr86bbaoadfhoaAalcefgl9hmbkaacefhaa8Fcefh8FahaAfhha8Ecefg8Ecl9hmbxikkaATmeaza8Afhaazcj;cbfhhcbhoceh8EaYh8FinaEaofhlaa8Vbbhrcbhoinala8FaofRbbcwtahaofRbbgqVc;:FiGce4cbaqceG9R7arfgr87bbaladfhlaLaocefgofmbka8FaQfh8FcdhoaacdfhaahaQfhha8EceGhlcbh8EalmbxdkkaATmbaocl4h8Eaza8AfRbbhqcwhoa3hlinalRbbaotaqVhqalcefhlaocwfgoca9hmbkcbhhaEh8FaYhainazcj;cbfahfRbbhrcwhoaahlinalRbbaotarVhralaAfhlaocwfgoca9hmbkara8E94aq7hqcbhoa8Fhlinalaqao486bbalcefhlaocwfgoca9hmbka8Fadfh8FaacefhaahcefghaA9hmbkkaEclfhEa3clfh3a8Aclfg8Aad6mbkaXazcjdfaAad2z:jjjjb8AazazcjdfaAcufad2fadz:jjjjb8AaAaOfhOaihxaimbkc9:hoxdkcbc99aPax9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaok:ysezu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnalaeci9UgrcHf6mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:kjjjb8Aav9cu83iUav9cu83i8Wav9cu83iyav9cu83iaav9cu83iKav9cu83izav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbavaiaqaDcsGfRbbgscl4gP9RcsGcdtfydbaxcefgOaPEhDavaias9RcsGcdtfydbaOaPTgzfgOascsGgPEhsaPThPdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiazfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaPfhiaOaPfhxxekaxcbalRbbgsEgHaDc;:eSgDfhOascsGhAdndnascl4gCmbaOcefhzxekaOhzavaiaC9RcsGcdtfydbhOkdndnaAmbazcefhxxekazhxavaias9RcsGcdtfydbhzkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhHascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaHhDxekaDcefhDkasce4cbasceG9R7amfgmhHkdndnaCcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhOaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkaOhsxekascefhskaPce4cbaPceG9R7amfgmhOkdndnaAcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhzaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkazhlxekalcefhlkaPce4cbaPceG9R7amfgmhzkdndnadcd9hmbabarcetfgDaH87ebaDclfaz87ebaDcdfaO87ebxekabarcdtfgDaHBdbaDcwfazBdbaDclfaOBdbkavc;abfaocitfgDaOBdbaDaHBdlavaicdtfaHBdbavc;abfaocefcsGcitfgDazBdbaDaOBdlavaicefgicsGcdtfaOBdbavc;abfaocdfcsGcitfgDaHBdbaDazBdlavaiaCTaCcsSVfgicsGcdtfazBdbaiaATaAcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnalaecvf9pmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk:4ioiue99dud99dud99dnaeTmbcbhiabhlindndnal8Uebgv:YgoJ:ji:1Salcof8UebgrciVgw:Y:vgDNJbbbZJbbb:;avcu9kEMgq:lJbbb9p9DTmbaq:Ohkxekcjjjj94hkkalclf8Uebhvalcdf8UebhxalarcefciGcetfak87ebdndnax:YgqaDNJbbbZJbbb:;axcu9kEMgm:lJbbb9p9DTmbam:Ohxxekcjjjj94hxkabaiarciGgkfcd7cetfax87ebdndnav:YgmaDNJbbbZJbbb:;avcu9kEMgP:lJbbb9p9DTmbaP:Ohvxekcjjjj94hvkalarcufciGcetfav87ebdndnawaw2:ZgPaPMaoaoN:taqaqN:tamamN:tgoJbbbbaoJbbbb9GE:raDNJbbbZMgD:lJbbb9p9DTmbaD:Ohrxekcjjjj94hrkalakcetfar87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2gdTmbinababydbgecwtcw91:Yaece91cjjj98Gcjjj;8if::NUdbabclfhbadcufgdmbkkk:Tvirud99eudndnadcl9hmbaeTmeindndnabRbbgiabcefgl8Sbbgvabcdfgo8Sbbgrf9R:YJbbuJabcifgwRbbgdce4adVgDcd4aDVgDcl4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax86bbdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao86bbdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai86bbdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad86bbabclfhbaecufgembxdkkaeTmbindndnab8Vebgiabcdfgl8Uebgvabclfgo8Uebgrf9R:YJbFu9habcofgw8Vebgdce4adVgDcd4aDVgDcl4aDVgDcw4aDVgD:Z:vgqNJbbbZMgk:lJbbb9p9DTmbak:Ohxxekcjjjj94hxkaoax87ebdndnaraif:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohoxekcjjjj94hokalao87ebdndnavaifar9R:YaqNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabai87ebdndnaDadcetGadceGV:ZaqNJbbbZMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkawad87ebabcwfhbaecufgembkkk9teiucbcbyd:K:G:cjbgeabcifc98GfgbBd:K:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkk83dbcj:Gdk8Kbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbc:K:Gdkl8W:qbb",t="b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuixkbbebeeddddilve9Weeeviebeoweuecj:Gdkr;Neqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949WbwY9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVJ9V29VVbDl79IV9Rbqq:W9Dklbzik94evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaeai86b:q:W:cjbaecitab8Piw83i:q:G:cjbaecefgecjd9hmbkk:JBl8Aud97dur978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnalTmbcuhoaiRbbgrc;WeGc:Ge9hmbarcsGgwce0mbc9:hoalcufadcd4cbawEgDadfgrcKcaawEgqaraq0Egk6mbaialfgxar9RhodnadTgmmbavaoad;8qbbkaicefhPcj;abad9Uc;WFbGcjdadca0EhsdndndnadTmbaoadfhzcbhHinaeaH9nmdaxaP9RaD6miabaHad2fhOaPaDfhAasaeaH9RaHasfae6EgCcsfgocl4cifcd4hXavcj;cbfaoc9WGgQcetfhLavcj;cbfaQci2fhKavcj;cbfaQfhYcbh8Aaoc;ab6hEincbh3dnawTmbaPa8Acd4fRbbh3kcbh5avcj;cbfh8Eindndndndna3a5cet4ciGgoc9:fPdebdkaxaA9RaQ6mwdnaQTmbavcj;cbfa5aQ2faAaQ;8qbbkaAaCfhAxdkaQTmeavcj;cbfa5aQ2fcbaQ;8kbxekaxaA9RaX6moaoclVcbawEhraAaXfhocbhidnaEmbaxao9Rc;Gb6mbcbhlina8EalfhidndndndndndnaAalco4fRbbgqciGarfPDbedibledibkaipxbbbbbbbbbbbbbbbbpklbxlkaiaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaoclffagRb:q:W:cjbfhoxikaiaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaocwffagRb:q:W:cjbfhoxdkaiaopbbbpklbaoczfhoxekaiaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbahaocdffagRb:q:W:cjbfhokdndndndndndnaqcd4ciGarfPDbedibledibkaiczfpxbbbbbbbbbbbbbbbbpklbxlkaiczfaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaoclffagRb:q:W:cjbfhoxikaiczfaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaocwffagRb:q:W:cjbfhoxdkaiczfaopbbbpklbaoczfhoxekaiczfaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbahaocdffagRb:q:W:cjbfhokdndndndndndnaqcl4ciGarfPDbedibledibkaicafpxbbbbbbbbbbbbbbbbpklbxlkaicafaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaoclffagRb:q:W:cjbfhoxikaicafaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbahaocwffagRb:q:W:cjbfhoxdkaicafaopbbbpklbaoczfhoxekaicafaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbahaocdffagRb:q:W:cjbfhokdndndndndndnaqco4arfPDbedibledibkaic8Wfpxbbbbbbbbbbbbbbbbpklbxlkaic8Wfaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Ngicitpbi:q:G:cjbaiRb:q:W:cjbgipsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbaiaoclffaqRb:q:W:cjbfhoxikaic8Wfaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Ngicitpbi:q:G:cjbaiRb:q:W:cjbgipsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Ngqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spklbaiaocwffaqRb:q:W:cjbfhoxdkaic8Wfaopbbbpklbaoczfhoxekaic8WfaopbbdaoRbbgicitpbi:q:G:cjbaiRb:q:W:cjbgipsaoRbegqcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpklbaiaocdffaqRb:q:W:cjbfhokalc;abfhialcjefaQ0meaihlaxao9Rc;Fb0mbkkdnaiaQ9pmbaici4hlinaxao9RcK6mwa8EaifhqdndndndndndnaAaico4fRbbalcoG4ciGarfPDbedibledibkaqpxbbbbbbbbbbbbbbbbpkbbxlkaqaopbblaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLg8Fcdp:mea8FpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogapxiiiiiiiiiiiiiiiip8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spkbbahaoclffagRb:q:W:cjbfhoxikaqaopbbwaopbbbg8Fclp:mea8FpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogapxssssssssssssssssp8Jg8Fp5b9cjF;8;4;W;G;ab9:9cU1:Nghcitpbi:q:G:cjbahRb:q:W:cjbghpsa8Fp5e9cjF;8;4;W;G;ab9:9cU1:Nggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPaaa8Fp9spkbbahaocwffagRb:q:W:cjbfhoxdkaqaopbbbpkbbaoczfhoxekaqaopbbdaoRbbghcitpbi:q:G:cjbahRb:q:W:cjbghpsaoRbeggcitpbi:q:G:cjbp9UpmbedilvorzHOACXQLpPpkbbahaocdffagRb:q:W:cjbfhokalcdfhlaiczfgiaQ6mbkkaohAaoTmoka8EaQfh8Ea5cefg5cl9hmbkdndndndnawTmbaza8Acd4fRbbglciGPlbedwbkaQTmdavcjdfa8Afhlava8Afpbdbh8Jcbhoinalavcj;cbfaofpblbg8KaYaofpblbg8LpmbzeHdOiAlCvXoQrLg8MaLaofpblbg8NaKaofpblbgypmbzeHdOiAlCvXoQrLg8PpmbezHdiOAlvCXorQLg8Fcep9Ta8Fpxeeeeeeeeeeeeeeeegap9op9Hp9rg8Fa8Jp9Ug8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9Abbbaladfgla8Ja8Ma8PpmwDKYqk8AExm35Ps8E8Fg8Fcep9Ta8Faap9op9Hp9rg8Fp9Ug8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9Abbbaladfgla8Ja8Ka8LpmwKDYq8AkEx3m5P8Es8Fg8Ka8NaypmwKDYq8AkEx3m5P8Es8Fg8LpmbezHdiOAlvCXorQLg8Fcep9Ta8Faap9op9Hp9rg8Fp9Ug8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp9Ug8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9Abbbaladfgla8Ja8Ka8LpmwDKYqk8AExm35Ps8E8Fg8Fcep9Ta8Faap9op9Hp9rg8Fp9Ugap9Abbbaladfglaaa8Fa8Fpmlvorlvorlvorlvorp9Ugap9Abbbaladfglaaa8Fa8FpmwDqkwDqkwDqkwDqkp9Ugap9Abbbaladfglaaa8Fa8FpmxmPsxmPsxmPsxmPsp9Ug8Jp9AbbbaladfhlaoczfgoaQ6mbxikkaQTmeavcjdfa8Afhlava8Afpbdbh8Jcbhoinalavcj;cbfaofpblbg8KaYaofpblbg8LpmbzeHdOiAlCvXoQrLg8MaLaofpblbg8NaKaofpblbgypmbzeHdOiAlCvXoQrLg8PpmbezHdiOAlvCXorQLg8Fcep:nea8Fpxebebebebebebebebgap9op:bep9rg8Fa8Jp:oeg8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9Abbbaladfgla8Ja8Ma8PpmwDKYqk8AExm35Ps8E8Fg8Fcep:nea8Faap9op:bep9rg8Fp:oeg8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9Abbbaladfgla8Ja8Ka8LpmwKDYq8AkEx3m5P8Es8Fg8Ka8NaypmwKDYq8AkEx3m5P8Es8Fg8LpmbezHdiOAlvCXorQLg8Fcep:nea8Faap9op:bep9rg8Fp:oeg8Jp9Abbbaladfgla8Ja8Fa8Fpmlvorlvorlvorlvorp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmwDqkwDqkwDqkwDqkp:oeg8Jp9Abbbaladfgla8Ja8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9Abbbaladfgla8Ja8Ka8LpmwDKYqk8AExm35Ps8E8Fg8Fcep:nea8Faap9op:bep9rg8Fp:oegap9Abbbaladfglaaa8Fa8Fpmlvorlvorlvorlvorp:oegap9Abbbaladfglaaa8Fa8FpmwDqkwDqkwDqkwDqkp:oegap9Abbbaladfglaaa8Fa8FpmxmPsxmPsxmPsxmPsp:oeg8Jp9AbbbaladfhlaoczfgoaQ6mbxdkkaQTmbcbhocbalcl4gl9Rc8FGhiavcjdfa8Afhrava8Afpbdbhainaravcj;cbfaofpblbg8JaYaofpblbg8KpmbzeHdOiAlCvXoQrLg8LaLaofpblbg8MaKaofpblbg8NpmbzeHdOiAlCvXoQrLgypmbezHdiOAlvCXorQLg8Faip:Rea8Falp:Tep9qg8Faap9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9Abbbaradfgraaa8LaypmwDKYqk8AExm35Ps8E8Fg8Faip:Rea8Falp:Tep9qg8Fp9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9Abbbaradfgraaa8Ja8KpmwKDYq8AkEx3m5P8Es8Fg8Ja8Ma8NpmwKDYq8AkEx3m5P8Es8Fg8KpmbezHdiOAlvCXorQLg8Faip:Rea8Falp:Tep9qg8Fp9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9Abbbaradfgraaa8Ja8KpmwDKYqk8AExm35Ps8E8Fg8Faip:Rea8Falp:Tep9qg8Fp9rgap9Abbbaradfgraaa8Fa8Fpmlvorlvorlvorlvorp9rgap9Abbbaradfgraaa8Fa8FpmwDqkwDqkwDqkwDqkp9rgap9Abbbaradfgraaa8Fa8FpmxmPsxmPsxmPsxmPsp9rgap9AbbbaradfhraoczfgoaQ6mbkka8Aclfg8Aad6mbkdnaCad2goTmbaOavcjdfao;8qbbkdnammbavavcjdfaCcufad2fad;8qbbkaCaHfhHc9:hoaAhPaAmbxlkkaeTmbaDalfhrcbhocuhlinaralaD9RglfaD6mdasaeao9Raoasfae6Eaofgoae6mbkaial9RhPkcbc99axaP9RakSEhoxekc9:hokavcj;kbf8Kjjjjbaokwbz:bjjjbkNsezu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnalaeci9UgrcHf6mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbav9cu83iUav9cu83i8Wav9cu83iyav9cu83iaav9cu83iKav9cu83izav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhldnaeTmbcmcsaDceSEhkcbhxcbhmcbhrcbhicbhoindnalaq9nmbc9:hoxikdndnawRbbgDc;Ve0mbavc;abfaoaDcu7gPcl4fcsGcitfgsydlhzasydbhHdndnaDcsGgsak9pmbavaiaPfcsGcdtfydbaxasEhDaxasTgOfhxxekdndnascsSmbcehOasc987asamffcefhDxekalcefhDal8SbbgscFeGhPdndnascu9mmbaDhlxekalcvfhlaPcFbGhPcrhsdninaD8SbbgOcFbGastaPVhPaOcu9kmeaDcefhDascrfgsc8J9hmbxdkkaDcefhlkcehOaPce4cbaPceG9R7amfhDkaDhmkavc;abfaocitfgsaDBdbasazBdlavaicdtfaDBdbavc;abfaocefcsGcitfgsaHBdbasaDBdlaocdfhoaOaifhidnadcd9hmbabarcetfgsaH87ebasclfaD87ebascdfaz87ebxdkabarcdtfgsaHBdbascwfaDBdbasclfazBdbxekdnaDcpe0mbavaiaqaDcsGfRbbgscl4gP9RcsGcdtfydbaxcefgOaPEhDavaias9RcsGcdtfydbaOaPTgzfgOascsGgPEhsaPThPdndnadcd9hmbabarcetfgHax87ebaHclfas87ebaHcdfaD87ebxekabarcdtfgHaxBdbaHcwfasBdbaHclfaDBdbkavaicdtfaxBdbavc;abfaocitfgHaDBdbaHaxBdlavaicefgicsGcdtfaDBdbavc;abfaocefcsGcitfgHasBdbaHaDBdlavaiazfgicsGcdtfasBdbavc;abfaocdfcsGcitfgDaxBdbaDasBdlaocifhoaiaPfhiaOaPfhxxekaxcbalRbbgsEgHaDc;:eSgDfhOascsGhAdndnascl4gCmbaOcefhzxekaOhzavaiaC9RcsGcdtfydbhOkdndnaAmbazcefhxxekazhxavaias9RcsGcdtfydbhzkdndnaDTmbalcefhDxekalcdfhDal8SbegPcFeGhsdnaPcu9kmbalcofhHascFbGhscrhldninaD8SbbgPcFbGaltasVhsaPcu9kmeaDcefhDalcrfglc8J9hmbkaHhDxekaDcefhDkasce4cbasceG9R7amfgmhHkdndnaCcsSmbaDhsxekaDcefhsaD8SbbglcFeGhPdnalcu9kmbaDcvfhOaPcFbGhPcrhldninas8SbbgDcFbGaltaPVhPaDcu9kmeascefhsalcrfglc8J9hmbkaOhsxekascefhskaPce4cbaPceG9R7amfgmhOkdndnaAcsSmbashlxekascefhlas8SbbgDcFeGhPdnaDcu9kmbascvfhzaPcFbGhPcrhDdninal8SbbgscFbGaDtaPVhPascu9kmealcefhlaDcrfgDc8J9hmbkazhlxekalcefhlkaPce4cbaPceG9R7amfgmhzkdndnadcd9hmbabarcetfgDaH87ebaDclfaz87ebaDcdfaO87ebxekabarcdtfgDaHBdbaDcwfazBdbaDclfaOBdbkavc;abfaocitfgDaOBdbaDaHBdlavaicdtfaHBdbavc;abfaocefcsGcitfgDazBdbaDaOBdlavaicefgicsGcdtfaOBdbavc;abfaocdfcsGcitfgDaHBdbaDazBdlavaiaCTaCcsSVfgicsGcdtfazBdbaiaATaAcsSVfhiaocifhokawcefhwaocsGhoaicsGhiarcifgrae6mbkkcbc99alaqSEhokavc;aef8Kjjjjbaok:clevu8Jjjjjbcz9Rhvdnalaecvf9pmbc9:skdnaiRbbc;:eGc;qeSmbcuskav9cb83iwaicefhoaialfc98fhrdnaeTmbdnadcdSmbcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcdtfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgiBdbalaiBdbawcefgwae9hmbxdkkcbhwindnaoar6mbc9:skaocefhlao8SbbgicFeGhddndnaicu9mmbalhoxekaocvfhoadcFbGhdcrhidninal8SbbgDcFbGaitadVhdaDcu9kmealcefhlaicrfgic8J9hmbxdkkalcefhokabawcetfadc8Etc8F91adcd47avcwfadceGcdtVglydbfgi87ebalaiBdbawcefgwae9hmbkkcbc99aoarSEk;Toio97eue97aec98Ghedndnadcl9hmbaeTmecbhdinababpbbbgicKp:RecKp:Sep;6eglaicwp:RecKp:Sep;6ealp;Geaiczp:RecKp:Sep;6egvp;Gep;Kep;Legopxbbbbbbbbbbbbbbbbp:2egralpxbbbjbbbjbbbjbbbjgwp9op9rp;Keglpxbb;:9cbb;:9cbb;:9cbb;:9calalp;Meaoaop;Meavaravawp9op9rp;Keglalp;Mep;Kep;Kep;Jep;Negvp;Mepxbbn0bbn0bbn0bbn0grp;KepxFbbbFbbbFbbbFbbbp9oaipxbbbFbbbFbbbFbbbFp9op9qalavp;Mearp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaoavp;Mearp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbabczfhbadclfgdae6mbxdkkaeTmbcbhdinabczfgDaDpbbbgipxbbbbbbFFbbbbbbFFgwp9oabpbbbgoaipmbediwDqkzHOAKY8AEgvczp:Reczp:Sep;6eglaoaipmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eavczp:Sep;6egvp;Gealp;Gep;Kep;Legipxbbbbbbbbbbbbbbbbp:2egralpxbbbjbbbjbbbjbbbjgqp9op9rp;Keglpxb;:FSb;:FSb;:FSb;:FSalalp;Meaiaip;Meavaravaqp9op9rp;Keglalp;Mep;Kep;Kep;Jep;Negvp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbp9oaiavp;Mearp;Keczp:Rep9qgialavp;Mearp;KepxFFbbFFbbFFbbFFbbp9oglpmwDKYqk8AExm35Ps8E8Fp9qpkbbabaoawp9oaialpmbezHdiOAlvCXorQLp9qpkbbabcafhbadclfgdae6mbkkk;2ileue97euo97dnaec98GgiTmbcbheinabcKfpx:ji:1S:ji:1S:ji:1S:ji:1SabpbbbglabczfgvpbbbgopmlvorxmPsCXQL358E8Fgrczp:Segwpxibbbibbbibbbibbbp9qp;6egDp;NegqaDaDp;MegDaDp;KealaopmbediwDqkzHOAKY8AEgDczp:Reczp:Sep;6eglalp;MeaDczp:Sep;6egoaop;Mearczp:Reczp:Sep;6egrarp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jep;Mepxbbn0bbn0bbn0bbn0gDp;KepxFFbbFFbbFFbbFFbbgkp9oaqaop;MeaDp;Keczp:Rep9qgoaqalp;MeaDp;Keakp9oaqarp;MeaDp;Keczp:Rep9qgDpmwDKYqk8AExm35Ps8E8Fglp5eawclp:RegqpEi:T:j83ibavalp5baqpEd:T:j83ibabcwfaoaDpmbezHdiOAlvCXorQLgDp5eaqpEe:T:j83ibabaDp5baqpEb:T:j83ibabcafhbaeclfgeai6mbkkkuee97dnadcd4ae2c98GgeTmbcbhdinababpbbbgicwp:Recwp:Sep;6eaicep:SepxbbjFbbjFbbjFbbjFp9opxbbjZbbjZbbjZbbjZp:Uep;Mepkbbabczfhbadclfgdae6mbkkk:Sodw97euaec98Ghedndnadcl9hmbaeTmecbhdinabpxbbuJbbuJbbuJbbuJabpbbbgicKp:TeglaicYp:Tep9qgvcdp:Teavp9qgvclp:Teavp9qgop;6ep;Negvaicwp:RecKp:SegraipxFbbbFbbbFbbbFbbbgwp9ogDp:Uep;6ep;Mepxbbn0bbn0bbn0bbn0gqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9oavaDarp:Xeaiczp:RecKp:Segip:Uep;6ep;Meaqp;Keawp9op9qavaDaraip:Uep:Xep;6ep;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qavaoalcep:Rep9oalpxebbbebbbebbbebbbp9op9qp;6ep;Meaqp;KecKp:Rep9qpkbbabczfhbadclfgdae6mbxdkkaeTmbcbhdinabczfgkpxbFu9hbFu9hbFu9hbFu9habpbbbglakpbbbgrpmlvorxmPsCXQL358E8Fgvczp:TegqavcHp:Tep9qgicdp:Teaip9qgiclp:Teaip9qgicwp:Teaip9qgop;6ep;NegialarpmbediwDqkzHOAKY8AEgDpxFFbbFFbbFFbbFFbbglp9ograDczp:Segwp:Ueavczp:Reczp:SegDp:Xep;6ep;Mepxbbn0bbn0bbn0bbn0gvp;Kealp9oaiarawaDp:Uep:Xep;6ep;Meavp;Keczp:Rep9qgwaiaoaqcep:Rep9oaqpxebbbebbbebbbebbbp9op9qp;6ep;Meavp;Keczp:ReaiaDarp:Uep;6ep;Meavp;Kealp9op9qgipmwDKYqk8AExm35Ps8E8FpkbbabawaipmbezHdiOAlvCXorQLpkbbabcafhbadclfgdae6mbkkk9teiucbcbydj:G:cjbgeabcifc98GfgbBdj:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkxebcj:Gdklz:zbb",n=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),i=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!=="object")return{supported:!1};var r=WebAssembly.validate(n)?o(t):o(e),s,a=WebAssembly.instantiate(r,{}).then(function(p){s=p.instance,s.exports.__wasm_call_ctors()});function o(p){var x=new Uint8Array(p.length);for(var _=0;_<p.length;++_){var y=p.charCodeAt(_);x[_]=y>96?y-97:y>64?y-39:y+4}var v=0;for(var _=0;_<p.length;++_)x[v++]=x[_]<60?i[x[_]]:(x[_]-60)*64+x[++_];return x.buffer.slice(0,v)}function c(p,x,_,y,v,E,w){var T=p.exports.sbrk,A=y+3&-4,P=T(A*v),S=T(E.length),R=new Uint8Array(p.exports.memory.buffer);R.set(E,S);var k=x(P,y,v,S,E.length);if(k==0&&w)w(P,A,v);if(_.set(R.subarray(P,P+y*v)),T(P-T(0)),k!=0)throw Error("Malformed buffer data: "+k)}var l={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp",COLOR:"meshopt_decodeFilterColor"},u={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"},d=[],f=0;function h(p){var x={object:new Worker(p),pending:0,requests:{}};return x.object.onmessage=function(_){var y=_.data;x.pending-=y.count,x.requests[y.id][y.action](y.value),delete x.requests[y.id]},x}function b(p){var x="self.ready = WebAssembly.instantiate(new Uint8Array(["+new Uint8Array(r)+"]), {}).then(function(result) { result.instance.exports.__wasm_call_ctors(); return result.instance; });self.onmessage = "+g.name+";"+c.toString()+g.toString(),_=new Blob([x],{type:"text/javascript"}),y=URL.createObjectURL(_);for(var v=d.length;v<p;++v)d[v]=h(y);for(var v=p;v<d.length;++v)d[v].object.postMessage({});d.length=p,URL.revokeObjectURL(y)}function m(p,x,_,y,v){var E=d[0];for(var w=1;w<d.length;++w)if(d[w].pending<E.pending)E=d[w];return new Promise(function(T,A){var P=new Uint8Array(_),S=++f;E.pending+=p,E.requests[S]={resolve:T,reject:A},E.object.postMessage({id:S,count:p,size:x,source:P,mode:y,filter:v},[P.buffer])})}function g(p){var x=p.data;self.ready.then(function(_){if(!x.id)return self.close();try{var y=new Uint8Array(x.count*x.size);c(_,_.exports[x.mode],y,x.count,x.size,x.source,_.exports[x.filter]),self.postMessage({id:x.id,count:x.count,action:"resolve",value:y},[y.buffer])}catch(v){self.postMessage({id:x.id,count:x.count,action:"reject",value:v})}})}return{ready:a,supported:!0,useWorkers:function(p){b(p)},decodeVertexBuffer:function(p,x,_,y,v){c(s,s.exports.meshopt_decodeVertexBuffer,p,x,_,y,s.exports[l[v]])},decodeIndexBuffer:function(p,x,_,y){c(s,s.exports.meshopt_decodeIndexBuffer,p,x,_,y)},decodeIndexSequence:function(p,x,_,y){c(s,s.exports.meshopt_decodeIndexSequence,p,x,_,y)},decodeGltfBuffer:function(p,x,_,y,v,E){c(s,s.exports[u[v]],p,x,_,y,s.exports[l[E]])},decodeGltfBufferAsync:function(p,x,_,y,v){if(d.length>0)return m(p,x,_,u[y],l[v]);return a.then(function(){var E=new Uint8Array(p*x);return c(s,s.exports[u[y]],E,p,x,_,s.exports[l[v]]),E})}}}()});var hX;var _R=ht(()=>{hX=function(){var e="b9H79Tebbbe:6eO9Geueu9Geub9Gbb9Gsuuuuuuuuuuuu99uueu9Gvuuuuub9Gruuuuuuub9Gouuuuuue999Gvuuuuueu9Gzuuuuuuuuuuu99uuuub9Gquuuuuuu99uueu9GPuuuuuuuuuuu99uueu9Gquuuuuuuu99ueu9Gruuuuuu99eu9Gwuuuuuu99ueu9Giuuue999Gluuuueu9Gluuuub9GiuuueuiLQdilvorlwDiqkxmPszbHHbelve9Weiiviebeoweuecj:Gdkr:Bdxo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bbz9TW79O9V9Wt9F79P9T9W29P9M95bw8E9TW79O9V9Wt9F79P9T9W29P9M959x9Pt9OcttV9P9I91tW7bD8A9TW79O9V9Wt9F79P9T9W29P9M959x9Pt9O9v9W9K9HtWbqQ9TW79O9V9Wt9F79P9T9W29P9M959t29V9W9W95bkX9TW79O9V9Wt9F79P9T9W29P9M959qV919UWbxQ9TW79O9V9Wt9F79P9T9W29P9M959q9V9P9Ut7bmX9TW79O9V9Wt9F79P9T9W29P9M959t9J9H2WbPa9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94SWt9J9O9sW9T9H9Wbs59TW79O9V9Wt9F9NW9UWV9HtW9q9V79Pt9P9V9U9sW9T9H9Wbzl79IV9RbHDwebcekdCXq;y;WeQdbk;r:herYue99iuY99Xue9:D998Jjjjjbcj;sb9Rgs8Kjjjjbcbhzasc:Cefcbc;Kbz:tjjjb8AdnabaeSmbabaeadcdtzMjjjb8AkdnamcdGTmbalcrfci4cbyd1:H:cjbHjjjjbbhHasc:Cefasyd;8egecdtfaHBdbasaecefBd;8ecbhlcbhednadTmbabheadhOinaHaeydbci4fcb86bbaeclfheaOcufgOmbkcbhlabheadhOinaHaeydbgAci4fgCaCRbbgCceaAcrGgAtV86bbaCcu7aA4ceGalfhlaeclfheaOcufgOmbkcualcdtalcFFFFi0Ehekaecbyd1:H:cjbHjjjjbbhzasc:Cefasyd;8egecdtfazBdbasaecefBd;8ealcd4alfhOcehHinaHgecethHaeaO6mbkcbhXcuaecdtgOaecFFFFi0Ecbyd1:H:cjbHjjjjbbhHasc:Cefasyd;8egAcdtfaHBdbasaAcefBd;8eaHcFeaOz:tjjjbhQdnadTmbaecufhLcbhKindndnaQabaKcdtfgYydbgAc:v;t;h;Ev2aLGgOcdtfgCydbgHcuSmbceheinazaHcdtfydbaASmdaOaefhHaecefheaQaHaLGgOcdtfgCydbgHcu9hmbkkazaXcdtfaABdbaCaXBdbaXhHaXcefhXkaYaHBdbaKcefgKad9hmbkkaQcbyd:m:H:cjbH:bjjjbbasasyd;8ecufBd;8ekcbh8AcualcefgecdtaecFFFFi0Ecbyd1:H:cjbHjjjjbbhLasc:Cefasyd;8egecdtfaLBdbasaLBdNeasaecefBd;8ecuadcitadcFFFFe0Ecbyd1:H:cjbHjjjjbbhEasc:Cefasyd;8egecdtfaEBdbasaEBd:yeasaecefBd;8eascNefabadalcbz:cjjjbcualcdtgealcFFFFi0Eg3cbyd1:H:cjbHjjjjbbhOasc:Cefasyd;8egHcdtfaOBdbasaHcefBd;8ea3cbyd1:H:cjbHjjjjbbhQasc:Cefasyd;8egHcdtfaQBdbasaHcefBd;8eaOaQaialavazasc:Cefz:djjjbalcbyd1:H:cjbHjjjjbbhYasc:Cefasyd;8egHcdtfaYBdbasaHcefBd;8ea3cbyd1:H:cjbHjjjjbbhHasc:Cefasyd;8egAcdtfaHBdbasaAcefBd;8ea3cbyd1:H:cjbHjjjjbbhAasc:Cefasyd;8egCcdtfaABdbasaCcefBd;8eaHcFeaez:tjjjbh5aAcFeaez:tjjjbh8EdnalTmbindnaLa8AgAcefg8AcdtfydbgCaLaAcdtgefydbgHSmbaCaH9Rh8FaEaHcitfhaa8Eaefhha5aefhKcbhCindndnaaaCcitfydbgXaA9hmbaKaABdbahaABdbxekdnaLaXcdtggfgeclfydbgHaeydbgeSmbaHae9RhHaEaecitfheinaeydbaASmdaecwfheaHcufgHmbkka8EagfgeaAaXaeydbcuSEBdbaKaXaAaKydbcuSEBdbkaCcefgCa8F9hmbkka8Aal9hmbkaOhHaQhAa5hXa8EhCcbheindndnaeaHydbgK9hmbdnaeaAydbgK9hmbaXydbhKdnaCydbg8Fcu9hmbaKcu9hmbaYaefcb86bbxikdna8FcuSmbaKcuSmbaea8FSmbaOa8FcdtfydbaOaKcdtfydb9hmbaYaefcd86bbxikaYaefhadnaea8FSmbaeaKSmbaace86bbxikaacl86bbxdkdnaeaQaKcdtg8Ffydb9hmbdnaCydbgacuSmbaeaaSmbaXydbggcuSmbaeagSmba8Ea8FfydbghcuSmbahaKSmba5a8Ffydbg8FcuSmba8FaKSmbdnaOaacdtfydbgKaOa8Fcdtfydb9hmbaKaOagcdtfydbg8FSmba8FaOahcdtfydb9hmbaYaefcd86bbxlkaYaefcl86bbxikaYaefcl86bbxdkaYaefcl86bbxekaYaefaYaKfRbb86bbkaHclfhHaAclfhAaXclfhXaCclfhCalaecefge9hmbkdnamcaGTmbcbh8JindndnaYa8Jfg8KRbbg8Lc9:fPibebekdndndnaOa8Jcdtfydbgea8J9hmbdnaqmbcbh8FxdkdnazTmbcbh8Fa8JheinaqazaecdtgefydbfRbbce4a8FVceGh8FaQaefydbgea8J9hmbxikkcbh8Fa8JheinaqaefRbbce4a8FVceGh8FaQaecdtfydbgea8J9hmbxdkkaYaefRbbhexeka8JheindnaLaecdtg8AfgeclfydbgHaeydbgeSmbaHae9RhgaEaecitfhhaOa8AfhacbhKinahaKcitfydbgXhednindnaLaecdtgCfgeclfydbgHaeydbgeSmbaHae9RhHaEaecitfheaaydbhAdninaOaeydbcdtfydbaASmeaecwfheaHcufgHTmdxbkkcbhexdkaQaCfydbgeaX9hmbkceheka8FaeVh8FaKcefgKag9hmbkkaQa8Afydbgea8J9hmbka8Lcia8FceGEheka8Kae86bbka8Jcefg8Jal9hmbkkdnaqTmbdndnazTmbazheaOhHalhAindnaqaeydbfRbbceGTmbaYaHydbfcl86bbkaeclfheaHclfhHaAcufgAmbxdkkaqheaOhHalhAindnaeRbbceGTmbaYaHydbfcl86bbkaecefheaHclfhHaAcufgAmbkkaOhealhAaYhHindnaYaeydbfRbbcl9hmbaHcl86bbkaeclfheaHcefhHaAcufgAmbkkamceGTmbaYhealhHindnaeRbbce9hmbaecl86bbkaecefheaHcufgHmbkkcbh8Mcualcx2alc;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbh8Nasc:Cefasyd;8egecdtfa8NBdbasaecefBd;8eascbBd:qeas9cb83i1ea8Naialavazasc1efz:ejjjbhydndnaDmbcbh8PcbhCxekcbhCawhecbhHindnaeIdbJbbbb9ETmbasaCcdtfaHBdbaCcefhCkaeclfheaDaHcefgH9hmbkcuaCal2gecdtaecFFFFi0Ecbyd1:H:cjbHjjjjbbh8Pasc:Cefasyd;8egecdtfa8PBdbasaecefBd;8ealTmbdnaCmbcbhCxekarcd4hgdnazTmbaCcdthhcbh8Fa8Phainaoaza8Fcdtfydbag2cdtfhKasheaahHaChAinaHaKaeydbcdtgXfIdbawaXfIdbNUdbaeclfheaHclfhHaAcufgAmbkaaahfhaa8Fcefg8Fal9hmbxdkkaCcdthhcbh8Fa8Phainaoa8Fag2cdtfhKasheaahHaChAinaHaKaeydbcdtgXfIdbawaXfIdbNUdbaeclfheaHclfhHaAcufgAmbkaaahfhaa8Fcefg8Fal9hmbkkcualc8S2gHalc;D;O;f8U0EgXcbyd1:H:cjbHjjjjbbheasc:Cefasyd;8egAcdtfaeBdbasaAcefBd;8eaecbaHz:tjjjbhIcbh8RcbhgdnaCTmbcbh8MaXcbyd1:H:cjbHjjjjbbhgasc:Cefasyd;8egecdtfagBdbasaecefBd;8eagcbaHz:tjjjb8AcuaCal2gecltgHaecFFFFb0Ecbyd1:H:cjbHjjjjbbh8Rasc:Cefasyd;8egecdtfa8RBdbasaecefBd;8ea8RcbaHz:tjjjb8AamcjjjjdGTmbcualcltgealcFFFFb0Ecbyd1:H:cjbHjjjjbbh8Masc:Cefasyd;8egHcdtfa8MBdbasaHcefBd;8ea8Mcbaez:tjjjb8AkdnadTmbcbhKabhHina8NaHclfydbg8Fcx2fgeIdba8NaHydbgacx2fgAIdbg8S:tgRa8NaHcwfydbghcx2fgXIdlaAIdlg8U:tg8VNaeIdla8U:tg8WaXIdba8S:tg8XN:tg8Ya8YNa8WaXIdwaAIdwg8Z:tg80NaeIdwa8Z:tg8Wa8VN:tg81a81Na8Wa8XNaRa80N:tg80a80NMMg8V:rhBa8Yh8Xa80h8Wa81hRdna8VJbbbb9EgATmba8YaB:vh8Xa80aB:vh8Wa81aB:vhRkaIaOaacdtfydbgXc8S2fgeaRaB:rg8VaRNNg83aeIdbMUdbaea8Wa8Va8WNgUNg85aeIdlMUdlaea8Xa8Va8XNg86Ng87aeIdwMUdwaeaRaUNgUaeIdxMUdxaea86aRNg88aeIdzMUdzaea8Wa86Ng89aeIdCMUdCaeaRa8Va8Xa8ZNaRa8SNa8Ua8WNMM:mg8:Ng86NgRaeIdKMUdKaea8Wa86Ng8WaeId3MUd3aea8Xa86Ng8XaeIdaMUdaaea86a8:Ng86aeId8KMUd8Kaea8VaeIdyMUdyaIaOa8Fcdtfydbg8Fc8S2fgea83aeIdbMUdbaea85aeIdlMUdlaea87aeIdwMUdwaeaUaeIdxMUdxaea88aeIdzMUdzaea89aeIdCMUdCaeaRaeIdKMUdKaea8WaeId3MUd3aea8XaeIdaMUdaaea86aeId8KMUd8Kaea8VaeIdyMUdyaIaOahcdtfydbgac8S2fgea83aeIdbMUdbaea85aeIdlMUdlaea87aeIdwMUdwaeaUaeIdxMUdxaea88aeIdzMUdzaea89aeIdCMUdCaeaRaeIdKMUdKaea8WaeId3MUd3aea8XaeIdaMUdaaea86aeId8KMUd8Kaea8VaeIdyMUdydna8MTmbdnaATmba8YaB:vh8Ya80aB:vh80a81aB:vh81ka8MaXcltfgeaBJbbbZNgRa80Ng8VaeIdlMUdlaeaRa8YNg8WaeIdwMUdwaeaRa81Ng8XaeIdbMUdbaeaRa8S:ma81Na8Ua80N:ta8Za8YN:tNgRaeIdxMUdxa8Ma8Fcltfgea8VaeIdlMUdlaea8WaeIdwMUdwaea8XaeIdbMUdbaeaRaeIdxMUdxa8Maacltfgea8VaeIdlMUdlaea8WaeIdwMUdwaea8XaeIdbMUdbaeaRaeIdxMUdxkaHcxfhHaKcifgKad6mbkkdnalTmbJq;x8J88J;n;m;m89J:v:;;w8ZamczGEamc;abGEh80cbhHaOhXazhKaIhea8NhAindnaHaXydb9hmbaHh8FdnazTmbaKydbh8Fka80hRdnaqTmbJbbjZa80aqa8FfRbbclGEhRkaecxfg8Fa8FIdbJbbbbMUdbaeczfg8Fa8FIdbJbbbbMUdbaecCfg8Fa8FIdbJbbbbMUdbaeaRaecyfg8FIdbg8YNgRaeIdbMUdbaeclfgaaRaaIdbMUdbaecwfgaaRaaIdbMUdbaecKfgaaaIdbaAIdbg8WaRN:tUdbaAcwfIdbh8Vaec3fgaaaIdbaRaAclfIdbg8XN:tUdbaecafgaaaIdbaRa8VN:tUdbaec8KfgaIdbh81a8Fa8YaRMUdbaaa81aRa8Va8VNa8Wa8WNa8Xa8XNMMNMUdbkaXclfhXaKclfhKaec8SfheaAcxfhAalaHcefgH9hmbkkdnadTmbcbh8Aabhainaba8Acdtfh8FcbhHinaYa8FaHc:G:G:cjbfydbcdtfydbgAfRbbhedndnaYaaaHfydbgXfRbbgKc99fcFeGcpe0mbaec99fcFeGc;:e6mekdnaKcufcFeGce0mba5aXcdtfydbaA9hmekdnaecufcFeGce0mba8EaAcdtfydbaX9hmekJbbacJbbacJbbbZaecFeGceSEaKcFeGceSEhUdna8Na8FaHc:K:G:cjbfydbcdtfydbcx2fgeIdwa8NaXcx2fgKIdwg86:tg8Sa8NaAcx2fghIdwa86:tg8Xa8XNahIdbaKIdbg8U:tg80a80NahIdlaKIdlg8Z:tg8Va8VNMMg81Na8Xa8Sa8XNaeIdba8U:tg83a80Na8VaeIdla8Z:tg85NMMg8WN:tg8Ya8YNa83a81Na80a8WN:tgRaRNa85a81Na8Va8WN:tg8Wa8WNMMgBJbbbb9ETmba8YaB:rgB:vh8Ya8WaB:vh8WaRaB:vhRkaUa81:rNgBa8Ya86NaRa8UNa8Za8WNMM:mg81Ng87a81Nh88a80a85Na8Va83N:tg81a81Na8Va8SNa8Xa85N:tg8Va8VNa8Xa83Na80a8SN:tg8Xa8XNMMg83:rh80a8Ya87Nh85a8Wa87Nh89aRa87Nh87a8WaBa8YNg8SNh8:a8SaRNhZaRaBa8WNgnNhca8Ya8SNh8Ya8WanNh8WaRaBaRNNh8Sdna83Jbbbb9ETmba81a80:vh81a8Xa80:vh8Xa8Va80:vh8VkaIaOaXcdtfydbc8S2fgeaeIdba8Sa8VaUa80:rNgRa8VNNMg80MUdbaea8Wa8XaRa8XNg8SNMg83aeIdlMUdlaea8Ya81aRa81Ng8WNMg8YaeIdwMUdwaeaca8Va8SNMg8SaeIdxMUdxaeaZa8Wa8VNMgUaeIdzMUdzaea8:a8Xa8WNMg8WaeIdCMUdCaea87a8VaRa81a86Na8Va8UNa8Za8XNMMg86:mNgRNMg8VaeIdKMUdKaea89a8XaRNMg8XaeId3MUd3aea85a81aRNMg81aeIdaMUdaaea88a86aRN:tgRaeId8KMUd8KaeaBaeIdyMUdyaIaOaAcdtfydbc8S2fgea80aeIdbMUdbaea83aeIdlMUdlaea8YaeIdwMUdwaea8SaeIdxMUdxaeaUaeIdzMUdzaea8WaeIdCMUdCaea8VaeIdKMUdKaea8XaeId3MUd3aea81aeIdaMUdaaeaRaeId8KMUd8KaeaBaeIdyMUdykaHclfgHcx9hmbkaacxfhaa8Acifg8Aad6mbkaCTmbcbhainJbbbbh80a8Nabaacdtfgeclfydbg8Fcx2fgHIdwa8Naeydbghcx2fgAIdwg8Z:tg8Va8VNaHIdbaAIdbg83:tg8Wa8WNaHIdlaAIdlg85:tg8Xa8XNMMg8Sa8Naecwfydbg8Acx2fgeIdwa8Z:tg8YNa8Va8YNa8WaeIdba83:tg81Na8XaeIdla85:tgBNMMgRa8VN:tJbbbbJbbjZa8Sa8Ya8YNa81a81NaBaBNMMg8UNaRaRN:tg86:va86Jbbbb9BEg86Nh88a8Ua8VNaRa8YN:ta86Nh89a8SaBNaRa8XN:ta86Nh8:a8Ua8XNaRaBN:ta86NhZa8Sa81NaRa8WN:ta86Nhna8Ua8WNaRa81N:ta86Nhca8WaBNa8Xa81N:tgRaRNa8Xa8YNa8VaBN:tgRaRNa8Va81Na8Wa8YN:tgRaRNMM:rJbbbZNhRa8PahaC2g8JcdtfhHa8Pa8AaC2gDcdtfhAa8Pa8FaC2g8KcdtfhXa8Z:mh9ca85:mhJa83:mh9eascjdfheaChKJbbbbhBJbbbbh86Jbbbbh8SJbbbbh8UJbbbbh8ZJbbbbh83Jbbbbh85Jbbbbh87JbbbbhUinaecwfaRa89aXIdbaHIdbg8Y:tg8XNa88aAIdba8Y:tg81NMg8VNUdbaeclfaRaZa8XNa8:a81NMg8WNUdbaeaRaca8XNana81NMg8XNUdbaecxfaRa9ca8VNaJa8WNa8Ya9ea8XNMMMg8YNUdbaRa8Va8WNNa8ZMh8ZaRa8Va8XNNa8UMh8UaRa8Wa8XNNa8SMh8SaRa8Ya8YNNaUMhUaRa8Va8YNNa87Mh87aRa8Wa8YNNa85Mh85aRa8Xa8YNNa83Mh83aRa8Va8VNNa86Mh86aRa8Wa8WNNaBMhBaRa8Xa8XNNa80Mh80aHclfhHaXclfhXaAclfhAaeczfheaKcufgKmbkagahc8S2fgea80aeIdbMUdbaeaBaeIdlMUdlaea86aeIdwMUdwaea8SaeIdxMUdxaea8UaeIdzMUdzaea8ZaeIdCMUdCaea83aeIdKMUdKaea85aeId3MUd3aea87aeIdaMUdaaeaUaeId8KMUd8KaeaRaeIdyMUdyaga8Fc8S2fgea80aeIdbMUdbaeaBaeIdlMUdlaea86aeIdwMUdwaea8SaeIdxMUdxaea8UaeIdzMUdzaea8ZaeIdCMUdCaea83aeIdKMUdKaea85aeId3MUd3aea87aeIdaMUdaaeaUaeId8KMUd8KaeaRaeIdyMUdyaga8Ac8S2fgea80aeIdbMUdbaeaBaeIdlMUdlaea86aeIdwMUdwaea8SaeIdxMUdxaea8UaeIdzMUdzaea8ZaeIdCMUdCaea83aeIdKMUdKaea85aeId3MUd3aea87aeIdaMUdaaeaUaeId8KMUd8KaeaRaeIdyMUdya8Ra8Jcltfh8FcbhHaChXina8FaHfgeascjdfaHfgAIdbaeIdbMUdbaeclfgKaAclfIdbaKIdbMUdbaecwfgKaAcwfIdbaKIdbMUdbaecxfgeaAcxfIdbaeIdbMUdbaHczfhHaXcufgXmbka8Ra8Kcltfh8FcbhHaChXina8FaHfgeascjdfaHfgAIdbaeIdbMUdbaeclfgKaAclfIdbaKIdbMUdbaecwfgKaAcwfIdbaKIdbMUdbaecxfgeaAcxfIdbaeIdbMUdbaHczfhHaXcufgXmbka8RaDcltfh8FcbhHaChXina8FaHfgeascjdfaHfgAIdbaeIdbMUdbaeclfgKaAclfIdbaKIdbMUdbaecwfgKaAcwfIdbaKIdbMUdbaecxfgeaAcxfIdbaeIdbMUdbaHczfhHaXcufgXmbkaacifgaad6mbkkcbhAdndnamcwGgTmbJbbbbh8ScbhScbh9hcbh9ixekcbhSa3cbyd1:H:cjbHjjjjbbh9iasc:Cefasyd;8egecdtfa9iBdbasaecefBd;8ecua9ialabadaOz:fjjjbgXcltaXcjjjjiGEcbyd1:H:cjbHjjjjbbh9hasc:Cefasyd;8egecdtfa9hBdbasaecefBd;8ea9haXa9ia8Nalz:gjjjbJFFuuh8SaXTmba9hheaXhHinaeIdbgRa8Sa8SaR9EEh8SaeclfheaHcufgHmbkaXhSkdnalTmbaLclfheaLydbhXaYhHalhKcbhAincbaeydbg8FaX9RaHRbbcpeGEaAfhAaHcefhHaeclfhea8FhXaKcufgKmbkaAce4hAkcuadaA9Rcifg6cx2a6c;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbh9kasc:Cefasyd;8egecdtfa9kBdbasaecefBd;8ecua6cdta6cFFFFi0Ecbyd1:H:cjbHjjjjbbh0asc:Cefasyd;8egecdtfa0BdbasaecefBd;8ea3cbyd1:H:cjbHjjjjbbh9masc:Cefasyd;8egecdtfa9mBdbasaecefBd;8ealcbyd1:H:cjbHjjjjbbh9nasc:Cefasyd;8egecdtfa9nBdbasaecefBd;8eaxaxNayJbbjZamclGEgZaZN:vh87JbbbbhUdnadak9nmbdna6ci6mbaCclth9oa9kcwfh9pJbbbbh85JbbbbhUinascNefabadalaOz:cjjjbabh8Acbh9qcbh9rinaba9rcdtfhDcbheindnaOa8AaefydbgAcdtghfydbgXaOaDaec:W:G:cjbfydbcdtfydbgHcdtg8JfydbgKSmbaYaHfRbbgacv2aYaAfRbbg8FfRb;a:G:cjbg8La8Fcv2aafg8KRb;a:G:cjbg3VcFeGTmbdnaKaX9nmba8KRb;G:G:cjbcFeGmekdna8FcufcFeGce0mbaaTmba5ahfydbaH9hmekdna8FTmbaacufcFeGce0mba8Ea8JfydbaA9hmeka9ka9qcx2fgXaHaAa3cFeGgKEBdlaXaAaHaKEBdbaXaKa8LGcb9hBdwa9qcefh9qkaeclfgecx9hmbkdna9rcifg9rad9pmba8Acxfh8Aa9qcifa69nmekka9qTmdcbh8KinaIaOa9ka8Kcx2fghydbgKcdtgXfydbg8Ac8S2fgeIdwa8Nahydlg8Fcx2fgHIdwg8WNaeIdzaHIdbg8XNaeIdaMgRaRMMa8WNaeIdlaHIdlg8YNaeIdCa8WNaeId3MgRaRMMa8YNaeIdba8XNaeIdxa8YNaeIdKMgRaRMMa8XNaeId8KMMM:lhRJbbbbJbbjZaeIdyg8V:va8VJbbbb9BEh8VdndnahydwgDmbJFFuuh86xekJbbbbJbbjZaIaOa8Fcdtfydbc8S2fgeIdyg81:va81Jbbbb9BEaeIdwa8NaKcx2fgHIdwg81NaeIdzaHIdbg80NaeIdaMgBaBMMa81NaeIdlaHIdlgBNaeIdCa81NaeId3Mg81a81MMaBNaeIdba80NaeIdxaBNaeIdKMg81a81MMa80NaeId8KMMM:lNh86ka8VaRNhBdnaCTmbagaKc8S2fgAIdwa8WNaAIdza8XNaAIdaMgRaRMMa8WNaAIdla8YNaAIdCa8WNaAId3MgRaRMMa8YNaAIdba8XNaAIdxa8YNaAIdKMgRaRMMa8XNaAId8KMMMhRa8Pa8FaC2gacdtfhHa8RaKaC2g8JcltfheaAIdyh81aChAinaHIdbg8Va8Va81NaecxfIdba8WaecwfIdbNa8XaeIdbNa8YaeclfIdbNMMMg8Va8VM:tNaRMhRaHclfhHaeczfheaAcufgAmbkdndnaDmbJbbbbh8Vxekaga8Fc8S2fgAIdwa8NaKcx2fgeIdwg8XNaAIdzaeIdbg8YNaAIdaMg8Va8VMMa8XNaAIdlaeIdlg81NaAIdCa8XNaAId3Mg8Va8VMMa81NaAIdba8YNaAIdxa81NaAIdKMg8Va8VMMa8YNaAId8KMMMh8Va8Pa8JcdtfhHa8RaacltfheaAIdyh80aChAinaHIdbg8Wa8Wa80NaecxfIdba8XaecwfIdbNa8YaeIdbNa81aeclfIdbNMMMg8Wa8WM:tNa8VMh8VaHclfhHaeczfheaAcufgAmbka8V:lh8VkaBaR:lMhBa86a8VMh86dndndnaYaKfRbbc9:fPddbekaQaXfydbgXaKSmbaOa8Fcdtfydbh8Jindndna5aXcdtgafydbgecuSmbaOaecdtfydba8JSmekdna8EaafydbgecuSmbaOaecdtfydba8JSmeka8FhekagaXc8S2fgAIdwa8Naecx2fgHIdwg8WNaAIdzaHIdbg8XNaAIdaMgRaRMMa8WNaAIdlaHIdlg8YNaAIdCa8WNaAId3MgRaRMMa8YNaAIdba8XNaAIdxa8YNaAIdKMgRaRMMa8XNaAId8KMMMhRa8PaeaC2cdtfhHa8RaXaC2cltfheaAIdyh81aChAinaHIdbg8Va8Va81NaecxfIdba8WaecwfIdbNa8XaeIdbNa8YaeclfIdbNMMMg8Va8VM:tNaRMhRaHclfhHaeczfheaAcufgAmbkaBaR:lMhBaQaafydbgXaK9hmbkkaYa8FfRbbci9hmeaDTmeaQa8FcdtfydbgXa8FSmeindndna5aXcdtgafydbgecuSmbaOaecdtfydba8ASmekdna8EaafydbgecuSmbaOaecdtfydba8ASmekaKhekagaXc8S2fgAIdwa8Naecx2fgHIdwg8WNaAIdzaHIdbg8XNaAIdaMgRaRMMa8WNaAIdlaHIdlg8YNaAIdCa8WNaAId3MgRaRMMa8YNaAIdba8XNaAIdxa8YNaAIdKMgRaRMMa8XNaAId8KMMMhRa8PaeaC2cdtfhHa8RaXaC2cltfheaAIdyh81aChAinaHIdbg8Va8Va81NaecxfIdba8WaecwfIdbNa8XaeIdbNa8YaeclfIdbNMMMg8Va8VM:tNaRMhRaHclfhHaeczfheaAcufgAmbka86aR:lMh86aQaafydbgXa8F9hmbxdkkdna8Ea5a5aXfydba8FSEaQaXfydbgacdtfydbgXcu9hmbaQa8FcdtfydbhXkagaac8S2fgAIdwa8NaXcx2fgeIdwg8WNaAIdzaeIdbg8XNaAIdaMgRaRMMa8WNaAIdlaeIdlg8YNaAIdCa8WNaAId3MgRaRMMa8YNaAIdba8XNaAIdxa8YNaAIdKMgRaRMMa8XNaAId8KMMMhRa8PaXaC2g8AcdtfhHa8RaaaC2g8JcltfheaAIdyh81aChAinaHIdbg8Va8Va81NaecxfIdba8WaecwfIdbNa8XaeIdbNa8YaeclfIdbNMMMg8Va8VM:tNaRMhRaHclfhHaeczfheaAcufgAmbkdndnaDmbJbbbbh8VxekagaXc8S2fgAIdwa8Naacx2fgeIdwg8XNaAIdzaeIdbg8YNaAIdaMg8Va8VMMa8XNaAIdlaeIdlg81NaAIdCa8XNaAId3Mg8Va8VMMa81NaAIdba8YNaAIdxa81NaAIdKMg8Va8VMMa8YNaAId8KMMMh8Va8Pa8JcdtfhHa8Ra8AcltfheaAIdyh80aChAinaHIdbg8Wa8Wa80NaecxfIdba8XaecwfIdbNa8YaeIdbNa81aeclfIdbNMMMg8Wa8WM:tNa8VMh8VaHclfhHaeczfheaAcufgAmbka8V:lh8VkaBaR:lMhBa86a8VMh86kaha86aBa86aB9DgeEUdwahaKa8FaeaDcb9hGgeEBdlaha8FaKaeEBdba8Kcefg8Ka9q9hmbkascjdfcbcj;qbz:tjjjb8Aa9phea9qhHinascjdfaeydbcA4cF8FGgAcFAaAcFA6EcdtfgAaAydbcefBdbaecxfheaHcufgHmbkcbhecbhHinascjdfaefgAydbhXaAaHBdbaXaHfhHaeclfgecj;qb9hmbkcbhea9phHinascjdfaHydbcA4cF8FGgAcFAaAcFA6EcdtfgAaAydbgAcefBdba0aAcdtfaeBdbaHcxfhHa9qaecefge9hmbkadak9RgAci9Uh9sdnalTmbcbhea9mhHinaHaeBdbaHclfhHalaecefge9hmbkkcbh9ta9ncbalz:tjjjbh3aAcO9Uh9ua9sce4h9rcbh8Lcbh8Kdnina9ka0a8Kcdtfydbcx2fg8JIdwgRa879Emea8La9s9pmeJFFuuh8Vdna9ra9q9pmba9ka0a9rcdtfydbcx2fIdwJbb;aZNh8VkdnaRa8V9ETmbaRaU9ETmba8La9u0mdkdna3aOa8JydlgDcdtg9vfg8AydbgAfg9wRbba3aOa8Jydbghcdtg9xfydbgefg9yRbbVmbaYahfRbbh9zdndnaLaecdtfgHclfydbgXaHydbgHSmbaXaH9RhXa8NaAcx2fh8Fa8Naecx2fhaaEaHcitfheindna9maeydbcdtfydbgHaASmba9maeclfydbcdtfydbgKaASmbaHaKSmba8NaKcx2fgKIdba8NaHcx2fgHIdbg8W:tgRaaIdlaHIdlg8X:tg80NaKIdla8X:tg8VaaIdba8W:tgBN:tg8YaRa8FIdla8X:tg86Na8Va8FIdba8W:tg8UN:tg8XNa8VaaIdwaHIdwg81:tg8ZNaKIdwa81:tg8Wa80N:tg80a8Va8FIdwa81:tg83Na8Wa86N:tg8VNa8WaBNaRa8ZN:tg81a8Wa8UNaRa83N:tgRNMMa8Ya8YNa80a80Na81a81NMMa8Xa8XNa8Va8VNaRaRNMMN:rJbbj8:N9FmikaecwfheaXcufgXmbkkdndndndna9zc9:fPdebdkahheina8AydbhAdndna5aecdtgHfydbgecuSmbaOaecdtfydbaASmekdna8EaHfydbgecuSmbaOaecdtfydbaASmekaDheka9maHfaeBdbaQaHfydbgeah9hmbxikkdna8Ea5a5a9xfydbaDSEaQa9xfydbghcdtfydbgecu9hmbaQa9vfydbheka9ma9xfaDBdbaehDka9mahcdtfaDBdbka9yce86bba9wce86bba8JIdwgRaUaUaR9DEhUa9tcefh9tcecda9zceSEa8Lfh8Lxeka9rcefh9rka8Kcefg8Ka9q9hmbkka9tTmddnalTmbcbh8Fcbhhindna9mahcdtgefydbgAahSmbaOaAcdtfydbh8AdnahaOaefydb9hg8JmbaIa8Ac8S2fgeaIahc8S2fgHIdbaeIdbMUdbaeaHIdlaeIdlMUdlaeaHIdwaeIdwMUdwaeaHIdxaeIdxMUdxaeaHIdzaeIdzMUdzaeaHIdCaeIdCMUdCaeaHIdKaeIdKMUdKaeaHId3aeId3MUd3aeaHIdaaeIdaMUdaaeaHId8KaeId8KMUd8KaeaHIdyaeIdyMUdya8MTmba8Ma8Acltfgea8MahcltfgHIdbaeIdbMUdbaeaHIdlaeIdlMUdlaeaHIdwaeIdwMUdwaeaHIdxaeIdxMUdxkaCTmbagaAc8S2fgeagahc8S2gDfgHIdbaeIdbMUdbaeaHIdlaeIdlMUdlaeaHIdwaeIdwMUdwaeaHIdxaeIdxMUdxaeaHIdzaeIdzMUdzaeaHIdCaeIdCMUdCaeaHIdKaeIdKMUdKaeaHId3aeId3MUd3aeaHIdaaeIdaMUdaaeaHId8KaeId8KMUd8KaeaHIdyaeIdyMUdya9oaA2haa8RhHaChXinaHaafgeaHa8FfgAIdbaeIdbMUdbaeclfgKaAclfIdbaKIdbMUdbaecwfgKaAcwfIdbaKIdbMUdbaecxfgeaAcxfIdbaeIdbMUdbaHczfhHaXcufgXmbka8JmbJbbbbJbbjZaIaDfgeIdygR:vaRJbbbb9BEaeIdwa8Na8Acx2fgHIdwgRNaeIdzaHIdbg8VNaeIdaMg8Wa8WMMaRNaeIdlaHIdlg8WNaeIdCaRNaeId3MgRaRMMa8WNaeIdba8VNaeIdxa8WNaeIdKMgRaRMMa8VNaeId8KMMM:lNgRa85a85aR9DEh85ka8Fa9ofh8Fahcefghal9hmbkcbhHa5heindnaeydbgAcuSmbdnaHa9maAcdtgXfydbgA9hmbcuhAa5aXfydbgXcuSmba9maXcdtfydbhAkaeaABdbkaeclfhealaHcefgH9hmbkcbhHa8EheindnaeydbgAcuSmbdnaHa9maAcdtgXfydbgA9hmbcuhAa8EaXfydbgXcuSmba9maXcdtfydbhAkaeaABdbkaeclfhealaHcefgH9hmbkka85aUaCEh85cbhHabhecbhAindnaOa9maeydbcdtfydbg8FcdtfydbgXaOa9maeclfydbcdtfydbgacdtfydbgKSmbaXaOa9maecwfydbcdtfydbg8AcdtfydbghSmbaKahSmbabaHcdtfgXa8FBdbaXcwfa8ABdbaXclfaaBdbaHcifhHkaecxfheaAcifgAad6mbkdndnaTmbaHhdxekdnaHak0mbaHhdxekdna8Sa859FmbaHhdxekJFFuuh8ScbhdabhecbhAindna9ha9iaeydbgXcdtfydbcdtfIdbgRa859ETmbaeclf8Pdbh9AabadcdtfgKaXBdbaKclfa9A83dbaRa8Sa8SaR9EEh8SadcifhdkaecxfheaAcifgAaH6mbkkadak0mbxdkkascNefabadalaOz:cjjjbkdndnadak0mbadhaxekdnaTmbadhaxekdna8Sa879FmbadhaxekcehKina8SJbb;aZNgRa87aRa879DEh8WJbbbbhRdnaSTmba9hheaShHinaeIdbg8VaRa8Va8W9FEaRa8VaR9EEhRaeclfheaHcufgHmbkkJFFuuh8ScbhaabhecbhHindna9ha9iaeydbgAcdtfydbcdtfIdbg8Va8W9ETmbaeclf8Pdbh9AabaacdtfgXaABdbaXclfa9A83dba8Va8Sa8Sa8V9EEh8SaacifhakaecxfheaHcifgHad6mbkdnaKaaad9hVceGmbadhaxdkaRaUaUaR9DEhUaaak9nmecbhKaahda8Sa879FmbkkdnamcjjjjdGTmba9ncbalz:tjjjbh8AdnaaTmbabheaahHina8AaeydbgAfce86bba8AaOaAcdtfydbfce86bbaeclfheaHcufgHmbkkascNefabaaalaOz:cjjjbdndnalTmbcbhXindna8AaXfRbbTmbdnaYaXfRbbgecl0mbceaetcQGmekdnaOaXcdtg8FfydbgeaXSmba8NaXcx2fgHa8Naecx2fgeydwBdwaHae8Pdb83dbxekaIaXc8S2fgKIdygcacJL:3;rUNgRMh87aKIdwg9BaRMh8SaKIdlg9CaRMh8UaKIdbg9DaRMh81aKIdag9EaRa8NaXcx2fg8JIdwg88N:th8ZaKId3g9FaRa8JIdlg89N:th83aKIdKg9Ga8JIdbg8:aRN:th80JbbbbhnaKIdCg9HJbbbbMh85aKIdzg9IJbbbbMhBaKIdxg9JJbbbbMh86dndnaCTmbaXhAinJbbbba87agaAc8S2fgHIdygR:vaRJbbbb9BEhRa8RaAaC2cltfheaHIdaa87Na8ZMh8ZaHId3a87Na83Mh83aHIdKa87Na80Mh80aHIdCa87Na85Mh85aHIdza87NaBMhBaHIdxa87Na86Mh86aHIdwa87Na8SMh8SaHIdla87Na8UMh8UaHIdba87Na81Mh81aChHina8ZaecwfIdbg8VaecxfIdbg8YNaRN:th8Za83aeclfIdbg8Wa8YNaRN:th83a85a8Wa8VNaRN:th85a81aeIdbg8Xa8XNaRN:th81a80a8Xa8YNaRN:th80aBa8Xa8VNaRN:thBa86a8Xa8WNaRN:th86a8Sa8Va8VNaRN:th8Sa8Ua8Wa8WNaRN:th8UaeczfheaHcufgHmbkaQaAcdtfydbgAaX9hmbka8MTmba8MaXcltfgeIdxhxaeIdwh9caeIdlhJaeIdbhRxekJbbbbhxJbbbbh9cJbbbbhJJbbbbhRkaBa81:vg8Wa80Na8Z:ta85aBa86a81:vg8VN:tg8Za8Ua86a8VN:tg8Y:vg8Xa8Va80Na83:tg8UN:th83a9caRa8WN:taJaRa8VN:tg86a8XN:tg85a8SaBa8WN:ta8Za8XN:tgB:vg8S:mh8Za86a8Y:vg9c:mhJdnJbbbbaRaRa81:vg9eN:ta86a9cN:ta85a8SN:tg86:la87J:983:g81NgR9ETmba8Za83NaJa8UNa9ea80Nax:tMMa86:vhnka81:laR9ETmba8Y:laR9ETmbaB:laR9ETmba9e:manNa8W:ma8ZanNa83aB:vMgBNa8V:maJanNa8X:maBNa8Ua8Y:vMMg85Na80:ma81:vMMMh87aLa8FfgeclfydbgHaeydbge9RhhaEaecitfh8FJbbbbhRdnaHaeSgDmbJbbbbhRa8FheahhAina8Naeclfydbcx2fgHIdwa88:tg8Va8VNaHIdba8::tg8Va8VNaHIdla89:tg8Va8VNMMg8Va8Naeydbcx2fgHIdwa88:tg8Wa8WNaHIdba8::tg8Wa8WNaHIdla89:tg8Wa8WNMMg8WaRaRa8W9DEgRaRa8V9DEhRaecwfheaAcufgAmbkaR:rgRaRNhRkaBa88:tg8Va8VNa87a8::tg8Va8VNa85a89:tg8Va8VNMMaR9EmbaKId8KhndnaDmbina8Na8Fclfydbcx2fgeIdba8Na8Fydbcx2fgHIdbg8W:tgRa89aHIdlg8X:tg80NaeIdla8X:tg8Va8:a8W:tg86N:tg8YaRa85a8X:tg8SNa8Va87a8W:tg8UN:tg8XNa8Va88aHIdwg81:tg8ZNaeIdwa81:tg8Wa80N:tg80a8VaBa81:tg83Na8Wa8SN:tg8VNa8Wa86NaRa8ZN:tg81a8Wa8UNaRa83N:tgRNMMa8Ya8YNa80a80Na81a81NMMa8Xa8XNa8Va8VNaRaRNMMN:rJbbj8:N9Fmda8Fcwfh8FahcufghmbkkJbbbbJbbjZac:vacJbbbb9BEgRa9BaBNa9Ia87Na9EMg8Va8VMMaBNa9Ca85Na9HaBNa9FMg8Va8VMMa85Na9Da87Na9Ja85Na9GMg8Va8VMMa87NanMMM:lNaRa9Ba88Na9Ia8:Na9EMg8Va8VMMa88Na9Ca89Na9Ha88Na9FMg8Va8VMMa89Na9Da8:Na9Ja89Na9GMg8Va8VMMa8:NanMMM:lNJbb;aZNJ:983:g81M9Emba8JaBUdwa8Ja85Udla8Ja87UdbkaXcefgXal9hmbkdnaCmbcbhCxdkcbhXindna8AaXfRbbTmbaOaXcdtgefydbaX9hmbaYaXfhhaQaefh8Ja8NaXcx2fhAa8PaXaC2cdtfhDcbhEincuhLdnahRbbci9hmbaXhLa8JydbgeaXSmba8PaEcdtgHfhKaDaHfIdbhRaXhLinaLhHcuhLdnaKaeaC2cdtfIdbaR9CmbaHcuSmbaHhLagaec8S2fIdyagaHc8S2fIdy9ETmbaehLkaQaecdtfydbgeaX9hmbkka8PaEcdtfhKa8RaEcltfh8FaXheinaKaeaC2cdtfJbbbbJbbjZagaeaLaLcuSEgHc8S2fIdygR:vaRJbbbb9BEa8FaHaC2cltfgHIdwaAIdwNaHIdbaAIdbNaHIdlaAIdlNMMaHIdxMNUdbaQaecdtfydbgeaX9hmbkaEcefgEaC9hmbkkaXcefgXal9hmbxdkkaCmbcbhCkaiavaoarawaCala8Na8Pazasayasc1efaYa8Aaqz:hjjjbkdnamcjjjjlGTmbazmbaaTmbabhecbhLinaYaeydbgAfRbbc3thQaecwfgXydbhHcjjjj94hCdna5aAcdtgEfydbaeclfgKydbgOSmbcjjjj94cba8EaOcdtfydbaASEhCkaeaQaCVaAVBdbaYaOfRbbc3th8Fcjjjj94hCcjjjj94hQdna5aOcdtfydbaHSmbcjjjj94cba8EaHcdtfydbaOSEhQkaKa8FaQVaOVBdbaYaHfRbbc3thOdna5aHcdtfydbaASmbcjjjj94cba8EaEfydbaHSEhCkaXaOaCVaHVBdbaecxfheaLcifgLaa6mbkkdnazTmbaaTmbaaheinabazabydbcdtfydbBdbabclfhbaecufgembkkdnaPTmbaPaZaU:rNUdbkdnasyd;8egHTmbaHcdtasc:Ceffc98fheinaeydbcbyd:m:H:cjbH:bjjjbbaec98fheaHcufgHmbkkascj;sbf8Kjjjjbaak;Yieouabydlhvabydbclfcbaicdtz:tjjjbhoadci9UhrdnadTmbdnalTmbaehwadhDinaoalawydbcdtfydbcdtfgqaqydbcefBdbawclfhwaDcufgDmbxdkkaehwadhDinaoawydbcdtfgqaqydbcefBdbawclfhwaDcufgDmbkkdnaiTmbcbhDaohwinawydbhqawaDBdbawclfhwaqaDfhDaicufgimbkkdnadci6mbinaecwfydbhwaeclfydbhDaeydbhidnalTmbalawcdtfydbhwalaDcdtfydbhDalaicdtfydbhikavaoaicdtfgqydbcitfaDBdbavaqydbcitfawBdlaqaqydbcefBdbavaoaDcdtfgqydbcitfawBdbavaqydbcitfaiBdlaqaqydbcefBdbavaoawcdtfgwydbcitfaiBdbavawydbcitfaDBdlawawydbcefBdbaecxfhearcufgrmbkkabydbcbBdbk:todDue99aicd4aifhrcehwinawgDcethwaDar6mbkcuaDcdtgraDcFFFFi0Ecbyd1:H:cjbHjjjjbbhwaoaoyd9GgqcefBd9GaoaqcdtfawBdbawcFearz:tjjjbhkdnaiTmbalcd4hlaDcufhxcbhminamhDdnavTmbavamcdtfydbhDkcbadaDal2cdtfgDydlgwawcjjjj94SEgwcH4aw7c:F:b:DD2cbaDydbgwawcjjjj94SEgwcH4aw7c;D;O:B8J27cbaDydwgDaDcjjjj94SEgDcH4aD7c:3F;N8N27axGhwamcdthPdndndnavTmbakawcdtfgrydbgDcuSmeadavaPfydbal2cdtfgsIdbhzcehqinaqhrdnadavaDcdtfydbal2cdtfgqIdbaz9CmbaqIdlasIdl9CmbaqIdwasIdw9BmlkarcefhqakawarfaxGgwcdtfgrydbgDcu9hmbxdkkakawcdtfgrydbgDcuSmbadamal2cdtfgsIdbhzcehqinaqhrdnadaDal2cdtfgqIdbaz9CmbaqIdlasIdl9CmbaqIdwasIdw9BmikarcefhqakawarfaxGgwcdtfgrydbgDcu9hmbkkaramBdbamhDkabaPfaDBdbamcefgmai9hmbkkakcbyd:m:H:cjbH:bjjjbbaoaoyd9GcufBd9GdnaeTmbaiTmbcbhDaehwinawaDBdbawclfhwaiaDcefgD9hmbkcbhDaehwindnaDabydbgrSmbawaearcdtfgrydbBdbaraDBdbkabclfhbawclfhwaiaDcefgD9hmbkkk;:odvuv998Jjjjjbca9Rgocbyd1:G:cjbBdKaocb8Pdj:G:cjb83izaocbydN:G:cjbBdwaocb8Pd:m:G:cjb83ibdnadTmbaicd4hrdnabmbdnalTmbcbhwinaealawcdtfydbar2cdtfhDcbhiinaoczfaifgqaDaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkawcefgwad9hmbxikkarcdthwcbhDincbhiinaoczfaifgqaeaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkaeawfheaDcefgDad9hmbxdkkdnalTmbcbhwinabawcx2fgiaealawcdtfydbar2cdtfgDIdbUdbaiaDIdlUdlaiaDIdwUdwcbhiinaoczfaifgqaDaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkawcefgwad9hmbxdkkarcdthlcbhwaehDinabawcx2fgiaeawar2cdtfgqIdbUdbaiaqIdlUdlaiaqIdwUdwcbhiinaoczfaifgqaDaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkaDalfhDawcefgwad9hmbkkJbbbbaoIdbaoIdzgx:tgkakJbbbb9DEgkaoIdlaoIdCgm:tgPaPak9DEgkaoIdwaoIdKgP:tgsasak9DEhsdnabTmbadTmbJbbbbJbbjZas:vasJbbbb9BEhkinabakabIdbax:tNUdbabclfgoakaoIdbam:tNUdbabcwfgoakaoIdbaP:tNUdbabcxfhbadcufgdmbkkdnavTmbavaPUdwavamUdlavaxUdbkask:WlewudnaeTmbcbhvabhoinaoavBdbaoclfhoaeavcefgv9hmbkkdnaiTmbcbhrinadarcdtfhwcbhDinalawaDcdtgvyd:G:G:cjbcdtfydbcdtfydbhodnalawavfydbcdtfydbgqabaqcdtfgkydbgvSmbinakabavgqcdtfgxydbgvBdbaxhkaqav9hmbkkdnaoabaocdtfgkydbgvSmbinakabavgocdtfgxydbgvBdbaxhkaoav9hmbkkdnaqaoSmbabaqaoaqao0Ecdtfaqaoaqao6EBdbkaDcefgDci9hmbkarcifgrai6mbkkdnaembcbskcbhxindnalaxcdtgvfydbax9hmbaxhodnaxabavfgDydbgvSmbaDhqinaqabavgocdtfgkydbgvBdbakhqaoav9hmbkkaDaoBdbkaxcefgxae9hmbkcbhkabhvcbhoindndnaoalydbgq9hmbdnaoavydbgq9hmbavakBdbakcefhkxdkavabaqcdtfydbBdbxekavabaqcdtfydbBdbkalclfhlavclfhvaeaocefgo9hmbkakk;jiilud99euabcbaecltz:tjjjbhvdnalTmbadhoaihralhwinarcwfIdbhDarclfIdbhqavaoydbcltfgkarIdbakIdbMUdbakaqakIdlMUdlakaDakIdwMUdwakakIdxJbbjZMUdxaoclfhoarcxfhrawcufgwmbkkdnaeTmbavhkaehrinakcxfgoIdbhDaocbBdbakakIdbJbbbbJbbjZaD:vaDJbbbb9BEgDNUdbakclfgoaDaoIdbNUdbakcwfgoaDaoIdbNUdbakczfhkarcufgrmbkkdnalTmbinavadydbcltfgkaicwfIdbakIdw:tgDaDNaiIdbakIdb:tgDaDNaiclfIdbakIdl:tgDaDNMMgDakIdxgqaqaD9DEUdxadclfhdaicxfhialcufglmbkkdnaeTmbavcxfhkinabakIdbUdbakczfhkabclfhbaecufgembkkk:moerudnaoTmbaecd4hzdnavTmbaicd4hHavcdthOcbhAindnaPaAfRbbTmbaAhednaDTmbaDaAcdtfydbhekdnasTmbasaefRbbceGmekdnamaAfRbbclSmbabaeaz2cdtfgiaraAcx2fgCIdbakNaxIdbMUdbaiaCIdlakNaxIdlMUdlaiaCIdwakNaxIdwMUdwkadaeaH2cdtfhXaqheawhiavhCinaXaeydbcdtgQfaiIdbalaQfIdb:vUdbaeclfheaiclfhiaCcufgCmbkkawaOfhwaAcefgAao9hmbxdkkdnasmbcbheaDhiindnaPaefRbbTmbaehCdnaDTmbaiydbhCkamaefRbbclSmbabaCaz2cdtfgCarIdbakNaxIdbMUdbaCarclfIdbakNaxIdlMUdlaCarcwfIdbakNaxIdwMUdwkaiclfhiarcxfhraoaecefge9hmbxdkkdnaDTmbindnaPRbbTmbasaDydbgefRbbceGmbamRbbclSmbabaeaz2cdtfgearIdbakNaxIdbMUdbaearclfIdbakNaxIdlMUdlaearcwfIdbakNaxIdwMUdwkaPcefhPaDclfhDamcefhmarcxfhraocufgombxdkkazcdthicbheindnaPaefRbbTmbasaefRbbceGmbamaefRbbclSmbabarIdbakNaxIdbMUdbabclfarclfIdbakNaxIdlMUdbabcwfarcwfIdbakNaxIdwMUdbkarcxfhrabaifhbaoaecefge9hmbkkk8MbabaeadaialavcbcbcbcbcbaoarawaDz:bjjjbk8MbabaeadaialavaoarawaDaqakaxamaPz:bjjjbkRbababaeadaialavaoarawaDaqakaxcjjjjdVamz:bjjjbk:g8Koque99due99duq998Jjjjjbc;Wb9Rgq8Kjjjjbcbhkaqcxfcbc;Kbz:tjjjb8Aaqcualcx2alc;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbgxBdxaqceBd2axaialavcbcbz:ejjjb8AaqcualcdtalcFFFFi0Egmcbyd1:H:cjbHjjjjbbgiBdzaqcdBd2dndnJFF959eJbbjZawJbbjZawJbbjZ9DE:vawJ9VO:d869DEgw:lJbbb9p9DTmbaw:OhPxekcjjjj94hPkadci9Uhsarco9UhzdndnaombaPcd9imekdnalTmbaPcuf:YhwdnaoTmbcbhvaihHaxhOindndnaoavfRbbceGTmbavcjjjjlVhAxekdndnaOclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcqthAdndnaOcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXVhAdndnaOIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXcCtVhAkaHaABdbaHclfhHaOcxfhOalavcefgv9hmbxdkkaxhvaihOalhHindndnavIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcCthAdndnavclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcqtaAVhAdndnavcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaOaAaXVBdbavcxfhvaOclfhOaHcufgHmbkkadTmbcbhkaehvcbhOinakaiavclfydbcdtfydbgHaiavcwfydbcdtfydbgA9haiavydbcdtfydbgXaH9haXaA9hGGfhkavcxfhvaOcifgOad6mbkkarci9UhQdndnaz:Z:rJbbbZMgw:lJbbb9p9DTmbaw:Ohvxekcjjjj94hvkaQ:ZhLcbhKc:bwhzdninakaQ9pmeazaP9Rcd9imeavazcufgOavaO9iEaPcefavaP9kEhYdnalTmbaYcuf:YhwdnaoTmbcbhOaihHaxhvindndnaoaOfRbbceGTmbaOcjjjjlVhAxekdndnavclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcqthAdndnavcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXVhAdndnavIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXcCtVhAkaHaABdbaHclfhHavcxfhvalaOcefgO9hmbxdkkaxhvaihOalhHindndnavIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcCthAdndnavclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcqtaAVhAdndnavcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaOaAaXVBdbavcxfhvaOclfhOaHcufgHmbkkcbhOdnadTmbaehvcbhHinaOaiavclfydbcdtfydbgAaiavcwfydbcdtfydbgX9haiavydbcdtfydbgraA9haraX9hGGfhOavcxfhvaHcifgHad6mbkkdnas:ZgCaL:taY:Ygwaz:Y:tg8ANak:ZgEaO:Zg3:tNaEaL:tawaP:Y:tg5Na3aC:tNMg8EJbbbb9BmbaCaE:ta5a8Aa3aL:tNNNa8E:vawMhwkdndnaOaQ0mbaOhkaYhPxekaOhsaYhzkdndnaKcl0mbdnawJbbbZMgw:lJbbb9p9DTmbaw:Ohvxdkcjjjj94hvxekaPazfcd9ThvkaKcefgKcs9hmbkkdndndnakmbJbbjZhwcbhOcdhvaDmexdkalcd4alfhHcehOinaOgvcethOavaH6mbkcbhOaqcuavcdtgYavcFFFFi0Ecbyd1:H:cjbHjjjjbbgKBdCaqciBd2aqamcbyd1:H:cjbHjjjjbbgzBdKaqclBd2dndndndnalTmbaPcuf:YhwaoTmecbhOaihAaxhHindndnaoaOfRbbceGTmbaOcjjjjlVhXxekdndnaHclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcqthXdndnaHcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkaXarVhXdndnaHIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkaXarcCtVhXkaAaXBdbaAclfhAaHcxfhHalaOcefgO9hmbxikkaKcFeaYz:tjjjb8AcbhPcbhvxdkaxhOaihHalhAindndnaOIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcCthXdndnaOclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkarcqtaXVhXdndnaOcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkaHaXarVBdbaOcxfhOaHclfhHaAcufgAmbkkaKcFeaYz:tjjjbhravcufhocbhPcbhYindndndnaraiaYcdtgKfydbgAcm4aA7c:v;t;h;Ev2gvcs4av7aoGgHcdtfgXydbgOcuSmbcehvinaiaOcdtgOfydbaASmdaHavfhOavcefhvaraOaoGgHcdtfgXydbgOcu9hmbkkaXaYBdbaPhvaPcefhPxekazaOfydbhvkazaKfavBdbaYcefgYal9hmbkcuaPc8S2gOaPc;D;O;f8U0EhvkcbhXaqavcbyd1:H:cjbHjjjjbbgvBd3aqcvBd2avcbaOz:tjjjbhOdnadTmbaehiinaxaiclfydbgrcx2fgvIdbaxaiydbgocx2fgHIdbg3:tgCaxaicwfydbgYcx2fgAIdlaHIdlg8A:tgwNavIdla8A:tgEaAIdba3:tg8EN:tgLaLNaEaAIdwaHIdwg5:tg8FNavIdwa5:tgEawN:tgwawNaEa8ENaCa8FN:tgCaCNMMg8E:rhEJbbnnJbbjZazaocdtfydbgvazarcdtfydbgASavazaYcdtfydbgrSGgHEh8Fdna8EJbbbb9ETmbaLaE:vhLaCaE:vhCawaE:vhwkaOavc8S2fgvavIdbawa8FaE:rNgEawNNg8FMUdbavaCaEaCNgaNghavIdlMUdlavaLaEaLNg8ENggavIdwMUdwavawaaNgaavIdxMUdxava8EawNg8JavIdzMUdzavaCa8ENg8EavIdCMUdCavawaEaLa5Nawa3Na8AaCNMM:mg8ANg3NgwavIdKMUdKavaCa3NgCavId3MUd3avaLa3NgLavIdaMUdaava3a8ANg3avId8KMUd8KavaEavIdyMUdydnaHmbaOaAc8S2fgva8FavIdbMUdbavahavIdlMUdlavagavIdwMUdwavaaavIdxMUdxava8JavIdzMUdzava8EavIdCMUdCavawavIdKMUdKavaCavId3MUd3avaLavIdaMUdaava3avId8KMUd8KavaEavIdyMUdyaOarc8S2fgva8FavIdbMUdbavahavIdlMUdlavagavIdwMUdwavaaavIdxMUdxava8JavIdzMUdzava8EavIdCMUdCavawavIdKMUdKavaCavId3MUd3avaLavIdaMUdaava3avId8KMUd8KavaEavIdyMUdykaicxfhiaXcifgXad6mbkkcbhAaqcuaPcdtgvaPcFFFFi0Egicbyd1:H:cjbHjjjjbbgHBdaaqcoBd2aqaicbyd1:H:cjbHjjjjbbgiBd8KaqcrBd2aHcFeavz:tjjjbhYdnalTmbazhHinJbbbbJbbjZaOaHydbgXc8S2fgvIdygw:vawJbbbb9BEavIdwaxcwfIdbgwNavIdzaxIdbgCNavIdaMgLaLMMawNavIdlaxclfIdbgLNavIdCawNavId3MgwawMMaLNavIdbaCNavIdxaLNavIdKMgwawMMaCNavId8KMMM:lNhwdndnaYaXcdtgvfgXydbcuSmbaiavfIdbaw9ETmekaXaABdbaiavfawUdbkaHclfhHaxcxfhxalaAcefgA9hmbkkdndnaPmbJbbbbhwxekJbbbbhwinaiIdbgCawawaC9DEhwaiclfhiaPcufgPmbkaw:rhwkakcd4akfhOcehiinaigvcethiavaO6mbkcbhOaqcuavcdtgiavcFFFFi0Ecbyd1:H:cjbHjjjjbbgHBdyaHcFeaiz:tjjjbhXdnadTmbavcufhrcbhPcbhxindnazaeaxcdtfgvydbcdtfydbgiazavclfydbcdtfydbgOSmbaiazavcwfydbcdtfydbgvSmbaOavSmbaYavcdtfydbhAdndnaYaOcdtfydbgvaYaicdtfydbgi9pmbavaA9pmbaAhlaihoavhAxekdnaAai9pmbaAav9pmbaihlavhoxekavhlaAhoaihAkabaPcx2fgvaABdbavcwfaoBdbavclfalBdbdnaXaoc:3F;N8N2alc:F:b:DD27aAc;D;O:B8J27arGgOcdtfgvydbgicuSmbcehHinaHhvdnabaicx2fgiydbaA9hmbaiydlal9hmbaiydwaoSmikavcefhHaXaOavfarGgOcdtfgvydbgicu9hmbkkavaPBdbaPcefhPkaxcifgxad6mbkaPci2hOkcwhvaDTmekaDawUdbkavcdthvaqcxfc98fhiinaiavfydbcbyd:m:H:cjbH:bjjjbbavc98fgvmbkaqc;Wbf8KjjjjbaOk:3ldrue9:8Jjjjjbc;Wb9Rgr8Kjjjjbcbhwarcxfcbc;Kbz:tjjjb8AdnabaeSmbabaeadcdtzMjjjb8AkarcualcdtalcFFFFi0EgDcbyd1:H:cjbHjjjjbbgqBdxarceBd2aqcbaialavcbarcxfz:djjjbcualcx2alc;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbhkarcxfaryd2gxcdtfakBdbaraxcefgmBd2akaialavcbcbz:ejjjb8AarcxfamcdtfaDcbyd1:H:cjbHjjjjbbgiBdbaraxcdfgvBd2arcxfavcdtfcuaialaeadaqz:fjjjbgecltaecjjjjiGEcbyd1:H:cjbHjjjjbbgqBdbaqaeaiakalz:gjjjbaxcifhkdnadTmbaoaoNhocbhwabhlcbheindnaqaialydbgvcdtfydbcdtfIdbao9ETmbalclf8PdbhPabawcdtfgDavBdbaDclfaP83dbawcifhwkalcxfhlaecifgead6mbkkdnakTmbaxcdtarcxffcwfhlinalydbcbyd:m:H:cjbH:bjjjbbalc98fhlakcufgkmbkkarc;Wbf8Kjjjjbawk:WCoDud99vue99vuv998Jjjjjbc;Wb9Rgw8KjjjjbdndnarmbcbhDxekawcxfcbc;Kbz:tjjjb8Aawcuadcx2adc;v:Q;v:Qe0Ecbyd1:H:cjbHjjjjbbgqBdxawceBd2aqaeadaicbcbz:ejjjb8AawcuadcdtadcFFFFi0Egkcbyd1:H:cjbHjjjjbbgxBdzawcdBd2adcd4adfhmceheinaegicetheaiam6mbkcbhPawcuaicdtgsaicFFFFi0Ecbyd1:H:cjbHjjjjbbgzBdCawciBd2dndnar:ZgH:rJbbbZMgO:lJbbb9p9DTmbaO:Ohexekcjjjj94hekaicufhAc:bwhCcbhXadhQcbhLinaeaCcufgiaeai9iEaPcefaeaP9kEhDdndnadTmbaDcuf:YhOaqhiaxheadhmindndnaiIdbaONJbbbZMgK:lJbbb9p9DTmbaK:OhYxekcjjjj94hYkaYcCthYdndnaiclfIdbaONJbbbZMgK:lJbbb9p9DTmbaK:Oh8Axekcjjjj94h8Aka8AcqtaYVhYdndnaicwfIdbaONJbbbZMgK:lJbbb9p9DTmbaK:Oh8Axekcjjjj94h8AkaeaYa8AVBdbaicxfhiaeclfheamcufgmmbkazcFeasz:tjjjbhEcbh3cbh5indnaEaxa5cdtfydbgYcm4aY7c:v;t;h;Ev2gics4ai7aAGgmcdtfg8AydbgecuSmbaeaYSmbcehiinaEamaifaAGgmcdtfg8AydbgecuSmeaicefhiaeaY9hmbkka8AaYBdba3aecuSfh3a5cefg5ad9hmbxdkkazcFeasz:tjjjb8Acbh3kdnaQ:ZgKaH:taD:YgOaC:Y:tg8ENaX:Zg8Fa3:Zga:tNa8FaH:taOaP:Y:tghNaaaK:tNMggJbbbb9BmbaKa8F:taha8EaaaH:tNNNag:vaOMhOkaPaDa3ar0giEhPaXa3aiEhXdna3arSmbaDaCaiEgCaP9Rcd9imbdndnaLcl0mbdnaOJbbbZMgO:lJbbb9p9DTmbaO:Ohexdkcjjjj94hexekaPaCfcd9Theka3aQaiEhQaLcefgLcs9hmekkdndnaXmbcihicbhDxekcbhiawakcbyd1:H:cjbHjjjjbbg5BdKawclBd2aPcuf:YhKdndnadTmbaqhiaxheadhmindndnaiIdbaKNJbbbZMgO:lJbbb9p9DTmbaO:OhYxekcjjjj94hYkaYcCthYdndnaiclfIdbaKNJbbbZMgO:lJbbb9p9DTmbaO:Oh8Axekcjjjj94h8Aka8AcqtaYVhYdndnaicwfIdbaKNJbbbZMgO:lJbbb9p9DTmbaO:Oh8Axekcjjjj94h8AkaeaYa8AVBdbaicxfhiaeclfheamcufgmmbkazcFeasz:tjjjbhEcbhDcbh3indndndnaEaxa3cdtgCfydbgYcm4aY7c:v;t;h;Ev2gics4ai7aAGgmcdtfg8AydbgecuSmbcehiinaxaecdtgefydbaYSmdamaifheaicefhiaEaeaAGgmcdtfg8Aydbgecu9hmbkka8Aa3BdbaDhiaDcefhDxeka5aefydbhika5aCfaiBdba3cefg3ad9hmbkcuaDc32giaDc;j:KM;jb0EhexekazcFeasz:tjjjb8AcbhDcbhekawaecbyd1:H:cjbHjjjjbbgeBd3awcvBd2aecbaiz:tjjjbh8Aavcd4hxdnadTmbdnalTmbaxcdthEa5hYaqhealhmadhAina8AaYydbc32fgiaeIdbaiIdbMUdbaiaeclfIdbaiIdlMUdlaiaecwfIdbaiIdwMUdwaiamIdbaiIdxMUdxaiamclfIdbaiIdzMUdzaiamcwfIdbaiIdCMUdCaiaiIdKJbbjZMUdKaYclfhYaecxfheamaEfhmaAcufgAmbxdkka5hmaqheadhYina8Aamydbc32fgiaeIdbaiIdbMUdbaiaeclfIdbaiIdlMUdlaiaecwfIdbaiIdwMUdwaiaiIdxJbbbbMUdxaiaiIdzJbbbbMUdzaiaiIdCJbbbbMUdCaiaiIdKJbbjZMUdKamclfhmaecxfheaYcufgYmbkkdnaDTmba8AhiaDheinaiaiIdbJbbbbJbbjZaicKfIdbgO:vaOJbbbb9BEgONUdbaiclfgmaOamIdbNUdbaicwfgmaOamIdbNUdbaicxfgmaOamIdbNUdbaiczfgmaOamIdbNUdbaicCfgmaOamIdbNUdbaic3fhiaecufgembkkcbhYawcuaDcdtgCaDcFFFFi0Egicbyd1:H:cjbHjjjjbbgeBdaawcoBd2awaicbyd1:H:cjbHjjjjbbgEBd8KaecFeaCz:tjjjbh3dnadTmbaoJbbjZJbbjZaK:vaPceSENgOaONhKaxcdthxalheinaKaec;8:G:cjbalEgmIdwa8Aa5ydbgAc32fgiIdC:tgOaONamIdbaiIdx:tgOaONamIdlaiIdz:tgOaONMMNaqcwfIdbaiIdw:tgOaONaqIdbaiIdb:tgOaONaqclfIdbaiIdl:tgOaONMMMhOdndna3aAcdtgifgmydbcuSmbaEaifIdbaO9ETmekamaYBdbaEaifaOUdbka5clfh5aqcxfhqaeaxfheadaYcefgY9hmbkkaba3aCzMjjjb8Acrhikaicdthiawcxfc98fheinaeaifydbcbyd:m:H:cjbH:bjjjbbaic98fgimbkkawc;Wbf8KjjjjbaDk:Pdidui99ducbhi8Jjjjjbca9Rglcbyd1:G:cjbBdKalcb8Pdj:G:cjb83izalcbydN:G:cjbBdwalcb8Pd:m:G:cjb83ibdndnaembJbbjFhvJbbjFhoJbbjFhrxekadcd4cdthwincbhdinalczfadfgDabadfIdbgvaDIdbgoaoav9EEUdbaladfgDavaDIdbgoaoav9DEUdbadclfgdcx9hmbkabawfhbaicefgiae9hmbkalIdwalIdK:thralIdlalIdC:thoalIdbalIdz:thvkJbbbbavavJbbbb9DEgvaoaoav9DEgvararav9DEk9DeeuabcFeaicdtz:tjjjbhlcbhbdnadTmbindnalaeydbcdtfgiydbcu9hmbaiabBdbabcefhbkaeclfheadcufgdmbkkabk;Bidqui998Jjjjjbc;Wb9Rgl8Kjjjjbalcxfcbc;Kbz:tjjjb8Aadcd4adfhvcehoinaogrcethoarav6mbkalcuarcdtgoarcFFFFi0Ecbyd1:H:cjbHjjjjbbgvBdxavcFeaoz:tjjjbhwdnadTmbaicd4hDarcufhqcbhkindndnawcbaeakaD2cdtfgrydlgiaicjjjj94SEgocH4ao7c:F:b:DD2cbarydbgxaxcjjjj94SEgocH4ao7c;D;O:B8J27cbarydwgmamcjjjj94SEgrcH4ar7c:3F;N8N27aqGgvcdtfgrydbgocuSmbam::hPai::hsax::hzcehiinaihrdnaeaoaD2cdtfgiIdbaz9CmbaiIdlas9CmbaiIdwaP9BmikarcefhiawavarfaqGgvcdtfgrydbgocu9hmbkkarakBdbakhokabakcdtfaoBdbakcefgkad9hmbkkalydxcbyd:m:H:cjbH:bjjjbbalc;Wbf8Kjjjjbk9teiucbcbyd:q:H:cjbgeabcifc98GfgbBd:q:H:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabk9teiucbcbyd:q:H:cjbgeabcrfc94GfgbBd:q:H:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikTeeucbabcbyd:q:H:cjbge9Rcifc98GaefgbBd:q:H:cjbdnabZbcztge9nmbabae9RcFFifcz4nb8Akkk:Kedbcj:Gdk1eFFuuFFuuFFuuFFuFFFuFFFuFbbbbbbbbebbbdbbbbbbbebbbebbbdbbbbbbbbbbbeeeeebebbebbebebbbeebbbbbbbbbbbbeeeeeebebbeeebeebbbbebebbbbbbbbbbbbbbbbbbc1:Hdkxebbbdbbb:G:qbb",t=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!=="object")return{supported:!1};var n,i=WebAssembly.instantiate(r(e),{}).then(function(x){n=x.instance,n.exports.__wasm_call_ctors()});function r(x){var _=new Uint8Array(x.length);for(var y=0;y<x.length;++y){var v=x.charCodeAt(y);_[y]=v>96?v-97:v>64?v-39:v+4}var E=0;for(var y=0;y<x.length;++y)_[E++]=_[y]<60?t[_[y]]:(_[y]-60)*64+_[++y];return _.buffer.slice(0,E)}function s(x){if(!x)throw Error("Assertion failed")}function a(x){return new Uint8Array(x.buffer,x.byteOffset,x.byteLength)}function o(x,_,y,v){var E=n.exports.sbrk,w=E(y*4),T=E(y*v*4),A=new Uint8Array(n.exports.memory.buffer);A.set(a(_),T),x(w,T,y,v*4),A=new Uint8Array(n.exports.memory.buffer);var P=new Uint32Array(y);return new Uint8Array(P.buffer).set(A.subarray(w,w+y*4)),E(w-E(0)),P}function c(x,_,y){var v=n.exports.sbrk,E=v(_.length*4),w=v(y*4),T=new Uint8Array(n.exports.memory.buffer),A=a(_);T.set(A,E);var P=x(w,E,_.length,y);T=new Uint8Array(n.exports.memory.buffer);var S=new Uint32Array(y);new Uint8Array(S.buffer).set(T.subarray(w,w+y*4)),v(E-v(0));for(var R=0;R<_.length;++R)_[R]=S[_[R]];return[S,P]}function l(x){var _=0;for(var y=0;y<x.length;++y){var v=x[y];_=_<v?v:_}return _}function u(x,_,y,v,E,w,T,A,P){var S=n.exports.sbrk,R=S(4),k=S(y*4),C=S(E*w),U=S(y*4),L=new Uint8Array(n.exports.memory.buffer);L.set(a(v),C),L.set(a(_),U);var O=x(k,U,y,C,E,w,T,A,P,R);L=new Uint8Array(n.exports.memory.buffer);var K=new Uint32Array(O);a(K).set(L.subarray(k,k+O*4));var B=new Float32Array(1);return a(B).set(L.subarray(R,R+4)),S(R-S(0)),[K,B[0]]}function d(x,_,y,v,E,w,T,A,P,S,R,k,C){var U=n.exports.sbrk,L=U(4),O=U(y*4),K=U(E*w),B=U(E*A),X=U(P.length*4),q=U(y*4),le=S?U(E):0,de=new Uint8Array(n.exports.memory.buffer);if(de.set(a(v),K),de.set(a(T),B),de.set(a(P),X),de.set(a(_),q),S)de.set(a(S),le);var Me=x(O,q,y,K,E,w,B,A,X,P.length,le,R,k,C,L);de=new Uint8Array(n.exports.memory.buffer);var pe=new Uint32Array(Me);a(pe).set(de.subarray(O,O+Me*4));var J=new Float32Array(1);return a(J).set(de.subarray(L,L+4)),U(L-U(0)),[pe,J[0]]}function f(x,_,y,v,E,w,T,A,P,S,R,k,C){var U=n.exports.sbrk,L=U(4),O=U(E*w),K=U(E*A),B=U(P.length*4),X=U(y*4),q=S?U(E):0,le=new Uint8Array(n.exports.memory.buffer);if(le.set(a(v),O),le.set(a(T),K),le.set(a(P),B),le.set(a(_),X),S)le.set(a(S),q);var de=x(X,y,O,E,w,K,A,B,P.length,q,R,k,C,L);le=new Uint8Array(n.exports.memory.buffer),a(_).set(le.subarray(X,X+de*4)),a(v).set(le.subarray(O,O+E*w)),a(T).set(le.subarray(K,K+E*A));var Me=new Float32Array(1);return a(Me).set(le.subarray(L,L+4)),U(L-U(0)),[de,Me[0]]}function h(x,_,y,v){var E=n.exports.sbrk,w=E(y*v),T=new Uint8Array(n.exports.memory.buffer);T.set(a(_),w);var A=x(w,y,v);return E(w-E(0)),A}function b(x,_,y,v,E,w,T,A){var P=n.exports.sbrk,S=P(A*4),R=P(y*v),k=E?P(y*w):0,C=new Uint8Array(n.exports.memory.buffer);if(C.set(a(_),R),E)C.set(a(E),k);var U=x(S,R,y,v,k,w,T,A);C=new Uint8Array(n.exports.memory.buffer);var L=new Uint32Array(U);return a(L).set(C.subarray(S,S+U*4)),P(S-P(0)),L}function m(x,_,y,v,E,w,T,A,P){var S=n.exports.sbrk,R=S(4),k=S(y*4),C=S(E*w),U=S(y*4),L=T?S(E):0,O=new Uint8Array(n.exports.memory.buffer);if(O.set(a(v),C),O.set(a(_),U),T)O.set(a(T),L);var K=x(k,U,y,C,E,w,L,A,P,R);O=new Uint8Array(n.exports.memory.buffer);var B=new Uint32Array(K);a(B).set(O.subarray(k,k+K*4));var X=new Float32Array(1);return a(X).set(O.subarray(R,R+4)),S(R-S(0)),[B,X[0]]}function g(x,_,y,v,E,w,T){var A=n.exports.sbrk,P=A(y*4),S=A(E*w),R=A(y*4),k=new Uint8Array(n.exports.memory.buffer);k.set(a(v),S),k.set(a(_),R);var C=x(P,R,y,S,E,w,T);k=new Uint8Array(n.exports.memory.buffer);var U=new Uint32Array(C);return a(U).set(k.subarray(P,P+C*4)),A(P-A(0)),U}var p={LockBorder:1,Sparse:2,ErrorAbsolute:4,Prune:8,Regularize:16,Permissive:32,_InternalDebug:1073741824};return{ready:i,supported:!0,compactMesh:function(x){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0);var _=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),y=c(n.exports.meshopt_optimizeVertexFetchRemap,_,l(x)+1);if(x!==_)for(var v=0;v<_.length;++v)x[v]=_[v];return y},generatePositionRemap:function(x,_){return s(x instanceof Float32Array),s(x.length%_==0),s(_>=3),o(n.exports.meshopt_generatePositionRemap,x,x.length/_,_)},simplify:function(x,_,y,v,E,w){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v>=0&&v<=x.length),s(v%3==0),s(E>=0);var T=0;for(var A=0;A<(w?w.length:0);++A)s(w[A]in p),T|=p[w[A]];var P=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),S=u(n.exports.meshopt_simplify,P,x.length,_,_.length/y,y*4,v,E,T);return S[0]=x instanceof Uint32Array?S[0]:new x.constructor(S[0]),S},simplifyWithAttributes:function(x,_,y,v,E,w,T,A,P,S){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v instanceof Float32Array),s(v.length==E*(_.length/y)),s(E>=0),s(T==null||T instanceof Uint8Array),s(T==null||T.length==_.length/y),s(A>=0&&A<=x.length),s(A%3==0),s(P>=0),s(Array.isArray(w)),s(E>=w.length),s(w.length<=32);for(var R=0;R<w.length;++R)s(w[R]>=0);var k=0;for(var R=0;R<(S?S.length:0);++R)s(S[R]in p),k|=p[S[R]];var C=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),U=d(n.exports.meshopt_simplifyWithAttributes,C,x.length,_,_.length/y,y*4,v,E*4,new Float32Array(w),T,A,P,k);return U[0]=x instanceof Uint32Array?U[0]:new x.constructor(U[0]),U},simplifyWithUpdate:function(x,_,y,v,E,w,T,A,P,S){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v instanceof Float32Array),s(v.length==E*(_.length/y)),s(E>=0),s(T==null||T instanceof Uint8Array),s(T==null||T.length==_.length/y),s(A>=0&&A<=x.length),s(A%3==0),s(P>=0),s(Array.isArray(w)),s(E>=w.length),s(w.length<=32);for(var R=0;R<w.length;++R)s(w[R]>=0);var k=0;for(var R=0;R<(S?S.length:0);++R)s(S[R]in p),k|=p[S[R]];var C=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),U=f(n.exports.meshopt_simplifyWithUpdate,C,x.length,_,_.length/y,y*4,v,E*4,new Float32Array(w),T,A,P,k);if(x!==C)for(var R=0;R<U[0];++R)x[R]=C[R];return U},getScale:function(x,_){return s(x instanceof Float32Array),s(x.length%_==0),s(_>=3),h(n.exports.meshopt_simplifyScale,x,x.length/_,_*4)},simplifyPoints:function(x,_,y,v,E,w){if(s(x instanceof Float32Array),s(x.length%_==0),s(_>=3),s(y>=0&&y<=x.length/_),v)return s(v instanceof Float32Array),s(v.length%E==0),s(E>=3),s(x.length/_==v.length/E),b(n.exports.meshopt_simplifyPoints,x,x.length/_,_*4,v,E*4,w||0,y);else return b(n.exports.meshopt_simplifyPoints,x,x.length/_,_*4,void 0,0,0,y)},simplifySloppy:function(x,_,y,v,E,w){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v==null||v instanceof Uint8Array),s(v==null||v.length==_.length/y),s(E>=0&&E<=x.length),s(E%3==0),s(w>=0);var T=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),A=m(n.exports.meshopt_simplifySloppy,T,x.length,_,_.length/y,y*4,v,E,w);return A[0]=x instanceof Uint32Array?A[0]:new x.constructor(A[0]),A},simplifyPrune:function(x,_,y,v){s(x instanceof Uint32Array||x instanceof Int32Array||x instanceof Uint16Array||x instanceof Int16Array),s(x.length%3==0),s(_ instanceof Float32Array),s(_.length%y==0),s(y>=3),s(v>=0);var E=x.BYTES_PER_ELEMENT==4?x:new Uint32Array(x),w=g(n.exports.meshopt_simplifyPrune,E,x.length,_,_.length/y,y*4,v);return w=x instanceof Uint32Array?w:new x.constructor(w),w}}}()});var mX;var vR=ht(()=>{mX=function(){var e="b9H79Tebbbe:neP9Geueu9Geub9Gbb9Giuuueu9Gmuuuuuuuuuuu9999eu9Gouuuuuueu9Gruuuuuuub9Gxuuuuuuuuuuuueu9Gxuuuuuuuuuuu99eu9GPuuuuuuuuuuuuu99b9Gouuuuuub9Gwuuuuuuuub9Gvuuuuub9GluuuubiQXdilvorwDqokoqxmbiibeilve9Weiiviebeoweuecj:Gdkr;Zeqo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9I919P29K9nW79O2Wt79c9V919U9KbeY9TW79O9V9Wt9F9I919P29K9nW79O2Wt7S2W94bd39TW79O9V9Wt9F9I919P29K9nW79O2Wt79t9W9Ht9P9H2bo39TW79O9V9Wt9F9J9V9T9W91tWJ2917tWV9c9V919U9K7bw39TW79O9V9Wt9F9J9V9T9W91tW9nW79O2Wt9c9V919U9K7bkE9TW79O9V9Wt9F9J9V9T9W91tW9t9W9OWVW9c9V919U9K7bxL9TW79O9V9Wt9F9V9Wt9P9T9P96W9nW79O2WtbPl79IV9RbsDwebcekdOAq;W:leXdbkIbabaec9:fgefcufae9Ugeabci9Uadfcufad9Ugbaeab0Ek:88JDPue99eux99due99euo99iu8Jjjjjbc:WD9Rgm8KjjjjbdndnalmbcbhPxekamc:Cwfcbc;Kbz:rjjjb8AcuaocdtgsaocFFFFi0Ehzcbyd;0:G:cjbhHdndnalcb9imbaoal9nmbamazaHHjjjjbbgHBd:CwamceBd;8wamazcbyd;0:G:cjbHjjjjbbgOBd:GwamcdBd;8wamcualcdtalcFFFFi0Ecbyd;0:G:cjbHjjjjbbgABd:KwamciBd;8waihzalhsinaHazydbcdtfcbBdbazclfhzascufgsmbkaihzalhsinaHazydbcdtfgCaCydbcefBdbazclfhzascufgsmbkaihzalhCcbhXindnaHazydbcdtgQfgsydbcb9imbaOaQfaXBdbasasydbgQcjjjj94VBdbaQaXfhXkazclfhzaCcufgCmbkalci9UhLdnalci6mbcbhzaihsinascwfydbhCasclfydbhXaOasydbcdtfgQaQydbgQcefBdbaAaQcdtfazBdbaOaXcdtfgXaXydbgXcefBdbaAaXcdtfazBdbaOaCcdtfgCaCydbgCcefBdbaAaCcdtfazBdbascxfhsaLazcefgz9hmbkkaihzalhsindnaHazydbcdtgCfgXydbgQcu9kmbaXaQcFFFFrGgQBdbaOaCfgCaCydbaQ9RBdbkazclfhzascufgsmbxdkkamazaHHjjjjbbgHBd:CwamceBd;8wamazcbyd;0:G:cjbHjjjjbbgOBd:GwamcdBd;8wamcualcdtalcFFFFi0Ecbyd;0:G:cjbHjjjjbbgABd:KwamciBd;8waHcbasz:rjjjbhXaihzalhsinaXazydbcdtfgCaCydbcefBdbazclfhzascufgsmbkalci9UhLdnaoTmbcbhzaOhsaXhCaohQinasazBdbasclfhsaCydbazfhzaCclfhCaQcufgQmbkkdnalci6mbcbhzaihsinascwfydbhCasclfydbhQaOasydbcdtfgKaKydbgKcefBdbaAaKcdtfazBdbaOaQcdtfgQaQydbgQcefBdbaAaQcdtfazBdbaOaCcdtfgCaCydbgCcefBdbaAaCcdtfazBdbascxfhsaLazcefgz9hmbkkaoTmbcbhzaohsinaOazfgCaCydbaXazfydb9RBdbazclfhzascufgsmbkkamaLcbyd;0:G:cjbHjjjjbbgzBd:OwamclBd;8wazcbaLz:rjjjbhYamcuaLcK2alcjjjjd0Ecbyd;0:G:cjbHjjjjbbg8ABd:SwamcvBd;8wJbbbbhEdnalci6g3mbarcd4hKaihsa8AhzaLhrJbbbbh5inavasclfydbaK2cdtfgCIdlh8EavasydbaK2cdtfgXIdlhEavascwfydbaK2cdtfgQIdlh8FaCIdwhaaXIdwhhaQIdwhgazaCIdbg8JaXIdbg8KMaQIdbg8LMJbbnn:vUdbazclfaXIdlaCIdlMaQIdlMJbbnn:vUdbaQIdwh8MaCIdwh8NaXIdwhyazcxfa8EaE:tg8Eagah:tggNaaah:tgaa8FaE:tghN:tgEJbbbbJbbjZa8Ja8K:tg8FahNa8Ea8La8K:tg8KN:tghahNaEaENaaa8KNa8FagN:tgEaENMMg8K:rg8E:va8KJbbbb9BEg8KNUdbazczfaEa8KNUdbazcCfaha8KNUdbazcwfa8Maya8NMMJbbnn:vUdba5a8EMh5ascxfhsazcKfhzarcufgrmbka5aL:Z:vJbbbZNhEkamcuaLcdtalcFFFF970Ecbyd;0:G:cjbHjjjjbbgCBd:WwamcoBd;8waq:Zhhdna3mbcbhzaChsinasazBdbasclfhsaLazcefgz9hmbkkaEahNhhamcuaLcltalcFFFFd0Ecbyd;0:G:cjbHjjjjbbg8PBd:0wamcrBd;8wcba8Pa8AaCaLcbz:djjjb8AJFFuuh8MJFFuuh8NJFFuuhydnalci6mbJFFuuhya8AhzaLhsJFFuuh8NJFFuuh8MinazcwfIdbgEa8Ma8MaE9EEh8MazclfIdbgEa8Na8NaE9EEh8NazIdbgEayayaE9EEhyazcKfhzascufgsmbkkah:rhEamaocetgzcuaocu9kEcbyd;0:G:cjbHjjjjbbgCBd:4wdndnaoal9nmbaihzalhsinaCazydbcetfcFFi87ebazclfhzascufgsmbxdkkaCcFeazz:rjjjb8AkaEJbbbZNh8JcuhIdnalci6mbcbhsJFFuuhEa8AhzcuhIinazcwfIdba8M:tghahNazIdbay:tghahNazclfIdba8N:tghahNMM:rghaEaIcuSahaE9DVgXEhEasaIaXEhIazcKfhzaLascefgs9hmbkkamczfcbcjwz:rjjjb8Aam9cb83iwam9cb83ibaxa8JNh8RJbbjZak:th8Lcbh8SJbbbbhRJbbbbh8UJbbbbh8VJbbbbh8WJbbbbh8XJbbbbh8Ycbh8ZcbhPinJbbbbhEdna8STmbJbbjZa8S:Z:vhEkJbbbbhhdna8Ya8YNa8Wa8WNa8Xa8XNMMg8KJbbbb9BmbJbbjZa8K:r:vhhka8VaENh8Ka8UaENh5aRaENh8EaIhLdndndndndna8SaPVTmbamydwg80Tmea8YahNh8Fa8XahNhaa8WahNhgaeamydbcdtfh81cbh3JFFuuhEcvhQcuhLindnaHa81a3cdtfydbcdtgzfydbgvTmbaAaOazfydbcdtfhsindndnaCaiasydbgKcx2fgzclfydbgrcetf8Vebcs4aCazydbgXcetf8Vebcs4faCazcwfydbglcetf8Vebcs4fgombcbhzxekcehzaHaXcdtfydbgXceSmbcehzaHarcdtfydbgrceSmbcehzaHalcdtfydbglceSmbdnarcdSaXcdSfalcdSfcd6mbaocefhzxekaocdfhzkdnazaQ9kmba8AaKcK2fgXIdwa8K:tghahNaXIdba8E:tghahNaXIdla5:tghahNMM:ra8J:va8LNJbbjZMJ9VO:d86JbbjZaXIdCa8FNaXIdxagNaaaXIdzNMMakN:tghahJ9VO:d869DENghaEazaQ6ahaE9DVgXEhEaKaLaXEhLazaQaXEhQkasclfhsavcufgvmbkka3cefg3a809hmbkkaLcu9hmekama8KUd:ODama5Ud:KDama8EUd:GDamcuBd:qDamcFFF;7rBdjDa8Pcba8AaYamc:GDfamc:qDfamcjDfz:ejjjbamyd:qDhLdndnaxJbbbb9ETmba8SaD6mbaLcuSmeceh3amIdjDa8R9EmixdkaLcu9hmekdna8STmbabaPcltfgHam8Piw83dwaHam8Pib83dbaPcefhPkc3hHinamc:CwfaHfydbcbyd;4:G:cjbH:bjjjbbaHc98fgHc989hmbxvkkcbh3a8Saq9pmbamydwaCaiaLcx2fgzydbcetf8Vebcs4aCazcwfydbcetf8Vebcs4faCazclfydbcetf8Vebcs4ffaw9nmekcbhzcbhsdna8ZTmbcbhsamczfhXinamczfascdtfaXydbgQBdbaXclfhXasaYaQfRbbTfhsa8Zcufg8ZmbkkamydwhlamydbhXam9cu83i:GDam9cu83i:ODam9cu83i:qDam9cu83i:yDinamcjDfazfcFFF;7rBdbazclfgzcz9hmbkasc;8easclfc:bd6Eg8Zcdth80dnalTmbaeaXcdtfhocbhrindnaHaoarcdtfydbcdtgzfydbgvTmbaAaOazfydbcdtfhscuhQcuhzinaHaiasydbgKcx2fgXclfydbcdtfydbaHaXydbcdtfydbfaHaXcwfydbcdtfydbfgXazaXaz6gXEhzaKaQaXEhQasclfhsavcufgvmbkaQcuSmba8AaQcK2fgsIdwa8M:tgEaENasIdbay:tgEaENasIdla8N:tgEaENMM:rhEcbhsindndnazamc:qDfasfgvydbgX6mbazaX9hmeaEamcjDfasfIdb9FTmekavazBdbamc:GDfasfaQBdbamcjDfasfaEUdbxdkasclfgscz9hmbkkarcefgral9hmbkkamczfa80fhQcbhzcbhsindnamc:GDfazfydbgXcuSmbaQascdtfaXBdbascefhskazclfgzcz9hmbkasa8Zfg8ZTmbJFFuuhhcuhKamczfhza8ZhvcuhQina8AazydbgXcK2fgsIdwa8M:tgEaENasIdbay:tgEaENasIdla8N:tgEaENMM:rhEdndnaHaiaXcx2fgsclfydbcdtfydbaHasydbcdtfydbfaHascwfydbcdtfydbfgsaQ6mbasaQ9hmeaEah9DTmekaEhhashQaXhKkazclfhzavcufgvmbkaKcuSmbaKhLkdnamaiaLcx2fgrydbarclfydbarcwfydbaCabaeadaPawaqa3z:fjjjbTmbaPcefhPJbbbbhRJbbbbh8UJbbbbh8VJbbbbh8WJbbbbh8XJbbbbh8YkcbhXinaAaOaraXcdtfydbcdtgsfydbcdtfgKhzaHasfgvydbgQhsdnaQTmbdninazydbaLSmeazclfhzascufgsTmdxbkkazaKaQcdtfc98fydbBdbavavydbcufBdbkaXcefgXci9hmbka8AaLcK2fgzIdbhEazIdlhhazIdwh8KazIdxh5azIdzh8EazIdCh8FaYaLfce86bba8Ya8FMh8Ya8Xa8EMh8Xa8Wa5Mh8Wa8Va8KMh8Va8UahMh8UaRaEMhRamydxh8Sxbkkamc:WDf8KjjjjbaPkjoivuv99lu8Jjjjjbca9Rgo8Kjjjjbdndnalcw0mbaiydbhraeabcitfgwalcdtciVBdlawarBdbdnalcd6mbaiclfhralcufhDawcxfhwinarydbhqawcuBdbawc98faqBdbawcwfhwarclfhraDcufgDmbkkalabfhwxekcbhqaocbBdKao9cb83izaocbBdwao9cb83ibJbbjZhkJbbjZhxinadaiaqcdtfydbcK2fhDcbhwinaoczfawfgraDawfIdbgmarIdbgP:tgsaxNaPMgPUdbaoawfgrasamaP:tNarIdbMUdbawclfgwcx9hmbkJbbjZakJbbjZMgk:vhxaqcefgqal9hmbkcbhradcbcecdaoIdlgmaoIdwgP9GEgwaoIdbgsaP9GEawasam9GEgzcdtgwfhHaoczfawfIdbhmaihwalhDinaiarcdtfgqydbhOaqawydbgABdbawaOBdbawclfhwaraHaAcK2fIdbam9DfhraDcufgDmbkdndnarcv6mbavc8X9kmbaralc98f6mekaiydbhraeabcitfgwalcdtciVBdlawarBdbaiclfhralcufhDawcxfhwinarydbhqawcuBdbawc98faqBdbawcwfhwarclfhraDcufgDmbkalabfhwxekaeabcitfgwamUdbawawydlc98GazVBdlabcefaeadaiaravcefgqz:djjjbhDawawydlciGaDabcu7fcdtVBdlaDaeadaiarcdtfalar9Raqz:djjjbhwkaocaf8Kjjjjbawk;Oddvue99dninabaecitfgrydlgwcd4gDTmednawciGgqci9hmbcihqdnawcl6mbabaecitfhbcbheawhqcehkindnaiabydbgDfRbbmbcbhkadaDcK2fgwIdwalIdw:tgxaxNawIdbalIdb:tgxaxNawIdlalIdl:tgxaxNMM:rgxaoIdb9DTmbaoaxUdbavaDBdbarydlhqkabcwfhbaecefgeaqcd46mbkakceGTmikaraqciGBdlskdnabcbaDalaqcdtfIdbarIdb:tgxJbbbb9FEgwaD7aecefgDfgecitfydlabawaDfgDcitfydlVci0mbaraqBdlkabaDadaialavaoz:ejjjbax:laoIdb9Fmbkkkjlevudndnabydwgxaladcetfgm8Vebcs4alaecetfgP8Vebgscs4falaicetfgz8Vebcs4ffaD0mbakmbcbhDabydxaq6mekavawcltfgxab8Pdw83dwaxab8Pdb83dbabydbhDdnabydwgwTmbaoaDcdtfhxawhsinalaxydbcetfcFFi87ebaxclfhxascufgsmbkkabaDawfBdbabydxhxab9cb83dwababydlaxci2fBdlaP8VebhscehDcbhxkdnascztcz91cu9kmbabaxcefBdwaPax87ebaoabydbcdtfaxcdtfaeBdbkdnam8Uebcu9kmbababydwgxcefBdwamax87ebaoabydbcdtfaxcdtfadBdbkdnaz8Uebcu9kmbababydwgxcefBdwazax87ebaoabydbcdtfaxcdtfaiBdbkarabydlfabydxci2faPRbb86bbarabydlfabydxci2fcefamRbb86bbarabydlfabydxci2fcdfazRbb86bbababydxcefBdxaDk:mPrHue99eue99eue99iu8Jjjjjbc;W;Gb9Rgx8KjjjjbdndnalmbcbhmxekcbhPaxc:m;Gbfcbc;Kbz:rjjjb8Aaxcualci9UgscltascjjjjiGEcbyd;0:G:cjbHjjjjbbgzBd:m9GaxceBd;S9GaxcuascK2gHcKfalcpFFFe0Ecbyd;0:G:cjbHjjjjbbgOBd:q9GaxcdBd;S9Gdnalci6gAmbarcd4hCascdthXaOhQazhLinavaiaPcx2fgrydwaC2cdtfhKavarydlaC2cdtfhYavarydbaC2cdtfh8AcbhraLhEinaQarfgma8Aarfg3Idbg5aYarfg8EIdbg8Fa5a8F9DEg5UdbamaKarfgaIdbg8Fa5a8Fa59DEg8FUdbamcxfgma3Idbg5a8EIdbgha5ah9EEg5UdbamaaIdbgha5aha59EEg5UdbaEa8Fa5MJbbbZNUdbaEaXfhEarclfgrcx9hmbkaQcKfhQaLclfhLaPcefgPas9hmbkkaOaHfgr9cb83dbar9cb83dzar9cb83dwaxcuascx2gralc:bjjjl0Ecbyd;0:G:cjbHjjjjbbgHBdN9GaxciBd;S9GascdthgazarfhvaxcwVhPaxclVhCaHh8Jazh8KcbhLinaxcbcj;Gbz:rjjjbhEaLas2cdthadnaAmba8Khrash3inaEarydbgmc8F91cjjjj94Vam7gmcQ4cx2fg8Ea8EydwcefBdwaEamcd4cFrGcx2fg8Ea8EydbcefBdbaEamcx4cFrGcx2fgmamydlcefBdlarclfhra3cufg3mbkkazaafh8AaHaafhXcbhmcbh3cbh8EcbhainaEamfgrydbhQara3BdbarcwfgKydbhYaKaaBdbarclfgrydbhKara8EBdbaQa3fh3aYaafhaaKa8Efh8Eamcxfgmcj;Gb9hmbkdnaAmbcbhravhminamarBdbamclfhmasarcefgr9hmbkavhrashminaEa8Aarydbg3cdtfydbg8Ec8F91a8E7cd4cFrGcx2fg8Ea8Eydbg8EcefBdbaXa8Ecdtfa3Bdbarclfhramcufgmmbka8JhrashminaCa8Aarydbg3cdtfydbg8Ec8F91a8E7cx4cFrGcx2fg8Ea8Eydbg8EcefBdbava8Ecdtfa3BdbarclfhramcufgmmbkavhrashminaPa8Aarydbg3cdtfydbg8Ec8F91cjjjj94Va8E7cQ4cx2fg8Ea8Eydbg8EcefBdbaXa8Ecdtfa3Bdbarclfhramcufgmmbkka8Jagfh8Ja8Kagfh8KaLcefgLci9hmbkaEaocetgrcuaocu9kEcbyd;0:G:cjbHjjjjbbgKBd:y9GaEclBd;S9Gdndnaoal9nmbaihralhminaKarydbcetfcFFi87ebarclfhramcufgmmbxdkkaKcFearz:rjjjb8Akcbh8EaEascbyd;0:G:cjbHjjjjbbg8ABd:C9GaOaHaHascdtfaHascitfa8AascbazaKaiawaDaqakz:hjjjbdndnalci6mba8Ahrashmina8EarRbbfh8EarcefhramcufgmmbkaE9cb83iwaE9cb83ibalawc9:fgrfcufar9UgrasaDfcufaD9Ugmaram0EhYcbhmcbhra8Ehaincbh3dnarTmba8AarfRbbceSh3kamaEaiaHydbcx2fgQydbaQclfydbaQcwfydbaKabaeadamawaqa3a3ce7a8EaY9nVaaamfaY6VGz:fjjjbfhmaHclfhHaaa8AarfRbb9Rhaasarcefgr9hmbkaEydxTmeabamcltfgraE8Piw83dwaraE8Pib83dbamcefhmxekaE9cb83iwaE9cb83ibcbhmkczhrinaEc:m;Gbfarfydbcbyd;4:G:cjbH:bjjjbbarc98fgrc989hmbkkaxc;W;Gbf8Kjjjjbamk:wKDQue99iue99iul9:euw99iu8Jjjjjbc;qb9RgP8Kjjjjbaxhsaxhzdndnavax0gHmbdnavTmbcbhOaehzavhAinawaDazydbcx2fgCcwfydbcetfgX8VebhQawaCclfydbcetfgL8VebhKawaCydbcetfgC8VebhYaXce87ebaLce87ebaCce87ebaOaKcs4aYcs4faQcs4ffhOazclfhzaAcufgAmbkaehzavhAinawaDazydbcx2fgCcwfydbcetfcFFi87ebawaCclfydbcetfcFFi87ebawaCydbcetfcFFi87ebazclfhzaAcufgAmbkcehzaqhsaOaq0mekalce86bbalcefcbavcufz:rjjjb8AxekaPaiBdxaPadBdwaPaeBdlavakaqci9Ug8Aaka8Aak6EaHEgK9RhEaxaK9Rh3aKcufh5aKceth8EaKcdtgCc98fh8FavcitgOaC9Rarfc98fhaascufhhavcufhgaraOfh8JJbbjZas:Y:vh8KcbazceakaxSEg8Lcdtg8M9Rh8NJFFuuhycuh8PcbhIcbh8RinaPclfa8RcdtfydbhQaPcb8Pd:y:G:cjbg8S83i9iaPcb8Pd:q:G:cjbgR83inaPcb8Pd1:G:cjbg8U83iUaPcb8Pdj:G:cjbg8V83i8WaPa8S83iyaPaR83iaaPa8U83iKaPa8V83izaQavcdtgYfh8WcbhXinabaQaXcdtgLfydbcK2fhAcbhzinaPc8WfazfgCaAazfgOIdbg8XaCIdbg8Ya8Xa8Y9DEUdbaCczfgCaOcxfIdbg8XaCIdbg8Ya8Xa8Y9EEUdbazclfgzcx9hmbkaba8WaXcu7cdtfydbcK2fhAcbhzaPIdUh8ZaPId9ih80aPId80h81aPId9ehBaPId8Wh83aPIdnhUinaPczfazfgCaAazfgOIdbg8XaCIdbg8Ya8Xa8Y9DEUdbaCczfgCaOcxfIdbg8XaCIdbg8Ya8Xa8Y9EEUdbazclfgzcx9hmbkaraLfgzaBa81:tg8Xa80a8Z:tg8YNaUa83:tg8Za8XNa8Za8YNMMUdbazaYfaPId8KaPIdC:tg8XaPIdyaPIdK:tg8YNaPIdaaPIdz:tg8Za8XNa8Za8YNMMUdbaXcefgXav9hmbkcbh85dnaHmbcbhAaQhza8JhCavhXinawaDazydbcx2fgOcwfydbcetfgL8Vebh8WawaOclfydbcetfg858Vebh86awaOydbcetfgO8Vebh87aLce87eba85ce87ebaOce87ebaCaAa86cs4a87cs4fa8Wcs4ffgABdbazclfhzaCclfhCaXcufgXmbkavhCinawaDaQydbcx2fgzcwfydbcetfcFFi87ebawazclfydbcetfcFFi87ebawazydbcetfcFFi87ebaQclfhQaCcufgCmbka8Jh85kdndndndndndndndndndndnava8E6mba8Eax9nmeavavaK9UgzaK29Raza320mda5aE9pmqa85Th87ceh8WaEhQxwka5ag9pmDa8Eax9nmixokavaK6mea5aE9pmwcehQaEhXa85Tmixlka5ag6mlxrka5ag9pmokcbhQaghXa85mekJFFuuh8XcbhLa5hzindnazcefgCaK6mbaQavaC9RgOaK6GmbarazcdtfIdbg8YaC:YNaravaz9RcdtfaYfc94fIdbg8ZaO:YNMg80a8X9Embdndna8KaOahf:YNg81:lJbbb9p9DTmba81:OhAxekcjjjj94hAka8ZasaA2aO9R:YNh8Zdndna8Kazasf:YNg81:lJbbb9p9DTmba81:OhOxekcjjjj94hOkamasaO2aC9R:Ya8YNa8ZMNa80Mg8Ya8Xa8Ya8X9DgOEh8XaCaLaOEhLkaza8LfgzaX6mbxlkkJFFuuh8XcbhLaEhCaahAa8FhOaKhzindnazaK6mbaQaCaK6GmbaraOfIdbg8Yaz:YNaAIdbg8ZaC:YNMg80a8X9Embdndna8Ka85aOfydbgYahf:YNg81:lJbbb9p9DTmba81:Oh8Wxekcjjjj94h8Wkamasa8W2aY9R:Yg81a8YNa8Za81NMNa80Mg8Ya8Xa8Ya8X9DgYEh8XazaLaYEhLkaCa8L9RhCaAa8NfhAaOa8MfhOaza8LfgzcufaX6mbxikka85Th87cbh8WaghQkJFFuuh8XcbhLaEhCaahAa8FhOaKhzindnazazaK9UgXaK29RaXa320mbdna8WTmbaCaCaK9UgXaK29RaXa320mekaraOfIdbg8Yaz:YNaAIdbg8ZaC:YNMg80a8X9EmbazhXaChYdna87mba85aOfydbgXhYkdndna8KaYahf:YNg81:lJbbb9p9DTmba81:Oh86xekcjjjj94h86ka8Zasa862aY9R:YNh8Zdndna8KaXahf:YNg81:lJbbb9p9DTmba81:OhYxekcjjjj94hYkamasaY2aX9R:Ya8YNa8ZMNa80Mg8Ya8Xa8Ya8X9DgXEh8XazaLaXEhLkaCa8L9RhCaAa8NfhAaOa8MfhOaza8LfgzcufaQ6mbkkaLTmba8Xay9DTmba8XhyaLhIa8Rh8Pka8Rcefg8Rci9hmbkdndnaoc8X9kmba8Pcb9omeka8Acufh85cbhYindndndnavaY9RaxaYaxfav0Eg8WTmbcbhAaeaYcdtfgzhCa8WhXinawaDaCydbcx2fgOcwfydbcetfgQ8VebhbawaOclfydbcetfgL8VebhrawaOydbcetfgO8VebhKaQce87ebaLce87ebaOce87ebaAarcs4aKcs4fabcs4ffhAaCclfhCaXcufgXmbka8WhOinawaDazydbcx2fgCcwfydbcetfcFFi87ebawaCclfydbcetfcFFi87ebawaCydbcetfcFFi87ebazclfhzaOcufgOmbkaAaq0mekalaYfgzce86bbazcefcba8Wcufz:rjjjb8AxekalaYfgzce86bbazcefcba85z:rjjjb8Aa8Ah8Wka8WaYfgYav9pmdxbkkaravcdtg8WfhLdnaITmbaPclfa8PcdtfydbhzaIhCinaLazydbfcb86bbazclfhzaCcufgCmbkkdnavaI9nmbaPclfa8PcdtfydbaIcdtfhzavaI9RhCinaLazydbfce86bbazclfhzaCcufgCmbkkcbhYindnaYa8PSmbcbhzaraPclfaYcdtfydbgKa8Wz:qjjjbhCavhXaIhOinaKaOazaLaCydbgQfRbbgAEcdtfaQBdbaCclfhCaOaAfhOazaA9RcefhzaXcufgXmbkkaYcefgYci9hmbkabaeadaialaIaocefgCarawaDaqakaxamz:hjjjbabaeaIcdtgzfadazfaiazfalaIfavaI9RaCarawaDaqakaxamz:hjjjbkaPc;qbf8Kjjjjbk:Seeru8Jjjjjbc:q;ab9Rgo8Kjjjjbaoc:q8WfcFecjzz:rjjjb8AcbhrdnadTmbaehwadhDinaoarcdtfawydbgqBdbaoc:q8WfaqcFiGcdtfgkydbhxakaqBdbawclfhwaraxaq9hfhraDcufgDmbkkabaeadaoaraiavz:jjjjbaoc:q;abf8Kjjjjbk;Sqloud99euD998Jjjjjbc:W;ab9Rgr8KjjjjbdndnadTmbaocd4hwcbhDcbhqindnavaeclfydbaw2cdtfgkIdbavaeydbaw2cdtfgxIdbgm:tgPavaecwfydbaw2cdtfgsIdlaxIdlgz:tgHNakIdlaz:tgOasIdbam:tgAN:tgCaCNaOasIdwaxIdwgX:tgQNakIdwaX:tgOaHN:tgHaHNaOaANaPaQN:tgPaPNMMgOJbbbb9Bmbarc8WfaDcltfgkaCaO:rgO:vgCUdwakaPaO:vgPUdlakaHaO:vgHUdbakaCaXNaHamNazaPNMM:mUdxaDcefhDkaecxfheaqcifgqad6mbkab9cb83dyab9cb83daab9cb83dKab9cb83dzab9cb83dwab9cb83dbaDTmearcbBd8Sar9cb83iKar9cb83izarczfavalaoarc8Sfcbcraiz:kjjjbarIdKhQarIdChLarIdzhKar9cb83iwar9cb83ibararc8WfaDczarc8Sfcbcicbz:kjjjbJbbbbhmdnarIdwgzazNarIdbgHaHNarIdlgXaXNMMgCJbbbb9BmbJbbjZaC:r:vhmkazamNhCaXamNhXaHamNhHJbbjZhmarc8WfheaDhvinaecwfIdbaCNaeIdbaHNaXaeclfIdbNMMgzamazam9DEhmaeczfheavcufgvmbkabaQUdwabaLUdlabaKUdbabarId3UdxdndnamJ;n;m;m899FmbJbbbbhzarc8WfheinaecxfIdbaQaecwfIdbgPNaKaeIdbgONaLaeclfIdbgANMMMaCaPNaHaONaXaANMM:vgPazaPaz9EEhzaeczfheaDcufgDmbkabaCUd8KabaXUdaabaHUd3abaQaCazN:tUdKabaLaXazN:tUdCabaKaHazN:tUdzabJbbjZamamN:t:rgmUdydndnaCJbbj:;aCJbbj:;9GEgzJbbjZazJbbjZ9FEJbb;:9cNJbbbZJbbb:;aCJbbbb9GEMgz:lJbbb9p9DTmbaz:Ohexekcjjjj94hekabae86b8UdndnaXJbbj:;aXJbbj:;9GEgzJbbjZazJbbjZ9FEJbb;:9cNJbbbZJbbb:;aXJbbbb9GEMgz:lJbbb9p9DTmbaz:Ohvxekcjjjj94hvkabav86bRdndnaHJbbj:;aHJbbj:;9GEgzJbbjZazJbbjZ9FEJbb;:9cNJbbbZJbbb:;aHJbbbb9GEMgz:lJbbb9p9DTmbaz:Ohwxekcjjjj94hwkabaw86b8SdndnaecKtcK91:YJbb;:9c:vaC:t:lavcKtcK91:YJbb;:9c:vaX:t:lawcKtcK91:YJbb;:9c:vaH:t:lamMMMJbb;:9cNJbbjZMgm:lJbbb9p9DTmbam:Ohexekcjjjj94hekaecFbaecFb9iEhexekabcjjj;8iBdycFbhekabae86b8Vxekab9cb83dyab9cb83daab9cb83dKab9cb83dzab9cb83dwab9cb83dbkarc:W;abf8Kjjjjbk;7woDuo99eue99euv998Jjjjjbcje9Rgw8Kjjjjbawc;abfcbaocdtgDz:rjjjb8Aawc;GbfcbaDz:rjjjb8AawcafhDawhqaohkinaqcFFF97BdbaDcFFF;7rBdbaqclfhqaDclfhDakcufgkmbkavcd4hxaicd4hmdnadTmbaocx2hPcbhsinashzdnarTmbarascdtfydbhzkaeazam2cdtfgDIdwhHaDIdlhOaDIdbhAalazax2cdtfIdbhCcbhDawcafhqawc;Gbfhvawhkawc;abfhiinaCaDc:O:G:cjbfIdbaHNaDc:G:G:cjbfIdbaANaDc:K:G:cjbfIdbaONMMgXMhQazhLdnaXaC:tgXaqIdbgK9DgYmbavydbhLkavaLBdbazhLdnaQakIdbg8A9EmbaiydbhLa8AhQkaiaLBdbakaQUdbaqaXaKaYEUdbaiclfhiakclfhkavclfhvaqclfhqaPaDcxfgD9hmbkascefgsad9hmbkkJbbbbhQcbhLawc;GbfhDawc;abfhqcbhkinalaqydbgvax2cdtfIdbalaDydbgiax2cdtfIdbaeavam2cdtfgvIdwaeaiam2cdtfgiIdw:tgCaCNavIdbaiIdb:tgCaCNavIdlaiIdl:tgCaCNMM:rMMgCaQaCaQ9EgvEhQakaLavEhLaqclfhqaDclfhDaoakcefgk9hmbkJbbbbhCdnaeawc;abfaLcdtgqfydbgkam2cdtfgDIdwaeawc;Gbfaqfydbgvam2cdtfgqIdwgH:tgXaXNaDIdbaqIdbgA:tg8Aa8ANaDIdlaqIdlgE:tgOaONMMgKJbbbb9ETmbaK:rgCalakax2cdtfIdbMalavax2cdtfIdb:taCaCM:vhCkaQJbbbZNhKaXaCNaHMhHaOaCNaEMhOa8AaCNaAMhAdnadTmbcbhqarhkinaqhDdnarTmbakydbhDkdnalaDax2cdtfIdbg3aeaDam2cdtfgDIdwaH:tgQaQNaDIdbaA:tgCaCNaDIdlaO:tgXaXNMMg5:rgEMg8EaK9ETmbJbbbbh8Adna5Jbbbb9ETmba8EaK:taEaEM:vh8Aka8AaQNaHMhHa8AaXNaOMhOa8AaCNaAMhAa3aKaEMMJbbbZNhKkakclfhkadaqcefgq9hmbkkabaKUdxabaHUdwabaOUdlabaAUdbawcjef8Kjjjjbk:reevu8Jjjjjbcj8W9Rgr8Kjjjjbaici2hwcbhDdnaiTmbarhiawhqinaiaeadRbbgkcdtfydbBdbaDakcefgkaDak0EhDaiclfhiadcefhdaqcufgqmbkkabarawaeaDalaoz:jjjjbarcj8Wf8Kjjjjbk:Eeeeu8Jjjjjbca9Rgo8Kjjjjbab9cb83dyab9cb83daab9cb83dKab9cb83dzab9cb83dwab9cb83dbdnadTmbaocbBd3ao9cb83iwao9cb83ibaoaeadaialaoc3falEavcbalEcrcbz:kjjjbabao8Pib83dbabao8Piw83dwkaocaf8Kjjjjbk::meQu8Jjjjjbcjz9Rgv8KjjjjbcbhoavcjPfcbaez:rjjjb8Aavcjxfcbaez:rjjjb8AdnaiTmbadhoaihrinavcjxfaoRbbfgwawRbbcef86bbavcjxfaocefRbbfgwawRbbcef86bbavcjxfaocdfRbbfgwawRbbcef86bbaocifhoarcufgrmbkcbhDcjehoadhqcehkindndnalTmbcbhxcuhmaqhrakhwcuhPinawcufamaoavcjPfarcefRbbgsfRbb9RcFeGgzci6aoavcjPfarRbbgHfRbb9RcFeGgOci6faoavcjPfarcdfRbbgAfRbb9RcFeGgCci6fgXcOtaOcFr7azaCf9RcwtVavcjxfaAfRbbgzavcjxfaHfRbbgHavcjxfasfRbbgsaHas6Egsazas6EcFe7VgsaP9kgzEhmaXcd6gHaxcefgOal9iVce9hmdasaPazEhPaxaOaHEhxarcifhrawai6hsawcefhwasmbxdkkcuhmaqhrakhwcuhxinawcufamaoavcjPfarcefRbbfRbb9RcFeGci6aoavcjPfarRbbfRbb9RcFeGci6faoavcjPfarcdfRbbfRbb9RcFeGci6fgPax9kgsEhmaPce0meaPaxasEhxarcifhrawai6hPawcefhwaPmbkkadamci2fgrcdfRbbhwarcefRbbhxarRbbhPadaDci2fgrcifaramaD9Rci2zNjjjb8AaPavcjPffaocefgo86bbaPavcjxffgmamRbbcuf86bbaxavcjPffao86bbaxavcjxffgmamRbbcuf86bbarcdfaw86bbarcefax86bbaraP86bbawavcjPffao86bbawavcjxffgrarRbbcuf86bbaqcifhqakcefhkaDcefgDai9hmbkcbhzdnalcb9mmbcbhsavcjPfcbaez:rjjjb8Aadcvfhlinadasci2fgxcefgDRbbhoaxcdfgqRbbhrdndnavcjPfaxRbbgmfRbbmbavcjPfarfRbbhwdndndnavcjPfaofRbbTmbawcFeGTmexikawcFeGmdascefgAai9pmdasc980mdascifhQcbhLarcFeGhCamcFeGhXalhwcbhKcbhYinawcufRbbhPawRbbhOcehkdndnawc9:fRbbgHao9hmbaPcFeGamSmekdnaPcFeGao9hmbaOcFeGamSmekaHamSaOcFeGaoSGhkkceh8AaYceGhYdndnaHar9hmbaPcFeGaoSmekdnaPcFeGar9hmbaOcFeGaoSmekaHaoSaOcFeGarSGh8AkakaYVhYaLaHcFeGgHaXSaPcFeGgPaCSGaPaXSaOcFeGgPaCSGVaHaCSaPaXSGVVhLa8AaKceGVhKdnaAcefgPai9pmbawcifhwaAaQ6hHaPhAaHmekkaYTmeaKmekarhwaohPaohHarhOamhrxdkdnaYTaLVceGTmbaYaKTVaLVceGmekamhwarhParhHamhOaohrxekaohwamhPamhHaohOkavcjPfarfce86bbavcjPfawfce86bbaxaH86bbaqar86bbaDaO86bbavcjPfaPfce86bbalcifhlascefgsai9hmbkkavcFeaecetz:rjjjbhwaici2hrindnawadRbbgmcetfgx8Uebgocu9kmbaxaz87ebawcjlfazcdtfabamcdtfydbBdbazhoazcefhzkadao86bbadcefhdarcufgrmbkazcdthokabavcjlfaoz:qjjjb8Aavcjzf8KjjjjbkObabaiaeadcbz:njjjbk9teiucbcbyd;8:G:cjbgeabcifc98GfgbBd;8:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabk9teiucbcbyd;8:G:cjbgeabcrfc94GfgbBd;8:G:cjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikTeeucbabcbyd;8:G:cjbge9Rcifc98GaefgbBd;8:G:cjbdnabZbcztge9nmbabae9RcFFifcz4nb8Akk:3qeludndnadch6mbadTmeabaead;8qbbabskabaeSmbdnaeadabfgi9Rcbadcet9R0mbadTmeabaead;8qbbabskaeab7ciGhldndndnabae9pmbdnalTmbadhvabhixikdnabciGmbadhvabhixdkadTmiabaeRbb86bbadcufhvdnabcefgiciGmbaecefhexdkavTmiabaeRbe86beadc9:fhvdnabcdfgiciGmbaecdfhexdkavTmiabaeRbd86bdadc99fhvdnabcifgiciGmbaecifhexdkavTmiabaeRbi86biabclfhiaeclfheadc98fhvxekdnalmbdnaiciGTmbadTmlabadcufgifglaeaifRbb86bbdnalciGmbaihdxekaiTmlabadc9:fgifglaeaifRbb86bbdnalciGmbaihdxekaiTmlabadc99fgifglaeaifRbb86bbdnalciGmbaihdxekaiTmlabadc98fgdfaeadfRbb86bbkadcl6mbdnadc98fgocxGcxSmbaocd4cefciGhiaec98fhlabc98fhvinavadfaladfydbBdbadc98fhdaicufgimbkkaocx6mbaec9Wfhvabc9WfhoinaoadfgicxfavadfglcxfydbBdbaicwfalcwfydbBdbaiclfalclfydbBdbaialydbBdbadc9Wfgdci0mbkkadTmdadhidnadciGglTmbaecufhvabcufhoadhiinaoaifavaifRbb86bbaicufhialcufglmbkkadcl6mdaec98fhlabc98fhvinavaifgecifalaifgdcifRbb86bbaecdfadcdfRbb86bbaecefadcefRbb86bbaeadRbb86bbaic98fgimbxikkavcl6mbdnavc98fglc3Gc3Smbavalcd4cefcrGgdcdt9RhvinaiaeydbBdbaeclfheaiclfhiadcufgdmbkkalc36mbinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaiczfaeczfydbBdbaicCfaecCfydbBdbaicKfaecKfydbBdbaic3faec3fydbBdbaecafheaicafhiavc9Gfgvci0mbkkavTmbdndnavcrGgdmbavhlxekavc94GhlinaiaeRbb86bbaicefhiaecefheadcufgdmbkkavcw6mbinaiaeRbb86bbaicefaecefRbb86bbaicdfaecdfRbb86bbaicifaecifRbb86bbaiclfaeclfRbb86bbaicvfaecvfRbb86bbaicofaecofRbb86bbaicrfaecrfRbb86bbaicwfhiaecwfhealc94fglmbkkabkk:pedbcj:GdktFFuuFFuuFFuubbbbFFuFFFuFFFuFbbbbbbjZbbbbbbbbbbbbbbjZbbbbbbbbbbbbbbjZ86;nAZ86;nAZ86;nAZ86;nA:;86;nAZ86;nAZ86;nAZ86;nA:;86;nAZ86;nAZ86;nAZ86;nA:;bc;0:Gdkxebbbdbbbj:qbb",t=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!=="object")return{supported:!1};var n,i=WebAssembly.instantiate(r(e),{}).then(function(m){n=m.instance,n.exports.__wasm_call_ctors()});function r(m){var g=new Uint8Array(m.length);for(var p=0;p<m.length;++p){var x=m.charCodeAt(p);g[p]=x>96?x-97:x>64?x-39:x+4}var _=0;for(var p=0;p<m.length;++p)g[_++]=g[p]<60?t[g[p]]:(g[p]-60)*64+g[++p];return g.buffer.slice(0,_)}function s(m){if(!m)throw Error("Assertion failed")}function a(m){return new Uint8Array(m.buffer,m.byteOffset,m.byteLength)}var o=48,c=16;function l(m,g){var p=m.meshlets[g*4+0],x=m.meshlets[g*4+1],_=m.meshlets[g*4+2],y=m.meshlets[g*4+3];return{vertices:m.vertices.subarray(p,p+_),triangles:m.triangles.subarray(x,x+y*3)}}function u(m,g,p,x,_,y,v,E,w,T){var A=n.exports.sbrk,P=n.exports.meshopt_buildMeshletsBound(g.length,y,v),S=A(P*c),R=A(g.length*4),k=A(g.length),C=A(g.byteLength),U=A(p.byteLength),L=new Uint8Array(n.exports.memory.buffer);L.set(a(g),C),L.set(a(p),U);var O=m(S,R,k,C,g.length,U,x,_,y,v,E,w,T);L=new Uint8Array(n.exports.memory.buffer);var K=L.subarray(S,S+O*c),B=new Uint32Array(K.buffer,K.byteOffset,K.byteLength/4).slice();for(var X=0;X<O;++X){var q=B[X*4+0],le=B[X*4+1],x=B[X*4+2],de=B[X*4+3];n.exports.meshopt_optimizeMeshlet(R+q*4,k+le,de,x)}var Me=O?B[(O-1)*4+0]+B[(O-1)*4+2]:0,pe=O?B[(O-1)*4+1]+B[(O-1)*4+3]*3:0,J={meshlets:B,vertices:new Uint32Array(L.buffer,R,Me).slice(),triangles:new Uint8Array(L.buffer,k,pe).slice(),meshletCount:O};return A(S-A(0)),J}function d(m){var g=new Float32Array(n.exports.memory.buffer,m,o/4);return{centerX:g[0],centerY:g[1],centerZ:g[2],radius:g[3],coneApexX:g[4],coneApexY:g[5],coneApexZ:g[6],coneAxisX:g[7],coneAxisY:g[8],coneAxisZ:g[9],coneCutoff:g[10]}}function f(m,g,p,x){var _=n.exports.sbrk,y=[],v=_(g.byteLength),E=_(m.vertices.byteLength),w=_(m.triangles.byteLength),T=_(o),A=new Uint8Array(n.exports.memory.buffer);A.set(a(g),v),A.set(a(m.vertices),E),A.set(a(m.triangles),w);for(var P=0;P<m.meshletCount;++P){var S=m.meshlets[P*4+0],R=m.meshlets[P*4+1],k=m.meshlets[P*4+3];n.exports.meshopt_computeMeshletBounds(T,E+S*4,w+R,k,v,p,x),y.push(d(T))}return _(v-_(0)),y}function h(m,g,p,x){var _=n.exports.sbrk,y=_(o),v=_(m.byteLength),E=_(g.byteLength),w=new Uint8Array(n.exports.memory.buffer);w.set(a(m),v),w.set(a(g),E),n.exports.meshopt_computeClusterBounds(y,v,m.length,E,p,x);var T=d(y);return _(y-_(0)),T}function b(m,g,p,x,_){var y=n.exports.sbrk,v=y(o),E=y(m.byteLength),w=x?y(x.byteLength):0,T=new Uint8Array(n.exports.memory.buffer);if(T.set(a(m),E),x)T.set(a(x),w);n.exports.meshopt_computeSphereBounds(v,E,g,p,w,x?_:0);var A=d(v);return y(v-y(0)),A}return{ready:i,supported:!0,buildMeshlets:function(m,g,p,x,_,y){s(m.length%3==0),s(g instanceof Float32Array),s(g.length%p==0),s(p>=3),s(x>=3&&x<=256),s(_>=1&&_<=512),y=y||0;var v=m.BYTES_PER_ELEMENT==4?m:new Uint32Array(m);return u(n.exports.meshopt_buildMeshletsFlex,v,g,g.length/p,p*4,x,_,_,y,0)},buildMeshletsFlex:function(m,g,p,x,_,y,v,E){s(m.length%3==0),s(g instanceof Float32Array),s(g.length%p==0),s(p>=3),s(x>=3&&x<=256),s(_>=1&&y<=512),s(_<=y),v=v||0,E=E||0;var w=m.BYTES_PER_ELEMENT==4?m:new Uint32Array(m);return u(n.exports.meshopt_buildMeshletsFlex,w,g,g.length/p,p*4,x,_,y,v,E)},buildMeshletsSpatial:function(m,g,p,x,_,y,v){s(m.length%3==0),s(g instanceof Float32Array),s(g.length%p==0),s(p>=3),s(x>=3&&x<=256),s(_>=1&&y<=512),s(_<=y),v=v||0;var E=m.BYTES_PER_ELEMENT==4?m:new Uint32Array(m);return u(n.exports.meshopt_buildMeshletsSpatial,E,g,g.length/p,p*4,x,_,y,v)},extractMeshlet:function(m,g){return s(g>=0&&g<m.meshletCount),l(m,g)},computeClusterBounds:function(m,g,p){s(m.length%3==0),s(m.length/3<=512),s(g instanceof Float32Array),s(g.length%p==0),s(p>=3);var x=m.BYTES_PER_ELEMENT==4?m:new Uint32Array(m);return h(x,g,g.length/p,p*4)},computeMeshletBounds:function(m,g,p){return s(g instanceof Float32Array),s(g.length%p==0),s(p>=3),f(m,g,g.length/p,p*4)},computeSphereBounds:function(m,g,p,x){return s(m instanceof Float32Array),s(m.length%g==0),s(g>=3),s(!p||p instanceof Float32Array),s(!p||p.length%x==0),s(!p||x>=1),s(!p||m.length/g==p.length/x),x=x||0,b(m,m.length/g,g*4,p,x*4)}}}()});var ER={};Lb(ER,{MeshoptEncoder:()=>TB});var TR=ht(()=>{xR();yR();_R();vR()});function rc(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 Vf(e,t="|"){return e.map((n)=>Gf(n)).join(t)}function sc(e,t){if(typeof t==="bigint")return t.toString();return t}class Fb{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function ac(e){return new Fb(e)}function Ub(e){return e===null||e===void 0}function Yr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Bb(e,t){let n=e/t,i=Math.round(n),r=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-i)<r)return 0;return n-i}function mi(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function oc(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Sr(e){return oc(e._zod.def)??e._zod.def.shape}function zb(e,t,n){Object.defineProperty(e,t,{get(){let i=n();return mi(this,t,i),i},enumerable:!0,configurable:!0})}function Vb(e,t,n){if(t in e)mi(e,t,n);else e[t]=n}function ra(e,t,n,i){let r=Sr(t);for(let s of n){let a=Object.getOwnPropertyDescriptor(r,s);if(!a.enumerable)continue;if(a.get)zb(e,s,()=>{let o=t._zod.def.shape[s];return i?i(o,s):o});else Vb(e,s,i?i(a.value,s):a.value)}}function fI(e,t){for(let n of Reflect.ownKeys(t)){let i=Object.getOwnPropertyDescriptor(t,n);if(!i.enumerable)continue;if(i.get)zb(e,n,()=>t[n]);else Vb(e,n,i.value)}}function ei(...e){let t={};for(let n of e){let i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function jb(e){return JSON.stringify(e)}function Hb(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var jf="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ha(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Gb=ac(()=>{if(Bn.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function sa(e){if(Ha(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(Ha(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Hf(e){if(sa(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 $b=new Set(["string","number","symbol"]),Kb=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Rr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ji(e,t,n){let i=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)i._zod.parent=e;return i}function Ue(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 Gf(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Wb(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Kl=(()=>({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]}))(),$f={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function hI(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={};return ra(s,e,Wl(e,t)),Ji(e,ei(n,{shape:s,checks:[]}))}function Wl(e,t){let n=Sr(e),i=[];for(let r of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,r)?.enumerable)throw Error(`Unrecognized key: "${String(r)}"`);if(t[r])i.push(r)}return i}function pI(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=new Set(Wl(e,t)),a={};return ra(a,e,Reflect.ownKeys(Sr(e)).filter((o)=>!s.has(o))),Ji(e,ei(n,{shape:a,checks:[]}))}function mI(e,t){if(!sa(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let r=Sr(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(r,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ji(e,ei(e._zod.def,{shape:Xb(e,t)}))}function Xb(e,t){let n={};return ra(n,e,Reflect.ownKeys(Sr(e))),fI(n,t),n}function gI(e,t){if(!sa(t))throw Error("Invalid input to safeExtend: expected a plain object");return Ji(e,ei(e._zod.def,{shape:Xb(e,t)}))}function bI(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};ra(n,e,Reflect.ownKeys(Sr(e))),ra(n,t,Reflect.ownKeys(Sr(t)));let i=ei(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ji(e,i)}function qb(e,t,n,i="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw Error(`.${i}() cannot be used on object schemas containing refinements`);let o=n?new Set(Wl(t,n)):void 0,c={};return ra(c,t,Reflect.ownKeys(Sr(t)),e&&((l,u)=>o&&!o.has(u)?l:new e({type:"optional",innerType:l}))),Ji(t,ei(t._zod.def,{shape:c,checks:[]}))}function xI(e,t,n){let i=n?new Set(Wl(t,n)):void 0,r={};return ra(r,t,Reflect.ownKeys(Sr(t)),(s,a)=>i&&!i.has(a)?s:new e({type:"nonoptional",innerType:s})),Ji(t,ei(t._zod.def,{shape:r}))}function gi(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 Jb(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 Zi(e,t){return t.map((n)=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function ic(e){return typeof e==="string"?e:e?.message}function Kf(e,t,n){var i;for(let r=t;r<e.length;r++)(i=e[r]).schema??(i.schema=n)}function Yi(e,t,n){var i;let r=e.inst?._zod?.traits;if(r?.has("$ZodType"))if(r.has("$ZodCheck"))(i=e).schema??(i.schema=e.inst);else e.schema=e.inst;let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,a=e.message?e.message:ic(e.inst?._zod.def?.error?.(e))??ic(s?.(e))??ic(t?.error?.(e))??ic(n.customError?.(e))??ic(n.localeError?.(e))??"Invalid input",o={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;o[c]=e[c]}if(o.path??(o.path=[]),o.message=a,t?.reportInput)o.input=e.input;return o}var yI=/[\uD800-\uDBFF]/;function Xl(e){let t=e.length;if(!yI.test(e))return t;let n=t;for(let i=0;i<t-1;i++)if((e.charCodeAt(i)&64512)===55296&&(e.charCodeAt(i+1)&64512)===56320)n--,i++;return n}function ql(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Zb(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function aa(...e){let[t,n,i]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:i};return{...t}}function Yb(e,t){for(let n in t){let i=Object.getOwnPropertyDescriptor(t,n);if(i.get)Object.defineProperty(e,n,{...i,enumerable:!1});else _I(e,n,i.value)}}function Mr(e,t,n,i=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:i,value:n}),n}function Jl(e,t,n){return Mr(e,t,n,!1)}function Qb(e,t){for(let n in e){let i=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Mr(this,n,i(this))},set(r){Mr(this,n,r)}})}return t}function _I(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Mr(this,t,n.bind(this))},set(i){Mr(this,t,i)}})}function vI(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var zf,Zr=!1,EI={configurable:!0,get(){Zr=!0;return}};function Et(e,t,n){let i=Object.getPrototypeOf(e._zod);if(t in i&&zf!==e._zod){zf=void 0;return}zf=e._zod,Object.defineProperty(i,t,{configurable:!0,get(){Object.defineProperty(this,t,EI);let r=Zr;Zr=!1;try{let s=n(this);if(Zr)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s});return Zr=Zr||r,s}catch(s){throw delete this[t],Zr=Zr||r,s}},set(r){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r})}})}function TI(e,t,n,i){let r=vI(e,t);if(!r)return;Object.defineProperty(r,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:i,value:void 0};return Object.defineProperty(this,t,s),s.value=n(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:i,value:s})}})}var AI="~constantCatch";function ex(e){let t=()=>e;return t[AI]=!0,t}var tx;var Wf={value:void 0,enumerable:!1},nx="captureStackTrace"in Error?Error:null;function wI(e){let t=nx;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return nx=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function se(e,t,n,i){let r={};function s(f){this.def=f,this.constr=d,this.traits=new Set}s.prototype=r;let a=n,o=a&&new WeakSet;function c(f,h){if(!f._zod){Wf.value=new s(h);try{Object.defineProperty(f,"_zod",Wf)}finally{Wf.value=void 0}}else if(f._zod.traits.has(e))return;if(f._zod.traits.add(e),t(f,h),o){let m=Object.getPrototypeOf(f),g=f._zod.constr.prototype,p=m;while(p&&p!==g)p=Object.getPrototypeOf(p);let x=p??m;if(!o.has(x))o.add(x),Yb(x,a)}let b=d.prototype;for(let m in b){if(!Object.prototype.hasOwnProperty.call(b,m))continue;if(!(m in f))f[m]=b[m].bind(f)}}let l=i?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(f){let h=i?.Parent?wI(u):this;c(h,f);let b=h._zod.deferred;if(b){for(let g of b)g();h._zod.deferred=void 0}let m=globalThis.__zod_globalConfig?.postProcessor;if(m)m(h);return h}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:(f)=>{if(i?.Parent&&f instanceof i.Parent)return!0;return f?._zod?.traits?.has(e)}}),Object.defineProperty(d,"name",{value:e}),d}class Qi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class cc extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(tx=globalThis).__zod_globalConfig??(tx.__zod_globalConfig={});var Bn=globalThis.__zod_globalConfig;function ti(e){if(e)Object.assign(Bn,e);return Bn}function SI(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,sc,2)),e.message}function MI(e){this._zod.message=e}var RI={get:SI,set:MI,enumerable:!0,configurable:!0},qf={value:void 0,enumerable:!1},ix=new WeakSet([Object.prototype,Error.prototype]),rx=(e,t)=>{e.name="$ZodError",qf.value=t,Object.defineProperty(e,"issues",qf),qf.value=void 0,Object.defineProperty(e,"message",RI);let n=Object.getPrototypeOf(e);if(!ix.has(n))ix.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let i=()=>this.message;return Object.defineProperty(this,"toString",{value:i,configurable:!0,writable:!0}),i},set(i){Object.defineProperty(this,"toString",{value:i,configurable:!0,writable:!0})}})},sx=se("$ZodError",rx),HB=se("$ZodError",rx,void 0,{Parent:Error});function II(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function ax(e,t=(n)=>n.message){let n={},i=[];for(let r of e.issues)if(r.path.length>0)II(n,r.path[0],()=>[]).push(t(r));else i.push(t(r));return{formErrors:i,fieldErrors:n}}function ox(e,t=(n)=>n.message){let n={_errors:[]},i=(r,s=[])=>{for(let a of r.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map((o)=>i({issues:o},[...s,...a.path]));else if(a.code==="invalid_key")i({issues:a.issues},[...s,...a.path]);else if(a.code==="invalid_element")i({issues:a.issues},[...s,...a.path]);else{let o=[...s,...a.path];if(o.length===0)n._errors.push(t(a));else{let c=n,l=0;while(l<o.length){let u=o[l],d=l===o.length-1;if(u==="_errors"){if(d)c._errors.push(t(a));l++;continue}if(!Object.prototype.hasOwnProperty.call(c,u))Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let f=c[u];if(d)f._errors.push(t(a));c=f,l++}}}};return i(e),n}function Zl(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Yl=(e)=>{let t=(n,i,r,s)=>{let a=r?{...r,async:!1}:{async:!1},o=n._zod.run({value:i,issues:[]},a);if(o instanceof Promise)throw new Qi;if(o.issues.length){let c=new(s?.Err??e)(o.issues.map((l)=>Yi(l,a,ti())));throw jf(c,s?.callee??t),c}return o.value};return t};var Ql=(e)=>{let t=async(n,i,r,s)=>{let a=r?{...r,async:!0}:{async:!0},o=n._zod.run({value:i,issues:[]},a);if(o instanceof Promise)o=await o;if(o.issues.length){let c=new(s?.Err??e)(o.issues.map((l)=>Yi(l,a,ti())));throw jf(c,s?.callee??t),c}return o.value};return t};var eu=(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 Qi;return s.issues.length?cx(e,s.issues,r):{success:!0,data:s.value}};function cx(e,t,n){let i;return{success:!1,get error(){if(!i)i=new e(t.map((r)=>Yi(r,n,ti()))),t=void 0,n=void 0;return i},set error(r){i=r,t=void 0,n=void 0}}}var tu=(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?cx(e,s.issues,r):{success:!0,data:s.value}};var CI=Symbol.for("zod.compile.invalid"),NI=Symbol.for("zod.compile.fallback"),Jf=(e,t,n)=>{let i=e._zod.bag.validator;if(i!==void 0){if(i(t)!==CI)return!0;if(i.definite===!0&&n===void 0)return!1}return PI(e,t,n)};function PI(e,t,n){let i=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},r=e._zod.bag.fallbackRun,s;if(r)i[NI]=!0,s=r({value:t,issues:[]},i);else s=e._zod.run({value:t,issues:[]},i);if(s instanceof Promise)throw new Qi;return s.issues.length===0}var Zf=async(e,t,n)=>{let i=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},r=e._zod.run({value:t,issues:[]},i);if(r instanceof Promise)r=await r;return r.issues.length===0},lx=(e)=>{let t=Yl(e),n=(i,r,s,a)=>{let o=s?{...s,direction:"backward"}:{direction:"backward"};return t(i,r,o,Zl(n,a))};return n};var ux=(e)=>{let t=Yl(e),n=(i,r,s,a)=>t(i,r,s,Zl(n,a));return n};var dx=(e)=>{let t=Ql(e),n=async(i,r,s,a)=>{let o=s?{...s,direction:"backward"}:{direction:"backward"};return await t(i,r,o,Zl(n,a))};return n};var fx=(e)=>{let t=Ql(e),n=async(i,r,s,a)=>await t(i,r,s,Zl(n,a));return n};var hx=(e)=>(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return eu(e)(t,n,r)};var px=(e)=>(t,n,i)=>eu(e)(t,n,i);var mx=(e)=>async(t,n,i)=>{let r=i?{...i,direction:"backward"}:{direction:"backward"};return tu(e)(t,n,r)};var gx=(e)=>async(t,n,i)=>tu(e)(t,n,i);var bx=/^[cC][0-9a-z]{6,}$/,xx=/^[0-9a-z]+$/,yx=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,_x=/^[0-9a-vA-V]{20}$/,vx=/^[A-Za-z0-9]{27}$/,Ex=/^[a-zA-Z0-9_-]{21}$/;function Tx(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Ax=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var wx=/^([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})$/,Qf=(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 Sx=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var OI="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Mx(){return new RegExp(OI,"u")}var Rx=/^(?:(?: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])$/,Ix=/^(([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 Cx=/^((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])$/,Nx=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Px=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ox=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var kx=/^https?$/,Dx=/^\+[1-9]\d{6,14}$/;var Lx="(?:(?:\\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])))";function kI(e){return new RegExp(`^${e}$`)}var Fx=kI(Lx);function Yf(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}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Ux(e){return new RegExp(`^${Yf(e)}$`)}function Bx(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${Yf({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,i=e.local?`${n}|${Yf({precision:e.precision})}`:n;return new RegExp(`^${Lx}T(?:${i})$`)}var zx=/^[\s\S]{0,}$/,Vx=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var nu=/^-?\d+$/,Ga=/^-?\d+(?:\.\d+)?$/,jx=/^(?:true|false)$/i;var Hx=/^[^A-Z]*$/,Gx=/^[^a-z]*$/;var Sn=se("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var eh=(e)=>{let t=e.value;return!Ub(t)&&t.length!==void 0},iu={number:"number",bigint:"bigint",object:"date"},th=se("$ZodCheckLessThan",(e,t)=>{Sn.init(e,t);let n=iu[typeof t.value];e._zod.check=(i)=>{if(t.inclusive?i.value<=t.value:i.value<t.value)return;i.issues.push({origin:iu[typeof i.value]??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})}}),nh=se("$ZodCheckGreaterThan",(e,t)=>{Sn.init(e,t);let n=iu[typeof t.value];e._zod.check=(i)=>{if(t.inclusive?i.value>=t.value:i.value>t.value)return;i.issues.push({origin:iu[typeof i.value]??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})}}),$x=se("$ZodCheckMultipleOf",(e,t)=>{Sn.init(e,t),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"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Bb(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})}}),Kx=se("$ZodCheckNumberFormat",(e,t)=>{Sn.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),i=n?"int":"number",[r,s]=Kl[t.format];e._zod.check=(a)=>{let o=a.value;if(n){if(!Number.isInteger(o)){a.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});return}if(!Number.isSafeInteger(o)){if(o>0)a.issues.push({input:o,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 a.issues.push({input:o,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(o<r)a.issues.push({origin:"number",input:o,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort});if(o>s)a.issues.push({origin:"number",input:o,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Wx=se("$ZodCheckMaxLength",(e,t)=>{var n;Sn.init(e,t),(n=e._zod.def).when??(n.when=eh),e._zod.check=(i)=>{let r=i.value,s=r.length;if((typeof r==="string"&&s>t.maximum?Xl(r):s)<=t.maximum)return;let o=ql(r);i.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Xx=se("$ZodCheckMinLength",(e,t)=>{var n;Sn.init(e,t),(n=e._zod.def).when??(n.when=eh),e._zod.check=(i)=>{let r=i.value,s=r.length;if((typeof r==="string"&&s>=t.minimum&&s<t.minimum*2?Xl(r):s)>=t.minimum)return;let o=ql(r);i.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qx=se("$ZodCheckLengthEquals",(e,t)=>{var n;Sn.init(e,t),(n=e._zod.def).when??(n.when=eh),e._zod.check=(i)=>{let r=i.value,s=r.length,a=typeof r==="string"&&s>=t.length&&s<=t.length*2?Xl(r):s;if(a===t.length)return;let o=ql(r),c=a>t.length;i.issues.push({origin:o,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),uc=se("$ZodCheckStringFormat",(e,t)=>{var n,i;if(Sn.init(e,t),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=()=>{})}),Jx=se("$ZodCheckRegex",(e,t)=>{uc.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})}}),Zx=se("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Hx),uc.init(e,t)}),Yx=se("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Gx),uc.init(e,t)}),Qx=se("$ZodCheckIncludes",(e,t)=>{Sn.init(e,t);let n=Rr(t.includes),i=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=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})}}),ey=se("$ZodCheckStartsWith",(e,t)=>{Sn.init(e,t);let n=new RegExp(`^${Rr(t.prefix)}.*`);t.pattern??(t.pattern=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})}}),ty=se("$ZodCheckEndsWith",(e,t)=>{Sn.init(e,t);let n=new RegExp(`.*${Rr(t.suffix)}$`);t.pattern??(t.pattern=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 ny=se("$ZodCheckOverwrite",(e,t)=>{Sn.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class ih{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{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?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {${t.join(``)}-};`)(...Object.values(this.closed))}}var ey={major:4,minor:6,patch:5};var Ut=se("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ey;let i=e._zod.def.checks,r=e._zod.traits.has("$ZodCheck")?[e,...i??[]]:i?.length?[...i]:[];for(let s of r)for(let a of s._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(o,c,l)=>{if(o.memo)return o;let u=gi(o),d;for(let f of c){if(f._zod.def.when){if(Kb(o))continue;if(!f._zod.def.when(o))continue}else if(u)continue;let h=o.issues.length,b=f._zod.check(o);if(b instanceof Promise&&l?.async===!1)throw new Qi;if(d||b instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await b,o.issues.length===h)return;if(Vf(o.issues,h,e),!u)u=gi(o,h)});else{if(o.issues.length===h)continue;if(Vf(o.issues,h,e),!u)u=gi(o,h)}}if(d)return d.then(()=>o);return o},a=(o,c,l)=>{if(gi(o))return o.aborted=!0,o;let u=s(c,r,l);if(u instanceof Promise){if(l.async===!1)throw new Qi;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(o,c)=>{if(c.skipChecks)return e._zod.parse(o,c);if(c.direction==="backward"){let u=e._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>a(d,o,c));return a(u,o,c)}let l=e._zod.parse(o,c);if(l instanceof Promise){if(c.async===!1)throw new Qi;return l.then((u)=>s(u,r,c))}return s(l,r,c)}}},{get "~standard"(){return Kl(this,"~standard",th(this))},set "~standard"(e){Mr(this,"~standard",e)}}),py=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>Yi(n,t,ei()))}:{value:e.value};async function CI(e,t){let n={async:!0};return py(await e._zod.run({value:t,issues:[]},n),n)}function th(e){return{validate:(t)=>{let n={async:!1};try{let i=e._zod.run({value:t,issues:[]},n);if(!(i instanceof Promise))return py(i,n)}catch(i){}return CI(e,t)},vendor:"zod",version:1}}var iu=se("$ZodString",(e,t)=>{Ut.init(e,t),e._zod.pattern=t.pattern??Lx,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=se("$ZodStringFormat",(e,t)=>{lc.init(e,t),iu.init(e,t)}),my=se("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=vx),$t.init(e,t)}),gy=se("$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=Xf(i))}else t.pattern??(t.pattern=Xf());$t.init(e,t)}),by=se("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ex),$t.init(e,t)}),xy=1,tu=2;function yy(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function NI(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return yy(e)||tu;return PI(e,t)}function PI(e,t){if(!t.normalize&&t.protocol?.source===Cx.source&&!/^https?:\/\//i.test(e))return xy;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??tu}return new URL(e)}catch{return tu}}var OI=/[\t\n\r]/g;function ty(e){return e.replace(OI,"")}function kI(e,t){return t.lastIndex=0,t.test(e.hostname)}function DI(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var _y=se("$ZodURL",(e,t)=>{$t.init(e,t),e._zod.check=(n)=>{try{let i=n.value.trim(),r=NI(i,t);if(r===xy){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(r===tu){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(r===!0){n.value=ty(i);return}if(t.hostname&&!kI(r,t.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&&!DI(r,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?r.href:ty(i);return}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),vy=se("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Tx()),$t.init(e,t)}),Ey=se("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?xx:yx(t.length)),$t.init(e,t)}),Ty=se("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=hx),$t.init(e,t)}),Ay=se("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=px),$t.init(e,t)}),wy=se("$ZodULID",(e,t)=>{t.pattern??(t.pattern=mx),$t.init(e,t)}),Sy=se("$ZodXID",(e,t)=>{t.pattern??(t.pattern=gx),$t.init(e,t)}),My=se("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=bx),$t.init(e,t)}),Ry=se("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Dx(t)),$t.init(e,t)}),Iy=se("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ox),$t.init(e,t)}),Cy=se("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=kx(t)),$t.init(e,t)}),Ny=se("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=_x),$t.init(e,t)}),Py=se("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ax),$t.init(e,t)}),LI=/^[0-9a-fA-F:.]+$/;function Oy(e){if(!LI.test(e))return!1;return yy(`http://[${e}]`)}var ky=se("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=wx),$t.init(e,t),e._zod.check=(n)=>{if(!Oy(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}});var Dy=se("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Sx),$t.init(e,t)});function FI(e){let t=e.split("/");if(t.length!==2)return!1;let[n,i]=t;if(!i)return!1;let r=Number(i);if(`${r}`!==i)return!1;if(r<0||r>128)return!1;return Oy(n)}var Ly=se("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Mx),$t.init(e,t),e._zod.check=(n)=>{if(!FI(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function Fy(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 nh=/^[0-9a-zA-Z+/]*={0,2}$/,Uy=se("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=nh),$t.init(e,t),e._zod.check=(n)=>{if(Fy(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),ru=/^[A-Za-z0-9_-]*$/;function UI(e){if(!ru.test(e))return!1;let t=e.replace(/[-_]/g,(i)=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Fy(n)}var By=se("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ru),$t.init(e,t),e._zod.check=(n)=>{if(UI(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),zy=se("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Nx),$t.init(e,t)});function BI(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 Vy=se("$ZodJWT",(e,t)=>{$t.init(e,t),e._zod.check=(n)=>{if(BI(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var ih=se("$ZodNumber",(e,t)=>{Ut.init(e,t),e._zod.pattern=Ha,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}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)?String(r):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),n}}),jy=se("$ZodNumberFormat",(e,t)=>{jx.init(e,t),ih.init(e,t)}),Hy=se("$ZodBoolean",(e,t)=>{Ut.init(e,t),e._zod.pattern=Ux,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 Gy=se("$ZodUnknown",(e,t)=>{Ut.init(e,t),e._zod.parse=(n)=>n}),$y=se("$ZodNever",(e,t)=>{Ut.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function ny(e,t,n){if(e.issues.length)t.issues.push(...Zi(n,e.issues));t.value[n]=e.value}var Ky=se("$ZodArray",(e,t)=>{Ut.init(e,t);let n=Un.memoizer;n?.attach(e),e._zod.parse=(i,r)=>{let s=i.value;if(!Array.isArray(s))return i.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),i;i.value=n?n.alloc(e,i,Array(s.length),r):Array(s.length);let a=[],o=r?.abortEarly;for(let c=0;c<s.length;c++){let l=s[c],u=t.element._zod.run({value:l,issues:[]},r);if(u instanceof Promise)a.push(u.then((d)=>ny(d,i,c)));else if(ny(u,i,c),o&&u.issues.length!==0&&gi(u))break}if(a.length)return Promise.all(a).then(()=>i);return i}});function nu(e,t,n,i,r,s){let a=n in i,o=s==="optional";if(!a&&o&&r==="optional")return;if(e.issues.length){if(r!==void 0&&o&&!a)return;t.issues.push(...Zi(n,e.issues))}if(!a&&r===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(a||r==="defaulted"&&!o)t.value[n]=void 0}else t.value[n]=e.value}var zI=[];function Wy(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),i=n.length?n:zI,r=i.length?[...t,...i]:t;for(let a of r)if(!e.shape?.[a]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(a)}": expected a Zod schema`);let s=Hb(e.shape);return{...e,allKeys:r,symbolKeys:i,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function Xy(e,t,n,i,r,s,a){let o=[],c=r.keySet,l=r.catchall._zod,u=l.def.type,{optin:d,optout:f}=l,h=0;for(let b in t){if(a&&n.issues.length!==h){if(gi(n,h))break;h=n.issues.length}if(c.has(b))continue;if(b==="__proto__"){if(u==="never")o.push(b);continue}if(u==="never"){o.push(b);continue}let m=l.run({value:t[b],issues:[]},i);if(m instanceof Promise)e.push(m.then((g)=>nu(g,n,b,t,d,f)));else nu(m,n,b,t,d,f)}if(o.length)n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}var VI=se("$ZodObject",(e,t)=>{Ut.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),i=n?.get?n.get.raw:t.shape??{};if(i){let l=()=>{let u={...i};return Object.defineProperty(t,"shape",{value:u}),l.raw=u,u};l.raw=i,Object.defineProperty(t,"shape",{get:l})}let r=sc(()=>Wy(t));Et(e,"propValues",(l)=>{let u=l.def.shape,d={};for(let f in u){let h=u[f]._zod;if(h.values){if(!Object.prototype.hasOwnProperty.call(d,f))mi(d,f,new Set);for(let b of h.values)d[f].add(b);if(h.optin!==void 0)d[f].add(void 0)}}return d});let s=ja,a=t.catchall,o,c=Un.memoizer;c?.attach(e),e._zod.parse=(l,u)=>{o??(o=r.value);let d=l.value;if(!s(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;l.value=c?c.alloc(e,l,{},u):{};let f=[],h=o.shape,b=u?.abortEarly,m=l.issues.length;for(let g of o.allKeys){if(b&&l.issues.length!==m){if(gi(l,m))break;m=l.issues.length}if(g==="__proto__")continue;let p=h[g],x=p._zod.optin,_=p._zod.optout,y=p._zod.run({value:d[g],issues:[]},u);if(y instanceof Promise)f.push(y.then((v)=>nu(v,l,g,d,x,_)));else nu(y,l,g,d,x,_)}if(!a)return f.length?Promise.all(f).then(()=>l):l;return Xy(f,d,l,u,r.value,e,b===!0)}}),qy=se("$ZodObjectJIT",(e,t)=>{VI.init(e,t);let n=e._zod.parse,i=sc(()=>Wy(t)),r=Un.memoizer,s=(h)=>{let b=i.value,m=b.symbolKeys,g=new Yf(["payload","ctx"],{shape:h,inst:e,memo:r,syms:m}),p=(v)=>`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`,x=(v,T)=>`+};`)(...Object.values(this.closed))}}var ry={major:4,minor:6,patch:5};var Ut=se("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ry;let i=e._zod.def.checks,r=e._zod.traits.has("$ZodCheck")?[e,...i??[]]:i?.length?[...i]:[];for(let s of r)for(let a of s._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(o,c,l)=>{if(o.memo)return o;let u=gi(o),d;for(let f of c){if(f._zod.def.when){if(Jb(o))continue;if(!f._zod.def.when(o))continue}else if(u)continue;let h=o.issues.length,b=f._zod.check(o);if(b instanceof Promise&&l?.async===!1)throw new Qi;if(d||b instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await b,o.issues.length===h)return;if(Kf(o.issues,h,e),!u)u=gi(o,h)});else{if(o.issues.length===h)continue;if(Kf(o.issues,h,e),!u)u=gi(o,h)}}if(d)return d.then(()=>o);return o},a=(o,c,l)=>{if(gi(o))return o.aborted=!0,o;let u=s(c,r,l);if(u instanceof Promise){if(l.async===!1)throw new Qi;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(o,c)=>{if(c.skipChecks)return e._zod.parse(o,c);if(c.direction==="backward"){let u=e._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>a(d,o,c));return a(u,o,c)}let l=e._zod.parse(o,c);if(l instanceof Promise){if(c.async===!1)throw new Qi;return l.then((u)=>s(u,r,c))}return s(l,r,c)}}},{get "~standard"(){return Jl(this,"~standard",ah(this))},set "~standard"(e){Mr(this,"~standard",e)}}),xy=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>Yi(n,t,ti()))}:{value:e.value};async function DI(e,t){let n={async:!0};return xy(await e._zod.run({value:t,issues:[]},n),n)}function ah(e){return{validate:(t)=>{let n={async:!1};try{let i=e._zod.run({value:t,issues:[]},n);if(!(i instanceof Promise))return xy(i,n)}catch(i){}return DI(e,t)},vendor:"zod",version:1}}var ou=se("$ZodString",(e,t)=>{Ut.init(e,t),e._zod.pattern=t.pattern??zx,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=se("$ZodStringFormat",(e,t)=>{uc.init(e,t),ou.init(e,t)}),yy=se("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=wx),$t.init(e,t)}),_y=se("$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=Qf(i))}else t.pattern??(t.pattern=Qf());$t.init(e,t)}),vy=se("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Sx),$t.init(e,t)}),Ey=1,su=2;function Ty(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function LI(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return Ty(e)||su;return FI(e,t)}function FI(e,t){if(!t.normalize&&t.protocol?.source===kx.source&&!/^https?:\/\//i.test(e))return Ey;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??su}return new URL(e)}catch{return su}}var UI=/[\t\n\r]/g;function sy(e){return e.replace(UI,"")}function BI(e,t){return t.lastIndex=0,t.test(e.hostname)}function zI(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Ay=se("$ZodURL",(e,t)=>{$t.init(e,t),e._zod.check=(n)=>{try{let i=n.value.trim(),r=LI(i,t);if(r===Ey){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(r===su){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(r===!0){n.value=sy(i);return}if(t.hostname&&!BI(r,t.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&&!zI(r,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?r.href:sy(i);return}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),wy=se("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Mx()),$t.init(e,t)}),Sy=se("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Ex:Tx(t.length)),$t.init(e,t)}),My=se("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=bx),$t.init(e,t)}),Ry=se("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=xx),$t.init(e,t)}),Iy=se("$ZodULID",(e,t)=>{t.pattern??(t.pattern=yx),$t.init(e,t)}),Cy=se("$ZodXID",(e,t)=>{t.pattern??(t.pattern=_x),$t.init(e,t)}),Ny=se("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=vx),$t.init(e,t)}),Py=se("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Bx(t)),$t.init(e,t)}),Oy=se("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Fx),$t.init(e,t)}),ky=se("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ux(t)),$t.init(e,t)}),Dy=se("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ax),$t.init(e,t)}),Ly=se("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Rx),$t.init(e,t)}),VI=/^[0-9a-fA-F:.]+$/;function Fy(e){if(!VI.test(e))return!1;return Ty(`http://[${e}]`)}var Uy=se("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ix),$t.init(e,t),e._zod.check=(n)=>{if(!Fy(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}});var By=se("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Cx),$t.init(e,t)});function jI(e){let t=e.split("/");if(t.length!==2)return!1;let[n,i]=t;if(!i)return!1;let r=Number(i);if(`${r}`!==i)return!1;if(r<0||r>128)return!1;return Fy(n)}var zy=se("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Nx),$t.init(e,t),e._zod.check=(n)=>{if(!jI(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function Vy(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 oh=/^[0-9a-zA-Z+/]*={0,2}$/,jy=se("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=oh),$t.init(e,t),e._zod.check=(n)=>{if(Vy(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),cu=/^[A-Za-z0-9_-]*$/;function HI(e){if(!cu.test(e))return!1;let t=e.replace(/[-_]/g,(i)=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Vy(n)}var Hy=se("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=cu),$t.init(e,t),e._zod.check=(n)=>{if(HI(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Gy=se("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Dx),$t.init(e,t)});function GI(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 $y=se("$ZodJWT",(e,t)=>{$t.init(e,t),e._zod.check=(n)=>{if(GI(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var ch=se("$ZodNumber",(e,t)=>{Ut.init(e,t),e._zod.pattern=Ga,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}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)?String(r):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),n}}),Ky=se("$ZodNumberFormat",(e,t)=>{Kx.init(e,t),ch.init(e,t)}),Wy=se("$ZodBoolean",(e,t)=>{Ut.init(e,t),e._zod.pattern=jx,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 Xy=se("$ZodUnknown",(e,t)=>{Ut.init(e,t),e._zod.parse=(n)=>n}),qy=se("$ZodNever",(e,t)=>{Ut.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function ay(e,t,n){if(e.issues.length)t.issues.push(...Zi(n,e.issues));t.value[n]=e.value}var Jy=se("$ZodArray",(e,t)=>{Ut.init(e,t);let n=Bn.memoizer;n?.attach(e),e._zod.parse=(i,r)=>{let s=i.value;if(!Array.isArray(s))return i.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),i;i.value=n?n.alloc(e,i,Array(s.length),r):Array(s.length);let a=[],o=r?.abortEarly;for(let c=0;c<s.length;c++){let l=s[c],u=t.element._zod.run({value:l,issues:[]},r);if(u instanceof Promise)a.push(u.then((d)=>ay(d,i,c)));else if(ay(u,i,c),o&&u.issues.length!==0&&gi(u))break}if(a.length)return Promise.all(a).then(()=>i);return i}});function au(e,t,n,i,r,s){let a=n in i,o=s==="optional";if(!a&&o&&r==="optional")return;if(e.issues.length){if(r!==void 0&&o&&!a)return;t.issues.push(...Zi(n,e.issues))}if(!a&&r===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(a||r==="defaulted"&&!o)t.value[n]=void 0}else t.value[n]=e.value}var $I=[];function Zy(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),i=n.length?n:$I,r=i.length?[...t,...i]:t;for(let a of r)if(!e.shape?.[a]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(a)}": expected a Zod schema`);let s=Wb(e.shape);return{...e,allKeys:r,symbolKeys:i,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function Yy(e,t,n,i,r,s,a){let o=[],c=r.keySet,l=r.catchall._zod,u=l.def.type,{optin:d,optout:f}=l,h=0;for(let b in t){if(a&&n.issues.length!==h){if(gi(n,h))break;h=n.issues.length}if(c.has(b))continue;if(b==="__proto__"){if(u==="never")o.push(b);continue}if(u==="never"){o.push(b);continue}let m=l.run({value:t[b],issues:[]},i);if(m instanceof Promise)e.push(m.then((g)=>au(g,n,b,t,d,f)));else au(m,n,b,t,d,f)}if(o.length)n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}var KI=se("$ZodObject",(e,t)=>{Ut.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),i=n?.get?n.get.raw:t.shape??{};if(i){let l=()=>{let u={...i};return Object.defineProperty(t,"shape",{value:u}),l.raw=u,u};l.raw=i,Object.defineProperty(t,"shape",{get:l})}let r=ac(()=>Zy(t));Et(e,"propValues",(l)=>{let u=l.def.shape,d={};for(let f in u){let h=u[f]._zod;if(h.values){if(!Object.prototype.hasOwnProperty.call(d,f))mi(d,f,new Set);for(let b of h.values)d[f].add(b);if(h.optin!==void 0)d[f].add(void 0)}}return d});let s=Ha,a=t.catchall,o,c=Bn.memoizer;c?.attach(e),e._zod.parse=(l,u)=>{o??(o=r.value);let d=l.value;if(!s(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;l.value=c?c.alloc(e,l,{},u):{};let f=[],h=o.shape,b=u?.abortEarly,m=l.issues.length;for(let g of o.allKeys){if(b&&l.issues.length!==m){if(gi(l,m))break;m=l.issues.length}if(g==="__proto__")continue;let p=h[g],x=p._zod.optin,_=p._zod.optout,y=p._zod.run({value:d[g],issues:[]},u);if(y instanceof Promise)f.push(y.then((v)=>au(v,l,g,d,x,_)));else au(y,l,g,d,x,_)}if(!a)return f.length?Promise.all(f).then(()=>l):l;return Yy(f,d,l,u,r.value,e,b===!0)}}),Qy=se("$ZodObjectJIT",(e,t)=>{KI.init(e,t);let n=e._zod.parse,i=ac(()=>Zy(t)),r=Bn.memoizer,s=(h)=>{let b=i.value,m=b.symbolKeys,g=new ih(["payload","ctx"],{shape:h,inst:e,memo:r,syms:m}),p=(v)=>`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`,x=(v,E)=>`let ${v}_ab = false;for (let i = 0; i < ${v}.issues.length; i++) {const iss = ${v}.issues[i];- iss.path = iss.path ? [${T}, ...iss.path] : [${T}];+ iss.path = iss.path ? [${E}, ...iss.path] : [${E}];payload.issues.push(iss);if (iss.continue !== true) ${v}_ab = true;}if (${v}_ab && ctx && ctx.abortEarly) {payload.value = newResult;return payload;- }`;g.write("const input = payload.value;");let _=Object.create(null),y=0;for(let v of b.allKeys)_[v]=`key_${y++}`;g.write(r?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let v of b.allKeys){if(v==="__proto__")continue;let T=_[v],A=typeof v==="symbol"?`syms[${m.indexOf(v)}]`:Ub(v),E=`${A} in input`,w=h[v],P=w?._zod?.optin,S=P!==void 0,I=w?._zod?.optout==="optional";if(g.write(`const ${T} = ${p(A)};`),S&&I){let U=P==="optional"?`${T}_present`:`${T}.value !== undefined || ${T}_present`;g.write(`- const ${T}_present = ${E};- if (!${T}.issues.length || ${T}_present) {- if (${T}.issues.length) {${x(T,A)}+ }`;g.write("const input = payload.value;");let _=Object.create(null),y=0;for(let v of b.allKeys)_[v]=`key_${y++}`;g.write(r?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let v of b.allKeys){if(v==="__proto__")continue;let E=_[v],w=typeof v==="symbol"?`syms[${m.indexOf(v)}]`:jb(v),T=`${w} in input`,A=h[v],P=A?._zod?.optin,S=P!==void 0,R=A?._zod?.optout==="optional";if(g.write(`const ${E} = ${p(w)};`),S&&R){let k=P==="optional"?`${E}_present`:`${E}.value !== undefined || ${E}_present`;g.write(`+ const ${E}_present = ${T};+ if (!${E}.issues.length || ${E}_present) {+ if (${E}.issues.length) {${x(E,w)}}- if (${U}) {- newResult[${A}] = ${T}.value;+ if (${k}) {+ newResult[${w}] = ${E}.value;}}`)}else if(!S)g.write(`- const ${T}_present = ${E};- if (${T}.issues.length) {${x(T,A)}+ const ${E}_present = ${T};+ if (${E}.issues.length) {${x(E,w)}}- if (!${T}_present && !${T}.issues.length) {+ if (!${E}_present && !${E}.issues.length) {payload.issues.push({code: "invalid_type",expected: "nonoptional",input: undefined,- path: [${A}]+ path: [${w}]});if (ctx && ctx.abortEarly) {payload.value = newResult;@@ -4283,22 +4283,22 @@ ${t.join(`}}- if (${T}_present) {- newResult[${A}] = ${T}.value;+ if (${E}_present) {+ newResult[${w}] = ${E}.value;}`);else if(g.write(`- if (${T}.issues.length) {${x(T,A)}+ if (${E}.issues.length) {${x(E,w)}}- `),P==="defaulted")g.write(`newResult[${A}] = ${T}.value;`);else g.write(`- if (${T}.value !== undefined || ${E}) {- newResult[${A}] = ${T}.value;+ `),P==="defaulted")g.write(`newResult[${w}] = ${E}.value;`);else g.write(`+ if (${E}.value !== undefined || ${T}) {+ newResult[${w}] = ${E}.value;}- `)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()},a,o=ja,c=!Un.jitless,u=c&&zb.value,d=t.catchall,f;e._zod.parse=(h,b)=>{f??(f=i.value);let m=h.value;if(!o(m))return h.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),h;if(c&&u&&b?.async===!1&&b.jitless!==!0){if(!a)a=s(t.shape);if(h=a(h,b),!d)return h;return Xy([],m,h,b,f,e,b?.abortEarly===!0)}return n(h,b)}});function iy(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)=>!gi(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((a)=>Yi(a,i,ei())))}),t}var rh=se("$ZodUnion",(e,t)=>{Ut.init(e,t),Et(e,"optin",(i)=>i.def.options.some((r)=>r._zod.optin==="defaulted")?"defaulted":i.def.options.some((r)=>r._zod.optin!==void 0)?"optional":void 0),Et(e,"optout",(i)=>i.def.options.some((r)=>r._zod.optout==="optional")?"optional":void 0),Et(e,"values",(i)=>{if(i.def.options.every((r)=>r._zod.values))return new Set(i.def.options.flatMap((r)=>Array.from(r._zod.values)));return}),Et(e,"pattern",(i)=>{if(i.def.options.every((r)=>r._zod.pattern)){let r=i.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${r.map((s)=>Yr(s.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,a=[];for(let o of t.options){let c=o._zod.run({value:i.value,issues:[]},r);if(c instanceof Promise)a.push(c),s=!0;else{if(c.issues.length===0)return c;a.push(c)}}if(!s)return iy(a,i,e,r);return Promise.all(a).then((o)=>iy(o,i,e,r))}});function jI(e){let t=new Map;for(let n of e.options){let i=n._zod.propValues?.[e.discriminator];if(!i||i.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let r of i)if(t.has(r)){if(r!==void 0)throw Error(`Duplicate discriminator value "${String(r)}"`);t.set(r,null)}else t.set(r,n)}return t}var Jy=se("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,rh.init(e,t);let n=e._zod.parse;Et(e,"propValues",(r)=>{let s={},a=0;for(let o of r.def.options){let c=o._zod.propValues;if(!c||Object.keys(c).length===0)throw Error(`Invalid discriminated union option at index "${r.def.options.indexOf(o)}"`);if(c[r.def.discriminator]?.has(void 0))a++;for(let[l,u]of Object.entries(c)){if(!Object.prototype.hasOwnProperty.call(s,l))mi(s,l,new Set);for(let d of u)s[l].add(d)}}if(!r.def.unionFallback&&a>1)s[r.def.discriminator]?.delete(void 0);return s}),t.options.forEach((r,s)=>{let a=ac(r._zod.def);if(a&&!Object.prototype.hasOwnProperty.call(a,t.discriminator))throw Error(`Invalid discriminated union option at index "${s}"`)});let i=sc(()=>jI(t));e._zod.parse=(r,s)=>{let a=r.value;if(!ja(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;let o=a?.[t.discriminator],c=i.value.get(o);if(c&&(o!==void 0||s.direction!=="backward"))return c._zod.run(r,s);if(t.unionFallback||s.direction==="backward")return n(r,s);return r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(i.value.keys()).filter((l)=>i.value.get(l)!==null),input:a,path:[t.discriminator],inst:e}),r}}),Zy=se("$ZodIntersection",(e,t)=>{Ut.init(e,t),e._zod.parse=(n,i)=>{let r=n.value,s=t.left._zod.run({value:r,issues:[]},i),a=t.right._zod.run({value:r,issues:[]},i);if(s instanceof Promise||a instanceof Promise)return Promise.all([s,a]).then(([c,l])=>ry(n,c,l));return ry(n,s,a)}});function Qf(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(ra(e)&&ra(t)){let n=Object.keys(t),i=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),r={...e,...t};if(Object.prototype.hasOwnProperty.call(r,"__proto__"))delete r.__proto__;for(let s of i){if(s==="__proto__")continue;let a=Qf(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};r[s]=a.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],a=Qf(r,s);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ry(e,t,n){let i=new Map,r,s=new Map,a=(l,u)=>{let d;if(l.code==="unrecognized_keys"&&!l.path?.length)r??(r=l),d=l.keys;else if(l.code==="invalid_key"&&l.origin==="record"&&l.path?.length===1){let f=String(l.path[0]);if(!s.has(f))s.set(f,l);d=[f]}else return!1;for(let f of d){if(!i.has(f))i.set(f,{});i.get(f)[u]=!0}return!0};for(let l of t.issues)if(!a(l,"l"))e.issues.push(l);for(let l of n.issues)if(!a(l,"r"))e.issues.push(l);let o=[...i].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(o.length){let l=r?o.filter((u)=>r.keys.includes(u)):[];if(l.length)e.issues.push({...r,keys:l});for(let u of o)if(!l.includes(u)&&s.has(u))e.issues.push(s.get(u))}let c=Qf(t.value,n.value);if(!c.valid){if(gi(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Yy=se("$ZodTuple",(e,t)=>{Ut.init(e,t);let n=t.items,i=Un.memoizer;i?.attach(e),e._zod.parse=(r,s)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=i?i.alloc(e,r,[],s):[];let o=[],c=sy(n,"optin"),l=sy(n,"optout");if(!t.rest){if(a.length<c)return r.issues.push({code:"too_small",minimum:c,inclusive:!0,input:a,inst:e,origin:"array"}),r;if(a.length>n.length)r.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:a,inst:e,origin:"array"})}let u=Array(n.length),d=t.rest?s?.abortEarly:void 0,f=!1;for(let h=0;h<n.length;h++){let b=n[h]._zod.run({value:a[h],issues:[]},s);if(b instanceof Promise)o.push(b.then((m)=>{u[h]=m}));else if(u[h]=b,d&&!f&&b.issues.length)f=gi(b)}if(t.rest&&!f){let h=n.length-1,b=a.slice(n.length),m=r.issues.length;for(let g of b){if(d&&r.issues.length!==m){if(gi(r,m))break;m=r.issues.length}h++;let p=t.rest._zod.run({value:g,issues:[]},s);if(p instanceof Promise)o.push(p.then((x)=>ay(x,r,h)));else ay(p,r,h)}}if(o.length)return Promise.all(o).then(()=>oy(u,r,n,a,l));return oy(u,r,n,a,l)}});function sy(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function ay(e,t,n){if(e.issues.length)t.issues.push(...Zi(n,e.issues));t.value[n]=e.value}function oy(e,t,n,i,r){for(let s=0;s<n.length;s++){let a=e[s],o=s<i.length;if(!o&&s>=r&&n[s]._zod.optin==="optional"){t.value.length=s;break}if(a.issues.length){if(!o&&s>=r){t.value.length=s;break}t.issues.push(...Zi(s,a.issues))}t.value[s]=a.value}for(let s=t.value.length-1;s>=i.length;s--)if(n[s]._zod.optout==="optional"&&t.value[s]===void 0)t.value.length=s;else break;return t}var Qy=se("$ZodRecord",(e,t)=>{Ut.init(e,t);let n=Un.memoizer;n?.attach(e),e._zod.parse=(i,r)=>{let s=i.value;if(!ra(s))return i.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),i;let a=[],o=t.keyType._zod.values;if(o&&!t.partial){i.value=n?n.alloc(e,i,{},r):{};let c=new Set;for(let u of o)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let d=t.keyType._zod.run({value:u,issues:[]},r);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){i.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((b)=>Yi(b,r,ei())),input:u,path:[u],inst:e});continue}let f=d.value;if(f==="__proto__")continue;let h=t.valueType._zod.run({value:s[u],issues:[]},r);if(h instanceof Promise)a.push(h.then((b)=>{if(b.issues.length)i.issues.push(...Zi(u,b.issues));i.value[f]=b.value}));else{if(h.issues.length)i.issues.push(...Zi(u,h.issues));i.value[f]=h.value}}let l;for(let u in s)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;i.value[u]=s[u]}else l=l??[],l.push(u);if(l&&l.length>0)i.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:l,continue:!0})}else{i.value=n?n.alloc(e,i,{},r):{};let c;for(let l of Reflect.ownKeys(s)){if(l==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,l))continue;let u=t.keyType._zod.run({value:l,issues:[]},r);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof l==="string"&&Ha.test(l)&&u.issues.length){let b=t.keyType._zod.run({value:Number(l),issues:[]},r);if(b instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(b.issues.length===0)u=b}if(u.issues.length){if(t.mode==="loose")i.value[l]=s[l];else if(o)c=c??[],c.push(l);else i.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((b)=>Yi(b,r,ei())),input:l,path:[l],inst:e});continue}let f=u.value;if(f==="__proto__")continue;let h=t.valueType._zod.run({value:s[l],issues:[]},r);if(h instanceof Promise)a.push(h.then((b)=>{if(b.issues.length)i.issues.push(...Zi(l,b.issues));i.value[f]=b.value}));else{if(h.issues.length)i.issues.push(...Zi(l,h.issues));i.value[f]=h.value}}if(c&&c.length>0)i.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}if(a.length)return Promise.all(a).then(()=>i);return i}});var e_=se("$ZodEnum",(e,t)=>{Ut.init(e,t);let n=ic(t.entries),i=new Set(n);e._zod.values=i,Et(e,"pattern",(r)=>{let s=ic(r.def.entries).filter((a)=>Vb.has(typeof a));return new RegExp(s.length?`^(${s.map((a)=>Rr(a.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,s)=>{let a=r.value;if(i.has(a))return r;return r.issues.push({code:"invalid_value",values:n,input:a,inst:e}),r}}),t_=se("$ZodLiteral",(e,t)=>{Ut.init(e,t);let n=new Set(t.values);e._zod.values=n,Et(e,"pattern",(i)=>{let r=i.def.values;return new RegExp(r.length?`^(${r.map((s)=>typeof s==="string"?Rr(s):s?Rr(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),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 n_=se("$ZodTransform",(e,t)=>{Ut.init(e,t),e._zod.optin="optional",Un.memoizer?.guard(e),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new oc(e.constructor.name);let r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then((a)=>(n.value=a,n));if(r instanceof Promise)throw new Qi;return n.value=r,n}});function cy(e,t){return e.value=t.issues.length?void 0:t.value,e}var sh=se("$ZodOptional",(e,t)=>{Ut.init(e,t),Et(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Et(e,"values",(n)=>{let i=n.def.innerType._zod.values;return i?new Set([...i,void 0]):void 0}),Et(e,"pattern",(n)=>{let i=n.def.innerType._zod.pattern;return i?new RegExp(`^(${Yr(i.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let r=t.innerType._zod.run({value:n.value,issues:[]},i);if(r instanceof Promise)return r.then((s)=>cy(n,s));return cy(n,r)}return t.innerType._zod.run(n,i)}}),i_=se("$ZodExactOptional",(e,t)=>{sh.init(e,t),Et(e,"values",(n)=>n.def.innerType._zod.values),Et(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),r_=se("$ZodNullable",(e,t)=>{Ut.init(e,t),Et(e,"optin",(n)=>n.def.innerType._zod.optin),Et(e,"optout",(n)=>n.def.innerType._zod.optout),Et(e,"pattern",(n)=>{let i=n.def.innerType._zod.pattern;return i?new RegExp(`^(${Yr(i.source)}|null)$`):void 0}),Et(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>{if(n.value===null)return n;return t.innerType._zod.run(n,i)}}),s_=se("$ZodDefault",(e,t)=>{Ut.init(e,t),e._zod.optin="defaulted",Et(e,"values",(n)=>n.def.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)=>ly(s,t));return ly(r,t)}});function ly(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var a_=se("$ZodPrefault",(e,t)=>{Ut.init(e,t),e._zod.optin="defaulted",Et(e,"values",(n)=>n.def.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)}}),o_=se("$ZodNonOptional",(e,t)=>{Ut.init(e,t),Et(e,"values",(n)=>{let i=n.def.innerType._zod.values;return i?new Set([...i].filter((r)=>r!==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)=>uy(s,e));return uy(r,e)}});function uy(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}function dy(e,t,n,i){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((r)=>Yi(r,i,ei()))},input:e.value}),e}var c_=se("$ZodCatch",(e,t)=>{Ut.init(e,t),Et(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Et(e,"optout",(n)=>n.def.innerType._zod.optout),Et(e,"values",(n)=>n.def.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({value:n.value,issues:[]},i);if(r instanceof Promise)return r.then((s)=>dy(n,s,t,i));return dy(n,r,t,i)}});var l_=se("$ZodPipe",(e,t)=>{Ut.init(e,t),Et(e,"values",(n)=>n.def.in._zod.values),Et(e,"optin",(n)=>n.def.in._zod.optin),Et(e,"optout",(n)=>n.def.out._zod.optout),Et(e,"propValues",(n)=>n.def.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((a)=>eu(a,t.in,i));return eu(s,t.in,i)}let r=t.in._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>eu(s,t.out,i));return eu(r,t.out,i)}});function eu(e,t,n){if(e.issues.some((i)=>i.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var u_=se("$ZodReadonly",(e,t)=>{Ut.init(e,t),Et(e,"propValues",(n)=>n.def.innerType._zod.propValues),Et(e,"values",(n)=>n.def.innerType._zod.values),Et(e,"optin",(n)=>n.def.innerType?._zod?.optin),Et(e,"optout",(n)=>n.def.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(fy);return fy(r)}});function fy(e){if(!e.memo)e.value=Object.freeze(e.value);return e}function HI(e){let t=e._zod.def,n=t.pattern,i=!!t.format?.includes("int"),r,s;for(let o of t.checks??[]){let c=o._zod.def;if(c.pattern)n=c.pattern;i||(i=!!c.format?.includes("int"));let l=c.minimum??c.length,u=c.maximum??c.length;if(l!==void 0&&(r===void 0||l>r))r=l;if(u!==void 0&&(s===void 0||u<s))s=u}if(n)return n.source;if(r!==void 0&&s!==void 0&&r>s)return"(?!)";if(r!==void 0||s!==void 0)return Fx({minimum:r,maximum:s}).source;let a=e._zod.pattern;return(i&&a===Ha?Yl:a)?.source}function eh(e){let t=e._zod.def,n=e._zod.pattern?.source,i=t.innerType??e._zod.innerType;if(i){let r=i._zod.pattern?.source,s=eh(i);if(n&&r&&s&&s!==r)return n.replace(Yr(r),()=>Yr(s));return n}if(t.options){let r=t.options.map(eh);if(r.every(Boolean))return`^(${r.map((s)=>Yr(s)).join("|")})$`}return HI(e)}var d_=se("$ZodTemplateLiteral",(e,t)=>{Ut.init(e,t);let n=[];for(let i of t.parts)if(typeof i==="object"&&i!==null){let r=eh(i);if(!r)throw Error(`Invalid template literal part, no pattern found: ${[...i._zod.traits].shift()}`);n.push(Yr(r))}else if(i===null||jb.has(typeof i))n.push(Rr(`${i}`));else throw Error(`Invalid template literal part: ${i}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(i,r)=>{if(typeof i.value!=="string")return i.issues.push({input:i.value,inst:e,expected:"string",code:"invalid_type"}),i;if(e._zod.pattern.lastIndex=0,!e._zod.pattern.test(i.value))return i.issues.push({input:i.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),i;return i}});var f_=se("$ZodCustom",(e,t)=>{wn.init(e,t),Ut.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)=>hy(s,n,i,e));hy(r,n,i,e);return}});function hy(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(sa(r))}}class p_ extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var oh="~memo",h_=[];function m_(e){return e!==null&&typeof e==="object"}function ah(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var g_=new WeakMap,uc=0,ou=1,dc=2;function cu(e,t,n){let i=g_.get(e);if(i!==void 0)return i?dc:uc;if(t.has(e))return dc;t.add(e);let r=uc,s=(u)=>{if(r!==dc&&u?._zod){let d=cu(u,t,n);if(d>r)r=d}},a=(u,d)=>{let f=uc;for(let h of Reflect.ownKeys(u)){let b=Object.getOwnPropertyDescriptor(u,h);if(d&&!b.enumerable)continue;let m=b.get?ou:b.value?._zod?cu(b.value,t,n):uc;if(m>f)f=m}return f},o=(u)=>{if(u>r)r=u},c=e._zod.def,l=c.type;switch(l){case"object":{let u=ac(c);o(u?a(u,!0):ou),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(let u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(let u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{let u=c._cachedInner??(n?e._zod.innerType:void 0);o(u?cu(u,t,!1):ou);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let d=Object.getOwnPropertyDescriptor(c,u);if(!d||d.get)continue;let f=d.value;if(!f||typeof f!=="object")continue;if(f._zod)s(f);else if(Array.isArray(f))for(let h of f)s(h)}}return t.delete(e),GI(e,r)}function GI(e,t){if(t!==ou)g_.set(e,t===dc);return t}function $I(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var su,au=[],KI={alloc(e,t,n){let i=su;if(!i)return n;su=void 0;let r={value:n,issues:null};return i.set(t.value,r),au.push(r),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,i=(r,s)=>{if(s.direction!=="backward"&&WI(s,r.value))throw new p_;return n(r,s)};if(e._zod.parse=i,e._zod.run===n)e._zod.run=i})},attach(e){var t;let n,i=!1,r,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let a=e._zod.parse,o=(c,l)=>{if(n===void 0){let p=cu(e,new Set,!1);if(p===uc){if(e._zod.parse=a,e._zod.run===o)e._zod.run=a;return a(c,l)}if(p===dc||i)n=!0;else i=!0}let u=c.value;if(!m_(u))return a(c,l);let d=l[oh];if(!d)d={buckets:new WeakMap,backEdges:void 0},l[oh]=d;let f;if(r===l)f=s;else f=$I(d,e),r=l,s=f;let h=f.get(u);if(h){if(c.value=h.value,h.issues){if(h.issues.length)c.issues.push(...ah(h.issues))}else c.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(h.value);return c}su=f;let b=au.length,m=a(c,l);su=void 0;let g=au.length>b?au.pop():void 0;if(m instanceof Promise)return m.then((p)=>{if(g)g.issues=p.issues.length?ah(p.issues):h_;return p});if(g)g.issues=m.issues.length?ah(m.issues):h_;return m};if(e._zod.parse=o,e._zod.run===a)e._zod.run=o})}};function b_(){return KI}function WI(e,t){let n=e[oh]?.backEdges;return n!==void 0&&m_(t)&&n.has(t)}var XI=()=>{let e={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 t(s){return e[s]??null}let n={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",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};function r(s,a){if(s==="number"&&typeof a==="number"&&!Number.isFinite(a))return String(a);return i[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let a=r(s.expected),o=Wb(s.input),c=r(o,s.input);return`Invalid input: expected ${a}, received ${c}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${Bf(s.values[0])}`;return`Invalid option: expected one of ${Lf(s.values,"|")}`;case"too_big":{let a=s.exact?"exactly ":s.inclusive?"<=":"<",o=t(s.origin);if(o)return`Too big: expected ${s.origin??"value"} to have ${a}${s.maximum.toString()} ${o.unit??"elements"}`;return`Too big: expected ${s.origin??"value"} to be ${a}${s.maximum.toString()}`}case"too_small":{let a=s.exact?"exactly ":s.inclusive?">=":">",o=t(s.origin);if(o)return`Too small: expected ${s.origin} to have ${a}${s.minimum.toString()} ${o.unit}`;return`Too small: expected ${s.origin} to be ${a}${s.minimum.toString()}`}case"invalid_format":{let a=s;if(a.format==="starts_with")return`Invalid string: must start with "${a.prefix}"`;if(a.format==="ends_with")return`Invalid string: must end with "${a.suffix}"`;if(a.format==="includes")return`Invalid string: must include "${a.includes}"`;if(a.format==="regex")return`Invalid string: must match pattern ${a.pattern}`;return`Invalid ${n[a.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${Lf(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":if(s.options&&Array.isArray(s.options)&&s.options.length>0)return`Invalid discriminator value. Expected ${s.options.map((o)=>`'${o}'`).join(" | ")}`;if(s.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function ch(){return{localeError:XI()}}var x_;class y_{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 qI(){return new y_}(x_=globalThis).__zod_globalRegistry??(x_.__zod_globalRegistry=qI());var aa=globalThis.__zod_globalRegistry;function __(e){if(e.checks)e.checks=[...e.checks];return e}function v_(e,t){return new e(__({type:"string",...Fe(t)}))}function E_(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Fe(t)})}function T_(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Fe(t)})}function A_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Fe(t)})}function w_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Fe(t)})}function S_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Fe(t)})}function M_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Fe(t)})}function R_(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Fe(t)})}function I_(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Fe(t)})}function C_(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Fe(t)})}function N_(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Fe(t)})}function P_(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Fe(t)})}function O_(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Fe(t)})}function k_(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Fe(t)})}function D_(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Fe(t)})}function L_(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Fe(t)})}function F_(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Fe(t)})}function U_(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Fe(t)})}function B_(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Fe(t)})}function z_(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Fe(t)})}function V_(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Fe(t)})}function j_(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Fe(t)})}function H_(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Fe(t)})}function G_(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Fe(t)})}function $_(e,t){return new e({type:"string",format:"date",check:"string_format",...Fe(t)})}function K_(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Fe(t)})}function W_(e,t){return new e({type:"string",format:"duration",check:"string_format",...Fe(t)})}function X_(e,t){return new e(__({type:"number",checks:[],...Fe(t)}))}function q_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Fe(t)})}function J_(e,t){return new e({type:"boolean",...Fe(t)})}function Z_(e){return new e({type:"unknown"})}function Y_(e,t){return new e({type:"never",...Fe(t)})}function lu(e,t){return new Jf({check:"less_than",...Fe(t),value:e,inclusive:!1})}function fc(e,t){return new Jf({check:"less_than",...Fe(t),value:e,inclusive:!0})}function uu(e,t){return new Zf({check:"greater_than",...Fe(t),value:e,inclusive:!1})}function hc(e,t){return new Zf({check:"greater_than",...Fe(t),value:e,inclusive:!0})}function du(e,t){return new Vx({check:"multiple_of",...Fe(t),value:e})}function fu(e,t){return new Hx({check:"max_length",...Fe(t),maximum:e})}function Ga(e,t){return new Gx({check:"min_length",...Fe(t),minimum:e})}function hu(e,t){return new $x({check:"length_equals",...Fe(t),length:e})}function lh(e,t){return new Kx({check:"string_format",format:"regex",...Fe(t),pattern:e})}function uh(e){return new Wx({check:"string_format",format:"lowercase",...Fe(e)})}function dh(e){return new Xx({check:"string_format",format:"uppercase",...Fe(e)})}function fh(e,t){return new qx({check:"string_format",format:"includes",...Fe(t),includes:e})}function hh(e,t){return new Jx({check:"string_format",format:"starts_with",...Fe(t),prefix:e})}function ph(e,t){return new Zx({check:"string_format",format:"ends_with",...Fe(t),suffix:e})}function Qr(e){return new Yx({check:"overwrite",tx:e})}function mh(e){return Qr((t)=>t.normalize(e))}function gh(){return Qr((e)=>e.trim())}function bh(){return Qr((e)=>e.toLowerCase())}function xh(){return Qr((e)=>e.toUpperCase())}function yh(){return Qr((e)=>Bb(e))}function Q_(e,t,n){return new e({type:"array",element:t,...Fe(n)})}function e0(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Fe(n)})}function t0(e,t){let n=JI((i)=>(i.addIssue=(r)=>{if(typeof r==="string")i.issues.push(sa(r,i.value,n._zod.def));else{let s=r;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=i.value;s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),i.issues.push(sa(s))}},e(i.value,i)),t);return n}function JI(e,t){let n=new wn({check:"custom",...Fe(t)});return n._zod.check=e,n}function pc(e,...t){for(let n of t)for(let i of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,i))mi(e,i,n[i]);return e}function vh(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??aa,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Ir(e,t,n,i,r){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:i.path,message:r}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(r);return Object.assign(n,s),!0}function qt(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 a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let o=e._zod.toJSONSchema?.();if(o)a.schema=o;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,u);else{let f=a.schema,h=t.processors[r.type];if(!h)throw Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);h(e,t,f,u)}let d=e._zod.parent;if(d){if(!a.ref)a.ref=d;qt(d,t,u),t.seen.get(d).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)pc(a.schema,c);if(t.io==="input"&&Bn(e))delete a.schema.examples,delete a.schema.default;if(t.io==="input"&&"_prefault"in a.schema)(i=a.schema).default??(i.default=a.schema._prefault);return delete a.schema._prefault,t.seen.get(e).schema}function n0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Eh(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let i=new Map;for(let a of e.seen.entries()){let o=e.metadataRegistry.get(a[0])?.id;if(o){let c=i.get(o);if(c&&c!==a[0])throw Error(`Duplicate schema id "${o}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(o,a[0])}}let r=(a)=>{let o=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(a[0])?.id,f=e.external.uri??((b)=>b);if(d)return{ref:f(d)};let h=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=h,{defId:h,ref:`${f("__shared")}#/${o}/${n0(h)}`}}let c="#",l=`${c}/${o}/`;if(a[1]===n&&!a[1].schema.id)return{ref:c};let u=a[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+n0(u)}},s=(a)=>{if(a[1].schema.$ref)return;let o=a[1],{ref:c,defId:l}=r(a);if(o.def={...o.schema},l)o.defId=l;let u=o.schema;for(let d in u)delete u[d];u.$ref=c};if(e.cycles==="throw")for(let a of e.seen.entries()){let o=a[1];if(o.cycle)throw Error(`Cycle detected: #/${o.cycle?.join("/")}/<root>+ `)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()},a,o=Ha,c=!Bn.jitless,u=c&&Gb.value,d=t.catchall,f;e._zod.parse=(h,b)=>{f??(f=i.value);let m=h.value;if(!o(m))return h.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),h;if(c&&u&&b?.async===!1&&b.jitless!==!0){if(!a)a=s(t.shape);if(h=a(h,b),!d)return h;return Yy([],m,h,b,f,e,b?.abortEarly===!0)}return n(h,b)}});function oy(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)=>!gi(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((a)=>Yi(a,i,ti())))}),t}var lh=se("$ZodUnion",(e,t)=>{Ut.init(e,t),Et(e,"optin",(i)=>i.def.options.some((r)=>r._zod.optin==="defaulted")?"defaulted":i.def.options.some((r)=>r._zod.optin!==void 0)?"optional":void 0),Et(e,"optout",(i)=>i.def.options.some((r)=>r._zod.optout==="optional")?"optional":void 0),Et(e,"values",(i)=>{if(i.def.options.every((r)=>r._zod.values))return new Set(i.def.options.flatMap((r)=>Array.from(r._zod.values)));return}),Et(e,"pattern",(i)=>{if(i.def.options.every((r)=>r._zod.pattern)){let r=i.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${r.map((s)=>Yr(s.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,a=[];for(let o of t.options){let c=o._zod.run({value:i.value,issues:[]},r);if(c instanceof Promise)a.push(c),s=!0;else{if(c.issues.length===0)return c;a.push(c)}}if(!s)return oy(a,i,e,r);return Promise.all(a).then((o)=>oy(o,i,e,r))}});function WI(e){let t=new Map;for(let n of e.options){let i=n._zod.propValues?.[e.discriminator];if(!i||i.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let r of i)if(t.has(r)){if(r!==void 0)throw Error(`Duplicate discriminator value "${String(r)}"`);t.set(r,null)}else t.set(r,n)}return t}var e_=se("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,lh.init(e,t);let n=e._zod.parse;Et(e,"propValues",(r)=>{let s={},a=0;for(let o of r.def.options){let c=o._zod.propValues;if(!c||Object.keys(c).length===0)throw Error(`Invalid discriminated union option at index "${r.def.options.indexOf(o)}"`);if(c[r.def.discriminator]?.has(void 0))a++;for(let[l,u]of Object.entries(c)){if(!Object.prototype.hasOwnProperty.call(s,l))mi(s,l,new Set);for(let d of u)s[l].add(d)}}if(!r.def.unionFallback&&a>1)s[r.def.discriminator]?.delete(void 0);return s}),t.options.forEach((r,s)=>{let a=oc(r._zod.def);if(a&&!Object.prototype.hasOwnProperty.call(a,t.discriminator))throw Error(`Invalid discriminated union option at index "${s}"`)});let i=ac(()=>WI(t));e._zod.parse=(r,s)=>{let a=r.value;if(!Ha(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;let o=a?.[t.discriminator],c=i.value.get(o);if(c&&(o!==void 0||s.direction!=="backward"))return c._zod.run(r,s);if(t.unionFallback||s.direction==="backward")return n(r,s);return r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(i.value.keys()).filter((l)=>i.value.get(l)!==null),input:a,path:[t.discriminator],inst:e}),r}}),t_=se("$ZodIntersection",(e,t)=>{Ut.init(e,t),e._zod.parse=(n,i)=>{let r=n.value,s=t.left._zod.run({value:r,issues:[]},i),a=t.right._zod.run({value:r,issues:[]},i);if(s instanceof Promise||a instanceof Promise)return Promise.all([s,a]).then(([c,l])=>cy(n,c,l));return cy(n,s,a)}});function rh(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(sa(e)&&sa(t)){let n=Object.keys(t),i=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),r={...e,...t};if(Object.prototype.hasOwnProperty.call(r,"__proto__"))delete r.__proto__;for(let s of i){if(s==="__proto__")continue;let a=rh(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};r[s]=a.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],a=rh(r,s);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function cy(e,t,n){let i=new Map,r,s=new Map,a=(l,u)=>{let d;if(l.code==="unrecognized_keys"&&!l.path?.length)r??(r=l),d=l.keys;else if(l.code==="invalid_key"&&l.origin==="record"&&l.path?.length===1){let f=String(l.path[0]);if(!s.has(f))s.set(f,l);d=[f]}else return!1;for(let f of d){if(!i.has(f))i.set(f,{});i.get(f)[u]=!0}return!0};for(let l of t.issues)if(!a(l,"l"))e.issues.push(l);for(let l of n.issues)if(!a(l,"r"))e.issues.push(l);let o=[...i].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(o.length){let l=r?o.filter((u)=>r.keys.includes(u)):[];if(l.length)e.issues.push({...r,keys:l});for(let u of o)if(!l.includes(u)&&s.has(u))e.issues.push(s.get(u))}let c=rh(t.value,n.value);if(!c.valid){if(gi(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var n_=se("$ZodTuple",(e,t)=>{Ut.init(e,t);let n=t.items,i=Bn.memoizer;i?.attach(e),e._zod.parse=(r,s)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=i?i.alloc(e,r,[],s):[];let o=[],c=ly(n,"optin"),l=ly(n,"optout");if(!t.rest){if(a.length<c)return r.issues.push({code:"too_small",minimum:c,inclusive:!0,input:a,inst:e,origin:"array"}),r;if(a.length>n.length)r.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:a,inst:e,origin:"array"})}let u=Array(n.length),d=t.rest?s?.abortEarly:void 0,f=!1;for(let h=0;h<n.length;h++){let b=n[h]._zod.run({value:a[h],issues:[]},s);if(b instanceof Promise)o.push(b.then((m)=>{u[h]=m}));else if(u[h]=b,d&&!f&&b.issues.length)f=gi(b)}if(t.rest&&!f){let h=n.length-1,b=a.slice(n.length),m=r.issues.length;for(let g of b){if(d&&r.issues.length!==m){if(gi(r,m))break;m=r.issues.length}h++;let p=t.rest._zod.run({value:g,issues:[]},s);if(p instanceof Promise)o.push(p.then((x)=>uy(x,r,h)));else uy(p,r,h)}}if(o.length)return Promise.all(o).then(()=>dy(u,r,n,a,l));return dy(u,r,n,a,l)}});function ly(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function uy(e,t,n){if(e.issues.length)t.issues.push(...Zi(n,e.issues));t.value[n]=e.value}function dy(e,t,n,i,r){for(let s=0;s<n.length;s++){let a=e[s],o=s<i.length;if(!o&&s>=r&&n[s]._zod.optin==="optional"){t.value.length=s;break}if(a.issues.length){if(!o&&s>=r){t.value.length=s;break}t.issues.push(...Zi(s,a.issues))}t.value[s]=a.value}for(let s=t.value.length-1;s>=i.length;s--)if(n[s]._zod.optout==="optional"&&t.value[s]===void 0)t.value.length=s;else break;return t}var i_=se("$ZodRecord",(e,t)=>{Ut.init(e,t);let n=Bn.memoizer;n?.attach(e),e._zod.parse=(i,r)=>{let s=i.value;if(!sa(s))return i.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),i;let a=[],o=t.keyType._zod.values;if(o&&!t.partial){i.value=n?n.alloc(e,i,{},r):{};let c=new Set;for(let u of o)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let d=t.keyType._zod.run({value:u,issues:[]},r);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){i.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((b)=>Yi(b,r,ti())),input:u,path:[u],inst:e});continue}let f=d.value;if(f==="__proto__")continue;let h=t.valueType._zod.run({value:s[u],issues:[]},r);if(h instanceof Promise)a.push(h.then((b)=>{if(b.issues.length)i.issues.push(...Zi(u,b.issues));i.value[f]=b.value}));else{if(h.issues.length)i.issues.push(...Zi(u,h.issues));i.value[f]=h.value}}let l;for(let u in s)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;i.value[u]=s[u]}else l=l??[],l.push(u);if(l&&l.length>0)i.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:l,continue:!0})}else{i.value=n?n.alloc(e,i,{},r):{};let c;for(let l of Reflect.ownKeys(s)){if(l==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,l))continue;let u=t.keyType._zod.run({value:l,issues:[]},r);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof l==="string"&&Ga.test(l)&&u.issues.length){let b=t.keyType._zod.run({value:Number(l),issues:[]},r);if(b instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(b.issues.length===0)u=b}if(u.issues.length){if(t.mode==="loose")i.value[l]=s[l];else if(o)c=c??[],c.push(l);else i.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((b)=>Yi(b,r,ti())),input:l,path:[l],inst:e});continue}let f=u.value;if(f==="__proto__")continue;let h=t.valueType._zod.run({value:s[l],issues:[]},r);if(h instanceof Promise)a.push(h.then((b)=>{if(b.issues.length)i.issues.push(...Zi(l,b.issues));i.value[f]=b.value}));else{if(h.issues.length)i.issues.push(...Zi(l,h.issues));i.value[f]=h.value}}if(c&&c.length>0)i.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}if(a.length)return Promise.all(a).then(()=>i);return i}});var r_=se("$ZodEnum",(e,t)=>{Ut.init(e,t);let n=rc(t.entries),i=new Set(n);e._zod.values=i,Et(e,"pattern",(r)=>{let s=rc(r.def.entries).filter((a)=>$b.has(typeof a));return new RegExp(s.length?`^(${s.map((a)=>Rr(a.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,s)=>{let a=r.value;if(i.has(a))return r;return r.issues.push({code:"invalid_value",values:n,input:a,inst:e}),r}}),s_=se("$ZodLiteral",(e,t)=>{Ut.init(e,t);let n=new Set(t.values);e._zod.values=n,Et(e,"pattern",(i)=>{let r=i.def.values;return new RegExp(r.length?`^(${r.map((s)=>typeof s==="string"?Rr(s):s?Rr(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),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 a_=se("$ZodTransform",(e,t)=>{Ut.init(e,t),e._zod.optin="optional",Bn.memoizer?.guard(e),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new cc(e.constructor.name);let r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then((a)=>(n.value=a,n));if(r instanceof Promise)throw new Qi;return n.value=r,n}});function fy(e,t){return e.value=t.issues.length?void 0:t.value,e}var uh=se("$ZodOptional",(e,t)=>{Ut.init(e,t),Et(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Et(e,"values",(n)=>{let i=n.def.innerType._zod.values;return i?new Set([...i,void 0]):void 0}),Et(e,"pattern",(n)=>{let i=n.def.innerType._zod.pattern;return i?new RegExp(`^(${Yr(i.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let r=t.innerType._zod.run({value:n.value,issues:[]},i);if(r instanceof Promise)return r.then((s)=>fy(n,s));return fy(n,r)}return t.innerType._zod.run(n,i)}}),o_=se("$ZodExactOptional",(e,t)=>{uh.init(e,t),Et(e,"values",(n)=>n.def.innerType._zod.values),Et(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),c_=se("$ZodNullable",(e,t)=>{Ut.init(e,t),Et(e,"optin",(n)=>n.def.innerType._zod.optin),Et(e,"optout",(n)=>n.def.innerType._zod.optout),Et(e,"pattern",(n)=>{let i=n.def.innerType._zod.pattern;return i?new RegExp(`^(${Yr(i.source)}|null)$`):void 0}),Et(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>{if(n.value===null)return n;return t.innerType._zod.run(n,i)}}),l_=se("$ZodDefault",(e,t)=>{Ut.init(e,t),e._zod.optin="defaulted",Et(e,"values",(n)=>n.def.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)=>hy(s,t));return hy(r,t)}});function hy(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var u_=se("$ZodPrefault",(e,t)=>{Ut.init(e,t),e._zod.optin="defaulted",Et(e,"values",(n)=>n.def.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)}}),d_=se("$ZodNonOptional",(e,t)=>{Ut.init(e,t),Et(e,"values",(n)=>{let i=n.def.innerType._zod.values;return i?new Set([...i].filter((r)=>r!==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)=>py(s,e));return py(r,e)}});function py(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}function my(e,t,n,i){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((r)=>Yi(r,i,ti()))},input:e.value}),e}var f_=se("$ZodCatch",(e,t)=>{Ut.init(e,t),Et(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Et(e,"optout",(n)=>n.def.innerType._zod.optout),Et(e,"values",(n)=>n.def.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({value:n.value,issues:[]},i);if(r instanceof Promise)return r.then((s)=>my(n,s,t,i));return my(n,r,t,i)}});var h_=se("$ZodPipe",(e,t)=>{Ut.init(e,t),Et(e,"values",(n)=>n.def.in._zod.values),Et(e,"optin",(n)=>n.def.in._zod.optin),Et(e,"optout",(n)=>n.def.out._zod.optout),Et(e,"propValues",(n)=>n.def.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((a)=>ru(a,t.in,i));return ru(s,t.in,i)}let r=t.in._zod.run(n,i);if(r instanceof Promise)return r.then((s)=>ru(s,t.out,i));return ru(r,t.out,i)}});function ru(e,t,n){if(e.issues.some((i)=>i.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var p_=se("$ZodReadonly",(e,t)=>{Ut.init(e,t),Et(e,"propValues",(n)=>n.def.innerType._zod.propValues),Et(e,"values",(n)=>n.def.innerType._zod.values),Et(e,"optin",(n)=>n.def.innerType?._zod?.optin),Et(e,"optout",(n)=>n.def.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(gy);return gy(r)}});function gy(e){if(!e.memo)e.value=Object.freeze(e.value);return e}function XI(e){let t=e._zod.def,n=t.pattern,i=!!t.format?.includes("int"),r,s;for(let o of t.checks??[]){let c=o._zod.def;if(c.pattern)n=c.pattern;i||(i=!!c.format?.includes("int"));let l=c.minimum??c.length,u=c.maximum??c.length;if(l!==void 0&&(r===void 0||l>r))r=l;if(u!==void 0&&(s===void 0||u<s))s=u}if(n)return n.source;if(r!==void 0&&s!==void 0&&r>s)return"(?!)";if(r!==void 0||s!==void 0)return Vx({minimum:r,maximum:s}).source;let a=e._zod.pattern;return(i&&a===Ga?nu:a)?.source}function sh(e){let t=e._zod.def,n=e._zod.pattern?.source,i=t.innerType??e._zod.innerType;if(i){let r=i._zod.pattern?.source,s=sh(i);if(n&&r&&s&&s!==r)return n.replace(Yr(r),()=>Yr(s));return n}if(t.options){let r=t.options.map(sh);if(r.every(Boolean))return`^(${r.map((s)=>Yr(s)).join("|")})$`}return XI(e)}var m_=se("$ZodTemplateLiteral",(e,t)=>{Ut.init(e,t);let n=[];for(let i of t.parts)if(typeof i==="object"&&i!==null){let r=sh(i);if(!r)throw Error(`Invalid template literal part, no pattern found: ${[...i._zod.traits].shift()}`);n.push(Yr(r))}else if(i===null||Kb.has(typeof i))n.push(Rr(`${i}`));else throw Error(`Invalid template literal part: ${i}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(i,r)=>{if(typeof i.value!=="string")return i.issues.push({input:i.value,inst:e,expected:"string",code:"invalid_type"}),i;if(e._zod.pattern.lastIndex=0,!e._zod.pattern.test(i.value))return i.issues.push({input:i.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),i;return i}});var g_=se("$ZodCustom",(e,t)=>{Sn.init(e,t),Ut.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)=>by(s,n,i,e));by(r,n,i,e);return}});function by(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(aa(r))}}class x_ extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var fh="~memo",b_=[];function y_(e){return e!==null&&typeof e==="object"}function dh(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var __=new WeakMap,dc=0,du=1,fc=2;function fu(e,t,n){let i=__.get(e);if(i!==void 0)return i?fc:dc;if(t.has(e))return fc;t.add(e);let r=dc,s=(u)=>{if(r!==fc&&u?._zod){let d=fu(u,t,n);if(d>r)r=d}},a=(u,d)=>{let f=dc;for(let h of Reflect.ownKeys(u)){let b=Object.getOwnPropertyDescriptor(u,h);if(d&&!b.enumerable)continue;let m=b.get?du:b.value?._zod?fu(b.value,t,n):dc;if(m>f)f=m}return f},o=(u)=>{if(u>r)r=u},c=e._zod.def,l=c.type;switch(l){case"object":{let u=oc(c);o(u?a(u,!0):du),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(let u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(let u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{let u=c._cachedInner??(n?e._zod.innerType:void 0);o(u?fu(u,t,!1):du);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let d=Object.getOwnPropertyDescriptor(c,u);if(!d||d.get)continue;let f=d.value;if(!f||typeof f!=="object")continue;if(f._zod)s(f);else if(Array.isArray(f))for(let h of f)s(h)}}return t.delete(e),qI(e,r)}function qI(e,t){if(t!==du)__.set(e,t===fc);return t}function JI(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var lu,uu=[],ZI={alloc(e,t,n){let i=lu;if(!i)return n;lu=void 0;let r={value:n,issues:null};return i.set(t.value,r),uu.push(r),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,i=(r,s)=>{if(s.direction!=="backward"&&YI(s,r.value))throw new x_;return n(r,s)};if(e._zod.parse=i,e._zod.run===n)e._zod.run=i})},attach(e){var t;let n,i=!1,r,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let a=e._zod.parse,o=(c,l)=>{if(n===void 0){let p=fu(e,new Set,!1);if(p===dc){if(e._zod.parse=a,e._zod.run===o)e._zod.run=a;return a(c,l)}if(p===fc||i)n=!0;else i=!0}let u=c.value;if(!y_(u))return a(c,l);let d=l[fh];if(!d)d={buckets:new WeakMap,backEdges:void 0},l[fh]=d;let f;if(r===l)f=s;else f=JI(d,e),r=l,s=f;let h=f.get(u);if(h){if(c.value=h.value,h.issues){if(h.issues.length)c.issues.push(...dh(h.issues))}else c.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(h.value);return c}lu=f;let b=uu.length,m=a(c,l);lu=void 0;let g=uu.length>b?uu.pop():void 0;if(m instanceof Promise)return m.then((p)=>{if(g)g.issues=p.issues.length?dh(p.issues):b_;return p});if(g)g.issues=m.issues.length?dh(m.issues):b_;return m};if(e._zod.parse=o,e._zod.run===a)e._zod.run=o})}};function v_(){return ZI}function YI(e,t){let n=e[fh]?.backEdges;return n!==void 0&&y_(t)&&n.has(t)}var QI=()=>{let e={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 t(s){return e[s]??null}let n={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",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};function r(s,a){if(s==="number"&&typeof a==="number"&&!Number.isFinite(a))return String(a);return i[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let a=r(s.expected),o=Zb(s.input),c=r(o,s.input);return`Invalid input: expected ${a}, received ${c}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${Gf(s.values[0])}`;return`Invalid option: expected one of ${Vf(s.values,"|")}`;case"too_big":{let a=s.exact?"exactly ":s.inclusive?"<=":"<",o=t(s.origin);if(o)return`Too big: expected ${s.origin??"value"} to have ${a}${s.maximum.toString()} ${o.unit??"elements"}`;return`Too big: expected ${s.origin??"value"} to be ${a}${s.maximum.toString()}`}case"too_small":{let a=s.exact?"exactly ":s.inclusive?">=":">",o=t(s.origin);if(o)return`Too small: expected ${s.origin} to have ${a}${s.minimum.toString()} ${o.unit}`;return`Too small: expected ${s.origin} to be ${a}${s.minimum.toString()}`}case"invalid_format":{let a=s;if(a.format==="starts_with")return`Invalid string: must start with "${a.prefix}"`;if(a.format==="ends_with")return`Invalid string: must end with "${a.suffix}"`;if(a.format==="includes")return`Invalid string: must include "${a.includes}"`;if(a.format==="regex")return`Invalid string: must match pattern ${a.pattern}`;return`Invalid ${n[a.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${Vf(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":if(s.options&&Array.isArray(s.options)&&s.options.length>0)return`Invalid discriminator value. Expected ${s.options.map((o)=>`'${o}'`).join(" | ")}`;if(s.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function hh(){return{localeError:QI()}}var E_;class T_{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 e1(){return new T_}(E_=globalThis).__zod_globalRegistry??(E_.__zod_globalRegistry=e1());var oa=globalThis.__zod_globalRegistry;function A_(e){if(e.checks)e.checks=[...e.checks];return e}function w_(e,t){return new e(A_({type:"string",...Ue(t)}))}function S_(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Ue(t)})}function M_(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Ue(t)})}function R_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Ue(t)})}function I_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ue(t)})}function C_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ue(t)})}function N_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ue(t)})}function P_(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Ue(t)})}function O_(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Ue(t)})}function k_(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ue(t)})}function D_(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Ue(t)})}function L_(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ue(t)})}function F_(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Ue(t)})}function U_(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Ue(t)})}function B_(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ue(t)})}function z_(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ue(t)})}function V_(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ue(t)})}function j_(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ue(t)})}function H_(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ue(t)})}function G_(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Ue(t)})}function $_(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Ue(t)})}function K_(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Ue(t)})}function W_(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Ue(t)})}function X_(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ue(t)})}function q_(e,t){return new e({type:"string",format:"date",check:"string_format",...Ue(t)})}function J_(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Ue(t)})}function Z_(e,t){return new e({type:"string",format:"duration",check:"string_format",...Ue(t)})}function Y_(e,t){return new e(A_({type:"number",checks:[],...Ue(t)}))}function Q_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ue(t)})}function ev(e,t){return new e({type:"boolean",...Ue(t)})}function tv(e){return new e({type:"unknown"})}function nv(e,t){return new e({type:"never",...Ue(t)})}function hu(e,t){return new th({check:"less_than",...Ue(t),value:e,inclusive:!1})}function hc(e,t){return new th({check:"less_than",...Ue(t),value:e,inclusive:!0})}function pu(e,t){return new nh({check:"greater_than",...Ue(t),value:e,inclusive:!1})}function pc(e,t){return new nh({check:"greater_than",...Ue(t),value:e,inclusive:!0})}function mu(e,t){return new $x({check:"multiple_of",...Ue(t),value:e})}function gu(e,t){return new Wx({check:"max_length",...Ue(t),maximum:e})}function $a(e,t){return new Xx({check:"min_length",...Ue(t),minimum:e})}function bu(e,t){return new qx({check:"length_equals",...Ue(t),length:e})}function ph(e,t){return new Jx({check:"string_format",format:"regex",...Ue(t),pattern:e})}function mh(e){return new Zx({check:"string_format",format:"lowercase",...Ue(e)})}function gh(e){return new Yx({check:"string_format",format:"uppercase",...Ue(e)})}function bh(e,t){return new Qx({check:"string_format",format:"includes",...Ue(t),includes:e})}function xh(e,t){return new ey({check:"string_format",format:"starts_with",...Ue(t),prefix:e})}function yh(e,t){return new ty({check:"string_format",format:"ends_with",...Ue(t),suffix:e})}function Qr(e){return new ny({check:"overwrite",tx:e})}function _h(e){return Qr((t)=>t.normalize(e))}function vh(){return Qr((e)=>e.trim())}function Eh(){return Qr((e)=>e.toLowerCase())}function Th(){return Qr((e)=>e.toUpperCase())}function Ah(){return Qr((e)=>Hb(e))}function iv(e,t,n){return new e({type:"array",element:t,...Ue(n)})}function rv(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Ue(n)})}function sv(e,t){let n=t1((i)=>(i.addIssue=(r)=>{if(typeof r==="string")i.issues.push(aa(r,i.value,n._zod.def));else{let s=r;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=i.value;s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),i.issues.push(aa(s))}},e(i.value,i)),t);return n}function t1(e,t){let n=new Sn({check:"custom",...Ue(t)});return n._zod.check=e,n}function mc(e,...t){for(let n of t)for(let i of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,i))mi(e,i,n[i]);return e}function Sh(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??oa,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Ir(e,t,n,i,r){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:i.path,message:r}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(r);return Object.assign(n,s),!0}function qt(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 a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let o=e._zod.toJSONSchema?.();if(o)a.schema=o;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,u);else{let f=a.schema,h=t.processors[r.type];if(!h)throw Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);h(e,t,f,u)}let d=e._zod.parent;if(d){if(!a.ref)a.ref=d;qt(d,t,u),t.seen.get(d).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)mc(a.schema,c);if(t.io==="input"&&zn(e))delete a.schema.examples,delete a.schema.default;if(t.io==="input"&&"_prefault"in a.schema)(i=a.schema).default??(i.default=a.schema._prefault);return delete a.schema._prefault,t.seen.get(e).schema}function av(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Mh(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let i=new Map;for(let a of e.seen.entries()){let o=e.metadataRegistry.get(a[0])?.id;if(o){let c=i.get(o);if(c&&c!==a[0])throw Error(`Duplicate schema id "${o}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(o,a[0])}}let r=(a)=>{let o=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(a[0])?.id,f=e.external.uri??((b)=>b);if(d)return{ref:f(d)};let h=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=h,{defId:h,ref:`${f("__shared")}#/${o}/${av(h)}`}}let c="#",l=`${c}/${o}/`;if(a[1]===n&&!a[1].schema.id)return{ref:c};let u=a[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+av(u)}},s=(a)=>{if(a[1].schema.$ref)return;let o=a[1],{ref:c,defId:l}=r(a);if(o.def={...o.schema},l)o.defId=l;let u=o.schema;for(let d in u)delete u[d];u.$ref=c};if(e.cycles==="throw")for(let a of e.seen.entries()){let o=a[1];if(o.cycle)throw Error(`Cycle detected: #/${o.cycle?.join("/")}/<root>-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let o=a[1];if(t===a[0]){s(a);continue}if(e.external){let l=e.external.registry.get(a[0])?.id;if(t!==a[0]&&l){s(a);continue}}if(e.metadataRegistry.get(a[0])?.id){s(a);continue}if(o.cycle){s(a);continue}if(o.count>1){if(e.reused==="ref")s(a)}}if(e.external)e.sharedDefsExtractedFor=e.external}function s0(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let i of t){if(!i||typeof i!=="object")return;s0(i);let r=Object.keys(i);if(r.length!==1||r[0]!=="type")return;let s=i.type;for(let a of Array.isArray(s)?s:[s]){if(typeof a!=="string")return;if(!n.includes(a))n.push(a)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var a0=new Set(["type","properties","required","additionalProperties"]),i0=["oneOf","anyOf"];function r0(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function _h(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let a in s)if(!a0.has(a))return null;t.push(s)}let n={},i=new Set;for(let s of t){for(let a in s.properties){if(Object.prototype.hasOwnProperty.call(n,a))continue;let o=[];for(let l of t){let u=l.properties?.[a]??r0(l);if(u===null||u===void 0)continue;if(!o.some((d)=>JSON.stringify(d)===JSON.stringify(u)))o.push(u)}let c=o.length===1?o[0]:_h(o)??{allOf:o};mi(n,a,c)}for(let a of s.required??[])i.add(a)}let r={type:"object",properties:n};if(i.size)r.required=[...i];if(t.every((s)=>s.additionalProperties===!1))r.additionalProperties=!1;else{let s=[];for(let a of t){let o=r0(a);if(o&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(o)))s.push(o)}if(s.length===1)r.additionalProperties=s[0];else if(s.length>1)r.additionalProperties={allOf:s}}return r}function ZI(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let r of a0)if(r in e)return;let n=t.filter((r)=>i0.some((s)=>Array.isArray(r[s]))),i=null;if(!n.length)i=_h(t);else{let r=n[0],s=i0.find((c)=>Array.isArray(r[c]));if(Object.keys(r).length!==1)return;let a=t.filter((c)=>c!==r),o=r[s].map((c)=>_h([...a,c]));if(o.some((c)=>!c))return;i={[s]:o}}if(!i)return;delete e.allOf,pc(e,i)}function Th(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=(o)=>{let c=e.seen.get(o);if(c.ref===null)return;let l=c.def??c.schema,u={...l},d=c.ref;if(c.ref=null,d){i(d);let h=e.seen.get(d),b=h.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(b);else pc(l,b);if(pc(l,u),o._zod.parent===d)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(!(g in u))delete l[g]}if(b.$ref&&h.def)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(g in h.def&&JSON.stringify(l[g])===JSON.stringify(h.def[g]))delete l[g]}}let f=o._zod.parent;if(f&&f!==d){i(f);let h=e.seen.get(f);if(h?.schema.$ref){if(l.$ref=h.schema.$ref,h.def)for(let b in l){if(b==="$ref"||b==="allOf")continue;if(b in h.def&&JSON.stringify(l[b])===JSON.stringify(h.def[b]))delete l[b]}}}e.override({zodSchema:o,jsonSchema:l,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let o of[...e.seen.entries()].reverse())i(o[0]);if(e.target!=="openapi-3.0")for(let o of e.seen.entries())s0(o[1].def??o[1].schema);for(let o of e.deferred)o();if(e.intersections.length){let o=new Map;for(let c of e.seen.values())for(let l of[c.schema,c.def]){let u=l?.allOf;if(!Array.isArray(u))continue;let d=o.get(u);if(d)d.push(l);else o.set(u,[l])}for(let c of e.intersections)for(let l of o.get(c)??[])ZI(l)}}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 o=e.external.registry.get(t)?.id;if(!o)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(o)}pc(r,n.defId?n.schema:n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&r.id===s)delete r.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let o of e.seen.entries()){let c=o[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;mi(a,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(a).length>0)if(e.target==="draft-2020-12")r.$defs=a;else r.definitions=a;try{let o=JSON.parse(JSON.stringify(r));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:mc(t,"input",e.processors),output:mc(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch(o){throw Error("Error converting schema to JSON.")}}function Bn(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 Bn(i.element,n);if(i.type==="set")return Bn(i.valueType,n);if(i.type==="lazy")return Bn(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"||i.type==="catch")return Bn(i.innerType,n);if(i.type==="intersection")return Bn(i.left,n)||Bn(i.right,n);if(i.type==="record"||i.type==="map")return Bn(i.keyType,n)||Bn(i.valueType,n);if(i.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Bn(i.in,n)||Bn(i.out,n)}if(i.type==="object"){for(let r in i.shape)if(Bn(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(let r of i.options)if(Bn(r,n))return!0;return!1}if(i.type==="tuple"){for(let r of i.items)if(Bn(r,n))return!0;if(i.rest&&Bn(i.rest,n))return!0;return!1}return!1}var o0=(e,t={})=>(n)=>{let i=vh({...n,processors:t});return qt(e,i),Eh(i,e),Th(i,e)},mc=(e,t,n={})=>(i)=>{let{libraryOptions:r,target:s}=i??{},a=vh({...r??{},target:s,io:t,processors:n});return qt(e,a),Eh(a,e),Th(a,e)};var $a=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},Ka=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},c0=(e,t)=>{$a(e,"minimum",t),Ka(e,"maximum",t)},f0=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},h0=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},p0=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},m0=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},l0=(e,t)=>$a(e,"minimum",t.minimum),u0=(e,t)=>Ka(e,"maximum",t.maximum),d0=(e)=>(t,n)=>{m0(t,n.format);let[i,r]=e[n.format];$a(t,"minimum",i),Ka(t,"maximum",r)},YI={greater_than:(e,t)=>$a(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Ka(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>f0(e,t.value),number_format:d0(jl),bigint_format:d0(zf),min_length:l0,max_length:u0,length_equals:(e,t)=>c0(e,t.length),min_size:l0,max_size:u0,size_equals:(e,t)=>c0(e,t.size),string_format:(e,t)=>{if(m0(e,t.format),t.pattern)h0(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>p0(e,t.mime)};function ti(e){let t={},n=e._zod.def,i=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let s of i)YI[s._zod.def.check]?.(t,s._zod.def);let r=e._zod.bag;if(r.minimum!==void 0)$a(t,"minimum",r.minimum);if(r.exclusiveMinimum!==void 0)$a(t,"exclusiveMinimum",r.exclusiveMinimum);if(r.maximum!==void 0)Ka(t,"maximum",r.maximum);if(r.exclusiveMaximum!==void 0)Ka(t,"exclusiveMaximum",r.exclusiveMaximum);if(r.multipleOf!==void 0)f0(t,r.multipleOf);if(r.format!==void 0){if(t.format??(t.format=r.format),r.format.includes("int"))t.isInt=!0}if(r.mime)p0(t,r.mime);for(let s of r.patterns??[])h0(t,s);return t}var QI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},e1=new Map([[nh,Rx],[ru,Ix]]),g0=(e)=>e1.get(e)??e,b0=(e,t,n,i)=>{let r=n;r.type="string";let{minimum:s,maximum:a,format:o,patterns:c,contentEncoding:l,laxFormat:u}=ti(e);if(typeof s==="number")r.minLength=s;if(typeof a==="number")r.maxLength=a;if(o){if(r.format=QI[o]??o,r.format==="")delete r.format;if(o==="time"||u)delete r.format}if(l)r.contentEncoding=l;if(c&&c.size>0){let d=[...c].map(g0);if(d.length===1)r.pattern=d[0].source;else if(d.length>1)r.allOf=[...d.map((f)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}},x0=(e,t,n,i)=>{let r=n,{minimum:s,maximum:a,multipleOf:o,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=ti(e);r.type=u?"integer":"number";let d=typeof l==="number"&&l>=(s??Number.NEGATIVE_INFINITY),f=typeof c==="number"&&c<=(a??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(d)if(h)r.minimum=l,r.exclusiveMinimum=!0;else r.exclusiveMinimum=l;else if(typeof s==="number")r.minimum=s;if(f)if(h)r.maximum=c,r.exclusiveMaximum=!0;else r.exclusiveMaximum=c;else if(typeof a==="number")r.maximum=a;if(o){let b=new Set;for(let p of o)if(Number.isFinite(p)&&p!==0)b.add(Math.abs(p));else Ir(e,t,r,i,`A multipleOf divisor of ${p} cannot be represented in JSON Schema`);let[m,...g]=b;if(m!==void 0)r.multipleOf=m;if(g.length)r.allOf=[...r.allOf??[],...g.map((p)=>({multipleOf:p}))]}},y0=(e,t,n,i)=>{n.type="boolean"};var _0=(e,t,n,i)=>{n.not={}};var v0=(e,t,n,i)=>{};var E0=(e,t,n,i)=>{let r=e._zod.def,s=ic(r.entries);if(s.length===0){n.not={};return}if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";n.enum=s},T0=(e,t,n,i)=>{let r=e._zod.def;if(r.values.length===0){n.not={};return}let s=[];for(let a of r.values)if(a===void 0){if(Ir(e,t,n,i,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a==="bigint"){if(Ir(e,t,n,i,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(a))}else s.push(a);if(s.length===0);else if(s.length===1){let a=s[0];if(n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[a];else n.const=a}else{if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";if(s.every((a)=>typeof a==="boolean"))n.type="boolean";if(s.every((a)=>a===null))n.type="null";n.enum=s}};var A0=(e,t,n,i)=>{let r=n,s=e._zod.pattern;if(!s)throw Error("Pattern not found in template literal");r.type="string",r.pattern=s.source};var w0=(e,t,n,i)=>{Ir(e,t,n,i,"Custom types cannot be represented in JSON Schema")};var S0=(e,t,n,i)=>{Ir(e,t,n,i,"Transforms cannot be represented in JSON Schema")};var M0=(e,t,n,i)=>{let r=n,s=e._zod.def,{minimum:a,maximum:o}=ti(e);if(typeof a==="number")r.minItems=a;if(typeof o==="number")r.maxItems=o;r.type="array",r.items=qt(s.element,t,{...i,path:[...i.path,"items"]})};function gc(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return gc(t.out);if(t.type==="catch")return gc(t.innerType);return e._zod.optin}var R0=(e,t,n,i)=>{let r=n,s=e._zod.def,a=s.shape;if(Object.getOwnPropertySymbols(a).length&&Ir(e,t,r,i,"Symbol keys cannot be represented in JSON Schema"))return;r.type="object",r.properties={};for(let l in a)mi(r.properties,l,qt(a[l],t,{...i,path:[...i.path,"properties",l]}));let c=[];for(let l of Object.keys(a)){let u=s.shape[l];if(t.io==="input"?gc(u)===void 0:u._zod.optout===void 0)c.push(l)}if(c.length>0)r.required=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=qt(s.catchall,t,{...i,path:[...i.path,"additionalProperties"]})},I0=(e,t,n,i)=>{let r=e._zod.def,s=r.inclusive===!1,a=r.options.map((o,c)=>qt(o,t,{...i,path:[...i.path,s?"oneOf":"anyOf",c]}));if(s)n.oneOf=a;else n.anyOf=a},C0=(e,t,n,i)=>{let r=e._zod.def,s=qt(r.left,t,{...i,path:[...i.path,"allOf",0]}),a=qt(r.right,t,{...i,path:[...i.path,"allOf",1]}),o=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...o(s)?s.allOf:[s],...o(a)?a.allOf:[a]];n.allOf=c,t.intersections.push(c)},N0=(e,t,n,i)=>{let r=n,s=e._zod.def;r.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",o=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((m,g)=>qt(m,t,{...i,path:[...i.path,a,g]})),l=s.rest?qt(s.rest,t,{...i,path:[...i.path,o,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null,u=s.items.length;while(u>0){let m=s.items[u-1];if(!(t.io==="input"?gc(m)!==void 0:m._zod.optout==="optional"))break;u--}let d=s.items.length,f=!s.rest;if(t.target==="draft-2020-12"){if(r.prefixItems=c,f)r.items=!1;else if(l)r.items=l;if(u>0)r.minItems=u;if(f)r.maxItems=d}else if(t.target==="openapi-3.0"){if(r.items={anyOf:c},l)r.items.anyOf.push(l);if(u>0)r.minItems=u;if(f)r.maxItems=d}else{if(r.items=c,f)r.additionalItems=!1;else if(l)r.additionalItems=l;if(u>0)r.minItems=u;if(f)r.maxItems=d}let{minimum:h,maximum:b}=ti(e);if(typeof h==="number")r.minItems=h;if(typeof b==="number")r.maxItems=b};function Ah(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let b=e.get(t)?.def;if(!b)return t;let m=Ah(e,b,n);return m===b?t:m}for(let b of["anyOf","oneOf"]){let m=t[b];if(!Array.isArray(m))continue;let g=m.map((p)=>Ah(e,p,n));if(g.some((p,x)=>p!==m[x]))t={...t,[b]:g}}let i=Array.isArray(t.type)?t.type:[t.type],r=!i.includes("string")&&i.some((b)=>b==="number"||b==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!r&&!s?.some((b)=>typeof b==="number"))return t;let{minimum:a,maximum:o,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...h}=t;if(h.enum)h.enum=h.enum.map((b)=>typeof b==="number"?String(b):b);else if(typeof h.const==="number")h.const=String(h.const);if(!r)return h;if(h.type="string",!s)h.pattern=(i.includes("number")?Ha:Yl).source;return h}var wh=new WeakMap;function t1(e){let t=new Map;for(let i of e.seen.values())if(i.def&&!t.has(i.schema))t.set(i.schema,i);let n=new Map;for(let i of wh.get(e)??[]){let r=e.seen.get(i),s=(r?.def??r?.schema)?.propertyNames;if(!s||s===!0||n.has(s))continue;let a=Ah(t,s,new Set);if(a!==s)n.set(s,a)}if(!n.size)return;for(let i of e.seen.values())for(let r of[i.schema,i.def]){let s=r&&n.get(r.propertyNames);if(s)r.propertyNames=s}}var P0=(e,t,n,i)=>{let r=n,s=e._zod.def;r.type="object";let a=s.keyType,o=ti(a).patterns;if(s.mode==="loose"&&o&&o.size>0){let u=qt(s.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(let d of o)mi(r.patternProperties,g0(d).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){r.propertyNames=qt(s.keyType,t,{...i,path:[...i.path,"propertyNames"]});let u=wh.get(t);if(!u)u=[],wh.set(t,u),t.deferred.push(()=>t1(t));u.push(e)}r.additionalProperties=qt(s.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let c=a._zod.values,l=t.io==="input"&&gc(s.valueType)!==void 0;if(c&&!s.partial&&!l){let u=[...c].filter((d)=>typeof d==="string"||typeof d==="number");if(u.length>0)r.required=u.map(String)}},O0=(e,t,n,i)=>{let r=e._zod.def,s=qt(r.innerType,t,i),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=r.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},k0=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType},Sh=Symbol();function D0(e,t,n,i,r){let s=!1,a=JSON.stringify(e,(o,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(a);return Ir(t,n,i,r,"BigInt defaults cannot be represented in JSON Schema"),Sh}var L0=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType;let a=D0(r.defaultValue,e,t,n,i);if(a!==Sh)n.default=a},F0=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);if(s.ref=r.innerType,t.io!=="input")return;let a=D0(r.defaultValue,e,t,n,i);if(a!==Sh)n._prefault=a},U0=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType;let a;try{a=r.catchValue(void 0)}catch{Ir(e,t,n,i,"Dynamic catch values are not supported in JSON Schema");return}n.default=a},B0=(e,t,n,i)=>{let r=e._zod.def,s=r.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?s?r.out:r.in:r.out;qt(a,t,i);let o=t.seen.get(e);o.ref=a},z0=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0};var Mh=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType};var V0=new WeakSet([Object.prototype,Error.prototype]);function pu(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let i=n(this);return Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0}),i},set(i){Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0})}})}var l1=(e,t)=>{tx.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(V0.has(n))return;V0.add(n),pu(n,"format",(i)=>(r)=>ix(i,r)),pu(n,"flatten",(i)=>(r)=>nx(i,r)),pu(n,"addIssue",(i)=>(r)=>{i.issues.push(r),i.message=JSON.stringify(i.issues,rc,2)}),pu(n,"addIssues",(i)=>(r)=>{i.issues.push(...r),i.message=JSON.stringify(i.issues,rc,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var ni=se("ZodError",l1,void 0,{Parent:Error});var j0=Xl(ni),H0=ql(ni),G0=Jl(ni),$0=Zl(ni),K0=sx(ni),W0=ax(ni),X0=ox(ni),q0=cx(ni),J0=lx(ni),Z0=ux(ni),Y0=dx(ni),Q0=fx(ni);function d1(){if(!Un.localeError)ei(ch())}function bc(){if(!Un.memoizer)ei({memoizer:b_()})}var Kt=se("ZodType",(e,t)=>(d1(),Ut.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Qn(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ji(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(uC(e,t))},superRefine(e,t){return this.check(dC(e,t))},overwrite(e){return this.check(Qr(e))},optional(){return nv(this)},exactOptional(){return q1(this)},nullable(){return iv(this)},nullish(){return nv(iv(this))},nonoptional(e){return tC(this,e)},array(){return at(this)},or(e){return Wa([this,e])},and(e){return G1(this,e)},transform(e){return rv(this,X1(e))},default(e){return Y1(this,e)},prefault(e){return eC(this,e)},catch(e){return iC(this,e)},pipe(e){return rv(this,e)},readonly(){return aC(this)},describe(e){let t=this.clone();return aa.add(t,{description:e}),t},meta(...e){if(e.length===0)return aa.get(this);let t=this.clone();return aa.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return Kl(this,"~standard",{...th(this),jsonSchema:{input:mc(this,"input"),output:mc(this,"output")}})},set "~standard"(e){Mr(this,"~standard",e)},parse:function e(t,n){return j0(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await H0(this,t,n,{callee:e})},safeParse(e,t){return G0(this,e,t)},async safeParseAsync(e,t){return $0(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Mr(this,"spa",e)},validate(e,t){return $f(this,e,t)},validateAsync(e,t){return Kf(this,e,t)},encode:function e(t,n){return K0(this,t,n,{callee:e})},decode:function e(t,n){return W0(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await X0(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await q0(this,t,n,{callee:e})},safeEncode(e,t){return J0(this,e,t)},safeDecode(e,t){return Z0(this,e,t)},async safeEncodeAsync(e,t){return Y0(this,e,t)},async safeDecodeAsync(e,t){return Q0(this,e,t)},toJSONSchema(e){return o0(this,{})(e)},get description(){return aa.get(this)?.description},get _def(){return this._zod.def}}),sv=se("_ZodString",(e,t)=>{iu.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>b0(e,n,i,r)},qb({format:(e)=>ti(e).format??null,minLength:(e)=>ti(e).minimum??null,maxLength:(e)=>ti(e).maximum??null},{regex(...e){return this.check(lh(...e))},includes(...e){return this.check(fh(...e))},startsWith(...e){return this.check(hh(...e))},endsWith(...e){return this.check(ph(...e))},min(...e){return this.check(Ga(...e))},max(...e){return this.check(fu(...e))},length(...e){return this.check(hu(...e))},nonempty(...e){return this.check(Ga(1,...e))},lowercase(e){return this.check(uh(e))},uppercase(e){return this.check(dh(e))},trim(){return this.check(gh())},normalize(...e){return this.check(mh(...e))},toLowerCase(){return this.check(bh())},toUpperCase(){return this.check(xh())},slugify(){return this.check(yh())}})),f1=se("ZodString",(e,t)=>{iu.init(e,t),sv.init(e,t)},{email(e){return this.check(E_(b1,e))},url(e){return this.check(R_(y1,e))},jwt(e){return this.check(H_(k1,e))},emoji(e){return this.check(I_(_1,e))},guid(e){return this.check(T_(x1,e))},uuid(e){return this.check(A_(mu,e))},uuidv4(e){return this.check(w_(mu,e))},uuidv6(e){return this.check(S_(mu,e))},uuidv7(e){return this.check(M_(mu,e))},nanoid(e){return this.check(C_(v1,e))},cuid(e){return this.check(N_(E1,e))},cuid2(e){return this.check(P_(T1,e))},ulid(e){return this.check(O_(A1,e))},base64(e){return this.check(z_(N1,e))},base64url(e){return this.check(V_(P1,e))},xid(e){return this.check(k_(w1,e))},ksuid(e){return this.check(D_(S1,e))},ipv4(e){return this.check(L_(M1,e))},ipv6(e){return this.check(F_(R1,e))},cidrv4(e){return this.check(U_(I1,e))},cidrv6(e){return this.check(B_(C1,e))},e164(e){return this.check(j_(O1,e))},datetime(e){return this.check(G_(h1,e))},date(e){return this.check($_(p1,e))},time(e){return this.check(K_(m1,e))},duration(e){return this.check(W_(g1,e))}});function Le(e){return v_(f1,e)}var Jt=se("ZodStringFormat",(e,t)=>{$t.init(e,t),sv.init(e,t)}),h1=se("ZodISODateTime",(e,t)=>{Ry.init(e,t),Jt.init(e,t)}),p1=se("ZodISODate",(e,t)=>{Iy.init(e,t),Jt.init(e,t)}),m1=se("ZodISOTime",(e,t)=>{Cy.init(e,t),Jt.init(e,t)}),g1=se("ZodISODuration",(e,t)=>{Ny.init(e,t),Jt.init(e,t)}),b1=se("ZodEmail",(e,t)=>{by.init(e,t),Jt.init(e,t)});var x1=se("ZodGUID",(e,t)=>{my.init(e,t),Jt.init(e,t)});var mu=se("ZodUUID",(e,t)=>{gy.init(e,t),Jt.init(e,t)});var y1=se("ZodURL",(e,t)=>{_y.init(e,t),Jt.init(e,t)});var _1=se("ZodEmoji",(e,t)=>{vy.init(e,t),Jt.init(e,t)});var v1=se("ZodNanoID",(e,t)=>{Ey.init(e,t),Jt.init(e,t)});var E1=se("ZodCUID",(e,t)=>{Ty.init(e,t),Jt.init(e,t)});var T1=se("ZodCUID2",(e,t)=>{Ay.init(e,t),Jt.init(e,t)});var A1=se("ZodULID",(e,t)=>{wy.init(e,t),Jt.init(e,t)});var w1=se("ZodXID",(e,t)=>{Sy.init(e,t),Jt.init(e,t)});var S1=se("ZodKSUID",(e,t)=>{My.init(e,t),Jt.init(e,t)});var M1=se("ZodIPv4",(e,t)=>{Py.init(e,t),Jt.init(e,t)});var R1=se("ZodIPv6",(e,t)=>{ky.init(e,t),Jt.init(e,t)});var I1=se("ZodCIDRv4",(e,t)=>{Dy.init(e,t),Jt.init(e,t)});var C1=se("ZodCIDRv6",(e,t)=>{Ly.init(e,t),Jt.init(e,t)});var N1=se("ZodBase64",(e,t)=>{Uy.init(e,t),Jt.init(e,t)});var P1=se("ZodBase64URL",(e,t)=>{By.init(e,t),Jt.init(e,t)});var O1=se("ZodE164",(e,t)=>{zy.init(e,t),Jt.init(e,t)});var k1=se("ZodJWT",(e,t)=>{Vy.init(e,t),Jt.init(e,t)});var av=se("ZodNumber",(e,t)=>{ih.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>x0(e,n,i,r),e.isFinite=!0},qb({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=ti(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=ti(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=ti(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>ti(e).format??null},{gt(e,t){return this.check(uu(e,t))},gte(e,t){return this.check(hc(e,t))},min(e,t){return this.check(hc(e,t))},lt(e,t){return this.check(lu(e,t))},lte(e,t){return this.check(fc(e,t))},max(e,t){return this.check(fc(e,t))},int(e){return this.check(ev(e))},safe(e){return this.check(ev(e))},positive(e){return this.check(uu(0,e))},nonnegative(e){return this.check(hc(0,e))},negative(e){return this.check(lu(0,e))},nonpositive(e){return this.check(fc(0,e))},multipleOf(e,t){return this.check(du(e,t))},step(e,t){return this.check(du(e,t))},finite(){return this}}));function gt(e){return X_(av,e)}var D1=se("ZodNumberFormat",(e,t)=>{jy.init(e,t),av.init(e,t)});function ev(e){return q_(D1,e)}var L1=se("ZodBoolean",(e,t)=>{Hy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>y0(e,n,i,r)});function ca(e){return J_(L1,e)}var F1=se("ZodUnknown",(e,t)=>{Gy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>v0(e,n,i,r)});function oa(){return Z_(F1)}var U1=se("ZodNever",(e,t)=>{$y.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>_0(e,n,i,r)});function B1(e){return Y_(U1,e)}var z1=se("ZodArray",(e,t)=>{bc(),Ky.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>M0(e,n,i,r),e.element=t.element},{min(e,t){return this.check(Ga(e,t))},nonempty(e){return this.check(Ga(1,e))},max(e,t){return this.check(fu(e,t))},length(e,t){return this.check(hu(e,t))},unwrap(){return this.element}});function at(e,t){return Q_(z1,e,t)}var V1=se("ZodObject",(e,t)=>{bc(),qy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>R0(e,n,i,r),xI(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return Ct(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Qn(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Qn(this._zod.def,{catchall:oa()}))},loose(){return this.clone(Qn(this._zod.def,{catchall:oa()}))},strict(){return this.clone(Qn(this._zod.def,{catchall:B1()}))},strip(){return this.clone(Qn(this._zod.def,{catchall:void 0}))},extend(e){return uI(this,e)},safeExtend(e){return dI(this,e)},merge(e){return fI(this,e)},pick(e){return cI(this,e)},omit(e){return lI(this,e)},partial(...e){return $b(Ch,this,e[0])},exactPartial(...e){return $b(lv,this,e[0],"exactPartial")},required(...e){return hI(uv,this,e[0])}});function be(e,t){let n={type:"object",shape:e??{},...Fe(t)};return new V1(n)}var ov=se("ZodUnion",(e,t)=>{rh.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>I0(e,n,i,r),e.options=t.options});function Wa(e,t){return new ov({type:"union",options:e,...Fe(t)})}var j1=se("ZodDiscriminatedUnion",(e,t)=>{ov.init(e,t),Jy.init(e,t)});function Ri(e,t,n){return new j1({type:"union",options:t,discriminator:e,...Fe(n)})}var H1=se("ZodIntersection",(e,t)=>{Zy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>C0(e,n,i,r)});function G1(e,t){return new H1({type:"intersection",left:e,right:t})}var $1=se("ZodTuple",(e,t)=>{bc(),Yy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>N0(e,n,i,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map((t)=>new Ch({type:"optional",innerType:t}))})}});function cv(e,t,n){let i=t instanceof Ut,r=i?n:t;return new $1({type:"tuple",items:e,rest:i?t:null,...Fe(r)})}var tv=se("ZodRecord",(e,t)=>{bc(),Qy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>P0(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function gu(e,t,n){if(!t||!t._zod)return new tv({type:"record",keyType:Le(),valueType:e,...Fe(t)});return new tv({type:"record",keyType:e,valueType:t,...Fe(n)})}var Ih=se("ZodEnum",(e,t)=>{e_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(i,r,s)=>E0(e,i,r,s),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{let s={};for(let a of i)if(n.has(a))s[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new Ih({...t,checks:[],...Fe(r),entries:s})},e.exclude=(i,r)=>{let s={...t.entries};for(let a of i)if(n.has(a))delete s[a];else throw Error(`Key ${a} not found in enum`);return new Ih({...t,checks:[],...Fe(r),entries:s})}});function Ct(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((i)=>[i,i])):e;return new Ih({type:"enum",entries:n,...Fe(t)})}var K1=se("ZodLiteral",(e,t)=>{t_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>T0(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 $e(e,t){return new K1({type:"literal",values:Array.isArray(e)?e:[e],...Fe(t)})}var W1=se("ZodTransform",(e,t)=>{bc(),n_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>S0(e,n,i,r),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new oc(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(sa(s,n.value,t));else{let a=s;if(a.fatal)a.continue=!1;if(a.code??(a.code="custom"),!("input"in a))a.input=n.value;a.inst??(a.inst=e),n.issues.push(sa(a))}};let r=t.transform(n.value,n);if(r instanceof Promise)return r.then((s)=>(n.value=s,n));return n.value=r,n}});function X1(e){return new W1({type:"transform",transform:e})}var Ch=se("ZodOptional",(e,t)=>{sh.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Mh(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function nv(e){return new Ch({type:"optional",innerType:e})}var lv=se("ZodExactOptional",(e,t)=>{i_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Mh(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function q1(e){return new lv({type:"optional",innerType:e})}var J1=se("ZodNullable",(e,t)=>{r_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>O0(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function iv(e){return new J1({type:"nullable",innerType:e})}var Z1=se("ZodDefault",(e,t)=>{s_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>L0(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Y1(e,t){return new Z1({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Uf(t)}})}var Q1=se("ZodPrefault",(e,t)=>{a_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>F0(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function eC(e,t){return new Q1({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Uf(t)}})}var uv=se("ZodNonOptional",(e,t)=>{o_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>k0(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function tC(e,t){return new uv({type:"nonoptional",innerType:e,...Fe(t)})}var nC=se("ZodCatch",(e,t)=>{c_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>U0(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function iC(e,t){return new nC({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Jb(t)})}var rC=se("ZodPipe",(e,t)=>{l_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>B0(e,n,i,r),e.in=t.in,e.out=t.out});function rv(e,t){return new rC({type:"pipe",in:e,out:t})}var sC=se("ZodReadonly",(e,t)=>{u_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>z0(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function aC(e){return new sC({type:"readonly",innerType:e})}var oC=se("ZodTemplateLiteral",(e,t)=>{d_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>A0(e,n,i,r)});function cC(e,t){return new oC({type:"template_literal",parts:e,...Fe(t)})}var lC=se("ZodCustom",(e,t)=>{f_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>w0(e,n,i,r)});function uC(e,t={}){return e0(lC,e,t)}function dC(e,t){return t0(e,t)}var bu={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"};var dv;(function(e){})(dv||(dv={}));var fv=["neutral","dark","light"];var Nh=(e,t)=>Object.freeze({id:e,rgb:Object.freeze([...t]),hex:`#${t.map((n)=>n.toString(16).padStart(2,"0")).join("")}`}),hv=Object.freeze({neutral:Nh("neutral",[170,177,188]),dark:Nh("dark",[26,26,26]),light:Nh("light",[223,227,232])});var WV=hv.neutral.rgb,XV=hv.neutral.hex;/*!+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let o=a[1];if(t===a[0]){s(a);continue}if(e.external){let l=e.external.registry.get(a[0])?.id;if(t!==a[0]&&l){s(a);continue}}if(e.metadataRegistry.get(a[0])?.id){s(a);continue}if(o.cycle){s(a);continue}if(o.count>1){if(e.reused==="ref")s(a)}}if(e.external)e.sharedDefsExtractedFor=e.external}function lv(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let i of t){if(!i||typeof i!=="object")return;lv(i);let r=Object.keys(i);if(r.length!==1||r[0]!=="type")return;let s=i.type;for(let a of Array.isArray(s)?s:[s]){if(typeof a!=="string")return;if(!n.includes(a))n.push(a)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var uv=new Set(["type","properties","required","additionalProperties"]),ov=["oneOf","anyOf"];function cv(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function wh(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let a in s)if(!uv.has(a))return null;t.push(s)}let n={},i=new Set;for(let s of t){for(let a in s.properties){if(Object.prototype.hasOwnProperty.call(n,a))continue;let o=[];for(let l of t){let u=l.properties?.[a]??cv(l);if(u===null||u===void 0)continue;if(!o.some((d)=>JSON.stringify(d)===JSON.stringify(u)))o.push(u)}let c=o.length===1?o[0]:wh(o)??{allOf:o};mi(n,a,c)}for(let a of s.required??[])i.add(a)}let r={type:"object",properties:n};if(i.size)r.required=[...i];if(t.every((s)=>s.additionalProperties===!1))r.additionalProperties=!1;else{let s=[];for(let a of t){let o=cv(a);if(o&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(o)))s.push(o)}if(s.length===1)r.additionalProperties=s[0];else if(s.length>1)r.additionalProperties={allOf:s}}return r}function n1(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let r of uv)if(r in e)return;let n=t.filter((r)=>ov.some((s)=>Array.isArray(r[s]))),i=null;if(!n.length)i=wh(t);else{let r=n[0],s=ov.find((c)=>Array.isArray(r[c]));if(Object.keys(r).length!==1)return;let a=t.filter((c)=>c!==r),o=r[s].map((c)=>wh([...a,c]));if(o.some((c)=>!c))return;i={[s]:o}}if(!i)return;delete e.allOf,mc(e,i)}function Rh(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let i=(o)=>{let c=e.seen.get(o);if(c.ref===null)return;let l=c.def??c.schema,u={...l},d=c.ref;if(c.ref=null,d){i(d);let h=e.seen.get(d),b=h.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(b);else mc(l,b);if(mc(l,u),o._zod.parent===d)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(!(g in u))delete l[g]}if(b.$ref&&h.def)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(g in h.def&&JSON.stringify(l[g])===JSON.stringify(h.def[g]))delete l[g]}}let f=o._zod.parent;if(f&&f!==d){i(f);let h=e.seen.get(f);if(h?.schema.$ref){if(l.$ref=h.schema.$ref,h.def)for(let b in l){if(b==="$ref"||b==="allOf")continue;if(b in h.def&&JSON.stringify(l[b])===JSON.stringify(h.def[b]))delete l[b]}}}e.override({zodSchema:o,jsonSchema:l,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let o of[...e.seen.entries()].reverse())i(o[0]);if(e.target!=="openapi-3.0")for(let o of e.seen.entries())lv(o[1].def??o[1].schema);for(let o of e.deferred)o();if(e.intersections.length){let o=new Map;for(let c of e.seen.values())for(let l of[c.schema,c.def]){let u=l?.allOf;if(!Array.isArray(u))continue;let d=o.get(u);if(d)d.push(l);else o.set(u,[l])}for(let c of e.intersections)for(let l of o.get(c)??[])n1(l)}}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 o=e.external.registry.get(t)?.id;if(!o)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(o)}mc(r,n.defId?n.schema:n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&r.id===s)delete r.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let o of e.seen.entries()){let c=o[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;mi(a,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(a).length>0)if(e.target==="draft-2020-12")r.$defs=a;else r.definitions=a;try{let o=JSON.parse(JSON.stringify(r));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:gc(t,"input",e.processors),output:gc(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch(o){throw Error("Error converting schema to JSON.")}}function zn(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 zn(i.element,n);if(i.type==="set")return zn(i.valueType,n);if(i.type==="lazy")return zn(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"||i.type==="catch")return zn(i.innerType,n);if(i.type==="intersection")return zn(i.left,n)||zn(i.right,n);if(i.type==="record"||i.type==="map")return zn(i.keyType,n)||zn(i.valueType,n);if(i.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return zn(i.in,n)||zn(i.out,n)}if(i.type==="object"){for(let r in i.shape)if(zn(i.shape[r],n))return!0;return!1}if(i.type==="union"){for(let r of i.options)if(zn(r,n))return!0;return!1}if(i.type==="tuple"){for(let r of i.items)if(zn(r,n))return!0;if(i.rest&&zn(i.rest,n))return!0;return!1}return!1}var dv=(e,t={})=>(n)=>{let i=Sh({...n,processors:t});return qt(e,i),Mh(i,e),Rh(i,e)},gc=(e,t,n={})=>(i)=>{let{libraryOptions:r,target:s}=i??{},a=Sh({...r??{},target:s,io:t,processors:n});return qt(e,a),Mh(a,e),Rh(a,e)};var Ka=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},Wa=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},fv=(e,t)=>{Ka(e,"minimum",t),Wa(e,"maximum",t)},gv=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},bv=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},xv=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},yv=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},hv=(e,t)=>Ka(e,"minimum",t.minimum),pv=(e,t)=>Wa(e,"maximum",t.maximum),mv=(e)=>(t,n)=>{yv(t,n.format);let[i,r]=e[n.format];Ka(t,"minimum",i),Wa(t,"maximum",r)},i1={greater_than:(e,t)=>Ka(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Wa(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>gv(e,t.value),number_format:mv(Kl),bigint_format:mv($f),min_length:hv,max_length:pv,length_equals:(e,t)=>fv(e,t.length),min_size:hv,max_size:pv,size_equals:(e,t)=>fv(e,t.size),string_format:(e,t)=>{if(yv(e,t.format),t.pattern)bv(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>xv(e,t.mime)};function ni(e){let t={},n=e._zod.def,i=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let s of i)i1[s._zod.def.check]?.(t,s._zod.def);let r=e._zod.bag;if(r.minimum!==void 0)Ka(t,"minimum",r.minimum);if(r.exclusiveMinimum!==void 0)Ka(t,"exclusiveMinimum",r.exclusiveMinimum);if(r.maximum!==void 0)Wa(t,"maximum",r.maximum);if(r.exclusiveMaximum!==void 0)Wa(t,"exclusiveMaximum",r.exclusiveMaximum);if(r.multipleOf!==void 0)gv(t,r.multipleOf);if(r.format!==void 0){if(t.format??(t.format=r.format),r.format.includes("int"))t.isInt=!0}if(r.mime)xv(t,r.mime);for(let s of r.patterns??[])bv(t,s);return t}var r1={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s1=new Map([[oh,Px],[cu,Ox]]),_v=(e)=>s1.get(e)??e,vv=(e,t,n,i)=>{let r=n;r.type="string";let{minimum:s,maximum:a,format:o,patterns:c,contentEncoding:l,laxFormat:u}=ni(e);if(typeof s==="number")r.minLength=s;if(typeof a==="number")r.maxLength=a;if(o){if(r.format=r1[o]??o,r.format==="")delete r.format;if(o==="time"||u)delete r.format}if(l)r.contentEncoding=l;if(c&&c.size>0){let d=[...c].map(_v);if(d.length===1)r.pattern=d[0].source;else if(d.length>1)r.allOf=[...d.map((f)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))]}},Ev=(e,t,n,i)=>{let r=n,{minimum:s,maximum:a,multipleOf:o,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=ni(e);r.type=u?"integer":"number";let d=typeof l==="number"&&l>=(s??Number.NEGATIVE_INFINITY),f=typeof c==="number"&&c<=(a??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(d)if(h)r.minimum=l,r.exclusiveMinimum=!0;else r.exclusiveMinimum=l;else if(typeof s==="number")r.minimum=s;if(f)if(h)r.maximum=c,r.exclusiveMaximum=!0;else r.exclusiveMaximum=c;else if(typeof a==="number")r.maximum=a;if(o){let b=new Set;for(let p of o)if(Number.isFinite(p)&&p!==0)b.add(Math.abs(p));else Ir(e,t,r,i,`A multipleOf divisor of ${p} cannot be represented in JSON Schema`);let[m,...g]=b;if(m!==void 0)r.multipleOf=m;if(g.length)r.allOf=[...r.allOf??[],...g.map((p)=>({multipleOf:p}))]}},Tv=(e,t,n,i)=>{n.type="boolean"};var Av=(e,t,n,i)=>{n.not={}};var wv=(e,t,n,i)=>{};var Sv=(e,t,n,i)=>{let r=e._zod.def,s=rc(r.entries);if(s.length===0){n.not={};return}if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";n.enum=s},Mv=(e,t,n,i)=>{let r=e._zod.def;if(r.values.length===0){n.not={};return}let s=[];for(let a of r.values)if(a===void 0){if(Ir(e,t,n,i,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a==="bigint"){if(Ir(e,t,n,i,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(a))}else s.push(a);if(s.length===0);else if(s.length===1){let a=s[0];if(n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[a];else n.const=a}else{if(s.every((a)=>typeof a==="number"))n.type="number";if(s.every((a)=>typeof a==="string"))n.type="string";if(s.every((a)=>typeof a==="boolean"))n.type="boolean";if(s.every((a)=>a===null))n.type="null";n.enum=s}};var Rv=(e,t,n,i)=>{let r=n,s=e._zod.pattern;if(!s)throw Error("Pattern not found in template literal");r.type="string",r.pattern=s.source};var Iv=(e,t,n,i)=>{Ir(e,t,n,i,"Custom types cannot be represented in JSON Schema")};var Cv=(e,t,n,i)=>{Ir(e,t,n,i,"Transforms cannot be represented in JSON Schema")};var Nv=(e,t,n,i)=>{let r=n,s=e._zod.def,{minimum:a,maximum:o}=ni(e);if(typeof a==="number")r.minItems=a;if(typeof o==="number")r.maxItems=o;r.type="array",r.items=qt(s.element,t,{...i,path:[...i.path,"items"]})};function bc(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return bc(t.out);if(t.type==="catch")return bc(t.innerType);return e._zod.optin}var Pv=(e,t,n,i)=>{let r=n,s=e._zod.def,a=s.shape;if(Object.getOwnPropertySymbols(a).length&&Ir(e,t,r,i,"Symbol keys cannot be represented in JSON Schema"))return;r.type="object",r.properties={};for(let l in a)mi(r.properties,l,qt(a[l],t,{...i,path:[...i.path,"properties",l]}));let c=[];for(let l of Object.keys(a)){let u=s.shape[l];if(t.io==="input"?bc(u)===void 0:u._zod.optout===void 0)c.push(l)}if(c.length>0)r.required=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=qt(s.catchall,t,{...i,path:[...i.path,"additionalProperties"]})},Ov=(e,t,n,i)=>{let r=e._zod.def,s=r.inclusive===!1,a=r.options.map((o,c)=>qt(o,t,{...i,path:[...i.path,s?"oneOf":"anyOf",c]}));if(s)n.oneOf=a;else n.anyOf=a},kv=(e,t,n,i)=>{let r=e._zod.def,s=qt(r.left,t,{...i,path:[...i.path,"allOf",0]}),a=qt(r.right,t,{...i,path:[...i.path,"allOf",1]}),o=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...o(s)?s.allOf:[s],...o(a)?a.allOf:[a]];n.allOf=c,t.intersections.push(c)},Dv=(e,t,n,i)=>{let r=n,s=e._zod.def;r.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",o=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((m,g)=>qt(m,t,{...i,path:[...i.path,a,g]})),l=s.rest?qt(s.rest,t,{...i,path:[...i.path,o,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null,u=s.items.length;while(u>0){let m=s.items[u-1];if(!(t.io==="input"?bc(m)!==void 0:m._zod.optout==="optional"))break;u--}let d=s.items.length,f=!s.rest;if(t.target==="draft-2020-12"){if(r.prefixItems=c,f)r.items=!1;else if(l)r.items=l;if(u>0)r.minItems=u;if(f)r.maxItems=d}else if(t.target==="openapi-3.0"){if(r.items={anyOf:c},l)r.items.anyOf.push(l);if(u>0)r.minItems=u;if(f)r.maxItems=d}else{if(r.items=c,f)r.additionalItems=!1;else if(l)r.additionalItems=l;if(u>0)r.minItems=u;if(f)r.maxItems=d}let{minimum:h,maximum:b}=ni(e);if(typeof h==="number")r.minItems=h;if(typeof b==="number")r.maxItems=b};function Ih(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let b=e.get(t)?.def;if(!b)return t;let m=Ih(e,b,n);return m===b?t:m}for(let b of["anyOf","oneOf"]){let m=t[b];if(!Array.isArray(m))continue;let g=m.map((p)=>Ih(e,p,n));if(g.some((p,x)=>p!==m[x]))t={...t,[b]:g}}let i=Array.isArray(t.type)?t.type:[t.type],r=!i.includes("string")&&i.some((b)=>b==="number"||b==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!r&&!s?.some((b)=>typeof b==="number"))return t;let{minimum:a,maximum:o,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...h}=t;if(h.enum)h.enum=h.enum.map((b)=>typeof b==="number"?String(b):b);else if(typeof h.const==="number")h.const=String(h.const);if(!r)return h;if(h.type="string",!s)h.pattern=(i.includes("number")?Ga:nu).source;return h}var Ch=new WeakMap;function a1(e){let t=new Map;for(let i of e.seen.values())if(i.def&&!t.has(i.schema))t.set(i.schema,i);let n=new Map;for(let i of Ch.get(e)??[]){let r=e.seen.get(i),s=(r?.def??r?.schema)?.propertyNames;if(!s||s===!0||n.has(s))continue;let a=Ih(t,s,new Set);if(a!==s)n.set(s,a)}if(!n.size)return;for(let i of e.seen.values())for(let r of[i.schema,i.def]){let s=r&&n.get(r.propertyNames);if(s)r.propertyNames=s}}var Lv=(e,t,n,i)=>{let r=n,s=e._zod.def;r.type="object";let a=s.keyType,o=ni(a).patterns;if(s.mode==="loose"&&o&&o.size>0){let u=qt(s.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(let d of o)mi(r.patternProperties,_v(d).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){r.propertyNames=qt(s.keyType,t,{...i,path:[...i.path,"propertyNames"]});let u=Ch.get(t);if(!u)u=[],Ch.set(t,u),t.deferred.push(()=>a1(t));u.push(e)}r.additionalProperties=qt(s.valueType,t,{...i,path:[...i.path,"additionalProperties"]})}let c=a._zod.values,l=t.io==="input"&&bc(s.valueType)!==void 0;if(c&&!s.partial&&!l){let u=[...c].filter((d)=>typeof d==="string"||typeof d==="number");if(u.length>0)r.required=u.map(String)}},Fv=(e,t,n,i)=>{let r=e._zod.def,s=qt(r.innerType,t,i),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=r.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},Uv=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType},Nh=Symbol();function Bv(e,t,n,i,r){let s=!1,a=JSON.stringify(e,(o,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(a);return Ir(t,n,i,r,"BigInt defaults cannot be represented in JSON Schema"),Nh}var zv=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType;let a=Bv(r.defaultValue,e,t,n,i);if(a!==Nh)n.default=a},Vv=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);if(s.ref=r.innerType,t.io!=="input")return;let a=Bv(r.defaultValue,e,t,n,i);if(a!==Nh)n._prefault=a},jv=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType;let a;try{a=r.catchValue(void 0)}catch{Ir(e,t,n,i,"Dynamic catch values are not supported in JSON Schema");return}n.default=a},Hv=(e,t,n,i)=>{let r=e._zod.def,s=r.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?s?r.out:r.in:r.out;qt(a,t,i);let o=t.seen.get(e);o.ref=a},Gv=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0};var Ph=(e,t,n,i)=>{let r=e._zod.def;qt(r.innerType,t,i);let s=t.seen.get(e);s.ref=r.innerType};var $v=new WeakSet([Object.prototype,Error.prototype]);function xu(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let i=n(this);return Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0}),i},set(i){Object.defineProperty(this,t,{value:i,configurable:!0,writable:!0})}})}var p1=(e,t)=>{sx.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if($v.has(n))return;$v.add(n),xu(n,"format",(i)=>(r)=>ox(i,r)),xu(n,"flatten",(i)=>(r)=>ax(i,r)),xu(n,"addIssue",(i)=>(r)=>{i.issues.push(r),i.message=JSON.stringify(i.issues,sc,2)}),xu(n,"addIssues",(i)=>(r)=>{i.issues.push(...r),i.message=JSON.stringify(i.issues,sc,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var ii=se("ZodError",p1,void 0,{Parent:Error});var Kv=Yl(ii),Wv=Ql(ii),Xv=eu(ii),qv=tu(ii),Jv=lx(ii),Zv=ux(ii),Yv=dx(ii),Qv=fx(ii),e0=hx(ii),t0=px(ii),n0=mx(ii),i0=gx(ii);function g1(){if(!Bn.localeError)ti(hh())}function xc(){if(!Bn.memoizer)ti({memoizer:v_()})}var Kt=se("ZodType",(e,t)=>(g1(),Ut.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ei(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ji(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(mC(e,t))},superRefine(e,t){return this.check(gC(e,t))},overwrite(e){return this.check(Qr(e))},optional(){return a0(this)},exactOptional(){return eC(this)},nullable(){return o0(this)},nullish(){return a0(o0(this))},nonoptional(e){return aC(this,e)},array(){return at(this)},or(e){return Xa([this,e])},and(e){return q1(this,e)},transform(e){return c0(this,Q1(e))},default(e){return iC(this,e)},prefault(e){return sC(this,e)},catch(e){return cC(this,e)},pipe(e){return c0(this,e)},readonly(){return dC(this)},describe(e){let t=this.clone();return oa.add(t,{description:e}),t},meta(...e){if(e.length===0)return oa.get(this);let t=this.clone();return oa.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return Jl(this,"~standard",{...ah(this),jsonSchema:{input:gc(this,"input"),output:gc(this,"output")}})},set "~standard"(e){Mr(this,"~standard",e)},parse:function e(t,n){return Kv(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Wv(this,t,n,{callee:e})},safeParse(e,t){return Xv(this,e,t)},async safeParseAsync(e,t){return qv(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Mr(this,"spa",e)},validate(e,t){return Jf(this,e,t)},validateAsync(e,t){return Zf(this,e,t)},encode:function e(t,n){return Jv(this,t,n,{callee:e})},decode:function e(t,n){return Zv(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Yv(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Qv(this,t,n,{callee:e})},safeEncode(e,t){return e0(this,e,t)},safeDecode(e,t){return t0(this,e,t)},async safeEncodeAsync(e,t){return n0(this,e,t)},async safeDecodeAsync(e,t){return i0(this,e,t)},toJSONSchema(e){return dv(this,{})(e)},get description(){return oa.get(this)?.description},get _def(){return this._zod.def}}),l0=se("_ZodString",(e,t)=>{ou.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>vv(e,n,i,r)},Qb({format:(e)=>ni(e).format??null,minLength:(e)=>ni(e).minimum??null,maxLength:(e)=>ni(e).maximum??null},{regex(...e){return this.check(ph(...e))},includes(...e){return this.check(bh(...e))},startsWith(...e){return this.check(xh(...e))},endsWith(...e){return this.check(yh(...e))},min(...e){return this.check($a(...e))},max(...e){return this.check(gu(...e))},length(...e){return this.check(bu(...e))},nonempty(...e){return this.check($a(1,...e))},lowercase(e){return this.check(mh(e))},uppercase(e){return this.check(gh(e))},trim(){return this.check(vh())},normalize(...e){return this.check(_h(...e))},toLowerCase(){return this.check(Eh())},toUpperCase(){return this.check(Th())},slugify(){return this.check(Ah())}})),b1=se("ZodString",(e,t)=>{ou.init(e,t),l0.init(e,t)},{email(e){return this.check(S_(E1,e))},url(e){return this.check(P_(A1,e))},jwt(e){return this.check(W_(B1,e))},emoji(e){return this.check(O_(w1,e))},guid(e){return this.check(M_(T1,e))},uuid(e){return this.check(R_(yu,e))},uuidv4(e){return this.check(I_(yu,e))},uuidv6(e){return this.check(C_(yu,e))},uuidv7(e){return this.check(N_(yu,e))},nanoid(e){return this.check(k_(S1,e))},cuid(e){return this.check(D_(M1,e))},cuid2(e){return this.check(L_(R1,e))},ulid(e){return this.check(F_(I1,e))},base64(e){return this.check(G_(L1,e))},base64url(e){return this.check($_(F1,e))},xid(e){return this.check(U_(C1,e))},ksuid(e){return this.check(B_(N1,e))},ipv4(e){return this.check(z_(P1,e))},ipv6(e){return this.check(V_(O1,e))},cidrv4(e){return this.check(j_(k1,e))},cidrv6(e){return this.check(H_(D1,e))},e164(e){return this.check(K_(U1,e))},datetime(e){return this.check(X_(x1,e))},date(e){return this.check(q_(y1,e))},time(e){return this.check(J_(_1,e))},duration(e){return this.check(Z_(v1,e))}});function Fe(e){return w_(b1,e)}var Jt=se("ZodStringFormat",(e,t)=>{$t.init(e,t),l0.init(e,t)}),x1=se("ZodISODateTime",(e,t)=>{Py.init(e,t),Jt.init(e,t)}),y1=se("ZodISODate",(e,t)=>{Oy.init(e,t),Jt.init(e,t)}),_1=se("ZodISOTime",(e,t)=>{ky.init(e,t),Jt.init(e,t)}),v1=se("ZodISODuration",(e,t)=>{Dy.init(e,t),Jt.init(e,t)}),E1=se("ZodEmail",(e,t)=>{vy.init(e,t),Jt.init(e,t)});var T1=se("ZodGUID",(e,t)=>{yy.init(e,t),Jt.init(e,t)});var yu=se("ZodUUID",(e,t)=>{_y.init(e,t),Jt.init(e,t)});var A1=se("ZodURL",(e,t)=>{Ay.init(e,t),Jt.init(e,t)});var w1=se("ZodEmoji",(e,t)=>{wy.init(e,t),Jt.init(e,t)});var S1=se("ZodNanoID",(e,t)=>{Sy.init(e,t),Jt.init(e,t)});var M1=se("ZodCUID",(e,t)=>{My.init(e,t),Jt.init(e,t)});var R1=se("ZodCUID2",(e,t)=>{Ry.init(e,t),Jt.init(e,t)});var I1=se("ZodULID",(e,t)=>{Iy.init(e,t),Jt.init(e,t)});var C1=se("ZodXID",(e,t)=>{Cy.init(e,t),Jt.init(e,t)});var N1=se("ZodKSUID",(e,t)=>{Ny.init(e,t),Jt.init(e,t)});var P1=se("ZodIPv4",(e,t)=>{Ly.init(e,t),Jt.init(e,t)});var O1=se("ZodIPv6",(e,t)=>{Uy.init(e,t),Jt.init(e,t)});var k1=se("ZodCIDRv4",(e,t)=>{By.init(e,t),Jt.init(e,t)});var D1=se("ZodCIDRv6",(e,t)=>{zy.init(e,t),Jt.init(e,t)});var L1=se("ZodBase64",(e,t)=>{jy.init(e,t),Jt.init(e,t)});var F1=se("ZodBase64URL",(e,t)=>{Hy.init(e,t),Jt.init(e,t)});var U1=se("ZodE164",(e,t)=>{Gy.init(e,t),Jt.init(e,t)});var B1=se("ZodJWT",(e,t)=>{$y.init(e,t),Jt.init(e,t)});var u0=se("ZodNumber",(e,t)=>{ch.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ev(e,n,i,r),e.isFinite=!0},Qb({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=ni(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=ni(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=ni(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>ni(e).format??null},{gt(e,t){return this.check(pu(e,t))},gte(e,t){return this.check(pc(e,t))},min(e,t){return this.check(pc(e,t))},lt(e,t){return this.check(hu(e,t))},lte(e,t){return this.check(hc(e,t))},max(e,t){return this.check(hc(e,t))},int(e){return this.check(r0(e))},safe(e){return this.check(r0(e))},positive(e){return this.check(pu(0,e))},nonnegative(e){return this.check(pc(0,e))},negative(e){return this.check(hu(0,e))},nonpositive(e){return this.check(hc(0,e))},multipleOf(e,t){return this.check(mu(e,t))},step(e,t){return this.check(mu(e,t))},finite(){return this}}));function gt(e){return Y_(u0,e)}var z1=se("ZodNumberFormat",(e,t)=>{Ky.init(e,t),u0.init(e,t)});function r0(e){return Q_(z1,e)}var V1=se("ZodBoolean",(e,t)=>{Wy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Tv(e,n,i,r)});function la(e){return ev(V1,e)}var j1=se("ZodUnknown",(e,t)=>{Xy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>wv(e,n,i,r)});function ca(){return tv(j1)}var H1=se("ZodNever",(e,t)=>{qy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Av(e,n,i,r)});function G1(e){return nv(H1,e)}var $1=se("ZodArray",(e,t)=>{xc(),Jy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Nv(e,n,i,r),e.element=t.element},{min(e,t){return this.check($a(e,t))},nonempty(e){return this.check($a(1,e))},max(e,t){return this.check(gu(e,t))},length(e,t){return this.check(bu(e,t))},unwrap(){return this.element}});function at(e,t){return iv($1,e,t)}var K1=se("ZodObject",(e,t)=>{xc(),Qy.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Pv(e,n,i,r),TI(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return Ct(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ei(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ei(this._zod.def,{catchall:ca()}))},loose(){return this.clone(ei(this._zod.def,{catchall:ca()}))},strict(){return this.clone(ei(this._zod.def,{catchall:G1()}))},strip(){return this.clone(ei(this._zod.def,{catchall:void 0}))},extend(e){return mI(this,e)},safeExtend(e){return gI(this,e)},merge(e){return bI(this,e)},pick(e){return hI(this,e)},omit(e){return pI(this,e)},partial(...e){return qb(Dh,this,e[0])},exactPartial(...e){return qb(h0,this,e[0],"exactPartial")},required(...e){return xI(p0,this,e[0])}});function be(e,t){let n={type:"object",shape:e??{},...Ue(t)};return new K1(n)}var d0=se("ZodUnion",(e,t)=>{lh.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ov(e,n,i,r),e.options=t.options});function Xa(e,t){return new d0({type:"union",options:e,...Ue(t)})}var W1=se("ZodDiscriminatedUnion",(e,t)=>{d0.init(e,t),e_.init(e,t)});function Ri(e,t,n){return new W1({type:"union",options:t,discriminator:e,...Ue(n)})}var X1=se("ZodIntersection",(e,t)=>{t_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>kv(e,n,i,r)});function q1(e,t){return new X1({type:"intersection",left:e,right:t})}var J1=se("ZodTuple",(e,t)=>{xc(),n_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Dv(e,n,i,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map((t)=>new Dh({type:"optional",innerType:t}))})}});function f0(e,t,n){let i=t instanceof Ut,r=i?n:t;return new J1({type:"tuple",items:e,rest:i?t:null,...Ue(r)})}var s0=se("ZodRecord",(e,t)=>{xc(),i_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Lv(e,n,i,r),e.keyType=t.keyType,e.valueType=t.valueType});function _u(e,t,n){if(!t||!t._zod)return new s0({type:"record",keyType:Fe(),valueType:e,...Ue(t)});return new s0({type:"record",keyType:e,valueType:t,...Ue(n)})}var kh=se("ZodEnum",(e,t)=>{r_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(i,r,s)=>Sv(e,i,r,s),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{let s={};for(let a of i)if(n.has(a))s[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new kh({...t,checks:[],...Ue(r),entries:s})},e.exclude=(i,r)=>{let s={...t.entries};for(let a of i)if(n.has(a))delete s[a];else throw Error(`Key ${a} not found in enum`);return new kh({...t,checks:[],...Ue(r),entries:s})}});function Ct(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((i)=>[i,i])):e;return new kh({type:"enum",entries:n,...Ue(t)})}var Z1=se("ZodLiteral",(e,t)=>{s_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Mv(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 $e(e,t){return new Z1({type:"literal",values:Array.isArray(e)?e:[e],...Ue(t)})}var Y1=se("ZodTransform",(e,t)=>{xc(),a_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Cv(e,n,i,r),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new cc(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(aa(s,n.value,t));else{let a=s;if(a.fatal)a.continue=!1;if(a.code??(a.code="custom"),!("input"in a))a.input=n.value;a.inst??(a.inst=e),n.issues.push(aa(a))}};let r=t.transform(n.value,n);if(r instanceof Promise)return r.then((s)=>(n.value=s,n));return n.value=r,n}});function Q1(e){return new Y1({type:"transform",transform:e})}var Dh=se("ZodOptional",(e,t)=>{uh.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ph(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function a0(e){return new Dh({type:"optional",innerType:e})}var h0=se("ZodExactOptional",(e,t)=>{o_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Ph(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function eC(e){return new h0({type:"optional",innerType:e})}var tC=se("ZodNullable",(e,t)=>{c_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Fv(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function o0(e){return new tC({type:"nullable",innerType:e})}var nC=se("ZodDefault",(e,t)=>{l_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>zv(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function iC(e,t){return new nC({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Hf(t)}})}var rC=se("ZodPrefault",(e,t)=>{u_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Vv(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function sC(e,t){return new rC({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Hf(t)}})}var p0=se("ZodNonOptional",(e,t)=>{d_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Uv(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function aC(e,t){return new p0({type:"nonoptional",innerType:e,...Ue(t)})}var oC=se("ZodCatch",(e,t)=>{f_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>jv(e,n,i,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function cC(e,t){return new oC({type:"catch",innerType:e,catchValue:typeof t==="function"?t:ex(t)})}var lC=se("ZodPipe",(e,t)=>{h_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Hv(e,n,i,r),e.in=t.in,e.out=t.out});function c0(e,t){return new lC({type:"pipe",in:e,out:t})}var uC=se("ZodReadonly",(e,t)=>{p_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Gv(e,n,i,r),e.unwrap=()=>e._zod.def.innerType});function dC(e){return new uC({type:"readonly",innerType:e})}var fC=se("ZodTemplateLiteral",(e,t)=>{m_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Rv(e,n,i,r)});function hC(e,t){return new fC({type:"template_literal",parts:e,...Ue(t)})}var pC=se("ZodCustom",(e,t)=>{g_.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,i,r)=>Iv(e,n,i,r)});function mC(e,t={}){return rv(pC,e,t)}function gC(e,t){return sv(e,t)}var vu={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"};var m0;(function(e){})(m0||(m0={}));var g0=["neutral","dark","light"];var Lh=(e,t)=>Object.freeze({id:e,rgb:Object.freeze([...t]),hex:`#${t.map((n)=>n.toString(16).padStart(2,"0")).join("")}`}),b0=Object.freeze({neutral:Lh("neutral",[170,177,188]),dark:Lh("dark",[26,26,26]),light:Lh("light",[223,227,232])});var oj=b0.neutral.rgb,cj=b0.neutral.hex;/*!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 Zt=Uint8Array,ii=Uint16Array,jh=Int32Array,yu=new Zt([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]),_u=new Zt([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]),Lh=new Zt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),_v=function(e,t){var n=new ii(31);for(var i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new jh(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}},vv=_v(yu,2),{b:Ev,r:Fh}=vv;Ev[28]=258,Fh[258]=28;var Tv=_v(_u,0),{b:fC,r:pv}=Tv,Uh=new ii(32768);for(ht=0;ht<32768;++ht)er=(ht&43690)>>1|(ht&21845)<<1,er=(er&52428)>>2|(er&13107)<<2,er=(er&61680)>>4|(er&3855)<<4,Uh[ht]=((er&65280)>>8|(er&255)<<8)>>1;var er,ht,nr=function(e,t,n){var i=e.length,r=0,s=new ii(t);for(;r<i;++r)if(e[r])++s[e[r]-1];var a=new ii(t);for(r=1;r<t;++r)a[r]=a[r-1]+s[r-1]<<1;var o;if(n){o=new ii(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],d=a[e[r]-1]++<<u;for(var f=d|(1<<u)-1;d<=f;++d)o[Uh[d]>>c]=l}}else{o=new ii(i);for(r=0;r<i;++r)if(e[r])o[r]=Uh[a[e[r]-1]++]>>15-e[r]}return o},es=new Zt(288);for(ht=0;ht<144;++ht)es[ht]=8;var ht;for(ht=144;ht<256;++ht)es[ht]=9;var ht;for(ht=256;ht<280;++ht)es[ht]=7;var ht;for(ht=280;ht<288;++ht)es[ht]=8;var ht,_c=new Zt(32);for(ht=0;ht<32;++ht)_c[ht]=5;var ht,hC=nr(es,9,0),pC=nr(es,9,1),mC=nr(_c,5,0),gC=nr(_c,5,1),Ph=function(e){var t=e[0];for(var n=1;n<e.length;++n)if(e[n]>t)t=e[n];return t},Ii=function(e,t,n){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(t&7)&n},Oh=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Hh=function(e){return(e+7)/8|0},vc=function(e,t,n){if(t==null||t<0)t=0;if(n==null||n>e.length)n=e.length;return new Zt(e.subarray(t,n))};var bC=["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"],zn=function(e,t,n){var i=Error(t||bC[e]);if(i.code=e,Error.captureStackTrace)Error.captureStackTrace(i,zn);if(!n)throw i;return i},xC=function(e,t,n,i){var r=e.length,s=i?i.length:0;if(!r||t.f&&!t.l)return n||new Zt(0);var a=!n,o=a||t.i!=2,c=t.i;if(a)n=new Zt(r*3);var l=function(ce){var _e=n.length;if(ce>_e){var Re=new Zt(Math.max(_e*2,ce));Re.set(n),n=Re}},u=t.f||0,d=t.p||0,f=t.b||0,{l:h,d:b,m,n:g}=t,p=r*8;do{if(!h){u=Ii(e,d,1);var x=Ii(e,d+1,3);if(d+=3,!x){var _=Hh(d)+4,y=e[_-4]|e[_-3]<<8,v=_+y;if(v>r){if(c)zn(0);break}if(o)l(f+y);n.set(e.subarray(_,v),f),t.b=f+=y,t.p=d=v*8,t.f=u;continue}else if(x==1)h=pC,b=gC,m=9,g=5;else if(x==2){var T=Ii(e,d,31)+257,A=Ii(e,d+10,15)+4,E=T+Ii(e,d+5,31)+1;d+=14;var w=new Zt(E),P=new Zt(19);for(var S=0;S<A;++S)P[Lh[S]]=Ii(e,d+S*3,7);d+=A*3;var I=Ph(P),U=(1<<I)-1,N=nr(P,I,1);for(var S=0;S<E;){var F=N[Ii(e,d,U)];d+=F&15;var _=F>>4;if(_<16)w[S++]=_;else{var D=0,O=0;if(_==16)O=3+Ii(e,d,3),d+=2,D=w[S-1];else if(_==17)O=3+Ii(e,d,7),d+=3;else if(_==18)O=11+Ii(e,d,127),d+=7;while(O--)w[S++]=D}}var K=w.subarray(0,T),B=w.subarray(T);m=Ph(K),g=Ph(B),h=nr(K,m,1),b=nr(B,g,1)}else zn(1);if(d>p){if(c)zn(0);break}}if(o)l(f+131072);var X=(1<<m)-1,q=(1<<g)-1,le=d;for(;;le=d){var D=h[Oh(e,d)&X],de=D>>4;if(d+=D&15,d>p){if(c)zn(0);break}if(!D)zn(2);if(de<256)n[f++]=de;else if(de==256){le=d,h=null;break}else{var Me=de-254;if(de>264){var S=de-257,pe=yu[S];Me=Ii(e,d,(1<<pe)-1)+Ev[S],d+=pe}var J=b[Oh(e,d)&q],L=J>>4;if(!J)zn(3);d+=J&15;var B=fC[L];if(L>3){var pe=_u[L];B+=Oh(e,d)&(1<<pe)-1,d+=pe}if(d>p){if(c)zn(0);break}if(o)l(f+131072);var W=f+Me;if(f<B){var ne=s-B,ie=Math.min(B,W);if(ne+f<0)zn(3);for(;f<ie;++f)n[f]=i[ne+f]}for(;f<W;++f)n[f]=n[f-B]}}if(t.l=h,t.p=le,t.b=f,t.f=u,h)u=1,t.m=m,t.d=b,t.n=g}while(!u);return f!=n.length&&a?vc(n,0,f):n.subarray(0,f)},Cr=function(e,t,n){n<<=t&7;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8},xc=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},kh=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:wv,l:0};if(r==1){var a=new Zt(n[0].s+1);return a[n[0].s]=1,{t:a,l:1}}n.sort(function(v,T){return v.f-T.f}),n.push({s:-1,f:25001});var o=n[0],c=n[1],l=0,u=1,d=2;n[0]={s:-1,f:o.f+c.f,l:o,r:c};while(u!=r-1)o=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:o.f+c.f,l:o,r:c};var f=s[0].s;for(var i=1;i<r;++i)if(s[i].s>f)f=s[i].s;var h=new ii(f+1),b=Bh(n[u-1],h,0);if(b>t){var i=0,m=0,g=b-t,p=1<<g;s.sort(function(T,A){return h[A.s]-h[T.s]||T.f-A.f});for(;i<r;++i){var x=s[i].s;if(h[x]>t)m+=p-(1<<b-h[x]),h[x]=t;else break}m>>=g;while(m>0){var _=s[i].s;if(h[_]<t)m-=1<<t-h[_]++-1;else++i}for(;i>=0&&m;--i){var y=s[i].s;if(h[y]==t)--h[y],++m}b=t}return{t:new Zt(h),l:b}},Bh=function(e,t,n){return e.s==-1?Math.max(Bh(e.l,t,n+1),Bh(e.r,t,n+1)):t[e.s]=n},mv=function(e){var t=e.length;while(t&&!e[--t]);var n=new ii(++t),i=0,r=e[0],s=1,a=function(c){n[i++]=c};for(var o=1;o<=t;++o)if(e[o]==r&&o!=t)++s;else{if(!r&&s>2){for(;s>138;s-=138)a(32754);if(s>2)a(s>10?s-11<<5|28690:s-3<<5|12305),s=0}else if(s>3){a(r),--s;for(;s>6;s-=6)a(8304);if(s>2)a(s-3<<5|8208),s=0}while(s--)a(r);s=1,r=e[o]}return{c:n.subarray(0,i),n:t}},yc=function(e,t){var n=0;for(var i=0;i<t.length;++i)n+=e[i]*t[i];return n},Av=function(e,t,n){var i=n.length,r=Hh(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},gv=function(e,t,n,i,r,s,a,o,c,l,u){Cr(t,u++,n),++r[256];var d=kh(r,15),{t:f,l:h}=d,b=kh(s,15),{t:m,l:g}=b,p=mv(f),{c:x,n:_}=p,y=mv(m),{c:v,n:T}=y,A=new ii(19);for(var E=0;E<x.length;++E)++A[x[E]&31];for(var E=0;E<v.length;++E)++A[v[E]&31];var w=kh(A,7),{t:P,l:S}=w,I=19;for(;I>4&&!P[Lh[I-1]];--I);var U=l+5<<3,N=yc(r,es)+yc(s,_c)+a,F=yc(r,f)+yc(s,m)+a+14+3*I+yc(A,P)+2*A[16]+3*A[17]+7*A[18];if(c>=0&&U<=N&&U<=F)return Av(t,u,e.subarray(c,c+l));var D,O,K,B;if(Cr(t,u,1+(F<N)),u+=2,F<N){D=nr(f,h,0),O=f,K=nr(m,g,0),B=m;var X=nr(P,S,0);Cr(t,u,_-257),Cr(t,u+5,T-1),Cr(t,u+10,I-4),u+=14;for(var E=0;E<I;++E)Cr(t,u+3*E,P[Lh[E]]);u+=3*I;var q=[x,v];for(var le=0;le<2;++le){var de=q[le];for(var E=0;E<de.length;++E){var Me=de[E]&31;if(Cr(t,u,X[Me]),u+=P[Me],Me>15)Cr(t,u,de[E]>>5&127),u+=de[E]>>12}}}else D=hC,O=es,K=mC,B=_c;for(var E=0;E<o;++E){var pe=i[E];if(pe>255){var Me=pe>>18&31;if(xc(t,u,D[Me+257]),u+=O[Me+257],Me>7)Cr(t,u,pe>>23&31),u+=yu[Me];var J=pe&31;if(xc(t,u,K[J]),u+=B[J],J>3)xc(t,u,pe>>5&8191),u+=_u[J]}else xc(t,u,D[pe]),u+=O[pe]}return xc(t,u,D[256]),u+O[256]},yC=new jh([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),wv=new Zt(0),_C=function(e,t,n,i,r,s){var a=s.z||e.length,o=new Zt(i+a+5*(1+Math.ceil(a/7000))+r),c=o.subarray(i,o.length-r),l=s.l,u=(s.r||0)&7;if(t){if(u)c[0]=s.r>>3;var d=yC[t-1],f=d>>13,h=d&8191,b=(1<<n)-1,m=s.p||new ii(32768),g=s.h||new ii(b+1),p=Math.ceil(n/3),x=2*p,_=function(Oe){return(e[Oe]^e[Oe+1]<<p^e[Oe+2]<<x)&b},y=new jh(25000),v=new ii(288),T=new ii(32),A=0,E=0,w=s.i||0,P=0,S=s.w||0,I=0;for(;w+2<a;++w){var U=_(w),N=w&32767,F=g[U];if(m[N]=F,g[U]=N,S<=w){var D=a-w;if((A>7000||P>24576)&&(D>423||!l)){u=gv(e,c,0,y,v,T,E,P,I,w-I,u),P=A=E=0,I=w;for(var O=0;O<286;++O)v[O]=0;for(var O=0;O<30;++O)T[O]=0}var K=2,B=0,X=h,q=N-F&32767;if(D>2&&U==_(w-q)){var le=Math.min(f,D)-1,de=Math.min(32767,w),Me=Math.min(258,D);while(q<=de&&--X&&N!=F){if(e[w+K]==e[w+K-q]){var pe=0;for(;pe<Me&&e[w+pe]==e[w+pe-q];++pe);if(pe>K){if(K=pe,B=q,pe>le)break;var J=Math.min(q,pe-2),L=0;for(var O=0;O<J;++O){var W=w-q+O&32767,ne=m[W],ie=W-ne&32767;if(ie>L)L=ie,F=W}}}N=F,F=m[N],q+=N-F&32767}}if(B){y[P++]=268435456|Fh[K]<<18|pv[B];var ce=Fh[K]&31,_e=pv[B]&31;E+=yu[ce]+_u[_e],++v[257+ce],++T[_e],S=w+K,++A}else y[P++]=e[w],++v[e[w]]}}for(w=Math.max(w,S);w<a;++w)y[P++]=e[w],++v[e[w]];if(u=gv(e,c,l,y,v,T,E,P,I,w-I,u),!l)s.r=u&7|c[u/8|0]<<3,u-=7,s.h=g,s.p=m,s.i=w,s.w=S}else{for(var w=s.w||0;w<a+l;w+=65535){var Re=w+65535;if(Re>=a)c[u/8|0]=l,Re=a;u=Av(c,u+1,e.subarray(w,Re))}s.i=a}return vc(o,0,i+Hh(u)+r)},vC=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}(),EC=function(){var e=-1;return{p:function(t){var n=e;for(var i=0;i<t.length;++i)n=vC[n&255^t[i]]^n>>>8;e=n},d:function(){return~e}}};var TC=function(e,t,n,i,r){if(!r){if(r={l:1},t.dictionary){var s=t.dictionary.subarray(-32768),a=new Zt(s.length+e.length);a.set(s),a.set(e,s.length),e=a,r.w=s.length}}return _C(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)},Sv=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 tr=function(e,t){return e[t]|e[t+1]<<8},Ci=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Dh=function(e,t){return Ci(e,t)+Ci(e,t+4)*4294967296},Sn=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function AC(e,t){return TC(e,t||{},0,0)}function wC(e,t){return xC(e,{i:2},t&&t.out,t&&t.dictionary)}var Mv=function(e,t,n,i){for(var r in e){var s=e[r],a=t+r,o=i;if(Array.isArray(s))o=Sv(i,s[1]),s=s[0];if(s instanceof Zt)n[a]=[s,o];else n[a+="/"]=[new Zt(0),o],Mv(s,a,n,i)}},bv=typeof TextEncoder<"u"&&new TextEncoder,zh=typeof TextDecoder<"u"&&new TextDecoder,SC=0;try{zh.decode(wv,{stream:!0}),SC=1}catch(e){}var MC=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:vc(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 xv(e,t){if(t){var n=new Zt(e.length);for(var i=0;i<e.length;++i)n[i]=e.charCodeAt(i);return n}if(bv)return bv.encode(e);var r=e.length,s=new Zt(e.length+(e.length>>1)),a=0,o=function(u){s[a++]=u};for(var i=0;i<r;++i){if(a+5>s.length){var c=new Zt(a+8+(r-i<<1));c.set(s),s=c}var l=e.charCodeAt(i);if(l<128||t)o(l);else if(l<2048)o(192|l>>6),o(128|l&63);else if(l>55295&&l<57344)l=65536+(l&1047552)|e.charCodeAt(++i)&1023,o(240|l>>18),o(128|l>>12&63),o(128|l>>6&63),o(128|l&63);else o(224|l>>12),o(128|l>>6&63),o(128|l&63)}return vc(s,0,a)}function RC(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(zh)return zh.decode(e);else{var r=MC(e),{s,r:n}=r;if(n.length)zn(8);return s}}var IC=function(e,t){return t+30+tr(e,t+26)+tr(e,t+28)},CC=function(e,t,n){var i=tr(e,t+28),r=RC(e.subarray(t+46,t+46+i),!(tr(e,t+8)&2048)),s=t+46+i,a=Ci(e,t+20),o=n&&a==4294967295?NC(e,s):[a,Ci(e,t+24),Ci(e,t+42)],c=o[0],l=o[1],u=o[2];return[tr(e,t+10),c,l,r,s+tr(e,t+30)+tr(e,t+32),u]},NC=function(e,t){for(;tr(e,t)!=1;t+=4+tr(e,t+2));return[Dh(e,t+12),Dh(e,t+4),Dh(e,t+20)]},Vh=function(e){var t=0;if(e)for(var n in e){var i=e[n].length;if(i>65535)zn(9);t+=i+4}return t},yv=function(e,t,n,i,r,s,a,o){var c=i.length,l=n.extra,u=o&&o.length,d=Vh(l);if(Sn(e,t,a!=null?33639248:67324752),t+=4,a!=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 f=new Date(n.mtime==null?Date.now():n.mtime),h=f.getFullYear()-1980;if(h<0||h>119)zn(10);if(Sn(e,t,h<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,s!=-1)Sn(e,t,n.crc),Sn(e,t+4,s<0?-s-2:s),Sn(e,t+8,n.size);if(Sn(e,t+12,c),Sn(e,t+14,d),t+=16,a!=null)Sn(e,t,u),Sn(e,t+6,n.attrs),Sn(e,t+10,a),t+=14;if(e.set(i,t),t+=c,d)for(var b in l){var m=l[b],g=m.length;Sn(e,t,+b),Sn(e,t+2,g),e.set(m,t+4),t+=4+g}if(u)e.set(o,t),t+=u;return t},PC=function(e,t,n,i,r){Sn(e,t,101010256),Sn(e,t+8,n),Sn(e,t+10,n),Sn(e,t+12,i),Sn(e,t+16,r)};function Rv(e,t){if(!t)t={};var n={},i=[];Mv(e,"",n,t);var r=0,s=0;for(var a in n){var o=n[a],c=o[0],l=o[1],u=l.level==0?0:8,d=xv(a),f=d.length,h=l.comment,b=h&&xv(h),m=b&&b.length,g=Vh(l.extra);if(f>65535)zn(11);var p=u?AC(c,l):c,x=p.length,_=EC();_.p(c),i.push(Sv(l,{size:c.length,crc:_.d(),c:p,f:d,m:b,u:f!=a.length||b&&h.length!=m,o:r,compression:u})),r+=30+f+g+x,s+=76+2*(f+g)+(m||0)+x}var y=new Zt(s+22),v=r,T=s-r;for(var A=0;A<i.length;++A){var d=i[A];yv(y,d.o,d,d.f,d.u,d.c.length);var E=30+d.f.length+Vh(d.extra);y.set(d.c,d.o+E),yv(y,r,d,d.f,d.u,d.c.length,d.o,d.m),r+=16+E+(d.m?d.m.length:0)}return PC(y,r,i.length,T,v),y}function Iv(e,t){var n={},i=e.length-22;for(;Ci(e,i)!=101010256;--i)if(!i||e.length-i>65558)zn(13);var r=tr(e,i+8);if(!r)return{};var s=Ci(e,i+16),a=s==4294967295||r==65535;if(a){var o=Ci(e,i-12);if(a=Ci(e,o)==101075792,a)r=Ci(e,o+32),s=Ci(e,o+48)}var c=t&&t.filter;for(var l=0;l<r;++l){var u=CC(e,s,a),d=u[0],f=u[1],h=u[2],b=u[3],m=u[4],g=u[5],p=IC(e,g);if(s=m,!c||c({name:b,size:f,originalSize:h,compression:d}))if(!d)n[b]=vc(e,p,p+f);else if(d==8)n[b]=wC(e.subarray(p,p+f),{out:new Zt(h)});else zn(14,"unknown compression type "+d)}return n}Ja();Cu();Pu();ku();Ja();Cu();ku();Pu();Ec();var tN=(()=>{let e=gt().int().min(0).max(16777215),t=gt().int().min(1).max(ua),n=gt().min(-36000).max(36000),i=gt().min(0).max(1),r={blend:Ct(["normal","multiply","screen","overlay"]),opacity:i};return be({schemaVersion:$e(2),size:gt().int().min(Tu).max(Eu),usage:Ct(ir),name:Le().min(1).max(80).optional(),layers:at(Ri("op",[be({op:$e("solid"),color:e,...r}).strict(),be({op:$e("checker"),colorA:e,colorB:e,squares:t,...r}).strict(),be({op:$e("stripes"),colorA:e,colorB:e,count:t,angleDeg:n,...r}).strict(),be({op:$e("gradient"),from:e,to:e,angleDeg:n,...r}).strict(),be({op:$e("bricks"),brick:e,mortar:e,rows:t,cols:t,mortarWidth:i,stagger:i,...r}).strict(),be({op:$e("noise"),colorA:e,colorB:e,scale:t,octaves:gt().int().min(1).max($h),seed:gt().int().min(-2147483648).max(2147483647),...r}).strict()])).min(1).max(Au)}).strict()})();function Wv(e,t=tN){let n=(X,q)=>gt().int().min(X).max(q),i=n(0,255),r=n(-4096,4096),s=cv([r,r]),a=cv([i,i,i,i]),o=Ct(ir),c=cC(["sha256:",Le().regex(/^[a-f0-9]{64}$/)]),l=Le().min(1).max(80),u=Le().regex(/^[a-z][a-z0-9_-]{0,79}$/),d=Le().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/),f={width:n(1,4096),height:n(1,4096)},h=be({x:r,y:r,width:n(1,2048),height:n(1,2048)}).strict(),b=be({x:n(0,4096),y:n(0,4096),...f}).strict(),m=Ri("kind",[h.extend({kind:$e("rectangle")}).strict(),h.extend({kind:$e("ellipse")}).strict(),be({kind:$e("polygon"),points:at(s).min(3).max(Mu)}).strict(),be({kind:$e("line"),from:s,to:s,width:n(1,2048)}).strict()]),g=be({op:$e("paint"),shape:m,rgba:a,opacity:i}).strict(),p=be({op:$e("mask"),shape:m,alpha:i,invert:ca()}).strict(),x=be({op:$e("stamps"),shape:m,rgba:a,opacity:i,count:n(1,Ac),seed:n(0,4294967295),area:h,periodic:ca()}).strict(),_=be({op:$e("legacy-v2"),spec:e,alpha:i,opacity:i}).strict(),y=be({colors:at(n(0,16777215)).min(1).max(Ru),dither:Ct(["none","bayer4"])}).strict(),v={schemaVersion:$e(3),width:n(4,wc),height:n(4,wc),usage:o,name:l.optional(),background:a},T=be({...v,operations:at(Ri("op",[g,p,x,_.extend({spec:t})])).max(Sc),palette:y.optional()}).strict(),A=be({...v,usage:o.optional(),background:a.optional(),operations:at(Ri("op",[g.partial({opacity:!0}),p.partial({alpha:!0,invert:!0}),x.partial({opacity:!0,periodic:!0}),_.partial({alpha:!0,opacity:!0})])).max(Sc),palette:y.partial({dither:!0}).optional()}).strict(),E=be({minFilter:Ct(Xh),magFilter:Ct(qh),wrapS:Ct(Mc),wrapT:Ct(Mc)}).strict(),w=be({resourceId:u,revisionId:c,sha256:c}).strict(),P=be({kind:$e("resource"),resourceId:d,pin:w,expected:be({...f,imageSha256:c,decodedPixelHash:c}).partial().strict().optional()}).strict(),S=be({name:u,content:b,gutter:n(0,32),edgeMode:Ct(["copy-edge","mask-rgb-dilate"]),source:Ri("kind",[be({kind:$e("procedural"),spec:T}).strict(),P]),crop:b.optional(),packed:$e(!0).optional()}).strict(),I={schemaVersion:$e(1),width:n(4,Nr.edge),height:n(4,Nr.edge),usage:o,sampler:E},U=Wa(Zh.map((X)=>$e(X))),N=be({...I,regions:at(S).min(1).max(Nr.regions),pack:be({edge:U,gutter:n(0,32),algorithm:$e("maxrects")}).strict().optional()}).strict(),F=be({...I,width:I.width.optional(),height:I.height.optional(),pack:be({edge:U,gutter:n(0,32).optional(),algorithm:$e("maxrects").optional()}).strict().optional(),sampler:E.optional(),regions:at(S.extend({source:Ri("kind",[be({kind:$e("procedural"),spec:A}).strict(),P])}).partial({content:!0,gutter:!0,edgeMode:!0})).min(1).max(Nr.regions)}).strict(),D=be({materialId:u,revisionId:c,resourceId:d,slot:Ct(["baseColor","normal","metallicRoughness","emissive","occlusion"]),usage:o,colorSpace:Ct(["srgb","linear"]),...f,encodedByteLength:n(1,da.encodedSourceBytes),imageSha256:c,decodedPixelHash:c.optional()}).strict(),O={id:Le().min(1).max(1024),...f,decodedPixelHash:c},K=Ri("kind",[be({...O,kind:$e("procedural"),recipeHash:c,compilerId:$e(Za)}).strict(),be({...O,kind:$e("resource"),descriptor:D}).strict()]),B=be({version:$e("kiln.atlas-manifest.v1"),compilerId:Ct(Ou),width:I.width,height:I.height,usage:o,origin:$e("top-left"),sampler:E,specHash:c,layoutHash:c,decodedPixelHash:c,atlasPixelHash:c,sources:at(K).min(1).max(Nr.sources),regions:at(be({name:u,content:b,allocation:b,crop:b,sourceId:Le().min(1).max(1024)}).strict()).min(1).max(Nr.regions),manifestHash:c}).strict();return{portableSamplerSchema:E,proceduralTextureSpecV3Schema:A,canonicalProceduralTextureSpecV3Schema:T,textureAtlasSpecV1Schema:F,canonicalTextureAtlasSpecV1Schema:N,textureAtlasManifestV1Schema:B,materialMapPinSchema:w,verifiedPinnedMaterialMapDescriptorSchema:D}}var Nn=Object.freeze({maxMapBytes:8388608,maxRecordBytes:33554432,maxManifestBytes:262144,maxMapEdge:4096,maxRecordPixels:8388608,maxPayloadBytes:16777216,maxPayloadPixels:16777216,maxPayloadRecords:16}),qv=["baseColor","normal","metallicRoughness","emissive","occlusion"],Jv={baseColor:"albedo",normal:"normal",metallicRoughness:"metallicRoughness",emissive:"emissive",occlusion:"occlusion"};var eo=Le().regex(/^[a-z][a-z0-9_-]{0,79}$/),ar=Le().regex(/^sha256:[a-f0-9]{64}$/),sr=Le().min(1).max(1000),Xv=Le().max(2000).url().refine((e)=>/^https?:\/\//.test(e),"Provenance URL must be HTTP(S)"),Zv=be({id:eo,kind:Ct(["external","procedural"]),provider:sr,creator:sr,assetId:sr.optional(),assetUrl:Xv.optional(),accessedAt:Le().datetime().optional(),license:be({spdx:sr,url:Xv,attribution:Le().max(4000)}).strict(),originalFiles:at(be({name:Le().min(1).max(200),sha256:ar,bytes:gt().int().positive().max(1073741824)}).strict()).max(20)}).strict().superRefine((e,t)=>{if(e.kind==="external"&&(!e.assetUrl||!e.originalFiles.length))t.addIssue({code:"custom",message:"External materials require a source URL and original file hashes"});if(new Set(e.originalFiles.map((n)=>n.name)).size!==e.originalFiles.length)t.addIssue({code:"custom",message:"Duplicate original filename"})}),Yv=be({operation:sr,tool:sr,version:sr,parameters:gu(Le().max(100),Wa([Le().max(2000),gt().finite(),ca()])).optional()}).strict(),Pi=gt().int().min(0).max(16777215),Ic=gt().int().min(1).max(256),Qa={blend:Ct(["normal","multiply","screen","overlay"]).default("normal"),opacity:gt().min(0).max(1).default(1)},Pc=be({schemaVersion:$e(2),size:gt().int().min(4).max(1024).default(256),usage:Ct(["albedo","normal","roughness","metalness","metallicRoughness","emissive","occlusion"]).default("albedo"),name:Le().min(1).max(80).optional(),layers:at(Ri("op",[be({op:$e("solid"),color:Pi,...Qa}).strict(),be({op:$e("checker"),colorA:Pi,colorB:Pi,squares:Ic.default(8),...Qa}).strict(),be({op:$e("stripes"),colorA:Pi,colorB:Pi,count:Ic.default(8),angleDeg:gt().min(-36000).max(36000).default(0),...Qa}).strict(),be({op:$e("gradient"),from:Pi,to:Pi,angleDeg:gt().min(-36000).max(36000).default(0),...Qa}).strict(),be({op:$e("bricks"),brick:Pi,mortar:Pi,rows:Ic.default(8),cols:Ic.default(4),mortarWidth:gt().min(0).max(1).default(0.06),stagger:gt().min(0).max(1).default(0.5),...Qa}).strict(),be({op:$e("noise"),colorA:Pi,colorB:Pi,scale:Ic.default(8),octaves:gt().int().min(1).max(6).default(3),seed:gt().int().min(-2147483648).max(2147483647).default(0),...Qa}).strict()])).min(1).max(8)}).strict(),tp=be({kind:$e("normal-from-height"),strength:gt().finite().positive().max(64)}).strict(),nN=be({compiler:$e("kiln.procedural-texture.v2"),spec:Pc,derive:tp.optional(),recipeHash:ar,pixelHash:ar,encoder:be({name:$e("sharp"),version:sr}).strict()}).strict(),Qv=be({baseColor:gt().int().min(0).max(16777215).optional(),roughness:gt().min(0).max(1).default(1),metalness:gt().min(0).max(1).default(0),emissive:gt().int().min(0).max(16777215).optional(),emissiveIntensity:gt().min(0).max(64).default(1),alphaMode:Ct(["opaque","mask","blend"]).default("opaque"),alphaCutoff:gt().min(0).max(1).default(0.5),doubleSided:ca().default(!1)}).strict(),Cc=be({schemaVersion:$e(1),materialId:eo,revisionId:ar,name:Le().min(1).max(200),tags:at(Le().min(1).max(80)).max(30),tileable:ca(),physicalSizeMeters:be({width:gt().finite().positive().max(1e5),height:gt().finite().positive().max(1e5)}).strict().optional(),parameters:Qv,sources:at(Zv).min(1).max(20),maps:at(be({slot:Ct(qv),file:Ct(["baseColor.png","normal.png","metallicRoughness.png","emissive.png","occlusion.png"]),sha256:ar,bytes:gt().int().positive().max(Nn.maxMapBytes),width:gt().int().positive().max(Nn.maxMapEdge),height:gt().int().positive().max(Nn.maxMapEdge),usage:Ct(["albedo","normal","metallicRoughness","emissive","occlusion"]),colorSpace:Ct(["srgb","linear"]),normalConvention:$e("opengl").optional(),channelPacking:$e("r-occlusion-g-roughness-b-metallic").optional(),sourceId:eo,originalFile:Le().min(1).max(200).optional(),transforms:at(Yv).max(30),procedural:nN.optional()}).strict()).min(1).max(5)}).strict(),Qh=be({materialId:eo,name:Le().min(1).max(200),tags:at(Le().min(1).max(80)).max(30).optional(),tileable:ca(),physicalSizeMeters:be({width:gt().finite().positive().max(1e5),height:gt().finite().positive().max(1e5)}).strict().optional(),parameters:Qv.partial().optional(),sources:at(Zv).min(1).max(20),maps:at(be({slot:Ct(qv),sourceId:eo,transforms:at(Yv).max(30),normalConvention:$e("opengl").optional(),channelPacking:$e("r-occlusion-g-roughness-b-metallic").optional(),procedural:Pc,derive:tp.optional()}).strict()).min(1).max(5)}).strict(),ep=be({schemaVersion:$e(1),records:at(be({manifest:Cc,files:gu(Le().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/),Le().max(Math.ceil(Nn.maxMapBytes/3)*4))}).strict()).max(Nn.maxPayloadRecords)}).strict();function io(e,t=!1,n=0){if(n>30)throw Error("Material JSON exceeds nesting limit");if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number"&&Number.isFinite(e))return;if(t&&e instanceof Uint8Array)return;if(!e||typeof e!=="object")throw Error("Material values must be plain JSON data");let i=Array.isArray(e),r=Object.getPrototypeOf(e);if(i?r!==Array.prototype:r!==Object.prototype&&r!==null)throw Error("Material values must have plain JSON prototypes");if(i&&e.length>1e4)throw Error("Material JSON array exceeds limit");for(let s of Reflect.ownKeys(e)){if(i&&s==="length")continue;if(typeof s!=="string"||["__proto__","prototype","constructor"].includes(s))throw Error("Material JSON contains a forbidden key");if(i&&(!/^(0|[1-9][0-9]*)$/.test(s)||Number(s)>=e.length))throw Error("Material arrays must contain only indexed data");let a=Object.getOwnPropertyDescriptor(e,s);if(!("value"in a)||!a.enumerable)throw Error("Material JSON accessors or hidden fields are not allowed");io(a.value,t,n+1)}if(i&&Object.keys(e).length!==e.length)throw Error("Material JSON arrays must be dense")}function Cn(e){io(e);let t=(n)=>Array.isArray(n)?n.map(t):n!==null&&typeof n==="object"?Object.fromEntries(Object.entries(n).sort(([i],[r])=>i<r?-1:i>r?1:0).map(([i,r])=>[i,t(r)])):n;return JSON.stringify(t(e))}function iN(e){if(io(e),new TextEncoder().encode(JSON.stringify(e)).length>Nn.maxManifestBytes)throw Error("Material manifest exceeds size limit");let t=Cc.parse(e);if(new Set(t.sources.map((r)=>r.id)).size!==t.sources.length)throw Error("Duplicate material source identity");if(new Set(t.maps.map((r)=>r.slot)).size!==t.maps.length)throw Error("Duplicate material map slot");let n=0,i=0;for(let r of t.maps){let s=r.slot==="baseColor"||r.slot==="emissive";if(r.file!==`${r.slot}.png`||r.usage!==Jv[r.slot]||r.colorSpace!==(s?"srgb":"linear"))throw Error("Material map filename, usage or color convention mismatch");if(r.slot==="normal"!==(r.normalConvention==="opengl")||r.slot==="metallicRoughness"!==(r.channelPacking==="r-occlusion-g-roughness-b-metallic"))throw Error("Material map convention is missing or invalid");let a=t.sources.find((o)=>o.id===r.sourceId);if(!a)throw Error("Material map source is missing");if(r.procedural){if(r.procedural.derive&&r.slot!=="normal")throw Error("Height derivation requires a normal map slot");if(Cn(r.procedural.spec)!==Cn(Tc(r.procedural.spec)))throw Error("Stored procedural material recipe must be canonical");if(a.kind!=="procedural"||r.originalFile||r.procedural.spec.usage!==r.usage||r.procedural.spec.size!==r.width||r.width!==r.height)throw Error("Procedural material source or map convention mismatch")}else if(a.kind!=="external"||!a.originalFiles.some((o)=>o.name===r.originalFile))throw Error("Material map must reference an original source file");n+=r.bytes,i+=r.width*r.height}if(n>Nn.maxRecordBytes||i>Nn.maxRecordPixels)throw Error("Material record exceeds byte or pixel budget");return t}var to=Wv(Pc),no={when:(e)=>!e.issues.length},eE=(e)=>e instanceof Error?e.message:String(e);function Nc(e,t,n){return(i,r)=>{try{let s=t(i);if(n&&Cn(i)!==Cn(s))r.addIssue({code:"custom",message:`${e} must be stored in canonical form.`})}catch(s){r.addIssue({code:"custom",message:eE(s)})}}}var tE=to.portableSamplerSchema.superRefine(Nc("sampler",Nu,!0),no),rN=to.canonicalProceduralTextureSpecV3Schema.superRefine(Nc("procedural V3 spec",Kh,!0),no),sN=to.canonicalTextureAtlasSpecV1Schema.superRefine(Nc("atlas spec",fa,!0),no),aN=to.textureAtlasManifestV1Schema,oN=be({resourceId:eo,revisionId:ar,sha256:ar}).strict().refine((e)=>e.sha256===e.revisionId,"Material pin hash must match revision"),cN=Ri("kind",[be({kind:$e("procedural"),compilerId:Ct(["kiln.procedural-texture.v2",Za]),spec:Wa([Pc,rN]),recipeHash:ar,pixelHash:ar,encoder:be({name:$e("sharp"),version:sr}).strict(),derive:tp.optional()}).strict(),be({kind:$e("atlas"),compilerId:Ct(Ou),spec:sN,manifest:aN,encoder:be({name:$e("sharp"),version:sr}).strict()}).strict().superRefine((e,t)=>{try{if(Rc(e.manifest,e.spec),e.compilerId!==e.manifest.compilerId)throw Error(`recipe compilerId ${e.compilerId} does not match the manifest's ${e.manifest.compilerId}.`)}catch(n){t.addIssue({code:"custom",message:`stored atlas manifest: ${eE(n)}`})}},no)]),nE=Cc.omit({schemaVersion:!0,maps:!0}).extend({schemaVersion:$e(2),dependencies:at(oN).max(16),maps:at(Cc.shape.maps.element.omit({procedural:!0}).extend({sampler:tE,pixelHash:ar,recipe:cN.optional()}).strict()).min(1).max(5)}).strict(),lN=Ri("schemaVersion",[Cc,nE]),uN=ep.extend({schemaVersion:$e(2),records:at(ep.shape.records.element.extend({manifest:lN}).strict()).max(Nn.maxPayloadRecords)}).strict(),iE=Ri("schemaVersion",[ep,uN]);function rE(e){return e.schemaVersion===1?[]:e.dependencies.map((t)=>({...t}))}var dN=Qh.extend({schemaVersion:$e(2),maps:at(Qh.shape.maps.element.omit({procedural:!0}).extend({sampler:tE,procedural:Wa([Pc,to.proceduralTextureSpecV3Schema.superRefine(Nc("procedural V3 spec",Kh,!1),no)]).optional(),atlas:to.textureAtlasSpecV1Schema.superRefine(Nc("atlas spec",fa,!1),no).optional()}).strict().refine((e)=>e.procedural!==void 0!==(e.atlas!==void 0),"Supply exactly one procedural or atlas recipe")).min(1).max(5)}).strict(),Sj=Wa([Qh,dN]);function ro(e){if(io(e),new TextEncoder().encode(JSON.stringify(e)).length>Nn.maxManifestBytes)throw Error("Material manifest exceeds size limit");if(!e||typeof e!=="object"||Array.isArray(e))throw Error("Invalid material manifest");if(e.schemaVersion===1)return iN(e);let t=nE.parse(e);if(new Set(t.sources.map((a)=>a.id)).size!==t.sources.length||new Set(t.maps.map((a)=>a.slot)).size!==t.maps.length)throw Error("Duplicate material source or slot");let n=0,i=0,r=new Map;for(let a of t.maps){let o=t.sources.find((l)=>l.id===a.sourceId);if(!o||a.file!==`${a.slot}.png`||a.usage!==Jv[a.slot]||a.colorSpace!==(a.slot==="baseColor"||a.slot==="emissive"?"srgb":"linear")||a.slot==="normal"!==(a.normalConvention==="opengl")||a.slot==="metallicRoughness"!==(a.channelPacking==="r-occlusion-g-roughness-b-metallic"))throw Error("Material map source/usage/convention mismatch");let c=a.recipe;if(c){if(o.kind!=="procedural"||a.originalFile)throw Error("Procedural/atlas map source convention mismatch");if(c.kind==="procedural"){let l=c.spec;if(l.schemaVersion===3){if(c.compilerId!==Za||l.width!==a.width||l.height!==a.height)throw Error("V3 compiler/dimensions mismatch")}else if(c.compilerId!=="kiln.procedural-texture.v2"||l.size!==a.width||a.width!==a.height||Cn(l)!==Cn(Tc(l)))throw Error("V2 compiler/canonical recipe dimensions mismatch");if(l.usage!==a.usage||c.pixelHash!==a.pixelHash||c.derive&&a.slot!=="normal")throw Error("Procedural recipe pixel/usage mismatch")}else{if(Rc(c.manifest,c.spec),c.spec.width!==a.width||c.spec.height!==a.height||c.spec.usage!==a.usage||Cn(c.spec.sampler)!==Cn(a.sampler)||c.manifest.decodedPixelHash!==a.pixelHash)throw Error("Atlas recipe map mismatch");for(let l of c.spec.regions)if(l.source.kind==="resource"){let u=l.source.pin;r.set(`${u.resourceId}/${u.revisionId}`,u)}}}else if(o.kind!=="external"||!o.originalFiles.some((l)=>l.name===a.originalFile))throw Error("External material source original file missing");n+=a.bytes,i+=a.width*a.height}let s=t.dependencies.map((a)=>`${a.resourceId}/${a.revisionId}`);if(new Set(s).size!==s.length||s.length!==r.size||s.some((a)=>!r.has(a)))throw Error("Material dependency pin inventory mismatch");if(n>Nn.maxRecordBytes||i>Nn.maxRecordPixels)throw Error("Material record exceeds byte/pixel budget");return structuredClone(t)}var Kn=67108864,np=Le().regex(/^[a-z][a-z0-9_-]{0,79}$/),fN=Le().regex(/^sha256:[a-f0-9]{64}$/),sE=be({version:$e("kiln.asset.v1"),assetId:np,revisionId:np,parentRevision:np.optional(),name:Le().min(1).max(200),tags:at(Le().max(80)).max(30),createdAt:Le().datetime(),description:Le().max(4000).optional(),brief:Le().max(8000).optional(),attribution:be({model:Le().max(200).optional(),harness:Le().max(200).optional(),author:Le().max(200).optional()}).optional(),editable:ca(),files:gu(Le(),be({sha256:fN,bytes:gt().int().nonnegative().max(Kn)})),build:be({engine:Le(),options:gu(Le(),oa()),warnings:at(Le()),integration:oa().optional(),qa:oa().optional(),dependencies:at(oa()).optional(),rebuild:Ct(["engine-required","external-dependencies-required"])}).optional(),preview:be({fidelity:oa().optional(),error:Le().optional(),backdrop:Ct(fv).optional()}).optional()}),Oc="materials.kiln.json",aE=25165824;function kc(e){let t=new Map;for(let n of e.manifest.build?.dependencies??[]){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Invalid saved asset dependency");let i=n;if(i.kind!=="kiln.material.v1"&&i.kind!=="kiln.material.v2"){if(i.delivery==="runtime")throw Error("Unsupported runtime dependency");if(i.delivery!=="embedded")throw Error("Unsupported saved asset dependency");continue}if(i.delivery!=="runtime")throw Error("Invalid saved material dependency");let r=ro(i.manifest);if(i.kind!==`kiln.material.v${r.schemaVersion}`)throw Error("Saved material dependency kind/version mismatch");let s=`${r.materialId}/${r.revisionId}`,a=t.get(s);if(a&&Cn(a)!==Cn(r))throw Error("Conflicting saved material dependency manifests");if(t.set(s,r),t.size>Nn.maxPayloadRecords)throw Error("Saved asset material dependency count exceeds limit")}return[...t.values()]}function oE(e,t=!1){let n=kc(e),i=new Map(n.map((d)=>[`${d.materialId}/${d.revisionId}`,Cn(d)]));if(!e.materialResources){if(t&&i.size)throw Error("Editable asset material closure unavailable");return}io(e.materialResources);let r=iE.parse(e.materialResources),s=0,a=0,o=new Map;for(let d of r.records){let f=ro(d.manifest),h=`${d.manifest.materialId}/${d.manifest.revisionId}`;if(o.has(h)||i.has(h)&&i.get(h)!==Cn(f))throw Error("Asset material closure mismatch");if(o.set(h,f),Object.keys(d.files).length!==d.manifest.maps.length)throw Error("Asset material map inventory mismatch");for(let b of d.manifest.maps){if(d.files[b.file]?.length!==Math.ceil(b.bytes/3)*4)throw Error("Asset material map size mismatch");s+=b.bytes,a+=b.width*b.height}}if(s>Nn.maxPayloadBytes||a>Nn.maxPayloadPixels)throw Error("Asset material closure exceeds allocation limits");let c=new Set,l=new Set,u=(d)=>{if(l.has(d))throw Error("Asset material closure contains a cycle");if(c.has(d))return;let f=o.get(d);if(!f)throw Error("Asset material closure incomplete");l.add(d);for(let h of rE(f))u(`${h.resourceId}/${h.revisionId}`);l.delete(d),c.add(d)};for(let d of i.keys())u(d);if(c.size!==o.size)throw Error("Asset material closure has unrelated records")}var hN=new Set(["asset.glb","source.kiln.js","preview.png"]);function Du(e){let t=sE.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(!hN.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>Kn||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");ip(e.files["asset.glb"]),oE(e)}function ip(e){if(e.length<20||e.length>Kn)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 rp(e){if(!e.length||e.length>100)throw Error("Bundle requires 1..100 revisions");let t={},n=0;for(let i of e){Du(i),oE(i,!0);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,a]of Object.entries(i.files))t[r+s]=a;if(i.materialResources){let s=new TextEncoder().encode(JSON.stringify(i.materialResources));if(s.length>aE)throw Error("Asset material payload exceeds byte limit");t[r+Oc]=s}}for(let i of Object.values(t))n+=i.length;if(n>Kn)throw Error("Bundle exceeds 64 MiB");return Rv(t,{level:0})}function cE(e){if(e.length>Kn+1048576)throw Error("Bundle exceeds 64 MiB");let t=0,n=0,i=Iv(e,{filter:(a)=>{if(t+=a.originalSize,n++,t>Kn||n>500||a.name.endsWith(`/${Oc}`)&&a.originalSize>aE||!/^[a-z][a-z0-9_-]{0,79}\/[a-z][a-z0-9_-]{0,79}\/(manifest\.json|asset\.glb|source\.kiln\.js|preview\.png|materials\.kiln\.json)$/.test(a.name))throw Error("Unsafe or oversized asset bundle");return!0}}),r=[],s=new Set;for(let[a,o]of Object.entries(i)){if(!a.endsWith("/manifest.json"))continue;if(o.length>1048576)throw Error("Manifest exceeds 1 MiB");let c=sE.parse(JSON.parse(new TextDecoder().decode(o))),l=`${c.assetId}/${c.revisionId}/`;if(a!==`${l}manifest.json`)throw Error("Bundle identity mismatch");let u={manifest:c,files:{}};s.add(a);for(let d of Object.keys(c.files)){if(!i[l+d])throw Error("Bundle file missing");u.files[d]=i[l+d],s.add(l+d)}if(i[l+Oc])u.materialResources=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i[l+Oc])),s.add(l+Oc);Du(u),r.push(u)}if(!r.length||s.size!==Object.keys(i).length)throw Error("Incomplete asset bundle");return r}function lE(e){let t=e.attribution;if(!t)return[];return[t.model?{label:"Model",value:t.model}:null,t.harness?{label:"Harness",value:t.harness}:null,t.author?{label:"Author",value:t.author}:null].filter((n)=>n!==null)}ji();ji();var DA={type:"change"},ug={type:"start"},FA={type:"end"},$d=new ms,LA=new yi,o8=Math.cos(70*Yc.DEG2RAD),gn=new j,qn=2*Math.PI,Ot={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},lg=0.000001;class dg extends zd{constructor(e,t=null){super(e,t);if(this.state=Ot.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:us.ROTATE,MIDDLE:us.DOLLY,RIGHT:us.PAN},this.touches={ONE:ds.ROTATE,TWO:ds.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 ln,this._lastTargetPosition=new j,this._quat=new ln().setFromUnitVectors(e.up,new j(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new fl,this._sphericalDelta=new fl,this._scale=1,this._panOffset=new j,this._rotateStart=new Ke,this._rotateEnd=new Ke,this._rotateDelta=new Ke,this._panStart=new Ke,this._panEnd=new Ke,this._panDelta=new Ke,this._dollyStart=new Ke,this._dollyEnd=new Ke,this._dollyDelta=new Ke,this._dollyDirection=new j,this._mouse=new Ke,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=l8.bind(this),this._onPointerDown=c8.bind(this),this._onPointerUp=u8.bind(this),this._onContextMenu=b8.bind(this),this._onMouseWheel=h8.bind(this),this._onKeyDown=p8.bind(this),this._onTouchStart=m8.bind(this),this._onTouchMove=g8.bind(this),this._onMouseDown=d8.bind(this),this._onMouseMove=f8.bind(this),this._interceptControlDown=x8.bind(this),this._interceptControlUp=y8.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.state=Ot.NONE,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();let e=this.domElement.getRootNode();e.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),e.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(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(DA),this.update(),this.state=Ot.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(gn.copy(t).sub(this.target),gn.applyQuaternion(this._quat),this._spherical.setFromVector3(gn),this.autoRotate&&this.state===Ot.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+=qn;else if(n>Math.PI)n-=qn;if(i<-Math.PI)i+=qn;else if(i>Math.PI)i-=qn;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(gn.setFromSpherical(this._spherical),gn.applyQuaternion(this._quatInverse),t.copy(this.target).add(gn),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 a=gn.length();s=this._clampDistance(a*this._scale);let o=a-s;this.object.position.addScaledVector(this._dollyDirection,o),this.object.updateMatrixWorld(),r=!!o}else if(this.object.isOrthographicCamera){let a=new j(this._mouse.x,this._mouse.y,0);a.unproject(this.object);let o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=o!==this.object.zoom;let c=new j(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(a),this.object.updateMatrixWorld(),s=gn.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($d.origin.copy(this.object.position),$d.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot($d.direction))<o8)this.object.lookAt(this.target);else LA.setFromNormalAndCoplanarPoint(this.object.up,this.target),$d.intersectPlane(LA,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)>lg||8*(1-this._lastQuaternion.dot(this.object.quaternion))>lg||this._lastTargetPosition.distanceToSquared(this.target)>lg)return this.dispatchEvent(DA),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 qn/60*this.autoRotateSpeed*e;else return qn/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){gn.setFromMatrixColumn(t,0),gn.multiplyScalar(-e),this._panOffset.add(gn)}_panUp(e,t){if(this.screenSpacePanning===!0)gn.setFromMatrixColumn(t,1);else gn.setFromMatrixColumn(t,0),gn.crossVectors(this.object.up,gn);gn.multiplyScalar(e),this._panOffset.add(gn)}_pan(e,t){let n=this.domElement;if(this.object.isPerspectiveCamera){let i=this.object.position;gn.copy(i).sub(this.target);let r=gn.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:a}=n;this._mouse.x=i/s*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(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(qn*this._rotateDelta.x/t.clientHeight),this._rotateUp(qn*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(qn*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(-qn*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(qn*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(-qn*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(qn*this._rotateDelta.x/t.clientHeight),this._rotateUp(qn*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,a=(e.pageY+t.y)*0.5;this._updateZoomParameters(s,a)}_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 Ke,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 c8(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 l8(e){if(this.enabled===!1)return;if(e.pointerType==="touch")this._onTouchMove(e);else this._onMouseMove(e)}function u8(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(FA),this.state=Ot.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 d8(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 us.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(e),this.state=Ot.DOLLY;break;case us.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=Ot.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=Ot.ROTATE}break;case us.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=Ot.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=Ot.PAN}break;default:this.state=Ot.NONE}if(this.state!==Ot.NONE)this.dispatchEvent(ug)}function f8(e){switch(this.state){case Ot.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(e);break;case Ot.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(e);break;case Ot.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(e);break}}function h8(e){if(this.enabled===!1||this.enableZoom===!1||this.state!==Ot.NONE)return;e.preventDefault(),this.dispatchEvent(ug),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(FA)}function p8(e){if(this.enabled===!1)return;this._handleKeyDown(e)}function m8(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case ds.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(e),this.state=Ot.TOUCH_ROTATE;break;case ds.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(e),this.state=Ot.TOUCH_PAN;break;default:this.state=Ot.NONE}break;case 2:switch(this.touches.TWO){case ds.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(e),this.state=Ot.TOUCH_DOLLY_PAN;break;case ds.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(e),this.state=Ot.TOUCH_DOLLY_ROTATE;break;default:this.state=Ot.NONE}break;default:this.state=Ot.NONE}if(this.state!==Ot.NONE)this.dispatchEvent(ug)}function g8(e){switch(this._trackPointer(e),this.state){case Ot.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(e),this.update();break;case Ot.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(e),this.update();break;case Ot.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(e),this.update();break;case Ot.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=Ot.NONE}}function b8(e){if(this.enabled===!1)return;e.preventDefault()}function x8(e){if(e.key==="Control")this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}function y8(e){if(e.key==="Control")this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}ji();class fg extends Po{constructor(){super();this.name="RoomEnvironment",this.position.y=-3.5;let e=new bs;e.deleteAttribute("uv");let t=new zr({side:kn}),n=new zr,i=new Uo(16777215,900,28,2);i.position.set(0.418,16.199,0.3),this.add(i);let r=new jt(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 ko(e,n,6),a=new Dt;a.position.set(-10.906,2.009,1.846),a.rotation.set(0,-0.195,0),a.scale.set(2.328,7.905,4.651),a.updateMatrix(),s.setMatrixAt(0,a.matrix),a.position.set(-5.607,-0.754,-0.758),a.rotation.set(0,0.994,0),a.scale.set(1.97,1.534,3.955),a.updateMatrix(),s.setMatrixAt(1,a.matrix),a.position.set(6.167,0.857,7.803),a.rotation.set(0,0.561,0),a.scale.set(3.927,6.285,3.687),a.updateMatrix(),s.setMatrixAt(2,a.matrix),a.position.set(-2.017,0.018,6.124),a.rotation.set(0,0.333,0),a.scale.set(2.002,4.566,2.064),a.updateMatrix(),s.setMatrixAt(3,a.matrix),a.position.set(2.291,-0.756,-2.621),a.rotation.set(0,-0.286,0),a.scale.set(1.546,1.552,1.496),a.updateMatrix(),s.setMatrixAt(4,a.matrix),a.position.set(-2.193,-0.369,-5.547),a.rotation.set(0,0.516,0),a.scale.set(3.875,3.487,2.986),a.updateMatrix(),s.setMatrixAt(5,a.matrix),this.add(s);let o=new jt(e,Ho(50));o.position.set(-16.116,14.37,8.208),o.scale.set(0.1,2.428,2.739),this.add(o);let c=new jt(e,Ho(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 jt(e,Ho(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 jt(e,Ho(43));u.position.set(-0.462,8.89,14.52),u.scale.set(4.38,5.441,0.088),this.add(u);let d=new jt(e,Ho(20));d.position.set(3.235,11.486,-12.541),d.scale.set(2.5,2,0.1),this.add(d);let f=new jt(e,Ho(100));f.position.set(0,20,0),f.scale.set(1,0.1,1),this.add(f)}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 Ho(e){return new Pd({color:0,emissive:16777215,emissiveIntensity:e})}ji();ji();ji();function hg(e,t){if(t===Am)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(t===No||t===Zc){let n=e.getIndex();if(n===null){let s=[],a=e.getAttribute("position");if(a!==void 0){for(let o=0;o<a.count;o++)s.push(o);e.setIndex(s),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===No)for(let s=1;s<=i;s++)r.push(n.getX(0)),r.push(n.getX(s)),r.push(n.getX(s+1));else for(let s=0;s<i;s++)if(s%2===0)r.push(n.getX(s)),r.push(n.getX(s+1)),r.push(n.getX(s+2));else r.push(n.getX(s+2)),r.push(n.getX(s+1)),r.push(n.getX(s));if(r.length/3!==i)console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");return e.setIndex(r),e.clearGroups(),e}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}function UA(e){let t=new Map,n=new Map,i=e.clone();return BA(e,i,function(r,s){t.set(s,r),n.set(r,s)}),i.traverse(function(r){if(!r.isSkinnedMesh)return;let s=r,a=t.get(r),o=a.skeleton.bones;s.skeleton=a.skeleton.clone(),s.bindMatrix.copy(a.bindMatrix),s.skeleton.bones=o.map(function(c){return n.get(c)}),s.bind(s.skeleton,s.bindMatrix)}),i}function BA(e,t,n){n(e,t);for(let i=0;i<e.children.length;i++)BA(e.children[i],t.children[i],n)}class _g extends jr{constructor(e){super(e);this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new WA(t)}),this.register(function(t){return new XA(t)}),this.register(function(t){return new iw(t)}),this.register(function(t){return new rw(t)}),this.register(function(t){return new sw(t)}),this.register(function(t){return new JA(t)}),this.register(function(t){return new ZA(t)}),this.register(function(t){return new YA(t)}),this.register(function(t){return new QA(t)}),this.register(function(t){return new KA(t)}),this.register(function(t){return new ew(t)}),this.register(function(t){return new qA(t)}),this.register(function(t){return new nw(t)}),this.register(function(t){return new tw(t)}),this.register(function(t){return new GA(t)}),this.register(function(t){return new bg(t,ut.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new bg(t,ut.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new aw(t)})}load(e,t,n,i){let r=this,s;if(this.resourcePath!=="")s=this.resourcePath;else if(this.path!==""){let c=Es.extractUrlBase(e);s=Es.resolveURL(c,this.path)}else s=Es.extractUrlBase(e);this.manager.itemStart(e);let a=function(c){if(i)i(c);else console.error(c);r.manager.itemError(e),r.manager.itemEnd(e)},o=new ul(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(c){try{r.parse(c,s,function(l){t(l),r.manager.itemEnd(e)},a)}catch(l){a(l)}},n,a)}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={},a={},o=new TextDecoder;if(typeof e==="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(o.decode(new Uint8Array(e,0,4))===ow){try{s[ut.KHR_BINARY_GLTF]=new cw(e)}catch(u){if(i)i(u);return}r=JSON.parse(s[ut.KHR_BINARY_GLTF].content)}else r=JSON.parse(o.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 hw(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");a[u.name]=u,s[u.name]=!0}if(r.extensionsUsed)for(let l=0;l<r.extensionsUsed.length;++l){let u=r.extensionsUsed[l],d=r.extensionsRequired||[];switch(u){case ut.KHR_MATERIALS_UNLIT:s[u]=new $A;break;case ut.KHR_DRACO_MESH_COMPRESSION:s[u]=new lw(r,this.dracoLoader);break;case ut.KHR_TEXTURE_TRANSFORM:s[u]=new uw;break;case ut.KHR_MESH_QUANTIZATION:s[u]=new dw;break;default:if(d.indexOf(u)>=0&&a[u]===void 0)console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}c.setExtensions(s),c.setPlugins(a),c.parse(n,i)}parseAsync(e,t){let n=this;return new Promise(function(i,r){n.parse(e,t,i,r)})}}function _8(){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 sn(e,t,n){let i=e.json.materials[t];if(i.extensions&&i.extensions[n])return i.extensions[n];return null}var ut={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 GA{constructor(e){this.parser=e,this.name=ut.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,o=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e],c,l=new qe(16777215);if(o.color!==void 0)l.setRGB(o.color[0],o.color[1],o.color[2],oi);let u=o.range!==void 0?o.range:0;switch(o.type){case"directional":c=new Bo(l),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new Uo(l),c.distance=u;break;case"spot":c=new Fd(l),c.distance=u,o.spot=o.spot||{},o.spot.innerConeAngle=o.spot.innerConeAngle!==void 0?o.spot.innerConeAngle:0,o.spot.outerConeAngle=o.spot.outerConeAngle!==void 0?o.spot.outerConeAngle:Math.PI/4,c.angle=o.spot.outerConeAngle,c.penumbra=1-o.spot.innerConeAngle/o.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw Error("THREE.GLTFLoader: Unexpected light type: "+o.type)}if(c.position.set(0,0,0),xr(c,o),o.intensity!==void 0)c.intensity=o.intensity;return c.name=t.createUniqueName(o.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],a=(r.extensions&&r.extensions[this.name]||{}).light;if(a===void 0)return null;return this._loadLight(a).then(function(o){return n._getNodeRef(t.cache,a,o)})}}class $A{constructor(){this.name=ut.KHR_MATERIALS_UNLIT}getMaterialType(){return mr}extendParams(e,t,n){let i=[];e.color=new qe(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],oi),e.opacity=s[3]}if(r.baseColorTexture!==void 0)i.push(n.assignTexture(e,"map",r.baseColorTexture,ps))}return Promise.all(i)}}class KA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=sn(this.parser,e,this.name);if(n===null)return Promise.resolve();if(n.emissiveStrength!==void 0)t.emissiveIntensity=n.emissiveStrength;return Promise.resolve()}}class WA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(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 Ke(r,r)}}return Promise.all(i)}}class XA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_DISPERSION}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(this.parser,e,this.name);if(n===null)return Promise.resolve();return t.dispersion=n.dispersion!==void 0?n.dispersion:0,Promise.resolve()}}class qA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(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 JA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_SHEEN}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.sheenColor=new qe(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],oi)}if(n.sheenRoughnessFactor!==void 0)t.sheenRoughness=n.sheenRoughnessFactor;if(n.sheenColorTexture!==void 0)i.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,ps));if(n.sheenRoughnessTexture!==void 0)i.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture));return Promise.all(i)}}class ZA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(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 YA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_VOLUME}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(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 qe().setRGB(r[0],r[1],r[2],oi),Promise.all(i)}}class QA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_IOR}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(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 ew{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_SPECULAR}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(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 qe().setRGB(r[0],r[1],r[2],oi),n.specularColorTexture!==void 0)i.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,ps));return Promise.all(i)}}class tw{constructor(e){this.parser=e,this.name=ut.EXT_MATERIALS_BUMP}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(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 nw{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return sn(this.parser,e,this.name)!==null?ui:null}extendMaterialParams(e,t){let n=sn(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 iw{constructor(e){this.parser=e,this.name=ut.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 rw{constructor(e){this.parser=e,this.name=ut.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],a=i.images[s.source],o=n.textureLoader;if(a.uri){let c=n.options.manager.getHandler(a.uri);if(c!==null)o=c}return n.loadTextureImage(e,s.source,o)}}class sw{constructor(e){this.parser=e,this.name=ut.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],a=i.images[s.source],o=n.textureLoader;if(a.uri){let c=n.options.manager.getHandler(a.uri);if(c!==null)o=c}return n.loadTextureImage(e,s.source,o)}}class bg{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(a){let o=i.byteOffset||0,c=i.byteLength||0,{count:l,byteStride:u}=i,d=new Uint8Array(a,o,c);if(s.decodeGltfBufferAsync)return s.decodeGltfBufferAsync(l,u,d,i.mode,i.filter).then(function(f){return f.buffer});else return s.ready.then(function(){let f=new ArrayBuffer(l*u);return s.decodeGltfBuffer(new Uint8Array(f),l,u,d,i.mode,i.filter),f})})}else return null}}class aw{constructor(e){this.name=ut.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!==Ti.TRIANGLES&&c.mode!==Ti.TRIANGLE_STRIP&&c.mode!==Ti.TRIANGLE_FAN&&c.mode!==void 0)return null;let s=n.extensions[this.name].attributes,a=[],o={};for(let c in s)a.push(this.parser.getDependency("accessor",s[c]).then((l)=>(o[c]=l,o[c])));if(a.length<1)return null;return a.push(this.parser.createNodeMesh(e)),Promise.all(a).then((c)=>{let l=c.pop(),u=l.isGroup?l.children:[l],d=c[0].count,f=[];for(let h of u){let b=new Qe,m=new j,g=new ln,p=new j(1,1,1),x=new ko(h.geometry,h.material,d);for(let y=0;y<d;y++){if(o.TRANSLATION)m.fromBufferAttribute(o.TRANSLATION,y);if(o.ROTATION)g.fromBufferAttribute(o.ROTATION,y);if(o.SCALE)p.fromBufferAttribute(o.SCALE,y);x.setMatrixAt(y,b.compose(m,g,p))}let _=null;for(let y in o)if(y==="_COLOR_0"){let v=o[y];x.instanceColor=new ls(v.array,v.itemSize,v.normalized)}else if(y!=="TRANSLATION"&&y!=="ROTATION"&&y!=="SCALE"){if(_===null){let T=x.geometry;_=new Dn,_.name=T.name;for(let A in T.attributes)_.setAttribute(A,T.attributes[A]);for(let A in T.morphAttributes)_.morphAttributes[A]=T.morphAttributes[A];if(T.index!==null)_.setIndex(T.index);_.morphTargetsRelative=T.morphTargetsRelative;for(let A of T.groups)_.addGroup(A.start,A.count,A.materialIndex);if(T.boundingBox!==null)_.boundingBox=T.boundingBox.clone();if(T.boundingSphere!==null)_.boundingSphere=T.boundingSphere.clone();_.drawRange.start=T.drawRange.start,_.drawRange.count=T.drawRange.count,_.userData=Object.assign({},T.userData),x.geometry=_}let v=o[y];_.setAttribute(y,new ls(v.array,v.itemSize,v.normalized))}Dt.prototype.copy.call(x,h),this.parser.assignFinalMaterial(x),f.push(x)}if(l.isGroup)return l.clear(),l.add(...f),l;return f[0]})}}var ow="glTF",xl=12,zA={JSON:1313821514,BIN:5130562};class cw{constructor(e){this.name=ut.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,xl),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!==ow)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-xl,r=new DataView(e,xl),s=0;while(s<i){let a=r.getUint32(s,!0);s+=4;let o=r.getUint32(s,!0);if(s+=4,o===zA.JSON){let c=new Uint8Array(e,xl+s,a);this.content=n.decode(c)}else if(o===zA.BIN){let c=xl+s;this.body=e.slice(c,c+a)}s+=a}if(this.content===null)throw Error("THREE.GLTFLoader: JSON content not found.")}}class lw{constructor(e,t){if(!t)throw Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=ut.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,a={},o={},c={};for(let l in s){let u=xg[l]||l.toLowerCase();a[u]=s[l]}for(let l in e.attributes){let u=xg[l]||l.toLowerCase();if(s[l]!==void 0){let d=n.accessors[e.attributes[l]],f=Go[d.componentType];c[u]=f.name,o[u]=d.normalized===!0}}return t.getDependency("bufferView",r).then(function(l){return new Promise(function(u,d){i.decodeDracoFile(l,function(f){for(let h in f.attributes){let b=f.attributes[h],m=o[h];if(m!==void 0)b.normalized=m}u(f)},a,c,oi,d)})})}}class uw{constructor(){this.name=ut.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);if(t.rotation!==void 0){let n=Math.cos(e.rotation),i=Math.sin(e.rotation);e.matrix.set(e.repeat.x*n,e.repeat.y*i,e.offset.x,-e.repeat.x*i,e.repeat.y*n,e.offset.y,0,0,1),e.matrixAutoUpdate=!1}return e.needsUpdate=!0,e}}class dw{constructor(){this.name=ut.KHR_MESH_QUANTIZATION}}class vg extends Vr{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,a=this.valueSize,o=a*2,c=a*3,l=i-t,u=(n-t)/l,d=u*u,f=d*u,h=e*c,b=h-c,m=-2*f+3*d,g=f-d,p=1-m,x=g-d+u;for(let _=0;_!==a;_++){let y=s[b+_+a],v=s[b+_+o]*l,T=s[h+_+a],A=s[h+_]*l;r[_]=p*y+x*v+m*T+g*A}return r}}var v8=new ln;class fw extends vg{interpolate_(e,t,n,i){let r=super.interpolate_(e,t,n,i);return v8.fromArray(r).normalize().toArray(r),r}}var Ti={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},Go={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},VA={9728:Bi,9729:En,9984:hd,9985:Io,9986:_a,9987:fr},jA={33071:Ro,33648:fd,10497:Mo},pg={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},xg={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"},Ts={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},E8={CUBICSPLINE:void 0,LINEAR:_d,STEP:Tm},mg={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function T8(e){if(e.DefaultMaterial===void 0)e.DefaultMaterial=new zr({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:fs});return e.DefaultMaterial}function Ca(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 xr(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 A8(e,t,n){let i=!1,r=!1,s=!1;for(let l=0,u=t.length;l<u;l++){let d=t[l];if(d.POSITION!==void 0)i=!0;if(d.NORMAL!==void 0)r=!0;if(d.COLOR_0!==void 0)s=!0;if(i&&r&&s)break}if(!i&&!r&&!s)return Promise.resolve(e);let a=[],o=[],c=[];for(let l=0,u=t.length;l<u;l++){let d=t[l];if(i){let f=d.POSITION!==void 0?n.getDependency("accessor",d.POSITION):e.attributes.position;a.push(f)}if(r){let f=d.NORMAL!==void 0?n.getDependency("accessor",d.NORMAL):e.attributes.normal;o.push(f)}if(s){let f=d.COLOR_0!==void 0?n.getDependency("accessor",d.COLOR_0):e.attributes.color;c.push(f)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(c)]).then(function(l){let u=l[0],d=l[1],f=l[2];if(i)e.morphAttributes.position=u;if(r)e.morphAttributes.normal=d;if(s)e.morphAttributes.color=f;return e.morphTargetsRelative=!0,e})}function w8(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 S8(e){let t,n=e.extensions&&e.extensions[ut.KHR_DRACO_MESH_COMPRESSION];if(n)t="draco:"+n.bufferView+":"+n.indices+":"+gg(n.attributes);else t=e.indices+":"+gg(e.attributes)+":"+e.mode;if(e.targets!==void 0)for(let i=0,r=e.targets.length;i<r;i++)t+=":"+gg(e.targets[i]);return t}function gg(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 yg(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 M8(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 R8=new Qe;class hw{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new _8,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 a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;let o=a.match(/Version\/(\d+)/);i=n&&o?parseInt(o[1],10):-1,r=a.indexOf("Firefox")>-1,s=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}if(typeof createImageBitmap>"u"||n&&i<17||r&&s<98)this.textureLoader=new Lo(this.options.manager);else this.textureLoader=new Ud(this.options.manager);if(this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new ul(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 a={scene:s[0][i.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:i.asset,parser:n,userData:{}};return Ca(r,a,i),xr(a,i),Promise.all(n._invokeAll(function(o){return o.afterRoot&&o.afterRoot(a)})).then(function(){for(let o of a.scenes)o.updateMatrixWorld();e(a)})}).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 a=0,o=s.length;a<o;a++)e[s[a]].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,a)=>{let o=this.associations.get(s);if(o!=null)this.associations.set(a,o);for(let[c,l]of s.children.entries())r(l,a.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[ut.KHR_BINARY_GLTF].body);let i=this.options;return new Promise(function(r,s){n.load(Es.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=pg[i.type],a=Go[i.componentType],o=i.normalized===!0,c=new a(i.count*s);return Promise.resolve(new vn(c,s,o))}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 a=s[0],o=pg[i.type],c=Go[i.componentType],l=c.BYTES_PER_ELEMENT,u=l*o,d=i.byteOffset||0,f=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,h=i.normalized===!0,b,m;if(f&&f!==u){let g=Math.floor(d/f),p="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+g+":"+i.count,x=t.cache.get(p);if(!x)b=new c(a,g*f,i.count*f/l),x=new tl(b,f/l),t.cache.add(p,x);m=new Oo(x,o,d%f/l,h)}else{if(a===null)b=new c(i.count*o);else b=new c(a,d,i.count*o);m=new vn(b,o,h)}if(i.sparse!==void 0){let g=pg.SCALAR,p=Go[i.sparse.indices.componentType],x=i.sparse.indices.byteOffset||0,_=i.sparse.values.byteOffset||0,y=new p(s[1],x,i.sparse.count*g),v=new c(s[2],_,i.sparse.count*o);if(a!==null)m=new vn(m.array.slice(),m.itemSize,m.normalized);m.normalized=!1;for(let T=0,A=y.length;T<A;T++){let E=y[T];if(m.setX(E,v[T*o]),o>=2)m.setY(E,v[T*o+1]);if(o>=3)m.setZ(E,v[T*o+2]);if(o>=4)m.setW(E,v[T*o+3]);if(o>=5)throw Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=h}return m})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,s=t.images[r],a=this.textureLoader;if(s.uri){let o=n.manager.getHandler(s.uri);if(o!==null)a=o}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let i=this,r=this.json,s=r.textures[e],a=r.images[t],o=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[o])return this.textureCache[o];let c=this.loadImageSource(t,n).then(function(l){if(l.flipY=!1,l.name=s.name||a.name||"",l.name===""&&typeof a.uri==="string"&&a.uri.startsWith("data:image/")===!1)l.name=a.uri;let d=(r.samplers||{})[s.sampler]||{};return l.magFilter=VA[d.magFilter]||En,l.minFilter=VA[d.minFilter]||fr,l.wrapS=jA[d.wrapS]||Mo,l.wrapT=jA[d.wrapT]||Mo,l.generateMipmaps=!l.isCompressedTexture&&l.minFilter!==Bi&&l.minFilter!==En,i.associations.set(l,{textures:e}),l}).catch(function(){return null});return this.textureCache[o]=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],a=self.URL||self.webkitURL,o=s.uri||"",c=!1;if(s.bufferView!==void 0)o=n.getDependency("bufferView",s.bufferView).then(function(u){c=!0;let d=new Blob([u],{type:s.mimeType});return o=a.createObjectURL(d),o});else if(s.uri===void 0)throw Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let l=Promise.resolve(o).then(function(u){return new Promise(function(d,f){let h=d;if(t.isImageBitmapLoader===!0)h=function(b){let m=new en(b);m.needsUpdate=!0,d(m)};t.load(Es.resolveURL(u,r.path),h,void 0,f)})}).then(function(u){if(c===!0)a.revokeObjectURL(o);return xr(u,s),u.userData.mimeType=s.mimeType||M8(s.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",o),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[ut.KHR_TEXTURE_TRANSFORM]){let a=n.extensions!==void 0?n.extensions[ut.KHR_TEXTURE_TRANSFORM]:void 0;if(a){let o=r.associations.get(s);s=r.extensions[ut.KHR_TEXTURE_TRANSFORM].extendTexture(s,a),r.associations.set(s,o)}}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 a="PointsMaterial:"+n.uuid,o=this.cache.get(a);if(!o)o=new ol,Xn.prototype.copy.call(o,n),o.color.copy(n.color),o.map=n.map,o.sizeAttenuation=!1,this.cache.add(a,o);n=o}else if(e.isLine){let a="LineBasicMaterial:"+n.uuid,o=this.cache.get(a);if(!o)o=new al,Xn.prototype.copy.call(o,n),o.color.copy(n.color),o.map=n.map,this.cache.add(a,o);n=o}if(i||r||s){let a="ClonedMaterial:"+n.uuid+":";if(i)a+="derivative-tangents:";if(r)a+="vertex-colors:";if(s)a+="flat-shading:";let o=this.cache.get(a);if(!o){if(o=n.clone(),r)o.vertexColors=!0;if(s)o.flatShading=!0;if(i){if(o.normalScale)o.normalScale.y*=-1;if(o.clearcoatNormalScale)o.clearcoatNormalScale.y*=-1}this.cache.add(a,o),this.associations.set(o,this.associations.get(n))}n=o}e.material=n}getMaterialType(){return zr}loadMaterial(e){let t=this,n=this.json,i=this.extensions,r=n.materials[e],s,a={},o=r.extensions||{},c=[];if(o[ut.KHR_MATERIALS_UNLIT]){let u=i[ut.KHR_MATERIALS_UNLIT];s=u.getMaterialType(),c.push(u.extendParams(a,r,t))}else{let u=r.pbrMetallicRoughness||{};if(a.color=new qe(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){let d=u.baseColorFactor;a.color.setRGB(d[0],d[1],d[2],oi),a.opacity=d[3]}if(u.baseColorTexture!==void 0)c.push(t.assignTexture(a,"map",u.baseColorTexture,ps));if(a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0)c.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),c.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture));s=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,a)})))}if(r.doubleSided===!0)a.side=vi;let l=r.alphaMode||mg.OPAQUE;if(l===mg.BLEND)a.transparent=!0,a.depthWrite=!1;else if(a.transparent=!1,l===mg.MASK)a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:0.5;if(r.normalTexture!==void 0&&s!==mr){if(c.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new Ke(1,1),r.normalTexture.scale!==void 0){let u=r.normalTexture.scale;a.normalScale.set(u,u)}}if(r.occlusionTexture!==void 0&&s!==mr){if(c.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0)a.aoMapIntensity=r.occlusionTexture.strength}if(r.emissiveFactor!==void 0&&s!==mr){let u=r.emissiveFactor;a.emissive=new qe().setRGB(u[0],u[1],u[2],oi)}if(r.emissiveTexture!==void 0&&s!==mr)c.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,ps));return Promise.all(c).then(function(){let u=new s(a);if(r.name)u.name=r.name;if(xr(u,r),t.associations.set(u,{materials:e}),r.extensions)Ca(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(a){return n[ut.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(o){return HA(o,a,t)})}let s=[];for(let a=0,o=e.length;a<o;a++){let c=e[a],l=S8(c),u=i[l];if(u)s.push(u.promise);else{let d;if(c.extensions&&c.extensions[ut.KHR_DRACO_MESH_COMPRESSION])d=r(c);else d=HA(new Dn,c,t);if(c.mode===Ti.TRIANGLE_STRIP)d=d.then((f)=>hg(f,Zc));else if(c.mode===Ti.TRIANGLE_FAN)d=d.then((f)=>hg(f,No));i[l]={primitive:c,promise:d},s.push(d)}}return Promise.all(s)}loadMesh(e){let t=this,n=this.json,i=this.extensions,r=n.meshes[e],s=r.primitives,a=[];for(let o=0,c=s.length;o<c;o++){let l=s[o].material===void 0?T8(this.cache):this.getDependency("material",s[o].material);a.push(l)}return a.push(t.loadGeometries(s)),Promise.all(a).then(async function(o){let c=o.slice(0,o.length-1),l=o[o.length-1],u=[];for(let f=0,h=l.length;f<h;f++){let b=l[f],m=s[f],g,p=c[f];if(m.mode===Ti.TRIANGLES||m.mode===Ti.TRIANGLE_STRIP||m.mode===Ti.TRIANGLE_FAN||m.mode===void 0){let x=r.isSkinnedMesh===!0,_=b.hasAttribute("skinIndex")&&b.hasAttribute("skinWeight");if(x&&_===!1)console.warn("THREE.GLTFLoader: Missing skinIndex or skinWeight attributes. Skinning disabled.");if(g=x&&_?new Md(b,p):new jt(b,p),g.isSkinnedMesh===!0)g.normalizeSkinWeights()}else if(m.mode===Ti.LINES)g=new Rd(b,p);else if(m.mode===Ti.LINE_STRIP)g=new gs(b,p);else if(m.mode===Ti.LINE_LOOP)g=new Id(b,p);else if(m.mode===Ti.POINTS)g=new Do(b,p);else throw Error("THREE.GLTFLoader: Primitive mode unsupported: "+m.mode);if(Object.keys(g.geometry.morphAttributes).length>0)w8(g,r);if(g.name=t.createUniqueName(r.name||"mesh_"+e),xr(g,r),m.extensions)Ca(i,g,m);t.assignFinalMaterial(g),u.push(g)}for(let f=0,h=u.length;f<h;f++)t.associations.set(u[f],{meshes:e,primitives:f});if(u.length===1){if(r.extensions)Ca(i,u[0],r);return u[0]}let d=new cr;if(r.extensions)Ca(i,d,r);t.associations.set(d,{meshes:e});for(let f=0,h=u.length;f<h;f++)d.add(u[f]);return d})}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 fn(Yc.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2000000);else if(n.type==="orthographic")t=new Ra(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar);if(n.name)t.name=this.createUniqueName(n.name);return xr(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,a=[],o=[];for(let c=0,l=s.length;c<l;c++){let u=s[c];if(u){a.push(u);let d=new Qe;if(r!==null)d.fromArray(r.array,c*16);o.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new rl(a,o)})}loadAnimation(e){let t=this.json,n=this,i=t.animations[e],r=i.name?i.name:"animation_"+e,s=[],a=[],o=[],c=[],l=[];for(let u=0,d=i.channels.length;u<d;u++){let f=i.channels[u],h=i.samplers[f.sampler],b=f.target,m=b.node,g=i.parameters!==void 0?i.parameters[h.input]:h.input,p=i.parameters!==void 0?i.parameters[h.output]:h.output;if(b.node===void 0)continue;s.push(this.getDependency("node",m)),a.push(this.getDependency("accessor",g)),o.push(this.getDependency("accessor",p)),c.push(h),l.push(b)}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(o),Promise.all(c),Promise.all(l)]).then(function(u){let d=u[0],f=u[1],h=u[2],b=u[3],m=u[4],g=[];for(let x=0,_=d.length;x<_;x++){let y=d[x],v=f[x],T=h[x],A=b[x],E=m[x];if(y===void 0)continue;if(y.updateMatrix)y.updateMatrix();let w=n._createAnimationTracks(y,v,T,A,E);if(w)for(let P=0;P<w.length;P++)g.push(w[P])}let p=new To(r,void 0,g);return xr(p,i),p})}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(a){if(!a.isMesh)return;for(let o=0,c=i.weights.length;o<c;o++)a.morphTargetInfluences[o]=i.weights[o]});return s})}loadNode(e){let t=this.json,n=this,i=t.nodes[e],r=n._loadNodeShallow(e),s=[],a=i.children||[];for(let c=0,l=a.length;c<l;c++)s.push(n.getDependency("node",a[c]));let o=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([r,Promise.all(s),o]).then(function(c){let l=c[0],u=c[1],d=c[2];if(d!==null)l.traverse(function(f){if(!f.isSkinnedMesh)return;f.bind(d,R8)});for(let f=0,h=u.length;f<h;f++)l.add(u[f]);if(l.userData.pivot!==void 0&&u.length>0){let f=l.userData.pivot,h=u[0];l.pivot=new j().fromArray(f),l.position.x-=f[0],l.position.y-=f[1],l.position.z-=f[2],h.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):"",a=[],o=i._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});if(o)a.push(o);if(r.camera!==void 0)a.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){a.push(c)}),this.nodeCache[e]=Promise.all(a).then(function(c){let l;if(r.isBone===!0)l=new nl;else if(c.length>1)l=new cr;else if(c.length===1)l=c[0];else l=new Dt;if(l!==c[0])for(let u=0,d=c.length;u<d;u++)l.add(c[u]);if(r.name)l.userData.name=r.name,l.name=s;if(xr(l,r),r.extensions)Ca(n,l,r);if(r.matrix!==void 0){let u=new Qe;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 cr;if(n.name)r.name=i.createUniqueName(n.name);if(xr(r,n),n.extensions)Ca(t,r,n);let s=n.nodes||[],a=[];for(let o=0,c=s.length;o<c;o++)a.push(i.getDependency("node",s[o]));return Promise.all(a).then(function(o){for(let l=0,u=o.length;l<u;l++){let d=o[l];if(d.parent!==null)r.add(UA(d));else r.add(d)}let c=(l)=>{let u=new Map;for(let[d,f]of i.associations)if(d instanceof Xn||d instanceof en)u.set(d,f);return l.traverse((d)=>{let f=i.associations.get(d);if(f!=null)u.set(d,f)}),u};return i.associations=c(r),r})}_createAnimationTracks(e,t,n,i,r){let s=[],a=e.name?e.name:e.uuid,o=[];function c(f){if(f.morphTargetInfluences)o.push(f.name?f.name:f.uuid)}if(Ts[r.path]===Ts.weights){if(c(e),e.isGroup)e.children.forEach(c)}else o.push(a);let l;switch(Ts[r.path]){case Ts.weights:l=ys;break;case Ts.rotation:l=_s;break;case Ts.translation:case Ts.scale:l=Ma;break;default:switch(n.itemSize){case 1:l=ys;break;case 2:case 3:default:l=Ma;break}break}let u=i.interpolation!==void 0?E8[i.interpolation]:_d,d=this._getArrayFromAccessor(n);for(let f=0,h=o.length;f<h;f++){let b=new l(o[f]+"."+Ts[r.path],t.array,d,u);if(i.interpolation==="CUBICSPLINE")this._createCubicSplineTrackInterpolant(b);s.push(b)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let n=yg(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 _s?fw:vg)(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function I8(e,t,n){let i=t.attributes,r=new hn;if(i.POSITION!==void 0){let o=n.json.accessors[i.POSITION],{min:c,max:l}=o;if(c!==void 0&&l!==void 0){if(r.set(new j(c[0],c[1],c[2]),new j(l[0],l[1],l[2])),o.normalized){let u=yg(Go[o.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 o=new j,c=new j;for(let l=0,u=s.length;l<u;l++){let d=s[l];if(d.POSITION!==void 0){let f=n.json.accessors[d.POSITION],{min:h,max:b}=f;if(h!==void 0&&b!==void 0){if(c.setX(Math.max(Math.abs(h[0]),Math.abs(b[0]))),c.setY(Math.max(Math.abs(h[1]),Math.abs(b[1]))),c.setZ(Math.max(Math.abs(h[2]),Math.abs(b[2]))),f.normalized){let m=yg(Go[f.componentType]);c.multiplyScalar(m)}o.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(o)}e.boundingBox=r;let a=new li;r.getCenter(a.center),a.radius=r.min.distanceTo(r.max)/2,e.boundingSphere=a}function HA(e,t,n){let i=t.attributes,r=[];function s(a,o){return n.getDependency("accessor",a).then(function(c){e.setAttribute(o,c)})}for(let a in i){let o=xg[a]||a.toLowerCase();if(o in e.attributes)continue;r.push(s(i[a],o))}if(t.indices!==void 0&&!e.index){let a=n.getDependency("accessor",t.indices).then(function(o){e.setIndex(o)});r.push(a)}if(ot.workingColorSpace!==oi&&"COLOR_0"in i)console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ot.workingColorSpace}" not supported.`);return xr(e,t),I8(e,t,n),Promise.all(r).then(function(){return t.targets!==void 0?A8(e,t.targets,n):e})}function yr(e){let t=new Set,n=new Set,i=new Set;e.traverse((r)=>{let s=r;if(!s.isMesh)return;t.add(s.geometry);for(let a of Array.isArray(s.material)?s.material:[s.material]){n.add(a);for(let o of Object.values(a))if(o instanceof en)i.add(o)}});for(let r of[...t,...n,...i])r.dispose()}async function pw(e){ip(e);let t=new ll,n=!1;t.onError=()=>{n=!0},t.addHandler(/^data:image\//,new Lo(t)),t.setURLModifier((s)=>{if(!s.startsWith("blob:")&&!s.startsWith("data:"))throw Error("External model resources are not loaded");return s});let i=new _g(t);i.register((s)=>({name:"KILN_embedded_images",async beforeRoot(){for(let a of s.json.images??[]){if(a.bufferView===void 0)continue;let o=new Uint8Array(await s.getDependency("bufferView",a.bufferView)),c="";for(let l=0;l<o.length;l+=8192)c+=String.fromCharCode(...o.subarray(l,l+8192));if(!/^image\/(png|jpeg|webp|avif)$/.test(a.mimeType??""))throw Error("Unsupported embedded image type");a.uri=`data:${a.mimeType};base64,${btoa(c)}`,delete a.bufferView}}}));let r=await i.parseAsync(Uint8Array.from(e).buffer,"");if(n){for(let s of r.scenes)yr(s);throw Error("An embedded texture could not be decoded.")}return Object.assign(r,{assertTexturesLoaded(){if(n)throw Error("An embedded texture could not be decoded.")}})}ji();function mw(e,t,n=40,i=[e]){let r=e.getCenter(new j),s=Math.max(e.getSize(new j).length()/2,0.01),a=new j(1,0.65,1.25).normalize(),o=new j().crossVectors(new j(0,1,0),a).normalize(),c=new j().crossVectors(a,o),l=[];for(let x of i.length?i:[e])for(let _ of[x.min.x,x.max.x])for(let y of[x.min.y,x.max.y])for(let v of[x.min.z,x.max.z])l.push(new j(_,y,v));let u=1/0,d=-1/0,f=1/0,h=-1/0;for(let x of l){let _=x.clone().sub(r),y=_.dot(o),v=_.dot(c);u=Math.min(u,y),d=Math.max(d,y),f=Math.min(f,v),h=Math.max(h,v)}r.addScaledVector(o,(u+d)/2),r.addScaledVector(c,(f+h)/2);let b=Math.tan(n*Math.PI/360),m=b*t,g=s;for(let x of l){let _=x.clone().sub(r),y=_.dot(a);g=Math.max(g,y+Math.abs(_.dot(o))*1.12/m,y+Math.abs(_.dot(c))*1.12/b)}let p=r.clone().addScaledVector(a,g);return{center:r,radius:s,distance:g,position:p}}ji();function Eg(e,t){return{position:e.position.clone(),target:t.clone()}}function Tg(e,t,n,i){e.position.copy(n.position),t.copy(n.target);let r=Math.max(i.getSize(new j).length(),0.001);e.near=Math.min(0.01,Math.max(r/1e5,0.00001)),e.far=Math.max(e.position.distanceTo(i.getCenter(new j))+r*20,10),e.updateProjectionMatrix()}function gw(e,t,n){let i=e.getWorldDirection(new j);if(i.y=0,i.lengthSq()<0.00000001)i.set(0,0,-1);i.normalize();let r=i.clone().cross(new j(0,1,0)),s=new j;if(t.has("KeyW")||t.has("ArrowUp"))s.add(i);if(t.has("KeyS")||t.has("ArrowDown"))s.sub(i);if(t.has("KeyD")||t.has("ArrowRight"))s.add(r);if(t.has("KeyA")||t.has("ArrowLeft"))s.sub(r);if(t.has("KeyE"))s.y++;if(t.has("KeyQ"))s.y--;return s.normalize().multiplyScalar(n)}function bw(e){let t=e.filter((i)=>Number.isFinite(i)&&i>0).sort((i,r)=>i-r);if(!t.length)throw Error("No frame timing evidence was collected.");let n=(i)=>t[Math.max(0,Math.ceil(t.length*i)-1)];return{samples:t.length,min:t[0],p50:n(0.5),p95:n(0.95),max:t.at(-1)}}async function xw(e,t){let n=t();if(n===void 0)throw Error("Wait for the selected artifact to be loaded before measuring.");let i=JSON.stringify(n),r=await e();if(JSON.stringify(t())!==i)throw Error("The artifact changed during measurement. Measure the loaded revision again.");return{...r,artifact:n}}function yw(e,t,n){if(t())return e;n(e);return}ji();function Kd(e,t){let n=e.parser.json.nodes??[],i=new Set;if(n.forEach((s,a)=>{if(s?.extensions?.KHR_node_visibility?.visible===!1)i.add(a)}),i.size===0)return 0;let r=0;for(let s of t)s.traverse((a)=>{let o=e.parser.associations.get(a)?.nodes;if(o===void 0||!i.has(o))return;a.visible=!1,r++});return r}function Wd(e){let t=!1;if(e.traverse((s)=>{if(!s.visible)t=!0}),!t)return new hn().setFromObject(e,!0);e.updateWorldMatrix(!0,!0);let n=new hn,i=new hn,r=new j;return e.traverseVisible((s)=>{let a=s,o=a.geometry;if(!o)return;let c=o.getAttribute("position");if(c&&a.isInstancedMesh!==!0){for(let u=0;u<c.count;u++){if(a.isMesh)a.getVertexPosition(u,r);else r.fromBufferAttribute(c,u);n.expandByPoint(r.applyMatrix4(s.matrixWorld))}return}let l=s;if(l.boundingBox!==void 0){if(l.boundingBox===null)l.computeBoundingBox();i.copy(l.boundingBox)}else{if(o.boundingBox===null)o.computeBoundingBox();i.copy(o.boundingBox)}n.union(i.applyMatrix4(s.matrixWorld))}),n.isEmpty()?new hn().setFromObject(e,!0):n}function yl(e){let t=0;return e.traverseVisible((n)=>{let i=n;if(!i.isMesh)return;let r=i.geometry.index?.count??i.geometry.attributes.position?.count??0;t+=r/3*(i.isInstancedMesh?i.count:1)}),t}async function _w(e){let t=e.parser.json.nodes??[],n=new Map;e.scene.traverse((c)=>{let l=e.parser.associations.get(c)?.nodes;if(l!==void 0&&!n.has(l))n.set(l,c)});let i=new Set,r=[];for(let[c,l]of n){let u=t[c]?.extensions?.MSFT_lod?.ids;if(!Array.isArray(u)||u.length===0)continue;if(u.some((b)=>!Number.isInteger(b)||!t[b]||n.has(b)))continue;let d=l.parent;while(d&&!i.has(d))d=d.parent;if(d)continue;let f=[l];for(let b of u)f.push(await e.parser.getDependency("node",b));Kd(e,f.slice(1)),i.add(l);let h=(l.name.replace(/[_ -]?LOD0$/i,"")||l.parent?.name||`Part ${c}`).replace(/^Mesh_/,"");r.push({id:String(c),label:h,levels:f})}if(r.length===0)return;let s=yl(e.scene)-r.reduce((c,l)=>c+Ag(l,0),0),a=Math.max(...r.map((c)=>c.levels.length)),o=Array.from({length:a},(c,l)=>s+r.reduce((u,d)=>u+Ag(d,l),0));return{chains:r,triangles:o}}var vw=(e,t)=>e.levels[Math.min(Math.max(Number.isFinite(t)?Math.floor(t):0,0),e.levels.length-1)];function Ag(e,t){let n=e.levels.find((i)=>i.parent)?.parent;while(n){if(!n.visible)return 0;n=n.parent}return yl(vw(e,t))}function Ew(e,t){let n=vw(e,t),i=e.levels.find((s)=>s.parent!==null);if(!i||i===n)return;let r=i.parent;r.children[r.children.indexOf(i)]=n,n.parent=r,i.parent=null}function Tw(e,t){for(let n of e.chains)Ew(n,t)}function Aw(e,t,n){let i=e.chains.find((r)=>r.id===t);if(!i)return!1;return Ew(i,n),!0}function ww(e,t){if(!e)return;return{triangles:yl(t),levels:e.triangles,chains:e.chains.map((n)=>({id:n.id,label:n.label,level:n.levels.findIndex((i)=>i.parent!==null),triangles:n.levels.map((i,r)=>Ag(n,r))}))}}function $o(e){return(e?.chains??[]).flatMap((t)=>t.levels.filter((n)=>n.parent===null))}function wg(e){return e.map((t,n)=>`LOD${n} · ${t.toLocaleString()} triangles`)}function _l(e){let t=new og({antialias:!0,alpha:!1});t.setPixelRatio(Math.min(devicePixelRatio,2)),t.setClearColor(1382930),t.toneMapping=Xc,t.toneMappingExposure=1.15,e.replaceChildren(t.domElement);let n=new Po,i=new fn(40,1,0.01,1000),r=new dg(i,t.domElement);r.enableDamping=!0,t.domElement.tabIndex=0,t.domElement.setAttribute("aria-label","Interactive 3D asset. Drag to orbit or use Explore navigation.");let s=new Set,a=!1,o=1,c=new Set(["KeyW","KeyA","KeyS","KeyD","KeyQ","KeyE","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","ShiftLeft","ShiftRight"]),l=(O)=>{if(!a||!c.has(O.code))return;O.preventDefault(),s.add(O.code)},u=(O)=>s.delete(O.code),d=()=>s.clear();t.domElement.addEventListener("keydown",l),t.domElement.addEventListener("keyup",u),t.domElement.addEventListener("blur",d);let f=new bl(t),h=new fg,b=f.fromScene(h,0.04);n.environment=b.texture,h.dispose(),f.dispose();let m=new Bo(16773591,2.4);m.position.set(4,8,5),n.add(m),n.add(new Dd(14806490,5065021,1.7));let g,p,x,_=[],y=!0,v=performance.now(),T=0,A=0,E=!1,w,P,S,I=(O)=>{if(!S)return;clearTimeout(S.timeout),S.reject(Error(O)),S=void 0},U=(O)=>{let K=t.getContext(),B=K.getExtension("WEBGL_debug_renderer_info");return{version:"kiln.viewer-performance.v1",measuredAt:new Date().toISOString(),windowMs:O-S.started,frameMs:bw(S.samples),...P===void 0?{}:{loadToFirstFrameMs:P},drawCalls:t.info.render.calls,triangles:t.info.render.triangles,lines:t.info.render.lines,points:t.info.render.points,geometryObjects:t.info.memory.geometries,textureObjects:t.info.memory.textures,shaderPrograms:t.info.programs?.length??0,viewport:{cssWidth:e.clientWidth,cssHeight:e.clientHeight,bufferWidth:t.domElement.width,bufferHeight:t.domElement.height,devicePixelRatio:t.getPixelRatio()},renderer:{version:String(K.getParameter(K.VERSION)),vendor:String(K.getParameter(K.VENDOR)),renderer:String(K.getParameter(K.RENDERER)),browser:navigator.userAgent,...B?{unmaskedVendor:String(K.getParameter(B.UNMASKED_VENDOR_WEBGL)),unmaskedRenderer:String(K.getParameter(B.UNMASKED_RENDERER_WEBGL))}:{}},camera:{position:i.position.toArray(),target:r.target.toArray(),fov:i.fov},limitations:["Exploratory measurement: workloads outside this page are uncontrolled. This is not an isolated performance baseline or budget acceptance.","Frame intervals measure browser requestAnimationFrame pacing, including scheduling and vertical sync; they are not GPU execution time.","Load-to-first-frame begins at GLB parsing and ends after the first render submission; it excludes download time and does not measure presentation latency.","Draw and resource counts come from this Three.js renderer, including studio lighting resources. Object counts are not GPU memory bytes.","This receipt describes this viewport, camera and device only. It is not a performance qualification for other consumers or hardware."]}},N=()=>{if(!g)return;let O=Wd(g),K=[];g.traverseVisible((de)=>{if(de instanceof jt||de instanceof gs||de instanceof Do){let Me=new hn().setFromObject(de,!0);if(!Me.isEmpty())K.push(Me)}});let{center:B,radius:X,distance:q,position:le}=mw(O,i.aspect,i.fov,K);if(r.target.copy(B),i.position.copy(le),i.near=Math.max(X/1000,0.0001),i.far=q+X*100,r.minDistance=X*0.1,r.maxDistance=X*80,o=Math.max(X*0.35,0.01),a)r.minDistance=X*0.00001;i.updateProjectionMatrix(),r.update()},F=new ResizeObserver(()=>{let{clientWidth:O,clientHeight:K}=e;if(!O||!K)return;t.setSize(O,K),i.aspect=O/K,i.updateProjectionMatrix()});F.observe(e);let D=(O)=>{if(E)return;let K=Math.min((O-v)/1000,0.1);if(v=O,e.clientWidth&&e.clientHeight){if(y)x?.update(K);if(a&&s.size){let B=gw(i,s,K*o*(s.has("ShiftLeft")||s.has("ShiftRight")?3:1));i.position.add(B),r.target.add(B)}if(r.update(),t.render(n,i),w!==void 0)P=performance.now()-w,w=void 0;if(S){if(S.previous>0&&S.samples.length<1800)S.samples.push(O-S.previous);if(S.previous=O,O-S.started>=S.duration&&S.samples.length){let B=U(O);clearTimeout(S.timeout),S.resolve(B),S=void 0}}}else s.clear(),I("Keep the measured viewport visible for the complete sampling window.");T=requestAnimationFrame(D)};return T=requestAnimationFrame(D),{async load(O,K={}){let B=performance.now(),X=++A;I("The artifact changed during measurement. Measure the new revision again.");let q=await pw(O);Kd(q,[q.scene]);let le=await _w(q);try{q.assertTexturesLoaded()}catch(ne){yr(q.scene);for(let ie of $o(le))yr(ie);throw ne}let de=yw(q,()=>!E&&X===A&&K.isCurrent?.()!==!1,(ne)=>{yr(ne.scene);for(let ie of $o(le))yr(ie)});if(!de)return;let Me=g&&K.preserveView?Eg(i,r.target):void 0;if(g){x?.stopAllAction(),x?.uncacheRoot(g),n.remove(g),yr(g);for(let ne of $o(p))yr(ne)}g=de.scene,p=le,w=B,P=void 0,n.add(g),_=de.animations,x=new Bd(g),y=!0;let{clientWidth:pe,clientHeight:J}=e;if(t.setSize(pe,J),i.aspect=pe&&J?pe/J:i.aspect,N(),Me)Tg(i,r.target,Me,Wd(g)),r.update();let L=0,W=new Set;return g.traverseVisible((ne)=>{let ie=ne;if(!ie.isMesh)return;L++;for(let ce of Array.isArray(ie.material)?ie.material:[ie.material])W.add(ce)}),K.onCommit?.(),{triangles:yl(g),meshes:L,materials:W.size,clips:_.map((ne)=>ne.name),...p?{levels:p.triangles}:{}}},level(O){if(I("The level of detail changed. Measure the displayed combination again."),p)Tw(p,O)},partLevel(O,K){if(I("The level of detail changed. Measure the displayed combination again."),p)Aw(p,O,K)},lod(){return g?ww(p,g):void 0},reset:N,cancelMeasurement:I,measure(O=3000){if(E||!g||!e.clientWidth||!e.clientHeight)return Promise.reject(Error("Load an artifact in a visible viewport before measuring."));if(!Number.isFinite(O)||O<1000||O>5000)return Promise.reject(Error("Measurement duration must be 1–5 seconds."));if(S)return Promise.reject(Error("A measurement is already running."));return new Promise((K,B)=>{S={started:performance.now(),previous:0,duration:O,samples:[],resolve:K,reject:B,timeout:setTimeout(()=>I("Measurement was interrupted or the browser stopped delivering frames."),O+2000)}})},view(){return Eg(i,r.target)},setView(O){if(!g)return;Tg(i,r.target,O,Wd(g)),r.update()},navigation(O){if(a=O==="explore",s.clear(),r.minDistance=a?0.00001:o/3.5,a)i.near=0.0001,i.updateProjectionMatrix()},wire(O){for(let K of g?[g,...$o(p)]:[])K.traverse((B)=>{let X=B;if(X.isMesh){for(let q of Array.isArray(X.material)?X.material:[X.material])if("wireframe"in q)q.wireframe=O}})},lighting(O){t.toneMappingExposure=O==="bright"?1.65:O==="soft"?0.85:1.15,m.intensity=O==="soft"?0.8:2.4},clip(O){if(x?.stopAllAction(),_[O])x?.clipAction(_[O]).play()},pause(O){y=!O},dispose(){if(I("The viewport closed before measurement finished."),E=!0,A++,cancelAnimationFrame(T),F.disconnect(),r.dispose(),t.domElement.removeEventListener("keydown",l),t.domElement.removeEventListener("keyup",u),t.domElement.removeEventListener("blur",d),g)yr(g);for(let O of $o(p))yr(O);b.dispose(),t.dispose(),e.replaceChildren()}}}var ue=(e)=>document.getElementById(e);function k(e,t,n){let i=document.createElement(e);if(t!==void 0)i.textContent=t;if(n)i.className=n;return i}function Rn(e){let t=ue("dashboard-status");t.textContent=e instanceof Error?e.message:String(e),t.hidden=!t.textContent}async function un(e,t){let n=await fetch(e,t?{method:t.method,headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)}:void 0),i=await n.json();if(!n.ok)throw Error(i.error??`Request failed (${n.status})`);return i}function Ko(e,t){let n=k("div",void 0,"empty");return n.append(k("b",e),k("p",t)),n}function Hi(e,t){try{localStorage.setItem(e,t)}catch{}}function As(e){try{return localStorage.getItem(e)}catch{return null}}function Tn(e){return e?e.slice(0,15):"Unspecified"}function Wo(e,t){let n=k("details",void 0,"record-details");return n.append(k("summary",e),k("pre",JSON.stringify(t,null,2))),n}function vl(e,t,n,i){let r=n.lod();if(e.hidden=!r,t.hidden=!r,t.replaceChildren(),e.replaceChildren(),e.onchange=null,!r)return;e.append(...wg(r.levels).map((l,u)=>new Option(l,String(u))));let s=new Option("Mixed part levels","mixed");s.disabled=!0,e.append(s);let a=k("p","","lod-total");a.setAttribute("role","status"),t.append(a);let o=new Map;if(r.chains.length>1){let l=k("details",void 0,"lod-parts");l.append(k("summary","Per-part levels")),l.append(k("p","Choose a level for each part. The main selector sets every part to the same index.","subtle"));let u=k("div",void 0,"lod-part-fields"),d=new Set(r.chains.filter((f,h,b)=>b.findIndex((m)=>m.label===f.label)!==h).map((f)=>f.label));for(let[f,h]of r.chains.entries()){let b=d.has(h.label)?`${h.label} (part ${f+1})`:h.label,m=k("label",b,"inline-field"),g=k("select");g.setAttribute("aria-label",`${b} level of detail`),g.append(...wg(h.triangles).map((p,x)=>new Option(p,String(x)))),g.onchange=()=>{n.partLevel(h.id,Number(g.value)),c(),i?.()},o.set(h.id,g),m.append(g),u.append(m)}l.append(u),t.append(l)}function c(){let l=n.lod();if(!l)return;let u=l.levels.findIndex((d,f)=>l.chains.every((h)=>h.level===Math.min(f,h.triangles.length-1)));e.value=u<0?"mixed":String(u),a.textContent=`${l.triangles.toLocaleString()} triangles displayed`;for(let d of l.chains){let f=o.get(d.id);if(f)f.value=String(d.level)}}return e.onchange=()=>{if(e.value==="mixed")return;let l=Number(e.value);n.level(l),c(),i?.(l)},c(),{refresh:c}}var Sw=/^[a-z][a-z0-9_-]{0,79}$/u,C8=/^r_[a-z0-9_-]{1,77}$/u;function Mw(e){let t=new URLSearchParams(e),n=t.get("collection"),i=t.get("asset"),r=t.get("revision");if(!n||!i||!r||!Sw.test(n)||!Sw.test(i)||!C8.test(r))return;return{collection:n,assetId:i,revisionId:r}}Mg();var cb=new TextEncoder,uB=new TextDecoder,Qo=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),ob=(e,t)=>Object.hasOwn(e,t);async function yR(e){let t=await crypto.subtle.digest("SHA-256",Uint8Array.from(e));return`sha256:${Array.from(new Uint8Array(t),(n)=>n.toString(16).padStart(2,"0")).join("")}`}function dB(e){if(e.length>200||!/^[a-z0-9][a-z0-9._-]*\.kiln-metadata\.json$/i.test(e)||/^(con|prn|aux|nul|com[0-9]|lpt[0-9])\./i.test(e))throw Error("Runtime metadata filename must be a portable sibling *.kiln-metadata.json filename")}function fB(e){if(e.length>200||!/^[a-z0-9][a-z0-9._-]*\.gltf$/i.test(e)||/^(con|prn|aux|nul|com[0-9]|lpt[0-9])\./i.test(e))throw Error("External texture output must be a portable sibling *.gltf filename")}function hB(e,t){if(t+8>e.length)return;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(t+4,!0)!==5130562)return;return e.subarray(t+8,t+8+n.getUint32(t,!0))}function pB(e){let t=new Map;for(let i of[...kc(e),...(e.materialResources?.records??[]).map(({manifest:r})=>r)])t.set(`${i.materialId}/${i.revisionId}`,i);let n=(i,r)=>i<r?-1:i>r?1:0;return[...t.values()].flatMap((i)=>i.maps.map((r)=>({sha256:r.sha256,pin:{resourceId:i.materialId,revisionId:i.revisionId,sha256:i.revisionId},slot:r.slot}))).sort((i,r)=>n(i.pin.resourceId,r.pin.resourceId)||n(i.pin.revisionId,r.pin.revisionId)||n(i.slot,r.slot))}function _R(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=12;while(n<e.length){if(n+8>e.length)throw Error("Invalid GLB chunk header");let s=t.getUint32(n,!0);if(s%4||n+8+s>e.length)throw Error("Invalid GLB chunk length");n+=8+s}let i=20+t.getUint32(12,!0),r=JSON.parse(uB.decode(e.subarray(20,i)));if(!Qo(r)||!Qo(r.asset)||r.asset.version!=="2.0")throw Error("Invalid glTF asset");return{json:r,jsonEnd:i}}function vR(e,t,n){let i=cb.encode(JSON.stringify(n)),r=Math.ceil(i.length/4)*4,s=new Uint8Array(20+r+e.length-t);if(s.length>Kn)throw Error("Runtime export exceeds 64 MiB");s.set(e.subarray(0,20));let a=new DataView(s.buffer);return a.setUint32(8,s.length,!0),a.setUint32(12,r,!0),s.fill(32,20,20+r),s.set(i,20),s.set(e.subarray(t),20+r),s}async function mB(e,t,n={}){let[{deliverRuntimeThreeGlb:i},{MeshoptEncoder:r}]=await Promise.all([Promise.resolve().then(() => (fR(),dR)),Promise.resolve().then(() => (xR(),bR))]);await r.ready;let s=await i(e,r,t,n);if(s.glb.byteLength>Kn)throw Error("Runtime export exceeds 64 MiB");return s}async function ER(e,t={}){let n=t.profile??"editable";if(n!=="editable"&&n!=="runtime")throw Error("Unknown export profile");if(t.target!==void 0&&t.target!=="three")throw Error("Unknown runtime export target");if(t.target!==void 0&&n!=="runtime")throw Error("A runtime export target requires the runtime profile");if(t.compression!==void 0&&t.target!=="three")throw Error("Runtime compression requires the three runtime target");let i=t.textures;if(i!==void 0&&i!=="manifest"&&i!=="external")throw Error("Unknown runtime texture option");if(i!==void 0&&n!=="runtime")throw Error("A texture manifest requires the runtime profile");if(i==="external"&&t.target!=="three")throw Error("External textures require target three");let r=t.gltfFileName??"runtime.gltf";if(i==="external")fB(r);Du(e);let s=e.files["asset.glb"];if(n==="editable")return{profile:n,glb:s};let a=t.metadataFileName??"runtime.kiln-metadata.json";dB(a);for(let[w,P]of Object.entries(e.files))if(await yR(P)!==e.manifest.files[w].sha256)throw Error(`Asset integrity mismatch: ${w}`);let{json:o,jsonEnd:c}=_R(s),l=o.asset;if(ob(l,"extras")&&!Qo(l.extras))throw Error("Cannot add provenance to non-object asset extras");let u=l.extras??{};if(ob(u,"kilnProvenanceV1"))throw Error("Asset extras already contain kilnProvenanceV1; export from the canonical revision");let d=[];if(o.scenes!==void 0&&!Array.isArray(o.scenes))throw Error("Invalid glTF scenes");for(let[w,P]of(o.scenes??[]).entries()){if(!Qo(P)||!Qo(P.extras)||!ob(P.extras,"kilnReviewClipsV1"))continue;let S=P.extras.kilnReviewClipsV1;if(!Qo(S)||S.version!==1&&S.version!==2||!Array.isArray(S.clips))throw Error("Unsupported scenes[].extras.kilnReviewClipsV1");d.push({index:w,kilnReviewClipsV1:S}),delete P.extras.kilnReviewClipsV1}let f={version:"kiln.runtime-metadata.v1",source:{assetId:e.manifest.assetId,revisionId:e.manifest.revisionId,glbSha256:e.manifest.files["asset.glb"].sha256,...e.manifest.files["source.kiln.js"]?{sourceSha256:e.manifest.files["source.kiln.js"].sha256}:{}},scenes:d},h=s,b=o,m=c,g,p;if(t.target==="three"){let w=await mB(vR(s,c,o),{...t.ktx2Encoder?{ktx2Encoder:t.ktx2Encoder}:{},...t.compression?{compression:t.compression}:{}},i==="external"?{gltfBasename:r.slice(0,-5)}:{});f.target="three",f.delivery=w.delivery,h=w.glb,g=w.imageSources,p=w.gltf,{json:b,jsonEnd:m}=_R(h)}if(i!==void 0)f.textures=await Rw(b,hB(h,m),{...g?{sources:g}:{},maps:pB(e)});let x=p?await gB(p,f.textures??[]):void 0,_=cb.encode(JSON.stringify(f));if(_.length>Kn)throw Error("Runtime export exceeds 64 MiB");let y={version:"kiln.provenance.v1",profile:"runtime",...t.target?{target:t.target}:{},metadata:{uri:a,sha256:await yR(_)}},v=b.asset;v.extras={...v.extras??u,kilnProvenanceV1:y};let T=vR(h,m,b);if(!x)return{profile:n,glb:T,metadata:{name:a,bytes:_}};let A=x.json.asset;A.extras={...A.extras??u,kilnProvenanceV1:y};let E=cb.encode(JSON.stringify(x.json));if(E.length>Kn)throw Error("Runtime export exceeds 64 MiB");return{profile:n,layout:"gltf",glb:T,gltf:{name:r,bytes:E},buffers:x.buffers,textures:x.textures,metadata:{name:a,bytes:_}}}async function gB(e,t){let n=structuredClone(e.json),i=new Map(Object.entries(e.resources)),r=Array.isArray(n.images)?n.images:[];if(r.length!==t.length)throw Error("External texture layout mismatch");let s=new Map;for(let[o,c]of r.entries()){let l=t[o],u=typeof c.uri==="string"?c.uri:"",d=i.get(u);if(!d||`sha256:${await El(d)}`!==l.sha256)throw Error("External texture bytes differ from the delivered GLB");i.delete(u);let f=`textures/${l.sha256.slice(7)}.${Iw(l.mimeType)}`;c.uri=f,l.uri=f,s.set(f,{uri:f,sha256:l.sha256,bytes:d})}let a=[...i].map(([o,c])=>({uri:o,bytes:c}));for(let{uri:o}of a)if(!/^[a-z0-9][a-z0-9._-]*\.bin$/i.test(o))throw Error(`Unexpected external glTF resource ${o}`);return{json:n,buffers:a,textures:[...s.values()]}}var Wi=Le().regex(/^[a-z][a-z0-9_-]{0,79}$/).refine((e)=>!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(e),"Reserved filesystem name"),lb=Le().regex(/^r_[0-9]{10}_[a-f0-9]{64}$/),wR=Le().regex(/^sha256:[a-f0-9]{64}$/),ec=Le().max(4000),SR=Le().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/),TR=be({collectionId:Wi,assetId:Wi,revisionId:Wi}).strict(),AR=be({style:ec.default(""),scale:Le().max(1000).default(""),palette:at(be({role:Le().min(1).max(100),color:Le().regex(/^#[a-fA-F0-9]{6}$/)}).strict()).max(64).default([]),materialRoles:at(be({role:Le().min(1).max(100),description:ec.default(""),resourceId:SR.optional()}).strict()).max(128).default([]),conventions:at(Le().max(1000)).max(100).default([]),exceptions:at(Le().max(1000)).max(100).default([])}).strict(),bB=be({resourceId:SR,revisionId:Le().min(1).max(200),sha256:wR,role:Le().max(100).optional()}).strict(),xB=at(bB).max(512),vr={name:Le().trim().min(1).max(200),brief:Le().max(16000).default(""),design:AR.default(()=>AR.parse({})),inventory:at(be({id:Wi,name:Le().trim().min(1).max(200),kind:Ct(["asset","environment"]).default("asset"),brief:ec.default(""),references:at(Wi).max(64).default([]),asset:TR.optional()}).strict()).max(1000).default([]),deliveryProfiles:at(be({id:Wi,target:Ct(["three","godot","unity","unreal","roblox","sbox","usdz","custom"]),description:ec.default(""),performanceIntent:Le().max(1000).default(""),constraints:at(Le().max(1000)).max(100).default([])}).strict()).max(32).default([]),materialDependencies:xB.default([]),references:at(be({id:Wi,title:Le().min(1).max(200),uri:Le().min(1).max(2048),description:ec.default(""),sha256:wR.optional()}).strict()).max(256).default([]),reviews:at(be({id:Wi,inventoryId:Wi,projectRevisionId:lb,asset:TR,reviewer:Le().trim().min(1).max(200),verdict:Ct(["comment","changes-requested","accepted"]),notes:ec}).strict()).max(2000).default([])};function MR(e,t){let n=(a,o)=>{if(new Set(a).size!==a.length)t.addIssue({code:bu.custom,path:[o],message:"Duplicate identity"})};n(e.inventory.map((a)=>a.id),"inventory"),n(e.references.map((a)=>a.id),"references"),n(e.deliveryProfiles.map((a)=>a.id),"deliveryProfiles"),n(e.materialDependencies.map((a)=>a.resourceId),"materialDependencies"),n(e.reviews.map((a)=>a.id),"reviews"),n(e.design.palette.map((a)=>a.role),"design.palette"),n(e.design.materialRoles.map((a)=>a.role),"design.materialRoles");let i=new Set(e.references.map((a)=>a.id)),r=new Set(e.inventory.map((a)=>a.id)),s=new Set(e.materialDependencies.map((a)=>a.resourceId));for(let a of e.inventory)if(n(a.references,`inventory.${a.id}.references`),a.references.some((o)=>!i.has(o)))t.addIssue({code:bu.custom,path:["inventory"],message:"Unknown reference"});if(e.reviews.some((a)=>!r.has(a.inventoryId)))t.addIssue({code:bu.custom,path:["reviews"],message:"Unknown inventory item"});if(e.design.materialRoles.some((a)=>a.resourceId&&!s.has(a.resourceId)))t.addIssue({code:bu.custom,path:["design"],message:"Material role requires a locked resource"})}var RR=be({projectId:Wi.optional(),...vr}).strict().superRefine(MR),QW=be({name:vr.name.optional(),brief:vr.brief.removeDefault().optional(),design:vr.design.removeDefault().optional(),inventory:vr.inventory.removeDefault().optional(),deliveryProfiles:vr.deliveryProfiles.removeDefault().optional(),materialDependencies:vr.materialDependencies.removeDefault().optional(),references:vr.references.removeDefault().optional(),reviews:vr.reviews.removeDefault().optional()}).strict(),eX=be({version:$e("kiln.project.v1"),projectId:Wi,revisionId:lb,parentRevision:lb.optional(),createdAt:Le().datetime(),...vr}).strict().superRefine(MR);function IR(e){let{palette:t,materialRoles:n,conventions:i,exceptions:r}=e.design??{};return{design:{palette:t??[],materialRoles:n??[],conventions:i??[],exceptions:r??[]},inventory:e.inventory??[],deliveryProfiles:e.deliveryProfiles??[],materialDependencies:e.materialDependencies??[],references:e.references??[],reviews:e.reviews??[]}}function CR(e,t){let n=JSON.parse(e);if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Project configuration must be a JSON object.");let i=n,r=i.design??{};if(!r||typeof r!=="object"||Array.isArray(r))throw Error("Design configuration must be a JSON object.");return RR.parse({...i,name:t.name,brief:t.brief,design:{...r,style:t.style,scale:t.scale}})}function NR(e){let t=[],n=As("kiln.project")??"",i,r=()=>{let c=ue("project-list");c.replaceChildren();for(let _ of t){let y=k("button",void 0,_.projectId===n?"active":"");if(y.append(k("strong",_.name),k("small",`${_.inventory.length} inventory items · ${_.materialDependencies.length} resources`)),_.projectId===n)y.setAttribute("aria-current","true");y.onclick=()=>{n=_.projectId,Hi("kiln.project",n),r()},c.append(y)}let l=t.find((_)=>_.projectId===n),u=ue("project-detail");if(u.replaceChildren(),!l){u.append(Ko("A direction for what comes next.","Projects are optional. Group related assets, materials and design decisions here, or build and review standalone assets in Library and Live Review."));return}let d=k("div",void 0,"project-summary"),f=k("div");f.append(k("h2",l.name),k("p",l.brief||"Add a brief to describe what this project should deliver."));let h=k("button","Edit project","secondary");h.onclick=()=>a(l),d.append(f,h),u.append(d);let b=k("p",`${l.projectId} · ${Tn(l.revisionId)} · ${new Date(l.createdAt).toLocaleString()}`,"mono");u.append(b);let m=k("div",void 0,"project-metrics");for(let[_,y]of[[l.inventory.length,"inventory items"],[l.materialDependencies.length,"locked resources"],[l.deliveryProfiles.length,"delivery profiles"]]){let v=k("div");v.append(k("strong",String(_)),k("span",String(y))),m.append(v)}u.append(m);let g=k("div",void 0,"profile-grid");for(let[_,y]of[["Visual direction",l.design.style||"Not specified"],["Scale",l.design.scale||"Not specified"]]){let v=k("div");v.append(k("span",_,"label"),k("p",y)),g.append(v)}u.append(g);let p=k("div",void 0,"palette");for(let _ of l.design.palette){let y=k("div",void 0,"swatch"),v=document.createElementNS("http://www.w3.org/2000/svg","svg");v.setAttribute("viewBox","0 0 24 24"),v.setAttribute("aria-hidden","true");let T=document.createElementNS("http://www.w3.org/2000/svg","rect");T.setAttribute("width","24"),T.setAttribute("height","24"),T.setAttribute("fill",_.color),v.append(T);let A=k("span",_.role);A.append(k("small",_.color)),y.append(v,A),p.append(y)}if(p.childElementCount)u.append(p);for(let[_,y]of[["Conventions",l.design.conventions],["Declared exceptions",l.design.exceptions]]){if(!y.length)continue;u.append(k("h3",_));let v=k("ul",void 0,"subtle");for(let T of y)v.append(k("li",T));u.append(v)}if(u.append(k("h3","Inventory")),!l.inventory.length)u.append(k("p","No inventory yet. Add deliberate asset and environment entries in the project configuration.","subtle"));else{let _=k("div",void 0,"table-wrap"),y=k("table"),v=k("thead"),T=k("tr");for(let E of["Item","Kind","Saved revision","Review"])T.append(k("th",E));v.append(T),y.append(v);let A=k("tbody");for(let E of l.inventory){let w=k("tr"),P=k("td",E.name);P.append(k("small",E.brief));let S=k("td"),I=k("td");if(E.asset){let U=k("button",Tn(E.asset.revisionId),"secondary");U.onclick=()=>e.openAsset(E.asset),S.append(U);let N=[...l.reviews].reverse().find((D)=>D.inventoryId===E.id&&D.asset.revisionId===E.asset.revisionId&&D.asset.assetId===E.asset.assetId&&D.asset.collectionId===E.asset.collectionId);I.append(k("small",N?`${N.verdict} · ${N.reviewer}`:"Unreviewed"));let F=k("button","Record review","secondary");F.onclick=()=>o(l,E),I.append(F)}else S.textContent="Not linked",I.textContent="No saved revision";w.append(P,k("td",E.kind),S,I),A.append(w)}y.append(A),_.append(y),u.append(_)}if(l.design.materialRoles.length){u.append(k("h3","Material roles"));for(let _ of l.design.materialRoles)u.append(k("p",`${_.role}: ${_.description||"No description"}${_.resourceId?` · ${_.resourceId}`:" · No resource assigned"}`,"subtle"))}if(l.deliveryProfiles.length){u.append(k("h3","Delivery intent"));for(let _ of l.deliveryProfiles){if(u.append(k("p",`${_.target} · ${_.description||_.id}`,"subtle")),_.performanceIntent)u.append(k("p",_.performanceIntent,"subtle"));for(let y of _.constraints)u.append(k("p",y,"subtle"))}u.append(k("p","Declared targets are project intent. They do not establish consumer or performance qualification.","subtle"))}if(l.references.length){u.append(k("h3","Reference records"));for(let _ of l.references){let y=k("p",`${_.title}: ${_.uri}`,"subtle");if(_.description)y.append(k("small",` · ${_.description}`));u.append(y)}}u.append(k("h3","Project downloads"));let x=k("div",void 0,"downloads");for(let _ of["editable","runtime"]){let y=k("a",_==="editable"?"Download editable project bundle":"Download runtime project bundle"),v=new URLSearchParams({profile:_,revision:l.revisionId});y.href=`/api/projects/${encodeURIComponent(l.projectId)}/bundle?${v}`,y.download=`${l.projectId}-${_}.zip`,x.append(y)}x.append(k("p","Both downloads bind this exact project revision and its linked saved inventory. Editable includes authored source and material resources for rebuilding. Runtime is delivery-only and cannot restore editable source. Unlinked inventory entries remain plans, not bundled assets.")),u.append(x),u.append(Wo("Exact project configuration and review records",l))},s=async()=>{let c=await un("/api/projects");if(t.length===c.projects.length&&t.every((l,u)=>l.revisionId===c.projects[u]?.revisionId))return;if(t=c.projects,!t.some((l)=>l.projectId===n))n=t[0]?.projectId??"";r(),e.changed(t)};function a(c){i=c,ue("project-editor-title").textContent=c?"Edit project":"New project",ue("project-name").value=c?.name??"",ue("project-brief").value=c?.brief??"",ue("project-style").value=c?.design.style??"",ue("project-scale").value=c?.design.scale??"",ue("project-config").value=JSON.stringify(IR(c??{name:""}),null,2),ue("project-save-status").textContent="",ue("project-editor").showModal(),ue("project-name").focus()}function o(c,l){if(!l.asset)return;let u=k("dialog"),d=k("form"),f=k("div",void 0,"editor-content"),h=k("h2",`Review ${l.name}`);h.id="review-dialog-title",u.setAttribute("aria-labelledby",h.id),f.append(h,k("p","Record an assessment of this exact saved revision. This is a review annotation; structural QA and release qualification remain separate.","subtle"),k("code",`${l.asset.assetId} / ${l.asset.revisionId}`,"mono"));let b=k("input");b.required=!0,b.value=As("kiln.reviewer")??"",b.maxLength=200;let m=k("label","Reviewer","field");m.append(b);let g=k("select");for(let[A,E]of[["comment","Comment"],["changes-requested","Changes requested"],["accepted","Visually accepted"]])g.append(new Option(E,A));let p=k("label","Assessment","field");p.append(g);let x=k("textarea");x.rows=4,x.maxLength=4000;let _=k("label","Notes","field");_.append(x);let y=k("p");y.setAttribute("role","status");let v=k("button","Save review");v.type="submit";let T=k("button","Cancel","secondary");T.type="button",T.onclick=()=>u.close(),f.append(m,p,_,y,v,T),d.append(f),u.append(d),document.body.append(u),u.addEventListener("close",()=>u.remove()),d.onsubmit=async(A)=>{A.preventDefault(),v.disabled=!0,y.textContent="Saving review…";try{await un(`/api/projects/${encodeURIComponent(c.projectId)}`,{method:"PATCH",body:{expectedRevision:c.revisionId,patch:{reviews:[...c.reviews,{id:`review_${crypto.randomUUID().replaceAll("-","")}`,inventoryId:l.id,projectRevisionId:c.revisionId,asset:l.asset,reviewer:b.value.trim(),verdict:g.value,notes:x.value}]}}}),Hi("kiln.reviewer",b.value.trim()),u.close(),await s()}catch(E){y.textContent=E instanceof Error?E.message:String(E)}finally{v.disabled=!1}},u.showModal(),b.focus()}return ue("new-project").onclick=()=>a(),ue("close-project-editor").onclick=()=>ue("project-editor").close(),ue("project-form").onsubmit=async(c)=>{c.preventDefault();let l=ue("save-project");l.disabled=!0,ue("project-save-status").textContent="Saving revision…";try{let u=CR(ue("project-config").value,{name:ue("project-name").value,brief:ue("project-brief").value,style:ue("project-style").value,scale:ue("project-scale").value});n=(await un(i?`/api/projects/${encodeURIComponent(i.projectId)}`:"/api/projects",i?{method:"PATCH",body:{expectedRevision:i.revisionId,patch:u}}:{method:"POST",body:u})).projectId,Hi("kiln.project",n),ue("project-editor").close(),Rn("Project revision saved."),await s()}catch(u){ue("project-save-status").textContent=u instanceof Error?u.message:String(u)}finally{l.disabled=!1}},{refresh:s}}var yB="Raw map pixels · unshaded · not GPU capture evidence",ub=/^[a-z][a-z0-9_-]{0,79}$/,db=/^sha256:[a-f0-9]{64}$/;function Pl(e){let t=new URLSearchParams(e.startsWith("?")?e:e.slice(e.indexOf("?")+1)),n=t.get("material"),i=t.get("materialRevision");if(t.getAll("material").length!==1||t.getAll("materialRevision").length!==1||!n||!i||!ub.test(n)||!db.test(i))return;return{materialId:n,revisionId:i}}function Sf(e){if(!ub.test(e.materialId)||!db.test(e.revisionId))throw Error("Invalid exact material selection");return`/?${new URLSearchParams({material:e.materialId,materialRevision:e.revisionId})}`}function fb(e){if(!ub.test(e.materialId)||!db.test(e.revisionId))throw Error("Invalid exact material selection");return`/api/materials/${encodeURIComponent(e.materialId)}/${encodeURIComponent(e.revisionId)}`}function PR(e){let t=ro(e),n=fb(t),i=t.maps.map((r)=>{let s="recipe"in r?r:void 0,a=s?.recipe?.kind==="atlas"?s.recipe:void 0;return{slot:r.slot,file:r.file,url:`${n}/${encodeURIComponent(r.file)}`,width:r.width,height:r.height,colorSpace:r.colorSpace,imageSha256:r.sha256,..."pixelHash"in r?{pixelHash:r.pixelHash}:{},..."sampler"in r?{sampler:{...r.sampler}}:{},atlas:!!a,...s?.recipe?{compilerId:s.recipe.compilerId}:{},...a?{manifestHash:a.manifest.manifestHash}:{},regions:a?a.manifest.regions.map((o)=>({name:o.name,content:{...o.content},allocation:{...o.allocation},leftPercent:o.content.x/r.width*100,topPercent:o.content.y/r.height*100,widthPercent:o.content.width/r.width*100,heightPercent:o.content.height/r.height*100})):[]}});return{materialId:t.materialId,revisionId:t.revisionId,name:t.name,fidelity:yB,maps:i}}function OR(e,t){if(!e||typeof e!=="object"||Array.isArray(e)||e.artifactGlbSha256!==t)throw Error("Retained evaluation does not identify the displayed artifact");let n=e.materialLibraryDependencies;if(n===void 0)return[];if(!Array.isArray(n)||n.length>16)throw Error("Invalid retained material dependency list");let i=new Map;for(let r of n){let s=ro(r),a=`${s.materialId}/${s.revisionId}`,o=i.get(a);if(o&&Cn(o)!==Cn(s))throw Error("Conflicting retained material identity");i.set(a,s)}return[...i.values()]}function Mf(e){let t=PR(e),n=k("section",void 0,"material-inspection");n.setAttribute("aria-label",`${t.name}: exact material maps`),n.append(k("p",`${t.materialId} · ${t.revisionId}`,"mono"),k("p",t.fidelity,"subtle"));let i=k("div",void 0,"material-inspection-controls"),r=(v,T)=>{let A=k("label",v,"inline-field");return A.append(T),i.append(A),T},s=r("Map",k("select"));for(let v of t.maps)s.append(new Option(`${v.slot}${v.atlas?" · atlas":""}`,v.slot));let a=r("Backdrop",k("select"));for(let v of["checker","light","dark"])a.append(new Option(v[0].toUpperCase()+v.slice(1),v));let o=r("Pixel zoom",k("select"));for(let v of[1,2,4])o.append(new Option(`${v}×`,String(v)));let c=k("div",void 0,"material-pixel-frame"),l=k("div",void 0,"material-pixel-sheet");c.dataset.backdrop="checker",c.tabIndex=0;let u=k("img");u.className="material-pixel-image",u.loading="lazy",u.draggable=!1;let d=k("div",void 0,"material-region-overlay"),f=k("label","Region overlays","inline-field"),h=k("input");h.type="checkbox",h.checked=!1,f.append(h),i.append(f),h.onchange=()=>{d.hidden=!h.checked},l.append(u,d),c.append(l);let b=k("p",void 0,"subtle");b.setAttribute("role","status");let m=k("dl"),g=k("div",void 0,"material-region-list"),p=k("a","Open this saved material revision");p.href=Sf(t),p.target="_blank",p.rel="noopener",n.append(i,c,b,m,g,p);let x=t.maps[0],_=()=>{l.style.width=`${x.width*Number(o.value)}px`,l.style.height=`${x.height*Number(o.value)}px`},y=()=>{x=t.maps.find((T)=>T.slot===s.value)??t.maps[0],f.hidden=!x.atlas,d.hidden=!x.atlas||!h.checked,b.textContent="Loading exact saved map…",u.alt=`${t.name}: ${x.slot}${x.atlas?" atlas sheet":""}, raw unshaded pixels`,u.width=x.width,u.height=x.height,u.src=x.url,_(),m.replaceChildren();let v=(T,A)=>m.append(k("dt",T),k("dd",A));if(v("Image",`${x.width} × ${x.height} · ${x.colorSpace} · nearest pixel display`),v("Sampling declaration",x.sampler?`${x.sampler.minFilter} / ${x.sampler.magFilter} · ${x.sampler.wrapS} / ${x.sampler.wrapT}`:"Not recorded in V1"),v("PNG hash",x.imageSha256),x.pixelHash)v("Decoded RGBA hash",x.pixelHash);if(x.compilerId)v("Compiler",x.compilerId);if(x.manifestHash)v("Atlas manifest hash",x.manifestHash);if(d.replaceChildren(),g.replaceChildren(),x.atlas){g.append(k("h4","Atlas regions · top-left pixel coordinates"));for(let T of x.regions){let A=k("span",void 0,"material-region-box");A.style.left=`${T.leftPercent}%`,A.style.top=`${T.topPercent}%`,A.style.width=`${T.widthPercent}%`,A.style.height=`${T.heightPercent}%`,A.append(k("span",T.name)),A.setAttribute("aria-hidden","true"),d.append(A);let E=k("button",`${T.name}: content ${T.content.x},${T.content.y} ${T.content.width}×${T.content.height}; allocation ${T.allocation.x},${T.allocation.y} ${T.allocation.width}×${T.allocation.height}`,"secondary");E.type="button",E.setAttribute("aria-pressed","false"),E.onclick=()=>{for(let w of d.children)w.classList.remove("selected");for(let w of g.querySelectorAll("button"))w.setAttribute("aria-pressed","false");if(A.classList.add("selected"),E.setAttribute("aria-pressed","true"),!d.hidden)A.scrollIntoView({block:"nearest",inline:"nearest"})},g.append(E)}}};return u.onload=()=>{b.textContent="Raw map loaded. These pixels are not a shaded capture."},u.onerror=()=>{b.textContent=`Exact ${t.materialId} revision map unavailable. No newer revision was substituted.`},s.onchange=y,a.onchange=()=>{c.dataset.backdrop=a.value},o.onchange=_,y(),n}function kR(e){if(!e.presetId.trim())throw Error("Choose a material preset");if(!e.seed.trim())throw Error("Enter an explicit seed");let t=Number(e.seed),n=Number(e.size);if(!Number.isInteger(t)||t<-2147483648||t>2147483647)throw Error("Seed must be a signed 32-bit integer");if(![64,128,256,512].includes(n))throw Error("Choose a supported map size");if(!e.creator.trim()||!e.spdx.trim()||!e.url.trim())throw Error("Creator and license details are required");let i=new URL(e.url.trim());if(i.protocol!=="https:"&&i.protocol!=="http:")throw Error("License URL must be HTTP(S)");return{presetId:e.presetId,seed:t,size:n,creator:e.creator.trim(),license:{spdx:e.spdx.trim(),url:e.url.trim(),attribution:e.attribution}}}function DR(e){let t=[],n=[],i=[],r=ue("materials-project"),s=k("button","Create from preset");ue("materials-refresh").before(s);let a=k("dialog");a.setAttribute("aria-labelledby","material-preset-heading");let o=k("form"),c=k("div",void 0,"detail-top"),l=k("h2","Create a material resource");l.id="material-preset-heading";let u=k("button","Cancel","secondary");u.type="button",u.onclick=()=>a.close(),c.append(l,u);let d=k("div",void 0,"editor-content");d.append(k("p","Offline starting recipes with editable layers and height-derived normals. Choose an explicit seed and provenance for the resource. Map images are not shaded material previews.","subtle"));function f(S,I){let U=k("label",S,"field");return U.append(I),d.append(U),I}let h=f("Preset",k("select")),b=k("p",void 0,"subtle");d.append(b);let m=f("Seed",k("input"));m.type="number",m.step="1",m.required=!0,m.min="-2147483648",m.max="2147483647",m.value="0";let g=f("Map size",k("select"));for(let S of[64,128,256,512])g.append(new Option(`${S} × ${S}`,String(S)));g.value="256";let p=f("Creator",k("input"));p.required=!0,p.maxLength=1000;let x=f("License identifier",k("input"));x.required=!0,x.placeholder="For example, CC0-1.0";let _=f("License URL",k("input"));_.type="url",_.required=!0;let y=f("Attribution text",k("textarea"));y.rows=2;let v=k("p");v.setAttribute("role","status");let T=k("button","Create resource");T.type="submit",d.append(v,T),o.append(c,d),a.append(o),document.body.append(a);let A=()=>{let S=i.find((I)=>I.id===h.value);b.textContent=S?`${S.description} Repeat scale: ${S.physicalSizeMeters.width} × ${S.physicalSizeMeters.height} m.`:""};h.onchange=A,s.onclick=async()=>{s.disabled=!0;try{i=(await un("/api/material-presets")).presets,h.replaceChildren(...i.map((S)=>new Option(S.name,S.id))),A(),v.textContent="",T.disabled=!i.length,a.showModal()}catch(S){Rn(S)}finally{s.disabled=!1}},o.onsubmit=async(S)=>{S.preventDefault(),T.disabled=!0,v.textContent="Creating immutable material resource…";try{let I=kR({presetId:h.value,seed:m.value,size:g.value,creator:p.value,spdx:x.value,url:_.value,attribution:y.value}),U=await un("/api/materials/preset",{method:"POST",body:I});await P(),a.close(),Rn(`${U.material.name} created at ${U.material.revisionId}. Ready for standalone assets. You can also lock this revision to an optional project.`)}catch(I){v.textContent=I instanceof Error?I.message:String(I)}finally{T.disabled=!1}};let E=fb;function w(){let S=n.find((D)=>D.projectId===r.value),I=ue("material-dependencies");if(I.replaceChildren(),S)if(I.append(k("h2",`${S.name}: locked resources`)),!S.materialDependencies.length)I.append(k("p","No materials are locked to this project yet. Select a resource revision below or configure dependencies with your agent.","subtle"));else{let D=k("table"),O=k("thead"),K=k("tr"),B=k("tbody");for(let q of["Resource / role","Exact revision","Local availability"])K.append(k("th",q));O.append(K),D.append(O);for(let q of S.materialDependencies){let le=t.find((pe)=>pe.materialId===q.resourceId&&pe.revisionId===q.revisionId),de=k("tr"),Me=k("td",q.resourceId);Me.append(k("small",q.role??S.design.materialRoles.filter((pe)=>pe.resourceId===q.resourceId).map((pe)=>pe.role).join(", "))),de.append(Me,k("td",q.revisionId,"mono"),k("td",le&&le.revisionId===q.sha256?"Exact local record available":le?"Dependency hash differs":"Not in local catalog")),B.append(de)}D.append(B);let X=k("div",void 0,"table-wrap");X.append(D),I.append(X)}let U=ue("material-list");U.replaceChildren();let N=ue("material-search").value.trim().toLowerCase(),F=t.filter((D)=>`${D.name} ${D.materialId} ${D.tags.join(" ")} ${D.sources.map((O)=>O.provider).join(" ")}`.toLowerCase().includes(N));if(ue("material-count").textContent=`${F.length} material revision${F.length===1?"":"s"}`,!F.length){U.append(Ko(N?"No matching materials":"Your material catalog starts here",N?"Try another material name, tag or provider.":"Materials added through Kiln appear here with their map roles, source records and exact revisions."));return}for(let D of F){let O=k("article",void 0,"material-card"),K=D.maps.find((L)=>L.slot==="baseColor")??D.maps[0];if(K){let L=k("img");L.src=`${E(D)}/${encodeURIComponent(K.file)}`,L.alt=`${D.name}: ${K.slot} map, not a shaded material preview`,L.loading="lazy",L.className="material-map",O.append(L,k("p",`${K.slot} map · unshaded`,"subtle"))}O.append(k("h3",D.name),k("p",D.tags.join(" · "),"subtle"));let B=k("dl"),X=(L,W)=>B.append(k("dt",L),k("dd",W));X("Revision",D.revisionId),X("Physical scale",D.physicalSizeMeters?`${D.physicalSizeMeters.width} × ${D.physicalSizeMeters.height} m`:"Not specified"),X("Tiling",D.tileable?"Declared tileable":"Not declared tileable"),X("Maps",D.maps.map((L)=>`${L.slot} ${L.width}×${L.height} (${L.colorSpace})`).join(" · ")),X("Surface factors",`Roughness ×${D.parameters.roughness} · Metalness ×${D.parameters.metalness}${D.maps.some((L)=>L.slot==="metallicRoughness")?" · multiplied by packed map channels":""}`),O.append(B);for(let L of D.sources){let W=k("p",`${L.provider} · ${L.creator} · ${L.kind}`,"subtle"),ne=k("a",L.license.spdx);if(ne.href=L.license.url,ne.target="_blank",ne.rel="noreferrer",W.append(document.createTextNode(" · "),ne),L.assetUrl){let ie=k("a","Source");ie.href=L.assetUrl,ie.target="_blank",ie.rel="noreferrer",W.append(document.createTextNode(" · "),ie)}if(O.append(W),L.license.attribution)O.append(k("p",L.license.attribution,"subtle"))}let q=k("div",void 0,"material-map-links");for(let L of D.maps){let W=k("a",L.slot);W.href=`${E(D)}/${encodeURIComponent(L.file)}`,W.target="_blank",W.rel="noopener",q.append(W)}O.append(q);let le=k("details",void 0,"material-map-inspection");le.append(k("summary","Inspect maps and atlas regions"));let de=!1;le.ontoggle=()=>{if(le.open&&!de)de=!0,le.append(Mf(D))};let Me=Pl(location.search);if(Me?.materialId===D.materialId&&Me.revisionId===D.revisionId)le.open=!0,O.dataset.selectedMaterial="true";O.append(le);let pe=S?.materialDependencies.find((L)=>L.resourceId===D.materialId),J=k("button",pe?.revisionId===D.revisionId?"Locked to project":pe?"Use this revision":"Add to project","secondary");if(J.disabled=!S||pe?.revisionId===D.revisionId,!S)J.title="Select a project to add a material dependency";J.onclick=async()=>{if(!S)return;J.disabled=!0;try{let L=S.materialDependencies.filter((W)=>W.resourceId!==D.materialId);L.push({resourceId:D.materialId,revisionId:D.revisionId,sha256:D.revisionId,...pe?.role?{role:pe.role}:{}}),await un(`/api/projects/${encodeURIComponent(S.projectId)}`,{method:"PATCH",body:{expectedRevision:S.revisionId,patch:{materialDependencies:L}}}),Rn(`${D.name} is locked to ${S.name} at this exact revision.`),await e()}catch(L){Rn(L),J.disabled=!1}},O.append(J,Wo("Map recipes, transformations and provenance",D)),U.append(O)}}let P=async()=>{t=(await un("/api/materials")).materials,w();let S=Pl(location.search);if(S&&!t.some((I)=>I.materialId===S.materialId&&I.revisionId===S.revisionId))Rn(`Exact material revision unavailable: ${S.materialId} at ${S.revisionId}. No newer revision was selected.`)};return ue("material-search").oninput=w,r.onchange=w,ue("materials-refresh").onclick=()=>void P().catch(Rn),{refresh:P,projects(S){n=S;let I=r.value;r.replaceChildren(new Option("All materials",""));for(let U of n)r.append(new Option(U.name,U.projectId));if(n.some((U)=>U.projectId===I))r.value=I;w()}}}function hb(e,t,n){return n?`${n.triangles.toLocaleString()} triangles displayed · ${t}`:`${e.triangles.toLocaleString()} triangles · ${e.meshes} meshes · ${t}`}var LR=(e,t)=>e.startedAt.localeCompare(t.startedAt)||e.operationId.localeCompare(t.operationId);function Ol(e,t){let n=new Map(e.operations.map((c)=>[c.operationId,c])),i=t.map((c)=>{let l=n.get(c.operationId);return l&&l.revision>c.revision?l:c}).sort(LR),r=(c)=>i.find((l)=>l.operationId===c?.operationId)??c,s=e.following?i.at(-1):r(e.selected),a=(c)=>!!c&&!!s&&c.projectId===s.projectId&&c.workId===s.workId&&LR(c,s)<=0&&(c.sessionId===s.sessionId||e.following&&e.crossRunContinuity===!0&&!!s.workId),o=s?.artifact?s:s?i.filter((c)=>c.artifact&&a(c)).at(-1)??(a(e.displayed)?e.displayed:void 0):void 0;return{...e,operations:i,selected:s,displayed:o,pinned:r(e.pinned)}}function pb(e,t){return Ol({...e,following:!1,selected:e.operations.find((n)=>n.operationId===t)??e.selected},e.operations)}function Zs(e,t){return e?.artifact&&t?.artifact&&e.operationId===t.operationId&&e.revision===t.revision&&e.artifact.sha256===t.artifact.sha256?t:void 0}function FR(e,t,n,i){if(e.status!=="complete"||!e.artifact)throw Error("Save requires a completed operation with an artifact.");if(!Zs(e,Zs(i,n)))throw Error("The visible artifact changed or has not loaded. Close this dialog and review it before saving.");let r=t.trim();if(!r||r.length>200)throw Error("Choose an asset name of 1–200 characters.");return{path:`/api/live/${encodeURIComponent(e.operationId)}/save`,body:{expectedRevision:e.revision,name:r,collection:"project"}}}function Rf(e,t,n,i){let r;e.onclick=async()=>{let s=n();if(!s){t.replaceChildren(k("p","Load an artifact before measuring.","subtle"));return}e.disabled=!0,t.replaceChildren(k("p","Measuring frame pacing for 3 seconds. Keep this viewport visible and the camera steady.","subtle"));try{let a=await xw(()=>s.measure(3000),i),o=k("div",void 0,"evidence-card");o.append(k("h3","Exploratory browser measurement"),k("p","Other workloads are not controlled. This sample is not an isolated performance baseline or budget acceptance."),k("strong",`p50 ${a.frameMs.p50.toFixed(1)} ms · p95 ${a.frameMs.p95.toFixed(1)} ms`),k("p",`${a.frameMs.samples} frame intervals · ${(a.windowMs/1000).toFixed(2)} s · ${a.drawCalls} draws · ${a.triangles.toLocaleString()} rendered triangles`),k("p",`${a.geometryObjects} geometry objects · ${a.textureObjects} texture objects. These counts are not GPU memory bytes.`),k("p",`GLB parse to first frame submission: ${a.loadToFirstFrameMs?.toFixed(1)??"unavailable"} ms. Download time excluded.`),k("p",`${a.viewport.cssWidth}×${a.viewport.cssHeight} CSS pixels · DPR ${a.viewport.devicePixelRatio.toFixed(2)}. Frame pacing includes browser scheduling and vertical sync, not GPU execution timing.`));let c=Wo("Exact measurement receipt and limitations",a);if(r)URL.revokeObjectURL(r);r=URL.createObjectURL(new Blob([JSON.stringify(a,null,2)],{type:"application/json"}));let l=k("a","Download measurement receipt");l.href=r,l.download="kiln-viewer-performance.json",o.append(c,l),t.replaceChildren(o)}catch(a){t.replaceChildren(k("p",a instanceof Error?a.message:String(a),"subtle"))}finally{e.disabled=!1}}}function mb(e,t,n,i){let r=e.inventory.find((a)=>a.id===t);if(!r&&!n)throw Error("Inventory item not found");let s=e.inventory.map((a)=>{if(a.id!==t)return a;let{asset:o,...c}=a;return n?{...c,asset:n}:c});if(!r&&n)s.push({id:t,name:i,kind:"asset",brief:"",references:[],asset:n});return{inventory:s}}async function kl(e,t,n,i){e.replaceChildren(k("h3","Project membership"));let{projects:r}=await un("/api/projects");if(!e.isConnected)return;let s=k("div");e.append(s);let a=k("p");a.setAttribute("role","status");let o=()=>kl(e,t,n,i);for(let m of r)for(let g of m.inventory){if(!g.asset||g.asset.collectionId!==t.collectionId||g.asset.assetId!==t.assetId)continue;let p=k("div",void 0,"membership-row");p.append(k("span",`${m.name} / ${g.name} · ${Tn(g.asset.revisionId)}${g.asset.revisionId===t.revisionId?" · this revision":" · another revision"}`));let x=k("button","Remove membership","secondary");x.onclick=async()=>{x.disabled=!0;try{await un(`/api/projects/${encodeURIComponent(m.projectId)}`,{method:"PATCH",body:{expectedRevision:m.revisionId,patch:mb(m,g.id,null,n)}}),await i(),await o()}catch(_){a.textContent=`${_ instanceof Error?_.message:_} Reopen membership to load the current project.`,x.disabled=!1}},p.append(x),s.append(p)}if(!s.childElementCount)s.append(k("p","This asset is standalone. Project membership is optional.","subtle"));if(!r.length){s.append(k("p","Create a named project in Projects to organize related assets."));return}let c=k("form"),l=k("select"),u=k("select"),d=k("label","Project","field"),f=k("label","Inventory item","field");d.append(l),f.append(u);for(let m of r)l.append(new Option(m.name,m.projectId));let h=()=>{let m=r.find((p)=>p.projectId===l.value);u.replaceChildren(new Option("Add as a new inventory item",""));for(let p of m.inventory)u.append(new Option(`${p.name}${p.asset?" (replace linked revision)":""}`,p.id));let g=m.inventory.find((p)=>p.asset?.collectionId===t.collectionId&&p.asset.assetId===t.assetId);if(g)u.value=g.id};l.onchange=h,h();let b=k("button","Link this exact revision");b.type="submit",c.append(d,f,k("p","Linking preserves the saved asset and its original build provenance. Replacing a link advances only this project.","subtle"),b,a),c.onsubmit=async(m)=>{m.preventDefault(),b.disabled=!0;let g=r.find((x)=>x.projectId===l.value),p=u.value||`asset_${crypto.randomUUID().replaceAll("-","")}`;try{await un(`/api/projects/${encodeURIComponent(g.projectId)}`,{method:"PATCH",body:{expectedRevision:g.revisionId,patch:mb(g,p,t,n)}}),await i(),await o()}catch(x){a.textContent=`${x instanceof Error?x.message:x} Reopen membership to load the current project.`,b.disabled=!1}},s.append(c)}function UR(){let e={following:!0,crossRunContinuity:!0,operations:[]},t=[],n="",i=0,r=!1,s,a=0,o,c,l,u,d,f,h,b=0,m=0,g=!1,p=!1,x,_=ue("live-project"),y=ue("live-source"),v=(L)=>y.value?`${L}${L.includes("?")?"&":"?"}source=${encodeURIComponent(y.value)}`:L,T=ue("live-run"),A=ue("live-work"),E=()=>`kiln.live.selection.${y.value}.${_.value}.${A.value}.${T.value}`,w=()=>`kiln.live.pin.${y.value}`,P=()=>t.filter((L)=>(!T.value||L.sessionId===T.value)&&(!A.value||(A.value==="ungrouped"?!L.workId:L.workId===A.value))),S=(L,W)=>{let ne=ue("live-connection");ne.textContent=L?"Connected":"Reconnecting",ne.className=`pill ${L?"connected":"warning"}`,ue("connection-status").textContent=W};function I(){let L=A.value,W=[...new Set(t.flatMap((ce)=>ce.workId?[ce.workId]:[]))];if(A.replaceChildren(new Option("All authoring items",""),new Option("Ungrouped history","ungrouped"),...W.map((ce)=>new Option(ce,ce))),L==="ungrouped"||W.includes(L))A.value=L;let ne=T.value,ie=[...new Set(t.map((ce)=>ce.sessionId))];T.replaceChildren(new Option("All runs",""));for(let ce of ie){let _e=t.find((Re)=>Re.sessionId===ce);T.append(new Option(`${_e.transport} · ${Tn(ce)}`,ce))}if(ie.includes(ne))T.value=ne}function U(){let L=ue("live-timeline"),W=L.scrollTop,ne=L.contains(document.activeElement)?document.activeElement.dataset.operation:void 0;if(L.replaceChildren(),!e.operations.length){L.append(Ko("Nothing observed yet","Actual Kiln operations will appear here. There is no agent running state to infer."));return}for(let ie of[...e.operations].reverse()){let ce=k("button",void 0,`timeline-item ${ie.status}${e.selected?.operationId===ie.operationId?" selected":""}${ie.pinned?" pinned":""}`);ce.dataset.operation=ie.operationId;let _e=k("span",void 0,"timeline-meta");if(_e.append(k("span",ie.transport.toUpperCase()),k("time",new Date(ie.startedAt).toLocaleTimeString())),ce.append(_e,k("strong",ie.tool.replace(/^kiln_/,"")),k("small",`${ie.status} · ${ie.artifact?"artifact available":"no artifact"}`),k("small",ie.workId?`Item ${ie.workId}`:`Ungrouped · run ${Tn(ie.sessionId)}`)),ce.setAttribute("aria-label",`${ie.tool}, ${ie.status}, ${new Date(ie.startedAt).toLocaleString()}`),e.selected?.operationId===ie.operationId)ce.setAttribute("aria-current","true");if(ce.onclick=()=>{e=pb(e,ie.operationId),Hi(E(),ie.operationId),q()},L.append(ce),ne===ie.operationId)ce.focus({preventScroll:!0})}L.scrollTop=W}function N(L){let W=k("div",void 0,"evidence-card");W.append(k("h3","Capture fidelity"));let ne=L.viewFidelity,ie=ne&&typeof ne==="object"?ne:void 0;if(W.append(k("strong",ie?String(ie.delivered??"Reported"):"No capture receipt yet")),W.append(k("p",ie?.materialFaithful===!0?"Material-faithful capture reported.":ie?"Geometry evidence only. Do not use this capture to judge materials.":"The interactive viewport uses local browser lighting; it is not a recorded capture.")),ie?.degradeReason)W.append(k("p",String(ie.degradeReason)));if(ie?.rendererId)W.append(k("p",`Renderer: ${String(ie.rendererId)}`,"mono"));if(ie?.inputGlbSha256)W.append(k("p",`Capture input: ${String(ie.inputGlbSha256)}`,"mono"));if(ie)W.append(k("p",ie.exactArtifact===!0?"Receipt identifies the exact evaluated artifact.":"Capture does not claim exact artifact equivalence."));return W}function F(){let L=ue("live-evidence"),W=ue("live-downloads");L.replaceChildren(),W.replaceChildren();let ne=e.displayed;if(!ne?.artifact){x=void 0;return}let ie=k("div",void 0,"evidence-card");ie.append(k("h3","Selected observed artifact"),k("strong",`${(ne.artifact.bytes/1024).toFixed(0)} KB GLB`),k("p",ne.artifact.sha256,"mono"),k("p",`Source: ${ne.programRef??"See authored source download"}`,"mono")),L.append(ie,N(ne));let ce=`${y.value}/${ne.operationId}/${ne.artifact.sha256}`;if(x?.key!==ce){let _e=k("div",void 0,"evidence-card live-material-inspection"),Re=k("button","Inspect exact material inputs","secondary");_e.append(k("h3","Materials and atlas sheets"),k("p","Declared inputs for this displayed artifact. Raw sheets are unshaded; capture fidelity is reported separately."),Re),x={key:ce,card:_e},Re.onclick=async()=>{Re.disabled=!0;let Oe=k("p","Reading the displayed artifact evaluation…");Oe.setAttribute("role","status"),_e.append(Oe);try{let We=await un(v(`/api/live/${encodeURIComponent(ne.operationId)}/evaluation.json`));if(x?.key!==ce)return;let Ye=OR(We,ne.artifact.sha256);Oe.textContent=Ye.length?"Exact declared revisions. Map images require the matching record in this local material library.":"No saved material resource declarations in this artifact. Embedded textures can still be viewed in the viewport.";for(let Wt of Ye){let lt=k("details");lt.append(k("summary",`${Wt.name} · ${Wt.revisionId}`));let Lt=!1;lt.ontoggle=()=>{if(lt.open&&!Lt)Lt=!0,lt.append(Mf(Wt))},_e.append(lt)}}catch(We){if(x?.key!==ce)return;Oe.textContent=`Material inspection unavailable for this exact artifact: ${We instanceof Error?We.message:String(We)}`,Re.disabled=!1}}}if(L.append(x.card),ne.captures.length)for(let _e of ne.captures){let Re=k("div",void 0,"evidence-card");Re.append(k("h3",_e.name));let Oe=ne.viewFidelity&&typeof ne.viewFidelity==="object"?ne.viewFidelity:void 0;Re.append(k("p",Oe?.materialFaithful===!0?`Recorded capture · ${String(Oe.delivered??"material-faithful")}`:`Recorded capture · ${String(Oe?.delivered??"fidelity unreported")}. Materials are not verified.`,Oe?.materialFaithful===!0?"subtle":"warning"));let We=k("a"),Ye=k("img");Ye.src=_e.url,Ye.alt=`Recorded ${_e.name} for ${ne.tool}`,Ye.loading="lazy",We.href=_e.url,We.target="_blank",We.rel="noopener",We.append(Ye),Re.append(We,k("p",_e.sha256,"mono")),L.append(Re)}else{let _e=k("div",void 0,"evidence-card");_e.append(k("h3","Recorded captures"),k("p",ne.status==="evaluated"||ne.status==="running"?"Artifact is ready. Capture work may still be in progress.":"No capture image was retained for this operation.")),L.append(_e)}for(let[_e,Re,Oe]of[[ne.artifact.url,"Observed GLB","asset.glb"],[v(`/api/live/${encodeURIComponent(ne.operationId)}/source.kiln.js`),"Authored source","source.kiln.js"]]){let We=k("a",Re);We.href=_e,We.download=Oe,W.append(We)}W.append(k("p","These are the observed artifact and source. Use the saved Library revision for an editable bundle with resources or a separate runtime export. A live observation is not a saved release."))}function D(){let L=Zs(e.displayed,l);ue("pin-build").disabled=!L,Me.disabled=L?.status!=="complete"}function O(){if(d&&l)ue("live-stage-label").textContent=hb(d,Tn(l.operationId),o?.lod())}function K(){if(f&&u)ue("compare-stage-label").textContent=`Pinned · ${hb(f,Tn(u.operationId),c?.lod())}`}async function B(L){if(ue("live-panel").hidden)return;let W=++b;if(!Zs(L,l))o?.cancelMeasurement("The review selection changed. Measure the loaded revision again.");if(!L?.artifact){ue("live-performance").replaceChildren(),o?.dispose(),o=void 0,l=void 0,d=void 0,ue("live-level-field").hidden=!0,ue("live-lod").replaceChildren(),ue("live-lod").hidden=!0,ue("live-stage-status").textContent="No completed artifact available for this run.",ue("live-stage-label").textContent="Current",D();return}if(l?.artifact?.sha256===L.artifact.sha256){l=L,ue("live-stage-status").textContent="",O(),D();return}ue("live-stage-status").textContent=`Loading ${Tn(L.operationId)}…${l?` Previous artifact ${Tn(l.operationId)} remains visible; Save and Pin are unavailable until the selection loads.`:""}`;try{let ne=await fetch(L.artifact.url);if(!ne.ok)throw Error("This retained artifact is no longer available");let ie=new Uint8Array(await ne.arrayBuffer());if(W!==b)return;o??=_l(ue("live-stage"));let ce=await o.load(ie,{isCurrent:()=>W===b,onCommit:()=>{l=L},preserveView:l?.projectId===L.projectId&&(l?.sessionId===L.sessionId||e.following)});if(!ce||W!==b)return;ue("live-performance").replaceChildren(),l=L,d=ce,D();let _e=ue("live-level");if(ue("live-level-field").hidden=!ce.levels,vl(_e,ue("live-lod"),o,(Re)=>{if(Re!==void 0)c?.level(Re),h?.refresh(),K();O()}),o.wire(g),o.navigation(ue("live-navigation").value),ue("live-stage-status").textContent="",O(),c)c.setView(o.view())}catch(ne){if(W!==b)return;ue("live-stage-status").textContent=`${ne instanceof Error?ne.message:ne}.${l?` Previous artifact ${Tn(l.operationId)} remains visible. Save and Pin are unavailable for the unloaded selection.`:""}`,D()}}async function X(L){if(ue("live-panel").hidden)return;let W=++m;if(ue("compare-viewport").hidden=!L?.artifact,ue("review-viewports").classList.toggle("comparing",!!L?.artifact),!L?.artifact){c?.dispose(),c=void 0,u=void 0,f=void 0,h=void 0,ue("compare-lod").replaceChildren(),ue("compare-level-field").hidden=!0;return}if(u?.artifact?.sha256===L.artifact.sha256){u=L,K(),ue("compare-stage-status").textContent="";return}if(!u)ue("compare-stage-label").textContent="Comparison";ue("compare-stage-status").textContent=`Loading pinned ${Tn(L.operationId)}…`;try{let ne=await fetch(L.artifact.url);if(!ne.ok)throw Error("Pinned artifact unavailable");let ie=new Uint8Array(await ne.arrayBuffer());if(W!==m)return;c??=_l(ue("compare-stage"));let ce=await c.load(ie,{preserveView:!0,isCurrent:()=>W===m,onCommit:()=>{u=L}});if(!ce||W!==m)return;if(u=L,f=ce,o)c.setView(o.view());let _e=Number(ue("live-level").value||0);c.level(Number.isFinite(_e)?_e:0),ue("compare-level-field").hidden=!ce.levels,h=vl(ue("compare-level"),ue("compare-lod"),c,K),K(),c.wire(g),c.navigation(ue("live-navigation").value),ue("compare-stage-status").textContent=""}catch(ne){if(W===m)ue("compare-stage-status").textContent=`${ne instanceof Error?ne.message:String(ne)}.${u?` Previous comparison ${Tn(u.operationId)} remains visible.`:""}`}}function q(){U();let L=e.selected,W=e.displayed,ne=ue("follow-latest");ne.textContent=e.following?"Following latest":"Follow latest",ne.setAttribute("aria-pressed",String(e.following));let ie=ue("live-current-summary");if(ie.replaceChildren(),L){ie.append(k("h2",L.tool.replace(/^kiln_/,"")),k("p",`${L.status} · ${L.transport} · Run ${Tn(L.sessionId)} · ${new Date(L.updatedAt).toLocaleString()}`));let Re=k("div",void 0,"tags");if(L.projectId)Re.append(k("span",L.projectId,"tag"));for(let Oe of L.phases)Re.append(k("span",Oe.phase,"tag"));ie.append(Re)}else ie.append(k("h2","No build selected"),k("p","Run Kiln tools from your agent or CLI. Completed evaluations appear here automatically."));let ce=L&&"observationIssues"in L&&Array.isArray(L.observationIssues)?L.observationIssues.map(String):[],_e=[L?.error,...ce,L&&W&&L.operationId!==W.operationId?`Current ${L.status} operation has no retained artifact. Showing the last successful artifact ${Tn(W.operationId)} from run ${Tn(W.sessionId)}.`:"",L&&!e.operations.some((Re)=>Re.operationId===L.operationId)?"This selection is outside the current retained history. Its loaded view remains until you choose another build.":""].filter(Boolean);ue("live-failure").textContent=_e.join(" "),ue("live-failure").hidden=!_e.length,D(),ue("clear-pin").hidden=!e.pinned,ue("live-count").textContent=`${e.operations.length} retained operation${e.operations.length===1?"":"s"}`,ue("live-record").textContent=JSON.stringify({selected:L,displayedArtifactOperation:W?.operationId,pinnedOperation:e.pinned?.operationId},null,2),F(),B(W),X(e.pinned)}async function le(){if(r)return;r=!0;let L=i;try{let W=new URLSearchParams;if(_.value)W.set("project",_.value);if(n)W.set("cursor",n);let ne=await un(v(`/api/live?${W}`));if(L!==i)return;if(a=0,S(!0,"Connected · checks every 2 seconds"),n=ne.cursor,ue("live-history-note").textContent=`Up to ${ne.retention.maxOperations} operations`,ue("live-history-issues").textContent=ne.observationIssues?.join(" ")??"",ue("live-history-issues").hidden=!ne.observationIssues?.length,!ne.unchanged){if(t=ne.operations,I(),e=Ol(e,P()),!p){p=!0;let ie=As(E());if(ie&&e.operations.some((_e)=>_e.operationId===ie))e=pb(e,ie);let ce=As(w());e.pinned=t.find((_e)=>_e.operationId===ce&&_e.pinned)??[...t].reverse().find((_e)=>_e.pinned&&_e.artifact)}q()}}catch(W){a++,S(!1,`Connection lost. Retrying; retained views remain available. ${W instanceof Error?W.message:W}`)}finally{if(r=!1,s)clearTimeout(s);s=setTimeout(()=>void le(),document.hidden?1e4:Math.min(30000,2000*2**Math.min(a,4)))}}_.onchange=()=>{i++,n="",t=[],p=!1,T.replaceChildren(new Option("All runs","")),A.value="",e={following:!0,crossRunContinuity:!0,operations:[]},q(),le()},y.onchange=()=>{_.value="",e.pinned=void 0,_.dispatchEvent(new Event("change"))},un("/api/live-sources").then(({sources:L})=>{y.replaceChildren(...L.map((W)=>new Option(W.label,W.id)))}).catch(Rn),T.onchange=()=>{e=Ol({...e,selected:void 0,displayed:void 0,following:!0,crossRunContinuity:!T.value},P()),q()},A.onchange=()=>T.dispatchEvent(new Event("change")),ue("follow-latest").onclick=()=>{e=Ol({...e,following:!e.following},P()),Hi(E(),e.following?"":e.selected?.operationId??""),q()},ue("live-refresh").onclick=()=>{n="",le(),q()},ue("pin-build").onclick=async()=>{let L=Zs(e.displayed,l);if(!L?.artifact)return;let W=ue("pin-build");W.disabled=!0;try{await un(v(`/api/live/${encodeURIComponent(L.operationId)}/pin`),{method:"POST",body:{pinned:!0}}),e.pinned={...L,pinned:!0},Hi(w(),L.operationId),n="",q(),le()}catch(ne){Rn(ne),D()}},ue("clear-pin").onclick=async()=>{if(!e.pinned)return;try{await un(v(`/api/live/${encodeURIComponent(e.pinned.operationId)}/pin`),{method:"POST",body:{pinned:!1}}),e.pinned=void 0,Hi(w(),""),n="",q(),le()}catch(L){Rn(L)}},ue("live-frame").onclick=()=>{if(o?.reset(),o)c?.setView(o.view())},ue("live-wire").onclick=()=>{g=!g,o?.wire(g),c?.wire(g),ue("live-wire").setAttribute("aria-pressed",String(g))};let de=k("button","Match comparison camera","secondary");de.onclick=()=>{if(o)c?.setView(o.view())},ue("live-frame").parentElement?.append(de);let Me=k("button","Save exact artifact");Me.disabled=!0,ue("live-frame").parentElement?.prepend(Me);let pe=k("button","Measure 3 s","secondary"),J=k("div");return J.id="live-performance",ue("live-evidence").after(J),ue("live-frame").parentElement?.append(pe),Rf(pe,J,()=>o,()=>Zs(e.displayed,l)?{operationId:l.operationId,revision:l.revision,glbSha256:l.artifact?.sha256}:void 0),Me.onclick=()=>{let L=Zs(e.displayed,l);if(L?.status!=="complete")return;let W=k("dialog"),ne=k("form"),ie=k("div",void 0,"editor-content"),ce=k("h2","Save reviewed artifact");ce.id="save-review-title",W.setAttribute("aria-labelledby",ce.id),ie.append(ce,k("p","Save the exact source, GLB and recorded capture to Library. Then optionally link the saved revision to one or more named projects. Kiln will not evaluate the source again.","subtle"),k("p",`${L.operationId} · revision ${L.revision}`,"mono"),k("p",L.artifact.sha256,"mono"));let _e=k("input");_e.required=!0,_e.maxLength=200,_e.value="";let Re=k("label","Asset name","field");Re.append(_e);let Oe=k("p");Oe.setAttribute("role","status");let We=k("button","Save exact artifact");We.type="submit";let Ye=k("button","Cancel","secondary");Ye.type="button",Ye.onclick=()=>W.close(),ie.append(Re,Oe,We,Ye),ne.append(ie),W.append(ne),document.body.append(W),W.addEventListener("close",()=>W.remove()),ne.onsubmit=async(Wt)=>{Wt.preventDefault(),We.disabled=!0,Oe.textContent="Saving retained bytes…";try{let lt=FR(L,_e.value,l,e.displayed),Lt=await un(v(lt.path),{method:"POST",body:lt.body});Oe.replaceChildren(k("span",`Saved ${Lt.asset.assetId} / ${Lt.asset.revisionId}. `));let Qt=k("a","Open saved revision"),nn=new URLSearchParams({collection:Lt.collection,asset:Lt.asset.assetId,revision:Lt.asset.revisionId});Qt.href=`/?${nn}`,Oe.append(Qt);let z=k("div");ie.append(z),kl(z,{collectionId:Lt.collection,assetId:Lt.asset.assetId,revisionId:Lt.asset.revisionId},Lt.asset.name,async()=>{}).catch((yn)=>{z.textContent=`Asset saved; membership unavailable: ${yn instanceof Error?yn.message:yn}. Open the saved asset in Library to link it.`}),_e.disabled=!0,We.textContent="Saved",Ye.textContent="Close"}catch(lt){Oe.textContent=lt instanceof Error?lt.message:String(lt),We.disabled=!1}},W.showModal(),_e.focus()},ue("live-navigation").onchange=(L)=>{let W=L.target.value;o?.navigation(W),c?.navigation(W),ue("live-navigation-help").textContent=W==="explore"?"Focus a viewport, then W A S D to move · Q / E down / up · Shift faster · Drag to look around · No collision simulation.":"Drag to orbit · Scroll to zoom · Right-drag to pan · Your camera stays in place between iterations."},window.addEventListener("online",()=>{n="",le()}),document.addEventListener("visibilitychange",()=>{if(!document.hidden)le()}),le(),{activate:q,projects(L){let W=_.value;_.replaceChildren(new Option("All work",""));for(let ne of L)_.append(new Option(ne.name,ne.projectId));if(L.some((ne)=>ne.projectId===W))_.value=W}}}var gb=["projects","live","library","materials"];function BR(e,t){let n=new URLSearchParams(e);if(n.has("asset")||n.has("open"))return"library";if(Pl(e))return"materials";return t&&gb.some((i)=>i===t)?t:"library"}function zR(e,t=()=>{}){let n=gb;function i(c){if(!n.includes(c))return;for(let l of n)ue(`${l}-panel`).hidden=l!==c;for(let l of document.querySelectorAll("#workspace-nav button")){let u=l.dataset.section===c;if(l.classList.toggle("active",u),u)l.setAttribute("aria-current","page");else l.removeAttribute("aria-current")}if(Hi("kiln.section",c),c==="live")r.activate();if(c==="materials")s.refresh().catch(Rn)}for(let c of document.querySelectorAll("#workspace-nav button"))c.onclick=()=>i(c.dataset.section);ue("open-files").onclick=()=>ue("open").click();let r=UR(),s=DR(()=>a.refresh()),a=NR({changed:(c)=>{r.projects(c),s.projects(c),t(c)},openAsset:(c)=>{i("library"),e(c)}});i(BR(location.search,As("kiln.section"))),a.refresh().catch(Rn),s.refresh().catch(Rn);let o=!1;return window.setInterval(async()=>{if(document.hidden||o||ue("project-editor").open)return;o=!0;try{await a.refresh()}catch{}finally{o=!1}},5000),{library:()=>i("library"),refreshProjects:a.refresh}}var Er=(e)=>`${e.collection}/${e.manifest.assetId}`;function VR(e,t,n){if(!n)return e;if(n==="standalone"){let r=new Set(t.flatMap((s)=>s.inventory.flatMap((a)=>a.asset?[`${a.asset.collectionId}/${a.asset.assetId}`]:[])));return e.filter((s)=>!r.has(Er(s)))}let i=new Set(t.find((r)=>r.projectId===n)?.inventory.flatMap((r)=>r.asset?[`${r.asset.collectionId}/${r.asset.assetId}/${r.asset.revisionId}`]:[])??[]);return e.filter((r)=>i.has(`${Er(r)}/${r.manifest.revisionId}`))}var Ue=(e)=>document.getElementById(e),dt=(e,t,n)=>{let i=document.createElement(e);if(t!==void 0)i.textContent=t;if(n)i.className=n;return i},Ul=[],Fl=[],ta=[],Ua=[],If="",Qs,Tr,An,Ys=0,jR=0,Dl=!1,Ll=!1,ea=new Set,_b=[],HR=[],Kr=(e)=>`${e.collection}/${e.manifest.assetId}/${e.manifest.revisionId}`,xb=(e)=>{Ue("status").textContent=e},Ar=(e)=>xb(e instanceof Error?e.message:String(e)),Ba=(e,t,n=_b)=>{let i=URL.createObjectURL(new Blob([Uint8Array.from(e)],{type:t}));return n.push(i),i};async function yb(e){let t=await fetch(e),n=await t.json();if(!t.ok)throw Error(n.error??"Request failed");return n}async function bb(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/${Kr(e)}/${t}`);if(!n.ok)throw Error((await n.json()).error??"File unavailable");return new Uint8Array(await n.arrayBuffer())}function _B(e,t){if(e.local){if(t==="editable.zip")return Ba(rp([e.local]),"application/zip");return Ba(e.local.files[t],t.endsWith(".js")?"text/javascript":"model/gltf-binary")}if(e.loose)return Ba(e.loose,"model/gltf-binary");return`/files/${Kr(e)}/${t}?download`}function GR(e,t){try{localStorage.setItem(e,t)}catch{}}function vB(e){try{return localStorage.getItem(e)}catch{return null}}function EB(){let e=Ue("collections");e.replaceChildren();for(let t of[{id:"all",label:"All saved assets"},...Ul,...Ua.length?[{id:"opened-files",label:"Opened files"}]:[]]){let n=dt("button",t.label,If===t.id?"active":"");n.onclick=()=>void tc(t.id).catch(Ar),e.append(n)}}async function tc(e,t=!0){if(t)KR.library();let n=++jR;If=e,ea.clear(),EB(),xb("");let i=e==="all"?await(async()=>{let r=await yb("/api/library");if(r.errors.length)xb(r.errors.map((s)=>`${s.collectionId}: ${s.message}`).join(" · "));return r.entries.map((s)=>({collection:s.collectionId,manifest:s.manifest}))})():e==="opened-files"?Ua:(await yb(`/api/assets?collection=${encodeURIComponent(e)}`)).assets.map((r)=>({collection:e,manifest:r}));if(n!==jR)return;ta=i,GR("kiln.collection",e),Ue("collection-title").textContent=e==="all"?"Library":e==="opened-files"?"Opened files":Ul.find((r)=>r.id===e)?.label??e,Ue("collection-caption").textContent=e==="opened-files"?"Previewed in your browser. Your original files stay untouched.":"Saved assets across registered storage. Projects link exact revisions; standalone assets belong here too.",Cf()}function TB(){let e=new Map;for(let t of VR(ta,Fl,Ue("library-project").value)){let n=Er(t);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===vB(`kiln.revision.${n.collection}.${n.manifest.assetId}`))??t[0]))}function Cf(){for(let i of HR.splice(0))URL.revokeObjectURL(i);let e=Ue("cards");e.replaceChildren();let t=Ue("search").value.toLowerCase(),n=TB().filter((i)=>`${i.manifest.name} ${i.manifest.tags.join(" ")}`.toLowerCase().includes(t));if(Ue("count").textContent=`${n.length} asset${n.length===1?"":"s"}`,Ue("export-selection").disabled=!ea.size,!n.length){let i=dt("div",void 0,"empty");if(i.append(dt("b",t?"No matching assets":"Your next idea belongs here."),dt("p",t?"Try another name or tag.":"Save an asset with your agent, or open a GLB or editable bundle.")),!t)i.append(dt("code",'kiln save asset.kiln.js --name "My asset"'));e.append(i);return}for(let i of n){let r=i.manifest,s=dt("article",void 0,"card"),a=dt("button",void 0,"card-open");a.setAttribute("aria-label",`View ${r.name}`),a.onclick=()=>void Bl(i).catch(Ar);let o=dt("div",void 0,"thumb");if(r.files["preview.png"]){let b=dt("img");b.loading="lazy",b.alt=r.name,b.src=i.local?Ba(i.local.files["preview.png"],"image/png",HR):`/files/${Kr(i)}/preview.png`,b.onerror=()=>{b.remove(),o.textContent="◇"},o.append(b)}else o.textContent="◇";let c=dt("div",void 0,"card-content");c.append(dt("span",r.name,"card-title"));let l=ta.filter((b)=>Er(b)===Er(i)),u=new Set(l.map((b)=>b.manifest.parentRevision)),d=l.filter((b)=>!u.has(b.manifest.revisionId));c.append(dt("span",`${r.editable?"Editable source":"Source unavailable"} · ${l.length} revision${l.length===1?"":"s"}${d.length>1?` · ${d.length} branches`:""}`,"card-meta"));let f=dt("div",void 0,"tags");for(let b of r.tags)f.append(dt("span",b,"tag"));c.append(f),c.append(dt("small",Ul.find((b)=>b.id===i.collection)?.label??i.collection,"card-meta"));let h=Fl.filter((b)=>b.inventory.some((m)=>m.asset&&m.asset.collectionId===i.collection&&m.asset.assetId===r.assetId));if(c.append(dt("small",h.length?h.map((b)=>b.name).join(" · "):"No project membership","card-meta")),a.append(o,c),s.append(a),!i.loose){let b=dt("input");b.type="checkbox",b.className="selection",b.checked=ea.has(Kr(i)),b.setAttribute("aria-label",`Select ${r.name}`),b.onchange=()=>{if(b.checked)ea.add(Kr(i));else ea.delete(Kr(i));Ue("export-selection").disabled=!ea.size},s.append(b)}e.append(s)}}async function Bl(e){let t=++Ys;Qs=e,Tr=void 0,An?.cancelMeasurement("The Library selection changed. Measure the loaded revision again."),Ue("library-performance").replaceChildren(),GR(`kiln.revision.${e.collection}.${e.manifest.assetId}`,e.manifest.revisionId);for(let u of _b.splice(0))URL.revokeObjectURL(u);let n=Ue("detail");if(!n.open)n.showModal();Ue("asset-name").textContent=e.manifest.name;let i=Ue("asset-membership");if(i.replaceChildren(),!e.local&&!e.loose){let u=dt("div");i.append(u),kl(u,{collectionId:e.collection,assetId:e.manifest.assetId,revisionId:e.manifest.revisionId},e.manifest.name,KR.refreshProjects).catch(Ar)}let r=Ue("revisions");r.replaceChildren();for(let u of ta.filter((d)=>Er(d)===Er(e))){let d=dt("option",`${new Date(u.manifest.createdAt).toLocaleString()} · ${u.manifest.description||u.manifest.revisionId.slice(0,10)}`);d.value=u.manifest.revisionId,d.selected=u.manifest.revisionId===e.manifest.revisionId,r.append(d)}r.onchange=()=>{let u=ta.find((d)=>Er(d)===Er(e)&&d.manifest.revisionId===r.value);if(u)Bl(u).catch(Ar)},Ue("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.");let s=Ue("asset-attribution");s.replaceChildren();for(let u of lE(e.manifest)){let d=dt("div");d.append(dt("span",u.label),dt("strong",u.value)),s.append(d)}s.hidden=!s.childElementCount;let a=document.getElementById("asset-material-inputs");if(!a)a=dt("section",void 0,"asset-material-inputs"),a.id="asset-material-inputs",s.after(a);a.replaceChildren();try{let u=kc({manifest:e.manifest,files:{}});if(u.length){a.append(dt("h3","Exact material build inputs"),dt("p","Open the saved revision to inspect its raw maps, sampling declaration and atlas regions. Declared inputs do not prove every map was used.","subtle"));for(let d of u){let f=dt("a",`${d.name} · ${d.materialId}`);f.href=Sf(d),f.target="_blank",f.rel="noopener",a.append(f,dt("p",d.revisionId,"mono"))}}}catch(u){a.append(dt("p",`Material revision links unavailable: ${u instanceof Error?u.message:String(u)}`,"subtle"))}Ue("provenance").textContent=e.loose?"Standalone GLB. No source or build provenance supplied.":JSON.stringify(e.manifest,null,2);let o=Ue("downloads");o.replaceChildren();for(let[u,d]of[["asset.glb","Original GLB"],...e.manifest.editable?[["source.kiln.js","Download source"]]:[],...!e.loose?[["editable.zip",e.manifest.editable?"Download editable bundle":"Download asset bundle"]]:[]]){let f=dt("a",d);f.href=_B(e,u),f.download=`${e.manifest.name.replace(/[^a-z0-9_-]/gi,"-")}${u==="asset.glb"?".glb":u==="source.kiln.js"?".kiln.js":".zip"}`,o.append(f)}if(!e.loose){let u=dt("button","Runtime GLB"),d=dt("span");d.setAttribute("role","status"),u.onclick=async()=>{u.disabled=!0,d.textContent="Preparing runtime download…";try{let f=e.local?await ER(e.local,{profile:"runtime"}):void 0,[h,b]=f?.profile==="runtime"?[f.glb,f.metadata.bytes]:await Promise.all([bb(e,"runtime.glb"),bb(e,"runtime.kiln-metadata.json")]);if(t!==Ys)return;let m=dt("a","Runtime GLB");m.href=Ba(h,"model/gltf-binary"),m.download="runtime.glb";let g=dt("a","Runtime metadata");g.href=Ba(b,"application/json"),g.download="runtime.kiln-metadata.json",u.replaceWith(m,g),d.textContent="Keep the companion metadata for traceability.",m.click()}catch(f){if(t!==Ys)return;d.textContent=`Runtime export unavailable: ${f instanceof Error?f.message:f}`,u.disabled=!1}},o.append(u,d),o.append(dt("p","Original GLB retains Kiln review data. Runtime GLB moves duplicate animation-review data into a companion JSON file; geometry and textures are unchanged. Keep the editable bundle for source and build records."))}Ue("refine").disabled=!e.manifest.editable,Ue("asset-stats").replaceChildren(),Ue("stage-status").textContent="Loading saved GLB…",Dl=!1,Ll=!1,Ue("wire").setAttribute("aria-pressed","false"),Ue("play").textContent="Pause";let c=Ue("animation");c.replaceChildren(new Option("Rest pose","")),Ue("play").disabled=!0;let l=Ue("level");l.replaceChildren(),l.hidden=!0,Ue("library-lod").replaceChildren(),Ue("library-lod").hidden=!0;try{An??=_l(Ue("stage"));let u=await bb(e,"asset.glb");if(t!==Ys)return;let d=await An.load(u,{isCurrent:()=>t===Ys,onCommit:()=>{Tr=e}});if(!d||t!==Ys)return;Tr=e,An.wire(!1),An.navigation(Ue("library-navigation").value),An.lighting(Ue("lighting").value),vl(l,Ue("library-lod"),An);for(let[f,h]of[...d.levels?d.levels.map((b,m)=>[b.toLocaleString(),`LOD${m} triangles`]):[[d.triangles.toLocaleString(),"triangles"]],[d.meshes,d.levels?"LOD0 meshes":"meshes"],[d.materials,d.levels?"LOD0 materials":"materials"],[`${(u.length/1024).toFixed(0)} KB`,"GLB"]]){let b=dt("div");b.append(dt("strong",String(f)),dt("span",String(h))),Ue("asset-stats").append(b)}for(let f=0;f<d.clips.length;f++)c.append(new Option(d.clips[f],String(f)));Ue("stage-status").textContent=""}catch(u){if(t===Ys)An?.dispose(),An=void 0,Ue("stage-status").textContent=`3D preview unavailable: ${u instanceof Error?u.message:u}. Downloads remain available.`}}async function $R(e){for(let t of e){if(t.bytes.length>Kn)throw Error("File exceeds 64 MiB");if(t.name.toLowerCase().endsWith(".zip"))for(let n of cE(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((a)=>a.toString(16).padStart(2,"0")).join("")}`!==n.manifest.files[i]?.sha256)throw Error(`Bundle integrity failure: ${i}`);if(!Ua.some((i)=>i.manifest.revisionId===n.manifest.revisionId&&i.manifest.assetId===n.manifest.assetId))Ua.push({collection:"opened-files",manifest:n.manifest,local:n})}else{let n=`a_${crypto.randomUUID().replaceAll("-","")}`;Ua.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")}Ue("open").onchange=async(e)=>{try{let t=Array.from(e.target.files??[]);if(t.some((n)=>n.size>Kn))throw Error("File exceeds 64 MiB");await $R(await Promise.all(t.map(async(n)=>({name:n.name,bytes:new Uint8Array(await n.arrayBuffer())}))))}catch(t){Ar(t)}};Ue("refresh").onclick=()=>void tc(If).catch(Ar);Ue("search").oninput=Cf;Ue("library-project").onchange=()=>void tc("all").catch(Ar);Ue("close-detail").onclick=()=>Ue("detail").close();Ue("detail").addEventListener("close",()=>{Ys++,Tr=void 0,An?.dispose(),An=void 0;for(let e of _b.splice(0))URL.revokeObjectURL(e);Cf()});Ue("frame").onclick=()=>An?.reset();Ue("wire").onclick=()=>{Dl=!Dl,An?.wire(Dl),Ue("wire").setAttribute("aria-pressed",String(Dl))};Ue("lighting").onchange=(e)=>An?.lighting(e.target.value);Ue("library-navigation").onchange=(e)=>{let t=e.target.value;An?.navigation(t),Ue("library-navigation-help").textContent=t==="explore"?"Focus the viewport, then W A S D to move · Q / E down / up · Shift faster · Drag to look around · No collision simulation.":"Drag to orbit · Scroll to zoom · Right-drag to pan"};Ue("animation").onchange=(e)=>{let t=e.target.value;An?.clip(t===""?-1:Number(t)),Ue("play").disabled=t===""};Ue("play").onclick=()=>{Ll=!Ll,An?.pause(Ll),Ue("play").textContent=Ll?"Play":"Pause"};Ue("refine").onclick=async()=>{if(!Qs)return;let e=Qs.manifest,t=Qs.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=${Qs.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=${Qs.collection}. Requested change: `;try{await navigator.clipboard.writeText(t),Ue("refine").textContent="Instructions copied"}catch{Ue("provenance").textContent=t,Ue("provenance").parentElement?.setAttribute("open","")}};Ue("export-selection").onclick=()=>{try{let e=dt("a");if(If==="opened-files")e.href=Ba(rp(ta.filter((t)=>ea.has(Kr(t))).map((t)=>t.local)),"application/zip");else{let t=new URLSearchParams;for(let n of ea)t.append("revision",n);e.href=`/api/bundle?${t}`}e.download="kiln-assets.zip",e.click()}catch(e){Ar(e)}};async function AB(){Ul=(await yb("/api/collections")).collections;let e=Mw(location.search);if(await tc(Ul.find((t)=>t.id===e?.collection)?.id??"all",!1),e){let t=ta.find((n)=>n.collection===e.collection&&n.manifest.assetId===e.assetId&&n.manifest.revisionId===e.revisionId);if(!t)throw Error("The requested saved revision is not available.");await Bl(t)}if(new URLSearchParams(location.search).has("open")){let t=await fetch("/api/standalone");if(!t.ok)throw Error("File unavailable");if(await $R([{name:t.headers.get("Content-Type")?.includes("zip")?"asset.zip":"asset.glb",bytes:new Uint8Array(await t.arrayBuffer())}]),Ua.length===1)await Bl(Ua[0])}}var KR=zR((e)=>{(async()=>{await tc(e.collectionId);let t=ta.find((n)=>n.manifest.assetId===e.assetId&&n.manifest.revisionId===e.revisionId);if(!t)throw Error("The linked saved revision is not available in this collection.");await Bl(t)})().catch(Ar)},(e)=>{Fl=e;let t=Ue("library-project"),n=t.value;t.replaceChildren(new Option("All projects and standalone",""),new Option("Standalone assets","standalone"));for(let i of Fl)t.append(new Option(i.name,i.projectId));if(n==="standalone"||Fl.some((i)=>i.projectId===n))t.value=n;Cf()});Rf(Ue("measure-library"),Ue("library-performance"),()=>An,()=>Tr&&Qs&&Kr(Tr)===Kr(Qs)?{collection:Tr.collection,assetId:Tr.manifest.assetId,revisionId:Tr.manifest.revisionId,glbSha256:Tr.manifest.files["asset.glb"]?.sha256}:void 0);AB().catch(Ar);+*/var Zt=Uint8Array,ri=Uint16Array,Wh=Int32Array,Tu=new Zt([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]),Au=new Zt([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]),Vh=new Zt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),A0=function(e,t){var n=new ri(31);for(var i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new Wh(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}},w0=A0(Tu,2),{b:S0,r:jh}=w0;S0[28]=258,jh[258]=28;var M0=A0(Au,0),{b:bC,r:x0}=M0,Hh=new ri(32768);for(pt=0;pt<32768;++pt)er=(pt&43690)>>1|(pt&21845)<<1,er=(er&52428)>>2|(er&13107)<<2,er=(er&61680)>>4|(er&3855)<<4,Hh[pt]=((er&65280)>>8|(er&255)<<8)>>1;var er,pt,nr=function(e,t,n){var i=e.length,r=0,s=new ri(t);for(;r<i;++r)if(e[r])++s[e[r]-1];var a=new ri(t);for(r=1;r<t;++r)a[r]=a[r-1]+s[r-1]<<1;var o;if(n){o=new ri(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],d=a[e[r]-1]++<<u;for(var f=d|(1<<u)-1;d<=f;++d)o[Hh[d]>>c]=l}}else{o=new ri(i);for(r=0;r<i;++r)if(e[r])o[r]=Hh[a[e[r]-1]++]>>15-e[r]}return o},es=new Zt(288);for(pt=0;pt<144;++pt)es[pt]=8;var pt;for(pt=144;pt<256;++pt)es[pt]=9;var pt;for(pt=256;pt<280;++pt)es[pt]=7;var pt;for(pt=280;pt<288;++pt)es[pt]=8;var pt,vc=new Zt(32);for(pt=0;pt<32;++pt)vc[pt]=5;var pt,xC=nr(es,9,0),yC=nr(es,9,1),_C=nr(vc,5,0),vC=nr(vc,5,1),Fh=function(e){var t=e[0];for(var n=1;n<e.length;++n)if(e[n]>t)t=e[n];return t},Ii=function(e,t,n){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(t&7)&n},Uh=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Xh=function(e){return(e+7)/8|0},Ec=function(e,t,n){if(t==null||t<0)t=0;if(n==null||n>e.length)n=e.length;return new Zt(e.subarray(t,n))};var EC=["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"],Vn=function(e,t,n){var i=Error(t||EC[e]);if(i.code=e,Error.captureStackTrace)Error.captureStackTrace(i,Vn);if(!n)throw i;return i},TC=function(e,t,n,i){var r=e.length,s=i?i.length:0;if(!r||t.f&&!t.l)return n||new Zt(0);var a=!n,o=a||t.i!=2,c=t.i;if(a)n=new Zt(r*3);var l=function(ce){var _e=n.length;if(ce>_e){var Re=new Zt(Math.max(_e*2,ce));Re.set(n),n=Re}},u=t.f||0,d=t.p||0,f=t.b||0,{l:h,d:b,m,n:g}=t,p=r*8;do{if(!h){u=Ii(e,d,1);var x=Ii(e,d+1,3);if(d+=3,!x){var _=Xh(d)+4,y=e[_-4]|e[_-3]<<8,v=_+y;if(v>r){if(c)Vn(0);break}if(o)l(f+y);n.set(e.subarray(_,v),f),t.b=f+=y,t.p=d=v*8,t.f=u;continue}else if(x==1)h=yC,b=vC,m=9,g=5;else if(x==2){var E=Ii(e,d,31)+257,w=Ii(e,d+10,15)+4,T=E+Ii(e,d+5,31)+1;d+=14;var A=new Zt(T),P=new Zt(19);for(var S=0;S<w;++S)P[Vh[S]]=Ii(e,d+S*3,7);d+=w*3;var R=Fh(P),k=(1<<R)-1,C=nr(P,R,1);for(var S=0;S<T;){var U=C[Ii(e,d,k)];d+=U&15;var _=U>>4;if(_<16)A[S++]=_;else{var L=0,O=0;if(_==16)O=3+Ii(e,d,3),d+=2,L=A[S-1];else if(_==17)O=3+Ii(e,d,7),d+=3;else if(_==18)O=11+Ii(e,d,127),d+=7;while(O--)A[S++]=L}}var K=A.subarray(0,E),B=A.subarray(E);m=Fh(K),g=Fh(B),h=nr(K,m,1),b=nr(B,g,1)}else Vn(1);if(d>p){if(c)Vn(0);break}}if(o)l(f+131072);var X=(1<<m)-1,q=(1<<g)-1,le=d;for(;;le=d){var L=h[Uh(e,d)&X],de=L>>4;if(d+=L&15,d>p){if(c)Vn(0);break}if(!L)Vn(2);if(de<256)n[f++]=de;else if(de==256){le=d,h=null;break}else{var Me=de-254;if(de>264){var S=de-257,pe=Tu[S];Me=Ii(e,d,(1<<pe)-1)+S0[S],d+=pe}var J=b[Uh(e,d)&q],F=J>>4;if(!J)Vn(3);d+=J&15;var B=bC[F];if(F>3){var pe=Au[F];B+=Uh(e,d)&(1<<pe)-1,d+=pe}if(d>p){if(c)Vn(0);break}if(o)l(f+131072);var W=f+Me;if(f<B){var ne=s-B,ie=Math.min(B,W);if(ne+f<0)Vn(3);for(;f<ie;++f)n[f]=i[ne+f]}for(;f<W;++f)n[f]=n[f-B]}}if(t.l=h,t.p=le,t.b=f,t.f=u,h)u=1,t.m=m,t.d=b,t.n=g}while(!u);return f!=n.length&&a?Ec(n,0,f):n.subarray(0,f)},Cr=function(e,t,n){n<<=t&7;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8},yc=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},Bh=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:I0,l:0};if(r==1){var a=new Zt(n[0].s+1);return a[n[0].s]=1,{t:a,l:1}}n.sort(function(v,E){return v.f-E.f}),n.push({s:-1,f:25001});var o=n[0],c=n[1],l=0,u=1,d=2;n[0]={s:-1,f:o.f+c.f,l:o,r:c};while(u!=r-1)o=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:o.f+c.f,l:o,r:c};var f=s[0].s;for(var i=1;i<r;++i)if(s[i].s>f)f=s[i].s;var h=new ri(f+1),b=Gh(n[u-1],h,0);if(b>t){var i=0,m=0,g=b-t,p=1<<g;s.sort(function(E,w){return h[w.s]-h[E.s]||E.f-w.f});for(;i<r;++i){var x=s[i].s;if(h[x]>t)m+=p-(1<<b-h[x]),h[x]=t;else break}m>>=g;while(m>0){var _=s[i].s;if(h[_]<t)m-=1<<t-h[_]++-1;else++i}for(;i>=0&&m;--i){var y=s[i].s;if(h[y]==t)--h[y],++m}b=t}return{t:new Zt(h),l:b}},Gh=function(e,t,n){return e.s==-1?Math.max(Gh(e.l,t,n+1),Gh(e.r,t,n+1)):t[e.s]=n},y0=function(e){var t=e.length;while(t&&!e[--t]);var n=new ri(++t),i=0,r=e[0],s=1,a=function(c){n[i++]=c};for(var o=1;o<=t;++o)if(e[o]==r&&o!=t)++s;else{if(!r&&s>2){for(;s>138;s-=138)a(32754);if(s>2)a(s>10?s-11<<5|28690:s-3<<5|12305),s=0}else if(s>3){a(r),--s;for(;s>6;s-=6)a(8304);if(s>2)a(s-3<<5|8208),s=0}while(s--)a(r);s=1,r=e[o]}return{c:n.subarray(0,i),n:t}},_c=function(e,t){var n=0;for(var i=0;i<t.length;++i)n+=e[i]*t[i];return n},R0=function(e,t,n){var i=n.length,r=Xh(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},_0=function(e,t,n,i,r,s,a,o,c,l,u){Cr(t,u++,n),++r[256];var d=Bh(r,15),{t:f,l:h}=d,b=Bh(s,15),{t:m,l:g}=b,p=y0(f),{c:x,n:_}=p,y=y0(m),{c:v,n:E}=y,w=new ri(19);for(var T=0;T<x.length;++T)++w[x[T]&31];for(var T=0;T<v.length;++T)++w[v[T]&31];var A=Bh(w,7),{t:P,l:S}=A,R=19;for(;R>4&&!P[Vh[R-1]];--R);var k=l+5<<3,C=_c(r,es)+_c(s,vc)+a,U=_c(r,f)+_c(s,m)+a+14+3*R+_c(w,P)+2*w[16]+3*w[17]+7*w[18];if(c>=0&&k<=C&&k<=U)return R0(t,u,e.subarray(c,c+l));var L,O,K,B;if(Cr(t,u,1+(U<C)),u+=2,U<C){L=nr(f,h,0),O=f,K=nr(m,g,0),B=m;var X=nr(P,S,0);Cr(t,u,_-257),Cr(t,u+5,E-1),Cr(t,u+10,R-4),u+=14;for(var T=0;T<R;++T)Cr(t,u+3*T,P[Vh[T]]);u+=3*R;var q=[x,v];for(var le=0;le<2;++le){var de=q[le];for(var T=0;T<de.length;++T){var Me=de[T]&31;if(Cr(t,u,X[Me]),u+=P[Me],Me>15)Cr(t,u,de[T]>>5&127),u+=de[T]>>12}}}else L=xC,O=es,K=_C,B=vc;for(var T=0;T<o;++T){var pe=i[T];if(pe>255){var Me=pe>>18&31;if(yc(t,u,L[Me+257]),u+=O[Me+257],Me>7)Cr(t,u,pe>>23&31),u+=Tu[Me];var J=pe&31;if(yc(t,u,K[J]),u+=B[J],J>3)yc(t,u,pe>>5&8191),u+=Au[J]}else yc(t,u,L[pe]),u+=O[pe]}return yc(t,u,L[256]),u+O[256]},AC=new Wh([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),I0=new Zt(0),wC=function(e,t,n,i,r,s){var a=s.z||e.length,o=new Zt(i+a+5*(1+Math.ceil(a/7000))+r),c=o.subarray(i,o.length-r),l=s.l,u=(s.r||0)&7;if(t){if(u)c[0]=s.r>>3;var d=AC[t-1],f=d>>13,h=d&8191,b=(1<<n)-1,m=s.p||new ri(32768),g=s.h||new ri(b+1),p=Math.ceil(n/3),x=2*p,_=function(ke){return(e[ke]^e[ke+1]<<p^e[ke+2]<<x)&b},y=new Wh(25000),v=new ri(288),E=new ri(32),w=0,T=0,A=s.i||0,P=0,S=s.w||0,R=0;for(;A+2<a;++A){var k=_(A),C=A&32767,U=g[k];if(m[C]=U,g[k]=C,S<=A){var L=a-A;if((w>7000||P>24576)&&(L>423||!l)){u=_0(e,c,0,y,v,E,T,P,R,A-R,u),P=w=T=0,R=A;for(var O=0;O<286;++O)v[O]=0;for(var O=0;O<30;++O)E[O]=0}var K=2,B=0,X=h,q=C-U&32767;if(L>2&&k==_(A-q)){var le=Math.min(f,L)-1,de=Math.min(32767,A),Me=Math.min(258,L);while(q<=de&&--X&&C!=U){if(e[A+K]==e[A+K-q]){var pe=0;for(;pe<Me&&e[A+pe]==e[A+pe-q];++pe);if(pe>K){if(K=pe,B=q,pe>le)break;var J=Math.min(q,pe-2),F=0;for(var O=0;O<J;++O){var W=A-q+O&32767,ne=m[W],ie=W-ne&32767;if(ie>F)F=ie,U=W}}}C=U,U=m[C],q+=C-U&32767}}if(B){y[P++]=268435456|jh[K]<<18|x0[B];var ce=jh[K]&31,_e=x0[B]&31;T+=Tu[ce]+Au[_e],++v[257+ce],++E[_e],S=A+K,++w}else y[P++]=e[A],++v[e[A]]}}for(A=Math.max(A,S);A<a;++A)y[P++]=e[A],++v[e[A]];if(u=_0(e,c,l,y,v,E,T,P,R,A-R,u),!l)s.r=u&7|c[u/8|0]<<3,u-=7,s.h=g,s.p=m,s.i=A,s.w=S}else{for(var A=s.w||0;A<a+l;A+=65535){var Re=A+65535;if(Re>=a)c[u/8|0]=l,Re=a;u=R0(c,u+1,e.subarray(A,Re))}s.i=a}return Ec(o,0,i+Xh(u)+r)},SC=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}(),MC=function(){var e=-1;return{p:function(t){var n=e;for(var i=0;i<t.length;++i)n=SC[n&255^t[i]]^n>>>8;e=n},d:function(){return~e}}};var RC=function(e,t,n,i,r){if(!r){if(r={l:1},t.dictionary){var s=t.dictionary.subarray(-32768),a=new Zt(s.length+e.length);a.set(s),a.set(e,s.length),e=a,r.w=s.length}}return wC(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)},C0=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 tr=function(e,t){return e[t]|e[t+1]<<8},Ci=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},zh=function(e,t){return Ci(e,t)+Ci(e,t+4)*4294967296},Mn=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function IC(e,t){return RC(e,t||{},0,0)}function CC(e,t){return TC(e,{i:2},t&&t.out,t&&t.dictionary)}var N0=function(e,t,n,i){for(var r in e){var s=e[r],a=t+r,o=i;if(Array.isArray(s))o=C0(i,s[1]),s=s[0];if(s instanceof Zt)n[a]=[s,o];else n[a+="/"]=[new Zt(0),o],N0(s,a,n,i)}},v0=typeof TextEncoder<"u"&&new TextEncoder,$h=typeof TextDecoder<"u"&&new TextDecoder,NC=0;try{$h.decode(I0,{stream:!0}),NC=1}catch(e){}var PC=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:Ec(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 E0(e,t){if(t){var n=new Zt(e.length);for(var i=0;i<e.length;++i)n[i]=e.charCodeAt(i);return n}if(v0)return v0.encode(e);var r=e.length,s=new Zt(e.length+(e.length>>1)),a=0,o=function(u){s[a++]=u};for(var i=0;i<r;++i){if(a+5>s.length){var c=new Zt(a+8+(r-i<<1));c.set(s),s=c}var l=e.charCodeAt(i);if(l<128||t)o(l);else if(l<2048)o(192|l>>6),o(128|l&63);else if(l>55295&&l<57344)l=65536+(l&1047552)|e.charCodeAt(++i)&1023,o(240|l>>18),o(128|l>>12&63),o(128|l>>6&63),o(128|l&63);else o(224|l>>12),o(128|l>>6&63),o(128|l&63)}return Ec(s,0,a)}function OC(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($h)return $h.decode(e);else{var r=PC(e),{s,r:n}=r;if(n.length)Vn(8);return s}}var kC=function(e,t){return t+30+tr(e,t+26)+tr(e,t+28)},DC=function(e,t,n){var i=tr(e,t+28),r=OC(e.subarray(t+46,t+46+i),!(tr(e,t+8)&2048)),s=t+46+i,a=Ci(e,t+20),o=n&&a==4294967295?LC(e,s):[a,Ci(e,t+24),Ci(e,t+42)],c=o[0],l=o[1],u=o[2];return[tr(e,t+10),c,l,r,s+tr(e,t+30)+tr(e,t+32),u]},LC=function(e,t){for(;tr(e,t)!=1;t+=4+tr(e,t+2));return[zh(e,t+12),zh(e,t+4),zh(e,t+20)]},Kh=function(e){var t=0;if(e)for(var n in e){var i=e[n].length;if(i>65535)Vn(9);t+=i+4}return t},T0=function(e,t,n,i,r,s,a,o){var c=i.length,l=n.extra,u=o&&o.length,d=Kh(l);if(Mn(e,t,a!=null?33639248:67324752),t+=4,a!=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 f=new Date(n.mtime==null?Date.now():n.mtime),h=f.getFullYear()-1980;if(h<0||h>119)Vn(10);if(Mn(e,t,h<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,s!=-1)Mn(e,t,n.crc),Mn(e,t+4,s<0?-s-2:s),Mn(e,t+8,n.size);if(Mn(e,t+12,c),Mn(e,t+14,d),t+=16,a!=null)Mn(e,t,u),Mn(e,t+6,n.attrs),Mn(e,t+10,a),t+=14;if(e.set(i,t),t+=c,d)for(var b in l){var m=l[b],g=m.length;Mn(e,t,+b),Mn(e,t+2,g),e.set(m,t+4),t+=4+g}if(u)e.set(o,t),t+=u;return t},FC=function(e,t,n,i,r){Mn(e,t,101010256),Mn(e,t+8,n),Mn(e,t+10,n),Mn(e,t+12,i),Mn(e,t+16,r)};function P0(e,t){if(!t)t={};var n={},i=[];N0(e,"",n,t);var r=0,s=0;for(var a in n){var o=n[a],c=o[0],l=o[1],u=l.level==0?0:8,d=E0(a),f=d.length,h=l.comment,b=h&&E0(h),m=b&&b.length,g=Kh(l.extra);if(f>65535)Vn(11);var p=u?IC(c,l):c,x=p.length,_=MC();_.p(c),i.push(C0(l,{size:c.length,crc:_.d(),c:p,f:d,m:b,u:f!=a.length||b&&h.length!=m,o:r,compression:u})),r+=30+f+g+x,s+=76+2*(f+g)+(m||0)+x}var y=new Zt(s+22),v=r,E=s-r;for(var w=0;w<i.length;++w){var d=i[w];T0(y,d.o,d,d.f,d.u,d.c.length);var T=30+d.f.length+Kh(d.extra);y.set(d.c,d.o+T),T0(y,r,d,d.f,d.u,d.c.length,d.o,d.m),r+=16+T+(d.m?d.m.length:0)}return FC(y,r,i.length,E,v),y}function O0(e,t){var n={},i=e.length-22;for(;Ci(e,i)!=101010256;--i)if(!i||e.length-i>65558)Vn(13);var r=tr(e,i+8);if(!r)return{};var s=Ci(e,i+16),a=s==4294967295||r==65535;if(a){var o=Ci(e,i-12);if(a=Ci(e,o)==101075792,a)r=Ci(e,o+32),s=Ci(e,o+48)}var c=t&&t.filter;for(var l=0;l<r;++l){var u=DC(e,s,a),d=u[0],f=u[1],h=u[2],b=u[3],m=u[4],g=u[5],p=kC(e,g);if(s=m,!c||c({name:b,size:f,originalSize:h,compression:d}))if(!d)n[b]=Ec(e,p,p+f);else if(d==8)n[b]=CC(e.subarray(p,p+f),{out:new Zt(h)});else Vn(14,"unknown compression type "+d)}return n}Ja();Ou();Du();Fu();Ja();Ou();Fu();Du();Tc();var aN=(()=>{let e=gt().int().min(0).max(16777215),t=gt().int().min(1).max(fa),n=gt().min(-36000).max(36000),i=gt().min(0).max(1),r={blend:Ct(["normal","multiply","screen","overlay"]),opacity:i};return be({schemaVersion:$e(2),size:gt().int().min(Su).max(wu),usage:Ct(ir),name:Fe().min(1).max(80).optional(),layers:at(Ri("op",[be({op:$e("solid"),color:e,...r}).strict(),be({op:$e("checker"),colorA:e,colorB:e,squares:t,...r}).strict(),be({op:$e("stripes"),colorA:e,colorB:e,count:t,angleDeg:n,...r}).strict(),be({op:$e("gradient"),from:e,to:e,angleDeg:n,...r}).strict(),be({op:$e("bricks"),brick:e,mortar:e,rows:t,cols:t,mortarWidth:i,stagger:i,...r}).strict(),be({op:$e("noise"),colorA:e,colorB:e,scale:t,octaves:gt().int().min(1).max(Jh),seed:gt().int().min(-2147483648).max(2147483647),...r}).strict()])).min(1).max(Mu)}).strict()})();function Z0(e,t=aN){let n=(X,q)=>gt().int().min(X).max(q),i=n(0,255),r=n(-4096,4096),s=f0([r,r]),a=f0([i,i,i,i]),o=Ct(ir),c=hC(["sha256:",Fe().regex(/^[a-f0-9]{64}$/)]),l=Fe().min(1).max(80),u=Fe().regex(/^[a-z][a-z0-9_-]{0,79}$/),d=Fe().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/),f={width:n(1,4096),height:n(1,4096)},h=be({x:r,y:r,width:n(1,2048),height:n(1,2048)}).strict(),b=be({x:n(0,4096),y:n(0,4096),...f}).strict(),m=Ri("kind",[h.extend({kind:$e("rectangle")}).strict(),h.extend({kind:$e("ellipse")}).strict(),be({kind:$e("polygon"),points:at(s).min(3).max(Cu)}).strict(),be({kind:$e("line"),from:s,to:s,width:n(1,2048)}).strict()]),g=be({op:$e("paint"),shape:m,rgba:a,opacity:i}).strict(),p=be({op:$e("mask"),shape:m,alpha:i,invert:la()}).strict(),x=be({op:$e("stamps"),shape:m,rgba:a,opacity:i,count:n(1,Sc),seed:n(0,4294967295),area:h,periodic:la()}).strict(),_=be({op:$e("legacy-v2"),spec:e,alpha:i,opacity:i}).strict(),y=be({colors:at(n(0,16777215)).min(1).max(Nu),dither:Ct(["none","bayer4"])}).strict(),v={schemaVersion:$e(3),width:n(4,Mc),height:n(4,Mc),usage:o,name:l.optional(),background:a},E=be({...v,operations:at(Ri("op",[g,p,x,_.extend({spec:t})])).max(Rc),palette:y.optional()}).strict(),w=be({...v,usage:o.optional(),background:a.optional(),operations:at(Ri("op",[g.partial({opacity:!0}),p.partial({alpha:!0,invert:!0}),x.partial({opacity:!0,periodic:!0}),_.partial({alpha:!0,opacity:!0})])).max(Rc),palette:y.partial({dither:!0}).optional()}).strict(),T=be({minFilter:Ct(Qh),magFilter:Ct(ep),wrapS:Ct(Ic),wrapT:Ct(Ic)}).strict(),A=be({resourceId:u,revisionId:c,sha256:c}).strict(),P=be({kind:$e("resource"),resourceId:d,pin:A,expected:be({...f,imageSha256:c,decodedPixelHash:c}).partial().strict().optional()}).strict(),S=be({name:u,content:b,gutter:n(0,32),edgeMode:Ct(["copy-edge","mask-rgb-dilate"]),source:Ri("kind",[be({kind:$e("procedural"),spec:E}).strict(),P]),crop:b.optional(),packed:$e(!0).optional()}).strict(),R={schemaVersion:$e(1),width:n(4,Nr.edge),height:n(4,Nr.edge),usage:o,sampler:T},k=Xa(np.map((X)=>$e(X))),C=be({...R,regions:at(S).min(1).max(Nr.regions),pack:be({edge:k,gutter:n(0,32),algorithm:$e("maxrects")}).strict().optional()}).strict(),U=be({...R,width:R.width.optional(),height:R.height.optional(),pack:be({edge:k,gutter:n(0,32).optional(),algorithm:$e("maxrects").optional()}).strict().optional(),sampler:T.optional(),regions:at(S.extend({source:Ri("kind",[be({kind:$e("procedural"),spec:w}).strict(),P])}).partial({content:!0,gutter:!0,edgeMode:!0})).min(1).max(Nr.regions)}).strict(),L=be({materialId:u,revisionId:c,resourceId:d,slot:Ct(["baseColor","normal","metallicRoughness","emissive","occlusion"]),usage:o,colorSpace:Ct(["srgb","linear"]),...f,encodedByteLength:n(1,ha.encodedSourceBytes),imageSha256:c,decodedPixelHash:c.optional()}).strict(),O={id:Fe().min(1).max(1024),...f,decodedPixelHash:c},K=Ri("kind",[be({...O,kind:$e("procedural"),recipeHash:c,compilerId:$e(Za)}).strict(),be({...O,kind:$e("resource"),descriptor:L}).strict()]),B=be({version:$e("kiln.atlas-manifest.v1"),compilerId:Ct(Lu),width:R.width,height:R.height,usage:o,origin:$e("top-left"),sampler:T,specHash:c,layoutHash:c,decodedPixelHash:c,atlasPixelHash:c,sources:at(K).min(1).max(Nr.sources),regions:at(be({name:u,content:b,allocation:b,crop:b,sourceId:Fe().min(1).max(1024)}).strict()).min(1).max(Nr.regions),manifestHash:c}).strict();return{portableSamplerSchema:T,proceduralTextureSpecV3Schema:w,canonicalProceduralTextureSpecV3Schema:E,textureAtlasSpecV1Schema:U,canonicalTextureAtlasSpecV1Schema:C,textureAtlasManifestV1Schema:B,materialMapPinSchema:A,verifiedPinnedMaterialMapDescriptorSchema:L}}var Pn=Object.freeze({maxMapBytes:8388608,maxRecordBytes:33554432,maxManifestBytes:262144,maxMapEdge:4096,maxRecordPixels:8388608,maxPayloadBytes:16777216,maxPayloadPixels:16777216,maxPayloadRecords:16}),Q0=["baseColor","normal","metallicRoughness","emissive","occlusion"],eE={baseColor:"albedo",normal:"normal",metallicRoughness:"metallicRoughness",emissive:"emissive",occlusion:"occlusion"};var eo=Fe().regex(/^[a-z][a-z0-9_-]{0,79}$/),ar=Fe().regex(/^sha256:[a-f0-9]{64}$/),sr=Fe().min(1).max(1000),Y0=Fe().max(2000).url().refine((e)=>/^https?:\/\//.test(e),"Provenance URL must be HTTP(S)"),tE=be({id:eo,kind:Ct(["external","procedural"]),provider:sr,creator:sr,assetId:sr.optional(),assetUrl:Y0.optional(),accessedAt:Fe().datetime().optional(),license:be({spdx:sr,url:Y0,attribution:Fe().max(4000)}).strict(),originalFiles:at(be({name:Fe().min(1).max(200),sha256:ar,bytes:gt().int().positive().max(1073741824)}).strict()).max(20)}).strict().superRefine((e,t)=>{if(e.kind==="external"&&(!e.assetUrl||!e.originalFiles.length))t.addIssue({code:"custom",message:"External materials require a source URL and original file hashes"});if(new Set(e.originalFiles.map((n)=>n.name)).size!==e.originalFiles.length)t.addIssue({code:"custom",message:"Duplicate original filename"})}),nE=be({operation:sr,tool:sr,version:sr,parameters:_u(Fe().max(100),Xa([Fe().max(2000),gt().finite(),la()])).optional()}).strict(),Pi=gt().int().min(0).max(16777215),Nc=gt().int().min(1).max(256),Qa={blend:Ct(["normal","multiply","screen","overlay"]).default("normal"),opacity:gt().min(0).max(1).default(1)},kc=be({schemaVersion:$e(2),size:gt().int().min(4).max(1024).default(256),usage:Ct(["albedo","normal","roughness","metalness","metallicRoughness","emissive","occlusion"]).default("albedo"),name:Fe().min(1).max(80).optional(),layers:at(Ri("op",[be({op:$e("solid"),color:Pi,...Qa}).strict(),be({op:$e("checker"),colorA:Pi,colorB:Pi,squares:Nc.default(8),...Qa}).strict(),be({op:$e("stripes"),colorA:Pi,colorB:Pi,count:Nc.default(8),angleDeg:gt().min(-36000).max(36000).default(0),...Qa}).strict(),be({op:$e("gradient"),from:Pi,to:Pi,angleDeg:gt().min(-36000).max(36000).default(0),...Qa}).strict(),be({op:$e("bricks"),brick:Pi,mortar:Pi,rows:Nc.default(8),cols:Nc.default(4),mortarWidth:gt().min(0).max(1).default(0.06),stagger:gt().min(0).max(1).default(0.5),...Qa}).strict(),be({op:$e("noise"),colorA:Pi,colorB:Pi,scale:Nc.default(8),octaves:gt().int().min(1).max(6).default(3),seed:gt().int().min(-2147483648).max(2147483647).default(0),...Qa}).strict()])).min(1).max(8)}).strict(),ap=be({kind:$e("normal-from-height"),strength:gt().finite().positive().max(64)}).strict(),oN=be({compiler:$e("kiln.procedural-texture.v2"),spec:kc,derive:ap.optional(),recipeHash:ar,pixelHash:ar,encoder:be({name:$e("sharp"),version:sr}).strict()}).strict(),iE=be({baseColor:gt().int().min(0).max(16777215).optional(),roughness:gt().min(0).max(1).default(1),metalness:gt().min(0).max(1).default(0),emissive:gt().int().min(0).max(16777215).optional(),emissiveIntensity:gt().min(0).max(64).default(1),alphaMode:Ct(["opaque","mask","blend"]).default("opaque"),alphaCutoff:gt().min(0).max(1).default(0.5),doubleSided:la().default(!1)}).strict(),Pc=be({schemaVersion:$e(1),materialId:eo,revisionId:ar,name:Fe().min(1).max(200),tags:at(Fe().min(1).max(80)).max(30),tileable:la(),physicalSizeMeters:be({width:gt().finite().positive().max(1e5),height:gt().finite().positive().max(1e5)}).strict().optional(),parameters:iE,sources:at(tE).min(1).max(20),maps:at(be({slot:Ct(Q0),file:Ct(["baseColor.png","normal.png","metallicRoughness.png","emissive.png","occlusion.png"]),sha256:ar,bytes:gt().int().positive().max(Pn.maxMapBytes),width:gt().int().positive().max(Pn.maxMapEdge),height:gt().int().positive().max(Pn.maxMapEdge),usage:Ct(["albedo","normal","metallicRoughness","emissive","occlusion"]),colorSpace:Ct(["srgb","linear"]),normalConvention:$e("opengl").optional(),channelPacking:$e("r-occlusion-g-roughness-b-metallic").optional(),sourceId:eo,originalFile:Fe().min(1).max(200).optional(),transforms:at(nE).max(30),procedural:oN.optional()}).strict()).min(1).max(5)}).strict(),rp=be({materialId:eo,name:Fe().min(1).max(200),tags:at(Fe().min(1).max(80)).max(30).optional(),tileable:la(),physicalSizeMeters:be({width:gt().finite().positive().max(1e5),height:gt().finite().positive().max(1e5)}).strict().optional(),parameters:iE.partial().optional(),sources:at(tE).min(1).max(20),maps:at(be({slot:Ct(Q0),sourceId:eo,transforms:at(nE).max(30),normalConvention:$e("opengl").optional(),channelPacking:$e("r-occlusion-g-roughness-b-metallic").optional(),procedural:kc,derive:ap.optional()}).strict()).min(1).max(5)}).strict(),sp=be({schemaVersion:$e(1),records:at(be({manifest:Pc,files:_u(Fe().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/),Fe().max(Math.ceil(Pn.maxMapBytes/3)*4))}).strict()).max(Pn.maxPayloadRecords)}).strict();function io(e,t=!1,n=0){if(n>30)throw Error("Material JSON exceeds nesting limit");if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number"&&Number.isFinite(e))return;if(t&&e instanceof Uint8Array)return;if(!e||typeof e!=="object")throw Error("Material values must be plain JSON data");let i=Array.isArray(e),r=Object.getPrototypeOf(e);if(i?r!==Array.prototype:r!==Object.prototype&&r!==null)throw Error("Material values must have plain JSON prototypes");if(i&&e.length>1e4)throw Error("Material JSON array exceeds limit");for(let s of Reflect.ownKeys(e)){if(i&&s==="length")continue;if(typeof s!=="string"||["__proto__","prototype","constructor"].includes(s))throw Error("Material JSON contains a forbidden key");if(i&&(!/^(0|[1-9][0-9]*)$/.test(s)||Number(s)>=e.length))throw Error("Material arrays must contain only indexed data");let a=Object.getOwnPropertyDescriptor(e,s);if(!("value"in a)||!a.enumerable)throw Error("Material JSON accessors or hidden fields are not allowed");io(a.value,t,n+1)}if(i&&Object.keys(e).length!==e.length)throw Error("Material JSON arrays must be dense")}function Nn(e){io(e);let t=(n)=>Array.isArray(n)?n.map(t):n!==null&&typeof n==="object"?Object.fromEntries(Object.entries(n).sort(([i],[r])=>i<r?-1:i>r?1:0).map(([i,r])=>[i,t(r)])):n;return JSON.stringify(t(e))}function cN(e){if(io(e),new TextEncoder().encode(JSON.stringify(e)).length>Pn.maxManifestBytes)throw Error("Material manifest exceeds size limit");let t=Pc.parse(e);if(new Set(t.sources.map((r)=>r.id)).size!==t.sources.length)throw Error("Duplicate material source identity");if(new Set(t.maps.map((r)=>r.slot)).size!==t.maps.length)throw Error("Duplicate material map slot");let n=0,i=0;for(let r of t.maps){let s=r.slot==="baseColor"||r.slot==="emissive";if(r.file!==`${r.slot}.png`||r.usage!==eE[r.slot]||r.colorSpace!==(s?"srgb":"linear"))throw Error("Material map filename, usage or color convention mismatch");if(r.slot==="normal"!==(r.normalConvention==="opengl")||r.slot==="metallicRoughness"!==(r.channelPacking==="r-occlusion-g-roughness-b-metallic"))throw Error("Material map convention is missing or invalid");let a=t.sources.find((o)=>o.id===r.sourceId);if(!a)throw Error("Material map source is missing");if(r.procedural){if(r.procedural.derive&&r.slot!=="normal")throw Error("Height derivation requires a normal map slot");if(Nn(r.procedural.spec)!==Nn(wc(r.procedural.spec)))throw Error("Stored procedural material recipe must be canonical");if(a.kind!=="procedural"||r.originalFile||r.procedural.spec.usage!==r.usage||r.procedural.spec.size!==r.width||r.width!==r.height)throw Error("Procedural material source or map convention mismatch")}else if(a.kind!=="external"||!a.originalFiles.some((o)=>o.name===r.originalFile))throw Error("Material map must reference an original source file");n+=r.bytes,i+=r.width*r.height}if(n>Pn.maxRecordBytes||i>Pn.maxRecordPixels)throw Error("Material record exceeds byte or pixel budget");return t}var to=Z0(kc),no={when:(e)=>!e.issues.length},rE=(e)=>e instanceof Error?e.message:String(e);function Oc(e,t,n){return(i,r)=>{try{let s=t(i);if(n&&Nn(i)!==Nn(s))r.addIssue({code:"custom",message:`${e} must be stored in canonical form.`})}catch(s){r.addIssue({code:"custom",message:rE(s)})}}}var sE=to.portableSamplerSchema.superRefine(Oc("sampler",ku,!0),no),lN=to.canonicalProceduralTextureSpecV3Schema.superRefine(Oc("procedural V3 spec",Zh,!0),no),uN=to.canonicalTextureAtlasSpecV1Schema.superRefine(Oc("atlas spec",pa,!0),no),dN=to.textureAtlasManifestV1Schema,fN=be({resourceId:eo,revisionId:ar,sha256:ar}).strict().refine((e)=>e.sha256===e.revisionId,"Material pin hash must match revision"),hN=Ri("kind",[be({kind:$e("procedural"),compilerId:Ct(["kiln.procedural-texture.v2",Za]),spec:Xa([kc,lN]),recipeHash:ar,pixelHash:ar,encoder:be({name:$e("sharp"),version:sr}).strict(),derive:ap.optional()}).strict(),be({kind:$e("atlas"),compilerId:Ct(Lu),spec:uN,manifest:dN,encoder:be({name:$e("sharp"),version:sr}).strict()}).strict().superRefine((e,t)=>{try{if(Cc(e.manifest,e.spec),e.compilerId!==e.manifest.compilerId)throw Error(`recipe compilerId ${e.compilerId} does not match the manifest's ${e.manifest.compilerId}.`)}catch(n){t.addIssue({code:"custom",message:`stored atlas manifest: ${rE(n)}`})}},no)]),aE=Pc.omit({schemaVersion:!0,maps:!0}).extend({schemaVersion:$e(2),dependencies:at(fN).max(16),maps:at(Pc.shape.maps.element.omit({procedural:!0}).extend({sampler:sE,pixelHash:ar,recipe:hN.optional()}).strict()).min(1).max(5)}).strict(),pN=Ri("schemaVersion",[Pc,aE]),mN=sp.extend({schemaVersion:$e(2),records:at(sp.shape.records.element.extend({manifest:pN}).strict()).max(Pn.maxPayloadRecords)}).strict(),oE=Ri("schemaVersion",[sp,mN]);function cE(e){return e.schemaVersion===1?[]:e.dependencies.map((t)=>({...t}))}var gN=rp.extend({schemaVersion:$e(2),maps:at(rp.shape.maps.element.omit({procedural:!0}).extend({sampler:sE,procedural:Xa([kc,to.proceduralTextureSpecV3Schema.superRefine(Oc("procedural V3 spec",Zh,!1),no)]).optional(),atlas:to.textureAtlasSpecV1Schema.superRefine(Oc("atlas spec",pa,!1),no).optional()}).strict().refine((e)=>e.procedural!==void 0!==(e.atlas!==void 0),"Supply exactly one procedural or atlas recipe")).min(1).max(5)}).strict(),zj=Xa([rp,gN]);function ro(e){if(io(e),new TextEncoder().encode(JSON.stringify(e)).length>Pn.maxManifestBytes)throw Error("Material manifest exceeds size limit");if(!e||typeof e!=="object"||Array.isArray(e))throw Error("Invalid material manifest");if(e.schemaVersion===1)return cN(e);let t=aE.parse(e);if(new Set(t.sources.map((a)=>a.id)).size!==t.sources.length||new Set(t.maps.map((a)=>a.slot)).size!==t.maps.length)throw Error("Duplicate material source or slot");let n=0,i=0,r=new Map;for(let a of t.maps){let o=t.sources.find((l)=>l.id===a.sourceId);if(!o||a.file!==`${a.slot}.png`||a.usage!==eE[a.slot]||a.colorSpace!==(a.slot==="baseColor"||a.slot==="emissive"?"srgb":"linear")||a.slot==="normal"!==(a.normalConvention==="opengl")||a.slot==="metallicRoughness"!==(a.channelPacking==="r-occlusion-g-roughness-b-metallic"))throw Error("Material map source/usage/convention mismatch");let c=a.recipe;if(c){if(o.kind!=="procedural"||a.originalFile)throw Error("Procedural/atlas map source convention mismatch");if(c.kind==="procedural"){let l=c.spec;if(l.schemaVersion===3){if(c.compilerId!==Za||l.width!==a.width||l.height!==a.height)throw Error("V3 compiler/dimensions mismatch")}else if(c.compilerId!=="kiln.procedural-texture.v2"||l.size!==a.width||a.width!==a.height||Nn(l)!==Nn(wc(l)))throw Error("V2 compiler/canonical recipe dimensions mismatch");if(l.usage!==a.usage||c.pixelHash!==a.pixelHash||c.derive&&a.slot!=="normal")throw Error("Procedural recipe pixel/usage mismatch")}else{if(Cc(c.manifest,c.spec),c.spec.width!==a.width||c.spec.height!==a.height||c.spec.usage!==a.usage||Nn(c.spec.sampler)!==Nn(a.sampler)||c.manifest.decodedPixelHash!==a.pixelHash)throw Error("Atlas recipe map mismatch");for(let l of c.spec.regions)if(l.source.kind==="resource"){let u=l.source.pin;r.set(`${u.resourceId}/${u.revisionId}`,u)}}}else if(o.kind!=="external"||!o.originalFiles.some((l)=>l.name===a.originalFile))throw Error("External material source original file missing");n+=a.bytes,i+=a.width*a.height}let s=t.dependencies.map((a)=>`${a.resourceId}/${a.revisionId}`);if(new Set(s).size!==s.length||s.length!==r.size||s.some((a)=>!r.has(a)))throw Error("Material dependency pin inventory mismatch");if(n>Pn.maxRecordBytes||i>Pn.maxRecordPixels)throw Error("Material record exceeds byte/pixel budget");return structuredClone(t)}var Wn=67108864,op=Fe().regex(/^[a-z][a-z0-9_-]{0,79}$/),bN=Fe().regex(/^sha256:[a-f0-9]{64}$/),lE=be({version:$e("kiln.asset.v1"),assetId:op,revisionId:op,parentRevision:op.optional(),name:Fe().min(1).max(200),tags:at(Fe().max(80)).max(30),createdAt:Fe().datetime(),description:Fe().max(4000).optional(),brief:Fe().max(8000).optional(),attribution:be({model:Fe().max(200).optional(),harness:Fe().max(200).optional(),author:Fe().max(200).optional()}).optional(),editable:la(),files:_u(Fe(),be({sha256:bN,bytes:gt().int().nonnegative().max(Wn)})),build:be({engine:Fe(),options:_u(Fe(),ca()),warnings:at(Fe()),integration:ca().optional(),qa:ca().optional(),dependencies:at(ca()).optional(),rebuild:Ct(["engine-required","external-dependencies-required"])}).optional(),preview:be({fidelity:ca().optional(),error:Fe().optional(),backdrop:Ct(g0).optional()}).optional()}),Dc="materials.kiln.json",uE=25165824;function Lc(e){let t=new Map;for(let n of e.manifest.build?.dependencies??[]){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Invalid saved asset dependency");let i=n;if(i.kind!=="kiln.material.v1"&&i.kind!=="kiln.material.v2"){if(i.delivery==="runtime")throw Error("Unsupported runtime dependency");if(i.delivery!=="embedded")throw Error("Unsupported saved asset dependency");continue}if(i.delivery!=="runtime")throw Error("Invalid saved material dependency");let r=ro(i.manifest);if(i.kind!==`kiln.material.v${r.schemaVersion}`)throw Error("Saved material dependency kind/version mismatch");let s=`${r.materialId}/${r.revisionId}`,a=t.get(s);if(a&&Nn(a)!==Nn(r))throw Error("Conflicting saved material dependency manifests");if(t.set(s,r),t.size>Pn.maxPayloadRecords)throw Error("Saved asset material dependency count exceeds limit")}return[...t.values()]}function dE(e,t=!1){let n=Lc(e),i=new Map(n.map((d)=>[`${d.materialId}/${d.revisionId}`,Nn(d)]));if(!e.materialResources){if(t&&i.size)throw Error("Editable asset material closure unavailable");return}io(e.materialResources);let r=oE.parse(e.materialResources),s=0,a=0,o=new Map;for(let d of r.records){let f=ro(d.manifest),h=`${d.manifest.materialId}/${d.manifest.revisionId}`;if(o.has(h)||i.has(h)&&i.get(h)!==Nn(f))throw Error("Asset material closure mismatch");if(o.set(h,f),Object.keys(d.files).length!==d.manifest.maps.length)throw Error("Asset material map inventory mismatch");for(let b of d.manifest.maps){if(d.files[b.file]?.length!==Math.ceil(b.bytes/3)*4)throw Error("Asset material map size mismatch");s+=b.bytes,a+=b.width*b.height}}if(s>Pn.maxPayloadBytes||a>Pn.maxPayloadPixels)throw Error("Asset material closure exceeds allocation limits");let c=new Set,l=new Set,u=(d)=>{if(l.has(d))throw Error("Asset material closure contains a cycle");if(c.has(d))return;let f=o.get(d);if(!f)throw Error("Asset material closure incomplete");l.add(d);for(let h of cE(f))u(`${h.resourceId}/${h.revisionId}`);l.delete(d),c.add(d)};for(let d of i.keys())u(d);if(c.size!==o.size)throw Error("Asset material closure has unrelated records")}var xN=new Set(["asset.glb","source.kiln.js","preview.png"]);function Uu(e){let t=lE.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(!xN.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>Wn||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");cp(e.files["asset.glb"]),dE(e)}function cp(e){if(e.length<20||e.length>Wn)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 lp(e){if(!e.length||e.length>100)throw Error("Bundle requires 1..100 revisions");let t={},n=0;for(let i of e){Uu(i),dE(i,!0);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,a]of Object.entries(i.files))t[r+s]=a;if(i.materialResources){let s=new TextEncoder().encode(JSON.stringify(i.materialResources));if(s.length>uE)throw Error("Asset material payload exceeds byte limit");t[r+Dc]=s}}for(let i of Object.values(t))n+=i.length;if(n>Wn)throw Error("Bundle exceeds 64 MiB");return P0(t,{level:0})}function fE(e){if(e.length>Wn+1048576)throw Error("Bundle exceeds 64 MiB");let t=0,n=0,i=O0(e,{filter:(a)=>{if(t+=a.originalSize,n++,t>Wn||n>500||a.name.endsWith(`/${Dc}`)&&a.originalSize>uE||!/^[a-z][a-z0-9_-]{0,79}\/[a-z][a-z0-9_-]{0,79}\/(manifest\.json|asset\.glb|source\.kiln\.js|preview\.png|materials\.kiln\.json)$/.test(a.name))throw Error("Unsafe or oversized asset bundle");return!0}}),r=[],s=new Set;for(let[a,o]of Object.entries(i)){if(!a.endsWith("/manifest.json"))continue;if(o.length>1048576)throw Error("Manifest exceeds 1 MiB");let c=lE.parse(JSON.parse(new TextDecoder().decode(o))),l=`${c.assetId}/${c.revisionId}/`;if(a!==`${l}manifest.json`)throw Error("Bundle identity mismatch");let u={manifest:c,files:{}};s.add(a);for(let d of Object.keys(c.files)){if(!i[l+d])throw Error("Bundle file missing");u.files[d]=i[l+d],s.add(l+d)}if(i[l+Dc])u.materialResources=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i[l+Dc])),s.add(l+Dc);Uu(u),r.push(u)}if(!r.length||s.size!==Object.keys(i).length)throw Error("Incomplete asset bundle");return r}function hE(e){let t=e.attribution;if(!t)return[];return[t.model?{label:"Model",value:t.model}:null,t.harness?{label:"Harness",value:t.harness}:null,t.author?{label:"Author",value:t.author}:null].filter((n)=>n!==null)}ji();ji();var BA={type:"change"},mg={type:"start"},VA={type:"end"},Xd=new ms,zA=new yi,f8=Math.cos(70*el.DEG2RAD),bn=new j,Jn=2*Math.PI,Ot={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},pg=0.000001;class gg extends Hd{constructor(e,t=null){super(e,t);if(this.state=Ot.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:us.ROTATE,MIDDLE:us.DOLLY,RIGHT:us.PAN},this.touches={ONE:ds.ROTATE,TWO:ds.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 ln,this._lastTargetPosition=new j,this._quat=new ln().setFromUnitVectors(e.up,new j(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new pl,this._sphericalDelta=new pl,this._scale=1,this._panOffset=new j,this._rotateStart=new Ke,this._rotateEnd=new Ke,this._rotateDelta=new Ke,this._panStart=new Ke,this._panEnd=new Ke,this._panDelta=new Ke,this._dollyStart=new Ke,this._dollyEnd=new Ke,this._dollyDelta=new Ke,this._dollyDirection=new j,this._mouse=new Ke,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=p8.bind(this),this._onPointerDown=h8.bind(this),this._onPointerUp=m8.bind(this),this._onContextMenu=E8.bind(this),this._onMouseWheel=x8.bind(this),this._onKeyDown=y8.bind(this),this._onTouchStart=_8.bind(this),this._onTouchMove=v8.bind(this),this._onMouseDown=g8.bind(this),this._onMouseMove=b8.bind(this),this._interceptControlDown=T8.bind(this),this._interceptControlUp=A8.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.state=Ot.NONE,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();let e=this.domElement.getRootNode();e.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),e.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(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(BA),this.update(),this.state=Ot.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(bn.copy(t).sub(this.target),bn.applyQuaternion(this._quat),this._spherical.setFromVector3(bn),this.autoRotate&&this.state===Ot.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+=Jn;else if(n>Math.PI)n-=Jn;if(i<-Math.PI)i+=Jn;else if(i>Math.PI)i-=Jn;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(bn.setFromSpherical(this._spherical),bn.applyQuaternion(this._quatInverse),t.copy(this.target).add(bn),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 a=bn.length();s=this._clampDistance(a*this._scale);let o=a-s;this.object.position.addScaledVector(this._dollyDirection,o),this.object.updateMatrixWorld(),r=!!o}else if(this.object.isOrthographicCamera){let a=new j(this._mouse.x,this._mouse.y,0);a.unproject(this.object);let o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=o!==this.object.zoom;let c=new j(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(a),this.object.updateMatrixWorld(),s=bn.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(Xd.origin.copy(this.object.position),Xd.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Xd.direction))<f8)this.object.lookAt(this.target);else zA.setFromNormalAndCoplanarPoint(this.object.up,this.target),Xd.intersectPlane(zA,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)>pg||8*(1-this._lastQuaternion.dot(this.object.quaternion))>pg||this._lastTargetPosition.distanceToSquared(this.target)>pg)return this.dispatchEvent(BA),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 Jn/60*this.autoRotateSpeed*e;else return Jn/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){bn.setFromMatrixColumn(t,0),bn.multiplyScalar(-e),this._panOffset.add(bn)}_panUp(e,t){if(this.screenSpacePanning===!0)bn.setFromMatrixColumn(t,1);else bn.setFromMatrixColumn(t,0),bn.crossVectors(this.object.up,bn);bn.multiplyScalar(e),this._panOffset.add(bn)}_pan(e,t){let n=this.domElement;if(this.object.isPerspectiveCamera){let i=this.object.position;bn.copy(i).sub(this.target);let r=bn.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:a}=n;this._mouse.x=i/s*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(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(Jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Jn*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(Jn*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(-Jn*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(Jn*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(-Jn*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(Jn*this._rotateDelta.x/t.clientHeight),this._rotateUp(Jn*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,a=(e.pageY+t.y)*0.5;this._updateZoomParameters(s,a)}_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 Ke,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 h8(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 p8(e){if(this.enabled===!1)return;if(e.pointerType==="touch")this._onTouchMove(e);else this._onMouseMove(e)}function m8(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(VA),this.state=Ot.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 g8(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 us.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(e),this.state=Ot.DOLLY;break;case us.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=Ot.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=Ot.ROTATE}break;case us.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=Ot.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=Ot.PAN}break;default:this.state=Ot.NONE}if(this.state!==Ot.NONE)this.dispatchEvent(mg)}function b8(e){switch(this.state){case Ot.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(e);break;case Ot.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(e);break;case Ot.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(e);break}}function x8(e){if(this.enabled===!1||this.enableZoom===!1||this.state!==Ot.NONE)return;e.preventDefault(),this.dispatchEvent(mg),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(VA)}function y8(e){if(this.enabled===!1)return;this._handleKeyDown(e)}function _8(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case ds.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(e),this.state=Ot.TOUCH_ROTATE;break;case ds.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(e),this.state=Ot.TOUCH_PAN;break;default:this.state=Ot.NONE}break;case 2:switch(this.touches.TWO){case ds.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(e),this.state=Ot.TOUCH_DOLLY_PAN;break;case ds.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(e),this.state=Ot.TOUCH_DOLLY_ROTATE;break;default:this.state=Ot.NONE}break;default:this.state=Ot.NONE}if(this.state!==Ot.NONE)this.dispatchEvent(mg)}function v8(e){switch(this._trackPointer(e),this.state){case Ot.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(e),this.update();break;case Ot.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(e),this.update();break;case Ot.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(e),this.update();break;case Ot.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=Ot.NONE}}function E8(e){if(this.enabled===!1)return;e.preventDefault()}function T8(e){if(e.key==="Control")this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}function A8(e){if(e.key==="Control")this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}ji();class bg extends Po{constructor(){super();this.name="RoomEnvironment",this.position.y=-3.5;let e=new bs;e.deleteAttribute("uv");let t=new zr({side:Dn}),n=new zr,i=new Uo(16777215,900,28,2);i.position.set(0.418,16.199,0.3),this.add(i);let r=new jt(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 ko(e,n,6),a=new Dt;a.position.set(-10.906,2.009,1.846),a.rotation.set(0,-0.195,0),a.scale.set(2.328,7.905,4.651),a.updateMatrix(),s.setMatrixAt(0,a.matrix),a.position.set(-5.607,-0.754,-0.758),a.rotation.set(0,0.994,0),a.scale.set(1.97,1.534,3.955),a.updateMatrix(),s.setMatrixAt(1,a.matrix),a.position.set(6.167,0.857,7.803),a.rotation.set(0,0.561,0),a.scale.set(3.927,6.285,3.687),a.updateMatrix(),s.setMatrixAt(2,a.matrix),a.position.set(-2.017,0.018,6.124),a.rotation.set(0,0.333,0),a.scale.set(2.002,4.566,2.064),a.updateMatrix(),s.setMatrixAt(3,a.matrix),a.position.set(2.291,-0.756,-2.621),a.rotation.set(0,-0.286,0),a.scale.set(1.546,1.552,1.496),a.updateMatrix(),s.setMatrixAt(4,a.matrix),a.position.set(-2.193,-0.369,-5.547),a.rotation.set(0,0.516,0),a.scale.set(3.875,3.487,2.986),a.updateMatrix(),s.setMatrixAt(5,a.matrix),this.add(s);let o=new jt(e,Ho(50));o.position.set(-16.116,14.37,8.208),o.scale.set(0.1,2.428,2.739),this.add(o);let c=new jt(e,Ho(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 jt(e,Ho(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 jt(e,Ho(43));u.position.set(-0.462,8.89,14.52),u.scale.set(4.38,5.441,0.088),this.add(u);let d=new jt(e,Ho(20));d.position.set(3.235,11.486,-12.541),d.scale.set(2.5,2,0.1),this.add(d);let f=new jt(e,Ho(100));f.position.set(0,20,0),f.scale.set(1,0.1,1),this.add(f)}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 Ho(e){return new Dd({color:0,emissive:16777215,emissiveIntensity:e})}ji();ji();ji();function xg(e,t){if(t===Im)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(t===No||t===Qc){let n=e.getIndex();if(n===null){let s=[],a=e.getAttribute("position");if(a!==void 0){for(let o=0;o<a.count;o++)s.push(o);e.setIndex(s),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===No)for(let s=1;s<=i;s++)r.push(n.getX(0)),r.push(n.getX(s)),r.push(n.getX(s+1));else for(let s=0;s<i;s++)if(s%2===0)r.push(n.getX(s)),r.push(n.getX(s+1)),r.push(n.getX(s+2));else r.push(n.getX(s+2)),r.push(n.getX(s+1)),r.push(n.getX(s));if(r.length/3!==i)console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");return e.setIndex(r),e.clearGroups(),e}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}function jA(e){let t=new Map,n=new Map,i=e.clone();return HA(e,i,function(r,s){t.set(s,r),n.set(r,s)}),i.traverse(function(r){if(!r.isSkinnedMesh)return;let s=r,a=t.get(r),o=a.skeleton.bones;s.skeleton=a.skeleton.clone(),s.bindMatrix.copy(a.bindMatrix),s.skeleton.bones=o.map(function(c){return n.get(c)}),s.bind(s.skeleton,s.bindMatrix)}),i}function HA(e,t,n){n(e,t);for(let i=0;i<e.children.length;i++)HA(e.children[i],t.children[i],n)}class wg extends jr{constructor(e){super(e);this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new ZA(t)}),this.register(function(t){return new YA(t)}),this.register(function(t){return new ow(t)}),this.register(function(t){return new cw(t)}),this.register(function(t){return new lw(t)}),this.register(function(t){return new ew(t)}),this.register(function(t){return new tw(t)}),this.register(function(t){return new nw(t)}),this.register(function(t){return new iw(t)}),this.register(function(t){return new JA(t)}),this.register(function(t){return new rw(t)}),this.register(function(t){return new QA(t)}),this.register(function(t){return new aw(t)}),this.register(function(t){return new sw(t)}),this.register(function(t){return new XA(t)}),this.register(function(t){return new Eg(t,ut.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new Eg(t,ut.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new uw(t)})}load(e,t,n,i){let r=this,s;if(this.resourcePath!=="")s=this.resourcePath;else if(this.path!==""){let c=Es.extractUrlBase(e);s=Es.resolveURL(c,this.path)}else s=Es.extractUrlBase(e);this.manager.itemStart(e);let a=function(c){if(i)i(c);else console.error(c);r.manager.itemError(e),r.manager.itemEnd(e)},o=new fl(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(c){try{r.parse(c,s,function(l){t(l),r.manager.itemEnd(e)},a)}catch(l){a(l)}},n,a)}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={},a={},o=new TextDecoder;if(typeof e==="string")r=JSON.parse(e);else if(e instanceof ArrayBuffer)if(o.decode(new Uint8Array(e,0,4))===dw){try{s[ut.KHR_BINARY_GLTF]=new fw(e)}catch(u){if(i)i(u);return}r=JSON.parse(s[ut.KHR_BINARY_GLTF].content)}else r=JSON.parse(o.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 bw(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");a[u.name]=u,s[u.name]=!0}if(r.extensionsUsed)for(let l=0;l<r.extensionsUsed.length;++l){let u=r.extensionsUsed[l],d=r.extensionsRequired||[];switch(u){case ut.KHR_MATERIALS_UNLIT:s[u]=new qA;break;case ut.KHR_DRACO_MESH_COMPRESSION:s[u]=new hw(r,this.dracoLoader);break;case ut.KHR_TEXTURE_TRANSFORM:s[u]=new pw;break;case ut.KHR_MESH_QUANTIZATION:s[u]=new mw;break;default:if(d.indexOf(u)>=0&&a[u]===void 0)console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}c.setExtensions(s),c.setPlugins(a),c.parse(n,i)}parseAsync(e,t){let n=this;return new Promise(function(i,r){n.parse(e,t,i,r)})}}function w8(){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 sn(e,t,n){let i=e.json.materials[t];if(i.extensions&&i.extensions[n])return i.extensions[n];return null}var ut={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 XA{constructor(e){this.parser=e,this.name=ut.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,o=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e],c,l=new qe(16777215);if(o.color!==void 0)l.setRGB(o.color[0],o.color[1],o.color[2],ci);let u=o.range!==void 0?o.range:0;switch(o.type){case"directional":c=new Bo(l),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new Uo(l),c.distance=u;break;case"spot":c=new zd(l),c.distance=u,o.spot=o.spot||{},o.spot.innerConeAngle=o.spot.innerConeAngle!==void 0?o.spot.innerConeAngle:0,o.spot.outerConeAngle=o.spot.outerConeAngle!==void 0?o.spot.outerConeAngle:Math.PI/4,c.angle=o.spot.outerConeAngle,c.penumbra=1-o.spot.innerConeAngle/o.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw Error("THREE.GLTFLoader: Unexpected light type: "+o.type)}if(c.position.set(0,0,0),xr(c,o),o.intensity!==void 0)c.intensity=o.intensity;return c.name=t.createUniqueName(o.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],a=(r.extensions&&r.extensions[this.name]||{}).light;if(a===void 0)return null;return this._loadLight(a).then(function(o){return n._getNodeRef(t.cache,a,o)})}}class qA{constructor(){this.name=ut.KHR_MATERIALS_UNLIT}getMaterialType(){return mr}extendParams(e,t,n){let i=[];e.color=new qe(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],ci),e.opacity=s[3]}if(r.baseColorTexture!==void 0)i.push(n.assignTexture(e,"map",r.baseColorTexture,ps))}return Promise.all(i)}}class JA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=sn(this.parser,e,this.name);if(n===null)return Promise.resolve();if(n.emissiveStrength!==void 0)t.emissiveIntensity=n.emissiveStrength;return Promise.resolve()}}class ZA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(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 Ke(r,r)}}return Promise.all(i)}}class YA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_DISPERSION}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(this.parser,e,this.name);if(n===null)return Promise.resolve();return t.dispersion=n.dispersion!==void 0?n.dispersion:0,Promise.resolve()}}class QA{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(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 ew{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_SHEEN}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(this.parser,e,this.name);if(n===null)return Promise.resolve();let i=[];if(t.sheenColor=new qe(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],ci)}if(n.sheenRoughnessFactor!==void 0)t.sheenRoughness=n.sheenRoughnessFactor;if(n.sheenColorTexture!==void 0)i.push(this.parser.assignTexture(t,"sheenColorMap",n.sheenColorTexture,ps));if(n.sheenRoughnessTexture!==void 0)i.push(this.parser.assignTexture(t,"sheenRoughnessMap",n.sheenRoughnessTexture));return Promise.all(i)}}class tw{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(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 nw{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_VOLUME}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(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 qe().setRGB(r[0],r[1],r[2],ci),Promise.all(i)}}class iw{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_IOR}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(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 rw{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_SPECULAR}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(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 qe().setRGB(r[0],r[1],r[2],ci),n.specularColorTexture!==void 0)i.push(this.parser.assignTexture(t,"specularColorMap",n.specularColorTexture,ps));return Promise.all(i)}}class sw{constructor(e){this.parser=e,this.name=ut.EXT_MATERIALS_BUMP}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(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 aw{constructor(e){this.parser=e,this.name=ut.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return sn(this.parser,e,this.name)!==null?di:null}extendMaterialParams(e,t){let n=sn(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 ow{constructor(e){this.parser=e,this.name=ut.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 cw{constructor(e){this.parser=e,this.name=ut.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],a=i.images[s.source],o=n.textureLoader;if(a.uri){let c=n.options.manager.getHandler(a.uri);if(c!==null)o=c}return n.loadTextureImage(e,s.source,o)}}class lw{constructor(e){this.parser=e,this.name=ut.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],a=i.images[s.source],o=n.textureLoader;if(a.uri){let c=n.options.manager.getHandler(a.uri);if(c!==null)o=c}return n.loadTextureImage(e,s.source,o)}}class Eg{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(a){let o=i.byteOffset||0,c=i.byteLength||0,{count:l,byteStride:u}=i,d=new Uint8Array(a,o,c);if(s.decodeGltfBufferAsync)return s.decodeGltfBufferAsync(l,u,d,i.mode,i.filter).then(function(f){return f.buffer});else return s.ready.then(function(){let f=new ArrayBuffer(l*u);return s.decodeGltfBuffer(new Uint8Array(f),l,u,d,i.mode,i.filter),f})})}else return null}}class uw{constructor(e){this.name=ut.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!==Ti.TRIANGLES&&c.mode!==Ti.TRIANGLE_STRIP&&c.mode!==Ti.TRIANGLE_FAN&&c.mode!==void 0)return null;let s=n.extensions[this.name].attributes,a=[],o={};for(let c in s)a.push(this.parser.getDependency("accessor",s[c]).then((l)=>(o[c]=l,o[c])));if(a.length<1)return null;return a.push(this.parser.createNodeMesh(e)),Promise.all(a).then((c)=>{let l=c.pop(),u=l.isGroup?l.children:[l],d=c[0].count,f=[];for(let h of u){let b=new Je,m=new j,g=new ln,p=new j(1,1,1),x=new ko(h.geometry,h.material,d);for(let y=0;y<d;y++){if(o.TRANSLATION)m.fromBufferAttribute(o.TRANSLATION,y);if(o.ROTATION)g.fromBufferAttribute(o.ROTATION,y);if(o.SCALE)p.fromBufferAttribute(o.SCALE,y);x.setMatrixAt(y,b.compose(m,g,p))}let _=null;for(let y in o)if(y==="_COLOR_0"){let v=o[y];x.instanceColor=new ls(v.array,v.itemSize,v.normalized)}else if(y!=="TRANSLATION"&&y!=="ROTATION"&&y!=="SCALE"){if(_===null){let E=x.geometry;_=new Ln,_.name=E.name;for(let w in E.attributes)_.setAttribute(w,E.attributes[w]);for(let w in E.morphAttributes)_.morphAttributes[w]=E.morphAttributes[w];if(E.index!==null)_.setIndex(E.index);_.morphTargetsRelative=E.morphTargetsRelative;for(let w of E.groups)_.addGroup(w.start,w.count,w.materialIndex);if(E.boundingBox!==null)_.boundingBox=E.boundingBox.clone();if(E.boundingSphere!==null)_.boundingSphere=E.boundingSphere.clone();_.drawRange.start=E.drawRange.start,_.drawRange.count=E.drawRange.count,_.userData=Object.assign({},E.userData),x.geometry=_}let v=o[y];_.setAttribute(y,new ls(v.array,v.itemSize,v.normalized))}Dt.prototype.copy.call(x,h),this.parser.assignFinalMaterial(x),f.push(x)}if(l.isGroup)return l.clear(),l.add(...f),l;return f[0]})}}var dw="glTF",_l=12,GA={JSON:1313821514,BIN:5130562};class fw{constructor(e){this.name=ut.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,_l),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!==dw)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-_l,r=new DataView(e,_l),s=0;while(s<i){let a=r.getUint32(s,!0);s+=4;let o=r.getUint32(s,!0);if(s+=4,o===GA.JSON){let c=new Uint8Array(e,_l+s,a);this.content=n.decode(c)}else if(o===GA.BIN){let c=_l+s;this.body=e.slice(c,c+a)}s+=a}if(this.content===null)throw Error("THREE.GLTFLoader: JSON content not found.")}}class hw{constructor(e,t){if(!t)throw Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=ut.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,a={},o={},c={};for(let l in s){let u=Tg[l]||l.toLowerCase();a[u]=s[l]}for(let l in e.attributes){let u=Tg[l]||l.toLowerCase();if(s[l]!==void 0){let d=n.accessors[e.attributes[l]],f=Go[d.componentType];c[u]=f.name,o[u]=d.normalized===!0}}return t.getDependency("bufferView",r).then(function(l){return new Promise(function(u,d){i.decodeDracoFile(l,function(f){for(let h in f.attributes){let b=f.attributes[h],m=o[h];if(m!==void 0)b.normalized=m}u(f)},a,c,ci,d)})})}}class pw{constructor(){this.name=ut.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);if(t.rotation!==void 0){let n=Math.cos(e.rotation),i=Math.sin(e.rotation);e.matrix.set(e.repeat.x*n,e.repeat.y*i,e.offset.x,-e.repeat.x*i,e.repeat.y*n,e.offset.y,0,0,1),e.matrixAutoUpdate=!1}return e.needsUpdate=!0,e}}class mw{constructor(){this.name=ut.KHR_MESH_QUANTIZATION}}class Sg extends Vr{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,a=this.valueSize,o=a*2,c=a*3,l=i-t,u=(n-t)/l,d=u*u,f=d*u,h=e*c,b=h-c,m=-2*f+3*d,g=f-d,p=1-m,x=g-d+u;for(let _=0;_!==a;_++){let y=s[b+_+a],v=s[b+_+o]*l,E=s[h+_+a],w=s[h+_]*l;r[_]=p*y+x*v+m*E+g*w}return r}}var S8=new ln;class gw extends Sg{interpolate_(e,t,n,i){let r=super.interpolate_(e,t,n,i);return S8.fromArray(r).normalize().toArray(r),r}}var Ti={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},Go={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},$A={9728:Bi,9729:Tn,9984:gd,9985:Io,9986:Ea,9987:fr},KA={33071:Ro,33648:md,10497:Mo},yg={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Tg={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"},Ts={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},M8={CUBICSPLINE:void 0,LINEAR:Td,STEP:Rm},_g={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function R8(e){if(e.DefaultMaterial===void 0)e.DefaultMaterial=new zr({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:fs});return e.DefaultMaterial}function Pa(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 xr(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 I8(e,t,n){let i=!1,r=!1,s=!1;for(let l=0,u=t.length;l<u;l++){let d=t[l];if(d.POSITION!==void 0)i=!0;if(d.NORMAL!==void 0)r=!0;if(d.COLOR_0!==void 0)s=!0;if(i&&r&&s)break}if(!i&&!r&&!s)return Promise.resolve(e);let a=[],o=[],c=[];for(let l=0,u=t.length;l<u;l++){let d=t[l];if(i){let f=d.POSITION!==void 0?n.getDependency("accessor",d.POSITION):e.attributes.position;a.push(f)}if(r){let f=d.NORMAL!==void 0?n.getDependency("accessor",d.NORMAL):e.attributes.normal;o.push(f)}if(s){let f=d.COLOR_0!==void 0?n.getDependency("accessor",d.COLOR_0):e.attributes.color;c.push(f)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(c)]).then(function(l){let u=l[0],d=l[1],f=l[2];if(i)e.morphAttributes.position=u;if(r)e.morphAttributes.normal=d;if(s)e.morphAttributes.color=f;return e.morphTargetsRelative=!0,e})}function C8(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 N8(e){let t,n=e.extensions&&e.extensions[ut.KHR_DRACO_MESH_COMPRESSION];if(n)t="draco:"+n.bufferView+":"+n.indices+":"+vg(n.attributes);else t=e.indices+":"+vg(e.attributes)+":"+e.mode;if(e.targets!==void 0)for(let i=0,r=e.targets.length;i<r;i++)t+=":"+vg(e.targets[i]);return t}function vg(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 Ag(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 P8(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 O8=new Je;class bw{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new w8,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 a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;let o=a.match(/Version\/(\d+)/);i=n&&o?parseInt(o[1],10):-1,r=a.indexOf("Firefox")>-1,s=r?a.match(/Firefox\/([0-9]+)\./)[1]:-1}if(typeof createImageBitmap>"u"||n&&i<17||r&&s<98)this.textureLoader=new Lo(this.options.manager);else this.textureLoader=new Vd(this.options.manager);if(this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new fl(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 a={scene:s[0][i.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:i.asset,parser:n,userData:{}};return Pa(r,a,i),xr(a,i),Promise.all(n._invokeAll(function(o){return o.afterRoot&&o.afterRoot(a)})).then(function(){for(let o of a.scenes)o.updateMatrixWorld();e(a)})}).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 a=0,o=s.length;a<o;a++)e[s[a]].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,a)=>{let o=this.associations.get(s);if(o!=null)this.associations.set(a,o);for(let[c,l]of s.children.entries())r(l,a.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[ut.KHR_BINARY_GLTF].body);let i=this.options;return new Promise(function(r,s){n.load(Es.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=yg[i.type],a=Go[i.componentType],o=i.normalized===!0,c=new a(i.count*s);return Promise.resolve(new En(c,s,o))}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 a=s[0],o=yg[i.type],c=Go[i.componentType],l=c.BYTES_PER_ELEMENT,u=l*o,d=i.byteOffset||0,f=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,h=i.normalized===!0,b,m;if(f&&f!==u){let g=Math.floor(d/f),p="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+g+":"+i.count,x=t.cache.get(p);if(!x)b=new c(a,g*f,i.count*f/l),x=new il(b,f/l),t.cache.add(p,x);m=new Oo(x,o,d%f/l,h)}else{if(a===null)b=new c(i.count*o);else b=new c(a,d,i.count*o);m=new En(b,o,h)}if(i.sparse!==void 0){let g=yg.SCALAR,p=Go[i.sparse.indices.componentType],x=i.sparse.indices.byteOffset||0,_=i.sparse.values.byteOffset||0,y=new p(s[1],x,i.sparse.count*g),v=new c(s[2],_,i.sparse.count*o);if(a!==null)m=new En(m.array.slice(),m.itemSize,m.normalized);m.normalized=!1;for(let E=0,w=y.length;E<w;E++){let T=y[E];if(m.setX(T,v[E*o]),o>=2)m.setY(T,v[E*o+1]);if(o>=3)m.setZ(T,v[E*o+2]);if(o>=4)m.setW(T,v[E*o+3]);if(o>=5)throw Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=h}return m})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,s=t.images[r],a=this.textureLoader;if(s.uri){let o=n.manager.getHandler(s.uri);if(o!==null)a=o}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let i=this,r=this.json,s=r.textures[e],a=r.images[t],o=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[o])return this.textureCache[o];let c=this.loadImageSource(t,n).then(function(l){if(l.flipY=!1,l.name=s.name||a.name||"",l.name===""&&typeof a.uri==="string"&&a.uri.startsWith("data:image/")===!1)l.name=a.uri;let d=(r.samplers||{})[s.sampler]||{};return l.magFilter=$A[d.magFilter]||Tn,l.minFilter=$A[d.minFilter]||fr,l.wrapS=KA[d.wrapS]||Mo,l.wrapT=KA[d.wrapT]||Mo,l.generateMipmaps=!l.isCompressedTexture&&l.minFilter!==Bi&&l.minFilter!==Tn,i.associations.set(l,{textures:e}),l}).catch(function(){return null});return this.textureCache[o]=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],a=self.URL||self.webkitURL,o=s.uri||"",c=!1;if(s.bufferView!==void 0)o=n.getDependency("bufferView",s.bufferView).then(function(u){c=!0;let d=new Blob([u],{type:s.mimeType});return o=a.createObjectURL(d),o});else if(s.uri===void 0)throw Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let l=Promise.resolve(o).then(function(u){return new Promise(function(d,f){let h=d;if(t.isImageBitmapLoader===!0)h=function(b){let m=new en(b);m.needsUpdate=!0,d(m)};t.load(Es.resolveURL(u,r.path),h,void 0,f)})}).then(function(u){if(c===!0)a.revokeObjectURL(o);return xr(u,s),u.userData.mimeType=s.mimeType||P8(s.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",o),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[ut.KHR_TEXTURE_TRANSFORM]){let a=n.extensions!==void 0?n.extensions[ut.KHR_TEXTURE_TRANSFORM]:void 0;if(a){let o=r.associations.get(s);s=r.extensions[ut.KHR_TEXTURE_TRANSFORM].extendTexture(s,a),r.associations.set(s,o)}}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 a="PointsMaterial:"+n.uuid,o=this.cache.get(a);if(!o)o=new ll,qn.prototype.copy.call(o,n),o.color.copy(n.color),o.map=n.map,o.sizeAttenuation=!1,this.cache.add(a,o);n=o}else if(e.isLine){let a="LineBasicMaterial:"+n.uuid,o=this.cache.get(a);if(!o)o=new cl,qn.prototype.copy.call(o,n),o.color.copy(n.color),o.map=n.map,this.cache.add(a,o);n=o}if(i||r||s){let a="ClonedMaterial:"+n.uuid+":";if(i)a+="derivative-tangents:";if(r)a+="vertex-colors:";if(s)a+="flat-shading:";let o=this.cache.get(a);if(!o){if(o=n.clone(),r)o.vertexColors=!0;if(s)o.flatShading=!0;if(i){if(o.normalScale)o.normalScale.y*=-1;if(o.clearcoatNormalScale)o.clearcoatNormalScale.y*=-1}this.cache.add(a,o),this.associations.set(o,this.associations.get(n))}n=o}e.material=n}getMaterialType(){return zr}loadMaterial(e){let t=this,n=this.json,i=this.extensions,r=n.materials[e],s,a={},o=r.extensions||{},c=[];if(o[ut.KHR_MATERIALS_UNLIT]){let u=i[ut.KHR_MATERIALS_UNLIT];s=u.getMaterialType(),c.push(u.extendParams(a,r,t))}else{let u=r.pbrMetallicRoughness||{};if(a.color=new qe(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){let d=u.baseColorFactor;a.color.setRGB(d[0],d[1],d[2],ci),a.opacity=d[3]}if(u.baseColorTexture!==void 0)c.push(t.assignTexture(a,"map",u.baseColorTexture,ps));if(a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0)c.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),c.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture));s=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,a)})))}if(r.doubleSided===!0)a.side=vi;let l=r.alphaMode||_g.OPAQUE;if(l===_g.BLEND)a.transparent=!0,a.depthWrite=!1;else if(a.transparent=!1,l===_g.MASK)a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:0.5;if(r.normalTexture!==void 0&&s!==mr){if(c.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new Ke(1,1),r.normalTexture.scale!==void 0){let u=r.normalTexture.scale;a.normalScale.set(u,u)}}if(r.occlusionTexture!==void 0&&s!==mr){if(c.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0)a.aoMapIntensity=r.occlusionTexture.strength}if(r.emissiveFactor!==void 0&&s!==mr){let u=r.emissiveFactor;a.emissive=new qe().setRGB(u[0],u[1],u[2],ci)}if(r.emissiveTexture!==void 0&&s!==mr)c.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,ps));return Promise.all(c).then(function(){let u=new s(a);if(r.name)u.name=r.name;if(xr(u,r),t.associations.set(u,{materials:e}),r.extensions)Pa(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(a){return n[ut.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(o){return WA(o,a,t)})}let s=[];for(let a=0,o=e.length;a<o;a++){let c=e[a],l=N8(c),u=i[l];if(u)s.push(u.promise);else{let d;if(c.extensions&&c.extensions[ut.KHR_DRACO_MESH_COMPRESSION])d=r(c);else d=WA(new Ln,c,t);if(c.mode===Ti.TRIANGLE_STRIP)d=d.then((f)=>xg(f,Qc));else if(c.mode===Ti.TRIANGLE_FAN)d=d.then((f)=>xg(f,No));i[l]={primitive:c,promise:d},s.push(d)}}return Promise.all(s)}loadMesh(e){let t=this,n=this.json,i=this.extensions,r=n.meshes[e],s=r.primitives,a=[];for(let o=0,c=s.length;o<c;o++){let l=s[o].material===void 0?R8(this.cache):this.getDependency("material",s[o].material);a.push(l)}return a.push(t.loadGeometries(s)),Promise.all(a).then(async function(o){let c=o.slice(0,o.length-1),l=o[o.length-1],u=[];for(let f=0,h=l.length;f<h;f++){let b=l[f],m=s[f],g,p=c[f];if(m.mode===Ti.TRIANGLES||m.mode===Ti.TRIANGLE_STRIP||m.mode===Ti.TRIANGLE_FAN||m.mode===void 0){let x=r.isSkinnedMesh===!0,_=b.hasAttribute("skinIndex")&&b.hasAttribute("skinWeight");if(x&&_===!1)console.warn("THREE.GLTFLoader: Missing skinIndex or skinWeight attributes. Skinning disabled.");if(g=x&&_?new Cd(b,p):new jt(b,p),g.isSkinnedMesh===!0)g.normalizeSkinWeights()}else if(m.mode===Ti.LINES)g=new Nd(b,p);else if(m.mode===Ti.LINE_STRIP)g=new gs(b,p);else if(m.mode===Ti.LINE_LOOP)g=new Pd(b,p);else if(m.mode===Ti.POINTS)g=new Do(b,p);else throw Error("THREE.GLTFLoader: Primitive mode unsupported: "+m.mode);if(Object.keys(g.geometry.morphAttributes).length>0)C8(g,r);if(g.name=t.createUniqueName(r.name||"mesh_"+e),xr(g,r),m.extensions)Pa(i,g,m);t.assignFinalMaterial(g),u.push(g)}for(let f=0,h=u.length;f<h;f++)t.associations.set(u[f],{meshes:e,primitives:f});if(u.length===1){if(r.extensions)Pa(i,u[0],r);return u[0]}let d=new cr;if(r.extensions)Pa(i,d,r);t.associations.set(d,{meshes:e});for(let f=0,h=u.length;f<h;f++)d.add(u[f]);return d})}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 hn(el.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2000000);else if(n.type==="orthographic")t=new Ca(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar);if(n.name)t.name=this.createUniqueName(n.name);return xr(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,a=[],o=[];for(let c=0,l=s.length;c<l;c++){let u=s[c];if(u){a.push(u);let d=new Je;if(r!==null)d.fromArray(r.array,c*16);o.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new al(a,o)})}loadAnimation(e){let t=this.json,n=this,i=t.animations[e],r=i.name?i.name:"animation_"+e,s=[],a=[],o=[],c=[],l=[];for(let u=0,d=i.channels.length;u<d;u++){let f=i.channels[u],h=i.samplers[f.sampler],b=f.target,m=b.node,g=i.parameters!==void 0?i.parameters[h.input]:h.input,p=i.parameters!==void 0?i.parameters[h.output]:h.output;if(b.node===void 0)continue;s.push(this.getDependency("node",m)),a.push(this.getDependency("accessor",g)),o.push(this.getDependency("accessor",p)),c.push(h),l.push(b)}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(o),Promise.all(c),Promise.all(l)]).then(function(u){let d=u[0],f=u[1],h=u[2],b=u[3],m=u[4],g=[];for(let x=0,_=d.length;x<_;x++){let y=d[x],v=f[x],E=h[x],w=b[x],T=m[x];if(y===void 0)continue;if(y.updateMatrix)y.updateMatrix();let A=n._createAnimationTracks(y,v,E,w,T);if(A)for(let P=0;P<A.length;P++)g.push(A[P])}let p=new To(r,void 0,g);return xr(p,i),p})}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(a){if(!a.isMesh)return;for(let o=0,c=i.weights.length;o<c;o++)a.morphTargetInfluences[o]=i.weights[o]});return s})}loadNode(e){let t=this.json,n=this,i=t.nodes[e],r=n._loadNodeShallow(e),s=[],a=i.children||[];for(let c=0,l=a.length;c<l;c++)s.push(n.getDependency("node",a[c]));let o=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([r,Promise.all(s),o]).then(function(c){let l=c[0],u=c[1],d=c[2];if(d!==null)l.traverse(function(f){if(!f.isSkinnedMesh)return;f.bind(d,O8)});for(let f=0,h=u.length;f<h;f++)l.add(u[f]);if(l.userData.pivot!==void 0&&u.length>0){let f=l.userData.pivot,h=u[0];l.pivot=new j().fromArray(f),l.position.x-=f[0],l.position.y-=f[1],l.position.z-=f[2],h.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):"",a=[],o=i._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});if(o)a.push(o);if(r.camera!==void 0)a.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){a.push(c)}),this.nodeCache[e]=Promise.all(a).then(function(c){let l;if(r.isBone===!0)l=new rl;else if(c.length>1)l=new cr;else if(c.length===1)l=c[0];else l=new Dt;if(l!==c[0])for(let u=0,d=c.length;u<d;u++)l.add(c[u]);if(r.name)l.userData.name=r.name,l.name=s;if(xr(l,r),r.extensions)Pa(n,l,r);if(r.matrix!==void 0){let u=new Je;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 cr;if(n.name)r.name=i.createUniqueName(n.name);if(xr(r,n),n.extensions)Pa(t,r,n);let s=n.nodes||[],a=[];for(let o=0,c=s.length;o<c;o++)a.push(i.getDependency("node",s[o]));return Promise.all(a).then(function(o){for(let l=0,u=o.length;l<u;l++){let d=o[l];if(d.parent!==null)r.add(jA(d));else r.add(d)}let c=(l)=>{let u=new Map;for(let[d,f]of i.associations)if(d instanceof qn||d instanceof en)u.set(d,f);return l.traverse((d)=>{let f=i.associations.get(d);if(f!=null)u.set(d,f)}),u};return i.associations=c(r),r})}_createAnimationTracks(e,t,n,i,r){let s=[],a=e.name?e.name:e.uuid,o=[];function c(f){if(f.morphTargetInfluences)o.push(f.name?f.name:f.uuid)}if(Ts[r.path]===Ts.weights){if(c(e),e.isGroup)e.children.forEach(c)}else o.push(a);let l;switch(Ts[r.path]){case Ts.weights:l=ys;break;case Ts.rotation:l=_s;break;case Ts.translation:case Ts.scale:l=Ia;break;default:switch(n.itemSize){case 1:l=ys;break;case 2:case 3:default:l=Ia;break}break}let u=i.interpolation!==void 0?M8[i.interpolation]:Td,d=this._getArrayFromAccessor(n);for(let f=0,h=o.length;f<h;f++){let b=new l(o[f]+"."+Ts[r.path],t.array,d,u);if(i.interpolation==="CUBICSPLINE")this._createCubicSplineTrackInterpolant(b);s.push(b)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let n=Ag(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 _s?gw:Sg)(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function k8(e,t,n){let i=t.attributes,r=new pn;if(i.POSITION!==void 0){let o=n.json.accessors[i.POSITION],{min:c,max:l}=o;if(c!==void 0&&l!==void 0){if(r.set(new j(c[0],c[1],c[2]),new j(l[0],l[1],l[2])),o.normalized){let u=Ag(Go[o.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 o=new j,c=new j;for(let l=0,u=s.length;l<u;l++){let d=s[l];if(d.POSITION!==void 0){let f=n.json.accessors[d.POSITION],{min:h,max:b}=f;if(h!==void 0&&b!==void 0){if(c.setX(Math.max(Math.abs(h[0]),Math.abs(b[0]))),c.setY(Math.max(Math.abs(h[1]),Math.abs(b[1]))),c.setZ(Math.max(Math.abs(h[2]),Math.abs(b[2]))),f.normalized){let m=Ag(Go[f.componentType]);c.multiplyScalar(m)}o.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(o)}e.boundingBox=r;let a=new ui;r.getCenter(a.center),a.radius=r.min.distanceTo(r.max)/2,e.boundingSphere=a}function WA(e,t,n){let i=t.attributes,r=[];function s(a,o){return n.getDependency("accessor",a).then(function(c){e.setAttribute(o,c)})}for(let a in i){let o=Tg[a]||a.toLowerCase();if(o in e.attributes)continue;r.push(s(i[a],o))}if(t.indices!==void 0&&!e.index){let a=n.getDependency("accessor",t.indices).then(function(o){e.setIndex(o)});r.push(a)}if(ot.workingColorSpace!==ci&&"COLOR_0"in i)console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ot.workingColorSpace}" not supported.`);return xr(e,t),k8(e,t,n),Promise.all(r).then(function(){return t.targets!==void 0?I8(e,t.targets,n):e})}function yr(e){let t=new Set,n=new Set,i=new Set;e.traverse((r)=>{let s=r;if(!s.isMesh)return;t.add(s.geometry);for(let a of Array.isArray(s.material)?s.material:[s.material]){n.add(a);for(let o of Object.values(a))if(o instanceof en)i.add(o)}});for(let r of[...t,...n,...i])r.dispose()}async function xw(e){cp(e);let t=new dl,n=!1;t.onError=()=>{n=!0},t.addHandler(/^data:image\//,new Lo(t)),t.setURLModifier((s)=>{if(!s.startsWith("blob:")&&!s.startsWith("data:"))throw Error("External model resources are not loaded");return s});let i=new wg(t);i.register((s)=>({name:"KILN_embedded_images",async beforeRoot(){for(let a of s.json.images??[]){if(a.bufferView===void 0)continue;let o=new Uint8Array(await s.getDependency("bufferView",a.bufferView)),c="";for(let l=0;l<o.length;l+=8192)c+=String.fromCharCode(...o.subarray(l,l+8192));if(!/^image\/(png|jpeg|webp|avif)$/.test(a.mimeType??""))throw Error("Unsupported embedded image type");a.uri=`data:${a.mimeType};base64,${btoa(c)}`,delete a.bufferView}}}));let r=await i.parseAsync(Uint8Array.from(e).buffer,"");if(n){for(let s of r.scenes)yr(s);throw Error("An embedded texture could not be decoded.")}return Object.assign(r,{assertTexturesLoaded(){if(n)throw Error("An embedded texture could not be decoded.")}})}ji();function yw(e,t,n=40,i=[e]){let r=e.getCenter(new j),s=Math.max(e.getSize(new j).length()/2,0.01),a=new j(1,0.65,1.25).normalize(),o=new j().crossVectors(new j(0,1,0),a).normalize(),c=new j().crossVectors(a,o),l=[];for(let x of i.length?i:[e])for(let _ of[x.min.x,x.max.x])for(let y of[x.min.y,x.max.y])for(let v of[x.min.z,x.max.z])l.push(new j(_,y,v));let u=1/0,d=-1/0,f=1/0,h=-1/0;for(let x of l){let _=x.clone().sub(r),y=_.dot(o),v=_.dot(c);u=Math.min(u,y),d=Math.max(d,y),f=Math.min(f,v),h=Math.max(h,v)}r.addScaledVector(o,(u+d)/2),r.addScaledVector(c,(f+h)/2);let b=Math.tan(n*Math.PI/360),m=b*t,g=s;for(let x of l){let _=x.clone().sub(r),y=_.dot(a);g=Math.max(g,y+Math.abs(_.dot(o))*1.12/m,y+Math.abs(_.dot(c))*1.12/b)}let p=r.clone().addScaledVector(a,g);return{center:r,radius:s,distance:g,position:p}}ji();function Mg(e,t){return{position:e.position.clone(),target:t.clone()}}function Rg(e,t,n,i){e.position.copy(n.position),t.copy(n.target);let r=Math.max(i.getSize(new j).length(),0.001);e.near=Math.min(0.01,Math.max(r/1e5,0.00001)),e.far=Math.max(e.position.distanceTo(i.getCenter(new j))+r*20,10),e.updateProjectionMatrix()}function _w(e,t,n){let i=e.getWorldDirection(new j);if(i.y=0,i.lengthSq()<0.00000001)i.set(0,0,-1);i.normalize();let r=i.clone().cross(new j(0,1,0)),s=new j;if(t.has("KeyW")||t.has("ArrowUp"))s.add(i);if(t.has("KeyS")||t.has("ArrowDown"))s.sub(i);if(t.has("KeyD")||t.has("ArrowRight"))s.add(r);if(t.has("KeyA")||t.has("ArrowLeft"))s.sub(r);if(t.has("KeyE"))s.y++;if(t.has("KeyQ"))s.y--;return s.normalize().multiplyScalar(n)}function vw(e){let t=e.filter((i)=>Number.isFinite(i)&&i>0).sort((i,r)=>i-r);if(!t.length)throw Error("No frame timing evidence was collected.");let n=(i)=>t[Math.max(0,Math.ceil(t.length*i)-1)];return{samples:t.length,min:t[0],p50:n(0.5),p95:n(0.95),max:t.at(-1)}}async function Ew(e,t){let n=t();if(n===void 0)throw Error("Wait for the selected artifact to be loaded before measuring.");let i=JSON.stringify(n),r=await e();if(JSON.stringify(t())!==i)throw Error("The artifact changed during measurement. Measure the loaded revision again.");return{...r,artifact:n}}function Tw(e,t,n){if(t())return e;n(e);return}ji();function qd(e,t){let n=e.parser.json.nodes??[],i=new Set;if(n.forEach((s,a)=>{if(s?.extensions?.KHR_node_visibility?.visible===!1)i.add(a)}),i.size===0)return 0;let r=0;for(let s of t)s.traverse((a)=>{let o=e.parser.associations.get(a)?.nodes;if(o===void 0||!i.has(o))return;a.visible=!1,r++});return r}function Jd(e){let t=!1;if(e.traverse((s)=>{if(!s.visible)t=!0}),!t)return new pn().setFromObject(e,!0);e.updateWorldMatrix(!0,!0);let n=new pn,i=new pn,r=new j;return e.traverseVisible((s)=>{let a=s,o=a.geometry;if(!o)return;let c=o.getAttribute("position");if(c&&a.isInstancedMesh!==!0){for(let u=0;u<c.count;u++){if(a.isMesh)a.getVertexPosition(u,r);else r.fromBufferAttribute(c,u);n.expandByPoint(r.applyMatrix4(s.matrixWorld))}return}let l=s;if(l.boundingBox!==void 0){if(l.boundingBox===null)l.computeBoundingBox();i.copy(l.boundingBox)}else{if(o.boundingBox===null)o.computeBoundingBox();i.copy(o.boundingBox)}n.union(i.applyMatrix4(s.matrixWorld))}),n.isEmpty()?new pn().setFromObject(e,!0):n}function vl(e){let t=0;return e.traverseVisible((n)=>{let i=n;if(!i.isMesh)return;let r=i.geometry.index?.count??i.geometry.attributes.position?.count??0;t+=r/3*(i.isInstancedMesh?i.count:1)}),t}async function Aw(e){let t=e.parser.json.nodes??[],n=new Map;e.scene.traverse((c)=>{let l=e.parser.associations.get(c)?.nodes;if(l!==void 0&&!n.has(l))n.set(l,c)});let i=new Set,r=[];for(let[c,l]of n){let u=t[c]?.extensions?.MSFT_lod?.ids;if(!Array.isArray(u)||u.length===0)continue;if(u.some((b)=>!Number.isInteger(b)||!t[b]||n.has(b)))continue;let d=l.parent;while(d&&!i.has(d))d=d.parent;if(d)continue;let f=[l];for(let b of u)f.push(await e.parser.getDependency("node",b));qd(e,f.slice(1)),i.add(l);let h=(l.name.replace(/[_ -]?LOD0$/i,"")||l.parent?.name||`Part ${c}`).replace(/^Mesh_/,"");r.push({id:String(c),label:h,levels:f})}if(r.length===0)return;let s=vl(e.scene)-r.reduce((c,l)=>c+Ig(l,0),0),a=Math.max(...r.map((c)=>c.levels.length)),o=Array.from({length:a},(c,l)=>s+r.reduce((u,d)=>u+Ig(d,l),0));return{chains:r,triangles:o}}var ww=(e,t)=>e.levels[Math.min(Math.max(Number.isFinite(t)?Math.floor(t):0,0),e.levels.length-1)];function Ig(e,t){let n=e.levels.find((i)=>i.parent)?.parent;while(n){if(!n.visible)return 0;n=n.parent}return vl(ww(e,t))}function Sw(e,t){let n=ww(e,t),i=e.levels.find((s)=>s.parent!==null);if(!i||i===n)return;let r=i.parent;r.children[r.children.indexOf(i)]=n,n.parent=r,i.parent=null}function Mw(e,t){for(let n of e.chains)Sw(n,t)}function Rw(e,t,n){let i=e.chains.find((r)=>r.id===t);if(!i)return!1;return Sw(i,n),!0}function Iw(e,t){if(!e)return;return{triangles:vl(t),levels:e.triangles,chains:e.chains.map((n)=>({id:n.id,label:n.label,level:n.levels.findIndex((i)=>i.parent!==null),triangles:n.levels.map((i,r)=>Ig(n,r))}))}}function $o(e){return(e?.chains??[]).flatMap((t)=>t.levels.filter((n)=>n.parent===null))}function Cg(e){return e.map((t,n)=>`LOD${n} · ${t.toLocaleString()} triangles`)}function El(e){let t=new fg({antialias:!0,alpha:!1});t.setPixelRatio(Math.min(devicePixelRatio,2)),t.setClearColor(1382930),t.toneMapping=Jc,t.toneMappingExposure=1.15,e.replaceChildren(t.domElement);let n=new Po,i=new hn(40,1,0.01,1000),r=new gg(i,t.domElement);r.enableDamping=!0,t.domElement.tabIndex=0,t.domElement.setAttribute("aria-label","Interactive 3D asset. Drag to orbit or use Explore navigation.");let s=new Set,a=!1,o=1,c=new Set(["KeyW","KeyA","KeyS","KeyD","KeyQ","KeyE","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","ShiftLeft","ShiftRight"]),l=(O)=>{if(!a||!c.has(O.code))return;O.preventDefault(),s.add(O.code)},u=(O)=>s.delete(O.code),d=()=>s.clear();t.domElement.addEventListener("keydown",l),t.domElement.addEventListener("keyup",u),t.domElement.addEventListener("blur",d);let f=new yl(t),h=new bg,b=f.fromScene(h,0.04);n.environment=b.texture,h.dispose(),f.dispose();let m=new Bo(16773591,2.4);m.position.set(4,8,5),n.add(m),n.add(new Ud(14806490,5065021,1.7));let g,p,x,_=[],y=!0,v=performance.now(),E=0,w=0,T=!1,A,P,S,R=(O)=>{if(!S)return;clearTimeout(S.timeout),S.reject(Error(O)),S=void 0},k=(O)=>{let K=t.getContext(),B=K.getExtension("WEBGL_debug_renderer_info");return{version:"kiln.viewer-performance.v1",measuredAt:new Date().toISOString(),windowMs:O-S.started,frameMs:vw(S.samples),...P===void 0?{}:{loadToFirstFrameMs:P},drawCalls:t.info.render.calls,triangles:t.info.render.triangles,lines:t.info.render.lines,points:t.info.render.points,geometryObjects:t.info.memory.geometries,textureObjects:t.info.memory.textures,shaderPrograms:t.info.programs?.length??0,viewport:{cssWidth:e.clientWidth,cssHeight:e.clientHeight,bufferWidth:t.domElement.width,bufferHeight:t.domElement.height,devicePixelRatio:t.getPixelRatio()},renderer:{version:String(K.getParameter(K.VERSION)),vendor:String(K.getParameter(K.VENDOR)),renderer:String(K.getParameter(K.RENDERER)),browser:navigator.userAgent,...B?{unmaskedVendor:String(K.getParameter(B.UNMASKED_VENDOR_WEBGL)),unmaskedRenderer:String(K.getParameter(B.UNMASKED_RENDERER_WEBGL))}:{}},camera:{position:i.position.toArray(),target:r.target.toArray(),fov:i.fov},limitations:["Exploratory measurement: workloads outside this page are uncontrolled. This is not an isolated performance baseline or budget acceptance.","Frame intervals measure browser requestAnimationFrame pacing, including scheduling and vertical sync; they are not GPU execution time.","Load-to-first-frame begins at GLB parsing and ends after the first render submission; it excludes download time and does not measure presentation latency.","Draw and resource counts come from this Three.js renderer, including studio lighting resources. Object counts are not GPU memory bytes.","This receipt describes this viewport, camera and device only. It is not a performance qualification for other consumers or hardware."]}},C=()=>{if(!g)return;let O=Jd(g),K=[];g.traverseVisible((de)=>{if(de instanceof jt||de instanceof gs||de instanceof Do){let Me=new pn().setFromObject(de,!0);if(!Me.isEmpty())K.push(Me)}});let{center:B,radius:X,distance:q,position:le}=yw(O,i.aspect,i.fov,K);if(r.target.copy(B),i.position.copy(le),i.near=Math.max(X/1000,0.0001),i.far=q+X*100,r.minDistance=X*0.1,r.maxDistance=X*80,o=Math.max(X*0.35,0.01),a)r.minDistance=X*0.00001;i.updateProjectionMatrix(),r.update()},U=new ResizeObserver(()=>{let{clientWidth:O,clientHeight:K}=e;if(!O||!K)return;t.setSize(O,K),i.aspect=O/K,i.updateProjectionMatrix()});U.observe(e);let L=(O)=>{if(T)return;let K=Math.min((O-v)/1000,0.1);if(v=O,e.clientWidth&&e.clientHeight){if(y)x?.update(K);if(a&&s.size){let B=_w(i,s,K*o*(s.has("ShiftLeft")||s.has("ShiftRight")?3:1));i.position.add(B),r.target.add(B)}if(r.update(),t.render(n,i),A!==void 0)P=performance.now()-A,A=void 0;if(S){if(S.previous>0&&S.samples.length<1800)S.samples.push(O-S.previous);if(S.previous=O,O-S.started>=S.duration&&S.samples.length){let B=k(O);clearTimeout(S.timeout),S.resolve(B),S=void 0}}}else s.clear(),R("Keep the measured viewport visible for the complete sampling window.");E=requestAnimationFrame(L)};return E=requestAnimationFrame(L),{async load(O,K={}){let B=performance.now(),X=++w;R("The artifact changed during measurement. Measure the new revision again.");let q=await xw(O);qd(q,[q.scene]);let le=await Aw(q);try{q.assertTexturesLoaded()}catch(ne){yr(q.scene);for(let ie of $o(le))yr(ie);throw ne}let de=Tw(q,()=>!T&&X===w&&K.isCurrent?.()!==!1,(ne)=>{yr(ne.scene);for(let ie of $o(le))yr(ie)});if(!de)return;let Me=g&&K.preserveView?Mg(i,r.target):void 0;if(g){x?.stopAllAction(),x?.uncacheRoot(g),n.remove(g),yr(g);for(let ne of $o(p))yr(ne)}g=de.scene,p=le,A=B,P=void 0,n.add(g),_=de.animations,x=new jd(g),y=!0;let{clientWidth:pe,clientHeight:J}=e;if(t.setSize(pe,J),i.aspect=pe&&J?pe/J:i.aspect,C(),Me)Rg(i,r.target,Me,Jd(g)),r.update();let F=0,W=new Set;return g.traverseVisible((ne)=>{let ie=ne;if(!ie.isMesh)return;F++;for(let ce of Array.isArray(ie.material)?ie.material:[ie.material])W.add(ce)}),K.onCommit?.(),{triangles:vl(g),meshes:F,materials:W.size,clips:_.map((ne)=>ne.name),...p?{levels:p.triangles}:{}}},level(O){if(R("The level of detail changed. Measure the displayed combination again."),p)Mw(p,O)},partLevel(O,K){if(R("The level of detail changed. Measure the displayed combination again."),p)Rw(p,O,K)},lod(){return g?Iw(p,g):void 0},reset:C,cancelMeasurement:R,measure(O=3000){if(T||!g||!e.clientWidth||!e.clientHeight)return Promise.reject(Error("Load an artifact in a visible viewport before measuring."));if(!Number.isFinite(O)||O<1000||O>5000)return Promise.reject(Error("Measurement duration must be 1–5 seconds."));if(S)return Promise.reject(Error("A measurement is already running."));return new Promise((K,B)=>{S={started:performance.now(),previous:0,duration:O,samples:[],resolve:K,reject:B,timeout:setTimeout(()=>R("Measurement was interrupted or the browser stopped delivering frames."),O+2000)}})},view(){return Mg(i,r.target)},setView(O){if(!g)return;Rg(i,r.target,O,Jd(g)),r.update()},navigation(O){if(a=O==="explore",s.clear(),r.minDistance=a?0.00001:o/3.5,a)i.near=0.0001,i.updateProjectionMatrix()},wire(O){for(let K of g?[g,...$o(p)]:[])K.traverse((B)=>{let X=B;if(X.isMesh){for(let q of Array.isArray(X.material)?X.material:[X.material])if("wireframe"in q)q.wireframe=O}})},lighting(O){t.toneMappingExposure=O==="bright"?1.65:O==="soft"?0.85:1.15,m.intensity=O==="soft"?0.8:2.4},clip(O){if(x?.stopAllAction(),_[O])x?.clipAction(_[O]).play()},pause(O){y=!O},dispose(){if(R("The viewport closed before measurement finished."),T=!0,w++,cancelAnimationFrame(E),U.disconnect(),r.dispose(),t.domElement.removeEventListener("keydown",l),t.domElement.removeEventListener("keyup",u),t.domElement.removeEventListener("blur",d),g)yr(g);for(let O of $o(p))yr(O);b.dispose(),t.dispose(),e.replaceChildren()}}}var ue=(e)=>document.getElementById(e);function D(e,t,n){let i=document.createElement(e);if(t!==void 0)i.textContent=t;if(n)i.className=n;return i}function In(e){let t=ue("dashboard-status");t.textContent=e instanceof Error?e.message:String(e),t.hidden=!t.textContent}async function un(e,t){let n=await fetch(e,t?{method:t.method,headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)}:void 0),i=await n.json();if(!n.ok)throw Error(i.error??`Request failed (${n.status})`);return i}function Ko(e,t){let n=D("div",void 0,"empty");return n.append(D("b",e),D("p",t)),n}function Hi(e,t){try{localStorage.setItem(e,t)}catch{}}function As(e){try{return localStorage.getItem(e)}catch{return null}}function An(e){return e?e.slice(0,15):"Unspecified"}function Wo(e,t){let n=D("details",void 0,"record-details");return n.append(D("summary",e),D("pre",JSON.stringify(t,null,2))),n}function Tl(e,t,n,i){let r=n.lod();if(e.hidden=!r,t.hidden=!r,t.replaceChildren(),e.replaceChildren(),e.onchange=null,!r)return;e.append(...Cg(r.levels).map((l,u)=>new Option(l,String(u))));let s=new Option("Mixed part levels","mixed");s.disabled=!0,e.append(s);let a=D("p","","lod-total");a.setAttribute("role","status"),t.append(a);let o=new Map;if(r.chains.length>1){let l=D("details",void 0,"lod-parts");l.append(D("summary","Per-part levels")),l.append(D("p","Choose a level for each part. The main selector sets every part to the same index.","subtle"));let u=D("div",void 0,"lod-part-fields"),d=new Set(r.chains.filter((f,h,b)=>b.findIndex((m)=>m.label===f.label)!==h).map((f)=>f.label));for(let[f,h]of r.chains.entries()){let b=d.has(h.label)?`${h.label} (part ${f+1})`:h.label,m=D("label",b,"inline-field"),g=D("select");g.setAttribute("aria-label",`${b} level of detail`),g.append(...Cg(h.triangles).map((p,x)=>new Option(p,String(x)))),g.onchange=()=>{n.partLevel(h.id,Number(g.value)),c(),i?.()},o.set(h.id,g),m.append(g),u.append(m)}l.append(u),t.append(l)}function c(){let l=n.lod();if(!l)return;let u=l.levels.findIndex((d,f)=>l.chains.every((h)=>h.level===Math.min(f,h.triangles.length-1)));e.value=u<0?"mixed":String(u),a.textContent=`${l.triangles.toLocaleString()} triangles displayed`;for(let d of l.chains){let f=o.get(d.id);if(f)f.value=String(d.level)}}return e.onchange=()=>{if(e.value==="mixed")return;let l=Number(e.value);n.level(l),c(),i?.(l)},c(),{refresh:c}}var Cw=/^[a-z][a-z0-9_-]{0,79}$/u,D8=/^r_[a-z0-9_-]{1,77}$/u;function Nw(e){let t=new URLSearchParams(e),n=t.get("collection"),i=t.get("asset"),r=t.get("revision");if(!n||!i||!r||!Cw.test(n)||!Cw.test(i)||!D8.test(r))return;return{collection:n,assetId:i,revisionId:r}}Pg();var fb=new TextEncoder,AB=new TextDecoder,ec=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),db=(e,t)=>Object.hasOwn(e,t);async function AR(e){let t=await crypto.subtle.digest("SHA-256",Uint8Array.from(e));return`sha256:${Array.from(new Uint8Array(t),(n)=>n.toString(16).padStart(2,"0")).join("")}`}function wB(e){if(e.length>200||!/^[a-z0-9][a-z0-9._-]*\.kiln-metadata\.json$/i.test(e)||/^(con|prn|aux|nul|com[0-9]|lpt[0-9])\./i.test(e))throw Error("Runtime metadata filename must be a portable sibling *.kiln-metadata.json filename")}function SB(e){if(e.length>200||!/^[a-z0-9][a-z0-9._-]*\.gltf$/i.test(e)||/^(con|prn|aux|nul|com[0-9]|lpt[0-9])\./i.test(e))throw Error("External texture output must be a portable sibling *.gltf filename")}function MB(e,t){if(t+8>e.length)return;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(t+4,!0)!==5130562)return;return e.subarray(t+8,t+8+n.getUint32(t,!0))}function RB(e){let t=new Map;for(let i of[...Lc(e),...(e.materialResources?.records??[]).map(({manifest:r})=>r)])t.set(`${i.materialId}/${i.revisionId}`,i);let n=(i,r)=>i<r?-1:i>r?1:0;return[...t.values()].flatMap((i)=>i.maps.map((r)=>({sha256:r.sha256,pin:{resourceId:i.materialId,revisionId:i.revisionId,sha256:i.revisionId},slot:r.slot}))).sort((i,r)=>n(i.pin.resourceId,r.pin.resourceId)||n(i.pin.revisionId,r.pin.revisionId)||n(i.slot,r.slot))}function wR(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=12;while(n<e.length){if(n+8>e.length)throw Error("Invalid GLB chunk header");let s=t.getUint32(n,!0);if(s%4||n+8+s>e.length)throw Error("Invalid GLB chunk length");n+=8+s}let i=20+t.getUint32(12,!0),r=JSON.parse(AB.decode(e.subarray(20,i)));if(!ec(r)||!ec(r.asset)||r.asset.version!=="2.0")throw Error("Invalid glTF asset");return{json:r,jsonEnd:i}}function SR(e,t,n){let i=fb.encode(JSON.stringify(n)),r=Math.ceil(i.length/4)*4,s=new Uint8Array(20+r+e.length-t);if(s.length>Wn)throw Error("Runtime export exceeds 64 MiB");s.set(e.subarray(0,20));let a=new DataView(s.buffer);return a.setUint32(8,s.length,!0),a.setUint32(12,r,!0),s.fill(32,20,20+r),s.set(i,20),s.set(e.subarray(t),20+r),s}async function IB(e,t,n={}){let[{deliverRuntimeThreeGlb:i},{MeshoptEncoder:r}]=await Promise.all([Promise.resolve().then(() => (bR(),gR)),Promise.resolve().then(() => (TR(),ER))]);await r.ready;let s=await i(e,r,t,n);if(s.glb.byteLength>Wn)throw Error("Runtime export exceeds 64 MiB");return s}async function MR(e,t={}){let n=t.profile??"editable";if(n!=="editable"&&n!=="runtime")throw Error("Unknown export profile");if(t.target!==void 0&&t.target!=="three")throw Error("Unknown runtime export target");if(t.target!==void 0&&n!=="runtime")throw Error("A runtime export target requires the runtime profile");if(t.compression!==void 0&&t.target!=="three")throw Error("Runtime compression requires the three runtime target");if(t.maxLod!==void 0&&t.target!=="three")throw Error("Runtime maxLod requires the three runtime target");if(t.positionBits!==void 0&&t.target!=="three")throw Error("Runtime positionBits requires the three runtime target");let i=t.textures;if(i!==void 0&&i!=="manifest"&&i!=="external")throw Error("Unknown runtime texture option");if(i!==void 0&&n!=="runtime")throw Error("A texture manifest requires the runtime profile");if(i==="external"&&t.target!=="three")throw Error("External textures require target three");let r=t.gltfFileName??"runtime.gltf";if(i==="external")SB(r);Uu(e);let s=e.files["asset.glb"];if(n==="editable")return{profile:n,glb:s};let a=t.metadataFileName??"runtime.kiln-metadata.json";wB(a);for(let[A,P]of Object.entries(e.files))if(await AR(P)!==e.manifest.files[A].sha256)throw Error(`Asset integrity mismatch: ${A}`);let{json:o,jsonEnd:c}=wR(s),l=o.asset;if(db(l,"extras")&&!ec(l.extras))throw Error("Cannot add provenance to non-object asset extras");let u=l.extras??{};if(db(u,"kilnProvenanceV1"))throw Error("Asset extras already contain kilnProvenanceV1; export from the canonical revision");let d=[];if(o.scenes!==void 0&&!Array.isArray(o.scenes))throw Error("Invalid glTF scenes");for(let[A,P]of(o.scenes??[]).entries()){if(!ec(P)||!ec(P.extras)||!db(P.extras,"kilnReviewClipsV1"))continue;let S=P.extras.kilnReviewClipsV1;if(!ec(S)||S.version!==1&&S.version!==2||!Array.isArray(S.clips))throw Error("Unsupported scenes[].extras.kilnReviewClipsV1");d.push({index:A,kilnReviewClipsV1:S}),delete P.extras.kilnReviewClipsV1}let f={version:"kiln.runtime-metadata.v1",source:{assetId:e.manifest.assetId,revisionId:e.manifest.revisionId,glbSha256:e.manifest.files["asset.glb"].sha256,...e.manifest.files["source.kiln.js"]?{sourceSha256:e.manifest.files["source.kiln.js"].sha256}:{}},scenes:d},h=s,b=o,m=c,g,p;if(t.target==="three"){let A=await IB(SR(s,c,o),{...t.ktx2Encoder?{ktx2Encoder:t.ktx2Encoder}:{},...t.compression?{compression:t.compression}:{},...t.maxLod!==void 0?{maxLod:t.maxLod}:{},...t.positionBits!==void 0?{positionBits:t.positionBits}:{}},i==="external"?{gltfBasename:r.slice(0,-5)}:{});f.target="three",f.delivery=A.delivery,h=A.glb,g=A.imageSources,p=A.gltf,{json:b,jsonEnd:m}=wR(h)}if(i!==void 0)f.textures=await Pw(b,MB(h,m),{...g?{sources:g}:{},maps:RB(e)});let x=p?await CB(p,f.textures??[]):void 0,_=fb.encode(JSON.stringify(f));if(_.length>Wn)throw Error("Runtime export exceeds 64 MiB");let y={version:"kiln.provenance.v1",profile:"runtime",...t.target?{target:t.target}:{},metadata:{uri:a,sha256:await AR(_)}},v=b.asset;v.extras={...v.extras??u,kilnProvenanceV1:y};let E=SR(h,m,b);if(!x)return{profile:n,glb:E,metadata:{name:a,bytes:_}};let w=x.json.asset;w.extras={...w.extras??u,kilnProvenanceV1:y};let T=fb.encode(JSON.stringify(x.json));if(T.length>Wn)throw Error("Runtime export exceeds 64 MiB");return{profile:n,layout:"gltf",glb:E,gltf:{name:r,bytes:T},buffers:x.buffers,textures:x.textures,metadata:{name:a,bytes:_}}}async function CB(e,t){let n=structuredClone(e.json),i=new Map(Object.entries(e.resources)),r=Array.isArray(n.images)?n.images:[];if(r.length!==t.length)throw Error("External texture layout mismatch");let s=new Map;for(let[o,c]of r.entries()){let l=t[o],u=typeof c.uri==="string"?c.uri:"",d=i.get(u);if(!d||`sha256:${await Al(d)}`!==l.sha256)throw Error("External texture bytes differ from the delivered GLB");i.delete(u);let f=`textures/${l.sha256.slice(7)}.${Ow(l.mimeType)}`;c.uri=f,l.uri=f,s.set(f,{uri:f,sha256:l.sha256,bytes:d})}let a=[...i].map(([o,c])=>({uri:o,bytes:c}));for(let{uri:o}of a)if(!/^[a-z0-9][a-z0-9._-]*\.bin$/i.test(o))throw Error(`Unexpected external glTF resource ${o}`);return{json:n,buffers:a,textures:[...s.values()]}}var Wi=Fe().regex(/^[a-z][a-z0-9_-]{0,79}$/).refine((e)=>!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(e),"Reserved filesystem name"),hb=Fe().regex(/^r_[0-9]{10}_[a-f0-9]{64}$/),CR=Fe().regex(/^sha256:[a-f0-9]{64}$/),tc=Fe().max(4000),NR=Fe().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/),RR=be({collectionId:Wi,assetId:Wi,revisionId:Wi}).strict(),IR=be({style:tc.default(""),scale:Fe().max(1000).default(""),palette:at(be({role:Fe().min(1).max(100),color:Fe().regex(/^#[a-fA-F0-9]{6}$/)}).strict()).max(64).default([]),materialRoles:at(be({role:Fe().min(1).max(100),description:tc.default(""),resourceId:NR.optional()}).strict()).max(128).default([]),conventions:at(Fe().max(1000)).max(100).default([]),exceptions:at(Fe().max(1000)).max(100).default([])}).strict(),NB=be({resourceId:NR,revisionId:Fe().min(1).max(200),sha256:CR,role:Fe().max(100).optional()}).strict(),PB=at(NB).max(512),vr={name:Fe().trim().min(1).max(200),brief:Fe().max(16000).default(""),design:IR.default(()=>IR.parse({})),inventory:at(be({id:Wi,name:Fe().trim().min(1).max(200),kind:Ct(["asset","environment"]).default("asset"),brief:tc.default(""),references:at(Wi).max(64).default([]),asset:RR.optional()}).strict()).max(1000).default([]),deliveryProfiles:at(be({id:Wi,target:Ct(["three","godot","unity","unreal","roblox","sbox","usdz","custom"]),description:tc.default(""),performanceIntent:Fe().max(1000).default(""),constraints:at(Fe().max(1000)).max(100).default([])}).strict()).max(32).default([]),materialDependencies:PB.default([]),references:at(be({id:Wi,title:Fe().min(1).max(200),uri:Fe().min(1).max(2048),description:tc.default(""),sha256:CR.optional()}).strict()).max(256).default([]),reviews:at(be({id:Wi,inventoryId:Wi,projectRevisionId:hb,asset:RR,reviewer:Fe().trim().min(1).max(200),verdict:Ct(["comment","changes-requested","accepted"]),notes:tc}).strict()).max(2000).default([])};function PR(e,t){let n=(a,o)=>{if(new Set(a).size!==a.length)t.addIssue({code:vu.custom,path:[o],message:"Duplicate identity"})};n(e.inventory.map((a)=>a.id),"inventory"),n(e.references.map((a)=>a.id),"references"),n(e.deliveryProfiles.map((a)=>a.id),"deliveryProfiles"),n(e.materialDependencies.map((a)=>a.resourceId),"materialDependencies"),n(e.reviews.map((a)=>a.id),"reviews"),n(e.design.palette.map((a)=>a.role),"design.palette"),n(e.design.materialRoles.map((a)=>a.role),"design.materialRoles");let i=new Set(e.references.map((a)=>a.id)),r=new Set(e.inventory.map((a)=>a.id)),s=new Set(e.materialDependencies.map((a)=>a.resourceId));for(let a of e.inventory)if(n(a.references,`inventory.${a.id}.references`),a.references.some((o)=>!i.has(o)))t.addIssue({code:vu.custom,path:["inventory"],message:"Unknown reference"});if(e.reviews.some((a)=>!r.has(a.inventoryId)))t.addIssue({code:vu.custom,path:["reviews"],message:"Unknown inventory item"});if(e.design.materialRoles.some((a)=>a.resourceId&&!s.has(a.resourceId)))t.addIssue({code:vu.custom,path:["design"],message:"Material role requires a locked resource"})}var OR=be({projectId:Wi.optional(),...vr}).strict().superRefine(PR),wX=be({name:vr.name.optional(),brief:vr.brief.removeDefault().optional(),design:vr.design.removeDefault().optional(),inventory:vr.inventory.removeDefault().optional(),deliveryProfiles:vr.deliveryProfiles.removeDefault().optional(),materialDependencies:vr.materialDependencies.removeDefault().optional(),references:vr.references.removeDefault().optional(),reviews:vr.reviews.removeDefault().optional()}).strict(),SX=be({version:$e("kiln.project.v1"),projectId:Wi,revisionId:hb,parentRevision:hb.optional(),createdAt:Fe().datetime(),...vr}).strict().superRefine(PR);function kR(e){let{palette:t,materialRoles:n,conventions:i,exceptions:r}=e.design??{};return{design:{palette:t??[],materialRoles:n??[],conventions:i??[],exceptions:r??[]},inventory:e.inventory??[],deliveryProfiles:e.deliveryProfiles??[],materialDependencies:e.materialDependencies??[],references:e.references??[],reviews:e.reviews??[]}}function DR(e,t){let n=JSON.parse(e);if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Project configuration must be a JSON object.");let i=n,r=i.design??{};if(!r||typeof r!=="object"||Array.isArray(r))throw Error("Design configuration must be a JSON object.");return OR.parse({...i,name:t.name,brief:t.brief,design:{...r,style:t.style,scale:t.scale}})}function LR(e){let t=[],n=As("kiln.project")??"",i,r=()=>{let c=ue("project-list");c.replaceChildren();for(let _ of t){let y=D("button",void 0,_.projectId===n?"active":"");if(y.append(D("strong",_.name),D("small",`${_.inventory.length} inventory items · ${_.materialDependencies.length} resources`)),_.projectId===n)y.setAttribute("aria-current","true");y.onclick=()=>{n=_.projectId,Hi("kiln.project",n),r()},c.append(y)}let l=t.find((_)=>_.projectId===n),u=ue("project-detail");if(u.replaceChildren(),!l){u.append(Ko("A direction for what comes next.","Projects are optional. Group related assets, materials and design decisions here, or build and review standalone assets in Library and Live Review."));return}let d=D("div",void 0,"project-summary"),f=D("div");f.append(D("h2",l.name),D("p",l.brief||"Add a brief to describe what this project should deliver."));let h=D("button","Edit project","secondary");h.onclick=()=>a(l),d.append(f,h),u.append(d);let b=D("p",`${l.projectId} · ${An(l.revisionId)} · ${new Date(l.createdAt).toLocaleString()}`,"mono");u.append(b);let m=D("div",void 0,"project-metrics");for(let[_,y]of[[l.inventory.length,"inventory items"],[l.materialDependencies.length,"locked resources"],[l.deliveryProfiles.length,"delivery profiles"]]){let v=D("div");v.append(D("strong",String(_)),D("span",String(y))),m.append(v)}u.append(m);let g=D("div",void 0,"profile-grid");for(let[_,y]of[["Visual direction",l.design.style||"Not specified"],["Scale",l.design.scale||"Not specified"]]){let v=D("div");v.append(D("span",_,"label"),D("p",y)),g.append(v)}u.append(g);let p=D("div",void 0,"palette");for(let _ of l.design.palette){let y=D("div",void 0,"swatch"),v=document.createElementNS("http://www.w3.org/2000/svg","svg");v.setAttribute("viewBox","0 0 24 24"),v.setAttribute("aria-hidden","true");let E=document.createElementNS("http://www.w3.org/2000/svg","rect");E.setAttribute("width","24"),E.setAttribute("height","24"),E.setAttribute("fill",_.color),v.append(E);let w=D("span",_.role);w.append(D("small",_.color)),y.append(v,w),p.append(y)}if(p.childElementCount)u.append(p);for(let[_,y]of[["Conventions",l.design.conventions],["Declared exceptions",l.design.exceptions]]){if(!y.length)continue;u.append(D("h3",_));let v=D("ul",void 0,"subtle");for(let E of y)v.append(D("li",E));u.append(v)}if(u.append(D("h3","Inventory")),!l.inventory.length)u.append(D("p","No inventory yet. Add deliberate asset and environment entries in the project configuration.","subtle"));else{let _=D("div",void 0,"table-wrap"),y=D("table"),v=D("thead"),E=D("tr");for(let T of["Item","Kind","Saved revision","Review"])E.append(D("th",T));v.append(E),y.append(v);let w=D("tbody");for(let T of l.inventory){let A=D("tr"),P=D("td",T.name);P.append(D("small",T.brief));let S=D("td"),R=D("td");if(T.asset){let k=D("button",An(T.asset.revisionId),"secondary");k.onclick=()=>e.openAsset(T.asset),S.append(k);let C=[...l.reviews].reverse().find((L)=>L.inventoryId===T.id&&L.asset.revisionId===T.asset.revisionId&&L.asset.assetId===T.asset.assetId&&L.asset.collectionId===T.asset.collectionId);R.append(D("small",C?`${C.verdict} · ${C.reviewer}`:"Unreviewed"));let U=D("button","Record review","secondary");U.onclick=()=>o(l,T),R.append(U)}else S.textContent="Not linked",R.textContent="No saved revision";A.append(P,D("td",T.kind),S,R),w.append(A)}y.append(w),_.append(y),u.append(_)}if(l.design.materialRoles.length){u.append(D("h3","Material roles"));for(let _ of l.design.materialRoles)u.append(D("p",`${_.role}: ${_.description||"No description"}${_.resourceId?` · ${_.resourceId}`:" · No resource assigned"}`,"subtle"))}if(l.deliveryProfiles.length){u.append(D("h3","Delivery intent"));for(let _ of l.deliveryProfiles){if(u.append(D("p",`${_.target} · ${_.description||_.id}`,"subtle")),_.performanceIntent)u.append(D("p",_.performanceIntent,"subtle"));for(let y of _.constraints)u.append(D("p",y,"subtle"))}u.append(D("p","Declared targets are project intent. They do not establish consumer or performance qualification.","subtle"))}if(l.references.length){u.append(D("h3","Reference records"));for(let _ of l.references){let y=D("p",`${_.title}: ${_.uri}`,"subtle");if(_.description)y.append(D("small",` · ${_.description}`));u.append(y)}}u.append(D("h3","Project downloads"));let x=D("div",void 0,"downloads");for(let _ of["editable","runtime"]){let y=D("a",_==="editable"?"Download editable project bundle":"Download runtime project bundle"),v=new URLSearchParams({profile:_,revision:l.revisionId});y.href=`/api/projects/${encodeURIComponent(l.projectId)}/bundle?${v}`,y.download=`${l.projectId}-${_}.zip`,x.append(y)}x.append(D("p","Both downloads bind this exact project revision and its linked saved inventory. Editable includes authored source and material resources for rebuilding. Runtime is delivery-only and cannot restore editable source. Unlinked inventory entries remain plans, not bundled assets.")),u.append(x),u.append(Wo("Exact project configuration and review records",l))},s=async()=>{let c=await un("/api/projects");if(t.length===c.projects.length&&t.every((l,u)=>l.revisionId===c.projects[u]?.revisionId))return;if(t=c.projects,!t.some((l)=>l.projectId===n))n=t[0]?.projectId??"";r(),e.changed(t)};function a(c){i=c,ue("project-editor-title").textContent=c?"Edit project":"New project",ue("project-name").value=c?.name??"",ue("project-brief").value=c?.brief??"",ue("project-style").value=c?.design.style??"",ue("project-scale").value=c?.design.scale??"",ue("project-config").value=JSON.stringify(kR(c??{name:""}),null,2),ue("project-save-status").textContent="",ue("project-editor").showModal(),ue("project-name").focus()}function o(c,l){if(!l.asset)return;let u=D("dialog"),d=D("form"),f=D("div",void 0,"editor-content"),h=D("h2",`Review ${l.name}`);h.id="review-dialog-title",u.setAttribute("aria-labelledby",h.id),f.append(h,D("p","Record an assessment of this exact saved revision. This is a review annotation; structural QA and release qualification remain separate.","subtle"),D("code",`${l.asset.assetId} / ${l.asset.revisionId}`,"mono"));let b=D("input");b.required=!0,b.value=As("kiln.reviewer")??"",b.maxLength=200;let m=D("label","Reviewer","field");m.append(b);let g=D("select");for(let[w,T]of[["comment","Comment"],["changes-requested","Changes requested"],["accepted","Visually accepted"]])g.append(new Option(T,w));let p=D("label","Assessment","field");p.append(g);let x=D("textarea");x.rows=4,x.maxLength=4000;let _=D("label","Notes","field");_.append(x);let y=D("p");y.setAttribute("role","status");let v=D("button","Save review");v.type="submit";let E=D("button","Cancel","secondary");E.type="button",E.onclick=()=>u.close(),f.append(m,p,_,y,v,E),d.append(f),u.append(d),document.body.append(u),u.addEventListener("close",()=>u.remove()),d.onsubmit=async(w)=>{w.preventDefault(),v.disabled=!0,y.textContent="Saving review…";try{await un(`/api/projects/${encodeURIComponent(c.projectId)}`,{method:"PATCH",body:{expectedRevision:c.revisionId,patch:{reviews:[...c.reviews,{id:`review_${crypto.randomUUID().replaceAll("-","")}`,inventoryId:l.id,projectRevisionId:c.revisionId,asset:l.asset,reviewer:b.value.trim(),verdict:g.value,notes:x.value}]}}}),Hi("kiln.reviewer",b.value.trim()),u.close(),await s()}catch(T){y.textContent=T instanceof Error?T.message:String(T)}finally{v.disabled=!1}},u.showModal(),b.focus()}return ue("new-project").onclick=()=>a(),ue("close-project-editor").onclick=()=>ue("project-editor").close(),ue("project-form").onsubmit=async(c)=>{c.preventDefault();let l=ue("save-project");l.disabled=!0,ue("project-save-status").textContent="Saving revision…";try{let u=DR(ue("project-config").value,{name:ue("project-name").value,brief:ue("project-brief").value,style:ue("project-style").value,scale:ue("project-scale").value});n=(await un(i?`/api/projects/${encodeURIComponent(i.projectId)}`:"/api/projects",i?{method:"PATCH",body:{expectedRevision:i.revisionId,patch:u}}:{method:"POST",body:u})).projectId,Hi("kiln.project",n),ue("project-editor").close(),In("Project revision saved."),await s()}catch(u){ue("project-save-status").textContent=u instanceof Error?u.message:String(u)}finally{l.disabled=!1}},{refresh:s}}var OB="Raw map pixels · unshaded · not GPU capture evidence",pb=/^[a-z][a-z0-9_-]{0,79}$/,mb=/^sha256:[a-f0-9]{64}$/;function Ll(e){let t=new URLSearchParams(e.startsWith("?")?e:e.slice(e.indexOf("?")+1)),n=t.get("material"),i=t.get("materialRevision");if(t.getAll("material").length!==1||t.getAll("materialRevision").length!==1||!n||!i||!pb.test(n)||!mb.test(i))return;return{materialId:n,revisionId:i}}function Nf(e){if(!pb.test(e.materialId)||!mb.test(e.revisionId))throw Error("Invalid exact material selection");return`/?${new URLSearchParams({material:e.materialId,materialRevision:e.revisionId})}`}function gb(e){if(!pb.test(e.materialId)||!mb.test(e.revisionId))throw Error("Invalid exact material selection");return`/api/materials/${encodeURIComponent(e.materialId)}/${encodeURIComponent(e.revisionId)}`}function FR(e){let t=ro(e),n=gb(t),i=t.maps.map((r)=>{let s="recipe"in r?r:void 0,a=s?.recipe?.kind==="atlas"?s.recipe:void 0;return{slot:r.slot,file:r.file,url:`${n}/${encodeURIComponent(r.file)}`,width:r.width,height:r.height,colorSpace:r.colorSpace,imageSha256:r.sha256,..."pixelHash"in r?{pixelHash:r.pixelHash}:{},..."sampler"in r?{sampler:{...r.sampler}}:{},atlas:!!a,...s?.recipe?{compilerId:s.recipe.compilerId}:{},...a?{manifestHash:a.manifest.manifestHash}:{},regions:a?a.manifest.regions.map((o)=>({name:o.name,content:{...o.content},allocation:{...o.allocation},leftPercent:o.content.x/r.width*100,topPercent:o.content.y/r.height*100,widthPercent:o.content.width/r.width*100,heightPercent:o.content.height/r.height*100})):[]}});return{materialId:t.materialId,revisionId:t.revisionId,name:t.name,fidelity:OB,maps:i}}function UR(e,t){if(!e||typeof e!=="object"||Array.isArray(e)||e.artifactGlbSha256!==t)throw Error("Retained evaluation does not identify the displayed artifact");let n=e.materialLibraryDependencies;if(n===void 0)return[];if(!Array.isArray(n)||n.length>16)throw Error("Invalid retained material dependency list");let i=new Map;for(let r of n){let s=ro(r),a=`${s.materialId}/${s.revisionId}`,o=i.get(a);if(o&&Nn(o)!==Nn(s))throw Error("Conflicting retained material identity");i.set(a,s)}return[...i.values()]}function Pf(e){let t=FR(e),n=D("section",void 0,"material-inspection");n.setAttribute("aria-label",`${t.name}: exact material maps`),n.append(D("p",`${t.materialId} · ${t.revisionId}`,"mono"),D("p",t.fidelity,"subtle"));let i=D("div",void 0,"material-inspection-controls"),r=(v,E)=>{let w=D("label",v,"inline-field");return w.append(E),i.append(w),E},s=r("Map",D("select"));for(let v of t.maps)s.append(new Option(`${v.slot}${v.atlas?" · atlas":""}`,v.slot));let a=r("Backdrop",D("select"));for(let v of["checker","light","dark"])a.append(new Option(v[0].toUpperCase()+v.slice(1),v));let o=r("Pixel zoom",D("select"));for(let v of[1,2,4])o.append(new Option(`${v}×`,String(v)));let c=D("div",void 0,"material-pixel-frame"),l=D("div",void 0,"material-pixel-sheet");c.dataset.backdrop="checker",c.tabIndex=0;let u=D("img");u.className="material-pixel-image",u.loading="lazy",u.draggable=!1;let d=D("div",void 0,"material-region-overlay"),f=D("label","Region overlays","inline-field"),h=D("input");h.type="checkbox",h.checked=!1,f.append(h),i.append(f),h.onchange=()=>{d.hidden=!h.checked},l.append(u,d),c.append(l);let b=D("p",void 0,"subtle");b.setAttribute("role","status");let m=D("dl"),g=D("div",void 0,"material-region-list"),p=D("a","Open this saved material revision");p.href=Nf(t),p.target="_blank",p.rel="noopener",n.append(i,c,b,m,g,p);let x=t.maps[0],_=()=>{l.style.width=`${x.width*Number(o.value)}px`,l.style.height=`${x.height*Number(o.value)}px`},y=()=>{x=t.maps.find((E)=>E.slot===s.value)??t.maps[0],f.hidden=!x.atlas,d.hidden=!x.atlas||!h.checked,b.textContent="Loading exact saved map…",u.alt=`${t.name}: ${x.slot}${x.atlas?" atlas sheet":""}, raw unshaded pixels`,u.width=x.width,u.height=x.height,u.src=x.url,_(),m.replaceChildren();let v=(E,w)=>m.append(D("dt",E),D("dd",w));if(v("Image",`${x.width} × ${x.height} · ${x.colorSpace} · nearest pixel display`),v("Sampling declaration",x.sampler?`${x.sampler.minFilter} / ${x.sampler.magFilter} · ${x.sampler.wrapS} / ${x.sampler.wrapT}`:"Not recorded in V1"),v("PNG hash",x.imageSha256),x.pixelHash)v("Decoded RGBA hash",x.pixelHash);if(x.compilerId)v("Compiler",x.compilerId);if(x.manifestHash)v("Atlas manifest hash",x.manifestHash);if(d.replaceChildren(),g.replaceChildren(),x.atlas){g.append(D("h4","Atlas regions · top-left pixel coordinates"));for(let E of x.regions){let w=D("span",void 0,"material-region-box");w.style.left=`${E.leftPercent}%`,w.style.top=`${E.topPercent}%`,w.style.width=`${E.widthPercent}%`,w.style.height=`${E.heightPercent}%`,w.append(D("span",E.name)),w.setAttribute("aria-hidden","true"),d.append(w);let T=D("button",`${E.name}: content ${E.content.x},${E.content.y} ${E.content.width}×${E.content.height}; allocation ${E.allocation.x},${E.allocation.y} ${E.allocation.width}×${E.allocation.height}`,"secondary");T.type="button",T.setAttribute("aria-pressed","false"),T.onclick=()=>{for(let A of d.children)A.classList.remove("selected");for(let A of g.querySelectorAll("button"))A.setAttribute("aria-pressed","false");if(w.classList.add("selected"),T.setAttribute("aria-pressed","true"),!d.hidden)w.scrollIntoView({block:"nearest",inline:"nearest"})},g.append(T)}}};return u.onload=()=>{b.textContent="Raw map loaded. These pixels are not a shaded capture."},u.onerror=()=>{b.textContent=`Exact ${t.materialId} revision map unavailable. No newer revision was substituted.`},s.onchange=y,a.onchange=()=>{c.dataset.backdrop=a.value},o.onchange=_,y(),n}function BR(e){if(!e.presetId.trim())throw Error("Choose a material preset");if(!e.seed.trim())throw Error("Enter an explicit seed");let t=Number(e.seed),n=Number(e.size);if(!Number.isInteger(t)||t<-2147483648||t>2147483647)throw Error("Seed must be a signed 32-bit integer");if(![64,128,256,512].includes(n))throw Error("Choose a supported map size");if(!e.creator.trim()||!e.spdx.trim()||!e.url.trim())throw Error("Creator and license details are required");let i=new URL(e.url.trim());if(i.protocol!=="https:"&&i.protocol!=="http:")throw Error("License URL must be HTTP(S)");return{presetId:e.presetId,seed:t,size:n,creator:e.creator.trim(),license:{spdx:e.spdx.trim(),url:e.url.trim(),attribution:e.attribution}}}function zR(e){let t=[],n=[],i=[],r=ue("materials-project"),s=D("button","Create from preset");ue("materials-refresh").before(s);let a=D("dialog");a.setAttribute("aria-labelledby","material-preset-heading");let o=D("form"),c=D("div",void 0,"detail-top"),l=D("h2","Create a material resource");l.id="material-preset-heading";let u=D("button","Cancel","secondary");u.type="button",u.onclick=()=>a.close(),c.append(l,u);let d=D("div",void 0,"editor-content");d.append(D("p","Offline starting recipes with editable layers and height-derived normals. Choose an explicit seed and provenance for the resource. Map images are not shaded material previews.","subtle"));function f(S,R){let k=D("label",S,"field");return k.append(R),d.append(k),R}let h=f("Preset",D("select")),b=D("p",void 0,"subtle");d.append(b);let m=f("Seed",D("input"));m.type="number",m.step="1",m.required=!0,m.min="-2147483648",m.max="2147483647",m.value="0";let g=f("Map size",D("select"));for(let S of[64,128,256,512])g.append(new Option(`${S} × ${S}`,String(S)));g.value="256";let p=f("Creator",D("input"));p.required=!0,p.maxLength=1000;let x=f("License identifier",D("input"));x.required=!0,x.placeholder="For example, CC0-1.0";let _=f("License URL",D("input"));_.type="url",_.required=!0;let y=f("Attribution text",D("textarea"));y.rows=2;let v=D("p");v.setAttribute("role","status");let E=D("button","Create resource");E.type="submit",d.append(v,E),o.append(c,d),a.append(o),document.body.append(a);let w=()=>{let S=i.find((R)=>R.id===h.value);b.textContent=S?`${S.description} Repeat scale: ${S.physicalSizeMeters.width} × ${S.physicalSizeMeters.height} m.`:""};h.onchange=w,s.onclick=async()=>{s.disabled=!0;try{i=(await un("/api/material-presets")).presets,h.replaceChildren(...i.map((S)=>new Option(S.name,S.id))),w(),v.textContent="",E.disabled=!i.length,a.showModal()}catch(S){In(S)}finally{s.disabled=!1}},o.onsubmit=async(S)=>{S.preventDefault(),E.disabled=!0,v.textContent="Creating immutable material resource…";try{let R=BR({presetId:h.value,seed:m.value,size:g.value,creator:p.value,spdx:x.value,url:_.value,attribution:y.value}),k=await un("/api/materials/preset",{method:"POST",body:R});await P(),a.close(),In(`${k.material.name} created at ${k.material.revisionId}. Ready for standalone assets. You can also lock this revision to an optional project.`)}catch(R){v.textContent=R instanceof Error?R.message:String(R)}finally{E.disabled=!1}};let T=gb;function A(){let S=n.find((L)=>L.projectId===r.value),R=ue("material-dependencies");if(R.replaceChildren(),S)if(R.append(D("h2",`${S.name}: locked resources`)),!S.materialDependencies.length)R.append(D("p","No materials are locked to this project yet. Select a resource revision below or configure dependencies with your agent.","subtle"));else{let L=D("table"),O=D("thead"),K=D("tr"),B=D("tbody");for(let q of["Resource / role","Exact revision","Local availability"])K.append(D("th",q));O.append(K),L.append(O);for(let q of S.materialDependencies){let le=t.find((pe)=>pe.materialId===q.resourceId&&pe.revisionId===q.revisionId),de=D("tr"),Me=D("td",q.resourceId);Me.append(D("small",q.role??S.design.materialRoles.filter((pe)=>pe.resourceId===q.resourceId).map((pe)=>pe.role).join(", "))),de.append(Me,D("td",q.revisionId,"mono"),D("td",le&&le.revisionId===q.sha256?"Exact local record available":le?"Dependency hash differs":"Not in local catalog")),B.append(de)}L.append(B);let X=D("div",void 0,"table-wrap");X.append(L),R.append(X)}let k=ue("material-list");k.replaceChildren();let C=ue("material-search").value.trim().toLowerCase(),U=t.filter((L)=>`${L.name} ${L.materialId} ${L.tags.join(" ")} ${L.sources.map((O)=>O.provider).join(" ")}`.toLowerCase().includes(C));if(ue("material-count").textContent=`${U.length} material revision${U.length===1?"":"s"}`,!U.length){k.append(Ko(C?"No matching materials":"Your material catalog starts here",C?"Try another material name, tag or provider.":"Materials added through Kiln appear here with their map roles, source records and exact revisions."));return}for(let L of U){let O=D("article",void 0,"material-card"),K=L.maps.find((F)=>F.slot==="baseColor")??L.maps[0];if(K){let F=D("img");F.src=`${T(L)}/${encodeURIComponent(K.file)}`,F.alt=`${L.name}: ${K.slot} map, not a shaded material preview`,F.loading="lazy",F.className="material-map",O.append(F,D("p",`${K.slot} map · unshaded`,"subtle"))}O.append(D("h3",L.name),D("p",L.tags.join(" · "),"subtle"));let B=D("dl"),X=(F,W)=>B.append(D("dt",F),D("dd",W));X("Revision",L.revisionId),X("Physical scale",L.physicalSizeMeters?`${L.physicalSizeMeters.width} × ${L.physicalSizeMeters.height} m`:"Not specified"),X("Tiling",L.tileable?"Declared tileable":"Not declared tileable"),X("Maps",L.maps.map((F)=>`${F.slot} ${F.width}×${F.height} (${F.colorSpace})`).join(" · ")),X("Surface factors",`Roughness ×${L.parameters.roughness} · Metalness ×${L.parameters.metalness}${L.maps.some((F)=>F.slot==="metallicRoughness")?" · multiplied by packed map channels":""}`),O.append(B);for(let F of L.sources){let W=D("p",`${F.provider} · ${F.creator} · ${F.kind}`,"subtle"),ne=D("a",F.license.spdx);if(ne.href=F.license.url,ne.target="_blank",ne.rel="noreferrer",W.append(document.createTextNode(" · "),ne),F.assetUrl){let ie=D("a","Source");ie.href=F.assetUrl,ie.target="_blank",ie.rel="noreferrer",W.append(document.createTextNode(" · "),ie)}if(O.append(W),F.license.attribution)O.append(D("p",F.license.attribution,"subtle"))}let q=D("div",void 0,"material-map-links");for(let F of L.maps){let W=D("a",F.slot);W.href=`${T(L)}/${encodeURIComponent(F.file)}`,W.target="_blank",W.rel="noopener",q.append(W)}O.append(q);let le=D("details",void 0,"material-map-inspection");le.append(D("summary","Inspect maps and atlas regions"));let de=!1;le.ontoggle=()=>{if(le.open&&!de)de=!0,le.append(Pf(L))};let Me=Ll(location.search);if(Me?.materialId===L.materialId&&Me.revisionId===L.revisionId)le.open=!0,O.dataset.selectedMaterial="true";O.append(le);let pe=S?.materialDependencies.find((F)=>F.resourceId===L.materialId),J=D("button",pe?.revisionId===L.revisionId?"Locked to project":pe?"Use this revision":"Add to project","secondary");if(J.disabled=!S||pe?.revisionId===L.revisionId,!S)J.title="Select a project to add a material dependency";J.onclick=async()=>{if(!S)return;J.disabled=!0;try{let F=S.materialDependencies.filter((W)=>W.resourceId!==L.materialId);F.push({resourceId:L.materialId,revisionId:L.revisionId,sha256:L.revisionId,...pe?.role?{role:pe.role}:{}}),await un(`/api/projects/${encodeURIComponent(S.projectId)}`,{method:"PATCH",body:{expectedRevision:S.revisionId,patch:{materialDependencies:F}}}),In(`${L.name} is locked to ${S.name} at this exact revision.`),await e()}catch(F){In(F),J.disabled=!1}},O.append(J,Wo("Map recipes, transformations and provenance",L)),k.append(O)}}let P=async()=>{t=(await un("/api/materials")).materials,A();let S=Ll(location.search);if(S&&!t.some((R)=>R.materialId===S.materialId&&R.revisionId===S.revisionId))In(`Exact material revision unavailable: ${S.materialId} at ${S.revisionId}. No newer revision was selected.`)};return ue("material-search").oninput=A,r.onchange=A,ue("materials-refresh").onclick=()=>void P().catch(In),{refresh:P,projects(S){n=S;let R=r.value;r.replaceChildren(new Option("All materials",""));for(let k of n)r.append(new Option(k.name,k.projectId));if(n.some((k)=>k.projectId===R))r.value=R;A()}}}function bb(e,t,n){return n?`${n.triangles.toLocaleString()} triangles displayed · ${t}`:`${e.triangles.toLocaleString()} triangles · ${e.meshes} meshes · ${t}`}var VR=(e,t)=>e.startedAt.localeCompare(t.startedAt)||e.operationId.localeCompare(t.operationId);function Fl(e,t){let n=new Map(e.operations.map((c)=>[c.operationId,c])),i=t.map((c)=>{let l=n.get(c.operationId);return l&&l.revision>c.revision?l:c}).sort(VR),r=(c)=>i.find((l)=>l.operationId===c?.operationId)??c,s=e.following?i.at(-1):r(e.selected),a=(c)=>!!c&&!!s&&c.projectId===s.projectId&&c.workId===s.workId&&VR(c,s)<=0&&(c.sessionId===s.sessionId||e.following&&e.crossRunContinuity===!0&&!!s.workId),o=s?.artifact?s:s?i.filter((c)=>c.artifact&&a(c)).at(-1)??(a(e.displayed)?e.displayed:void 0):void 0;return{...e,operations:i,selected:s,displayed:o,pinned:r(e.pinned)}}function xb(e,t){return Fl({...e,following:!1,selected:e.operations.find((n)=>n.operationId===t)??e.selected},e.operations)}function Ys(e,t){return e?.artifact&&t?.artifact&&e.operationId===t.operationId&&e.revision===t.revision&&e.artifact.sha256===t.artifact.sha256?t:void 0}function jR(e,t,n,i){if(e.status!=="complete"||!e.artifact)throw Error("Save requires a completed operation with an artifact.");if(!Ys(e,Ys(i,n)))throw Error("The visible artifact changed or has not loaded. Close this dialog and review it before saving.");let r=t.trim();if(!r||r.length>200)throw Error("Choose an asset name of 1–200 characters.");return{path:`/api/live/${encodeURIComponent(e.operationId)}/save`,body:{expectedRevision:e.revision,name:r,collection:"project"}}}function Of(e,t,n,i){let r;e.onclick=async()=>{let s=n();if(!s){t.replaceChildren(D("p","Load an artifact before measuring.","subtle"));return}e.disabled=!0,t.replaceChildren(D("p","Measuring frame pacing for 3 seconds. Keep this viewport visible and the camera steady.","subtle"));try{let a=await Ew(()=>s.measure(3000),i),o=D("div",void 0,"evidence-card");o.append(D("h3","Exploratory browser measurement"),D("p","Other workloads are not controlled. This sample is not an isolated performance baseline or budget acceptance."),D("strong",`p50 ${a.frameMs.p50.toFixed(1)} ms · p95 ${a.frameMs.p95.toFixed(1)} ms`),D("p",`${a.frameMs.samples} frame intervals · ${(a.windowMs/1000).toFixed(2)} s · ${a.drawCalls} draws · ${a.triangles.toLocaleString()} rendered triangles`),D("p",`${a.geometryObjects} geometry objects · ${a.textureObjects} texture objects. These counts are not GPU memory bytes.`),D("p",`GLB parse to first frame submission: ${a.loadToFirstFrameMs?.toFixed(1)??"unavailable"} ms. Download time excluded.`),D("p",`${a.viewport.cssWidth}×${a.viewport.cssHeight} CSS pixels · DPR ${a.viewport.devicePixelRatio.toFixed(2)}. Frame pacing includes browser scheduling and vertical sync, not GPU execution timing.`));let c=Wo("Exact measurement receipt and limitations",a);if(r)URL.revokeObjectURL(r);r=URL.createObjectURL(new Blob([JSON.stringify(a,null,2)],{type:"application/json"}));let l=D("a","Download measurement receipt");l.href=r,l.download="kiln-viewer-performance.json",o.append(c,l),t.replaceChildren(o)}catch(a){t.replaceChildren(D("p",a instanceof Error?a.message:String(a),"subtle"))}finally{e.disabled=!1}}}function yb(e,t,n,i){let r=e.inventory.find((a)=>a.id===t);if(!r&&!n)throw Error("Inventory item not found");let s=e.inventory.map((a)=>{if(a.id!==t)return a;let{asset:o,...c}=a;return n?{...c,asset:n}:c});if(!r&&n)s.push({id:t,name:i,kind:"asset",brief:"",references:[],asset:n});return{inventory:s}}async function Ul(e,t,n,i){e.replaceChildren(D("h3","Project membership"));let{projects:r}=await un("/api/projects");if(!e.isConnected)return;let s=D("div");e.append(s);let a=D("p");a.setAttribute("role","status");let o=()=>Ul(e,t,n,i);for(let m of r)for(let g of m.inventory){if(!g.asset||g.asset.collectionId!==t.collectionId||g.asset.assetId!==t.assetId)continue;let p=D("div",void 0,"membership-row");p.append(D("span",`${m.name} / ${g.name} · ${An(g.asset.revisionId)}${g.asset.revisionId===t.revisionId?" · this revision":" · another revision"}`));let x=D("button","Remove membership","secondary");x.onclick=async()=>{x.disabled=!0;try{await un(`/api/projects/${encodeURIComponent(m.projectId)}`,{method:"PATCH",body:{expectedRevision:m.revisionId,patch:yb(m,g.id,null,n)}}),await i(),await o()}catch(_){a.textContent=`${_ instanceof Error?_.message:_} Reopen membership to load the current project.`,x.disabled=!1}},p.append(x),s.append(p)}if(!s.childElementCount)s.append(D("p","This asset is standalone. Project membership is optional.","subtle"));if(!r.length){s.append(D("p","Create a named project in Projects to organize related assets."));return}let c=D("form"),l=D("select"),u=D("select"),d=D("label","Project","field"),f=D("label","Inventory item","field");d.append(l),f.append(u);for(let m of r)l.append(new Option(m.name,m.projectId));let h=()=>{let m=r.find((p)=>p.projectId===l.value);u.replaceChildren(new Option("Add as a new inventory item",""));for(let p of m.inventory)u.append(new Option(`${p.name}${p.asset?" (replace linked revision)":""}`,p.id));let g=m.inventory.find((p)=>p.asset?.collectionId===t.collectionId&&p.asset.assetId===t.assetId);if(g)u.value=g.id};l.onchange=h,h();let b=D("button","Link this exact revision");b.type="submit",c.append(d,f,D("p","Linking preserves the saved asset and its original build provenance. Replacing a link advances only this project.","subtle"),b,a),c.onsubmit=async(m)=>{m.preventDefault(),b.disabled=!0;let g=r.find((x)=>x.projectId===l.value),p=u.value||`asset_${crypto.randomUUID().replaceAll("-","")}`;try{await un(`/api/projects/${encodeURIComponent(g.projectId)}`,{method:"PATCH",body:{expectedRevision:g.revisionId,patch:yb(g,p,t,n)}}),await i(),await o()}catch(x){a.textContent=`${x instanceof Error?x.message:x} Reopen membership to load the current project.`,b.disabled=!1}},s.append(c)}function HR(){let e={following:!0,crossRunContinuity:!0,operations:[]},t=[],n="",i=0,r=!1,s,a=0,o,c,l,u,d,f,h,b=0,m=0,g=!1,p=!1,x,_=ue("live-project"),y=ue("live-source"),v=(F)=>y.value?`${F}${F.includes("?")?"&":"?"}source=${encodeURIComponent(y.value)}`:F,E=ue("live-run"),w=ue("live-work"),T=()=>`kiln.live.selection.${y.value}.${_.value}.${w.value}.${E.value}`,A=()=>`kiln.live.pin.${y.value}`,P=()=>t.filter((F)=>(!E.value||F.sessionId===E.value)&&(!w.value||(w.value==="ungrouped"?!F.workId:F.workId===w.value))),S=(F,W)=>{let ne=ue("live-connection");ne.textContent=F?"Connected":"Reconnecting",ne.className=`pill ${F?"connected":"warning"}`,ue("connection-status").textContent=W};function R(){let F=w.value,W=[...new Set(t.flatMap((ce)=>ce.workId?[ce.workId]:[]))];if(w.replaceChildren(new Option("All authoring items",""),new Option("Ungrouped history","ungrouped"),...W.map((ce)=>new Option(ce,ce))),F==="ungrouped"||W.includes(F))w.value=F;let ne=E.value,ie=[...new Set(t.map((ce)=>ce.sessionId))];E.replaceChildren(new Option("All runs",""));for(let ce of ie){let _e=t.find((Re)=>Re.sessionId===ce);E.append(new Option(`${_e.transport} · ${An(ce)}`,ce))}if(ie.includes(ne))E.value=ne}function k(){let F=ue("live-timeline"),W=F.scrollTop,ne=F.contains(document.activeElement)?document.activeElement.dataset.operation:void 0;if(F.replaceChildren(),!e.operations.length){F.append(Ko("Nothing observed yet","Actual Kiln operations will appear here. There is no agent running state to infer."));return}for(let ie of[...e.operations].reverse()){let ce=D("button",void 0,`timeline-item ${ie.status}${e.selected?.operationId===ie.operationId?" selected":""}${ie.pinned?" pinned":""}`);ce.dataset.operation=ie.operationId;let _e=D("span",void 0,"timeline-meta");if(_e.append(D("span",ie.transport.toUpperCase()),D("time",new Date(ie.startedAt).toLocaleTimeString())),ce.append(_e,D("strong",ie.tool.replace(/^kiln_/,"")),D("small",`${ie.status} · ${ie.artifact?"artifact available":"no artifact"}`),D("small",ie.workId?`Item ${ie.workId}`:`Ungrouped · run ${An(ie.sessionId)}`)),ce.setAttribute("aria-label",`${ie.tool}, ${ie.status}, ${new Date(ie.startedAt).toLocaleString()}`),e.selected?.operationId===ie.operationId)ce.setAttribute("aria-current","true");if(ce.onclick=()=>{e=xb(e,ie.operationId),Hi(T(),ie.operationId),q()},F.append(ce),ne===ie.operationId)ce.focus({preventScroll:!0})}F.scrollTop=W}function C(F){let W=D("div",void 0,"evidence-card");W.append(D("h3","Capture fidelity"));let ne=F.viewFidelity,ie=ne&&typeof ne==="object"?ne:void 0;if(W.append(D("strong",ie?String(ie.delivered??"Reported"):"No capture receipt yet")),W.append(D("p",ie?.materialFaithful===!0?"Material-faithful capture reported.":ie?"Geometry evidence only. Do not use this capture to judge materials.":"The interactive viewport uses local browser lighting; it is not a recorded capture.")),ie?.degradeReason)W.append(D("p",String(ie.degradeReason)));if(ie?.rendererId)W.append(D("p",`Renderer: ${String(ie.rendererId)}`,"mono"));if(ie?.inputGlbSha256)W.append(D("p",`Capture input: ${String(ie.inputGlbSha256)}`,"mono"));if(ie)W.append(D("p",ie.exactArtifact===!0?"Receipt identifies the exact evaluated artifact.":"Capture does not claim exact artifact equivalence."));return W}function U(){let F=ue("live-evidence"),W=ue("live-downloads");F.replaceChildren(),W.replaceChildren();let ne=e.displayed;if(!ne?.artifact){x=void 0;return}let ie=D("div",void 0,"evidence-card");ie.append(D("h3","Selected observed artifact"),D("strong",`${(ne.artifact.bytes/1024).toFixed(0)} KB GLB`),D("p",ne.artifact.sha256,"mono"),D("p",`Source: ${ne.programRef??"See authored source download"}`,"mono")),F.append(ie,C(ne));let ce=`${y.value}/${ne.operationId}/${ne.artifact.sha256}`;if(x?.key!==ce){let _e=D("div",void 0,"evidence-card live-material-inspection"),Re=D("button","Inspect exact material inputs","secondary");_e.append(D("h3","Materials and atlas sheets"),D("p","Declared inputs for this displayed artifact. Raw sheets are unshaded; capture fidelity is reported separately."),Re),x={key:ce,card:_e},Re.onclick=async()=>{Re.disabled=!0;let ke=D("p","Reading the displayed artifact evaluation…");ke.setAttribute("role","status"),_e.append(ke);try{let We=await un(v(`/api/live/${encodeURIComponent(ne.operationId)}/evaluation.json`));if(x?.key!==ce)return;let Qe=UR(We,ne.artifact.sha256);ke.textContent=Qe.length?"Exact declared revisions. Map images require the matching record in this local material library.":"No saved material resource declarations in this artifact. Embedded textures can still be viewed in the viewport.";for(let Wt of Qe){let lt=D("details");lt.append(D("summary",`${Wt.name} · ${Wt.revisionId}`));let Lt=!1;lt.ontoggle=()=>{if(lt.open&&!Lt)Lt=!0,lt.append(Pf(Wt))},_e.append(lt)}}catch(We){if(x?.key!==ce)return;ke.textContent=`Material inspection unavailable for this exact artifact: ${We instanceof Error?We.message:String(We)}`,Re.disabled=!1}}}if(F.append(x.card),ne.captures.length)for(let _e of ne.captures){let Re=D("div",void 0,"evidence-card");Re.append(D("h3",_e.name));let ke=ne.viewFidelity&&typeof ne.viewFidelity==="object"?ne.viewFidelity:void 0;Re.append(D("p",ke?.materialFaithful===!0?`Recorded capture · ${String(ke.delivered??"material-faithful")}`:`Recorded capture · ${String(ke?.delivered??"fidelity unreported")}. Materials are not verified.`,ke?.materialFaithful===!0?"subtle":"warning"));let We=D("a"),Qe=D("img");Qe.src=_e.url,Qe.alt=`Recorded ${_e.name} for ${ne.tool}`,Qe.loading="lazy",We.href=_e.url,We.target="_blank",We.rel="noopener",We.append(Qe),Re.append(We,D("p",_e.sha256,"mono")),F.append(Re)}else{let _e=D("div",void 0,"evidence-card");_e.append(D("h3","Recorded captures"),D("p",ne.status==="evaluated"||ne.status==="running"?"Artifact is ready. Capture work may still be in progress.":"No capture image was retained for this operation.")),F.append(_e)}for(let[_e,Re,ke]of[[ne.artifact.url,"Observed GLB","asset.glb"],[v(`/api/live/${encodeURIComponent(ne.operationId)}/source.kiln.js`),"Authored source","source.kiln.js"]]){let We=D("a",Re);We.href=_e,We.download=ke,W.append(We)}W.append(D("p","These are the observed artifact and source. Use the saved Library revision for an editable bundle with resources or a separate runtime export. A live observation is not a saved release."))}function L(){let F=Ys(e.displayed,l);ue("pin-build").disabled=!F,Me.disabled=F?.status!=="complete"}function O(){if(d&&l)ue("live-stage-label").textContent=bb(d,An(l.operationId),o?.lod())}function K(){if(f&&u)ue("compare-stage-label").textContent=`Pinned · ${bb(f,An(u.operationId),c?.lod())}`}async function B(F){if(ue("live-panel").hidden)return;let W=++b;if(!Ys(F,l))o?.cancelMeasurement("The review selection changed. Measure the loaded revision again.");if(!F?.artifact){ue("live-performance").replaceChildren(),o?.dispose(),o=void 0,l=void 0,d=void 0,ue("live-level-field").hidden=!0,ue("live-lod").replaceChildren(),ue("live-lod").hidden=!0,ue("live-stage-status").textContent="No completed artifact available for this run.",ue("live-stage-label").textContent="Current",L();return}if(l?.artifact?.sha256===F.artifact.sha256){l=F,ue("live-stage-status").textContent="",O(),L();return}ue("live-stage-status").textContent=`Loading ${An(F.operationId)}…${l?` Previous artifact ${An(l.operationId)} remains visible; Save and Pin are unavailable until the selection loads.`:""}`;try{let ne=await fetch(F.artifact.url);if(!ne.ok)throw Error("This retained artifact is no longer available");let ie=new Uint8Array(await ne.arrayBuffer());if(W!==b)return;o??=El(ue("live-stage"));let ce=await o.load(ie,{isCurrent:()=>W===b,onCommit:()=>{l=F},preserveView:l?.projectId===F.projectId&&(l?.sessionId===F.sessionId||e.following)});if(!ce||W!==b)return;ue("live-performance").replaceChildren(),l=F,d=ce,L();let _e=ue("live-level");if(ue("live-level-field").hidden=!ce.levels,Tl(_e,ue("live-lod"),o,(Re)=>{if(Re!==void 0)c?.level(Re),h?.refresh(),K();O()}),o.wire(g),o.navigation(ue("live-navigation").value),ue("live-stage-status").textContent="",O(),c)c.setView(o.view())}catch(ne){if(W!==b)return;ue("live-stage-status").textContent=`${ne instanceof Error?ne.message:ne}.${l?` Previous artifact ${An(l.operationId)} remains visible. Save and Pin are unavailable for the unloaded selection.`:""}`,L()}}async function X(F){if(ue("live-panel").hidden)return;let W=++m;if(ue("compare-viewport").hidden=!F?.artifact,ue("review-viewports").classList.toggle("comparing",!!F?.artifact),!F?.artifact){c?.dispose(),c=void 0,u=void 0,f=void 0,h=void 0,ue("compare-lod").replaceChildren(),ue("compare-level-field").hidden=!0;return}if(u?.artifact?.sha256===F.artifact.sha256){u=F,K(),ue("compare-stage-status").textContent="";return}if(!u)ue("compare-stage-label").textContent="Comparison";ue("compare-stage-status").textContent=`Loading pinned ${An(F.operationId)}…`;try{let ne=await fetch(F.artifact.url);if(!ne.ok)throw Error("Pinned artifact unavailable");let ie=new Uint8Array(await ne.arrayBuffer());if(W!==m)return;c??=El(ue("compare-stage"));let ce=await c.load(ie,{preserveView:!0,isCurrent:()=>W===m,onCommit:()=>{u=F}});if(!ce||W!==m)return;if(u=F,f=ce,o)c.setView(o.view());let _e=Number(ue("live-level").value||0);c.level(Number.isFinite(_e)?_e:0),ue("compare-level-field").hidden=!ce.levels,h=Tl(ue("compare-level"),ue("compare-lod"),c,K),K(),c.wire(g),c.navigation(ue("live-navigation").value),ue("compare-stage-status").textContent=""}catch(ne){if(W===m)ue("compare-stage-status").textContent=`${ne instanceof Error?ne.message:String(ne)}.${u?` Previous comparison ${An(u.operationId)} remains visible.`:""}`}}function q(){k();let F=e.selected,W=e.displayed,ne=ue("follow-latest");ne.textContent=e.following?"Following latest":"Follow latest",ne.setAttribute("aria-pressed",String(e.following));let ie=ue("live-current-summary");if(ie.replaceChildren(),F){ie.append(D("h2",F.tool.replace(/^kiln_/,"")),D("p",`${F.status} · ${F.transport} · Run ${An(F.sessionId)} · ${new Date(F.updatedAt).toLocaleString()}`));let Re=D("div",void 0,"tags");if(F.projectId)Re.append(D("span",F.projectId,"tag"));for(let ke of F.phases)Re.append(D("span",ke.phase,"tag"));ie.append(Re)}else ie.append(D("h2","No build selected"),D("p","Run Kiln tools from your agent or CLI. Completed evaluations appear here automatically."));let ce=F&&"observationIssues"in F&&Array.isArray(F.observationIssues)?F.observationIssues.map(String):[],_e=[F?.error,...ce,F&&W&&F.operationId!==W.operationId?`Current ${F.status} operation has no retained artifact. Showing the last successful artifact ${An(W.operationId)} from run ${An(W.sessionId)}.`:"",F&&!e.operations.some((Re)=>Re.operationId===F.operationId)?"This selection is outside the current retained history. Its loaded view remains until you choose another build.":""].filter(Boolean);ue("live-failure").textContent=_e.join(" "),ue("live-failure").hidden=!_e.length,L(),ue("clear-pin").hidden=!e.pinned,ue("live-count").textContent=`${e.operations.length} retained operation${e.operations.length===1?"":"s"}`,ue("live-record").textContent=JSON.stringify({selected:F,displayedArtifactOperation:W?.operationId,pinnedOperation:e.pinned?.operationId},null,2),U(),B(W),X(e.pinned)}async function le(){if(r)return;r=!0;let F=i;try{let W=new URLSearchParams;if(_.value)W.set("project",_.value);if(n)W.set("cursor",n);let ne=await un(v(`/api/live?${W}`));if(F!==i)return;if(a=0,S(!0,"Connected · checks every 2 seconds"),n=ne.cursor,ue("live-history-note").textContent=`Up to ${ne.retention.maxOperations} operations`,ue("live-history-issues").textContent=ne.observationIssues?.join(" ")??"",ue("live-history-issues").hidden=!ne.observationIssues?.length,!ne.unchanged){if(t=ne.operations,R(),e=Fl(e,P()),!p){p=!0;let ie=As(T());if(ie&&e.operations.some((_e)=>_e.operationId===ie))e=xb(e,ie);let ce=As(A());e.pinned=t.find((_e)=>_e.operationId===ce&&_e.pinned)??[...t].reverse().find((_e)=>_e.pinned&&_e.artifact)}q()}}catch(W){a++,S(!1,`Connection lost. Retrying; retained views remain available. ${W instanceof Error?W.message:W}`)}finally{if(r=!1,s)clearTimeout(s);s=setTimeout(()=>void le(),document.hidden?1e4:Math.min(30000,2000*2**Math.min(a,4)))}}_.onchange=()=>{i++,n="",t=[],p=!1,E.replaceChildren(new Option("All runs","")),w.value="",e={following:!0,crossRunContinuity:!0,operations:[]},q(),le()},y.onchange=()=>{_.value="",e.pinned=void 0,_.dispatchEvent(new Event("change"))},un("/api/live-sources").then(({sources:F})=>{y.replaceChildren(...F.map((W)=>new Option(W.label,W.id)))}).catch(In),E.onchange=()=>{e=Fl({...e,selected:void 0,displayed:void 0,following:!0,crossRunContinuity:!E.value},P()),q()},w.onchange=()=>E.dispatchEvent(new Event("change")),ue("follow-latest").onclick=()=>{e=Fl({...e,following:!e.following},P()),Hi(T(),e.following?"":e.selected?.operationId??""),q()},ue("live-refresh").onclick=()=>{n="",le(),q()},ue("pin-build").onclick=async()=>{let F=Ys(e.displayed,l);if(!F?.artifact)return;let W=ue("pin-build");W.disabled=!0;try{await un(v(`/api/live/${encodeURIComponent(F.operationId)}/pin`),{method:"POST",body:{pinned:!0}}),e.pinned={...F,pinned:!0},Hi(A(),F.operationId),n="",q(),le()}catch(ne){In(ne),L()}},ue("clear-pin").onclick=async()=>{if(!e.pinned)return;try{await un(v(`/api/live/${encodeURIComponent(e.pinned.operationId)}/pin`),{method:"POST",body:{pinned:!1}}),e.pinned=void 0,Hi(A(),""),n="",q(),le()}catch(F){In(F)}},ue("live-frame").onclick=()=>{if(o?.reset(),o)c?.setView(o.view())},ue("live-wire").onclick=()=>{g=!g,o?.wire(g),c?.wire(g),ue("live-wire").setAttribute("aria-pressed",String(g))};let de=D("button","Match comparison camera","secondary");de.onclick=()=>{if(o)c?.setView(o.view())},ue("live-frame").parentElement?.append(de);let Me=D("button","Save exact artifact");Me.disabled=!0,ue("live-frame").parentElement?.prepend(Me);let pe=D("button","Measure 3 s","secondary"),J=D("div");return J.id="live-performance",ue("live-evidence").after(J),ue("live-frame").parentElement?.append(pe),Of(pe,J,()=>o,()=>Ys(e.displayed,l)?{operationId:l.operationId,revision:l.revision,glbSha256:l.artifact?.sha256}:void 0),Me.onclick=()=>{let F=Ys(e.displayed,l);if(F?.status!=="complete")return;let W=D("dialog"),ne=D("form"),ie=D("div",void 0,"editor-content"),ce=D("h2","Save reviewed artifact");ce.id="save-review-title",W.setAttribute("aria-labelledby",ce.id),ie.append(ce,D("p","Save the exact source, GLB and recorded capture to Library. Then optionally link the saved revision to one or more named projects. Kiln will not evaluate the source again.","subtle"),D("p",`${F.operationId} · revision ${F.revision}`,"mono"),D("p",F.artifact.sha256,"mono"));let _e=D("input");_e.required=!0,_e.maxLength=200,_e.value="";let Re=D("label","Asset name","field");Re.append(_e);let ke=D("p");ke.setAttribute("role","status");let We=D("button","Save exact artifact");We.type="submit";let Qe=D("button","Cancel","secondary");Qe.type="button",Qe.onclick=()=>W.close(),ie.append(Re,ke,We,Qe),ne.append(ie),W.append(ne),document.body.append(W),W.addEventListener("close",()=>W.remove()),ne.onsubmit=async(Wt)=>{Wt.preventDefault(),We.disabled=!0,ke.textContent="Saving retained bytes…";try{let lt=jR(F,_e.value,l,e.displayed),Lt=await un(v(lt.path),{method:"POST",body:lt.body});ke.replaceChildren(D("span",`Saved ${Lt.asset.assetId} / ${Lt.asset.revisionId}. `));let Qt=D("a","Open saved revision"),nn=new URLSearchParams({collection:Lt.collection,asset:Lt.asset.assetId,revision:Lt.asset.revisionId});Qt.href=`/?${nn}`,ke.append(Qt);let z=D("div");ie.append(z),Ul(z,{collectionId:Lt.collection,assetId:Lt.asset.assetId,revisionId:Lt.asset.revisionId},Lt.asset.name,async()=>{}).catch((_n)=>{z.textContent=`Asset saved; membership unavailable: ${_n instanceof Error?_n.message:_n}. Open the saved asset in Library to link it.`}),_e.disabled=!0,We.textContent="Saved",Qe.textContent="Close"}catch(lt){ke.textContent=lt instanceof Error?lt.message:String(lt),We.disabled=!1}},W.showModal(),_e.focus()},ue("live-navigation").onchange=(F)=>{let W=F.target.value;o?.navigation(W),c?.navigation(W),ue("live-navigation-help").textContent=W==="explore"?"Focus a viewport, then W A S D to move · Q / E down / up · Shift faster · Drag to look around · No collision simulation.":"Drag to orbit · Scroll to zoom · Right-drag to pan · Your camera stays in place between iterations."},window.addEventListener("online",()=>{n="",le()}),document.addEventListener("visibilitychange",()=>{if(!document.hidden)le()}),le(),{activate:q,projects(F){let W=_.value;_.replaceChildren(new Option("All work",""));for(let ne of F)_.append(new Option(ne.name,ne.projectId));if(F.some((ne)=>ne.projectId===W))_.value=W}}}var _b=["projects","live","library","materials"];function GR(e,t){let n=new URLSearchParams(e);if(n.has("asset")||n.has("open"))return"library";if(Ll(e))return"materials";return t&&_b.some((i)=>i===t)?t:"library"}function $R(e,t=()=>{}){let n=_b;function i(c){if(!n.includes(c))return;for(let l of n)ue(`${l}-panel`).hidden=l!==c;for(let l of document.querySelectorAll("#workspace-nav button")){let u=l.dataset.section===c;if(l.classList.toggle("active",u),u)l.setAttribute("aria-current","page");else l.removeAttribute("aria-current")}if(Hi("kiln.section",c),c==="live")r.activate();if(c==="materials")s.refresh().catch(In)}for(let c of document.querySelectorAll("#workspace-nav button"))c.onclick=()=>i(c.dataset.section);ue("open-files").onclick=()=>ue("open").click();let r=HR(),s=zR(()=>a.refresh()),a=LR({changed:(c)=>{r.projects(c),s.projects(c),t(c)},openAsset:(c)=>{i("library"),e(c)}});i(GR(location.search,As("kiln.section"))),a.refresh().catch(In),s.refresh().catch(In);let o=!1;return window.setInterval(async()=>{if(document.hidden||o||ue("project-editor").open)return;o=!0;try{await a.refresh()}catch{}finally{o=!1}},5000),{library:()=>i("library"),refreshProjects:a.refresh}}var Er=(e)=>`${e.collection}/${e.manifest.assetId}`;function KR(e,t,n){if(!n)return e;if(n==="standalone"){let r=new Set(t.flatMap((s)=>s.inventory.flatMap((a)=>a.asset?[`${a.asset.collectionId}/${a.asset.assetId}`]:[])));return e.filter((s)=>!r.has(Er(s)))}let i=new Set(t.find((r)=>r.projectId===n)?.inventory.flatMap((r)=>r.asset?[`${r.asset.collectionId}/${r.asset.assetId}/${r.asset.revisionId}`]:[])??[]);return e.filter((r)=>i.has(`${Er(r)}/${r.manifest.revisionId}`))}var Be=(e)=>document.getElementById(e),dt=(e,t,n)=>{let i=document.createElement(e);if(t!==void 0)i.textContent=t;if(n)i.className=n;return i},jl=[],Vl=[],na=[],Ba=[],kf="",ea,Tr,wn,Qs=0,WR=0,Bl=!1,zl=!1,ta=new Set,Ab=[],XR=[],Kr=(e)=>`${e.collection}/${e.manifest.assetId}/${e.manifest.revisionId}`,Eb=(e)=>{Be("status").textContent=e},Ar=(e)=>Eb(e instanceof Error?e.message:String(e)),za=(e,t,n=Ab)=>{let i=URL.createObjectURL(new Blob([Uint8Array.from(e)],{type:t}));return n.push(i),i};async function Tb(e){let t=await fetch(e),n=await t.json();if(!t.ok)throw Error(n.error??"Request failed");return n}async function vb(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/${Kr(e)}/${t}`);if(!n.ok)throw Error((await n.json()).error??"File unavailable");return new Uint8Array(await n.arrayBuffer())}function kB(e,t){if(e.local){if(t==="editable.zip")return za(lp([e.local]),"application/zip");return za(e.local.files[t],t.endsWith(".js")?"text/javascript":"model/gltf-binary")}if(e.loose)return za(e.loose,"model/gltf-binary");return`/files/${Kr(e)}/${t}?download`}function qR(e,t){try{localStorage.setItem(e,t)}catch{}}function DB(e){try{return localStorage.getItem(e)}catch{return null}}function LB(){let e=Be("collections");e.replaceChildren();for(let t of[{id:"all",label:"All saved assets"},...jl,...Ba.length?[{id:"opened-files",label:"Opened files"}]:[]]){let n=dt("button",t.label,kf===t.id?"active":"");n.onclick=()=>void nc(t.id).catch(Ar),e.append(n)}}async function nc(e,t=!0){if(t)ZR.library();let n=++WR;kf=e,ta.clear(),LB(),Eb("");let i=e==="all"?await(async()=>{let r=await Tb("/api/library");if(r.errors.length)Eb(r.errors.map((s)=>`${s.collectionId}: ${s.message}`).join(" · "));return r.entries.map((s)=>({collection:s.collectionId,manifest:s.manifest}))})():e==="opened-files"?Ba:(await Tb(`/api/assets?collection=${encodeURIComponent(e)}`)).assets.map((r)=>({collection:e,manifest:r}));if(n!==WR)return;na=i,qR("kiln.collection",e),Be("collection-title").textContent=e==="all"?"Library":e==="opened-files"?"Opened files":jl.find((r)=>r.id===e)?.label??e,Be("collection-caption").textContent=e==="opened-files"?"Previewed in your browser. Your original files stay untouched.":"Saved assets across registered storage. Projects link exact revisions; standalone assets belong here too.",Df()}function FB(){let e=new Map;for(let t of KR(na,Vl,Be("library-project").value)){let n=Er(t);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===DB(`kiln.revision.${n.collection}.${n.manifest.assetId}`))??t[0]))}function Df(){for(let i of XR.splice(0))URL.revokeObjectURL(i);let e=Be("cards");e.replaceChildren();let t=Be("search").value.toLowerCase(),n=FB().filter((i)=>`${i.manifest.name} ${i.manifest.tags.join(" ")}`.toLowerCase().includes(t));if(Be("count").textContent=`${n.length} asset${n.length===1?"":"s"}`,Be("export-selection").disabled=!ta.size,!n.length){let i=dt("div",void 0,"empty");if(i.append(dt("b",t?"No matching assets":"Your next idea belongs here."),dt("p",t?"Try another name or tag.":"Save an asset with your agent, or open a GLB or editable bundle.")),!t)i.append(dt("code",'kiln save asset.kiln.js --name "My asset"'));e.append(i);return}for(let i of n){let r=i.manifest,s=dt("article",void 0,"card"),a=dt("button",void 0,"card-open");a.setAttribute("aria-label",`View ${r.name}`),a.onclick=()=>void Hl(i).catch(Ar);let o=dt("div",void 0,"thumb");if(r.files["preview.png"]){let b=dt("img");b.loading="lazy",b.alt=r.name,b.src=i.local?za(i.local.files["preview.png"],"image/png",XR):`/files/${Kr(i)}/preview.png`,b.onerror=()=>{b.remove(),o.textContent="◇"},o.append(b)}else o.textContent="◇";let c=dt("div",void 0,"card-content");c.append(dt("span",r.name,"card-title"));let l=na.filter((b)=>Er(b)===Er(i)),u=new Set(l.map((b)=>b.manifest.parentRevision)),d=l.filter((b)=>!u.has(b.manifest.revisionId));c.append(dt("span",`${r.editable?"Editable source":"Source unavailable"} · ${l.length} revision${l.length===1?"":"s"}${d.length>1?` · ${d.length} branches`:""}`,"card-meta"));let f=dt("div",void 0,"tags");for(let b of r.tags)f.append(dt("span",b,"tag"));c.append(f),c.append(dt("small",jl.find((b)=>b.id===i.collection)?.label??i.collection,"card-meta"));let h=Vl.filter((b)=>b.inventory.some((m)=>m.asset&&m.asset.collectionId===i.collection&&m.asset.assetId===r.assetId));if(c.append(dt("small",h.length?h.map((b)=>b.name).join(" · "):"No project membership","card-meta")),a.append(o,c),s.append(a),!i.loose){let b=dt("input");b.type="checkbox",b.className="selection",b.checked=ta.has(Kr(i)),b.setAttribute("aria-label",`Select ${r.name}`),b.onchange=()=>{if(b.checked)ta.add(Kr(i));else ta.delete(Kr(i));Be("export-selection").disabled=!ta.size},s.append(b)}e.append(s)}}async function Hl(e){let t=++Qs;ea=e,Tr=void 0,wn?.cancelMeasurement("The Library selection changed. Measure the loaded revision again."),Be("library-performance").replaceChildren(),qR(`kiln.revision.${e.collection}.${e.manifest.assetId}`,e.manifest.revisionId);for(let u of Ab.splice(0))URL.revokeObjectURL(u);let n=Be("detail");if(!n.open)n.showModal();Be("asset-name").textContent=e.manifest.name;let i=Be("asset-membership");if(i.replaceChildren(),!e.local&&!e.loose){let u=dt("div");i.append(u),Ul(u,{collectionId:e.collection,assetId:e.manifest.assetId,revisionId:e.manifest.revisionId},e.manifest.name,ZR.refreshProjects).catch(Ar)}let r=Be("revisions");r.replaceChildren();for(let u of na.filter((d)=>Er(d)===Er(e))){let d=dt("option",`${new Date(u.manifest.createdAt).toLocaleString()} · ${u.manifest.description||u.manifest.revisionId.slice(0,10)}`);d.value=u.manifest.revisionId,d.selected=u.manifest.revisionId===e.manifest.revisionId,r.append(d)}r.onchange=()=>{let u=na.find((d)=>Er(d)===Er(e)&&d.manifest.revisionId===r.value);if(u)Hl(u).catch(Ar)},Be("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.");let s=Be("asset-attribution");s.replaceChildren();for(let u of hE(e.manifest)){let d=dt("div");d.append(dt("span",u.label),dt("strong",u.value)),s.append(d)}s.hidden=!s.childElementCount;let a=document.getElementById("asset-material-inputs");if(!a)a=dt("section",void 0,"asset-material-inputs"),a.id="asset-material-inputs",s.after(a);a.replaceChildren();try{let u=Lc({manifest:e.manifest,files:{}});if(u.length){a.append(dt("h3","Exact material build inputs"),dt("p","Open the saved revision to inspect its raw maps, sampling declaration and atlas regions. Declared inputs do not prove every map was used.","subtle"));for(let d of u){let f=dt("a",`${d.name} · ${d.materialId}`);f.href=Nf(d),f.target="_blank",f.rel="noopener",a.append(f,dt("p",d.revisionId,"mono"))}}}catch(u){a.append(dt("p",`Material revision links unavailable: ${u instanceof Error?u.message:String(u)}`,"subtle"))}Be("provenance").textContent=e.loose?"Standalone GLB. No source or build provenance supplied.":JSON.stringify(e.manifest,null,2);let o=Be("downloads");o.replaceChildren();for(let[u,d]of[["asset.glb","Original GLB"],...e.manifest.editable?[["source.kiln.js","Download source"]]:[],...!e.loose?[["editable.zip",e.manifest.editable?"Download editable bundle":"Download asset bundle"]]:[]]){let f=dt("a",d);f.href=kB(e,u),f.download=`${e.manifest.name.replace(/[^a-z0-9_-]/gi,"-")}${u==="asset.glb"?".glb":u==="source.kiln.js"?".kiln.js":".zip"}`,o.append(f)}if(!e.loose){let u=dt("button","Runtime GLB"),d=dt("span");d.setAttribute("role","status"),u.onclick=async()=>{u.disabled=!0,d.textContent="Preparing runtime download…";try{let f=e.local?await MR(e.local,{profile:"runtime"}):void 0,[h,b]=f?.profile==="runtime"?[f.glb,f.metadata.bytes]:await Promise.all([vb(e,"runtime.glb"),vb(e,"runtime.kiln-metadata.json")]);if(t!==Qs)return;let m=dt("a","Runtime GLB");m.href=za(h,"model/gltf-binary"),m.download="runtime.glb";let g=dt("a","Runtime metadata");g.href=za(b,"application/json"),g.download="runtime.kiln-metadata.json",u.replaceWith(m,g),d.textContent="Keep the companion metadata for traceability.",m.click()}catch(f){if(t!==Qs)return;d.textContent=`Runtime export unavailable: ${f instanceof Error?f.message:f}`,u.disabled=!1}},o.append(u,d),o.append(dt("p","Original GLB retains Kiln review data. Runtime GLB moves duplicate animation-review data into a companion JSON file; geometry and textures are unchanged. Keep the editable bundle for source and build records."))}Be("refine").disabled=!e.manifest.editable,Be("asset-stats").replaceChildren(),Be("stage-status").textContent="Loading saved GLB…",Bl=!1,zl=!1,Be("wire").setAttribute("aria-pressed","false"),Be("play").textContent="Pause";let c=Be("animation");c.replaceChildren(new Option("Rest pose","")),Be("play").disabled=!0;let l=Be("level");l.replaceChildren(),l.hidden=!0,Be("library-lod").replaceChildren(),Be("library-lod").hidden=!0;try{wn??=El(Be("stage"));let u=await vb(e,"asset.glb");if(t!==Qs)return;let d=await wn.load(u,{isCurrent:()=>t===Qs,onCommit:()=>{Tr=e}});if(!d||t!==Qs)return;Tr=e,wn.wire(!1),wn.navigation(Be("library-navigation").value),wn.lighting(Be("lighting").value),Tl(l,Be("library-lod"),wn);for(let[f,h]of[...d.levels?d.levels.map((b,m)=>[b.toLocaleString(),`LOD${m} triangles`]):[[d.triangles.toLocaleString(),"triangles"]],[d.meshes,d.levels?"LOD0 meshes":"meshes"],[d.materials,d.levels?"LOD0 materials":"materials"],[`${(u.length/1024).toFixed(0)} KB`,"GLB"]]){let b=dt("div");b.append(dt("strong",String(f)),dt("span",String(h))),Be("asset-stats").append(b)}for(let f=0;f<d.clips.length;f++)c.append(new Option(d.clips[f],String(f)));Be("stage-status").textContent=""}catch(u){if(t===Qs)wn?.dispose(),wn=void 0,Be("stage-status").textContent=`3D preview unavailable: ${u instanceof Error?u.message:u}. Downloads remain available.`}}async function JR(e){for(let t of e){if(t.bytes.length>Wn)throw Error("File exceeds 64 MiB");if(t.name.toLowerCase().endsWith(".zip"))for(let n of fE(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((a)=>a.toString(16).padStart(2,"0")).join("")}`!==n.manifest.files[i]?.sha256)throw Error(`Bundle integrity failure: ${i}`);if(!Ba.some((i)=>i.manifest.revisionId===n.manifest.revisionId&&i.manifest.assetId===n.manifest.assetId))Ba.push({collection:"opened-files",manifest:n.manifest,local:n})}else{let n=`a_${crypto.randomUUID().replaceAll("-","")}`;Ba.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 nc("opened-files")}Be("open").onchange=async(e)=>{try{let t=Array.from(e.target.files??[]);if(t.some((n)=>n.size>Wn))throw Error("File exceeds 64 MiB");await JR(await Promise.all(t.map(async(n)=>({name:n.name,bytes:new Uint8Array(await n.arrayBuffer())}))))}catch(t){Ar(t)}};Be("refresh").onclick=()=>void nc(kf).catch(Ar);Be("search").oninput=Df;Be("library-project").onchange=()=>void nc("all").catch(Ar);Be("close-detail").onclick=()=>Be("detail").close();Be("detail").addEventListener("close",()=>{Qs++,Tr=void 0,wn?.dispose(),wn=void 0;for(let e of Ab.splice(0))URL.revokeObjectURL(e);Df()});Be("frame").onclick=()=>wn?.reset();Be("wire").onclick=()=>{Bl=!Bl,wn?.wire(Bl),Be("wire").setAttribute("aria-pressed",String(Bl))};Be("lighting").onchange=(e)=>wn?.lighting(e.target.value);Be("library-navigation").onchange=(e)=>{let t=e.target.value;wn?.navigation(t),Be("library-navigation-help").textContent=t==="explore"?"Focus the viewport, then W A S D to move · Q / E down / up · Shift faster · Drag to look around · No collision simulation.":"Drag to orbit · Scroll to zoom · Right-drag to pan"};Be("animation").onchange=(e)=>{let t=e.target.value;wn?.clip(t===""?-1:Number(t)),Be("play").disabled=t===""};Be("play").onclick=()=>{zl=!zl,wn?.pause(zl),Be("play").textContent=zl?"Play":"Pause"};Be("refine").onclick=async()=>{if(!ea)return;let e=ea.manifest,t=ea.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=${ea.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=${ea.collection}. Requested change: `;try{await navigator.clipboard.writeText(t),Be("refine").textContent="Instructions copied"}catch{Be("provenance").textContent=t,Be("provenance").parentElement?.setAttribute("open","")}};Be("export-selection").onclick=()=>{try{let e=dt("a");if(kf==="opened-files")e.href=za(lp(na.filter((t)=>ta.has(Kr(t))).map((t)=>t.local)),"application/zip");else{let t=new URLSearchParams;for(let n of ta)t.append("revision",n);e.href=`/api/bundle?${t}`}e.download="kiln-assets.zip",e.click()}catch(e){Ar(e)}};async function UB(){jl=(await Tb("/api/collections")).collections;let e=Nw(location.search);if(await nc(jl.find((t)=>t.id===e?.collection)?.id??"all",!1),e){let t=na.find((n)=>n.collection===e.collection&&n.manifest.assetId===e.assetId&&n.manifest.revisionId===e.revisionId);if(!t)throw Error("The requested saved revision is not available.");await Hl(t)}if(new URLSearchParams(location.search).has("open")){let t=await fetch("/api/standalone");if(!t.ok)throw Error("File unavailable");if(await JR([{name:t.headers.get("Content-Type")?.includes("zip")?"asset.zip":"asset.glb",bytes:new Uint8Array(await t.arrayBuffer())}]),Ba.length===1)await Hl(Ba[0])}}var ZR=$R((e)=>{(async()=>{await nc(e.collectionId);let t=na.find((n)=>n.manifest.assetId===e.assetId&&n.manifest.revisionId===e.revisionId);if(!t)throw Error("The linked saved revision is not available in this collection.");await Hl(t)})().catch(Ar)},(e)=>{Vl=e;let t=Be("library-project"),n=t.value;t.replaceChildren(new Option("All projects and standalone",""),new Option("Standalone assets","standalone"));for(let i of Vl)t.append(new Option(i.name,i.projectId));if(n==="standalone"||Vl.some((i)=>i.projectId===n))t.value=n;Df()});Of(Be("measure-library"),Be("library-performance"),()=>wn,()=>Tr&&ea&&Kr(Tr)===Kr(ea)?{collection:Tr.collection,assetId:Tr.manifest.assetId,revisionId:Tr.manifest.revisionId,glbSha256:Tr.manifest.files["asset.glb"]?.sha256}:void 0);UB().catch(Ar);